@dxtmisha/functional-basic 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. package/package.json +5 -3
  2. package/src/classes/Api.ts +407 -0
  3. package/src/classes/ApiDefault.ts +83 -0
  4. package/src/classes/ApiHeaders.ts +52 -0
  5. package/src/classes/ApiPreparation.ts +114 -0
  6. package/src/classes/ApiResponse.ts +293 -0
  7. package/src/classes/ApiStatus.ts +173 -0
  8. package/src/classes/BroadcastMessage.ts +73 -0
  9. package/src/classes/Cache.ts +60 -0
  10. package/src/classes/CacheItem.ts +95 -0
  11. package/src/classes/CacheStatic.ts +30 -0
  12. package/src/classes/Cookie.ts +135 -0
  13. package/src/classes/CookieBlock.ts +31 -0
  14. package/src/classes/DataStorage.ts +194 -0
  15. package/src/classes/Datetime.ts +891 -0
  16. package/src/classes/EventItem.ts +373 -0
  17. package/src/classes/Geo.ts +320 -0
  18. package/src/classes/GeoFlag.ts +386 -0
  19. package/src/classes/GeoIntl.ts +839 -0
  20. package/src/classes/GeoPhone.ts +272 -0
  21. package/src/classes/Global.ts +32 -0
  22. package/src/classes/Hash.ts +142 -0
  23. package/src/classes/Icons.ts +165 -0
  24. package/src/classes/Loading.ts +90 -0
  25. package/src/classes/Meta.ts +284 -0
  26. package/src/classes/MetaManager.ts +200 -0
  27. package/src/classes/MetaOg.ts +147 -0
  28. package/src/classes/MetaTwitter.ts +154 -0
  29. package/src/classes/ScrollbarWidth.ts +86 -0
  30. package/src/classes/Translate.ts +293 -0
  31. package/src/classes/__tests__/Api.test.ts +728 -0
  32. package/src/classes/__tests__/ApiDefault.test.ts +222 -0
  33. package/src/classes/__tests__/ApiHeaders.test.ts +447 -0
  34. package/src/classes/__tests__/ApiPreparation.test.ts +257 -0
  35. package/src/classes/__tests__/ApiResponse.test.ts +547 -0
  36. package/src/classes/__tests__/ApiStatus.test.ts +403 -0
  37. package/src/classes/__tests__/Meta.test.ts +629 -0
  38. package/src/classes/__tests__/MetaManager.test.ts +836 -0
  39. package/src/classes/__tests__/MetaOg.test.ts +677 -0
  40. package/src/classes/__tests__/MetaTwitter.test.ts +423 -0
  41. package/src/functions/anyToString.ts +36 -0
  42. package/src/functions/applyTemplate.ts +63 -0
  43. package/src/functions/arrFill.ts +10 -0
  44. package/src/functions/copyObject.ts +10 -0
  45. package/src/functions/createElement.ts +40 -0
  46. package/src/functions/domQuerySelector.ts +15 -0
  47. package/src/functions/domQuerySelectorAll.ts +15 -0
  48. package/src/functions/encodeAttribute.ts +15 -0
  49. package/src/functions/eventStopPropagation.ts +10 -0
  50. package/src/functions/executeFunction.ts +13 -0
  51. package/src/functions/executePromise.ts +19 -0
  52. package/src/functions/forEach.ts +39 -0
  53. package/src/functions/frame.ts +38 -0
  54. package/src/functions/getAttributes.ts +27 -0
  55. package/src/functions/getClipboardData.ts +13 -0
  56. package/src/functions/getColumn.ts +18 -0
  57. package/src/functions/getElement.ts +35 -0
  58. package/src/functions/getElementId.ts +39 -0
  59. package/src/functions/getElementItem.ts +27 -0
  60. package/src/functions/getElementOrWindow.ts +23 -0
  61. package/src/functions/getExp.ts +21 -0
  62. package/src/functions/getItemByPath.ts +24 -0
  63. package/src/functions/getKey.ts +9 -0
  64. package/src/functions/getLengthOfAllArray.ts +13 -0
  65. package/src/functions/getMaxLengthAllArray.ts +13 -0
  66. package/src/functions/getMinLengthAllArray.ts +13 -0
  67. package/src/functions/getMouseClient.ts +17 -0
  68. package/src/functions/getMouseClientX.ts +9 -0
  69. package/src/functions/getMouseClientY.ts +9 -0
  70. package/src/functions/getObjectByKeys.ts +24 -0
  71. package/src/functions/getObjectNoUndefined.ts +23 -0
  72. package/src/functions/getObjectOrNone.ts +11 -0
  73. package/src/functions/getRandomText.ts +29 -0
  74. package/src/functions/getRequestString.ts +21 -0
  75. package/src/functions/getStepPercent.ts +19 -0
  76. package/src/functions/getStepValue.ts +19 -0
  77. package/src/functions/goScroll.ts +40 -0
  78. package/src/functions/inArray.ts +10 -0
  79. package/src/functions/initScrollbarOffset.ts +14 -0
  80. package/src/functions/intersectKey.ts +34 -0
  81. package/src/functions/isArray.ts +9 -0
  82. package/src/functions/isDifferent.ts +27 -0
  83. package/src/functions/isDomRuntime.ts +12 -0
  84. package/src/functions/isFilled.ts +49 -0
  85. package/src/functions/isFloat.ts +16 -0
  86. package/src/functions/isFunction.ts +11 -0
  87. package/src/functions/isInDom.ts +15 -0
  88. package/src/functions/isIntegerBetween.ts +11 -0
  89. package/src/functions/isNull.ts +11 -0
  90. package/src/functions/isNumber.ts +16 -0
  91. package/src/functions/isObject.ts +9 -0
  92. package/src/functions/isObjectNotArray.ts +11 -0
  93. package/src/functions/isSelected.ts +32 -0
  94. package/src/functions/isSelectedByList.ts +19 -0
  95. package/src/functions/isString.ts +9 -0
  96. package/src/functions/isWindow.ts +11 -0
  97. package/src/functions/random.ts +10 -0
  98. package/src/functions/replaceRecursive.ts +60 -0
  99. package/src/functions/replaceTemplate.ts +22 -0
  100. package/src/functions/secondToTime.ts +20 -0
  101. package/src/functions/setElementItem.ts +56 -0
  102. package/src/functions/setValues.ts +59 -0
  103. package/src/functions/splice.ts +59 -0
  104. package/src/functions/strFill.ts +12 -0
  105. package/src/functions/toArray.ts +19 -0
  106. package/src/functions/toCamelCase.ts +16 -0
  107. package/src/functions/toCamelCaseFirst.ts +12 -0
  108. package/src/functions/toDate.ts +44 -0
  109. package/src/functions/toKebabCase.ts +25 -0
  110. package/src/functions/toNumber.ts +35 -0
  111. package/src/functions/toNumberByMax.ts +33 -0
  112. package/src/functions/toPercent.ts +10 -0
  113. package/src/functions/toPercentBy100.ts +12 -0
  114. package/src/functions/transformation.ts +59 -0
  115. package/src/functions/uniqueArray.ts +9 -0
  116. package/src/functions/writeClipboardData.ts +17 -0
  117. package/src/library.ts +116 -0
  118. package/src/types/apiTypes.ts +143 -0
  119. package/src/types/basicTypes.ts +155 -0
  120. package/src/types/geoTypes.ts +109 -0
  121. package/src/types/metaTypes.ts +764 -0
  122. package/src/vite-env.d.ts +1 -0
@@ -0,0 +1,839 @@
1
+ import { getColumn } from '../functions/getColumn'
2
+ import { isDomRuntime } from '../functions/isDomRuntime'
3
+ import { isString } from '../functions/isString'
4
+ import { toDate } from '../functions/toDate'
5
+ import { toNumber } from '../functions/toNumber'
6
+
7
+ import { Geo } from './Geo'
8
+
9
+ import {
10
+ type NumberOrStringOrDate,
11
+ type NumberOrString,
12
+ type ItemValue
13
+ } from '../types/basicTypes'
14
+ import {
15
+ type GeoDate,
16
+ type GeoItemFull
17
+ } from '../types/geoTypes'
18
+
19
+ /**
20
+ * The Intl namespace object contains several constructors as well as functionality common
21
+ * to the internationalization constructors and other language sensitive functions. Collectively,
22
+ * they comprise the ECMAScript Internationalization API, which provides language sensitive
23
+ * string comparison, number formatting, date and time formatting, and more
24
+ *
25
+ * Объект Intl является пространством имён для API интернационализации ECMAScript, предоставляющим
26
+ * языка-зависимое сравнение строк, форматирование чисел и дат со временем. Конструкторы объектов
27
+ * Collator, NumberFormat и DateTimeFormat являются свойствами объекта Intl. На этой странице
28
+ * описаны эти свойства, а также общая функциональность конструкторов интернационализации и других
29
+ * языка-зависимых функций
30
+ */
31
+ export class GeoIntl {
32
+ /**
33
+ * Returns an instance of the class according to the specified country code.
34
+ *
35
+ * Возвращает экземпляр класса по указанному коду страны.
36
+ * @param code country code, full form language-country or one of them/
37
+ * код страны, полный вид язык-страна или один из них
38
+ */
39
+ static getInstance(code: string = Geo.getLocation()) {
40
+ return new GeoIntl(code)
41
+ }
42
+
43
+ private readonly geo: GeoItemFull
44
+
45
+ /**
46
+ * Constructor
47
+ * @param code country code, full form language-country or one of them/
48
+ * код страны, полный вид язык-страна или один из них
49
+ */
50
+ constructor(code: string = Geo.getLocation()) {
51
+ this.geo = Geo.find(code)
52
+
53
+ const location = this.getLocation()
54
+
55
+ if (location in items) {
56
+ return items[location] as GeoIntl
57
+ }
58
+
59
+ items[location] = this
60
+ }
61
+
62
+ /**
63
+ * Returns country code and language.
64
+ *
65
+ * Возвращает код страны и языка.
66
+ */
67
+ getLocation(): string {
68
+ return this.geo.standard
69
+ }
70
+
71
+ /**
72
+ * Returns the first day of the week.
73
+ *
74
+ * Возвращает первый день недели.
75
+ */
76
+ getFirstDay(): string {
77
+ return this.geo.firstDay
78
+ }
79
+
80
+ /**
81
+ * The consistent translation of language, region and script display names.
82
+ *
83
+ * Последовательный перевод отображаемых названий языка, региона и скрипта.
84
+ * @param value the code to provide depends on the type/ предоставляемый код зависит от типа
85
+ * @param typeOptions an object with some or all of the following properties/
86
+ * объект с некоторыми или всеми из следующих свойств
87
+ */
88
+ display(
89
+ value?: string,
90
+ typeOptions?: Intl.DisplayNamesOptions['type'] | Intl.DisplayNamesOptions
91
+ ): string {
92
+ let options: Intl.DisplayNamesOptions = { type: 'language' }
93
+ let text
94
+
95
+ if (typeOptions) {
96
+ if (typeof typeOptions === 'string') {
97
+ options.type = typeOptions
98
+ } else {
99
+ options = {
100
+ ...options,
101
+ ...typeOptions
102
+ }
103
+ }
104
+ }
105
+
106
+ try {
107
+ if (isDomRuntime()) {
108
+ if (value) {
109
+ text = new Intl.DisplayNames(this.getLocation(), options).of(value)
110
+ } else if (options.type === 'language') {
111
+ text = new Intl.DisplayNames(this.getLocation(), options).of(this.geo.language)
112
+ } else if (options.type === 'region') {
113
+ text = new Intl.DisplayNames(this.getLocation(), options).of(this.geo.country)
114
+ }
115
+ }
116
+ } catch (e) {
117
+ console.error('display: ', e)
118
+ }
119
+
120
+ return text ?? value ?? ''
121
+ }
122
+
123
+ /**
124
+ * Get display names of language.
125
+ *
126
+ * Получить отображаемые имена языка.
127
+ * @param value the code to provide depends on the type/ предоставляемый код зависит от типа
128
+ * @param style the formatting style to use/ используемый стиль форматирования
129
+ */
130
+ languageName(
131
+ value?: string,
132
+ style?: Intl.RelativeTimeFormatStyle
133
+ ): string {
134
+ const options: Intl.DisplayNamesOptions = {
135
+ type: 'language',
136
+ style
137
+ }
138
+
139
+ return this.display(Geo.getByCode(value).language, options)
140
+ }
141
+
142
+ /**
143
+ * Get display names of region.
144
+ *
145
+ * Получить отображаемые имена региона.
146
+ * @param value the code to provide depends on the type/ предоставляемый код зависит от типа
147
+ * @param style the formatting style to use/ используемый стиль форматирования
148
+ */
149
+ countryName(
150
+ value?: string,
151
+ style?: Intl.RelativeTimeFormatStyle
152
+ ): string {
153
+ const options: Intl.DisplayNamesOptions = {
154
+ type: 'region',
155
+ style
156
+ }
157
+
158
+ return this.display(value, options)
159
+ }
160
+
161
+ /**
162
+ * The method returns a string containing the full name in a specific format.
163
+ *
164
+ * Метод возвращает строку, содержащую полное имя в определённом формате.
165
+ * @param last last name/ фамилию
166
+ * @param first first name/ имя
167
+ * @param surname surname middle name (optional)/ отчество
168
+ * @param short shorten the names/ сократить названия
169
+ */
170
+ fullName(
171
+ last: string,
172
+ first: string,
173
+ surname?: string,
174
+ short?: boolean
175
+ ): string {
176
+ const nameFormat = this.geo?.nameFormat ?? 'fl'
177
+ let fullName
178
+
179
+ switch (nameFormat) {
180
+ case 'fsl':
181
+ fullName = `${first}${surname ? ` ${surname}` : ''} ${last}`
182
+ break
183
+ case 'lf':
184
+ fullName = `${last} ${first}`
185
+ break
186
+ case 'lsf':
187
+ fullName = `${last}${surname ? ` ${surname}` : ''} ${first}`
188
+ break
189
+ default:
190
+ fullName = `${first} ${last}`
191
+ break
192
+ }
193
+
194
+ if (short) {
195
+ return fullName.replace(/ (.)[^ ]+/ig, ' $1.')
196
+ }
197
+
198
+ return fullName
199
+ }
200
+
201
+ /**
202
+ * In basic use without specifying a locale, a formatted string.
203
+ *
204
+ * При обычном использовании без указания локали форматированная строка.
205
+ * @param value a number, bigint, or string, to format/ число для форматирования
206
+ * @param options an object with some or all properties/ объект с некоторыми
207
+ * или всеми свойствами
208
+ */
209
+ number(
210
+ value: NumberOrString,
211
+ options?: Intl.NumberFormatOptions
212
+ ): string {
213
+ return this.numberObject(options)?.format?.(toNumber(value)) || value.toString()
214
+ }
215
+
216
+ /**
217
+ * Decimal point symbol.
218
+ *
219
+ * Символ десятичной точки.
220
+ */
221
+ decimal(): string {
222
+ return this.numberObject()
223
+ ?.formatToParts?.(1.2)
224
+ ?.find?.(item => item.type === 'decimal')?.value || '.'
225
+ }
226
+
227
+ /**
228
+ * Currency formatting.
229
+ *
230
+ * Форматирование валюты.
231
+ * @param value a number, bigint, or string, to format/ число для форматирования
232
+ * @param currencyOptions the currency to use in currency formatting/
233
+ * валюта для использования в форматировании валюты
234
+ * @param numberOnly do not display the currency symbol/ не выводить значок валюты
235
+ */
236
+ currency(
237
+ value: NumberOrString,
238
+ currencyOptions?: string | Intl.NumberFormatOptions,
239
+ numberOnly = false
240
+ ): string {
241
+ const options: Intl.NumberFormatOptions = ({
242
+ style: 'currency',
243
+ currencyDisplay: 'symbol',
244
+ ...(typeof currencyOptions === 'string' ? { currency: currencyOptions } : currencyOptions || {})
245
+ })
246
+
247
+ const number: string = value
248
+ .toString()
249
+ .replace(/^([\S\s]+[\d ])([a-zA-Z]{3})$/i, (...text: string[]): string => {
250
+ options.currency = String(text[2]).toUpperCase()
251
+ return String(text[1])
252
+ })
253
+
254
+ if (numberOnly) {
255
+ const object = this.numberObject(options)
256
+ if (object) {
257
+ return getColumn(
258
+ object.formatToParts(toNumber(value))
259
+ .filter(item => ['literal', 'currency'].indexOf(item.type) === -1),
260
+ 'value'
261
+ )
262
+ .join('')
263
+ } else {
264
+ return value.toString()
265
+ }
266
+ } else if ('currency' in options) {
267
+ return this.number(
268
+ typeof value === 'number' ? value : number,
269
+ options
270
+ )
271
+ } else {
272
+ return this.number(
273
+ typeof value === 'number' ? value : number,
274
+ {
275
+ ...options,
276
+ style: 'decimal'
277
+ }
278
+ )
279
+ }
280
+ }
281
+
282
+ /**
283
+ * Returns the currency symbol if it exists, otherwise the currency code.
284
+ *
285
+ * Возвращает символ для валюты, если он есть, или сам код валюты.
286
+ * @param currency the currency to use in currency formatting/
287
+ * валюта для использования в форматировании валюты
288
+ * @param currencyDisplay how to display the currency in currency formatting/
289
+ * как отобразить валюту в формате валюты
290
+ */
291
+ currencySymbol(
292
+ currency: string,
293
+ currencyDisplay: keyof Intl.NumberFormatOptionsCurrencyDisplayRegistry = 'symbol'
294
+ ): string {
295
+ return this.numberObject({
296
+ style: 'currency',
297
+ currencyDisplay,
298
+ currency
299
+ })
300
+ ?.formatToParts?.(100)
301
+ ?.find?.(item => item.type === 'currency')?.value || currency
302
+ }
303
+
304
+ /**
305
+ * Unit formatting.
306
+ * If the style is 'unit', a unit property must be provided.
307
+ *
308
+ * Форматирование юнитов.
309
+ * @param value a number, bigint, or string, to format/ число для форматирования
310
+ * @param unitOptions the unit to use in unit formatting/ блок для использования
311
+ * в форматировании блока
312
+ */
313
+ unit(
314
+ value: NumberOrString,
315
+ unitOptions?: string | Intl.NumberFormatOptions
316
+ ): string {
317
+ const options: Intl.NumberFormatOptions = ({
318
+ style: 'unit',
319
+ ...(typeof unitOptions === 'string' ? { unit: unitOptions } : unitOptions || {})
320
+ })
321
+
322
+ const number: string = value
323
+ .toString()
324
+ .replace(/^([\S\s]+[\d ])([a-zA-Z]+)$/i, (...text: string[]): string => {
325
+ options.unit = String(text[2]).toLowerCase()
326
+ return String(text[1])
327
+ })
328
+
329
+ return this.number(number, options)
330
+ }
331
+
332
+ /**
333
+ * Возвращает отформатированный размер файла
334
+ * @param value a number, bigint, or string, to format /<br>число для форматирования
335
+ * @param unitOptions the unit to use in unit formatting /<br>блок для использования
336
+ * в форматировании блока
337
+ */
338
+ sizeFile(
339
+ value: NumberOrString,
340
+ unitOptions:
341
+ 'byte'
342
+ | 'kilobyte'
343
+ | 'megabyte'
344
+ | 'gigabyte'
345
+ | 'terabyte'
346
+ | 'petabyte'
347
+ | Intl.NumberFormatOptions = 'byte'
348
+ ): string {
349
+ const number: number = toNumber(value)
350
+
351
+ if (
352
+ number > 1024
353
+ && isString(unitOptions)
354
+ ) {
355
+ switch (unitOptions) {
356
+ case 'byte':
357
+ return this.sizeFile(number / 1024, 'kilobyte')
358
+ case 'kilobyte':
359
+ return this.sizeFile(number / 1024, 'megabyte')
360
+ case 'megabyte':
361
+ return this.sizeFile(number / 1024, 'gigabyte')
362
+ case 'gigabyte':
363
+ return this.sizeFile(number / 1024, 'terabyte')
364
+ case 'terabyte':
365
+ return this.sizeFile(number / 1024, 'petabyte')
366
+ }
367
+ }
368
+
369
+ return this.unit(value, unitOptions)
370
+ }
371
+
372
+ /**
373
+ * Number as a percentage.
374
+ *
375
+ * Число в виде процента.
376
+ * @param value a number, bigint, or string, to format/ число для форматирования
377
+ * @param options an object with some or all properties/ объект с некоторыми или всеми свойствами
378
+ */
379
+ percent(
380
+ value: NumberOrString,
381
+ options?: Intl.NumberFormatOptions
382
+ ): string {
383
+ return this.number(value, {
384
+ style: 'percent',
385
+ ...(options || {})
386
+ })
387
+ }
388
+
389
+ /**
390
+ * Number as a percentage (unit).
391
+ *
392
+ * Число в виде процента (единица).
393
+ * @param value a number, bigint, or string, to format/ число для форматирования
394
+ * @param options an object with some or all properties/
395
+ * объект с некоторыми или всеми свойствами
396
+ */
397
+ percentBy100(
398
+ value: NumberOrString,
399
+ options?: Intl.NumberFormatOptions
400
+ ): string {
401
+ return this.percent(toNumber(value) / 100, options)
402
+ }
403
+
404
+ /**
405
+ * Применять форматирование, учитывающее множественное число, и языковые правила, связанные с множественным числом
406
+ * @param value a number, bigint, or string, to format/ число для форматирования
407
+ * @param words list of words for formatting (in the format one|two|few|many|other|zero)/
408
+ * список слов для форматирования (в формате `one|two|few|many|other|zero`)
409
+ * @param options Property for PluralRules/ свойство для PluralRules
410
+ * @param optionsNumber an object with some or all properties/ объект с некоторыми или всеми свойствами
411
+ */
412
+ plural(
413
+ value: NumberOrString,
414
+ words: string,
415
+ options?: Intl.PluralRulesOptions,
416
+ optionsNumber?: Intl.NumberFormatOptions
417
+ ): string {
418
+ const number = toNumber(value)
419
+ const list = words.split('|')
420
+
421
+ if (list.length > 1) {
422
+ try {
423
+ if (isDomRuntime()) {
424
+ const plural = new Intl.PluralRules(this.getLocation(), options)
425
+ const type = plural.select(number)
426
+ let wordsFormat: string | undefined
427
+
428
+ switch (type) {
429
+ case 'zero':
430
+ wordsFormat = list[list.length - 1]
431
+ break
432
+ case 'one':
433
+ wordsFormat = list?.[0]
434
+ break
435
+ case 'two':
436
+ wordsFormat = list?.[1]
437
+ break
438
+ case 'few':
439
+ wordsFormat = list?.[3] ? list?.[2] : list?.[1]
440
+ break
441
+ case 'many':
442
+ wordsFormat = list?.[3] || list?.[2] || list?.[1]
443
+ break
444
+ case 'other':
445
+ if (list.length === 6) {
446
+ wordsFormat = list[list.length - 2]
447
+ } else {
448
+ wordsFormat = list[list.length - 1]
449
+ }
450
+ break
451
+ }
452
+
453
+ return `${this.number(number, optionsNumber)} ${wordsFormat ?? ''}`.trim()
454
+ }
455
+ } catch (e) {
456
+ console.error('plural: ', e)
457
+ }
458
+ }
459
+
460
+ return `${this.number(number, optionsNumber)} ${list?.[0] ?? ''}`.trim()
461
+ }
462
+
463
+ /**
464
+ * Enables language-sensitive date and time formatting.
465
+ *
466
+ * Конструктором объектов, включающих языка-зависимое форматирование даты и времени.
467
+ * @param value the date to format/ дата для форматирования
468
+ * @param type type of data format/ тип формата data
469
+ * @param styleOptions the representation of the month/ представление месяца
470
+ * @param hour24 whether to use 12-hour time/ использовать ли 12-часовое время
471
+ */
472
+ date(
473
+ value: NumberOrStringOrDate,
474
+ type?: GeoDate,
475
+ styleOptions?: Intl.DateTimeFormatOptions['month'] | Intl.DateTimeFormatOptions,
476
+ hour24?: boolean
477
+ ): string {
478
+ const date = toDate(value)
479
+
480
+ const isDisplay = typeof styleOptions === 'string'
481
+ const options = this.dateOptions(type, isDisplay ? styleOptions : 'short')
482
+
483
+ if (hour24) {
484
+ options.hour12 = false
485
+ }
486
+
487
+ if (!isDisplay) {
488
+ Object.assign(options, styleOptions)
489
+ }
490
+
491
+ return date.toLocaleString(this.getLocation(), options)
492
+ }
493
+
494
+ /**
495
+ * Enables language-sensitive relative time formatting.
496
+ *
497
+ * Включает форматирование относительного времени с учетом языка.
498
+ * @param value a number, bigint, or string, to format/ число для форматирования
499
+ * @param styleOptions the length of the internationalized message/
500
+ * длина интернационализированного сообщения
501
+ * @param todayValue current day/ текущий день
502
+ */
503
+ relative(
504
+ value: NumberOrStringOrDate,
505
+ styleOptions?: Intl.RelativeTimeFormatStyle | Intl.RelativeTimeFormatOptions,
506
+ todayValue?: Date
507
+ ): string {
508
+ const date = toDate(value)
509
+ const today = todayValue || new Date()
510
+ const options: Intl.RelativeTimeFormatOptions = ({
511
+ numeric: 'auto',
512
+ ...(typeof styleOptions === 'string' ? { style: styleOptions } : styleOptions || {})
513
+ })
514
+
515
+ let unit: Intl.RelativeTimeFormatUnit = 'second'
516
+ let relative = (date.getTime() - today.getTime()) / 1000
517
+
518
+ if (Math.abs(relative) >= 60) {
519
+ unit = 'minute'
520
+ relative /= 60
521
+
522
+ if (Math.abs(relative) >= 60) {
523
+ unit = 'hour'
524
+ relative /= 60
525
+
526
+ if (Math.abs(relative) >= 24) {
527
+ unit = 'day'
528
+ relative /= 24
529
+
530
+ if (Math.abs(relative) >= 30) {
531
+ unit = 'month'
532
+ relative /= 30
533
+
534
+ if (Math.abs(relative) >= 12) {
535
+ unit = 'year'
536
+ relative /= 12
537
+ }
538
+ }
539
+ }
540
+ }
541
+ }
542
+
543
+ return this.relativeByValue(relative, unit, options)
544
+ }
545
+
546
+ /**
547
+ * Enables language-sensitive relative time formatting
548
+ * Including the ability to add a limit to output the standard time format if the value
549
+ * exceeds the allowable limit.
550
+ *
551
+ * Включает форматирование относительного времени с учетом языка.
552
+ * Включая возможность добавления лимита, чтобы выводить уже стандартный формат времени,
553
+ * если значение вышло за пределы допустимого.
554
+ * @param value a number, bigint, or string, to format/ число для форматирования
555
+ * @param limit values that determine the output limit (values per day)/
556
+ * значения, по которым определяем предел вывода (значения в день)
557
+ * @param todayValue current day/ текущий день
558
+ * @param relativeOptions the length of the internationalized message/
559
+ * длина интернационализированного сообщения
560
+ * @param dateOptions the representation of the month/ представление месяца
561
+ * @param type type of data format/ тип формата data
562
+ * @param hour24 whether to use 12-hour time/ использовать ли 12-часовое время
563
+ */
564
+ relativeLimit(
565
+ value: NumberOrStringOrDate,
566
+ limit: number,
567
+ todayValue?: Date,
568
+ relativeOptions?: Intl.RelativeTimeFormatStyle | Intl.RelativeTimeFormatOptions,
569
+ dateOptions?: Intl.DateTimeFormatOptions['month'] | Intl.DateTimeFormatOptions,
570
+ type?: GeoDate,
571
+ hour24?: boolean
572
+ ): string {
573
+ const date = toDate(value)
574
+ const today = todayValue || new Date()
575
+ const limitValueIn = (new Date(today))
576
+ const limitValueOut = (new Date(today))
577
+
578
+ limitValueIn.setDate(today.getDate() - limit)
579
+ limitValueOut.setDate(today.getDate() + limit)
580
+
581
+ if (
582
+ date >= limitValueIn
583
+ && date <= limitValueOut
584
+ ) {
585
+ return this.relative(
586
+ date,
587
+ relativeOptions,
588
+ today
589
+ )
590
+ } else {
591
+ return this.date(
592
+ date,
593
+ type,
594
+ dateOptions,
595
+ hour24
596
+ )
597
+ }
598
+ }
599
+
600
+ /**
601
+ * Возвращает отформатированное значение времени, прошедшего с момента события
602
+ * @param value a number, bigint, or string, to format/ число для форматирования
603
+ * @param unit time unit/ единица времени
604
+ * @param styleOptions additional option or formatting style/ дополнительная опция или стиль форматирования
605
+ */
606
+ relativeByValue(
607
+ value: NumberOrString,
608
+ unit: Intl.RelativeTimeFormatUnit,
609
+ styleOptions?: Intl.RelativeTimeFormatStyle | Intl.RelativeTimeFormatOptions
610
+ ): string {
611
+ const options: Intl.RelativeTimeFormatOptions = ({
612
+ numeric: 'auto',
613
+ ...(typeof styleOptions === 'string' ? { style: styleOptions } : styleOptions || {})
614
+ })
615
+
616
+ try {
617
+ if (isDomRuntime()) {
618
+ return new Intl.RelativeTimeFormat(this.getLocation(), options).format(Math.round(toNumber(value)), unit)
619
+ }
620
+ } catch (e) {
621
+ console.error('relative: ', e)
622
+ }
623
+
624
+ return ''
625
+ }
626
+
627
+ /**
628
+ * Names of months.<br>
629
+ * Названия месяцев.
630
+ * @param value the date to format/ дата для форматирования
631
+ * @param style the representation of the month/ представление месяца
632
+ */
633
+ month(
634
+ value?: NumberOrStringOrDate,
635
+ style?: Intl.DateTimeFormatOptions['month']
636
+ ): string {
637
+ try {
638
+ if (isDomRuntime()) {
639
+ return Intl.DateTimeFormat(this.getLocation(), { month: style || 'long' })
640
+ .format(toDate(value))
641
+ }
642
+ } catch (e) {
643
+ console.error('month: ', e)
644
+ }
645
+
646
+ return ''
647
+ }
648
+
649
+ /**
650
+ * Array to list of months.
651
+ *
652
+ * Массив в список месяцев.
653
+ * @param style the representation of the month/ представление месяца
654
+ */
655
+ months(
656
+ style?: Intl.DateTimeFormatOptions['month']
657
+ ): ItemValue<number | undefined>[] {
658
+ const list: ItemValue<number | undefined>[] = [{
659
+ label: '',
660
+ value: undefined
661
+ }]
662
+
663
+ try {
664
+ if (isDomRuntime()) {
665
+ const date = new Date()
666
+ const format = Intl.DateTimeFormat(this.getLocation(), { month: style || 'long' })
667
+
668
+ for (let i = 0; i < 12; i++) {
669
+ date.setMonth(i)
670
+ list.push({
671
+ label: format.format(date)
672
+ .replace(/^./, character => character.toUpperCase()),
673
+ value: i + 1
674
+ })
675
+ }
676
+ }
677
+ } catch (e) {
678
+ console.error('months: ', e)
679
+ }
680
+
681
+ return list
682
+ }
683
+
684
+ /**
685
+ * Returns names of days of the week.
686
+ *
687
+ * Возвращает названия дней недели.
688
+ * @param value the date to format/ дата для форматирования
689
+ * @param style the representation of the weekday/ представление о дне недели
690
+ */
691
+ weekday(
692
+ value?: NumberOrStringOrDate,
693
+ style?: Intl.DateTimeFormatOptions['weekday']
694
+ ): string {
695
+ try {
696
+ if (isDomRuntime()) {
697
+ return Intl.DateTimeFormat(this.getLocation(), { weekday: style || 'long' })
698
+ .format(toDate(value))
699
+ }
700
+ } catch (e) {
701
+ console.error('weekday: ', e)
702
+ }
703
+
704
+ return ''
705
+ }
706
+
707
+ /**
708
+ * An array of the list of names of the days of the week.
709
+ *
710
+ * Массив из списка названий дней недели.
711
+ * @param style the representation of the weekday/ представление о дне недели
712
+ */
713
+ weekdays(
714
+ style?: Intl.DateTimeFormatOptions['weekday']
715
+ ): ItemValue<number | undefined>[] {
716
+ const list: ItemValue<number | undefined>[] = [{
717
+ label: '',
718
+ value: undefined
719
+ }]
720
+
721
+ try {
722
+ if (isDomRuntime()) {
723
+ const date = new Date()
724
+ const format = Intl.DateTimeFormat(this.getLocation(), { weekday: style || 'long' })
725
+ const current = date.getDay() + (this.geo.firstDay === 'Mo' ? -1 : 1)
726
+
727
+ date.setDate(date.getDate() - current)
728
+
729
+ for (let i = 0; i < 7; i++) {
730
+ list.push({
731
+ label: format
732
+ .format(date)
733
+ .replace(/^./, character => character.toUpperCase()),
734
+ value: date.getDay()
735
+ })
736
+
737
+ date.setDate(date.getDate() + 1)
738
+ }
739
+ }
740
+ } catch (e) {
741
+ console.error('weekdays: ', e)
742
+ }
743
+
744
+ return list
745
+ }
746
+
747
+ /**
748
+ * Time.
749
+ *
750
+ * Время.
751
+ * @param value the date to format/ дата для форматирования
752
+ */
753
+ time(value: NumberOrStringOrDate): string {
754
+ return this.date(value, 'time')
755
+ }
756
+
757
+ /**
758
+ * Sorts strings taking into account the characteristics of countries.
759
+ *
760
+ * Сортирует строки с учетом особенностей стран.
761
+ * @param data an array with data/ массив с данными
762
+ * @param compareFn a function for sorting/ функция для сортировки
763
+ */
764
+ sort<T>(
765
+ data: T[],
766
+ compareFn: (a: T, b: T) => [string, string] = (a, b) => [a as string, b as string]
767
+ ) {
768
+ if (isDomRuntime()) {
769
+ const collator = new Intl.Collator(this.getLocation())
770
+
771
+ return data.sort((a, b) => collator.compare(...compareFn(a, b)))
772
+ }
773
+
774
+ return data
775
+ }
776
+
777
+ /**
778
+ * The object enables language-sensitive number formatting.
779
+ *
780
+ * Объект включает форматирование чисел с учетом языка.
781
+ * @param options an object with some or all properties/
782
+ * объект с некоторыми или всеми свойствами
783
+ */
784
+ private numberObject(options?: Intl.NumberFormatOptions): Intl.NumberFormat | undefined {
785
+ try {
786
+ if (isDomRuntime()) {
787
+ return new Intl.NumberFormat(this.getLocation(), options)
788
+ }
789
+ } catch (e) {
790
+ console.error('numberObject: ', e)
791
+ }
792
+
793
+ return undefined
794
+ }
795
+
796
+ /**
797
+ * Returns options for data according to its type.
798
+ *
799
+ * Возвращает options для data по его типу.
800
+ * @param type type of data format/ тип формата data
801
+ * @param display the representation of the month/ представление месяца
802
+ */
803
+ private dateOptions(
804
+ type?: GeoDate,
805
+ display: Intl.DateTimeFormatOptions['month'] = 'short'
806
+ ): Intl.DateTimeFormatOptions {
807
+ const options: Intl.DateTimeFormatOptions = {}
808
+
809
+ if (['full', 'datetime', 'date', undefined, 'year-month', 'year'].indexOf(type) !== -1) {
810
+ options.year = 'numeric'
811
+ }
812
+
813
+ if (['full', 'datetime', 'date', undefined, 'year-month', 'month', 'day-month'].indexOf(type) !== -1) {
814
+ options.month = display
815
+ }
816
+
817
+ if (['full', 'datetime', 'date', undefined, 'day', 'day-month'].indexOf(type) !== -1) {
818
+ options.day = '2-digit'
819
+ }
820
+
821
+ if (type !== undefined) {
822
+ if (['full', 'datetime', 'time', 'hour-minute', 'hour'].indexOf(type) !== -1) {
823
+ options.hour = '2-digit'
824
+ }
825
+
826
+ if (['full', 'datetime', 'time', 'hour-minute', 'minute'].indexOf(type) !== -1) {
827
+ options.minute = '2-digit'
828
+ }
829
+
830
+ if (['full', 'time', 'second'].indexOf(type) !== -1) {
831
+ options.second = '2-digit'
832
+ }
833
+ }
834
+
835
+ return options
836
+ }
837
+ }
838
+
839
+ const items: Record<string, GeoIntl> = {}