Debian Codegraph @

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

raw symbols SCIP
1 /*!
2 * VisualEditor annotated text content state class
3 *
4 * @copyright See AUTHORS.txt
5 */
6
7 /**
8 * Annotated text content state (a snapshot of node content)
9 *
10 * @class
11 *
12 * @constructor
13 * @param {HTMLElement} element Element whose content is to be snapshotted
14 */
15 ve.ce.TextState = function VeCeTextState( element ) {
16 /**
17 * @property {ve.ce.TextStateChunk[]|null} chunks Linearized annotated text content
18 */
19 this.chunks = this.constructor.static.getChunks( element );
20 };
21
22 /* Inheritance */
23
24 OO.initClass( ve.ce.TextState );
25
26 /* Static methods */
27
28 /**
29 * Saves a snapshot of the current text content state
30 *
31 * @param {HTMLElement} element Element whose content is to be snapshotted
32 * @return {ve.ce.TextStateChunk[]} chunks
33 */
34 ve.ce.TextState.static.getChunks = function ( element ) {
35 // Stack of element-lists in force; each element list is equal to its predecessor extended
36 // by one element. This means two chunks have object-equal element lists if they have the
37 // same elements in force (i.e. if their text nodes are DOM siblings).
38 const elementListStack = [ [] ],
39 chunks = [];
40 let stackTop = 0;
41
42 /**
43 * Add to chunks, merging content with the same elements/type into the same chunk
44 *
45 * @param {string} text Plain text
46 * @param {string} [type] If this is a unicorn then 'unicorn', else 'text' (default)
47 */
48 function add( text, type ) {
49 if (
50 !chunks.length ||
51 chunks[ chunks.length - 1 ].elements !== elementListStack[ stackTop ] ||
52 chunks[ chunks.length - 1 ].type !== type
53 ) {
54 chunks.push( new ve.ce.TextStateChunk(
55 text,
56 elementListStack[ stackTop ],
57 type || 'text'
58 ) );
59 } else {
60 chunks[ chunks.length - 1 ].text += text;
61 }
62 }
63
64 let view;
65 const annotationStack = [];
66 let node = element;
67 while ( true ) {
68 // Process node
69 // If appropriate, step into first child and loop
70 // If no next sibling, step out until there is (breaking if we leave element)
71 // Step to next sibling and loop
72 if ( node.nodeType === Node.TEXT_NODE ) {
73 add( node.data.replace( /\u00A0/g, ' ' ) );
74 } else if (
75 // Node types that don't appear in the model
76 // TODO: what about comments?
77 node.nodeType !== Node.ELEMENT_NODE ||
78 node.classList.contains( 've-ce-branchNode-blockSlug' ) ||
79 node.classList.contains( 've-ce-cursorHolder' )
80 ) {
81 // Do nothing
82 } else if ( ( view = $( node ).data( 'view' ) ) && view instanceof ve.ce.LeafNode ) {
83 // Don't return the content, but return placeholder characters so the
84 // offsets match up.
85 // Only return placeholders for the first element in a sibling group;
86 // otherwise we'll double count this node
87 if ( node === view.$element[ 0 ] ) {
88 // \u2603 is the snowman character: ☃
89 add( '\u2603'.repeat( view.getOuterLength() ) );
90 }
91 } else if ( node.classList.contains( 've-ce-unicorn' ) ) {
92 add( '', 'unicorn' );
93 } else if ( node.firstChild ) {
94 if ( ve.ce.isAnnotationElement( node ) ) {
95 // Push a new element stack state
96 elementListStack.push( elementListStack[ stackTop ].concat( node ) );
97 annotationStack.push( node );
98 stackTop++;
99 }
100 node = node.firstChild;
101 continue;
102 }
103 // else no child nodes; do nothing
104
105 // Step out of this node, then keep stepping outwards until there is a next sibling
106 while ( true ) {
107 if ( node === element ) {
108 break;
109 }
110 if ( node === annotationStack[ annotationStack.length - 1 ] ) {
111 annotationStack.pop();
112 elementListStack.pop();
113 stackTop--;
114 }
115 if ( node.nextSibling ) {
116 break;
117 }
118 node = node.parentNode;
119 }
120 if ( node === element ) {
121 break;
122 }
123 node = node.nextSibling;
124 }
125 return chunks;
126 };
127
128 /* Methods */
129
130 /**
131 * Test whether the text state is equal to another.
132 *
133 * @param {ve.ce.TextState} other The other text state
134 * @return {boolean} Whether the states are equal
135 */
136 ve.ce.TextState.prototype.isEqual = function ( other ) {
137 if ( other === this ) {
138 return true;
139 }
140 if ( !other || this.chunks.length !== other.chunks.length ) {
141 return false;
142 }
143 for ( let i = 0, len = this.chunks.length; i < len; i++ ) {
144 if ( !( this.chunks[ i ].isEqual( other.chunks[ i ] ) ) ) {
145 return false;
146 }
147 }
148 return true;
149 };
150
151 /**
152 * Create a model transaction from a change in text state.
153 * This must be fast enough to cope with the typical typing scenario (either with or
154 * without an IME) where the contents of a single text node get modified several times
155 * per second.
156 *
157 * @param {ve.ce.TextState} prev Previous text state (must be for the same node)
158 * @param {ve.dm.Document} modelDoc The model document
159 * @param {number} modelOffset The offset of the node in the model
160 * @param {ve.dm.AnnotationSet} [unicornAnnotations] The annotations at the unicorn, if any
161 * @return {ve.dm.Transaction|null} Transaction corresponding to the text state change
162 */
163 ve.ce.TextState.prototype.getChangeTransaction = function ( prev, modelDoc, modelOffset, unicornAnnotations ) {
164 /**
165 * Calculates the size of newArray - oldArray (asymmetric difference)
166 * This is O(n^2) but the lengths should be fairly low, and this doesn't
167 * happen during typical typing.
168 *
169 * @param {Array} newArray
170 * @param {Array} oldArray
171 * @param {Function} equals Two-argument, boolean valued equivalence test
172 * @return {number} Number of elements of newArray not in oldArray
173 */
174 function countMissing( newArray, oldArray, equals ) {
175 let count = 0;
176 for ( let i = 0, iLen = newArray.length; i < iLen; i++ ) {
177 let j, jLen;
178 for ( j = 0, jLen = oldArray.length; j < jLen; j++ ) {
179 if ( equals( newArray[ i ], oldArray[ j ] ) ) {
180 break;
181 }
182 }
183 if ( j === jLen ) {
184 count++;
185 }
186 }
187 return count;
188 }
189
190 const oldChunks = prev.chunks,
191 newChunks = this.chunks,
192 modelData = modelDoc.data,
193 newData = [];
194
195 // Find first changed chunk at start/end of oldChunks/newChunks
196 const change = ve.countEdgeMatches( oldChunks, newChunks, ( a, b ) => a.isEqual( b ) );
197 if ( change === null ) {
198 // No change
199 return null;
200 }
201
202 // Count matching characters with matching annotations at start/end of the changed chunks.
203 // During typical typing, there is a single changed chunk with matching start/end chars.
204 let textStart = 0;
205 let textEnd = 0;
206 if ( change.start + change.end < Math.min( oldChunks.length, newChunks.length ) ) {
207 // Both oldChunks and newChunks include a changed chunk. Therefore the first changed
208 // chunk of oldChunks and newChunks is respectively oldChunks[ change.start ] and
209 // newChunks[ change.start ] . If they have matching annotations, then matching
210 // characters at their start are also part of the unchanged start region.
211 if ( oldChunks[ change.start ].hasEqualElements( newChunks[ change.start ] ) ) {
212 const oldChunk = oldChunks[ change.start ];
213 const newChunk = newChunks[ change.start ];
214 const iLen = Math.min( oldChunk.text.length, newChunk.text.length );
215 let i;
216 for ( i = 0; i < iLen; i++ ) {
217 if ( oldChunk.text[ i ] !== newChunk.text[ i ] ) {
218 break;
219 }
220 }
221 textStart = i;
222 }
223
224 // Likewise, the last changed chunk of oldChunks and newChunks is respectively
225 // oldChunks[ oldChunks.length - 1 - change.end ] and
226 // newChunks[ newChunks.length - 1 - change.end ] , and if they have matching
227 // annotations, then matching characters at their end potentially form part of
228 // the unchanged end region.
229 if ( oldChunks[ oldChunks.length - 1 - change.end ].hasEqualElements(
230 newChunks[ newChunks.length - 1 - change.end ]
231 ) ) {
232 const oldChunk = oldChunks[ oldChunks.length - 1 - change.end ];
233 const newChunk = newChunks[ newChunks.length - 1 - change.end ];
234 // However, if only one chunk has changed in oldChunks/newChunks, then
235 // oldChunk/newChunk is also the *first* changed chunk, in which case
236 // textStart has already eaten into that chunk; so take care not to
237 // overlap it. (For example, for 'ana'->'anna', textStart will be 2 so
238 // we want to limit textEnd to 1, else the 'n' of 'ana' will be counted
239 // twice).
240 const iLen = Math.min(
241 oldChunk.text.length -
242 ( change.start + change.end === oldChunks.length - 1 ? textStart : 0 ),
243 newChunk.text.length -
244 ( change.start + change.end === newChunks.length - 1 ? textStart : 0 )
245 );
246 let i;
247 for ( i = 0; i < iLen; i++ ) {
248 if ( newChunk.text[ newChunk.text.length - 1 - i ] !==
249 oldChunk.text[ oldChunk.text.length - 1 - i ]
250 ) {
251 break;
252 }
253 }
254 textEnd = i;
255 }
256 }
257
258 // Starting just inside the node, skip past matching chunks at the array starts
259 let changeOffset = modelOffset + 1;
260 for ( let i = 0, iLen = change.start; i < iLen; i++ ) {
261 changeOffset += oldChunks[ i ].text.length;
262 }
263
264 // Calculate range of old content to remove
265 let removed = 0;
266 for ( let i = change.start, iLen = oldChunks.length - change.end; i < iLen; i++ ) {
267 removed += oldChunks[ i ].text.length;
268 }
269 const removeRange = new ve.Range( changeOffset + textStart, changeOffset + removed - textEnd );
270
271 // Prepare new content, reusing existing ve.dm.Annotation objects where possible
272 for ( let i = change.start, iLen = newChunks.length - change.end; i < iLen; i++ ) {
273 const newChunk = newChunks[ i ];
274 if ( newChunk.type === 'unicorn' ) {
275 // Unicorns don't exist in the model
276 continue;
277 }
278 let data = newChunk.text.split( '' );
279 if ( i === change.start ) {
280 data = data.slice( textStart );
281 }
282 if ( i === iLen - 1 ) {
283 data = data.slice( 0, data.length - textEnd );
284 }
285 if ( data.length === 0 ) {
286 // There is nothing to add, because textStart/textEnd causes all the
287 // content in this chunk to be retained,
288 continue;
289 }
290
291 // Search for matching elements in old chunks adjacent to the change (i.e. removed
292 // chunks or the first chunk before/after the removal). O(n^2) is fine here
293 // because during typical typing there is only one changed chunk, and the worst
294 // case is three new chunks (e.g. when the interior of an existing chunk is
295 // annotated).
296 let annotations = null;
297 let missing = null;
298 // In the old chunks, find the chunks adjacent to the change
299 let jStart;
300 let matchStartOffset;
301 if ( change.start === 0 ) {
302 jStart = 0;
303 matchStartOffset = changeOffset;
304 } else {
305 // Include the last chunk before the change
306 jStart = change.start - 1;
307 matchStartOffset = changeOffset - oldChunks[ jStart ].text.length;
308 }
309 let jEnd;
310 if ( change.end === 0 ) {
311 jEnd = oldChunks.length;
312 } else {
313 // Include the first chunk after the change
314 jEnd = oldChunks.length - change.end + 1;
315 }
316
317 // Search for exact match first. During typical typing there is an exact
318 // match at j=1 (or j=0 if there is no previous chunk).
319 let matchOffset = matchStartOffset;
320 for ( let j = jStart; j < jEnd; j++ ) {
321 const oldChunk = oldChunks[ j ];
322 if ( !oldChunk.hasEqualElements( newChunk ) ) {
323 matchOffset += oldChunk.text.length;
324 continue;
325 }
326 if ( oldChunk.type === 'unicorn' ) {
327 if ( !unicornAnnotations ) {
328 throw new Error( 'No unicorn annotations' );
329 }
330 annotations = unicornAnnotations;
331 break;
332 }
333 annotations = modelData.getInsertionAnnotationsFromRange(
334 new ve.Range( matchOffset ),
335 true
336 );
337 break;
338 }
339 if ( annotations === null ) {
340 // No exact match: search for the old chunk whose element list covers best
341 // (choosing the startmost of any tying chunks). There may be no missing
342 // elements even though the match is not exact (e.g. because of removed
343 // annotations and reordering).
344 //
345 // This block doesn't happen during typical typing, so performance is
346 // less critical.
347 let leastMissing = newChunk.elements.length;
348 let bestOffset = null;
349 matchOffset = matchStartOffset;
350 for ( let j = jStart; j < jEnd; j++ ) {
351 const oldChunk = oldChunks[ j ];
352 missing = countMissing(
353 newChunk.elements,
354 oldChunk.elements,
355 ve.ce.TextStateChunk.static.compareElements
356 );
357 if ( missing < leastMissing ) {
358 leastMissing = missing;
359 bestOffset = matchOffset;
360 if ( missing === 0 ) {
361 break;
362 }
363 }
364 matchOffset += oldChunk.text.length;
365 }
366 let oldAnnotations;
367 if ( bestOffset === null ) {
368 oldAnnotations = new ve.dm.AnnotationSet( modelData.getStore() );
369 } else {
370 oldAnnotations = modelData.getInsertionAnnotationsFromRange(
371 new ve.Range( bestOffset ),
372 true
373 );
374 }
375 // For each element in new order, add applicable old annotation, or
376 // (if whitelisted) newly-created annotation.
377 // TODO: this can potentially duplicate existing non-adjacent
378 // annotations. Sometimes this could be required behaviour, e.g. for
379 // directionality spans; in other situations it would be cleaner to
380 // duplicate.
381 annotations = new ve.dm.AnnotationSet( modelData.getStore() );
382 for ( let j = 0, jLen = newChunk.elements.length; j < jLen; j++ ) {
383 const element = newChunk.elements[ j ];
384 // Recover the node from jQuery data store. This can only break if the browser
385 // completely rebuilds the node, but should work in cases like typing into
386 // collapsed links because nails ensure the link is never completely empty.
387 const view = $( element ).data( 'view' );
388 let ann;
389 if ( view ) {
390 ann = view.getModel();
391 } else {
392 // No view: new annotation element (or replacement one):
393 // see https://phabricator.wikimedia.org/T116269 and
394 // https://code.google.com/p/chromium/issues/detail?id=546461
395 const modelClass = ve.dm.modelRegistry.lookup(
396 ve.dm.modelRegistry.matchElement( element )
397 );
398 if ( !( modelClass && modelClass.prototype instanceof ve.dm.Annotation ) ) {
399 // Erroneous element; nothing we can do with it
400 continue;
401 }
402 ann = ve.dm.annotationFactory.createFromElement(
403 modelClass.static.toDataElement( [ element ], ve.dm.converter )
404 );
405 const oldAnn = oldAnnotations.getComparable( ann );
406 if ( oldAnn ) {
407 ann = oldAnn;
408 } else if ( !ann.constructor.static.inferFromView ) {
409 // New and un-whitelisted: drop the annotation
410 continue;
411 }
412 }
413 annotations.add( ann, annotations.getLength() );
414 }
415 }
416 ve.dm.Document.static.addAnnotationsToData( data, annotations );
417 ve.batchPush( newData, data );
418 }
419
420 return ve.dm.TransactionBuilder.static.newFromReplacement( modelDoc, removeRange, newData );
421 };