@overmvp/kumi 0.0.0-stage → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +67 -2
- package/animation/color-transition.ts +196 -0
- package/animation/cycle.ts +151 -0
- package/animation/ease.ts +29 -0
- package/animation/index.ts +13 -0
- package/animation/package.json +12 -0
- package/animation/presets.ts +376 -0
- package/animation/spec.ts +197 -0
- package/builder/Cargo.lock +192 -0
- package/builder/Cargo.toml +7 -0
- package/builder/css-v1.mjs +387 -0
- package/builder/css-v1.test.mjs +361 -0
- package/builder/generated-output.mjs +61 -0
- package/builder/generated-output.test.mjs +132 -0
- package/builder/jsx-form.mjs +93 -0
- package/builder/jsx-form.test.mjs +48 -0
- package/builder/jsx-lists.mjs +209 -0
- package/builder/link-addon-package.mjs +127 -0
- package/builder/lua-assets.mjs +74 -0
- package/builder/lua-builtin-values.mjs +57 -0
- package/builder/lua-builtin-values.test.mjs +155 -0
- package/builder/lua-loop-closures.mjs +183 -0
- package/builder/lua-loop-closures.test.mjs +89 -0
- package/builder/lua-truthiness.mjs +61 -0
- package/builder/lua-truthiness.test.mjs +113 -0
- package/builder/module-declarations.mjs +594 -0
- package/builder/module-declarations.test.mjs +435 -0
- package/builder/native-kernels.mjs +60 -0
- package/builder/native-lua.d.ts +57 -0
- package/builder/native-routes.mjs +51 -0
- package/builder/no-static-ref-read.mjs +93 -0
- package/builder/no-static-ref-read.test.mjs +181 -0
- package/builder/secure-snippet.mjs +317 -0
- package/builder/secure-snippet.test.mjs +101 -0
- package/builder/shared-lua-runtime.mjs +150 -0
- package/builder/src/addon-link.lua +29 -0
- package/builder/src/arrays.lua +260 -0
- package/builder/src/assets.rs +177 -0
- package/builder/src/classes.lua +75 -0
- package/builder/src/collections.lua +190 -0
- package/builder/src/compiler.rs +2336 -0
- package/builder/src/config.rs +42 -0
- package/builder/src/entries.rs +166 -0
- package/builder/src/errors.lua +15 -0
- package/builder/src/lua_data.rs +231 -0
- package/builder/src/main.rs +381 -0
- package/builder/src/native_ir.rs +65 -0
- package/builder/src/native_signal.rs +83 -0
- package/builder/src/numbers.lua +76 -0
- package/builder/src/project-front.mjs +3682 -0
- package/builder/src/records.lua +75 -0
- package/builder/src/routes.rs +124 -0
- package/builder/src/setup-store.lua +18 -0
- package/builder/src/signal-kernel.fingerprint +1 -0
- package/builder/src/strings.lua +103 -0
- package/builder/src/ts-lower.mjs +68 -0
- package/builder/src/wow-reads.lua +22 -0
- package/builder/src/wow_client.rs +253 -0
- package/builder/src/wow_types.rs +564 -0
- package/builder/style-modules.mjs +93 -0
- package/builder/style-states.mjs +100 -0
- package/builder/style-states.test.mjs +103 -0
- package/builder/vite-assets.mjs +53 -0
- package/builder/vite-project.mjs +10 -0
- package/config.ts +59 -0
- package/eslint.mjs +74 -0
- package/form/index.ts +526 -0
- package/form/package.json +13 -0
- package/motion/index.ts +2 -0
- package/motion/package.json +10 -0
- package/package.json +26 -4
- package/router/index.ts +50 -0
- package/router/navigation.ts +22 -0
- package/router/package.json +12 -0
- package/router/router-view.ts +134 -0
- package/router/routes.ts +64 -0
- package/scripts/addon-build.mjs +364 -0
- package/scripts/addon-project.mjs +78 -0
- package/scripts/kumi-cli.mjs +105 -0
- package/scripts/link-addons.mjs +61 -0
- package/src/bindings.ts +35 -0
- package/src/context.ts +15 -0
- package/src/css-tokens.ts +239 -0
- package/src/css-v1.ts +68 -0
- package/src/cvars.ts +91 -0
- package/src/element-node.ts +32 -0
- package/src/elements.ts +505 -0
- package/src/feature-scope.ts +82 -0
- package/src/flex-layout.ts +807 -0
- package/src/frame-scheduler.ts +336 -0
- package/src/grid-tracks.ts +165 -0
- package/src/image-imports.d.ts +24 -0
- package/src/images.ts +79 -0
- package/src/index.ts +29 -0
- package/src/jsx-dev-runtime.ts +2 -0
- package/src/jsx-runtime.ts +29 -0
- package/src/jsx.d.ts +12 -0
- package/src/keyed-list.ts +366 -0
- package/src/media-query.ts +144 -0
- package/src/module-ui.ts +147 -0
- package/src/module.ts +311 -0
- package/src/node-selectors.ts +114 -0
- package/src/owned-collections.ts +52 -0
- package/src/providers.ts +241 -0
- package/src/reactive-scope.ts +34 -0
- package/src/reactivity.ts +275 -0
- package/src/result.ts +64 -0
- package/src/runtime.ts +52 -0
- package/src/scheduler.ts +185 -0
- package/src/signal-kernel.ts +63 -0
- package/src/style-classes.ts +51 -0
- package/src/style-states.ts +134 -0
- package/src/style-variables.ts +53 -0
- package/src/text-children.ts +42 -0
- package/src/theme.ts +50 -0
- package/src/transition.ts +18 -0
- package/state/index.ts +9 -0
- package/state/package.json +12 -0
- package/state/setup-store-persistence.ts +206 -0
- package/state/setup-store-view.ts +10 -0
- package/state/setup-store.ts +342 -0
- package/state/store-bindings.ts +25 -0
- package/state/store.ts +84 -0
- package/styles/_layers.scss +14 -0
- package/templates/addon/.agents/skills/kumi-build-debug/SKILL.md +36 -0
- package/templates/addon/.agents/skills/kumi-feature/SKILL.md +50 -0
- package/templates/addon/.agents/skills/kumi-plugin/SKILL.md +36 -0
- package/templates/addon/.agents/skills/kumi-store/SKILL.md +47 -0
- package/templates/addon/.agents/skills/kumi-ui/SKILL.md +73 -0
- package/templates/addon/.agents/skills/kumi-wow-api/SKILL.md +30 -0
- package/templates/addon/.claude/skills/kumi-build-debug/SKILL.md +36 -0
- package/templates/addon/.claude/skills/kumi-feature/SKILL.md +50 -0
- package/templates/addon/.claude/skills/kumi-plugin/SKILL.md +36 -0
- package/templates/addon/.claude/skills/kumi-store/SKILL.md +47 -0
- package/templates/addon/.claude/skills/kumi-ui/SKILL.md +73 -0
- package/templates/addon/.claude/skills/kumi-wow-api/SKILL.md +30 -0
- package/templates/addon/AGENTS.md +34 -0
- package/templates/addon/Assets/Art/Corner10.tga +0 -0
- package/templates/addon/Assets/Art/Corner11.tga +0 -0
- package/templates/addon/Assets/Art/Corner12.tga +0 -0
- package/templates/addon/Assets/Art/Corner13.tga +0 -0
- package/templates/addon/Assets/Art/Corner14.tga +0 -0
- package/templates/addon/Assets/Art/Corner15.tga +0 -0
- package/templates/addon/Assets/Art/Corner16.tga +0 -0
- package/templates/addon/Assets/Art/Corner2.tga +0 -0
- package/templates/addon/Assets/Art/Corner3.tga +0 -0
- package/templates/addon/Assets/Art/Corner4.tga +0 -0
- package/templates/addon/Assets/Art/Corner5.tga +0 -0
- package/templates/addon/Assets/Art/Corner6.tga +0 -0
- package/templates/addon/Assets/Art/Corner7.tga +0 -0
- package/templates/addon/Assets/Art/Corner8.tga +0 -0
- package/templates/addon/Assets/Art/Corner9.tga +0 -0
- package/templates/addon/Assets/Art/Dot.tga +0 -0
- package/templates/addon/Assets/Art/Gear.tga +0 -0
- package/templates/addon/Assets/Art/Grip.tga +0 -0
- package/templates/addon/Assets/Art/Outline10.tga +0 -0
- package/templates/addon/Assets/Art/Outline12.tga +0 -0
- package/templates/addon/Assets/Art/Outline13.tga +0 -0
- package/templates/addon/Assets/Art/Outline14.tga +0 -0
- package/templates/addon/Assets/Art/Outline15.tga +0 -0
- package/templates/addon/Assets/Art/Outline2.tga +0 -0
- package/templates/addon/Assets/Art/Outline3.tga +0 -0
- package/templates/addon/Assets/Art/Outline5.tga +0 -0
- package/templates/addon/Assets/Art/Outline7.tga +0 -0
- package/templates/addon/Assets/Art/Outline9.tga +0 -0
- package/templates/addon/Assets/Art/Round11.tga +0 -0
- package/templates/addon/Assets/Art/Round11Border.tga +0 -0
- package/templates/addon/Assets/Art/Round4.tga +0 -0
- package/templates/addon/Assets/Art/Round4Border.tga +0 -0
- package/templates/addon/Assets/Art/Round6.tga +0 -0
- package/templates/addon/Assets/Art/Round6Border.tga +0 -0
- package/templates/addon/Assets/Art/Round8.tga +0 -0
- package/templates/addon/Assets/Art/Round8Border.tga +0 -0
- package/templates/addon/Assets/Art/Search.tga +0 -0
- package/templates/addon/CLAUDE.md +1 -0
- package/templates/addon/README.md +49 -0
- package/templates/addon/eslint.config.mjs +6 -0
- package/templates/addon/gitignore +9 -0
- package/templates/addon/kumi.config.ts +17 -0
- package/templates/addon/package.json +20 -0
- package/templates/addon/src/app/app.module.ts +18 -0
- package/templates/addon/src/app/commands.store.ts +11 -0
- package/templates/addon/src/app/layout/AppWindow.module.scss +92 -0
- package/templates/addon/src/app/layout/AppWindow.tsx +32 -0
- package/templates/addon/src/app/main.ts +5 -0
- package/templates/addon/src/app/routes/(window)/home/page.tsx +8 -0
- package/templates/addon/src/app/routes/(window)/plugins/page.tsx +38 -0
- package/templates/addon/src/app/routes/(window)/settings/page.tsx +8 -0
- package/templates/addon/src/app/theme.ts +6 -0
- package/templates/addon/src/modules/greeting/api/player.api.ts +29 -0
- package/templates/addon/src/modules/greeting/greeting.module.ts +18 -0
- package/templates/addon/src/modules/greeting/model/greeting.store.ts +81 -0
- package/templates/addon/src/modules/greeting/services/greeting.service.ts +38 -0
- package/templates/addon/src/modules/greeting/ui/Greeting.module.scss +105 -0
- package/templates/addon/src/modules/greeting/ui/GreetingCard.tsx +29 -0
- package/templates/addon/src/modules/greeting/widgets/GreetingHud.tsx +54 -0
- package/templates/addon/src/modules/greeting/widgets/GreetingOverview.tsx +18 -0
- package/templates/addon/src/modules/greeting/widgets/GreetingSettings.tsx +56 -0
- package/templates/addon/src/modules/playtime/api/clock.api.ts +6 -0
- package/templates/addon/src/modules/playtime/model/playtime.store.ts +19 -0
- package/templates/addon/src/modules/playtime/playtime.module.ts +18 -0
- package/templates/addon/src/modules/playtime/services/playtime.service.ts +18 -0
- package/templates/addon/src/modules/playtime/ui/Playtime.module.scss +25 -0
- package/templates/addon/src/modules/playtime/ui/PlaytimeBadge.tsx +10 -0
- package/templates/addon/src/modules/playtime/widgets/PlaytimePage.tsx +16 -0
- package/templates/addon/src/shared/api/native-art.ts +28 -0
- package/templates/addon/src/shared/assets/close.png +0 -0
- package/templates/addon/src/shared/lib/format.ts +20 -0
- package/templates/addon/src/shared/styles/_tokens.scss +12 -0
- package/templates/addon/src/shared/ui/Button.tsx +29 -0
- package/templates/addon/src/shared/ui/Choice.tsx +34 -0
- package/templates/addon/src/shared/ui/Controls.module.scss +93 -0
- package/templates/addon/src/shared/ui/Glyph.tsx +18 -0
- package/templates/addon/src/shared/ui/Slider.tsx +25 -0
- package/templates/addon/src/shared/ui/Toggle.tsx +29 -0
- package/templates/addon/src/shared/ui/focus-ref.ts +7 -0
- package/templates/addon/src/shared/ui/range-skin.tsx +15 -0
- package/templates/addon/tsconfig.json +63 -0
- package/translate/index.ts +14 -0
- package/translate/package.json +9 -0
- package/utils/colors.ts +76 -0
- package/utils/format.ts +37 -0
- package/utils/index.ts +4 -0
- package/utils/number.ts +17 -0
- package/utils/package.json +7 -0
- package/utils/text.ts +6 -0
- package/validate/index.ts +119 -0
- package/validate/package.json +9 -0
- package/wow/absolute-position.ts +142 -0
- package/wow/action-bar-layout.ts +108 -0
- package/wow/action-button.ts +219 -0
- package/wow/action-catalog.ts +98 -0
- package/wow/addon-manifest.ts +36 -0
- package/wow/animation.ts +428 -0
- package/wow/app-ui.ts +221 -0
- package/wow/aura-button.ts +76 -0
- package/wow/aura-container.ts +591 -0
- package/wow/aura-countdown.ts +201 -0
- package/wow/aura-slot.ts +153 -0
- package/wow/bar-shade.ts +93 -0
- package/wow/borrowed-slot.ts +216 -0
- package/wow/button-drag.ts +48 -0
- package/wow/cast-clock.ts +153 -0
- package/wow/cast-text.ts +83 -0
- package/wow/class-colors.ts +126 -0
- package/wow/clock.ts +7 -0
- package/wow/color-picker.ts +128 -0
- package/wow/commands.ts +17 -0
- package/wow/contained-frame.ts +128 -0
- package/wow/contract.ts +42 -0
- package/wow/cooldown-timing.ts +24 -0
- package/wow/css-box.ts +144 -0
- package/wow/css-color.ts +12 -0
- package/wow/css-style.ts +109 -0
- package/wow/css-surfaces.ts +603 -0
- package/wow/css-text.ts +399 -0
- package/wow/cursor.ts +45 -0
- package/wow/cvar-schema.ts +32 -0
- package/wow/cvars.ts +98 -0
- package/wow/dropdown-art.ts +39 -0
- package/wow/element-click.ts +20 -0
- package/wow/element-event-coordinator.ts +219 -0
- package/wow/element-events.ts +317 -0
- package/wow/event-dispatcher.ts +151 -0
- package/wow/events.ts +50 -0
- package/wow/font-cache.ts +92 -0
- package/wow/frame-access.ts +53 -0
- package/wow/frame-layer.ts +5 -0
- package/wow/frame-timing.ts +13 -0
- package/wow/frames.ts +236 -0
- package/wow/heal-prediction.ts +305 -0
- package/wow/hooks.ts +133 -0
- package/wow/image-layers.ts +55 -0
- package/wow/index.ts +111 -0
- package/wow/layout-view.ts +663 -0
- package/wow/locale-font.ts +15 -0
- package/wow/lua-string.ts +18 -0
- package/wow/lua-table.ts +18 -0
- package/wow/macro-book.ts +84 -0
- package/wow/map-position.ts +27 -0
- package/wow/media-query.ts +65 -0
- package/wow/module-events.ts +11 -0
- package/wow/native-hooks.ts +168 -0
- package/wow/native-placement.ts +88 -0
- package/wow/native.ts +153 -0
- package/wow/number-format.ts +8 -0
- package/wow/number-input.ts +10 -0
- package/wow/panel-host.ts +97 -0
- package/wow/pixel.ts +35 -0
- package/wow/plugins.ts +246 -0
- package/wow/protect.ts +48 -0
- package/wow/protected-layout.ts +133 -0
- package/wow/protected-view.ts +103 -0
- package/wow/range-art.ts +81 -0
- package/wow/readable-api.ts +120 -0
- package/wow/reparent-frame.ts +99 -0
- package/wow/rounded-texture.ts +183 -0
- package/wow/saved-variables.ts +109 -0
- package/wow/scroll-view.ts +64 -0
- package/wow/secret-ref.ts +14 -0
- package/wow/secure-bindings.ts +89 -0
- package/wow/secure-clicks.ts +432 -0
- package/wow/secure-snippet.ts +235 -0
- package/wow/secure-state.ts +130 -0
- package/wow/secure-target-visibility.ts +89 -0
- package/wow/secure-transaction.ts +331 -0
- package/wow/special-window.ts +269 -0
- package/wow/spell-cooldown.ts +36 -0
- package/wow/start-addon.ts +122 -0
- package/wow/state-paint.ts +256 -0
- package/wow/transition.ts +86 -0
- package/wow/unit-button.ts +39 -0
- package/wow/unit-cast.ts +92 -0
- package/wow/unit-health-text.ts +47 -0
- package/wow/view-nodes.ts +304 -0
- package/wow/view.ts +1864 -0
- package/wow/visible-frame-job.ts +34 -0
- package/wow/width-reserve.ts +108 -0
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
import { ownedArray, ownedSet, type OwnedArray, type OwnedReadonlyArray, type OwnedRecord, type OwnedSet } from "../src/owned-collections";
|
|
2
|
+
import { guardSetupSignal, setupRefKind, type Ref } from "../src/reactivity";
|
|
3
|
+
import { fail, formatFailure, ok, type Result } from "../src/result";
|
|
4
|
+
import type { RuntimeScope } from "../src/runtime";
|
|
5
|
+
import type { Cancel } from "../src/scheduler";
|
|
6
|
+
import type { StoreStorage } from "./store";
|
|
7
|
+
|
|
8
|
+
type Snapshot = Record<string, unknown>;
|
|
9
|
+
export interface StorePersistence {
|
|
10
|
+
readonly pick: OwnedReadonlyArray<string>;
|
|
11
|
+
readonly perCharacter?: boolean;
|
|
12
|
+
readonly storage?: StoreStorage<Snapshot>;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** Saves one store's batched field writes, or puts the fields back when storage rejects them. */
|
|
16
|
+
interface PendingSave {
|
|
17
|
+
flush(this: void): Result<void>;
|
|
18
|
+
rollback(this: void): void;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
let batchDepth = 0;
|
|
22
|
+
let pendingSaves: OwnedArray<PendingSave> | undefined;
|
|
23
|
+
|
|
24
|
+
function requireSuccess<T>(result: Result<T>): T {
|
|
25
|
+
if (!result.ok) throw new Error(formatFailure(result));
|
|
26
|
+
return result.value;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function settle(failure?: Result<never>) {
|
|
30
|
+
const saves = pendingSaves;
|
|
31
|
+
pendingSaves = undefined;
|
|
32
|
+
if (saves === undefined) return failure;
|
|
33
|
+
if (failure !== undefined) {
|
|
34
|
+
for (const save of saves) save.rollback();
|
|
35
|
+
return failure;
|
|
36
|
+
}
|
|
37
|
+
let result: Result<never> | undefined;
|
|
38
|
+
for (const save of saves) {
|
|
39
|
+
if (result !== undefined) {
|
|
40
|
+
save.rollback();
|
|
41
|
+
continue;
|
|
42
|
+
}
|
|
43
|
+
const saved = save.flush();
|
|
44
|
+
if (!saved.ok) result = saved;
|
|
45
|
+
}
|
|
46
|
+
return result;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Run several store writes as one change. Each store saves its persisted fields once at the end.
|
|
51
|
+
* If the callback throws or storage rejects a save, that store's fields return to their previous values.
|
|
52
|
+
*/
|
|
53
|
+
export function batch<T>(this: void, run: (this: void) => T): Result<T> {
|
|
54
|
+
batchDepth++;
|
|
55
|
+
let value: T;
|
|
56
|
+
try {
|
|
57
|
+
value = run();
|
|
58
|
+
} catch (problem) {
|
|
59
|
+
batchDepth--;
|
|
60
|
+
const failure = fail(String(problem));
|
|
61
|
+
return batchDepth === 0 ? settle(failure) ?? failure : failure;
|
|
62
|
+
}
|
|
63
|
+
batchDepth--;
|
|
64
|
+
if (batchDepth > 0) return ok(value);
|
|
65
|
+
return settle() ?? ok(value);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function deferStoreWatches(scope: RuntimeScope) {
|
|
69
|
+
const { watch, watchEffect } = scope;
|
|
70
|
+
const pending = ownedArray<(this: void) => void>();
|
|
71
|
+
|
|
72
|
+
function defer(start: (this: void) => Result<Cancel>): Result<Cancel> {
|
|
73
|
+
let cancelled = false;
|
|
74
|
+
let stop: Cancel | undefined;
|
|
75
|
+
pending.push(() => {
|
|
76
|
+
if (cancelled) return;
|
|
77
|
+
const attached = requireSuccess(start());
|
|
78
|
+
if (cancelled) attached();
|
|
79
|
+
else stop = attached;
|
|
80
|
+
});
|
|
81
|
+
return ok(() => {
|
|
82
|
+
cancelled = true;
|
|
83
|
+
stop?.();
|
|
84
|
+
stop = undefined;
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
scope.watch = (read, change, options) => defer(() => watch(read, change, options));
|
|
89
|
+
scope.watchEffect = effect => defer(() => watchEffect(effect));
|
|
90
|
+
const restore = () => {
|
|
91
|
+
scope.watch = watch;
|
|
92
|
+
scope.watchEffect = watchEffect;
|
|
93
|
+
};
|
|
94
|
+
const unregister = requireSuccess(scope.onDispose(restore));
|
|
95
|
+
return () => {
|
|
96
|
+
unregister();
|
|
97
|
+
restore();
|
|
98
|
+
for (const start of pending) start();
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export function hydrateSetupStore(id: string, scope: RuntimeScope, pick: OwnedReadonlyArray<string>, storage: StoreStorage<Snapshot>,
|
|
103
|
+
cells: Readonly<Record<string, Ref<unknown>>>) {
|
|
104
|
+
const selected = ownedArray<{ key: string; cell: Ref<unknown> }>();
|
|
105
|
+
const peek = ownedArray<(this: void) => unknown>();
|
|
106
|
+
const seen = ownedSet<Ref<unknown>>();
|
|
107
|
+
for (const key of pick) {
|
|
108
|
+
const cell = cells[key];
|
|
109
|
+
if (cell === undefined || setupRefKind(cell) !== "signal") throw new Error("Persisted field " + key + " needs a Kumi ref");
|
|
110
|
+
if (seen.has(cell)) throw new Error("Persisted field " + key + " repeats a ref");
|
|
111
|
+
seen.add(cell);
|
|
112
|
+
selected.push({ key, cell });
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
if (storage.claim !== undefined) requireSuccess(scope.onDispose(requireSuccess(storage.claim(id))));
|
|
116
|
+
const restored = requireSuccess(storage.read());
|
|
117
|
+
let committed: Snapshot = {};
|
|
118
|
+
let writing = false;
|
|
119
|
+
let hydrated = false;
|
|
120
|
+
let restoring = false;
|
|
121
|
+
// Lua tables drop nil values, so the changed keys are tracked separately from their previous values.
|
|
122
|
+
let changed: OwnedSet<string> | undefined;
|
|
123
|
+
let previous: Snapshot = {};
|
|
124
|
+
|
|
125
|
+
function snapshot(): Snapshot {
|
|
126
|
+
const next: Snapshot = {};
|
|
127
|
+
for (let index = 0; index < selected.length; index++) next[selected[index].key] = peek[index]();
|
|
128
|
+
return next;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function write(next: Snapshot, name: string) {
|
|
132
|
+
writing = true;
|
|
133
|
+
try {
|
|
134
|
+
const written = storage.write(next);
|
|
135
|
+
if (!written.ok) return fail("Could not save " + name + ": " + formatFailure(written));
|
|
136
|
+
committed = next;
|
|
137
|
+
return ok(undefined);
|
|
138
|
+
} finally {
|
|
139
|
+
writing = false;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
const save: PendingSave = {
|
|
144
|
+
flush: () => {
|
|
145
|
+
if (changed === undefined) return ok(undefined);
|
|
146
|
+
const saved = write(snapshot(), "store " + id);
|
|
147
|
+
if (!saved.ok) {
|
|
148
|
+
save.rollback();
|
|
149
|
+
return saved;
|
|
150
|
+
}
|
|
151
|
+
changed = undefined;
|
|
152
|
+
previous = {};
|
|
153
|
+
return saved;
|
|
154
|
+
},
|
|
155
|
+
rollback: () => {
|
|
156
|
+
const keys = changed;
|
|
157
|
+
const values = previous;
|
|
158
|
+
changed = undefined;
|
|
159
|
+
previous = {};
|
|
160
|
+
if (keys === undefined) return;
|
|
161
|
+
restoring = true;
|
|
162
|
+
try {
|
|
163
|
+
for (const { key, cell } of selected) {
|
|
164
|
+
if (keys.has(key)) cell.value = values[key];
|
|
165
|
+
}
|
|
166
|
+
} finally {
|
|
167
|
+
restoring = false;
|
|
168
|
+
}
|
|
169
|
+
},
|
|
170
|
+
};
|
|
171
|
+
|
|
172
|
+
for (const field of selected) {
|
|
173
|
+
const { key, cell } = field;
|
|
174
|
+
const name = id + "." + key;
|
|
175
|
+
const guard = guardSetupSignal(cell, next => {
|
|
176
|
+
if (!hydrated || restoring) return;
|
|
177
|
+
if (writing) throw new Error("Reentrant write to persisted field " + name);
|
|
178
|
+
if (batchDepth > 0) {
|
|
179
|
+
let keys = changed;
|
|
180
|
+
if (keys === undefined) {
|
|
181
|
+
keys = ownedSet<string>();
|
|
182
|
+
changed = keys;
|
|
183
|
+
const saves = pendingSaves ??= ownedArray<PendingSave>();
|
|
184
|
+
saves.push(save);
|
|
185
|
+
}
|
|
186
|
+
if (!keys.has(key)) {
|
|
187
|
+
keys.add(key);
|
|
188
|
+
previous[key] = committed[key];
|
|
189
|
+
}
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
const result = write({ ...(committed as OwnedRecord<Snapshot>), [key]: next }, "field " + name);
|
|
193
|
+
if (!result.ok) throw new Error(result.reason);
|
|
194
|
+
});
|
|
195
|
+
if (guard === undefined) throw new Error("Persisted field " + key + " already has a storage owner");
|
|
196
|
+
requireSuccess(scope.onDispose(guard.detach));
|
|
197
|
+
peek.push(guard.peek);
|
|
198
|
+
}
|
|
199
|
+
for (let index = 0; index < selected.length; index++) {
|
|
200
|
+
const { key, cell } = selected[index];
|
|
201
|
+
const value = restored?.[key];
|
|
202
|
+
if (value !== undefined) cell.value = value;
|
|
203
|
+
committed[key] = peek[index]();
|
|
204
|
+
}
|
|
205
|
+
hydrated = true;
|
|
206
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/** @internal The native compiler lowers this accessor view to a Lua metatable. */
|
|
2
|
+
export interface StoreAccessor {
|
|
3
|
+
readonly get: (this: void) => unknown;
|
|
4
|
+
readonly set?: (this: void, value: unknown) => void;
|
|
5
|
+
readonly enumerable: true;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export function createSetupStoreView(fields: Record<string, unknown>, accessors: Record<string, StoreAccessor>): object {
|
|
9
|
+
return Object.defineProperties(fields, accessors);
|
|
10
|
+
}
|
|
@@ -0,0 +1,342 @@
|
|
|
1
|
+
import { direct, fail, formatFailure, ok, type Result } from "../src/result";
|
|
2
|
+
import { withReactiveScope } from "../src/reactive-scope";
|
|
3
|
+
import { setupRefKind, type ComputedRef, type ReadonlyRef, type Ref, type SignalRef } from "../src/reactivity";
|
|
4
|
+
import type { RuntimeScope } from "../src/runtime";
|
|
5
|
+
import type { ServiceToken } from "../src/providers";
|
|
6
|
+
import { ownedArray, ownedMap, ownedWeakMap, type OwnedMap, type OwnedReadonlyArray, type OwnedWeakMap } from "../src/owned-collections";
|
|
7
|
+
import { batch, deferStoreWatches, hydrateSetupStore, type StorePersistence } from "./setup-store-persistence";
|
|
8
|
+
import { createSetupStoreView, type StoreAccessor } from "./setup-store-view";
|
|
9
|
+
import type { StoreStorage } from "./store";
|
|
10
|
+
|
|
11
|
+
declare const setupStoreShape: unique symbol;
|
|
12
|
+
declare const readonlySource: unique symbol;
|
|
13
|
+
|
|
14
|
+
/** A read-only view of a store ref. Actions still write the original ref. */
|
|
15
|
+
export interface StoreReadonly<T> extends ReadonlyRef<T> {
|
|
16
|
+
readonly [readonlySource]: true;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
type StoreField<Value> = Value extends SignalRef<infer State> ? State
|
|
20
|
+
: Value extends ComputedRef<infer State> ? State
|
|
21
|
+
: Value extends StoreReadonly<infer State> ? State : Value;
|
|
22
|
+
type WritableStoreKeys<Source> = {
|
|
23
|
+
[Key in keyof Source]-?: Source[Key] extends SignalRef<unknown> ? Key : never
|
|
24
|
+
}[keyof Source];
|
|
25
|
+
type ReadonlyStoreKeys<Source> = {
|
|
26
|
+
[Key in keyof Source]-?: Source[Key] extends StoreReadonly<unknown> ? Key : never
|
|
27
|
+
}[keyof Source];
|
|
28
|
+
type StorePatch<Source> = { [Key in WritableStoreKeys<Source>]?: StoreField<Source[Key]> };
|
|
29
|
+
|
|
30
|
+
/** Members Kumi adds to every store. */
|
|
31
|
+
export interface StoreApi<Source extends object> {
|
|
32
|
+
/** The ID passed to defineStore. */
|
|
33
|
+
readonly $id: string;
|
|
34
|
+
/** Write several writable fields as one change. Persisted fields are saved once. */
|
|
35
|
+
$patch(this: void, values: StorePatch<Source>): Result<void>;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export type SetupStore<Source extends object> = {
|
|
39
|
+
-readonly [Key in WritableStoreKeys<Source>]: StoreField<Source[Key]>
|
|
40
|
+
} & {
|
|
41
|
+
readonly [Key in Exclude<keyof Source, WritableStoreKeys<Source>>]: StoreField<Source[Key]>
|
|
42
|
+
} & StoreApi<Source> & { readonly [setupStoreShape]: Source };
|
|
43
|
+
|
|
44
|
+
export type SetupStoreRefs<Source extends object> = {
|
|
45
|
+
[Key in keyof Source as Source[Key] extends SignalRef<unknown> | ComputedRef<unknown> | StoreReadonly<unknown> ? Key : never]:
|
|
46
|
+
Source[Key] extends ComputedRef<infer State> ? ReadonlyRef<State>
|
|
47
|
+
: Source[Key] extends StoreReadonly<infer State> ? ReadonlyRef<State> : Source[Key]
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
type PersistedStoreKey<Source> = (WritableStoreKeys<Source> | ReadonlyStoreKeys<Source>) & string;
|
|
51
|
+
|
|
52
|
+
export interface SetupStoreOptions<Source extends object, Key extends PersistedStoreKey<Source>> {
|
|
53
|
+
readonly persist?: {
|
|
54
|
+
/** Refs to save. A field exposed through readonly() can be saved too. */
|
|
55
|
+
readonly pick: readonly Key[];
|
|
56
|
+
/** Save in the addon's per-character SavedVariables instead of the account-wide one. */
|
|
57
|
+
readonly perCharacter?: boolean;
|
|
58
|
+
/** Defaults to the addon's SavedVariables, under this store's ID. */
|
|
59
|
+
readonly storage?: StoreStorage<{ [Field in NoInfer<Key>]: StoreField<Source[Field]> }>;
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** The function defineStore returns. Call it to get the store. */
|
|
64
|
+
export type StoreFactory<Source extends object> = (this: void, owner?: RuntimeScope) => SetupStore<Source>;
|
|
65
|
+
/** Any function returned by defineStore, as listed in a module's `stores`. */
|
|
66
|
+
export type AnyStoreFactory = (this: void, owner?: RuntimeScope) => object;
|
|
67
|
+
|
|
68
|
+
type Inject = (this: void, token: ServiceToken<object>) => Result<object>;
|
|
69
|
+
type DefaultStorage = (this: void, id: string, defaults: Readonly<Record<string, unknown>>, perCharacter: boolean) =>
|
|
70
|
+
StoreStorage<Record<string, unknown>> | undefined;
|
|
71
|
+
|
|
72
|
+
interface StoreDefinition {
|
|
73
|
+
readonly id: string;
|
|
74
|
+
readonly setup: (this: void) => object;
|
|
75
|
+
readonly persistence?: StorePersistence;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
interface StoreSlot {
|
|
79
|
+
readonly definition: StoreDefinition;
|
|
80
|
+
store?: object;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
interface Registration {
|
|
84
|
+
readonly owner: RuntimeScope;
|
|
85
|
+
readonly resolve?: Inject;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** @internal The stores of one addon: one instance per store ID, shared by every module and load-on-demand part. */
|
|
89
|
+
export interface StoreHost {
|
|
90
|
+
readonly registrations: OwnedMap<StoreDefinition, Registration>;
|
|
91
|
+
readonly instances: OwnedMap<string, StoreSlot>;
|
|
92
|
+
readonly root: (this: void) => RuntimeScope | undefined;
|
|
93
|
+
storage?: DefaultStorage;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
class ReadonlyView<T> implements ReadonlyRef<T> {
|
|
97
|
+
constructor(readonly source: Ref<T>) {}
|
|
98
|
+
|
|
99
|
+
get value(): T {
|
|
100
|
+
return this.source.value;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
class StoreComputed<T> implements ReadonlyRef<T> {
|
|
105
|
+
constructor(private readonly source: ComputedRef<T>, private readonly name: string) {}
|
|
106
|
+
|
|
107
|
+
get value(): T {
|
|
108
|
+
const value = this.source.value;
|
|
109
|
+
if (!value.ok) throw new Error(this.name + ": " + formatFailure(value));
|
|
110
|
+
return value.value;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const definitions = ownedWeakMap<AnyStoreFactory, StoreDefinition>();
|
|
115
|
+
let owners: OwnedWeakMap<RuntimeScope, OwnedMap<string, StoreSlot>> | undefined;
|
|
116
|
+
let bindings: OwnedWeakMap<object, object> | undefined;
|
|
117
|
+
const opening: string[] = [];
|
|
118
|
+
let activeHost: StoreHost | undefined;
|
|
119
|
+
let activeInject: Inject | undefined;
|
|
120
|
+
|
|
121
|
+
/** Expose a ref read-only. Store actions keep writing the ref you pass in. */
|
|
122
|
+
export function readonly<T>(this: void, source: Ref<T>): StoreReadonly<T> {
|
|
123
|
+
return new ReadonlyView(source) as unknown as StoreReadonly<T>;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Get a service inside a store's setup. The store must be listed in a module's `stores`,
|
|
128
|
+
* and the token must be one of that module's providers or an export of a module it imports.
|
|
129
|
+
*/
|
|
130
|
+
export function inject<Value extends object>(this: void, token: abstract new (...dependencies: never[]) => Value): Value;
|
|
131
|
+
export function inject<Value extends object>(this: void, token: ServiceToken<Value>): Value;
|
|
132
|
+
export function inject<Value extends object>(this: void, token: ServiceToken<Value>): Value {
|
|
133
|
+
const resolve = activeInject;
|
|
134
|
+
if (resolve === undefined) {
|
|
135
|
+
throw new Error("inject(" + token.name + ") works only inside the setup of a store listed in a module's stores");
|
|
136
|
+
}
|
|
137
|
+
const result = resolve(token);
|
|
138
|
+
if (!result.ok) throw new Error(formatFailure(result));
|
|
139
|
+
return result.value as Value;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function createStoreFields(id: string, source: Record<string, unknown>) {
|
|
143
|
+
const fields: Record<string, unknown> = {};
|
|
144
|
+
const accessors: Record<string, StoreAccessor> = {};
|
|
145
|
+
const refs: Record<string, ReadonlyRef<unknown>> = {};
|
|
146
|
+
const cells: Record<string, Ref<unknown>> = {};
|
|
147
|
+
for (const key of Object.keys(source)) {
|
|
148
|
+
if (key === "$id" || key === "$patch") throw new Error("Store " + id + " cannot declare " + key);
|
|
149
|
+
const value = source[key];
|
|
150
|
+
const kind = setupRefKind(value);
|
|
151
|
+
if (kind === "signal") {
|
|
152
|
+
const cell = value as Ref<unknown>;
|
|
153
|
+
refs[key] = cell;
|
|
154
|
+
cells[key] = cell;
|
|
155
|
+
accessors[key] = { get: () => cell.value, set: next => { cell.value = next; }, enumerable: true };
|
|
156
|
+
} else if (kind === "computed") {
|
|
157
|
+
const cell = new StoreComputed(value as ComputedRef<unknown>, id + "." + key);
|
|
158
|
+
refs[key] = cell;
|
|
159
|
+
accessors[key] = { get: () => cell.value, enumerable: true };
|
|
160
|
+
} else if (value instanceof ReadonlyView) {
|
|
161
|
+
const view = value as ReadonlyView<unknown>;
|
|
162
|
+
refs[key] = view;
|
|
163
|
+
cells[key] = view.source;
|
|
164
|
+
accessors[key] = { get: () => view.value, enumerable: true };
|
|
165
|
+
} else {
|
|
166
|
+
fields[key] = value;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
fields.$id = id;
|
|
170
|
+
fields.$patch = (values: Record<string, unknown>) => batch(() => {
|
|
171
|
+
for (const key of Object.keys(values)) {
|
|
172
|
+
const accessor = accessors[key];
|
|
173
|
+
const write = accessor?.set;
|
|
174
|
+
if (write === undefined) throw new Error("Store " + id + " cannot patch " + key + ": it is not a writable ref");
|
|
175
|
+
write(values[key]);
|
|
176
|
+
}
|
|
177
|
+
});
|
|
178
|
+
return { store: createSetupStoreView(fields, accessors), refs, cells };
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function protectLocalSetup<T>(this: void, run: (this: void) => T): Result<T> {
|
|
182
|
+
try {
|
|
183
|
+
return ok(run());
|
|
184
|
+
} catch (problem) {
|
|
185
|
+
return fail(String(problem));
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function defaultsOf(pick: OwnedReadonlyArray<string>, cells: Readonly<Record<string, Ref<unknown>>>) {
|
|
190
|
+
const defaults: Record<string, unknown> = {};
|
|
191
|
+
for (const key of pick) {
|
|
192
|
+
const cell = cells[key];
|
|
193
|
+
if (cell !== undefined) defaults[key] = cell.value;
|
|
194
|
+
}
|
|
195
|
+
return defaults;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** Open one instance in a registry, or return the instance it already holds. */
|
|
199
|
+
function openStore(definition: StoreDefinition, owner: RuntimeScope, registry: OwnedMap<string, StoreSlot>,
|
|
200
|
+
resolve: Inject | undefined, storage: DefaultStorage | undefined): object {
|
|
201
|
+
const { id, setup, persistence } = definition;
|
|
202
|
+
if (!owner.isActive()) throw new Error("Store " + id + " needs an active owner");
|
|
203
|
+
const existing = registry.get(id);
|
|
204
|
+
if (existing !== undefined) {
|
|
205
|
+
if (existing.definition !== definition) throw new Error("Duplicate store ID: " + id);
|
|
206
|
+
if (existing.store === undefined) throw new Error("Circular store dependency: " + [...opening, id].join(" -> "));
|
|
207
|
+
return existing.store;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
const scope = owner.fork();
|
|
211
|
+
if (scope.protect === direct) scope.protect = protectLocalSetup;
|
|
212
|
+
const slot: StoreSlot = { definition };
|
|
213
|
+
registry.set(id, slot);
|
|
214
|
+
opening.push(id);
|
|
215
|
+
const previousInject = activeInject;
|
|
216
|
+
activeInject = resolve;
|
|
217
|
+
let opened = false;
|
|
218
|
+
try {
|
|
219
|
+
const ready = withReactiveScope(scope, () => {
|
|
220
|
+
if (persistence === undefined || persistence.pick.length === 0) {
|
|
221
|
+
return createStoreFields(id, setup() as Record<string, unknown>);
|
|
222
|
+
}
|
|
223
|
+
const startWatches = deferStoreWatches(scope);
|
|
224
|
+
const fields = createStoreFields(id, setup() as Record<string, unknown>);
|
|
225
|
+
const perCharacter = persistence.perCharacter === true;
|
|
226
|
+
const chosen = persistence.storage ?? storage?.(id, defaultsOf(persistence.pick, fields.cells), perCharacter);
|
|
227
|
+
if (chosen === undefined) {
|
|
228
|
+
throw new Error("Store " + id + " persists fields but has no storage. Set addon."
|
|
229
|
+
+ (perCharacter ? "savedVariablesPerCharacter" : "savedVariables") + " in kumi.config.ts or pass persist.storage.");
|
|
230
|
+
}
|
|
231
|
+
hydrateSetupStore(id, scope, persistence.pick, chosen, fields.cells);
|
|
232
|
+
startWatches();
|
|
233
|
+
return fields;
|
|
234
|
+
});
|
|
235
|
+
if (!ready.ok) throw new Error("Store " + id + ": " + formatFailure(ready));
|
|
236
|
+
const { store, refs } = ready.value;
|
|
237
|
+
const registered = scope.onDispose(() => {
|
|
238
|
+
bindings?.delete(store);
|
|
239
|
+
if (registry.get(id) === slot) registry.delete(id);
|
|
240
|
+
});
|
|
241
|
+
if (!registered.ok) throw new Error("Store " + id + ": " + formatFailure(registered));
|
|
242
|
+
const referenceMap = bindings ??= ownedWeakMap<object, object>();
|
|
243
|
+
referenceMap.set(store, refs);
|
|
244
|
+
slot.store = store;
|
|
245
|
+
opened = true;
|
|
246
|
+
return store;
|
|
247
|
+
} finally {
|
|
248
|
+
activeInject = previousInject;
|
|
249
|
+
opening.pop();
|
|
250
|
+
if (!opened) {
|
|
251
|
+
if (registry.get(id) === slot) registry.delete(id);
|
|
252
|
+
scope.dispose();
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
function openOwned(definition: StoreDefinition, owner: RuntimeScope) {
|
|
258
|
+
const registry = owners ??= ownedWeakMap<RuntimeScope, OwnedMap<string, StoreSlot>>();
|
|
259
|
+
let group = registry.get(owner);
|
|
260
|
+
if (group === undefined) {
|
|
261
|
+
group = ownedMap<string, StoreSlot>();
|
|
262
|
+
registry.set(owner, group);
|
|
263
|
+
}
|
|
264
|
+
return openStore(definition, owner, group, undefined, activeHost?.storage);
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
function openHosted(host: StoreHost, definition: StoreDefinition) {
|
|
268
|
+
const registration = host.registrations.get(definition);
|
|
269
|
+
const owner = registration?.owner ?? host.root();
|
|
270
|
+
if (owner === undefined) throw new Error("Store " + definition.id + " needs a running addon");
|
|
271
|
+
return openStore(definition, owner, host.instances, registration?.resolve, host.storage);
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/**
|
|
275
|
+
* Define a store. Call the returned function anywhere in the addon to get its single instance.
|
|
276
|
+
* List it in a module's `stores` when its setup uses inject().
|
|
277
|
+
*/
|
|
278
|
+
export function defineStore<Source extends object, Key extends PersistedStoreKey<Source> = PersistedStoreKey<Source>>(
|
|
279
|
+
id: string, setup: (this: void) => Source, options?: SetupStoreOptions<NoInfer<Source>, Key>,
|
|
280
|
+
): StoreFactory<Source> {
|
|
281
|
+
const persist = options?.persist;
|
|
282
|
+
const definition: StoreDefinition = {
|
|
283
|
+
id,
|
|
284
|
+
setup: setup as (this: void) => object,
|
|
285
|
+
persistence: persist === undefined ? undefined : {
|
|
286
|
+
pick: persist.pick as unknown as OwnedReadonlyArray<string>,
|
|
287
|
+
perCharacter: persist.perCharacter,
|
|
288
|
+
storage: persist.storage as unknown as StoreStorage<Record<string, unknown>> | undefined,
|
|
289
|
+
},
|
|
290
|
+
};
|
|
291
|
+
const useStore = (owner?: RuntimeScope) => {
|
|
292
|
+
if (owner !== undefined) return openOwned(definition, owner) as SetupStore<Source>;
|
|
293
|
+
const host = activeHost;
|
|
294
|
+
if (host === undefined) throw new Error("Store " + id + " needs a running addon. Call it after startAddon, or pass an owner scope.");
|
|
295
|
+
return openHosted(host, definition) as SetupStore<Source>;
|
|
296
|
+
};
|
|
297
|
+
definitions.set(useStore, definition);
|
|
298
|
+
return useStore;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/** Return the store's refs for JSX bindings: writable refs stay writable, computed and readonly fields are read-only. */
|
|
302
|
+
export function storeToRefs<Source extends object>(store: SetupStore<Source>): SetupStoreRefs<Source> {
|
|
303
|
+
const refs = bindings?.get(store);
|
|
304
|
+
if (refs === undefined) throw new Error("Expected an active Kumi setup store");
|
|
305
|
+
return refs as SetupStoreRefs<Source>;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/** @internal Create the store host of a module container. */
|
|
309
|
+
export function createStoreHost(this: void, root: (this: void) => RuntimeScope | undefined): StoreHost {
|
|
310
|
+
const host: StoreHost = { registrations: ownedMap(), instances: ownedMap(), root };
|
|
311
|
+
activeHost = host;
|
|
312
|
+
return host;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/** @internal Make the host current, for example when an addon starts. */
|
|
316
|
+
export function activateStoreHost(this: void, host: StoreHost): void {
|
|
317
|
+
activeHost = host;
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/** @internal Register and open a module's stores in the module scope. */
|
|
321
|
+
export function openModuleStores(this: void, host: StoreHost, moduleId: string, stores: OwnedReadonlyArray<AnyStoreFactory>,
|
|
322
|
+
owner: RuntimeScope, resolve: Inject): Result<void> {
|
|
323
|
+
const chosen = ownedArray<StoreDefinition>();
|
|
324
|
+
for (const factory of stores) {
|
|
325
|
+
const definition = definitions.get(factory);
|
|
326
|
+
if (definition === undefined) return fail("Module " + moduleId + ": stores accepts functions returned by defineStore");
|
|
327
|
+
const other = host.registrations.get(definition);
|
|
328
|
+
if (other !== undefined) return fail("Module " + moduleId + ": store " + definition.id + " is already provided by another module");
|
|
329
|
+
chosen.push(definition);
|
|
330
|
+
}
|
|
331
|
+
for (const definition of chosen) host.registrations.set(definition, { owner, resolve });
|
|
332
|
+
const released = owner.onDispose(() => {
|
|
333
|
+
for (const definition of chosen) host.registrations.delete(definition);
|
|
334
|
+
});
|
|
335
|
+
if (!released.ok) return released;
|
|
336
|
+
activeHost = host;
|
|
337
|
+
for (const definition of chosen) {
|
|
338
|
+
const opened = protectLocalSetup(() => openStore(definition, owner, host.instances, resolve, host.storage));
|
|
339
|
+
if (!opened.ok) return fail("Module " + moduleId + ": " + opened.reason);
|
|
340
|
+
}
|
|
341
|
+
return ok(undefined);
|
|
342
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { ref, type ReadonlyRef, type Ref } from "../src/reactivity";
|
|
2
|
+
|
|
3
|
+
export function createStore<State extends object>(read: <K extends keyof State>(this: void, key: K) => State[K]) {
|
|
4
|
+
const fields = new Map<keyof State, Ref<State[keyof State]>>();
|
|
5
|
+
|
|
6
|
+
function field<K extends keyof State>(key: K): ReadonlyRef<State[K]> {
|
|
7
|
+
let value = fields.get(key);
|
|
8
|
+
if (!value) {
|
|
9
|
+
value = ref(read(key));
|
|
10
|
+
fields.set(key, value);
|
|
11
|
+
}
|
|
12
|
+
return value as ReadonlyRef<State[K]>;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function sync(key?: keyof State) {
|
|
16
|
+
if (key !== undefined) {
|
|
17
|
+
const value = fields.get(key);
|
|
18
|
+
if (value) value.value = read(key);
|
|
19
|
+
return;
|
|
20
|
+
}
|
|
21
|
+
for (const [field, value] of fields) value.value = read(field);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
return { field, sync };
|
|
25
|
+
}
|
package/state/store.ts
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { ownedArray, type OwnedRecord } from "../src/owned-collections";
|
|
2
|
+
import type { ReadonlyRef } from "../src/reactivity";
|
|
3
|
+
import { fail, ok, type Result } from "../src/result";
|
|
4
|
+
import { createStore } from "./store-bindings";
|
|
5
|
+
|
|
6
|
+
export { createStore };
|
|
7
|
+
|
|
8
|
+
// A store owns the snapshot. A host may supply synchronous storage for it.
|
|
9
|
+
export interface StoreStorage<State extends object> {
|
|
10
|
+
read(this: void): Result<Partial<State> | undefined>;
|
|
11
|
+
write(this: void, snapshot: Readonly<State>): Result<void>;
|
|
12
|
+
/** Reserve the storage for one open store. Return the release callback, or fail when another store holds it. */
|
|
13
|
+
claim?(this: void, owner: string): Result<(this: void) => void>;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
type StateKey<State> = keyof State & string;
|
|
17
|
+
|
|
18
|
+
export interface StateStore<State extends object> {
|
|
19
|
+
field<K extends StateKey<State>>(this: void, key: K): ReadonlyRef<State[K]>;
|
|
20
|
+
set<K extends StateKey<State>>(this: void, key: K, value: NoInfer<State[K]>): Result<void>;
|
|
21
|
+
patch(this: void, values: Partial<State>): Result<void>;
|
|
22
|
+
reset(this: void): Result<void>;
|
|
23
|
+
snapshot(this: void): Readonly<State>;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function createStateStore<State extends object>(defaults: State, storage?: StoreStorage<NoInfer<State>>): Result<StateStore<State>> {
|
|
27
|
+
const restored = storage?.read();
|
|
28
|
+
if (restored && !restored.ok) return restored;
|
|
29
|
+
const initial = {} as State;
|
|
30
|
+
for (const key of Object.keys(defaults) as StateKey<State>[]) {
|
|
31
|
+
const value = defaults[key];
|
|
32
|
+
if (value != null) initial[key] = value;
|
|
33
|
+
}
|
|
34
|
+
const keys = Object.keys(initial) as StateKey<State>[];
|
|
35
|
+
const writable = new Set<StateKey<State>>();
|
|
36
|
+
for (const key of keys) writable.add(key);
|
|
37
|
+
let current = { ...initial };
|
|
38
|
+
const { field, sync } = createStore<State>(key => current[key as StateKey<State>] as State[typeof key]);
|
|
39
|
+
|
|
40
|
+
function snapshot(): State {
|
|
41
|
+
return { ...(current as OwnedRecord<State>) };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function apply(next: State): Result<void> {
|
|
45
|
+
const changed = ownedArray<StateKey<State>>();
|
|
46
|
+
for (const key of keys) if (next[key] !== current[key]) changed.push(key);
|
|
47
|
+
if (changed.length === 0) return ok(undefined);
|
|
48
|
+
const written = storage?.write(next);
|
|
49
|
+
if (written && !written.ok) return written;
|
|
50
|
+
current = next;
|
|
51
|
+
for (const key of changed) sync(key);
|
|
52
|
+
return ok(undefined);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
for (const key of keys) {
|
|
56
|
+
const value = restored?.value?.[key];
|
|
57
|
+
if (value !== undefined) current[key] = value;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function patch(values: Partial<State>): Result<void> {
|
|
61
|
+
const next = snapshot();
|
|
62
|
+
for (const key of Object.keys(values) as StateKey<State>[]) {
|
|
63
|
+
const value = values[key];
|
|
64
|
+
if (value == null) continue;
|
|
65
|
+
if (!writable.has(key)) return fail("Unknown state field " + String(key));
|
|
66
|
+
next[key] = value;
|
|
67
|
+
}
|
|
68
|
+
return apply(next);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function set<K extends StateKey<State>>(key: K, value: NoInfer<State[K]>): Result<void> {
|
|
72
|
+
if (value == null) return fail("Use a concrete value for " + String(key));
|
|
73
|
+
if (!writable.has(key)) return fail("Unknown state field " + String(key));
|
|
74
|
+
return apply({ ...(current as OwnedRecord<State>), [key]: value });
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
return ok({
|
|
78
|
+
field,
|
|
79
|
+
set,
|
|
80
|
+
patch,
|
|
81
|
+
reset: () => apply({ ...initial }),
|
|
82
|
+
snapshot,
|
|
83
|
+
});
|
|
84
|
+
}
|