@wirekyt/angular 0.0.1 → 0.0.3

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.
@@ -0,0 +1,1011 @@
1
+ import { createScope, MachineStatus, hasTag, matchesState, getExitEnterStates, INIT_STATE, resolveStateValue, findTransition } from '@wirekyt/dom';
2
+ export { mergeProps } from '@wirekyt/dom';
3
+ import * as i0 from '@angular/core';
4
+ import { RendererStyleFlags2, effect, inject, DestroyRef, signal, computed, untracked, afterNextRender, InjectionToken, PLATFORM_ID, Injectable, createComponent, Injector, isDevMode } from '@angular/core';
5
+ import { compact, isFunction, toArray, warn, isString, ensure, isEqual, callAll } from '@wirekyt/dom/utils';
6
+ import { createNormalizer } from '@wirekyt/dom/types';
7
+ import { isPlatformBrowser, DOCUMENT } from '@angular/common';
8
+
9
+ const isAttributeKey = (key) => key === "role" ||
10
+ key === "id" ||
11
+ key === "tabindex" ||
12
+ key.startsWith("aria-") ||
13
+ key.startsWith("data-");
14
+ const eventNameFromHandlerKey = (key, el) => {
15
+ if (!/^on[A-Z]/.test(key))
16
+ return undefined;
17
+ if (key === "onDoubleClick")
18
+ return "dblclick";
19
+ if (key === "onChange") {
20
+ const tagName = el.tagName.toLowerCase();
21
+ if (tagName === "textarea")
22
+ return "input";
23
+ if (tagName === "input") {
24
+ const type = el.type;
25
+ return type === "checkbox" || type === "radio" || type === "file" ? "change" : "input";
26
+ }
27
+ if (tagName === "select")
28
+ return "change";
29
+ }
30
+ return key.slice(2).toLowerCase();
31
+ };
32
+ const isClassKey = (key) => key === "class" || key === "className";
33
+ const isStyleKey = (key) => key === "style";
34
+ const tokenizeClassString = (value) => value.split(/\s+/).filter((token) => token.length > 0);
35
+ const parseStyleString = (value) => {
36
+ const result = {};
37
+ for (const part of value.split(";")) {
38
+ const trimmed = part.trim();
39
+ if (trimmed.length === 0)
40
+ continue;
41
+ const colon = trimmed.indexOf(":");
42
+ if (colon < 0)
43
+ continue;
44
+ const name = trimmed.slice(0, colon).trim();
45
+ const styleValue = trimmed.slice(colon + 1).trim();
46
+ if (name.length === 0)
47
+ continue;
48
+ result[name] = styleValue;
49
+ }
50
+ return result;
51
+ };
52
+ const computeClassSet = (value) => {
53
+ const result = new Set();
54
+ if (value == null || value === false)
55
+ return result;
56
+ if (typeof value === "string") {
57
+ for (const token of tokenizeClassString(value))
58
+ result.add(token);
59
+ return result;
60
+ }
61
+ if (Array.isArray(value)) {
62
+ for (const item of value) {
63
+ if (typeof item === "string" && item.length > 0)
64
+ result.add(item);
65
+ }
66
+ return result;
67
+ }
68
+ if (typeof value === "object") {
69
+ const entries = value;
70
+ for (const key of Object.keys(entries)) {
71
+ if (entries[key])
72
+ result.add(key);
73
+ }
74
+ return result;
75
+ }
76
+ return result;
77
+ };
78
+ const computeStyleMap = (value) => {
79
+ const result = new Map();
80
+ if (value == null || value === false)
81
+ return result;
82
+ if (typeof value === "string") {
83
+ for (const [name, styleValue] of Object.entries(parseStyleString(value))) {
84
+ result.set(name, styleValue);
85
+ }
86
+ return result;
87
+ }
88
+ if (typeof value === "object") {
89
+ const entries = value;
90
+ for (const key of Object.keys(entries)) {
91
+ const styleValue = entries[key];
92
+ if (styleValue == null || styleValue === false)
93
+ continue;
94
+ result.set(key, String(styleValue));
95
+ }
96
+ return result;
97
+ }
98
+ return result;
99
+ };
100
+ function bindProps(options) {
101
+ const { elementRef, renderer, destroyRef } = options;
102
+ let prev = {};
103
+ let prevElement = null;
104
+ const listeners = new Map();
105
+ const appliedClasses = new Set();
106
+ const appliedStyles = new Set();
107
+ const removeListener = (key) => {
108
+ const listener = listeners.get(key);
109
+ if (!listener)
110
+ return;
111
+ listener.dispose();
112
+ listeners.delete(key);
113
+ };
114
+ const removeAttribute = (el, key) => {
115
+ renderer.removeAttribute(el, key);
116
+ };
117
+ const removeProperty = (el, key) => {
118
+ renderer.setProperty(el, key, "");
119
+ };
120
+ const applyClasses = (el, nextValue) => {
121
+ const nextSet = computeClassSet(nextValue);
122
+ for (const token of appliedClasses) {
123
+ if (!nextSet.has(token)) {
124
+ renderer.removeClass(el, token);
125
+ appliedClasses.delete(token);
126
+ }
127
+ }
128
+ for (const token of nextSet) {
129
+ if (!appliedClasses.has(token)) {
130
+ renderer.addClass(el, token);
131
+ appliedClasses.add(token);
132
+ }
133
+ }
134
+ };
135
+ const removeAllClasses = (el) => {
136
+ for (const token of appliedClasses) {
137
+ renderer.removeClass(el, token);
138
+ }
139
+ appliedClasses.clear();
140
+ };
141
+ const styleFlags = (name) => name.startsWith("--") ? RendererStyleFlags2.DashCase : undefined;
142
+ const applyStyles = (el, nextValue) => {
143
+ const nextMap = computeStyleMap(nextValue);
144
+ for (const name of appliedStyles) {
145
+ if (!nextMap.has(name)) {
146
+ renderer.removeStyle(el, name, styleFlags(name));
147
+ appliedStyles.delete(name);
148
+ }
149
+ }
150
+ for (const [name, styleValue] of nextMap) {
151
+ renderer.setStyle(el, name, styleValue, styleFlags(name));
152
+ appliedStyles.add(name);
153
+ }
154
+ };
155
+ const removeAllStyles = (el) => {
156
+ for (const name of appliedStyles) {
157
+ renderer.removeStyle(el, name, styleFlags(name));
158
+ }
159
+ appliedStyles.clear();
160
+ };
161
+ const resetElement = (el) => {
162
+ for (const { dispose } of listeners.values())
163
+ dispose();
164
+ listeners.clear();
165
+ if (el) {
166
+ removeAllClasses(el);
167
+ removeAllStyles(el);
168
+ }
169
+ else {
170
+ appliedClasses.clear();
171
+ appliedStyles.clear();
172
+ }
173
+ prev = {};
174
+ };
175
+ effect(() => {
176
+ const el = elementRef.nativeElement;
177
+ const next = (options.props() ?? {});
178
+ if (el !== prevElement) {
179
+ resetElement(prevElement);
180
+ prevElement = el;
181
+ }
182
+ if (!el)
183
+ return;
184
+ for (const key of Object.keys(next)) {
185
+ const nextValue = next[key];
186
+ const prevValue = prev[key];
187
+ const eventName = eventNameFromHandlerKey(key, el);
188
+ if (eventName && typeof nextValue === "function") {
189
+ const listener = listeners.get(key);
190
+ if (prevValue === nextValue && listener?.eventName === eventName)
191
+ continue;
192
+ removeListener(key);
193
+ const dispose = renderer.listen(el, eventName, nextValue);
194
+ listeners.set(key, { eventName, dispose });
195
+ continue;
196
+ }
197
+ if (eventName && listeners.has(key) && typeof nextValue !== "function") {
198
+ removeListener(key);
199
+ if (nextValue == null || nextValue === false)
200
+ continue;
201
+ }
202
+ if (isClassKey(key)) {
203
+ if (Object.is(prevValue, nextValue))
204
+ continue;
205
+ applyClasses(el, nextValue);
206
+ continue;
207
+ }
208
+ if (isStyleKey(key)) {
209
+ if (Object.is(prevValue, nextValue))
210
+ continue;
211
+ applyStyles(el, nextValue);
212
+ continue;
213
+ }
214
+ if (isAttributeKey(key)) {
215
+ if (nextValue == null || nextValue === false) {
216
+ if (prevValue !== undefined && prevValue !== null && prevValue !== false) {
217
+ removeAttribute(el, key);
218
+ }
219
+ continue;
220
+ }
221
+ if (Object.is(prevValue, nextValue))
222
+ continue;
223
+ renderer.setAttribute(el, key, String(nextValue));
224
+ continue;
225
+ }
226
+ if (nextValue == null) {
227
+ if (prevValue !== undefined && prevValue !== null) {
228
+ removeProperty(el, key);
229
+ }
230
+ continue;
231
+ }
232
+ if (Object.is(prevValue, nextValue))
233
+ continue;
234
+ renderer.setProperty(el, key, nextValue);
235
+ }
236
+ for (const key of Object.keys(prev)) {
237
+ if (key in next)
238
+ continue;
239
+ const prevValue = prev[key];
240
+ const eventName = eventNameFromHandlerKey(key, el);
241
+ if (eventName && typeof prevValue === "function") {
242
+ removeListener(key);
243
+ continue;
244
+ }
245
+ if (isClassKey(key)) {
246
+ applyClasses(el, undefined);
247
+ continue;
248
+ }
249
+ if (isStyleKey(key)) {
250
+ applyStyles(el, undefined);
251
+ continue;
252
+ }
253
+ if (isAttributeKey(key)) {
254
+ removeAttribute(el, key);
255
+ continue;
256
+ }
257
+ removeProperty(el, key);
258
+ }
259
+ prev = { ...next };
260
+ });
261
+ destroyRef.onDestroy(() => {
262
+ resetElement(prevElement);
263
+ prevElement = null;
264
+ });
265
+ }
266
+
267
+ const normalizeProps = createNormalizer((v) => v);
268
+
269
+ function isPlainFunction(value) {
270
+ return typeof value === "function";
271
+ }
272
+ const flush = (fn) => {
273
+ queueMicrotask(fn);
274
+ };
275
+ function useMachine(options) {
276
+ const destroyRef = inject(DestroyRef);
277
+ const machine = options.machine;
278
+ const latestFns = new Map();
279
+ const wrappers = new Map();
280
+ const resolveValue = (key, value) => {
281
+ if (!isPlainFunction(value))
282
+ return value;
283
+ latestFns.set(key, value);
284
+ let wrapper = wrappers.get(key);
285
+ if (!wrapper) {
286
+ wrapper = (...args) => latestFns.get(key)?.(...args);
287
+ wrappers.set(key, wrapper);
288
+ }
289
+ return wrapper;
290
+ };
291
+ const resolveContext = (raw) => {
292
+ const resolved = {};
293
+ for (const key of Object.keys(raw)) {
294
+ resolved[key] = resolveValue(key, raw[key]);
295
+ }
296
+ return resolved;
297
+ };
298
+ const initialContextRaw = options.context();
299
+ const initialContext = resolveContext(initialContextRaw);
300
+ const currentProps = signal(initialContext, /* @ts-ignore */
301
+ ...(ngDevMode ? [{ debugName: "currentProps" }] : /* istanbul ignore next */ []));
302
+ const scope = computed(() => {
303
+ const props = currentProps();
304
+ const getRootNode = props.getRootNode;
305
+ return createScope({
306
+ id: props.id,
307
+ ids: props.ids,
308
+ getRootNode: getRootNode ?? (() => document),
309
+ });
310
+ }, /* @ts-ignore */
311
+ ...(ngDevMode ? [{ debugName: "scope" }] : /* istanbul ignore next */ []));
312
+ const props = computed(() => {
313
+ return (machine.props?.({ props: compact(currentProps()), scope: scope() }) ?? currentProps());
314
+ }, /* @ts-ignore */
315
+ ...(ngDevMode ? [{ debugName: "props" }] : /* istanbul ignore next */ []));
316
+ const prop = ((key) => props()[key]);
317
+ const createBindable = (params) => {
318
+ const initialParams = params();
319
+ const initial = initialParams.value !== undefined ? initialParams.value : initialParams.defaultValue;
320
+ const value = signal(initial, /* @ts-ignore */
321
+ ...(ngDevMode ? [{ debugName: "value" }] : /* istanbul ignore next */ []));
322
+ const ref = { current: initial };
323
+ let defaultEffectInitialized = false;
324
+ let defaultHydrationChecked = false;
325
+ let userTouched = false;
326
+ effect(() => {
327
+ const nextParams = params();
328
+ const nextDefault = nextParams.defaultValue;
329
+ const controlled = nextParams.value !== undefined;
330
+ if (!defaultEffectInitialized) {
331
+ defaultEffectInitialized = true;
332
+ return;
333
+ }
334
+ if (userTouched || controlled || defaultHydrationChecked)
335
+ return;
336
+ defaultHydrationChecked = true;
337
+ if (nextDefault === undefined)
338
+ return;
339
+ if (!(nextParams.isEqual ?? Object.is)(untracked(value), nextDefault)) {
340
+ value.set(nextDefault);
341
+ }
342
+ });
343
+ const get = () => {
344
+ const controlled = params().value !== undefined;
345
+ const next = controlled ? params().value : value();
346
+ ref.current = next;
347
+ return next;
348
+ };
349
+ return {
350
+ initial,
351
+ ref,
352
+ get,
353
+ set(nextValue) {
354
+ const commit = () => {
355
+ const prev = get();
356
+ const next = isFunction(nextValue) ? nextValue(prev) : nextValue;
357
+ if (params().debug) {
358
+ console.log(`[bindable > ${params().debug}] setValue`, { next, prev });
359
+ }
360
+ if (params().value === undefined) {
361
+ userTouched = true;
362
+ value.set(next);
363
+ }
364
+ if (!(params().isEqual ?? Object.is)(next, prev)) {
365
+ params().onChange?.(next, prev);
366
+ }
367
+ };
368
+ if (params().sync)
369
+ untracked(commit);
370
+ else
371
+ commit();
372
+ },
373
+ invoke(nextValue, prevValue) {
374
+ params().onChange?.(nextValue, prevValue);
375
+ },
376
+ hash(valueToHash) {
377
+ return params().hash?.(valueToHash) ?? String(valueToHash);
378
+ },
379
+ };
380
+ };
381
+ createBindable.cleanup = (fn) => {
382
+ destroyRef.onDestroy(fn);
383
+ };
384
+ createBindable.ref = (defaultValue) => {
385
+ let value = defaultValue;
386
+ return {
387
+ get: () => value,
388
+ set: (next) => {
389
+ value = next;
390
+ },
391
+ };
392
+ };
393
+ const context = machine.context?.({
394
+ prop,
395
+ bindable: createBindable,
396
+ get scope() {
397
+ return scope();
398
+ },
399
+ flush,
400
+ getContext: () => ctx,
401
+ getComputed: () => computedValue,
402
+ getRefs: () => refs,
403
+ getEvent: () => getEvent(),
404
+ });
405
+ const ctx = {
406
+ get(key) {
407
+ return context?.[key]?.get();
408
+ },
409
+ set(key, value) {
410
+ context?.[key]?.set(value);
411
+ },
412
+ initial(key) {
413
+ return context?.[key]?.initial;
414
+ },
415
+ hash(key) {
416
+ const binding = context?.[key];
417
+ return binding?.hash(binding.get());
418
+ },
419
+ };
420
+ const refs = (() => {
421
+ const values = machine.refs?.({ prop, context: ctx }) ?? {};
422
+ const ref = { current: values };
423
+ return {
424
+ get(key) {
425
+ return ref.current[key];
426
+ },
427
+ set(key, value) {
428
+ ref.current[key] = value;
429
+ },
430
+ };
431
+ })();
432
+ let status = MachineStatus.NotStarted;
433
+ let transitionRef = null;
434
+ let previousEvent = null;
435
+ let currentEvent = { type: "" };
436
+ let pendingEvents = [];
437
+ let effects = new Map();
438
+ const trackedEffects = new Set();
439
+ const listeners = new Set();
440
+ let stateSignal;
441
+ const getEvent = () => ({
442
+ ...currentEvent,
443
+ current: () => currentEvent,
444
+ previous: () => previousEvent,
445
+ });
446
+ const getState = () => ({
447
+ ...state,
448
+ matches(...values) {
449
+ const current = state.get();
450
+ return values.some((value) => matchesState(current, value));
451
+ },
452
+ hasTag(tag) {
453
+ return hasTag(machine, state.get(), tag);
454
+ },
455
+ });
456
+ const notifyState = () => {
457
+ const next = getState();
458
+ stateSignal.set(next);
459
+ for (const listener of listeners)
460
+ listener(next);
461
+ };
462
+ const getParams = () => ({
463
+ state: getState(),
464
+ context: ctx,
465
+ event: getEvent(),
466
+ prop,
467
+ send,
468
+ action,
469
+ guard,
470
+ track,
471
+ refs,
472
+ computed: computedValue,
473
+ flush,
474
+ get scope() {
475
+ return scope();
476
+ },
477
+ choose,
478
+ });
479
+ const action = (keys) => {
480
+ const actionKeys = isFunction(keys) ? keys(getParams()) : keys;
481
+ if (!actionKeys)
482
+ return;
483
+ const fns = toArray(actionKeys).map((key) => {
484
+ const fn = machine.implementations?.actions?.[String(key)];
485
+ if (!fn)
486
+ warn(`[wirekyt] No implementation found for action "${JSON.stringify(key)}"`);
487
+ return fn;
488
+ });
489
+ for (const fn of fns) {
490
+ fn?.(getParams());
491
+ }
492
+ };
493
+ const guard = (key) => {
494
+ if (isFunction(key))
495
+ return key(getParams());
496
+ return machine.implementations?.guards?.[String(key)]?.(getParams());
497
+ };
498
+ const runEffects = (keys) => {
499
+ const effectKeys = isFunction(keys) ? keys(getParams()) : keys;
500
+ if (!effectKeys)
501
+ return undefined;
502
+ const fns = toArray(effectKeys).map((key) => {
503
+ const fn = machine.implementations?.effects?.[String(key)];
504
+ if (!fn)
505
+ warn(`[wirekyt] No implementation found for effect "${JSON.stringify(key)}"`);
506
+ return fn;
507
+ });
508
+ const cleanups = [];
509
+ for (const fn of fns) {
510
+ const cleanup = fn?.(getParams());
511
+ if (cleanup)
512
+ cleanups.push(cleanup);
513
+ }
514
+ return cleanups.length > 0
515
+ ? () => {
516
+ for (const cleanup of cleanups)
517
+ cleanup();
518
+ }
519
+ : undefined;
520
+ };
521
+ const choose = (transitions) => {
522
+ return toArray(transitions).find((transition) => {
523
+ let result = !transition.guard;
524
+ if (isString(transition.guard))
525
+ result = !!guard(transition.guard);
526
+ else if (isFunction(transition.guard))
527
+ result = transition.guard(getParams());
528
+ return result;
529
+ });
530
+ };
531
+ const computedValue = ((key) => {
532
+ ensure(machine.computed, () => `[wirekyt] No computed object found on machine`);
533
+ const fn = machine.computed[key];
534
+ return fn?.({
535
+ context: ctx,
536
+ event: getEvent(),
537
+ prop,
538
+ refs,
539
+ get scope() {
540
+ return scope();
541
+ },
542
+ computed: computedValue,
543
+ });
544
+ });
545
+ const track = (deps, fn) => {
546
+ let initialized = false;
547
+ let previous = [];
548
+ const ref = effect(() => {
549
+ const current = deps.map((dep) => dep());
550
+ if (!initialized) {
551
+ initialized = true;
552
+ previous = current;
553
+ return;
554
+ }
555
+ if (current.some((value, index) => !isEqual(previous[index], value))) {
556
+ previous = current;
557
+ fn();
558
+ }
559
+ }, /* @ts-ignore */
560
+ ...(ngDevMode ? [{ debugName: "ref" }] : /* istanbul ignore next */ []));
561
+ trackedEffects.add(ref);
562
+ };
563
+ const state = createBindable(() => ({
564
+ defaultValue: resolveStateValue(machine, machine.initialState({ prop })),
565
+ onChange(nextState, prevState) {
566
+ const { exiting, entering } = getExitEnterStates(machine, prevState, nextState, transitionRef?.reenter);
567
+ for (const item of exiting) {
568
+ const cleanup = effects.get(item.path);
569
+ cleanup?.();
570
+ effects.delete(item.path);
571
+ }
572
+ for (const item of exiting) {
573
+ action(item.state?.exit);
574
+ }
575
+ action(transitionRef?.actions);
576
+ for (const item of entering) {
577
+ const cleanup = runEffects(item.state?.effects);
578
+ if (cleanup) {
579
+ const existing = effects.get(item.path);
580
+ effects.set(item.path, existing ? callAll(existing, cleanup) : cleanup);
581
+ }
582
+ }
583
+ if (prevState === INIT_STATE) {
584
+ action(machine.entry);
585
+ const cleanup = runEffects(machine.effects);
586
+ if (cleanup) {
587
+ const existing = effects.get(INIT_STATE);
588
+ effects.set(INIT_STATE, existing ? callAll(existing, cleanup) : cleanup);
589
+ }
590
+ }
591
+ for (const item of entering) {
592
+ action(item.state?.entry);
593
+ }
594
+ notifyState();
595
+ },
596
+ }));
597
+ stateSignal = signal(getState());
598
+ const send = (event) => {
599
+ if (status === MachineStatus.Stopped)
600
+ return;
601
+ if (status !== MachineStatus.Started) {
602
+ pendingEvents.push(event);
603
+ return;
604
+ }
605
+ previousEvent = currentEvent;
606
+ currentEvent = event;
607
+ const currentState = untracked(() => state.get());
608
+ const { transitions, source } = findTransition(machine, currentState, event.type);
609
+ const transition = choose(transitions);
610
+ if (!transition)
611
+ return;
612
+ transitionRef = transition;
613
+ const target = resolveStateValue(machine, transition.target ?? currentState, source);
614
+ if (target !== currentState) {
615
+ state.set(target);
616
+ }
617
+ else if (transition.reenter) {
618
+ state.invoke(currentState, currentState);
619
+ }
620
+ else {
621
+ action(transition.actions);
622
+ }
623
+ };
624
+ const setContext = (patch) => {
625
+ currentProps.update((previous) => ({ ...previous, ...patch }));
626
+ notifyState();
627
+ };
628
+ const stop = () => {
629
+ if (status === MachineStatus.Stopped)
630
+ return;
631
+ status = MachineStatus.Stopped;
632
+ pendingEvents = [];
633
+ for (const ref of trackedEffects)
634
+ ref.destroy();
635
+ trackedEffects.clear();
636
+ for (const cleanup of effects.values())
637
+ cleanup();
638
+ effects = new Map();
639
+ transitionRef = null;
640
+ action(machine.exit);
641
+ listeners.clear();
642
+ };
643
+ const service = {
644
+ getStatus: () => status,
645
+ get state() {
646
+ return getState();
647
+ },
648
+ context: ctx,
649
+ send,
650
+ prop,
651
+ get scope() {
652
+ return scope();
653
+ },
654
+ refs,
655
+ computed: computedValue,
656
+ get event() {
657
+ return getEvent();
658
+ },
659
+ subscribe(listener) {
660
+ listeners.add(listener);
661
+ return () => listeners.delete(listener);
662
+ },
663
+ setContext,
664
+ stop,
665
+ };
666
+ let prevRawContext = initialContextRaw;
667
+ let prevResolvedContext = initialContext;
668
+ effect(() => {
669
+ const nextRaw = options.context();
670
+ const nextKeys = new Set(Object.keys(nextRaw));
671
+ for (const key of Object.keys(prevRawContext)) {
672
+ nextKeys.add(key);
673
+ }
674
+ const patch = {};
675
+ let hasChanges = false;
676
+ const nextResolvedContext = {};
677
+ for (const key of nextKeys) {
678
+ const nextRawValue = nextRaw[key];
679
+ const prevRawValue = prevRawContext[key];
680
+ const nextResolvedValue = key in nextRaw ? resolveValue(key, nextRawValue) : undefined;
681
+ if (key in nextRaw) {
682
+ nextResolvedContext[key] = nextResolvedValue;
683
+ }
684
+ if (!Object.is(prevRawValue, nextRawValue) &&
685
+ !Object.is(prevResolvedContext[key], nextResolvedValue)) {
686
+ patch[key] = nextResolvedValue;
687
+ hasChanges = true;
688
+ }
689
+ }
690
+ if (hasChanges) {
691
+ service.setContext(patch);
692
+ }
693
+ prevRawContext = nextRaw;
694
+ prevResolvedContext = nextResolvedContext;
695
+ });
696
+ machine.watch?.(getParams());
697
+ afterNextRender(() => {
698
+ if (status === MachineStatus.Stopped)
699
+ return;
700
+ status = MachineStatus.Started;
701
+ state.invoke(state.initial, INIT_STATE);
702
+ const events = pendingEvents;
703
+ pendingEvents = [];
704
+ for (const event of events) {
705
+ send(event);
706
+ }
707
+ });
708
+ const api = computed(() => {
709
+ void stateSignal();
710
+ return options.connect(service, normalizeProps);
711
+ }, /* @ts-ignore */
712
+ ...(ngDevMode ? [{ debugName: "api" }] : /* istanbul ignore next */ []));
713
+ destroyRef.onDestroy(stop);
714
+ return {
715
+ state: stateSignal.asReadonly(),
716
+ send: service.send,
717
+ service,
718
+ api,
719
+ };
720
+ }
721
+
722
+ const ENVIRONMENT_TOKEN = new InjectionToken("WIREKIT.ENVIRONMENT_TOKEN");
723
+ const createDefaultContext = (platformId) => ({
724
+ getRootNode: () => (isPlatformBrowser(platformId) ? document : undefined),
725
+ });
726
+ function provideEnvironment(config = {}) {
727
+ return {
728
+ provide: ENVIRONMENT_TOKEN,
729
+ useFactory: () => {
730
+ if (config.getRootNode) {
731
+ const getRootNode = config.getRootNode;
732
+ return { getRootNode };
733
+ }
734
+ const platformId = inject(PLATFORM_ID);
735
+ return createDefaultContext(platformId);
736
+ },
737
+ };
738
+ }
739
+ function injectEnvironment() {
740
+ const platformId = inject(PLATFORM_ID);
741
+ const ctx = inject(ENVIRONMENT_TOKEN, { optional: true });
742
+ return ctx ?? createDefaultContext(platformId);
743
+ }
744
+
745
+ const MODALITY_KEYS = new Set([
746
+ "Tab",
747
+ "ArrowUp",
748
+ "ArrowDown",
749
+ "ArrowLeft",
750
+ "ArrowRight",
751
+ "Enter",
752
+ "Escape",
753
+ " ",
754
+ ]);
755
+ function isModalityKey(key) {
756
+ return MODALITY_KEYS.has(key);
757
+ }
758
+ class InteractionService {
759
+ _modality = signal(null, /* @ts-ignore */
760
+ ...(ngDevMode ? [{ debugName: "_modality" }] : /* istanbul ignore next */ []));
761
+ modality = this._modality.asReadonly();
762
+ isFocusVisible = computed(() => this._modality() === "keyboard", /* @ts-ignore */
763
+ ...(ngDevMode ? [{ debugName: "isFocusVisible" }] : /* istanbul ignore next */ []));
764
+ constructor() {
765
+ const platformId = inject(PLATFORM_ID);
766
+ const document = inject(DOCUMENT);
767
+ const destroyRef = inject(DestroyRef);
768
+ if (!isPlatformBrowser(platformId))
769
+ return;
770
+ const onPointer = () => this._modality.set("pointer");
771
+ const onKey = (event) => {
772
+ if (isModalityKey(event.key))
773
+ this._modality.set("keyboard");
774
+ };
775
+ document.addEventListener("pointerdown", onPointer, true);
776
+ document.addEventListener("keydown", onKey, true);
777
+ destroyRef.onDestroy(() => {
778
+ document.removeEventListener("pointerdown", onPointer, true);
779
+ document.removeEventListener("keydown", onKey, true);
780
+ });
781
+ }
782
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.0", ngImport: i0, type: InteractionService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
783
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.1.0", ngImport: i0, type: InteractionService });
784
+ }
785
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.0", ngImport: i0, type: InteractionService, decorators: [{
786
+ type: Injectable
787
+ }], ctorParameters: () => [] });
788
+ const INTERACTION_TOKEN = new InjectionToken("WIREKIT.INTERACTION_TOKEN");
789
+ function provideInteraction() {
790
+ return [InteractionService, { provide: INTERACTION_TOKEN, useExisting: InteractionService }];
791
+ }
792
+ function injectInteraction() {
793
+ const ctx = inject(INTERACTION_TOKEN, { optional: true });
794
+ if (ctx)
795
+ return ctx;
796
+ return {
797
+ modality: signal(null).asReadonly(),
798
+ isFocusVisible: signal(false).asReadonly(),
799
+ };
800
+ }
801
+
802
+ const DEFAULT_LOCALE = "en-US";
803
+ const RTL_LANG_CODES = new Set([
804
+ "ae",
805
+ "ar",
806
+ "arc",
807
+ "bcc",
808
+ "bqi",
809
+ "ckb",
810
+ "dv",
811
+ "fa",
812
+ "glk",
813
+ "he",
814
+ "iw",
815
+ "khw",
816
+ "ks",
817
+ "ku",
818
+ "mzn",
819
+ "nqo",
820
+ "pnb",
821
+ "ps",
822
+ "sd",
823
+ "ug",
824
+ "ur",
825
+ "yi",
826
+ ]);
827
+ function getDirection(locale) {
828
+ const lang = locale.toLowerCase().split("-")[0] ?? "";
829
+ return RTL_LANG_CODES.has(lang) ? "rtl" : "ltr";
830
+ }
831
+ const LOCALE_TOKEN = new InjectionToken("WIREKYT.LOCALE_TOKEN");
832
+ function provideLocale(config = {}) {
833
+ return {
834
+ provide: LOCALE_TOKEN,
835
+ useFactory: () => {
836
+ const locale = config.locale ?? DEFAULT_LOCALE;
837
+ const dir = config.dir ?? getDirection(locale);
838
+ return { locale, dir };
839
+ },
840
+ };
841
+ }
842
+ function injectLocale() {
843
+ const ctx = inject(LOCALE_TOKEN, { optional: true });
844
+ return ctx ?? { locale: DEFAULT_LOCALE, dir: getDirection(DEFAULT_LOCALE) };
845
+ }
846
+ const collatorCache = new Map();
847
+ const dateFormatterCache = new Map();
848
+ const filterCache = new Map();
849
+ const MAX_CACHE_SIZE = 64;
850
+ const stableSerialize = (value) => {
851
+ if (value === null || typeof value !== "object")
852
+ return JSON.stringify(value);
853
+ if (Array.isArray(value))
854
+ return `[${value.map(stableSerialize).join(",")}]`;
855
+ const record = value;
856
+ return `{${Object.keys(record)
857
+ .sort()
858
+ .filter((key) => record[key] !== undefined)
859
+ .map((key) => `${JSON.stringify(key)}:${stableSerialize(record[key])}`)
860
+ .join(",")}}`;
861
+ };
862
+ const cacheKey = (locale, options) => `${locale}:${stableSerialize(options ?? {})}`;
863
+ const setCached = (cache, key, value) => {
864
+ if (!cache.has(key) && cache.size >= MAX_CACHE_SIZE) {
865
+ const oldest = cache.keys().next().value;
866
+ if (oldest !== undefined)
867
+ cache.delete(oldest);
868
+ }
869
+ cache.set(key, value);
870
+ };
871
+ function getCollator(locale, options) {
872
+ const key = cacheKey(locale, options);
873
+ let collator = collatorCache.get(key);
874
+ if (!collator) {
875
+ collator = new Intl.Collator(locale, options);
876
+ setCached(collatorCache, key, collator);
877
+ }
878
+ return collator;
879
+ }
880
+ function getDateFormatter(locale, options) {
881
+ const key = cacheKey(locale, options);
882
+ let formatter = dateFormatterCache.get(key);
883
+ if (!formatter) {
884
+ formatter = new Intl.DateTimeFormat(locale, options);
885
+ setCached(dateFormatterCache, key, formatter);
886
+ }
887
+ return formatter;
888
+ }
889
+ function getFilter(locale, options = { sensitivity: "base" }) {
890
+ const normalizedOptions = { ...options, usage: "search" };
891
+ const key = cacheKey(locale, normalizedOptions);
892
+ const cached = filterCache.get(key);
893
+ if (cached)
894
+ return cached;
895
+ const collator = getCollator(locale, normalizedOptions);
896
+ const filter = {
897
+ contains(s, sub) {
898
+ if (sub.length === 0)
899
+ return true;
900
+ for (let i = 0; i + sub.length <= s.length; i++) {
901
+ if (collator.compare(s.slice(i, i + sub.length), sub) === 0)
902
+ return true;
903
+ }
904
+ return false;
905
+ },
906
+ startsWith(s, sub) {
907
+ if (sub.length > s.length)
908
+ return false;
909
+ return collator.compare(s.slice(0, sub.length), sub) === 0;
910
+ },
911
+ endsWith(s, sub) {
912
+ if (sub.length > s.length)
913
+ return false;
914
+ return collator.compare(s.slice(s.length - sub.length), sub) === 0;
915
+ },
916
+ };
917
+ setCached(filterCache, key, filter);
918
+ return filter;
919
+ }
920
+
921
+ function createContextCarrier(options) {
922
+ return {
923
+ originInjector: options.originInjector,
924
+ environmentInjector: options.environmentInjector,
925
+ elementInjector: options.elementInjector,
926
+ root: options.root,
927
+ };
928
+ }
929
+ function createEmbeddedViewWithCarrier(viewContainer, template, carrier, context) {
930
+ return viewContainer.createEmbeddedView(template, context, {
931
+ injector: carrier.elementInjector,
932
+ });
933
+ }
934
+ function createComponentWithCarrier(component, carrier) {
935
+ return createComponent(component, {
936
+ environmentInjector: carrier.environmentInjector,
937
+ elementInjector: carrier.elementInjector,
938
+ });
939
+ }
940
+ function buildRootCarrier(options) {
941
+ const elementInjector = Injector.create({
942
+ parent: options.originInjector,
943
+ providers: [
944
+ { provide: options.rootToken, useValue: options.root },
945
+ ...(options.providers ?? []),
946
+ ],
947
+ });
948
+ return createContextCarrier({
949
+ originInjector: options.originInjector,
950
+ environmentInjector: options.environmentInjector,
951
+ elementInjector,
952
+ root: options.root,
953
+ });
954
+ }
955
+
956
+ const warnMixedFormAndModelBinding = (componentName) => {
957
+ if (!isDevMode())
958
+ return;
959
+ console.warn(`[@wyrekit/angular] ${componentName}: a form binding and [(value)] are both present on the same root. The form binding remains the source of truth.`);
960
+ };
961
+
962
+ const noopChange = (_value) => { };
963
+ const noopTouched = () => { };
964
+ const createCvaController = (options) => {
965
+ let onChange = noopChange;
966
+ let onTouched = noopTouched;
967
+ let warned = false;
968
+ const maybeWarn = () => {
969
+ if (warned)
970
+ return;
971
+ if (!options.hasExternalModelBinding())
972
+ return;
973
+ warned = true;
974
+ warnMixedFormAndModelBinding(options.componentName);
975
+ };
976
+ return {
977
+ writeValue(value) {
978
+ maybeWarn();
979
+ options.value.set(value === null ? undefined : value);
980
+ },
981
+ registerOnChange(fn) {
982
+ maybeWarn();
983
+ onChange = fn;
984
+ },
985
+ registerOnTouched(fn) {
986
+ onTouched = fn;
987
+ },
988
+ setDisabledState(disabled) {
989
+ options.setDisabled(disabled);
990
+ },
991
+ notifyValueChange(value) {
992
+ onChange(value);
993
+ },
994
+ markTouched() {
995
+ onTouched();
996
+ },
997
+ };
998
+ };
999
+
1000
+ let counter = 0;
1001
+ const createId = () => {
1002
+ counter += 1;
1003
+ return String(counter);
1004
+ };
1005
+
1006
+ /**
1007
+ * Generated bundle index. Do not edit.
1008
+ */
1009
+
1010
+ export { DEFAULT_LOCALE, ENVIRONMENT_TOKEN, INTERACTION_TOKEN, InteractionService, LOCALE_TOKEN, bindProps, buildRootCarrier, createComponentWithCarrier, createContextCarrier, createCvaController, createEmbeddedViewWithCarrier, createId, getCollator, getDateFormatter, getDirection, getFilter, injectEnvironment, injectInteraction, injectLocale, normalizeProps, provideEnvironment, provideInteraction, provideLocale, useMachine, warnMixedFormAndModelBinding };
1011
+ //# sourceMappingURL=wirekyt-angular.mjs.map