poe-svelte-ui-lib 2.1.3 → 2.2.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/README.md CHANGED
@@ -85,7 +85,21 @@ npm install poe-svelte-ui-lib
85
85
 
86
86
  ## GUI устройства
87
87
 
88
- GUI из конструктора рисует `GUIRenderer`. Он раскладывает сетку (18 колонок, строка `6rem`), вкладывает компоненты в `Accordion` и `Tabs` (по `parentId`, номер вкладки - после 35-го знака `id`), берёт значения переменных, разбирает битовые поля, собирает пакеты команд и ведёт смарт-виджеты и файлы. Приложение отвечает за транспорт, выбор модуля, загрузку GUI и хранилище значений.
88
+ GUI из конструктора рисует `GUIRenderer`. Он раскладывает сетку (23 колонки, строка `6rem`), вкладывает компоненты в `Accordion` и `Tabs` (по `parentId`, номер вкладки - после 35-го знака `id`), берёт значения переменных, разбирает битовые поля, собирает пакеты команд и ведёт смарт-виджеты и файлы. Приложение отвечает за транспорт, выбор модуля, загрузку GUI и хранилище значений.
89
+
90
+ ### Раскладка и правила для автора GUI
91
+
92
+ Сетка - 23 колонки: в неё ровно встают 2, 3, 4, 6 и 12 одинаковых групп с пустой колонкой между ними (11, 7, 5, 3 и 1 колонка на группу). Рендерер понимает GUI по группам, поэтому автор соблюдает правила:
93
+
94
+ 1. Группа - параметры одного объекта (мотор, канал, контур регулятора). Внутри группы блоки стоят вплотную, без пустых клеток.
95
+ 2. Группы рядом разделяет пустая колонка.
96
+ 3. Группы друг под другом разделяет пустая строка или блок во всю ширину (`Divider`, заголовок, график).
97
+ 4. Заголовок группы - `TextField` в её первой строке на всю ширину группы.
98
+ 5. Поля внутри группы - строками формы: «Напряжение | Ток», «Кол-во ПП | Скорость».
99
+ 6. Широкий блок (график, таблица, смарт-виджет, список кнопками) - во всю ширину своей группы.
100
+ 7. Блок не перекрывает пустую клетку-границу, иначе он склеит две группы.
101
+
102
+ На компьютере сетка такая, как в конструкторе; пустая колонка между группами сжимается до узкой полосы, пустая строка - до обычного зазора. Если рендерер уже 640px (телефон, узкая панель), блоки раскладываются по группам: одинаковые группы из мелких блоков (каналы) - карточками по 2-3 в ряд, остальные - друг под другом, поля группы - строками с переносом. `Accordion` раскладывает своё содержимое так же, колонок у него не меньше, чем у самого дальнего блока.
89
103
 
90
104
  ```svelte
91
105
  <UI.GUIRenderer components={module.UIBlocks} {link} persistKey={module.ModSN} viewer={!canManage} render={{ VideoViewer: video }} onError={addMessage} />
@@ -19,6 +19,10 @@
19
19
  widgetPacket,
20
20
  widgetPrefixes,
21
21
  writeBits,
22
+ layoutFlow,
23
+ layoutColumns,
24
+ flowMinWidth,
25
+ type FlowNode,
22
26
  type DeviceLink,
23
27
  type DevicePacket,
24
28
  } from "../gui"
@@ -182,7 +186,21 @@
182
186
  return (Array.isArray(external) ? external : (component.properties.options ?? [])) as IOption[]
183
187
  }
184
188
 
189
+ /* ********************************************************** */
190
+ /* Уже NARROW_MAX_PX (телефон, узкая панель) - раскладка по группам автора (layoutFlow в gui.ts), иначе его сетка */
191
+ const NARROW_MAX_PX = 640
192
+ let width = $state(0)
193
+ const narrow = $derived(width > 0 && width < NARROW_MAX_PX)
194
+
195
+ /* Группа из мелких блоков (канал, мотор) - в рамке; виджеты и графики - уже карточки */
196
+ const framed = (node: FlowNode) => node.kind !== "leaf" && Number.isFinite(flowMinWidth(node))
197
+
185
198
  const cellStyle = (component: UIComponent, fixedHeight: boolean) => {
199
+ /* Телефон: место задаёт раскладка, высота по содержимому; графику и видео - высота из конструктора, не больше 20rem */
200
+ if (narrow) {
201
+ const fixed = component.type === "Graph" || component.type === "PeriodChart" || component.type === "VideoViewer"
202
+ return fixed ? `height: min(${component.position.height * GUI_GRID.cellHeight}rem, 20rem);` : ""
203
+ }
186
204
  const area = `grid-area: ${component.position.row} / ${component.position.col} / span ${spanRows(component)} / span ${component.position.width};`
187
205
  const auto = component.type === "Accordion" || isWidgetType(component.type)
188
206
  const height = `${component.position.height * GUI_GRID.cellHeight}rem`
@@ -194,12 +212,58 @@
194
212
  const writable = (component: UIComponent) => !viewer && COMPONENTS[component.type].io !== "none"
195
213
  </script>
196
214
 
197
- <div class="grid gap-2" style="grid-template-columns: repeat({GUI_GRID.columns}, minmax(0, 1fr))">
198
- {#each tree.get("") ?? [] as component (component.id)}
199
- {@render Cell(component, false)}
200
- {/each}
215
+ <div bind:clientWidth={width}>
216
+ {@render Layout((tree.get("") ?? []).filter(visible), GUI_GRID.columns, false)}
201
217
  </div>
202
218
 
219
+ <!-- Блоки одного контейнера: на телефоне раскладка по группам, на компьютере сетка автора -->
220
+ {#snippet Layout(list: UIComponent[], total: number, fixedHeight: boolean)}
221
+ {#if narrow}
222
+ {@render Flow(layoutFlow(list))}
223
+ {:else}
224
+ <div class="grid gap-2" style="grid-template-columns: {layoutColumns(list, total)}">
225
+ {#each list as component (component.id)}
226
+ {@render Cell(component, fixedHeight)}
227
+ {/each}
228
+ </div>
229
+ {/if}
230
+ {/snippet}
231
+
232
+ {#snippet Flow(node: FlowNode)}
233
+ {#if node.kind === "leaf"}
234
+ {@render Cell(node.component, false)}
235
+ {:else if node.kind === "stack"}
236
+ <div class="flex min-w-0 flex-col gap-2">
237
+ {#each node.items as item, index (index)}
238
+ {@render Flow(item)}
239
+ {/each}
240
+ </div>
241
+ {:else}
242
+ {@const widths = node.items.map(flowMinWidth)}
243
+ {@const same = node.kind === "groups" && widths.every((w) => w === widths[0] && Number.isFinite(w))}
244
+ {#if same}
245
+ <!-- Одинаковые группы (каналы) - сеткой, сколько поместится -->
246
+ <div class="grid gap-2" style="grid-template-columns: repeat(auto-fill, minmax(min({widths[0] + 18}px, 100%), 1fr))">
247
+ {#each node.items as item, index (index)}
248
+ <div class="min-w-0 {framed(item) ? 'rounded-xl border border-(--hairline-color) p-2' : ''}">{@render Flow(item)}</div>
249
+ {/each}
250
+ </div>
251
+ {:else}
252
+ <div class="flex flex-wrap gap-2">
253
+ {#each node.items as item, index (index)}
254
+ {@const framedGroup = node.kind === "groups" && framed(item)}
255
+ <div
256
+ class="min-w-0 {framedGroup ? 'rounded-xl border border-(--hairline-color) p-2' : ''}"
257
+ style="flex: 1 1 {Number.isFinite(widths[index]) ? `${widths[index] + (framedGroup ? 18 : 0)}px` : '100%'}"
258
+ >
259
+ {@render Flow(item)}
260
+ </div>
261
+ {/each}
262
+ </div>
263
+ {/if}
264
+ {/if}
265
+ {/snippet}
266
+
203
267
  {#snippet Cell(component: UIComponent, fixedHeight: boolean)}
204
268
  {#if visible(component)}
205
269
  {@const id = component.properties.id ?? ""}
@@ -209,9 +273,10 @@
209
273
  {@render render[component.type]?.(component)}
210
274
  {:else if component.type === "Accordion"}
211
275
  <Accordion {...component.properties}>
212
- {#each childrenOf(component) as child (child.id)}
213
- {@render Cell(child, !!component.properties.image)}
214
- {/each}
276
+ <!-- Своя сетка содержимого во всю ширину аккордеона: колонок не меньше, чем у самого дальнего блока -->
277
+ <div class="min-w-0" style="grid-column: 1 / -1; grid-row: 1 / -1">
278
+ {@render Layout(childrenOf(component).filter(visible), component.properties.size?.width ?? 1, !!component.properties.image)}
279
+ </div>
215
280
  </Accordion>
216
281
  {:else if component.type === "Tabs"}
217
282
  <Tabs {...component.properties} Components={Cell} apiArray={childrenOf(component)} />
@@ -6,7 +6,7 @@ export declare const COMPONENT_SIZES: Record<UIType, {
6
6
  width: number;
7
7
  height: number;
8
8
  }>;
9
- export declare const minComponentWidth: (type: string) => 1 | 6;
9
+ export declare const minComponentWidth: (type: string) => 1 | 7;
10
10
  export declare const createComponent: <K extends UIType>(type: K, { col, row }?: {
11
11
  col?: number;
12
12
  row?: number;
package/dist/defaults.js CHANGED
@@ -62,35 +62,35 @@ export const COMPONENT_DEFAULTS = {
62
62
  VideoViewer: { label, showSelect: true },
63
63
  Divider: { type: "line", width: 2, anchor: "center" },
64
64
  };
65
- /* Размер нового компонента в клетках сетки */
65
+ /* Размер нового компонента в клетках сетки: компактный, автор растягивает по месту; каркас (разделитель, аккордеон, вкладки) - во всю ширину */
66
66
  export const COMPONENT_SIZES = {
67
- WidgetWiFi: { width: 8, height: 1 },
68
- WidgetDeviceInfo: { width: 8, height: 1 },
69
- WidgetFileSystem: { width: 10, height: 1 },
70
- WidgetStackInfo: { width: 10, height: 1 },
71
- WidgetRGBStrip: { width: 8, height: 1 },
72
- WidgetPFD: { width: 12, height: 1 },
73
- WidgetMap: { width: 14, height: 1 },
67
+ WidgetWiFi: { width: 7, height: 1 },
68
+ WidgetDeviceInfo: { width: 7, height: 1 },
69
+ WidgetFileSystem: { width: 7, height: 1 },
70
+ WidgetStackInfo: { width: 7, height: 1 },
71
+ WidgetRGBStrip: { width: 7, height: 1 },
72
+ WidgetPFD: { width: 7, height: 1 },
73
+ WidgetMap: { width: 7, height: 1 },
74
74
  Accordion: { width: GUI_GRID.columns, height: 1 },
75
75
  Tabs: { width: GUI_GRID.columns, height: 4 },
76
- Input: { width: 4, height: 1 },
77
- Select: { width: 4, height: 1 },
78
- Slider: { width: 4, height: 1 },
76
+ Input: { width: 3, height: 1 },
77
+ Select: { width: 3, height: 1 },
78
+ Slider: { width: 3, height: 1 },
79
79
  Switch: { width: 2, height: 1 },
80
- FileAttach: { width: 5, height: 1 },
80
+ FileAttach: { width: 7, height: 1 },
81
81
  Joystick: { width: 4, height: 3 },
82
82
  Button: { width: 2, height: 1 },
83
- Table: { width: 12, height: 2 },
84
- ProgressBar: { width: 4, height: 1 },
83
+ Table: { width: 11, height: 2 },
84
+ ProgressBar: { width: 3, height: 1 },
85
85
  TextField: { width: 3, height: 1 },
86
- Graph: { width: 10, height: 3 },
87
- PeriodChart: { width: 10, height: 4 },
86
+ Graph: { width: 7, height: 3 },
87
+ PeriodChart: { width: 7, height: 4 },
88
88
  Widget: { width: 3, height: 3 },
89
89
  VideoViewer: { width: 7, height: 7 },
90
90
  Divider: { width: GUI_GRID.columns, height: 1 },
91
91
  };
92
- /* Наименьшая ширина: смарт-виджет не уже 6 клеток, иначе шапка и поля не помещаются */
93
- export const minComponentWidth = (type) => (isWidgetType(type) ? 6 : 1);
92
+ /* Наименьшая ширина: смарт-виджет не уже 7 клеток (треть сетки), иначе шапка и поля не помещаются */
93
+ export const minComponentWidth = (type) => (isWidgetType(type) ? 7 : 1);
94
94
  /* Новый компонент в клетке (col, row) области шириной areaWidth; tab - номер вкладки родителя Tabs (последний знак id). Не помещающийся компонент сужается, но не меньше minComponentWidth - тогда сдвигается влево */
95
95
  export const createComponent = (type, { col = 1, row = 1 } = {}, parentId = "", { tab, areaWidth = GUI_GRID.columns } = {}) => {
96
96
  const uuid = crypto.randomUUID();
package/dist/gui.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import type { DeviceTransport } from "./fsTransfer";
2
2
  import type { IUIComponentHandler, IWidgetFileSystemInfo, IWidgetStackInfo, UIComponent } from "./types";
3
3
  export declare const GUI_GRID: {
4
- readonly columns: 18;
4
+ readonly columns: 23;
5
5
  readonly cellHeight: 6;
6
6
  };
7
7
  export declare const isWidgetType: (type: string) => boolean;
@@ -151,3 +151,13 @@ export declare const mergeDevicePayload: (values: {
151
151
  get(key: string): unknown;
152
152
  set(key: string, value: never): unknown;
153
153
  }, prefix: string, argument: string, payload: unknown) => void;
154
+ export type FlowNode = {
155
+ kind: "leaf";
156
+ component: UIComponent;
157
+ } | {
158
+ kind: "stack" | "groups" | "line";
159
+ items: FlowNode[];
160
+ };
161
+ export declare const layoutFlow: (list: UIComponent[]) => FlowNode;
162
+ export declare const flowMinWidth: (node: FlowNode) => number;
163
+ export declare const layoutColumns: (list: UIComponent[], total: number) => string;
package/dist/gui.js CHANGED
@@ -1,7 +1,7 @@
1
1
  /* $lib/gui.ts - чистые правила рендерера GUI устройства (GUIRenderer): сетка, поля смарт-виджетов, битовые поля, сборка пакетов команд, слияние ответа устройства в хранилище значений. Без Svelte - проверяются тестами против dist */
2
2
  import { bitFieldGet, bitFieldSet } from "./bitField.js";
3
- /* Сетка GUI: 18 колонок, высота строки в rem - общая для конструктора и рендерера */
4
- export const GUI_GRID = { columns: 18, cellHeight: 6 };
3
+ /* Сетка GUI: 23 колонки (2, 3, 4, 6 и 12 равных групп с пустой колонкой между ними), высота строки в rem - общая для конструктора и рендерера */
4
+ export const GUI_GRID = { columns: 23, cellHeight: 6 };
5
5
  /* Смарт-виджет - тип с префиксом Widget, кроме примитива Widget */
6
6
  export const isWidgetType = (type) => type.startsWith("Widget") && type !== "Widget";
7
7
  /* Строк сетки у компонента: аккордеон и смарт-виджеты - одна строка, растущая по содержимому */
@@ -219,3 +219,104 @@ export const mergeDevicePayload = (values, prefix, argument, payload) => {
219
219
  put(prefix + name, value);
220
220
  }
221
221
  };
222
+ /* ********************************************************** */
223
+ /* Раскладка по правилам автора: группа - блоки вплотную; группы разделяет пустая строка или блок во всю ширину (друг под другом), пустая колонка (рядом); см. README «Раскладка и правила для автора GUI» */
224
+ const rows = (c) => [c.position.row, c.position.row + spanRows(c)];
225
+ const cols = (c) => [c.position.col, c.position.col + c.position.width];
226
+ /* Деление по оси: gap - новая часть только через пустую клетку (граница групп), без gap - на любой границе (строки формы) */
227
+ const split = (list, range, gap) => {
228
+ const sorted = [...list].sort((a, b) => range(a)[0] - range(b)[0]);
229
+ const parts = [];
230
+ let end = -Infinity;
231
+ for (const c of sorted) {
232
+ const [start, stop] = range(c);
233
+ if (gap ? start > end : start >= end)
234
+ parts.push([c]);
235
+ else
236
+ parts[parts.length - 1].push(c);
237
+ end = Math.max(end, stop);
238
+ }
239
+ return parts;
240
+ };
241
+ const leaf = (component) => ({ kind: "leaf", component });
242
+ /* Группа без пустых клеток внутри: строки формы сверху вниз, в строке блоки рядом; блок в несколько строк (джойстик) встаёт рядом со своими соседями */
243
+ const form = (list) => {
244
+ if (list.length === 1)
245
+ return leaf(list[0]);
246
+ const bands = split(list, rows, false);
247
+ if (bands.length > 1)
248
+ return { kind: "stack", items: bands.map(form) };
249
+ const columns = split(list, cols, false);
250
+ if (columns.length > 1)
251
+ return { kind: "line", items: columns.map(form) };
252
+ return { kind: "stack", items: [...list].sort((a, b) => a.position.row - b.position.row || a.position.col - b.position.col).map(leaf) };
253
+ };
254
+ /* Участки между блоками во всю ширину (разделитель, график): такой блок - тоже граница разделов */
255
+ const parts = (list) => {
256
+ const out = [];
257
+ let run = [];
258
+ for (const band of split(list, rows, false)) {
259
+ if (split(band, cols, false).length > 1) {
260
+ run.push(...band);
261
+ continue;
262
+ }
263
+ if (run.length)
264
+ out.push(run);
265
+ out.push(band);
266
+ run = [];
267
+ }
268
+ if (run.length)
269
+ out.push(run);
270
+ return out;
271
+ };
272
+ export const layoutFlow = (list) => {
273
+ if (list.length === 1)
274
+ return leaf(list[0]);
275
+ const sections = split(list, rows, true);
276
+ if (sections.length > 1)
277
+ return { kind: "stack", items: sections.map(layoutFlow) };
278
+ const runs = parts(list);
279
+ if (runs.length > 1)
280
+ return { kind: "stack", items: runs.map(layoutFlow) };
281
+ const groups = split(list, cols, true);
282
+ if (groups.length > 1)
283
+ return { kind: "groups", items: groups.map(layoutFlow) };
284
+ return form(list);
285
+ };
286
+ /* Наименьшая удобная ширина блока на телефоне, px; не указан - во всю ширину */
287
+ const MIN_PX = {
288
+ Switch: 90,
289
+ Input: 120,
290
+ Select: 130,
291
+ Slider: 120,
292
+ Button: 110,
293
+ TextField: 100,
294
+ ProgressBar: 140,
295
+ Widget: 120,
296
+ Joystick: 200,
297
+ };
298
+ export const flowMinWidth = (node) => {
299
+ if (node.kind === "leaf") {
300
+ /* Список кнопками - по ширине вариантов, не поместится в пол-экрана - во всю ширину */
301
+ const props = node.component.properties;
302
+ if (node.component.type === "Select" && props.type === "buttons") {
303
+ const px = 44 * (props.options?.length ?? 2);
304
+ return px > 300 ? Infinity : Math.max(px, 120);
305
+ }
306
+ return MIN_PX[node.component.type] ?? Infinity;
307
+ }
308
+ const widths = node.items.map(flowMinWidth);
309
+ return node.kind === "stack" ? Math.max(...widths) : widths.reduce((sum, w) => sum + w + 8, -8);
310
+ };
311
+ /* Компьютер: сетка из колонок автора, внутренние пустые колонки (границы групп) - узкая полоса вместо полной колонки */
312
+ const GUTTER = "0.75rem";
313
+ export const layoutColumns = (list, total) => {
314
+ const used = new Set();
315
+ for (const c of list)
316
+ for (let col = c.position.col; col < c.position.col + c.position.width; col++)
317
+ used.add(col);
318
+ const count = Math.max(total, ...list.map((c) => c.position.col + c.position.width - 1));
319
+ const first = Math.min(...used);
320
+ const last = Math.max(...used);
321
+ return Array.from({ length: count }, (_, i) => (i + 1 > first && i + 1 < last && !used.has(i + 1) ? GUTTER : "minmax(0, 1fr)")).join(" ");
322
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "poe-svelte-ui-lib",
3
- "version": "2.1.3",
3
+ "version": "2.2.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/Oleg-Perevyshin/ElementsUI.git"