@matreshka/bff 0.20.0 → 0.22.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/dist/components/board.d.ts +7 -0
- package/dist/components/board.js +7 -0
- package/dist/components/camera.d.ts +4 -0
- package/dist/components/camera.js +4 -0
- package/dist/components/component.d.ts +2 -1
- package/dist/components/dialog.d.ts +5 -0
- package/dist/components/dialog.js +8 -0
- package/dist/components/for-each.d.ts +3 -3
- package/dist/components/for-each.js +18 -26
- package/dist/components/inputs/text-editor.d.ts +17 -0
- package/dist/components/inputs/text-editor.js +17 -0
- package/dist/components/item-list/item-list.js +11 -11
- package/dist/components/item-list/list-from-ref-context.d.ts +4 -1
- package/dist/components/item-list/list-from-ref-context.js +6 -4
- package/dist/components/item-list/types.d.ts +5 -5
- package/dist/components/item-list/types.js +1 -1
- package/dist/components/map.d.ts +11 -0
- package/dist/components/map.js +7 -0
- package/dist/components/popover.d.ts +5 -0
- package/dist/components/popover.js +8 -0
- package/dist/components/stack.d.ts +4 -0
- package/dist/components/stack.js +4 -0
- package/dist/core/actions/close-entry.d.ts +15 -0
- package/dist/core/actions/close-entry.js +28 -0
- package/dist/core/actions/component-local-actions.d.ts +113 -0
- package/dist/core/actions/component-local-actions.js +274 -0
- package/dist/core/actions/dec-context-value.d.ts +21 -0
- package/dist/core/actions/dec-context-value.js +35 -0
- package/dist/core/actions/inc-context-value.d.ts +22 -0
- package/dist/core/actions/inc-context-value.js +35 -0
- package/dist/core/actions/local-action.d.ts +4 -0
- package/dist/core/actions/local-action.js +43 -0
- package/dist/core/actions/set-context.d.ts +20 -0
- package/dist/core/actions/set-context.js +33 -0
- package/dist/core/conditions/condition-operand.d.ts +5 -3
- package/dist/core/context/context-ref.d.ts +26 -4
- package/dist/core/context/context-ref.js +25 -8
- package/dist/core/context/context.d.ts +52 -10
- package/dist/core/context/context.js +87 -13
- package/dist/core/index.d.ts +3 -6
- package/dist/core/index.js +6 -6
- package/dist/core/local/index.d.ts +14 -0
- package/dist/core/local/index.js +18 -0
- package/dist/core/types/component-instance.d.ts +7 -0
- package/dist/core/types/component-instance.js +4 -0
- package/dist/core/types/context-value-ref.d.ts +5 -3
- package/dist/core/utils/replace-context-keys.js +1 -2
- package/package.json +2 -2
- package/dist/core/actions/set-context-value.d.ts +0 -21
- package/dist/core/actions/set-context-value.js +0 -34
- package/dist/core/actions/set-context-values.d.ts +0 -35
- package/dist/core/actions/set-context-values.js +0 -30
|
@@ -1,12 +1,32 @@
|
|
|
1
1
|
import { JsonObject } from "@matreshka/shared/types/json";
|
|
2
2
|
import { Paths, PathValue } from "ts-essentials";
|
|
3
|
+
import { ActionConfig } from "../actions/action";
|
|
4
|
+
import { DecContextValue } from "../actions/dec-context-value";
|
|
5
|
+
import { IncContextValue } from "../actions/inc-context-value";
|
|
6
|
+
import { SetContext } from "../actions/set-context";
|
|
7
|
+
import { ToggleContextValue } from "../actions/toggle-context-value";
|
|
8
|
+
import { ContextValueOrRef } from "../types/context-value-ref";
|
|
3
9
|
import { Context } from "./context";
|
|
10
|
+
type ContextRefLocalSet<ContextType extends JsonObject, PathType extends string> = {
|
|
11
|
+
set: (value: ContextValueOrRef<PathValue<ContextType, PathType>>, config?: ActionConfig) => SetContext<ContextType>;
|
|
12
|
+
};
|
|
13
|
+
type ContextRefLocalToggle = {
|
|
14
|
+
toggle: (config?: ActionConfig) => ToggleContextValue;
|
|
15
|
+
};
|
|
16
|
+
type ContextRefLocalNumeric = {
|
|
17
|
+
inc: (step?: ContextValueOrRef<number>, config?: ActionConfig) => IncContextValue;
|
|
18
|
+
dec: (step?: ContextValueOrRef<number>, config?: ActionConfig) => DecContextValue;
|
|
19
|
+
};
|
|
20
|
+
/** Локальные действия по ref; `toggle` / `inc` / `dec` — по типу значения по пути. */
|
|
21
|
+
export type ContextRefLocalActions<ContextType extends JsonObject, PathType extends string> = ContextRefLocalSet<ContextType, PathType> & (PathValue<ContextType, PathType> extends boolean | undefined ? ContextRefLocalToggle : {}) & (PathValue<ContextType, PathType> extends number | undefined ? ContextRefLocalNumeric : {});
|
|
4
22
|
export type ContextRefValue<R extends ContextRef> = R extends {
|
|
5
23
|
readonly __valueType?: infer ValueType;
|
|
6
24
|
} ? Exclude<ValueType, undefined> : R extends ContextRef<infer ContextType, infer PathType> ? PathValue<ContextType, PathType> : never;
|
|
7
25
|
export declare class ContextRef<ContextType extends JsonObject = JsonObject, PathType extends string = string> {
|
|
8
26
|
readonly context: Context<any>;
|
|
9
27
|
readonly path: PathType;
|
|
28
|
+
/** Локальные (client-only) действия по этому ref. */
|
|
29
|
+
readonly local: ContextRefLocalActions<ContextType, PathType>;
|
|
10
30
|
constructor(context: Context<any>, path: PathType);
|
|
11
31
|
/**
|
|
12
32
|
* Продолжение пути в рамках того же контекста.
|
|
@@ -23,7 +43,7 @@ export declare class ContextRef<ContextType extends JsonObject = JsonObject, Pat
|
|
|
23
43
|
* `@{<id контекста other>.<путь other>}` (через `other.toString()`), без подстановки
|
|
24
44
|
* значения на момент вызова.
|
|
25
45
|
*
|
|
26
|
-
* При каждом чтении
|
|
46
|
+
* При каждом чтении {@link Context.get} подставляет в эту строку актуальное значение по
|
|
27
47
|
* ссылке `other` (тот же механизм, что и для обычных путей с плейсхолдерами).
|
|
28
48
|
* Если во втором контексте меняется строка-сегмент пути или индекс, одна и та же
|
|
29
49
|
* ссылка `ContextRef` продолжает указывать на корректные данные.
|
|
@@ -42,12 +62,14 @@ export declare class ContextRef<ContextType extends JsonObject = JsonObject, Pat
|
|
|
42
62
|
* @experimental
|
|
43
63
|
*/
|
|
44
64
|
strictRef<OtherContextType extends JsonObject, OtherPathType extends Paths<OtherContextType>>(other: ContextRef<OtherContextType, OtherPathType>): ContextRef<ContextType, `${PathType}.${PathValue<OtherContextType, OtherPathType> & string}`>;
|
|
45
|
-
|
|
65
|
+
/** Значение по текущему пути (делегирует {@link Context.get}). */
|
|
66
|
+
get(): PathValue<ContextType, PathType>;
|
|
46
67
|
/**
|
|
47
|
-
* Запись значения по текущему пути через {@link Context.
|
|
68
|
+
* Запись значения по текущему пути через {@link Context.set}.
|
|
48
69
|
* Если контекст уже уничтожен, вызов игнорируется (без исключения).
|
|
49
70
|
*/
|
|
50
|
-
|
|
71
|
+
set(value: PathValue<ContextType, PathType>): void;
|
|
51
72
|
toString(): string;
|
|
52
73
|
toJSON(): string;
|
|
53
74
|
}
|
|
75
|
+
export {};
|
|
@@ -1,11 +1,27 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.ContextRef = void 0;
|
|
4
|
+
const dec_context_value_1 = require("../actions/dec-context-value");
|
|
5
|
+
const inc_context_value_1 = require("../actions/inc-context-value");
|
|
6
|
+
const set_context_1 = require("../actions/set-context");
|
|
7
|
+
const toggle_context_value_1 = require("../actions/toggle-context-value");
|
|
4
8
|
const client_context_1 = require("../client-context");
|
|
5
9
|
class ContextRef {
|
|
6
10
|
constructor(context, path) {
|
|
7
11
|
this.context = context;
|
|
8
12
|
this.path = path;
|
|
13
|
+
/** Локальные (client-only) действия по этому ref. */
|
|
14
|
+
this.local = {
|
|
15
|
+
set: (value, config) => {
|
|
16
|
+
const patch = {
|
|
17
|
+
[this.path]: value,
|
|
18
|
+
};
|
|
19
|
+
return (0, set_context_1.createSetContext)(this.context, patch, config);
|
|
20
|
+
},
|
|
21
|
+
toggle: (config) => (0, toggle_context_value_1.toggleContextValue)(this, config),
|
|
22
|
+
inc: (step = 1, config) => (0, inc_context_value_1.incContextValue)(this, step, config),
|
|
23
|
+
dec: (step = 1, config) => (0, dec_context_value_1.decContextValue)(this, step, config),
|
|
24
|
+
};
|
|
9
25
|
}
|
|
10
26
|
ref(path) {
|
|
11
27
|
if (path instanceof ContextRef) {
|
|
@@ -20,7 +36,7 @@ class ContextRef {
|
|
|
20
36
|
* `@{<id контекста other>.<путь other>}` (через `other.toString()`), без подстановки
|
|
21
37
|
* значения на момент вызова.
|
|
22
38
|
*
|
|
23
|
-
* При каждом чтении
|
|
39
|
+
* При каждом чтении {@link Context.get} подставляет в эту строку актуальное значение по
|
|
24
40
|
* ссылке `other` (тот же механизм, что и для обычных путей с плейсхолдерами).
|
|
25
41
|
* Если во втором контексте меняется строка-сегмент пути или индекс, одна и та же
|
|
26
42
|
* ссылка `ContextRef` продолжает указывать на корректные данные.
|
|
@@ -42,20 +58,21 @@ class ContextRef {
|
|
|
42
58
|
const fullPath = `${this.path}.${other.toString()}`;
|
|
43
59
|
return new ContextRef(this.context, fullPath);
|
|
44
60
|
}
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
return this.context.value(this.path);
|
|
61
|
+
/** Значение по текущему пути (делегирует {@link Context.get}). */
|
|
62
|
+
get() {
|
|
63
|
+
return this.context.get(this.path);
|
|
49
64
|
}
|
|
50
65
|
/**
|
|
51
|
-
* Запись значения по текущему пути через {@link Context.
|
|
66
|
+
* Запись значения по текущему пути через {@link Context.set}.
|
|
52
67
|
* Если контекст уже уничтожен, вызов игнорируется (без исключения).
|
|
53
68
|
*/
|
|
54
|
-
|
|
69
|
+
set(value) {
|
|
55
70
|
if (this.context.isDestroyed()) {
|
|
56
71
|
return;
|
|
57
72
|
}
|
|
58
|
-
this.context.
|
|
73
|
+
this.context.set({
|
|
74
|
+
[this.path]: value,
|
|
75
|
+
});
|
|
59
76
|
}
|
|
60
77
|
toString() {
|
|
61
78
|
return `@{${this.context.id}.${this.path}}`;
|
|
@@ -1,9 +1,16 @@
|
|
|
1
1
|
import { JsonObject } from "@matreshka/shared/types/json";
|
|
2
|
-
import { BehaviorSubject } from "rxjs";
|
|
2
|
+
import { BehaviorSubject, Observable } from "rxjs";
|
|
3
3
|
import { Paths, PathValue } from "ts-essentials";
|
|
4
4
|
import { ZodObject } from "zod/v4";
|
|
5
|
+
import { ActionConfig } from "../actions/action";
|
|
6
|
+
import { LocalContextPathPatch } from "../actions/set-context";
|
|
5
7
|
import type { Client } from "../client";
|
|
8
|
+
import { ContextValueOrRef } from "../types/context-value-ref";
|
|
6
9
|
import { ContextRef } from "./context-ref";
|
|
10
|
+
/** Частичное обновление данных контекста по dotted-путям (см. {@link Context.set}). */
|
|
11
|
+
export type ContextPathPatch<T extends JsonObject> = Partial<{
|
|
12
|
+
[K in Paths<T>]: PathValue<T, K>;
|
|
13
|
+
}>;
|
|
7
14
|
/**
|
|
8
15
|
* Контекст данных, связанных с клиентом.
|
|
9
16
|
*
|
|
@@ -16,7 +23,7 @@ export declare class Context<T extends JsonObject> {
|
|
|
16
23
|
/** Уникальный идентификатор контекста */
|
|
17
24
|
readonly id: `${string}-${string}-${string}-${string}-${string}`;
|
|
18
25
|
/** Реактивное хранилище данных контекста. */
|
|
19
|
-
data$?: BehaviorSubject<T>;
|
|
26
|
+
protected data$?: BehaviorSubject<T>;
|
|
20
27
|
/** Схема валидации данных контекста */
|
|
21
28
|
readonly schema?: ZodObject;
|
|
22
29
|
/** Флаг, указывающий, что контекст должен быть инициализирован при авторизации клиента */
|
|
@@ -26,9 +33,16 @@ export declare class Context<T extends JsonObject> {
|
|
|
26
33
|
* Явный {@link destroy} по-прежнему обязателен, если данные не нужны весь runtime.
|
|
27
34
|
*/
|
|
28
35
|
readonly persistent: boolean;
|
|
36
|
+
/** Локальные (client-only) действия над данными этого контекста. */
|
|
37
|
+
readonly local: {
|
|
38
|
+
set: (patch: LocalContextPathPatch<T>, config?: ActionConfig) => import("../actions/set-context").SetContext<T>;
|
|
39
|
+
toggle: <K extends Paths<T>>(path: PathValue<T, K> extends boolean | undefined ? K : never, config?: ActionConfig) => import("../actions/toggle-context-value").ToggleContextValue;
|
|
40
|
+
inc: <K extends Paths<T>>(path: PathValue<T, K> extends number | undefined ? K : never, step?: ContextValueOrRef<number>, config?: ActionConfig) => import("../actions/inc-context-value").IncContextValue;
|
|
41
|
+
dec: <K extends Paths<T>>(path: PathValue<T, K> extends number | undefined ? K : never, step?: ContextValueOrRef<number>, config?: ActionConfig) => import("../actions/dec-context-value").DecContextValue;
|
|
42
|
+
};
|
|
29
43
|
/** Реактивное хранилище инициализации контекста */
|
|
30
44
|
private _init$;
|
|
31
|
-
readonly init$:
|
|
45
|
+
readonly init$: Observable<void>;
|
|
32
46
|
/**
|
|
33
47
|
* Отслеживает, было ли изменение данных инициировано клиентом.
|
|
34
48
|
* Если да — синхронизация с клиентом не требуется.
|
|
@@ -42,6 +56,7 @@ export declare class Context<T extends JsonObject> {
|
|
|
42
56
|
private dataSubscription?;
|
|
43
57
|
private clientSubscriptions;
|
|
44
58
|
private assertNotDestroyed;
|
|
59
|
+
private assertInitialized;
|
|
45
60
|
/** Ошибка загрузки initDataCallback — в error$ всех клиентов, привязанных к контексту. */
|
|
46
61
|
private reportInitFailureToClients;
|
|
47
62
|
/**
|
|
@@ -85,18 +100,45 @@ export declare class Context<T extends JsonObject> {
|
|
|
85
100
|
* Возвращает значение из контекста по указанному пути.
|
|
86
101
|
*
|
|
87
102
|
* Путь может содержать плейсхолдеры, которые будут заменены актуальными значениями.
|
|
103
|
+
* Объекты и массивы — **копия** ({@link structuredClone}); in-place мутация результата
|
|
104
|
+
* не меняет контекст. Для снимка всего `T` — {@link snapshot}.
|
|
88
105
|
*
|
|
89
106
|
* @param path Строка с путём до значения.
|
|
90
107
|
* @returns Значение по заданному пути или undefined.
|
|
91
108
|
*/
|
|
92
|
-
|
|
93
|
-
setValue<K extends Paths<T>>(path: K, value: PathValue<T, K>): void;
|
|
109
|
+
get<K extends Paths<T>>(path: K): PathValue<T, K>;
|
|
94
110
|
/**
|
|
95
|
-
*
|
|
96
|
-
*
|
|
97
|
-
*
|
|
111
|
+
* Частичное обновление данных по dotted-путям одним вызовом `next`.
|
|
112
|
+
*
|
|
113
|
+
* Предпочтительный способ правки нескольких полей на BFF. Ключ с явным
|
|
114
|
+
* `undefined` применяется (отличие от отсутствующего ключа в patch).
|
|
115
|
+
* Для целого снимка после load — {@link replace}.
|
|
116
|
+
*/
|
|
117
|
+
set(patch: ContextPathPatch<T>): void;
|
|
118
|
+
/**
|
|
119
|
+
* Полная замена корня контекста (результат load, `{ ...loaded, field }`).
|
|
120
|
+
*
|
|
121
|
+
* Не merge patch: переданный объект становится новым состоянием целиком.
|
|
122
|
+
*/
|
|
123
|
+
replace(data: T): void;
|
|
124
|
+
/**
|
|
125
|
+
* Глубокая копия всего `T` (structured clone корня).
|
|
126
|
+
*
|
|
127
|
+
* Для одного поля — {@link get}. Нужен, когда на время async нужен отсоединённый
|
|
128
|
+
* снимок всего состояния, а не ссылка на живые данные.
|
|
129
|
+
*/
|
|
130
|
+
snapshot(): T;
|
|
131
|
+
/**
|
|
132
|
+
* Read-only поток данных контекста для подписок и RxJS-операторов.
|
|
133
|
+
*
|
|
134
|
+
* Если {@link init} ещё не создал хранилище, подписка **ждёт** успешного init
|
|
135
|
+
* ({@link init$}), затем ведёт себя как после init. При {@link destroy} до init
|
|
136
|
+
* поток завершается без эмиссий.
|
|
137
|
+
*
|
|
138
|
+
* После подключения сразу эмитит текущее состояние, затем каждое обновление
|
|
139
|
+
* через {@link set}, {@link replace} и т.п.
|
|
98
140
|
*/
|
|
99
|
-
|
|
141
|
+
watch(): Observable<T>;
|
|
100
142
|
/**
|
|
101
143
|
|
|
102
144
|
* @param path Путь до значения.
|
|
@@ -107,7 +149,7 @@ export declare class Context<T extends JsonObject> {
|
|
|
107
149
|
* Ссылка на значение в **этом** контексте по пути, который задаётся **во втором**
|
|
108
150
|
* контексте строкой и меняется во времени.
|
|
109
151
|
*
|
|
110
|
-
* В отличие от прямого чтения `other.
|
|
152
|
+
* В отличие от прямого чтения `other.get()` при создании ссылки, в путь записывается
|
|
111
153
|
* только плейсхолдер `@{<id контекста other>.<путь other>}` (см. `ContextRef.toString`).
|
|
112
154
|
* При каждом обращении `Context.value` подставляет актуальное значение поля `other`;
|
|
113
155
|
* это уже строка-путь относительно корня текущего контекста (например `cards.1.balance`).
|
|
@@ -7,6 +7,10 @@ const targeted_message_1 = require("@matreshka/shared/messages/targeted-message"
|
|
|
7
7
|
const fetch_from_object_1 = require("@matreshka/shared/utils/fetch-from-object");
|
|
8
8
|
const rxjs_1 = require("rxjs");
|
|
9
9
|
const v4_1 = require("zod/v4");
|
|
10
|
+
const dec_context_value_1 = require("../actions/dec-context-value");
|
|
11
|
+
const inc_context_value_1 = require("../actions/inc-context-value");
|
|
12
|
+
const set_context_1 = require("../actions/set-context");
|
|
13
|
+
const toggle_context_value_1 = require("../actions/toggle-context-value");
|
|
10
14
|
const client_context_1 = require("../client-context");
|
|
11
15
|
const deep_pick_1 = require("../utils/deep-pick");
|
|
12
16
|
const incoming_message_observer_1 = require("../utils/incoming-message-observer");
|
|
@@ -14,6 +18,13 @@ const objects_diff_1 = require("../utils/objects-diff");
|
|
|
14
18
|
const replace_context_keys_1 = require("../utils/replace-context-keys");
|
|
15
19
|
const set_object_property_1 = require("../utils/set-object-property");
|
|
16
20
|
const context_ref_1 = require("./context-ref");
|
|
21
|
+
/** Отделяет чтение через {@link Context.get} от живого дерева в хранилище. */
|
|
22
|
+
function cloneGetResult(value) {
|
|
23
|
+
if (value !== null && typeof value === "object") {
|
|
24
|
+
return structuredClone(value);
|
|
25
|
+
}
|
|
26
|
+
return value;
|
|
27
|
+
}
|
|
17
28
|
/** Глобальный реестр контекстов: lookup по id, привязки к клиентам, учёт init. */
|
|
18
29
|
const contextRegistry = new Map();
|
|
19
30
|
function registerContext(context) {
|
|
@@ -70,6 +81,11 @@ class Context {
|
|
|
70
81
|
throw new Error(`Context ${this.id} has been destroyed`);
|
|
71
82
|
}
|
|
72
83
|
}
|
|
84
|
+
assertInitialized() {
|
|
85
|
+
if (!this.data$) {
|
|
86
|
+
throw new Error(`Context ${this.id} is not initialized`);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
73
89
|
/** Ошибка загрузки initDataCallback — в error$ всех клиентов, привязанных к контексту. */
|
|
74
90
|
reportInitFailureToClients(error) {
|
|
75
91
|
getRegistryEntry(this.id)?.clients.forEach((_, client) => {
|
|
@@ -85,6 +101,13 @@ class Context {
|
|
|
85
101
|
constructor(config) {
|
|
86
102
|
/** Уникальный идентификатор контекста */
|
|
87
103
|
this.id = crypto.randomUUID();
|
|
104
|
+
/** Локальные (client-only) действия над данными этого контекста. */
|
|
105
|
+
this.local = {
|
|
106
|
+
set: (patch, config) => (0, set_context_1.createSetContext)(this, patch, config),
|
|
107
|
+
toggle: (path, config) => (0, toggle_context_value_1.toggleContextValue)(this.ref(path), config),
|
|
108
|
+
inc: (path, step, config) => (0, inc_context_value_1.incContextValue)(this.ref(path), step ?? 1, config),
|
|
109
|
+
dec: (path, step, config) => (0, dec_context_value_1.decContextValue)(this.ref(path), step ?? 1, config),
|
|
110
|
+
};
|
|
88
111
|
/** Реактивное хранилище инициализации контекста */
|
|
89
112
|
this._init$ = new rxjs_1.ReplaySubject(1);
|
|
90
113
|
this.init$ = this._init$.asObservable();
|
|
@@ -202,7 +225,7 @@ class Context {
|
|
|
202
225
|
(0, set_object_property_1.setObjectProperty)(data, change.key, change.value);
|
|
203
226
|
});
|
|
204
227
|
this.dataChangedByClient = client;
|
|
205
|
-
this.
|
|
228
|
+
this.replace(data);
|
|
206
229
|
return;
|
|
207
230
|
}
|
|
208
231
|
})));
|
|
@@ -302,27 +325,78 @@ class Context {
|
|
|
302
325
|
void this.initPromise.catch(() => { });
|
|
303
326
|
return this.initPromise;
|
|
304
327
|
}
|
|
305
|
-
|
|
328
|
+
get(path) {
|
|
306
329
|
this.assertNotDestroyed();
|
|
307
|
-
|
|
330
|
+
this.assertInitialized();
|
|
331
|
+
const value = (0, fetch_from_object_1.fetchFromObject)(this.data$.getValue(), (0, replace_context_keys_1.replaceContextKeys)(path, getContextById));
|
|
332
|
+
return cloneGetResult(value);
|
|
308
333
|
}
|
|
309
|
-
|
|
334
|
+
/**
|
|
335
|
+
* Частичное обновление данных по dotted-путям одним вызовом `next`.
|
|
336
|
+
*
|
|
337
|
+
* Предпочтительный способ правки нескольких полей на BFF. Ключ с явным
|
|
338
|
+
* `undefined` применяется (отличие от отсутствующего ключа в patch).
|
|
339
|
+
* Для целого снимка после load — {@link replace}.
|
|
340
|
+
*/
|
|
341
|
+
set(patch) {
|
|
310
342
|
this.assertNotDestroyed();
|
|
343
|
+
this.assertInitialized();
|
|
311
344
|
const data = this.data$.getValue();
|
|
312
|
-
|
|
345
|
+
for (const path of Object.keys(patch)) {
|
|
346
|
+
// hasOwnProperty: «loading: undefined» пишем, пропущенный ключ — не трогаем.
|
|
347
|
+
if (Object.prototype.hasOwnProperty.call(patch, path)) {
|
|
348
|
+
(0, set_object_property_1.setObjectProperty)(data, path, patch[path]);
|
|
349
|
+
}
|
|
350
|
+
}
|
|
313
351
|
this.data$.next(data);
|
|
314
352
|
}
|
|
315
353
|
/**
|
|
316
|
-
*
|
|
317
|
-
*
|
|
318
|
-
*
|
|
354
|
+
* Полная замена корня контекста (результат load, `{ ...loaded, field }`).
|
|
355
|
+
*
|
|
356
|
+
* Не merge patch: переданный объект становится новым состоянием целиком.
|
|
319
357
|
*/
|
|
320
|
-
|
|
358
|
+
replace(data) {
|
|
321
359
|
this.assertNotDestroyed();
|
|
322
|
-
|
|
323
|
-
|
|
360
|
+
this.assertInitialized();
|
|
361
|
+
this.data$.next(data);
|
|
362
|
+
}
|
|
363
|
+
/**
|
|
364
|
+
* Глубокая копия всего `T` (structured clone корня).
|
|
365
|
+
*
|
|
366
|
+
* Для одного поля — {@link get}. Нужен, когда на время async нужен отсоединённый
|
|
367
|
+
* снимок всего состояния, а не ссылка на живые данные.
|
|
368
|
+
*/
|
|
369
|
+
snapshot() {
|
|
370
|
+
this.assertNotDestroyed();
|
|
371
|
+
this.assertInitialized();
|
|
372
|
+
return structuredClone(this.data$.getValue());
|
|
373
|
+
}
|
|
374
|
+
/**
|
|
375
|
+
* Read-only поток данных контекста для подписок и RxJS-операторов.
|
|
376
|
+
*
|
|
377
|
+
* Если {@link init} ещё не создал хранилище, подписка **ждёт** успешного init
|
|
378
|
+
* ({@link init$}), затем ведёт себя как после init. При {@link destroy} до init
|
|
379
|
+
* поток завершается без эмиссий.
|
|
380
|
+
*
|
|
381
|
+
* После подключения сразу эмитит текущее состояние, затем каждое обновление
|
|
382
|
+
* через {@link set}, {@link replace} и т.п.
|
|
383
|
+
*/
|
|
384
|
+
watch() {
|
|
385
|
+
this.assertNotDestroyed();
|
|
386
|
+
// asObservable() — без .next у подписчиков; тот же поток, что у внутреннего Subject.
|
|
387
|
+
const connect = () => {
|
|
388
|
+
if (this.destroyed || !this.data$) {
|
|
389
|
+
// destroy до init: init$ уже complete, подписчик не должен висеть.
|
|
390
|
+
return rxjs_1.EMPTY;
|
|
391
|
+
}
|
|
392
|
+
return this.data$.asObservable();
|
|
393
|
+
};
|
|
394
|
+
// init уже создал Subject (в т.ч. промежуточный `{}` во время await load).
|
|
395
|
+
if (this.data$) {
|
|
396
|
+
return connect();
|
|
324
397
|
}
|
|
325
|
-
|
|
398
|
+
// boot() до init(): ждём успешный init, затем обычные эмиссии BehaviorSubject.
|
|
399
|
+
return this.init$.pipe((0, rxjs_1.take)(1), (0, rxjs_1.switchMap)(() => connect()));
|
|
326
400
|
}
|
|
327
401
|
/**
|
|
328
402
|
|
|
@@ -337,7 +411,7 @@ class Context {
|
|
|
337
411
|
* Ссылка на значение в **этом** контексте по пути, который задаётся **во втором**
|
|
338
412
|
* контексте строкой и меняется во времени.
|
|
339
413
|
*
|
|
340
|
-
* В отличие от прямого чтения `other.
|
|
414
|
+
* В отличие от прямого чтения `other.get()` при создании ссылки, в путь записывается
|
|
341
415
|
* только плейсхолдер `@{<id контекста other>.<путь other>}` (см. `ContextRef.toString`).
|
|
342
416
|
* При каждом обращении `Context.value` подставляет актуальное значение поля `other`;
|
|
343
417
|
* это уже строка-путь относительно корня текущего контекста (например `cards.1.balance`).
|
package/dist/core/index.d.ts
CHANGED
|
@@ -1,10 +1,4 @@
|
|
|
1
1
|
export * from "./actions/action";
|
|
2
|
-
export * from "./actions/animate-component";
|
|
3
|
-
export * from "./actions/local-action";
|
|
4
|
-
export * from "./actions/set-context-value";
|
|
5
|
-
export * from "./actions/set-context-values";
|
|
6
|
-
export * from "./actions/toggle-context-value";
|
|
7
|
-
export * from "./actions/write-text-to-clipboard";
|
|
8
2
|
export * from "./boot";
|
|
9
3
|
export * from "./client";
|
|
10
4
|
export * from "./client-context";
|
|
@@ -15,6 +9,9 @@ export * from "./matreshka";
|
|
|
15
9
|
export * from "./conditions";
|
|
16
10
|
export * from "./context/context";
|
|
17
11
|
export * from "./context/context-ref";
|
|
12
|
+
export type { DimensionalValue } from "@matreshka/shared/types/dimensional-value";
|
|
13
|
+
export { ComponentAnimationEffect, DimensionalUnit, TimingFunction, local, } from "./local";
|
|
14
|
+
export type { ActionConfig, AnimateComponentConfig, ComponentAnimationEffects, DimensionalKeyframeStops, OpacityKeyframeStops, } from "./local";
|
|
18
15
|
export * from "./types/client-settings";
|
|
19
16
|
export * from "./utils/calculate-components";
|
|
20
17
|
export * from "./utils/color-roles-to-ids";
|
package/dist/core/index.js
CHANGED
|
@@ -14,13 +14,8 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
|
14
14
|
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
15
|
};
|
|
16
16
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
+
exports.local = exports.TimingFunction = exports.DimensionalUnit = exports.ComponentAnimationEffect = void 0;
|
|
17
18
|
__exportStar(require("./actions/action"), exports);
|
|
18
|
-
__exportStar(require("./actions/animate-component"), exports);
|
|
19
|
-
__exportStar(require("./actions/local-action"), exports);
|
|
20
|
-
__exportStar(require("./actions/set-context-value"), exports);
|
|
21
|
-
__exportStar(require("./actions/set-context-values"), exports);
|
|
22
|
-
__exportStar(require("./actions/toggle-context-value"), exports);
|
|
23
|
-
__exportStar(require("./actions/write-text-to-clipboard"), exports);
|
|
24
19
|
__exportStar(require("./boot"), exports);
|
|
25
20
|
__exportStar(require("./client"), exports);
|
|
26
21
|
__exportStar(require("./client-context"), exports);
|
|
@@ -31,6 +26,11 @@ __exportStar(require("./matreshka"), exports);
|
|
|
31
26
|
__exportStar(require("./conditions"), exports);
|
|
32
27
|
__exportStar(require("./context/context"), exports);
|
|
33
28
|
__exportStar(require("./context/context-ref"), exports);
|
|
29
|
+
var local_1 = require("./local");
|
|
30
|
+
Object.defineProperty(exports, "ComponentAnimationEffect", { enumerable: true, get: function () { return local_1.ComponentAnimationEffect; } });
|
|
31
|
+
Object.defineProperty(exports, "DimensionalUnit", { enumerable: true, get: function () { return local_1.DimensionalUnit; } });
|
|
32
|
+
Object.defineProperty(exports, "TimingFunction", { enumerable: true, get: function () { return local_1.TimingFunction; } });
|
|
33
|
+
Object.defineProperty(exports, "local", { enumerable: true, get: function () { return local_1.local; } });
|
|
34
34
|
__exportStar(require("./types/client-settings"), exports);
|
|
35
35
|
__exportStar(require("./utils/calculate-components"), exports);
|
|
36
36
|
__exportStar(require("./utils/color-roles-to-ids"), exports);
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { animate } from "../actions/animate-component";
|
|
2
|
+
import { writeTextToClipboard } from "../actions/write-text-to-clipboard";
|
|
3
|
+
export type { ActionConfig } from "../actions/action";
|
|
4
|
+
export { DimensionalUnit } from "@matreshka/shared/enums/dimensional-unit";
|
|
5
|
+
export type { DimensionalValue } from "@matreshka/shared/types/dimensional-value";
|
|
6
|
+
export { animate, ComponentAnimationEffect, TimingFunction, } from "../actions/animate-component";
|
|
7
|
+
export type { AnimateComponentConfig, ComponentAnimationEffects, DimensionalKeyframeStops, OpacityKeyframeStops, } from "../actions/animate-component";
|
|
8
|
+
/**
|
|
9
|
+
* Глобальные локальные (client-only) действия Matreshka BFF.
|
|
10
|
+
*/
|
|
11
|
+
export declare const local: {
|
|
12
|
+
readonly animate: typeof animate;
|
|
13
|
+
readonly writeTextToClipboard: typeof writeTextToClipboard;
|
|
14
|
+
};
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.local = exports.TimingFunction = exports.ComponentAnimationEffect = exports.animate = exports.DimensionalUnit = void 0;
|
|
4
|
+
const animate_component_1 = require("../actions/animate-component");
|
|
5
|
+
const write_text_to_clipboard_1 = require("../actions/write-text-to-clipboard");
|
|
6
|
+
var dimensional_unit_1 = require("@matreshka/shared/enums/dimensional-unit");
|
|
7
|
+
Object.defineProperty(exports, "DimensionalUnit", { enumerable: true, get: function () { return dimensional_unit_1.DimensionalUnit; } });
|
|
8
|
+
var animate_component_2 = require("../actions/animate-component");
|
|
9
|
+
Object.defineProperty(exports, "animate", { enumerable: true, get: function () { return animate_component_2.animate; } });
|
|
10
|
+
Object.defineProperty(exports, "ComponentAnimationEffect", { enumerable: true, get: function () { return animate_component_2.ComponentAnimationEffect; } });
|
|
11
|
+
Object.defineProperty(exports, "TimingFunction", { enumerable: true, get: function () { return animate_component_2.TimingFunction; } });
|
|
12
|
+
/**
|
|
13
|
+
* Глобальные локальные (client-only) действия Matreshka BFF.
|
|
14
|
+
*/
|
|
15
|
+
exports.local = {
|
|
16
|
+
animate: animate_component_1.animate,
|
|
17
|
+
writeTextToClipboard: write_text_to_clipboard_1.writeTextToClipboard,
|
|
18
|
+
};
|
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
import { EntryComponent } from "../../components";
|
|
2
|
+
import { InstanceLocalActions } from "../actions/local-action";
|
|
2
3
|
import type { Client } from "../client";
|
|
3
4
|
import type { Componentable } from "./componentable";
|
|
5
|
+
type ComponentInstanceLocalActions<ComponentType> = ComponentType extends {
|
|
6
|
+
local: infer LocalActions;
|
|
7
|
+
} ? InstanceLocalActions<LocalActions> : Record<string, never>;
|
|
4
8
|
/**
|
|
5
9
|
* Инстанс server-компонента на клиенте.
|
|
6
10
|
* Один BFF-объект может быть сериализован несколько раз с разными id (`uuid-0`, `uuid-1`, …).
|
|
@@ -15,6 +19,8 @@ export declare class ComponentInstance<ComponentType extends Componentable = Com
|
|
|
15
19
|
constructor(
|
|
16
20
|
/** Id инстанса на клиенте (обычно `target` входящего сообщения). */
|
|
17
21
|
id: string, component: ComponentType);
|
|
22
|
+
/** Локальные действия компонента, адресованные этому instance. */
|
|
23
|
+
readonly local: ComponentInstanceLocalActions<ComponentType>;
|
|
18
24
|
get client(): Client | undefined;
|
|
19
25
|
/** Entry-инстанс дерева, внутри которого сериализован этот компонент (`entry.component` — BFF entry). */
|
|
20
26
|
get entry(): ComponentInstance<EntryComponent> | undefined;
|
|
@@ -23,3 +29,4 @@ export declare class ComponentInstance<ComponentType extends Componentable = Com
|
|
|
23
29
|
/** Закрепляет instance за client/entry после успешной сериализации конфига. */
|
|
24
30
|
commitSerialization(): void;
|
|
25
31
|
}
|
|
32
|
+
export {};
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.ComponentInstance = void 0;
|
|
4
|
+
const local_action_1 = require("../actions/local-action");
|
|
4
5
|
const client_context_1 = require("../client-context");
|
|
5
6
|
const entry_context_1 = require("../entry-context");
|
|
6
7
|
/**
|
|
@@ -14,6 +15,9 @@ class ComponentInstance {
|
|
|
14
15
|
this.id = id;
|
|
15
16
|
this.component = component;
|
|
16
17
|
this._serialized = false;
|
|
18
|
+
this.local = (0, local_action_1.createInstanceLocalActions)("local" in component
|
|
19
|
+
? component.local
|
|
20
|
+
: undefined, id);
|
|
17
21
|
}
|
|
18
22
|
get client() {
|
|
19
23
|
return this._client;
|
|
@@ -9,7 +9,7 @@ import { ContextRef, ContextRefValue } from "../context/context-ref";
|
|
|
9
9
|
* @example
|
|
10
10
|
* ```ts
|
|
11
11
|
* function bindAmount(ref: ContextValueRef<number | undefined>) {
|
|
12
|
-
* ref.
|
|
12
|
+
* ref.get(); // number | undefined
|
|
13
13
|
* }
|
|
14
14
|
*
|
|
15
15
|
* bindAmount(pageContext.ref("amount"));
|
|
@@ -17,13 +17,15 @@ import { ContextRef, ContextRefValue } from "../context/context-ref";
|
|
|
17
17
|
*/
|
|
18
18
|
export type ContextValueRef<ValueType> = ContextRef<any, any> & {
|
|
19
19
|
readonly __valueType?: ValueType;
|
|
20
|
-
|
|
21
|
-
|
|
20
|
+
get(): ValueType;
|
|
21
|
+
set(value: ValueType): void;
|
|
22
22
|
};
|
|
23
23
|
/**
|
|
24
24
|
* Ref `R` совместим с ожидаемым типом значения `ValueType` (проверка на call site).
|
|
25
25
|
*/
|
|
26
26
|
export type CompatibleContextValueRef<ValueType, R extends ContextRef> = ValueType extends ContextRefValue<R> ? R : never;
|
|
27
|
+
/** Статическое значение или ссылка на совместимое значение в контексте. */
|
|
28
|
+
export type ContextValueOrRef<ValueType> = ValueType | ContextValueRef<Exclude<ValueType, undefined>>;
|
|
27
29
|
/**
|
|
28
30
|
* Ссылка на массив элементов в контексте (`ItemType[] | undefined`).
|
|
29
31
|
*
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.replaceContextKeys = replaceContextKeys;
|
|
4
|
-
const fetch_from_object_1 = require("@matreshka/shared/utils/fetch-from-object");
|
|
5
4
|
const parse_context_path_1 = require("./parse-context-path");
|
|
6
5
|
/**
|
|
7
6
|
* Заменяет плейсхолдеры вида `{ключ}` в строке значениями из объекта контекста.
|
|
@@ -27,7 +26,7 @@ function replaceContextKeys(str, resolveContext) {
|
|
|
27
26
|
if (!context.inited()) {
|
|
28
27
|
throw new Error(`Context ${pathInfo.contextId} not initialized`);
|
|
29
28
|
}
|
|
30
|
-
const value =
|
|
29
|
+
const value = context.get(pathInfo.key);
|
|
31
30
|
str = replaceAll(str, `@{${path}}`, value ?? defaultValue);
|
|
32
31
|
});
|
|
33
32
|
const restContextKeys = findContextKeys(str);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@matreshka/bff",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.22.0",
|
|
4
4
|
"description": "Matreshka BFF: server-driven UI runtime — routing, pages, context, component DSL, and platform APIs",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"types": "./dist/index.d.ts",
|
|
@@ -62,7 +62,7 @@
|
|
|
62
62
|
"vitest": "^4.1.0"
|
|
63
63
|
},
|
|
64
64
|
"dependencies": {
|
|
65
|
-
"@matreshka/shared": "^0.
|
|
65
|
+
"@matreshka/shared": "^0.21.0",
|
|
66
66
|
"@simplewebauthn/server": "^13.1.1",
|
|
67
67
|
"@simplewebauthn/types": "^12.0.0",
|
|
68
68
|
"fast-xml-parser": "^5.3.3",
|
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
import { ContextRefValue } from "../context/context-ref";
|
|
2
|
-
import { ContextValueRef } from "../types/context-value-ref";
|
|
3
|
-
import { ActionConfig } from "./action";
|
|
4
|
-
import { LocalAction } from "./local-action";
|
|
5
|
-
/**
|
|
6
|
-
* Запись одного значения в Context на клиенте (с sync на BFF через `context-values`).
|
|
7
|
-
*
|
|
8
|
-
* `R` — конкретный ref; `value` имеет тип значения по этому ref.
|
|
9
|
-
*/
|
|
10
|
-
export declare class SetContextValue<R extends ContextValueRef<unknown>> extends LocalAction {
|
|
11
|
-
private readonly ref;
|
|
12
|
-
private readonly value;
|
|
13
|
-
constructor(ref: R, value: ContextRefValue<R>, config?: ActionConfig);
|
|
14
|
-
class(): string;
|
|
15
|
-
payload(): object;
|
|
16
|
-
}
|
|
17
|
-
/**
|
|
18
|
-
* Функциональная форма {@link SetContextValue}.
|
|
19
|
-
* Тип `value` должен совпадать с типом значения по `ref`.
|
|
20
|
-
*/
|
|
21
|
-
export declare function setContextValue<R extends ContextValueRef<unknown>>(ref: R, value: ContextRefValue<R>, config?: ActionConfig): SetContextValue<R>;
|