@1337exp/taoux 0.8.0 → 0.9.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>\r\nimport { TaoButton, TaoInputNumber, TaoSegmented, TaoSegmentedOption, TaoSelect, TaoSwitch } from '@1337exp/taoui';\r\nimport { computed, ref } from 'vue';\r\nimport { movePoint, removePoint, setEase, TaoxCurveEditor, valueBounds, type CurveGuides, type CurvePoint } from '../curveeditor';\r\nimport { DEFAULT_BEZIER, EASE_DIRECTIONS, EASE_FAMILIES, easeName, easeParts, type Ease, type EaseDirection, type EaseFamily } from '../ease';\r\nimport { clampTo, niceStep, roundTo } from '../num';\r\nimport type { CurveFieldLabels } from './labels';\r\n\r\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.\r\n// The first taoux module on top of TaoUI: the plot and the logic stay in taoux, the fields and buttons are TaoUI components.\r\n// Кривая с полями: график (TaoxCurveEditor), поля выбранной точки, переход к следующей точке, шаг сетки, удаление и сброс.\r\n// Первый модуль taoux поверх TaoUI: график и логика остаются в taoux, поля и кнопки это компоненты TaoUI.\r\nconst props = withDefaults(\r\n defineProps<{\r\n /**\r\n * Curve points.\r\n * Точки кривой.\r\n */\r\n modelValue: readonly CurvePoint[];\r\n /**\r\n * Allowed values: they fix the plot view and do not let a point be dragged past the bound.\r\n * Допустимые значения: фиксируют вид графика и не дают утащить точку за границу.\r\n */\r\n min?: number;\r\n max?: number;\r\n /**\r\n * The \"default\" curve: without it there is no reset button.\r\n * Кривая «по умолчанию»: без неё кнопки сброса нет.\r\n */\r\n defaultValue?: readonly CurvePoint[];\r\n /**\r\n * How many decimals to keep in time and value; not set means do not round.\r\n * Сколько знаков после запятой оставлять у времени и значения; не задано — не обрезать.\r\n */\r\n precision?: number;\r\n /**\r\n * The time step of the grid and of the time field.\r\n * Шаг по времени у сетки и у поля времени.\r\n */\r\n stepT?: number;\r\n /**\r\n * Snapping to the grid at start.\r\n * Прилипание к сетке при старте.\r\n */\r\n snap?: boolean;\r\n /**\r\n * Labels in the app language; missing ones fall back to English.\r\n * Надписи на языке приложения; недостающие берутся английские.\r\n */\r\n labels?: Partial<CurveFieldLabels>;\r\n /**\r\n * Guides from the selected point to the axes: `off`, `lines` (default) or `values`.\r\n * Направляющие от выбранной точки к осям: `off`, `lines` (по умолчанию) или `values`.\r\n */\r\n guides?: CurveGuides;\r\n /**\r\n * Labels for screen readers: see TaoxCurveEditor.\r\n * Подписи для скринридеров: см. TaoxCurveEditor.\r\n */\r\n pointLabel?: (index: number, point: CurvePoint) => string;\r\n handleLabel?: (n: number, index: number) => string;\r\n }>(),\r\n { stepT: 0.05, snap: true, guides: 'lines' },\r\n);\r\nconst emit = defineEmits<{ 'update:modelValue': [value: CurvePoint[]]; commit: [] }>();\r\n\r\nconst DEFAULT_LABELS: CurveFieldLabels = {\r\n time: 'Time',\r\n value: 'Value',\r\n transition: 'Transition to the next point',\r\n snap: 'Snap to grid',\r\n remove: 'Remove',\r\n reset: 'Reset',\r\n hint: 'Double-click adds a point, Alt+click or Delete removes it, Shift disables snapping',\r\n};\r\nconst text = computed(() => ({ ...DEFAULT_LABELS, ...props.labels }));\r\n\r\nconst selected = ref(0);\r\nconst snapOn = ref(props.snap);\r\n\r\nconst points = computed(() => props.modelValue.map((p) => ({ ...p })));\r\nconst current = computed(() => points.value[Math.min(selected.value, points.value.length - 1)]!);\r\nconst stepV = computed(() => {\r\n const b = valueBounds(points.value, props.min, props.max);\r\n return niceStep(b.max - b.min, 20);\r\n});\r\nconst canReset = computed(() => props.defaultValue !== undefined && JSON.stringify(points.value) !== JSON.stringify(props.defaultValue));\r\n\r\nfunction change(next: CurvePoint[]) {\r\n emit('update:modelValue', next);\r\n}\r\n\r\nfunction removeSelected() {\r\n change(removePoint(points.value, selected.value));\r\n selected.value = 0;\r\n emit('commit');\r\n}\r\n\r\nfunction setField(field: 't' | 'v', value: number | null) {\r\n if (value === null || !Number.isFinite(value)) return;\r\n const p = current.value;\r\n const tt = field === 't' ? roundTo(value, props.precision) : p.t;\r\n const v = field === 'v' ? clampTo(roundTo(value, props.precision), props.min, props.max) : p.v;\r\n change(movePoint(points.value, selected.value, tt, v));\r\n emit('commit');\r\n}\r\n\r\nfunction reset() {\r\n if (props.defaultValue === undefined) return;\r\n selected.value = 0;\r\n change(props.defaultValue.map((p) => ({ ...p })));\r\n emit('commit');\r\n}\r\n\r\n//--------------------------------------------------\r\n// The transition from the selected point to the next: the kind (linear, step, a family or bezier) and the direction.\r\n// Function names are not translated: they are known from CSS and animation libraries and would not be found by a translation.\r\n// Переход от выбранной точки к следующей: вид (linear, step, семейство или bezier) и направление.\r\n// Названия функций не переводятся: их знают по CSS и библиотекам анимации, по переводу не найдут.\r\n\r\nconst isLast = computed(() => selected.value >= points.value.length - 1);\r\nconst kind = computed(() => {\r\n const e = current.value.ease;\r\n if (e === undefined || e === 'linear') return 'linear';\r\n if (typeof e === 'object') return 'bezier';\r\n return easeParts(e)?.family ?? e;\r\n});\r\nconst direction = computed<EaseDirection>(() => {\r\n const e = current.value.ease;\r\n return typeof e === 'string' ? (easeParts(e)?.direction ?? 'in-out') : 'in-out';\r\n});\r\n// linear, step and Bezier have no direction: the switch stays in place, inactive, so that it is visible how this works\r\n// У linear, step и Безье направления нет: переключатель остаётся на месте неактивным, чтобы было видно, как это устроено\r\nconst hasDirection = computed(() => !isLast.value && typeof current.value.ease === 'string' && easeParts(current.value.ease) !== null);\r\nconst kindOptions = ['linear', 'step', ...EASE_FAMILIES, 'bezier'].map((v) => ({ value: v, label: v }));\r\n\r\nfunction applyEase(next: Ease) {\r\n change(setEase(points.value, selected.value, next));\r\n emit('commit');\r\n}\r\n\r\nfunction setKind(v: string | number | null) {\r\n if (typeof v !== 'string') return;\r\n if (v === 'linear' || v === 'step') applyEase(v);\r\n else if (v === 'bezier') applyEase({ bezier: DEFAULT_BEZIER });\r\n else applyEase(easeName(v as EaseFamily, direction.value));\r\n}\r\n\r\nfunction setDirection(v: unknown) {\r\n const e = current.value.ease;\r\n const parts = typeof e === 'string' ? easeParts(e) : null;\r\n if (parts && typeof v === 'string' && (EASE_DIRECTIONS as readonly string[]).includes(v)) applyEase(easeName(parts.family, v as EaseDirection));\r\n}\r\n</script>\r\n\r\n<template>\r\n <div class=\"tx-curve-field\">\r\n <TaoxCurveEditor\r\n :model-value=\"points\"\r\n v-model:selected=\"selected\"\r\n :min=\"min\"\r\n :max=\"max\"\r\n :precision=\"precision\"\r\n :snap=\"snapOn\"\r\n :step-t=\"stepT\"\r\n :hint=\"text.hint\"\r\n :guides=\"guides\"\r\n :point-label=\"pointLabel\"\r\n :handle-label=\"handleLabel\"\r\n @update:model-value=\"change\"\r\n @commit=\"emit('commit')\"\r\n />\r\n\r\n <div class=\"tx-curve-field__fields\">\r\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>\r\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>\r\n </div>\r\n\r\n <div class=\"tx-curve-field__ease\">\r\n <span class=\"tx-curve-field__title\" aria-hidden=\"true\">{{ text.transition }}</span>\r\n <div class=\"tx-curve-field__ease-row\" role=\"group\" :aria-label=\"text.transition\">\r\n <TaoSelect class=\"tx-curve-field__kind\" size=\"small\" :clearable=\"false\" :options=\"kindOptions\" :disabled=\"isLast\" :model-value=\"kind\" @update:model-value=\"setKind\" />\r\n <TaoSegmented size=\"small\" :disabled=\"!hasDirection\" :model-value=\"hasDirection ? direction : undefined\" @update:model-value=\"setDirection\">\r\n <TaoSegmentedOption v-for=\"d in EASE_DIRECTIONS\" :key=\"d\" :value=\"d\" :label=\"d\" />\r\n </TaoSegmented>\r\n </div>\r\n </div>\r\n\r\n <div class=\"tx-curve-field__bar\">\r\n <TaoSwitch v-model=\"snapOn\" :label=\"text.snap\" />\r\n <span class=\"tx-curve-field__spacer\" />\r\n <TaoButton size=\"small\" variant=\"ghost\" :disabled=\"points.length <= 2\" @click=\"removeSelected\">{{ text.remove }}</TaoButton>\r\n <TaoButton v-if=\"defaultValue !== undefined\" size=\"small\" variant=\"ghost\" :disabled=\"!canReset\" @click=\"reset\">{{ text.reset }}</TaoButton>\r\n </div>\r\n </div>\r\n</template>\r\n\r\n<style scoped>\r\n.tx-curve-field {\r\n --tx-curve-bg: var(--tao-color-surface-sunken);\r\n --tx-curve-border: var(--tao-color-border);\r\n --tx-curve-grid: var(--tao-color-border);\r\n --tx-curve-label: var(--tao-color-text-muted);\r\n --tx-curve-text: var(--tao-color-text);\r\n --tx-curve-accent: var(--tao-color-accent);\r\n\r\n display: flex;\r\n flex-direction: column;\r\n gap: 8px;\r\n}\r\n\r\n.tx-curve-field__fields {\r\n display: grid;\r\n grid-template-columns: 1fr 1fr;\r\n gap: 8px;\r\n}\r\n\r\n.tx-curve-field__fields > label {\r\n display: flex;\r\n flex-direction: column;\r\n gap: 2px;\r\n color: var(--tao-color-text-muted);\r\n font-size: 11px;\r\n}\r\n\r\n.tx-curve-field__ease {\r\n display: flex;\r\n flex-direction: column;\r\n gap: 2px;\r\n}\r\n\r\n.tx-curve-field__title {\r\n color: var(--tao-color-text-muted);\r\n font-size: 11px;\r\n}\r\n\r\n/* The list and the direction in one row: the list takes the rest, the switch keeps its own width / Список и направление в одну строку: список забирает остаток, переключатель держит свою ширину */\r\n.tx-curve-field__ease-row {\r\n display: flex;\r\n align-items: center;\r\n gap: 6px;\r\n}\r\n\r\n.tx-curve-field__kind {\r\n flex: 1;\r\n min-width: 0;\r\n}\r\n\r\n.tx-curve-field__ease-row > :last-child {\r\n flex: none;\r\n}\r\n\r\n.tx-curve-field__bar {\r\n display: flex;\r\n align-items: center;\r\n gap: 4px;\r\n font-size: 12px;\r\n}\r\n\r\n.tx-curve-field__spacer {\r\n flex: 1;\r\n}\r\n</style>\r\n","<script lang=\"ts\" setup>\r\nimport { TaoButton, TaoInputNumber, TaoSegmented, TaoSegmentedOption, TaoSelect, TaoSwitch } from '@1337exp/taoui';\r\nimport { computed, ref } from 'vue';\r\nimport { movePoint, removePoint, setEase, TaoxCurveEditor, valueBounds, type CurveGuides, type CurvePoint } from '../curveeditor';\r\nimport { DEFAULT_BEZIER, EASE_DIRECTIONS, EASE_FAMILIES, easeName, easeParts, type Ease, type EaseDirection, type EaseFamily } from '../ease';\r\nimport { clampTo, niceStep, roundTo } from '../num';\r\nimport type { CurveFieldLabels } from './labels';\r\n\r\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.\r\n// The first taoux module on top of TaoUI: the plot and the logic stay in taoux, the fields and buttons are TaoUI components.\r\n// Кривая с полями: график (TaoxCurveEditor), поля выбранной точки, переход к следующей точке, шаг сетки, удаление и сброс.\r\n// Первый модуль taoux поверх TaoUI: график и логика остаются в taoux, поля и кнопки это компоненты TaoUI.\r\nconst props = withDefaults(\r\n defineProps<{\r\n /**\r\n * Curve points.\r\n * Точки кривой.\r\n */\r\n modelValue: readonly CurvePoint[];\r\n /**\r\n * Allowed values: they fix the plot view and do not let a point be dragged past the bound.\r\n * Допустимые значения: фиксируют вид графика и не дают утащить точку за границу.\r\n */\r\n min?: number;\r\n max?: number;\r\n /**\r\n * The \"default\" curve: without it there is no reset button.\r\n * Кривая «по умолчанию»: без неё кнопки сброса нет.\r\n */\r\n defaultValue?: readonly CurvePoint[];\r\n /**\r\n * How many decimals to keep in time and value; not set means do not round.\r\n * Сколько знаков после запятой оставлять у времени и значения; не задано — не обрезать.\r\n */\r\n precision?: number;\r\n /**\r\n * The time step of the grid and of the time field.\r\n * Шаг по времени у сетки и у поля времени.\r\n */\r\n stepT?: number;\r\n /**\r\n * Snapping to the grid at start.\r\n * Прилипание к сетке при старте.\r\n */\r\n snap?: boolean;\r\n /**\r\n * Labels in the app language; missing ones fall back to English.\r\n * Надписи на языке приложения; недостающие берутся английские.\r\n */\r\n labels?: Partial<CurveFieldLabels>;\r\n /**\r\n * Guides from the selected point to the axes: `off`, `lines` (default) or `values`.\r\n * Направляющие от выбранной точки к осям: `off`, `lines` (по умолчанию) или `values`.\r\n */\r\n guides?: CurveGuides;\r\n /**\r\n * Labels for screen readers: see TaoxCurveEditor.\r\n * Подписи для скринридеров: см. TaoxCurveEditor.\r\n */\r\n pointLabel?: (index: number, point: CurvePoint) => string;\r\n handleLabel?: (n: number, index: number) => string;\r\n }>(),\r\n { stepT: 0.05, snap: true, guides: 'lines' },\r\n);\r\nconst emit = defineEmits<{ 'update:modelValue': [value: CurvePoint[]]; commit: [] }>();\r\n\r\nconst DEFAULT_LABELS: CurveFieldLabels = {\r\n time: 'Time',\r\n value: 'Value',\r\n transition: 'Transition to the next point',\r\n snap: 'Snap to grid',\r\n remove: 'Remove',\r\n reset: 'Reset',\r\n hint: 'Double-click adds a point, Alt+click or Delete removes it, Shift disables snapping',\r\n};\r\nconst text = computed(() => ({ ...DEFAULT_LABELS, ...props.labels }));\r\n\r\nconst selected = ref(0);\r\nconst snapOn = ref(props.snap);\r\n\r\nconst points = computed(() => props.modelValue.map((p) => ({ ...p })));\r\nconst current = computed(() => points.value[Math.min(selected.value, points.value.length - 1)]!);\r\nconst stepV = computed(() => {\r\n const b = valueBounds(points.value, props.min, props.max);\r\n return niceStep(b.max - b.min, 20);\r\n});\r\nconst canReset = computed(() => props.defaultValue !== undefined && JSON.stringify(points.value) !== JSON.stringify(props.defaultValue));\r\n\r\nfunction change(next: CurvePoint[]) {\r\n emit('update:modelValue', next);\r\n}\r\n\r\nfunction removeSelected() {\r\n change(removePoint(points.value, selected.value));\r\n selected.value = 0;\r\n emit('commit');\r\n}\r\n\r\nfunction setField(field: 't' | 'v', value: number | null) {\r\n if (value === null || !Number.isFinite(value)) return;\r\n const p = current.value;\r\n const tt = field === 't' ? roundTo(value, props.precision) : p.t;\r\n const v = field === 'v' ? clampTo(roundTo(value, props.precision), props.min, props.max) : p.v;\r\n change(movePoint(points.value, selected.value, tt, v));\r\n emit('commit');\r\n}\r\n\r\nfunction reset() {\r\n if (props.defaultValue === undefined) return;\r\n selected.value = 0;\r\n change(props.defaultValue.map((p) => ({ ...p })));\r\n emit('commit');\r\n}\r\n\r\n//--------------------------------------------------\r\n// The transition from the selected point to the next: the kind (linear, step, a family or bezier) and the direction.\r\n// Function names are not translated: they are known from CSS and animation libraries and would not be found by a translation.\r\n// Переход от выбранной точки к следующей: вид (linear, step, семейство или bezier) и направление.\r\n// Названия функций не переводятся: их знают по CSS и библиотекам анимации, по переводу не найдут.\r\n\r\nconst isLast = computed(() => selected.value >= points.value.length - 1);\r\nconst kind = computed(() => {\r\n const e = current.value.ease;\r\n if (e === undefined || e === 'linear') return 'linear';\r\n if (typeof e === 'object') return 'bezier';\r\n return easeParts(e)?.family ?? e;\r\n});\r\nconst direction = computed<EaseDirection>(() => {\r\n const e = current.value.ease;\r\n return typeof e === 'string' ? (easeParts(e)?.direction ?? 'in-out') : 'in-out';\r\n});\r\n// linear, step and Bezier have no direction: the switch stays in place, inactive, so that it is visible how this works\r\n// У linear, step и Безье направления нет: переключатель остаётся на месте неактивным, чтобы было видно, как это устроено\r\nconst hasDirection = computed(() => !isLast.value && typeof current.value.ease === 'string' && easeParts(current.value.ease) !== null);\r\nconst kindOptions = ['linear', 'step', ...EASE_FAMILIES, 'bezier'].map((v) => ({ value: v, label: v }));\r\n\r\nfunction applyEase(next: Ease) {\r\n change(setEase(points.value, selected.value, next));\r\n emit('commit');\r\n}\r\n\r\nfunction setKind(v: string | number | null) {\r\n if (typeof v !== 'string') return;\r\n if (v === 'linear' || v === 'step') applyEase(v);\r\n else if (v === 'bezier') applyEase({ bezier: DEFAULT_BEZIER });\r\n else applyEase(easeName(v as EaseFamily, direction.value));\r\n}\r\n\r\nfunction setDirection(v: unknown) {\r\n const e = current.value.ease;\r\n const parts = typeof e === 'string' ? easeParts(e) : null;\r\n if (parts && typeof v === 'string' && (EASE_DIRECTIONS as readonly string[]).includes(v)) applyEase(easeName(parts.family, v as EaseDirection));\r\n}\r\n</script>\r\n\r\n<template>\r\n <div class=\"tx-curve-field\">\r\n <TaoxCurveEditor\r\n :model-value=\"points\"\r\n v-model:selected=\"selected\"\r\n :min=\"min\"\r\n :max=\"max\"\r\n :precision=\"precision\"\r\n :snap=\"snapOn\"\r\n :step-t=\"stepT\"\r\n :hint=\"text.hint\"\r\n :guides=\"guides\"\r\n :point-label=\"pointLabel\"\r\n :handle-label=\"handleLabel\"\r\n @update:model-value=\"change\"\r\n @commit=\"emit('commit')\"\r\n />\r\n\r\n <div class=\"tx-curve-field__fields\">\r\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>\r\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>\r\n </div>\r\n\r\n <div class=\"tx-curve-field__ease\">\r\n <span class=\"tx-curve-field__title\" aria-hidden=\"true\">{{ text.transition }}</span>\r\n <div class=\"tx-curve-field__ease-row\" role=\"group\" :aria-label=\"text.transition\">\r\n <TaoSelect class=\"tx-curve-field__kind\" size=\"small\" :clearable=\"false\" :options=\"kindOptions\" :disabled=\"isLast\" :model-value=\"kind\" @update:model-value=\"setKind\" />\r\n <TaoSegmented size=\"small\" :disabled=\"!hasDirection\" :model-value=\"hasDirection ? direction : undefined\" @update:model-value=\"setDirection\">\r\n <TaoSegmentedOption v-for=\"d in EASE_DIRECTIONS\" :key=\"d\" :value=\"d\" :label=\"d\" />\r\n </TaoSegmented>\r\n </div>\r\n </div>\r\n\r\n <div class=\"tx-curve-field__bar\">\r\n <TaoSwitch v-model=\"snapOn\" :label=\"text.snap\" />\r\n <span class=\"tx-curve-field__spacer\" />\r\n <TaoButton size=\"small\" variant=\"ghost\" :disabled=\"points.length <= 2\" @click=\"removeSelected\">{{ text.remove }}</TaoButton>\r\n <TaoButton v-if=\"defaultValue !== undefined\" size=\"small\" variant=\"ghost\" :disabled=\"!canReset\" @click=\"reset\">{{ text.reset }}</TaoButton>\r\n </div>\r\n </div>\r\n</template>\r\n\r\n<style scoped>\r\n.tx-curve-field {\r\n --tx-curve-bg: var(--tao-color-surface-sunken);\r\n --tx-curve-border: var(--tao-color-border);\r\n --tx-curve-grid: var(--tao-color-border);\r\n --tx-curve-label: var(--tao-color-text-muted);\r\n --tx-curve-text: var(--tao-color-text);\r\n --tx-curve-accent: var(--tao-color-accent);\r\n\r\n display: flex;\r\n flex-direction: column;\r\n gap: 8px;\r\n}\r\n\r\n.tx-curve-field__fields {\r\n display: grid;\r\n grid-template-columns: 1fr 1fr;\r\n gap: 8px;\r\n}\r\n\r\n.tx-curve-field__fields > label {\r\n display: flex;\r\n flex-direction: column;\r\n gap: 2px;\r\n color: var(--tao-color-text-muted);\r\n font-size: 11px;\r\n}\r\n\r\n.tx-curve-field__ease {\r\n display: flex;\r\n flex-direction: column;\r\n gap: 2px;\r\n}\r\n\r\n.tx-curve-field__title {\r\n color: var(--tao-color-text-muted);\r\n font-size: 11px;\r\n}\r\n\r\n/* The list and the direction in one row: the list takes the rest, the switch keeps its own width / Список и направление в одну строку: список забирает остаток, переключатель держит свою ширину */\r\n.tx-curve-field__ease-row {\r\n display: flex;\r\n align-items: center;\r\n gap: 6px;\r\n}\r\n\r\n.tx-curve-field__kind {\r\n flex: 1;\r\n min-width: 0;\r\n}\r\n\r\n.tx-curve-field__ease-row > :last-child {\r\n flex: none;\r\n}\r\n\r\n.tx-curve-field__bar {\r\n display: flex;\r\n align-items: center;\r\n gap: 4px;\r\n font-size: 12px;\r\n}\r\n\r\n.tx-curve-field__spacer {\r\n flex: 1;\r\n}\r\n</style>\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAYA,MAAM,QAAQ;EAoDd,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,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Q,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"}
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 { 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 @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 { 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 @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: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;;MAA9F,MAAK;MAAQ,SAAQ;MAAS,UAAQ,CAAG,SAAA;MAAW,SAAO;;MAAO,SAAAK,cAAgB,CAAbF,gBAAAC,gBAAA,KAAA,MAAK,KAAK,GAAA,CAAA,C"}
@@ -2,14 +2,16 @@
2
2
  /*
3
3
  * Configured with CSS variables on any ancestor:
4
4
  * Настройка через CSS-переменные на любом предке:
5
- * --tx-gradient-border, --tx-gradient-stop-border, --tx-gradient-stop-outline, --tx-gradient-accent.
5
+ * --tx-gradient-border, --tx-gradient-stop-border, --tx-gradient-stop-outline, --tx-gradient-accent,
6
+ * --tx-gradient-radius (the corners of the bar, 4px by default).
7
+ * --tx-gradient-radius — углы полосы, по умолчанию 4px.
6
8
  */
7
9
  .tx-gradient {
8
10
  position: relative;
9
11
  height: 22px;
10
12
  margin-bottom: 20px; /* room for the stop handles and the mark of the selected one / место под ручки остановок и отметку выбранной */
11
13
  border: 1px solid var(--tx-gradient-border, #2a2d33);
12
- border-radius: 4px;
14
+ border-radius: var(--tx-gradient-radius, 4px);
13
15
  /* a checkerboard under the bar shows transparency / шахматка под полосой показывает прозрачность */
14
16
  background-color: #fff;
15
17
  background-size: 100% 100%, 12px 12px;
@@ -1 +1 @@
1
- {"version":3,"file":"gradienteditor.js","names":["_openBlock","_createElementBlock","_normalizeStyle","_unref","_Fragment","_renderList","_normalizeClass","_withModifiers","_createElementVNode","_sfc_main"],"sources":["../src/gradienteditor/ops.ts","../src/gradienteditor/TaoxGradientEditor.vue","../src/gradienteditor/TaoxGradientEditor.vue"],"sourcesContent":["import { clamp01, roundTo } from '../num';\r\n\r\n/**\r\n * A gradient stop: t in 0…1, colour in linear RGB 0…1 (not sRGB), alpha 0…1.\r\n * Linear colour is what rendering needs; for the CSS preview bar it is converted to sRGB (`gradientCss`).\r\n * Остановка градиента: t в 0…1, цвет в линейном RGB 0…1 (не sRGB), alpha 0…1.\r\n * Линейный цвет нужен рендеру; в CSS-полоску он переводится в sRGB (`gradientCss`).\r\n */\r\nexport interface GradientStop {\r\n t: number;\r\n color: [number, number, number];\r\n alpha: number;\r\n}\r\n\r\n\r\nconst copy = (stops: readonly GradientStop[]): GradientStop[] => stops.map((s) => ({ ...s, color: [...s.color] as GradientStop['color'] }));\r\n\r\n/**\r\n * Default decimals of t and opacity: \"0.5700000000000001\" in a file is of use to nobody.\r\n * Знаков после запятой по умолчанию у t и непрозрачности: «0.5700000000000001» в файле никому не нужно.\r\n */\r\nexport const DEFAULT_PRECISION = 3;\r\n\r\n/**\r\n * Decimals of the colour components for a given `precision` of t and opacity. The colour is linear, and in the dark part of the scale sRGB rises steeply\r\n * (a linear step of 0.001 is 3 levels out of 255), so two more decimals are needed here: five when t has three.\r\n * Знаков у компонент цвета при `precision` у t и непрозрачности. Цвет линейный, а в тёмной части шкалы sRGB круто растёт\r\n * (шаг 0.001 линейного это 3 уровня из 255), поэтому тут нужно на два знака больше: при трёх у t это пять.\r\n */\r\nexport const colorDigits = (precision: number | null): number | null => (precision === null ? null : precision + 2);\r\n\r\n/**\r\n * Opacity 0…1 with `digits` decimals (three by default).\r\n * Непрозрачность 0…1 с `digits` знаками (по умолчанию три).\r\n */\r\nexport const roundAlpha = (a: number, digits: number | null = DEFAULT_PRECISION): number => roundTo(Math.min(1, Math.max(0, a)), digits);\r\n\r\n/**\r\n * Changes stop `i`; t and opacity are rounded to `precision` decimals (three by default; `null` turns it off), the colour to `precision + 2`.\r\n * Меняет остановку `i`; t и непрозрачность округляются до `precision` знаков (по умолчанию три; `null` отключает), цвет до `precision + 2`.\r\n */\r\nexport function patchStop(stops: readonly GradientStop[], i: number, patch: Partial<GradientStop>, precision: number | null = DEFAULT_PRECISION): GradientStop[] {\r\n const next = copy(stops);\r\n const stop = { ...next[i]!, ...patch };\r\n stop.alpha = roundAlpha(stop.alpha, precision);\r\n stop.t = roundTo(Math.min(1, Math.max(0, stop.t)), precision);\r\n stop.color = stop.color.map((c) => roundTo(c, colorDigits(precision))) as GradientStop['color'];\r\n next[i] = stop;\r\n return next;\r\n}\r\n\r\n/**\r\n * The colour and opacity of the gradient at t: linear between stops, equal to the end stop beyond the ends. Returns [r, g, b, a].\r\n * Цвет и непрозрачность градиента в t: линейно между остановками, за краями равны крайней. Возвращает [r, g, b, a].\r\n */\r\nexport function sampleGradient(stops: readonly GradientStop[], t: number): [number, number, number, number] {\r\n const n = stops.length;\r\n if (n === 0) return [1, 1, 1, 1];\r\n const x = clamp01(t);\r\n let a = stops[0]!;\r\n let b = stops[0]!;\r\n let k = 0;\r\n if (x >= stops[n - 1]!.t) {\r\n a = b = stops[n - 1]!;\r\n } else if (x > stops[0]!.t) {\r\n for (let i = 1; i < n; i++) {\r\n if (x <= stops[i]!.t) {\r\n a = stops[i - 1]!;\r\n b = stops[i]!;\r\n const span = b.t - a.t;\r\n k = span <= 0 ? 1 : (x - a.t) / span;\r\n break;\r\n }\r\n }\r\n }\r\n return [\r\n a.color[0] + (b.color[0] - a.color[0]) * k,\r\n a.color[1] + (b.color[1] - a.color[1]) * k,\r\n a.color[2] + (b.color[2] - a.color[2]) * k,\r\n a.alpha + (b.alpha - a.alpha) * k,\r\n ];\r\n}\r\n\r\n/**\r\n * Moves stop `i` along t within its neighbours.\r\n * Сдвигает остановку `i` по t в пределах соседей.\r\n */\r\nexport function moveStop(stops: readonly GradientStop[], i: number, t: number, precision?: number | null): GradientStop[] {\r\n const next = copy(stops);\r\n const lo = i > 0 ? next[i - 1]!.t : 0;\r\n const hi = i < next.length - 1 ? next[i + 1]!.t : 1;\r\n next[i] = { ...next[i]!, t: Math.min(hi, Math.max(lo, roundTo(clamp01(t), precision))) };\r\n return next;\r\n}\r\n\r\n/**\r\n * Adds a stop at `t` with the colour the gradient has at that point; returns the new list and the index.\r\n * Добавляет остановку в `t` с цветом, который градиент имеет в этой точке; возвращает новый список и индекс.\r\n */\r\nexport function addStop(stops: readonly GradientStop[], t: number, precision: number | null = DEFAULT_PRECISION): { stops: GradientStop[]; index: number } {\r\n const x = roundTo(clamp01(t), precision);\r\n const [r, g, b, a] = sampleGradient(stops, x);\r\n const next = copy(stops);\r\n const at = next.findIndex((s) => s.t > x);\r\n const index = at === -1 ? next.length : at;\r\n const d = colorDigits(precision);\r\n next.splice(index, 0, { t: x, color: [roundTo(r, d), roundTo(g, d), roundTo(b, d)], alpha: roundAlpha(a, precision) });\r\n return { stops: next, index };\r\n}\r\n\r\n/**\r\n * Removes a stop; the last one is never removed.\r\n * Убирает остановку; последнюю не убирает.\r\n */\r\nexport function removeStop(stops: readonly GradientStop[], i: number): GradientStop[] {\r\n if (stops.length <= 1) return copy(stops);\r\n return copy(stops.filter((_, k) => k !== i));\r\n}\r\n\r\n/**\r\n * Stops lying right next to stop `i` (within `px` pixels at bar width `width`), itself included: a pile of overlapping handles.\r\n * Остановки, лежащие вплотную к остановке `i` (в пределах `px` пикселей при ширине полосы `width`), включая её саму: стопка наложенных ручек.\r\n */\r\nexport function stackAround(stops: readonly GradientStop[], i: number, width: number, px: number): number[] {\r\n const here = stops[i]?.t ?? 0;\r\n return stops.flatMap((s, k) => (Math.abs(s.t - here) * width <= px ? [k] : []));\r\n}\r\n\r\n/**\r\n * Which handle of the pile to take when it was dragged by `dx` pixels. The order of stops must not change, so only an outer one can be pulled out:\r\n * the first to the left, the last to the right.\r\n * Какую ручку из стопки взять, когда её потянули на `dx` пикселей. Порядок остановок менять нельзя, поэтому вытянуть можно\r\n * только крайнюю: влево первую, вправо последнюю.\r\n */\r\nexport function pickFromStack(cluster: readonly number[], dx: number): number {\r\n return dx < 0 ? Math.min(...cluster) : Math.max(...cluster);\r\n}\r\n\r\n/**\r\n * Linear colour → sRGB, 0…1.\r\n * Линейный цвет → sRGB, 0…1.\r\n */\r\nexport const toSrgb = (c: number) => (c <= 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 1 / 2.4) - 0.055);\r\n/**\r\n * sRGB → linear colour, 0…1.\r\n * sRGB → линейный цвет, 0…1.\r\n */\r\nexport const toLinear = (c: number) => (c <= 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4));\r\n\r\n/**\r\n * A CSS gradient for the preview bar (linear colour is converted to sRGB, alpha stays).\r\n * CSS-градиент для полосы предпросмотра (линейный цвет переводится в sRGB, альфа остаётся).\r\n */\r\nexport function gradientCss(stops: readonly GradientStop[]): string {\r\n const srgb = (c: number) => Math.round(255 * toSrgb(Math.min(1, Math.max(0, c))));\r\n const parts = stops.map((s) => `rgba(${srgb(s.color[0])}, ${srgb(s.color[1])}, ${srgb(s.color[2])}, ${s.alpha.toFixed(3)}) ${(s.t * 100).toFixed(1)}%`);\r\n return `linear-gradient(to right, ${parts.join(', ')})`;\r\n}\r\n","<script lang=\"ts\" setup>\r\nimport { nextTick, ref } from 'vue';\r\nimport { addStop, DEFAULT_PRECISION, gradientCss, moveStop, pickFromStack, removeStop, stackAround, toSrgb, type GradientStop } from './ops';\r\n\r\nconst props = withDefaults(\r\n defineProps<{\r\n /**\r\n * Stops in ascending t (at least one).\r\n * Остановки по возрастанию t (минимум одна).\r\n */\r\n modelValue: readonly GradientStop[];\r\n /**\r\n * Index of the selected stop.\r\n * Индекс выбранной остановки.\r\n */\r\n selected?: number;\r\n /**\r\n * A hint on hover over the bar.\r\n * Подсказка при наведении на полосу.\r\n */\r\n hint?: string;\r\n /**\r\n * Decimals of t and opacity in what the component emits; `null` does not round. Three by default; the colour components get two more.\r\n * Знаков после запятой у t и непрозрачности в том, что компонент отдаёт; `null` не обрезает. По умолчанию три; компоненты цвета получают на два знака больше.\r\n */\r\n precision?: number | null;\r\n /**\r\n * The keyboard arrow step along t (Shift: 10 times larger).\r\n * Шаг стрелки с клавиатуры по t (Shift: в 10 раз крупнее).\r\n */\r\n keyStep?: number;\r\n /**\r\n * The stop label for screen readers; \"Stop 1\" by default.\r\n * Подпись остановки для скринридеров; по умолчанию «Stop 1».\r\n */\r\n stopLabel?: (index: number, stop: GradientStop) => string;\r\n }>(),\r\n { selected: 0, precision: DEFAULT_PRECISION, keyStep: 0.01 },\r\n);\r\nconst emit = defineEmits<{\r\n 'update:modelValue': [value: GradientStop[]];\r\n 'update:selected': [index: number];\r\n /**\r\n * An edit is finished (released, added, removed): the moment to record into history.\r\n * Правка закончена (отпустили, добавили, убрали): момент для записи в историю.\r\n */\r\n commit: [];\r\n}>();\r\n\r\nconst bar = ref<HTMLElement | null>(null);\r\n\r\nfunction tAt(e: PointerEvent | MouseEvent): number {\r\n const r = bar.value!.getBoundingClientRect();\r\n return (e.clientX - r.left) / r.width;\r\n}\r\n\r\n/**\r\n * Handles closer than this distance (px) count as overlapping each other.\r\n * Ручки ближе этого расстояния (px) считаются наложенными друг на друга.\r\n */\r\nconst STACK_PX = 7;\r\n/**\r\n * The pointer shift (px) after which it is clear which way the pile is being dragged.\r\n * Сдвиг указателя (px), после которого понятно, в какую сторону тащат стопку.\r\n */\r\nconst PICK_PX = 3;\r\n\r\nlet dragging = -1;\r\n/**\r\n * A pile of overlapping handles was pressed: which one to take is decided by the first movement.\r\n * Нажали на стопку наложенных ручек: какую из них взять, решает первое движение.\r\n */\r\nlet pending: { cluster: number[]; x: number } | null = null;\r\n\r\nfunction onStopDown(e: PointerEvent, i: number) {\r\n if (e.altKey) {\r\n emit('update:modelValue', removeStop(props.modelValue, i));\r\n emit('update:selected', 0);\r\n emit('commit');\r\n return;\r\n }\r\n emit('update:selected', i);\r\n try {\r\n (e.currentTarget as Element).setPointerCapture(e.pointerId);\r\n } catch {\r\n // the pointer has already gone or the capture is unavailable: dragging works without it\r\n // указатель уже ушёл или захват недоступен: тянуть можно и без него\r\n }\r\n\r\n const width = bar.value!.getBoundingClientRect().width;\r\n const cluster = stackAround(props.modelValue, i, width, STACK_PX);\r\n dragging = i;\r\n // A pile of overlapping handles: which one to take is decided by the direction of the first movement\r\n // Стопка наложенных ручек: какую из них взять, решит направление первого движения\r\n if (cluster.length > 1) pending = { cluster, x: e.clientX };\r\n}\r\n\r\nfunction onMove(e: PointerEvent) {\r\n if (dragging < 0) return;\r\n if (pending) {\r\n const dx = e.clientX - pending.x;\r\n if (Math.abs(dx) < PICK_PX) return;\r\n dragging = pickFromStack(pending.cluster, dx);\r\n pending = null;\r\n emit('update:selected', dragging);\r\n }\r\n emit('update:modelValue', moveStop(props.modelValue, dragging, tAt(e), props.precision));\r\n}\r\n\r\nfunction onUp() {\r\n if (dragging < 0) return;\r\n const moved = pending === null;\r\n dragging = -1;\r\n pending = null;\r\n if (moved) emit('commit');\r\n}\r\n\r\nconst stopColor = (s: GradientStop) => `rgb(${s.color.map((c) => Math.round(255 * toSrgb(Math.min(1, Math.max(0, c))))).join(' ')})`;\r\n\r\n/**\r\n * Stop keys (focus on it): arrows move along t, Home/End to the start and end, Insert adds, Delete removes.\r\n * Клавиши остановки (фокус на ней): стрелки двигают по t, Home/End в начало и конец, Insert добавляет, Delete убирает.\r\n */\r\nfunction onStopKey(e: KeyboardEvent, i: number) {\r\n const stop = props.modelValue[i];\r\n if (!stop) return;\r\n const fine = props.keyStep * (e.shiftKey ? 10 : 1);\r\n\r\n let to: number | null = null;\r\n if (e.key === 'ArrowLeft' || e.key === 'ArrowDown') to = stop.t - fine;\r\n else if (e.key === 'ArrowRight' || e.key === 'ArrowUp') to = stop.t + fine;\r\n else if (e.key === 'Home') to = 0;\r\n else if (e.key === 'End') to = 1;\r\n\r\n if (to !== null) {\r\n e.preventDefault();\r\n emit('update:modelValue', moveStop(props.modelValue, i, to, props.precision));\r\n emit('commit');\r\n } else if (e.key === 'Insert') {\r\n // between this stop and the next (for the last: between it and the previous), with the gradient colour at that point\r\n // между этой остановкой и следующей (у последней: между ней и предыдущей), с цветом градиента в этой точке\r\n e.preventDefault();\r\n const other = props.modelValue[i + 1] ?? props.modelValue[i - 1];\r\n if (!other) return;\r\n const r = addStop(props.modelValue, (stop.t + other.t) / 2, props.precision);\r\n emit('update:modelValue', r.stops);\r\n emit('update:selected', r.index);\r\n emit('commit');\r\n focusStop(r.index);\r\n } else if (e.key === 'Delete' || e.key === 'Backspace') {\r\n e.preventDefault();\r\n const next = Math.max(0, i - 1);\r\n emit('update:modelValue', removeStop(props.modelValue, i));\r\n emit('update:selected', next);\r\n emit('commit');\r\n focusStop(next);\r\n }\r\n}\r\n\r\n/**\r\n * Focus on handle `i` after a re-render: keys go to the selected one, and focus must not stay on the old one.\r\n * Фокус на ручку `i` после перерисовки: клавиши идут к той, что выбрана, и фокус не должен оставаться на старой.\r\n */\r\nfunction focusStop(i: number) {\r\n void nextTick(() => bar.value?.querySelectorAll<HTMLElement>('.tx-gradient-stop')[i]?.focus());\r\n}\r\n\r\nconst labelOf = (i: number, s: GradientStop) => (props.stopLabel ? props.stopLabel(i, s) : `Stop ${i + 1}`);\r\n\r\nfunction onBarClick(e: MouseEvent) {\r\n if (e.target !== bar.value) return;\r\n const r = addStop(props.modelValue, tAt(e), props.precision);\r\n emit('update:modelValue', r.stops);\r\n emit('update:selected', r.index);\r\n emit('commit');\r\n}\r\n</script>\r\n\r\n<template>\r\n <div ref=\"bar\" class=\"tx-gradient\" :style=\"{ backgroundImage: gradientCss(modelValue) }\" :title=\"hint\" @click=\"onBarClick\">\r\n <span\r\n v-for=\"(s, i) in modelValue\"\r\n :key=\"i\"\r\n class=\"tx-gradient-stop\"\r\n :class=\"{ on: i === selected }\"\r\n :style=\"{ left: `${s.t * 100}%`, color: stopColor(s) }\"\r\n tabindex=\"0\"\r\n role=\"slider\"\r\n aria-orientation=\"horizontal\"\r\n aria-valuemin=\"0\"\r\n aria-valuemax=\"1\"\r\n :aria-valuenow=\"s.t\"\r\n :aria-valuetext=\"`${Math.round(s.t * 100)}%`\"\r\n :aria-label=\"labelOf(i, s)\"\r\n @focus=\"emit('update:selected', i)\"\r\n @keydown=\"onStopKey($event, i)\"\r\n @pointerdown.stop=\"onStopDown($event, i)\"\r\n @pointermove=\"onMove\"\r\n @pointerup=\"onUp\"\r\n @pointercancel=\"onUp\"\r\n >\r\n <!-- a filled triangle of the stop colour, tip towards the bar: on a light and a dark background it shows by its outline / залитый треугольник цвета остановки, остриём к полосе: на светлом и тёмном фоне его видно по обводке -->\r\n <svg viewBox=\"0 0 12 12\">\r\n <polygon class=\"tx-gradient-halo\" points=\"6,0.5 11.5,11.5 0.5,11.5\" />\r\n <polygon points=\"6,0.5 11.5,11.5 0.5,11.5\" />\r\n </svg>\r\n </span>\r\n </div>\r\n</template>\r\n\r\n<style>\r\n/*\r\n * Configured with CSS variables on any ancestor:\r\n * Настройка через CSS-переменные на любом предке:\r\n * --tx-gradient-border, --tx-gradient-stop-border, --tx-gradient-stop-outline, --tx-gradient-accent.\r\n */\r\n.tx-gradient {\r\n position: relative;\r\n height: 22px;\r\n margin-bottom: 20px; /* room for the stop handles and the mark of the selected one / место под ручки остановок и отметку выбранной */\r\n border: 1px solid var(--tx-gradient-border, #2a2d33);\r\n border-radius: 4px;\r\n /* a checkerboard under the bar shows transparency / шахматка под полосой показывает прозрачность */\r\n background-color: #fff;\r\n background-size: 100% 100%, 12px 12px;\r\n cursor: crosshair;\r\n}\r\n\r\n.tx-gradient-stop {\r\n position: absolute;\r\n top: calc(100% - 2px);\r\n width: 14px;\r\n height: 14px;\r\n margin-left: -7px;\r\n cursor: grab;\r\n}\r\n\r\n.tx-gradient-stop:active {\r\n cursor: grabbing;\r\n}\r\n\r\n.tx-gradient-stop:focus {\r\n outline: none;\r\n}\r\n\r\n/* keyboard focus: a glow of the accent colour around the triangle / фокус с клавиатуры: свечение акцентного цвета вокруг треугольника */\r\n.tx-gradient-stop:focus-visible svg {\r\n filter: drop-shadow(0 0 3px var(--tx-gradient-accent, #4fc3f7));\r\n}\r\n\r\n.tx-gradient-stop svg {\r\n display: block;\r\n width: 100%;\r\n height: 100%;\r\n overflow: visible;\r\n}\r\n\r\n/* a dark 1px outline outside the main one: the handle is visible on light bar colours behind it too / тёмная обводка в 1px снаружи основной: ручка видна и на светлых цветах полосы за ней */\r\n.tx-gradient-stop .tx-gradient-halo {\r\n fill: none;\r\n stroke: var(--tx-gradient-stop-outline, rgba(0, 0, 0, 0.85));\r\n stroke-width: 3.5;\r\n stroke-linejoin: round;\r\n}\r\n\r\n.tx-gradient-stop polygon:not(.tx-gradient-halo) {\r\n fill: currentColor; /* the stop colour is set by the component itself / цвет остановки задаёт сам компонент */\r\n stroke: var(--tx-gradient-stop-border, #5a606b);\r\n stroke-width: 1.5;\r\n stroke-linejoin: round;\r\n}\r\n\r\n/*\r\n * The selected handle: above the others (not hidden in a pile), slightly larger and with an accent stroke under it.\r\n * The fill stays the stop colour: the accent must not argue with it, so the outline is not coloured.\r\n * Выбранная ручка: выше остальных (в стопке не прячется), чуть крупнее и с акцентной черточкой под ней.\r\n * Заливка остаётся цветом остановки: акцент не должен спорить с ним, поэтому обводку не красим.\r\n */\r\n.tx-gradient-stop.on {\r\n z-index: 1;\r\n}\r\n\r\n.tx-gradient-stop.on svg {\r\n transform: scale(1.25);\r\n transform-origin: 50% 0;\r\n}\r\n\r\n.tx-gradient-stop.on::after {\r\n content: '';\r\n position: absolute;\r\n bottom: -6px;\r\n left: 50%;\r\n width: 12px;\r\n height: 2px;\r\n margin-left: -6px;\r\n border-radius: 1px;\r\n background: var(--tx-gradient-accent, #4fc3f7);\r\n}\r\n</style>\r\n","<script lang=\"ts\" setup>\r\nimport { nextTick, ref } from 'vue';\r\nimport { addStop, DEFAULT_PRECISION, gradientCss, moveStop, pickFromStack, removeStop, stackAround, toSrgb, type GradientStop } from './ops';\r\n\r\nconst props = withDefaults(\r\n defineProps<{\r\n /**\r\n * Stops in ascending t (at least one).\r\n * Остановки по возрастанию t (минимум одна).\r\n */\r\n modelValue: readonly GradientStop[];\r\n /**\r\n * Index of the selected stop.\r\n * Индекс выбранной остановки.\r\n */\r\n selected?: number;\r\n /**\r\n * A hint on hover over the bar.\r\n * Подсказка при наведении на полосу.\r\n */\r\n hint?: string;\r\n /**\r\n * Decimals of t and opacity in what the component emits; `null` does not round. Three by default; the colour components get two more.\r\n * Знаков после запятой у t и непрозрачности в том, что компонент отдаёт; `null` не обрезает. По умолчанию три; компоненты цвета получают на два знака больше.\r\n */\r\n precision?: number | null;\r\n /**\r\n * The keyboard arrow step along t (Shift: 10 times larger).\r\n * Шаг стрелки с клавиатуры по t (Shift: в 10 раз крупнее).\r\n */\r\n keyStep?: number;\r\n /**\r\n * The stop label for screen readers; \"Stop 1\" by default.\r\n * Подпись остановки для скринридеров; по умолчанию «Stop 1».\r\n */\r\n stopLabel?: (index: number, stop: GradientStop) => string;\r\n }>(),\r\n { selected: 0, precision: DEFAULT_PRECISION, keyStep: 0.01 },\r\n);\r\nconst emit = defineEmits<{\r\n 'update:modelValue': [value: GradientStop[]];\r\n 'update:selected': [index: number];\r\n /**\r\n * An edit is finished (released, added, removed): the moment to record into history.\r\n * Правка закончена (отпустили, добавили, убрали): момент для записи в историю.\r\n */\r\n commit: [];\r\n}>();\r\n\r\nconst bar = ref<HTMLElement | null>(null);\r\n\r\nfunction tAt(e: PointerEvent | MouseEvent): number {\r\n const r = bar.value!.getBoundingClientRect();\r\n return (e.clientX - r.left) / r.width;\r\n}\r\n\r\n/**\r\n * Handles closer than this distance (px) count as overlapping each other.\r\n * Ручки ближе этого расстояния (px) считаются наложенными друг на друга.\r\n */\r\nconst STACK_PX = 7;\r\n/**\r\n * The pointer shift (px) after which it is clear which way the pile is being dragged.\r\n * Сдвиг указателя (px), после которого понятно, в какую сторону тащат стопку.\r\n */\r\nconst PICK_PX = 3;\r\n\r\nlet dragging = -1;\r\n/**\r\n * A pile of overlapping handles was pressed: which one to take is decided by the first movement.\r\n * Нажали на стопку наложенных ручек: какую из них взять, решает первое движение.\r\n */\r\nlet pending: { cluster: number[]; x: number } | null = null;\r\n\r\nfunction onStopDown(e: PointerEvent, i: number) {\r\n if (e.altKey) {\r\n emit('update:modelValue', removeStop(props.modelValue, i));\r\n emit('update:selected', 0);\r\n emit('commit');\r\n return;\r\n }\r\n emit('update:selected', i);\r\n try {\r\n (e.currentTarget as Element).setPointerCapture(e.pointerId);\r\n } catch {\r\n // the pointer has already gone or the capture is unavailable: dragging works without it\r\n // указатель уже ушёл или захват недоступен: тянуть можно и без него\r\n }\r\n\r\n const width = bar.value!.getBoundingClientRect().width;\r\n const cluster = stackAround(props.modelValue, i, width, STACK_PX);\r\n dragging = i;\r\n // A pile of overlapping handles: which one to take is decided by the direction of the first movement\r\n // Стопка наложенных ручек: какую из них взять, решит направление первого движения\r\n if (cluster.length > 1) pending = { cluster, x: e.clientX };\r\n}\r\n\r\nfunction onMove(e: PointerEvent) {\r\n if (dragging < 0) return;\r\n if (pending) {\r\n const dx = e.clientX - pending.x;\r\n if (Math.abs(dx) < PICK_PX) return;\r\n dragging = pickFromStack(pending.cluster, dx);\r\n pending = null;\r\n emit('update:selected', dragging);\r\n }\r\n emit('update:modelValue', moveStop(props.modelValue, dragging, tAt(e), props.precision));\r\n}\r\n\r\nfunction onUp() {\r\n if (dragging < 0) return;\r\n const moved = pending === null;\r\n dragging = -1;\r\n pending = null;\r\n if (moved) emit('commit');\r\n}\r\n\r\nconst stopColor = (s: GradientStop) => `rgb(${s.color.map((c) => Math.round(255 * toSrgb(Math.min(1, Math.max(0, c))))).join(' ')})`;\r\n\r\n/**\r\n * Stop keys (focus on it): arrows move along t, Home/End to the start and end, Insert adds, Delete removes.\r\n * Клавиши остановки (фокус на ней): стрелки двигают по t, Home/End в начало и конец, Insert добавляет, Delete убирает.\r\n */\r\nfunction onStopKey(e: KeyboardEvent, i: number) {\r\n const stop = props.modelValue[i];\r\n if (!stop) return;\r\n const fine = props.keyStep * (e.shiftKey ? 10 : 1);\r\n\r\n let to: number | null = null;\r\n if (e.key === 'ArrowLeft' || e.key === 'ArrowDown') to = stop.t - fine;\r\n else if (e.key === 'ArrowRight' || e.key === 'ArrowUp') to = stop.t + fine;\r\n else if (e.key === 'Home') to = 0;\r\n else if (e.key === 'End') to = 1;\r\n\r\n if (to !== null) {\r\n e.preventDefault();\r\n emit('update:modelValue', moveStop(props.modelValue, i, to, props.precision));\r\n emit('commit');\r\n } else if (e.key === 'Insert') {\r\n // between this stop and the next (for the last: between it and the previous), with the gradient colour at that point\r\n // между этой остановкой и следующей (у последней: между ней и предыдущей), с цветом градиента в этой точке\r\n e.preventDefault();\r\n const other = props.modelValue[i + 1] ?? props.modelValue[i - 1];\r\n if (!other) return;\r\n const r = addStop(props.modelValue, (stop.t + other.t) / 2, props.precision);\r\n emit('update:modelValue', r.stops);\r\n emit('update:selected', r.index);\r\n emit('commit');\r\n focusStop(r.index);\r\n } else if (e.key === 'Delete' || e.key === 'Backspace') {\r\n e.preventDefault();\r\n const next = Math.max(0, i - 1);\r\n emit('update:modelValue', removeStop(props.modelValue, i));\r\n emit('update:selected', next);\r\n emit('commit');\r\n focusStop(next);\r\n }\r\n}\r\n\r\n/**\r\n * Focus on handle `i` after a re-render: keys go to the selected one, and focus must not stay on the old one.\r\n * Фокус на ручку `i` после перерисовки: клавиши идут к той, что выбрана, и фокус не должен оставаться на старой.\r\n */\r\nfunction focusStop(i: number) {\r\n void nextTick(() => bar.value?.querySelectorAll<HTMLElement>('.tx-gradient-stop')[i]?.focus());\r\n}\r\n\r\nconst labelOf = (i: number, s: GradientStop) => (props.stopLabel ? props.stopLabel(i, s) : `Stop ${i + 1}`);\r\n\r\nfunction onBarClick(e: MouseEvent) {\r\n if (e.target !== bar.value) return;\r\n const r = addStop(props.modelValue, tAt(e), props.precision);\r\n emit('update:modelValue', r.stops);\r\n emit('update:selected', r.index);\r\n emit('commit');\r\n}\r\n</script>\r\n\r\n<template>\r\n <div ref=\"bar\" class=\"tx-gradient\" :style=\"{ backgroundImage: gradientCss(modelValue) }\" :title=\"hint\" @click=\"onBarClick\">\r\n <span\r\n v-for=\"(s, i) in modelValue\"\r\n :key=\"i\"\r\n class=\"tx-gradient-stop\"\r\n :class=\"{ on: i === selected }\"\r\n :style=\"{ left: `${s.t * 100}%`, color: stopColor(s) }\"\r\n tabindex=\"0\"\r\n role=\"slider\"\r\n aria-orientation=\"horizontal\"\r\n aria-valuemin=\"0\"\r\n aria-valuemax=\"1\"\r\n :aria-valuenow=\"s.t\"\r\n :aria-valuetext=\"`${Math.round(s.t * 100)}%`\"\r\n :aria-label=\"labelOf(i, s)\"\r\n @focus=\"emit('update:selected', i)\"\r\n @keydown=\"onStopKey($event, i)\"\r\n @pointerdown.stop=\"onStopDown($event, i)\"\r\n @pointermove=\"onMove\"\r\n @pointerup=\"onUp\"\r\n @pointercancel=\"onUp\"\r\n >\r\n <!-- a filled triangle of the stop colour, tip towards the bar: on a light and a dark background it shows by its outline / залитый треугольник цвета остановки, остриём к полосе: на светлом и тёмном фоне его видно по обводке -->\r\n <svg viewBox=\"0 0 12 12\">\r\n <polygon class=\"tx-gradient-halo\" points=\"6,0.5 11.5,11.5 0.5,11.5\" />\r\n <polygon points=\"6,0.5 11.5,11.5 0.5,11.5\" />\r\n </svg>\r\n </span>\r\n </div>\r\n</template>\r\n\r\n<style>\r\n/*\r\n * Configured with CSS variables on any ancestor:\r\n * Настройка через CSS-переменные на любом предке:\r\n * --tx-gradient-border, --tx-gradient-stop-border, --tx-gradient-stop-outline, --tx-gradient-accent.\r\n */\r\n.tx-gradient {\r\n position: relative;\r\n height: 22px;\r\n margin-bottom: 20px; /* room for the stop handles and the mark of the selected one / место под ручки остановок и отметку выбранной */\r\n border: 1px solid var(--tx-gradient-border, #2a2d33);\r\n border-radius: 4px;\r\n /* a checkerboard under the bar shows transparency / шахматка под полосой показывает прозрачность */\r\n background-color: #fff;\r\n background-size: 100% 100%, 12px 12px;\r\n cursor: crosshair;\r\n}\r\n\r\n.tx-gradient-stop {\r\n position: absolute;\r\n top: calc(100% - 2px);\r\n width: 14px;\r\n height: 14px;\r\n margin-left: -7px;\r\n cursor: grab;\r\n}\r\n\r\n.tx-gradient-stop:active {\r\n cursor: grabbing;\r\n}\r\n\r\n.tx-gradient-stop:focus {\r\n outline: none;\r\n}\r\n\r\n/* keyboard focus: a glow of the accent colour around the triangle / фокус с клавиатуры: свечение акцентного цвета вокруг треугольника */\r\n.tx-gradient-stop:focus-visible svg {\r\n filter: drop-shadow(0 0 3px var(--tx-gradient-accent, #4fc3f7));\r\n}\r\n\r\n.tx-gradient-stop svg {\r\n display: block;\r\n width: 100%;\r\n height: 100%;\r\n overflow: visible;\r\n}\r\n\r\n/* a dark 1px outline outside the main one: the handle is visible on light bar colours behind it too / тёмная обводка в 1px снаружи основной: ручка видна и на светлых цветах полосы за ней */\r\n.tx-gradient-stop .tx-gradient-halo {\r\n fill: none;\r\n stroke: var(--tx-gradient-stop-outline, rgba(0, 0, 0, 0.85));\r\n stroke-width: 3.5;\r\n stroke-linejoin: round;\r\n}\r\n\r\n.tx-gradient-stop polygon:not(.tx-gradient-halo) {\r\n fill: currentColor; /* the stop colour is set by the component itself / цвет остановки задаёт сам компонент */\r\n stroke: var(--tx-gradient-stop-border, #5a606b);\r\n stroke-width: 1.5;\r\n stroke-linejoin: round;\r\n}\r\n\r\n/*\r\n * The selected handle: above the others (not hidden in a pile), slightly larger and with an accent stroke under it.\r\n * The fill stays the stop colour: the accent must not argue with it, so the outline is not coloured.\r\n * Выбранная ручка: выше остальных (в стопке не прячется), чуть крупнее и с акцентной черточкой под ней.\r\n * Заливка остаётся цветом остановки: акцент не должен спорить с ним, поэтому обводку не красим.\r\n */\r\n.tx-gradient-stop.on {\r\n z-index: 1;\r\n}\r\n\r\n.tx-gradient-stop.on svg {\r\n transform: scale(1.25);\r\n transform-origin: 50% 0;\r\n}\r\n\r\n.tx-gradient-stop.on::after {\r\n content: '';\r\n position: absolute;\r\n bottom: -6px;\r\n left: 50%;\r\n width: 12px;\r\n height: 2px;\r\n margin-left: -6px;\r\n border-radius: 1px;\r\n background: var(--tx-gradient-accent, #4fc3f7);\r\n}\r\n</style>\r\n"],"mappings":";;;AAeA,IAAM,QAAQ,UAAmD,MAAM,KAAK,OAAO;CAAE,GAAG;CAAG,OAAO,CAAC,GAAG,EAAE,KAAK;AAA2B,EAAE;;;;;AAM1I,IAAa,oBAAoB;;;;;;;AAQjC,IAAa,eAAe,cAA6C,cAAc,OAAO,OAAO,YAAY;;;;;AAMjH,IAAa,cAAc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,EAAE,KAAK;GAC/B,KAAK,QAAQ;EACjB;;GAII,OAAAA,UAAA,GAAAC,mBA4BM,OAAA;IA5BG,SAAA;IAAJ,KAAI;IAAM,OAAM;IAAe,OAAKC,eAAA,EAAA,iBAAqBC,MAAA,WAAA,CAAW,CAAC,QAAA,UAAU,EAAA,CAAA;IAAM,OAAO,QAAA;IAAO,SAAO;G,KAC3GH,UAAA,IAAA,GAAAC,mBA0BOG,UAAA,MAAAC,WAzBc,QAAA,aAAT,GAAG,MAAC;IADhB,OAAAL,UAAA,GAAAC,mBA0BO,QAAA;KAxBF,KAAK;KACN,OAAKK,eAAA,CAAC,oBAAkB,EAAA,IACV,MAAM,QAAA,SAAQ,CAAA,CAAA;KAC3B,OAAKJ,eAAA;MAAA,MAAA,GAAa,EAAE,IAAC,IAAA;MAAA,OAAkB,UAAU,CAAC;KAAA,CAAA;KACnD,UAAS;KACT,MAAK;KACL,oBAAiB;KACjB,iBAAc;KACd,iBAAc;KACb,iBAAe,EAAE;KACjB,kBAAc,GAAK,KAAK,MAAM,EAAE,IAAC,GAAA,EAAA;KACjC,cAAY,QAAQ,GAAG,CAAC;KACxB,UAAK,WAAE,KAAI,mBAAoB,CAAC;KAChC,YAAO,WAAE,UAAU,QAAQ,CAAC;KAC5B,eAAWK,eAAA,WAAO,WAAW,QAAQ,CAAC,GAAA,CAAA,MAAA,CAAA;KACtC,eAAa;KACb,aAAW;KACX,iBAAe;I,kCAGhBC,mBAGM,OAAA,EAHD,SAAQ,YAAW,GAAA,CACpBA,mBAAsE,WAAA;KAA7D,OAAM;KAAmB,QAAO;I,IACzCA,mBAA6C,WAAA,EAApC,QAAO,2BAA0B,CAAA,C"}
1
+ {"version":3,"file":"gradienteditor.js","names":["_openBlock","_createElementBlock","_normalizeStyle","_unref","_Fragment","_renderList","_normalizeClass","_withModifiers","_createElementVNode","_sfc_main"],"sources":["../src/gradienteditor/ops.ts","../src/gradienteditor/TaoxGradientEditor.vue","../src/gradienteditor/TaoxGradientEditor.vue"],"sourcesContent":["import { clamp01, roundTo } from '../num';\r\n\r\n/**\r\n * A gradient stop: t in 0…1, colour in linear RGB 0…1 (not sRGB), alpha 0…1.\r\n * Linear colour is what rendering needs; for the CSS preview bar it is converted to sRGB (`gradientCss`).\r\n * Остановка градиента: t в 0…1, цвет в линейном RGB 0…1 (не sRGB), alpha 0…1.\r\n * Линейный цвет нужен рендеру; в CSS-полоску он переводится в sRGB (`gradientCss`).\r\n */\r\nexport interface GradientStop {\r\n t: number;\r\n color: [number, number, number];\r\n alpha: number;\r\n}\r\n\r\n\r\nconst copy = (stops: readonly GradientStop[]): GradientStop[] => stops.map((s) => ({ ...s, color: [...s.color] as GradientStop['color'] }));\r\n\r\n/**\r\n * Default decimals of t and opacity: \"0.5700000000000001\" in a file is of use to nobody.\r\n * Знаков после запятой по умолчанию у t и непрозрачности: «0.5700000000000001» в файле никому не нужно.\r\n */\r\nexport const DEFAULT_PRECISION = 3;\r\n\r\n/**\r\n * Decimals of the colour components for a given `precision` of t and opacity. The colour is linear, and in the dark part of the scale sRGB rises steeply\r\n * (a linear step of 0.001 is 3 levels out of 255), so two more decimals are needed here: five when t has three.\r\n * Знаков у компонент цвета при `precision` у t и непрозрачности. Цвет линейный, а в тёмной части шкалы sRGB круто растёт\r\n * (шаг 0.001 линейного это 3 уровня из 255), поэтому тут нужно на два знака больше: при трёх у t это пять.\r\n */\r\nexport const colorDigits = (precision: number | null): number | null => (precision === null ? null : precision + 2);\r\n\r\n/**\r\n * Opacity 0…1 with `digits` decimals (three by default).\r\n * Непрозрачность 0…1 с `digits` знаками (по умолчанию три).\r\n */\r\nexport const roundAlpha = (a: number, digits: number | null = DEFAULT_PRECISION): number => roundTo(Math.min(1, Math.max(0, a)), digits);\r\n\r\n/**\r\n * Changes stop `i`; t and opacity are rounded to `precision` decimals (three by default; `null` turns it off), the colour to `precision + 2`.\r\n * Меняет остановку `i`; t и непрозрачность округляются до `precision` знаков (по умолчанию три; `null` отключает), цвет до `precision + 2`.\r\n */\r\nexport function patchStop(stops: readonly GradientStop[], i: number, patch: Partial<GradientStop>, precision: number | null = DEFAULT_PRECISION): GradientStop[] {\r\n const next = copy(stops);\r\n const stop = { ...next[i]!, ...patch };\r\n stop.alpha = roundAlpha(stop.alpha, precision);\r\n stop.t = roundTo(Math.min(1, Math.max(0, stop.t)), precision);\r\n stop.color = stop.color.map((c) => roundTo(c, colorDigits(precision))) as GradientStop['color'];\r\n next[i] = stop;\r\n return next;\r\n}\r\n\r\n/**\r\n * The colour and opacity of the gradient at t: linear between stops, equal to the end stop beyond the ends. Returns [r, g, b, a].\r\n * Цвет и непрозрачность градиента в t: линейно между остановками, за краями равны крайней. Возвращает [r, g, b, a].\r\n */\r\nexport function sampleGradient(stops: readonly GradientStop[], t: number): [number, number, number, number] {\r\n const n = stops.length;\r\n if (n === 0) return [1, 1, 1, 1];\r\n const x = clamp01(t);\r\n let a = stops[0]!;\r\n let b = stops[0]!;\r\n let k = 0;\r\n if (x >= stops[n - 1]!.t) {\r\n a = b = stops[n - 1]!;\r\n } else if (x > stops[0]!.t) {\r\n for (let i = 1; i < n; i++) {\r\n if (x <= stops[i]!.t) {\r\n a = stops[i - 1]!;\r\n b = stops[i]!;\r\n const span = b.t - a.t;\r\n k = span <= 0 ? 1 : (x - a.t) / span;\r\n break;\r\n }\r\n }\r\n }\r\n return [\r\n a.color[0] + (b.color[0] - a.color[0]) * k,\r\n a.color[1] + (b.color[1] - a.color[1]) * k,\r\n a.color[2] + (b.color[2] - a.color[2]) * k,\r\n a.alpha + (b.alpha - a.alpha) * k,\r\n ];\r\n}\r\n\r\n/**\r\n * Moves stop `i` along t within its neighbours.\r\n * Сдвигает остановку `i` по t в пределах соседей.\r\n */\r\nexport function moveStop(stops: readonly GradientStop[], i: number, t: number, precision?: number | null): GradientStop[] {\r\n const next = copy(stops);\r\n const lo = i > 0 ? next[i - 1]!.t : 0;\r\n const hi = i < next.length - 1 ? next[i + 1]!.t : 1;\r\n next[i] = { ...next[i]!, t: Math.min(hi, Math.max(lo, roundTo(clamp01(t), precision))) };\r\n return next;\r\n}\r\n\r\n/**\r\n * Adds a stop at `t` with the colour the gradient has at that point; returns the new list and the index.\r\n * Добавляет остановку в `t` с цветом, который градиент имеет в этой точке; возвращает новый список и индекс.\r\n */\r\nexport function addStop(stops: readonly GradientStop[], t: number, precision: number | null = DEFAULT_PRECISION): { stops: GradientStop[]; index: number } {\r\n const x = roundTo(clamp01(t), precision);\r\n const [r, g, b, a] = sampleGradient(stops, x);\r\n const next = copy(stops);\r\n const at = next.findIndex((s) => s.t > x);\r\n const index = at === -1 ? next.length : at;\r\n const d = colorDigits(precision);\r\n next.splice(index, 0, { t: x, color: [roundTo(r, d), roundTo(g, d), roundTo(b, d)], alpha: roundAlpha(a, precision) });\r\n return { stops: next, index };\r\n}\r\n\r\n/**\r\n * Removes a stop; the last one is never removed.\r\n * Убирает остановку; последнюю не убирает.\r\n */\r\nexport function removeStop(stops: readonly GradientStop[], i: number): GradientStop[] {\r\n if (stops.length <= 1) return copy(stops);\r\n return copy(stops.filter((_, k) => k !== i));\r\n}\r\n\r\n/**\r\n * Stops lying right next to stop `i` (within `px` pixels at bar width `width`), itself included: a pile of overlapping handles.\r\n * Остановки, лежащие вплотную к остановке `i` (в пределах `px` пикселей при ширине полосы `width`), включая её саму: стопка наложенных ручек.\r\n */\r\nexport function stackAround(stops: readonly GradientStop[], i: number, width: number, px: number): number[] {\r\n const here = stops[i]?.t ?? 0;\r\n return stops.flatMap((s, k) => (Math.abs(s.t - here) * width <= px ? [k] : []));\r\n}\r\n\r\n/**\r\n * Which handle of the pile to take when it was dragged by `dx` pixels. The order of stops must not change, so only an outer one can be pulled out:\r\n * the first to the left, the last to the right.\r\n * Какую ручку из стопки взять, когда её потянули на `dx` пикселей. Порядок остановок менять нельзя, поэтому вытянуть можно\r\n * только крайнюю: влево первую, вправо последнюю.\r\n */\r\nexport function pickFromStack(cluster: readonly number[], dx: number): number {\r\n return dx < 0 ? Math.min(...cluster) : Math.max(...cluster);\r\n}\r\n\r\n/**\r\n * Linear colour → sRGB, 0…1.\r\n * Линейный цвет → sRGB, 0…1.\r\n */\r\nexport const toSrgb = (c: number) => (c <= 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 1 / 2.4) - 0.055);\r\n/**\r\n * sRGB → linear colour, 0…1.\r\n * sRGB → линейный цвет, 0…1.\r\n */\r\nexport const toLinear = (c: number) => (c <= 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4));\r\n\r\n/**\r\n * A CSS gradient for the preview bar (linear colour is converted to sRGB, alpha stays).\r\n * CSS-градиент для полосы предпросмотра (линейный цвет переводится в sRGB, альфа остаётся).\r\n */\r\nexport function gradientCss(stops: readonly GradientStop[]): string {\r\n const srgb = (c: number) => Math.round(255 * toSrgb(Math.min(1, Math.max(0, c))));\r\n const parts = stops.map((s) => `rgba(${srgb(s.color[0])}, ${srgb(s.color[1])}, ${srgb(s.color[2])}, ${s.alpha.toFixed(3)}) ${(s.t * 100).toFixed(1)}%`);\r\n return `linear-gradient(to right, ${parts.join(', ')})`;\r\n}\r\n","<script lang=\"ts\" setup>\r\nimport { nextTick, ref } from 'vue';\r\nimport { addStop, DEFAULT_PRECISION, gradientCss, moveStop, pickFromStack, removeStop, stackAround, toSrgb, type GradientStop } from './ops';\r\n\r\nconst props = withDefaults(\r\n defineProps<{\r\n /**\r\n * Stops in ascending t (at least one).\r\n * Остановки по возрастанию t (минимум одна).\r\n */\r\n modelValue: readonly GradientStop[];\r\n /**\r\n * Index of the selected stop.\r\n * Индекс выбранной остановки.\r\n */\r\n selected?: number;\r\n /**\r\n * A hint on hover over the bar.\r\n * Подсказка при наведении на полосу.\r\n */\r\n hint?: string;\r\n /**\r\n * Decimals of t and opacity in what the component emits; `null` does not round. Three by default; the colour components get two more.\r\n * Знаков после запятой у t и непрозрачности в том, что компонент отдаёт; `null` не обрезает. По умолчанию три; компоненты цвета получают на два знака больше.\r\n */\r\n precision?: number | null;\r\n /**\r\n * The keyboard arrow step along t (Shift: 10 times larger).\r\n * Шаг стрелки с клавиатуры по t (Shift: в 10 раз крупнее).\r\n */\r\n keyStep?: number;\r\n /**\r\n * The stop label for screen readers; \"Stop 1\" by default.\r\n * Подпись остановки для скринридеров; по умолчанию «Stop 1».\r\n */\r\n stopLabel?: (index: number, stop: GradientStop) => string;\r\n }>(),\r\n { selected: 0, precision: DEFAULT_PRECISION, keyStep: 0.01 },\r\n);\r\nconst emit = defineEmits<{\r\n 'update:modelValue': [value: GradientStop[]];\r\n 'update:selected': [index: number];\r\n /**\r\n * An edit is finished (released, added, removed): the moment to record into history.\r\n * Правка закончена (отпустили, добавили, убрали): момент для записи в историю.\r\n */\r\n commit: [];\r\n}>();\r\n\r\nconst bar = ref<HTMLElement | null>(null);\r\n\r\nfunction tAt(e: PointerEvent | MouseEvent): number {\r\n const r = bar.value!.getBoundingClientRect();\r\n return (e.clientX - r.left) / r.width;\r\n}\r\n\r\n/**\r\n * Handles closer than this distance (px) count as overlapping each other.\r\n * Ручки ближе этого расстояния (px) считаются наложенными друг на друга.\r\n */\r\nconst STACK_PX = 7;\r\n/**\r\n * The pointer shift (px) after which it is clear which way the pile is being dragged.\r\n * Сдвиг указателя (px), после которого понятно, в какую сторону тащат стопку.\r\n */\r\nconst PICK_PX = 3;\r\n\r\nlet dragging = -1;\r\n/**\r\n * A pile of overlapping handles was pressed: which one to take is decided by the first movement.\r\n * Нажали на стопку наложенных ручек: какую из них взять, решает первое движение.\r\n */\r\nlet pending: { cluster: number[]; x: number } | null = null;\r\n\r\nfunction onStopDown(e: PointerEvent, i: number) {\r\n if (e.altKey) {\r\n emit('update:modelValue', removeStop(props.modelValue, i));\r\n emit('update:selected', 0);\r\n emit('commit');\r\n return;\r\n }\r\n emit('update:selected', i);\r\n try {\r\n (e.currentTarget as Element).setPointerCapture(e.pointerId);\r\n } catch {\r\n // the pointer has already gone or the capture is unavailable: dragging works without it\r\n // указатель уже ушёл или захват недоступен: тянуть можно и без него\r\n }\r\n\r\n const width = bar.value!.getBoundingClientRect().width;\r\n const cluster = stackAround(props.modelValue, i, width, STACK_PX);\r\n dragging = i;\r\n // A pile of overlapping handles: which one to take is decided by the direction of the first movement\r\n // Стопка наложенных ручек: какую из них взять, решит направление первого движения\r\n if (cluster.length > 1) pending = { cluster, x: e.clientX };\r\n}\r\n\r\nfunction onMove(e: PointerEvent) {\r\n if (dragging < 0) return;\r\n if (pending) {\r\n const dx = e.clientX - pending.x;\r\n if (Math.abs(dx) < PICK_PX) return;\r\n dragging = pickFromStack(pending.cluster, dx);\r\n pending = null;\r\n emit('update:selected', dragging);\r\n }\r\n emit('update:modelValue', moveStop(props.modelValue, dragging, tAt(e), props.precision));\r\n}\r\n\r\nfunction onUp() {\r\n if (dragging < 0) return;\r\n const moved = pending === null;\r\n dragging = -1;\r\n pending = null;\r\n if (moved) emit('commit');\r\n}\r\n\r\nconst stopColor = (s: GradientStop) => `rgb(${s.color.map((c) => Math.round(255 * toSrgb(Math.min(1, Math.max(0, c))))).join(' ')})`;\r\n\r\n/**\r\n * Stop keys (focus on it): arrows move along t, Home/End to the start and end, Insert adds, Delete removes.\r\n * Клавиши остановки (фокус на ней): стрелки двигают по t, Home/End в начало и конец, Insert добавляет, Delete убирает.\r\n */\r\nfunction onStopKey(e: KeyboardEvent, i: number) {\r\n const stop = props.modelValue[i];\r\n if (!stop) return;\r\n const fine = props.keyStep * (e.shiftKey ? 10 : 1);\r\n\r\n let to: number | null = null;\r\n if (e.key === 'ArrowLeft' || e.key === 'ArrowDown') to = stop.t - fine;\r\n else if (e.key === 'ArrowRight' || e.key === 'ArrowUp') to = stop.t + fine;\r\n else if (e.key === 'Home') to = 0;\r\n else if (e.key === 'End') to = 1;\r\n\r\n if (to !== null) {\r\n e.preventDefault();\r\n emit('update:modelValue', moveStop(props.modelValue, i, to, props.precision));\r\n emit('commit');\r\n } else if (e.key === 'Insert') {\r\n // between this stop and the next (for the last: between it and the previous), with the gradient colour at that point\r\n // между этой остановкой и следующей (у последней: между ней и предыдущей), с цветом градиента в этой точке\r\n e.preventDefault();\r\n const other = props.modelValue[i + 1] ?? props.modelValue[i - 1];\r\n if (!other) return;\r\n const r = addStop(props.modelValue, (stop.t + other.t) / 2, props.precision);\r\n emit('update:modelValue', r.stops);\r\n emit('update:selected', r.index);\r\n emit('commit');\r\n focusStop(r.index);\r\n } else if (e.key === 'Delete' || e.key === 'Backspace') {\r\n e.preventDefault();\r\n const next = Math.max(0, i - 1);\r\n emit('update:modelValue', removeStop(props.modelValue, i));\r\n emit('update:selected', next);\r\n emit('commit');\r\n focusStop(next);\r\n }\r\n}\r\n\r\n/**\r\n * Focus on handle `i` after a re-render: keys go to the selected one, and focus must not stay on the old one.\r\n * Фокус на ручку `i` после перерисовки: клавиши идут к той, что выбрана, и фокус не должен оставаться на старой.\r\n */\r\nfunction focusStop(i: number) {\r\n void nextTick(() => bar.value?.querySelectorAll<HTMLElement>('.tx-gradient-stop')[i]?.focus());\r\n}\r\n\r\nconst labelOf = (i: number, s: GradientStop) => (props.stopLabel ? props.stopLabel(i, s) : `Stop ${i + 1}`);\r\n\r\nfunction onBarClick(e: MouseEvent) {\r\n if (e.target !== bar.value) return;\r\n const r = addStop(props.modelValue, tAt(e), props.precision);\r\n emit('update:modelValue', r.stops);\r\n emit('update:selected', r.index);\r\n emit('commit');\r\n}\r\n</script>\r\n\r\n<template>\r\n <div ref=\"bar\" class=\"tx-gradient\" :style=\"{ backgroundImage: gradientCss(modelValue) }\" :title=\"hint\" @click=\"onBarClick\">\r\n <span\r\n v-for=\"(s, i) in modelValue\"\r\n :key=\"i\"\r\n class=\"tx-gradient-stop\"\r\n :class=\"{ on: i === selected }\"\r\n :style=\"{ left: `${s.t * 100}%`, color: stopColor(s) }\"\r\n tabindex=\"0\"\r\n role=\"slider\"\r\n aria-orientation=\"horizontal\"\r\n aria-valuemin=\"0\"\r\n aria-valuemax=\"1\"\r\n :aria-valuenow=\"s.t\"\r\n :aria-valuetext=\"`${Math.round(s.t * 100)}%`\"\r\n :aria-label=\"labelOf(i, s)\"\r\n @focus=\"emit('update:selected', i)\"\r\n @keydown=\"onStopKey($event, i)\"\r\n @pointerdown.stop=\"onStopDown($event, i)\"\r\n @pointermove=\"onMove\"\r\n @pointerup=\"onUp\"\r\n @pointercancel=\"onUp\"\r\n >\r\n <!-- a filled triangle of the stop colour, tip towards the bar: on a light and a dark background it shows by its outline / залитый треугольник цвета остановки, остриём к полосе: на светлом и тёмном фоне его видно по обводке -->\r\n <svg viewBox=\"0 0 12 12\">\r\n <polygon class=\"tx-gradient-halo\" points=\"6,0.5 11.5,11.5 0.5,11.5\" />\r\n <polygon points=\"6,0.5 11.5,11.5 0.5,11.5\" />\r\n </svg>\r\n </span>\r\n </div>\r\n</template>\r\n\r\n<style>\r\n/*\r\n * Configured with CSS variables on any ancestor:\r\n * Настройка через CSS-переменные на любом предке:\r\n * --tx-gradient-border, --tx-gradient-stop-border, --tx-gradient-stop-outline, --tx-gradient-accent,\r\n * --tx-gradient-radius (the corners of the bar, 4px by default).\r\n * --tx-gradient-radius — углы полосы, по умолчанию 4px.\r\n */\r\n.tx-gradient {\r\n position: relative;\r\n height: 22px;\r\n margin-bottom: 20px; /* room for the stop handles and the mark of the selected one / место под ручки остановок и отметку выбранной */\r\n border: 1px solid var(--tx-gradient-border, #2a2d33);\r\n border-radius: var(--tx-gradient-radius, 4px);\r\n /* a checkerboard under the bar shows transparency / шахматка под полосой показывает прозрачность */\r\n background-color: #fff;\r\n background-size: 100% 100%, 12px 12px;\r\n cursor: crosshair;\r\n}\r\n\r\n.tx-gradient-stop {\r\n position: absolute;\r\n top: calc(100% - 2px);\r\n width: 14px;\r\n height: 14px;\r\n margin-left: -7px;\r\n cursor: grab;\r\n}\r\n\r\n.tx-gradient-stop:active {\r\n cursor: grabbing;\r\n}\r\n\r\n.tx-gradient-stop:focus {\r\n outline: none;\r\n}\r\n\r\n/* keyboard focus: a glow of the accent colour around the triangle / фокус с клавиатуры: свечение акцентного цвета вокруг треугольника */\r\n.tx-gradient-stop:focus-visible svg {\r\n filter: drop-shadow(0 0 3px var(--tx-gradient-accent, #4fc3f7));\r\n}\r\n\r\n.tx-gradient-stop svg {\r\n display: block;\r\n width: 100%;\r\n height: 100%;\r\n overflow: visible;\r\n}\r\n\r\n/* a dark 1px outline outside the main one: the handle is visible on light bar colours behind it too / тёмная обводка в 1px снаружи основной: ручка видна и на светлых цветах полосы за ней */\r\n.tx-gradient-stop .tx-gradient-halo {\r\n fill: none;\r\n stroke: var(--tx-gradient-stop-outline, rgba(0, 0, 0, 0.85));\r\n stroke-width: 3.5;\r\n stroke-linejoin: round;\r\n}\r\n\r\n.tx-gradient-stop polygon:not(.tx-gradient-halo) {\r\n fill: currentColor; /* the stop colour is set by the component itself / цвет остановки задаёт сам компонент */\r\n stroke: var(--tx-gradient-stop-border, #5a606b);\r\n stroke-width: 1.5;\r\n stroke-linejoin: round;\r\n}\r\n\r\n/*\r\n * The selected handle: above the others (not hidden in a pile), slightly larger and with an accent stroke under it.\r\n * The fill stays the stop colour: the accent must not argue with it, so the outline is not coloured.\r\n * Выбранная ручка: выше остальных (в стопке не прячется), чуть крупнее и с акцентной черточкой под ней.\r\n * Заливка остаётся цветом остановки: акцент не должен спорить с ним, поэтому обводку не красим.\r\n */\r\n.tx-gradient-stop.on {\r\n z-index: 1;\r\n}\r\n\r\n.tx-gradient-stop.on svg {\r\n transform: scale(1.25);\r\n transform-origin: 50% 0;\r\n}\r\n\r\n.tx-gradient-stop.on::after {\r\n content: '';\r\n position: absolute;\r\n bottom: -6px;\r\n left: 50%;\r\n width: 12px;\r\n height: 2px;\r\n margin-left: -6px;\r\n border-radius: 1px;\r\n background: var(--tx-gradient-accent, #4fc3f7);\r\n}\r\n</style>\r\n","<script lang=\"ts\" setup>\r\nimport { nextTick, ref } from 'vue';\r\nimport { addStop, DEFAULT_PRECISION, gradientCss, moveStop, pickFromStack, removeStop, stackAround, toSrgb, type GradientStop } from './ops';\r\n\r\nconst props = withDefaults(\r\n defineProps<{\r\n /**\r\n * Stops in ascending t (at least one).\r\n * Остановки по возрастанию t (минимум одна).\r\n */\r\n modelValue: readonly GradientStop[];\r\n /**\r\n * Index of the selected stop.\r\n * Индекс выбранной остановки.\r\n */\r\n selected?: number;\r\n /**\r\n * A hint on hover over the bar.\r\n * Подсказка при наведении на полосу.\r\n */\r\n hint?: string;\r\n /**\r\n * Decimals of t and opacity in what the component emits; `null` does not round. Three by default; the colour components get two more.\r\n * Знаков после запятой у t и непрозрачности в том, что компонент отдаёт; `null` не обрезает. По умолчанию три; компоненты цвета получают на два знака больше.\r\n */\r\n precision?: number | null;\r\n /**\r\n * The keyboard arrow step along t (Shift: 10 times larger).\r\n * Шаг стрелки с клавиатуры по t (Shift: в 10 раз крупнее).\r\n */\r\n keyStep?: number;\r\n /**\r\n * The stop label for screen readers; \"Stop 1\" by default.\r\n * Подпись остановки для скринридеров; по умолчанию «Stop 1».\r\n */\r\n stopLabel?: (index: number, stop: GradientStop) => string;\r\n }>(),\r\n { selected: 0, precision: DEFAULT_PRECISION, keyStep: 0.01 },\r\n);\r\nconst emit = defineEmits<{\r\n 'update:modelValue': [value: GradientStop[]];\r\n 'update:selected': [index: number];\r\n /**\r\n * An edit is finished (released, added, removed): the moment to record into history.\r\n * Правка закончена (отпустили, добавили, убрали): момент для записи в историю.\r\n */\r\n commit: [];\r\n}>();\r\n\r\nconst bar = ref<HTMLElement | null>(null);\r\n\r\nfunction tAt(e: PointerEvent | MouseEvent): number {\r\n const r = bar.value!.getBoundingClientRect();\r\n return (e.clientX - r.left) / r.width;\r\n}\r\n\r\n/**\r\n * Handles closer than this distance (px) count as overlapping each other.\r\n * Ручки ближе этого расстояния (px) считаются наложенными друг на друга.\r\n */\r\nconst STACK_PX = 7;\r\n/**\r\n * The pointer shift (px) after which it is clear which way the pile is being dragged.\r\n * Сдвиг указателя (px), после которого понятно, в какую сторону тащат стопку.\r\n */\r\nconst PICK_PX = 3;\r\n\r\nlet dragging = -1;\r\n/**\r\n * A pile of overlapping handles was pressed: which one to take is decided by the first movement.\r\n * Нажали на стопку наложенных ручек: какую из них взять, решает первое движение.\r\n */\r\nlet pending: { cluster: number[]; x: number } | null = null;\r\n\r\nfunction onStopDown(e: PointerEvent, i: number) {\r\n if (e.altKey) {\r\n emit('update:modelValue', removeStop(props.modelValue, i));\r\n emit('update:selected', 0);\r\n emit('commit');\r\n return;\r\n }\r\n emit('update:selected', i);\r\n try {\r\n (e.currentTarget as Element).setPointerCapture(e.pointerId);\r\n } catch {\r\n // the pointer has already gone or the capture is unavailable: dragging works without it\r\n // указатель уже ушёл или захват недоступен: тянуть можно и без него\r\n }\r\n\r\n const width = bar.value!.getBoundingClientRect().width;\r\n const cluster = stackAround(props.modelValue, i, width, STACK_PX);\r\n dragging = i;\r\n // A pile of overlapping handles: which one to take is decided by the direction of the first movement\r\n // Стопка наложенных ручек: какую из них взять, решит направление первого движения\r\n if (cluster.length > 1) pending = { cluster, x: e.clientX };\r\n}\r\n\r\nfunction onMove(e: PointerEvent) {\r\n if (dragging < 0) return;\r\n if (pending) {\r\n const dx = e.clientX - pending.x;\r\n if (Math.abs(dx) < PICK_PX) return;\r\n dragging = pickFromStack(pending.cluster, dx);\r\n pending = null;\r\n emit('update:selected', dragging);\r\n }\r\n emit('update:modelValue', moveStop(props.modelValue, dragging, tAt(e), props.precision));\r\n}\r\n\r\nfunction onUp() {\r\n if (dragging < 0) return;\r\n const moved = pending === null;\r\n dragging = -1;\r\n pending = null;\r\n if (moved) emit('commit');\r\n}\r\n\r\nconst stopColor = (s: GradientStop) => `rgb(${s.color.map((c) => Math.round(255 * toSrgb(Math.min(1, Math.max(0, c))))).join(' ')})`;\r\n\r\n/**\r\n * Stop keys (focus on it): arrows move along t, Home/End to the start and end, Insert adds, Delete removes.\r\n * Клавиши остановки (фокус на ней): стрелки двигают по t, Home/End в начало и конец, Insert добавляет, Delete убирает.\r\n */\r\nfunction onStopKey(e: KeyboardEvent, i: number) {\r\n const stop = props.modelValue[i];\r\n if (!stop) return;\r\n const fine = props.keyStep * (e.shiftKey ? 10 : 1);\r\n\r\n let to: number | null = null;\r\n if (e.key === 'ArrowLeft' || e.key === 'ArrowDown') to = stop.t - fine;\r\n else if (e.key === 'ArrowRight' || e.key === 'ArrowUp') to = stop.t + fine;\r\n else if (e.key === 'Home') to = 0;\r\n else if (e.key === 'End') to = 1;\r\n\r\n if (to !== null) {\r\n e.preventDefault();\r\n emit('update:modelValue', moveStop(props.modelValue, i, to, props.precision));\r\n emit('commit');\r\n } else if (e.key === 'Insert') {\r\n // between this stop and the next (for the last: between it and the previous), with the gradient colour at that point\r\n // между этой остановкой и следующей (у последней: между ней и предыдущей), с цветом градиента в этой точке\r\n e.preventDefault();\r\n const other = props.modelValue[i + 1] ?? props.modelValue[i - 1];\r\n if (!other) return;\r\n const r = addStop(props.modelValue, (stop.t + other.t) / 2, props.precision);\r\n emit('update:modelValue', r.stops);\r\n emit('update:selected', r.index);\r\n emit('commit');\r\n focusStop(r.index);\r\n } else if (e.key === 'Delete' || e.key === 'Backspace') {\r\n e.preventDefault();\r\n const next = Math.max(0, i - 1);\r\n emit('update:modelValue', removeStop(props.modelValue, i));\r\n emit('update:selected', next);\r\n emit('commit');\r\n focusStop(next);\r\n }\r\n}\r\n\r\n/**\r\n * Focus on handle `i` after a re-render: keys go to the selected one, and focus must not stay on the old one.\r\n * Фокус на ручку `i` после перерисовки: клавиши идут к той, что выбрана, и фокус не должен оставаться на старой.\r\n */\r\nfunction focusStop(i: number) {\r\n void nextTick(() => bar.value?.querySelectorAll<HTMLElement>('.tx-gradient-stop')[i]?.focus());\r\n}\r\n\r\nconst labelOf = (i: number, s: GradientStop) => (props.stopLabel ? props.stopLabel(i, s) : `Stop ${i + 1}`);\r\n\r\nfunction onBarClick(e: MouseEvent) {\r\n if (e.target !== bar.value) return;\r\n const r = addStop(props.modelValue, tAt(e), props.precision);\r\n emit('update:modelValue', r.stops);\r\n emit('update:selected', r.index);\r\n emit('commit');\r\n}\r\n</script>\r\n\r\n<template>\r\n <div ref=\"bar\" class=\"tx-gradient\" :style=\"{ backgroundImage: gradientCss(modelValue) }\" :title=\"hint\" @click=\"onBarClick\">\r\n <span\r\n v-for=\"(s, i) in modelValue\"\r\n :key=\"i\"\r\n class=\"tx-gradient-stop\"\r\n :class=\"{ on: i === selected }\"\r\n :style=\"{ left: `${s.t * 100}%`, color: stopColor(s) }\"\r\n tabindex=\"0\"\r\n role=\"slider\"\r\n aria-orientation=\"horizontal\"\r\n aria-valuemin=\"0\"\r\n aria-valuemax=\"1\"\r\n :aria-valuenow=\"s.t\"\r\n :aria-valuetext=\"`${Math.round(s.t * 100)}%`\"\r\n :aria-label=\"labelOf(i, s)\"\r\n @focus=\"emit('update:selected', i)\"\r\n @keydown=\"onStopKey($event, i)\"\r\n @pointerdown.stop=\"onStopDown($event, i)\"\r\n @pointermove=\"onMove\"\r\n @pointerup=\"onUp\"\r\n @pointercancel=\"onUp\"\r\n >\r\n <!-- a filled triangle of the stop colour, tip towards the bar: on a light and a dark background it shows by its outline / залитый треугольник цвета остановки, остриём к полосе: на светлом и тёмном фоне его видно по обводке -->\r\n <svg viewBox=\"0 0 12 12\">\r\n <polygon class=\"tx-gradient-halo\" points=\"6,0.5 11.5,11.5 0.5,11.5\" />\r\n <polygon points=\"6,0.5 11.5,11.5 0.5,11.5\" />\r\n </svg>\r\n </span>\r\n </div>\r\n</template>\r\n\r\n<style>\r\n/*\r\n * Configured with CSS variables on any ancestor:\r\n * Настройка через CSS-переменные на любом предке:\r\n * --tx-gradient-border, --tx-gradient-stop-border, --tx-gradient-stop-outline, --tx-gradient-accent,\r\n * --tx-gradient-radius (the corners of the bar, 4px by default).\r\n * --tx-gradient-radius — углы полосы, по умолчанию 4px.\r\n */\r\n.tx-gradient {\r\n position: relative;\r\n height: 22px;\r\n margin-bottom: 20px; /* room for the stop handles and the mark of the selected one / место под ручки остановок и отметку выбранной */\r\n border: 1px solid var(--tx-gradient-border, #2a2d33);\r\n border-radius: var(--tx-gradient-radius, 4px);\r\n /* a checkerboard under the bar shows transparency / шахматка под полосой показывает прозрачность */\r\n background-color: #fff;\r\n background-size: 100% 100%, 12px 12px;\r\n cursor: crosshair;\r\n}\r\n\r\n.tx-gradient-stop {\r\n position: absolute;\r\n top: calc(100% - 2px);\r\n width: 14px;\r\n height: 14px;\r\n margin-left: -7px;\r\n cursor: grab;\r\n}\r\n\r\n.tx-gradient-stop:active {\r\n cursor: grabbing;\r\n}\r\n\r\n.tx-gradient-stop:focus {\r\n outline: none;\r\n}\r\n\r\n/* keyboard focus: a glow of the accent colour around the triangle / фокус с клавиатуры: свечение акцентного цвета вокруг треугольника */\r\n.tx-gradient-stop:focus-visible svg {\r\n filter: drop-shadow(0 0 3px var(--tx-gradient-accent, #4fc3f7));\r\n}\r\n\r\n.tx-gradient-stop svg {\r\n display: block;\r\n width: 100%;\r\n height: 100%;\r\n overflow: visible;\r\n}\r\n\r\n/* a dark 1px outline outside the main one: the handle is visible on light bar colours behind it too / тёмная обводка в 1px снаружи основной: ручка видна и на светлых цветах полосы за ней */\r\n.tx-gradient-stop .tx-gradient-halo {\r\n fill: none;\r\n stroke: var(--tx-gradient-stop-outline, rgba(0, 0, 0, 0.85));\r\n stroke-width: 3.5;\r\n stroke-linejoin: round;\r\n}\r\n\r\n.tx-gradient-stop polygon:not(.tx-gradient-halo) {\r\n fill: currentColor; /* the stop colour is set by the component itself / цвет остановки задаёт сам компонент */\r\n stroke: var(--tx-gradient-stop-border, #5a606b);\r\n stroke-width: 1.5;\r\n stroke-linejoin: round;\r\n}\r\n\r\n/*\r\n * The selected handle: above the others (not hidden in a pile), slightly larger and with an accent stroke under it.\r\n * The fill stays the stop colour: the accent must not argue with it, so the outline is not coloured.\r\n * Выбранная ручка: выше остальных (в стопке не прячется), чуть крупнее и с акцентной черточкой под ней.\r\n * Заливка остаётся цветом остановки: акцент не должен спорить с ним, поэтому обводку не красим.\r\n */\r\n.tx-gradient-stop.on {\r\n z-index: 1;\r\n}\r\n\r\n.tx-gradient-stop.on svg {\r\n transform: scale(1.25);\r\n transform-origin: 50% 0;\r\n}\r\n\r\n.tx-gradient-stop.on::after {\r\n content: '';\r\n position: absolute;\r\n bottom: -6px;\r\n left: 50%;\r\n width: 12px;\r\n height: 2px;\r\n margin-left: -6px;\r\n border-radius: 1px;\r\n background: var(--tx-gradient-accent, #4fc3f7);\r\n}\r\n</style>\r\n"],"mappings":";;;AAeA,IAAM,QAAQ,UAAmD,MAAM,KAAK,OAAO;CAAE,GAAG;CAAG,OAAO,CAAC,GAAG,EAAE,KAAK;AAA2B,EAAE;;;;;AAM1I,IAAa,oBAAoB;;;;;;;AAQjC,IAAa,eAAe,cAA6C,cAAc,OAAO,OAAO,YAAY;;;;;AAMjH,IAAa,cAAc,GAAW,SAAA,MAAsD,QAAQ,KAAK,IAAI,GAAG,KAAK,IAAI,GAAG,CAAC,CAAC,GAAG,MAAM;;;;;AAMvI,SAAgB,UAAU,OAAgC,GAAW,OAA8B,YAAA,GAA8D;CAC7J,MAAM,OAAO,KAAK,KAAK;CACvB,MAAM,OAAO;EAAE,GAAG,KAAK;EAAK,GAAG;CAAM;CACrC,KAAK,QAAQ,WAAW,KAAK,OAAO,SAAS;CAC7C,KAAK,IAAI,QAAQ,KAAK,IAAI,GAAG,KAAK,IAAI,GAAG,KAAK,CAAC,CAAC,GAAG,SAAS;CAC5D,KAAK,QAAQ,KAAK,MAAM,KAAK,MAAM,QAAQ,GAAG,YAAY,SAAS,CAAC,CAAC;CACrE,KAAK,KAAK;CACV,OAAO;AACX;;;;;AAMA,SAAgB,eAAe,OAAgC,GAA6C;CACxG,MAAM,IAAI,MAAM;CAChB,IAAI,MAAM,GAAG,OAAO;EAAC;EAAG;EAAG;EAAG;CAAC;CAC/B,MAAM,IAAI,QAAQ,CAAC;CACnB,IAAI,IAAI,MAAM;CACd,IAAI,IAAI,MAAM;CACd,IAAI,IAAI;CACR,IAAI,KAAK,MAAM,IAAI,EAAE,CAAE,GACnB,IAAI,IAAI,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,UAAU,QAAQ,CAAC;KAC5B,eAAWK,eAAA,WAAO,WAAW,QAAQ,CAAC,GAAA,CAAA,MAAA,CAAA;KACtC,eAAa;KACb,aAAW;KACX,iBAAe;I,kCAGhBC,mBAGM,OAAA,EAHD,SAAQ,YAAW,GAAA,CACpBA,mBAAsE,WAAA;KAA7D,OAAM;KAAmB,QAAO;I,IACzCA,mBAA6C,WAAA,EAApC,QAAO,2BAA0B,CAAA,C"}
package/dist/swiperow.css CHANGED
@@ -2,12 +2,17 @@
2
2
  /*
3
3
  * Variables, on the row or on any element around it (the defaults stand in var(), so an ancestor's value reaches here):
4
4
  * --tx-swipe-bg the face of the row and the ground its actions are tinted on (the raised surface; a row right on
5
- * the page: var(--tao-color-bg))
6
- * --tx-swipe-radius the corners of the row (the panel radius)
5
+ * the page: the page background colour)
6
+ * --tx-swipe-radius the corners of the row (12px)
7
7
  * --tx-swipe-gap the gap between the end actions (6px)
8
+ * --tx-swipe-tone, --tx-swipe-tone-text, --tx-swipe-armed-text, --tx-swipe-accent
9
+ * the colour of an action (set on the action itself), its text, the text of an armed action and the
10
+ * focus ring; the TaoUI bridge maps them to the tone of the action
8
11
  * Переменные — на строке или на любом элементе вокруг неё (значения по умолчанию стоят в var(), поэтому значение предка
9
12
  * доходит сюда): --tx-swipe-bg — лицо строки и основа подкраски действий; --tx-swipe-radius — углы; --tx-swipe-gap —
10
- * зазор между действиями справа.
13
+ * зазор между действиями справа; --tx-swipe-tone, --tx-swipe-tone-text, --tx-swipe-armed-text, --tx-swipe-accent —
14
+ * цвет действия (задаётся на самом действии), его текст, текст сработавшего действия и кольцо фокуса; мост TaoUI
15
+ * наводит их на тон действия.
11
16
  */
12
17
  .tx-swipe {
13
18
  /* a stacking context of its own: the z-index of the face counts inside the row only, so a floating bar or a glass
@@ -16,8 +21,8 @@
16
21
  списком остаются поверх его строк */
17
22
  isolation: isolate;
18
23
  --_tx-swipe-gap: var(--tx-swipe-gap, 6px);
19
- --_tx-swipe-radius: var(--tx-swipe-radius, var(--tao-radius-panel, 12px));
20
- --_tx-swipe-bg: var(--tx-swipe-bg, var(--tao-color-surface-raised, #1f1f1f));
24
+ --_tx-swipe-radius: var(--tx-swipe-radius, 12px);
25
+ --_tx-swipe-bg: var(--tx-swipe-bg, #1f1f1f);
21
26
  position: relative;
22
27
  overflow: hidden;
23
28
  border-radius: var(--_tx-swipe-radius);
@@ -88,8 +93,8 @@
88
93
  overflow: hidden;
89
94
  border: 0;
90
95
  border-radius: var(--_tx-swipe-radius);
91
- background: color-mix(in srgb, var(--tao-tone) 22%, var(--_tx-swipe-bg));
92
- color: var(--tao-tone-text);
96
+ background: color-mix(in srgb, var(--tx-swipe-tone, #9ca3af) 22%, var(--_tx-swipe-bg));
97
+ color: var(--tx-swipe-tone-text, #d1d5db);
93
98
  font: inherit;
94
99
  font-size: 13px;
95
100
  cursor: pointer;
@@ -116,11 +121,11 @@
116
121
  padding-inline-start: 22px;
117
122
  }
118
123
  .tx-swipe__action--armed {
119
- background: color-mix(in srgb, var(--tao-tone) 45%, var(--_tx-swipe-bg));
120
- color: var(--tao-color-text-strong);
124
+ background: color-mix(in srgb, var(--tx-swipe-tone, #9ca3af) 45%, var(--_tx-swipe-bg));
125
+ color: var(--tx-swipe-armed-text, #fff);
121
126
  }
122
127
  .tx-swipe__action:focus-visible {
123
- outline: 2px solid var(--tao-color-accent);
128
+ outline: 2px solid var(--tx-swipe-accent, #4fc3f7);
124
129
  outline-offset: -2px;
125
130
  }
126
131