@matreshka/bff 0.9.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 (275) hide show
  1. package/LICENSE +32 -0
  2. package/README.md +35 -0
  3. package/dist/components/actions/server-action.d.ts +30 -0
  4. package/dist/components/actions/server-action.js +23 -0
  5. package/dist/components/aliases/button.d.ts +17 -0
  6. package/dist/components/aliases/button.js +54 -0
  7. package/dist/components/aliases/column.d.ts +11 -0
  8. package/dist/components/aliases/column.js +31 -0
  9. package/dist/components/aliases/row.d.ts +11 -0
  10. package/dist/components/aliases/row.js +31 -0
  11. package/dist/components/aliases/surface.d.ts +11 -0
  12. package/dist/components/aliases/surface.js +30 -0
  13. package/dist/components/app.d.ts +5 -0
  14. package/dist/components/app.js +12 -0
  15. package/dist/components/board.d.ts +58 -0
  16. package/dist/components/board.js +152 -0
  17. package/dist/components/boot.d.ts +2 -0
  18. package/dist/components/boot.js +39 -0
  19. package/dist/components/camera.d.ts +77 -0
  20. package/dist/components/camera.js +116 -0
  21. package/dist/components/charts/bar-chart.d.ts +14 -0
  22. package/dist/components/charts/bar-chart.js +27 -0
  23. package/dist/components/charts/chart.d.ts +69 -0
  24. package/dist/components/charts/chart.js +42 -0
  25. package/dist/components/charts/doughnut-chart.d.ts +14 -0
  26. package/dist/components/charts/doughnut-chart.js +27 -0
  27. package/dist/components/charts/line-chart.d.ts +14 -0
  28. package/dist/components/charts/line-chart.js +27 -0
  29. package/dist/components/charts/pie-chart.d.ts +14 -0
  30. package/dist/components/charts/pie-chart.js +27 -0
  31. package/dist/components/charts/polar-area-chart.d.ts +14 -0
  32. package/dist/components/charts/polar-area-chart.js +27 -0
  33. package/dist/components/charts/radar-chart.d.ts +14 -0
  34. package/dist/components/charts/radar-chart.js +27 -0
  35. package/dist/components/component.d.ts +159 -0
  36. package/dist/components/component.js +380 -0
  37. package/dist/components/container.d.ts +48 -0
  38. package/dist/components/container.js +80 -0
  39. package/dist/components/dialog.d.ts +83 -0
  40. package/dist/components/dialog.js +120 -0
  41. package/dist/components/entry-component.d.ts +34 -0
  42. package/dist/components/entry-component.js +74 -0
  43. package/dist/components/enum/password-input-kind.d.ts +1 -0
  44. package/dist/components/enum/password-input-kind.js +5 -0
  45. package/dist/components/enum/popover-position-area.d.ts +1 -0
  46. package/dist/components/enum/popover-position-area.js +5 -0
  47. package/dist/components/enum/text-input-kind.d.ts +1 -0
  48. package/dist/components/enum/text-input-kind.js +5 -0
  49. package/dist/components/enum/textarea-resize.d.ts +1 -0
  50. package/dist/components/enum/textarea-resize.js +5 -0
  51. package/dist/components/file-upload-area.d.ts +79 -0
  52. package/dist/components/file-upload-area.js +138 -0
  53. package/dist/components/for-each.d.ts +188 -0
  54. package/dist/components/for-each.js +362 -0
  55. package/dist/components/form.d.ts +62 -0
  56. package/dist/components/form.js +92 -0
  57. package/dist/components/grid.d.ts +80 -0
  58. package/dist/components/grid.js +79 -0
  59. package/dist/components/index.d.ts +55 -0
  60. package/dist/components/index.js +76 -0
  61. package/dist/components/inputs/input-component.d.ts +37 -0
  62. package/dist/components/inputs/input-component.js +30 -0
  63. package/dist/components/inputs/number-input.d.ts +45 -0
  64. package/dist/components/inputs/number-input.js +43 -0
  65. package/dist/components/inputs/password-input.d.ts +28 -0
  66. package/dist/components/inputs/password-input.js +42 -0
  67. package/dist/components/inputs/text-editor.d.ts +91 -0
  68. package/dist/components/inputs/text-editor.js +282 -0
  69. package/dist/components/inputs/text-input.d.ts +48 -0
  70. package/dist/components/inputs/text-input.js +40 -0
  71. package/dist/components/inputs/textarea.d.ts +36 -0
  72. package/dist/components/inputs/textarea.js +42 -0
  73. package/dist/components/item-list/flatten-nested-items.d.ts +11 -0
  74. package/dist/components/item-list/flatten-nested-items.js +100 -0
  75. package/dist/components/item-list/index.d.ts +5 -0
  76. package/dist/components/item-list/index.js +21 -0
  77. package/dist/components/item-list/item-list-host.d.ts +10 -0
  78. package/dist/components/item-list/item-list-host.js +2 -0
  79. package/dist/components/item-list/item-list.d.ts +68 -0
  80. package/dist/components/item-list/item-list.js +206 -0
  81. package/dist/components/item-list/list-from-ref-context.d.ts +11 -0
  82. package/dist/components/item-list/list-from-ref-context.js +27 -0
  83. package/dist/components/item-list/nested-items-host-support.d.ts +36 -0
  84. package/dist/components/item-list/nested-items-host-support.js +109 -0
  85. package/dist/components/item-list/types.d.ts +40 -0
  86. package/dist/components/item-list/types.js +13 -0
  87. package/dist/components/line.d.ts +43 -0
  88. package/dist/components/line.js +35 -0
  89. package/dist/components/map.d.ts +83 -0
  90. package/dist/components/map.js +146 -0
  91. package/dist/components/outputs/currency.d.ts +63 -0
  92. package/dist/components/outputs/currency.js +42 -0
  93. package/dist/components/outputs/datetime.d.ts +69 -0
  94. package/dist/components/outputs/datetime.js +49 -0
  95. package/dist/components/outputs/icon.d.ts +43 -0
  96. package/dist/components/outputs/icon.js +38 -0
  97. package/dist/components/outputs/iframe.d.ts +48 -0
  98. package/dist/components/outputs/iframe.js +44 -0
  99. package/dist/components/outputs/image.d.ts +73 -0
  100. package/dist/components/outputs/image.js +63 -0
  101. package/dist/components/outputs/number.d.ts +39 -0
  102. package/dist/components/outputs/number.js +47 -0
  103. package/dist/components/outputs/output-component.d.ts +58 -0
  104. package/dist/components/outputs/output-component.js +50 -0
  105. package/dist/components/outputs/progress-bar.d.ts +33 -0
  106. package/dist/components/outputs/progress-bar.js +42 -0
  107. package/dist/components/outputs/progress-spinner.d.ts +37 -0
  108. package/dist/components/outputs/progress-spinner.js +43 -0
  109. package/dist/components/outputs/qr-code.d.ts +28 -0
  110. package/dist/components/outputs/qr-code.js +40 -0
  111. package/dist/components/outputs/text.d.ts +57 -0
  112. package/dist/components/outputs/text.js +78 -0
  113. package/dist/components/outputs/vector.d.ts +47 -0
  114. package/dist/components/outputs/vector.js +53 -0
  115. package/dist/components/page.d.ts +96 -0
  116. package/dist/components/page.js +127 -0
  117. package/dist/components/popover.d.ts +63 -0
  118. package/dist/components/popover.js +96 -0
  119. package/dist/components/stack.d.ts +158 -0
  120. package/dist/components/stack.js +146 -0
  121. package/dist/components/types/component-sequence.d.ts +3 -0
  122. package/dist/components/types/component-sequence.js +2 -0
  123. package/dist/components/types/container-overlay.d.ts +3 -0
  124. package/dist/components/types/container-overlay.js +2 -0
  125. package/dist/components/utils/component-factory-shared.d.ts +4 -0
  126. package/dist/components/utils/component-factory-shared.js +12 -0
  127. package/dist/core/actions/action.d.ts +35 -0
  128. package/dist/core/actions/action.js +45 -0
  129. package/dist/core/actions/animate-component.d.ts +58 -0
  130. package/dist/core/actions/animate-component.js +57 -0
  131. package/dist/core/actions/local-action.d.ts +8 -0
  132. package/dist/core/actions/local-action.js +12 -0
  133. package/dist/core/actions/set-context-value.d.ts +18 -0
  134. package/dist/core/actions/set-context-value.js +32 -0
  135. package/dist/core/actions/set-context-values.d.ts +34 -0
  136. package/dist/core/actions/set-context-values.js +30 -0
  137. package/dist/core/actions/toggle-context-value.d.ts +21 -0
  138. package/dist/core/actions/toggle-context-value.js +30 -0
  139. package/dist/core/actions/write-text-to-clipboard.d.ts +30 -0
  140. package/dist/core/actions/write-text-to-clipboard.js +44 -0
  141. package/dist/core/boot.d.ts +2 -0
  142. package/dist/core/boot.js +8 -0
  143. package/dist/core/client-context.d.ts +7 -0
  144. package/dist/core/client-context.js +20 -0
  145. package/dist/core/client.d.ts +133 -0
  146. package/dist/core/client.js +292 -0
  147. package/dist/core/conditions/condition-group.d.ts +14 -0
  148. package/dist/core/conditions/condition-group.js +30 -0
  149. package/dist/core/conditions/condition-operand.d.ts +27 -0
  150. package/dist/core/conditions/condition-operand.js +15 -0
  151. package/dist/core/conditions/condition.d.ts +27 -0
  152. package/dist/core/conditions/condition.js +35 -0
  153. package/dist/core/conditions/context-array-includes.d.ts +32 -0
  154. package/dist/core/conditions/context-array-includes.js +52 -0
  155. package/dist/core/conditions/context-array-length.d.ts +86 -0
  156. package/dist/core/conditions/context-array-length.js +155 -0
  157. package/dist/core/conditions/context-value-defined.d.ts +12 -0
  158. package/dist/core/conditions/context-value-defined.js +21 -0
  159. package/dist/core/conditions/context-value-equal.d.ts +14 -0
  160. package/dist/core/conditions/context-value-equal.js +26 -0
  161. package/dist/core/conditions/context-value-in.d.ts +17 -0
  162. package/dist/core/conditions/context-value-in.js +26 -0
  163. package/dist/core/conditions/context-value-not-equal.d.ts +14 -0
  164. package/dist/core/conditions/context-value-not-equal.js +26 -0
  165. package/dist/core/conditions/context-value-undefined.d.ts +12 -0
  166. package/dist/core/conditions/context-value-undefined.js +21 -0
  167. package/dist/core/conditions/desktop-device.d.ts +11 -0
  168. package/dist/core/conditions/desktop-device.js +21 -0
  169. package/dist/core/conditions/groups.d.ts +71 -0
  170. package/dist/core/conditions/groups.js +74 -0
  171. package/dist/core/conditions/index.d.ts +17 -0
  172. package/dist/core/conditions/index.js +33 -0
  173. package/dist/core/conditions/mobile-device.d.ts +11 -0
  174. package/dist/core/conditions/mobile-device.js +21 -0
  175. package/dist/core/conditions/not-desktop-device.d.ts +11 -0
  176. package/dist/core/conditions/not-desktop-device.js +21 -0
  177. package/dist/core/conditions/not-mobile-device.d.ts +11 -0
  178. package/dist/core/conditions/not-mobile-device.js +21 -0
  179. package/dist/core/conditions/not-tablet-device.d.ts +11 -0
  180. package/dist/core/conditions/not-tablet-device.js +21 -0
  181. package/dist/core/conditions/tablet-device.d.ts +11 -0
  182. package/dist/core/conditions/tablet-device.js +21 -0
  183. package/dist/core/context/context-ref.d.ts +48 -0
  184. package/dist/core/context/context-ref.js +58 -0
  185. package/dist/core/context/context.d.ts +121 -0
  186. package/dist/core/context/context.js +353 -0
  187. package/dist/core/entry-context.d.ts +14 -0
  188. package/dist/core/entry-context.js +31 -0
  189. package/dist/core/gateway-connection.d.ts +29 -0
  190. package/dist/core/gateway-connection.js +146 -0
  191. package/dist/core/index.d.ts +30 -0
  192. package/dist/core/index.js +46 -0
  193. package/dist/core/matreshka.d.ts +61 -0
  194. package/dist/core/matreshka.js +186 -0
  195. package/dist/core/router.d.ts +38 -0
  196. package/dist/core/router.js +116 -0
  197. package/dist/core/types/client-settings.d.ts +31 -0
  198. package/dist/core/types/client-settings.js +2 -0
  199. package/dist/core/types/component-instance.d.ts +25 -0
  200. package/dist/core/types/component-instance.js +42 -0
  201. package/dist/core/types/component-tree-node.d.ts +11 -0
  202. package/dist/core/types/component-tree-node.js +18 -0
  203. package/dist/core/types/componentable.d.ts +21 -0
  204. package/dist/core/types/componentable.js +2 -0
  205. package/dist/core/types/context-ref-primitive-value.d.ts +5 -0
  206. package/dist/core/types/context-ref-primitive-value.js +2 -0
  207. package/dist/core/types/message.d.ts +15 -0
  208. package/dist/core/types/message.js +2 -0
  209. package/dist/core/types/mixed-with-callbacks-array.d.ts +9 -0
  210. package/dist/core/types/mixed-with-callbacks-array.js +2 -0
  211. package/dist/core/types/native-picker-context-ref.d.ts +7 -0
  212. package/dist/core/types/native-picker-context-ref.js +2 -0
  213. package/dist/core/types/pageable.d.ts +15 -0
  214. package/dist/core/types/pageable.js +2 -0
  215. package/dist/core/types/standalone-component.d.ts +9 -0
  216. package/dist/core/types/standalone-component.js +2 -0
  217. package/dist/core/types/status-code.d.ts +319 -0
  218. package/dist/core/types/status-code.js +322 -0
  219. package/dist/core/utils/calculate-components.d.ts +13 -0
  220. package/dist/core/utils/calculate-components.js +40 -0
  221. package/dist/core/utils/color-token-id.d.ts +11 -0
  222. package/dist/core/utils/color-token-id.js +24 -0
  223. package/dist/core/utils/deep-pick.d.ts +2 -0
  224. package/dist/core/utils/deep-pick.js +54 -0
  225. package/dist/core/utils/hex-to-hsl.d.ts +14 -0
  226. package/dist/core/utils/hex-to-hsl.js +49 -0
  227. package/dist/core/utils/incoming-message-observer.d.ts +9 -0
  228. package/dist/core/utils/incoming-message-observer.js +23 -0
  229. package/dist/core/utils/merge-deep.d.ts +8 -0
  230. package/dist/core/utils/merge-deep.js +39 -0
  231. package/dist/core/utils/objects-diff.d.ts +13 -0
  232. package/dist/core/utils/objects-diff.js +56 -0
  233. package/dist/core/utils/parse-context-path.d.ts +4 -0
  234. package/dist/core/utils/parse-context-path.js +16 -0
  235. package/dist/core/utils/replace-context-keys.d.ts +12 -0
  236. package/dist/core/utils/replace-context-keys.js +90 -0
  237. package/dist/core/utils/serialize-component-tree.d.ts +9 -0
  238. package/dist/core/utils/serialize-component-tree.js +24 -0
  239. package/dist/core/utils/set-object-property.d.ts +2 -0
  240. package/dist/core/utils/set-object-property.js +29 -0
  241. package/dist/core/utils/track-created-instances.d.ts +10 -0
  242. package/dist/core/utils/track-created-instances.js +18 -0
  243. package/dist/core/version.d.ts +1 -0
  244. package/dist/core/version.js +21 -0
  245. package/dist/index.d.ts +3 -0
  246. package/dist/index.js +19 -0
  247. package/dist/platforms/android-platform.d.ts +6 -0
  248. package/dist/platforms/android-platform.js +10 -0
  249. package/dist/platforms/browser-platform.d.ts +79 -0
  250. package/dist/platforms/browser-platform.js +143 -0
  251. package/dist/platforms/client-platform.d.ts +6 -0
  252. package/dist/platforms/client-platform.js +10 -0
  253. package/dist/platforms/index.d.ts +12 -0
  254. package/dist/platforms/index.js +28 -0
  255. package/dist/platforms/ios-platform.d.ts +6 -0
  256. package/dist/platforms/ios-platform.js +10 -0
  257. package/dist/platforms/max-mini-app-platform.d.ts +45 -0
  258. package/dist/platforms/max-mini-app-platform.js +87 -0
  259. package/dist/platforms/mobile-platform.d.ts +117 -0
  260. package/dist/platforms/mobile-platform.js +316 -0
  261. package/dist/platforms/platform.d.ts +109 -0
  262. package/dist/platforms/platform.js +224 -0
  263. package/dist/platforms/pwa-platform.d.ts +6 -0
  264. package/dist/platforms/pwa-platform.js +10 -0
  265. package/dist/platforms/server-platform.d.ts +6 -0
  266. package/dist/platforms/server-platform.js +10 -0
  267. package/dist/platforms/telegram-mini-app-platform.d.ts +87 -0
  268. package/dist/platforms/telegram-mini-app-platform.js +166 -0
  269. package/dist/platforms/utils/client-platform.d.ts +4 -0
  270. package/dist/platforms/utils/client-platform.js +38 -0
  271. package/dist/platforms/utils/mobile-ble-services.d.ts +3 -0
  272. package/dist/platforms/utils/mobile-ble-services.js +31 -0
  273. package/dist/platforms/web-platform.d.ts +9 -0
  274. package/dist/platforms/web-platform.js +13 -0
  275. package/package.json +109 -0
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./flatten-nested-items"), exports);
18
+ __exportStar(require("./item-list"), exports);
19
+ __exportStar(require("./item-list-host"), exports);
20
+ __exportStar(require("./nested-items-host-support"), exports);
21
+ __exportStar(require("./types"), exports);
@@ -0,0 +1,10 @@
1
+ import type { NestedItemBase } from "@matreshka/shared/types/nested-item-base";
2
+ /** Host map/board, принимающий flat nested-items с wire. */
3
+ export type ItemListHost = {
4
+ /** Отправляет клиенту обновлённый flat-массив slot'а. */
5
+ syncNestedItems(slot: string, items: NestedItemBase[]): void;
6
+ /** Пересобирает весь slot после изменения сегмента itemList. */
7
+ resyncNestedSlot(slot: string): void;
8
+ /** Активные instances host-кomponenta на клиенте. */
9
+ readonly hostInstances: readonly import("../../core").ComponentInstance[];
10
+ };
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,68 @@
1
+ import type { ServerComponentConfig } from "@matreshka/shared/types/server-component-config";
2
+ import { ComponentInstance, ComponentTreeNode, ContextRef } from "../../core";
3
+ import type { ItemListHost } from "./item-list-host";
4
+ import { type ItemListInitConfig, type NestedItemTreeNode } from "./types";
5
+ /**
6
+ * Динамический сегмент nested-элементов (map markers / board items):
7
+ * читает массив из `Context`, генерирует элементы и синхронизирует host через diff.
8
+ */
9
+ export declare class ItemList<RefType extends ContextRef<any, any>, ItemType extends NestedItemTreeNode = NestedItemTreeNode> {
10
+ readonly isItemList: true;
11
+ /** Уникальный id сегмента для nested path и release instances. */
12
+ readonly segmentId: string;
13
+ readonly preload: boolean;
14
+ private readonly config;
15
+ /** Скрытый контекст индексов строк для `ref` внутри generator. */
16
+ private readonly indexContext;
17
+ private host?;
18
+ private slot?;
19
+ /** Счётчик видимых host-instances (onShow/onHide). */
20
+ private hostShowCount;
21
+ private contextSubscription?;
22
+ /** Checksum track-ключей — пропуск лишнего resync. */
23
+ private lastItemsCheckSum;
24
+ private readonly instanceStates;
25
+ constructor(config: ItemListInitConfig<RefType, ItemType>);
26
+ /** Включать сегмент в preload-serialize страницы. */
27
+ shouldIncludeInPreloadSerialize(): boolean;
28
+ /** Привязывает сегмент к host-кomponentu (map/board) и имени slot'а. */
29
+ attach(host: ItemListHost, slot: string): void;
30
+ /** Вызывается host-кomponentом из onShow: подписка на Context и первый sync. */
31
+ onHostShow(): void;
32
+ /** Вызывается host-кomponentом из onHide: отписка, когда host полностью скрыт. */
33
+ onHostHide(): void;
34
+ /** Сериализованные элементы сегмента для flatten / preload. */
35
+ buildItems(instance: ComponentInstance): (Omit<ItemType, "component"> & {
36
+ id: string;
37
+ component: ServerComponentConfig;
38
+ })[];
39
+ /**
40
+ * Дерево nested-кomponentов для walk/registration:
41
+ * из кэша активных instances или dry-run generator по текущему массиву.
42
+ */
43
+ getNestedComponents(): ComponentTreeNode[];
44
+ /** Подписывается на изменения массива в `Context` после init. */
45
+ private subscribeToListRef;
46
+ /**
47
+ * Пересобирает slot на host'е, если изменился состав/порядок (по `track`).
48
+ * `onlyIfChanged: false` — принудительный sync (onShow / preload).
49
+ */
50
+ private syncToHost;
51
+ /** Стабильный ключ кэша строки: префикс `id` + результат `track`. */
52
+ private itemCacheKey;
53
+ /** Публичный id элемента для клиента (без префикса кэша). */
54
+ private trackId;
55
+ /** Lazy-init per-instance state (кэш строк и sync instances). */
56
+ private getInstanceState;
57
+ /** Освобождает временные instances, созданные при прошлой сериализации. */
58
+ private releaseItemSyncInstances;
59
+ /** Удаляет из кэша строки, которых больше нет в массиве Context. */
60
+ private evictRemovedItemCaches;
61
+ /**
62
+ * Строит элементы сегмента для instance:
63
+ * переиспользует кэш по track-ключу, обновляет index store для item ref.
64
+ */
65
+ private generateItems;
66
+ }
67
+ /** Factory для DSL: `itemList({ ref, track, generator, preload? })`. */
68
+ export declare const itemList: <RefType extends ContextRef<any, any>, ItemType extends NestedItemTreeNode = NestedItemTreeNode>(config: ItemListInitConfig<RefType, ItemType>) => ItemList<RefType, ItemType>;
@@ -0,0 +1,206 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.itemList = exports.ItemList = void 0;
4
+ const rxjs_1 = require("rxjs");
5
+ const core_1 = require("../../core");
6
+ const track_created_instances_1 = require("../../core/utils/track-created-instances");
7
+ const flatten_nested_items_1 = require("./flatten-nested-items");
8
+ const list_from_ref_context_1 = require("./list-from-ref-context");
9
+ const types_1 = require("./types");
10
+ /**
11
+ * Динамический сегмент nested-элементов (map markers / board items):
12
+ * читает массив из `Context`, генерирует элементы и синхронизирует host через diff.
13
+ */
14
+ class ItemList {
15
+ constructor(config) {
16
+ this.isItemList = true;
17
+ /** Уникальный id сегмента для nested path и release instances. */
18
+ this.segmentId = (0, flatten_nested_items_1.newItemListSegmentId)();
19
+ /** Счётчик видимых host-instances (onShow/onHide). */
20
+ this.hostShowCount = 0;
21
+ /** Checksum track-ключей — пропуск лишнего resync. */
22
+ this.lastItemsCheckSum = "";
23
+ this.instanceStates = new Map();
24
+ this.config = config;
25
+ this.preload = config.preload ?? false;
26
+ this.indexContext = new list_from_ref_context_1.ItemListIndexStore(config.ref.context.preload);
27
+ void this.indexContext.initSync();
28
+ }
29
+ /** Включать сегмент в preload-serialize страницы. */
30
+ shouldIncludeInPreloadSerialize() {
31
+ return this.preload && this.config.ref.context.inited();
32
+ }
33
+ /** Привязывает сегмент к host-кomponentu (map/board) и имени slot'а. */
34
+ attach(host, slot) {
35
+ this.host = host;
36
+ this.slot = slot;
37
+ }
38
+ /** Вызывается host-кomponentом из onShow: подписка на Context и первый sync. */
39
+ onHostShow() {
40
+ this.hostShowCount++;
41
+ if (this.hostShowCount === 1) {
42
+ this.subscribeToListRef();
43
+ }
44
+ this.syncToHost(this.preload);
45
+ }
46
+ /** Вызывается host-кomponentом из onHide: отписка, когда host полностью скрыт. */
47
+ onHostHide() {
48
+ this.hostShowCount--;
49
+ if (this.hostShowCount <= 0) {
50
+ this.hostShowCount = 0;
51
+ this.contextSubscription?.unsubscribe();
52
+ this.contextSubscription = undefined;
53
+ }
54
+ }
55
+ /** Сериализованные элементы сегмента для flatten / preload. */
56
+ buildItems(instance) {
57
+ if (!instance.client) {
58
+ return [];
59
+ }
60
+ return (0, core_1.runWithClient)(instance.client, () => (0, core_1.runWithEntryContext)(instance.entry, instance.client, () => {
61
+ this.releaseItemSyncInstances(instance);
62
+ const items = this.generateItems(instance);
63
+ // Индексы элементов живут во внутреннем контексте itemList (strictRef).
64
+ // Без authorizeClient клиент не получит его и ref вида
65
+ // `departments.@{…index}.name` резолвится в пустую строку.
66
+ this.indexContext.authorizeClient(instance.client);
67
+ const state = this.getInstanceState(instance);
68
+ const { result, instances } = (0, track_created_instances_1.runWithCreatedInstanceTracking)(() => items.map(({ id, item }) => ({
69
+ ...item,
70
+ id,
71
+ component: item.component.serialize(),
72
+ })));
73
+ state.itemSyncInstances = instances;
74
+ return result;
75
+ }));
76
+ }
77
+ /**
78
+ * Дерево nested-кomponentов для walk/registration:
79
+ * из кэша активных instances или dry-run generator по текущему массиву.
80
+ */
81
+ getNestedComponents() {
82
+ const components = [];
83
+ for (const state of this.instanceStates.values()) {
84
+ for (const item of state.itemsCache.values()) {
85
+ components.push(item.component);
86
+ }
87
+ }
88
+ if (components.length > 0) {
89
+ return components;
90
+ }
91
+ const value = (0, types_1.getItemListValue)(this.config.ref);
92
+ for (const data of value) {
93
+ const cacheKey = this.itemCacheKey(data);
94
+ const item = this.config.generator({
95
+ ref: (0, types_1.createItemListItemLink)(this.config.ref, this.indexContext.ref(`${cacheKey}.index`)),
96
+ itemList: this,
97
+ });
98
+ components.push(item.component);
99
+ }
100
+ return components;
101
+ }
102
+ /** Подписывается на изменения массива в `Context` после init. */
103
+ subscribeToListRef() {
104
+ if (this.contextSubscription) {
105
+ return;
106
+ }
107
+ const contextSubscription = new rxjs_1.Subscription();
108
+ this.contextSubscription = contextSubscription;
109
+ contextSubscription.add(this.config.ref.context.init$.subscribe(() => {
110
+ contextSubscription.add(this.config.ref.context.data$.pipe((0, rxjs_1.skip)(1)).subscribe(() => {
111
+ this.syncToHost(true);
112
+ }));
113
+ }));
114
+ }
115
+ /**
116
+ * Пересобирает slot на host'е, если изменился состав/порядок (по `track`).
117
+ * `onlyIfChanged: false` — принудительный sync (onShow / preload).
118
+ */
119
+ syncToHost(onlyIfChanged) {
120
+ const value = (0, types_1.getItemListValue)(this.config.ref);
121
+ const itemsCheckSum = value.map(this.config.track).join("|");
122
+ if (itemsCheckSum === this.lastItemsCheckSum && onlyIfChanged) {
123
+ return;
124
+ }
125
+ this.lastItemsCheckSum = itemsCheckSum;
126
+ const host = this.host;
127
+ const slot = this.slot;
128
+ if (!host || !slot || host.hostInstances.length === 0) {
129
+ return;
130
+ }
131
+ const currentItemIds = new Set(value.map((item) => this.itemCacheKey(item)));
132
+ for (const instance of host.hostInstances) {
133
+ this.evictRemovedItemCaches(currentItemIds, instance);
134
+ }
135
+ host.resyncNestedSlot(slot);
136
+ }
137
+ /** Стабильный ключ кэша строки: префикс `id` + результат `track`. */
138
+ itemCacheKey(item) {
139
+ return "id" + this.config.track(item);
140
+ }
141
+ /** Публичный id элемента для клиента (без префикса кэша). */
142
+ trackId(item) {
143
+ return this.config.track(item);
144
+ }
145
+ /** Lazy-init per-instance state (кэш строк и sync instances). */
146
+ getInstanceState(instance) {
147
+ let state = this.instanceStates.get(instance);
148
+ if (!state) {
149
+ state = {
150
+ itemSyncInstances: [],
151
+ itemsCache: new Map(),
152
+ };
153
+ this.instanceStates.set(instance, state);
154
+ }
155
+ return state;
156
+ }
157
+ /** Освобождает временные instances, созданные при прошлой сериализации. */
158
+ releaseItemSyncInstances(instance) {
159
+ const state = this.instanceStates.get(instance);
160
+ if (!state || state.itemSyncInstances.length === 0) {
161
+ return;
162
+ }
163
+ (0, flatten_nested_items_1.releaseItemListInstances)(state.itemSyncInstances);
164
+ state.itemSyncInstances = [];
165
+ }
166
+ /** Удаляет из кэша строки, которых больше нет в массиве Context. */
167
+ evictRemovedItemCaches(currentItemIds, instance) {
168
+ const cache = this.getInstanceState(instance).itemsCache;
169
+ for (const itemId of cache.keys()) {
170
+ if (!currentItemIds.has(itemId)) {
171
+ cache.delete(itemId);
172
+ }
173
+ }
174
+ }
175
+ /**
176
+ * Строит элементы сегмента для instance:
177
+ * переиспользует кэш по track-ключу, обновляет index store для item ref.
178
+ */
179
+ generateItems(instance) {
180
+ const cache = this.getInstanceState(instance).itemsCache;
181
+ const value = (0, types_1.getItemListValue)(this.config.ref);
182
+ const store = this.indexContext.data$.getValue();
183
+ for (const key of Object.keys(store)) {
184
+ delete store[key];
185
+ }
186
+ const items = value.map((data, index) => {
187
+ const cacheKey = this.itemCacheKey(data);
188
+ store[cacheKey] = { index: `${index}` };
189
+ let item = cache.get(cacheKey);
190
+ if (!item) {
191
+ item = this.config.generator({
192
+ ref: (0, types_1.createItemListItemLink)(this.config.ref, this.indexContext.ref(`${cacheKey}.index`)),
193
+ itemList: this,
194
+ });
195
+ cache.set(cacheKey, item);
196
+ }
197
+ return { id: this.trackId(data), item };
198
+ });
199
+ this.indexContext.syncIndexStoreFromMutations();
200
+ return items;
201
+ }
202
+ }
203
+ exports.ItemList = ItemList;
204
+ /** Factory для DSL: `itemList({ ref, track, generator, preload? })`. */
205
+ const itemList = (config) => new ItemList(config);
206
+ exports.itemList = itemList;
@@ -0,0 +1,11 @@
1
+ import { Context, type JsonObject } from "../../core";
2
+ type ItemListIndexContext = Record<string, {
3
+ index: `${number}`;
4
+ }>;
5
+ /** Контекст индексов элементов ItemList; данные не загружаются снаружи. */
6
+ export declare class ItemListIndexStore<T extends JsonObject = ItemListIndexContext> extends Context<T> {
7
+ initSync(): this;
8
+ syncIndexStoreFromMutations(): void;
9
+ constructor(preload: boolean);
10
+ }
11
+ export {};
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ItemListIndexStore = void 0;
4
+ const rxjs_1 = require("rxjs");
5
+ const v4_1 = require("zod/v4");
6
+ const core_1 = require("../../core");
7
+ /** Контекст индексов элементов ItemList; данные не загружаются снаружи. */
8
+ class ItemListIndexStore extends core_1.Context {
9
+ initSync() {
10
+ if (this.inited())
11
+ return this;
12
+ this.data$ = new rxjs_1.BehaviorSubject({});
13
+ this.subscribeToDataChanges();
14
+ return this;
15
+ }
16
+ syncIndexStoreFromMutations() {
17
+ super.emitAfterInPlaceMutation();
18
+ }
19
+ constructor(preload) {
20
+ super({
21
+ data: async () => ({}),
22
+ preload,
23
+ schema: v4_1.z.strictObject({}),
24
+ });
25
+ }
26
+ }
27
+ exports.ItemListIndexStore = ItemListIndexStore;
@@ -0,0 +1,36 @@
1
+ import type { ComponentInstance } from "../../core";
2
+ import type { ComponentInitConfig } from "../component";
3
+ import { flattenNestedItems } from "./flatten-nested-items";
4
+ import type { ItemList } from "./item-list";
5
+ import type { ItemListHost } from "./item-list-host";
6
+ import type { NestedItemTreeNode } from "./types";
7
+ /** Runtime-состояние slot'а nested-элементов host-кomponenta (map/board). */
8
+ export type NestedItemsSlotState<TItem extends NestedItemTreeNode> = {
9
+ /** Имя slot'а на клиенте (`markers`, `items` и т.п.). */
10
+ slot: string;
11
+ /** Исходный гибридный массив: статические элементы и `itemList`. */
12
+ source: (TItem | ItemList<any, TItem>)[];
13
+ /** Все `itemList`, найденные в `source` — для attach и lifecycle. */
14
+ itemLists: ItemList<any, TItem>[];
15
+ };
16
+ /** Создаёт начальное состояние slot'а из конфига host-кomponenta. */
17
+ export declare function createNestedItemsSlotState<TItem extends NestedItemTreeNode>(source: (TItem | ItemList<any, TItem>)[] | undefined): NestedItemsSlotState<TItem>;
18
+ /** Собирает все `itemList` из гибридного массива, сохраняя порядок. */
19
+ export declare function collectItemListsFromSource<TItem extends NestedItemTreeNode>(source: (TItem | ItemList<any, TItem>)[] | undefined): ItemList<any, TItem>[];
20
+ /** Привязывает `itemList` к host'у и записывает имя slot'а в состояние. */
21
+ export declare function attachItemListsToHost<TItem extends NestedItemTreeNode>(host: ItemListHost, slot: string, state: NestedItemsSlotState<TItem>): void;
22
+ /**
23
+ * Подписывает все `itemList` на lifecycle host-кomponenta:
24
+ * `onShow` / `onHide` пробрасываются в `itemList.onHostShow()` / `onHostHide()`.
25
+ */
26
+ export declare function wireNestedItemsHostLifecycle(config: ComponentInitConfig<any>, itemLists: ItemList<any, any>[]): void;
27
+ /**
28
+ * Адаптер `ItemListHost` для map/board: отправляет клиенту
29
+ * `NestedItemsSyncMessage` всем активным instances host-кomponenta.
30
+ */
31
+ export declare function createItemListHostAdapter<TItem extends NestedItemTreeNode>(getInstances: () => readonly ComponentInstance[], getSlotState: (slot: string) => NestedItemsSlotState<TItem> | undefined): ItemListHost;
32
+ /**
33
+ * Сериализация slot'а в flat-массив для первого ответа страницы:
34
+ * статика всегда включается, `itemList` — только с `preload: true` и готовыми данными.
35
+ */
36
+ export declare function flattenNestedItemsForSerialize<TItem extends NestedItemTreeNode>(state: NestedItemsSlotState<TItem> | undefined, instance: ComponentInstance): ReturnType<typeof flattenNestedItems<TItem, any>> | undefined;
@@ -0,0 +1,109 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createNestedItemsSlotState = createNestedItemsSlotState;
4
+ exports.collectItemListsFromSource = collectItemListsFromSource;
5
+ exports.attachItemListsToHost = attachItemListsToHost;
6
+ exports.wireNestedItemsHostLifecycle = wireNestedItemsHostLifecycle;
7
+ exports.createItemListHostAdapter = createItemListHostAdapter;
8
+ exports.flattenNestedItemsForSerialize = flattenNestedItemsForSerialize;
9
+ const nested_items_sync_message_1 = require("@matreshka/shared/messages/bff-to-client/components/nested-items/nested-items-sync-message");
10
+ const flatten_nested_items_1 = require("./flatten-nested-items");
11
+ /** Создаёт начальное состояние slot'а из конфига host-кomponenta. */
12
+ function createNestedItemsSlotState(source) {
13
+ const normalizedSource = source ?? [];
14
+ return {
15
+ slot: "",
16
+ source: normalizedSource,
17
+ itemLists: collectItemListsFromSource(normalizedSource),
18
+ };
19
+ }
20
+ /** Собирает все `itemList` из гибридного массива, сохраняя порядок. */
21
+ function collectItemListsFromSource(source) {
22
+ const itemLists = [];
23
+ for (const entry of source ?? []) {
24
+ if ((0, flatten_nested_items_1.isItemList)(entry)) {
25
+ itemLists.push(entry);
26
+ }
27
+ }
28
+ return itemLists;
29
+ }
30
+ /** Привязывает `itemList` к host'у и записывает имя slot'а в состояние. */
31
+ function attachItemListsToHost(host, slot, state) {
32
+ state.slot = slot;
33
+ for (const itemList of state.itemLists) {
34
+ itemList.attach(host, slot);
35
+ }
36
+ }
37
+ /**
38
+ * Подписывает все `itemList` на lifecycle host-кomponenta:
39
+ * `onShow` / `onHide` пробрасываются в `itemList.onHostShow()` / `onHostHide()`.
40
+ */
41
+ function wireNestedItemsHostLifecycle(config, itemLists) {
42
+ if (typeof config.onShow === "undefined") {
43
+ config.onShow = [];
44
+ }
45
+ if (typeof config.onShow === "function") {
46
+ config.onShow = [config.onShow];
47
+ }
48
+ config.onShow.push(() => {
49
+ for (const itemList of itemLists) {
50
+ itemList.onHostShow();
51
+ }
52
+ });
53
+ if (typeof config.onHide === "undefined") {
54
+ config.onHide = [];
55
+ }
56
+ if (typeof config.onHide === "function") {
57
+ config.onHide = [config.onHide];
58
+ }
59
+ config.onHide.push(() => {
60
+ for (const itemList of itemLists) {
61
+ itemList.onHostHide();
62
+ }
63
+ });
64
+ }
65
+ /**
66
+ * Адаптер `ItemListHost` для map/board: отправляет клиенту
67
+ * `NestedItemsSyncMessage` всем активным instances host-кomponenta.
68
+ */
69
+ function createItemListHostAdapter(getInstances, getSlotState) {
70
+ return {
71
+ get hostInstances() {
72
+ return getInstances();
73
+ },
74
+ syncNestedItems(slot, items) {
75
+ for (const instance of getInstances().filter((i) => i.client)) {
76
+ instance.client.outcomingMessage$.next(new nested_items_sync_message_1.NestedItemsSyncMessage(instance.id, { slot, items }));
77
+ }
78
+ },
79
+ resyncNestedSlot(slot) {
80
+ const state = getSlotState(slot);
81
+ if (!state) {
82
+ return;
83
+ }
84
+ for (const instance of getInstances().filter((i) => i.client)) {
85
+ const flat = (0, flatten_nested_items_1.flattenNestedItems)(state.source, instance);
86
+ instance.client.outcomingMessage$.next(new nested_items_sync_message_1.NestedItemsSyncMessage(instance.id, { slot, items: flat }));
87
+ }
88
+ },
89
+ };
90
+ }
91
+ /**
92
+ * Сериализация slot'а в flat-массив для первого ответа страницы:
93
+ * статика всегда включается, `itemList` — только с `preload: true` и готовыми данными.
94
+ */
95
+ function flattenNestedItemsForSerialize(state, instance) {
96
+ if (!state || state.source.length === 0) {
97
+ return undefined;
98
+ }
99
+ const filteredSource = state.source.filter((entry) => {
100
+ if (!(0, flatten_nested_items_1.isItemList)(entry)) {
101
+ return true;
102
+ }
103
+ return entry.shouldIncludeInPreloadSerialize();
104
+ });
105
+ if (filteredSource.length === 0) {
106
+ return undefined;
107
+ }
108
+ return (0, flatten_nested_items_1.flattenNestedItems)(filteredSource, instance);
109
+ }
@@ -0,0 +1,40 @@
1
+ import type { Paths, PathValue } from "ts-essentials";
2
+ import type { ComponentTreeNode, ContextRef, JsonObject } from "../../core";
3
+ export type ListArrayValue = readonly unknown[] | unknown[];
4
+ type ItemArray<RefType extends ContextRef<any, any>> = Extract<ReturnType<RefType["value"]>, ListArrayValue>;
5
+ export type CompatibleItemListRef<RefType extends ContextRef<any, any>> = [
6
+ ItemArray<RefType>
7
+ ] extends [never] ? never : RefType;
8
+ export type ItemListItemData<RefType extends ContextRef<any, any>> = ItemArray<RefType>[number];
9
+ export type ItemListTypedItemRef<ContextType extends JsonObject, PathType extends string, ValueType> = Omit<ContextRef<any, any>, "path" | "ref" | "value"> & {
10
+ readonly path: PathType;
11
+ readonly __valueType?: ValueType;
12
+ value(): ValueType;
13
+ value(): JsonObject;
14
+ ref<K extends Paths<ValueType>>(path: K): ItemListTypedItemRef<ContextType, `${PathType}.${K & string}`, PathValue<ValueType, K>>;
15
+ ref<P2 extends string>(path: ContextRef<ContextType, P2>): ContextRef<ContextType, `${PathType}.${P2}`>;
16
+ };
17
+ export type ItemListItemLink<RefType extends ContextRef<any, any>> = RefType extends ContextRef<infer ContextType, infer PathType> ? ItemListTypedItemRef<ContextType, `${PathType}.${number}`, ItemListItemData<RefType>> : never;
18
+ export type NestedItemTreeNode = {
19
+ component: ComponentTreeNode;
20
+ };
21
+ export type ItemListGeneratorProperties<RefType extends ContextRef<any, any>, ItemType extends NestedItemTreeNode = NestedItemTreeNode> = {
22
+ ref: ItemListItemLink<RefType>;
23
+ itemList: {
24
+ readonly segmentId: string;
25
+ };
26
+ };
27
+ export type ItemListInitConfig<RefType extends ContextRef<any, any>, ItemType extends NestedItemTreeNode = NestedItemTreeNode> = {
28
+ ref: CompatibleItemListRef<RefType>;
29
+ track: (data: ItemListItemData<RefType>) => string;
30
+ preload?: boolean;
31
+ generator: (properties: ItemListGeneratorProperties<RefType, ItemType>) => ItemType;
32
+ };
33
+ export declare function getItemListValue<RefType extends ContextRef<any, any>>(ref: RefType): ItemListItemData<RefType>[];
34
+ type ItemListIndexContextRecord = Record<string, {
35
+ index: `${number}`;
36
+ }>;
37
+ export declare function createItemListItemLink<ContextType extends JsonObject, PathType extends string, RefType extends ContextRef<ContextType, PathType> & {
38
+ value(): ListArrayValue | undefined;
39
+ }>(ref: RefType, indexRef: ContextRef<ItemListIndexContextRecord, `${string}.index`>): ItemListItemLink<RefType>;
40
+ export {};
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getItemListValue = getItemListValue;
4
+ exports.createItemListItemLink = createItemListItemLink;
5
+ function getItemListValue(ref) {
6
+ const rawValue = ref.value();
7
+ return Array.isArray(rawValue)
8
+ ? rawValue
9
+ : [];
10
+ }
11
+ function createItemListItemLink(ref, indexRef) {
12
+ return ref.strictRef(indexRef);
13
+ }
@@ -0,0 +1,43 @@
1
+ import { ServerComponentClass } from "@matreshka/shared/enums/server-component-class";
2
+ import { Componentable, StandaloneComponent } from "../core";
3
+ import { ComponentInitConfig as BaseComponentInitConfig, Component, ComponentProperties } from "./component";
4
+ /**
5
+ * Свойства компонента Line.
6
+ */
7
+ export type LineProperties = ComponentProperties & {
8
+ /**
9
+ * Толщина линии в пикселях (на клиенте преобразуется в rem).
10
+ */
11
+ size?: number;
12
+ /**
13
+ * Радиус скругления в пикселях (на клиенте преобразуется в rem).
14
+ */
15
+ radius?: number;
16
+ };
17
+ /**
18
+ * Конфигурация инициализации для компонента Line.
19
+ */
20
+ export type LineInitConfig<ComponentType extends Componentable = Line, PropertiesType extends LineProperties = LineProperties> = BaseComponentInitConfig<ComponentType, PropertiesType> & {
21
+ size?: number;
22
+ radius?: number;
23
+ };
24
+ type DefaultInitConfigType = LineInitConfig<Line>;
25
+ export declare const line: (options?: LineInitConfig<Line>) => Line;
26
+ /**
27
+ * Компонент-линия, отображающий горизонтальную или вертикальную линию.
28
+ */
29
+ export declare class Line<InitConfigType extends LineInitConfig<any> = DefaultInitConfigType, PropertiesType extends LineProperties = LineProperties> extends Component<InitConfigType, PropertiesType> implements StandaloneComponent {
30
+ protected initProperties(initValues: InitConfigType): PropertiesType;
31
+ /**
32
+ * Возвращает флаг, указывающий, что компонент является самостоятельным.
33
+ * @returns Всегда true.
34
+ */
35
+ standalone(): true;
36
+ /**
37
+ * Возвращает уникальный идентификатор класса компонента.
38
+ *
39
+ * @returns Строка с именем CSS-класса.
40
+ */
41
+ protected class(): ServerComponentClass;
42
+ }
43
+ export {};
@@ -0,0 +1,35 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Line = exports.line = void 0;
4
+ const server_component_class_1 = require("@matreshka/shared/enums/server-component-class");
5
+ const component_1 = require("./component");
6
+ const line = (options = {}) => new Line(options);
7
+ exports.line = line;
8
+ /**
9
+ * Компонент-линия, отображающий горизонтальную или вертикальную линию.
10
+ */
11
+ class Line extends component_1.Component {
12
+ initProperties(initValues) {
13
+ return {
14
+ ...super.initProperties(initValues),
15
+ size: initValues.size,
16
+ radius: initValues.radius,
17
+ };
18
+ }
19
+ /**
20
+ * Возвращает флаг, указывающий, что компонент является самостоятельным.
21
+ * @returns Всегда true.
22
+ */
23
+ standalone() {
24
+ return true;
25
+ }
26
+ /**
27
+ * Возвращает уникальный идентификатор класса компонента.
28
+ *
29
+ * @returns Строка с именем CSS-класса.
30
+ */
31
+ class() {
32
+ return server_component_class_1.ServerComponentClass.Line;
33
+ }
34
+ }
35
+ exports.Line = Line;