poe-svelte-ui-lib 1.109.0 → 1.111.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/README.md +2 -2
  2. package/dist/Accordion/AccordionProps.svelte +0 -1
  3. package/dist/Button/ButtonProps.svelte +0 -1
  4. package/dist/CommonSnippets.svelte +1 -1
  5. package/dist/Divider/DividerProps.svelte +0 -1
  6. package/dist/FileAttach/FileAttachProps.svelte +0 -1
  7. package/dist/Graph/Graph.svelte +0 -1
  8. package/dist/Input/Input.svelte +4 -12
  9. package/dist/Joystick/Joystick.svelte +1 -12
  10. package/dist/Modal.README.md +1 -1
  11. package/dist/ProgressBar/ProgressBar.svelte +1 -7
  12. package/dist/Slider/Slider.svelte +3 -9
  13. package/dist/Switch/SwitchProps.svelte +0 -1
  14. package/dist/Table/Table.svelte +1 -13
  15. package/dist/Table/TableProps.svelte +0 -3
  16. package/dist/Table/columnWidth.js +0 -1
  17. package/dist/Tabs/README.md +1 -1
  18. package/dist/Tabs/Tabs.svelte +4 -1
  19. package/dist/TextField/TextField.svelte +1 -1
  20. package/dist/Widget/Widget.svelte +1 -7
  21. package/dist/WidgetMap/README.md +5 -5
  22. package/dist/WidgetMap/mapWrapper/MapLibre.svelte +1 -1
  23. package/dist/WidgetMap/mapWrapper/contexts.svelte.d.ts +1 -33
  24. package/dist/WidgetMap/mapWrapper/contexts.svelte.js +21 -109
  25. package/dist/WidgetMap/mapWrapper/index.d.ts +1 -1
  26. package/dist/WidgetMap/mapWrapper/index.js +1 -1
  27. package/dist/WidgetMap/mission/coverage.d.ts +0 -1
  28. package/dist/WidgetMap/mission/coverage.js +0 -1
  29. package/dist/WidgetMap/mission/route.d.ts +0 -1
  30. package/dist/WidgetMap/mission/route.js +1 -3
  31. package/dist/bitField.js +0 -1
  32. package/dist/hints.d.ts +0 -1
  33. package/dist/hints.js +1 -2
  34. package/dist/html.js +15 -8
  35. package/dist/index.d.ts +3 -6
  36. package/dist/index.js +3 -6
  37. package/dist/locales/index.d.ts +1 -1
  38. package/dist/locales/index.js +1 -2
  39. package/dist/locales/languages.js +0 -1
  40. package/dist/locales/localize.js +0 -1
  41. package/dist/locales/translations.js +0 -1
  42. package/dist/number.d.ts +1 -0
  43. package/dist/number.js +11 -0
  44. package/dist/options.js +0 -1
  45. package/dist/protocols/PROTOCOL.md +14 -10
  46. package/dist/protocols/can.js +42 -28
  47. package/dist/protocols/cbor/decoder.d.ts +2 -1
  48. package/dist/protocols/cbor/decoder.js +6 -1
  49. package/dist/protocols/cbor/types.d.ts +0 -3
  50. package/dist/protocols/cbor/types.js +0 -6
  51. package/dist/protocols/crc.js +0 -1
  52. package/dist/protocols/dictionary.d.ts +10 -2
  53. package/dist/protocols/dictionary.js +27 -5
  54. package/dist/protocols/framer.d.ts +10 -0
  55. package/dist/protocols/framer.js +39 -0
  56. package/dist/protocols/hex.d.ts +2 -0
  57. package/dist/protocols/hex.js +9 -0
  58. package/dist/protocols/index.d.ts +1 -1
  59. package/dist/protocols/index.js +2 -3
  60. package/dist/protocols/packet.d.ts +4 -6
  61. package/dist/protocols/packet.js +29 -36
  62. package/dist/protocols/plotGroups.js +0 -1
  63. package/dist/protocols/xPoeDebug.d.ts +9 -5
  64. package/dist/protocols/xPoeDebug.js +41 -67
  65. package/dist/protocols/xPoeDebugView.d.ts +1 -1
  66. package/dist/protocols/xPoeDebugView.js +15 -32
  67. package/dist/theme.css +0 -2
  68. package/dist/widgetAccent.js +1 -1
  69. package/package.json +2 -2
  70. package/dist/libIcons/ButtonRemove.svelte +0 -10
  71. package/dist/libIcons/ButtonRemove.svelte.d.ts +0 -18
  72. package/dist/libIcons/LoaderRotate.svelte +0 -9
  73. package/dist/libIcons/LoaderRotate.svelte.d.ts +0 -18
package/README.md CHANGED
@@ -203,10 +203,10 @@ export const T = createTranslator(translations)
203
203
  ```bash
204
204
  npm run dev # витрина на локальном сервере
205
205
  npm run check # проверка типов
206
- npm run TestProtocols # тесты протоколов и битовых полей
206
+ npm run TestProtocols # тесты: протоколы, битовые поля, очистка HTML, облёт поля
207
207
  npm run Formatting # prettier
208
208
  npm run build # сборка витрины в docs/
209
- npm pack # сборка пакета в dist/ с проверками
209
+ npm pack # сборка пакета в dist/: проверка типов, тесты, publint
210
210
  ```
211
211
 
212
212
  Витрина устроена как конструктор DevCloud: слева компонент и его код, справа панель свойств той же ширины, что в облаке. Если подпись не влезает, это видно сразу.
@@ -1,4 +1,3 @@
1
- <!-- $lib/ElementsUI/AccordionProps.svelte -->
2
1
  <script lang="ts">
3
2
  import { T } from "../locales/i18n"
4
3
  import { findOptionByClass, updateProperty, type IAccordionProps, type IUIComponentHandler, type UIComponent } from "../types"
@@ -1,4 +1,3 @@
1
- <!-- $lib/ElementsUI/ButtonProps.svelte -->
2
1
  <script lang="ts">
3
2
  import TextsEditor from "../TextsEditor.svelte"
4
3
  import { localizeText } from "../locales/localize"
@@ -55,7 +55,7 @@
55
55
  onUpdate={(value) => {
56
56
  updateProperty("id", (value as UI.IOption).value as string, component, onPropertyChange)
57
57
  onPropertyChange({
58
- /* \u041f\u043e\u0434\u043f\u0438\u0441\u044c \u043f\u0435\u0440\u0435\u043c\u0435\u043d\u043d\u043e\u0439 \u0438\u0437 \u043e\u0431\u043b\u0430\u043a\u0430 \u00ab<id> - <\u0438\u043c\u044f>\u00bb: \u0438\u043c\u044f - \u0432\u0441\u0451 \u043f\u043e\u0441\u043b\u0435 \u043f\u0435\u0440\u0432\u043e\u0433\u043e \u0440\u0430\u0437\u0434\u0435\u043b\u0438\u0442\u0435\u043b\u044f; \u043f\u0440\u0438\u043d\u0438\u043c\u0430\u0435\u0442\u0441\u044f \u0438 \u0434\u043b\u0438\u043d\u043d\u043e\u0435 \u0442\u0438\u0440\u0435 (\u2014) \u0441\u0442\u0430\u0440\u044b\u0445 \u043f\u043e\u0434\u043f\u0438\u0441\u0435\u0439 */
58
+ /* Подпись переменной из облака «<id> - <имя>»: имя - всё после первого разделителя; принимается и длинное тире U+2014 старых подписей */
59
59
  name: (value as UI.IOption).name?.match(/\s[\u2014-]\s(.*)/)?.[1]?.trim(),
60
60
  eventHandler: { Variables: [(value as UI.IOption).value as string] },
61
61
  })
@@ -1,4 +1,3 @@
1
- <!-- $lib/ElementsUI/DividerProps.svelte -->
2
1
  <script lang="ts">
3
2
  import { T } from "../locales/i18n"
4
3
  import { updateProperty, type IDividerProps, type IUIComponentHandler, type UIComponent } from "../types"
@@ -1,4 +1,3 @@
1
- <!-- $lib/ElementsUI/ButtonProps.svelte -->
2
1
  <script lang="ts">
3
2
  import { T } from "../locales/i18n"
4
3
  import { type IFileAttachProps, type IUIComponentHandler, type UIComponent, updateProperty, findOptionByClass } from "../types"
@@ -1,4 +1,3 @@
1
- <!-- $lib/ElementsUI/Graph.svelte -->
2
1
  <script module lang="ts">
3
2
  import type { IOption } from "../types"
4
3
 
@@ -1,5 +1,6 @@
1
1
  <!-- $lib/Input/Input.svelte - радиус 10, высота 32 (h-8), выравнивание по левому краю, кольцо фокуса. -->
2
2
  <script lang="ts">
3
+ import { roundToClean } from "../number"
3
4
  import { T } from "../locales/i18n"
4
5
  import type { IInputProps } from "../types"
5
6
  import { twMerge } from "tailwind-merge"
@@ -62,18 +63,9 @@
62
63
  }
63
64
 
64
65
  $effect(() => {
65
- if (type === "number" && typeof value == "number") value = roundToClean(value)
66
+ if (type === "number" && typeof value == "number") value = roundToClean(value, 5)
66
67
  })
67
68
 
68
- const roundToClean = (num: number): number => {
69
- if (Number.isInteger(num)) return num
70
- for (const digits of [1, 2, 3, 4, 5]) {
71
- const rounded = Number(num.toFixed(digits))
72
- if (Math.abs(rounded - num) < 1e-10) return rounded
73
- }
74
- return Number(num.toFixed(5))
75
- }
76
-
77
69
  /* Мастер-цвет поля (bg-* в componentClass): рамка и лёгкий фон цветом роли; сам класс bg-* в поле не передаётся, иначе он срезает фон */
78
70
  const hasRole = $derived(!!itemAccentStyle(componentClass))
79
71
  const fieldClass = $derived(
@@ -216,7 +208,7 @@
216
208
  onUpdate(value as number)
217
209
  return
218
210
  }
219
- value = roundToClean(Number(value) + (number.step ?? 1))
211
+ value = roundToClean(Number(value) + (number.step ?? 1), 5)
220
212
  onUpdate(value as number)
221
213
  }}
222
214
  aria-label={$T("ui.increase")}>▲</button
@@ -231,7 +223,7 @@
231
223
  onUpdate(value as number)
232
224
  return
233
225
  }
234
- value = roundToClean(Number(value) - (number.step ?? 1))
226
+ value = roundToClean(Number(value) - (number.step ?? 1), 5)
235
227
  onUpdate(value as number)
236
228
  }}
237
229
  aria-label={$T("ui.decrease")}>▼</button
@@ -1,4 +1,5 @@
1
1
  <script lang="ts">
2
+ import { roundToClean } from "../number"
2
3
  import { sanitizeHtml } from "../html"
3
4
  import { twMerge } from "tailwind-merge"
4
5
  import { widgetAccentStyle } from "../widgetAccent"
@@ -124,18 +125,6 @@
124
125
 
125
126
  let clipPos = Math.cos(Math.PI / directions.length) * 100
126
127
  let angle = 360 / directions.length
127
-
128
- const roundToClean = (num: number): number => {
129
- if (Number.isInteger(num)) return num
130
-
131
- const rounded1 = Number(num.toFixed(1))
132
- if (Math.abs(rounded1 - num) < 1e-10) return rounded1
133
-
134
- const rounded2 = Number(num.toFixed(2))
135
- if (Math.abs(rounded2 - num) < 1e-10) return rounded2
136
-
137
- return rounded2
138
- }
139
128
  </script>
140
129
 
141
130
  <div
@@ -49,7 +49,7 @@
49
49
 
50
50
  ## Стек окон
51
51
 
52
- Какие окна открыты и в каком порядке, хранит `ModalStack` (`src/lib/ModalStackStore.ts`). Это store со списком id открытых окон:
52
+ Какие окна открыты и в каком порядке, хранит внутренний `ModalStack` (`src/lib/ModalStackStore.ts`, наружу не экспортируется). Это store со списком id открытых окон:
53
53
 
54
54
  ```ts
55
55
  ModalStack.subscribe // список id в порядке открытия
@@ -1,5 +1,6 @@
1
1
  <!-- $lib/ProgressBar/ProgressBar.svelte - полоса 6px, подпись и значение над ней -->
2
2
  <script lang="ts">
3
+ import { roundToClean } from "../number"
3
4
  import { twMerge } from "tailwind-merge"
4
5
  import { itemAccentStyle } from "../widgetAccent"
5
6
  import type { IProgressBarProps, IReceivingDataObject } from "../types"
@@ -55,13 +56,6 @@
55
56
  if (value) return (((Math.min(Math.max(value, min), max) - min) / (max - min)) * 100) as number
56
57
  return 0
57
58
  }
58
-
59
- const roundToClean = (num: number): number => {
60
- if (Number.isInteger(num)) return num
61
- const rounded1 = Number(num.toFixed(1))
62
- if (Math.abs(rounded1 - num) < 1e-10) return rounded1
63
- return Number(num.toFixed(2))
64
- }
65
59
  </script>
66
60
 
67
61
  <div
@@ -1,5 +1,6 @@
1
1
  <!-- $lib/Slider/Slider.svelte - дорожка 4px, ползунок 18px; в диапазонном режиме оба <input> на всю ширину с одинаковыми min/max наложены друг на друга, события ловит только ::thumb, клик по пустой дорожке ползунок не двигает -->
2
2
  <script lang="ts">
3
+ import { roundToClean } from "../number"
3
4
  import { T } from "../locales/i18n"
4
5
  import type { ISliderProps } from "../types"
5
6
  import { twMerge } from "tailwind-merge"
@@ -7,7 +8,7 @@
7
8
 
8
9
  let {
9
10
  id = crypto.randomUUID(),
10
- /* Было "bg-blue" - декоративная заливка. Цвет заливки дорожки берётся из --bg-color, который задаётся классом bg-* в вызове; без него используется акцент. */
11
+ /* Цвет заливки дорожки берётся из --bg-color, который задаётся классом bg-* в вызове; без него используется акцент */
11
12
  wrapperClass = "",
12
13
  label = { name: "", class: "" },
13
14
  type = "single",
@@ -76,15 +77,8 @@
76
77
  }
77
78
  })
78
79
 
79
- const roundToClean = (num: number): number => {
80
- if (Number.isInteger(num)) return num
81
- const rounded1 = Number(num.toFixed(1))
82
- if (Math.abs(rounded1 - num) < 1e-10) return rounded1
83
- return Number(num.toFixed(2))
84
- }
85
-
86
80
  /* Единые классы для нативного ползунка: высота input РАВНА высоте thumb (18px) - тогда центрирование по вертикали отдаётся обычному flexbox родителя (items-center), без ручного margin-top на ::-webkit-slider-thumb. Такой margin-top пришлось бы подбирать под конкретную высоту трека, и он даёт разный результат в Chromium и Safari/WebKit - при равных высотах input и thumb смещения нет по определению, это работает одинаково везде. */
87
- /* Бегунок: было border-(--hairline-color) (почти прозрачная линия) + мягкая тень - на светлом фоне белый кружок буквально сливался с дорожкой. Рамка в 2px цветом заливки даёт чёткий, "премиальный" контур вместо почти невидимой линии. */
81
+ /* Бегунок: рамка 2px цветом заливки, чтобы белый кружок не сливался с дорожкой на светлом фоне */
88
82
  const THUMB = `w-full appearance-none bg-transparent h-[18px]
89
83
  [&::-webkit-slider-runnable-track]:h-[18px] [&::-webkit-slider-runnable-track]:bg-transparent
90
84
  [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:size-[18px]
@@ -62,7 +62,6 @@
62
62
  onChange={(value) => {
63
63
  updateProperty("bitMode", value === 1, component, onPropertyChange)
64
64
  updateProperty("value", 0, component, onPropertyChange)
65
- // if (!component.properties.bitMode) updateProperty("value", 0, component, onPropertyChange)
66
65
  }}
67
66
  />
68
67
  {/snippet}
@@ -1,5 +1,5 @@
1
- <!-- $lib/ElementsUI/Table.svelte -->
2
1
  <script lang="ts">
2
+ import { roundToClean } from "../number"
3
3
  import type { IOption, ITableButton, ITableContent, ITableHeader, ITableImage, ITableProgressBar, ITableProps, ITableText } from "../types"
4
4
  import { fly, slide } from "svelte/transition"
5
5
  import { twMerge } from "tailwind-merge"
@@ -190,18 +190,6 @@
190
190
  if (value != null && !isNaN(value)) return (((Math.min(Math.max(value, min), max) - min) / (max - min)) * 100) as number
191
191
  }
192
192
 
193
- const roundToClean = (num: number): number => {
194
- if (Number.isInteger(num)) return num
195
-
196
- const rounded1 = Number(num.toFixed(1))
197
- if (Math.abs(rounded1 - num) < 1e-10) return rounded1
198
-
199
- const rounded2 = Number(num.toFixed(2))
200
- if (Math.abs(rounded2 - num) < 1e-10) return rounded2
201
-
202
- return rounded2
203
- }
204
-
205
193
  $effect(() => {
206
194
  if (!container) return () => (buffer = [])
207
195
  const observer = new ResizeObserver(measureScrollbar)
@@ -156,7 +156,6 @@
156
156
  }
157
157
  const headers = [...(component.properties.header || []), newColumn]
158
158
  updateProperty("header", headers, component, onPropertyChange)
159
- // updateTableBody()
160
159
  }}
161
160
  />
162
161
  {/snippet}
@@ -308,7 +307,6 @@
308
307
  i == index ? { ...textItem, data: { ...textItem.data, key: value } } : textItem,
309
308
  ),
310
309
  )
311
- // updateTableBody()
312
310
  }}
313
311
  />
314
312
  <UI.Input
@@ -408,7 +406,6 @@
408
406
  i == index ? { ...textItem, data: { ...textItem.data, key: value } } : textItem,
409
407
  ),
410
408
  )
411
- // updateTableBody()
412
409
  }}
413
410
  />
414
411
  <UI.Input
@@ -1,3 +1,2 @@
1
- /* $lib/Table/columnWidth.ts */
2
1
  /* Ширина колонки моноширинного текста таблицы в символах: растёт вместе с --table-font-size (знак моноширинного шрифта - 0.6-0.62em, берётся 0.64 с запасом), не уже подписи шапки (11px, заглавные, ~0.5rem на знак); 1.5rem - внутренние отступы ячейки, 1px - разделитель колонок */
3
2
  export const tableMonoWidth = (chars, labelChars = 0) => `max(calc(var(--table-font-size, 13px) * ${+(chars * 0.64).toFixed(2)} + 1.5rem + 1px), calc(${labelChars * 0.5}rem + 1.5rem + 1px))`;
@@ -43,7 +43,7 @@
43
43
 
44
44
  Содержимое можно передать тремя способами (если переданы несколько, работает первый по списку):
45
45
 
46
- 1. список компонентов `apiArray` и сниппет `Components`, который их рисует. Так делают конструктор и превью интерфейса. На вкладке показываются компоненты, у которых `id` оканчивается номером этой вкладки (с нуля);
46
+ 1. список компонентов `apiArray` и сниппет `Components`, который их рисует. Так делают конструктор и превью интерфейса. На вкладке показываются компоненты, у которых `id` оканчивается номером этой вкладки (с нуля). У id из конструктора (UUID без первого символа, 35 знаков, + номер) номер берётся после 35-го знака, поэтому цифра в конце UUID не мешает;
47
47
  2. общий сниппет `children`, он получает текущую вкладку;
48
48
  3. сниппет у каждой вкладки `items[].children`.
49
49
 
@@ -20,6 +20,9 @@
20
20
  }: ITabsProps = $props()
21
21
 
22
22
  const isCol = $derived(!!items.find((item) => item.class?.startsWith("flex-col")))
23
+
24
+ /* Номер вкладки дочернего компонента. Конструктор даёт id = UUID без первого символа (35 знаков) + номер вкладки: берём всё после 35-го знака, иначе цифра в конце UUID приклеилась бы к номеру. Прочие id - число в конце */
25
+ const tabOfComponent = (componentId: string) => (/^[0-9a-f-]{35}\d+$/i.test(componentId) ? componentId.slice(35) : componentId.match(/(\d+)$/)?.[1])
23
26
  </script>
24
27
 
25
28
  <div id={`${id}-${crypto.randomUUID().slice(0, 6)}`} class="h-full w-full" style={widgetAccentStyle(wrapperClass)}>
@@ -73,7 +76,7 @@
73
76
  style="grid-template-columns: repeat({size.width || 1}, minmax(0, 1fr)); grid-template-rows: repeat({size.height || 1}, auto);"
74
77
  >
75
78
  {#if Components}
76
- {#each (apiArray ?? []).filter((c) => c.id.match(/(\d+)$/)?.[1] === `${activeTab}`) as comp}
79
+ {#each (apiArray ?? []).filter((c) => tabOfComponent(c.id) === `${activeTab}`) as comp}
77
80
  {@render Components(comp, false)}
78
81
  {/each}
79
82
  {:else if children}
@@ -11,7 +11,7 @@
11
11
  content = { name: "", class: "", size: "base" },
12
12
  }: ITextFieldProps = $props()
13
13
 
14
- /* Было: text-sm / text-base / text-2xl / text-4xl / text-5xl - вне шкалы. Стало: 13 / 15 / 24 / 34 / 44 с весом и трекингом по роли. */
14
+ /* Размеры по шкале темы: 13 / 15 / 24 / 34 / 44 с весом и трекингом по роли */
15
15
  const textSize = {
16
16
  small: "text-[13px] leading-[1.45] text-(--muted-color)",
17
17
  base: "text-[15px] leading-[1.5]",
@@ -1,5 +1,6 @@
1
1
  <!-- $lib/Widget/Widget.svelte - карточка значения: шапка фиксированной высоты и гибкое тело, кнопки ± 32px, дорожка слайдера 4px -->
2
2
  <script lang="ts">
3
+ import { roundToClean } from "../number"
3
4
  import { sanitizeHtml } from "../html"
4
5
  import { T } from "../locales/i18n"
5
6
  import type { IWidgetProps } from "../types"
@@ -94,13 +95,6 @@
94
95
  : "auto",
95
96
  )
96
97
 
97
- const roundToClean = (num: number): number => {
98
- if (Number.isInteger(num)) return num
99
- const rounded1 = Number(num.toFixed(1))
100
- if (Math.abs(rounded1 - num) < 1e-10) return rounded1
101
- return Number(num.toFixed(2))
102
- }
103
-
104
98
  const pct = $derived(() => {
105
99
  const lo = settings.number?.minNum ?? 0
106
100
  const hi = settings.number?.maxNum ?? 10
@@ -512,7 +512,7 @@ Telemetry_SendObject(g_telemetry_stream, g_mcfg.DevSN, "Data", dev, sizeof(dev)
512
512
  <details>
513
513
  <summary>🔬 Как устроено</summary>
514
514
 
515
- `toMission` / `toWaypointsFile`, формат QGC WPL 110: строки `seq, current, frame, command, p1-p4, lat, lon, alt, autocontinue` через табуляцию.
515
+ `toMission`, формат QGC WPL 110: строки `seq, current, frame, command, p1-p4, lat, lon, alt, autocontinue` через табуляцию.
516
516
 
517
517
  | Команда | Код | frame | Параметры |
518
518
  | ------------------------------ | --- | ----------- | ------------------------------------------------------------------------------------------- |
@@ -546,14 +546,14 @@ Telemetry_SendObject(g_telemetry_stream, g_mcfg.DevSN, "Data", dev, sizeof(dev)
546
546
  | Площадь | `coverage.ts`: `fieldArea`, `fieldsArea` |
547
547
  | Быстрая оценка угла | `coverage.ts`: `estimateAngleCost`, `optimizeAngle`, `bestFieldAngle` |
548
548
  | Точный подбор угла | `coverage.ts`: `searchFieldAngle` |
549
- | Миссия QGC WPL 110 | `coverage.ts`: `toMission`, `toWaypointsFile` |
549
+ | Миссия QGC WPL 110 | `coverage.ts`: `toMission` |
550
550
  | Прогресс по телеметрии | `progress.ts` |
551
551
  | Интерфейс, итоги, подбор | `MapAgro.svelte` |
552
552
 
553
- Расчёт можно вызвать и без карты. Из библиотеки экспортируются:
553
+ Расчёт внутренний, наружу экспортируются только план и его типы, чтобы хранить его у себя:
554
554
 
555
- - режим «Агро»: `planFields` (несколько полей), `planCoverage` (одно поле), `optimizeAngle`, `bestFieldAngle`, `toWaypointsFile`, `fieldArea`, `fieldsArea`, `DEFAULT_MISSION_PLAN`, типы `IMissionPlan`, `IMissionField`, `LngLat`, `SprayControl`, `ICoverageResult`;
556
- - режим «Маршрут»: `routeStats`, `routeToWaypointsFile`, `DEFAULT_ROUTE_PLAN`, типы `IRoutePlan`, `IRouteWaypoint`.
555
+ - режим «Агро»: `DEFAULT_MISSION_PLAN`, типы `IMissionPlan`, `IMissionField`, `LngLat`, `SprayControl`;
556
+ - режим «Маршрут»: `DEFAULT_ROUTE_PLAN`, типы `IRoutePlan`, `IRouteWaypoint`.
557
557
 
558
558
  </details>
559
559
 
@@ -67,7 +67,7 @@
67
67
  mapCtx.map = map
68
68
  }
69
69
 
70
- // Инициализация карты
70
+ /* Инициализация карты */
71
71
  $effect(createMap)
72
72
 
73
73
  $effect(() => {
@@ -1,55 +1,23 @@
1
- import type { Map as MapLibre, Marker, AddLayerObject, SourceSpecification, CanvasSourceSpecification, StyleSpecification, SkySpecification, TerrainSpecification, ProjectionSpecification, LightSpecification } from "maplibre-gl";
1
+ import type { Map as MapLibre, Marker, AddLayerObject, SourceSpecification, CanvasSourceSpecification, StyleSpecification } from "maplibre-gl";
2
2
  import type * as maplibregl from "maplibre-gl";
3
3
  declare class MapContext {
4
- /** Map instance */
5
4
  _map: MapLibre | null;
6
- /** Callbacks to be called when the map style is loaded */
7
5
  private _listener?;
8
6
  private _pending;
9
- /** Names of layers dynamically added */
10
7
  userLayers: Set<string>;
11
- /** Names of sources dynamically added */
12
8
  userSources: Set<string>;
13
- /** Terrain specification of the current base style */
14
- baseTerrain?: TerrainSpecification | undefined;
15
- /** Sky specification set by user */
16
- userTerrain?: TerrainSpecification | undefined;
17
- /** Sky specification of the current base style */
18
- baseSky?: SkySpecification | undefined;
19
- /** Sky specification set by user */
20
- userSky?: SkySpecification | undefined;
21
- /** Light specification of the current base style */
22
- baseLight?: LightSpecification | undefined;
23
- /** Light specification set by user */
24
- userLight?: LightSpecification | undefined;
25
- /** Projection specification of the current base style */
26
- baseProjection?: ProjectionSpecification | undefined;
27
- /** Projection specification set by user */
28
- userProjection?: ProjectionSpecification | undefined;
29
9
  get map(): maplibregl.Map | null;
30
10
  set map(value: maplibregl.Map | null);
31
11
  addLayer(addLayerObject: AddLayerObject, beforeId?: string): void;
32
12
  removeLayer(id: string): void;
33
13
  addSource(id: string, source: SourceSpecification | CanvasSourceSpecification): void;
34
14
  removeSource(id: string): void;
35
- /** Wait for the style to be loaded before calling the function */
36
15
  waitForStyleLoaded(func: (map: maplibregl.Map) => void): void;
37
16
  private _onstyledata;
38
17
  setStyle(style: string | StyleSpecification | null): void;
39
18
  }
40
19
  export declare function prepareMapContext(): MapContext;
41
20
  export declare function getMapContext(): MapContext;
42
- declare class SourceContext {
43
- /** sourceId */
44
- id: string;
45
- }
46
- export declare function prepareSourceContext(): SourceContext;
47
- export declare function getSourceContext(): SourceContext;
48
- declare class LayerContext {
49
- id: string;
50
- }
51
- export declare function prepareLayerContext(): LayerContext;
52
- export declare function getLayerContext(): LayerContext | null;
53
21
  declare class MarkerContext {
54
22
  marker: Marker | null;
55
23
  }
@@ -1,35 +1,13 @@
1
1
  import { setContext, getContext } from "svelte";
2
2
  const MAP_CONTEXT_KEY = Symbol("MapLibre map context");
3
- const SOURCE_CONTEXT_KEY = Symbol("MapLibre source context");
4
- const LAYER_CONTEXT_KEY = Symbol("MapLibre layer context");
5
3
  const MARKER_CONTEXT_KEY = Symbol("MapLibre marker context");
6
- // https://svelte.dev/docs/svelte/$state#Classes
4
+ /* Карта и её пользовательские источники и слои: переживают смену базового стиля, до загрузки стиля добавление ждёт в очереди */
7
5
  class MapContext {
8
- /** Map instance */
9
6
  _map = $state.raw(null);
10
- /** Callbacks to be called when the map style is loaded */
11
7
  _listener = undefined;
12
8
  _pending = [];
13
- /** Names of layers dynamically added */
14
9
  userLayers = new Set();
15
- /** Names of sources dynamically added */
16
10
  userSources = new Set();
17
- /** Terrain specification of the current base style */
18
- baseTerrain;
19
- /** Sky specification set by user */
20
- userTerrain;
21
- /** Sky specification of the current base style */
22
- baseSky;
23
- /** Sky specification set by user */
24
- userSky;
25
- /** Light specification of the current base style */
26
- baseLight;
27
- /** Light specification set by user */
28
- userLight;
29
- /** Projection specification of the current base style */
30
- baseProjection;
31
- /** Projection specification set by user */
32
- userProjection;
33
11
  get map() {
34
12
  return this._map;
35
13
  }
@@ -48,87 +26,55 @@ class MapContext {
48
26
  if (!this.map)
49
27
  throw new Error("Map is not initialized");
50
28
  this.userLayers.add(addLayerObject.id);
51
- this.waitForStyleLoaded((map) => {
52
- map.addLayer(addLayerObject, beforeId);
53
- });
29
+ this.waitForStyleLoaded((map) => map.addLayer(addLayerObject, beforeId));
54
30
  }
55
31
  removeLayer(id) {
56
32
  if (!this.map)
57
33
  throw new Error("Map is not initialized");
58
34
  this.userLayers.delete(id);
59
- this.waitForStyleLoaded((map) => {
60
- map.removeLayer(id);
61
- });
35
+ this.waitForStyleLoaded((map) => map.removeLayer(id));
62
36
  }
63
37
  addSource(id, source) {
64
38
  this.userSources.add(id);
65
- this.waitForStyleLoaded((map) => {
66
- map.addSource(id, source);
67
- });
39
+ this.waitForStyleLoaded((map) => map.addSource(id, source));
68
40
  }
69
41
  removeSource(id) {
70
42
  this.userSources.delete(id);
71
- this.waitForStyleLoaded((map) => {
72
- map.removeSource(id);
73
- });
43
+ this.waitForStyleLoaded((map) => map.removeSource(id));
74
44
  }
75
- /** Wait for the style to be loaded before calling the function */
45
+ /* Вызов сразу, если стиль загружен, иначе после загрузки */
76
46
  waitForStyleLoaded(func) {
77
- if (!this.map) {
47
+ if (!this.map)
78
48
  return;
79
- }
80
- if (this.map.style._loaded) {
81
- // style is already loaded
49
+ if (this.map.style._loaded)
82
50
  func(this.map);
83
- }
84
- else {
85
- // we need to wait the style to be loaded
51
+ else
86
52
  this._pending.push(func);
87
- }
88
53
  }
89
54
  _onstyledata(ev) {
90
55
  const map = ev.target;
91
- if (map?.style._loaded) {
92
- for (const func of this._pending) {
93
- // call pending tasks
94
- func(map);
95
- }
96
- this._pending = [];
97
- }
56
+ if (!map?.style._loaded)
57
+ return;
58
+ for (const func of this._pending)
59
+ func(map);
60
+ this._pending = [];
98
61
  }
62
+ /* Смена базового стиля с переносом пользовательских источников и слоёв */
99
63
  setStyle(style) {
100
- const { userSources: addedSources, userLayers: addedLayers } = this;
64
+ const { userSources, userLayers } = this;
101
65
  if (!style) {
102
66
  this.map?.setStyle(null);
103
67
  return;
104
68
  }
105
69
  this.map?.setStyle($state.snapshot(style), {
106
- // Preserves user styles when the base style changes
107
70
  transformStyle: (previous, next) => {
108
- this.baseLight = next.light;
109
- this.baseProjection = next.projection;
110
- this.baseSky = next.sky;
111
- this.baseTerrain = next.terrain;
112
- if (!previous) {
71
+ if (!previous)
113
72
  return next;
114
- }
115
73
  const sources = next.sources;
116
- for (const [key, value] of Object.entries(previous.sources)) {
117
- if (addedSources.has(key)) {
74
+ for (const [key, value] of Object.entries(previous.sources))
75
+ if (userSources.has(key))
118
76
  sources[key] = value;
119
- }
120
- }
121
- const userLayers = previous.layers.filter((layer) => addedLayers.has(layer.id));
122
- const layers = [...next.layers, ...userLayers];
123
- return {
124
- ...next,
125
- light: this.userLight || this.baseLight,
126
- projection: this.userProjection || this.baseProjection,
127
- sky: this.userSky || this.baseSky,
128
- terrain: this.userTerrain || this.baseTerrain,
129
- sources,
130
- layers,
131
- };
77
+ return { ...next, sources, layers: [...next.layers, ...previous.layers.filter((layer) => userLayers.has(layer.id))] };
132
78
  },
133
79
  });
134
80
  }
@@ -144,36 +90,6 @@ export function getMapContext() {
144
90
  throw new Error("Map context not found");
145
91
  return mapCtx;
146
92
  }
147
- // https://svelte.dev/docs/svelte/$state#Classes
148
- class SourceContext {
149
- /** sourceId */
150
- id = $state("");
151
- }
152
- export function prepareSourceContext() {
153
- const sourceCtx = new SourceContext();
154
- setContext(SOURCE_CONTEXT_KEY, sourceCtx);
155
- return sourceCtx;
156
- }
157
- export function getSourceContext() {
158
- const sourceCtx = getContext(SOURCE_CONTEXT_KEY);
159
- if (!sourceCtx || !sourceCtx.id)
160
- throw new Error("Source context not found");
161
- return sourceCtx;
162
- }
163
- class LayerContext {
164
- id = $state("");
165
- }
166
- export function prepareLayerContext() {
167
- const layerCtx = new LayerContext();
168
- setContext(LAYER_CONTEXT_KEY, layerCtx);
169
- return layerCtx;
170
- }
171
- export function getLayerContext() {
172
- const layerCtx = getContext(LAYER_CONTEXT_KEY);
173
- if (!layerCtx || !layerCtx.id)
174
- throw new Error("Layer context not found");
175
- return layerCtx;
176
- }
177
93
  class MarkerContext {
178
94
  marker = $state.raw(null);
179
95
  }
@@ -183,9 +99,5 @@ export function prepareMarkerContext() {
183
99
  return markerCtx;
184
100
  }
185
101
  export function getMarkerContext() {
186
- const markerCtx = getContext(MARKER_CONTEXT_KEY);
187
- if (!markerCtx) {
188
- return null;
189
- }
190
- return markerCtx;
102
+ return getContext(MARKER_CONTEXT_KEY) ?? null;
191
103
  }
@@ -7,4 +7,4 @@ export { default as Marker } from "./Marker.svelte";
7
7
  export { default as Popup } from "./Popup.svelte";
8
8
  export { default as Line } from "./Line.svelte";
9
9
  export { default as CustomControl } from "./controls/CustomControl.svelte";
10
- export { getMapContext, getSourceContext, getMarkerContext } from "./contexts.svelte.js";
10
+ export { getMapContext } from "./contexts.svelte.js";
@@ -7,4 +7,4 @@ export { default as Marker } from "./Marker.svelte";
7
7
  export { default as Popup } from "./Popup.svelte";
8
8
  export { default as Line } from "./Line.svelte";
9
9
  export { default as CustomControl } from "./controls/CustomControl.svelte";
10
- export { getMapContext, getSourceContext, getMarkerContext } from "./contexts.svelte.js";
10
+ export { getMapContext } from "./contexts.svelte.js";
@@ -57,7 +57,6 @@ export interface IMissionExport {
57
57
  };
58
58
  returnHome?: boolean;
59
59
  }
60
- export declare const toWaypointsFile: (res: ICoverageResult, home: LngLat, opt: IMissionExport) => string;
61
60
  export declare const toMission: (res: ICoverageResult, home: LngLat, opt: IMissionExport) => {
62
61
  text: string;
63
62
  nav: {
@@ -903,7 +903,6 @@ export const searchFieldAngle = async (contour, holes, spacing, margin, speed, o
903
903
  onProgress?.(1);
904
904
  return best;
905
905
  };
906
- export const toWaypointsFile = (res, home, opt) => toMission(res, home, opt).text;
907
906
  /* Миссия и номера команд её точек маршрута: по ним прогресс считается из WPNum телеметрии */
908
907
  export const toMission = (res, home, opt) => {
909
908
  const lines = ["QGC WPL 110"];