Debian Codegraph @

resources/src/mediawiki.DateFormatter/DateFormatter.js

raw symbols SCIP
1 'use strict';
2
3 const config = require( './config.json' );
4
5 const instanceCache = {
6 user: null,
7 utc: null,
8 site: null
9 };
10
11 let supportsOffsetCache = null;
12
13 // Rough polyfill for Array.prototype.includes, used in MW 1.43 backport
14 const includes = ( arr, x, from ) => arr.indexOf( x, from ) !== -1;
15
16 // Private function collection.
17 // JSDOC doesn't like top-level function declarations.
18 // These can probably be private static methods when we have ES2022.
19 const priv = {
20 /**
21 * Determine whether the browser supports offset strings like "+00:00", which
22 * were introduced in ECMA-402, 11th edition (2024).
23 *
24 * @return {boolean}
25 */
26 supportsOffset() {
27 if ( supportsOffsetCache === null ) {
28 try {
29 // eslint-disable-next-line no-new
30 new Intl.DateTimeFormat( undefined, { timeZone: '+01:00' } );
31 supportsOffsetCache = true;
32 } catch ( e ) {
33 supportsOffsetCache = false;
34 }
35 }
36 return supportsOffsetCache;
37 },
38
39 /**
40 * Convert an offset in minutes to a string suitable for the timeZone option to
41 * the Intl.DateTimeFormat constructor. We use the MW sign convention for the
42 * input, where positive is positive, not the inverted JS convention.
43 *
44 * @param {number} offset
45 * @return {string|undefined}
46 */
47 offsetToZone( offset ) {
48 const hour = Math.floor( Math.abs( offset ) / 60 );
49 const minute = Math.abs( offset ) % 60;
50 if ( priv.supportsOffset() ) {
51 const pad = ( x ) => `${ x < 10 ? '0' : '' }${ x }`;
52 return `${ offset < 0 ? '-' : '+' }${ pad( hour ) }:${ pad( minute ) }`;
53 }
54 if ( minute !== 0 ) {
55 // Can't represent this zone -- just use the system time zone
56 return undefined;
57 }
58 return `Etc/GMT${ offset < 0 ? '+' : '-' }${ hour }`;
59 },
60
61 /**
62 * Check if a zone name is usable as an input to the Intl.DateTimeFormat constructor.
63 * If this returns false, we will use the offset instead.
64 *
65 * @param {string} zoneName
66 * @return {boolean}
67 */
68 isKnownZoneName( zoneName ) {
69 // Feature test for Safari 11.1
70 // eslint-disable-next-line compat/compat
71 return Intl.supportedValuesOf && includes( Intl.supportedValuesOf( 'timeZone' ), zoneName );
72 },
73
74 /**
75 * Convert a MW time zone option value to an identifier suitable for
76 * Intl.DateTimeFormat. UserOptionsModule does some normalisation so this is
77 * not quite as complex as UserTimeCorrection::parse()
78 *
79 * @param {string|null} optionValue The user option value, if any
80 * @param {string} localZone The configured default zone
81 * @param {number} localOffset The configured default offset, in minutes
82 * @return {string|undefined}
83 */
84 normalizeZone( optionValue, localZone, localOffset ) {
85 if ( optionValue ) {
86 const parts = optionValue.split( '|', 3 );
87 if ( parts[ 0 ] === 'ZoneInfo' ) {
88 if ( priv.isKnownZoneName( parts[ 2 ] ) ) {
89 return parts[ 2 ];
90 } else {
91 return priv.offsetToZone( parseInt( parts[ 1 ], 10 ) );
92 }
93 } else if ( parts[ 0 ] === 'Offset' ) {
94 return priv.offsetToZone( parts[ 1 ] );
95 }
96 }
97 return priv.isKnownZoneName( localZone ) ? localZone : priv.offsetToZone( localOffset );
98 },
99
100 /**
101 * Get the normalized user time zone
102 *
103 * @return {string|undefined}
104 */
105 getUserZone() {
106 return priv.normalizeZone(
107 mw.user.options.get( 'timecorrection' ),
108 config.localZone,
109 config.localOffset
110 );
111 },
112
113 /**
114 * Get the normalized site default zone
115 *
116 * @return {string|undefined}
117 */
118 getSiteZone() {
119 return priv.normalizeZone( null, config.localZone, config.localOffset );
120 },
121
122 /**
123 * Get the date style desired by the user, e.g. "dmy".
124 *
125 * @return {string}
126 */
127 getUserDateStyle() {
128 const def = config.defaultStyle;
129 const style = mw.user.options.get( 'date', def );
130 return ( !style || style === 'default' ) ? def : style;
131 },
132
133 /**
134 * Convert an array of parts as returned by Intl.DateTimeFormat.formatParts
135 * to an object.
136 *
137 * @param {Array} parts
138 * @return {Object}
139 */
140 partsToInfo( parts ) {
141 const info = {};
142 for ( const part of parts ) {
143 info[ part.type ] = part.value;
144 }
145 return info;
146 },
147
148 /**
149 * Substitute parameters into the given pattern string
150 *
151 * @param {Object} info
152 * @param {string} pattern
153 * @return {string}
154 */
155 formatPattern( info, pattern ) {
156 return pattern.replace(
157 /\{(\w+)}/g,
158 ( _, name ) => name in info ? info[ name ] : '?'
159 );
160 },
161
162 /**
163 * Convert an English "long offset" part value to a string like "+01:00"
164 *
165 * @param {string} offset
166 * @return {string}
167 */
168 longOffsetToIsoOffset( offset ) {
169 const m = /(GMT|UTC)?([+-][0-9]{2}:[0-9]{2})/.exec( offset );
170 return m ? m[ 2 ] : '+00:00';
171 }
172 };
173
174 /**
175 * @module mediawiki.DateFormatter
176 */
177 /**
178 * Time and date formatter class.
179 *
180 * The main aim of this class is to make it easy to produce a date which is
181 * consistent with the way server-side MediaWiki formats dates, in the current
182 * user's timezone and preferred format.
183 *
184 * The input format is always a native Date object. This isn't a date parser
185 * class.
186 *
187 * The most common operations are available as static methods, which have no
188 * dependency on "this", so they can be called via destructuring assignment.
189 *
190 * The constructor is internal. Instances should be obtained via the static
191 * factory methods.
192 *
193 * @example
194 * // Static interface
195 * const { formatTimeAndDate } = require( 'mediawiki.DateFormatter' );
196 * const now = formatTimeAndDate( new Date() );
197 *
198 * // Non-static interface
199 * const DateFormatter = require( 'mediawiki.DateFormatter' );
200 * const mwTimestamp = DateFormatter.forUtc().formatMw( new Date() );
201 *
202 * @since 1.44
203 */
204 class DateFormatter {
205
206 /**
207 * Get a DateFormatter instance configured for the current user
208 *
209 * @return {DateFormatter}
210 */
211 static forUser() {
212 if ( !instanceCache.user ) {
213 instanceCache.user = new DateFormatter(
214 config.locales,
215 config.formats,
216 priv.getUserZone(),
217 priv.getUserDateStyle()
218 );
219 }
220 return instanceCache.user;
221 }
222
223 /**
224 * Get a DateFormatter instance, configured for the current user except with
225 * the time zone set to UTC.
226 *
227 * @return {DateFormatter}
228 */
229 static forUtc() {
230 if ( !instanceCache.utc ) {
231 instanceCache.utc = new DateFormatter(
232 config.locales,
233 config.formats,
234 'Etc/GMT',
235 priv.getUserDateStyle()
236 );
237 }
238 return instanceCache.utc;
239 }
240
241 /**
242 * Get a DateFormatter instance, configured for the current user except with
243 * the site default time zone.
244 *
245 * @return {DateFormatter}
246 */
247 static forSiteZone() {
248 if ( !instanceCache.site ) {
249 instanceCache.site = new DateFormatter(
250 config.locales,
251 config.formats,
252 priv.getSiteZone(),
253 priv.getUserDateStyle()
254 );
255 }
256 return instanceCache.site;
257 }
258
259 /**
260 * Format a Date to a time and date string (static variant)
261 *
262 * @param {Date} date
263 * @return {string}
264 */
265 static formatTimeAndDate( date ) {
266 return DateFormatter.forUser().formatTimeAndDate( date );
267 }
268
269 /**
270 * Format a Date to a date string (static variant)
271 *
272 * @param {Date} date
273 * @return {string}
274 */
275 static formatDate( date ) {
276 return DateFormatter.forUser().formatDate( date );
277 }
278
279 /**
280 * Format a Date to a time string (static variant)
281 *
282 * @param {Date} date
283 * @return {string}
284 */
285 static formatTime( date ) {
286 return DateFormatter.forUser().formatTime( date );
287 }
288
289 /**
290 * Format a Date to a date string without the year (static variant)
291 *
292 * @param {Date} date
293 * @return {string}
294 */
295 static formatPrettyDate( date ) {
296 return DateFormatter.forUser().formatPrettyDate( date );
297 }
298
299 // No static method for formatMw() -- use forUtc().formatMw()
300
301 /**
302 * Format a Date in ISO 8601 format, including timezone designator.
303 * (static variant)
304 *
305 * @param {Date} date
306 * @return {string}
307 */
308 static formatIso( date ) {
309 return DateFormatter.forUser().formatIso( date );
310 }
311
312 /**
313 * Format a Date in ISO 8601 format, without the timezone designator,
314 * implying unqualified local time, and without seconds. This is suitable
315 * for passing to a datetime-local input. (static variant)
316 *
317 * @param {Date} date
318 * @return {string}
319 */
320 static formatForDateTimeInput( date ) {
321 return DateFormatter.forUser().formatForDateTimeInput( date );
322 }
323
324 /**
325 * Format a date range, showing time and date. (static variant)
326 *
327 * TODO: Have MW provide localisation.
328 * This function depends on the browser for localisation. It does not
329 * properly respect the user's date format preferences, and has limited
330 * language support.
331 *
332 * @param {Date} date1
333 * @param {Date} date2
334 * @return {string}
335 */
336 static formatTimeAndDateRange( date1, date2 ) {
337 return DateFormatter.forUser().formatTimeAndDateRange( date1, date2 );
338 }
339
340 /**
341 * Format a date range, showing time only. (static variant)
342 *
343 * TODO: Have MW provide localisation.
344 *
345 * @param {Date} date1
346 * @param {Date} date2
347 * @return {string}
348 */
349 static formatTimeRange( date1, date2 ) {
350 return DateFormatter.forUser().formatTimeRange( date1, date2 );
351 }
352
353 /**
354 * Format a date range, showing date only. (static variant)
355 *
356 * TODO: Have MW provide localisation.
357 *
358 * @param {Date} date1
359 * @param {Date} date2
360 * @return {string}
361 */
362 static formatDateRange( date1, date2 ) {
363 return DateFormatter.forUser().formatDateRange( date1, date2 );
364 }
365
366 /**
367 * Get the short name of the time zone, e.g. "PST".
368 *
369 * @param {Date} date The reference date
370 * @return {string}
371 */
372 static getShortZoneName( date ) {
373 return DateFormatter.forUser().getShortZoneName( date );
374 }
375
376 /**
377 * Get the time zone offset as a number of minutes, in the sign-preserving
378 * convention, e.g. "+01:00" becomes 60.
379 *
380 * @param {Date} date The reference date for DST
381 * @return {number}
382 */
383 static getZoneOffsetMinutes( date ) {
384 return DateFormatter.forUser().getZoneOffsetMinutes( date );
385 }
386
387 /**
388 * Clear the instance cache. For testing.
389 *
390 * @internal
391 * @ignore
392 */
393 static clearInstanceCache() {
394 instanceCache.user = null;
395 instanceCache.utc = null;
396 instanceCache.site = null;
397 supportsOffsetCache = null;
398 }
399
400 /**
401 * @internal
402 * @ignore
403 *
404 * @param {string[]} locales The locale fallback chain
405 * @param {Object} formats The available date formats, indexed by combined
406 * style+type key, e.g. "dmy pretty". The property values are objects with
407 * the following properties:
408 * - locale: {string} A locale name, overriding the locales parameter
409 * - pattern: {string} A pattern for formatPattern()
410 * - options: {object} Options to pass to Intl.DateTimeFormat()
411 * - error: {string} A parse error relating to the localisation source
412 * @param {string|undefined} zone The normalized time zone identifier
413 * @param {string} style The selected date style, one of those available in
414 * formats, e.g. "dmy". The user's preferred format with fallbacks applied.
415 */
416 constructor( locales, formats, zone, style ) {
417 this.locales = locales;
418 this.formats = Object.assign( {}, formats );
419 const machineTemplate = {
420 locale: 'en',
421 options: {
422 year: 'numeric', month: '2-digit', day: '2-digit',
423 hour: '2-digit', minute: '2-digit', second: '2-digit',
424 hour12: false, timeZoneName: 'longOffset'
425 }
426 };
427 this.formats.datetime = Object.assign(
428 { pattern: '{year}-{month}-{day}T{hour}:{minute}' },
429 machineTemplate
430 );
431 this.formats.iso = Object.assign(
432 { pattern: '{year}-{month}-{day}T{hour}:{minute}:{second}{mwZoneOffset}' },
433 machineTemplate
434 );
435 this.formats.mw = Object.assign(
436 { pattern: '{year}{month}{day}{hour}{minute}{second}' },
437 machineTemplate
438 );
439 this.formats.monthNumber = { locale: 'en', options: { month: 'numeric' } };
440 this.zone = zone;
441 this.intlFormatters = {};
442 this.style = style;
443 }
444
445 /**
446 * Format a Date to a time and date string (non-static)
447 *
448 * @param {Date} date
449 * @return {string}
450 */
451 formatTimeAndDate( date ) {
452 return this.formatInternal( this.style, 'both', date );
453 }
454
455 /**
456 * Format a Date to a date string (non-static)
457 *
458 * @param {Date} date
459 * @return {string}
460 */
461 formatDate( date ) {
462 return this.formatInternal( this.style, 'date', date );
463 }
464
465 /**
466 * Format a Date to a time string (non-static)
467 *
468 * @param {Date} date
469 * @return {string}
470 */
471 formatTime( date ) {
472 return this.formatInternal( this.style, 'time', date );
473 }
474
475 /**
476 * Format a Date to a date string without the year (non-static)
477 *
478 * @param {Date} date
479 * @return {string}
480 */
481 formatPrettyDate( date ) {
482 return this.formatInternal( this.style, 'pretty', date );
483 }
484
485 /**
486 * Format a Date to a MediaWiki 14-character timestamp. Since MediaWiki
487 * timestamps are conventionally UTC, this should typically be called on an
488 * instance retrieved with forUtc().
489 *
490 * @param {Date} date
491 * @return {string}
492 */
493 formatMw( date ) {
494 return this.formatInternal( null, 'mw', date );
495 }
496
497 /**
498 * Format a Date in ISO 8601 format, including timezone designator.
499 * (non-static)
500 *
501 * @param {Date} date
502 * @return {string}
503 */
504 formatIso( date ) {
505 return this.formatInternal( null, 'iso', date );
506 }
507
508 /**
509 * Format a Date in ISO 8601 format, without the timezone designator,
510 * implying unqualified local time, and without seconds. This is suitable
511 * for passing to a datetime-local input. (non-static)
512 *
513 * @param {Date} date
514 * @return {string}
515 */
516 formatForDateTimeInput( date ) {
517 return this.formatInternal( null, 'datetime', date );
518 }
519
520 /**
521 * Format a date range, showing time and date. (non-static)
522 *
523 * TODO: Have MW provide localisation.
524 * This function depends on the browser for localisation. It does not
525 * properly respect the user's date format preferences, and has limited
526 * language support.
527 *
528 * @param {Date} date1
529 * @param {Date} date2
530 * @return {string}
531 */
532 formatTimeAndDateRange( date1, date2 ) {
533 return this.formatRangeInternal( this.style, 'both', date1, date2 );
534 }
535
536 /**
537 * Format a date range, showing time only. (non-static)
538 *
539 * TODO: Have MW provide localisation.
540 *
541 * @param {Date} date1
542 * @param {Date} date2
543 * @return {string}
544 */
545 formatTimeRange( date1, date2 ) {
546 return this.formatRangeInternal( this.style, 'time', date1, date2 );
547 }
548
549 /**
550 * Format a date range, showing date only. (non-static)
551 *
552 * TODO: Have MW provide localisation.
553 *
554 * @param {Date} date1
555 * @param {Date} date2
556 * @return {string}
557 */
558 formatDateRange( date1, date2 ) {
559 return this.formatRangeInternal( this.style, 'date', date1, date2 );
560 }
561
562 /**
563 * Get the short name of the time zone, e.g. "PST".
564 *
565 * @param {Date} date The reference date
566 * @return {string}
567 */
568 getShortZoneName( date ) {
569 return this.getLocalInfoInternal( 'timeZoneName', 'short', date );
570 }
571
572 /**
573 * Get the time zone offset as a number of minutes, in the sign-preserving
574 * convention, e.g. "+01:00" becomes 60.
575 *
576 * @param {Date} date The reference date for DST
577 * @return {number}
578 */
579 getZoneOffsetMinutes( date ) {
580 const [ h, m ] =
581 priv.longOffsetToIsoOffset(
582 this.getLocalInfoInternal( 'timeZoneName', 'longOffset', date )
583 ).split( ':' );
584 return h * 60 + Math.sign( +h ) * m;
585 }
586
587 /**
588 * Format a date/time with a specified style.
589 *
590 * @internal
591 * @ignore
592 *
593 * @param {string|null} style The style, e.g. "dmy", or null to use an
594 * internal type identifier for a machine-readable style.
595 * @param {string} type The type, e.g. "both" for both time and date. If
596 * style is null then this can be an internal style added by the
597 * constructor.
598 * @param {Date} date
599 * @return {string}
600 */
601 formatInternal( style, type, date ) {
602 const formatName = style ? `${ style } ${ type }` : type;
603 const formatter = this.getIntlFormatInternal( formatName );
604 const pattern = this.formats[ formatName ].pattern;
605 if ( pattern ) {
606 const info = priv.partsToInfo( formatter.formatToParts( date ) );
607 if ( includes( pattern, '{mwMonth' ) ) {
608 const i = +this.getIntlFormatInternal( 'monthNumber' ).format( date );
609 [ info.mwMonth, info.mwMonthGen, info.mwMonthAbbrev ] = config.months[ i ] || [];
610 }
611 if ( includes( pattern, '{mwZoneOffset}' ) ) {
612 info.mwZoneOffset = priv.longOffsetToIsoOffset( info.timeZoneName );
613 }
614 return priv.formatPattern( info, pattern );
615 } else {
616 return formatter.format( date );
617 }
618 }
619
620 /**
621 * Format a time/date range with a specified style
622 *
623 * @internal
624 * @ignore
625 *
626 * @param {string} style
627 * @param {string} type
628 * @param {Date} date1
629 * @param {Date} date2
630 * @return {string}
631 */
632 formatRangeInternal( style, type, date1, date2 ) {
633 const formatName = style ? `${ style } ${ type }` : type;
634 const formatter = this.getIntlFormatInternal( formatName );
635 const pattern = this.formats[ formatName ].rangePattern;
636 if ( pattern ) {
637 return priv.formatPattern(
638 priv.partsToInfo( formatter.formatRangeToParts( date1, date2 ) ),
639 pattern
640 );
641 } else {
642 return formatter.formatRange( date1, date2 );
643 }
644 }
645
646 /**
647 * Get a DateTimeFormat object configured for the specified combined
648 * type/style.
649 *
650 * @internal
651 * @ignore
652 *
653 * @param {string} formatName
654 * @return {Intl.DateTimeFormat}
655 */
656 getIntlFormatInternal( formatName ) {
657 if ( !( formatName in this.intlFormatters ) ) {
658 if ( !( formatName in this.formats ) ) {
659 throw new Error( `Unknown date format "${ formatName }"` );
660 }
661 const format = this.formats[ formatName ];
662 const locale = format.locale || this.locales;
663 const options = Object.assign( {}, format.options );
664 options.timeZone = this.zone;
665 this.intlFormatters[ formatName ] = new Intl.DateTimeFormat( locale, options );
666 }
667 return this.intlFormatters[ formatName ];
668 }
669
670 /**
671 * Extract a part value from a formatted date, with the given configuration
672 * for that part value.
673 *
674 * @internal
675 * @ignore
676 *
677 * @param {string} fieldName
678 * @param {string} configValue
679 * @param {Date} date
680 * @return {string}
681 */
682 getLocalInfoInternal( fieldName, configValue, date ) {
683 const key = `info ${ fieldName }.${ configValue }`;
684 if ( !this.formats[ key ] ) {
685 this.formats[ key ] = { options: { [ fieldName ]: configValue } };
686 }
687 const formatter = this.getIntlFormatInternal( key );
688 const info = priv.partsToInfo( formatter.formatToParts( date ) );
689 return info[ fieldName ] || '';
690 }
691 }
692
693 if ( window.QUnit ) {
694 DateFormatter.priv = priv;
695 DateFormatter.config = config;
696 }
697
698 module.exports = DateFormatter;