@1337exp/taoux 0.0.0-stage → 0.1.1

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 (94) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/LICENSE +21 -0
  3. package/README.md +137 -2
  4. package/README.ru.md +140 -0
  5. package/dist/camera.d.ts +22 -0
  6. package/dist/camera.js +38 -0
  7. package/dist/camera.js.map +1 -0
  8. package/dist/canvas/TaoxCanvas.vue.d.ts +37 -0
  9. package/dist/canvas/host.d.ts +138 -0
  10. package/dist/canvas/index.d.ts +3 -0
  11. package/dist/canvas/useCanvasGestures.d.ts +44 -0
  12. package/dist/canvas.css +55 -0
  13. package/dist/canvas.js +696 -0
  14. package/dist/canvas.js.map +1 -0
  15. package/dist/chunks/curveeditor-F3XBWHPL.js +759 -0
  16. package/dist/chunks/curveeditor-F3XBWHPL.js.map +1 -0
  17. package/dist/curve.d.ts +53 -0
  18. package/dist/curve.js +81 -0
  19. package/dist/curve.js.map +1 -0
  20. package/dist/curveeditor/TaoxCurveEditor.vue.d.ts +74 -0
  21. package/dist/curveeditor/index.d.ts +3 -0
  22. package/dist/curveeditor/ops.d.ts +63 -0
  23. package/dist/curveeditor.css +115 -0
  24. package/dist/curveeditor.js +1 -0
  25. package/dist/curvefield/TaoxCurveField.vue.d.ts +64 -0
  26. package/dist/curvefield/index.d.ts +2 -0
  27. package/dist/curvefield/labels.d.ts +13 -0
  28. package/dist/curvefield.css +57 -0
  29. package/dist/curvefield.js +252 -0
  30. package/dist/curvefield.js.map +1 -0
  31. package/dist/ease.d.ts +62 -0
  32. package/dist/ease.js +157 -0
  33. package/dist/ease.js.map +1 -0
  34. package/dist/edgescroll.d.ts +77 -0
  35. package/dist/edgescroll.js +78 -0
  36. package/dist/edgescroll.js.map +1 -0
  37. package/dist/file.d.ts +10 -0
  38. package/dist/file.js +22 -0
  39. package/dist/file.js.map +1 -0
  40. package/dist/gestures.d.ts +174 -0
  41. package/dist/gestures.js +229 -0
  42. package/dist/gestures.js.map +1 -0
  43. package/dist/gradienteditor/TaoxGradientEditor.vue.d.ts +48 -0
  44. package/dist/gradienteditor/index.d.ts +2 -0
  45. package/dist/gradienteditor/ops.d.ts +83 -0
  46. package/dist/gradienteditor.css +81 -0
  47. package/dist/gradienteditor.js +337 -0
  48. package/dist/gradienteditor.js.map +1 -0
  49. package/dist/history.d.ts +42 -0
  50. package/dist/history.js +89 -0
  51. package/dist/history.js.map +1 -0
  52. package/dist/i18n.d.ts +51 -0
  53. package/dist/i18n.js +102 -0
  54. package/dist/i18n.js.map +1 -0
  55. package/dist/ids.d.ts +5 -0
  56. package/dist/ids.js +17 -0
  57. package/dist/ids.js.map +1 -0
  58. package/dist/links/TaoxLinks.vue.d.ts +14 -0
  59. package/dist/links/index.d.ts +2 -0
  60. package/dist/links/types.d.ts +37 -0
  61. package/dist/links.css +80 -0
  62. package/dist/links.js +72 -0
  63. package/dist/links.js.map +1 -0
  64. package/dist/num.d.ts +35 -0
  65. package/dist/num.js +60 -0
  66. package/dist/num.js.map +1 -0
  67. package/dist/palette.d.ts +34 -0
  68. package/dist/palette.js +41 -0
  69. package/dist/palette.js.map +1 -0
  70. package/dist/pins.d.ts +66 -0
  71. package/dist/pins.js +83 -0
  72. package/dist/pins.js.map +1 -0
  73. package/dist/playback/core.d.ts +81 -0
  74. package/dist/playback/index.d.ts +2 -0
  75. package/dist/playback/use.d.ts +38 -0
  76. package/dist/playback.js +199 -0
  77. package/dist/playback.js.map +1 -0
  78. package/dist/session.d.ts +125 -0
  79. package/dist/session.js +195 -0
  80. package/dist/session.js.map +1 -0
  81. package/dist/snap.d.ts +24 -0
  82. package/dist/snap.js +34 -0
  83. package/dist/snap.js.map +1 -0
  84. package/dist/storage.d.ts +16 -0
  85. package/dist/storage.js +30 -0
  86. package/dist/storage.js.map +1 -0
  87. package/dist/touch.d.ts +9 -0
  88. package/dist/touch.js +20 -0
  89. package/dist/touch.js.map +1 -0
  90. package/dist/wheel.d.ts +31 -0
  91. package/dist/wheel.js +47 -0
  92. package/dist/wheel.js.map +1 -0
  93. package/package.json +183 -4
  94. package/theme/taoui.css +43 -0
package/dist/i18n.js ADDED
@@ -0,0 +1,102 @@
1
+ import { computed, ref } from "vue";
2
+ //#region src/i18n.ts
3
+ function lookup(dict, path) {
4
+ let cur = dict;
5
+ for (const part of path.split(".")) {
6
+ if (cur === null || typeof cur !== "object") return void 0;
7
+ cur = cur[part];
8
+ }
9
+ return typeof cur === "string" ? cur : void 0;
10
+ }
11
+ /**
12
+ * Typed i18n on object dictionaries. Texts and language codes belong to the app,
13
+ * only the mechanics are here: translation with `{0}` arguments, a fallback language, language choice and remembering it.
14
+ * Типизированный i18n на словарях-объектах. Тексты и коды языков принадлежат приложению,
15
+ * здесь только механика: перевод с `{0}`-аргументами, запасной язык, выбор языка и его запоминание.
16
+ *
17
+ * `K` is the type of allowed keys. By default it is all dictionary paths; narrow it if the dictionary has
18
+ * branches that are not translated through `t()` (for example, node texts).
19
+ * `K` — тип допустимых ключей. По умолчанию это все пути словарей; сузьте, если в словаре есть
20
+ * ветки, которые не переводятся через `t()` (например, тексты нод).
21
+ */
22
+ function createI18n(options) {
23
+ const { locales, fallback, storageKey } = options;
24
+ const codes = Object.keys(locales);
25
+ const current = ref(fallback);
26
+ function isLocaleCode(value) {
27
+ return typeof value === "string" && codes.includes(value);
28
+ }
29
+ /**
30
+ * The first browser language we support ('ru-RU' → 'ru'); otherwise the fallback.
31
+ * Первый из языков браузера, который мы поддерживаем ('ru-RU' → 'ru'); иначе запасной.
32
+ */
33
+ function detectLocale(languages) {
34
+ for (const tag of languages) {
35
+ const base = tag.toLowerCase().split(/[-_]/)[0];
36
+ if (isLocaleCode(base)) return base;
37
+ }
38
+ return fallback;
39
+ }
40
+ /**
41
+ * Apply the interface language: every `t()` in templates re-renders, `<html lang>` is updated.
42
+ * Применить язык интерфейса: все `t()` в шаблонах перерисуются, `<html lang>` обновится.
43
+ */
44
+ function applyLocale(code) {
45
+ current.value = code;
46
+ if (typeof document !== "undefined") document.documentElement.lang = code;
47
+ }
48
+ /**
49
+ * Apply the language and remember the user's choice.
50
+ * Применить язык и запомнить выбор пользователя.
51
+ */
52
+ function setLocale(code) {
53
+ applyLocale(code);
54
+ try {
55
+ localStorage.setItem(storageKey, code);
56
+ } catch {}
57
+ }
58
+ /**
59
+ * The language at start: the saved choice, else the browser language, else the fallback.
60
+ * Язык при старте: сохранённый выбор, иначе язык браузера, иначе запасной.
61
+ */
62
+ function initLocale() {
63
+ let saved = null;
64
+ try {
65
+ saved = localStorage.getItem(storageKey);
66
+ } catch {}
67
+ const code = isLocaleCode(saved) ? saved : detectLocale(typeof navigator === "undefined" ? [] : navigator.languages);
68
+ applyLocale(code);
69
+ return code;
70
+ }
71
+ /**
72
+ * Translation without reactivity: for places where the language is known explicitly (and in tests).
73
+ * Перевод без реактивности: нужен там, где язык известен явно (и в тестах).
74
+ */
75
+ function translate(code, key, args = []) {
76
+ return (lookup(locales[code], key) ?? lookup(locales[fallback], key) ?? key).replace(/\{(\d+)\}/g, (match, index) => {
77
+ const value = args[Number(index)];
78
+ return value === void 0 ? match : String(value);
79
+ });
80
+ }
81
+ function useI18n() {
82
+ return {
83
+ locale: computed(() => current.value),
84
+ t: (key, args) => translate(current.value, key, args)
85
+ };
86
+ }
87
+ return {
88
+ codes,
89
+ current,
90
+ isLocaleCode,
91
+ detectLocale,
92
+ applyLocale,
93
+ setLocale,
94
+ initLocale,
95
+ translate,
96
+ useI18n
97
+ };
98
+ }
99
+ //#endregion
100
+ export { createI18n };
101
+
102
+ //# sourceMappingURL=i18n.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"i18n.js","names":[],"sources":["../src/i18n.ts"],"sourcesContent":["import { computed, ref, type ComputedRef, type Ref } from 'vue';\r\n\r\n/**\r\n * All dot-separated paths to dictionary strings: 'file.save', 'link.arrow', ...\r\n * Все пути до строк словаря через точку: 'file.save', 'link.arrow', ...\r\n */\r\nexport type Paths<T, P extends string = ''> = {\r\n [K in keyof T & string]: T[K] extends string ? `${P}${K}` : Paths<T[K], `${P}${K}.`>;\r\n}[keyof T & string];\r\n\r\nexport type MessageArgs = readonly (string | number)[];\r\n\r\nexport interface I18nOptions<L extends Record<string, object>> {\r\n /**\r\n * Dictionaries by language code. The other dictionaries must repeat the structure of any one of them.\r\n * Словари по кодам языков. Остальные словари должны повторять структуру любого из них.\r\n */\r\n locales: L;\r\n /**\r\n * The language to fall back to when the key is missing in the chosen one.\r\n * Язык, на который падаем, если ключа нет в выбранном.\r\n */\r\n fallback: keyof L & string;\r\n /**\r\n * The localStorage key for the user's choice.\r\n * Ключ localStorage для выбора пользователя.\r\n */\r\n storageKey: string;\r\n}\r\n\r\nfunction lookup(dict: unknown, path: string): string | undefined {\r\n let cur: unknown = dict;\r\n for (const part of path.split('.')) {\r\n if (cur === null || typeof cur !== 'object') return undefined;\r\n cur = (cur as Record<string, unknown>)[part];\r\n }\r\n return typeof cur === 'string' ? cur : undefined;\r\n}\r\n\r\n/**\r\n * Typed i18n on object dictionaries. Texts and language codes belong to the app,\r\n * only the mechanics are here: translation with `{0}` arguments, a fallback language, language choice and remembering it.\r\n * Типизированный i18n на словарях-объектах. Тексты и коды языков принадлежат приложению,\r\n * здесь только механика: перевод с `{0}`-аргументами, запасной язык, выбор языка и его запоминание.\r\n *\r\n * `K` is the type of allowed keys. By default it is all dictionary paths; narrow it if the dictionary has\r\n * branches that are not translated through `t()` (for example, node texts).\r\n * `K` — тип допустимых ключей. По умолчанию это все пути словарей; сузьте, если в словаре есть\r\n * ветки, которые не переводятся через `t()` (например, тексты нод).\r\n */\r\nexport function createI18n<L extends Record<string, object>, K extends string = Paths<L[keyof L & string]>>(\r\n options: I18nOptions<L>,\r\n) {\r\n type Code = keyof L & string;\r\n\r\n const { locales, fallback, storageKey } = options;\r\n const codes = Object.keys(locales) as Code[];\r\n // An explicit Ref<Code>: on a generic type ref() would unwrap it to any in the declarations.\r\n // Явный Ref<Code>: на обобщённом типе ref() размотал бы его до any в декларациях.\r\n const current = ref(fallback) as Ref<Code>;\r\n\r\n function isLocaleCode(value: unknown): value is Code {\r\n return typeof value === 'string' && (codes as readonly string[]).includes(value);\r\n }\r\n\r\n /**\r\n * The first browser language we support ('ru-RU' → 'ru'); otherwise the fallback.\r\n * Первый из языков браузера, который мы поддерживаем ('ru-RU' → 'ru'); иначе запасной.\r\n */\r\n function detectLocale(languages: readonly string[]): Code {\r\n for (const tag of languages) {\r\n const base = tag.toLowerCase().split(/[-_]/)[0];\r\n if (isLocaleCode(base)) return base;\r\n }\r\n return fallback;\r\n }\r\n\r\n /**\r\n * Apply the interface language: every `t()` in templates re-renders, `<html lang>` is updated.\r\n * Применить язык интерфейса: все `t()` в шаблонах перерисуются, `<html lang>` обновится.\r\n */\r\n function applyLocale(code: Code): void {\r\n current.value = code;\r\n if (typeof document !== 'undefined') document.documentElement.lang = code;\r\n }\r\n\r\n /**\r\n * Apply the language and remember the user's choice.\r\n * Применить язык и запомнить выбор пользователя.\r\n */\r\n function setLocale(code: Code): void {\r\n applyLocale(code);\r\n try {\r\n localStorage.setItem(storageKey, code);\r\n } catch {\r\n // private mode or storage is blocked: the language is simply not remembered\r\n // приватный режим или запрет хранилища: язык просто не запомнится\r\n }\r\n }\r\n\r\n /**\r\n * The language at start: the saved choice, else the browser language, else the fallback.\r\n * Язык при старте: сохранённый выбор, иначе язык браузера, иначе запасной.\r\n */\r\n function initLocale(): Code {\r\n let saved: string | null = null;\r\n try {\r\n saved = localStorage.getItem(storageKey);\r\n } catch {\r\n // see setLocale\r\n // см. setLocale\r\n }\r\n\r\n const code = isLocaleCode(saved)\r\n ? saved\r\n : detectLocale(typeof navigator === 'undefined' ? [] : navigator.languages);\r\n applyLocale(code);\r\n return code;\r\n }\r\n\r\n /**\r\n * Translation without reactivity: for places where the language is known explicitly (and in tests).\r\n * Перевод без реактивности: нужен там, где язык известен явно (и в тестах).\r\n */\r\n function translate(code: Code, key: K, args: MessageArgs = []): string {\r\n // the fallback: the fallback language, then the key itself (so that a gap is visible)\r\n // запасной вариант: запасной язык, затем сам ключ (чтобы пропуск было видно)\r\n const template = lookup(locales[code], key) ?? lookup(locales[fallback], key) ?? key;\r\n return template.replace(/\\{(\\d+)\\}/g, (match, index: string) => {\r\n const value = args[Number(index)];\r\n return value === undefined ? match : String(value);\r\n });\r\n }\r\n\r\n function useI18n(): { locale: ComputedRef<Code>; t: (key: K, args?: MessageArgs) => string } {\r\n return {\r\n locale: computed(() => current.value),\r\n // reads current.value inside, so the template re-renders when the language changes\r\n // читает current.value внутри, поэтому шаблон перерисуется при смене языка\r\n t: (key: K, args?: MessageArgs) => translate(current.value, key, args),\r\n };\r\n }\r\n\r\n return {\r\n codes,\r\n current,\r\n isLocaleCode,\r\n detectLocale,\r\n applyLocale,\r\n setLocale,\r\n initLocale,\r\n translate,\r\n useI18n,\r\n };\r\n}\r\n"],"mappings":";;AA8BA,SAAS,OAAO,MAAe,MAAkC;CAC7D,IAAI,MAAe;CACnB,KAAK,MAAM,QAAQ,KAAK,MAAM,GAAG,GAAG;EAChC,IAAI,QAAQ,QAAQ,OAAO,QAAQ,UAAU,OAAO,KAAA;EACpD,MAAO,IAAgC;CAC3C;CACA,OAAO,OAAO,QAAQ,WAAW,MAAM,KAAA;AAC3C;;;;;;;;;;;;AAaA,SAAgB,WACZ,SACF;CAGE,MAAM,EAAE,SAAS,UAAU,eAAe;CAC1C,MAAM,QAAQ,OAAO,KAAK,OAAO;CAGjC,MAAM,UAAU,IAAI,QAAQ;CAE5B,SAAS,aAAa,OAA+B;EACjD,OAAO,OAAO,UAAU,YAAa,MAA4B,SAAS,KAAK;CACnF;;;;;CAMA,SAAS,aAAa,WAAoC;EACtD,KAAK,MAAM,OAAO,WAAW;GACzB,MAAM,OAAO,IAAI,YAAY,CAAC,CAAC,MAAM,MAAM,CAAC,CAAC;GAC7C,IAAI,aAAa,IAAI,GAAG,OAAO;EACnC;EACA,OAAO;CACX;;;;;CAMA,SAAS,YAAY,MAAkB;EACnC,QAAQ,QAAQ;EAChB,IAAI,OAAO,aAAa,aAAa,SAAS,gBAAgB,OAAO;CACzE;;;;;CAMA,SAAS,UAAU,MAAkB;EACjC,YAAY,IAAI;EAChB,IAAI;GACA,aAAa,QAAQ,YAAY,IAAI;EACzC,QAAQ,CAGR;CACJ;;;;;CAMA,SAAS,aAAmB;EACxB,IAAI,QAAuB;EAC3B,IAAI;GACA,QAAQ,aAAa,QAAQ,UAAU;EAC3C,QAAQ,CAGR;EAEA,MAAM,OAAO,aAAa,KAAK,IACzB,QACA,aAAa,OAAO,cAAc,cAAc,CAAC,IAAI,UAAU,SAAS;EAC9E,YAAY,IAAI;EAChB,OAAO;CACX;;;;;CAMA,SAAS,UAAU,MAAY,KAAQ,OAAoB,CAAC,GAAW;EAInE,QADiB,OAAO,QAAQ,OAAO,GAAG,KAAK,OAAO,QAAQ,WAAW,GAAG,KAAK,IAAA,CACjE,QAAQ,eAAe,OAAO,UAAkB;GAC5D,MAAM,QAAQ,KAAK,OAAO,KAAK;GAC/B,OAAO,UAAU,KAAA,IAAY,QAAQ,OAAO,KAAK;EACrD,CAAC;CACL;CAEA,SAAS,UAAoF;EACzF,OAAO;GACH,QAAQ,eAAe,QAAQ,KAAK;GAGpC,IAAI,KAAQ,SAAuB,UAAU,QAAQ,OAAO,KAAK,IAAI;EACzE;CACJ;CAEA,OAAO;EACH;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACJ;AACJ"}
package/dist/ids.d.ts ADDED
@@ -0,0 +1,5 @@
1
+ /**
2
+ * A unique id with a prefix; `taken` lets you skip ids already in use (for example, loaded from a file).
3
+ * Уникальный id с префиксом; `taken` позволяет пропустить уже занятые (например, загруженные из файла).
4
+ */
5
+ export declare function uid(prefix: string, taken?: (id: string) => boolean): string;
package/dist/ids.js ADDED
@@ -0,0 +1,17 @@
1
+ //#region src/ids.ts
2
+ var counter = 0;
3
+ /**
4
+ * A unique id with a prefix; `taken` lets you skip ids already in use (for example, loaded from a file).
5
+ * Уникальный id с префиксом; `taken` позволяет пропустить уже занятые (например, загруженные из файла).
6
+ */
7
+ function uid(prefix, taken = () => false) {
8
+ let id;
9
+ do
10
+ id = `${prefix}${++counter}`;
11
+ while (taken(id));
12
+ return id;
13
+ }
14
+ //#endregion
15
+ export { uid };
16
+
17
+ //# sourceMappingURL=ids.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ids.js","names":[],"sources":["../src/ids.ts"],"sourcesContent":["let counter = 0;\n\n/**\n * A unique id with a prefix; `taken` lets you skip ids already in use (for example, loaded from a file).\n * Уникальный id с префиксом; `taken` позволяет пропустить уже занятые (например, загруженные из файла).\n */\nexport function uid(prefix: string, taken: (id: string) => boolean = () => false): string {\n let id: string;\n do id = `${prefix}${++counter}`;\n while (taken(id));\n return id;\n}\n"],"mappings":";AAAA,IAAI,UAAU;;;;;AAMd,SAAgB,IAAI,QAAgB,cAAuC,OAAe;CACtF,IAAI;CACJ;EAAG,KAAK,GAAG,SAAS,EAAE;QACf,MAAM,EAAE;CACf,OAAO;AACX"}
@@ -0,0 +1,14 @@
1
+ import type { LinkLine, LinkPreview } from './types';
2
+ type __VLS_Props = {
3
+ lines: readonly LinkLine[];
4
+ selectedId?: string | null;
5
+ preview?: LinkPreview | null;
6
+ /**
7
+ * Highlight the hovered and selected link with a blurred glow.
8
+ * Подсвечивать наведённую и выбранную связь размытым свечением.
9
+ */
10
+ glow?: boolean;
11
+ };
12
+ declare const __VLS_export: import("vue").DefineComponent<__VLS_Props, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").PublicProps, Readonly<__VLS_Props> & Readonly<{}>, {}, {}, {}, {}, string, import("vue").ComponentProvideOptions, false, {}, any>;
13
+ declare const _default: typeof __VLS_export;
14
+ export default _default;
@@ -0,0 +1,2 @@
1
+ export { default as TaoxLinks } from './TaoxLinks.vue';
2
+ export type { LinkLine, LinkPreview } from './types';
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Ready-made link geometry. Paths are built by the app (see `curve`): the canvas does not know how pins are laid out.
3
+ * Готовая геометрия связи. Пути строит приложение (см. `curve`): холст не знает, как устроены пины.
4
+ */
5
+ export interface LinkLine {
6
+ /**
7
+ * Goes into `data-conn-id`: that is how the canvas knows which link was clicked.
8
+ * Попадает в `data-conn-id`: по нему холст понимает, по какой связи кликнули.
9
+ */
10
+ id: string;
11
+ /**
12
+ * The line path (the SVG `d` attribute).
13
+ * Путь линии (атрибут `d` SVG).
14
+ */
15
+ d: string;
16
+ /**
17
+ * The path of the filled arrowhead; none means no arrow.
18
+ * Путь залитого наконечника стрелки; нет — стрелки нет.
19
+ */
20
+ head?: string | null;
21
+ /**
22
+ * The colour of this link (any CSS colour). Without it `--tx-link-color` is used.
23
+ * Цвет этой связи (любой CSS-цвет). Без него берётся `--tx-link-color`.
24
+ */
25
+ color?: string;
26
+ }
27
+ /**
28
+ * The link the user is dragging out right now.
29
+ * Связь, которую пользователь протягивает сейчас.
30
+ */
31
+ export interface LinkPreview extends LinkLine {
32
+ /**
33
+ * The target is not allowed: the line turns red.
34
+ * Цель недопустима: линия краснеет.
35
+ */
36
+ invalid?: boolean;
37
+ }
package/dist/links.css ADDED
@@ -0,0 +1,80 @@
1
+
2
+ /*
3
+ * Configured with CSS variables on any ancestor:
4
+ * Настройка через CSS-переменные на любом предке:
5
+ * --tx-link-color, --tx-link-hover-color, --tx-link-selected-color, --tx-link-preview-color, --tx-link-invalid-color,
6
+ * --tx-link-width, --tx-link-width-active, --tx-link-hit, --tx-link-hit-coarse, --tx-link-glow (opacity of the glow).
7
+ * --tx-link-width, --tx-link-width-active, --tx-link-hit, --tx-link-hit-coarse, --tx-link-glow (непрозрачность свечения).
8
+ */
9
+ .tx-links {
10
+ position: absolute;
11
+ top: 0;
12
+ left: 0;
13
+ overflow: visible;
14
+ pointer-events: none;
15
+ }
16
+ .tx-links path {
17
+ fill: none;
18
+ stroke-linecap: round;
19
+ /* thickness in screen pixels, independent of zoom / толщина в экранных пикселях, не зависит от зума */
20
+ vector-effect: non-scaling-stroke;
21
+ }
22
+ .tx-link {
23
+ --tx-link-now: var(--tx-link-line-color, var(--tx-link-color, #9ca3af));
24
+ }
25
+
26
+ /* A link without its own colour turns the hover colour on hover. An own colour stays on hover (it gets thicker and glows). / Своего цвета у связи нет: наведение красит её в hover-цвет. Свой цвет при наведении остаётся (утолщается и светится). */
27
+ .tx-link:hover {
28
+ --tx-link-now: var(--tx-link-line-color, var(--tx-link-hover-color, #fff));
29
+ }
30
+ .tx-link.selected {
31
+ --tx-link-now: var(--tx-link-selected-color, #f59e0b);
32
+ }
33
+ .tx-link-line {
34
+ stroke: var(--tx-link-now);
35
+ stroke-width: var(--tx-link-width, 2);
36
+ pointer-events: none;
37
+ }
38
+ .tx-link:hover .tx-link-line,
39
+ .tx-link.selected .tx-link-line {
40
+ stroke-width: var(--tx-link-width-active, 3);
41
+ }
42
+ .tx-link-head {
43
+ fill: var(--tx-link-now);
44
+ stroke: none;
45
+ pointer-events: none;
46
+ }
47
+ .tx-link-glow {
48
+ stroke: var(--tx-link-now);
49
+ stroke-width: 9;
50
+ opacity: 0;
51
+ filter: blur(3px);
52
+ pointer-events: none;
53
+ }
54
+ .tx-link:hover .tx-link-glow,
55
+ .tx-link.selected .tx-link-glow {
56
+ opacity: var(--tx-link-glow, 0.35);
57
+ }
58
+ .tx-link-hit {
59
+ stroke: transparent;
60
+ stroke-width: var(--tx-link-hit, 14);
61
+ pointer-events: stroke;
62
+ cursor: pointer;
63
+ }
64
+
65
+ /* A finger is thicker than a cursor: the hit area of a link is wider. / Палец толще курсора: зона попадания по связи шире. */
66
+ @media (pointer: coarse) {
67
+ .tx-link-hit {
68
+ stroke-width: var(--tx-link-hit-coarse, 30);
69
+ }
70
+ }
71
+ .tx-link-preview {
72
+ --tx-link-now: var(--tx-link-line-color, var(--tx-link-preview-color, #f59e0b));
73
+ opacity: 0.85;
74
+ }
75
+ .tx-link-preview .tx-link-line {
76
+ stroke-dasharray: 6 4;
77
+ }
78
+ .tx-link-preview.invalid {
79
+ --tx-link-now: var(--tx-link-invalid-color, #ef4444);
80
+ }
package/dist/links.js ADDED
@@ -0,0 +1,72 @@
1
+ import { Fragment, createCommentVNode, createElementBlock, createElementVNode, defineComponent, normalizeClass, normalizeStyle, openBlock, renderList } from "vue";
2
+ //#region src/links/TaoxLinks.vue?vue&type=script&setup=true&lang.ts
3
+ var _hoisted_1 = {
4
+ class: "tx-links",
5
+ width: "1",
6
+ height: "1"
7
+ };
8
+ var _hoisted_2 = ["data-conn-id"];
9
+ var _hoisted_3 = ["d"];
10
+ var _hoisted_4 = ["d"];
11
+ var _hoisted_5 = ["d"];
12
+ var _hoisted_6 = ["d"];
13
+ var _hoisted_7 = ["d"];
14
+ var _hoisted_8 = ["d"];
15
+ //#endregion
16
+ //#region src/links/TaoxLinks.vue
17
+ var TaoxLinks_default = /* @__PURE__ */ defineComponent({
18
+ __name: "TaoxLinks",
19
+ props: {
20
+ lines: {},
21
+ selectedId: {},
22
+ preview: {},
23
+ glow: { type: Boolean }
24
+ },
25
+ setup(__props) {
26
+ const colorStyle = (line) => line.color ? { "--tx-link-line-color": line.color } : void 0;
27
+ return (_ctx, _cache) => {
28
+ return openBlock(), createElementBlock("svg", _hoisted_1, [(openBlock(true), createElementBlock(Fragment, null, renderList(__props.lines, (line) => {
29
+ return openBlock(), createElementBlock("g", {
30
+ key: line.id,
31
+ class: normalizeClass(["tx-link", { selected: __props.selectedId === line.id }]),
32
+ "data-conn-id": line.id,
33
+ style: normalizeStyle(colorStyle(line))
34
+ }, [
35
+ __props.glow ? (openBlock(), createElementBlock("path", {
36
+ key: 0,
37
+ class: "tx-link-glow",
38
+ d: line.d
39
+ }, null, 8, _hoisted_3)) : createCommentVNode("", true),
40
+ createElementVNode("path", {
41
+ class: "tx-link-line",
42
+ d: line.d
43
+ }, null, 8, _hoisted_4),
44
+ line.head ? (openBlock(), createElementBlock("path", {
45
+ key: 1,
46
+ class: "tx-link-head",
47
+ d: line.head
48
+ }, null, 8, _hoisted_5)) : createCommentVNode("", true),
49
+ createElementVNode("path", {
50
+ class: "tx-link-hit",
51
+ d: line.d
52
+ }, null, 8, _hoisted_6)
53
+ ], 14, _hoisted_2);
54
+ }), 128)), __props.preview ? (openBlock(), createElementBlock("g", {
55
+ key: 0,
56
+ class: normalizeClass(["tx-link tx-link-preview", { invalid: __props.preview.invalid }]),
57
+ style: normalizeStyle(colorStyle(__props.preview))
58
+ }, [createElementVNode("path", {
59
+ class: "tx-link-line",
60
+ d: __props.preview.d
61
+ }, null, 8, _hoisted_7), __props.preview.head ? (openBlock(), createElementBlock("path", {
62
+ key: 0,
63
+ class: "tx-link-head",
64
+ d: __props.preview.head
65
+ }, null, 8, _hoisted_8)) : createCommentVNode("", true)], 6)) : createCommentVNode("", true)]);
66
+ };
67
+ }
68
+ });
69
+ //#endregion
70
+ export { TaoxLinks_default as TaoxLinks };
71
+
72
+ //# sourceMappingURL=links.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"links.js","names":["_openBlock","_createElementBlock","_Fragment","_renderList","_normalizeClass","_normalizeStyle","_createCommentVNode","_createElementVNode","_sfc_main"],"sources":["../src/links/TaoxLinks.vue","../src/links/TaoxLinks.vue"],"sourcesContent":["<script lang=\"ts\" setup>\nimport type { LinkLine, LinkPreview } from './types';\n\ndefineProps<{\n lines: readonly LinkLine[];\n selectedId?: string | null;\n preview?: LinkPreview | null;\n /**\n * Highlight the hovered and selected link with a blurred glow.\n * Подсвечивать наведённую и выбранную связь размытым свечением.\n */\n glow?: boolean;\n}>();\n\nconst colorStyle = (line: LinkLine) => (line.color ? { '--tx-link-line-color': line.color } : undefined);\n</script>\n\n<template>\n <svg class=\"tx-links\" width=\"1\" height=\"1\">\n <g\n v-for=\"line in lines\"\n :key=\"line.id\"\n class=\"tx-link\"\n :class=\"{ selected: selectedId === line.id }\"\n :data-conn-id=\"line.id\"\n :style=\"colorStyle(line)\"\n >\n <path v-if=\"glow\" class=\"tx-link-glow\" :d=\"line.d\" />\n <path class=\"tx-link-line\" :d=\"line.d\" />\n <path v-if=\"line.head\" class=\"tx-link-head\" :d=\"line.head\" />\n <path class=\"tx-link-hit\" :d=\"line.d\" />\n </g>\n\n <g v-if=\"preview\" class=\"tx-link tx-link-preview\" :class=\"{ invalid: preview.invalid }\" :style=\"colorStyle(preview)\">\n <path class=\"tx-link-line\" :d=\"preview.d\" />\n <path v-if=\"preview.head\" class=\"tx-link-head\" :d=\"preview.head\" />\n </g>\n </svg>\n</template>\n\n<style>\n/*\n * Configured with CSS variables on any ancestor:\n * Настройка через CSS-переменные на любом предке:\n * --tx-link-color, --tx-link-hover-color, --tx-link-selected-color, --tx-link-preview-color, --tx-link-invalid-color,\n * --tx-link-width, --tx-link-width-active, --tx-link-hit, --tx-link-hit-coarse, --tx-link-glow (opacity of the glow).\n * --tx-link-width, --tx-link-width-active, --tx-link-hit, --tx-link-hit-coarse, --tx-link-glow (непрозрачность свечения).\n */\n.tx-links {\n position: absolute;\n top: 0;\n left: 0;\n overflow: visible;\n pointer-events: none;\n}\n\n.tx-links path {\n fill: none;\n stroke-linecap: round;\n /* thickness in screen pixels, independent of zoom / толщина в экранных пикселях, не зависит от зума */\n vector-effect: non-scaling-stroke;\n}\n\n.tx-link {\n --tx-link-now: var(--tx-link-line-color, var(--tx-link-color, #9ca3af));\n}\n\n/* A link without its own colour turns the hover colour on hover. An own colour stays on hover (it gets thicker and glows). / Своего цвета у связи нет: наведение красит её в hover-цвет. Свой цвет при наведении остаётся (утолщается и светится). */\n.tx-link:hover {\n --tx-link-now: var(--tx-link-line-color, var(--tx-link-hover-color, #fff));\n}\n\n.tx-link.selected {\n --tx-link-now: var(--tx-link-selected-color, #f59e0b);\n}\n\n.tx-link-line {\n stroke: var(--tx-link-now);\n stroke-width: var(--tx-link-width, 2);\n pointer-events: none;\n}\n\n.tx-link:hover .tx-link-line,\n.tx-link.selected .tx-link-line {\n stroke-width: var(--tx-link-width-active, 3);\n}\n\n.tx-link-head {\n fill: var(--tx-link-now);\n stroke: none;\n pointer-events: none;\n}\n\n.tx-link-glow {\n stroke: var(--tx-link-now);\n stroke-width: 9;\n opacity: 0;\n filter: blur(3px);\n pointer-events: none;\n}\n\n.tx-link:hover .tx-link-glow,\n.tx-link.selected .tx-link-glow {\n opacity: var(--tx-link-glow, 0.35);\n}\n\n.tx-link-hit {\n stroke: transparent;\n stroke-width: var(--tx-link-hit, 14);\n pointer-events: stroke;\n cursor: pointer;\n}\n\n/* A finger is thicker than a cursor: the hit area of a link is wider. / Палец толще курсора: зона попадания по связи шире. */\n@media (pointer: coarse) {\n .tx-link-hit {\n stroke-width: var(--tx-link-hit-coarse, 30);\n }\n}\n\n.tx-link-preview {\n --tx-link-now: var(--tx-link-line-color, var(--tx-link-preview-color, #f59e0b));\n opacity: 0.85;\n}\n\n.tx-link-preview .tx-link-line {\n stroke-dasharray: 6 4;\n}\n\n.tx-link-preview.invalid {\n --tx-link-now: var(--tx-link-invalid-color, #ef4444);\n}\n</style>\n","<script lang=\"ts\" setup>\nimport type { LinkLine, LinkPreview } from './types';\n\ndefineProps<{\n lines: readonly LinkLine[];\n selectedId?: string | null;\n preview?: LinkPreview | null;\n /**\n * Highlight the hovered and selected link with a blurred glow.\n * Подсвечивать наведённую и выбранную связь размытым свечением.\n */\n glow?: boolean;\n}>();\n\nconst colorStyle = (line: LinkLine) => (line.color ? { '--tx-link-line-color': line.color } : undefined);\n</script>\n\n<template>\n <svg class=\"tx-links\" width=\"1\" height=\"1\">\n <g\n v-for=\"line in lines\"\n :key=\"line.id\"\n class=\"tx-link\"\n :class=\"{ selected: selectedId === line.id }\"\n :data-conn-id=\"line.id\"\n :style=\"colorStyle(line)\"\n >\n <path v-if=\"glow\" class=\"tx-link-glow\" :d=\"line.d\" />\n <path class=\"tx-link-line\" :d=\"line.d\" />\n <path v-if=\"line.head\" class=\"tx-link-head\" :d=\"line.head\" />\n <path class=\"tx-link-hit\" :d=\"line.d\" />\n </g>\n\n <g v-if=\"preview\" class=\"tx-link tx-link-preview\" :class=\"{ invalid: preview.invalid }\" :style=\"colorStyle(preview)\">\n <path class=\"tx-link-line\" :d=\"preview.d\" />\n <path v-if=\"preview.head\" class=\"tx-link-head\" :d=\"preview.head\" />\n </g>\n </svg>\n</template>\n\n<style>\n/*\n * Configured with CSS variables on any ancestor:\n * Настройка через CSS-переменные на любом предке:\n * --tx-link-color, --tx-link-hover-color, --tx-link-selected-color, --tx-link-preview-color, --tx-link-invalid-color,\n * --tx-link-width, --tx-link-width-active, --tx-link-hit, --tx-link-hit-coarse, --tx-link-glow (opacity of the glow).\n * --tx-link-width, --tx-link-width-active, --tx-link-hit, --tx-link-hit-coarse, --tx-link-glow (непрозрачность свечения).\n */\n.tx-links {\n position: absolute;\n top: 0;\n left: 0;\n overflow: visible;\n pointer-events: none;\n}\n\n.tx-links path {\n fill: none;\n stroke-linecap: round;\n /* thickness in screen pixels, independent of zoom / толщина в экранных пикселях, не зависит от зума */\n vector-effect: non-scaling-stroke;\n}\n\n.tx-link {\n --tx-link-now: var(--tx-link-line-color, var(--tx-link-color, #9ca3af));\n}\n\n/* A link without its own colour turns the hover colour on hover. An own colour stays on hover (it gets thicker and glows). / Своего цвета у связи нет: наведение красит её в hover-цвет. Свой цвет при наведении остаётся (утолщается и светится). */\n.tx-link:hover {\n --tx-link-now: var(--tx-link-line-color, var(--tx-link-hover-color, #fff));\n}\n\n.tx-link.selected {\n --tx-link-now: var(--tx-link-selected-color, #f59e0b);\n}\n\n.tx-link-line {\n stroke: var(--tx-link-now);\n stroke-width: var(--tx-link-width, 2);\n pointer-events: none;\n}\n\n.tx-link:hover .tx-link-line,\n.tx-link.selected .tx-link-line {\n stroke-width: var(--tx-link-width-active, 3);\n}\n\n.tx-link-head {\n fill: var(--tx-link-now);\n stroke: none;\n pointer-events: none;\n}\n\n.tx-link-glow {\n stroke: var(--tx-link-now);\n stroke-width: 9;\n opacity: 0;\n filter: blur(3px);\n pointer-events: none;\n}\n\n.tx-link:hover .tx-link-glow,\n.tx-link.selected .tx-link-glow {\n opacity: var(--tx-link-glow, 0.35);\n}\n\n.tx-link-hit {\n stroke: transparent;\n stroke-width: var(--tx-link-hit, 14);\n pointer-events: stroke;\n cursor: pointer;\n}\n\n/* A finger is thicker than a cursor: the hit area of a link is wider. / Палец толще курсора: зона попадания по связи шире. */\n@media (pointer: coarse) {\n .tx-link-hit {\n stroke-width: var(--tx-link-hit-coarse, 30);\n }\n}\n\n.tx-link-preview {\n --tx-link-now: var(--tx-link-line-color, var(--tx-link-preview-color, #f59e0b));\n opacity: 0.85;\n}\n\n.tx-link-preview .tx-link-line {\n stroke-dasharray: 6 4;\n}\n\n.tx-link-preview.invalid {\n --tx-link-now: var(--tx-link-invalid-color, #ef4444);\n}\n</style>\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;EAcA,MAAM,cAAc,SAAoB,KAAK,QAAQ,EAAE,wBAAwB,KAAK,MAAM,IAAI,KAAA;;GAI1F,OAAAA,UAAA,GAAAC,mBAmBM,OAnBN,YAmBM,EAlBFD,UAAA,IAAA,GAAAC,mBAYIC,UAAA,MAAAC,WAXe,QAAA,QAAR,SAAI;IADf,OAAAH,UAAA,GAAAC,mBAYI,KAAA;KAVC,KAAK,KAAK;KACX,OAAKG,eAAA,CAAC,WAAS,EAAA,UACK,QAAA,eAAe,KAAK,GAAE,CAAA,CAAA;KACzC,gBAAc,KAAK;KACnB,OAAKC,eAAE,WAAW,IAAI,CAAA;;KAEX,QAAA,QAAZL,UAAA,GAAAC,mBAAqD,QAAA;;MAAnC,OAAM;MAAgB,GAAG,KAAK;;KAChDM,mBAAyC,QAAA;MAAnC,OAAM;MAAgB,GAAG,KAAK;;KACxB,KAAK,QAAjBP,UAAA,GAAAC,mBAA6D,QAAA;;MAAtC,OAAM;MAAgB,GAAG,KAAK;;KACrDM,mBAAwC,QAAA;MAAlC,OAAM;MAAe,GAAG,KAAK;;;G,WAG9B,QAAA,WAATP,UAAA,GAAAC,mBAGI,KAAA;;IAHc,OAAKG,eAAA,CAAC,2BAAyB,EAAA,SAAoB,QAAA,QAAQ,QAAO,CAAA,CAAA;IAAK,OAAKC,eAAE,WAAW,QAAA,OAAO,CAAA;G,IAC9GE,mBAA4C,QAAA;IAAtC,OAAM;IAAgB,GAAG,QAAA,QAAQ;G,yBAC3B,QAAA,QAAQ,QAApBP,UAAA,GAAAC,mBAAmE,QAAA;;IAAzC,OAAM;IAAgB,GAAG,QAAA,QAAQ"}
package/dist/num.d.ts ADDED
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Clamps `v` into `lo…hi`.
3
+ * Зажимает `v` в `lo…hi`.
4
+ */
5
+ export declare const clamp: (v: number, lo: number, hi: number) => number;
6
+ /**
7
+ * Clamps into 0…1.
8
+ * Зажимает в 0…1.
9
+ */
10
+ export declare const clamp01: (x: number) => number;
11
+ /**
12
+ * Clamps `v` into the bounds; a bound that is not set does not limit.
13
+ * Зажимает `v` в границы; незаданная граница не ограничивает.
14
+ */
15
+ export declare function clampTo(v: number, min?: number, max?: number): number;
16
+ /**
17
+ * Rounds to `digits` decimals (no "-0"); `null` and `undefined` leave the value as is.
18
+ * Обрезает до `digits` знаков после запятой (без «-0»); `null` и `undefined` оставляют значение как есть.
19
+ */
20
+ export declare function roundTo(x: number, digits?: number | null): number;
21
+ /**
22
+ * Snaps `x` to the nearest multiple of `step` without a float tail; a step of 0 or less leaves the value as is.
23
+ * Прижимает `x` к ближайшему кратному `step`, без хвоста float; шаг 0 или меньше оставляет значение как есть.
24
+ */
25
+ export declare function snapTo(x: number, step: number): number;
26
+ /**
27
+ * A "1, 2, 5 × 10ⁿ" step that gives about `target` ticks on a span of length `span`.
28
+ * Шаг «1, 2, 5 × 10ⁿ», при котором на отрезке длиной `span` выходит около `target` делений.
29
+ */
30
+ export declare function niceStep(span: number, target?: number): number;
31
+ /**
32
+ * Ticks on `lo…hi` with step `step`: multiples of the step, with no float error build-up and no "-0".
33
+ * Метки на отрезке `lo…hi` с шагом `step`: кратные шагу, без накопления ошибки float и без «-0».
34
+ */
35
+ export declare function ticks(lo: number, hi: number, step: number): number[];
package/dist/num.js ADDED
@@ -0,0 +1,60 @@
1
+ //#region src/num.ts
2
+ /**
3
+ * Clamps `v` into `lo…hi`.
4
+ * Зажимает `v` в `lo…hi`.
5
+ */
6
+ var clamp = (v, lo, hi) => Math.min(Math.max(v, lo), hi);
7
+ /**
8
+ * Clamps into 0…1.
9
+ * Зажимает в 0…1.
10
+ */
11
+ var clamp01 = (x) => x < 0 ? 0 : x > 1 ? 1 : x;
12
+ /**
13
+ * Clamps `v` into the bounds; a bound that is not set does not limit.
14
+ * Зажимает `v` в границы; незаданная граница не ограничивает.
15
+ */
16
+ function clampTo(v, min, max) {
17
+ return Math.min(max ?? Infinity, Math.max(min ?? -Infinity, v));
18
+ }
19
+ /**
20
+ * Rounds to `digits` decimals (no "-0"); `null` and `undefined` leave the value as is.
21
+ * Обрезает до `digits` знаков после запятой (без «-0»); `null` и `undefined` оставляют значение как есть.
22
+ */
23
+ function roundTo(x, digits) {
24
+ if (digits === void 0 || digits === null) return x;
25
+ const k = Math.pow(10, Math.max(0, Math.floor(digits)));
26
+ return Math.round(x * k) / k + 0;
27
+ }
28
+ /**
29
+ * Snaps `x` to the nearest multiple of `step` without a float tail; a step of 0 or less leaves the value as is.
30
+ * Прижимает `x` к ближайшему кратному `step`, без хвоста float; шаг 0 или меньше оставляет значение как есть.
31
+ */
32
+ function snapTo(x, step) {
33
+ return step > 0 ? Math.round(Math.round(x / step) * step * 1e6) / 1e6 + 0 : x;
34
+ }
35
+ /**
36
+ * A "1, 2, 5 × 10ⁿ" step that gives about `target` ticks on a span of length `span`.
37
+ * Шаг «1, 2, 5 × 10ⁿ», при котором на отрезке длиной `span` выходит около `target` делений.
38
+ */
39
+ function niceStep(span, target = 4) {
40
+ if (!(span > 0)) return 1;
41
+ const raw = span / Math.max(1, target);
42
+ const pow = Math.pow(10, Math.floor(Math.log10(raw)));
43
+ const f = raw / pow;
44
+ return (f < 1.5 ? 1 : f < 3.5 ? 2 : f < 7.5 ? 5 : 10) * pow;
45
+ }
46
+ /**
47
+ * Ticks on `lo…hi` with step `step`: multiples of the step, with no float error build-up and no "-0".
48
+ * Метки на отрезке `lo…hi` с шагом `step`: кратные шагу, без накопления ошибки float и без «-0».
49
+ */
50
+ function ticks(lo, hi, step) {
51
+ const out = [];
52
+ const first = Math.ceil(lo / step - 1e-9);
53
+ const last = Math.floor(hi / step + 1e-9);
54
+ for (let i = first; i <= last; i++) out.push(Math.round(i * step * 1e6) / 1e6 + 0);
55
+ return out;
56
+ }
57
+ //#endregion
58
+ export { clamp, clamp01, clampTo, niceStep, roundTo, snapTo, ticks };
59
+
60
+ //# sourceMappingURL=num.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"num.js","names":[],"sources":["../src/num.ts"],"sourcesContent":["// Small numeric maths several modules need (curve, gradient, playback):\n// clamping, rounding, steps, \"nice\" scale ticks. Imports nothing.\n// Мелкая числовая математика, которая нужна сразу нескольким модулям (кривая, градиент, воспроизведение):\n// зажим, округление, шаг, «красивые» деления шкалы. Ничего не импортирует.\n\n/**\n * Clamps `v` into `lo…hi`.\n * Зажимает `v` в `lo…hi`.\n */\nexport const clamp = (v: number, lo: number, hi: number): number => Math.min(Math.max(v, lo), hi);\n\n/**\n * Clamps into 0…1.\n * Зажимает в 0…1.\n */\nexport const clamp01 = (x: number): number => (x < 0 ? 0 : x > 1 ? 1 : x);\n\n/**\n * Clamps `v` into the bounds; a bound that is not set does not limit.\n * Зажимает `v` в границы; незаданная граница не ограничивает.\n */\nexport function clampTo(v: number, min?: number, max?: number): number {\n return Math.min(max ?? Infinity, Math.max(min ?? -Infinity, v));\n}\n\n/**\n * Rounds to `digits` decimals (no \"-0\"); `null` and `undefined` leave the value as is.\n * Обрезает до `digits` знаков после запятой (без «-0»); `null` и `undefined` оставляют значение как есть.\n */\nexport function roundTo(x: number, digits?: number | null): number {\n if (digits === undefined || digits === null) return x;\n const k = Math.pow(10, Math.max(0, Math.floor(digits)));\n return Math.round(x * k) / k + 0;\n}\n\n/**\n * Snaps `x` to the nearest multiple of `step` without a float tail; a step of 0 or less leaves the value as is.\n * Прижимает `x` к ближайшему кратному `step`, без хвоста float; шаг 0 или меньше оставляет значение как есть.\n */\nexport function snapTo(x: number, step: number): number {\n return step > 0 ? Math.round(Math.round(x / step) * step * 1e6) / 1e6 + 0 : x;\n}\n\n/**\n * A \"1, 2, 5 × 10ⁿ\" step that gives about `target` ticks on a span of length `span`.\n * Шаг «1, 2, 5 × 10ⁿ», при котором на отрезке длиной `span` выходит около `target` делений.\n */\nexport function niceStep(span: number, target = 4): number {\n if (!(span > 0)) return 1;\n const raw = span / Math.max(1, target);\n const pow = Math.pow(10, Math.floor(Math.log10(raw)));\n const f = raw / pow;\n return (f < 1.5 ? 1 : f < 3.5 ? 2 : f < 7.5 ? 5 : 10) * pow;\n}\n\n/**\n * Ticks on `lo…hi` with step `step`: multiples of the step, with no float error build-up and no \"-0\".\n * Метки на отрезке `lo…hi` с шагом `step`: кратные шагу, без накопления ошибки float и без «-0».\n */\nexport function ticks(lo: number, hi: number, step: number): number[] {\n const out: number[] = [];\n const first = Math.ceil(lo / step - 1e-9);\n const last = Math.floor(hi / step + 1e-9);\n for (let i = first; i <= last; i++) out.push(Math.round(i * step * 1e6) / 1e6 + 0);\n return out;\n}\n"],"mappings":";;;;;AASA,IAAa,SAAS,GAAW,IAAY,OAAuB,KAAK,IAAI,KAAK,IAAI,GAAG,EAAE,GAAG,EAAE;;;;;AAMhG,IAAa,WAAW,MAAuB,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI;;;;;AAMvE,SAAgB,QAAQ,GAAW,KAAc,KAAsB;CACnE,OAAO,KAAK,IAAI,OAAO,UAAU,KAAK,IAAI,OAAO,WAAW,CAAC,CAAC;AAClE;;;;;AAMA,SAAgB,QAAQ,GAAW,QAAgC;CAC/D,IAAI,WAAW,KAAA,KAAa,WAAW,MAAM,OAAO;CACpD,MAAM,IAAI,KAAK,IAAI,IAAI,KAAK,IAAI,GAAG,KAAK,MAAM,MAAM,CAAC,CAAC;CACtD,OAAO,KAAK,MAAM,IAAI,CAAC,IAAI,IAAI;AACnC;;;;;AAMA,SAAgB,OAAO,GAAW,MAAsB;CACpD,OAAO,OAAO,IAAI,KAAK,MAAM,KAAK,MAAM,IAAI,IAAI,IAAI,OAAO,GAAG,IAAI,MAAM,IAAI;AAChF;;;;;AAMA,SAAgB,SAAS,MAAc,SAAS,GAAW;CACvD,IAAI,EAAE,OAAO,IAAI,OAAO;CACxB,MAAM,MAAM,OAAO,KAAK,IAAI,GAAG,MAAM;CACrC,MAAM,MAAM,KAAK,IAAI,IAAI,KAAK,MAAM,KAAK,MAAM,GAAG,CAAC,CAAC;CACpD,MAAM,IAAI,MAAM;CAChB,QAAQ,IAAI,MAAM,IAAI,IAAI,MAAM,IAAI,IAAI,MAAM,IAAI,MAAM;AAC5D;;;;;AAMA,SAAgB,MAAM,IAAY,IAAY,MAAwB;CAClE,MAAM,MAAgB,CAAC;CACvB,MAAM,QAAQ,KAAK,KAAK,KAAK,OAAO,IAAI;CACxC,MAAM,OAAO,KAAK,MAAM,KAAK,OAAO,IAAI;CACxC,KAAK,IAAI,IAAI,OAAO,KAAK,MAAM,KAAK,IAAI,KAAK,KAAK,MAAM,IAAI,OAAO,GAAG,IAAI,MAAM,CAAC;CACjF,OAAO;AACX"}
@@ -0,0 +1,34 @@
1
+ /**
2
+ * The least the palette knows about a node.
3
+ * Минимум, что палитра знает о ноде.
4
+ */
5
+ export interface PaletteItem {
6
+ id: string;
7
+ title: string;
8
+ hidden?: boolean;
9
+ }
10
+ export interface NodeGroup<T> {
11
+ category: string;
12
+ nodes: T[];
13
+ }
14
+ /**
15
+ * Category: the part of the id before "/" (`math/add` → `math`); without "/" it is `other`.
16
+ * Категория: часть id до «/» (`math/add` → `math`), без «/» — `other`.
17
+ */
18
+ export declare const categoryOf: (def: {
19
+ id: string;
20
+ }) => string;
21
+ /**
22
+ * Nodes matching a query (every word must occur in the name or id), by category and name.
23
+ * Hidden ones (`hidden`) are not shown. `extraText` adds translations to the search text, so one can search in any language.
24
+ * Ноды, подходящие под запрос (все слова должны встретиться в названии или id), по категориям и названиям.
25
+ * Скрытые (`hidden`) не показываются. `extraText` добавляет к тексту поиска переводы, чтобы искать можно было на любом языке.
26
+ */
27
+ export declare function filterNodes<T extends PaletteItem>(defs: readonly T[], query: string, extraText?: (def: T) => string): T[];
28
+ /**
29
+ * Groups of consecutive nodes of one category (the input must be sorted by `filterNodes`).
30
+ * Группы идущих подряд нод одной категории (вход должен быть отсортирован `filterNodes`).
31
+ */
32
+ export declare function groupByCategory<T extends {
33
+ id: string;
34
+ }>(defs: readonly T[]): NodeGroup<T>[];
@@ -0,0 +1,41 @@
1
+ //#region src/palette.ts
2
+ /**
3
+ * Category: the part of the id before "/" (`math/add` → `math`); without "/" it is `other`.
4
+ * Категория: часть id до «/» (`math/add` → `math`), без «/» — `other`.
5
+ */
6
+ var categoryOf = (def) => def.id.includes("/") ? def.id.split("/")[0] : "other";
7
+ /**
8
+ * Nodes matching a query (every word must occur in the name or id), by category and name.
9
+ * Hidden ones (`hidden`) are not shown. `extraText` adds translations to the search text, so one can search in any language.
10
+ * Ноды, подходящие под запрос (все слова должны встретиться в названии или id), по категориям и названиям.
11
+ * Скрытые (`hidden`) не показываются. `extraText` добавляет к тексту поиска переводы, чтобы искать можно было на любом языке.
12
+ */
13
+ function filterNodes(defs, query, extraText = () => "") {
14
+ const words = query.toLowerCase().split(/\s+/).filter(Boolean);
15
+ return defs.filter((def) => {
16
+ if (def.hidden) return false;
17
+ const haystack = `${def.title} ${def.id} ${extraText(def)}`.toLowerCase();
18
+ return words.every((w) => haystack.includes(w));
19
+ }).sort((a, b) => categoryOf(a).localeCompare(categoryOf(b)) || a.title.localeCompare(b.title));
20
+ }
21
+ /**
22
+ * Groups of consecutive nodes of one category (the input must be sorted by `filterNodes`).
23
+ * Группы идущих подряд нод одной категории (вход должен быть отсортирован `filterNodes`).
24
+ */
25
+ function groupByCategory(defs) {
26
+ const groups = [];
27
+ for (const def of defs) {
28
+ const category = categoryOf(def);
29
+ const last = groups[groups.length - 1];
30
+ if (last?.category === category) last.nodes.push(def);
31
+ else groups.push({
32
+ category,
33
+ nodes: [def]
34
+ });
35
+ }
36
+ return groups;
37
+ }
38
+ //#endregion
39
+ export { categoryOf, filterNodes, groupByCategory };
40
+
41
+ //# sourceMappingURL=palette.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"palette.js","names":[],"sources":["../src/palette.ts"],"sourcesContent":["// Pure node-palette logic: search and groups by category. The palette window and the pin compatibility rules stay in the app.\r\n// Чистая логика палитры нод: поиск и группы по категориям. Окно палитры и правила совместимости пинов остаются в приложении.\r\n/**\r\n * The least the palette knows about a node.\r\n * Минимум, что палитра знает о ноде.\r\n */\r\nexport interface PaletteItem {\r\n id: string;\r\n title: string;\r\n hidden?: boolean;\r\n}\r\n\r\nexport interface NodeGroup<T> {\r\n category: string;\r\n nodes: T[];\r\n}\r\n\r\n/**\r\n * Category: the part of the id before \"/\" (`math/add` → `math`); without \"/\" it is `other`.\r\n * Категория: часть id до «/» (`math/add` → `math`), без «/» — `other`.\r\n */\r\nexport const categoryOf = (def: { id: string }): string => (def.id.includes('/') ? def.id.split('/')[0]! : 'other');\r\n\r\n/**\r\n * Nodes matching a query (every word must occur in the name or id), by category and name.\r\n * Hidden ones (`hidden`) are not shown. `extraText` adds translations to the search text, so one can search in any language.\r\n * Ноды, подходящие под запрос (все слова должны встретиться в названии или id), по категориям и названиям.\r\n * Скрытые (`hidden`) не показываются. `extraText` добавляет к тексту поиска переводы, чтобы искать можно было на любом языке.\r\n */\r\nexport function filterNodes<T extends PaletteItem>(defs: readonly T[], query: string, extraText: (def: T) => string = () => ''): T[] {\r\n const words = query.toLowerCase().split(/\\s+/).filter(Boolean);\r\n\r\n return defs\r\n .filter((def) => {\r\n if (def.hidden) return false;\r\n const haystack = `${def.title} ${def.id} ${extraText(def)}`.toLowerCase();\r\n return words.every((w) => haystack.includes(w));\r\n })\r\n .sort((a, b) => categoryOf(a).localeCompare(categoryOf(b)) || a.title.localeCompare(b.title));\r\n}\r\n\r\n/**\r\n * Groups of consecutive nodes of one category (the input must be sorted by `filterNodes`).\r\n * Группы идущих подряд нод одной категории (вход должен быть отсортирован `filterNodes`).\r\n */\r\nexport function groupByCategory<T extends { id: string }>(defs: readonly T[]): NodeGroup<T>[] {\r\n const groups: NodeGroup<T>[] = [];\r\n for (const def of defs) {\r\n const category = categoryOf(def);\r\n const last = groups[groups.length - 1];\r\n if (last?.category === category) last.nodes.push(def);\r\n else groups.push({ category, nodes: [def] });\r\n }\r\n return groups;\r\n}\r\n"],"mappings":";;;;;AAqBA,IAAa,cAAc,QAAiC,IAAI,GAAG,SAAS,GAAG,IAAI,IAAI,GAAG,MAAM,GAAG,CAAC,CAAC,KAAM;;;;;;;AAQ3G,SAAgB,YAAmC,MAAoB,OAAe,kBAAsC,IAAS;CACjI,MAAM,QAAQ,MAAM,YAAY,CAAC,CAAC,MAAM,KAAK,CAAC,CAAC,OAAO,OAAO;CAE7D,OAAO,KACF,QAAQ,QAAQ;EACb,IAAI,IAAI,QAAQ,OAAO;EACvB,MAAM,WAAW,GAAG,IAAI,MAAM,GAAG,IAAI,GAAG,GAAG,UAAU,GAAG,IAAI,YAAY;EACxE,OAAO,MAAM,OAAO,MAAM,SAAS,SAAS,CAAC,CAAC;CAClD,CAAC,CAAC,CACD,MAAM,GAAG,MAAM,WAAW,CAAC,CAAC,CAAC,cAAc,WAAW,CAAC,CAAC,KAAK,EAAE,MAAM,cAAc,EAAE,KAAK,CAAC;AACpG;;;;;AAMA,SAAgB,gBAA0C,MAAoC;CAC1F,MAAM,SAAyB,CAAC;CAChC,KAAK,MAAM,OAAO,MAAM;EACpB,MAAM,WAAW,WAAW,GAAG;EAC/B,MAAM,OAAO,OAAO,OAAO,SAAS;EACpC,IAAI,MAAM,aAAa,UAAU,KAAK,MAAM,KAAK,GAAG;OAC/C,OAAO,KAAK;GAAE;GAAU,OAAO,CAAC,GAAG;EAAE,CAAC;CAC/C;CACA,OAAO;AACX"}