Debian Codegraph @

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

raw symbols SCIP
1 /*!
2 * VisualEditor Standalone Initialization Platform class.
3 *
4 * @copyright See AUTHORS.txt
5 */
6
7 /**
8 * Initialization Standalone platform.
9 *
10 * @example
11 * var platform = new ve.init.sa.Platform( ve.messagePaths );
12 * platform.initialize().done( () => {
13 * $( document.body ).append( $( '<p>' ).text(
14 * platform.getMessage( 'visualeditor' )
15 * ) );
16 * } );
17 *
18 * @class
19 * @extends ve.init.Platform
20 *
21 * @constructor
22 * @param {string[]} [messagePaths] Message folder paths
23 */
24 ve.init.sa.Platform = function VeInitSaPlatform( messagePaths ) {
25 // Parent constructor
26 ve.init.Platform.call( this );
27
28 // Properties
29 this.externalLinkUrlProtocolsRegExp = /^https?:\/\//i;
30 this.unanchoredExternalLinkUrlProtocolsRegExp = /https?:\/\//i;
31 this.messagePaths = messagePaths || [];
32 this.parsedMessages = {};
33 this.userLanguages = [ 'en' ];
34 };
35
36 /* Inheritance */
37
38 OO.inheritClass( ve.init.sa.Platform, ve.init.Platform );
39
40 /* Methods */
41
42 /** @inheritdoc */
43 ve.init.sa.Platform.prototype.getExternalLinkUrlProtocolsRegExp = function () {
44 return this.externalLinkUrlProtocolsRegExp;
45 };
46
47 /** @inheritdoc */
48 ve.init.sa.Platform.prototype.getUnanchoredExternalLinkUrlProtocolsRegExp = function () {
49 return this.unanchoredExternalLinkUrlProtocolsRegExp;
50 };
51
52 /** @inheritdoc */
53 ve.init.sa.Platform.prototype.notify = function ( message, title ) {
54 const $notification = $( '<div>' ).addClass( 've-init-notification' );
55
56 if ( title ) {
57 $notification.append(
58 // Never appends strings directly
59 // eslint-disable-next-line no-jquery/no-append-html
60 $( '<div>' ).addClass( 've-init-notification-title' ).append(
61 typeof title === 'string' ? document.createTextNode( title ) : title
62 )
63 );
64 }
65 $notification.append(
66 // Never appends strings directly
67 // eslint-disable-next-line no-jquery/no-append-html
68 $( '<div>' ).addClass( 've-init-notification-message' ).append(
69 typeof message === 'string' ? document.createTextNode( message ) : message
70 )
71 );
72
73 const $notificationWrapper = $( '<div>' ).addClass( 've-init-notification-wrapper' );
74 $notificationWrapper.append( $notification );
75
76 if ( !this.$notifications ) {
77 this.$notifications = $( '<div>' ).addClass( 've-init-notifications' );
78 $( document.body ).append( this.$notifications );
79 }
80
81 let closeId;
82
83 function remove() {
84 $notificationWrapper.remove();
85 }
86 function collapse() {
87 $notificationWrapper.addClass( 've-init-notification-collapse' );
88 $notificationWrapper.one( 'transitionend', remove );
89 }
90 function close() {
91 clearTimeout( closeId );
92 $notificationWrapper.removeClass( 've-init-notification-open' );
93 $notificationWrapper.css( 'height', $notificationWrapper[ 0 ].clientHeight );
94 $notificationWrapper.one( 'transitionend', collapse );
95 }
96 function open() {
97 $notificationWrapper.addClass( 've-init-notification-open' );
98 closeId = setTimeout( close, 5000 );
99 }
100
101 requestAnimationFrame( open );
102
103 $notification.on( 'click', close );
104
105 this.$notifications.append( $notificationWrapper );
106 };
107
108 /**
109 * Get message folder paths
110 *
111 * @return {string[]} Message folder paths
112 */
113 ve.init.sa.Platform.prototype.getMessagePaths = function () {
114 return this.messagePaths;
115 };
116
117 /** @inheritdoc */
118 ve.init.sa.Platform.prototype.addMessages = function ( messages ) {
119 $.i18n().load( messages, $.i18n().locale );
120 };
121
122 /**
123 * @method
124 * @inheritdoc
125 */
126 ve.init.sa.Platform.prototype.getMessage = $.i18n;
127
128 /**
129 * @method
130 * @inheritdoc
131 */
132 ve.init.sa.Platform.prototype.parseNumber = function ( value ) {
133 // TODO: Support separated numbers such as (en)123,456.78 or (fr)123.456,78
134 return parseFloat( value );
135 };
136
137 /**
138 * @method
139 * @inheritdoc
140 */
141 ve.init.sa.Platform.prototype.formatNumber = function ( number ) {
142 return number.toLocaleString();
143 };
144
145 /**
146 * @inheritdoc
147 */
148 ve.init.sa.Platform.prototype.getHtmlMessage = function ( key ) {
149 const args = arguments,
150 message = this.getMessage( key );
151 let $message = $( [] ),
152 lastOffset = 0;
153 message.replace( /\$[0-9]+/g, ( placeholder, offset ) => {
154 $message = $message.add( ve.sanitizeHtml( message.slice( lastOffset, offset ) ) );
155 const placeholderIndex = +( placeholder.slice( 1 ) );
156 const arg = args[ placeholderIndex ];
157 $message = $message.add(
158 typeof arg === 'string' ?
159 // Arguments come from the code so shouldn't be sanitized
160 document.createTextNode( arg ) :
161 arg
162 );
163 lastOffset = offset + placeholder.length;
164 } );
165 $message = $message.add( ve.sanitizeHtml( message.slice( lastOffset ) ) );
166 return $message.toArray();
167 };
168
169 /**
170 * @inheritdoc
171 */
172 ve.init.sa.Platform.prototype.getConfig = function () {
173 /* Standalone has no config yet */
174 return null;
175 };
176
177 /**
178 * @inheritdoc
179 */
180 ve.init.sa.Platform.prototype.getUserConfig = function ( keys ) {
181 if ( Array.isArray( keys ) ) {
182 const values = {};
183 for ( let i = 0, l = keys.length; i < l; i++ ) {
184 values[ keys[ i ] ] = this.getUserConfig( keys[ i ] );
185 }
186 return values;
187 } else {
188 try {
189 return JSON.parse( localStorage.getItem( 've-' + keys ) );
190 } catch ( e ) {
191 return null;
192 }
193 }
194 };
195
196 /**
197 * @inheritdoc
198 */
199 ve.init.sa.Platform.prototype.setUserConfig = function ( keyOrValueMap, value ) {
200 if ( typeof keyOrValueMap === 'object' ) {
201 for ( const i in keyOrValueMap ) {
202 if ( Object.prototype.hasOwnProperty.call( keyOrValueMap, i ) ) {
203 if ( !this.setUserConfig( i, keyOrValueMap[ i ] ) ) {
204 // localStorage will fail if the quota is full, so further
205 // sets won't work anyway.
206 return false;
207 }
208 }
209 }
210 } else {
211 try {
212 localStorage.setItem( 've-' + keyOrValueMap, JSON.stringify( value ) );
213 } catch ( e ) {
214 return false;
215 }
216 }
217 return true;
218 };
219
220 ve.init.sa.Platform.prototype.createSafeStorage = function ( storage ) {
221 return new ve.init.sa.SafeStorage( storage );
222 };
223
224 /**
225 * @inheritdoc
226 */
227 ve.init.sa.Platform.prototype.addParsedMessages = function ( messages ) {
228 for ( const key in messages ) {
229 this.parsedMessages[ key ] = messages[ key ];
230 }
231 };
232
233 /**
234 * @inheritdoc
235 */
236 ve.init.sa.Platform.prototype.getParsedMessage = function ( key ) {
237 if ( Object.prototype.hasOwnProperty.call( this.parsedMessages, key ) ) {
238 return this.parsedMessages[ key ];
239 }
240 // Fallback to regular messages, html escaping applied.
241 return this.getMessage( key ).replace( /['"<>&]/g, ( char ) => ( {
242 '\'': '&#039;',
243 '"': '&quot;',
244 '<': '&lt;',
245 '>': '&gt;',
246 '&': '&amp;'
247 }[ char ] ) );
248 };
249
250 /**
251 * @inheritdoc
252 */
253 ve.init.sa.Platform.prototype.getLanguageCodes = function () {
254 return Object.keys( $.uls.data.getAutonyms() );
255 };
256
257 /**
258 * @method
259 * @inheritdoc
260 */
261 ve.init.sa.Platform.prototype.getLanguageName = $.uls.data.getAutonym;
262
263 /**
264 * @method
265 * @inheritdoc
266 */
267 ve.init.sa.Platform.prototype.getLanguageAutonym = $.uls.data.getAutonym;
268
269 /**
270 * @method
271 * @inheritdoc
272 */
273 ve.init.sa.Platform.prototype.getLanguageDirection = $.uls.data.getDir;
274
275 /**
276 * @inheritdoc
277 */
278 ve.init.sa.Platform.prototype.getUserLanguages = function () {
279 return this.userLanguages;
280 };
281
282 /**
283 * @inheritdoc
284 */
285 ve.init.sa.Platform.prototype.initialize = function () {
286 const messagePaths = this.getMessagePaths(),
287 locale = $.i18n().locale,
288 languages = [ locale, 'en' ], // Always use 'en' as the final fallback
289 languagesCovered = {},
290 promises = [];
291 let fallbacks = $.i18n.fallbacks[ locale ];
292
293 if ( !VisualEditorSupportCheck() ) {
294 return ve.createDeferred().reject().promise();
295 }
296
297 if ( !fallbacks ) {
298 // Try to find something that has fallbacks (which means it's a language we know about)
299 // by stripping things from the end. But collect all the intermediate ones in case we
300 // go past languages that don't have fallbacks but do exist.
301 const localeParts = locale.split( '-' );
302 localeParts.pop();
303 while ( localeParts.length && !fallbacks ) {
304 const partialLocale = localeParts.join( '-' );
305 languages.push( partialLocale );
306 fallbacks = $.i18n.fallbacks[ partialLocale ];
307 localeParts.pop();
308 }
309 }
310
311 if ( fallbacks ) {
312 languages.push( ...fallbacks );
313 }
314
315 this.userLanguages = languages;
316
317 for ( let i = 0, iLen = languages.length; i < iLen; i++ ) {
318 if ( languagesCovered[ languages[ i ] ] ) {
319 continue;
320 }
321 languagesCovered[ languages[ i ] ] = true;
322
323 // Lower-case the language code for the filename. jQuery.i18n does not case-fold
324 // language codes, so we should not case-fold the second argument in #load.
325 const filename = languages[ i ].toLowerCase() + '.json';
326
327 for ( let j = 0, jLen = messagePaths.length; j < jLen; j++ ) {
328 const deferred = ve.createDeferred();
329 $.i18n().load( messagePaths[ j ] + filename, languages[ i ] )
330 .always( deferred.resolve );
331 promises.push( deferred.promise() );
332 }
333 }
334 return ve.promiseAll( promises );
335 };