@1337exp/taoux 0.17.0 → 0.18.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/CHANGELOG.md CHANGED
@@ -1,5 +1,13 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.18.0
4
+
5
+ **It needs TaoUI 6** (`@1337exp/taoui` `^6.0.0` as the optional peer, Vue `^3.5.0`): `TaoxCurveField` gives `TaoSelect` its `items` of `{ id, label }`. Nothing else to migrate: new modules and members; `commands` itself is unchanged. In Vitest, let Vite process the kit: `test.server.deps.inline: ['@1337exp/taoui']` (its CSS is imported by the components).
6
+
7
+ - **`curveops`: the sampling of a curve with no Vue.** `sampleCurve`, `sampleSegment`, `addPoint`, `movePoint`, `removePoint`, `setEase`, `valueBounds` were exported with the editor component, so a game that only plays a curve pulled Vue in. `@1337exp/taoux/curveops` is the same code on its own (the editor re-exports it, nothing changes there). `tests/curveops.test.ts` fails if it ever imports Vue.
8
+ - **`Command.repeat`: a held key, per command.** `repeat: false` runs a command once per press (a save, a toggle); the default is as before, it runs again while the key is held (a nudge, an undo). The held key is swallowed either way, so the browser's own dialog does not open. `bind`'s `repeat: false` still turns the repeat off for everything.
9
+ - **`commandsvue`: `useCommands`, the registry in a Vue app.** Every app that used `createCommands` wrote the same glue: add the commands, `bind` the keys on mount and stop on unmount, wrap `toMenu` in a `computed`, and turn the `select` of a menu into `commands.run`. `useCommands(commands, { add, target })` is that glue: the commands of the component are added at once (a menu can name them in the same `setup`) and removed with it, the shortcuts are heard from `onMounted` to unmount (`target: false` for a menu without keys), `menu(layout)` gives a `ComputedRef` of menu items that follows what the labels, `enabled` and `checked` read, and `onSelect(item)` runs `item.id`: TaoUI 6 emits the whole item from `select`, not a bare id, so `@select="commands.run"` of the old docs would pass an object (the comment of `run` says so now). The registry stays where it is, in TaoUX: it is behaviour, not a look, and the kit's menus only take items. `useCommands` takes the registry by its shape, so the module imports nothing from another module of the package. A component kept alive (`<KeepAlive>`) lets go of its commands and its keys when it is hidden and takes them again when it comes back; Vue sets the new page up before it deactivates the old one, so two pages that are switched in a `<KeepAlive>` must not add the same command id (the registry throws on a duplicate, as it always did).
10
+
3
11
  ## 0.17.0
4
12
 
5
13
  Nothing to migrate: new optional members of `History`; a history that does not use them behaves and saves exactly as before.
package/README.md CHANGED
@@ -105,11 +105,13 @@ import { History } from '@1337exp/taoux/history';
105
105
  | `links` (Vue) | links layer: SVG from ready geometry, `--tx-link-*` | vue (peer) |
106
106
  | `canvas` (Vue) | canvas: mouse and touch gestures, wheel, auto-scroll, keys; the `CanvasHost` contract | vue (peer) |
107
107
  | `curveeditor` (Vue) | curve editor plot: grid, snapping, bounds, decimals, auto-scroll at the edge; point operations; per-segment transitions with Bezier handles; `formatT` writes the 0…1 time as years, seconds…; keyboard (Tab, arrows, Shift, Insert, Delete) | vue (peer) |
108
+ | `curveops` | the point operations and `sampleCurve(points, t)` of a curve with no Vue: for a game, a worker, a build step | none |
108
109
  | `swiperow` (Vue, tier 2) | `TaoxSwipeRow`: a list row a finger slides sideways, as in a mail app: to the start one action that runs past a threshold (read / unread), to the end actions that grow out and stay open, a long pull runs the last one (delete); TaoUI icons and tones, `@action="id => …"`; Tab reaches the actions | vue, **@1337exp/taoui** (peer) |
109
110
  | `curvefield` (Vue, tier 2) | `TaoxCurveField`: a curve with fields on TaoUI components: point time and value, transition to the next point (`ease`), snapping, remove and reset; labels come from the app | vue, **@1337exp/taoui** (peer) |
110
111
  | `gradienteditor` (Vue) | gradient bar with stop handles; stop operations, `gradientCss`; keyboard (Tab, arrows, Home/End, Insert, Delete) | vue (peer) |
111
112
  | `playback` | playback model: time, pause, loop, speed, seeking; `createPlayback` without Vue and `usePlayback` for a component | vue (peer, for `usePlayback`) |
112
113
  | `tour` | a guided tour of a page, step by step: `createTour` without Vue (jumps over steps whose target is gone, ends as `done` or `skipped`), `useTour` for a component, `createTourMemory` so it shows once | vue (peer, for `useTour`), storage |
114
+ | `commandsvue` | `commands` in a Vue app: `useCommands(registry, { add })` adds the commands of a component (and removes them with it), listens to the shortcuts while it is mounted, `menu(layout)` is a `computed` that follows the state, `onSelect(item)` is the `@select` of a menu (it takes the item TaoUI 6 emits and runs `item.id`) | vue (peer) |
113
115
  | `undovue` | `undo` and `history` for Vue: `useUndoStack` and `useHistory` keep `canUndo` / `canRedo` (and, for `useHistory`, `undoLabel` / `redoLabel` / `dirty`) as refs after every move (for `historyCommands` and the menu); `useUndoFlags(source)` + `sync()` for a stack you already have | vue (peer) |
114
116
  | `pins` | row pin positions measured from the DOM: `usePinMeasure`, `createPinRegistry` | vue (peer) |
115
117
  | `i18n` | typed i18n: `createI18n({ locales, fallback, storageKey })` | vue (peer, optional) |
package/README.ru.md CHANGED
@@ -105,11 +105,13 @@ import { History } from '@1337exp/taoux/history';
105
105
  | `links` (Vue) | слой связей: SVG из готовой геометрии, `--tx-link-*` | vue (peer) |
106
106
  | `canvas` (Vue) | холст: жесты мыши и сенсора, колесо, автопрокрутка, клавиши; контракт `CanvasHost` | vue (peer) |
107
107
  | `curveeditor` (Vue) | поле редактора кривой: сетка, шаг, границы, знаки, автопрокрутка у края; операции над точками; переходы между точками с ручками Безье; `formatT` записывает время 0…1 годами, секундами…; клавиатура (Tab, стрелки, Shift, Insert, Delete) | vue (peer) |
108
+ | `curveops` | операции над точками и `sampleCurve(points, t)` кривой без Vue: для игры, воркера, шага сборки | нет |
108
109
  | `swiperow` (Vue, ярус 2) | `TaoxSwipeRow`: строка списка, которую палец сдвигает вбок, как в почте: вправо одно действие, выполняется после порога (прочитано / не прочитано), влево действия вырастают и остаются открытыми, длинный свайп выполняет последнее (удалить); иконки и тона TaoUI, `@action="id => …"`; до действий можно дойти Tab | vue, **@1337exp/taoui** (peer) |
109
110
  | `curvefield` (Vue, ярус 2) | `TaoxCurveField`: кривая с полями на компонентах TaoUI: время и значение точки, переход к следующей точке (`ease`), шаг, удаление и сброс; надписи задаёт приложение | vue, **@1337exp/taoui** (peer) |
110
111
  | `gradienteditor` (Vue) | полоса градиента с ручками остановок; операции над остановками, `gradientCss`; клавиатура (Tab, стрелки, Home/End, Insert, Delete) | vue (peer) |
111
112
  | `playback` | модель воспроизведения: время, пауза, цикл, скорость, перемотка; `createPlayback` без Vue и `usePlayback` для компонента | vue (peer, для `usePlayback`) |
112
113
  | `tour` | тур по странице по шагам: `createTour` без Vue (перепрыгивает шаги, у которых пропала цель, завершается как `done` или `skipped`), `useTour` для компонента, `createTourMemory`, чтобы показывался один раз | vue (peer, для `useTour`), storage |
114
+ | `commandsvue` | `commands` в приложении на Vue: `useCommands(registry, { add })` добавляет команды компонента (и убирает их вместе с ним), слушает сочетания, пока он смонтирован, `menu(layout)` это `computed`, который следует за состоянием, `onSelect(item)` это `@select` меню (берёт пункт, который отдаёт TaoUI 6, и выполняет `item.id`) | vue (peer) |
113
115
  | `undovue` | `undo` и `history` для Vue: `useUndoStack` и `useHistory` держат `canUndo` / `canRedo` (а `useHistory` ещё `undoLabel` / `redoLabel` / `dirty`) как ref после каждого хода (для `historyCommands` и меню); `useUndoFlags(source)` + `sync()` для уже готового стека | vue (peer) |
114
116
  | `pins` | позиции пинов-строк, измеренные по DOM: `usePinMeasure`, `createPinRegistry` | vue (peer) |
115
117
  | `i18n` | типизированный i18n: `createI18n({ locales, fallback, storageKey })` | vue (peer, опционально) |
@@ -1,169 +1,7 @@
1
1
  import { createEdgeScroller } from "../edgescroll.js";
2
- import { clamp01, clampTo, niceStep, roundTo, snapTo, ticks } from "../num.js";
3
- import { easeValue } from "../ease.js";
2
+ import { clampTo, niceStep, roundTo, snapTo, ticks } from "../num.js";
3
+ import { addPoint, movePoint, removePoint, sampleSegment, setEase, valueBounds } from "../curveops.js";
4
4
  import { Fragment, computed, createCommentVNode, createElementBlock, createElementVNode, defineComponent, nextTick, normalizeClass, onBeforeUnmount, openBlock, ref, renderList, toDisplayString, withModifiers } from "vue";
5
- //#region src/curveeditor/ops.ts
6
- /**
7
- * The curve value at t: beyond the end points it equals the end point, between them it follows the `ease` of the left point (linear without it).
8
- * Значение кривой в t: вне крайних точек равно крайней, между ними по переходу `ease` левой точки (без него линейно).
9
- */
10
- function sampleCurve(points, t) {
11
- const n = points.length;
12
- if (n === 0) return 0;
13
- const x = clamp01(t);
14
- if (x <= points[0].t) return points[0].v;
15
- if (x >= points[n - 1].t) return points[n - 1].v;
16
- for (let i = 1; i < n; i++) {
17
- const b = points[i];
18
- if (x <= b.t) {
19
- const a = points[i - 1];
20
- const span = b.t - a.t;
21
- return span <= 0 ? b.v : a.v + (b.v - a.v) * easeValue(a.ease, (x - a.t) / span);
22
- }
23
- }
24
- return points[n - 1].v;
25
- }
26
- /**
27
- * Moves point `i`: along t it stays between its neighbours (the order is kept), along v it is free.
28
- * Двигает точку `i`: по t она остаётся между соседями (порядок не нарушается), по v свободна.
29
- */
30
- function movePoint(points, i, t, v) {
31
- const next = points.map((p) => ({ ...p }));
32
- const lo = i > 0 ? next[i - 1].t : 0;
33
- const hi = i < next.length - 1 ? next[i + 1].t : 1;
34
- next[i] = {
35
- ...next[i],
36
- t: Math.min(hi, Math.max(lo, clamp01(t))),
37
- v
38
- };
39
- return next;
40
- }
41
- /**
42
- * Adds a point at `t` with value `v` (the curve value at that point by default); returns the new list and the point index.
43
- * Добавляет точку в `t` со значением `v` (по умолчанию значение кривой в этой точке); возвращает новый список и индекс точки.
44
- */
45
- function addPoint(points, t, v) {
46
- const x = clamp01(t);
47
- const next = points.map((p) => ({ ...p }));
48
- const at = next.findIndex((p) => p.t > x);
49
- const index = at === -1 ? next.length : at;
50
- next.splice(index, 0, {
51
- t: x,
52
- v: v ?? sampleCurve(points, x)
53
- });
54
- return {
55
- points: next,
56
- index
57
- };
58
- }
59
- /**
60
- * Removes a point; never leaves fewer than two (a curve of one point is just a number).
61
- * Убирает точку; меньше двух точек не оставляет (кривая из одной точки это просто число).
62
- */
63
- function removePoint(points, i) {
64
- if (points.length <= 2) return points.map((p) => ({ ...p }));
65
- return points.filter((_, k) => k !== i).map((p) => ({ ...p }));
66
- }
67
- /**
68
- * A segment transition that is neither a straight line nor a step: its shape has to be drawn and taken into account when choosing the view.
69
- * Переход участка, который не прямая и не ступенька: его форму нужно рисовать и учитывать при подборе вида.
70
- */
71
- var curved = (e) => e !== void 0 && e !== "linear" && e !== "step";
72
- /**
73
- * The polyline of segment a→b for drawing: a straight one has two ends, other transitions `steps` pieces (a step: a corner).
74
- * Ломаная участка a→b для рисования: у прямой два конца, у остальных переходов `steps` отрезков (ступенька: угол).
75
- */
76
- function sampleSegment(a, b, steps = 24) {
77
- if (a.ease === "step") return [
78
- {
79
- t: a.t,
80
- v: a.v
81
- },
82
- {
83
- t: b.t,
84
- v: a.v
85
- },
86
- {
87
- t: b.t,
88
- v: b.v
89
- }
90
- ];
91
- if (!curved(a.ease)) return [{
92
- t: a.t,
93
- v: a.v
94
- }, {
95
- t: b.t,
96
- v: b.v
97
- }];
98
- const out = [];
99
- for (let i = 0; i <= steps; i++) {
100
- const u = i / steps;
101
- out.push({
102
- t: a.t + (b.t - a.t) * u,
103
- v: a.v + (b.v - a.v) * easeValue(a.ease, u)
104
- });
105
- }
106
- return out;
107
- }
108
- /**
109
- * A copy of the list with the transition of point `i` (`undefined` and `linear` remove the field: the file stays short).
110
- * Копия списка с переходом точки `i` (`undefined` и `linear` убирают поле: файл остаётся коротким).
111
- */
112
- function setEase(points, i, ease) {
113
- return points.map((p, k) => {
114
- if (k !== i) return { ...p };
115
- const { ease: _old, ...rest } = p;
116
- return ease === void 0 || ease === "linear" ? rest : {
117
- ...rest,
118
- ease
119
- };
120
- });
121
- }
122
- /**
123
- * Value limits for drawing: from 0 (or below the minimum) to the maximum with some headroom, no narrower than 0…1.
124
- * The given `min`/`max` (the field bounds) fix the view: the plot neither drifts nor leaves the allowed range.
125
- * Пределы значений для отрисовки: от 0 (или ниже минимума) до максимума с запасом, не уже чем 0…1.
126
- * Заданные `min`/`max` (границы поля) фиксируют вид: график не плывёт и не выходит за допустимое.
127
- */
128
- function valueBounds(points, min, max) {
129
- let lo = 0;
130
- let hi = 1;
131
- for (const p of points) {
132
- lo = Math.min(lo, p.v);
133
- hi = Math.max(hi, p.v);
134
- }
135
- let outLo = Infinity;
136
- let outHi = -Infinity;
137
- const see = (v) => {
138
- lo = Math.min(lo, v);
139
- hi = Math.max(hi, v);
140
- outLo = Math.min(outLo, v);
141
- outHi = Math.max(outHi, v);
142
- };
143
- for (let i = 0; i < points.length - 1; i++) {
144
- const a = points[i];
145
- if (!curved(a.ease)) continue;
146
- if (typeof a.ease === "object") {
147
- const dv = points[i + 1].v - a.v;
148
- for (const y of [a.ease.bezier[1], a.ease.bezier[3]]) see(a.v + y * dv);
149
- }
150
- for (const s of sampleSegment(points[i], points[i + 1])) see(s.v);
151
- }
152
- const auto = {
153
- min: lo,
154
- max: hi === lo ? lo + 1 : hi * 1.1
155
- };
156
- const a = min === void 0 ? auto.min : Math.min(min, outLo);
157
- const b = max === void 0 ? auto.max : Math.max(max, outHi);
158
- return b > a ? {
159
- min: a,
160
- max: b
161
- } : {
162
- min: a,
163
- max: a + 1
164
- };
165
- }
166
- //#endregion
167
5
  //#region src/curveeditor/TaoxCurveEditor.vue?vue&type=script&setup=true&lang.ts
168
6
  var _hoisted_1 = ["viewBox", "title"];
169
7
  var _hoisted_2 = [
@@ -756,6 +594,6 @@ var TaoxCurveEditor_default = /* @__PURE__ */ defineComponent({
756
594
  }
757
595
  });
758
596
  //#endregion
759
- export { sampleCurve as a, valueBounds as c, removePoint as i, addPoint as n, sampleSegment as o, movePoint as r, setEase as s, TaoxCurveEditor_default as t };
597
+ export { TaoxCurveEditor_default as t };
760
598
 
761
- //# sourceMappingURL=curveeditor-B1mAStQs.js.map
599
+ //# sourceMappingURL=curveeditor-C9SsYXjQ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"curveeditor-C9SsYXjQ.js","names":["_openBlock","_createElementBlock","_withModifiers","_Fragment","_renderList","_normalizeClass","_toDisplayString","_createElementVNode","_createCommentVNode","_sfc_main"],"sources":["../../src/curveeditor/TaoxCurveEditor.vue","../../src/curveeditor/TaoxCurveEditor.vue"],"sourcesContent":["<script lang=\"ts\" setup>\r\nimport { computed, nextTick, onBeforeUnmount, ref } from 'vue';\r\nimport { createEdgeScroller } from '../edgescroll';\r\nimport { clampTo, niceStep, roundTo, snapTo, ticks } from '../num';\r\nimport { addPoint, movePoint, removePoint, sampleSegment, setEase, valueBounds, type CurveGuides, type CurvePoint } from './ops';\r\n\r\nconst props = withDefaults(\r\n defineProps<{\r\n /**\r\n * Curve points in ascending t (at least two).\r\n * Точки кривой по возрастанию t (минимум две).\r\n */\r\n modelValue: readonly CurvePoint[];\r\n /**\r\n * Index of the selected point.\r\n * Индекс выбранной точки.\r\n */\r\n selected?: number;\r\n /**\r\n * Allowed values: they fix the plot view and do not let a point be dragged past the bound.\r\n * Допустимые значения: фиксируют вид графика и не дают утащить точку за границу.\r\n */\r\n min?: number;\r\n max?: number;\r\n /**\r\n * How many decimals to keep in t and v; not set means do not round.\r\n * Сколько знаков после запятой оставлять у t и v; не задано — не обрезать.\r\n */\r\n precision?: number;\r\n /**\r\n * Snapping to the grid (Shift flips the mode for the moment).\r\n * Прилипание к сетке (Shift на время меняет режим).\r\n */\r\n snap?: boolean;\r\n /**\r\n * The time step and the distance between labelled lines.\r\n * Шаг по времени и расстояние между подписанными линиями.\r\n */\r\n stepT?: number;\r\n majorT?: number;\r\n /**\r\n * A hint on hover over the field.\r\n * Подсказка при наведении на поле.\r\n */\r\n hint?: string;\r\n /**\r\n * The point label for screen readers; \"Point 1: t, v\" by default.\r\n * Подпись точки для скринридеров; по умолчанию «Point 1: t, v».\r\n */\r\n pointLabel?: (index: number, point: CurvePoint) => string;\r\n /**\r\n * How time is written: on the time axis, on the tag of the selected point and in the default point label. `t` is 0…1, the\r\n * editor's own time; a curve over years or seconds says so here (`(t) => `${Math.round(t * 14)} y``). By default the number\r\n * itself.\r\n * Как записывается время: на оси времени, на метке выбранной точки и в подписи точки по умолчанию. `t` — от 0 до 1, собственное\r\n * время редактора; кривая по годам или секундам говорит это здесь. По умолчанию само число.\r\n */\r\n formatT?: (t: number) => string;\r\n /**\r\n * Guides from the selected point to the axes: `off` none, `lines` dashed lines only, `values` lines and the point values on the axes.\r\n * `lines` by default: noticeable, but not overloaded.\r\n * Направляющие от выбранной точки к осям: `off` нет, `lines` только пунктирные линии, `values` линии и значения точки на осях.\r\n * По умолчанию `lines`: заметно, но не перегружает.\r\n */\r\n guides?: CurveGuides;\r\n /**\r\n * The label of a Bezier handle for screen readers (n: 1 or 2); \"Bezier handle n\" by default.\r\n * Подпись ручки Безье для скринридеров (n: 1 или 2); по умолчанию «Bezier handle n».\r\n */\r\n handleLabel?: (n: number, index: number) => string;\r\n }>(),\r\n { selected: 0, snap: true, stepT: 0.05, majorT: 0.25, guides: 'lines' },\r\n);\r\nconst emit = defineEmits<{\r\n 'update:modelValue': [value: CurvePoint[]];\r\n 'update:selected': [index: number];\r\n /**\r\n * An edit is finished (a point was released, added, removed): the moment to record into history.\r\n * Правка закончена (отпустили точку, добавили, убрали): момент для записи в историю.\r\n */\r\n commit: [];\r\n}>();\r\n\r\nconst W = 280;\r\nconst H = 132;\r\nconst PAD_L = 30;\r\nconst PAD_R = 10;\r\nconst PAD_T = 10;\r\nconst PAD_B = 16;\r\nconst PLOT_W = W - PAD_L - PAD_R;\r\nconst PLOT_H = H - PAD_T - PAD_B;\r\n\r\nconst svg = ref<SVGSVGElement | null>(null);\r\n\r\nconst points = computed(() => props.modelValue);\r\n// The limits are remembered for the duration of a drag: otherwise the plot would \"float\" under the hand\r\n// Пределы запоминаем на время перетаскивания: иначе график «плыл» бы под рукой\r\nconst frozen = ref<{ min: number; max: number } | null>(null);\r\n// The view shift by value: accumulated by auto-scroll at the edge while a point is dragged\r\n// Сдвиг вида по значению: накапливает автопрокрутка у края, пока тянут точку\r\nconst shift = ref(0);\r\nconst bounds = computed(() => (frozen.value ? { min: frozen.value.min + shift.value, max: frozen.value.max + shift.value } : valueBounds(points.value, props.min, props.max)));\r\nconst span = computed(() => bounds.value.max - bounds.value.min);\r\n\r\nconst majorV = computed(() => niceStep(span.value, 4));\r\nconst stepV = computed(() => niceStep(span.value, 20));\r\nconst gridT = computed(() => ticks(0, 1, props.stepT));\r\nconst gridV = computed(() => ticks(bounds.value.min, bounds.value.max, stepV.value));\r\nconst labelsV = computed(() => ticks(bounds.value.min, bounds.value.max, majorV.value));\r\nconst labelsT = computed(() => ticks(0, 1, props.majorT));\r\nconst isMajorT = (x: number) => Math.abs(x / props.majorT - Math.round(x / props.majorT)) < 1e-6;\r\nconst isMajorV = (v: number) => Math.abs(v / majorV.value - Math.round(v / majorV.value)) < 1e-6;\r\n\r\nconst px = (tt: number) => PAD_L + tt * PLOT_W;\r\nconst py = (v: number) => PAD_T + (1 - (v - bounds.value.min) / span.value) * PLOT_H;\r\n// Segments are drawn by their transitions: a straight one has two ends, smooth ones dozens of pieces, a step a corner\r\n// Участки рисуются по своим переходам: у прямой два конца, у плавных десятки отрезков, у ступеньки угол\r\nconst path = computed(() => {\r\n const pts = points.value;\r\n const out: string[] = [];\r\n for (let i = 0; i < pts.length - 1; i++) {\r\n sampleSegment(pts[i]!, pts[i + 1]!).forEach((p, k) => out.push(`${i === 0 && k === 0 ? 'M' : 'L'} ${px(p.t).toFixed(1)} ${py(p.v).toFixed(1)}`));\r\n }\r\n return out.join(' ');\r\n});\r\nconst fmt = (n: number) => String(Math.round(n * 1000) / 1000);\r\nconst fmtT = (tt: number) => (props.formatT ? props.formatT(tt) : fmt(tt));\r\n\r\n// The values of the selected point on the axes: time under the plot, value on the left. They show while the point is dragged, so there is no need to look for the fields.\r\n// Значения выбранной точки на осях: время под графиком, значение слева. Они видны, пока точку тянут, и не надо искать глазами поля.\r\nconst CHAR_W = 4.6;\r\nconst tagWidth = (text: string) => text.length * CHAR_W + 5;\r\nconst tags = computed(() => {\r\n const p = points.value[Math.min(props.selected, points.value.length - 1)];\r\n if (!p) return null;\r\n const t = fmtT(p.t);\r\n const v = fmt(p.v);\r\n const wt = tagWidth(t);\r\n const wv = tagWidth(v);\r\n const cx = Math.min(W - wt / 2 - 1, Math.max(wt / 2 + 1, px(p.t)));\r\n const cy = Math.min(PAD_T + PLOT_H - 5, Math.max(PAD_T + 5, py(p.v)));\r\n return {\r\n x: px(p.t),\r\n y: py(p.v),\r\n t: { text: t, cx, w: wt },\r\n v: { text: v, cy, w: wv },\r\n };\r\n});\r\n\r\ninterface PointerSample {\r\n clientX: number;\r\n clientY: number;\r\n shiftKey: boolean;\r\n}\r\n\r\n/**\r\n * Pointer coordinates in curve units as they are: no snapping, rounding or bounds.\r\n * Координаты указателя в единицах кривой, как есть: без прилипания, округления и границ.\r\n */\r\nfunction rawCurve(e: PointerSample): { t: number; v: number } {\r\n const r = svg.value!.getBoundingClientRect();\r\n const x = ((e.clientX - r.left) / r.width) * W;\r\n const y = ((e.clientY - r.top) / r.height) * H;\r\n const { min, max } = bounds.value;\r\n return { t: (x - PAD_L) / PLOT_W, v: min + (1 - (y - PAD_T) / PLOT_H) * (max - min) };\r\n}\r\n\r\n/**\r\n * Pointer coordinates in curve units; Shift temporarily flips the snapping mode.\r\n * Координаты указателя в единицах кривой; Shift временно меняет режим шага.\r\n */\r\nfunction toCurve(e: PointerSample): { t: number; v: number } {\r\n let { t: tt, v } = rawCurve(e);\r\n if (props.snap !== e.shiftKey) {\r\n tt = snapTo(tt, props.stepT);\r\n v = snapTo(v, stepV.value);\r\n }\r\n return { t: roundTo(tt, props.precision), v: clampTo(roundTo(v, props.precision), props.min, props.max) };\r\n}\r\n\r\nlet dragging = -1;\r\nlet lastPointer: PointerSample = { clientX: 0, clientY: 0, shiftKey: false };\r\n\r\n/**\r\n * The point follows the pointer: both when it moves and when the view moved under a still pointer.\r\n * Точка идёт за указателем: и при его движении, и когда вид уехал под неподвижным указателем.\r\n */\r\nfunction followPointer() {\r\n if (dragging < 0) return;\r\n const { t: tt, v } = toCurve(lastPointer);\r\n emit('update:modelValue', movePoint(points.value, dragging, tt, v));\r\n}\r\n\r\n// Dragging a point to the top/bottom edge of the plot: the view by value follows (by time it is always 0…1).\r\n// The field bounds are not crossed: with min and max set the view stands still.\r\n// Тянем точку к верхнему/нижнему краю графика: вид по значению едет следом (по времени он всегда 0…1).\r\n// Границы поля не пересекаем: при заданных min и max вид стоит.\r\nconst scroller = createEdgeScroller({\r\n bounds: () => svg.value?.getBoundingClientRect() ?? null,\r\n pointer: () => [lastPointer.clientX, lastPointer.clientY],\r\n enabled: () => dragging >= 0,\r\n zone: 18,\r\n maxSpeed: 240,\r\n onScroll: (_dx, dy) => {\r\n const base = frozen.value;\r\n const r = svg.value?.getBoundingClientRect();\r\n if (!base || !r) return;\r\n // The visible area moved down by dy px: the view values decreased\r\n // Видимая область уехала вниз на dy px: значения вида уменьшились\r\n const dv = ((dy * H) / r.height / PLOT_H) * (base.max - base.min);\r\n const lo = props.min === undefined ? -Infinity : props.min - base.min;\r\n const hi = props.max === undefined ? Infinity : props.max - base.max;\r\n shift.value = Math.min(hi, Math.max(lo, shift.value - dv));\r\n followPointer();\r\n },\r\n});\r\nonBeforeUnmount(scroller.stop);\r\n\r\nfunction onDown(e: PointerEvent, i: number) {\r\n emit('update:selected', i);\r\n if (e.altKey) {\r\n emit('update:modelValue', removePoint(points.value, i));\r\n emit('update:selected', 0);\r\n emit('commit');\r\n return;\r\n }\r\n dragging = i;\r\n lastPointer = e;\r\n shift.value = 0;\r\n frozen.value = valueBounds(points.value, props.min, props.max);\r\n try {\r\n (e.currentTarget as Element).setPointerCapture(e.pointerId);\r\n } catch {\r\n // the pointer has already gone or the capture is unavailable: dragging works without it\r\n // указатель уже ушёл или захват недоступен: тянуть можно и без него\r\n }\r\n}\r\n\r\nfunction onMove(e: PointerEvent) {\r\n if (dragging < 0) return;\r\n lastPointer = e;\r\n followPointer();\r\n scroller.kick();\r\n}\r\n\r\nfunction onUp() {\r\n if (dragging < 0) return;\r\n dragging = -1;\r\n scroller.stop();\r\n frozen.value = null;\r\n shift.value = 0;\r\n emit('commit');\r\n}\r\n\r\n//--------------------------------------------------\r\n// Handles of the cubic Bezier curve of the selected segment\r\n// Ручки кубической кривой Безье у выбранного участка\r\n\r\n/**\r\n * The segment that starts at the selected point and follows a Bezier: only it has handles (and only if the segment has height).\r\n * Участок, который начинается в выбранной точке и идёт по Безье: ручки есть только у него (и только если у участка есть высота).\r\n */\r\nconst bezierSegment = computed(() => {\r\n const i = Math.min(props.selected, points.value.length - 1);\r\n const a = points.value[i];\r\n const b = points.value[i + 1];\r\n if (!a || !b || typeof a.ease !== 'object' || Math.abs(b.v - a.v) < 1e-9 || b.t - a.t <= 0) return null;\r\n return { i, a, b, bezier: a.ease.bezier };\r\n});\r\n\r\n/**\r\n * The two handles of the segment in plot coordinates.\r\n * Две ручки участка в координатах плота.\r\n */\r\nconst bezierHandles = computed(() => {\r\n const s = bezierSegment.value;\r\n if (!s) return [];\r\n const [x1, y1, x2, y2] = s.bezier;\r\n return [\r\n { n: 0, t: s.a.t + x1 * (s.b.t - s.a.t), v: s.a.v + y1 * (s.b.v - s.a.v), from: s.a },\r\n { n: 1, t: s.a.t + x2 * (s.b.t - s.a.t), v: s.a.v + y2 * (s.b.v - s.a.v), from: s.b },\r\n ];\r\n});\r\n\r\n/**\r\n * Starts of segments with a Bezier: the \"B\" mark is drawn above them.\r\n * Начала участков с Безье: над ними рисуется метка «B».\r\n */\r\nconst bezierMarks = computed(() => points.value.flatMap((p, i) => (typeof p.ease === 'object' && i < points.value.length - 1 ? [{ i, t: p.t, v: p.v }] : [])));\r\n\r\nconst round2 = (x: number) => Math.round(x * 100) / 100;\r\nconst BEZIER_STEP = 0.05;\r\n\r\n/**\r\n * Handle `n` is put at (x, y) of the normalised segment: x in 0…1, y free within reasonable limits (overshoot).\r\n * Ручка `n` ставится в (x, y) нормализованного участка: x в 0…1, y свободный в разумных пределах (заступ).\r\n */\r\nfunction setBezierHandle(n: 0 | 1, x: number, y: number, commitNow = false) {\r\n const s = bezierSegment.value;\r\n if (!s) return;\r\n const next: [number, number, number, number] = [...s.bezier];\r\n next[n * 2] = Math.min(1, Math.max(0, round2(x)));\r\n next[n * 2 + 1] = Math.min(3, Math.max(-2, round2(y)));\r\n emit('update:modelValue', setEase(points.value, s.i, { bezier: next }));\r\n if (commitNow) emit('commit');\r\n}\r\n\r\nlet handleDrag = -1;\r\n\r\nfunction onHandleDown(e: PointerEvent, n: number) {\r\n handleDrag = n;\r\n frozen.value = valueBounds(points.value, props.min, props.max);\r\n try {\r\n (e.currentTarget as Element).setPointerCapture(e.pointerId);\r\n } catch {\r\n // the pointer has already gone or the capture is unavailable: dragging works without it\r\n // указатель уже ушёл или захват недоступен: тянуть можно и без него\r\n }\r\n}\r\n\r\nfunction onHandleMove(e: PointerEvent) {\r\n const s = bezierSegment.value;\r\n if (handleDrag < 0 || !s) return;\r\n const { t, v } = rawCurve(e);\r\n setBezierHandle(handleDrag as 0 | 1, (t - s.a.t) / (s.b.t - s.a.t), (v - s.a.v) / (s.b.v - s.a.v));\r\n}\r\n\r\nfunction onHandleUp() {\r\n if (handleDrag < 0) return;\r\n handleDrag = -1;\r\n frozen.value = null;\r\n emit('commit');\r\n}\r\n\r\n/**\r\n * Arrows on a handle move it by a step (Shift larger): left and right along x, up and down along y.\r\n * Стрелки на ручке сдвигают её на шаг (Shift крупнее): влево и вправо по x, вверх и вниз по y.\r\n */\r\nfunction onHandleKey(e: KeyboardEvent, n: number) {\r\n const s = bezierSegment.value;\r\n const arrows: Record<string, [number, number]> = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, 1], ArrowDown: [0, -1] };\r\n const d = arrows[e.key];\r\n if (!s || !d) return;\r\n e.preventDefault();\r\n e.stopPropagation();\r\n const k = BEZIER_STEP * (e.shiftKey ? 5 : 1);\r\n setBezierHandle(n as 0 | 1, s.bezier[n * 2]! + d[0] * k, s.bezier[n * 2 + 1]! + d[1] * k, true);\r\n}\r\n\r\n/**\r\n * A double click on the plot must not select the page text around it.\r\n * Двойной клик по графику не должен выделять текст страницы вокруг.\r\n */\r\nfunction noSelect(e: MouseEvent) {\r\n if (e.detail > 1) e.preventDefault();\r\n}\r\n\r\nfunction onDouble(e: MouseEvent) {\r\n const { t: tt, v } = toCurve(e);\r\n const r = addPoint(points.value, tt, v);\r\n emit('update:selected', r.index);\r\n emit('update:modelValue', r.points);\r\n emit('commit');\r\n}\r\n\r\n/**\r\n * The arrow step with Shift: this many times larger.\r\n * Шаг стрелки с Shift: во столько раз крупнее.\r\n */\r\nconst COARSE = 5;\r\n\r\n/**\r\n * Moves point `i` by `dx` steps in time and `dy` steps in value (grid steps), with snapping, rounding and bounds.\r\n * Сдвигает точку `i` на `dx` шагов по времени и `dy` шагов по значению (шаги сетки), с прижатием, округлением и границами.\r\n */\r\nfunction nudge(i: number, dx: number, dy: number, coarse: boolean) {\r\n const p = points.value[i];\r\n if (!p) return;\r\n const k = coarse ? COARSE : 1;\r\n const tt = roundTo(snapTo(p.t + dx * k * props.stepT, props.stepT), props.precision);\r\n const v = clampTo(roundTo(snapTo(p.v + dy * k * stepV.value, stepV.value), props.precision), props.min, props.max);\r\n emit('update:modelValue', movePoint(points.value, i, tt, v));\r\n emit('commit');\r\n}\r\n\r\n/**\r\n * Insert adds a point between the selected one and the next (for the last: between it and the previous) on the curve itself.\r\n * Insert добавляет точку между выбранной и следующей (у последней: между ней и предыдущей) на самой кривой.\r\n */\r\n/**\r\n * Focus on point `i` after a re-render: keys go to the selected point, and focus must not stay on the old one.\r\n * Фокус на точку `i` после перерисовки: клавиши идут к той точке, что выбрана, и фокус не должен оставаться на старой.\r\n */\r\nfunction focusDot(i: number) {\r\n void nextTick(() => svg.value?.querySelectorAll<SVGElement>('.tx-curve-dot')[i]?.focus());\r\n}\r\n\r\nfunction insertAfter(i: number) {\r\n const a = points.value[i];\r\n const b = points.value[i + 1] ?? points.value[i - 1];\r\n if (!a || !b) return;\r\n const r = addPoint(points.value, roundTo((a.t + b.t) / 2, props.precision));\r\n emit('update:selected', r.index);\r\n emit('update:modelValue', r.points);\r\n emit('commit');\r\n focusDot(r.index);\r\n}\r\n\r\nfunction removeAt(i: number) {\r\n const next = Math.max(0, i - 1);\r\n emit('update:modelValue', removePoint(points.value, i));\r\n emit('update:selected', next);\r\n emit('commit');\r\n focusDot(next);\r\n}\r\n\r\n/**\r\n * Point keys (focus on it): arrows move by a grid step, Shift larger; Insert adds, Delete removes.\r\n * Клавиши точки (фокус на ней): стрелки двигают на шаг сетки, Shift крупнее; Insert добавляет, Delete убирает.\r\n */\r\nfunction onKey(e: KeyboardEvent) {\r\n // the point that has focus; if the key came from the field itself (after a click on it), then the selected one\r\n // точка, на которой фокус; если клавиша пришла с самого поля (после клика по нему), то выбранная\r\n const target = (e.target as Element | null)?.closest('.tx-curve-dot');\r\n const index = target ? Number(target.getAttribute('data-index')) : NaN;\r\n const i = Number.isInteger(index) ? index : Math.min(props.selected, points.value.length - 1);\r\n const arrows: Record<string, [number, number]> = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, 1], ArrowDown: [0, -1] };\r\n const move = arrows[e.key];\r\n if (move) {\r\n e.preventDefault();\r\n nudge(i, move[0], move[1], e.shiftKey);\r\n } else if (e.key === 'Insert') {\r\n e.preventDefault();\r\n insertAfter(i);\r\n } else if (e.key === 'Delete' || e.key === 'Backspace') {\r\n e.preventDefault();\r\n removeAt(i);\r\n }\r\n}\r\n\r\nconst labelOf = (i: number, p: CurvePoint) => (props.pointLabel ? props.pointLabel(i, p) : `Point ${i + 1}: ${fmtT(p.t)}, ${fmt(p.v)}`);\r\n</script>\r\n\r\n<template>\r\n <svg ref=\"svg\" class=\"tx-curve\" :viewBox=\"`0 0 ${W} ${H}`\" :title=\"hint\" tabindex=\"-1\" role=\"group\" @dblclick.self=\"onDouble\" @mousedown=\"noSelect\" @keydown=\"onKey\">\r\n <!-- fine grid: the same steps as snapping / мелкая сетка: те же шаги, что у прилипания -->\r\n <line v-for=\"x in gridT\" :key=\"`gt${x}`\" class=\"tx-curve-grid\" :class=\"{ major: isMajorT(x) }\" :x1=\"px(x)\" :x2=\"px(x)\" :y1=\"PAD_T\" :y2=\"H - PAD_B\" />\r\n <line v-for=\"v in gridV\" :key=\"`gv${v}`\" class=\"tx-curve-grid\" :class=\"{ major: isMajorV(v) }\" :x1=\"PAD_L\" :x2=\"W - PAD_R\" :y1=\"py(v)\" :y2=\"py(v)\" />\r\n\r\n <text v-for=\"(v, i) in labelsV\" :key=\"`lv${v}`\" class=\"tx-curve-label\" :class=\"{ edge: v === 0 || i === 0 || i === labelsV.length - 1 }\" :x=\"PAD_L - 4\" :y=\"py(v)\" text-anchor=\"end\" dominant-baseline=\"middle\">{{ fmt(v) }}</text>\r\n <text v-for=\"x in labelsT\" :key=\"`lt${x}`\" class=\"tx-curve-label\" :class=\"{ edge: x === 0 || x === 1 }\" :x=\"px(x)\" :y=\"H - 4\" :text-anchor=\"x === 0 ? 'start' : x === 1 ? 'end' : 'middle'\">{{ fmtT(x) }}</text>\r\n\r\n <g v-if=\"tags && guides !== 'off'\" class=\"tx-curve-tags\" aria-hidden=\"true\">\r\n <line class=\"tx-curve-guide\" :x1=\"tags.x\" :x2=\"tags.x\" :y1=\"tags.y\" :y2=\"PAD_T + PLOT_H\" />\r\n <line class=\"tx-curve-guide\" :x1=\"PAD_L\" :x2=\"tags.x\" :y1=\"tags.y\" :y2=\"tags.y\" />\r\n <template v-if=\"guides === 'values'\">\r\n <rect class=\"tx-curve-tag-bg\" :x=\"tags.t.cx - tags.t.w / 2\" :y=\"H - 12\" :width=\"tags.t.w\" height=\"11\" rx=\"2\" />\r\n <text class=\"tx-curve-tag\" :x=\"tags.t.cx\" :y=\"H - 4\" text-anchor=\"middle\">{{ tags.t.text }}</text>\r\n <rect class=\"tx-curve-tag-bg\" :x=\"PAD_L - 3 - tags.v.w\" :y=\"tags.v.cy - 5.5\" :width=\"tags.v.w\" height=\"11\" rx=\"2\" />\r\n <text class=\"tx-curve-tag\" :x=\"PAD_L - 5\" :y=\"tags.v.cy\" text-anchor=\"end\" dominant-baseline=\"middle\">{{ tags.v.text }}</text>\r\n </template>\r\n </g>\r\n\r\n <path class=\"tx-curve-line\" :d=\"path\" />\r\n\r\n <!-- The \"B\" mark above the start of a Bezier segment: shows the point has handles even when it is not selected / Метка «B» над началом участка с Безье: видно, что у точки есть ручки, даже когда она не выбрана -->\r\n <text v-for=\"m in bezierMarks\" :key=\"`b${m.i}`\" class=\"tx-curve-mark\" :x=\"px(m.t)\" :y=\"py(m.v) - 8\" text-anchor=\"middle\" aria-hidden=\"true\">B</text>\r\n\r\n <g v-if=\"bezierHandles.length\" class=\"tx-curve-bezier\">\r\n <template v-for=\"h in bezierHandles\" :key=\"h.n\">\r\n <line class=\"tx-curve-arm\" :x1=\"px(h.from.t)\" :y1=\"py(h.from.v)\" :x2=\"px(h.t)\" :y2=\"py(h.v)\" />\r\n <circle\r\n class=\"tx-curve-handle\"\r\n :cx=\"px(h.t)\"\r\n :cy=\"py(h.v)\"\r\n r=\"4\"\r\n tabindex=\"0\"\r\n role=\"slider\"\r\n :aria-label=\"handleLabel ? handleLabel(h.n + 1, bezierSegment!.i) : `Bezier handle ${h.n + 1}`\"\r\n @pointerdown.stop=\"onHandleDown($event, h.n)\"\r\n @pointermove=\"onHandleMove\"\r\n @pointerup=\"onHandleUp\"\r\n @pointercancel=\"onHandleUp\"\r\n @keydown=\"onHandleKey($event, h.n)\"\r\n />\r\n </template>\r\n </g>\r\n <circle\r\n v-for=\"(p, i) in points\"\r\n :key=\"i\"\r\n class=\"tx-curve-dot\"\r\n :class=\"{ on: i === selected }\"\r\n :cx=\"px(p.t)\"\r\n :cy=\"py(p.v)\"\r\n r=\"5\"\r\n :data-index=\"i\"\r\n tabindex=\"0\"\r\n role=\"button\"\r\n :aria-label=\"labelOf(i, p)\"\r\n @focus=\"emit('update:selected', i)\"\r\n @pointerdown.stop=\"onDown($event, i)\"\r\n @pointermove=\"onMove\"\r\n @pointerup=\"onUp\"\r\n @pointercancel=\"onUp\"\r\n />\r\n </svg>\r\n</template>\r\n\r\n<style>\r\n/*\r\n * Configured with CSS variables on any ancestor:\r\n * Настройка через CSS-переменные на любом предке:\r\n * --tx-curve-bg, --tx-curve-border, --tx-curve-grid, --tx-curve-label, --tx-curve-accent,\r\n * --tx-curve-text (the numbers at the ends of the axes: start and end of the scale, brighter than the rest),\r\n * --tx-curve-radius (the corners of the plot, 4px by default),\r\n * --tx-curve-dot-opacity (opacity of unselected points, 0.3 by default).\r\n * --tx-curve-text (цифры у краёв осей: начало и конец шкалы, ярче остальных),\r\n * --tx-curve-radius (углы графика, по умолчанию 4px),\r\n * --tx-curve-dot-opacity (непрозрачность невыбранных точек, по умолчанию 0.3).\r\n */\r\n.tx-curve {\r\n display: block;\r\n width: 100%;\r\n height: auto;\r\n border: 1px solid var(--tx-curve-border, #2a2d33);\r\n border-radius: var(--tx-curve-radius, 4px);\r\n background: var(--tx-curve-bg, #15171b);\r\n touch-action: none;\r\n user-select: none;\r\n outline: none;\r\n}\r\n\r\n.tx-curve-grid {\r\n pointer-events: none; /* otherwise a double click hits the grid line, not the field / иначе двойной клик попадает в линию сетки, а не в поле */\r\n stroke: var(--tx-curve-grid, #2a2d33);\r\n stroke-width: 0.5;\r\n opacity: 0.45;\r\n}\r\n\r\n.tx-curve-grid.major {\r\n stroke-width: 1;\r\n opacity: 1;\r\n}\r\n\r\n.tx-curve-guide {\r\n stroke: var(--tx-curve-accent, #4fc3f7);\r\n stroke-width: 1;\r\n stroke-dasharray: 2 3;\r\n opacity: 0.45;\r\n pointer-events: none;\r\n}\r\n\r\n.tx-curve-tag-bg {\r\n fill: var(--tx-curve-bg, #15171b);\r\n pointer-events: none;\r\n}\r\n\r\n.tx-curve-tag {\r\n fill: var(--tx-curve-accent, #4fc3f7);\r\n font-size: 8px;\r\n font-weight: 700;\r\n pointer-events: none;\r\n user-select: none;\r\n}\r\n\r\n.tx-curve-label.edge {\r\n fill: var(--tx-curve-text, #d6d9e0);\r\n}\r\n\r\n.tx-curve-label {\r\n fill: var(--tx-curve-label, #8b929c);\r\n font-size: 8px;\r\n pointer-events: none;\r\n user-select: none;\r\n}\r\n\r\n.tx-curve-line {\r\n fill: none;\r\n stroke: var(--tx-curve-accent, #4fc3f7);\r\n stroke-width: 2;\r\n pointer-events: none;\r\n}\r\n\r\n.tx-curve-mark {\r\n fill: var(--tx-curve-accent, #4fc3f7);\r\n font: 600 9px/1 system-ui, sans-serif;\r\n pointer-events: none;\r\n user-select: none;\r\n}\r\n\r\n.tx-curve-arm {\r\n stroke: var(--tx-curve-label, #8b929c);\r\n stroke-width: 1;\r\n stroke-dasharray: 3 2;\r\n pointer-events: none;\r\n}\r\n\r\n.tx-curve-handle {\r\n fill: var(--tx-curve-label, #8b929c);\r\n stroke: var(--tx-curve-bg, #15171b);\r\n stroke-width: 1.5;\r\n cursor: grab;\r\n}\r\n\r\n.tx-curve-handle:active {\r\n cursor: grabbing;\r\n}\r\n\r\n.tx-curve-handle:hover,\r\n.tx-curve-handle:focus-visible {\r\n fill: var(--tx-curve-accent, #4fc3f7);\r\n outline: none;\r\n}\r\n\r\n.tx-curve-dot {\r\n fill: var(--tx-curve-bg, #15171b);\r\n stroke: var(--tx-curve-accent, #4fc3f7);\r\n stroke-width: 2;\r\n opacity: var(--tx-curve-dot-opacity, 0.3);\r\n cursor: grab;\r\n}\r\n\r\n.tx-curve-dot:active {\r\n cursor: grabbing;\r\n}\r\n\r\n.tx-curve-dot:focus {\r\n outline: none;\r\n}\r\n\r\n/* keyboard focus: a thicker outline and a glow (browsers draw the outline of SVG shapes differently) / фокус с клавиатуры: утолщённая обводка и свечение (контур у SVG-форм браузеры рисуют по-разному) */\r\n.tx-curve-dot:focus-visible {\r\n stroke-width: 3;\r\n filter: drop-shadow(0 0 3px var(--tx-curve-accent, #4fc3f7));\r\n opacity: 1;\r\n}\r\n\r\n.tx-curve-dot.on,\r\n.tx-curve-dot:hover {\r\n fill: var(--tx-curve-accent, #4fc3f7);\r\n opacity: 1;\r\n}\r\n</style>\r\n","<script lang=\"ts\" setup>\r\nimport { computed, nextTick, onBeforeUnmount, ref } from 'vue';\r\nimport { createEdgeScroller } from '../edgescroll';\r\nimport { clampTo, niceStep, roundTo, snapTo, ticks } from '../num';\r\nimport { addPoint, movePoint, removePoint, sampleSegment, setEase, valueBounds, type CurveGuides, type CurvePoint } from './ops';\r\n\r\nconst props = withDefaults(\r\n defineProps<{\r\n /**\r\n * Curve points in ascending t (at least two).\r\n * Точки кривой по возрастанию t (минимум две).\r\n */\r\n modelValue: readonly CurvePoint[];\r\n /**\r\n * Index of the selected point.\r\n * Индекс выбранной точки.\r\n */\r\n selected?: number;\r\n /**\r\n * Allowed values: they fix the plot view and do not let a point be dragged past the bound.\r\n * Допустимые значения: фиксируют вид графика и не дают утащить точку за границу.\r\n */\r\n min?: number;\r\n max?: number;\r\n /**\r\n * How many decimals to keep in t and v; not set means do not round.\r\n * Сколько знаков после запятой оставлять у t и v; не задано — не обрезать.\r\n */\r\n precision?: number;\r\n /**\r\n * Snapping to the grid (Shift flips the mode for the moment).\r\n * Прилипание к сетке (Shift на время меняет режим).\r\n */\r\n snap?: boolean;\r\n /**\r\n * The time step and the distance between labelled lines.\r\n * Шаг по времени и расстояние между подписанными линиями.\r\n */\r\n stepT?: number;\r\n majorT?: number;\r\n /**\r\n * A hint on hover over the field.\r\n * Подсказка при наведении на поле.\r\n */\r\n hint?: string;\r\n /**\r\n * The point label for screen readers; \"Point 1: t, v\" by default.\r\n * Подпись точки для скринридеров; по умолчанию «Point 1: t, v».\r\n */\r\n pointLabel?: (index: number, point: CurvePoint) => string;\r\n /**\r\n * How time is written: on the time axis, on the tag of the selected point and in the default point label. `t` is 0…1, the\r\n * editor's own time; a curve over years or seconds says so here (`(t) => `${Math.round(t * 14)} y``). By default the number\r\n * itself.\r\n * Как записывается время: на оси времени, на метке выбранной точки и в подписи точки по умолчанию. `t` — от 0 до 1, собственное\r\n * время редактора; кривая по годам или секундам говорит это здесь. По умолчанию само число.\r\n */\r\n formatT?: (t: number) => string;\r\n /**\r\n * Guides from the selected point to the axes: `off` none, `lines` dashed lines only, `values` lines and the point values on the axes.\r\n * `lines` by default: noticeable, but not overloaded.\r\n * Направляющие от выбранной точки к осям: `off` нет, `lines` только пунктирные линии, `values` линии и значения точки на осях.\r\n * По умолчанию `lines`: заметно, но не перегружает.\r\n */\r\n guides?: CurveGuides;\r\n /**\r\n * The label of a Bezier handle for screen readers (n: 1 or 2); \"Bezier handle n\" by default.\r\n * Подпись ручки Безье для скринридеров (n: 1 или 2); по умолчанию «Bezier handle n».\r\n */\r\n handleLabel?: (n: number, index: number) => string;\r\n }>(),\r\n { selected: 0, snap: true, stepT: 0.05, majorT: 0.25, guides: 'lines' },\r\n);\r\nconst emit = defineEmits<{\r\n 'update:modelValue': [value: CurvePoint[]];\r\n 'update:selected': [index: number];\r\n /**\r\n * An edit is finished (a point was released, added, removed): the moment to record into history.\r\n * Правка закончена (отпустили точку, добавили, убрали): момент для записи в историю.\r\n */\r\n commit: [];\r\n}>();\r\n\r\nconst W = 280;\r\nconst H = 132;\r\nconst PAD_L = 30;\r\nconst PAD_R = 10;\r\nconst PAD_T = 10;\r\nconst PAD_B = 16;\r\nconst PLOT_W = W - PAD_L - PAD_R;\r\nconst PLOT_H = H - PAD_T - PAD_B;\r\n\r\nconst svg = ref<SVGSVGElement | null>(null);\r\n\r\nconst points = computed(() => props.modelValue);\r\n// The limits are remembered for the duration of a drag: otherwise the plot would \"float\" under the hand\r\n// Пределы запоминаем на время перетаскивания: иначе график «плыл» бы под рукой\r\nconst frozen = ref<{ min: number; max: number } | null>(null);\r\n// The view shift by value: accumulated by auto-scroll at the edge while a point is dragged\r\n// Сдвиг вида по значению: накапливает автопрокрутка у края, пока тянут точку\r\nconst shift = ref(0);\r\nconst bounds = computed(() => (frozen.value ? { min: frozen.value.min + shift.value, max: frozen.value.max + shift.value } : valueBounds(points.value, props.min, props.max)));\r\nconst span = computed(() => bounds.value.max - bounds.value.min);\r\n\r\nconst majorV = computed(() => niceStep(span.value, 4));\r\nconst stepV = computed(() => niceStep(span.value, 20));\r\nconst gridT = computed(() => ticks(0, 1, props.stepT));\r\nconst gridV = computed(() => ticks(bounds.value.min, bounds.value.max, stepV.value));\r\nconst labelsV = computed(() => ticks(bounds.value.min, bounds.value.max, majorV.value));\r\nconst labelsT = computed(() => ticks(0, 1, props.majorT));\r\nconst isMajorT = (x: number) => Math.abs(x / props.majorT - Math.round(x / props.majorT)) < 1e-6;\r\nconst isMajorV = (v: number) => Math.abs(v / majorV.value - Math.round(v / majorV.value)) < 1e-6;\r\n\r\nconst px = (tt: number) => PAD_L + tt * PLOT_W;\r\nconst py = (v: number) => PAD_T + (1 - (v - bounds.value.min) / span.value) * PLOT_H;\r\n// Segments are drawn by their transitions: a straight one has two ends, smooth ones dozens of pieces, a step a corner\r\n// Участки рисуются по своим переходам: у прямой два конца, у плавных десятки отрезков, у ступеньки угол\r\nconst path = computed(() => {\r\n const pts = points.value;\r\n const out: string[] = [];\r\n for (let i = 0; i < pts.length - 1; i++) {\r\n sampleSegment(pts[i]!, pts[i + 1]!).forEach((p, k) => out.push(`${i === 0 && k === 0 ? 'M' : 'L'} ${px(p.t).toFixed(1)} ${py(p.v).toFixed(1)}`));\r\n }\r\n return out.join(' ');\r\n});\r\nconst fmt = (n: number) => String(Math.round(n * 1000) / 1000);\r\nconst fmtT = (tt: number) => (props.formatT ? props.formatT(tt) : fmt(tt));\r\n\r\n// The values of the selected point on the axes: time under the plot, value on the left. They show while the point is dragged, so there is no need to look for the fields.\r\n// Значения выбранной точки на осях: время под графиком, значение слева. Они видны, пока точку тянут, и не надо искать глазами поля.\r\nconst CHAR_W = 4.6;\r\nconst tagWidth = (text: string) => text.length * CHAR_W + 5;\r\nconst tags = computed(() => {\r\n const p = points.value[Math.min(props.selected, points.value.length - 1)];\r\n if (!p) return null;\r\n const t = fmtT(p.t);\r\n const v = fmt(p.v);\r\n const wt = tagWidth(t);\r\n const wv = tagWidth(v);\r\n const cx = Math.min(W - wt / 2 - 1, Math.max(wt / 2 + 1, px(p.t)));\r\n const cy = Math.min(PAD_T + PLOT_H - 5, Math.max(PAD_T + 5, py(p.v)));\r\n return {\r\n x: px(p.t),\r\n y: py(p.v),\r\n t: { text: t, cx, w: wt },\r\n v: { text: v, cy, w: wv },\r\n };\r\n});\r\n\r\ninterface PointerSample {\r\n clientX: number;\r\n clientY: number;\r\n shiftKey: boolean;\r\n}\r\n\r\n/**\r\n * Pointer coordinates in curve units as they are: no snapping, rounding or bounds.\r\n * Координаты указателя в единицах кривой, как есть: без прилипания, округления и границ.\r\n */\r\nfunction rawCurve(e: PointerSample): { t: number; v: number } {\r\n const r = svg.value!.getBoundingClientRect();\r\n const x = ((e.clientX - r.left) / r.width) * W;\r\n const y = ((e.clientY - r.top) / r.height) * H;\r\n const { min, max } = bounds.value;\r\n return { t: (x - PAD_L) / PLOT_W, v: min + (1 - (y - PAD_T) / PLOT_H) * (max - min) };\r\n}\r\n\r\n/**\r\n * Pointer coordinates in curve units; Shift temporarily flips the snapping mode.\r\n * Координаты указателя в единицах кривой; Shift временно меняет режим шага.\r\n */\r\nfunction toCurve(e: PointerSample): { t: number; v: number } {\r\n let { t: tt, v } = rawCurve(e);\r\n if (props.snap !== e.shiftKey) {\r\n tt = snapTo(tt, props.stepT);\r\n v = snapTo(v, stepV.value);\r\n }\r\n return { t: roundTo(tt, props.precision), v: clampTo(roundTo(v, props.precision), props.min, props.max) };\r\n}\r\n\r\nlet dragging = -1;\r\nlet lastPointer: PointerSample = { clientX: 0, clientY: 0, shiftKey: false };\r\n\r\n/**\r\n * The point follows the pointer: both when it moves and when the view moved under a still pointer.\r\n * Точка идёт за указателем: и при его движении, и когда вид уехал под неподвижным указателем.\r\n */\r\nfunction followPointer() {\r\n if (dragging < 0) return;\r\n const { t: tt, v } = toCurve(lastPointer);\r\n emit('update:modelValue', movePoint(points.value, dragging, tt, v));\r\n}\r\n\r\n// Dragging a point to the top/bottom edge of the plot: the view by value follows (by time it is always 0…1).\r\n// The field bounds are not crossed: with min and max set the view stands still.\r\n// Тянем точку к верхнему/нижнему краю графика: вид по значению едет следом (по времени он всегда 0…1).\r\n// Границы поля не пересекаем: при заданных min и max вид стоит.\r\nconst scroller = createEdgeScroller({\r\n bounds: () => svg.value?.getBoundingClientRect() ?? null,\r\n pointer: () => [lastPointer.clientX, lastPointer.clientY],\r\n enabled: () => dragging >= 0,\r\n zone: 18,\r\n maxSpeed: 240,\r\n onScroll: (_dx, dy) => {\r\n const base = frozen.value;\r\n const r = svg.value?.getBoundingClientRect();\r\n if (!base || !r) return;\r\n // The visible area moved down by dy px: the view values decreased\r\n // Видимая область уехала вниз на dy px: значения вида уменьшились\r\n const dv = ((dy * H) / r.height / PLOT_H) * (base.max - base.min);\r\n const lo = props.min === undefined ? -Infinity : props.min - base.min;\r\n const hi = props.max === undefined ? Infinity : props.max - base.max;\r\n shift.value = Math.min(hi, Math.max(lo, shift.value - dv));\r\n followPointer();\r\n },\r\n});\r\nonBeforeUnmount(scroller.stop);\r\n\r\nfunction onDown(e: PointerEvent, i: number) {\r\n emit('update:selected', i);\r\n if (e.altKey) {\r\n emit('update:modelValue', removePoint(points.value, i));\r\n emit('update:selected', 0);\r\n emit('commit');\r\n return;\r\n }\r\n dragging = i;\r\n lastPointer = e;\r\n shift.value = 0;\r\n frozen.value = valueBounds(points.value, props.min, props.max);\r\n try {\r\n (e.currentTarget as Element).setPointerCapture(e.pointerId);\r\n } catch {\r\n // the pointer has already gone or the capture is unavailable: dragging works without it\r\n // указатель уже ушёл или захват недоступен: тянуть можно и без него\r\n }\r\n}\r\n\r\nfunction onMove(e: PointerEvent) {\r\n if (dragging < 0) return;\r\n lastPointer = e;\r\n followPointer();\r\n scroller.kick();\r\n}\r\n\r\nfunction onUp() {\r\n if (dragging < 0) return;\r\n dragging = -1;\r\n scroller.stop();\r\n frozen.value = null;\r\n shift.value = 0;\r\n emit('commit');\r\n}\r\n\r\n//--------------------------------------------------\r\n// Handles of the cubic Bezier curve of the selected segment\r\n// Ручки кубической кривой Безье у выбранного участка\r\n\r\n/**\r\n * The segment that starts at the selected point and follows a Bezier: only it has handles (and only if the segment has height).\r\n * Участок, который начинается в выбранной точке и идёт по Безье: ручки есть только у него (и только если у участка есть высота).\r\n */\r\nconst bezierSegment = computed(() => {\r\n const i = Math.min(props.selected, points.value.length - 1);\r\n const a = points.value[i];\r\n const b = points.value[i + 1];\r\n if (!a || !b || typeof a.ease !== 'object' || Math.abs(b.v - a.v) < 1e-9 || b.t - a.t <= 0) return null;\r\n return { i, a, b, bezier: a.ease.bezier };\r\n});\r\n\r\n/**\r\n * The two handles of the segment in plot coordinates.\r\n * Две ручки участка в координатах плота.\r\n */\r\nconst bezierHandles = computed(() => {\r\n const s = bezierSegment.value;\r\n if (!s) return [];\r\n const [x1, y1, x2, y2] = s.bezier;\r\n return [\r\n { n: 0, t: s.a.t + x1 * (s.b.t - s.a.t), v: s.a.v + y1 * (s.b.v - s.a.v), from: s.a },\r\n { n: 1, t: s.a.t + x2 * (s.b.t - s.a.t), v: s.a.v + y2 * (s.b.v - s.a.v), from: s.b },\r\n ];\r\n});\r\n\r\n/**\r\n * Starts of segments with a Bezier: the \"B\" mark is drawn above them.\r\n * Начала участков с Безье: над ними рисуется метка «B».\r\n */\r\nconst bezierMarks = computed(() => points.value.flatMap((p, i) => (typeof p.ease === 'object' && i < points.value.length - 1 ? [{ i, t: p.t, v: p.v }] : [])));\r\n\r\nconst round2 = (x: number) => Math.round(x * 100) / 100;\r\nconst BEZIER_STEP = 0.05;\r\n\r\n/**\r\n * Handle `n` is put at (x, y) of the normalised segment: x in 0…1, y free within reasonable limits (overshoot).\r\n * Ручка `n` ставится в (x, y) нормализованного участка: x в 0…1, y свободный в разумных пределах (заступ).\r\n */\r\nfunction setBezierHandle(n: 0 | 1, x: number, y: number, commitNow = false) {\r\n const s = bezierSegment.value;\r\n if (!s) return;\r\n const next: [number, number, number, number] = [...s.bezier];\r\n next[n * 2] = Math.min(1, Math.max(0, round2(x)));\r\n next[n * 2 + 1] = Math.min(3, Math.max(-2, round2(y)));\r\n emit('update:modelValue', setEase(points.value, s.i, { bezier: next }));\r\n if (commitNow) emit('commit');\r\n}\r\n\r\nlet handleDrag = -1;\r\n\r\nfunction onHandleDown(e: PointerEvent, n: number) {\r\n handleDrag = n;\r\n frozen.value = valueBounds(points.value, props.min, props.max);\r\n try {\r\n (e.currentTarget as Element).setPointerCapture(e.pointerId);\r\n } catch {\r\n // the pointer has already gone or the capture is unavailable: dragging works without it\r\n // указатель уже ушёл или захват недоступен: тянуть можно и без него\r\n }\r\n}\r\n\r\nfunction onHandleMove(e: PointerEvent) {\r\n const s = bezierSegment.value;\r\n if (handleDrag < 0 || !s) return;\r\n const { t, v } = rawCurve(e);\r\n setBezierHandle(handleDrag as 0 | 1, (t - s.a.t) / (s.b.t - s.a.t), (v - s.a.v) / (s.b.v - s.a.v));\r\n}\r\n\r\nfunction onHandleUp() {\r\n if (handleDrag < 0) return;\r\n handleDrag = -1;\r\n frozen.value = null;\r\n emit('commit');\r\n}\r\n\r\n/**\r\n * Arrows on a handle move it by a step (Shift larger): left and right along x, up and down along y.\r\n * Стрелки на ручке сдвигают её на шаг (Shift крупнее): влево и вправо по x, вверх и вниз по y.\r\n */\r\nfunction onHandleKey(e: KeyboardEvent, n: number) {\r\n const s = bezierSegment.value;\r\n const arrows: Record<string, [number, number]> = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, 1], ArrowDown: [0, -1] };\r\n const d = arrows[e.key];\r\n if (!s || !d) return;\r\n e.preventDefault();\r\n e.stopPropagation();\r\n const k = BEZIER_STEP * (e.shiftKey ? 5 : 1);\r\n setBezierHandle(n as 0 | 1, s.bezier[n * 2]! + d[0] * k, s.bezier[n * 2 + 1]! + d[1] * k, true);\r\n}\r\n\r\n/**\r\n * A double click on the plot must not select the page text around it.\r\n * Двойной клик по графику не должен выделять текст страницы вокруг.\r\n */\r\nfunction noSelect(e: MouseEvent) {\r\n if (e.detail > 1) e.preventDefault();\r\n}\r\n\r\nfunction onDouble(e: MouseEvent) {\r\n const { t: tt, v } = toCurve(e);\r\n const r = addPoint(points.value, tt, v);\r\n emit('update:selected', r.index);\r\n emit('update:modelValue', r.points);\r\n emit('commit');\r\n}\r\n\r\n/**\r\n * The arrow step with Shift: this many times larger.\r\n * Шаг стрелки с Shift: во столько раз крупнее.\r\n */\r\nconst COARSE = 5;\r\n\r\n/**\r\n * Moves point `i` by `dx` steps in time and `dy` steps in value (grid steps), with snapping, rounding and bounds.\r\n * Сдвигает точку `i` на `dx` шагов по времени и `dy` шагов по значению (шаги сетки), с прижатием, округлением и границами.\r\n */\r\nfunction nudge(i: number, dx: number, dy: number, coarse: boolean) {\r\n const p = points.value[i];\r\n if (!p) return;\r\n const k = coarse ? COARSE : 1;\r\n const tt = roundTo(snapTo(p.t + dx * k * props.stepT, props.stepT), props.precision);\r\n const v = clampTo(roundTo(snapTo(p.v + dy * k * stepV.value, stepV.value), props.precision), props.min, props.max);\r\n emit('update:modelValue', movePoint(points.value, i, tt, v));\r\n emit('commit');\r\n}\r\n\r\n/**\r\n * Insert adds a point between the selected one and the next (for the last: between it and the previous) on the curve itself.\r\n * Insert добавляет точку между выбранной и следующей (у последней: между ней и предыдущей) на самой кривой.\r\n */\r\n/**\r\n * Focus on point `i` after a re-render: keys go to the selected point, and focus must not stay on the old one.\r\n * Фокус на точку `i` после перерисовки: клавиши идут к той точке, что выбрана, и фокус не должен оставаться на старой.\r\n */\r\nfunction focusDot(i: number) {\r\n void nextTick(() => svg.value?.querySelectorAll<SVGElement>('.tx-curve-dot')[i]?.focus());\r\n}\r\n\r\nfunction insertAfter(i: number) {\r\n const a = points.value[i];\r\n const b = points.value[i + 1] ?? points.value[i - 1];\r\n if (!a || !b) return;\r\n const r = addPoint(points.value, roundTo((a.t + b.t) / 2, props.precision));\r\n emit('update:selected', r.index);\r\n emit('update:modelValue', r.points);\r\n emit('commit');\r\n focusDot(r.index);\r\n}\r\n\r\nfunction removeAt(i: number) {\r\n const next = Math.max(0, i - 1);\r\n emit('update:modelValue', removePoint(points.value, i));\r\n emit('update:selected', next);\r\n emit('commit');\r\n focusDot(next);\r\n}\r\n\r\n/**\r\n * Point keys (focus on it): arrows move by a grid step, Shift larger; Insert adds, Delete removes.\r\n * Клавиши точки (фокус на ней): стрелки двигают на шаг сетки, Shift крупнее; Insert добавляет, Delete убирает.\r\n */\r\nfunction onKey(e: KeyboardEvent) {\r\n // the point that has focus; if the key came from the field itself (after a click on it), then the selected one\r\n // точка, на которой фокус; если клавиша пришла с самого поля (после клика по нему), то выбранная\r\n const target = (e.target as Element | null)?.closest('.tx-curve-dot');\r\n const index = target ? Number(target.getAttribute('data-index')) : NaN;\r\n const i = Number.isInteger(index) ? index : Math.min(props.selected, points.value.length - 1);\r\n const arrows: Record<string, [number, number]> = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, 1], ArrowDown: [0, -1] };\r\n const move = arrows[e.key];\r\n if (move) {\r\n e.preventDefault();\r\n nudge(i, move[0], move[1], e.shiftKey);\r\n } else if (e.key === 'Insert') {\r\n e.preventDefault();\r\n insertAfter(i);\r\n } else if (e.key === 'Delete' || e.key === 'Backspace') {\r\n e.preventDefault();\r\n removeAt(i);\r\n }\r\n}\r\n\r\nconst labelOf = (i: number, p: CurvePoint) => (props.pointLabel ? props.pointLabel(i, p) : `Point ${i + 1}: ${fmtT(p.t)}, ${fmt(p.v)}`);\r\n</script>\r\n\r\n<template>\r\n <svg ref=\"svg\" class=\"tx-curve\" :viewBox=\"`0 0 ${W} ${H}`\" :title=\"hint\" tabindex=\"-1\" role=\"group\" @dblclick.self=\"onDouble\" @mousedown=\"noSelect\" @keydown=\"onKey\">\r\n <!-- fine grid: the same steps as snapping / мелкая сетка: те же шаги, что у прилипания -->\r\n <line v-for=\"x in gridT\" :key=\"`gt${x}`\" class=\"tx-curve-grid\" :class=\"{ major: isMajorT(x) }\" :x1=\"px(x)\" :x2=\"px(x)\" :y1=\"PAD_T\" :y2=\"H - PAD_B\" />\r\n <line v-for=\"v in gridV\" :key=\"`gv${v}`\" class=\"tx-curve-grid\" :class=\"{ major: isMajorV(v) }\" :x1=\"PAD_L\" :x2=\"W - PAD_R\" :y1=\"py(v)\" :y2=\"py(v)\" />\r\n\r\n <text v-for=\"(v, i) in labelsV\" :key=\"`lv${v}`\" class=\"tx-curve-label\" :class=\"{ edge: v === 0 || i === 0 || i === labelsV.length - 1 }\" :x=\"PAD_L - 4\" :y=\"py(v)\" text-anchor=\"end\" dominant-baseline=\"middle\">{{ fmt(v) }}</text>\r\n <text v-for=\"x in labelsT\" :key=\"`lt${x}`\" class=\"tx-curve-label\" :class=\"{ edge: x === 0 || x === 1 }\" :x=\"px(x)\" :y=\"H - 4\" :text-anchor=\"x === 0 ? 'start' : x === 1 ? 'end' : 'middle'\">{{ fmtT(x) }}</text>\r\n\r\n <g v-if=\"tags && guides !== 'off'\" class=\"tx-curve-tags\" aria-hidden=\"true\">\r\n <line class=\"tx-curve-guide\" :x1=\"tags.x\" :x2=\"tags.x\" :y1=\"tags.y\" :y2=\"PAD_T + PLOT_H\" />\r\n <line class=\"tx-curve-guide\" :x1=\"PAD_L\" :x2=\"tags.x\" :y1=\"tags.y\" :y2=\"tags.y\" />\r\n <template v-if=\"guides === 'values'\">\r\n <rect class=\"tx-curve-tag-bg\" :x=\"tags.t.cx - tags.t.w / 2\" :y=\"H - 12\" :width=\"tags.t.w\" height=\"11\" rx=\"2\" />\r\n <text class=\"tx-curve-tag\" :x=\"tags.t.cx\" :y=\"H - 4\" text-anchor=\"middle\">{{ tags.t.text }}</text>\r\n <rect class=\"tx-curve-tag-bg\" :x=\"PAD_L - 3 - tags.v.w\" :y=\"tags.v.cy - 5.5\" :width=\"tags.v.w\" height=\"11\" rx=\"2\" />\r\n <text class=\"tx-curve-tag\" :x=\"PAD_L - 5\" :y=\"tags.v.cy\" text-anchor=\"end\" dominant-baseline=\"middle\">{{ tags.v.text }}</text>\r\n </template>\r\n </g>\r\n\r\n <path class=\"tx-curve-line\" :d=\"path\" />\r\n\r\n <!-- The \"B\" mark above the start of a Bezier segment: shows the point has handles even when it is not selected / Метка «B» над началом участка с Безье: видно, что у точки есть ручки, даже когда она не выбрана -->\r\n <text v-for=\"m in bezierMarks\" :key=\"`b${m.i}`\" class=\"tx-curve-mark\" :x=\"px(m.t)\" :y=\"py(m.v) - 8\" text-anchor=\"middle\" aria-hidden=\"true\">B</text>\r\n\r\n <g v-if=\"bezierHandles.length\" class=\"tx-curve-bezier\">\r\n <template v-for=\"h in bezierHandles\" :key=\"h.n\">\r\n <line class=\"tx-curve-arm\" :x1=\"px(h.from.t)\" :y1=\"py(h.from.v)\" :x2=\"px(h.t)\" :y2=\"py(h.v)\" />\r\n <circle\r\n class=\"tx-curve-handle\"\r\n :cx=\"px(h.t)\"\r\n :cy=\"py(h.v)\"\r\n r=\"4\"\r\n tabindex=\"0\"\r\n role=\"slider\"\r\n :aria-label=\"handleLabel ? handleLabel(h.n + 1, bezierSegment!.i) : `Bezier handle ${h.n + 1}`\"\r\n @pointerdown.stop=\"onHandleDown($event, h.n)\"\r\n @pointermove=\"onHandleMove\"\r\n @pointerup=\"onHandleUp\"\r\n @pointercancel=\"onHandleUp\"\r\n @keydown=\"onHandleKey($event, h.n)\"\r\n />\r\n </template>\r\n </g>\r\n <circle\r\n v-for=\"(p, i) in points\"\r\n :key=\"i\"\r\n class=\"tx-curve-dot\"\r\n :class=\"{ on: i === selected }\"\r\n :cx=\"px(p.t)\"\r\n :cy=\"py(p.v)\"\r\n r=\"5\"\r\n :data-index=\"i\"\r\n tabindex=\"0\"\r\n role=\"button\"\r\n :aria-label=\"labelOf(i, p)\"\r\n @focus=\"emit('update:selected', i)\"\r\n @pointerdown.stop=\"onDown($event, i)\"\r\n @pointermove=\"onMove\"\r\n @pointerup=\"onUp\"\r\n @pointercancel=\"onUp\"\r\n />\r\n </svg>\r\n</template>\r\n\r\n<style>\r\n/*\r\n * Configured with CSS variables on any ancestor:\r\n * Настройка через CSS-переменные на любом предке:\r\n * --tx-curve-bg, --tx-curve-border, --tx-curve-grid, --tx-curve-label, --tx-curve-accent,\r\n * --tx-curve-text (the numbers at the ends of the axes: start and end of the scale, brighter than the rest),\r\n * --tx-curve-radius (the corners of the plot, 4px by default),\r\n * --tx-curve-dot-opacity (opacity of unselected points, 0.3 by default).\r\n * --tx-curve-text (цифры у краёв осей: начало и конец шкалы, ярче остальных),\r\n * --tx-curve-radius (углы графика, по умолчанию 4px),\r\n * --tx-curve-dot-opacity (непрозрачность невыбранных точек, по умолчанию 0.3).\r\n */\r\n.tx-curve {\r\n display: block;\r\n width: 100%;\r\n height: auto;\r\n border: 1px solid var(--tx-curve-border, #2a2d33);\r\n border-radius: var(--tx-curve-radius, 4px);\r\n background: var(--tx-curve-bg, #15171b);\r\n touch-action: none;\r\n user-select: none;\r\n outline: none;\r\n}\r\n\r\n.tx-curve-grid {\r\n pointer-events: none; /* otherwise a double click hits the grid line, not the field / иначе двойной клик попадает в линию сетки, а не в поле */\r\n stroke: var(--tx-curve-grid, #2a2d33);\r\n stroke-width: 0.5;\r\n opacity: 0.45;\r\n}\r\n\r\n.tx-curve-grid.major {\r\n stroke-width: 1;\r\n opacity: 1;\r\n}\r\n\r\n.tx-curve-guide {\r\n stroke: var(--tx-curve-accent, #4fc3f7);\r\n stroke-width: 1;\r\n stroke-dasharray: 2 3;\r\n opacity: 0.45;\r\n pointer-events: none;\r\n}\r\n\r\n.tx-curve-tag-bg {\r\n fill: var(--tx-curve-bg, #15171b);\r\n pointer-events: none;\r\n}\r\n\r\n.tx-curve-tag {\r\n fill: var(--tx-curve-accent, #4fc3f7);\r\n font-size: 8px;\r\n font-weight: 700;\r\n pointer-events: none;\r\n user-select: none;\r\n}\r\n\r\n.tx-curve-label.edge {\r\n fill: var(--tx-curve-text, #d6d9e0);\r\n}\r\n\r\n.tx-curve-label {\r\n fill: var(--tx-curve-label, #8b929c);\r\n font-size: 8px;\r\n pointer-events: none;\r\n user-select: none;\r\n}\r\n\r\n.tx-curve-line {\r\n fill: none;\r\n stroke: var(--tx-curve-accent, #4fc3f7);\r\n stroke-width: 2;\r\n pointer-events: none;\r\n}\r\n\r\n.tx-curve-mark {\r\n fill: var(--tx-curve-accent, #4fc3f7);\r\n font: 600 9px/1 system-ui, sans-serif;\r\n pointer-events: none;\r\n user-select: none;\r\n}\r\n\r\n.tx-curve-arm {\r\n stroke: var(--tx-curve-label, #8b929c);\r\n stroke-width: 1;\r\n stroke-dasharray: 3 2;\r\n pointer-events: none;\r\n}\r\n\r\n.tx-curve-handle {\r\n fill: var(--tx-curve-label, #8b929c);\r\n stroke: var(--tx-curve-bg, #15171b);\r\n stroke-width: 1.5;\r\n cursor: grab;\r\n}\r\n\r\n.tx-curve-handle:active {\r\n cursor: grabbing;\r\n}\r\n\r\n.tx-curve-handle:hover,\r\n.tx-curve-handle:focus-visible {\r\n fill: var(--tx-curve-accent, #4fc3f7);\r\n outline: none;\r\n}\r\n\r\n.tx-curve-dot {\r\n fill: var(--tx-curve-bg, #15171b);\r\n stroke: var(--tx-curve-accent, #4fc3f7);\r\n stroke-width: 2;\r\n opacity: var(--tx-curve-dot-opacity, 0.3);\r\n cursor: grab;\r\n}\r\n\r\n.tx-curve-dot:active {\r\n cursor: grabbing;\r\n}\r\n\r\n.tx-curve-dot:focus {\r\n outline: none;\r\n}\r\n\r\n/* keyboard focus: a thicker outline and a glow (browsers draw the outline of SVG shapes differently) / фокус с клавиатуры: утолщённая обводка и свечение (контур у SVG-форм браузеры рисуют по-разному) */\r\n.tx-curve-dot:focus-visible {\r\n stroke-width: 3;\r\n filter: drop-shadow(0 0 3px var(--tx-curve-accent, #4fc3f7));\r\n opacity: 1;\r\n}\r\n\r\n.tx-curve-dot.on,\r\n.tx-curve-dot:hover {\r\n fill: var(--tx-curve-accent, #4fc3f7);\r\n opacity: 1;\r\n}\r\n</style>\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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,UAAK,WAAE,KAAI,mBAAoB,CAAC;MAChC,eAAWH,eAAA,WAAO,OAAO,QAAQ,CAAC,GAAA,CAAA,MAAA,CAAA;MAClC,eAAa;MACb,aAAW;MACX,iBAAe"}
@@ -23,6 +23,13 @@ export interface Command {
23
23
  checked?: () => boolean;
24
24
  /** With `checked`: a radio of this group. / Вместе с `checked`: радио этой группы. */
25
25
  group?: string;
26
+ /**
27
+ * A held key runs it again (`true`, the default: a nudge, an undo) or once per press (`false`: a save, a toggle). The held key is swallowed
28
+ * either way, so the browser's own dialog does not open.
29
+ * Зажатая клавиша запускает её снова (`true`, по умолчанию: сдвиг, отмена) или один раз на нажатие (`false`: сохранить, переключатель).
30
+ * Зажатая клавиша глотается в обоих случаях, так что собственный диалог браузера не открывается.
31
+ */
32
+ repeat?: boolean;
26
33
  run: () => void;
27
34
  }
28
35
  /**
package/dist/commands.js CHANGED
@@ -27,8 +27,10 @@ function createCommands(initial = [], options = {}) {
27
27
  return !!command && (command.enabled?.() ?? true);
28
28
  };
29
29
  /**
30
- * Runs the command if it exists and is enabled. Returns whether it ran. Give it to `@select` of a menu.
31
- * Выполняет команду, если она есть и доступна. Возвращает, выполнилась ли. Отдайте его в `@select` меню.
30
+ * Runs the command if it exists and is enabled. Returns whether it ran. A menu of TaoUI 6 emits the item, not the id, so
31
+ * `@select` takes `(item) => commands.run(item.id)` (`onSelect` of `useCommands` is that).
32
+ * Выполняет команду, если она есть и доступна. Возвращает, выполнилась ли. Меню TaoUI 6 отдаёт пункт, а не id, поэтому
33
+ * в `@select` идёт `(item) => commands.run(item.id)` (это и есть `onSelect` из `useCommands`).
32
34
  */
33
35
  function run(id) {
34
36
  if (!isEnabled(id)) return false;
@@ -101,7 +103,8 @@ function createCommands(initial = [], options = {}) {
101
103
  function bind(target, bindOptions = {}) {
102
104
  const bindings = () => {
103
105
  const map = {};
104
- for (const command of commands.values()) for (const combo of shortcuts(command)) map[combo] ??= () => {
106
+ for (const command of commands.values()) for (const combo of shortcuts(command)) map[combo] ??= (event) => {
107
+ if (event.repeat && command.repeat === false) return;
105
108
  run(command.id);
106
109
  };
107
110
  return map;
@@ -1 +1 @@
1
- {"version":3,"file":"commands.js","names":[],"sources":["../src/commands.ts"],"sourcesContent":["import { bindHotkeys, type BindOptions, formatHotkey, type HotkeyHandler, isApplePlatform, isReservedHotkey, normalizeHotkey, type PlatformOptions, type ReservedOptions } from './hotkeys';\n\n/**\n * A registry of commands: one source for the menu bar, a context menu, a toolbar, a command palette and the keyboard.\n * A command knows its label, its shortcut, whether it can run now and whether it is checked; the menus only show that.\n * Реестр команд: один источник для полосы меню, контекстного меню, панели инструментов, палитры команд и клавиатуры.\n * Команда знает подпись, сочетание, можно ли её сейчас выполнить и отмечена ли она; меню это только показывают.\n */\n\ntype Text = string | (() => string);\n\nexport interface Command {\n id: string;\n /** A function is read every time: a label from `i18n` follows the language. / Функция читается каждый раз: подпись из `i18n` следует за языком. */\n label: Text;\n /**\n * `Mod+S`, or several (the first one is shown). `Mod` is ⌘ on Apple and Ctrl elsewhere.\n * `Mod+S` или несколько (показывается первое). `Mod` — ⌘ у Apple и Ctrl у остальных.\n */\n shortcut?: string | readonly string[];\n /** Icon name for the menu. / Имя иконки для меню. */\n icon?: string;\n /** Can it run now. Default: always. / Можно ли выполнить сейчас. По умолчанию всегда. */\n enabled?: () => boolean;\n /** Makes it a checkbox (a toggle) in the menu. / Делает её чекбоксом (переключателем) в меню. */\n checked?: () => boolean;\n /** With `checked`: a radio of this group. / Вместе с `checked`: радио этой группы. */\n group?: string;\n run: () => void;\n}\n\n/**\n * The menu entries `toMenu` builds. The same shape as `TaoMenuItem` of TaoUI (a test holds it), declared here,\n * so TaoUX does not depend on TaoUI: pass the result to `TaoMenubar`, `TaoDropdownMenu`, `TaoContextMenu` as is.\n * Пункты меню, которые строит `toMenu`. Та же форма, что у `TaoMenuItem` из TaoUI (это держит тест), объявлена здесь,\n * чтобы TaoUX не зависел от TaoUI: результат передаётся в `TaoMenubar`, `TaoDropdownMenu`, `TaoContextMenu` как есть.\n */\nexport type CommandMenuItem =\n | { type?: 'item'; id: string; label: string; icon?: string; shortcut?: string; disabled?: boolean; items?: CommandMenuItem[] }\n | { type: 'checkbox'; id: string; label: string; checked: boolean; shortcut?: string; disabled?: boolean }\n | { type: 'radio'; id: string; group: string; label: string; checked: boolean; shortcut?: string; disabled?: boolean }\n | { type: 'label'; label: string }\n | { type: 'separator' };\n\n/**\n * What a menu is made of: a command id, `'-'` for a separator, a submenu, a group caption.\n * Из чего состоит меню: id команды, `'-'` для разделителя, подменю, подпись группы.\n */\nexport type MenuLayoutEntry = string | { id?: string; label: Text; icon?: string; items: MenuLayout } | { type: 'label'; label: Text };\nexport type MenuLayout = readonly MenuLayoutEntry[];\n\nexport interface ShortcutProblem {\n id: string;\n shortcut: string;\n /** `reserved`: the browser keeps it; `duplicate`: another command has it too (`other`). */\n problem: 'reserved' | 'duplicate';\n other?: string;\n}\n\nconst text = (value: Text) => (typeof value === 'function' ? value() : value);\nconst shortcuts = (command: Command) => (command.shortcut === undefined ? [] : typeof command.shortcut === 'string' ? [command.shortcut] : [...command.shortcut]);\n\n/**\n * Creates the registry. Nothing is reactive by itself: `toMenu` reads `label`, `enabled` and `checked` when called,\n * so in Vue call it inside `computed` and read refs in those functions, and the menu follows the state.\n * Создаёт реестр. Сам по себе ничего не реактивно: `toMenu` читает `label`, `enabled` и `checked` в момент вызова,\n * так что во Vue вызывайте его внутри `computed` и читайте ref-ы в этих функциях, и меню будет следовать за состоянием.\n */\nexport function createCommands(initial: readonly Command[] = [], options: PlatformOptions = {}) {\n const mac = options.mac ?? isApplePlatform();\n const commands = new Map<string, Command>();\n\n /**\n * Adds commands; an id taken twice is an error. Returns the function that removes them again.\n * Добавляет команды; занятый id — ошибка. Возвращает функцию, которая их убирает.\n */\n function add(command: Command | readonly Command[]): () => void {\n const list = Array.isArray(command) ? (command as readonly Command[]) : [command as Command];\n for (const c of list) {\n if (commands.has(c.id)) throw new Error(`commands: \"${c.id}\" is already registered`);\n }\n list.forEach((c) => commands.set(c.id, c));\n return () => list.forEach((c) => commands.get(c.id) === c && commands.delete(c.id));\n }\n\n const get = (id: string) => commands.get(id);\n const isEnabled = (id: string) => {\n const command = commands.get(id);\n return !!command && (command.enabled?.() ?? true);\n };\n\n /**\n * Runs the command if it exists and is enabled. Returns whether it ran. Give it to `@select` of a menu.\n * Выполняет команду, если она есть и доступна. Возвращает, выполнилась ли. Отдайте его в `@select` меню.\n */\n function run(id: string): boolean {\n if (!isEnabled(id)) return false;\n commands.get(id)!.run();\n return true;\n }\n\n /** The shortcut label for this platform (`⇧⌘Z` / `Ctrl+Shift+Z`), or undefined. / Подпись сочетания для этой платформы. */\n function shortcutLabel(id: string): string | undefined {\n const first = shortcuts(commands.get(id) ?? ({} as Command))[0];\n return first === undefined ? undefined : formatHotkey(first, { mac });\n }\n\n function item(command: Command): CommandMenuItem {\n const base = { id: command.id, label: text(command.label), shortcut: shortcutLabel(command.id), disabled: !isEnabled(command.id) };\n if (command.checked && command.group !== undefined) return { type: 'radio', group: command.group, checked: command.checked(), ...base };\n if (command.checked) return { type: 'checkbox', checked: command.checked(), ...base };\n return { ...base, icon: command.icon };\n }\n\n /**\n * Builds the menu tree from a layout. An unknown id is an error (a typo would silently lose a menu entry).\n * For a menu bar the top level is submenus: `[{ id: 'file', label: 'File', items: ['save', '-', 'undo'] }]`.\n * Строит дерево меню по раскладке. Незнакомый id — ошибка (опечатка тихо потеряла бы пункт).\n * Для полосы меню верхний уровень — подменю: `[{ id: 'file', label: 'File', items: ['save', '-', 'undo'] }]`.\n */\n function toMenu(layout: MenuLayout, path = 'menu'): CommandMenuItem[] {\n return layout.map((entry, index): CommandMenuItem => {\n if (entry === '-') return { type: 'separator' };\n if (typeof entry === 'string') {\n const command = commands.get(entry);\n if (!command) throw new Error(`commands: the menu names \"${entry}\", which is not registered`);\n return item(command);\n }\n if ('type' in entry) return { type: 'label', label: text(entry.label) };\n const id = entry.id ?? `${path}-${index}`;\n return { id, label: text(entry.label), icon: entry.icon, items: toMenu(entry.items, id) };\n });\n }\n\n /**\n * Listens to the shortcuts of every registered command on the target (commands added later count too).\n * A disabled command swallows its key and does nothing, so Mod+S never opens the browser's \"Save page\".\n * Returns the function that stops listening.\n * Слушает сочетания всех зарегистрированных команд на цели (добавленные позже тоже).\n * Недоступная команда глотает свою клавишу и ничего не делает, так что Mod+S не откроет «Сохранить страницу» браузера.\n * Возвращает функцию, которая перестаёт слушать.\n */\n function bind(target: EventTarget, bindOptions: Omit<BindOptions, 'mac'> = {}): () => void {\n const bindings = () => {\n const map: Record<string, HotkeyHandler> = {};\n for (const command of commands.values()) {\n for (const combo of shortcuts(command)) {\n map[combo] ??= () => {\n run(command.id);\n };\n }\n }\n return map;\n };\n return bindHotkeys(target, bindings, { ...bindOptions, mac });\n }\n\n /**\n * Shortcuts that will not work: kept by the browser, or given to two commands. Handy in a test of your app.\n * Сочетания, которые не сработают: их держит браузер или они даны двум командам. Удобно в тесте приложения.\n */\n function check(reservedOptions: Omit<ReservedOptions, 'mac'> = {}): ShortcutProblem[] {\n const problems: ShortcutProblem[] = [];\n const seen = new Map<string, string>();\n for (const command of commands.values()) {\n for (const shortcut of shortcuts(command)) {\n if (isReservedHotkey(shortcut, { ...reservedOptions, mac })) problems.push({ id: command.id, shortcut, problem: 'reserved' });\n const key = normalizeHotkey(shortcut, { mac });\n const other = seen.get(key);\n if (other !== undefined && other !== command.id) problems.push({ id: command.id, shortcut, problem: 'duplicate', other });\n else seen.set(key, command.id);\n }\n }\n return problems;\n }\n\n add(initial);\n\n return {\n add,\n get,\n has: (id: string) => commands.has(id),\n list: () => [...commands.values()],\n isEnabled,\n run,\n label: (id: string) => {\n const command = commands.get(id);\n return command ? text(command.label) : undefined;\n },\n shortcutLabel,\n toMenu,\n bind,\n check,\n };\n}\n\nexport type Commands = ReturnType<typeof createCommands>;\n\ntype Flag = boolean | { readonly value: boolean } | (() => boolean);\nconst flag = (value: Flag) => (typeof value === 'function' ? value() : typeof value === 'boolean' ? value : value.value);\n\n/**\n * What undo/redo needs from a history: a document session (`canUndo` refs) fits as is, a `History` with an `apply` wrapper.\n * Что undo/redo нужно от истории: сессия документа (ref-ы `canUndo`) подходит как есть, `History` — с обёрткой `apply`.\n */\nexport interface UndoSource {\n readonly canUndo: Flag;\n readonly canRedo: Flag;\n undo(): unknown;\n redo(): unknown;\n}\n\nexport interface HistoryCommandOptions {\n labels?: { undo?: Text; redo?: Text };\n}\n\n/**\n * Undo and Redo as commands (`undo`, `redo`; Mod+Z, Mod+Shift+Z and Mod+Y): they are disabled by themselves when\n * there is nothing to undo or redo, in the menu and on the keyboard.\n * Undo и Redo как команды (`undo`, `redo`; Mod+Z, Mod+Shift+Z и Mod+Y): сами становятся недоступными, когда\n * откатывать или возвращать нечего, и в меню, и на клавиатуре.\n *\n * ```ts\n * commands.add(historyCommands(session, { labels: { undo: () => t('undo'), redo: () => t('redo') } }));\n * ```\n */\nexport function historyCommands(source: UndoSource, options: HistoryCommandOptions = {}): Command[] {\n return [\n { id: 'undo', label: options.labels?.undo ?? 'Undo', shortcut: 'Mod+Z', enabled: () => flag(source.canUndo), run: () => void source.undo() },\n { id: 'redo', label: options.labels?.redo ?? 'Redo', shortcut: ['Mod+Shift+Z', 'Mod+Y'], enabled: () => flag(source.canRedo), run: () => void source.redo() },\n ];\n}\n"],"mappings":";;AA2DA,IAAM,QAAQ,UAAiB,OAAO,UAAU,aAAa,MAAM,IAAI;AACvE,IAAM,aAAa,YAAsB,QAAQ,aAAa,KAAA,IAAY,CAAC,IAAI,OAAO,QAAQ,aAAa,WAAW,CAAC,QAAQ,QAAQ,IAAI,CAAC,GAAG,QAAQ,QAAQ;;;;;;;AAQ/J,SAAgB,eAAe,UAA8B,CAAC,GAAG,UAA2B,CAAC,GAAG;CAC5F,MAAM,MAAM,QAAQ,OAAO,gBAAgB;CAC3C,MAAM,2BAAW,IAAI,IAAqB;;;;;CAM1C,SAAS,IAAI,SAAmD;EAC5D,MAAM,OAA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AAM,QAAQ,KAAK,IAAI,GAAG;GAC1B,IAAI,UAAU,KAAA,KAAa,UAAU,QAAQ,IAAI,SAAS,KAAK;IAAE,IAAI,QAAQ;IAAI;IAAU,SAAS;IAAa;GAAM,CAAC;QACnH,KAAK,IAAI,KAAK,QAAQ,EAAE;EACjC;EAEJ,OAAO;CACX;CAEA,IAAI,OAAO;CAEX,OAAO;EACH;EACA;EACA,MAAM,OAAe,SAAS,IAAI,EAAE;EACpC,YAAY,CAAC,GAAG,SAAS,OAAO,CAAC;EACjC;EACA;EACA,QAAQ,OAAe;GACnB,MAAM,UAAU,SAAS,IAAI,EAAE;GAC/B,OAAO,UAAU,KAAK,QAAQ,KAAK,IAAI,KAAA;EAC3C;EACA;EACA;EACA;EACA;CACJ;AACJ;AAKA,IAAM,QAAQ,UAAiB,OAAO,UAAU,aAAa,MAAM,IAAI,OAAO,UAAU,YAAY,QAAQ,MAAM;;;;;;;;;;;AA2BlH,SAAgB,gBAAgB,QAAoB,UAAiC,CAAC,GAAc;CAChG,OAAO,CACH;EAAE,IAAI;EAAQ,OAAO,QAAQ,QAAQ,QAAQ;EAAQ,UAAU;EAAS,eAAe,KAAK,OAAO,OAAO;EAAG,WAAW,KAAK,OAAO,KAAK;CAAE,GAC3I;EAAE,IAAI;EAAQ,OAAO,QAAQ,QAAQ,QAAQ;EAAQ,UAAU,CAAC,eAAe,OAAO;EAAG,eAAe,KAAK,OAAO,OAAO;EAAG,WAAW,KAAK,OAAO,KAAK;CAAE,CAChK;AACJ"}
1
+ {"version":3,"file":"commands.js","names":[],"sources":["../src/commands.ts"],"sourcesContent":["import { bindHotkeys, type BindOptions, formatHotkey, type HotkeyHandler, isApplePlatform, isReservedHotkey, normalizeHotkey, type PlatformOptions, type ReservedOptions } from './hotkeys';\n\n/**\n * A registry of commands: one source for the menu bar, a context menu, a toolbar, a command palette and the keyboard.\n * A command knows its label, its shortcut, whether it can run now and whether it is checked; the menus only show that.\n * Реестр команд: один источник для полосы меню, контекстного меню, панели инструментов, палитры команд и клавиатуры.\n * Команда знает подпись, сочетание, можно ли её сейчас выполнить и отмечена ли она; меню это только показывают.\n */\n\ntype Text = string | (() => string);\n\nexport interface Command {\n id: string;\n /** A function is read every time: a label from `i18n` follows the language. / Функция читается каждый раз: подпись из `i18n` следует за языком. */\n label: Text;\n /**\n * `Mod+S`, or several (the first one is shown). `Mod` is ⌘ on Apple and Ctrl elsewhere.\n * `Mod+S` или несколько (показывается первое). `Mod` — ⌘ у Apple и Ctrl у остальных.\n */\n shortcut?: string | readonly string[];\n /** Icon name for the menu. / Имя иконки для меню. */\n icon?: string;\n /** Can it run now. Default: always. / Можно ли выполнить сейчас. По умолчанию всегда. */\n enabled?: () => boolean;\n /** Makes it a checkbox (a toggle) in the menu. / Делает её чекбоксом (переключателем) в меню. */\n checked?: () => boolean;\n /** With `checked`: a radio of this group. / Вместе с `checked`: радио этой группы. */\n group?: string;\n /**\n * A held key runs it again (`true`, the default: a nudge, an undo) or once per press (`false`: a save, a toggle). The held key is swallowed\n * either way, so the browser's own dialog does not open.\n * Зажатая клавиша запускает её снова (`true`, по умолчанию: сдвиг, отмена) или один раз на нажатие (`false`: сохранить, переключатель).\n * Зажатая клавиша глотается в обоих случаях, так что собственный диалог браузера не открывается.\n */\n repeat?: boolean;\n run: () => void;\n}\n\n/**\n * The menu entries `toMenu` builds. The same shape as `TaoMenuItem` of TaoUI (a test holds it), declared here,\n * so TaoUX does not depend on TaoUI: pass the result to `TaoMenubar`, `TaoDropdownMenu`, `TaoContextMenu` as is.\n * Пункты меню, которые строит `toMenu`. Та же форма, что у `TaoMenuItem` из TaoUI (это держит тест), объявлена здесь,\n * чтобы TaoUX не зависел от TaoUI: результат передаётся в `TaoMenubar`, `TaoDropdownMenu`, `TaoContextMenu` как есть.\n */\nexport type CommandMenuItem =\n | { type?: 'item'; id: string; label: string; icon?: string; shortcut?: string; disabled?: boolean; items?: CommandMenuItem[] }\n | { type: 'checkbox'; id: string; label: string; checked: boolean; shortcut?: string; disabled?: boolean }\n | { type: 'radio'; id: string; group: string; label: string; checked: boolean; shortcut?: string; disabled?: boolean }\n | { type: 'label'; label: string }\n | { type: 'separator' };\n\n/**\n * What a menu is made of: a command id, `'-'` for a separator, a submenu, a group caption.\n * Из чего состоит меню: id команды, `'-'` для разделителя, подменю, подпись группы.\n */\nexport type MenuLayoutEntry = string | { id?: string; label: Text; icon?: string; items: MenuLayout } | { type: 'label'; label: Text };\nexport type MenuLayout = readonly MenuLayoutEntry[];\n\nexport interface ShortcutProblem {\n id: string;\n shortcut: string;\n /** `reserved`: the browser keeps it; `duplicate`: another command has it too (`other`). */\n problem: 'reserved' | 'duplicate';\n other?: string;\n}\n\nconst text = (value: Text) => (typeof value === 'function' ? value() : value);\nconst shortcuts = (command: Command) => (command.shortcut === undefined ? [] : typeof command.shortcut === 'string' ? [command.shortcut] : [...command.shortcut]);\n\n/**\n * Creates the registry. Nothing is reactive by itself: `toMenu` reads `label`, `enabled` and `checked` when called,\n * so in Vue call it inside `computed` and read refs in those functions, and the menu follows the state.\n * Создаёт реестр. Сам по себе ничего не реактивно: `toMenu` читает `label`, `enabled` и `checked` в момент вызова,\n * так что во Vue вызывайте его внутри `computed` и читайте ref-ы в этих функциях, и меню будет следовать за состоянием.\n */\nexport function createCommands(initial: readonly Command[] = [], options: PlatformOptions = {}) {\n const mac = options.mac ?? isApplePlatform();\n const commands = new Map<string, Command>();\n\n /**\n * Adds commands; an id taken twice is an error. Returns the function that removes them again.\n * Добавляет команды; занятый id — ошибка. Возвращает функцию, которая их убирает.\n */\n function add(command: Command | readonly Command[]): () => void {\n const list = Array.isArray(command) ? (command as readonly Command[]) : [command as Command];\n for (const c of list) {\n if (commands.has(c.id)) throw new Error(`commands: \"${c.id}\" is already registered`);\n }\n list.forEach((c) => commands.set(c.id, c));\n return () => list.forEach((c) => commands.get(c.id) === c && commands.delete(c.id));\n }\n\n const get = (id: string) => commands.get(id);\n const isEnabled = (id: string) => {\n const command = commands.get(id);\n return !!command && (command.enabled?.() ?? true);\n };\n\n /**\n * Runs the command if it exists and is enabled. Returns whether it ran. A menu of TaoUI 6 emits the item, not the id, so\n * `@select` takes `(item) => commands.run(item.id)` (`onSelect` of `useCommands` is that).\n * Выполняет команду, если она есть и доступна. Возвращает, выполнилась ли. Меню TaoUI 6 отдаёт пункт, а не id, поэтому\n * в `@select` идёт `(item) => commands.run(item.id)` (это и есть `onSelect` из `useCommands`).\n */\n function run(id: string): boolean {\n if (!isEnabled(id)) return false;\n commands.get(id)!.run();\n return true;\n }\n\n /** The shortcut label for this platform (`⇧⌘Z` / `Ctrl+Shift+Z`), or undefined. / Подпись сочетания для этой платформы. */\n function shortcutLabel(id: string): string | undefined {\n const first = shortcuts(commands.get(id) ?? ({} as Command))[0];\n return first === undefined ? undefined : formatHotkey(first, { mac });\n }\n\n function item(command: Command): CommandMenuItem {\n const base = { id: command.id, label: text(command.label), shortcut: shortcutLabel(command.id), disabled: !isEnabled(command.id) };\n if (command.checked && command.group !== undefined) return { type: 'radio', group: command.group, checked: command.checked(), ...base };\n if (command.checked) return { type: 'checkbox', checked: command.checked(), ...base };\n return { ...base, icon: command.icon };\n }\n\n /**\n * Builds the menu tree from a layout. An unknown id is an error (a typo would silently lose a menu entry).\n * For a menu bar the top level is submenus: `[{ id: 'file', label: 'File', items: ['save', '-', 'undo'] }]`.\n * Строит дерево меню по раскладке. Незнакомый id — ошибка (опечатка тихо потеряла бы пункт).\n * Для полосы меню верхний уровень — подменю: `[{ id: 'file', label: 'File', items: ['save', '-', 'undo'] }]`.\n */\n function toMenu(layout: MenuLayout, path = 'menu'): CommandMenuItem[] {\n return layout.map((entry, index): CommandMenuItem => {\n if (entry === '-') return { type: 'separator' };\n if (typeof entry === 'string') {\n const command = commands.get(entry);\n if (!command) throw new Error(`commands: the menu names \"${entry}\", which is not registered`);\n return item(command);\n }\n if ('type' in entry) return { type: 'label', label: text(entry.label) };\n const id = entry.id ?? `${path}-${index}`;\n return { id, label: text(entry.label), icon: entry.icon, items: toMenu(entry.items, id) };\n });\n }\n\n /**\n * Listens to the shortcuts of every registered command on the target (commands added later count too).\n * A disabled command swallows its key and does nothing, so Mod+S never opens the browser's \"Save page\".\n * Returns the function that stops listening.\n * Слушает сочетания всех зарегистрированных команд на цели (добавленные позже тоже).\n * Недоступная команда глотает свою клавишу и ничего не делает, так что Mod+S не откроет «Сохранить страницу» браузера.\n * Возвращает функцию, которая перестаёт слушать.\n */\n function bind(target: EventTarget, bindOptions: Omit<BindOptions, 'mac'> = {}): () => void {\n const bindings = () => {\n const map: Record<string, HotkeyHandler> = {};\n for (const command of commands.values()) {\n for (const combo of shortcuts(command)) {\n map[combo] ??= (event) => {\n if (event.repeat && command.repeat === false) return;\n run(command.id);\n };\n }\n }\n return map;\n };\n return bindHotkeys(target, bindings, { ...bindOptions, mac });\n }\n\n /**\n * Shortcuts that will not work: kept by the browser, or given to two commands. Handy in a test of your app.\n * Сочетания, которые не сработают: их держит браузер или они даны двум командам. Удобно в тесте приложения.\n */\n function check(reservedOptions: Omit<ReservedOptions, 'mac'> = {}): ShortcutProblem[] {\n const problems: ShortcutProblem[] = [];\n const seen = new Map<string, string>();\n for (const command of commands.values()) {\n for (const shortcut of shortcuts(command)) {\n if (isReservedHotkey(shortcut, { ...reservedOptions, mac })) problems.push({ id: command.id, shortcut, problem: 'reserved' });\n const key = normalizeHotkey(shortcut, { mac });\n const other = seen.get(key);\n if (other !== undefined && other !== command.id) problems.push({ id: command.id, shortcut, problem: 'duplicate', other });\n else seen.set(key, command.id);\n }\n }\n return problems;\n }\n\n add(initial);\n\n return {\n add,\n get,\n has: (id: string) => commands.has(id),\n list: () => [...commands.values()],\n isEnabled,\n run,\n label: (id: string) => {\n const command = commands.get(id);\n return command ? text(command.label) : undefined;\n },\n shortcutLabel,\n toMenu,\n bind,\n check,\n };\n}\n\nexport type Commands = ReturnType<typeof createCommands>;\n\ntype Flag = boolean | { readonly value: boolean } | (() => boolean);\nconst flag = (value: Flag) => (typeof value === 'function' ? value() : typeof value === 'boolean' ? value : value.value);\n\n/**\n * What undo/redo needs from a history: a document session (`canUndo` refs) fits as is, a `History` with an `apply` wrapper.\n * Что undo/redo нужно от истории: сессия документа (ref-ы `canUndo`) подходит как есть, `History` — с обёрткой `apply`.\n */\nexport interface UndoSource {\n readonly canUndo: Flag;\n readonly canRedo: Flag;\n undo(): unknown;\n redo(): unknown;\n}\n\nexport interface HistoryCommandOptions {\n labels?: { undo?: Text; redo?: Text };\n}\n\n/**\n * Undo and Redo as commands (`undo`, `redo`; Mod+Z, Mod+Shift+Z and Mod+Y): they are disabled by themselves when\n * there is nothing to undo or redo, in the menu and on the keyboard.\n * Undo и Redo как команды (`undo`, `redo`; Mod+Z, Mod+Shift+Z и Mod+Y): сами становятся недоступными, когда\n * откатывать или возвращать нечего, и в меню, и на клавиатуре.\n *\n * ```ts\n * commands.add(historyCommands(session, { labels: { undo: () => t('undo'), redo: () => t('redo') } }));\n * ```\n */\nexport function historyCommands(source: UndoSource, options: HistoryCommandOptions = {}): Command[] {\n return [\n { id: 'undo', label: options.labels?.undo ?? 'Undo', shortcut: 'Mod+Z', enabled: () => flag(source.canUndo), run: () => void source.undo() },\n { id: 'redo', label: options.labels?.redo ?? 'Redo', shortcut: ['Mod+Shift+Z', 'Mod+Y'], enabled: () => flag(source.canRedo), run: () => void source.redo() },\n ];\n}\n"],"mappings":";;AAkEA,IAAM,QAAQ,UAAiB,OAAO,UAAU,aAAa,MAAM,IAAI;AACvE,IAAM,aAAa,YAAsB,QAAQ,aAAa,KAAA,IAAY,CAAC,IAAI,OAAO,QAAQ,aAAa,WAAW,CAAC,QAAQ,QAAQ,IAAI,CAAC,GAAG,QAAQ,QAAQ;;;;;;;AAQ/J,SAAgB,eAAe,UAA8B,CAAC,GAAG,UAA2B,CAAC,GAAG;CAC5F,MAAM,MAAM,QAAQ,OAAO,gBAAgB;CAC3C,MAAM,2BAAW,IAAI,IAAqB;;;;;CAM1C,SAAS,IAAI,SAAmD;EAC5D,MAAM,OAA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AM,MAAM,gBAAgB,UAAU,EAAE,IAAI,CAAC;GAC7C,MAAM,QAAQ,KAAK,IAAI,GAAG;GAC1B,IAAI,UAAU,KAAA,KAAa,UAAU,QAAQ,IAAI,SAAS,KAAK;IAAE,IAAI,QAAQ;IAAI;IAAU,SAAS;IAAa;GAAM,CAAC;QACnH,KAAK,IAAI,KAAK,QAAQ,EAAE;EACjC;EAEJ,OAAO;CACX;CAEA,IAAI,OAAO;CAEX,OAAO;EACH;EACA;EACA,MAAM,OAAe,SAAS,IAAI,EAAE;EACpC,YAAY,CAAC,GAAG,SAAS,OAAO,CAAC;EACjC;EACA;EACA,QAAQ,OAAe;GACnB,MAAM,UAAU,SAAS,IAAI,EAAE;GAC/B,OAAO,UAAU,KAAK,QAAQ,KAAK,IAAI,KAAA;EAC3C;EACA;EACA;EACA;EACA;CACJ;AACJ;AAKA,IAAM,QAAQ,UAAiB,OAAO,UAAU,aAAa,MAAM,IAAI,OAAO,UAAU,YAAY,QAAQ,MAAM;;;;;;;;;;;AA2BlH,SAAgB,gBAAgB,QAAoB,UAAiC,CAAC,GAAc;CAChG,OAAO,CACH;EAAE,IAAI;EAAQ,OAAO,QAAQ,QAAQ,QAAQ;EAAQ,UAAU;EAAS,eAAe,KAAK,OAAO,OAAO;EAAG,WAAW,KAAK,OAAO,KAAK;CAAE,GAC3I;EAAE,IAAI;EAAQ,OAAO,QAAQ,QAAQ,QAAQ;EAAQ,UAAU,CAAC,eAAe,OAAO;EAAG,eAAe,KAAK,OAAO,OAAO;EAAG,WAAW,KAAK,OAAO,KAAK;CAAE,CAChK;AACJ"}
@@ -0,0 +1,47 @@
1
+ import { type ComputedRef } from 'vue';
2
+ /**
3
+ * The registry of commands (`createCommands`) in a Vue app: the commands live as long as the component does, the keys are
4
+ * listened to while it is mounted, a menu is a `computed` that follows the state, and the `select` of a menu runs the command.
5
+ * It takes the registry by its shape, not by import, so a composite module stays independent of another one.
6
+ * Реестр команд (`createCommands`) в приложении на Vue: команды живут, пока жив компонент, клавиши слушаются, пока он
7
+ * смонтирован, меню это `computed`, который следует за состоянием, а `select` меню выполняет команду. Реестр берётся по
8
+ * форме, а не импортом, чтобы составной модуль не зависел от другого.
9
+ *
10
+ * ```ts
11
+ * const commands = createCommands() // once, in a module of the app
12
+ * // in the root component:
13
+ * const { menu, onSelect } = useCommands(commands, { add: [...appCommands] })
14
+ * const bar = menu(layout) // a ComputedRef of menu items
15
+ * ```
16
+ * ```vue
17
+ * <TaoMenubar :items="bar" @select="onSelect" />
18
+ * ```
19
+ */
20
+ /** What `useCommands` needs from a registry: `createCommands()` fits as it is. / Что `useCommands` нужно от реестра: `createCommands()` подходит как есть. */
21
+ export interface CommandRegistry<C, L, I> {
22
+ add(command: C | readonly C[]): () => void;
23
+ bind(target: EventTarget): () => void;
24
+ toMenu(layout: L): I[];
25
+ run(id: string): boolean;
26
+ }
27
+ export interface UseCommandsOptions<C> {
28
+ /** Commands of this component: added now, removed when it goes. / Команды этого компонента: добавляются сразу, убираются вместе с ним. */
29
+ add?: readonly C[];
30
+ /** Where the shortcuts are listened to. Default: `window`. `false`: do not listen (the menu only). / Где слушать сочетания. По умолчанию `window`. `false`: не слушать (только меню). */
31
+ target?: EventTarget | false;
32
+ }
33
+ export interface UseCommands<L, I> {
34
+ /** A menu from a layout, as a `computed`: it is made again when a state that a label, `enabled` or `checked` reads changes. / Меню по раскладке как `computed`: пересобирается, когда меняется состояние, которое читают подпись, `enabled` или `checked`. */
35
+ menu(layout: L): ComputedRef<I[]>;
36
+ /**
37
+ * For `@select` of a menu: runs the command named by the item. It takes the item that TaoUI 6 emits (not a bare id); returns whether
38
+ * it ran (a disabled command does not).
39
+ * Для `@select` меню: выполняет команду, названную пунктом. Берёт пункт, который отдаёт TaoUI 6 (не голый id); возвращает,
40
+ * выполнилась ли команда (недоступная — нет).
41
+ */
42
+ onSelect(item: {
43
+ id?: string;
44
+ } | string): boolean;
45
+ run(id: string): boolean;
46
+ }
47
+ export declare function useCommands<C, L, I>(registry: CommandRegistry<C, L, I>, options?: UseCommandsOptions<C>): UseCommands<L, I>;