@1337exp/taoux 0.5.5 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +15 -0
- package/README.md +4 -2
- package/README.ru.md +4 -2
- package/dist/swiperow/TaoxSwipeRow.vue.d.ts +12 -0
- package/dist/swiperow.js +28 -2
- package/dist/swiperow.js.map +1 -1
- package/dist/tour/core.d.ts +77 -0
- package/dist/tour/index.d.ts +3 -0
- package/dist/tour/memory.d.ts +16 -0
- package/dist/tour/use.d.ts +21 -0
- package/dist/tour.js +172 -0
- package/dist/tour.js.map +1 -0
- package/dist/undovue.d.ts +65 -0
- package/dist/undovue.js +90 -0
- package/dist/undovue.js.map +1 -0
- package/package.json +10 -2
- package/skills/taoux/SKILL.md +3 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,20 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.7.0
|
|
4
|
+
|
|
5
|
+
Nothing to migrate: a new module, nothing existing changes.
|
|
6
|
+
|
|
7
|
+
- **New module `undovue`: reactive `canUndo` / `canRedo` for `UndoStack` and `History`.** Both are plain classes whose flags are getters, so an app that wants the Undo and Redo items of a menu to switch on and off had to keep two refs and a `syncFlags()` by hand (every project that uses `undo` or `history` did). `useUndoStack(optionsOrStack)` and `useHistory(initialOrHistory)` wrap the class and keep `canUndo` / `canRedo` (read-only refs) in step after `record`, `undo`, `redo`, `clear`, `commit`, `reset`; `useHistory` also fits `historyCommands` as a source. For a stack you already made (a factory of yours, a store), `useUndoFlags(source)` gives the refs and `sync()`. The classes themselves are not touched.
|
|
8
|
+
|
|
9
|
+
## 0.6.0
|
|
10
|
+
|
|
11
|
+
- **New module `tour`: the model of a guided tour of a page.** `createTour({ steps, available, onEnd })` is a plain state machine without Vue: `start`, `next`, `prev`, `goTo`, `skip`, `finish`, `setSteps`, `subscribe`. A step is `{ id, ...yours }`; one that `available` refuses (its target is not on the page) is jumped over in both directions, and `first` / `last` say whether there is anywhere to go, and `position` / `total` count only the steps that can be shown (for a "2 of 4" that does not count the skipped ones). A tour ends once as `done` or `skipped`. `useTour` is the same with refs for a component, `createTourMemory(key)` remembers that a tour was seen. It draws nothing: the spotlight and the card belong to the app or to TaoUI.
|
|
12
|
+
|
|
13
|
+
## 0.5.6
|
|
14
|
+
|
|
15
|
+
- **`swiperow`: an open row does not click through.** The row that stayed open on its actions still had a live face: a tap on the sliver of it that is left opened the item, and the press outside that closed the row went on to a click on whatever lay under the finger (another row opened). Now a click on the open row only closes it and does not reach its content, and the click after a press outside is swallowed once (a mail app does the same). `:swallow-outside-click="false"` lets the outside click through after the row has closed. A press that gives no click (a scroll) lets go of the guard after 0.6 s. The action buttons work as before.
|
|
16
|
+
- **`swiperow`: a row mounted open** (`open` true from the start) closes on a press outside it too; the listener was only added when `open` changed.
|
|
17
|
+
|
|
3
18
|
## 0.5.5
|
|
4
19
|
|
|
5
20
|
- **`swiperow` stays under a floating bar.** The face of a row has `z-index: 1`, and the row had no stacking context of its own, so the faces took part in the stacking of the whole page and were drawn over a floating `TaoNav` (its glass pill included): the text of the rows showed over the menu. The row is `isolation: isolate` now, and the face counts inside it only.
|
package/README.md
CHANGED
|
@@ -107,10 +107,12 @@ import { History } from '@1337exp/taoux/history';
|
|
|
107
107
|
| `curvefield` (Vue, tier 2) | `TaoxCurveField`: a curve with fields on TaoUI components: point time and value, transition to the next point (`ease`), snapping, remove and reset; labels come from the app | vue, **@1337exp/taoui** (peer) |
|
|
108
108
|
| `gradienteditor` (Vue) | gradient bar with stop handles; stop operations, `gradientCss`; keyboard (Tab, arrows, Home/End, Insert, Delete) | vue (peer) |
|
|
109
109
|
| `playback` | playback model: time, pause, loop, speed, seeking; `createPlayback` without Vue and `usePlayback` for a component | vue (peer, for `usePlayback`) |
|
|
110
|
+
| `tour` | a guided tour of a page, step by step: `createTour` without Vue (jumps over steps whose target is gone, ends as `done` or `skipped`), `useTour` for a component, `createTourMemory` so it shows once | vue (peer, for `useTour`), storage |
|
|
111
|
+
| `undovue` | `undo` and `history` for Vue: `useUndoStack` and `useHistory` keep `canUndo` / `canRedo` as refs after every move (for `historyCommands` and the menu); `useUndoFlags(source)` + `sync()` for a stack you already have | vue (peer) |
|
|
110
112
|
| `pins` | row pin positions measured from the DOM: `usePinMeasure`, `createPinRegistry` | vue (peer) |
|
|
111
113
|
| `i18n` | typed i18n: `createI18n({ locales, fallback, storageKey })` | vue (peer, optional) |
|
|
112
114
|
|
|
113
|
-
Vue modules (`links`, `canvas`, `curveeditor`, `curvefield`, `gradienteditor`, `swiperow`) need their styles imported explicitly: `import '@1337exp/taoux/canvas.css'`. Composite modules (session, commands, palette, links, canvas, pins, curveeditor, gradienteditor, playback) import only primitives. Tier 2, fields (`curvefield`, `swiperow`), assemble composites into a ready field on TaoUI components: it is the only tier allowed to import TaoUI, which is why `@1337exp/taoui` is an optional peer dependency. `curvefield` needs both `curveeditor.css` and `curvefield.css`. The `tiers.test.ts` test guards all of that. The swipe row, its variables and how to test a swipe are in [docs/swiperow.md](docs/swiperow.md) ([Русский](docs/swiperow.ru.md)). The canvas contract is described in [docs/canvas.md](docs/canvas.md) ([Русский](docs/canvas.ru.md)); transitions between curve points are in [docs/ease.md](docs/ease.md) ([Русский](docs/ease.ru.md)).
|
|
115
|
+
Vue modules (`links`, `canvas`, `curveeditor`, `curvefield`, `gradienteditor`, `swiperow`) need their styles imported explicitly: `import '@1337exp/taoux/canvas.css'`. Composite modules (session, commands, palette, links, canvas, pins, curveeditor, gradienteditor, playback, tour, undovue) import only primitives. Tier 2, fields (`curvefield`, `swiperow`), assemble composites into a ready field on TaoUI components: it is the only tier allowed to import TaoUI, which is why `@1337exp/taoui` is an optional peer dependency. `curvefield` needs both `curveeditor.css` and `curvefield.css`. The `tiers.test.ts` test guards all of that. The swipe row, its variables and how to test a swipe are in [docs/swiperow.md](docs/swiperow.md) ([Русский](docs/swiperow.ru.md)). The canvas contract is described in [docs/canvas.md](docs/canvas.md) ([Русский](docs/canvas.ru.md)); transitions between curve points are in [docs/ease.md](docs/ease.md) ([Русский](docs/ease.ru.md)).
|
|
114
116
|
|
|
115
117
|
The rule: a module lands here when a second project needs it. A module's core knows nothing about Vue or the DOM unless that is its job.
|
|
116
118
|
|
|
@@ -134,7 +136,7 @@ Working against a local checkout instead of npm: put `"@1337exp/taoux": "file:..
|
|
|
134
136
|
|
|
135
137
|
## Sandbox
|
|
136
138
|
|
|
137
|
-
The `sandbox/` folder is a demo and a testing ground: pages import the modules straight from `src/`, with no build. It holds `curveeditor`, `curvefield`, `gradienteditor`, `slider`, `color`, `playback`, `sortable` and `
|
|
139
|
+
The `sandbox/` folder is a demo and a testing ground: pages import the modules straight from `src/`, with no build. It holds `curveeditor`, `curvefield`, `gradienteditor`, `slider`, `color`, `playback`, `sortable`, `swiperow` and `tour`, with an EN / RU switch and a dark / light switch (the TaoUI theme, through the bridge). A new page is `sandbox/<name>.html` + `.ts` + a demo `.vue` and a link in `sandbox/index.html`. `npm run sandbox:build` makes a static copy with relative paths, ready for any folder (for example `/sandbox/taoux/`).
|
|
138
140
|
|
|
139
141
|
Screenshots and clips in this README come from the sandbox: see [docs/media](docs/media/README.md).
|
|
140
142
|
|
package/README.ru.md
CHANGED
|
@@ -107,10 +107,12 @@ import { History } from '@1337exp/taoux/history';
|
|
|
107
107
|
| `curvefield` (Vue, ярус 2) | `TaoxCurveField`: кривая с полями на компонентах TaoUI: время и значение точки, переход к следующей точке (`ease`), шаг, удаление и сброс; надписи задаёт приложение | vue, **@1337exp/taoui** (peer) |
|
|
108
108
|
| `gradienteditor` (Vue) | полоса градиента с ручками остановок; операции над остановками, `gradientCss`; клавиатура (Tab, стрелки, Home/End, Insert, Delete) | vue (peer) |
|
|
109
109
|
| `playback` | модель воспроизведения: время, пауза, цикл, скорость, перемотка; `createPlayback` без Vue и `usePlayback` для компонента | vue (peer, для `usePlayback`) |
|
|
110
|
+
| `tour` | тур по странице по шагам: `createTour` без Vue (перепрыгивает шаги, у которых пропала цель, завершается как `done` или `skipped`), `useTour` для компонента, `createTourMemory`, чтобы показывался один раз | vue (peer, для `useTour`), storage |
|
|
111
|
+
| `undovue` | `undo` и `history` для Vue: `useUndoStack` и `useHistory` держат `canUndo` / `canRedo` как ref после каждого хода (для `historyCommands` и меню); `useUndoFlags(source)` + `sync()` для уже готового стека | vue (peer) |
|
|
110
112
|
| `pins` | позиции пинов-строк, измеренные по DOM: `usePinMeasure`, `createPinRegistry` | vue (peer) |
|
|
111
113
|
| `i18n` | типизированный i18n: `createI18n({ locales, fallback, storageKey })` | vue (peer, опционально) |
|
|
112
114
|
|
|
113
|
-
Vue-модули (`links`, `canvas`, `curveeditor`, `curvefield`, `gradienteditor`, `swiperow`) требуют явного импорта стилей: `import '@1337exp/taoux/canvas.css'`. Составные модули (session, commands, palette, links, canvas, pins, curveeditor, gradienteditor, playback) импортируют только примитивы. Ярус 2, поля (`curvefield`, `swiperow`), собирает составные модули в готовое поле на компонентах TaoUI: только ему можно импортировать TaoUI, поэтому `@1337exp/taoui` это необязательная peer-зависимость. Для `curvefield` нужны оба файла стилей, `curveeditor.css` и `curvefield.css`. Всё это охраняет тест `tiers.test.ts`; строка со свайпом, её переменные и как проверять свайп — в [docs/swiperow.ru.md](docs/swiperow.ru.md); контракт холста описан в [docs/canvas.ru.md](docs/canvas.ru.md), переходы между точками кривой в [docs/ease.ru.md](docs/ease.ru.md).
|
|
115
|
+
Vue-модули (`links`, `canvas`, `curveeditor`, `curvefield`, `gradienteditor`, `swiperow`) требуют явного импорта стилей: `import '@1337exp/taoux/canvas.css'`. Составные модули (session, commands, palette, links, canvas, pins, curveeditor, gradienteditor, playback, tour, undovue) импортируют только примитивы. Ярус 2, поля (`curvefield`, `swiperow`), собирает составные модули в готовое поле на компонентах TaoUI: только ему можно импортировать TaoUI, поэтому `@1337exp/taoui` это необязательная peer-зависимость. Для `curvefield` нужны оба файла стилей, `curveeditor.css` и `curvefield.css`. Всё это охраняет тест `tiers.test.ts`; строка со свайпом, её переменные и как проверять свайп — в [docs/swiperow.ru.md](docs/swiperow.ru.md); контракт холста описан в [docs/canvas.ru.md](docs/canvas.ru.md), переходы между точками кривой в [docs/ease.ru.md](docs/ease.ru.md).
|
|
114
116
|
|
|
115
117
|
Правило: модуль попадает сюда, когда он понадобился во втором проекте. Ядро модулей не знает про Vue и DOM, если это не их задача.
|
|
116
118
|
|
|
@@ -136,7 +138,7 @@ npm run dev # watch: пересборка JS и деклараций
|
|
|
136
138
|
|
|
137
139
|
## Песочница
|
|
138
140
|
|
|
139
|
-
Папка `sandbox/` это демо и поле для проверки: страницы подключают модули прямо из `src/`, без сборки. Сейчас там `curveeditor`, `curvefield`, `gradienteditor`, `slider`, `color`, `playback`, `sortable` и `
|
|
141
|
+
Папка `sandbox/` это демо и поле для проверки: страницы подключают модули прямо из `src/`, без сборки. Сейчас там `curveeditor`, `curvefield`, `gradienteditor`, `slider`, `color`, `playback`, `sortable`, `swiperow` и `tour`, с переключателем языка (EN / RU) и темы (тёмная / светлая: тема TaoUI через мост). Новая страница = `sandbox/<имя>.html` + `.ts` + демо `.vue` и ссылка в `sandbox/index.html`. `npm run sandbox:build` собирает статическую копию с относительными путями, её можно положить в любую папку (например, `/sandbox/taoux/`).
|
|
140
142
|
|
|
141
143
|
Скриншоты и ролики в этом README сняты с песочницы: см. [docs/media](docs/media/README.md).
|
|
142
144
|
|
|
@@ -20,6 +20,17 @@ type __VLS_Props = {
|
|
|
20
20
|
* по-прежнему работают нажатием и свайпом.
|
|
21
21
|
*/
|
|
22
22
|
tabbable?: boolean;
|
|
23
|
+
/**
|
|
24
|
+
* An open row closes on a press outside it, and that press does not go on to click what lies under it: the tap
|
|
25
|
+
* that closes is only a tap that closes (a mail app does the same), it does not open another row or press a
|
|
26
|
+
* button. Turn it off to let the click through after the row has closed. A click on the open row itself never
|
|
27
|
+
* reaches its content: it closes the row.
|
|
28
|
+
* Открытая строка закрывается нажатием вне неё, и это нажатие не становится кликом по тому, что под пальцем:
|
|
29
|
+
* тап «закрыть» только закрывает (как в почтовом приложении), он не открывает другую строку и не жмёт кнопку.
|
|
30
|
+
* Выключите, чтобы после закрытия клик проходил. Клик по самой открытой строке до её содержимого не доходит:
|
|
31
|
+
* он закрывает строку.
|
|
32
|
+
*/
|
|
33
|
+
swallowOutsideClick?: boolean;
|
|
23
34
|
};
|
|
24
35
|
type __VLS_Slots = {
|
|
25
36
|
default?(): unknown;
|
|
@@ -50,6 +61,7 @@ declare const __VLS_base: import("vue").DefineComponent<__VLS_PublicProps, {}, {
|
|
|
50
61
|
fullSwipe: boolean;
|
|
51
62
|
mouse: boolean;
|
|
52
63
|
tabbable: boolean;
|
|
64
|
+
swallowOutsideClick: boolean;
|
|
53
65
|
}, {}, {}, {}, string, import("vue").ComponentProvideOptions, false, {}, any>;
|
|
54
66
|
declare const __VLS_export: __VLS_WithSlots<typeof __VLS_base, __VLS_Slots>;
|
|
55
67
|
declare const _default: typeof __VLS_export;
|
package/dist/swiperow.js
CHANGED
|
@@ -101,6 +101,7 @@ var _hoisted_3 = [
|
|
|
101
101
|
"aria-label",
|
|
102
102
|
"onClick"
|
|
103
103
|
];
|
|
104
|
+
var SWALLOW_MS = 600;
|
|
104
105
|
//#endregion
|
|
105
106
|
//#region src/swiperow/TaoxSwipeRow.vue
|
|
106
107
|
var TaoxSwipeRow_default = /* @__PURE__ */ defineComponent({
|
|
@@ -124,6 +125,10 @@ var TaoxSwipeRow_default = /* @__PURE__ */ defineComponent({
|
|
|
124
125
|
tabbable: {
|
|
125
126
|
type: Boolean,
|
|
126
127
|
default: true
|
|
128
|
+
},
|
|
129
|
+
swallowOutsideClick: {
|
|
130
|
+
type: Boolean,
|
|
131
|
+
default: true
|
|
127
132
|
}
|
|
128
133
|
}, {
|
|
129
134
|
"open": {
|
|
@@ -230,6 +235,10 @@ var TaoxSwipeRow_default = /* @__PURE__ */ defineComponent({
|
|
|
230
235
|
e.stopPropagation();
|
|
231
236
|
e.preventDefault();
|
|
232
237
|
swiped = false;
|
|
238
|
+
} else if (open.value) {
|
|
239
|
+
e.stopPropagation();
|
|
240
|
+
e.preventDefault();
|
|
241
|
+
open.value = false;
|
|
233
242
|
}
|
|
234
243
|
}
|
|
235
244
|
function run(action) {
|
|
@@ -247,13 +256,29 @@ var TaoxSwipeRow_default = /* @__PURE__ */ defineComponent({
|
|
|
247
256
|
startShown.value = false;
|
|
248
257
|
open.value = false;
|
|
249
258
|
}
|
|
259
|
+
let swallowTimer;
|
|
260
|
+
function disarmSwallow() {
|
|
261
|
+
document.removeEventListener("click", swallowClick, true);
|
|
262
|
+
clearTimeout(swallowTimer);
|
|
263
|
+
}
|
|
264
|
+
function swallowClick(e) {
|
|
265
|
+
disarmSwallow();
|
|
266
|
+
if (root.value?.contains(e.target)) return;
|
|
267
|
+
e.stopImmediatePropagation();
|
|
268
|
+
e.preventDefault();
|
|
269
|
+
}
|
|
250
270
|
function onOutside(e) {
|
|
251
|
-
if (
|
|
271
|
+
if (root.value?.contains(e.target)) return;
|
|
272
|
+
open.value = false;
|
|
273
|
+
if (!props.swallowOutsideClick) return;
|
|
274
|
+
disarmSwallow();
|
|
275
|
+
document.addEventListener("click", swallowClick, true);
|
|
276
|
+
swallowTimer = setTimeout(disarmSwallow, SWALLOW_MS);
|
|
252
277
|
}
|
|
253
278
|
watch(open, (isOpen) => {
|
|
254
279
|
if (isOpen) document.addEventListener("pointerdown", onOutside, true);
|
|
255
280
|
else document.removeEventListener("pointerdown", onOutside, true);
|
|
256
|
-
});
|
|
281
|
+
}, { immediate: true });
|
|
257
282
|
let resize;
|
|
258
283
|
onMounted(() => {
|
|
259
284
|
if (!root.value) return;
|
|
@@ -267,6 +292,7 @@ var TaoxSwipeRow_default = /* @__PURE__ */ defineComponent({
|
|
|
267
292
|
stopFocusLoss?.();
|
|
268
293
|
resize?.disconnect();
|
|
269
294
|
document.removeEventListener("pointerdown", onOutside, true);
|
|
295
|
+
disarmSwallow();
|
|
270
296
|
});
|
|
271
297
|
const startWidth = computed(() => Math.max(0, offset.value));
|
|
272
298
|
const fade = (width, from, span) => Math.min(1, Math.max(0, (width - from) / span));
|
package/dist/swiperow.js.map
CHANGED
|
@@ -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/**\n * How far the row may move: no further than there is something behind it. Without the full swipe a pull past the open\n * actions meets a spring: it still follows the finger, ever slower, up to half the open width more, and on release the\n * row rests open.\n * Насколько строка может уехать. Без длинного свайпа протяжка дальше открытых действий упирается в пружину: строка\n * всё ещё идёт за пальцем, всё медленнее, не дальше ещё половины открытой ширины, а после отпускания остаётся открытой.\n */\nexport function clampOffset(offset: number, g: SwipeRowGeometry): number {\n const right = g.hasStart ? g.width : 0;\n if (offset < 0 && g.endCount > 0 && !g.fullSwipe) {\n const open = endOpenWidth(g);\n const over = -offset - open;\n if (over <= 0) return offset;\n const room = open / 2;\n return -(open + room * (1 - 1 / (1 + over / room)));\n }\n const left = g.endCount === 0 ? 0 : -g.width;\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 // without the full swipe nothing is about to run: the actions only grow, side by side\n // без длинного свайпа ничего не выполнится: действия просто растут, все поровну\n if (drag <= open || !g.fullSwipe) 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 * The action buttons are Tab stops (each shows its side when it gets the focus). Turn it off when the app has\n * its own keyboard path to the same actions (arrows, Delete, a menu key): the buttons leave the Tab order and\n * still work by a click or a swipe.\n * Кнопки действий — остановки Tab (каждая показывает свою сторону при фокусе). Выключите, когда у приложения\n * свой путь к тем же действиям с клавиатуры (стрелки, Delete, клавиша меню): кнопки уходят из порядка Tab и\n * по-прежнему работают нажатием и свайпом.\n */\n tabbable?: boolean;\n }>(),\n { start: undefined, end: () => [], actionWidth: 76, fullSwipe: true, mouse: false, disabled: false, tabbable: true },\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 and only its side (Tab from the start action to an\n// end one used to keep the start shown, which wins, and the focused button stayed hidden under the row); the focus on\n// the row's own content shows neither\n// клавиатура: кнопка действия, получившая фокус, показывает свою сторону и только её (Tab с левого действия на правое\n// оставлял показанной левую сторону, а она главнее, и кнопка с фокусом пряталась под строкой); фокус на содержимом\n// строки не показывает ни одну\n\nfunction onFocusIn(e: FocusEvent) {\n const side = (e.target as HTMLElement).closest<HTMLElement>('[data-side]')?.dataset.side;\n startShown.value = side === 'start';\n open.value = side === 'end';\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, 'tx-swipe--mouse': mouse }\"\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 :tabindex=\"tabbable ? undefined : -1\"\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 :tabindex=\"tabbable ? undefined : -1\"\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/*\n * Variables, on the row or on any element around it (the defaults stand in var(), so an ancestor's value reaches here):\n * --tx-swipe-bg the face of the row and the ground its actions are tinted on (the raised surface; a row right on\n * the page: var(--tao-color-bg))\n * --tx-swipe-radius the corners of the row (the panel radius)\n * --tx-swipe-gap the gap between the end actions (6px)\n * Переменные — на строке или на любом элементе вокруг неё (значения по умолчанию стоят в var(), поэтому значение предка\n * доходит сюда): --tx-swipe-bg — лицо строки и основа подкраски действий; --tx-swipe-radius — углы; --tx-swipe-gap —\n * зазор между действиями справа.\n */\n.tx-swipe {\n /* a stacking context of its own: the z-index of the face counts inside the row only, so a floating bar or a glass\n panel over the list stays over its rows\n свой контекст наложения: z-index лица действует только внутри строки, поэтому плавающая панель или стекло над\n списком остаются поверх его строк */\n isolation: isolate;\n --_tx-swipe-gap: var(--tx-swipe-gap, 6px);\n --_tx-swipe-radius: var(--tx-swipe-radius, var(--tao-radius-panel, 12px));\n --_tx-swipe-bg: var(--tx-swipe-bg, var(--tao-color-surface-raised, #1f1f1f));\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(--_tx-swipe-bg);\n transition: transform 0.22s ease;\n}\n\n.tx-swipe--dragging .tx-swipe__front {\n transition: none;\n}\n\n/* a pull is not a selection: while it runs nothing is selected; with `mouse` the mouse drags the row, so its text is\n not selected by a press-and-move at all (a finger selects with a long press, which a swipe is not)\n протяжка — не выделение: пока она идёт, ничего не выделяется; с `mouse` мышь тянет строку, поэтому её текст не\n выделяется нажатием с движением вовсе (палец выделяет долгим нажатием, а свайп им не является) */\n.tx-swipe--dragging,\n.tx-swipe--mouse .tx-swipe__front {\n -webkit-user-select: none;\n user-select: 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 /* a button, not text: a press or a pull over it selects nothing and calls no callout\n кнопка, а не текст: нажатие или протяжка по ней ничего не выделяет и не вызывает меню */\n -webkit-user-select: none;\n user-select: none;\n -webkit-touch-callout: none;\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(--_tx-swipe-bg));\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(--_tx-swipe-bg));\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 * The action buttons are Tab stops (each shows its side when it gets the focus). Turn it off when the app has\n * its own keyboard path to the same actions (arrows, Delete, a menu key): the buttons leave the Tab order and\n * still work by a click or a swipe.\n * Кнопки действий — остановки Tab (каждая показывает свою сторону при фокусе). Выключите, когда у приложения\n * свой путь к тем же действиям с клавиатуры (стрелки, Delete, клавиша меню): кнопки уходят из порядка Tab и\n * по-прежнему работают нажатием и свайпом.\n */\n tabbable?: boolean;\n }>(),\n { start: undefined, end: () => [], actionWidth: 76, fullSwipe: true, mouse: false, disabled: false, tabbable: true },\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 and only its side (Tab from the start action to an\n// end one used to keep the start shown, which wins, and the focused button stayed hidden under the row); the focus on\n// the row's own content shows neither\n// клавиатура: кнопка действия, получившая фокус, показывает свою сторону и только её (Tab с левого действия на правое\n// оставлял показанной левую сторону, а она главнее, и кнопка с фокусом пряталась под строкой); фокус на содержимом\n// строки не показывает ни одну\n\nfunction onFocusIn(e: FocusEvent) {\n const side = (e.target as HTMLElement).closest<HTMLElement>('[data-side]')?.dataset.side;\n startShown.value = side === 'start';\n open.value = side === 'end';\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, 'tx-swipe--mouse': mouse }\"\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 :tabindex=\"tabbable ? undefined : -1\"\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 :tabindex=\"tabbable ? undefined : -1\"\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/*\n * Variables, on the row or on any element around it (the defaults stand in var(), so an ancestor's value reaches here):\n * --tx-swipe-bg the face of the row and the ground its actions are tinted on (the raised surface; a row right on\n * the page: var(--tao-color-bg))\n * --tx-swipe-radius the corners of the row (the panel radius)\n * --tx-swipe-gap the gap between the end actions (6px)\n * Переменные — на строке или на любом элементе вокруг неё (значения по умолчанию стоят в var(), поэтому значение предка\n * доходит сюда): --tx-swipe-bg — лицо строки и основа подкраски действий; --tx-swipe-radius — углы; --tx-swipe-gap —\n * зазор между действиями справа.\n */\n.tx-swipe {\n /* a stacking context of its own: the z-index of the face counts inside the row only, so a floating bar or a glass\n panel over the list stays over its rows\n свой контекст наложения: z-index лица действует только внутри строки, поэтому плавающая панель или стекло над\n списком остаются поверх его строк */\n isolation: isolate;\n --_tx-swipe-gap: var(--tx-swipe-gap, 6px);\n --_tx-swipe-radius: var(--tx-swipe-radius, var(--tao-radius-panel, 12px));\n --_tx-swipe-bg: var(--tx-swipe-bg, var(--tao-color-surface-raised, #1f1f1f));\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(--_tx-swipe-bg);\n transition: transform 0.22s ease;\n}\n\n.tx-swipe--dragging .tx-swipe__front {\n transition: none;\n}\n\n/* a pull is not a selection: while it runs nothing is selected; with `mouse` the mouse drags the row, so its text is\n not selected by a press-and-move at all (a finger selects with a long press, which a swipe is not)\n протяжка — не выделение: пока она идёт, ничего не выделяется; с `mouse` мышь тянет строку, поэтому её текст не\n выделяется нажатием с движением вовсе (палец выделяет долгим нажатием, а свайп им не является) */\n.tx-swipe--dragging,\n.tx-swipe--mouse .tx-swipe__front {\n -webkit-user-select: none;\n user-select: 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 /* a button, not text: a press or a pull over it selects nothing and calls no callout\n кнопка, а не текст: нажатие или протяжка по ней ничего не выделяет и не вызывает меню */\n -webkit-user-select: none;\n user-select: none;\n -webkit-touch-callout: none;\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(--_tx-swipe-bg));\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(--_tx-swipe-bg));\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-redu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A;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/**\n * How far the row may move: no further than there is something behind it. Without the full swipe a pull past the open\n * actions meets a spring: it still follows the finger, ever slower, up to half the open width more, and on release the\n * row rests open.\n * Насколько строка может уехать. Без длинного свайпа протяжка дальше открытых действий упирается в пружину: строка\n * всё ещё идёт за пальцем, всё медленнее, не дальше ещё половины открытой ширины, а после отпускания остаётся открытой.\n */\nexport function clampOffset(offset: number, g: SwipeRowGeometry): number {\n const right = g.hasStart ? g.width : 0;\n if (offset < 0 && g.endCount > 0 && !g.fullSwipe) {\n const open = endOpenWidth(g);\n const over = -offset - open;\n if (over <= 0) return offset;\n const room = open / 2;\n return -(open + room * (1 - 1 / (1 + over / room)));\n }\n const left = g.endCount === 0 ? 0 : -g.width;\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 // without the full swipe nothing is about to run: the actions only grow, side by side\n // без длинного свайпа ничего не выполнится: действия просто растут, все поровну\n if (drag <= open || !g.fullSwipe) 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 * The action buttons are Tab stops (each shows its side when it gets the focus). Turn it off when the app has\n * its own keyboard path to the same actions (arrows, Delete, a menu key): the buttons leave the Tab order and\n * still work by a click or a swipe.\n * Кнопки действий — остановки Tab (каждая показывает свою сторону при фокусе). Выключите, когда у приложения\n * свой путь к тем же действиям с клавиатуры (стрелки, Delete, клавиша меню): кнопки уходят из порядка Tab и\n * по-прежнему работают нажатием и свайпом.\n */\n tabbable?: boolean;\n /**\n * An open row closes on a press outside it, and that press does not go on to click what lies under it: the tap\n * that closes is only a tap that closes (a mail app does the same), it does not open another row or press a\n * button. Turn it off to let the click through after the row has closed. A click on the open row itself never\n * reaches its content: it closes the row.\n * Открытая строка закрывается нажатием вне неё, и это нажатие не становится кликом по тому, что под пальцем:\n * тап «закрыть» только закрывает (как в почтовом приложении), он не открывает другую строку и не жмёт кнопку.\n * Выключите, чтобы после закрытия клик проходил. Клик по самой открытой строке до её содержимого не доходит:\n * он закрывает строку.\n */\n swallowOutsideClick?: boolean;\n }>(),\n { start: undefined, end: () => [], actionWidth: 76, fullSwipe: true, mouse: false, disabled: false, tabbable: true, swallowOutsideClick: true },\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 по строке: он не должен открывать элемент\n// an open row: a click on it only closes it, it does not open the item hidden under the sliver that is left\n// открытая строка: клик по ней только закрывает её, а не открывает элемент под оставшейся полоской\nfunction onClickCapture(e: MouseEvent) {\n if (swiped) {\n e.stopPropagation();\n e.preventDefault();\n swiped = false;\n } else if (open.value) {\n e.stopPropagation();\n e.preventDefault();\n open.value = 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 and only its side (Tab from the start action to an\n// end one used to keep the start shown, which wins, and the focused button stayed hidden under the row); the focus on\n// the row's own content shows neither\n// клавиатура: кнопка действия, получившая фокус, показывает свою сторону и только её (Tab с левого действия на правое\n// оставлял показанной левую сторону, а она главнее, и кнопка с фокусом пряталась под строкой); фокус на содержимом\n// строки не показывает ни одну\n\nfunction onFocusIn(e: FocusEvent) {\n const side = (e.target as HTMLElement).closest<HTMLElement>('[data-side]')?.dataset.side;\n startShown.value = side === 'start';\n open.value = side === 'end';\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, and the click that follows that touch is swallowed once\n// открытая строка закрывается касанием вне её, а клик, идущий за этим касанием, гасится один раз\nconst SWALLOW_MS = 600;\nlet swallowTimer: ReturnType<typeof setTimeout> | undefined;\n\nfunction disarmSwallow() {\n document.removeEventListener('click', swallowClick, true);\n clearTimeout(swallowTimer);\n}\n\nfunction swallowClick(e: MouseEvent) {\n disarmSwallow();\n if (root.value?.contains(e.target as Node)) return;\n e.stopImmediatePropagation();\n e.preventDefault();\n}\n\nfunction onOutside(e: PointerEvent) {\n if (root.value?.contains(e.target as Node)) return;\n open.value = false;\n if (!props.swallowOutsideClick) return;\n // a press that is a scroll or a long press gives no click: the guard goes away by itself\n // нажатие, ставшее прокруткой или долгим, клика не даёт: охрана снимается сама\n disarmSwallow();\n document.addEventListener('click', swallowClick, true);\n swallowTimer = setTimeout(disarmSwallow, SWALLOW_MS);\n}\nwatch(\n open,\n (isOpen) => {\n if (isOpen) document.addEventListener('pointerdown', onOutside, true);\n else document.removeEventListener('pointerdown', onOutside, true);\n },\n { immediate: 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 disarmSwallow();\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, 'tx-swipe--mouse': mouse }\"\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 :tabindex=\"tabbable ? undefined : -1\"\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 :tabindex=\"tabbable ? undefined : -1\"\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/*\n * Variables, on the row or on any element around it (the defaults stand in var(), so an ancestor's value reaches here):\n * --tx-swipe-bg the face of the row and the ground its actions are tinted on (the raised surface; a row right on\n * the page: var(--tao-color-bg))\n * --tx-swipe-radius the corners of the row (the panel radius)\n * --tx-swipe-gap the gap between the end actions (6px)\n * Переменные — на строке или на любом элементе вокруг неё (значения по умолчанию стоят в var(), поэтому значение предка\n * доходит сюда): --tx-swipe-bg — лицо строки и основа подкраски действий; --tx-swipe-radius — углы; --tx-swipe-gap —\n * зазор между действиями справа.\n */\n.tx-swipe {\n /* a stacking context of its own: the z-index of the face counts inside the row only, so a floating bar or a glass\n panel over the list stays over its rows\n свой контекст наложения: z-index лица действует только внутри строки, поэтому плавающая панель или стекло над\n списком остаются поверх его строк */\n isolation: isolate;\n --_tx-swipe-gap: var(--tx-swipe-gap, 6px);\n --_tx-swipe-radius: var(--tx-swipe-radius, var(--tao-radius-panel, 12px));\n --_tx-swipe-bg: var(--tx-swipe-bg, var(--tao-color-surface-raised, #1f1f1f));\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(--_tx-swipe-bg);\n transition: transform 0.22s ease;\n}\n\n.tx-swipe--dragging .tx-swipe__front {\n transition: none;\n}\n\n/* a pull is not a selection: while it runs nothing is selected; with `mouse` the mouse drags the row, so its text is\n not selected by a press-and-move at all (a finger selects with a long press, which a swipe is not)\n протяжка — не выделение: пока она идёт, ничего не выделяется; с `mouse` мышь тянет строку, поэтому её текст не\n выделяется нажатием с движением вовсе (палец выделяет долгим нажатием, а свайп им не является) */\n.tx-swipe--dragging,\n.tx-swipe--mouse .tx-swipe__front {\n -webkit-user-select: none;\n user-select: 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 /* a button, not text: a press or a pull over it selects nothing and calls no callout\n кнопка, а не текст: нажатие или протяжка по ней ничего не выделяет и не вызывает меню */\n -webkit-user-select: none;\n user-select: none;\n -webkit-touch-callout: none;\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(--_tx-swipe-bg));\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(--_tx-swipe-bg));\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 * The action buttons are Tab stops (each shows its side when it gets the focus). Turn it off when the app has\n * its own keyboard path to the same actions (arrows, Delete, a menu key): the buttons leave the Tab order and\n * still work by a click or a swipe.\n * Кнопки действий — остановки Tab (каждая показывает свою сторону при фокусе). Выключите, когда у приложения\n * свой путь к тем же действиям с клавиатуры (стрелки, Delete, клавиша меню): кнопки уходят из порядка Tab и\n * по-прежнему работают нажатием и свайпом.\n */\n tabbable?: boolean;\n /**\n * An open row closes on a press outside it, and that press does not go on to click what lies under it: the tap\n * that closes is only a tap that closes (a mail app does the same), it does not open another row or press a\n * button. Turn it off to let the click through after the row has closed. A click on the open row itself never\n * reaches its content: it closes the row.\n * Открытая строка закрывается нажатием вне неё, и это нажатие не становится кликом по тому, что под пальцем:\n * тап «закрыть» только закрывает (как в почтовом приложении), он не открывает другую строку и не жмёт кнопку.\n * Выключите, чтобы после закрытия клик проходил. Клик по самой открытой строке до её содержимого не доходит:\n * он закрывает строку.\n */\n swallowOutsideClick?: boolean;\n }>(),\n { start: undefined, end: () => [], actionWidth: 76, fullSwipe: true, mouse: false, disabled: false, tabbable: true, swallowOutsideClick: true },\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 по строке: он не должен открывать элемент\n// an open row: a click on it only closes it, it does not open the item hidden under the sliver that is left\n// открытая строка: клик по ней только закрывает её, а не открывает элемент под оставшейся полоской\nfunction onClickCapture(e: MouseEvent) {\n if (swiped) {\n e.stopPropagation();\n e.preventDefault();\n swiped = false;\n } else if (open.value) {\n e.stopPropagation();\n e.preventDefault();\n open.value = 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 and only its side (Tab from the start action to an\n// end one used to keep the start shown, which wins, and the focused button stayed hidden under the row); the focus on\n// the row's own content shows neither\n// клавиатура: кнопка действия, получившая фокус, показывает свою сторону и только её (Tab с левого действия на правое\n// оставлял показанной левую сторону, а она главнее, и кнопка с фокусом пряталась под строкой); фокус на содержимом\n// строки не показывает ни одну\n\nfunction onFocusIn(e: FocusEvent) {\n const side = (e.target as HTMLElement).closest<HTMLElement>('[data-side]')?.dataset.side;\n startShown.value = side === 'start';\n open.value = side === 'end';\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, and the click that follows that touch is swallowed once\n// открытая строка закрывается касанием вне её, а клик, идущий за этим касанием, гасится один раз\nconst SWALLOW_MS = 600;\nlet swallowTimer: ReturnType<typeof setTimeout> | undefined;\n\nfunction disarmSwallow() {\n document.removeEventListener('click', swallowClick, true);\n clearTimeout(swallowTimer);\n}\n\nfunction swallowClick(e: MouseEvent) {\n disarmSwallow();\n if (root.value?.contains(e.target as Node)) return;\n e.stopImmediatePropagation();\n e.preventDefault();\n}\n\nfunction onOutside(e: PointerEvent) {\n if (root.value?.contains(e.target as Node)) return;\n open.value = false;\n if (!props.swallowOutsideClick) return;\n // a press that is a scroll or a long press gives no click: the guard goes away by itself\n // нажатие, ставшее прокруткой или долгим, клика не даёт: охрана снимается сама\n disarmSwallow();\n document.addEventListener('click', swallowClick, true);\n swallowTimer = setTimeout(disarmSwallow, SWALLOW_MS);\n}\nwatch(\n open,\n (isOpen) => {\n if (isOpen) document.addEventListener('pointerdown', onOutside, true);\n else document.removeEventListener('pointerdown', onOutside, true);\n },\n { immediate: 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 disarmSwallow();\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, 'tx-swipe--mouse': mouse }\"\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 :tabindex=\"tabbable ? undefined : -1\"\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 :tabindex=\"tabbable ? undefined : -1\"\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/*\n * Variables, on the row or on any element around it (the defaults stand in var(), so an ancestor's value reaches here):\n * --tx-swipe-bg the face of the row and the ground its actions are tinted on (the raised surface; a row right on\n * the page: var(--tao-color-bg))\n * --tx-swipe-radius the corners of the row (the panel radius)\n * --tx-swipe-gap the gap between the end actions (6px)\n * Переменные — на строке или на любом элементе вокруг неё (значения по умолчанию стоят в var(), поэтому значение предка\n * доходит сюда): --tx-swipe-bg — лицо строки и основа подкраски действий; --tx-swipe-radius — углы; --tx-swipe-gap —\n * зазор между действиями справа.\n */\n.tx-swipe {\n /* a stacking context of its own: the z-index of the face counts inside the row only, so a floating bar or a glass\n panel over the list stays over its rows\n свой контекст наложения: z-index лица действует только внутри строки, поэтому плавающая панель или стекло над\n списком остаются поверх его строк */\n isolation: isolate;\n --_tx-swipe-gap: var(--tx-swipe-gap, 6px);\n --_tx-swipe-radius: var(--tx-swipe-radius, var(--tao-radius-panel, 12px));\n --_tx-swipe-bg: var(--tx-swipe-bg, var(--tao-color-surface-raised, #1f1f1f));\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(--_tx-swipe-bg);\n transition: transform 0.22s ease;\n}\n\n.tx-swipe--dragging .tx-swipe__front {\n transition: none;\n}\n\n/* a pull is not a selection: while it runs nothing is selected; with `mouse` the mouse drags the row, so its text is\n not selected by a press-and-move at all (a finger selects with a long press, which a swipe is not)\n протяжка — не выделение: пока она идёт, ничего не выделяется; с `mouse` мышь тянет строку, поэтому её текст не\n выделяется нажатием с движением вовсе (палец выделяет долгим нажатием, а свайп им не является) */\n.tx-swipe--dragging,\n.tx-swipe--mouse .tx-swipe__front {\n -webkit-user-select: none;\n user-select: 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 /* a button, not text: a press or a pull over it selects nothing and calls no callout\n кнопка, а не текст: нажатие или протяжка по ней ничего не выделяет и не вызывает меню */\n -webkit-user-select: none;\n user-select: none;\n -webkit-touch-callout: none;\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(--_tx-swipe-bg));\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(--_tx-swipe-bg));\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,CA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;I,IAEhBG,WAAQ,KAAA,QAAA,SAAA,C"}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A step of a tour. Only `id` is required: the rest (a target, a text, a placement) is yours, the model carries it.
|
|
3
|
+
* Шаг тура. Обязателен только `id`: остальное (цель, текст, место) ваше, модель его просто несёт.
|
|
4
|
+
*/
|
|
5
|
+
export interface TourStep {
|
|
6
|
+
id: string;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* How a tour ended: `done` (the last step was passed or `finish()`) or `skipped` (`skip()`, Esc, the cross).
|
|
10
|
+
* Как закончился тур: `done` (прошли последний шаг или `finish()`) или `skipped` (`skip()`, Esc, крестик).
|
|
11
|
+
*/
|
|
12
|
+
export type TourEnd = 'done' | 'skipped';
|
|
13
|
+
export interface TourState<S extends TourStep = TourStep> {
|
|
14
|
+
/** Whether a step is on screen. / Показан ли шаг. */
|
|
15
|
+
active: boolean;
|
|
16
|
+
/** The index of the current step in `steps` (-1 while not active). / Индекс текущего шага в `steps` (-1, пока тур не идёт). */
|
|
17
|
+
index: number;
|
|
18
|
+
/** The current step, or null. / Текущий шаг или null. */
|
|
19
|
+
step: S | null;
|
|
20
|
+
/** How many steps there are (also those that are jumped over now). / Сколько всего шагов (и тех, что сейчас перепрыгиваются). */
|
|
21
|
+
count: number;
|
|
22
|
+
/**
|
|
23
|
+
* The place of the current step among the steps that can be shown now, from 0, and how many of those there are: what
|
|
24
|
+
* a counter ("2 of 4") and the dots want, since the steps that are jumped over are not counted. `index` / `count`
|
|
25
|
+
* stay the place in the whole list.
|
|
26
|
+
* Место текущего шага среди шагов, которые можно показать сейчас, с 0, и сколько таких всего: то, что нужно счётчику
|
|
27
|
+
* («2 из 4») и точкам, ведь перепрыгиваемые шаги не считаются. `index` / `count` — место в полном списке.
|
|
28
|
+
*/
|
|
29
|
+
position: number;
|
|
30
|
+
total: number;
|
|
31
|
+
/** No step to go back to. / Назад идти некуда. */
|
|
32
|
+
first: boolean;
|
|
33
|
+
/** No step to go on to: `next()` ends the tour. / Дальше идти некуда: `next()` завершает тур. */
|
|
34
|
+
last: boolean;
|
|
35
|
+
}
|
|
36
|
+
export interface TourOptions<S extends TourStep = TourStep> {
|
|
37
|
+
steps: S[];
|
|
38
|
+
/**
|
|
39
|
+
* Whether a step can be shown now (its target is on the page, the user has the right). A step that cannot is
|
|
40
|
+
* jumped over, in either direction. Called at every move, so it may look at the page.
|
|
41
|
+
* Можно ли показать шаг сейчас (его цель есть на странице, у пользователя есть право). Шаг, который нельзя,
|
|
42
|
+
* перепрыгивается в обе стороны. Вызывается при каждом переходе, поэтому может смотреть на страницу.
|
|
43
|
+
*/
|
|
44
|
+
available?: (step: S, index: number) => boolean;
|
|
45
|
+
/** Called once when a tour ends. / Вызывается один раз, когда тур закончился. */
|
|
46
|
+
onEnd?: (reason: TourEnd, step: S | null) => void;
|
|
47
|
+
}
|
|
48
|
+
export interface Tour<S extends TourStep = TourStep> extends TourState<S> {
|
|
49
|
+
/**
|
|
50
|
+
* Starts at step `at` (an index or an `id`; the first by default). If that step cannot be shown, the next one
|
|
51
|
+
* that can is taken. Returns false, and nothing starts, when there is no such step.
|
|
52
|
+
* Начинает с шага `at` (индекс или `id`; по умолчанию первый). Если его нельзя показать, берётся ближайший
|
|
53
|
+
* следующий, который можно. Возвращает false, и ничего не начинается, если такого шага нет.
|
|
54
|
+
*/
|
|
55
|
+
start(at?: number | string): boolean;
|
|
56
|
+
/** The next step; from the last one it ends the tour as `done`. / Следующий шаг; с последнего завершает тур как `done`. */
|
|
57
|
+
next(): void;
|
|
58
|
+
/** The previous step; from the first one it stays. / Предыдущий шаг; с первого остаётся на месте. */
|
|
59
|
+
prev(): void;
|
|
60
|
+
/** Jumps to a step (an index or an `id`); false if it does not exist or cannot be shown. / Переход к шагу; false, если шага нет или его нельзя показать. */
|
|
61
|
+
goTo(target: number | string): boolean;
|
|
62
|
+
/** Ends the tour as `skipped`. / Завершает тур как `skipped`. */
|
|
63
|
+
skip(): void;
|
|
64
|
+
/** Ends the tour as `done`. / Завершает тур как `done`. */
|
|
65
|
+
finish(): void;
|
|
66
|
+
/**
|
|
67
|
+
* Replaces the steps. A tour that runs stays on the step with the same `id`, or, when it is gone, moves to the next
|
|
68
|
+
* one that can be shown, or ends as `done`.
|
|
69
|
+
* Заменяет шаги. Идущий тур остаётся на шаге с тем же `id`, а если его нет, переходит к ближайшему показываемому
|
|
70
|
+
* или завершается как `done`.
|
|
71
|
+
*/
|
|
72
|
+
setSteps(steps: S[]): void;
|
|
73
|
+
/** The listener is called on any change. Returns the unsubscribe function. / Слушатель вызывается при любом изменении. */
|
|
74
|
+
subscribe(listener: (state: TourState<S>) => void): () => void;
|
|
75
|
+
dispose(): void;
|
|
76
|
+
}
|
|
77
|
+
export declare function createTour<S extends TourStep = TourStep>(options: TourOptions<S>): Tour<S>;
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { type KeyStorage } from '../storage';
|
|
2
|
+
/**
|
|
3
|
+
* What a user has already seen of a tour, kept in localStorage under `key`, so a tour does not come back at every visit.
|
|
4
|
+
* Storage may be forbidden (private mode): then nothing is remembered and nothing throws.
|
|
5
|
+
* Что пользователь уже видел из тура; лежит в localStorage под ключом `key`, чтобы тур не возвращался при каждом визите.
|
|
6
|
+
* Хранилище может быть запрещено (приватный режим): тогда ничего не запоминается и ничего не бросает исключений.
|
|
7
|
+
*/
|
|
8
|
+
export interface TourMemory {
|
|
9
|
+
/** Whether the tour was ended (done or skipped) before. / Заканчивали ли тур раньше. */
|
|
10
|
+
seen(): boolean;
|
|
11
|
+
/** Remembers that the tour was ended. / Запоминает, что тур закончен. */
|
|
12
|
+
markSeen(): boolean;
|
|
13
|
+
/** Forgets it: the tour can show again ("show the tour once more" in a menu). / Забывает: тур снова можно показать. */
|
|
14
|
+
reset(): boolean;
|
|
15
|
+
}
|
|
16
|
+
export declare function createTourMemory(key: string, storage?: KeyStorage): TourMemory;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { type ToRefs } from 'vue';
|
|
2
|
+
import { type Tour, type TourOptions, type TourState, type TourStep } from './core';
|
|
3
|
+
export type UseTour<S extends TourStep = TourStep> = ToRefs<TourState<S>> & {
|
|
4
|
+
start: Tour<S>['start'];
|
|
5
|
+
next(): void;
|
|
6
|
+
prev(): void;
|
|
7
|
+
goTo: Tour<S>['goTo'];
|
|
8
|
+
skip(): void;
|
|
9
|
+
finish(): void;
|
|
10
|
+
setSteps(steps: S[]): void;
|
|
11
|
+
/**
|
|
12
|
+
* The model without Vue: for cases that need its full API (subscribe).
|
|
13
|
+
* Модель без Vue: для случаев, когда нужен её полный API (subscribe).
|
|
14
|
+
*/
|
|
15
|
+
tour: Tour<S>;
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* A tour for a Vue component: reactive state on top of `createTour`; it is let go on unmount.
|
|
19
|
+
* Тур для компонента Vue: реактивное состояние поверх `createTour`; при размонтировании отпускается.
|
|
20
|
+
*/
|
|
21
|
+
export declare function useTour<S extends TourStep = TourStep>(options: TourOptions<S>): UseTour<S>;
|
package/dist/tour.js
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import { createSavedStorage } from "./storage.js";
|
|
2
|
+
import { onBeforeUnmount, reactive, toRefs } from "vue";
|
|
3
|
+
//#region src/tour/core.ts
|
|
4
|
+
function createTour(options) {
|
|
5
|
+
let steps = [...options.steps];
|
|
6
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
7
|
+
let disposed = false;
|
|
8
|
+
const can = (i) => i >= 0 && i < steps.length && (options.available?.(steps[i], i) ?? true);
|
|
9
|
+
/** The nearest showable step from `from` (included) in a direction, or -1. / Ближайший показываемый шаг от `from` (включая его) или -1. */
|
|
10
|
+
function seek(from, dir) {
|
|
11
|
+
for (let i = from; i >= 0 && i < steps.length; i += dir) if (can(i)) return i;
|
|
12
|
+
return -1;
|
|
13
|
+
}
|
|
14
|
+
const tour = {
|
|
15
|
+
active: false,
|
|
16
|
+
index: -1,
|
|
17
|
+
step: null,
|
|
18
|
+
count: steps.length,
|
|
19
|
+
position: -1,
|
|
20
|
+
total: 0,
|
|
21
|
+
first: true,
|
|
22
|
+
last: true
|
|
23
|
+
};
|
|
24
|
+
function sync() {
|
|
25
|
+
tour.count = steps.length;
|
|
26
|
+
tour.step = tour.active ? steps[tour.index] ?? null : null;
|
|
27
|
+
let total = 0;
|
|
28
|
+
let position = -1;
|
|
29
|
+
for (let i = 0; i < steps.length; i++) {
|
|
30
|
+
if (!can(i)) continue;
|
|
31
|
+
if (i <= tour.index) position = tour.active ? total : -1;
|
|
32
|
+
total++;
|
|
33
|
+
}
|
|
34
|
+
tour.total = total;
|
|
35
|
+
tour.position = position;
|
|
36
|
+
tour.first = !tour.active || seek(tour.index - 1, -1) < 0;
|
|
37
|
+
tour.last = !tour.active || seek(tour.index + 1, 1) < 0;
|
|
38
|
+
}
|
|
39
|
+
function emit() {
|
|
40
|
+
sync();
|
|
41
|
+
const state = {
|
|
42
|
+
active: tour.active,
|
|
43
|
+
index: tour.index,
|
|
44
|
+
step: tour.step,
|
|
45
|
+
count: tour.count,
|
|
46
|
+
position: tour.position,
|
|
47
|
+
total: tour.total,
|
|
48
|
+
first: tour.first,
|
|
49
|
+
last: tour.last
|
|
50
|
+
};
|
|
51
|
+
for (const listener of [...listeners]) listener(state);
|
|
52
|
+
}
|
|
53
|
+
function end(reason) {
|
|
54
|
+
if (!tour.active) return;
|
|
55
|
+
const last = steps[tour.index] ?? null;
|
|
56
|
+
tour.active = false;
|
|
57
|
+
tour.index = -1;
|
|
58
|
+
emit();
|
|
59
|
+
options.onEnd?.(reason, last);
|
|
60
|
+
}
|
|
61
|
+
const indexOf = (target) => typeof target === "string" ? steps.findIndex((s) => s.id === target) : target;
|
|
62
|
+
function show(index) {
|
|
63
|
+
tour.active = true;
|
|
64
|
+
tour.index = index;
|
|
65
|
+
emit();
|
|
66
|
+
}
|
|
67
|
+
tour.start = (at = 0) => {
|
|
68
|
+
if (disposed) return false;
|
|
69
|
+
const from = indexOf(at);
|
|
70
|
+
const found = from < 0 ? -1 : seek(from, 1);
|
|
71
|
+
if (found < 0) return false;
|
|
72
|
+
show(found);
|
|
73
|
+
return true;
|
|
74
|
+
};
|
|
75
|
+
tour.next = () => {
|
|
76
|
+
if (!tour.active) return;
|
|
77
|
+
const found = seek(tour.index + 1, 1);
|
|
78
|
+
if (found < 0) end("done");
|
|
79
|
+
else show(found);
|
|
80
|
+
};
|
|
81
|
+
tour.prev = () => {
|
|
82
|
+
if (!tour.active) return;
|
|
83
|
+
const found = seek(tour.index - 1, -1);
|
|
84
|
+
if (found >= 0) show(found);
|
|
85
|
+
};
|
|
86
|
+
tour.goTo = (target) => {
|
|
87
|
+
const i = indexOf(target);
|
|
88
|
+
if (!tour.active || !can(i)) return false;
|
|
89
|
+
show(i);
|
|
90
|
+
return true;
|
|
91
|
+
};
|
|
92
|
+
tour.skip = () => end("skipped");
|
|
93
|
+
tour.finish = () => end("done");
|
|
94
|
+
tour.setSteps = (next) => {
|
|
95
|
+
const id = tour.step?.id;
|
|
96
|
+
const following = steps.slice(tour.index + 1).map((s) => s.id);
|
|
97
|
+
steps = [...next];
|
|
98
|
+
if (!tour.active) {
|
|
99
|
+
emit();
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
const same = id === void 0 ? -1 : steps.findIndex((s) => s.id === id);
|
|
103
|
+
let found = same >= 0 && can(same) ? same : same >= 0 ? seek(same + 1, 1) : -1;
|
|
104
|
+
for (const nextId of same >= 0 ? [] : following) {
|
|
105
|
+
const at = steps.findIndex((s) => s.id === nextId);
|
|
106
|
+
if (found < 0 && at >= 0 && can(at)) found = at;
|
|
107
|
+
}
|
|
108
|
+
if (found < 0) end("done");
|
|
109
|
+
else show(found);
|
|
110
|
+
};
|
|
111
|
+
tour.subscribe = (listener) => {
|
|
112
|
+
listeners.add(listener);
|
|
113
|
+
return () => listeners.delete(listener);
|
|
114
|
+
};
|
|
115
|
+
tour.dispose = () => {
|
|
116
|
+
disposed = true;
|
|
117
|
+
tour.active = false;
|
|
118
|
+
tour.index = -1;
|
|
119
|
+
listeners.clear();
|
|
120
|
+
sync();
|
|
121
|
+
};
|
|
122
|
+
sync();
|
|
123
|
+
return tour;
|
|
124
|
+
}
|
|
125
|
+
//#endregion
|
|
126
|
+
//#region src/tour/memory.ts
|
|
127
|
+
function createTourMemory(key, storage = createSavedStorage(key)) {
|
|
128
|
+
return {
|
|
129
|
+
seen: () => storage.read() === "1",
|
|
130
|
+
markSeen: () => storage.write("1"),
|
|
131
|
+
reset: () => storage.remove()
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
//#endregion
|
|
135
|
+
//#region src/tour/use.ts
|
|
136
|
+
/**
|
|
137
|
+
* A tour for a Vue component: reactive state on top of `createTour`; it is let go on unmount.
|
|
138
|
+
* Тур для компонента Vue: реактивное состояние поверх `createTour`; при размонтировании отпускается.
|
|
139
|
+
*/
|
|
140
|
+
function useTour(options) {
|
|
141
|
+
const tour = createTour(options);
|
|
142
|
+
const state = reactive({
|
|
143
|
+
active: tour.active,
|
|
144
|
+
index: tour.index,
|
|
145
|
+
step: tour.step,
|
|
146
|
+
count: tour.count,
|
|
147
|
+
position: tour.position,
|
|
148
|
+
total: tour.total,
|
|
149
|
+
first: tour.first,
|
|
150
|
+
last: tour.last
|
|
151
|
+
});
|
|
152
|
+
const stop = tour.subscribe((s) => Object.assign(state, s));
|
|
153
|
+
onBeforeUnmount(() => {
|
|
154
|
+
stop();
|
|
155
|
+
tour.dispose();
|
|
156
|
+
});
|
|
157
|
+
return {
|
|
158
|
+
...toRefs(state),
|
|
159
|
+
start: tour.start,
|
|
160
|
+
next: tour.next,
|
|
161
|
+
prev: tour.prev,
|
|
162
|
+
goTo: tour.goTo,
|
|
163
|
+
skip: tour.skip,
|
|
164
|
+
finish: tour.finish,
|
|
165
|
+
setSteps: tour.setSteps,
|
|
166
|
+
tour
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
//#endregion
|
|
170
|
+
export { createTour, createTourMemory, useTour };
|
|
171
|
+
|
|
172
|
+
//# sourceMappingURL=tour.js.map
|
package/dist/tour.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tour.js","names":[],"sources":["../src/tour/core.ts","../src/tour/memory.ts","../src/tour/use.ts"],"sourcesContent":["/**\n * A step of a tour. Only `id` is required: the rest (a target, a text, a placement) is yours, the model carries it.\n * Шаг тура. Обязателен только `id`: остальное (цель, текст, место) ваше, модель его просто несёт.\n */\nexport interface TourStep {\n id: string;\n}\n\n/**\n * How a tour ended: `done` (the last step was passed or `finish()`) or `skipped` (`skip()`, Esc, the cross).\n * Как закончился тур: `done` (прошли последний шаг или `finish()`) или `skipped` (`skip()`, Esc, крестик).\n */\nexport type TourEnd = 'done' | 'skipped';\n\nexport interface TourState<S extends TourStep = TourStep> {\n /** Whether a step is on screen. / Показан ли шаг. */\n active: boolean;\n /** The index of the current step in `steps` (-1 while not active). / Индекс текущего шага в `steps` (-1, пока тур не идёт). */\n index: number;\n /** The current step, or null. / Текущий шаг или null. */\n step: S | null;\n /** How many steps there are (also those that are jumped over now). / Сколько всего шагов (и тех, что сейчас перепрыгиваются). */\n count: number;\n /**\n * The place of the current step among the steps that can be shown now, from 0, and how many of those there are: what\n * a counter (\"2 of 4\") and the dots want, since the steps that are jumped over are not counted. `index` / `count`\n * stay the place in the whole list.\n * Место текущего шага среди шагов, которые можно показать сейчас, с 0, и сколько таких всего: то, что нужно счётчику\n * («2 из 4») и точкам, ведь перепрыгиваемые шаги не считаются. `index` / `count` — место в полном списке.\n */\n position: number;\n total: number;\n /** No step to go back to. / Назад идти некуда. */\n first: boolean;\n /** No step to go on to: `next()` ends the tour. / Дальше идти некуда: `next()` завершает тур. */\n last: boolean;\n}\n\nexport interface TourOptions<S extends TourStep = TourStep> {\n steps: S[];\n /**\n * Whether a step can be shown now (its target is on the page, the user has the right). A step that cannot is\n * jumped over, in either direction. Called at every move, so it may look at the page.\n * Можно ли показать шаг сейчас (его цель есть на странице, у пользователя есть право). Шаг, который нельзя,\n * перепрыгивается в обе стороны. Вызывается при каждом переходе, поэтому может смотреть на страницу.\n */\n available?: (step: S, index: number) => boolean;\n /** Called once when a tour ends. / Вызывается один раз, когда тур закончился. */\n onEnd?: (reason: TourEnd, step: S | null) => void;\n}\n\nexport interface Tour<S extends TourStep = TourStep> extends TourState<S> {\n /**\n * Starts at step `at` (an index or an `id`; the first by default). If that step cannot be shown, the next one\n * that can is taken. Returns false, and nothing starts, when there is no such step.\n * Начинает с шага `at` (индекс или `id`; по умолчанию первый). Если его нельзя показать, берётся ближайший\n * следующий, который можно. Возвращает false, и ничего не начинается, если такого шага нет.\n */\n start(at?: number | string): boolean;\n /** The next step; from the last one it ends the tour as `done`. / Следующий шаг; с последнего завершает тур как `done`. */\n next(): void;\n /** The previous step; from the first one it stays. / Предыдущий шаг; с первого остаётся на месте. */\n prev(): void;\n /** Jumps to a step (an index or an `id`); false if it does not exist or cannot be shown. / Переход к шагу; false, если шага нет или его нельзя показать. */\n goTo(target: number | string): boolean;\n /** Ends the tour as `skipped`. / Завершает тур как `skipped`. */\n skip(): void;\n /** Ends the tour as `done`. / Завершает тур как `done`. */\n finish(): void;\n /**\n * Replaces the steps. A tour that runs stays on the step with the same `id`, or, when it is gone, moves to the next\n * one that can be shown, or ends as `done`.\n * Заменяет шаги. Идущий тур остаётся на шаге с тем же `id`, а если его нет, переходит к ближайшему показываемому\n * или завершается как `done`.\n */\n setSteps(steps: S[]): void;\n /** The listener is called on any change. Returns the unsubscribe function. / Слушатель вызывается при любом изменении. */\n subscribe(listener: (state: TourState<S>) => void): () => void;\n dispose(): void;\n}\n\nexport function createTour<S extends TourStep = TourStep>(options: TourOptions<S>): Tour<S> {\n let steps = [...options.steps];\n const listeners = new Set<(state: TourState<S>) => void>();\n let disposed = false;\n\n const can = (i: number) => i >= 0 && i < steps.length && (options.available?.(steps[i]!, i) ?? true);\n\n /** The nearest showable step from `from` (included) in a direction, or -1. / Ближайший показываемый шаг от `from` (включая его) или -1. */\n function seek(from: number, dir: 1 | -1): number {\n for (let i = from; i >= 0 && i < steps.length; i += dir) {\n if (can(i)) {\n return i;\n }\n }\n return -1;\n }\n\n const tour = {\n active: false,\n index: -1,\n step: null as S | null,\n count: steps.length,\n position: -1,\n total: 0,\n first: true,\n last: true,\n } as Tour<S>;\n\n function sync() {\n tour.count = steps.length;\n tour.step = tour.active ? (steps[tour.index] ?? null) : null;\n let total = 0;\n let position = -1;\n for (let i = 0; i < steps.length; i++) {\n if (!can(i)) continue;\n if (i <= tour.index) position = tour.active ? total : -1;\n total++;\n }\n tour.total = total;\n tour.position = position;\n tour.first = !tour.active || seek(tour.index - 1, -1) < 0;\n tour.last = !tour.active || seek(tour.index + 1, 1) < 0;\n }\n\n function emit() {\n sync();\n const state: TourState<S> = { active: tour.active, index: tour.index, step: tour.step, count: tour.count, position: tour.position, total: tour.total, first: tour.first, last: tour.last };\n for (const listener of [...listeners]) {\n listener(state);\n }\n }\n\n function end(reason: TourEnd) {\n if (!tour.active) {\n return;\n }\n const last = steps[tour.index] ?? null;\n tour.active = false;\n tour.index = -1;\n emit();\n options.onEnd?.(reason, last);\n }\n\n const indexOf = (target: number | string) => (typeof target === 'string' ? steps.findIndex((s) => s.id === target) : target);\n\n function show(index: number) {\n tour.active = true;\n tour.index = index;\n emit();\n }\n\n tour.start = (at = 0) => {\n if (disposed) {\n return false;\n }\n const from = indexOf(at);\n const found = from < 0 ? -1 : seek(from, 1);\n if (found < 0) {\n return false;\n }\n show(found);\n return true;\n };\n\n tour.next = () => {\n if (!tour.active) {\n return;\n }\n const found = seek(tour.index + 1, 1);\n if (found < 0) {\n end('done');\n } else {\n show(found);\n }\n };\n\n tour.prev = () => {\n if (!tour.active) {\n return;\n }\n const found = seek(tour.index - 1, -1);\n if (found >= 0) {\n show(found);\n }\n };\n\n tour.goTo = (target) => {\n const i = indexOf(target);\n if (!tour.active || !can(i)) {\n return false;\n }\n show(i);\n return true;\n };\n\n tour.skip = () => end('skipped');\n tour.finish = () => end('done');\n\n tour.setSteps = (next) => {\n const id = tour.step?.id;\n // the steps after the current one, in the old order: where to go when the current one is gone\n // шаги после текущего в старом порядке: куда идти, если текущий пропал\n const following = steps.slice(tour.index + 1).map((s) => s.id);\n steps = [...next];\n if (!tour.active) {\n emit();\n return;\n }\n const same = id === undefined ? -1 : steps.findIndex((s) => s.id === id);\n let found = same >= 0 && can(same) ? same : same >= 0 ? seek(same + 1, 1) : -1;\n for (const nextId of same >= 0 ? [] : following) {\n const at = steps.findIndex((s) => s.id === nextId);\n if (found < 0 && at >= 0 && can(at)) {\n found = at;\n }\n }\n if (found < 0) {\n end('done');\n } else {\n show(found);\n }\n };\n\n tour.subscribe = (listener) => {\n listeners.add(listener);\n return () => listeners.delete(listener);\n };\n\n tour.dispose = () => {\n disposed = true;\n tour.active = false;\n tour.index = -1;\n listeners.clear();\n sync();\n };\n\n sync();\n return tour;\n}\n","import { createSavedStorage, type KeyStorage } from '../storage';\n\n/**\n * What a user has already seen of a tour, kept in localStorage under `key`, so a tour does not come back at every visit.\n * Storage may be forbidden (private mode): then nothing is remembered and nothing throws.\n * Что пользователь уже видел из тура; лежит в localStorage под ключом `key`, чтобы тур не возвращался при каждом визите.\n * Хранилище может быть запрещено (приватный режим): тогда ничего не запоминается и ничего не бросает исключений.\n */\nexport interface TourMemory {\n /** Whether the tour was ended (done or skipped) before. / Заканчивали ли тур раньше. */\n seen(): boolean;\n /** Remembers that the tour was ended. / Запоминает, что тур закончен. */\n markSeen(): boolean;\n /** Forgets it: the tour can show again (\"show the tour once more\" in a menu). / Забывает: тур снова можно показать. */\n reset(): boolean;\n}\n\nexport function createTourMemory(key: string, storage: KeyStorage = createSavedStorage(key)): TourMemory {\n return {\n seen: () => storage.read() === '1',\n markSeen: () => storage.write('1'),\n reset: () => storage.remove(),\n };\n}\n","import { onBeforeUnmount, reactive, toRefs, type ToRefs } from 'vue';\nimport { createTour, type Tour, type TourOptions, type TourState, type TourStep } from './core';\n\nexport type UseTour<S extends TourStep = TourStep> = ToRefs<TourState<S>> & {\n start: Tour<S>['start'];\n next(): void;\n prev(): void;\n goTo: Tour<S>['goTo'];\n skip(): void;\n finish(): void;\n setSteps(steps: S[]): void;\n /**\n * The model without Vue: for cases that need its full API (subscribe).\n * Модель без Vue: для случаев, когда нужен её полный API (subscribe).\n */\n tour: Tour<S>;\n};\n\n/**\n * A tour for a Vue component: reactive state on top of `createTour`; it is let go on unmount.\n * Тур для компонента Vue: реактивное состояние поверх `createTour`; при размонтировании отпускается.\n */\nexport function useTour<S extends TourStep = TourStep>(options: TourOptions<S>): UseTour<S> {\n const tour = createTour(options);\n const state = reactive({ active: tour.active, index: tour.index, step: tour.step, count: tour.count, position: tour.position, total: tour.total, first: tour.first, last: tour.last }) as TourState<S>;\n const stop = tour.subscribe((s) => Object.assign(state, s));\n onBeforeUnmount(() => {\n stop();\n tour.dispose();\n });\n\n return {\n ...toRefs(state),\n start: tour.start,\n next: tour.next,\n prev: tour.prev,\n goTo: tour.goTo,\n skip: tour.skip,\n finish: tour.finish,\n setSteps: tour.setSteps,\n tour,\n } as UseTour<S>;\n}\n"],"mappings":";;;AAiFA,SAAgB,WAA0C,SAAkC;CACxF,IAAI,QAAQ,CAAC,GAAG,QAAQ,KAAK;CAC7B,MAAM,4BAAY,IAAI,IAAmC;CACzD,IAAI,WAAW;CAEf,MAAM,OAAO,MAAc,KAAK,KAAK,IAAI,MAAM,WAAW,QAAQ,YAAY,MAAM,IAAK,CAAC,KAAK;;CAG/F,SAAS,KAAK,MAAc,KAAqB;EAC7C,KAAK,IAAI,IAAI,MAAM,KAAK,KAAK,IAAI,MAAM,QAAQ,KAAK,KAChD,IAAI,IAAI,CAAC,GACL,OAAO;EAGf,OAAO;CACX;CAEA,MAAM,OAAO;EACT,QAAQ;EACR,OAAO;EACP,MAAM;EACN,OAAO,MAAM;EACb,UAAU;EACV,OAAO;EACP,OAAO;EACP,MAAM;CACV;CAEA,S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;EAC3B,UAAU,IAAI,QAAQ;EACtB,aAAa,UAAU,OAAO,QAAQ;CAC1C;CAEA,KAAK,gBAAgB;EACjB,WAAW;EACX,KAAK,SAAS;EACd,KAAK,QAAQ;EACb,UAAU,MAAM;EAChB,KAAK;CACT;CAEA,KAAK;CACL,OAAO;AACX;;;AC9NA,SAAgB,iBAAiB,KAAa,UAAsB,mBAAmB,GAAG,GAAe;CACrG,OAAO;EACH,YAAY,QAAQ,KAAK,MAAM;EAC/B,gBAAgB,QAAQ,MAAM,GAAG;EACjC,aAAa,QAAQ,OAAO;CAChC;AACJ;;;;;;;ACDA,SAAgB,QAAuC,SAAqC;CACxF,MAAM,OAAO,WAAW,OAAO;CAC/B,MAAM,QAAQ,SAAS;EAAE,QAAQ,KAAK;EAAQ,OAAO,KAAK;EAAO,MAAM,KAAK;EAAM,OAAO,KAAK;EAAO,UAAU,KAAK;EAAU,OAAO,KAAK;EAAO,OAAO,KAAK;EAAO,MAAM,KAAK;CAAK,CAAC;CACrL,MAAM,OAAO,KAAK,WAAW,MAAM,OAAO,OAAO,OAAO,CAAC,CAAC;CAC1D,sBAAsB;EAClB,KAAK;EACL,KAAK,QAAQ;CACjB,CAAC;CAED,OAAO;EACH,GAAG,OAAO,KAAK;EACf,OAAO,KAAK;EACZ,MAAM,KAAK;EACX,MAAM,KAAK;EACX,MAAM,KAAK;EACX,MAAM,KAAK;EACX,QAAQ,KAAK;EACb,UAAU,KAAK;EACf;CACJ;AACJ"}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { type Ref } from 'vue';
|
|
2
|
+
import { History } from './history';
|
|
3
|
+
import { UndoStack, type UndoEntry, type UndoOptions } from './undo';
|
|
4
|
+
/**
|
|
5
|
+
* Undo and redo for Vue: the flags of a stack or a history as refs, so that the Undo and Redo items of a menu
|
|
6
|
+
* (`historyCommands`, `TaoMenubar`) switch on and off by themselves. `UndoStack` and `History` are plain classes: their
|
|
7
|
+
* `canUndo` is a getter that Vue cannot see, so each of these keeps the refs in step after every move.
|
|
8
|
+
* Undo и redo для Vue: флаги стека или истории как ref, чтобы пункты «Отменить» и «Повторить» в меню (`historyCommands`,
|
|
9
|
+
* `TaoMenubar`) включались и гасли сами. `UndoStack` и `History` — обычные классы: их `canUndo` — геттер, которого Vue
|
|
10
|
+
* не видит, поэтому здесь ref-ы выравниваются после каждого хода.
|
|
11
|
+
*/
|
|
12
|
+
/** Anything with the two flags: an `UndoStack`, a `History`, your own. / Всё, у чего есть два флага: `UndoStack`, `History`, своё. */
|
|
13
|
+
export interface UndoFlagsSource {
|
|
14
|
+
readonly canUndo: boolean;
|
|
15
|
+
readonly canRedo: boolean;
|
|
16
|
+
}
|
|
17
|
+
export interface UndoFlags {
|
|
18
|
+
readonly canUndo: Readonly<Ref<boolean>>;
|
|
19
|
+
readonly canRedo: Readonly<Ref<boolean>>;
|
|
20
|
+
/**
|
|
21
|
+
* Reads the source again. Call it after a move you made on the source itself, behind the back of the wrapper.
|
|
22
|
+
* Читает источник заново. Зовите после хода, сделанного на самом источнике, мимо обёртки.
|
|
23
|
+
*/
|
|
24
|
+
sync(): void;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Refs for a stack or a history you already have (made by a factory of yours, kept in a store). Nothing is moved by it:
|
|
28
|
+
* call `sync()` after every `record`, `undo`, `redo`, `commit`, `clear`.
|
|
29
|
+
* Ref-ы для стека или истории, которые у вас уже есть (сделаны вашей фабрикой, лежат в хранилище). Сам ничего не двигает:
|
|
30
|
+
* зовите `sync()` после каждого `record`, `undo`, `redo`, `commit`, `clear`.
|
|
31
|
+
*/
|
|
32
|
+
export declare function useUndoFlags(source: UndoFlagsSource): UndoFlags;
|
|
33
|
+
export interface UseUndoStack<T> extends UndoFlags {
|
|
34
|
+
/** The stack itself, for what the wrapper does not cover. / Сам стек, для того, что обёртка не покрывает. */
|
|
35
|
+
stack: UndoStack<T>;
|
|
36
|
+
/** `UndoStack.record`, then the flags. / `UndoStack.record`, затем флаги. */
|
|
37
|
+
record(entry: UndoEntry<T>, key?: string, now?: number): void;
|
|
38
|
+
/** `UndoStack.undo`: the next list or null; the flags follow. / `UndoStack.undo`: следующий список или null; флаги следуют. */
|
|
39
|
+
undo(current: readonly T[], now?: number): T[] | null;
|
|
40
|
+
redo(current: readonly T[], now?: number): T[] | null;
|
|
41
|
+
clear(): void;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* An `UndoStack` with reactive flags: options make a new one, or pass a stack you already have. The moves go through
|
|
45
|
+
* the wrapper, so the flags are always right.
|
|
46
|
+
* `UndoStack` с реактивными флагами: опции создают новый, либо передайте готовый стек. Ходы идут через обёртку,
|
|
47
|
+
* поэтому флаги всегда верны.
|
|
48
|
+
*/
|
|
49
|
+
export declare function useUndoStack<T>(from: UndoOptions<T> | UndoStack<T>): UseUndoStack<T>;
|
|
50
|
+
export interface UseHistory extends UndoFlags {
|
|
51
|
+
/** The history itself. / Сама история. */
|
|
52
|
+
history: History;
|
|
53
|
+
/** `History.commit`: false when the state did not change; the flags follow. / `History.commit`: false, если состояние не изменилось. */
|
|
54
|
+
commit(state: string, key?: string): boolean;
|
|
55
|
+
/** The previous state or null. It also fits `historyCommands` as a source. / Предыдущее состояние или null. */
|
|
56
|
+
undo(): string | null;
|
|
57
|
+
redo(): string | null;
|
|
58
|
+
/** Starts the history over (a file was loaded). / Начинает историю заново (загружен файл). */
|
|
59
|
+
reset(state: string): void;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* A `History` with reactive flags: an initial state makes a new one, or pass a history you already have.
|
|
63
|
+
* `History` с реактивными флагами: начальное состояние создаёт новую, либо передайте готовую историю.
|
|
64
|
+
*/
|
|
65
|
+
export declare function useHistory(from: string | History, limit?: number): UseHistory;
|
package/dist/undovue.js
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { History } from "./history.js";
|
|
2
|
+
import { UndoStack } from "./undo.js";
|
|
3
|
+
import { readonly, ref } from "vue";
|
|
4
|
+
//#region src/undovue.ts
|
|
5
|
+
/**
|
|
6
|
+
* Refs for a stack or a history you already have (made by a factory of yours, kept in a store). Nothing is moved by it:
|
|
7
|
+
* call `sync()` after every `record`, `undo`, `redo`, `commit`, `clear`.
|
|
8
|
+
* Ref-ы для стека или истории, которые у вас уже есть (сделаны вашей фабрикой, лежат в хранилище). Сам ничего не двигает:
|
|
9
|
+
* зовите `sync()` после каждого `record`, `undo`, `redo`, `commit`, `clear`.
|
|
10
|
+
*/
|
|
11
|
+
function useUndoFlags(source) {
|
|
12
|
+
const canUndo = ref(source.canUndo);
|
|
13
|
+
const canRedo = ref(source.canRedo);
|
|
14
|
+
function sync() {
|
|
15
|
+
canUndo.value = source.canUndo;
|
|
16
|
+
canRedo.value = source.canRedo;
|
|
17
|
+
}
|
|
18
|
+
return {
|
|
19
|
+
canUndo: readonly(canUndo),
|
|
20
|
+
canRedo: readonly(canRedo),
|
|
21
|
+
sync
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* An `UndoStack` with reactive flags: options make a new one, or pass a stack you already have. The moves go through
|
|
26
|
+
* the wrapper, so the flags are always right.
|
|
27
|
+
* `UndoStack` с реактивными флагами: опции создают новый, либо передайте готовый стек. Ходы идут через обёртку,
|
|
28
|
+
* поэтому флаги всегда верны.
|
|
29
|
+
*/
|
|
30
|
+
function useUndoStack(from) {
|
|
31
|
+
const stack = from instanceof UndoStack ? from : new UndoStack(from);
|
|
32
|
+
const flags = useUndoFlags(stack);
|
|
33
|
+
return {
|
|
34
|
+
...flags,
|
|
35
|
+
stack,
|
|
36
|
+
record(entry, key, now) {
|
|
37
|
+
stack.record(entry, key, now);
|
|
38
|
+
flags.sync();
|
|
39
|
+
},
|
|
40
|
+
undo(current, now) {
|
|
41
|
+
const next = stack.undo(current, now);
|
|
42
|
+
flags.sync();
|
|
43
|
+
return next;
|
|
44
|
+
},
|
|
45
|
+
redo(current, now) {
|
|
46
|
+
const next = stack.redo(current, now);
|
|
47
|
+
flags.sync();
|
|
48
|
+
return next;
|
|
49
|
+
},
|
|
50
|
+
clear() {
|
|
51
|
+
stack.clear();
|
|
52
|
+
flags.sync();
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* A `History` with reactive flags: an initial state makes a new one, or pass a history you already have.
|
|
58
|
+
* `History` с реактивными флагами: начальное состояние создаёт новую, либо передайте готовую историю.
|
|
59
|
+
*/
|
|
60
|
+
function useHistory(from, limit) {
|
|
61
|
+
const history = from instanceof History ? from : new History(from, limit);
|
|
62
|
+
const flags = useUndoFlags(history);
|
|
63
|
+
return {
|
|
64
|
+
...flags,
|
|
65
|
+
history,
|
|
66
|
+
commit(state, key) {
|
|
67
|
+
const changed = history.commit(state, key);
|
|
68
|
+
flags.sync();
|
|
69
|
+
return changed;
|
|
70
|
+
},
|
|
71
|
+
undo() {
|
|
72
|
+
const state = history.undo();
|
|
73
|
+
flags.sync();
|
|
74
|
+
return state;
|
|
75
|
+
},
|
|
76
|
+
redo() {
|
|
77
|
+
const state = history.redo();
|
|
78
|
+
flags.sync();
|
|
79
|
+
return state;
|
|
80
|
+
},
|
|
81
|
+
reset(state) {
|
|
82
|
+
history.reset(state);
|
|
83
|
+
flags.sync();
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
//#endregion
|
|
88
|
+
export { useHistory, useUndoFlags, useUndoStack };
|
|
89
|
+
|
|
90
|
+
//# sourceMappingURL=undovue.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"undovue.js","names":[],"sources":["../src/undovue.ts"],"sourcesContent":["import { readonly, ref, type Ref } from 'vue';\nimport { History } from './history';\nimport { UndoStack, type UndoEntry, type UndoOptions } from './undo';\n\n/**\n * Undo and redo for Vue: the flags of a stack or a history as refs, so that the Undo and Redo items of a menu\n * (`historyCommands`, `TaoMenubar`) switch on and off by themselves. `UndoStack` and `History` are plain classes: their\n * `canUndo` is a getter that Vue cannot see, so each of these keeps the refs in step after every move.\n * Undo и redo для Vue: флаги стека или истории как ref, чтобы пункты «Отменить» и «Повторить» в меню (`historyCommands`,\n * `TaoMenubar`) включались и гасли сами. `UndoStack` и `History` — обычные классы: их `canUndo` — геттер, которого Vue\n * не видит, поэтому здесь ref-ы выравниваются после каждого хода.\n */\n\n/** Anything with the two flags: an `UndoStack`, a `History`, your own. / Всё, у чего есть два флага: `UndoStack`, `History`, своё. */\nexport interface UndoFlagsSource {\n readonly canUndo: boolean;\n readonly canRedo: boolean;\n}\n\nexport interface UndoFlags {\n readonly canUndo: Readonly<Ref<boolean>>;\n readonly canRedo: Readonly<Ref<boolean>>;\n /**\n * Reads the source again. Call it after a move you made on the source itself, behind the back of the wrapper.\n * Читает источник заново. Зовите после хода, сделанного на самом источнике, мимо обёртки.\n */\n sync(): void;\n}\n\n/**\n * Refs for a stack or a history you already have (made by a factory of yours, kept in a store). Nothing is moved by it:\n * call `sync()` after every `record`, `undo`, `redo`, `commit`, `clear`.\n * Ref-ы для стека или истории, которые у вас уже есть (сделаны вашей фабрикой, лежат в хранилище). Сам ничего не двигает:\n * зовите `sync()` после каждого `record`, `undo`, `redo`, `commit`, `clear`.\n */\nexport function useUndoFlags(source: UndoFlagsSource): UndoFlags {\n const canUndo = ref(source.canUndo);\n const canRedo = ref(source.canRedo);\n function sync() {\n canUndo.value = source.canUndo;\n canRedo.value = source.canRedo;\n }\n return { canUndo: readonly(canUndo), canRedo: readonly(canRedo), sync };\n}\n\nexport interface UseUndoStack<T> extends UndoFlags {\n /** The stack itself, for what the wrapper does not cover. / Сам стек, для того, что обёртка не покрывает. */\n stack: UndoStack<T>;\n /** `UndoStack.record`, then the flags. / `UndoStack.record`, затем флаги. */\n record(entry: UndoEntry<T>, key?: string, now?: number): void;\n /** `UndoStack.undo`: the next list or null; the flags follow. / `UndoStack.undo`: следующий список или null; флаги следуют. */\n undo(current: readonly T[], now?: number): T[] | null;\n redo(current: readonly T[], now?: number): T[] | null;\n clear(): void;\n}\n\n/**\n * An `UndoStack` with reactive flags: options make a new one, or pass a stack you already have. The moves go through\n * the wrapper, so the flags are always right.\n * `UndoStack` с реактивными флагами: опции создают новый, либо передайте готовый стек. Ходы идут через обёртку,\n * поэтому флаги всегда верны.\n */\nexport function useUndoStack<T>(from: UndoOptions<T> | UndoStack<T>): UseUndoStack<T> {\n const stack = from instanceof UndoStack ? from : new UndoStack<T>(from);\n const flags = useUndoFlags(stack);\n return {\n ...flags,\n stack,\n record(entry, key, now) {\n stack.record(entry, key, now);\n flags.sync();\n },\n undo(current, now) {\n const next = stack.undo(current, now);\n flags.sync();\n return next;\n },\n redo(current, now) {\n const next = stack.redo(current, now);\n flags.sync();\n return next;\n },\n clear() {\n stack.clear();\n flags.sync();\n },\n };\n}\n\nexport interface UseHistory extends UndoFlags {\n /** The history itself. / Сама история. */\n history: History;\n /** `History.commit`: false when the state did not change; the flags follow. / `History.commit`: false, если состояние не изменилось. */\n commit(state: string, key?: string): boolean;\n /** The previous state or null. It also fits `historyCommands` as a source. / Предыдущее состояние или null. */\n undo(): string | null;\n redo(): string | null;\n /** Starts the history over (a file was loaded). / Начинает историю заново (загружен файл). */\n reset(state: string): void;\n}\n\n/**\n * A `History` with reactive flags: an initial state makes a new one, or pass a history you already have.\n * `History` с реактивными флагами: начальное состояние создаёт новую, либо передайте готовую историю.\n */\nexport function useHistory(from: string | History, limit?: number): UseHistory {\n const history = from instanceof History ? from : new History(from, limit);\n const flags = useUndoFlags(history);\n return {\n ...flags,\n history,\n commit(state, key) {\n const changed = history.commit(state, key);\n flags.sync();\n return changed;\n },\n undo() {\n const state = history.undo();\n flags.sync();\n return state;\n },\n redo() {\n const state = history.redo();\n flags.sync();\n return state;\n },\n reset(state) {\n history.reset(state);\n flags.sync();\n },\n };\n}\n"],"mappings":";;;;;;;;;;AAmCA,SAAgB,aAAa,QAAoC;CAC7D,MAAM,UAAU,IAAI,OAAO,OAAO;CAClC,MAAM,UAAU,IAAI,OAAO,OAAO;C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oux",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.0",
|
|
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",
|
|
@@ -148,6 +148,14 @@
|
|
|
148
148
|
"types": "./dist/touch.d.ts",
|
|
149
149
|
"import": "./dist/touch.js"
|
|
150
150
|
},
|
|
151
|
+
"./tour": {
|
|
152
|
+
"types": "./dist/tour/index.d.ts",
|
|
153
|
+
"import": "./dist/tour.js"
|
|
154
|
+
},
|
|
155
|
+
"./undovue": {
|
|
156
|
+
"types": "./dist/undovue.d.ts",
|
|
157
|
+
"import": "./dist/undovue.js"
|
|
158
|
+
},
|
|
151
159
|
"./undo": {
|
|
152
160
|
"types": "./dist/undo.d.ts",
|
|
153
161
|
"import": "./dist/undo.js"
|
|
@@ -185,7 +193,7 @@
|
|
|
185
193
|
}
|
|
186
194
|
},
|
|
187
195
|
"devDependencies": {
|
|
188
|
-
"@1337exp/taoui": "^5.
|
|
196
|
+
"@1337exp/taoui": "^5.25.0",
|
|
189
197
|
"@types/node": "^26.6.4",
|
|
190
198
|
"@vitejs/plugin-vue": "^6.0.10",
|
|
191
199
|
"@vue/test-utils": "^2.5.1",
|
package/skills/taoux/SKILL.md
CHANGED
|
@@ -27,7 +27,7 @@ controls, or with your own design.
|
|
|
27
27
|
| `camera` | pan, zoom around the cursor, screen ↔ world (`zoomAt`) |
|
|
28
28
|
| `history` | `new History(snapshot)`: undo / redo on string snapshots, rapid edits with one `key` merged into one step |
|
|
29
29
|
| `undo` | `new UndoStack({ id, revive, vanish? })`: undo / redo of a list of records by steps that keep only the touched ones (`diffRecords(prev, next, id)` makes a step; a returned record takes its old place); right for a list that is edited and synced, where `History` would store the whole list per step and an undo would roll back a sync. `coalesceMaxMs` caps a merged step of typing |
|
|
30
|
-
| `swiperow` | `<TaoxSwipeRow :start="{ id, label, icon, tone }" :end="[{ id, label, icon, tone }]" v-model:open @action="run">` around a list row: a pull to the start runs `start` past a threshold, to the end opens the actions, a long pull runs the last one (`fullSwipe`, on by default); a mouse drags only with `mouse`; `:tabbable="false"` takes the actions out of the Tab order when the app has its own keys for them; `--tx-swipe-bg` for a row right on the page (see docs/swiperow.md); import `@1337exp/taoux/swiperow.css`. Needs TaoUI (tier 2) |
|
|
30
|
+
| `swiperow` | `<TaoxSwipeRow :start="{ id, label, icon, tone }" :end="[{ id, label, icon, tone }]" v-model:open @action="run">` around a list row: a pull to the start runs `start` past a threshold, to the end opens the actions, a long pull runs the last one (`fullSwipe`, on by default); a mouse drags only with `mouse`; `:tabbable="false"` takes the actions out of the Tab order when the app has its own keys for them; an open row closes on a click on it or a press outside, and that click does not go on (once; `:swallow-outside-click="false"` lets the outside one through); `--tx-swipe-bg` for a row right on the page (see docs/swiperow.md); import `@1337exp/taoux/swiperow.css`. Needs TaoUI (tier 2) |
|
|
31
31
|
| `sortable` | `useSortable(listRef, { onMove: (from, to) => (list.value = moveItem(list.value, from, to)) })`; mark each item `data-sortable-item` and a focusable grip inside it `data-sortable-handle` (a TaoButton with `icon="tao-grip"` and an aria-label); style `[data-sortable-dragging]` / `[data-sortable-lifted]`. Keyboard: Space lifts, arrows move, Space drops, Esc returns; `texts: sortableTextsRu` for Russian |
|
|
32
32
|
| `session` | `createDocumentSession(...)`: history + autosave + files + restore + notices for one document; `canUndo` / `canRedo` refs. `camera` is optional (a list, not a canvas); count with `countItems` (`countNodes` is its old name) |
|
|
33
33
|
| `commands` | `createCommands([...])`: one registry for menus, shortcuts and palettes (see below) |
|
|
@@ -46,6 +46,8 @@ controls, or with your own design.
|
|
|
46
46
|
| `palette` | search and groups for a palette of nodes |
|
|
47
47
|
| `pins` | row pin positions measured from the DOM (`usePinMeasure`, `createPinRegistry`) |
|
|
48
48
|
| `playback` | time, pause, loop, speed, seeking: `createPlayback` (no Vue), `usePlayback` (drives TaoUI `TaoScrubber`) |
|
|
49
|
+
| `tour` | a guided tour of the page, step by step: `createTour` (no Vue; jumps over steps whose target is gone, `done` / `skipped`), `useTour`, `createTourMemory` (shown once); the drawing is up to you or TaoUI |
|
|
50
|
+
| `undovue` | `undo` and `history` for Vue: `useUndoStack`, `useHistory` (the same classes with `canUndo` / `canRedo` as refs, so the Undo / Redo menu items follow), `useUndoFlags(existing)` + `sync()` |
|
|
49
51
|
| `i18n` | typed i18n: `createI18n({ locales, fallback, storageKey })` |
|
|
50
52
|
| `links` (Vue) | `TaoxLinks`: an SVG layer of links from ready geometry |
|
|
51
53
|
| `canvas` (Vue) | `TaoxCanvas`: pan / zoom canvas with mouse, touch, wheel, auto-scroll, keys; the `CanvasHost` contract |
|