Debian Codegraph @

extensions/VisualEditor/lib/ve/src/ce/ve.ce.ContentBranchNode.js

raw symbols SCIP
1 /*!
2 * VisualEditor ContentEditable ContentBranchNode class.
3 *
4 * @copyright See AUTHORS.txt
5 */
6
7 /**
8 * ContentEditable content branch node.
9 *
10 * Content branch nodes can only have content nodes as children.
11 *
12 * @abstract
13 * @extends ve.ce.BranchNode
14 * @constructor
15 * @param {ve.dm.BranchNode} model Model to observe
16 * @param {Object} [config] Configuration options
17 */
18 ve.ce.ContentBranchNode = function VeCeContentBranchNode() {
19 // Properties
20 this.lastTransaction = null;
21 // Parent constructor calls renderContents, so this must be set first
22 this.rendered = false;
23 this.unicornAnnotations = null;
24 this.unicorns = null;
25
26 // Parent constructor
27 ve.ce.ContentBranchNode.super.apply( this, arguments );
28
29 this.onClickHandler = this.onClick.bind( this );
30
31 // Events
32 this.connect( this, { childUpdate: 'onChildUpdate' } );
33 this.model.connect( this, { detach: 'onModelDetach' } );
34 // Some browsers allow clicking links inside contenteditable, such as in iOS Safari when the
35 // keyboard is closed
36 this.$element.on( 'click', this.onClickHandler );
37 };
38
39 /* Inheritance */
40
41 OO.inheritClass( ve.ce.ContentBranchNode, ve.ce.BranchNode );
42
43 /* Static Members */
44
45 /**
46 * @property {boolean} Whether Enter splits this node type. Must be true for ContentBranchNodes.
47 *
48 * Warning: overriding this to false in a subclass will cause crashes on Enter key handling.
49 *
50 * @static
51 * @inheritable
52 */
53 ve.ce.ContentBranchNode.static.splitOnEnter = true;
54
55 ve.ce.ContentBranchNode.static.autoFocus = true;
56
57 /* Static Methods */
58
59 /**
60 * Append the return value of #getRenderedContents to a DOM element.
61 *
62 * @param {HTMLElement} container DOM element
63 * @param {HTMLElement} wrapper Wrapper returned by #getRenderedContents
64 */
65 ve.ce.ContentBranchNode.static.appendRenderedContents = function ( container, wrapper ) {
66 function resolveOriginals( domElement ) {
67 for ( let i = 0, len = domElement.childNodes.length; i < len; i++ ) {
68 const child = domElement.childNodes[ i ];
69 if ( child.veOrigNode ) {
70 domElement.replaceChild( child.veOrigNode, child );
71 } else if ( child.childNodes && child.childNodes.length ) {
72 resolveOriginals( child );
73 }
74 }
75 }
76
77 /* Resolve references to the original nodes. */
78 resolveOriginals( wrapper );
79 while ( wrapper.firstChild ) {
80 container.appendChild( wrapper.firstChild );
81 }
82 };
83
84 /* Methods */
85
86 /**
87 * @inheritdoc
88 */
89 ve.ce.ContentBranchNode.prototype.initialize = function () {
90 // Parent method
91 ve.ce.ContentBranchNode.super.prototype.initialize.call( this );
92 this.$element.addClass( 've-ce-contentBranchNode' );
93 };
94
95 /**
96 * @inheritdoc
97 */
98 ve.ce.ContentBranchNode.prototype.onSetup = function () {
99 // Parent method
100 ve.ce.ContentBranchNode.super.prototype.onSetup.apply( this, arguments );
101
102 // DOM changes (duplicated from constructor in case this.$element is replaced)
103 this.$element.addClass( 've-ce-contentBranchNode' );
104 };
105
106 /**
107 * Handle click events.
108 *
109 * @param {jQuery.Event} e Click event
110 */
111 ve.ce.ContentBranchNode.prototype.onClick = function ( e ) {
112 if (
113 // Only block clicks on links
114 ( e.target !== this.$element[ 0 ] && e.target.nodeName.toUpperCase() === 'A' ) &&
115 // Don't prevent a modified click, which in some browsers deliberately opens the link
116 ( !e.altKey && !e.ctrlKey && !e.metaKey && !e.shiftKey )
117 ) {
118 e.preventDefault();
119 }
120 };
121
122 /**
123 * Handle childUpdate events.
124 *
125 * Rendering is only done once per transaction. If a paragraph has multiple nodes in it then it's
126 * possible to receive multiple `childUpdate` events for a single transaction such as annotating
127 * across them. State is tracked by storing and comparing the length of the surface model's complete
128 * history.
129 *
130 * This is used to automatically render contents.
131 *
132 * @param {ve.dm.Transaction} transaction
133 */
134 ve.ce.ContentBranchNode.prototype.onChildUpdate = function ( transaction ) {
135 if ( transaction === null || transaction === this.lastTransaction ) {
136 this.lastTransaction = transaction;
137 return;
138 }
139 this.renderContents();
140 };
141
142 /**
143 * @inheritdoc
144 */
145 ve.ce.ContentBranchNode.prototype.onSplice = function ( index, deleteCount, ...nodes ) {
146 // Parent method
147 ve.ce.ContentBranchNode.super.prototype.onSplice.apply( this, arguments );
148
149 // FIXME T126025: adjust slugNodes indexes if isRenderingLocked. This should be
150 // sufficient to keep this.slugNodes valid - only text changes can occur, which
151 // cannot create a requirement for a new slug (it can make an existing slug
152 // redundant, but it is harmless to leave it there).
153 // TODO fix the use of ve.ce.DocumentNode and getSurface
154 if (
155 this.root instanceof ve.ce.DocumentNode &&
156 this.root.getSurface().isRenderingLocked
157 ) {
158 this.slugNodes.splice( index, deleteCount, ...new Array( nodes.length ) );
159 }
160
161 // Rerender to make sure annotations are applied correctly
162 this.renderContents();
163 };
164
165 /**
166 * @inheritdoc
167 */
168 ve.ce.ContentBranchNode.prototype.setupBlockSlugs = function () {
169 // Respect render lock
170 // TODO: Can this check be moved into the parent method?
171 // TODO fix the use of ve.ce.DocumentNode and getSurface
172 if (
173 this.root instanceof ve.ce.DocumentNode &&
174 this.root.getSurface().isRenderingLocked()
175 ) {
176 return;
177 }
178 // Parent method
179 ve.ce.ContentBranchNode.super.prototype.setupBlockSlugs.apply( this, arguments );
180 };
181
182 /**
183 * @inheritdoc
184 */
185 ve.ce.ContentBranchNode.prototype.setupInlineSlugs = function () {
186 // Respect render lock
187 // TODO: Can this check be moved into the parent method?
188 // TODO fix the use of ve.ce.DocumentNode and getSurface
189 if (
190 this.root instanceof ve.ce.DocumentNode &&
191 this.root.getSurface().isRenderingLocked()
192 ) {
193 return;
194 }
195 // Parent method
196 ve.ce.ContentBranchNode.super.prototype.setupInlineSlugs.apply( this, arguments );
197 };
198
199 /**
200 * @typedef {Object} UnicornInfo
201 * @memberof ve.ce.ContentBranchNode
202 * @property {boolean} hasCursor
203 * @property {ve.dm.AnnotationSet|null} annotations
204 * @property {HTMLElement[]|null} unicorns
205 */
206
207 /**
208 * @typedef {HTMLElement} HTMLElementWithUnicorn
209 * @memberof ve.ce.ContentBranchNode
210 * @property {ve.ce.ContentBranchNode.UnicornInfo} unicornInfo Unicorn information
211 */
212
213 /**
214 * Get an HTML rendering of the contents.
215 *
216 * If you are actually going to append the result to a DOM, you need to
217 * do this with #appendRenderedContents, which resolves the cloned
218 * nodes returned by this function back to their originals.
219 *
220 * @return {ve.ce.ContentBranchNode.HTMLElementWithUnicorn} Wrapper containing rendered contents
221 */
222 ve.ce.ContentBranchNode.prototype.getRenderedContents = function () {
223 const store = this.model.doc.getStore(),
224 annotationSet = new ve.dm.AnnotationSet( store ),
225 doc = this.getElementDocument(),
226 wrapper = doc.createElement( 'div' ),
227 annotatedHtml = [],
228 annotationStack = [],
229 nodeStack = [],
230 unicornInfo = {
231 hasCursor: false,
232 annotations: null,
233 unicorns: null
234 };
235
236 let annotationsChanged,
237 current = wrapper,
238 buffer = '';
239 // Source mode optimization
240 if ( this.getModel().getDocument().sourceMode ) {
241 wrapper.appendChild(
242 document.createTextNode(
243 this.getModel().getDocument().getDataFromNode( this.getModel() ).join( '' )
244 )
245 );
246 wrapper.unicornInfo = unicornInfo;
247 return wrapper;
248 }
249
250 const openAnnotation = ( annotation ) => {
251 annotationsChanged = true;
252 if ( buffer !== '' ) {
253 if ( current.nodeType === Node.TEXT_NODE ) {
254 current.textContent += buffer;
255 } else {
256 current.appendChild( doc.createTextNode( buffer ) );
257 }
258 buffer = '';
259 }
260 // Create a new DOM node and descend into it
261 annotation.store = store;
262 const ann = ve.ce.annotationFactory.create( annotation.getType(), annotation, this );
263 ann.appendTo( current );
264 annotationStack.push( ann );
265 nodeStack.push( current );
266 current = ann.getContentContainer();
267 };
268
269 const closeAnnotation = () => {
270 annotationsChanged = true;
271 if ( buffer !== '' ) {
272 if ( current.nodeType === Node.TEXT_NODE ) {
273 current.textContent += buffer;
274 } else {
275 current.appendChild( doc.createTextNode( buffer ) );
276 }
277 buffer = '';
278 }
279 // Traverse up
280 const ann = annotationStack.pop();
281 ann.attachContents();
282 current = nodeStack.pop();
283 };
284
285 // Gather annotated HTML from the child nodes
286 for ( let i = 0, ilen = this.children.length; i < ilen; i++ ) {
287 ve.batchPush( annotatedHtml, this.children[ i ].getAnnotatedHtml() );
288 }
289
290 // Set relCursor to collapsed selection offset, or -1 if none
291 // (in which case we don't need to worry about preannotation)
292 let relCursor = -1;
293 let dmSurface;
294 if ( this.getRoot() ) {
295 const ceSurface = this.getRoot().getSurface();
296 dmSurface = ceSurface.getModel();
297 // TODO: dmSurface is used again later but might not be set
298 const dmSelection = dmSurface.getTranslatedSelection();
299 if ( dmSelection instanceof ve.dm.LinearSelection && dmSelection.isCollapsed() ) {
300 // Subtract 1 for CBN opening tag
301 relCursor = dmSelection.getRange().start - this.getOffset() - 1;
302 }
303 }
304
305 let unicorn;
306 // Set cursor status for renderContents. If hasCursor, splice unicorn marker at the
307 // collapsed selection offset. It will be rendered later if it is needed, else ignored
308 if ( relCursor < 0 || relCursor > this.getLength() ) {
309 unicornInfo.hasCursor = false;
310 } else {
311 unicornInfo.hasCursor = true;
312 let offset = 0;
313 let i, ilen;
314 for ( i = 0, ilen = annotatedHtml.length; i < ilen; i++ ) {
315 const htmlItem = annotatedHtml[ i ][ 0 ];
316 const childLength = ( typeof htmlItem === 'string' ) ? 1 : 2;
317 if ( offset <= relCursor && relCursor < offset + childLength ) {
318 unicorn = [
319 {}, // Unique object, for testing object equality later
320 dmSurface.getInsertionAnnotations().storeHashes
321 ];
322 annotatedHtml.splice( i, 0, unicorn );
323 break;
324 }
325 offset += childLength;
326 }
327 // Special case for final position
328 if ( i === ilen && offset === relCursor ) {
329 unicorn = [
330 {}, // Unique object, for testing object equality later
331 dmSurface.getInsertionAnnotations().storeHashes
332 ];
333 annotatedHtml.push( unicorn );
334 }
335 }
336
337 // Render HTML with annotations
338 for ( let i = 0, ilen = annotatedHtml.length; i < ilen; i++ ) {
339 let item;
340 let itemAnnotations;
341 if ( Array.isArray( annotatedHtml[ i ] ) ) {
342 item = annotatedHtml[ i ][ 0 ];
343 itemAnnotations = new ve.dm.AnnotationSet( store, annotatedHtml[ i ][ 1 ] );
344 } else {
345 item = annotatedHtml[ i ];
346 itemAnnotations = new ve.dm.AnnotationSet( store );
347 }
348
349 // annotationsChanged gets set to true by openAnnotation and closeAnnotation
350 annotationsChanged = false;
351 ve.dm.Converter.static.openAndCloseAnnotations( annotationSet, itemAnnotations,
352 openAnnotation, closeAnnotation
353 );
354
355 // Handle the actual item
356 if ( typeof item === 'string' ) {
357 buffer += item;
358 } else if ( unicorn && item === unicorn[ 0 ] ) {
359 if ( annotationsChanged ) {
360 if ( buffer !== '' ) {
361 current.appendChild( doc.createTextNode( buffer ) );
362 buffer = '';
363 }
364 const preUnicorn = doc.createElement( 'img' );
365 const postUnicorn = doc.createElement( 'img' );
366 preUnicorn.className = 've-ce-unicorn ve-ce-pre-unicorn';
367 postUnicorn.className = 've-ce-unicorn ve-ce-post-unicorn';
368 $( preUnicorn ).data( 'modelOffset', ( this.getOffset() + 1 + i ) );
369 $( postUnicorn ).data( 'modelOffset', ( this.getOffset() + 1 + i ) );
370 if ( ve.inputDebug ) {
371 preUnicorn.setAttribute( 'src', ve.ce.unicornImgDataUri );
372 postUnicorn.setAttribute( 'src', ve.ce.unicornImgDataUri );
373 preUnicorn.className += ' ve-ce-unicorn-debug';
374 postUnicorn.className += ' ve-ce-unicorn-debug';
375 } else {
376 preUnicorn.setAttribute( 'src', ve.ce.minImgDataUri );
377 postUnicorn.setAttribute( 'src', ve.ce.minImgDataUri );
378 }
379 current.appendChild( preUnicorn );
380 current.appendChild( postUnicorn );
381 unicornInfo.annotations = dmSurface.getInsertionAnnotations();
382 unicornInfo.unicorns = [ preUnicorn, postUnicorn ];
383 } else {
384 unicornInfo.annotations = null;
385 unicornInfo.unicorns = null;
386 }
387 } else {
388 if ( buffer !== '' ) {
389 current.appendChild( doc.createTextNode( buffer ) );
390 buffer = '';
391 }
392 // DOM equivalent of $( current ).append( item.clone() );
393 for ( let j = 0, jlen = item.length; j < jlen; j++ ) {
394 // Append a clone so as to not relocate the original node
395 const clone = item[ j ].cloneNode( true );
396 // Store a reference to the original node in a property
397 clone.veOrigNode = item[ j ];
398 current.appendChild( clone );
399 }
400 }
401 }
402 if ( buffer !== '' ) {
403 current.appendChild( doc.createTextNode( buffer ) );
404 buffer = '';
405 }
406 while ( annotationStack.length > 0 ) {
407 closeAnnotation();
408 }
409 wrapper.unicornInfo = unicornInfo;
410 return wrapper;
411 };
412
413 ve.ce.ContentBranchNode.prototype.onModelDetach = function () {
414 // TODO fix the use of ve.ce.DocumentNode and getSurface
415 if ( this.root instanceof ve.ce.DocumentNode ) {
416 this.root.getSurface().setContentBranchNodeChanged();
417 }
418 };
419
420 /**
421 * Render contents.
422 *
423 * @return {boolean} Whether the contents have changed
424 */
425 ve.ce.ContentBranchNode.prototype.renderContents = function () {
426 // TODO fix the use of ve.ce.DocumentNode and getSurface
427 if (
428 this.root instanceof ve.ce.DocumentNode &&
429 this.root.getSurface().isRenderingLocked()
430 ) {
431 return false;
432 }
433
434 if ( this.root instanceof ve.ce.DocumentNode ) {
435 this.root.getSurface().setContentBranchNodeChanged();
436 }
437
438 let rendered = this.getRenderedContents();
439 const unicornInfo = rendered.unicornInfo;
440
441 // Return if unchanged. Test by building the new version and checking DOM-equality.
442 // However we have to normalize to cope with consecutive text nodes. We can't normalize
443 // the attached version, because that would close IMEs. As an optimization, don't perform
444 // this checking if this node has never rendered before.
445
446 if ( this.rendered ) {
447 const oldWrapper = this.$element[ 0 ].cloneNode( true );
448 $( oldWrapper )
449 .find( '.ve-ce-annotation-active' )
450 .removeClass( 've-ce-annotation-active' );
451 $( oldWrapper )
452 .find( '.ve-ce-branchNode-inlineSlug' )
453 .children()
454 .unwrap()
455 .filter( '.ve-ce-chimera' )
456 .remove();
457 const newWrapper = this.$element[ 0 ].cloneNode( false );
458 while ( rendered.firstChild ) {
459 newWrapper.appendChild( rendered.firstChild );
460 }
461 oldWrapper.normalize();
462 newWrapper.normalize();
463 if ( newWrapper.isEqualNode( oldWrapper ) ) {
464 return false;
465 }
466 rendered = newWrapper;
467 }
468 this.rendered = true;
469
470 this.unicornAnnotations = unicornInfo.annotations || null;
471 this.unicorns = unicornInfo.unicorns || null;
472
473 // Detach all child nodes from this.$element
474 for ( let i = 0, len = this.$element.length; i < len; i++ ) {
475 const element = this.$element[ i ];
476 while ( element.firstChild ) {
477 element.removeChild( element.firstChild );
478 }
479 }
480
481 // Reattach nodes
482 this.constructor.static.appendRenderedContents( this.$element[ 0 ], rendered );
483
484 // Set unicorning status
485 if ( this.getRoot() ) {
486 if ( !unicornInfo.hasCursor ) {
487 this.getRoot().getSurface().setNotUnicorning( this );
488 } else if ( this.unicorns ) {
489 this.getRoot().getSurface().setUnicorning( this );
490 } else {
491 this.getRoot().getSurface().setNotUnicorningAll( this );
492 }
493 }
494
495 // Add slugs
496 this.setupInlineSlugs();
497
498 // Highlight the node in debug mode
499 if ( ve.inputDebug ) {
500 this.$element.css( 'backgroundColor', '#eee' );
501 setTimeout( () => {
502 this.$element.css( 'backgroundColor', '' );
503 }, 300 );
504 }
505
506 return true;
507 };
508
509 /**
510 * @inheritdoc
511 */
512 ve.ce.ContentBranchNode.prototype.detach = function () {
513 if ( this.getRoot() ) {
514 // This should be true, as the root is removed in the parent detach
515 // method which hasn't run yet. However, just in case a node gets
516 // double-detached…
517 this.getRoot().getSurface().setNotUnicorning( this );
518 }
519
520 // Parent method
521 ve.ce.ContentBranchNode.super.prototype.detach.call( this );
522 };
523
524 /**
525 * @inheritdoc
526 */
527 ve.ce.ContentBranchNode.prototype.destroy = function () {
528 this.$element.off( 'click', this.onClickHandler );
529
530 // Parent method
531 ve.ce.ContentBranchNode.super.prototype.destroy.call( this );
532 };