/
datetime.ts
403 lines (373 loc) · 11 KB
/
datetime.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
import {
isString,
isBoolean,
isPlainObject,
isDate,
isNumber,
isEmptyObject,
assign
} from '@intlify/shared'
import {
handleMissing,
isTranslateFallbackWarn,
NOT_REOSLVED,
MISSING_RESOLVE_VALUE
} from './context'
import { CoreWarnCodes, getWarnMessage } from './warnings'
import { CoreErrorCodes, createCoreError } from './errors'
import { getLocale } from './fallbacker'
import { Availabilities } from './intl'
import type { Locale, FallbackLocale } from './runtime'
import type {
DateTimeFormat,
DateTimeFormats as DateTimeFormatsType,
DateTimeFormatOptions,
PickupFormatKeys
} from './types/index'
import type { LocaleOptions } from './fallbacker'
import type { CoreContext, CoreInternalContext } from './context'
/**
* # datetime
*
* ## usages:
* // for example `context.datetimeFormats` below
* 'en-US': {
* short: {
* year: 'numeric', month: '2-digit', day: '2-digit',
* hour: '2-digit', minute: '2-digit'
* }
* },
* 'ja-JP': { ... }
*
* // datetimeable value only
* datetime(context, value)
*
* // key argument
* datetime(context, value, 'short')
*
* // key & locale argument
* datetime(context, value, 'short', 'ja-JP')
*
* // object sytle argument
* datetime(context, value, { key: 'short', locale: 'ja-JP' })
*
* // suppress localize miss warning option, override context.missingWarn
* datetime(context, value, { key: 'short', locale: 'ja-JP', missingWarn: false })
*
* // suppress localize fallback warning option, override context.fallbackWarn
* datetime(context, value, { key: 'short', locale: 'ja-JP', fallbackWarn: false })
*
* // if you specify `part` options, you can get an array of objects containing the formatted datetime in parts
* datetime(context, value, { key: 'short', part: true })
*
* // orverride context.datetimeFormats[locale] options with functino options
* datetime(cnotext, value, 'short', { year: '2-digit' })
* datetime(cnotext, value, 'short', 'ja-JP', { year: '2-digit' })
* datetime(context, value, { key: 'short', part: true, year: '2-digit' })
*/
/**
* DateTime options
*
* @remarks
* Options for Datetime formatting API
*
* @VueI18nGeneral
*/
export interface DateTimeOptions<Key = string, Locales = Locale>
extends Intl.DateTimeFormatOptions,
LocaleOptions<Locales> {
/**
* @remarks
* The target format key
*/
key?: Key
/**
* @remarks
* Whether suppress warnings outputted when localization fails
*/
missingWarn?: boolean
/**
* @remarks
* Whether do resolve on format keys when your language lacks a formatting for a key
*/
fallbackWarn?: boolean
/**
* @remarks
* Whether to use [Intel.DateTimeFormat#formatToParts](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/formatToParts)
*/
part?: boolean
}
/**
* `datetime` function overloads
*/
export function datetime<
Context extends CoreContext<Message, {}, {}, {}>,
Message = string
>(
context: Context,
value: number | string | Date
): string | number | Intl.DateTimeFormatPart[]
export function datetime<
Context extends CoreContext<Message, {}, {}, {}>,
Value extends number | string | Date = number,
Key extends string = string,
ResourceKeys extends PickupFormatKeys<
Context['datetimeFormats']
> = PickupFormatKeys<Context['datetimeFormats']>,
Message = string
>(
context: Context,
value: Value,
keyOrOptions:
| Key
| ResourceKeys
| DateTimeOptions<Key | ResourceKeys, Context['locale']>
): string | number | Intl.DateTimeFormatPart[]
export function datetime<
Context extends CoreContext<Message, {}, {}, {}>,
Value extends number | string | Date = number,
Key extends string = string,
ResourceKeys extends PickupFormatKeys<
Context['datetimeFormats']
> = PickupFormatKeys<Context['datetimeFormats']>,
Message = string
>(
context: Context,
value: Value,
keyOrOptions:
| Key
| ResourceKeys
| DateTimeOptions<Key | ResourceKeys, Context['locale']>,
locale: Context['locale']
): string | number | Intl.DateTimeFormatPart[]
export function datetime<
Context extends CoreContext<Message, {}, {}, {}>,
Value extends number | string | Date = number,
Key extends string = string,
ResourceKeys extends PickupFormatKeys<
Context['datetimeFormats']
> = PickupFormatKeys<Context['datetimeFormats']>,
Message = string
>(
context: Context,
value: Value,
keyOrOptions:
| Key
| ResourceKeys
| DateTimeOptions<Key | ResourceKeys, Context['locale']>,
override: Intl.DateTimeFormatOptions
): string | number | Intl.DateTimeFormatPart[]
export function datetime<
Context extends CoreContext<Message, {}, {}, {}>,
Value extends number | string | Date = number,
Key extends string = string,
ResourceKeys extends PickupFormatKeys<
Context['datetimeFormats']
> = PickupFormatKeys<Context['datetimeFormats']>,
Message = string
>(
context: Context,
value: Value,
keyOrOptions:
| Key
| ResourceKeys
| DateTimeOptions<Key | ResourceKeys, Context['locale']>,
locale: Context['locale'],
override: Intl.DateTimeFormatOptions
): string | number | Intl.DateTimeFormatPart[]
// implementation of `datetime` function
export function datetime<
Context extends CoreContext<Message, {}, {}, {}>,
Message = string
>(
context: Context,
...args: unknown[]
): string | number | Intl.DateTimeFormatPart[] {
const {
datetimeFormats,
unresolving,
fallbackLocale,
onWarn,
localeFallbacker
} = context
const { __datetimeFormatters } = context as unknown as CoreInternalContext
if (__DEV__ && !Availabilities.dateTimeFormat) {
onWarn(getWarnMessage(CoreWarnCodes.CANNOT_FORMAT_DATE))
return MISSING_RESOLVE_VALUE
}
const [key, value, options, overrides] = parseDateTimeArgs(...args)
const missingWarn = isBoolean(options.missingWarn)
? options.missingWarn
: context.missingWarn
const fallbackWarn = isBoolean(options.fallbackWarn)
? options.fallbackWarn
: context.fallbackWarn
const part = !!options.part
const locale = getLocale(context, options)
const locales = localeFallbacker(
context as any, // eslint-disable-line @typescript-eslint/no-explicit-any
fallbackLocale as FallbackLocale,
locale
)
if (!isString(key) || key === '') {
return new Intl.DateTimeFormat(locale, overrides).format(value)
}
// resolve format
let datetimeFormat: DateTimeFormat = {}
let targetLocale: Locale | undefined
let format: DateTimeFormatOptions | null = null
let from: Locale = locale
let to: Locale | null = null
const type = 'datetime format'
for (let i = 0; i < locales.length; i++) {
targetLocale = to = locales[i]
if (
__DEV__ &&
locale !== targetLocale &&
isTranslateFallbackWarn(fallbackWarn, key)
) {
onWarn(
getWarnMessage(CoreWarnCodes.FALLBACK_TO_DATE_FORMAT, {
key,
target: targetLocale
})
)
}
// for vue-devtools timeline event
if (__DEV__ && locale !== targetLocale) {
const emitter = (context as unknown as CoreInternalContext).__v_emitter
if (emitter) {
emitter.emit('fallback', {
type,
key,
from,
to,
groupId: `${type}:${key}`
})
}
}
datetimeFormat =
(datetimeFormats as unknown as DateTimeFormatsType)[targetLocale] || {}
format = datetimeFormat[key]
if (isPlainObject(format)) break
handleMissing(context as any, key, targetLocale, missingWarn, type) // eslint-disable-line @typescript-eslint/no-explicit-any
from = to
}
// checking format and target locale
if (!isPlainObject(format) || !isString(targetLocale)) {
return unresolving ? NOT_REOSLVED : key
}
let id = `${targetLocale}__${key}`
if (!isEmptyObject(overrides)) {
id = `${id}__${JSON.stringify(overrides)}`
}
let formatter = __datetimeFormatters.get(id)
if (!formatter) {
formatter = new Intl.DateTimeFormat(
targetLocale,
assign({}, format, overrides)
)
__datetimeFormatters.set(id, formatter)
}
return !part ? formatter.format(value) : formatter.formatToParts(value)
}
/** @internal */
export const DATETIME_FORMAT_OPTIONS_KEYS = [
'localeMatcher',
'weekday',
'era',
'year',
'month',
'day',
'hour',
'minute',
'second',
'timeZoneName',
'formatMatcher',
'hour12',
'timeZone',
'dateStyle',
'timeStyle',
'calendar',
'dayPeriod',
'numberingSystem',
'hourCycle',
'fractionalSecondDigits'
]
/** @internal */
export function parseDateTimeArgs(
...args: unknown[]
): [string, number | Date, DateTimeOptions, Intl.DateTimeFormatOptions] {
const [arg1, arg2, arg3, arg4] = args
const options = {} as DateTimeOptions
let overrides = {} as Intl.DateTimeFormatOptions
let value: number | Date
if (isString(arg1)) {
// Only allow ISO strings - other date formats are often supported,
// but may cause different results in different browsers.
const matches = arg1.match(/(\d{4}-\d{2}-\d{2})(T|\s)?(.*)/)
if (!matches) {
throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT)
}
// Some browsers can not parse the iso datetime separated by space,
// this is a compromise solution by replace the 'T'/' ' with 'T'
const dateTime = matches[3]
? matches[3].trim().startsWith('T')
? `${matches[1].trim()}${matches[3].trim()}`
: `${matches[1].trim()}T${matches[3].trim()}`
: matches[1].trim()
value = new Date(dateTime)
try {
// This will fail if the date is not valid
value.toISOString()
} catch (e) {
throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT)
}
} else if (isDate(arg1)) {
if (isNaN(arg1.getTime())) {
throw createCoreError(CoreErrorCodes.INVALID_DATE_ARGUMENT)
}
value = arg1
} else if (isNumber(arg1)) {
value = arg1
} else {
throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT)
}
if (isString(arg2)) {
options.key = arg2
} else if (isPlainObject(arg2)) {
Object.keys(arg2).forEach(key => {
if (DATETIME_FORMAT_OPTIONS_KEYS.includes(key)) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(overrides as any)[key] = (arg2 as any)[key]
} else {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(options as any)[key] = (arg2 as any)[key]
}
})
}
if (isString(arg3)) {
options.locale = arg3
} else if (isPlainObject(arg3)) {
overrides = arg3
}
if (isPlainObject(arg4)) {
overrides = arg4
}
return [options.key || '', value, options, overrides]
}
/** @internal */
export function clearDateTimeFormat<DateTimeFormats = {}, Message = string>(
ctx: CoreContext<Message, {}, DateTimeFormats>,
locale: Locale,
format: DateTimeFormat
): void {
const context = ctx as unknown as CoreInternalContext
for (const key in format) {
const id = `${locale}__${key}`
if (!context.__datetimeFormatters.has(id)) {
continue
}
context.__datetimeFormatters.delete(id)
}
}