-
Notifications
You must be signed in to change notification settings - Fork 4.4k
/
Copy pathindex.js
234 lines (201 loc) · 6.99 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
/**
* External dependencies
*/
import classnames from 'classnames';
import { noop, startsWith } from 'lodash';
/**
* WordPress dependencies
*/
import { Button, ExternalLink, VisuallyHidden } from '@wordpress/components';
import { __, sprintf } from '@wordpress/i18n';
import { useCallback, useState, Fragment } from '@wordpress/element';
import {
safeDecodeURI,
filterURLForDisplay,
isURL,
prependHTTP,
getProtocol,
} from '@wordpress/url';
import { useInstanceId } from '@wordpress/compose';
import { useSelect } from '@wordpress/data';
/**
* Internal dependencies
*/
import LinkControlSettingsDrawer from './settings-drawer';
import LinkControlSearchItem from './search-item';
import LinkControlSearchInput from './search-input';
const MODE_EDIT = 'edit';
function LinkControl( {
value,
settings,
onChange = noop,
showInitialSuggestions,
} ) {
const instanceId = useInstanceId( LinkControl );
const [ inputValue, setInputValue ] = useState( '' );
const [ isEditingLink, setIsEditingLink ] = useState( ! value || ! value.url );
const { fetchSearchSuggestions } = useSelect( ( select ) => {
const { getSettings } = select( 'core/block-editor' );
return {
fetchSearchSuggestions: getSettings().__experimentalFetchLinkSuggestions,
};
}, [] );
// Handlers
/**
* onChange LinkControlSearchInput event handler
*
* @param {string} val Current value returned by the search.
*/
const onInputChange = ( val = '' ) => {
setInputValue( val );
};
// Utils
/**
* Handler function which switches the mode of the component,
* between `edit` and `show` mode.
*
* @param {string} mode Component mode: `show` or `edit`.
*/
const setMode = ( mode = 'show' ) => () => {
setIsEditingLink( MODE_EDIT === mode );
// Populate input searcher whether
// the current link has a title.
if ( value && value.title && MODE_EDIT === mode ) {
setInputValue( value.title );
}
};
const resetInput = () => {
setInputValue( '' );
};
const handleDirectEntry = ( val ) => {
let type = 'URL';
const protocol = getProtocol( val ) || '';
if ( protocol.includes( 'mailto' ) ) {
type = 'mailto';
}
if ( protocol.includes( 'tel' ) ) {
type = 'tel';
}
if ( startsWith( val, '#' ) ) {
type = 'internal';
}
return Promise.resolve(
[ {
id: '-1',
title: val,
url: type === 'URL' ? prependHTTP( val ) : val,
type,
} ]
);
};
const handleEntitySearch = async ( val, args ) => {
const results = await Promise.all( [
fetchSearchSuggestions( val, {
...( args.isInitialSuggestions ? { perPage: 3 } : {} ),
} ),
handleDirectEntry( val ),
] );
const couldBeURL = ! val.includes( ' ' );
// If it's potentially a URL search then concat on a URL search suggestion
// just for good measure. That way once the actual results run out we always
// have a URL option to fallback on.
return couldBeURL && ! args.isInitialSuggestions ? results[ 0 ].concat( results[ 1 ] ) : results[ 0 ];
};
// Effects
const getSearchHandler = useCallback( ( val, args ) => {
const protocol = getProtocol( val ) || '';
const isMailto = protocol.includes( 'mailto' );
const isInternal = startsWith( val, '#' );
const isTel = protocol.includes( 'tel' );
const handleManualEntry = isInternal || isMailto || isTel || isURL( val ) || ( val && val.includes( 'www.' ) );
return ( handleManualEntry ) ? handleDirectEntry( val, args ) : handleEntitySearch( val, args );
}, [ handleDirectEntry, fetchSearchSuggestions ] );
// Render Components
const renderSearchResults = ( { suggestionsListProps, buildSuggestionItemProps, suggestions, selectedSuggestion, isLoading, isInitialSuggestions } ) => {
const resultsListClasses = classnames( 'block-editor-link-control__search-results', {
'is-loading': isLoading,
} );
const manualLinkEntryTypes = [ 'url', 'mailto', 'tel', 'internal' ];
const searchResultsLabelId = isInitialSuggestions ? `block-editor-link-control-search-results-label-${ instanceId }` : undefined;
const labelText = isInitialSuggestions ? __( 'Recently updated' ) : sprintf( __( 'Search results for %s' ), inputValue );
// According to guidelines aria-label should be added if the label
// itself is not visible.
// See: https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/listbox_role
const ariaLabel = isInitialSuggestions ? undefined : labelText;
const SearchResultsLabel = (
<span className="block-editor-link-control__search-results-label" id={ searchResultsLabelId } aria-label={ ariaLabel } >
{ labelText }
</span>
);
return (
<div className="block-editor-link-control__search-results-wrapper">
{ isInitialSuggestions ? SearchResultsLabel : <VisuallyHidden>{ SearchResultsLabel }</VisuallyHidden> }
<div { ...suggestionsListProps } className={ resultsListClasses } aria-labelledby={ searchResultsLabelId }>
{ suggestions.map( ( suggestion, index ) => (
<LinkControlSearchItem
key={ `${ suggestion.id }-${ suggestion.type }` }
itemProps={ buildSuggestionItemProps( suggestion, index ) }
suggestion={ suggestion }
onClick={ () => {
setIsEditingLink( false );
onChange( { ...value, ...suggestion } );
} }
isSelected={ index === selectedSuggestion }
isURL={ manualLinkEntryTypes.includes( suggestion.type.toLowerCase() ) }
searchTerm={ inputValue }
/>
) ) }
</div>
</div>
);
};
return (
<div className="block-editor-link-control">
{ ( ! isEditingLink ) && (
<Fragment>
<p className="screen-reader-text" id={ `current-link-label-${ instanceId }` }>
{ __( 'Currently selected' ) }:
</p>
<div
aria-labelledby={ `current-link-label-${ instanceId }` }
aria-selected="true"
className={ classnames( 'block-editor-link-control__search-item', {
'is-current': true,
} ) }
>
<span className="block-editor-link-control__search-item-header">
<ExternalLink
className="block-editor-link-control__search-item-title"
href={ value.url }
>
{ value.title }
</ExternalLink>
<span className="block-editor-link-control__search-item-info">{ filterURLForDisplay( safeDecodeURI( value.url ) ) || '' }</span>
</span>
<Button isSecondary onClick={ setMode( MODE_EDIT ) } className="block-editor-link-control__search-item-action block-editor-link-control__search-item-action--edit">
{ __( 'Edit' ) }
</Button>
</div>
</Fragment>
) }
{ isEditingLink && (
<LinkControlSearchInput
value={ inputValue }
onChange={ onInputChange }
onSelect={ ( suggestion ) => {
setIsEditingLink( false );
onChange( { ...value, ...suggestion } );
} }
renderSuggestions={ renderSearchResults }
fetchSuggestions={ getSearchHandler }
onReset={ resetInput }
showInitialSuggestions={ showInitialSuggestions }
/>
) }
{ ! isEditingLink && (
<LinkControlSettingsDrawer value={ value } settings={ settings } onChange={ onChange } />
) }
</div>
);
}
export default LinkControl;