@1337exp/taoux 0.16.0 → 0.17.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.
@@ -1 +1 @@
1
- {"version":3,"file":"history.js","names":[],"sources":["../src/history.ts"],"sourcesContent":["/**\n * Edits with the same key made faster than this many ms apart merge into one entry (typing a number into a field and the like).\n * Правки с одним ключом, сделанные чаще чем раз в столько мс, склеиваются в одну запись (набор числа в поле и т.п.).\n */\nexport const COALESCE_MS = 800;\n\n/**\n * A history taken out of a `History` to be put back later: for an editor with several documents, each keeps its own.\n * It is plain data (strings and a number), so it can be stored anywhere.\n * История, вынутая из `History`, чтобы вернуть её позже: у редактора с несколькими документами у каждого своя.\n * Это простые данные (строки и число), их можно хранить где угодно.\n */\nexport interface HistoryState {\n states: readonly string[];\n index: number;\n}\n\n/**\n * Undo/redo state history: a linear list of snapshots and a pointer to the current one.\n * Snapshots are strings (graph JSON): they are immutable, easy to compare and need no copying.\n * История состояний для undo/redo: линейный список снимков и указатель на текущий.\n * Снимки — строки (JSON графа): они неизменяемы, их легко сравнивать и не нужно копировать.\n */\nexport class History {\n private states: string[];\n private index = 0;\n private lastKey: string | undefined;\n private lastTime = 0;\n\n constructor(\n initial: string,\n private readonly limit = 100,\n private readonly now: () => number = Date.now,\n ) {\n this.states = [initial];\n }\n\n get canUndo(): boolean {\n return this.index > 0;\n }\n\n get canRedo(): boolean {\n return this.index < this.states.length - 1;\n }\n\n /**\n * Records a new state. If it does not differ from the current one, does nothing (returns false).\n * An edit discards the \"future\" (redo). With the same `key` in a row and within `COALESCE_MS`,\n * edits replace each other instead of piling up.\n * Записывает новое состояние. Если оно не отличается от текущего, ничего не делает (вернёт false).\n * Правка отбрасывает «будущее» (redo). С одинаковым `key` подряд и в пределах `COALESCE_MS`\n * правки заменяют друг друга, а не копятся.\n */\n commit(state: string, key?: string): boolean {\n if (state === this.states[this.index]) return false;\n\n const t = this.now();\n const atTop = this.index === this.states.length - 1;\n const coalesce = key !== undefined && key === this.lastKey && t - this.lastTime <= COALESCE_MS && this.index > 0 && atTop;\n\n if (coalesce) {\n this.states[this.index] = state;\n // Back to the state before the series of edits: no entry is needed.\n // Вернулись к состоянию до серии правок: запись не нужна.\n if (this.states[this.index - 1] === state) {\n this.states.pop();\n this.index--;\n }\n } else {\n this.states.length = this.index + 1;\n this.states.push(state);\n this.index++;\n if (this.states.length > this.limit + 1) {\n this.states.shift();\n this.index--;\n }\n }\n\n this.lastKey = key;\n this.lastTime = t;\n return true;\n }\n\n /**\n * Returns the previous state, or null if there is nothing to undo.\n * Возвращает предыдущее состояние или null, если отменять нечего.\n */\n undo(): string | null {\n if (!this.canUndo) return null;\n this.lastKey = undefined;\n return this.states[--this.index]!;\n }\n\n redo(): string | null {\n if (!this.canRedo) return null;\n this.lastKey = undefined;\n return this.states[++this.index]!;\n }\n\n /**\n * A copy of the whole history (the snapshots and the position), to put back with `restore`.\n * Копия всей истории (снимки и положение), чтобы вернуть её через `restore`.\n */\n save(): HistoryState {\n return { states: [...this.states], index: this.index };\n }\n\n /**\n * Puts a saved history back. The current snapshot of it should be the state of the document the app shows now;\n * what is not (an index out of range, no snapshots) is refused with an error. A series of merged edits is not\n * continued across a restore.\n * Возвращает сохранённую историю. Текущий снимок в ней должен быть состоянием документа, который приложение показывает\n * сейчас; негодное (положение вне списка, нет снимков) отклоняется ошибкой. Серия склеенных правок через возврат не продолжается.\n */\n restore(state: HistoryState): void {\n if (!Number.isInteger(state.index) || state.index < 0 || state.index >= state.states.length) {\n throw new RangeError('History.restore: the position is outside the saved snapshots');\n }\n this.states = [...state.states];\n this.index = state.index;\n this.lastKey = undefined;\n }\n\n /**\n * Start the history over (for example, after loading a file).\n * Начать историю заново (например, после загрузки файла).\n */\n reset(state: string): void {\n this.states = [state];\n this.index = 0;\n this.lastKey = undefined;\n }\n}\n"],"mappings":";;;;;AAIA,IAAa,cAAc;;;;;;;AAmB3B,IAAa,UAAb,MAAqB;CAQI;CACA;CARrB;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CACzD;;;;;;;;CASA,QAAQ,OAA2B;EAC/B,IAAI,CAAC,OAAO,UAAU,MAAM,KAAK,KAAK,MAAM,QAAQ,KAAK,MAAM,SAAS,MAAM,OAAO,QACjF,MAAM,IAAI,WAAW,8DAA8D;EAEvF,KAAK,SAAS,CAAC,GAAG,MAAM,MAAM;EAC9B,KAAK,QAAQ,MAAM;EACnB,KAAK,UAAU,KAAA;CACnB;;;;;CAMA,MAAM,OAAqB;EACvB,KAAK,SAAS,CAAC,KAAK;EACpB,KAAK,QAAQ;EACb,KAAK,UAAU,KAAA;CACnB;AACJ"}
1
+ {"version":3,"file":"history.js","names":[],"sources":["../src/history.ts"],"sourcesContent":["/**\r\n * Edits with the same key made faster than this many ms apart merge into one entry (typing a number into a field and the like).\r\n * Правки с одним ключом, сделанные чаще чем раз в столько мс, склеиваются в одну запись (набор числа в поле и т.п.).\r\n */\r\nexport const COALESCE_MS = 800;\r\n\r\n/**\r\n * A history taken out of a `History` to be put back later: for an editor with several documents, each keeps its own.\r\n * It is plain data (strings and a number), so it can be stored anywhere.\r\n * История, вынутая из `History`, чтобы вернуть её позже: у редактора с несколькими документами у каждого своя.\r\n * Это простые данные (строки и число), их можно хранить где угодно.\r\n */\r\nexport interface HistoryState {\r\n states: readonly string[];\r\n index: number;\r\n /**\r\n * The label of the step that made each snapshot (the first has none), when the history has labels. A history saved before labels existed has none: it is put back unlabelled.\r\n * Подпись шага, который сделал каждый снимок (у первого её нет), если в истории есть подписи. История, сохранённая до подписей, их не имеет: возвращается без подписей.\r\n */\r\n labels?: readonly (string | undefined)[];\r\n /**\r\n * The snapshot marked saved by `markSaved()`, when it is not the first one (so a history that never saved is the plain data it always was). Without it `restore` takes the first snapshot as the saved one.\r\n * Снимок, отмеченный `markSaved()`, если это не первый снимок (так история, которая не сохранялась, остаётся теми же простыми данными). Без него `restore` считает сохранённым первый снимок.\r\n */\r\n saved?: string;\r\n}\r\n\r\nexport interface HistoryOptions {\r\n /**\r\n * How long, ms, edits with one key merge. `Infinity`: until `seal()` or another key, however long the pause (an editor that ends a drag itself). Default `COALESCE_MS`.\r\n * Сколько мс правки с одним ключом склеиваются. `Infinity`: до `seal()` или другого ключа, как бы долго ни длилась пауза (редактор, который сам заканчивает перетаскивание). По умолчанию `COALESCE_MS`.\r\n */\r\n coalesceMs?: number;\r\n}\r\n\r\n/**\r\n * Undo/redo state history: a linear list of snapshots and a pointer to the current one.\r\n * Snapshots are strings (graph JSON): they are immutable, easy to compare and need no copying.\r\n * История состояний для undo/redo: линейный список снимков и указатель на текущий.\r\n * Снимки — строки (JSON графа): они неизменяемы, их легко сравнивать и не нужно копировать.\r\n */\r\nexport class History {\r\n private states: string[];\r\n private labels: (string | undefined)[] = [undefined];\r\n private index = 0;\r\n private lastKey: string | undefined;\r\n private lastTime = 0;\r\n private saved: string;\r\n private readonly coalesceMs: number;\r\n\r\n constructor(\r\n initial: string,\r\n private readonly limit = 100,\r\n private readonly now: () => number = Date.now,\r\n options: HistoryOptions = {},\r\n ) {\r\n this.states = [initial];\r\n this.saved = initial;\r\n this.coalesceMs = options.coalesceMs ?? COALESCE_MS;\r\n }\r\n\r\n get canUndo(): boolean {\r\n return this.index > 0;\r\n }\r\n\r\n get canRedo(): boolean {\r\n return this.index < this.states.length - 1;\r\n }\r\n\r\n /**\r\n * The label of the step an undo would take back, or undefined (nothing to undo, or the step has no label).\r\n * Подпись шага, который отменит undo, или undefined (отменять нечего или у шага нет подписи).\r\n */\r\n get undoLabel(): string | undefined {\r\n return this.canUndo ? this.labels[this.index] : undefined;\r\n }\r\n\r\n /**\r\n * The label of the step a redo would bring back.\r\n * Подпись шага, который вернёт redo.\r\n */\r\n get redoLabel(): string | undefined {\r\n return this.canRedo ? this.labels[this.index + 1] : undefined;\r\n }\r\n\r\n /**\r\n * Whether the current snapshot differs from the one marked by `markSaved()` (the start, or the one `reset` began from). It follows the history: undoing back to the saved\r\n * snapshot is clean again.\r\n * Отличается ли текущий снимок от отмеченного `markSaved()` (начального или того, с которого начал `reset`). Следует за историей: откат до сохранённого снимка снова чист.\r\n */\r\n get dirty(): boolean {\r\n return this.states[this.index] !== this.saved;\r\n }\r\n\r\n /**\r\n * Marks the current snapshot as the saved one.\r\n * Отмечает текущий снимок сохранённым.\r\n */\r\n markSaved(): void {\r\n this.saved = this.states[this.index]!;\r\n }\r\n\r\n /**\r\n * Ends a series of merged edits: the next edit with the same key is a new step. An editor that knows where a gesture ends (a pointer was released, a field lost focus) calls it\r\n * there; one that does not leaves it to the time window.\r\n * Заканчивает серию склеенных правок: следующая правка с тем же ключом это новый шаг. Редактор, который знает, где кончается жест (отпустили указатель, поле потеряло фокус),\r\n * зовёт его там; тот, кто не знает, оставляет это окну времени.\r\n */\r\n seal(): void {\r\n this.lastKey = undefined;\r\n }\r\n\r\n /**\r\n * Records a new state. If it does not differ from the current one, does nothing (returns false).\r\n * An edit discards the \"future\" (redo). With the same `key` in a row and within `COALESCE_MS`,\r\n * edits replace each other instead of piling up.\r\n * Записывает новое состояние. Если оно не отличается от текущего, ничего не делает (вернёт false).\r\n * Правка отбрасывает «будущее» (redo). С одинаковым `key` подряд и в пределах `COALESCE_MS`\r\n * правки заменяют друг друга, а не копятся. `label` называет шаг (для «Отменить: …»); у склеенной серии подпись первой правки.\r\n * The `label` names the step (for \"Undo: …\"); a merged series keeps the label of its first edit.\r\n */\r\n commit(state: string, key?: string, label?: string): boolean {\r\n if (state === this.states[this.index]) return false;\r\n\r\n const t = this.now();\r\n const atTop = this.index === this.states.length - 1;\r\n const coalesce = key !== undefined && key === this.lastKey && t - this.lastTime <= this.coalesceMs && this.index > 0 && atTop;\r\n\r\n if (coalesce) {\r\n this.states[this.index] = state;\r\n // Back to the state before the series of edits: no entry is needed.\r\n // Вернулись к состоянию до серии правок: запись не нужна.\r\n if (this.states[this.index - 1] === state) {\r\n this.states.pop();\r\n this.labels.pop();\r\n this.index--;\r\n }\r\n } else {\r\n this.states.length = this.index + 1;\r\n this.labels.length = this.index + 1;\r\n this.states.push(state);\r\n this.labels.push(label);\r\n this.index++;\r\n if (this.states.length > this.limit + 1) {\r\n this.states.shift();\r\n this.labels.shift();\r\n this.index--;\r\n }\r\n }\r\n\r\n this.lastKey = key;\r\n this.lastTime = t;\r\n return true;\r\n }\r\n\r\n /**\r\n * Returns the previous state, or null if there is nothing to undo.\r\n * Возвращает предыдущее состояние или null, если отменять нечего.\r\n */\r\n undo(): string | null {\r\n if (!this.canUndo) return null;\r\n this.lastKey = undefined;\r\n return this.states[--this.index]!;\r\n }\r\n\r\n redo(): string | null {\r\n if (!this.canRedo) return null;\r\n this.lastKey = undefined;\r\n return this.states[++this.index]!;\r\n }\r\n\r\n /**\r\n * A copy of the whole history (the snapshots and the position), to put back with `restore`.\r\n * Копия всей истории (снимки и положение), чтобы вернуть её через `restore`.\r\n */\r\n save(): HistoryState {\r\n const state: HistoryState = { states: [...this.states], index: this.index };\r\n // only a history that has labels carries them, so one without is the plain data it always was / подписи несёт только история, у которой они есть, так что без них это те же простые данные, что и раньше\r\n const withLabels = this.labels.some(l => l !== undefined) ? { ...state, labels: [...this.labels] } : state;\r\n return this.saved !== this.states[0] ? { ...withLabels, saved: this.saved } : withLabels;\r\n }\r\n\r\n /**\r\n * Puts a saved history back. The current snapshot of it should be the state of the document the app shows now;\r\n * what is not (an index out of range, no snapshots) is refused with an error. A series of merged edits is not\r\n * continued across a restore.\r\n * Возвращает сохранённую историю. Текущий снимок в ней должен быть состоянием документа, который приложение показывает\r\n * сейчас; негодное (положение вне списка, нет снимков) отклоняется ошибкой. Серия склеенных правок через возврат не продолжается.\r\n */\r\n restore(state: HistoryState): void {\r\n if (!Number.isInteger(state.index) || state.index < 0 || state.index >= state.states.length) {\r\n throw new RangeError('History.restore: the position is outside the saved snapshots');\r\n }\r\n this.states = [...state.states];\r\n // a label that went through JSON is null, not undefined / подпись, прошедшая через JSON, это null, а не undefined\r\n this.labels = state.states.map((_, i) => state.labels?.[i] ?? undefined);\r\n this.index = state.index;\r\n this.saved = state.saved ?? state.states[0]!;\r\n this.lastKey = undefined;\r\n }\r\n\r\n /**\r\n * Start the history over (for example, after loading a file).\r\n * Начать историю заново (например, после загрузки файла).\r\n */\r\n reset(state: string): void {\r\n this.states = [state];\r\n this.labels = [undefined];\r\n this.saved = state;\r\n this.index = 0;\r\n this.lastKey = undefined;\r\n }\r\n}\r\n"],"mappings":";;;;;AAIA,IAAa,cAAc;;;;;;;AAqC3B,IAAa,UAAb,MAAqB;CAWI;CACA;CAXrB;CACA,SAAyC,CAAC,KAAA,CAAS;CACnD,QAAgB;CAChB;CACA,WAAmB;CACnB;CACA;CAEA,YACI,SACA,QAAyB,KACzB,MAAqC,KAAK,KAC1C,UAA0B,CAAC,GAC7B;EAHmB,KAAA,QAAA;EACA,KAAA,MAAA;EAGjB,KAAK,SAAS,CAAC,OAAO;EACtB,KAAK,QAAQ;EACb,KAAK,aAAa,QAAQ,cAAA;CAC9B;CAEA,IAAI,UAAmB;EACnB,OAAO,KAAK,QAAQ;CACxB;CAEA,IAAI,UAAmB;EACnB,OAAO,KAAK,QAAQ,KAAK,OAAO,SAAS;CAC7C;;;;;CAMA,IAAI,YAAgC;EAChC,OAAO,KAAK,UAAU,KAAK,OAAO,KAAK,SAAS,KAAA;CACpD;;;;;CAMA,IAAI,YAAgC;EAChC,OAAO,KAAK,UAAU,KAAK,OAAO,KAAK,QAAQ,KAAK,KAAA;CACxD;;;;;;CAOA,IAAI,QAAiB;EACjB,OAAO,KAAK,OAAO,KAAK,WAAW,KAAK;CAC5C;;;;;CAMA,YAAkB;EACd,KAAK,QAAQ,KAAK,OAAO,KAAK;CAClC;;;;;;;CAQA,OAAa;EACT,KAAK,UAAU,KAAA;CACnB;;;;;;;;;;CAWA,OAAO,OAAe,KAAc,OAAyB;EACzD,IAAI,UAAU,KAAK,OAAO,KAAK,QAAQ,OAAO;EAE9C,MAAM,IAAI,KAAK,IAAI;EACnB,MAAM,QAAQ,KAAK,UAAU,KAAK,OAAO,SAAS;EAGlD,IAFiB,QAAQ,KA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O,QACjF,MAAM,IAAI,WAAW,8DAA8D;EAEvF,KAAK,SAAS,CAAC,GAAG,MAAM,MAAM;EAE9B,KAAK,SAAS,MAAM,OAAO,KAAK,GAAG,MAAM,MAAM,SAAS,MAAM,KAAA,CAAS;EACvE,KAAK,QAAQ,MAAM;EACnB,KAAK,QAAQ,MAAM,SAAS,MAAM,OAAO;EACzC,KAAK,UAAU,KAAA;CACnB;;;;;CAMA,MAAM,OAAqB;EACvB,KAAK,SAAS,CAAC,KAAK;EACpB,KAAK,SAAS,CAAC,KAAA,CAAS;EACxB,KAAK,QAAQ;EACb,KAAK,QAAQ;EACb,KAAK,UAAU,KAAA;CACnB;AACJ"}
package/dist/undovue.d.ts CHANGED
@@ -50,8 +50,18 @@ export declare function useUndoStack<T>(from: UndoOptions<T> | UndoStack<T>): Us
50
50
  export interface UseHistory extends UndoFlags {
51
51
  /** The history itself. / Сама история. */
52
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;
53
+ /** The label of the step an undo would take back (`History.undoLabel`), as a ref. / Подпись шага, который отменит undo (`History.undoLabel`), как ref. */
54
+ readonly undoLabel: Readonly<Ref<string | undefined>>;
55
+ /** The label of the step a redo would bring back, as a ref. / Подпись шага, который вернёт redo, как ref. */
56
+ readonly redoLabel: Readonly<Ref<string | undefined>>;
57
+ /** `History.dirty` as a ref: the current snapshot is not the saved one. / `History.dirty` как ref: текущий снимок не сохранённый. */
58
+ readonly dirty: Readonly<Ref<boolean>>;
59
+ /** `History.commit`: false when the state did not change; the flags follow. `label` names the step. / `History.commit`: false, если состояние не изменилось; `label` называет шаг. */
60
+ commit(state: string, key?: string, label?: string): boolean;
61
+ /** `History.seal`: ends a series of merged edits. / `History.seal`: заканчивает серию склеенных правок. */
62
+ seal(): void;
63
+ /** `History.markSaved`; `dirty` follows. / `History.markSaved`; `dirty` следует. */
64
+ markSaved(): void;
55
65
  /** The previous state or null. It also fits `historyCommands` as a source. / Предыдущее состояние или null. */
56
66
  undo(): string | null;
57
67
  redo(): string | null;
package/dist/undovue.js CHANGED
@@ -60,27 +60,47 @@ function useUndoStack(from) {
60
60
  function useHistory(from, limit) {
61
61
  const history = from instanceof History ? from : new History(from, limit);
62
62
  const flags = useUndoFlags(history);
63
+ const undoLabel = ref(history.undoLabel);
64
+ const redoLabel = ref(history.redoLabel);
65
+ const dirty = ref(history.dirty);
66
+ function sync() {
67
+ flags.sync();
68
+ undoLabel.value = history.undoLabel;
69
+ redoLabel.value = history.redoLabel;
70
+ dirty.value = history.dirty;
71
+ }
63
72
  return {
64
73
  ...flags,
74
+ sync,
75
+ undoLabel: readonly(undoLabel),
76
+ redoLabel: readonly(redoLabel),
77
+ dirty: readonly(dirty),
65
78
  history,
66
- commit(state, key) {
67
- const changed = history.commit(state, key);
68
- flags.sync();
79
+ commit(state, key, label) {
80
+ const changed = history.commit(state, key, label);
81
+ sync();
69
82
  return changed;
70
83
  },
84
+ seal() {
85
+ history.seal();
86
+ },
87
+ markSaved() {
88
+ history.markSaved();
89
+ sync();
90
+ },
71
91
  undo() {
72
92
  const state = history.undo();
73
- flags.sync();
93
+ sync();
74
94
  return state;
75
95
  },
76
96
  redo() {
77
97
  const state = history.redo();
78
- flags.sync();
98
+ sync();
79
99
  return state;
80
100
  },
81
101
  reset(state) {
82
102
  history.reset(state);
83
- flags.sync();
103
+ sync();
84
104
  }
85
105
  };
86
106
  }
@@ -1 +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"}
1
+ {"version":3,"file":"undovue.js","names":[],"sources":["../src/undovue.ts"],"sourcesContent":["import { readonly, ref, type Ref } from 'vue';\r\nimport { History } from './history';\r\nimport { UndoStack, type UndoEntry, type UndoOptions } from './undo';\r\n\r\n/**\r\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\r\n * (`historyCommands`, `TaoMenubar`) switch on and off by themselves. `UndoStack` and `History` are plain classes: their\r\n * `canUndo` is a getter that Vue cannot see, so each of these keeps the refs in step after every move.\r\n * Undo и redo для Vue: флаги стека или истории как ref, чтобы пункты «Отменить» и «Повторить» в меню (`historyCommands`,\r\n * `TaoMenubar`) включались и гасли сами. `UndoStack` и `History` — обычные классы: их `canUndo` — геттер, которого Vue\r\n * не видит, поэтому здесь ref-ы выравниваются после каждого хода.\r\n */\r\n\r\n/** Anything with the two flags: an `UndoStack`, a `History`, your own. / Всё, у чего есть два флага: `UndoStack`, `History`, своё. */\r\nexport interface UndoFlagsSource {\r\n readonly canUndo: boolean;\r\n readonly canRedo: boolean;\r\n}\r\n\r\nexport interface UndoFlags {\r\n readonly canUndo: Readonly<Ref<boolean>>;\r\n readonly canRedo: Readonly<Ref<boolean>>;\r\n /**\r\n * Reads the source again. Call it after a move you made on the source itself, behind the back of the wrapper.\r\n * Читает источник заново. Зовите после хода, сделанного на самом источнике, мимо обёртки.\r\n */\r\n sync(): void;\r\n}\r\n\r\n/**\r\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:\r\n * call `sync()` after every `record`, `undo`, `redo`, `commit`, `clear`.\r\n * Ref-ы для стека или истории, которые у вас уже есть (сделаны вашей фабрикой, лежат в хранилище). Сам ничего не двигает:\r\n * зовите `sync()` после каждого `record`, `undo`, `redo`, `commit`, `clear`.\r\n */\r\nexport function useUndoFlags(source: UndoFlagsSource): UndoFlags {\r\n const canUndo = ref(source.canUndo);\r\n const canRedo = ref(source.canRedo);\r\n function sync() {\r\n canUndo.value = source.canUndo;\r\n canRedo.value = source.canRedo;\r\n }\r\n return { canUndo: readonly(canUndo), canRedo: readonly(canRedo), sync };\r\n}\r\n\r\nexport interface UseUndoStack<T> extends UndoFlags {\r\n /** The stack itself, for what the wrapper does not cover. / Сам стек, для того, что обёртка не покрывает. */\r\n stack: UndoStack<T>;\r\n /** `UndoStack.record`, then the flags. / `UndoStack.record`, затем флаги. */\r\n record(entry: UndoEntry<T>, key?: string, now?: number): void;\r\n /** `UndoStack.undo`: the next list or null; the flags follow. / `UndoStack.undo`: следующий список или null; флаги следуют. */\r\n undo(current: readonly T[], now?: number): T[] | null;\r\n redo(current: readonly T[], now?: number): T[] | null;\r\n clear(): void;\r\n}\r\n\r\n/**\r\n * An `UndoStack` with reactive flags: options make a new one, or pass a stack you already have. The moves go through\r\n * the wrapper, so the flags are always right.\r\n * `UndoStack` с реактивными флагами: опции создают новый, либо передайте готовый стек. Ходы идут через обёртку,\r\n * поэтому флаги всегда верны.\r\n */\r\nexport function useUndoStack<T>(from: UndoOptions<T> | UndoStack<T>): UseUndoStack<T> {\r\n const stack = from instanceof UndoStack ? from : new UndoStack<T>(from);\r\n const flags = useUndoFlags(stack);\r\n return {\r\n ...flags,\r\n stack,\r\n record(entry, key, now) {\r\n stack.record(entry, key, now);\r\n flags.sync();\r\n },\r\n undo(current, now) {\r\n const next = stack.undo(current, now);\r\n flags.sync();\r\n return next;\r\n },\r\n redo(current, now) {\r\n const next = stack.redo(current, now);\r\n flags.sync();\r\n return next;\r\n },\r\n clear() {\r\n stack.clear();\r\n flags.sync();\r\n },\r\n };\r\n}\r\n\r\nexport interface UseHistory extends UndoFlags {\r\n /** The history itself. / Сама история. */\r\n history: History;\r\n /** The label of the step an undo would take back (`History.undoLabel`), as a ref. / Подпись шага, который отменит undo (`History.undoLabel`), как ref. */\r\n readonly undoLabel: Readonly<Ref<string | undefined>>;\r\n /** The label of the step a redo would bring back, as a ref. / Подпись шага, который вернёт redo, как ref. */\r\n readonly redoLabel: Readonly<Ref<string | undefined>>;\r\n /** `History.dirty` as a ref: the current snapshot is not the saved one. / `History.dirty` как ref: текущий снимок не сохранённый. */\r\n readonly dirty: Readonly<Ref<boolean>>;\r\n /** `History.commit`: false when the state did not change; the flags follow. `label` names the step. / `History.commit`: false, если состояние не изменилось; `label` называет шаг. */\r\n commit(state: string, key?: string, label?: string): boolean;\r\n /** `History.seal`: ends a series of merged edits. / `History.seal`: заканчивает серию склеенных правок. */\r\n seal(): void;\r\n /** `History.markSaved`; `dirty` follows. / `History.markSaved`; `dirty` следует. */\r\n markSaved(): void;\r\n /** The previous state or null. It also fits `historyCommands` as a source. / Предыдущее состояние или null. */\r\n undo(): string | null;\r\n redo(): string | null;\r\n /** Starts the history over (a file was loaded). / Начинает историю заново (загружен файл). */\r\n reset(state: string): void;\r\n}\r\n\r\n/**\r\n * A `History` with reactive flags: an initial state makes a new one, or pass a history you already have.\r\n * `History` с реактивными флагами: начальное состояние создаёт новую, либо передайте готовую историю.\r\n */\r\nexport function useHistory(from: string | History, limit?: number): UseHistory {\r\n const history = from instanceof History ? from : new History(from, limit);\r\n const flags = useUndoFlags(history);\r\n const undoLabel = ref(history.undoLabel);\r\n const redoLabel = ref(history.redoLabel);\r\n const dirty = ref(history.dirty);\r\n function sync() {\r\n flags.sync();\r\n undoLabel.value = history.undoLabel;\r\n redoLabel.value = history.redoLabel;\r\n dirty.value = history.dirty;\r\n }\r\n return {\r\n ...flags,\r\n sync,\r\n undoLabel: readonly(undoLabel),\r\n redoLabel: readonly(redoLabel),\r\n dirty: readonly(dirty),\r\n history,\r\n commit(state, key, label) {\r\n const changed = history.commit(state, key, label);\r\n sync();\r\n return changed;\r\n },\r\n seal() {\r\n history.seal();\r\n },\r\n markSaved() {\r\n history.markSaved();\r\n sync();\r\n },\r\n undo() {\r\n const state = history.undo();\r\n sync();\r\n return state;\r\n },\r\n redo() {\r\n const state = history.redo();\r\n sync();\r\n return state;\r\n },\r\n reset(state) {\r\n history.reset(state);\r\n sync();\r\n },\r\n };\r\n}\r\n"],"mappings":";;;;;;;;;;AAmCA,SAAgB,aAAa,QAAoC;CAC7D,MAAM,UAAU,IAAI,OAAO,OAAO;CAClC,MAAM,UAAU,IAAI,OAAO,OAAO;CAClC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O;EACX;EACA,OAAO;GACH,QAAQ,KAAK;EACjB;EACA,YAAY;GACR,QAAQ,UAAU;GAClB,KAAK;EACT;EACA,OAAO;GACH,MAAM,QAAQ,QAAQ,KAAK;GAC3B,KAAK;GACL,OAAO;EACX;EACA,OAAO;GACH,MAAM,QAAQ,QAAQ,KAAK;GAC3B,KAAK;GACL,OAAO;EACX;EACA,MAAM,OAAO;GACT,QAAQ,MAAM,KAAK;GACnB,KAAK;EACT;CACJ;AACJ"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@1337exp/taoux",
3
- "version": "0.16.0",
3
+ "version": "0.17.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",
@@ -1,103 +1,103 @@
1
- ---
2
- name: taoux
3
- description: Build interaction in Vue 3 apps with @1337exp/taoux (TaoUX) — subpath modules for gestures (tap, long press, pinch, swipe), reorderable lists (sortable), swipe rows with actions (swiperow), undo by snapshots or by records, document sessions, autosave across tabs, commands and hotkeys, playback, canvas, curve and gradient editors, and joining them to TaoUI. Use when code imports @1337exp/taoux/*, uses Taox* components or --tx-* variables, or the user asks for TaoUX.
4
- ---
5
-
6
- # TaoUX
7
-
8
- Behaviour building blocks for apps and editors: the logic is plain TypeScript (tested without a DOM), the few Vue modules are
9
- thin shells, and TaoUX has **no buttons or fields of its own** outside the two TaoUI-based fields. Pair it with TaoUI for the
10
- controls, or with your own design.
11
-
12
- ## Rules
13
-
14
- 1. **Import by subpath**, there is no root entry: `import { History } from '@1337exp/taoux/history'`. Only what you import
15
- reaches the bundle. ESM only.
16
- 2. **A Vue module's styles are imported explicitly**: `import '@1337exp/taoux/curveeditor.css'` (also `canvas.css`,
17
- `links.css`, `gradienteditor.css`, `curvefield.css`, `swiperow.css`; `curvefield` needs `curveeditor.css` too).
18
- 3. **With TaoUI, add the bridge**: `import '@1337exp/taoux/taoui.css'` points every `--tx-*` colour, tone and corner radius at a `--tao-*` token (the bridge is the only file that names
19
- `--tao-*`; a module that needs a new one gets a `--tx-*` variable and a line there), so
20
- the editors follow the TaoUI theme and palettes. Zero specificity: your rules win. Without it the editors stay dark.
21
- 4. **Values travel through `v-model`**; TaoUX never renders a TaoUI control itself, except the tier-2 fields `curvefield` and `swiperow`.
22
- 5. **Pre-1.0**: breaking changes happen between minors; read `CHANGELOG.md`.
23
-
24
- ## Modules
25
-
26
- | Import | What for |
27
- |---|---|
28
- | `camera` | pan, zoom around the cursor, screen ↔ world (`zoomAt`; the range is 0.2…2 unless you pass `ZoomLimits`), `fitCamera(rect, size, padding?, limits?)` for "zoom to fit" |
29
- | `history` | `new History(snapshot)`: undo / redo on string snapshots, rapid edits with one `key` merged into one step; `save()` / `restore(state)` take a whole history out and put it back (one per document in a tabbed editor) |
30
- | `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 |
31
- | `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) |
32
- | `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; works inside a zoomed (scaled) canvas too |
33
- | `session` | `createDocumentSession(...)`: history + autosave + files + restore + notices for one document; `canUndo` / `canRedo` refs; `dirty` ref + `markSaved()` for an "unsaved" mark (a flag, not a history position); `saveHistory()` / `restoreHistory(state)` give each of several documents its own undo (`load` the next with `resetHistory`, then restore its history). `camera` is optional (a list, not a canvas); count with `countItems` (`countNodes` is its old name); `zoom` clamps a loaded view to the canvas range |
34
- | `commands` | `createCommands([...])`: one registry for menus, shortcuts and palettes (see below) |
35
- | `hotkeys` | `parseHotkey('Mod+Shift+Z')`, `matchHotkey`, `formatHotkey` (`Ctrl+Shift+Z` / `⇧⌘Z`), `isReservedHotkey`, `bindHotkeys(element, map)` |
36
- | `storage` | autosave to localStorage that never throws; `tryWrite` gives the reason (`quota` / `denied`), `remove`, `subscribe` for changes from other tabs |
37
- | `file` | `downloadBlob(name, data, mime?)` saves bytes or a `Blob`; `downloadText(name, text, mime?)`; `readTextFile(file, limit?)` reads a picked file, refusing a big one; `readBytesFile(file, limit?)` the same as bytes (an archive, an image) |
38
- | `guides` | `snapToGuides(movingRect, otherRects, thresholdInWorldUnits)` → `{ dx, dy, lines }`: smart guides while dragging (edges and centres of the other nodes); you apply the shift and draw the lines; divide a screen threshold by the zoom |
39
- | `snap` | soft snapping to a grid, threshold follows the zoom |
40
- | `wheel` | wheel / trackpad → pan or zoom, like Figma (zoom only with Ctrl / ⌘ or a pinch) |
41
- | `zip` | `await createZip([{ name: 'a/b.png', data }])` and `await readZip(bytes, limits?)`: a project of several files in one `.zip`. Reading an archive from outside is defensive (unsafe names, CRC, size limits against zip bombs); catch `ZipError` and show text by its `code`. `looksLikeZip(bytes)` tells an archive from JSON. Needs `CompressionStream` (any current browser, Node 18+) |
42
- | `edgescroll` | auto-scroll near an edge while dragging (`createEdgeScroller`) |
43
- | `gestures` | tap, double tap, long press, pinch; `SwipeTracker` (swipe vs scroll) + `settleOpen` (where a released row rests); `listenFocusLoss(cancel)` while a press is held, as Alt-Tab swallows the pointerup |
44
- | `touch` | `coarse`: is the pointer a finger |
45
- | `curve` | link paths: Bezier between pins, arrowheads of constant screen size |
46
- | `ids` | `uuid()` for stored / synced records; `uid(prefix, taken)` restarts from zero on every load, only for ids inside one document |
47
- | `ease` | easing between curve points (8 families × in / out / in-out, `linear`, `step`, cubic Bezier), `easeValue` |
48
- | `num` | `clamp`, `roundTo`, `snapTo`, `niceStep`, `ticks` |
49
- | `palette` | search and groups for a palette of nodes |
50
- | `pins` | row pin positions measured from the DOM (`usePinMeasure`, `createPinRegistry`) |
51
- | `playback` | time, pause, loop, speed, seeking: `createPlayback` (no Vue), `usePlayback` (drives TaoUI `TaoScrubber`) |
52
- | `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 |
53
- | `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()` |
54
- | `i18n` | typed i18n: `createI18n({ locales, fallback, storageKey })` |
55
- | `links` (Vue) | `TaoxLinks`: an SVG layer of links from ready geometry |
56
- | `canvas` (Vue) | `TaoxCanvas`: pan / zoom canvas with mouse, touch, wheel, auto-scroll, keys; the `CanvasHost` contract; prop `background: 'grid' | 'dots' | 'none'`; options `marquee: 'contain'` (only nodes wholly inside the frame), `zoom: { min, max }`; option `inertia: true | { friction, minSpeed, maxSpeed }` (the camera glides after a pan released on the move: only a clear flick, 0.4 px/ms by default, glides; a pointer held still before the release stops it, a 1:1 drag; the arithmetic is `canvas/glide`); the world offset lands on whole device pixels; `TaoxGuides :lines` (also exported from `canvas`) draws the `lines` of `snapToGuides` in the world over the nodes, look by `--tx-guide-color`, `--tx-guide-width`, `--tx-guide-dash`; option `keys: 'window' | 'focus'` (default `'window'`: the keys Delete / Esc / Ctrl+Z work from the whole window; `'focus'`: only when the event comes from inside the canvas, which takes focus on a press, for a canvas beside a drawer or text fields); host `claimsKey(e)` keeps a key from the canvas while a tool uses it; host `placing` + `placeAt(screen, world)` is a "place a node" tool (the next left press only says where); host `contextMenu(screen, world, target)` shows the app's menu on a right click (true) or leaves the palette (false) |
57
- | `curveeditor` (Vue) | `TaoxCurveEditor`: points, snapping, bounds, per-segment easing with Bezier handles, keyboard; time is 0…1, `formatT(t)` writes it as years, seconds… on the axis and tag |
58
- | `gradienteditor` (Vue) | `TaoxGradientEditor`: stops on a bar, `gradientCss`, keyboard |
59
- | `curvefield` (Vue, needs TaoUI) | `TaoxCurveField`: a curve editor with TaoUI fields for time, value, easing, snapping |
60
-
61
- ## Commands, hotkeys and the TaoUI menu bar
62
-
63
- ```ts
64
- import { computed, onBeforeUnmount, onMounted } from 'vue';
65
- import { createCommands, historyCommands } from '@1337exp/taoux/commands';
66
-
67
- const commands = createCommands([
68
- { id: 'save', label: () => t('save'), shortcut: 'Mod+S', enabled: () => dirty.value, run: save },
69
- { id: 'grid', label: () => t('grid'), shortcut: "Mod+'", checked: () => grid.value, run: () => (grid.value = !grid.value) },
70
- ...historyCommands(session), // Undo / Redo, disabled when there is nothing to undo
71
- ]);
72
-
73
- // in computed: labels, enabled and checked follow the refs they read
74
- const menu = computed(() => commands.toMenu([
75
- { id: 'file', label: t('file'), items: ['save'] },
76
- { id: 'edit', label: t('edit'), items: ['undo', 'redo', '-', 'grid'] },
77
- ]));
78
-
79
- let unbind = () => {};
80
- onMounted(() => (unbind = commands.bind(document)));
81
- onBeforeUnmount(() => unbind());
82
- ```
83
-
84
- ```vue
85
- <TaoMenubar :items="menu" @select="commands.run" />
86
- ```
87
-
88
- - `Mod` is ⌘ on Apple and Ctrl elsewhere; the menu shows the platform's label by itself.
89
- - A disabled command swallows its key, so Mod+S never opens the browser's «Save page».
90
- - In a text field, plain keys and text editing (Mod+Z / C / V / A) stay with the field.
91
- - `commands.check()` in a test lists shortcuts the browser keeps (⌘W, ⌘T, ⌘Q, ⌘R in Safari) and duplicates.
92
- - `toMenu` returns the same shape as TaoUI's `TaoMenuItem[]` (a type test holds it), so it also feeds `TaoContextMenu`
93
- and `TaoDropdownMenu`.
94
-
95
- ## Mistakes to avoid
96
-
97
- - Importing from `@1337exp/taoux` (no root entry) or from `dist/` paths.
98
- - Forgetting the module CSS (`curveeditor.css`…) or the bridge `taoui.css`: the editor renders unstyled or dark.
99
- - Calling `toMenu` outside `computed`: the menu does not follow the state.
100
- - Using `History` for a list of records that is synced: its snapshots are the whole list, and an undo after a sync rolls back the other device's edits. Use `undo` (`UndoStack`), and stamp a returned record as new in `revive`.
101
- - Keeping editor state outside `history` / `session` and then wondering why Undo skips it: commit a snapshot after
102
- every edit (`session.commit(key)` or `recorded(fn)`).
103
- - Offering a reserved shortcut (⌘W, ⌘T, ⌘N, Ctrl+Tab): the browser takes it before the page.
1
+ ---
2
+ name: taoux
3
+ description: Build interaction in Vue 3 apps with @1337exp/taoux (TaoUX) — subpath modules for gestures (tap, long press, pinch, swipe), reorderable lists (sortable), swipe rows with actions (swiperow), undo by snapshots or by records, document sessions, autosave across tabs, commands and hotkeys, playback, canvas, curve and gradient editors, and joining them to TaoUI. Use when code imports @1337exp/taoux/*, uses Taox* components or --tx-* variables, or the user asks for TaoUX.
4
+ ---
5
+
6
+ # TaoUX
7
+
8
+ Behaviour building blocks for apps and editors: the logic is plain TypeScript (tested without a DOM), the few Vue modules are
9
+ thin shells, and TaoUX has **no buttons or fields of its own** outside the two TaoUI-based fields. Pair it with TaoUI for the
10
+ controls, or with your own design.
11
+
12
+ ## Rules
13
+
14
+ 1. **Import by subpath**, there is no root entry: `import { History } from '@1337exp/taoux/history'`. Only what you import
15
+ reaches the bundle. ESM only.
16
+ 2. **A Vue module's styles are imported explicitly**: `import '@1337exp/taoux/curveeditor.css'` (also `canvas.css`,
17
+ `links.css`, `gradienteditor.css`, `curvefield.css`, `swiperow.css`; `curvefield` needs `curveeditor.css` too).
18
+ 3. **With TaoUI, add the bridge**: `import '@1337exp/taoux/taoui.css'` points every `--tx-*` colour, tone and corner radius at a `--tao-*` token (the bridge is the only file that names
19
+ `--tao-*`; a module that needs a new one gets a `--tx-*` variable and a line there), so
20
+ the editors follow the TaoUI theme and palettes. Zero specificity: your rules win. Without it the editors stay dark.
21
+ 4. **Values travel through `v-model`**; TaoUX never renders a TaoUI control itself, except the tier-2 fields `curvefield` and `swiperow`.
22
+ 5. **Pre-1.0**: breaking changes happen between minors; read `CHANGELOG.md`.
23
+
24
+ ## Modules
25
+
26
+ | Import | What for |
27
+ |---|---|
28
+ | `camera` | pan, zoom around the cursor, screen ↔ world (`zoomAt`; the range is 0.2…2 unless you pass `ZoomLimits`), `fitCamera(rect, size, padding?, limits?)` for "zoom to fit" |
29
+ | `history` | `new History(snapshot)`: undo / redo on string snapshots, rapid edits with one `key` merged into one step (by time, or until `seal()`; `{ coalesceMs: Infinity }` for an editor that ends the gesture itself); `commit(state, key, label)` names a step (`undoLabel`, `redoLabel`); `dirty` / `markSaved()` follow the position; `save()` / `restore(state)` take a whole history out and put it back (one per document in a tabbed editor) |
30
+ | `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 |
31
+ | `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) |
32
+ | `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; works inside a zoomed (scaled) canvas too |
33
+ | `session` | `createDocumentSession(...)`: history + autosave + files + restore + notices for one document; `canUndo` / `canRedo` refs; `dirty` ref + `markSaved()` for an "unsaved" mark (a flag, not a history position); `saveHistory()` / `restoreHistory(state)` give each of several documents its own undo (`load` the next with `resetHistory`, then restore its history). `camera` is optional (a list, not a canvas); count with `countItems` (`countNodes` is its old name); `zoom` clamps a loaded view to the canvas range |
34
+ | `commands` | `createCommands([...])`: one registry for menus, shortcuts and palettes (see below) |
35
+ | `hotkeys` | `parseHotkey('Mod+Shift+Z')`, `matchHotkey`, `formatHotkey` (`Ctrl+Shift+Z` / `⇧⌘Z`), `isReservedHotkey`, `bindHotkeys(element, map)` |
36
+ | `storage` | autosave to localStorage that never throws; `tryWrite` gives the reason (`quota` / `denied`), `remove`, `subscribe` for changes from other tabs |
37
+ | `file` | `downloadBlob(name, data, mime?)` saves bytes or a `Blob`; `downloadText(name, text, mime?)`; `readTextFile(file, limit?)` reads a picked file, refusing a big one; `readBytesFile(file, limit?)` the same as bytes (an archive, an image) |
38
+ | `guides` | `snapToGuides(movingRect, otherRects, thresholdInWorldUnits)` → `{ dx, dy, lines }`: smart guides while dragging (edges and centres of the other nodes); you apply the shift and draw the lines; divide a screen threshold by the zoom |
39
+ | `snap` | soft snapping to a grid, threshold follows the zoom |
40
+ | `wheel` | wheel / trackpad → pan or zoom, like Figma (zoom only with Ctrl / ⌘ or a pinch) |
41
+ | `zip` | `await createZip([{ name: 'a/b.png', data }])` and `await readZip(bytes, limits?)`: a project of several files in one `.zip`. Reading an archive from outside is defensive (unsafe names, CRC, size limits against zip bombs); catch `ZipError` and show text by its `code`. `looksLikeZip(bytes)` tells an archive from JSON. Needs `CompressionStream` (any current browser, Node 18+) |
42
+ | `edgescroll` | auto-scroll near an edge while dragging (`createEdgeScroller`) |
43
+ | `gestures` | tap, double tap, long press, pinch; `SwipeTracker` (swipe vs scroll) + `settleOpen` (where a released row rests); `listenFocusLoss(cancel)` while a press is held, as Alt-Tab swallows the pointerup |
44
+ | `touch` | `coarse`: is the pointer a finger |
45
+ | `curve` | link paths: Bezier between pins, arrowheads of constant screen size |
46
+ | `ids` | `uuid()` for stored / synced records; `uid(prefix, taken)` restarts from zero on every load, only for ids inside one document |
47
+ | `ease` | easing between curve points (8 families × in / out / in-out, `linear`, `step`, cubic Bezier), `easeValue` |
48
+ | `num` | `clamp`, `roundTo`, `snapTo`, `niceStep`, `ticks` |
49
+ | `palette` | search and groups for a palette of nodes |
50
+ | `pins` | row pin positions measured from the DOM (`usePinMeasure`, `createPinRegistry`) |
51
+ | `playback` | time, pause, loop, speed, seeking: `createPlayback` (no Vue), `usePlayback` (drives TaoUI `TaoScrubber`) |
52
+ | `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 |
53
+ | `undovue` | `undo` and `history` for Vue: `useUndoStack`, `useHistory` (the same classes with `canUndo` / `canRedo` as refs, so the Undo / Redo menu items follow; `useHistory` also `undoLabel`, `redoLabel`, `dirty`, `seal()`, `markSaved()`), `useUndoFlags(existing)` + `sync()` |
54
+ | `i18n` | typed i18n: `createI18n({ locales, fallback, storageKey })` |
55
+ | `links` (Vue) | `TaoxLinks`: an SVG layer of links from ready geometry |
56
+ | `canvas` (Vue) | `TaoxCanvas`: pan / zoom canvas with mouse, touch, wheel, auto-scroll, keys; the `CanvasHost` contract; prop `background: 'grid' | 'dots' | 'none'`; options `marquee: 'contain'` (only nodes wholly inside the frame), `zoom: { min, max }`; option `inertia: true | { friction, minSpeed, maxSpeed }` (the camera glides after a pan released on the move: only a clear flick, 0.4 px/ms by default, glides; a pointer held still before the release stops it, a 1:1 drag; the arithmetic is `canvas/glide`); the world offset lands on whole device pixels; `TaoxGuides :lines` (also exported from `canvas`) draws the `lines` of `snapToGuides` in the world over the nodes, look by `--tx-guide-color`, `--tx-guide-width`, `--tx-guide-dash`; option `keys: 'window' | 'focus'` (default `'window'`: the keys Delete / Esc / Ctrl+Z work from the whole window; `'focus'`: only when the event comes from inside the canvas, which takes focus on a press, for a canvas beside a drawer or text fields); host `claimsKey(e)` keeps a key from the canvas while a tool uses it; host `placing` + `placeAt(screen, world)` is a "place a node" tool (the next left press only says where); host `contextMenu(screen, world, target)` shows the app's menu on a right click (true) or leaves the palette (false) |
57
+ | `curveeditor` (Vue) | `TaoxCurveEditor`: points, snapping, bounds, per-segment easing with Bezier handles, keyboard; time is 0…1, `formatT(t)` writes it as years, seconds… on the axis and tag |
58
+ | `gradienteditor` (Vue) | `TaoxGradientEditor`: stops on a bar, `gradientCss`, keyboard |
59
+ | `curvefield` (Vue, needs TaoUI) | `TaoxCurveField`: a curve editor with TaoUI fields for time, value, easing, snapping |
60
+
61
+ ## Commands, hotkeys and the TaoUI menu bar
62
+
63
+ ```ts
64
+ import { computed, onBeforeUnmount, onMounted } from 'vue';
65
+ import { createCommands, historyCommands } from '@1337exp/taoux/commands';
66
+
67
+ const commands = createCommands([
68
+ { id: 'save', label: () => t('save'), shortcut: 'Mod+S', enabled: () => dirty.value, run: save },
69
+ { id: 'grid', label: () => t('grid'), shortcut: "Mod+'", checked: () => grid.value, run: () => (grid.value = !grid.value) },
70
+ ...historyCommands(session), // Undo / Redo, disabled when there is nothing to undo
71
+ ]);
72
+
73
+ // in computed: labels, enabled and checked follow the refs they read
74
+ const menu = computed(() => commands.toMenu([
75
+ { id: 'file', label: t('file'), items: ['save'] },
76
+ { id: 'edit', label: t('edit'), items: ['undo', 'redo', '-', 'grid'] },
77
+ ]));
78
+
79
+ let unbind = () => {};
80
+ onMounted(() => (unbind = commands.bind(document)));
81
+ onBeforeUnmount(() => unbind());
82
+ ```
83
+
84
+ ```vue
85
+ <TaoMenubar :items="menu" @select="commands.run" />
86
+ ```
87
+
88
+ - `Mod` is ⌘ on Apple and Ctrl elsewhere; the menu shows the platform's label by itself.
89
+ - A disabled command swallows its key, so Mod+S never opens the browser's «Save page».
90
+ - In a text field, plain keys and text editing (Mod+Z / C / V / A) stay with the field.
91
+ - `commands.check()` in a test lists shortcuts the browser keeps (⌘W, ⌘T, ⌘Q, ⌘R in Safari) and duplicates.
92
+ - `toMenu` returns the same shape as TaoUI's `TaoMenuItem[]` (a type test holds it), so it also feeds `TaoContextMenu`
93
+ and `TaoDropdownMenu`.
94
+
95
+ ## Mistakes to avoid
96
+
97
+ - Importing from `@1337exp/taoux` (no root entry) or from `dist/` paths.
98
+ - Forgetting the module CSS (`curveeditor.css`…) or the bridge `taoui.css`: the editor renders unstyled or dark.
99
+ - Calling `toMenu` outside `computed`: the menu does not follow the state.
100
+ - Using `History` for a list of records that is synced: its snapshots are the whole list, and an undo after a sync rolls back the other device's edits. Use `undo` (`UndoStack`), and stamp a returned record as new in `revive`.
101
+ - Keeping editor state outside `history` / `session` and then wondering why Undo skips it: commit a snapshot after
102
+ every edit (`session.commit(key)` or `recorded(fn)`).
103
+ - Offering a reserved shortcut (⌘W, ⌘T, ⌘N, Ctrl+Tab): the browser takes it before the page.