@1337exp/taoux 0.5.6 → 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 +10 -0
- package/README.md +4 -2
- package/README.ru.md +4 -2
- 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 +2 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,15 @@
|
|
|
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
|
+
|
|
3
13
|
## 0.5.6
|
|
4
14
|
|
|
5
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.
|
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
|
|
|
@@ -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,QAA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AAO,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;CAClC,SAAS,OAAO;EACZ,QAAQ,QAAQ,OAAO;EACvB,QAAQ,QAAQ,OAAO;CAC3B;CACA,OAAO;EAAE,SAAS,SAAS,OAAO;EAAG,SAAS,SAAS,OAAO;EAAG;CAAK;AAC1E;;;;;;;AAmBA,SAAgB,aAAgB,MAAsD;CAClF,MAAM,QAAQ,gBAAgB,YAAY,OAAO,IAAI,UAAa,IAAI;CACtE,MAAM,QAAQ,aAAa,KAAK;CAChC,OAAO;EACH,GAAG;EACH;EACA,OAAO,OAAO,KAAK,KAAK;GACpB,MAAM,OAAO,OAAO,KAAK,GAAG;GAC5B,MAAM,KAAK;EACf;EACA,KAAK,SAAS,KAAK;GACf,MAAM,OAAO,MAAM,KAAK,SAAS,GAAG;GACpC,MAAM,KAAK;GACX,OAAO;EACX;EACA,KAAK,SAAS,KAAK;GACf,MAAM,OAAO,MAAM,KAAK,SAAS,GAAG;GACpC,MAAM,KAAK;GACX,OAAO;EACX;EACA,QAAQ;GACJ,MAAM,MAAM;GACZ,MAAM,KAAK;EACf;CACJ;AACJ;;;;;AAkBA,SAAgB,WAAW,MAAwB,OAA4B;CAC3E,MAAM,UAAU,gBAAgB,UAAU,OAAO,IAAI,QAAQ,MAAM,KAAK;CACxE,MAAM,QAAQ,aAAa,OAAO;CAClC,OAAO;EACH,GAAG;EACH;EACA,OAAO,OAAO,KAAK;GACf,MAAM,UAAU,QAAQ,OAAO,OAAO,GAAG;GACzC,MAAM,KAAK;GACX,OAAO;EACX;EACA,OAAO;GACH,MAAM,QAAQ,QAAQ,KAAK;GAC3B,MAAM,KAAK;GACX,OAAO;EACX;EACA,OAAO;GACH,MAAM,QAAQ,QAAQ,KAAK;GAC3B,MAAM,KAAK;GACX,OAAO;EACX;EACA,MAAM,OAAO;GACT,QAAQ,MAAM,KAAK;GACnB,MAAM,KAAK;EACf;CACJ;AACJ"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@1337exp/taoux",
|
|
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
|
@@ -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 |
|