@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,188 @@
1
+ import { ServerComponentClass } from "@matreshka/shared/enums/server-component-class";
2
+ import type { ForEachConfig } from "@matreshka/shared/types/for-each-config";
3
+ import { Paths, PathValue } from "ts-essentials";
4
+ import { ComponentInstance, ComponentTreeNode, Context, ContextRef, ContextRefValue, JsonObject, StandaloneComponent } from "../core";
5
+ import { Component, ComponentInitConfig, ComponentProperties } from "./component";
6
+ type ForEachArrayValue = readonly unknown[] | unknown[];
7
+ type ForEachItemArray<RefType extends ContextRef<any, any>> = Extract<ContextRefValue<RefType>, ForEachArrayValue>;
8
+ export type CompatibleForEachRef<RefType extends ContextRef<any, any>> = [
9
+ ForEachItemArray<RefType>
10
+ ] extends [never] ? never : RefType;
11
+ type ForEachItemData<RefType extends ContextRef<any, any>> = ForEachItemArray<RefType>[number];
12
+ type ForEachTypedItemRef<ContextType extends JsonObject, PathType extends string, ValueType> = Omit<ContextRef<any, any>, "context" | "path" | "ref" | "value"> & {
13
+ readonly context: Context<ContextType>;
14
+ readonly path: PathType;
15
+ readonly __valueType?: ValueType;
16
+ value(): ValueType;
17
+ value(): JsonObject;
18
+ ref<K extends Paths<ValueType>>(path: K): ForEachTypedItemRef<ContextType, `${PathType}.${K & string}`, PathValue<ValueType, K>>;
19
+ ref<P2 extends string>(path: ContextRef<ContextType, P2>): ContextRef<ContextType, `${PathType}.${P2}`>;
20
+ };
21
+ type ForEachItemLink<RefType extends ContextRef<any, any>> = RefType extends ContextRef<infer ContextType, infer PathType> ? ForEachTypedItemRef<ContextType, `${PathType}.${number}`, ForEachItemData<RefType>> : never;
22
+ export type ForEachDataRef<DataType> = ContextRef<any, any> & {
23
+ readonly __valueType?: DataType[];
24
+ value(): DataType[] | undefined;
25
+ };
26
+ /**
27
+ * Свойства, передаваемые генератору компонентов в `ForEach`.
28
+ *
29
+ * @property component Компонент `ForEach`, инициирующий генерацию.
30
+ * @property key Ключ контекста, в котором хранятся данные элемента.
31
+ */
32
+ export type ForEachGeneratorProperties<RefType extends ContextRef<any, any>, ComponentType extends ComponentTreeNode = ComponentTreeNode> = {
33
+ component: ForEach<RefType, ComponentType>;
34
+ ref: ForEachItemLink<RefType>;
35
+ };
36
+ /**
37
+ * Свойства компонента `ForEach`.
38
+ *
39
+ * @property ref Ссылка в контексте, по которой хранятся данные списка.
40
+ */
41
+ export type ForEachProperties = {
42
+ ref: ContextRef<any, any>;
43
+ componentContext: Context<any>;
44
+ components?: (ComponentTreeNode | ComponentTreeNode[])[];
45
+ divider?: ComponentTreeNode[];
46
+ } & ComponentProperties;
47
+ export declare const forEach: <RefType extends ContextRef<any, any>, ComponentType extends ComponentTreeNode = ComponentTreeNode, PropertiesType extends ForEachProperties = ForEachProperties>(config: ForEachInitConfig<RefType, ComponentType, PropertiesType>) => ForEach<RefType, ComponentType, PropertiesType>;
48
+ /**
49
+ * Конфигурация инициализации компонента `ForEach`.
50
+ *
51
+ * @property ref Ссылка в контексте, по которой хранятся данные списка.
52
+ * @property track Функция, возвращающая уникальный идентификатор для каждого элемента данных.
53
+ * @property preload Флаг, указывающий, что компонент должен генерировать компоненты при инициализации, ускоряет загрузку страницы, но увеличивает время загрузки и объем данных, к тому же данные могут измениться к моменту onShow из-за изменения контекста.
54
+ * @property generator Функция, генерирующая компонент(ы) для каждого элемента данных.
55
+ */
56
+ export type ForEachInitConfig<RefType extends ContextRef<any, any>, ComponentType extends ComponentTreeNode = ComponentTreeNode, PropertiesType extends ForEachProperties = ForEachProperties> = {
57
+ ref: CompatibleForEachRef<RefType>;
58
+ preload?: boolean;
59
+ track: (data: ForEachItemData<RefType>) => string;
60
+ generator: (properties: ForEachGeneratorProperties<RefType, ComponentType>) => ComponentType | ComponentType[];
61
+ /** Разделитель между элементами списка (не после последнего). */
62
+ divider?: ComponentTreeNode | ComponentTreeNode[];
63
+ } & ComponentInitConfig<ForEach<RefType, ComponentType>, PropertiesType>;
64
+ /**
65
+ * Компонент, отображающий список элементов путём генерации компонентов на основе массива данных.
66
+ */
67
+ export declare class ForEach<RefType extends ContextRef<any, any>, ComponentType extends ComponentTreeNode = ComponentTreeNode, PropertiesType extends ForEachProperties = ForEachProperties> extends Component<ForEachInitConfig<RefType, ComponentType>, PropertiesType> implements StandaloneComponent {
68
+ /** Включён ли preload: элементы сериализуются уже в первом ответе страницы. */
69
+ private preload;
70
+ /** Сколько раз ForEach в состоянии onShow (несколько instance на клиенте). */
71
+ private instanceCount;
72
+ /** Подписка на контекст списка; снимается, когда все onShow завершились onHide. */
73
+ private contextSubscription?;
74
+ /** Контекст индексов элементов (`id{track}` → `{ index }`). */
75
+ private componentContext;
76
+ /**
77
+ * Состояние по каждому instance ForEach: свой кэш generator и instances дочерних компонентов.
78
+ * Снятие одного instance ForEach не затрагивает другие entry/client.
79
+ */
80
+ private instanceStates;
81
+ /** Контрольная сумма `track`-ключей с прошлой генерации; для пропуска лишнего sync. */
82
+ private lastItemsCheckSum;
83
+ /**
84
+ * Возвращает уникальный идентификатор класса компонента.
85
+ *
86
+ * @returns Строка `"for-each"`.
87
+ */
88
+ protected class(): ServerComponentClass;
89
+ /**
90
+ * Возвращает флаг, указывающий, что компонент является самостоятельным.
91
+ * @returns Всегда true.
92
+ */
93
+ standalone(): true;
94
+ /**
95
+ * Стабильный ключ элемента в кэше и в {@link ForEachContext}.
96
+ *
97
+ * @param item Элемент данных из ref списка.
98
+ * @returns Ключ вида `id{track(item)}`.
99
+ */
100
+ private itemId;
101
+ /**
102
+ * Возвращает или создаёт состояние, привязанное к конкретному instance ForEach.
103
+ *
104
+ * @param forEachInstance Instance ForEach на клиенте (связка client + entry + id).
105
+ */
106
+ private getInstanceState;
107
+ /**
108
+ * Снимает instances элементов списка и удаляет состояние для одного instance ForEach.
109
+ *
110
+ * @param forEachInstance Instance ForEach, инстанс которого прекращено.
111
+ */
112
+ private releaseInstanceState;
113
+ /**
114
+ * Снимает instances дочерних компонентов элементов, созданные при последнем preload/sync
115
+ * для конкретного instance ForEach.
116
+ *
117
+ * @param forEachInstance Instance ForEach, для которого снимаются дочерние instances.
118
+ */
119
+ private releaseItemSyncInstances;
120
+ /**
121
+ * Удаляет из кэша элементы, которых больше нет в данных списка.
122
+ *
123
+ * @param currentItemIds Актуальные ключи элементов после `track`.
124
+ * @param cache Кэш generator для конкретного instance ForEach.
125
+ */
126
+ private evictRemovedItemCaches;
127
+ /**
128
+ * Сериализует слоты элементов списка и запоминает созданные instances для последующего снятия.
129
+ *
130
+ * @param components Слоты по одному на элемент (узел или массив узлов).
131
+ * @param forEachInstance Instance ForEach, в контексте которого выполняется сериализация.
132
+ * @returns Сериализованные конфиги для клиента.
133
+ */
134
+ private serializeItemsWithTracking;
135
+ /**
136
+ * Строит дерево компонентов по текущему значению ref: обновляет индексы в
137
+ * {@link componentContext}, берёт узлы из кэша instance ForEach или вызывает `generator`.
138
+ *
139
+ * @param forEachInstance Instance ForEach, для которого строится дерево элементов.
140
+ * @returns Слоты элементов в порядке следования в массиве данных.
141
+ */
142
+ private generateComponents;
143
+ /**
144
+ * Синхронизирует элементы списка с клиентом для одного instance ForEach.
145
+ *
146
+ * @param forEachInstance Instance ForEach на клиенте.
147
+ * @param currentItemIds Актуальные ключи элементов списка.
148
+ */
149
+ private syncForEachInstance;
150
+ /**
151
+ * Отправляет клиенту актуальные конфиги элементов (`ForEachSyncComponentsMessage`).
152
+ * Вызывается при onShow и при изменении массива в ref (добавление, удаление, порядок).
153
+ *
154
+ * @param onlyIfChanged Если `true`, sync пропускается, когда не изменился набор `track`-ключей.
155
+ */
156
+ private syncComponents;
157
+ /**
158
+ * Создает экземпляр компонента ForEach.
159
+ *
160
+ * @param config Конфигурация инициализации компонента.
161
+ */
162
+ constructor(config: ForEachInitConfig<RefType, ComponentType>);
163
+ /**
164
+ * Инициализирует свойства компонента.
165
+ *
166
+ * @param initValues Объект конфигурации инициализации.
167
+ * @returns Объект свойств.
168
+ */
169
+ protected initProperties(initValues: ForEachInitConfig<RefType, ComponentType>): PropertiesType;
170
+ /**
171
+ * Вызывает `generator` для одного элемента и нормализует результат в массив узлов.
172
+ *
173
+ * @param properties ForEach-экземпляр и ref на элемент списка с индексом.
174
+ * @returns Компоненты одного элемента списка.
175
+ */
176
+ protected generateItemComponents(properties: {
177
+ component: ForEach<RefType, ComponentType>;
178
+ ref: ForEachItemLink<RefType>;
179
+ }): ComponentTreeNode[];
180
+ /**
181
+ * Сериализует ForEach; при `preload` включает готовые элементы и divider в properties.
182
+ *
183
+ * @param instance Instance ForEach; если не передан — создаётся новый.
184
+ * @returns Конфиг для клиента.
185
+ */
186
+ serialize(instance?: ComponentInstance<this>): ForEachConfig;
187
+ }
188
+ export {};
@@ -0,0 +1,362 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ForEach = exports.forEach = void 0;
4
+ const server_component_class_1 = require("@matreshka/shared/enums/server-component-class");
5
+ const for_each_sync_components_message_1 = require("@matreshka/shared/messages/bff-to-client/components/for-each/for-each-sync-components-message");
6
+ const rxjs_1 = require("rxjs");
7
+ const v4_1 = require("zod/v4");
8
+ const core_1 = require("../core");
9
+ const serialize_component_tree_1 = require("../core/utils/serialize-component-tree");
10
+ const track_created_instances_1 = require("../core/utils/track-created-instances");
11
+ const component_1 = require("./component");
12
+ /** Возвращает массив элементов списка из ref; не-массив даёт пустой массив. */
13
+ function getForEachValue(ref) {
14
+ const rawValue = ref.value();
15
+ return Array.isArray(rawValue)
16
+ ? rawValue
17
+ : [];
18
+ }
19
+ /**
20
+ * Связывает ref элемента списка с ref индекса в {@link ForEachContext},
21
+ * чтобы генератор мог читать `ref.value()` и вложенные поля элемента.
22
+ */
23
+ function createForEachItemLink(ref, indexRef) {
24
+ return ref.strictRef(indexRef);
25
+ }
26
+ const forEach = (config) => new ForEach(config);
27
+ exports.forEach = forEach;
28
+ class ForEachContext extends core_1.Context {
29
+ /**
30
+ * Синхронно поднимает `data$`, чтобы индексы элементов были доступны при preload-сериализации.
31
+ * @returns Тот же экземпляр контекста.
32
+ */
33
+ initSync() {
34
+ // Запрет на повторную инициализацию контекста
35
+ if (this.inited())
36
+ return this;
37
+ this.data$ = new rxjs_1.BehaviorSubject({});
38
+ this.subscribeToDataChanges();
39
+ }
40
+ /**
41
+ * После in-place обновления карты индексов в `data$` — одна синхронизация с клиентом.
42
+ * @see Context.emitAfterInPlaceMutation
43
+ */
44
+ syncIndexStoreFromMutations() {
45
+ super.emitAfterInPlaceMutation();
46
+ }
47
+ /**
48
+ * Контекст индексов элементов ForEach; данные не загружаются снаружи (`schema` пустой).
49
+ *
50
+ * @param preload Наследует флаг preload родительского контекста списка.
51
+ */
52
+ constructor(preload) {
53
+ super({
54
+ data: async () => ({}),
55
+ preload: preload,
56
+ schema: v4_1.z.strictObject({}), // Запрет изменения из внешних источников
57
+ });
58
+ }
59
+ }
60
+ /**
61
+ * Компонент, отображающий список элементов путём генерации компонентов на основе массива данных.
62
+ */
63
+ class ForEach extends component_1.Component {
64
+ /**
65
+ * Возвращает уникальный идентификатор класса компонента.
66
+ *
67
+ * @returns Строка `"for-each"`.
68
+ */
69
+ class() {
70
+ return server_component_class_1.ServerComponentClass.ForEach;
71
+ }
72
+ /**
73
+ * Возвращает флаг, указывающий, что компонент является самостоятельным.
74
+ * @returns Всегда true.
75
+ */
76
+ standalone() {
77
+ return true;
78
+ }
79
+ /**
80
+ * Стабильный ключ элемента в кэше и в {@link ForEachContext}.
81
+ *
82
+ * @param item Элемент данных из ref списка.
83
+ * @returns Ключ вида `id{track(item)}`.
84
+ */
85
+ itemId(item) {
86
+ // Префикс id: при трекинге по числу strictRef не путает ключ с индексом массива.
87
+ return "id" + this.config.track(item);
88
+ }
89
+ /**
90
+ * Возвращает или создаёт состояние, привязанное к конкретному instance ForEach.
91
+ *
92
+ * @param forEachInstance Instance ForEach на клиенте (связка client + entry + id).
93
+ */
94
+ getInstanceState(forEachInstance) {
95
+ let state = this.instanceStates.get(forEachInstance);
96
+ if (!state) {
97
+ state = {
98
+ itemSyncInstances: [],
99
+ componentsCache: new Map(),
100
+ };
101
+ this.instanceStates.set(forEachInstance, state);
102
+ }
103
+ return state;
104
+ }
105
+ /**
106
+ * Снимает instances элементов списка и удаляет состояние для одного instance ForEach.
107
+ *
108
+ * @param forEachInstance Instance ForEach, инстанс которого прекращено.
109
+ */
110
+ releaseInstanceState(forEachInstance) {
111
+ this.releaseItemSyncInstances(forEachInstance);
112
+ this.instanceStates.delete(forEachInstance);
113
+ }
114
+ /**
115
+ * Снимает instances дочерних компонентов элементов, созданные при последнем preload/sync
116
+ * для конкретного instance ForEach.
117
+ *
118
+ * @param forEachInstance Instance ForEach, для которого снимаются дочерние instances.
119
+ */
120
+ releaseItemSyncInstances(forEachInstance) {
121
+ const state = this.instanceStates.get(forEachInstance);
122
+ if (!state || state.itemSyncInstances.length === 0) {
123
+ return;
124
+ }
125
+ const byComponent = new Map();
126
+ for (const instance of state.itemSyncInstances) {
127
+ const component = instance.component;
128
+ const list = byComponent.get(component) ?? [];
129
+ list.push(instance);
130
+ byComponent.set(component, list);
131
+ }
132
+ for (const [component, instances] of byComponent) {
133
+ component.releaseInstances(instances);
134
+ }
135
+ state.itemSyncInstances = [];
136
+ }
137
+ /**
138
+ * Удаляет из кэша элементы, которых больше нет в данных списка.
139
+ *
140
+ * @param currentItemIds Актуальные ключи элементов после `track`.
141
+ * @param cache Кэш generator для конкретного instance ForEach.
142
+ */
143
+ evictRemovedItemCaches(currentItemIds, cache) {
144
+ for (const itemId of cache.keys()) {
145
+ if (!currentItemIds.has(itemId)) {
146
+ cache.delete(itemId);
147
+ }
148
+ }
149
+ }
150
+ /**
151
+ * Сериализует слоты элементов списка и запоминает созданные instances для последующего снятия.
152
+ *
153
+ * @param components Слоты по одному на элемент (узел или массив узлов).
154
+ * @param forEachInstance Instance ForEach, в контексте которого выполняется сериализация.
155
+ * @returns Сериализованные конфиги для клиента.
156
+ */
157
+ serializeItemsWithTracking(components, forEachInstance) {
158
+ this.releaseItemSyncInstances(forEachInstance);
159
+ const state = this.getInstanceState(forEachInstance);
160
+ const { result, instances } = (0, track_created_instances_1.runWithCreatedInstanceTracking)(() => (0, serialize_component_tree_1.serializeForEachSlots)(components));
161
+ state.itemSyncInstances = instances;
162
+ return result;
163
+ }
164
+ /**
165
+ * Строит дерево компонентов по текущему значению ref: обновляет индексы в
166
+ * {@link componentContext}, берёт узлы из кэша instance ForEach или вызывает `generator`.
167
+ *
168
+ * @param forEachInstance Instance ForEach, для которого строится дерево элементов.
169
+ * @returns Слоты элементов в порядке следования в массиве данных.
170
+ */
171
+ generateComponents(forEachInstance) {
172
+ const cache = this.getInstanceState(forEachInstance).componentsCache;
173
+ const value = getForEachValue(this.config.ref);
174
+ const itemsCheckSum = value.map(this.config.track).join("|");
175
+ this.lastItemsCheckSum = itemsCheckSum;
176
+ // Тот же объект, что в BehaviorSubject: мутируем in-place, чтобы strictRef видел
177
+ // индекс через getValue() без next() (иначе срабатывали бы подписчики Context).
178
+ const store = this.componentContext.data$.getValue();
179
+ for (const key of Object.keys(store)) {
180
+ delete store[key];
181
+ }
182
+ const components = (Array.isArray(value) ? value : []).map((item, index) => {
183
+ const itemId = this.itemId(item);
184
+ store[itemId] = { index: `${index}` };
185
+ if (cache.has(itemId)) {
186
+ return cache.get(itemId);
187
+ }
188
+ const result = this.generateItemComponents({
189
+ component: this,
190
+ ref: createForEachItemLink(this.config.ref, this.componentContext.ref(`${itemId}.index`)),
191
+ });
192
+ cache.set(itemId, result);
193
+ return result;
194
+ });
195
+ this.componentContext.syncIndexStoreFromMutations();
196
+ return components;
197
+ }
198
+ /**
199
+ * Синхронизирует элементы списка с клиентом для одного instance ForEach.
200
+ *
201
+ * @param forEachInstance Instance ForEach на клиенте.
202
+ * @param currentItemIds Актуальные ключи элементов списка.
203
+ */
204
+ syncForEachInstance(forEachInstance, currentItemIds) {
205
+ this.evictRemovedItemCaches(currentItemIds, this.getInstanceState(forEachInstance).componentsCache);
206
+ (0, core_1.runWithClient)(forEachInstance.client, () => {
207
+ (0, core_1.runWithEntryContext)(forEachInstance.entry, forEachInstance.client, () => {
208
+ const components = this.generateComponents(forEachInstance);
209
+ const serializedComponents = this.serializeItemsWithTracking(components, forEachInstance);
210
+ forEachInstance.client.outcomingMessage$.next(new for_each_sync_components_message_1.ForEachSyncComponentsMessage(forEachInstance.id, serializedComponents));
211
+ });
212
+ });
213
+ }
214
+ /**
215
+ * Отправляет клиенту актуальные конфиги элементов (`ForEachSyncComponentsMessage`).
216
+ * Вызывается при onShow и при изменении массива в ref (добавление, удаление, порядок).
217
+ *
218
+ * @param onlyIfChanged Если `true`, sync пропускается, когда не изменился набор `track`-ключей.
219
+ */
220
+ async syncComponents(onlyIfChanged = true) {
221
+ const value = getForEachValue(this.config.ref);
222
+ const itemsCheckSum = value.map(this.config.track).join("|");
223
+ if (itemsCheckSum === this.lastItemsCheckSum && onlyIfChanged) {
224
+ return;
225
+ }
226
+ if (this.instances.length === 0) {
227
+ return;
228
+ }
229
+ const currentItemIds = new Set(value.map((item) => this.itemId(item)));
230
+ for (const forEachInstance of this.instances) {
231
+ this.syncForEachInstance(forEachInstance, currentItemIds);
232
+ }
233
+ }
234
+ /**
235
+ * Создает экземпляр компонента ForEach.
236
+ *
237
+ * @param config Конфигурация инициализации компонента.
238
+ */
239
+ constructor(config) {
240
+ if (typeof config.onShow === "undefined") {
241
+ config.onShow = [];
242
+ }
243
+ if (typeof config.onShow === "function") {
244
+ config.onShow = [config.onShow];
245
+ }
246
+ config.onShow.push(() => {
247
+ void this.syncComponents(this.preload);
248
+ this.instanceCount++;
249
+ if (this.instanceCount === 1) {
250
+ const contextSubscription = new rxjs_1.Subscription();
251
+ this.contextSubscription = contextSubscription;
252
+ contextSubscription.add(this.config.ref.context.init$.subscribe(() => {
253
+ contextSubscription.add(this.config.ref.context.data$.pipe((0, rxjs_1.skip)(1)).subscribe(() => {
254
+ void this.syncComponents(true);
255
+ }));
256
+ }));
257
+ }
258
+ });
259
+ if (typeof config.onHide === "undefined") {
260
+ config.onHide = [];
261
+ }
262
+ if (typeof config.onHide === "function") {
263
+ config.onHide = [config.onHide];
264
+ }
265
+ config.onHide.push(() => {
266
+ this.instanceCount--;
267
+ if (this.instanceCount === 0) {
268
+ this.contextSubscription?.unsubscribe();
269
+ this.contextSubscription = undefined;
270
+ }
271
+ });
272
+ super(config);
273
+ /** Включён ли preload: элементы сериализуются уже в первом ответе страницы. */
274
+ this.preload = false;
275
+ /** Сколько раз ForEach в состоянии onShow (несколько instance на клиенте). */
276
+ this.instanceCount = 0;
277
+ /**
278
+ * Состояние по каждому instance ForEach: свой кэш generator и instances дочерних компонентов.
279
+ * Снятие одного instance ForEach не затрагивает другие entry/client.
280
+ */
281
+ this.instanceStates = new Map();
282
+ /** Контрольная сумма `track`-ключей с прошлой генерации; для пропуска лишнего sync. */
283
+ this.lastItemsCheckSum = "";
284
+ this.preload = config.preload ?? false;
285
+ this.componentContext = new ForEachContext(config.ref.context.preload);
286
+ this.destroyInstance$.subscribe((releasedInstance) => {
287
+ this.releaseInstanceState(releasedInstance);
288
+ });
289
+ this.stopUsing$.subscribe(() => {
290
+ this.instanceStates.clear();
291
+ });
292
+ // Инициализируем контекст сразу, чтобы при ранней сериализации data$ уже существовал.
293
+ void this.componentContext.initSync();
294
+ }
295
+ /**
296
+ * Инициализирует свойства компонента.
297
+ *
298
+ * @param initValues Объект конфигурации инициализации.
299
+ * @returns Объект свойств.
300
+ */
301
+ initProperties(initValues) {
302
+ const properties = {
303
+ ...super.initProperties(initValues),
304
+ ref: initValues.ref,
305
+ componentContext: this.componentContext,
306
+ };
307
+ if (initValues.divider !== undefined) {
308
+ properties.divider = (0, core_1.calculateComponents)(Array.isArray(initValues.divider)
309
+ ? initValues.divider
310
+ : [initValues.divider]);
311
+ }
312
+ return properties;
313
+ }
314
+ /**
315
+ * Вызывает `generator` для одного элемента и нормализует результат в массив узлов.
316
+ *
317
+ * @param properties ForEach-экземпляр и ref на элемент списка с индексом.
318
+ * @returns Компоненты одного элемента списка.
319
+ */
320
+ generateItemComponents(properties) {
321
+ const result = this.config.generator(properties);
322
+ return Array.isArray(result) ? result : [result];
323
+ }
324
+ /**
325
+ * Сериализует ForEach; при `preload` включает готовые элементы и divider в properties.
326
+ *
327
+ * @param instance Instance ForEach; если не передан — создаётся новый.
328
+ * @returns Конфиг для клиента.
329
+ */
330
+ serialize(instance) {
331
+ if (!instance) {
332
+ instance = this.createInstance();
333
+ }
334
+ const result = super.serialize(instance);
335
+ const extra = {};
336
+ if (this.preload && this.properties.ref.context.inited()) {
337
+ (0, core_1.runWithClient)(instance.client, () => {
338
+ (0, core_1.runWithEntryContext)(instance.entry, instance.client, () => {
339
+ extra.components = this.serializeItemsWithTracking(this.generateComponents(instance), instance);
340
+ });
341
+ });
342
+ }
343
+ if (this.properties.divider) {
344
+ extra.divider = (0, core_1.serializeComponentList)(this.properties.divider);
345
+ }
346
+ if (Object.keys(extra).length > 0) {
347
+ return {
348
+ ...result,
349
+ class: server_component_class_1.ServerComponentClass.ForEach,
350
+ properties: {
351
+ ...result.properties,
352
+ ...extra,
353
+ },
354
+ };
355
+ }
356
+ return {
357
+ ...result,
358
+ class: server_component_class_1.ServerComponentClass.ForEach,
359
+ };
360
+ }
361
+ }
362
+ exports.ForEach = ForEach;
@@ -0,0 +1,62 @@
1
+ import { ServerComponentClass } from "@matreshka/shared/enums/server-component-class";
2
+ import type { FormConfig } from "@matreshka/shared/types/form-config";
3
+ import { Componentable, ComponentTreeNode, MixedWithCallbacksArray, StandaloneComponent } from "../core";
4
+ import { Component, ComponentInitConfig, ComponentProperties, ServerComponentAction } from "./component";
5
+ export type FormProperties = {
6
+ content: ComponentTreeNode[];
7
+ } & ComponentProperties;
8
+ /**
9
+ * Конфигурация инициализации для компонента Form.
10
+ *
11
+ * @property content Список вложенных компонентов.
12
+ * @property onSubmit Действие, вызываемое при отправке формы.
13
+ */
14
+ export type FormInitConfig<ComponentType extends Componentable = Form, PropertiesType extends FormProperties = FormProperties> = {
15
+ content: MixedWithCallbacksArray<ComponentTreeNode>;
16
+ onSubmit: ServerComponentAction<ComponentType> | ServerComponentAction<ComponentType>[];
17
+ } & ComponentInitConfig<ComponentType, PropertiesType>;
18
+ type DefaultInitConfigType = FormInitConfig<Form>;
19
+ export declare function form(options: Omit<DefaultInitConfigType, "content">, content: DefaultInitConfigType["content"]): Form;
20
+ export declare function form(config: DefaultInitConfigType): Form;
21
+ /**
22
+ * Компонент формы, содержащей вложенные компоненты и поддерживающей отправку.
23
+ * Перед инстансм необходимо убедиться, что внутри формы есть кнопка с type = submit,
24
+ * иначе обработка отправки формы не будет работать
25
+ *
26
+ * @template T Тип вложенных узлов дерева ({@link ComponentTreeNode}).
27
+ */
28
+ export declare class Form<InitConfigType extends FormInitConfig<any> = DefaultInitConfigType, PropertiesType extends FormProperties = FormProperties> extends Component<InitConfigType, PropertiesType> implements StandaloneComponent {
29
+ /**
30
+ * Возвращает уникальный идентификатор класса компонента.
31
+ *
32
+ * @returns Строка "form".
33
+ */
34
+ protected class(): ServerComponentClass;
35
+ /**
36
+ * Возвращает флаг, указывающий, что компонент является самостоятельным.
37
+ * @returns Всегда true.
38
+ */
39
+ standalone(): true;
40
+ /**
41
+ * Создает новый экземпляр формы.
42
+ *
43
+ * @param config Конфигурация инициализации формы.
44
+ *
45
+ * Компонент обеспечивает корректную работу сабмита по нажатию Enter и отображение
46
+ * клавиатуры с кнопкой отправки на мобильных устройствах.
47
+ *
48
+ * Убедитесь, что внутри формы присутствует кнопка с type=submit.
49
+ * Если кнопок нет — форма будет отправлена.
50
+ */
51
+ constructor(config: InitConfigType);
52
+ /**
53
+ * Инициализирует свойства компонента.
54
+ *
55
+ * @param initValues Объект конфигурации инициализации.
56
+ * @returns Объект со свойствами компонента.
57
+ */
58
+ protected initProperties(initValues: InitConfigType): PropertiesType;
59
+ protected serializeRuleOverrides(overrides: Partial<PropertiesType>): Record<string, unknown>;
60
+ serialize(): FormConfig;
61
+ }
62
+ export {};