-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
inline.js
300 lines (266 loc) · 8.03 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
/**
* WordPress dependencies
*/
import { useMemo, createInterpolateElement } from '@wordpress/element';
import { __, sprintf } from '@wordpress/i18n';
import { speak } from '@wordpress/a11y';
import { Popover } from '@wordpress/components';
import { prependHTTP } from '@wordpress/url';
import {
create,
insert,
isCollapsed,
applyFormat,
removeFormat,
slice,
replace,
split,
concat,
useAnchor,
} from '@wordpress/rich-text';
import {
__experimentalLinkControl as LinkControl,
store as blockEditorStore,
useCachedTruthy,
} from '@wordpress/block-editor';
import { useSelect } from '@wordpress/data';
/**
* Internal dependencies
*/
import { createLinkFormat, isValidHref, getFormatBoundary } from './utils';
import { link as settings } from './index';
const LINK_SETTINGS = [
...LinkControl.DEFAULT_LINK_SETTINGS,
{
id: 'nofollow',
title: __( 'Mark as nofollow' ),
},
];
function InlineLinkUI( {
isActive,
activeAttributes,
value,
onChange,
onFocusOutside,
stopAddingLink,
contentRef,
} ) {
const richLinkTextValue = getRichTextValueFromSelection( value, isActive );
// Get the text content minus any HTML tags.
const richTextText = richLinkTextValue.text;
const { createPageEntity, userCanCreatePages } = useSelect( ( select ) => {
const { getSettings } = select( blockEditorStore );
const _settings = getSettings();
return {
createPageEntity: _settings.__experimentalCreatePageEntity,
userCanCreatePages: _settings.__experimentalUserCanCreatePages,
};
}, [] );
const linkValue = useMemo(
() => ( {
url: activeAttributes.url,
type: activeAttributes.type,
id: activeAttributes.id,
opensInNewTab: activeAttributes.target === '_blank',
nofollow: activeAttributes.rel?.includes( 'nofollow' ),
title: richTextText,
} ),
[
activeAttributes.id,
activeAttributes.rel,
activeAttributes.target,
activeAttributes.type,
activeAttributes.url,
richTextText,
]
);
function removeLink() {
const newValue = removeFormat( value, 'core/link' );
onChange( newValue );
stopAddingLink();
speak( __( 'Link removed.' ), 'assertive' );
}
function onChangeLink( nextValue ) {
const hasLink = linkValue?.url;
const isNewLink = ! hasLink;
// Merge the next value with the current link value.
nextValue = {
...linkValue,
...nextValue,
};
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,
nofollow: nextValue.nofollow,
} );
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 );
}
onChange( newValue );
}
// Focus should only be returned to the rich text on submit if this link is not
// being created for the first time. If it is then focus should remain within the
// Link UI because it should remain open for the user to modify the link they have
// just created.
if ( ! isNewLink ) {
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,
} );
// As you change the link by interacting with the Link UI
// the return value of document.getSelection jumps to the field you're editing,
// not the highlighted text. Given that useAnchor uses document.getSelection,
// it will return null, since it can't find the <mark> element within the Link UI.
// This caches the last truthy value of the selection anchor reference.
// This ensures the Popover is positioned correctly on initial submission of the link.
const cachedRect = useCachedTruthy( popoverAnchor.getBoundingClientRect() );
popoverAnchor.getBoundingClientRect = () => cachedRect;
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 }
onClose={ stopAddingLink }
onFocusOutside={ onFocusOutside }
placement="bottom"
offset={ 10 }
shift
>
<LinkControl
value={ linkValue }
onChange={ onChangeLink }
onRemove={ removeLink }
hasRichPreviews
createSuggestion={ createPageEntity && handleCreate }
withCreateSuggestion={ userCanCreatePages }
createSuggestionButtonText={ createButtonText }
hasTextControl
settings={ LINK_SETTINGS }
showInitialSuggestions={ true }
suggestionsQuery={ {
// always show Pages as initial suggestions
initialSuggestionsSearchOptions: {
type: 'post',
subtype: 'page',
perPage: 20,
},
} }
/>
</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 InlineLinkUI;