@1337exp/taoux 0.5.6 → 0.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +18 -0
- package/README.md +4 -2
- package/README.ru.md +4 -2
- package/dist/camera.d.ts +18 -3
- package/dist/camera.js +20 -5
- package/dist/camera.js.map +1 -1
- package/dist/canvas/host.d.ts +20 -1
- package/dist/canvas.js +5 -4
- package/dist/canvas.js.map +1 -1
- package/dist/session.d.ts +6 -1
- package/dist/session.js +2 -2
- package/dist/session.js.map +1 -1
- package/dist/tour/core.d.ts +77 -0
- package/dist/tour/index.d.ts +3 -0
- package/dist/tour/memory.d.ts +16 -0
- package/dist/tour/use.d.ts +21 -0
- package/dist/tour.js +172 -0
- package/dist/tour.js.map +1 -0
- package/dist/undovue.d.ts +65 -0
- package/dist/undovue.js +90 -0
- package/dist/undovue.js.map +1 -0
- package/package.json +10 -2
- package/skills/taoux/SKILL.md +5 -3
package/dist/session.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { clampZoom, zoomLimits } from "./camera.js";
|
|
2
2
|
import { History } from "./history.js";
|
|
3
3
|
import { ref } from "vue";
|
|
4
4
|
//#region src/session.ts
|
|
@@ -119,7 +119,7 @@ function createDocumentSession(options) {
|
|
|
119
119
|
if (view && camera) camera.set({
|
|
120
120
|
x: view.x,
|
|
121
121
|
y: view.y,
|
|
122
|
-
z:
|
|
122
|
+
z: clampZoom(view.z, zoomLimits(options.zoom))
|
|
123
123
|
});
|
|
124
124
|
if (resetHistory) {
|
|
125
125
|
history.reset(snapshot());
|
package/dist/session.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session.js","names":[],"sources":["../src/session.ts"],"sourcesContent":["import { ref } from 'vue';\nimport { MAX_ZOOM, MIN_ZOOM, type Camera } from './camera';\nimport { History } from './history';\nimport type { SavedStorage } from './storage';\n\nexport type NoticeArgs = readonly (string | number)[];\n\n/**\n * A short message to the user. Holds a translation key: the interface builds the text.\n * Короткое сообщение пользователю. Хранит ключ перевода: текст собирает интерфейс.\n */\nexport interface SessionNotice<K extends string = string> {\n kind: 'info' | 'error';\n key: K;\n args?: NoticeArgs;\n}\n\n/**\n * Why opening a file was refused; the interface builds the user text from `code`.\n * Причина отказа открыть файл; текст для пользователя собирает интерфейс по `code`.\n */\nexport interface LoadError {\n code: string;\n detail?: string | number;\n}\n\nexport type LoadResult<D> =\n | { ok: true; doc: D; view?: Camera; dropped: number }\n | { ok: false; error: LoadError };\n\n/**\n * Message keys the session shows by itself. The app dictionary must contain them.\n * Ключи сообщений, которые сессия показывает сама. Словарь приложения обязан их содержать.\n */\nexport interface SessionKeys<K extends string> {\n loaded: K; // {0} is the number of items (`countItems`) / {0} — число элементов (`countItems`)\n loadedWithDropped: K; // {0} is the number of items, {1} how many entries the codec dropped / {0} — число элементов, {1} — сколько записей отбросил кодек\n newDocument: K;\n saveFailed: K;\n restoreFailed: K;\n /**\n * The key for the reason a file was refused.\n * Ключ для причины отказа открыть файл.\n */\n loadError(code: string): K;\n}\n\nexport interface SessionOptions<D, K extends string> {\n /**\n * The document in the app store.\n * Документ в сторе приложения.\n */\n document: { get(): D; set(doc: D): void };\n /**\n * The view of a canvas editor: saved with the document and brought back on open. Leave it out for a document\n * without one (a list of notes): `serialize` then gets `undefined`, and a `view` from `parse` is ignored.\n * Вид редактора-холста: сохраняется с документом и возвращается при открытии. Не задавайте для документа без него\n * (список заметок): тогда `serialize` получает `undefined`, а `view` из `parse` пропускается.\n */\n camera?: { get(): Camera; set(camera: Camera): void };\n storage: SavedStorage;\n codec: {\n serialize(doc: D, view: Camera | undefined, pretty: boolean): string;\n parse(text: string): LoadResult<D>;\n };\n empty(): D;\n /**\n * How many items are in the document (nodes, notes): substituted into the message about opening a file.\n * Сколько элементов в документе (узлов, заметок): подставляется в сообщение об открытии файла.\n */\n countItems?(doc: D): number;\n /**\n * @deprecated The old name of `countItems`; still read when `countItems` is not given.\n * Старое имя `countItems`; читается, если `countItems` не задан.\n */\n countNodes?(doc: D): number;\n keys: SessionKeys<K>;\n /**\n * The document was replaced as a whole (open, new, restore): reset the selection, the drag, the palette.\n * Документ подменён целиком (открытие, новый, восстановление): сбросить выделение, протягивание, палитру.\n */\n onReset?(): void;\n /**\n * The state was restored from history (undo/redo): drop references to what is gone.\n * Состояние восстановлено из истории (undo/redo): убрать ссылки на то, чего больше нет.\n */\n onRestore?(doc: D): void;\n /**\n * The pause before autosave, ms.\n * Пауза перед автосохранением, мс.\n */\n autosaveDelay?: number;\n /**\n * How long to show a notice, ms.\n * Сколько секунд показывать уведомление, мс.\n */\n noticeMs?: number;\n}\n\nconst DEFAULT_NOTICE_MS = 5000;\nconst DEFAULT_AUTOSAVE_MS = 400;\n\n/**\n * The lifecycle of an editor document: history (undo/redo with merged edits), autosave guarded against storage\n * failures, opening and saving a file, restore after a reload, notices.\n * The document, the camera and the file format belong to the app, only the mechanics are here.\n * Жизненный цикл документа редактора: история (undo/redo со склейкой правок), автосохранение с защитой от сбоев\n * хранилища, открытие и сохранение файла, восстановление после перезагрузки, уведомления.\n * Документ, камера и формат файла принадлежат приложению, здесь только механика.\n */\nexport function createDocumentSession<D, K extends string>(options: SessionOptions<D, K>) {\n const { document: doc, camera, storage, codec, keys } = options;\n const noticeMs = options.noticeMs ?? DEFAULT_NOTICE_MS;\n const count = (d: D) => (options.countItems ?? options.countNodes)?.(d) ?? 0;\n const autosaveDelay = options.autosaveDelay ?? DEFAULT_AUTOSAVE_MS;\n\n //---]>\n // notices\n // уведомления\n\n const notice = ref<SessionNotice<K> | null>(null);\n let noticeTimer: ReturnType<typeof setTimeout> | undefined;\n\n function showNotice(kind: SessionNotice<K>['kind'], key: K, args?: NoticeArgs) {\n notice.value = { kind, key, args };\n clearTimeout(noticeTimer);\n noticeTimer = setTimeout(() => (notice.value = null), noticeMs);\n }\n\n //---]>\n // autosave\n // автосохранение\n\n let autosaveOn = false;\n let saveTimer: ReturnType<typeof setTimeout> | undefined;\n let saveFailedShown = false;\n\n /**\n * Writes the document and the camera position to storage.\n * Записывает документ и положение камеры в хранилище.\n */\n function flushSave() {\n clearTimeout(saveTimer);\n saveTimer = undefined;\n if (!autosaveOn) return;\n\n if (storage.write(codec.serialize(doc.get(), camera?.get(), false))) {\n saveFailedShown = false;\n } else if (!saveFailedShown) {\n saveFailedShown = true; // tell once, not on every edit / сообщаем один раз, а не при каждой правке\n showNotice('error', keys.saveFailed);\n }\n }\n\n function scheduleSave() {\n if (!autosaveOn) return;\n clearTimeout(saveTimer);\n saveTimer = setTimeout(flushSave, autosaveDelay);\n }\n\n /**\n * Turns autosave on. Off by default (nothing is written in tests and before restore).\n * Edits are saved with a small delay, and at once when the tab is hidden or closed.\n * Returns a function that turns everything off.\n * Включает автосохранение. Выключено по умолчанию (в тестах и до восстановления ничего не пишется).\n * Правки сохраняются с небольшой задержкой, а при скрытии вкладки и закрытии сразу.\n * Возвращает функцию, которая всё отключает.\n */\n function startAutosave(): () => void {\n autosaveOn = true;\n const onHide = () => {\n if (document.visibilityState === 'hidden') flushSave();\n };\n window.addEventListener('pagehide', flushSave);\n document.addEventListener('visibilitychange', onHide);\n\n return () => {\n autosaveOn = false;\n clearTimeout(saveTimer);\n window.removeEventListener('pagehide', flushSave);\n document.removeEventListener('visibilitychange', onHide);\n };\n }\n\n //---]>\n // history\n // история\n\n const snapshot = () => JSON.stringify(doc.get());\n const history = new History(snapshot());\n const canUndo = ref(false);\n const canRedo = ref(false);\n\n function syncHistory() {\n canUndo.value = history.canUndo;\n canRedo.value = history.canRedo;\n scheduleSave(); // the document changed (an edit, undo or redo): autosave will pick it up / документ изменился (правка, undo или redo): автосохранение подхватит\n }\n\n /**\n * Remembers the current state as a history step. The same `key` in a row merges edits (typing text).\n * Запоминает текущее состояние как шаг истории. Одинаковый `key` подряд склеивает правки (набор текста).\n */\n function commit(key?: string) {\n history.commit(snapshot(), key);\n syncHistory();\n }\n\n function restore(state: string | null): boolean {\n if (state === null) return false;\n\n doc.set(JSON.parse(state) as D);\n options.onRestore?.(doc.get());\n syncHistory();\n return true;\n }\n\n const undo = () => restore(history.undo());\n const redo = () => restore(history.redo());\n\n /**\n * An action that changes the document: afterwards the state goes into history.\n * Действие, меняющее документ: после него состояние попадает в историю.\n */\n function recorded<A extends unknown[], R>(fn: (...args: A) => R, key?: (...args: A) => string): (...args: A) => R {\n return (...args) => {\n const result = fn(...args);\n commit(key?.(...args));\n return result;\n };\n }\n\n //---]>\n // opening, files, restore\n // открытие, файлы, восстановление\n\n /**\n * Replaces the document as a whole. Without `resetHistory` it is an ordinary edit: it can be undone.\n * Подменяет документ целиком. Без `resetHistory` это обычная правка: её можно отменить.\n */\n function load(next: D, view?: Camera, resetHistory = false) {\n doc.set(next);\n options.onReset?.();\n if (view && camera) camera.set({ x: view.x, y: view.y, z: Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, view.z)) });\n\n if (resetHistory) {\n history.reset(snapshot());\n syncHistory();\n } else {\n commit();\n }\n }\n\n /**\n * The file text for download.\n * Текст файла для скачивания.\n */\n const exportText = () => codec.serialize(doc.get(), camera?.get(), true);\n\n /**\n * Opens a document from file text. On an error the document is unchanged. The result is shown as a notice.\n * Открывает документ из текста файла. При ошибке документ не меняется. Результат показывается уведомлением.\n */\n function importText(text: string): LoadError | null {\n const result = codec.parse(text);\n if (!result.ok) {\n const { code, detail } = result.error;\n showNotice('error', keys.loadError(code), detail === undefined ? undefined : [detail]);\n return result.error;\n }\n\n load(result.doc, result.view);\n const items = count(result.doc);\n if (result.dropped > 0) showNotice('error', keys.loadedWithDropped, [items, result.dropped]);\n else showNotice('info', keys.loaded, [items]);\n return null;\n }\n\n function newDocument() {\n load(options.empty(), { x: 0, y: 0, z: 1 });\n showNotice('info', keys.newDocument);\n }\n\n /**\n * At app start: brings the document back from autosave. Returns true if there was something to restore.\n * При старте приложения: поднимает документ из автосохранения. Возвращает true, если было что поднимать.\n */\n function restoreSaved(): boolean {\n const text = storage.read();\n if (text === null) return false;\n\n const result = codec.parse(text);\n if (!result.ok) {\n storage.backupBroken(text);\n showNotice('error', keys.restoreFailed);\n return false;\n }\n\n load(result.doc, result.view, true);\n return true;\n }\n\n return {\n notice,\n showNotice,\n canUndo,\n canRedo,\n commit,\n undo,\n redo,\n recorded,\n load,\n exportText,\n importText,\n newDocument,\n restoreSaved,\n startAutosave,\n flushSave,\n };\n}\n\nexport type DocumentSession<D, K extends string> = ReturnType<typeof createDocumentSession<D, K>>;\n"],"mappings":";;;;AAmGA,IAAM,oBAAoB;AAC1B,IAAM,sBAAsB;;;;;;;;;AAU5B,SAAgB,sBAA2C,SAA+B;CACtF,MAAM,EAAE,UAAU,KAAK,QAAQ,SAAS,OAAO,SAAS;CACxD,MAAM,WAAW,QAAQ,YAAY;CACrC,MAAM,SAAS,OAAU,QAAQ,cAAc,QAAQ,WAAA,GAAc,CAAC,KAAK;CAC3E,MAAM,gBAAgB,QAAQ,iBAAiB;CAM/C,MAAM,SAAS,IAA6B,IAAI;CAChD,IAAI;CAEJ,SAAS,WAAW,MAAgC,KAAQ,MAAmB;EAC3E,OAAO,QAAQ;GAAE;GAAM;GAAK;EAAK;EACjC,aAAa,WAAW;EACxB,cAAc,iBAAkB,OAAO,QAAQ,MAAO,QAAQ;CAClE;CAMA,IAAI,aAAa;CACjB,IAAI;CACJ,IAAI,kBAAkB;;;;;CAMtB,SAAS,YAAY;EACjB,aAAa,SAAS;EACtB,YAAY,KAAA;EACZ,IAAI,CAAC,YAAY;EAEjB,IAAI,QAAQ,MAAM,MAAM,UAAU,IAAI,IAAI,GAAG,QAAQ,IAAI,GAAG,KAAK,CAAC,GAC9D,kBAAkB;OACf,IAAI,CAAC,iBAAiB;GACzB,kBAAkB;GAClB,WAAW,SAAS,KAAK,UAAU;EACvC;CACJ;CAEA,SAAS,eAAe;EACpB,IAAI,CAAC,YAAY;EACjB,aAAa,SAAS;EACtB,YAAY,WAAW,WAAW,aAAa;CACnD;;;;;;;;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":3,"file":"session.js","names":[],"sources":["../src/session.ts"],"sourcesContent":["import { ref } from 'vue';\nimport { clampZoom, zoomLimits, type Camera, type ZoomLimits } from './camera';\nimport { History } from './history';\nimport type { SavedStorage } from './storage';\n\nexport type NoticeArgs = readonly (string | number)[];\n\n/**\n * A short message to the user. Holds a translation key: the interface builds the text.\n * Короткое сообщение пользователю. Хранит ключ перевода: текст собирает интерфейс.\n */\nexport interface SessionNotice<K extends string = string> {\n kind: 'info' | 'error';\n key: K;\n args?: NoticeArgs;\n}\n\n/**\n * Why opening a file was refused; the interface builds the user text from `code`.\n * Причина отказа открыть файл; текст для пользователя собирает интерфейс по `code`.\n */\nexport interface LoadError {\n code: string;\n detail?: string | number;\n}\n\nexport type LoadResult<D> =\n | { ok: true; doc: D; view?: Camera; dropped: number }\n | { ok: false; error: LoadError };\n\n/**\n * Message keys the session shows by itself. The app dictionary must contain them.\n * Ключи сообщений, которые сессия показывает сама. Словарь приложения обязан их содержать.\n */\nexport interface SessionKeys<K extends string> {\n loaded: K; // {0} is the number of items (`countItems`) / {0} — число элементов (`countItems`)\n loadedWithDropped: K; // {0} is the number of items, {1} how many entries the codec dropped / {0} — число элементов, {1} — сколько записей отбросил кодек\n newDocument: K;\n saveFailed: K;\n restoreFailed: K;\n /**\n * The key for the reason a file was refused.\n * Ключ для причины отказа открыть файл.\n */\n loadError(code: string): K;\n}\n\nexport interface SessionOptions<D, K extends string> {\n /**\n * The document in the app store.\n * Документ в сторе приложения.\n */\n document: { get(): D; set(doc: D): void };\n /**\n * The view of a canvas editor: saved with the document and brought back on open. Leave it out for a document\n * without one (a list of notes): `serialize` then gets `undefined`, and a `view` from `parse` is ignored.\n * Вид редактора-холста: сохраняется с документом и возвращается при открытии. Не задавайте для документа без него\n * (список заметок): тогда `serialize` получает `undefined`, а `view` из `parse` пропускается.\n */\n camera?: { get(): Camera; set(camera: Camera): void };\n storage: SavedStorage;\n codec: {\n serialize(doc: D, view: Camera | undefined, pretty: boolean): string;\n parse(text: string): LoadResult<D>;\n };\n empty(): D;\n /**\n * How many items are in the document (nodes, notes): substituted into the message about opening a file.\n * Сколько элементов в документе (узлов, заметок): подставляется в сообщение об открытии файла.\n */\n countItems?(doc: D): number;\n /**\n * @deprecated The old name of `countItems`; still read when `countItems` is not given.\n * Старое имя `countItems`; читается, если `countItems` не задан.\n */\n countNodes?(doc: D): number;\n keys: SessionKeys<K>;\n /**\n * The document was replaced as a whole (open, new, restore): reset the selection, the drag, the palette.\n * Документ подменён целиком (открытие, новый, восстановление): сбросить выделение, протягивание, палитру.\n */\n onReset?(): void;\n /**\n * The state was restored from history (undo/redo): drop references to what is gone.\n * Состояние восстановлено из истории (undo/redo): убрать ссылки на то, чего больше нет.\n */\n onRestore?(doc: D): void;\n /**\n * The pause before autosave, ms.\n * Пауза перед автосохранением, мс.\n */\n autosaveDelay?: number;\n /**\n * How long to show a notice, ms.\n * Сколько секунд показывать уведомление, мс.\n */\n noticeMs?: number;\n /**\n * The zoom range a loaded view is clamped to: the same as the canvas `zoom` option (default 0.2…2).\n * Диапазон, в который зажимается масштаб загруженного вида: тот же, что у опции холста `zoom` (по умолчанию 0.2…2).\n */\n zoom?: Partial<ZoomLimits>;\n}\n\nconst DEFAULT_NOTICE_MS = 5000;\nconst DEFAULT_AUTOSAVE_MS = 400;\n\n/**\n * The lifecycle of an editor document: history (undo/redo with merged edits), autosave guarded against storage\n * failures, opening and saving a file, restore after a reload, notices.\n * The document, the camera and the file format belong to the app, only the mechanics are here.\n * Жизненный цикл документа редактора: история (undo/redo со склейкой правок), автосохранение с защитой от сбоев\n * хранилища, открытие и сохранение файла, восстановление после перезагрузки, уведомления.\n * Документ, камера и формат файла принадлежат приложению, здесь только механика.\n */\nexport function createDocumentSession<D, K extends string>(options: SessionOptions<D, K>) {\n const { document: doc, camera, storage, codec, keys } = options;\n const noticeMs = options.noticeMs ?? DEFAULT_NOTICE_MS;\n const count = (d: D) => (options.countItems ?? options.countNodes)?.(d) ?? 0;\n const autosaveDelay = options.autosaveDelay ?? DEFAULT_AUTOSAVE_MS;\n\n //---]>\n // notices\n // уведомления\n\n const notice = ref<SessionNotice<K> | null>(null);\n let noticeTimer: ReturnType<typeof setTimeout> | undefined;\n\n function showNotice(kind: SessionNotice<K>['kind'], key: K, args?: NoticeArgs) {\n notice.value = { kind, key, args };\n clearTimeout(noticeTimer);\n noticeTimer = setTimeout(() => (notice.value = null), noticeMs);\n }\n\n //---]>\n // autosave\n // автосохранение\n\n let autosaveOn = false;\n let saveTimer: ReturnType<typeof setTimeout> | undefined;\n let saveFailedShown = false;\n\n /**\n * Writes the document and the camera position to storage.\n * Записывает документ и положение камеры в хранилище.\n */\n function flushSave() {\n clearTimeout(saveTimer);\n saveTimer = undefined;\n if (!autosaveOn) return;\n\n if (storage.write(codec.serialize(doc.get(), camera?.get(), false))) {\n saveFailedShown = false;\n } else if (!saveFailedShown) {\n saveFailedShown = true; // tell once, not on every edit / сообщаем один раз, а не при каждой правке\n showNotice('error', keys.saveFailed);\n }\n }\n\n function scheduleSave() {\n if (!autosaveOn) return;\n clearTimeout(saveTimer);\n saveTimer = setTimeout(flushSave, autosaveDelay);\n }\n\n /**\n * Turns autosave on. Off by default (nothing is written in tests and before restore).\n * Edits are saved with a small delay, and at once when the tab is hidden or closed.\n * Returns a function that turns everything off.\n * Включает автосохранение. Выключено по умолчанию (в тестах и до восстановления ничего не пишется).\n * Правки сохраняются с небольшой задержкой, а при скрытии вкладки и закрытии сразу.\n * Возвращает функцию, которая всё отключает.\n */\n function startAutosave(): () => void {\n autosaveOn = true;\n const onHide = () => {\n if (document.visibilityState === 'hidden') flushSave();\n };\n window.addEventListener('pagehide', flushSave);\n document.addEventListener('visibilitychange', onHide);\n\n return () => {\n autosaveOn = false;\n clearTimeout(saveTimer);\n window.removeEventListener('pagehide', flushSave);\n document.removeEventListener('visibilitychange', onHide);\n };\n }\n\n //---]>\n // history\n // история\n\n const snapshot = () => JSON.stringify(doc.get());\n const history = new History(snapshot());\n const canUndo = ref(false);\n const canRedo = ref(false);\n\n function syncHistory() {\n canUndo.value = history.canUndo;\n canRedo.value = history.canRedo;\n scheduleSave(); // the document changed (an edit, undo or redo): autosave will pick it up / документ изменился (правка, undo или redo): автосохранение подхватит\n }\n\n /**\n * Remembers the current state as a history step. The same `key` in a row merges edits (typing text).\n * Запоминает текущее состояние как шаг истории. Одинаковый `key` подряд склеивает правки (набор текста).\n */\n function commit(key?: string) {\n history.commit(snapshot(), key);\n syncHistory();\n }\n\n function restore(state: string | null): boolean {\n if (state === null) return false;\n\n doc.set(JSON.parse(state) as D);\n options.onRestore?.(doc.get());\n syncHistory();\n return true;\n }\n\n const undo = () => restore(history.undo());\n const redo = () => restore(history.redo());\n\n /**\n * An action that changes the document: afterwards the state goes into history.\n * Действие, меняющее документ: после него состояние попадает в историю.\n */\n function recorded<A extends unknown[], R>(fn: (...args: A) => R, key?: (...args: A) => string): (...args: A) => R {\n return (...args) => {\n const result = fn(...args);\n commit(key?.(...args));\n return result;\n };\n }\n\n //---]>\n // opening, files, restore\n // открытие, файлы, восстановление\n\n /**\n * Replaces the document as a whole. Without `resetHistory` it is an ordinary edit: it can be undone.\n * Подменяет документ целиком. Без `resetHistory` это обычная правка: её можно отменить.\n */\n function load(next: D, view?: Camera, resetHistory = false) {\n doc.set(next);\n options.onReset?.();\n if (view && camera) camera.set({ x: view.x, y: view.y, z: clampZoom(view.z, zoomLimits(options.zoom)) });\n\n if (resetHistory) {\n history.reset(snapshot());\n syncHistory();\n } else {\n commit();\n }\n }\n\n /**\n * The file text for download.\n * Текст файла для скачивания.\n */\n const exportText = () => codec.serialize(doc.get(), camera?.get(), true);\n\n /**\n * Opens a document from file text. On an error the document is unchanged. The result is shown as a notice.\n * Открывает документ из текста файла. При ошибке документ не меняется. Результат показывается уведомлением.\n */\n function importText(text: string): LoadError | null {\n const result = codec.parse(text);\n if (!result.ok) {\n const { code, detail } = result.error;\n showNotice('error', keys.loadError(code), detail === undefined ? undefined : [detail]);\n return result.error;\n }\n\n load(result.doc, result.view);\n const items = count(result.doc);\n if (result.dropped > 0) showNotice('error', keys.loadedWithDropped, [items, result.dropped]);\n else showNotice('info', keys.loaded, [items]);\n return null;\n }\n\n function newDocument() {\n load(options.empty(), { x: 0, y: 0, z: 1 });\n showNotice('info', keys.newDocument);\n }\n\n /**\n * At app start: brings the document back from autosave. Returns true if there was something to restore.\n * При старте приложения: поднимает документ из автосохранения. Возвращает true, если было что поднимать.\n */\n function restoreSaved(): boolean {\n const text = storage.read();\n if (text === null) return false;\n\n const result = codec.parse(text);\n if (!result.ok) {\n storage.backupBroken(text);\n showNotice('error', keys.restoreFailed);\n return false;\n }\n\n load(result.doc, result.view, true);\n return true;\n }\n\n return {\n notice,\n showNotice,\n canUndo,\n canRedo,\n commit,\n undo,\n redo,\n recorded,\n load,\n exportText,\n importText,\n newDocument,\n restoreSaved,\n startAutosave,\n flushSave,\n };\n}\n\nexport type DocumentSession<D, K extends string> = ReturnType<typeof createDocumentSession<D, K>>;\n"],"mappings":";;;;AAwGA,IAAM,oBAAoB;AAC1B,IAAM,sBAAsB;;;;;;;;;AAU5B,SAAgB,sBAA2C,SAA+B;CACtF,MAAM,EAAE,UAAU,KAAK,QAAQ,SAAS,OAAO,SAAS;CACxD,MAAM,WAAW,QAAQ,YAAY;CACrC,MAAM,SAAS,OAAU,QAAQ,cAAc,QAAQ,WAAA,GAAc,CAAC,KAAK;CAC3E,MAAM,gBAAgB,QAAQ,iBAAiB;CAM/C,MAAM,SAAS,IAA6B,IAAI;CAChD,IAAI;CAEJ,SAAS,WAAW,MAAgC,KAAQ,MAAmB;EAC3E,OAAO,QAAQ;GAAE;GAAM;GAAK;EAAK;EACjC,aAAa,WAAW;EACxB,cAAc,iBAAkB,OAAO,QAAQ,MAAO,QAAQ;CAClE;CAMA,IAAI,aAAa;CACjB,IAAI;CACJ,IAAI,kBAAkB;;;;;CAMtB,SAAS,YAAY;EACjB,aAAa,SAAS;EACtB,YAAY,KAAA;EACZ,IAAI,CAAC,YAA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AAI;EAC/B,IAAI,CAAC,OAAO,IAAI;GACZ,QAAQ,aAAa,IAAI;GACzB,WAAW,SAAS,KAAK,aAAa;GACtC,OAAO;EACX;EAEA,KAAK,OAAO,KAAK,OAAO,MAAM,IAAI;EAClC,OAAO;CACX;CAEA,OAAO;EACH;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACJ;AACJ"}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A step of a tour. Only `id` is required: the rest (a target, a text, a placement) is yours, the model carries it.
|
|
3
|
+
* Шаг тура. Обязателен только `id`: остальное (цель, текст, место) ваше, модель его просто несёт.
|
|
4
|
+
*/
|
|
5
|
+
export interface TourStep {
|
|
6
|
+
id: string;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* How a tour ended: `done` (the last step was passed or `finish()`) or `skipped` (`skip()`, Esc, the cross).
|
|
10
|
+
* Как закончился тур: `done` (прошли последний шаг или `finish()`) или `skipped` (`skip()`, Esc, крестик).
|
|
11
|
+
*/
|
|
12
|
+
export type TourEnd = 'done' | 'skipped';
|
|
13
|
+
export interface TourState<S extends TourStep = TourStep> {
|
|
14
|
+
/** Whether a step is on screen. / Показан ли шаг. */
|
|
15
|
+
active: boolean;
|
|
16
|
+
/** The index of the current step in `steps` (-1 while not active). / Индекс текущего шага в `steps` (-1, пока тур не идёт). */
|
|
17
|
+
index: number;
|
|
18
|
+
/** The current step, or null. / Текущий шаг или null. */
|
|
19
|
+
step: S | null;
|
|
20
|
+
/** How many steps there are (also those that are jumped over now). / Сколько всего шагов (и тех, что сейчас перепрыгиваются). */
|
|
21
|
+
count: number;
|
|
22
|
+
/**
|
|
23
|
+
* The place of the current step among the steps that can be shown now, from 0, and how many of those there are: what
|
|
24
|
+
* a counter ("2 of 4") and the dots want, since the steps that are jumped over are not counted. `index` / `count`
|
|
25
|
+
* stay the place in the whole list.
|
|
26
|
+
* Место текущего шага среди шагов, которые можно показать сейчас, с 0, и сколько таких всего: то, что нужно счётчику
|
|
27
|
+
* («2 из 4») и точкам, ведь перепрыгиваемые шаги не считаются. `index` / `count` — место в полном списке.
|
|
28
|
+
*/
|
|
29
|
+
position: number;
|
|
30
|
+
total: number;
|
|
31
|
+
/** No step to go back to. / Назад идти некуда. */
|
|
32
|
+
first: boolean;
|
|
33
|
+
/** No step to go on to: `next()` ends the tour. / Дальше идти некуда: `next()` завершает тур. */
|
|
34
|
+
last: boolean;
|
|
35
|
+
}
|
|
36
|
+
export interface TourOptions<S extends TourStep = TourStep> {
|
|
37
|
+
steps: S[];
|
|
38
|
+
/**
|
|
39
|
+
* Whether a step can be shown now (its target is on the page, the user has the right). A step that cannot is
|
|
40
|
+
* jumped over, in either direction. Called at every move, so it may look at the page.
|
|
41
|
+
* Можно ли показать шаг сейчас (его цель есть на странице, у пользователя есть право). Шаг, который нельзя,
|
|
42
|
+
* перепрыгивается в обе стороны. Вызывается при каждом переходе, поэтому может смотреть на страницу.
|
|
43
|
+
*/
|
|
44
|
+
available?: (step: S, index: number) => boolean;
|
|
45
|
+
/** Called once when a tour ends. / Вызывается один раз, когда тур закончился. */
|
|
46
|
+
onEnd?: (reason: TourEnd, step: S | null) => void;
|
|
47
|
+
}
|
|
48
|
+
export interface Tour<S extends TourStep = TourStep> extends TourState<S> {
|
|
49
|
+
/**
|
|
50
|
+
* Starts at step `at` (an index or an `id`; the first by default). If that step cannot be shown, the next one
|
|
51
|
+
* that can is taken. Returns false, and nothing starts, when there is no such step.
|
|
52
|
+
* Начинает с шага `at` (индекс или `id`; по умолчанию первый). Если его нельзя показать, берётся ближайший
|
|
53
|
+
* следующий, который можно. Возвращает false, и ничего не начинается, если такого шага нет.
|
|
54
|
+
*/
|
|
55
|
+
start(at?: number | string): boolean;
|
|
56
|
+
/** The next step; from the last one it ends the tour as `done`. / Следующий шаг; с последнего завершает тур как `done`. */
|
|
57
|
+
next(): void;
|
|
58
|
+
/** The previous step; from the first one it stays. / Предыдущий шаг; с первого остаётся на месте. */
|
|
59
|
+
prev(): void;
|
|
60
|
+
/** Jumps to a step (an index or an `id`); false if it does not exist or cannot be shown. / Переход к шагу; false, если шага нет или его нельзя показать. */
|
|
61
|
+
goTo(target: number | string): boolean;
|
|
62
|
+
/** Ends the tour as `skipped`. / Завершает тур как `skipped`. */
|
|
63
|
+
skip(): void;
|
|
64
|
+
/** Ends the tour as `done`. / Завершает тур как `done`. */
|
|
65
|
+
finish(): void;
|
|
66
|
+
/**
|
|
67
|
+
* Replaces the steps. A tour that runs stays on the step with the same `id`, or, when it is gone, moves to the next
|
|
68
|
+
* one that can be shown, or ends as `done`.
|
|
69
|
+
* Заменяет шаги. Идущий тур остаётся на шаге с тем же `id`, а если его нет, переходит к ближайшему показываемому
|
|
70
|
+
* или завершается как `done`.
|
|
71
|
+
*/
|
|
72
|
+
setSteps(steps: S[]): void;
|
|
73
|
+
/** The listener is called on any change. Returns the unsubscribe function. / Слушатель вызывается при любом изменении. */
|
|
74
|
+
subscribe(listener: (state: TourState<S>) => void): () => void;
|
|
75
|
+
dispose(): void;
|
|
76
|
+
}
|
|
77
|
+
export declare function createTour<S extends TourStep = TourStep>(options: TourOptions<S>): Tour<S>;
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { type KeyStorage } from '../storage';
|
|
2
|
+
/**
|
|
3
|
+
* What a user has already seen of a tour, kept in localStorage under `key`, so a tour does not come back at every visit.
|
|
4
|
+
* Storage may be forbidden (private mode): then nothing is remembered and nothing throws.
|
|
5
|
+
* Что пользователь уже видел из тура; лежит в localStorage под ключом `key`, чтобы тур не возвращался при каждом визите.
|
|
6
|
+
* Хранилище может быть запрещено (приватный режим): тогда ничего не запоминается и ничего не бросает исключений.
|
|
7
|
+
*/
|
|
8
|
+
export interface TourMemory {
|
|
9
|
+
/** Whether the tour was ended (done or skipped) before. / Заканчивали ли тур раньше. */
|
|
10
|
+
seen(): boolean;
|
|
11
|
+
/** Remembers that the tour was ended. / Запоминает, что тур закончен. */
|
|
12
|
+
markSeen(): boolean;
|
|
13
|
+
/** Forgets it: the tour can show again ("show the tour once more" in a menu). / Забывает: тур снова можно показать. */
|
|
14
|
+
reset(): boolean;
|
|
15
|
+
}
|
|
16
|
+
export declare function createTourMemory(key: string, storage?: KeyStorage): TourMemory;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { type ToRefs } from 'vue';
|
|
2
|
+
import { type Tour, type TourOptions, type TourState, type TourStep } from './core';
|
|
3
|
+
export type UseTour<S extends TourStep = TourStep> = ToRefs<TourState<S>> & {
|
|
4
|
+
start: Tour<S>['start'];
|
|
5
|
+
next(): void;
|
|
6
|
+
prev(): void;
|
|
7
|
+
goTo: Tour<S>['goTo'];
|
|
8
|
+
skip(): void;
|
|
9
|
+
finish(): void;
|
|
10
|
+
setSteps(steps: S[]): void;
|
|
11
|
+
/**
|
|
12
|
+
* The model without Vue: for cases that need its full API (subscribe).
|
|
13
|
+
* Модель без Vue: для случаев, когда нужен её полный API (subscribe).
|
|
14
|
+
*/
|
|
15
|
+
tour: Tour<S>;
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* A tour for a Vue component: reactive state on top of `createTour`; it is let go on unmount.
|
|
19
|
+
* Тур для компонента Vue: реактивное состояние поверх `createTour`; при размонтировании отпускается.
|
|
20
|
+
*/
|
|
21
|
+
export declare function useTour<S extends TourStep = TourStep>(options: TourOptions<S>): UseTour<S>;
|
package/dist/tour.js
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import { createSavedStorage } from "./storage.js";
|
|
2
|
+
import { onBeforeUnmount, reactive, toRefs } from "vue";
|
|
3
|
+
//#region src/tour/core.ts
|
|
4
|
+
function createTour(options) {
|
|
5
|
+
let steps = [...options.steps];
|
|
6
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
7
|
+
let disposed = false;
|
|
8
|
+
const can = (i) => i >= 0 && i < steps.length && (options.available?.(steps[i], i) ?? true);
|
|
9
|
+
/** The nearest showable step from `from` (included) in a direction, or -1. / Ближайший показываемый шаг от `from` (включая его) или -1. */
|
|
10
|
+
function seek(from, dir) {
|
|
11
|
+
for (let i = from; i >= 0 && i < steps.length; i += dir) if (can(i)) return i;
|
|
12
|
+
return -1;
|
|
13
|
+
}
|
|
14
|
+
const tour = {
|
|
15
|
+
active: false,
|
|
16
|
+
index: -1,
|
|
17
|
+
step: null,
|
|
18
|
+
count: steps.length,
|
|
19
|
+
position: -1,
|
|
20
|
+
total: 0,
|
|
21
|
+
first: true,
|
|
22
|
+
last: true
|
|
23
|
+
};
|
|
24
|
+
function sync() {
|
|
25
|
+
tour.count = steps.length;
|
|
26
|
+
tour.step = tour.active ? steps[tour.index] ?? null : null;
|
|
27
|
+
let total = 0;
|
|
28
|
+
let position = -1;
|
|
29
|
+
for (let i = 0; i < steps.length; i++) {
|
|
30
|
+
if (!can(i)) continue;
|
|
31
|
+
if (i <= tour.index) position = tour.active ? total : -1;
|
|
32
|
+
total++;
|
|
33
|
+
}
|
|
34
|
+
tour.total = total;
|
|
35
|
+
tour.position = position;
|
|
36
|
+
tour.first = !tour.active || seek(tour.index - 1, -1) < 0;
|
|
37
|
+
tour.last = !tour.active || seek(tour.index + 1, 1) < 0;
|
|
38
|
+
}
|
|
39
|
+
function emit() {
|
|
40
|
+
sync();
|
|
41
|
+
const state = {
|
|
42
|
+
active: tour.active,
|
|
43
|
+
index: tour.index,
|
|
44
|
+
step: tour.step,
|
|
45
|
+
count: tour.count,
|
|
46
|
+
position: tour.position,
|
|
47
|
+
total: tour.total,
|
|
48
|
+
first: tour.first,
|
|
49
|
+
last: tour.last
|
|
50
|
+
};
|
|
51
|
+
for (const listener of [...listeners]) listener(state);
|
|
52
|
+
}
|
|
53
|
+
function end(reason) {
|
|
54
|
+
if (!tour.active) return;
|
|
55
|
+
const last = steps[tour.index] ?? null;
|
|
56
|
+
tour.active = false;
|
|
57
|
+
tour.index = -1;
|
|
58
|
+
emit();
|
|
59
|
+
options.onEnd?.(reason, last);
|
|
60
|
+
}
|
|
61
|
+
const indexOf = (target) => typeof target === "string" ? steps.findIndex((s) => s.id === target) : target;
|
|
62
|
+
function show(index) {
|
|
63
|
+
tour.active = true;
|
|
64
|
+
tour.index = index;
|
|
65
|
+
emit();
|
|
66
|
+
}
|
|
67
|
+
tour.start = (at = 0) => {
|
|
68
|
+
if (disposed) return false;
|
|
69
|
+
const from = indexOf(at);
|
|
70
|
+
const found = from < 0 ? -1 : seek(from, 1);
|
|
71
|
+
if (found < 0) return false;
|
|
72
|
+
show(found);
|
|
73
|
+
return true;
|
|
74
|
+
};
|
|
75
|
+
tour.next = () => {
|
|
76
|
+
if (!tour.active) return;
|
|
77
|
+
const found = seek(tour.index + 1, 1);
|
|
78
|
+
if (found < 0) end("done");
|
|
79
|
+
else show(found);
|
|
80
|
+
};
|
|
81
|
+
tour.prev = () => {
|
|
82
|
+
if (!tour.active) return;
|
|
83
|
+
const found = seek(tour.index - 1, -1);
|
|
84
|
+
if (found >= 0) show(found);
|
|
85
|
+
};
|
|
86
|
+
tour.goTo = (target) => {
|
|
87
|
+
const i = indexOf(target);
|
|
88
|
+
if (!tour.active || !can(i)) return false;
|
|
89
|
+
show(i);
|
|
90
|
+
return true;
|
|
91
|
+
};
|
|
92
|
+
tour.skip = () => end("skipped");
|
|
93
|
+
tour.finish = () => end("done");
|
|
94
|
+
tour.setSteps = (next) => {
|
|
95
|
+
const id = tour.step?.id;
|
|
96
|
+
const following = steps.slice(tour.index + 1).map((s) => s.id);
|
|
97
|
+
steps = [...next];
|
|
98
|
+
if (!tour.active) {
|
|
99
|
+
emit();
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
const same = id === void 0 ? -1 : steps.findIndex((s) => s.id === id);
|
|
103
|
+
let found = same >= 0 && can(same) ? same : same >= 0 ? seek(same + 1, 1) : -1;
|
|
104
|
+
for (const nextId of same >= 0 ? [] : following) {
|
|
105
|
+
const at = steps.findIndex((s) => s.id === nextId);
|
|
106
|
+
if (found < 0 && at >= 0 && can(at)) found = at;
|
|
107
|
+
}
|
|
108
|
+
if (found < 0) end("done");
|
|
109
|
+
else show(found);
|
|
110
|
+
};
|
|
111
|
+
tour.subscribe = (listener) => {
|
|
112
|
+
listeners.add(listener);
|
|
113
|
+
return () => listeners.delete(listener);
|
|
114
|
+
};
|
|
115
|
+
tour.dispose = () => {
|
|
116
|
+
disposed = true;
|
|
117
|
+
tour.active = false;
|
|
118
|
+
tour.index = -1;
|
|
119
|
+
listeners.clear();
|
|
120
|
+
sync();
|
|
121
|
+
};
|
|
122
|
+
sync();
|
|
123
|
+
return tour;
|
|
124
|
+
}
|
|
125
|
+
//#endregion
|
|
126
|
+
//#region src/tour/memory.ts
|
|
127
|
+
function createTourMemory(key, storage = createSavedStorage(key)) {
|
|
128
|
+
return {
|
|
129
|
+
seen: () => storage.read() === "1",
|
|
130
|
+
markSeen: () => storage.write("1"),
|
|
131
|
+
reset: () => storage.remove()
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
//#endregion
|
|
135
|
+
//#region src/tour/use.ts
|
|
136
|
+
/**
|
|
137
|
+
* A tour for a Vue component: reactive state on top of `createTour`; it is let go on unmount.
|
|
138
|
+
* Тур для компонента Vue: реактивное состояние поверх `createTour`; при размонтировании отпускается.
|
|
139
|
+
*/
|
|
140
|
+
function useTour(options) {
|
|
141
|
+
const tour = createTour(options);
|
|
142
|
+
const state = reactive({
|
|
143
|
+
active: tour.active,
|
|
144
|
+
index: tour.index,
|
|
145
|
+
step: tour.step,
|
|
146
|
+
count: tour.count,
|
|
147
|
+
position: tour.position,
|
|
148
|
+
total: tour.total,
|
|
149
|
+
first: tour.first,
|
|
150
|
+
last: tour.last
|
|
151
|
+
});
|
|
152
|
+
const stop = tour.subscribe((s) => Object.assign(state, s));
|
|
153
|
+
onBeforeUnmount(() => {
|
|
154
|
+
stop();
|
|
155
|
+
tour.dispose();
|
|
156
|
+
});
|
|
157
|
+
return {
|
|
158
|
+
...toRefs(state),
|
|
159
|
+
start: tour.start,
|
|
160
|
+
next: tour.next,
|
|
161
|
+
prev: tour.prev,
|
|
162
|
+
goTo: tour.goTo,
|
|
163
|
+
skip: tour.skip,
|
|
164
|
+
finish: tour.finish,
|
|
165
|
+
setSteps: tour.setSteps,
|
|
166
|
+
tour
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
//#endregion
|
|
170
|
+
export { createTour, createTourMemory, useTour };
|
|
171
|
+
|
|
172
|
+
//# sourceMappingURL=tour.js.map
|
package/dist/tour.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tour.js","names":[],"sources":["../src/tour/core.ts","../src/tour/memory.ts","../src/tour/use.ts"],"sourcesContent":["/**\n * A step of a tour. Only `id` is required: the rest (a target, a text, a placement) is yours, the model carries it.\n * Шаг тура. Обязателен только `id`: остальное (цель, текст, место) ваше, модель его просто несёт.\n */\nexport interface TourStep {\n id: string;\n}\n\n/**\n * How a tour ended: `done` (the last step was passed or `finish()`) or `skipped` (`skip()`, Esc, the cross).\n * Как закончился тур: `done` (прошли последний шаг или `finish()`) или `skipped` (`skip()`, Esc, крестик).\n */\nexport type TourEnd = 'done' | 'skipped';\n\nexport interface TourState<S extends TourStep = TourStep> {\n /** Whether a step is on screen. / Показан ли шаг. */\n active: boolean;\n /** The index of the current step in `steps` (-1 while not active). / Индекс текущего шага в `steps` (-1, пока тур не идёт). */\n index: number;\n /** The current step, or null. / Текущий шаг или null. */\n step: S | null;\n /** How many steps there are (also those that are jumped over now). / Сколько всего шагов (и тех, что сейчас перепрыгиваются). */\n count: number;\n /**\n * The place of the current step among the steps that can be shown now, from 0, and how many of those there are: what\n * a counter (\"2 of 4\") and the dots want, since the steps that are jumped over are not counted. `index` / `count`\n * stay the place in the whole list.\n * Место текущего шага среди шагов, которые можно показать сейчас, с 0, и сколько таких всего: то, что нужно счётчику\n * («2 из 4») и точкам, ведь перепрыгиваемые шаги не считаются. `index` / `count` — место в полном списке.\n */\n position: number;\n total: number;\n /** No step to go back to. / Назад идти некуда. */\n first: boolean;\n /** No step to go on to: `next()` ends the tour. / Дальше идти некуда: `next()` завершает тур. */\n last: boolean;\n}\n\nexport interface TourOptions<S extends TourStep = TourStep> {\n steps: S[];\n /**\n * Whether a step can be shown now (its target is on the page, the user has the right). A step that cannot is\n * jumped over, in either direction. Called at every move, so it may look at the page.\n * Можно ли показать шаг сейчас (его цель есть на странице, у пользователя есть право). Шаг, который нельзя,\n * перепрыгивается в обе стороны. Вызывается при каждом переходе, поэтому может смотреть на страницу.\n */\n available?: (step: S, index: number) => boolean;\n /** Called once when a tour ends. / Вызывается один раз, когда тур закончился. */\n onEnd?: (reason: TourEnd, step: S | null) => void;\n}\n\nexport interface Tour<S extends TourStep = TourStep> extends TourState<S> {\n /**\n * Starts at step `at` (an index or an `id`; the first by default). If that step cannot be shown, the next one\n * that can is taken. Returns false, and nothing starts, when there is no such step.\n * Начинает с шага `at` (индекс или `id`; по умолчанию первый). Если его нельзя показать, берётся ближайший\n * следующий, который можно. Возвращает false, и ничего не начинается, если такого шага нет.\n */\n start(at?: number | string): boolean;\n /** The next step; from the last one it ends the tour as `done`. / Следующий шаг; с последнего завершает тур как `done`. */\n next(): void;\n /** The previous step; from the first one it stays. / Предыдущий шаг; с первого остаётся на месте. */\n prev(): void;\n /** Jumps to a step (an index or an `id`); false if it does not exist or cannot be shown. / Переход к шагу; false, если шага нет или его нельзя показать. */\n goTo(target: number | string): boolean;\n /** Ends the tour as `skipped`. / Завершает тур как `skipped`. */\n skip(): void;\n /** Ends the tour as `done`. / Завершает тур как `done`. */\n finish(): void;\n /**\n * Replaces the steps. A tour that runs stays on the step with the same `id`, or, when it is gone, moves to the next\n * one that can be shown, or ends as `done`.\n * Заменяет шаги. Идущий тур остаётся на шаге с тем же `id`, а если его нет, переходит к ближайшему показываемому\n * или завершается как `done`.\n */\n setSteps(steps: S[]): void;\n /** The listener is called on any change. Returns the unsubscribe function. / Слушатель вызывается при любом изменении. */\n subscribe(listener: (state: TourState<S>) => void): () => void;\n dispose(): void;\n}\n\nexport function createTour<S extends TourStep = TourStep>(options: TourOptions<S>): Tour<S> {\n let steps = [...options.steps];\n const listeners = new Set<(state: TourState<S>) => void>();\n let disposed = false;\n\n const can = (i: number) => i >= 0 && i < steps.length && (options.available?.(steps[i]!, i) ?? true);\n\n /** The nearest showable step from `from` (included) in a direction, or -1. / Ближайший показываемый шаг от `from` (включая его) или -1. */\n function seek(from: number, dir: 1 | -1): number {\n for (let i = from; i >= 0 && i < steps.length; i += dir) {\n if (can(i)) {\n return i;\n }\n }\n return -1;\n }\n\n const tour = {\n active: false,\n index: -1,\n step: null as S | null,\n count: steps.length,\n position: -1,\n total: 0,\n first: true,\n last: true,\n } as Tour<S>;\n\n function sync() {\n tour.count = steps.length;\n tour.step = tour.active ? (steps[tour.index] ?? null) : null;\n let total = 0;\n let position = -1;\n for (let i = 0; i < steps.length; i++) {\n if (!can(i)) continue;\n if (i <= tour.index) position = tour.active ? total : -1;\n total++;\n }\n tour.total = total;\n tour.position = position;\n tour.first = !tour.active || seek(tour.index - 1, -1) < 0;\n tour.last = !tour.active || seek(tour.index + 1, 1) < 0;\n }\n\n function emit() {\n sync();\n const state: TourState<S> = { active: tour.active, index: tour.index, step: tour.step, count: tour.count, position: tour.position, total: tour.total, first: tour.first, last: tour.last };\n for (const listener of [...listeners]) {\n listener(state);\n }\n }\n\n function end(reason: TourEnd) {\n if (!tour.active) {\n return;\n }\n const last = steps[tour.index] ?? null;\n tour.active = false;\n tour.index = -1;\n emit();\n options.onEnd?.(reason, last);\n }\n\n const indexOf = (target: number | string) => (typeof target === 'string' ? steps.findIndex((s) => s.id === target) : target);\n\n function show(index: number) {\n tour.active = true;\n tour.index = index;\n emit();\n }\n\n tour.start = (at = 0) => {\n if (disposed) {\n return false;\n }\n const from = indexOf(at);\n const found = from < 0 ? -1 : seek(from, 1);\n if (found < 0) {\n return false;\n }\n show(found);\n return true;\n };\n\n tour.next = () => {\n if (!tour.active) {\n return;\n }\n const found = seek(tour.index + 1, 1);\n if (found < 0) {\n end('done');\n } else {\n show(found);\n }\n };\n\n tour.prev = () => {\n if (!tour.active) {\n return;\n }\n const found = seek(tour.index - 1, -1);\n if (found >= 0) {\n show(found);\n }\n };\n\n tour.goTo = (target) => {\n const i = indexOf(target);\n if (!tour.active || !can(i)) {\n return false;\n }\n show(i);\n return true;\n };\n\n tour.skip = () => end('skipped');\n tour.finish = () => end('done');\n\n tour.setSteps = (next) => {\n const id = tour.step?.id;\n // the steps after the current one, in the old order: where to go when the current one is gone\n // шаги после текущего в старом порядке: куда идти, если текущий пропал\n const following = steps.slice(tour.index + 1).map((s) => s.id);\n steps = [...next];\n if (!tour.active) {\n emit();\n return;\n }\n const same = id === undefined ? -1 : steps.findIndex((s) => s.id === id);\n let found = same >= 0 && can(same) ? same : same >= 0 ? seek(same + 1, 1) : -1;\n for (const nextId of same >= 0 ? [] : following) {\n const at = steps.findIndex((s) => s.id === nextId);\n if (found < 0 && at >= 0 && can(at)) {\n found = at;\n }\n }\n if (found < 0) {\n end('done');\n } else {\n show(found);\n }\n };\n\n tour.subscribe = (listener) => {\n listeners.add(listener);\n return () => listeners.delete(listener);\n };\n\n tour.dispose = () => {\n disposed = true;\n tour.active = false;\n tour.index = -1;\n listeners.clear();\n sync();\n };\n\n sync();\n return tour;\n}\n","import { createSavedStorage, type KeyStorage } from '../storage';\n\n/**\n * What a user has already seen of a tour, kept in localStorage under `key`, so a tour does not come back at every visit.\n * Storage may be forbidden (private mode): then nothing is remembered and nothing throws.\n * Что пользователь уже видел из тура; лежит в localStorage под ключом `key`, чтобы тур не возвращался при каждом визите.\n * Хранилище может быть запрещено (приватный режим): тогда ничего не запоминается и ничего не бросает исключений.\n */\nexport interface TourMemory {\n /** Whether the tour was ended (done or skipped) before. / Заканчивали ли тур раньше. */\n seen(): boolean;\n /** Remembers that the tour was ended. / Запоминает, что тур закончен. */\n markSeen(): boolean;\n /** Forgets it: the tour can show again (\"show the tour once more\" in a menu). / Забывает: тур снова можно показать. */\n reset(): boolean;\n}\n\nexport function createTourMemory(key: string, storage: KeyStorage = createSavedStorage(key)): TourMemory {\n return {\n seen: () => storage.read() === '1',\n markSeen: () => storage.write('1'),\n reset: () => storage.remove(),\n };\n}\n","import { onBeforeUnmount, reactive, toRefs, type ToRefs } from 'vue';\nimport { createTour, type Tour, type TourOptions, type TourState, type TourStep } from './core';\n\nexport type UseTour<S extends TourStep = TourStep> = ToRefs<TourState<S>> & {\n start: Tour<S>['start'];\n next(): void;\n prev(): void;\n goTo: Tour<S>['goTo'];\n skip(): void;\n finish(): void;\n setSteps(steps: S[]): void;\n /**\n * The model without Vue: for cases that need its full API (subscribe).\n * Модель без Vue: для случаев, когда нужен её полный API (subscribe).\n */\n tour: Tour<S>;\n};\n\n/**\n * A tour for a Vue component: reactive state on top of `createTour`; it is let go on unmount.\n * Тур для компонента Vue: реактивное состояние поверх `createTour`; при размонтировании отпускается.\n */\nexport function useTour<S extends TourStep = TourStep>(options: TourOptions<S>): UseTour<S> {\n const tour = createTour(options);\n const state = reactive({ active: tour.active, index: tour.index, step: tour.step, count: tour.count, position: tour.position, total: tour.total, first: tour.first, last: tour.last }) as TourState<S>;\n const stop = tour.subscribe((s) => Object.assign(state, s));\n onBeforeUnmount(() => {\n stop();\n tour.dispose();\n });\n\n return {\n ...toRefs(state),\n start: tour.start,\n next: tour.next,\n prev: tour.prev,\n goTo: tour.goTo,\n skip: tour.skip,\n finish: tour.finish,\n setSteps: tour.setSteps,\n tour,\n } as UseTour<S>;\n}\n"],"mappings":";;;AAiFA,SAAgB,WAA0C,SAAkC;CACxF,IAAI,QAAQ,CAAC,GAAG,QAAQ,KAAK;CAC7B,MAAM,4BAAY,IAAI,IAAmC;CACzD,IAAI,WAAW;CAEf,MAAM,OAAO,MAAc,KAAK,KAAK,IAAI,MAAM,WAAW,QAAQ,YAAY,MAAM,IAAK,CAAC,KAAK;;CAG/F,SAAS,KAAK,MAAc,KAAqB;EAC7C,KAAK,IAAI,I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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.1",
|
|
4
4
|
"description": "Interaction and behavior building blocks for Vue apps: curve and gradient editors, canvas, undo/redo, playback. Import only what you need, bring your own design.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"vue",
|
|
@@ -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",
|