-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
inline.js
301 lines (263 loc) · 8.47 KB
/
inline.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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
/**
* WordPress dependencies
*/
import { useState, useRef, createInterpolateElement } from '@wordpress/element';
import { __, sprintf } from '@wordpress/i18n';
import { withSpokenMessages, Popover } from '@wordpress/components';
import { prependHTTP } from '@wordpress/url';
import {
create,
insert,
isCollapsed,
applyFormat,
useAnchor,
removeFormat,
slice,
replace,
split,
concat,
} from '@wordpress/rich-text';
import {
__experimentalLinkControl as LinkControl,
store as blockEditorStore,
} from '@wordpress/block-editor';
import { useSelect } from '@wordpress/data';
/**
* Internal dependencies
*/
import { createLinkFormat, isValidHref, getFormatBoundary } from './utils';
import { link as settings } from './index';
import useLinkInstanceKey from './use-link-instance-key';
function InlineLinkUI( {
isActive,
activeAttributes,
addingLink,
value,
onChange,
speak,
stopAddingLink,
contentRef,
} ) {
const richLinkTextValue = getRichTextValueFromSelection( value, isActive );
// Get the text content minus any HTML tags.
const richTextText = richLinkTextValue.text;
/**
* Pending settings to be applied to the next link. When inserting a new
* link, toggle values cannot be applied immediately, because there is not
* yet a link for them to apply to. Thus, they are maintained in a state
* value until the time that the link can be inserted or edited.
*
* @type {[Object|undefined,Function]}
*/
const [ nextLinkValue, setNextLinkValue ] = useState();
const { createPageEntity, userCanCreatePages } = useSelect( ( select ) => {
const { getSettings } = select( blockEditorStore );
const _settings = getSettings();
return {
createPageEntity: _settings.__experimentalCreatePageEntity,
userCanCreatePages: _settings.__experimentalUserCanCreatePages,
};
}, [] );
const linkValue = {
url: activeAttributes.url,
type: activeAttributes.type,
id: activeAttributes.id,
opensInNewTab: activeAttributes.target === '_blank',
title: richTextText,
...nextLinkValue,
};
function removeLink() {
const newValue = removeFormat( value, 'core/link' );
onChange( newValue );
stopAddingLink();
speak( __( 'Link removed.' ), 'assertive' );
}
function onChangeLink( nextValue ) {
// Merge with values from state, both for the purpose of assigning the
// next state value, and for use in constructing the new link format if
// the link is ready to be applied.
nextValue = {
...nextLinkValue,
...nextValue,
};
// LinkControl calls `onChange` immediately upon the toggling a setting.
const didToggleSetting =
linkValue.opensInNewTab !== nextValue.opensInNewTab &&
linkValue.url === nextValue.url;
// If change handler was called as a result of a settings change during
// link insertion, it must be held in state until the link is ready to
// be applied.
const didToggleSettingForNewLink =
didToggleSetting && nextValue.url === undefined;
// If link will be assigned, the state value can be considered flushed.
// Otherwise, persist the pending changes.
setNextLinkValue( didToggleSettingForNewLink ? nextValue : undefined );
if ( didToggleSettingForNewLink ) {
return;
}
const newUrl = prependHTTP( nextValue.url );
const linkFormat = createLinkFormat( {
url: newUrl,
type: nextValue.type,
id:
nextValue.id !== undefined && nextValue.id !== null
? String( nextValue.id )
: undefined,
opensInNewWindow: nextValue.opensInNewTab,
} );
const newText = nextValue.title || newUrl;
if ( isCollapsed( value ) && ! isActive ) {
// Scenario: we don't have any actively selected text or formats.
const toInsert = applyFormat(
create( { text: newText } ),
linkFormat,
0,
newText.length
);
onChange( insert( value, toInsert ) );
} else {
// Scenario: we have any active text selection or an active format.
let newValue;
if ( newText === richTextText ) {
// If we're not updating the text then ignore.
newValue = applyFormat( value, linkFormat );
} else {
// Create new RichText value for the new text in order that we
// can apply formats to it.
newValue = create( { text: newText } );
// Apply the new Link format to this new text value.
newValue = applyFormat(
newValue,
linkFormat,
0,
newText.length
);
// Get the boundaries of the active link format.
const boundary = getFormatBoundary( value, {
type: 'core/link',
} );
// Split the value at the start of the active link format.
// Passing "start" as the 3rd parameter is required to ensure
// the second half of the split value is split at the format's
// start boundary and avoids relying on the value's "end" property
// which may not correspond correctly.
const [ valBefore, valAfter ] = split(
value,
boundary.start,
boundary.start
);
// Update the original (full) RichTextValue replacing the
// target text with the *new* RichTextValue containing:
// 1. The new text content.
// 2. The new link format.
// As "replace" will operate on the first match only, it is
// run only against the second half of the value which was
// split at the active format's boundary. This avoids a bug
// with incorrectly targetted replacements.
// See: https://github.com/WordPress/gutenberg/issues/41771.
// Note original formats will be lost when applying this change.
// That is expected behaviour.
// See: https://github.com/WordPress/gutenberg/pull/33849#issuecomment-936134179.
const newValAfter = replace( valAfter, richTextText, newValue );
newValue = concat( valBefore, newValAfter );
}
newValue.start = newValue.end;
newValue.activeFormats = [];
onChange( newValue );
}
// Focus should only be shifted back to the formatted segment when the
// URL is submitted.
if ( ! didToggleSetting ) {
stopAddingLink();
}
if ( ! isValidHref( newUrl ) ) {
speak(
__(
'Warning: the link has been inserted but may have errors. Please test it.'
),
'assertive'
);
} else if ( isActive ) {
speak( __( 'Link edited.' ), 'assertive' );
} else {
speak( __( 'Link inserted.' ), 'assertive' );
}
}
const popoverAnchor = useAnchor( {
editableContentElement: contentRef.current,
settings,
} );
// Generate a string based key that is unique to this anchor reference.
// This is used to force re-mount the LinkControl component to avoid
// potential stale state bugs caused by the component not being remounted
// See https://github.com/WordPress/gutenberg/pull/34742.
const forceRemountKey = useLinkInstanceKey( popoverAnchor );
// The focusOnMount prop shouldn't evolve during render of a Popover
// otherwise it causes a render of the content.
const focusOnMount = useRef( addingLink ? 'firstElement' : false );
async function handleCreate( pageTitle ) {
const page = await createPageEntity( {
title: pageTitle,
status: 'draft',
} );
return {
id: page.id,
type: page.type,
title: page.title.rendered,
url: page.link,
kind: 'post-type',
};
}
function createButtonText( searchTerm ) {
return createInterpolateElement(
sprintf(
/* translators: %s: search term. */
__( 'Create Page: <mark>%s</mark>' ),
searchTerm
),
{ mark: <mark /> }
);
}
return (
<Popover
anchor={ popoverAnchor }
focusOnMount={ focusOnMount.current }
onClose={ stopAddingLink }
placement="bottom"
shift
>
<LinkControl
key={ forceRemountKey }
value={ linkValue }
onChange={ onChangeLink }
onRemove={ removeLink }
forceIsEditingLink={ addingLink }
hasRichPreviews
createSuggestion={ createPageEntity && handleCreate }
withCreateSuggestion={ userCanCreatePages }
createSuggestionButtonText={ createButtonText }
hasTextControl
/>
</Popover>
);
}
function getRichTextValueFromSelection( value, isActive ) {
// Default to the selection ranges on the RichTextValue object.
let textStart = value.start;
let textEnd = value.end;
// If the format is currently active then the rich text value
// should always be taken from the bounds of the active format
// and not the selected text.
if ( isActive ) {
const boundary = getFormatBoundary( value, {
type: 'core/link',
} );
textStart = boundary.start;
// Text *selection* always extends +1 beyond the edge of the format.
// We account for that here.
textEnd = boundary.end + 1;
}
// Get a RichTextValue containing the selected text content.
return slice( value, textStart, textEnd );
}
export default withSpokenMessages( InlineLinkUI );