-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdiff.diff
More file actions
598 lines (553 loc) · 17.9 KB
/
Copy pathdiff.diff
File metadata and controls
598 lines (553 loc) · 17.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
diff --git a/esbuild.config.cjs b/esbuild.config.cjs
index e77748b..6ae1116 100644
--- a/esbuild.config.cjs
+++ b/esbuild.config.cjs
@@ -1,11 +1,17 @@
const { build } = require("esbuild");
+const { immer } = require("zustand/middleware/immer");
// Common build configuration
const commonConfig = {
bundle: true,
minify: true,
entryPoints: ["src/index.ts"],
- external: ["zustand/vanilla", "zustand/middleware"],
+ external: [
+ "zustand/vanilla",
+ "zustand/middleware",
+ "zustand/middleware/immer",
+ "immer",
+ ],
};
// CJS build
@@ -21,5 +27,3 @@ build({
format: "esm",
outdir: "dist/esm",
}).catch(() => process.exit(1));
-
-
diff --git a/package-lock.json b/package-lock.json
index e4b4277..cbca93a 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,14 +1,15 @@
{
"name": "zef-components",
- "version": "1.0.1",
+ "version": "2.0.5",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "zef-components",
- "version": "1.0.1",
+ "version": "2.0.5",
"license": "ISC",
"dependencies": {
+ "immer": "^10.1.3",
"zustand": "^5.0.8"
},
"devDependencies": {
@@ -499,6 +500,16 @@
"@esbuild/win32-x64": "0.25.9"
}
},
+ "node_modules/immer": {
+ "version": "10.1.3",
+ "resolved": "https://registry.npmjs.org/immer/-/immer-10.1.3.tgz",
+ "integrity": "sha512-tmjF/k8QDKydUlm3mZU+tjM6zeq9/fFpPqH9SzWmBnVVKsPBg/V66qsMwb3/Bo90cgUN+ghdVBess+hPsxUyRw==",
+ "license": "MIT",
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/immer"
+ }
+ },
"node_modules/zustand": {
"version": "5.0.8",
"resolved": "https://registry.npmjs.org/zustand/-/zustand-5.0.8.tgz",
diff --git a/package.json b/package.json
index bc6729b..064e62a 100644
--- a/package.json
+++ b/package.json
@@ -1,10 +1,10 @@
{
"name": "zef-components",
- "version": "2.0.5",
+ "version": "2.0.6",
"description": "A lightweight library for creating reactive web components with state management, declarative templates, and seamless store integration.",
"module": "dist/esm/index.js",
"main": "dist/cjs/index.js",
- "source" : "src/index.ts",
+ "source": "src/index.ts",
"types": "dist/types/index.d.ts",
"scripts": {
"build": "node esbuild.config.cjs && tsc"
@@ -31,7 +31,11 @@
"esbuild": "^0.25.9"
},
"dependencies": {
+ "immer": "^10.1.3",
"zustand": "^5.0.8"
},
- "files": ["dist" , "src"]
+ "files": [
+ "dist",
+ "src"
+ ]
}
diff --git a/releases/zef-components-2.0.6.tgz b/releases/zef-components-2.0.6.tgz
new file mode 100644
index 0000000..a9e881c
Binary files /dev/null and b/releases/zef-components-2.0.6.tgz differ
diff --git a/src/index.ts b/src/index.ts
index c599499..16926a1 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -1,15 +1,18 @@
import { createStore } from "zustand/vanilla";
import { subscribeWithSelector } from "zustand/middleware";
+import { immer } from "zustand/middleware/immer";
import {
clearStoreListeners,
createReactiveProxy,
initializeEventListener,
+ initializePropsListeners,
initializeStoreListeners,
reattachEventListeners,
registerForLoop,
- registerRerenders as registerReRenders,
+ registerReRenders,
renderForLoop,
+ updateProps,
} from "./methods";
import {
FactoryOption,
@@ -20,6 +23,9 @@ import {
EventHandle,
GlobalStore,
StateType,
+ StoreUpdater,
+ PropListenerRecord,
+ BoundState,
} from "./types";
import {
maybeCall,
@@ -29,18 +35,24 @@ import {
export const globalStore = createStore<GlobalStore>(
//@ts-expect-error zustand middleware
- subscribeWithSelector(() => ({}))
+ subscribeWithSelector(immer(() => ({})))
);
-export default function Factory<T extends StateType>(
- name: string,
- html: string,
- options?: FactoryOption<T>
-) {
+export default function Factory<
+ T extends StateType,
+ K extends BoundState,
+ L extends BoundState
+>(name: string, html: string, options?: FactoryOption<T, K, L>) {
+ const observedAttributes: string[] = [];
+ if (options?.observedAttributes) {
+ observedAttributes.push(...options.observedAttributes);
+ }
+ if (options?.props) {
+ observedAttributes.push(...Object.values(options.props).map(prop => prop.replace("json::", "")));
+ }
class Component extends HTMLElement {
- static observedAttributes = options?.observedAttributes ?? [];
-
- state: T;
+ static observedAttributes = observedAttributes;
+ state: T & Record<keyof K, () => any> & Record<keyof L, () => string>;
_globalStore = globalStore;
_value: any;
get value() {
@@ -61,6 +73,7 @@ export default function Factory<T extends StateType>(
_dynamicFieldRecord: DynamicFieldsRecord = {};
_eventListenerRecord: EventListenerRecord = {};
_storeListenerRecord: [() => void] = [() => {}];
+ _propsListenerRecord: PropListenerRecord = {};
_valueUpdater: any;
constructor() {
@@ -68,12 +81,16 @@ export default function Factory<T extends StateType>(
const initialState = maybeCall(options?.state, this) ?? {};
+ initializePropsListeners.apply(this, [options?.props, initialState]);
+
initializeStoreListeners.apply(this, [
options?.storeListener,
initialState,
]);
- this.state = createReactiveProxy.apply(this, [initialState]) as T;
+ this.state = createReactiveProxy.apply(this, [initialState]) as T &
+ Record<keyof K, any> &
+ Record<keyof L, any>;
this._valueUpdater = options?.value ?? null;
this._value = maybeCall(this._valueUpdater, this);
@@ -100,11 +117,13 @@ export default function Factory<T extends StateType>(
);
initializeEventListener.apply(this, [options?.eventListener ?? {}]);
-
+ //@ts-expect-error user provided method
options?.onMount?.apply(this);
}
attributeChangedCallback(name: string, oldValue: string, newValue: string) {
+ updateProps.apply(this, [name, oldValue, newValue]);
+ //@ts-expect-error user provided method
options?.onAttributeChanged?.apply(this, [name, oldValue, newValue]);
}
@@ -138,20 +157,22 @@ export default function Factory<T extends StateType>(
}
reattachEventListeners.apply(this, [id]);
}
+ //@ts-expect-error user provided method
options?.onRender?.apply(this, [pathname]);
}
disconnectedCallback() {
clearStoreListeners.apply(this);
+ //@ts-expect-error user provided method
options?.onUnmount?.apply(this);
}
/* magic method */
- get $store() {
+ $getStore() {
return this._globalStore.getState();
}
- set $store(val: any) {
- this._globalStore.setState(val);
+ $setStore(updater: StoreUpdater) {
+ this._globalStore.setState(updater);
}
$(css: string) {
@@ -178,9 +199,10 @@ export default function Factory<T extends StateType>(
$$off(css: string, event: string) {
if (!this._eventListenerRecord[css]) return;
+
const toRemove = this._eventListenerRecord[css].filter(
- ({ event: eventName }) => {
- return eventName === event;
+ ({ event: recordedEvent }) => {
+ return recordedEvent === event;
}
);
for (const { event, handler, options } of toRemove) {
@@ -188,9 +210,10 @@ export default function Factory<T extends StateType>(
target.removeEventListener(event, handler, options);
});
}
+
this._eventListenerRecord[css] = this._eventListenerRecord[css].filter(
- (handle) => {
- return !toRemove.includes(handle);
+ ({ event: recordedEvent }) => {
+ return recordedEvent != event;
}
);
}
diff --git a/src/methods.ts b/src/methods.ts
index 3379e56..1299c58 100644
--- a/src/methods.ts
+++ b/src/methods.ts
@@ -1,6 +1,11 @@
/* External methods bound to the main Component.*/
-import { EventListenerRecord, StateType, WebComponent } from "./types";
+import {
+ EventListenerRecord,
+ GlobalStore,
+ StateType,
+ WebComponent,
+} from "./types";
import {
maybeCall,
FOR_LOOP_REGEX,
@@ -8,10 +13,11 @@ import {
parseDocumentFragment,
targetFromPath,
TERNARY_REGEX,
+ parseJSON,
} from "./utils";
export function createReactiveProxy(
- this: WebComponent<StateType>,
+ this: WebComponent,
initialState: StateType,
previousPath: string = ""
) {
@@ -47,10 +53,49 @@ export function createReactiveProxy(
//@ts-expect-error yeah yeah yeah proxy magic
return new Proxy(initialState, handler);
}
+export function initializePropsListeners(
+ this: WebComponent,
+ propsListener: GlobalStore | undefined,
+ initialState: StateType
+) {
+ if (!propsListener) return;
+
+ for (const key in propsListener) {
+ const propName = propsListener[key];
+
+ const attrValue = this.getAttribute(propName);
+ if (propName.startsWith("json::")) {
+ initialState[key] = () => parseJSON(attrValue);
+
+ const realPropName = propName.replace("json::", "");
+ this._propsListenerRecord[realPropName] = { type: "json", key };
+ continue;
+ }
+
+ initialState[key] = () => attrValue;
+ this._propsListenerRecord[propName] = { type: "string", key };
+ }
+}
+
+export function updateProps(
+ this: WebComponent,
+ name: string,
+ _: string,
+ newValue: string
+) {
+ if (!(name in this._propsListenerRecord)) return;
+ const { type, key } = this._propsListenerRecord[name];
+ if (type == "json") {
+ const parsed = parseJSON(newValue);
+ this.state[key] = () => parsed;
+ } else {
+ this.state[key] = () => newValue;
+ }
+}
export function initializeStoreListeners(
- this: WebComponent<StateType>,
- storeListener: Record<string, string> | undefined,
+ this: WebComponent,
+ storeListener: StateType | undefined,
initialState: StateType
) {
if (!storeListener) return;
@@ -64,7 +109,7 @@ export function initializeStoreListeners(
//@ts-expect-error zustand middleware
(currentVal: any) => {
if (currentVal !== this.state[key]) {
- this.state[key] = currentVal;
+ this.state[key] = () => currentVal;
this.reRenderProperty(key);
}
}
@@ -73,11 +118,11 @@ export function initializeStoreListeners(
}
}
-export function clearStoreListeners(this: WebComponent<StateType>) {
+export function clearStoreListeners(this: WebComponent) {
this._storeListenerRecord.forEach((unsub) => unsub());
}
-export function registerRerenders(this: WebComponent<StateType>) {
+export function registerReRenders(this: WebComponent) {
this.$$("[re-render]").forEach((element) => {
const reRenderAttr = element.getAttribute("re-render") ?? "";
@@ -99,32 +144,18 @@ export function registerRerenders(this: WebComponent<StateType>) {
}
export function initializeEventListener(
- this: WebComponent<StateType>,
+ this: WebComponent,
eventListeners: EventListenerRecord
) {
for (let cssSelector in eventListeners) {
- for (let { event, handler, options } of eventListeners[cssSelector]) {
- const boundHandler = handler.bind(this);
- this.root.querySelectorAll(cssSelector).forEach((element) => {
- element.addEventListener(event, boundHandler, options);
- });
- if (!this._eventListenerRecord[cssSelector]) {
- this._eventListenerRecord[cssSelector] = [];
- }
- this._eventListenerRecord[cssSelector].push({
- event,
- handler: boundHandler,
- options,
- });
+ for (let eventHandle of eventListeners[cssSelector]) {
+ this.$$on(cssSelector, eventHandle);
}
}
}
-export function reattachEventListeners(
- this: WebComponent<StateType>,
- id: string
-) {
- const target = this.root.querySelector(`[internal-id=${id}]`);
+export function reattachEventListeners(this: WebComponent, id: string) {
+ const target = this.$(`[internal-id=${id}]`);
if (!target) return;
for (let cssSelector in this._eventListenerRecord) {
for (let { event, handler, options } of this._eventListenerRecord[
@@ -140,7 +171,7 @@ export function reattachEventListeners(
}
}
-export function registerForLoop(this: WebComponent<StateType>) {
+export function registerForLoop(this: WebComponent) {
this.$$("[for-loop]").forEach((template) => {
const forAttr = template.getAttribute("for-loop");
const match = forAttr?.match(FOR_LOOP_REGEX);
@@ -164,7 +195,7 @@ export function registerForLoop(this: WebComponent<StateType>) {
}
export function renderForLoop(
- this: WebComponent<StateType>,
+ this: WebComponent,
raw: string,
container: Element
) {
diff --git a/src/types.ts b/src/types.ts
index 271724b..829a79f 100644
--- a/src/types.ts
+++ b/src/types.ts
@@ -3,55 +3,71 @@ import { StoreApi } from "zustand/vanilla";
export type StateType = {
[key: string]: any;
};
+export type BoundState = Record<string,string>
export type GlobalStore = {
[key: string]: any;
};
-export interface FactoryOption<T extends StateType> {
+export interface FactoryOption<
+ T extends StateType,
+ K extends BoundState,
+ L extends BoundState
+> {
observedAttributes?: string[];
- value?: (this: WebComponent<T>) => any;
- state?: T | ((this: WebComponent<T>) => T);
+ value?: (this: WebComponent<T, K, L>) => any;
+ state?: T | ((this: WebComponent<T, K, L>) => T);
+ props?: L;
- onMount?: (this: WebComponent<T>) => void;
- onUnmount?: (this: WebComponent<T>) => void;
- onRender?: (this: WebComponent<T>, path: string) => void;
+ onMount?: (this: WebComponent<T, K>) => void;
+ onUnmount?: (this: WebComponent<T, K, L>) => void;
+ onRender?: (this: WebComponent<T, K, L>, path: string) => void;
onAttributeChanged?: (
- this: WebComponent<T>,
+ this: WebComponent<T, K, L>,
name: string,
oldValue: string,
newValue: string
) => void;
eventListener?: EventListenerRecord;
- storeListener?: Record<Exclude<string, keyof T>, string>;
+ storeListener?: K;
noShadowRoot?: boolean;
}
-export interface WebComponent<T extends StateType> extends HTMLElement {
+export type StoreUpdater<R = void> = (
+ arg: GlobalStore
+) => R extends void ? void : never;
+
+export interface WebComponent<
+ T extends StateType = StateType,
+ K extends BoundState = BoundState,
+ L extends BoundState = BoundState
+> extends HTMLElement {
name: string;
root: HTMLElement | ShadowRoot;
rawHTML: string;
- state: T;
+ state: T & Record<keyof K, () => any> & Record<keyof L, () => string | any>;
value: any;
$: (css: string) => Element | null;
$$: (css: string) => NodeListOf<Element>;
- $store: any;
+ $getStore: () => GlobalStore;
+ $setStore: (updater: StoreUpdater) => void;
$$on: (css: string, ev: EventHandle) => void;
$$off: (css: string, event: string) => void;
- reRenderProperty: (this: WebComponent<T>, pathname: string) => void;
+ reRenderProperty: (this: WebComponent<T, K, L>, pathname: string) => void;
_globalStore: StoreApi<GlobalStore>;
_dynamicFieldRecord: DynamicFieldsRecord;
_eventListenerRecord: EventListenerRecord;
_storeListenerRecord: [() => void];
- _valueUpdater: (this: WebComponent<T>) => any;
+ _propsListenerRecord: PropListenerRecord;
+ _valueUpdater: (this: WebComponent<T, K, L>) => any;
}
export type DynamicFieldsRecord = Record<string, DynamicField[]>;
@@ -63,9 +79,16 @@ export type DynamicField = {
};
export type EventListenerRecord = Record<string, EventHandle[]>;
+export type PropListenerRecord = Record<
+ string,
+ {
+ type: "string" | "json";
+ key: string;
+ }
+>;
export type EventHandle = {
event: string;
- handler: (this: WebComponent<StateType>, ev: Event) => void;
+ handler: (this: WebComponent, ev: Event) => void;
options?: EventListenerOptions;
};
diff --git a/src/utils.ts b/src/utils.ts
index a1bf2ed..520adc1 100644
--- a/src/utils.ts
+++ b/src/utils.ts
@@ -1,10 +1,28 @@
import { StateType } from "./types";
export const TERNARY_REGEX =
- /\{\{(?<path>[a-z0-9\.]*)\s*(?:\?)?\s*(['"`](?<trueVal>[^'"`]*)['"`])?\s*(?::)?\s*(['"`](?<falseVal>[^'"`]*)['"`])?\s*\}\}/gi;
+ /\{\{(?<json>json::)?(?<path>[a-z0-9\.]*)\s*(?:\?)?\s*(['"`](?<trueVal>[^'"`]*)['"`])?\s*(?::)?\s*(['"`](?<falseVal>[^'"`]*)['"`])?\s*\}\}/gi;
export const FOR_LOOP_REGEX =
/((?<index>\w+)\s*,\s*)?(?<name>\w+)\s+((in)|(of))\s+(?<path>[a-z0-9\.]+)/i;
+export function parseJSON(json: string | null) {
+ if (!json) return null;
+ try {
+ return JSON.parse(json.replaceAll("'", '"'));
+ } catch (e) {
+ // console.error(e);
+ return null;
+ }
+}
+
+function mashallJSON(obj: any) {
+ return JSON.stringify(obj).replaceAll('"', "'");
+}
+
+function unProxyfy(obj: object) {
+ return JSON.parse(JSON.stringify(obj));
+}
+
export function parseDocumentFragment(rawHTML: string) {
const template = document.createElement("template");
template.innerHTML = rawHTML;
@@ -30,7 +48,7 @@ export function targetFromPath(obj: StateType, path: string) {
const props = path.split(".").map((p) => p.trim());
let target: any = obj;
for (let prop of props) {
- if (typeof target === "object" && target[prop] != undefined) {
+ if (typeof target === "object" && target != undefined && target[prop] != undefined) {
target = maybeCall(target[prop]);
} else {
return null;
@@ -39,10 +57,7 @@ export function targetFromPath(obj: StateType, path: string) {
return target;
}
-export function parseHTMLDeclaration(
- rawHTML: string,
- object: StateType
-) {
+export function parseHTMLDeclaration(rawHTML: string, object: StateType) {
return rawHTML.replaceAll(TERNARY_REGEX, (substr: string, ...args) => {
const groups = args.at(-1);
if (!groups || !("path" in groups)) return substr;
@@ -57,6 +72,10 @@ export function parseHTMLDeclaration(
if (trueVal || falseVal) {
return value ? trueVal : falseVal;
}
- return value?.toString();
+ if ("json" in groups && groups["json"]) {
+ return mashallJSON(value);
+ }
+ const rawValue = typeof value === "object" ? unProxyfy(value) : value;
+ return rawValue?.toString();
});
}