@1337exp/taoux 0.4.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,23 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.5.1
4
+
5
+ - **`swiperow`: the actions show without a jump.** The icon and the label always stand where they end up (nothing pops into the layout, so the heights stay), and only their opacity follows the width of their block: the icon fades in first, the label later, once the block holds it. The start action is one line from the start edge, the icon first. A short fade covers the moment the row settles by itself. The `action` slot gets the block's `width`.
6
+ - **`swiperow`: nothing behind, nothing trailing.** On a long pull to the end the start action showed at the start edge: its panel kept a 6px padding and did not clip. The panel clips now and the gap is the button's margin, so at width 0 nothing of it is left (the keyboard still reaches it). Under the finger the actions trailed the row (their widths eased all the time the full swipe was armed, and the icons and labels faded with a delay): now they follow in the same frame, and only the moment the full swipe arms or disarms eases the widths.
7
+ - **`swiperow`: the middle actions give way instead of the widths jumping.** Up to the open width the end actions grow evenly, as before. Past it the actions between the row and the last one stop at their width and shrink back, smoothly, to slivers (`SWIPE_SLIVER_PX`, 32px) a fifth of the row past the full-swipe threshold, and the last action takes the room they give up; further on they stay slivers, a visible link, and a pull back opens them out the same way. `endWidths` is one continuous function of the pull (the `armed` argument is kept but no longer used), so the eased switch when the full swipe armed is gone too.
8
+ - **A held gesture lets go when the window loses the focus.** Alt-Tab or a screenshot tool often swallow the `pointerup` of a press that was held: a swipe row stayed pulled and a dragged list item stayed lifted when the user came back. `TaoxSwipeRow` and `useSortable` now end the gesture on a window blur, a hidden page or `pagehide`, and the row or the item goes back to rest, as TaoUI's carousel and slider do. The listener is exported as `listenFocusLoss` from `gestures`.
9
+ - `swiperow`: the icon and the label of an end action sit a little closer (gap 2px, icon 20px), not pressed to the edges of a short row.
10
+ - The sandbox has a second list with no start action: those rows go only to the left.
11
+ - The sandbox mail list sets the actions per row: a newsletter has More, Unsubscribe, Delete; a letter from a person only More and Delete.
12
+ - **Docs:** «Why TaoUX» tells what it is now (gestures and lists, undo by records, storage across tabs, the tiers, the skill), and the skill's description names the new modules. A `taoux-dev` skill for working in the repository (`.claude/skills`, now tracked).
13
+
14
+ ## 0.5.0
15
+
16
+ - **New module `swiperow` (tier 2, Vue, on TaoUI): `TaoxSwipeRow`, a list row a finger slides sideways, as in a mail app.** To the start (right) one action is behind the row: a pull past its threshold (96px, or a third of a narrow row; or flung that way past half of it) runs it on release and the row comes back, as read / unread. To the end (left) the actions grow out evenly from slivers to their width and the row rests open on them (`v-model:open`), by the nearest stop or a fling; a pull back, a touch outside or an action closes it. Pulled far (60% of the width), the full swipe is armed: the last action takes nearly the whole row, the others shrink to slivers, and the release runs it (delete; `fullSwipe: false` turns it off). Armed actions buzz where the phone can. A vertical move stays the page's scroll; a mouse drags only with `mouse`; the click at the end of a swipe does not reach the row; Tab reaches the actions and opens their side. The gesture is `SwipeTracker` of `gestures`; the decisions are pure and exported (`swipeRowRelease`, `armedAt`, `endWidths`, `clampOffset`). Import `@1337exp/taoux/swiperow.css`. A sandbox page shows a mail list.
17
+ - The sandbox and the tests now run on TaoUI 5.6.2 (dev dependency; the peer range stays `^5.0.0`).
18
+
19
+ - **New module `sortable` (tier 1, Vue): reorder a list by a grip, with the pointer and the keyboard.** `useSortable(listRef, { onMove })` listens on the list; the markup is yours: `data-sortable-item` on each item, in order, and `data-sortable-handle` on a focusable grip inside it (a TaoButton with `icon="tao-grip"`). The pointer: press the grip, the item follows and the others make room (by its size and the gap), the list (or the page) scrolls at its edge through `edgescroll`, release drops it, Esc puts it back; past the ends it is drawn no further than the end (it would stretch the scrolled area and run away with the edge scroll) and lands in the last place. The keyboard: Space or Enter lifts, ↑ ↓ (← → with `axis: 'x'`) move one place, Space / Enter drop, Esc returns it where it started, Tab drops it where it is; a live region of its own says where the item is (`sortableTextsEn` / `sortableTextsRu`, or your `texts`, a function follows the language). The list stays the app's: `onMove(from, to)`, and `moveItem(list, from, to)` makes the moved copy. While moving, the item carries `data-sortable-dragging` or `data-sortable-lifted` for your styles. Pure helpers `sortTarget` and `sortShifts` are exported and tested. A sandbox page shows it with TaoUI.
20
+
3
21
  ## 0.4.0
4
22
 
5
23
  - **New module `undo` (tier 0): undo and redo by records.** `UndoStack` keeps steps made of only the records they touched (`before` and `after` images), not snapshots of the whole document as `History` does, so a step costs what it changed, and an undo after a sync does not roll back what another device has just changed. `diffRecords(prev, next, id)` makes a step from two lists (records are immutable, found by identity); `record(entry, key?)` merges quick edits with one key within `coalesceMs` (3 s) into one step; `undo(current)` / `redo(current)` take the current list and return the next one. Two hooks carry what only the app knows: `revive(image, now)` stamps a returned record as new (`updatedAt: now`), and `vanish(record, now)` marks a record the step created as gone instead of erasing it (a tombstone; without it the record is dropped). A record that comes back takes its old place (a step keeps where its records stood, `beforeAt` / `afterAt`), so a note removed from the middle returns to the middle and «delete all» undone is the same list in the same order; the nearest place if the list changed meanwhile. The merge window slides with every edit, so typing without a pause stays one step; `coalesceMaxMs` caps how long a merged step may grow (no cap by default). It came out of Next Up's `core/undo.ts`; nothing else changes.
package/README.md CHANGED
@@ -27,11 +27,13 @@
27
27
 
28
28
  ## Why TaoUX
29
29
 
30
- - **Pay for what you use.** Every module is its own subpath import with its own entry point: `import { zoomAt } from '@1337exp/taoux/camera'`. `sideEffects` is declared, the rest tree-shakes.
31
- - **Logic first.** The core of a module (camera maths, history, easing, playback) is plain TypeScript with no Vue or DOM unless that is its job, and it is unit-tested that way. Components are thin shells on top.
32
- - **Your design.** Components are styled by `--tx-*` CSS variables with sensible dark defaults. No design system is required.
33
- - **Works with TaoUI in one line.** `import '@1337exp/taoux/taoui.css'` and the editors follow the TaoUI theme. [Details below.](#with-taoui)
34
- - **Typed i18n, undo/redo, autosave, playback** and the other things every editor-like app ends up writing again.
30
+ - **Pay for what you use.** Every module is its own subpath import with its own entry point: `import { zoomAt } from '@1337exp/taoux/camera'`. `sideEffects` is declared, the rest tree-shakes; there is no root entry, so nothing you did not import reaches the bundle.
31
+ - **Logic first, tested without a browser.** The core of a module (camera maths, undo, easing, playback, where a swiped row comes to rest) is plain TypeScript, unit-tested with no DOM. The Vue parts are thin shells on top.
32
+ - **Fingers and keys alike.** Taps, long presses, pinches and swipes that tell a swipe from a scroll; lists reordered by a grip (`sortable`) and rows slid aside for their actions (`swiperow`), each with a keyboard path and a live region for a screen reader.
33
+ - **For apps, not only editors.** Undo by records that is safe next to a sync (`undo`), autosave that never throws and hears other tabs (`storage`), UUIDs for stored records, typed i18n, commands and hotkeys that build the menus.
34
+ - **Your design, or TaoUI in one line.** Components take `--tx-*` CSS variables with dark defaults; `import '@1337exp/taoux/taoui.css'` makes them follow the TaoUI theme and palettes. [Details below.](#with-taoui)
35
+ - **Layers you can rely on.** Primitives import nothing, composites only primitives, and only the fields (`curvefield`, `swiperow`) touch TaoUI: a test reads the imports and keeps it so.
36
+ - **Ready for AI assistants.** The package ships a skill that names every module and the usual mistakes, so an assistant writes TaoUX code instead of guessing.
35
37
 
36
38
  <table>
37
39
  <tr>
@@ -48,7 +50,7 @@
48
50
 
49
51
  ```bash
50
52
  npm install @1337exp/taoux
51
- npm install @1337exp/taoui # optional: only for curvefield and the TaoUI bridge
53
+ npm install @1337exp/taoui # optional: only for curvefield, swiperow and the TaoUI bridge
52
54
  ```
53
55
 
54
56
  Peers: `vue ^3.4` (for the Vue modules) and, optionally, `@1337exp/taoui ^5.0.0`. Modules without Vue need nothing.
@@ -88,25 +90,27 @@ import { History } from '@1337exp/taoux/history';
88
90
  | `snap` | soft snapping to a grid with a threshold that follows the camera zoom | nothing |
89
91
  | `wheel` | wheel/trackpad → pan or zoom (like Figma) | nothing |
90
92
  | `edgescroll` | auto-scroll speed near an edge and a ready loop, `createEdgeScroller` (canvas, curve editors, any drag) | nothing |
91
- | `gestures` | touch gestures: tap, double tap, long press, pinch, swipe (`SwipeTracker` + `settleOpen` for a row that slides open) | nothing |
93
+ | `gestures` | touch gestures: tap, double tap, long press, pinch, swipe (`SwipeTracker` + `settleOpen` for a row that slides open); `listenFocusLoss` ends a held gesture when the window loses the focus | nothing |
92
94
  | `touch` | `coarse`: is there a coarse pointer (a finger) | vue (peer) |
93
95
  | `curve` | link paths: bezier between pins, arrowheads of constant screen size | nothing |
94
96
  | `ids` | `uuid()` for records that are stored or synced; `uid(prefix, taken)` for ids inside one document | nothing |
95
97
  | `ease` | easing functions between curve points: 8 families × in / out / in-out, `linear`, `step`, cubic Bezier; `easeValue`, `isEase` (the editor draws with it, a runtime evaluates with it) | nothing |
96
98
  | `num` | small numeric helpers: `clamp`, `roundTo`, `snapTo`, `niceStep`, `ticks` (shared by the curve, gradient and playback modules) | nothing |
99
+ | `sortable` (Vue) | reorder a list by a grip and by the keyboard: `useSortable(listRef, { onMove })`, `data-sortable-item` / `data-sortable-handle`; the others make room, the list scrolls at its edge, Esc puts it back, a live region tells a screen reader; `moveItem` | vue (peer) |
97
100
  | `session` | document lifecycle: history, autosave, files, restore, notices; a canvas camera is optional (`countItems`) | vue (peer) |
98
101
  | `commands` | a registry of commands (label, shortcut, `enabled`, `checked`, `run`): `toMenu(layout)` builds a `TaoMenuItem[]` tree for `TaoMenubar` / `TaoContextMenu`, `bind` listens to the same shortcuts, `historyCommands` gives Undo / Redo that disable themselves, `check` finds reserved and duplicate shortcuts | DOM (for `bind`) |
99
102
  | `palette` | search and groups of nodes for a palette | nothing |
100
103
  | `links` (Vue) | links layer: SVG from ready geometry, `--tx-link-*` | vue (peer) |
101
104
  | `canvas` (Vue) | canvas: mouse and touch gestures, wheel, auto-scroll, keys; the `CanvasHost` contract | vue (peer) |
102
105
  | `curveeditor` (Vue) | curve editor plot: grid, snapping, bounds, decimals, auto-scroll at the edge; point operations; per-segment transitions with Bezier handles; keyboard (Tab, arrows, Shift, Insert, Delete) | vue (peer) |
106
+ | `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) |
103
107
  | `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) |
104
108
  | `gradienteditor` (Vue) | gradient bar with stop handles; stop operations, `gradientCss`; keyboard (Tab, arrows, Home/End, Insert, Delete) | vue (peer) |
105
109
  | `playback` | playback model: time, pause, loop, speed, seeking; `createPlayback` without Vue and `usePlayback` for a component | vue (peer, for `usePlayback`) |
106
110
  | `pins` | row pin positions measured from the DOM: `usePinMeasure`, `createPinRegistry` | vue (peer) |
107
111
  | `i18n` | typed i18n: `createI18n({ locales, fallback, storageKey })` | vue (peer, optional) |
108
112
 
109
- Vue modules (`links`, `canvas`, `curveeditor`, `curvefield`, `gradienteditor`) need their styles imported explicitly: `import '@1337exp/taoux/canvas.css'`. Composite modules (session, commands, palette, links, canvas, pins, curveeditor, gradienteditor, playback) import only primitives. Tier 2, fields (`curvefield`), assemble composites into a ready field on TaoUI components: it is the only tier allowed to import TaoUI, which is why `@1337exp/taoui` is an optional peer dependency. `curvefield` needs both `curveeditor.css` and `curvefield.css`. The `tiers.test.ts` test guards all of that. The canvas contract is described in [docs/canvas.md](docs/canvas.md) ([Русский](docs/canvas.ru.md)); transitions between curve points are in [docs/ease.md](docs/ease.md) ([Русский](docs/ease.ru.md)).
113
+ Vue modules (`links`, `canvas`, `curveeditor`, `curvefield`, `gradienteditor`, `swiperow`) need their styles imported explicitly: `import '@1337exp/taoux/canvas.css'`. Composite modules (session, commands, palette, links, canvas, pins, curveeditor, gradienteditor, playback) import only primitives. Tier 2, fields (`curvefield`, `swiperow`), assemble composites into a ready field on TaoUI components: it is the only tier allowed to import TaoUI, which is why `@1337exp/taoui` is an optional peer dependency. `curvefield` needs both `curveeditor.css` and `curvefield.css`. The `tiers.test.ts` test guards all of that. The canvas contract is described in [docs/canvas.md](docs/canvas.md) ([Русский](docs/canvas.ru.md)); transitions between curve points are in [docs/ease.md](docs/ease.md) ([Русский](docs/ease.ru.md)).
110
114
 
111
115
  The rule: a module lands here when a second project needs it. A module's core knows nothing about Vue or the DOM unless that is its job.
112
116
 
@@ -130,7 +134,7 @@ Working against a local checkout instead of npm: put `"@1337exp/taoux": "file:..
130
134
 
131
135
  ## Sandbox
132
136
 
133
- The `sandbox/` folder is a demo and a testing ground: pages import the modules straight from `src/`, with no build. It holds `curveeditor`, `curvefield`, `gradienteditor`, `slider`, `color` and `playback`, with an EN / RU switch and a dark / light switch (the TaoUI theme, through the bridge). A new page is `sandbox/<name>.html` + `.ts` + a demo `.vue` and a link in `sandbox/index.html`. `npm run sandbox:build` makes a static copy with relative paths, ready for any folder (for example `/sandbox/taoux/`).
137
+ The `sandbox/` folder is a demo and a testing ground: pages import the modules straight from `src/`, with no build. It holds `curveeditor`, `curvefield`, `gradienteditor`, `slider`, `color`, `playback`, `sortable` and `swiperow`, with an EN / RU switch and a dark / light switch (the TaoUI theme, through the bridge). A new page is `sandbox/<name>.html` + `.ts` + a demo `.vue` and a link in `sandbox/index.html`. `npm run sandbox:build` makes a static copy with relative paths, ready for any folder (for example `/sandbox/taoux/`).
134
138
 
135
139
  Screenshots and clips in this README come from the sandbox: see [docs/media](docs/media/README.md).
136
140
 
package/README.ru.md CHANGED
@@ -27,11 +27,13 @@
27
27
 
28
28
  ## Почему TaoUX
29
29
 
30
- - **Платите только за используемое.** Каждый модуль это свой subpath-импорт и своя точка входа: `import { zoomAt } from '@1337exp/taoux/camera'`. `sideEffects` объявлен, остальное режется tree-shaking'ом.
31
- - **Сначала логика.** Ядро модуля (математика камеры, история, easing, воспроизведение) это обычный TypeScript без Vue и DOM, если это не его задача, и тесты написаны именно так. Компоненты тонкая оболочка сверху.
32
- - **Ваш дизайн.** Компоненты настраиваются CSS-переменными `--tx-*` с разумными тёмными значениями по умолчанию. Дизайн-система не обязательна.
33
- - **С TaoUI в одну строку.** `import '@1337exp/taoux/taoui.css'`, и редакторы следуют теме TaoUI. [Подробности ниже.](#с-taoui)
34
- - **Типизированный i18n, undo/redo, автосохранение, воспроизведение** и остальное, что каждое приложение-редактор пишет заново.
30
+ - **Платите только за используемое.** Каждый модуль — свой subpath-импорт и своя точка входа: `import { zoomAt } from '@1337exp/taoux/camera'`. `sideEffects` объявлен, остальное режется tree-shaking'ом; общей точки входа нет, поэтому в сборку не попадает ничего, что вы не импортировали.
31
+ - **Сначала логика, проверенная без браузера.** Ядро модуля (математика камеры, отмена, easing, воспроизведение, где остановится сдвинутая строка) — обычный TypeScript с тестами без DOM. Vue-части — тонкая оболочка сверху.
32
+ - **И пальцем, и с клавиатуры.** Тапы, долгие нажатия, щипки и свайпы, которые отличают свайп от прокрутки; списки, которые переставляют за ручку (`sortable`), и строки, которые сдвигают ради действий (`swiperow`), — у каждого есть путь с клавиатуры и живой регион для скринридера.
33
+ - **Для приложений, не только для редакторов.** Отмена по записям, безопасная рядом с синхронизацией (`undo`), автосохранение, которое не бросает исключений и слышит другие вкладки (`storage`), UUID для хранимых записей, типизированный i18n, команды и горячие клавиши, из которых строятся меню.
34
+ - **Ваш дизайн или TaoUI одной строкой.** Компоненты настраиваются CSS-переменными `--tx-*` с тёмными значениями по умолчанию; `import '@1337exp/taoux/taoui.css'` — и они следуют теме и палитрам TaoUI. [Подробности ниже.](#с-taoui)
35
+ - **Ярусы, на которые можно положиться.** Примитивы ничего не импортируют, составные — только примитивы, и только поля (`curvefield`, `swiperow`) касаются TaoUI: тест читает импорты и следит за этим.
36
+ - **Готов для ИИ-ассистентов.** В пакете есть skill, который называет каждый модуль и частые ошибки, поэтому ассистент пишет код на TaoUX, а не угадывает.
35
37
 
36
38
  <table>
37
39
  <tr>
@@ -48,7 +50,7 @@
48
50
 
49
51
  ```bash
50
52
  npm install @1337exp/taoux
51
- npm install @1337exp/taoui # по желанию: только для curvefield и моста к TaoUI
53
+ npm install @1337exp/taoui # по желанию: только для curvefield, swiperow и моста к TaoUI
52
54
  ```
53
55
 
54
56
  Peer-зависимости: `vue ^3.4` (для Vue-модулей) и, по желанию, `@1337exp/taoui ^5.0.0`. Модулям без Vue ничего не нужно.
@@ -88,25 +90,27 @@ import { History } from '@1337exp/taoux/history';
88
90
  | `snap` | мягкая привязка к сетке с порогом по масштабу камеры | нет |
89
91
  | `wheel` | колесо/тачпад → pan или zoom (как в Figma) | нет |
90
92
  | `edgescroll` | скорость автопрокрутки у края и готовый цикл `createEdgeScroller` (холст, редакторы кривых и любое перетаскивание) | нет |
91
- | `gestures` | сенсорные жесты: тап, двойной тап, долгое нажатие, щипок, свайп (`SwipeTracker` + `settleOpen` для строки, которая отъезжает) | нет |
93
+ | `gestures` | сенсорные жесты: тап, двойной тап, долгое нажатие, щипок, свайп (`SwipeTracker` + `settleOpen` для строки, которая отъезжает); `listenFocusLoss` завершает удерживаемый жест, когда окно теряет фокус | нет |
92
94
  | `touch` | `coarse` — есть ли грубый указатель (палец) | vue (peer) |
93
95
  | `curve` | пути связей: безье между пинами, стрелки постоянного экранного размера | нет |
94
96
  | `ids` | `uuid()` для записей, которые хранятся или синхронизируются; `uid(prefix, taken)` для id внутри одного документа | нет |
95
97
  | `ease` | функции движения между точками кривой: 8 семейств × in / out / in-out, `linear`, `step`, кубический Безье; `easeValue`, `isEase` (редактор рисует ими, рантайм считает ими же) | нет |
96
98
  | `num` | мелкая числовая математика: `clamp`, `roundTo`, `snapTo`, `niceStep`, `ticks` (общая для кривой, градиента и воспроизведения) | нет |
99
+ | `sortable` (Vue) | перестановка списка за ручку и с клавиатуры: `useSortable(listRef, { onMove })`, `data-sortable-item` / `data-sortable-handle`; остальные расступаются, у края список прокручивается, Esc возвращает, живой регион сообщает скринридеру; `moveItem` | vue (peer) |
97
100
  | `session` | жизненный цикл документа: история, автосохранение, файлы, восстановление, уведомления; камера холста необязательна (`countItems`) | vue (peer) |
98
101
  | `commands` | реестр команд (подпись, сочетание, `enabled`, `checked`, `run`): `toMenu(layout)` строит дерево `TaoMenuItem[]` для `TaoMenubar` / `TaoContextMenu`, `bind` слушает те же сочетания, `historyCommands` даёт Undo / Redo, которые сами становятся недоступными, `check` находит занятые браузером и повторённые сочетания | DOM (для `bind`) |
99
102
  | `palette` | поиск и группы нод для палитры | нет |
100
103
  | `links` (Vue) | слой связей: SVG из готовой геометрии, `--tx-link-*` | vue (peer) |
101
104
  | `canvas` (Vue) | холст: жесты мыши и сенсора, колесо, автопрокрутка, клавиши; контракт `CanvasHost` | vue (peer) |
102
105
  | `curveeditor` (Vue) | поле редактора кривой: сетка, шаг, границы, знаки, автопрокрутка у края; операции над точками; переходы между точками с ручками Безье; клавиатура (Tab, стрелки, Shift, Insert, Delete) | vue (peer) |
106
+ | `swiperow` (Vue, ярус 2) | `TaoxSwipeRow`: строка списка, которую палец сдвигает вбок, как в почте: вправо одно действие, выполняется после порога (прочитано / не прочитано), влево действия вырастают и остаются открытыми, длинный свайп выполняет последнее (удалить); иконки и тона TaoUI, `@action="id => …"`; до действий можно дойти Tab | vue, **@1337exp/taoui** (peer) |
103
107
  | `curvefield` (Vue, ярус 2) | `TaoxCurveField`: кривая с полями на компонентах TaoUI: время и значение точки, переход к следующей точке (`ease`), шаг, удаление и сброс; надписи задаёт приложение | vue, **@1337exp/taoui** (peer) |
104
108
  | `gradienteditor` (Vue) | полоса градиента с ручками остановок; операции над остановками, `gradientCss`; клавиатура (Tab, стрелки, Home/End, Insert, Delete) | vue (peer) |
105
109
  | `playback` | модель воспроизведения: время, пауза, цикл, скорость, перемотка; `createPlayback` без Vue и `usePlayback` для компонента | vue (peer, для `usePlayback`) |
106
110
  | `pins` | позиции пинов-строк, измеренные по DOM: `usePinMeasure`, `createPinRegistry` | vue (peer) |
107
111
  | `i18n` | типизированный i18n: `createI18n({ locales, fallback, storageKey })` | vue (peer, опционально) |
108
112
 
109
- Vue-модули (`links`, `canvas`, `curveeditor`, `curvefield`, `gradienteditor`) требуют явного импорта стилей: `import '@1337exp/taoux/canvas.css'`. Составные модули (session, commands, palette, links, canvas, pins, curveeditor, gradienteditor, playback) импортируют только примитивы. Ярус 2, поля (`curvefield`), собирает составные модули в готовое поле на компонентах TaoUI: только ему можно импортировать TaoUI, поэтому `@1337exp/taoui` это необязательная peer-зависимость. Для `curvefield` нужны оба файла стилей, `curveeditor.css` и `curvefield.css`. Всё это охраняет тест `tiers.test.ts`; контракт холста описан в [docs/canvas.ru.md](docs/canvas.ru.md), переходы между точками кривой в [docs/ease.ru.md](docs/ease.ru.md).
113
+ Vue-модули (`links`, `canvas`, `curveeditor`, `curvefield`, `gradienteditor`, `swiperow`) требуют явного импорта стилей: `import '@1337exp/taoux/canvas.css'`. Составные модули (session, commands, palette, links, canvas, pins, curveeditor, gradienteditor, playback) импортируют только примитивы. Ярус 2, поля (`curvefield`, `swiperow`), собирает составные модули в готовое поле на компонентах TaoUI: только ему можно импортировать TaoUI, поэтому `@1337exp/taoui` это необязательная peer-зависимость. Для `curvefield` нужны оба файла стилей, `curveeditor.css` и `curvefield.css`. Всё это охраняет тест `tiers.test.ts`; контракт холста описан в [docs/canvas.ru.md](docs/canvas.ru.md), переходы между точками кривой в [docs/ease.ru.md](docs/ease.ru.md).
110
114
 
111
115
  Правило: модуль попадает сюда, когда он понадобился во втором проекте. Ядро модулей не знает про Vue и DOM, если это не их задача.
112
116
 
@@ -132,7 +136,7 @@ npm run dev # watch: пересборка JS и деклараций
132
136
 
133
137
  ## Песочница
134
138
 
135
- Папка `sandbox/` это демо и поле для проверки: страницы подключают модули прямо из `src/`, без сборки. Сейчас там `curveeditor`, `curvefield`, `gradienteditor`, `slider`, `color` и `playback`, с переключателем языка (EN / RU) и темы (тёмная / светлая: тема TaoUI через мост). Новая страница = `sandbox/<имя>.html` + `.ts` + демо `.vue` и ссылка в `sandbox/index.html`. `npm run sandbox:build` собирает статическую копию с относительными путями, её можно положить в любую папку (например, `/sandbox/taoux/`).
139
+ Папка `sandbox/` это демо и поле для проверки: страницы подключают модули прямо из `src/`, без сборки. Сейчас там `curveeditor`, `curvefield`, `gradienteditor`, `slider`, `color`, `playback`, `sortable` и `swiperow`, с переключателем языка (EN / RU) и темы (тёмная / светлая: тема TaoUI через мост). Новая страница = `sandbox/<имя>.html` + `.ts` + демо `.vue` и ссылка в `sandbox/index.html`. `npm run sandbox:build` собирает статическую копию с относительными путями, её можно положить в любую папку (например, `/sandbox/taoux/`).
136
140
 
137
141
  Скриншоты и ролики в этом README сняты с песочницы: см. [docs/media](docs/media/README.md).
138
142
 
@@ -250,4 +250,13 @@ export declare function settleOpen(release: SwipeRelease, open: {
250
250
  start?: number;
251
251
  end?: number;
252
252
  }, fling?: number): number;
253
+ /**
254
+ * Calls `onLoss` when the window really loses the focus: Alt-Tab, a screenshot tool, the tab hidden or left. Those often
255
+ * swallow the `pointerup` of a press that was held, and a drag would stay «pressed» after the user came back; end the
256
+ * gesture there. Returns the function that stops listening. The same rule as TaoUI's carousel and slider.
257
+ * Вызывает `onLoss`, когда окно действительно теряет фокус: Alt-Tab, программа скриншотов, вкладка скрыта или закрыта.
258
+ * Они часто глотают `pointerup` удерживаемого нажатия, и перетаскивание осталось бы «нажатым», когда пользователь
259
+ * вернётся; там жест и заканчивают. Возвращает функцию, которая прекращает слушать.
260
+ */
261
+ export declare function listenFocusLoss(onLoss: () => void): () => void;
253
262
  export {};
package/dist/gestures.js CHANGED
@@ -343,7 +343,29 @@ function settleOpen(release, open, fling = SWIPE_FLING_PX_PER_MS) {
343
343
  if (Math.abs(velocity) >= fling) return (velocity > 0 ? stops.filter((p) => p > offset) : stops.filter((p) => p < offset).reverse())[0] ?? (velocity > 0 ? stops[stops.length - 1] : stops[0]);
344
344
  return stops.reduce((best, p) => Math.abs(p - offset) < Math.abs(best - offset) ? p : best, 0);
345
345
  }
346
+ /**
347
+ * Calls `onLoss` when the window really loses the focus: Alt-Tab, a screenshot tool, the tab hidden or left. Those often
348
+ * swallow the `pointerup` of a press that was held, and a drag would stay «pressed» after the user came back; end the
349
+ * gesture there. Returns the function that stops listening. The same rule as TaoUI's carousel and slider.
350
+ * Вызывает `onLoss`, когда окно действительно теряет фокус: Alt-Tab, программа скриншотов, вкладка скрыта или закрыта.
351
+ * Они часто глотают `pointerup` удерживаемого нажатия, и перетаскивание осталось бы «нажатым», когда пользователь
352
+ * вернётся; там жест и заканчивают. Возвращает функцию, которая прекращает слушать.
353
+ */
354
+ function listenFocusLoss(onLoss) {
355
+ if (typeof window === "undefined") return () => {};
356
+ const onVisibility = () => {
357
+ if (document.hidden) onLoss();
358
+ };
359
+ document.addEventListener("visibilitychange", onVisibility);
360
+ window.addEventListener("blur", onLoss);
361
+ window.addEventListener("pagehide", onLoss);
362
+ return () => {
363
+ document.removeEventListener("visibilitychange", onVisibility);
364
+ window.removeEventListener("blur", onLoss);
365
+ window.removeEventListener("pagehide", onLoss);
366
+ };
367
+ }
346
368
  //#endregion
347
- export { DOUBLE_TAP_MS, DOUBLE_TAP_RADIUS_PX, LONG_PRESS_MS, PINCH_DEADBAND_PX, PINCH_DOMINANCE, PINCH_ENGAGE_PX, PINCH_MIN_NET_PX, PINCH_RELEASE_MIN_PX, PINCH_RELEASE_RATIO, PINCH_WINDOW, PinchTracker, SWIPE_FLING_PX_PER_MS, SWIPE_SLOP_PX, SWIPE_VELOCITY_WINDOW_MS, SwipeTracker, TAP_MAX_MS, TAP_SLOP_PX, TapRecognizer, pinchOf, settleOpen };
369
+ export { DOUBLE_TAP_MS, DOUBLE_TAP_RADIUS_PX, LONG_PRESS_MS, PINCH_DEADBAND_PX, PINCH_DOMINANCE, PINCH_ENGAGE_PX, PINCH_MIN_NET_PX, PINCH_RELEASE_MIN_PX, PINCH_RELEASE_RATIO, PINCH_WINDOW, PinchTracker, SWIPE_FLING_PX_PER_MS, SWIPE_SLOP_PX, SWIPE_VELOCITY_WINDOW_MS, SwipeTracker, TAP_MAX_MS, TAP_SLOP_PX, TapRecognizer, listenFocusLoss, pinchOf, settleOpen };
348
370
 
349
371
  //# sourceMappingURL=gestures.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"gestures.js","names":[],"sources":["../src/gestures.ts"],"sourcesContent":["/**\n * Recognition of touch gestures. Pure logic with no DOM and no timers: time and coordinates come from outside,\n * so everything is covered by tests. Events and timers (long press) live in EditorCanvas.\n * Распознавание сенсорных жестов. Чистая логика без DOM и таймеров: время и координаты приходят снаружи,\n * поэтому всё проверяется тестами. События и таймеры (долгое нажатие) живут в EditorCanvas.\n */\n\n/**\n * By how many px a finger may move and still count as \"standing still\".\n * На сколько px палец может сместиться и всё ещё считаться «стоящим на месте».\n */\nexport const TAP_SLOP_PX = 8;\n/**\n * A touch longer than this is no longer a tap.\n * Дольше этого касание уже не тап.\n */\nexport const TAP_MAX_MS = 300;\n/**\n * How long the finger must be held still for a long press.\n * Сколько надо держать палец неподвижно для долгого нажатия.\n */\nexport const LONG_PRESS_MS = 500;\n/**\n * The second tap must come no later and no further than this from the first.\n * Второй тап должен прийти не позже и не дальше этого от первого.\n */\nexport const DOUBLE_TAP_MS = 300;\nexport const DOUBLE_TAP_RADIUS_PX = 30;\n\nexport interface Sample {\n x: number;\n y: number;\n /**\n * Time, ms (any monotonic scale).\n * Время, мс (любая монотонная шкала).\n */\n t: number;\n}\n\nconst dist = (a: { x: number; y: number }, b: { x: number; y: number }) => Math.hypot(a.x - b.x, a.y - b.y);\n\nexport type TapResult = 'tap' | 'double' | null;\n\n/**\n * Parses a one-finger touch: tap, double tap, movement, readiness of a long press.\n * Разбирает касание одним пальцем: тап, двойной тап, сдвиг, готовность долгого нажатия.\n */\nexport class TapRecognizer {\n private start: Sample | null = null;\n private moved = false;\n private lastTap: Sample | null = null;\n private doubleDown = false;\n\n /**\n * The finger landed. Returns true if this is the second touch of a double tap (it is not finished yet:\n * a drag may follow, as in \"double tap and drag\").\n * Палец лёг. Возвращает true, если это второе касание двойного тапа (оно ещё не закончено:\n * дальше может быть протяжка, как «двойной тап и тянуть»).\n */\n down(s: Sample): boolean {\n this.start = s;\n this.moved = false;\n const prev = this.lastTap;\n this.doubleDown = prev !== null && s.t - prev.t <= DOUBLE_TAP_MS && dist(s, prev) <= DOUBLE_TAP_RADIUS_PX;\n return this.doubleDown;\n }\n\n /**\n * The finger moved. Returns true if it already left the slop (neither a tap nor a long press).\n * Палец сдвинулся. Возвращает true, если он уже ушёл дальше допуска (не тап и не долгое нажатие).\n */\n move(s: Sample): boolean {\n if (this.start && !this.moved && dist(s, this.start) > TAP_SLOP_PX) this.moved = true;\n return this.moved;\n }\n\n get isMoved(): boolean {\n return this.moved;\n }\n\n /**\n * Whether it is time to count the touch as a long press: the finger lies still longer than `LONG_PRESS_MS`.\n * Пора ли считать касание долгим нажатием: палец лежит на месте дольше `LONG_PRESS_MS`.\n */\n longPressDue(now: number): boolean {\n return this.start !== null && !this.moved && now - this.start.t >= LONG_PRESS_MS;\n }\n\n /**\n * The finger was lifted: what that was. After `double` the next tap counts as single again.\n * Палец поднят: что это было. После `double` следующий тап снова считается одиночным.\n */\n up(s: Sample): TapResult {\n const start = this.start;\n this.start = null;\n if (!start) return null;\n\n this.move(s);\n if (this.moved || s.t - start.t > TAP_MAX_MS) {\n this.lastTap = null;\n return null;\n }\n if (this.doubleDown) {\n this.lastTap = null;\n return 'double';\n }\n this.lastTap = s;\n return 'tap';\n }\n\n /**\n * The gesture turned out to be something else (a long press, a pinch, an interruption): forget both the current touch and the previous tap.\n * Жест оказался чем-то другим (долгое нажатие, щипок, прерывание): забываем и текущее касание, и предыдущий тап.\n */\n cancel(): void {\n this.start = null;\n this.lastTap = null;\n this.doubleDown = false;\n }\n}\n\n//--------------------------------------------------\n// Pinch and a two-finger gesture\n// Щипок и жест двумя пальцами\n\ntype Point = { x: number; y: number };\n\nexport interface Pinch {\n /**\n * The centre between the fingers.\n * Центр между пальцами.\n */\n cx: number;\n cy: number;\n /**\n * The distance between the fingers; 0 if there is one finger (then only a shift).\n * Расстояние между пальцами; 0, если палец один (тогда только сдвиг).\n */\n dist: number;\n}\n\nexport function pinchOf(a: Point, b?: Point): Pinch {\n if (!b) return { cx: a.x, cy: a.y, dist: 0 };\n return { cx: (a.x + b.x) / 2, cy: (a.y + b.y) / 2, dist: dist(a, b) };\n}\n\nexport interface PinchStep {\n /**\n * By how many times to change the scale.\n * Во сколько раз изменить масштаб.\n */\n factor: number;\n /**\n * Around which point (the centre before the step).\n * Вокруг какой точки (центр до шага).\n */\n pivot: [number, number];\n /**\n * By how much to shift the camera after the scale.\n * На сколько сдвинуть камеру после масштаба.\n */\n pan: [number, number];\n}\n\n/**\n * Until the distance between the fingers has changed by this much, the gesture counts as a plain shift: the scale is not touched.\n * Пока расстояние между пальцами не изменилось на столько, жест считается просто сдвигом: масштаб не трогаем.\n */\nexport const PINCH_ENGAGE_PX = 20;\n/**\n * Distance changes smaller than this count as finger jitter and are ignored.\n * Изменения расстояния мельче этого считаем дрожанием пальцев и игнорируем.\n */\nexport const PINCH_DEADBAND_PX = 1.5;\n/**\n * How many last steps we look at when deciding \"shifting or scaling\".\n * Сколько последних шагов смотрим, решая «сдвигают или масштабируют».\n */\nexport const PINCH_WINDOW = 6;\n/**\n * To turn the scale on, the distance over the window must change at least as much as the centre moves, and at least this much.\n * Для включения масштаба расстояние за окно должно меняться не меньше, чем сдвигается центр, и не меньше этого.\n */\nexport const PINCH_DOMINANCE = 1;\nexport const PINCH_MIN_NET_PX = 4;\n/**\n * The scale turns off again when the centre moves this many times further than the distance changes over the window (and at least `PINCH_RELEASE_MIN_PX`).\n * Масштаб выключается обратно, когда центр за окно уходит в столько раз дальше, чем меняется расстояние (и не меньше `PINCH_RELEASE_MIN_PX`).\n */\nexport const PINCH_RELEASE_RATIO = 2;\nexport const PINCH_RELEASE_MIN_PX = 12;\n\ninterface PinchDelta {\n dx: number;\n dy: number;\n dd: number;\n}\n\n/**\n * A two-finger gesture: shift and/or scale. The scale is the ratio of distances, and the distance between the fingers\n * drifts during an ordinary two-finger shift too, so it cannot be applied just like that.\n * Жест двумя пальцами: сдвиг и/или масштаб. Масштаб считается как отношение расстояний, а расстояние между\n * пальцами при обычном сдвиге двумя пальцами тоже «плывёт», поэтому его нельзя применять просто так.\n *\n * - The distance must change deliberately (`PINCH_ENGAGE_PX`), not build up by drift.\n * - Over the last `PINCH_WINDOW` steps the distance must change more than the centre moves:\n * while the fingers are carried together, the scale does not turn on however the distance floats. We look at the signed sum:\n * the browser sends finger movement one at a time, and \"one moved, the other caught up\" cancels out.\n * - Once the scale is on there is no jump (counting is from the current distance), and small jitter is cut by a\n * dead zone. If the fingers are then carried together, the scale turns off again.\n * - Расстояние должно измениться осознанно (`PINCH_ENGAGE_PX`), а не накопиться дрейфом.\n * - При этом за последние `PINCH_WINDOW` шагов расстояние должно меняться сильнее, чем сдвигается центр:\n * пока пальцы везут вместе, масштаб не включается, как бы расстояние ни плавало. Смотрим на сумму со знаком:\n * браузер присылает движение пальцев по одному, и «один сдвинулся, второй догнал» взаимно сокращается.\n * - Когда масштаб включился, скачка нет (отсчёт идёт от текущего расстояния), а мелкое дрожание отсекается\n * мёртвой зоной. Если потом пальцы повезли вместе, масштаб выключается обратно.\n *\n * The centre shift always works.\n * Сдвиг центра работает всегда.\n */\nexport class PinchTracker {\n private prev: Pinch = { cx: 0, cy: 0, dist: 0 };\n private startDist = 0;\n private baseDist = 0;\n private engaged = false;\n private recent: PinchDelta[] = [];\n\n /**\n * A new set of fingers (a gesture began or the number of fingers changed): count from scratch, there will be no jump.\n * Новый набор пальцев (жест начался или число пальцев изменилось): отсчёт заново, скачка не будет.\n */\n begin(p: Pinch): void {\n this.prev = p;\n this.startDist = p.dist;\n this.baseDist = p.dist;\n this.engaged = false;\n this.recent = [];\n }\n\n get isZooming(): boolean {\n return this.engaged;\n }\n\n update(next: Pinch): PinchStep {\n const step: PinchStep = {\n factor: 1,\n pivot: [this.prev.cx, this.prev.cy],\n pan: [next.cx - this.prev.cx, next.cy - this.prev.cy],\n };\n\n // With one finger (the distance is 0 either way) there is no scale.\n // С одним пальцем (расстояние 0 с любой стороны) масштаба нет.\n const twoFingers = this.startDist > 0 && next.dist > 0 && this.prev.dist > 0;\n this.recent.push({ dx: step.pan[0], dy: step.pan[1], dd: twoFingers ? next.dist - this.prev.dist : 0 });\n if (this.recent.length > PINCH_WINDOW) this.recent.shift();\n this.prev = next;\n if (!twoFingers) return step;\n\n let sx = 0;\n let sy = 0;\n let sd = 0;\n for (const d of this.recent) {\n sx += d.dx;\n sy += d.dy;\n sd += d.dd;\n }\n const netCenter = Math.hypot(sx, sy);\n const netDist = Math.abs(sd);\n\n if (!this.engaged) {\n const intentional = Math.abs(next.dist - this.startDist) >= PINCH_ENGAGE_PX;\n if (intentional && netDist >= PINCH_MIN_NET_PX && netDist >= PINCH_DOMINANCE * netCenter) {\n this.engaged = true;\n this.baseDist = next.dist; // counted from this moment: no jump / отсчёт с этого момента: без скачка\n }\n } else if (netCenter >= PINCH_RELEASE_MIN_PX && netCenter >= PINCH_RELEASE_RATIO * netDist) {\n // The fingers were carried together: the scale turns off, the new threshold is counted from the current distance.\n // Пальцы повезли вместе: масштаб выключаем, новый порог отсчитываем от нынешнего расстояния.\n this.engaged = false;\n this.startDist = next.dist;\n this.baseDist = next.dist;\n } else if (Math.abs(next.dist - this.baseDist) >= PINCH_DEADBAND_PX) {\n step.factor = next.dist / this.baseDist;\n this.baseDist = next.dist;\n }\n return step;\n }\n}\n\n//--------------------------------------------------\n// Swipe: a row that slides open to show its actions, a sheet pulled down\n// Свайп: строка, которая отъезжает и показывает действия, лист, который тянут вниз\n\n/**\n * How far the finger moves before the intent is decided: a swipe along the axis, or a scroll across it.\n * Сколько палец проходит, прежде чем решается намерение: свайп вдоль оси или прокрутка поперёк.\n */\nexport const SWIPE_SLOP_PX = 10;\n/**\n * A release faster than this (px/ms) is a fling: it goes on in its direction whatever the offset.\n * Отпускание быстрее этого (px/мс) — бросок: он продолжается в своём направлении при любом сдвиге.\n */\nexport const SWIPE_FLING_PX_PER_MS = 0.4;\n/**\n * The release speed is measured over this last stretch of the gesture, ms.\n * Скорость отпускания меряется на этом последнем отрезке жеста, мс.\n */\nexport const SWIPE_VELOCITY_WINDOW_MS = 100;\n\n/**\n * `pending` — not decided yet (inside the slop); `swipe` — along the axis, the app moves the row; `scroll` — across,\n * the gesture belongs to the page and the tracker ignores it until the next `down`.\n * `pending` — ещё не решено (в пределах допуска); `swipe` — вдоль оси, приложение двигает строку; `scroll` — поперёк,\n * жест принадлежит странице, и трекер его игнорирует до следующего `down`.\n */\nexport type SwipeIntent = 'pending' | 'swipe' | 'scroll';\n\nexport interface SwipeStep {\n intent: SwipeIntent;\n /**\n * Where the row stands now: the offset it had at `down` plus the travel since the swipe engaged (so it does not\n * jump by the slop).\n * Где строка сейчас: сдвиг на момент `down` плюс путь с момента, как свайп включился (поэтому без скачка на допуск).\n */\n offset: number;\n}\n\nexport interface SwipeRelease {\n offset: number;\n /** px/ms along the axis, + to the right / down. / px/мс вдоль оси, + вправо / вниз. */\n velocity: number;\n}\n\n/**\n * Tells a swipe from a scroll and follows it. Pure logic, as the other recognizers: the app feeds it pointer samples,\n * moves the element by `offset` and, on release, asks `settleOpen` where the element should come to rest.\n * Отличает свайп от прокрутки и ведёт его. Чистая логика, как остальные распознаватели: приложение подаёт отсчёты\n * указателя, двигает элемент на `offset`, а при отпускании спрашивает `settleOpen`, где элементу остановиться.\n */\nexport class SwipeTracker {\n private start: Sample | null = null;\n private from = 0;\n private engage: Sample | null = null;\n private intent: SwipeIntent = 'pending';\n private trail: Sample[] = [];\n\n constructor(\n private readonly axis: 'x' | 'y' = 'x',\n private readonly slop: number = SWIPE_SLOP_PX,\n ) {}\n\n private along(s: Sample): number {\n return this.axis === 'x' ? s.x : s.y;\n }\n\n private across(s: Sample): number {\n return this.axis === 'x' ? s.y : s.x;\n }\n\n /**\n * The finger landed. `from` is where the row already stands (0 closed, or its open offset).\n * Палец лёг. `from` — где строка уже стоит (0 — закрыта, или её открытый сдвиг).\n */\n down(s: Sample, from = 0): void {\n this.start = s;\n this.from = from;\n this.engage = null;\n this.intent = 'pending';\n this.trail = [s];\n }\n\n move(s: Sample): SwipeStep {\n const start = this.start;\n if (!start || this.intent === 'scroll') return { intent: this.intent, offset: this.from };\n\n if (this.intent === 'pending') {\n const da = Math.abs(this.along(s) - this.along(start));\n const dc = Math.abs(this.across(s) - this.across(start));\n if (Math.max(da, dc) <= this.slop) return { intent: 'pending', offset: this.from };\n // the axis wins only when it leads: a diagonal goes to the page / ось побеждает, только если ведёт: диагональ — странице\n this.intent = da > dc ? 'swipe' : 'scroll';\n if (this.intent === 'scroll') return { intent: 'scroll', offset: this.from };\n this.engage = s;\n }\n\n this.trail.push(s);\n while (this.trail.length > 2 && s.t - this.trail[0]!.t > SWIPE_VELOCITY_WINDOW_MS) this.trail.shift();\n return { intent: 'swipe', offset: this.from + this.along(s) - this.along(this.engage!) };\n }\n\n /**\n * The finger was lifted. Null unless it was a swipe.\n * Палец поднят. Null, если это был не свайп.\n */\n up(s: Sample): SwipeRelease | null {\n const step = this.move(s);\n const swiped = this.intent === 'swipe';\n const first = this.trail[0];\n this.start = null;\n if (!swiped || !first) return null;\n const dt = s.t - first.t;\n const velocity = dt > 0 ? (this.along(s) - this.along(first)) / dt : 0;\n return { offset: step.offset, velocity };\n }\n\n cancel(): void {\n this.start = null;\n this.intent = 'pending';\n this.trail = [];\n }\n\n get current(): SwipeIntent {\n return this.intent;\n }\n}\n\n/**\n * Where a released row comes to rest: closed (0), open at the start (`start`, > 0, actions on the left) or open at\n * the end (`-end`, actions on the right). A fling goes on in its direction, one stop at a time (an open row flung\n * back closes, it does not fly to the other side); otherwise the nearest stop wins.\n * Где отпущенная строка останавливается: закрыта (0), открыта в начале (`start`, > 0, действия слева) или в конце\n * (`-end`, действия справа). Бросок продолжается в своём направлении на одну остановку (открытая строка, брошенная\n * обратно, закрывается, а не улетает на другую сторону); иначе побеждает ближайшая остановка.\n */\nexport function settleOpen(\n release: SwipeRelease,\n open: { start?: number; end?: number },\n fling: number = SWIPE_FLING_PX_PER_MS,\n): number {\n const stops = [0];\n if (open.start) stops.push(open.start);\n if (open.end) stops.push(-open.end);\n stops.sort((a, b) => a - b);\n\n const { offset, velocity } = release;\n if (Math.abs(velocity) >= fling) {\n // the stop beyond the offset in the direction of the fling, or the last one / остановка за сдвигом по ходу броска\n const ahead = velocity > 0 ? stops.filter((p) => p > offset) : stops.filter((p) => p < offset).reverse();\n return ahead[0] ?? (velocity > 0 ? stops[stops.length - 1]! : stops[0]!);\n }\n return stops.reduce((best, p) => (Math.abs(p - offset) < Math.abs(best - offset) ? p : best), 0);\n}\n"],"mappings":";;;;;;;;;;;AAWA,IAAa,cAAc;;;;;AAK3B,IAAa,aAAa;;;;;AAK1B,IAAa,gBAAgB;;;;;AAK7B,IAAa,gBAAgB;AAC7B,IAAa,uBAAuB;AAYpC,IAAM,QAAQ,GAA6B,MAAgC,KAAK,MAAM,EAAE,IAAI,EAAE,GAAG,EAAE,IAAI,EAAE,CAAC;;;;;AAQ1G,IAAa,gBAAb,MAA2B;CACvB,QAA+B;CAC/B,QAAgB;CAChB,UAAiC;CACjC,aAAqB;;;;;;;CAQrB,KAAK,GAAoB;EACrB,KAAK,QAAQ;EACb,KAAK,QAAQ;EACb,MAAM,OAAO,KAAK;EAClB,KAAK,aAAa,SAAS,QAAQ,EAAE,IAAI,KAAK,KAAA,OAAsB,KAAK,GAAG,IAAI,KAAA;EAChF,OAAO,KAAK;CAChB;;;;;CAMA,KAAK,GAAoB;EACrB,IAAI,KAAK,SAAS,CAAC,KAAK,SAAS,KAAK,GAAG,KAAK,KAAK,IAAA,GAAiB,KAAK,QAAQ;EACjF,OAAO,KAAK;CAChB;CAEA,IAAI,UAAmB;EACnB,OAAO,KAAK;CAChB;;;;;CAMA,aAAa,KAAsB;EAC/B,OAAO,KAAK,UAAU,QAAQ,CAAC,KAAK,SAAS,MAAM,KAAK,MAAM,KAAA;CAClE;;;;;CAMA,GAAG,GAAsB;EACrB,MAAM,QAAQ,KAAK;EACnB,KAAK,QAAQ;EACb,IAAI,CAAC,OAAO,OAAO;EAEnB,KAAK,KAAK,CAAC;EACX,IAAI,KAAK,SAAS,EAAE,I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,OAAO,OAAO;EAC9B,MAAM,KAAK,EAAE,IAAI,MAAM;EACvB,MAAM,WAAW,KAAK,KAAK,KAAK,MAAM,CAAC,IAAI,KAAK,MAAM,KAAK,KAAK,KAAK;EACrE,OAAO;GAAE,QAAQ,KAAK;GAAQ;EAAS;CAC3C;CAEA,SAAe;EACX,KAAK,QAAQ;EACb,KAAK,SAAS;EACd,KAAK,QAAQ,CAAC;CAClB;CAEA,IAAI,UAAuB;EACvB,OAAO,KAAK;CAChB;AACJ;;;;;;;;;AAUA,SAAgB,WACZ,SACA,MACA,QAAgB,uBACV;CACN,MAAM,QAAQ,CAAC,CAAC;CAChB,IAAI,KAAK,OAAO,MAAM,KAAK,KAAK,KAAK;CACrC,IAAI,KAAK,KAAK,MAAM,KAAK,CAAC,KAAK,GAAG;CAClC,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC;CAE1B,MAAM,EAAE,QAAQ,aAAa;CAC7B,IAAI,KAAK,IAAI,QAAQ,KAAK,OAGtB,QADc,WAAW,IAAI,MAAM,QAAQ,MAAM,IAAI,MAAM,IAAI,MAAM,QAAQ,MAAM,IAAI,MAAM,CAAC,CAAC,QAAQ,EAAA,CAC1F,OAAO,WAAW,IAAI,MAAM,MAAM,SAAS,KAAM,MAAM;CAExE,OAAO,MAAM,QAAQ,MAAM,MAAO,KAAK,IAAI,IAAI,MAAM,IAAI,KAAK,IAAI,OAAO,MAAM,IAAI,IAAI,MAAO,CAAC;AACnG"}
1
+ {"version":3,"file":"gestures.js","names":[],"sources":["../src/gestures.ts"],"sourcesContent":["/**\n * Recognition of touch gestures. Pure logic with no DOM and no timers: time and coordinates come from outside,\n * so everything is covered by tests. Events and timers (long press) live in EditorCanvas.\n * Распознавание сенсорных жестов. Чистая логика без DOM и таймеров: время и координаты приходят снаружи,\n * поэтому всё проверяется тестами. События и таймеры (долгое нажатие) живут в EditorCanvas.\n */\n\n/**\n * By how many px a finger may move and still count as \"standing still\".\n * На сколько px палец может сместиться и всё ещё считаться «стоящим на месте».\n */\nexport const TAP_SLOP_PX = 8;\n/**\n * A touch longer than this is no longer a tap.\n * Дольше этого касание уже не тап.\n */\nexport const TAP_MAX_MS = 300;\n/**\n * How long the finger must be held still for a long press.\n * Сколько надо держать палец неподвижно для долгого нажатия.\n */\nexport const LONG_PRESS_MS = 500;\n/**\n * The second tap must come no later and no further than this from the first.\n * Второй тап должен прийти не позже и не дальше этого от первого.\n */\nexport const DOUBLE_TAP_MS = 300;\nexport const DOUBLE_TAP_RADIUS_PX = 30;\n\nexport interface Sample {\n x: number;\n y: number;\n /**\n * Time, ms (any monotonic scale).\n * Время, мс (любая монотонная шкала).\n */\n t: number;\n}\n\nconst dist = (a: { x: number; y: number }, b: { x: number; y: number }) => Math.hypot(a.x - b.x, a.y - b.y);\n\nexport type TapResult = 'tap' | 'double' | null;\n\n/**\n * Parses a one-finger touch: tap, double tap, movement, readiness of a long press.\n * Разбирает касание одним пальцем: тап, двойной тап, сдвиг, готовность долгого нажатия.\n */\nexport class TapRecognizer {\n private start: Sample | null = null;\n private moved = false;\n private lastTap: Sample | null = null;\n private doubleDown = false;\n\n /**\n * The finger landed. Returns true if this is the second touch of a double tap (it is not finished yet:\n * a drag may follow, as in \"double tap and drag\").\n * Палец лёг. Возвращает true, если это второе касание двойного тапа (оно ещё не закончено:\n * дальше может быть протяжка, как «двойной тап и тянуть»).\n */\n down(s: Sample): boolean {\n this.start = s;\n this.moved = false;\n const prev = this.lastTap;\n this.doubleDown = prev !== null && s.t - prev.t <= DOUBLE_TAP_MS && dist(s, prev) <= DOUBLE_TAP_RADIUS_PX;\n return this.doubleDown;\n }\n\n /**\n * The finger moved. Returns true if it already left the slop (neither a tap nor a long press).\n * Палец сдвинулся. Возвращает true, если он уже ушёл дальше допуска (не тап и не долгое нажатие).\n */\n move(s: Sample): boolean {\n if (this.start && !this.moved && dist(s, this.start) > TAP_SLOP_PX) this.moved = true;\n return this.moved;\n }\n\n get isMoved(): boolean {\n return this.moved;\n }\n\n /**\n * Whether it is time to count the touch as a long press: the finger lies still longer than `LONG_PRESS_MS`.\n * Пора ли считать касание долгим нажатием: палец лежит на месте дольше `LONG_PRESS_MS`.\n */\n longPressDue(now: number): boolean {\n return this.start !== null && !this.moved && now - this.start.t >= LONG_PRESS_MS;\n }\n\n /**\n * The finger was lifted: what that was. After `double` the next tap counts as single again.\n * Палец поднят: что это было. После `double` следующий тап снова считается одиночным.\n */\n up(s: Sample): TapResult {\n const start = this.start;\n this.start = null;\n if (!start) return null;\n\n this.move(s);\n if (this.moved || s.t - start.t > TAP_MAX_MS) {\n this.lastTap = null;\n return null;\n }\n if (this.doubleDown) {\n this.lastTap = null;\n return 'double';\n }\n this.lastTap = s;\n return 'tap';\n }\n\n /**\n * The gesture turned out to be something else (a long press, a pinch, an interruption): forget both the current touch and the previous tap.\n * Жест оказался чем-то другим (долгое нажатие, щипок, прерывание): забываем и текущее касание, и предыдущий тап.\n */\n cancel(): void {\n this.start = null;\n this.lastTap = null;\n this.doubleDown = false;\n }\n}\n\n//--------------------------------------------------\n// Pinch and a two-finger gesture\n// Щипок и жест двумя пальцами\n\ntype Point = { x: number; y: number };\n\nexport interface Pinch {\n /**\n * The centre between the fingers.\n * Центр между пальцами.\n */\n cx: number;\n cy: number;\n /**\n * The distance between the fingers; 0 if there is one finger (then only a shift).\n * Расстояние между пальцами; 0, если палец один (тогда только сдвиг).\n */\n dist: number;\n}\n\nexport function pinchOf(a: Point, b?: Point): Pinch {\n if (!b) return { cx: a.x, cy: a.y, dist: 0 };\n return { cx: (a.x + b.x) / 2, cy: (a.y + b.y) / 2, dist: dist(a, b) };\n}\n\nexport interface PinchStep {\n /**\n * By how many times to change the scale.\n * Во сколько раз изменить масштаб.\n */\n factor: number;\n /**\n * Around which point (the centre before the step).\n * Вокруг какой точки (центр до шага).\n */\n pivot: [number, number];\n /**\n * By how much to shift the camera after the scale.\n * На сколько сдвинуть камеру после масштаба.\n */\n pan: [number, number];\n}\n\n/**\n * Until the distance between the fingers has changed by this much, the gesture counts as a plain shift: the scale is not touched.\n * Пока расстояние между пальцами не изменилось на столько, жест считается просто сдвигом: масштаб не трогаем.\n */\nexport const PINCH_ENGAGE_PX = 20;\n/**\n * Distance changes smaller than this count as finger jitter and are ignored.\n * Изменения расстояния мельче этого считаем дрожанием пальцев и игнорируем.\n */\nexport const PINCH_DEADBAND_PX = 1.5;\n/**\n * How many last steps we look at when deciding \"shifting or scaling\".\n * Сколько последних шагов смотрим, решая «сдвигают или масштабируют».\n */\nexport const PINCH_WINDOW = 6;\n/**\n * To turn the scale on, the distance over the window must change at least as much as the centre moves, and at least this much.\n * Для включения масштаба расстояние за окно должно меняться не меньше, чем сдвигается центр, и не меньше этого.\n */\nexport const PINCH_DOMINANCE = 1;\nexport const PINCH_MIN_NET_PX = 4;\n/**\n * The scale turns off again when the centre moves this many times further than the distance changes over the window (and at least `PINCH_RELEASE_MIN_PX`).\n * Масштаб выключается обратно, когда центр за окно уходит в столько раз дальше, чем меняется расстояние (и не меньше `PINCH_RELEASE_MIN_PX`).\n */\nexport const PINCH_RELEASE_RATIO = 2;\nexport const PINCH_RELEASE_MIN_PX = 12;\n\ninterface PinchDelta {\n dx: number;\n dy: number;\n dd: number;\n}\n\n/**\n * A two-finger gesture: shift and/or scale. The scale is the ratio of distances, and the distance between the fingers\n * drifts during an ordinary two-finger shift too, so it cannot be applied just like that.\n * Жест двумя пальцами: сдвиг и/или масштаб. Масштаб считается как отношение расстояний, а расстояние между\n * пальцами при обычном сдвиге двумя пальцами тоже «плывёт», поэтому его нельзя применять просто так.\n *\n * - The distance must change deliberately (`PINCH_ENGAGE_PX`), not build up by drift.\n * - Over the last `PINCH_WINDOW` steps the distance must change more than the centre moves:\n * while the fingers are carried together, the scale does not turn on however the distance floats. We look at the signed sum:\n * the browser sends finger movement one at a time, and \"one moved, the other caught up\" cancels out.\n * - Once the scale is on there is no jump (counting is from the current distance), and small jitter is cut by a\n * dead zone. If the fingers are then carried together, the scale turns off again.\n * - Расстояние должно измениться осознанно (`PINCH_ENGAGE_PX`), а не накопиться дрейфом.\n * - При этом за последние `PINCH_WINDOW` шагов расстояние должно меняться сильнее, чем сдвигается центр:\n * пока пальцы везут вместе, масштаб не включается, как бы расстояние ни плавало. Смотрим на сумму со знаком:\n * браузер присылает движение пальцев по одному, и «один сдвинулся, второй догнал» взаимно сокращается.\n * - Когда масштаб включился, скачка нет (отсчёт идёт от текущего расстояния), а мелкое дрожание отсекается\n * мёртвой зоной. Если потом пальцы повезли вместе, масштаб выключается обратно.\n *\n * The centre shift always works.\n * Сдвиг центра работает всегда.\n */\nexport class PinchTracker {\n private prev: Pinch = { cx: 0, cy: 0, dist: 0 };\n private startDist = 0;\n private baseDist = 0;\n private engaged = false;\n private recent: PinchDelta[] = [];\n\n /**\n * A new set of fingers (a gesture began or the number of fingers changed): count from scratch, there will be no jump.\n * Новый набор пальцев (жест начался или число пальцев изменилось): отсчёт заново, скачка не будет.\n */\n begin(p: Pinch): void {\n this.prev = p;\n this.startDist = p.dist;\n this.baseDist = p.dist;\n this.engaged = false;\n this.recent = [];\n }\n\n get isZooming(): boolean {\n return this.engaged;\n }\n\n update(next: Pinch): PinchStep {\n const step: PinchStep = {\n factor: 1,\n pivot: [this.prev.cx, this.prev.cy],\n pan: [next.cx - this.prev.cx, next.cy - this.prev.cy],\n };\n\n // With one finger (the distance is 0 either way) there is no scale.\n // С одним пальцем (расстояние 0 с любой стороны) масштаба нет.\n const twoFingers = this.startDist > 0 && next.dist > 0 && this.prev.dist > 0;\n this.recent.push({ dx: step.pan[0], dy: step.pan[1], dd: twoFingers ? next.dist - this.prev.dist : 0 });\n if (this.recent.length > PINCH_WINDOW) this.recent.shift();\n this.prev = next;\n if (!twoFingers) return step;\n\n let sx = 0;\n let sy = 0;\n let sd = 0;\n for (const d of this.recent) {\n sx += d.dx;\n sy += d.dy;\n sd += d.dd;\n }\n const netCenter = Math.hypot(sx, sy);\n const netDist = Math.abs(sd);\n\n if (!this.engaged) {\n const intentional = Math.abs(next.dist - this.startDist) >= PINCH_ENGAGE_PX;\n if (intentional && netDist >= PINCH_MIN_NET_PX && netDist >= PINCH_DOMINANCE * netCenter) {\n this.engaged = true;\n this.baseDist = next.dist; // counted from this moment: no jump / отсчёт с этого момента: без скачка\n }\n } else if (netCenter >= PINCH_RELEASE_MIN_PX && netCenter >= PINCH_RELEASE_RATIO * netDist) {\n // The fingers were carried together: the scale turns off, the new threshold is counted from the current distance.\n // Пальцы повезли вместе: масштаб выключаем, новый порог отсчитываем от нынешнего расстояния.\n this.engaged = false;\n this.startDist = next.dist;\n this.baseDist = next.dist;\n } else if (Math.abs(next.dist - this.baseDist) >= PINCH_DEADBAND_PX) {\n step.factor = next.dist / this.baseDist;\n this.baseDist = next.dist;\n }\n return step;\n }\n}\n\n//--------------------------------------------------\n// Swipe: a row that slides open to show its actions, a sheet pulled down\n// Свайп: строка, которая отъезжает и показывает действия, лист, который тянут вниз\n\n/**\n * How far the finger moves before the intent is decided: a swipe along the axis, or a scroll across it.\n * Сколько палец проходит, прежде чем решается намерение: свайп вдоль оси или прокрутка поперёк.\n */\nexport const SWIPE_SLOP_PX = 10;\n/**\n * A release faster than this (px/ms) is a fling: it goes on in its direction whatever the offset.\n * Отпускание быстрее этого (px/мс) — бросок: он продолжается в своём направлении при любом сдвиге.\n */\nexport const SWIPE_FLING_PX_PER_MS = 0.4;\n/**\n * The release speed is measured over this last stretch of the gesture, ms.\n * Скорость отпускания меряется на этом последнем отрезке жеста, мс.\n */\nexport const SWIPE_VELOCITY_WINDOW_MS = 100;\n\n/**\n * `pending` — not decided yet (inside the slop); `swipe` — along the axis, the app moves the row; `scroll` — across,\n * the gesture belongs to the page and the tracker ignores it until the next `down`.\n * `pending` — ещё не решено (в пределах допуска); `swipe` — вдоль оси, приложение двигает строку; `scroll` — поперёк,\n * жест принадлежит странице, и трекер его игнорирует до следующего `down`.\n */\nexport type SwipeIntent = 'pending' | 'swipe' | 'scroll';\n\nexport interface SwipeStep {\n intent: SwipeIntent;\n /**\n * Where the row stands now: the offset it had at `down` plus the travel since the swipe engaged (so it does not\n * jump by the slop).\n * Где строка сейчас: сдвиг на момент `down` плюс путь с момента, как свайп включился (поэтому без скачка на допуск).\n */\n offset: number;\n}\n\nexport interface SwipeRelease {\n offset: number;\n /** px/ms along the axis, + to the right / down. / px/мс вдоль оси, + вправо / вниз. */\n velocity: number;\n}\n\n/**\n * Tells a swipe from a scroll and follows it. Pure logic, as the other recognizers: the app feeds it pointer samples,\n * moves the element by `offset` and, on release, asks `settleOpen` where the element should come to rest.\n * Отличает свайп от прокрутки и ведёт его. Чистая логика, как остальные распознаватели: приложение подаёт отсчёты\n * указателя, двигает элемент на `offset`, а при отпускании спрашивает `settleOpen`, где элементу остановиться.\n */\nexport class SwipeTracker {\n private start: Sample | null = null;\n private from = 0;\n private engage: Sample | null = null;\n private intent: SwipeIntent = 'pending';\n private trail: Sample[] = [];\n\n constructor(\n private readonly axis: 'x' | 'y' = 'x',\n private readonly slop: number = SWIPE_SLOP_PX,\n ) {}\n\n private along(s: Sample): number {\n return this.axis === 'x' ? s.x : s.y;\n }\n\n private across(s: Sample): number {\n return this.axis === 'x' ? s.y : s.x;\n }\n\n /**\n * The finger landed. `from` is where the row already stands (0 closed, or its open offset).\n * Палец лёг. `from` — где строка уже стоит (0 — закрыта, или её открытый сдвиг).\n */\n down(s: Sample, from = 0): void {\n this.start = s;\n this.from = from;\n this.engage = null;\n this.intent = 'pending';\n this.trail = [s];\n }\n\n move(s: Sample): SwipeStep {\n const start = this.start;\n if (!start || this.intent === 'scroll') return { intent: this.intent, offset: this.from };\n\n if (this.intent === 'pending') {\n const da = Math.abs(this.along(s) - this.along(start));\n const dc = Math.abs(this.across(s) - this.across(start));\n if (Math.max(da, dc) <= this.slop) return { intent: 'pending', offset: this.from };\n // the axis wins only when it leads: a diagonal goes to the page / ось побеждает, только если ведёт: диагональ — странице\n this.intent = da > dc ? 'swipe' : 'scroll';\n if (this.intent === 'scroll') return { intent: 'scroll', offset: this.from };\n this.engage = s;\n }\n\n this.trail.push(s);\n while (this.trail.length > 2 && s.t - this.trail[0]!.t > SWIPE_VELOCITY_WINDOW_MS) this.trail.shift();\n return { intent: 'swipe', offset: this.from + this.along(s) - this.along(this.engage!) };\n }\n\n /**\n * The finger was lifted. Null unless it was a swipe.\n * Палец поднят. Null, если это был не свайп.\n */\n up(s: Sample): SwipeRelease | null {\n const step = this.move(s);\n const swiped = this.intent === 'swipe';\n const first = this.trail[0];\n this.start = null;\n if (!swiped || !first) return null;\n const dt = s.t - first.t;\n const velocity = dt > 0 ? (this.along(s) - this.along(first)) / dt : 0;\n return { offset: step.offset, velocity };\n }\n\n cancel(): void {\n this.start = null;\n this.intent = 'pending';\n this.trail = [];\n }\n\n get current(): SwipeIntent {\n return this.intent;\n }\n}\n\n/**\n * Where a released row comes to rest: closed (0), open at the start (`start`, > 0, actions on the left) or open at\n * the end (`-end`, actions on the right). A fling goes on in its direction, one stop at a time (an open row flung\n * back closes, it does not fly to the other side); otherwise the nearest stop wins.\n * Где отпущенная строка останавливается: закрыта (0), открыта в начале (`start`, > 0, действия слева) или в конце\n * (`-end`, действия справа). Бросок продолжается в своём направлении на одну остановку (открытая строка, брошенная\n * обратно, закрывается, а не улетает на другую сторону); иначе побеждает ближайшая остановка.\n */\nexport function settleOpen(\n release: SwipeRelease,\n open: { start?: number; end?: number },\n fling: number = SWIPE_FLING_PX_PER_MS,\n): number {\n const stops = [0];\n if (open.start) stops.push(open.start);\n if (open.end) stops.push(-open.end);\n stops.sort((a, b) => a - b);\n\n const { offset, velocity } = release;\n if (Math.abs(velocity) >= fling) {\n // the stop beyond the offset in the direction of the fling, or the last one / остановка за сдвигом по ходу броска\n const ahead = velocity > 0 ? stops.filter((p) => p > offset) : stops.filter((p) => p < offset).reverse();\n return ahead[0] ?? (velocity > 0 ? stops[stops.length - 1]! : stops[0]!);\n }\n return stops.reduce((best, p) => (Math.abs(p - offset) < Math.abs(best - offset) ? p : best), 0);\n}\n\n//--------------------------------------------------\n// Focus loss / Потеря фокуса окна\n\n/**\n * Calls `onLoss` when the window really loses the focus: Alt-Tab, a screenshot tool, the tab hidden or left. Those often\n * swallow the `pointerup` of a press that was held, and a drag would stay «pressed» after the user came back; end the\n * gesture there. Returns the function that stops listening. The same rule as TaoUI's carousel and slider.\n * Вызывает `onLoss`, когда окно действительно теряет фокус: Alt-Tab, программа скриншотов, вкладка скрыта или закрыта.\n * Они часто глотают `pointerup` удерживаемого нажатия, и перетаскивание осталось бы «нажатым», когда пользователь\n * вернётся; там жест и заканчивают. Возвращает функцию, которая прекращает слушать.\n */\nexport function listenFocusLoss(onLoss: () => void): () => void {\n if (typeof window === 'undefined') return () => {};\n const onVisibility = () => {\n if (document.hidden) onLoss();\n };\n document.addEventListener('visibilitychange', onVisibility);\n window.addEventListener('blur', onLoss);\n window.addEventListener('pagehide', onLoss);\n return () => {\n document.removeEventListener('visibilitychange', onVisibility);\n window.removeEventListener('blur', onLoss);\n window.removeEventListener('pagehide', onLoss);\n };\n}\n"],"mappings":";;;;;;;;;;;AAWA,IAAa,cAAc;;;;;AAK3B,IAAa,aAAa;;;;;AAK1B,IAAa,gBAAgB;;;;;AAK7B,IAAa,gBAAgB;AAC7B,IAAa,uBAAuB;AAYpC,IAAM,QAAQ,GAA6B,MAAgC,KAAK,MAAM,EAAE,IAAI,EAAE,GAAG,EAAE,IAAI,EAAE,CAAC;;;;;AAQ1G,IAAa,gBAAb,MAA2B;CACvB,QAA+B;CAC/B,QAAgB;CAChB,UAAiC;CACjC,aAAqB;;;;;;;CAQrB,KAAK,GAAoB;EACrB,KAAK,QAAQ;EACb,KAAK,QAAQ;EACb,MAAM,OAAO,KAAK;EAClB,KAAK,aAAa,SAAS,QAAQ,EAAE,IAAI,KAAK,KAAA,OAAsB,KAAK,GAAG,IAAI,KAAA;EAChF,OAAO,KAAK;CAChB;;;;;CAMA,KAAK,GAAoB;EACrB,IAAI,KAAK,SAAS,CAAC,KAAK,SAAS,KAAK,GAAG,KAAK,KAAK,IAAA,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MAAO,CAAC;AACnG;;;;;;;;;AAaA,SAAgB,gBAAgB,QAAgC;CAC5D,IAAI,OAAO,WAAW,aAAa,aAAa,CAAC;CACjD,MAAM,qBAAqB;EACvB,IAAI,SAAS,QAAQ,OAAO;CAChC;CACA,SAAS,iBAAiB,oBAAoB,YAAY;CAC1D,OAAO,iBAAiB,QAAQ,MAAM;CACtC,OAAO,iBAAiB,YAAY,MAAM;CAC1C,aAAa;EACT,SAAS,oBAAoB,oBAAoB,YAAY;EAC7D,OAAO,oBAAoB,QAAQ,MAAM;EACzC,OAAO,oBAAoB,YAAY,MAAM;CACjD;AACJ"}
@@ -0,0 +1,66 @@
1
+ import { type MaybeRefOrGetter, type Ref } from 'vue';
2
+ /**
3
+ * Reordering a list by dragging a handle, and by the keyboard. The list belongs to the app: the composable only says
4
+ * «move from → to», the app moves the item in its array, Vue redraws.
5
+ * The pointer: press the handle, the item lifts and follows, the others make room, the list scrolls at its edge,
6
+ * release drops it, Esc puts it back. The keyboard: Space or Enter on the handle lifts it, ↑ ↓ (← → on a row) move it
7
+ * one place at a time, Space / Enter drops it, Esc returns it where it started; a live region tells a screen reader.
8
+ * The markup is the app's: `data-sortable-item` on each item (in order) and `data-sortable-handle` on a focusable handle
9
+ * inside it (a button with `tao-grip`). While dragging the item has `data-sortable-dragging`, while lifted by the
10
+ * keyboard `data-sortable-lifted`: style them (a shadow, a lift).
11
+ *
12
+ * Перестановка списка перетаскиванием за ручку и с клавиатуры. Список принадлежит приложению: composable только
13
+ * говорит «откуда → куда», приложение переставляет элемент в своём массиве, Vue перерисовывает.
14
+ * Указатель: нажал на ручку — элемент поднимается и едет следом, остальные расступаются, у края список прокручивается,
15
+ * отпустил — встал, Esc — вернулся. Клавиатура: Пробел или Enter на ручке поднимает, ↑ ↓ (← → в строке) двигают на
16
+ * одно место, Пробел / Enter ставят, Esc возвращает туда, откуда начали; живой регион сообщает скринридеру.
17
+ * Разметка приложения: `data-sortable-item` на каждом элементе (по порядку) и `data-sortable-handle` на фокусируемой
18
+ * ручке внутри (кнопка с `tao-grip`). Во время перетаскивания у элемента `data-sortable-dragging`, при подъёме с
19
+ * клавиатуры `data-sortable-lifted`: оформите их (тень, подъём).
20
+ */
21
+ export type SortableAxis = 'y' | 'x';
22
+ /**
23
+ * Where an item dragged from `from` lands: before the first other item whose middle is past the pointer. `starts` and
24
+ * `sizes` are the items' positions and sizes along the axis, in the order of the list, measured before the drag.
25
+ * Куда встаёт элемент, который тащат из `from`: перед первым другим элементом, чья середина дальше указателя.
26
+ */
27
+ export declare function sortTarget(pointer: number, starts: readonly number[], sizes: readonly number[], from: number): number;
28
+ /**
29
+ * How far each other item shifts to make room: the items between `from` and `to` move by the dragged item's size and
30
+ * the gap, the rest stay.
31
+ * На сколько сдвигается каждый другой элемент, чтобы освободить место.
32
+ */
33
+ export declare function sortShifts(count: number, from: number, to: number, size: number): number[];
34
+ /** A copy of the list with the item moved. / Копия списка с переставленным элементом. */
35
+ export declare function moveItem<T>(list: readonly T[], from: number, to: number): T[];
36
+ /** The texts for a screen reader; `{item}` is the item's text, `{position}` / `{count}` its place. */
37
+ export interface SortableTexts {
38
+ lifted: string;
39
+ moved: string;
40
+ dropped: string;
41
+ canceled: string;
42
+ }
43
+ export declare const sortableTextsEn: SortableTexts;
44
+ export declare const sortableTextsRu: SortableTexts;
45
+ export interface SortableOptions {
46
+ /**
47
+ * The item moved: put it at `to` in your array (`list.value = moveItem(list.value, from, to)`).
48
+ * Элемент переставлен: поставьте его на место `to` в своём массиве.
49
+ */
50
+ onMove(from: number, to: number): void;
51
+ axis?: SortableAxis;
52
+ /** Off while true (a filtered list, a read-only view). / Выключено, пока true. */
53
+ disabled?: MaybeRefOrGetter<boolean>;
54
+ /** The texts for a screen reader; a function is read each time, so it follows the language. / Тексты для скринридера. */
55
+ texts?: SortableTexts | (() => SortableTexts);
56
+ /** The text of an item for those messages; its text content by default. / Текст элемента для сообщений. */
57
+ itemLabel?(element: HTMLElement, index: number): string;
58
+ }
59
+ export declare function useSortable(container: Ref<HTMLElement | null>, options: SortableOptions): {
60
+ /** The index being dragged by the pointer, or null. / Индекс, который тащат указателем, или null. */
61
+ dragging: Ref<number | null, number | null>;
62
+ /** The index lifted by the keyboard, or null. / Индекс, поднятый с клавиатуры, или null. */
63
+ lifted: Ref<number | null, number | null>;
64
+ /** Stops a pointer drag without moving. / Прерывает перетаскивание без переноса. */
65
+ cancel: () => void;
66
+ };