drawnui-react 0.1.0-preview.9 → 1.0.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 (117) hide show
  1. package/README.md +229 -22
  2. package/SKIPPED.md +37 -28
  3. package/dist/controls/AnimatedFramesRenderer.d.ts +9 -0
  4. package/dist/controls/AnimatedFramesRenderer.js +18 -1
  5. package/dist/controls/DrawnGame.d.ts +44 -0
  6. package/dist/controls/DrawnGame.js +82 -0
  7. package/dist/controls/GridStructure.d.ts +25 -3
  8. package/dist/controls/GridStructure.js +81 -5
  9. package/dist/controls/SkiaBackdrop.d.ts +8 -2
  10. package/dist/controls/SkiaBackdrop.js +42 -14
  11. package/dist/controls/SkiaButton.d.ts +17 -3
  12. package/dist/controls/SkiaButton.js +26 -8
  13. package/dist/controls/SkiaCarousel.d.ts +22 -3
  14. package/dist/controls/SkiaCarousel.js +85 -9
  15. package/dist/controls/SkiaCheckbox.d.ts +0 -1
  16. package/dist/controls/SkiaCheckbox.js +2 -7
  17. package/dist/controls/SkiaDrawer.d.ts +15 -0
  18. package/dist/controls/SkiaDrawer.js +42 -7
  19. package/dist/controls/SkiaEditor.d.ts +51 -2
  20. package/dist/controls/SkiaEditor.js +292 -58
  21. package/dist/controls/SkiaGif.d.ts +7 -0
  22. package/dist/controls/SkiaGif.js +25 -4
  23. package/dist/controls/SkiaImage.d.ts +10 -0
  24. package/dist/controls/SkiaImage.js +80 -19
  25. package/dist/controls/SkiaLabel.d.ts +200 -11
  26. package/dist/controls/SkiaLabel.js +925 -93
  27. package/dist/controls/SkiaLabelFps.d.ts +12 -0
  28. package/dist/controls/SkiaLabelFps.js +35 -0
  29. package/dist/controls/SkiaLayout.d.ts +89 -9
  30. package/dist/controls/SkiaLayout.js +397 -23
  31. package/dist/controls/SkiaLottie.js +5 -3
  32. package/dist/controls/SkiaProgress.d.ts +2 -1
  33. package/dist/controls/SkiaProgress.js +8 -5
  34. package/dist/controls/SkiaRadioButton.d.ts +2 -0
  35. package/dist/controls/SkiaRadioButton.js +16 -4
  36. package/dist/controls/SkiaRichLabel.d.ts +1 -1
  37. package/dist/controls/SkiaRichLabel.js +11 -1
  38. package/dist/controls/SkiaScroll.d.ts +86 -7
  39. package/dist/controls/SkiaScroll.js +361 -40
  40. package/dist/controls/SkiaScrollBar.d.ts +27 -0
  41. package/dist/controls/SkiaScrollBar.js +51 -2
  42. package/dist/controls/SkiaShaderCarousel.d.ts +11 -1
  43. package/dist/controls/SkiaShaderCarousel.js +27 -5
  44. package/dist/controls/SkiaShape.d.ts +15 -2
  45. package/dist/controls/SkiaShape.js +57 -10
  46. package/dist/controls/SkiaShell.d.ts +282 -0
  47. package/dist/controls/SkiaShell.js +972 -0
  48. package/dist/controls/SkiaSlider.d.ts +20 -2
  49. package/dist/controls/SkiaSlider.js +61 -7
  50. package/dist/controls/SkiaSprite.d.ts +4 -0
  51. package/dist/controls/SkiaSprite.js +27 -11
  52. package/dist/controls/SkiaSvg.d.ts +4 -0
  53. package/dist/controls/SkiaSvg.js +28 -4
  54. package/dist/controls/SkiaSwitch.d.ts +0 -1
  55. package/dist/controls/SkiaSwitch.js +4 -8
  56. package/dist/controls/SkiaToggle.d.ts +25 -5
  57. package/dist/controls/SkiaToggle.js +58 -5
  58. package/dist/controls/SnappingLayout.d.ts +12 -1
  59. package/dist/controls/SnappingLayout.js +21 -2
  60. package/dist/controls/TooltipStyle.d.ts +52 -0
  61. package/dist/controls/TooltipStyle.js +88 -0
  62. package/dist/core/Accessibility.d.ts +162 -11
  63. package/dist/core/Accessibility.js +882 -22
  64. package/dist/core/Animators.d.ts +37 -1
  65. package/dist/core/Animators.js +102 -9
  66. package/dist/core/Canvas.d.ts +307 -8
  67. package/dist/core/Canvas.js +1202 -66
  68. package/dist/core/ControlStyle.d.ts +2 -0
  69. package/dist/core/ControlStyle.js +2 -0
  70. package/dist/core/DesignerActions.d.ts +32 -0
  71. package/dist/core/DesignerActions.js +68 -0
  72. package/dist/core/Easing.d.ts +12 -1
  73. package/dist/core/Easing.js +25 -1
  74. package/dist/core/Gestures.d.ts +86 -2
  75. package/dist/core/Gestures.js +184 -4
  76. package/dist/core/Hover.d.ts +51 -0
  77. package/dist/core/Hover.js +140 -0
  78. package/dist/core/ImageEffects.d.ts +2 -0
  79. package/dist/core/ImageEffects.js +2 -0
  80. package/dist/core/KeyboardManager.d.ts +40 -0
  81. package/dist/core/KeyboardManager.js +98 -8
  82. package/dist/core/PopupWindows.d.ts +94 -0
  83. package/dist/core/PopupWindows.js +207 -0
  84. package/dist/core/Props.d.ts +11 -0
  85. package/dist/core/Props.js +44 -0
  86. package/dist/core/ScrollAnimators.d.ts +6 -0
  87. package/dist/core/ScrollAnimators.js +16 -1
  88. package/dist/core/Shaping.d.ts +40 -0
  89. package/dist/core/Shaping.js +224 -0
  90. package/dist/core/SkiaControl.d.ts +306 -13
  91. package/dist/core/SkiaControl.js +681 -75
  92. package/dist/core/SkiaEffect.d.ts +29 -1
  93. package/dist/core/SkiaEffect.js +78 -16
  94. package/dist/core/SkiaImageManager.d.ts +101 -18
  95. package/dist/core/SkiaImageManager.js +318 -63
  96. package/dist/core/Styles.js +7 -1
  97. package/dist/core/Super.d.ts +33 -2
  98. package/dist/core/Super.js +58 -12
  99. package/dist/core/TextInputProxy.d.ts +31 -1
  100. package/dist/core/TextInputProxy.js +97 -15
  101. package/dist/core/Tooltips.d.ts +71 -0
  102. package/dist/core/Tooltips.js +205 -0
  103. package/dist/core/Types.d.ts +11 -1
  104. package/dist/core/Types.js +32 -1
  105. package/dist/core/ViewsAdapter.d.ts +7 -2
  106. package/dist/core/ViewsAdapter.js +10 -3
  107. package/dist/index.d.ts +8 -0
  108. package/dist/index.js +8 -0
  109. package/dist/react/SkiaShell.d.ts +8 -74
  110. package/dist/react/SkiaShell.js +163 -475
  111. package/dist/react/index.d.ts +48 -4
  112. package/dist/react/index.js +210 -43
  113. package/dist/react/reconciler.d.ts +32 -0
  114. package/dist/react/reconciler.js +71 -40
  115. package/dist/vite/index.d.ts +9 -0
  116. package/dist/vite/index.js +36 -3
  117. package/package.json +103 -5
@@ -1,17 +1,21 @@
1
+ import { CanvasLeaveWatchers } from "./SkiaControl";
1
2
  import { Super } from "./Super";
2
3
  import { SkiaAccessibilityManager } from "./Accessibility";
4
+ import { HoverManager } from "./Hover";
5
+ import { TooltipController } from "./Tooltips";
6
+ import { PopupAnchor, PopupLayer } from "./PopupWindows";
7
+ import { KeyboardManager } from "./KeyboardManager";
8
+ import { TouchEffect } from "./Gestures";
9
+ import { TextInputProxy } from "./TextInputProxy";
3
10
  import { Colors, SKRect } from "./Types";
4
- import { ContextMenuEventArgs, GestureEventProcessingInfo, PointerData, SKPoint, SkiaGesturesParameters, TouchActionEventArgs, } from "./Gestures";
5
- /**
6
- * Mirrors DrawnUi Canvas (DrawnView): hosts one Content control on an HTML canvas element,
7
- * owns RenderingScale (devicePixelRatio), the surface, the on-demand frame loop and raw input.
8
- * Frames are drawn only after Update() (invalidation), never continuously.
9
- * Gestures are accumulated and processed in order at the START of the next frame, like DrawnUi.
10
- */
11
+ import { ContextMenuEventArgs, GestureEventProcessingInfo, MultitouchTracker, PointerData, SKPoint, SkiaGesturesParameters, TouchActionEventArgs, } from "./Gestures";
11
12
  export class Canvas {
12
13
  Element;
13
14
  /** Points a pointer may travel between Down and Up and still count as a tap (AppoMobi TouchEffect default). */
14
15
  static TappedCancelMoveThresholdPoints = 16;
16
+ /** Alias of TouchEffect.LongPressTimeMsDefault: how long a press is held still to be a LongPressing. */
17
+ static get LongPressTimeMs() { return TouchEffect.LongPressTimeMsDefault; }
18
+ static set LongPressTimeMs(ms) { TouchEffect.LongPressTimeMsDefault = ms; }
15
19
  BackgroundColor = Colors.Transparent;
16
20
  /** Accelerated = WebGL surface, Default = software. Read once at first frame. */
17
21
  RenderingMode = "Accelerated";
@@ -33,18 +37,153 @@ export class Canvas {
33
37
  WillFirstTimeDraw;
34
38
  /** DrawnView.WasDrawn: raised after every frame has been drawn (the C# event passes no context). */
35
39
  WasDrawn;
40
+ /**
41
+ * The system's light / dark appearance (DrawnUi.Rust `system_theme`): undefined until the host learns it, which it
42
+ * does when the canvas is created (`prefers-color-scheme`), then it follows every change.
43
+ */
44
+ get SystemTheme() { return this.systemTheme; }
45
+ /**
46
+ * Raised once when the host learns the system theme (set it in the Canvas init / the `<Canvas>` prop to get that first
47
+ * value), then once per change; a repeated value is not raised. No handler, no call; it never asks for a frame.
48
+ */
49
+ SystemThemeChanged;
50
+ systemTheme;
51
+ themeQuery;
52
+ onThemeQuery = () => this.SetSystemTheme(this.themeQuery.matches ? "Dark" : "Light");
53
+ SetSystemTheme(theme) {
54
+ if (theme === this.systemTheme)
55
+ return;
56
+ this.systemTheme = theme;
57
+ this.SystemThemeChanged?.(theme);
58
+ }
36
59
  /** Registry + rate-limited snapshot of accessible controls, rendered by the DOM overlay (DrawnUi AccessibilityManager). */
37
60
  AccessibilityManager = new SkiaAccessibilityManager();
61
+ /** Mouse hover of the controls (drawnui-cross 6m): ReceivesHover / IsHovered / HoverChanged. */
62
+ Hover = new HoverManager();
63
+ // ---- tooltips (drawnui-cross 6ar) ----
64
+ tooltipController;
65
+ /** Made on first use: a canvas that never shows a tooltip allocates nothing for it. */
66
+ get tooltip() { return this.tooltipController ??= new TooltipController(this); }
67
+ /** Look and timing of the tooltips on this canvas; unset uses `Super.TooltipStyle`. */
68
+ TooltipStyle;
69
+ get TooltipStyleUsed() { return this.TooltipStyle ?? Super.TooltipStyle; }
70
+ /** The text of the tooltip shown now, undefined when none is shown. */
71
+ get ShownTooltip() { return this.tooltip.ShownText; }
72
+ // ---- popup windows (drawnui-cross 6at, the DrawnUi.Rust / .NET API) ----
73
+ popupLayer;
74
+ /** Made on first use, like the tooltip. */
75
+ get popups() { return this.popupLayer ??= new PopupLayer(this); }
76
+ popupKeysHooked = false;
77
+ /** Raised when a popup window closed: picked, a press outside, Escape, the wheel, window blur or ClosePopupWindow. */
78
+ PopupWindowClosed = new Set();
79
+ /** The root controls of the open popup windows, bottom to top: a read-only view for tools (a new array per read). */
80
+ get PopupWindowRoots() { return this.popupLayer?.Roots ?? []; }
81
+ wasDrawnListeners;
82
+ /**
83
+ * Handlers run at the end of every drawn frame, after the `WasDrawn` callback and before the surface is flushed (a
84
+ * tool drawing an overlay on `Surface.getCanvas()`). Made on first use: a canvas without listeners does no work.
85
+ */
86
+ get WasDrawnListeners() { return this.wasDrawnListeners ??= new Set(); }
87
+ raiseWasDrawn = (f) => Canvas.Guard("a WasDrawn listener", f, () => f(this));
88
+ /**
89
+ * Shows `content` over everything, opening from `anchor` the way native menus do: at a point (a right click, canvas
90
+ * points), or below a rect or a control (a dropdown), flipped to the other side where it does not fit. It closes with
91
+ * a press outside it, Escape, the wheel outside it, window blur, `ClosePopupWindow` and the options.
92
+ */
93
+ OpenPopupWindow(content, anchor, options = {}) {
94
+ const id = this.popups.Open(content, PopupAnchor.From(anchor), options, this);
95
+ this.HookPopupKeys(true);
96
+ if (!options.Passive)
97
+ this.tooltip.Reset(); // a menu opening closes the tooltip
98
+ this.Hover.RequestCheck();
99
+ this.Update();
100
+ return id;
101
+ }
102
+ /** Closes the popup window (nothing when it is closed already). */
103
+ ClosePopupWindow(id) { this.popups.Close(id); this.AfterPopupsChanged(); }
104
+ /** Closes every popup window. */
105
+ ClosePopupWindows() { this.popups.CloseAll(true); this.AfterPopupsChanged(); }
106
+ /** The popup window is still open. */
107
+ IsPopupWindowOpen(id) { return this.popups.IsOpen(id); }
108
+ /**
109
+ * Moves the keyboard and screen-reader focus to `control` at the end of the next frame, for app code such as a custom
110
+ * menu that moves its highlight (C# DrawnView.SetAccessibilityFocus). A control not drawn yet gets it once it is, within
111
+ * 3 seconds. It wins over the library's own moves in the same frame (a closed popup window giving the keyboard back to
112
+ * its opener); undefined cancels a move still waiting. The focus ring shows only if the keyboard is in use.
113
+ */
114
+ SetAccessibilityFocus(control) { this.AccessibilityManager.SetAccessibilityFocus(control); this.Update(); }
115
+ /**
116
+ * The drawn control with the keyboard and screen-reader focus (C# KeyboardFocusNode). Set undefined to let no drawn
117
+ * control keep it: the DOM focus goes back to the canvas and the keys belong to the app; a control moves it there.
118
+ */
119
+ get KeyboardFocusNode() { return this.AccessibilityManager.FocusedNode; }
120
+ set KeyboardFocusNode(control) {
121
+ if (control)
122
+ this.AccessibilityManager.SetAccessibilityFocus(control);
123
+ else
124
+ this.AccessibilityManager.ClearKeyboardFocus();
125
+ this.Update();
126
+ }
127
+ /** True while a popup window that takes input is open. */
128
+ get HasPopupWindows() { return this.popups.HasInteractive; }
129
+ /** The content of the top popup window that takes input. */
130
+ get TopPopupWindow() { return this.popups.TopInteractive; }
131
+ /** The window stopped being active (blur): popup windows and the tooltip close, as native menus do. */
132
+ OnWindowDeactivated() { this.ClosePopupWindows(); this.tooltip.CloseOnInput(); }
133
+ /**
134
+ * The browser window (tab) has the keyboard (C# DrawnView.IsWindowActive): false after its blur, true again after its
135
+ * focus. A focused editor hides its caret while it is false.
136
+ */
137
+ IsWindowActive = typeof document === "undefined" || typeof document.hasFocus !== "function" || document.hasFocus();
138
+ /** Raised when IsWindowActive changes (C# WindowActiveChanged). */
139
+ WindowActiveChanged = new Set();
140
+ SetWindowActive(active) {
141
+ if (this.IsWindowActive === active)
142
+ return;
143
+ this.IsWindowActive = active;
144
+ for (const h of [...this.WindowActiveChanged])
145
+ h(active);
146
+ }
147
+ RaisePopupWindowClosed(id) { for (const h of [...this.PopupWindowClosed])
148
+ h(id); }
149
+ AfterPopupsChanged() {
150
+ if (!this.popups.HasAny)
151
+ this.HookPopupKeys(false);
152
+ this.Hover.RequestCheck();
153
+ this.Update();
154
+ }
155
+ onPopupKey = (key) => {
156
+ if (key !== "Escape" || !this.popups.CloseTop())
157
+ return false;
158
+ this.AfterPopupsChanged();
159
+ return true;
160
+ };
161
+ HookPopupKeys(on) {
162
+ if (on === this.popupKeysHooked)
163
+ return;
164
+ this.popupKeysHooked = on;
165
+ if (on)
166
+ KeyboardManager.SubscribeNavigation(this.onPopupKey);
167
+ else
168
+ KeyboardManager.UnsubscribeNavigation(this.onPopupKey);
169
+ }
170
+ onWindowBlur = () => this.OnWindowDeactivated();
171
+ // IsWindowActive follows the window for the canvas' whole life, input on or off (a focused editor needs it)
172
+ onWindowInactive = () => this.SetWindowActive(false);
173
+ onWindowActive = () => this.SetWindowActive(true);
38
174
  content;
39
175
  get Content() { return this.content; }
40
176
  set Content(value) {
41
- if (this.content)
177
+ if (this.content && this.content !== value) {
178
+ this.ControlLeft(this.content, false);
42
179
  this.content._superview = undefined;
180
+ }
43
181
  this.content = value;
44
182
  if (value) {
45
183
  value.Parent = undefined;
46
184
  value._superview = this;
47
185
  }
186
+ this.Hover.RequestCheck();
48
187
  this.Update();
49
188
  }
50
189
  surface;
@@ -54,28 +193,68 @@ export class Canvas {
54
193
  frameId = 0;
55
194
  disposed = false;
56
195
  observer;
196
+ /**
197
+ * The device pixels the element covers, as the browser reports them (ResizeObserver device-pixel-content-box). At a
198
+ * fractional display scale the rounded CSS size can be a pixel off (701.3 x 333.3 CSS px at 1.25 cover 877 x 416 device
199
+ * px), and the browser would then resample the whole canvas, softening every glyph.
200
+ */
201
+ devicePixels;
202
+ /** The element's CSS width when the device-pixel box was reported. */
203
+ devicePixelsCss = 0;
204
+ /** The WebGL context is lost: no frames until the browser restores it. */
205
+ contextLost = false;
206
+ /**
207
+ * The GPU context generation, unique across canvases: a new one when this canvas is made and when its WebGL context
208
+ * is restored. Every GPU object made under another one (Image caches, picture caches that may replay them, kept
209
+ * composite surfaces, effect textures; also those a control brought from another canvas) is remade at its next draw
210
+ * (DrawnUi.Rust Gpu::epoch). A texture of another WebGL context draws nothing.
211
+ */
212
+ GpuEpoch = Canvas.NextGpuEpoch();
213
+ static gpuEpochs = 0;
214
+ static NextGpuEpoch() { return ++Canvas.gpuEpochs; }
57
215
  /** `init` runs before the first frame is drawn: the place to attach `WillFirstTimeDraw` / `WasDrawn` for that frame. */
58
216
  constructor(Element, init) {
59
217
  this.Element = Element;
60
218
  if (!Super.CK)
61
219
  throw new Error("DrawnUi: call Super.UseDrawnUi()...BuildAsync() before creating a Canvas");
62
220
  init?.(this);
63
- this.observer = new ResizeObserver(() => this.OnResized());
64
- this.observer.observe(Element);
221
+ if (typeof window.matchMedia === "function") {
222
+ this.themeQuery = window.matchMedia("(prefers-color-scheme: dark)");
223
+ this.themeQuery.addEventListener?.("change", this.onThemeQuery);
224
+ this.onThemeQuery();
225
+ }
226
+ Element.addEventListener("webglcontextlost", this.onContextLost);
227
+ Element.addEventListener("webglcontextrestored", this.onContextRestored);
228
+ window.addEventListener("blur", this.onWindowInactive);
229
+ window.addEventListener("focus", this.onWindowActive);
230
+ this.Hover.RootAt = (x, y) => this.popupLayer?.At(x, y) ?? this.content;
231
+ this.observer = new ResizeObserver((entries) => {
232
+ const entry = entries[entries.length - 1];
233
+ const box = entry?.devicePixelContentBoxSize?.[0];
234
+ if (box) {
235
+ this.devicePixels = [box.inlineSize, box.blockSize];
236
+ this.devicePixelsCss = entry.contentBoxSize?.[0]?.inlineSize ?? entry.contentRect.width;
237
+ }
238
+ this.OnResized();
239
+ });
240
+ // browsers without the device-pixel box (Safari) take the rounded size
241
+ try {
242
+ this.observer.observe(Element, { box: "device-pixel-content-box" });
243
+ }
244
+ catch {
245
+ this.observer.observe(Element);
246
+ }
65
247
  this.OnResized();
66
248
  }
67
249
  /** Request a redraw (full measure + arrange + render) on the next animation frame. */
68
250
  Update() {
69
- if (this.frameId || !this.surface || this.disposed)
251
+ if (this.frameId || !this.surface || this.disposed || this.contextLost)
70
252
  return;
71
253
  const surface = this.surface;
72
254
  this.frameId = surface.requestAnimationFrame((c) => {
73
255
  this.frameId = 0;
74
- if (this.surface === surface && !this.disposed) {
75
- this.Draw(c);
76
- surface.flush();
77
- this.DrainDisposeQueue();
78
- }
256
+ if (this.surface === surface && !this.disposed)
257
+ this.DrawGuarded(c, surface);
79
258
  });
80
259
  }
81
260
  /** Deletes the current surface; a pending frame on it is cancelled first (drawing on a deleted surface faults). */
@@ -84,7 +263,8 @@ export class Canvas {
84
263
  cancelAnimationFrame(this.frameId);
85
264
  this.frameId = 0;
86
265
  }
87
- this.surface?.delete();
266
+ // dispose, not delete: a software surface owns pixels CanvasKit allocated for it, which delete() leaves behind
267
+ this.surface?.dispose();
88
268
  this.surface = undefined;
89
269
  }
90
270
  /** On-screen surface at the element's current pixel size, reusing the GL/GrContext when accelerated. */
@@ -92,7 +272,7 @@ export class Canvas {
92
272
  const CK = Super.CK;
93
273
  if (this.RenderingMode === "Accelerated") {
94
274
  if (!this.grContext) {
95
- this.glHandle = CK.GetWebGLContext(this.Element);
275
+ this.glHandle = Canvas.WithoutPolygonMode(() => CK.GetWebGLContext(this.Element));
96
276
  this.grContext = (this.glHandle ? CK.MakeWebGLContext(this.glHandle) : null) ?? undefined;
97
277
  }
98
278
  if (this.grContext) {
@@ -109,36 +289,113 @@ export class Canvas {
109
289
  * redrawn content lands in the same paint and no blank frame is ever shown while dragging.
110
290
  */
111
291
  OnResized() {
112
- const dpr = window.devicePixelRatio || 1;
113
- const w = Math.max(1, Math.round(this.Element.clientWidth * dpr));
114
- const h = Math.max(1, Math.round(this.Element.clientHeight * dpr));
292
+ let dpr = window.devicePixelRatio || 1;
293
+ // the device-pixel box can disagree with devicePixelRatio (DPR emulation in DevTools or Playwright, some zoom cases):
294
+ // past 2% the scale follows the box, so the layout keeps the element's CSS size (DrawnUi.Rust e7ff239)
295
+ if (this.devicePixels && this.devicePixelsCss > 0) {
296
+ const boxScale = this.devicePixels[0] / this.devicePixelsCss;
297
+ if (Math.abs(boxScale - dpr) > dpr * 0.02)
298
+ dpr = boxScale;
299
+ }
300
+ const w = Math.max(1, this.devicePixels?.[0] ?? Math.round(this.Element.clientWidth * dpr));
301
+ const h = Math.max(1, this.devicePixels?.[1] ?? Math.round(this.Element.clientHeight * dpr));
115
302
  if (this.surface && this.Element.width === w && this.Element.height === h && this.RenderingScale === dpr)
116
303
  return;
117
304
  this.RenderingScale = dpr;
118
305
  this.Element.width = w;
119
306
  this.Element.height = h;
307
+ if (this.contextLost)
308
+ return; // the restore makes the surface at this size
120
309
  this.ReleaseSurface();
121
310
  this.surface = this.CreateSurface(w, h);
122
311
  if (!this.surface)
123
312
  throw new Error("DrawnUi: cannot create surface");
124
313
  this.DrawNow();
125
314
  }
315
+ /**
316
+ * Registers the WebGL context without `WEBGL_polygon_mode` (drawnui-cross 6bt): Emscripten turns on every extension it
317
+ * knows while it registers a context, nothing here draws with that one, and WebKit warns "non-portable extension
318
+ * enabled" for it. The lookup is hidden only for this synchronous call (creating the context here first would change
319
+ * the attributes CanvasKit asks for).
320
+ */
321
+ static WithoutPolygonMode(make) {
322
+ const prototypes = [globalThis.WebGL2RenderingContext?.prototype, globalThis.WebGLRenderingContext?.prototype]
323
+ .filter((p) => !!p);
324
+ const originals = prototypes.map((p) => p.getExtension);
325
+ prototypes.forEach((p, i) => { p.getExtension = function (name) { return name === "WEBGL_polygon_mode" ? null : originals[i].call(this, name); }; });
326
+ try {
327
+ return make();
328
+ }
329
+ finally {
330
+ prototypes.forEach((p, i) => { p.getExtension = originals[i]; });
331
+ }
332
+ }
333
+ /**
334
+ * WebGL context lost: keep the browser restoring it (preventDefault) and stop the frames. The old Skia context is
335
+ * abandoned here, while the context is lost: WebGL ignores every call on a lost context without a word, so the GL
336
+ * deletes Skia makes while it lets go of its objects stay silent (done after the restore, they reach the new
337
+ * generation and every one logs "object does not belong to this context"). CanvasKit has no `abandonContext`;
338
+ * `releaseResourcesAndAbandonContext` is its only way, and after it freeing an old image or surface makes no GL call.
339
+ */
340
+ onContextLost = (e) => {
341
+ e.preventDefault();
342
+ this.contextLost = true;
343
+ if (this.frameId) {
344
+ cancelAnimationFrame(this.frameId);
345
+ this.frameId = 0;
346
+ }
347
+ if (this.grContext)
348
+ this.grContext.releaseResourcesAndAbandonContext();
349
+ this.surface?.dispose();
350
+ this.surface = undefined;
351
+ this.grContext?.delete();
352
+ this.grContext = undefined;
353
+ };
354
+ /**
355
+ * WebGL context restored (as DrawnUi.Rust and the C# Wasm / Blazor heads): every GL object of the lost generation is
356
+ * gone, and the old Skia context was abandoned when it was lost. The same WebGL object is registered again (the old
357
+ * handle deleted first, which clears the canvas' context object) with a new GrContext and surface; GpuEpoch makes the
358
+ * old generation's GPU objects remake themselves.
359
+ */
360
+ onContextRestored = () => {
361
+ if (this.disposed)
362
+ return;
363
+ if (this.grContext)
364
+ this.grContext.releaseResourcesAndAbandonContext(); // lost before this Canvas listened
365
+ this.surface?.dispose();
366
+ this.surface = undefined;
367
+ this.grContext?.delete();
368
+ this.grContext = undefined;
369
+ if (this.glHandle) {
370
+ Super.CK.deleteContext(this.glHandle);
371
+ this.glHandle = undefined;
372
+ }
373
+ this.contextLost = false;
374
+ this.GpuEpoch = Canvas.NextGpuEpoch();
375
+ this.surface = this.CreateSurface(this.Element.width, this.Element.height);
376
+ this.DrawNow();
377
+ };
126
378
  /** Draws one frame immediately (outside the rAF loop) and presents it. */
127
379
  DrawNow() {
128
380
  const surface = this.surface;
129
- if (!surface || this.disposed)
381
+ if (!surface || this.disposed || this.contextLost)
130
382
  return;
131
- this.Draw(surface.getCanvas());
132
- surface.flush();
133
- this.DrainDisposeQueue();
383
+ this.DrawGuarded(surface.getCanvas(), surface);
134
384
  }
135
385
  Draw(canvas) {
136
386
  const started = performance.now();
137
387
  this.ProcessPendingGestures();
138
- const executed = this.ExecuteAnimators(Math.round(started * 1_000_000));
388
+ this.ProcessTextSelectionFrame();
389
+ // Animators run on the frame's vsync time (inside a rAF callback document.timeline.currentTime is the frame
390
+ // timestamp), not on when this callback happened to start: callback starts drift by several ms around vsync
391
+ // (measured 12..23 ms between frames shown 16.7 ms apart), and a game loop moving by speed * delta then
392
+ // jumps unevenly on screen.
393
+ const frameTime = Number(document.timeline?.currentTime ?? started);
394
+ this.FrameTimeNanos = Math.round(frameTime * 1_000_000);
395
+ const executed = this.ExecuteAnimators(Math.round(frameTime * 1_000_000));
139
396
  const canRender = this.CanRender;
140
- if (canRender && !this.WasRendered)
141
- this.WillFirstTimeDraw?.(this, { Canvas: canvas, Surface: this.surface });
397
+ if (canRender && !this.WasRendered && this.WillFirstTimeDraw)
398
+ Canvas.Guard("WillFirstTimeDraw", this.WillFirstTimeDraw, () => this.WillFirstTimeDraw(this, { Canvas: canvas, Surface: this.surface }));
142
399
  canvas.clear(Super.ParseColor(this.BackgroundColor));
143
400
  const root = this.content;
144
401
  if (root) {
@@ -148,7 +405,16 @@ export class Canvas {
148
405
  root.Arrange(new SKRect(0, 0, w, h), root.WidthRequest, root.HeightRequest, scale);
149
406
  root.Render({ Context: { Canvas: canvas, Surface: this.surface }, Destination: new SKRect(0, 0, w, h), Scale: scale });
150
407
  }
408
+ // popup windows, then the tooltip, over everything
409
+ const top = { Context: { Canvas: canvas, Surface: this.surface }, Destination: new SKRect(0, 0, this.Element.width, this.Element.height), Scale: this.RenderingScale };
410
+ if (this.popupLayer?.HasAny)
411
+ this.popupLayer.Draw(top, top.Destination);
412
+ this.tooltipController?.Draw(top, top.Destination);
151
413
  this.AccessibilityManager.OnFrameEnd(this.RenderingScale, this.Element.width, this.Element.height, () => this.Update());
414
+ TextInputProxy.AfterFrame(this);
415
+ this.Hover.AfterFrame(this.content, this.activeTouchIds.size > 0);
416
+ if (this.Hover.Paused)
417
+ this.tooltipController?.Reset(); // content moves under the pointer
152
418
  const now = performance.now();
153
419
  this.FrameTime = now - started;
154
420
  this.FrameIndex++;
@@ -156,10 +422,15 @@ export class Canvas {
156
422
  while (this.frameTimes.length && this.frameTimes[0] < now - 1000)
157
423
  this.frameTimes.shift();
158
424
  this.FPS = this.frameTimes.length;
425
+ this.ForgetGoneControls();
159
426
  if (executed > 0)
160
427
  this.Update(); // animators running: keep frames coming
161
428
  // C# order: WasDrawn at the end of the frame, then the frame counts as rendered
162
- this.WasDrawn?.(this);
429
+ if (this.WasDrawn)
430
+ Canvas.Guard("WasDrawn", this.WasDrawn, () => this.WasDrawn(this));
431
+ const listeners = this.wasDrawnListeners;
432
+ if (listeners !== undefined && listeners.size > 0)
433
+ listeners.forEach(this.raiseWasDrawn);
163
434
  if (!this.WasRendered && canRender)
164
435
  this.WasRendered = true;
165
436
  }
@@ -183,21 +454,148 @@ export class Canvas {
183
454
  return true;
184
455
  }
185
456
  UnregisterAnimator(uid) { this.AnimatingControls.delete(uid); }
457
+ /**
458
+ * `root` leaves this canvas (removed from its parent, replaced as content, disposed): what runs for its subtree stops,
459
+ * as DrawnUi.Rust 44c718f. Its animators leave the frame loop: disposed, they stop; only removed, they pause and wait on
460
+ * their control (PendingUnattachedAnimators), going on from there when it is arranged on a canvas again. A focused editor in it loses the
461
+ * focus, a game in it stops getting keys (CanvasLeaveWatchers). Runs once per removal, never per frame.
462
+ */
463
+ ControlLeft(root, disposed) {
464
+ const inside = (c) => { for (let p = c; p; p = p.Parent)
465
+ if (p === root)
466
+ return true; return false; };
467
+ for (const a of this.AnimatingControls.values()) {
468
+ const control = a.Parent;
469
+ if (!control || !inside(control))
470
+ continue;
471
+ this.AnimatingControls.delete(a.Uid);
472
+ if (disposed || control.IsDisposed)
473
+ a.Stop();
474
+ else {
475
+ // paused as a hidden control's animator is: the time off the canvas is not counted when it goes on
476
+ if (!a.IsPaused) {
477
+ a.Pause();
478
+ a.PausedWhileHidden = true;
479
+ }
480
+ if (!control.PendingUnattachedAnimators?.includes(a))
481
+ (control.PendingUnattachedAnimators ??= []).push(a);
482
+ }
483
+ }
484
+ for (const c of [...CanvasLeaveWatchers])
485
+ if (inside(c))
486
+ c.OnLeftCanvas();
487
+ }
488
+ static reportedAnimators = new WeakSet();
489
+ /** An animator's callback threw: logged once for that animator, the frame goes on. */
490
+ /**
491
+ * One exception never stops the frame loop (drawnui-cross 6ch, DrawnUi.Net 3db4eba3): app code the frame runs (a
492
+ * listener, a gesture handler) is called through this; a throw is logged once per source and the frame goes on.
493
+ */
494
+ static Guard(what, source, call) {
495
+ try {
496
+ return call();
497
+ }
498
+ catch (e) {
499
+ if (!Canvas.reportedSources.has(source)) {
500
+ Canvas.reportedSources.add(source);
501
+ console.error(`DrawnUi: ${what} threw; the frame goes on`, e);
502
+ }
503
+ return undefined;
504
+ }
505
+ }
506
+ static reportedSources = new WeakSet();
507
+ /**
508
+ * Draws a frame and always shows it: a throw inside it (app drawing code) is logged once, the canvas state is reset and
509
+ * the frame loop goes on (a running animation or game keeps asking for frames).
510
+ */
511
+ DrawGuarded(canvas, surface) {
512
+ try {
513
+ this.Draw(canvas);
514
+ }
515
+ catch (e) {
516
+ canvas.restoreToCount(1);
517
+ if (!Canvas.reportedFrameError) {
518
+ Canvas.reportedFrameError = true;
519
+ console.error("DrawnUi: drawing a frame threw; the next frames go on", e);
520
+ }
521
+ if (this.AnimatingControls.size > 0)
522
+ this.Update();
523
+ }
524
+ finally {
525
+ surface.flush();
526
+ this.DrainDisposeQueue();
527
+ }
528
+ }
529
+ static reportedFrameError = false;
530
+ static ReportAnimatorError(a, e) {
531
+ if (Canvas.reportedAnimators.has(a))
532
+ return;
533
+ Canvas.reportedAnimators.add(a);
534
+ console.error("DrawnUi: an animator's callback threw; the other animators and the frame go on", e);
535
+ }
186
536
  /** Ticks every registered animator once; returns how many ran. */
187
537
  ExecuteAnimators(frameTimeNanos) {
188
- let executed = 0;
538
+ let executed = 0, wake = Infinity;
189
539
  for (const a of [...this.AnimatingControls.values()]) {
190
540
  if (!a.Parent) {
191
541
  this.AnimatingControls.delete(a.Uid);
192
542
  continue;
193
543
  }
194
- a.TickFrame(frameTimeNanos);
544
+ // the control or a parent is hidden: its animator pauses, no frames, and goes on from where it was when shown
545
+ if (a.Parent.HiddenInTree()) {
546
+ if (!a.IsPaused) {
547
+ a.Pause();
548
+ a.PausedWhileHidden = true;
549
+ }
550
+ continue;
551
+ }
552
+ if (a.PausedWhileHidden) {
553
+ a.PausedWhileHidden = false;
554
+ a.Resume();
555
+ }
556
+ if (a.IsPaused)
557
+ continue; // a paused animator neither ticks nor keeps frames coming (C# DrawnView)
558
+ if (a.SleepUntilNanos > frameTimeNanos) {
559
+ wake = Math.min(wake, a.SleepUntilNanos);
560
+ continue;
561
+ } // nothing changes yet
562
+ // one animator whose callback throws must not stop the others or the frame (DrawnUi.Net catches the pass, Super.Log)
563
+ try {
564
+ a.TickFrame(frameTimeNanos);
565
+ }
566
+ catch (e) {
567
+ Canvas.ReportAnimatorError(a, e);
568
+ }
195
569
  executed++;
570
+ if (a.SleepUntilNanos > frameTimeNanos)
571
+ wake = Math.min(wake, a.SleepUntilNanos);
196
572
  }
573
+ this.WakeAt(wake, frameTimeNanos);
197
574
  return executed;
198
575
  }
576
+ wakeTimer = 0;
577
+ wakeAtNanos = Infinity;
578
+ /** One timer for the earliest sleeping animator: the frame loop wakes then, no frames run in between. */
579
+ WakeAt(nanos, nowNanos) {
580
+ if (!isFinite(nanos))
581
+ return;
582
+ if (this.wakeTimer && this.wakeAtNanos <= nanos)
583
+ return;
584
+ if (this.wakeTimer)
585
+ clearTimeout(this.wakeTimer);
586
+ this.wakeAtNanos = nanos;
587
+ this.wakeTimer = window.setTimeout(() => { this.wakeTimer = 0; this.wakeAtNanos = Infinity; this.Update(); }, Math.max(0, (nanos - nowNanos) / 1_000_000));
588
+ }
199
589
  /** Frames drawn so far (SkiaBackdrop uses it to refresh once after a cached record). */
200
590
  FrameIndex = 0;
591
+ /**
592
+ * DrawnView.WheelDeltaPerNotch: the Wheel.Delta one mouse-wheel notch produces, 100 CSS pixels in Chrome and Edge. A
593
+ * scroll moves by the event's share of a notch, so a touchpad, which sends many small events, scrolls as far as the
594
+ * fingers moved. 0 = units unknown: every event scrolls one line.
595
+ */
596
+ WheelDeltaPerNotch = 100;
597
+ /** Vsync time of the last frame the animators ran on (nanoseconds, the performance.now() timeline). */
598
+ FrameTimeNanos = 0;
201
599
  /** On-screen surface (SkiaBackdrop snapshots it). */
202
600
  get Surface() { return this.surface; }
203
601
  /**
@@ -241,16 +639,36 @@ export class Canvas {
241
639
  }
242
640
  }
243
641
  finally {
244
- surface.delete();
642
+ surface.dispose(); // its pixels too (CK.MakeSurface allocates them)
245
643
  }
246
644
  }
247
645
  Dispose() {
248
646
  this.disposed = true;
647
+ if (this.wakeTimer) {
648
+ clearTimeout(this.wakeTimer);
649
+ this.wakeTimer = 0;
650
+ }
651
+ this.Element.removeEventListener("webglcontextlost", this.onContextLost);
652
+ this.Element.removeEventListener("webglcontextrestored", this.onContextRestored);
653
+ this.themeQuery?.removeEventListener?.("change", this.onThemeQuery);
654
+ this.SystemThemeChanged = undefined;
655
+ window.removeEventListener("blur", this.onWindowInactive);
656
+ window.removeEventListener("focus", this.onWindowActive);
657
+ this.WindowActiveChanged.clear();
249
658
  this.Gestures = "Disabled";
659
+ this.ArrowsStartKeyboardNavigation = false;
660
+ this.tooltipController?.Dispose();
661
+ this.popupLayer?.Dispose();
662
+ this.HookPopupKeys(false);
250
663
  this.observer.disconnect();
251
664
  this.content?.Dispose();
252
665
  this.Content = undefined;
666
+ this.DrainDisposeQueue(); // what the last frames handed over for deletion goes while the context lives
253
667
  this.ReleaseSurface();
668
+ // GPU objects that outlive this canvas (a control the app keeps and shows on another canvas) are freed later, under
669
+ // another WebGL context: the abandoned Skia context makes no GL call when they go (as DrawnUi.Net Cells 81b89f1a)
670
+ if (this.grContext && !this.contextLost)
671
+ this.grContext.releaseResourcesAndAbandonContext();
254
672
  this.grContext?.delete();
255
673
  this.grContext = undefined;
256
674
  if (this.glHandle) {
@@ -274,6 +692,163 @@ export class Canvas {
274
692
  pointerDownArgs = new Map();
275
693
  previousTouchArgs = new Map();
276
694
  pendingGestures = [];
695
+ // ---- page text selection with the mouse, as in browsers (port of C# DrawnView.TextSelection, drawnui-cross 6cc) ----
696
+ // A main-button drag that starts on no interactive control selects the selectable labels (AccessibilityTextSelectable)
697
+ // it crosses, in reading order, the first and last partly. Idle cost: one check per gesture and per frame.
698
+ textDrag;
699
+ pageSelection = [];
700
+ pageSelectionKeys = false;
701
+ /**
702
+ * The text selected on the page: the labels a mouse drag selected, joined with new lines, in page order; else the
703
+ * selection of the label in focus. Empty when nothing is selected.
704
+ */
705
+ get SelectedText() {
706
+ if (this.pageSelection.length > 0)
707
+ return this.pageSelection.map((l) => l.SelectedText).filter((t) => t).join("\n");
708
+ return this.focusedChild?.SelectedText ?? "";
709
+ }
710
+ /** True while a mouse drag selection holds page text: the page, not a label, owns Ctrl+C. */
711
+ get OwnsTextSelectionKeys() { return this.pageSelection.some((l) => l.SelectionLength > 0); }
712
+ /** Puts SelectedText on the clipboard through Super.SetClipboardText. False when nothing is selected. */
713
+ CopyTextSelection() {
714
+ const text = this.SelectedText;
715
+ if (!text)
716
+ return false;
717
+ Super.SetClipboardText(text);
718
+ return true;
719
+ }
720
+ /** Drops the page text selection (every label a drag selected) and the selection of the label in focus. */
721
+ ClearTextSelection() {
722
+ for (const label of this.pageSelection)
723
+ label.ClearSelection();
724
+ this.pageSelection.length = 0;
725
+ this.focusedChild?.ClearSelection?.();
726
+ this.AttachPageSelectionKeys(false);
727
+ }
728
+ /**
729
+ * Before a gesture goes to the controls: a mouse drag that is selecting text keeps its moves (a scroll under it does
730
+ * not scroll), a main-button press drops the previous page selection. True when the gesture was used here.
731
+ */
732
+ PreviewTextSelectionGesture(args) {
733
+ const mouseMain = args.Event.Pointer?.DeviceType === "Mouse" && args.Event.Pointer.Button === "Left";
734
+ const drag = this.textDrag;
735
+ if (args.Type === "Down" && mouseMain) {
736
+ this.textDrag = undefined;
737
+ // a press on an open popup window (the menu that copies the selection) keeps it, as browsers keep a selection
738
+ // while their context menu is used
739
+ const onPopup = this.popups.HasInteractive && !!this.popups.At(args.Event.Location.X, args.Event.Location.Y);
740
+ if (this.pageSelection.length > 0 && !onPopup)
741
+ this.ClearTextSelection();
742
+ }
743
+ else if (args.Type === "Panning" && drag) {
744
+ drag.X = args.Event.Location.X;
745
+ drag.Y = args.Event.Location.Y;
746
+ drag.Moved = true;
747
+ this.UpdateTextDrag(drag);
748
+ this.Update();
749
+ return true;
750
+ }
751
+ else if (args.Type === "Up" && drag) {
752
+ if (drag.Moved)
753
+ this.UpdateTextDrag(drag);
754
+ this.textDrag = undefined;
755
+ }
756
+ return false;
757
+ }
758
+ /**
759
+ * After a mouse main-button press went to the controls: when it landed on no interactive control (empty space, a
760
+ * scroll's empty area, a selectable label), a drag from here selects text. Not inside a scroll that holds no
761
+ * selectable text: that one keeps scrolling by mouse drag.
762
+ */
763
+ AfterTextSelectionDown(args, consumed) {
764
+ if (args.Type !== "Down" || args.Event.Pointer?.DeviceType !== "Mouse" || args.Event.Pointer.Button !== "Left")
765
+ return;
766
+ if (consumed && !IsScroll(consumed) && !IsSelectableLabel(consumed))
767
+ return;
768
+ if (consumed && IsScroll(consumed) && consumed.ScrollBarOwnsGesture)
769
+ return; // a press on the scroll bar drags the bar
770
+ const collected = [];
771
+ if (this.content)
772
+ CollectSelectable(this.content, collected);
773
+ if (collected.length === 0)
774
+ return;
775
+ const labels = ReadingOrder(collected);
776
+ const x = args.Event.Location.X, y = args.Event.Location.Y;
777
+ const scroll = (consumed && IsScroll(consumed) ? consumed : undefined) ?? ScrollOf(consumed ?? undefined) ?? ScrollAt(labels, x, y);
778
+ if (scroll && !labels.some((l) => IsInside(l, scroll)))
779
+ return;
780
+ const [label, index] = Locate(labels, x, y);
781
+ if (!label)
782
+ return;
783
+ this.textDrag = { Labels: labels, StartLabel: label, StartIndex: index, Scroll: scroll, X: x, Y: y, Moved: false };
784
+ }
785
+ /** Frame start: while a drag holds the pointer past a scroll's top or bottom edge, the scroll follows it. */
786
+ ProcessTextSelectionFrame() {
787
+ const drag = this.textDrag;
788
+ if (!drag?.Scroll || !drag.Moved)
789
+ return;
790
+ const view = drag.Scroll.GetAccessibilityPixelRect();
791
+ if (view.Width <= 0 || view.Height <= 0)
792
+ return;
793
+ const past = drag.Y > view.Bottom ? drag.Y - view.Bottom : drag.Y < view.Top ? drag.Y - view.Top : 0;
794
+ if (past === 0)
795
+ return;
796
+ // faster the farther past the edge, as browsers do
797
+ const step = Math.min(Math.max(Math.abs(past) * 0.25, 2), 40) / this.RenderingScale * Math.sign(past);
798
+ drag.Scroll.ScrollTo(drag.Scroll.ViewportOffsetX, drag.Scroll.ViewportOffsetY - step, 0, true);
799
+ this.UpdateTextDrag(drag);
800
+ this.Update();
801
+ }
802
+ UpdateTextDrag(drag) {
803
+ const [endLabel, endIndex] = Locate(drag.Labels, drag.X, drag.Y);
804
+ if (!endLabel)
805
+ return;
806
+ const a = drag.Labels.indexOf(drag.StartLabel), b = drag.Labels.indexOf(endLabel);
807
+ if (a < 0 || b < 0)
808
+ return;
809
+ const [fromLabel, fromIndex, toLabel, toIndex] = a < b || (a === b && drag.StartIndex <= endIndex)
810
+ ? [a, drag.StartIndex, b, endIndex] : [b, endIndex, a, drag.StartIndex];
811
+ for (const label of this.pageSelection) {
812
+ const at = drag.Labels.indexOf(label);
813
+ if (at < fromLabel || at > toLabel)
814
+ label.ClearSelection();
815
+ }
816
+ this.pageSelection.length = 0;
817
+ for (let i = fromLabel; i <= toLabel; i++) {
818
+ const label = drag.Labels[i];
819
+ const start = i === fromLabel ? fromIndex : 0, end = i === toLabel ? toIndex : label.SelectableLength;
820
+ label.Select(start, Math.max(0, end - start));
821
+ this.pageSelection.push(label);
822
+ }
823
+ this.AttachPageSelectionKeys(this.OwnsTextSelectionKeys);
824
+ }
825
+ AttachPageSelectionKeys(attach) {
826
+ if (attach === this.pageSelectionKeys)
827
+ return;
828
+ this.pageSelectionKeys = attach;
829
+ if (attach)
830
+ KeyboardManager.Subscribe(this.onPageSelectionKey, Canvas.noChar);
831
+ else
832
+ KeyboardManager.Unsubscribe(this.onPageSelectionKey, Canvas.noChar);
833
+ }
834
+ static noChar = () => { };
835
+ onPageSelectionKey = (key, e) => {
836
+ // Esc keeps the selection, as in browsers: a click elsewhere drops it
837
+ if (KeyboardManager.IsOwnedByElement(e) || !KeyboardManager.IsControlPressed)
838
+ return;
839
+ if (key === "KeyC")
840
+ this.CopyTextSelection();
841
+ else if (key === "KeyA" && IsSelectableLabel(this.focusedChild)) {
842
+ // as for one label: Ctrl+A selects all of the label in focus
843
+ e.preventDefault();
844
+ const focused = this.focusedChild;
845
+ for (const label of this.pageSelection)
846
+ label.ClearSelection();
847
+ this.pageSelection.length = 0;
848
+ this.AttachPageSelectionKeys(false);
849
+ focused.SelectAll();
850
+ }
851
+ };
277
852
  onPointer = (e) => {
278
853
  const type = e.type === "pointerdown" ? "Pressed" :
279
854
  e.type === "pointermove" ? "Moved" :
@@ -282,13 +857,24 @@ export class Canvas {
282
857
  if (!type)
283
858
  return;
284
859
  if (type === "Moved" && !this.activeTouchIds.has(e.pointerId)) {
860
+ if (e.pointerType === "touch")
861
+ return; // touch never hovers
862
+ const hx = e.offsetX * this.RenderingScale, hy = e.offsetY * this.RenderingScale;
863
+ if (this.activeTouchIds.size === 0) {
864
+ this.Hover.Move(this.content, hx, hy);
865
+ this.tooltip.OnPointerMove(this.Hover.Path, hx, hy);
866
+ }
867
+ if (this.popups.HasAny)
868
+ this.popups.PointerAt(hx, hy);
285
869
  if (e.pointerType === "mouse")
286
- this.UpdateCursor(e.offsetX, e.offsetY);
870
+ this.UpdateCursor();
287
871
  return;
288
- } // hover not ported (TouchActionResult.Pointer)
872
+ }
289
873
  if ((type === "Released" || type === "Cancelled") && !this.activeTouchIds.has(e.pointerId))
290
874
  return; // Up of a pointer that never pressed here
291
875
  // Capture so Up outside the element still arrives; throws for synthetic events (tests) — harmless.
876
+ if (type === "Pressed")
877
+ this.tooltip.CloseOnInput();
292
878
  if (type === "Pressed") {
293
879
  try {
294
880
  this.Element.setPointerCapture(e.pointerId);
@@ -297,6 +883,7 @@ export class Canvas {
297
883
  }
298
884
  const rect = this.Element.getBoundingClientRect();
299
885
  const args = new TouchActionEventArgs();
886
+ args.Timestamp = EventTime(e);
300
887
  args.Id = e.pointerId;
301
888
  args.Type = type;
302
889
  args.Scale = this.RenderingScale;
@@ -310,46 +897,235 @@ export class Canvas {
310
897
  pd.PressedButtons = e.buttons;
311
898
  args.Pointer = pd;
312
899
  this.OnTouchAction(args);
313
- if (type === "Released" || type === "Cancelled")
900
+ if (type === "Released" || type === "Cancelled") {
901
+ this.claimedTouches.delete(e.pointerId);
314
902
  this.UpdateTouchAction();
903
+ }
904
+ // a click on the focused field gives its input DOM focus again (desktop typing and IME); on touch that is done in the
905
+ // touchend (onTouchEnd), the only event iOS opens the soft keyboard from
906
+ if (type === "Released" && e.pointerType === "mouse")
907
+ TextInputProxy.FocusFromTap(e.clientX, e.clientY);
908
+ // the touch taps the browser delivered, for a double tap whose second tap it kept (onDoubleClick)
909
+ if (type === "Released" && e.pointerType !== "mouse" && !this.replayingTap) {
910
+ this.touchUps.push(performance.now());
911
+ if (this.touchUps.length > 2)
912
+ this.touchUps.shift();
913
+ }
914
+ };
915
+ /** The mouse left the canvas: hover ends at once, also while content moves. */
916
+ onPointerLeave = (e) => {
917
+ if (e.pointerType === "touch")
918
+ return;
919
+ this.Hover.Leave();
920
+ this.tooltip.Reset();
921
+ if (this.popups.HasAny)
922
+ this.popups.PointerAt(undefined, undefined);
315
923
  };
316
924
  preventTouch = (e) => e.preventDefault();
925
+ // ---- the on-screen keyboard (C# DrawnView.Keyboard, drawnui-cross 6cj: SkiaScroll.AdaptToKeyboardAuto, off by default) ----
926
+ /** Points of this canvas, up from its bottom, that the on-screen keyboard covers (0 when none). */
927
+ KeyboardCovered = 0;
928
+ keyboardScroll;
929
+ onViewportResize = () => this.ApplyKeyboard();
930
+ /**
931
+ * Measures the part the keyboard covers (the visual viewport shrinks when it opens) and, when the focused text field sits
932
+ * in a scroll with AdaptToKeyboardAuto, hands that scroll the field and the covered height; the scroll it adapted lets go
933
+ * when the keyboard closes or the field moves to another scroll. Runs on viewport resizes and focus changes only.
934
+ */
935
+ ApplyKeyboard() {
936
+ const vv = typeof window !== "undefined" ? window.visualViewport : undefined;
937
+ if (!vv)
938
+ return;
939
+ const layoutH = window.innerHeight, visibleBottom = vv.offsetTop + vv.height;
940
+ // a keyboard shrinks the visual viewport against the layout viewport (a page zoom scales it instead)
941
+ const keyboard = layoutH - vv.height > 80 && Math.abs((vv.scale ?? 1) - 1) < 0.01;
942
+ const b = this.Element.getBoundingClientRect();
943
+ const covered = keyboard ? Math.max(0, Math.min(b.bottom, layoutH) - visibleBottom) : 0;
944
+ this.KeyboardCovered = covered;
945
+ let scroll;
946
+ const field = this.focusedChild;
947
+ if (covered > 0 && field?.IsFocused && field.CursorPosition !== undefined) {
948
+ for (let p = field.Parent; p && !scroll; p = p.Parent)
949
+ if (p.AdaptToKeyboardAuto)
950
+ scroll = p;
951
+ if (scroll) {
952
+ scroll.AdaptToKeyboardFor = field;
953
+ scroll.AdaptToKeyboardSize = covered;
954
+ }
955
+ }
956
+ // keyboard up, no focused field (between two fields): the adapted scroll keeps its room
957
+ if (covered > 0 && !scroll)
958
+ return;
959
+ if (this.keyboardScroll && this.keyboardScroll !== scroll) {
960
+ this.keyboardScroll.AdaptToKeyboardFor = undefined;
961
+ this.keyboardScroll.AdaptToKeyboardSize = 0;
962
+ }
963
+ this.keyboardScroll = scroll;
964
+ }
965
+ /** When the last touch releases came (ms), at most two. */
966
+ touchUps = [];
967
+ replayingTap = false;
968
+ /**
969
+ * iOS Safari (measured on an iPhone, iOS 26.6.1) takes the second tap of a double tap for itself: it sends no pointer or
970
+ * touch event for it, only click, click and dblclick. A dblclick that follows ONE touch release (the other browsers
971
+ * deliver both taps first) brings that tap back as a touch tap at its place, so a double tap reaches the controls (a 3D
972
+ * viewer's reset).
973
+ */
974
+ onDoubleClick = (e) => {
975
+ const now = performance.now(), recent = this.touchUps.filter((t) => now - t < 700);
976
+ this.touchUps.length = 0;
977
+ if (recent.length !== 1)
978
+ return;
979
+ const pointerId = 2_000_000 + Math.floor(now);
980
+ // the second tap happened just before the dblclick: dated by it, not by when a frame handles it
981
+ const at = { clientX: e.clientX, clientY: e.clientY, pointerId, pointerType: "touch", button: 0, isTrusted: true, timeStamp: e.timeStamp };
982
+ this.replayingTap = true;
983
+ try {
984
+ this.onPointer({ ...at, type: "pointerdown", buttons: 1 });
985
+ this.onPointer({ ...at, type: "pointerup", buttons: 0 });
986
+ }
987
+ finally {
988
+ this.replayingTap = false;
989
+ }
990
+ };
991
+ /**
992
+ * The end of a touch is the user gesture iOS opens the soft keyboard from (a focus() in pointerup does not open it): the
993
+ * press's gestures run now, inside it, so a field they focus focuses its input here, and a tap on the focused field gives
994
+ * its input focus again.
995
+ */
996
+ /** A finger or a pen is down on the canvas: a text field focused now takes its input focus in the touchend (onTouchEnd). */
997
+ get TouchPressed() {
998
+ for (const a of this.pointerDownArgs.values())
999
+ if (a.Pointer && a.Pointer.DeviceType !== "Mouse")
1000
+ return true;
1001
+ return false;
1002
+ }
1003
+ onTouchEnd = (e) => {
1004
+ TextInputProxy.TouchGesture = true;
1005
+ try {
1006
+ this.ProcessPendingGestures();
1007
+ }
1008
+ finally {
1009
+ TextInputProxy.TouchGesture = false;
1010
+ }
1011
+ const t = e.changedTouches[0];
1012
+ // the input has focus now: no compatibility mouse events or click follow, whose focus would go to the canvas host
1013
+ // and take the keyboard away again
1014
+ if (t && TextInputProxy.FocusFromTap(t.clientX, t.clientY, true) && e.cancelable)
1015
+ e.preventDefault();
1016
+ TextInputProxy.AfterTouchEnd();
1017
+ };
1018
+ /** Gestures="Enabled": touch / pen pointers whose Down a control used (see OnTouchAction). */
1019
+ claimedTouches = new Set();
1020
+ /** Gestures="Enabled": while a claimed touch is down the page may not take its drag. */
1021
+ preventClaimedTouch = (e) => { if (this.claimedTouches.size > 0 && e.cancelable)
1022
+ e.preventDefault(); };
317
1023
  /** Called when no control handled a context-menu request; return true to suppress the browser's canvas menu. */
318
1024
  ContextMenu;
319
1025
  /** DOM contextmenu (right click / long press / Menu key) -> ContextMenuEventArgs routed through the tree like a tap. */
320
1026
  onContextMenu = (e) => {
321
- const rect = this.Element.getBoundingClientRect();
322
- const scale = this.RenderingScale;
323
- const x = e.clientX - rect.left, y = e.clientY - rect.top;
324
1027
  const pointerType = e.pointerType;
325
1028
  const source = pointerType === "touch" || pointerType === "pen" ? "touch" : pointerType === "mouse" || e.button === 2 ? "mouse" : "keyboard";
326
- const args = new ContextMenuEventArgs(new SKPoint(x, y), new SKPoint(x * scale, y * scale), source, e);
327
- let handled = this.content?.ProcessContextMenu(args.Pixels, args) ?? false;
328
- if (!handled && this.ContextMenu)
329
- handled = this.ContextMenu(this, args) === true;
1029
+ // a long press: the browser's own contextmenu (Android Chrome) or the press's long press raises it, once (6cb); a
1030
+ // browser menu that comes first runs the long press before it (the word under the finger is selected first, C#
1031
+ // SkipRepeatedTouchContextMenu)
1032
+ if (source === "touch")
1033
+ this.LongPressNow(e.pointerId);
1034
+ // the press the menu comes from first, in the order it happened (the browser sends contextmenu at the press on macOS
1035
+ // and Linux, after the release on Windows): processed later, its press would close a menu that opens now
1036
+ else
1037
+ this.ProcessPendingGestures();
1038
+ const handled = source === "touch" ? this.RaiseTouchContextMenu(e.clientX, e.clientY, e) : this.RaiseContextMenu(e.clientX, e.clientY, source, e);
330
1039
  if (handled)
331
1040
  e.preventDefault();
1041
+ // a menu opened while the button is still down: the rest of that press goes nowhere (its release would tap the item
1042
+ // under it)
1043
+ if (source !== "touch" && this.activeTouchIds.size > 0 && this.popups.HasInteractive)
1044
+ this.popups.SwallowPress = true;
332
1045
  };
1046
+ /** A context-menu request at a point of the page (client CSS px), routed through the tree like a tap; true when one took it. */
1047
+ RaiseContextMenu(clientX, clientY, source, native) {
1048
+ const rect = this.Element.getBoundingClientRect();
1049
+ const scale = this.RenderingScale;
1050
+ const x = clientX - rect.left, y = clientY - rect.top;
1051
+ const args = new ContextMenuEventArgs(new SKPoint(x, y), new SKPoint(x * scale, y * scale), source, native);
1052
+ this.tooltip.CloseOnInput();
1053
+ // over a popup window its content is asked; elsewhere the popups close and the request goes on, so a new menu can
1054
+ // open there (C# PopupLayer ContextMenu)
1055
+ const popupRoot = this.popups.HasInteractive ? this.popups.At(args.Pixels.X, args.Pixels.Y) : undefined;
1056
+ if (popupRoot) {
1057
+ popupRoot.ProcessContextMenu(args.Pixels, args);
1058
+ return true;
1059
+ }
1060
+ if (this.popups.HasInteractive) {
1061
+ this.popups.CloseAll(false);
1062
+ this.AfterPopupsChanged();
1063
+ }
1064
+ let handled = this.content?.ProcessContextMenu(args.Pixels, args) ?? false;
1065
+ if (!handled && this.ContextMenu)
1066
+ handled = this.ContextMenu(this, args) === true;
1067
+ return handled;
1068
+ }
1069
+ // ---- a long press on touch raises the context menu (drawnui-cross 6cb) ----
1070
+ /** The touch or pen press going on: its context menu is raised once, by the browser's contextmenu or after its long press. */
1071
+ touchMenu;
1072
+ /** The long press of a touch press was just queued: its context menu follows the LongPressing (client CSS px). */
1073
+ touchMenuDue;
1074
+ /** A touch or pen press starts (on the canvas, or on selectable text of the overlay): its context menu is still to come. */
1075
+ StartTouchPress() { this.touchMenu = { Raised: false, Handled: false }; }
1076
+ /**
1077
+ * The context menu of the touch press now (Source "touch"), raised once per press whoever asks first: the browser's own
1078
+ * contextmenu (Android Chrome fires one on a long press) or the press's long press (iOS Safari fires none). True when a
1079
+ * handler took it: the browser's own menu is then suppressed where it can be.
1080
+ */
1081
+ RaiseTouchContextMenu(clientX, clientY, native) {
1082
+ const press = this.touchMenu ??= { Raised: false, Handled: false };
1083
+ if (press.Raised)
1084
+ return press.Handled;
1085
+ press.Raised = true;
1086
+ press.Handled = this.RaiseContextMenu(clientX, clientY, "touch", native ?? new MouseEvent("contextmenu", { clientX, clientY }));
1087
+ // the app showed its own menu: the drawn Copy button of a touch text selection steps aside, the selection stays
1088
+ if (press.Handled)
1089
+ this.focusedChild?.HideCopyButton?.();
1090
+ return press.Handled;
1091
+ }
1092
+ /**
1093
+ * The Menu key, Shift+F10 or a screen reader's context-menu command on the control in keyboard focus (the DOM
1094
+ * `contextmenu` of its overlay node): its context menu opens at its center, from it or the first control above it with
1095
+ * a ContextMenu handler, then the Canvas' own (Source "keyboard", as every DrawnUI engine). True when one took it.
1096
+ */
1097
+ OpenContextMenuFromKeyboard(control, native) {
1098
+ const r = control.GetAccessibilityPixelRect(), scale = this.RenderingScale;
1099
+ const pixels = new SKPoint((r.Left + r.Right) / 2, (r.Top + r.Bottom) / 2);
1100
+ const args = new ContextMenuEventArgs(new SKPoint(pixels.X / scale, pixels.Y / scale), pixels, "keyboard", native);
1101
+ this.tooltip.CloseOnInput();
1102
+ for (let c = control; c; c = c.Parent) {
1103
+ if (!c.ContextMenu)
1104
+ continue;
1105
+ args.Control = c;
1106
+ args.Local = new SKPoint(pixels.X - c.DrawingRect.Left, pixels.Y - c.DrawingRect.Top);
1107
+ if (c.ContextMenu(c, args) === true)
1108
+ return true;
1109
+ }
1110
+ args.Control = undefined;
1111
+ return !!this.ContextMenu && this.ContextMenu(this, args) === true;
1112
+ }
333
1113
  cursorPointer = false;
334
1114
  /**
335
1115
  * DrawnUi.Blazor shows `cursor: pointer` over interactive controls through its overlay elements; here the overlay
336
- * is pointer-events:none, so the mouse position is tested against the accessibility snapshot (the accessible
337
- * controls' rects in points, already sorted and rate-limited), each hit control answering WantsPointerCursor
338
- * (itself tappable, or a tappable span of a label), and the canvas element's cursor is switched only when the
339
- * answer changes. Mouse moves only, no work without a mouse and none in the frame loop.
1116
+ * is pointer-events:none, so the canvas decides from the hover hit path (Hover.Path: the controls under the mouse by
1117
+ * the routing rules of ProcessGestures, so nothing below a popup that blocks gestures below): a control in the
1118
+ * accessibility tree (it has a role) that answers WantsPointerCursor (itself tappable, or a tappable span of a label)
1119
+ * shows the hand. A popup's close-on-background-tap wrapper has no role, so its backdrop shows none. The canvas
1120
+ * element's cursor is switched only when the answer changes. Mouse moves only, none in the frame loop.
340
1121
  */
341
- UpdateCursor(x, y) {
1122
+ UpdateCursor() {
342
1123
  let hit = false;
343
- const scale = this.RenderingScale;
344
- for (const n of this.AccessibilityManager.Snapshot) {
345
- if (x < n.Rect.Left || x >= n.Rect.Right || y < n.Rect.Top || y >= n.Rect.Bottom)
346
- continue;
347
- // the control decides (whole control, or a tappable span of a label); point in pixels relative to the control's
348
- // origin, taken from the snapshot rect (already carries the scroll / cache offset; a rotated control gets its bbox)
349
- if (n.Source.WantsPointerCursor((x - n.Rect.Left) * scale, (y - n.Rect.Top) * scale)) {
1124
+ const path = this.Hover.Path, xs = this.Hover.PathX, ys = this.Hover.PathY;
1125
+ for (let i = path.length - 1; i >= 0 && !hit; i--) {
1126
+ const c = path[i];
1127
+ if (c.IsAccessibilityElement && c.WantsPointerCursor(xs[i] - c.DrawingRect.Left, ys[i] - c.DrawingRect.Top))
350
1128
  hit = true;
351
- break;
352
- }
353
1129
  }
354
1130
  if (hit !== this.cursorPointer) {
355
1131
  this.cursorPointer = hit;
@@ -366,12 +1142,19 @@ export class Canvas {
366
1142
  onWheel = (e) => {
367
1143
  const rect = this.Element.getBoundingClientRect();
368
1144
  const args = new TouchActionEventArgs();
1145
+ args.Timestamp = EventTime(e);
369
1146
  args.Id = -1;
370
1147
  args.Type = "Wheel";
371
1148
  args.Scale = this.RenderingScale;
372
1149
  args.Location = new SKPoint((e.clientX - rect.left) * this.RenderingScale, (e.clientY - rect.top) * this.RenderingScale);
373
1150
  args.StartingLocation = args.Location;
374
- args.Wheel = { Delta: e.deltaY !== 0 ? e.deltaY : e.deltaX };
1151
+ // lines and pages to pixels, then the dominant axis (the .NET browser heads, fc8980c1); a vertical scroll leaves
1152
+ // horizontal events alone (C# ba03cb20)
1153
+ const factor = e.deltaMode === 1 ? 40 : e.deltaMode === 2 ? 800 : 1;
1154
+ const horizontal = Math.abs(e.deltaX) > Math.abs(e.deltaY);
1155
+ // IsZoom: Ctrl / Cmd + wheel, or a touchpad pinch (browsers send it as a Ctrl wheel), as AppoMobi WheelEventArgs.IsZoom
1156
+ args.Wheel = { Delta: (horizontal ? e.deltaX : e.deltaY) * factor, IsHorizontal: horizontal, IsZoom: e.ctrlKey || e.metaKey };
1157
+ this.tooltip.CloseOnInput();
375
1158
  if (this.gestures === "Lock") {
376
1159
  e.preventDefault();
377
1160
  this.OnGestureEvent(args, "Wheel");
@@ -389,7 +1172,8 @@ export class Canvas {
389
1172
  ProcessGestureNow(args, result) {
390
1173
  this.ProcessPendingGestures();
391
1174
  const root = this.content;
392
- const consumed = root ? this.ProcessGestures(root, SkiaGesturesParameters.Create(result, args)) : null;
1175
+ const gesture = SkiaGesturesParameters.Create(result, args);
1176
+ const consumed = root ? Canvas.Guard("a gesture handler", root, () => this.ProcessGestures(root, gesture)) ?? null : null;
393
1177
  this.Update();
394
1178
  return !!consumed && (args.Handled || !consumed.BlockGesturesBelow);
395
1179
  }
@@ -446,11 +1230,29 @@ export class Canvas {
446
1230
  el.style.userSelect = "none";
447
1231
  for (const t of ["pointerdown", "pointermove", "pointerup", "pointercancel"])
448
1232
  el.addEventListener(t, this.onPointer);
1233
+ el.addEventListener("pointerleave", this.onPointerLeave);
449
1234
  el.addEventListener("contextmenu", this.onContextMenu);
1235
+ el.addEventListener("touchend", this.onTouchEnd);
1236
+ el.addEventListener("dblclick", this.onDoubleClick);
1237
+ window.visualViewport?.addEventListener("resize", this.onViewportResize);
450
1238
  el.addEventListener("wheel", this.onWheel, { passive: false });
451
- if (this.gestures === "Lock")
1239
+ window.addEventListener("blur", this.onWindowBlur);
1240
+ if (this.gestures === "Lock") {
452
1241
  el.addEventListener("touchmove", this.preventTouch, { passive: false });
1242
+ // the canvas owns every touch (DrawnUi.Web applyGestureStyle, DrawnUi.Rust host): no iOS callout or text
1243
+ // selection on a long press, and no rubber band / pull-down of the page starting on it
1244
+ const st = el.style;
1245
+ st.webkitUserSelect = "none";
1246
+ st.webkitTouchCallout = "none";
1247
+ this.pageOverscroll = [document.documentElement.style.overscrollBehavior, document.body.style.overscrollBehavior];
1248
+ document.documentElement.style.overscrollBehavior = "none";
1249
+ document.body.style.overscrollBehavior = "none";
1250
+ }
1251
+ else if (this.gestures === "Enabled")
1252
+ el.addEventListener("touchmove", this.preventClaimedTouch, { passive: false });
453
1253
  }
1254
+ /** The page's own overscroll-behavior before Lock set it to none (html, body), put back on detach. */
1255
+ pageOverscroll;
454
1256
  DetachInput() {
455
1257
  const el = this.Element;
456
1258
  el.style.touchAction = "";
@@ -460,12 +1262,31 @@ export class Canvas {
460
1262
  el.style.userSelect = "";
461
1263
  for (const t of ["pointerdown", "pointermove", "pointerup", "pointercancel"])
462
1264
  el.removeEventListener(t, this.onPointer);
1265
+ el.removeEventListener("pointerleave", this.onPointerLeave);
463
1266
  el.removeEventListener("contextmenu", this.onContextMenu);
1267
+ el.removeEventListener("touchend", this.onTouchEnd);
1268
+ el.removeEventListener("dblclick", this.onDoubleClick);
1269
+ window.visualViewport?.removeEventListener("resize", this.onViewportResize);
1270
+ this.textDrag = undefined;
464
1271
  el.removeEventListener("wheel", this.onWheel);
1272
+ window.removeEventListener("blur", this.onWindowBlur);
465
1273
  el.removeEventListener("touchmove", this.preventTouch);
1274
+ el.removeEventListener("touchmove", this.preventClaimedTouch);
1275
+ if (this.pageOverscroll) {
1276
+ const st = el.style;
1277
+ st.webkitUserSelect = "";
1278
+ st.webkitTouchCallout = "";
1279
+ [document.documentElement.style.overscrollBehavior, document.body.style.overscrollBehavior] = this.pageOverscroll;
1280
+ this.pageOverscroll = undefined;
1281
+ }
1282
+ this.claimedTouches.clear();
1283
+ for (const id of [...this.longPressTimers.keys()])
1284
+ this.DisarmLongPress(id);
1285
+ this.longPressed.clear();
466
1286
  this.activeTouchIds.clear();
467
1287
  this.pointerDownArgs.clear();
468
1288
  this.previousTouchArgs.clear();
1289
+ this.fingers.Reset();
469
1290
  }
470
1291
  /** Port of DrawnUi.Blazor Canvas.OnTouchAction: per-pointer state machine producing Down / Panning / Tapped / Up. */
471
1292
  OnTouchAction(args) {
@@ -473,12 +1294,36 @@ export class Canvas {
473
1294
  return;
474
1295
  const id = args.Id;
475
1296
  if (args.Type === "Pressed") {
1297
+ if (args.Pointer && args.Pointer.DeviceType !== "Mouse" && this.activeTouchIds.size === 0)
1298
+ this.StartTouchPress();
1299
+ this.ArmLongPress(id, args);
1300
+ // the fingers for pinch and turn: the first restarts them, a second one makes the press no tap
1301
+ if (this.activeTouchIds.size === 0) {
1302
+ this.fingers.Restart(id, args.Location);
1303
+ this.multiTouch = false;
1304
+ }
1305
+ else {
1306
+ for (const [other, last] of this.previousTouchArgs)
1307
+ this.fingers.AddMovement(other, last.Location); // their latest places
1308
+ this.fingers.AddMovement(id, args.Location);
1309
+ this.multiTouch = true;
1310
+ }
476
1311
  this.activeTouchIds.add(id);
477
1312
  args.NumberOfTouches = this.activeTouchIds.size;
478
1313
  args.StartingLocation = args.Location;
479
1314
  args.IsInContact = true;
480
1315
  this.pointerDownArgs.set(id, args);
481
1316
  this.previousTouchArgs.set(id, args);
1317
+ // Gestures="Enabled", touch or pen: page scrolling was left to touch-action alone, and iOS Safari still takes an
1318
+ // off-axis drag from the page axis (pointercancel mid-gesture, w3c/pointerevents#303). So the Down is processed
1319
+ // now, like the wheel (queued gestures first, same "used" rule): when a control used it the touch is claimed and
1320
+ // its touchmoves are default-prevented until it ends. It is not queued as well, so it is processed exactly once and
1321
+ // the Panning / Up that follow keep their order. An unclaimed touch shares the page as before.
1322
+ if (this.gestures === "Enabled" && args.Pointer && args.Pointer.DeviceType !== "Mouse") {
1323
+ if (this.ProcessGestureNow(args, "Down"))
1324
+ this.claimedTouches.add(id);
1325
+ return;
1326
+ }
482
1327
  this.OnGestureEvent(args, "Down");
483
1328
  return;
484
1329
  }
@@ -487,6 +1332,11 @@ export class Canvas {
487
1332
  const downArgs = this.pointerDownArgs.get(id);
488
1333
  args.StartingLocation = downArgs ? downArgs.StartingLocation : args.Location;
489
1334
  if (args.Type === "Moved") {
1335
+ if (this.activeTouchIds.size > 1)
1336
+ args.Manipulation = this.fingers.AddMovement(id, args.Location); // nothing for one finger
1337
+ const threshold = Canvas.TappedCancelMoveThresholdPoints * Math.max(0.1, this.RenderingScale);
1338
+ if (Math.abs(args.Distance.Total.X) >= threshold || Math.abs(args.Distance.Total.Y) >= threshold)
1339
+ this.DisarmLongPress(id);
490
1340
  if (args.Distance.Delta.X !== 0 || args.Distance.Delta.Y !== 0)
491
1341
  this.OnGestureEvent(args, "Panning");
492
1342
  this.previousTouchArgs.set(id, args);
@@ -494,7 +1344,9 @@ export class Canvas {
494
1344
  }
495
1345
  if (args.Type === "Released" || args.Type === "Cancelled") {
496
1346
  args.IsInContact = args.NumberOfTouches > 1;
497
- if (!args.IsInContact && downArgs && args.Type === "Released") {
1347
+ const longPressed = this.longPressed.delete(id);
1348
+ this.DisarmLongPress(id);
1349
+ if (!args.IsInContact && downArgs && args.Type === "Released" && !longPressed && !this.multiTouch) {
498
1350
  const threshold = Canvas.TappedCancelMoveThresholdPoints * Math.max(0.1, this.RenderingScale);
499
1351
  if (Math.abs(args.Distance.Total.X) < threshold && Math.abs(args.Distance.Total.Y) < threshold)
500
1352
  this.OnGestureEvent(args, "Tapped");
@@ -503,6 +1355,58 @@ export class Canvas {
503
1355
  this.previousTouchArgs.delete(id);
504
1356
  this.pointerDownArgs.delete(id);
505
1357
  this.activeTouchIds.delete(id);
1358
+ if (this.activeTouchIds.size === 0)
1359
+ this.fingers.Reset();
1360
+ else
1361
+ this.fingers.Lifted(id);
1362
+ }
1363
+ }
1364
+ /** The fingers down, for TouchActionEventArgs.Manipulation (pinch and turn). */
1365
+ fingers = new MultitouchTracker();
1366
+ /** The press had a second finger: it is no tap (AppoMobi.Blazor.Gestures). */
1367
+ multiTouch = false;
1368
+ longPressTimers = new Map();
1369
+ longPressed = new Set();
1370
+ /** The long press of a new press: due LongPressTimeMs later unless the pointer moves away or lets go. */
1371
+ ArmLongPress(id, down) {
1372
+ this.DisarmLongPress(id);
1373
+ this.longPressed.delete(id);
1374
+ this.longPressTimers.set(id, window.setTimeout(() => {
1375
+ this.longPressTimers.delete(id);
1376
+ if (!this.activeTouchIds.has(id))
1377
+ return;
1378
+ this.longPressed.add(id);
1379
+ const args = new TouchActionEventArgs();
1380
+ Object.assign(args, down);
1381
+ args.Timestamp = performance.now();
1382
+ args.Location = down.StartingLocation ?? down.Location;
1383
+ this.OnGestureEvent(args, "LongPressing");
1384
+ // on touch the context menu follows the long press (6cb), at the press point
1385
+ if (down.Pointer && down.Pointer.DeviceType !== "Mouse") {
1386
+ const rect = this.Element.getBoundingClientRect(), scale = Math.max(0.1, this.RenderingScale);
1387
+ this.touchMenuDue = { X: rect.left + args.Location.X / scale, Y: rect.top + args.Location.Y / scale };
1388
+ }
1389
+ }, Canvas.LongPressTimeMs));
1390
+ }
1391
+ /** The long press of a held touch, now (the browser's context menu came first): queued gestures first, then it; its timer is off. */
1392
+ LongPressNow(pointerId) {
1393
+ const id = this.longPressTimers.has(pointerId) ? pointerId : [...this.longPressTimers.keys()][0];
1394
+ const down = id === undefined ? undefined : this.pointerDownArgs.get(id);
1395
+ if (id === undefined || !down || !this.activeTouchIds.has(id))
1396
+ return;
1397
+ this.DisarmLongPress(id);
1398
+ this.longPressed.add(id);
1399
+ const args = new TouchActionEventArgs();
1400
+ Object.assign(args, down);
1401
+ args.Timestamp = performance.now();
1402
+ args.Location = down.StartingLocation ?? down.Location;
1403
+ this.ProcessGestureNow(args, "LongPressing");
1404
+ }
1405
+ DisarmLongPress(id) {
1406
+ const t = this.longPressTimers.get(id);
1407
+ if (t) {
1408
+ clearTimeout(t);
1409
+ this.longPressTimers.delete(id);
506
1410
  }
507
1411
  }
508
1412
  OnGestureEvent(args, result) {
@@ -517,7 +1421,12 @@ export class Canvas {
517
1421
  if (!root)
518
1422
  return;
519
1423
  for (const args of batch)
520
- this.ProcessGestures(root, args);
1424
+ Canvas.Guard("a gesture handler", root, () => this.ProcessGestures(root, args));
1425
+ const due = this.touchMenuDue;
1426
+ if (due) {
1427
+ this.touchMenuDue = undefined;
1428
+ this.RaiseTouchContextMenu(due.X, due.Y);
1429
+ }
521
1430
  }
522
1431
  /**
523
1432
  * The control that consumed the current gesture keeps it until it lets go (DrawnUi Canvas.HadInput). Without this a
@@ -530,24 +1439,251 @@ export class Canvas {
530
1439
  static IsSavedGesture(type) {
531
1440
  return type === "Panning" || type === "Wheel" || type === "Up";
532
1441
  }
533
- /** Entry into the control tree, same shape as DrawnUi Canvas.ProcessGestures. */
1442
+ // ---- arrows start keyboard navigation (C# 6aee5c51) ----
1443
+ arrowsStart = false;
1444
+ /**
1445
+ * While no drawn control has keyboard focus (or only one behind the active modal), the arrow keys start keyboard
1446
+ * navigation as the first Tab does: Down and Right go to the first Tab stop, Up and Left to the last, and the key is used
1447
+ * for that. Once a control has focus the arrows work as usual (inside a list or a menu). Off by default, since games use
1448
+ * the arrows as their own keys while nothing is focused: an app turns it on for its menu screens and off while playing.
1449
+ */
1450
+ get ArrowsStartKeyboardNavigation() { return this.arrowsStart; }
1451
+ set ArrowsStartKeyboardNavigation(v) {
1452
+ if (this.arrowsStart === v)
1453
+ return;
1454
+ this.arrowsStart = v;
1455
+ if (v)
1456
+ KeyboardManager.SubscribeNavigation(this.onArrowKey);
1457
+ else
1458
+ KeyboardManager.UnsubscribeNavigation(this.onArrowKey);
1459
+ }
1460
+ onArrowKey = (key, e) => {
1461
+ const forward = key === "ArrowDown" || key === "ArrowRight" ? true : key === "ArrowUp" || key === "ArrowLeft" ? false : undefined;
1462
+ // a page element, a drawn control's element or the editor's input has the keys: nothing to start
1463
+ if (forward === undefined || this.disposed || KeyboardManager.IsOwnedByElement(e) || e.defaultPrevented)
1464
+ return false;
1465
+ const mgr = this.AccessibilityManager, focused = mgr.FocusedNode;
1466
+ if (focused && !mgr.IsOutsideModal(focused))
1467
+ return false;
1468
+ const first = mgr.NextTabStop(undefined, forward);
1469
+ if (!first)
1470
+ return false;
1471
+ e.preventDefault();
1472
+ mgr.RequestKeyboardFocus(first);
1473
+ this.Update();
1474
+ return true;
1475
+ };
1476
+ // ---- focus (C# DrawnView FocusedChild / ReportFocus, drawnui-cross 6ap) ----
1477
+ focusedChild;
1478
+ focusAtDown;
1479
+ tapNoFocus = false;
1480
+ reportingFocus = false;
1481
+ /**
1482
+ * A control that left the canvas (removed or disposed) is let go by the focus, the gesture dispatch and the tooltips,
1483
+ * so the last control that took input does not keep its page alive (C# 4cb28ab6). Checked once per frame.
1484
+ */
1485
+ ForgetGoneControls() {
1486
+ const gone = (c) => !!c && (c.IsDisposed || c.Superview !== this);
1487
+ if (gone(this.focusedChild))
1488
+ this.focusedChild = undefined;
1489
+ if (gone(this.focusAtDown))
1490
+ this.focusAtDown = undefined;
1491
+ if (gone(this.gestureOwner))
1492
+ this.gestureOwner = null;
1493
+ this.tooltipController?.ForgetGone(gone);
1494
+ }
1495
+ /** The control that has the canvas focus (an editor while it edits, a CanBeFocused control that was tapped). */
1496
+ get FocusedChild() { return this.focusedChild; }
1497
+ /**
1498
+ * Moves the focus. The new control is asked first and the focus moves only when it takes it (a tap on a button leaves an
1499
+ * editor focused); undefined clears it. Nothing moves while the focused control has LockFocus. `setter` is a control
1500
+ * that focused itself already (an editor on its press) or the focused control letting go itself (Escape, submit).
1501
+ */
1502
+ ReportFocus(value, setter) {
1503
+ if (value === this.focusedChild || this.reportingFocus)
1504
+ return;
1505
+ if (this.focusedChild?.LockFocus && setter !== this.focusedChild)
1506
+ return;
1507
+ this.reportingFocus = true;
1508
+ try {
1509
+ if (value && value !== setter && !value.SetFrameworkFocus(true))
1510
+ return;
1511
+ const previous = this.focusedChild;
1512
+ this.focusedChild = value;
1513
+ if (previous && !previous.IsDisposed)
1514
+ previous.SetFrameworkFocus(false);
1515
+ // the keyboard is up: the newly focused field goes above it too
1516
+ if (this.KeyboardCovered > 0)
1517
+ setTimeout(() => this.ApplyKeyboard(), 50);
1518
+ }
1519
+ finally {
1520
+ this.reportingFocus = false;
1521
+ }
1522
+ }
1523
+ /** Entry into the control tree; on a completed tap the focus follows it (C# Canvas: focus only on Tapped). */
534
1524
  ProcessGestures(root, args) {
1525
+ if (args.Type === "Down") {
1526
+ this.focusAtDown = this.focusedChild;
1527
+ this.tapNoFocus = false;
1528
+ }
1529
+ // a mouse drag selecting page text keeps its moves: no scroll under it scrolls (the pointer is captured, so the
1530
+ // moves keep coming once it leaves the canvas and the scroll follows it past its edge)
1531
+ if (this.PreviewTextSelectionGesture(args))
1532
+ return null;
1533
+ const consumed = this.RouteGestures(root, args);
1534
+ this.AfterTextSelectionDown(args, consumed);
1535
+ // a control that claimed the focus during this gesture (an editor on its press) keeps it; a press that closed the
1536
+ // popup windows moves nothing
1537
+ if (args.Type === "Tapped" && !this.tapNoFocus && this.focusedChild === this.focusAtDown)
1538
+ this.ReportFocus(consumed ?? undefined);
1539
+ return consumed;
1540
+ }
1541
+ /** Same shape as DrawnUi Canvas.ProcessGestures. */
1542
+ RouteGestures(root, args) {
535
1543
  const info = () => new GestureEventProcessingInfo(args.Event.Location, SKPoint.Empty, SKPoint.Empty, null);
1544
+ const popups = this.popups, at = args.Event.Location;
1545
+ // the rest of a press that closed the popup windows goes nowhere (native menus)
1546
+ if (args.Type === "Down")
1547
+ popups.SwallowPress = false;
1548
+ if (popups.SwallowPress) {
1549
+ if (args.Type === "Up")
1550
+ popups.SwallowPress = false;
1551
+ return null;
1552
+ }
1553
+ // the wheel outside the popup windows closes them (what they opened from is about to move), before any owner takes it
1554
+ if (args.Type === "Wheel" && popups.HasInteractive && !popups.At(at.X, at.Y)) {
1555
+ popups.CloseAll(false);
1556
+ this.AfterPopupsChanged();
1557
+ }
1558
+ // the wheel goes to the press owner only while a press is held; between presses it goes by position, and it
1559
+ // never makes an owner: a wheel over a second scroll moves that one, not the last one the wheel moved
1560
+ // (DrawnUi.Rust input_router "the wheel goes to the owner of the press first"; C# keeps the last wheel consumer)
1561
+ const wheel = args.Type === "Wheel";
536
1562
  if (args.Type === "Down")
537
1563
  this.gestureOwner = null;
538
- else if (this.gestureOwner && Canvas.IsSavedGesture(args.Type)) {
1564
+ else if (this.gestureOwner && Canvas.IsSavedGesture(args.Type) && (!wheel || this.activeTouchIds.size > 0)) {
539
1565
  const owner = this.gestureOwner;
540
1566
  const alive = !!owner.Superview && owner.IsVisible && !owner.InputTransparent;
541
1567
  const consumed = alive ? owner.OnSkiaGestureEvent(args, info()) : null;
542
1568
  if (consumed) {
543
1569
  // it still wants the gesture: nobody else sees this one (C# skips the tree pass for a saved gesture)
544
- this.gestureOwner = args.Type === "Up" ? null : consumed;
1570
+ if (!wheel)
1571
+ this.gestureOwner = args.Type === "Up" ? null : consumed;
545
1572
  return consumed;
546
1573
  }
547
- this.gestureOwner = null; // it let go (a button whose press turned into a pan): route normally again
1574
+ // it let go (a button whose press turned into a pan): route normally again; a wheel it does not use goes by
1575
+ // position and leaves it the press
1576
+ if (!wheel)
1577
+ this.gestureOwner = null;
1578
+ }
1579
+ // over a popup window its controls take the gesture and nothing below sees it; a press elsewhere closes them
1580
+ if (popups.HasInteractive) {
1581
+ const popupRoot = popups.At(at.X, at.Y);
1582
+ if (popupRoot) {
1583
+ const used = popupRoot.ProcessGestures(args, info()) ?? popupRoot;
1584
+ if (!wheel)
1585
+ this.gestureOwner = args.Type !== "Up" ? used : null;
1586
+ return used;
1587
+ }
1588
+ if (args.Type === "Down") {
1589
+ this.tapNoFocus = true;
1590
+ popups.CloseAll(false);
1591
+ popups.SwallowPress = true;
1592
+ this.AfterPopupsChanged();
1593
+ return null;
1594
+ }
548
1595
  }
549
1596
  const consumed = root.ProcessGestures(args, info());
550
- this.gestureOwner = consumed && args.Type !== "Up" ? consumed : null;
1597
+ // a mouse move never makes an owner (DrawnUi.Net 62608ca7): a focused field takes every hover, and as the owner it
1598
+ // would get the next release of a press that began elsewhere
1599
+ if (!wheel && args.Type !== "Pointer")
1600
+ this.gestureOwner = consumed && args.Type !== "Up" ? consumed : null;
551
1601
  return consumed;
552
1602
  }
553
1603
  }
1604
+ const IsScroll = (c) => !!c && "ScrollTo" in c && "ViewportOffsetY" in c;
1605
+ /**
1606
+ * When a browser event happened, on the performance.now() clock (its timeStamp; now when the browser gives none or a time
1607
+ * from another clock): a slow frame holds events back, and gestures are dated by when they happened.
1608
+ */
1609
+ function EventTime(e) {
1610
+ const now = performance.now(), t = e.timeStamp;
1611
+ return typeof t === "number" && t > 0 && t <= now + 1 ? t : now;
1612
+ }
1613
+ const IsSelectableLabel = (c) => !!c && c.AccessibilityTextSelectable && "TextIndexAtCanvas" in c;
1614
+ /**
1615
+ * Where a canvas point falls in the labels' order: inside a drawn label, its text index there; before a label (above it,
1616
+ * or left of it on its line), that label's start; past them all, the end of the last drawn one.
1617
+ */
1618
+ function Locate(labels, x, y) {
1619
+ let last;
1620
+ for (const label of labels) {
1621
+ const r = label.GetAccessibilityPixelRect();
1622
+ if (r.Width <= 0 || r.Height <= 0)
1623
+ continue;
1624
+ if (x >= r.Left && x < r.Right && y >= r.Top && y < r.Bottom)
1625
+ return [label, label.TextIndexAtCanvas(x, y)];
1626
+ if (y < r.Top || (y <= r.Bottom && x < r.Left))
1627
+ return [label, 0];
1628
+ last = label;
1629
+ }
1630
+ return last ? [last, last.SelectableLength] : [undefined, 0];
1631
+ }
1632
+ /**
1633
+ * The labels in reading order, as they are seen (the tree order is not: a page in two columns lists the left column's
1634
+ * labels first, and a drag in the right column would then start at a label below it): by top, labels whose tops are within
1635
+ * half the smaller height forming one line, read left to right.
1636
+ */
1637
+ function ReadingOrder(labels) {
1638
+ const rects = new Map(labels.map((l) => [l, l.GetAccessibilityPixelRect()]));
1639
+ const sorted = [...labels].sort((a, b) => rects.get(a).Top - rects.get(b).Top || rects.get(a).Left - rects.get(b).Left);
1640
+ for (let start = 0, i = 1; i <= sorted.length; i++) {
1641
+ if (i < sorted.length) {
1642
+ const first = rects.get(sorted[start]), next = rects.get(sorted[i]);
1643
+ if (next.Top - first.Top < Math.min(first.Height, next.Height) / 2)
1644
+ continue;
1645
+ }
1646
+ if (i - start > 1) {
1647
+ const line = sorted.slice(start, i).sort((a, b) => rects.get(a).Left - rects.get(b).Left);
1648
+ for (let k = 0; k < line.length; k++)
1649
+ sorted[start + k] = line[k];
1650
+ }
1651
+ start = i;
1652
+ }
1653
+ return sorted;
1654
+ }
1655
+ function CollectSelectable(control, into) {
1656
+ if (!control.IsVisible || control.IsDisposed)
1657
+ return;
1658
+ if (IsSelectableLabel(control))
1659
+ into.push(control);
1660
+ const views = "Views" in control ? control.Views : undefined;
1661
+ const content = views ? undefined : control.Content;
1662
+ for (const child of views ?? (content ? [content] : []))
1663
+ CollectSelectable(child, into);
1664
+ }
1665
+ function ScrollOf(control) {
1666
+ for (let p = control?.Parent; p; p = p.Parent)
1667
+ if (IsScroll(p))
1668
+ return p;
1669
+ return undefined;
1670
+ }
1671
+ /** The innermost drawn scroll around a selectable label whose viewport holds the point. */
1672
+ function ScrollAt(labels, x, y) {
1673
+ for (const label of labels) {
1674
+ for (let p = label.Parent; p; p = p.Parent) {
1675
+ if (!IsScroll(p))
1676
+ continue;
1677
+ const r = p.GetAccessibilityPixelRect();
1678
+ if (x >= r.Left && x < r.Right && y >= r.Top && y < r.Bottom)
1679
+ return p;
1680
+ }
1681
+ }
1682
+ return undefined;
1683
+ }
1684
+ function IsInside(control, ancestor) {
1685
+ for (let p = control.Parent; p; p = p.Parent)
1686
+ if (p === ancestor)
1687
+ return true;
1688
+ return false;
1689
+ }