@1337exp/taoux 0.2.1 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +17 -0
- package/README.md +6 -5
- package/README.ru.md +6 -5
- package/dist/file.d.ts +16 -3
- package/dist/file.js +27 -5
- package/dist/file.js.map +1 -1
- package/dist/gestures.d.ts +79 -0
- package/dist/gestures.js +121 -1
- package/dist/gestures.js.map +1 -1
- package/dist/ids.d.ts +13 -0
- package/dist/ids.js +25 -1
- package/dist/ids.js.map +1 -1
- package/dist/session.d.ts +15 -4
- package/dist/session.js +7 -6
- package/dist/session.js.map +1 -1
- package/dist/storage.d.ts +39 -1
- package/dist/storage.js +44 -3
- package/dist/storage.js.map +1 -1
- package/dist/undo.d.ts +113 -0
- package/dist/undo.js +166 -0
- package/dist/undo.js.map +1 -0
- package/package.json +5 -1
- package/skills/taoux/SKILL.md +7 -5
package/dist/session.js
CHANGED
|
@@ -15,6 +15,7 @@ var DEFAULT_AUTOSAVE_MS = 400;
|
|
|
15
15
|
function createDocumentSession(options) {
|
|
16
16
|
const { document: doc, camera, storage, codec, keys } = options;
|
|
17
17
|
const noticeMs = options.noticeMs ?? DEFAULT_NOTICE_MS;
|
|
18
|
+
const count = (d) => (options.countItems ?? options.countNodes)?.(d) ?? 0;
|
|
18
19
|
const autosaveDelay = options.autosaveDelay ?? DEFAULT_AUTOSAVE_MS;
|
|
19
20
|
const notice = ref(null);
|
|
20
21
|
let noticeTimer;
|
|
@@ -38,7 +39,7 @@ function createDocumentSession(options) {
|
|
|
38
39
|
clearTimeout(saveTimer);
|
|
39
40
|
saveTimer = void 0;
|
|
40
41
|
if (!autosaveOn) return;
|
|
41
|
-
if (storage.write(codec.serialize(doc.get(), camera
|
|
42
|
+
if (storage.write(codec.serialize(doc.get(), camera?.get(), false))) saveFailedShown = false;
|
|
42
43
|
else if (!saveFailedShown) {
|
|
43
44
|
saveFailedShown = true;
|
|
44
45
|
showNotice("error", keys.saveFailed);
|
|
@@ -115,7 +116,7 @@ function createDocumentSession(options) {
|
|
|
115
116
|
function load(next, view, resetHistory = false) {
|
|
116
117
|
doc.set(next);
|
|
117
118
|
options.onReset?.();
|
|
118
|
-
if (view) camera.set({
|
|
119
|
+
if (view && camera) camera.set({
|
|
119
120
|
x: view.x,
|
|
120
121
|
y: view.y,
|
|
121
122
|
z: Math.min(2, Math.max(MIN_ZOOM, view.z))
|
|
@@ -129,7 +130,7 @@ function createDocumentSession(options) {
|
|
|
129
130
|
* The file text for download.
|
|
130
131
|
* Текст файла для скачивания.
|
|
131
132
|
*/
|
|
132
|
-
const exportText = () => codec.serialize(doc.get(), camera
|
|
133
|
+
const exportText = () => codec.serialize(doc.get(), camera?.get(), true);
|
|
133
134
|
/**
|
|
134
135
|
* Opens a document from file text. On an error the document is unchanged. The result is shown as a notice.
|
|
135
136
|
* Открывает документ из текста файла. При ошибке документ не меняется. Результат показывается уведомлением.
|
|
@@ -142,9 +143,9 @@ function createDocumentSession(options) {
|
|
|
142
143
|
return result.error;
|
|
143
144
|
}
|
|
144
145
|
load(result.doc, result.view);
|
|
145
|
-
const
|
|
146
|
-
if (result.dropped > 0) showNotice("error", keys.loadedWithDropped, [
|
|
147
|
-
else showNotice("info", keys.loaded, [
|
|
146
|
+
const items = count(result.doc);
|
|
147
|
+
if (result.dropped > 0) showNotice("error", keys.loadedWithDropped, [items, result.dropped]);
|
|
148
|
+
else showNotice("info", keys.loaded, [items]);
|
|
148
149
|
return null;
|
|
149
150
|
}
|
|
150
151
|
function newDocument() {
|
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 nodes / {0} — число нод\n loadedWithDropped: K; // {0} is the number of nodes, {1} how many links were 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 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 nodes are in the document: substituted into the message about opening a file.\n * Сколько нод в документе: подставляется в сообщение об открытии файла.\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 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.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 nodes = options.countNodes(result.doc);\n if (result.dropped > 0) showNotice('error', keys.loadedWithDropped, [nodes, result.dropped]);\n else showNotice('info', keys.loaded, [nodes]);\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":";;;;AAwFA,IAAM,oBAAoB;AAC1B,IAAM,sBAAsB;;;;;;;;;AAU5B,SAAgB,sBAA2C,SAA+B;C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AI;EAC5B,MAAM,QAAQ,QAAQ,WAAW,OAAO,GAAG;EAC3C,IAAI,OAAO,UAAU,GAAG,WAAW,SAAS,KAAK,mBAAmB,CAAC,OAAO,OAAO,OAAO,CAAC;OACtF,WAAW,QAAQ,KAAK,QAAQ,CAAC,KAAK,CAAC;EAC5C,OAAO;CACX;CAEA,SAAS,cAAc;EACnB,KAAK,QAAQ,MAAM,GAAG;GAAE,GAAG;GAAG,GAAG;GAAG,GAAG;EAAE,CAAC;EAC1C,WAAW,QAAQ,KAAK,WAAW;CACvC;;;;;CAMA,SAAS,eAAwB;EAC7B,MAAM,OAAO,QAAQ,KAAK;EAC1B,IAAI,SAAS,MAAM,OAAO;EAE1B,MAAM,SAAS,MAAM,MAAM,IAAI;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"}
|
|
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":";;;;AA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AM,WAAW,OAAO;GAChC,WAAW,SAAS,KAAK,UAAU,IAAI,GAAG,WAAW,KAAA,IAAY,KAAA,IAAY,CAAC,MAAM,CAAC;GACrF,OAAO,OAAO;EAClB;EAEA,KAAK,OAAO,KAAK,OAAO,IAAI;EAC5B,MAAM,QAAQ,MAAM,OAAO,GAAG;EAC9B,IAAI,OAAO,UAAU,GAAG,WAAW,SAAS,KAAK,mBAAmB,CAAC,OAAO,OAAO,OAAO,CAAC;OACtF,WAAW,QAAQ,KAAK,QAAQ,CAAC,KAAK,CAAC;EAC5C,OAAO;CACX;CAEA,SAAS,cAAc;EACnB,KAAK,QAAQ,MAAM,GAAG;GAAE,GAAG;GAAG,GAAG;GAAG,GAAG;EAAE,CAAC;EAC1C,WAAW,QAAQ,KAAK,WAAW;CACvC;;;;;CAMA,SAAS,eAAwB;EAC7B,MAAM,OAAO,QAAQ,KAAK;EAC1B,IAAI,SAAS,MAAM,OAAO;EAE1B,MAAM,SAAS,MAAM,MAAM,IAAI;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"}
|
package/dist/storage.d.ts
CHANGED
|
@@ -13,4 +13,42 @@ export interface SavedStorage {
|
|
|
13
13
|
*/
|
|
14
14
|
backupBroken(text: string): void;
|
|
15
15
|
}
|
|
16
|
-
|
|
16
|
+
/**
|
|
17
|
+
* Why a write failed: the quota is full (the user can free space), storage is denied (private mode, site settings),
|
|
18
|
+
* or something else.
|
|
19
|
+
* Почему запись не удалась: квота заполнена (пользователь может освободить место), хранилище запрещено (приватный
|
|
20
|
+
* режим, настройки сайта) или что-то другое.
|
|
21
|
+
*/
|
|
22
|
+
export type StorageFailure = 'quota' | 'denied' | 'unknown';
|
|
23
|
+
export type StorageWriteResult = {
|
|
24
|
+
ok: true;
|
|
25
|
+
} | {
|
|
26
|
+
ok: false;
|
|
27
|
+
reason: StorageFailure;
|
|
28
|
+
};
|
|
29
|
+
/**
|
|
30
|
+
* What `createSavedStorage` returns: a `SavedStorage` (so it fits `createDocumentSession` as before) and more.
|
|
31
|
+
* Что возвращает `createSavedStorage`: `SavedStorage` (поэтому подходит `createDocumentSession`, как раньше) и больше.
|
|
32
|
+
*/
|
|
33
|
+
export interface KeyStorage extends SavedStorage {
|
|
34
|
+
/** Like `write`, with the reason of a failure. / Как `write`, с причиной отказа. */
|
|
35
|
+
tryWrite(text: string): StorageWriteResult;
|
|
36
|
+
/** Removes the key; true if storage answered. / Удаляет ключ; true, если хранилище ответило. */
|
|
37
|
+
remove(): boolean;
|
|
38
|
+
/**
|
|
39
|
+
* Calls `listener` when another tab of the same site changes this key: the new text, or null when it was removed
|
|
40
|
+
* or the whole storage was cleared. The tab that writes is not told (the browser fires the event in the others).
|
|
41
|
+
* Returns the function that stops listening.
|
|
42
|
+
* Вызывает `listener`, когда другая вкладка того же сайта меняет этот ключ: новый текст или null, если ключ удалён
|
|
43
|
+
* или хранилище очищено целиком. Пишущей вкладке не сообщается (браузер шлёт событие в остальные).
|
|
44
|
+
* Возвращает функцию, которая прекращает слушать.
|
|
45
|
+
*/
|
|
46
|
+
subscribe(listener: (text: string | null) => void): () => void;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* The reason behind a storage exception. Browsers name a full quota differently (`QuotaExceededError`, the old
|
|
50
|
+
* Firefox `NS_ERROR_DOM_QUOTA_REACHED`, codes 22 and 1014); a ban is a `SecurityError`.
|
|
51
|
+
* Причина исключения хранилища. Браузеры называют полную квоту по-разному; запрет — это `SecurityError`.
|
|
52
|
+
*/
|
|
53
|
+
export declare function storageFailure(error: unknown): StorageFailure;
|
|
54
|
+
export declare function createSavedStorage(key: string): KeyStorage;
|
package/dist/storage.js
CHANGED
|
@@ -1,6 +1,29 @@
|
|
|
1
1
|
//#region src/storage.ts
|
|
2
|
+
/**
|
|
3
|
+
* The reason behind a storage exception. Browsers name a full quota differently (`QuotaExceededError`, the old
|
|
4
|
+
* Firefox `NS_ERROR_DOM_QUOTA_REACHED`, codes 22 and 1014); a ban is a `SecurityError`.
|
|
5
|
+
* Причина исключения хранилища. Браузеры называют полную квоту по-разному; запрет — это `SecurityError`.
|
|
6
|
+
*/
|
|
7
|
+
function storageFailure(error) {
|
|
8
|
+
const e = error;
|
|
9
|
+
if (!e) return "unknown";
|
|
10
|
+
if (e.name === "QuotaExceededError" || e.name === "NS_ERROR_DOM_QUOTA_REACHED" || e.code === 22 || e.code === 1014) return "quota";
|
|
11
|
+
if (e.name === "SecurityError" || e.code === 18) return "denied";
|
|
12
|
+
return "unknown";
|
|
13
|
+
}
|
|
2
14
|
function createSavedStorage(key) {
|
|
3
15
|
const brokenKey = `${key}.broken`;
|
|
16
|
+
function tryWrite(text) {
|
|
17
|
+
try {
|
|
18
|
+
localStorage.setItem(key, text);
|
|
19
|
+
return { ok: true };
|
|
20
|
+
} catch (error) {
|
|
21
|
+
return {
|
|
22
|
+
ok: false,
|
|
23
|
+
reason: storageFailure(error)
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
}
|
|
4
27
|
return {
|
|
5
28
|
read() {
|
|
6
29
|
try {
|
|
@@ -9,9 +32,11 @@ function createSavedStorage(key) {
|
|
|
9
32
|
return null;
|
|
10
33
|
}
|
|
11
34
|
},
|
|
12
|
-
write(text)
|
|
35
|
+
write: (text) => tryWrite(text).ok,
|
|
36
|
+
tryWrite,
|
|
37
|
+
remove() {
|
|
13
38
|
try {
|
|
14
|
-
localStorage.
|
|
39
|
+
localStorage.removeItem(key);
|
|
15
40
|
return true;
|
|
16
41
|
} catch {
|
|
17
42
|
return false;
|
|
@@ -21,10 +46,26 @@ function createSavedStorage(key) {
|
|
|
21
46
|
try {
|
|
22
47
|
localStorage.setItem(brokenKey, text);
|
|
23
48
|
} catch {}
|
|
49
|
+
},
|
|
50
|
+
subscribe(listener) {
|
|
51
|
+
if (typeof window === "undefined") return () => {};
|
|
52
|
+
let area = null;
|
|
53
|
+
try {
|
|
54
|
+
area = localStorage;
|
|
55
|
+
} catch {
|
|
56
|
+
return () => {};
|
|
57
|
+
}
|
|
58
|
+
const onStorage = (event) => {
|
|
59
|
+
if (event.storageArea && event.storageArea !== area) return;
|
|
60
|
+
if (event.key === key) listener(event.newValue);
|
|
61
|
+
else if (event.key === null) listener(null);
|
|
62
|
+
};
|
|
63
|
+
window.addEventListener("storage", onStorage);
|
|
64
|
+
return () => window.removeEventListener("storage", onStorage);
|
|
24
65
|
}
|
|
25
66
|
};
|
|
26
67
|
}
|
|
27
68
|
//#endregion
|
|
28
|
-
export { createSavedStorage };
|
|
69
|
+
export { createSavedStorage, storageFailure };
|
|
29
70
|
|
|
30
71
|
//# sourceMappingURL=storage.js.map
|
package/dist/storage.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"storage.js","names":[],"sources":["../src/storage.ts"],"sourcesContent":["/**\n * Autosave to localStorage. Any operation may fail: private mode, a site-level ban, a full quota.\n * So errors are swallowed and reported as a result, not thrown.\n * Автосохранение в localStorage. Любая операция может не сработать: приватный режим,\n * запрет сайта, переполнение квоты. Поэтому ошибки глушим и сообщаем результатом, а не исключением.\n */\nexport interface SavedStorage {\n read(): string | null;\n write(text: string): boolean;\n /**\n * What was saved could not be read: the copy is set aside so autosave does not overwrite it.\n * Сохранённое не удалось прочитать: откладываем копию, чтобы автосохранение её не затёрло.\n */\n backupBroken(text: string): void;\n}\n\nexport function createSavedStorage(key: string):
|
|
1
|
+
{"version":3,"file":"storage.js","names":[],"sources":["../src/storage.ts"],"sourcesContent":["/**\n * Autosave to localStorage. Any operation may fail: private mode, a site-level ban, a full quota.\n * So errors are swallowed and reported as a result, not thrown.\n * Автосохранение в localStorage. Любая операция может не сработать: приватный режим,\n * запрет сайта, переполнение квоты. Поэтому ошибки глушим и сообщаем результатом, а не исключением.\n */\nexport interface SavedStorage {\n read(): string | null;\n write(text: string): boolean;\n /**\n * What was saved could not be read: the copy is set aside so autosave does not overwrite it.\n * Сохранённое не удалось прочитать: откладываем копию, чтобы автосохранение её не затёрло.\n */\n backupBroken(text: string): void;\n}\n\n/**\n * Why a write failed: the quota is full (the user can free space), storage is denied (private mode, site settings),\n * or something else.\n * Почему запись не удалась: квота заполнена (пользователь может освободить место), хранилище запрещено (приватный\n * режим, настройки сайта) или что-то другое.\n */\nexport type StorageFailure = 'quota' | 'denied' | 'unknown';\n\nexport type StorageWriteResult = { ok: true } | { ok: false; reason: StorageFailure };\n\n/**\n * What `createSavedStorage` returns: a `SavedStorage` (so it fits `createDocumentSession` as before) and more.\n * Что возвращает `createSavedStorage`: `SavedStorage` (поэтому подходит `createDocumentSession`, как раньше) и больше.\n */\nexport interface KeyStorage extends SavedStorage {\n /** Like `write`, with the reason of a failure. / Как `write`, с причиной отказа. */\n tryWrite(text: string): StorageWriteResult;\n /** Removes the key; true if storage answered. / Удаляет ключ; true, если хранилище ответило. */\n remove(): boolean;\n /**\n * Calls `listener` when another tab of the same site changes this key: the new text, or null when it was removed\n * or the whole storage was cleared. The tab that writes is not told (the browser fires the event in the others).\n * Returns the function that stops listening.\n * Вызывает `listener`, когда другая вкладка того же сайта меняет этот ключ: новый текст или null, если ключ удалён\n * или хранилище очищено целиком. Пишущей вкладке не сообщается (браузер шлёт событие в остальные).\n * Возвращает функцию, которая прекращает слушать.\n */\n subscribe(listener: (text: string | null) => void): () => void;\n}\n\n/**\n * The reason behind a storage exception. Browsers name a full quota differently (`QuotaExceededError`, the old\n * Firefox `NS_ERROR_DOM_QUOTA_REACHED`, codes 22 and 1014); a ban is a `SecurityError`.\n * Причина исключения хранилища. Браузеры называют полную квоту по-разному; запрет — это `SecurityError`.\n */\nexport function storageFailure(error: unknown): StorageFailure {\n const e = error as { name?: string; code?: number } | null;\n if (!e) return 'unknown';\n if (e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED' || e.code === 22 || e.code === 1014) return 'quota';\n if (e.name === 'SecurityError' || e.code === 18) return 'denied';\n return 'unknown';\n}\n\nexport function createSavedStorage(key: string): KeyStorage {\n const brokenKey = `${key}.broken`;\n\n function tryWrite(text: string): StorageWriteResult {\n try {\n localStorage.setItem(key, text);\n return { ok: true };\n } catch (error) {\n return { ok: false, reason: storageFailure(error) };\n }\n }\n\n return {\n read() {\n try {\n return localStorage.getItem(key);\n } catch {\n return null;\n }\n },\n write: (text) => tryWrite(text).ok,\n tryWrite,\n remove() {\n try {\n localStorage.removeItem(key);\n return true;\n } catch {\n return false;\n }\n },\n backupBroken(text) {\n try {\n localStorage.setItem(brokenKey, text);\n } catch {\n // nothing to do: there is no room\n // нечего делать: места нет\n }\n },\n subscribe(listener) {\n if (typeof window === 'undefined') return () => {};\n let area: Storage | null = null;\n try {\n area = localStorage;\n } catch {\n return () => {}; // storage is denied: no other tab can write it either / хранилище запрещено\n }\n const onStorage = (event: StorageEvent) => {\n // the same key in sessionStorage is someone else's / тот же ключ в sessionStorage — чужой\n if (event.storageArea && event.storageArea !== area) return;\n // key null: the other tab called clear() / key null: другая вкладка вызвала clear()\n if (event.key === key) listener(event.newValue);\n else if (event.key === null) listener(null);\n };\n window.addEventListener('storage', onStorage);\n return () => window.removeEventListener('storage', onStorage);\n },\n };\n}\n"],"mappings":";;;;;;AAmDA,SAAgB,eAAe,OAAgC;CAC3D,MAAM,IAAI;CACV,IAAI,CAAC,GAAG,OAAO;CACf,IAAI,EAAE,SAAS,wBAAwB,EAAE,SAAS,gCAAgC,EAAE,SAAS,MAAM,EAAE,SAAS,MAAM,OAAO;CAC3H,IAAI,EAAE,SAAS,mBAAmB,EAAE,SAAS,IAAI,OAAO;CACxD,OAAO;AACX;AAEA,SAAgB,mBAAmB,KAAyB;CACxD,MAAM,YAAY,GAAG,IAAI;CAEzB,SAAS,SAAS,MAAkC;EAChD,IAAI;GACA,aAAa,QAAQ,KAAK,IAAI;GAC9B,OAAO,EAAE,IAAI,KAAK;EACtB,SAAS,OAAO;GACZ,OAAO;IAAE,IAAI;IAAO,QAAQ,eAAe,KAAK;GAAE;EACtD;CACJ;CAEA,OAAO;EACH,OAAO;GACH,IAAI;IACA,OAAO,aAAa,QAAQ,GAAG;GACnC,QAAQ;IACJ,OAAO;GACX;EACJ;EACA,QAAQ,SAAS,SAAS,IAAI,CAAC,CAAC;EAChC;EACA,SAAS;GACL,IAAI;IACA,aAAa,WAAW,GAAG;IAC3B,OAAO;GACX,QAAQ;IACJ,OAAO;GACX;EACJ;EACA,aAAa,MAAM;GACf,IAAI;IACA,aAAa,QAAQ,WAAW,IAAI;GACxC,QAAQ,CAGR;EACJ;EACA,UAAU,UAAU;GAChB,IAAI,OAAO,WAAW,aAAa,aAAa,CAAC;GACjD,IAAI,OAAuB;GAC3B,IAAI;IACA,OAAO;GACX,QAAQ;IACJ,aAAa,CAAC;GAClB;GACA,MAAM,aAAa,UAAwB;IAEvC,IAAI,MAAM,eAAe,MAAM,gBAAgB,MAAM;IAErD,IAAI,MAAM,QAAQ,KAAK,SAAS,MAAM,QAAQ;SACzC,IAAI,MAAM,QAAQ,MAAM,SAAS,IAAI;GAC9C;GACA,OAAO,iBAAiB,WAAW,SAAS;GAC5C,aAAa,OAAO,oBAAoB,WAAW,SAAS;EAChE;CACJ;AACJ"}
|
package/dist/undo.d.ts
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Undo and redo by records, not by snapshots of the whole document. A step keeps only the records it touched, before
|
|
3
|
+
* and after. For a list that is edited and synced (notes, tasks, contacts) that is what `History` cannot give:
|
|
4
|
+
* a snapshot of the whole list costs the whole list per step, and an undo made after a sync would roll back what
|
|
5
|
+
* another device has just changed. Here an undo touches only the records of its step.
|
|
6
|
+
* Undo и redo по записям, а не по снимкам всего документа. Шаг хранит только затронутые им записи, до и после. Для
|
|
7
|
+
* списка, который правят и синхронизируют (заметки, задачи, контакты), это то, чего не даёт `History`: снимок всего
|
|
8
|
+
* списка стоит всего списка на шаг, а отмена после синхронизации откатила бы то, что только что изменило другое
|
|
9
|
+
* устройство. Здесь отмена трогает только записи своего шага.
|
|
10
|
+
*
|
|
11
|
+
* Pure TypeScript, no Vue and no DOM. Records are immutable: an edit makes a new object, and `diffRecords` finds the
|
|
12
|
+
* changed ones by identity.
|
|
13
|
+
* Чистый TypeScript, без Vue и DOM. Записи неизменяемы: правка создаёт новый объект, а `diffRecords` находит
|
|
14
|
+
* изменённые по тождеству.
|
|
15
|
+
*/
|
|
16
|
+
/**
|
|
17
|
+
* Edits with the same key made faster than this many ms apart merge into one step (autosave while typing).
|
|
18
|
+
* Правки с одним ключом, сделанные чаще чем раз в столько мс, склеиваются в один шаг (автосохранение при наборе).
|
|
19
|
+
*/
|
|
20
|
+
export declare const COALESCE_MS = 3000;
|
|
21
|
+
/**
|
|
22
|
+
* What one step changed: the touched records before and after (`null`: the record did not exist / is gone).
|
|
23
|
+
* Что изменил один шаг: затронутые записи до и после (`null`: записи не было / её больше нет).
|
|
24
|
+
*/
|
|
25
|
+
export interface UndoEntry<T> {
|
|
26
|
+
before: Map<string, T | null>;
|
|
27
|
+
after: Map<string, T | null>;
|
|
28
|
+
/**
|
|
29
|
+
* Where a record stood in the list before / after the step (its index), so a record that comes back takes its old
|
|
30
|
+
* place instead of the end. `diffRecords` fills them; a hand-made entry may leave them out.
|
|
31
|
+
* Где запись стояла в списке до / после шага (её индекс), чтобы вернувшаяся запись встала на своё место, а не в
|
|
32
|
+
* конец. `diffRecords` их заполняет; шаг, собранный вручную, может их не задавать.
|
|
33
|
+
*/
|
|
34
|
+
beforeAt?: Map<string, number>;
|
|
35
|
+
afterAt?: Map<string, number>;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* The step between two lists, or null when nothing changed. Records are compared by identity, so an unchanged
|
|
39
|
+
* record must stay the same object.
|
|
40
|
+
* Шаг между двумя списками или null, если ничего не изменилось. Записи сравниваются по тождеству, поэтому
|
|
41
|
+
* нетронутая запись должна остаться тем же объектом.
|
|
42
|
+
*/
|
|
43
|
+
export declare function diffRecords<T>(prev: readonly T[], next: readonly T[], id: (record: T) => string): UndoEntry<T> | null;
|
|
44
|
+
export interface UndoOptions<T> {
|
|
45
|
+
/** The id of a record. / Id записи. */
|
|
46
|
+
id(record: T): string;
|
|
47
|
+
/**
|
|
48
|
+
* A record comes back from a step (an image). Stamp it as new, so that a sync does not take the undo for stale:
|
|
49
|
+
* `{ ...image, updatedAt: now }`.
|
|
50
|
+
* Запись возвращается из шага (образ). Пометьте её свежей, чтобы синхронизация не сочла отмену устаревшей.
|
|
51
|
+
*/
|
|
52
|
+
revive(image: T, now: number): T;
|
|
53
|
+
/**
|
|
54
|
+
* A record that the step created (or removed) has to go away. Do not delete it from the list when the list is
|
|
55
|
+
* synced: mark it gone, as a tombstone: `{ ...record, deletedAt: now, updatedAt: now }`. Without it the record
|
|
56
|
+
* is dropped from the list.
|
|
57
|
+
* Запись, которую шаг создал (или удалил), должна исчезнуть. В синхронизируемом списке не стирайте её, а пометьте
|
|
58
|
+
* исчезнувшей, надгробием. Без этого запись просто убирается из списка.
|
|
59
|
+
*/
|
|
60
|
+
vanish?(record: T, now: number): T;
|
|
61
|
+
/** How many steps to keep. / Сколько шагов хранить. */
|
|
62
|
+
limit?: number;
|
|
63
|
+
/** The merge window of `record(entry, key)`, ms. / Окно склейки для `record(entry, key)`, мс. */
|
|
64
|
+
coalesceMs?: number;
|
|
65
|
+
/**
|
|
66
|
+
* The longest a merged step may grow, ms from its first edit. The window above slides with every edit, so typing
|
|
67
|
+
* without a pause would otherwise stay one step however long it goes on (one undo would take a minute of text
|
|
68
|
+
* away). No limit by default.
|
|
69
|
+
* Сколько может расти склеенный шаг, мс от его первой правки. Окно выше сдвигается с каждой правкой, поэтому набор
|
|
70
|
+
* без пауз иначе остаётся одним шагом сколь угодно долго (одна отмена унесла бы минуту текста). По умолчанию без
|
|
71
|
+
* предела.
|
|
72
|
+
*/
|
|
73
|
+
coalesceMaxMs?: number;
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* The stack of steps and the pointer in it. It does not hold the list: `undo` and `redo` take the current list and
|
|
77
|
+
* return the next one (or null when there is nothing to do), the app puts it where it keeps its records.
|
|
78
|
+
* Стек шагов и указатель в нём. Список он не хранит: `undo` и `redo` принимают текущий список и возвращают следующий
|
|
79
|
+
* (или null, если делать нечего), а приложение кладёт его туда, где хранит записи.
|
|
80
|
+
*/
|
|
81
|
+
export declare class UndoStack<T> {
|
|
82
|
+
private readonly options;
|
|
83
|
+
private entries;
|
|
84
|
+
private index;
|
|
85
|
+
private lastKey;
|
|
86
|
+
private lastTime;
|
|
87
|
+
private firstTime;
|
|
88
|
+
private readonly limit;
|
|
89
|
+
private readonly coalesceMs;
|
|
90
|
+
private readonly coalesceMaxMs;
|
|
91
|
+
constructor(options: UndoOptions<T>);
|
|
92
|
+
get canUndo(): boolean;
|
|
93
|
+
get canRedo(): boolean;
|
|
94
|
+
/**
|
|
95
|
+
* Records a step; it drops the "future" (redo). With the same `key` in a row and within `coalesceMs` the step
|
|
96
|
+
* merges into the previous one: the first `before` stays, the last `after` wins.
|
|
97
|
+
* Записывает шаг и отбрасывает «будущее» (redo). С одинаковым `key` подряд и в пределах `coalesceMs` шаг
|
|
98
|
+
* склеивается с предыдущим: остаётся первый `before`, побеждает последний `after`.
|
|
99
|
+
*/
|
|
100
|
+
record(entry: UndoEntry<T>, key?: string, now?: number): void;
|
|
101
|
+
undo(current: readonly T[], now?: number): T[] | null;
|
|
102
|
+
redo(current: readonly T[], now?: number): T[] | null;
|
|
103
|
+
clear(): void;
|
|
104
|
+
/**
|
|
105
|
+
* Puts the images over the current list; the other records are not touched. A record that is in the list keeps its
|
|
106
|
+
* place; one that comes back goes to the place it had (the list may have changed since, so it is the nearest one),
|
|
107
|
+
* and without a known place to the end.
|
|
108
|
+
* Кладёт образы поверх текущего списка; остальные записи не трогает. Запись, которая есть в списке, остаётся на
|
|
109
|
+
* месте; вернувшаяся встаёт туда, где стояла (список с тех пор мог измениться, поэтому — на ближайшее место), а без
|
|
110
|
+
* известного места — в конец.
|
|
111
|
+
*/
|
|
112
|
+
private apply;
|
|
113
|
+
}
|
package/dist/undo.js
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
//#region src/undo.ts
|
|
2
|
+
/**
|
|
3
|
+
* Undo and redo by records, not by snapshots of the whole document. A step keeps only the records it touched, before
|
|
4
|
+
* and after. For a list that is edited and synced (notes, tasks, contacts) that is what `History` cannot give:
|
|
5
|
+
* a snapshot of the whole list costs the whole list per step, and an undo made after a sync would roll back what
|
|
6
|
+
* another device has just changed. Here an undo touches only the records of its step.
|
|
7
|
+
* Undo и redo по записям, а не по снимкам всего документа. Шаг хранит только затронутые им записи, до и после. Для
|
|
8
|
+
* списка, который правят и синхронизируют (заметки, задачи, контакты), это то, чего не даёт `History`: снимок всего
|
|
9
|
+
* списка стоит всего списка на шаг, а отмена после синхронизации откатила бы то, что только что изменило другое
|
|
10
|
+
* устройство. Здесь отмена трогает только записи своего шага.
|
|
11
|
+
*
|
|
12
|
+
* Pure TypeScript, no Vue and no DOM. Records are immutable: an edit makes a new object, and `diffRecords` finds the
|
|
13
|
+
* changed ones by identity.
|
|
14
|
+
* Чистый TypeScript, без Vue и DOM. Записи неизменяемы: правка создаёт новый объект, а `diffRecords` находит
|
|
15
|
+
* изменённые по тождеству.
|
|
16
|
+
*/
|
|
17
|
+
/**
|
|
18
|
+
* Edits with the same key made faster than this many ms apart merge into one step (autosave while typing).
|
|
19
|
+
* Правки с одним ключом, сделанные чаще чем раз в столько мс, склеиваются в один шаг (автосохранение при наборе).
|
|
20
|
+
*/
|
|
21
|
+
var COALESCE_MS = 3e3;
|
|
22
|
+
/**
|
|
23
|
+
* The step between two lists, or null when nothing changed. Records are compared by identity, so an unchanged
|
|
24
|
+
* record must stay the same object.
|
|
25
|
+
* Шаг между двумя списками или null, если ничего не изменилось. Записи сравниваются по тождеству, поэтому
|
|
26
|
+
* нетронутая запись должна остаться тем же объектом.
|
|
27
|
+
*/
|
|
28
|
+
function diffRecords(prev, next, id) {
|
|
29
|
+
const was = new Map(prev.map((r) => [id(r), r]));
|
|
30
|
+
const is = new Map(next.map((r) => [id(r), r]));
|
|
31
|
+
const wasAt = new Map(prev.map((r, i) => [id(r), i]));
|
|
32
|
+
const isAt = new Map(next.map((r, i) => [id(r), i]));
|
|
33
|
+
const entry = {
|
|
34
|
+
before: /* @__PURE__ */ new Map(),
|
|
35
|
+
after: /* @__PURE__ */ new Map(),
|
|
36
|
+
beforeAt: /* @__PURE__ */ new Map(),
|
|
37
|
+
afterAt: /* @__PURE__ */ new Map()
|
|
38
|
+
};
|
|
39
|
+
const place = (key) => {
|
|
40
|
+
const before = wasAt.get(key);
|
|
41
|
+
const after = isAt.get(key);
|
|
42
|
+
if (before !== void 0) entry.beforeAt.set(key, before);
|
|
43
|
+
if (after !== void 0) entry.afterAt.set(key, after);
|
|
44
|
+
};
|
|
45
|
+
for (const [key, record] of is) if (was.get(key) !== record) {
|
|
46
|
+
entry.before.set(key, was.get(key) ?? null);
|
|
47
|
+
entry.after.set(key, record);
|
|
48
|
+
place(key);
|
|
49
|
+
}
|
|
50
|
+
for (const [key, record] of was) if (!is.has(key)) {
|
|
51
|
+
entry.before.set(key, record);
|
|
52
|
+
entry.after.set(key, null);
|
|
53
|
+
place(key);
|
|
54
|
+
}
|
|
55
|
+
return entry.after.size === 0 ? null : entry;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* The stack of steps and the pointer in it. It does not hold the list: `undo` and `redo` take the current list and
|
|
59
|
+
* return the next one (or null when there is nothing to do), the app puts it where it keeps its records.
|
|
60
|
+
* Стек шагов и указатель в нём. Список он не хранит: `undo` и `redo` принимают текущий список и возвращают следующий
|
|
61
|
+
* (или null, если делать нечего), а приложение кладёт его туда, где хранит записи.
|
|
62
|
+
*/
|
|
63
|
+
var UndoStack = class {
|
|
64
|
+
options;
|
|
65
|
+
entries = [];
|
|
66
|
+
index = 0;
|
|
67
|
+
lastKey;
|
|
68
|
+
lastTime = 0;
|
|
69
|
+
firstTime = 0;
|
|
70
|
+
limit;
|
|
71
|
+
coalesceMs;
|
|
72
|
+
coalesceMaxMs;
|
|
73
|
+
constructor(options) {
|
|
74
|
+
this.options = options;
|
|
75
|
+
this.limit = options.limit ?? 50;
|
|
76
|
+
this.coalesceMs = options.coalesceMs ?? 3e3;
|
|
77
|
+
this.coalesceMaxMs = options.coalesceMaxMs ?? Infinity;
|
|
78
|
+
}
|
|
79
|
+
get canUndo() {
|
|
80
|
+
return this.index > 0;
|
|
81
|
+
}
|
|
82
|
+
get canRedo() {
|
|
83
|
+
return this.index < this.entries.length;
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Records a step; it drops the "future" (redo). With the same `key` in a row and within `coalesceMs` the step
|
|
87
|
+
* merges into the previous one: the first `before` stays, the last `after` wins.
|
|
88
|
+
* Записывает шаг и отбрасывает «будущее» (redo). С одинаковым `key` подряд и в пределах `coalesceMs` шаг
|
|
89
|
+
* склеивается с предыдущим: остаётся первый `before`, побеждает последний `after`.
|
|
90
|
+
*/
|
|
91
|
+
record(entry, key, now = Date.now()) {
|
|
92
|
+
const atTop = this.index > 0 && this.index === this.entries.length;
|
|
93
|
+
if (key !== void 0 && key === this.lastKey && atTop && now - this.lastTime <= this.coalesceMs && now - this.firstTime <= this.coalesceMaxMs) {
|
|
94
|
+
const previous = this.entries[this.index - 1];
|
|
95
|
+
for (const [id, record] of entry.before) {
|
|
96
|
+
if (previous.before.has(id)) continue;
|
|
97
|
+
previous.before.set(id, record);
|
|
98
|
+
const at = entry.beforeAt?.get(id);
|
|
99
|
+
if (at !== void 0) (previous.beforeAt ??= /* @__PURE__ */ new Map()).set(id, at);
|
|
100
|
+
}
|
|
101
|
+
for (const [id, record] of entry.after) {
|
|
102
|
+
previous.after.set(id, record);
|
|
103
|
+
const at = entry.afterAt?.get(id);
|
|
104
|
+
if (at !== void 0) (previous.afterAt ??= /* @__PURE__ */ new Map()).set(id, at);
|
|
105
|
+
else previous.afterAt?.delete(id);
|
|
106
|
+
}
|
|
107
|
+
} else {
|
|
108
|
+
this.entries.length = this.index;
|
|
109
|
+
this.entries.push(entry);
|
|
110
|
+
if (this.entries.length > this.limit) this.entries.shift();
|
|
111
|
+
this.index = this.entries.length;
|
|
112
|
+
this.firstTime = now;
|
|
113
|
+
}
|
|
114
|
+
this.lastKey = key;
|
|
115
|
+
this.lastTime = now;
|
|
116
|
+
}
|
|
117
|
+
undo(current, now = Date.now()) {
|
|
118
|
+
if (!this.canUndo) return null;
|
|
119
|
+
this.lastKey = void 0;
|
|
120
|
+
const entry = this.entries[--this.index];
|
|
121
|
+
return this.apply(current, entry.before, entry.beforeAt, now);
|
|
122
|
+
}
|
|
123
|
+
redo(current, now = Date.now()) {
|
|
124
|
+
if (!this.canRedo) return null;
|
|
125
|
+
this.lastKey = void 0;
|
|
126
|
+
const entry = this.entries[this.index++];
|
|
127
|
+
return this.apply(current, entry.after, entry.afterAt, now);
|
|
128
|
+
}
|
|
129
|
+
clear() {
|
|
130
|
+
this.entries = [];
|
|
131
|
+
this.index = 0;
|
|
132
|
+
this.lastKey = void 0;
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Puts the images over the current list; the other records are not touched. A record that is in the list keeps its
|
|
136
|
+
* place; one that comes back goes to the place it had (the list may have changed since, so it is the nearest one),
|
|
137
|
+
* and without a known place to the end.
|
|
138
|
+
* Кладёт образы поверх текущего списка; остальные записи не трогает. Запись, которая есть в списке, остаётся на
|
|
139
|
+
* месте; вернувшаяся встаёт туда, где стояла (список с тех пор мог измениться, поэтому — на ближайшее место), а без
|
|
140
|
+
* известного места — в конец.
|
|
141
|
+
*/
|
|
142
|
+
apply(current, images, places, now) {
|
|
143
|
+
const { id, revive, vanish } = this.options;
|
|
144
|
+
const result = new Map(current.map((r) => [id(r), r]));
|
|
145
|
+
const back = [];
|
|
146
|
+
for (const [key, image] of images) {
|
|
147
|
+
if (image) {
|
|
148
|
+
if (result.has(key)) result.set(key, revive(image, now));
|
|
149
|
+
else back.push([places?.get(key) ?? Infinity, revive(image, now)]);
|
|
150
|
+
continue;
|
|
151
|
+
}
|
|
152
|
+
const existing = result.get(key);
|
|
153
|
+
if (!existing) continue;
|
|
154
|
+
if (vanish) result.set(key, vanish(existing, now));
|
|
155
|
+
else result.delete(key);
|
|
156
|
+
}
|
|
157
|
+
const list = [...result.values()];
|
|
158
|
+
back.sort((a, b) => a[0] - b[0]);
|
|
159
|
+
for (const [at, record] of back) list.splice(Math.min(at, list.length), 0, record);
|
|
160
|
+
return list;
|
|
161
|
+
}
|
|
162
|
+
};
|
|
163
|
+
//#endregion
|
|
164
|
+
export { COALESCE_MS, UndoStack, diffRecords };
|
|
165
|
+
|
|
166
|
+
//# sourceMappingURL=undo.js.map
|
package/dist/undo.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"undo.js","names":[],"sources":["../src/undo.ts"],"sourcesContent":["/**\n * Undo and redo by records, not by snapshots of the whole document. A step keeps only the records it touched, before\n * and after. For a list that is edited and synced (notes, tasks, contacts) that is what `History` cannot give:\n * a snapshot of the whole list costs the whole list per step, and an undo made after a sync would roll back what\n * another device has just changed. Here an undo touches only the records of its step.\n * Undo и redo по записям, а не по снимкам всего документа. Шаг хранит только затронутые им записи, до и после. Для\n * списка, который правят и синхронизируют (заметки, задачи, контакты), это то, чего не даёт `History`: снимок всего\n * списка стоит всего списка на шаг, а отмена после синхронизации откатила бы то, что только что изменило другое\n * устройство. Здесь отмена трогает только записи своего шага.\n *\n * Pure TypeScript, no Vue and no DOM. Records are immutable: an edit makes a new object, and `diffRecords` finds the\n * changed ones by identity.\n * Чистый TypeScript, без Vue и DOM. Записи неизменяемы: правка создаёт новый объект, а `diffRecords` находит\n * изменённые по тождеству.\n */\n\n/**\n * Edits with the same key made faster than this many ms apart merge into one step (autosave while typing).\n * Правки с одним ключом, сделанные чаще чем раз в столько мс, склеиваются в один шаг (автосохранение при наборе).\n */\nexport const COALESCE_MS = 3000;\n\n/**\n * What one step changed: the touched records before and after (`null`: the record did not exist / is gone).\n * Что изменил один шаг: затронутые записи до и после (`null`: записи не было / её больше нет).\n */\nexport interface UndoEntry<T> {\n before: Map<string, T | null>;\n after: Map<string, T | null>;\n /**\n * Where a record stood in the list before / after the step (its index), so a record that comes back takes its old\n * place instead of the end. `diffRecords` fills them; a hand-made entry may leave them out.\n * Где запись стояла в списке до / после шага (её индекс), чтобы вернувшаяся запись встала на своё место, а не в\n * конец. `diffRecords` их заполняет; шаг, собранный вручную, может их не задавать.\n */\n beforeAt?: Map<string, number>;\n afterAt?: Map<string, number>;\n}\n\n/**\n * The step between two lists, or null when nothing changed. Records are compared by identity, so an unchanged\n * record must stay the same object.\n * Шаг между двумя списками или null, если ничего не изменилось. Записи сравниваются по тождеству, поэтому\n * нетронутая запись должна остаться тем же объектом.\n */\nexport function diffRecords<T>(prev: readonly T[], next: readonly T[], id: (record: T) => string): UndoEntry<T> | null {\n const was = new Map(prev.map((r) => [id(r), r]));\n const is = new Map(next.map((r) => [id(r), r]));\n const wasAt = new Map(prev.map((r, i) => [id(r), i]));\n const isAt = new Map(next.map((r, i) => [id(r), i]));\n const entry: UndoEntry<T> = { before: new Map(), after: new Map(), beforeAt: new Map(), afterAt: new Map() };\n const place = (key: string) => {\n const before = wasAt.get(key);\n const after = isAt.get(key);\n if (before !== undefined) entry.beforeAt!.set(key, before);\n if (after !== undefined) entry.afterAt!.set(key, after);\n };\n\n for (const [key, record] of is) {\n if (was.get(key) !== record) {\n entry.before.set(key, was.get(key) ?? null);\n entry.after.set(key, record);\n place(key);\n }\n }\n for (const [key, record] of was) {\n if (!is.has(key)) {\n entry.before.set(key, record);\n entry.after.set(key, null);\n place(key);\n }\n }\n return entry.after.size === 0 ? null : entry;\n}\n\nexport interface UndoOptions<T> {\n /** The id of a record. / Id записи. */\n id(record: T): string;\n /**\n * A record comes back from a step (an image). Stamp it as new, so that a sync does not take the undo for stale:\n * `{ ...image, updatedAt: now }`.\n * Запись возвращается из шага (образ). Пометьте её свежей, чтобы синхронизация не сочла отмену устаревшей.\n */\n revive(image: T, now: number): T;\n /**\n * A record that the step created (or removed) has to go away. Do not delete it from the list when the list is\n * synced: mark it gone, as a tombstone: `{ ...record, deletedAt: now, updatedAt: now }`. Without it the record\n * is dropped from the list.\n * Запись, которую шаг создал (или удалил), должна исчезнуть. В синхронизируемом списке не стирайте её, а пометьте\n * исчезнувшей, надгробием. Без этого запись просто убирается из списка.\n */\n vanish?(record: T, now: number): T;\n /** How many steps to keep. / Сколько шагов хранить. */\n limit?: number;\n /** The merge window of `record(entry, key)`, ms. / Окно склейки для `record(entry, key)`, мс. */\n coalesceMs?: number;\n /**\n * The longest a merged step may grow, ms from its first edit. The window above slides with every edit, so typing\n * without a pause would otherwise stay one step however long it goes on (one undo would take a minute of text\n * away). No limit by default.\n * Сколько может расти склеенный шаг, мс от его первой правки. Окно выше сдвигается с каждой правкой, поэтому набор\n * без пауз иначе остаётся одним шагом сколь угодно долго (одна отмена унесла бы минуту текста). По умолчанию без\n * предела.\n */\n coalesceMaxMs?: number;\n}\n\n/**\n * The stack of steps and the pointer in it. It does not hold the list: `undo` and `redo` take the current list and\n * return the next one (or null when there is nothing to do), the app puts it where it keeps its records.\n * Стек шагов и указатель в нём. Список он не хранит: `undo` и `redo` принимают текущий список и возвращают следующий\n * (или null, если делать нечего), а приложение кладёт его туда, где хранит записи.\n */\nexport class UndoStack<T> {\n private entries: UndoEntry<T>[] = [];\n private index = 0;\n private lastKey: string | undefined;\n private lastTime = 0;\n // when the step on top began: the limit of a merged step counts from here / когда начался верхний шаг\n private firstTime = 0;\n private readonly limit: number;\n private readonly coalesceMs: number;\n private readonly coalesceMaxMs: number;\n\n constructor(private readonly options: UndoOptions<T>) {\n this.limit = options.limit ?? 50;\n this.coalesceMs = options.coalesceMs ?? COALESCE_MS;\n this.coalesceMaxMs = options.coalesceMaxMs ?? Infinity;\n }\n\n get canUndo(): boolean {\n return this.index > 0;\n }\n\n get canRedo(): boolean {\n return this.index < this.entries.length;\n }\n\n /**\n * Records a step; it drops the \"future\" (redo). With the same `key` in a row and within `coalesceMs` the step\n * merges into the previous one: the first `before` stays, the last `after` wins.\n * Записывает шаг и отбрасывает «будущее» (redo). С одинаковым `key` подряд и в пределах `coalesceMs` шаг\n * склеивается с предыдущим: остаётся первый `before`, побеждает последний `after`.\n */\n record(entry: UndoEntry<T>, key?: string, now: number = Date.now()): void {\n const atTop = this.index > 0 && this.index === this.entries.length;\n const merge =\n key !== undefined &&\n key === this.lastKey &&\n atTop &&\n now - this.lastTime <= this.coalesceMs &&\n now - this.firstTime <= this.coalesceMaxMs;\n if (merge) {\n const previous = this.entries[this.index - 1]!;\n for (const [id, record] of entry.before) {\n if (previous.before.has(id)) continue;\n previous.before.set(id, record);\n const at = entry.beforeAt?.get(id);\n if (at !== undefined) (previous.beforeAt ??= new Map()).set(id, at);\n }\n for (const [id, record] of entry.after) {\n previous.after.set(id, record);\n const at = entry.afterAt?.get(id);\n if (at !== undefined) (previous.afterAt ??= new Map()).set(id, at);\n else previous.afterAt?.delete(id);\n }\n } else {\n this.entries.length = this.index;\n this.entries.push(entry);\n if (this.entries.length > this.limit) this.entries.shift();\n this.index = this.entries.length;\n this.firstTime = now;\n }\n this.lastKey = key;\n this.lastTime = now;\n }\n\n undo(current: readonly T[], now: number = Date.now()): T[] | null {\n if (!this.canUndo) return null;\n this.lastKey = undefined;\n const entry = this.entries[--this.index]!;\n return this.apply(current, entry.before, entry.beforeAt, now);\n }\n\n redo(current: readonly T[], now: number = Date.now()): T[] | null {\n if (!this.canRedo) return null;\n this.lastKey = undefined;\n const entry = this.entries[this.index++]!;\n return this.apply(current, entry.after, entry.afterAt, now);\n }\n\n clear(): void {\n this.entries = [];\n this.index = 0;\n this.lastKey = undefined;\n }\n\n /**\n * Puts the images over the current list; the other records are not touched. A record that is in the list keeps its\n * place; one that comes back goes to the place it had (the list may have changed since, so it is the nearest one),\n * and without a known place to the end.\n * Кладёт образы поверх текущего списка; остальные записи не трогает. Запись, которая есть в списке, остаётся на\n * месте; вернувшаяся встаёт туда, где стояла (список с тех пор мог измениться, поэтому — на ближайшее место), а без\n * известного места — в конец.\n */\n private apply(current: readonly T[], images: Map<string, T | null>, places: Map<string, number> | undefined, now: number): T[] {\n const { id, revive, vanish } = this.options;\n const result = new Map(current.map((r) => [id(r), r]));\n const back: [number, T][] = [];\n for (const [key, image] of images) {\n if (image) {\n if (result.has(key)) result.set(key, revive(image, now));\n else back.push([places?.get(key) ?? Infinity, revive(image, now)]);\n continue;\n }\n const existing = result.get(key);\n if (!existing) continue;\n if (vanish) result.set(key, vanish(existing, now));\n else result.delete(key);\n }\n const list = [...result.values()];\n // in order of their old places, so «delete all» undone is the same list again / по возрастанию старых мест\n back.sort((a, b) => a[0] - b[0]);\n for (const [at, record] of back) list.splice(Math.min(at, list.length), 0, record);\n return list;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAoBA,IAAa,cAAc;;;;;;;AAyB3B,SAAgB,YAAe,MAAoB,MAAoB,IAAgD;CACnH,MAAM,MAAM,IAAI,IAAI,KAAK,KAAK,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC;CAC/C,MAAM,KAAK,IAAI,IAAI,KAAK,KAAK,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC;CAC9C,MAAM,QAAQ,IAAI,IAAI,KAAK,KAAK,GAAG,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC;CACpD,MAAM,OAAO,IAAI,IAAI,KAAK,KAAK,GAAG,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC;CACnD,MAAM,QAAsB;EAAE,wBAAQ,IAAI,IAAI;EAAG,uBAAO,IAAI,IAAI;EAAG,0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Q,KAAK,QAAQ,KAAK;EAChC,OAAO,KAAK,MAAM,SAAS,MAAM,OAAO,MAAM,SAAS,GAAG;CAC9D;CAEA,QAAc;EACV,KAAK,UAAU,CAAC;EAChB,KAAK,QAAQ;EACb,KAAK,UAAU,KAAA;CACnB;;;;;;;;;CAUA,MAAc,SAAuB,QAA+B,QAAyC,KAAkB;EAC3H,MAAM,EAAE,IAAI,QAAQ,WAAW,KAAK;EACpC,MAAM,SAAS,IAAI,IAAI,QAAQ,KAAK,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC;EACrD,MAAM,OAAsB,CAAC;EAC7B,KAAK,MAAM,CAAC,KAAK,UAAU,QAAQ;GAC/B,IAAI,OAAO;IACP,IAAI,OAAO,IAAI,GAAG,GAAG,OAAO,IAAI,KAAK,OAAO,OAAO,GAAG,CAAC;SAClD,KAAK,KAAK,CAAC,QAAQ,IAAI,GAAG,KAAK,UAAU,OAAO,OAAO,GAAG,CAAC,CAAC;IACjE;GACJ;GACA,MAAM,WAAW,OAAO,IAAI,GAAG;GAC/B,IAAI,CAAC,UAAU;GACf,IAAI,QAAQ,OAAO,IAAI,KAAK,OAAO,UAAU,GAAG,CAAC;QAC5C,OAAO,OAAO,GAAG;EAC1B;EACA,MAAM,OAAO,CAAC,GAAG,OAAO,OAAO,CAAC;EAEhC,KAAK,MAAM,GAAG,MAAM,EAAE,KAAK,EAAE,EAAE;EAC/B,KAAK,MAAM,CAAC,IAAI,WAAW,MAAM,KAAK,OAAO,KAAK,IAAI,IAAI,KAAK,MAAM,GAAG,GAAG,MAAM;EACjF,OAAO;CACX;AACJ"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@1337exp/taoux",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.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",
|
|
@@ -139,6 +139,10 @@
|
|
|
139
139
|
"types": "./dist/touch.d.ts",
|
|
140
140
|
"import": "./dist/touch.js"
|
|
141
141
|
},
|
|
142
|
+
"./undo": {
|
|
143
|
+
"types": "./dist/undo.d.ts",
|
|
144
|
+
"import": "./dist/undo.js"
|
|
145
|
+
},
|
|
142
146
|
"./wheel": {
|
|
143
147
|
"types": "./dist/wheel.d.ts",
|
|
144
148
|
"import": "./dist/wheel.js"
|