@platforma-sdk/ui-vue 1.82.1 → 1.83.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.
Files changed (50) hide show
  1. package/.turbo/turbo-build.log +12 -15
  2. package/.turbo/turbo-formatter$colon$check.log +2 -2
  3. package/.turbo/turbo-linter$colon$check.log +2 -2
  4. package/.turbo/turbo-types$colon$check.log +1 -1
  5. package/CHANGELOG.md +45 -0
  6. package/dist/components/PlAnnotations/components/PlAnnotations.vue2.js.map +1 -1
  7. package/dist/defineApp.d.ts +2 -32
  8. package/dist/defineApp.d.ts.map +1 -1
  9. package/dist/defineApp.js +20 -62
  10. package/dist/defineApp.js.map +1 -1
  11. package/dist/index.js +39 -39
  12. package/dist/internal/createAppV3.js +16 -16
  13. package/dist/lib/util/helpers/dist/utils.js +2 -5
  14. package/dist/lib/util/helpers/dist/utils.js.map +1 -1
  15. package/dist/lib.js +1 -1
  16. package/package.json +7 -7
  17. package/src/defineApp.ts +1 -183
  18. package/dist/internal/createAppModel.d.ts +0 -7
  19. package/dist/internal/createAppModel.d.ts.map +0 -1
  20. package/dist/internal/createAppModel.js +0 -57
  21. package/dist/internal/createAppModel.js.map +0 -1
  22. package/dist/internal/createAppV1.d.ts +0 -53
  23. package/dist/internal/createAppV1.d.ts.map +0 -1
  24. package/dist/internal/createAppV1.js +0 -129
  25. package/dist/internal/createAppV1.js.map +0 -1
  26. package/dist/internal/createAppV2.d.ts +0 -50
  27. package/dist/internal/createAppV2.d.ts.map +0 -1
  28. package/dist/internal/createAppV2.js +0 -137
  29. package/dist/internal/createAppV2.js.map +0 -1
  30. package/dist/internal/createAppV2.test.d.ts +0 -15
  31. package/dist/internal/createAppV2.test.d.ts.map +0 -1
  32. package/dist/internal/test-helpers/BlockMock.d.ts +0 -29
  33. package/dist/internal/test-helpers/BlockMock.d.ts.map +0 -1
  34. package/dist/internal/test-helpers/createMockApi.d.ts +0 -4
  35. package/dist/internal/test-helpers/createMockApi.d.ts.map +0 -1
  36. package/dist/internal/test-helpers/utils.d.ts +0 -4
  37. package/dist/internal/test-helpers/utils.d.ts.map +0 -1
  38. package/dist/internal/v1.static-test.d.ts +0 -7
  39. package/dist/internal/v1.static-test.d.ts.map +0 -1
  40. package/dist/internal/v2.static-test.d.ts +0 -7
  41. package/dist/internal/v2.static-test.d.ts.map +0 -1
  42. package/src/internal/createAppModel.ts +0 -112
  43. package/src/internal/createAppV1.ts +0 -324
  44. package/src/internal/createAppV2.test.ts +0 -207
  45. package/src/internal/createAppV2.ts +0 -392
  46. package/src/internal/test-helpers/BlockMock.ts +0 -161
  47. package/src/internal/test-helpers/createMockApi.ts +0 -104
  48. package/src/internal/test-helpers/utils.ts +0 -65
  49. package/src/internal/v1.static-test.ts +0 -107
  50. package/src/internal/v2.static-test.ts +0 -107
@@ -1,324 +0,0 @@
1
- import { deepClone, isJsonEqual, tap } from "@milaboratories/helpers";
2
- import type { Mutable } from "@milaboratories/helpers";
3
- import type {
4
- NavigationState,
5
- BlockOutputsBase,
6
- BlockState,
7
- PlatformaV1,
8
- PlatformaExtended,
9
- } from "@platforma-sdk/model";
10
- import { reactive, nextTick, computed, watch } from "vue";
11
- import type {
12
- StateModelOptions,
13
- UnwrapOutputs,
14
- OptionalResult,
15
- OutputValues,
16
- OutputErrors,
17
- AppSettings,
18
- } from "../types";
19
- import { createModel } from "../createModel";
20
- import { createAppModel } from "./createAppModel";
21
- import { parseQuery } from "../urls";
22
- import { ensureOutputHasStableFlag, MultiError, unwrapOutput } from "../utils";
23
- import { useDebounceFn } from "@vueuse/core";
24
- /**
25
- * Creates an application instance with reactive state management, outputs, and methods for state updates and navigation.
26
- *
27
- * @template Args - The type of arguments used in the application.
28
- * @template Outputs - The type of block outputs extending `BlockOutputsBase`.
29
- * @template UiState - The type of the UI state.
30
- * @template Href - The type of navigation href, defaulting to a string starting with `/`.
31
- *
32
- * @param state - Initial state of the application, including args, outputs, UI state, and navigation state.
33
- * @param platforma - A platform interface for interacting with block states.
34
- * @param settings - Application settings, such as debug flags.
35
- *
36
- * @returns A reactive application object with methods, getters, and state.
37
- */
38
- export function createAppV1<
39
- Args = unknown,
40
- Outputs extends BlockOutputsBase = BlockOutputsBase,
41
- UiState = unknown,
42
- Href extends `/${string}` = `/${string}`,
43
- >(
44
- state: BlockState<Args, Outputs, UiState, Href>,
45
- platforma: PlatformaExtended<PlatformaV1<Args, Outputs, UiState, Href>>,
46
- settings: AppSettings,
47
- ) {
48
- type AppModel = {
49
- args: Args;
50
- ui: UiState;
51
- };
52
-
53
- const log = (msg: string, ...rest: unknown[]) => {
54
- if (settings.debug) {
55
- console.log(`%c>>> %c${msg}`, "color: orange; font-weight: bold", "color: orange", ...rest);
56
- }
57
- };
58
-
59
- /**
60
- * Reactive snapshot of the application state, including args, outputs, UI state, and navigation state.
61
- */
62
- const snapshot = reactive({
63
- args: Object.freeze(state.args),
64
- outputs: Object.freeze(state.outputs),
65
- ui: Object.freeze(state.ui),
66
- navigationState: Object.freeze(state.navigationState) as NavigationState<Href>,
67
- }) as {
68
- args: Readonly<Args>;
69
- outputs: Partial<Readonly<Outputs>>;
70
- ui: Readonly<UiState>;
71
- navigationState: Readonly<NavigationState<Href>>;
72
- };
73
-
74
- const debounceSpan = settings.debounceSpan ?? 200;
75
-
76
- const maxWait = tap(settings.debounceMaxWait ?? 0, (v) =>
77
- v < 20_000 ? 20_000 : v < debounceSpan ? debounceSpan * 100 : v,
78
- );
79
-
80
- const setBlockArgs = useDebounceFn(
81
- (args: Args) => {
82
- if (!isJsonEqual(args, snapshot.args)) {
83
- platforma.setBlockArgs(args);
84
- }
85
- },
86
- debounceSpan,
87
- { maxWait },
88
- );
89
-
90
- const setBlockUiState = useDebounceFn(
91
- (ui: UiState) => {
92
- if (!isJsonEqual(ui, snapshot.ui)) {
93
- platforma.setBlockUiState(ui);
94
- }
95
- },
96
- debounceSpan,
97
- { maxWait },
98
- );
99
-
100
- const setBlockArgsAndUiState = useDebounceFn(
101
- (args: Args, ui: UiState) => {
102
- if (!isJsonEqual(args, snapshot.args) || !isJsonEqual(ui, snapshot.ui)) {
103
- platforma.setBlockArgsAndUiState(args, ui);
104
- }
105
- },
106
- debounceSpan,
107
- { maxWait },
108
- );
109
-
110
- (platforma as PlatformaV1<Args, Outputs, UiState, Href>).onStateUpdates(async (updates) => {
111
- updates.forEach((patch) => {
112
- if (patch.key === "args" && !isJsonEqual(snapshot.args, patch.value)) {
113
- snapshot.args = Object.freeze(patch.value);
114
- log("args patch", snapshot.args);
115
- }
116
-
117
- if (patch.key === "ui" && !isJsonEqual(snapshot.ui, patch.value)) {
118
- snapshot.ui = Object.freeze(patch.value);
119
- log("ui patch", snapshot.ui);
120
- }
121
-
122
- if (patch.key === "outputs" && !isJsonEqual(snapshot.outputs, patch.value)) {
123
- snapshot.outputs = Object.freeze(patch.value);
124
- log("outputs patch", snapshot.outputs);
125
- }
126
-
127
- if (patch.key === "navigationState" && !isJsonEqual(snapshot.navigationState, patch.value)) {
128
- snapshot.navigationState = Object.freeze(patch.value);
129
- log("navigationState patch", snapshot.navigationState);
130
- }
131
- });
132
-
133
- await nextTick();
134
- });
135
-
136
- const cloneArgs = () => deepClone(snapshot.args) as Args;
137
- const cloneUiState = () => deepClone(snapshot.ui) as UiState;
138
- const cloneNavigationState = () =>
139
- deepClone(snapshot.navigationState) as Mutable<NavigationState<Href>>;
140
-
141
- const methods = {
142
- createArgsModel<T = Args>(options: StateModelOptions<Args, T> = {}) {
143
- return createModel<T, Args>({
144
- get() {
145
- if (options.transform) {
146
- return options.transform(snapshot.args);
147
- }
148
-
149
- return snapshot.args as T;
150
- },
151
- validate: options.validate,
152
- autoSave: true,
153
- onSave(newArgs) {
154
- setBlockArgs(newArgs);
155
- },
156
- });
157
- },
158
- /**
159
- * defaultUiState is temporarily here, remove it after implementing initialUiState
160
- */
161
- createUiModel<T = UiState>(
162
- options: StateModelOptions<UiState, T> = {},
163
- defaultUiState: () => UiState,
164
- ) {
165
- return createModel<T, UiState>({
166
- get() {
167
- if (options.transform) {
168
- return options.transform(snapshot.ui);
169
- }
170
-
171
- return (snapshot.ui ?? defaultUiState()) as T;
172
- },
173
- validate: options.validate,
174
- autoSave: true,
175
- onSave(newData) {
176
- setBlockUiState(newData);
177
- },
178
- });
179
- },
180
- /**
181
- * Note: Don't forget to list the output names, like: useOutputs('output1', 'output2', ...etc)
182
- * @param keys - List of output names
183
- * @returns {OptionalResult<UnwrapOutputs<Outputs, K>>}
184
- */
185
- useOutputs<K extends keyof Outputs>(...keys: K[]): OptionalResult<UnwrapOutputs<Outputs, K>> {
186
- const data = reactive({
187
- errors: undefined,
188
- value: undefined,
189
- });
190
-
191
- watch(
192
- () => snapshot.outputs,
193
- () => {
194
- try {
195
- Object.assign(data, {
196
- value: this.unwrapOutputs<K>(...keys),
197
- errors: undefined,
198
- });
199
- } catch (error) {
200
- Object.assign(data, {
201
- value: undefined,
202
- errors: [String(error)],
203
- });
204
- }
205
- },
206
- { immediate: true, deep: true },
207
- );
208
-
209
- return data as OptionalResult<UnwrapOutputs<Outputs, K>>;
210
- },
211
- /**
212
- * Retrieves the unwrapped values of outputs for the given keys.
213
- *
214
- * @template K - Keys of the outputs to unwrap.
215
- * @param keys - List of output names.
216
- * @throws Error if the outputs contain errors.
217
- * @returns An object with unwrapped output values.
218
- */
219
- unwrapOutputs<K extends keyof Outputs>(...keys: K[]): UnwrapOutputs<Outputs, K> {
220
- const outputs = snapshot.outputs;
221
- const entries = keys.map((key) => [key, unwrapOutput(outputs[key])]);
222
- return Object.fromEntries(entries);
223
- },
224
- /**
225
- * Updates the arguments state by applying a callback.
226
- *
227
- * @param cb - Callback to modify the current arguments.
228
- * @returns A promise resolving after the update is applied.
229
- */
230
- updateArgs(cb: (args: Args) => void) {
231
- const newArgs = cloneArgs();
232
- cb(newArgs);
233
- return platforma.setBlockArgs(newArgs);
234
- },
235
- /**
236
- * Updates the UI state by applying a callback.
237
- *
238
- * @param cb - Callback to modify the current UI state.
239
- * @returns A promise resolving after the update is applied.
240
- * @todo Make it mutable since there is already an initial one
241
- */
242
- updateUiState(cb: (args: UiState) => UiState): Promise<void> {
243
- const newUiState = cloneUiState();
244
- return platforma.setBlockUiState(cb(newUiState));
245
- },
246
- /**
247
- * Updates the navigation state by applying a callback.
248
- *
249
- * @param cb - Callback to modify the current navigation state.
250
- * @returns A promise resolving after the update is applied.
251
- */
252
- updateNavigationState(cb: (args: Mutable<NavigationState<Href>>) => void) {
253
- const newState = cloneNavigationState();
254
- cb(newState);
255
- return platforma.setNavigationState(newState);
256
- },
257
- /**
258
- * Navigates to a specific href by updating the navigation state.
259
- *
260
- * @param href - The target href to navigate to.
261
- * @returns A promise resolving after the navigation state is updated.
262
- */
263
- navigateTo(href: Href) {
264
- const newState = cloneNavigationState();
265
- newState.href = href;
266
- return platforma.setNavigationState(newState);
267
- },
268
- };
269
-
270
- const outputs = computed<OutputValues<Outputs>>(() => {
271
- const entries = Object.entries(snapshot.outputs).map(([k, outputWithStatus]) =>
272
- platforma.blockModelInfo.outputs[k].withStatus
273
- ? [k, ensureOutputHasStableFlag(outputWithStatus)]
274
- : [
275
- k,
276
- outputWithStatus.ok && outputWithStatus.value !== undefined
277
- ? outputWithStatus.value
278
- : undefined,
279
- ],
280
- );
281
- return Object.fromEntries(entries);
282
- });
283
-
284
- const outputErrors = computed<OutputErrors<Outputs>>(() => {
285
- const entries = Object.entries(snapshot.outputs).map(([k, vOrErr]) => [
286
- k,
287
- vOrErr && vOrErr.ok === false ? new MultiError(vOrErr.errors) : undefined,
288
- ]);
289
- return Object.fromEntries(entries);
290
- });
291
-
292
- const getters = {
293
- snapshot,
294
- queryParams: computed(() => parseQuery<Href>(snapshot.navigationState.href)),
295
- href: computed(() => snapshot.navigationState.href),
296
- hasErrors: computed(() => Object.values(snapshot.outputs).some((v) => !v?.ok)),
297
- };
298
-
299
- const model = createAppModel(
300
- {
301
- get() {
302
- return { args: snapshot.args, ui: snapshot.ui } as AppModel;
303
- },
304
- autoSave: true,
305
- onSave(newData: AppModel) {
306
- setBlockArgsAndUiState(newData.args, newData.ui);
307
- },
308
- },
309
- {
310
- outputs,
311
- outputErrors,
312
- },
313
- settings,
314
- );
315
-
316
- return reactive(Object.assign(model, methods, getters));
317
- }
318
-
319
- export type BaseAppV1<
320
- Args = unknown,
321
- Outputs extends BlockOutputsBase = BlockOutputsBase,
322
- UiState = unknown,
323
- Href extends `/${string}` = `/${string}`,
324
- > = ReturnType<typeof createAppV1<Args, Outputs, UiState, Href>>;
@@ -1,207 +0,0 @@
1
- import { describe, it, expect, vi, beforeEach } from "vitest";
2
- import { createAppV2 } from "./createAppV2";
3
- import { type OutputWithStatus, unwrapResult } from "@platforma-sdk/model";
4
- import { BlockStateMock } from "./test-helpers/BlockMock";
5
- import { BlockMock } from "./test-helpers/BlockMock";
6
- import { delay } from "@milaboratories/helpers";
7
- import { createMockApi } from "./test-helpers/createMockApi";
8
- import { watch } from "vue";
9
- import { patchPoolingDelay } from "./createAppV2";
10
-
11
- type Args = {
12
- x: number;
13
- y: number;
14
- };
15
-
16
- type UiState = {
17
- label: string;
18
- delay?: number;
19
- };
20
-
21
- const defaultArgs = () => ({
22
- x: 0,
23
- y: 0,
24
- });
25
-
26
- type Outputs = {
27
- sum: OutputWithStatus<number>;
28
- };
29
-
30
- const defaultOutputs = (): Outputs => {
31
- return {
32
- sum: {
33
- ok: true,
34
- value: 0,
35
- stable: true,
36
- },
37
- };
38
- };
39
-
40
- const defaultState = (): BlockStateMock<Args, Outputs, UiState, `/${string}`> => {
41
- return new BlockStateMock(defaultArgs(), defaultOutputs(), { label: "" }, "/");
42
- };
43
-
44
- class BlockSum extends BlockMock<Args, Outputs, UiState, `/${string}`> {
45
- async process(): Promise<void> {
46
- const { args, author } = this.state;
47
- this.state.setState({
48
- author,
49
- outputs: { sum: { ok: true, value: args.x + args.y, stable: true } },
50
- });
51
- }
52
- }
53
-
54
- export const platforma = createMockApi<Args, Outputs, UiState>(new BlockSum(defaultState()));
55
-
56
- describe("createApp", { timeout: 20_000 }, () => {
57
- beforeEach(() => {
58
- // Mock window.addEventListener to prevent actual event listeners
59
- vi.stubGlobal("window", {
60
- addEventListener: vi.fn(),
61
- });
62
- });
63
-
64
- it("should create an app with reactive snapshot", async () => {
65
- const initialState = await platforma.loadBlockState().then(unwrapResult);
66
-
67
- const app = createAppV2(
68
- initialState,
69
- {
70
- ...platforma,
71
- blockModelInfo: {
72
- outputs: {
73
- sum: { withStatus: false },
74
- },
75
- pluginIds: [],
76
- featureFlags: {},
77
- pluginPublicOutputs: {},
78
- },
79
- },
80
- { debug: true, debounceSpan: 10 },
81
- );
82
-
83
- expect(app.model.args).toEqual({ x: 0, y: 0 });
84
- expect(app.model.ui).toEqual({ label: "" });
85
- expect(app.snapshot.navigationState.href).toBe("/");
86
-
87
- let watchCountShallow = 0;
88
-
89
- watch(
90
- () => app.model.args,
91
- () => {
92
- watchCountShallow++;
93
- },
94
- );
95
-
96
- app.model.args.x = 1;
97
- app.model.args.y = 2;
98
-
99
- const t1 = performance.now();
100
- await app.allSettled();
101
- await delay(100);
102
- const t2 = performance.now();
103
- console.log("allSettled", t2 - t1);
104
-
105
- expect(app.model.args).toEqual(app.snapshot.args);
106
- expect(app.model.args).toEqual({ x: 1, y: 2 });
107
- expect(app.model.outputs.sum).toEqual(3);
108
-
109
- app.model.args.x = 3;
110
- app.model.args.y = 3;
111
-
112
- const t3 = performance.now();
113
- await app.allSettled();
114
- await delay(patchPoolingDelay + 10);
115
- const t4 = performance.now();
116
- console.log("allSettled", t4 - t3);
117
-
118
- expect(watchCountShallow).toBe(0); // no changes
119
-
120
- expect(app.model.args).toEqual(app.snapshot.args);
121
- expect(app.model.args).toEqual({ x: 3, y: 3 });
122
- expect(app.model.outputs.sum).toEqual(6);
123
-
124
- app.closedRef = true;
125
- });
126
-
127
- it("states should be synchronized", async () => {
128
- const sharedBlock = new BlockSum(defaultState());
129
- const platforma1 = createMockApi<Args, Outputs, UiState>(sharedBlock);
130
- const platforma2 = createMockApi<Args, Outputs, UiState>(sharedBlock);
131
-
132
- const initialState1 = await platforma1.loadBlockState().then(unwrapResult);
133
- const initialState2 = await platforma2.loadBlockState().then(unwrapResult);
134
-
135
- const app1 = createAppV2(
136
- initialState1,
137
- {
138
- ...platforma1,
139
- blockModelInfo: {
140
- outputs: {
141
- sum: { withStatus: false },
142
- },
143
- pluginIds: [],
144
- featureFlags: {},
145
- pluginPublicOutputs: {},
146
- },
147
- },
148
- { appId: "app1", debug: true, debounceSpan: 10 },
149
- );
150
- const app2 = createAppV2(
151
- initialState2,
152
- {
153
- ...platforma2,
154
- blockModelInfo: {
155
- outputs: {
156
- sum: { withStatus: false },
157
- },
158
- pluginIds: [],
159
- featureFlags: {},
160
- pluginPublicOutputs: {},
161
- },
162
- },
163
- { appId: "app2", debug: true, debounceSpan: 10 },
164
- );
165
-
166
- app1.model.args.x = 1;
167
- app1.model.args.y = 2;
168
-
169
- await app1.allSettled();
170
- await app2.allSettled();
171
-
172
- expect(app1.model.args).toEqual(app2.model.args);
173
- expect(app1.model.args).toEqual({ x: 1, y: 2 });
174
- expect(app1.model.outputs.sum).toEqual(3);
175
- expect(app2.model.outputs.sum).toEqual(3);
176
-
177
- app2.model.args.x = 3;
178
- app2.model.args.y = 4;
179
-
180
- await Promise.all([app1.allSettled(), app2.allSettled()]);
181
- await delay(patchPoolingDelay + 10);
182
-
183
- expect(app1.model.args).toEqual(app2.model.args);
184
- expect(app1.model.args).toEqual({ x: 3, y: 4 });
185
- expect(app1.model.outputs.sum).toEqual(7);
186
- expect(app2.model.outputs.sum).toEqual(7);
187
-
188
- app1.model.args.x = 5;
189
- app1.model.args.y = 5;
190
- app1.model.ui.delay = 20;
191
- await delay(5);
192
- app2.model.args.x = 7;
193
- app2.model.args.y = 7;
194
-
195
- await Promise.all([app1.allSettled(), app2.allSettled()]);
196
- await delay(patchPoolingDelay + 10);
197
-
198
- expect(app1.model.args).toEqual(app1.snapshot.args);
199
- expect(app1.model.args).toEqual(app2.model.args);
200
- expect(app1.model.args).toEqual({ x: 5, y: 5 });
201
- expect(app1.model.outputs.sum).toEqual(10);
202
- expect(app2.model.outputs.sum).toEqual(10);
203
-
204
- app1.closedRef = true;
205
- app2.closedRef = true;
206
- });
207
- });