This repository has been archived by the owner on Jun 26, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 37
/
imageuploadediting.js
291 lines (242 loc) · 9.12 KB
/
imageuploadediting.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
/**
* @license Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
/**
* @module image/imageupload/imageuploadediting
*/
import Plugin from '@ckeditor/ckeditor5-core/src/plugin';
import FileRepository from '@ckeditor/ckeditor5-upload/src/filerepository';
import Notification from '@ckeditor/ckeditor5-ui/src/notification/notification';
import UpcastWriter from '@ckeditor/ckeditor5-engine/src/view/upcastwriter';
import ImageUploadCommand from '../../src/imageupload/imageuploadcommand';
import { isImageType, isLocalImage, fetchLocalImage } from '../../src/imageupload/utils';
/**
* The editing part of the image upload feature. It registers the `'imageUpload'` command.
*
* @extends module:core/plugin~Plugin
*/
export default class ImageUploadEditing extends Plugin {
/**
* @inheritDoc
*/
static get requires() {
return [ FileRepository, Notification ];
}
/**
* @inheritDoc
*/
init() {
const editor = this.editor;
const doc = editor.model.document;
const schema = editor.model.schema;
const conversion = editor.conversion;
const fileRepository = editor.plugins.get( FileRepository );
// Setup schema to allow uploadId and uploadStatus for images.
schema.extend( 'image', {
allowAttributes: [ 'uploadId', 'uploadStatus' ]
} );
// Register imageUpload command.
editor.commands.add( 'imageUpload', new ImageUploadCommand( editor ) );
// Register upcast converter for uploadId.
conversion.for( 'upcast' )
.attributeToAttribute( {
view: {
name: 'img',
key: 'uploadId'
},
model: 'uploadId'
} );
// Handle pasted images.
// For every image file, a new file loader is created and a placeholder image is
// inserted into the content. Then, those images are uploaded once they appear in the model
// (see Document#change listener below).
this.listenTo( editor.editing.view.document, 'clipboardInput', ( evt, data ) => {
// Skip if non empty HTML data is included.
// https://github.com/ckeditor/ckeditor5-upload/issues/68
if ( isHtmlIncluded( data.dataTransfer ) ) {
return;
}
const images = Array.from( data.dataTransfer.files ).filter( file => {
// See https://github.com/ckeditor/ckeditor5-image/pull/254.
if ( !file ) {
return false;
}
return isImageType( file );
} );
const ranges = data.targetRanges.map( viewRange => editor.editing.mapper.toModelRange( viewRange ) );
editor.model.change( writer => {
// Set selection to paste target.
writer.setSelection( ranges );
if ( images.length ) {
evt.stop();
// Upload images after the selection has changed in order to ensure the command's state is refreshed.
editor.model.enqueueChange( 'default', () => {
editor.execute( 'imageUpload', { file: images } );
} );
}
} );
} );
// Handle HTML pasted with images with base64 or blob sources.
// For every image file, a new file loader is created and a placeholder image is
// inserted into the content. Then, those images are uploaded once they appear in the model
// (see Document#change listener below).
if ( editor.plugins.has( 'Clipboard' ) ) {
this.listenTo( editor.plugins.get( 'Clipboard' ), 'inputTransformation', ( evt, data ) => {
const fetchableImages = Array.from( editor.editing.view.createRangeIn( data.content ) )
.filter( value => isLocalImage( value.item ) && !value.item.getAttribute( 'uploadProcessed' ) )
.map( value => { return { promise: fetchLocalImage( value.item ), imageElement: value.item }; } );
if ( !fetchableImages.length ) {
return;
}
const writer = new UpcastWriter();
for ( const fetchableImage of fetchableImages ) {
// Set attribute marking that the image was processed already.
writer.setAttribute( 'uploadProcessed', true, fetchableImage.imageElement );
const loader = fileRepository.createLoader( fetchableImage.promise );
if ( loader ) {
writer.setAttribute( 'src', '', fetchableImage.imageElement );
writer.setAttribute( 'uploadId', loader.id, fetchableImage.imageElement );
}
}
} );
}
// Prevents from the browser redirecting to the dropped image.
editor.editing.view.document.on( 'dragover', ( evt, data ) => {
data.preventDefault();
} );
// Upload placeholder images that appeared in the model.
doc.on( 'change', () => {
const changes = doc.differ.getChanges( { includeChangesInGraveyard: true } );
for ( const entry of changes ) {
if ( entry.type == 'insert' && entry.name == 'image' ) {
const item = entry.position.nodeAfter;
const isInGraveyard = entry.position.root.rootName == '$graveyard';
// Check if the image element still has upload id.
const uploadId = item.getAttribute( 'uploadId' );
if ( !uploadId ) {
continue;
}
// Check if the image is loaded on this client.
const loader = fileRepository.loaders.get( uploadId );
if ( !loader ) {
continue;
}
if ( isInGraveyard ) {
// If the image was inserted to the graveyard - abort the loading process.
loader.abort();
} else if ( loader.status == 'idle' ) {
// If the image was inserted into content and has not been loaded yet, start loading it.
this._readAndUpload( loader, item );
}
}
}
} );
}
/**
* Read and upload an image.
*
* The image is read from the disk and as a base64 encoded string it is set temporarily to
* `image[src]`. When the image is successfully uploaded the temporary data is replaced with the target
* image's URL (the URL to the uploaded image on the server).
*
* @protected
* @param {module:upload/filerepository~FileLoader} loader
* @param {module:engine/model/element~Element} imageElement
* @returns {Promise}
*/
_readAndUpload( loader, imageElement ) {
const editor = this.editor;
const model = editor.model;
const t = editor.locale.t;
const fileRepository = editor.plugins.get( FileRepository );
const notification = editor.plugins.get( Notification );
model.enqueueChange( 'transparent', writer => {
writer.setAttribute( 'uploadStatus', 'reading', imageElement );
} );
return loader.read()
.then( data => {
const viewFigure = editor.editing.mapper.toViewElement( imageElement );
const viewImg = viewFigure.getChild( 0 );
const promise = loader.upload();
editor.editing.view.change( writer => {
writer.setAttribute( 'src', data, viewImg );
} );
model.enqueueChange( 'transparent', writer => {
writer.setAttribute( 'uploadStatus', 'uploading', imageElement );
} );
return promise;
} )
.then( data => {
model.enqueueChange( 'transparent', writer => {
writer.setAttributes( { uploadStatus: 'complete', src: data.default }, imageElement );
this._parseAndSetSrcsetAttributeOnImage( data, imageElement, writer );
} );
clean();
} )
.catch( error => {
// If status is not 'error' nor 'aborted' - throw error because it means that something else went wrong,
// it might be generic error and it would be real pain to find what is going on.
if ( loader.status !== 'error' && loader.status !== 'aborted' ) {
throw error;
}
// Might be 'aborted'.
if ( loader.status == 'error' && error ) {
notification.showWarning( error, {
title: t( 'Upload failed' ),
namespace: 'upload'
} );
}
clean();
// Permanently remove image from insertion batch.
model.enqueueChange( 'transparent', writer => {
writer.remove( imageElement );
} );
} );
function clean() {
model.enqueueChange( 'transparent', writer => {
writer.removeAttribute( 'uploadId', imageElement );
writer.removeAttribute( 'uploadStatus', imageElement );
} );
fileRepository.destroyLoader( loader );
}
}
/**
* Creates `srcset` attribute based on a given file upload response and sets it as an attribute to a specific image element.
*
* @protected
* @param {Object} data Data object from which `srcset` will be created.
* @param {module:engine/model/element~Element} image The image element on which `srcset` attribute will be set.
* @param {module:engine/model/writer~Writer} writer
*/
_parseAndSetSrcsetAttributeOnImage( data, image, writer ) {
// Srcset attribute for responsive images support.
let maxWidth = 0;
const srcsetAttribute = Object.keys( data )
// Filter out keys that are not integers.
.filter( key => {
const width = parseInt( key, 10 );
if ( !isNaN( width ) ) {
maxWidth = Math.max( maxWidth, width );
return true;
}
} )
// Convert each key to srcset entry.
.map( key => `${ data[ key ] } ${ key }w` )
// Join all entries.
.join( ', ' );
if ( srcsetAttribute != '' ) {
writer.setAttribute( 'srcset', {
data: srcsetAttribute,
width: maxWidth
}, image );
}
}
}
// Returns `true` if non-empty `text/html` is included in the data transfer.
//
// @param {module:clipboard/datatransfer~DataTransfer} dataTransfer
// @returns {Boolean}
export function isHtmlIncluded( dataTransfer ) {
return Array.from( dataTransfer.types ).includes( 'text/html' ) && dataTransfer.getData( 'text/html' ) !== '';
}