@twobirds/microcomponents 0.10.1 → 0.10.2
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/dist/MC.min.js +1 -1
- package/dist/autoload.min.js +1 -1
- package/dist/cli/index.js +18 -22
- package/dist/cli/inliner.d.ts +8 -5
- package/dist/cli/inliner.d.ts.map +1 -1
- package/dist/core/MC.d.ts +98 -50
- package/dist/core/MC.d.ts.map +1 -1
- package/dist/core/elements.js +134 -76
- package/dist/core/index.d.ts +5 -4
- package/dist/core/index.d.ts.map +1 -1
- package/dist/docs/api-external.d.ts +101 -0
- package/dist/docs/api-external.d.ts.map +1 -0
- package/dist/docs/cli.d.ts +115 -0
- package/dist/docs/cli.d.ts.map +1 -0
- package/dist/docs/concepts.d.ts +42 -0
- package/dist/docs/concepts.d.ts.map +1 -0
- package/dist/docs/installation.d.ts +74 -0
- package/dist/docs/installation.d.ts.map +1 -0
- package/dist/docs/mcp.d.ts +45 -0
- package/dist/docs/mcp.d.ts.map +1 -0
- package/dist/elements.min.js +1 -1
- package/dist/formValues.min.js +1 -1
- package/dist/mcp/api.json +325 -29
- package/dist/mcp/concepts/event-system.md +1 -1
- package/dist/mcp/index.js +13 -6
- package/dist/microcomponents.js +145 -82
- package/dist/microcomponents.min.js +1 -1
- package/dist/observables.min.js +1 -1
- package/dist/state/formValues.d.ts +3 -3
- package/dist/state/formValues.js +139 -81
- package/dist/state/index.d.ts +3 -0
- package/dist/state/index.d.ts.map +1 -1
- package/dist/state/observables.d.ts +2 -2
- package/dist/state/observables.js +136 -78
- package/dist/types/index.d.ts +1 -0
- package/dist/types/index.d.ts.map +1 -1
- package/dist/utils/helpers.d.ts +12 -0
- package/dist/utils/helpers.d.ts.map +1 -1
- package/package.json +3 -2
|
@@ -7,7 +7,7 @@ Handler conventions (auto-attached):
|
|
|
7
7
|
|
|
8
8
|
Lifecycle events when registered via defineCE:
|
|
9
9
|
|
|
10
|
-
- oneInit() - constructor finished;
|
|
10
|
+
- oneInit() - constructor finished and declared assets loaded; read them via `this.assets`
|
|
11
11
|
- onConnected() - element inserted into DOM
|
|
12
12
|
- onDisconnected() - element removed from DOM
|
|
13
13
|
- onAdopted() - element moved to new document
|
package/dist/mcp/index.js
CHANGED
|
@@ -44,8 +44,11 @@ above the first overload supplies the prose.
|
|
|
44
44
|
@example Keep it fresh: pnpm run mcp:dev restarts the server process on change
|
|
45
45
|
*/
|
|
46
46
|
var mcp_docs_generate_exports = /* @__PURE__ */ __exportAll({
|
|
47
|
+
extract: () => extract,
|
|
47
48
|
index: () => index$1,
|
|
48
|
-
|
|
49
|
+
scanFile: () => scanFile,
|
|
50
|
+
undocumented: () => undocumented$1,
|
|
51
|
+
walk: () => walk
|
|
49
52
|
});
|
|
50
53
|
/** Read a barrel file, returning each re-exported name with its group and hidden flag. */
|
|
51
54
|
function readBarrel(file) {
|
|
@@ -53,10 +56,14 @@ function readBarrel(file) {
|
|
|
53
56
|
for (let i = 0; i < lines.length; i++) {
|
|
54
57
|
if (!/^\s*export\s+(type\s+)?\{/.test(lines[i])) continue;
|
|
55
58
|
let k = i;
|
|
56
|
-
while (k
|
|
59
|
+
while (k < lines.length) {
|
|
60
|
+
const stmt = lines[k].trim();
|
|
61
|
+
if (k > i) {
|
|
62
|
+
lines[i] += " " + stmt;
|
|
63
|
+
lines[k] = "";
|
|
64
|
+
}
|
|
65
|
+
if (/}\s*from/.test(stmt)) break;
|
|
57
66
|
k++;
|
|
58
|
-
lines[i] += " " + lines[k].trim();
|
|
59
|
-
lines[k] = "";
|
|
60
67
|
}
|
|
61
68
|
i = k;
|
|
62
69
|
}
|
|
@@ -64,7 +71,7 @@ function readBarrel(file) {
|
|
|
64
71
|
let pending = "";
|
|
65
72
|
for (let i = 0; i < lines.length; i++) {
|
|
66
73
|
const line = lines[i].trim();
|
|
67
|
-
if (line.startsWith("/**")
|
|
74
|
+
if (line.startsWith("/**")) {
|
|
68
75
|
let k = i;
|
|
69
76
|
while (k < lines.length && !lines[k].includes("*/")) k++;
|
|
70
77
|
pending = lines.slice(i, k + 1).join("\n");
|
|
@@ -147,7 +154,7 @@ function extract(block) {
|
|
|
147
154
|
if (raw.length) raw[0] = raw[0].replace(/^\/\*\*/, "");
|
|
148
155
|
if (raw.length > 1) raw[raw.length - 1] = raw[raw.length - 1].replace(/\*\/$/, "");
|
|
149
156
|
const markerCol = (/^[\t ]*/.exec(raw[1])?.[0] ?? "").length;
|
|
150
|
-
const lines = raw.map((l) => l.replace(
|
|
157
|
+
const lines = raw.map((l) => l.replace(/^[\t ]*\*\s?/, "")).map((l) => l.replace(/\{\@link(?:code|linkplain)?\s+([^\s}]+)[^}]*\}/g, "$1"));
|
|
151
158
|
const isContinuation = (index) => {
|
|
152
159
|
return (/^[\t ]*/.exec(raw[index])?.[0] ?? "").length > markerCol;
|
|
153
160
|
};
|
package/dist/microcomponents.js
CHANGED
|
@@ -497,6 +497,20 @@ function kebabToPascal(str) {
|
|
|
497
497
|
return str.split("-").map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join("");
|
|
498
498
|
}
|
|
499
499
|
/**
|
|
500
|
+
* Converts a PascalCase string to kebab-case.
|
|
501
|
+
* Example: 'MyComponentName' -> 'my-component-name'
|
|
502
|
+
* @param str - The PascalCase string to convert.
|
|
503
|
+
* @returns The converted kebab-case string.
|
|
504
|
+
*
|
|
505
|
+
* @example
|
|
506
|
+
* ```ts
|
|
507
|
+
* console.log(pascalToKebab('MyElement'));
|
|
508
|
+
* ```
|
|
509
|
+
*/
|
|
510
|
+
function pascalToKebab(str) {
|
|
511
|
+
return str.replace(/[A-Z]/g, (m, i) => (i ? "-" : "") + m.toLowerCase());
|
|
512
|
+
}
|
|
513
|
+
/**
|
|
500
514
|
* Creates a debounced version of a function that delays execution until after the specified
|
|
501
515
|
* number of milliseconds have elapsed since the last time this function was invoked.
|
|
502
516
|
* Useful for rate-limiting expensive operations like event handlers or API calls.
|
|
@@ -783,13 +797,15 @@ function remove(target, key) {
|
|
|
783
797
|
if (!Object.keys(_mc).length && target instanceof HTMLElement && target.hasAttribute("data-mc")) target.removeAttribute("data-mc");
|
|
784
798
|
}
|
|
785
799
|
/**
|
|
786
|
-
Runs the "Init" lifecycle event on a DOM microcomponent instance
|
|
800
|
+
Runs the "Init" lifecycle event on a DOM microcomponent instance.
|
|
787
801
|
|
|
788
802
|
This function schedules the `trigger('Init')` call in a microtask, ensuring
|
|
789
803
|
that all synchronous initialization is complete before the lifecycle hook
|
|
790
|
-
executes.
|
|
791
|
-
|
|
792
|
-
|
|
804
|
+
executes. The {@link DC} constructor calls it once the declared assets are in
|
|
805
|
+
place — synchronously in a bundled build, after the fetch resolves in a
|
|
806
|
+
dev/autoload build — so `oneInit()` always sees the loaded assets. Only `DC`
|
|
807
|
+
instances have an Init lifecycle — the `DC` constructor calls this exclusively,
|
|
808
|
+
so the signature encodes that invariant instead of re-checking it at runtime.
|
|
793
809
|
|
|
794
810
|
@param element - The DOM microcomponent instance on which to trigger the Init event.
|
|
795
811
|
*/
|
|
@@ -857,16 +873,18 @@ function findMcAncestor(from, key) {
|
|
|
857
873
|
The base class for all microcomponents — shared root of both {@link MC} and {@link DC}.
|
|
858
874
|
|
|
859
875
|
Holds a `WeakRef` to the target (a DOM element for `DC`, or any plain object for `MC`)
|
|
860
|
-
to avoid circular references.
|
|
861
|
-
|
|
876
|
+
to avoid circular references. It starts loading any `static assets` for `MC` and `DC`
|
|
877
|
+
alike (shared per class through `_assetsPromise`), read through the {@link McBase.assets}
|
|
878
|
+
getter. For `DC` subclasses it bootstraps one automatic behaviour:
|
|
862
879
|
|
|
863
880
|
1. **Event listener auto-attachment** — methods whose names start with `on` or `one`
|
|
864
881
|
(e.g. `onClick`, `oneInit`) are wired to the target element via {@link on} / {@link one}.
|
|
865
|
-
2. **"Init" lifecycle event** — dispatched asynchronously in a microtask so that all
|
|
866
|
-
synchronous constructor work finishes first.
|
|
867
882
|
|
|
868
|
-
|
|
869
|
-
|
|
883
|
+
The **"Init" lifecycle event** and the DOM attach of auto-attached assets are dispatched
|
|
884
|
+
by the {@link DC} constructor — after the declared assets are in place — so that
|
|
885
|
+
`oneInit()` runs once the instance is fully constructed and its assets are loaded. Plain
|
|
886
|
+
`MC` instances fetch their assets server-side with no DOM attach and no `Init` lifecycle,
|
|
887
|
+
keeping server-side usage lightweight.
|
|
870
888
|
|
|
871
889
|
### Plugin extension points
|
|
872
890
|
|
|
@@ -919,20 +937,45 @@ runs once after the constructor.
|
|
|
919
937
|
var McBase = class {
|
|
920
938
|
_target;
|
|
921
939
|
/**
|
|
940
|
+
* Loaded asset cache, keyed by camelCase descriptor (`'targetHtml'` → `.target.html`).
|
|
941
|
+
* Inlined by the bundler in a bundled build, filled by `loadAssets()` in dev/autoload.
|
|
942
|
+
* Read through the {@link McBase.assets} getter.
|
|
943
|
+
*/
|
|
944
|
+
static _assets = {};
|
|
945
|
+
/**
|
|
946
|
+
* Declares companion files for auto-loading by convention (e.g. `['targetHtml', 'json']`).
|
|
947
|
+
* Asset names are camelCase and translated into file extensions: `'targetHtml'` → `.target.html`.
|
|
948
|
+
*/
|
|
949
|
+
static assets = [];
|
|
950
|
+
/**
|
|
951
|
+
* In-flight asset request, cached per class so that instances constructed while
|
|
952
|
+
* the first fetch is still pending (e.g. in a loop) share a single request
|
|
953
|
+
* instead of each triggering their own. Resolves to the freshly loaded assets.
|
|
954
|
+
*/
|
|
955
|
+
static _assetsPromise;
|
|
956
|
+
/**
|
|
922
957
|
The constructor for the base `McBase` class.
|
|
923
958
|
|
|
924
|
-
Initializes a weak reference to the target
|
|
925
|
-
|
|
959
|
+
Initializes a weak reference to the target, auto-attaches listeners for `DC`
|
|
960
|
+
subclasses, and starts loading any `static assets` for `MC` and `DC` alike —
|
|
961
|
+
a server-side `MC` fetches them with no DOM, a `DC` gets them attached by its
|
|
962
|
+
own constructor. The load is shared per class through `_assetsPromise`.
|
|
926
963
|
|
|
927
964
|
@param target - The object or element this microcomponent represents.
|
|
928
965
|
*/
|
|
929
966
|
constructor(target) {
|
|
930
967
|
this._target = new WeakRef(target || {});
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
968
|
+
const ctor = this.constructor;
|
|
969
|
+
if (this instanceof DC && this.constructor !== DC) autoAttachListeners(this);
|
|
970
|
+
const remaining = (ctor.assets ?? []).filter((key) => !ctor._assets[key]);
|
|
971
|
+
if (remaining.length && !ctor._assetsPromise) ctor._assetsPromise = loadAssets(ctor._originalTag || (this instanceof DC ? this.target.tagName.toLowerCase() : pascalToKebab(ctor.name)), remaining).then((res) => {
|
|
972
|
+
const loadedAssets = {};
|
|
973
|
+
remaining.forEach((key, i) => {
|
|
974
|
+
loadedAssets[key] = res[i];
|
|
975
|
+
});
|
|
976
|
+
ctor._assets = Object.assign({}, ctor._assets, loadedAssets);
|
|
977
|
+
return loadedAssets;
|
|
978
|
+
});
|
|
936
979
|
}
|
|
937
980
|
/**
|
|
938
981
|
Returns the current target object (DOM node or other data) referenced by this microcomponent.
|
|
@@ -950,6 +993,21 @@ var McBase = class {
|
|
|
950
993
|
get target() {
|
|
951
994
|
return this._target.deref();
|
|
952
995
|
}
|
|
996
|
+
/**
|
|
997
|
+
The loaded assets for this component instance.
|
|
998
|
+
|
|
999
|
+
`static assets` are loaded before `oneInit()` fires on a `DC`, so this getter is
|
|
1000
|
+
ready inside the `oneInit()` callback. A server-side `MC` fills it from `loadAssets()`;
|
|
1001
|
+
await `MC._assetsPromise` before reading it. It returns the merged asset record keyed
|
|
1002
|
+
by descriptor: `css` / `targetCss` / `shadowCss` / `shadowHtml` / `targetHtml` arrive
|
|
1003
|
+
as strings, `*Json` entries arrive parsed, and a plain `html` template is returned as a
|
|
1004
|
+
string for `parse()`. An empty object when no assets are declared.
|
|
1005
|
+
|
|
1006
|
+
@returns A record mapping asset keys to their content.
|
|
1007
|
+
*/
|
|
1008
|
+
get assets() {
|
|
1009
|
+
return this.constructor._assets || {};
|
|
1010
|
+
}
|
|
953
1011
|
};
|
|
954
1012
|
/**
|
|
955
1013
|
A general-purpose base microcomponent that does not require a DOM target.
|
|
@@ -957,6 +1015,11 @@ A general-purpose base microcomponent that does not require a DOM target.
|
|
|
957
1015
|
Inherits from `McBase`, but is primarily used as a lightweight container or
|
|
958
1016
|
for logic not directly tied to DOM elements.
|
|
959
1017
|
|
|
1018
|
+
`static assets` work here too: a server-side `MC` fetches its companion files
|
|
1019
|
+
(`.json`, `.html`, `.css`) with `loadAssets()` and reads them through the
|
|
1020
|
+
{@link McBase.assets} getter — await `MC._assetsPromise` before reading. There is
|
|
1021
|
+
no DOM attach and no `Init` lifecycle; those are `DC`-only.
|
|
1022
|
+
|
|
960
1023
|
@template TTarget - The concrete type of the wrapped target data; preserved by
|
|
961
1024
|
the `target` getter, so `new MC({ some: 'data' }).target.some` stays typed.
|
|
962
1025
|
@group Micro Components
|
|
@@ -1027,14 +1090,26 @@ and translated into file extensions: `'targetHtml'` → `.target.html`, `'json'`
|
|
|
1027
1090
|
The path is derived from the custom element tag segments, and the basename is the
|
|
1028
1091
|
last segment. For `<cart-container-checkout>`, assets load from `/cart/container/checkout.*`.
|
|
1029
1092
|
|
|
1030
|
-
|
|
1031
|
-
|
|
1093
|
+
**Assets are loaded before `oneInit()` fires.** The constructor applies them to the
|
|
1094
|
+
target, then dispatches the `Init` lifecycle event — synchronously in a bundled build
|
|
1095
|
+
(assets inlined), after the fetch resolves in a dev/autoload build. Inside `oneInit()`
|
|
1096
|
+
the loaded assets are read through the {@link DC.assets} getter. Everything ending in
|
|
1097
|
+
`Json` arrives parsed; all other files arrive as text.
|
|
1098
|
+
|
|
1099
|
+
**Auto-attached assets**: `.css`, `.target.css`, `.shadow.css`, `.target.html` and
|
|
1100
|
+
`.shadow.html` are attached automatically by `processAssets()` — CSS is injected into
|
|
1101
|
+
the document or shadow scope, HTML is set as `target.innerHTML` / `shadowRoot.innerHTML`,
|
|
1102
|
+
and native event handlers in the template (`<button click="this|go">`) are wired.
|
|
1103
|
+
|
|
1104
|
+
**Plain `.html` is NOT auto-attached.** It is a template held in {@link DC.assets} for
|
|
1105
|
+
components created programmatically with a `data` parameter: in `oneInit()` you compile
|
|
1106
|
+
the target markup from template + data with `parse()`.
|
|
1032
1107
|
|
|
1033
1108
|
**One-time global styles**: Assets named `'css'` and `'targetCss'` inject CSS into the
|
|
1034
1109
|
global document scope via `injectCSS(document, ...)`. Because these are idempotent
|
|
1035
1110
|
global side effects, they are processed only once — after the first instance loads them,
|
|
1036
|
-
the entries are
|
|
1037
|
-
|
|
1111
|
+
the entries are dropped from `static _assets`. Subsequent instances skip re-processing
|
|
1112
|
+
them entirely.
|
|
1038
1113
|
|
|
1039
1114
|
**CSS file roles**:
|
|
1040
1115
|
|
|
@@ -1045,7 +1120,9 @@ scope once, like `targetCss`.
|
|
|
1045
1120
|
component's own shadow root, so each instance gets its own copy.
|
|
1046
1121
|
|
|
1047
1122
|
Every declared asset — CSS, HTML, JSON — is inlined into `static _assets` at build time by
|
|
1048
|
-
the
|
|
1123
|
+
the bundler, which replaces the `static assets` declaration with `static _assets` (the
|
|
1124
|
+
`static assets` line is deleted from the bundled `.js`) and collapses each inlined
|
|
1125
|
+
`.[shadow/target].css` / `.html` to a single line, so a bundled build performs no fetches.
|
|
1049
1126
|
|
|
1050
1127
|
In a bundled build the plain `.css` files are additionally concatenated into a single
|
|
1051
1128
|
`bundle.css` by the bundling script. That file is a convenience listing of the available
|
|
@@ -1057,14 +1134,14 @@ The runtime decides whether an asset still needs fetching with `!ctor._assets[ke
|
|
|
1057
1134
|
inlined entry must never be an empty string: that would trigger a re-fetch of a file that
|
|
1058
1135
|
does not exist in a bundled build.
|
|
1059
1136
|
|
|
1060
|
-
@example static assets
|
|
1137
|
+
@example static assets read in oneInit
|
|
1061
1138
|
|
|
1062
1139
|
```ts
|
|
1063
1140
|
class CartCheckout extends DC {
|
|
1064
1141
|
static assets = ['targetHtml', 'targetCss', 'configJson'];
|
|
1065
1142
|
|
|
1066
|
-
|
|
1067
|
-
const { configJson } =
|
|
1143
|
+
oneInit() {
|
|
1144
|
+
const { configJson } = this.assets;
|
|
1068
1145
|
console.log(configJson);
|
|
1069
1146
|
}
|
|
1070
1147
|
}
|
|
@@ -1073,6 +1150,26 @@ defineCE('cart-checkout', CartCheckout);
|
|
|
1073
1150
|
|
|
1074
1151
|
`configJson` arrives already parsed into an object.
|
|
1075
1152
|
|
|
1153
|
+
@example plain .html template compiled with data
|
|
1154
|
+
|
|
1155
|
+
```ts
|
|
1156
|
+
class UserCard extends DC {
|
|
1157
|
+
static assets = ['html', 'targetCss'];
|
|
1158
|
+
|
|
1159
|
+
constructor(target: HTMLElement, data: { name: string }) {
|
|
1160
|
+
super(target);
|
|
1161
|
+
this.data = data;
|
|
1162
|
+
}
|
|
1163
|
+
|
|
1164
|
+
oneInit() {
|
|
1165
|
+
this.target.innerHTML = parse(this.assets.html, this.data);
|
|
1166
|
+
}
|
|
1167
|
+
}
|
|
1168
|
+
defineCE('user-card', UserCard);
|
|
1169
|
+
```
|
|
1170
|
+
|
|
1171
|
+
`user-card.html` holds the `{name}` template; `parse()` fills it from `data`.
|
|
1172
|
+
|
|
1076
1173
|
### `static attributes?: object`
|
|
1077
1174
|
|
|
1078
1175
|
Sets HTML attributes on every instance automatically.
|
|
@@ -1126,8 +1223,7 @@ internal events that can be caught with handler methods:
|
|
|
1126
1223
|
| `onDisconnected()` | Element was removed from the DOM (`disconnectedCallback`) |
|
|
1127
1224
|
| `onAdopted()` | Element was moved to a new document (`adoptedCallback`) |
|
|
1128
1225
|
| `onAttributeChanged()` | An observed attribute changed (`attributeChangedCallback`) |
|
|
1129
|
-
| `oneInit()` | Constructor finished;
|
|
1130
|
-
| `oneAssets()` | Constructor finished; all assets loaded and available; ev contains assets object |
|
|
1226
|
+
| `oneInit()` | Constructor finished and declared assets loaded; read them via `this.assets` |
|
|
1131
1227
|
|
|
1132
1228
|
@example Event handlers in action
|
|
1133
1229
|
|
|
@@ -1242,22 +1338,6 @@ var DC = class DC extends McBase {
|
|
|
1242
1338
|
*/
|
|
1243
1339
|
static tag;
|
|
1244
1340
|
/**
|
|
1245
|
-
* Result container for assets (e.g., `['targetHtml', 'json']`).
|
|
1246
|
-
* Asset names (keys) are camelCase and translated into file extensions: `'targetHtml'` → `.target.html`.
|
|
1247
|
-
*/
|
|
1248
|
-
static _assets = {};
|
|
1249
|
-
/**
|
|
1250
|
-
* Declares companion files for auto-loading by convention (e.g., `['targetHtml', 'json']`).
|
|
1251
|
-
* Asset names are camelCase and translated into file extensions: `'targetHtml'` → `.target.html`.
|
|
1252
|
-
*/
|
|
1253
|
-
static assets = [];
|
|
1254
|
-
/**
|
|
1255
|
-
* In-flight asset request, cached per class so that instances constructed while
|
|
1256
|
-
* the first fetch is still pending (e.g. in a loop) share a single request
|
|
1257
|
-
* instead of each triggering their own. Resolves to the freshly loaded assets.
|
|
1258
|
-
*/
|
|
1259
|
-
static _assetsPromise;
|
|
1260
|
-
/**
|
|
1261
1341
|
* Sets HTML attributes on every instance automatically.
|
|
1262
1342
|
* Example: `{ role: 'listitem', 'aria-label': 'nav' }`.
|
|
1263
1343
|
*/
|
|
@@ -1269,8 +1349,10 @@ var DC = class DC extends McBase {
|
|
|
1269
1349
|
* 1. Calls {@link McBase} to establish the target reference and auto-attach listeners.
|
|
1270
1350
|
* 2. If `static tag` is set and differs from the current element, replaces the target
|
|
1271
1351
|
* with a new built-in element (or removes it if `tag === ''`).
|
|
1272
|
-
* 3.
|
|
1273
|
-
* 4.
|
|
1352
|
+
* 3. Applies any `static attributes` to the target element.
|
|
1353
|
+
* 4. Loads `static assets` (inlined in a bundled build, fetched in dev/autoload),
|
|
1354
|
+
* applies the auto-attached ones to the target, then fires the `Init` lifecycle
|
|
1355
|
+
* event — so `oneInit()` runs with the assets loaded and readable via {@link DC.assets}.
|
|
1274
1356
|
*
|
|
1275
1357
|
* @param target - The host DOM element this component operates on.
|
|
1276
1358
|
*/
|
|
@@ -1293,43 +1375,24 @@ var DC = class DC extends McBase {
|
|
|
1293
1375
|
if (ctor.attributes) Object.keys(ctor.attributes).forEach((key) => {
|
|
1294
1376
|
this.target.setAttribute(key, attributes[key]);
|
|
1295
1377
|
});
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
return loadedAssets;
|
|
1309
|
-
});
|
|
1310
|
-
ctor._assetsPromise.then((loadedAssets) => {
|
|
1311
|
-
processAssets(this, loadedAssets);
|
|
1312
|
-
that.trigger("assets", ctor._assets);
|
|
1313
|
-
});
|
|
1314
|
-
} else if ([...Object.keys(ctor._assets)].length) queueMicrotask(() => that.trigger("assets", ctor._assets));
|
|
1378
|
+
if (Object.keys(ctor._assets).length) {
|
|
1379
|
+
processAssets(this, ctor._assets);
|
|
1380
|
+
for (const onceKey of ["css", "targetCss"]) delete ctor._assets[onceKey];
|
|
1381
|
+
ctor.assets = ctor.assets.filter((key) => key !== "css" && key !== "targetCss");
|
|
1382
|
+
}
|
|
1383
|
+
if (ctor._assetsPromise) ctor._assetsPromise.then((loadedAssets) => {
|
|
1384
|
+
processAssets(this, loadedAssets);
|
|
1385
|
+
for (const onceKey of ["css", "targetCss"]) delete ctor._assets[onceKey];
|
|
1386
|
+
ctor.assets = ctor.assets.filter((key) => key !== "css" && key !== "targetCss");
|
|
1387
|
+
init(this);
|
|
1388
|
+
});
|
|
1389
|
+
else init(this);
|
|
1315
1390
|
if (ctor.tag === "") {
|
|
1316
1391
|
this.target.remove();
|
|
1317
1392
|
return;
|
|
1318
1393
|
}
|
|
1319
1394
|
}
|
|
1320
1395
|
/**
|
|
1321
|
-
Returns the loaded assets for this component instance.
|
|
1322
|
-
|
|
1323
|
-
Assets are loaded asynchronously when `static assets` is defined on the class.
|
|
1324
|
-
This method returns the resolved asset map keyed by filename, or `undefined`
|
|
1325
|
-
if assets have not yet been loaded.
|
|
1326
|
-
|
|
1327
|
-
@returns A record mapping asset keys to their content strings, or undefined.
|
|
1328
|
-
*/
|
|
1329
|
-
getAssets() {
|
|
1330
|
-
return this.constructor._assets || {};
|
|
1331
|
-
}
|
|
1332
|
-
/**
|
|
1333
1396
|
Static helper to attach a microcomponent instance to a DOM element.
|
|
1334
1397
|
|
|
1335
1398
|
Wrapper around the `add()` utility function, providing a class-level API
|
|
@@ -2033,7 +2096,7 @@ observePlugin(DC);
|
|
|
2033
2096
|
class Counter extends DC {
|
|
2034
2097
|
data = { clicks: 1 };
|
|
2035
2098
|
|
|
2036
|
-
|
|
2099
|
+
oneInit() {
|
|
2037
2100
|
this
|
|
2038
2101
|
.subscribe('data', (v) => console.log('data →', v))
|
|
2039
2102
|
.bind('data', this.target);
|
|
@@ -2416,7 +2479,7 @@ subsequent calls are no-ops.
|
|
|
2416
2479
|
class Counter extends DC {
|
|
2417
2480
|
data = { clicks: 1 };
|
|
2418
2481
|
|
|
2419
|
-
|
|
2482
|
+
oneInit() {
|
|
2420
2483
|
this
|
|
2421
2484
|
.subscribe('data', (v) => console.log('data →', v))
|
|
2422
2485
|
.bind('data', this.target);
|
|
@@ -2512,7 +2575,7 @@ formValuePlugin(DC);
|
|
|
2512
2575
|
class CheckoutForm extends DC {
|
|
2513
2576
|
static assets = ['targetHtml'];
|
|
2514
2577
|
|
|
2515
|
-
|
|
2578
|
+
oneInit() {
|
|
2516
2579
|
this
|
|
2517
2580
|
.formValues(this.target, 'formData')
|
|
2518
2581
|
.subscribe('formData', (data) => console.log(data))
|
|
@@ -2800,7 +2863,7 @@ import { DC, defineCE, formValues } from '@twobirds/microcomponents';
|
|
|
2800
2863
|
class MyForm extends DC {
|
|
2801
2864
|
static assets = ['targetHtml'];
|
|
2802
2865
|
|
|
2803
|
-
|
|
2866
|
+
oneInit() {
|
|
2804
2867
|
formValues(this, 'formData', this.target);
|
|
2805
2868
|
this.formData.subscribe((data) => console.log('form changed:', data));
|
|
2806
2869
|
}
|
|
@@ -2845,7 +2908,7 @@ formValuePlugin(DC);
|
|
|
2845
2908
|
class CheckoutForm extends DC {
|
|
2846
2909
|
static assets = ['targetHtml'];
|
|
2847
2910
|
|
|
2848
|
-
|
|
2911
|
+
oneInit() {
|
|
2849
2912
|
this
|
|
2850
2913
|
.formValues(this.target, 'formData')
|
|
2851
2914
|
.subscribe('formData', (data) => console.log(data))
|
|
@@ -2879,4 +2942,4 @@ formValues: function(target, propName) {
|
|
|
2879
2942
|
} });
|
|
2880
2943
|
}
|
|
2881
2944
|
//#endregion
|
|
2882
|
-
export { BubbleController, DC, MC, McBase, autoload, bindTemplateEvents, copyGettersSetters, debounce, deepEqual, defineCE, flattenObject, formValuePlugin, formValues, getCE, getMcEventName, htmlToElements, injectCSS, isAlreadyObserved, isBrowser, isMcHost, isNativeObject, kebabToPascal, listCE, loadAssets, nameSpace, observe, observePlugin, off, on, one, parse, processAssets, sortObject, trigger, trueEventName };
|
|
2945
|
+
export { BubbleController, DC, MC, McBase, autoload, bindTemplateEvents, copyGettersSetters, debounce, deepEqual, defineCE, flattenObject, formValuePlugin, formValues, getCE, getMcEventName, htmlToElements, injectCSS, isAlreadyObserved, isBrowser, isMcHost, isNativeObject, kebabToPascal, listCE, loadAssets, nameSpace, observe, observePlugin, off, on, one, parse, pascalToKebab, processAssets, sortObject, trigger, trueEventName };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
function e(e){return`_mc`+e[0].toUpperCase()+e.substring(1)}function t(e,t){let n=t.toLowerCase();return`on`+n in e?n:`_mc`+t[0].toUpperCase()+t.substring(1)}function n(e,r,i){if(e){if(typeof e==`string`){document.querySelectorAll(e).forEach(e=>n(e,r,i));return}e.removeEventListener(t(e,r),i)}}function r(e,n,i,a=!1){if(e){if(typeof e==`string`){document.querySelectorAll(e).forEach(e=>r(e,n,i));return}return e.addEventListener(t(e,n),i,{capture:!1,once:a}),i}}function i(e,t,n){if(e){if(typeof e==`string`){document.querySelectorAll(e).forEach(e=>i(e,t,n));return}return r(e,t,n,!0),n}}var a=class{stopped=!1;constructor(){}stop(){this.stopped=!0}};function o(e,n,r={},i=`l`,s){if(!e)return;if(typeof e==`string`){document.querySelectorAll(e).forEach(e=>o(e,n,r,i));return}let c=/^_mc/.test(n)?n:t(e,n),l=s||new a,u=new CustomEvent(c,{detail:{data:r,control:l},bubbles:!1});l.stopped||/l/.test(i)&&(e.dispatchEvent(u),l.stopped)||/[ud]/.test(i)&&queueMicrotask(()=>{if(i.indexOf(`u`)>-1&&o(e.parentElement,c,r,`lu`,l),i.indexOf(`d`)>-1)for(let t of e.children)o(t,c,r,`ld`)})}function s(){return typeof window<`u`&&window.document!==void 0}function c(e){return typeof e==`object`&&!!e&&e.constructor===Object}function l(e){let t={},n=Object.keys(e).sort();for(let r=0;r<n.length;r++){let i=n[r],a=e[i];c(a)?t[i]=l(a):t[i]=a}return t}function u(e,t=!0){let n={},r=e,i=Object.getOwnPropertyNames(e);for(let e=0;e<i.length;e++){let t=i[e],a=r[t];if(a instanceof Object){let e=u(a,!1);for(let r in e)n[t+`.`+r]=e[r]}else n[t]=a}return t?l(n):n}function d(e,t){if(e===t||e!==e&&t!==t)return!0;if(typeof e!=`object`||!e||typeof t!=`object`||!t||e.constructor!==t.constructor)return!1;if(e instanceof Date)return e.getTime()===t.getTime();if(e instanceof RegExp)return e.toString()===t.toString();if(Array.isArray(e)){let n=t;if(e.length!==n.length)return!1;for(let t=0;t<e.length;t++)if(!d(e[t],n[t]))return!1;return!0}let n=e,r=t,i=Object.keys(n);if(i.length!==Object.keys(r).length)return!1;for(let e=0;e<i.length;e++){let t=i[e];if(!Object.prototype.hasOwnProperty.call(r,t)||!d(n[t],r[t]))return!1}return!0}function f(e,t={}){let n=t,r=typeof e==`string`?e.split(`.`):e;if(!(!n||!r[0]||!n[r[0]])){if(r.length>1){let e=n[r[0]];return c(e)?f(r.slice(1),e):void 0}return n[r[0]]}}function p(e,t,...n){let r=[e,t,...n];if(r.length>2){for(;r.length>1;)r[0]=p(r[0],r[1]),r.splice(1,1);return r[0]}if(typeof e==`string`){let n=e;return e.match(/\{[^\{\}]*\}/g)?.forEach(e=>{let r=f(e.substring(1,e.length-1),t);r!==void 0&&(n=n.replace(e,String(r)))}),n}else if(c(e)){let n=e;Object.keys(n).forEach(e=>{Object.prototype.hasOwnProperty.call(n,e)&&(n[e]=p(n[e],t))})}return e}function m(e){return e.split(`-`).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(``)}function h(e,t){let n;return(...r)=>{clearTimeout(n),n=setTimeout(()=>{e(...r)},t)}}function ee(e){let t=document.createElement(`template`);return e=e.replace(/<([A-Za-z0-9\-]*)([^>\/]*)(\/>)/gi,`<$1$2></$1>`),t.innerHTML=e,t.content.normalize(),Array.from(t.content.childNodes)}function g(e,t){let n=Object.getOwnPropertyDescriptors(e);for(let[e,r]of Object.entries(n))(`get`in r||`set`in r)&&Object.defineProperty(t,e,r)}var _=new WeakMap;function v(e,t){let n=_.get(e)??new Set;if(n.has(t))return e.adoptedStyleSheets[0];n.add(t),_.set(e,n);let r=new CSSStyleSheet;return r.replaceSync(t),e.adoptedStyleSheets.push(r),r}function y(e,t){let n=e.target,r=n.shadowRoot;!r&&Object.keys(t).some(e=>e.indexOf(`shadow`)===0)&&(r=n.attachShadow({mode:`open`})),Object.keys(t).forEach(i=>{switch(i){case`css`:v(document,t[i]);break;case`targetCss`:v(document,t[i]);break;case`shadowCss`:v(r,t[i]);break;case`shadowHtml`:r.innerHTML=t[i],x(r,e);break;case`targetHtml`:n.innerHTML=t[i],x(n,e);break}})}function b(e,t){let n=t=>{let n=t.match(/^([a-z]+)([A-Z][a-z]*)$/);return n?`./${e.replace(/-/g,`/`)}.${n[1]}.${n[2].toLowerCase()}`:`./${e.replace(/-/g,`/`)}.${t.toLowerCase()}`};return Promise.all(t.map(async e=>{let t=n(e);try{let n=await fetch(t);if(!n.ok)return`file not found: ${t}`;if(t.endsWith(`json`)){let r=await n.text();try{return JSON.parse(r)}catch{return console.error(`could not JSON.parse() asset '${e}' from ${t}:\n`,r),null}}return n.text()}catch{return`file not found: ${t}`}}))}function x(e,t){let n=[...e.querySelectorAll(`*`)];for(let e of n){if(!(e instanceof HTMLElement))continue;let n=[...e.attributes];for(let i of n){let n=i.name.toLowerCase();if(!(`on`+n in e))continue;let a=i.value.trim().split(`|`);if(a.length<2)continue;let[s,c,l]=a;e.removeAttribute(i.name);let u;if(l)try{u=JSON.parse(l)}catch{u=l}s===`this`||s===``?r(e,n,()=>t.trigger(c,u)):r(e,n,()=>o(s,c,u))}}}function S(e,t){return typeof HTMLElement<`u`&&e instanceof HTMLElement&&`_mc`in e&&(t===void 0||t in e._mc)}function C(e,t,n={}){let r=e;`_mc`in e||(r._mc=new O(e));let i=r._mc;return t.length&&!i[t]&&(i[t]=n,e instanceof HTMLElement&&!e.getAttribute(`data-mc`)&&e.setAttribute(`data-mc`,``)),r}function te(e,t){if(!t)return;let n=e._mc;n&&(n[t]&&delete n[t],!Object.keys(n).length&&e instanceof HTMLElement&&e.hasAttribute(`data-mc`)&&e.removeAttribute(`data-mc`))}function ne(e){queueMicrotask(()=>{e.trigger(`Init`,null)})}function w(e){let t=e.target,n=Object.getPrototypeOf(e),i=e,a=Object.getOwnPropertyNames(n).filter(e=>/^(on[A-Z]|one[A-Z])/.test(e)&&typeof n[e]==`function`);for(let e of a){let n=/^one/.test(e);r(t,e.replace(/^one?/,``),t=>i[e](t),n)}}function T(e){return Array.from(e.querySelectorAll(`[data-mc]:not(:scope [data-mc] [data-mc])`)).filter(e=>e instanceof HTMLElement&&`_mc`in e).map(e=>e._mc)}function E(e,t){let n=e.parentElement?.closest(`[data-mc]`);for(;n instanceof HTMLElement;){if(`_mc`in n){let e=n._mc;if(t===void 0||t in e)return e}n=n.parentElement?.closest(`[data-mc]`)}return null}var D=class{_target;constructor(e){if(this._target=new WeakRef(e||{}),this instanceof O&&this.constructor!==O){w(this);let e=this.constructor.tag;(e===void 0||e.toUpperCase()===this.target.tagName)&&ne(this)}}get target(){return this._target.deref()}},re=class extends D{constructor(e){super(e)}},O=class e extends D{static tag;static _assets={};static assets=[];static _assetsPromise;static attributes={};constructor(t){super(t);let n=this.constructor;if(n===e)return;let r=this.target.tagName.toLowerCase();if(n.tag!==void 0&&r!==n.tag&&n.tag!==``){let t=document.createElement(n.tag);t.classList.add(r),n._originalTag=r,e.add(t,n.name,new n(t)),delete n._originalTag,r.includes(`-`)&&!this.target.isConnected?this.on(`connected`,()=>this.target.replaceWith(t)):this.target.replaceWith(t);return}let i=n.attributes;n.attributes&&Object.keys(n.attributes).forEach(e=>{this.target.setAttribute(e,i[e])});let a=this,o=n.assets.filter(e=>!n._assets[e]);if(Object.keys(n._assets).length&&y(this,n._assets),o.length?(n._assetsPromise||=b(n._originalTag||r,o).then(e=>{let t={};o.forEach((n,r)=>{t[n]=e[r]}),n._assets=Object.assign({},n._assets,t);for(let e of[`css`,`targetCss`])t[e]!==void 0&&delete n._assets[e];return n.assets=n.assets.filter(e=>e!==`css`&&e!==`targetCss`),t}),n._assetsPromise.then(e=>{y(this,e),a.trigger(`assets`,n._assets)})):[...Object.keys(n._assets)].length&&queueMicrotask(()=>a.trigger(`assets`,n._assets)),n.tag===``){this.target.remove();return}}getAssets(){return this.constructor._assets||{}}static add(e,t,n={}){return C(e,t,n)}static remove(e,t){te(e,t)}static get(e,t,n){if(!S(e))return;let r=e._mc[t];return r instanceof n?r:void 0}off(e,t){n(this.target,e,t)}on(e,t){return r(this.target,e,t)}one(e,t){return i(this.target,e,t)}trigger(e,t={},n=`l`,r){o(this.target,e,t,n,r)}ancestors(e){let t=[],n=E(this.target,e);for(;n;)t.push(n),n=E(n.target,e);return t}closest(e){return E(this.target,e)}children(e){let t=T(this.target);return e===void 0?t:t.filter(t=>e in t)}descendants(e){return Array.from(this.target.querySelectorAll(`[data-mc]`)).filter(e=>e instanceof HTMLElement&&`_mc`in e).map(e=>e._mc).filter(t=>e===void 0||e in t)}};function k(e){return e.split(`-`).join(`/`)}function A(e){return`./`+k(e)+`.js`}var j=new Set;function M(e){return()=>{let t=Array.from(document.querySelectorAll(`[data-mc*="${e}"]`)).filter(e=>e instanceof HTMLElement);if(t.length===0)return;let n=customElements.get(e);for(let r of t){try{O.add(r,n.name,new n(r))}catch{if(`create`in n&&typeof n.create==`function`){let e=n.create(r);if(!S(e))throw`create() of Class ${n.name} did not return a McHost.`;e.setAttribute(`data-mc`,r.getAttribute(`data-mc`)??``),r.replaceWith(e),r=e}else throw`Class ${n.name} doesn't have a callable constructor AND class doesn't have a static .create() method.`}let t=r.getAttribute(`data-mc`).split(` `).filter(t=>t!==e&&t!==``).join(` `).trim();r.setAttribute(`data-mc`,t)}}}function N(e){if(j.has(e))return;j.add(e);let t=A(e),n=document.createElement(`script`);n.setAttribute(`src`,t),n.setAttribute(`blocking`,`render`),n.async=!0,n.setAttribute(`type`,`module`),n.setAttribute(`data-name`,e),n.setAttribute(`loading`,``),customElements.whenDefined(e).then(M(e)),n.addEventListener(`load`,t=>{j.delete(e),document.head.querySelector(`script[data-name="${e}"]`)?.remove()}),n.addEventListener(`error`,e=>{console.error(`could not load DC code from`,t)}),document.head.append(n)}function P(){[...document.querySelectorAll(`:not(:defined)`)].filter(e=>!!e&&!customElements.get(e.tagName.toLowerCase())&&!j.has(e.tagName.toLowerCase())).forEach(e=>{N(e.tagName.toLowerCase())}),[...document.querySelectorAll(`[data-mc]:not([data-mc=""]`)].filter(e=>!!e).forEach(e=>{(e.getAttribute(`data-mc`)?.split(` `).filter(e=>e!==``))?.forEach(e=>{let t=customElements.get(e);!j.has(e)&&!t?N(e):t&&M(e)()})})}var F=null;function I(e=!0){return e?F?!0:(F=new MutationObserver(P),setTimeout(()=>{F.observe(document.body,{childList:!0,subtree:!0}),P()},5),window.autoload??=I,!0):(F&&=(F.disconnect(),null),!1)}I.state=j;function ie(e,t){return Object.defineProperty(t,"name",{value:e})}function ae(e){return class extends e{constructor(...e){super(...e)}}}function L(e,t,n=[],r){if(customElements.get(e)){console.warn(`IGNORED: Custom element "${e}" is already defined!`);return}if(!e.includes(`-`))throw Error(`createCustomElement: tagName must contain at least one hyphen ("-").`);let i=HTMLElement;r&&(i=document.createElement(r).constructor);let a=m(e);if(!(t.prototype instanceof D))return customElements.define(e,t),t;let o=ie(a,class extends ae(i){constructor(e){super(),O.add(this,a,new t(this,e))}connectedCallback(){this.dispatchEvent(new CustomEvent(`_mcConnected`))}connectedMoveCallback(){this.dispatchEvent(new CustomEvent(`_mcConnectedMove`))}disconnectedCallback(){this.dispatchEvent(new CustomEvent(`_mcDisconnected`))}adoptedCallback(){this.dispatchEvent(new CustomEvent(`_mcAdopted`))}attributeChangedCallback(e,t,n){this.dispatchEvent(new CustomEvent(`_mcAttributeChanged`,{detail:{name:e,oldValue:t,newValue:n}}))}formResetCallback(){this.dispatchEvent(new CustomEvent(`_mcFormReset`))}static get observedAttributes(){return[...n]}});return customElements.define(e,o,{extends:r}),L.list||=[],L.list.push(e),o}function R(e){return customElements.get(e)}function z(){return L.list??[]}function B(e){let t=new Set,n=/\{[^\{\}]*\}/g;return(e.getAttributeNames?e.getAttributeNames():[]).filter(t=>e.getAttribute(t)?.match(n)).forEach(r=>{new Set(e.getAttribute(r)?.match(n)).forEach(e=>t.add(e.replace(/[\{\}]/g,``)))}),[...e.childNodes].filter(e=>e.nodeType===3&&(e.nodeValue||``).match(n)).forEach(e=>{(e?.nodeValue||``).match(n).forEach(e=>t.add(e.replace(/[\{\}]/g,``)))}),[...t]}var V=[`INPUT`,`SELECT`,`TEXTAREA`],H=class extends O{data={};oldDisplay=``;constructor(e){super(e),B(e).forEach(e=>this.data[e]=``),X(this),this.#e()}#e(){let e=this.target,t=!1;(e.getAttributeNames?e.getAttributeNames():[]).filter(t=>e.getAttribute(t)?.match(/\{[^\{\}]*\}/g)).forEach(t=>{let n=new Set(e.getAttribute(t)?.match(/\{[^\{\}]*\}/g)),r=e.getAttribute(t)??``;this.data.subscribe((r=>i=>{let a=r;n.forEach(e=>{a=a.replace(e,String(i[e.replace(/[\{\}]/g,``)]))}),e.setAttribute(t,a)})(r))}),[...e.childNodes].filter(e=>e.nodeType===3&&(e.nodeValue||``).match(/\{[^\{\}]*\}/g)).forEach(n=>{t=!0;let r=n.nodeValue??``,i=new Set(r.match(/\{[^\{\}]*\}/g));this.data.subscribe((t=>r=>{let a=t;i.forEach(e=>{a=a.replace(e,String(r[e.replace(/[\{\}]/g,``)]))}),this.oldDisplay?e.style=this.oldDisplay:e.removeAttribute(`style`),delete this.oldDisplay,n.nodeValue=a})(r)),this.oldDisplay=e.getAttribute(`style`)||``,t&&!V.includes(e.tagName)&&e.tagName!==`FIELDSET`&&(e.style.display=`none`)})}onData(e){let t={};Object.keys(e.detail.data).forEach(n=>{this.data.hasOwnProperty(n)&&(t[n]=e.detail.data[n])}),JSON.stringify(t)!==JSON.stringify(this.data)&&Object.assign(this.data,t)}};function U(e){return[e,...e.querySelectorAll(`*`)].filter(e=>!!B(e).length).filter(e=>e?.tagName!==`STYLE`).reverse()}function W(e){U(e).forEach(e=>{e?._mc?._placeholders||O.add(e,`_placeholders`,new H(e))})}function G(e){return typeof e==`object`&&!!e}var K={};function q(e){let t=e.constructor,n=t.name,r=class extends t{#e=!0;#t=[];constructor(e){super(e);let t=this.constructor;t.callbacks=[],G(e)&&Object.getOwnPropertyNames(e).forEach(t=>{this[t]=e[t]})}get callbacks(){return this.#t}set callbacks(e){this.#t=e}[Symbol.toPrimitive](e){let t=this.valueOf();return e===`string`?String(t):e===`number`?Number(t):t}subscribe(e){return this.#t.push(e),this}unsubscribe(e){return this.#t=this.#t.filter(t=>t!==e),this}bind(e){if(s()){if(G(this.valueOf())){W(e);let t=[e,...e.querySelectorAll(`[data-mc]`)].filter(e=>!!e?._mc?._placeholders);this.#t.push(function(e){let n=u(e);t.forEach(e=>{e&&o(e,`data`,n)})}),this.notify()}else console.warn(`IGNORED - cannot bind a non-Object to the dom, IS:`,typeof this.valueOf(),this);return this}}notify(e){let t=G(this.valueOf())&&!(this.valueOf()instanceof Array)?structuredClone(Object.assign({},this)):this.valueOf();return e!==void 0&&(this.#e=e),this.#e&&this.#t.forEach(e=>{e(t)}),this}};return K[n]=r,r}function J(e){return K[e.constructor.name]||q(e)}function Y(e){return(typeof e==`object`||typeof e==`function`)&&e!==null&&`subscribe`in e}function X(e,t){let n=e;return(t?[t]:[...Object.getOwnPropertyNames(e)]).forEach(t=>{let r=n[t];if(Object.prototype.hasOwnProperty.call(e,t)&&typeof r!=`function`&&!Y(r)){if(t[0]===`_`||r===void 0)return;let i=r,a=new(J(i))(i),o=function(){queueMicrotask(function(){a.notify()})};Object.defineProperty(e,t,{enumerable:!0,get(){if(G(a.valueOf())){let e=structuredClone(Object.assign({},a));queueMicrotask(function(){d(structuredClone(Object.assign({},a)),e)||o()})}return a},set(e){if(typeof e==typeof a.valueOf())if(G(a.valueOf())&&!(a.valueOf()instanceof Array))Y(a)||(a=new(J(e))(structuredClone(Object.assign({},e))),g(e,a)),Object.assign(a,e),a.notify();else{let t=a.valueOf(),n=a.callbacks;e!==t&&(a=new(J(e))(e),a.callbacks=n,o())}else console.warn(`IGNORED - cannot change observable types, IS:`,typeof a.valueOf(),a,`- CANNOT BECOME:`,typeof e)}}),n[t]=i}}),e}function Z(e){let t=Object.getPrototypeOf(e.prototype);function n(e,t){let n=e[t];Y(n)||X(e,t)}Object.hasOwn(t,`notify`)||Object.assign(t,{notify:function(e){return n(this,e),this[e].notify(),this},subscribe:function(e,t){return n(this,e),this[e].subscribe(t),this},bind:function(e,t){return n(this,e),this[e].bind(t),this}})}Z(O);var oe=e=>e.tagName.toLowerCase(),Q=class{constructor(e){}},se=class extends Q{#e;constructor(e){super(e),this.#e=e}get val(){return this.#e.form?new FormData(this.#e.form).get(this.#e.name)??null:null}set val(e){let t=[...this.#e.form?.querySelectorAll(`input[type="radio"][name="${this.#e.name}"]`)??[]];t.filter(t=>t.getAttribute(`value`)===e).shift().checked=!0}},ce=class extends Q{#e;constructor(e){super(e),this.#e=e}get val(){return this.#e.checked}set val(e){this.#e.checked=e}},le=class extends Q{#e;constructor(e){super(e),this.#e=e}get val(){return this.#e.value}set val(e){this.#e.value=e}},ue=class extends Q{#e;#t=!1;constructor(e){super(e),this.#e=e,this.#t=e.multiple}get val(){let e=[];return[...this.#e.querySelectorAll(`option`)].filter(e=>e.selected).forEach(t=>{e.push(t.value)}),this.#t?e:e[0]}set val(e){e=typeof e==`string`?[e]:e,[...this.#e.querySelectorAll(`option`)].forEach(t=>{e.indexOf(t.value)>-1?t.selected=!0:t.selected=!1})}},de=class extends Q{#e;constructor(e){super(e),this.#e=e}get val(){return this.#e.value||``}set val(e){this.#e.value=e}},fe=e=>{let t=[...(e||document).querySelectorAll(`input,select,textarea`)],n={};return t.forEach(e=>{let t=e.getAttribute(`name`);if(t){let r=!1;switch(oe(e)){case`input`:switch(e.type){case`radio`:r=new se(e);break;case`checkbox`:r=new ce(e);break;default:r=new le(e)}break;case`select`:r=new ue(e);break;case`textarea`:r=new de(e);break}if(r){let i=r;O.add(e,t,i),Object.defineProperty(n,t,{enumerable:!0,configurable:!0,get:()=>i.val,set:e=>{i.val!==e&&(i.val=e)}})}}}),n};function $(e,t,n){if(!s())return;let r=fe(n),i=e;i[t]=Object.assign({},r),X(e,t);let a=i[t];g(r,a),[...n.querySelectorAll(`input, textarea, select`)].forEach(e=>{e.addEventListener(`input`,()=>{a.notify()})})}function pe(e){let t=Object.getPrototypeOf(e.prototype);Object.hasOwn(t,`formValues`)||Object.assign(t,{formValues:function(e,t){return $(this,t,e),this}})}export{a as BubbleController,O as DC,re as MC,D as McBase,I as autoload,x as bindTemplateEvents,g as copyGettersSetters,h as debounce,d as deepEqual,L as defineCE,u as flattenObject,pe as formValuePlugin,$ as formValues,R as getCE,e as getMcEventName,ee as htmlToElements,v as injectCSS,Y as isAlreadyObserved,s as isBrowser,S as isMcHost,c as isNativeObject,m as kebabToPascal,z as listCE,b as loadAssets,f as nameSpace,X as observe,Z as observePlugin,n as off,r as on,i as one,p as parse,y as processAssets,l as sortObject,o as trigger,t as trueEventName};
|
|
1
|
+
function e(e){return`_mc`+e[0].toUpperCase()+e.substring(1)}function t(e,t){let n=t.toLowerCase();return`on`+n in e?n:`_mc`+t[0].toUpperCase()+t.substring(1)}function n(e,r,i){if(e){if(typeof e==`string`){document.querySelectorAll(e).forEach(e=>n(e,r,i));return}e.removeEventListener(t(e,r),i)}}function r(e,n,i,a=!1){if(e){if(typeof e==`string`){document.querySelectorAll(e).forEach(e=>r(e,n,i));return}return e.addEventListener(t(e,n),i,{capture:!1,once:a}),i}}function i(e,t,n){if(e){if(typeof e==`string`){document.querySelectorAll(e).forEach(e=>i(e,t,n));return}return r(e,t,n,!0),n}}var a=class{stopped=!1;constructor(){}stop(){this.stopped=!0}};function o(e,n,r={},i=`l`,s){if(!e)return;if(typeof e==`string`){document.querySelectorAll(e).forEach(e=>o(e,n,r,i));return}let c=/^_mc/.test(n)?n:t(e,n),l=s||new a,u=new CustomEvent(c,{detail:{data:r,control:l},bubbles:!1});l.stopped||/l/.test(i)&&(e.dispatchEvent(u),l.stopped)||/[ud]/.test(i)&&queueMicrotask(()=>{if(i.indexOf(`u`)>-1&&o(e.parentElement,c,r,`lu`,l),i.indexOf(`d`)>-1)for(let t of e.children)o(t,c,r,`ld`)})}function s(){return typeof window<`u`&&window.document!==void 0}function c(e){return typeof e==`object`&&!!e&&e.constructor===Object}function l(e){let t={},n=Object.keys(e).sort();for(let r=0;r<n.length;r++){let i=n[r],a=e[i];c(a)?t[i]=l(a):t[i]=a}return t}function u(e,t=!0){let n={},r=e,i=Object.getOwnPropertyNames(e);for(let e=0;e<i.length;e++){let t=i[e],a=r[t];if(a instanceof Object){let e=u(a,!1);for(let r in e)n[t+`.`+r]=e[r]}else n[t]=a}return t?l(n):n}function d(e,t){if(e===t||e!==e&&t!==t)return!0;if(typeof e!=`object`||!e||typeof t!=`object`||!t||e.constructor!==t.constructor)return!1;if(e instanceof Date)return e.getTime()===t.getTime();if(e instanceof RegExp)return e.toString()===t.toString();if(Array.isArray(e)){let n=t;if(e.length!==n.length)return!1;for(let t=0;t<e.length;t++)if(!d(e[t],n[t]))return!1;return!0}let n=e,r=t,i=Object.keys(n);if(i.length!==Object.keys(r).length)return!1;for(let e=0;e<i.length;e++){let t=i[e];if(!Object.prototype.hasOwnProperty.call(r,t)||!d(n[t],r[t]))return!1}return!0}function f(e,t={}){let n=t,r=typeof e==`string`?e.split(`.`):e;if(!(!n||!r[0]||!n[r[0]])){if(r.length>1){let e=n[r[0]];return c(e)?f(r.slice(1),e):void 0}return n[r[0]]}}function p(e,t,...n){let r=[e,t,...n];if(r.length>2){for(;r.length>1;)r[0]=p(r[0],r[1]),r.splice(1,1);return r[0]}if(typeof e==`string`){let n=e;return e.match(/\{[^\{\}]*\}/g)?.forEach(e=>{let r=f(e.substring(1,e.length-1),t);r!==void 0&&(n=n.replace(e,String(r)))}),n}else if(c(e)){let n=e;Object.keys(n).forEach(e=>{Object.prototype.hasOwnProperty.call(n,e)&&(n[e]=p(n[e],t))})}return e}function m(e){return e.split(`-`).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(``)}function h(e){return e.replace(/[A-Z]/g,(e,t)=>(t?`-`:``)+e.toLowerCase())}function ee(e,t){let n;return(...r)=>{clearTimeout(n),n=setTimeout(()=>{e(...r)},t)}}function te(e){let t=document.createElement(`template`);return e=e.replace(/<([A-Za-z0-9\-]*)([^>\/]*)(\/>)/gi,`<$1$2></$1>`),t.innerHTML=e,t.content.normalize(),Array.from(t.content.childNodes)}function g(e,t){let n=Object.getOwnPropertyDescriptors(e);for(let[e,r]of Object.entries(n))(`get`in r||`set`in r)&&Object.defineProperty(t,e,r)}var _=new WeakMap;function v(e,t){let n=_.get(e)??new Set;if(n.has(t))return e.adoptedStyleSheets[0];n.add(t),_.set(e,n);let r=new CSSStyleSheet;return r.replaceSync(t),e.adoptedStyleSheets.push(r),r}function y(e,t){let n=e.target,r=n.shadowRoot;!r&&Object.keys(t).some(e=>e.indexOf(`shadow`)===0)&&(r=n.attachShadow({mode:`open`})),Object.keys(t).forEach(i=>{switch(i){case`css`:v(document,t[i]);break;case`targetCss`:v(document,t[i]);break;case`shadowCss`:v(r,t[i]);break;case`shadowHtml`:r.innerHTML=t[i],x(r,e);break;case`targetHtml`:n.innerHTML=t[i],x(n,e);break}})}function b(e,t){let n=t=>{let n=t.match(/^([a-z]+)([A-Z][a-z]*)$/);return n?`./${e.replace(/-/g,`/`)}.${n[1]}.${n[2].toLowerCase()}`:`./${e.replace(/-/g,`/`)}.${t.toLowerCase()}`};return Promise.all(t.map(async e=>{let t=n(e);try{let n=await fetch(t);if(!n.ok)return`file not found: ${t}`;if(t.endsWith(`json`)){let r=await n.text();try{return JSON.parse(r)}catch{return console.error(`could not JSON.parse() asset '${e}' from ${t}:\n`,r),null}}return n.text()}catch{return`file not found: ${t}`}}))}function x(e,t){let n=[...e.querySelectorAll(`*`)];for(let e of n){if(!(e instanceof HTMLElement))continue;let n=[...e.attributes];for(let i of n){let n=i.name.toLowerCase();if(!(`on`+n in e))continue;let a=i.value.trim().split(`|`);if(a.length<2)continue;let[s,c,l]=a;e.removeAttribute(i.name);let u;if(l)try{u=JSON.parse(l)}catch{u=l}s===`this`||s===``?r(e,n,()=>t.trigger(c,u)):r(e,n,()=>o(s,c,u))}}}function S(e,t){return typeof HTMLElement<`u`&&e instanceof HTMLElement&&`_mc`in e&&(t===void 0||t in e._mc)}function C(e,t,n={}){let r=e;`_mc`in e||(r._mc=new k(e));let i=r._mc;return t.length&&!i[t]&&(i[t]=n,e instanceof HTMLElement&&!e.getAttribute(`data-mc`)&&e.setAttribute(`data-mc`,``)),r}function w(e,t){if(!t)return;let n=e._mc;n&&(n[t]&&delete n[t],!Object.keys(n).length&&e instanceof HTMLElement&&e.hasAttribute(`data-mc`)&&e.removeAttribute(`data-mc`))}function T(e){queueMicrotask(()=>{e.trigger(`Init`,null)})}function ne(e){let t=e.target,n=Object.getPrototypeOf(e),i=e,a=Object.getOwnPropertyNames(n).filter(e=>/^(on[A-Z]|one[A-Z])/.test(e)&&typeof n[e]==`function`);for(let e of a){let n=/^one/.test(e);r(t,e.replace(/^one?/,``),t=>i[e](t),n)}}function E(e){return Array.from(e.querySelectorAll(`[data-mc]:not(:scope [data-mc] [data-mc])`)).filter(e=>e instanceof HTMLElement&&`_mc`in e).map(e=>e._mc)}function D(e,t){let n=e.parentElement?.closest(`[data-mc]`);for(;n instanceof HTMLElement;){if(`_mc`in n){let e=n._mc;if(t===void 0||t in e)return e}n=n.parentElement?.closest(`[data-mc]`)}return null}var O=class{_target;static _assets={};static assets=[];static _assetsPromise;constructor(e){this._target=new WeakRef(e||{});let t=this.constructor;this instanceof k&&this.constructor!==k&&ne(this);let n=(t.assets??[]).filter(e=>!t._assets[e]);n.length&&!t._assetsPromise&&(t._assetsPromise=b(t._originalTag||(this instanceof k?this.target.tagName.toLowerCase():h(t.name)),n).then(e=>{let r={};return n.forEach((t,n)=>{r[t]=e[n]}),t._assets=Object.assign({},t._assets,r),r}))}get target(){return this._target.deref()}get assets(){return this.constructor._assets||{}}},re=class extends O{constructor(e){super(e)}},k=class e extends O{static tag;static attributes={};constructor(t){super(t);let n=this.constructor;if(n===e)return;let r=this.target.tagName.toLowerCase();if(n.tag!==void 0&&r!==n.tag&&n.tag!==``){let t=document.createElement(n.tag);t.classList.add(r),n._originalTag=r,e.add(t,n.name,new n(t)),delete n._originalTag,r.includes(`-`)&&!this.target.isConnected?this.on(`connected`,()=>this.target.replaceWith(t)):this.target.replaceWith(t);return}let i=n.attributes;if(n.attributes&&Object.keys(n.attributes).forEach(e=>{this.target.setAttribute(e,i[e])}),Object.keys(n._assets).length){y(this,n._assets);for(let e of[`css`,`targetCss`])delete n._assets[e];n.assets=n.assets.filter(e=>e!==`css`&&e!==`targetCss`)}if(n._assetsPromise?n._assetsPromise.then(e=>{y(this,e);for(let e of[`css`,`targetCss`])delete n._assets[e];n.assets=n.assets.filter(e=>e!==`css`&&e!==`targetCss`),T(this)}):T(this),n.tag===``){this.target.remove();return}}static add(e,t,n={}){return C(e,t,n)}static remove(e,t){w(e,t)}static get(e,t,n){if(!S(e))return;let r=e._mc[t];return r instanceof n?r:void 0}off(e,t){n(this.target,e,t)}on(e,t){return r(this.target,e,t)}one(e,t){return i(this.target,e,t)}trigger(e,t={},n=`l`,r){o(this.target,e,t,n,r)}ancestors(e){let t=[],n=D(this.target,e);for(;n;)t.push(n),n=D(n.target,e);return t}closest(e){return D(this.target,e)}children(e){let t=E(this.target);return e===void 0?t:t.filter(t=>e in t)}descendants(e){return Array.from(this.target.querySelectorAll(`[data-mc]`)).filter(e=>e instanceof HTMLElement&&`_mc`in e).map(e=>e._mc).filter(t=>e===void 0||e in t)}};function ie(e){return e.split(`-`).join(`/`)}function A(e){return`./`+ie(e)+`.js`}var j=new Set;function M(e){return()=>{let t=Array.from(document.querySelectorAll(`[data-mc*="${e}"]`)).filter(e=>e instanceof HTMLElement);if(t.length===0)return;let n=customElements.get(e);for(let r of t){try{k.add(r,n.name,new n(r))}catch{if(`create`in n&&typeof n.create==`function`){let e=n.create(r);if(!S(e))throw`create() of Class ${n.name} did not return a McHost.`;e.setAttribute(`data-mc`,r.getAttribute(`data-mc`)??``),r.replaceWith(e),r=e}else throw`Class ${n.name} doesn't have a callable constructor AND class doesn't have a static .create() method.`}let t=r.getAttribute(`data-mc`).split(` `).filter(t=>t!==e&&t!==``).join(` `).trim();r.setAttribute(`data-mc`,t)}}}function N(e){if(j.has(e))return;j.add(e);let t=A(e),n=document.createElement(`script`);n.setAttribute(`src`,t),n.setAttribute(`blocking`,`render`),n.async=!0,n.setAttribute(`type`,`module`),n.setAttribute(`data-name`,e),n.setAttribute(`loading`,``),customElements.whenDefined(e).then(M(e)),n.addEventListener(`load`,t=>{j.delete(e),document.head.querySelector(`script[data-name="${e}"]`)?.remove()}),n.addEventListener(`error`,e=>{console.error(`could not load DC code from`,t)}),document.head.append(n)}function P(){[...document.querySelectorAll(`:not(:defined)`)].filter(e=>!!e&&!customElements.get(e.tagName.toLowerCase())&&!j.has(e.tagName.toLowerCase())).forEach(e=>{N(e.tagName.toLowerCase())}),[...document.querySelectorAll(`[data-mc]:not([data-mc=""]`)].filter(e=>!!e).forEach(e=>{(e.getAttribute(`data-mc`)?.split(` `).filter(e=>e!==``))?.forEach(e=>{let t=customElements.get(e);!j.has(e)&&!t?N(e):t&&M(e)()})})}var F=null;function I(e=!0){return e?F?!0:(F=new MutationObserver(P),setTimeout(()=>{F.observe(document.body,{childList:!0,subtree:!0}),P()},5),window.autoload??=I,!0):(F&&=(F.disconnect(),null),!1)}I.state=j;function ae(e,t){return Object.defineProperty(t,"name",{value:e})}function oe(e){return class extends e{constructor(...e){super(...e)}}}function L(e,t,n=[],r){if(customElements.get(e)){console.warn(`IGNORED: Custom element "${e}" is already defined!`);return}if(!e.includes(`-`))throw Error(`createCustomElement: tagName must contain at least one hyphen ("-").`);let i=HTMLElement;r&&(i=document.createElement(r).constructor);let a=m(e);if(!(t.prototype instanceof O))return customElements.define(e,t),t;let o=ae(a,class extends oe(i){constructor(e){super(),k.add(this,a,new t(this,e))}connectedCallback(){this.dispatchEvent(new CustomEvent(`_mcConnected`))}connectedMoveCallback(){this.dispatchEvent(new CustomEvent(`_mcConnectedMove`))}disconnectedCallback(){this.dispatchEvent(new CustomEvent(`_mcDisconnected`))}adoptedCallback(){this.dispatchEvent(new CustomEvent(`_mcAdopted`))}attributeChangedCallback(e,t,n){this.dispatchEvent(new CustomEvent(`_mcAttributeChanged`,{detail:{name:e,oldValue:t,newValue:n}}))}formResetCallback(){this.dispatchEvent(new CustomEvent(`_mcFormReset`))}static get observedAttributes(){return[...n]}});return customElements.define(e,o,{extends:r}),L.list||=[],L.list.push(e),o}function R(e){return customElements.get(e)}function z(){return L.list??[]}function B(e){let t=new Set,n=/\{[^\{\}]*\}/g;return(e.getAttributeNames?e.getAttributeNames():[]).filter(t=>e.getAttribute(t)?.match(n)).forEach(r=>{new Set(e.getAttribute(r)?.match(n)).forEach(e=>t.add(e.replace(/[\{\}]/g,``)))}),[...e.childNodes].filter(e=>e.nodeType===3&&(e.nodeValue||``).match(n)).forEach(e=>{(e?.nodeValue||``).match(n).forEach(e=>t.add(e.replace(/[\{\}]/g,``)))}),[...t]}var V=[`INPUT`,`SELECT`,`TEXTAREA`],H=class extends k{data={};oldDisplay=``;constructor(e){super(e),B(e).forEach(e=>this.data[e]=``),Y(this),this.#e()}#e(){let e=this.target,t=!1;(e.getAttributeNames?e.getAttributeNames():[]).filter(t=>e.getAttribute(t)?.match(/\{[^\{\}]*\}/g)).forEach(t=>{let n=new Set(e.getAttribute(t)?.match(/\{[^\{\}]*\}/g)),r=e.getAttribute(t)??``;this.data.subscribe((r=>i=>{let a=r;n.forEach(e=>{a=a.replace(e,String(i[e.replace(/[\{\}]/g,``)]))}),e.setAttribute(t,a)})(r))}),[...e.childNodes].filter(e=>e.nodeType===3&&(e.nodeValue||``).match(/\{[^\{\}]*\}/g)).forEach(n=>{t=!0;let r=n.nodeValue??``,i=new Set(r.match(/\{[^\{\}]*\}/g));this.data.subscribe((t=>r=>{let a=t;i.forEach(e=>{a=a.replace(e,String(r[e.replace(/[\{\}]/g,``)]))}),this.oldDisplay?e.style=this.oldDisplay:e.removeAttribute(`style`),delete this.oldDisplay,n.nodeValue=a})(r)),this.oldDisplay=e.getAttribute(`style`)||``,t&&!V.includes(e.tagName)&&e.tagName!==`FIELDSET`&&(e.style.display=`none`)})}onData(e){let t={};Object.keys(e.detail.data).forEach(n=>{this.data.hasOwnProperty(n)&&(t[n]=e.detail.data[n])}),JSON.stringify(t)!==JSON.stringify(this.data)&&Object.assign(this.data,t)}};function U(e){return[e,...e.querySelectorAll(`*`)].filter(e=>!!B(e).length).filter(e=>e?.tagName!==`STYLE`).reverse()}function W(e){U(e).forEach(e=>{e?._mc?._placeholders||k.add(e,`_placeholders`,new H(e))})}function G(e){return typeof e==`object`&&!!e}var K={};function se(e){let t=e.constructor,n=t.name,r=class extends t{#e=!0;#t=[];constructor(e){super(e);let t=this.constructor;t.callbacks=[],G(e)&&Object.getOwnPropertyNames(e).forEach(t=>{this[t]=e[t]})}get callbacks(){return this.#t}set callbacks(e){this.#t=e}[Symbol.toPrimitive](e){let t=this.valueOf();return e===`string`?String(t):e===`number`?Number(t):t}subscribe(e){return this.#t.push(e),this}unsubscribe(e){return this.#t=this.#t.filter(t=>t!==e),this}bind(e){if(s()){if(G(this.valueOf())){W(e);let t=[e,...e.querySelectorAll(`[data-mc]`)].filter(e=>!!e?._mc?._placeholders);this.#t.push(function(e){let n=u(e);t.forEach(e=>{e&&o(e,`data`,n)})}),this.notify()}else console.warn(`IGNORED - cannot bind a non-Object to the dom, IS:`,typeof this.valueOf(),this);return this}}notify(e){let t=G(this.valueOf())&&!(this.valueOf()instanceof Array)?structuredClone(Object.assign({},this)):this.valueOf();return e!==void 0&&(this.#e=e),this.#e&&this.#t.forEach(e=>{e(t)}),this}};return K[n]=r,r}function q(e){return K[e.constructor.name]||se(e)}function J(e){return(typeof e==`object`||typeof e==`function`)&&e!==null&&`subscribe`in e}function Y(e,t){let n=e;return(t?[t]:[...Object.getOwnPropertyNames(e)]).forEach(t=>{let r=n[t];if(Object.prototype.hasOwnProperty.call(e,t)&&typeof r!=`function`&&!J(r)){if(t[0]===`_`||r===void 0)return;let i=r,a=new(q(i))(i),o=function(){queueMicrotask(function(){a.notify()})};Object.defineProperty(e,t,{enumerable:!0,get(){if(G(a.valueOf())){let e=structuredClone(Object.assign({},a));queueMicrotask(function(){d(structuredClone(Object.assign({},a)),e)||o()})}return a},set(e){if(typeof e==typeof a.valueOf())if(G(a.valueOf())&&!(a.valueOf()instanceof Array))J(a)||(a=new(q(e))(structuredClone(Object.assign({},e))),g(e,a)),Object.assign(a,e),a.notify();else{let t=a.valueOf(),n=a.callbacks;e!==t&&(a=new(q(e))(e),a.callbacks=n,o())}else console.warn(`IGNORED - cannot change observable types, IS:`,typeof a.valueOf(),a,`- CANNOT BECOME:`,typeof e)}}),n[t]=i}}),e}function X(e){let t=Object.getPrototypeOf(e.prototype);function n(e,t){let n=e[t];J(n)||Y(e,t)}Object.hasOwn(t,`notify`)||Object.assign(t,{notify:function(e){return n(this,e),this[e].notify(),this},subscribe:function(e,t){return n(this,e),this[e].subscribe(t),this},bind:function(e,t){return n(this,e),this[e].bind(t),this}})}X(k);var Z=e=>e.tagName.toLowerCase(),Q=class{constructor(e){}},ce=class extends Q{#e;constructor(e){super(e),this.#e=e}get val(){return this.#e.form?new FormData(this.#e.form).get(this.#e.name)??null:null}set val(e){let t=[...this.#e.form?.querySelectorAll(`input[type="radio"][name="${this.#e.name}"]`)??[]];t.filter(t=>t.getAttribute(`value`)===e).shift().checked=!0}},le=class extends Q{#e;constructor(e){super(e),this.#e=e}get val(){return this.#e.checked}set val(e){this.#e.checked=e}},ue=class extends Q{#e;constructor(e){super(e),this.#e=e}get val(){return this.#e.value}set val(e){this.#e.value=e}},de=class extends Q{#e;#t=!1;constructor(e){super(e),this.#e=e,this.#t=e.multiple}get val(){let e=[];return[...this.#e.querySelectorAll(`option`)].filter(e=>e.selected).forEach(t=>{e.push(t.value)}),this.#t?e:e[0]}set val(e){e=typeof e==`string`?[e]:e,[...this.#e.querySelectorAll(`option`)].forEach(t=>{e.indexOf(t.value)>-1?t.selected=!0:t.selected=!1})}},fe=class extends Q{#e;constructor(e){super(e),this.#e=e}get val(){return this.#e.value||``}set val(e){this.#e.value=e}},pe=e=>{let t=[...(e||document).querySelectorAll(`input,select,textarea`)],n={};return t.forEach(e=>{let t=e.getAttribute(`name`);if(t){let r=!1;switch(Z(e)){case`input`:switch(e.type){case`radio`:r=new ce(e);break;case`checkbox`:r=new le(e);break;default:r=new ue(e)}break;case`select`:r=new de(e);break;case`textarea`:r=new fe(e);break}if(r){let i=r;k.add(e,t,i),Object.defineProperty(n,t,{enumerable:!0,configurable:!0,get:()=>i.val,set:e=>{i.val!==e&&(i.val=e)}})}}}),n};function $(e,t,n){if(!s())return;let r=pe(n),i=e;i[t]=Object.assign({},r),Y(e,t);let a=i[t];g(r,a),[...n.querySelectorAll(`input, textarea, select`)].forEach(e=>{e.addEventListener(`input`,()=>{a.notify()})})}function me(e){let t=Object.getPrototypeOf(e.prototype);Object.hasOwn(t,`formValues`)||Object.assign(t,{formValues:function(e,t){return $(this,t,e),this}})}export{a as BubbleController,k as DC,re as MC,O as McBase,I as autoload,x as bindTemplateEvents,g as copyGettersSetters,ee as debounce,d as deepEqual,L as defineCE,u as flattenObject,me as formValuePlugin,$ as formValues,R as getCE,e as getMcEventName,te as htmlToElements,v as injectCSS,J as isAlreadyObserved,s as isBrowser,S as isMcHost,c as isNativeObject,m as kebabToPascal,z as listCE,b as loadAssets,f as nameSpace,Y as observe,X as observePlugin,n as off,r as on,i as one,p as parse,h as pascalToKebab,y as processAssets,l as sortObject,o as trigger,t as trueEventName};
|
package/dist/observables.min.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
function e(e,t){let n=t.toLowerCase();return`on`+n in e?n:`_mc`+t[0].toUpperCase()+t.substring(1)}function t(n,r,i){if(n){if(typeof n==`string`){document.querySelectorAll(n).forEach(e=>t(e,r,i));return}n.removeEventListener(e(n,r),i)}}function n(t,r,i,a=!1){if(t){if(typeof t==`string`){document.querySelectorAll(t).forEach(e=>n(e,r,i));return}return t.addEventListener(e(t,r),i,{capture:!1,once:a}),i}}function r(e,t,i){if(e){if(typeof e==`string`){document.querySelectorAll(e).forEach(e=>r(e,t,i));return}return n(e,t,i,!0),i}}var i=class{stopped=!1;constructor(){}stop(){this.stopped=!0}};function a(t,n,r={},o=`l`,s){if(!t)return;if(typeof t==`string`){document.querySelectorAll(t).forEach(e=>a(e,n,r,o));return}let c=/^_mc/.test(n)?n:e(t,n),l=s||new i,u=new CustomEvent(c,{detail:{data:r,control:l},bubbles:!1});l.stopped||/l/.test(o)&&(t.dispatchEvent(u),l.stopped)||/[ud]/.test(o)&&queueMicrotask(()=>{if(o.indexOf(`u`)>-1&&a(t.parentElement,c,r,`lu`,l),o.indexOf(`d`)>-1)for(let e of t.children)a(e,c,r,`ld`)})}function o(){return typeof window<`u`&&window.document!==void 0}function s(e){return typeof e==`object`&&!!e&&e.constructor===Object}function c(e){let t={},n=Object.keys(e).sort();for(let r=0;r<n.length;r++){let i=n[r],a=e[i];s(a)?t[i]=c(a):t[i]=a}return t}function l(e,t=!0){let n={},r=e,i=Object.getOwnPropertyNames(e);for(let e=0;e<i.length;e++){let t=i[e],a=r[t];if(a instanceof Object){let e=l(a,!1);for(let r in e)n[t+`.`+r]=e[r]}else n[t]=a}return t?c(n):n}function u(e,t){if(e===t||e!==e&&t!==t)return!0;if(typeof e!=`object`||!e||typeof t!=`object`||!t||e.constructor!==t.constructor)return!1;if(e instanceof Date)return e.getTime()===t.getTime();if(e instanceof RegExp)return e.toString()===t.toString();if(Array.isArray(e)){let n=t;if(e.length!==n.length)return!1;for(let t=0;t<e.length;t++)if(!u(e[t],n[t]))return!1;return!0}let n=e,r=t,i=Object.keys(n);if(i.length!==Object.keys(r).length)return!1;for(let e=0;e<i.length;e++){let t=i[e];if(!Object.prototype.hasOwnProperty.call(r,t)||!u(n[t],r[t]))return!1}return!0}function d(e,t){let n=Object.getOwnPropertyDescriptors(e);for(let[e,r]of Object.entries(n))(`get`in r||`set`in r)&&Object.defineProperty(t,e,r)}var f=new WeakMap;function p(e,t){let n=f.get(e)??new Set;if(n.has(t))return e.adoptedStyleSheets[0];n.add(t),f.set(e,n);let r=new CSSStyleSheet;return r.replaceSync(t),e.adoptedStyleSheets.push(r),r}function m(e,t){let n=e.target,r=n.shadowRoot;!r&&Object.keys(t).some(e=>e.indexOf(`shadow`)===0)&&(r=n.attachShadow({mode:`open`})),Object.keys(t).forEach(i=>{switch(i){case`css`:p(document,t[i]);break;case`targetCss`:p(document,t[i]);break;case`shadowCss`:p(r,t[i]);break;case`shadowHtml`:r.innerHTML=t[i],g(r,e);break;case`targetHtml`:n.innerHTML=t[i],g(n,e);break}})}function h(e,t){let n=t=>{let n=t.match(/^([a-z]+)([A-Z][a-z]*)$/);return n?`./${e.replace(/-/g,`/`)}.${n[1]}.${n[2].toLowerCase()}`:`./${e.replace(/-/g,`/`)}.${t.toLowerCase()}`};return Promise.all(t.map(async e=>{let t=n(e);try{let n=await fetch(t);if(!n.ok)return`file not found: ${t}`;if(t.endsWith(`json`)){let r=await n.text();try{return JSON.parse(r)}catch{return console.error(`could not JSON.parse() asset '${e}' from ${t}:\n`,r),null}}return n.text()}catch{return`file not found: ${t}`}}))}function g(e,t){let r=[...e.querySelectorAll(`*`)];for(let e of r){if(!(e instanceof HTMLElement))continue;let r=[...e.attributes];for(let i of r){let r=i.name.toLowerCase();if(!(`on`+r in e))continue;let o=i.value.trim().split(`|`);if(o.length<2)continue;let[s,c,l]=o;e.removeAttribute(i.name);let u;if(l)try{u=JSON.parse(l)}catch{u=l}s===`this`||s===``?n(e,r,()=>t.trigger(c,u)):n(e,r,()=>a(s,c,u))}}}function _(e,t){return typeof HTMLElement<`u`&&e instanceof HTMLElement&&`_mc`in e&&(t===void 0||t in e._mc)}function v(e,t,n={}){let r=e;`_mc`in e||(r._mc=new T(e));let i=r._mc;return t.length&&!i[t]&&(i[t]=n,e instanceof HTMLElement&&!e.getAttribute(`data-mc`)&&e.setAttribute(`data-mc`,``)),r}function y(e,t){if(!t)return;let n=e._mc;n&&(n[t]&&delete n[t],!Object.keys(n).length&&e instanceof HTMLElement&&e.hasAttribute(`data-mc`)&&e.removeAttribute(`data-mc`))}function b(e){queueMicrotask(()=>{e.trigger(`Init`,null)})}function x(e){let t=e.target,r=Object.getPrototypeOf(e),i=e,a=Object.getOwnPropertyNames(r).filter(e=>/^(on[A-Z]|one[A-Z])/.test(e)&&typeof r[e]==`function`);for(let e of a){let r=/^one/.test(e);n(t,e.replace(/^one?/,``),t=>i[e](t),r)}}function S(e){return Array.from(e.querySelectorAll(`[data-mc]:not(:scope [data-mc] [data-mc])`)).filter(e=>e instanceof HTMLElement&&`_mc`in e).map(e=>e._mc)}function C(e,t){let n=e.parentElement?.closest(`[data-mc]`);for(;n instanceof HTMLElement;){if(`_mc`in n){let e=n._mc;if(t===void 0||t in e)return e}n=n.parentElement?.closest(`[data-mc]`)}return null}var w=class{_target;constructor(e){if(this._target=new WeakRef(e||{}),this instanceof T&&this.constructor!==T){x(this);let e=this.constructor.tag;(e===void 0||e.toUpperCase()===this.target.tagName)&&b(this)}}get target(){return this._target.deref()}},T=class e extends w{static tag;static _assets={};static assets=[];static _assetsPromise;static attributes={};constructor(t){super(t);let n=this.constructor;if(n===e)return;let r=this.target.tagName.toLowerCase();if(n.tag!==void 0&&r!==n.tag&&n.tag!==``){let t=document.createElement(n.tag);t.classList.add(r),n._originalTag=r,e.add(t,n.name,new n(t)),delete n._originalTag,r.includes(`-`)&&!this.target.isConnected?this.on(`connected`,()=>this.target.replaceWith(t)):this.target.replaceWith(t);return}let i=n.attributes;n.attributes&&Object.keys(n.attributes).forEach(e=>{this.target.setAttribute(e,i[e])});let a=this,o=n.assets.filter(e=>!n._assets[e]);if(Object.keys(n._assets).length&&m(this,n._assets),o.length?(n._assetsPromise||=h(n._originalTag||r,o).then(e=>{let t={};o.forEach((n,r)=>{t[n]=e[r]}),n._assets=Object.assign({},n._assets,t);for(let e of[`css`,`targetCss`])t[e]!==void 0&&delete n._assets[e];return n.assets=n.assets.filter(e=>e!==`css`&&e!==`targetCss`),t}),n._assetsPromise.then(e=>{m(this,e),a.trigger(`assets`,n._assets)})):[...Object.keys(n._assets)].length&&queueMicrotask(()=>a.trigger(`assets`,n._assets)),n.tag===``){this.target.remove();return}}getAssets(){return this.constructor._assets||{}}static add(e,t,n={}){return v(e,t,n)}static remove(e,t){y(e,t)}static get(e,t,n){if(!_(e))return;let r=e._mc[t];return r instanceof n?r:void 0}off(e,n){t(this.target,e,n)}on(e,t){return n(this.target,e,t)}one(e,t){return r(this.target,e,t)}trigger(e,t={},n=`l`,r){a(this.target,e,t,n,r)}ancestors(e){let t=[],n=C(this.target,e);for(;n;)t.push(n),n=C(n.target,e);return t}closest(e){return C(this.target,e)}children(e){let t=S(this.target);return e===void 0?t:t.filter(t=>e in t)}descendants(e){return Array.from(this.target.querySelectorAll(`[data-mc]`)).filter(e=>e instanceof HTMLElement&&`_mc`in e).map(e=>e._mc).filter(t=>e===void 0||e in t)}};function E(e){let t=new Set,n=/\{[^\{\}]*\}/g;return(e.getAttributeNames?e.getAttributeNames():[]).filter(t=>e.getAttribute(t)?.match(n)).forEach(r=>{new Set(e.getAttribute(r)?.match(n)).forEach(e=>t.add(e.replace(/[\{\}]/g,``)))}),[...e.childNodes].filter(e=>e.nodeType===3&&(e.nodeValue||``).match(n)).forEach(e=>{(e?.nodeValue||``).match(n).forEach(e=>t.add(e.replace(/[\{\}]/g,``)))}),[...t]}var D=[`INPUT`,`SELECT`,`TEXTAREA`],O=class extends T{data={};oldDisplay=``;constructor(e){super(e),E(e).forEach(e=>this.data[e]=``),I(this),this.#e()}#e(){let e=this.target,t=!1;(e.getAttributeNames?e.getAttributeNames():[]).filter(t=>e.getAttribute(t)?.match(/\{[^\{\}]*\}/g)).forEach(t=>{let n=new Set(e.getAttribute(t)?.match(/\{[^\{\}]*\}/g)),r=e.getAttribute(t)??``;this.data.subscribe((r=>i=>{let a=r;n.forEach(e=>{a=a.replace(e,String(i[e.replace(/[\{\}]/g,``)]))}),e.setAttribute(t,a)})(r))}),[...e.childNodes].filter(e=>e.nodeType===3&&(e.nodeValue||``).match(/\{[^\{\}]*\}/g)).forEach(n=>{t=!0;let r=n.nodeValue??``,i=new Set(r.match(/\{[^\{\}]*\}/g));this.data.subscribe((t=>r=>{let a=t;i.forEach(e=>{a=a.replace(e,String(r[e.replace(/[\{\}]/g,``)]))}),this.oldDisplay?e.style=this.oldDisplay:e.removeAttribute(`style`),delete this.oldDisplay,n.nodeValue=a})(r)),this.oldDisplay=e.getAttribute(`style`)||``,t&&!D.includes(e.tagName)&&e.tagName!==`FIELDSET`&&(e.style.display=`none`)})}onData(e){let t={};Object.keys(e.detail.data).forEach(n=>{this.data.hasOwnProperty(n)&&(t[n]=e.detail.data[n])}),JSON.stringify(t)!==JSON.stringify(this.data)&&Object.assign(this.data,t)}};function k(e){return[e,...e.querySelectorAll(`*`)].filter(e=>!!E(e).length).filter(e=>e?.tagName!==`STYLE`).reverse()}function A(e){k(e).forEach(e=>{e?._mc?._placeholders||T.add(e,`_placeholders`,new O(e))})}function j(e){return typeof e==`object`&&!!e}var M={};function N(e){let t=e.constructor,n=t.name,r=class extends t{#e=!0;#t=[];constructor(e){super(e);let t=this.constructor;t.callbacks=[],j(e)&&Object.getOwnPropertyNames(e).forEach(t=>{this[t]=e[t]})}get callbacks(){return this.#t}set callbacks(e){this.#t=e}[Symbol.toPrimitive](e){let t=this.valueOf();return e===`string`?String(t):e===`number`?Number(t):t}subscribe(e){return this.#t.push(e),this}unsubscribe(e){return this.#t=this.#t.filter(t=>t!==e),this}bind(e){if(o()){if(j(this.valueOf())){A(e);let t=[e,...e.querySelectorAll(`[data-mc]`)].filter(e=>!!e?._mc?._placeholders);this.#t.push(function(e){let n=l(e);t.forEach(e=>{e&&a(e,`data`,n)})}),this.notify()}else console.warn(`IGNORED - cannot bind a non-Object to the dom, IS:`,typeof this.valueOf(),this);return this}}notify(e){let t=j(this.valueOf())&&!(this.valueOf()instanceof Array)?structuredClone(Object.assign({},this)):this.valueOf();return e!==void 0&&(this.#e=e),this.#e&&this.#t.forEach(e=>{e(t)}),this}};return M[n]=r,r}function P(e){return M[e.constructor.name]||N(e)}function F(e){return(typeof e==`object`||typeof e==`function`)&&e!==null&&`subscribe`in e}function I(e,t){let n=e;return(t?[t]:[...Object.getOwnPropertyNames(e)]).forEach(t=>{let r=n[t];if(Object.prototype.hasOwnProperty.call(e,t)&&typeof r!=`function`&&!F(r)){if(t[0]===`_`||r===void 0)return;let i=r,a=new(P(i))(i),o=function(){queueMicrotask(function(){a.notify()})};Object.defineProperty(e,t,{enumerable:!0,get(){if(j(a.valueOf())){let e=structuredClone(Object.assign({},a));queueMicrotask(function(){u(structuredClone(Object.assign({},a)),e)||o()})}return a},set(e){if(typeof e==typeof a.valueOf())if(j(a.valueOf())&&!(a.valueOf()instanceof Array))F(a)||(a=new(P(e))(structuredClone(Object.assign({},e))),d(e,a)),Object.assign(a,e),a.notify();else{let t=a.valueOf(),n=a.callbacks;e!==t&&(a=new(P(e))(e),a.callbacks=n,o())}else console.warn(`IGNORED - cannot change observable types, IS:`,typeof a.valueOf(),a,`- CANNOT BECOME:`,typeof e)}}),n[t]=i}}),e}function L(e){let t=Object.getPrototypeOf(e.prototype);function n(e,t){let n=e[t];F(n)||I(e,t)}Object.hasOwn(t,`notify`)||Object.assign(t,{notify:function(e){return n(this,e),this[e].notify(),this},subscribe:function(e,t){return n(this,e),this[e].subscribe(t),this},bind:function(e,t){return n(this,e),this[e].bind(t),this}})}export{F as isAlreadyObserved,I as observe,L as observePlugin};
|
|
1
|
+
function e(e,t){let n=t.toLowerCase();return`on`+n in e?n:`_mc`+t[0].toUpperCase()+t.substring(1)}function t(n,r,i){if(n){if(typeof n==`string`){document.querySelectorAll(n).forEach(e=>t(e,r,i));return}n.removeEventListener(e(n,r),i)}}function n(t,r,i,a=!1){if(t){if(typeof t==`string`){document.querySelectorAll(t).forEach(e=>n(e,r,i));return}return t.addEventListener(e(t,r),i,{capture:!1,once:a}),i}}function r(e,t,i){if(e){if(typeof e==`string`){document.querySelectorAll(e).forEach(e=>r(e,t,i));return}return n(e,t,i,!0),i}}var i=class{stopped=!1;constructor(){}stop(){this.stopped=!0}};function a(t,n,r={},o=`l`,s){if(!t)return;if(typeof t==`string`){document.querySelectorAll(t).forEach(e=>a(e,n,r,o));return}let c=/^_mc/.test(n)?n:e(t,n),l=s||new i,u=new CustomEvent(c,{detail:{data:r,control:l},bubbles:!1});l.stopped||/l/.test(o)&&(t.dispatchEvent(u),l.stopped)||/[ud]/.test(o)&&queueMicrotask(()=>{if(o.indexOf(`u`)>-1&&a(t.parentElement,c,r,`lu`,l),o.indexOf(`d`)>-1)for(let e of t.children)a(e,c,r,`ld`)})}function o(){return typeof window<`u`&&window.document!==void 0}function s(e){return typeof e==`object`&&!!e&&e.constructor===Object}function c(e){let t={},n=Object.keys(e).sort();for(let r=0;r<n.length;r++){let i=n[r],a=e[i];s(a)?t[i]=c(a):t[i]=a}return t}function l(e,t=!0){let n={},r=e,i=Object.getOwnPropertyNames(e);for(let e=0;e<i.length;e++){let t=i[e],a=r[t];if(a instanceof Object){let e=l(a,!1);for(let r in e)n[t+`.`+r]=e[r]}else n[t]=a}return t?c(n):n}function u(e,t){if(e===t||e!==e&&t!==t)return!0;if(typeof e!=`object`||!e||typeof t!=`object`||!t||e.constructor!==t.constructor)return!1;if(e instanceof Date)return e.getTime()===t.getTime();if(e instanceof RegExp)return e.toString()===t.toString();if(Array.isArray(e)){let n=t;if(e.length!==n.length)return!1;for(let t=0;t<e.length;t++)if(!u(e[t],n[t]))return!1;return!0}let n=e,r=t,i=Object.keys(n);if(i.length!==Object.keys(r).length)return!1;for(let e=0;e<i.length;e++){let t=i[e];if(!Object.prototype.hasOwnProperty.call(r,t)||!u(n[t],r[t]))return!1}return!0}function d(e){return e.replace(/[A-Z]/g,(e,t)=>(t?`-`:``)+e.toLowerCase())}function f(e,t){let n=Object.getOwnPropertyDescriptors(e);for(let[e,r]of Object.entries(n))(`get`in r||`set`in r)&&Object.defineProperty(t,e,r)}var p=new WeakMap;function m(e,t){let n=p.get(e)??new Set;if(n.has(t))return e.adoptedStyleSheets[0];n.add(t),p.set(e,n);let r=new CSSStyleSheet;return r.replaceSync(t),e.adoptedStyleSheets.push(r),r}function h(e,t){let n=e.target,r=n.shadowRoot;!r&&Object.keys(t).some(e=>e.indexOf(`shadow`)===0)&&(r=n.attachShadow({mode:`open`})),Object.keys(t).forEach(i=>{switch(i){case`css`:m(document,t[i]);break;case`targetCss`:m(document,t[i]);break;case`shadowCss`:m(r,t[i]);break;case`shadowHtml`:r.innerHTML=t[i],_(r,e);break;case`targetHtml`:n.innerHTML=t[i],_(n,e);break}})}function g(e,t){let n=t=>{let n=t.match(/^([a-z]+)([A-Z][a-z]*)$/);return n?`./${e.replace(/-/g,`/`)}.${n[1]}.${n[2].toLowerCase()}`:`./${e.replace(/-/g,`/`)}.${t.toLowerCase()}`};return Promise.all(t.map(async e=>{let t=n(e);try{let n=await fetch(t);if(!n.ok)return`file not found: ${t}`;if(t.endsWith(`json`)){let r=await n.text();try{return JSON.parse(r)}catch{return console.error(`could not JSON.parse() asset '${e}' from ${t}:\n`,r),null}}return n.text()}catch{return`file not found: ${t}`}}))}function _(e,t){let r=[...e.querySelectorAll(`*`)];for(let e of r){if(!(e instanceof HTMLElement))continue;let r=[...e.attributes];for(let i of r){let r=i.name.toLowerCase();if(!(`on`+r in e))continue;let o=i.value.trim().split(`|`);if(o.length<2)continue;let[s,c,l]=o;e.removeAttribute(i.name);let u;if(l)try{u=JSON.parse(l)}catch{u=l}s===`this`||s===``?n(e,r,()=>t.trigger(c,u)):n(e,r,()=>a(s,c,u))}}}function v(e,t){return typeof HTMLElement<`u`&&e instanceof HTMLElement&&`_mc`in e&&(t===void 0||t in e._mc)}function y(e,t,n={}){let r=e;`_mc`in e||(r._mc=new E(e));let i=r._mc;return t.length&&!i[t]&&(i[t]=n,e instanceof HTMLElement&&!e.getAttribute(`data-mc`)&&e.setAttribute(`data-mc`,``)),r}function b(e,t){if(!t)return;let n=e._mc;n&&(n[t]&&delete n[t],!Object.keys(n).length&&e instanceof HTMLElement&&e.hasAttribute(`data-mc`)&&e.removeAttribute(`data-mc`))}function x(e){queueMicrotask(()=>{e.trigger(`Init`,null)})}function S(e){let t=e.target,r=Object.getPrototypeOf(e),i=e,a=Object.getOwnPropertyNames(r).filter(e=>/^(on[A-Z]|one[A-Z])/.test(e)&&typeof r[e]==`function`);for(let e of a){let r=/^one/.test(e);n(t,e.replace(/^one?/,``),t=>i[e](t),r)}}function C(e){return Array.from(e.querySelectorAll(`[data-mc]:not(:scope [data-mc] [data-mc])`)).filter(e=>e instanceof HTMLElement&&`_mc`in e).map(e=>e._mc)}function w(e,t){let n=e.parentElement?.closest(`[data-mc]`);for(;n instanceof HTMLElement;){if(`_mc`in n){let e=n._mc;if(t===void 0||t in e)return e}n=n.parentElement?.closest(`[data-mc]`)}return null}var T=class{_target;static _assets={};static assets=[];static _assetsPromise;constructor(e){this._target=new WeakRef(e||{});let t=this.constructor;this instanceof E&&this.constructor!==E&&S(this);let n=(t.assets??[]).filter(e=>!t._assets[e]);n.length&&!t._assetsPromise&&(t._assetsPromise=g(t._originalTag||(this instanceof E?this.target.tagName.toLowerCase():d(t.name)),n).then(e=>{let r={};return n.forEach((t,n)=>{r[t]=e[n]}),t._assets=Object.assign({},t._assets,r),r}))}get target(){return this._target.deref()}get assets(){return this.constructor._assets||{}}},E=class e extends T{static tag;static attributes={};constructor(t){super(t);let n=this.constructor;if(n===e)return;let r=this.target.tagName.toLowerCase();if(n.tag!==void 0&&r!==n.tag&&n.tag!==``){let t=document.createElement(n.tag);t.classList.add(r),n._originalTag=r,e.add(t,n.name,new n(t)),delete n._originalTag,r.includes(`-`)&&!this.target.isConnected?this.on(`connected`,()=>this.target.replaceWith(t)):this.target.replaceWith(t);return}let i=n.attributes;if(n.attributes&&Object.keys(n.attributes).forEach(e=>{this.target.setAttribute(e,i[e])}),Object.keys(n._assets).length){h(this,n._assets);for(let e of[`css`,`targetCss`])delete n._assets[e];n.assets=n.assets.filter(e=>e!==`css`&&e!==`targetCss`)}if(n._assetsPromise?n._assetsPromise.then(e=>{h(this,e);for(let e of[`css`,`targetCss`])delete n._assets[e];n.assets=n.assets.filter(e=>e!==`css`&&e!==`targetCss`),x(this)}):x(this),n.tag===``){this.target.remove();return}}static add(e,t,n={}){return y(e,t,n)}static remove(e,t){b(e,t)}static get(e,t,n){if(!v(e))return;let r=e._mc[t];return r instanceof n?r:void 0}off(e,n){t(this.target,e,n)}on(e,t){return n(this.target,e,t)}one(e,t){return r(this.target,e,t)}trigger(e,t={},n=`l`,r){a(this.target,e,t,n,r)}ancestors(e){let t=[],n=w(this.target,e);for(;n;)t.push(n),n=w(n.target,e);return t}closest(e){return w(this.target,e)}children(e){let t=C(this.target);return e===void 0?t:t.filter(t=>e in t)}descendants(e){return Array.from(this.target.querySelectorAll(`[data-mc]`)).filter(e=>e instanceof HTMLElement&&`_mc`in e).map(e=>e._mc).filter(t=>e===void 0||e in t)}};function D(e){let t=new Set,n=/\{[^\{\}]*\}/g;return(e.getAttributeNames?e.getAttributeNames():[]).filter(t=>e.getAttribute(t)?.match(n)).forEach(r=>{new Set(e.getAttribute(r)?.match(n)).forEach(e=>t.add(e.replace(/[\{\}]/g,``)))}),[...e.childNodes].filter(e=>e.nodeType===3&&(e.nodeValue||``).match(n)).forEach(e=>{(e?.nodeValue||``).match(n).forEach(e=>t.add(e.replace(/[\{\}]/g,``)))}),[...t]}var O=[`INPUT`,`SELECT`,`TEXTAREA`],k=class extends E{data={};oldDisplay=``;constructor(e){super(e),D(e).forEach(e=>this.data[e]=``),L(this),this.#e()}#e(){let e=this.target,t=!1;(e.getAttributeNames?e.getAttributeNames():[]).filter(t=>e.getAttribute(t)?.match(/\{[^\{\}]*\}/g)).forEach(t=>{let n=new Set(e.getAttribute(t)?.match(/\{[^\{\}]*\}/g)),r=e.getAttribute(t)??``;this.data.subscribe((r=>i=>{let a=r;n.forEach(e=>{a=a.replace(e,String(i[e.replace(/[\{\}]/g,``)]))}),e.setAttribute(t,a)})(r))}),[...e.childNodes].filter(e=>e.nodeType===3&&(e.nodeValue||``).match(/\{[^\{\}]*\}/g)).forEach(n=>{t=!0;let r=n.nodeValue??``,i=new Set(r.match(/\{[^\{\}]*\}/g));this.data.subscribe((t=>r=>{let a=t;i.forEach(e=>{a=a.replace(e,String(r[e.replace(/[\{\}]/g,``)]))}),this.oldDisplay?e.style=this.oldDisplay:e.removeAttribute(`style`),delete this.oldDisplay,n.nodeValue=a})(r)),this.oldDisplay=e.getAttribute(`style`)||``,t&&!O.includes(e.tagName)&&e.tagName!==`FIELDSET`&&(e.style.display=`none`)})}onData(e){let t={};Object.keys(e.detail.data).forEach(n=>{this.data.hasOwnProperty(n)&&(t[n]=e.detail.data[n])}),JSON.stringify(t)!==JSON.stringify(this.data)&&Object.assign(this.data,t)}};function A(e){return[e,...e.querySelectorAll(`*`)].filter(e=>!!D(e).length).filter(e=>e?.tagName!==`STYLE`).reverse()}function j(e){A(e).forEach(e=>{e?._mc?._placeholders||E.add(e,`_placeholders`,new k(e))})}function M(e){return typeof e==`object`&&!!e}var N={};function P(e){let t=e.constructor,n=t.name,r=class extends t{#e=!0;#t=[];constructor(e){super(e);let t=this.constructor;t.callbacks=[],M(e)&&Object.getOwnPropertyNames(e).forEach(t=>{this[t]=e[t]})}get callbacks(){return this.#t}set callbacks(e){this.#t=e}[Symbol.toPrimitive](e){let t=this.valueOf();return e===`string`?String(t):e===`number`?Number(t):t}subscribe(e){return this.#t.push(e),this}unsubscribe(e){return this.#t=this.#t.filter(t=>t!==e),this}bind(e){if(o()){if(M(this.valueOf())){j(e);let t=[e,...e.querySelectorAll(`[data-mc]`)].filter(e=>!!e?._mc?._placeholders);this.#t.push(function(e){let n=l(e);t.forEach(e=>{e&&a(e,`data`,n)})}),this.notify()}else console.warn(`IGNORED - cannot bind a non-Object to the dom, IS:`,typeof this.valueOf(),this);return this}}notify(e){let t=M(this.valueOf())&&!(this.valueOf()instanceof Array)?structuredClone(Object.assign({},this)):this.valueOf();return e!==void 0&&(this.#e=e),this.#e&&this.#t.forEach(e=>{e(t)}),this}};return N[n]=r,r}function F(e){return N[e.constructor.name]||P(e)}function I(e){return(typeof e==`object`||typeof e==`function`)&&e!==null&&`subscribe`in e}function L(e,t){let n=e;return(t?[t]:[...Object.getOwnPropertyNames(e)]).forEach(t=>{let r=n[t];if(Object.prototype.hasOwnProperty.call(e,t)&&typeof r!=`function`&&!I(r)){if(t[0]===`_`||r===void 0)return;let i=r,a=new(F(i))(i),o=function(){queueMicrotask(function(){a.notify()})};Object.defineProperty(e,t,{enumerable:!0,get(){if(M(a.valueOf())){let e=structuredClone(Object.assign({},a));queueMicrotask(function(){u(structuredClone(Object.assign({},a)),e)||o()})}return a},set(e){if(typeof e==typeof a.valueOf())if(M(a.valueOf())&&!(a.valueOf()instanceof Array))I(a)||(a=new(F(e))(structuredClone(Object.assign({},e))),f(e,a)),Object.assign(a,e),a.notify();else{let t=a.valueOf(),n=a.callbacks;e!==t&&(a=new(F(e))(e),a.callbacks=n,o())}else console.warn(`IGNORED - cannot change observable types, IS:`,typeof a.valueOf(),a,`- CANNOT BECOME:`,typeof e)}}),n[t]=i}}),e}function R(e){let t=Object.getPrototypeOf(e.prototype);function n(e,t){let n=e[t];I(n)||L(e,t)}Object.hasOwn(t,`notify`)||Object.assign(t,{notify:function(e){return n(this,e),this[e].notify(),this},subscribe:function(e,t){return n(this,e),this[e].subscribe(t),this},bind:function(e,t){return n(this,e),this[e].bind(t),this}})}export{I as isAlreadyObserved,L as observe,R as observePlugin};
|
|
@@ -25,7 +25,7 @@ formValuePlugin(DC);
|
|
|
25
25
|
class CheckoutForm extends DC {
|
|
26
26
|
static assets = ['targetHtml'];
|
|
27
27
|
|
|
28
|
-
|
|
28
|
+
oneInit() {
|
|
29
29
|
this
|
|
30
30
|
.formValues(this.target, 'formData')
|
|
31
31
|
.subscribe('formData', (data) => console.log(data))
|
|
@@ -83,7 +83,7 @@ import { DC, defineCE, formValues } from '@twobirds/microcomponents';
|
|
|
83
83
|
class MyForm extends DC {
|
|
84
84
|
static assets = ['targetHtml'];
|
|
85
85
|
|
|
86
|
-
|
|
86
|
+
oneInit() {
|
|
87
87
|
formValues(this, 'formData', this.target);
|
|
88
88
|
this.formData.subscribe((data) => console.log('form changed:', data));
|
|
89
89
|
}
|
|
@@ -114,7 +114,7 @@ formValuePlugin(DC);
|
|
|
114
114
|
class CheckoutForm extends DC {
|
|
115
115
|
static assets = ['targetHtml'];
|
|
116
116
|
|
|
117
|
-
|
|
117
|
+
oneInit() {
|
|
118
118
|
this
|
|
119
119
|
.formValues(this.target, 'formData')
|
|
120
120
|
.subscribe('formData', (data) => console.log(data))
|