@matreshka/bff 0.32.0 → 0.33.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.
@@ -6,7 +6,6 @@ import { Componentable, ComponentInstance, ComponentTreeNode, MixedWithCallbacks
6
6
  import type { ActionConfig } from "../core/actions/action";
7
7
  import type { AnimateComponent } from "../core/actions/animate-component";
8
8
  import { EntryComponent, EntryComponentInitConfig, EntryComponentProperties } from "./entry-component";
9
- import type { Overlay } from "./types/container-overlay";
10
9
  /** Анимации подложки модального диалога при инициализации. */
11
10
  export type DialogBackdropInitConfig = {
12
11
  onEnter?: AnimateComponent | AnimateComponent[];
@@ -89,7 +88,7 @@ export declare class Dialog<InitConfigType extends DialogInitConfig<any> = Defau
89
88
  /**
90
89
  * Оверлеи диалога. По умолчанию — `overlays` конструктора.
91
90
  */
92
- protected overlays(): Overlay[] | undefined;
91
+ protected overlays(): InitConfigType["overlays"];
93
92
  /**
94
93
  * Возвращает уникальный идентификатор класса компонента.
95
94
  * @returns Строка "dialog".
@@ -26,16 +26,16 @@ type DefaultInitConfigType = EntryComponentInitConfig<EntryComponent>;
26
26
  export declare abstract class EntryComponent<InitConfigType extends EntryComponentInitConfig<any> = DefaultInitConfigType, PropertiesType extends EntryComponentProperties = EntryComponentProperties, SerializedConfigType extends EntryServerComponentConfig = EntryServerComponentConfig> extends Component<InitConfigType, PropertiesType> {
27
27
  private readonly registeredTools;
28
28
  private declaredToolsRegistered;
29
- private entryLifecycleInteractionsRegistered;
29
+ private entryInteractionsRegistered;
30
30
  constructor(config: InitConfigType);
31
31
  /**
32
- * `onEnter` / `onLeave` читаются при первом создании entry-инстанса,
33
- * уже после конструктора наследника — поля и `this.options` доступны.
34
- * Дополнительные interaction для того же момента — в {@link registerEntryLifecycleInteractionsExtra}.
32
+ * Декларативная карта interaction entry: имя события → обработчики.
33
+ * Наследники расширяют её через `{ ...super.entryInteractions(), scroll: ... }`.
34
+ * Вызывается лениво (после конструктора наследника), поэтому поля подкласса доступны.
35
35
  */
36
- protected registerEntryLifecycleInteractions(): void;
37
- /** Хук для наследников: один раз сразу после enter/leave (см. {@link registerEntryLifecycleInteractions}). */
38
- protected registerEntryLifecycleInteractionsExtra(): void;
36
+ protected entryInteractions(): Record<string, ServerComponentAction<any, any> | ServerComponentAction<any, any>[] | undefined>;
37
+ /** Идемпотентная регистрация {@link entryInteractions}. */
38
+ private registerEntryInteractions;
39
39
  /**
40
40
  * Показ entry. По умолчанию — `onEnter` конструктора.
41
41
  */
@@ -52,8 +52,6 @@ export declare abstract class EntryComponent<InitConfigType extends EntryCompone
52
52
  /** Сохранённые WebMCP-тулзы. execute не сериализуется и не вызывается до сообщения вызова. */
53
53
  get entryTools(): readonly WebMcpTool[];
54
54
  protected registerEntryTools(tools: readonly WebMcpTool[] | undefined): void;
55
- /** Привязка обработчиков к имени взаимодействия. */
56
- protected bindDeclaredInteraction(event: string, handlers: ServerComponentAction<any, any> | ServerComponentAction<any, any>[] | undefined): void;
57
55
  /**
58
56
  * Тулзы читают поля наследника, поэтому регистрируются после конструктора:
59
57
  * при первом чтении списка и перед сериализацией.
@@ -72,7 +70,7 @@ export declare abstract class EntryComponent<InitConfigType extends EntryCompone
72
70
  beginSerializationContext(): ComponentInstance<this>;
73
71
  /**
74
72
  * Явное создание instance entry (редко для Page/Dialog; для App-оверлеев см.
75
- * {@link beginSerializationContext}). Обработчики enter/leave регистрируются здесь же.
73
+ * {@link beginSerializationContext}). Interaction entry регистрируются здесь же.
76
74
  */
77
75
  createInstance(): ComponentInstance<this>;
78
76
  protected createSelfEntry(): ComponentInstance<this>;
@@ -18,24 +18,31 @@ class EntryComponent extends component_1.Component {
18
18
  super(config);
19
19
  this.registeredTools = [];
20
20
  this.declaredToolsRegistered = false;
21
- this.entryLifecycleInteractionsRegistered = false;
21
+ this.entryInteractionsRegistered = false;
22
22
  }
23
23
  /**
24
- * `onEnter` / `onLeave` читаются при первом создании entry-инстанса,
25
- * уже после конструктора наследника — поля и `this.options` доступны.
26
- * Дополнительные interaction для того же момента — в {@link registerEntryLifecycleInteractionsExtra}.
24
+ * Декларативная карта interaction entry: имя события → обработчики.
25
+ * Наследники расширяют её через `{ ...super.entryInteractions(), scroll: ... }`.
26
+ * Вызывается лениво (после конструктора наследника), поэтому поля подкласса доступны.
27
27
  */
28
- registerEntryLifecycleInteractions() {
29
- if (this.entryLifecycleInteractionsRegistered) {
28
+ entryInteractions() {
29
+ return {
30
+ enter: this.onEnter(),
31
+ leave: this.onLeave(),
32
+ };
33
+ }
34
+ /** Идемпотентная регистрация {@link entryInteractions}. */
35
+ registerEntryInteractions() {
36
+ if (this.entryInteractionsRegistered) {
30
37
  return;
31
38
  }
32
- this.entryLifecycleInteractionsRegistered = true;
33
- this.bindDeclaredInteraction("enter", this.onEnter());
34
- this.bindDeclaredInteraction("leave", this.onLeave());
35
- this.registerEntryLifecycleInteractionsExtra();
39
+ this.entryInteractionsRegistered = true;
40
+ for (const [event, handlers] of Object.entries(this.entryInteractions())) {
41
+ if (handlers !== undefined) {
42
+ this.bindActions(event, handlers);
43
+ }
44
+ }
36
45
  }
37
- /** Хук для наследников: один раз сразу после enter/leave (см. {@link registerEntryLifecycleInteractions}). */
38
- registerEntryLifecycleInteractionsExtra() { }
39
46
  /**
40
47
  * Показ entry. По умолчанию — `onEnter` конструктора.
41
48
  */
@@ -66,13 +73,6 @@ class EntryComponent extends component_1.Component {
66
73
  }
67
74
  this.registeredTools.push(...tools);
68
75
  }
69
- /** Привязка обработчиков к имени взаимодействия. */
70
- bindDeclaredInteraction(event, handlers) {
71
- if (handlers === undefined) {
72
- return;
73
- }
74
- this.bindActions(event, handlers);
75
- }
76
76
  /**
77
77
  * Тулзы читают поля наследника, поэтому регистрируются после конструктора:
78
78
  * при первом чтении списка и перед сериализацией.
@@ -159,14 +159,14 @@ class EntryComponent extends component_1.Component {
159
159
  }
160
160
  /**
161
161
  * Явное создание instance entry (редко для Page/Dialog; для App-оверлеев см.
162
- * {@link beginSerializationContext}). Обработчики enter/leave регистрируются здесь же.
162
+ * {@link beginSerializationContext}). Interaction entry регистрируются здесь же.
163
163
  */
164
164
  createInstance() {
165
- this.registerEntryLifecycleInteractions();
165
+ this.registerEntryInteractions();
166
166
  return super.createInstance();
167
167
  }
168
168
  createSelfEntry() {
169
- this.registerEntryLifecycleInteractions();
169
+ this.registerEntryInteractions();
170
170
  const instance = super.createSelfEntry();
171
171
  const client = (0, client_context_1.currentClient)();
172
172
  // Подписка на leave и прочие interaction до commitSerialization instance.entry.
@@ -1,8 +1,8 @@
1
1
  import { ServerComponentClass } from "@matreshka/client-bff-protocol/enums/server-component-class";
2
2
  import type { ForEachConfig } from "@matreshka/client-bff-protocol/types/for-each-config";
3
3
  import { Paths, PathValue } from "ts-essentials";
4
- import { AnySchemaContextRef, ComponentInstance, ComponentTreeNode, Context, ContextRef, ContextRefLocalActions, ContextRefValueType, JsonObject, StandaloneComponent, WritableContextRefOfValue } from "../core";
5
4
  import type { z } from "zod";
5
+ import { AnySchemaContextRef, ComponentInstance, ComponentTreeNode, Context, ContextRef, ContextRefLocalActions, ContextRefValueType, JsonObject, StandaloneComponent, WritableContextRefOfValue } from "../core";
6
6
  import { Component, ComponentInitConfig, ComponentProperties } from "./component";
7
7
  type ForEachArrayValue = readonly unknown[] | unknown[];
8
8
  type ForEachItemArray<RefType extends AnySchemaContextRef> = Extract<ContextRefValueType<RefType>, ForEachArrayValue>;
@@ -28,11 +28,8 @@ type DefaultInitConfigType = PageInitConfig<Page>;
28
28
  */
29
29
  export declare abstract class Page<InitConfigType extends PageInitConfig<any> = DefaultInitConfigType, PropertiesType extends PageProperties = PageProperties> extends EntryComponent<InitConfigType, PropertiesType, PageConfig> implements Pageable {
30
30
  constructor();
31
- /**
32
- * Обработчик прокрутки регистрируется вместе с enter/leave — после конструктора наследника,
33
- * когда доступны поля подкласса (см. {@link EntryComponent.registerEntryLifecycleInteractions}).
34
- */
35
- protected registerEntryLifecycleInteractionsExtra(): void;
31
+ /** Добавляет `scroll` к стандартным enter/leave (см. {@link EntryComponent.entryInteractions}). */
32
+ protected entryInteractions(): ReturnType<EntryComponent["entryInteractions"]>;
36
33
  /**
37
34
  * Возвращает HTTP-статус страницы.
38
35
  * @returns Статус страницы (по умолчанию 200 OK).
@@ -15,12 +15,9 @@ class Page extends entry_component_1.EntryComponent {
15
15
  // @ts-expect-error Page задаёт content в boot(), а не через конфиг конструктора Component.
16
16
  super({});
17
17
  }
18
- /**
19
- * Обработчик прокрутки регистрируется вместе с enter/leave — после конструктора наследника,
20
- * когда доступны поля подкласса (см. {@link EntryComponent.registerEntryLifecycleInteractions}).
21
- */
22
- registerEntryLifecycleInteractionsExtra() {
23
- this.bindDeclaredInteraction("scroll", this.onScroll());
18
+ /** Добавляет `scroll` к стандартным enter/leave (см. {@link EntryComponent.entryInteractions}). */
19
+ entryInteractions() {
20
+ return { ...super.entryInteractions(), scroll: this.onScroll() };
24
21
  }
25
22
  /**
26
23
  * Возвращает HTTP-статус страницы.
@@ -75,6 +75,13 @@ export declare class ContextRef<ContextType extends JsonObject = JsonObject, Pat
75
75
  * та же ошибка, что у {@link Context.set}.
76
76
  */
77
77
  set(value: PathValue<ContextType, PathType>): Observable<ContextUpdateDelivery>;
78
+ /**
79
+ * Следующее значение по текущему пути из текущего снимка.
80
+ *
81
+ * Callback получает то же, что {@link get}, и возвращает значение того же типа.
82
+ * Запись идёт через {@link set}.
83
+ */
84
+ update(updater: (current: PathValue<ContextType, PathType>) => PathValue<ContextType, PathType>): Observable<ContextUpdateDelivery>;
78
85
  toString(): string;
79
86
  toJSON(): string;
80
87
  }
@@ -6,6 +6,12 @@ const inc_context_value_1 = require("../actions/inc-context-value");
6
6
  const set_context_1 = require("../actions/set-context");
7
7
  const toggle_context_value_1 = require("../actions/toggle-context-value");
8
8
  const client_context_1 = require("../client-context");
9
+ function cloneContextValue(value) {
10
+ if (value !== null && typeof value === "object") {
11
+ return structuredClone(value);
12
+ }
13
+ return value;
14
+ }
9
15
  class ContextRef {
10
16
  constructor(context, path) {
11
17
  this.context = context;
@@ -72,6 +78,15 @@ class ContextRef {
72
78
  [this.path]: value,
73
79
  });
74
80
  }
81
+ /**
82
+ * Следующее значение по текущему пути из текущего снимка.
83
+ *
84
+ * Callback получает то же, что {@link get}, и возвращает значение того же типа.
85
+ * Запись идёт через {@link set}.
86
+ */
87
+ update(updater) {
88
+ return this.set(cloneContextValue(updater(this.get())));
89
+ }
75
90
  toString() {
76
91
  return `@{${this.context.id}.${this.path}}`;
77
92
  }
@@ -178,6 +178,14 @@ export declare class Context<T extends JsonObject, S extends z.ZodObject | undef
178
178
  * Возвращает тот же hot {@link Observable}, что и {@link set}.
179
179
  */
180
180
  replace(data: T): Observable<ContextUpdateDelivery>;
181
+ /**
182
+ * Следующее состояние целиком из текущего снимка `T`.
183
+ *
184
+ * Callback получает копию текущих данных и возвращает значение того же типа.
185
+ * Результат сохраняется как structured clone, как в {@link replace}.
186
+ * Возвращает тот же hot {@link Observable}, что и {@link set}.
187
+ */
188
+ update(updater: (current: T) => T): Observable<ContextUpdateDelivery>;
181
189
  /**
182
190
  * Глубокая копия всего `T` (structured clone корня).
183
191
  *
@@ -193,7 +201,7 @@ export declare class Context<T extends JsonObject, S extends z.ZodObject | undef
193
201
  * поток завершается без эмиссий.
194
202
  *
195
203
  * После подключения сразу эмитит текущее состояние, затем каждое обновление
196
- * через {@link set}, {@link replace} и т.п.
204
+ * через {@link set}, {@link replace}, {@link update} и т.п.
197
205
  */
198
206
  watch(): Observable<T>;
199
207
  /**
@@ -517,6 +517,16 @@ class Context {
517
517
  replace(data) {
518
518
  return this.updateDataAndWait(() => structuredClone(data));
519
519
  }
520
+ /**
521
+ * Следующее состояние целиком из текущего снимка `T`.
522
+ *
523
+ * Callback получает копию текущих данных и возвращает значение того же типа.
524
+ * Результат сохраняется как structured clone, как в {@link replace}.
525
+ * Возвращает тот же hot {@link Observable}, что и {@link set}.
526
+ */
527
+ update(updater) {
528
+ return this.updateDataAndWait((current) => structuredClone(updater(current)));
529
+ }
520
530
  /**
521
531
  * Глубокая копия всего `T` (structured clone корня).
522
532
  *
@@ -536,7 +546,7 @@ class Context {
536
546
  * поток завершается без эмиссий.
537
547
  *
538
548
  * После подключения сразу эмитит текущее состояние, затем каждое обновление
539
- * через {@link set}, {@link replace} и т.п.
549
+ * через {@link set}, {@link replace}, {@link update} и т.п.
540
550
  */
541
551
  watch() {
542
552
  this.assertNotDestroyed();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@matreshka/bff",
3
- "version": "0.32.0",
3
+ "version": "0.33.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",