-
Notifications
You must be signed in to change notification settings - Fork 3.6k
/
ckboxcommand.ts
437 lines (373 loc) · 12.9 KB
/
ckboxcommand.ts
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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
/**
* @license Copyright (c) 2003-2024, CKSource Holding sp. z o.o. All rights reserved.
* For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
/* global document, window, setTimeout, URL */
/**
* @module ckbox/ckboxcommand
*/
import type { Writer } from 'ckeditor5/src/engine.js';
import { Command, type Editor } from 'ckeditor5/src/core.js';
import { createElement, toMap } from 'ckeditor5/src/utils.js';
import type {
CKBoxAssetDefinition,
CKBoxAssetImageAttributesDefinition,
CKBoxAssetImageDefinition,
CKBoxAssetLinkAttributesDefinition,
CKBoxAssetLinkDefinition,
CKBoxRawAssetDefinition
} from './ckboxconfig.js';
import { blurHashToDataUrl, getImageUrls } from './utils.js';
// Defines the waiting time (in milliseconds) for inserting the chosen asset into the model. The chosen asset is temporarily stored in the
// `CKBoxCommand#_chosenAssets` and it is removed from there automatically after this time. See `CKBoxCommand#_chosenAssets` for more
// details.
const ASSET_INSERTION_WAIT_TIMEOUT = 1000;
/**
* The CKBox command. It is used by the {@link module:ckbox/ckboxediting~CKBoxEditing CKBox editing feature} to open the CKBox file manager.
* The file manager allows inserting an image or a link to a file into the editor content.
*
* ```ts
* editor.execute( 'ckbox' );
* ```
*
* **Note:** This command uses other features to perform the following tasks:
* - To insert images it uses the {@link module:image/image/insertimagecommand~InsertImageCommand 'insertImage'} command from the
* {@link module:image/image~Image Image feature}.
* - To insert links to other files it uses the {@link module:link/linkcommand~LinkCommand 'link'} command from the
* {@link module:link/link~Link Link feature}.
*/
export default class CKBoxCommand extends Command {
declare public value: boolean;
/**
* A set of all chosen assets. They are stored temporarily and they are automatically removed 1 second after being chosen.
* Chosen assets have to be "remembered" for a while to be able to map the given asset with the element inserted into the model.
* This association map is then used to set the ID on the model element.
*
* All chosen assets are automatically removed after the timeout, because (theoretically) it may happen that they will never be
* inserted into the model, even if the {@link module:link/linkcommand~LinkCommand `'link'`} command or the
* {@link module:image/image/insertimagecommand~InsertImageCommand `'insertImage'`} command is enabled. Such a case may arise when
* another plugin blocks the command execution. Then, in order not to keep the chosen (but not inserted) assets forever, we delete
* them automatically to prevent memory leakage. The 1 second timeout is enough to insert the asset into the model and extract the
* ID from the chosen asset.
*
* The assets are stored only if
* the {@link module:ckbox/ckboxconfig~CKBoxConfig#ignoreDataId `config.ckbox.ignoreDataId`} option is set to `false` (by default).
*
* @internal
*/
public readonly _chosenAssets = new Set<CKBoxAssetDefinition>();
/**
* The DOM element that acts as a mounting point for the CKBox dialog.
*/
private _wrapper: Element | null = null;
/**
* @inheritDoc
*/
constructor( editor: Editor ) {
super( editor );
this._initListeners();
}
/**
* @inheritDoc
*/
public override refresh(): void {
this.value = this._getValue();
this.isEnabled = this._checkEnabled();
}
/**
* @inheritDoc
*/
public override execute(): void {
this.fire<CKBoxEvent<'open'>>( 'ckbox:open' );
}
/**
* Indicates if the CKBox dialog is already opened.
*
* @protected
* @returns {Boolean}
*/
private _getValue(): boolean {
return this._wrapper !== null;
}
/**
* Checks whether the command can be enabled in the current context.
*/
private _checkEnabled() {
const imageCommand = this.editor.commands.get( 'insertImage' )!;
const linkCommand = this.editor.commands.get( 'link' )!;
if ( !imageCommand.isEnabled && !linkCommand.isEnabled ) {
return false;
}
return true;
}
/**
* Creates the options object for the CKBox dialog.
*
* @returns The object with properties:
* - theme The theme for CKBox dialog.
* - language The language for CKBox dialog.
* - tokenUrl The token endpoint URL.
* - serviceOrigin The base URL of the API service.
* - forceDemoLabel Whether to force "Powered by CKBox" link.
* - dialog.onClose The callback function invoked after closing the CKBox dialog.
* - assets.onChoose The callback function invoked after choosing the assets.
*/
private _prepareOptions() {
const editor = this.editor;
const ckboxConfig = editor.config.get( 'ckbox' )!;
return {
theme: ckboxConfig.theme,
language: ckboxConfig.language,
tokenUrl: ckboxConfig.tokenUrl,
serviceOrigin: ckboxConfig.serviceOrigin,
forceDemoLabel: ckboxConfig.forceDemoLabel,
dialog: {
onClose: () => this.fire<CKBoxEvent<'close'>>( 'ckbox:close' )
},
assets: {
onChoose: ( assets: Array<CKBoxRawAssetDefinition> ) => this.fire<CKBoxEvent<'choose'>>( 'ckbox:choose', assets )
}
};
}
/**
* Initializes various event listeners for the `ckbox:*` events, because all functionality of the `ckbox` command is event-based.
*/
private _initListeners() {
const editor = this.editor;
const model = editor.model;
const shouldInsertDataId = !editor.config.get( 'ckbox.ignoreDataId' );
// Refresh the command after firing the `ckbox:*` event.
this.on<CKBoxEvent>( 'ckbox', () => {
this.refresh();
}, { priority: 'low' } );
// Handle opening of the CKBox dialog.
this.on<CKBoxEvent<'open'>>( 'ckbox:open', () => {
if ( !this.isEnabled || this.value ) {
return;
}
this._wrapper = createElement( document, 'div', { class: 'ck ckbox-wrapper' } );
document.body.appendChild( this._wrapper );
window.CKBox.mount( this._wrapper, this._prepareOptions() );
} );
// Handle closing of the CKBox dialog.
this.on<CKBoxEvent<'close'>>( 'ckbox:close', () => {
if ( !this.value ) {
return;
}
this._wrapper!.remove();
this._wrapper = null;
editor.editing.view.focus();
} );
// Handle choosing the assets.
this.on<CKBoxEvent<'choose'>>( 'ckbox:choose', ( evt, assets ) => {
if ( !this.isEnabled ) {
return;
}
const imageCommand = editor.commands.get( 'insertImage' )!;
const linkCommand = editor.commands.get( 'link' )!;
const assetsToProcess = prepareAssets( {
assets,
isImageAllowed: imageCommand.isEnabled,
isLinkAllowed: linkCommand.isEnabled
} );
const assetsCount = assetsToProcess.length;
if ( assetsCount === 0 ) {
return;
}
// All assets are inserted in one undo step.
model.change( writer => {
for ( const asset of assetsToProcess ) {
const isLastAsset = asset === assetsToProcess[ assetsCount - 1 ];
const isSingleAsset = assetsCount === 1;
this._insertAsset( asset, isLastAsset, writer, isSingleAsset );
// If asset ID must be set for the inserted model element, store the asset temporarily and remove it automatically
// after the timeout.
if ( shouldInsertDataId ) {
setTimeout( () => this._chosenAssets.delete( asset ), ASSET_INSERTION_WAIT_TIMEOUT );
this._chosenAssets.add( asset );
}
}
} );
editor.editing.view.focus();
} );
// Clean up after the editor is destroyed.
this.listenTo( editor, 'destroy', () => {
this.fire<CKBoxEvent<'close'>>( 'ckbox:close' );
this._chosenAssets.clear();
} );
}
/**
* Inserts the asset into the model.
*
* @param asset The asset to be inserted.
* @param isLastAsset Indicates if the current asset is the last one from the chosen set.
* @param writer An instance of the model writer.
* @param isSingleAsset It's true when only one asset is processed.
*/
private _insertAsset(
asset: CKBoxAssetDefinition,
isLastAsset: boolean,
writer: Writer,
isSingleAsset: boolean
) {
const editor = this.editor;
const model = editor.model;
const selection = model.document.selection;
// Remove the `linkHref` attribute to not affect the asset to be inserted.
writer.removeSelectionAttribute( 'linkHref' );
if ( asset.type === 'image' ) {
this._insertImage( asset );
} else {
this._insertLink( asset, writer, isSingleAsset );
}
// Except for the last chosen asset, move the selection to the end of the current range to avoid overwriting other, already
// inserted assets.
if ( !isLastAsset ) {
writer.setSelection( selection.getLastPosition() );
}
}
/**
* Inserts the image by calling the `insertImage` command.
*
* @param asset The asset to be inserted.
*/
private _insertImage( asset: CKBoxAssetImageDefinition ) {
const editor = this.editor;
const {
imageFallbackUrl,
imageSources,
imageTextAlternative,
imageWidth,
imageHeight,
imagePlaceholder
} = asset.attributes;
editor.execute( 'insertImage', {
source: {
src: imageFallbackUrl,
sources: imageSources,
alt: imageTextAlternative,
width: imageWidth,
height: imageHeight,
...( imagePlaceholder ? { placeholder: imagePlaceholder } : null )
}
} );
}
/**
* Inserts the link to the asset by calling the `link` command.
*
* @param asset The asset to be inserted.
* @param writer An instance of the model writer.
* @param isSingleAsset It's true when only one asset is processed.
*/
private _insertLink( asset: CKBoxAssetLinkDefinition, writer: Writer, isSingleAsset: boolean ): void {
const editor = this.editor;
const model = editor.model;
const selection = model.document.selection;
const { linkName, linkHref } = asset.attributes;
// If the selection is collapsed, insert the asset name as the link label and select it.
if ( selection.isCollapsed ) {
const selectionAttributes = toMap( selection.getAttributes() );
const textNode = writer.createText( linkName, selectionAttributes );
if ( !isSingleAsset ) {
const selectionLastPosition = selection.getLastPosition()!;
const parentElement = selectionLastPosition.parent;
// Insert new `paragraph` when selection is not in an empty `paragraph`.
if ( !( parentElement.name === 'paragraph' && parentElement.isEmpty ) ) {
editor.execute( 'insertParagraph', {
position: selectionLastPosition
} );
}
const range = model.insertContent( textNode );
writer.setSelection( range );
editor.execute( 'link', linkHref );
return;
}
const range = model.insertContent( textNode );
writer.setSelection( range );
}
editor.execute( 'link', linkHref );
}
}
/**
* Parses the chosen assets into the internal data format. Filters out chosen assets that are not allowed.
*/
function prepareAssets(
{ assets, isImageAllowed, isLinkAllowed }: {
assets: Array<CKBoxRawAssetDefinition>;
isImageAllowed: boolean;
isLinkAllowed: boolean;
}
): Array<CKBoxAssetDefinition> {
return assets
.map( asset => isImage( asset ) ?
{
id: asset.data.id,
type: 'image',
attributes: prepareImageAssetAttributes( asset )
} as const :
{
id: asset.data.id,
type: 'link',
attributes: prepareLinkAssetAttributes( asset )
} as const
)
.filter( asset => asset.type === 'image' ? isImageAllowed : isLinkAllowed );
}
/**
* Parses the assets attributes into the internal data format.
*
* @internal
*/
export function prepareImageAssetAttributes( asset: CKBoxRawAssetDefinition ): CKBoxAssetImageAttributesDefinition {
const { imageFallbackUrl, imageSources } = getImageUrls( asset.data.imageUrls! );
const { description, width, height, blurHash } = asset.data.metadata!;
const imagePlaceholder = blurHashToDataUrl( blurHash );
return {
imageFallbackUrl,
imageSources,
imageTextAlternative: description || '',
imageWidth: width,
imageHeight: height,
...( imagePlaceholder ? { imagePlaceholder } : null )
};
}
/**
* Parses the assets attributes into the internal data format.
*
* @param origin The base URL for assets inserted into the editor.
*/
function prepareLinkAssetAttributes( asset: CKBoxRawAssetDefinition ): CKBoxAssetLinkAttributesDefinition {
return {
linkName: asset.data.name,
linkHref: getAssetUrl( asset )
};
}
/**
* Checks whether the asset is an image.
*/
function isImage( asset: CKBoxRawAssetDefinition ) {
const metadata = asset.data.metadata;
if ( !metadata ) {
return false;
}
return metadata.width && metadata.height;
}
/**
* Creates the URL for the asset.
*
* @param origin The base URL for assets inserted into the editor.
*/
function getAssetUrl( asset: CKBoxRawAssetDefinition ) {
const url = new URL( asset.data.url );
url.searchParams.set( 'download', 'true' );
return url.toString();
}
/**
* Fired when the command is executed, the dialog is closed or the assets are chosen.
*
* @eventName ~CKBoxCommand#ckbox
*/
type CKBoxEvent<Name extends '' | 'choose' | 'open' | 'close' = ''> = {
name: Name extends '' ? 'ckbox' : `ckbox:${ Name }`;
args: Name extends 'choose' ? [ assets: Array<CKBoxRawAssetDefinition> ] : [];
};