@1337exp/taoux 0.16.0 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"curvefield.js","names":["_openBlock","_createElementBlock","_createVNode","_unref","TaoxCurveEditor","_createElementVNode","_createTextVNode","_toDisplayString","_withCtx","_Fragment","_renderList","_createBlock","_createCommentVNode","_sfc_main"],"sources":["../src/curvefield/TaoxCurveField.vue","../src/curvefield/TaoxCurveField.vue"],"sourcesContent":["<script lang=\"ts\" setup>\nimport { TaoButton, TaoInputNumber, TaoSegmented, TaoSegmentedOption, TaoSelect, TaoSwitch } from '@1337exp/taoui';\nimport { computed, ref } from 'vue';\nimport { movePoint, removePoint, setEase, TaoxCurveEditor, valueBounds, type CurveGuides, type CurvePoint } from '../curveeditor';\nimport { DEFAULT_BEZIER, EASE_DIRECTIONS, EASE_FAMILIES, easeName, easeParts, type Ease, type EaseDirection, type EaseFamily } from '../ease';\nimport { clampTo, niceStep, roundTo } from '../num';\nimport type { CurveFieldLabels } from './labels';\n\n// A curve with fields: the plot (TaoxCurveEditor), the fields of the selected point, the transition to the next point, the grid step, remove and reset.\n// The first taoux module on top of TaoUI: the plot and the logic stay in taoux, the fields and buttons are TaoUI components.\n// Кривая с полями: график (TaoxCurveEditor), поля выбранной точки, переход к следующей точке, шаг сетки, удаление и сброс.\n// Первый модуль taoux поверх TaoUI: график и логика остаются в taoux, поля и кнопки это компоненты TaoUI.\nconst props = withDefaults(\n defineProps<{\n /**\n * Curve points.\n * Точки кривой.\n */\n modelValue: readonly CurvePoint[];\n /**\n * Allowed values: they fix the plot view and do not let a point be dragged past the bound.\n * Допустимые значения: фиксируют вид графика и не дают утащить точку за границу.\n */\n min?: number;\n max?: number;\n /**\n * The \"default\" curve: without it there is no reset button.\n * Кривая «по умолчанию»: без неё кнопки сброса нет.\n */\n defaultValue?: readonly CurvePoint[];\n /**\n * How many decimals to keep in time and value; not set means do not round.\n * Сколько знаков после запятой оставлять у времени и значения; не задано — не обрезать.\n */\n precision?: number;\n /**\n * The time step of the grid and of the time field.\n * Шаг по времени у сетки и у поля времени.\n */\n stepT?: number;\n /**\n * Snapping to the grid at start.\n * Прилипание к сетке при старте.\n */\n snap?: boolean;\n /**\n * Labels in the app language; missing ones fall back to English.\n * Надписи на языке приложения; недостающие берутся английские.\n */\n labels?: Partial<CurveFieldLabels>;\n /**\n * Guides from the selected point to the axes: `off`, `lines` (default) or `values`.\n * Направляющие от выбранной точки к осям: `off`, `lines` (по умолчанию) или `values`.\n */\n guides?: CurveGuides;\n /**\n * Labels for screen readers: see TaoxCurveEditor.\n * Подписи для скринридеров: см. TaoxCurveEditor.\n */\n pointLabel?: (index: number, point: CurvePoint) => string;\n handleLabel?: (n: number, index: number) => string;\n /**\n * How the plot writes time (its axis and the tag of the selected point): see TaoxCurveEditor.\n * Как график записывает время (ось и метка выбранной точки): см. TaoxCurveEditor.\n */\n formatT?: (t: number) => string;\n }>(),\n { stepT: 0.05, snap: true, guides: 'lines' },\n);\nconst emit = defineEmits<{ 'update:modelValue': [value: CurvePoint[]]; commit: [] }>();\n\nconst DEFAULT_LABELS: CurveFieldLabels = {\n time: 'Time',\n value: 'Value',\n transition: 'Transition to the next point',\n snap: 'Snap to grid',\n remove: 'Remove',\n reset: 'Reset',\n hint: 'Double-click adds a point, Alt+click or Delete removes it, Shift disables snapping',\n};\nconst text = computed(() => ({ ...DEFAULT_LABELS, ...props.labels }));\n\nconst selected = ref(0);\nconst snapOn = ref(props.snap);\n\nconst points = computed(() => props.modelValue.map((p) => ({ ...p })));\nconst current = computed(() => points.value[Math.min(selected.value, points.value.length - 1)]!);\nconst stepV = computed(() => {\n const b = valueBounds(points.value, props.min, props.max);\n return niceStep(b.max - b.min, 20);\n});\nconst canReset = computed(() => props.defaultValue !== undefined && JSON.stringify(points.value) !== JSON.stringify(props.defaultValue));\n\nfunction change(next: CurvePoint[]) {\n emit('update:modelValue', next);\n}\n\nfunction removeSelected() {\n change(removePoint(points.value, selected.value));\n selected.value = 0;\n emit('commit');\n}\n\nfunction setField(field: 't' | 'v', value: number | null) {\n if (value === null || !Number.isFinite(value)) return;\n const p = current.value;\n const tt = field === 't' ? roundTo(value, props.precision) : p.t;\n const v = field === 'v' ? clampTo(roundTo(value, props.precision), props.min, props.max) : p.v;\n change(movePoint(points.value, selected.value, tt, v));\n emit('commit');\n}\n\nfunction reset() {\n if (props.defaultValue === undefined) return;\n selected.value = 0;\n change(props.defaultValue.map((p) => ({ ...p })));\n emit('commit');\n}\n\n//--------------------------------------------------\n// The transition from the selected point to the next: the kind (linear, step, a family or bezier) and the direction.\n// Function names are not translated: they are known from CSS and animation libraries and would not be found by a translation.\n// Переход от выбранной точки к следующей: вид (linear, step, семейство или bezier) и направление.\n// Названия функций не переводятся: их знают по CSS и библиотекам анимации, по переводу не найдут.\n\nconst isLast = computed(() => selected.value >= points.value.length - 1);\nconst kind = computed(() => {\n const e = current.value.ease;\n if (e === undefined || e === 'linear') return 'linear';\n if (typeof e === 'object') return 'bezier';\n return easeParts(e)?.family ?? e;\n});\nconst direction = computed<EaseDirection>(() => {\n const e = current.value.ease;\n return typeof e === 'string' ? (easeParts(e)?.direction ?? 'in-out') : 'in-out';\n});\n// linear, step and Bezier have no direction: the switch stays in place, inactive, so that it is visible how this works\n// У linear, step и Безье направления нет: переключатель остаётся на месте неактивным, чтобы было видно, как это устроено\nconst hasDirection = computed(() => !isLast.value && typeof current.value.ease === 'string' && easeParts(current.value.ease) !== null);\nconst kindOptions = ['linear', 'step', ...EASE_FAMILIES, 'bezier'].map((v) => ({ value: v, label: v }));\n\nfunction applyEase(next: Ease) {\n change(setEase(points.value, selected.value, next));\n emit('commit');\n}\n\nfunction setKind(v: string | number | null) {\n if (typeof v !== 'string') return;\n if (v === 'linear' || v === 'step') applyEase(v);\n else if (v === 'bezier') applyEase({ bezier: DEFAULT_BEZIER });\n else applyEase(easeName(v as EaseFamily, direction.value));\n}\n\nfunction setDirection(v: unknown) {\n const e = current.value.ease;\n const parts = typeof e === 'string' ? easeParts(e) : null;\n if (parts && typeof v === 'string' && (EASE_DIRECTIONS as readonly string[]).includes(v)) applyEase(easeName(parts.family, v as EaseDirection));\n}\n</script>\n\n<template>\n <div class=\"tx-curve-field\">\n <TaoxCurveEditor\n :model-value=\"points\"\n v-model:selected=\"selected\"\n :min=\"min\"\n :max=\"max\"\n :precision=\"precision\"\n :snap=\"snapOn\"\n :step-t=\"stepT\"\n :hint=\"text.hint\"\n :guides=\"guides\"\n :point-label=\"pointLabel\"\n :handle-label=\"handleLabel\"\n :format-t=\"formatT\"\n @update:model-value=\"change\"\n @commit=\"emit('commit')\"\n />\n\n <div class=\"tx-curve-field__fields\">\n <label>{{ text.time }}<TaoInputNumber size=\"small\" :min=\"0\" :max=\"1\" :step=\"stepT\" :precision=\"precision\" :controls=\"false\" :model-value=\"current.t\" @update:model-value=\"(x) => setField('t', x)\" /></label>\n <label>{{ text.value }}<TaoInputNumber size=\"small\" :min=\"min\" :max=\"max\" :step=\"stepV\" :precision=\"precision\" :controls=\"false\" :model-value=\"current.v\" @update:model-value=\"(x) => setField('v', x)\" /></label>\n </div>\n\n <div class=\"tx-curve-field__ease\">\n <span class=\"tx-curve-field__title\" aria-hidden=\"true\">{{ text.transition }}</span>\n <div class=\"tx-curve-field__ease-row\" role=\"group\" :aria-label=\"text.transition\">\n <TaoSelect class=\"tx-curve-field__kind\" size=\"small\" :clearable=\"false\" :options=\"kindOptions\" :disabled=\"isLast\" :model-value=\"kind\" @update:model-value=\"setKind\" />\n <TaoSegmented size=\"small\" :disabled=\"!hasDirection\" :model-value=\"hasDirection ? direction : undefined\" @update:model-value=\"setDirection\">\n <TaoSegmentedOption v-for=\"d in EASE_DIRECTIONS\" :key=\"d\" :value=\"d\" :label=\"d\" />\n </TaoSegmented>\n </div>\n </div>\n\n <div class=\"tx-curve-field__bar\">\n <TaoSwitch v-model=\"snapOn\" :label=\"text.snap\" />\n <span class=\"tx-curve-field__spacer\" />\n <TaoButton size=\"small\" variant=\"ghost\" :disabled=\"points.length <= 2\" @click=\"removeSelected\">{{ text.remove }}</TaoButton>\n <TaoButton v-if=\"defaultValue !== undefined\" size=\"small\" variant=\"ghost\" :disabled=\"!canReset\" @click=\"reset\">{{ text.reset }}</TaoButton>\n </div>\n </div>\n</template>\n\n<style scoped>\n.tx-curve-field {\n display: flex;\n flex-direction: column;\n gap: 8px;\n}\n\n.tx-curve-field__fields {\n display: grid;\n grid-template-columns: 1fr 1fr;\n gap: 8px;\n}\n\n.tx-curve-field__fields > label {\n display: flex;\n flex-direction: column;\n gap: 2px;\n color: var(--tx-curve-label, #8b929c);\n font-size: 11px;\n}\n\n.tx-curve-field__ease {\n display: flex;\n flex-direction: column;\n gap: 2px;\n}\n\n.tx-curve-field__title {\n color: var(--tx-curve-label, #8b929c);\n font-size: 11px;\n}\n\n/* The list and the direction in one row: the list takes the rest, the switch keeps its own width / Список и направление в одну строку: список забирает остаток, переключатель держит свою ширину */\n.tx-curve-field__ease-row {\n display: flex;\n align-items: center;\n gap: 6px;\n}\n\n.tx-curve-field__kind {\n flex: 1;\n min-width: 0;\n}\n\n.tx-curve-field__ease-row > :last-child {\n flex: none;\n}\n\n.tx-curve-field__bar {\n display: flex;\n align-items: center;\n gap: 4px;\n font-size: 12px;\n}\n\n.tx-curve-field__spacer {\n flex: 1;\n}\n</style>\n","<script lang=\"ts\" setup>\nimport { TaoButton, TaoInputNumber, TaoSegmented, TaoSegmentedOption, TaoSelect, TaoSwitch } from '@1337exp/taoui';\nimport { computed, ref } from 'vue';\nimport { movePoint, removePoint, setEase, TaoxCurveEditor, valueBounds, type CurveGuides, type CurvePoint } from '../curveeditor';\nimport { DEFAULT_BEZIER, EASE_DIRECTIONS, EASE_FAMILIES, easeName, easeParts, type Ease, type EaseDirection, type EaseFamily } from '../ease';\nimport { clampTo, niceStep, roundTo } from '../num';\nimport type { CurveFieldLabels } from './labels';\n\n// A curve with fields: the plot (TaoxCurveEditor), the fields of the selected point, the transition to the next point, the grid step, remove and reset.\n// The first taoux module on top of TaoUI: the plot and the logic stay in taoux, the fields and buttons are TaoUI components.\n// Кривая с полями: график (TaoxCurveEditor), поля выбранной точки, переход к следующей точке, шаг сетки, удаление и сброс.\n// Первый модуль taoux поверх TaoUI: график и логика остаются в taoux, поля и кнопки это компоненты TaoUI.\nconst props = withDefaults(\n defineProps<{\n /**\n * Curve points.\n * Точки кривой.\n */\n modelValue: readonly CurvePoint[];\n /**\n * Allowed values: they fix the plot view and do not let a point be dragged past the bound.\n * Допустимые значения: фиксируют вид графика и не дают утащить точку за границу.\n */\n min?: number;\n max?: number;\n /**\n * The \"default\" curve: without it there is no reset button.\n * Кривая «по умолчанию»: без неё кнопки сброса нет.\n */\n defaultValue?: readonly CurvePoint[];\n /**\n * How many decimals to keep in time and value; not set means do not round.\n * Сколько знаков после запятой оставлять у времени и значения; не задано — не обрезать.\n */\n precision?: number;\n /**\n * The time step of the grid and of the time field.\n * Шаг по времени у сетки и у поля времени.\n */\n stepT?: number;\n /**\n * Snapping to the grid at start.\n * Прилипание к сетке при старте.\n */\n snap?: boolean;\n /**\n * Labels in the app language; missing ones fall back to English.\n * Надписи на языке приложения; недостающие берутся английские.\n */\n labels?: Partial<CurveFieldLabels>;\n /**\n * Guides from the selected point to the axes: `off`, `lines` (default) or `values`.\n * Направляющие от выбранной точки к осям: `off`, `lines` (по умолчанию) или `values`.\n */\n guides?: CurveGuides;\n /**\n * Labels for screen readers: see TaoxCurveEditor.\n * Подписи для скринридеров: см. TaoxCurveEditor.\n */\n pointLabel?: (index: number, point: CurvePoint) => string;\n handleLabel?: (n: number, index: number) => string;\n /**\n * How the plot writes time (its axis and the tag of the selected point): see TaoxCurveEditor.\n * Как график записывает время (ось и метка выбранной точки): см. TaoxCurveEditor.\n */\n formatT?: (t: number) => string;\n }>(),\n { stepT: 0.05, snap: true, guides: 'lines' },\n);\nconst emit = defineEmits<{ 'update:modelValue': [value: CurvePoint[]]; commit: [] }>();\n\nconst DEFAULT_LABELS: CurveFieldLabels = {\n time: 'Time',\n value: 'Value',\n transition: 'Transition to the next point',\n snap: 'Snap to grid',\n remove: 'Remove',\n reset: 'Reset',\n hint: 'Double-click adds a point, Alt+click or Delete removes it, Shift disables snapping',\n};\nconst text = computed(() => ({ ...DEFAULT_LABELS, ...props.labels }));\n\nconst selected = ref(0);\nconst snapOn = ref(props.snap);\n\nconst points = computed(() => props.modelValue.map((p) => ({ ...p })));\nconst current = computed(() => points.value[Math.min(selected.value, points.value.length - 1)]!);\nconst stepV = computed(() => {\n const b = valueBounds(points.value, props.min, props.max);\n return niceStep(b.max - b.min, 20);\n});\nconst canReset = computed(() => props.defaultValue !== undefined && JSON.stringify(points.value) !== JSON.stringify(props.defaultValue));\n\nfunction change(next: CurvePoint[]) {\n emit('update:modelValue', next);\n}\n\nfunction removeSelected() {\n change(removePoint(points.value, selected.value));\n selected.value = 0;\n emit('commit');\n}\n\nfunction setField(field: 't' | 'v', value: number | null) {\n if (value === null || !Number.isFinite(value)) return;\n const p = current.value;\n const tt = field === 't' ? roundTo(value, props.precision) : p.t;\n const v = field === 'v' ? clampTo(roundTo(value, props.precision), props.min, props.max) : p.v;\n change(movePoint(points.value, selected.value, tt, v));\n emit('commit');\n}\n\nfunction reset() {\n if (props.defaultValue === undefined) return;\n selected.value = 0;\n change(props.defaultValue.map((p) => ({ ...p })));\n emit('commit');\n}\n\n//--------------------------------------------------\n// The transition from the selected point to the next: the kind (linear, step, a family or bezier) and the direction.\n// Function names are not translated: they are known from CSS and animation libraries and would not be found by a translation.\n// Переход от выбранной точки к следующей: вид (linear, step, семейство или bezier) и направление.\n// Названия функций не переводятся: их знают по CSS и библиотекам анимации, по переводу не найдут.\n\nconst isLast = computed(() => selected.value >= points.value.length - 1);\nconst kind = computed(() => {\n const e = current.value.ease;\n if (e === undefined || e === 'linear') return 'linear';\n if (typeof e === 'object') return 'bezier';\n return easeParts(e)?.family ?? e;\n});\nconst direction = computed<EaseDirection>(() => {\n const e = current.value.ease;\n return typeof e === 'string' ? (easeParts(e)?.direction ?? 'in-out') : 'in-out';\n});\n// linear, step and Bezier have no direction: the switch stays in place, inactive, so that it is visible how this works\n// У linear, step и Безье направления нет: переключатель остаётся на месте неактивным, чтобы было видно, как это устроено\nconst hasDirection = computed(() => !isLast.value && typeof current.value.ease === 'string' && easeParts(current.value.ease) !== null);\nconst kindOptions = ['linear', 'step', ...EASE_FAMILIES, 'bezier'].map((v) => ({ value: v, label: v }));\n\nfunction applyEase(next: Ease) {\n change(setEase(points.value, selected.value, next));\n emit('commit');\n}\n\nfunction setKind(v: string | number | null) {\n if (typeof v !== 'string') return;\n if (v === 'linear' || v === 'step') applyEase(v);\n else if (v === 'bezier') applyEase({ bezier: DEFAULT_BEZIER });\n else applyEase(easeName(v as EaseFamily, direction.value));\n}\n\nfunction setDirection(v: unknown) {\n const e = current.value.ease;\n const parts = typeof e === 'string' ? easeParts(e) : null;\n if (parts && typeof v === 'string' && (EASE_DIRECTIONS as readonly string[]).includes(v)) applyEase(easeName(parts.family, v as EaseDirection));\n}\n</script>\n\n<template>\n <div class=\"tx-curve-field\">\n <TaoxCurveEditor\n :model-value=\"points\"\n v-model:selected=\"selected\"\n :min=\"min\"\n :max=\"max\"\n :precision=\"precision\"\n :snap=\"snapOn\"\n :step-t=\"stepT\"\n :hint=\"text.hint\"\n :guides=\"guides\"\n :point-label=\"pointLabel\"\n :handle-label=\"handleLabel\"\n :format-t=\"formatT\"\n @update:model-value=\"change\"\n @commit=\"emit('commit')\"\n />\n\n <div class=\"tx-curve-field__fields\">\n <label>{{ text.time }}<TaoInputNumber size=\"small\" :min=\"0\" :max=\"1\" :step=\"stepT\" :precision=\"precision\" :controls=\"false\" :model-value=\"current.t\" @update:model-value=\"(x) => setField('t', x)\" /></label>\n <label>{{ text.value }}<TaoInputNumber size=\"small\" :min=\"min\" :max=\"max\" :step=\"stepV\" :precision=\"precision\" :controls=\"false\" :model-value=\"current.v\" @update:model-value=\"(x) => setField('v', x)\" /></label>\n </div>\n\n <div class=\"tx-curve-field__ease\">\n <span class=\"tx-curve-field__title\" aria-hidden=\"true\">{{ text.transition }}</span>\n <div class=\"tx-curve-field__ease-row\" role=\"group\" :aria-label=\"text.transition\">\n <TaoSelect class=\"tx-curve-field__kind\" size=\"small\" :clearable=\"false\" :options=\"kindOptions\" :disabled=\"isLast\" :model-value=\"kind\" @update:model-value=\"setKind\" />\n <TaoSegmented size=\"small\" :disabled=\"!hasDirection\" :model-value=\"hasDirection ? direction : undefined\" @update:model-value=\"setDirection\">\n <TaoSegmentedOption v-for=\"d in EASE_DIRECTIONS\" :key=\"d\" :value=\"d\" :label=\"d\" />\n </TaoSegmented>\n </div>\n </div>\n\n <div class=\"tx-curve-field__bar\">\n <TaoSwitch v-model=\"snapOn\" :label=\"text.snap\" />\n <span class=\"tx-curve-field__spacer\" />\n <TaoButton size=\"small\" variant=\"ghost\" :disabled=\"points.length <= 2\" @click=\"removeSelected\">{{ text.remove }}</TaoButton>\n <TaoButton v-if=\"defaultValue !== undefined\" size=\"small\" variant=\"ghost\" :disabled=\"!canReset\" @click=\"reset\">{{ text.reset }}</TaoButton>\n </div>\n </div>\n</template>\n\n<style scoped>\n.tx-curve-field {\n display: flex;\n flex-direction: column;\n gap: 8px;\n}\n\n.tx-curve-field__fields {\n display: grid;\n grid-template-columns: 1fr 1fr;\n gap: 8px;\n}\n\n.tx-curve-field__fields > label {\n display: flex;\n flex-direction: column;\n gap: 2px;\n color: var(--tx-curve-label, #8b929c);\n font-size: 11px;\n}\n\n.tx-curve-field__ease {\n display: flex;\n flex-direction: column;\n gap: 2px;\n}\n\n.tx-curve-field__title {\n color: var(--tx-curve-label, #8b929c);\n font-size: 11px;\n}\n\n/* The list and the direction in one row: the list takes the rest, the switch keeps its own width / Список и направление в одну строку: список забирает остаток, переключатель держит свою ширину */\n.tx-curve-field__ease-row {\n display: flex;\n align-items: center;\n gap: 6px;\n}\n\n.tx-curve-field__kind {\n flex: 1;\n min-width: 0;\n}\n\n.tx-curve-field__ease-row > :last-child {\n flex: none;\n}\n\n.tx-curve-field__bar {\n display: flex;\n align-items: center;\n gap: 4px;\n font-size: 12px;\n}\n\n.tx-curve-field__spacer {\n flex: 1;\n}\n</style>\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAYA,MAAM,QAAQ;EAyDd,MAAM,OAAO;EAEb,MAAM,iBAAmC;GACrC,MAAM;GACN,OAAO;GACP,YAAY;GACZ,MAAM;GACN,QAAQ;GACR,OAAO;GACP,MAAM;EACV;EACA,MAAM,OAAO,gBAAgB;GAAE,GAAG;GAAgB,GAAG,MAAM;EAAO,EAAE;EAEpE,MAAM,WAAW,IAAI,CAAC;EACtB,MAAM,SAAS,IAAI,MAAM,IAAI;EAE7B,MAAM,SAAS,eAAe,MAAM,WAAW,KAAK,OAAO,EAAE,GAAG,EAAE,EAAE,CAAC;EACrE,MAAM,UAAU,eAAe,OAAO,MAAM,KAAK,IAAI,SAAS,OAAO,OAAO,MAAM,SAAS,CAAC,EAAG;EAC/F,MAAM,QAAQ,eAAe;GACzB,MAAM,IAAI,YAAY,OAAO,OAAO,MAAM,KAAK,MAAM,GAAG;GACxD,OAAO,SAAS,EAAE,MAAM,EAAE,KAAK,EAAE;EACrC,CAAC;EACD,MAAM,WAAW,eAAe,MAAM,iBAAiB,KAAA,KAAa,KAAK,UAAU,OAAO,KAAK,MAAM,KAAK,UAAU,MAAM,YAAY,CAAC;EAEvI,SAAS,OAAO,MAAoB;GAChC,KAAK,qBAAqB,IAAI;EAClC;EAEA,SAAS,iBAAiB;GACtB,OAAO,YAAY,OAAO,OAAO,SAAS,KAAK,CAAC;GAChD,SAAS,QAAQ;GACjB,KAAK,QAAQ;EACjB;EAEA,SAAS,SAAS,OAAkB,OAAsB;GACtD,IAAI,UAAU,QAAQ,CAAC,OAAO,SAAS,KAAK,GAAG;GAC/C,MAAM,IAAI,QAAQ;GAClB,MAAM,KAAK,UAAU,MAAM,QAA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M,GAAA,CAAA,C;;;KAC5F,QAAA,iBAAiB,KAAA,KAAlCP,UAAA,GAAAW,YAA2IR,MAAA,SAAA,GAAA;;MAA9F,MAAK;MAAQ,SAAQ;MAAS,UAAQ,CAAG,SAAA;MAAW,SAAO;;MAAO,SAAAK,cAAgB,CAAbF,gBAAAC,gBAAA,KAAA,MAAK,KAAK,GAAA,CAAA,C"}
1
+ {"version":3,"file":"curvefield.js","names":["_openBlock","_createElementBlock","_createVNode","_unref","TaoxCurveEditor","_createElementVNode","_createTextVNode","_toDisplayString","_withCtx","_Fragment","_renderList","_createBlock","_createCommentVNode","_sfc_main"],"sources":["../src/curvefield/TaoxCurveField.vue","../src/curvefield/TaoxCurveField.vue"],"sourcesContent":["<script lang=\"ts\" setup>\nimport { TaoButton, TaoInputNumber, TaoSegmented, TaoSegmentedOption, TaoSelect, TaoSwitch } from '@1337exp/taoui';\nimport { computed, ref } from 'vue';\nimport { movePoint, removePoint, setEase, TaoxCurveEditor, valueBounds, type CurveGuides, type CurvePoint } from '../curveeditor';\nimport { DEFAULT_BEZIER, EASE_DIRECTIONS, EASE_FAMILIES, easeName, easeParts, type Ease, type EaseDirection, type EaseFamily } from '../ease';\nimport { clampTo, niceStep, roundTo } from '../num';\nimport type { CurveFieldLabels } from './labels';\n\n// A curve with fields: the plot (TaoxCurveEditor), the fields of the selected point, the transition to the next point, the grid step, remove and reset.\n// The first taoux module on top of TaoUI: the plot and the logic stay in taoux, the fields and buttons are TaoUI components.\n// Кривая с полями: график (TaoxCurveEditor), поля выбранной точки, переход к следующей точке, шаг сетки, удаление и сброс.\n// Первый модуль taoux поверх TaoUI: график и логика остаются в taoux, поля и кнопки это компоненты TaoUI.\nconst props = withDefaults(\n defineProps<{\n /**\n * Curve points.\n * Точки кривой.\n */\n modelValue: readonly CurvePoint[];\n /**\n * Allowed values: they fix the plot view and do not let a point be dragged past the bound.\n * Допустимые значения: фиксируют вид графика и не дают утащить точку за границу.\n */\n min?: number;\n max?: number;\n /**\n * The \"default\" curve: without it there is no reset button.\n * Кривая «по умолчанию»: без неё кнопки сброса нет.\n */\n defaultValue?: readonly CurvePoint[];\n /**\n * How many decimals to keep in time and value; not set means do not round.\n * Сколько знаков после запятой оставлять у времени и значения; не задано — не обрезать.\n */\n precision?: number;\n /**\n * The time step of the grid and of the time field.\n * Шаг по времени у сетки и у поля времени.\n */\n stepT?: number;\n /**\n * Snapping to the grid at start.\n * Прилипание к сетке при старте.\n */\n snap?: boolean;\n /**\n * Labels in the app language; missing ones fall back to English.\n * Надписи на языке приложения; недостающие берутся английские.\n */\n labels?: Partial<CurveFieldLabels>;\n /**\n * Guides from the selected point to the axes: `off`, `lines` (default) or `values`.\n * Направляющие от выбранной точки к осям: `off`, `lines` (по умолчанию) или `values`.\n */\n guides?: CurveGuides;\n /**\n * Labels for screen readers: see TaoxCurveEditor.\n * Подписи для скринридеров: см. TaoxCurveEditor.\n */\n pointLabel?: (index: number, point: CurvePoint) => string;\n handleLabel?: (n: number, index: number) => string;\n /**\n * How the plot writes time (its axis and the tag of the selected point): see TaoxCurveEditor.\n * Как график записывает время (ось и метка выбранной точки): см. TaoxCurveEditor.\n */\n formatT?: (t: number) => string;\n }>(),\n { stepT: 0.05, snap: true, guides: 'lines' },\n);\nconst emit = defineEmits<{ 'update:modelValue': [value: CurvePoint[]]; commit: [] }>();\n\nconst DEFAULT_LABELS: CurveFieldLabels = {\n time: 'Time',\n value: 'Value',\n transition: 'Transition to the next point',\n snap: 'Snap to grid',\n remove: 'Remove',\n reset: 'Reset',\n hint: 'Double-click adds a point, Alt+click or Delete removes it, Shift disables snapping',\n};\nconst text = computed(() => ({ ...DEFAULT_LABELS, ...props.labels }));\n\nconst selected = ref(0);\nconst snapOn = ref(props.snap);\n\nconst points = computed(() => props.modelValue.map((p) => ({ ...p })));\nconst current = computed(() => points.value[Math.min(selected.value, points.value.length - 1)]!);\nconst stepV = computed(() => {\n const b = valueBounds(points.value, props.min, props.max);\n return niceStep(b.max - b.min, 20);\n});\nconst canReset = computed(() => props.defaultValue !== undefined && JSON.stringify(points.value) !== JSON.stringify(props.defaultValue));\n\nfunction change(next: CurvePoint[]) {\n emit('update:modelValue', next);\n}\n\nfunction removeSelected() {\n change(removePoint(points.value, selected.value));\n selected.value = 0;\n emit('commit');\n}\n\nfunction setField(field: 't' | 'v', value: number | null) {\n if (value === null || !Number.isFinite(value)) return;\n const p = current.value;\n const tt = field === 't' ? roundTo(value, props.precision) : p.t;\n const v = field === 'v' ? clampTo(roundTo(value, props.precision), props.min, props.max) : p.v;\n change(movePoint(points.value, selected.value, tt, v));\n emit('commit');\n}\n\nfunction reset() {\n if (props.defaultValue === undefined) return;\n selected.value = 0;\n change(props.defaultValue.map((p) => ({ ...p })));\n emit('commit');\n}\n\n//--------------------------------------------------\n// The transition from the selected point to the next: the kind (linear, step, a family or bezier) and the direction.\n// Function names are not translated: they are known from CSS and animation libraries and would not be found by a translation.\n// Переход от выбранной точки к следующей: вид (linear, step, семейство или bezier) и направление.\n// Названия функций не переводятся: их знают по CSS и библиотекам анимации, по переводу не найдут.\n\nconst isLast = computed(() => selected.value >= points.value.length - 1);\nconst kind = computed(() => {\n const e = current.value.ease;\n if (e === undefined || e === 'linear') return 'linear';\n if (typeof e === 'object') return 'bezier';\n return easeParts(e)?.family ?? e;\n});\nconst direction = computed<EaseDirection>(() => {\n const e = current.value.ease;\n return typeof e === 'string' ? (easeParts(e)?.direction ?? 'in-out') : 'in-out';\n});\n// linear, step and Bezier have no direction: the switch stays in place, inactive, so that it is visible how this works\n// У linear, step и Безье направления нет: переключатель остаётся на месте неактивным, чтобы было видно, как это устроено\nconst hasDirection = computed(() => !isLast.value && typeof current.value.ease === 'string' && easeParts(current.value.ease) !== null);\nconst kindOptions = ['linear', 'step', ...EASE_FAMILIES, 'bezier'].map((v) => ({ id: v, label: v }));\n\nfunction applyEase(next: Ease) {\n change(setEase(points.value, selected.value, next));\n emit('commit');\n}\n\nfunction setKind(v: string | number | null) {\n if (typeof v !== 'string') return;\n if (v === 'linear' || v === 'step') applyEase(v);\n else if (v === 'bezier') applyEase({ bezier: DEFAULT_BEZIER });\n else applyEase(easeName(v as EaseFamily, direction.value));\n}\n\nfunction setDirection(v: unknown) {\n const e = current.value.ease;\n const parts = typeof e === 'string' ? easeParts(e) : null;\n if (parts && typeof v === 'string' && (EASE_DIRECTIONS as readonly string[]).includes(v)) applyEase(easeName(parts.family, v as EaseDirection));\n}\n</script>\n\n<template>\n <div class=\"tx-curve-field\">\n <TaoxCurveEditor\n :model-value=\"points\"\n v-model:selected=\"selected\"\n :min=\"min\"\n :max=\"max\"\n :precision=\"precision\"\n :snap=\"snapOn\"\n :step-t=\"stepT\"\n :hint=\"text.hint\"\n :guides=\"guides\"\n :point-label=\"pointLabel\"\n :handle-label=\"handleLabel\"\n :format-t=\"formatT\"\n @update:model-value=\"change\"\n @commit=\"emit('commit')\"\n />\n\n <div class=\"tx-curve-field__fields\">\n <label>{{ text.time }}<TaoInputNumber size=\"small\" :min=\"0\" :max=\"1\" :step=\"stepT\" :precision=\"precision\" :controls=\"false\" :model-value=\"current.t\" @update:model-value=\"(x) => setField('t', x)\" /></label>\n <label>{{ text.value }}<TaoInputNumber size=\"small\" :min=\"min\" :max=\"max\" :step=\"stepV\" :precision=\"precision\" :controls=\"false\" :model-value=\"current.v\" @update:model-value=\"(x) => setField('v', x)\" /></label>\n </div>\n\n <div class=\"tx-curve-field__ease\">\n <span class=\"tx-curve-field__title\" aria-hidden=\"true\">{{ text.transition }}</span>\n <div class=\"tx-curve-field__ease-row\" role=\"group\" :aria-label=\"text.transition\">\n <TaoSelect class=\"tx-curve-field__kind\" size=\"small\" :clearable=\"false\" :items=\"kindOptions\" :disabled=\"isLast\" :model-value=\"kind\" @update:model-value=\"setKind\" />\n <TaoSegmented size=\"small\" :disabled=\"!hasDirection\" :model-value=\"hasDirection ? direction : undefined\" @update:model-value=\"setDirection\">\n <TaoSegmentedOption v-for=\"d in EASE_DIRECTIONS\" :key=\"d\" :value=\"d\" :label=\"d\" />\n </TaoSegmented>\n </div>\n </div>\n\n <div class=\"tx-curve-field__bar\">\n <TaoSwitch v-model=\"snapOn\" :label=\"text.snap\" />\n <span class=\"tx-curve-field__spacer\" />\n <TaoButton size=\"small\" variant=\"ghost\" :disabled=\"points.length <= 2\" @click=\"removeSelected\">{{ text.remove }}</TaoButton>\n <TaoButton v-if=\"defaultValue !== undefined\" size=\"small\" variant=\"ghost\" :disabled=\"!canReset\" @click=\"reset\">{{ text.reset }}</TaoButton>\n </div>\n </div>\n</template>\n\n<style scoped>\n.tx-curve-field {\n display: flex;\n flex-direction: column;\n gap: 8px;\n}\n\n.tx-curve-field__fields {\n display: grid;\n grid-template-columns: 1fr 1fr;\n gap: 8px;\n}\n\n.tx-curve-field__fields > label {\n display: flex;\n flex-direction: column;\n gap: 2px;\n color: var(--tx-curve-label, #8b929c);\n font-size: 11px;\n}\n\n.tx-curve-field__ease {\n display: flex;\n flex-direction: column;\n gap: 2px;\n}\n\n.tx-curve-field__title {\n color: var(--tx-curve-label, #8b929c);\n font-size: 11px;\n}\n\n/* The list and the direction in one row: the list takes the rest, the switch keeps its own width / Список и направление в одну строку: список забирает остаток, переключатель держит свою ширину */\n.tx-curve-field__ease-row {\n display: flex;\n align-items: center;\n gap: 6px;\n}\n\n.tx-curve-field__kind {\n flex: 1;\n min-width: 0;\n}\n\n.tx-curve-field__ease-row > :last-child {\n flex: none;\n}\n\n.tx-curve-field__bar {\n display: flex;\n align-items: center;\n gap: 4px;\n font-size: 12px;\n}\n\n.tx-curve-field__spacer {\n flex: 1;\n}\n</style>\n","<script lang=\"ts\" setup>\nimport { TaoButton, TaoInputNumber, TaoSegmented, TaoSegmentedOption, TaoSelect, TaoSwitch } from '@1337exp/taoui';\nimport { computed, ref } from 'vue';\nimport { movePoint, removePoint, setEase, TaoxCurveEditor, valueBounds, type CurveGuides, type CurvePoint } from '../curveeditor';\nimport { DEFAULT_BEZIER, EASE_DIRECTIONS, EASE_FAMILIES, easeName, easeParts, type Ease, type EaseDirection, type EaseFamily } from '../ease';\nimport { clampTo, niceStep, roundTo } from '../num';\nimport type { CurveFieldLabels } from './labels';\n\n// A curve with fields: the plot (TaoxCurveEditor), the fields of the selected point, the transition to the next point, the grid step, remove and reset.\n// The first taoux module on top of TaoUI: the plot and the logic stay in taoux, the fields and buttons are TaoUI components.\n// Кривая с полями: график (TaoxCurveEditor), поля выбранной точки, переход к следующей точке, шаг сетки, удаление и сброс.\n// Первый модуль taoux поверх TaoUI: график и логика остаются в taoux, поля и кнопки это компоненты TaoUI.\nconst props = withDefaults(\n defineProps<{\n /**\n * Curve points.\n * Точки кривой.\n */\n modelValue: readonly CurvePoint[];\n /**\n * Allowed values: they fix the plot view and do not let a point be dragged past the bound.\n * Допустимые значения: фиксируют вид графика и не дают утащить точку за границу.\n */\n min?: number;\n max?: number;\n /**\n * The \"default\" curve: without it there is no reset button.\n * Кривая «по умолчанию»: без неё кнопки сброса нет.\n */\n defaultValue?: readonly CurvePoint[];\n /**\n * How many decimals to keep in time and value; not set means do not round.\n * Сколько знаков после запятой оставлять у времени и значения; не задано — не обрезать.\n */\n precision?: number;\n /**\n * The time step of the grid and of the time field.\n * Шаг по времени у сетки и у поля времени.\n */\n stepT?: number;\n /**\n * Snapping to the grid at start.\n * Прилипание к сетке при старте.\n */\n snap?: boolean;\n /**\n * Labels in the app language; missing ones fall back to English.\n * Надписи на языке приложения; недостающие берутся английские.\n */\n labels?: Partial<CurveFieldLabels>;\n /**\n * Guides from the selected point to the axes: `off`, `lines` (default) or `values`.\n * Направляющие от выбранной точки к осям: `off`, `lines` (по умолчанию) или `values`.\n */\n guides?: CurveGuides;\n /**\n * Labels for screen readers: see TaoxCurveEditor.\n * Подписи для скринридеров: см. TaoxCurveEditor.\n */\n pointLabel?: (index: number, point: CurvePoint) => string;\n handleLabel?: (n: number, index: number) => string;\n /**\n * How the plot writes time (its axis and the tag of the selected point): see TaoxCurveEditor.\n * Как график записывает время (ось и метка выбранной точки): см. TaoxCurveEditor.\n */\n formatT?: (t: number) => string;\n }>(),\n { stepT: 0.05, snap: true, guides: 'lines' },\n);\nconst emit = defineEmits<{ 'update:modelValue': [value: CurvePoint[]]; commit: [] }>();\n\nconst DEFAULT_LABELS: CurveFieldLabels = {\n time: 'Time',\n value: 'Value',\n transition: 'Transition to the next point',\n snap: 'Snap to grid',\n remove: 'Remove',\n reset: 'Reset',\n hint: 'Double-click adds a point, Alt+click or Delete removes it, Shift disables snapping',\n};\nconst text = computed(() => ({ ...DEFAULT_LABELS, ...props.labels }));\n\nconst selected = ref(0);\nconst snapOn = ref(props.snap);\n\nconst points = computed(() => props.modelValue.map((p) => ({ ...p })));\nconst current = computed(() => points.value[Math.min(selected.value, points.value.length - 1)]!);\nconst stepV = computed(() => {\n const b = valueBounds(points.value, props.min, props.max);\n return niceStep(b.max - b.min, 20);\n});\nconst canReset = computed(() => props.defaultValue !== undefined && JSON.stringify(points.value) !== JSON.stringify(props.defaultValue));\n\nfunction change(next: CurvePoint[]) {\n emit('update:modelValue', next);\n}\n\nfunction removeSelected() {\n change(removePoint(points.value, selected.value));\n selected.value = 0;\n emit('commit');\n}\n\nfunction setField(field: 't' | 'v', value: number | null) {\n if (value === null || !Number.isFinite(value)) return;\n const p = current.value;\n const tt = field === 't' ? roundTo(value, props.precision) : p.t;\n const v = field === 'v' ? clampTo(roundTo(value, props.precision), props.min, props.max) : p.v;\n change(movePoint(points.value, selected.value, tt, v));\n emit('commit');\n}\n\nfunction reset() {\n if (props.defaultValue === undefined) return;\n selected.value = 0;\n change(props.defaultValue.map((p) => ({ ...p })));\n emit('commit');\n}\n\n//--------------------------------------------------\n// The transition from the selected point to the next: the kind (linear, step, a family or bezier) and the direction.\n// Function names are not translated: they are known from CSS and animation libraries and would not be found by a translation.\n// Переход от выбранной точки к следующей: вид (linear, step, семейство или bezier) и направление.\n// Названия функций не переводятся: их знают по CSS и библиотекам анимации, по переводу не найдут.\n\nconst isLast = computed(() => selected.value >= points.value.length - 1);\nconst kind = computed(() => {\n const e = current.value.ease;\n if (e === undefined || e === 'linear') return 'linear';\n if (typeof e === 'object') return 'bezier';\n return easeParts(e)?.family ?? e;\n});\nconst direction = computed<EaseDirection>(() => {\n const e = current.value.ease;\n return typeof e === 'string' ? (easeParts(e)?.direction ?? 'in-out') : 'in-out';\n});\n// linear, step and Bezier have no direction: the switch stays in place, inactive, so that it is visible how this works\n// У linear, step и Безье направления нет: переключатель остаётся на месте неактивным, чтобы было видно, как это устроено\nconst hasDirection = computed(() => !isLast.value && typeof current.value.ease === 'string' && easeParts(current.value.ease) !== null);\nconst kindOptions = ['linear', 'step', ...EASE_FAMILIES, 'bezier'].map((v) => ({ id: v, label: v }));\n\nfunction applyEase(next: Ease) {\n change(setEase(points.value, selected.value, next));\n emit('commit');\n}\n\nfunction setKind(v: string | number | null) {\n if (typeof v !== 'string') return;\n if (v === 'linear' || v === 'step') applyEase(v);\n else if (v === 'bezier') applyEase({ bezier: DEFAULT_BEZIER });\n else applyEase(easeName(v as EaseFamily, direction.value));\n}\n\nfunction setDirection(v: unknown) {\n const e = current.value.ease;\n const parts = typeof e === 'string' ? easeParts(e) : null;\n if (parts && typeof v === 'string' && (EASE_DIRECTIONS as readonly string[]).includes(v)) applyEase(easeName(parts.family, v as EaseDirection));\n}\n</script>\n\n<template>\n <div class=\"tx-curve-field\">\n <TaoxCurveEditor\n :model-value=\"points\"\n v-model:selected=\"selected\"\n :min=\"min\"\n :max=\"max\"\n :precision=\"precision\"\n :snap=\"snapOn\"\n :step-t=\"stepT\"\n :hint=\"text.hint\"\n :guides=\"guides\"\n :point-label=\"pointLabel\"\n :handle-label=\"handleLabel\"\n :format-t=\"formatT\"\n @update:model-value=\"change\"\n @commit=\"emit('commit')\"\n />\n\n <div class=\"tx-curve-field__fields\">\n <label>{{ text.time }}<TaoInputNumber size=\"small\" :min=\"0\" :max=\"1\" :step=\"stepT\" :precision=\"precision\" :controls=\"false\" :model-value=\"current.t\" @update:model-value=\"(x) => setField('t', x)\" /></label>\n <label>{{ text.value }}<TaoInputNumber size=\"small\" :min=\"min\" :max=\"max\" :step=\"stepV\" :precision=\"precision\" :controls=\"false\" :model-value=\"current.v\" @update:model-value=\"(x) => setField('v', x)\" /></label>\n </div>\n\n <div class=\"tx-curve-field__ease\">\n <span class=\"tx-curve-field__title\" aria-hidden=\"true\">{{ text.transition }}</span>\n <div class=\"tx-curve-field__ease-row\" role=\"group\" :aria-label=\"text.transition\">\n <TaoSelect class=\"tx-curve-field__kind\" size=\"small\" :clearable=\"false\" :items=\"kindOptions\" :disabled=\"isLast\" :model-value=\"kind\" @update:model-value=\"setKind\" />\n <TaoSegmented size=\"small\" :disabled=\"!hasDirection\" :model-value=\"hasDirection ? direction : undefined\" @update:model-value=\"setDirection\">\n <TaoSegmentedOption v-for=\"d in EASE_DIRECTIONS\" :key=\"d\" :value=\"d\" :label=\"d\" />\n </TaoSegmented>\n </div>\n </div>\n\n <div class=\"tx-curve-field__bar\">\n <TaoSwitch v-model=\"snapOn\" :label=\"text.snap\" />\n <span class=\"tx-curve-field__spacer\" />\n <TaoButton size=\"small\" variant=\"ghost\" :disabled=\"points.length <= 2\" @click=\"removeSelected\">{{ text.remove }}</TaoButton>\n <TaoButton v-if=\"defaultValue !== undefined\" size=\"small\" variant=\"ghost\" :disabled=\"!canReset\" @click=\"reset\">{{ text.reset }}</TaoButton>\n </div>\n </div>\n</template>\n\n<style scoped>\n.tx-curve-field {\n display: flex;\n flex-direction: column;\n gap: 8px;\n}\n\n.tx-curve-field__fields {\n display: grid;\n grid-template-columns: 1fr 1fr;\n gap: 8px;\n}\n\n.tx-curve-field__fields > label {\n display: flex;\n flex-direction: column;\n gap: 2px;\n color: var(--tx-curve-label, #8b929c);\n font-size: 11px;\n}\n\n.tx-curve-field__ease {\n display: flex;\n flex-direction: column;\n gap: 2px;\n}\n\n.tx-curve-field__title {\n color: var(--tx-curve-label, #8b929c);\n font-size: 11px;\n}\n\n/* The list and the direction in one row: the list takes the rest, the switch keeps its own width / Список и направление в одну строку: список забирает остаток, переключатель держит свою ширину */\n.tx-curve-field__ease-row {\n display: flex;\n align-items: center;\n gap: 6px;\n}\n\n.tx-curve-field__kind {\n flex: 1;\n min-width: 0;\n}\n\n.tx-curve-field__ease-row > :last-child {\n flex: none;\n}\n\n.tx-curve-field__bar {\n display: flex;\n align-items: center;\n gap: 4px;\n font-size: 12px;\n}\n\n.tx-curve-field__spacer {\n flex: 1;\n}\n</style>\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAYA,MAAM,QAAQ;EAyDd,MAAM,OAAO;EAEb,MAAM,iBAAmC;GACrC,MAAM;GACN,OAAO;GACP,YAAY;GACZ,MAAM;GACN,QAAQ;GACR,OAAO;GACP,MAAM;EACV;EACA,MAAM,OAAO,gBAAgB;GAAE,GAAG;GAAgB,GAAG,MAAM;EAAO,EAAE;EAEpE,MAAM,WAAW,IAAI,CAAC;EACtB,MAAM,SAAS,IAAI,MAAM,IAAI;EAE7B,MAAM,SAAS,eAAe,MAAM,WAAW,KAAK,OAAO,EAAE,GAAG,EAAE,EAAE,CAAC;EACrE,MAAM,UAAU,eAAe,OAAO,MAAM,KAAK,IAAI,SAAS,OAAO,OAAO,MAAM,SAAS,CAAC,EAAG;EAC/F,MAAM,QAAQ,eAAe;GACzB,MAAM,IAAI,YAAY,OAAO,OAAO,MAAM,KAAK,MAAM,GAAG;GACxD,OAAO,SAAS,EAAE,MAAM,EAAE,KAAK,EAAE;EACrC,CAAC;EACD,MAAM,WAAW,eAAe,MAAM,iBAAiB,KAAA,KAAa,KAAK,UAAU,OAAO,KAAK,MAAM,KAAK,UAAU,MAAM,YAAY,CAAC;EAEvI,SAAS,OAAO,MAAoB;GAChC,KAAK,qBAAqB,IAAI;EAClC;EAEA,SAAS,iBAAiB;GACtB,OAAO,YAAY,OAAO,OAAO,SAAS,KAAK,CAAC;GAChD,SAAS,QAAQ;GACjB,KAAK,QAAQ;EACjB;EAEA,SAAS,SAAS,OAAkB,OAAsB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AAQ,SAAQ;MAAS,UAAU,OAAA,MAAO,UAAM;MAAQ,SAAO;;MAAgB,SAAAK,cAAiB,CAAdF,gBAAAC,gBAAA,KAAA,MAAK,MAAM,GAAA,CAAA,C;;;KAC5F,QAAA,iBAAiB,KAAA,KAAlCP,UAAA,GAAAW,YAA2IR,MAAA,SAAA,GAAA;;MAA9F,MAAK;MAAQ,SAAQ;MAAS,UAAQ,CAAG,SAAA;MAAW,SAAO;;MAAO,SAAAK,cAAgB,CAAbF,gBAAAC,gBAAA,KAAA,MAAK,KAAK,GAAA,CAAA,C"}
@@ -0,0 +1,63 @@
1
+ import { type Ease } from './ease';
2
+ /**
3
+ * A curve point: t in 0…1, v is the value. `ease` sets how to go from this point to the next (linear by default);
4
+ * on the last point it has no effect.
5
+ * Точка кривой: t в 0…1, v значение. `ease` задаёт, как идти от этой точки к следующей (по умолчанию линейно);
6
+ * у последней точки он ни на что не влияет.
7
+ */
8
+ /**
9
+ * Guides from the selected point to the axes: none, lines only, lines and values.
10
+ * Направляющие от выбранной точки к осям: нет, только линии, линии и значения.
11
+ */
12
+ export type CurveGuides = 'off' | 'lines' | 'values';
13
+ export interface CurvePoint {
14
+ t: number;
15
+ v: number;
16
+ ease?: Ease;
17
+ }
18
+ /**
19
+ * The curve value at t: beyond the end points it equals the end point, between them it follows the `ease` of the left point (linear without it).
20
+ * Значение кривой в t: вне крайних точек равно крайней, между ними по переходу `ease` левой точки (без него линейно).
21
+ */
22
+ export declare function sampleCurve(points: readonly CurvePoint[], t: number): number;
23
+ /**
24
+ * Moves point `i`: along t it stays between its neighbours (the order is kept), along v it is free.
25
+ * Двигает точку `i`: по t она остаётся между соседями (порядок не нарушается), по v свободна.
26
+ */
27
+ export declare function movePoint(points: readonly CurvePoint[], i: number, t: number, v: number): CurvePoint[];
28
+ /**
29
+ * Adds a point at `t` with value `v` (the curve value at that point by default); returns the new list and the point index.
30
+ * Добавляет точку в `t` со значением `v` (по умолчанию значение кривой в этой точке); возвращает новый список и индекс точки.
31
+ */
32
+ export declare function addPoint(points: readonly CurvePoint[], t: number, v?: number): {
33
+ points: CurvePoint[];
34
+ index: number;
35
+ };
36
+ /**
37
+ * Removes a point; never leaves fewer than two (a curve of one point is just a number).
38
+ * Убирает точку; меньше двух точек не оставляет (кривая из одной точки это просто число).
39
+ */
40
+ export declare function removePoint(points: readonly CurvePoint[], i: number): CurvePoint[];
41
+ /**
42
+ * The polyline of segment a→b for drawing: a straight one has two ends, other transitions `steps` pieces (a step: a corner).
43
+ * Ломаная участка a→b для рисования: у прямой два конца, у остальных переходов `steps` отрезков (ступенька: угол).
44
+ */
45
+ export declare function sampleSegment(a: CurvePoint, b: CurvePoint, steps?: number): {
46
+ t: number;
47
+ v: number;
48
+ }[];
49
+ /**
50
+ * A copy of the list with the transition of point `i` (`undefined` and `linear` remove the field: the file stays short).
51
+ * Копия списка с переходом точки `i` (`undefined` и `linear` убирают поле: файл остаётся коротким).
52
+ */
53
+ export declare function setEase(points: readonly CurvePoint[], i: number, ease: Ease | undefined): CurvePoint[];
54
+ /**
55
+ * Value limits for drawing: from 0 (or below the minimum) to the maximum with some headroom, no narrower than 0…1.
56
+ * The given `min`/`max` (the field bounds) fix the view: the plot neither drifts nor leaves the allowed range.
57
+ * Пределы значений для отрисовки: от 0 (или ниже минимума) до максимума с запасом, не уже чем 0…1.
58
+ * Заданные `min`/`max` (границы поля) фиксируют вид: график не плывёт и не выходит за допустимое.
59
+ */
60
+ export declare function valueBounds(points: readonly CurvePoint[], min?: number, max?: number): {
61
+ min: number;
62
+ max: number;
63
+ };
@@ -0,0 +1,167 @@
1
+ import { clamp01 } from "./num.js";
2
+ import { easeValue } from "./ease.js";
3
+ //#region src/curveops.ts
4
+ /**
5
+ * The curve value at t: beyond the end points it equals the end point, between them it follows the `ease` of the left point (linear without it).
6
+ * Значение кривой в t: вне крайних точек равно крайней, между ними по переходу `ease` левой точки (без него линейно).
7
+ */
8
+ function sampleCurve(points, t) {
9
+ const n = points.length;
10
+ if (n === 0) return 0;
11
+ const x = clamp01(t);
12
+ if (x <= points[0].t) return points[0].v;
13
+ if (x >= points[n - 1].t) return points[n - 1].v;
14
+ for (let i = 1; i < n; i++) {
15
+ const b = points[i];
16
+ if (x <= b.t) {
17
+ const a = points[i - 1];
18
+ const span = b.t - a.t;
19
+ return span <= 0 ? b.v : a.v + (b.v - a.v) * easeValue(a.ease, (x - a.t) / span);
20
+ }
21
+ }
22
+ return points[n - 1].v;
23
+ }
24
+ /**
25
+ * Moves point `i`: along t it stays between its neighbours (the order is kept), along v it is free.
26
+ * Двигает точку `i`: по t она остаётся между соседями (порядок не нарушается), по v свободна.
27
+ */
28
+ function movePoint(points, i, t, v) {
29
+ const next = points.map((p) => ({ ...p }));
30
+ const lo = i > 0 ? next[i - 1].t : 0;
31
+ const hi = i < next.length - 1 ? next[i + 1].t : 1;
32
+ next[i] = {
33
+ ...next[i],
34
+ t: Math.min(hi, Math.max(lo, clamp01(t))),
35
+ v
36
+ };
37
+ return next;
38
+ }
39
+ /**
40
+ * Adds a point at `t` with value `v` (the curve value at that point by default); returns the new list and the point index.
41
+ * Добавляет точку в `t` со значением `v` (по умолчанию значение кривой в этой точке); возвращает новый список и индекс точки.
42
+ */
43
+ function addPoint(points, t, v) {
44
+ const x = clamp01(t);
45
+ const next = points.map((p) => ({ ...p }));
46
+ const at = next.findIndex((p) => p.t > x);
47
+ const index = at === -1 ? next.length : at;
48
+ next.splice(index, 0, {
49
+ t: x,
50
+ v: v ?? sampleCurve(points, x)
51
+ });
52
+ return {
53
+ points: next,
54
+ index
55
+ };
56
+ }
57
+ /**
58
+ * Removes a point; never leaves fewer than two (a curve of one point is just a number).
59
+ * Убирает точку; меньше двух точек не оставляет (кривая из одной точки это просто число).
60
+ */
61
+ function removePoint(points, i) {
62
+ if (points.length <= 2) return points.map((p) => ({ ...p }));
63
+ return points.filter((_, k) => k !== i).map((p) => ({ ...p }));
64
+ }
65
+ /**
66
+ * A segment transition that is neither a straight line nor a step: its shape has to be drawn and taken into account when choosing the view.
67
+ * Переход участка, который не прямая и не ступенька: его форму нужно рисовать и учитывать при подборе вида.
68
+ */
69
+ var curved = (e) => e !== void 0 && e !== "linear" && e !== "step";
70
+ /**
71
+ * The polyline of segment a→b for drawing: a straight one has two ends, other transitions `steps` pieces (a step: a corner).
72
+ * Ломаная участка a→b для рисования: у прямой два конца, у остальных переходов `steps` отрезков (ступенька: угол).
73
+ */
74
+ function sampleSegment(a, b, steps = 24) {
75
+ if (a.ease === "step") return [
76
+ {
77
+ t: a.t,
78
+ v: a.v
79
+ },
80
+ {
81
+ t: b.t,
82
+ v: a.v
83
+ },
84
+ {
85
+ t: b.t,
86
+ v: b.v
87
+ }
88
+ ];
89
+ if (!curved(a.ease)) return [{
90
+ t: a.t,
91
+ v: a.v
92
+ }, {
93
+ t: b.t,
94
+ v: b.v
95
+ }];
96
+ const out = [];
97
+ for (let i = 0; i <= steps; i++) {
98
+ const u = i / steps;
99
+ out.push({
100
+ t: a.t + (b.t - a.t) * u,
101
+ v: a.v + (b.v - a.v) * easeValue(a.ease, u)
102
+ });
103
+ }
104
+ return out;
105
+ }
106
+ /**
107
+ * A copy of the list with the transition of point `i` (`undefined` and `linear` remove the field: the file stays short).
108
+ * Копия списка с переходом точки `i` (`undefined` и `linear` убирают поле: файл остаётся коротким).
109
+ */
110
+ function setEase(points, i, ease) {
111
+ return points.map((p, k) => {
112
+ if (k !== i) return { ...p };
113
+ const { ease: _old, ...rest } = p;
114
+ return ease === void 0 || ease === "linear" ? rest : {
115
+ ...rest,
116
+ ease
117
+ };
118
+ });
119
+ }
120
+ /**
121
+ * Value limits for drawing: from 0 (or below the minimum) to the maximum with some headroom, no narrower than 0…1.
122
+ * The given `min`/`max` (the field bounds) fix the view: the plot neither drifts nor leaves the allowed range.
123
+ * Пределы значений для отрисовки: от 0 (или ниже минимума) до максимума с запасом, не уже чем 0…1.
124
+ * Заданные `min`/`max` (границы поля) фиксируют вид: график не плывёт и не выходит за допустимое.
125
+ */
126
+ function valueBounds(points, min, max) {
127
+ let lo = 0;
128
+ let hi = 1;
129
+ for (const p of points) {
130
+ lo = Math.min(lo, p.v);
131
+ hi = Math.max(hi, p.v);
132
+ }
133
+ let outLo = Infinity;
134
+ let outHi = -Infinity;
135
+ const see = (v) => {
136
+ lo = Math.min(lo, v);
137
+ hi = Math.max(hi, v);
138
+ outLo = Math.min(outLo, v);
139
+ outHi = Math.max(outHi, v);
140
+ };
141
+ for (let i = 0; i < points.length - 1; i++) {
142
+ const a = points[i];
143
+ if (!curved(a.ease)) continue;
144
+ if (typeof a.ease === "object") {
145
+ const dv = points[i + 1].v - a.v;
146
+ for (const y of [a.ease.bezier[1], a.ease.bezier[3]]) see(a.v + y * dv);
147
+ }
148
+ for (const s of sampleSegment(points[i], points[i + 1])) see(s.v);
149
+ }
150
+ const auto = {
151
+ min: lo,
152
+ max: hi === lo ? lo + 1 : hi * 1.1
153
+ };
154
+ const a = min === void 0 ? auto.min : Math.min(min, outLo);
155
+ const b = max === void 0 ? auto.max : Math.max(max, outHi);
156
+ return b > a ? {
157
+ min: a,
158
+ max: b
159
+ } : {
160
+ min: a,
161
+ max: a + 1
162
+ };
163
+ }
164
+ //#endregion
165
+ export { addPoint, movePoint, removePoint, sampleCurve, sampleSegment, setEase, valueBounds };
166
+
167
+ //# sourceMappingURL=curveops.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"curveops.js","names":[],"sources":["../src/curveops.ts"],"sourcesContent":["import { easeValue, type Ease } from './ease';\nimport { clamp01 } from './num';\n\n/**\n * A curve point: t in 0…1, v is the value. `ease` sets how to go from this point to the next (linear by default);\n * on the last point it has no effect.\n * Точка кривой: t в 0…1, v значение. `ease` задаёт, как идти от этой точки к следующей (по умолчанию линейно);\n * у последней точки он ни на что не влияет.\n */\n/**\n * Guides from the selected point to the axes: none, lines only, lines and values.\n * Направляющие от выбранной точки к осям: нет, только линии, линии и значения.\n */\nexport type CurveGuides = 'off' | 'lines' | 'values';\n\nexport interface CurvePoint {\n t: number;\n v: number;\n ease?: Ease;\n}\n\n/**\n * The curve value at t: beyond the end points it equals the end point, between them it follows the `ease` of the left point (linear without it).\n * Значение кривой в t: вне крайних точек равно крайней, между ними по переходу `ease` левой точки (без него линейно).\n */\nexport function sampleCurve(points: readonly CurvePoint[], t: number): number {\n const n = points.length;\n if (n === 0) return 0;\n const x = clamp01(t);\n if (x <= points[0]!.t) return points[0]!.v;\n if (x >= points[n - 1]!.t) return points[n - 1]!.v;\n for (let i = 1; i < n; i++) {\n const b = points[i]!;\n if (x <= b.t) {\n const a = points[i - 1]!;\n const span = b.t - a.t;\n return span <= 0 ? b.v : a.v + (b.v - a.v) * easeValue(a.ease, (x - a.t) / span);\n }\n }\n return points[n - 1]!.v;\n}\n\n/**\n * Moves point `i`: along t it stays between its neighbours (the order is kept), along v it is free.\n * Двигает точку `i`: по t она остаётся между соседями (порядок не нарушается), по v свободна.\n */\nexport function movePoint(points: readonly CurvePoint[], i: number, t: number, v: number): CurvePoint[] {\n const next = points.map((p) => ({ ...p }));\n const lo = i > 0 ? next[i - 1]!.t : 0;\n const hi = i < next.length - 1 ? next[i + 1]!.t : 1;\n next[i] = { ...next[i]!, t: Math.min(hi, Math.max(lo, clamp01(t))), v };\n return next;\n}\n\n/**\n * Adds a point at `t` with value `v` (the curve value at that point by default); returns the new list and the point index.\n * Добавляет точку в `t` со значением `v` (по умолчанию значение кривой в этой точке); возвращает новый список и индекс точки.\n */\nexport function addPoint(points: readonly CurvePoint[], t: number, v?: number): { points: CurvePoint[]; index: number } {\n const x = clamp01(t);\n const next = points.map((p) => ({ ...p }));\n const at = next.findIndex((p) => p.t > x);\n const index = at === -1 ? next.length : at;\n next.splice(index, 0, { t: x, v: v ?? sampleCurve(points, x) });\n return { points: next, index };\n}\n\n/**\n * Removes a point; never leaves fewer than two (a curve of one point is just a number).\n * Убирает точку; меньше двух точек не оставляет (кривая из одной точки это просто число).\n */\nexport function removePoint(points: readonly CurvePoint[], i: number): CurvePoint[] {\n if (points.length <= 2) return points.map((p) => ({ ...p }));\n return points.filter((_, k) => k !== i).map((p) => ({ ...p }));\n}\n\n/**\n * A segment transition that is neither a straight line nor a step: its shape has to be drawn and taken into account when choosing the view.\n * Переход участка, который не прямая и не ступенька: его форму нужно рисовать и учитывать при подборе вида.\n */\nconst curved = (e: Ease | undefined) => e !== undefined && e !== 'linear' && e !== 'step';\n\n/**\n * The polyline of segment a→b for drawing: a straight one has two ends, other transitions `steps` pieces (a step: a corner).\n * Ломаная участка a→b для рисования: у прямой два конца, у остальных переходов `steps` отрезков (ступенька: угол).\n */\nexport function sampleSegment(a: CurvePoint, b: CurvePoint, steps = 24): { t: number; v: number }[] {\n if (a.ease === 'step') return [{ t: a.t, v: a.v }, { t: b.t, v: a.v }, { t: b.t, v: b.v }];\n if (!curved(a.ease)) return [{ t: a.t, v: a.v }, { t: b.t, v: b.v }];\n const out: { t: number; v: number }[] = [];\n for (let i = 0; i <= steps; i++) {\n const u = i / steps;\n out.push({ t: a.t + (b.t - a.t) * u, v: a.v + (b.v - a.v) * easeValue(a.ease, u) });\n }\n return out;\n}\n\n/**\n * A copy of the list with the transition of point `i` (`undefined` and `linear` remove the field: the file stays short).\n * Копия списка с переходом точки `i` (`undefined` и `linear` убирают поле: файл остаётся коротким).\n */\nexport function setEase(points: readonly CurvePoint[], i: number, ease: Ease | undefined): CurvePoint[] {\n return points.map((p, k) => {\n if (k !== i) return { ...p };\n const { ease: _old, ...rest } = p;\n return ease === undefined || ease === 'linear' ? rest : { ...rest, ease };\n });\n}\n\n/**\n * Value limits for drawing: from 0 (or below the minimum) to the maximum with some headroom, no narrower than 0…1.\n * The given `min`/`max` (the field bounds) fix the view: the plot neither drifts nor leaves the allowed range.\n * Пределы значений для отрисовки: от 0 (или ниже минимума) до максимума с запасом, не уже чем 0…1.\n * Заданные `min`/`max` (границы поля) фиксируют вид: график не плывёт и не выходит за допустимое.\n */\nexport function valueBounds(points: readonly CurvePoint[], min?: number, max?: number): { min: number; max: number } {\n let lo = 0;\n let hi = 1;\n for (const p of points) {\n lo = Math.min(lo, p.v);\n hi = Math.max(hi, p.v);\n }\n // what goes beyond the point values (overshoot, handles): the field bounds are the allowed point values, but all of it has to be visible\n // то, что выходит за значения точек (заступ, ручки): границы поля это допустимые значения точек, а видеть это нужно всё\n let outLo = Infinity;\n let outHi = -Infinity;\n const see = (v: number) => {\n lo = Math.min(lo, v);\n hi = Math.max(hi, v);\n outLo = Math.min(outLo, v);\n outHi = Math.max(outHi, v);\n };\n // transitions with overshoot (back, elastic, Bezier) go beyond the point values: the view is chosen by the curve itself\n // переходы с заступом (back, elastic, Безье) выходят за значения точек: вид подбираем по самой кривой\n for (let i = 0; i < points.length - 1; i++) {\n const a = points[i]!;\n if (!curved(a.ease)) continue;\n // Bezier handles must fit the view too: otherwise a handle that went off the edge cannot be reached\n // ручки Безье тоже должны попадать в вид: иначе уехавшую за край ручку не достать\n if (typeof a.ease === 'object') {\n const dv = points[i + 1]!.v - a.v;\n for (const y of [a.ease.bezier[1], a.ease.bezier[3]]) see(a.v + y * dv);\n }\n for (const s of sampleSegment(points[i]!, points[i + 1]!)) see(s.v);\n }\n const auto = { min: lo, max: hi === lo ? lo + 1 : hi * 1.1 };\n // a given bound fixes the view, but overshoot and handles widen it: so they do not hide behind the edge\n // заданная граница фиксирует вид, но заступ и ручки её раздвигают: так они не прячутся за край\n const a = min === undefined ? auto.min : Math.min(min, outLo);\n const b = max === undefined ? auto.max : Math.max(max, outHi);\n return b > a ? { min: a, max: b } : { min: a, max: a + 1 };\n}\n"],"mappings":";;;;;;;AAyBA,SAAgB,YAAY,QAA+B,GAAmB;CAC1E,MAAM,IAAI,OAAO;CACjB,IAAI,MAAM,GAAG,OAAO;CACpB,MAAM,IAAI,QAAQ,CAAC;CACnB,IAAI,KAAK,OAAO,EAAE,CAAE,GAAG,OAAO,OAAO,EAAE,CAAE;CACzC,IAAI,KAAK,OAAO,IAAI,EAAE,CAAE,GAAG,OAAO,OAAO,IAAI,EAAE,CAAE;C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AAK,IAAI,IAAI,EAAE,CAAC;CACzB;CAGA,IAAI,QAAQ;CACZ,IAAI,QAAQ;CACZ,MAAM,OAAO,MAAc;EACvB,KAAK,KAAK,IAAI,IAAI,CAAC;EACnB,KAAK,KAAK,IAAI,IAAI,CAAC;EACnB,QAAQ,KAAK,IAAI,OAAO,CAAC;EACzB,QAAQ,KAAK,IAAI,OAAO,CAAC;CAC7B;CAGA,KAAK,IAAI,IAAI,GAAG,IAAI,OAAO,SAAS,GAAG,KAAK;EACxC,MAAM,IAAI,OAAO;EACjB,IAAI,CAAC,OAAO,EAAE,IAAI,GAAG;EAGrB,IAAI,OAAO,EAAE,SAAS,UAAU;GAC5B,MAAM,KAAK,OAAO,IAAI,EAAE,CAAE,IAAI,EAAE;GAChC,KAAK,MAAM,KAAK,CAAC,EAAE,KAAK,OAAO,IAAI,EAAE,KAAK,OAAO,EAAE,GAAG,IAAI,EAAE,IAAI,IAAI,EAAE;EAC1E;EACA,KAAK,MAAM,KAAK,cAAc,OAAO,IAAK,OAAO,IAAI,EAAG,GAAG,IAAI,EAAE,CAAC;CACtE;CACA,MAAM,OAAO;EAAE,KAAK;EAAI,KAAK,OAAO,KAAK,KAAK,IAAI,KAAK;CAAI;CAG3D,MAAM,IAAI,QAAQ,KAAA,IAAY,KAAK,MAAM,KAAK,IAAI,KAAK,KAAK;CAC5D,MAAM,IAAI,QAAQ,KAAA,IAAY,KAAK,MAAM,KAAK,IAAI,KAAK,KAAK;CAC5D,OAAO,IAAI,IAAI;EAAE,KAAK;EAAG,KAAK;CAAE,IAAI;EAAE,KAAK;EAAG,KAAK,IAAI;CAAE;AAC7D"}
package/dist/history.d.ts CHANGED
@@ -12,6 +12,23 @@ export declare const COALESCE_MS = 800;
12
12
  export interface HistoryState {
13
13
  states: readonly string[];
14
14
  index: number;
15
+ /**
16
+ * The label of the step that made each snapshot (the first has none), when the history has labels. A history saved before labels existed has none: it is put back unlabelled.
17
+ * Подпись шага, который сделал каждый снимок (у первого её нет), если в истории есть подписи. История, сохранённая до подписей, их не имеет: возвращается без подписей.
18
+ */
19
+ labels?: readonly (string | undefined)[];
20
+ /**
21
+ * The snapshot marked saved by `markSaved()`, when it is not the first one (so a history that never saved is the plain data it always was). Without it `restore` takes the first snapshot as the saved one.
22
+ * Снимок, отмеченный `markSaved()`, если это не первый снимок (так история, которая не сохранялась, остаётся теми же простыми данными). Без него `restore` считает сохранённым первый снимок.
23
+ */
24
+ saved?: string;
25
+ }
26
+ export interface HistoryOptions {
27
+ /**
28
+ * How long, ms, edits with one key merge. `Infinity`: until `seal()` or another key, however long the pause (an editor that ends a drag itself). Default `COALESCE_MS`.
29
+ * Сколько мс правки с одним ключом склеиваются. `Infinity`: до `seal()` или другого ключа, как бы долго ни длилась пауза (редактор, который сам заканчивает перетаскивание). По умолчанию `COALESCE_MS`.
30
+ */
31
+ coalesceMs?: number;
15
32
  }
16
33
  /**
17
34
  * Undo/redo state history: a linear list of snapshots and a pointer to the current one.
@@ -23,21 +40,53 @@ export declare class History {
23
40
  private readonly limit;
24
41
  private readonly now;
25
42
  private states;
43
+ private labels;
26
44
  private index;
27
45
  private lastKey;
28
46
  private lastTime;
29
- constructor(initial: string, limit?: number, now?: () => number);
47
+ private saved;
48
+ private readonly coalesceMs;
49
+ constructor(initial: string, limit?: number, now?: () => number, options?: HistoryOptions);
30
50
  get canUndo(): boolean;
31
51
  get canRedo(): boolean;
52
+ /**
53
+ * The label of the step an undo would take back, or undefined (nothing to undo, or the step has no label).
54
+ * Подпись шага, который отменит undo, или undefined (отменять нечего или у шага нет подписи).
55
+ */
56
+ get undoLabel(): string | undefined;
57
+ /**
58
+ * The label of the step a redo would bring back.
59
+ * Подпись шага, который вернёт redo.
60
+ */
61
+ get redoLabel(): string | undefined;
62
+ /**
63
+ * Whether the current snapshot differs from the one marked by `markSaved()` (the start, or the one `reset` began from). It follows the history: undoing back to the saved
64
+ * snapshot is clean again.
65
+ * Отличается ли текущий снимок от отмеченного `markSaved()` (начального или того, с которого начал `reset`). Следует за историей: откат до сохранённого снимка снова чист.
66
+ */
67
+ get dirty(): boolean;
68
+ /**
69
+ * Marks the current snapshot as the saved one.
70
+ * Отмечает текущий снимок сохранённым.
71
+ */
72
+ markSaved(): void;
73
+ /**
74
+ * Ends a series of merged edits: the next edit with the same key is a new step. An editor that knows where a gesture ends (a pointer was released, a field lost focus) calls it
75
+ * there; one that does not leaves it to the time window.
76
+ * Заканчивает серию склеенных правок: следующая правка с тем же ключом это новый шаг. Редактор, который знает, где кончается жест (отпустили указатель, поле потеряло фокус),
77
+ * зовёт его там; тот, кто не знает, оставляет это окну времени.
78
+ */
79
+ seal(): void;
32
80
  /**
33
81
  * Records a new state. If it does not differ from the current one, does nothing (returns false).
34
82
  * An edit discards the "future" (redo). With the same `key` in a row and within `COALESCE_MS`,
35
83
  * edits replace each other instead of piling up.
36
84
  * Записывает новое состояние. Если оно не отличается от текущего, ничего не делает (вернёт false).
37
85
  * Правка отбрасывает «будущее» (redo). С одинаковым `key` подряд и в пределах `COALESCE_MS`
38
- * правки заменяют друг друга, а не копятся.
86
+ * правки заменяют друг друга, а не копятся. `label` называет шаг (для «Отменить: …»); у склеенной серии подпись первой правки.
87
+ * The `label` names the step (for "Undo: …"); a merged series keeps the label of its first edit.
39
88
  */
40
- commit(state: string, key?: string): boolean;
89
+ commit(state: string, key?: string, label?: string): boolean;
41
90
  /**
42
91
  * Returns the previous state, or null if there is nothing to undo.
43
92
  * Возвращает предыдущее состояние или null, если отменять нечего.
package/dist/history.js CHANGED
@@ -14,13 +14,18 @@ var History = class {
14
14
  limit;
15
15
  now;
16
16
  states;
17
+ labels = [void 0];
17
18
  index = 0;
18
19
  lastKey;
19
20
  lastTime = 0;
20
- constructor(initial, limit = 100, now = Date.now) {
21
+ saved;
22
+ coalesceMs;
23
+ constructor(initial, limit = 100, now = Date.now, options = {}) {
21
24
  this.limit = limit;
22
25
  this.now = now;
23
26
  this.states = [initial];
27
+ this.saved = initial;
28
+ this.coalesceMs = options.coalesceMs ?? 800;
24
29
  }
25
30
  get canUndo() {
26
31
  return this.index > 0;
@@ -29,29 +34,72 @@ var History = class {
29
34
  return this.index < this.states.length - 1;
30
35
  }
31
36
  /**
37
+ * The label of the step an undo would take back, or undefined (nothing to undo, or the step has no label).
38
+ * Подпись шага, который отменит undo, или undefined (отменять нечего или у шага нет подписи).
39
+ */
40
+ get undoLabel() {
41
+ return this.canUndo ? this.labels[this.index] : void 0;
42
+ }
43
+ /**
44
+ * The label of the step a redo would bring back.
45
+ * Подпись шага, который вернёт redo.
46
+ */
47
+ get redoLabel() {
48
+ return this.canRedo ? this.labels[this.index + 1] : void 0;
49
+ }
50
+ /**
51
+ * Whether the current snapshot differs from the one marked by `markSaved()` (the start, or the one `reset` began from). It follows the history: undoing back to the saved
52
+ * snapshot is clean again.
53
+ * Отличается ли текущий снимок от отмеченного `markSaved()` (начального или того, с которого начал `reset`). Следует за историей: откат до сохранённого снимка снова чист.
54
+ */
55
+ get dirty() {
56
+ return this.states[this.index] !== this.saved;
57
+ }
58
+ /**
59
+ * Marks the current snapshot as the saved one.
60
+ * Отмечает текущий снимок сохранённым.
61
+ */
62
+ markSaved() {
63
+ this.saved = this.states[this.index];
64
+ }
65
+ /**
66
+ * Ends a series of merged edits: the next edit with the same key is a new step. An editor that knows where a gesture ends (a pointer was released, a field lost focus) calls it
67
+ * there; one that does not leaves it to the time window.
68
+ * Заканчивает серию склеенных правок: следующая правка с тем же ключом это новый шаг. Редактор, который знает, где кончается жест (отпустили указатель, поле потеряло фокус),
69
+ * зовёт его там; тот, кто не знает, оставляет это окну времени.
70
+ */
71
+ seal() {
72
+ this.lastKey = void 0;
73
+ }
74
+ /**
32
75
  * Records a new state. If it does not differ from the current one, does nothing (returns false).
33
76
  * An edit discards the "future" (redo). With the same `key` in a row and within `COALESCE_MS`,
34
77
  * edits replace each other instead of piling up.
35
78
  * Записывает новое состояние. Если оно не отличается от текущего, ничего не делает (вернёт false).
36
79
  * Правка отбрасывает «будущее» (redo). С одинаковым `key` подряд и в пределах `COALESCE_MS`
37
- * правки заменяют друг друга, а не копятся.
80
+ * правки заменяют друг друга, а не копятся. `label` называет шаг (для «Отменить: …»); у склеенной серии подпись первой правки.
81
+ * The `label` names the step (for "Undo: …"); a merged series keeps the label of its first edit.
38
82
  */
39
- commit(state, key) {
83
+ commit(state, key, label) {
40
84
  if (state === this.states[this.index]) return false;
41
85
  const t = this.now();
42
86
  const atTop = this.index === this.states.length - 1;
43
- if (key !== void 0 && key === this.lastKey && t - this.lastTime <= 800 && this.index > 0 && atTop) {
87
+ if (key !== void 0 && key === this.lastKey && t - this.lastTime <= this.coalesceMs && this.index > 0 && atTop) {
44
88
  this.states[this.index] = state;
45
89
  if (this.states[this.index - 1] === state) {
46
90
  this.states.pop();
91
+ this.labels.pop();
47
92
  this.index--;
48
93
  }
49
94
  } else {
50
95
  this.states.length = this.index + 1;
96
+ this.labels.length = this.index + 1;
51
97
  this.states.push(state);
98
+ this.labels.push(label);
52
99
  this.index++;
53
100
  if (this.states.length > this.limit + 1) {
54
101
  this.states.shift();
102
+ this.labels.shift();
55
103
  this.index--;
56
104
  }
57
105
  }
@@ -78,10 +126,18 @@ var History = class {
78
126
  * Копия всей истории (снимки и положение), чтобы вернуть её через `restore`.
79
127
  */
80
128
  save() {
81
- return {
129
+ const state = {
82
130
  states: [...this.states],
83
131
  index: this.index
84
132
  };
133
+ const withLabels = this.labels.some((l) => l !== void 0) ? {
134
+ ...state,
135
+ labels: [...this.labels]
136
+ } : state;
137
+ return this.saved !== this.states[0] ? {
138
+ ...withLabels,
139
+ saved: this.saved
140
+ } : withLabels;
85
141
  }
86
142
  /**
87
143
  * Puts a saved history back. The current snapshot of it should be the state of the document the app shows now;
@@ -93,7 +149,9 @@ var History = class {
93
149
  restore(state) {
94
150
  if (!Number.isInteger(state.index) || state.index < 0 || state.index >= state.states.length) throw new RangeError("History.restore: the position is outside the saved snapshots");
95
151
  this.states = [...state.states];
152
+ this.labels = state.states.map((_, i) => state.labels?.[i] ?? void 0);
96
153
  this.index = state.index;
154
+ this.saved = state.saved ?? state.states[0];
97
155
  this.lastKey = void 0;
98
156
  }
99
157
  /**
@@ -102,6 +160,8 @@ var History = class {
102
160
  */
103
161
  reset(state) {
104
162
  this.states = [state];
163
+ this.labels = [void 0];
164
+ this.saved = state;
105
165
  this.index = 0;
106
166
  this.lastKey = void 0;
107
167
  }