@1337exp/taoux 0.8.0 → 0.10.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 CHANGED
@@ -1,5 +1,29 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.10.0
4
+
5
+ Nothing to migrate: two optional host members; a host without them works as before.
6
+
7
+ - **`canvas`: a press on a label, a link or an ARIA checkbox / radio / switch inside a node belongs to it.** The canvas passed presses to `input`, `textarea`, `select`, `button` and left the rest to the drag, so a checkbox drawn as a `label` (TaoUI's `TaoCheckbox`) could not be ticked with a mouse: the press started dragging the node and the click never came.
8
+ - **`canvas`: a `background` prop: `grid` (default), `dots` or `none`.** Some people read a canvas with fewer details better: `dots` puts a dot at every crossing of the grid (every fifth one when zoomed far out), `none` leaves the plain colour. Only a look: snapping to the grid is the app's. The dots colour is `--tx-canvas-dot` (the bridge maps it).
9
+ - **`links`: the arrowhead is filled.** `.tx-links path { fill: none }` is more specific than `.tx-link-head { fill }`, so an arrowhead was drawn with no fill and was never seen; the line, shortened to run into it, stopped short of the node. The head rule is as specific now.
10
+ - **`curve`: `linkPointAt(a, aSide, b, bSide, t = 0.5)`.** A point on the curve of `linkShape`: the middle of a link for a label, a handle or a marker.
11
+ - **`canvas`: a double click on a link tells what was under the pointer.** `ActivateTarget` of kind `link` has `element`, the element under the pointer, so an app that draws something on a link (a label) can tell a double click on it from one on the line (which puts a point).
12
+ - **New module `guides`: smart guides for dragging.** `snapToGuides(moving, others, threshold, options?)` compares the edges and the centre of the dragged rectangle with those of the other rectangles, per axis, and returns `{ dx, dy, lines }`: how far to shift it so that the nearest pair coincides (within the threshold, in world units; divide a screen threshold by the zoom) and the lines to draw, one per coinciding position, shared by every rectangle that lies on it. Edges and centres can be switched off in `options`. Plain numbers, no DOM and no Vue; collecting the rectangles, applying the shift and drawing stay with the app.
13
+ - **`sortable` in a scaled canvas.** The offsets were measured in screen px and drawn as CSS px, so a list inside a zoomed canvas (a checklist in a node) lagged or ran ahead of the pointer at any zoom but 100%. The scale is measured from the item (rect size over `offsetHeight`) when the drag starts and the offsets are divided by it; the scrolled distance of the list is multiplied by it. At zoom 1 nothing changes.
14
+ - **`camera`: `fitCamera(rect, size, padding?, limits?)`.** The camera that shows a whole rectangle in a view, centred, with air around, zoom clamped to the limits (with `max: 1`: fit but never enlarge). "Zoom to fit" of every canvas editor was a few lines each app wrote again.
15
+ - **`canvas`: a context menu hook.** A right click without dragging used to open the node palette and nothing else. `host.contextMenu(screen, world, target)` is asked first, with what lies under the pointer (`{ kind: 'node', nodeId }`, `{ kind: 'link', id }` or `{ kind: 'empty' }`); return true after showing your menu, false (or have no member) and the palette opens as before. A right button that was dragged still pans and asks nothing. On touch a finger held still on a node or a link (the long press) asks the same, with the same targets; held on an empty place it asks with `{ kind: 'empty' }` and opens the palette unless you return true. Without the member nothing changes (the palette on an empty place, nothing on a node).
16
+ - **`canvas`: a "place" tool.** A toolbar with "Note", "Frame", "Text" tools needs the canvas to say where the next click landed. `host.placing` (readonly boolean) arms it; while it is true, a left press on the canvas calls `host.placeAt(screen, world)` and does nothing else (no selection, no frame, no drag); it also lands over a node and over a field inside one (the tool was just chosen, a note under the cursor must not swallow the click); the right and middle buttons still pan. Disarming the tool (after one placement, on Esc) is the app's business. Both members are needed: without `placeAt` the flag is ignored.
17
+
18
+ ## 0.9.0
19
+
20
+ Migrate: `curvefield` and `swiperow` now take their colours from the bridge like the other modules, so import `@1337exp/taoux/taoui.css` with them (`curvefield` drew the plot in TaoUI colours by itself, `swiperow` read the TaoUI tone tokens). Without it they use the built-in dark defaults. `swiperow` without the bridge has a 12px radius (it was the TaoUI panel radius).
21
+
22
+ - **The TaoUI bridge is a contract.** `theme/taoui.css` is the only file that names a `--tao-*` token; the modules read `--tx-*` with a fallback. `tests/bridge.test.ts` checks that no file in `src/` names `--tao-*`, that every themed variable (colour, tone, radius) the components read is mapped, and that the bridge points only at tokens the installed TaoUI defines.
23
+ - **Corner radius through the bridge.** New `--tx-curve-radius`, `--tx-gradient-radius`, `--tx-canvas-radius` (defaults 4px, 4px, 6px, as before) mapped to `--tao-radius-control`; `--tx-swipe-radius` is mapped to `--tao-radius-panel`.
24
+ - **`swiperow`: the action tone and the focus ring have variables.** `--tx-swipe-tone`, `--tx-swipe-tone-text`, `--tx-swipe-armed-text`, `--tx-swipe-accent`; the bridge maps the tone on the action element.
25
+ - **`curveeditor`: the label of zero stays bright.** The brightness of the end labels of the value axis was decided by their place in the list, so a new label below zero took the colour from it while the scale was rescaling; now zero keeps it.
26
+
3
27
  ## 0.8.0
4
28
 
5
29
  Nothing to migrate: one new function; `downloadText` keeps its signature and result.
package/README.md CHANGED
@@ -66,7 +66,7 @@ import '@1337exp/taoux/taoui.css'; // the bridge: --tx-* → --tao-*, t
66
66
  import '@1337exp/taoux/curveeditor.css'; // styles of a Vue module are imported explicitly
67
67
  ```
68
68
 
69
- `taoui.css` is plain CSS with zero specificity and no dependency on TaoUI, so any rule of yours wins. Values then travel through `v-model`: `usePlayback` drives `TaoScrubber`, a TaoUI field edits a curve point, a TaoUI slider sets the opacity of a gradient stop. With code: [docs/taoui.md](docs/taoui.md). Without the bridge the editors keep their dark defaults; `TaoxCurveField` (built from TaoUI components) follows the theme by itself.
69
+ `taoui.css` is plain CSS with zero specificity and no dependency on TaoUI, so any rule of yours wins. Values then travel through `v-model`: `usePlayback` drives `TaoScrubber`, a TaoUI field edits a curve point, a TaoUI slider sets the opacity of a gradient stop. With code: [docs/taoui.md](docs/taoui.md). Without the bridge the editors keep their dark defaults; `TaoxCurveField` and `TaoxSwipeRow` need it too. The bridge is a contract: the only file that names `--tao-*` tokens.
70
70
 
71
71
  <a id="modules"></a>
72
72
 
@@ -89,6 +89,7 @@ import { History } from '@1337exp/taoux/history';
89
89
  | `file` | download bytes or text as a file (`downloadBlob`, `downloadText`, any `mime`), read a picked file as text with a size limit | DOM |
90
90
  | `snap` | soft snapping to a grid with a threshold that follows the camera zoom | nothing |
91
91
  | `wheel` | wheel/trackpad → pan or zoom (like Figma) | nothing |
92
+ | `guides` | smart guides for dragging (as in Figma): `snapToGuides(rect, others, threshold)` compares edges and centres with the other rectangles and returns the shift that puts them together and the lines to draw | nothing |
92
93
  | `edgescroll` | auto-scroll speed near an edge and a ready loop, `createEdgeScroller` (canvas, curve editors, any drag) | nothing |
93
94
  | `gestures` | touch gestures: tap, double tap, long press, pinch, swipe (`SwipeTracker` + `settleOpen` for a row that slides open); `listenFocusLoss` ends a held gesture when the window loses the focus | nothing |
94
95
  | `touch` | `coarse`: is there a coarse pointer (a finger) | vue (peer) |
package/README.ru.md CHANGED
@@ -66,7 +66,7 @@ import '@1337exp/taoux/taoui.css'; // мост: --tx-* → --tao-*, р
66
66
  import '@1337exp/taoux/curveeditor.css'; // стили Vue-модуля подключаются явно
67
67
  ```
68
68
 
69
- `taoui.css` это обычный CSS с нулевой специфичностью и без зависимости от TaoUI, поэтому любое ваше правило главнее. Дальше значения ходят через `v-model`: `usePlayback` ведёт `TaoScrubber`, поле TaoUI правит точку кривой, слайдер TaoUI задаёт прозрачность остановки градиента. С кодом: [docs/taoui.ru.md](docs/taoui.ru.md). Без моста редакторы остаются с тёмными значениями по умолчанию; `TaoxCurveField` (собран из компонентов TaoUI) подстраивается под тему сам.
69
+ `taoui.css` это обычный CSS с нулевой специфичностью и без зависимости от TaoUI, поэтому любое ваше правило главнее. Дальше значения ходят через `v-model`: `usePlayback` ведёт `TaoScrubber`, поле TaoUI правит точку кривой, слайдер TaoUI задаёт прозрачность остановки градиента. С кодом: [docs/taoui.ru.md](docs/taoui.ru.md). Без моста редакторы остаются с тёмными значениями по умолчанию; `TaoxCurveField` и `TaoxSwipeRow` тоже нуждаются в нём. Мост это контракт: единственный файл, где названы токены `--tao-*`.
70
70
 
71
71
  <a id="модули"></a>
72
72
 
@@ -89,6 +89,7 @@ import { History } from '@1337exp/taoux/history';
89
89
  | `file` | скачивание байтов или текста как файла (`downloadBlob`, `downloadText`, любой `mime`), чтение выбранного файла как текста с лимитом размера | DOM |
90
90
  | `snap` | мягкая привязка к сетке с порогом по масштабу камеры | нет |
91
91
  | `wheel` | колесо/тачпад → pan или zoom (как в Figma) | нет |
92
+ | `guides` | умные направляющие при перетаскивании (как в Figma): `snapToGuides(rect, others, threshold)` сравнивает края и центры с другими прямоугольниками и возвращает сдвиг, который их совмещает, и линии для отрисовки | нет |
92
93
  | `edgescroll` | скорость автопрокрутки у края и готовый цикл `createEdgeScroller` (холст, редакторы кривых и любое перетаскивание) | нет |
93
94
  | `gestures` | сенсорные жесты: тап, двойной тап, долгое нажатие, щипок, свайп (`SwipeTracker` + `settleOpen` для строки, которая отъезжает); `listenFocusLoss` завершает удерживаемый жест, когда окно теряет фокус | нет |
94
95
  | `touch` | `coarse` — есть ли грубый указатель (палец) | vue (peer) |
package/dist/camera.d.ts CHANGED
@@ -35,3 +35,20 @@ export declare function panBy(cam: Camera, dx: number, dy: number): Camera;
35
35
  * Масштаб в `factor` раз; точка под курсором (sx, sy) остаётся на месте. `limits` по умолчанию 0.2…2.
36
36
  */
37
37
  export declare function zoomAt(cam: Camera, sx: number, sy: number, factor: number, limits?: Readonly<ZoomLimits>): Camera;
38
+ /**
39
+ * A camera that shows the whole rectangle `rect` (world units) in a view `size` (px), centred, with `padding` px of air
40
+ * on every side. The zoom is clamped to `limits` (a tiny rectangle is not blown up beyond `max`; with `max` set to 1 it is
41
+ * "fit, but never enlarge"). An empty or degenerate rectangle gives the default camera.
42
+ * Камера, которая показывает весь прямоугольник `rect` (мировые единицы) в области `size` (px), по центру, с запасом
43
+ * `padding` px со всех сторон. Масштаб ограничен `limits` (крошечный прямоугольник не раздувается выше `max`; с `max`, равным 1,
44
+ * это «вписать, но не увеличивать»). Пустой или вырожденный прямоугольник даёт камеру по умолчанию.
45
+ */
46
+ export declare function fitCamera(rect: {
47
+ x: number;
48
+ y: number;
49
+ w: number;
50
+ h: number;
51
+ } | null, size: {
52
+ w: number;
53
+ h: number;
54
+ }, padding?: number, limits?: Readonly<ZoomLimits>): Camera;
package/dist/camera.js CHANGED
@@ -47,7 +47,26 @@ function zoomAt(cam, sx, sy, factor, limits = ZOOM_LIMITS) {
47
47
  z
48
48
  };
49
49
  }
50
+ /**
51
+ * A camera that shows the whole rectangle `rect` (world units) in a view `size` (px), centred, with `padding` px of air
52
+ * on every side. The zoom is clamped to `limits` (a tiny rectangle is not blown up beyond `max`; with `max` set to 1 it is
53
+ * "fit, but never enlarge"). An empty or degenerate rectangle gives the default camera.
54
+ * Камера, которая показывает весь прямоугольник `rect` (мировые единицы) в области `size` (px), по центру, с запасом
55
+ * `padding` px со всех сторон. Масштаб ограничен `limits` (крошечный прямоугольник не раздувается выше `max`; с `max`, равным 1,
56
+ * это «вписать, но не увеличивать»). Пустой или вырожденный прямоугольник даёт камеру по умолчанию.
57
+ */
58
+ function fitCamera(rect, size, padding = 48, limits = ZOOM_LIMITS) {
59
+ if (!rect || rect.w <= 0 || rect.h <= 0 || size.w <= 0 || size.h <= 0) return createCamera();
60
+ const availW = Math.max(1, size.w - padding * 2);
61
+ const availH = Math.max(1, size.h - padding * 2);
62
+ const z = clampZoom(Math.min(availW / rect.w, availH / rect.h), limits);
63
+ return {
64
+ z,
65
+ x: (size.w - rect.w * z) / 2 - rect.x * z,
66
+ y: (size.h - rect.h * z) / 2 - rect.y * z
67
+ };
68
+ }
50
69
  //#endregion
51
- export { MAX_ZOOM, MIN_ZOOM, ZOOM_LIMITS, clampZoom, createCamera, panBy, screenToWorld, worldToScreen, zoomAt, zoomLimits };
70
+ export { MAX_ZOOM, MIN_ZOOM, ZOOM_LIMITS, clampZoom, createCamera, fitCamera, panBy, screenToWorld, worldToScreen, zoomAt, zoomLimits };
52
71
 
53
72
  //# sourceMappingURL=camera.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"camera.js","names":[],"sources":["../src/camera.ts"],"sourcesContent":["/**\n * Camera: screen point = world * z + (x, y).\n * Screen coordinates here are relative to the top-left corner of the canvas.\n * Камера: экранная точка = мировая * z + (x, y).\n * Экранные координаты здесь — относительно левого верхнего угла холста.\n */\nexport interface Camera {\n x: number;\n y: number;\n z: number;\n}\n\nexport const MIN_ZOOM = 0.2;\nexport const MAX_ZOOM = 2;\n\n/**\n * The range of the zoom. Apps with another scale of the world (a level a thousand units long) pass their own.\n * Диапазон масштаба. Приложения с другим масштабом мира (уровень длиной в тысячу единиц) передают свой.\n */\nexport interface ZoomLimits {\n min: number;\n max: number;\n}\n\nexport const ZOOM_LIMITS: Readonly<ZoomLimits> = { min: MIN_ZOOM, max: MAX_ZOOM };\n\n/**\n * Limits with the defaults filled in: `{ min: 0.05 }` keeps the default maximum.\n * Пределы с подставленными значениями по умолчанию: `{ min: 0.05 }` оставляет максимум прежним.\n */\nexport function zoomLimits(limits?: Partial<ZoomLimits>): ZoomLimits {\n return { min: limits?.min ?? MIN_ZOOM, max: limits?.max ?? MAX_ZOOM };\n}\n\nexport const clampZoom = (z: number, limits: Readonly<ZoomLimits> = ZOOM_LIMITS): number => Math.min(limits.max, Math.max(limits.min, z));\n\nexport const createCamera = (): Camera => ({ x: 0, y: 0, z: 1 });\n\nexport function screenToWorld(cam: Camera, sx: number, sy: number): [number, number] {\n return [(sx - cam.x) / cam.z, (sy - cam.y) / cam.z];\n}\n\nexport function worldToScreen(cam: Camera, wx: number, wy: number): [number, number] {\n return [wx * cam.z + cam.x, wy * cam.z + cam.y];\n}\n\nexport function panBy(cam: Camera, dx: number, dy: number): Camera {\n return { ...cam, x: cam.x + dx, y: cam.y + dy };\n}\n\n/**\n * Zoom by `factor`; the point under the cursor (sx, sy) stays where it is. `limits` default to 0.2…2.\n * Масштаб в `factor` раз; точка под курсором (sx, sy) остаётся на месте. `limits` по умолчанию 0.2…2.\n */\nexport function zoomAt(cam: Camera, sx: number, sy: number, factor: number, limits: Readonly<ZoomLimits> = ZOOM_LIMITS): Camera {\n const z = clampZoom(cam.z * factor, limits);\n const k = z / cam.z;\n return { x: sx - (sx - cam.x) * k, y: sy - (sy - cam.y) * k, z };\n}\n"],"mappings":";AAYA,IAAa,WAAW;AACxB,IAAa,WAAW;AAWxB,IAAa,cAAoC;CAAE,KAAK;CAAU,KAAA;AAAc;;;;;AAMhF,SAAgB,WAAW,QAA0C;CACjE,OAAO;EAAE,KAAK,QAAQ,OAAA;EAAiB,KAAK,QAAQ,OAAA;CAAgB;AACxE;AAEA,IAAa,aAAa,GAAW,SAA+B,gBAAwB,KAAK,IAAI,OAAO,KAAK,KAAK,IAAI,OAAO,KAAK,CAAC,CAAC;AAExI,IAAa,sBAA8B;CAAE,GAAG;CAAG,GAAG;CAAG,GAAG;AAAE;AAE9D,SAAgB,cAAc,KAAa,IAAY,IAA8B;CACjF,OAAO,EAAE,KAAK,IAAI,KAAK,IAAI,IAAI,KAAK,IAAI,KAAK,IAAI,CAAC;AACtD;AAEA,SAAgB,cAAc,KAAa,IAAY,IAA8B;CACjF,OAAO,CAAC,KAAK,IAAI,IAAI,IAAI,GAAG,KAAK,IAAI,IAAI,IAAI,CAAC;AAClD;AAEA,SAAgB,MAAM,KAAa,IAAY,IAAoB;CAC/D,OAAO;EAAE,GAAG;EAAK,GAAG,IAAI,IAAI;EAAI,GAAG,IAAI,IAAI;CAAG;AAClD;;;;;AAMA,SAAgB,OAAO,KAAa,IAAY,IAAY,QAAgB,SAA+B,aAAqB;CAC5H,MAAM,IAAI,UAAU,IAAI,IAAI,QAAQ,MAAM;CAC1C,MAAM,IAAI,IAAI,IAAI;CAClB,OAAO;EAAE,GAAG,MAAM,KAAK,IAAI,KAAK;EAAG,GAAG,MAAM,KAAK,IAAI,KAAK;EAAG;CAAE;AACnE"}
1
+ {"version":3,"file":"camera.js","names":[],"sources":["../src/camera.ts"],"sourcesContent":["/**\n * Camera: screen point = world * z + (x, y).\n * Screen coordinates here are relative to the top-left corner of the canvas.\n * Камера: экранная точка = мировая * z + (x, y).\n * Экранные координаты здесь — относительно левого верхнего угла холста.\n */\nexport interface Camera {\n x: number;\n y: number;\n z: number;\n}\n\nexport const MIN_ZOOM = 0.2;\nexport const MAX_ZOOM = 2;\n\n/**\n * The range of the zoom. Apps with another scale of the world (a level a thousand units long) pass their own.\n * Диапазон масштаба. Приложения с другим масштабом мира (уровень длиной в тысячу единиц) передают свой.\n */\nexport interface ZoomLimits {\n min: number;\n max: number;\n}\n\nexport const ZOOM_LIMITS: Readonly<ZoomLimits> = { min: MIN_ZOOM, max: MAX_ZOOM };\n\n/**\n * Limits with the defaults filled in: `{ min: 0.05 }` keeps the default maximum.\n * Пределы с подставленными значениями по умолчанию: `{ min: 0.05 }` оставляет максимум прежним.\n */\nexport function zoomLimits(limits?: Partial<ZoomLimits>): ZoomLimits {\n return { min: limits?.min ?? MIN_ZOOM, max: limits?.max ?? MAX_ZOOM };\n}\n\nexport const clampZoom = (z: number, limits: Readonly<ZoomLimits> = ZOOM_LIMITS): number => Math.min(limits.max, Math.max(limits.min, z));\n\nexport const createCamera = (): Camera => ({ x: 0, y: 0, z: 1 });\n\nexport function screenToWorld(cam: Camera, sx: number, sy: number): [number, number] {\n return [(sx - cam.x) / cam.z, (sy - cam.y) / cam.z];\n}\n\nexport function worldToScreen(cam: Camera, wx: number, wy: number): [number, number] {\n return [wx * cam.z + cam.x, wy * cam.z + cam.y];\n}\n\nexport function panBy(cam: Camera, dx: number, dy: number): Camera {\n return { ...cam, x: cam.x + dx, y: cam.y + dy };\n}\n\n/**\n * Zoom by `factor`; the point under the cursor (sx, sy) stays where it is. `limits` default to 0.2…2.\n * Масштаб в `factor` раз; точка под курсором (sx, sy) остаётся на месте. `limits` по умолчанию 0.2…2.\n */\nexport function zoomAt(cam: Camera, sx: number, sy: number, factor: number, limits: Readonly<ZoomLimits> = ZOOM_LIMITS): Camera {\n const z = clampZoom(cam.z * factor, limits);\n const k = z / cam.z;\n return { x: sx - (sx - cam.x) * k, y: sy - (sy - cam.y) * k, z };\n}\n\n/**\n * A camera that shows the whole rectangle `rect` (world units) in a view `size` (px), centred, with `padding` px of air\n * on every side. The zoom is clamped to `limits` (a tiny rectangle is not blown up beyond `max`; with `max` set to 1 it is\n * \"fit, but never enlarge\"). An empty or degenerate rectangle gives the default camera.\n * Камера, которая показывает весь прямоугольник `rect` (мировые единицы) в области `size` (px), по центру, с запасом\n * `padding` px со всех сторон. Масштаб ограничен `limits` (крошечный прямоугольник не раздувается выше `max`; с `max`, равным 1,\n * это «вписать, но не увеличивать»). Пустой или вырожденный прямоугольник даёт камеру по умолчанию.\n */\nexport function fitCamera(\n rect: { x: number; y: number; w: number; h: number } | null,\n size: { w: number; h: number },\n padding = 48,\n limits: Readonly<ZoomLimits> = ZOOM_LIMITS,\n): Camera {\n if (!rect || rect.w <= 0 || rect.h <= 0 || size.w <= 0 || size.h <= 0) return createCamera();\n const availW = Math.max(1, size.w - padding * 2);\n const availH = Math.max(1, size.h - padding * 2);\n const z = clampZoom(Math.min(availW / rect.w, availH / rect.h), limits);\n return { z, x: (size.w - rect.w * z) / 2 - rect.x * z, y: (size.h - rect.h * z) / 2 - rect.y * z };\n}\n"],"mappings":";AAYA,IAAa,WAAW;AACxB,IAAa,WAAW;AAWxB,IAAa,cAAoC;CAAE,KAAK;CAAU,KAAA;AAAc;;;;;AAMhF,SAAgB,WAAW,QAA0C;CACjE,OAAO;EAAE,KAAK,QAAQ,OAAA;EAAiB,KAAK,QAAQ,OAAA;CAAgB;AACxE;AAEA,IAAa,aAAa,GAAW,SAA+B,gBAAwB,KAAK,IAAI,OAAO,KAAK,KAAK,IAAI,OAAO,KAAK,CAAC,CAAC;AAExI,IAAa,sBAA8B;CAAE,GAAG;CAAG,GAAG;CAAG,GAAG;AAAE;AAE9D,SAAgB,cAAc,KAAa,IAAY,IAA8B;CACjF,OAAO,EAAE,KAAK,IAAI,KAAK,IAAI,IAAI,KAAK,IAAI,KAAK,IAAI,CAAC;AACtD;AAEA,SAAgB,cAAc,KAAa,IAAY,IAA8B;CACjF,OAAO,CAAC,KAAK,IAAI,IAAI,IAAI,GAAG,KAAK,IAAI,IAAI,IAAI,CAAC;AAClD;AAEA,SAAgB,MAAM,KAAa,IAAY,IAAoB;CAC/D,OAAO;EAAE,GAAG;EAAK,GAAG,IAAI,IAAI;EAAI,GAAG,IAAI,IAAI;CAAG;AAClD;;;;;AAMA,SAAgB,OAAO,KAAa,IAAY,IAAY,QAAgB,SAA+B,aAAqB;CAC5H,MAAM,IAAI,UAAU,IAAI,IAAI,QAAQ,MAAM;CAC1C,MAAM,IAAI,IAAI,IAAI;CAClB,OAAO;EAAE,GAAG,MAAM,KAAK,IAAI,KAAK;EAAG,GAAG,MAAM,KAAK,IAAI,KAAK;EAAG;CAAE;AACnE;;;;;;;;;AAUA,SAAgB,UACZ,MACA,MACA,UAAU,IACV,SAA+B,aACzB;CACN,IAAI,CAAC,QAAQ,KAAK,KAAK,KAAK,KAAK,KAAK,KAAK,KAAK,KAAK,KAAK,KAAK,KAAK,GAAG,OAAO,aAAa;CAC3F,MAAM,SAAS,KAAK,IAAI,GAAG,KAAK,IAAI,UAAU,CAAC;CAC/C,MAAM,SAAS,KAAK,IAAI,GAAG,KAAK,IAAI,UAAU,CAAC;CAC/C,MAAM,IAAI,UAAU,KAAK,IAAI,SAAS,KAAK,GAAG,SAAS,KAAK,CAAC,GAAG,MAAM;CACtE,OAAO;EAAE;EAAG,IAAI,KAAK,IAAI,KAAK,IAAI,KAAK,IAAI,KAAK,IAAI;EAAG,IAAI,KAAK,IAAI,KAAK,IAAI,KAAK,IAAI,KAAK,IAAI;CAAE;AACrG"}
@@ -12,6 +12,13 @@ declare const __VLS_export: <P>(__VLS_props: NonNullable<Awaited<typeof __VLS_se
12
12
  * Шаг мелкой сетки на фоне, мировые единицы.
13
13
  */
14
14
  grid?: number;
15
+ /**
16
+ * What is drawn on the background: `grid` (lines, the default), `dots` (a dot at every crossing, fewer details) or
17
+ * `none`. It is only a look: snapping to the grid is the app's own setting.
18
+ * Что нарисовано на фоне: `grid` (линии, по умолчанию), `dots` (точка в каждом пересечении, меньше деталей) или `none`.
19
+ * Это только вид: привязка к сетке отдельная настройка приложения.
20
+ */
21
+ background?: "grid" | "dots" | "none";
15
22
  }> & (typeof globalThis extends {
16
23
  __VLS_PROPS_FALLBACK: infer P_1;
17
24
  } ? P_1 : {});
@@ -25,10 +25,28 @@ export type ActivateTarget = {
25
25
  kind: 'link';
26
26
  id: string;
27
27
  at: Point;
28
+ /**
29
+ * The element under the pointer, so the app can tell the line from something drawn on it (a label).
30
+ * Элемент под указателем: приложение отличит линию от того, что нарисовано на ней (подписи).
31
+ */
32
+ element: Element | null;
28
33
  } | {
29
34
  kind: 'handle';
30
35
  nodeId: string;
31
36
  };
37
+ /**
38
+ * What a right click landed on: a node, a link or an empty place.
39
+ * На что пришёлся правый клик: нода, связь или пустое место.
40
+ */
41
+ export type ContextTarget = {
42
+ kind: 'node';
43
+ nodeId: string;
44
+ } | {
45
+ kind: 'link';
46
+ id: string;
47
+ } | {
48
+ kind: 'empty';
49
+ };
32
50
  /**
33
51
  * Dragging out a link. `P` is a pin address: opaque for the canvas, only the app understands it.
34
52
  * Протягивание связи. `P` — адрес пина: для холста непрозрачный, его понимает только приложение.
@@ -117,6 +135,29 @@ export interface CanvasHost<P = unknown> {
117
135
  * Спрашивается перед клавишами холста (Delete, Backspace, Escape, Ctrl+Z / Y). Нет члена: холст берёт свои клавиши, как раньше.
118
136
  */
119
137
  claimsKey?(event: KeyboardEvent): boolean;
138
+ /**
139
+ * A "place something" tool is armed (a note, a frame): the next left press on the canvas calls `placeAt` and does nothing else
140
+ * (no selection, no frame, no drag). Esc and the end of the tool are the app's business (disarm in `placeAt` or on a key).
141
+ * Both members are needed; without `placeAt` the flag is ignored.
142
+ * Включён инструмент «поставить» (заметку, рамку): следующее нажатие левой кнопкой по холсту зовёт `placeAt` и больше ничего
143
+ * не делает (ни выделения, ни рамки, ни перетаскивания). Esc и конец инструмента — забота приложения (снять в `placeAt` или по клавише).
144
+ * Нужны оба члена; без `placeAt` флаг игнорируется.
145
+ */
146
+ readonly placing?: boolean;
147
+ /**
148
+ * Where the press landed: `screen` in px relative to the canvas, `world` in world units.
149
+ * Куда пришлось нажатие: `screen` в px относительно холста, `world` в мировых единицах.
150
+ */
151
+ placeAt?(screen: Point, world: Point): void;
152
+ /**
153
+ * A right click without dragging (a dragged right button pans), or a finger held still on a node, a link or an empty
154
+ * place (the long press on touch). The app shows its menu for `target` and returns true;
155
+ * false (or no member) leaves the old behaviour: the node palette opens. `screen` is in px relative to the canvas.
156
+ * Правый клик без перетаскивания (с перетаскиванием правая кнопка двигает холст) или палец, неподвижно лежащий на
157
+ * ноде, связи или пустом месте (долгое нажатие на сенсоре). Приложение показывает своё меню для
158
+ * `target` и возвращает true; false (или нет члена) оставляет прежнее: открывается палитра нод. `screen` в px относительно холста.
159
+ */
160
+ contextMenu?(screen: Point, world: Point, target: ContextTarget): boolean;
120
161
  }
121
162
  /**
122
163
  * How the canvas finds pins in the DOM. The rest of the DOM contract the app's node view must keep:
@@ -1,3 +1,3 @@
1
1
  export { default as TaoxCanvas } from './TaoxCanvas.vue';
2
2
  export { useCanvasGestures, type Marquee } from './useCanvasGestures';
3
- export type { ActivateTarget, CanvasHost, CanvasOptions, ConnectHost, Point, Rect, ResizeEdge, ResizeHost, Size, } from './host';
3
+ export type { ActivateTarget, CanvasHost, CanvasOptions, ConnectHost, ContextTarget, Point, Rect, ResizeEdge, ResizeHost, Size, } from './host';
package/dist/canvas.css CHANGED
@@ -2,7 +2,9 @@
2
2
  /*
3
3
  * Configured with CSS variables on the canvas or an ancestor:
4
4
  * Настройка через CSS-переменные на холсте или предке:
5
- * --tx-canvas-bg, --tx-canvas-grid-minor, --tx-canvas-grid-major, --tx-canvas-accent, --tx-canvas-accent-subtle.
5
+ * --tx-canvas-bg, --tx-canvas-grid-minor, --tx-canvas-grid-major, --tx-canvas-dot, --tx-canvas-accent, --tx-canvas-accent-subtle,
6
+ * --tx-canvas-radius (the corners of the debug badge, 6px by default).
7
+ * --tx-canvas-radius — углы отладочной плашки, по умолчанию 6px.
6
8
  */
7
9
  .tx-canvas {
8
10
  position: relative;
@@ -47,7 +49,7 @@
47
49
  left: 8px;
48
50
  bottom: 8px;
49
51
  padding: 4px 8px;
50
- border-radius: 6px;
52
+ border-radius: var(--tx-canvas-radius, 6px);
51
53
  background: rgba(0, 0, 0, 0.7);
52
54
  color: #fff;
53
55
  font: 12px/1.3 monospace;
package/dist/canvas.js CHANGED
@@ -75,7 +75,7 @@ function useCanvasGestures(root, host, options) {
75
75
  * Input fields inside nodes: a click on them selects the node but does not drag it and does not take focus away.
76
76
  * Поля ввода внутри нод: клик по ним выделяет ноду, но не тащит её и не отбирает фокус.
77
77
  */
78
- const isEditable = (target) => !!target?.closest("input, textarea, select, button, [contenteditable=\"true\"]");
78
+ const isEditable = (target) => !!target?.closest("input, textarea, select, button, label, a[href], [contenteditable=\"true\"], [role=\"checkbox\"], [role=\"radio\"], [role=\"switch\"]");
79
79
  /**
80
80
  * The pin under the cursor: the nearest pin (if the app can) or the one exactly under the pointer.
81
81
  * Пин под курсором: ближайший пин (если приложение умеет) или тот, что точно под указателем.
@@ -85,6 +85,25 @@ function useCanvasGestures(root, host, options) {
85
85
  const rect = root.value.getBoundingClientRect();
86
86
  return screenToWorld(host.camera, e.clientX - rect.left, e.clientY - rect.top);
87
87
  }
88
+ /**
89
+ * A right click: ask the app for a menu for what lies under the pointer. True when it showed one.
90
+ * Правый клик: просим у приложения меню для того, что под указателем. True, если оно его показало.
91
+ */
92
+ function openContextAt(e) {
93
+ if (!host.contextMenu) return false;
94
+ const under = document.elementFromPoint(e.clientX, e.clientY);
95
+ const link = connIdAt(under);
96
+ const node = nodeIdAt(under);
97
+ const target = link ? {
98
+ kind: "link",
99
+ id: link
100
+ } : node ? {
101
+ kind: "node",
102
+ nodeId: node
103
+ } : { kind: "empty" };
104
+ const rect = root.value.getBoundingClientRect();
105
+ return host.contextMenu([e.clientX - rect.left, e.clientY - rect.top], cursorWorld(e), target);
106
+ }
88
107
  function openPaletteAt(e, origin) {
89
108
  const rect = root.value.getBoundingClientRect();
90
109
  host.openPalette([e.clientX - rect.left, e.clientY - rect.top], cursorWorld(e), origin);
@@ -158,16 +177,30 @@ function useCanvasGestures(root, host, options) {
158
177
  return doubleDown;
159
178
  }
160
179
  /**
161
- * A finger lies on an empty place without moving: this is the touch right click, the palette opens.
162
- * Палец лежит на пустом месте и не двигается: это правый клик сенсора, открываем палитру.
180
+ * A finger lies without moving: this is the touch right click. On a node or a link the app's context menu opens
181
+ * (when it has one); on an empty place, or when the app shows no menu, the palette opens (an empty place only).
182
+ * Палец лежит и не двигается: это правый клик сенсора. На ноде или связи открывается контекстное меню приложения
183
+ * (если оно есть); на пустом месте, или когда меню приложение не показало, открывается палитра (только на пустом месте).
163
184
  */
164
185
  function onLongPress() {
165
186
  longPressTimer = void 0;
166
- if (mode !== "pan" || !taps.longPressDue(performance.now() + 50)) return;
187
+ if (mode !== "pan" && !(mode === "drag" && armed !== null) || !taps.longPressDue(performance.now() + 50)) return;
188
+ const target = armed ? {
189
+ kind: "node",
190
+ nodeId: armed
191
+ } : armedConn ? {
192
+ kind: "link",
193
+ id: armedConn
194
+ } : { kind: "empty" };
195
+ const rect = root.value.getBoundingClientRect();
196
+ const handled = host.contextMenu?.([lastX - rect.left, lastY - rect.top], screenToWorld(host.camera, lastX - rect.left, lastY - rect.top), target) ?? false;
197
+ if (!handled && target.kind !== "empty") return;
167
198
  taps.cancel();
199
+ armed = null;
200
+ armedConn = null;
168
201
  mode = "idle";
169
202
  navigator.vibrate?.(15);
170
- openPaletteAt({
203
+ if (!handled) openPaletteAt({
171
204
  clientX: lastX,
172
205
  clientY: lastY
173
206
  }, null);
@@ -288,6 +321,12 @@ function useCanvasGestures(root, host, options) {
288
321
  el.focus();
289
322
  mode = "pan";
290
323
  } else if (e.button === 0) {
324
+ if (host.placing && host.placeAt) {
325
+ const rect = el.getBoundingClientRect();
326
+ host.placeAt([e.clientX - rect.left, e.clientY - rect.top], cursorWorld(e));
327
+ e.preventDefault();
328
+ return;
329
+ }
291
330
  const id = nodeIdAt(e.target);
292
331
  if (id && isEditable(e.target)) {
293
332
  if (touch) armed = id;
@@ -498,7 +537,9 @@ function useCanvasGestures(root, host, options) {
498
537
  } else if (mode === "drag" || mode === "resize") {
499
538
  host.endDrag();
500
539
  host.commit();
501
- } else if (mode === "pan" && e.button === 2 && panDistance < PAN_CLICK_THRESHOLD) openPaletteAt(e, null);
540
+ } else if (mode === "pan" && e.button === 2 && panDistance < PAN_CLICK_THRESHOLD) {
541
+ if (!openContextAt(e)) openPaletteAt(e, null);
542
+ }
502
543
  mode = "idle";
503
544
  marquee.value = null;
504
545
  stopAutoScroll();
@@ -537,7 +578,8 @@ function useCanvasGestures(root, host, options) {
537
578
  host.activate({
538
579
  kind: "link",
539
580
  id: connId,
540
- at: cursorWorld(p)
581
+ at: cursorWorld(p),
582
+ element: under
541
583
  });
542
584
  return;
543
585
  }
@@ -629,7 +671,8 @@ var TaoxCanvas_default = /* @__PURE__ */ defineComponent({
629
671
  props: {
630
672
  host: {},
631
673
  options: {},
632
- grid: { default: 24 }
674
+ grid: { default: 24 },
675
+ background: { default: "grid" }
633
676
  },
634
677
  setup(__props, { expose: __expose }) {
635
678
  const props = __props;
@@ -643,6 +686,15 @@ var TaoxCanvas_default = /* @__PURE__ */ defineComponent({
643
686
  const { x, y, z } = props.host.camera;
644
687
  const small = props.grid * z;
645
688
  const big = small * 5;
689
+ if (props.background === "none") return { backgroundImage: "none" };
690
+ if (props.background === "dots") {
691
+ const step = small < 10 ? big : small;
692
+ return {
693
+ backgroundImage: "radial-gradient(circle, var(--tx-canvas-dot, rgba(255, 255, 255, 0.1)) 1.1px, transparent 1.6px)",
694
+ backgroundSize: `${step}px ${step}px`,
695
+ backgroundPosition: `${x - step / 2}px ${y - step / 2}px`
696
+ };
697
+ }
646
698
  return {
647
699
  backgroundSize: `${small}px ${small}px, ${small}px ${small}px, ${big}px ${big}px, ${big}px ${big}px`,
648
700
  backgroundPosition: `${x}px ${y}px`