poe-svelte-ui-lib 2.1.0 → 2.1.2

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.
@@ -72,7 +72,18 @@
72
72
  if (components !== localized.src || lang !== localized.lang) localized = { src: components, lang, out: localizeDeep(components, lang) }
73
73
  return localized.out
74
74
  })
75
- const childrenOf = (parent: UIComponent) => blocks.filter((c) => c.parentId === parent.parentId + parent.id)
75
+ /* Дети контейнеров одним проходом: ключ - parentId ребёнка (parentId + id родителя), корень - "" */
76
+ const tree = $derived.by(() => {
77
+ const map = new Map<string, UIComponent[]>()
78
+ for (const c of blocks) {
79
+ const key = c.parentId ?? ""
80
+ const list = map.get(key)
81
+ if (list) list.push(c)
82
+ else map.set(key, [c])
83
+ }
84
+ return map
85
+ })
86
+ const childrenOf = (parent: UIComponent) => tree.get((parent.parentId ?? "") + parent.id) ?? []
76
87
  const visible = (c: UIComponent) => !viewer || c.access === "full" || c.access === "viewOnly"
77
88
 
78
89
  const report = (error: unknown) => onError?.(error instanceof Error ? error.message : String(error))
@@ -184,7 +195,7 @@
184
195
  </script>
185
196
 
186
197
  <div class="grid gap-2" style="grid-template-columns: repeat({GUI_GRID.columns}, minmax(0, 1fr))">
187
- {#each blocks.filter((c) => !c.parentId) as component (component.id)}
198
+ {#each tree.get("") ?? [] as component (component.id)}
188
199
  {@render Cell(component, false)}
189
200
  {/each}
190
201
  </div>
@@ -351,8 +362,9 @@
351
362
  {:else if component.type === "WidgetMap"}
352
363
  <WidgetMap
353
364
  {...component.properties}
354
- value={Object.fromEntries(
355
- widgetPrefixes(component.type, component.properties).map((group) => [group, fields(component, group, WIDGET_FIELDS.WidgetMap)]),
365
+ value={stable(
366
+ component.id,
367
+ Object.fromEntries(widgetPrefixes(component.type, component.properties).map((group) => [group, fields(component, group, WIDGET_FIELDS.WidgetMap)])),
356
368
  )}
357
369
  persistKey={persist(component)}
358
370
  plan={loadMission(component.id, "plan")}
@@ -49,7 +49,7 @@
49
49
  <details>
50
50
  <summary>📜 Журнал и подгрузка</summary>
51
51
 
52
- **Журнал.** С `dataBuffer.stashData` таблица не берёт `body`, а копит строки, которые приложение добавляет методом `push(rows)` через `bind:this`. Строки лежат в кольцевом буфере размером `bufferSize`: старые вытесняются без копирования всего буфера, перерисовка - одна на пачку `push`.
52
+ **Журнал.** С `dataBuffer.stashData` таблица не берёт `body`, а копит строки, которые приложение добавляет методом `push(rows)` через `bind:this`. Строки лежат в кольцевом буфере размером `bufferSize`: старые вытесняются без копирования всего буфера, перерисовка - не чаще кадра экрана, сколько бы `push` ни пришло за это время. На скрытой вкладке строки копятся в буфере и появляются при возврате.
53
53
 
54
54
  ```svelte
55
55
  <script>
@@ -80,7 +80,7 @@
80
80
  - Колонка с `width: "0%"` скрыта. Без `width` колонка занимает `minmax(0, 1fr)`.
81
81
  - Колонки с выравниванием вправо показывают цифры одинаковой ширины.
82
82
  - Текстовая ячейка выводит `render(row)`, без него - значение по `key`: массив вариантов `{ name, value }` списком `name`, другой объект - как JSON. Всё выводится как текст, HTML - только с `html: true`, данные тогда экранирует вызывающий. Ссылку задаёт `href(row)`: ячейка становится `<a>` с текстом внутри, HTML для этого не нужен. `
83
- ` в тексте переносит строку. Цвет из строки задаёт `accent(row)` (роль темы, как у компонентов), с `badge: true` текст стоит на мягкой подложке своего цвета.
83
+ ` в тексте переносит строку. Цвет из строки задаёт `accent(row)` (роль темы, как у компонентов), с `badge: true` текст стоит на мягкой подложке своего цвета; ячейка из одних бейджей ставит их вплотную с переносом. `onClick(row)` делает текст кнопкой (открыть папку и т.п.), сортировка по `key` при этом остаётся. Несколько элементов ячейки встают в ряд, со `stack: true` у колонки - столбиком.
84
84
  - `modal: true` открывает по нажатию содержимое ячейки целиком: длинные строки переносятся, отступы сохраняются, кнопка в окне копирует текст. `modal` - сниппет `Snippet<[row]>`: в окне своё содержимое (без кнопки внизу), так устроено окно xPOE-Debug.
85
85
  - `copy` и подсказка берут видимый текст ячейки (у HTML-ячейки без разметки).
86
86
  - `outline` рисует рамки строк и колонок.
@@ -125,6 +125,7 @@
125
125
  | `label` | `{ name, class }` | Заголовок колонки |
126
126
  | `width` | `string` | Ширина. `"0%"` скрывает колонку |
127
127
  | `align` | `"left" \| "center" \| "right"` | Выравнивание |
128
+ | `stack` | `boolean` | Элементы ячейки столбиком |
128
129
  | `disableSelect` | `boolean` | Запретить выделение текста |
129
130
  | `content` | `ITableContent[] \| (row) => ITableContent[]` | Что в ячейке: список или функция от строки |
130
131
 
@@ -132,7 +133,7 @@
132
133
 
133
134
  | `type` | Поля `data` |
134
135
  | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
135
- | `text` | `key`, `render(row)`, `href(row)`, `html`, `sortable`, `truncated`, `tooltip`, `copy`, `modal` (`true` или сниппет), `accent(row)`, `badge` |
136
+ | `text` | `key`, `render(row)`, `href(row)`, `html`, `sortable`, `truncated`, `tooltip` (`true` или функция от строки), `copy`, `modal` (`true` или сниппет), `accent(row)`, `badge`, `onClick(row)` |
136
137
  | `button` | `name`, `icon`, `title`, `class` (строки или функции от строки), `eventHandler`, `onClick(row)`. У кнопки-иконки без `name` обязательно `title`. Весь `data` может быть функцией от строки |
137
138
  | `select` | `key` (массив вариантов в строке), `keyCol`, `onChange` |
138
139
  | `progressBar` | `key`, `minNum`, `maxNum`, `units` |
@@ -36,14 +36,15 @@
36
36
  const bufferSize = $derived(dataBuffer.bufferSize ?? 10)
37
37
 
38
38
  /* ********************************************************** */
39
- /* Журнал: кольцевой буфер вне реактивности, наружу - снимок строк один раз на пачку push() */
39
+ /* Журнал: кольцевой буфер вне реактивности, наружу - снимок строк не чаще кадра: пакеты приходят каждый своей задачей, перерисовка на каждый была бы лишней */
40
40
  type Entry = { key: number; row: Row }
41
41
  const ring = createRing<Entry>(untrack(() => bufferSize))
42
42
  let seq = 0
43
43
  let stream = $state.raw<Entry[]>([])
44
- let queued = false
44
+ let frame = 0
45
45
  const flush = () => {
46
- queued = false
46
+ if (frame) cancelAnimationFrame(frame)
47
+ frame = 0
47
48
  const entries = ring.toArray()
48
49
  stream = dataBuffer.logger ? entries.reverse() : entries
49
50
  }
@@ -51,10 +52,7 @@
51
52
  /* Добавляет строки в журнал (dataBuffer.stashData); старые вытесняются за bufferSize */
52
53
  export const push = (rows: Row | Row[]) => {
53
54
  for (const row of Array.isArray(rows) ? rows : [rows]) ring.push({ key: ++seq, row })
54
- if (!queued) {
55
- queued = true
56
- queueMicrotask(flush)
57
- }
55
+ frame ||= requestAnimationFrame(flush)
58
56
  }
59
57
 
60
58
  /* Очищает журнал */
@@ -226,6 +224,7 @@
226
224
  return () => {
227
225
  window.removeEventListener("scroll", closeDropdown, true)
228
226
  window.removeEventListener("resize", closeDropdown, true)
227
+ cancelAnimationFrame(frame)
229
228
  }
230
229
  })
231
230
  </script>
@@ -291,8 +290,12 @@
291
290
  {#each header as column, j (column)}
292
291
  {#if column.width !== "0%"}
293
292
  {@const contents = columnContent(column, row) as ITableContent<Row>[]}
293
+ <!-- Одни бейджи - вплотную с переносом; stack - столбиком; иначе - в ряд равными долями -->
294
+ {@const badges = contents.length > 1 && contents.every((c) => c.type === "text" && c.data.badge)}
294
295
  <div
295
- class="relative grid min-h-7 w-full min-w-0 items-center gap-x-2 px-3 py-1 text-[length:var(--table-font-size,13px)] wrap-break-word
296
+ class="relative {badges
297
+ ? 'flex flex-wrap gap-1'
298
+ : 'grid gap-x-2'} min-h-7 w-full min-w-0 items-center px-3 py-1 text-[length:var(--table-font-size,13px)] wrap-break-word
296
299
  {column.align === 'center'
297
300
  ? 'justify-center justify-items-center text-center'
298
301
  : column.align === 'right'
@@ -301,7 +304,7 @@
301
304
  {j !== 0 ? 'border-l' : ''} {outline ? 'border-(--hairline-color)' : 'border-transparent'} {column.disableSelect
302
305
  ? 'select-none'
303
306
  : 'select-all'}"
304
- style="grid-template-columns: repeat({contents.length}, minmax(0, 1fr));"
307
+ style={badges ? undefined : `grid-template-columns: ${column.stack ? "minmax(0, 1fr)" : `repeat(${contents.length}, minmax(0, 1fr))`};`}
305
308
  >
306
309
  {#each contents as content, index}
307
310
  {#if content.type === "button"}
@@ -390,7 +393,12 @@
390
393
  ? 'text-(--accent-text)'
391
394
  : ''} {accent && text.badge ? 'w-fit rounded-md bg-(--accent-soft) px-1.5 text-[12px] font-medium' : 'w-full'}"
392
395
  style={accentStyle(accent)}
393
- onmouseenter={text.tooltip ? (e) => (tooltip = { show: true, text: cellText(row, text), x: e.clientX, y: e.clientY }) : undefined}
396
+ onmouseenter={text.tooltip
397
+ ? (e) => {
398
+ const tip = typeof text.tooltip === "function" ? text.tooltip(row) : cellText(row, text)
399
+ if (tip) tooltip = { show: true, text: tip, x: e.clientX, y: e.clientY }
400
+ }
401
+ : undefined}
394
402
  onmouseleave={text.tooltip ? () => (tooltip.show = false) : undefined}
395
403
  onmousemove={text.tooltip ? (e) => ((tooltip.x = e.clientX), (tooltip.y = e.clientY)) : undefined}
396
404
  role="presentation"
@@ -406,6 +414,14 @@
406
414
  >
407
415
  {#if text.html}{@html sanitizeHtml(value)}{:else}{value}{/if}
408
416
  </button>
417
+ {:else if text.onClick}
418
+ <button
419
+ class="cursor-pointer text-left hover:underline"
420
+ onclick={(e) => {
421
+ e.stopPropagation()
422
+ text.onClick?.(row)
423
+ }}>{value}</button
424
+ >
409
425
  {:else if text.href}
410
426
  <a class="underline" href={text.href(row)}>{value}</a>
411
427
  {:else if text.html}
package/dist/types.d.ts CHANGED
@@ -340,8 +340,9 @@ export interface ITableText<T extends object> {
340
340
  html?: boolean;
341
341
  sortable?: boolean;
342
342
  truncated?: boolean;
343
- tooltip?: boolean;
343
+ tooltip?: boolean | ((row: T) => string);
344
344
  copy?: boolean;
345
+ onClick?: (row: T) => void;
345
346
  modal?: boolean | Snippet<[T]>;
346
347
  accent?: (row: T) => AccentColor | undefined;
347
348
  badge?: boolean;
@@ -396,6 +397,7 @@ export interface ITableHeader<T extends object> {
396
397
  };
397
398
  width?: string;
398
399
  align?: "left" | "center" | "right";
400
+ stack?: boolean;
399
401
  disableSelect?: boolean;
400
402
  content?: ITableContent<T>[] | ((row: T) => ITableContent<T>[]);
401
403
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "poe-svelte-ui-lib",
3
- "version": "2.1.0",
3
+ "version": "2.1.2",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/Oleg-Perevyshin/ElementsUI.git"