Debian Codegraph @

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

raw symbols SCIP
1 /*!
2 * VisualEditor ContentEditable BranchNode class.
3 *
4 * @copyright See AUTHORS.txt
5 */
6
7 /**
8 * ContentEditable branch node.
9 *
10 * Branch nodes can have branch or leaf nodes as children.
11 *
12 * @class
13 * @abstract
14 * @extends ve.ce.Node
15 * @mixes ve.BranchNode
16 * @constructor
17 * @param {ve.dm.BranchNode} model Model to observe
18 * @param {Object} [config] Configuration options
19 */
20 ve.ce.BranchNode = function VeCeBranchNode( model ) {
21 // Mixin constructor
22 ve.BranchNode.call( this );
23
24 // Parent constructor
25 ve.ce.BranchNode.super.apply( this, arguments );
26
27 // Properties
28 this.tagName = this.$element.get( 0 ).nodeName.toLowerCase();
29 this.slugNodes = [];
30
31 // Events
32 this.model.connect( this, { splice: 'onSplice' } );
33
34 // Initialization
35 this.onSplice( 0, 0, ...model.getChildren() );
36 };
37
38 /* Inheritance */
39
40 OO.inheritClass( ve.ce.BranchNode, ve.ce.Node );
41
42 OO.mixinClass( ve.ce.BranchNode, ve.BranchNode );
43
44 /* Static Properties */
45
46 /**
47 * Inline slug template.
48 *
49 * @static
50 * @property {HTMLElement}
51 */
52 ve.ce.BranchNode.inlineSlugTemplate = ( function () {
53 const profile = $.client.profile();
54 const layout = profile.layout;
55 const $img = $( '<img>' )
56 .attr( {
57 role: 'none',
58 alt: ''
59 } )
60 .addClass( 've-ce-chimera' );
61 if ( layout === 'webkit' || layout === 'gecko' ) {
62 // The following classes are used here:
63 // * ve-ce-chimera-gecko
64 // * ve-ce-chimera-webkit
65 $img.addClass( 've-ce-chimera-' + layout );
66 }
67
68 const $span = $( '<span>' )
69 .addClass( 've-ce-branchNode-slug ve-ce-branchNode-inlineSlug' )
70 .append( $img );
71
72 // Support: Firefox <69
73 // Firefox <=37 misbehaves if we don't set an src: https://bugzilla.mozilla.org/show_bug.cgi?id=989012
74 // Firefox <69 misbehaves if we don't set an src and there is no sizing at node creation time: https://bugzilla.mozilla.org/show_bug.cgi?id=1267906
75 // Setting an src in Chrome is slow, so only set it in affected versions of Firefox
76 if ( layout === 'gecko' && profile.versionNumber < 69 ) {
77 $img.prop( 'src', ve.ce.minImgDataUri );
78 }
79 return $span.get( 0 );
80 }() );
81
82 /**
83 * Inline slug template for input debugging.
84 *
85 * @static
86 * @property {HTMLElement}
87 */
88 ve.ce.BranchNode.inputDebugInlineSlugTemplate = $( '<span>' )
89 .addClass( 've-ce-branchNode-slug ve-ce-branchNode-inlineSlug' )
90 .append(
91 $( '<img>' )
92 .addClass( 've-ce-chimera ve-ce-chimera-debug' )
93 .attr( {
94 src: ve.ce.chimeraImgDataUri,
95 role: 'none',
96 alt: ''
97 } )
98 )
99 .get( 0 );
100
101 /**
102 * Block slug template.
103 *
104 * @static
105 * @property {HTMLElement}
106 */
107 ve.ce.BranchNode.blockSlugTemplate = $( '<div>' )
108 .addClass( 've-ce-branchNode-slug ve-ce-branchNode-blockSlug' )
109 .get( 0 );
110
111 /* Methods */
112
113 /**
114 * @inheritdoc
115 */
116 ve.ce.BranchNode.prototype.initialize = function () {
117 // Parent method
118 ve.ce.BranchNode.super.prototype.initialize.call( this );
119
120 this.$element.addClass( 've-ce-branchNode' );
121 };
122
123 /**
124 * Update the DOM wrapper.
125 *
126 * WARNING: The contents, .data( 'view' ), the contentEditable property and any classes the wrapper
127 * already has will be moved to the new wrapper, but other attributes and any other information
128 * added using $.data() will be lost upon updating the wrapper. To retain information added to the
129 * wrapper, subscribe to the 'teardown' and 'setup' events, or override #initialize.
130 *
131 * @fires ve.ce.View#teardown
132 * @fires ve.ce.View#setup
133 */
134 ve.ce.BranchNode.prototype.updateTagName = function () {
135 const tagName = this.getTagName();
136
137 if ( tagName !== this.tagName ) {
138 this.emit( 'teardown' );
139 const wrapper = document.createElement( tagName );
140 // Copy classes
141 // eslint-disable-next-line mediawiki/class-doc
142 wrapper.className = this.$element[ 0 ].className;
143 // Copy contentEditable
144 wrapper.contentEditable = this.$element[ 0 ].contentEditable;
145
146 // Insert new node, then move contents, then remove old node
147 // This lets ve.ce.Surface#afterMutations see that this is a move
148 if ( this.$element[ 0 ].parentNode ) {
149 this.$element[ 0 ].parentNode.insertBefore( wrapper, this.$element[ 0 ] );
150 }
151 while ( this.$element[ 0 ].firstChild ) {
152 wrapper.appendChild( this.$element[ 0 ].firstChild );
153 }
154 if ( this.$element[ 0 ].parentNode ) {
155 this.$element[ 0 ].parentNode.removeChild( this.$element[ 0 ] );
156 }
157
158 // Use new element from now on
159 this.$element = $( wrapper );
160 // Remember which tag name we are using now
161 this.tagName = tagName;
162 // Give subclasses the opportunity to touch the new element
163 this.initialize();
164 this.emit( 'setup' );
165
166 // TODO fix the use of ve.ce.DocumentNode and getSurface
167 if ( this.root instanceof ve.ce.DocumentNode ) {
168 this.root.getSurface().setContentBranchNodeChanged();
169 }
170 }
171 };
172
173 /**
174 * Handles model update events.
175 *
176 * @param {ve.dm.Transaction} transaction
177 */
178 ve.ce.BranchNode.prototype.onModelUpdate = function ( transaction ) {
179 this.emit( 'childUpdate', transaction );
180 };
181
182 /**
183 * Handle splice events.
184 *
185 * ve.ce.Node objects are generated from the inserted ve.dm.Node objects, producing a view that's a
186 * mirror of its model.
187 *
188 * @param {number} index Index to remove and or insert nodes at
189 * @param {number} deleteCount Number of nodes to remove
190 * @param {...ve.dm.BranchNode} [modelNodes] Variadic list of nodes to insert
191 */
192 ve.ce.BranchNode.prototype.onSplice = function ( index, deleteCount, ...modelNodes ) {
193 // attachedRoot and doc can be undefined in tests
194 const dmDoc = this.getModel().getDocument(),
195 attachedRoot = dmDoc && dmDoc.attachedRoot,
196 isAllAttached = !attachedRoot || attachedRoot instanceof ve.dm.DocumentNode;
197
198 let inAttachedRoot, upstreamOfAttachedRoot;
199 if ( !isAllAttached ) {
200 // Optimization: Skip traversal when whole doc is attached
201 inAttachedRoot = this.getModel().isDownstreamOf( attachedRoot );
202 upstreamOfAttachedRoot = attachedRoot.collectUpstream();
203 }
204
205 // Convert models to views and attach them to this node
206 const viewNodes = modelNodes.map( ( model ) => {
207 let view;
208 if (
209 isAllAttached || inAttachedRoot || upstreamOfAttachedRoot.indexOf( model ) !== -1 ||
210 // HACK: An internal item node was requested directly, e.g. for preview (T228070)
211 // TODO: Come up with a more explict way to skip the UnrenderedNode optimisation.
212 model.findParent( ve.dm.InternalItemNode )
213 ) {
214 view = ve.ce.nodeFactory.createFromModel( model );
215 view.model.connect( this, { update: 'onModelUpdate' } );
216 } else {
217 view = new ve.ce.UnrenderedNode( model );
218 }
219 return view;
220 } );
221 const removals = this.children.splice( index, deleteCount, ...viewNodes );
222 removals.forEach( ( view ) => {
223 view.model.disconnect( this, { update: 'onModelUpdate' } );
224 // Stop child listening to its model (e.g. for splice event)
225 view.model.disconnect( view );
226 view.setLive( false );
227 view.detach();
228 view.$element.detach();
229 // And fare thee weel a while
230 view.destroy();
231 } );
232 if ( viewNodes.length ) {
233 const fragment = document.createDocumentFragment();
234 for ( let i = viewNodes.length - 1; i >= 0; i-- ) {
235 viewNodes[ i ].attach( this );
236 for ( let j = viewNodes[ i ].$element.length - 1; j >= 0; j-- ) {
237 fragment.insertBefore( viewNodes[ i ].$element[ j ], fragment.childNodes[ 0 ] || null );
238 }
239 }
240 if ( fragment.childNodes.length ) {
241 // Only calculate this if it's needed, this function looks expensive
242 const position = this.getDomPosition( index );
243 position.node.insertBefore(
244 fragment,
245 position.node.children[ position.offset ] || null
246 );
247 }
248 for ( let i = viewNodes.length - 1; i >= 0; i-- ) {
249 if ( this.live !== viewNodes[ i ].isLive() ) {
250 viewNodes[ i ].setLive( this.live );
251 }
252 }
253 }
254
255 // TODO: restructure to clarify the logic (exactly one of these is a no-op)
256 this.setupBlockSlugs();
257 this.setupInlineSlugs();
258 };
259
260 /**
261 * Setup block slugs
262 */
263 ve.ce.BranchNode.prototype.setupBlockSlugs = function () {
264 // Only proceed if we are in a non-content node
265 if ( this.canHaveChildrenNotContent() ) {
266 this.setupSlugs( true );
267 }
268 };
269
270 /**
271 * Setup inline slugs
272 */
273 ve.ce.BranchNode.prototype.setupInlineSlugs = function () {
274 // Only proceed if we are in a content node
275 if ( !this.canHaveChildrenNotContent() ) {
276 this.setupSlugs( false );
277 }
278 };
279
280 /**
281 * Remove all slugs in this branch
282 */
283 ve.ce.BranchNode.prototype.removeSlugs = function () {
284 // Remove all slugs in this branch
285 for ( const i in this.slugNodes ) {
286 if ( this.slugNodes[ i ] !== undefined && this.slugNodes[ i ].parentNode ) {
287 this.slugNodes[ i ].parentNode.removeChild( this.slugNodes[ i ] );
288 }
289 delete this.slugNodes[ i ];
290 }
291 };
292
293 /**
294 * Setup slugs where needed.
295 *
296 * Existing slugs will be removed before new ones are added.
297 *
298 * @param {boolean} isBlock Set up block slugs, otherwise setup inline slugs
299 */
300 ve.ce.BranchNode.prototype.setupSlugs = function ( isBlock ) {
301 // Source mode optimization
302 if ( this.getModel().getDocument() && this.getModel().getDocument().sourceMode && isBlock ) {
303 return;
304 }
305
306 const doc = this.getElementDocument();
307
308 this.removeSlugs();
309
310 let slugTemplate;
311 if ( isBlock ) {
312 slugTemplate = ve.ce.BranchNode.blockSlugTemplate;
313 } else if ( ve.inputDebug ) {
314 slugTemplate = ve.ce.BranchNode.inputDebugInlineSlugTemplate;
315 } else {
316 slugTemplate = ve.ce.BranchNode.inlineSlugTemplate;
317 }
318
319 for ( const i in this.getModel().slugPositions ) {
320 const slugNode = doc.importNode( slugTemplate, true );
321 // FIXME T126019: InternalListNode has an empty $element, so we assume that the slug goes
322 // at the end instead. This is a hack and the internal list needs to die in a fire.
323 if ( this.children[ i ] && this.children[ i ].$element[ 0 ] ) {
324 const child = this.children[ i ].$element[ 0 ];
325 // child.parentNode might not be equal to this.$element[ 0 ]: e.g. annotated inline nodes
326 child.parentNode.insertBefore( slugNode, child );
327 } else {
328 this.$element[ 0 ].appendChild( slugNode );
329 }
330 this.slugNodes[ i ] = slugNode;
331 if ( isBlock ) {
332 const slugButton = new ve.ui.NoFocusButtonWidget( {
333 tabIndex: -1,
334 label: ve.msg( 'visualeditor-slug-insert' ),
335 icon: 'add',
336 framed: false
337 } ).on( 'click', this.onSlugClick.bind( this, slugNode ) );
338 $( slugNode ).append( slugButton.$element );
339 }
340 }
341 };
342
343 /**
344 * Handle slug click events
345 *
346 * @param {HTMLElement} slugNode Slug node clicked
347 */
348 ve.ce.BranchNode.prototype.onSlugClick = function ( slugNode ) {
349 this.getRoot().getSurface().createSlug( slugNode );
350 };
351
352 /**
353 * Get a slug at an offset.
354 *
355 * @param {number} offset Offset to get slug at
356 * @return {HTMLElement|null}
357 */
358 ve.ce.BranchNode.prototype.getSlugAtOffset = function ( offset ) {
359 let startOffset = this.model.getOffset() + ( this.isWrapped() ? 1 : 0 );
360
361 if ( offset === startOffset ) {
362 return this.slugNodes[ 0 ] || null;
363 }
364 for ( let i = 0; i < this.children.length; i++ ) {
365 startOffset += this.children[ i ].model.getOuterLength();
366 if ( offset === startOffset ) {
367 return this.slugNodes[ i + 1 ] || null;
368 }
369 }
370 return null;
371 };
372
373 /**
374 * Set live state on child nodes.
375 *
376 * @param {boolean} live New live state
377 */
378 ve.ce.BranchNode.prototype.setLive = function ( live ) {
379 // Parent method
380 ve.ce.BranchNode.super.prototype.setLive.apply( this, arguments );
381
382 for ( let i = 0; i < this.children.length; i++ ) {
383 this.children[ i ].setLive( live );
384 }
385 };
386
387 /**
388 * Release all memory.
389 */
390 ve.ce.BranchNode.prototype.destroy = function () {
391 for ( let i = 0, len = this.children.length; i < len; i++ ) {
392 this.children[ i ].destroy();
393 }
394
395 // Parent method
396 ve.ce.BranchNode.super.prototype.destroy.call( this );
397 };
398
399 /**
400 * @inheritdoc
401 */
402 ve.ce.BranchNode.prototype.detach = function () {
403 for ( let i = 0, len = this.children.length; i < len; i++ ) {
404 this.children[ i ].detach();
405 }
406
407 // Parent method
408 ve.ce.BranchNode.super.prototype.detach.call( this );
409 };
410
411 /**
412 * Get the DOM position (node and offset) corresponding to a position in this node
413 *
414 * The node/offset have the same semantics as a DOM Selection focusNode/focusOffset
415 *
416 * @param {number} offset The offset inside this node of the required position
417 * @return {ve.ce.NodeAndOffset} The DOM position; guaranteed to be this node's final DOM node
418 */
419 ve.ce.BranchNode.prototype.getDomPosition = function ( offset ) {
420 const domNode = this.$element.last()[ 0 ];
421
422 // Step backwards past empty nodes
423 let ceNode;
424 let i = offset - 1;
425 while ( true ) {
426 ceNode = this.children[ i-- ];
427 if ( !ceNode ) {
428 // No preceding children with DOM nodes
429 return { node: domNode, offset: 0 };
430 }
431 if ( ceNode.$element && ceNode.$element.length > 0 ) {
432 // Preceding child with a DOM node
433 return {
434 node: domNode,
435 offset: Array.prototype.indexOf.call(
436 domNode.childNodes,
437 ceNode.$element.last()[ 0 ]
438 ) + 1
439 };
440 }
441 if ( ceNode.getType() === 'text' ) {
442 break;
443 }
444 }
445 // Darn, we hit a text node. CE text nodes can contain varying annotations and so it is
446 // difficult to calculate how many childNodes to skip. Let's try stepping forward instead.
447 i = offset;
448 while ( true ) {
449 ceNode = this.children[ i++ ];
450 if ( !ceNode ) {
451 // No following children with DOM nodes
452 return { node: domNode, offset: domNode.childNodes.length };
453 }
454 if ( ceNode.$element && ceNode.$element.length > 0 ) {
455 // Following child with a DOM node
456 return {
457 node: domNode,
458 offset: Array.prototype.indexOf.call(
459 domNode.childNodes,
460 ceNode.$element.first()[ 0 ]
461 )
462 };
463 }
464 if ( ceNode.getType() === 'text' ) {
465 break;
466 }
467 }
468 // Oh no, there's a text node in both directions
469 throw new Error( 'Cannot calculate DOM position: adjacent text nodes' );
470 };