Debian Codegraph @

extensions/VisualEditor/lib/ve/src/ve.utils.client.js

raw symbols SCIP
1 /*!
2 * VisualEditor client (browser) specific utilities that interact with a rendered DOM.
3 *
4 * @copyright See AUTHORS.txt
5 */
6
7 /**
8 * @method
9 * @see OO.ui.Element#scrollIntoView
10 */
11 ve.scrollIntoView = OO.ui.Element.static.scrollIntoView.bind( OO.ui.Element.static );
12
13 /**
14 * Select the contents of an element
15 *
16 * @param {HTMLElement} element
17 */
18 ve.selectElement = function ( element ) {
19 const win = OO.ui.Element.static.getWindow( element ),
20 nativeRange = win.document.createRange(),
21 nativeSelection = win.getSelection();
22 nativeRange.setStart( element, 0 );
23 nativeRange.setEnd( element, element.childNodes.length );
24 nativeSelection.removeAllRanges();
25 nativeSelection.addRange( nativeRange );
26 };
27
28 /**
29 * Feature detect if the browser supports extending selections
30 *
31 * Should work everywhere except IE
32 *
33 * @private
34 * @property {boolean}
35 */
36 ve.supportsSelectionExtend = !!window.getSelection().extend;
37
38 /**
39 * Translate rect by some fixed vector and return a new offset object
40 *
41 * @param {Object} rect Offset object containing all or any of top, left, bottom, right, width & height
42 * @param {number} x Horizontal translation
43 * @param {number} y Vertical translation
44 * @return {Object} Translated rect
45 */
46 ve.translateRect = function ( rect, x, y ) {
47 const translatedRect = {};
48 if ( rect.top !== undefined ) {
49 translatedRect.top = rect.top + y;
50 }
51 if ( rect.bottom !== undefined ) {
52 translatedRect.bottom = rect.bottom + y;
53 }
54 if ( rect.left !== undefined ) {
55 translatedRect.left = rect.left + x;
56 }
57 if ( rect.right !== undefined ) {
58 translatedRect.right = rect.right + x;
59 }
60 if ( rect.width !== undefined ) {
61 translatedRect.width = rect.width;
62 }
63 if ( rect.height !== undefined ) {
64 translatedRect.height = rect.height;
65 }
66 return translatedRect;
67 };
68
69 /**
70 * Get the start and end rectangles (in a text flow sense) from a list of rectangles
71 *
72 * The start rectangle is the top-most, and the end rectangle is the bottom-most.
73 *
74 * @param {Object[]|null} rects Full list of rectangles
75 * @return {Object.<string,Object>|null} Object containing two rectangles: start and end, or null if there are no rectangles
76 */
77 ve.getStartAndEndRects = function ( rects ) {
78 if ( !rects || !rects.length ) {
79 return null;
80 }
81 let startRect, endRect;
82 for ( let i = 0, l = rects.length; i < l; i++ ) {
83 if ( !startRect || rects[ i ].top < startRect.top ) {
84 // Use ve.extendObject as ve.copy copies non-plain objects by reference
85 startRect = ve.extendObject( {}, rects[ i ] );
86 } else if ( rects[ i ].top === startRect.top ) {
87 // Merge rects with the same top coordinate
88 startRect.left = Math.min( startRect.left, rects[ i ].left );
89 startRect.right = Math.max( startRect.right, rects[ i ].right );
90 startRect.width = startRect.right - startRect.left;
91 }
92 if ( !endRect || rects[ i ].bottom > endRect.bottom ) {
93 // Use ve.extendObject as ve.copy copies non-plain objects by reference
94 endRect = ve.extendObject( {}, rects[ i ] );
95 } else if ( rects[ i ].bottom === endRect.bottom ) {
96 // Merge rects with the same bottom coordinate
97 endRect.left = Math.min( endRect.left, rects[ i ].left );
98 endRect.right = Math.max( endRect.right, rects[ i ].right );
99 endRect.width = startRect.right - startRect.left;
100 }
101 }
102 return {
103 start: startRect,
104 end: endRect
105 };
106 };
107
108 /**
109 * Minimize a set of rectangles by discarding ones which are contained by others
110 *
111 * @param {Object[]} rects Full list of rectangles
112 * @param {number} [allowedErrorOffset=3] Allowed error offset, the pixel error amount
113 * used in coordinate comparisons.
114 * @return {Object[]} Minimized list of rectangles
115 */
116 ve.minimizeRects = function ( rects, allowedErrorOffset ) {
117 if ( allowedErrorOffset === undefined ) {
118 allowedErrorOffset = 3;
119 }
120
121 // Check if rect1 contains rect2
122 function contains( rect1, rect2 ) {
123 return rect2.left >= rect1.left - allowedErrorOffset &&
124 rect2.top >= rect1.top - allowedErrorOffset &&
125 rect2.right <= rect1.right + allowedErrorOffset &&
126 rect2.bottom <= rect1.bottom + allowedErrorOffset;
127 }
128
129 function merge( rect1, rect2 ) {
130 const rect = {
131 top: Math.min( rect1.top, rect2.top ),
132 left: Math.min( rect1.left, rect2.left ),
133 bottom: Math.max( rect1.bottom, rect2.bottom ),
134 right: Math.max( rect1.right, rect2.right )
135 };
136 rect.width = rect.right - rect.left;
137 rect.height = rect.bottom - rect.top;
138 return rect;
139 }
140
141 function isApprox( a, b ) {
142 return Math.abs( a - b ) < allowedErrorOffset;
143 }
144
145 const minimalRects = [];
146 rects.forEach( ( rect ) => {
147 let keep = true;
148 for ( let i = 0, il = minimalRects.length; i < il; i++ ) {
149 // This rect is contained by an existing rect, discard
150 if ( contains( minimalRects[ i ], rect ) ) {
151 keep = false;
152 break;
153 }
154 // An existing rect is contained by this rect, discard the existing rect
155 if ( contains( rect, minimalRects[ i ] ) ) {
156 minimalRects.splice( i, 1 );
157 i--;
158 il--;
159 break;
160 }
161 // Rect is horizontally adjacent to an existing rect, merge
162 if (
163 isApprox( rect.top, minimalRects[ i ].top ) && isApprox( rect.bottom, minimalRects[ i ].bottom ) && (
164 isApprox( rect.left, minimalRects[ i ].right ) || isApprox( rect.right, minimalRects[ i ].left )
165 )
166 ) {
167 keep = false;
168 minimalRects[ i ] = merge( minimalRects[ i ], rect );
169 break;
170 }
171 // Rect is vertically adjacent to an existing rect, merge
172 if (
173 isApprox( rect.left, minimalRects[ i ].left ) && isApprox( rect.right, minimalRects[ i ].right ) && (
174 isApprox( rect.top, minimalRects[ i ].bottom ) || isApprox( rect.bottom, minimalRects[ i ].top )
175 )
176 ) {
177 keep = false;
178 minimalRects[ i ] = merge( minimalRects[ i ], rect );
179 break;
180 }
181 // TODO: Consider case where a rect bridges two existing minimalRects, and so requires two
182 // merges in one step. As rects are usually returned in order, this is unlikely to happen.
183 }
184 if ( keep ) {
185 minimalRects.push( rect );
186 }
187 } );
188
189 return minimalRects;
190 };
191
192 /**
193 * Get the client platform string from the browser.
194 *
195 * FIXME T126036: This is a wrapper for calling getSystemPlatform() on the current
196 * platform except that if the platform hasn't been constructed yet, it falls back
197 * to using the base class implementation in {ve.init.Platform}. A proper solution
198 * would be not to need this information before the platform is constructed.
199 *
200 * @see ve.init.Platform#getSystemPlatform
201 * @return {string} Client platform string
202 */
203 ve.getSystemPlatform = function () {
204 return ( ve.init.platform && ve.init.platform.constructor || ve.init.Platform ).static.getSystemPlatform();
205 };
206
207 /**
208 * Check whether a jQuery event represents a plain left click, without any modifiers
209 *
210 * @param {jQuery.Event} e
211 * @return {boolean} Whether it was an unmodified left click
212 */
213 ve.isUnmodifiedLeftClick = function ( e ) {
214 return e && e.which && e.which === OO.ui.MouseButtons.LEFT && !( e.shiftKey || e.altKey || e.ctrlKey || e.metaKey );
215 };
216
217 /**
218 * Are multiple formats for clipboardData items supported?
219 *
220 * If you want to use unknown formats, an additional check for whether we're
221 * on MS Edge needs to be made, as that only supports standard plain text / HTML.
222 *
223 * @param {jQuery.Event} e A jQuery event object for a copy/paste event
224 * @param {boolean} [customTypes] Check whether non-standard formats are supported
225 * @return {boolean} Whether multiple clipboardData item formats are supported
226 */
227 ve.isClipboardDataFormatsSupported = function ( e, customTypes ) {
228 const cacheKey = customTypes ? 'cachedCustom' : 'cached';
229
230 if ( ve.isClipboardDataFormatsSupported[ cacheKey ] === undefined ) {
231 const profile = $.client.profile();
232 const clipboardData = e.originalEvent.clipboardData || e.originalEvent.dataTransfer;
233 ve.isClipboardDataFormatsSupported[ cacheKey ] = !!(
234 clipboardData &&
235 ( !customTypes || profile.name !== 'edge' ) && (
236 // Support: Chrome
237 clipboardData.items ||
238 // Support: Firefox >= 48
239 // (but not Firefox Android, which has name='android' and doesn't support this feature)
240 ( profile.name === 'firefox' && profile.versionNumber >= 48 )
241 )
242 );
243 }
244
245 return ve.isClipboardDataFormatsSupported[ cacheKey ];
246 };
247
248 /**
249 * Workaround for catastrophic Firefox bug (T209646)
250 *
251 * Support: Firefox <= ~70
252 * anchorNode and focusNode return unusable 'Restricted' object
253 * when focus is in a number input:
254 * https://bugzilla.mozilla.org/show_bug.cgi?id=1495482
255 * This task was resolved around late 2019
256 *
257 * @param {Selection} selection Native selection
258 */
259 ve.fixSelectionNodes = function ( selection ) {
260 const profile = $.client.profile();
261
262 if ( profile.layout !== 'gecko' ) {
263 return;
264 }
265
266 function fixNodeProperty( prop ) {
267 Object.defineProperty( selection, prop, {
268 get: function () {
269 const node = Object.getOwnPropertyDescriptor( Selection.prototype, prop ).get.call( this );
270 try {
271 // Try to read a property out of node if it not null
272 // Throws an exception in FF
273 // eslint-disable-next-line no-unused-expressions
274 node && node.prop;
275 } catch ( e ) {
276 // When an input is focused, the selection becomes the input itself,
277 // so the anchor/focusNode is the input's parent.
278 // Fall back to null if that doesn't exist.
279 ve.log( 'Worked around Firefox bug with getSelection().anchorNode/focusNode. See https://phabricator.wikimedia.org/T209646.' );
280 return ( document.activeElement && document.activeElement.parentNode ) || null;
281 }
282 return node;
283 }
284 } );
285 }
286
287 if ( !Object.getOwnPropertyDescriptor( selection, 'anchorNode' ) ) {
288 fixNodeProperty( 'anchorNode' );
289 fixNodeProperty( 'focusNode' );
290 }
291 };
292
293 /**
294 * Safely decode HTML entities
295 *
296 * @param {string} html Text with HTML entities
297 * @return {string} Text with HTML entities decoded
298 */
299 ve.safeDecodeEntities = function ( html ) {
300 // Decode HTML entities, safely (no elements permitted inside textarea)
301 const textarea = document.createElement( 'textarea' );
302 textarea.innerHTML = html;
303 return textarea.textContent;
304 };