@matreshka/bff 0.33.2 → 0.34.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.js +5 -2
- package/dist/components/for-each.d.ts +20 -23
- package/dist/components/for-each.js +82 -62
- package/dist/components/item-list/flatten-nested-items.d.ts +13 -4
- package/dist/components/item-list/flatten-nested-items.js +11 -5
- package/dist/components/item-list/item-list.d.ts +15 -9
- package/dist/components/item-list/item-list.js +52 -19
- package/dist/components/item-list/nested-items-host-support.d.ts +15 -5
- package/dist/components/item-list/nested-items-host-support.js +61 -8
- package/dist/components/map.js +5 -2
- package/package.json +2 -2
package/dist/components/board.js
CHANGED
|
@@ -48,7 +48,10 @@ class Board extends component_1.Component {
|
|
|
48
48
|
this.itemsSlot.source = itemsSlot.source;
|
|
49
49
|
this.itemsSlot.itemLists = itemsSlot.itemLists;
|
|
50
50
|
(0, item_list_1.attachItemListsToHost)(this, "items", this.itemsSlot);
|
|
51
|
-
this.itemListHostAdapter = (0, item_list_1.createItemListHostAdapter)(() => this.instances, (slot) => (slot === "items" ? this.itemsSlot : undefined));
|
|
51
|
+
this.itemListHostAdapter = (0, item_list_1.createItemListHostAdapter)(() => this.instances, (slot) => (slot === "items" ? this.itemsSlot : undefined), "items");
|
|
52
|
+
this.destroyInstance$.subscribe((released) => {
|
|
53
|
+
this.itemListHostAdapter.releaseHostInstance(released);
|
|
54
|
+
});
|
|
52
55
|
if (config.onCenterChange) {
|
|
53
56
|
const actions = config.onCenterChange;
|
|
54
57
|
this.bindActions("center-change", actions);
|
|
@@ -100,7 +103,7 @@ class Board extends component_1.Component {
|
|
|
100
103
|
instance = this.createInstance();
|
|
101
104
|
}
|
|
102
105
|
const result = super.serialize(instance);
|
|
103
|
-
const items =
|
|
106
|
+
const items = this.itemListHostAdapter.serializeSlot(instance);
|
|
104
107
|
return {
|
|
105
108
|
...result,
|
|
106
109
|
class: server_component_class_1.ServerComponentClass.Board,
|
|
@@ -107,6 +107,8 @@ export declare class ForEach<RefType extends AnySchemaContextRef, ComponentType
|
|
|
107
107
|
*
|
|
108
108
|
* @param forEachInstance Instance ForEach на клиенте (связка client + entry + id).
|
|
109
109
|
*/
|
|
110
|
+
/** Ключ на wire: значение `track` без внутреннего префикса индексного контекста. */
|
|
111
|
+
private trackKey;
|
|
110
112
|
private getInstanceState;
|
|
111
113
|
/**
|
|
112
114
|
* Снимает instances элементов списка и удаляет состояние для одного instance ForEach.
|
|
@@ -114,45 +116,40 @@ export declare class ForEach<RefType extends AnySchemaContextRef, ComponentType
|
|
|
114
116
|
* @param forEachInstance Instance ForEach, инстанс которого прекращено.
|
|
115
117
|
*/
|
|
116
118
|
private releaseInstanceState;
|
|
119
|
+
/** Снимает instances, созданные одной сериализацией слота. */
|
|
120
|
+
private releaseTrackedInstances;
|
|
117
121
|
/**
|
|
118
|
-
*
|
|
119
|
-
* для конкретного instance ForEach.
|
|
122
|
+
* Удаляет слоты, которых больше нет в массиве, и снимает только их instances.
|
|
120
123
|
*
|
|
121
|
-
* @param
|
|
124
|
+
* @param currentTrackKeys Актуальные значения `track`.
|
|
125
|
+
* @param state Состояние одного instance ForEach.
|
|
122
126
|
*/
|
|
123
|
-
private
|
|
127
|
+
private evictRemovedSlots;
|
|
124
128
|
/**
|
|
125
|
-
*
|
|
129
|
+
* Сериализует слот один раз и запоминает payload вместе с instances.
|
|
126
130
|
*
|
|
127
|
-
* @param
|
|
128
|
-
* @param
|
|
131
|
+
* @param tree Узлы элемента из кэша generator.
|
|
132
|
+
* @param state Состояние instance ForEach.
|
|
133
|
+
* @param trackKey Значение `track` элемента.
|
|
134
|
+
* @returns Конфиги строки для клиента.
|
|
129
135
|
*/
|
|
130
|
-
private
|
|
136
|
+
private serializeSlotOnce;
|
|
131
137
|
/**
|
|
132
|
-
*
|
|
138
|
+
* Собирает diff списка: полный порядок ключей и конфиги только новых ключей.
|
|
139
|
+
* Индексный контекст обновляется для всех элементов, уже отданные слоты не сериализуются.
|
|
133
140
|
*
|
|
134
|
-
* @param
|
|
135
|
-
* @
|
|
136
|
-
* @returns Сериализованные конфиги для клиента.
|
|
141
|
+
* @param forEachInstance Instance ForEach, для которого строится payload.
|
|
142
|
+
* @returns Payload preload и `ForEachSyncComponentsMessage`.
|
|
137
143
|
*/
|
|
138
|
-
private
|
|
139
|
-
/**
|
|
140
|
-
* Строит дерево компонентов по текущему значению ref: обновляет индексы в
|
|
141
|
-
* {@link componentContext}, берёт узлы из кэша instance ForEach или вызывает `generator`.
|
|
142
|
-
*
|
|
143
|
-
* @param forEachInstance Instance ForEach, для которого строится дерево элементов.
|
|
144
|
-
* @returns Слоты элементов в порядке следования в массиве данных.
|
|
145
|
-
*/
|
|
146
|
-
private generateComponents;
|
|
144
|
+
private buildSyncPayload;
|
|
147
145
|
/**
|
|
148
146
|
* Синхронизирует элементы списка с клиентом для одного instance ForEach.
|
|
149
147
|
*
|
|
150
148
|
* @param forEachInstance Instance ForEach на клиенте.
|
|
151
|
-
* @param currentItemIds Актуальные ключи элементов списка.
|
|
152
149
|
*/
|
|
153
150
|
private syncForEachInstance;
|
|
154
151
|
/**
|
|
155
|
-
* Отправляет клиенту
|
|
152
|
+
* Отправляет клиенту порядок ключей и конфиги новых элементов (`ForEachSyncComponentsMessage`).
|
|
156
153
|
* Вызывается при onShow и при изменении массива в ref (добавление, удаление, порядок).
|
|
157
154
|
*
|
|
158
155
|
* @param onlyIfChanged Если `true`, sync пропускается, когда не изменился набор `track`-ключей.
|
|
@@ -5,7 +5,6 @@ const server_component_class_1 = require("@matreshka/client-bff-protocol/enums/s
|
|
|
5
5
|
const for_each_sync_components_message_1 = require("@matreshka/client-bff-protocol/messages/bff-to-client/components/for-each/for-each-sync-components-message");
|
|
6
6
|
const rxjs_1 = require("rxjs");
|
|
7
7
|
const core_1 = require("../core");
|
|
8
|
-
const serialize_component_tree_1 = require("../core/utils/serialize-component-tree");
|
|
9
8
|
const track_created_instances_1 = require("../core/utils/track-created-instances");
|
|
10
9
|
const component_1 = require("./component");
|
|
11
10
|
/** Возвращает массив элементов списка из ref; не-массив даёт пустой массив. */
|
|
@@ -84,12 +83,16 @@ class ForEach extends component_1.Component {
|
|
|
84
83
|
*
|
|
85
84
|
* @param forEachInstance Instance ForEach на клиенте (связка client + entry + id).
|
|
86
85
|
*/
|
|
86
|
+
/** Ключ на wire: значение `track` без внутреннего префикса индексного контекста. */
|
|
87
|
+
trackKey(item) {
|
|
88
|
+
return this.config.track(item);
|
|
89
|
+
}
|
|
87
90
|
getInstanceState(forEachInstance) {
|
|
88
91
|
let state = this.instanceStates.get(forEachInstance);
|
|
89
92
|
if (!state) {
|
|
90
93
|
state = {
|
|
91
|
-
itemSyncInstances: [],
|
|
92
94
|
componentsCache: new Map(),
|
|
95
|
+
serializedByKey: new Map(),
|
|
93
96
|
};
|
|
94
97
|
this.instanceStates.set(forEachInstance, state);
|
|
95
98
|
}
|
|
@@ -101,108 +104,126 @@ class ForEach extends component_1.Component {
|
|
|
101
104
|
* @param forEachInstance Instance ForEach, инстанс которого прекращено.
|
|
102
105
|
*/
|
|
103
106
|
releaseInstanceState(forEachInstance) {
|
|
104
|
-
this.
|
|
107
|
+
const state = this.instanceStates.get(forEachInstance);
|
|
108
|
+
if (state) {
|
|
109
|
+
for (const slot of state.serializedByKey.values()) {
|
|
110
|
+
this.releaseTrackedInstances(slot.instances);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
105
113
|
this.instanceStates.delete(forEachInstance);
|
|
106
114
|
}
|
|
107
|
-
/**
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
*
|
|
111
|
-
* @param forEachInstance Instance ForEach, для которого снимаются дочерние instances.
|
|
112
|
-
*/
|
|
113
|
-
releaseItemSyncInstances(forEachInstance) {
|
|
114
|
-
const state = this.instanceStates.get(forEachInstance);
|
|
115
|
-
if (!state || state.itemSyncInstances.length === 0) {
|
|
115
|
+
/** Снимает instances, созданные одной сериализацией слота. */
|
|
116
|
+
releaseTrackedInstances(instances) {
|
|
117
|
+
if (instances.length === 0) {
|
|
116
118
|
return;
|
|
117
119
|
}
|
|
118
120
|
const byComponent = new Map();
|
|
119
|
-
for (const instance of
|
|
121
|
+
for (const instance of instances) {
|
|
120
122
|
const component = instance.component;
|
|
121
123
|
const list = byComponent.get(component) ?? [];
|
|
122
124
|
list.push(instance);
|
|
123
125
|
byComponent.set(component, list);
|
|
124
126
|
}
|
|
125
|
-
for (const [component,
|
|
126
|
-
component.releaseInstances(
|
|
127
|
+
for (const [component, componentInstances] of byComponent) {
|
|
128
|
+
component.releaseInstances(componentInstances);
|
|
127
129
|
}
|
|
128
|
-
state.itemSyncInstances = [];
|
|
129
130
|
}
|
|
130
131
|
/**
|
|
131
|
-
* Удаляет
|
|
132
|
+
* Удаляет слоты, которых больше нет в массиве, и снимает только их instances.
|
|
132
133
|
*
|
|
133
|
-
* @param
|
|
134
|
-
* @param
|
|
134
|
+
* @param currentTrackKeys Актуальные значения `track`.
|
|
135
|
+
* @param state Состояние одного instance ForEach.
|
|
135
136
|
*/
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
137
|
+
evictRemovedSlots(currentTrackKeys, state) {
|
|
138
|
+
// Копия ключей: ниже удаляем записи прямо из Map.
|
|
139
|
+
// Слот уже отдан клиенту — снимаем его instances и оба кэша.
|
|
140
|
+
// Ключ дерева — `id` + track, как в {@link itemId}: так strictRef не путает его с индексом.
|
|
141
|
+
for (const trackKey of [...state.serializedByKey.keys()]) {
|
|
142
|
+
if (currentTrackKeys.has(trackKey)) {
|
|
143
|
+
continue;
|
|
144
|
+
}
|
|
145
|
+
const slot = state.serializedByKey.get(trackKey);
|
|
146
|
+
if (slot) {
|
|
147
|
+
this.releaseTrackedInstances(slot.instances);
|
|
148
|
+
}
|
|
149
|
+
state.serializedByKey.delete(trackKey);
|
|
150
|
+
state.componentsCache.delete("id" + trackKey);
|
|
151
|
+
}
|
|
152
|
+
// Дерево без сериализованного слота (generator успел отработать, serialize — нет).
|
|
153
|
+
// slice(2) снимает префикс `id` и возвращает значение track.
|
|
154
|
+
for (const itemId of [...state.componentsCache.keys()]) {
|
|
155
|
+
if (!currentTrackKeys.has(itemId.slice(2))) {
|
|
156
|
+
state.componentsCache.delete(itemId);
|
|
140
157
|
}
|
|
141
158
|
}
|
|
142
159
|
}
|
|
143
160
|
/**
|
|
144
|
-
* Сериализует
|
|
161
|
+
* Сериализует слот один раз и запоминает payload вместе с instances.
|
|
145
162
|
*
|
|
146
|
-
* @param
|
|
147
|
-
* @param
|
|
148
|
-
* @
|
|
163
|
+
* @param tree Узлы элемента из кэша generator.
|
|
164
|
+
* @param state Состояние instance ForEach.
|
|
165
|
+
* @param trackKey Значение `track` элемента.
|
|
166
|
+
* @returns Конфиги строки для клиента.
|
|
149
167
|
*/
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
const { result, instances } = (0, track_created_instances_1.runWithCreatedInstanceTracking)(() => (0, serialize_component_tree_1.serializeForEachSlots)(components));
|
|
154
|
-
state.itemSyncInstances = instances;
|
|
168
|
+
serializeSlotOnce(tree, state, trackKey) {
|
|
169
|
+
const { result, instances } = (0, track_created_instances_1.runWithCreatedInstanceTracking)(() => (0, core_1.serializeComponentList)(tree));
|
|
170
|
+
state.serializedByKey.set(trackKey, { components: result, instances });
|
|
155
171
|
return result;
|
|
156
172
|
}
|
|
157
173
|
/**
|
|
158
|
-
*
|
|
159
|
-
*
|
|
174
|
+
* Собирает diff списка: полный порядок ключей и конфиги только новых ключей.
|
|
175
|
+
* Индексный контекст обновляется для всех элементов, уже отданные слоты не сериализуются.
|
|
160
176
|
*
|
|
161
|
-
* @param forEachInstance Instance ForEach, для которого строится
|
|
162
|
-
* @returns
|
|
177
|
+
* @param forEachInstance Instance ForEach, для которого строится payload.
|
|
178
|
+
* @returns Payload preload и `ForEachSyncComponentsMessage`.
|
|
163
179
|
*/
|
|
164
|
-
|
|
165
|
-
const
|
|
166
|
-
const
|
|
167
|
-
const
|
|
168
|
-
this.lastItemsCheckSum =
|
|
169
|
-
const items = Array.isArray(value) ? value : [];
|
|
180
|
+
buildSyncPayload(forEachInstance) {
|
|
181
|
+
const state = this.getInstanceState(forEachInstance);
|
|
182
|
+
const items = getForEachValue(this.config.ref);
|
|
183
|
+
const order = items.map((item) => this.trackKey(item));
|
|
184
|
+
this.lastItemsCheckSum = order.join("|");
|
|
170
185
|
const store = {};
|
|
171
186
|
for (let index = 0; index < items.length; index++) {
|
|
172
187
|
store[this.itemId(items[index])] = { index: `${index}` };
|
|
173
188
|
}
|
|
174
189
|
this.componentContext.replace(store);
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
190
|
+
this.evictRemovedSlots(new Set(order), state);
|
|
191
|
+
const upserts = [];
|
|
192
|
+
for (let index = 0; index < items.length; index++) {
|
|
193
|
+
const trackKey = order[index];
|
|
194
|
+
if (state.serializedByKey.has(trackKey)) {
|
|
195
|
+
continue;
|
|
196
|
+
}
|
|
197
|
+
const itemId = this.itemId(items[index]);
|
|
198
|
+
let tree = state.componentsCache.get(itemId);
|
|
199
|
+
if (!tree) {
|
|
200
|
+
tree = this.generateItemComponents({
|
|
201
|
+
component: this,
|
|
202
|
+
ref: createForEachItemLink(this.config.ref, this.componentContext.ref(`${itemId}.index`)),
|
|
203
|
+
});
|
|
204
|
+
state.componentsCache.set(itemId, tree);
|
|
179
205
|
}
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
206
|
+
upserts.push({
|
|
207
|
+
key: trackKey,
|
|
208
|
+
components: this.serializeSlotOnce(tree, state, trackKey),
|
|
183
209
|
});
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
});
|
|
210
|
+
}
|
|
211
|
+
return { order, upserts };
|
|
187
212
|
}
|
|
188
213
|
/**
|
|
189
214
|
* Синхронизирует элементы списка с клиентом для одного instance ForEach.
|
|
190
215
|
*
|
|
191
216
|
* @param forEachInstance Instance ForEach на клиенте.
|
|
192
|
-
* @param currentItemIds Актуальные ключи элементов списка.
|
|
193
217
|
*/
|
|
194
|
-
syncForEachInstance(forEachInstance
|
|
195
|
-
this.evictRemovedItemCaches(currentItemIds, this.getInstanceState(forEachInstance).componentsCache);
|
|
218
|
+
syncForEachInstance(forEachInstance) {
|
|
196
219
|
(0, core_1.runWithClient)(forEachInstance.client, () => {
|
|
197
220
|
(0, core_1.runWithEntryContext)(forEachInstance.entry, forEachInstance.client, () => {
|
|
198
|
-
|
|
199
|
-
const serializedComponents = this.serializeItemsWithTracking(components, forEachInstance);
|
|
200
|
-
forEachInstance.client.outcomingMessage$.next(new for_each_sync_components_message_1.ForEachSyncComponentsMessage(forEachInstance.id, serializedComponents));
|
|
221
|
+
forEachInstance.client.outcomingMessage$.next(new for_each_sync_components_message_1.ForEachSyncComponentsMessage(forEachInstance.id, this.buildSyncPayload(forEachInstance)));
|
|
201
222
|
});
|
|
202
223
|
});
|
|
203
224
|
}
|
|
204
225
|
/**
|
|
205
|
-
* Отправляет клиенту
|
|
226
|
+
* Отправляет клиенту порядок ключей и конфиги новых элементов (`ForEachSyncComponentsMessage`).
|
|
206
227
|
* Вызывается при onShow и при изменении массива в ref (добавление, удаление, порядок).
|
|
207
228
|
*
|
|
208
229
|
* @param onlyIfChanged Если `true`, sync пропускается, когда не изменился набор `track`-ключей.
|
|
@@ -216,9 +237,8 @@ class ForEach extends component_1.Component {
|
|
|
216
237
|
if (this.instances.length === 0) {
|
|
217
238
|
return;
|
|
218
239
|
}
|
|
219
|
-
const currentItemIds = new Set(value.map((item) => this.itemId(item)));
|
|
220
240
|
for (const forEachInstance of this.instances) {
|
|
221
|
-
this.syncForEachInstance(forEachInstance
|
|
241
|
+
this.syncForEachInstance(forEachInstance);
|
|
222
242
|
}
|
|
223
243
|
}
|
|
224
244
|
/**
|
|
@@ -327,7 +347,7 @@ class ForEach extends component_1.Component {
|
|
|
327
347
|
if (this.preload && this.properties.ref.context.inited()) {
|
|
328
348
|
(0, core_1.runWithClient)(instance.client, () => {
|
|
329
349
|
(0, core_1.runWithEntryContext)(instance.entry, instance.client, () => {
|
|
330
|
-
extra.components = this.
|
|
350
|
+
extra.components = this.buildSyncPayload(instance);
|
|
331
351
|
});
|
|
332
352
|
});
|
|
333
353
|
}
|
|
@@ -1,11 +1,20 @@
|
|
|
1
|
+
import type { NestedItemBase } from "@matreshka/client-bff-protocol/types/nested-item-base";
|
|
2
|
+
import type { ServerComponentConfig } from "@matreshka/client-bff-protocol/types/server-component-config";
|
|
1
3
|
import type { ComponentInstance, ComponentTreeNode } from "../../core";
|
|
2
4
|
import type { ItemList } from "./item-list";
|
|
3
5
|
import type { NestedItemTreeNode } from "./types";
|
|
4
|
-
|
|
5
|
-
export
|
|
6
|
+
/** Статический элемент слота, сериализованный один раз на host-instance. */
|
|
7
|
+
export type CachedStaticNestedItem = {
|
|
8
|
+
item: NestedItemBase;
|
|
9
|
+
instances: ComponentInstance[];
|
|
10
|
+
};
|
|
11
|
+
export type StaticNestedItemCache = Map<string, CachedStaticNestedItem>;
|
|
12
|
+
export type SerializedNestedSlotItem<TItem extends NestedItemTreeNode> = Omit<TItem, "component"> & {
|
|
6
13
|
id: string;
|
|
7
|
-
component:
|
|
8
|
-
}
|
|
14
|
+
component: ServerComponentConfig;
|
|
15
|
+
};
|
|
16
|
+
export declare function isItemList(value: unknown): value is ItemList<any, any>;
|
|
17
|
+
export declare function flattenNestedItems<TItem extends NestedItemTreeNode>(source: (TItem | ItemList<any, TItem>)[] | undefined, instance: ComponentInstance, staticCache?: StaticNestedItemCache): SerializedNestedSlotItem<TItem>[];
|
|
9
18
|
export declare function collectNestedComponentsFromSource<TItem extends NestedItemTreeNode>(source: (TItem | ItemList<any, TItem>)[] | undefined): ComponentTreeNode[];
|
|
10
19
|
export declare function releaseItemListInstances(instances: ComponentInstance[]): void;
|
|
11
20
|
export declare function newItemListSegmentId(): string;
|
|
@@ -46,25 +46,31 @@ function isItemList(value) {
|
|
|
46
46
|
value !== null &&
|
|
47
47
|
value.isItemList === true);
|
|
48
48
|
}
|
|
49
|
-
function flattenNestedItems(source, instance) {
|
|
49
|
+
function flattenNestedItems(source, instance, staticCache) {
|
|
50
50
|
const result = [];
|
|
51
51
|
for (const entry of source ?? []) {
|
|
52
52
|
if (isItemList(entry)) {
|
|
53
53
|
result.push(...entry.buildItems(instance));
|
|
54
54
|
}
|
|
55
55
|
else {
|
|
56
|
-
result.push(serializeStaticNestedItem(entry, instance));
|
|
56
|
+
result.push(serializeStaticNestedItem(entry, instance, staticCache));
|
|
57
57
|
}
|
|
58
58
|
}
|
|
59
59
|
return result;
|
|
60
60
|
}
|
|
61
|
-
function serializeStaticNestedItem(entry, instance) {
|
|
61
|
+
function serializeStaticNestedItem(entry, instance, staticCache) {
|
|
62
|
+
const id = entry.component.id;
|
|
63
|
+
const cached = staticCache?.get(id);
|
|
64
|
+
if (cached) {
|
|
65
|
+
return cached.item;
|
|
66
|
+
}
|
|
62
67
|
return (0, core_1.runWithClient)(instance.client, () => (0, core_1.runWithEntryContext)(instance.entry, instance.client, () => {
|
|
63
|
-
const { result } = (0, track_created_instances_1.runWithCreatedInstanceTracking)(() => ({
|
|
68
|
+
const { result, instances } = (0, track_created_instances_1.runWithCreatedInstanceTracking)(() => ({
|
|
64
69
|
...entry,
|
|
65
|
-
id
|
|
70
|
+
id,
|
|
66
71
|
component: entry.component.serialize(),
|
|
67
72
|
}));
|
|
73
|
+
staticCache?.set(id, { item: result, instances });
|
|
68
74
|
return result;
|
|
69
75
|
}));
|
|
70
76
|
}
|
|
@@ -2,6 +2,10 @@ import type { ServerComponentConfig } from "@matreshka/client-bff-protocol/types
|
|
|
2
2
|
import { AnySchemaContextRef, ComponentInstance, ComponentTreeNode } from "../../core";
|
|
3
3
|
import type { ItemListHost } from "./item-list-host";
|
|
4
4
|
import { type ItemListInitConfig, type NestedItemTreeNode } from "./types";
|
|
5
|
+
type SerializedItemListItem<ItemType extends NestedItemTreeNode> = Omit<ItemType, "component"> & {
|
|
6
|
+
id: string;
|
|
7
|
+
component: ServerComponentConfig;
|
|
8
|
+
};
|
|
5
9
|
/**
|
|
6
10
|
* Динамический сегмент nested-элементов (map markers / board items):
|
|
7
11
|
* читает массив из `Context`, генерирует элементы и синхронизирует host через diff.
|
|
@@ -31,11 +35,10 @@ export declare class ItemList<RefType extends AnySchemaContextRef, ItemType exte
|
|
|
31
35
|
onHostShow(): void;
|
|
32
36
|
/** Вызывается host-кomponentом из onHide: отписка, когда host полностью скрыт. */
|
|
33
37
|
onHostHide(): void;
|
|
34
|
-
/** Сериализованные элементы сегмента для flatten / preload. */
|
|
35
|
-
buildItems(instance: ComponentInstance):
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
})[];
|
|
38
|
+
/** Сериализованные элементы сегмента для flatten / preload. Уже отданные id не сериализуются. */
|
|
39
|
+
buildItems(instance: ComponentInstance): SerializedItemListItem<ItemType>[];
|
|
40
|
+
/** Снимает кэш и instances сегмента, когда host-instance уничтожен. */
|
|
41
|
+
releaseHostInstance(instance: ComponentInstance): void;
|
|
39
42
|
/**
|
|
40
43
|
* Дерево nested-кomponentов для walk/registration:
|
|
41
44
|
* из кэша активных instances или dry-run generator по текущему массиву.
|
|
@@ -52,11 +55,13 @@ export declare class ItemList<RefType extends AnySchemaContextRef, ItemType exte
|
|
|
52
55
|
private itemCacheKey;
|
|
53
56
|
/** Публичный id элемента для клиента (без префикса кэша). */
|
|
54
57
|
private trackId;
|
|
55
|
-
/** Lazy-init per-instance state (кэш строк и
|
|
58
|
+
/** Lazy-init per-instance state (кэш строк и уже отданные конфиги). */
|
|
56
59
|
private getInstanceState;
|
|
57
|
-
/**
|
|
58
|
-
private
|
|
59
|
-
/**
|
|
60
|
+
/** Сериализует элемент один раз и сохраняет instances до ухода ключа из массива. */
|
|
61
|
+
private serializeItemOnce;
|
|
62
|
+
/** Снимает instances элементов, которых больше нет в массиве. */
|
|
63
|
+
private evictSerializedItems;
|
|
64
|
+
/** Удаляет из кэша generator строки, которых больше нет в массиве Context. */
|
|
60
65
|
private evictRemovedItemCaches;
|
|
61
66
|
/**
|
|
62
67
|
* Строит элементы сегмента для instance:
|
|
@@ -66,3 +71,4 @@ export declare class ItemList<RefType extends AnySchemaContextRef, ItemType exte
|
|
|
66
71
|
}
|
|
67
72
|
/** Factory для DSL: `itemList({ ref, track, generator, preload? })`. */
|
|
68
73
|
export declare const itemList: <RefType extends AnySchemaContextRef, ItemType extends NestedItemTreeNode = NestedItemTreeNode>(config: ItemListInitConfig<RefType, ItemType>) => ItemList<RefType, ItemType>;
|
|
74
|
+
export {};
|
|
@@ -52,28 +52,43 @@ class ItemList {
|
|
|
52
52
|
this.contextSubscription = undefined;
|
|
53
53
|
}
|
|
54
54
|
}
|
|
55
|
-
/** Сериализованные элементы сегмента для flatten / preload. */
|
|
55
|
+
/** Сериализованные элементы сегмента для flatten / preload. Уже отданные id не сериализуются. */
|
|
56
56
|
buildItems(instance) {
|
|
57
57
|
if (!instance.client) {
|
|
58
58
|
return [];
|
|
59
59
|
}
|
|
60
60
|
return (0, core_1.runWithClient)(instance.client, () => (0, core_1.runWithEntryContext)(instance.entry, instance.client, () => {
|
|
61
|
-
this.releaseItemSyncInstances(instance);
|
|
62
61
|
const items = this.generateItems(instance);
|
|
63
62
|
// Индексы элементов живут во внутреннем контексте itemList (strictRef).
|
|
64
63
|
// Без authorizeClient клиент не получит его и ref вида
|
|
65
64
|
// `departments.@{…index}.name` резолвится в пустую строку.
|
|
66
65
|
this.indexContext.authorizeClient(instance.client);
|
|
67
66
|
const state = this.getInstanceState(instance);
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
67
|
+
this.evictSerializedItems(new Set(items.map((entry) => entry.id)), state);
|
|
68
|
+
const result = [];
|
|
69
|
+
for (const { id, item } of items) {
|
|
70
|
+
const cached = state.serializedById.get(id);
|
|
71
|
+
if (cached) {
|
|
72
|
+
result.push(cached.item);
|
|
73
|
+
continue;
|
|
74
|
+
}
|
|
75
|
+
const serialized = this.serializeItemOnce(id, item, state);
|
|
76
|
+
result.push(serialized);
|
|
77
|
+
}
|
|
74
78
|
return result;
|
|
75
79
|
}));
|
|
76
80
|
}
|
|
81
|
+
/** Снимает кэш и instances сегмента, когда host-instance уничтожен. */
|
|
82
|
+
releaseHostInstance(instance) {
|
|
83
|
+
const state = this.instanceStates.get(instance);
|
|
84
|
+
if (!state) {
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
for (const slot of state.serializedById.values()) {
|
|
88
|
+
(0, flatten_nested_items_1.releaseItemListInstances)(slot.instances);
|
|
89
|
+
}
|
|
90
|
+
this.instanceStates.delete(instance);
|
|
91
|
+
}
|
|
77
92
|
/**
|
|
78
93
|
* Дерево nested-кomponentов для walk/registration:
|
|
79
94
|
* из кэша активных instances или dry-run generator по текущему массиву.
|
|
@@ -143,31 +158,46 @@ class ItemList {
|
|
|
143
158
|
trackId(item) {
|
|
144
159
|
return this.config.track(item);
|
|
145
160
|
}
|
|
146
|
-
/** Lazy-init per-instance state (кэш строк и
|
|
161
|
+
/** Lazy-init per-instance state (кэш строк и уже отданные конфиги). */
|
|
147
162
|
getInstanceState(instance) {
|
|
148
163
|
let state = this.instanceStates.get(instance);
|
|
149
164
|
if (!state) {
|
|
150
165
|
state = {
|
|
151
|
-
itemSyncInstances: [],
|
|
152
166
|
itemsCache: new Map(),
|
|
167
|
+
serializedById: new Map(),
|
|
153
168
|
};
|
|
154
169
|
this.instanceStates.set(instance, state);
|
|
155
170
|
}
|
|
156
171
|
return state;
|
|
157
172
|
}
|
|
158
|
-
/**
|
|
159
|
-
|
|
160
|
-
const
|
|
161
|
-
|
|
162
|
-
|
|
173
|
+
/** Сериализует элемент один раз и сохраняет instances до ухода ключа из массива. */
|
|
174
|
+
serializeItemOnce(id, item, state) {
|
|
175
|
+
const { result, instances } = (0, track_created_instances_1.runWithCreatedInstanceTracking)(() => ({
|
|
176
|
+
...item,
|
|
177
|
+
id,
|
|
178
|
+
component: item.component.serialize(),
|
|
179
|
+
}));
|
|
180
|
+
state.serializedById.set(id, { item: result, instances });
|
|
181
|
+
return result;
|
|
182
|
+
}
|
|
183
|
+
/** Снимает instances элементов, которых больше нет в массиве. */
|
|
184
|
+
evictSerializedItems(currentIds, state) {
|
|
185
|
+
for (const id of [...state.serializedById.keys()]) {
|
|
186
|
+
if (currentIds.has(id)) {
|
|
187
|
+
continue;
|
|
188
|
+
}
|
|
189
|
+
const slot = state.serializedById.get(id);
|
|
190
|
+
if (slot) {
|
|
191
|
+
(0, flatten_nested_items_1.releaseItemListInstances)(slot.instances);
|
|
192
|
+
}
|
|
193
|
+
state.serializedById.delete(id);
|
|
194
|
+
state.itemsCache.delete("id" + id);
|
|
163
195
|
}
|
|
164
|
-
(0, flatten_nested_items_1.releaseItemListInstances)(state.itemSyncInstances);
|
|
165
|
-
state.itemSyncInstances = [];
|
|
166
196
|
}
|
|
167
|
-
/** Удаляет из кэша строки, которых больше нет в массиве Context. */
|
|
197
|
+
/** Удаляет из кэша generator строки, которых больше нет в массиве Context. */
|
|
168
198
|
evictRemovedItemCaches(currentItemIds, instance) {
|
|
169
199
|
const cache = this.getInstanceState(instance).itemsCache;
|
|
170
|
-
for (const itemId of cache.keys()) {
|
|
200
|
+
for (const itemId of [...cache.keys()]) {
|
|
171
201
|
if (!currentItemIds.has(itemId)) {
|
|
172
202
|
cache.delete(itemId);
|
|
173
203
|
}
|
|
@@ -180,6 +210,9 @@ class ItemList {
|
|
|
180
210
|
generateItems(instance) {
|
|
181
211
|
const cache = this.getInstanceState(instance).itemsCache;
|
|
182
212
|
const value = (0, types_1.getItemListValue)(this.config.ref);
|
|
213
|
+
this.lastItemsCheckSum = value
|
|
214
|
+
.map((item) => this.config.track(item))
|
|
215
|
+
.join("|");
|
|
183
216
|
const store = {};
|
|
184
217
|
for (let index = 0; index < value.length; index++) {
|
|
185
218
|
const cacheKey = this.itemCacheKey(value[index]);
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { ComponentInstance } from "../../core";
|
|
2
2
|
import type { ComponentInitConfig } from "../component";
|
|
3
|
-
import {
|
|
3
|
+
import { type SerializedNestedSlotItem, type StaticNestedItemCache } from "./flatten-nested-items";
|
|
4
4
|
import type { ItemList } from "./item-list";
|
|
5
5
|
import type { ItemListHost } from "./item-list-host";
|
|
6
6
|
import type { NestedItemTreeNode } from "./types";
|
|
@@ -24,13 +24,23 @@ export declare function attachItemListsToHost<TItem extends NestedItemTreeNode>(
|
|
|
24
24
|
* `onShow` / `onHide` пробрасываются в `itemList.onHostShow()` / `onHostHide()`.
|
|
25
25
|
*/
|
|
26
26
|
export declare function wireNestedItemsHostLifecycle(config: ComponentInitConfig<any>, itemLists: ItemList<any, any>[]): void;
|
|
27
|
+
export type ItemListHostAdapter<TItem extends NestedItemTreeNode = NestedItemTreeNode> = ItemListHost & {
|
|
28
|
+
/** Снимает кэш слота вместе с host-instance. */
|
|
29
|
+
releaseHostInstance(instance: ComponentInstance): void;
|
|
30
|
+
/**
|
|
31
|
+
* Flat-массив для первого ответа страницы.
|
|
32
|
+
* Помечает id как уже отданные, чтобы следующий sync не слал их снова.
|
|
33
|
+
* Сохраняет поля элемента (position, coordinates, …), не только NestedItemBase.
|
|
34
|
+
*/
|
|
35
|
+
serializeSlot(instance: ComponentInstance): SerializedNestedSlotItem<TItem>[] | undefined;
|
|
36
|
+
};
|
|
27
37
|
/**
|
|
28
|
-
* Адаптер `ItemListHost` для map/board:
|
|
29
|
-
*
|
|
38
|
+
* Адаптер `ItemListHost` для map/board: клиенту уходит порядок id
|
|
39
|
+
* и конфиги только тех элементов, которых у instance ещё нет.
|
|
30
40
|
*/
|
|
31
|
-
export declare function createItemListHostAdapter<TItem extends NestedItemTreeNode>(getInstances: () => readonly ComponentInstance[], getSlotState: (slot: string) => NestedItemsSlotState<TItem> | undefined):
|
|
41
|
+
export declare function createItemListHostAdapter<TItem extends NestedItemTreeNode>(getInstances: () => readonly ComponentInstance[], getSlotState: (slot: string) => NestedItemsSlotState<TItem> | undefined, slotName: string): ItemListHostAdapter<TItem>;
|
|
32
42
|
/**
|
|
33
43
|
* Сериализация slot'а в flat-массив для первого ответа страницы:
|
|
34
44
|
* статика всегда включается, `itemList` — только с `preload: true` и готовыми данными.
|
|
35
45
|
*/
|
|
36
|
-
export declare function flattenNestedItemsForSerialize<TItem extends NestedItemTreeNode>(state: NestedItemsSlotState<TItem> | undefined, instance: ComponentInstance):
|
|
46
|
+
export declare function flattenNestedItemsForSerialize<TItem extends NestedItemTreeNode>(state: NestedItemsSlotState<TItem> | undefined, instance: ComponentInstance, staticCache?: StaticNestedItemCache): SerializedNestedSlotItem<TItem>[] | undefined;
|
|
@@ -63,17 +63,44 @@ function wireNestedItemsHostLifecycle(config, itemLists) {
|
|
|
63
63
|
});
|
|
64
64
|
}
|
|
65
65
|
/**
|
|
66
|
-
* Адаптер `ItemListHost` для map/board:
|
|
67
|
-
*
|
|
66
|
+
* Адаптер `ItemListHost` для map/board: клиенту уходит порядок id
|
|
67
|
+
* и конфиги только тех элементов, которых у instance ещё нет.
|
|
68
68
|
*/
|
|
69
|
-
function createItemListHostAdapter(getInstances, getSlotState) {
|
|
69
|
+
function createItemListHostAdapter(getInstances, getSlotState, slotName) {
|
|
70
|
+
const caches = new Map();
|
|
71
|
+
const cacheFor = (instance) => {
|
|
72
|
+
let cache = caches.get(instance);
|
|
73
|
+
if (!cache) {
|
|
74
|
+
cache = { staticById: new Map(), sentIds: new Set() };
|
|
75
|
+
caches.set(instance, cache);
|
|
76
|
+
}
|
|
77
|
+
return cache;
|
|
78
|
+
};
|
|
79
|
+
const publish = (instance, slot, flat) => {
|
|
80
|
+
const cache = cacheFor(instance);
|
|
81
|
+
const order = flat.map((item) => item.id);
|
|
82
|
+
const nextIds = new Set(order);
|
|
83
|
+
for (const id of [...cache.staticById.keys()]) {
|
|
84
|
+
if (nextIds.has(id)) {
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
const cached = cache.staticById.get(id);
|
|
88
|
+
if (cached) {
|
|
89
|
+
(0, flatten_nested_items_1.releaseItemListInstances)(cached.instances);
|
|
90
|
+
}
|
|
91
|
+
cache.staticById.delete(id);
|
|
92
|
+
}
|
|
93
|
+
const upserts = flat.filter((item) => !cache.sentIds.has(item.id));
|
|
94
|
+
cache.sentIds = nextIds;
|
|
95
|
+
instance.client.outcomingMessage$.next(new nested_items_sync_message_1.NestedItemsSyncMessage(instance.id, { slot, order, upserts }));
|
|
96
|
+
};
|
|
70
97
|
return {
|
|
71
98
|
get hostInstances() {
|
|
72
99
|
return getInstances();
|
|
73
100
|
},
|
|
74
101
|
syncNestedItems(slot, items) {
|
|
75
102
|
for (const instance of getInstances().filter((i) => i.client)) {
|
|
76
|
-
|
|
103
|
+
publish(instance, slot, items);
|
|
77
104
|
}
|
|
78
105
|
},
|
|
79
106
|
resyncNestedSlot(slot) {
|
|
@@ -82,9 +109,35 @@ function createItemListHostAdapter(getInstances, getSlotState) {
|
|
|
82
109
|
return;
|
|
83
110
|
}
|
|
84
111
|
for (const instance of getInstances().filter((i) => i.client)) {
|
|
85
|
-
const
|
|
86
|
-
|
|
112
|
+
const cache = cacheFor(instance);
|
|
113
|
+
const flat = (0, flatten_nested_items_1.flattenNestedItems)(state.source, instance, cache.staticById);
|
|
114
|
+
publish(instance, slot, flat);
|
|
115
|
+
}
|
|
116
|
+
},
|
|
117
|
+
releaseHostInstance(instance) {
|
|
118
|
+
const state = getSlotState(slotName);
|
|
119
|
+
for (const itemList of state?.itemLists ?? []) {
|
|
120
|
+
itemList.releaseHostInstance(instance);
|
|
121
|
+
}
|
|
122
|
+
const cache = caches.get(instance);
|
|
123
|
+
if (cache) {
|
|
124
|
+
for (const cached of cache.staticById.values()) {
|
|
125
|
+
(0, flatten_nested_items_1.releaseItemListInstances)(cached.instances);
|
|
126
|
+
}
|
|
127
|
+
caches.delete(instance);
|
|
128
|
+
}
|
|
129
|
+
},
|
|
130
|
+
serializeSlot(instance) {
|
|
131
|
+
const state = getSlotState(slotName);
|
|
132
|
+
const cache = cacheFor(instance);
|
|
133
|
+
const flat = flattenNestedItemsForSerialize(state, instance, cache.staticById);
|
|
134
|
+
if (!flat) {
|
|
135
|
+
return undefined;
|
|
136
|
+
}
|
|
137
|
+
for (const item of flat) {
|
|
138
|
+
cache.sentIds.add(item.id);
|
|
87
139
|
}
|
|
140
|
+
return flat;
|
|
88
141
|
},
|
|
89
142
|
};
|
|
90
143
|
}
|
|
@@ -92,7 +145,7 @@ function createItemListHostAdapter(getInstances, getSlotState) {
|
|
|
92
145
|
* Сериализация slot'а в flat-массив для первого ответа страницы:
|
|
93
146
|
* статика всегда включается, `itemList` — только с `preload: true` и готовыми данными.
|
|
94
147
|
*/
|
|
95
|
-
function flattenNestedItemsForSerialize(state, instance) {
|
|
148
|
+
function flattenNestedItemsForSerialize(state, instance, staticCache) {
|
|
96
149
|
if (!state || state.source.length === 0) {
|
|
97
150
|
return undefined;
|
|
98
151
|
}
|
|
@@ -105,5 +158,5 @@ function flattenNestedItemsForSerialize(state, instance) {
|
|
|
105
158
|
if (filteredSource.length === 0) {
|
|
106
159
|
return undefined;
|
|
107
160
|
}
|
|
108
|
-
return (0, flatten_nested_items_1.flattenNestedItems)(filteredSource, instance);
|
|
161
|
+
return (0, flatten_nested_items_1.flattenNestedItems)(filteredSource, instance, staticCache);
|
|
109
162
|
}
|
package/dist/components/map.js
CHANGED
|
@@ -44,7 +44,10 @@ class Map extends component_1.Component {
|
|
|
44
44
|
this.markersSlot.source = markersSlot.source;
|
|
45
45
|
this.markersSlot.itemLists = markersSlot.itemLists;
|
|
46
46
|
(0, item_list_1.attachItemListsToHost)(this, "markers", this.markersSlot);
|
|
47
|
-
this.itemListHostAdapter = (0, item_list_1.createItemListHostAdapter)(() => this.instances, (slot) => (slot === "markers" ? this.markersSlot : undefined));
|
|
47
|
+
this.itemListHostAdapter = (0, item_list_1.createItemListHostAdapter)(() => this.instances, (slot) => (slot === "markers" ? this.markersSlot : undefined), "markers");
|
|
48
|
+
this.destroyInstance$.subscribe((released) => {
|
|
49
|
+
this.itemListHostAdapter.releaseHostInstance(released);
|
|
50
|
+
});
|
|
48
51
|
if (config.onCenterChange) {
|
|
49
52
|
const actions = config.onCenterChange;
|
|
50
53
|
this.bindActions("center-change", actions);
|
|
@@ -94,7 +97,7 @@ class Map extends component_1.Component {
|
|
|
94
97
|
instance = this.createInstance();
|
|
95
98
|
}
|
|
96
99
|
const result = super.serialize(instance);
|
|
97
|
-
const markers =
|
|
100
|
+
const markers = this.itemListHostAdapter.serializeSlot(instance);
|
|
98
101
|
return {
|
|
99
102
|
...result,
|
|
100
103
|
class: server_component_class_1.ServerComponentClass.Map,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@matreshka/bff",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.34.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/client-bff-protocol": "^0.
|
|
65
|
+
"@matreshka/client-bff-protocol": "^0.3.0",
|
|
66
66
|
"@matreshka/gateway-bff-protocol": "^0.1.0",
|
|
67
67
|
"@matreshka/shared": "^0.25.1",
|
|
68
68
|
"@simplewebauthn/server": "^13.1.1",
|