@1337exp/taoux 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/LICENSE +21 -0
  3. package/README.md +137 -2
  4. package/README.ru.md +140 -0
  5. package/dist/camera.d.ts +22 -0
  6. package/dist/camera.js +38 -0
  7. package/dist/camera.js.map +1 -0
  8. package/dist/canvas/TaoxCanvas.vue.d.ts +37 -0
  9. package/dist/canvas/host.d.ts +138 -0
  10. package/dist/canvas/index.d.ts +3 -0
  11. package/dist/canvas/useCanvasGestures.d.ts +44 -0
  12. package/dist/canvas.css +55 -0
  13. package/dist/canvas.js +696 -0
  14. package/dist/canvas.js.map +1 -0
  15. package/dist/chunks/curveeditor-F3XBWHPL.js +759 -0
  16. package/dist/chunks/curveeditor-F3XBWHPL.js.map +1 -0
  17. package/dist/curve.d.ts +53 -0
  18. package/dist/curve.js +81 -0
  19. package/dist/curve.js.map +1 -0
  20. package/dist/curveeditor/TaoxCurveEditor.vue.d.ts +74 -0
  21. package/dist/curveeditor/index.d.ts +3 -0
  22. package/dist/curveeditor/ops.d.ts +63 -0
  23. package/dist/curveeditor.css +115 -0
  24. package/dist/curveeditor.js +1 -0
  25. package/dist/curvefield/TaoxCurveField.vue.d.ts +64 -0
  26. package/dist/curvefield/index.d.ts +2 -0
  27. package/dist/curvefield/labels.d.ts +13 -0
  28. package/dist/curvefield.css +57 -0
  29. package/dist/curvefield.js +252 -0
  30. package/dist/curvefield.js.map +1 -0
  31. package/dist/ease.d.ts +62 -0
  32. package/dist/ease.js +157 -0
  33. package/dist/ease.js.map +1 -0
  34. package/dist/edgescroll.d.ts +77 -0
  35. package/dist/edgescroll.js +78 -0
  36. package/dist/edgescroll.js.map +1 -0
  37. package/dist/file.d.ts +10 -0
  38. package/dist/file.js +22 -0
  39. package/dist/file.js.map +1 -0
  40. package/dist/gestures.d.ts +174 -0
  41. package/dist/gestures.js +229 -0
  42. package/dist/gestures.js.map +1 -0
  43. package/dist/gradienteditor/TaoxGradientEditor.vue.d.ts +48 -0
  44. package/dist/gradienteditor/index.d.ts +2 -0
  45. package/dist/gradienteditor/ops.d.ts +83 -0
  46. package/dist/gradienteditor.css +81 -0
  47. package/dist/gradienteditor.js +337 -0
  48. package/dist/gradienteditor.js.map +1 -0
  49. package/dist/history.d.ts +42 -0
  50. package/dist/history.js +89 -0
  51. package/dist/history.js.map +1 -0
  52. package/dist/i18n.d.ts +51 -0
  53. package/dist/i18n.js +102 -0
  54. package/dist/i18n.js.map +1 -0
  55. package/dist/ids.d.ts +5 -0
  56. package/dist/ids.js +17 -0
  57. package/dist/ids.js.map +1 -0
  58. package/dist/links/TaoxLinks.vue.d.ts +14 -0
  59. package/dist/links/index.d.ts +2 -0
  60. package/dist/links/types.d.ts +37 -0
  61. package/dist/links.css +80 -0
  62. package/dist/links.js +72 -0
  63. package/dist/links.js.map +1 -0
  64. package/dist/num.d.ts +35 -0
  65. package/dist/num.js +60 -0
  66. package/dist/num.js.map +1 -0
  67. package/dist/palette.d.ts +34 -0
  68. package/dist/palette.js +41 -0
  69. package/dist/palette.js.map +1 -0
  70. package/dist/pins.d.ts +66 -0
  71. package/dist/pins.js +83 -0
  72. package/dist/pins.js.map +1 -0
  73. package/dist/playback/core.d.ts +81 -0
  74. package/dist/playback/index.d.ts +2 -0
  75. package/dist/playback/use.d.ts +38 -0
  76. package/dist/playback.js +199 -0
  77. package/dist/playback.js.map +1 -0
  78. package/dist/session.d.ts +125 -0
  79. package/dist/session.js +195 -0
  80. package/dist/session.js.map +1 -0
  81. package/dist/snap.d.ts +24 -0
  82. package/dist/snap.js +34 -0
  83. package/dist/snap.js.map +1 -0
  84. package/dist/storage.d.ts +16 -0
  85. package/dist/storage.js +30 -0
  86. package/dist/storage.js.map +1 -0
  87. package/dist/touch.d.ts +9 -0
  88. package/dist/touch.js +20 -0
  89. package/dist/touch.js.map +1 -0
  90. package/dist/wheel.d.ts +31 -0
  91. package/dist/wheel.js +47 -0
  92. package/dist/wheel.js.map +1 -0
  93. package/package.json +183 -4
  94. package/theme/taoui.css +43 -0
package/dist/canvas.js ADDED
@@ -0,0 +1,696 @@
1
+ import { panBy, screenToWorld, zoomAt } from "./camera.js";
2
+ import "./snap.js";
3
+ import { createEdgeScroller } from "./edgescroll.js";
4
+ import { PinchTracker, TapRecognizer, pinchOf } from "./gestures.js";
5
+ import { wheelIntent } from "./wheel.js";
6
+ import { computed, createCommentVNode, createElementBlock, createElementVNode, defineComponent, normalizeClass, normalizeStyle, onMounted, onUnmounted, openBlock, ref, renderSlot, toDisplayString, unref, watch, withModifiers } from "vue";
7
+ //#region src/canvas/useCanvasGestures.ts
8
+ var PAN_CLICK_THRESHOLD = 4;
9
+ /**
10
+ * The canvas gesture machine: mouse, touch (tap, double tap, long press, pinch), wheel, auto-scroll at the edge,
11
+ * keys. It does not know the data model: the app decides through `host`.
12
+ * The host is taken once at creation: it must be a stable object.
13
+ * Машина жестов холста: мышь, сенсор (тап, двойной тап, долгое нажатие, щипок), колесо, автопрокрутка у края,
14
+ * клавиши. Не знает модель данных: решения принимает приложение через `host`.
15
+ * Хост берётся один раз при создании: он должен быть стабильным объектом.
16
+ */
17
+ function useCanvasGestures(root, host, options) {
18
+ let mode = "idle";
19
+ let lastX = 0;
20
+ let lastY = 0;
21
+ let baseSelection = [];
22
+ let panDistance = 0;
23
+ /**
24
+ * Alt is held: grid snapping is temporarily off. Remembered so that auto-scroll (no event) knows it too.
25
+ * Alt зажат: привязка к сетке временно отключена. Запоминаем, чтобы автопрокрутка (без события) тоже знала.
26
+ */
27
+ let altDown = false;
28
+ const snapNow = () => (host.snapEnabled ?? false) && !altDown;
29
+ let resizeId = "";
30
+ let resizeEdge = "se";
31
+ let resizeStart = {
32
+ x: 0,
33
+ y: 0,
34
+ w: 0,
35
+ h: 0
36
+ };
37
+ /**
38
+ * Mouse shift since the resize began, world units.
39
+ * Сдвиг мыши с начала изменения размера, мировые единицы.
40
+ */
41
+ let resizeDx = 0;
42
+ let resizeDy = 0;
43
+ const touches = /* @__PURE__ */ new Map();
44
+ const taps = new TapRecognizer();
45
+ let longPressTimer;
46
+ let lastTouchAt = 0;
47
+ const pinch = new PinchTracker();
48
+ /**
49
+ * The node a finger landed on: its selection and raise are postponed until the intent is clear. The touch may still
50
+ * turn out to be the start of a two-finger gesture, and then the user's existing selection must not be lost.
51
+ * We select when the finger started dragging (left the slop) or was lifted (tap, hold).
52
+ * Нода, на которую лёг палец: её выделение и подъём откладываются, пока не ясно намерение. Касание ещё может
53
+ * оказаться началом жеста двумя пальцами, и тогда выделение, которое было у пользователя, не должно слететь.
54
+ * Выделяем, когда палец пошёл тянуть (вышел за допуск) или поднят (тап, удержание).
55
+ */
56
+ let armed = null;
57
+ /**
58
+ * The link a finger landed on: as with a node, it is selected only if this is a tap (the finger did not go to move the canvas).
59
+ * Связь, на которую лёг палец: как с нодой, выбираем её только если это тап (палец не пошёл двигать холст).
60
+ */
61
+ let armedConn = null;
62
+ /**
63
+ * `?debug=touch`: the last recognised gesture and the number of fingers show in the corner.
64
+ * `?debug=touch`: в углу видно последний распознанный жест и число пальцев.
65
+ */
66
+ const debug = typeof location !== "undefined" && new URLSearchParams(location.search).get("debug") === "touch";
67
+ const debugText = ref("");
68
+ const note = (label) => {
69
+ if (debug) debugText.value = `${label} · fingers: ${touches.size}`;
70
+ };
71
+ const marquee = ref(null);
72
+ const nodeIdAt = (target) => target?.closest("[data-node-id]")?.dataset.nodeId ?? null;
73
+ const connIdAt = (target) => target?.closest("[data-conn-id]")?.dataset.connId ?? null;
74
+ /**
75
+ * Input fields inside nodes: a click on them selects the node but does not drag it and does not take focus away.
76
+ * Поля ввода внутри нод: клик по ним выделяет ноду, но не тащит её и не отбирает фокус.
77
+ */
78
+ const isEditable = (target) => !!target?.closest("input, textarea, select, button, [contenteditable=\"true\"]");
79
+ /**
80
+ * The pin under the cursor: the nearest pin (if the app can) or the one exactly under the pointer.
81
+ * Пин под курсором: ближайший пин (если приложение умеет) или тот, что точно под указателем.
82
+ */
83
+ const pinUnder = (e) => options.pinNear?.(e) ?? options.pinAt(document.elementFromPoint(e.clientX, e.clientY));
84
+ function cursorWorld(e) {
85
+ const rect = root.value.getBoundingClientRect();
86
+ return screenToWorld(host.camera, e.clientX - rect.left, e.clientY - rect.top);
87
+ }
88
+ function openPaletteAt(e, origin) {
89
+ const rect = root.value.getBoundingClientRect();
90
+ host.openPalette([e.clientX - rect.left, e.clientY - rect.top], cursorWorld(e), origin);
91
+ }
92
+ function nodesInMarquee() {
93
+ const m = marquee.value;
94
+ if (!m || !root.value) return [];
95
+ const left = Math.min(m.x0, m.x1);
96
+ const right = Math.max(m.x0, m.x1);
97
+ const top = Math.min(m.y0, m.y1);
98
+ const bottom = Math.max(m.y0, m.y1);
99
+ const ids = [];
100
+ for (const el of root.value.querySelectorAll("[data-node-id]")) {
101
+ const r = (el.hasAttribute("data-node-container") ? el.querySelector("[data-node-handle]") ?? el : el).getBoundingClientRect();
102
+ if (r.left < right && r.right > left && r.top < bottom && r.bottom > top) ids.push(el.dataset.nodeId);
103
+ }
104
+ return ids;
105
+ }
106
+ const sampleOf = (e) => ({
107
+ x: e.clientX,
108
+ y: e.clientY,
109
+ t: performance.now()
110
+ });
111
+ function capture(e) {
112
+ try {
113
+ root.value?.setPointerCapture(e.pointerId);
114
+ } catch {}
115
+ }
116
+ function releaseCapture(e) {
117
+ try {
118
+ root.value?.releasePointerCapture(e.pointerId);
119
+ } catch {}
120
+ }
121
+ function clearLongPress() {
122
+ clearTimeout(longPressTimer);
123
+ longPressTimer = void 0;
124
+ }
125
+ /**
126
+ * A second finger landed on the canvas: the gesture in progress is cancelled and a pinch begins. Returns true if the event was handled.
127
+ * Второй палец лёг на холст: начатый жест отменяется, начинается щипок. Возвращает true, если событие обработано.
128
+ */
129
+ function touchDown(e) {
130
+ if (e.isPrimary) {
131
+ touches.clear();
132
+ armed = null;
133
+ armedConn = null;
134
+ if (mode !== "idle") abortGesture();
135
+ }
136
+ touches.set(e.pointerId, {
137
+ x: e.clientX,
138
+ y: e.clientY
139
+ });
140
+ if (touches.size < 2) return false;
141
+ host.closePalette();
142
+ abortGesture();
143
+ mode = "pinch";
144
+ rebasePinch();
145
+ capture(e);
146
+ e.preventDefault();
147
+ note("pinch");
148
+ return true;
149
+ }
150
+ /**
151
+ * A finger landed on the canvas (the first one): remembered for a tap, and the long-press timer is set. Returns true for a second tap in a row.
152
+ * Палец лёг на холст (первый): запоминаем для тапа и ставим таймер долгого нажатия. Возвращает true для второго тапа подряд.
153
+ */
154
+ function beginTouch(e) {
155
+ clearLongPress();
156
+ const doubleDown = taps.down(sampleOf(e));
157
+ longPressTimer = setTimeout(onLongPress, 500);
158
+ return doubleDown;
159
+ }
160
+ /**
161
+ * A finger lies on an empty place without moving: this is the touch right click, the palette opens.
162
+ * Палец лежит на пустом месте и не двигается: это правый клик сенсора, открываем палитру.
163
+ */
164
+ function onLongPress() {
165
+ longPressTimer = void 0;
166
+ if (mode !== "pan" || !taps.longPressDue(performance.now() + 50)) return;
167
+ taps.cancel();
168
+ mode = "idle";
169
+ navigator.vibrate?.(15);
170
+ openPaletteAt({
171
+ clientX: lastX,
172
+ clientY: lastY
173
+ }, null);
174
+ note("long press");
175
+ }
176
+ /**
177
+ * A finger was lifted or cancelled anywhere in the window, not only over the canvas: for example, over a palette that opened
178
+ * under it. The canvas must stop counting this finger as lying down, otherwise it stays "the second" forever.
179
+ * Палец поднят или отменён где угодно в окне, а не только над холстом: например, над палитрой, которая открылась
180
+ * под ним. Холст должен перестать считать этот палец лежащим, иначе он останется «вторым» навсегда.
181
+ */
182
+ function purgeTouch(e) {
183
+ if (e.pointerType !== "touch" || !touches.delete(e.pointerId)) return;
184
+ if (mode !== "pinch") return;
185
+ if (touches.size === 0) mode = "idle";
186
+ else rebasePinch();
187
+ }
188
+ /**
189
+ * The intent became clear (the finger started dragging or was lifted): select and raise the node it landed on.
190
+ * Намерение стало ясно (палец пошёл тянуть или поднят): выделяем и поднимаем ноду, на которую он лёг.
191
+ */
192
+ function commitArmed() {
193
+ const id = armed;
194
+ armed = null;
195
+ if (!id) return;
196
+ host.selectConnection(null);
197
+ if (mode === "resize" || !host.selection.has(id)) host.setSelection([id]);
198
+ host.raise?.(id);
199
+ if (mode === "drag") host.beginDrag(id);
200
+ }
201
+ /**
202
+ * A finger was lifted. Returns true if the event was handled entirely (a pinch is going on).
203
+ * Палец поднят. Возвращает true, если событие обработано целиком (идёт щипок).
204
+ */
205
+ function touchUp(e) {
206
+ touches.delete(e.pointerId);
207
+ if (mode === "pinch") {
208
+ if (touches.size === 0) {
209
+ mode = "idle";
210
+ note("pinch ended");
211
+ } else rebasePinch();
212
+ releaseCapture(e);
213
+ return true;
214
+ }
215
+ clearLongPress();
216
+ lastTouchAt = Date.now();
217
+ const result = taps.up(sampleOf(e));
218
+ commitArmed();
219
+ const onLine = armedConn !== null;
220
+ if (armedConn) {
221
+ const id = armedConn;
222
+ armedConn = null;
223
+ if (!taps.isMoved) {
224
+ host.setSelection([]);
225
+ host.selectConnection(id);
226
+ }
227
+ }
228
+ if (result === "double") {
229
+ activateAt(e);
230
+ note("double tap");
231
+ } else if (result === "tap") {
232
+ if (mode === "pan" && !onLine) {
233
+ host.setSelection([]);
234
+ host.selectConnection(null);
235
+ }
236
+ note("tap");
237
+ }
238
+ return false;
239
+ }
240
+ /**
241
+ * The set of fingers changed (a second one landed, one was lifted): the gesture is counted from scratch, no jump.
242
+ * Набор пальцев изменился (лёг второй, подняли один): отсчёт жеста начинается заново, скачка нет.
243
+ */
244
+ function rebasePinch() {
245
+ const [a, b] = [...touches.values()];
246
+ if (a) pinch.begin(pinchOf(a, b));
247
+ }
248
+ /**
249
+ * The browser sends finger movement as separate events: one finger moved, then the other. Between them the distance
250
+ * between the fingers "jerks" although the gesture is one. So the position of two fingers is processed once per frame, when
251
+ * both have arrived.
252
+ * Браузер присылает движение пальцев отдельными событиями: сдвинулся один палец, потом второй. Между ними расстояние
253
+ * между пальцами «дёргается», хотя жест один. Поэтому положение двух пальцев разбираем один раз за кадр, когда
254
+ * оба уже пришли.
255
+ */
256
+ let pinchFrame = 0;
257
+ function schedulePinch() {
258
+ if (pinchFrame) return;
259
+ pinchFrame = requestAnimationFrame(() => {
260
+ pinchFrame = 0;
261
+ if (mode === "pinch") pinchMove();
262
+ });
263
+ }
264
+ /**
265
+ * Pinch and a two-finger gesture; with one finger left we just move the canvas.
266
+ * Щипок и жест двумя пальцами; с одним оставшимся пальцем просто двигаем холст.
267
+ */
268
+ function pinchMove() {
269
+ const [a, b] = [...touches.values()];
270
+ const el = root.value;
271
+ if (!a || !el) return;
272
+ const step = pinch.update(pinchOf(a, b));
273
+ const rect = el.getBoundingClientRect();
274
+ host.setCamera(panBy(zoomAt(host.camera, step.pivot[0] - rect.left, step.pivot[1] - rect.top, step.factor), step.pan[0], step.pan[1]));
275
+ }
276
+ function onPointerDown(e) {
277
+ const el = root.value;
278
+ if (!el) return;
279
+ altDown = e.altKey;
280
+ const touch = e.pointerType === "touch";
281
+ if (touch && touchDown(e)) return;
282
+ host.closePalette();
283
+ lastX = e.clientX;
284
+ lastY = e.clientY;
285
+ panDistance = 0;
286
+ const doubleDown = touch && beginTouch(e);
287
+ if (e.button === 1 || e.button === 2) {
288
+ el.focus();
289
+ mode = "pan";
290
+ } else if (e.button === 0) {
291
+ const id = nodeIdAt(e.target);
292
+ if (id && isEditable(e.target)) {
293
+ if (touch) armed = id;
294
+ else {
295
+ host.raise?.(id);
296
+ host.selectConnection(null);
297
+ if (!host.selection.has(id)) host.setSelection([id]);
298
+ }
299
+ return;
300
+ }
301
+ el.focus();
302
+ const connId = connIdAt(e.target);
303
+ if (connId) {
304
+ if (touch) {
305
+ armedConn = connId;
306
+ mode = host.selectMode ? "idle" : "pan";
307
+ e.preventDefault();
308
+ capture(e);
309
+ return;
310
+ }
311
+ host.setSelection([]);
312
+ host.selectConnection(connId);
313
+ e.preventDefault();
314
+ return;
315
+ }
316
+ if (!touch) host.selectConnection(null);
317
+ const pin = host.connect ? options.pinAt(e.target) : null;
318
+ const additive = e.ctrlKey || e.shiftKey || touch && !!host.selectMode;
319
+ if (id && (!touch || additive)) host.raise?.(id);
320
+ const resizeHandle = host.resize && id ? e.target.closest("[data-resize]") : null;
321
+ if (pin && host.connect) {
322
+ host.connect.start(pin, cursorWorld(e));
323
+ mode = "connect";
324
+ } else if (id && resizeHandle && host.resize) {
325
+ const rect = host.resize.rectOf(id);
326
+ if (!rect) return;
327
+ if (touch) armed = id;
328
+ else host.setSelection([id]);
329
+ resizeId = id;
330
+ resizeEdge = resizeHandle.dataset.resize;
331
+ resizeStart = rect;
332
+ resizeDx = 0;
333
+ resizeDy = 0;
334
+ mode = "resize";
335
+ } else if (id) {
336
+ if (additive) {
337
+ host.toggleSelected(id);
338
+ if (!host.selection.has(id)) return;
339
+ host.beginDrag(id);
340
+ } else if (touch) armed = id;
341
+ else {
342
+ if (!host.selection.has(id)) host.setSelection([id]);
343
+ host.beginDrag(id);
344
+ }
345
+ mode = "drag";
346
+ } else if (touch && !host.selectMode && !doubleDown) {
347
+ mode = "pan";
348
+ note("pan");
349
+ } else {
350
+ if (touch) host.selectConnection(null);
351
+ baseSelection = additive ? [...host.selection] : [];
352
+ host.setSelection(baseSelection);
353
+ marquee.value = {
354
+ x0: e.clientX,
355
+ y0: e.clientY,
356
+ x1: e.clientX,
357
+ y1: e.clientY
358
+ };
359
+ mode = "marquee";
360
+ if (touch) note("marquee");
361
+ }
362
+ } else return;
363
+ e.preventDefault();
364
+ capture(e);
365
+ }
366
+ /**
367
+ * The gesture broke off and `pointerup` never came (alt-tab, the window was covered, the system took the pointer):
368
+ * we close what was started so that nothing "hangs": a dragged link, the selection frame, a grabbed node.
369
+ * What was done by then (a shift, a size) stays and goes into history.
370
+ * Жест оборвался, а `pointerup` не пришёл (alt-tab, окно перекрыли, система забрала указатель):
371
+ * закрываем начатое, чтобы ничего не «зависло»: протянутая связь, рамка выделения, захваченная нода.
372
+ * Сделанное к этому моменту (сдвиг, размер) остаётся и записывается в историю.
373
+ */
374
+ function abortGesture() {
375
+ clearLongPress();
376
+ taps.cancel();
377
+ armed = null;
378
+ armedConn = null;
379
+ if (mode === "connect") host.connect?.cancel();
380
+ else if (mode === "drag" || mode === "resize") {
381
+ host.endDrag();
382
+ host.commit();
383
+ }
384
+ mode = "idle";
385
+ marquee.value = null;
386
+ stopAutoScroll();
387
+ }
388
+ /**
389
+ * Abort everything, including fingers on the canvas (window focus lost, a system cancel).
390
+ * Оборвать всё, включая пальцы на холсте (потеря фокуса окна, системная отмена).
391
+ */
392
+ function cancelGesture() {
393
+ touches.clear();
394
+ abortGesture();
395
+ }
396
+ function onPointerCancel(e) {
397
+ touches.delete(e.pointerId);
398
+ if (mode === "pinch" && touches.size > 0) {
399
+ rebasePinch();
400
+ return;
401
+ }
402
+ cancelGesture();
403
+ }
404
+ /**
405
+ * The pointer capture is lost: if a gesture is still going and it is not a pinch (there the fingers are lifted by themselves), we break it.
406
+ * Захват указателя пропал: если жест ещё идёт и это не щипок (там палец снимают сами), рвём его.
407
+ */
408
+ function onLostCapture() {
409
+ if (mode === "pinch" || mode === "idle") return;
410
+ cancelGesture();
411
+ }
412
+ const SCROLL_MODES = [
413
+ "drag",
414
+ "resize",
415
+ "marquee",
416
+ "connect"
417
+ ];
418
+ const scroller = createEdgeScroller({
419
+ bounds: () => root.value?.getBoundingClientRect() ?? null,
420
+ pointer: () => [lastX, lastY],
421
+ enabled: () => SCROLL_MODES.includes(mode),
422
+ onScroll: autoScrollStep
423
+ });
424
+ const kickAutoScroll = scroller.kick;
425
+ const stopAutoScroll = scroller.stop;
426
+ function autoScrollStep(sx, sy) {
427
+ const z = host.camera.z;
428
+ host.setCamera(panBy(host.camera, -sx, -sy));
429
+ const pointer = {
430
+ clientX: lastX,
431
+ clientY: lastY
432
+ };
433
+ if (mode === "drag") host.moveSelected(sx / z, sy / z, snapNow());
434
+ else if (mode === "resize") {
435
+ resizeDx += sx / z;
436
+ resizeDy += sy / z;
437
+ host.resize?.from(resizeId, resizeEdge, resizeStart, resizeDx, resizeDy, snapNow());
438
+ } else if (mode === "connect") host.connect?.update(cursorWorld(pointer), pinUnder(pointer));
439
+ else if (mode === "marquee" && marquee.value) {
440
+ const m = marquee.value;
441
+ marquee.value = {
442
+ x0: m.x0 - sx,
443
+ y0: m.y0 - sy,
444
+ x1: lastX,
445
+ y1: lastY
446
+ };
447
+ host.setSelection([...baseSelection, ...nodesInMarquee()]);
448
+ }
449
+ }
450
+ function onPointerMove(e) {
451
+ altDown = e.altKey;
452
+ if (e.pointerType === "touch") {
453
+ if (touches.has(e.pointerId)) touches.set(e.pointerId, {
454
+ x: e.clientX,
455
+ y: e.clientY
456
+ });
457
+ if (mode === "pinch") {
458
+ schedulePinch();
459
+ return;
460
+ }
461
+ if (taps.move(sampleOf(e))) clearLongPress();
462
+ if (!taps.isMoved && (mode === "pan" || mode === "drag" || mode === "resize")) return;
463
+ if (armed && (mode === "drag" || mode === "resize")) commitArmed();
464
+ } else if (mode !== "idle" && e.buttons === 0) {
465
+ cancelGesture();
466
+ return;
467
+ }
468
+ const dx = e.clientX - lastX;
469
+ const dy = e.clientY - lastY;
470
+ lastX = e.clientX;
471
+ lastY = e.clientY;
472
+ if (mode === "pan") {
473
+ panDistance += Math.hypot(dx, dy);
474
+ host.setCamera(panBy(host.camera, dx, dy));
475
+ } else if (mode === "drag") host.moveSelected(dx / host.camera.z, dy / host.camera.z, snapNow());
476
+ else if (mode === "resize") {
477
+ resizeDx += dx / host.camera.z;
478
+ resizeDy += dy / host.camera.z;
479
+ host.resize?.from(resizeId, resizeEdge, resizeStart, resizeDx, resizeDy, snapNow());
480
+ } else if (mode === "connect") host.connect?.update(cursorWorld(e), pinUnder(e));
481
+ else if (mode === "marquee" && marquee.value) {
482
+ marquee.value = {
483
+ ...marquee.value,
484
+ x1: e.clientX,
485
+ y1: e.clientY
486
+ };
487
+ host.setSelection([...baseSelection, ...nodesInMarquee()]);
488
+ }
489
+ kickAutoScroll();
490
+ }
491
+ function onPointerUp(e) {
492
+ if (e.pointerType === "touch" && touchUp(e)) return;
493
+ if (mode === "idle") return;
494
+ if (mode === "connect" && host.connect) {
495
+ const under = document.elementFromPoint(e.clientX, e.clientY);
496
+ const origin = host.connect.origin;
497
+ if (!host.connect.finish(pinUnder(e)) && origin !== null && under && root.value?.contains(under) && !under.closest("[data-node-id]")) openPaletteAt(e, origin);
498
+ } else if (mode === "drag" || mode === "resize") {
499
+ host.endDrag();
500
+ host.commit();
501
+ } else if (mode === "pan" && e.button === 2 && panDistance < PAN_CLICK_THRESHOLD) openPaletteAt(e, null);
502
+ mode = "idle";
503
+ marquee.value = null;
504
+ stopAutoScroll();
505
+ releaseCapture(e);
506
+ }
507
+ /**
508
+ * Hotkeys on the whole window, so they work after a click on the toolbar too.
509
+ * We look at the physical key (`code`) so that Ctrl+Z works in the Russian layout as well.
510
+ * Горячие клавиши на всём окне, чтобы работали и после клика по панели инструментов.
511
+ * Смотрим на физическую клавишу (`code`), чтобы Ctrl+Z работало и в русской раскладке.
512
+ */
513
+ function onKey(e) {
514
+ const tag = e.target?.tagName;
515
+ if (tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT" || e.target?.isContentEditable) return;
516
+ if (e.ctrlKey || e.metaKey) {
517
+ if (e.code === "KeyZ" && !e.shiftKey) host.undo();
518
+ else if (e.code === "KeyY" || e.code === "KeyZ" && e.shiftKey) host.redo();
519
+ else return;
520
+ } else if (e.key === "Delete" || e.key === "Backspace") host.removeSelected();
521
+ else if (e.key === "Escape") host.closePalette();
522
+ else return;
523
+ e.preventDefault();
524
+ }
525
+ /**
526
+ * The double action (a double click or a double tap): on a link and on a node strip; what exactly happens
527
+ * is decided by the app.
528
+ * Двойное действие (двойной клик или двойной тап): по связи и по полосе ноды; что именно произойдёт,
529
+ * решает приложение.
530
+ */
531
+ function activateAt(p) {
532
+ if (!host.activate) return;
533
+ const under = document.elementFromPoint(p.clientX, p.clientY);
534
+ const connId = connIdAt(under);
535
+ if (connId) {
536
+ host.activate({
537
+ kind: "link",
538
+ id: connId,
539
+ at: cursorWorld(p)
540
+ });
541
+ return;
542
+ }
543
+ const handle = under?.closest("[data-node-handle]");
544
+ const nodeId = handle ? nodeIdAt(handle) : null;
545
+ if (nodeId) host.activate({
546
+ kind: "handle",
547
+ nodeId
548
+ });
549
+ }
550
+ /**
551
+ * The event arrives at the canvas (it holds the pointer capture). On touch we recognise the double tap ourselves, otherwise the action would fire twice.
552
+ * Событие приходит на холст (он держит захват указателя). На сенсоре двойной тап распознаём сами, иначе действие сработало бы дважды.
553
+ */
554
+ function onDblClick(e) {
555
+ if (Date.now() - lastTouchAt < 800) return;
556
+ activateAt(e);
557
+ }
558
+ /**
559
+ * The wheel moves the canvas, zoom only with Ctrl/Cmd (a trackpad pinch arrives as Ctrl + wheel): so a wheel over a
560
+ * scrollable note does not zoom the canvas the moment the cursor slips off its edge.
561
+ * Колесо двигает холст, а масштаб только с Ctrl/Cmd (щипок тачпада приходит как Ctrl + колесо): так колесо над
562
+ * заметкой, которую можно прокрутить, не масштабирует холст, стоит курсору случайно выйти за её край.
563
+ */
564
+ function onWheel(e) {
565
+ const el = root.value;
566
+ const zooming = e.ctrlKey || e.metaKey;
567
+ const field = e.target?.closest("textarea");
568
+ if (!zooming && field && field.scrollHeight > field.clientHeight) return;
569
+ e.preventDefault();
570
+ const rect = el.getBoundingClientRect();
571
+ const intent = wheelIntent(e, rect.height);
572
+ if (intent.kind === "zoom") host.setCamera(zoomAt(host.camera, e.clientX - rect.left, e.clientY - rect.top, intent.factor));
573
+ else host.setCamera(panBy(host.camera, intent.dx, intent.dy));
574
+ }
575
+ let resizeObserver = null;
576
+ onMounted(() => {
577
+ const el = root.value;
578
+ const update = () => host.setViewport({
579
+ w: el.clientWidth,
580
+ h: el.clientHeight
581
+ });
582
+ update();
583
+ resizeObserver = new ResizeObserver(update);
584
+ resizeObserver.observe(el);
585
+ window.addEventListener("keydown", onKey);
586
+ window.addEventListener("blur", cancelGesture);
587
+ window.addEventListener("pointerup", purgeTouch);
588
+ window.addEventListener("pointercancel", purgeTouch);
589
+ });
590
+ onUnmounted(() => {
591
+ resizeObserver?.disconnect();
592
+ window.removeEventListener("keydown", onKey);
593
+ window.removeEventListener("blur", cancelGesture);
594
+ window.removeEventListener("pointerup", purgeTouch);
595
+ window.removeEventListener("pointercancel", purgeTouch);
596
+ stopAutoScroll();
597
+ clearLongPress();
598
+ cancelAnimationFrame(pinchFrame);
599
+ });
600
+ watch(() => host.paletteOpen, (now, before) => {
601
+ if (!now && before) root.value?.focus();
602
+ });
603
+ return {
604
+ marquee,
605
+ debug,
606
+ debugText,
607
+ handlers: {
608
+ onPointerDown,
609
+ onPointerMove,
610
+ onPointerUp,
611
+ onPointerCancel,
612
+ onLostCapture,
613
+ onWheel,
614
+ onDblClick
615
+ }
616
+ };
617
+ }
618
+ //#endregion
619
+ //#region src/canvas/TaoxCanvas.vue?vue&type=script&setup=true&lang.ts
620
+ var _hoisted_1 = {
621
+ key: 1,
622
+ class: "tx-canvas-debug"
623
+ };
624
+ //#endregion
625
+ //#region src/canvas/TaoxCanvas.vue
626
+ var TaoxCanvas_default = /* @__PURE__ */ defineComponent({
627
+ __name: "TaoxCanvas",
628
+ props: {
629
+ host: {},
630
+ options: {},
631
+ grid: { default: 24 }
632
+ },
633
+ setup(__props, { expose: __expose }) {
634
+ const props = __props;
635
+ const root = ref(null);
636
+ const { marquee, debug, debugText, handlers } = useCanvasGestures(root, props.host, props.options);
637
+ const world = computed(() => {
638
+ const { x, y, z } = props.host.camera;
639
+ return { transform: `translate(${x}px, ${y}px) scale(${z})` };
640
+ });
641
+ const gridStyle = computed(() => {
642
+ const { x, y, z } = props.host.camera;
643
+ const small = props.grid * z;
644
+ const big = small * 5;
645
+ return {
646
+ backgroundSize: `${small}px ${small}px, ${small}px ${small}px, ${big}px ${big}px, ${big}px ${big}px`,
647
+ backgroundPosition: `${x}px ${y}px`
648
+ };
649
+ });
650
+ const marqueeStyle = computed(() => {
651
+ const m = marquee.value;
652
+ const rect = root.value?.getBoundingClientRect();
653
+ if (!m || !rect) return {};
654
+ return {
655
+ left: `${Math.min(m.x0, m.x1) - rect.left}px`,
656
+ top: `${Math.min(m.y0, m.y1) - rect.top}px`,
657
+ width: `${Math.abs(m.x1 - m.x0)}px`,
658
+ height: `${Math.abs(m.y1 - m.y0)}px`
659
+ };
660
+ });
661
+ __expose({ root });
662
+ return (_ctx, _cache) => {
663
+ return openBlock(), createElementBlock("div", {
664
+ ref_key: "root",
665
+ ref: root,
666
+ class: normalizeClass(["tx-canvas", { connecting: __props.host.connect?.origin != null }]),
667
+ tabindex: "0",
668
+ style: normalizeStyle(gridStyle.value),
669
+ onPointerdown: _cache[0] || (_cache[0] = (...args) => unref(handlers).onPointerDown && unref(handlers).onPointerDown(...args)),
670
+ onPointermove: _cache[1] || (_cache[1] = (...args) => unref(handlers).onPointerMove && unref(handlers).onPointerMove(...args)),
671
+ onPointerup: _cache[2] || (_cache[2] = (...args) => unref(handlers).onPointerUp && unref(handlers).onPointerUp(...args)),
672
+ onPointercancel: _cache[3] || (_cache[3] = (...args) => unref(handlers).onPointerCancel && unref(handlers).onPointerCancel(...args)),
673
+ onLostpointercapture: _cache[4] || (_cache[4] = (...args) => unref(handlers).onLostCapture && unref(handlers).onLostCapture(...args)),
674
+ onWheel: _cache[5] || (_cache[5] = (...args) => unref(handlers).onWheel && unref(handlers).onWheel(...args)),
675
+ onContextmenu: _cache[6] || (_cache[6] = withModifiers(() => {}, ["prevent"])),
676
+ onDblclick: _cache[7] || (_cache[7] = (...args) => unref(handlers).onDblClick && unref(handlers).onDblClick(...args))
677
+ }, [
678
+ createElementVNode("div", {
679
+ class: "tx-canvas-world",
680
+ style: normalizeStyle(world.value)
681
+ }, [renderSlot(_ctx.$slots, "default")], 4),
682
+ unref(marquee) ? (openBlock(), createElementBlock("div", {
683
+ key: 0,
684
+ class: "tx-canvas-marquee",
685
+ style: normalizeStyle(marqueeStyle.value)
686
+ }, null, 4)) : createCommentVNode("", true),
687
+ unref(debug) ? (openBlock(), createElementBlock("div", _hoisted_1, toDisplayString(unref(debugText)), 1)) : createCommentVNode("", true),
688
+ renderSlot(_ctx.$slots, "overlay")
689
+ ], 38);
690
+ };
691
+ }
692
+ });
693
+ //#endregion
694
+ export { TaoxCanvas_default as TaoxCanvas, useCanvasGestures };
695
+
696
+ //# sourceMappingURL=canvas.js.map