poe-svelte-ui-lib 2.0.2 → 2.1.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
@@ -89,15 +89,15 @@ GUI из конструктора рисует `GUIRenderer`. Он раскла
89
89
  <UI.GUIRenderer components={module.UIBlocks} {link} persistKey={module.ModSN} viewer={!canManage} render={{ VideoViewer: video }} onError={addMessage} />
90
90
  ```
91
91
 
92
- | Пропс | Что это |
93
- | ------------ | ------------------------------------------------------------------------------------------------------------- |
94
- | `components` | `UIComponent[]` в формате 2.0 (`migrateGUI` применяется один раз к сохранённым GUI, рендерер его не вызывает) |
95
- | `link` | `DeviceLink` выбранного модуля, см. ниже |
96
- | `language` | язык текстов GUI, по умолчанию язык библиотеки |
97
- | `viewer` | наблюдатель: видны только `access` `full` и `viewOnly`, управление отключено |
98
- | `persistKey` | ключ хранения в браузере (обычно `ModSN`): свёрнутость виджетов, планы `WidgetMap` |
99
- | `render` | своя отрисовка типа: `{ VideoViewer: snippet }`, сниппет получает компонент |
100
- | `onError` | текст ошибки команды или передачи файла |
92
+ | Пропс | Что это |
93
+ | ------------ | ---------------------------------------------------------------------------------- |
94
+ | `components` | `UIComponent[]` в формате 2.0 |
95
+ | `link` | `DeviceLink` выбранного модуля, см. ниже |
96
+ | `language` | язык текстов GUI, по умолчанию язык библиотеки |
97
+ | `viewer` | наблюдатель: видны только `access` `full` и `viewOnly`, управление отключено |
98
+ | `persistKey` | ключ хранения в браузере (обычно `ModSN`): свёрнутость виджетов, планы `WidgetMap` |
99
+ | `render` | своя отрисовка типа: `{ VideoViewer: snippet }`, сниппет получает компонент |
100
+ | `onError` | текст ошибки команды или передачи файла |
101
101
 
102
102
  ```ts
103
103
  interface DeviceLink {
@@ -247,7 +247,7 @@ export const T = createTranslator(translations)
247
247
 
248
248
  ## Переход на 2.0
249
249
 
250
- Версия 2.0 меняет API. Сохранённые GUI (каталог DevCloud, интерфейсы устройств) переводятся один раз функцией `migrateGUI(components)`, для одного компонента - `migrateProperties(component)`; рендерер GUI старый формат не читает. Обе функции чистые: исходный объект не меняется, повторный вызов ничего не меняет. Код приложений правится вручную по списку ниже.
250
+ Версия 2.0 меняет API. Сохранённые GUI 1.x рендерер не читает: каталог DevCloud и интерфейсы устройств переведены один раз (функции перевода удалены в 2.1.0). Код приложений правится вручную по списку ниже.
251
251
 
252
252
  **Цвет: `accent` вместо классов.** Классы `bg-*` и `text-*` в `componentClass`, `wrapperClass`, `settings.class`, `options[].class`, `items[].class` цвет больше не задают.
253
253
 
@@ -304,7 +304,7 @@ export const T = createTranslator(translations)
304
304
  | `updateProperty("label.class", v, component, onPropertyChange)` | `createPropsEditor(component, onPropertyChange).patch("label", { class: v })` |
305
305
  | `updateComponent`, `findOptionByClass`, `findColorOption`, `stripLegacyTextColor`, `COLOR_OPTIONS`, `TEXT_COLOR_OPTIONS`, `WidgetAccentPicker` | удалены |
306
306
 
307
- В `poe-svelte-ui-lib/constructor` также `optionsStore`, `ACCENT_OPTIONS`, `CommonSnippets`, `createPropsEditor` и словарь `constructorTranslations`. В `i18n` добавлены `extendTranslations(dictionary)` и тип `TranslationKey` (подсказка ключей в `$T`, любая строка по-прежнему допустима).
307
+ В `poe-svelte-ui-lib/constructor` также `optionsStore` (в нём и палитра `ACCENT_OPTIONS`; повторное нажатие на выбранный цвет снимает его), `CommonSnippets`, `createPropsEditor` и словарь `constructorTranslations`. В `i18n` добавлены `extendTranslations(dictionary)` и тип `TranslationKey` (подсказка ключей в `$T`, любая строка по-прежнему допустима).
308
308
 
309
309
  **Table.**
310
310
 
@@ -377,7 +377,7 @@ const canModal = createRawSnippet((row: () => CanRow) => ({ render: () => `<div
377
377
  **Прочее.**
378
378
 
379
379
  - Компоненты не выводят случайные DOM id вида `${id}-xxxxxx`. Проп `id` примитива - переменная устройства, в разметку он не попадает (кроме `Button`, где это атрибут `id`).
380
- - Новые экспорты: `Icon`, `accentStyle`, `ACCENT_COLORS`, `AccentColor`, `migrateProperties`, `migrateGUI`, `copyText`, `SelectValue`, `IconSource`, `configureMapLibre`.
380
+ - Новые экспорты: `Icon`, `accentStyle`, `ACCENT_COLORS`, `AccentColor`, `copyText`, `SelectValue`, `IconSource`, `configureMapLibre`.
381
381
  - Ключи переводов `ui.info.show`, `ui.info.hide`, `library.for_constructor` удалены; добавлены `ui.joystick.*`, `widget.rgb.hue`, `widget.rgb.brightness`.
382
382
 
383
383
  ## Как описывать компонент
@@ -7,7 +7,8 @@
7
7
  import type { UIComponent, IButtonProps } from "../types"
8
8
  import { createPropsEditor, optionByClass, type PropertyChange } from "../propsEditor"
9
9
  import * as UI from ".."
10
- import { ACCENT_OPTIONS, optionsStore } from "../options"
10
+ import { optionsStore } from "../options"
11
+ import type { AccentColor } from "../accent"
11
12
  import { twMerge } from "tailwind-merge"
12
13
  import { ICONS } from "../icons"
13
14
  import CommonSnippets from "../CommonSnippets.svelte"
@@ -31,16 +32,16 @@
31
32
  if (!component.eventHandler?.Argument) onPropertyChange({ eventHandler: { Argument: "ModCfg" } })
32
33
  })
33
34
 
34
- /* Один выбор цвета: "-" - secondary, цвет - primary этого цвета, повторное нажатие на выбранный - plain (без фона) */
35
- const colorValue = $derived(properties.variant === "primary" ? (properties.accent ?? "blue") : properties.variant === "secondary" ? "" : undefined)
36
- const setColor = (accent: (typeof ACCENT_OPTIONS)[number]["value"]) =>
35
+ /* Один выбор цвета: серый - secondary (поверхность с контуром), цвет - primary этого цвета, повторное нажатие на выбранный - plain (без фона) */
36
+ const colorValue = $derived(properties.variant === "primary" ? (properties.accent ?? "blue") : properties.variant === "secondary" ? "gray" : undefined)
37
+ const setColor = (accent: AccentColor) =>
37
38
  onPropertyChange({
38
39
  properties:
39
40
  accent === colorValue
40
41
  ? { variant: "plain", accent: undefined }
41
- : accent
42
- ? { variant: "primary", accent: accent === "blue" ? undefined : accent }
43
- : { variant: "secondary", accent: undefined },
42
+ : accent === "gray"
43
+ ? { variant: "secondary", accent: undefined }
44
+ : { variant: "primary", accent: accent === "blue" ? undefined : accent },
44
45
  })
45
46
 
46
47
  /* Иконка без подписи - круглая кнопка по размеру иконки */
@@ -91,7 +92,13 @@
91
92
  />
92
93
  <div class="flex items-end gap-2">
93
94
  <UI.Button wrapperClass="w-8" content={{ icon: InfoIcon, info: { text: $T("constructor.props.button.colors.hint"), side: "right" } }} />
94
- <UI.Select label={{ name: $T("constructor.props.colors") }} type="buttons" options={ACCENT_OPTIONS} value={colorValue} onUpdate={setColor} />
95
+ <UI.Select
96
+ label={{ name: $T("constructor.props.colors") }}
97
+ type="buttons"
98
+ options={$optionsStore.ACCENT_OPTIONS}
99
+ value={colorValue}
100
+ onUpdate={setColor}
101
+ />
95
102
  </div>
96
103
  </PropsGroup>
97
104
  <PropsGroup label={$T("constructor.props.group.appearance")}>
@@ -4,7 +4,7 @@
4
4
  import * as UI from "./index"
5
5
  import { T } from "./locales/i18n"
6
6
  import CrossIcon from "./libIcons/CrossIcon.svelte"
7
- import { ACCENT_OPTIONS, optionsStore } from "./options"
7
+ import { optionsStore } from "./options"
8
8
  import { createPropsEditor, optionByClass, type PropertyChange } from "./propsEditor"
9
9
  import type { AccentColor } from "./accent"
10
10
  import type { IOption } from "./types"
@@ -172,9 +172,9 @@
172
172
  <UI.Select
173
173
  label={{ name: $T("ui.accent") }}
174
174
  type="buttons"
175
- options={ACCENT_OPTIONS.filter((option) => !initialValue?.exclude?.includes(option.value))}
176
- value={properties.accent ?? ""}
177
- onUpdate={(accent) => edit.set("accent", accent || undefined)}
175
+ options={$optionsStore.ACCENT_OPTIONS.filter((option) => !initialValue?.exclude?.includes(option.value))}
176
+ value={properties.accent}
177
+ onUpdate={(accent) => edit.set("accent", accent === properties.accent ? undefined : accent)}
178
178
  />
179
179
  {:else if snippet === "Label"}
180
180
  <TextsEditor {component} {onPropertyChange} />
@@ -6,7 +6,7 @@
6
6
  import type { IProgressBarProps, UIComponent } from "../types"
7
7
  import { createPropsEditor, type PropertyChange } from "../propsEditor"
8
8
  import * as UI from ".."
9
- import { ACCENT_OPTIONS, optionsStore } from "../options"
9
+ import { optionsStore } from "../options"
10
10
  import TextsEditor from "../TextsEditor.svelte"
11
11
  import ButtonAdd from "../libIcons/ButtonAdd.svelte"
12
12
  import ButtonDelete from "../libIcons/ButtonDelete.svelte"
@@ -89,9 +89,9 @@
89
89
  <UI.Select
90
90
  wrapperClass="col-span-2"
91
91
  type="buttons"
92
- options={ACCENT_OPTIONS.filter((option) => option.value)}
92
+ options={$optionsStore.ACCENT_OPTIONS}
93
93
  value={progress.accent}
94
- onUpdate={(accent) => edit.updateItem("items", index, { accent: accent || undefined })}
94
+ onUpdate={(accent) => edit.updateItem("items", index, { accent: accent === progress.accent ? undefined : accent })}
95
95
  />
96
96
  <UI.Button wrapperClass="w-8" content={{ icon: ButtonDelete }} onClick={() => edit.removeItem("items", index)} />
97
97
  </div>
@@ -7,7 +7,7 @@
7
7
  import * as UI from ".."
8
8
  import ButtonDelete from "../libIcons/ButtonDelete.svelte"
9
9
  import ButtonAdd from "../libIcons/ButtonAdd.svelte"
10
- import { ACCENT_OPTIONS, optionsStore } from "../options"
10
+ import { optionsStore } from "../options"
11
11
  import CommonSnippets from "../CommonSnippets.svelte"
12
12
  import PropsGroup from "../PropsGroup.svelte"
13
13
  import PropsListModal from "../PropsListModal.svelte"
@@ -166,9 +166,9 @@
166
166
  />
167
167
  <UI.Select
168
168
  type="buttons"
169
- options={ACCENT_OPTIONS}
170
- value={option.accent ?? ""}
171
- onUpdate={(accent) => edit.updateItem("options", index, { accent: accent || undefined })}
169
+ options={$optionsStore.ACCENT_OPTIONS}
170
+ value={option.accent}
171
+ onUpdate={(accent) => edit.updateItem("options", index, { accent: accent === option.accent ? undefined : accent })}
172
172
  />
173
173
  <UI.Button wrapperClass="w-8" content={{ icon: ButtonDelete }} onClick={() => edit.removeItem("options", index)} />
174
174
  </div>
@@ -72,10 +72,36 @@
72
72
  /* Двойной слайдер: оба input на всю ширину трека с ОДИНАКОВЫМ min/max, наложены друг на друга. pointer-events выключен на самом input и включён только на ::thumb (класс .range-overlay ниже) - тянуть можно исключительно за конкретный бегунок. Tailwind не генерирует CSS для сочетания произвольного варианта псевдоэлемента с pointer-events-*, поэтому это обычный style-блок ниже, а не класс. */
73
73
  </script>
74
74
 
75
+ {#snippet counter(target: "lower" | "upper")}
76
+ {@const v = target === "lower" ? lower : upper}
77
+ <div class="flex h-7 shrink-0 items-center gap-1 rounded-lg border border-(--border-color) bg-(--field-color) px-1 {disabled ? 'opacity-45' : ''}">
78
+ {#each DIRECTIONS as direction (direction)}
79
+ <button
80
+ class="flex size-5 items-center justify-center rounded text-(--muted-color) transition-colors duration-150 hover:bg-(--container-color) disabled:cursor-not-allowed disabled:opacity-40 {direction ===
81
+ 1
82
+ ? 'order-last'
83
+ : ''} {disabled ? 'cursor-not-allowed' : 'cursor-pointer'}"
84
+ onclick={() => adjust(target, direction)}
85
+ disabled={disabled ||
86
+ (direction === -1
87
+ ? target === "lower"
88
+ ? v <= number.minNum
89
+ : v <= lower + number.step
90
+ : target === "upper" || !isRange
91
+ ? v >= number.maxNum
92
+ : v >= upper - number.step)}
93
+ aria-label={direction === 1 ? $T("ui.increase") : $T("ui.decrease")}>{direction === 1 ? "+" : "−"}</button
94
+ >
95
+ {/each}
96
+ <span class="inline-block text-center text-[13px] font-semibold tabular-nums" style="width: {valueWidth}">{v}</span>
97
+ </div>
98
+ {/snippet}
99
+
75
100
  <div class={twMerge(`relative flex w-full flex-col gap-1.5`, wrapperClass)} style={accentStyle(accent)}>
76
101
  <FieldLabel {label} for={uid} class="w-full" />
77
102
 
78
103
  <div class="flex w-full items-center gap-3">
104
+ {#if isRange}{@render counter("lower")}{/if}
79
105
  <!-- Дорожка: фон --border-color заметен на светлом фоне, заливка - акцент -->
80
106
  <div class="relative flex h-8 flex-1 items-center {disabled ? 'cursor-not-allowed opacity-45' : ''}">
81
107
  <div class="pointer-events-none absolute inset-x-0 top-1/2 h-1.5 -translate-y-1/2 rounded-full bg-(--border-color)"></div>
@@ -111,31 +137,8 @@
111
137
  {/each}
112
138
  </div>
113
139
 
114
- <!-- Значения со счётчиком -->
115
- {#each targets as target (target)}
116
- {@const v = target === "lower" ? lower : upper}
117
- <div class="flex h-7 shrink-0 items-center gap-1 rounded-lg border border-(--border-color) bg-(--field-color) px-1 {disabled ? 'opacity-45' : ''}">
118
- {#each DIRECTIONS as direction (direction)}
119
- <button
120
- class="flex size-5 items-center justify-center rounded text-(--muted-color) transition-colors duration-150 hover:bg-(--container-color) disabled:cursor-not-allowed disabled:opacity-40 {direction ===
121
- 1
122
- ? 'order-last'
123
- : ''} {disabled ? 'cursor-not-allowed' : 'cursor-pointer'}"
124
- onclick={() => adjust(target, direction)}
125
- disabled={disabled ||
126
- (direction === -1
127
- ? target === "lower"
128
- ? v <= number.minNum
129
- : v <= lower + number.step
130
- : target === "upper" || !isRange
131
- ? v >= number.maxNum
132
- : v >= upper - number.step)}
133
- aria-label={direction === 1 ? $T("ui.increase") : $T("ui.decrease")}>{direction === 1 ? "+" : "−"}</button
134
- >
135
- {/each}
136
- <span class="inline-block text-center text-[13px] font-semibold tabular-nums" style="width: {valueWidth}">{v}</span>
137
- </div>
138
- {/each}
140
+ <!-- Значение со счётчиком: у диапазона нижнее слева от дорожки, верхнее справа -->
141
+ {@render counter(isRange ? "upper" : "lower")}
139
142
  </div>
140
143
  </div>
141
144
 
@@ -5,7 +5,7 @@
5
5
  import type { UIComponent, ISwitchProps } from "../types"
6
6
  import { createPropsEditor, type PropertyChange } from "../propsEditor"
7
7
  import * as UI from ".."
8
- import { ACCENT_OPTIONS, optionsStore } from "../options"
8
+ import { optionsStore } from "../options"
9
9
  import ButtonAdd from "../libIcons/ButtonAdd.svelte"
10
10
  import ButtonDelete from "../libIcons/ButtonDelete.svelte"
11
11
  import CommonSnippets from "../CommonSnippets.svelte"
@@ -52,7 +52,7 @@
52
52
  <CommonSnippets snippet="Label" {component} {onPropertyChange} />
53
53
  <CommonSnippets snippet="LabelAlign" {component} {onPropertyChange} />
54
54
  {#if !bitMode}
55
- <CommonSnippets snippet="Accent" initialValue={{ exclude: ["", "gray"] }} {component} {onPropertyChange} />
55
+ <CommonSnippets snippet="Accent" initialValue={{ exclude: ["gray"] }} {component} {onPropertyChange} />
56
56
  {/if}
57
57
  {#if component.properties.type != "checkbox"}
58
58
  <UI.Switch
@@ -96,9 +96,9 @@
96
96
  />
97
97
  <UI.Select
98
98
  type="buttons"
99
- options={ACCENT_OPTIONS.filter((option) => option.value && option.value !== "gray")}
99
+ options={$optionsStore.ACCENT_OPTIONS.filter((option) => option.value !== "gray")}
100
100
  value={bit.accent}
101
- onUpdate={(accent) => edit.updateItem("options", index, { accent: accent || undefined })}
101
+ onUpdate={(accent) => edit.updateItem("options", index, { accent: accent === bit.accent ? undefined : accent })}
102
102
  />
103
103
  <UI.Switch
104
104
  label={{ captionRight: $T("constructor.props.disabled") }}
@@ -79,7 +79,8 @@
79
79
  - Ширину колонки в знаках моноширинного текста считает `tableMonoWidth(знаков, знаковПодписи?)` из `columnWidth.ts`. Колонка растёт вместе с размером шрифта и не бывает уже заголовка. Пример: `width: tableMonoWidth(6, 2)` для `0x0000`.
80
80
  - Колонка с `width: "0%"` скрыта. Без `width` колонка занимает `minmax(0, 1fr)`.
81
81
  - Колонки с выравниванием вправо показывают цифры одинаковой ширины.
82
- - Текстовая ячейка выводит `render(row)`, без него - значение по `key`: массив вариантов `{ name, value }` списком `name`, другой объект - как JSON. Всё выводится как текст, HTML - только с `html: true`, данные тогда экранирует вызывающий. Ссылку задаёт `href(row)`: ячейка становится `<a>` с текстом внутри, HTML для этого не нужен.
82
+ - Текстовая ячейка выводит `render(row)`, без него - значение по `key`: массив вариантов `{ name, value }` списком `name`, другой объект - как JSON. Всё выводится как текст, HTML - только с `html: true`, данные тогда экранирует вызывающий. Ссылку задаёт `href(row)`: ячейка становится `<a>` с текстом внутри, HTML для этого не нужен. `
83
+ ` в тексте переносит строку. Цвет из строки задаёт `accent(row)` (роль темы, как у компонентов), с `badge: true` текст стоит на мягкой подложке своего цвета.
83
84
  - `modal: true` открывает по нажатию содержимое ячейки целиком: длинные строки переносятся, отступы сохраняются, кнопка в окне копирует текст. `modal` - сниппет `Snippet<[row]>`: в окне своё содержимое (без кнопки внизу), так устроено окно xPOE-Debug.
84
85
  - `copy` и подсказка берут видимый текст ячейки (у HTML-ячейки без разметки).
85
86
  - `outline` рисует рамки строк и колонок.
@@ -131,7 +132,7 @@
131
132
 
132
133
  | `type` | Поля `data` |
133
134
  | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
134
- | `text` | `key`, `render(row)`, `href(row)`, `html`, `sortable`, `truncated`, `tooltip`, `copy`, `modal` (`true` или сниппет), `class` |
135
+ | `text` | `key`, `render(row)`, `href(row)`, `html`, `sortable`, `truncated`, `tooltip`, `copy`, `modal` (`true` или сниппет), `accent(row)`, `badge` |
135
136
  | `button` | `name`, `icon`, `title`, `class` (строки или функции от строки), `eventHandler`, `onClick(row)`. У кнопки-иконки без `name` обязательно `title`. Весь `data` может быть функцией от строки |
136
137
  | `select` | `key` (массив вариантов в строке), `keyCol`, `onChange` |
137
138
  | `progressBar` | `key`, `minNum`, `maxNum`, `units` |
@@ -381,10 +381,15 @@
381
381
  {:else if content.type === "text"}
382
382
  {@const text = content.data}
383
383
  {@const value = cellContent(row, text)}
384
- <!-- w-full + min-w-0: при justify-items-start ячейка иначе берёт ширину по содержимому и truncate не даёт «…» -->
384
+ {@const accent = text.accent?.(row)}
385
+ <!-- w-full + min-w-0: при justify-items-start ячейка иначе берёт ширину по содержимому и truncate не даёт «…»;
386
+ в тексте - перенос строки -->
385
387
  <div class="flex w-full min-w-0 items-center">
386
388
  <div
387
- class="w-full max-w-full min-w-0 wrap-break-word {text.truncated ? 'truncate' : 'whitespace-normal'}"
389
+ class="max-w-full min-w-0 wrap-break-word {text.truncated ? 'truncate' : 'whitespace-pre-line'} {accent
390
+ ? 'text-(--accent-text)'
391
+ : ''} {accent && text.badge ? 'w-fit rounded-md bg-(--accent-soft) px-1.5 text-[12px] font-medium' : 'w-full'}"
392
+ style={accentStyle(accent)}
388
393
  onmouseenter={text.tooltip ? (e) => (tooltip = { show: true, text: cellText(row, text), x: e.clientX, y: e.clientY }) : undefined}
389
394
  onmouseleave={text.tooltip ? () => (tooltip.show = false) : undefined}
390
395
  onmousemove={text.tooltip ? (e) => ((tooltip.x = e.clientX), (tooltip.y = e.clientY)) : undefined}
@@ -6,7 +6,8 @@
6
6
  import * as UI from ".."
7
7
  import ButtonDelete from "../libIcons/ButtonDelete.svelte"
8
8
  import ButtonAdd from "../libIcons/ButtonAdd.svelte"
9
- import { ACCENT_OPTIONS, optionsStore } from "../options"
9
+ import { optionsStore } from "../options"
10
+ import { isAccentColor, type AccentColor } from "../accent"
10
11
  import { ICONS } from "../icons"
11
12
  import CommonSnippets from "../CommonSnippets.svelte"
12
13
  import PropsGroup from "../PropsGroup.svelte"
@@ -31,7 +32,11 @@
31
32
  let isDropdownOpen = $state(-1)
32
33
 
33
34
  /* Цвет кнопки ячейки - роль bg-* в её class */
34
- const roleOf = (classes: string | undefined) => (classes?.match(/(?:^|\s)bg-(\w+)/)?.[1] ?? "") as (typeof ACCENT_OPTIONS)[number]["value"]
35
+ /* Цвет кнопки по классу bg-*: без него - цвет таблицы, bg-transparent - без цвета */
36
+ const roleOf = (classes: string | undefined, fallback?: AccentColor): AccentColor | undefined => {
37
+ const role = classes?.match(/(?:^|\s)bg-(\w+)/)?.[1]
38
+ return role === undefined ? fallback : isAccentColor(role) ? role : undefined
39
+ }
35
40
 
36
41
  let settingsContainer: HTMLDivElement[] = $state([])
37
42
  let columnContainer: HTMLDivElement | null = $state(null)
@@ -339,8 +344,8 @@
339
344
  wrapperClass="min-w-0 flex-1"
340
345
  label={{ name: $T("constructor.props.colors") }}
341
346
  type="buttons"
342
- options={ACCENT_OPTIONS.filter((option) => option.value)}
343
- value={roleOf(button.class as string) || (component.properties.accent ?? "")}
347
+ options={$optionsStore.ACCENT_OPTIONS}
348
+ value={roleOf(button.class as string, component.properties.accent)}
344
349
  onUpdate={(accent) =>
345
350
  updateContentProperty(
346
351
  columnIndex,
@@ -140,7 +140,6 @@
140
140
 
141
141
  <!-- Редактируемые настройки -->
142
142
  <div class="flex flex-col gap-3 rounded-[10px] border border-(--hairline-color) bg-(--back-color) p-3">
143
- <span class="text-[12px] font-semibold text-(--muted-color)">{$T("widget.info.settings")}</span>
144
143
  <div class="grid grid-cols-1 gap-2 sm:grid-cols-2">
145
144
  <div use:hint={{ text: $T("widget.info.hint.name"), enabled: $hints }}>
146
145
  <UI.Input
@@ -146,10 +146,6 @@
146
146
  {#if cfg.WiFiMode === 1 || cfg.WiFiMode === 3}
147
147
  <!-- Клиентский режим (STA) -->
148
148
  <div class="flex flex-col gap-3 rounded-[10px] border border-(--hairline-color) bg-(--back-color) p-3" transition:slide={{ duration: 150 }}>
149
- <span class="w-fit text-[12px] font-semibold text-(--muted-color)" use:hint={{ text: $T("widget.wifi.hint.sta"), enabled: $hints }}
150
- >{$T("widget.wifi.sta")}</span
151
- >
152
-
153
149
  <!-- SSID с поиском и пароль - одной строкой по 50%, на узком экране друг под другом -->
154
150
  <div class="grid grid-cols-1 gap-x-4 gap-y-3 sm:grid-cols-2">
155
151
  <div class="flex min-w-0 items-end gap-2">
@@ -175,7 +171,7 @@
175
171
  <!-- one-time-code: менеджер паролей браузера не считает поле паролем входа и не накрывает список сетей у SSID своими сохранёнными логинами (autocomplete="off" для паролей Chrome игнорирует) -->
176
172
  <UI.Input
177
173
  type="password"
178
- label={{ name: $T("widget.common.password") }}
174
+ label={{ name: $T("widget.wifi.sta_psk") }}
179
175
  bind:value={cfg.StaPSK}
180
176
  maxlength={64}
181
177
  help={{ autocomplete: "one-time-code", regExp: PSK_REGEXP }}
@@ -230,16 +226,14 @@
230
226
  {#if cfg.WiFiMode === 2 || cfg.WiFiMode === 3}
231
227
  <!-- Точка доступа (AP) -->
232
228
  <div class="flex flex-col gap-3 rounded-[10px] border border-(--hairline-color) bg-(--back-color) p-3" transition:slide={{ duration: 150 }}>
233
- <span class="w-fit text-[12px] font-semibold text-(--muted-color)" use:hint={{ text: $T("widget.wifi.hint.ap"), enabled: $hints }}
234
- >{$T("widget.wifi.ap")}</span
235
- >
236
-
237
229
  <!-- Те же колонки, что у STA: в режиме STA + AP пароли стоят друг под другом -->
238
230
  <div class="grid grid-cols-1 gap-x-4 gap-y-3 sm:grid-cols-2">
239
- <UI.Input label={{ name: "SSID" }} bind:value={cfg.ApSSID} maxlength={32} />
231
+ <div use:hint={{ text: $T("widget.wifi.hint.ap"), enabled: $hints }}>
232
+ <UI.Input label={{ name: $T("widget.wifi.ap_ssid") }} bind:value={cfg.ApSSID} maxlength={32} />
233
+ </div>
240
234
  <UI.Input
241
235
  type="password"
242
- label={{ name: $T("widget.common.password") }}
236
+ label={{ name: $T("widget.wifi.ap_psk") }}
243
237
  bind:value={cfg.ApPSK}
244
238
  maxlength={64}
245
239
  help={{ autocomplete: "one-time-code", regExp: PSK_REGEXP }}
@@ -26,7 +26,7 @@ import WidgetRGBStripProps from "./WidgetRGBStrip/WidgetRGBStripProps.svelte";
26
26
  import WidgetPFDProps from "./WidgetPFD/WidgetPFDProps.svelte";
27
27
  import WidgetMapProps from "./WidgetMap/WidgetMapProps.svelte";
28
28
  export { constructorTranslations };
29
- export { optionsStore, ACCENT_OPTIONS } from "./options";
29
+ export { optionsStore } from "./options";
30
30
  export { createPropsEditor, applyPropertyChange, type PropertyChange } from "./propsEditor";
31
31
  export { default as CommonSnippets } from "./CommonSnippets.svelte";
32
32
  export { COMPONENT_DEFAULTS, COMPONENT_SIZES, minComponentWidth, createComponent } from "./defaults";
@@ -27,7 +27,7 @@ import WidgetPFDProps from "./WidgetPFD/WidgetPFDProps.svelte";
27
27
  import WidgetMapProps from "./WidgetMap/WidgetMapProps.svelte";
28
28
  extendTranslations(constructorTranslations);
29
29
  export { constructorTranslations };
30
- export { optionsStore, ACCENT_OPTIONS } from "./options";
30
+ export { optionsStore } from "./options";
31
31
  export { createPropsEditor, applyPropertyChange } from "./propsEditor";
32
32
  export { default as CommonSnippets } from "./CommonSnippets.svelte";
33
33
  export { COMPONENT_DEFAULTS, COMPONENT_SIZES, minComponentWidth, createComponent } from "./defaults";
package/dist/index.d.ts CHANGED
@@ -36,7 +36,6 @@ export * from "./locales/i18n";
36
36
  export * from "./locales/languages";
37
37
  export { localizeDeep, type LocalizedText } from "./locales/localize";
38
38
  export { accentStyle, ACCENT_COLORS, type AccentColor } from "./accent";
39
- export { migrateProperties, migrateGUI } from "./migrate";
40
39
  export { default as GUIRenderer } from "./GUIRenderer/GUIRenderer.svelte";
41
40
  export { COMPONENTS, componentVariables, type ComponentEntry, type ComponentIO } from "./registry";
42
41
  export { GUI_GRID, isWidgetType, spanRows, WIDGET_FIELDS, WIDGET_SAVE_FIELDS, widgetKey, widgetPrefixes, readWidgetFields, widgetPacket, bitRange, readBits, writeBits, commandPacket, tablePacket, mergeDevicePayload, type WidgetFieldsType, type DeviceLink, type DevicePacket, } from "./gui";
package/dist/index.js CHANGED
@@ -37,7 +37,6 @@ export * from "./locales/i18n";
37
37
  export * from "./locales/languages";
38
38
  export { localizeDeep } from "./locales/localize";
39
39
  export { accentStyle, ACCENT_COLORS } from "./accent";
40
- export { migrateProperties, migrateGUI } from "./migrate";
41
40
  export { default as GUIRenderer } from "./GUIRenderer/GUIRenderer.svelte";
42
41
  export { COMPONENTS, componentVariables } from "./registry";
43
42
  export { GUI_GRID, isWidgetType, spanRows, WIDGET_FIELDS, WIDGET_SAVE_FIELDS, widgetKey, widgetPrefixes, readWidgetFields, widgetPacket, bitRange, readBits, writeBits, commandPacket, tablePacket, mergeDevicePayload, } from "./gui";
@@ -124,11 +124,6 @@ declare const translations: {
124
124
  en: string;
125
125
  zh: string;
126
126
  };
127
- "widget.common.password": {
128
- ru: string;
129
- en: string;
130
- zh: string;
131
- };
132
127
  "widget.common.ip": {
133
128
  ru: string;
134
129
  en: string;
@@ -164,27 +159,32 @@ declare const translations: {
164
159
  en: string;
165
160
  zh: string;
166
161
  };
167
- "widget.wifi.sta": {
162
+ "widget.wifi.ssid": {
168
163
  ru: string;
169
164
  en: string;
170
165
  zh: string;
171
166
  };
172
- "widget.wifi.ssid": {
167
+ "widget.wifi.sta_psk": {
173
168
  ru: string;
174
169
  en: string;
175
170
  zh: string;
176
171
  };
177
- "widget.wifi.scan": {
172
+ "widget.wifi.ap_ssid": {
178
173
  ru: string;
179
174
  en: string;
180
175
  zh: string;
181
176
  };
182
- "widget.wifi.ip_mode": {
177
+ "widget.wifi.ap_psk": {
178
+ ru: string;
179
+ en: string;
180
+ zh: string;
181
+ };
182
+ "widget.wifi.scan": {
183
183
  ru: string;
184
184
  en: string;
185
185
  zh: string;
186
186
  };
187
- "widget.wifi.ap": {
187
+ "widget.wifi.ip_mode": {
188
188
  ru: string;
189
189
  en: string;
190
190
  zh: string;
@@ -239,11 +239,6 @@ declare const translations: {
239
239
  en: string;
240
240
  zh: string;
241
241
  };
242
- "widget.info.settings": {
243
- ru: string;
244
- en: string;
245
- zh: string;
246
- };
247
242
  "widget.info.name": {
248
243
  ru: string;
249
244
  en: string;
@@ -419,11 +414,6 @@ declare const translations: {
419
414
  en: string;
420
415
  zh: string;
421
416
  };
422
- "widget.wifi.hint.sta": {
423
- ru: string;
424
- en: string;
425
- zh: string;
426
- };
427
417
  "widget.wifi.hint.ap": {
428
418
  ru: string;
429
419
  en: string;
@@ -33,7 +33,6 @@ const translations = {
33
33
  "widget.common.refresh": { ru: "Обновить", en: "Refresh", zh: "刷新" },
34
34
  "widget.common.delete": { ru: "Удалить", en: "Delete", zh: "删除" },
35
35
  "widget.common.unsaved": { ru: "Есть несохранённые изменения", en: "There are unsaved changes", zh: "有未保存的更改" },
36
- "widget.common.password": { ru: "Пароль", en: "Password", zh: "密码" },
37
36
  "widget.common.ip": { ru: "IP адрес", en: "IP address", zh: "IP 地址" },
38
37
  "widget.common.mask": { ru: "Маска подсети", en: "Subnet mask", zh: "子网掩码" },
39
38
  "widget.common.gateway": { ru: "Шлюз", en: "Gateway", zh: "网关" },
@@ -41,11 +40,12 @@ const translations = {
41
40
  "widget.common.kbytes": { ru: "{n} КБ", en: "{n} KB", zh: "{n} KB" },
42
41
  "widget.common.mbytes": { ru: "{n} МБ", en: "{n} MB", zh: "{n} MB" },
43
42
  "widget.common.free": { ru: "Свободно {size}", en: "Free {size}", zh: "可用 {size}" },
44
- "widget.wifi.sta": { ru: "Режим клиента (STA)", en: "Client mode (STA)", zh: "客户端模式 (STA)" },
45
- "widget.wifi.ssid": { ru: "SSID сети", en: "Network SSID", zh: "网络 SSID" },
43
+ "widget.wifi.ssid": { ru: "Сеть Wi-Fi (SSID)", en: "Wi-Fi network (SSID)", zh: "Wi-Fi 网络 (SSID)" },
44
+ "widget.wifi.sta_psk": { ru: "Пароль сети Wi-Fi", en: "Wi-Fi network password", zh: "Wi-Fi 网络密码" },
45
+ "widget.wifi.ap_ssid": { ru: "Имя точки доступа (SSID)", en: "Access point name (SSID)", zh: "接入点名称 (SSID)" },
46
+ "widget.wifi.ap_psk": { ru: "Пароль точки доступа", en: "Access point password", zh: "接入点密码" },
46
47
  "widget.wifi.scan": { ru: "Сканировать сети", en: "Scan networks", zh: "扫描网络" },
47
48
  "widget.wifi.ip_mode": { ru: "Получение IP", en: "IP assignment", zh: "IP 获取方式" },
48
- "widget.wifi.ap": { ru: "Точка доступа (AP)", en: "Access point (AP)", zh: "接入点 (AP)" },
49
49
  "widget.wifi.ap_confirm_title": { ru: "Сохранить режим AP?", en: "Save AP mode?", zh: "保存 AP 模式?" },
50
50
  "widget.wifi.ap_confirm_text": {
51
51
  ru: "Wi-Fi клиент (STA) будет выключен, устройство отключится от облака и станет доступно только по своей точке доступа. Продолжить?",
@@ -60,7 +60,6 @@ const translations = {
60
60
  "widget.info.runs": { ru: "Запусков", en: "Boot count", zh: "启动次数" },
61
61
  "widget.info.sta_ip": { ru: "IP-адрес (STA)", en: "IP address (STA)", zh: "IP 地址 (STA)" },
62
62
  "widget.info.ap_ip": { ru: "IP-адрес (AP)", en: "IP address (AP)", zh: "IP 地址 (AP)" },
63
- "widget.info.settings": { ru: "Настройки", en: "Settings", zh: "设置" },
64
63
  "widget.info.name": { ru: "Имя устройства", en: "Device name", zh: "设备名称" },
65
64
  "widget.info.host": { ru: "Имя хоста", en: "Host name", zh: "主机名" },
66
65
  "widget.info.web_user": { ru: "Пользователь Web", en: "Web user", zh: "Web 用户" },
@@ -132,11 +131,6 @@ const translations = {
132
131
  en: "Wi-Fi mode: client - the device joins a router, access point - creates its own network, both - at once; off - Wi-Fi is disabled",
133
132
  zh: "Wi-Fi 模式:客户端 - 设备连接路由器,热点 - 创建自己的网络,两者 - 同时;关闭 - Wi-Fi 停用",
134
133
  },
135
- "widget.wifi.hint.sta": {
136
- ru: "Подключение устройства к вашему роутеру: через него устройство выходит в облако",
137
- en: "Connecting the device to your router: the device reaches the cloud through it",
138
- zh: "设备连接到您的路由器:设备通过它访问云端",
139
- },
140
134
  "widget.wifi.hint.ap": {
141
135
  ru: "Собственная сеть устройства - для настройки без роутера, например если роутер сменился",
142
136
  en: "The device's own network - for setup without a router, e.g. after the router has changed",
package/dist/options.d.ts CHANGED
@@ -1,10 +1,11 @@
1
- export declare const ACCENT_OPTIONS: {
2
- id: string;
3
- value: "" | "gray" | "red" | "orange" | "yellow" | "green" | "cyan" | "blue" | "purple";
4
- name: string | undefined;
5
- icon: string | undefined;
6
- }[];
7
1
  export declare const optionsStore: import("svelte/store").Readable<{
2
+ ACCENT_OPTIONS: {
3
+ accent: "gray" | "red" | "orange" | "yellow" | "green" | "cyan" | "blue" | "purple";
4
+ id: string;
5
+ value: "gray" | "red" | "orange" | "yellow" | "green" | "cyan" | "blue" | "purple";
6
+ name: string | undefined;
7
+ icon: string | undefined;
8
+ }[];
8
9
  HEADER_OPTIONS: {
9
10
  id: string;
10
11
  value: string;
package/dist/options.js CHANGED
@@ -4,10 +4,10 @@ import { PROPS_ICONS } from "./libIcons/propsIcons";
4
4
  import { ACCENT_COLORS } from "./accent";
5
5
  /* Вариант со стабильным id по значению: id не меняется при смене языка */
6
6
  const opt = (value, name, icon) => ({ id: String(value), value, name, icon });
7
- /* Палитра ролей темы: "" - без цвета (акцент родителя или темы); порядок по кругу тонов, серый первым */
8
- export const ACCENT_OPTIONS = [opt("", "-"), ...ACCENT_COLORS.map((accent) => ({ ...opt(accent, ""), accent }))];
9
7
  export const optionsStore = derived(T, ($T) => {
10
8
  return {
9
+ /* Палитра ролей темы, порядок по кругу тонов, серый первым. Повторное нажатие на выбранный цвет снимает его: компонент берёт цвет родителя или темы */
10
+ ACCENT_OPTIONS: ACCENT_COLORS.map((accent) => ({ ...opt(accent, ""), accent })),
11
11
  /* Поля eventHandler - строки */
12
12
  HEADER_OPTIONS: ["GET", "SET", "OK!", "ER!"].map((header) => opt(header, header)),
13
13
  SHORT_ARGUMENT_OPTION: [opt("ModCfg", $T("constructor.props.action.save")), opt("NoSend", $T("constructor.props.action.nosend"))],
package/dist/types.d.ts CHANGED
@@ -343,7 +343,8 @@ export interface ITableText<T extends object> {
343
343
  tooltip?: boolean;
344
344
  copy?: boolean;
345
345
  modal?: boolean | Snippet<[T]>;
346
- class?: string;
346
+ accent?: (row: T) => AccentColor | undefined;
347
+ badge?: boolean;
347
348
  }
348
349
  export interface ITableSelect<T extends object> {
349
350
  key: keyof T;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "poe-svelte-ui-lib",
3
- "version": "2.0.2",
3
+ "version": "2.1.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/Oleg-Perevyshin/ElementsUI.git"
package/dist/migrate.d.ts DELETED
@@ -1,3 +0,0 @@
1
- import type { UIComponent } from "./types";
2
- export declare const migrateProperties: <C extends UIComponent>(component: C) => C;
3
- export declare const migrateGUI: <C extends UIComponent>(components: C[]) => C[];
package/dist/migrate.js DELETED
@@ -1,143 +0,0 @@
1
- /* $lib/migrate.ts - перевод сохранённого GUI 1.x в формат 2.0: цвет из классов (bg-*, text-*) в accent, Select хранит значение варианта, Switch - число. Чистые функции, повторный вызов ничего не меняет */
2
- import { isAccentColor } from "./accent.js";
3
- import { isWidgetType } from "./gui.js";
4
- /* Цвет текста 1.x: токен темы text-(color:--red-text) или палитра Tailwind text-red-500, text-[#333] */
5
- const TEXT_COLOR = /^(?:dark:)?text-(?:\(color:--(\w+)-text\)|(\w+)-\d{3}|\[#(?:333|e2e3e7)\])$/;
6
- /* Заливка 1.x: роль bg-red, мягкий вариант bg-red-soft, без роли - bg-max, bg-accent */
7
- const BG_COLOR = /^bg-(\w+?)(?:-soft)?$/;
8
- const BG_NEUTRAL = ["max", "accent"];
9
- /* Убирает из строки классов цветовые классы вида kind, возвращает остаток и роль */
10
- const takeColor = (classes, kind) => {
11
- if (typeof classes !== "string")
12
- return { rest: "" };
13
- let accent;
14
- let found;
15
- const rest = classes
16
- .split(/\s+/)
17
- .filter((cls) => {
18
- const match = cls.match(kind === "bg" ? BG_COLOR : TEXT_COLOR);
19
- const role = match?.[1] ?? match?.[2];
20
- if (!match || (kind === "bg" && !isAccentColor(role) && !BG_NEUTRAL.includes(role)))
21
- return true;
22
- if (isAccentColor(role))
23
- accent = role;
24
- found = cls;
25
- return false;
26
- })
27
- .join(" ");
28
- return { rest, accent, found };
29
- };
30
- /* Переносит цвет из props[key] в accent (если accent ещё не задан); пустой класс удаляется */
31
- const moveColor = (props, key, kind = "bg") => {
32
- if (typeof props[key] !== "string")
33
- return;
34
- const { rest, accent } = takeColor(props[key], kind);
35
- if (accent && !props.accent)
36
- props.accent = accent;
37
- if (rest)
38
- props[key] = rest;
39
- else
40
- delete props[key];
41
- };
42
- /* Вариант 1.x: цвет в class -> accent */
43
- const migrateOption = (option) => {
44
- if (!option || typeof option !== "object" || !("class" in option))
45
- return option;
46
- const { class: classes, ...rest } = option;
47
- const { accent } = takeColor(classes, "bg");
48
- return accent && !rest.accent ? { ...rest, accent } : rest;
49
- };
50
- const isOptionObject = (value) => !!value && typeof value === "object" && !Array.isArray(value) && "value" in value;
51
- const WRAPPER_ACCENT = ["Slider", "Switch", "Joystick", "PeriodChart", "Tabs", "VideoViewer", "ProgressBar", "Table"];
52
- export const migrateProperties = (component) => {
53
- if (!component?.properties || typeof component.properties !== "object")
54
- return component;
55
- const props = structuredClone(component.properties);
56
- const type = component.type;
57
- if (type === "Accordion" || type === "Input" || isWidgetType(type))
58
- moveColor(props, "componentClass");
59
- if (WRAPPER_ACCENT.includes(type))
60
- moveColor(props, "wrapperClass");
61
- switch (type) {
62
- case "Button": {
63
- if (typeof props.componentClass !== "string")
64
- break;
65
- /* bg-max, bg-gray, мягкие - secondary; прочие роли - primary своего цвета; bg-transparent и без заливки - plain */
66
- const { rest, accent, found } = takeColor(props.componentClass, "bg");
67
- if (found && !props.variant)
68
- props.variant = found === "bg-max" || found === "bg-gray" || found.endsWith("-soft") ? "secondary" : "primary";
69
- if (accent && props.variant === "primary" && !props.accent)
70
- props.accent = accent;
71
- props.componentClass = rest.replace(/(?:^|\s)bg-transparent(?=\s|$)/, "").trim();
72
- if (!props.componentClass)
73
- delete props.componentClass;
74
- break;
75
- }
76
- case "Select":
77
- if (Array.isArray(props.value))
78
- props.value = props.value.map((v) => (isOptionObject(v) ? v.value : v));
79
- else if (isOptionObject(props.value))
80
- props.value = props.value.value;
81
- if (Array.isArray(props.options))
82
- props.options = props.options.map(migrateOption);
83
- break;
84
- case "Switch":
85
- if (typeof props.value === "boolean")
86
- props.value = Number(props.value);
87
- if (Array.isArray(props.options)) {
88
- const options = props.options.map(migrateOption);
89
- if (props.bitMode)
90
- props.options = options;
91
- else {
92
- if (options[0]?.accent && !props.accent)
93
- props.accent = options[0].accent;
94
- if (options[0]?.disabled && props.disabled === undefined)
95
- props.disabled = true;
96
- delete props.options;
97
- }
98
- }
99
- break;
100
- case "ProgressBar":
101
- if (Array.isArray(props.items))
102
- props.items = props.items.map(migrateOption);
103
- break;
104
- case "Divider":
105
- if (typeof props.color === "string") {
106
- const { accent } = takeColor(props.color, "bg");
107
- if (accent && !props.accent)
108
- props.accent = accent;
109
- delete props.color;
110
- }
111
- break;
112
- case "TextField":
113
- moveColor(props, "wrapperClass", "text");
114
- if (typeof props.content?.class === "string") {
115
- const { rest, accent } = takeColor(props.content.class, "text");
116
- if (accent && !props.accent)
117
- props.accent = accent;
118
- props.content.class = rest;
119
- }
120
- break;
121
- case "Tabs":
122
- /* Цвет текста вкладок теперь от accent */
123
- if (Array.isArray(props.items))
124
- props.items = props.items.map((item) => (typeof item?.class === "string" ? { ...item, class: takeColor(item.class, "text").rest } : item));
125
- break;
126
- case "Widget":
127
- if (props.settings && typeof props.settings === "object") {
128
- const { accent } = takeColor(props.settings.class, "bg");
129
- if (accent && !props.accent)
130
- props.accent = accent;
131
- delete props.settings.class;
132
- }
133
- if (props.icons && typeof props.icons === "object")
134
- delete props.icons.class;
135
- break;
136
- case "Input":
137
- delete props.isValid;
138
- break;
139
- }
140
- return { ...component, properties: props };
141
- };
142
- /* Весь GUI (массив компонентов) */
143
- export const migrateGUI = (components) => (Array.isArray(components) ? components.map(migrateProperties) : components);