Debian Codegraph @

extensions/VisualEditor/lib/ve/src/init/ve.init.Platform.js

raw symbols SCIP
1 /*!
2 * VisualEditor Initialization Platform class.
3 *
4 * @copyright See AUTHORS.txt
5 */
6
7 /**
8 * Generic Initialization platform.
9 *
10 * @abstract
11 * @mixes OO.EventEmitter
12 *
13 * @constructor
14 */
15 ve.init.Platform = function VeInitPlatform() {
16 // Mixin constructors
17 OO.EventEmitter.call( this );
18
19 this.localStorage = this.createLocalStorage();
20 this.sessionStorage = this.createSessionStorage();
21
22 // Register
23 ve.init.platform = this;
24
25 // Provide messages to OOUI
26 OO.ui.getUserLanguages = this.getUserLanguages.bind( this );
27 OO.ui.msg = this.getMessage.bind( this );
28
29 // Notify those waiting for a platform that they can finish initialization
30 setTimeout( () => {
31 ve.init.Platform.static.deferredPlatform.resolve( ve.init.platform );
32 } );
33 };
34
35 /* Inheritance */
36
37 OO.mixinClass( ve.init.Platform, OO.EventEmitter );
38
39 /* Static Properties */
40
41 /**
42 * A jQuery.Deferred that tracks when the platform has been created.
43 *
44 * @private
45 */
46 ve.init.Platform.static.deferredPlatform = ve.createDeferred();
47
48 /**
49 * A promise that tracks when ve.init.platform is ready for use. When
50 * this promise is resolved the platform will have been created and
51 * initialized.
52 *
53 * This promise is safe to access early in VE startup before
54 * `ve.init.platform` has been set.
55 *
56 * @property {jQuery.Promise}
57 */
58 ve.init.Platform.static.initializedPromise = ve.init.Platform.static.deferredPlatform.promise().then( ( platform ) => platform.getInitializedPromise() );
59
60 /* Static Methods */
61
62 /**
63 * Get client platform string from browser.
64 *
65 * @static
66 * @inheritable
67 * @return {string} Client platform string
68 */
69 ve.init.Platform.static.getSystemPlatform = function () {
70 return $.client.profile().platform;
71 };
72
73 /**
74 * Check whether we are running in Edge.
75 *
76 * @static
77 * @inheritable
78 * @return {boolean} We are in Edge
79 */
80 ve.init.Platform.static.isEdge = function () {
81 return $.client.profile().name === 'edge';
82 };
83
84 /**
85 * Check whether we are running on iOS
86 *
87 * @static
88 * @inheritable
89 * @return {boolean} We are running on iOS
90 */
91 ve.init.Platform.static.isIos = function () {
92 return /ipad|iphone|ipod/i.test( navigator.userAgent );
93 };
94
95 /* Methods */
96
97 /**
98 * Get an anchored regular expression that matches allowed external link URLs
99 * starting at the beginning of an input string.
100 *
101 * @abstract
102 * @return {RegExp} Regular expression object
103 */
104 ve.init.Platform.prototype.getExternalLinkUrlProtocolsRegExp = null;
105
106 /**
107 * Get an unanchored regular expression that matches allowed external link URLs
108 * anywhere in an input string.
109 *
110 * @abstract
111 * @return {RegExp} Regular expression object
112 */
113 ve.init.Platform.prototype.getUnanchoredExternalLinkUrlProtocolsRegExp = null;
114
115 /**
116 * Get a regular expression that matches IDs used only for linking document
117 * data to metadata. Use null if your document format does not have such IDs.
118 *
119 * @return {RegExp|null} Regular expression object
120 */
121 ve.init.Platform.prototype.getMetadataIdRegExp = function () {
122 return null;
123 };
124
125 /**
126 * Show a read-only notification to the user.
127 *
128 * @abstract
129 * @param {jQuery|string} message
130 * @param {jQuery|string} [title]
131 */
132 ve.init.Platform.prototype.notify = null;
133
134 /**
135 * Get a platform config value
136 *
137 * @abstract
138 * @param {string|string[]} key Config key, or list of keys
139 * @return {any|Object} Config value, or keyed object of config values if list of keys provided
140 */
141 ve.init.Platform.prototype.getConfig = null;
142
143 /**
144 * Get a user config value
145 *
146 * @abstract
147 * @param {string|string[]} key Config key, or list of keys
148 * @return {any|Object} Config value, or keyed object of config values if list of keys provided
149 */
150 ve.init.Platform.prototype.getUserConfig = null;
151
152 /**
153 * Set a user config value
154 *
155 * @abstract
156 * @param {string|Object} keyOrValueMap Key to set value for, or object mapping keys to values
157 * @param {any} [value] Value to set (optional, only in use when key is a string)
158 */
159 ve.init.Platform.prototype.setUserConfig = null;
160
161 /**
162 * Create a safe storage object
163 *
164 * @abstract
165 * @return {ve.init.SafeStorage}
166 */
167 ve.init.Platform.prototype.createSafeStorage = null;
168
169 /**
170 * Create a list storage object from a safe storage object
171 *
172 * @param {ve.init.SafeStorage} safeStorage
173 * @return {ve.init.ConflictableStorage}
174 */
175 ve.init.Platform.prototype.createConflictableStorage = function ( safeStorage ) {
176 return ve.init.createConflictableStorage( safeStorage );
177 };
178
179 ve.init.Platform.prototype.createLocalStorage = function () {
180 let localStorage;
181
182 try {
183 localStorage = window.localStorage;
184 } catch ( e ) {}
185
186 return this.createConflictableStorage( this.createSafeStorage( localStorage ) );
187 };
188
189 ve.init.Platform.prototype.createSessionStorage = function () {
190 let sessionStorage;
191
192 try {
193 sessionStorage = window.sessionStorage;
194 } catch ( e ) {}
195
196 return this.createConflictableStorage( this.createSafeStorage( sessionStorage ) );
197 };
198
199 /**
200 * Add multiple messages to the localization system.
201 *
202 * @abstract
203 * @param {Object} messages Containing plain message values
204 */
205 ve.init.Platform.prototype.addMessages = null;
206
207 /**
208 * Get a message from the localization system.
209 *
210 * @abstract
211 * @param {string} key Message key
212 * @param {...any} [args] List of arguments which will be injected at $1, $2, etc. in the message
213 * @return {string} Localized message, or key or '<' + key + '>' if message not found
214 */
215 ve.init.Platform.prototype.getMessage = null;
216
217 /**
218 * Get the current user's name, if the platform supports it
219 *
220 * @return {string|null} User name, or null if not applicable
221 */
222 ve.init.Platform.prototype.getUserName = function () {
223 return null;
224 };
225
226 /**
227 * Parse a string into a number
228 *
229 * @abstract
230 * @param {string} value String to be converted
231 * @return {number} Number value, NaN if not a number
232 */
233 ve.init.Platform.prototype.parseNumber = null;
234
235 /**
236 * For a number as a string
237 *
238 * @abstract
239 * @param {number} number Number to be formatted
240 * @return {string} Formatted number
241 */
242 ve.init.Platform.prototype.formatNumber = null;
243
244 /**
245 * Get an HTML message from the localization system, with HTML or DOM arguments
246 *
247 * @abstract
248 * @param {string} key Message key
249 * @param {...any} [args] List of arguments which will be injected at $1, $2, etc. in the message
250 * @return {Node[]} Localized message, or key or '<' + key + '>' if message not found
251 */
252 ve.init.Platform.prototype.getHtmlMessage = null;
253
254 /**
255 * Add multiple parsed messages to the localization system.
256 *
257 * @abstract
258 * @param {Object} messages Map of message-key/html pairs
259 */
260 ve.init.Platform.prototype.addParsedMessages = null;
261
262 /**
263 * Get a parsed message as HTML string.
264 *
265 * Does not support $# replacements.
266 *
267 * @abstract
268 * @param {string} key Message key
269 * @return {string} Parsed localized message as HTML string
270 */
271 ve.init.Platform.prototype.getParsedMessage = null;
272
273 /**
274 * Get the user language and any fallback languages.
275 *
276 * @abstract
277 * @return {string[]} User language strings
278 */
279 ve.init.Platform.prototype.getUserLanguages = null;
280
281 /**
282 * Get a list of URL entry points where media can be found.
283 *
284 * @abstract
285 * @return {string[]} API URLs
286 */
287 ve.init.Platform.prototype.getMediaSources = null;
288
289 /**
290 * Get a list of all language codes.
291 *
292 * @abstract
293 * @return {string[]} Language codes
294 */
295 ve.init.Platform.prototype.getLanguageCodes = null;
296
297 /**
298 * Check if a language code is known to this platform.
299 *
300 * @param {string} code Language code
301 * @return {boolean} Language code is known
302 */
303 ve.init.Platform.prototype.hasLanguageCode = function ( code ) {
304 return this.getLanguageCodes().indexOf( code ) !== -1;
305 };
306
307 /**
308 * Get a language's name from its code, in the current user language if possible.
309 *
310 * @abstract
311 * @param {string} code Language code
312 * @return {string} Language name
313 */
314 ve.init.Platform.prototype.getLanguageName = null;
315
316 /**
317 * Get a language's autonym from its code.
318 *
319 * @abstract
320 * @param {string} code Language code
321 * @return {string} Language autonym
322 */
323 ve.init.Platform.prototype.getLanguageAutonym = null;
324
325 /**
326 * Get a language's direction from its code.
327 *
328 * @abstract
329 * @param {string} code Language code
330 * @return {string} Language direction
331 */
332 ve.init.Platform.prototype.getLanguageDirection = null;
333
334 /**
335 * Initialize the platform. The default implementation is to do nothing and return a resolved
336 * promise. Subclasses should override this if they have asynchronous initialization work to do.
337 * The promise rejects if the platform is incompatible.
338 *
339 * External callers should not call this. Instead, call #getInitializedPromise.
340 *
341 * @private
342 * @return {jQuery.Promise} Promise that will be resolved once initialization is done
343 */
344 ve.init.Platform.prototype.initialize = function () {
345 if ( !VisualEditorSupportCheck() ) {
346 return ve.createDeferred().reject().promise();
347 }
348 return ve.createDeferred().resolve().promise();
349 };
350
351 /**
352 * Get a promise to track when the platform has initialized. The platform won't be ready for use
353 * until this promise is resolved.
354 *
355 * Since the initialization only happens once, and the same (resolved) promise
356 * is returned when called again, and since the Platform instance is global
357 * (shared between different Target instances) it is important not to rely
358 * on this promise being asynchronous.
359 *
360 * @return {jQuery.Promise} Promise that will be resolved once the platform is ready
361 */
362 ve.init.Platform.prototype.getInitializedPromise = function () {
363 if ( !this.initialized ) {
364 this.initialized = this.initialize();
365 }
366 return this.initialized;
367 };
368
369 /**
370 * Post-process the symbol list.
371 *
372 * If a keyed object format is used, it is coverted to an array,
373 * and the label property is set from the key when required.
374 *
375 * For individual symbols, turns the `source` property into a CSS class.
376 *
377 * @param {Object|Array} symbols Symbol data
378 * @return {Object[]}
379 */
380 ve.init.Platform.prototype.processSpecialCharSymbols = function ( symbols ) {
381 let symbolList;
382 if ( Array.isArray( symbols ) ) {
383 symbolList = ve.copy( symbols );
384 } else {
385 symbolList = [];
386 Object.keys( symbols ).forEach( ( key ) => {
387 const val = symbols[ key ];
388 if ( typeof val === 'object' ) {
389 const symbolData = ve.copy( val );
390 if ( !Object.prototype.hasOwnProperty.call( symbolData, 'label' ) ) {
391 symbolData.label = key;
392 }
393 symbolList.push( symbolData );
394 } else if ( key !== val ) {
395 symbolList.push( {
396 label: key,
397 string: val
398 } );
399 } else {
400 // Plain string
401 symbolList.push( val );
402 }
403 } );
404 }
405 symbolList.forEach( ( symbol ) => {
406 if ( symbol.source ) {
407 symbol.classes = symbol.classes || [];
408 symbol.classes.push( 've-ui-specialCharacterDialog-source' );
409 }
410 } );
411 return symbolList;
412 };
413
414 /**
415 * Fetch the special character list object
416 *
417 * Returns a promise which resolves with the character list
418 *
419 * @return {jQuery.Promise}
420 */
421 ve.init.Platform.prototype.fetchSpecialCharList = function () {
422 function tryParseJSON( json ) {
423 try {
424 return JSON.parse( json );
425 } catch ( err ) {
426 // There was no character list found, or the character list message is
427 // invalid json string.
428 ve.log( 've.init.Platform: Could not parse the special character list ' + json );
429 ve.log( err.message );
430 }
431 return null;
432 }
433
434 const charsObj = {},
435 groups = [ 'accents', 'mathematical', 'symbols' ];
436
437 groups.forEach( ( group ) => {
438 // The following messages are used here:
439 // * visualeditor-specialcharacter-group-set-accents
440 // * visualeditor-specialcharacter-group-set-mathematical
441 // * visualeditor-specialcharacter-group-set-symbols
442 const symbols = tryParseJSON( ve.msg( 'visualeditor-specialcharacter-group-set-' + group ) );
443 if ( symbols ) {
444 charsObj[ group ] = {
445 // The following messages are used here:
446 // * visualeditor-specialcharacter-group-label-accents
447 // * visualeditor-specialcharacter-group-label-mathematical
448 // * visualeditor-specialcharacter-group-label-symbols
449 label: ve.msg( 'visualeditor-specialcharacter-group-label-' + group ),
450 symbols: this.processSpecialCharSymbols( symbols )
451 };
452 }
453 } );
454
455 // This implementation always resolves instantly
456 return ve.createDeferred().resolve( charsObj ).promise();
457 };
458
459 /**
460 * Decode HTML entities for insertion into the document
461 *
462 * @method
463 * @param {string} html HTML string
464 * @return {string}
465 */
466 ve.init.Platform.prototype.decodeEntities = ve.safeDecodeEntities;