@1337exp/taoux 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +27 -0
- package/LICENSE +21 -0
- package/README.md +137 -2
- package/README.ru.md +140 -0
- package/dist/camera.d.ts +22 -0
- package/dist/camera.js +38 -0
- package/dist/camera.js.map +1 -0
- package/dist/canvas/TaoxCanvas.vue.d.ts +37 -0
- package/dist/canvas/host.d.ts +138 -0
- package/dist/canvas/index.d.ts +3 -0
- package/dist/canvas/useCanvasGestures.d.ts +44 -0
- package/dist/canvas.css +55 -0
- package/dist/canvas.js +696 -0
- package/dist/canvas.js.map +1 -0
- package/dist/chunks/curveeditor-goX9maE5.js +759 -0
- package/dist/chunks/curveeditor-goX9maE5.js.map +1 -0
- package/dist/curve.d.ts +53 -0
- package/dist/curve.js +81 -0
- package/dist/curve.js.map +1 -0
- package/dist/curveeditor/TaoxCurveEditor.vue.d.ts +74 -0
- package/dist/curveeditor/index.d.ts +3 -0
- package/dist/curveeditor/ops.d.ts +63 -0
- package/dist/curveeditor.css +115 -0
- package/dist/curveeditor.js +1 -0
- package/dist/curvefield/TaoxCurveField.vue.d.ts +64 -0
- package/dist/curvefield/index.d.ts +2 -0
- package/dist/curvefield/labels.d.ts +13 -0
- package/dist/curvefield.css +57 -0
- package/dist/curvefield.js +252 -0
- package/dist/curvefield.js.map +1 -0
- package/dist/ease.d.ts +62 -0
- package/dist/ease.js +157 -0
- package/dist/ease.js.map +1 -0
- package/dist/edgescroll.d.ts +77 -0
- package/dist/edgescroll.js +78 -0
- package/dist/edgescroll.js.map +1 -0
- package/dist/file.d.ts +10 -0
- package/dist/file.js +22 -0
- package/dist/file.js.map +1 -0
- package/dist/gestures.d.ts +174 -0
- package/dist/gestures.js +229 -0
- package/dist/gestures.js.map +1 -0
- package/dist/gradienteditor/TaoxGradientEditor.vue.d.ts +48 -0
- package/dist/gradienteditor/index.d.ts +2 -0
- package/dist/gradienteditor/ops.d.ts +83 -0
- package/dist/gradienteditor.css +81 -0
- package/dist/gradienteditor.js +337 -0
- package/dist/gradienteditor.js.map +1 -0
- package/dist/history.d.ts +42 -0
- package/dist/history.js +89 -0
- package/dist/history.js.map +1 -0
- package/dist/i18n.d.ts +51 -0
- package/dist/i18n.js +102 -0
- package/dist/i18n.js.map +1 -0
- package/dist/ids.d.ts +5 -0
- package/dist/ids.js +17 -0
- package/dist/ids.js.map +1 -0
- package/dist/links/TaoxLinks.vue.d.ts +14 -0
- package/dist/links/index.d.ts +2 -0
- package/dist/links/types.d.ts +37 -0
- package/dist/links.css +80 -0
- package/dist/links.js +72 -0
- package/dist/links.js.map +1 -0
- package/dist/num.d.ts +35 -0
- package/dist/num.js +60 -0
- package/dist/num.js.map +1 -0
- package/dist/palette.d.ts +34 -0
- package/dist/palette.js +41 -0
- package/dist/palette.js.map +1 -0
- package/dist/pins.d.ts +66 -0
- package/dist/pins.js +83 -0
- package/dist/pins.js.map +1 -0
- package/dist/playback/core.d.ts +81 -0
- package/dist/playback/index.d.ts +2 -0
- package/dist/playback/use.d.ts +38 -0
- package/dist/playback.js +199 -0
- package/dist/playback.js.map +1 -0
- package/dist/session.d.ts +125 -0
- package/dist/session.js +195 -0
- package/dist/session.js.map +1 -0
- package/dist/snap.d.ts +24 -0
- package/dist/snap.js +34 -0
- package/dist/snap.js.map +1 -0
- package/dist/storage.d.ts +16 -0
- package/dist/storage.js +30 -0
- package/dist/storage.js.map +1 -0
- package/dist/touch.d.ts +9 -0
- package/dist/touch.js +20 -0
- package/dist/touch.js.map +1 -0
- package/dist/wheel.d.ts +31 -0
- package/dist/wheel.js +47 -0
- package/dist/wheel.js.map +1 -0
- package/package.json +183 -4
- package/theme/taoui.css +43 -0
|
@@ -0,0 +1,337 @@
|
|
|
1
|
+
import { clamp01, roundTo } from "./num.js";
|
|
2
|
+
import { Fragment, createElementBlock, createElementVNode, defineComponent, nextTick, normalizeClass, normalizeStyle, openBlock, ref, renderList, unref, withModifiers } from "vue";
|
|
3
|
+
//#region src/gradienteditor/ops.ts
|
|
4
|
+
var copy = (stops) => stops.map((s) => ({
|
|
5
|
+
...s,
|
|
6
|
+
color: [...s.color]
|
|
7
|
+
}));
|
|
8
|
+
/**
|
|
9
|
+
* Default decimals of t and opacity: "0.5700000000000001" in a file is of use to nobody.
|
|
10
|
+
* Знаков после запятой по умолчанию у t и непрозрачности: «0.5700000000000001» в файле никому не нужно.
|
|
11
|
+
*/
|
|
12
|
+
var DEFAULT_PRECISION = 3;
|
|
13
|
+
/**
|
|
14
|
+
* 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
|
|
15
|
+
* (a linear step of 0.001 is 3 levels out of 255), so two more decimals are needed here: five when t has three.
|
|
16
|
+
* Знаков у компонент цвета при `precision` у t и непрозрачности. Цвет линейный, а в тёмной части шкалы sRGB круто растёт
|
|
17
|
+
* (шаг 0.001 линейного это 3 уровня из 255), поэтому тут нужно на два знака больше: при трёх у t это пять.
|
|
18
|
+
*/
|
|
19
|
+
var colorDigits = (precision) => precision === null ? null : precision + 2;
|
|
20
|
+
/**
|
|
21
|
+
* Opacity 0…1 with `digits` decimals (three by default).
|
|
22
|
+
* Непрозрачность 0…1 с `digits` знаками (по умолчанию три).
|
|
23
|
+
*/
|
|
24
|
+
var roundAlpha = (a, digits = 3) => roundTo(Math.min(1, Math.max(0, a)), digits);
|
|
25
|
+
/**
|
|
26
|
+
* Changes stop `i`; t and opacity are rounded to `precision` decimals (three by default; `null` turns it off), the colour to `precision + 2`.
|
|
27
|
+
* Меняет остановку `i`; t и непрозрачность округляются до `precision` знаков (по умолчанию три; `null` отключает), цвет до `precision + 2`.
|
|
28
|
+
*/
|
|
29
|
+
function patchStop(stops, i, patch, precision = 3) {
|
|
30
|
+
const next = copy(stops);
|
|
31
|
+
const stop = {
|
|
32
|
+
...next[i],
|
|
33
|
+
...patch
|
|
34
|
+
};
|
|
35
|
+
stop.alpha = roundAlpha(stop.alpha, precision);
|
|
36
|
+
stop.t = roundTo(Math.min(1, Math.max(0, stop.t)), precision);
|
|
37
|
+
stop.color = stop.color.map((c) => roundTo(c, colorDigits(precision)));
|
|
38
|
+
next[i] = stop;
|
|
39
|
+
return next;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* 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].
|
|
43
|
+
* Цвет и непрозрачность градиента в t: линейно между остановками, за краями равны крайней. Возвращает [r, g, b, a].
|
|
44
|
+
*/
|
|
45
|
+
function sampleGradient(stops, t) {
|
|
46
|
+
const n = stops.length;
|
|
47
|
+
if (n === 0) return [
|
|
48
|
+
1,
|
|
49
|
+
1,
|
|
50
|
+
1,
|
|
51
|
+
1
|
|
52
|
+
];
|
|
53
|
+
const x = clamp01(t);
|
|
54
|
+
let a = stops[0];
|
|
55
|
+
let b = stops[0];
|
|
56
|
+
let k = 0;
|
|
57
|
+
if (x >= stops[n - 1].t) a = b = stops[n - 1];
|
|
58
|
+
else if (x > stops[0].t) {
|
|
59
|
+
for (let i = 1; i < n; i++) if (x <= stops[i].t) {
|
|
60
|
+
a = stops[i - 1];
|
|
61
|
+
b = stops[i];
|
|
62
|
+
const span = b.t - a.t;
|
|
63
|
+
k = span <= 0 ? 1 : (x - a.t) / span;
|
|
64
|
+
break;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return [
|
|
68
|
+
a.color[0] + (b.color[0] - a.color[0]) * k,
|
|
69
|
+
a.color[1] + (b.color[1] - a.color[1]) * k,
|
|
70
|
+
a.color[2] + (b.color[2] - a.color[2]) * k,
|
|
71
|
+
a.alpha + (b.alpha - a.alpha) * k
|
|
72
|
+
];
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Moves stop `i` along t within its neighbours.
|
|
76
|
+
* Сдвигает остановку `i` по t в пределах соседей.
|
|
77
|
+
*/
|
|
78
|
+
function moveStop(stops, i, t, precision) {
|
|
79
|
+
const next = copy(stops);
|
|
80
|
+
const lo = i > 0 ? next[i - 1].t : 0;
|
|
81
|
+
const hi = i < next.length - 1 ? next[i + 1].t : 1;
|
|
82
|
+
next[i] = {
|
|
83
|
+
...next[i],
|
|
84
|
+
t: Math.min(hi, Math.max(lo, roundTo(clamp01(t), precision)))
|
|
85
|
+
};
|
|
86
|
+
return next;
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Adds a stop at `t` with the colour the gradient has at that point; returns the new list and the index.
|
|
90
|
+
* Добавляет остановку в `t` с цветом, который градиент имеет в этой точке; возвращает новый список и индекс.
|
|
91
|
+
*/
|
|
92
|
+
function addStop(stops, t, precision = 3) {
|
|
93
|
+
const x = roundTo(clamp01(t), precision);
|
|
94
|
+
const [r, g, b, a] = sampleGradient(stops, x);
|
|
95
|
+
const next = copy(stops);
|
|
96
|
+
const at = next.findIndex((s) => s.t > x);
|
|
97
|
+
const index = at === -1 ? next.length : at;
|
|
98
|
+
const d = colorDigits(precision);
|
|
99
|
+
next.splice(index, 0, {
|
|
100
|
+
t: x,
|
|
101
|
+
color: [
|
|
102
|
+
roundTo(r, d),
|
|
103
|
+
roundTo(g, d),
|
|
104
|
+
roundTo(b, d)
|
|
105
|
+
],
|
|
106
|
+
alpha: roundAlpha(a, precision)
|
|
107
|
+
});
|
|
108
|
+
return {
|
|
109
|
+
stops: next,
|
|
110
|
+
index
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Removes a stop; the last one is never removed.
|
|
115
|
+
* Убирает остановку; последнюю не убирает.
|
|
116
|
+
*/
|
|
117
|
+
function removeStop(stops, i) {
|
|
118
|
+
if (stops.length <= 1) return copy(stops);
|
|
119
|
+
return copy(stops.filter((_, k) => k !== i));
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Stops lying right next to stop `i` (within `px` pixels at bar width `width`), itself included: a pile of overlapping handles.
|
|
123
|
+
* Остановки, лежащие вплотную к остановке `i` (в пределах `px` пикселей при ширине полосы `width`), включая её саму: стопка наложенных ручек.
|
|
124
|
+
*/
|
|
125
|
+
function stackAround(stops, i, width, px) {
|
|
126
|
+
const here = stops[i]?.t ?? 0;
|
|
127
|
+
return stops.flatMap((s, k) => Math.abs(s.t - here) * width <= px ? [k] : []);
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* 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:
|
|
131
|
+
* the first to the left, the last to the right.
|
|
132
|
+
* Какую ручку из стопки взять, когда её потянули на `dx` пикселей. Порядок остановок менять нельзя, поэтому вытянуть можно
|
|
133
|
+
* только крайнюю: влево первую, вправо последнюю.
|
|
134
|
+
*/
|
|
135
|
+
function pickFromStack(cluster, dx) {
|
|
136
|
+
return dx < 0 ? Math.min(...cluster) : Math.max(...cluster);
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* Linear colour → sRGB, 0…1.
|
|
140
|
+
* Линейный цвет → sRGB, 0…1.
|
|
141
|
+
*/
|
|
142
|
+
var toSrgb = (c) => c <= .0031308 ? c * 12.92 : 1.055 * Math.pow(c, 1 / 2.4) - .055;
|
|
143
|
+
/**
|
|
144
|
+
* sRGB → linear colour, 0…1.
|
|
145
|
+
* sRGB → линейный цвет, 0…1.
|
|
146
|
+
*/
|
|
147
|
+
var toLinear = (c) => c <= .04045 ? c / 12.92 : Math.pow((c + .055) / 1.055, 2.4);
|
|
148
|
+
/**
|
|
149
|
+
* A CSS gradient for the preview bar (linear colour is converted to sRGB, alpha stays).
|
|
150
|
+
* CSS-градиент для полосы предпросмотра (линейный цвет переводится в sRGB, альфа остаётся).
|
|
151
|
+
*/
|
|
152
|
+
function gradientCss(stops) {
|
|
153
|
+
const srgb = (c) => Math.round(255 * toSrgb(Math.min(1, Math.max(0, c))));
|
|
154
|
+
return `linear-gradient(to right, ${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)}%`).join(", ")})`;
|
|
155
|
+
}
|
|
156
|
+
//#endregion
|
|
157
|
+
//#region src/gradienteditor/TaoxGradientEditor.vue?vue&type=script&setup=true&lang.ts
|
|
158
|
+
var _hoisted_1 = ["title"];
|
|
159
|
+
var _hoisted_2 = [
|
|
160
|
+
"aria-valuenow",
|
|
161
|
+
"aria-valuetext",
|
|
162
|
+
"aria-label",
|
|
163
|
+
"onFocus",
|
|
164
|
+
"onKeydown",
|
|
165
|
+
"onPointerdown"
|
|
166
|
+
];
|
|
167
|
+
var STACK_PX = 7;
|
|
168
|
+
/**
|
|
169
|
+
* The pointer shift (px) after which it is clear which way the pile is being dragged.
|
|
170
|
+
* Сдвиг указателя (px), после которого понятно, в какую сторону тащат стопку.
|
|
171
|
+
*/
|
|
172
|
+
var PICK_PX = 3;
|
|
173
|
+
//#endregion
|
|
174
|
+
//#region src/gradienteditor/TaoxGradientEditor.vue
|
|
175
|
+
var TaoxGradientEditor_default = /* @__PURE__ */ defineComponent({
|
|
176
|
+
__name: "TaoxGradientEditor",
|
|
177
|
+
props: {
|
|
178
|
+
modelValue: {},
|
|
179
|
+
selected: { default: 0 },
|
|
180
|
+
hint: {},
|
|
181
|
+
precision: { default: 3 },
|
|
182
|
+
keyStep: { default: .01 },
|
|
183
|
+
stopLabel: {}
|
|
184
|
+
},
|
|
185
|
+
emits: [
|
|
186
|
+
"update:modelValue",
|
|
187
|
+
"update:selected",
|
|
188
|
+
"commit"
|
|
189
|
+
],
|
|
190
|
+
setup(__props, { emit: __emit }) {
|
|
191
|
+
const props = __props;
|
|
192
|
+
const emit = __emit;
|
|
193
|
+
const bar = ref(null);
|
|
194
|
+
function tAt(e) {
|
|
195
|
+
const r = bar.value.getBoundingClientRect();
|
|
196
|
+
return (e.clientX - r.left) / r.width;
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* Handles closer than this distance (px) count as overlapping each other.
|
|
200
|
+
* Ручки ближе этого расстояния (px) считаются наложенными друг на друга.
|
|
201
|
+
*/
|
|
202
|
+
let dragging = -1;
|
|
203
|
+
/**
|
|
204
|
+
* A pile of overlapping handles was pressed: which one to take is decided by the first movement.
|
|
205
|
+
* Нажали на стопку наложенных ручек: какую из них взять, решает первое движение.
|
|
206
|
+
*/
|
|
207
|
+
let pending = null;
|
|
208
|
+
function onStopDown(e, i) {
|
|
209
|
+
if (e.altKey) {
|
|
210
|
+
emit("update:modelValue", removeStop(props.modelValue, i));
|
|
211
|
+
emit("update:selected", 0);
|
|
212
|
+
emit("commit");
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
emit("update:selected", i);
|
|
216
|
+
try {
|
|
217
|
+
e.currentTarget.setPointerCapture(e.pointerId);
|
|
218
|
+
} catch {}
|
|
219
|
+
const width = bar.value.getBoundingClientRect().width;
|
|
220
|
+
const cluster = stackAround(props.modelValue, i, width, STACK_PX);
|
|
221
|
+
dragging = i;
|
|
222
|
+
if (cluster.length > 1) pending = {
|
|
223
|
+
cluster,
|
|
224
|
+
x: e.clientX
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
function onMove(e) {
|
|
228
|
+
if (dragging < 0) return;
|
|
229
|
+
if (pending) {
|
|
230
|
+
const dx = e.clientX - pending.x;
|
|
231
|
+
if (Math.abs(dx) < PICK_PX) return;
|
|
232
|
+
dragging = pickFromStack(pending.cluster, dx);
|
|
233
|
+
pending = null;
|
|
234
|
+
emit("update:selected", dragging);
|
|
235
|
+
}
|
|
236
|
+
emit("update:modelValue", moveStop(props.modelValue, dragging, tAt(e), props.precision));
|
|
237
|
+
}
|
|
238
|
+
function onUp() {
|
|
239
|
+
if (dragging < 0) return;
|
|
240
|
+
const moved = pending === null;
|
|
241
|
+
dragging = -1;
|
|
242
|
+
pending = null;
|
|
243
|
+
if (moved) emit("commit");
|
|
244
|
+
}
|
|
245
|
+
const stopColor = (s) => `rgb(${s.color.map((c) => Math.round(255 * toSrgb(Math.min(1, Math.max(0, c))))).join(" ")})`;
|
|
246
|
+
/**
|
|
247
|
+
* Stop keys (focus on it): arrows move along t, Home/End to the start and end, Insert adds, Delete removes.
|
|
248
|
+
* Клавиши остановки (фокус на ней): стрелки двигают по t, Home/End в начало и конец, Insert добавляет, Delete убирает.
|
|
249
|
+
*/
|
|
250
|
+
function onStopKey(e, i) {
|
|
251
|
+
const stop = props.modelValue[i];
|
|
252
|
+
if (!stop) return;
|
|
253
|
+
const fine = props.keyStep * (e.shiftKey ? 10 : 1);
|
|
254
|
+
let to = null;
|
|
255
|
+
if (e.key === "ArrowLeft" || e.key === "ArrowDown") to = stop.t - fine;
|
|
256
|
+
else if (e.key === "ArrowRight" || e.key === "ArrowUp") to = stop.t + fine;
|
|
257
|
+
else if (e.key === "Home") to = 0;
|
|
258
|
+
else if (e.key === "End") to = 1;
|
|
259
|
+
if (to !== null) {
|
|
260
|
+
e.preventDefault();
|
|
261
|
+
emit("update:modelValue", moveStop(props.modelValue, i, to, props.precision));
|
|
262
|
+
emit("commit");
|
|
263
|
+
} else if (e.key === "Insert") {
|
|
264
|
+
e.preventDefault();
|
|
265
|
+
const other = props.modelValue[i + 1] ?? props.modelValue[i - 1];
|
|
266
|
+
if (!other) return;
|
|
267
|
+
const r = addStop(props.modelValue, (stop.t + other.t) / 2, props.precision);
|
|
268
|
+
emit("update:modelValue", r.stops);
|
|
269
|
+
emit("update:selected", r.index);
|
|
270
|
+
emit("commit");
|
|
271
|
+
focusStop(r.index);
|
|
272
|
+
} else if (e.key === "Delete" || e.key === "Backspace") {
|
|
273
|
+
e.preventDefault();
|
|
274
|
+
const next = Math.max(0, i - 1);
|
|
275
|
+
emit("update:modelValue", removeStop(props.modelValue, i));
|
|
276
|
+
emit("update:selected", next);
|
|
277
|
+
emit("commit");
|
|
278
|
+
focusStop(next);
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
/**
|
|
282
|
+
* Focus on handle `i` after a re-render: keys go to the selected one, and focus must not stay on the old one.
|
|
283
|
+
* Фокус на ручку `i` после перерисовки: клавиши идут к той, что выбрана, и фокус не должен оставаться на старой.
|
|
284
|
+
*/
|
|
285
|
+
function focusStop(i) {
|
|
286
|
+
nextTick(() => bar.value?.querySelectorAll(".tx-gradient-stop")[i]?.focus());
|
|
287
|
+
}
|
|
288
|
+
const labelOf = (i, s) => props.stopLabel ? props.stopLabel(i, s) : `Stop ${i + 1}`;
|
|
289
|
+
function onBarClick(e) {
|
|
290
|
+
if (e.target !== bar.value) return;
|
|
291
|
+
const r = addStop(props.modelValue, tAt(e), props.precision);
|
|
292
|
+
emit("update:modelValue", r.stops);
|
|
293
|
+
emit("update:selected", r.index);
|
|
294
|
+
emit("commit");
|
|
295
|
+
}
|
|
296
|
+
return (_ctx, _cache) => {
|
|
297
|
+
return openBlock(), createElementBlock("div", {
|
|
298
|
+
ref_key: "bar",
|
|
299
|
+
ref: bar,
|
|
300
|
+
class: "tx-gradient",
|
|
301
|
+
style: normalizeStyle({ backgroundImage: unref(gradientCss)(__props.modelValue) }),
|
|
302
|
+
title: __props.hint,
|
|
303
|
+
onClick: onBarClick
|
|
304
|
+
}, [(openBlock(true), createElementBlock(Fragment, null, renderList(__props.modelValue, (s, i) => {
|
|
305
|
+
return openBlock(), createElementBlock("span", {
|
|
306
|
+
key: i,
|
|
307
|
+
class: normalizeClass(["tx-gradient-stop", { on: i === __props.selected }]),
|
|
308
|
+
style: normalizeStyle({
|
|
309
|
+
left: `${s.t * 100}%`,
|
|
310
|
+
color: stopColor(s)
|
|
311
|
+
}),
|
|
312
|
+
tabindex: "0",
|
|
313
|
+
role: "slider",
|
|
314
|
+
"aria-orientation": "horizontal",
|
|
315
|
+
"aria-valuemin": "0",
|
|
316
|
+
"aria-valuemax": "1",
|
|
317
|
+
"aria-valuenow": s.t,
|
|
318
|
+
"aria-valuetext": `${Math.round(s.t * 100)}%`,
|
|
319
|
+
"aria-label": labelOf(i, s),
|
|
320
|
+
onFocus: ($event) => emit("update:selected", i),
|
|
321
|
+
onKeydown: ($event) => onStopKey($event, i),
|
|
322
|
+
onPointerdown: withModifiers(($event) => onStopDown($event, i), ["stop"]),
|
|
323
|
+
onPointermove: onMove,
|
|
324
|
+
onPointerup: onUp,
|
|
325
|
+
onPointercancel: onUp
|
|
326
|
+
}, [..._cache[0] || (_cache[0] = [createElementVNode("svg", { viewBox: "0 0 12 12" }, [createElementVNode("polygon", {
|
|
327
|
+
class: "tx-gradient-halo",
|
|
328
|
+
points: "6,0.5 11.5,11.5 0.5,11.5"
|
|
329
|
+
}), createElementVNode("polygon", { points: "6,0.5 11.5,11.5 0.5,11.5" })], -1)])], 46, _hoisted_2);
|
|
330
|
+
}), 128))], 12, _hoisted_1);
|
|
331
|
+
};
|
|
332
|
+
}
|
|
333
|
+
});
|
|
334
|
+
//#endregion
|
|
335
|
+
export { DEFAULT_PRECISION, TaoxGradientEditor_default as TaoxGradientEditor, addStop, colorDigits, gradientCss, moveStop, patchStop, pickFromStack, removeStop, roundAlpha, sampleGradient, stackAround, toLinear, toSrgb };
|
|
336
|
+
|
|
337
|
+
//# sourceMappingURL=gradienteditor.js.map
|
|
@@ -0,0 +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,GAAW,SAAA,MAAsD,QAAQ,KA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Q;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"}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Edits with the same key made faster than this many ms apart merge into one entry (typing a number into a field and the like).
|
|
3
|
+
* Правки с одним ключом, сделанные чаще чем раз в столько мс, склеиваются в одну запись (набор числа в поле и т.п.).
|
|
4
|
+
*/
|
|
5
|
+
export declare const COALESCE_MS = 800;
|
|
6
|
+
/**
|
|
7
|
+
* Undo/redo state history: a linear list of snapshots and a pointer to the current one.
|
|
8
|
+
* Snapshots are strings (graph JSON): they are immutable, easy to compare and need no copying.
|
|
9
|
+
* История состояний для undo/redo: линейный список снимков и указатель на текущий.
|
|
10
|
+
* Снимки — строки (JSON графа): они неизменяемы, их легко сравнивать и не нужно копировать.
|
|
11
|
+
*/
|
|
12
|
+
export declare class History {
|
|
13
|
+
private readonly limit;
|
|
14
|
+
private readonly now;
|
|
15
|
+
private states;
|
|
16
|
+
private index;
|
|
17
|
+
private lastKey;
|
|
18
|
+
private lastTime;
|
|
19
|
+
constructor(initial: string, limit?: number, now?: () => number);
|
|
20
|
+
get canUndo(): boolean;
|
|
21
|
+
get canRedo(): boolean;
|
|
22
|
+
/**
|
|
23
|
+
* Records a new state. If it does not differ from the current one, does nothing (returns false).
|
|
24
|
+
* An edit discards the "future" (redo). With the same `key` in a row and within `COALESCE_MS`,
|
|
25
|
+
* edits replace each other instead of piling up.
|
|
26
|
+
* Записывает новое состояние. Если оно не отличается от текущего, ничего не делает (вернёт false).
|
|
27
|
+
* Правка отбрасывает «будущее» (redo). С одинаковым `key` подряд и в пределах `COALESCE_MS`
|
|
28
|
+
* правки заменяют друг друга, а не копятся.
|
|
29
|
+
*/
|
|
30
|
+
commit(state: string, key?: string): boolean;
|
|
31
|
+
/**
|
|
32
|
+
* Returns the previous state, or null if there is nothing to undo.
|
|
33
|
+
* Возвращает предыдущее состояние или null, если отменять нечего.
|
|
34
|
+
*/
|
|
35
|
+
undo(): string | null;
|
|
36
|
+
redo(): string | null;
|
|
37
|
+
/**
|
|
38
|
+
* Start the history over (for example, after loading a file).
|
|
39
|
+
* Начать историю заново (например, после загрузки файла).
|
|
40
|
+
*/
|
|
41
|
+
reset(state: string): void;
|
|
42
|
+
}
|
package/dist/history.js
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
//#region src/history.ts
|
|
2
|
+
/**
|
|
3
|
+
* Edits with the same key made faster than this many ms apart merge into one entry (typing a number into a field and the like).
|
|
4
|
+
* Правки с одним ключом, сделанные чаще чем раз в столько мс, склеиваются в одну запись (набор числа в поле и т.п.).
|
|
5
|
+
*/
|
|
6
|
+
var COALESCE_MS = 800;
|
|
7
|
+
/**
|
|
8
|
+
* Undo/redo state history: a linear list of snapshots and a pointer to the current one.
|
|
9
|
+
* Snapshots are strings (graph JSON): they are immutable, easy to compare and need no copying.
|
|
10
|
+
* История состояний для undo/redo: линейный список снимков и указатель на текущий.
|
|
11
|
+
* Снимки — строки (JSON графа): они неизменяемы, их легко сравнивать и не нужно копировать.
|
|
12
|
+
*/
|
|
13
|
+
var History = class {
|
|
14
|
+
limit;
|
|
15
|
+
now;
|
|
16
|
+
states;
|
|
17
|
+
index = 0;
|
|
18
|
+
lastKey;
|
|
19
|
+
lastTime = 0;
|
|
20
|
+
constructor(initial, limit = 100, now = Date.now) {
|
|
21
|
+
this.limit = limit;
|
|
22
|
+
this.now = now;
|
|
23
|
+
this.states = [initial];
|
|
24
|
+
}
|
|
25
|
+
get canUndo() {
|
|
26
|
+
return this.index > 0;
|
|
27
|
+
}
|
|
28
|
+
get canRedo() {
|
|
29
|
+
return this.index < this.states.length - 1;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Records a new state. If it does not differ from the current one, does nothing (returns false).
|
|
33
|
+
* An edit discards the "future" (redo). With the same `key` in a row and within `COALESCE_MS`,
|
|
34
|
+
* edits replace each other instead of piling up.
|
|
35
|
+
* Записывает новое состояние. Если оно не отличается от текущего, ничего не делает (вернёт false).
|
|
36
|
+
* Правка отбрасывает «будущее» (redo). С одинаковым `key` подряд и в пределах `COALESCE_MS`
|
|
37
|
+
* правки заменяют друг друга, а не копятся.
|
|
38
|
+
*/
|
|
39
|
+
commit(state, key) {
|
|
40
|
+
if (state === this.states[this.index]) return false;
|
|
41
|
+
const t = this.now();
|
|
42
|
+
const atTop = this.index === this.states.length - 1;
|
|
43
|
+
if (key !== void 0 && key === this.lastKey && t - this.lastTime <= 800 && this.index > 0 && atTop) {
|
|
44
|
+
this.states[this.index] = state;
|
|
45
|
+
if (this.states[this.index - 1] === state) {
|
|
46
|
+
this.states.pop();
|
|
47
|
+
this.index--;
|
|
48
|
+
}
|
|
49
|
+
} else {
|
|
50
|
+
this.states.length = this.index + 1;
|
|
51
|
+
this.states.push(state);
|
|
52
|
+
this.index++;
|
|
53
|
+
if (this.states.length > this.limit + 1) {
|
|
54
|
+
this.states.shift();
|
|
55
|
+
this.index--;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
this.lastKey = key;
|
|
59
|
+
this.lastTime = t;
|
|
60
|
+
return true;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Returns the previous state, or null if there is nothing to undo.
|
|
64
|
+
* Возвращает предыдущее состояние или null, если отменять нечего.
|
|
65
|
+
*/
|
|
66
|
+
undo() {
|
|
67
|
+
if (!this.canUndo) return null;
|
|
68
|
+
this.lastKey = void 0;
|
|
69
|
+
return this.states[--this.index];
|
|
70
|
+
}
|
|
71
|
+
redo() {
|
|
72
|
+
if (!this.canRedo) return null;
|
|
73
|
+
this.lastKey = void 0;
|
|
74
|
+
return this.states[++this.index];
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Start the history over (for example, after loading a file).
|
|
78
|
+
* Начать историю заново (например, после загрузки файла).
|
|
79
|
+
*/
|
|
80
|
+
reset(state) {
|
|
81
|
+
this.states = [state];
|
|
82
|
+
this.index = 0;
|
|
83
|
+
this.lastKey = void 0;
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
//#endregion
|
|
87
|
+
export { COALESCE_MS, History };
|
|
88
|
+
|
|
89
|
+
//# sourceMappingURL=history.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"history.js","names":[],"sources":["../src/history.ts"],"sourcesContent":["/**\n * Edits with the same key made faster than this many ms apart merge into one entry (typing a number into a field and the like).\n * Правки с одним ключом, сделанные чаще чем раз в столько мс, склеиваются в одну запись (набор числа в поле и т.п.).\n */\nexport const COALESCE_MS = 800;\n\n/**\n * Undo/redo state history: a linear list of snapshots and a pointer to the current one.\n * Snapshots are strings (graph JSON): they are immutable, easy to compare and need no copying.\n * История состояний для undo/redo: линейный список снимков и указатель на текущий.\n * Снимки — строки (JSON графа): они неизменяемы, их легко сравнивать и не нужно копировать.\n */\nexport class History {\n private states: string[];\n private index = 0;\n private lastKey: string | undefined;\n private lastTime = 0;\n\n constructor(\n initial: string,\n private readonly limit = 100,\n private readonly now: () => number = Date.now,\n ) {\n this.states = [initial];\n }\n\n get canUndo(): boolean {\n return this.index > 0;\n }\n\n get canRedo(): boolean {\n return this.index < this.states.length - 1;\n }\n\n /**\n * Records a new state. If it does not differ from the current one, does nothing (returns false).\n * An edit discards the \"future\" (redo). With the same `key` in a row and within `COALESCE_MS`,\n * edits replace each other instead of piling up.\n * Записывает новое состояние. Если оно не отличается от текущего, ничего не делает (вернёт false).\n * Правка отбрасывает «будущее» (redo). С одинаковым `key` подряд и в пределах `COALESCE_MS`\n * правки заменяют друг друга, а не копятся.\n */\n commit(state: string, key?: string): boolean {\n if (state === this.states[this.index]) return false;\n\n const t = this.now();\n const atTop = this.index === this.states.length - 1;\n const coalesce = key !== undefined && key === this.lastKey && t - this.lastTime <= COALESCE_MS && this.index > 0 && atTop;\n\n if (coalesce) {\n this.states[this.index] = state;\n // Back to the state before the series of edits: no entry is needed.\n // Вернулись к состоянию до серии правок: запись не нужна.\n if (this.states[this.index - 1] === state) {\n this.states.pop();\n this.index--;\n }\n } else {\n this.states.length = this.index + 1;\n this.states.push(state);\n this.index++;\n if (this.states.length > this.limit + 1) {\n this.states.shift();\n this.index--;\n }\n }\n\n this.lastKey = key;\n this.lastTime = t;\n return true;\n }\n\n /**\n * Returns the previous state, or null if there is nothing to undo.\n * Возвращает предыдущее состояние или null, если отменять нечего.\n */\n undo(): string | null {\n if (!this.canUndo) return null;\n this.lastKey = undefined;\n return this.states[--this.index]!;\n }\n\n redo(): string | null {\n if (!this.canRedo) return null;\n this.lastKey = undefined;\n return this.states[++this.index]!;\n }\n\n /**\n * Start the history over (for example, after loading a file).\n * Начать историю заново (например, после загрузки файла).\n */\n reset(state: string): void {\n this.states = [state];\n this.index = 0;\n this.lastKey = undefined;\n }\n}\n"],"mappings":";;;;;AAIA,IAAa,cAAc;;;;;;;AAQ3B,IAAa,UAAb,MAAqB;CAQI;CACA;CARrB;CACA,QAAgB;CAChB;CACA,WAAmB;CAEnB,YACI,SACA,QAAyB,KACzB,MAAqC,KAAK,KAC5C;EAFmB,KAAA,QAAA;EACA,KAAA,MAAA;EAEjB,KAAK,SAAS,CAAC,OAAO;CAC1B;CAEA,IAAI,UAAmB;EACnB,OAAO,KAAK,QAAQ;CACxB;CAEA,IAAI,UAAmB;EACnB,OAAO,KAAK,QAAQ,KAAK,OAAO,SAAS;CAC7C;;;;;;;;;CAUA,OAAO,OAAe,KAAuB;EACzC,IAAI,UAAU,KAAK,OAAO,KAAK,QAAQ,OAAO;EAE9C,MAAM,IAAI,KAAK,IAAI;EACnB,MAAM,QAAQ,KAAK,UAAU,KAAK,OAAO,SAAS;EAGlD,IAFiB,QAAQ,KAAA,KAAa,QAAQ,KAAK,WAAW,IAAI,KAAK,YAAA,OAA2B,KAAK,QAAQ,KAAK,OAEtG;GACV,KAAK,OAAO,KAAK,SAAS;GAG1B,IAAI,KAAK,OAAO,KAAK,QAAQ,OAAO,OAAO;IACvC,KAAK,OAAO,IAAI;IAChB,KAAK;GACT;EACJ,OAAO;GACH,KAAK,OAAO,SAAS,KAAK,QAAQ;GAClC,KAAK,OAAO,KAAK,KAAK;GACtB,KAAK;GACL,IAAI,KAAK,OAAO,SAAS,KAAK,QAAQ,GAAG;IACrC,KAAK,OAAO,MAAM;IAClB,KAAK;GACT;EACJ;EAEA,KAAK,UAAU;EACf,KAAK,WAAW;EAChB,OAAO;CACX;;;;;CAMA,OAAsB;EAClB,IAAI,CAAC,KAAK,SAAS,OAAO;EAC1B,KAAK,UAAU,KAAA;EACf,OAAO,KAAK,OAAO,EAAE,KAAK;CAC9B;CAEA,OAAsB;EAClB,IAAI,CAAC,KAAK,SAAS,OAAO;EAC1B,KAAK,UAAU,KAAA;EACf,OAAO,KAAK,OAAO,EAAE,KAAK;CAC9B;;;;;CAMA,MAAM,OAAqB;EACvB,KAAK,SAAS,CAAC,KAAK;EACpB,KAAK,QAAQ;EACb,KAAK,UAAU,KAAA;CACnB;AACJ"}
|
package/dist/i18n.d.ts
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { type ComputedRef, type Ref } from 'vue';
|
|
2
|
+
/**
|
|
3
|
+
* All dot-separated paths to dictionary strings: 'file.save', 'link.arrow', ...
|
|
4
|
+
* Все пути до строк словаря через точку: 'file.save', 'link.arrow', ...
|
|
5
|
+
*/
|
|
6
|
+
export type Paths<T, P extends string = ''> = {
|
|
7
|
+
[K in keyof T & string]: T[K] extends string ? `${P}${K}` : Paths<T[K], `${P}${K}.`>;
|
|
8
|
+
}[keyof T & string];
|
|
9
|
+
export type MessageArgs = readonly (string | number)[];
|
|
10
|
+
export interface I18nOptions<L extends Record<string, object>> {
|
|
11
|
+
/**
|
|
12
|
+
* Dictionaries by language code. The other dictionaries must repeat the structure of any one of them.
|
|
13
|
+
* Словари по кодам языков. Остальные словари должны повторять структуру любого из них.
|
|
14
|
+
*/
|
|
15
|
+
locales: L;
|
|
16
|
+
/**
|
|
17
|
+
* The language to fall back to when the key is missing in the chosen one.
|
|
18
|
+
* Язык, на который падаем, если ключа нет в выбранном.
|
|
19
|
+
*/
|
|
20
|
+
fallback: keyof L & string;
|
|
21
|
+
/**
|
|
22
|
+
* The localStorage key for the user's choice.
|
|
23
|
+
* Ключ localStorage для выбора пользователя.
|
|
24
|
+
*/
|
|
25
|
+
storageKey: string;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Typed i18n on object dictionaries. Texts and language codes belong to the app,
|
|
29
|
+
* only the mechanics are here: translation with `{0}` arguments, a fallback language, language choice and remembering it.
|
|
30
|
+
* Типизированный i18n на словарях-объектах. Тексты и коды языков принадлежат приложению,
|
|
31
|
+
* здесь только механика: перевод с `{0}`-аргументами, запасной язык, выбор языка и его запоминание.
|
|
32
|
+
*
|
|
33
|
+
* `K` is the type of allowed keys. By default it is all dictionary paths; narrow it if the dictionary has
|
|
34
|
+
* branches that are not translated through `t()` (for example, node texts).
|
|
35
|
+
* `K` — тип допустимых ключей. По умолчанию это все пути словарей; сузьте, если в словаре есть
|
|
36
|
+
* ветки, которые не переводятся через `t()` (например, тексты нод).
|
|
37
|
+
*/
|
|
38
|
+
export declare function createI18n<L extends Record<string, object>, K extends string = Paths<L[keyof L & string]>>(options: I18nOptions<L>): {
|
|
39
|
+
codes: (keyof L & string)[];
|
|
40
|
+
current: Ref<keyof L & string, keyof L & string>;
|
|
41
|
+
isLocaleCode: (value: unknown) => value is keyof L & string;
|
|
42
|
+
detectLocale: (languages: readonly string[]) => keyof L & string;
|
|
43
|
+
applyLocale: (code: keyof L & string) => void;
|
|
44
|
+
setLocale: (code: keyof L & string) => void;
|
|
45
|
+
initLocale: () => keyof L & string;
|
|
46
|
+
translate: (code: keyof L & string, key: K, args?: MessageArgs) => string;
|
|
47
|
+
useI18n: () => {
|
|
48
|
+
locale: ComputedRef<keyof L & string>;
|
|
49
|
+
t: (key: K, args?: MessageArgs) => string;
|
|
50
|
+
};
|
|
51
|
+
};
|