@studiometa/js-toolkit 3.4.3 → 3.6.0-beta.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/Base.d.ts +21 -1
- package/Base/Base.js +47 -5
- package/Base/Base.js.map +2 -2
- package/Base/managers/AbstractManager.d.ts +2 -2
- package/Base/managers/EventsManager.js +1 -1
- package/Base/managers/EventsManager.js.map +2 -2
- package/Base/utils.d.ts +1 -1
- package/Base/utils.js +1 -2
- package/Base/utils.js.map +2 -2
- package/decorators/withBreakpointManager.js +1 -1
- package/decorators/withBreakpointManager.js.map +2 -2
- package/helpers/createApp.js +8 -17
- package/helpers/createApp.js.map +2 -2
- package/helpers/defineFeatures.d.ts +7 -0
- package/helpers/defineFeatures.js +21 -0
- package/helpers/defineFeatures.js.map +7 -0
- package/helpers/getDirectChildren.js +4 -3
- package/helpers/getDirectChildren.js.map +2 -2
- package/helpers/index.d.ts +3 -0
- package/helpers/index.js +12 -0
- package/helpers/index.js.map +2 -2
- package/helpers/logTree.d.ts +17 -0
- package/helpers/logTree.js +59 -0
- package/helpers/logTree.js.map +7 -0
- package/helpers/queryComponent.d.ts +28 -0
- package/helpers/queryComponent.js +66 -0
- package/helpers/queryComponent.js.map +7 -0
- package/index.d.ts +1 -1
- package/index.js +1 -1
- package/index.js.map +1 -1
- package/package.json +1 -1
- package/services/AbstractService.d.ts +1 -1
- package/services/AbstractService.js +1 -1
- package/services/AbstractService.js.map +2 -2
- package/services/DragService.d.ts +5 -5
- package/services/RafService.d.ts +1 -1
- package/services/RafService.js +13 -7
- package/services/RafService.js.map +2 -2
- package/services/ScrollService.d.ts +21 -3
- package/services/ScrollService.js +55 -7
- package/services/ScrollService.js.map +2 -2
- package/utils/collide/boundingRectToCircle.d.ts +2 -2
- package/utils/css/animate.js +166 -96
- package/utils/css/animate.js.map +2 -2
- package/utils/css/transform.js +12 -13
- package/utils/css/transform.js.map +2 -2
- package/utils/index.d.ts +1 -0
- package/utils/index.js +1 -0
- package/utils/index.js.map +2 -2
- package/utils/math/smoothTo.d.ts +24 -6
- package/utils/memoize.d.ts +1 -1
- package/utils/object/getAllProperties.js +4 -2
- package/utils/object/getAllProperties.js.map +2 -2
- package/utils/scheduler.d.ts +1 -1
- package/utils/storage/createLocalStorageProvider.d.ts +2 -0
- package/utils/storage/createLocalStorageProvider.js +32 -0
- package/utils/storage/createLocalStorageProvider.js.map +7 -0
- package/utils/storage/createMemoryStorageProvider.d.ts +2 -0
- package/utils/storage/createMemoryStorageProvider.js +27 -0
- package/utils/storage/createMemoryStorageProvider.js.map +7 -0
- package/utils/storage/createNoopProvider.d.ts +2 -0
- package/utils/storage/createNoopProvider.js +23 -0
- package/utils/storage/createNoopProvider.js.map +7 -0
- package/utils/storage/createSessionStorageProvider.d.ts +2 -0
- package/utils/storage/createSessionStorageProvider.js +31 -0
- package/utils/storage/createSessionStorageProvider.js.map +7 -0
- package/utils/storage/createStorage.d.ts +2 -0
- package/utils/storage/createStorage.js +100 -0
- package/utils/storage/createStorage.js.map +7 -0
- package/utils/storage/createUrlSearchParamsInHashProvider.d.ts +2 -0
- package/utils/storage/createUrlSearchParamsInHashProvider.js +57 -0
- package/utils/storage/createUrlSearchParamsInHashProvider.js.map +7 -0
- package/utils/storage/createUrlSearchParamsProvider.d.ts +2 -0
- package/utils/storage/createUrlSearchParamsProvider.js +41 -0
- package/utils/storage/createUrlSearchParamsProvider.js.map +7 -0
- package/utils/storage/getBrowserContext.d.ts +1 -0
- package/utils/storage/getBrowserContext.js +17 -0
- package/utils/storage/getBrowserContext.js.map +7 -0
- package/utils/storage/getGlobalStorage.d.ts +1 -0
- package/utils/storage/getGlobalStorage.js +7 -0
- package/utils/storage/getGlobalStorage.js.map +7 -0
- package/utils/storage/getStorageKeys.d.ts +1 -0
- package/utils/storage/getStorageKeys.js +12 -0
- package/utils/storage/getStorageKeys.js.map +7 -0
- package/utils/storage/index.d.ts +8 -0
- package/utils/storage/index.js +62 -0
- package/utils/storage/index.js.map +7 -0
- package/utils/storage/providers.d.ts +11 -0
- package/utils/storage/providers.js +30 -0
- package/utils/storage/providers.js.map +7 -0
- package/utils/storage/serializers.d.ts +2 -0
- package/utils/storage/serializers.js +14 -0
- package/utils/storage/serializers.js.map +7 -0
- package/utils/storage/types.d.ts +33 -0
- package/utils/storage/types.js +1 -0
- package/utils/storage/types.js.map +7 -0
- package/utils/storage.d.ts +1 -0
- package/utils/storage.js +2 -0
- package/utils/storage.js.map +7 -0
- package/utils/string/changeCase.js +1 -1
- package/utils/string/changeCase.js.map +2 -2
- package/utils/tween.js +5 -5
- package/utils/tween.js.map +2 -2
- package/tsconfig.build.tsbuildinfo +0 -1
package/Base/Base.d.ts
CHANGED
|
@@ -91,14 +91,21 @@ export declare class Base<T extends BaseProps = BaseProps> {
|
|
|
91
91
|
__eventHandlers: Map<string, Set<EventListenerOrEventListenerObject>>;
|
|
92
92
|
/**
|
|
93
93
|
* Get the root instance of the app.
|
|
94
|
+
* @deprecated Use `$closest(name)` instead. Will be removed in v4.
|
|
94
95
|
* @link https://js-toolkit.studiometa.dev/api/instance-properties.html#root
|
|
95
96
|
*/
|
|
96
97
|
get $root(): Base;
|
|
97
98
|
/**
|
|
98
99
|
* The parent instance if the current instance is registered as a child component in a parent component.
|
|
100
|
+
* @deprecated Use `$closest(name)` instead. Will be removed in v4.
|
|
99
101
|
* @link https://js-toolkit.studiometa.dev/api/instance-properties.html#parent
|
|
100
102
|
*/
|
|
101
|
-
get $parent(): T['$parent'] & Base | null;
|
|
103
|
+
get $parent(): (T['$parent'] & Base) | null;
|
|
104
|
+
/**
|
|
105
|
+
* Internal parent resolution without deprecation warning.
|
|
106
|
+
* @internal
|
|
107
|
+
*/
|
|
108
|
+
get __parent(): (T['$parent'] & Base) | null;
|
|
102
109
|
/**
|
|
103
110
|
* Merge configuration with the parents' configurations.
|
|
104
111
|
* @private
|
|
@@ -130,9 +137,22 @@ export declare class Base<T extends BaseProps = BaseProps> {
|
|
|
130
137
|
__children: ChildrenManager<T['$children'] & BaseChildren>;
|
|
131
138
|
/**
|
|
132
139
|
* Children.
|
|
140
|
+
* @deprecated Use `$query(name)` instead. Will be removed in v4.
|
|
133
141
|
* @link https://js-toolkit.studiometa.dev/api/instance-properties.html#children
|
|
134
142
|
*/
|
|
135
143
|
get $children(): T['$children'] & BaseChildren;
|
|
144
|
+
/**
|
|
145
|
+
* Get all descendant component instances matching the given query.
|
|
146
|
+
* Sugar for `queryComponentAll(query, { from: this.$el })`.
|
|
147
|
+
* @link https://js-toolkit.studiometa.dev/api/instance-methods.html#query-query
|
|
148
|
+
*/
|
|
149
|
+
$query<U extends Base = Base>(query: string): U[];
|
|
150
|
+
/**
|
|
151
|
+
* Get the closest ancestor component instance matching the given query.
|
|
152
|
+
* Sugar for `closestComponent(query, { from: this.$el })`.
|
|
153
|
+
* @link https://js-toolkit.studiometa.dev/api/instance-methods.html#closest-query
|
|
154
|
+
*/
|
|
155
|
+
$closest<U extends Base = Base>(query: string): U | undefined;
|
|
136
156
|
__events: EventsManager;
|
|
137
157
|
/**
|
|
138
158
|
* Small helper to log stuff.
|
package/Base/Base.js
CHANGED
|
@@ -16,6 +16,7 @@ import {
|
|
|
16
16
|
OptionsManager
|
|
17
17
|
} from "./managers/index.js";
|
|
18
18
|
import { getInstanceFromElement } from "../helpers/getInstanceFromElement.js";
|
|
19
|
+
import { queryComponentAll, closestComponent } from "../helpers/queryComponent.js";
|
|
19
20
|
import { noop, isDev, isFunction, isArray } from "../utils/index.js";
|
|
20
21
|
let id = 0;
|
|
21
22
|
class Base {
|
|
@@ -75,27 +76,46 @@ class Base {
|
|
|
75
76
|
__eventHandlers = /* @__PURE__ */ new Map();
|
|
76
77
|
/**
|
|
77
78
|
* Get the root instance of the app.
|
|
79
|
+
* @deprecated Use `$closest(name)` instead. Will be removed in v4.
|
|
78
80
|
* @link https://js-toolkit.studiometa.dev/api/instance-properties.html#root
|
|
79
81
|
*/
|
|
80
82
|
get $root() {
|
|
81
|
-
if (
|
|
83
|
+
if (isDev) {
|
|
84
|
+
console.warn(
|
|
85
|
+
`[${this.$id}] $root is deprecated and will be removed in v4. Use $closest(name) instead.`
|
|
86
|
+
);
|
|
87
|
+
}
|
|
88
|
+
if (!this.__parent) {
|
|
82
89
|
return this;
|
|
83
90
|
}
|
|
84
|
-
let parent = this
|
|
85
|
-
let root = this
|
|
91
|
+
let parent = this.__parent;
|
|
92
|
+
let root = this.__parent;
|
|
86
93
|
while (parent) {
|
|
87
|
-
if (!parent
|
|
94
|
+
if (!parent.__parent) {
|
|
88
95
|
root = parent;
|
|
89
96
|
}
|
|
90
|
-
parent = parent
|
|
97
|
+
parent = parent.__parent;
|
|
91
98
|
}
|
|
92
99
|
return root;
|
|
93
100
|
}
|
|
94
101
|
/**
|
|
95
102
|
* The parent instance if the current instance is registered as a child component in a parent component.
|
|
103
|
+
* @deprecated Use `$closest(name)` instead. Will be removed in v4.
|
|
96
104
|
* @link https://js-toolkit.studiometa.dev/api/instance-properties.html#parent
|
|
97
105
|
*/
|
|
98
106
|
get $parent() {
|
|
107
|
+
if (isDev) {
|
|
108
|
+
console.warn(
|
|
109
|
+
`[${this.$id}] $parent is deprecated and will be removed in v4. Use $closest(name) instead.`
|
|
110
|
+
);
|
|
111
|
+
}
|
|
112
|
+
return this.__parent;
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Internal parent resolution without deprecation warning.
|
|
116
|
+
* @internal
|
|
117
|
+
*/
|
|
118
|
+
get __parent() {
|
|
99
119
|
const parents = /* @__PURE__ */ new Set();
|
|
100
120
|
for (const instance of getInstances()) {
|
|
101
121
|
if (!instance.$config.components) continue;
|
|
@@ -162,11 +182,33 @@ class Base {
|
|
|
162
182
|
__children;
|
|
163
183
|
/**
|
|
164
184
|
* Children.
|
|
185
|
+
* @deprecated Use `$query(name)` instead. Will be removed in v4.
|
|
165
186
|
* @link https://js-toolkit.studiometa.dev/api/instance-properties.html#children
|
|
166
187
|
*/
|
|
167
188
|
get $children() {
|
|
189
|
+
if (isDev) {
|
|
190
|
+
console.warn(
|
|
191
|
+
`[${this.$id}] $children is deprecated and will be removed in v4. Use $query(name) instead.`
|
|
192
|
+
);
|
|
193
|
+
}
|
|
168
194
|
return this.__children.props;
|
|
169
195
|
}
|
|
196
|
+
/**
|
|
197
|
+
* Get all descendant component instances matching the given query.
|
|
198
|
+
* Sugar for `queryComponentAll(query, { from: this.$el })`.
|
|
199
|
+
* @link https://js-toolkit.studiometa.dev/api/instance-methods.html#query-query
|
|
200
|
+
*/
|
|
201
|
+
$query(query) {
|
|
202
|
+
return queryComponentAll(query, { from: this.$el });
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* Get the closest ancestor component instance matching the given query.
|
|
206
|
+
* Sugar for `closestComponent(query, { from: this.$el })`.
|
|
207
|
+
* @link https://js-toolkit.studiometa.dev/api/instance-methods.html#closest-query
|
|
208
|
+
*/
|
|
209
|
+
$closest(query) {
|
|
210
|
+
return closestComponent(query, { from: this.$el });
|
|
211
|
+
}
|
|
170
212
|
__events;
|
|
171
213
|
/**
|
|
172
214
|
* Small helper to log stuff.
|
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 addToRegistry,\n getInstances,\n findClosestInstance,\n} from './utils.js';\nimport {\n ChildrenManager,\n RefsManager,\n ServicesManager,\n EventsManager,\n OptionsManager,\n} from './managers/index.js';\nimport { getInstanceFromElement } from '../helpers/getInstanceFromElement.js';\nimport { noop, isDev, isFunction, isArray } from '../utils/index.js';\n\nlet id = 0;\n\nexport type BaseEl = HTMLElement & { __base__?: Map<string, 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 *\n * @link https://js-toolkit.studiometa.dev/api/\n */\nexport class Base<T extends BaseProps = BaseProps> {\n /**\n * Declare the `this.constructor` type\n * @link https://github.com/microsoft/TypeScript/issues/3841#issuecomment-2381594311\n */\n declare ['constructor']: BaseConstructor;\n\n /**\n * This is a Base instance.\n */\n static readonly $isBase = true as const;\n\n /**\n * Config.\n * @link https://js-toolkit.studiometa.dev/api/configuration.html\n */\n static config: BaseConfig = {\n name: 'Base',\n emits: [\n // hook events\n 'before-mounted',\n 'mounted',\n 'after-mounted',\n 'updated',\n 'before-destroyed',\n 'destroyed',\n 'after-destroyed',\n 'terminated',\n // default services' events\n 'ticked',\n 'scrolled',\n 'resized',\n 'moved',\n 'loaded',\n 'keyed',\n ],\n };\n\n /**\n * The instance id.\n * @link https://js-toolkit.studiometa.dev/api/instance-properties.html#id\n */\n $id: string;\n\n /**\n * The root element.\n * @link https://js-toolkit.studiometa.dev/api/instance-properties.html#el\n */\n $el: T['$el'] & BaseEl;\n\n /**\n * The state of the component.\n * @link https://js-toolkit.studiometa.dev/api/instance-properties.html#isMounted\n */\n $isMounted = false;\n\n /**\n * Is the component currently mounting itself and its children?\n * @private\n */\n __isMounting = false;\n\n /**\n * Store the event handlers.\n * @private\n */\n __eventHandlers: Map<string, Set<EventListenerOrEventListenerObject>> = new Map();\n\n /**\n * Get the root instance of the app.\n * @link https://js-toolkit.studiometa.dev/api/instance-properties.html#root\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 * The parent instance if the current instance is registered as a child component in a parent component.\n * @link https://js-toolkit.studiometa.dev/api/instance-properties.html#parent\n */\n get $parent(): T['$parent'] & Base | null {\n const parents = new Set<T['$parent'] & Base>();\n\n for (const instance of getInstances()) {\n if (!instance.$config.components) continue;\n\n if (\n Object.values(instance.$config.components).includes(this.constructor) &&\n instance.$el.contains(this.$el)\n ) {\n parents.add(instance);\n }\n }\n\n const closest = findClosestInstance(this.$el, parents);\n\n return closest ?? null;\n }\n\n /**\n * Merge configuration with the parents' configurations.\n * @private\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 /**\n * The normalized config of the component.\n * @link https://js-toolkit.studiometa.dev/api/instance-properties.html#config\n */\n get $config() {\n return this.__config;\n }\n\n __services: ServicesManager;\n\n /**\n * Services.\n * @link https://js-toolkit.studiometa.dev/api/instance-properties.html#services\n */\n get $services(): ServicesManager {\n return this.__services;\n }\n\n __refs: RefsManager<T['$refs'] & BaseRefs>;\n\n /**\n * Refs.\n * @link https://js-toolkit.studiometa.dev/api/instance-properties.html#refs\n */\n get $refs(): T['$refs'] & BaseRefs {\n return this.__refs.props;\n }\n\n __options: OptionsManager<T['$options'] & BaseOptions>;\n\n /**\n * Options.\n * @link https://js-toolkit.studiometa.dev/api/instance-properties.html#options\n */\n get $options(): T['$options'] & BaseOptions {\n return this.__options.props;\n }\n\n __children: ChildrenManager<T['$children'] & BaseChildren>;\n\n /**\n * Children.\n * @link https://js-toolkit.studiometa.dev/api/instance-properties.html#children\n */\n get $children(): T['$children'] & BaseChildren {\n return this.__children.props;\n }\n\n __events: EventsManager;\n\n /**\n * Small helper to log stuff.\n * @link https://js-toolkit.studiometa.dev/api/instance-methods.html#log-content\n */\n get $log(): (...args: unknown[]) => void {\n return this.$options.log ? window.console.log.bind(window, `[${this.$id}]`) : noop;\n }\n\n /**\n * Small helper to make warning easier.\n * @link https://js-toolkit.studiometa.dev/api/instance-methods.html#warn-content\n */\n get $warn(): (...args: unknown[]) => void {\n return this.$options.log ? window.console.warn.bind(window, `[${this.$id}]`) : noop;\n }\n\n /**\n * Small helper to debug information.\n * @internal\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 * @internal\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 * @internal\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 * @return {boolean} Wether the given event has been bound or not.\n * @internal\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 * @link https://js-toolkit.studiometa.dev/api/instantiation.html\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 // Add current component to the registry\n addToRegistry($config.name, this.constructor);\n\n this.$id = `${$config.name}-${id}`;\n id += 1;\n\n this.$el = element;\n this.$el.__base__ ??= new Map();\n this.$el.__base__.set($config.name, 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('before-mounted', () => {\n addInstance(this);\n });\n this.$on('after-destroyed', () => {\n deleteInstance(this);\n });\n\n if (isDev) {\n this.__debug('constructor', this);\n }\n }\n\n /**\n * Trigger the `mounted` callback.\n * @link https://js-toolkit.studiometa.dev/api/instance-methods.html#mount\n */\n async $mount(): Promise<this> {\n if (this.$isMounted || this.__isMounting) {\n return this;\n }\n\n this.__isMounting = true;\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 ]);\n\n await addToQueue(() => {\n this.$isMounted = true;\n this.__callMethod('mounted');\n });\n\n this.__isMounting = false;\n this.$emit('after-mounted');\n\n return this;\n }\n\n /**\n * Update the instance children.\n * @link https://js-toolkit.studiometa.dev/api/instance-methods.html#update\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 ]);\n\n await addToQueue(() => this.__callMethod('updated'));\n\n return this;\n }\n\n /**\n * Trigger the `destroyed` callback.\n * @link https://js-toolkit.studiometa.dev/api/instance-methods.html#destroy\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 this.$emit('before-destroyed');\n this.$isMounted = false;\n\n await Promise.all([\n addToQueue(() => this.__events.unbindRootElement()),\n addToQueue(() => this.__refs.unregisterAll()),\n addToQueue(() => this.__services.disableAll()),\n addToQueue(() => this.__children.destroyAll()),\n ]);\n\n await addToQueue(() => this.__callMethod('destroyed'));\n\n this.$emit('after-destroyed');\n\n return this;\n }\n\n /**\n * Terminate a child instance when it is not needed anymore.\n * @link https://js-toolkit.studiometa.dev/api/instance-methods.html#terminate\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.$config.name, 'terminated')),\n ]);\n }\n\n /**\n * Add an emitted event.\n *\n * @param {string} event The event name.\n * @return {void}\n * @internal\n */\n __addEmits(event: string): void {\n const ctor = this.constructor;\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 * @return {void}\n * @internal\n */\n __removeEmits(event: string): void {\n const ctor = this.constructor;\n const index = ctor.config.emits.indexOf(event);\n ctor.config.emits.splice(index, 1);\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 * @return {() => void}\n * A function to unbind the listener.\n * @link https://js-toolkit.studiometa.dev/api/instance-methods.html#on-event-callback-options\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 * @return {void}\n * @link https://js-toolkit.studiometa.dev/api/instance-methods.html#off-event-callback-options\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 * @return {void}\n * @link https://js-toolkit.studiometa.dev/api/instance-methods.html#emit-event-args\n */\n $emit(event: string | Event, ...args: unknown[]) {\n if (isDev) {\n this.__debug('$emit', event, args);\n }\n\n this.$el.dispatchEvent(\n event instanceof Event ? event : new CustomEvent(event, { detail: args }),\n );\n }\n\n /**\n * Register and mount all instances of the component.\n * @link https://js-toolkit.studiometa.dev/api/static-methods.html#register-nameorselector-string\n */\n static $register<T extends BaseProps = BaseProps, U extends typeof Base<T> = typeof Base<T>>(\n this: U,\n nameOrSelector?: string,\n ): Promise<InstanceType<U>>[] {\n addToRegistry(nameOrSelector ?? this.config.name, this);\n\n return getComponentElements(nameOrSelector ?? this.config.name).map(\n async (el) =>\n getInstanceFromElement(el, this) ?? (new this(el).$mount() as Promise<InstanceType<U>>),\n );\n }\n}\n"],
|
|
5
|
-
"mappings": "AACA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;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,8BAA8B;AACvC,SAAS,MAAM,OAAO,YAAY,eAAe;AAEjD,IAAI,KAAK;AAiDF,MAAM,KAAsC;AAAA;AAAA;AAAA;AAAA,EAUjD,OAAgB,UAAU;AAAA;AAAA;AAAA;AAAA;AAAA,EAM1B,OAAO,SAAqB;AAAA,IAC1B,MAAM;AAAA,IACN,OAAO;AAAA;AAAA,MAEL;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA;AAAA,MAEA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,aAAa;AAAA;AAAA;AAAA;AAAA;AAAA,EAMb,eAAe;AAAA;AAAA;AAAA;AAAA;AAAA,EAMf,kBAAwE,oBAAI,IAAI;AAAA;AAAA;AAAA;AAAA;AAAA,
|
|
4
|
+
"sourcesContent": ["/* eslint-disable no-use-before-define */\nimport {\n getComponentElements,\n getEventTarget,\n addToQueue,\n addInstance,\n deleteInstance,\n addToRegistry,\n getInstances,\n findClosestInstance,\n} from './utils.js';\nimport {\n ChildrenManager,\n RefsManager,\n ServicesManager,\n EventsManager,\n OptionsManager,\n} from './managers/index.js';\nimport { getInstanceFromElement } from '../helpers/getInstanceFromElement.js';\nimport { queryComponentAll, closestComponent } from '../helpers/queryComponent.js';\nimport { noop, isDev, isFunction, isArray } from '../utils/index.js';\n\nlet id = 0;\n\nexport type BaseEl = HTMLElement & { __base__?: Map<string, 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 *\n * @link https://js-toolkit.studiometa.dev/api/\n */\nexport class Base<T extends BaseProps = BaseProps> {\n /**\n * Declare the `this.constructor` type\n * @link https://github.com/microsoft/TypeScript/issues/3841#issuecomment-2381594311\n */\n declare ['constructor']: BaseConstructor;\n\n /**\n * This is a Base instance.\n */\n static readonly $isBase = true as const;\n\n /**\n * Config.\n * @link https://js-toolkit.studiometa.dev/api/configuration.html\n */\n static config: BaseConfig = {\n name: 'Base',\n emits: [\n // hook events\n 'before-mounted',\n 'mounted',\n 'after-mounted',\n 'updated',\n 'before-destroyed',\n 'destroyed',\n 'after-destroyed',\n 'terminated',\n // default services' events\n 'ticked',\n 'scrolled',\n 'resized',\n 'moved',\n 'loaded',\n 'keyed',\n ],\n };\n\n /**\n * The instance id.\n * @link https://js-toolkit.studiometa.dev/api/instance-properties.html#id\n */\n $id: string;\n\n /**\n * The root element.\n * @link https://js-toolkit.studiometa.dev/api/instance-properties.html#el\n */\n $el: T['$el'] & BaseEl;\n\n /**\n * The state of the component.\n * @link https://js-toolkit.studiometa.dev/api/instance-properties.html#isMounted\n */\n $isMounted = false;\n\n /**\n * Is the component currently mounting itself and its children?\n * @private\n */\n __isMounting = false;\n\n /**\n * Store the event handlers.\n * @private\n */\n __eventHandlers: Map<string, Set<EventListenerOrEventListenerObject>> = new Map();\n\n /**\n * Get the root instance of the app.\n * @deprecated Use `$closest(name)` instead. Will be removed in v4.\n * @link https://js-toolkit.studiometa.dev/api/instance-properties.html#root\n */\n get $root(): Base {\n if (isDev) {\n console.warn(\n `[${this.$id}] $root is deprecated and will be removed in v4. Use $closest(name) instead.`,\n );\n }\n\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 * The parent instance if the current instance is registered as a child component in a parent component.\n * @deprecated Use `$closest(name)` instead. Will be removed in v4.\n * @link https://js-toolkit.studiometa.dev/api/instance-properties.html#parent\n */\n get $parent(): T['$parent'] & Base | null {\n if (isDev) {\n console.warn(\n `[${this.$id}] $parent is deprecated and will be removed in v4. Use $closest(name) instead.`,\n );\n }\n\n return this.__parent;\n }\n\n /**\n * Internal parent resolution without deprecation warning.\n * @internal\n */\n get __parent(): T['$parent'] & Base | null {\n const parents = new Set<T['$parent'] & Base>();\n\n for (const instance of getInstances()) {\n if (!instance.$config.components) continue;\n\n if (\n Object.values(instance.$config.components).includes(this.constructor) &&\n instance.$el.contains(this.$el)\n ) {\n parents.add(instance);\n }\n }\n\n const closest = findClosestInstance(this.$el, parents);\n\n return closest ?? null;\n }\n\n /**\n * Merge configuration with the parents' configurations.\n * @private\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 /**\n * The normalized config of the component.\n * @link https://js-toolkit.studiometa.dev/api/instance-properties.html#config\n */\n get $config() {\n return this.__config;\n }\n\n __services: ServicesManager;\n\n /**\n * Services.\n * @link https://js-toolkit.studiometa.dev/api/instance-properties.html#services\n */\n get $services(): ServicesManager {\n return this.__services;\n }\n\n __refs: RefsManager<T['$refs'] & BaseRefs>;\n\n /**\n * Refs.\n * @link https://js-toolkit.studiometa.dev/api/instance-properties.html#refs\n */\n get $refs(): T['$refs'] & BaseRefs {\n return this.__refs.props;\n }\n\n __options: OptionsManager<T['$options'] & BaseOptions>;\n\n /**\n * Options.\n * @link https://js-toolkit.studiometa.dev/api/instance-properties.html#options\n */\n get $options(): T['$options'] & BaseOptions {\n return this.__options.props;\n }\n\n __children: ChildrenManager<T['$children'] & BaseChildren>;\n\n /**\n * Children.\n * @deprecated Use `$query(name)` instead. Will be removed in v4.\n * @link https://js-toolkit.studiometa.dev/api/instance-properties.html#children\n */\n get $children(): T['$children'] & BaseChildren {\n if (isDev) {\n console.warn(\n `[${this.$id}] $children is deprecated and will be removed in v4. Use $query(name) instead.`,\n );\n }\n\n return this.__children.props;\n }\n\n /**\n * Get all descendant component instances matching the given query.\n * Sugar for `queryComponentAll(query, { from: this.$el })`.\n * @link https://js-toolkit.studiometa.dev/api/instance-methods.html#query-query\n */\n $query<U extends Base = Base>(query: string): U[] {\n return queryComponentAll<U>(query, { from: this.$el });\n }\n\n /**\n * Get the closest ancestor component instance matching the given query.\n * Sugar for `closestComponent(query, { from: this.$el })`.\n * @link https://js-toolkit.studiometa.dev/api/instance-methods.html#closest-query\n */\n $closest<U extends Base = Base>(query: string): U | undefined {\n return closestComponent<U>(query, { from: this.$el });\n }\n\n __events: EventsManager;\n\n /**\n * Small helper to log stuff.\n * @link https://js-toolkit.studiometa.dev/api/instance-methods.html#log-content\n */\n get $log(): (...args: unknown[]) => void {\n return this.$options.log ? window.console.log.bind(window, `[${this.$id}]`) : noop;\n }\n\n /**\n * Small helper to make warning easier.\n * @link https://js-toolkit.studiometa.dev/api/instance-methods.html#warn-content\n */\n get $warn(): (...args: unknown[]) => void {\n return this.$options.log ? window.console.warn.bind(window, `[${this.$id}]`) : noop;\n }\n\n /**\n * Small helper to debug information.\n * @internal\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 * @internal\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 * @internal\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 * @return {boolean} Wether the given event has been bound or not.\n * @internal\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 * @link https://js-toolkit.studiometa.dev/api/instantiation.html\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 // Add current component to the registry\n addToRegistry($config.name, this.constructor);\n\n this.$id = `${$config.name}-${id}`;\n id += 1;\n\n this.$el = element;\n this.$el.__base__ ??= new Map();\n this.$el.__base__.set($config.name, 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('before-mounted', () => {\n addInstance(this);\n });\n this.$on('after-destroyed', () => {\n deleteInstance(this);\n });\n\n if (isDev) {\n this.__debug('constructor', this);\n }\n }\n\n /**\n * Trigger the `mounted` callback.\n * @link https://js-toolkit.studiometa.dev/api/instance-methods.html#mount\n */\n async $mount(): Promise<this> {\n if (this.$isMounted || this.__isMounting) {\n return this;\n }\n\n this.__isMounting = true;\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 ]);\n\n await addToQueue(() => {\n this.$isMounted = true;\n this.__callMethod('mounted');\n });\n\n this.__isMounting = false;\n this.$emit('after-mounted');\n\n return this;\n }\n\n /**\n * Update the instance children.\n * @link https://js-toolkit.studiometa.dev/api/instance-methods.html#update\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 ]);\n\n await addToQueue(() => this.__callMethod('updated'));\n\n return this;\n }\n\n /**\n * Trigger the `destroyed` callback.\n * @link https://js-toolkit.studiometa.dev/api/instance-methods.html#destroy\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 this.$emit('before-destroyed');\n this.$isMounted = false;\n\n await Promise.all([\n addToQueue(() => this.__events.unbindRootElement()),\n addToQueue(() => this.__refs.unregisterAll()),\n addToQueue(() => this.__services.disableAll()),\n addToQueue(() => this.__children.destroyAll()),\n ]);\n\n await addToQueue(() => this.__callMethod('destroyed'));\n\n this.$emit('after-destroyed');\n\n return this;\n }\n\n /**\n * Terminate a child instance when it is not needed anymore.\n * @link https://js-toolkit.studiometa.dev/api/instance-methods.html#terminate\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.$config.name, 'terminated')),\n ]);\n }\n\n /**\n * Add an emitted event.\n *\n * @param {string} event The event name.\n * @return {void}\n * @internal\n */\n __addEmits(event: string): void {\n const ctor = this.constructor;\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 * @return {void}\n * @internal\n */\n __removeEmits(event: string): void {\n const ctor = this.constructor;\n const index = ctor.config.emits.indexOf(event);\n ctor.config.emits.splice(index, 1);\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 * @return {() => void}\n * A function to unbind the listener.\n * @link https://js-toolkit.studiometa.dev/api/instance-methods.html#on-event-callback-options\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 * @return {void}\n * @link https://js-toolkit.studiometa.dev/api/instance-methods.html#off-event-callback-options\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 * @return {void}\n * @link https://js-toolkit.studiometa.dev/api/instance-methods.html#emit-event-args\n */\n $emit(event: string | Event, ...args: unknown[]) {\n if (isDev) {\n this.__debug('$emit', event, args);\n }\n\n this.$el.dispatchEvent(\n event instanceof Event ? event : new CustomEvent(event, { detail: args }),\n );\n }\n\n /**\n * Register and mount all instances of the component.\n * @link https://js-toolkit.studiometa.dev/api/static-methods.html#register-nameorselector-string\n */\n static $register<T extends BaseProps = BaseProps, U extends typeof Base<T> = typeof Base<T>>(\n this: U,\n nameOrSelector?: string,\n ): Promise<InstanceType<U>>[] {\n addToRegistry(nameOrSelector ?? this.config.name, this);\n\n return getComponentElements(nameOrSelector ?? this.config.name).map(\n async (el) =>\n getInstanceFromElement(el, this) ?? (new this(el).$mount() as Promise<InstanceType<U>>),\n );\n }\n}\n"],
|
|
5
|
+
"mappings": "AACA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;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,8BAA8B;AACvC,SAAS,mBAAmB,wBAAwB;AACpD,SAAS,MAAM,OAAO,YAAY,eAAe;AAEjD,IAAI,KAAK;AAiDF,MAAM,KAAsC;AAAA;AAAA;AAAA;AAAA,EAUjD,OAAgB,UAAU;AAAA;AAAA;AAAA;AAAA;AAAA,EAM1B,OAAO,SAAqB;AAAA,IAC1B,MAAM;AAAA,IACN,OAAO;AAAA;AAAA,MAEL;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA;AAAA,MAEA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA;AAA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,KAAM,IAAI,KAAK,EAAE,EAAE,OAAO;AAAA,IAC7D;AAAA,EACF;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -11,12 +11,12 @@ export declare class AbstractManager<T extends any = any> {
|
|
|
11
11
|
* Get the base instance root element.
|
|
12
12
|
*/
|
|
13
13
|
get __element(): HTMLElement & {
|
|
14
|
-
__base__?: Map<string, Base |
|
|
14
|
+
__base__?: Map<string, Base | 'terminated'>;
|
|
15
15
|
};
|
|
16
16
|
/**
|
|
17
17
|
* Get the base instance config.
|
|
18
18
|
*/
|
|
19
|
-
get __config(): import("
|
|
19
|
+
get __config(): import("#private/index.js").BaseConfig;
|
|
20
20
|
/**
|
|
21
21
|
* Get the events manager.
|
|
22
22
|
*/
|
|
@@ -160,7 +160,7 @@ class EventsManager extends AbstractManager {
|
|
|
160
160
|
*/
|
|
161
161
|
__childrenHandler = {
|
|
162
162
|
handleEvent: (event) => {
|
|
163
|
-
const children = this.__base
|
|
163
|
+
const children = this.__base.__children.props;
|
|
164
164
|
for (const childName of Object.keys(children)) {
|
|
165
165
|
let index = -1;
|
|
166
166
|
for (const child of children[childName]) {
|
|
@@ -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, 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 * @return {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 * @return {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 * @return {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 * @return {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 element?.[action](event, that.__refsHandler);\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 * @return {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 * @return {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<T extends Event = Event> = {\n event: T;\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 * @return {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 * @return {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 children = this.__base.$children;\n\n for (const childName of Object.keys(children)) {\n let index = -1;\n\n for (const child of children[childName] as Base<BaseProps>[]) {\n index++;\n\n if (\n child.$el === event.currentTarget &&\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\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 * @return {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 * @return {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 * @return {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 * @return {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 * @return {void}\n */\n bindRootElement() {\n manageRootElement(this);\n }\n\n /**\n * Unbind event method from the root element.\n *\n * @return {void}\n */\n unbindRootElement() {\n manageRootElement(this, 'remove');\n }\n}\n"],
|
|
5
|
-
"mappings": "AACA,SAAS,wBAAwB;AACjC,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,QA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QAAQ;AACZ,UAAI,QAAQ,KAAK,OAAO,MAAM,OAAO,CAAC,GAAG;AACvC,gBAAS,KAAK,OAAO,MAAM,OAAO,EAAoB,QAAQ,GAAG;AAAA,MACnE;AAEA,WAAK,OAAO,MAAM,EAAE,gBAAgB,EAAE,OAAO,OAAO,QAAQ,IAAI,CAAC,CAAC;AAAA,IACpE;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,oBAAyC;AAAA,IACvC,aAAa,CAAC,UAAuB;AACnC,YAAM,WAAW,KAAK,OAAO;
|
|
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 * @return {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 * @return {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 * @return {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 * @return {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 element?.[action](event, that.__refsHandler);\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 * @return {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 * @return {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<T extends Event = Event> = {\n event: T;\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 * @return {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 * @return {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 children = this.__base.__children.props;\n\n for (const childName of Object.keys(children)) {\n let index = -1;\n\n for (const child of children[childName] as Base<BaseProps>[]) {\n index++;\n\n if (\n child.$el === event.currentTarget &&\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\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 * @return {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 * @return {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 * @return {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 * @return {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 * @return {void}\n */\n bindRootElement() {\n manageRootElement(this);\n }\n\n /**\n * Unbind event method from the root element.\n *\n * @return {void}\n */\n unbindRootElement() {\n manageRootElement(this, 'remove');\n }\n}\n"],
|
|
5
|
+
"mappings": "AACA,SAAS,wBAAwB;AACjC,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,EAAE,KAAK,IAAI,OAAO,MAAM,KAAK;AACpC,SAAO,SAAS,KAAK;AACvB;AAWA,SAAS,sBAAsB,MAAqB,OAAO,IAAc;AACvE,QAAM,QAAQ,SAAS,MAAM,WAAW,IAAI,CAAC,UAAU;AACvD,QAAM,MAAM,MAAM,SAAS;AAE3B,MAAI,UAAU,KAAK,eAAe,IAAI,GAAG;AAEzC,MAAI,CAAC,S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base/utils.d.ts
CHANGED
|
@@ -34,7 +34,7 @@ export declare function getEventTarget(instance: Base, event: string, config: Ba
|
|
|
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
|
-
export declare function getInstances():
|
|
37
|
+
export declare function getInstances(): ReadonlySet<Base>;
|
|
38
38
|
export declare function getInstances<T extends BaseConstructor = BaseConstructor>(ctor: T): Set<InstanceType<T>>;
|
|
39
39
|
export declare function getElements(): Set<HTMLElement & {
|
|
40
40
|
__base__: Map<string, Base>;
|
package/Base/utils.js
CHANGED
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';\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 the global elements storage.\n * It will hold reference to all elements with at least one component attached to it.\n */\nfunction getElementsStorage(): Set<HTMLElement & { __base__: Map<string, Base>}> {\n return (globalThis.__JS_TOOLKIT_ELEMENTS__ ??= new Set<HTMLElement & { __base__: Map<string, 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():
|
|
5
|
-
"mappings": "AAAA,SAAS,SAAS,WAAW,YAAY,gBAAgB;AAEzD,SAAS,gBAAgB;AACzB,SAAS,mBAAmB;AAC5B,SAAS,8BAA8B;AAEvC,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,SAAQ,WAAW,6BAA6B,oBAAI,IAAU;AAChE;AAMA,SAAS,qBAAwE;AAC/E,SAAQ,WAAW,4BAA4B,oBAAI,IAAkD;AACvG;AAUO,SAAS,aACd,
|
|
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 the global elements storage.\n * It will hold reference to all elements with at least one component attached to it.\n */\nfunction getElementsStorage(): Set<HTMLElement & { __base__: Map<string, Base>}> {\n return (globalThis.__JS_TOOLKIT_ELEMENTS__ ??= new Set<HTMLElement & { __base__: Map<string, 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(): ReadonlySet<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): ReadonlySet<InstanceType<T>> | ReadonlySet<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 }\n\n return new Set(getInstancesStorage());\n}\n\nexport function getElements() {\n return new Set(getElementsStorage());\n}\n\nexport function addInstance(instance: Base) {\n getInstancesStorage().add(instance);\n getElementsStorage().add(instance.$el as HTMLElement & { __base__: Map<string, Base>});\n}\n\nexport function deleteInstance(instance: Base) {\n getInstancesStorage().delete(instance);\n getElementsStorage().delete(instance.$el as HTMLElement & { __base__: Map<string, Base>});\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 // Add children components to the registry\n if (ctor.config?.components) {\n for (const [selector, childConstructor] of Object.entries(ctor.config?.components)) {\n if ('$isBase' in childConstructor && childConstructor.$isBase) {\n addToRegistry(selector, childConstructor);\n }\n }\n }\n\n const mutation = useMutation(document, { childList: true, subtree: true });\n if (!mutation.has(registryKey)) {\n mutation.add(registryKey, mutationCallback);\n }\n}\n\n/**\n * Find the closest instance from the given element in the given set of Base instances.\n */\nexport function findClosestInstance<T extends Base = Base>(element: HTMLElement, instances: Set<T>): T {\n let closest = null;\n let minDepth = Infinity;\n\n for (const instance of instances) {\n let depth = 0;\n let el = element;\n while (el && el !== instance.$el) {\n depth++;\n el = el.parentElement;\n }\n\n if (depth < minDepth) {\n minDepth = depth;\n closest = instance;\n }\n }\n\n return closest;\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,SAAS,WAAW,YAAY,gBAAgB;AAEzD,SAAS,gBAAgB;AACzB,SAAS,mBAAmB;AAC5B,SAAS,8BAA8B;AAEvC,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,SA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F;AAEA,QAAM,WAAW,YAAY,UAAU,EAAE,WAAW,MAAM,SAAS,KAAK,CAAC;AACzE,MAAI,CAAC,SAAS,IAAI,WAAW,GAAG;AAC9B,aAAS,IAAI,aAAa,gBAAgB;AAAA,EAC5C;AACF;AAKO,SAAS,oBAA2C,SAAsB,WAAsB;AACrG,MAAI,UAAU;AACd,MAAI,WAAW;AAEf,aAAW,YAAY,WAAW;AAChC,QAAI,QAAQ;AACZ,QAAI,KAAK;AACT,WAAO,MAAM,OAAO,SAAS,KAAK;AAChC;AACA,WAAK,GAAG;AAAA,IACV;AAEA,QAAI,QAAQ,UAAU;AACpB,iBAAW;AACX,gBAAU;AAAA,IACZ;AAAA,EACF;AAEA,SAAO;AACT;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -13,7 +13,7 @@ function testBreakpoints(breakpoints) {
|
|
|
13
13
|
function mountComponents(instance, breakpoints) {
|
|
14
14
|
return breakpoints.map(([bk, ComponentClass]) => {
|
|
15
15
|
const child = new ComponentClass(instance.$el);
|
|
16
|
-
Object.defineProperty(child, "$parent", { get: () => instance
|
|
16
|
+
Object.defineProperty(child, "$parent", { get: () => instance.__parent });
|
|
17
17
|
return [bk.split(" "), child];
|
|
18
18
|
});
|
|
19
19
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../packages/js-toolkit/decorators/withBreakpointManager.ts"],
|
|
4
|
-
"sourcesContent": ["import type { BaseDecorator, BaseInterface } from '../Base/types.js';\nimport type { Base, BaseConstructor, BaseProps } from '../Base/index.js';\nimport { useResize } from '../services/index.js';\nimport { isDev, isArray } from '../utils/index.js';\n\n/**\n * Test the breakpoins of the given Base instance and return the hook to call.\n */\nfunction testBreakpoints(breakpoints: Array<[string[], Base]>) {\n const { breakpoint } = useResize().props();\n for (const [breakpointKeys, instance] of breakpoints) {\n if (breakpointKeys.includes(breakpoint) && !instance.$isMounted) {\n setTimeout(() => instance.$mount(), 0);\n } else if (!breakpointKeys.includes(breakpoint) && instance.$isMounted) {\n instance.$destroy();\n }\n }\n}\n\n/**\n * Prepare the components.\n */\nfunction mountComponents(\n instance: Base,\n breakpoints: Array<[string, BaseConstructor]>,\n): Array<[string[], Base]> {\n return breakpoints.map(([bk, ComponentClass]) => {\n const child = new ComponentClass(instance.$el);\n Object.defineProperty(child, '$parent', { get: () => instance
|
|
5
|
-
"mappings": "AAEA,SAAS,iBAAiB;AAC1B,SAAS,OAAO,eAAe;AAK/B,SAAS,gBAAgB,aAAsC;AAC7D,QAAM,EAAE,WAAW,IAAI,UAAU,EAAE,MAAM;AACzC,aAAW,CAAC,gBAAgB,QAAQ,KAAK,aAAa;AACpD,QAAI,eAAe,SAAS,UAAU,KAAK,CAAC,SAAS,YAAY;AAC/D,iBAAW,MAAM,SAAS,OAAO,GAAG,CAAC;AAAA,IACvC,WAAW,CAAC,eAAe,SAAS,UAAU,KAAK,SAAS,YAAY;AACtE,eAAS,SAAS;AAAA,IACpB;AAAA,EACF;AACF;AAKA,SAAS,gBACP,UACA,aACyB;AACzB,SAAO,YAAY,IAAI,CAAC,CAAC,IAAI,cAAc,MAAM;AAC/C,UAAM,QAAQ,IAAI,eAAe,SAAS,GAAG;AAC7C,WAAO,eAAe,OAAO,WAAW,EAAE,KAAK,MAAM,SAAS,
|
|
4
|
+
"sourcesContent": ["import type { BaseDecorator, BaseInterface } from '../Base/types.js';\nimport type { Base, BaseConstructor, BaseProps } from '../Base/index.js';\nimport { useResize } from '../services/index.js';\nimport { isDev, isArray } from '../utils/index.js';\n\n/**\n * Test the breakpoins of the given Base instance and return the hook to call.\n */\nfunction testBreakpoints(breakpoints: Array<[string[], Base]>) {\n const { breakpoint } = useResize().props();\n for (const [breakpointKeys, instance] of breakpoints) {\n if (breakpointKeys.includes(breakpoint) && !instance.$isMounted) {\n setTimeout(() => instance.$mount(), 0);\n } else if (!breakpointKeys.includes(breakpoint) && instance.$isMounted) {\n instance.$destroy();\n }\n }\n}\n\n/**\n * Prepare the components.\n */\nfunction mountComponents(\n instance: Base,\n breakpoints: Array<[string, BaseConstructor]>,\n): Array<[string[], Base]> {\n return breakpoints.map(([bk, ComponentClass]) => {\n const child = new ComponentClass(instance.$el);\n Object.defineProperty(child, '$parent', { get: () => instance.__parent });\n return [bk.split(' '), child];\n });\n}\n\n/**\n * A cache object to hold each Base sub-instances.\n */\nconst instances: WeakMap<Base, Array<[string[], Base]>> = new WeakMap();\n\n/**\n * BreakpointManager class.\n * @link https://js-toolkit.studiometa.dev/api/decorators/withBreakpointManager.html\n*/\nexport function withBreakpointManager<S extends Base>(\n BaseClass: typeof Base,\n breakpoints: Array<[string, BaseConstructor<Base>]>,\n): BaseDecorator<BaseInterface, S> {\n if (!isArray(breakpoints)) {\n if (isDev) {\n throw new Error('[withBreakpointManager] The `breakpoints` parameter must be an array.');\n }\n\n // @ts-ignore\n return BaseClass;\n }\n\n if (breakpoints.length < 2) {\n if (isDev) {\n throw new Error('[withBreakpointManager] You must define at least 2 breakpoints.');\n }\n\n // @ts-ignore\n return BaseClass;\n }\n\n const { add, props } = useResize();\n\n // Do nothing if no breakpoint has been defined.\n // @link https://js-toolkit.studiometa.dev/api/services/useResize.html#breakpoint\n if (!props().breakpoint) {\n if (isDev) {\n throw new Error('The `BreakpointManager` class requires breakpoints to be defined.');\n }\n\n // @ts-ignore\n return BaseClass;\n }\n\n /**\n * Class.\n */\n class WithBreakpointManager<T extends BaseProps = BaseProps> extends BaseClass<T> {\n /**\n * Watch for the document resize to test the breakpoints.\n */\n constructor(element: HTMLElement) {\n super(element);\n\n if (!instances.has(this)) {\n instances.set(this, mountComponents(this, breakpoints));\n }\n\n add(`BreakpointManager-${this.$id}`, () => {\n testBreakpoints(instances.get(this));\n });\n }\n\n /**\n * Override the default $mount method to prevent component's from being\n * mounted when they should not.\n */\n async $mount() {\n await super.$mount();\n\n testBreakpoints(instances.get(this));\n\n return this;\n }\n\n /**\n * Destroy all instances when the main one is destroyed.\n */\n async $destroy() {\n const promises = [];\n if (isArray(instances.get(this))) {\n for (const [, instance] of instances.get(this)) {\n promises.push(instance.$destroy());\n }\n }\n\n await Promise.all(promises);\n\n return super.$destroy();\n }\n }\n\n // @ts-ignore\n return WithBreakpointManager;\n}\n"],
|
|
5
|
+
"mappings": "AAEA,SAAS,iBAAiB;AAC1B,SAAS,OAAO,eAAe;AAK/B,SAAS,gBAAgB,aAAsC;AAC7D,QAAM,EAAE,WAAW,IAAI,UAAU,EAAE,MAAM;AACzC,aAAW,CAAC,gBAAgB,QAAQ,KAAK,aAAa;AACpD,QAAI,eAAe,SAAS,UAAU,KAAK,CAAC,SAAS,YAAY;AAC/D,iBAAW,MAAM,SAAS,OAAO,GAAG,CAAC;AAAA,IACvC,WAAW,CAAC,eAAe,SAAS,UAAU,KAAK,SAAS,YAAY;AACtE,eAAS,SAAS;AAAA,IACpB;AAAA,EACF;AACF;AAKA,SAAS,gBACP,UACA,aACyB;AACzB,SAAO,YAAY,IAAI,CAAC,CAAC,IAAI,cAAc,MAAM;AAC/C,UAAM,QAAQ,IAAI,eAAe,SAAS,GAAG;AAC7C,WAAO,eAAe,OAAO,WAAW,EAAE,KAAK,MAAM,SAAS,SAAS,CAAC;AACxE,WAAO,CAAC,GAAG,MAAM,GAAG,GAAG,KAAK;AAAA,EAC9B,CAAC;AACH;AAKA,MAAM,YAAoD,oBAAI,QAAQ;AAM/D,SAAS,sBACd,WACA,aACiC;AACjC,MAAI,CAAC,QAAQ,WAAW,GAAG;AACzB,QAAI,OAAO;AACT,YAAM,IAAI,MAAM,uEAAuE;AAAA,IACzF;AAGA,WAAO;AAAA,EACT;AAEA,MAAI,YAAY,SAAS,GAAG;AAC1B,QAAI,OAAO;AACT,YAAM,IAAI,MAAM,iEAAiE;AAAA,IACnF;AAGA,WAAO;AAAA,EACT;AAEA,QAAM,EAAE,KAAK,MAAM,IAAI,UAAU;AAIjC,MAAI,CAAC,MAAM,EAAE,YAAY;AACvB,QAAI,OAAO;AACT,YAAM,IAAI,MAAM,mEAAmE;AAAA,IACrF;AAGA,WAAO;AAAA,EACT;AAAA,EAKA,MAAM,8BAA+D,UAAa;AAAA;AAAA;AAAA;AAAA,IAIhF,YAAY,SAAsB;AAChC,YAAM,OAAO;AAEb,UAAI,CAAC,UAAU,IAAI,IAAI,GAAG;AACxB,kBAAU,IAAI,MAAM,gBAAgB,MAAM,WAAW,CAAC;AAAA,MACxD;AAEA,UAAI,qBAAqB,KAAK,GAAG,IAAI,MAAM;AACzC,wBAAgB,UAAU,IAAI,IAAI,CAAC;AAAA,MACrC,CAAC;AAAA,IACH;AAAA;AAAA;AAAA;AAAA;AAAA,IAMA,MAAM,SAAS;AACb,YAAM,MAAM,OAAO;AAEnB,sBAAgB,UAAU,IAAI,IAAI,CAAC;AAEnC,aAAO;AAAA,IACT;AAAA;AAAA;AAAA;AAAA,IAKA,MAAM,WAAW;AACf,YAAM,WAAW,CAAC;AAClB,UAAI,QAAQ,UAAU,IAAI,IAAI,CAAC,GAAG;AAChC,mBAAW,CAAC,EAAE,QAAQ,KAAK,UAAU,IAAI,IAAI,GAAG;AAC9C,mBAAS,KAAK,SAAS,SAAS,CAAC;AAAA,QACnC;AAAA,MACF;AAEA,YAAM,QAAQ,IAAI,QAAQ;AAE1B,aAAO,MAAM,SAAS;AAAA,IACxB;AAAA,EACF;AAGA,SAAO;AACT;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/helpers/createApp.js
CHANGED
|
@@ -1,29 +1,20 @@
|
|
|
1
1
|
import { features } from "../Base/features.js";
|
|
2
|
-
import {
|
|
2
|
+
import { defineFeatures } from "./defineFeatures.js";
|
|
3
|
+
import { isDev } from "../utils/index.js";
|
|
4
|
+
import { logTree } from "./logTree.js";
|
|
3
5
|
function createApp(App, options = {}) {
|
|
4
6
|
let app;
|
|
5
7
|
const {
|
|
6
8
|
root = document.body,
|
|
7
|
-
|
|
8
|
-
blocking = null,
|
|
9
|
-
prefix = null,
|
|
10
|
-
attributes = null
|
|
9
|
+
...featureOptions
|
|
11
10
|
} = options instanceof HTMLElement ? { root: options } : options;
|
|
12
|
-
|
|
13
|
-
features.set("breakpoints", breakpoints);
|
|
14
|
-
}
|
|
15
|
-
if (isBoolean(blocking)) {
|
|
16
|
-
features.set("blocking", blocking);
|
|
17
|
-
}
|
|
18
|
-
if (isString(prefix)) {
|
|
19
|
-
features.set("prefix", prefix);
|
|
20
|
-
}
|
|
21
|
-
if (isObject(attributes)) {
|
|
22
|
-
features.set("attributes", attributes);
|
|
23
|
-
}
|
|
11
|
+
defineFeatures(featureOptions);
|
|
24
12
|
async function init() {
|
|
25
13
|
app = new App(root);
|
|
26
14
|
await app.$mount();
|
|
15
|
+
if (isDev) {
|
|
16
|
+
globalThis.$logTree = () => logTree(app);
|
|
17
|
+
}
|
|
27
18
|
return app;
|
|
28
19
|
}
|
|
29
20
|
let p;
|
package/helpers/createApp.js.map
CHANGED
|
@@ -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 { features } from '../Base/features.js';\nimport {
|
|
5
|
-
"mappings": "AAEA,SAAS,gBAAgB;AACzB,SAAS,
|
|
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 { defineFeatures } from './defineFeatures.js';\nimport { isDev } from '../utils/index.js';\nimport { logTree } from './logTree.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 ...featureOptions\n } = options instanceof HTMLElement ? { root: options } : options;\n\n defineFeatures(featureOptions);\n\n async function init() {\n app = new App(root) as S & Base<T>;\n await app.$mount();\n if (isDev) {\n globalThis.$logTree = () => logTree(app);\n }\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,sBAAsB;AAC/B,SAAS,aAAa;AACtB,SAAS,eAAe;AAWjB,SAAS,UACd,KACA,UAA0C,CAAC,GACf;AAC5B,MAAI;AACJ,QAAM;AAAA,IACJ,OAAO,SAAS;AAAA,IAChB,GAAG;AAAA,EACL,IAAI,mBAAmB,cAAc,EAAE,MAAM,QAAQ,IAAI;AAEzD,iBAAe,cAAc;AAE7B,iBAAe,OAAO;AACpB,UAAM,IAAI,IAAI,IAAI;AAClB,UAAM,IAAI,OAAO;AACjB,QAAI,OAAO;AACT,iBAAW,WAAW,MAAM,QAAQ,GAAG;AAAA,IACzC;AACA,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
|
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { Features } from '../Base/features.js';
|
|
2
|
+
/**
|
|
3
|
+
* Configure global features outside of `createApp`.
|
|
4
|
+
* Useful when using `registerComponent` instead of `createApp`.
|
|
5
|
+
* @link https://js-toolkit.studiometa.dev/api/helpers/defineFeatures.html
|
|
6
|
+
*/
|
|
7
|
+
export declare function defineFeatures(options: Partial<Features>): void;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { features } from "../Base/features.js";
|
|
2
|
+
import { isBoolean, isObject, isString } from "../utils/index.js";
|
|
3
|
+
function defineFeatures(options) {
|
|
4
|
+
const { breakpoints, blocking, prefix, attributes } = options;
|
|
5
|
+
if (isObject(breakpoints)) {
|
|
6
|
+
features.set("breakpoints", breakpoints);
|
|
7
|
+
}
|
|
8
|
+
if (isBoolean(blocking)) {
|
|
9
|
+
features.set("blocking", blocking);
|
|
10
|
+
}
|
|
11
|
+
if (isString(prefix)) {
|
|
12
|
+
features.set("prefix", prefix);
|
|
13
|
+
}
|
|
14
|
+
if (isObject(attributes)) {
|
|
15
|
+
features.set("attributes", attributes);
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
export {
|
|
19
|
+
defineFeatures
|
|
20
|
+
};
|
|
21
|
+
//# sourceMappingURL=defineFeatures.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../packages/js-toolkit/helpers/defineFeatures.ts"],
|
|
4
|
+
"sourcesContent": ["import type { Features } from '../Base/features.js';\nimport { features } from '../Base/features.js';\nimport { isBoolean, isObject, isString } from '../utils/index.js';\n\n/**\n * Configure global features outside of `createApp`.\n * Useful when using `registerComponent` instead of `createApp`.\n * @link https://js-toolkit.studiometa.dev/api/helpers/defineFeatures.html\n */\nexport function defineFeatures(options: Partial<Features>): void {\n const { breakpoints, blocking, prefix, attributes } = 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"],
|
|
5
|
+
"mappings": "AACA,SAAS,gBAAgB;AACzB,SAAS,WAAW,UAAU,gBAAgB;AAOvC,SAAS,eAAe,SAAkC;AAC/D,QAAM,EAAE,aAAa,UAAU,QAAQ,WAAW,IAAI;AAEtD,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;AACF;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|