@studiometa/js-toolkit 3.0.0-alpha.7 → 3.0.0-alpha.9
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/Base.d.ts +2 -2
- package/Base/Base.js +2 -3
- package/Base/Base.js.map +2 -2
- package/Base/managers/ChildrenManager.d.ts +1 -1
- package/Base/managers/ChildrenManager.js +8 -1
- package/Base/managers/ChildrenManager.js.map +2 -2
- package/Base/managers/EventsManager.js +14 -14
- package/Base/managers/EventsManager.js.map +2 -2
- package/Base/managers/RefsManager.js +7 -5
- package/Base/managers/RefsManager.js.map +2 -2
- package/Base/utils.d.ts +1 -3
- package/Base/utils.js +1 -4
- package/Base/utils.js.map +2 -2
- package/README.md +3 -3
- package/helpers/getDirectChildren.js +10 -5
- package/helpers/getDirectChildren.js.map +2 -2
- package/package.json +2 -2
package/Base/Base.d.ts
CHANGED
|
@@ -47,7 +47,7 @@ export type Managers = {
|
|
|
47
47
|
/**
|
|
48
48
|
* Base class.
|
|
49
49
|
*/
|
|
50
|
-
export declare class Base<T extends BaseProps = BaseProps>
|
|
50
|
+
export declare class Base<T extends BaseProps = BaseProps> {
|
|
51
51
|
/**
|
|
52
52
|
* This is a Base instance.
|
|
53
53
|
*/
|
|
@@ -189,7 +189,7 @@ export declare class Base<T extends BaseProps = BaseProps> extends EventTarget {
|
|
|
189
189
|
* @param {any[]} args The arguments to apply to the functions bound to this event.
|
|
190
190
|
* @returns {void}
|
|
191
191
|
*/
|
|
192
|
-
$emit(event: string, ...args: unknown[]): void;
|
|
192
|
+
$emit(event: string | Event, ...args: unknown[]): void;
|
|
193
193
|
/**
|
|
194
194
|
* Register and mount all instances of the component.
|
|
195
195
|
*/
|
package/Base/Base.js
CHANGED
|
@@ -14,7 +14,7 @@ import {
|
|
|
14
14
|
} from "./managers/index.js";
|
|
15
15
|
import { noop, isDev, isFunction, isArray } from "../utils/index.js";
|
|
16
16
|
let id = 0;
|
|
17
|
-
class Base
|
|
17
|
+
class Base {
|
|
18
18
|
/**
|
|
19
19
|
* This is a Base instance.
|
|
20
20
|
*/
|
|
@@ -174,7 +174,6 @@ class Base extends EventTarget {
|
|
|
174
174
|
* @param {HTMLElement} element The component's root element dd.
|
|
175
175
|
*/
|
|
176
176
|
constructor(element) {
|
|
177
|
-
super();
|
|
178
177
|
if (!element) {
|
|
179
178
|
if (isDev) {
|
|
180
179
|
throw new Error("The root element must be defined.");
|
|
@@ -385,7 +384,7 @@ class Base extends EventTarget {
|
|
|
385
384
|
if (isDev) {
|
|
386
385
|
this.__debug("$emit", event, args);
|
|
387
386
|
}
|
|
388
|
-
this.dispatchEvent(new CustomEvent(event, { detail: args }));
|
|
387
|
+
this.$el.dispatchEvent(event instanceof Event ? event : new CustomEvent(event, { detail: args }));
|
|
389
388
|
}
|
|
390
389
|
/**
|
|
391
390
|
* Register and mount all instances of the component.
|
package/Base/Base.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../packages/js-toolkit/Base/Base.ts"],
|
|
4
|
-
"sourcesContent": ["/* eslint-disable no-use-before-define */\nimport {\n getComponentElements,\n getEventTarget,\n addToQueue,\n addInstance,\n deleteInstance,\n} from './utils.js';\nimport {\n ChildrenManager,\n RefsManager,\n ServicesManager,\n EventsManager,\n OptionsManager,\n} from './managers/index.js';\nimport { noop, isDev, isFunction, isArray } from '../utils/index.js';\n\nlet id = 0;\n\nexport type BaseEl = HTMLElement & { __base__?: WeakMap<BaseConstructor, Base | 'terminated'> };\nexport type BaseConstructor<T extends Base = Base> = {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n new (...args: any[]): T;\n prototype: Base;\n} & Pick<typeof Base, keyof typeof Base>;\nexport type BaseAsyncConstructor<T extends Base = Base> = (\n instance: Base,\n) => Promise<BaseConstructor<T> | { default: BaseConstructor<T> }>;\nexport type BaseOptions = { [name: string]: unknown };\nexport type BaseRefs = { [name: string]: HTMLElement | HTMLElement[] };\nexport type BaseChildren = { [nameOrSelector: string]: Base[] | Promise<Base>[] };\nexport type BaseConfigComponents = {\n [nameOrSelector: string]: BaseConstructor | BaseAsyncConstructor;\n};\n\nexport type BaseConfig = {\n name: string;\n debug?: boolean;\n log?: boolean;\n refs?: string[];\n emits?: string[];\n components?: BaseConfigComponents;\n options?: import('./managers/OptionsManager').OptionsSchema;\n};\n\nexport type BaseProps = {\n $el?: HTMLElement;\n $options?: BaseOptions;\n $refs?: BaseRefs;\n $children?: BaseChildren;\n $parent?: Base;\n};\n\nexport type Managers = {\n ChildrenManager: typeof ChildrenManager;\n EventsManager: typeof EventsManager;\n OptionsManager: typeof OptionsManager;\n RefsManager: typeof RefsManager;\n ServicesManager: typeof ServicesManager;\n};\n\n/**\n * Base class.\n */\nexport class Base<T extends BaseProps = BaseProps> extends EventTarget {\n /**\n * This is a Base instance.\n */\n static readonly $isBase = true as const;\n\n /**\n * The instance parent.\n */\n $parent: T['$parent'] & Base = null;\n\n /**\n * The instance id.\n */\n $id: string;\n\n /**\n * The root element.\n */\n $el: T['$el'] & BaseEl;\n\n /**\n * The state of the component.\n */\n $isMounted = false;\n\n /**\n * Store the event handlers.\n */\n __eventHandlers: Map<string, Set<EventListenerOrEventListenerObject>> = new Map();\n\n /**\n * Get the root instance of the app.\n */\n get $root(): Base {\n if (!this.$parent) {\n return this;\n }\n\n let parent = this.$parent;\n let root = this.$parent;\n\n while (parent) {\n if (!parent.$parent) {\n root = parent;\n }\n\n parent = parent.$parent;\n }\n\n return root;\n }\n\n /**\n * Merge configuration with the parents' configurations.\n */\n get __config(): BaseConfig {\n let proto = Object.getPrototypeOf(this);\n let { config } = proto.constructor;\n\n while (proto.constructor.config && proto.constructor.$isBase) {\n config = { ...proto.constructor.config, ...config };\n\n if (proto.constructor.config.options) {\n config.options = { ...proto.constructor.config.options, ...config.options };\n }\n\n if (proto.constructor.config.emits && config.emits) {\n config.emits = [...proto.constructor.config.emits, ...config.emits];\n }\n\n proto = Object.getPrototypeOf(proto);\n }\n\n config.options = config.options ?? {};\n config.refs = config.refs ?? [];\n config.components = config.components ?? {};\n\n return config;\n }\n\n static config: BaseConfig = {\n name: 'Base',\n emits: [\n // hook events\n 'before-mounted',\n 'mounted',\n 'updated',\n 'destroyed',\n 'terminated',\n // default services' events\n 'ticked',\n 'scrolled',\n 'resized',\n 'moved',\n 'loaded',\n 'keyed',\n ],\n };\n\n __services: ServicesManager;\n\n get $services(): ServicesManager {\n return this.__services;\n }\n\n __refs: RefsManager & T['$refs'] & BaseRefs;\n\n get $refs(): RefsManager & T['$refs'] & BaseRefs {\n return this.__refs;\n }\n\n __options: OptionsManager & T['$options'] & BaseOptions;\n\n get $options(): OptionsManager & T['$options'] & BaseOptions {\n return this.__options;\n }\n\n __children: ChildrenManager & T['$children'] & BaseChildren;\n\n get $children(): ChildrenManager & T['$children'] & BaseChildren {\n return this.__children;\n }\n\n __events: EventsManager;\n\n /**\n * Small helper to log stuff.\n */\n get $log(): (...args: unknown[]) => void {\n return this.__options.log ? window.console.log.bind(window, `[${this.__config.name}]`) : noop;\n }\n\n /**\n * Small helper to make warning easier.\n */\n get $warn(): (...args: unknown[]) => void {\n return this.__options.log ? window.console.warn.bind(window, `[${this.__config.name}]`) : noop;\n }\n\n /**\n * Small helper to debug information.\n */\n get __debug(): (...args: unknown[]) => void {\n return isDev && this.__options.debug\n ? window.console.log.bind(window, `[debug] [${this.$id}]`)\n : noop;\n }\n\n /**\n * Get manager constructors.\n */\n get __managers(): Managers {\n return {\n ChildrenManager,\n EventsManager,\n OptionsManager,\n RefsManager,\n ServicesManager,\n };\n }\n\n /**\n * Call an instance method and emit corresponding events.\n */\n __callMethod(method: string, ...args: unknown[]): unknown {\n if (isDev) {\n this.__debug('callMethod', method, ...args);\n }\n\n this.$emit(method, ...args);\n\n // We always emit an event, but we do not call the method if it does not exist\n if (!isFunction(this[method])) {\n return null;\n }\n\n if (isDev) {\n this.__debug(method, this, ...args);\n }\n\n return this[method].call(this, ...args);\n }\n\n /**\n * Test if the given event has been bound to the instance.\n *\n * @param {string} event The event's name.\n * @returns {boolean} Wether the given event has been bound or not.\n */\n __hasEvent(event: string): boolean {\n const eventHandlers = this.__eventHandlers.get(event);\n return eventHandlers && eventHandlers.size > 0;\n }\n\n /**\n * Class constructor where all the magic takes place.\n *\n * @param {HTMLElement} element The component's root element dd.\n */\n constructor(element: HTMLElement) {\n super();\n\n if (!element) {\n if (isDev) {\n throw new Error('The root element must be defined.');\n }\n return;\n }\n\n const { __config } = this;\n\n if (__config.name === 'Base') {\n if (isDev) {\n throw new Error('The `config.name` property is required.');\n }\n return;\n }\n\n this.$id = `${__config.name}-${id}`;\n id += 1;\n\n this.$el = element;\n\n if (!this.$el.__base__) {\n this.$el.__base__ = new WeakMap();\n }\n\n this.$el.__base__.set(this.__ctor, this);\n\n for (const service of ['Options', 'Services', 'Events', 'Refs', 'Children']) {\n this[`__${service.toLowerCase()}`] = new this.__managers[`${service}Manager`](this);\n }\n\n this.$on('mounted', () => {\n addInstance(this);\n });\n this.$on('destroyed', () => {\n deleteInstance(this);\n });\n\n if (isDev) {\n this.__debug('constructor', this);\n }\n }\n\n /**\n * Trigger the `mounted` callback.\n */\n async $mount(): Promise<this> {\n if (this.$isMounted) {\n return this;\n }\n\n this.$emit('before-mounted');\n\n if (isDev) {\n this.__debug('$mount');\n }\n\n await Promise.all([\n addToQueue(() => this.$children.registerAll()),\n addToQueue(() => this.$refs.registerAll()),\n addToQueue(() => this.__events.bindRootElement()),\n addToQueue(() => this.$services.enableAll()),\n addToQueue(() => this.$children.mountAll()),\n addToQueue(() => (this.$isMounted = true)),\n addToQueue(() => this.__callMethod('mounted')),\n ]);\n\n return this;\n }\n\n /**\n * Update the instance children.\n */\n async $update(): Promise<this> {\n if (isDev) {\n this.__debug('$update');\n }\n\n await Promise.all([\n // Undo\n addToQueue(() => this.$refs.unregisterAll()),\n addToQueue(() => this.$services.disableAll()),\n // Redo\n addToQueue(() => this.$children.registerAll()),\n addToQueue(() => this.$refs.registerAll()),\n addToQueue(() => this.$services.enableAll()),\n // Update\n addToQueue(() => this.$children.updateAll()),\n addToQueue(() => this.__callMethod('updated')),\n ]);\n\n return this;\n }\n\n /**\n * Trigger the `destroyed` callback.\n */\n async $destroy(): Promise<this> {\n if (!this.$isMounted) {\n return this;\n }\n\n if (isDev) {\n this.__debug('$destroy');\n }\n\n await Promise.all([\n addToQueue(() => (this.$isMounted = false)),\n addToQueue(() => this.__events.unbindRootElement()),\n addToQueue(() => this.$refs.unregisterAll()),\n addToQueue(() => this.$services.disableAll()),\n addToQueue(() => this.$children.destroyAll()),\n addToQueue(() => this.__callMethod('destroyed')),\n ]);\n\n return this;\n }\n\n /**\n * Terminate a child instance when it is not needed anymore.\n */\n async $terminate(): Promise<void> {\n if (isDev) {\n this.__debug('$terminate');\n }\n\n await Promise.all([\n // First, destroy the component.\n addToQueue(() => this.$destroy()),\n // Execute the `terminated` hook if it exists\n addToQueue(() => this.__callMethod('terminated')),\n // Delete instance\n addToQueue(() => this.$el.__base__.set(this.__ctor, 'terminated')),\n ]);\n }\n\n /**\n * Add an emitted event.\n *\n * @param {string} event The event name.\n * @returns {void}\n */\n __addEmits(event: string): void {\n const ctor = this.__ctor;\n if (isArray(ctor.config.emits)) {\n ctor.config.emits.push(event);\n } else {\n ctor.config.emits = [event];\n }\n }\n\n /**\n * Remove an emitted event.\n *\n * @param {string} event The event name.\n * @returns {void}\n */\n __removeEmits(event: string): void {\n const ctor = this.__ctor;\n const index = ctor.config.emits.indexOf(event);\n ctor.config.emits.splice(index, 1);\n }\n\n /**\n * Get the instance constructor.\n */\n get __ctor(): BaseConstructor {\n return this.constructor as BaseConstructor;\n }\n\n /**\n * Bind a listener function to an event.\n *\n * @param {string} event\n * Name of the event.\n * @param {EventListenerOrEventListenerObject} listener\n * Function to be called.\n * @param {boolean|AddEventListenerOptions} [options]\n * Options for the `removeEventListener` method.\n * @returns {() => void}\n * A function to unbind the listener.\n */\n $on(\n event: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | AddEventListenerOptions,\n ): () => void {\n if (isDev) {\n this.__debug('$on', event, listener, options);\n }\n\n let set = this.__eventHandlers.get(event);\n\n if (!set) {\n set = new Set();\n this.__eventHandlers.set(event, set);\n }\n\n set.add(listener);\n\n const target = getEventTarget(this, event, this.__config);\n target?.addEventListener(event, listener, options);\n\n if (isDev) {\n if (!target) {\n console.warn(\n `[${this.$id}]`,\n `The \"${event}\" event is missing from the configuration and is not a native`,\n `event for the root element of type \\`${this.$el.constructor.name}\\`.`,\n );\n }\n }\n\n return () => {\n this.$off(event, listener, options);\n };\n }\n\n /**\n * Unbind a listener function from an event.\n *\n * @param {string} event\n * Name of the event.\n * @param {EventListenerOrEventListenerObject} listener\n * Function to be removed.\n * @param {boolean|EventListenerOptions} [options]\n * Options for the `removeEventListener` method.\n * @returns {void}\n */\n $off(\n event: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | EventListenerOptions,\n ) {\n if (isDev) {\n this.__debug('$off', event, listener);\n }\n\n this.__eventHandlers.get(event).delete(listener);\n\n const target = getEventTarget(this, event, this.__config);\n target?.removeEventListener(event, listener, options);\n }\n\n /**\n * Emits an event.\n *\n * @param {string} event Name of the event.\n * @param {any[]} args The arguments to apply to the functions bound to this event.\n * @returns {void}\n */\n $emit(event: string, ...args: unknown[]) {\n if (isDev) {\n this.__debug('$emit', event, args);\n }\n\n this.dispatchEvent(new CustomEvent(event, { detail: args }));\n }\n\n /**\n * Register and mount all instances of the component.\n */\n static $register(nameOrSelector?: string): Array<Promise<Base>> {\n return getComponentElements(nameOrSelector ?? this.config.name).map((el) =>\n new this(el).$mount(),\n );\n }\n}\n"],
|
|
5
|
-
"mappings": "AACA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,MAAM,OAAO,YAAY,eAAe;AAEjD,IAAI,KAAK;AA+CF,MAAM,
|
|
4
|
+
"sourcesContent": ["/* eslint-disable no-use-before-define */\nimport {\n getComponentElements,\n getEventTarget,\n addToQueue,\n addInstance,\n deleteInstance,\n} from './utils.js';\nimport {\n ChildrenManager,\n RefsManager,\n ServicesManager,\n EventsManager,\n OptionsManager,\n} from './managers/index.js';\nimport { noop, isDev, isFunction, isArray } from '../utils/index.js';\n\nlet id = 0;\n\nexport type BaseEl = HTMLElement & { __base__?: WeakMap<BaseConstructor, Base | 'terminated'> };\nexport type BaseConstructor<T extends Base = Base> = {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n new (...args: any[]): T;\n prototype: Base;\n} & Pick<typeof Base, keyof typeof Base>;\nexport type BaseAsyncConstructor<T extends Base = Base> = (\n instance: Base,\n) => Promise<BaseConstructor<T> | { default: BaseConstructor<T> }>;\nexport type BaseOptions = { [name: string]: unknown };\nexport type BaseRefs = { [name: string]: HTMLElement | HTMLElement[] };\nexport type BaseChildren = { [nameOrSelector: string]: Base[] | Promise<Base>[] };\nexport type BaseConfigComponents = {\n [nameOrSelector: string]: BaseConstructor | BaseAsyncConstructor;\n};\n\nexport type BaseConfig = {\n name: string;\n debug?: boolean;\n log?: boolean;\n refs?: string[];\n emits?: string[];\n components?: BaseConfigComponents;\n options?: import('./managers/OptionsManager').OptionsSchema;\n};\n\nexport type BaseProps = {\n $el?: HTMLElement;\n $options?: BaseOptions;\n $refs?: BaseRefs;\n $children?: BaseChildren;\n $parent?: Base;\n};\n\nexport type Managers = {\n ChildrenManager: typeof ChildrenManager;\n EventsManager: typeof EventsManager;\n OptionsManager: typeof OptionsManager;\n RefsManager: typeof RefsManager;\n ServicesManager: typeof ServicesManager;\n};\n\n/**\n * Base class.\n */\nexport class Base<T extends BaseProps = BaseProps> {\n /**\n * This is a Base instance.\n */\n static readonly $isBase = true as const;\n\n /**\n * The instance parent.\n */\n $parent: T['$parent'] & Base = null;\n\n /**\n * The instance id.\n */\n $id: string;\n\n /**\n * The root element.\n */\n $el: T['$el'] & BaseEl;\n\n /**\n * The state of the component.\n */\n $isMounted = false;\n\n /**\n * Store the event handlers.\n */\n __eventHandlers: Map<string, Set<EventListenerOrEventListenerObject>> = new Map();\n\n /**\n * Get the root instance of the app.\n */\n get $root(): Base {\n if (!this.$parent) {\n return this;\n }\n\n let parent = this.$parent;\n let root = this.$parent;\n\n while (parent) {\n if (!parent.$parent) {\n root = parent;\n }\n\n parent = parent.$parent;\n }\n\n return root;\n }\n\n /**\n * Merge configuration with the parents' configurations.\n */\n get __config(): BaseConfig {\n let proto = Object.getPrototypeOf(this);\n let { config } = proto.constructor;\n\n while (proto.constructor.config && proto.constructor.$isBase) {\n config = { ...proto.constructor.config, ...config };\n\n if (proto.constructor.config.options) {\n config.options = { ...proto.constructor.config.options, ...config.options };\n }\n\n if (proto.constructor.config.emits && config.emits) {\n config.emits = [...proto.constructor.config.emits, ...config.emits];\n }\n\n proto = Object.getPrototypeOf(proto);\n }\n\n config.options = config.options ?? {};\n config.refs = config.refs ?? [];\n config.components = config.components ?? {};\n\n return config;\n }\n\n static config: BaseConfig = {\n name: 'Base',\n emits: [\n // hook events\n 'before-mounted',\n 'mounted',\n 'updated',\n 'destroyed',\n 'terminated',\n // default services' events\n 'ticked',\n 'scrolled',\n 'resized',\n 'moved',\n 'loaded',\n 'keyed',\n ],\n };\n\n __services: ServicesManager;\n\n get $services(): ServicesManager {\n return this.__services;\n }\n\n __refs: RefsManager & T['$refs'] & BaseRefs;\n\n get $refs(): RefsManager & T['$refs'] & BaseRefs {\n return this.__refs;\n }\n\n __options: OptionsManager & T['$options'] & BaseOptions;\n\n get $options(): OptionsManager & T['$options'] & BaseOptions {\n return this.__options;\n }\n\n __children: ChildrenManager & T['$children'] & BaseChildren;\n\n get $children(): ChildrenManager & T['$children'] & BaseChildren {\n return this.__children;\n }\n\n __events: EventsManager;\n\n /**\n * Small helper to log stuff.\n */\n get $log(): (...args: unknown[]) => void {\n return this.__options.log ? window.console.log.bind(window, `[${this.__config.name}]`) : noop;\n }\n\n /**\n * Small helper to make warning easier.\n */\n get $warn(): (...args: unknown[]) => void {\n return this.__options.log ? window.console.warn.bind(window, `[${this.__config.name}]`) : noop;\n }\n\n /**\n * Small helper to debug information.\n */\n get __debug(): (...args: unknown[]) => void {\n return isDev && this.__options.debug\n ? window.console.log.bind(window, `[debug] [${this.$id}]`)\n : noop;\n }\n\n /**\n * Get manager constructors.\n */\n get __managers(): Managers {\n return {\n ChildrenManager,\n EventsManager,\n OptionsManager,\n RefsManager,\n ServicesManager,\n };\n }\n\n /**\n * Call an instance method and emit corresponding events.\n */\n __callMethod(method: string, ...args: unknown[]): unknown {\n if (isDev) {\n this.__debug('callMethod', method, ...args);\n }\n\n this.$emit(method, ...args);\n\n // We always emit an event, but we do not call the method if it does not exist\n if (!isFunction(this[method])) {\n return null;\n }\n\n if (isDev) {\n this.__debug(method, this, ...args);\n }\n\n return this[method].call(this, ...args);\n }\n\n /**\n * Test if the given event has been bound to the instance.\n *\n * @param {string} event The event's name.\n * @returns {boolean} Wether the given event has been bound or not.\n */\n __hasEvent(event: string): boolean {\n const eventHandlers = this.__eventHandlers.get(event);\n return eventHandlers && eventHandlers.size > 0;\n }\n\n /**\n * Class constructor where all the magic takes place.\n *\n * @param {HTMLElement} element The component's root element dd.\n */\n constructor(element: HTMLElement) {\n if (!element) {\n if (isDev) {\n throw new Error('The root element must be defined.');\n }\n return;\n }\n\n const { __config } = this;\n\n if (__config.name === 'Base') {\n if (isDev) {\n throw new Error('The `config.name` property is required.');\n }\n return;\n }\n\n this.$id = `${__config.name}-${id}`;\n id += 1;\n\n this.$el = element;\n\n if (!this.$el.__base__) {\n this.$el.__base__ = new WeakMap();\n }\n\n this.$el.__base__.set(this.__ctor, this);\n\n for (const service of ['Options', 'Services', 'Events', 'Refs', 'Children']) {\n this[`__${service.toLowerCase()}`] = new this.__managers[`${service}Manager`](this);\n }\n\n this.$on('mounted', () => {\n addInstance(this);\n });\n this.$on('destroyed', () => {\n deleteInstance(this);\n });\n\n if (isDev) {\n this.__debug('constructor', this);\n }\n }\n\n /**\n * Trigger the `mounted` callback.\n */\n async $mount(): Promise<this> {\n if (this.$isMounted) {\n return this;\n }\n\n this.$emit('before-mounted');\n\n if (isDev) {\n this.__debug('$mount');\n }\n\n await Promise.all([\n addToQueue(() => this.$children.registerAll()),\n addToQueue(() => this.$refs.registerAll()),\n addToQueue(() => this.__events.bindRootElement()),\n addToQueue(() => this.$services.enableAll()),\n addToQueue(() => this.$children.mountAll()),\n addToQueue(() => (this.$isMounted = true)),\n addToQueue(() => this.__callMethod('mounted')),\n ]);\n\n return this;\n }\n\n /**\n * Update the instance children.\n */\n async $update(): Promise<this> {\n if (isDev) {\n this.__debug('$update');\n }\n\n await Promise.all([\n // Undo\n addToQueue(() => this.$refs.unregisterAll()),\n addToQueue(() => this.$services.disableAll()),\n // Redo\n addToQueue(() => this.$children.registerAll()),\n addToQueue(() => this.$refs.registerAll()),\n addToQueue(() => this.$services.enableAll()),\n // Update\n addToQueue(() => this.$children.updateAll()),\n addToQueue(() => this.__callMethod('updated')),\n ]);\n\n return this;\n }\n\n /**\n * Trigger the `destroyed` callback.\n */\n async $destroy(): Promise<this> {\n if (!this.$isMounted) {\n return this;\n }\n\n if (isDev) {\n this.__debug('$destroy');\n }\n\n await Promise.all([\n addToQueue(() => (this.$isMounted = false)),\n addToQueue(() => this.__events.unbindRootElement()),\n addToQueue(() => this.$refs.unregisterAll()),\n addToQueue(() => this.$services.disableAll()),\n addToQueue(() => this.$children.destroyAll()),\n addToQueue(() => this.__callMethod('destroyed')),\n ]);\n\n return this;\n }\n\n /**\n * Terminate a child instance when it is not needed anymore.\n */\n async $terminate(): Promise<void> {\n if (isDev) {\n this.__debug('$terminate');\n }\n\n await Promise.all([\n // First, destroy the component.\n addToQueue(() => this.$destroy()),\n // Execute the `terminated` hook if it exists\n addToQueue(() => this.__callMethod('terminated')),\n // Delete instance\n addToQueue(() => this.$el.__base__.set(this.__ctor, 'terminated')),\n ]);\n }\n\n /**\n * Add an emitted event.\n *\n * @param {string} event The event name.\n * @returns {void}\n */\n __addEmits(event: string): void {\n const ctor = this.__ctor;\n if (isArray(ctor.config.emits)) {\n ctor.config.emits.push(event);\n } else {\n ctor.config.emits = [event];\n }\n }\n\n /**\n * Remove an emitted event.\n *\n * @param {string} event The event name.\n * @returns {void}\n */\n __removeEmits(event: string): void {\n const ctor = this.__ctor;\n const index = ctor.config.emits.indexOf(event);\n ctor.config.emits.splice(index, 1);\n }\n\n /**\n * Get the instance constructor.\n */\n get __ctor(): BaseConstructor {\n return this.constructor as BaseConstructor;\n }\n\n /**\n * Bind a listener function to an event.\n *\n * @param {string} event\n * Name of the event.\n * @param {EventListenerOrEventListenerObject} listener\n * Function to be called.\n * @param {boolean|AddEventListenerOptions} [options]\n * Options for the `removeEventListener` method.\n * @returns {() => void}\n * A function to unbind the listener.\n */\n $on(\n event: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | AddEventListenerOptions,\n ): () => void {\n if (isDev) {\n this.__debug('$on', event, listener, options);\n }\n\n let set = this.__eventHandlers.get(event);\n\n if (!set) {\n set = new Set();\n this.__eventHandlers.set(event, set);\n }\n\n set.add(listener);\n\n const target = getEventTarget(this, event, this.__config);\n target?.addEventListener(event, listener, options);\n\n if (isDev) {\n if (!target) {\n console.warn(\n `[${this.$id}]`,\n `The \"${event}\" event is missing from the configuration and is not a native`,\n `event for the root element of type \\`${this.$el.constructor.name}\\`.`,\n );\n }\n }\n\n return () => {\n this.$off(event, listener, options);\n };\n }\n\n /**\n * Unbind a listener function from an event.\n *\n * @param {string} event\n * Name of the event.\n * @param {EventListenerOrEventListenerObject} listener\n * Function to be removed.\n * @param {boolean|EventListenerOptions} [options]\n * Options for the `removeEventListener` method.\n * @returns {void}\n */\n $off(\n event: string,\n listener: EventListenerOrEventListenerObject,\n options?: boolean | EventListenerOptions,\n ) {\n if (isDev) {\n this.__debug('$off', event, listener);\n }\n\n this.__eventHandlers.get(event).delete(listener);\n\n const target = getEventTarget(this, event, this.__config);\n target?.removeEventListener(event, listener, options);\n }\n\n /**\n * Emits an event.\n *\n * @param {string} event Name of the event.\n * @param {any[]} args The arguments to apply to the functions bound to this event.\n * @returns {void}\n */\n $emit(event: string | Event, ...args: unknown[]) {\n if (isDev) {\n this.__debug('$emit', event, args);\n }\n\n this.$el.dispatchEvent(event instanceof Event ? event : new CustomEvent(event, { detail: args }));\n }\n\n /**\n * Register and mount all instances of the component.\n */\n static $register(nameOrSelector?: string): Array<Promise<Base>> {\n return getComponentElements(nameOrSelector ?? this.config.name).map((el) =>\n new this(el).$mount(),\n );\n }\n}\n"],
|
|
5
|
+
"mappings": "AACA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,MAAM,OAAO,YAAY,eAAe;AAEjD,IAAI,KAAK;AA+CF,MAAM,KAAsC;AAAA;AAAA;AAAA;AAAA,EAIjD,OAAgB,UAAU;AAAA;AAAA;AAAA;AAAA,EAK1B,UAA+B;AAAA;AAAA;AAAA;AAAA,EAK/B;AAAA;AAAA;AAAA;AAAA,EAKA;AAAA;AAAA;AAAA;AAAA,EAKA,aAAa;AAAA;AAAA;AAAA;AAAA,EAKb,kBAAwE,oBAAI,IAAI;AAAA;AAAA;AAAA;AAAA,EAKhF,IAAI,QAAc;AAChB,QAAI,CAAC,KAAK,SAAS;AACjB,aAAO;AAAA,IACT;AAEA,QAAI,SAAS,KAAK;AAClB,QAAI,OAAO,KAAK;AAEhB,WAAO,QAAQ;AACb,UAAI,CAAC,OAAO,SAAS;AACnB,eAAO;AAAA,MACT;AAEA,eAAS,OAAO;AAAA,IAClB;AAEA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA,EAKA,IAAI,WAAuB;AACzB,QAAI,QAAQ,OAAO,eAAe,IAAI;AAC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AAA,IACF;AAEA,WAAO,MAAM;AACX,WAAK,KAAK,OAAO,UAAU,OAAO;AAAA,IACpC;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAaA,KACE,OACA,UACA,SACA;AACA,QAAI,OAAO;AACT,WAAK,QAAQ,QAAQ,OAAO,QAAQ;AAAA,IACtC;AAEA,SAAK,gBAAgB,IAAI,KAAK,EAAE,OAAO,QAAQ;AAE/C,UAAM,SAAS,eAAe,MAAM,OAAO,KAAK,QAAQ;AACxD,YAAQ,oBAAoB,OAAO,UAAU,OAAO;AAAA,EACtD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,MAAM,UAA0B,MAAiB;AAC/C,QAAI,OAAO;AACT,WAAK,QAAQ,SAAS,OAAO,IAAI;AAAA,IACnC;AAEA,SAAK,IAAI,cAAc,iBAAiB,QAAQ,QAAQ,IAAI,YAAY,OAAO,EAAE,QAAQ,KAAK,CAAC,CAAC;AAAA,EAClG;AAAA;AAAA;AAAA;AAAA,EAKA,OAAO,UAAU,gBAA+C;AAC9D,WAAO,qBAAqB,kBAAkB,KAAK,OAAO,IAAI,EAAE;AAAA,MAAI,CAAC,OACnE,IAAI,KAAK,EAAE,EAAE,OAAO;AAAA,IACtB;AAAA,EACF;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -49,5 +49,5 @@ export declare class ChildrenManager extends AbstractManager {
|
|
|
49
49
|
* @private
|
|
50
50
|
*/
|
|
51
51
|
__register(name: string, component: BaseConstructor | BaseAsyncConstructor): void;
|
|
52
|
-
__getValue(name: string, component: BaseConstructor | BaseAsyncConstructor):
|
|
52
|
+
__getValue(name: string, component: BaseConstructor | BaseAsyncConstructor): any[];
|
|
53
53
|
}
|
|
@@ -132,7 +132,14 @@ class ChildrenManager extends AbstractManager {
|
|
|
132
132
|
if (elements.length === 0) {
|
|
133
133
|
return [];
|
|
134
134
|
}
|
|
135
|
-
|
|
135
|
+
const children = [];
|
|
136
|
+
for (const element of elements) {
|
|
137
|
+
const child = __getChild(this, element, component);
|
|
138
|
+
if (child !== "terminated") {
|
|
139
|
+
children.push(child);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
return children;
|
|
136
143
|
}
|
|
137
144
|
}
|
|
138
145
|
export {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../packages/js-toolkit/Base/managers/ChildrenManager.ts"],
|
|
4
|
-
"sourcesContent": ["import type { Base, BaseConstructor, BaseAsyncConstructor, BaseEl } from '../index.js';\nimport { AbstractManager } from './AbstractManager.js';\nimport { getComponentElements, addToQueue } from '../utils.js';\nimport { startsWith } from '../../utils/index.js';\n\n/**\n * Get a child component's instance.\n *\n * @param {ChildrenManager} that\n * @param {HTMLElement & { __base__?: WeakMap<BaseConstructor, Base> }} el\n * The root element of the child component.\n * @param {BaseConstructor|BaseAsyncConstructor} ComponentClass\n * A Base class or a Promise for async components.\n * @returns {Base|Promise<Base | 'terminated'>|'terminated'}\n * A Base instance or a Promise resolving to a Base instance.\n * @private\n */\nfunction __getChild(\n // eslint-disable-next-line no-use-before-define\n that: ChildrenManager,\n el: BaseEl,\n ComponentClass: BaseConstructor | BaseAsyncConstructor,\n): Base | Promise<Base | 'terminated'> | 'terminated' {\n const asyncComponentPromise = that.__asyncComponentPromises.get(\n ComponentClass as BaseAsyncConstructor,\n );\n\n // Test if we have a constructor and not a promise or if the promise has been resolved\n if (\n '$isBase' in ComponentClass ||\n (asyncComponentPromise && asyncComponentPromise.status === 'resolved')\n ) {\n let ctor = ComponentClass as BaseConstructor;\n\n // Get resolved constructor from weakmap.\n // Only test for existence as the status was checked before.\n if (asyncComponentPromise) {\n ctor = asyncComponentPromise.ctor;\n }\n\n // Return existing instance if it exists\n if (el.__base__ && el.__base__.has(ctor)) {\n return el.__base__.get(ctor);\n }\n\n // Return a new instance if the component class is a child of the Base class\n // eslint-disable-next-line new-cap\n const child = new ctor(el);\n Object.defineProperty(child, '$parent', { get: () => that.__base });\n return child;\n }\n\n const promise = asyncComponentPromise\n ? asyncComponentPromise.promise\n : ComponentClass(that.__base);\n\n if (!asyncComponentPromise) {\n that.__asyncComponentPromises.set(ComponentClass, {\n promise,\n status: 'pending',\n ctor: undefined,\n });\n }\n\n // Resolve async components\n return promise.then((module) => {\n // @ts-ignore\n const ctor = module.default ?? module;\n\n that.__asyncComponentPromises.set(ComponentClass, {\n promise,\n status: 'resolved',\n ctor,\n });\n\n return __getChild(that, el, ctor);\n });\n}\n\n/**\n * Execute the given hook for all children instances.\n *\n * @param {ChildrenManager} that\n * @param {'$mount'|'$update'|'$destroy'} hook The hook to execute.\n * @private\n */\n// eslint-disable-next-line no-use-before-define\nasync function __triggerHookForAll(that: ChildrenManager, hook: '$mount' | '$update' | '$destroy') {\n return addToQueue(() => {\n const promises = [];\n for (const name of that.registeredNames) {\n for (const instance of that[name]) {\n if (instance instanceof Promise) {\n promises.push(\n instance.then((resolvedInstance) =>\n addToQueue(() => that.__triggerHook(hook, resolvedInstance, name)),\n ),\n );\n } else {\n promises.push(addToQueue(() => that.__triggerHook(hook, instance, name)));\n }\n }\n }\n return Promise.all(promises);\n });\n}\n\n/**\n * Children manager.\n */\nexport class ChildrenManager extends AbstractManager {\n /**\n * Store async component promises to avoid calling them multiple times and\n * waiting for them when they are already resolved.\n */\n __asyncComponentPromises: WeakMap<\n BaseAsyncConstructor,\n {\n promise: ReturnType<BaseAsyncConstructor>;\n status: 'pending' | 'resolved';\n ctor?: BaseConstructor;\n }\n > = new WeakMap();\n\n get registeredNames(): string[] {\n return Object.keys(this).filter((key) => !startsWith(key, '__'));\n }\n\n /**\n * Register instances of all children components.\n */\n async registerAll() {\n const promises = [];\n\n for (const [name, component] of Object.entries(this.__config.components)) {\n promises.push(this.__register(name, component));\n }\n\n await Promise.all(promises);\n }\n\n /**\n * Mount all child component instances.\n */\n async mountAll() {\n await __triggerHookForAll(this, '$mount');\n }\n\n /**\n * Update all child component instances.\n */\n async updateAll() {\n await __triggerHookForAll(this, '$update');\n }\n\n /**\n * Destroy all child component instances.\n */\n async destroyAll() {\n await __triggerHookForAll(this, '$destroy');\n }\n\n /**\n * Execute the given hook for the given instance.\n *\n * @param {'$mount'|'$update'|'$destroy'} hook The hook to trigger.\n * @param {Base} instance The target instance.\n * @param {string} name The name of the component.\n * @private\n */\n async __triggerHook(hook: '$mount' | '$update' | '$destroy', instance: Base, name: string) {\n if (hook === '$update' && !instance.$isMounted) {\n // eslint-disable-next-line no-param-reassign\n hook = '$mount';\n }\n\n if (hook === '$update' || hook === '$destroy') {\n this.__eventsManager.unbindChild(name, instance);\n }\n\n if (hook === '$update' || hook === '$mount') {\n this.__eventsManager.bindChild(name, instance);\n }\n\n await instance[hook]();\n }\n\n /**\n * Register instance of a child component.\n *\n * @param {string} name\n * The name of the child component.\n * @param {BaseConstructor|BaseAsyncConstructor} component\n * A Base class or a Promise for async components.\n * @private\n */\n __register(name: string, component: BaseConstructor | BaseAsyncConstructor) {\n Object.defineProperty(this, name, {\n enumerable: true,\n configurable: true,\n get: () => this.__getValue(name, component),\n });\n }\n\n __getValue(name: string, component: BaseConstructor | BaseAsyncConstructor) {\n const elements = getComponentElements(name, this.__element);\n\n if (elements.length === 0) {\n return [];\n }\n\n
|
|
5
|
-
"mappings": "AACA,SAAS,uBAAuB;AAChC,SAAS,sBAAsB,kBAAkB;AACjD,SAAS,kBAAkB;AAc3B,SAAS,WAEP,MACA,IACA,gBACoD;AACpD,QAAM,wBAAwB,KAAK,yBAAyB;AAAA,IAC1D;AAAA,EACF;AAGA,MACE,aAAa,kBACZ,yBAAyB,sBAAsB,WAAW,YAC3D;AACA,QAAI,OAAO;AAIX,QAAI,uBAAuB;AACzB,aAAO,sBAAsB;AAAA,IAC/B;AAGA,QAAI,GAAG,YAAY,GAAG,SAAS,IAAI,IAAI,GAAG;AACxC,aAAO,GAAG,SAAS,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S;AAE1D,QAAI,SAAS,WAAW,GAAG;AACzB,aAAO,CAAC;AAAA,IACV;
|
|
4
|
+
"sourcesContent": ["import type { Base, BaseConstructor, BaseAsyncConstructor, BaseEl } from '../index.js';\nimport { AbstractManager } from './AbstractManager.js';\nimport { getComponentElements, addToQueue } from '../utils.js';\nimport { startsWith } from '../../utils/index.js';\n\n/**\n * Get a child component's instance.\n *\n * @param {ChildrenManager} that\n * @param {HTMLElement & { __base__?: WeakMap<BaseConstructor, Base> }} el\n * The root element of the child component.\n * @param {BaseConstructor|BaseAsyncConstructor} ComponentClass\n * A Base class or a Promise for async components.\n * @returns {Base|Promise<Base | 'terminated'>|'terminated'}\n * A Base instance or a Promise resolving to a Base instance.\n * @private\n */\nfunction __getChild(\n // eslint-disable-next-line no-use-before-define\n that: ChildrenManager,\n el: BaseEl,\n ComponentClass: BaseConstructor | BaseAsyncConstructor,\n): Base | Promise<Base | 'terminated'> | 'terminated' {\n const asyncComponentPromise = that.__asyncComponentPromises.get(\n ComponentClass as BaseAsyncConstructor,\n );\n\n // Test if we have a constructor and not a promise or if the promise has been resolved\n if (\n '$isBase' in ComponentClass ||\n (asyncComponentPromise && asyncComponentPromise.status === 'resolved')\n ) {\n let ctor = ComponentClass as BaseConstructor;\n\n // Get resolved constructor from weakmap.\n // Only test for existence as the status was checked before.\n if (asyncComponentPromise) {\n ctor = asyncComponentPromise.ctor;\n }\n\n // Return existing instance if it exists\n if (el.__base__ && el.__base__.has(ctor)) {\n return el.__base__.get(ctor);\n }\n\n // Return a new instance if the component class is a child of the Base class\n // eslint-disable-next-line new-cap\n const child = new ctor(el);\n Object.defineProperty(child, '$parent', { get: () => that.__base });\n return child;\n }\n\n const promise = asyncComponentPromise\n ? asyncComponentPromise.promise\n : ComponentClass(that.__base);\n\n if (!asyncComponentPromise) {\n that.__asyncComponentPromises.set(ComponentClass, {\n promise,\n status: 'pending',\n ctor: undefined,\n });\n }\n\n // Resolve async components\n return promise.then((module) => {\n // @ts-ignore\n const ctor = module.default ?? module;\n\n that.__asyncComponentPromises.set(ComponentClass, {\n promise,\n status: 'resolved',\n ctor,\n });\n\n return __getChild(that, el, ctor);\n });\n}\n\n/**\n * Execute the given hook for all children instances.\n *\n * @param {ChildrenManager} that\n * @param {'$mount'|'$update'|'$destroy'} hook The hook to execute.\n * @private\n */\n// eslint-disable-next-line no-use-before-define\nasync function __triggerHookForAll(that: ChildrenManager, hook: '$mount' | '$update' | '$destroy') {\n return addToQueue(() => {\n const promises = [];\n for (const name of that.registeredNames) {\n for (const instance of that[name]) {\n if (instance instanceof Promise) {\n promises.push(\n instance.then((resolvedInstance) =>\n addToQueue(() => that.__triggerHook(hook, resolvedInstance, name)),\n ),\n );\n } else {\n promises.push(addToQueue(() => that.__triggerHook(hook, instance, name)));\n }\n }\n }\n return Promise.all(promises);\n });\n}\n\n/**\n * Children manager.\n */\nexport class ChildrenManager extends AbstractManager {\n /**\n * Store async component promises to avoid calling them multiple times and\n * waiting for them when they are already resolved.\n */\n __asyncComponentPromises: WeakMap<\n BaseAsyncConstructor,\n {\n promise: ReturnType<BaseAsyncConstructor>;\n status: 'pending' | 'resolved';\n ctor?: BaseConstructor;\n }\n > = new WeakMap();\n\n get registeredNames(): string[] {\n return Object.keys(this).filter((key) => !startsWith(key, '__'));\n }\n\n /**\n * Register instances of all children components.\n */\n async registerAll() {\n const promises = [];\n\n for (const [name, component] of Object.entries(this.__config.components)) {\n promises.push(this.__register(name, component));\n }\n\n await Promise.all(promises);\n }\n\n /**\n * Mount all child component instances.\n */\n async mountAll() {\n await __triggerHookForAll(this, '$mount');\n }\n\n /**\n * Update all child component instances.\n */\n async updateAll() {\n await __triggerHookForAll(this, '$update');\n }\n\n /**\n * Destroy all child component instances.\n */\n async destroyAll() {\n await __triggerHookForAll(this, '$destroy');\n }\n\n /**\n * Execute the given hook for the given instance.\n *\n * @param {'$mount'|'$update'|'$destroy'} hook The hook to trigger.\n * @param {Base} instance The target instance.\n * @param {string} name The name of the component.\n * @private\n */\n async __triggerHook(hook: '$mount' | '$update' | '$destroy', instance: Base, name: string) {\n if (hook === '$update' && !instance.$isMounted) {\n // eslint-disable-next-line no-param-reassign\n hook = '$mount';\n }\n\n if (hook === '$update' || hook === '$destroy') {\n this.__eventsManager.unbindChild(name, instance);\n }\n\n if (hook === '$update' || hook === '$mount') {\n this.__eventsManager.bindChild(name, instance);\n }\n\n await instance[hook]();\n }\n\n /**\n * Register instance of a child component.\n *\n * @param {string} name\n * The name of the child component.\n * @param {BaseConstructor|BaseAsyncConstructor} component\n * A Base class or a Promise for async components.\n * @private\n */\n __register(name: string, component: BaseConstructor | BaseAsyncConstructor) {\n Object.defineProperty(this, name, {\n enumerable: true,\n configurable: true,\n get: () => this.__getValue(name, component),\n });\n }\n\n __getValue(name: string, component: BaseConstructor | BaseAsyncConstructor) {\n const elements = getComponentElements(name, this.__element);\n\n if (elements.length === 0) {\n return [];\n }\n\n\n const children = [];\n for (const element of elements) {\n const child = __getChild(this, element, component);\n if (child !== 'terminated') {\n children.push(child);\n }\n }\n\n return children;\n }\n}\n"],
|
|
5
|
+
"mappings": "AACA,SAAS,uBAAuB;AAChC,SAAS,sBAAsB,kBAAkB;AACjD,SAAS,kBAAkB;AAc3B,SAAS,WAEP,MACA,IACA,gBACoD;AACpD,QAAM,wBAAwB,KAAK,yBAAyB;AAAA,IAC1D;AAAA,EACF;AAGA,MACE,aAAa,kBACZ,yBAAyB,sBAAsB,WAAW,YAC3D;AACA,QAAI,OAAO;AAIX,QAAI,uBAAuB;AACzB,aAAO,sBAAsB;AAAA,IAC/B;AAGA,QAAI,GAAG,YAAY,GAAG,SAAS,IAAI,IAAI,GAAG;AACxC,aAAO,GAAG,SAAS,IAAI,IAAI;AAAA,IAC7B;AAIA,UAAM,QAAQ,IAAI,KAAK,EAAE;AACzB,WAAO,eAAe,OAAO,WAAW,EAAE,KAAK,MAAM,KAAK,OAAO,CAAC;AAClE,WAAO;AAAA,EACT;AAEA,QAAM,UAAU,wBACZ,sBAAsB,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,iBAAS,KAAK,KAAK;AAAA,MACrB;AAAA,IACF;AAEA,WAAO;AAAA,EACT;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import getAllProperties from "../../utils/object/getAllProperties.js";
|
|
2
2
|
import { dashCase, isArray, pascalCase } from "../../utils/index.js";
|
|
3
|
-
import { getEventTarget } from "../utils.js";
|
|
3
|
+
import { getEventTarget, eventIsNative, eventIsDefinedInConfig } from "../utils.js";
|
|
4
4
|
import { AbstractManager } from "./AbstractManager.js";
|
|
5
5
|
import { normalizeRefName } from "./RefsManager.js";
|
|
6
6
|
import { features } from "../features.js";
|
|
@@ -163,19 +163,19 @@ class EventsManager extends AbstractManager {
|
|
|
163
163
|
__childrenHandler = {
|
|
164
164
|
handleEvent: (event) => {
|
|
165
165
|
const childrenManager = this.__base.$children;
|
|
166
|
-
const
|
|
167
|
-
|
|
168
|
-
child
|
|
169
|
-
|
|
170
|
-
(
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
166
|
+
for (const childName of childrenManager.registeredNames) {
|
|
167
|
+
let index = -1;
|
|
168
|
+
for (const child of childrenManager[childName]) {
|
|
169
|
+
index++;
|
|
170
|
+
if (child.$el === event.target && (eventIsNative(event.type, child.$el) || eventIsDefinedInConfig(event.type, child.__config))) {
|
|
171
|
+
const normalizedEventName = pascalCase(event.type);
|
|
172
|
+
const normalizedChildName = pascalCase(childName);
|
|
173
|
+
const method = `on${normalizedChildName}${normalizedEventName}`;
|
|
174
|
+
const args = isArray(event.detail) ? event.detail : [];
|
|
175
|
+
this.__base[method](normalizeParams({ event, index, args, target: child }));
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
179
|
}
|
|
180
180
|
};
|
|
181
181
|
/**
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../packages/js-toolkit/Base/managers/EventsManager.ts"],
|
|
4
|
-
"sourcesContent": ["import type { Base } from '../index.js';\nimport getAllProperties from '../../utils/object/getAllProperties.js';\nimport { dashCase, isArray, pascalCase } from '../../utils/index.js';\nimport { getEventTarget, eventIsNative, eventIsDefinedInConfig } from '../utils.js';\nimport { AbstractManager } from './AbstractManager.js';\nimport { normalizeRefName } from './RefsManager.js';\nimport { features } from '../features.js';\n\nconst regexes = new Map();\n\n/**\n * Get a regex with a cache;\n *\n * @param {string} regex\n * @returns {RegExp}\n */\nfunction getRegex(regex: string): RegExp {\n if (!regexes.has(regex)) {\n regexes.set(regex, new RegExp(regex));\n }\n\n return regexes.get(regex);\n}\n\n/**\n * Get the event name from the given method and its tied ref or children name.\n *\n * @param {string} method\n * @param {string} name\n * @returns {string}\n * @private\n */\nfunction getEventNameByMethod(method: string, name = ''): string {\n const regex = getRegex(`^on${pascalCase(name)}([A-Z].*)$`);\n const [, event] = method.match(regex);\n return dashCase(event);\n}\n\n/**\n * Get the base instance methods matching the `onSomething` pattern.\n *\n * @param {EventsManager} that\n * @param {string} [name]\n * @returns {string[]}\n * @private\n */\n// eslint-disable-next-line no-use-before-define\nfunction getEventMethodsByName(that: EventsManager, name = ''): string[] {\n const regex = getRegex(`^on${pascalCase(name)}[A-Z].*$`);\n const key = regex.toString();\n\n let methods = that.__methodsCache.get(key);\n\n if (!methods) {\n methods = Array.from(\n getAllProperties(that.__base, [], (method) => regex.test(method)).reduce(\n (set, [method]) => set.add(method),\n new Set(),\n ),\n ) as string[];\n that.__methodsCache.set(key, methods);\n }\n\n return methods;\n}\n\n/**\n * Manage a ref event methods.\n *\n * @param {EventsManager} that\n * @param {string} name\n * The name of the ref.\n * @param {HTMLElement[]} elements\n * The elements of the ref.\n * @param {'add'|'remove'} [mode]\n * The action to perform: add or remove the event listeners.\n * @returns {void}\n * @private\n */\nfunction manageRef(\n // eslint-disable-next-line no-use-before-define\n that: EventsManager,\n name: string,\n elements: HTMLElement[],\n mode: 'add' | 'remove' = 'add',\n) {\n const action = `${mode}EventListener`;\n const methods = getEventMethodsByName(that, name);\n for (const method of methods) {\n const event = getEventNameByMethod(method, name);\n for (const element of elements) {\n if (element instanceof EventTarget) {\n element[action](event, that.__refsHandler);\n }\n }\n }\n}\n/**\n * Manage event methods to the given child instance.\n *\n * @param {EventsManager} that\n * @param {string} name\n * The name of the ref.\n * @param {Base} instance\n * A base instance.\n * @param {'add'|'remove'} [mode]\n * The action to perform: add or remove the event listeners.\n * @returns {void}\n * @private\n */\nfunction manageChild(\n // eslint-disable-next-line no-use-before-define\n that: EventsManager,\n name: string,\n instance: Base,\n mode: 'add' | 'remove' = 'add',\n) {\n const action = mode === 'add' ? '$on' : '$off';\n const methods = getEventMethodsByName(that, name);\n const config = instance.__config;\n for (const method of methods) {\n const event = getEventNameByMethod(method, name);\n if (getEventTarget(instance, event, config)) {\n instance[action](event, that.__childrenHandler);\n }\n }\n}\n\nconst isDocumentRegex = /^onDocument[A-Z][a-z]+/;\nconst isWindowRegex = /^onWindow[A-Z][a-z]+/;\nconst methodIsDocument = (method) => isDocumentRegex.test(method);\nconst methodIsWindow = (method) => isWindowRegex.test(method);\nconst methodIsGlobal = (method) => methodIsWindow(method) || methodIsDocument(method);\nconst getGlobalEventTarget = (method) => (methodIsDocument(method) ? document : window);\n\n/**\n * Manage event methods on the root element.\n *\n * @param {EventsManager} that\n * @param {'add'|'remove'} [mode]\n * The action to perform: add or remove the event listeners, defaults to 'add'.\n * @returns {void}\n * @private\n */\n// eslint-disable-next-line no-use-before-define\nfunction manageRootElement(that: EventsManager, mode: 'add' | 'remove' = 'add') {\n const modeMethod = `${mode}EventListener`;\n const methods = getEventMethodsByName(that);\n\n const { __base: base, __config: config } = that;\n\n for (const method of methods) {\n let event = getEventNameByMethod(method);\n\n if (methodIsGlobal(method)) {\n event = getEventNameByMethod(method, methodIsDocument(method) ? 'document' : 'window');\n const target = getGlobalEventTarget(method);\n target[modeMethod](\n event,\n methodIsDocument(method) ? that.__documentHandler : that.__windowHandler,\n );\n } else {\n const target = getEventTarget(base, event, config);\n target?.[modeMethod](event, that.__rootElementHandler);\n }\n }\n}\n\nexport type EventManagerCallbackParams = {\n event: Event | null;\n args: Array<any>;\n index: number;\n target: Element | Base | Promise<Base> | typeof window | typeof document | null;\n};\n\n/**\n * Normalize `on...` method params.\n */\nfunction normalizeParams(\n params: Partial<EventManagerCallbackParams> = {},\n): EventManagerCallbackParams {\n return {\n event: null,\n args: [],\n index: 0,\n target: null,\n ...params,\n };\n}\n\n/**\n * Event management class.\n *\n * @todo Prevent binding of `onChildOrRefEvent` to the root element\n * @todo Use event delegation?\n */\nexport class EventsManager extends AbstractManager {\n __methodsCache: Map<string, string[]> = new Map();\n\n /**\n * Event listener object for the root element.\n */\n __rootElementHandler: EventListenerObject = {\n handleEvent: (event: Event | CustomEvent) => {\n const normalizedEventName = pascalCase(event.type);\n const method = `on${normalizedEventName}`;\n const isCustomEvent = event instanceof CustomEvent;\n\n this.__base[method](\n normalizeParams({\n event,\n args: isCustomEvent ? event.detail ?? [] : [],\n target: isCustomEvent ? this.__base : this.__element,\n }),\n );\n },\n };\n\n /**\n * Event listener object for the root element.\n *\n * @type {EventListenerObject}\n */\n __documentHandler = {\n /**\n * @param {Event|CustomEvent} event\n * @returns {void}\n */\n handleEvent: (event) => {\n const normalizedEventName = pascalCase(event.type);\n const method = `onDocument${normalizedEventName}`;\n\n this.__base[method](normalizeParams({ event, target: document }));\n },\n };\n\n /**\n * Event listener object for the root element.\n *\n * @type {EventListenerObject}\n */\n __windowHandler = {\n /**\n * @param {Event|CustomEvent} event\n * @returns {void}\n */\n handleEvent: (event) => {\n const normalizedEventName = pascalCase(event.type);\n const method = `onWindow${normalizedEventName}`;\n\n this.__base[method](normalizeParams({ event, target: window }));\n },\n };\n\n /**\n * Event listener object for the refs.\n */\n __refsHandler: EventListenerObject = {\n handleEvent: (event) => {\n const ref = event.currentTarget as HTMLElement;\n const attributes = features.get('attributes');\n const refName = normalizeRefName(ref.getAttribute(attributes.ref));\n\n const normalizedRefName = pascalCase(refName);\n const normalizedEventName = pascalCase(event.type);\n const method = `on${normalizedRefName}${normalizedEventName}`;\n\n let index = 0;\n if (isArray(this.__base.$refs[refName])) {\n index = (this.__base.$refs[refName] as HTMLElement[]).indexOf(ref);\n }\n\n this.__base[method](normalizeParams({ event, index, target: ref }));\n },\n };\n\n /**\n * Event listener object for the children.\n */\n __childrenHandler: EventListenerObject = {\n handleEvent: (event: CustomEvent) => {\n const childrenManager = this.__base.$children;\n\n // @todo handle async child components\n const { name, child: resolvedChild } = childrenManager.registeredNames\n .map((childName) => ({\n name: childName,\n child: [...childrenManager[childName]].find(\n // @ts-ignore\n (instance) => instance === event.currentTarget || instance.$el === event.currentTarget,\n ),\n }))\n .find(({ child }) => child);\n\n const normalizedChildName = pascalCase(name);\n const normalizedEventName = pascalCase(event.type);\n const method = `on${normalizedChildName}${normalizedEventName}`;\n\n const index = [...childrenManager[name]].indexOf(resolvedChild);\n\n const args = isArray(event.detail) ? event.detail : [];\n this.__base[method](normalizeParams({ event, index, args, target: resolvedChild }));\n },\n };\n\n /**\n * Class constructor.\n */\n constructor(base: Base) {\n super(base);\n\n this.__hideProperties([\n '__methodsCache',\n '__rootElementHandler',\n '__refsHandler',\n '__childrenHandler',\n '__documentHandler',\n '__windowHandler',\n ]);\n }\n\n /**\n * Bind event methods to the given ref elements.\n *\n * @param {string} name\n * The name of the ref.\n * @param {HTMLElement[]} elements\n * The elements of the ref.\n * @returns {void}\n */\n bindRef(name: string, elements: HTMLElement[]) {\n manageRef(this, name, elements);\n }\n\n /**\n * Bind event methods to the given ref elements.\n *\n * @param {string} name\n * The name of the ref.\n * @param {HTMLElement[]} elements\n * The elements of the ref.\n * @returns {void}\n */\n unbindRef(name: string, elements: HTMLElement[]) {\n manageRef(this, name, elements, 'remove');\n }\n\n /**\n * Bind event methods to the given child instance.\n *\n * @param {string} name\n * The name of the ref.\n * @param {Base} instance\n * A base instance.\n * @returns {void}\n */\n bindChild(name: string, instance: Base) {\n manageChild(this, name, instance);\n }\n\n /**\n * Unbind event methods to the given child instance.\n *\n * @param {string} name\n * The name of the ref.\n * @param {Base} instance\n * A base instance.\n * @returns {void}\n */\n unbindChild(name: string, instance: Base) {\n manageChild(this, name, instance, 'remove');\n }\n\n /**\n * Bind event methods on the root element.\n *\n * @returns {void}\n */\n bindRootElement() {\n manageRootElement(this);\n }\n\n /**\n * Unbind event method from the root element.\n *\n * @returns {void}\n */\n unbindRootElement() {\n manageRootElement(this, 'remove');\n }\n}\n"],
|
|
5
|
-
"mappings": "AACA,OAAO,sBAAsB;AAC7B,SAAS,UAAU,SAAS,kBAAkB;AAC9C,SAAS,
|
|
4
|
+
"sourcesContent": ["import type { Base, BaseProps } from '../index.js';\nimport getAllProperties from '../../utils/object/getAllProperties.js';\nimport { dashCase, isArray, pascalCase } from '../../utils/index.js';\nimport { getEventTarget, eventIsNative, eventIsDefinedInConfig } from '../utils.js';\nimport { AbstractManager } from './AbstractManager.js';\nimport { normalizeRefName } from './RefsManager.js';\nimport { features } from '../features.js';\n\nconst regexes = new Map();\n\n/**\n * Get a regex with a cache;\n *\n * @param {string} regex\n * @returns {RegExp}\n */\nfunction getRegex(regex: string): RegExp {\n if (!regexes.has(regex)) {\n regexes.set(regex, new RegExp(regex));\n }\n\n return regexes.get(regex);\n}\n\n/**\n * Get the event name from the given method and its tied ref or children name.\n *\n * @param {string} method\n * @param {string} name\n * @returns {string}\n * @private\n */\nfunction getEventNameByMethod(method: string, name = ''): string {\n const regex = getRegex(`^on${pascalCase(name)}([A-Z].*)$`);\n const [, event] = method.match(regex);\n return dashCase(event);\n}\n\n/**\n * Get the base instance methods matching the `onSomething` pattern.\n *\n * @param {EventsManager} that\n * @param {string} [name]\n * @returns {string[]}\n * @private\n */\n// eslint-disable-next-line no-use-before-define\nfunction getEventMethodsByName(that: EventsManager, name = ''): string[] {\n const regex = getRegex(`^on${pascalCase(name)}[A-Z].*$`);\n const key = regex.toString();\n\n let methods = that.__methodsCache.get(key);\n\n if (!methods) {\n methods = Array.from(\n getAllProperties(that.__base, [], (method) => regex.test(method)).reduce(\n (set, [method]) => set.add(method),\n new Set(),\n ),\n ) as string[];\n that.__methodsCache.set(key, methods);\n }\n\n return methods;\n}\n\n/**\n * Manage a ref event methods.\n *\n * @param {EventsManager} that\n * @param {string} name\n * The name of the ref.\n * @param {HTMLElement[]} elements\n * The elements of the ref.\n * @param {'add'|'remove'} [mode]\n * The action to perform: add or remove the event listeners.\n * @returns {void}\n * @private\n */\nfunction manageRef(\n // eslint-disable-next-line no-use-before-define\n that: EventsManager,\n name: string,\n elements: HTMLElement[],\n mode: 'add' | 'remove' = 'add',\n) {\n const action = `${mode}EventListener`;\n const methods = getEventMethodsByName(that, name);\n for (const method of methods) {\n const event = getEventNameByMethod(method, name);\n for (const element of elements) {\n if (element instanceof EventTarget) {\n element[action](event, that.__refsHandler);\n }\n }\n }\n}\n/**\n * Manage event methods to the given child instance.\n *\n * @param {EventsManager} that\n * @param {string} name\n * The name of the ref.\n * @param {Base} instance\n * A base instance.\n * @param {'add'|'remove'} [mode]\n * The action to perform: add or remove the event listeners.\n * @returns {void}\n * @private\n */\nfunction manageChild(\n // eslint-disable-next-line no-use-before-define\n that: EventsManager,\n name: string,\n instance: Base,\n mode: 'add' | 'remove' = 'add',\n) {\n const action = mode === 'add' ? '$on' : '$off';\n const methods = getEventMethodsByName(that, name);\n const config = instance.__config;\n for (const method of methods) {\n const event = getEventNameByMethod(method, name);\n if (getEventTarget(instance, event, config)) {\n instance[action](event, that.__childrenHandler);\n }\n }\n}\n\nconst isDocumentRegex = /^onDocument[A-Z][a-z]+/;\nconst isWindowRegex = /^onWindow[A-Z][a-z]+/;\nconst methodIsDocument = (method) => isDocumentRegex.test(method);\nconst methodIsWindow = (method) => isWindowRegex.test(method);\nconst methodIsGlobal = (method) => methodIsWindow(method) || methodIsDocument(method);\nconst getGlobalEventTarget = (method) => (methodIsDocument(method) ? document : window);\n\n/**\n * Manage event methods on the root element.\n *\n * @param {EventsManager} that\n * @param {'add'|'remove'} [mode]\n * The action to perform: add or remove the event listeners, defaults to 'add'.\n * @returns {void}\n * @private\n */\n// eslint-disable-next-line no-use-before-define\nfunction manageRootElement(that: EventsManager, mode: 'add' | 'remove' = 'add') {\n const modeMethod = `${mode}EventListener`;\n const methods = getEventMethodsByName(that);\n\n const { __base: base, __config: config } = that;\n\n for (const method of methods) {\n let event = getEventNameByMethod(method);\n\n if (methodIsGlobal(method)) {\n event = getEventNameByMethod(method, methodIsDocument(method) ? 'document' : 'window');\n const target = getGlobalEventTarget(method);\n target[modeMethod](\n event,\n methodIsDocument(method) ? that.__documentHandler : that.__windowHandler,\n );\n } else {\n const target = getEventTarget(base, event, config);\n target?.[modeMethod](event, that.__rootElementHandler);\n }\n }\n}\n\nexport type EventManagerCallbackParams = {\n event: Event | null;\n args: Array<any>;\n index: number;\n target: Element | Base | Promise<Base> | typeof window | typeof document | null;\n};\n\n/**\n * Normalize `on...` method params.\n */\nfunction normalizeParams(\n params: Partial<EventManagerCallbackParams> = {},\n): EventManagerCallbackParams {\n return {\n event: null,\n args: [],\n index: 0,\n target: null,\n ...params,\n };\n}\n\n/**\n * Event management class.\n *\n * @todo Prevent binding of `onChildOrRefEvent` to the root element\n * @todo Use event delegation?\n */\nexport class EventsManager extends AbstractManager {\n __methodsCache: Map<string, string[]> = new Map();\n\n /**\n * Event listener object for the root element.\n */\n __rootElementHandler: EventListenerObject = {\n handleEvent: (event: Event | CustomEvent) => {\n const normalizedEventName = pascalCase(event.type);\n const method = `on${normalizedEventName}`;\n const isCustomEvent = event instanceof CustomEvent;\n\n this.__base[method](\n normalizeParams({\n event,\n args: isCustomEvent ? (event.detail ?? []) : [],\n target: isCustomEvent ? this.__base : this.__element,\n }),\n );\n },\n };\n\n /**\n * Event listener object for the root element.\n *\n * @type {EventListenerObject}\n */\n __documentHandler = {\n /**\n * @param {Event|CustomEvent} event\n * @returns {void}\n */\n handleEvent: (event) => {\n const normalizedEventName = pascalCase(event.type);\n const method = `onDocument${normalizedEventName}`;\n\n this.__base[method](normalizeParams({ event, target: document }));\n },\n };\n\n /**\n * Event listener object for the root element.\n *\n * @type {EventListenerObject}\n */\n __windowHandler = {\n /**\n * @param {Event|CustomEvent} event\n * @returns {void}\n */\n handleEvent: (event) => {\n const normalizedEventName = pascalCase(event.type);\n const method = `onWindow${normalizedEventName}`;\n\n this.__base[method](normalizeParams({ event, target: window }));\n },\n };\n\n /**\n * Event listener object for the refs.\n */\n __refsHandler: EventListenerObject = {\n handleEvent: (event) => {\n const ref = event.currentTarget as HTMLElement;\n const attributes = features.get('attributes');\n const refName = normalizeRefName(ref.getAttribute(attributes.ref));\n\n const normalizedRefName = pascalCase(refName);\n const normalizedEventName = pascalCase(event.type);\n const method = `on${normalizedRefName}${normalizedEventName}`;\n\n let index = 0;\n if (isArray(this.__base.$refs[refName])) {\n index = (this.__base.$refs[refName] as HTMLElement[]).indexOf(ref);\n }\n\n this.__base[method](normalizeParams({ event, index, target: ref }));\n },\n };\n\n /**\n * Event listener object for the children.\n */\n __childrenHandler: EventListenerObject = {\n handleEvent: (event: CustomEvent) => {\n const childrenManager = this.__base.$children;\n\n for (const childName of childrenManager.registeredNames) {\n let index = -1;\n\n for (const child of childrenManager[childName] as Base<BaseProps>[]) {\n index++;\n\n if (\n child.$el === event.target &&\n (eventIsNative(event.type, child.$el) ||\n eventIsDefinedInConfig(event.type, child.__config))\n ) {\n const normalizedEventName = pascalCase(event.type);\n const normalizedChildName = pascalCase(childName);\n const method = `on${normalizedChildName}${normalizedEventName}`;\n const args = isArray(event.detail) ? event.detail : [];\n this.__base[method](normalizeParams({ event, index, args, target: child }));\n }\n }\n }\n },\n };\n\n /**\n * Class constructor.\n */\n constructor(base: Base) {\n super(base);\n\n this.__hideProperties([\n '__methodsCache',\n '__rootElementHandler',\n '__refsHandler',\n '__childrenHandler',\n '__documentHandler',\n '__windowHandler',\n ]);\n }\n\n /**\n * Bind event methods to the given ref elements.\n *\n * @param {string} name\n * The name of the ref.\n * @param {HTMLElement[]} elements\n * The elements of the ref.\n * @returns {void}\n */\n bindRef(name: string, elements: HTMLElement[]) {\n manageRef(this, name, elements);\n }\n\n /**\n * Bind event methods to the given ref elements.\n *\n * @param {string} name\n * The name of the ref.\n * @param {HTMLElement[]} elements\n * The elements of the ref.\n * @returns {void}\n */\n unbindRef(name: string, elements: HTMLElement[]) {\n manageRef(this, name, elements, 'remove');\n }\n\n /**\n * Bind event methods to the given child instance.\n *\n * @param {string} name\n * The name of the ref.\n * @param {Base} instance\n * A base instance.\n * @returns {void}\n */\n bindChild(name: string, instance: Base) {\n manageChild(this, name, instance);\n }\n\n /**\n * Unbind event methods to the given child instance.\n *\n * @param {string} name\n * The name of the ref.\n * @param {Base} instance\n * A base instance.\n * @returns {void}\n */\n unbindChild(name: string, instance: Base) {\n manageChild(this, name, instance, 'remove');\n }\n\n /**\n * Bind event methods on the root element.\n *\n * @returns {void}\n */\n bindRootElement() {\n manageRootElement(this);\n }\n\n /**\n * Unbind event method from the root element.\n *\n * @returns {void}\n */\n unbindRootElement() {\n manageRootElement(this, 'remove');\n }\n}\n"],
|
|
5
|
+
"mappings": "AACA,OAAO,sBAAsB;AAC7B,SAAS,UAAU,SAAS,kBAAkB;AAC9C,SAAS,gBAAgB,eAAe,8BAA8B;AACtE,SAAS,uBAAuB;AAChC,SAAS,wBAAwB;AACjC,SAAS,gBAAgB;AAEzB,MAAM,UAAU,oBAAI,IAAI;AAQxB,SAAS,SAAS,OAAuB;AACvC,MAAI,CAAC,QAAQ,IAAI,KAAK,GAAG;AACvB,YAAQ,IAAI,OAAO,IAAI,OAAO,KAAK,CAAC;AAAA,EACtC;AAEA,SAAO,QAAQ,IAAI,KAAK;AAC1B;AAUA,SAAS,qBAAqB,QAAgB,OAAO,IAAY;AAC/D,QAAM,QAAQ,SAAS,MAAM,WAAW,IAAI,CAAC,YAAY;AACzD,QAAM,CAAC,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M,MAAM,QAAQ;AAAA,EAClC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWA,YAAY,MAAc,UAAgB;AACxC,gBAAY,MAAM,MAAM,UAAU,QAAQ;AAAA,EAC5C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,kBAAkB;AAChB,sBAAkB,IAAI;AAAA,EACxB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,oBAAoB;AAClB,sBAAkB,MAAM,QAAQ;AAAA,EAClC;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -36,11 +36,13 @@ function __register(that, refName) {
|
|
|
36
36
|
const propName = normalizeRefName(refName);
|
|
37
37
|
const { name } = that.__base.$options;
|
|
38
38
|
const attributes = features.get("attributes");
|
|
39
|
-
const refs =
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
)
|
|
43
|
-
|
|
39
|
+
const refs = [];
|
|
40
|
+
const selector = `[${attributes.ref}="${refName}"],[${attributes.ref}="${name}.${refName}"]`;
|
|
41
|
+
for (const ref of that.__element.querySelectorAll(selector)) {
|
|
42
|
+
if (refBelongToInstance(ref, that.__element, name)) {
|
|
43
|
+
refs.push(ref);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
44
46
|
if (isDev && !isMultiple && refs.length > 1) {
|
|
45
47
|
console.warn(
|
|
46
48
|
`[${that.__base.$id}]`,
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../packages/js-toolkit/Base/managers/RefsManager.ts"],
|
|
4
|
-
"sourcesContent": ["import { AbstractManager } from './AbstractManager.js';\nimport {\n isDev,\n isArray,\n isDefined,\n getAncestorWhereUntil,\n endsWith,\n startsWith,\n memo,\n camelCase,\n} from '../../utils/index.js';\nimport { features } from '../features.js';\n\nconst NORMALIZE_REF_NAME_REGEX = /\\[\\]$/;\nconst NAMESPACED_REF_REGEX = /^(.*\\.)/;\n\n/**\n * Normalize the name of ref.\n */\nexport const normalizeRefName = memo(function normalizeRefName(name: string) {\n let normalizedName = name;\n\n if (endsWith(name, '[]')) {\n normalizedName = normalizedName.replace(NORMALIZE_REF_NAME_REGEX, '');\n }\n\n if (normalizedName.includes('.')) {\n return normalizedName.replace(NAMESPACED_REF_REGEX, '');\n }\n\n return normalizedName;\n});\n\n/**\n * Filter refs belonging to the related Base instance.\n */\nfunction refBelongToInstance(ref: HTMLElement, rootElement: HTMLElement, name: string) {\n const attributes = features.get('attributes');\n const isPrefixed = startsWith(ref.getAttribute(attributes.ref), name);\n const firstComponentAncestor = getAncestorWhereUntil(\n ref,\n (el) =>\n el &&\n (isPrefixed\n ? el.getAttribute(attributes.component) === name && el\n : el.getAttribute(attributes.component)) &&\n el !== rootElement,\n (el) => el === rootElement,\n );\n\n return firstComponentAncestor === rootElement;\n}\n\n/**\n * Register one ref.\n *\n * @param {RefsManager} that\n * @param {string} refName The ref name.\n * @private\n */\nfunction __register(that: RefsManager, refName: string) {\n const isMultiple = endsWith(refName, '[]');\n const propName = normalizeRefName(refName);\n const { name } = that.__base.$options;\n const attributes = features.get('attributes');\n
|
|
5
|
-
"mappings": "AAAA,SAAS,uBAAuB;AAChC;AAAA,EACE;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,gBAAgB;AAEzB,MAAM,2BAA2B;AACjC,MAAM,uBAAuB;AAKtB,MAAM,mBAAmB,KAAK,SAASA,kBAAiB,MAAc;AAC3E,MAAI,iBAAiB;AAErB,MAAI,SAAS,MAAM,IAAI,GAAG;AACxB,qBAAiB,eAAe,QAAQ,0BAA0B,EAAE;AAAA,EACtE;AAEA,MAAI,eAAe,SAAS,GAAG,GAAG;AAChC,WAAO,eAAe,QAAQ,sBAAsB,EAAE;AAAA,EACxD;AAEA,SAAO;AACT,CAAC;AAKD,SAAS,oBAAoB,KAAkB,aAA0B,MAAc;AACrF,QAAM,aAAa,SAAS,IAAI,YAAY;AAC5C,QAAM,aAAa,WAAW,IAAI,aAAa,WAAW,GAAG,GAAG,IAAI;AACpE,QAAM,yBAAyB;AAAA,IAC7B;AAAA,IACA,CAAC,OACC,OACC,aACG,GAAG,aAAa,WAAW,SAAS,MAAM,QAAQ,KAClD,GAAG,aAAa,WAAW,SAAS,MACxC,OAAO;AAAA,IACT,CAAC,OAAO,OAAO;AAAA,EACjB;AAEA,SAAO,2BAA2B;AACpC;AASA,SAAS,WAAW,MAAmB,SAAiB;AACtD,QAAM,aAAa,SAAS,SAAS,IAAI;AACzC,QAAM,WAAW,iBAAiB,OAAO;AACzC,QAAM,EAAE,KAAK,IAAI,KAAK,OAAO;AAC7B,QAAM,aAAa,SAAS,IAAI,YAAY;
|
|
4
|
+
"sourcesContent": ["import { AbstractManager } from './AbstractManager.js';\nimport {\n isDev,\n isArray,\n isDefined,\n getAncestorWhereUntil,\n endsWith,\n startsWith,\n memo,\n camelCase,\n} from '../../utils/index.js';\nimport { features } from '../features.js';\n\nconst NORMALIZE_REF_NAME_REGEX = /\\[\\]$/;\nconst NAMESPACED_REF_REGEX = /^(.*\\.)/;\n\n/**\n * Normalize the name of ref.\n */\nexport const normalizeRefName = memo(function normalizeRefName(name: string) {\n let normalizedName = name;\n\n if (endsWith(name, '[]')) {\n normalizedName = normalizedName.replace(NORMALIZE_REF_NAME_REGEX, '');\n }\n\n if (normalizedName.includes('.')) {\n return normalizedName.replace(NAMESPACED_REF_REGEX, '');\n }\n\n return normalizedName;\n});\n\n/**\n * Filter refs belonging to the related Base instance.\n */\nfunction refBelongToInstance(ref: HTMLElement, rootElement: HTMLElement, name: string) {\n const attributes = features.get('attributes');\n const isPrefixed = startsWith(ref.getAttribute(attributes.ref), name);\n const firstComponentAncestor = getAncestorWhereUntil(\n ref,\n (el) =>\n el &&\n (isPrefixed\n ? el.getAttribute(attributes.component) === name && el\n : el.getAttribute(attributes.component)) &&\n el !== rootElement,\n (el) => el === rootElement,\n );\n\n return firstComponentAncestor === rootElement;\n}\n\n/**\n * Register one ref.\n *\n * @param {RefsManager} that\n * @param {string} refName The ref name.\n * @private\n */\nfunction __register(that: RefsManager, refName: string) {\n const isMultiple = endsWith(refName, '[]');\n const propName = normalizeRefName(refName);\n const { name } = that.__base.$options;\n const attributes = features.get('attributes');\n const refs = [] as HTMLElement[];\n const selector = `[${attributes.ref}=\"${refName}\"],[${attributes.ref}=\"${name}.${refName}\"]`;\n\n for (const ref of that.__element.querySelectorAll<HTMLElement>(selector)) {\n if (refBelongToInstance(ref, that.__element, name)) {\n refs.push(ref);\n }\n }\n\n /* v8 ignore next 7 */\n if (isDev && !isMultiple && refs.length > 1) {\n console.warn(\n `[${that.__base.$id}]`,\n `The \"${refName}\" ref has been found multiple times.`,\n 'Did you forgot to add the `[]` suffix to its name?',\n );\n }\n\n if (refs.length) {\n that.__eventsManager.bindRef(refName, refs);\n }\n\n Object.defineProperty(that, camelCase(propName), {\n // @todo remove usage of non-multiple refs as array\n value: isMultiple || refs.length > 1 ? refs : refs[0],\n enumerable: true,\n configurable: true,\n });\n}\n\n/**\n * Unregister one ref.\n */\nfunction __unregister(that: RefsManager, refName: string) {\n const propName = normalizeRefName(refName);\n const refs = isArray(that[propName]) ? that[propName] : [that[propName]];\n that.__eventsManager.unbindRef(refName, refs);\n}\n\n/**\n * Refs Manager\n *\n * @todo Use `MutationObserver` to automatically update refs?\n */\nexport class RefsManager extends AbstractManager {\n /**\n * Get refs configuration.\n */\n get __refs() {\n return this.__config.refs ?? [];\n }\n\n /**\n * Register all refs.\n */\n registerAll() {\n for (const refName of this.__refs) __register(this, refName);\n }\n\n /**\n * Unregister all refs.\n */\n unregisterAll() {\n for (const refName of this.__refs) __unregister(this, refName);\n }\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,uBAAuB;AAChC;AAAA,EACE;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;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,QAAQ,OAAO;AAAA,MACf;AAAA,IACF;AAAA,EACF;AAEA,MAAI,KAAK,QAAQ;AACf,SAAK,gBAAgB,QAAQ,SAAS,IAAI;AAAA,EAC5C;AAEA,SAAO,eAAe,MAAM,UAAU,QAAQ,GAAG;AAAA;AAAA,IAE/C,OAAO,cAAc,KAAK,SAAS,IAAI,OAAO,KAAK,CAAC;AAAA,IACpD,YAAY;AAAA,IACZ,cAAc;AAAA,EAChB,CAAC;AACH;AAKA,SAAS,aAAa,MAAmB,SAAiB;AACxD,QAAM,WAAW,iBAAiB,OAAO;AACzC,QAAM,OAAO,QAAQ,KAAK,QAAQ,CAAC,IAAI,KAAK,QAAQ,IAAI,CAAC,KAAK,QAAQ,CAAC;AACvE,OAAK,gBAAgB,UAAU,SAAS,IAAI;AAC9C;AAOO,MAAM,oBAAoB,gBAAgB;AAAA;AAAA;AAAA;AAAA,EAI/C,IAAI,SAAS;AACX,WAAO,KAAK,SAAS,QAAQ,CAAC;AAAA,EAChC;AAAA;AAAA;AAAA;AAAA,EAKA,cAAc;AACZ,eAAW,WAAW,KAAK,OAAQ,YAAW,MAAM,OAAO;AAAA,EAC7D;AAAA;AAAA;AAAA;AAAA,EAKA,gBAAgB;AACd,eAAW,WAAW,KAAK,OAAQ,cAAa,MAAM,OAAO;AAAA,EAC/D;AACF;",
|
|
6
6
|
"names": ["normalizeRefName"]
|
|
7
7
|
}
|
package/Base/utils.d.ts
CHANGED
|
@@ -24,10 +24,8 @@ export declare function eventIsDefinedInConfig(event: string, config: BaseConfig
|
|
|
24
24
|
export declare function eventIsNative(event: string, element: HTMLElement): boolean;
|
|
25
25
|
/**
|
|
26
26
|
* Get the target of a given event.
|
|
27
|
-
*
|
|
28
|
-
* @todo Return false in v3 if event is not defined or not native to prevent adding a listener.
|
|
29
27
|
*/
|
|
30
|
-
export declare function getEventTarget(instance: Base, event: string, config: BaseConfig): Base
|
|
28
|
+
export declare function getEventTarget(instance: Base, event: string, config: BaseConfig): Base['$el'];
|
|
31
29
|
/**
|
|
32
30
|
* Get all mounted instances or the ones from a given component.
|
|
33
31
|
*/
|
package/Base/utils.js
CHANGED
|
@@ -50,10 +50,7 @@ function eventIsNative(event, element) {
|
|
|
50
50
|
return isDefined(element[`on${event}`]);
|
|
51
51
|
}
|
|
52
52
|
function getEventTarget(instance, event, config) {
|
|
53
|
-
if (eventIsDefinedInConfig(event, config)) {
|
|
54
|
-
return instance;
|
|
55
|
-
}
|
|
56
|
-
if (eventIsNative(event, instance.$el)) {
|
|
53
|
+
if (eventIsDefinedInConfig(event, config) || eventIsNative(event, instance.$el)) {
|
|
57
54
|
return instance.$el;
|
|
58
55
|
}
|
|
59
56
|
}
|
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, isDev, SmartQueue } 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 */\nfunction getSelector(nameOrSelector: string): string {\n const { component } = features.get('attributes');\n const key = component + nameOrSelector;\n\n if (!selectors.has(key)) {\n const parts = [\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 * @returns {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
|
|
5
|
-
"mappings": "AAAA,SAAS,SAAS,WAAkB,kBAAkB;AAEtD,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;AAKlB,SAAS,YAAY,gBAAgC;AACnD,QAAM,EAAE,UAAU,IAAI,SAAS,IAAI,YAAY;AAC/C,QAAM,MAAM,YAAY;AAExB,MAAI,CAAC,UAAU,IAAI,GAAG,GAAG;AACvB,UAAM,QAAQ;AAAA;AAAA,MAEZ,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;
|
|
4
|
+
"sourcesContent": ["import { isArray, isDefined, isDev, SmartQueue } 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 */\nfunction getSelector(nameOrSelector: string): string {\n const { component } = features.get('attributes');\n const key = component + nameOrSelector;\n\n if (!selectors.has(key)) {\n const parts = [\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 * @returns {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(\n instance: Base,\n event: string,\n config: BaseConfig,\n): Base['$el'] {\n if (eventIsDefinedInConfig(event, config) || eventIsNative(event, instance.$el)) {\n return instance.$el;\n }\n}\n\nconst instances = new Set<Base>();\n\n/**\n * Get all mounted instances or the ones from a given component.\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 instances) {\n if (instance instanceof ctor) {\n filteredInstances.add(instance as InstanceType<T>);\n }\n }\n return filteredInstances;\n } else {\n return new Set(instances);\n }\n}\n\nexport function addInstance(instance: Base) {\n instances.add(instance);\n}\n\nexport function deleteInstance(instance: Base) {\n instances.delete(instance);\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,SAAS,WAAkB,kBAAkB;AAEtD,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;AAKlB,SAAS,YAAY,gBAAgC;AACnD,QAAM,EAAE,UAAU,IAAI,SAAS,IAAI,YAAY;AAC/C,QAAM,MAAM,YAAY;AAExB,MAAI,CAAC,UAAU,IAAI,GAAG,GAAG;AACvB,UAAM,QAAQ;AAAA;AAAA,MAEZ,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,UAAk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/)
|
|
4
4
|
[](https://www.npmjs.com/package/@studiometa/js-toolkit/v/next)
|
|
@@ -28,7 +28,7 @@ This project is a JavaScript micro-framework (along with its utility functions)
|
|
|
28
28
|
- Initializing components in the right place at the right time
|
|
29
29
|
- Defining dependencies between components
|
|
30
30
|
|
|
31
|
-
Visit [js-toolkit.studiometa.dev](https://js-toolkit.studiometa.dev) to learn more.
|
|
31
|
+
Visit [js-toolkit.studiometa.dev](https://js-toolkit.studiometa.dev) to learn more, or jump directly to [ui.studiometa.dev](https://ui.studiometa.dev) to discover existing components.
|
|
32
32
|
|
|
33
33
|
## Quick overview
|
|
34
34
|
|
|
@@ -127,7 +127,7 @@ class App extends Base {
|
|
|
127
127
|
export default createApp(App);
|
|
128
128
|
```
|
|
129
129
|
|
|
130
|
-
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=
|
|
130
|
+
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.
|
|
131
131
|
|
|
132
132
|
## Contributing
|
|
133
133
|
|
|
@@ -8,12 +8,17 @@ function getDirectChildren(parentInstance, parentName, childrenName) {
|
|
|
8
8
|
if (!isArray(nestedParents) || nestedParents.length <= 0) {
|
|
9
9
|
return children;
|
|
10
10
|
}
|
|
11
|
-
|
|
12
|
-
|
|
11
|
+
const directChildren = [];
|
|
12
|
+
for (const child of children) {
|
|
13
|
+
for (const nestedParent of nestedParents) {
|
|
13
14
|
const nestedChildren = nestedParent.$children[childrenName];
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
15
|
+
if (isArray(nestedChildren) && nestedChildren.includes(child)) {
|
|
16
|
+
continue;
|
|
17
|
+
}
|
|
18
|
+
directChildren.push(child);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
return directChildren;
|
|
17
22
|
}
|
|
18
23
|
function isDirectChild(parentInstance, parentName, childrenName, childInstance) {
|
|
19
24
|
return getDirectChildren(parentInstance, parentName, childrenName).includes(childInstance);
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../packages/js-toolkit/helpers/getDirectChildren.ts"],
|
|
4
|
-
"sourcesContent": ["import { Base, BaseProps } from '../Base/index.js';\nimport { isArray } from '../utils/index.js';\n\n/**\n * Get direct children from a parent when working with nested components.\n *\n * @template {Base} T\n * @param {Base} parentInstance\n * @param {string} parentName\n * @param {string} childrenName\n * @returns {T[]}\n */\nexport function getDirectChildren<T extends Base = Base>(\n parentInstance: Base,\n parentName: string,\n childrenName: string,\n): T[] {\n const children = parentInstance.$children[childrenName] as Base<BaseProps>[];\n const nestedParents = parentInstance.$children[parentName] as Base<BaseProps>[];\n\n if (!isArray(children)) {\n return [];\n }\n\n if (!isArray(nestedParents) || nestedParents.length <= 0) {\n return children as T[];\n }\n\n
|
|
5
|
-
"mappings": "AACA,SAAS,eAAe;AAWjB,SAAS,kBACd,gBACA,YACA,cACK;AACL,QAAM,WAAW,eAAe,UAAU,YAAY;AACtD,QAAM,gBAAgB,eAAe,UAAU,UAAU;AAEzD,MAAI,CAAC,QAAQ,QAAQ,GAAG;AACtB,WAAO,CAAC;AAAA,EACV;AAEA,MAAI,CAAC,QAAQ,aAAa,KAAK,cAAc,UAAU,GAAG;AACxD,WAAO;AAAA,EACT;AAEA,
|
|
4
|
+
"sourcesContent": ["import { Base, BaseProps } from '../Base/index.js';\nimport { isArray } from '../utils/index.js';\n\n/**\n * Get direct children from a parent when working with nested components.\n *\n * @template {Base} T\n * @param {Base} parentInstance\n * @param {string} parentName\n * @param {string} childrenName\n * @returns {T[]}\n */\nexport function getDirectChildren<T extends Base = Base>(\n parentInstance: Base,\n parentName: string,\n childrenName: string,\n): T[] {\n const children = parentInstance.$children[childrenName] as Base<BaseProps>[];\n const nestedParents = parentInstance.$children[parentName] as Base<BaseProps>[];\n\n if (!isArray(children)) {\n return [];\n }\n\n if (!isArray(nestedParents) || nestedParents.length <= 0) {\n return children as T[];\n }\n\n const directChildren = [];\n\n for (const child of children) {\n for (const nestedParent of nestedParents) {\n const nestedChildren = nestedParent.$children[childrenName] as Base<BaseProps>[];\n\n if (isArray(nestedChildren) && nestedChildren.includes(child)) {\n continue;\n }\n\n directChildren.push(child);\n }\n }\n\n return directChildren;\n}\n\n/**\n * Test if a component instance is a direct child from the given component.\n *\n * @param {Base} parentInstance\n * @param {string} parentName\n * @param {string} childrenName\n * @param {Base} childInstance\n * @returns {boolean}\n */\nexport function isDirectChild(parentInstance, parentName, childrenName, childInstance) {\n return getDirectChildren(parentInstance, parentName, childrenName).includes(childInstance);\n}\n"],
|
|
5
|
+
"mappings": "AACA,SAAS,eAAe;AAWjB,SAAS,kBACd,gBACA,YACA,cACK;AACL,QAAM,WAAW,eAAe,UAAU,YAAY;AACtD,QAAM,gBAAgB,eAAe,UAAU,UAAU;AAEzD,MAAI,CAAC,QAAQ,QAAQ,GAAG;AACtB,WAAO,CAAC;AAAA,EACV;AAEA,MAAI,CAAC,QAAQ,aAAa,KAAK,cAAc,UAAU,GAAG;AACxD,WAAO;AAAA,EACT;AAEA,QAAM,iBAAiB,CAAC;AAExB,aAAW,SAAS,UAAU;AAC5B,eAAW,gBAAgB,eAAe;AACxC,YAAM,iBAAiB,aAAa,UAAU,YAAY;AAE1D,UAAI,QAAQ,cAAc,KAAK,eAAe,SAAS,KAAK,GAAG;AAC7D;AAAA,MACF;AAEA,qBAAe,KAAK,KAAK;AAAA,IAC3B;AAAA,EACF;AAEA,SAAO;AACT;AAWO,SAAS,cAAc,gBAAgB,YAAY,cAAc,eAAe;AACrF,SAAO,kBAAkB,gBAAgB,YAAY,YAAY,EAAE,SAAS,aAAa;AAC3F;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@studiometa/js-toolkit",
|
|
3
|
-
"version": "3.0.0-alpha.
|
|
3
|
+
"version": "3.0.0-alpha.9",
|
|
4
4
|
"description": "A set of useful little bits of JavaScript to boost your project! 🚀",
|
|
5
5
|
"publishConfig": {
|
|
6
6
|
"access": "public"
|
|
@@ -39,7 +39,7 @@
|
|
|
39
39
|
"toolkit"
|
|
40
40
|
],
|
|
41
41
|
"dependencies": {
|
|
42
|
-
"@motionone/easing": "^10.
|
|
42
|
+
"@motionone/easing": "^10.18.0",
|
|
43
43
|
"deepmerge": "^4.3.1"
|
|
44
44
|
}
|
|
45
45
|
}
|