@studiometa/js-toolkit 3.3.0 → 3.4.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.
package/Base/utils.d.ts CHANGED
@@ -33,8 +33,9 @@ export declare function getEventTarget(instance: Base, event: string, config: Ba
33
33
  /**
34
34
  * Get all mounted instances or the ones from a given component.
35
35
  * @link https://js-toolkit.studiometa.dev/api/helpers/getInstances.html
36
- */
36
+ */
37
37
  export declare function getInstances(): Set<Base>;
38
38
  export declare function getInstances<T extends BaseConstructor = BaseConstructor>(ctor: T): Set<InstanceType<T>>;
39
39
  export declare function addInstance(instance: Base): void;
40
40
  export declare function deleteInstance(instance: Base): void;
41
+ export declare function addToRegistry(nameOrSelector: string, ctor: BaseConstructor): void;
package/Base/utils.js CHANGED
@@ -1,5 +1,7 @@
1
1
  import { isArray, isDefined, SmartQueue, dashCase } from "../utils/index.js";
2
2
  import { features } from "./features.js";
3
+ import { useMutation } from "../services/MutationService.js";
4
+ import { getInstanceFromElement } from "../helpers/getInstanceFromElement.js";
3
5
  let queue;
4
6
  function addToQueue(fn) {
5
7
  if (features.get("blocking")) {
@@ -58,7 +60,7 @@ function getEventTarget(instance, event, config) {
58
60
  }
59
61
  }
60
62
  function getInstancesStorage() {
61
- return globalThis.__js_toolkit_instances__ ??= /* @__PURE__ */ new Set();
63
+ return globalThis.__JS_TOOLKIT_INSTANCES__ ??= /* @__PURE__ */ new Set();
62
64
  }
63
65
  function getInstances(ctor) {
64
66
  if (isDefined(ctor)) {
@@ -79,9 +81,42 @@ function addInstance(instance) {
79
81
  function deleteInstance(instance) {
80
82
  getInstancesStorage().delete(instance);
81
83
  }
84
+ const registryKey = "__JS_TOOLKIT_REGISTRY__";
85
+ function registry() {
86
+ return globalThis[registryKey] ??= /* @__PURE__ */ new Map();
87
+ }
88
+ function mutationCallback() {
89
+ addToQueue(() => {
90
+ for (const [nameOrSelector, ctor] of registry()) {
91
+ for (const el of getComponentElements(nameOrSelector)) {
92
+ if (!getInstanceFromElement(el, ctor)) {
93
+ new ctor(el).$mount();
94
+ }
95
+ }
96
+ }
97
+ });
98
+ addToQueue(() => {
99
+ for (const instance of getInstances()) {
100
+ if (!instance.$el.isConnected) {
101
+ instance.$terminate();
102
+ }
103
+ }
104
+ });
105
+ }
106
+ function addToRegistry(nameOrSelector, ctor) {
107
+ if (registry().has(nameOrSelector)) {
108
+ return;
109
+ }
110
+ registry().set(nameOrSelector, ctor);
111
+ const mutation = useMutation(document, { childList: true, subtree: true });
112
+ if (!mutation.has(registryKey)) {
113
+ mutation.add(registryKey, mutationCallback);
114
+ }
115
+ }
82
116
  export {
83
117
  addInstance,
84
118
  addToQueue,
119
+ addToRegistry,
85
120
  deleteInstance,
86
121
  eventIsDefinedInConfig,
87
122
  eventIsNative,
package/Base/utils.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../packages/js-toolkit/Base/utils.ts"],
4
- "sourcesContent": ["import { isArray, isDefined, SmartQueue, dashCase } from '../utils/index.js';\nimport type { Base, BaseConfig, BaseConstructor } from './index.js';\nimport { features } from './features.js';\n\nlet queue: SmartQueue;\n\n/**\n * Add a task to the main queue.\n */\nexport function addToQueue(fn: () => unknown) {\n if (features.get('blocking')) {\n fn();\n return;\n }\n\n if (!queue) {\n queue = new SmartQueue();\n }\n\n return queue.add(fn);\n}\n\nconst selectors = new Map();\n\n// Separator used for multi-component declaration in `data-component` attributeS.\nconst separator = ' ';\n\n/**\n * Get the selector for a given component.\n */\nexport function getSelector(nameOrSelector: string): string {\n const { component } = features.get('attributes');\n const prefix = features.get('prefix');\n const key = prefix + component + nameOrSelector;\n\n if (!selectors.has(key)) {\n const parts = [\n // Tag select\n `${prefix}-${dashCase(nameOrSelector)}`,\n // Single selector\n `[${component}=\"${nameOrSelector}\"]`,\n // Selector in the middle of a list of selectors\n `[${component}*=\"${separator}${nameOrSelector}${separator}\"]`,\n // Selector at the end of a list of selectors\n `[${component}$=\"${separator}${nameOrSelector}\"]`,\n // Selector at the beginning of a list of selectors\n `[${component}^=\"${nameOrSelector}${separator}\"]`,\n ];\n selectors.set(key, parts.join(','));\n }\n\n return selectors.get(key);\n}\n\n/**\n * Get a list of elements based on the name of a component.\n *\n * @param {string} nameOrSelector\n * The name or selector to used for this component.\n * @param {HTMLElement|Document} element\n * The root element on which to query the selector, defaults to `document`.\n * @return {Array<HTMLElement>}\n * A list of elements on which the component should be mounted.\n */\nexport function getComponentElements(\n nameOrSelector: string,\n element: HTMLElement | Document = document,\n): HTMLElement[] {\n const selector = getSelector(nameOrSelector);\n let elements = [];\n\n try {\n elements = Array.from(element.querySelectorAll(selector));\n // eslint-disable-next-line no-empty\n } catch {}\n\n // If no child component found with the default selector, and if the selector does not\n // start with an uppercase letter, matching a component's name, try a classic DOM selector.\n if (elements.length === 0 && nameOrSelector[0] === nameOrSelector[0].toLowerCase()) {\n elements = Array.from(element.querySelectorAll(nameOrSelector));\n }\n\n return elements;\n}\n\n/**\n * Test if an event is defined in the given config.\n */\nexport function eventIsDefinedInConfig(event: string, config: BaseConfig): boolean {\n return isArray(config.emits) && config.emits.includes(event);\n}\n\n/**\n * Test if an event can be used on the given element.\n */\nexport function eventIsNative(event: string, element: HTMLElement): boolean {\n return isDefined(element[`on${event}`]);\n}\n\n/**\n * Get the target of a given event.\n */\nexport function getEventTarget(instance: Base, event: string, config: BaseConfig): Base['$el'] {\n if (eventIsDefinedInConfig(event, config) || eventIsNative(event, instance.$el)) {\n return instance.$el;\n }\n}\n\n/**\n * Get the global instance storage.\n * We attach it to `globalThis` so it can be shared between different\n * instances of the framework.\n */\nfunction getInstancesStorage(): Set<Base> {\n return globalThis.__js_toolkit_instances__ ??= new Set<Base>();\n}\n\n/**\n * Get all mounted instances or the ones from a given component.\n * @link https://js-toolkit.studiometa.dev/api/helpers/getInstances.html\n*/\nexport function getInstances(): Set<Base>;\nexport function getInstances<T extends BaseConstructor = BaseConstructor>(\n ctor: T,\n): Set<InstanceType<T>>;\nexport function getInstances<T extends BaseConstructor = BaseConstructor>(\n ctor?: T,\n): Set<InstanceType<T>> | Set<Base> {\n if (isDefined(ctor)) {\n const filteredInstances = new Set<InstanceType<T>>();\n for (const instance of getInstancesStorage()) {\n if (instance instanceof ctor) {\n filteredInstances.add(instance as InstanceType<T>);\n }\n }\n return filteredInstances;\n } else {\n return new Set(getInstancesStorage());\n }\n}\n\nexport function addInstance(instance: Base) {\n getInstancesStorage().add(instance);\n}\n\nexport function deleteInstance(instance: Base) {\n getInstancesStorage().delete(instance);\n}\n"],
5
- "mappings": "AAAA,SAAS,SAAS,WAAW,YAAY,gBAAgB;AAEzD,SAAS,gBAAgB;AAEzB,IAAI;AAKG,SAAS,WAAW,IAAmB;AAC5C,MAAI,SAAS,IAAI,UAAU,GAAG;AAC5B,OAAG;AACH;AAAA,EACF;AAEA,MAAI,CAAC,OAAO;AACV,YAAQ,IAAI,WAAW;AAAA,EACzB;AAEA,SAAO,MAAM,IAAI,EAAE;AACrB;AAEA,MAAM,YAAY,oBAAI,IAAI;AAG1B,MAAM,YAAY;AAKX,SAAS,YAAY,gBAAgC;AAC1D,QAAM,EAAE,UAAU,IAAI,SAAS,IAAI,YAAY;AAC/C,QAAM,SAAS,SAAS,IAAI,QAAQ;AACpC,QAAM,MAAM,SAAS,YAAY;AAEjC,MAAI,CAAC,UAAU,IAAI,GAAG,GAAG;AACvB,UAAM,QAAQ;AAAA;AAAA,MAEZ,GAAG,MAAM,IAAI,SAAS,cAAc,CAAC;AAAA;AAAA,MAErC,IAAI,SAAS,KAAK,cAAc;AAAA;AAAA,MAEhC,IAAI,SAAS,MAAM,SAAS,GAAG,cAAc,GAAG,SAAS;AAAA;AAAA,MAEzD,IAAI,SAAS,MAAM,SAAS,GAAG,cAAc;AAAA;AAAA,MAE7C,IAAI,SAAS,MAAM,cAAc,GAAG,SAAS;AAAA,IAC/C;AACA,cAAU,IAAI,KAAK,MAAM,KAAK,GAAG,CAAC;AAAA,EACpC;AAEA,SAAO,UAAU,IAAI,GAAG;AAC1B;AAYO,SAAS,qBACd,gBACA,UAAkC,UACnB;AACf,QAAM,WAAW,YAAY,cAAc;AAC3C,MAAI,WAAW,CAAC;AAEhB,MAAI;AACF,eAAW,MAAM,KAAK,QAAQ,iBAAiB,QAAQ,CAAC;AAAA,EAE1D,QAAQ;AAAA,EAAC;AAIT,MAAI,SAAS,WAAW,KAAK,eAAe,CAAC,MAAM,eAAe,CAAC,EAAE,YAAY,GAAG;AAClF,eAAW,MAAM,KAAK,QAAQ,iBAAiB,cAAc,CAAC;AAAA,EAChE;AAEA,SAAO;AACT;AAKO,SAAS,uBAAuB,OAAe,QAA6B;AACjF,SAAO,QAAQ,OAAO,KAAK,KAAK,OAAO,MAAM,SAAS,KAAK;AAC7D;AAKO,SAAS,cAAc,OAAe,SAA+B;AAC1E,SAAO,UAAU,QAAQ,KAAK,KAAK,EAAE,CAAC;AACxC;AAKO,SAAS,eAAe,UAAgB,OAAe,QAAiC;AAC7F,MAAI,uBAAuB,OAAO,MAAM,KAAK,cAAc,OAAO,SAAS,GAAG,GAAG;AAC/E,WAAO,SAAS;AAAA,EAClB;AACF;AAOA,SAAS,sBAAiC;AACxC,SAAO,WAAW,6BAA6B,oBAAI,IAAU;AAC/D;AAUO,SAAS,aACd,MACkC;AAClC,MAAI,UAAU,IAAI,GAAG;AACnB,UAAM,oBAAoB,oBAAI,IAAqB;AACnD,eAAW,YAAY,oBAAoB,GAAG;AAC5C,UAAI,oBAAoB,MAAM;AAC5B,0BAAkB,IAAI,QAA2B;AAAA,MACnD;AAAA,IACF;AACA,WAAO;AAAA,EACT,OAAO;AACL,WAAO,IAAI,IAAI,oBAAoB,CAAC;AAAA,EACtC;AACF;AAEO,SAAS,YAAY,UAAgB;AAC1C,sBAAoB,EAAE,IAAI,QAAQ;AACpC;AAEO,SAAS,eAAe,UAAgB;AAC7C,sBAAoB,EAAE,OAAO,QAAQ;AACvC;",
4
+ "sourcesContent": ["import { isArray, isDefined, SmartQueue, dashCase } from '../utils/index.js';\nimport type { Base, BaseConfig, BaseConstructor } from './index.js';\nimport { features } from './features.js';\nimport { useMutation } from '../services/MutationService.js';\nimport { getInstanceFromElement } from '../helpers/getInstanceFromElement.js';\n\nlet queue: SmartQueue;\n\n/**\n * Add a task to the main queue.\n */\nexport function addToQueue(fn: () => unknown) {\n if (features.get('blocking')) {\n fn();\n return;\n }\n\n if (!queue) {\n queue = new SmartQueue();\n }\n\n return queue.add(fn);\n}\n\nconst selectors = new Map();\n\n// Separator used for multi-component declaration in `data-component` attributeS.\nconst separator = ' ';\n\n/**\n * Get the selector for a given component.\n */\nexport function getSelector(nameOrSelector: string): string {\n const { component } = features.get('attributes');\n const prefix = features.get('prefix');\n const key = prefix + component + nameOrSelector;\n\n if (!selectors.has(key)) {\n const parts = [\n // Tag select\n `${prefix}-${dashCase(nameOrSelector)}`,\n // Single selector\n `[${component}=\"${nameOrSelector}\"]`,\n // Selector in the middle of a list of selectors\n `[${component}*=\"${separator}${nameOrSelector}${separator}\"]`,\n // Selector at the end of a list of selectors\n `[${component}$=\"${separator}${nameOrSelector}\"]`,\n // Selector at the beginning of a list of selectors\n `[${component}^=\"${nameOrSelector}${separator}\"]`,\n ];\n selectors.set(key, parts.join(','));\n }\n\n return selectors.get(key);\n}\n\n/**\n * Get a list of elements based on the name of a component.\n *\n * @param {string} nameOrSelector\n * The name or selector to used for this component.\n * @param {HTMLElement|Document} element\n * The root element on which to query the selector, defaults to `document`.\n * @return {Array<HTMLElement>}\n * A list of elements on which the component should be mounted.\n */\nexport function getComponentElements(\n nameOrSelector: string,\n element: HTMLElement | Document = document,\n): HTMLElement[] {\n const selector = getSelector(nameOrSelector);\n let elements = [];\n\n try {\n elements = Array.from(element.querySelectorAll(selector));\n // eslint-disable-next-line no-empty\n } catch {}\n\n // If no child component found with the default selector, and if the selector does not\n // start with an uppercase letter, matching a component's name, try a classic DOM selector.\n if (elements.length === 0 && nameOrSelector[0] === nameOrSelector[0].toLowerCase()) {\n elements = Array.from(element.querySelectorAll(nameOrSelector));\n }\n\n return elements;\n}\n\n/**\n * Test if an event is defined in the given config.\n */\nexport function eventIsDefinedInConfig(event: string, config: BaseConfig): boolean {\n return isArray(config.emits) && config.emits.includes(event);\n}\n\n/**\n * Test if an event can be used on the given element.\n */\nexport function eventIsNative(event: string, element: HTMLElement): boolean {\n return isDefined(element[`on${event}`]);\n}\n\n/**\n * Get the target of a given event.\n */\nexport function getEventTarget(instance: Base, event: string, config: BaseConfig): Base['$el'] {\n if (eventIsDefinedInConfig(event, config) || eventIsNative(event, instance.$el)) {\n return instance.$el;\n }\n}\n\n/**\n * Get the global instance storage.\n * We attach it to `globalThis` so it can be shared between different\n * instances of the framework.\n */\nfunction getInstancesStorage(): Set<Base> {\n return (globalThis.__JS_TOOLKIT_INSTANCES__ ??= new Set<Base>());\n}\n\n/**\n * Get all mounted instances or the ones from a given component.\n * @link https://js-toolkit.studiometa.dev/api/helpers/getInstances.html\n */\nexport function getInstances(): Set<Base>;\nexport function getInstances<T extends BaseConstructor = BaseConstructor>(\n ctor: T,\n): Set<InstanceType<T>>;\nexport function getInstances<T extends BaseConstructor = BaseConstructor>(\n ctor?: T,\n): Set<InstanceType<T>> | Set<Base> {\n if (isDefined(ctor)) {\n const filteredInstances = new Set<InstanceType<T>>();\n for (const instance of getInstancesStorage()) {\n if (instance instanceof ctor) {\n filteredInstances.add(instance as InstanceType<T>);\n }\n }\n return filteredInstances;\n } else {\n return new Set(getInstancesStorage());\n }\n}\n\nexport function addInstance(instance: Base) {\n getInstancesStorage().add(instance);\n}\n\nexport function deleteInstance(instance: Base) {\n getInstancesStorage().delete(instance);\n}\n\nconst registryKey = '__JS_TOOLKIT_REGISTRY__';\n\nfunction registry() {\n return (globalThis[registryKey] ??= new Map<string, BaseConstructor>());\n}\n\nfunction mutationCallback() {\n addToQueue(() => {\n for (const [nameOrSelector, ctor] of registry()) {\n for (const el of getComponentElements(nameOrSelector)) {\n if (!getInstanceFromElement(el, ctor)) {\n new ctor(el).$mount();\n }\n }\n }\n });\n\n addToQueue(() => {\n for (const instance of getInstances()) {\n if (!instance.$el.isConnected) {\n instance.$terminate();\n }\n }\n });\n}\n\nexport function addToRegistry(nameOrSelector: string, ctor: BaseConstructor) {\n if (registry().has(nameOrSelector)) {\n return;\n }\n\n registry().set(nameOrSelector, ctor);\n\n const mutation = useMutation(document, { childList: true, subtree: true });\n if (!mutation.has(registryKey)) {\n mutation.add(registryKey, mutationCallback);\n }\n}\n"],
5
+ "mappings": "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",
6
6
  "names": []
7
7
  }
package/README.md CHANGED
@@ -108,22 +108,13 @@ And then adjust it as you wish in your HTML:
108
108
  </div>
109
109
  ```
110
110
 
111
- The framework also offers a way to instantiate a root component as an application, with child components as dependencies:
111
+ Like Web Components, components based on the `Base` class can be registered. Any matching component found in the DOM from the moment it is registered to any future change will be mounted.
112
112
 
113
113
  ```js
114
- import { Base, createApp } from '@studiometa/js-toolkit';
114
+ import { registerComponent } from '@studiometa/js-toolkit';
115
115
  import Counter from './components/Counter.js';
116
116
 
117
- class App extends Base {
118
- static config = {
119
- name: 'App',
120
- components: {
121
- Counter,
122
- },
123
- };
124
- }
125
-
126
- export default createApp(App);
117
+ registerComponent(Counter);
127
118
  ```
128
119
 
129
120
  Visit our ["Getting Started" guide](https://js-toolkit.studiometa.dev/guide/) to learn more and try the above component by visiting [the playground](https://ui.studiometa.dev/-/play/#script=eNqVkjFPwzAQhff%2BijcguRVtEGurSpTuDKyIwdiXYprYkX2pQFX%2BO7bjlg6A1EiJndO97873bNrOecYRjzLQHMqTZNp0HQbU3rUQD4F7bVxLLO8%2BwoKda%2FaGxWoyUY0MAVvXWyYP%2BmSyOmQOjhMgsGSjoJytzQ7rHAOsbGkJUVRinoOe6rDEi5BaizmEp9YdKO1UShOvY5br2DgbE0dSqkDdzx%2FAX11kP%2FXtG%2FlRkh5NtewbXuL%2BFBvGzRC%2FQzwHsCOOfeaOprMC9MS9t%2BB3E6qb1GCVM6qDbHrahLHKKiESIVwQcsYJ87s%2BjiOvZ72zG623jVH7cwNZWZi4XRdSGUKVzn6hfs4j%2Bwew%2BBsQEaOVyfbrbIyKYqFy8SJZsnzhTzG5TDstcdyp2umSTeM7W30DtazCdQ%3D%3D&html=eNqFkEsKwzAMRPc9hdDe5EOXcaD0Br2BEyvBkMjGkUN7%2Byb1ogkUupJAmjfMNNatYI0Y1fs5eCYWjXefWChiPvggzrNahILGGqGfzLJoDOoKw0RPGM22YnsBaLok4jnLIg0ajbUHQQ3dqLopkarKEuLmYslie7O2KbL0NyXS7Ff6D3p8%2Fk4sxyHJAdXv0RDkFUgjp7nbY65mQ2ksTw7R8aiqPBwvJF%2BfS1NstbVv4jxoZA%3D%3D&style=eNpLyk%2BpVKjmUlAoSExJycxLt1IwLErNteaqBQBpsgf8). Discover our existing library of components by checking out the [@studiometa/ui](https://github.com/studiometa/ui) package.
@@ -10,7 +10,6 @@ export interface withMountOnMediaQueryInterface extends BaseInterface {
10
10
  * @private
11
11
  */
12
12
  __matches: boolean;
13
- $mount(): this;
14
13
  }
15
14
  /**
16
15
  * IntersectionObserver decoration.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../packages/js-toolkit/decorators/withMountOnMediaQuery.ts"],
4
- "sourcesContent": ["import { BaseInterface, BaseDecorator } from '../Base/types.js';\nimport type { Base, BaseProps, BaseConfig } from '../Base/index.js';\nimport { isDev } from '../utils/is.js';\n\nexport interface withMountOnMediaQueryProps extends BaseProps {\n $options: {\n media: string;\n };\n}\n\nexport interface withMountOnMediaQueryInterface extends BaseInterface {\n /**\n * @private\n */\n __matches: boolean;\n $mount(): this;\n}\n\n/**\n * IntersectionObserver decoration.\n * @link https://js-toolkit.studiometa.dev/api/decorators/withMountOnMediaQuery.html\n*/\nexport function withMountOnMediaQuery<S extends Base = Base>(\n BaseClass: typeof Base,\n media,\n): BaseDecorator<withMountOnMediaQueryInterface, S, withMountOnMediaQueryProps> {\n /**\n * Class.\n */\n class WithMountOnMediaQuery<T extends BaseProps = BaseProps> extends BaseClass<\n T & withMountOnMediaQueryProps\n > {\n /**\n * Config.\n */\n static config: BaseConfig = {\n ...BaseClass.config,\n options: {\n media: String,\n },\n };\n\n /**\n * Is the media query matches?\n *\n * @private\n */\n __matches = false;\n\n /**\n * Listen for media query changes when the class in instantiated.\n *\n * @param {HTMLElement} element The component's root element.\n */\n constructor(element: HTMLElement) {\n super(element);\n\n if (isDev && !this.$options.media && !media) {\n this.$warn(\n 'Missing either \"$options.media\" or \"media\" argument in withMountOnMediaQuery decorator.',\n );\n return;\n }\n\n const mediaQueryList = window.matchMedia(this.$options.media || media);\n\n // Set initial value\n this.__matches = mediaQueryList.matches;\n\n const changeHandler = (event: MediaQueryListEvent) => {\n this.__matches = event.matches;\n\n if (event.matches && !this.$isMounted) {\n this.$mount();\n } else if (this.$isMounted) {\n setTimeout(() => this.$destroy());\n }\n };\n\n // Start listening for changes\n mediaQueryList.addEventListener('change', changeHandler);\n\n this.$on('terminated', () => {\n mediaQueryList.removeEventListener('change', changeHandler);\n });\n }\n\n /**\n * Override the mounting of the component.\n */\n async $mount() {\n if (this.__matches) {\n return super.$mount();\n }\n\n return this;\n }\n }\n\n // @ts-ignore\n return WithMountOnMediaQuery;\n}\n"],
5
- "mappings": "AAEA,SAAS,aAAa;AAoBf,SAAS,sBACd,WACA,OAC8E;AAAA,EAI9E,MAAM,8BAA+D,UAEnE;AAAA;AAAA;AAAA;AAAA,IAIA,OAAO,SAAqB;AAAA,MAC1B,GAAG,UAAU;AAAA,MACb,SAAS;AAAA,QACP,OAAO;AAAA,MACT;AAAA,IACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAOA,YAAY;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAOZ,YAAY,SAAsB;AAChC,YAAM,OAAO;AAEb,UAAI,SAAS,CAAC,KAAK,SAAS,SAAS,CAAC,OAAO;AAC3C,aAAK;AAAA,UACH;AAAA,QACF;AACA;AAAA,MACF;AAEA,YAAM,iBAAiB,OAAO,WAAW,KAAK,SAAS,SAAS,KAAK;AAGrE,WAAK,YAAY,eAAe;AAEhC,YAAM,gBAAgB,CAAC,UAA+B;AACpD,aAAK,YAAY,MAAM;AAEvB,YAAI,MAAM,WAAW,CAAC,KAAK,YAAY;AACrC,eAAK,OAAO;AAAA,QACd,WAAW,KAAK,YAAY;AAC1B,qBAAW,MAAM,KAAK,SAAS,CAAC;AAAA,QAClC;AAAA,MACF;AAGA,qBAAe,iBAAiB,UAAU,aAAa;AAEvD,WAAK,IAAI,cAAc,MAAM;AAC3B,uBAAe,oBAAoB,UAAU,aAAa;AAAA,MAC5D,CAAC;AAAA,IACH;AAAA;AAAA;AAAA;AAAA,IAKA,MAAM,SAAS;AACb,UAAI,KAAK,WAAW;AAClB,eAAO,MAAM,OAAO;AAAA,MACtB;AAEA,aAAO;AAAA,IACT;AAAA,EACF;AAGA,SAAO;AACT;",
4
+ "sourcesContent": ["import { BaseInterface, BaseDecorator } from '../Base/types.js';\nimport type { Base, BaseProps, BaseConfig } from '../Base/index.js';\nimport { isDev } from '../utils/is.js';\n\nexport interface withMountOnMediaQueryProps extends BaseProps {\n $options: {\n media: string;\n };\n}\n\nexport interface withMountOnMediaQueryInterface extends BaseInterface {\n /**\n * @private\n */\n __matches: boolean;\n}\n\n/**\n * IntersectionObserver decoration.\n * @link https://js-toolkit.studiometa.dev/api/decorators/withMountOnMediaQuery.html\n*/\nexport function withMountOnMediaQuery<S extends Base = Base>(\n BaseClass: typeof Base,\n media,\n): BaseDecorator<withMountOnMediaQueryInterface, S, withMountOnMediaQueryProps> {\n /**\n * Class.\n */\n class WithMountOnMediaQuery<T extends BaseProps = BaseProps> extends BaseClass<\n T & withMountOnMediaQueryProps\n > {\n /**\n * Config.\n */\n static config: BaseConfig = {\n ...BaseClass.config,\n options: {\n media: String,\n },\n };\n\n /**\n * Is the media query matches?\n *\n * @private\n */\n __matches = false;\n\n /**\n * Listen for media query changes when the class in instantiated.\n *\n * @param {HTMLElement} element The component's root element.\n */\n constructor(element: HTMLElement) {\n super(element);\n\n if (isDev && !this.$options.media && !media) {\n this.$warn(\n 'Missing either \"$options.media\" or \"media\" argument in withMountOnMediaQuery decorator.',\n );\n return;\n }\n\n const mediaQueryList = window.matchMedia(this.$options.media || media);\n\n // Set initial value\n this.__matches = mediaQueryList.matches;\n\n const changeHandler = (event: MediaQueryListEvent) => {\n this.__matches = event.matches;\n\n if (event.matches && !this.$isMounted) {\n this.$mount();\n } else if (this.$isMounted) {\n setTimeout(() => this.$destroy());\n }\n };\n\n // Start listening for changes\n mediaQueryList.addEventListener('change', changeHandler);\n\n this.$on('terminated', () => {\n mediaQueryList.removeEventListener('change', changeHandler);\n });\n }\n\n /**\n * Override the mounting of the component.\n */\n async $mount() {\n if (this.__matches) {\n return super.$mount();\n }\n\n return this;\n }\n }\n\n // @ts-ignore\n return WithMountOnMediaQuery;\n}\n"],
5
+ "mappings": "AAEA,SAAS,aAAa;AAmBf,SAAS,sBACd,WACA,OAC8E;AAAA,EAI9E,MAAM,8BAA+D,UAEnE;AAAA;AAAA;AAAA;AAAA,IAIA,OAAO,SAAqB;AAAA,MAC1B,GAAG,UAAU;AAAA,MACb,SAAS;AAAA,QACP,OAAO;AAAA,MACT;AAAA,IACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAOA,YAAY;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAOZ,YAAY,SAAsB;AAChC,YAAM,OAAO;AAEb,UAAI,SAAS,CAAC,KAAK,SAAS,SAAS,CAAC,OAAO;AAC3C,aAAK;AAAA,UACH;AAAA,QACF;AACA;AAAA,MACF;AAEA,YAAM,iBAAiB,OAAO,WAAW,KAAK,SAAS,SAAS,KAAK;AAGrE,WAAK,YAAY,eAAe;AAEhC,YAAM,gBAAgB,CAAC,UAA+B;AACpD,aAAK,YAAY,MAAM;AAEvB,YAAI,MAAM,WAAW,CAAC,KAAK,YAAY;AACrC,eAAK,OAAO;AAAA,QACd,WAAW,KAAK,YAAY;AAC1B,qBAAW,MAAM,KAAK,SAAS,CAAC;AAAA,QAClC;AAAA,MACF;AAGA,qBAAe,iBAAiB,UAAU,aAAa;AAEvD,WAAK,IAAI,cAAc,MAAM;AAC3B,uBAAe,oBAAoB,UAAU,aAAa;AAAA,MAC5D,CAAC;AAAA,IACH;AAAA;AAAA;AAAA;AAAA,IAKA,MAAM,SAAS;AACb,UAAI,KAAK,WAAW;AAClB,eAAO,MAAM,OAAO;AAAA,MACtB;AAEA,aAAO;AAAA,IACT;AAAA,EACF;AAGA,SAAO;AACT;",
6
6
  "names": []
7
7
  }
@@ -14,7 +14,6 @@ export interface WithMountWhenInViewInterface extends BaseInterface {
14
14
  * @private
15
15
  */
16
16
  __observer: IntersectionObserver;
17
- $mount(): this;
18
17
  }
19
18
  /**
20
19
  * IntersectionObserver decoration.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../packages/js-toolkit/decorators/withMountWhenInView.ts"],
4
- "sourcesContent": ["import { BaseInterface, BaseDecorator } from '../Base/types.js';\nimport type { Base, BaseProps, BaseConfig } from '../Base/index.js';\n\nexport interface WithMountWhenInViewProps extends BaseProps {\n $options: {\n intersectionObserver: IntersectionObserverInit;\n };\n}\n\nexport interface WithMountWhenInViewInterface extends BaseInterface {\n /**\n * @private\n */\n __isVisible: boolean;\n /**\n * @private\n */\n __observer: IntersectionObserver;\n $mount(): this;\n}\n\n/**\n * IntersectionObserver decoration.\n * @link https://js-toolkit.studiometa.dev/api/decorators/withMountWhenInView.html\n*/\nexport function withMountWhenInView<S extends Base = Base>(\n BaseClass: typeof Base,\n // eslint-disable-next-line unicorn/no-object-as-default-parameter\n defaultOptions: IntersectionObserverInit = { threshold: [0, 1] },\n): BaseDecorator<WithMountWhenInViewInterface, S, WithMountWhenInViewProps> {\n /**\n * Class.\n */\n class WithMountWhenInView<T extends BaseProps = BaseProps> extends BaseClass<\n T & WithMountWhenInViewProps\n > {\n /**\n * Config.\n */\n static config: BaseConfig = {\n ...BaseClass.config,\n options: {\n intersectionObserver: Object,\n },\n };\n\n /**\n * Is the component visible?\n *\n * @private\n */\n __isVisible = false;\n\n /**\n * The component's observer.\n *\n * @private\n */\n __observer: IntersectionObserver;\n\n /**\n * Create an observer when the class in instantiated.\n *\n * @param {HTMLElement} element The component's root element.\n */\n constructor(element: HTMLElement) {\n super(element);\n\n this.__observer = new IntersectionObserver(\n (entries) => {\n const isVisible = entries.reduce((acc, entry) => acc || entry.isIntersecting, false);\n if (this.__isVisible !== isVisible) {\n this.__isVisible = isVisible;\n\n if (isVisible) {\n this.$mount();\n } else {\n setTimeout(() => this.$destroy());\n }\n }\n },\n {\n ...defaultOptions,\n ...(this.$options as typeof this.$options & WithMountWhenInViewProps['$options'])\n .intersectionObserver,\n },\n );\n\n this.__observer.observe(this.$el);\n\n this.$on('terminated', () => {\n this.__observer.disconnect();\n });\n }\n\n /**\n * Override the mounting of the component.\n */\n async $mount() {\n if (this.__isVisible) {\n return super.$mount();\n }\n\n return this;\n }\n }\n\n // @ts-ignore\n return WithMountWhenInView;\n}\n"],
5
- "mappings": "AAyBO,SAAS,oBACd,WAEA,iBAA2C,EAAE,WAAW,CAAC,GAAG,CAAC,EAAE,GACW;AAAA,EAI1E,MAAM,4BAA6D,UAEjE;AAAA;AAAA;AAAA;AAAA,IAIA,OAAO,SAAqB;AAAA,MAC1B,GAAG,UAAU;AAAA,MACb,SAAS;AAAA,QACP,sBAAsB;AAAA,MACxB;AAAA,IACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAOA,cAAc;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAOd;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAOA,YAAY,SAAsB;AAChC,YAAM,OAAO;AAEb,WAAK,aAAa,IAAI;AAAA,QACpB,CAAC,YAAY;AACX,gBAAM,YAAY,QAAQ,OAAO,CAAC,KAAK,UAAU,OAAO,MAAM,gBAAgB,KAAK;AACnF,cAAI,KAAK,gBAAgB,WAAW;AAClC,iBAAK,cAAc;AAEnB,gBAAI,WAAW;AACb,mBAAK,OAAO;AAAA,YACd,OAAO;AACL,yBAAW,MAAM,KAAK,SAAS,CAAC;AAAA,YAClC;AAAA,UACF;AAAA,QACF;AAAA,QACA;AAAA,UACE,GAAG;AAAA,UACH,GAAI,KAAK,SACN;AAAA,QACL;AAAA,MACF;AAEA,WAAK,WAAW,QAAQ,KAAK,GAAG;AAEhC,WAAK,IAAI,cAAc,MAAM;AAC3B,aAAK,WAAW,WAAW;AAAA,MAC7B,CAAC;AAAA,IACH;AAAA;AAAA;AAAA;AAAA,IAKA,MAAM,SAAS;AACb,UAAI,KAAK,aAAa;AACpB,eAAO,MAAM,OAAO;AAAA,MACtB;AAEA,aAAO;AAAA,IACT;AAAA,EACF;AAGA,SAAO;AACT;",
4
+ "sourcesContent": ["import { BaseInterface, BaseDecorator } from '../Base/types.js';\nimport type { Base, BaseProps, BaseConfig } from '../Base/index.js';\n\nexport interface WithMountWhenInViewProps extends BaseProps {\n $options: {\n intersectionObserver: IntersectionObserverInit;\n };\n}\n\nexport interface WithMountWhenInViewInterface extends BaseInterface {\n /**\n * @private\n */\n __isVisible: boolean;\n /**\n * @private\n */\n __observer: IntersectionObserver;\n}\n\n/**\n * IntersectionObserver decoration.\n * @link https://js-toolkit.studiometa.dev/api/decorators/withMountWhenInView.html\n*/\nexport function withMountWhenInView<S extends Base = Base>(\n BaseClass: typeof Base,\n // eslint-disable-next-line unicorn/no-object-as-default-parameter\n defaultOptions: IntersectionObserverInit = { threshold: [0, 1] },\n): BaseDecorator<WithMountWhenInViewInterface, S, WithMountWhenInViewProps> {\n /**\n * Class.\n */\n class WithMountWhenInView<T extends BaseProps = BaseProps> extends BaseClass<\n T & WithMountWhenInViewProps\n > {\n /**\n * Config.\n */\n static config: BaseConfig = {\n ...BaseClass.config,\n options: {\n intersectionObserver: Object,\n },\n };\n\n /**\n * Is the component visible?\n *\n * @private\n */\n __isVisible = false;\n\n /**\n * The component's observer.\n *\n * @private\n */\n __observer: IntersectionObserver;\n\n /**\n * Create an observer when the class in instantiated.\n *\n * @param {HTMLElement} element The component's root element.\n */\n constructor(element: HTMLElement) {\n super(element);\n\n this.__observer = new IntersectionObserver(\n (entries) => {\n const isVisible = entries.reduce((acc, entry) => acc || entry.isIntersecting, false);\n if (this.__isVisible !== isVisible) {\n this.__isVisible = isVisible;\n\n if (isVisible) {\n this.$mount();\n } else {\n setTimeout(() => this.$destroy());\n }\n }\n },\n {\n ...defaultOptions,\n ...(this.$options as typeof this.$options & WithMountWhenInViewProps['$options'])\n .intersectionObserver,\n },\n );\n\n this.__observer.observe(this.$el);\n\n this.$on('terminated', () => {\n this.__observer.disconnect();\n });\n }\n\n /**\n * Override the mounting of the component.\n */\n async $mount() {\n if (this.__isVisible) {\n return super.$mount();\n }\n\n return this;\n }\n }\n\n // @ts-ignore\n return WithMountWhenInView;\n}\n"],
5
+ "mappings": "AAwBO,SAAS,oBACd,WAEA,iBAA2C,EAAE,WAAW,CAAC,GAAG,CAAC,EAAE,GACW;AAAA,EAI1E,MAAM,4BAA6D,UAEjE;AAAA;AAAA;AAAA;AAAA,IAIA,OAAO,SAAqB;AAAA,MAC1B,GAAG,UAAU;AAAA,MACb,SAAS;AAAA,QACP,sBAAsB;AAAA,MACxB;AAAA,IACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAOA,cAAc;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAOd;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAOA,YAAY,SAAsB;AAChC,YAAM,OAAO;AAEb,WAAK,aAAa,IAAI;AAAA,QACpB,CAAC,YAAY;AACX,gBAAM,YAAY,QAAQ,OAAO,CAAC,KAAK,UAAU,OAAO,MAAM,gBAAgB,KAAK;AACnF,cAAI,KAAK,gBAAgB,WAAW;AAClC,iBAAK,cAAc;AAEnB,gBAAI,WAAW;AACb,mBAAK,OAAO;AAAA,YACd,OAAO;AACL,yBAAW,MAAM,KAAK,SAAS,CAAC;AAAA,YAClC;AAAA,UACF;AAAA,QACF;AAAA,QACA;AAAA,UACE,GAAG;AAAA,UACH,GAAI,KAAK,SACN;AAAA,QACL;AAAA,MACF;AAEA,WAAK,WAAW,QAAQ,KAAK,GAAG;AAEhC,WAAK,IAAI,cAAc,MAAM;AAC3B,aAAK,WAAW,WAAW;AAAA,MAC7B,CAAC;AAAA,IACH;AAAA;AAAA;AAAA;AAAA,IAKA,MAAM,SAAS;AACb,UAAI,KAAK,aAAa;AACpB,eAAO,MAAM,OAAO;AAAA,MACtB;AAEA,aAAO;AAAA,IACT;AAAA,EACF;AAGA,SAAO;AACT;",
6
6
  "names": []
7
7
  }
@@ -1,6 +1,4 @@
1
- import { getInstances } from "../Base/index.js";
2
1
  import { features } from "../Base/features.js";
3
- import { useMutation } from "../services/index.js";
4
2
  import { isBoolean, isObject, isString } from "../utils/index.js";
5
3
  function createApp(App, options = {}) {
6
4
  let app;
@@ -23,23 +21,6 @@ function createApp(App, options = {}) {
23
21
  if (isObject(attributes)) {
24
22
  features.set("attributes", attributes);
25
23
  }
26
- const service = useMutation(document.documentElement, { childList: true, subtree: true });
27
- const symbol = Symbol("createApp");
28
- service.add(symbol, (props) => {
29
- for (const mutation of props.mutations) {
30
- if (mutation.type === "childList") {
31
- for (const node of mutation.removedNodes) {
32
- if (!node.isConnected) {
33
- for (const instance of getInstances()) {
34
- if (node === instance.$el || node.contains(instance.$el)) {
35
- instance.$terminate();
36
- }
37
- }
38
- }
39
- }
40
- }
41
- }
42
- });
43
24
  async function init() {
44
25
  app = new App(root);
45
26
  await app.$mount();
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../packages/js-toolkit/helpers/createApp.ts"],
4
- "sourcesContent": ["import type { Base, BaseConstructor, BaseProps } from '../Base/index.js';\nimport type { Features } from '../Base/features.js';\nimport { getInstances } from '../Base/index.js';\nimport { features } from '../Base/features.js';\nimport { useMutation } from '../services/index.js';\nimport { isBoolean, isObject, isString } from '../utils/index.js';\n\nexport type CreateAppOptions = Partial<Features> & {\n root?: HTMLElement;\n};\n\n/**\n * Instantiate and mount the given component on the given root element when the page has been loaded\n * and return a function to use the app instance when it is ready.\n * @link https://js-toolkit.studiometa.dev/api/helpers/createApp.html\n*/\nexport function createApp<S extends BaseConstructor<Base>, T extends BaseProps = BaseProps>(\n App: S,\n options: HTMLElement | CreateAppOptions = {},\n): () => Promise<S & Base<T>> {\n let app: S & Base<T>;\n const {\n root = document.body,\n breakpoints = null,\n blocking = null,\n prefix = null,\n attributes = null,\n } = options instanceof HTMLElement ? { root: options } : options;\n\n if (isObject(breakpoints)) {\n features.set('breakpoints', breakpoints);\n }\n\n if (isBoolean(blocking)) {\n features.set('blocking', blocking);\n }\n\n if (isString(prefix)) {\n features.set('prefix', prefix);\n }\n\n if (isObject(attributes)) {\n features.set('attributes', attributes);\n }\n\n // Terminate components whose root element has been removed from the DOM\n const service = useMutation(document.documentElement, { childList: true, subtree: true });\n const symbol = Symbol('createApp');\n service.add(symbol, (props) => {\n for (const mutation of props.mutations) {\n if (mutation.type === 'childList') {\n for (const node of mutation.removedNodes) {\n if (!node.isConnected) {\n for (const instance of getInstances()) {\n if (node === instance.$el || node.contains(instance.$el)) {\n instance.$terminate();\n }\n }\n }\n }\n }\n }\n });\n\n async function init() {\n app = new App(root) as S & Base<T>;\n await app.$mount();\n return app;\n }\n\n let p: Promise<S & Base<T>>;\n\n if (features.get('blocking')) {\n p = init();\n } else {\n p = new Promise<S & Base<T>>((resolve) => {\n if (document.readyState === 'complete') {\n resolve(init());\n } else {\n document.addEventListener('readystatechange', () => {\n if (document.readyState === 'complete') {\n resolve(init());\n }\n });\n }\n });\n }\n\n return () => p;\n}\n"],
5
- "mappings": "AAEA,SAAS,oBAAoB;AAC7B,SAAS,gBAAgB;AACzB,SAAS,mBAAmB;AAC5B,SAAS,WAAW,UAAU,gBAAgB;AAWvC,SAAS,UACd,KACA,UAA0C,CAAC,GACf;AAC5B,MAAI;AACJ,QAAM;AAAA,IACJ,OAAO,SAAS;AAAA,IAChB,cAAc;AAAA,IACd,WAAW;AAAA,IACX,SAAS;AAAA,IACT,aAAa;AAAA,EACf,IAAI,mBAAmB,cAAc,EAAE,MAAM,QAAQ,IAAI;AAEzD,MAAI,SAAS,WAAW,GAAG;AACzB,aAAS,IAAI,eAAe,WAAW;AAAA,EACzC;AAEA,MAAI,UAAU,QAAQ,GAAG;AACvB,aAAS,IAAI,YAAY,QAAQ;AAAA,EACnC;AAEA,MAAI,SAAS,MAAM,GAAG;AACpB,aAAS,IAAI,UAAU,MAAM;AAAA,EAC/B;AAEA,MAAI,SAAS,UAAU,GAAG;AACxB,aAAS,IAAI,cAAc,UAAU;AAAA,EACvC;AAGA,QAAM,UAAU,YAAY,SAAS,iBAAiB,EAAE,WAAW,MAAM,SAAS,KAAK,CAAC;AACxF,QAAM,SAAS,OAAO,WAAW;AACjC,UAAQ,IAAI,QAAQ,CAAC,UAAU;AAC7B,eAAW,YAAY,MAAM,WAAW;AACtC,UAAI,SAAS,SAAS,aAAa;AACjC,mBAAW,QAAQ,SAAS,cAAc;AACxC,cAAI,CAAC,KAAK,aAAa;AACrB,uBAAW,YAAY,aAAa,GAAG;AACrC,kBAAI,SAAS,SAAS,OAAO,KAAK,SAAS,SAAS,GAAG,GAAG;AACxD,yBAAS,WAAW;AAAA,cACtB;AAAA,YACF;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF,CAAC;AAED,iBAAe,OAAO;AACpB,UAAM,IAAI,IAAI,IAAI;AAClB,UAAM,IAAI,OAAO;AACjB,WAAO;AAAA,EACT;AAEA,MAAI;AAEJ,MAAI,SAAS,IAAI,UAAU,GAAG;AAC5B,QAAI,KAAK;AAAA,EACX,OAAO;AACL,QAAI,IAAI,QAAqB,CAAC,YAAY;AACxC,UAAI,SAAS,eAAe,YAAY;AACtC,gBAAQ,KAAK,CAAC;AAAA,MAChB,OAAO;AACL,iBAAS,iBAAiB,oBAAoB,MAAM;AAClD,cAAI,SAAS,eAAe,YAAY;AACtC,oBAAQ,KAAK,CAAC;AAAA,UAChB;AAAA,QACF,CAAC;AAAA,MACH;AAAA,IACF,CAAC;AAAA,EACH;AAEA,SAAO,MAAM;AACf;",
4
+ "sourcesContent": ["import type { Base, BaseConstructor, BaseProps } from '../Base/index.js';\nimport type { Features } from '../Base/features.js';\nimport { features } from '../Base/features.js';\nimport { isBoolean, isObject, isString } from '../utils/index.js';\n\nexport type CreateAppOptions = Partial<Features> & {\n root?: HTMLElement;\n};\n\n/**\n * Instantiate and mount the given component on the given root element when the page has been loaded\n * and return a function to use the app instance when it is ready.\n * @link https://js-toolkit.studiometa.dev/api/helpers/createApp.html\n*/\nexport function createApp<S extends BaseConstructor<Base>, T extends BaseProps = BaseProps>(\n App: S,\n options: HTMLElement | CreateAppOptions = {},\n): () => Promise<S & Base<T>> {\n let app: S & Base<T>;\n const {\n root = document.body,\n breakpoints = null,\n blocking = null,\n prefix = null,\n attributes = null,\n } = options instanceof HTMLElement ? { root: options } : options;\n\n if (isObject(breakpoints)) {\n features.set('breakpoints', breakpoints);\n }\n\n if (isBoolean(blocking)) {\n features.set('blocking', blocking);\n }\n\n if (isString(prefix)) {\n features.set('prefix', prefix);\n }\n\n if (isObject(attributes)) {\n features.set('attributes', attributes);\n }\n\n async function init() {\n app = new App(root) as S & Base<T>;\n await app.$mount();\n return app;\n }\n\n let p: Promise<S & Base<T>>;\n\n if (features.get('blocking')) {\n p = init();\n } else {\n p = new Promise<S & Base<T>>((resolve) => {\n if (document.readyState === 'complete') {\n resolve(init());\n } else {\n document.addEventListener('readystatechange', () => {\n if (document.readyState === 'complete') {\n resolve(init());\n }\n });\n }\n });\n }\n\n return () => p;\n}\n"],
5
+ "mappings": "AAEA,SAAS,gBAAgB;AACzB,SAAS,WAAW,UAAU,gBAAgB;AAWvC,SAAS,UACd,KACA,UAA0C,CAAC,GACf;AAC5B,MAAI;AACJ,QAAM;AAAA,IACJ,OAAO,SAAS;AAAA,IAChB,cAAc;AAAA,IACd,WAAW;AAAA,IACX,SAAS;AAAA,IACT,aAAa;AAAA,EACf,IAAI,mBAAmB,cAAc,EAAE,MAAM,QAAQ,IAAI;AAEzD,MAAI,SAAS,WAAW,GAAG;AACzB,aAAS,IAAI,eAAe,WAAW;AAAA,EACzC;AAEA,MAAI,UAAU,QAAQ,GAAG;AACvB,aAAS,IAAI,YAAY,QAAQ;AAAA,EACnC;AAEA,MAAI,SAAS,MAAM,GAAG;AACpB,aAAS,IAAI,UAAU,MAAM;AAAA,EAC/B;AAEA,MAAI,SAAS,UAAU,GAAG;AACxB,aAAS,IAAI,cAAc,UAAU;AAAA,EACvC;AAEA,iBAAe,OAAO;AACpB,UAAM,IAAI,IAAI,IAAI;AAClB,UAAM,IAAI,OAAO;AACjB,WAAO;AAAA,EACT;AAEA,MAAI;AAEJ,MAAI,SAAS,IAAI,UAAU,GAAG;AAC5B,QAAI,KAAK;AAAA,EACX,OAAO;AACL,QAAI,IAAI,QAAqB,CAAC,YAAY;AACxC,UAAI,SAAS,eAAe,YAAY;AACtC,gBAAQ,KAAK,CAAC;AAAA,MAChB,OAAO;AACL,iBAAS,iBAAiB,oBAAoB,MAAM;AAClD,cAAI,SAAS,eAAe,YAAY;AACtC,oBAAQ,KAAK,CAAC;AAAA,UAChB;AAAA,QACF,CAAC;AAAA,MACH;AAAA,IACF,CAAC;AAAA,EACH;AAEA,SAAO,MAAM;AACf;",
6
6
  "names": []
7
7
  }
package/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export declare const version: "3.3.0";
1
+ export declare const version: "3.4.0";
2
2
  export * from './Base/index.js';
3
3
  export * from './Base/types.js';
4
4
  export * from './decorators/index.js';
package/index.js CHANGED
@@ -1,4 +1,4 @@
1
- const version = "3.3.0";
1
+ const version = "3.4.0";
2
2
  export * from "./Base/index.js";
3
3
  export * from "./Base/types.js";
4
4
  export * from "./decorators/index.js";
package/index.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../packages/js-toolkit/index.ts"],
4
- "sourcesContent": ["export const version = '3.3.0' as const;\n\nexport * from './Base/index.js';\nexport * from './Base/types.js';\nexport * from './decorators/index.js';\nexport * from './helpers/index.js';\nexport * from './services/index.js';\n"],
4
+ "sourcesContent": ["export const version = '3.4.0' as const;\n\nexport * from './Base/index.js';\nexport * from './Base/types.js';\nexport * from './decorators/index.js';\nexport * from './helpers/index.js';\nexport * from './services/index.js';\n"],
5
5
  "mappings": "AAAO,MAAM,UAAU;AAEvB,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;",
6
6
  "names": []
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@studiometa/js-toolkit",
3
- "version": "3.3.0",
3
+ "version": "3.4.0",
4
4
  "description": "A set of useful little bits of JavaScript to boost your project! 🚀",
5
5
  "publishConfig": {
6
6
  "access": "public"
package/utils/cache.js CHANGED
@@ -1,12 +1,11 @@
1
1
  import { isArray } from "./is.js";
2
- const map = /* @__PURE__ */ new Map();
3
2
  function cache(keys, callback) {
4
3
  const normalizedKeys = isArray(keys) ? keys : [keys];
5
- let value = map;
4
+ let value = globalThis.__JS_TOOLKIT_CACHE__ ??= /* @__PURE__ */ new Map();
6
5
  let index = 1;
7
6
  for (const key of normalizedKeys) {
8
7
  if (!value.has(key)) {
9
- const newValue = index === keys.length ? callback() : /* @__PURE__ */ new Map();
8
+ const newValue = index === normalizedKeys.length ? callback() : /* @__PURE__ */ new Map();
10
9
  value.set(key, newValue);
11
10
  }
12
11
  value = value.get(key);
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../packages/js-toolkit/utils/cache.ts"],
4
- "sourcesContent": ["import { isArray } from './is.js';\n\nconst map = new Map();\n\n/**\n * Cache the result of a callback in map instances.\n * @link https://js-toolkit.studiometa.dev/utils/cache.html\n*/\nexport function cache<T extends any>(keys: any | any[], callback: () => T): T {\n const normalizedKeys = isArray(keys) ? keys : [keys];\n let value = map;\n let index = 1;\n\n for (const key of normalizedKeys) {\n if (!value.has(key)) {\n const newValue = index === keys.length ? callback() : new Map();\n value.set(key, newValue);\n }\n\n value = value.get(key);\n index += 1;\n }\n\n return value as T;\n}\n"],
5
- "mappings": "AAAA,SAAS,eAAe;AAExB,MAAM,MAAM,oBAAI,IAAI;AAMb,SAAS,MAAqB,MAAmB,UAAsB;AAC5E,QAAM,iBAAiB,QAAQ,IAAI,IAAI,OAAO,CAAC,IAAI;AACnD,MAAI,QAAQ;AACZ,MAAI,QAAQ;AAEZ,aAAW,OAAO,gBAAgB;AAChC,QAAI,CAAC,MAAM,IAAI,GAAG,GAAG;AACnB,YAAM,WAAW,UAAU,KAAK,SAAS,SAAS,IAAI,oBAAI,IAAI;AAC9D,YAAM,IAAI,KAAK,QAAQ;AAAA,IACzB;AAEA,YAAQ,MAAM,IAAI,GAAG;AACrB,aAAS;AAAA,EACX;AAEA,SAAO;AACT;",
4
+ "sourcesContent": ["import { isArray } from './is.js';\n\n/**\n * Cache the result of a callback in map instances.\n * @link https://js-toolkit.studiometa.dev/utils/cache.html\n*/\nexport function cache<T extends any>(keys: any | any[], callback: () => T): T {\n const normalizedKeys = isArray(keys) ? keys : [keys];\n let value = (globalThis.__JS_TOOLKIT_CACHE__ ??= new Map());\n let index = 1;\n\n for (const key of normalizedKeys) {\n if (!value.has(key)) {\n const newValue = index === normalizedKeys.length ? callback() : new Map();\n value.set(key, newValue);\n }\n\n value = value.get(key);\n index += 1;\n }\n\n return value as T;\n}\n"],
5
+ "mappings": "AAAA,SAAS,eAAe;AAMjB,SAAS,MAAqB,MAAmB,UAAsB;AAC5E,QAAM,iBAAiB,QAAQ,IAAI,IAAI,OAAO,CAAC,IAAI;AACnD,MAAI,QAAS,WAAW,yBAAyB,oBAAI,IAAI;AACzD,MAAI,QAAQ;AAEZ,aAAW,OAAO,gBAAgB;AAChC,QAAI,CAAC,MAAM,IAAI,GAAG,GAAG;AACnB,YAAM,WAAW,UAAU,eAAe,SAAS,SAAS,IAAI,oBAAI,IAAI;AACxE,YAAM,IAAI,KAAK,QAAQ;AAAA,IACzB;AAEA,YAAQ,MAAM,IAAI,GAAG;AACrB,aAAS;AAAA,EACX;AAEA,SAAO;AACT;",
6
6
  "names": []
7
7
  }