@empathyco/x-archetype-utils 2.0.0-alpha.2 → 2.0.0-alpha.20

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.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # x-archetype-utils
2
2
 
3
- `x-archetype-utils` is a library that provides utilities to ease development. It's used in the [Interface X Archetype](https://github.com/empathyco/x-archetype) project.
3
+ `x-archetype-utils` is a library that provides utilities to ease development. It's used in the [Interface X Archetype](https://github.com/empathyco/x-archetype) project.
4
4
 
5
5
  ## Contributing
6
6
 
@@ -1,14 +1,14 @@
1
1
  'use strict';
2
2
 
3
- const rollupCssInjectorConfig = {
4
- replace: {
5
- // Replace X CSS injector by our custom one.
6
- 'export default injectCss;': 'export default (css) => window.xCSSInjector.addStyle({ source: css });',
7
- delimiters: ['', '']
8
- },
9
- styles: {
10
- mode: ['inject', (varname) => `window.xCSSInjector.addStyle({ source: ${varname} });`]
11
- }
3
+ const rollupCssInjectorConfig = {
4
+ replace: {
5
+ // Replace X CSS injector by our custom one.
6
+ 'export default injectCss': 'export default (css) => window.xCSSInjector.addStyle({ source: css });',
7
+ delimiters: ['', ''],
8
+ },
9
+ styles: {
10
+ mode: ['inject', (varname) => `window.xCSSInjector.addStyle({ source: ${varname} });`],
11
+ },
12
12
  };
13
13
 
14
14
  exports.rollupCssInjectorConfig = rollupCssInjectorConfig;
@@ -1,26 +1,26 @@
1
1
  'use strict';
2
2
 
3
- const webpackConfig = {
4
- transpileDependencies: ['@empathyco/x-components'],
5
- configureWebpack: {
6
- module: {
7
- rules: [
8
- {
9
- test: /\.ts|js|vue$/,
10
- enforce: 'pre',
11
- use: ['source-map-loader']
12
- }
13
- ]
14
- },
15
- output: {
16
- devtoolModuleFilenameTemplate: ({ resourcePath, hash, query }) => resourcePath.match(/\.vue$/) &&
17
- !query.match(/type=script/) &&
18
- !query.match(/\?rollup-plugin-vue=script.ts/)
19
- ? `webpack-generated:///${resourcePath}?${hash}`
20
- : `sources://${resourcePath}`,
21
- devtoolFallbackModuleFilenameTemplate: 'webpack:///[resource-path]?[hash]'
22
- }
23
- }
3
+ const webpackConfig = {
4
+ transpileDependencies: ['@empathyco/x-components'],
5
+ configureWebpack: {
6
+ module: {
7
+ rules: [
8
+ {
9
+ test: /\.ts|js|vue$/,
10
+ enforce: 'pre',
11
+ use: ['source-map-loader'],
12
+ },
13
+ ],
14
+ },
15
+ output: {
16
+ devtoolModuleFilenameTemplate: ({ resourcePath, hash, query, }) => resourcePath.match(/\.vue$/) &&
17
+ !query.match(/type=script/) &&
18
+ !query.match(/\?rollup-plugin-vue=script.ts/)
19
+ ? `webpack-generated:///${resourcePath}?${hash}`
20
+ : `sources://${resourcePath}`,
21
+ devtoolFallbackModuleFilenameTemplate: 'webpack:///[resource-path]?[hash]',
22
+ },
23
+ },
24
24
  };
25
25
 
26
26
  exports.webpackConfig = webpackConfig;
@@ -1,80 +1,93 @@
1
1
  'use strict';
2
2
 
3
- /**
4
- * Instance of the injector that will be used across all the initializations.
5
- */
6
- let instance = null;
7
- /**
8
- * Custom CSS injector that allows to inject styles into a host element.
9
- *
10
- * @public
11
- */
12
- class CssInjector {
13
- /**
14
- * Initializes the instance of the injector if it's not already initialized and sets it in the
15
- * window object if it's required.
16
- *
17
- * @param setInWindow - Whether to set the injector instance in the window object.
18
- */
19
- constructor(setInWindow = true) {
20
- this.stylesQueue = [];
21
- if (!(instance instanceof CssInjector)) {
22
- // eslint-disable-next-line @typescript-eslint/no-this-alias
23
- instance = this;
24
- }
25
- if (setInWindow) {
26
- this.setInWindow();
27
- }
28
- return instance;
29
- }
30
- /**
31
- * Adds the styles to the host element.
32
- *
33
- * @param styles - The styles to be added.
34
- */
35
- addStyle(styles) {
36
- this.stylesQueue.push(styles.source);
37
- if (this.host) {
38
- this.stylesQueue.forEach(styles => {
39
- const styleTag = document.createElement('style');
40
- styleTag.textContent = styles;
41
- this.host.appendChild(styleTag);
42
- });
43
- this.stylesQueue = [];
44
- }
45
- }
46
- /**
47
- * Sets the host element.
48
- *
49
- * @param host - The host element.
50
- */
51
- setHost(host) {
52
- this.host = host;
53
- }
54
- /**
55
- * Sets the injector instance in the window object.
56
- */
57
- setInWindow() {
58
- if (typeof window !== 'undefined' && instance) {
59
- window.xCSSInjector = instance;
60
- }
61
- }
62
- /**
63
- * Checks if the injector instance is in the window object.
64
- *
65
- * @returns Whether the injector instance is in the window object.
66
- */
67
- isInWindow() {
68
- return typeof window === 'undefined'
69
- ? false
70
- : window.xCSSInjector === instance;
71
- }
72
- }
73
- /**
74
- * Instance of the injector.
75
- *
76
- * @public
77
- */
3
+ /** Singleton instance of the injector that will be used across all the initializations. */
4
+ let instance = null;
5
+ /**
6
+ * Custom CSS injector that allows to inject styles into a host element.
7
+ *
8
+ * @public
9
+ */
10
+ class CssInjector {
11
+ /**
12
+ * Initializes the instance of the injector if it's not already initialized and sets it in the
13
+ * window object if it's required.
14
+ *
15
+ * @param setInWindow - Whether to set the injector instance in the window object.
16
+ */
17
+ constructor(setInWindow = true) {
18
+ this.hosts = new Set();
19
+ this.stylesToAdopt = [];
20
+ if (!(instance instanceof CssInjector)) {
21
+ // eslint-disable-next-line ts/no-this-alias
22
+ instance = this;
23
+ }
24
+ if (setInWindow) {
25
+ this.setInWindow();
26
+ }
27
+ return instance;
28
+ }
29
+ /**
30
+ * Adds the style to the host element.
31
+ *
32
+ * @param style - The styles to be added.
33
+ * @param style.source - Styles source.
34
+ */
35
+ addStyle(style) {
36
+ const sheet = new CSSStyleSheet();
37
+ sheet.replaceSync(style.source);
38
+ this.stylesToAdopt.push(sheet);
39
+ this.hosts.forEach(host => (host.adoptedStyleSheets = this.stylesToAdopt));
40
+ }
41
+ /**
42
+ * Sets the host element. Alias of addHost method.
43
+ *
44
+ * @param host - The host element.
45
+ * @deprecated Use addHost instead.
46
+ */
47
+ setHost(host) {
48
+ this.addHost(host instanceof ShadowRoot ? host : document);
49
+ }
50
+ /**
51
+ * Adds the element to the hosts set.
52
+ *
53
+ * @param host - The host element.
54
+ */
55
+ addHost(host) {
56
+ this.hosts.add(host);
57
+ host.adoptedStyleSheets = this.stylesToAdopt;
58
+ }
59
+ /**
60
+ * Removes the element from the hosts set.
61
+ *
62
+ * @param host - The host element to remove.
63
+ */
64
+ removeHost(host) {
65
+ this.hosts.delete(host);
66
+ }
67
+ /**
68
+ * Sets the injector instance in the window object.
69
+ */
70
+ setInWindow() {
71
+ if (typeof window !== 'undefined' && instance) {
72
+ window.xCSSInjector = instance;
73
+ }
74
+ }
75
+ /**
76
+ * Checks if the injector instance is in the window object.
77
+ *
78
+ * @returns Whether the injector instance is in the window object.
79
+ */
80
+ isInWindow() {
81
+ return typeof window === 'undefined'
82
+ ? false
83
+ : window.xCSSInjector === instance;
84
+ }
85
+ }
86
+ /**
87
+ * Instance of the injector.
88
+ *
89
+ * @public
90
+ */
78
91
  const cssInjector = new CssInjector(typeof window !== 'undefined');
79
92
 
80
93
  exports.CssInjector = CssInjector;
@@ -1,137 +1,139 @@
1
1
  'use strict';
2
2
 
3
+ var xDeepMerge = require('@empathyco/x-deep-merge');
3
4
  var xUtils = require('@empathyco/x-utils');
4
5
  var vueI18n = require('vue-i18n');
5
- var xDeepMerge = require('@empathyco/x-deep-merge');
6
6
 
7
- /**
8
- * I18n settings manager.
9
- *
10
- * @public
11
- */
12
- class I18n {
13
- /**
14
- * Constructs a new {@link I18n} instance with the passed {@link I18nOptions | i18n options}.
15
- *
16
- * @param options - The new {@link I18nOptions | i18n options}.
17
- */
18
- constructor({ locale, messages, device, fallbackLocale }) {
19
- this.locale = locale;
20
- this.device = device;
21
- this.messages = messages;
22
- this.fallbackLocale = fallbackLocale;
23
- }
24
- /**
25
- * Creates a new {@link I18n} instance.
26
- *
27
- * @param options - The new {@link I18nOptions | i18n options}.
28
- *
29
- * @returns The new instance.
30
- */
31
- static async create(options) {
32
- const instance = new I18n(options);
33
- instance.currentMessages = await instance.getCurrentMessages();
34
- return instance;
35
- }
36
- /**
37
- * Installs VueI18n plugin.
38
- *
39
- * @param vue - The Vue instance.
40
- */
41
- install(vue) {
42
- this.vueI18n = vueI18n.createI18n({
43
- locale: this.locale,
44
- silentFallbackWarn: true,
45
- messages: this.currentMessages ? { [this.locale]: this.currentMessages } : {},
46
- missing: (_, key) => {
47
- var _a;
48
- return ((_a = this.getMessageWithDotsInKey(key)) !== null && _a !== void 0 ? _a : `[i18n] Key '${key}' is missing for locale: '${this.locale}'`);
49
- }
50
- });
51
- // eslint-disable-next-line @typescript-eslint/no-unsafe-call
52
- vue.use(this.vueI18n);
53
- }
54
- /**
55
- * Tries to get a value from the messages object accessing it key by key.
56
- * When a key fails, takes the remaining key parts and tries to access the message
57
- * joining them into a single key.
58
- *
59
- * @param path - A dot separated key to access the message object.
60
- * @returns The message corresponding to the provided key, or empty string if it doesn't exist.
61
- */
62
- getMessageWithDotsInKey(path) {
63
- // TO-DO Support function or array messages
64
- const message = path
65
- .split('.')
66
- .reduce((messages, key, index, pathParts) => {
67
- var _a;
68
- return xUtils.isObject(messages)
69
- ? (_a = messages[key]) !== null && _a !== void 0 ? _a : messages[pathParts.slice(index).join('.')]
70
- : messages;
71
- }, this.currentMessages);
72
- return typeof message === 'string' ? message : null;
73
- }
74
- /**
75
- * Sets the new locale and updates the messages accordingly.
76
- *
77
- * @param newLocale - The new locale.
78
- *
79
- * @returns The new messages.
80
- */
81
- async setLocale(newLocale) {
82
- if (this.locale !== newLocale) {
83
- this.locale = newLocale;
84
- await this.changeMessages();
85
- this.vueI18n.global.locale = this.locale;
86
- }
87
- }
88
- /**
89
- * Sets the new device and updates the messages accordingly.
90
- *
91
- * @param newDevice - The new device.
92
- *
93
- * @returns The new messages.
94
- */
95
- async setDevice(newDevice) {
96
- if (this.device !== newDevice) {
97
- this.device = newDevice;
98
- await this.changeMessages();
99
- }
100
- }
101
- /**
102
- * Updates the current messages based on the new locale and/or device.
103
- */
104
- async changeMessages() {
105
- this.currentMessages = await this.getCurrentMessages();
106
- // eslint-disable-next-line @typescript-eslint/no-unsafe-call
107
- this.vueI18n.global.setLocaleMessage(this.locale, this.currentMessages);
108
- }
109
- /**
110
- * Retrieves the corresponding messages for the set locale and device.
111
- *
112
- * @remarks By default, it merges `base` messages with the specific `device` ones. If there are
113
- * no messages for the current locale, the fallback locale is used instead.
114
- *
115
- * @returns The messages for the current locale and device.
116
- */
117
- async getCurrentMessages() {
118
- const rawMessages = this.locale in this.messages
119
- ? this.messages[this.locale]
120
- : this.messages[this.fallbackLocale];
121
- const messages = areLazyMessages(rawMessages) ? (await rawMessages()).default : rawMessages;
122
- // eslint-disable-next-line @typescript-eslint/no-unsafe-call
123
- return xDeepMerge.deepMerge({}, messages.base, messages[this.device]);
124
- }
125
- }
126
- /**
127
- * Type-guard to check if the passed messages should be lazy-loaded.
128
- *
129
- * @param messages - The messages to check.
130
- *
131
- * @returns True if the messages are lazy or false otherwise.
132
- */
133
- function areLazyMessages(messages) {
134
- return typeof messages === 'function';
7
+ /**
8
+ * I18n settings manager.
9
+ *
10
+ * @public
11
+ */
12
+ class I18n {
13
+ /**
14
+ * Constructs a new {@link I18n} instance with the passed {@link I18nOptions | i18n options}.
15
+ *
16
+ * @param options - The new {@link I18nOptions | i18n options}.
17
+ * @param options.locale - i18n locale.
18
+ * @param options.messages - i18n messages.
19
+ * @param options.device - i18n device.
20
+ * @param options.fallbackLocale - i18n fallbackLocale.
21
+ */
22
+ constructor({ locale, messages, device, fallbackLocale }) {
23
+ this.locale = locale;
24
+ this.device = device;
25
+ this.messages = messages;
26
+ this.fallbackLocale = fallbackLocale;
27
+ }
28
+ /**
29
+ * Creates a new {@link I18n} instance.
30
+ *
31
+ * @param options - The new {@link I18nOptions | i18n options}.
32
+ *
33
+ * @returns The new instance.
34
+ */
35
+ static async create(options) {
36
+ const instance = new I18n(options);
37
+ instance.currentMessages = await instance.getCurrentMessages();
38
+ return instance;
39
+ }
40
+ /**
41
+ * Installs VueI18n plugin.
42
+ *
43
+ * @param vue - The Vue instance.
44
+ */
45
+ install(vue) {
46
+ this.vueI18n = vueI18n.createI18n({
47
+ legacy: false,
48
+ locale: this.locale,
49
+ silentFallbackWarn: true,
50
+ // eslint-disable-next-line ts/no-unsafe-assignment
51
+ messages: this.currentMessages ? { [this.locale]: this.currentMessages } : {},
52
+ missing: (_, key) => {
53
+ var _a;
54
+ return ((_a = this.getMessageWithDotsInKey(key)) !== null && _a !== void 0 ? _a : `[i18n] Key '${key}' is missing for locale: '${this.locale}'`);
55
+ },
56
+ });
57
+ vue.use(this.vueI18n);
58
+ }
59
+ /**
60
+ * Tries to get a value from the messages object accessing it key by key.
61
+ * When a key fails, takes the remaining key parts and tries to access the message
62
+ * joining them into a single key.
63
+ *
64
+ * @param path - A dot separated key to access the message object.
65
+ * @returns The message corresponding to the provided key, or empty string if it doesn't exist.
66
+ */
67
+ getMessageWithDotsInKey(path) {
68
+ // TO-DO Support function or array messages
69
+ // eslint-disable-next-line ts/no-unsafe-assignment
70
+ const message = path.split('.').reduce((messages, key, index, pathParts) => {
71
+ var _a;
72
+ // eslint-disable-next-line ts/no-unsafe-return
73
+ return xUtils.isObject(messages)
74
+ ? ((_a = messages[key]) !== null && _a !== void 0 ? _a : messages[pathParts.slice(index).join('.')])
75
+ : messages;
76
+ }, this.currentMessages);
77
+ return typeof message === 'string' ? message : null;
78
+ }
79
+ /**
80
+ * Sets the new locale and updates the messages accordingly.
81
+ *
82
+ * @param newLocale - The new locale.
83
+ *
84
+ * @returns The new messages.
85
+ */
86
+ async setLocale(newLocale) {
87
+ if (this.locale !== newLocale) {
88
+ this.locale = newLocale;
89
+ await this.changeMessages();
90
+ this.vueI18n.global.locale.value = this.locale;
91
+ }
92
+ }
93
+ /**
94
+ * Sets the new device and updates the messages accordingly.
95
+ *
96
+ * @param newDevice - The new device.
97
+ *
98
+ * @returns The new messages.
99
+ */
100
+ async setDevice(newDevice) {
101
+ if (this.device !== newDevice) {
102
+ this.device = newDevice;
103
+ await this.changeMessages();
104
+ }
105
+ }
106
+ /**
107
+ * Updates the current messages based on the new locale and/or device.
108
+ */
109
+ async changeMessages() {
110
+ this.currentMessages = await this.getCurrentMessages();
111
+ this.vueI18n.global.setLocaleMessage(this.locale, this.currentMessages);
112
+ }
113
+ /**
114
+ * Retrieves the corresponding messages for the set locale and device.
115
+ *
116
+ * @remarks By default, it merges `base` messages with the specific `device` ones. If there are
117
+ * no messages for the current locale, the fallback locale is used instead.
118
+ *
119
+ * @returns The messages for the current locale and device.
120
+ */
121
+ async getCurrentMessages() {
122
+ const rawMessages = this.locale in this.messages ? this.messages[this.locale] : this.messages[this.fallbackLocale];
123
+ const messages = areLazyMessages(rawMessages) ? (await rawMessages()).default : rawMessages;
124
+ // eslint-disable-next-line ts/no-unsafe-return
125
+ return xDeepMerge.deepMerge({}, messages.base, messages[this.device]);
126
+ }
127
+ }
128
+ /**
129
+ * Type-guard to check if the passed messages should be lazy-loaded.
130
+ *
131
+ * @param messages - The messages to check.
132
+ *
133
+ * @returns True if the messages are lazy or false otherwise.
134
+ */
135
+ function areLazyMessages(messages) {
136
+ return typeof messages === 'function';
135
137
  }
136
138
 
137
139
  exports.I18n = I18n;
package/dist/cjs/index.js CHANGED
@@ -1,14 +1,14 @@
1
1
  'use strict';
2
2
 
3
- var i18n_plugin = require('./i18n/i18n.plugin.js');
4
- var webpack_config = require('./build/webpack/webpack.config.js');
5
3
  var rollup_config = require('./build/rollup/rollup.config.js');
4
+ var webpack_config = require('./build/webpack/webpack.config.js');
6
5
  var cssInjector = require('./css-injector/css-injector.js');
6
+ var i18n_plugin = require('./i18n/i18n.plugin.js');
7
7
 
8
8
 
9
9
 
10
- exports.I18n = i18n_plugin.I18n;
11
- exports.webpackConfig = webpack_config.webpackConfig;
12
10
  exports.rollupCssInjectorConfig = rollup_config.rollupCssInjectorConfig;
11
+ exports.webpackConfig = webpack_config.webpackConfig;
13
12
  exports.CssInjector = cssInjector.CssInjector;
14
13
  exports.cssInjector = cssInjector.cssInjector;
14
+ exports.I18n = i18n_plugin.I18n;
@@ -1,12 +1,12 @@
1
- const rollupCssInjectorConfig = {
2
- replace: {
3
- // Replace X CSS injector by our custom one.
4
- 'export default injectCss;': 'export default (css) => window.xCSSInjector.addStyle({ source: css });',
5
- delimiters: ['', '']
6
- },
7
- styles: {
8
- mode: ['inject', (varname) => `window.xCSSInjector.addStyle({ source: ${varname} });`]
9
- }
1
+ const rollupCssInjectorConfig = {
2
+ replace: {
3
+ // Replace X CSS injector by our custom one.
4
+ 'export default injectCss': 'export default (css) => window.xCSSInjector.addStyle({ source: css });',
5
+ delimiters: ['', ''],
6
+ },
7
+ styles: {
8
+ mode: ['inject', (varname) => `window.xCSSInjector.addStyle({ source: ${varname} });`],
9
+ },
10
10
  };
11
11
 
12
12
  export { rollupCssInjectorConfig };
@@ -1,24 +1,24 @@
1
- const webpackConfig = {
2
- transpileDependencies: ['@empathyco/x-components'],
3
- configureWebpack: {
4
- module: {
5
- rules: [
6
- {
7
- test: /\.ts|js|vue$/,
8
- enforce: 'pre',
9
- use: ['source-map-loader']
10
- }
11
- ]
12
- },
13
- output: {
14
- devtoolModuleFilenameTemplate: ({ resourcePath, hash, query }) => resourcePath.match(/\.vue$/) &&
15
- !query.match(/type=script/) &&
16
- !query.match(/\?rollup-plugin-vue=script.ts/)
17
- ? `webpack-generated:///${resourcePath}?${hash}`
18
- : `sources://${resourcePath}`,
19
- devtoolFallbackModuleFilenameTemplate: 'webpack:///[resource-path]?[hash]'
20
- }
21
- }
1
+ const webpackConfig = {
2
+ transpileDependencies: ['@empathyco/x-components'],
3
+ configureWebpack: {
4
+ module: {
5
+ rules: [
6
+ {
7
+ test: /\.ts|js|vue$/,
8
+ enforce: 'pre',
9
+ use: ['source-map-loader'],
10
+ },
11
+ ],
12
+ },
13
+ output: {
14
+ devtoolModuleFilenameTemplate: ({ resourcePath, hash, query, }) => resourcePath.match(/\.vue$/) &&
15
+ !query.match(/type=script/) &&
16
+ !query.match(/\?rollup-plugin-vue=script.ts/)
17
+ ? `webpack-generated:///${resourcePath}?${hash}`
18
+ : `sources://${resourcePath}`,
19
+ devtoolFallbackModuleFilenameTemplate: 'webpack:///[resource-path]?[hash]',
20
+ },
21
+ },
22
22
  };
23
23
 
24
24
  export { webpackConfig };