Debian Codegraph @

extensions/VisualEditor/lib/ve/src/ce/nodes/ve.ce.GeneratedContentNode.js

raw symbols SCIP
1 /*!
2 * VisualEditor ContentEditable GeneratedContentNode class.
3 *
4 * @copyright See AUTHORS.txt
5 */
6
7 /**
8 * ContentEditable generated content node.
9 *
10 * @class
11 * @abstract
12 *
13 * @constructor
14 */
15 ve.ce.GeneratedContentNode = function VeCeGeneratedContentNode() {
16 // Properties
17 this.generatingPromise = null;
18 this.generatedContentsInvalid = null;
19
20 // Events
21 this.model.connect( this, { update: 'onGeneratedContentNodeUpdate' } );
22 this.connect( this, { teardown: 'abortGenerating' } );
23
24 // Initialization
25 this.update();
26 };
27
28 /* Inheritance */
29
30 OO.initClass( ve.ce.GeneratedContentNode );
31
32 /* Events */
33
34 /**
35 * @event ve.ce.GeneratedContentNode#rerender
36 */
37
38 /* Static members */
39
40 // We handle rendering ourselves, no need to render attributes from originalDomElements
41 ve.ce.GeneratedContentNode.static.renderHtmlAttributes = false;
42
43 /* Static methods */
44
45 /**
46 * Wait for all content-generation within a given node to finish
47 *
48 * If no GeneratedContentNodes are within the node, a resolved promise will be
49 * returned.
50 *
51 * @param {ve.ce.View} view Any view node
52 * @return {jQuery.Promise} Promise, resolved when content is generated
53 */
54 ve.ce.GeneratedContentNode.static.awaitGeneratedContent = function ( view ) {
55 const promises = [];
56
57 function queueNode( node ) {
58 if ( typeof node.generateContents === 'function' ) {
59 if ( node.isGenerating() ) {
60 const promise = ve.createDeferred();
61 node.once( 'rerender', promise.resolve );
62 promises.push( promise );
63 }
64 }
65 }
66
67 // Traverse children to see when they are all rerendered
68 if ( view instanceof ve.ce.BranchNode ) {
69 view.traverse( queueNode );
70 } else {
71 queueNode( view );
72 }
73
74 return ve.promiseAll( promises );
75 };
76
77 /* Abstract methods */
78
79 /**
80 * Start a deferred process to generate the contents of the node.
81 *
82 * If successful, the returned promise must be resolved with the generated DOM elements passed
83 * in as the first parameter, i.e. promise.resolve( domElements ); . Any other parameters to
84 * .resolve() are ignored.
85 *
86 * If the returned promise object is abortable (has an .abort() method), .abort() will be called if
87 * a newer update is started before the current update has finished. When a promise is aborted, it
88 * should cease its work and shouldn't be resolved or rejected. If an outdated update's promise
89 * is resolved or rejected anyway (which may happen if an aborted promise misbehaves, or if the
90 * promise wasn't abortable), this is ignored and doneGenerating()/failGenerating() is not called.
91 *
92 * Additional data may be passed in the config object to instruct this function to render something
93 * different than what's in the model. This data is implementation-specific and is passed through
94 * by forceUpdate().
95 *
96 * @abstract
97 * @method
98 * @param {Object} [config] Optional additional data
99 * @return {jQuery.Promise} Promise object, may be abortable
100 */
101 ve.ce.GeneratedContentNode.prototype.generateContents = null;
102
103 /* Methods */
104
105 /**
106 * Handler for the update event
107 *
108 * @param {boolean} staged Update happened in staging mode
109 */
110 ve.ce.GeneratedContentNode.prototype.onGeneratedContentNodeUpdate = function ( staged ) {
111 this.update( undefined, staged );
112 };
113
114 /**
115 * Make an array of DOM elements suitable for rendering.
116 *
117 * Subclasses can override this to provide their own cleanup steps. This function takes an
118 * array of DOM elements cloned within the source document and returns an array of DOM elements
119 * cloned into the target document. If it's important that the DOM elements still be associated
120 * with the original document, you should modify domElements before calling the parent
121 * implementation, otherwise you should call the parent implementation first and modify its
122 * return value.
123 *
124 * @param {Node[]} domElements Clones of the DOM elements from the store
125 * @return {HTMLElement[]} Clones of the DOM elements in the right document, with modifications
126 */
127 ve.ce.GeneratedContentNode.prototype.getRenderedDomElements = function ( domElements ) {
128 const doc = this.getElementDocument();
129
130 let rendering = this.filterRenderedDomElements(
131 // Clone the elements into the target document
132 ve.copyDomElements( domElements, doc )
133 );
134
135 if ( rendering.length ) {
136 // Span wrap root text nodes so they can be measured
137 rendering = rendering.map( ( node ) => {
138 if ( node.nodeType === Node.TEXT_NODE ) {
139 const span = document.createElement( 'span' );
140 span.appendChild( node );
141 return span;
142 }
143 return node;
144 } );
145 // Render the computed values of some attributes
146 ve.resolveAttributes(
147 rendering,
148 domElements[ 0 ].ownerDocument,
149 ve.dm.Converter.static.computedAttributes
150 );
151 } else {
152 rendering = [ document.createElement( 'span' ) ];
153 }
154
155 if ( rendering.every( ve.isVoidElement ) ) {
156 // Should contain at least one non-void element, e.g. for attaching
157 // a visibility button in ve.ce.FocusableNode#updateInvisibleIconSync
158 rendering.push( document.createElement( 'span' ) );
159 }
160
161 return rendering;
162 };
163
164 /**
165 * Filter out elements from the rendered content which we don't want to display in the CE.
166 *
167 * @param {Node[]} domElements Clones of the DOM elements from the store, already copied into the document
168 * @return {Node[]} DOM elements to keep
169 */
170 ve.ce.GeneratedContentNode.prototype.filterRenderedDomElements = function ( domElements ) {
171 return ve.filterMetaElements( domElements );
172 };
173
174 /**
175 * Rerender the contents of this node.
176 *
177 * @param {Object|string|Array} generatedContents Generated contents, in the default case an HTMLElement array
178 * @param {boolean} [staged] Update happened in staging mode
179 * @fires ve.ce.View#setup
180 * @fires ve.ce.View#teardown
181 * @fires ve.dm.GeneratedContentNode#generatedContentsError
182 */
183 ve.ce.GeneratedContentNode.prototype.render = function ( generatedContents, staged ) {
184 if ( this.live ) {
185 this.emit( 'teardown' );
186 }
187 const $newElements = $( this.getRenderedDomElements( ve.copyDomElements( generatedContents ) ) );
188 this.generatedContentsInvalid = !this.validateGeneratedContents( $( generatedContents ) );
189 if ( !staged || !this.generatedContentsInvalid ) {
190 if ( !this.$element[ 0 ].parentNode ) {
191 // this.$element hasn't been attached yet, so just overwrite it
192 this.$element = $newElements;
193 } else {
194 // Switch out this.$element (which can contain multiple siblings) in place
195 const lengthChange = this.$element.length !== $newElements.length;
196 this.$element.first().replaceWith( $newElements );
197 this.$element.remove();
198 this.$element = $newElements;
199 if ( lengthChange ) {
200 // Changing the DOM node count can move the cursor, so re-apply
201 // the cursor position from the model (T231094).
202 setTimeout( () => {
203 if ( this.getRoot() && this.getRoot().getSurface() ) {
204 this.getRoot().getSurface().showModelSelection();
205 }
206 } );
207 }
208 }
209 } else {
210 this.generatedContentsValid = false;
211 this.model.emit( 'generatedContentsError', $newElements );
212 }
213
214 // Prevent tabbing to focusable elements inside the editable surface
215 this.preventTabbingInside();
216
217 // Update focusable and resizable elements if necessary
218 // TODO: Move these method definitions to their respective mixins.
219 if ( this.$focusable ) {
220 this.$focusable = this.getFocusableElement();
221 this.$bounding = this.getBoundingElement();
222 }
223 if ( this.$resizable ) {
224 this.$resizable = this.getResizableElement();
225 }
226
227 this.initialize();
228 if ( this.live ) {
229 this.emit( 'setup' );
230 }
231
232 this.afterRender();
233 };
234
235 /**
236 * Prevent tabbing to focusable elements inside the editable surface, because it conflicts with
237 * allowing tabbing out of the surface. (The surface takes the focus back when it moves to an
238 * element inside it.)
239 *
240 * In the future, this might be implemented using the `inert` property, currently not supported by
241 * any browser: https://html.spec.whatwg.org/multipage/interaction.html#inert-subtrees
242 * https://caniuse.com/mdn-api_htmlelement_inert
243 *
244 * @private
245 */
246 ve.ce.GeneratedContentNode.prototype.preventTabbingInside = function () {
247 // Like OO.ui.findFocusable(), but find *all* such nodes rather than the first one.
248 const selector = 'input, select, textarea, button, object, a, area, [contenteditable], [tabindex]',
249 $focusableCandidates = this.$element.find( selector ).addBack( selector );
250
251 $focusableCandidates.each( ( i, element ) => {
252 const $element = $( element );
253 if ( OO.ui.isFocusableElement( $element ) ) {
254 $element.attr( 'tabindex', -1 );
255 }
256 } );
257 };
258
259 /**
260 * Trigger rerender events after rendering the contents of the node.
261 *
262 * Nodes may override this method if the rerender event needs to be deferred (e.g. until images have loaded)
263 *
264 * @fires ve.ce.GeneratedContentNode#rerender
265 */
266 ve.ce.GeneratedContentNode.prototype.afterRender = function () {
267 this.emit( 'rerender' );
268 };
269
270 /**
271 * Check whether the response HTML contains an error.
272 *
273 * The default implementation always returns true.
274 *
275 * @param {jQuery} $element The generated element
276 * @return {boolean} There is no error
277 */
278 ve.ce.GeneratedContentNode.prototype.validateGeneratedContents = function () {
279 return true;
280 };
281
282 /**
283 * Update the contents of this node based on the model and config data. If this combination of
284 * model and config data has been rendered before, the cached rendering in the store will be used.
285 *
286 * @param {Object} [config] Optional additional data to pass to generateContents()
287 * @param {boolean} [staged] Update happened in staging mode
288 */
289 ve.ce.GeneratedContentNode.prototype.update = function ( config, staged ) {
290 const store = this.model.doc.getStore(),
291 contents = store.value( store.hashOfValue( null, OO.getHash( [ this.model.getHashObjectForRendering(), config ] ) ) );
292 if ( contents ) {
293 this.render( contents, staged );
294 } else {
295 this.forceUpdate( config, staged );
296 }
297 };
298
299 /**
300 * Force the contents to be updated. Like update(), but bypasses the store.
301 *
302 * @param {Object} [config] Optional additional data to pass to generateContents()
303 * @param {boolean} [staged] Update happened in staging mode
304 */
305 ve.ce.GeneratedContentNode.prototype.forceUpdate = function ( config, staged ) {
306 if ( this.generatingPromise ) {
307 // Abort the currently pending generation process if possible
308 this.abortGenerating();
309 } else {
310 // Only call startGenerating if we weren't generating before
311 this.startGenerating();
312 }
313
314 // Create a new promise
315 const promise = this.generatingPromise = this.generateContents( config );
316 promise
317 // If this promise is no longer the currently pending one, ignore it completely
318 .done( ( generatedContents ) => {
319 if ( this.generatingPromise === promise ) {
320 this.doneGenerating( generatedContents, config, staged );
321 }
322 } )
323 .fail( () => {
324 if ( this.generatingPromise === promise ) {
325 this.failGenerating();
326 }
327 } );
328 };
329
330 /**
331 * Called when the node starts generating new content.
332 *
333 * This function is only called when the node wasn't already generating content. If a second update
334 * comes in, this function will only be called if the first update has already finished (i.e.
335 * doneGenerating or failGenerating has already been called).
336 */
337 ve.ce.GeneratedContentNode.prototype.startGenerating = function () {
338 this.$element.addClass( 've-ce-generatedContentNode-generating' );
339 };
340
341 /**
342 * Abort the currently pending generation, if any, and remove the generating CSS class.
343 *
344 * This invokes .abort() on the pending promise if the promise has that method. It also ensures
345 * that if the promise does get resolved or rejected later, this is ignored.
346 */
347 ve.ce.GeneratedContentNode.prototype.abortGenerating = function () {
348 const promise = this.generatingPromise;
349 if ( promise ) {
350 // Unset this.generatingPromise first so that if the promise is resolved or rejected
351 // from within .abort(), this is ignored as it should be
352 this.generatingPromise = null;
353 if ( typeof promise.abort === 'function' ) {
354 promise.abort();
355 }
356 }
357 this.$element.removeClass( 've-ce-generatedContentNode-generating' );
358 };
359
360 /**
361 * Called when the node successfully finishes generating new content.
362 *
363 * @param {Object|string|Array} generatedContents Generated contents
364 * @param {Object} [config] Config object passed to forceUpdate()
365 * @param {boolean} [staged] Update happened in staging mode
366 */
367 ve.ce.GeneratedContentNode.prototype.doneGenerating = function ( generatedContents, config, staged ) {
368 this.$element.removeClass( 've-ce-generatedContentNode-generating' );
369 this.generatingPromise = null;
370
371 // Because doneGenerating is invoked asynchronously, the model node may have become detached
372 // in the meantime. Handle this gracefully.
373 if ( this.model && this.model.doc ) {
374 const store = this.model.doc.getStore();
375 const hash = OO.getHash( [ this.model.getHashObjectForRendering(), config ] );
376 store.hash( generatedContents, hash );
377 this.render( generatedContents, staged );
378 }
379 };
380
381 /**
382 * Called when the GeneratedContentNode has failed to generate new content.
383 */
384 ve.ce.GeneratedContentNode.prototype.failGenerating = function () {
385 this.$element.removeClass( 've-ce-generatedContentNode-generating' );
386 this.generatingPromise = null;
387 };
388
389 /**
390 * Check whether this GeneratedContentNode is currently generating new content.
391 *
392 * @return {boolean} Whether we're generating
393 */
394 ve.ce.GeneratedContentNode.prototype.isGenerating = function () {
395 return !!this.generatingPromise;
396 };
397
398 /**
399 * Get the focusable element
400 *
401 * @return {jQuery} Focusable element
402 */
403 ve.ce.GeneratedContentNode.prototype.getFocusableElement = function () {
404 return this.$element;
405 };
406
407 /**
408 * Get the bounding element
409 *
410 * @return {jQuery} Bounding element
411 */
412 ve.ce.GeneratedContentNode.prototype.getBoundingElement = function () {
413 return this.$element;
414 };
415
416 /**
417 * Get the resizable element
418 *
419 * @return {jQuery} Resizable element
420 */
421 ve.ce.GeneratedContentNode.prototype.getResizableElement = function () {
422 return this.$element;
423 };