arrmatura 6.2.1 → 6.3.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.
@@ -1,37 +0,0 @@
1
- import { CtxNode } from "../ctx/CtxNode";
2
- import { Ctx } from "../ctx/Ctx";
3
- import type { XmlNode } from "ultimus/types";
4
-
5
- class DynamicTag extends Ctx<CDynamicTagNode> {
6
- get displayName(): string {
7
- return "dynamics";
8
- }
9
-
10
- get content() {
11
- const tag = this.component.tag;
12
- const uid = `${this.uid}:${String(tag ?? "")}`;
13
- return new Map([
14
- [
15
- uid,
16
- Object.assign(
17
- this.platform.getCompiledNodes({ ...this.node.xml, tag } as XmlNode),
18
- { uid }
19
- ),
20
- ],
21
- ]);
22
- }
23
- }
24
-
25
- export class CDynamicTagNode extends CtxNode {
26
- xml: XmlNode & { tag: string };
27
-
28
- constructor(xml: XmlNode, expr: string) {
29
- super();
30
- this.compileAttribute("tag", expr);
31
- this.xml = xml;
32
- }
33
-
34
- get EntityConstructor() {
35
- return DynamicTag;
36
- }
37
- }
@@ -1,57 +0,0 @@
1
- import { CtxNode } from "../ctx/CtxNode";
2
- import { Ctx } from "../ctx/Ctx";
3
- import type { Hash, XmlNode } from "ultimus/types";
4
- import type { EContent, IPlatform } from "arrmatura-api/types";
5
-
6
- export class Selector extends Ctx<CSelectorNode> {
7
- get displayName(): string {
8
- return `💠Selector`;
9
- }
10
-
11
- /**
12
- * Gets the content of the function.
13
- *
14
- * @return {any} The content of the function.
15
- */
16
- get content() {
17
- const cases = this.node.getCases(this.platform);
18
- const matchedCase = cases?.[this.component.on as string];
19
- if (!matchedCase) {
20
- this.log('unmatched case', this.component.on, cases);
21
- }
22
- return matchedCase ?? cases?.['default'] ?? Object.values(cases)[0];
23
- }
24
- }
25
-
26
- export class CSelectorNode extends CtxNode {
27
- cases: Hash<EContent> | null = null;
28
- key = '';
29
- nodes?: XmlNode["nodes"];
30
-
31
- constructor({ tag, attrs, nodes }: XmlNode) {
32
- super();
33
- this.tag = tag;
34
- this.nodes = nodes;
35
- this.compileAttributes(attrs);
36
- }
37
-
38
- /**
39
- * Retrieves the cases nodes for a component.
40
- *
41
- * @param {IPlatform} platform - The platform to get cases for.
42
- * @return {Hash<EContent>} - The cases for the platform.
43
- */
44
- getCases(platform: IPlatform): Hash<EContent> {
45
- return this.cases ?? (this.cases = (this.nodes ?? []).reduce<Hash<EContent>>(
46
- (groups, node) => {
47
- groups[node.attrs?.when as string] = platform.getCompiledNodes(node.nodes ?? []);
48
- return groups;
49
- },
50
- {}
51
- ));
52
- }
53
-
54
- get EntityConstructor() {
55
- return Selector;
56
- }
57
- }
package/src/core/slot.ts DELETED
@@ -1,36 +0,0 @@
1
- import { CtxNode } from "../ctx/CtxNode";
2
- import { Ctx } from "../ctx/Ctx";
3
- import type { XmlNode } from "ultimus/types";
4
- import type { ICtx } from "arrmatura-api/types";
5
- import { Composite } from "./composition";
6
-
7
- class Slot extends Ctx {
8
- get displayName(): string {
9
- return "🔸";
10
- }
11
-
12
- get compositeScope(): Composite {
13
- return this.scope as Composite;
14
- }
15
-
16
- get content() {
17
- return this.compositeScope.slotContent((this.node as CSlotNode).key);
18
- }
19
-
20
- get recontentScope(): ICtx {
21
- return this.compositeScope.scope;
22
- }
23
- }
24
-
25
- export class CSlotNode extends CtxNode {
26
- key?: string;
27
-
28
- constructor(x: XmlNode) {
29
- super();
30
- this.key = x.attrs?.key as string;
31
- }
32
-
33
- get EntityConstructor() {
34
- return Slot;
35
- }
36
- }
package/src/ctx/Ctx.ts DELETED
@@ -1,424 +0,0 @@
1
- import { areEqual, capitalize, identity } from "ultimus";
2
- import { stringify } from "../utils/stringify";
3
- import type { Delta, Fn, Hash, Proc, Uid } from "ultimus/types";
4
- import type {
5
- EProcedure,
6
- ICtx,
7
- ICtxNode,
8
- IComponent,
9
- IPlatform,
10
- } from "arrmatura-api/types";
11
-
12
- /**
13
- * The Component Context class.
14
- * It creates, refers and manages a component instance.
15
- *
16
- * A component instance gets reference to its context in 2nd constructor parameter.
17
- */
18
- export class Ctx<T extends ICtxNode = ICtxNode> implements ICtx {
19
- readonly component: IComponent;
20
- $children?: Map<Uid, ICtx>;
21
- readonly root: ICtx;
22
- readonly scope: ICtx;
23
- isDone = false;
24
-
25
- #isInited = false;
26
- #state: Hash = {};
27
- #initialState: Hash = {};
28
- #listeners?: Set<(c: Ctx) => void>;
29
- #defered?: EProcedure[] = [];
30
- #weak?: Map<string, number>;
31
- #refs?: Hash<ICtx>;
32
- #propFnMap?: Map<string, Proc>;
33
-
34
- constructor(
35
- readonly platform: IPlatform,
36
- protected readonly node: T,
37
- private _parent?: ICtx,
38
- scope?: ICtx
39
- ) {
40
- this.scope = scope ?? this;
41
- this.root = scope?.root ?? this;
42
- this.#initialState = this.node.resolveInitialProps(this);
43
- this.component = this.createComponent(this.#initialState);
44
-
45
- if (this.refId) {
46
- this.scope.addEntityReference(this.refId, this);
47
- }
48
- }
49
-
50
- get parent(): ICtx | undefined {
51
- return this._parent;
52
- }
53
-
54
- get uid(): string {
55
- return this.node.uid;
56
- }
57
-
58
- get displayName(): string {
59
- return "🔹";
60
- }
61
-
62
- createComponent(initials: Hash): IComponent {
63
- return { ...initials };
64
- }
65
-
66
- // --- State
67
-
68
- // updates component state
69
- up(Δ?: Delta | Promise<any> | null | void | unknown, force = false): void {
70
- if (!Δ || this.isDone) {
71
- return;
72
- }
73
-
74
- if (Δ instanceof Promise) {
75
- this.upAsync(Δ, "*");
76
- return;
77
- }
78
-
79
- const changes = new Map<string, unknown>();
80
- Object.entries(Δ).forEach(([k, v]) => {
81
- if (v instanceof Promise) {
82
- this.upAsync(v, k);
83
- } else if (
84
- k &&
85
- typeof v !== "undefined" &&
86
- !areEqual(v, this.#state[k])
87
- ) {
88
- this.#state[k] = v;
89
- changes.set(k, v);
90
- }
91
- });
92
-
93
- if (changes.size || force) {
94
- this.stateChanged(changes);
95
- }
96
- }
97
-
98
- private upAsync(promise: Promise<any>, key: string): void {
99
- const racer = this.raceCondition(`set:${key}`);
100
- if (key[0] !== "*") {
101
- const akey = key.replace("Promise", "");
102
- void promise.then((val) => racer(() => this.up({ [akey]: val })));
103
- } else {
104
- void promise.then((r: Delta) => racer(() => this.up(r)));
105
- }
106
- }
107
-
108
- private stateChanged(changes: Map<string, unknown>) {
109
- if (this.component.stateChanged) {
110
- this.component.stateChanged(changes);
111
- } else {
112
- changes.forEach((v, k) => {
113
- const setter = this.component[`set${capitalize(k)}`];
114
- if (typeof setter === "function") {
115
- setter.call(this.component, v);
116
- } else {
117
- this.component[k] = v;
118
- }
119
- });
120
- }
121
- this.touch();
122
- }
123
-
124
- // do recontent and notify all
125
- touch() {
126
- this.recontent();
127
- this.notify();
128
- }
129
-
130
- // gets component property by key
131
- get(propId: string): unknown {
132
- const map = this.#propFnMap ?? (this.#propFnMap = new Map());
133
- if (map.has(propId)) {
134
- return map.get(propId)();
135
- }
136
-
137
- let fn: Fn | null = null;
138
- const impl = this.component;
139
- const instant = impl[propId];
140
- if (instant && typeof instant === "function") {
141
- const bound = instant.bind(impl);
142
- fn = () => bound;
143
- } else {
144
- const [pk, ...path] = propId.split(".");
145
- if (pk[0] === "@") {
146
- path.unshift(pk.slice(1));
147
- const val = this.platform.getResource(path) ?? null;
148
- fn = () => val;
149
- } else {
150
- const gettr = impl[`get${capitalize(pk)}`];
151
- const fn0 =
152
- typeof gettr === "function"
153
- ? () => gettr.call(impl) ?? null
154
- : () => impl[pk] ?? null;
155
-
156
- fn = !path.length
157
- ? fn0
158
- : () => path.reduce((r, p) => r?.[p] ?? null, fn0());
159
- }
160
- }
161
-
162
- map.set(propId, fn);
163
-
164
- return fn();
165
- }
166
-
167
- getFromScope(propId: string): unknown {
168
- return this.scope.get(propId);
169
- }
170
-
171
- // --- Left Arrow.
172
-
173
- notify() {
174
- this.#listeners?.forEach((fn) => fn(this));
175
- }
176
-
177
- // add listener to componet state changes
178
- subscribe(handler: (src: Ctx) => any): Proc {
179
- const listeners = this.#listeners ?? (this.#listeners = new Set());
180
- listeners.add(handler);
181
- return () => {
182
- listeners.delete(handler);
183
- };
184
- }
185
-
186
- // --- Right Arrow.
187
-
188
- // emits action event to this component
189
- emit(key: string, data: Delta): void {
190
- if (!key || !key.includes(".")) {
191
- this.up(key ? { [key]: data } : data);
192
- return;
193
- }
194
-
195
- const [refId, target] = key.split(".");
196
- try {
197
- const ref = this.getByRef(refId);
198
- if (!ref) {
199
- throw new Error(`No such reference: ${refId}`);
200
- }
201
- if (!target) {
202
- ref.up(data);
203
- return;
204
- }
205
-
206
- const propId = `on${capitalize(target)}`;
207
- const impl = ref.component;
208
- const method = impl[propId];
209
-
210
- if (!method) {
211
- ref.up({ [target]: data });
212
- return;
213
- }
214
-
215
- if (!method || !(typeof method === "function")) {
216
- throw new Error(`No such method ${refId}.${propId}`);
217
- }
218
-
219
- const result = method.call(impl, data, impl, ref);
220
-
221
- this.log(`-> ${refId}.${propId}`, result, data, impl);
222
-
223
- ref.up(result);
224
- } catch (ex) {
225
- this.logError(`emit ${key}:`, ex);
226
- }
227
- return;
228
- }
229
-
230
- // Done life-cycle hook.
231
- done() {
232
- if (this.isDone) {
233
- return;
234
- }
235
- this.isDone = true;
236
-
237
- this.component.done?.(this);
238
-
239
- this.children?.forEach((c) => c.done());
240
-
241
- this.#defered?.forEach((f) => f(this));
242
- this.#defered = undefined;
243
-
244
- this._parent?.children?.delete(this.uid);
245
- this._parent = undefined;
246
- }
247
-
248
- // map of children contexts
249
- get children(): Map<Uid, ICtx> | undefined {
250
- return this.$children;
251
- }
252
-
253
- // map of chidren of its node
254
- get content() {
255
- return this.node.getContent(this.platform);
256
- }
257
-
258
- // actual scope for re-content
259
- get recontentScope() {
260
- return this.scope;
261
- }
262
-
263
- settleAsChild() {
264
- if (!this.#isInited) {
265
- this.#isInited = true;
266
-
267
- this.initConnectors();
268
-
269
- this.up(this.#initialState, true);
270
-
271
- this.up(this.component.init?.(this));
272
- } else {
273
- void this.up(this.node.resolveProps(this), true);
274
- }
275
- }
276
-
277
- // perform children instantiation and updates
278
- private recontent() {
279
- const nodes = this.content;
280
-
281
- this.platform.redraw(this, this.root);
282
-
283
- this.children?.forEach((e, uid) => {
284
- if (!nodes?.get(uid)) {
285
- e.done();
286
- }
287
- });
288
-
289
- const children = new Map<Uid, ICtx>();
290
-
291
- nodes?.forEach((node: ICtxNode, uid: Uid) => {
292
- const e =
293
- this.children?.get(uid) ??
294
- node.createContext(this.platform, this, this.recontentScope);
295
- children.set(e.uid, e);
296
- });
297
-
298
- this.$children = children;
299
-
300
- for (const ch of children.values()) {
301
- ch.settleAsChild();
302
- }
303
- }
304
-
305
- // --- Referencing.
306
-
307
- get refId() {
308
- return this.node.refId;
309
- }
310
-
311
- // gets any context instance in current or upper scope by key
312
- getByRef(refId: string): ICtx | undefined {
313
- if (!refId) return undefined;
314
-
315
- if (refId === "this") {
316
- return this;
317
- }
318
- const local = this.#refs?.[refId];
319
- if (local) {
320
- return local;
321
- }
322
- const ref = this === this.scope ? null : this.scope.getByRef(refId);
323
- return ref as Ctx;
324
- }
325
-
326
- addEntityReference(refId: string, c: ICtx) {
327
- (this.#refs ?? (this.#refs = {}))[refId] = c;
328
- }
329
-
330
- // --- Routines -------------------------
331
-
332
- private initConnectors() {
333
- if (this.node.connectors) {
334
- for (const [key, pipes] of this.node.connectors.entries()) {
335
- const [srcIds, targetPropName] = key.split("|");
336
- const [refId, ...propIds] = srcIds.split(".");
337
-
338
- const ref = this.scope.getByRef(refId) as Ctx;
339
- if (!ref) {
340
- this.logError(`Connect: No such ref: ${refId}`);
341
- continue;
342
- }
343
-
344
- if (!propIds.length) {
345
- this.logError(`Connect: No prop specified: ${key}`);
346
- continue;
347
- }
348
-
349
- const propId = propIds.join(".");
350
- const applicator = targetPropName
351
- ? (rr: any) => ({ [targetPropName]: rr })
352
- : identity;
353
-
354
- this.defer(
355
- ref.subscribe((source: Ctx) => {
356
- try {
357
- const r = applicator(pipes(this, source.get(propId)));
358
- this.up(r as Delta);
359
- } catch (ex) {
360
- source.logError("Notify ", ex);
361
- }
362
- })
363
- );
364
-
365
- // hot subscription
366
- Object.assign(
367
- this.#initialState,
368
- applicator(pipes(ref, ref.get(propId)))
369
- );
370
- }
371
- }
372
- }
373
-
374
- raceCondition(key: string) {
375
- const COUNTERS = this.#weak ?? (this.#weak = new Map<string, number>());
376
- let counter = 1 + (COUNTERS.get(key) ?? 0);
377
- COUNTERS.set(key, counter);
378
- return (fn: () => unknown) => {
379
- if (counter === COUNTERS.get(key)) {
380
- counter = 0;
381
- return fn();
382
- }
383
- };
384
- }
385
-
386
- // register callback to be called on done
387
- defer(fn: EProcedure) {
388
- if (fn && typeof fn === "function") {
389
- (this.#defered ?? (this.#defered = [])).push(fn);
390
- }
391
- }
392
-
393
- log(val: any, ...args: unknown[]) {
394
- this.platform.log({
395
- level: "log",
396
- source: `${this.displayName}:${this.uid}`,
397
- message: val,
398
- params: args,
399
- });
400
- return val;
401
- }
402
-
403
- logError(error: any, ...args: unknown[]) {
404
- this.platform.log({
405
- level: "error",
406
- source: `${this.displayName}:${this.uid}`,
407
- error,
408
- message: `${String(error.message || error)}\n${this.toString().slice(
409
- 0,
410
- 120
411
- )}`,
412
- params: args,
413
- });
414
- }
415
-
416
- // access to resource by key
417
- res(key: string | string[]) {
418
- return this.platform.getResource(key);
419
- }
420
-
421
- toString(): string {
422
- return stringify(this);
423
- }
424
- }
@@ -1,159 +0,0 @@
1
- import { nextId } from "ultimus";
2
- import {
3
- compileExpression,
4
- compilePipeExpression,
5
- } from "../utils/compileExpression";
6
- import type { Delta, Expression, Hash, Uid } from "ultimus/types";
7
- import type {
8
- IPlatform,
9
- ICtx,
10
- ICtxNode,
11
- PropertyGetter,
12
- PropertyResolver,
13
- } from "arrmatura-api/types";
14
-
15
- /**
16
- * ContextNode is a factory for all ICtx instances.
17
- */
18
- export abstract class CtxNode implements ICtxNode {
19
- protected $content?: Map<Uid, ICtxNode> | undefined;
20
- uid: Uid = nextId("N");
21
- refId?: string;
22
- private readonly propertyResolvers: PropertyResolver[] = [];
23
- private initialState: Hash<(c: ICtx) => any> = {};
24
- connectors?: Map<string, (c: ICtx, x: unknown) => unknown>;
25
- tag: any;
26
-
27
- abstract get EntityConstructor(): new (
28
- platform: IPlatform,
29
- node: typeof this,
30
- parent?: ICtx,
31
- scope?: ICtx
32
- ) => ICtx;
33
-
34
- /**
35
- * Create a context object.
36
- *
37
- * @param {IPlatform} platform - The platform object.
38
- * @param {ICtx} parent - The parent context object (optional).
39
- * @param {ICtx} scope - The scope context object (optional).
40
- * @return {ICtx} The created context object.
41
- */
42
- createContext(platform: IPlatform, parent?: ICtx, scope?: ICtx): ICtx {
43
- return new this.EntityConstructor(platform, this, parent, scope);
44
- }
45
-
46
- getContent(_platform: IPlatform): Map<Uid, ICtxNode> | undefined {
47
- return this.$content;
48
- }
49
-
50
- addPropertyResolver(getter: PropertyGetter, propKey: string) {
51
- this.propertyResolvers.push((c: ICtx, delta: Delta) => {
52
- delta[propKey] = getter(c);
53
- return delta;
54
- });
55
- return this;
56
- }
57
-
58
- private addDataPropertyResolver(getter: PropertyGetter, propKey: string) {
59
- this.propertyResolvers.push((c: ICtx, delta: Delta) => {
60
- const val = getter(c);
61
- delta.data = Object.assign((delta.data as object) || {}, {
62
- [propKey]: val,
63
- });
64
- return delta;
65
- });
66
- return this;
67
- }
68
-
69
- private addPropertiesResolver(getter: PropertyGetter) {
70
- this.propertyResolvers.push((c: ICtx, delta: Delta) => {
71
- const value = getter(c);
72
- if (value && typeof value === "object") {
73
- Object.entries(value).forEach(([key, val]) => {
74
- delta[key] = val;
75
- });
76
- }
77
- return delta;
78
- });
79
- return this;
80
- }
81
-
82
- addConnector(expr: Expression, propName: string) {
83
- const { key, pipec } = compilePipeExpression(expr);
84
- (this.connectors ?? (this.connectors = new Map())).set(
85
- `${key}|${propName}`,
86
- pipec
87
- );
88
- }
89
-
90
- private addEmitter(expr: Expression, k: string) {
91
- const { key, pipec } = compilePipeExpression(expr);
92
- this.initialState[k] = (c) => (data: unknown) =>
93
- c.scope?.emit(key, pipec(c, data) as Delta);
94
- }
95
-
96
- resolveInitialProps(c: ICtx) {
97
- return this.propertyResolvers.reduce(
98
- (delta, resolver) => resolver(c, delta),
99
- Object.entries(this.initialState).reduce((acc, [key, fn]) => {
100
- acc[key] = fn(c);
101
- return acc;
102
- }, {} as Hash)
103
- );
104
- }
105
-
106
- resolveProps(c: ICtx) {
107
- return this.propertyResolvers.reduce(
108
- (delta, resolver) => resolver(c, delta),
109
- {}
110
- );
111
- }
112
-
113
- compileAttribute(k: string, v: unknown) {
114
- if (k.startsWith("data-")) {
115
- this.addDataPropertyResolver(compileExpression(v), k.slice(5));
116
- } else if (k === "ref") {
117
- this.refId = String(v);
118
- } else if (k === "props") {
119
- const sv = String(v);
120
- if (sv[0] === "<" && sv[1] === "-") {
121
- this.addConnector(sv.slice(2), "");
122
- } else {
123
- this.addPropertiesResolver(compileExpression(v));
124
- }
125
- } else {
126
- if (typeof v !== "string") {
127
- this.initialState[k] = () => v;
128
- } else {
129
- if (v[0] === "<" && v[1] === "-") {
130
- this.addConnector(v.slice(2), k);
131
- } else if (v[0] === "-" && v[1] === ">") {
132
- this.addEmitter(v.slice(2), k);
133
- } else {
134
- if (!v.includes("{") && v[0] !== "@") {
135
- this.initialState[k] = () => v;
136
- } else {
137
- if (
138
- v[0] === "@" &&
139
- v[1] === "@" &&
140
- v.match(/^@@[a-z0-9\-_.]+$/i) != null
141
- ) {
142
- this.initialState[k] = (c) => c.platform.getResource(v.slice(2));
143
- } else {
144
- this.addPropertyResolver(compileExpression(v), k);
145
- }
146
- }
147
- }
148
- }
149
- }
150
- }
151
-
152
- compileAttributes(attrs?: Hash) {
153
- if (attrs) {
154
- Object.entries(attrs).forEach((keyValue) =>
155
- this.compileAttribute(...keyValue)
156
- );
157
- }
158
- }
159
- }