@mgdis/core-ui-helpers 1.0.0

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 (146) hide show
  1. package/.turbo/turbo-build.log +52 -0
  2. package/CHANGELOG.md +12 -0
  3. package/LICENSE +29 -0
  4. package/README.md +95 -0
  5. package/dist/angular/index.cjs +27 -0
  6. package/dist/angular/index.cjs.map +1 -0
  7. package/dist/angular/index.d.ts +21 -0
  8. package/dist/angular/index.js +25 -0
  9. package/dist/angular/index.js.map +1 -0
  10. package/dist/angular/index.umd.js +33 -0
  11. package/dist/angular/index.umd.js.map +1 -0
  12. package/dist/locale/index.cjs +164 -0
  13. package/dist/locale/index.cjs.map +1 -0
  14. package/dist/locale/index.d.ts +103 -0
  15. package/dist/locale/index.js +156 -0
  16. package/dist/locale/index.js.map +1 -0
  17. package/dist/locale/index.umd.js +170 -0
  18. package/dist/locale/index.umd.js.map +1 -0
  19. package/dist/playwright/index.cjs +124 -0
  20. package/dist/playwright/index.cjs.map +1 -0
  21. package/dist/playwright/index.d.ts +35 -0
  22. package/dist/playwright/index.js +120 -0
  23. package/dist/playwright/index.js.map +1 -0
  24. package/dist/playwright/index.umd.js +130 -0
  25. package/dist/playwright/index.umd.js.map +1 -0
  26. package/dist/stencil/index.cjs +281 -0
  27. package/dist/stencil/index.cjs.map +1 -0
  28. package/dist/stencil/index.d.ts +111 -0
  29. package/dist/stencil/index.js +277 -0
  30. package/dist/stencil/index.js.map +1 -0
  31. package/dist/stencil/index.umd.js +287 -0
  32. package/dist/stencil/index.umd.js.map +1 -0
  33. package/dist/storybook/index.cjs +2109 -0
  34. package/dist/storybook/index.cjs.map +1 -0
  35. package/dist/storybook/index.d.ts +85 -0
  36. package/dist/storybook/index.js +2103 -0
  37. package/dist/storybook/index.js.map +1 -0
  38. package/dist/storybook/index.umd.js +2115 -0
  39. package/dist/storybook/index.umd.js.map +1 -0
  40. package/dist/tests/index.cjs +166 -0
  41. package/dist/tests/index.cjs.map +1 -0
  42. package/dist/tests/index.d.ts +91 -0
  43. package/dist/tests/index.js +161 -0
  44. package/dist/tests/index.js.map +1 -0
  45. package/dist/tests/index.umd.js +172 -0
  46. package/dist/tests/index.umd.js.map +1 -0
  47. package/dist/utils/index.cjs +433 -0
  48. package/dist/utils/index.cjs.map +1 -0
  49. package/dist/utils/index.d.ts +265 -0
  50. package/dist/utils/index.js +409 -0
  51. package/dist/utils/index.js.map +1 -0
  52. package/dist/utils/index.umd.js +439 -0
  53. package/dist/utils/index.umd.js.map +1 -0
  54. package/dist/vue/index.cjs +1934 -0
  55. package/dist/vue/index.cjs.map +1 -0
  56. package/dist/vue/index.d.ts +35 -0
  57. package/dist/vue/index.js +1932 -0
  58. package/dist/vue/index.js.map +1 -0
  59. package/dist/vue/index.umd.js +1940 -0
  60. package/dist/vue/index.umd.js.map +1 -0
  61. package/json-doc.test.json +253 -0
  62. package/package.json +80 -0
  63. package/rollup.config.mjs +61 -0
  64. package/src/angular/index.spec.ts +8 -0
  65. package/src/angular/index.ts +1 -0
  66. package/src/angular/mg-angular-logger/index.ts +1 -0
  67. package/src/angular/mg-angular-logger/mg-angular-logger.conf.ts +3 -0
  68. package/src/angular/mg-angular-logger/mg-angular-logger.spec.ts +40 -0
  69. package/src/angular/mg-angular-logger/mg-angular-logger.ts +23 -0
  70. package/src/locale/index.spec.ts +14 -0
  71. package/src/locale/index.ts +1 -0
  72. package/src/locale/locale.spec.ts +173 -0
  73. package/src/locale/locale.ts +166 -0
  74. package/src/playwright/config/index.ts +43 -0
  75. package/src/playwright/index.spec.ts +16 -0
  76. package/src/playwright/index.ts +4 -0
  77. package/src/playwright/utils/__snapshots__/utils.spec.ts.snap +48 -0
  78. package/src/playwright/utils/index.ts +1 -0
  79. package/src/playwright/utils/utils.spec.ts +43 -0
  80. package/src/playwright/utils/utils.ts +64 -0
  81. package/src/stencil/ide/__snapshots__/ide.spec.ts.snap +527 -0
  82. package/src/stencil/ide/ide.spec.ts +25 -0
  83. package/src/stencil/ide/ide.ts +214 -0
  84. package/src/stencil/ide/index.ts +1 -0
  85. package/src/stencil/index.spec.ts +12 -0
  86. package/src/stencil/index.ts +1 -0
  87. package/src/storybook/index.spec.ts +15 -0
  88. package/src/storybook/index.ts +1 -0
  89. package/src/storybook/stencil/__snapshots__/stencil.spec.ts.snap +329 -0
  90. package/src/storybook/stencil/index.ts +1 -0
  91. package/src/storybook/stencil/stencil-shim.d.ts +1 -0
  92. package/src/storybook/stencil/stencil.conf.ts +4 -0
  93. package/src/storybook/stencil/stencil.spec.ts +142 -0
  94. package/src/storybook/stencil/stencil.ts +366 -0
  95. package/src/tests/index.spec.ts +13 -0
  96. package/src/tests/index.ts +1 -0
  97. package/src/tests/unit/__snapshots__/unit.spec.ts.snap +52 -0
  98. package/src/tests/unit/index.ts +1 -0
  99. package/src/tests/unit/unit.conf.ts +9 -0
  100. package/src/tests/unit/unit.spec.ts +44 -0
  101. package/src/tests/unit/unit.ts +171 -0
  102. package/src/utils/attributes/class-list/class-list.spec.ts +36 -0
  103. package/src/utils/attributes/class-list/class-list.ts +51 -0
  104. package/src/utils/attributes/class-list/index.ts +1 -0
  105. package/src/utils/attributes/id/id.spec.ts +51 -0
  106. package/src/utils/attributes/id/id.ts +46 -0
  107. package/src/utils/attributes/id/index.ts +1 -0
  108. package/src/utils/attributes/index.ts +3 -0
  109. package/src/utils/attributes/to-kebab-case/index.ts +1 -0
  110. package/src/utils/attributes/to-kebab-case/to-kebab-case.spec.ts +29 -0
  111. package/src/utils/attributes/to-kebab-case/to-kebab-case.ts +23 -0
  112. package/src/utils/components/__snapshots__/components.spec.ts.snap +313 -0
  113. package/src/utils/components/components.conf.ts +11 -0
  114. package/src/utils/components/components.spec.ts +192 -0
  115. package/src/utils/components/components.ts +138 -0
  116. package/src/utils/components/index.ts +2 -0
  117. package/src/utils/date/date.spec.ts +12 -0
  118. package/src/utils/date/date.ts +20 -0
  119. package/src/utils/date/index.ts +1 -0
  120. package/src/utils/elements/elements.spec.ts +17 -0
  121. package/src/utils/elements/elements.ts +16 -0
  122. package/src/utils/elements/index.ts +1 -0
  123. package/src/utils/index.spec.ts +84 -0
  124. package/src/utils/index.ts +8 -0
  125. package/src/utils/number/index.ts +1 -0
  126. package/src/utils/number/number.spec.ts +14 -0
  127. package/src/utils/number/number.ts +6 -0
  128. package/src/utils/object/index.ts +2 -0
  129. package/src/utils/object/object.conf.ts +4 -0
  130. package/src/utils/object/object.spec.ts +98 -0
  131. package/src/utils/object/object.ts +26 -0
  132. package/src/utils/string/index.ts +1 -0
  133. package/src/utils/string/string.spec.ts +47 -0
  134. package/src/utils/string/string.ts +38 -0
  135. package/src/utils/windows/index.ts +1 -0
  136. package/src/utils/windows/windows.spec.ts +65 -0
  137. package/src/utils/windows/windows.ts +50 -0
  138. package/src/vue/index.spec.ts +8 -0
  139. package/src/vue/index.ts +1 -0
  140. package/src/vue/mg-model/index.ts +1 -0
  141. package/src/vue/mg-model/mg-model.conf.ts +6 -0
  142. package/src/vue/mg-model/mg-model.spec.ts +50 -0
  143. package/src/vue/mg-model/mg-model.ts +50 -0
  144. package/tsconfig.json +17 -0
  145. package/typedoc.json +14 -0
  146. package/vitest.config.mts +13 -0
@@ -0,0 +1,14 @@
1
+ import { describe, expect, test } from 'vitest';
2
+ import { defineLocales, localeCurrency, localeDate, localeDatePattern, localeNumber, localePercent, localeUnit } from '.';
3
+
4
+ describe('locale', () => {
5
+ test('import', () => {
6
+ expect(localeDatePattern).toBeDefined();
7
+ expect(localeCurrency).toBeDefined();
8
+ expect(localeNumber).toBeDefined();
9
+ expect(localePercent).toBeDefined();
10
+ expect(localeUnit).toBeDefined();
11
+ expect(localeDate).toBeDefined();
12
+ expect(defineLocales).toBeDefined();
13
+ });
14
+ });
@@ -0,0 +1 @@
1
+ export * from './locale';
@@ -0,0 +1,173 @@
1
+ import { describe, expect, test } from 'vitest';
2
+ import { localeCurrency, localeNumber, localeDate, localePercent, localeUnit, defineLocales, localeDatePattern } from './locale';
3
+
4
+ const messagesFr = { lang: 'fr' };
5
+ const messagesEn = { lang: 'en' };
6
+ const messages = { en: messagesEn, fr: messagesFr };
7
+
8
+ describe('locale', () => {
9
+ describe.each(['en', 'fr'])('locale: %s', locale => {
10
+ describe('localeCurrency', () => {
11
+ test('Should Format number to the locale currency', () => {
12
+ const formatedCurrency = localeCurrency(1234567890.12, locale, 'EUR');
13
+ expect(formatedCurrency).toEqual(locale === 'en' ? '€1,234,567,890.12' : '1 234 567 890,12\xa0€');
14
+ });
15
+ });
16
+
17
+ describe('localeNumber', () => {
18
+ test('Should Format number to the locale', () => {
19
+ const formatedCurrency = localeNumber(1234567890.12, locale);
20
+ expect(formatedCurrency).toEqual(locale === 'en' ? '1,234,567,890.12' : '1 234 567 890,12');
21
+ });
22
+ test('Should Format number to the locale and manage 00 in decimal returned value', () => {
23
+ const formatedCurrency = localeNumber(1234567890, locale, 2);
24
+ expect(formatedCurrency).toEqual(locale === 'en' ? '1,234,567,890.00' : '1 234 567 890,00');
25
+ });
26
+ test.each([0, 5])('Should Format number to the locale and format the decimal length, case length %s', length => {
27
+ const formatedCurrency = localeNumber(1234567890, locale, length);
28
+ const decimal = length > 0 ? '00000' : null;
29
+ const localePoint = locale === 'en' ? '.' : ',';
30
+ const integer = locale === 'en' ? '1,234,567,890' : '1 234 567 890';
31
+ expect(formatedCurrency).toEqual(integer + (decimal ? localePoint + decimal : ''));
32
+ });
33
+ });
34
+
35
+ describe('localeDatePattern', () => {
36
+ test.each([
37
+ { locale: 'fr', expected: 'dd/mm/yyyy' },
38
+ { locale: 'en', expected: 'mm/dd/yyyy' },
39
+ ])('Should get date pattern', ({ locale, expected }) => {
40
+ const pattern = localeDatePattern(locale);
41
+ expect(pattern).toEqual(expected);
42
+ });
43
+ });
44
+
45
+ describe('localeDate', () => {
46
+ test.each([undefined, '', 'blu'])('Should return empty string: %s', date => {
47
+ const formatedDate = localeDate(date, locale);
48
+ expect(formatedDate).toEqual('');
49
+ });
50
+
51
+ test('Should return formated date', () => {
52
+ const formatedDate = localeDate('2022-06-02', locale);
53
+ expect(formatedDate).toEqual(locale === 'en' ? '6/2/2022' : '02/06/2022');
54
+ });
55
+
56
+ test('Should return formated date with given timeZone config', () => {
57
+ const formatedDate = localeDate('2022-06-02', locale, { timeZone: 'America/New_York' });
58
+ expect(formatedDate).toEqual(locale === 'en' ? '6/1/2022' : '01/06/2022');
59
+ });
60
+ });
61
+
62
+ describe('defineLocales', () => {
63
+ test('Should return navigator locale', () => {
64
+ const locales = defineLocales(messages, locale)(document.createElement('div'));
65
+ expect(locales.locale).toEqual('en-US');
66
+ expect(locales.messages).toMatchObject(messagesEn);
67
+ });
68
+
69
+ test('Should return default locale', () => {
70
+ const navigatorBackup = window.navigator;
71
+ globalThis.window.navigator = {} as Navigator;
72
+ const locales = defineLocales(messages, locale)(document.createElement('div'));
73
+ expect(locales.locale).toEqual(locale);
74
+ expect(locales.messages).toMatchObject({ lang: locale });
75
+
76
+ // reset default navigator default value
77
+ globalThis.window.navigator = navigatorBackup;
78
+ });
79
+
80
+ test('Should return matching locale', () => {
81
+ const div = document.createElement('div');
82
+ div.lang = 'fr-FR';
83
+ const locales = defineLocales(messages, locale)(div);
84
+ expect(locales.locale).toEqual(div.lang);
85
+ expect(locales.messages).toMatchObject(messagesFr);
86
+ });
87
+
88
+ test('Should return default locale messages when requested does not exist', () => {
89
+ const div = document.createElement('div');
90
+ div.lang = 'ca';
91
+ const locales = defineLocales(messages, locale)(div);
92
+ expect(locales.locale).toEqual(div.lang);
93
+ expect(locales.messages).toMatchObject({ lang: locale });
94
+ });
95
+
96
+ test('Should handle empty messages object', () => {
97
+ const div = document.createElement('div');
98
+ div.lang = 'fr';
99
+ const locales = defineLocales({}, 'en')(div);
100
+ expect(locales.locale).toEqual('fr');
101
+ expect(locales.messages).toMatchObject({ lang: 'en' });
102
+ });
103
+
104
+ test('Should return default object when messages and default locale are not found', () => {
105
+ const div = document.createElement('div');
106
+ div.lang = 'fr';
107
+ const locales = defineLocales({ it: { lang: 'it' } }, 'es')(div);
108
+ expect(locales.locale).toEqual('fr');
109
+ expect(locales.messages).toMatchObject({ lang: 'es' });
110
+ });
111
+ });
112
+
113
+ describe('localePercent', () => {
114
+ test.each([
115
+ [0.42, 'en', 2, '42.00%'],
116
+ [0.42, 'fr', 2, '42,00 %'],
117
+ [1.23, 'en', 1, '123.0%'],
118
+ [1.23, 'fr', 1, '123,0 %'],
119
+ [0, 'fr', 0, '0 %'],
120
+ [0, 'en', 0, '0%'],
121
+ [1, 'fr', 0, '100 %'],
122
+ [1, 'en', 0, '100%'],
123
+ [-0.5, 'fr', 2, '-50,00 %'],
124
+ [-0.5, 'en', 2, '-50.00%'],
125
+ [Number.POSITIVE_INFINITY, 'fr', 0, '∞ %'],
126
+ [Number.POSITIVE_INFINITY, 'en', 0, '∞%'],
127
+ [Number.NEGATIVE_INFINITY, 'fr', 0, '-∞ %'],
128
+ [Number.NEGATIVE_INFINITY, 'en', 0, '-∞%'],
129
+ [NaN, 'fr', 0, 'NaN %'],
130
+ [NaN, 'en', 0, 'NaN%'],
131
+ ])('Should format %s value correctly for locale %s with %s decimals', (value, locale, decimals, expected) => {
132
+ const result = localePercent(value, locale, decimals);
133
+ // Normalize spaces before comparison
134
+ expect(result.replace(/\s/g, ' ')).toBe(expected.replace(/\s/g, ' '));
135
+ });
136
+
137
+ test('Should handle undefined decimal length', () => {
138
+ expect(localePercent(0.42, 'fr').replace(/\s/g, ' ')).toBe('42 %'.replace(/\s/g, ' '));
139
+ expect(localePercent(0.42, 'en').replace(/\s/g, ' ')).toBe('42%'.replace(/\s/g, ' '));
140
+ });
141
+ });
142
+
143
+ describe('localeUnit', () => {
144
+ test.each([
145
+ [1234567890.12, 'fr', 'kilometer', 'short', 2, '1 234 567 890,12 km'],
146
+ [23, 'fr', 'celsius', 'short', 0, '23 °C'],
147
+ [10, 'fr', 'kilometer', 'long', 0, '10 kilomètres'],
148
+ [1234567890.12, 'en', 'kilometer', 'short', 2, '1,234,567,890.12 km'],
149
+ [23, 'en', 'celsius', 'short', 0, '23°C'],
150
+ [10, 'en', 'kilometer', 'long', 0, '10 kilometers'],
151
+ ])('Should format %s value correctly for locale %s with unit %s', (value, locale, unit, unitDisplay, decimals, expected) => {
152
+ const result = localeUnit(value, locale, unit, unitDisplay as Intl.NumberFormatOptions['unitDisplay'], decimals);
153
+ // Normalize spaces before comparison
154
+ expect(result.replace(/\s/g, ' ')).toBe(expected.replace(/\s/g, ' '));
155
+ });
156
+
157
+ test('Should respect decimal length', () => {
158
+ expect(localeUnit(1234.567, 'en', 'kilometer', 'short', 2).replace(/\s/g, ' ')).toBe('1,234.57 km'.replace(/\s/g, ' '));
159
+ expect(localeUnit(1234.567, 'fr', 'kilometer', 'short', 2).replace(/\s/g, ' ')).toBe('1 234,57 km'.replace(/\s/g, ' '));
160
+ });
161
+
162
+ test('Should use default unitDisplay and decimalLength when not provided', () => {
163
+ expect(localeUnit(1234, 'en', 'kilometer').replace(/\s/g, ' ')).toBe('1,234 km');
164
+ expect(localeUnit(1234, 'fr', 'kilometer').replace(/\s/g, ' ')).toBe('1 234 km');
165
+ });
166
+
167
+ test('Should use default unitDisplay when only decimalLength is provided', () => {
168
+ expect(localeUnit(1234.567, 'en', 'kilometer', undefined, 2).replace(/\s/g, ' ')).toBe('1,234.57 km');
169
+ expect(localeUnit(1234.567, 'fr', 'kilometer', undefined, 2).replace(/\s/g, ' ')).toBe('1 234,57 km');
170
+ });
171
+ });
172
+ });
173
+ });
@@ -0,0 +1,166 @@
1
+ import { dateRegExp } from '../utils/date';
2
+ import type { ObjectType } from '../utils/object';
3
+
4
+ /**
5
+ * Gets the date pattern based on the specified locale.
6
+ * @param locale - the locale to refer to
7
+ * @returns date pattern
8
+ * @example
9
+ * ```ts
10
+ * localeDatePattern('fr') // 'dd/mm/yyyy'
11
+ * ```
12
+ */
13
+ export const localeDatePattern = (locale: string) => {
14
+ const year = { value: '2023', pattern: 'yyyy' };
15
+ const month = { value: '12', pattern: 'mm' };
16
+ const day = { value: '24', pattern: 'dd' };
17
+ return localeDate([year.value, month.value, day.value].join('-'), locale, { timeZone: 'UTC' })
18
+ .replace(year.value, year.pattern)
19
+ .replace(month.value, month.pattern)
20
+ .replace(day.value, day.pattern);
21
+ };
22
+
23
+ /**
24
+ * Get locale and messages
25
+ * We load the defined locale but for now we only support the first subtag for messages
26
+ * @param element - element we need to get the language
27
+ * @param messages - messages to use
28
+ * @param defaultLocale - default messages locale
29
+ * @returns messages object
30
+ */
31
+ const localeMessages = (element: HTMLElement, messages: ObjectType, defaultLocale: string): { locale: string; messages: ObjectType } => {
32
+ // Get local
33
+ const closestLangAttribute: HTMLElement | null = element.closest('[lang]');
34
+ const closestLang: string[] = Intl.NumberFormat.supportedLocalesOf(closestLangAttribute?.lang as string);
35
+ const locale = closestLang.length > 0 && typeof closestLang[0] === 'string' ? closestLang[0] : navigator.language || defaultLocale;
36
+ // Only keep first subtag
37
+ const localeSubtag = locale.split('-').shift() as string;
38
+
39
+ // If messages is empty, return a default object
40
+ if (Object.keys(messages).length === 0) {
41
+ return {
42
+ locale,
43
+ messages: { lang: defaultLocale },
44
+ };
45
+ }
46
+
47
+ // Return
48
+ return {
49
+ locale,
50
+ messages: (messages[localeSubtag] || messages[defaultLocale] || { lang: defaultLocale }) as ObjectType,
51
+ };
52
+ };
53
+
54
+ /**
55
+ * Format number to the locale currency
56
+ * @param number - number to format
57
+ * @param locale - locale to apply
58
+ * @param currency - currency to apply
59
+ * @returns formatted currency
60
+ * @example
61
+ * ```ts
62
+ * localeCurrency(1234567890.12, 'fr', 'EUR') // '1 234 567 890,12\xa0€'
63
+ * ```
64
+ */
65
+ export const localeCurrency = (number: number, locale: string, currency: string): string => new Intl.NumberFormat(locale, { style: 'currency', currency }).format(number);
66
+
67
+ /**
68
+ * Format number to locale
69
+ * @param number - number to format
70
+ * @param locale - locale to apply
71
+ * @param decimalLength - decimal length to apply
72
+ * @returns formatted number
73
+ * @example
74
+ * ```ts
75
+ * localeNumber(1234567890.12, 'fr') // 1 234 567 890,12
76
+ * ```
77
+ */
78
+ export const localeNumber = (number: number, locale: string, decimalLength: number = 0): string =>
79
+ new Intl.NumberFormat(locale, { minimumFractionDigits: decimalLength }).format(Number(number));
80
+
81
+ /**
82
+ * Format number as percentage based on locale
83
+ * @param number - number to format
84
+ * @param locale - locale to apply
85
+ * @param decimalLength - decimal length to apply
86
+ * @returns formatted percentage
87
+ * @example
88
+ * ```ts
89
+ * localePercent(0.42, 'fr', 2) // '42,00 %'
90
+ * localePercent(0.42, 'en', 2) // '42.00%'
91
+ * ```
92
+ */
93
+ export const localePercent = (number: number, locale: string, decimalLength: number = 0): string => {
94
+ return new Intl.NumberFormat(locale, {
95
+ style: 'percent',
96
+ minimumFractionDigits: decimalLength,
97
+ maximumFractionDigits: decimalLength,
98
+ }).format(number);
99
+ };
100
+
101
+ /**
102
+ * Format number with standardized unit based on locale using Intl unit formatting
103
+ * @param number - number to format
104
+ * @param locale - locale to apply
105
+ * @param unit - standardized unit (e.g., 'kilometer', 'kilogram', 'celsius')
106
+ * @param unitDisplay - how to display the unit ('short', 'long', 'narrow')
107
+ * @param decimalLength - decimal length to apply
108
+ * @returns formatted number with localized unit
109
+ * @example
110
+ * ```ts
111
+ * localeUnit(1234567890.12, 'fr', 'kilometer') // '1 234 567 890,12 km'
112
+ * localeUnit(23, 'fr', 'celsius') // '23 °C'
113
+ * localeUnit(10, 'fr', 'kilometer', 0, 'long') // '10 kilomètres'
114
+ * ```
115
+ */
116
+ export const localeUnit = (
117
+ number: number,
118
+ locale: string,
119
+ unit: Intl.NumberFormatOptions['unit'],
120
+ unitDisplay: Intl.NumberFormatOptions['unitDisplay'] = 'short',
121
+ decimalLength: number = 0,
122
+ ): string => {
123
+ return new Intl.NumberFormat(locale, {
124
+ style: 'unit',
125
+ unit,
126
+ unitDisplay,
127
+ minimumFractionDigits: decimalLength,
128
+ maximumFractionDigits: decimalLength,
129
+ }).format(number);
130
+ };
131
+
132
+ /**
133
+ * Locale date format
134
+ * @param date - date to format
135
+ * @param locale - locale to apply
136
+ * @param config - DateTimeFormatOptions object to apply
137
+ * @returns formatted date
138
+ * @example
139
+ * ```ts
140
+ * localeDate('2022-06-02', 'fr') // '02/06/2022'
141
+ * ```
142
+ */
143
+ export const localeDate = (date: string | undefined, locale: string, config?: Intl.DateTimeFormatOptions): string =>
144
+ typeof date !== 'string' || date === '' || !dateRegExp.test(date) ? '' : new Intl.DateTimeFormat(locale, config).format(new Date(date));
145
+
146
+ /**
147
+ * Get Intl object
148
+ * @param messages - locales to render in object format. `ex: { en: { porp: "test" }, fr: { porp: "test" }}`.
149
+ * @param defaultLocale - fallback locale to render. `ex: 'en'`.
150
+ * @returns from the element passed in return function you will get the matching messages object
151
+ * @example
152
+ * ```ts
153
+ * import en from './en/messages.json';
154
+ * import fr from './fr/messages.json';
155
+ * import { defineLocales } from '@mgdis/core-ui-helpers/dist/utils';
156
+ *
157
+ * const defaultLocale = 'en';
158
+ * const messages = { en, fr };
159
+ *
160
+ * export const initLocales = defineLocales(messages, defaultLocale);
161
+ * ```
162
+ */
163
+ export const defineLocales =
164
+ (messages: ObjectType, defaultLocale: 'fr' | 'en') =>
165
+ (element: HTMLElement): { locale: string; messages: ObjectType } =>
166
+ localeMessages(element, messages, defaultLocale);
@@ -0,0 +1,43 @@
1
+ import { type PlaywrightTestConfig } from '@playwright/test';
2
+
3
+ const config: PlaywrightTestConfig = {
4
+ testMatch: '*.e2e.ts',
5
+ snapshotPathTemplate: '{testFileDir}/__screenshots__/{arg}-{projectName}{ext}',
6
+ /* Maximum time one test can run for. */
7
+ timeout: 30 * 1000,
8
+ expect: {
9
+ /**
10
+ * Maximum time expect() should wait for the condition to be met.
11
+ * For example in `await expect(locator).toHaveText();`
12
+ */
13
+ timeout: 5000,
14
+ },
15
+ /* Run tests in files in parallel */
16
+ fullyParallel: true,
17
+ /* Fail the build on CI if you accidentally left test.only in the source code. */
18
+ forbidOnly: !!process.env.CI,
19
+ /* Retry on CI only */
20
+ retries: process.env.CI ? 2 : 0,
21
+ /* Stop on CI on first failure */
22
+ maxFailures: process.env.CI ? 1 : 0,
23
+ /* Opt out of parallel tests on CI. */
24
+ workers: process.env.CI ? 1 : undefined,
25
+ /* Reporter to use. See https://playwright.dev/docs/test-reporters */
26
+ reporter: [
27
+ ['html', { open: 'never' }],
28
+ ['junit', { outputFile: 'results.xml' }],
29
+ ],
30
+ /* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */
31
+ use: {
32
+ headless: true,
33
+ /* Maximum time each action such as `click()` can take. Defaults to 0 (no limit). */
34
+ actionTimeout: 0,
35
+ /* Base URL to use in actions like `await page.goto('/')`. */
36
+ // baseURL: 'http://localhost:3000',
37
+
38
+ /* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */
39
+ trace: 'on-first-retry',
40
+ },
41
+ };
42
+
43
+ export default config;
@@ -0,0 +1,16 @@
1
+ import { describe, expect, test } from 'vitest';
2
+ import { playwrightBaseConfig, renderAttributes, renderProperties } from '.';
3
+
4
+ describe('playwright', () => {
5
+ describe('config', () => {
6
+ test('import', () => {
7
+ expect(playwrightBaseConfig).toBeDefined();
8
+ });
9
+ });
10
+ describe('utils', () => {
11
+ test('import', () => {
12
+ expect(renderAttributes).toBeDefined();
13
+ expect(renderProperties).toBeDefined();
14
+ });
15
+ });
16
+ });
@@ -0,0 +1,4 @@
1
+ import playwrightBaseConfig from './config';
2
+ import { renderAttributes, renderProperties } from './utils';
3
+
4
+ export { playwrightBaseConfig, renderAttributes, renderProperties };
@@ -0,0 +1,48 @@
1
+ // Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
2
+
3
+ exports[`utils > renderAttributes > Should render attributes 1`] = `""`;
4
+
5
+ exports[`utils > renderAttributes > Should render attributes 2`] = `""`;
6
+
7
+ exports[`utils > renderAttributes > Should render attributes 3`] = `""`;
8
+
9
+ exports[`utils > renderAttributes > Should render attributes 4`] = `"name="batman""`;
10
+
11
+ exports[`utils > renderAttributes > Should render attributes 5`] = `"name="<div class='blu'>blu</div>""`;
12
+
13
+ exports[`utils > renderAttributes > Should render attributes 6`] = `"name="batman" user="bruce" active="true" id="1""`;
14
+
15
+ exports[`utils > renderAttributes > Should render attributes 7`] = `"empty-string="""`;
16
+
17
+ exports[`utils > renderAttributes > Should render attributes 8`] = `"name="0""`;
18
+
19
+ exports[`utils > renderAttributes > Should render attributes 9`] = `""`;
20
+
21
+ exports[`utils > renderAttributes > Should render attributes 10`] = `"name="""`;
22
+
23
+ exports[`utils > renderAttributes > Should render attributes 11`] = `""`;
24
+
25
+ exports[`utils > renderAttributes > Should render attributes 12`] = `""`;
26
+
27
+ exports[`utils > renderAttributes > Should render attributes 13`] = `""`;
28
+
29
+ exports[`utils > renderProperties > Should not render attributes as properties 1`] = `""`;
30
+
31
+ exports[`utils > renderProperties > Should not render attributes as properties 2`] = `""`;
32
+
33
+ exports[`utils > renderProperties > Should not render attributes as properties 3`] = `""`;
34
+
35
+ exports[`utils > renderProperties > Should not render attributes as properties 4`] = `
36
+ "
37
+ "
38
+ `;
39
+
40
+ exports[`utils > renderProperties > Should render properties, case id selector 1`] = `
41
+ "
42
+ document.querySelector('div').object={};document.querySelector('div').array=[]"
43
+ `;
44
+
45
+ exports[`utils > renderProperties > Should render properties, case id selector 2`] = `
46
+ "
47
+ document.querySelector('div').object={};document.querySelector('div').array=[];document.querySelector('div').fn=() => {\\n }"
48
+ `;
@@ -0,0 +1 @@
1
+ export * from './utils';
@@ -0,0 +1,43 @@
1
+ import { describe, expect, test } from 'vitest';
2
+ import { renderAttributes, renderProperties } from './utils';
3
+
4
+ describe('utils', () => {
5
+ describe('renderAttributes', () => {
6
+ test.each([
7
+ undefined,
8
+ null,
9
+ {},
10
+ { name: 'batman' },
11
+ { name: '<div class="blu">blu</div>' },
12
+ { name: 'batman', user: 'bruce', active: true, id: 1, object: {}, array: [], function: () => {} },
13
+ { emptyString: '' },
14
+ { name: 0 },
15
+ { name: false },
16
+ { name: ' ' },
17
+ { name: null },
18
+ { name: undefined },
19
+ ' ',
20
+ ])('Should render attributes', args => {
21
+ const res = renderAttributes(args as Record<string, unknown>);
22
+ expect(res).toMatchSnapshot();
23
+ });
24
+ });
25
+
26
+ describe('renderProperties', () => {
27
+ test('Should render properties, case id selector', () => {
28
+ const res = renderProperties({ object: {} }, '#id');
29
+ expect(res).toEqual("\n document.getElementById('id').object={}");
30
+ });
31
+ test.each([undefined, null, {}, { name: 'batman' }])('Should not render attributes as properties', args => {
32
+ const res = renderProperties(args as Record<string, unknown>, 'div');
33
+ expect(res).toMatchSnapshot();
34
+ });
35
+ test.each([undefined, () => {}].map(fn => ({ name: 'batman', user: 'bruce', active: true, id: 1, object: {}, array: [], fn })))(
36
+ 'Should render properties, case id selector',
37
+ args => {
38
+ const res = renderProperties(args, 'div');
39
+ expect(res).toMatchSnapshot();
40
+ },
41
+ );
42
+ });
43
+ });
@@ -0,0 +1,64 @@
1
+ import { isObject, isValidString } from '../../utils';
2
+
3
+ /**
4
+ * Render attributes from props objects
5
+ * @param args - argument to render as string. ex: `{status: 'visible'}`
6
+ * @returns formated inline attributed. ex: 'status="visible"'
7
+ * @example
8
+ * ```ts
9
+ * import { renderAttributes } from '@mgdis/core-ui-helpers/dist/playwright';
10
+ *
11
+ * const attributes = renderAttributes({ status: 'visible', color: 'red' });
12
+ * console.log(attributes); // Output: 'status="visible" color="red"'
13
+ * ```
14
+ */
15
+ export const renderAttributes = (args: Record<string, unknown>): string =>
16
+ (isObject<Record<string, never>>(args) &&
17
+ Object.keys(args)
18
+ .filter(key => ![null, undefined, false].includes(args[key]) && !['object', 'function'].includes(typeof args[key]))
19
+ .map(key => {
20
+ const attribute: string = key.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
21
+ const value: string = ['number', 'boolean'].includes(typeof args[key]) || isValidString(args[key]) ? String(args[key]).replace(/"/g, "'") : '';
22
+ return `${attribute}="${value}"`;
23
+ })
24
+ .join(' ')) ||
25
+ '';
26
+
27
+ /**
28
+ * Render properties from props objects.
29
+ * Insert return value in <script></script> element
30
+ * @param args - argument to render as script. ex: `{status: 'visible'}`
31
+ * @param selector - querySelector get targetted element and bind properties on it
32
+ * @returns stringified properties script
33
+ * @example
34
+ * ```ts
35
+ * import { renderProperties } from '@mgdis/core-ui-helpers/dist/playwright';
36
+ *
37
+ * const propertiesScript = renderProperties({ status: 'visible', color: 'red' }, '.targetElement');
38
+ * console.log(propertiesScript);
39
+ * // Output: 'document.querySelector(".targetElement").status="visible"; document.querySelector(".targetElement").color="red";'
40
+ * ```
41
+ */
42
+ export const renderProperties = (args: Record<string, unknown>, selector: string): string => {
43
+ // has generated id selector starting with "#" create charcters (ex: '#0j3xzw4w7m') make test crashed sometime with "querySelector"
44
+ // we use "getElementById" document query
45
+ const query: 'querySelector' | 'getElementById' = selector.startsWith('#') ? 'getElementById' : 'querySelector';
46
+ if (query === 'getElementById') selector = selector.replace('#', '');
47
+
48
+ return args !== null && typeof args === 'object' && Object.keys(args).length > 0
49
+ ? `
50
+ ${
51
+ Object.keys(args)
52
+ .filter(key => ['object', 'function'].includes(typeof (args as Record<string, never>)[key]))
53
+ .map(key => {
54
+ const value = JSON.stringify((args as Record<string, never>)[key], (_key, val) => (typeof val === 'function' ? `<fn>${val}</fn>` : val));
55
+ return `document.${query}('${selector}').${key}=${value}`;
56
+ }) // stringify json AND keep function values
57
+ .join(';') // create string
58
+ .split('"<fn>') // remove fn start decorator
59
+ .join('')
60
+ .split('</fn>"')
61
+ .join('') // remove fn end decorator
62
+ }`
63
+ : '';
64
+ };