Debian Codegraph @

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

raw symbols SCIP
1 /*!
2 * VisualEditor ContentEditable Document class.
3 *
4 * @copyright See AUTHORS.txt
5 */
6
7 /**
8 * ContentEditable document.
9 *
10 * @class
11 * @extends ve.Document
12 *
13 * @constructor
14 * @param {ve.dm.Document} model Model to observe
15 * @param {ve.ce.Surface} surface Surface document is part of
16 */
17 ve.ce.Document = function VeCeDocument( model, surface ) {
18 // Parent constructor
19 ve.ce.Document.super.call( this, new ve.ce.DocumentNode( model.getDocumentNode(), surface ) );
20
21 this.lang = null;
22 this.dir = null;
23
24 this.setLang( model.getLang() );
25 this.setDir( model.getDir() );
26
27 // Properties
28 this.model = model;
29 };
30
31 /* Inheritance */
32
33 OO.inheritClass( ve.ce.Document, ve.Document );
34
35 /* Events */
36
37 /**
38 * Language or direction changed
39 *
40 * @event ve.ce.Document#langChange
41 */
42
43 /* Methods */
44
45 /**
46 * Set the document view language
47 *
48 * @param {string} lang Language code
49 */
50 ve.ce.Document.prototype.setLang = function ( lang ) {
51 this.getDocumentNode().$element.prop( 'lang', lang );
52 this.lang = lang;
53 this.emit( 'langChange' );
54 };
55
56 /**
57 * Set the document view directionality
58 *
59 * @param {string} dir Directionality (ltr/rtl)
60 */
61 ve.ce.Document.prototype.setDir = function ( dir ) {
62 this.getDocumentNode().$element.prop( 'dir', dir );
63 this.dir = dir;
64 this.emit( 'langChange' );
65 };
66
67 /**
68 * Get the document view language
69 *
70 * @return {string} Language code
71 */
72 ve.ce.Document.prototype.getLang = function () {
73 return this.lang;
74 };
75
76 /**
77 * Get the document view directionality
78 *
79 * @return {string} Directionality (ltr/rtl)
80 */
81 ve.ce.Document.prototype.getDir = function () {
82 return this.dir;
83 };
84
85 /**
86 * Get a slug at an offset.
87 *
88 * @param {number} offset Offset to get slug at
89 * @return {HTMLElement} Slug at offset
90 */
91 ve.ce.Document.prototype.getSlugAtOffset = function ( offset ) {
92 const node = this.getBranchNodeFromOffset( offset );
93 return node ? node.getSlugAtOffset( offset ) : null;
94 };
95
96 /**
97 * Calculate the DOM position corresponding to a DM offset
98 *
99 * If there are multiple DOM locations, heuristically pick the best one for cursor placement
100 *
101 * @private
102 * @param {number} offset Linear model offset
103 * @return {ve.ce.NodeAndOffset} Position
104 * @throws {Error} Offset could not be translated to a DOM element and offset
105 */
106 ve.ce.Document.prototype.getNodeAndOffset = function ( offset ) {
107 const countedNodes = [];
108
109 // 1. Step with ve.adjacentDomPosition( …, { stop: function () { return true; } } )
110 // until we hit a position at the correct offset (which is guaranteed to be the first
111 // such position in document order).
112 // 2. Use ve.adjacentDomPosition( …, { stop: … } ) once to return all
113 // subsequent positions at the same offset.
114 // 3. Look at the possible positions and pick as follows:
115 // - If there is a unicorn, return just inside it
116 // - Else if there is a nail, return just outside it
117 // - Else if there is a text node, return an offset in it
118 // - Else return the first matching offset
119 //
120 // Offsets of DOM nodes are counted to match their model equivalents.
121 //
122 // TODO: take the following into account:
123 // Unfortunately, there is no way to avoid slugless block nodes with no DM length: an
124 // IME can remove all the text from a node at a time when it is unsafe to fixup the node
125 // contents. In this case, a maximally deep element gives better bounding rectangle
126 // coordinates than any of its containers.
127
128 if ( !this.model.getDocumentRange().containsRange( new ve.Range( offset ) ) ) {
129 throw new Error( 'Offset is out of bounds' );
130 }
131 const branchNode = this.getBranchNodeFromOffset( offset );
132 let count = branchNode.getOffset() + ( branchNode.isWrapped() ? 1 : 0 );
133
134 let node;
135 if ( !( branchNode instanceof ve.ce.ContentBranchNode ) ) {
136 // The cursor does not lie in a ContentBranchNode, so we can determine
137 // everything from the DM tree
138 let i, ceChild;
139 for ( i = 0; ; i++ ) {
140 ceChild = branchNode.children[ i ];
141 if ( count === offset ) {
142 break;
143 }
144 if ( !ceChild ) {
145 throw new Error( 'Offset lies beyond branchNode' );
146 }
147 count += ceChild.getOuterLength();
148 if ( count > offset ) {
149 if ( ceChild.getOuterLength() !== 2 ) {
150 throw new Error( 'Offset lies inside child of strange size' );
151 }
152 node = ceChild.$element[ 0 ];
153 if ( node ) {
154 return { node: node, offset: 0 };
155 }
156 // Else ceChild has no DOM representation; step forwards
157 break;
158 }
159 }
160 // Offset lies directly in branchNode, just before ceChild
161 node = branchNode.$element[ 0 ];
162 while ( ceChild && !ceChild.$element[ 0 ] ) {
163 // Node does not have a DOM representation; move forwards past it
164 i++;
165 ceChild = branchNode.children[ i ];
166 }
167 if ( !ceChild || !ceChild.$element[ 0 ] ) {
168 // Offset lies just at the end of branchNode
169 return { node: node, offset: node.childNodes.length };
170 }
171 return {
172 node: node,
173 offset: Array.prototype.indexOf.call(
174 node.childNodes,
175 ceChild.$element[ 0 ]
176 )
177 };
178 }
179
180 // Else the cursor lies in a ContentBranchNode, so we must traverse the DOM, keeping
181 // count of the corresponding DM position until it reaches offset.
182 let position = { node: branchNode.$element[ 0 ], offset: 0 };
183
184 function noDescend() {
185 return this.classList.contains( 've-ce-branchNode-blockSlug' ) ||
186 ve.rejectsCursor( this );
187 }
188
189 while ( true ) {
190 if ( count === offset ) {
191 break;
192 }
193 position = ve.adjacentDomPosition(
194 position,
195 1,
196 {
197 noDescend: noDescend,
198 stop: function () {
199 return true;
200 }
201 }
202 );
203 const step = position.steps[ 0 ];
204 node = step.node;
205 if ( node.nodeType === Node.TEXT_NODE ) {
206 if ( step.type === 'leave' ) {
207 // Skip without incrementing
208 continue;
209 }
210 // else the code below always breaks or skips over the text node;
211 // therefore it is guaranteed that step.type === 'enter' (we just
212 // stepped in)
213 // TODO: what about zero-length text nodes?
214 if ( offset <= count + node.data.length ) {
215 // Match the appropriate offset in the text node
216 position = { node: node, offset: offset - count };
217 break;
218 } else {
219 // Skip over the text node
220 count += node.data.length;
221 position = { node: node, offset: node.data.length };
222 continue;
223 }
224 } // else it is an element node (TODO: handle comment etc)
225
226 if ( !(
227 node.classList.contains( 've-ce-branchNode' ) ||
228 node.classList.contains( 've-ce-leafNode' )
229 ) ) {
230 // Nodes like b, inline slug, browser-generated br that doesn't have
231 // class ve-ce-leafNode: continue walk without incrementing
232 continue;
233 }
234
235 if ( step.type === 'leave' ) {
236 // Below we'll guarantee that .ve-ce-branchNode/.ve-ce-leafNode elements
237 // are only entered if their open/close tags take up a model offset, so
238 // we can increment unconditionally here
239 count++;
240 continue;
241 } // else step.type === 'enter' || step.type === 'cross'
242
243 const model = $.data( node, 'view' ).model;
244
245 if ( countedNodes.indexOf( model ) !== -1 ) {
246 // This DM node is rendered as multiple DOM elements, and we have already
247 // counted it as part of an earlier element. Skip past without incrementing
248 position = { node: node.parentNode, offset: ve.parentIndex( node ) + 1 };
249 continue;
250 }
251 countedNodes.push( model );
252 if ( offset >= count + model.getOuterLength() ) {
253 // Offset doesn't lie inside the node. Skip past and count length
254 // skip past the whole node
255 position = { node: node.parentNode, offset: ve.parentIndex( node ) + 1 };
256 count += model.getOuterLength();
257 } else if ( step.type === 'cross' ) {
258 if ( offset === count + 1 ) {
259 // The offset lies inside the crossed node
260 position = { node: node, offset: 0 };
261 break;
262 }
263 count += 2;
264 } else {
265 count += 1;
266 }
267 }
268 // Now "position" is the first DOM position (in document order) at the correct
269 // model offset.
270
271 // If the position is exactly after the first of multiple view nodes sharing a model,
272 // then jump to the position exactly after the final such view node.
273 const prevNode = position.node.childNodes[ position.offset - 1 ];
274 if ( prevNode && prevNode.nodeType === Node.ELEMENT_NODE && (
275 prevNode.classList.contains( 've-ce-branchNode' ) ||
276 prevNode.classList.contains( 've-ce-leafNode' )
277 ) ) {
278 const $viewNodes = $.data( prevNode, 'view' ).$element;
279 if ( $viewNodes.length > 1 ) {
280 position.node = $viewNodes.get( -1 ).parentNode;
281 position.offset = 1 + ve.parentIndex( $viewNodes.get( -1 ) );
282 }
283 }
284
285 // Find all subsequent DOM positions at the same model offset
286 const found = {};
287 function stop( s ) {
288 let m;
289 if ( s.node.nodeType === Node.TEXT_NODE ) {
290 return s.type === 'internal';
291 }
292
293 if (
294 s.node.classList.contains( 've-ce-branchNode' ) ||
295 s.node.classList.contains( 've-ce-leafNode' )
296 ) {
297 m = $.data( s.node, 'view' ).model;
298 if ( countedNodes.indexOf( m ) !== -1 ) {
299 return false;
300 }
301 countedNodes.push( m );
302 return true;
303 }
304 return false;
305 }
306 const steps = ve.adjacentDomPosition( position, 1, { stop: stop, noDescend: noDescend } ).steps;
307 steps.slice( 0, -1 ).forEach( ( s ) => {
308 // Step type cannot be "internal", else the offset would have incremented
309 const hasClass = function ( className ) {
310 return s.node.nodeType === Node.ELEMENT_NODE &&
311 s.node.classList.contains( className );
312 };
313 found.preUnicorn = found.preUnicorn || ( hasClass( 've-ce-pre-unicorn' ) && s );
314 found.postUnicorn = found.postUnicorn || ( hasClass( 've-ce-post-unicorn' ) && s );
315 found.preOpenNail = found.preOpenNail || ( hasClass( 've-ce-nail-pre-open' ) && s );
316 found.postOpenNail = found.postOpenNail || ( hasClass( 've-ce-nail-post-open' ) && s );
317 found.preCloseNail = found.preCloseNail || ( hasClass( 've-ce-nail-pre-close' ) && s );
318 found.postCloseNail = found.postCloseNail || ( hasClass( 've-ce-nail-post-close' ) && s );
319 found.focusableNode = found.focusableNode || ( hasClass( 've-ce-focusableNode' ) && s );
320 found.text = found.text || ( s.node.nodeType === Node.TEXT_NODE && s );
321 } );
322
323 // If there is a unicorn, it should be a unique pre/post-Unicorn pair containing text or
324 // nothing return the position just inside.
325 if ( found.preUnicorn ) {
326 return ve.ce.nextCursorOffset( found.preUnicorn.node );
327 }
328 if ( found.postUnicorn ) {
329 return ve.ce.previousCursorOffset( found.postUnicorn.node );
330 }
331
332 if ( found.preOpenNail ) {
333 // This will also cover the case where there is a post-open nail, as there will
334 // be no offset difference between them
335 return ve.ce.previousCursorOffset( found.preOpenNail.node );
336 }
337 if ( found.postCloseNail ) {
338 // This will also cover the case where there is a pre-close nail, as there will
339 // be no offset difference between them
340 return ve.ce.nextCursorOffset( found.postCloseNail.node );
341 }
342 if ( found.text ) {
343 if ( position.node.nodeType === Node.TEXT_NODE ) {
344 return position;
345 }
346 // We must either have entered or left the text node
347 return { node: found.text.node, offset: 0 };
348 }
349 return position;
350 };
351
352 /**
353 * Get the block directionality of some range
354 *
355 * Uses the computed CSS direction value of the current node
356 *
357 * @param {ve.Range} range
358 * @return {string} 'rtl', 'ltr'
359 */
360 ve.ce.Document.prototype.getDirectionalityFromRange = function ( range ) {
361 const selectedNodes = this.selectNodes( range, 'covered' );
362
363 let effectiveNode;
364 if ( selectedNodes.length > 1 ) {
365 // Selection of multiple nodes
366 // Get the common parent node
367 effectiveNode = this.selectNodes( range, 'siblings' )[ 0 ].node.getParent();
368 } else {
369 // Selection of a single node
370 effectiveNode = selectedNodes[ 0 ].node;
371
372 while ( effectiveNode.isContent() ) {
373 // This means that we're in a leaf node, like TextNode
374 // those don't read the directionality properly, we will
375 // have to climb up the parentage chain until we find a
376 // wrapping node like paragraph or list item, etc.
377 effectiveNode = effectiveNode.parent;
378 }
379 }
380
381 return effectiveNode.$element.css( 'direction' );
382 };