poe-svelte-ui-lib 2.8.0 → 2.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.
- package/README.md +1 -1
- package/dist/Graph/Graph.svelte +58 -23
- package/dist/Graph/README.md +2 -1
- package/dist/PeriodChart/PeriodChartProps.svelte +7 -1
- package/dist/ProgressBar/ProgressBarProps.svelte +1 -1
- package/dist/Select/SelectProps.svelte +1 -1
- package/dist/Switch/SwitchProps.svelte +1 -1
- package/dist/Table/README.md +3 -1
- package/dist/Table/Table.svelte +19 -2
- package/dist/Table/TableProps.svelte +4 -0
- package/dist/Tabs/TabsProps.svelte +7 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.js +1 -0
- package/dist/libIcons/MoreIcon.svelte +5 -0
- package/dist/libIcons/MoreIcon.svelte.d.ts +18 -0
- package/dist/protocols/PROTOCOL.md +2 -1
- package/dist/protocols/dictionary.d.ts +0 -1
- package/dist/protocols/dictionary.js +5 -5
- package/dist/protocols/index.d.ts +1 -1
- package/dist/protocols/index.js +1 -1
- package/dist/types.d.ts +8 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -194,7 +194,7 @@ interface DeviceReply {
|
|
|
194
194
|
|
|
195
195
|
- Свою команду по именам приложение шлёт так же: `sendCommand(link, header, argument, payload)` (аргумент - имя или код), код для ожидания - `argumentCode(link, argument)`.
|
|
196
196
|
- Входящий конверт разберите `decodeWsEnvelope(packet)`: получите `{ header, argument, code, reply, VAL }`. По `code` будите `waitFor`, по `argument` зовите `mergeDevicePayload`.
|
|
197
|
-
-
|
|
197
|
+
- Словарь - встроенный `DEFAULT_DICTIONARY`. Команду, которой в нём нет, передайте кодом: числом или строкой `"4097"`/`"0x1001"`.
|
|
198
198
|
|
|
199
199
|
```ts
|
|
200
200
|
import { encodeWsEnvelope, decodeWsEnvelope, valueToCbor, cborToValue } from "poe-svelte-ui-lib/protocols"
|
package/dist/Graph/Graph.svelte
CHANGED
|
@@ -175,10 +175,6 @@
|
|
|
175
175
|
|
|
176
176
|
/* Общая геометрия осей - переиспользуется отрисовкой и обработчиком наведения мыши, чтобы не дублировать формулы */
|
|
177
177
|
const computeGeometry = (data: Line[]) => {
|
|
178
|
-
const padding = { top: 10, right: 10, bottom: 20, left: 35 }
|
|
179
|
-
const graphWidth = width - padding.left - padding.right
|
|
180
|
-
const graphHeight = height - padding.top - padding.bottom
|
|
181
|
-
|
|
182
178
|
const allPoints = data.flatMap((line) => line.points)
|
|
183
179
|
const minX = allPoints.length ? Math.min(...allPoints.map((p) => p.x)) : 0
|
|
184
180
|
const maxX = allPoints.length ? Math.max(...allPoints.map((p) => p.x)) : 1
|
|
@@ -188,10 +184,18 @@
|
|
|
188
184
|
const { min: yMin, max: yMax } = (!isHistoryMode && liveYRange) || computeAutoYRange(allPoints.map((p) => p.y))
|
|
189
185
|
const ySpan = yMax - yMin || 1
|
|
190
186
|
|
|
187
|
+
/* Подписи Y на круглых значениях; левое поле по самой длинной подписи (моноширинный 10px - около 6 px на знак) */
|
|
188
|
+
const yStep = niceStep(ySpan, 6)
|
|
189
|
+
const yDecimals = stepDecimals(yStep)
|
|
190
|
+
const yLabelChars = Math.max(...[yMin, yMax].map((v) => (Math.ceil(Math.abs(v) / yStep) * yStep * Math.sign(v)).toFixed(yDecimals).length))
|
|
191
|
+
const padding = { top: 10, right: 10, bottom: 20, left: Math.max(35, Math.ceil(yLabelChars * 6.2) + 10) }
|
|
192
|
+
const graphWidth = width - padding.left - padding.right
|
|
193
|
+
const graphHeight = height - padding.top - padding.bottom
|
|
194
|
+
|
|
191
195
|
const getX = (x: number) => padding.left + ((x - minX) / timeSpan) * graphWidth
|
|
192
196
|
const getY = (y: number) => padding.top + graphHeight - ((y - yMin) / ySpan) * graphHeight
|
|
193
197
|
|
|
194
|
-
return { padding, graphWidth, minX, timeSpan, yMin, yMax, getX, getY }
|
|
198
|
+
return { padding, graphWidth, minX, timeSpan, yMin, yMax, yStep, yDecimals, getX, getY }
|
|
195
199
|
}
|
|
196
200
|
|
|
197
201
|
/* Бинарный поиск ближайшей по времени точки - точки линий всегда отсортированы по x (по построению) */
|
|
@@ -210,15 +214,40 @@
|
|
|
210
214
|
|
|
211
215
|
const pad2 = (n: number) => String(n).padStart(2, "0")
|
|
212
216
|
|
|
213
|
-
/*
|
|
214
|
-
const
|
|
215
|
-
|
|
217
|
+
/* Круглый шаг сетки значений: 1, 2, 2.5 или 5 × 10^n, не меньше span / target */
|
|
218
|
+
const niceStep = (span: number, target: number): number => {
|
|
219
|
+
const raw = span / target || 1
|
|
220
|
+
const pow = 10 ** Math.floor(Math.log10(raw))
|
|
221
|
+
return ([1, 2, 2.5, 5, 10].find((m) => m * pow >= raw) ?? 10) * pow
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/* Знаков после запятой для подписей с шагом step */
|
|
225
|
+
const stepDecimals = (step: number): number => {
|
|
226
|
+
let d = 0
|
|
227
|
+
while (d < 6 && Math.abs(Math.round(step * 10 ** d) - step * 10 ** d) > 1e-9) d++
|
|
228
|
+
return d
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/* Шаги сетки времени, мс: от 0.1 с до года */
|
|
232
|
+
const TIME_STEPS = [
|
|
233
|
+
100, 200, 500, 1e3, 2e3, 5e3, 1e4, 15e3, 3e4, 6e4, 12e4, 3e5, 6e5, 9e5, 18e5, 36e5, 72e5, 108e5, 216e5, 432e5, 864e5, 1728e5, 6048e5, 2592e6, 7776e6,
|
|
234
|
+
31536e6,
|
|
235
|
+
]
|
|
236
|
+
|
|
237
|
+
/* Компактная адаптивная подпись сетки по оси X: относительное время для живого режима (точность по шагу сетки), дата/время - для статического */
|
|
238
|
+
const formatAxisLabel = (t: number, spanMs: number, stepMs = 1000): string => {
|
|
239
|
+
if (!isHistoryMode) {
|
|
240
|
+
const s = (t - Date.now()) / 1000
|
|
241
|
+
const text = s.toFixed(stepMs < 1000 ? 1 : 0)
|
|
242
|
+
return `${Number(text) === 0 ? "0" : text}s`
|
|
243
|
+
}
|
|
216
244
|
const d = new Date(t)
|
|
217
245
|
const hhmm = `${pad2(d.getHours())}:${pad2(d.getMinutes())}`
|
|
218
|
-
if (spanMs < 24 * 60 * 60 * 1000) return hhmm
|
|
219
246
|
const ddmm = `${pad2(d.getDate())}.${pad2(d.getMonth() + 1)}`
|
|
220
|
-
if (
|
|
221
|
-
return `${ddmm}.${d.getFullYear()}`
|
|
247
|
+
if (stepMs >= 2592e6) return `${pad2(d.getMonth() + 1)}.${d.getFullYear()}`
|
|
248
|
+
if (stepMs >= 864e5) return spanMs < 31536e6 ? ddmm : `${ddmm}.${d.getFullYear()}`
|
|
249
|
+
const time = stepMs < 6e4 ? `${hhmm}:${pad2(d.getSeconds())}` : hhmm
|
|
250
|
+
return spanMs < 864e5 ? time : `${ddmm} ${time}`
|
|
222
251
|
}
|
|
223
252
|
|
|
224
253
|
/* Полная подпись времени в тултипе */
|
|
@@ -275,7 +304,7 @@
|
|
|
275
304
|
ctx.clearRect(0, 0, width, height)
|
|
276
305
|
|
|
277
306
|
const data = lines()
|
|
278
|
-
const { padding, graphWidth, minX, timeSpan, yMin, yMax, getX, getY } = computeGeometry(data)
|
|
307
|
+
const { padding, graphWidth, minX, timeSpan, yMin, yMax, yStep, yDecimals, getX, getY } = computeGeometry(data)
|
|
279
308
|
const style = getComputedStyle(canvas)
|
|
280
309
|
|
|
281
310
|
/* Сетка в стиле PeriodChart: пунктир цветом --faint-color темы, подписи тем же цветом без прозрачности */
|
|
@@ -289,11 +318,14 @@
|
|
|
289
318
|
/* Сетка X */
|
|
290
319
|
ctx.textAlign = "center"
|
|
291
320
|
|
|
292
|
-
/*
|
|
293
|
-
const
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
321
|
+
/* Линии сетки на круглых отметках времени: самый мелкий шаг, при котором подписи не слипаются (не меньше 50 px) */
|
|
322
|
+
const labelWidthAt = (step: number) =>
|
|
323
|
+
Math.max(ctx.measureText(formatAxisLabel(minX, timeSpan, step)).width, ctx.measureText(formatAxisLabel(minX + timeSpan, timeSpan, step)).width)
|
|
324
|
+
const stepMs = TIME_STEPS.find((step) => (step / timeSpan) * graphWidth >= Math.max(labelWidthAt(step) + 12, 50)) ?? TIME_STEPS.at(-1)!
|
|
325
|
+
const labelWidth = labelWidthAt(stepMs)
|
|
326
|
+
/* Живой режим - отметки кратны шагу от текущего момента («0s», «-5s»), статический - кратны шагу в местном времени */
|
|
327
|
+
const anchor = isHistoryMode ? -new Date(minX).getTimezoneOffset() * 60_000 : Date.now()
|
|
328
|
+
for (let t = anchor + Math.ceil((minX - anchor) / stepMs) * stepMs; t <= minX + timeSpan + 1e-6; t += stepMs) {
|
|
297
329
|
const x = getX(t)
|
|
298
330
|
ctx.globalAlpha = GRID_ALPHA
|
|
299
331
|
ctx.beginPath()
|
|
@@ -302,15 +334,17 @@
|
|
|
302
334
|
ctx.stroke()
|
|
303
335
|
ctx.globalAlpha = 1
|
|
304
336
|
ctx.textBaseline = "top"
|
|
305
|
-
|
|
337
|
+
ctx.fillText(
|
|
338
|
+
formatAxisLabel(t, timeSpan, stepMs),
|
|
339
|
+
Math.min(Math.max(x, padding.left + labelWidth / 2), width - padding.right - labelWidth / 2),
|
|
340
|
+
height - padding.bottom + 2,
|
|
341
|
+
)
|
|
306
342
|
}
|
|
307
343
|
|
|
308
|
-
/* Сетка Y */
|
|
344
|
+
/* Сетка Y на круглых значениях (1, 2, 2.5, 5 × 10^n), линий не больше 8 */
|
|
309
345
|
ctx.textAlign = "right"
|
|
310
346
|
ctx.textBaseline = "middle"
|
|
311
|
-
|
|
312
|
-
for (let i = 0; i <= ySteps; i++) {
|
|
313
|
-
const yVal = yMax - (i * (yMax - yMin)) / ySteps
|
|
347
|
+
for (let yVal = Math.ceil(yMin / yStep) * yStep; yVal <= yMax + yStep * 1e-9; yVal += yStep) {
|
|
314
348
|
const y = getY(yVal)
|
|
315
349
|
ctx.globalAlpha = GRID_ALPHA
|
|
316
350
|
ctx.beginPath()
|
|
@@ -318,7 +352,8 @@
|
|
|
318
352
|
ctx.lineTo(width - padding.right, y)
|
|
319
353
|
ctx.stroke()
|
|
320
354
|
ctx.globalAlpha = 1
|
|
321
|
-
|
|
355
|
+
const text = (Math.abs(yVal) < yStep * 1e-9 ? 0 : yVal).toFixed(yDecimals)
|
|
356
|
+
ctx.fillText(text, padding.left - 5, y)
|
|
322
357
|
}
|
|
323
358
|
ctx.setLineDash([])
|
|
324
359
|
|
package/dist/Graph/README.md
CHANGED
|
@@ -72,7 +72,8 @@
|
|
|
72
72
|
- Цвета линий по порядку - метки темы: `--blue-mark`, `--red-mark`, `--green-mark`, `--orange-mark`, `--purple-mark`, `--cyan-mark`.
|
|
73
73
|
- Точки каждой линии лежат в кольцевом буфере вне реактивности: 20 последних в режиме AUTO и 100 при заданном интервале. Перерисовка - не чаще кадра.
|
|
74
74
|
- Масштаб по Y считается по данным с запасом 10%. В живом режиме он плавно подъезжает к новому диапазону.
|
|
75
|
-
-
|
|
75
|
+
- Сетка стоит на круглых отметках. По Y шаг 1, 2, 2.5 или 5 × 10ⁿ (около шести линий), знаков после запятой - сколько у шага, левое поле растёт под самую длинную подпись. По X шаг от 0.1 с до года - самый мелкий, при котором подписи не слипаются (не ближе 50 px).
|
|
76
|
+
- Подписи по X: в живом режиме - секунды относительно текущего момента, кратные шагу (`0s`, `-5s`, при шаге меньше секунды - `-0.5s`). В статическом - время, кратное шагу в местном времени: `ЧЧ:ММ:СС` при шаге меньше минуты, иначе `ЧЧ:ММ` (с `ДД.ММ`, если ряд длиннее суток), `ДД.ММ` при шаге от суток, `ММ.ГГГГ` от месяца.
|
|
76
77
|
- Подсказка при наведении берёт ближайшую по времени точку каждой линии и рисует вертикальную линию-указатель. Значения в подсказке и в легенде округляются до двух знаков.
|
|
77
78
|
- Сетка пунктирная, цвета `--faint-color` темы, указатель под подсказкой - `--muted-color`. При смене темы график перерисовывается.
|
|
78
79
|
|
|
@@ -85,7 +85,13 @@
|
|
|
85
85
|
<UI.Input value={level.data.join(", ")} onUpdate={(value) => updateLevel(index, { data: parseNumbers(String(value)) })} />
|
|
86
86
|
<UI.Input value={(level.labels ?? []).join(", ")} onUpdate={(value) => updateLevel(index, { labels: parseList(String(value)) })} />
|
|
87
87
|
{#if levels.length > 1}
|
|
88
|
-
<UI.Button
|
|
88
|
+
<UI.Button
|
|
89
|
+
wrapperClass="w-8"
|
|
90
|
+
variant="primary"
|
|
91
|
+
accent="red"
|
|
92
|
+
content={{ icon: ButtonDelete }}
|
|
93
|
+
onClick={() => setLevels(levels.filter((_, i) => i !== index))}
|
|
94
|
+
/>
|
|
89
95
|
{:else}
|
|
90
96
|
<span></span>
|
|
91
97
|
{/if}
|
|
@@ -93,7 +93,7 @@
|
|
|
93
93
|
value={progress.accent}
|
|
94
94
|
onUpdate={(accent) => edit.updateItem("items", index, { accent: accent === progress.accent ? undefined : accent })}
|
|
95
95
|
/>
|
|
96
|
-
<UI.Button wrapperClass="w-8" content={{ icon: ButtonDelete }} onClick={() => edit.removeItem("items", index)} />
|
|
96
|
+
<UI.Button wrapperClass="w-8" variant="primary" accent="red" content={{ icon: ButtonDelete }} onClick={() => edit.removeItem("items", index)} />
|
|
97
97
|
</div>
|
|
98
98
|
{/each}
|
|
99
99
|
<div id="item-{items.length}" class="min-h-4"></div>
|
|
@@ -170,7 +170,7 @@
|
|
|
170
170
|
value={option.accent}
|
|
171
171
|
onUpdate={(accent) => edit.updateItem("options", index, { accent: accent === option.accent ? undefined : accent })}
|
|
172
172
|
/>
|
|
173
|
-
<UI.Button wrapperClass="w-8" content={{ icon: ButtonDelete }} onClick={() => edit.removeItem("options", index)} />
|
|
173
|
+
<UI.Button wrapperClass="w-8" variant="primary" accent="red" content={{ icon: ButtonDelete }} onClick={() => edit.removeItem("options", index)} />
|
|
174
174
|
</div>
|
|
175
175
|
{/each}
|
|
176
176
|
<div id="item-{options.length}" class="min-h-4"></div>
|
|
@@ -106,7 +106,7 @@
|
|
|
106
106
|
onUpdate={(value) => edit.updateItem("options", index, { disabled: value === 1 })}
|
|
107
107
|
/>
|
|
108
108
|
{#if bits.length > 1}
|
|
109
|
-
<UI.Button wrapperClass="w-8" content={{ icon: ButtonDelete }} onClick={() => edit.removeItem("options", index)} />
|
|
109
|
+
<UI.Button wrapperClass="w-8" variant="primary" accent="red" content={{ icon: ButtonDelete }} onClick={() => edit.removeItem("options", index)} />
|
|
110
110
|
{:else}
|
|
111
111
|
<span></span>
|
|
112
112
|
{/if}
|
package/dist/Table/README.md
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
|
|
7
7
|
- 📄 Показывает список строк, которые прислало устройство: одна строка на запись.
|
|
8
8
|
- 🔘 В ячейке может стоять кнопка: таблица сообщает приложению, какая кнопка нажата и в какой строке, команду отправляет приложение.
|
|
9
|
+
- ⋯ В ячейке может стоять меню действий строки (кнопка «⋯» и пункты `Dropdown`), например «Изменить» и красное «Удалить».
|
|
9
10
|
- 🔽 Можно выбрать значение из списка прямо в ячейке.
|
|
10
11
|
- 📊 Число можно показать полосой прогресса с единицами измерения.
|
|
11
12
|
- 🖼️ В ячейке может быть картинка или иконка.
|
|
@@ -64,7 +65,7 @@
|
|
|
64
65
|
- `logger` пишет новые строки сверху.
|
|
65
66
|
- `autoscroll` держит таблицу прокрученной к последней строке, пока пользователь сам не отмотал её выше. В режиме `logger` не прокручивает.
|
|
66
67
|
- `visibleRows` - сколько строк видно без прокрутки. Высоту таблица считает по первым строкам.
|
|
67
|
-
- `clearButton` добавляет кнопку очистки в узкой колонке справа (`2.5rem`), она не перекрывает заголовки. Очистку можно вызвать и из кода: `clear()`.
|
|
68
|
+
- `clearButton` добавляет красную кнопку очистки в узкой колонке справа (`2.5rem`), она не перекрывает заголовки. Очистку можно вызвать и из кода: `clear()`.
|
|
68
69
|
|
|
69
70
|
**Подгрузка.** Если задан `cursor` и передан `loader`, при прокрутке почти до конца (последние 50 px) таблица вызывает `getData`. Если строк меньше высоты таблицы, она сама зовёт `getData`, пока не заполнится. Пока `loader()` возвращает `true`, повторных вызовов нет. `cursor = null` выключает подгрузку. Без `loader` подгрузка не работает.
|
|
70
71
|
|
|
@@ -139,6 +140,7 @@
|
|
|
139
140
|
| `text` | `key`, `render(row)`, `href(row)`, `html`, `sortable`, `truncated`, `tooltip` (`true` или функция от строки), `copy`, `modal` (`true` или сниппет), `accent(row)`, `badge`, `onClick(row)` |
|
|
140
141
|
| `button` | `name`, `icon`, `title`, `class` (строки или функции от строки), `eventHandler`, `onClick(row)`. У кнопки-иконки без `name` обязательно `title`. Весь `data` может быть функцией от строки |
|
|
141
142
|
| `select` | `key` (массив вариантов в строке), `keyCol`, `onChange` |
|
|
143
|
+
| `menu` | `items(row)` - пункты `Dropdown` для строки, `icon` (по умолчанию «⋯», `IconMore`), `title`. Только из кода приложения, в конструкторе нет; удаление - пункт с `accent: "red"` |
|
|
142
144
|
| `progressBar` | `key`, `minNum`, `maxNum`, `units` |
|
|
143
145
|
| `image` | `src` (строка или функция), `alt`, `class`, `width`, `height`, `defaultIcon` |
|
|
144
146
|
|
package/dist/Table/Table.svelte
CHANGED
|
@@ -13,6 +13,8 @@
|
|
|
13
13
|
import Button from "../Button/Button.svelte"
|
|
14
14
|
import Modal from "../Modal.svelte"
|
|
15
15
|
import CopyButton from "./CopyButton.svelte"
|
|
16
|
+
import Dropdown from "../Dropdown/Dropdown.svelte"
|
|
17
|
+
import MoreIcon from "../libIcons/MoreIcon.svelte"
|
|
16
18
|
import { htmlToText, sanitizeHtml } from "../html"
|
|
17
19
|
import { createRing } from "../ring"
|
|
18
20
|
import { copyText } from "../clipboard"
|
|
@@ -114,7 +116,8 @@
|
|
|
114
116
|
const ACTIONS_COLUMN = "2.5rem"
|
|
115
117
|
/* Колонка по содержимому: width "fit" или без width с одними кнопками */
|
|
116
118
|
const isFit = (column: ITableHeader<Row>) =>
|
|
117
|
-
column.width === "fit" ||
|
|
119
|
+
column.width === "fit" ||
|
|
120
|
+
(!column.width && Array.isArray(column.content) && column.content.length > 0 && column.content.every((c) => c.type === "button" || c.type === "menu"))
|
|
118
121
|
/* Ширины колонок по содержимому в px (замер после отрисовки), ключ - номер колонки в header */
|
|
119
122
|
let fitWidths = $state<Record<number, number>>({})
|
|
120
123
|
const hasFit = $derived(header.some((c) => c.width !== "0%" && isFit(c)))
|
|
@@ -321,7 +324,7 @@
|
|
|
321
324
|
{#if dataBuffer.clearButton}
|
|
322
325
|
<div class="flex items-center justify-center tracking-normal normal-case">
|
|
323
326
|
<Button
|
|
324
|
-
componentClass={twMerge("size-7 p-1.5 text-(--
|
|
327
|
+
componentClass={twMerge("size-7 p-1.5 text-(--red-text) hover:bg-(--red-color)/10", dataBuffer.clearClass)}
|
|
325
328
|
content={{ icon: ButtonClear, info: { text: $T("common.table.clear"), side: "left" } }}
|
|
326
329
|
onClick={clear}
|
|
327
330
|
/>
|
|
@@ -385,6 +388,20 @@
|
|
|
385
388
|
{/if}
|
|
386
389
|
{$T(resolve(button.name, row) ?? "")}
|
|
387
390
|
</button>
|
|
391
|
+
{:else if content.type === "menu"}
|
|
392
|
+
<Dropdown
|
|
393
|
+
align="end"
|
|
394
|
+
button={{
|
|
395
|
+
variant: "plain",
|
|
396
|
+
wrapperClass: "w-fit shrink-0",
|
|
397
|
+
componentClass: "aspect-auto h-7 w-auto rounded-lg px-2 py-0 [&>span]:size-4",
|
|
398
|
+
content: {
|
|
399
|
+
icon: content.data.icon ?? MoreIcon,
|
|
400
|
+
info: content.data.title ? { text: $T(content.data.title), side: "left" } : undefined,
|
|
401
|
+
},
|
|
402
|
+
}}
|
|
403
|
+
items={content.data.items(row)}
|
|
404
|
+
/>
|
|
388
405
|
{:else if content.type === "select"}
|
|
389
406
|
{@const select = content.data}
|
|
390
407
|
{@const options = (Array.isArray(row[select.key]) ? row[select.key] : []) as IOption<string | number>[]}
|
|
@@ -231,6 +231,8 @@
|
|
|
231
231
|
</div>
|
|
232
232
|
<UI.Button
|
|
233
233
|
wrapperClass="w-8"
|
|
234
|
+
variant="primary"
|
|
235
|
+
accent="red"
|
|
234
236
|
content={{ icon: ButtonDelete }}
|
|
235
237
|
onClick={() => {
|
|
236
238
|
const headers = [...(component.properties.header || [])]
|
|
@@ -479,6 +481,8 @@
|
|
|
479
481
|
</div>
|
|
480
482
|
<UI.Button
|
|
481
483
|
wrapperClass="w-8 shrink-0"
|
|
484
|
+
variant="primary"
|
|
485
|
+
accent="red"
|
|
482
486
|
content={{ icon: ButtonDelete }}
|
|
483
487
|
onClick={() => {
|
|
484
488
|
const headers = [...(component.properties.header || [])]
|
|
@@ -130,7 +130,13 @@
|
|
|
130
130
|
onUpdate={(value) => edit.updateItem("items", index, { disabled: value === 1 })}
|
|
131
131
|
/>
|
|
132
132
|
{#if items.length > 1}
|
|
133
|
-
<UI.Button
|
|
133
|
+
<UI.Button
|
|
134
|
+
wrapperClass="w-8 shrink-0"
|
|
135
|
+
variant="primary"
|
|
136
|
+
accent="red"
|
|
137
|
+
content={{ icon: ButtonDelete }}
|
|
138
|
+
onClick={() => edit.removeItem("items", index)}
|
|
139
|
+
/>
|
|
134
140
|
{/if}
|
|
135
141
|
</div>
|
|
136
142
|
{/each}
|
package/dist/index.d.ts
CHANGED
|
@@ -55,6 +55,7 @@ export { default as IconDelete } from "./libIcons/ButtonDelete.svelte";
|
|
|
55
55
|
export { default as IconAdd } from "./libIcons/ButtonAdd.svelte";
|
|
56
56
|
export { default as IconDownload } from "./libIcons/ButtonDownload.svelte";
|
|
57
57
|
export { default as IconCopy } from "./libIcons/CopyIcon.svelte";
|
|
58
|
+
export { default as IconMore } from "./libIcons/MoreIcon.svelte";
|
|
58
59
|
export { default as IconInfo } from "./libIcons/InfoIcon.svelte";
|
|
59
60
|
export { default as IconError } from "./libIcons/Error.svelte";
|
|
60
61
|
export { default as IconLibrary } from "./libIcons/Library.svelte";
|
|
@@ -65,5 +66,5 @@ export { default as IconGripVerticalRight } from "./libIcons/IconGripVerticalRig
|
|
|
65
66
|
export { escapeHtml, htmlToText, sanitizeHtml } from "./html";
|
|
66
67
|
export { hintsSetting, hint, type HintParams } from "./hints";
|
|
67
68
|
export { applyDragGhost, clearDragGhost, createDropPlaceholder } from "./dragStyle";
|
|
68
|
-
export { type UIComponent, type UIComponentPropsMap, type UIType, type Position, type IUIComponentHandler, type IButtonProps, type IAccordionProps, type IInputProps, type ISelectProps, type IOption, type SelectValue, type IconSource, type ISwitchProps, type IDividerProps, type ISliderProps, type ITextFieldProps, type IProgressBarProps, type IWidgetProps, type IWidgetWiFiProps, type IWidgetWiFiConfig, type IWidgetDeviceInfoProps, type IWidgetDeviceInfoConfig, type IWidgetFileSystemProps, type IWidgetFileSystemInfo, type IWidgetFileSystemFile, type IWidgetFileSystemUpload, type IWidgetStackInfoProps, type IWidgetStackInfo, type IWidgetStackInfoHeap, type IWidgetStackInfoTask, type IWidgetRGBStripProps, type IWidgetRGBStripConfig, type IWidgetPFDProps, type IWidgetPFDData, type IWidgetPFDLimits, type IWidgetMapProps, type IWidgetMapData, type IGraphProps, type IGraphDataObject, type IGraphHistoryPoint, type IGraphHistorySeries, type ITableHeader, type ITableText, type ITableSelect, type ITableButton, type ITableProgressBar, type ITableImage, type ITableContent, type ITableProps, type ITabsProps, type IJoystickProps, type IFileAttachProps, type FileAttachValue, type IDropdownProps, type IDropdownItem, type IDropdownTriggerProps, type ICarouselProps, type IReceivingDataObject, type IVideoViewerProps, type IPeriodChartProps, type IPeriodChartLevel, } from "./types";
|
|
69
|
+
export { type UIComponent, type UIComponentPropsMap, type UIType, type Position, type IUIComponentHandler, type IButtonProps, type IAccordionProps, type IInputProps, type ISelectProps, type IOption, type SelectValue, type IconSource, type ISwitchProps, type IDividerProps, type ISliderProps, type ITextFieldProps, type IProgressBarProps, type IWidgetProps, type IWidgetWiFiProps, type IWidgetWiFiConfig, type IWidgetDeviceInfoProps, type IWidgetDeviceInfoConfig, type IWidgetFileSystemProps, type IWidgetFileSystemInfo, type IWidgetFileSystemFile, type IWidgetFileSystemUpload, type IWidgetStackInfoProps, type IWidgetStackInfo, type IWidgetStackInfoHeap, type IWidgetStackInfoTask, type IWidgetRGBStripProps, type IWidgetRGBStripConfig, type IWidgetPFDProps, type IWidgetPFDData, type IWidgetPFDLimits, type IWidgetMapProps, type IWidgetMapData, type IGraphProps, type IGraphDataObject, type IGraphHistoryPoint, type IGraphHistorySeries, type ITableHeader, type ITableText, type ITableSelect, type ITableButton, type ITableMenu, type ITableProgressBar, type ITableImage, type ITableContent, type ITableProps, type ITabsProps, type IJoystickProps, type IFileAttachProps, type FileAttachValue, type IDropdownProps, type IDropdownItem, type IDropdownTriggerProps, type ICarouselProps, type IReceivingDataObject, type IVideoViewerProps, type IPeriodChartProps, type IPeriodChartLevel, } from "./types";
|
|
69
70
|
export { ICONS, ICON_NAMES, ICONS_ARRAY } from "./icons";
|
package/dist/index.js
CHANGED
|
@@ -57,6 +57,7 @@ export { default as IconDelete } from "./libIcons/ButtonDelete.svelte";
|
|
|
57
57
|
export { default as IconAdd } from "./libIcons/ButtonAdd.svelte";
|
|
58
58
|
export { default as IconDownload } from "./libIcons/ButtonDownload.svelte";
|
|
59
59
|
export { default as IconCopy } from "./libIcons/CopyIcon.svelte";
|
|
60
|
+
export { default as IconMore } from "./libIcons/MoreIcon.svelte";
|
|
60
61
|
export { default as IconInfo } from "./libIcons/InfoIcon.svelte";
|
|
61
62
|
export { default as IconError } from "./libIcons/Error.svelte";
|
|
62
63
|
export { default as IconLibrary } from "./libIcons/Library.svelte";
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
interface $$__sveltets_2_IsomorphicComponent<Props extends Record<string, any> = any, Events extends Record<string, any> = any, Slots extends Record<string, any> = any, Exports = {}, Bindings = string> {
|
|
2
|
+
new (options: import('svelte').ComponentConstructorOptions<Props>): import('svelte').SvelteComponent<Props, Events, Slots> & {
|
|
3
|
+
$$bindings?: Bindings;
|
|
4
|
+
} & Exports;
|
|
5
|
+
(internal: unknown, props: {
|
|
6
|
+
$$events?: Events;
|
|
7
|
+
$$slots?: Slots;
|
|
8
|
+
}): Exports & {
|
|
9
|
+
$set?: any;
|
|
10
|
+
$on?: any;
|
|
11
|
+
};
|
|
12
|
+
z_$$bindings?: Bindings;
|
|
13
|
+
}
|
|
14
|
+
declare const MoreIcon: $$__sveltets_2_IsomorphicComponent<Record<string, never>, {
|
|
15
|
+
[evt: string]: CustomEvent<any>;
|
|
16
|
+
}, {}, {}, string>;
|
|
17
|
+
type MoreIcon = InstanceType<typeof MoreIcon>;
|
|
18
|
+
export default MoreIcon;
|
|
@@ -110,7 +110,8 @@
|
|
|
110
110
|
|
|
111
111
|
- `api_har.h` прошивок генерируется из `commands.yaml` командой `npm run Dictionary` (`src/lib/dictionaries/firmware/api_har.h`, вручную не править). В прошивках лежат копии словаря `.framework/Dictionary.yaml` и заголовка, сборка сверяет их между собой.
|
|
112
112
|
- Часть аргументов словаря - задел, прошивки их пока не обрабатывают: `BackUp`, `BindMKey`, `ModList`, `ModMode`, `ModT2-ModT5`, `FwUpgE`, `OrOfs`, `OrAccCal`, `OrMagCal`. Коды у них закреплены и не меняются. Такой аргумент модуль примет, но ответа не будет, поэтому в примерах берут реальные команды (`ModCfg`, `ModInfo`, `FS`).
|
|
113
|
-
-
|
|
113
|
+
- Словарь один на стек: прошивки собираются с его копией, поэтому приложения берут встроенный `DEFAULT_DICTIONARY`. Объект словаря (`createDictionary(codes)`): `code(имя)`, `name(код)`, `header(код)`, `har(заголовок, команда, ответ)`.
|
|
114
|
+
- Команду, которой нет в словаре, задают числом: `code` и `har` принимают код строкой, десятичный или HEX (`"4097"`, `"0x1001"`), а `name` для неизвестного кода возвращает его же числом строкой, так что запись «туда и обратно» сходится.
|
|
114
115
|
- Такой словарь принимают `encodeHar`, `decodeHar`, `encodeWsEnvelope`, `decodeWsEnvelope`, `encodeXPoeDebugFrame` (последний аргумент), `createXPoeDebugParser({ dictionary })` и связь `GUIRenderer` (поле `dictionary`). Без него берётся встроенный.
|
|
115
116
|
|
|
116
117
|
</details>
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { DEFAULT_ARGUMENT_CODES } from "../dictionaries/generated/commands.js";
|
|
2
2
|
export { DEFAULT_ARGUMENT_CODES };
|
|
3
3
|
export declare const HEADER_CODES: Record<string, number>;
|
|
4
|
-
export declare const parseArgumentDictionary: (text: string) => Record<string, number>;
|
|
5
4
|
export interface Dictionary {
|
|
6
5
|
code(name: string): number | undefined;
|
|
7
6
|
name(code: number): string;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/* Словарь заголовков и аргументов протокола - заголовок и аргумент поля HAR (makeHar/splitHar) на шине и в WebSocket-конверте {HAR, VAL}. Аргументы по умолчанию - из мастер-словаря команд src/lib/dictionaries/commands.yaml (единственный источник; .framework/Dictionary.yaml прошивок - его справочные копии), DEFAULT_ARGUMENT_CODES генерируется из него (dictionaries/generated/commands.ts, npm run Dictionary)
|
|
1
|
+
/* Словарь заголовков и аргументов протокола - заголовок и аргумент поля HAR (makeHar/splitHar) на шине и в WebSocket-конверте {HAR, VAL}. Аргументы по умолчанию - из мастер-словаря команд src/lib/dictionaries/commands.yaml (единственный источник; .framework/Dictionary.yaml прошивок - его справочные копии), DEFAULT_ARGUMENT_CODES генерируется из него (dictionaries/generated/commands.ts, npm run Dictionary): прошивки собираются с его копией, поэтому приложения берут только встроенный словарь; аргумент, которого в словаре нет, задаётся числом (кодом) */
|
|
2
2
|
import { DEFAULT_ARGUMENT_CODES } from "../dictionaries/generated/commands.js";
|
|
3
3
|
import { makeHar, splitHar } from "./packet.js";
|
|
4
4
|
export { DEFAULT_ARGUMENT_CODES };
|
|
@@ -9,8 +9,8 @@ export const HEADER_CODES = {
|
|
|
9
9
|
"ER!": 3,
|
|
10
10
|
};
|
|
11
11
|
const HEADER_NAMES = Object.keys(HEADER_CODES);
|
|
12
|
-
/*
|
|
13
|
-
|
|
12
|
+
/* Аргумент числом, если его нет в словаре: десятичный «4097» или HEX «0x1001»; иначе undefined */
|
|
13
|
+
const numericArgument = (text) => /^\d+$/.test(text) ? Number(text) : /^0[xX][0-9A-Fa-f]+$/.test(text) ? parseInt(text, 16) : undefined;
|
|
14
14
|
/* Словарь аргументов устройства с обратным поиском; при повторе кода имя берётся первое */
|
|
15
15
|
export const createDictionary = (codes) => {
|
|
16
16
|
const byName = new Map(Object.entries(codes));
|
|
@@ -19,12 +19,12 @@ export const createDictionary = (codes) => {
|
|
|
19
19
|
if (!byCode.has(code))
|
|
20
20
|
byCode.set(code, name);
|
|
21
21
|
return {
|
|
22
|
-
code: (name) => byName.get(name),
|
|
22
|
+
code: (name) => byName.get(name) ?? numericArgument(name.trim()),
|
|
23
23
|
name: (code) => byCode.get(code) ?? String(code),
|
|
24
24
|
header: (code) => HEADER_NAMES[code] ?? String(code),
|
|
25
25
|
har(header, argument, reply = true) {
|
|
26
26
|
const hdr = HEADER_NAMES.indexOf(header);
|
|
27
|
-
const arg = typeof argument === "number" ? argument : byName.get(argument);
|
|
27
|
+
const arg = typeof argument === "number" ? argument : (byName.get(argument) ?? numericArgument(argument.trim()));
|
|
28
28
|
if (hdr < 0 || arg === undefined)
|
|
29
29
|
throw new Error(`Hdr/Arg отсутствует в словаре: ${header} ${argument}`);
|
|
30
30
|
return makeHar(hdr, arg, reply);
|
|
@@ -8,6 +8,6 @@ export { createPlotGroups, debugPlotValues, DEBUG_PLOT_ARGUMENT, type PlotPoint
|
|
|
8
8
|
export { encodeXPoeDebugFrame, createXPoeDebugParser, xPoeDebugValueFromText, xPoeDebugRow, DEBUG_LOG_ARGUMENT, type XPoeDebugItem, type XPoeDebugRow, } from "./xPoeDebug.js";
|
|
9
9
|
export { formatXPoeDebugValue, formatXPoeDebugPretty, xPoeDebugMessage } from "./xPoeDebugView.js";
|
|
10
10
|
export { CAN_FINAL_BIT, CAN_PACKET_ID_MASK, canFragments, encodeSlcanFrame, encodeCanPacket, createCanParser, slcanOpenCommands, type CanFrame, type CanMessage, } from "./can.js";
|
|
11
|
-
export { HEADER_CODES, DEFAULT_ARGUMENT_CODES, DEFAULT_DICTIONARY,
|
|
11
|
+
export { HEADER_CODES, DEFAULT_ARGUMENT_CODES, DEFAULT_DICTIONARY, createDictionary, encodeHar, decodeHar, type Dictionary, type HarParts, } from "./dictionary.js";
|
|
12
12
|
export { encodeWsEnvelope, decodeWsEnvelope, type WsEnvelope, type WsMessage } from "./wsEnvelope.js";
|
|
13
13
|
export { formatDeviceMessage, parseDebugLogMessage, DEVICE_MESSAGES, MESSAGE_CODES, MESSAGE_GROUPS, type DeviceMessage, type DeviceMessageEntry, type DeviceMessageGroup, type DeviceMessageLevel, type FormattedDeviceMessage, } from "./messages.js";
|
package/dist/protocols/index.js
CHANGED
|
@@ -17,7 +17,7 @@ export { formatXPoeDebugValue, formatXPoeDebugPretty, xPoeDebugMessage } from ".
|
|
|
17
17
|
/* CAN/CAN FD через slcan-адаптер: нарезка пакета на кадры как в can_service прошивки, кадры slcan, потоковый разбор со сборкой фрагментов */
|
|
18
18
|
export { CAN_FINAL_BIT, CAN_PACKET_ID_MASK, canFragments, encodeSlcanFrame, encodeCanPacket, createCanParser, slcanOpenCommands, } from "./can.js";
|
|
19
19
|
/* Словарь заголовков и аргументов HAR - по умолчанию из мастер-словаря команд dictionaries/commands.yaml библиотеки (устройства и облако), разбор файла словаря, словарь устройства с обратным поиском; HAR из слов и обратно */
|
|
20
|
-
export { HEADER_CODES, DEFAULT_ARGUMENT_CODES, DEFAULT_DICTIONARY,
|
|
20
|
+
export { HEADER_CODES, DEFAULT_ARGUMENT_CODES, DEFAULT_DICTIONARY, createDictionary, encodeHar, decodeHar, } from "./dictionary.js";
|
|
21
21
|
/* Конверт WebSocket {HAR, VAL} на всех соединениях: сборка из заголовка и аргумента (имя или код), разбор в слова по словарю */
|
|
22
22
|
export { encodeWsEnvelope, decodeWsEnvelope } from "./wsEnvelope.js";
|
|
23
23
|
/* Сообщения устройств: Message - код из мастер-словаря dictionaries/messages.yaml (коды по группам MESSAGE_GROUPS), Args - параметры; текст на языке, уровень и группа */
|
package/dist/types.d.ts
CHANGED
|
@@ -451,9 +451,17 @@ export interface ITableImage<T extends object> {
|
|
|
451
451
|
height?: string;
|
|
452
452
|
defaultIcon?: ConstructorOfATypedSvelteComponent | string;
|
|
453
453
|
}
|
|
454
|
+
export interface ITableMenu<T extends object> {
|
|
455
|
+
icon?: IconSource;
|
|
456
|
+
title?: string;
|
|
457
|
+
items: (row: T) => IDropdownItem[];
|
|
458
|
+
}
|
|
454
459
|
export type ITableContent<T extends object> = {
|
|
455
460
|
type: "text";
|
|
456
461
|
data: ITableText<T>;
|
|
462
|
+
} | {
|
|
463
|
+
type: "menu";
|
|
464
|
+
data: ITableMenu<T>;
|
|
457
465
|
} | {
|
|
458
466
|
type: "select";
|
|
459
467
|
data: ITableSelect<T>;
|