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
/
Copy pathimageuploadediting.js
241 lines (198 loc) · 7.21 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
/**
* @license Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md.
*/
/**
* @module image/imageupload/imageuploadediting
*/
import Plugin from '@ckeditor/ckeditor5-core/src/plugin';
import FileRepository from '@ckeditor/ckeditor5-upload/src/filerepository';
import ImageUploadCommand from '../../src/imageupload/imageuploadcommand';
import Notification from '@ckeditor/ckeditor5-ui/src/notification/notification';
import ModelSelection from '@ckeditor/ckeditor5-engine/src/model/selection';
import ModelRange from '@ckeditor/ckeditor5-engine/src/model/range';
import { isImageType, findOptimalInsertionPosition } from '../../src/imageupload/utils';
/**
* Image upload editing plugin.
*
* @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 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 ) );
// Execute imageUpload command when image is dropped or pasted.
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;
}
let targetModelSelection = new ModelSelection(
data.targetRanges.map( viewRange => editor.editing.mapper.toModelRange( viewRange ) )
);
for ( const file of data.dataTransfer.files ) {
if ( isImageType( file ) ) {
const insertAt = findOptimalInsertionPosition( targetModelSelection );
editor.model.change( writer => {
const loader = fileRepository.createLoader( file );
// Do not throw when upload adapter is not set. FileRepository will log an error anyway.
if ( !loader ) {
return;
}
const imageElement = writer.createElement( 'image', { uploadId: loader.id } );
const targetSelection = new ModelSelection( [ new ModelRange( insertAt ) ] );
editor.model.insertContent( imageElement, targetSelection );
// Inserting an image might've failed due to schema regulations.
if ( imageElement.parent ) {
writer.setSelection( imageElement, 'on' );
}
} );
evt.stop();
}
// Use target ranges only for the first image. Then, use that image position
// so we keep adding the next ones after the previous one.
targetModelSelection = doc.selection;
}
} );
// Prevents from browser redirecting to the dropped image.
editor.editing.view.document.on( 'dragover', ( evt, data ) => {
data.preventDefault();
} );
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, start loading it.
this._load( loader, item );
}
}
}
} );
}
/**
* Performs image loading. The image is read from the disk and temporary data is displayed. When the upload process
* is complete the temporary data is replaced with the target image from the server.
*
* @private
* @param {module:upload/filerepository~FileLoader} loader
* @param {module:engine/model/element~Element} imageElement
* @returns {Promise}
*/
_load( 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 );
// 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
}, imageElement );
}
} );
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' ) {
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 );
}
}
}
// 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' ) !== '';
}