@1337exp/taoux 0.5.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,16 @@
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
+
3
14
  ## 0.5.0
4
15
 
5
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.
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,7 +90,7 @@ 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 |
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,7 +90,7 @@ 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 внутри одного документа | нет |
@@ -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,IAAI,MAAM,IAAA,KAAgB;GAC1C,KAAK,UAAU;GACf,OAAO;EACX;EACA,IAAI,KAAK,YAAY;GACjB,KAAK,UAAU;GACf,OAAO;EACX;EACA,KAAK,UAAU;EACf,OAAO;CACX;;;;;C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AAQ,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,GAAiB,KAAK,QAAQ;EACjF,OAAO,KAAK;CAChB;CAEA,IAAI,UAAmB;EACnB,OAAO,KAAK;CAChB;;;;;CAMA,aAAa,KAAsB;EAC/B,OAAO,KAAK,UAAU,QAAQ,CAAC,KAA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ChC;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"}
package/dist/sortable.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { createEdgeScroller } from "./edgescroll.js";
2
+ import { listenFocusLoss } from "./gestures.js";
2
3
  import { onBeforeUnmount, onMounted, ref, toValue } from "vue";
3
4
  //#region src/sortable.ts
4
5
  /**
@@ -74,6 +75,7 @@ function useSortable(container, options) {
74
75
  const sizeOf = (r) => axis === "y" ? r.height : r.width;
75
76
  const pointerOf = (e) => axis === "y" ? e.clientY : e.clientX;
76
77
  let drag = null;
78
+ let stopFocusLoss;
77
79
  const scrollPos = (s) => s ? axis === "y" ? s.scrollTop : s.scrollLeft : axis === "y" ? window.scrollY : window.scrollX;
78
80
  const edge = createEdgeScroller({
79
81
  bounds: () => {
@@ -156,6 +158,7 @@ function useSortable(container, options) {
156
158
  document.addEventListener("pointermove", onPointerMove);
157
159
  document.addEventListener("pointerup", onPointerUp);
158
160
  document.addEventListener("pointercancel", onPointerCancel);
161
+ stopFocusLoss = listenFocusLoss(() => finish(false));
159
162
  document.addEventListener("keydown", onDragKey, true);
160
163
  }
161
164
  function onPointerMove(event) {
@@ -175,6 +178,8 @@ function useSortable(container, options) {
175
178
  document.removeEventListener("pointermove", onPointerMove);
176
179
  document.removeEventListener("pointerup", onPointerUp);
177
180
  document.removeEventListener("pointercancel", onPointerCancel);
181
+ stopFocusLoss?.();
182
+ stopFocusLoss = void 0;
178
183
  document.removeEventListener("keydown", onDragKey, true);
179
184
  for (const el of els) {
180
185
  el.style.transform = "";
@@ -1 +1 @@
1
- {"version":3,"file":"sortable.js","names":[],"sources":["../src/sortable.ts"],"sourcesContent":["import { onBeforeUnmount, onMounted, ref, toValue, type MaybeRefOrGetter, type Ref } from 'vue';\nimport { createEdgeScroller } from './edgescroll';\n\n/**\n * Reordering a list by dragging a handle, and by the keyboard. The list belongs to the app: the composable only says\n * «move from → to», the app moves the item in its array, Vue redraws.\n * The pointer: press the handle, the item lifts and follows, the others make room, the list scrolls at its edge,\n * release drops it, Esc puts it back. The keyboard: Space or Enter on the handle lifts it, ↑ ↓ (← → on a row) move it\n * one place at a time, Space / Enter drops it, Esc returns it where it started; a live region tells a screen reader.\n * The markup is the app's: `data-sortable-item` on each item (in order) and `data-sortable-handle` on a focusable handle\n * inside it (a button with `tao-grip`). While dragging the item has `data-sortable-dragging`, while lifted by the\n * keyboard `data-sortable-lifted`: style them (a shadow, a lift).\n *\n * Перестановка списка перетаскиванием за ручку и с клавиатуры. Список принадлежит приложению: composable только\n * говорит «откуда → куда», приложение переставляет элемент в своём массиве, Vue перерисовывает.\n * Указатель: нажал на ручку — элемент поднимается и едет следом, остальные расступаются, у края список прокручивается,\n * отпустил — встал, Esc — вернулся. Клавиатура: Пробел или Enter на ручке поднимает, ↑ ↓ (← → в строке) двигают на\n * одно место, Пробел / Enter ставят, Esc возвращает туда, откуда начали; живой регион сообщает скринридеру.\n * Разметка приложения: `data-sortable-item` на каждом элементе (по порядку) и `data-sortable-handle` на фокусируемой\n * ручке внутри (кнопка с `tao-grip`). Во время перетаскивания у элемента `data-sortable-dragging`, при подъёме с\n * клавиатуры `data-sortable-lifted`: оформите их (тень, подъём).\n */\n\nexport type SortableAxis = 'y' | 'x';\n\n/**\n * Where an item dragged from `from` lands: before the first other item whose middle is past the pointer. `starts` and\n * `sizes` are the items' positions and sizes along the axis, in the order of the list, measured before the drag.\n * Куда встаёт элемент, который тащат из `from`: перед первым другим элементом, чья середина дальше указателя.\n */\nexport function sortTarget(pointer: number, starts: readonly number[], sizes: readonly number[], from: number): number {\n let target = 0;\n for (let i = 0; i < starts.length; i++) {\n if (i === from) continue;\n if (pointer > starts[i]! + sizes[i]! / 2) target++;\n }\n return target;\n}\n\n/**\n * How far each other item shifts to make room: the items between `from` and `to` move by the dragged item's size and\n * the gap, the rest stay.\n * На сколько сдвигается каждый другой элемент, чтобы освободить место.\n */\nexport function sortShifts(count: number, from: number, to: number, size: number): number[] {\n return Array.from({ length: count }, (_, i) => {\n if (i === from) return 0;\n if (from < to && i > from && i <= to) return -size;\n if (to < from && i >= to && i < from) return size;\n return 0;\n });\n}\n\n/** A copy of the list with the item moved. / Копия списка с переставленным элементом. */\nexport function moveItem<T>(list: readonly T[], from: number, to: number): T[] {\n const next = list.slice();\n if (from < 0 || from >= next.length) return next;\n const [item] = next.splice(from, 1);\n next.splice(Math.max(0, Math.min(to, next.length)), 0, item!);\n return next;\n}\n\n/** The texts for a screen reader; `{item}` is the item's text, `{position}` / `{count}` its place. */\nexport interface SortableTexts {\n lifted: string;\n moved: string;\n dropped: string;\n canceled: string;\n}\n\nexport const sortableTextsEn: SortableTexts = {\n lifted: 'Picked up {item}, position {position} of {count}. Use the arrow keys to move, Space to drop, Escape to cancel.',\n moved: '{item}, position {position} of {count}.',\n dropped: '{item} dropped at position {position} of {count}.',\n canceled: 'Move canceled. {item} is back at position {position} of {count}.',\n};\n\nexport const sortableTextsRu: SortableTexts = {\n lifted: '{item} поднят, место {position} из {count}. Стрелки двигают, Пробел ставит, Escape отменяет.',\n moved: '{item}, место {position} из {count}.',\n dropped: '{item} поставлен на место {position} из {count}.',\n canceled: 'Перенос отменён. {item} снова на месте {position} из {count}.',\n};\n\nexport interface SortableOptions {\n /**\n * The item moved: put it at `to` in your array (`list.value = moveItem(list.value, from, to)`).\n * Элемент переставлен: поставьте его на место `to` в своём массиве.\n */\n onMove(from: number, to: number): void;\n axis?: SortableAxis;\n /** Off while true (a filtered list, a read-only view). / Выключено, пока true. */\n disabled?: MaybeRefOrGetter<boolean>;\n /** The texts for a screen reader; a function is read each time, so it follows the language. / Тексты для скринридера. */\n texts?: SortableTexts | (() => SortableTexts);\n /** The text of an item for those messages; its text content by default. / Текст элемента для сообщений. */\n itemLabel?(element: HTMLElement, index: number): string;\n}\n\nconst ITEM = '[data-sortable-item]';\nconst HANDLE = '[data-sortable-handle]';\n\nfunction scrollParent(el: HTMLElement, axis: SortableAxis): HTMLElement | null {\n for (let p: HTMLElement | null = el; p; p = p.parentElement) {\n const style = getComputedStyle(p);\n const overflow = axis === 'y' ? style.overflowY : style.overflowX;\n if (/(auto|scroll)/.test(overflow) && (axis === 'y' ? p.scrollHeight > p.clientHeight : p.scrollWidth > p.clientWidth)) return p;\n }\n return null;\n}\n\nexport function useSortable(container: Ref<HTMLElement | null>, options: SortableOptions) {\n const axis = options.axis ?? 'y';\n const dragging = ref<number | null>(null);\n const lifted = ref<number | null>(null);\n const texts = () => (typeof options.texts === 'function' ? options.texts() : options.texts) ?? sortableTextsEn;\n\n // a live region of our own, so a screen reader hears where the item is / свой живой регион для скринридера\n let live: HTMLElement | null = null;\n function announce(template: string, index: number) {\n if (!live) return;\n const els = items();\n const label = els[index] ? (options.itemLabel?.(els[index]!, index) ?? els[index]!.textContent?.trim() ?? '') : '';\n live.textContent = template\n .replace('{item}', label)\n .replace('{position}', String(index + 1))\n .replace('{count}', String(els.length));\n }\n\n const items = () => (container.value ? Array.from(container.value.querySelectorAll<HTMLElement>(ITEM)) : []);\n const along = (r: DOMRect) => (axis === 'y' ? r.top : r.left);\n const sizeOf = (r: DOMRect) => (axis === 'y' ? r.height : r.width);\n const pointerOf = (e: PointerEvent) => (axis === 'y' ? e.clientY : e.clientX);\n\n //---]>\n // the pointer / указатель\n\n let drag: {\n from: number;\n to: number;\n start: number;\n scroll0: number;\n starts: number[];\n sizes: number[];\n step: number;\n els: HTMLElement[];\n handle: HTMLElement;\n pointerId: number;\n last: [number, number];\n scroller: HTMLElement | null;\n } | null = null;\n\n const scrollPos = (s: HTMLElement | null) => (s ? (axis === 'y' ? s.scrollTop : s.scrollLeft) : axis === 'y' ? window.scrollY : window.scrollX);\n\n const edge = createEdgeScroller({\n bounds: () => {\n if (!drag) return null;\n if (drag.scroller) return drag.scroller.getBoundingClientRect();\n return { left: 0, top: 0, width: window.innerWidth, height: window.innerHeight };\n },\n pointer: () => drag?.last ?? [0, 0],\n enabled: () => drag !== null,\n onScroll: (dx, dy) => {\n if (!drag) return;\n const d = axis === 'y' ? dy : dx;\n if (drag.scroller) {\n if (axis === 'y') drag.scroller.scrollTop += d;\n else drag.scroller.scrollLeft += d;\n } else {\n window.scrollBy(axis === 'y' ? 0 : d, axis === 'y' ? d : 0);\n }\n follow();\n },\n });\n\n function follow() {\n if (!drag) return;\n const pointer = (axis === 'y' ? drag.last[1] : drag.last[0]) + scrollPos(drag.scroller) - drag.scroll0;\n // the item stays within the list: past its ends it would make the scrolled area longer, the edge scroll would\n // follow it, and the two would run away together\n // элемент не выходит за пределы списка: за краями он удлинял бы прокручиваемую область, прокрутка у края шла бы\n // за ним, и они убегали бы вместе\n const { starts, sizes, from } = drag;\n const last = starts.length - 1;\n const min = starts[0]! - starts[from]!;\n const max = starts[last]! + sizes[last]! - (starts[from]! + sizes[from]!);\n // the place follows the pointer itself, only what is drawn is held in: past the end it is the last place\n // место следует за самим указателем, ограничено только то, что нарисовано: за краем — последнее место\n const raw = pointer - drag.start;\n const offset = Math.min(max, Math.max(min, raw));\n const to = sortTarget(starts[from]! + sizes[from]! / 2 + raw, starts, sizes, from);\n drag.to = to;\n const shifts = sortShifts(drag.els.length, drag.from, to, drag.step);\n drag.els.forEach((el, i) => {\n const value = i === drag!.from ? offset : shifts[i]!;\n el.style.transform = value ? (axis === 'y' ? `translateY(${value}px)` : `translateX(${value}px)`) : '';\n });\n }\n\n function onPointerDown(event: PointerEvent) {\n if (toValue(options.disabled) || event.button !== 0 || lifted.value !== null) return;\n const handle = (event.target as HTMLElement).closest<HTMLElement>(HANDLE);\n if (!handle || !container.value?.contains(handle)) return;\n const els = items();\n const from = els.findIndex((el) => el.contains(handle));\n if (from < 0) return;\n event.preventDefault();\n\n const rects = els.map((el) => el.getBoundingClientRect());\n const scroller = scrollParent(container.value, axis);\n // the others make room by the dragged item's size and the gap between items\n // остальные расступаются на размер перетаскиваемого элемента и зазор между элементами\n const gap = els.length > 1 ? Math.max(0, along(rects[1]!) - along(rects[0]!) - sizeOf(rects[0]!)) : 0;\n const step = sizeOf(rects[from]!) + gap;\n drag = {\n from,\n to: from,\n start: pointerOf(event),\n scroll0: scrollPos(scroller),\n starts: rects.map(along),\n sizes: rects.map(sizeOf),\n step,\n els,\n handle,\n pointerId: event.pointerId,\n last: [event.clientX, event.clientY],\n scroller,\n };\n try {\n // the moves come to the handle even off the list; optional, the document listens anyway\n // движения приходят на ручку и вне списка; не обязательно, документ всё равно слушает\n handle.setPointerCapture?.(event.pointerId);\n } catch {\n /* a pointer the browser does not know (a synthetic event) / указатель, неизвестный браузеру */\n }\n els.forEach((el, i) => {\n el.style.transition = i === from ? 'none' : 'transform 150ms ease';\n if (i === from) {\n el.style.position = 'relative';\n el.style.zIndex = '1';\n el.setAttribute('data-sortable-dragging', '');\n }\n });\n dragging.value = from;\n document.addEventListener('pointermove', onPointerMove);\n document.addEventListener('pointerup', onPointerUp);\n document.addEventListener('pointercancel', onPointerCancel);\n document.addEventListener('keydown', onDragKey, true);\n }\n\n function onPointerMove(event: PointerEvent) {\n if (!drag || event.pointerId !== drag.pointerId) return;\n drag.last = [event.clientX, event.clientY];\n follow();\n edge.kick();\n }\n\n function finish(commit: boolean) {\n if (!drag) return;\n const { from, to, els, handle, pointerId } = drag;\n drag = null;\n edge.stop();\n try {\n handle.releasePointerCapture?.(pointerId);\n } catch {\n /* already released / уже отпущен */\n }\n document.removeEventListener('pointermove', onPointerMove);\n document.removeEventListener('pointerup', onPointerUp);\n document.removeEventListener('pointercancel', onPointerCancel);\n document.removeEventListener('keydown', onDragKey, true);\n for (const el of els) {\n el.style.transform = '';\n el.style.transition = '';\n el.style.position = '';\n el.style.zIndex = '';\n el.removeAttribute('data-sortable-dragging');\n }\n dragging.value = null;\n if (commit && to !== from) options.onMove(from, to);\n }\n\n const onPointerUp = (event: PointerEvent) => {\n if (drag && event.pointerId === drag.pointerId) finish(true);\n };\n const onPointerCancel = () => finish(false);\n function onDragKey(event: KeyboardEvent) {\n if (event.key === 'Escape') {\n event.preventDefault();\n event.stopPropagation();\n finish(false);\n }\n }\n\n //---]>\n // the keyboard / клавиатура\n\n let liftedFrom = 0;\n\n function focusHandle(index: number) {\n // after the app moved the item and Vue redrew the list / после того как приложение переставило элемент\n requestAnimationFrame(() => items()[index]?.querySelector<HTMLElement>(HANDLE)?.focus());\n }\n\n function setLifted(index: number | null) {\n items().forEach((el, i) => {\n if (i === index) el.setAttribute('data-sortable-lifted', '');\n else el.removeAttribute('data-sortable-lifted');\n });\n lifted.value = index;\n }\n\n function onKeydown(event: KeyboardEvent) {\n if (toValue(options.disabled) || drag) return;\n const handle = (event.target as HTMLElement).closest<HTMLElement>(HANDLE);\n if (!handle || !container.value?.contains(handle)) return;\n const els = items();\n const index = els.findIndex((el) => el.contains(handle));\n if (index < 0) return;\n\n const pick = event.key === ' ' || event.key === 'Enter';\n if (lifted.value === null) {\n if (!pick) return;\n event.preventDefault();\n liftedFrom = index;\n setLifted(index);\n announce(texts().lifted, index);\n return;\n }\n\n const back = axis === 'y' ? 'ArrowUp' : 'ArrowLeft';\n const forward = axis === 'y' ? 'ArrowDown' : 'ArrowRight';\n if (event.key === back || event.key === forward) {\n event.preventDefault();\n const to = index + (event.key === forward ? 1 : -1);\n if (to < 0 || to >= els.length) return;\n options.onMove(index, to);\n requestAnimationFrame(() => {\n setLifted(to);\n announce(texts().moved, to);\n });\n focusHandle(to);\n } else if (pick) {\n event.preventDefault();\n setLifted(null);\n announce(texts().dropped, index);\n } else if (event.key === 'Escape') {\n event.preventDefault();\n event.stopPropagation();\n if (index !== liftedFrom) {\n options.onMove(index, liftedFrom);\n focusHandle(liftedFrom);\n }\n setLifted(null);\n requestAnimationFrame(() => announce(texts().canceled, liftedFrom));\n } else if (event.key === 'Tab') {\n // leaving the handle drops the item where it is / уход с ручки ставит элемент на месте\n setLifted(null);\n }\n }\n\n function onFocusOut(event: FocusEvent) {\n if (lifted.value === null) return;\n const next = event.relatedTarget as HTMLElement | null;\n // focus moving to the same item's handle after a move is not a leave / переход фокуса на ручку после переноса\n if (next?.closest(HANDLE) && container.value?.contains(next)) return;\n if (next) setLifted(null);\n }\n\n onMounted(() => {\n const el = container.value;\n if (!el) return;\n el.addEventListener('pointerdown', onPointerDown);\n el.addEventListener('keydown', onKeydown);\n el.addEventListener('focusout', onFocusOut);\n live = document.createElement('div');\n live.setAttribute('aria-live', 'assertive');\n live.setAttribute('aria-atomic', 'true');\n live.style.cssText = 'position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap';\n document.body.appendChild(live);\n });\n\n onBeforeUnmount(() => {\n finish(false);\n const el = container.value;\n el?.removeEventListener('pointerdown', onPointerDown);\n el?.removeEventListener('keydown', onKeydown);\n el?.removeEventListener('focusout', onFocusOut);\n live?.remove();\n live = null;\n });\n\n return {\n /** The index being dragged by the pointer, or null. / Индекс, который тащат указателем, или null. */\n dragging,\n /** The index lifted by the keyboard, or null. / Индекс, поднятый с клавиатуры, или null. */\n lifted,\n /** Stops a pointer drag without moving. / Прерывает перетаскивание без переноса. */\n cancel: () => finish(false),\n };\n}\n"],"mappings":";;;;;;;;AA8BA,SAAgB,WAAW,SAAiB,QAA2B,OAA0B,MAAsB;CACnH,IAAI,SAAS;CACb,KAAK,IAAI,IAAI,GAAG,IAAI,OAAO,QAAQ,KAAK;EACpC,IAAI,MAAM,MAAM;EAChB,IAAI,UAAU,OAAO,KAAM,MAAM,KAAM,GAAG;CAC9C;CACA,OAAO;AACX;;;;;;AAOA,SAAgB,WAAW,OAAe,MAAc,IAAY,MAAwB;CACxF,OAAO,MAAM,KAAK,EAAE,QAAQ,MAAM,IAAI,GAAG,MAAM;EAC3C,IAAI,MAAM,MAAM,OAAO;EACvB,IAAI,OAAO,MAAM,IAAI,QAAQ,KAAK,IAAI,OAAO,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;EAClB,OAAO,KAAK;EACZ,MAAM,KAAK,UAAU;EACrB,IAAI,oBAAoB,eAAe,aAAa;EACpD,IAAI,oBAAoB,WAAW,SAAS;EAC5C,IAAI,oBAAoB,YAAY,UAAU;EAC9C,MAAM,OAAO;EACb,OAAO;CACX,CAAC;CAED,OAAO;;EAEH;;EAEA;;EAEA,cAAc,OAAO,KAAK;CAC9B;AACJ"}
1
+ {"version":3,"file":"sortable.js","names":[],"sources":["../src/sortable.ts"],"sourcesContent":["import { onBeforeUnmount, onMounted, ref, toValue, type MaybeRefOrGetter, type Ref } from 'vue';\nimport { createEdgeScroller } from './edgescroll';\nimport { listenFocusLoss } from './gestures';\n\n/**\n * Reordering a list by dragging a handle, and by the keyboard. The list belongs to the app: the composable only says\n * «move from → to», the app moves the item in its array, Vue redraws.\n * The pointer: press the handle, the item lifts and follows, the others make room, the list scrolls at its edge,\n * release drops it, Esc puts it back. The keyboard: Space or Enter on the handle lifts it, ↑ ↓ (← → on a row) move it\n * one place at a time, Space / Enter drops it, Esc returns it where it started; a live region tells a screen reader.\n * The markup is the app's: `data-sortable-item` on each item (in order) and `data-sortable-handle` on a focusable handle\n * inside it (a button with `tao-grip`). While dragging the item has `data-sortable-dragging`, while lifted by the\n * keyboard `data-sortable-lifted`: style them (a shadow, a lift).\n *\n * Перестановка списка перетаскиванием за ручку и с клавиатуры. Список принадлежит приложению: composable только\n * говорит «откуда → куда», приложение переставляет элемент в своём массиве, Vue перерисовывает.\n * Указатель: нажал на ручку — элемент поднимается и едет следом, остальные расступаются, у края список прокручивается,\n * отпустил — встал, Esc — вернулся. Клавиатура: Пробел или Enter на ручке поднимает, ↑ ↓ (← → в строке) двигают на\n * одно место, Пробел / Enter ставят, Esc возвращает туда, откуда начали; живой регион сообщает скринридеру.\n * Разметка приложения: `data-sortable-item` на каждом элементе (по порядку) и `data-sortable-handle` на фокусируемой\n * ручке внутри (кнопка с `tao-grip`). Во время перетаскивания у элемента `data-sortable-dragging`, при подъёме с\n * клавиатуры `data-sortable-lifted`: оформите их (тень, подъём).\n */\n\nexport type SortableAxis = 'y' | 'x';\n\n/**\n * Where an item dragged from `from` lands: before the first other item whose middle is past the pointer. `starts` and\n * `sizes` are the items' positions and sizes along the axis, in the order of the list, measured before the drag.\n * Куда встаёт элемент, который тащат из `from`: перед первым другим элементом, чья середина дальше указателя.\n */\nexport function sortTarget(pointer: number, starts: readonly number[], sizes: readonly number[], from: number): number {\n let target = 0;\n for (let i = 0; i < starts.length; i++) {\n if (i === from) continue;\n if (pointer > starts[i]! + sizes[i]! / 2) target++;\n }\n return target;\n}\n\n/**\n * How far each other item shifts to make room: the items between `from` and `to` move by the dragged item's size and\n * the gap, the rest stay.\n * На сколько сдвигается каждый другой элемент, чтобы освободить место.\n */\nexport function sortShifts(count: number, from: number, to: number, size: number): number[] {\n return Array.from({ length: count }, (_, i) => {\n if (i === from) return 0;\n if (from < to && i > from && i <= to) return -size;\n if (to < from && i >= to && i < from) return size;\n return 0;\n });\n}\n\n/** A copy of the list with the item moved. / Копия списка с переставленным элементом. */\nexport function moveItem<T>(list: readonly T[], from: number, to: number): T[] {\n const next = list.slice();\n if (from < 0 || from >= next.length) return next;\n const [item] = next.splice(from, 1);\n next.splice(Math.max(0, Math.min(to, next.length)), 0, item!);\n return next;\n}\n\n/** The texts for a screen reader; `{item}` is the item's text, `{position}` / `{count}` its place. */\nexport interface SortableTexts {\n lifted: string;\n moved: string;\n dropped: string;\n canceled: string;\n}\n\nexport const sortableTextsEn: SortableTexts = {\n lifted: 'Picked up {item}, position {position} of {count}. Use the arrow keys to move, Space to drop, Escape to cancel.',\n moved: '{item}, position {position} of {count}.',\n dropped: '{item} dropped at position {position} of {count}.',\n canceled: 'Move canceled. {item} is back at position {position} of {count}.',\n};\n\nexport const sortableTextsRu: SortableTexts = {\n lifted: '{item} поднят, место {position} из {count}. Стрелки двигают, Пробел ставит, Escape отменяет.',\n moved: '{item}, место {position} из {count}.',\n dropped: '{item} поставлен на место {position} из {count}.',\n canceled: 'Перенос отменён. {item} снова на месте {position} из {count}.',\n};\n\nexport interface SortableOptions {\n /**\n * The item moved: put it at `to` in your array (`list.value = moveItem(list.value, from, to)`).\n * Элемент переставлен: поставьте его на место `to` в своём массиве.\n */\n onMove(from: number, to: number): void;\n axis?: SortableAxis;\n /** Off while true (a filtered list, a read-only view). / Выключено, пока true. */\n disabled?: MaybeRefOrGetter<boolean>;\n /** The texts for a screen reader; a function is read each time, so it follows the language. / Тексты для скринридера. */\n texts?: SortableTexts | (() => SortableTexts);\n /** The text of an item for those messages; its text content by default. / Текст элемента для сообщений. */\n itemLabel?(element: HTMLElement, index: number): string;\n}\n\nconst ITEM = '[data-sortable-item]';\nconst HANDLE = '[data-sortable-handle]';\n\nfunction scrollParent(el: HTMLElement, axis: SortableAxis): HTMLElement | null {\n for (let p: HTMLElement | null = el; p; p = p.parentElement) {\n const style = getComputedStyle(p);\n const overflow = axis === 'y' ? style.overflowY : style.overflowX;\n if (/(auto|scroll)/.test(overflow) && (axis === 'y' ? p.scrollHeight > p.clientHeight : p.scrollWidth > p.clientWidth)) return p;\n }\n return null;\n}\n\nexport function useSortable(container: Ref<HTMLElement | null>, options: SortableOptions) {\n const axis = options.axis ?? 'y';\n const dragging = ref<number | null>(null);\n const lifted = ref<number | null>(null);\n const texts = () => (typeof options.texts === 'function' ? options.texts() : options.texts) ?? sortableTextsEn;\n\n // a live region of our own, so a screen reader hears where the item is / свой живой регион для скринридера\n let live: HTMLElement | null = null;\n function announce(template: string, index: number) {\n if (!live) return;\n const els = items();\n const label = els[index] ? (options.itemLabel?.(els[index]!, index) ?? els[index]!.textContent?.trim() ?? '') : '';\n live.textContent = template\n .replace('{item}', label)\n .replace('{position}', String(index + 1))\n .replace('{count}', String(els.length));\n }\n\n const items = () => (container.value ? Array.from(container.value.querySelectorAll<HTMLElement>(ITEM)) : []);\n const along = (r: DOMRect) => (axis === 'y' ? r.top : r.left);\n const sizeOf = (r: DOMRect) => (axis === 'y' ? r.height : r.width);\n const pointerOf = (e: PointerEvent) => (axis === 'y' ? e.clientY : e.clientX);\n\n //---]>\n // the pointer / указатель\n\n let drag: {\n from: number;\n to: number;\n start: number;\n scroll0: number;\n starts: number[];\n sizes: number[];\n step: number;\n els: HTMLElement[];\n handle: HTMLElement;\n pointerId: number;\n last: [number, number];\n scroller: HTMLElement | null;\n } | null = null;\n\n let stopFocusLoss: (() => void) | undefined;\n\n const scrollPos = (s: HTMLElement | null) => (s ? (axis === 'y' ? s.scrollTop : s.scrollLeft) : axis === 'y' ? window.scrollY : window.scrollX);\n\n const edge = createEdgeScroller({\n bounds: () => {\n if (!drag) return null;\n if (drag.scroller) return drag.scroller.getBoundingClientRect();\n return { left: 0, top: 0, width: window.innerWidth, height: window.innerHeight };\n },\n pointer: () => drag?.last ?? [0, 0],\n enabled: () => drag !== null,\n onScroll: (dx, dy) => {\n if (!drag) return;\n const d = axis === 'y' ? dy : dx;\n if (drag.scroller) {\n if (axis === 'y') drag.scroller.scrollTop += d;\n else drag.scroller.scrollLeft += d;\n } else {\n window.scrollBy(axis === 'y' ? 0 : d, axis === 'y' ? d : 0);\n }\n follow();\n },\n });\n\n function follow() {\n if (!drag) return;\n const pointer = (axis === 'y' ? drag.last[1] : drag.last[0]) + scrollPos(drag.scroller) - drag.scroll0;\n // the item stays within the list: past its ends it would make the scrolled area longer, the edge scroll would\n // follow it, and the two would run away together\n // элемент не выходит за пределы списка: за краями он удлинял бы прокручиваемую область, прокрутка у края шла бы\n // за ним, и они убегали бы вместе\n const { starts, sizes, from } = drag;\n const last = starts.length - 1;\n const min = starts[0]! - starts[from]!;\n const max = starts[last]! + sizes[last]! - (starts[from]! + sizes[from]!);\n // the place follows the pointer itself, only what is drawn is held in: past the end it is the last place\n // место следует за самим указателем, ограничено только то, что нарисовано: за краем — последнее место\n const raw = pointer - drag.start;\n const offset = Math.min(max, Math.max(min, raw));\n const to = sortTarget(starts[from]! + sizes[from]! / 2 + raw, starts, sizes, from);\n drag.to = to;\n const shifts = sortShifts(drag.els.length, drag.from, to, drag.step);\n drag.els.forEach((el, i) => {\n const value = i === drag!.from ? offset : shifts[i]!;\n el.style.transform = value ? (axis === 'y' ? `translateY(${value}px)` : `translateX(${value}px)`) : '';\n });\n }\n\n function onPointerDown(event: PointerEvent) {\n if (toValue(options.disabled) || event.button !== 0 || lifted.value !== null) return;\n const handle = (event.target as HTMLElement).closest<HTMLElement>(HANDLE);\n if (!handle || !container.value?.contains(handle)) return;\n const els = items();\n const from = els.findIndex((el) => el.contains(handle));\n if (from < 0) return;\n event.preventDefault();\n\n const rects = els.map((el) => el.getBoundingClientRect());\n const scroller = scrollParent(container.value, axis);\n // the others make room by the dragged item's size and the gap between items\n // остальные расступаются на размер перетаскиваемого элемента и зазор между элементами\n const gap = els.length > 1 ? Math.max(0, along(rects[1]!) - along(rects[0]!) - sizeOf(rects[0]!)) : 0;\n const step = sizeOf(rects[from]!) + gap;\n drag = {\n from,\n to: from,\n start: pointerOf(event),\n scroll0: scrollPos(scroller),\n starts: rects.map(along),\n sizes: rects.map(sizeOf),\n step,\n els,\n handle,\n pointerId: event.pointerId,\n last: [event.clientX, event.clientY],\n scroller,\n };\n try {\n // the moves come to the handle even off the list; optional, the document listens anyway\n // движения приходят на ручку и вне списка; не обязательно, документ всё равно слушает\n handle.setPointerCapture?.(event.pointerId);\n } catch {\n /* a pointer the browser does not know (a synthetic event) / указатель, неизвестный браузеру */\n }\n els.forEach((el, i) => {\n el.style.transition = i === from ? 'none' : 'transform 150ms ease';\n if (i === from) {\n el.style.position = 'relative';\n el.style.zIndex = '1';\n el.setAttribute('data-sortable-dragging', '');\n }\n });\n dragging.value = from;\n document.addEventListener('pointermove', onPointerMove);\n document.addEventListener('pointerup', onPointerUp);\n document.addEventListener('pointercancel', onPointerCancel);\n // the window lost the focus mid-drag (Alt-Tab, a screenshot): the pointerup may never come; put the item back\n // окно потеряло фокус посреди перетаскивания: pointerup может не прийти; возвращаем элемент на место\n stopFocusLoss = listenFocusLoss(() => finish(false));\n document.addEventListener('keydown', onDragKey, true);\n }\n\n function onPointerMove(event: PointerEvent) {\n if (!drag || event.pointerId !== drag.pointerId) return;\n drag.last = [event.clientX, event.clientY];\n follow();\n edge.kick();\n }\n\n function finish(commit: boolean) {\n if (!drag) return;\n const { from, to, els, handle, pointerId } = drag;\n drag = null;\n edge.stop();\n try {\n handle.releasePointerCapture?.(pointerId);\n } catch {\n /* already released / уже отпущен */\n }\n document.removeEventListener('pointermove', onPointerMove);\n document.removeEventListener('pointerup', onPointerUp);\n document.removeEventListener('pointercancel', onPointerCancel);\n stopFocusLoss?.();\n stopFocusLoss = undefined;\n document.removeEventListener('keydown', onDragKey, true);\n for (const el of els) {\n el.style.transform = '';\n el.style.transition = '';\n el.style.position = '';\n el.style.zIndex = '';\n el.removeAttribute('data-sortable-dragging');\n }\n dragging.value = null;\n if (commit && to !== from) options.onMove(from, to);\n }\n\n const onPointerUp = (event: PointerEvent) => {\n if (drag && event.pointerId === drag.pointerId) finish(true);\n };\n const onPointerCancel = () => finish(false);\n function onDragKey(event: KeyboardEvent) {\n if (event.key === 'Escape') {\n event.preventDefault();\n event.stopPropagation();\n finish(false);\n }\n }\n\n //---]>\n // the keyboard / клавиатура\n\n let liftedFrom = 0;\n\n function focusHandle(index: number) {\n // after the app moved the item and Vue redrew the list / после того как приложение переставило элемент\n requestAnimationFrame(() => items()[index]?.querySelector<HTMLElement>(HANDLE)?.focus());\n }\n\n function setLifted(index: number | null) {\n items().forEach((el, i) => {\n if (i === index) el.setAttribute('data-sortable-lifted', '');\n else el.removeAttribute('data-sortable-lifted');\n });\n lifted.value = index;\n }\n\n function onKeydown(event: KeyboardEvent) {\n if (toValue(options.disabled) || drag) return;\n const handle = (event.target as HTMLElement).closest<HTMLElement>(HANDLE);\n if (!handle || !container.value?.contains(handle)) return;\n const els = items();\n const index = els.findIndex((el) => el.contains(handle));\n if (index < 0) return;\n\n const pick = event.key === ' ' || event.key === 'Enter';\n if (lifted.value === null) {\n if (!pick) return;\n event.preventDefault();\n liftedFrom = index;\n setLifted(index);\n announce(texts().lifted, index);\n return;\n }\n\n const back = axis === 'y' ? 'ArrowUp' : 'ArrowLeft';\n const forward = axis === 'y' ? 'ArrowDown' : 'ArrowRight';\n if (event.key === back || event.key === forward) {\n event.preventDefault();\n const to = index + (event.key === forward ? 1 : -1);\n if (to < 0 || to >= els.length) return;\n options.onMove(index, to);\n requestAnimationFrame(() => {\n setLifted(to);\n announce(texts().moved, to);\n });\n focusHandle(to);\n } else if (pick) {\n event.preventDefault();\n setLifted(null);\n announce(texts().dropped, index);\n } else if (event.key === 'Escape') {\n event.preventDefault();\n event.stopPropagation();\n if (index !== liftedFrom) {\n options.onMove(index, liftedFrom);\n focusHandle(liftedFrom);\n }\n setLifted(null);\n requestAnimationFrame(() => announce(texts().canceled, liftedFrom));\n } else if (event.key === 'Tab') {\n // leaving the handle drops the item where it is / уход с ручки ставит элемент на месте\n setLifted(null);\n }\n }\n\n function onFocusOut(event: FocusEvent) {\n if (lifted.value === null) return;\n const next = event.relatedTarget as HTMLElement | null;\n // focus moving to the same item's handle after a move is not a leave / переход фокуса на ручку после переноса\n if (next?.closest(HANDLE) && container.value?.contains(next)) return;\n if (next) setLifted(null);\n }\n\n onMounted(() => {\n const el = container.value;\n if (!el) return;\n el.addEventListener('pointerdown', onPointerDown);\n el.addEventListener('keydown', onKeydown);\n el.addEventListener('focusout', onFocusOut);\n live = document.createElement('div');\n live.setAttribute('aria-live', 'assertive');\n live.setAttribute('aria-atomic', 'true');\n live.style.cssText = 'position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap';\n document.body.appendChild(live);\n });\n\n onBeforeUnmount(() => {\n finish(false);\n const el = container.value;\n el?.removeEventListener('pointerdown', onPointerDown);\n el?.removeEventListener('keydown', onKeydown);\n el?.removeEventListener('focusout', onFocusOut);\n live?.remove();\n live = null;\n });\n\n return {\n /** The index being dragged by the pointer, or null. / Индекс, который тащат указателем, или null. */\n dragging,\n /** The index lifted by the keyboard, or null. / Индекс, поднятый с клавиатуры, или null. */\n lifted,\n /** Stops a pointer drag without moving. / Прерывает перетаскивание без переноса. */\n cancel: () => finish(false),\n };\n}\n"],"mappings":";;;;;;;;;AA+BA,SAAgB,WAAW,SAAiB,QAA2B,OAA0B,MAAsB;CACnH,IAAI,SAAS;CACb,KAAK,IAAI,IAAI,GAAG,IAAI,OAAO,QAAQ,KAAK;EACpC,IAAI,MAAM,MAAM;EAChB,IAAI,UAAU,OAAO,KAAM,MAAM,KAAM,GAAG;CAC9C;CACA,OAAO;AACX;;;;;;AAOA,SAAgB,WAAW,OAAe,MAAc,IAAY,MAAwB;CACxF,OAAO,MAAM,KAAK,EAAE,QAAQ,MAAM,IAAI,GAAG,MAAM;EAC3C,IAAI,MAAM,MAAM,OAAO;EACvB,IAAI,OAAO,MAAM,IAAI,QAAQ,KAAK,IAAI,OAAO,CAAC;EAC9C,IAAI,KAAK,QAAQ,KAAK,MAAM,IAAI,MAAM,OAAO;EAC7C,OAAO;CACX,CAAC;AACL;;AAGA,SAAgB,SAAY,MAAoB,MAAc,IAAiB;CAC3E,MAAM,OAAO,KAAK,MAAM;CACxB,IAAI,OAAO,KAAK,QAAQ,KAAK,QAAQ,OAAO;CAC5C,MAAM,CAAC,QAAQ,KAAK,OAAO,MAAM,CAAC;CAClC,KAAK,OAAO,KAAK,IAAI,GAAG,KAAK,IAAI,IAAI,KAAK,MAAM,CAAC,GAAG,GAAG,IAAK;CAC5D,OAAO;AACX;AAUA,IAAa,kBAAiC;CAC1C,QAAQ;CACR,OAAO;CACP,SAAS;CACT,UAAU;AACd;AAEA,IAAa,kBAAiC;CAC1C,QAAQ;CACR,OAAO;CACP,SAAS;CACT,UAAU;AACd;AAiBA,IAAM,OAAO;AACb,IAAM,SAAS;AAEf,SAAS,aAAa,IAAiB,MAAwC;CAC3E,KAAK,IAAI,IAAwB,IAAI,GAAG,IAAI,EAAE,eAAe;EACzD,MAAM,QAAQ,iBAAiB,CAAC;EAChC,MAAM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AAI;GACd,4BAA4B,SAAS,MAAM,CAAC,CAAC,UAAU,UAAU,CAAC;EACtE,OAAO,IAAI,MAAM,QAAQ,OAErB,UAAU,IAAI;CAEtB;CAEA,SAAS,WAAW,OAAmB;EACnC,IAAI,OAAO,UAAU,MAAM;EAC3B,MAAM,OAAO,MAAM;EAEnB,IAAI,MAAM,QAAQ,MAAM,KAAK,UAAU,OAAO,SAAS,IAAI,GAAG;EAC9D,IAAI,MAAM,UAAU,IAAI;CAC5B;CAEA,gBAAgB;EACZ,MAAM,KAAK,UAAU;EACrB,IAAI,CAAC,IAAI;EACT,GAAG,iBAAiB,eAAe,aAAa;EAChD,GAAG,iBAAiB,WAAW,SAAS;EACxC,GAAG,iBAAiB,YAAY,UAAU;EAC1C,OAAO,SAAS,cAAc,KAAK;EACnC,KAAK,aAAa,aAAa,WAAW;EAC1C,KAAK,aAAa,eAAe,MAAM;EACvC,KAAK,MAAM,UAAU;EACrB,SAAS,KAAK,YAAY,IAAI;CAClC,CAAC;CAED,sBAAsB;EAClB,OAAO,KAAK;EACZ,MAAM,KAAK,UAAU;EACrB,IAAI,oBAAoB,eAAe,aAAa;EACpD,IAAI,oBAAoB,WAAW,SAAS;EAC5C,IAAI,oBAAoB,YAAY,UAAU;EAC9C,MAAM,OAAO;EACb,OAAO;CACX,CAAC;CAED,OAAO;;EAEH;;EAEA;;EAEA,cAAc,OAAO,KAAK;CAC9B;AACJ"}
@@ -19,6 +19,7 @@ type __VLS_Slots = {
19
19
  action: SwipeRowAction;
20
20
  armed: boolean;
21
21
  side: 'start' | 'end';
22
+ width: number;
22
23
  }): unknown;
23
24
  };
24
25
  type __VLS_ModelProps = {
@@ -1,3 +1,3 @@
1
1
  export { default as TaoxSwipeRow } from './TaoxSwipeRow.vue';
2
- export { armedAt, clampOffset, endOpenWidth, endWidths, FULL_SWIPE_RATIO, fullThreshold, START_THRESHOLD_PX, startThreshold, swipeRowRelease, } from './model';
2
+ export { armedAt, clampOffset, endOpenWidth, endWidths, FULL_SWIPE_RATIO, fullThreshold, START_THRESHOLD_PX, startThreshold, SWIPE_SLIVER_PX, swipeRowRelease, } from './model';
3
3
  export type { SwipeRowAction, SwipeRowGeometry, SwipeRowOutcome } from './model';
@@ -56,11 +56,17 @@ export type SwipeRowOutcome = {
56
56
  * продолжается в своём направлении.
57
57
  */
58
58
  export declare function swipeRowRelease(release: SwipeRelease, g: SwipeRowGeometry): SwipeRowOutcome;
59
+ /** The narrowest an action between the row and the last one gets: still a visible link. / Самое узкое промежуточное действие. */
60
+ export declare const SWIPE_SLIVER_PX = 32;
59
61
  /**
60
- * The widths of the end actions at a pull of `drag` px (≥ 0): they share the space evenly, so they grow from slivers
61
- * to their full width and on; once the full swipe is armed the last one takes nearly all of it and the others shrink
62
- * to slivers.
63
- * Ширины действий справа при протяжке на `drag` px: делят место поровну, поэтому растут от полосок до полной ширины и
64
- * дальше; когда длинный свайп взведён, последнее занимает почти всё, остальные сжимаются в полоски.
62
+ * The widths of the end actions at a pull of `drag` px (≥ 0), one continuous function, so nothing jumps. Up to the
63
+ * open width they share the space evenly and grow to their width. Past it the actions between the row and the last one
64
+ * stop growing and shrink back, smoothly, to slivers (`SWIPE_SLIVER_PX`) a little past the full-swipe threshold, and the last one
65
+ * takes what they give up; further on they stay slivers, so a pull back opens them out again the same way.
66
+ * `armed` is no longer used (the widths depend on the pull alone); it stays for the 0.5.0 signature.
67
+ * Ширины действий справа при протяжке на `drag` px — одна непрерывная функция, поэтому ничего не прыгает. До открытой
68
+ * ширины они делят место поровну и растут до своей ширины. Дальше промежуточные перестают расти и плавно сжимаются до
69
+ * полосок к порогу длинного свайпа, а последнее забирает отданное место; за порогом они остаются полосками, поэтому
70
+ * при обратном движении так же плавно раскрываются. `armed` больше не нужен; оставлен ради подписи 0.5.0.
65
71
  */
66
- export declare function endWidths(drag: number, g: SwipeRowGeometry, armed: boolean, gap?: number): number[];
72
+ export declare function endWidths(drag: number, g: SwipeRowGeometry, _armed?: boolean, gap?: number): number[];
package/dist/swiperow.css CHANGED
@@ -25,9 +25,14 @@
25
25
  display: flex;
26
26
  gap: var(--tx-swipe-gap);
27
27
  }
28
+
29
+ /* clipped, with the gap as the button's margin: at width 0 nothing of it is left, while the keyboard can still reach it
30
+ (a padding kept a 6px box, and the button showed at the start edge of a row pulled the other way)
31
+ с обрезкой, а зазор — поле кнопки: при ширине 0 от неё ничего не остаётся, а клавиатура всё равно до неё доходит
32
+ (padding оставлял коробку в 6px, и кнопка виднелась у начального края строки, которую тянули в другую сторону) */
28
33
  .tx-swipe__start {
29
34
  inset-inline-start: 0;
30
- padding-inline-end: var(--tx-swipe-gap);
35
+ overflow: hidden;
31
36
  transition: width 0.22s ease;
32
37
  }
33
38
  .tx-swipe__end {
@@ -43,7 +48,9 @@
43
48
  flex-direction: column;
44
49
  align-items: center;
45
50
  justify-content: center;
46
- gap: 4px;
51
+ /* the icon and the label read as one: a small gap, not pressed to the edges of a short row
52
+ иконка и подпись читаются вместе: небольшой зазор, а не прижаты к краям невысокой строки */
53
+ gap: 2px;
47
54
  min-width: 0;
48
55
  height: 100%;
49
56
  padding: 0;
@@ -59,18 +66,23 @@
59
66
  width 0.15s ease,
60
67
  background-color 0.15s ease;
61
68
  }
69
+
70
+ /* under the finger the actions follow the row in the same frame: no width easing, or they trail behind it
71
+ под пальцем действия идут за строкой в том же кадре: без сглаживания ширины, иначе они отстают */
62
72
  .tx-swipe--dragging .tx-swipe__end .tx-swipe__action {
63
73
  transition: background-color 0.15s ease;
64
74
  }
65
75
 
66
- /* the full swipe armed: the last action takes the row; the widths animate to it / длинный свайп взведён */
67
- .tx-swipe--armed-full .tx-swipe__end .tx-swipe__action {
68
- transition:
69
- width 0.15s ease,
70
- background-color 0.15s ease;
71
- }
76
+ /* the start action is one line, from the start edge: the icon at a fixed place, the label after it
77
+ действие слева — одна строка от начального края: иконка на постоянном месте, подпись за ней */
72
78
  .tx-swipe__action--start {
73
79
  flex: 1;
80
+ flex-direction: row;
81
+ justify-content: flex-start;
82
+ gap: 10px;
83
+ min-width: 0;
84
+ margin-inline-end: var(--tx-swipe-gap);
85
+ padding-inline-start: 22px;
74
86
  }
75
87
  .tx-swipe__action--armed {
76
88
  background: color-mix(in srgb, var(--tao-tone) 45%, var(--tao-color-surface-raised, #1f1f1f));
@@ -80,16 +92,36 @@
80
92
  outline: 2px solid var(--tao-color-accent);
81
93
  outline-offset: -2px;
82
94
  }
95
+
96
+ /* never squeezed or cut with «…»: a label wider than its block stays whole and centred, the block clips it, and it is
97
+ still transparent then; so the line never changes as the block grows
98
+ подпись не сжимается и не обрезается «…»: шире блока — остаётся целой и по центру, блок её обрезает, а она в это
99
+ время ещё прозрачна; поэтому строка не меняется, пока блок растёт */
83
100
  .tx-swipe__label {
84
- max-width: 100%;
85
- overflow: hidden;
86
- text-overflow: ellipsis;
101
+ flex: none;
87
102
  white-space: nowrap;
103
+ line-height: 1.2;
104
+ }
105
+ .tx-swipe__action :is(svg, .tao-icon) {
106
+ flex: none;
107
+ }
108
+
109
+ /* a short fade, so a row settling by itself shows them softly too; under the finger none
110
+ короткий переход: строка, доезжающая сама, тоже их проявляет мягко; под пальцем без него */
111
+ .tx-swipe__label,
112
+ .tx-swipe__action .tao-icon {
113
+ transition: opacity 0.12s ease;
114
+ }
115
+ .tx-swipe--dragging .tx-swipe__label,
116
+ .tx-swipe--dragging .tx-swipe__action .tao-icon {
117
+ transition: none;
88
118
  }
89
119
  @media (prefers-reduced-motion: reduce) {
90
120
  .tx-swipe__front,
91
121
  .tx-swipe__start,
92
- .tx-swipe__action {
122
+ .tx-swipe__action,
123
+ .tx-swipe__label,
124
+ .tx-swipe__action .tao-icon {
93
125
  transition: none;
94
126
  }
95
127
  }
package/dist/swiperow.js CHANGED
@@ -1,4 +1,4 @@
1
- import { SwipeTracker, settleOpen } from "./gestures.js";
1
+ import { SwipeTracker, listenFocusLoss, settleOpen } from "./gestures.js";
2
2
  import { Fragment, computed, createBlock, createCommentVNode, createElementBlock, createElementVNode, defineComponent, mergeModels, normalizeClass, normalizeStyle, onBeforeUnmount, onMounted, openBlock, ref, renderList, renderSlot, toDisplayString, unref, useModel, watch } from "vue";
3
3
  import { TaoIcon, toneClass } from "@1337exp/taoui";
4
4
  //#region src/swiperow/model.ts
@@ -49,38 +49,41 @@ function swipeRowRelease(release, g) {
49
49
  }, { end: endOpenWidth(g) }) < 0
50
50
  };
51
51
  }
52
+ /** The narrowest an action between the row and the last one gets: still a visible link. / Самое узкое промежуточное действие. */
53
+ var SWIPE_SLIVER_PX = 32;
52
54
  /**
53
- * The widths of the end actions at a pull of `drag` px (≥ 0): they share the space evenly, so they grow from slivers
54
- * to their full width and on; once the full swipe is armed the last one takes nearly all of it and the others shrink
55
- * to slivers.
56
- * Ширины действий справа при протяжке на `drag` px: делят место поровну, поэтому растут от полосок до полной ширины и
57
- * дальше; когда длинный свайп взведён, последнее занимает почти всё, остальные сжимаются в полоски.
55
+ * The widths of the end actions at a pull of `drag` px (≥ 0), one continuous function, so nothing jumps. Up to the
56
+ * open width they share the space evenly and grow to their width. Past it the actions between the row and the last one
57
+ * stop growing and shrink back, smoothly, to slivers (`SWIPE_SLIVER_PX`) a little past the full-swipe threshold, and the last one
58
+ * takes what they give up; further on they stay slivers, so a pull back opens them out again the same way.
59
+ * `armed` is no longer used (the widths depend on the pull alone); it stays for the 0.5.0 signature.
60
+ * Ширины действий справа при протяжке на `drag` px — одна непрерывная функция, поэтому ничего не прыгает. До открытой
61
+ * ширины они делят место поровну и растут до своей ширины. Дальше промежуточные перестают расти и плавно сжимаются до
62
+ * полосок к порогу длинного свайпа, а последнее забирает отданное место; за порогом они остаются полосками, поэтому
63
+ * при обратном движении так же плавно раскрываются. `armed` больше не нужен; оставлен ради подписи 0.5.0.
58
64
  */
59
- function endWidths(drag, g, armed, gap = 6) {
65
+ function endWidths(drag, g, _armed, gap = 6) {
60
66
  const n = g.endCount;
61
67
  if (n === 0 || drag <= 0) return Array.from({ length: n }, () => 0);
62
68
  const room = Math.max(0, drag - gap * n);
63
- if (!armed) return Array.from({ length: n }, () => room / n);
64
- const sliver = Math.min(28, room / n);
65
- return Array.from({ length: n }, (_, i) => i === n - 1 ? room - sliver * (n - 1) : sliver);
69
+ const open = endOpenWidth(g);
70
+ if (n === 1) return [room];
71
+ if (drag <= open) return Array.from({ length: n }, () => room / n);
72
+ const end = Math.max(open + 1, Math.min(g.width * .9, fullThreshold(g) + g.width * .2));
73
+ const t = Math.min(1, (drag - open) / (end - open));
74
+ const widest = g.actionWidth - gap;
75
+ const middle = Math.min(widest, Math.max(0, widest + (Math.min(32, widest) - widest) * t));
76
+ return Array.from({ length: n }, (_, i) => i === n - 1 ? room - middle * (n - 1) : middle);
66
77
  }
67
78
  //#endregion
68
79
  //#region src/swiperow/TaoxSwipeRow.vue?vue&type=script&setup=true&lang.ts
69
80
  var _hoisted_1 = ["aria-label"];
70
81
  var _hoisted_2 = {
71
- key: 1,
72
- class: "tx-swipe__label"
73
- };
74
- var _hoisted_3 = {
75
82
  key: 1,
76
83
  class: "tx-swipe__end",
77
84
  "data-side": "end"
78
85
  };
79
- var _hoisted_4 = ["aria-label", "onClick"];
80
- var _hoisted_5 = {
81
- key: 1,
82
- class: "tx-swipe__label"
83
- };
86
+ var _hoisted_3 = ["aria-label", "onClick"];
84
87
  //#endregion
85
88
  //#region src/swiperow/TaoxSwipeRow.vue
86
89
  var TaoxSwipeRow_default = /* @__PURE__ */ defineComponent({
@@ -134,7 +137,7 @@ var TaoxSwipeRow_default = /* @__PURE__ */ defineComponent({
134
137
  });
135
138
  const offset = computed(() => dragging.value ? drag.value : rest.value);
136
139
  const armed = computed(() => dragging.value ? armedAt(drag.value, geometry.value) : null);
137
- const widths = computed(() => endWidths(Math.max(0, -offset.value), geometry.value, armed.value === "full" || gone.value));
140
+ const widths = computed(() => endWidths(gone.value ? width.value : Math.max(0, -offset.value), geometry.value));
138
141
  const lastEnd = computed(() => props.end[props.end.length - 1]);
139
142
  watch(armed, (next) => {
140
143
  if (next && typeof navigator !== "undefined") navigator.vibrate?.(8);
@@ -147,12 +150,23 @@ var TaoxSwipeRow_default = /* @__PURE__ */ defineComponent({
147
150
  y: e.clientY,
148
151
  t: e.timeStamp
149
152
  });
153
+ let stopFocusLoss;
154
+ function release() {
155
+ stopFocusLoss?.();
156
+ stopFocusLoss = void 0;
157
+ pointerId = null;
158
+ dragging.value = false;
159
+ }
150
160
  function onDown(e) {
151
161
  if (props.disabled || pointerId !== null || e.pointerType === "mouse" && (!props.mouse || e.button !== 0)) return;
152
162
  pointerId = e.pointerId;
153
163
  swiped = false;
154
164
  startShown.value = false;
155
165
  tracker.down(sample(e), rest.value);
166
+ stopFocusLoss = listenFocusLoss(() => {
167
+ tracker.cancel();
168
+ release();
169
+ });
156
170
  }
157
171
  function onMove(e) {
158
172
  if (e.pointerId !== pointerId) return;
@@ -169,14 +183,10 @@ var TaoxSwipeRow_default = /* @__PURE__ */ defineComponent({
169
183
  }
170
184
  function onUp(e) {
171
185
  if (e.pointerId !== pointerId) return;
172
- const release = tracker.up(sample(e));
173
- pointerId = null;
174
- if (!release) {
175
- dragging.value = false;
176
- return;
177
- }
178
- const outcome = swipeRowRelease(release, geometry.value);
179
- dragging.value = false;
186
+ const result = tracker.up(sample(e));
187
+ release();
188
+ if (!result) return;
189
+ const outcome = swipeRowRelease(result, geometry.value);
180
190
  if (outcome.kind === "start" && props.start) {
181
191
  open.value = false;
182
192
  emit("action", props.start.id);
@@ -192,8 +202,7 @@ var TaoxSwipeRow_default = /* @__PURE__ */ defineComponent({
192
202
  function onCancel(e) {
193
203
  if (e.pointerId !== pointerId) return;
194
204
  tracker.cancel();
195
- pointerId = null;
196
- dragging.value = false;
205
+ release();
197
206
  }
198
207
  function onClickCapture(e) {
199
208
  if (swiped) {
@@ -234,11 +243,16 @@ var TaoxSwipeRow_default = /* @__PURE__ */ defineComponent({
234
243
  }
235
244
  });
236
245
  onBeforeUnmount(() => {
246
+ stopFocusLoss?.();
237
247
  resize?.disconnect();
238
248
  document.removeEventListener("pointerdown", onOutside, true);
239
249
  });
240
250
  const startWidth = computed(() => Math.max(0, offset.value));
241
- const showLabel = (w) => w >= 56;
251
+ const fade = (width, from, span) => Math.min(1, Math.max(0, (width - from) / span));
252
+ const endIcon = (w) => fade(w, 22, 20);
253
+ const endLabel = (w) => fade(w, 50, 18);
254
+ const startIcon = (w) => fade(w, 36, 24);
255
+ const startLabel = (w) => fade(w, 84, 28);
242
256
  return (_ctx, _cache) => {
243
257
  return openBlock(), createElementBlock("div", {
244
258
  ref_key: "root",
@@ -263,32 +277,39 @@ var TaoxSwipeRow_default = /* @__PURE__ */ defineComponent({
263
277
  }, [renderSlot(_ctx.$slots, "action", {
264
278
  action: __props.start,
265
279
  armed: armed.value === "start",
266
- side: "start"
280
+ side: "start",
281
+ width: startWidth.value
267
282
  }, () => [__props.start.icon ? (openBlock(), createBlock(unref(TaoIcon), {
268
283
  key: 0,
269
284
  name: __props.start.icon,
270
- size: 22
271
- }, null, 8, ["name"])) : createCommentVNode("", true), showLabel(startWidth.value) ? (openBlock(), createElementBlock("span", _hoisted_2, toDisplayString(__props.start.label), 1)) : createCommentVNode("", true)])], 10, _hoisted_1)], 4)) : createCommentVNode("", true),
272
- __props.end.length ? (openBlock(), createElementBlock("div", _hoisted_3, [(openBlock(true), createElementBlock(Fragment, null, renderList(__props.end, (action, i) => {
285
+ size: 20,
286
+ style: normalizeStyle({ opacity: startIcon(startWidth.value) })
287
+ }, null, 8, ["name", "style"])) : createCommentVNode("", true), createElementVNode("span", {
288
+ class: "tx-swipe__label",
289
+ style: normalizeStyle({ opacity: startLabel(startWidth.value) })
290
+ }, toDisplayString(__props.start.label), 5)])], 10, _hoisted_1)], 4)) : createCommentVNode("", true),
291
+ __props.end.length ? (openBlock(), createElementBlock("div", _hoisted_2, [(openBlock(true), createElementBlock(Fragment, null, renderList(__props.end, (action, i) => {
273
292
  return openBlock(), createElementBlock("button", {
274
293
  key: action.id,
275
294
  type: "button",
276
295
  class: normalizeClass(["tx-swipe__action", [unref(toneClass)(action.tone ?? "neutral"), { "tx-swipe__action--armed": i === __props.end.length - 1 && (armed.value === "full" || gone.value) }]]),
277
- style: normalizeStyle({
278
- width: `${widths.value[i]}px`,
279
- opacity: Math.min(1, (widths.value[i] ?? 0) / 28)
280
- }),
296
+ style: normalizeStyle({ width: `${widths.value[i]}px` }),
281
297
  "aria-label": action.label,
282
298
  onClick: ($event) => run(action)
283
299
  }, [renderSlot(_ctx.$slots, "action", {
284
300
  action,
285
301
  armed: i === __props.end.length - 1 && armed.value === "full",
286
- side: "end"
302
+ side: "end",
303
+ width: widths.value[i] ?? 0
287
304
  }, () => [action.icon ? (openBlock(), createBlock(unref(TaoIcon), {
288
305
  key: 0,
289
306
  name: action.icon,
290
- size: 22
291
- }, null, 8, ["name"])) : createCommentVNode("", true), showLabel(widths.value[i] ?? 0) ? (openBlock(), createElementBlock("span", _hoisted_5, toDisplayString(action.label), 1)) : createCommentVNode("", true)])], 14, _hoisted_4);
307
+ size: 20,
308
+ style: normalizeStyle({ opacity: endIcon(widths.value[i] ?? 0) })
309
+ }, null, 8, ["name", "style"])) : createCommentVNode("", true), createElementVNode("span", {
310
+ class: "tx-swipe__label",
311
+ style: normalizeStyle({ opacity: endLabel(widths.value[i] ?? 0) })
312
+ }, toDisplayString(action.label), 5)])], 14, _hoisted_3);
292
313
  }), 128))])) : createCommentVNode("", true),
293
314
  createElementVNode("div", {
294
315
  class: "tx-swipe__front",
@@ -304,6 +325,6 @@ var TaoxSwipeRow_default = /* @__PURE__ */ defineComponent({
304
325
  }
305
326
  });
306
327
  //#endregion
307
- export { FULL_SWIPE_RATIO, START_THRESHOLD_PX, TaoxSwipeRow_default as TaoxSwipeRow, armedAt, clampOffset, endOpenWidth, endWidths, fullThreshold, startThreshold, swipeRowRelease };
328
+ export { FULL_SWIPE_RATIO, START_THRESHOLD_PX, SWIPE_SLIVER_PX, TaoxSwipeRow_default as TaoxSwipeRow, armedAt, clampOffset, endOpenWidth, endWidths, fullThreshold, startThreshold, swipeRowRelease };
308
329
 
309
330
  //# sourceMappingURL=swiperow.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"swiperow.js","names":["_useModel","_openBlock","_createElementBlock","_normalizeClass","_normalizeStyle","_createElementVNode","_unref","_renderSlot","_createBlock","_createCommentVNode","_toDisplayString","_Fragment","_renderList","_sfc_main"],"sources":["../src/swiperow/model.ts","../src/swiperow/TaoxSwipeRow.vue","../src/swiperow/TaoxSwipeRow.vue"],"sourcesContent":["import { settleOpen, SWIPE_FLING_PX_PER_MS, type SwipeRelease } from '../gestures';\n\n/**\n * An action of a swipe row. `tone` is a TaoUI tone (`neutral`, `danger`, `success`…), `icon` a TaoIcon name.\n * Действие свайп-строки. `tone` — тон TaoUI, `icon` — имя TaoIcon.\n */\nexport interface SwipeRowAction {\n id: string;\n label: string;\n icon?: string;\n tone?: 'accent' | 'neutral' | 'success' | 'danger' | 'warning' | 'info';\n}\n\n/**\n * The thresholds of the row, px or a share of its width.\n * Пороги строки, px или доля её ширины.\n */\nexport interface SwipeRowGeometry {\n /** The row width. / Ширина строки. */\n width: number;\n /** How wide each end action stands when the row is open. / Ширина каждого действия справа в открытой строке. */\n actionWidth: number;\n /** How many end actions. / Сколько действий справа. */\n endCount: number;\n /** Whether there is a start action. / Есть ли действие слева. */\n hasStart: boolean;\n /** Whether pulling far runs the last end action by itself. / Выполняет ли длинный свайп последнее действие сам. */\n fullSwipe: boolean;\n}\n\n/** Past this share of the width a pull to the end runs the last action. / После этой доли ширины длинный свайп выполняет последнее действие. */\nexport const FULL_SWIPE_RATIO = 0.6;\n/** A pull to the start runs its action past this many px (or a third of a narrow row). / Свайп вправо выполняет действие после стольких px. */\nexport const START_THRESHOLD_PX = 96;\n\nexport const startThreshold = (g: SwipeRowGeometry) => Math.min(START_THRESHOLD_PX, g.width / 3);\nexport const endOpenWidth = (g: SwipeRowGeometry) => g.actionWidth * g.endCount;\nexport const fullThreshold = (g: SwipeRowGeometry) => Math.max(endOpenWidth(g) + 24, g.width * FULL_SWIPE_RATIO);\n\n/**\n * Whether the row, at this offset, is past the point where releasing runs an action: `start`, `full` or null.\n * Пройдена ли при этом сдвиге точка, после которой отпускание выполняет действие: `start`, `full` или null.\n */\nexport function armedAt(offset: number, g: SwipeRowGeometry): 'start' | 'full' | null {\n if (offset > 0 && g.hasStart && offset >= startThreshold(g)) return 'start';\n if (offset < 0 && g.fullSwipe && g.endCount > 0 && -offset >= fullThreshold(g)) return 'full';\n return null;\n}\n\n/** How far the row may move: no further than there is something behind it. / Насколько строка может уехать. */\nexport function clampOffset(offset: number, g: SwipeRowGeometry): number {\n const right = g.hasStart ? g.width : 0;\n const left = g.endCount === 0 ? 0 : g.fullSwipe ? -g.width : -endOpenWidth(g) * 1.5;\n return Math.min(right, Math.max(left, offset));\n}\n\nexport type SwipeRowOutcome =\n | { kind: 'rest'; open: boolean } // the row comes to rest: open (the end actions shown) or closed\n | { kind: 'start' } // the start action runs, the row goes back\n | { kind: 'full' }; // the last end action runs\n\n/**\n * What a release does. A pull to the start past its threshold (or flung that way past half of it) runs the start\n * action; a pull to the end past the full threshold runs the last end action; otherwise the row rests open or closed,\n * a fling going on in its direction (`settleOpen`).\n * Что делает отпускание. Свайп вправо дальше порога (или брошенный туда дальше его половины) выполняет действие слева;\n * влево дальше полного порога — последнее действие справа; иначе строка встаёт открытой или закрытой, бросок\n * продолжается в своём направлении.\n */\nexport function swipeRowRelease(release: SwipeRelease, g: SwipeRowGeometry): SwipeRowOutcome {\n const offset = clampOffset(release.offset, g);\n const armed = armedAt(offset, g);\n if (armed) return { kind: armed };\n if (offset > 0 && g.hasStart && release.velocity >= SWIPE_FLING_PX_PER_MS && offset >= startThreshold(g) / 2) {\n return { kind: 'start' };\n }\n if (g.endCount === 0) return { kind: 'rest', open: false };\n const rest = settleOpen({ offset: Math.min(0, offset), velocity: release.velocity }, { end: endOpenWidth(g) });\n return { kind: 'rest', open: rest < 0 };\n}\n\n/**\n * The widths of the end actions at a pull of `drag` px (≥ 0): they share the space evenly, so they grow from slivers\n * to their full width and on; once the full swipe is armed the last one takes nearly all of it and the others shrink\n * to slivers.\n * Ширины действий справа при протяжке на `drag` px: делят место поровну, поэтому растут от полосок до полной ширины и\n * дальше; когда длинный свайп взведён, последнее занимает почти всё, остальные сжимаются в полоски.\n */\nexport function endWidths(drag: number, g: SwipeRowGeometry, armed: boolean, gap = 6): number[] {\n const n = g.endCount;\n if (n === 0 || drag <= 0) return Array.from({ length: n }, () => 0);\n const room = Math.max(0, drag - gap * n);\n if (!armed) return Array.from({ length: n }, () => room / n);\n const sliver = Math.min(28, room / n);\n return Array.from({ length: n }, (_, i) => (i === n - 1 ? room - sliver * (n - 1) : sliver));\n}\n","<script lang=\"ts\" setup>\nimport { TaoIcon, toneClass } from '@1337exp/taoui';\nimport { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue';\nimport { SwipeTracker, type Sample } from '../gestures';\nimport { armedAt, clampOffset, endOpenWidth, endWidths, startThreshold, swipeRowRelease, type SwipeRowAction, type SwipeRowGeometry } from './model';\n\n// A row of a list that a finger slides sideways, as in a mail app. To the start (right): one action behind it, run on\n// release past its threshold, and the row comes back (read / unread). To the end (left): the actions grow out and the\n// row stays open on them; pulled far, the last one takes the row and runs on release (delete). The gesture (a swipe or\n// a scroll, the release speed, where to rest) is TaoUX's gestures; the actions are TaoUI icons and tones.\n// Строка списка, которую палец сдвигает вбок, как в почте. Вправо: одно действие позади, выполняется при отпускании\n// дальше порога, строка возвращается (прочитано / не прочитано). Влево: действия вырастают, и строка остаётся открытой\n// на них; если тянуть далеко, последнее занимает строку и выполняется при отпускании (удалить).\nconst props = withDefaults(\n defineProps<{\n /** The action behind the row on a pull to the start. / Действие позади строки при свайпе вправо. */\n start?: SwipeRowAction;\n /** The actions on a pull to the end, in order; the last one is the full swipe. / Действия при свайпе влево; последнее — длинный свайп. */\n end?: SwipeRowAction[];\n /** The width of each end action when the row is open, px. / Ширина каждого действия справа в открытой строке. */\n actionWidth?: number;\n /** Pulling far to the end runs the last action. / Длинный свайп влево выполняет последнее действие. */\n fullSwipe?: boolean;\n /** A mouse can drag it too (a touch screen always can). / Тянуть можно и мышью (палец может всегда). */\n mouse?: boolean;\n disabled?: boolean;\n }>(),\n { start: undefined, end: () => [], actionWidth: 76, fullSwipe: true, mouse: false, disabled: false },\n);\n\nconst emit = defineEmits<{\n /** An action was chosen: by a button, a pull past the threshold, or the full swipe. / Выбрано действие. */\n action: [id: string];\n}>();\n\n/** The end actions are shown. / Действия справа открыты. */\nconst open = defineModel<boolean>('open', { default: false });\n\ndefineSlots<{\n default?(): unknown;\n /** Your own face of an action. / Свой вид действия. */\n action?(props: { action: SwipeRowAction; armed: boolean; side: 'start' | 'end' }): unknown;\n}>();\n\nconst root = ref<HTMLElement | null>(null);\nconst width = ref(320);\nconst dragging = ref(false);\nconst drag = ref(0);\n// a moment after a full swipe: the row stays off to the side while the app removes it\n// миг после длинного свайпа: строка остаётся сдвинутой, пока приложение её убирает\nconst gone = ref(false);\nconst startShown = ref(false);\n\nconst geometry = computed<SwipeRowGeometry>(() => ({\n width: width.value,\n actionWidth: props.actionWidth,\n endCount: props.end.length,\n hasStart: Boolean(props.start),\n fullSwipe: props.fullSwipe,\n}));\n\nconst rest = computed(() => {\n if (gone.value) return -width.value;\n if (startShown.value) return startThreshold(geometry.value);\n return open.value ? -endOpenWidth(geometry.value) : 0;\n});\nconst offset = computed(() => (dragging.value ? drag.value : rest.value));\nconst armed = computed(() => (dragging.value ? armedAt(drag.value, geometry.value) : null));\nconst widths = computed(() => endWidths(Math.max(0, -offset.value), geometry.value, armed.value === 'full' || gone.value));\nconst lastEnd = computed(() => props.end[props.end.length - 1]);\n\n// a short buzz where the phone can, when an action becomes armed / короткая вибрация там, где телефон умеет\nwatch(armed, (next) => {\n if (next && typeof navigator !== 'undefined') navigator.vibrate?.(8);\n});\n\n//---]>\n// the gesture / жест\n\nconst tracker = new SwipeTracker('x');\nlet pointerId: number | null = null;\nlet swiped = false;\nconst sample = (e: PointerEvent): Sample => ({ x: e.clientX, y: e.clientY, t: e.timeStamp });\n\nfunction onDown(e: PointerEvent) {\n if (props.disabled || pointerId !== null || (e.pointerType === 'mouse' && (!props.mouse || e.button !== 0))) return;\n pointerId = e.pointerId;\n swiped = false;\n startShown.value = false;\n tracker.down(sample(e), rest.value);\n}\n\nfunction onMove(e: PointerEvent) {\n if (e.pointerId !== pointerId) return;\n const step = tracker.move(sample(e));\n if (step.intent !== 'swipe') return;\n if (!dragging.value) {\n dragging.value = true;\n try {\n (e.currentTarget as HTMLElement).setPointerCapture(e.pointerId);\n } catch {\n /* a pointer the browser does not know / неизвестный браузеру указатель */\n }\n }\n swiped = true;\n drag.value = clampOffset(step.offset, geometry.value);\n}\n\nfunction onUp(e: PointerEvent) {\n if (e.pointerId !== pointerId) return;\n const release = tracker.up(sample(e));\n pointerId = null;\n if (!release) {\n dragging.value = false;\n return;\n }\n const outcome = swipeRowRelease(release, geometry.value);\n dragging.value = false;\n if (outcome.kind === 'start' && props.start) {\n open.value = false;\n emit('action', props.start.id);\n } else if (outcome.kind === 'full' && lastEnd.value) {\n gone.value = true;\n emit('action', lastEnd.value.id);\n // the app removes the row; if it keeps it (an archive that failed), it comes back\n // приложение убирает строку; если оставит, она вернётся\n setTimeout(() => {\n gone.value = false;\n open.value = false;\n }, 400);\n } else if (outcome.kind === 'rest') {\n open.value = outcome.open;\n }\n}\n\nfunction onCancel(e: PointerEvent) {\n if (e.pointerId !== pointerId) return;\n tracker.cancel();\n pointerId = null;\n dragging.value = false;\n}\n\n// the end of a swipe also fires a click on the row: it must not open the item\n// конец свайпа даёт и click по строке: он не должен открывать элемент\nfunction onClickCapture(e: MouseEvent) {\n if (swiped) {\n e.stopPropagation();\n e.preventDefault();\n swiped = false;\n }\n}\n\nfunction run(action: SwipeRowAction) {\n open.value = false;\n startShown.value = false;\n emit('action', action.id);\n}\n\n//---]>\n// the keyboard: an action button that gets the focus shows its side\n// клавиатура: кнопка действия, получившая фокус, показывает свою сторону\n\nfunction onFocusIn(e: FocusEvent) {\n const side = (e.target as HTMLElement).closest<HTMLElement>('[data-side]')?.dataset.side;\n if (side === 'end') open.value = true;\n if (side === 'start') startShown.value = true;\n}\n\nfunction onFocusOut(e: FocusEvent) {\n if (root.value?.contains(e.relatedTarget as Node | null)) return;\n startShown.value = false;\n open.value = false;\n}\n\n// an open row closes on a touch outside it / открытая строка закрывается касанием вне её\nfunction onOutside(e: PointerEvent) {\n if (!root.value?.contains(e.target as Node)) open.value = false;\n}\nwatch(open, (isOpen) => {\n if (isOpen) document.addEventListener('pointerdown', onOutside, true);\n else document.removeEventListener('pointerdown', onOutside, true);\n});\n\nlet resize: ResizeObserver | undefined;\nonMounted(() => {\n if (!root.value) return;\n width.value = root.value.clientWidth || width.value;\n if (typeof ResizeObserver !== 'undefined') {\n resize = new ResizeObserver(() => (width.value = root.value?.clientWidth || width.value));\n resize.observe(root.value);\n }\n});\nonBeforeUnmount(() => {\n resize?.disconnect();\n document.removeEventListener('pointerdown', onOutside, true);\n});\n\nconst startWidth = computed(() => Math.max(0, offset.value));\nconst showLabel = (w: number) => w >= 56;\n</script>\n\n<template>\n <div\n ref=\"root\"\n class=\"tx-swipe\"\n :class=\"{ 'tx-swipe--dragging': dragging, 'tx-swipe--armed-full': armed === 'full' || gone }\"\n @focusin=\"onFocusIn\"\n @focusout=\"onFocusOut\"\n >\n <div v-if=\"start\" class=\"tx-swipe__start\" data-side=\"start\" :style=\"{ width: `${startWidth}px` }\">\n <button\n type=\"button\"\n class=\"tx-swipe__action tx-swipe__action--start\"\n :class=\"[toneClass(start.tone ?? 'neutral'), { 'tx-swipe__action--armed': armed === 'start' }]\"\n :aria-label=\"start.label\"\n @click=\"run(start)\"\n >\n <slot name=\"action\" :action=\"start\" :armed=\"armed === 'start'\" side=\"start\">\n <TaoIcon v-if=\"start.icon\" :name=\"start.icon\" :size=\"22\" />\n <span v-if=\"showLabel(startWidth)\" class=\"tx-swipe__label\">{{ start.label }}</span>\n </slot>\n </button>\n </div>\n\n <div v-if=\"end.length\" class=\"tx-swipe__end\" data-side=\"end\">\n <button\n v-for=\"(action, i) in end\"\n :key=\"action.id\"\n type=\"button\"\n class=\"tx-swipe__action\"\n :class=\"[toneClass(action.tone ?? 'neutral'), { 'tx-swipe__action--armed': i === end.length - 1 && (armed === 'full' || gone) }]\"\n :style=\"{ width: `${widths[i]}px`, opacity: Math.min(1, (widths[i] ?? 0) / 28) }\"\n :aria-label=\"action.label\"\n @click=\"run(action)\"\n >\n <slot name=\"action\" :action=\"action\" :armed=\"i === end.length - 1 && armed === 'full'\" side=\"end\">\n <TaoIcon v-if=\"action.icon\" :name=\"action.icon\" :size=\"22\" />\n <span v-if=\"showLabel(widths[i] ?? 0)\" class=\"tx-swipe__label\">{{ action.label }}</span>\n </slot>\n </button>\n </div>\n\n <div\n class=\"tx-swipe__front\"\n :style=\"{ transform: `translate3d(${offset}px, 0, 0)` }\"\n @pointerdown=\"onDown\"\n @pointermove=\"onMove\"\n @pointerup=\"onUp\"\n @pointercancel=\"onCancel\"\n @click.capture=\"onClickCapture\"\n >\n <slot />\n </div>\n </div>\n</template>\n\n<style>\n.tx-swipe {\n --tx-swipe-gap: 6px;\n --tx-swipe-radius: var(--tao-radius-panel, 12px);\n position: relative;\n overflow: hidden;\n border-radius: var(--tx-swipe-radius);\n}\n\n.tx-swipe__front {\n position: relative;\n z-index: 1;\n /* the page keeps the vertical scroll, the tracker takes the sideways pull / вертикаль — странице, вбок — трекеру */\n touch-action: pan-y;\n border-radius: inherit;\n background: var(--tao-color-surface-raised, #1f1f1f);\n transition: transform 0.22s ease;\n}\n\n.tx-swipe--dragging .tx-swipe__front {\n transition: none;\n}\n\n.tx-swipe__start,\n.tx-swipe__end {\n position: absolute;\n inset-block: 0;\n display: flex;\n gap: var(--tx-swipe-gap);\n}\n\n.tx-swipe__start {\n inset-inline-start: 0;\n padding-inline-end: var(--tx-swipe-gap);\n transition: width 0.22s ease;\n}\n\n.tx-swipe__end {\n inset-inline-end: 0;\n justify-content: flex-end;\n}\n\n.tx-swipe--dragging .tx-swipe__start {\n transition: none;\n}\n\n.tx-swipe__action {\n display: inline-flex;\n flex: none;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n gap: 4px;\n min-width: 0;\n height: 100%;\n padding: 0;\n overflow: hidden;\n border: 0;\n border-radius: var(--tx-swipe-radius);\n background: color-mix(in srgb, var(--tao-tone) 22%, var(--tao-color-surface-raised, #1f1f1f));\n color: var(--tao-tone-text);\n font: inherit;\n font-size: 13px;\n cursor: pointer;\n transition:\n width 0.15s ease,\n background-color 0.15s ease;\n}\n\n.tx-swipe--dragging .tx-swipe__end .tx-swipe__action {\n transition: background-color 0.15s ease;\n}\n\n/* the full swipe armed: the last action takes the row; the widths animate to it / длинный свайп взведён */\n.tx-swipe--armed-full .tx-swipe__end .tx-swipe__action {\n transition:\n width 0.15s ease,\n background-color 0.15s ease;\n}\n\n.tx-swipe__action--start {\n flex: 1;\n}\n\n.tx-swipe__action--armed {\n background: color-mix(in srgb, var(--tao-tone) 45%, var(--tao-color-surface-raised, #1f1f1f));\n color: var(--tao-color-text-strong);\n}\n\n.tx-swipe__action:focus-visible {\n outline: 2px solid var(--tao-color-accent);\n outline-offset: -2px;\n}\n\n.tx-swipe__label {\n max-width: 100%;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n}\n\n@media (prefers-reduced-motion: reduce) {\n .tx-swipe__front,\n .tx-swipe__start,\n .tx-swipe__action {\n transition: none;\n }\n}\n</style>\n","<script lang=\"ts\" setup>\nimport { TaoIcon, toneClass } from '@1337exp/taoui';\nimport { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue';\nimport { SwipeTracker, type Sample } from '../gestures';\nimport { armedAt, clampOffset, endOpenWidth, endWidths, startThreshold, swipeRowRelease, type SwipeRowAction, type SwipeRowGeometry } from './model';\n\n// A row of a list that a finger slides sideways, as in a mail app. To the start (right): one action behind it, run on\n// release past its threshold, and the row comes back (read / unread). To the end (left): the actions grow out and the\n// row stays open on them; pulled far, the last one takes the row and runs on release (delete). The gesture (a swipe or\n// a scroll, the release speed, where to rest) is TaoUX's gestures; the actions are TaoUI icons and tones.\n// Строка списка, которую палец сдвигает вбок, как в почте. Вправо: одно действие позади, выполняется при отпускании\n// дальше порога, строка возвращается (прочитано / не прочитано). Влево: действия вырастают, и строка остаётся открытой\n// на них; если тянуть далеко, последнее занимает строку и выполняется при отпускании (удалить).\nconst props = withDefaults(\n defineProps<{\n /** The action behind the row on a pull to the start. / Действие позади строки при свайпе вправо. */\n start?: SwipeRowAction;\n /** The actions on a pull to the end, in order; the last one is the full swipe. / Действия при свайпе влево; последнее — длинный свайп. */\n end?: SwipeRowAction[];\n /** The width of each end action when the row is open, px. / Ширина каждого действия справа в открытой строке. */\n actionWidth?: number;\n /** Pulling far to the end runs the last action. / Длинный свайп влево выполняет последнее действие. */\n fullSwipe?: boolean;\n /** A mouse can drag it too (a touch screen always can). / Тянуть можно и мышью (палец может всегда). */\n mouse?: boolean;\n disabled?: boolean;\n }>(),\n { start: undefined, end: () => [], actionWidth: 76, fullSwipe: true, mouse: false, disabled: false },\n);\n\nconst emit = defineEmits<{\n /** An action was chosen: by a button, a pull past the threshold, or the full swipe. / Выбрано действие. */\n action: [id: string];\n}>();\n\n/** The end actions are shown. / Действия справа открыты. */\nconst open = defineModel<boolean>('open', { default: false });\n\ndefineSlots<{\n default?(): unknown;\n /** Your own face of an action. / Свой вид действия. */\n action?(props: { action: SwipeRowAction; armed: boolean; side: 'start' | 'end' }): unknown;\n}>();\n\nconst root = ref<HTMLElement | null>(null);\nconst width = ref(320);\nconst dragging = ref(false);\nconst drag = ref(0);\n// a moment after a full swipe: the row stays off to the side while the app removes it\n// миг после длинного свайпа: строка остаётся сдвинутой, пока приложение её убирает\nconst gone = ref(false);\nconst startShown = ref(false);\n\nconst geometry = computed<SwipeRowGeometry>(() => ({\n width: width.value,\n actionWidth: props.actionWidth,\n endCount: props.end.length,\n hasStart: Boolean(props.start),\n fullSwipe: props.fullSwipe,\n}));\n\nconst rest = computed(() => {\n if (gone.value) return -width.value;\n if (startShown.value) return startThreshold(geometry.value);\n return open.value ? -endOpenWidth(geometry.value) : 0;\n});\nconst offset = computed(() => (dragging.value ? drag.value : rest.value));\nconst armed = computed(() => (dragging.value ? armedAt(drag.value, geometry.value) : null));\nconst widths = computed(() => endWidths(Math.max(0, -offset.value), geometry.value, armed.value === 'full' || gone.value));\nconst lastEnd = computed(() => props.end[props.end.length - 1]);\n\n// a short buzz where the phone can, when an action becomes armed / короткая вибрация там, где телефон умеет\nwatch(armed, (next) => {\n if (next && typeof navigator !== 'undefined') navigator.vibrate?.(8);\n});\n\n//---]>\n// the gesture / жест\n\nconst tracker = new SwipeTracker('x');\nlet pointerId: number | null = null;\nlet swiped = false;\nconst sample = (e: PointerEvent): Sample => ({ x: e.clientX, y: e.clientY, t: e.timeStamp });\n\nfunction onDown(e: PointerEvent) {\n if (props.disabled || pointerId !== null || (e.pointerType === 'mouse' && (!props.mouse || e.button !== 0))) return;\n pointerId = e.pointerId;\n swiped = false;\n startShown.value = false;\n tracker.down(sample(e), rest.value);\n}\n\nfunction onMove(e: PointerEvent) {\n if (e.pointerId !== pointerId) return;\n const step = tracker.move(sample(e));\n if (step.intent !== 'swipe') return;\n if (!dragging.value) {\n dragging.value = true;\n try {\n (e.currentTarget as HTMLElement).setPointerCapture(e.pointerId);\n } catch {\n /* a pointer the browser does not know / неизвестный браузеру указатель */\n }\n }\n swiped = true;\n drag.value = clampOffset(step.offset, geometry.value);\n}\n\nfunction onUp(e: PointerEvent) {\n if (e.pointerId !== pointerId) return;\n const release = tracker.up(sample(e));\n pointerId = null;\n if (!release) {\n dragging.value = false;\n return;\n }\n const outcome = swipeRowRelease(release, geometry.value);\n dragging.value = false;\n if (outcome.kind === 'start' && props.start) {\n open.value = false;\n emit('action', props.start.id);\n } else if (outcome.kind === 'full' && lastEnd.value) {\n gone.value = true;\n emit('action', lastEnd.value.id);\n // the app removes the row; if it keeps it (an archive that failed), it comes back\n // приложение убирает строку; если оставит, она вернётся\n setTimeout(() => {\n gone.value = false;\n open.value = false;\n }, 400);\n } else if (outcome.kind === 'rest') {\n open.value = outcome.open;\n }\n}\n\nfunction onCancel(e: PointerEvent) {\n if (e.pointerId !== pointerId) return;\n tracker.cancel();\n pointerId = null;\n dragging.value = false;\n}\n\n// the end of a swipe also fires a click on the row: it must not open the item\n// конец свайпа даёт и click по строке: он не должен открывать элемент\nfunction onClickCapture(e: MouseEvent) {\n if (swiped) {\n e.stopPropagation();\n e.preventDefault();\n swiped = false;\n }\n}\n\nfunction run(action: SwipeRowAction) {\n open.value = false;\n startShown.value = false;\n emit('action', action.id);\n}\n\n//---]>\n// the keyboard: an action button that gets the focus shows its side\n// клавиатура: кнопка действия, получившая фокус, показывает свою сторону\n\nfunction onFocusIn(e: FocusEvent) {\n const side = (e.target as HTMLElement).closest<HTMLElement>('[data-side]')?.dataset.side;\n if (side === 'end') open.value = true;\n if (side === 'start') startShown.value = true;\n}\n\nfunction onFocusOut(e: FocusEvent) {\n if (root.value?.contains(e.relatedTarget as Node | null)) return;\n startShown.value = false;\n open.value = false;\n}\n\n// an open row closes on a touch outside it / открытая строка закрывается касанием вне её\nfunction onOutside(e: PointerEvent) {\n if (!root.value?.contains(e.target as Node)) open.value = false;\n}\nwatch(open, (isOpen) => {\n if (isOpen) document.addEventListener('pointerdown', onOutside, true);\n else document.removeEventListener('pointerdown', onOutside, true);\n});\n\nlet resize: ResizeObserver | undefined;\nonMounted(() => {\n if (!root.value) return;\n width.value = root.value.clientWidth || width.value;\n if (typeof ResizeObserver !== 'undefined') {\n resize = new ResizeObserver(() => (width.value = root.value?.clientWidth || width.value));\n resize.observe(root.value);\n }\n});\nonBeforeUnmount(() => {\n resize?.disconnect();\n document.removeEventListener('pointerdown', onOutside, true);\n});\n\nconst startWidth = computed(() => Math.max(0, offset.value));\nconst showLabel = (w: number) => w >= 56;\n</script>\n\n<template>\n <div\n ref=\"root\"\n class=\"tx-swipe\"\n :class=\"{ 'tx-swipe--dragging': dragging, 'tx-swipe--armed-full': armed === 'full' || gone }\"\n @focusin=\"onFocusIn\"\n @focusout=\"onFocusOut\"\n >\n <div v-if=\"start\" class=\"tx-swipe__start\" data-side=\"start\" :style=\"{ width: `${startWidth}px` }\">\n <button\n type=\"button\"\n class=\"tx-swipe__action tx-swipe__action--start\"\n :class=\"[toneClass(start.tone ?? 'neutral'), { 'tx-swipe__action--armed': armed === 'start' }]\"\n :aria-label=\"start.label\"\n @click=\"run(start)\"\n >\n <slot name=\"action\" :action=\"start\" :armed=\"armed === 'start'\" side=\"start\">\n <TaoIcon v-if=\"start.icon\" :name=\"start.icon\" :size=\"22\" />\n <span v-if=\"showLabel(startWidth)\" class=\"tx-swipe__label\">{{ start.label }}</span>\n </slot>\n </button>\n </div>\n\n <div v-if=\"end.length\" class=\"tx-swipe__end\" data-side=\"end\">\n <button\n v-for=\"(action, i) in end\"\n :key=\"action.id\"\n type=\"button\"\n class=\"tx-swipe__action\"\n :class=\"[toneClass(action.tone ?? 'neutral'), { 'tx-swipe__action--armed': i === end.length - 1 && (armed === 'full' || gone) }]\"\n :style=\"{ width: `${widths[i]}px`, opacity: Math.min(1, (widths[i] ?? 0) / 28) }\"\n :aria-label=\"action.label\"\n @click=\"run(action)\"\n >\n <slot name=\"action\" :action=\"action\" :armed=\"i === end.length - 1 && armed === 'full'\" side=\"end\">\n <TaoIcon v-if=\"action.icon\" :name=\"action.icon\" :size=\"22\" />\n <span v-if=\"showLabel(widths[i] ?? 0)\" class=\"tx-swipe__label\">{{ action.label }}</span>\n </slot>\n </button>\n </div>\n\n <div\n class=\"tx-swipe__front\"\n :style=\"{ transform: `translate3d(${offset}px, 0, 0)` }\"\n @pointerdown=\"onDown\"\n @pointermove=\"onMove\"\n @pointerup=\"onUp\"\n @pointercancel=\"onCancel\"\n @click.capture=\"onClickCapture\"\n >\n <slot />\n </div>\n </div>\n</template>\n\n<style>\n.tx-swipe {\n --tx-swipe-gap: 6px;\n --tx-swipe-radius: var(--tao-radius-panel, 12px);\n position: relative;\n overflow: hidden;\n border-radius: var(--tx-swipe-radius);\n}\n\n.tx-swipe__front {\n position: relative;\n z-index: 1;\n /* the page keeps the vertical scroll, the tracker takes the sideways pull / вертикаль — странице, вбок — трекеру */\n touch-action: pan-y;\n border-radius: inherit;\n background: var(--tao-color-surface-raised, #1f1f1f);\n transition: transform 0.22s ease;\n}\n\n.tx-swipe--dragging .tx-swipe__front {\n transition: none;\n}\n\n.tx-swipe__start,\n.tx-swipe__end {\n position: absolute;\n inset-block: 0;\n display: flex;\n gap: var(--tx-swipe-gap);\n}\n\n.tx-swipe__start {\n inset-inline-start: 0;\n padding-inline-end: var(--tx-swipe-gap);\n transition: width 0.22s ease;\n}\n\n.tx-swipe__end {\n inset-inline-end: 0;\n justify-content: flex-end;\n}\n\n.tx-swipe--dragging .tx-swipe__start {\n transition: none;\n}\n\n.tx-swipe__action {\n display: inline-flex;\n flex: none;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n gap: 4px;\n min-width: 0;\n height: 100%;\n padding: 0;\n overflow: hidden;\n border: 0;\n border-radius: var(--tx-swipe-radius);\n background: color-mix(in srgb, var(--tao-tone) 22%, var(--tao-color-surface-raised, #1f1f1f));\n color: var(--tao-tone-text);\n font: inherit;\n font-size: 13px;\n cursor: pointer;\n transition:\n width 0.15s ease,\n background-color 0.15s ease;\n}\n\n.tx-swipe--dragging .tx-swipe__end .tx-swipe__action {\n transition: background-color 0.15s ease;\n}\n\n/* the full swipe armed: the last action takes the row; the widths animate to it / длинный свайп взведён */\n.tx-swipe--armed-full .tx-swipe__end .tx-swipe__action {\n transition:\n width 0.15s ease,\n background-color 0.15s ease;\n}\n\n.tx-swipe__action--start {\n flex: 1;\n}\n\n.tx-swipe__action--armed {\n background: color-mix(in srgb, var(--tao-tone) 45%, var(--tao-color-surface-raised, #1f1f1f));\n color: var(--tao-color-text-strong);\n}\n\n.tx-swipe__action:focus-visible {\n outline: 2px solid var(--tao-color-accent);\n outline-offset: -2px;\n}\n\n.tx-swipe__label {\n max-width: 100%;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n}\n\n@media (prefers-reduced-motion: reduce) {\n .tx-swipe__front,\n .tx-swipe__start,\n .tx-swipe__action {\n transition: none;\n }\n}\n</style>\n"],"mappings":";;;;;AA+BA,IAAa,mBAAmB;;AAEhC,IAAa,qBAAqB;AAElC,IAAa,kBAAkB,MAAwB,KAAK,IAAA,IAAwB,EAAE,QAAQ,CAAC;AAC/F,IAAa,gBAAgB,MAAwB,EAAE,cAAc,EAAE;AACvE,IAAa,iBAAiB,MAAwB,KAAK,IAAI,aAAa,CAAC,IAAI,IAAI,EAAE,QAAQ,gBAAgB;;;;;AAM/G,SAAgB,QAAQ,QAAgB,GAA8C;CAClF,IAAI,SAAS,KAAK,EAAE,YAAY,UAAU,eAAe,CAAC,GAAG,OAAO;CACpE,IAAI,SAAS,KAAK,EAAE,aAAa,EAAE,WAAW,KAAK,CAAC,UAAU,cAAc,CAAC,GAAG,OAAO;CACvF,OAAO;AACX;;AAGA,SAAgB,YAAY,QAAgB,GAA6B;CACrE,MAAM,QAAQ,EAAE,WAAW,EAAE,QAAQ;CACrC,MAAM,OAAO,EAAE,aAAa,IAAI,IAAI,EAAE,YAAY,CAAC,EAAE,QAAQ,CAAC,aAAa,CAAC,IAAI;CAChF,OAAO,KAAK,IAAI,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AACjD;;;;;;;;;AAeA,SAAgB,gBAAgB,SAAuB,GAAsC;CACzF,MAAM,SAAS,YAAY,QAAQ,QAAQ,CAAC;CAC5C,MAAM,QAAQ,QAAQ,QAAQ,CAAC;CAC/B,IAAI,OAAO,OAAO,EAAE,MAAM,MAAM;CAChC,IAAI,SAAS,KAAK,EAAE,YAAY,QAAQ,YAAA,MAAqC,UAAU,eAAe,CAAC,IAAI,GACvG,OAAO,EAAE,MAAM,QAAQ;CAE3B,IAAI,EAAE,aAAa,GAAG,OAAO;EAAE,MAAM;EAAQ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A,WAAA,eAA8B,OAAA,MAAM,WAAA,CAAA;KACzC,eAAa;KACb,eAAa;KACb,aAAW;KACX,iBAAe;KACA;I,IAEhBG,WAAQ,KAAA,QAAA,SAAA,C"}
1
+ {"version":3,"file":"swiperow.js","names":["_useModel","_openBlock","_createElementBlock","_normalizeClass","_normalizeStyle","_createElementVNode","_unref","_renderSlot","_createBlock","_createCommentVNode","_toDisplayString","_Fragment","_renderList","_sfc_main"],"sources":["../src/swiperow/model.ts","../src/swiperow/TaoxSwipeRow.vue","../src/swiperow/TaoxSwipeRow.vue"],"sourcesContent":["import { settleOpen, SWIPE_FLING_PX_PER_MS, type SwipeRelease } from '../gestures';\n\n/**\n * An action of a swipe row. `tone` is a TaoUI tone (`neutral`, `danger`, `success`…), `icon` a TaoIcon name.\n * Действие свайп-строки. `tone` — тон TaoUI, `icon` — имя TaoIcon.\n */\nexport interface SwipeRowAction {\n id: string;\n label: string;\n icon?: string;\n tone?: 'accent' | 'neutral' | 'success' | 'danger' | 'warning' | 'info';\n}\n\n/**\n * The thresholds of the row, px or a share of its width.\n * Пороги строки, px или доля её ширины.\n */\nexport interface SwipeRowGeometry {\n /** The row width. / Ширина строки. */\n width: number;\n /** How wide each end action stands when the row is open. / Ширина каждого действия справа в открытой строке. */\n actionWidth: number;\n /** How many end actions. / Сколько действий справа. */\n endCount: number;\n /** Whether there is a start action. / Есть ли действие слева. */\n hasStart: boolean;\n /** Whether pulling far runs the last end action by itself. / Выполняет ли длинный свайп последнее действие сам. */\n fullSwipe: boolean;\n}\n\n/** Past this share of the width a pull to the end runs the last action. / После этой доли ширины длинный свайп выполняет последнее действие. */\nexport const FULL_SWIPE_RATIO = 0.6;\n/** A pull to the start runs its action past this many px (or a third of a narrow row). / Свайп вправо выполняет действие после стольких px. */\nexport const START_THRESHOLD_PX = 96;\n\nexport const startThreshold = (g: SwipeRowGeometry) => Math.min(START_THRESHOLD_PX, g.width / 3);\nexport const endOpenWidth = (g: SwipeRowGeometry) => g.actionWidth * g.endCount;\nexport const fullThreshold = (g: SwipeRowGeometry) => Math.max(endOpenWidth(g) + 24, g.width * FULL_SWIPE_RATIO);\n\n/**\n * Whether the row, at this offset, is past the point where releasing runs an action: `start`, `full` or null.\n * Пройдена ли при этом сдвиге точка, после которой отпускание выполняет действие: `start`, `full` или null.\n */\nexport function armedAt(offset: number, g: SwipeRowGeometry): 'start' | 'full' | null {\n if (offset > 0 && g.hasStart && offset >= startThreshold(g)) return 'start';\n if (offset < 0 && g.fullSwipe && g.endCount > 0 && -offset >= fullThreshold(g)) return 'full';\n return null;\n}\n\n/** How far the row may move: no further than there is something behind it. / Насколько строка может уехать. */\nexport function clampOffset(offset: number, g: SwipeRowGeometry): number {\n const right = g.hasStart ? g.width : 0;\n const left = g.endCount === 0 ? 0 : g.fullSwipe ? -g.width : -endOpenWidth(g) * 1.5;\n return Math.min(right, Math.max(left, offset));\n}\n\nexport type SwipeRowOutcome =\n | { kind: 'rest'; open: boolean } // the row comes to rest: open (the end actions shown) or closed\n | { kind: 'start' } // the start action runs, the row goes back\n | { kind: 'full' }; // the last end action runs\n\n/**\n * What a release does. A pull to the start past its threshold (or flung that way past half of it) runs the start\n * action; a pull to the end past the full threshold runs the last end action; otherwise the row rests open or closed,\n * a fling going on in its direction (`settleOpen`).\n * Что делает отпускание. Свайп вправо дальше порога (или брошенный туда дальше его половины) выполняет действие слева;\n * влево дальше полного порога — последнее действие справа; иначе строка встаёт открытой или закрытой, бросок\n * продолжается в своём направлении.\n */\nexport function swipeRowRelease(release: SwipeRelease, g: SwipeRowGeometry): SwipeRowOutcome {\n const offset = clampOffset(release.offset, g);\n const armed = armedAt(offset, g);\n if (armed) return { kind: armed };\n if (offset > 0 && g.hasStart && release.velocity >= SWIPE_FLING_PX_PER_MS && offset >= startThreshold(g) / 2) {\n return { kind: 'start' };\n }\n if (g.endCount === 0) return { kind: 'rest', open: false };\n const rest = settleOpen({ offset: Math.min(0, offset), velocity: release.velocity }, { end: endOpenWidth(g) });\n return { kind: 'rest', open: rest < 0 };\n}\n\n/** The narrowest an action between the row and the last one gets: still a visible link. / Самое узкое промежуточное действие. */\nexport const SWIPE_SLIVER_PX = 32;\n\n/**\n * The widths of the end actions at a pull of `drag` px (≥ 0), one continuous function, so nothing jumps. Up to the\n * open width they share the space evenly and grow to their width. Past it the actions between the row and the last one\n * stop growing and shrink back, smoothly, to slivers (`SWIPE_SLIVER_PX`) a little past the full-swipe threshold, and the last one\n * takes what they give up; further on they stay slivers, so a pull back opens them out again the same way.\n * `armed` is no longer used (the widths depend on the pull alone); it stays for the 0.5.0 signature.\n * Ширины действий справа при протяжке на `drag` px — одна непрерывная функция, поэтому ничего не прыгает. До открытой\n * ширины они делят место поровну и растут до своей ширины. Дальше промежуточные перестают расти и плавно сжимаются до\n * полосок к порогу длинного свайпа, а последнее забирает отданное место; за порогом они остаются полосками, поэтому\n * при обратном движении так же плавно раскрываются. `armed` больше не нужен; оставлен ради подписи 0.5.0.\n */\nexport function endWidths(drag: number, g: SwipeRowGeometry, _armed?: boolean, gap = 6): number[] {\n const n = g.endCount;\n if (n === 0 || drag <= 0) return Array.from({ length: n }, () => 0);\n const room = Math.max(0, drag - gap * n);\n const open = endOpenWidth(g);\n if (n === 1) return [room];\n if (drag <= open) return Array.from({ length: n }, () => room / n);\n\n // the squeeze runs a little past the full threshold (a fifth of the row more), so on a phone it takes a long stretch\n // of the pull and reads as a slide, not a snap\n // сжатие идёт чуть дальше порога длинного свайпа (ещё пятая часть строки), поэтому на телефоне занимает длинный\n // отрезок протяжки и читается как плавный переход, а не рывок\n const end = Math.max(open + 1, Math.min(g.width * 0.9, fullThreshold(g) + g.width * 0.2));\n const t = Math.min(1, (drag - open) / (end - open));\n const widest = g.actionWidth - gap;\n const middle = Math.min(widest, Math.max(0, widest + (Math.min(SWIPE_SLIVER_PX, widest) - widest) * t));\n return Array.from({ length: n }, (_, i) => (i === n - 1 ? room - middle * (n - 1) : middle));\n}\n","<script lang=\"ts\" setup>\nimport { TaoIcon, toneClass } from '@1337exp/taoui';\nimport { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue';\nimport { listenFocusLoss, SwipeTracker, type Sample } from '../gestures';\nimport { armedAt, clampOffset, endOpenWidth, endWidths, startThreshold, swipeRowRelease, type SwipeRowAction, type SwipeRowGeometry } from './model';\n\n// A row of a list that a finger slides sideways, as in a mail app. To the start (right): one action behind it, run on\n// release past its threshold, and the row comes back (read / unread). To the end (left): the actions grow out and the\n// row stays open on them; pulled far, the last one takes the row and runs on release (delete). The gesture (a swipe or\n// a scroll, the release speed, where to rest) is TaoUX's gestures; the actions are TaoUI icons and tones.\n// Строка списка, которую палец сдвигает вбок, как в почте. Вправо: одно действие позади, выполняется при отпускании\n// дальше порога, строка возвращается (прочитано / не прочитано). Влево: действия вырастают, и строка остаётся открытой\n// на них; если тянуть далеко, последнее занимает строку и выполняется при отпускании (удалить).\nconst props = withDefaults(\n defineProps<{\n /** The action behind the row on a pull to the start. / Действие позади строки при свайпе вправо. */\n start?: SwipeRowAction;\n /** The actions on a pull to the end, in order; the last one is the full swipe. / Действия при свайпе влево; последнее — длинный свайп. */\n end?: SwipeRowAction[];\n /** The width of each end action when the row is open, px. / Ширина каждого действия справа в открытой строке. */\n actionWidth?: number;\n /** Pulling far to the end runs the last action. / Длинный свайп влево выполняет последнее действие. */\n fullSwipe?: boolean;\n /** A mouse can drag it too (a touch screen always can). / Тянуть можно и мышью (палец может всегда). */\n mouse?: boolean;\n disabled?: boolean;\n }>(),\n { start: undefined, end: () => [], actionWidth: 76, fullSwipe: true, mouse: false, disabled: false },\n);\n\nconst emit = defineEmits<{\n /** An action was chosen: by a button, a pull past the threshold, or the full swipe. / Выбрано действие. */\n action: [id: string];\n}>();\n\n/** The end actions are shown. / Действия справа открыты. */\nconst open = defineModel<boolean>('open', { default: false });\n\ndefineSlots<{\n default?(): unknown;\n /** Your own face of an action. / Свой вид действия. */\n action?(props: { action: SwipeRowAction; armed: boolean; side: 'start' | 'end'; width: number }): unknown;\n}>();\n\nconst root = ref<HTMLElement | null>(null);\nconst width = ref(320);\nconst dragging = ref(false);\nconst drag = ref(0);\n// a moment after a full swipe: the row stays off to the side while the app removes it\n// миг после длинного свайпа: строка остаётся сдвинутой, пока приложение её убирает\nconst gone = ref(false);\nconst startShown = ref(false);\n\nconst geometry = computed<SwipeRowGeometry>(() => ({\n width: width.value,\n actionWidth: props.actionWidth,\n endCount: props.end.length,\n hasStart: Boolean(props.start),\n fullSwipe: props.fullSwipe,\n}));\n\nconst rest = computed(() => {\n if (gone.value) return -width.value;\n if (startShown.value) return startThreshold(geometry.value);\n return open.value ? -endOpenWidth(geometry.value) : 0;\n});\nconst offset = computed(() => (dragging.value ? drag.value : rest.value));\nconst armed = computed(() => (dragging.value ? armedAt(drag.value, geometry.value) : null));\n// gone (the full swipe ran): the last action holds the whole row while the app removes it / последнее держит всю строку\nconst widths = computed(() => endWidths(gone.value ? width.value : Math.max(0, -offset.value), geometry.value));\nconst lastEnd = computed(() => props.end[props.end.length - 1]);\n\n// a short buzz where the phone can, when an action becomes armed / короткая вибрация там, где телефон умеет\nwatch(armed, (next) => {\n if (next && typeof navigator !== 'undefined') navigator.vibrate?.(8);\n});\n\n//---]>\n// the gesture / жест\n\nconst tracker = new SwipeTracker('x');\nlet pointerId: number | null = null;\nlet swiped = false;\nconst sample = (e: PointerEvent): Sample => ({ x: e.clientX, y: e.clientY, t: e.timeStamp });\n\n// the window lost the focus while the press was held (Alt-Tab, a screenshot): its pointerup may never come, so the row\n// lets go and settles where it rested, instead of staying stuck to a finger that is gone\n// окно потеряло фокус во время нажатия: pointerup может не прийти, поэтому строка отпускается и встаёт на место\nlet stopFocusLoss: (() => void) | undefined;\n\nfunction release() {\n stopFocusLoss?.();\n stopFocusLoss = undefined;\n pointerId = null;\n dragging.value = false;\n}\n\nfunction onDown(e: PointerEvent) {\n if (props.disabled || pointerId !== null || (e.pointerType === 'mouse' && (!props.mouse || e.button !== 0))) return;\n pointerId = e.pointerId;\n swiped = false;\n startShown.value = false;\n tracker.down(sample(e), rest.value);\n stopFocusLoss = listenFocusLoss(() => {\n tracker.cancel();\n release();\n });\n}\n\nfunction onMove(e: PointerEvent) {\n if (e.pointerId !== pointerId) return;\n const step = tracker.move(sample(e));\n if (step.intent !== 'swipe') return;\n if (!dragging.value) {\n dragging.value = true;\n try {\n (e.currentTarget as HTMLElement).setPointerCapture(e.pointerId);\n } catch {\n /* a pointer the browser does not know / неизвестный браузеру указатель */\n }\n }\n swiped = true;\n drag.value = clampOffset(step.offset, geometry.value);\n}\n\nfunction onUp(e: PointerEvent) {\n if (e.pointerId !== pointerId) return;\n const result = tracker.up(sample(e));\n release();\n if (!result) return;\n const outcome = swipeRowRelease(result, geometry.value);\n if (outcome.kind === 'start' && props.start) {\n open.value = false;\n emit('action', props.start.id);\n } else if (outcome.kind === 'full' && lastEnd.value) {\n gone.value = true;\n emit('action', lastEnd.value.id);\n // the app removes the row; if it keeps it (an archive that failed), it comes back\n // приложение убирает строку; если оставит, она вернётся\n setTimeout(() => {\n gone.value = false;\n open.value = false;\n }, 400);\n } else if (outcome.kind === 'rest') {\n open.value = outcome.open;\n }\n}\n\nfunction onCancel(e: PointerEvent) {\n if (e.pointerId !== pointerId) return;\n tracker.cancel();\n release();\n}\n\n// the end of a swipe also fires a click on the row: it must not open the item\n// конец свайпа даёт и click по строке: он не должен открывать элемент\nfunction onClickCapture(e: MouseEvent) {\n if (swiped) {\n e.stopPropagation();\n e.preventDefault();\n swiped = false;\n }\n}\n\nfunction run(action: SwipeRowAction) {\n open.value = false;\n startShown.value = false;\n emit('action', action.id);\n}\n\n//---]>\n// the keyboard: an action button that gets the focus shows its side\n// клавиатура: кнопка действия, получившая фокус, показывает свою сторону\n\nfunction onFocusIn(e: FocusEvent) {\n const side = (e.target as HTMLElement).closest<HTMLElement>('[data-side]')?.dataset.side;\n if (side === 'end') open.value = true;\n if (side === 'start') startShown.value = true;\n}\n\nfunction onFocusOut(e: FocusEvent) {\n if (root.value?.contains(e.relatedTarget as Node | null)) return;\n startShown.value = false;\n open.value = false;\n}\n\n// an open row closes on a touch outside it / открытая строка закрывается касанием вне её\nfunction onOutside(e: PointerEvent) {\n if (!root.value?.contains(e.target as Node)) open.value = false;\n}\nwatch(open, (isOpen) => {\n if (isOpen) document.addEventListener('pointerdown', onOutside, true);\n else document.removeEventListener('pointerdown', onOutside, true);\n});\n\nlet resize: ResizeObserver | undefined;\nonMounted(() => {\n if (!root.value) return;\n width.value = root.value.clientWidth || width.value;\n if (typeof ResizeObserver !== 'undefined') {\n resize = new ResizeObserver(() => (width.value = root.value?.clientWidth || width.value));\n resize.observe(root.value);\n }\n});\nonBeforeUnmount(() => {\n stopFocusLoss?.();\n resize?.disconnect();\n document.removeEventListener('pointerdown', onOutside, true);\n});\n\nconst startWidth = computed(() => Math.max(0, offset.value));\n\n/*\n * The icon and the label always stand where they end up, so nothing pops in and the heights never jump; only their\n * opacity follows the width of their block. The icon comes first, the label later, when the block is wide enough to\n * hold it.\n * Иконка и подпись всегда стоят на своих итоговых местах, поэтому ничего не выскакивает и высоты не прыгают; от ширины\n * блока зависит только их прозрачность. Иконка проявляется раньше, подпись позже, когда блок уже вмещает её.\n */\nconst fade = (width: number, from: number, span: number) => Math.min(1, Math.max(0, (width - from) / span));\nconst endIcon = (w: number) => fade(w, 22, 20);\nconst endLabel = (w: number) => fade(w, 50, 18);\nconst startIcon = (w: number) => fade(w, 36, 24);\nconst startLabel = (w: number) => fade(w, 84, 28);\n</script>\n\n<template>\n <div\n ref=\"root\"\n class=\"tx-swipe\"\n :class=\"{ 'tx-swipe--dragging': dragging, 'tx-swipe--armed-full': armed === 'full' || gone }\"\n @focusin=\"onFocusIn\"\n @focusout=\"onFocusOut\"\n >\n <div v-if=\"start\" class=\"tx-swipe__start\" data-side=\"start\" :style=\"{ width: `${startWidth}px` }\">\n <button\n type=\"button\"\n class=\"tx-swipe__action tx-swipe__action--start\"\n :class=\"[toneClass(start.tone ?? 'neutral'), { 'tx-swipe__action--armed': armed === 'start' }]\"\n :aria-label=\"start.label\"\n @click=\"run(start)\"\n >\n <slot name=\"action\" :action=\"start\" :armed=\"armed === 'start'\" side=\"start\" :width=\"startWidth\">\n <TaoIcon v-if=\"start.icon\" :name=\"start.icon\" :size=\"20\" :style=\"{ opacity: startIcon(startWidth) }\" />\n <span class=\"tx-swipe__label\" :style=\"{ opacity: startLabel(startWidth) }\">{{ start.label }}</span>\n </slot>\n </button>\n </div>\n\n <div v-if=\"end.length\" class=\"tx-swipe__end\" data-side=\"end\">\n <button\n v-for=\"(action, i) in end\"\n :key=\"action.id\"\n type=\"button\"\n class=\"tx-swipe__action\"\n :class=\"[toneClass(action.tone ?? 'neutral'), { 'tx-swipe__action--armed': i === end.length - 1 && (armed === 'full' || gone) }]\"\n :style=\"{ width: `${widths[i]}px` }\"\n :aria-label=\"action.label\"\n @click=\"run(action)\"\n >\n <slot name=\"action\" :action=\"action\" :armed=\"i === end.length - 1 && armed === 'full'\" side=\"end\" :width=\"widths[i] ?? 0\">\n <TaoIcon v-if=\"action.icon\" :name=\"action.icon\" :size=\"20\" :style=\"{ opacity: endIcon(widths[i] ?? 0) }\" />\n <span class=\"tx-swipe__label\" :style=\"{ opacity: endLabel(widths[i] ?? 0) }\">{{ action.label }}</span>\n </slot>\n </button>\n </div>\n\n <div\n class=\"tx-swipe__front\"\n :style=\"{ transform: `translate3d(${offset}px, 0, 0)` }\"\n @pointerdown=\"onDown\"\n @pointermove=\"onMove\"\n @pointerup=\"onUp\"\n @pointercancel=\"onCancel\"\n @click.capture=\"onClickCapture\"\n >\n <slot />\n </div>\n </div>\n</template>\n\n<style>\n.tx-swipe {\n --tx-swipe-gap: 6px;\n --tx-swipe-radius: var(--tao-radius-panel, 12px);\n position: relative;\n overflow: hidden;\n border-radius: var(--tx-swipe-radius);\n}\n\n.tx-swipe__front {\n position: relative;\n z-index: 1;\n /* the page keeps the vertical scroll, the tracker takes the sideways pull / вертикаль — странице, вбок — трекеру */\n touch-action: pan-y;\n border-radius: inherit;\n background: var(--tao-color-surface-raised, #1f1f1f);\n transition: transform 0.22s ease;\n}\n\n.tx-swipe--dragging .tx-swipe__front {\n transition: none;\n}\n\n.tx-swipe__start,\n.tx-swipe__end {\n position: absolute;\n inset-block: 0;\n display: flex;\n gap: var(--tx-swipe-gap);\n}\n\n/* clipped, with the gap as the button's margin: at width 0 nothing of it is left, while the keyboard can still reach it\n (a padding kept a 6px box, and the button showed at the start edge of a row pulled the other way)\n с обрезкой, а зазор — поле кнопки: при ширине 0 от неё ничего не остаётся, а клавиатура всё равно до неё доходит\n (padding оставлял коробку в 6px, и кнопка виднелась у начального края строки, которую тянули в другую сторону) */\n.tx-swipe__start {\n inset-inline-start: 0;\n overflow: hidden;\n transition: width 0.22s ease;\n}\n\n.tx-swipe__end {\n inset-inline-end: 0;\n justify-content: flex-end;\n}\n\n.tx-swipe--dragging .tx-swipe__start {\n transition: none;\n}\n\n.tx-swipe__action {\n display: inline-flex;\n flex: none;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n /* the icon and the label read as one: a small gap, not pressed to the edges of a short row\n иконка и подпись читаются вместе: небольшой зазор, а не прижаты к краям невысокой строки */\n gap: 2px;\n min-width: 0;\n height: 100%;\n padding: 0;\n overflow: hidden;\n border: 0;\n border-radius: var(--tx-swipe-radius);\n background: color-mix(in srgb, var(--tao-tone) 22%, var(--tao-color-surface-raised, #1f1f1f));\n color: var(--tao-tone-text);\n font: inherit;\n font-size: 13px;\n cursor: pointer;\n transition:\n width 0.15s ease,\n background-color 0.15s ease;\n}\n\n/* under the finger the actions follow the row in the same frame: no width easing, or they trail behind it\n под пальцем действия идут за строкой в том же кадре: без сглаживания ширины, иначе они отстают */\n.tx-swipe--dragging .tx-swipe__end .tx-swipe__action {\n transition: background-color 0.15s ease;\n}\n\n/* the start action is one line, from the start edge: the icon at a fixed place, the label after it\n действие слева — одна строка от начального края: иконка на постоянном месте, подпись за ней */\n.tx-swipe__action--start {\n flex: 1;\n flex-direction: row;\n justify-content: flex-start;\n gap: 10px;\n min-width: 0;\n margin-inline-end: var(--tx-swipe-gap);\n padding-inline-start: 22px;\n}\n\n.tx-swipe__action--armed {\n background: color-mix(in srgb, var(--tao-tone) 45%, var(--tao-color-surface-raised, #1f1f1f));\n color: var(--tao-color-text-strong);\n}\n\n.tx-swipe__action:focus-visible {\n outline: 2px solid var(--tao-color-accent);\n outline-offset: -2px;\n}\n\n/* never squeezed or cut with «…»: a label wider than its block stays whole and centred, the block clips it, and it is\n still transparent then; so the line never changes as the block grows\n подпись не сжимается и не обрезается «…»: шире блока — остаётся целой и по центру, блок её обрезает, а она в это\n время ещё прозрачна; поэтому строка не меняется, пока блок растёт */\n.tx-swipe__label {\n flex: none;\n white-space: nowrap;\n line-height: 1.2;\n}\n\n.tx-swipe__action :is(svg, .tao-icon) {\n flex: none;\n}\n\n/* a short fade, so a row settling by itself shows them softly too; under the finger none\n короткий переход: строка, доезжающая сама, тоже их проявляет мягко; под пальцем без него */\n.tx-swipe__label,\n.tx-swipe__action .tao-icon {\n transition: opacity 0.12s ease;\n}\n\n.tx-swipe--dragging .tx-swipe__label,\n.tx-swipe--dragging .tx-swipe__action .tao-icon {\n transition: none;\n}\n\n@media (prefers-reduced-motion: reduce) {\n .tx-swipe__front,\n .tx-swipe__start,\n .tx-swipe__action,\n .tx-swipe__label,\n .tx-swipe__action .tao-icon {\n transition: none;\n }\n}\n</style>\n","<script lang=\"ts\" setup>\nimport { TaoIcon, toneClass } from '@1337exp/taoui';\nimport { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue';\nimport { listenFocusLoss, SwipeTracker, type Sample } from '../gestures';\nimport { armedAt, clampOffset, endOpenWidth, endWidths, startThreshold, swipeRowRelease, type SwipeRowAction, type SwipeRowGeometry } from './model';\n\n// A row of a list that a finger slides sideways, as in a mail app. To the start (right): one action behind it, run on\n// release past its threshold, and the row comes back (read / unread). To the end (left): the actions grow out and the\n// row stays open on them; pulled far, the last one takes the row and runs on release (delete). The gesture (a swipe or\n// a scroll, the release speed, where to rest) is TaoUX's gestures; the actions are TaoUI icons and tones.\n// Строка списка, которую палец сдвигает вбок, как в почте. Вправо: одно действие позади, выполняется при отпускании\n// дальше порога, строка возвращается (прочитано / не прочитано). Влево: действия вырастают, и строка остаётся открытой\n// на них; если тянуть далеко, последнее занимает строку и выполняется при отпускании (удалить).\nconst props = withDefaults(\n defineProps<{\n /** The action behind the row on a pull to the start. / Действие позади строки при свайпе вправо. */\n start?: SwipeRowAction;\n /** The actions on a pull to the end, in order; the last one is the full swipe. / Действия при свайпе влево; последнее — длинный свайп. */\n end?: SwipeRowAction[];\n /** The width of each end action when the row is open, px. / Ширина каждого действия справа в открытой строке. */\n actionWidth?: number;\n /** Pulling far to the end runs the last action. / Длинный свайп влево выполняет последнее действие. */\n fullSwipe?: boolean;\n /** A mouse can drag it too (a touch screen always can). / Тянуть можно и мышью (палец может всегда). */\n mouse?: boolean;\n disabled?: boolean;\n }>(),\n { start: undefined, end: () => [], actionWidth: 76, fullSwipe: true, mouse: false, disabled: false },\n);\n\nconst emit = defineEmits<{\n /** An action was chosen: by a button, a pull past the threshold, or the full swipe. / Выбрано действие. */\n action: [id: string];\n}>();\n\n/** The end actions are shown. / Действия справа открыты. */\nconst open = defineModel<boolean>('open', { default: false });\n\ndefineSlots<{\n default?(): unknown;\n /** Your own face of an action. / Свой вид действия. */\n action?(props: { action: SwipeRowAction; armed: boolean; side: 'start' | 'end'; width: number }): unknown;\n}>();\n\nconst root = ref<HTMLElement | null>(null);\nconst width = ref(320);\nconst dragging = ref(false);\nconst drag = ref(0);\n// a moment after a full swipe: the row stays off to the side while the app removes it\n// миг после длинного свайпа: строка остаётся сдвинутой, пока приложение её убирает\nconst gone = ref(false);\nconst startShown = ref(false);\n\nconst geometry = computed<SwipeRowGeometry>(() => ({\n width: width.value,\n actionWidth: props.actionWidth,\n endCount: props.end.length,\n hasStart: Boolean(props.start),\n fullSwipe: props.fullSwipe,\n}));\n\nconst rest = computed(() => {\n if (gone.value) return -width.value;\n if (startShown.value) return startThreshold(geometry.value);\n return open.value ? -endOpenWidth(geometry.value) : 0;\n});\nconst offset = computed(() => (dragging.value ? drag.value : rest.value));\nconst armed = computed(() => (dragging.value ? armedAt(drag.value, geometry.value) : null));\n// gone (the full swipe ran): the last action holds the whole row while the app removes it / последнее держит всю строку\nconst widths = computed(() => endWidths(gone.value ? width.value : Math.max(0, -offset.value), geometry.value));\nconst lastEnd = computed(() => props.end[props.end.length - 1]);\n\n// a short buzz where the phone can, when an action becomes armed / короткая вибрация там, где телефон умеет\nwatch(armed, (next) => {\n if (next && typeof navigator !== 'undefined') navigator.vibrate?.(8);\n});\n\n//---]>\n// the gesture / жест\n\nconst tracker = new SwipeTracker('x');\nlet pointerId: number | null = null;\nlet swiped = false;\nconst sample = (e: PointerEvent): Sample => ({ x: e.clientX, y: e.clientY, t: e.timeStamp });\n\n// the window lost the focus while the press was held (Alt-Tab, a screenshot): its pointerup may never come, so the row\n// lets go and settles where it rested, instead of staying stuck to a finger that is gone\n// окно потеряло фокус во время нажатия: pointerup может не прийти, поэтому строка отпускается и встаёт на место\nlet stopFocusLoss: (() => void) | undefined;\n\nfunction release() {\n stopFocusLoss?.();\n stopFocusLoss = undefined;\n pointerId = null;\n dragging.value = false;\n}\n\nfunction onDown(e: PointerEvent) {\n if (props.disabled || pointerId !== null || (e.pointerType === 'mouse' && (!props.mouse || e.button !== 0))) return;\n pointerId = e.pointerId;\n swiped = false;\n startShown.value = false;\n tracker.down(sample(e), rest.value);\n stopFocusLoss = listenFocusLoss(() => {\n tracker.cancel();\n release();\n });\n}\n\nfunction onMove(e: PointerEvent) {\n if (e.pointerId !== pointerId) return;\n const step = tracker.move(sample(e));\n if (step.intent !== 'swipe') return;\n if (!dragging.value) {\n dragging.value = true;\n try {\n (e.currentTarget as HTMLElement).setPointerCapture(e.pointerId);\n } catch {\n /* a pointer the browser does not know / неизвестный браузеру указатель */\n }\n }\n swiped = true;\n drag.value = clampOffset(step.offset, geometry.value);\n}\n\nfunction onUp(e: PointerEvent) {\n if (e.pointerId !== pointerId) return;\n const result = tracker.up(sample(e));\n release();\n if (!result) return;\n const outcome = swipeRowRelease(result, geometry.value);\n if (outcome.kind === 'start' && props.start) {\n open.value = false;\n emit('action', props.start.id);\n } else if (outcome.kind === 'full' && lastEnd.value) {\n gone.value = true;\n emit('action', lastEnd.value.id);\n // the app removes the row; if it keeps it (an archive that failed), it comes back\n // приложение убирает строку; если оставит, она вернётся\n setTimeout(() => {\n gone.value = false;\n open.value = false;\n }, 400);\n } else if (outcome.kind === 'rest') {\n open.value = outcome.open;\n }\n}\n\nfunction onCancel(e: PointerEvent) {\n if (e.pointerId !== pointerId) return;\n tracker.cancel();\n release();\n}\n\n// the end of a swipe also fires a click on the row: it must not open the item\n// конец свайпа даёт и click по строке: он не должен открывать элемент\nfunction onClickCapture(e: MouseEvent) {\n if (swiped) {\n e.stopPropagation();\n e.preventDefault();\n swiped = false;\n }\n}\n\nfunction run(action: SwipeRowAction) {\n open.value = false;\n startShown.value = false;\n emit('action', action.id);\n}\n\n//---]>\n// the keyboard: an action button that gets the focus shows its side\n// клавиатура: кнопка действия, получившая фокус, показывает свою сторону\n\nfunction onFocusIn(e: FocusEvent) {\n const side = (e.target as HTMLElement).closest<HTMLElement>('[data-side]')?.dataset.side;\n if (side === 'end') open.value = true;\n if (side === 'start') startShown.value = true;\n}\n\nfunction onFocusOut(e: FocusEvent) {\n if (root.value?.contains(e.relatedTarget as Node | null)) return;\n startShown.value = false;\n open.value = false;\n}\n\n// an open row closes on a touch outside it / открытая строка закрывается касанием вне её\nfunction onOutside(e: PointerEvent) {\n if (!root.value?.contains(e.target as Node)) open.value = false;\n}\nwatch(open, (isOpen) => {\n if (isOpen) document.addEventListener('pointerdown', onOutside, true);\n else document.removeEventListener('pointerdown', onOutside, true);\n});\n\nlet resize: ResizeObserver | undefined;\nonMounted(() => {\n if (!root.value) return;\n width.value = root.value.clientWidth || width.value;\n if (typeof ResizeObserver !== 'undefined') {\n resize = new ResizeObserver(() => (width.value = root.value?.clientWidth || width.value));\n resize.observe(root.value);\n }\n});\nonBeforeUnmount(() => {\n stopFocusLoss?.();\n resize?.disconnect();\n document.removeEventListener('pointerdown', onOutside, true);\n});\n\nconst startWidth = computed(() => Math.max(0, offset.value));\n\n/*\n * The icon and the label always stand where they end up, so nothing pops in and the heights never jump; only their\n * opacity follows the width of their block. The icon comes first, the label later, when the block is wide enough to\n * hold it.\n * Иконка и подпись всегда стоят на своих итоговых местах, поэтому ничего не выскакивает и высоты не прыгают; от ширины\n * блока зависит только их прозрачность. Иконка проявляется раньше, подпись позже, когда блок уже вмещает её.\n */\nconst fade = (width: number, from: number, span: number) => Math.min(1, Math.max(0, (width - from) / span));\nconst endIcon = (w: number) => fade(w, 22, 20);\nconst endLabel = (w: number) => fade(w, 50, 18);\nconst startIcon = (w: number) => fade(w, 36, 24);\nconst startLabel = (w: number) => fade(w, 84, 28);\n</script>\n\n<template>\n <div\n ref=\"root\"\n class=\"tx-swipe\"\n :class=\"{ 'tx-swipe--dragging': dragging, 'tx-swipe--armed-full': armed === 'full' || gone }\"\n @focusin=\"onFocusIn\"\n @focusout=\"onFocusOut\"\n >\n <div v-if=\"start\" class=\"tx-swipe__start\" data-side=\"start\" :style=\"{ width: `${startWidth}px` }\">\n <button\n type=\"button\"\n class=\"tx-swipe__action tx-swipe__action--start\"\n :class=\"[toneClass(start.tone ?? 'neutral'), { 'tx-swipe__action--armed': armed === 'start' }]\"\n :aria-label=\"start.label\"\n @click=\"run(start)\"\n >\n <slot name=\"action\" :action=\"start\" :armed=\"armed === 'start'\" side=\"start\" :width=\"startWidth\">\n <TaoIcon v-if=\"start.icon\" :name=\"start.icon\" :size=\"20\" :style=\"{ opacity: startIcon(startWidth) }\" />\n <span class=\"tx-swipe__label\" :style=\"{ opacity: startLabel(startWidth) }\">{{ start.label }}</span>\n </slot>\n </button>\n </div>\n\n <div v-if=\"end.length\" class=\"tx-swipe__end\" data-side=\"end\">\n <button\n v-for=\"(action, i) in end\"\n :key=\"action.id\"\n type=\"button\"\n class=\"tx-swipe__action\"\n :class=\"[toneClass(action.tone ?? 'neutral'), { 'tx-swipe__action--armed': i === end.length - 1 && (armed === 'full' || gone) }]\"\n :style=\"{ width: `${widths[i]}px` }\"\n :aria-label=\"action.label\"\n @click=\"run(action)\"\n >\n <slot name=\"action\" :action=\"action\" :armed=\"i === end.length - 1 && armed === 'full'\" side=\"end\" :width=\"widths[i] ?? 0\">\n <TaoIcon v-if=\"action.icon\" :name=\"action.icon\" :size=\"20\" :style=\"{ opacity: endIcon(widths[i] ?? 0) }\" />\n <span class=\"tx-swipe__label\" :style=\"{ opacity: endLabel(widths[i] ?? 0) }\">{{ action.label }}</span>\n </slot>\n </button>\n </div>\n\n <div\n class=\"tx-swipe__front\"\n :style=\"{ transform: `translate3d(${offset}px, 0, 0)` }\"\n @pointerdown=\"onDown\"\n @pointermove=\"onMove\"\n @pointerup=\"onUp\"\n @pointercancel=\"onCancel\"\n @click.capture=\"onClickCapture\"\n >\n <slot />\n </div>\n </div>\n</template>\n\n<style>\n.tx-swipe {\n --tx-swipe-gap: 6px;\n --tx-swipe-radius: var(--tao-radius-panel, 12px);\n position: relative;\n overflow: hidden;\n border-radius: var(--tx-swipe-radius);\n}\n\n.tx-swipe__front {\n position: relative;\n z-index: 1;\n /* the page keeps the vertical scroll, the tracker takes the sideways pull / вертикаль — странице, вбок — трекеру */\n touch-action: pan-y;\n border-radius: inherit;\n background: var(--tao-color-surface-raised, #1f1f1f);\n transition: transform 0.22s ease;\n}\n\n.tx-swipe--dragging .tx-swipe__front {\n transition: none;\n}\n\n.tx-swipe__start,\n.tx-swipe__end {\n position: absolute;\n inset-block: 0;\n display: flex;\n gap: var(--tx-swipe-gap);\n}\n\n/* clipped, with the gap as the button's margin: at width 0 nothing of it is left, while the keyboard can still reach it\n (a padding kept a 6px box, and the button showed at the start edge of a row pulled the other way)\n с обрезкой, а зазор — поле кнопки: при ширине 0 от неё ничего не остаётся, а клавиатура всё равно до неё доходит\n (padding оставлял коробку в 6px, и кнопка виднелась у начального края строки, которую тянули в другую сторону) */\n.tx-swipe__start {\n inset-inline-start: 0;\n overflow: hidden;\n transition: width 0.22s ease;\n}\n\n.tx-swipe__end {\n inset-inline-end: 0;\n justify-content: flex-end;\n}\n\n.tx-swipe--dragging .tx-swipe__start {\n transition: none;\n}\n\n.tx-swipe__action {\n display: inline-flex;\n flex: none;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n /* the icon and the label read as one: a small gap, not pressed to the edges of a short row\n иконка и подпись читаются вместе: небольшой зазор, а не прижаты к краям невысокой строки */\n gap: 2px;\n min-width: 0;\n height: 100%;\n padding: 0;\n overflow: hidden;\n border: 0;\n border-radius: var(--tx-swipe-radius);\n background: color-mix(in srgb, var(--tao-tone) 22%, var(--tao-color-surface-raised, #1f1f1f));\n color: var(--tao-tone-text);\n font: inherit;\n font-size: 13px;\n cursor: pointer;\n transition:\n width 0.15s ease,\n background-color 0.15s ease;\n}\n\n/* under the finger the actions follow the row in the same frame: no width easing, or they trail behind it\n под пальцем действия идут за строкой в том же кадре: без сглаживания ширины, иначе они отстают */\n.tx-swipe--dragging .tx-swipe__end .tx-swipe__action {\n transition: background-color 0.15s ease;\n}\n\n/* the start action is one line, from the start edge: the icon at a fixed place, the label after it\n действие слева — одна строка от начального края: иконка на постоянном месте, подпись за ней */\n.tx-swipe__action--start {\n flex: 1;\n flex-direction: row;\n justify-content: flex-start;\n gap: 10px;\n min-width: 0;\n margin-inline-end: var(--tx-swipe-gap);\n padding-inline-start: 22px;\n}\n\n.tx-swipe__action--armed {\n background: color-mix(in srgb, var(--tao-tone) 45%, var(--tao-color-surface-raised, #1f1f1f));\n color: var(--tao-color-text-strong);\n}\n\n.tx-swipe__action:focus-visible {\n outline: 2px solid var(--tao-color-accent);\n outline-offset: -2px;\n}\n\n/* never squeezed or cut with «…»: a label wider than its block stays whole and centred, the block clips it, and it is\n still transparent then; so the line never changes as the block grows\n подпись не сжимается и не обрезается «…»: шире блока — остаётся целой и по центру, блок её обрезает, а она в это\n время ещё прозрачна; поэтому строка не меняется, пока блок растёт */\n.tx-swipe__label {\n flex: none;\n white-space: nowrap;\n line-height: 1.2;\n}\n\n.tx-swipe__action :is(svg, .tao-icon) {\n flex: none;\n}\n\n/* a short fade, so a row settling by itself shows them softly too; under the finger none\n короткий переход: строка, доезжающая сама, тоже их проявляет мягко; под пальцем без него */\n.tx-swipe__label,\n.tx-swipe__action .tao-icon {\n transition: opacity 0.12s ease;\n}\n\n.tx-swipe--dragging .tx-swipe__label,\n.tx-swipe--dragging .tx-swipe__action .tao-icon {\n transition: none;\n}\n\n@media (prefers-reduced-motion: reduce) {\n .tx-swipe__front,\n .tx-swipe__start,\n .tx-swipe__action,\n .tx-swipe__label,\n .tx-swipe__action .tao-icon {\n transition: none;\n }\n}\n</style>\n"],"mappings":";;;;;AA+BA,IAAa,mBAAmB;;AAEhC,IAAa,qBAAqB;AAElC,IAAa,kBAAkB,MAAwB,KAAK,IAAA,IAAwB,EAAE,QAAQ,CAAC;AAC/F,IAAa,gBAAgB,MAAwB,EAAE,cAAc,EAAE;AACvE,IAAa,iBAAiB,MAAwB,KAAK,IAAI,aAAa,CAAC,IAAI,IAAI,EAAE,QAAQ,gBAAgB;;;;;AAM/G,SAAgB,QAAQ,QAAgB,GAA8C;CAClF,IAAI,SAAS,KAAK,EAAE,YAAY,UAAU,eAAe,CAAC,GAAG,OAAO;CACpE,IAAI,SAAS,KAAK,EAAE,aAAa,EAAE,WAAW,KAAK,CAAC,UAAU,cAAc,CAAC,GAAG,OAAO;CACvF,OAAO;AACX;;AAGA,SAAgB,YAAY,QAAgB,GAA6B;CACrE,MAAM,QAAQ,EAAE,WAAW,EAAE,QAAQ;CACrC,MAAM,OAAO,EAAE,aAAa,IAAI,IAAI,EAAE,YAAY,CAAC,EAAE,QAAQ,CAAC,aAAa,CAAC,IAAI;CAChF,OAAO,KAAK,IAAI,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AACjD;;;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,C;;IAKxGL,mBAUM,OAAA;KATF,OAAM;KACL,OAAKD,eAAA,EAAA,WAAA,eAA8B,OAAA,MAAM,WAAA,CAAA;KACzC,eAAa;KACb,eAAa;KACb,aAAW;KACX,iBAAe;KACA;I,IAEhBG,WAAQ,KAAA,QAAA,SAAA,C"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@1337exp/taoux",
3
- "version": "0.5.0",
3
+ "version": "0.5.1",
4
4
  "description": "Interaction and behavior building blocks for Vue apps: curve and gradient editors, canvas, undo/redo, playback. Import only what you need, bring your own design.",
5
5
  "keywords": [
6
6
  "vue",
@@ -1,12 +1,13 @@
1
1
  ---
2
2
  name: taoux
3
- description: Build editor-like behaviour in Vue 3 apps with @1337exp/taoux (TaoUX) — subpath modules for camera, undo history, document sessions, commands and hotkeys, playback, canvas, curve and gradient editors, and joining them to TaoUI. Use when code imports @1337exp/taoux/*, uses Taox* components or --tx-* variables, or the user asks for TaoUX.
3
+ description: Build interaction in Vue 3 apps with @1337exp/taoux (TaoUX) — subpath modules for gestures (tap, long press, pinch, swipe), reorderable lists (sortable), swipe rows with actions (swiperow), undo by snapshots or by records, document sessions, autosave across tabs, commands and hotkeys, playback, canvas, curve and gradient editors, and joining them to TaoUI. Use when code imports @1337exp/taoux/*, uses Taox* components or --tx-* variables, or the user asks for TaoUX.
4
4
  ---
5
5
 
6
6
  # TaoUX
7
7
 
8
- Behaviour building blocks for editors: the logic is plain TypeScript (tested without a DOM), the few Vue modules are thin
9
- shells, and TaoUX has **no buttons or fields of its own**. Pair it with TaoUI for the controls, or with your own design.
8
+ Behaviour building blocks for apps and editors: the logic is plain TypeScript (tested without a DOM), the few Vue modules are
9
+ thin shells, and TaoUX has **no buttons or fields of its own** outside the two TaoUI-based fields. Pair it with TaoUI for the
10
+ controls, or with your own design.
10
11
 
11
12
  ## Rules
12
13
 
@@ -16,7 +17,7 @@ shells, and TaoUX has **no buttons or fields of its own**. Pair it with TaoUI fo
16
17
  `links.css`, `gradienteditor.css`, `curvefield.css`, `swiperow.css`; `curvefield` needs `curveeditor.css` too).
17
18
  3. **With TaoUI, add the bridge**: `import '@1337exp/taoux/taoui.css'` points every `--tx-*` colour at a `--tao-*` role, so
18
19
  the editors follow the TaoUI theme and palettes. Zero specificity: your rules win. Without it the editors stay dark.
19
- 4. **Values travel through `v-model`**; TaoUX never renders a TaoUI control itself, except tier-2 `curvefield`.
20
+ 4. **Values travel through `v-model`**; TaoUX never renders a TaoUI control itself, except the tier-2 fields `curvefield` and `swiperow`.
20
21
  5. **Pre-1.0**: breaking changes happen between minors; read `CHANGELOG.md`.
21
22
 
22
23
  ## Modules
@@ -36,7 +37,7 @@ shells, and TaoUX has **no buttons or fields of its own**. Pair it with TaoUI fo
36
37
  | `snap` | soft snapping to a grid, threshold follows the zoom |
37
38
  | `wheel` | wheel / trackpad → pan or zoom, like Figma (zoom only with Ctrl / ⌘ or a pinch) |
38
39
  | `edgescroll` | auto-scroll near an edge while dragging (`createEdgeScroller`) |
39
- | `gestures` | tap, double tap, long press, pinch; `SwipeTracker` (swipe vs scroll) + `settleOpen` (where a released row rests) |
40
+ | `gestures` | tap, double tap, long press, pinch; `SwipeTracker` (swipe vs scroll) + `settleOpen` (where a released row rests); `listenFocusLoss(cancel)` while a press is held, as Alt-Tab swallows the pointerup |
40
41
  | `touch` | `coarse`: is the pointer a finger |
41
42
  | `curve` | link paths: Bezier between pins, arrowheads of constant screen size |
42
43
  | `ids` | `uuid()` for stored / synced records; `uid(prefix, taken)` restarts from zero on every load, only for ids inside one document |