drawnui-react 0.1.0-preview.4 → 0.1.0-preview.40

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 (105) hide show
  1. package/README.md +119 -14
  2. package/SKIPPED.md +36 -26
  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 +16 -2
  8. package/dist/controls/GridStructure.js +40 -4
  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 +48 -2
  20. package/dist/controls/SkiaEditor.js +268 -53
  21. package/dist/controls/SkiaGif.d.ts +7 -0
  22. package/dist/controls/SkiaGif.js +25 -4
  23. package/dist/controls/SkiaImage.d.ts +5 -0
  24. package/dist/controls/SkiaImage.js +48 -14
  25. package/dist/controls/SkiaLabel.d.ts +117 -9
  26. package/dist/controls/SkiaLabel.js +526 -80
  27. package/dist/controls/SkiaLabelFps.d.ts +16 -0
  28. package/dist/controls/SkiaLabelFps.js +41 -0
  29. package/dist/controls/SkiaLayout.d.ts +89 -9
  30. package/dist/controls/SkiaLayout.js +364 -21
  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 +35 -5
  39. package/dist/controls/SkiaScroll.js +252 -32
  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 +13 -2
  45. package/dist/controls/SkiaShape.js +50 -10
  46. package/dist/controls/SkiaSlider.d.ts +20 -2
  47. package/dist/controls/SkiaSlider.js +61 -7
  48. package/dist/controls/SkiaSprite.d.ts +4 -0
  49. package/dist/controls/SkiaSprite.js +22 -10
  50. package/dist/controls/SkiaSvg.d.ts +4 -0
  51. package/dist/controls/SkiaSvg.js +28 -4
  52. package/dist/controls/SkiaSwitch.d.ts +0 -1
  53. package/dist/controls/SkiaSwitch.js +4 -8
  54. package/dist/controls/SkiaToggle.d.ts +25 -5
  55. package/dist/controls/SkiaToggle.js +58 -5
  56. package/dist/controls/SnappingLayout.d.ts +12 -1
  57. package/dist/controls/SnappingLayout.js +21 -2
  58. package/dist/controls/TooltipStyle.d.ts +52 -0
  59. package/dist/controls/TooltipStyle.js +88 -0
  60. package/dist/core/Accessibility.d.ts +134 -0
  61. package/dist/core/Accessibility.js +675 -9
  62. package/dist/core/Animators.d.ts +37 -1
  63. package/dist/core/Animators.js +102 -9
  64. package/dist/core/Canvas.d.ts +222 -10
  65. package/dist/core/Canvas.js +698 -37
  66. package/dist/core/ControlStyle.d.ts +2 -0
  67. package/dist/core/ControlStyle.js +2 -0
  68. package/dist/core/Easing.d.ts +12 -1
  69. package/dist/core/Easing.js +25 -1
  70. package/dist/core/Gestures.d.ts +81 -2
  71. package/dist/core/Gestures.js +177 -3
  72. package/dist/core/Hover.d.ts +51 -0
  73. package/dist/core/Hover.js +140 -0
  74. package/dist/core/ImageEffects.d.ts +2 -0
  75. package/dist/core/ImageEffects.js +2 -0
  76. package/dist/core/KeyboardManager.d.ts +40 -0
  77. package/dist/core/KeyboardManager.js +98 -8
  78. package/dist/core/PopupWindows.d.ts +94 -0
  79. package/dist/core/PopupWindows.js +205 -0
  80. package/dist/core/ScrollAnimators.js +9 -0
  81. package/dist/core/Shaping.d.ts +40 -0
  82. package/dist/core/Shaping.js +224 -0
  83. package/dist/core/SkiaControl.d.ts +279 -10
  84. package/dist/core/SkiaControl.js +621 -64
  85. package/dist/core/SkiaEffect.d.ts +17 -0
  86. package/dist/core/SkiaEffect.js +43 -8
  87. package/dist/core/SkiaImageManager.js +1 -1
  88. package/dist/core/Super.d.ts +29 -2
  89. package/dist/core/Super.js +54 -3
  90. package/dist/core/Tooltips.d.ts +71 -0
  91. package/dist/core/Tooltips.js +205 -0
  92. package/dist/core/Types.d.ts +11 -1
  93. package/dist/core/Types.js +32 -1
  94. package/dist/core/ViewsAdapter.d.ts +7 -2
  95. package/dist/core/ViewsAdapter.js +10 -3
  96. package/dist/index.d.ts +6 -0
  97. package/dist/index.js +6 -0
  98. package/dist/react/SkiaShell.js +65 -26
  99. package/dist/react/index.d.ts +33 -4
  100. package/dist/react/index.js +157 -18
  101. package/dist/react/reconciler.d.ts +20 -0
  102. package/dist/react/reconciler.js +69 -14
  103. package/dist/vite/index.d.ts +9 -0
  104. package/dist/vite/index.js +36 -3
  105. package/package.json +61 -2
@@ -1,7 +1,12 @@
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";
3
8
  import { Colors, SKRect } from "./Types";
4
- import { ContextMenuEventArgs, GestureEventProcessingInfo, PointerData, SKPoint, SkiaGesturesParameters, TouchActionEventArgs, } from "./Gestures";
9
+ import { ContextMenuEventArgs, GestureEventProcessingInfo, MultitouchTracker, PointerData, SKPoint, SkiaGesturesParameters, TouchActionEventArgs, } from "./Gestures";
5
10
  /**
6
11
  * Mirrors DrawnUi Canvas (DrawnView): hosts one Content control on an HTML canvas element,
7
12
  * owns RenderingScale (devicePixelRatio), the surface, the on-demand frame loop and raw input.
@@ -12,6 +17,11 @@ export class Canvas {
12
17
  Element;
13
18
  /** Points a pointer may travel between Down and Up and still count as a tap (AppoMobi TouchEffect default). */
14
19
  static TappedCancelMoveThresholdPoints = 16;
20
+ /**
21
+ * A press held this long without moving past TappedCancelMoveThresholdPoints is a LongPressing, at the press point
22
+ * (AppoMobi TouchEffect, DrawnUi.Rust LONG_PRESS_MS); its release sends no Tapped. A timer, no frames while waiting.
23
+ */
24
+ static LongPressTimeMs = 1500;
15
25
  BackgroundColor = Colors.Transparent;
16
26
  /** Accelerated = WebGL surface, Default = software. Read once at first frame. */
17
27
  RenderingMode = "Accelerated";
@@ -21,18 +31,146 @@ export class Canvas {
21
31
  /** Frames per second over the last second of drawn frames. */
22
32
  FPS = 0;
23
33
  frameTimes = [];
34
+ /** DrawnView.WasRendered: a frame has been drawn on a ready surface (set after the first one completes). */
35
+ WasRendered = false;
36
+ /** DrawnView.CanRender: the surface (and its GPU context when accelerated) is ready to draw. */
37
+ get CanRender() { return !!this.surface && !this.disposed; }
38
+ /**
39
+ * DrawnView.WillFirstTimeDraw: raised once, right before the first frame drawn on a ready surface, with that
40
+ * frame's drawing context. The engine draws its first frame while it is being constructed (so the page never shows
41
+ * an unpainted canvas): pass it through the constructor's `init` to receive that frame.
42
+ */
43
+ WillFirstTimeDraw;
44
+ /** DrawnView.WasDrawn: raised after every frame has been drawn (the C# event passes no context). */
45
+ WasDrawn;
24
46
  /** Registry + rate-limited snapshot of accessible controls, rendered by the DOM overlay (DrawnUi AccessibilityManager). */
25
47
  AccessibilityManager = new SkiaAccessibilityManager();
48
+ /** Mouse hover of the controls (drawnui-cross 6m): ReceivesHover / IsHovered / HoverChanged. */
49
+ Hover = new HoverManager();
50
+ // ---- tooltips (drawnui-cross 6ar) ----
51
+ tooltipController;
52
+ /** Made on first use: a canvas that never shows a tooltip allocates nothing for it. */
53
+ get tooltip() { return this.tooltipController ??= new TooltipController(this); }
54
+ /** Look and timing of the tooltips on this canvas; unset uses `Super.TooltipStyle`. */
55
+ TooltipStyle;
56
+ get TooltipStyleUsed() { return this.TooltipStyle ?? Super.TooltipStyle; }
57
+ /** The text of the tooltip shown now, undefined when none is shown. */
58
+ get ShownTooltip() { return this.tooltip.ShownText; }
59
+ // ---- popup windows (drawnui-cross 6at, the DrawnUi.Rust / .NET API) ----
60
+ popupLayer;
61
+ /** Made on first use, like the tooltip. */
62
+ get popups() { return this.popupLayer ??= new PopupLayer(this); }
63
+ popupKeysHooked = false;
64
+ /** Raised when a popup window closed: picked, a press outside, Escape, the wheel, window blur or ClosePopupWindow. */
65
+ PopupWindowClosed = new Set();
66
+ /** The root controls of the open popup windows, bottom to top: a read-only view for tools (a new array per read). */
67
+ get PopupWindowRoots() { return this.popupLayer?.Roots ?? []; }
68
+ wasDrawnListeners;
69
+ /**
70
+ * Handlers run at the end of every drawn frame, after the `WasDrawn` callback and before the surface is flushed (a
71
+ * tool drawing an overlay on `Surface.getCanvas()`). Made on first use: a canvas without listeners does no work.
72
+ */
73
+ get WasDrawnListeners() { return this.wasDrawnListeners ??= new Set(); }
74
+ raiseWasDrawn = (f) => f(this);
75
+ /**
76
+ * Shows `content` over everything, opening from `anchor` the way native menus do: at a point (a right click, canvas
77
+ * points), or below a rect or a control (a dropdown), flipped to the other side where it does not fit. It closes with
78
+ * a press outside it, Escape, the wheel outside it, window blur, `ClosePopupWindow` and the options.
79
+ */
80
+ OpenPopupWindow(content, anchor, options = {}) {
81
+ const id = this.popups.Open(content, PopupAnchor.From(anchor), options, this);
82
+ this.HookPopupKeys(true);
83
+ if (!options.Passive)
84
+ this.tooltip.Reset(); // a menu opening closes the tooltip
85
+ this.Hover.RequestCheck();
86
+ this.Update();
87
+ return id;
88
+ }
89
+ /** Closes the popup window (nothing when it is closed already). */
90
+ ClosePopupWindow(id) { this.popups.Close(id); this.AfterPopupsChanged(); }
91
+ /** Closes every popup window. */
92
+ ClosePopupWindows() { this.popups.CloseAll(true); this.AfterPopupsChanged(); }
93
+ /** The popup window is still open. */
94
+ IsPopupWindowOpen(id) { return this.popups.IsOpen(id); }
95
+ /**
96
+ * Moves the keyboard and screen-reader focus to `control` at the end of the next frame, for app code such as a custom
97
+ * menu that moves its highlight (C# DrawnView.SetAccessibilityFocus). A control not drawn yet gets it once it is, within
98
+ * 3 seconds. It wins over the library's own moves in the same frame (a closed popup window giving the keyboard back to
99
+ * its opener); undefined cancels a move still waiting. The focus ring shows only if the keyboard is in use.
100
+ */
101
+ SetAccessibilityFocus(control) { this.AccessibilityManager.SetAccessibilityFocus(control); this.Update(); }
102
+ /**
103
+ * The drawn control with the keyboard and screen-reader focus (C# KeyboardFocusNode). Set undefined to let no drawn
104
+ * control keep it: the DOM focus goes back to the canvas and the keys belong to the app; a control moves it there.
105
+ */
106
+ get KeyboardFocusNode() { return this.AccessibilityManager.FocusedNode; }
107
+ set KeyboardFocusNode(control) {
108
+ if (control)
109
+ this.AccessibilityManager.SetAccessibilityFocus(control);
110
+ else
111
+ this.AccessibilityManager.ClearKeyboardFocus();
112
+ this.Update();
113
+ }
114
+ /** True while a popup window that takes input is open. */
115
+ get HasPopupWindows() { return this.popups.HasInteractive; }
116
+ /** The content of the top popup window that takes input. */
117
+ get TopPopupWindow() { return this.popups.TopInteractive; }
118
+ /** The window stopped being active (blur): popup windows and the tooltip close, as native menus do. */
119
+ OnWindowDeactivated() { this.ClosePopupWindows(); this.tooltip.CloseOnInput(); }
120
+ /**
121
+ * The browser window (tab) has the keyboard (C# DrawnView.IsWindowActive): false after its blur, true again after its
122
+ * focus. A focused editor hides its caret while it is false.
123
+ */
124
+ IsWindowActive = typeof document === "undefined" || typeof document.hasFocus !== "function" || document.hasFocus();
125
+ /** Raised when IsWindowActive changes (C# WindowActiveChanged). */
126
+ WindowActiveChanged = new Set();
127
+ SetWindowActive(active) {
128
+ if (this.IsWindowActive === active)
129
+ return;
130
+ this.IsWindowActive = active;
131
+ for (const h of [...this.WindowActiveChanged])
132
+ h(active);
133
+ }
134
+ RaisePopupWindowClosed(id) { for (const h of [...this.PopupWindowClosed])
135
+ h(id); }
136
+ AfterPopupsChanged() {
137
+ if (!this.popups.HasAny)
138
+ this.HookPopupKeys(false);
139
+ this.Hover.RequestCheck();
140
+ this.Update();
141
+ }
142
+ onPopupKey = (key) => {
143
+ if (key !== "Escape" || !this.popups.CloseTop())
144
+ return false;
145
+ this.AfterPopupsChanged();
146
+ return true;
147
+ };
148
+ HookPopupKeys(on) {
149
+ if (on === this.popupKeysHooked)
150
+ return;
151
+ this.popupKeysHooked = on;
152
+ if (on)
153
+ KeyboardManager.SubscribeNavigation(this.onPopupKey);
154
+ else
155
+ KeyboardManager.UnsubscribeNavigation(this.onPopupKey);
156
+ }
157
+ onWindowBlur = () => this.OnWindowDeactivated();
158
+ // IsWindowActive follows the window for the canvas' whole life, input on or off (a focused editor needs it)
159
+ onWindowInactive = () => this.SetWindowActive(false);
160
+ onWindowActive = () => this.SetWindowActive(true);
26
161
  content;
27
162
  get Content() { return this.content; }
28
163
  set Content(value) {
29
- if (this.content)
164
+ if (this.content && this.content !== value) {
165
+ this.ControlLeft(this.content, false);
30
166
  this.content._superview = undefined;
167
+ }
31
168
  this.content = value;
32
169
  if (value) {
33
170
  value.Parent = undefined;
34
171
  value._superview = this;
35
172
  }
173
+ this.Hover.RequestCheck();
36
174
  this.Update();
37
175
  }
38
176
  surface;
@@ -42,17 +180,31 @@ export class Canvas {
42
180
  frameId = 0;
43
181
  disposed = false;
44
182
  observer;
45
- constructor(Element) {
183
+ /** The WebGL context is lost: no frames until the browser restores it. */
184
+ contextLost = false;
185
+ /**
186
+ * Bumped when the WebGL context was restored: every GPU object made before (Image caches, picture caches that may
187
+ * replay them, kept composite surfaces, effect textures) is remade at its next draw (DrawnUi.Rust Gpu::epoch).
188
+ */
189
+ GpuEpoch = 0;
190
+ /** `init` runs before the first frame is drawn: the place to attach `WillFirstTimeDraw` / `WasDrawn` for that frame. */
191
+ constructor(Element, init) {
46
192
  this.Element = Element;
47
193
  if (!Super.CK)
48
194
  throw new Error("DrawnUi: call Super.UseDrawnUi()...BuildAsync() before creating a Canvas");
195
+ init?.(this);
196
+ Element.addEventListener("webglcontextlost", this.onContextLost);
197
+ Element.addEventListener("webglcontextrestored", this.onContextRestored);
198
+ window.addEventListener("blur", this.onWindowInactive);
199
+ window.addEventListener("focus", this.onWindowActive);
200
+ this.Hover.RootAt = (x, y) => this.popupLayer?.At(x, y) ?? this.content;
49
201
  this.observer = new ResizeObserver(() => this.OnResized());
50
202
  this.observer.observe(Element);
51
203
  this.OnResized();
52
204
  }
53
205
  /** Request a redraw (full measure + arrange + render) on the next animation frame. */
54
206
  Update() {
55
- if (this.frameId || !this.surface || this.disposed)
207
+ if (this.frameId || !this.surface || this.disposed || this.contextLost)
56
208
  return;
57
209
  const surface = this.surface;
58
210
  this.frameId = surface.requestAnimationFrame((c) => {
@@ -70,7 +222,8 @@ export class Canvas {
70
222
  cancelAnimationFrame(this.frameId);
71
223
  this.frameId = 0;
72
224
  }
73
- this.surface?.delete();
225
+ // dispose, not delete: a software surface owns pixels CanvasKit allocated for it, which delete() leaves behind
226
+ this.surface?.dispose();
74
227
  this.surface = undefined;
75
228
  }
76
229
  /** On-screen surface at the element's current pixel size, reusing the GL/GrContext when accelerated. */
@@ -103,16 +256,53 @@ export class Canvas {
103
256
  this.RenderingScale = dpr;
104
257
  this.Element.width = w;
105
258
  this.Element.height = h;
259
+ if (this.contextLost)
260
+ return; // the restore makes the surface at this size
106
261
  this.ReleaseSurface();
107
262
  this.surface = this.CreateSurface(w, h);
108
263
  if (!this.surface)
109
264
  throw new Error("DrawnUi: cannot create surface");
110
265
  this.DrawNow();
111
266
  }
267
+ /** WebGL context lost: keep the browser restoring it (preventDefault) and stop the frames. */
268
+ onContextLost = (e) => {
269
+ e.preventDefault();
270
+ this.contextLost = true;
271
+ if (this.frameId) {
272
+ cancelAnimationFrame(this.frameId);
273
+ this.frameId = 0;
274
+ }
275
+ };
276
+ /**
277
+ * WebGL context restored (as DrawnUi.Rust and the C# Wasm / Blazor heads): every GL object of the lost generation is
278
+ * gone. The old Skia context is abandoned first, while its own GL handle is current and before the new context makes
279
+ * any object, so its GL calls reach only lost-generation objects. CanvasKit exposes no `abandonContext`;
280
+ * `releaseResourcesAndAbandonContext` is its only way to abandon, and after it freeing an old image or surface makes no
281
+ * GL call. Then the same WebGL object is registered again (the old handle deleted first, which clears the canvas'
282
+ * context object) with a new GrContext and surface; GpuEpoch makes the old generation's GPU objects remake themselves.
283
+ */
284
+ onContextRestored = () => {
285
+ if (this.disposed)
286
+ return;
287
+ if (this.grContext)
288
+ this.grContext.releaseResourcesAndAbandonContext();
289
+ this.surface?.dispose();
290
+ this.surface = undefined;
291
+ this.grContext?.delete();
292
+ this.grContext = undefined;
293
+ if (this.glHandle) {
294
+ Super.CK.deleteContext(this.glHandle);
295
+ this.glHandle = undefined;
296
+ }
297
+ this.contextLost = false;
298
+ this.GpuEpoch++;
299
+ this.surface = this.CreateSurface(this.Element.width, this.Element.height);
300
+ this.DrawNow();
301
+ };
112
302
  /** Draws one frame immediately (outside the rAF loop) and presents it. */
113
303
  DrawNow() {
114
304
  const surface = this.surface;
115
- if (!surface || this.disposed)
305
+ if (!surface || this.disposed || this.contextLost)
116
306
  return;
117
307
  this.Draw(surface.getCanvas());
118
308
  surface.flush();
@@ -121,7 +311,16 @@ export class Canvas {
121
311
  Draw(canvas) {
122
312
  const started = performance.now();
123
313
  this.ProcessPendingGestures();
124
- const executed = this.ExecuteAnimators(Math.round(started * 1_000_000));
314
+ // Animators run on the frame's vsync time (inside a rAF callback document.timeline.currentTime is the frame
315
+ // timestamp), not on when this callback happened to start: callback starts drift by several ms around vsync
316
+ // (measured 12..23 ms between frames shown 16.7 ms apart), and a game loop moving by speed * delta then
317
+ // jumps unevenly on screen.
318
+ const frameTime = Number(document.timeline?.currentTime ?? started);
319
+ this.FrameTimeNanos = Math.round(frameTime * 1_000_000);
320
+ const executed = this.ExecuteAnimators(Math.round(frameTime * 1_000_000));
321
+ const canRender = this.CanRender;
322
+ if (canRender && !this.WasRendered)
323
+ this.WillFirstTimeDraw?.(this, { Canvas: canvas, Surface: this.surface });
125
324
  canvas.clear(Super.ParseColor(this.BackgroundColor));
126
325
  const root = this.content;
127
326
  if (root) {
@@ -131,7 +330,15 @@ export class Canvas {
131
330
  root.Arrange(new SKRect(0, 0, w, h), root.WidthRequest, root.HeightRequest, scale);
132
331
  root.Render({ Context: { Canvas: canvas, Surface: this.surface }, Destination: new SKRect(0, 0, w, h), Scale: scale });
133
332
  }
333
+ // popup windows, then the tooltip, over everything
334
+ const top = { Context: { Canvas: canvas, Surface: this.surface }, Destination: new SKRect(0, 0, this.Element.width, this.Element.height), Scale: this.RenderingScale };
335
+ if (this.popupLayer?.HasAny)
336
+ this.popupLayer.Draw(top, top.Destination);
337
+ this.tooltipController?.Draw(top, top.Destination);
134
338
  this.AccessibilityManager.OnFrameEnd(this.RenderingScale, this.Element.width, this.Element.height, () => this.Update());
339
+ this.Hover.AfterFrame(this.content, this.activeTouchIds.size > 0);
340
+ if (this.Hover.Paused)
341
+ this.tooltipController?.Reset(); // content moves under the pointer
135
342
  const now = performance.now();
136
343
  this.FrameTime = now - started;
137
344
  this.FrameIndex++;
@@ -139,8 +346,16 @@ export class Canvas {
139
346
  while (this.frameTimes.length && this.frameTimes[0] < now - 1000)
140
347
  this.frameTimes.shift();
141
348
  this.FPS = this.frameTimes.length;
349
+ this.ForgetGoneControls();
142
350
  if (executed > 0)
143
351
  this.Update(); // animators running: keep frames coming
352
+ // C# order: WasDrawn at the end of the frame, then the frame counts as rendered
353
+ this.WasDrawn?.(this);
354
+ const listeners = this.wasDrawnListeners;
355
+ if (listeners !== undefined && listeners.size > 0)
356
+ listeners.forEach(this.raiseWasDrawn);
357
+ if (!this.WasRendered && canRender)
358
+ this.WasRendered = true;
144
359
  }
145
360
  // ---- deferred disposal (DrawnUi DisposeObject: never delete Skia objects mid-frame) ----
146
361
  disposeQueue = [];
@@ -162,21 +377,94 @@ export class Canvas {
162
377
  return true;
163
378
  }
164
379
  UnregisterAnimator(uid) { this.AnimatingControls.delete(uid); }
380
+ /**
381
+ * `root` leaves this canvas (removed from its parent, replaced as content, disposed): what runs for its subtree stops,
382
+ * as DrawnUi.Rust 44c718f. Its animators leave the frame loop: disposed, they stop; only removed, they pause and wait on
383
+ * their control (PendingUnattachedAnimators), going on from there when it is arranged on a canvas again. A focused editor in it loses the
384
+ * focus, a game in it stops getting keys (CanvasLeaveWatchers). Runs once per removal, never per frame.
385
+ */
386
+ ControlLeft(root, disposed) {
387
+ const inside = (c) => { for (let p = c; p; p = p.Parent)
388
+ if (p === root)
389
+ return true; return false; };
390
+ for (const a of this.AnimatingControls.values()) {
391
+ const control = a.Parent;
392
+ if (!control || !inside(control))
393
+ continue;
394
+ this.AnimatingControls.delete(a.Uid);
395
+ if (disposed || control.IsDisposed)
396
+ a.Stop();
397
+ else {
398
+ // paused as a hidden control's animator is: the time off the canvas is not counted when it goes on
399
+ if (!a.IsPaused) {
400
+ a.Pause();
401
+ a.PausedWhileHidden = true;
402
+ }
403
+ if (!control.PendingUnattachedAnimators?.includes(a))
404
+ (control.PendingUnattachedAnimators ??= []).push(a);
405
+ }
406
+ }
407
+ for (const c of [...CanvasLeaveWatchers])
408
+ if (inside(c))
409
+ c.OnLeftCanvas();
410
+ }
165
411
  /** Ticks every registered animator once; returns how many ran. */
166
412
  ExecuteAnimators(frameTimeNanos) {
167
- let executed = 0;
413
+ let executed = 0, wake = Infinity;
168
414
  for (const a of [...this.AnimatingControls.values()]) {
169
415
  if (!a.Parent) {
170
416
  this.AnimatingControls.delete(a.Uid);
171
417
  continue;
172
418
  }
419
+ // the control or a parent is hidden: its animator pauses, no frames, and goes on from where it was when shown
420
+ if (a.Parent.HiddenInTree()) {
421
+ if (!a.IsPaused) {
422
+ a.Pause();
423
+ a.PausedWhileHidden = true;
424
+ }
425
+ continue;
426
+ }
427
+ if (a.PausedWhileHidden) {
428
+ a.PausedWhileHidden = false;
429
+ a.Resume();
430
+ }
431
+ if (a.IsPaused)
432
+ continue; // a paused animator neither ticks nor keeps frames coming (C# DrawnView)
433
+ if (a.SleepUntilNanos > frameTimeNanos) {
434
+ wake = Math.min(wake, a.SleepUntilNanos);
435
+ continue;
436
+ } // nothing changes yet
173
437
  a.TickFrame(frameTimeNanos);
174
438
  executed++;
439
+ if (a.SleepUntilNanos > frameTimeNanos)
440
+ wake = Math.min(wake, a.SleepUntilNanos);
175
441
  }
442
+ this.WakeAt(wake, frameTimeNanos);
176
443
  return executed;
177
444
  }
445
+ wakeTimer = 0;
446
+ wakeAtNanos = Infinity;
447
+ /** One timer for the earliest sleeping animator: the frame loop wakes then, no frames run in between. */
448
+ WakeAt(nanos, nowNanos) {
449
+ if (!isFinite(nanos))
450
+ return;
451
+ if (this.wakeTimer && this.wakeAtNanos <= nanos)
452
+ return;
453
+ if (this.wakeTimer)
454
+ clearTimeout(this.wakeTimer);
455
+ this.wakeAtNanos = nanos;
456
+ this.wakeTimer = window.setTimeout(() => { this.wakeTimer = 0; this.wakeAtNanos = Infinity; this.Update(); }, Math.max(0, (nanos - nowNanos) / 1_000_000));
457
+ }
178
458
  /** Frames drawn so far (SkiaBackdrop uses it to refresh once after a cached record). */
179
459
  FrameIndex = 0;
460
+ /**
461
+ * DrawnView.WheelDeltaPerNotch: the Wheel.Delta one mouse-wheel notch produces, 100 CSS pixels in Chrome and Edge. A
462
+ * scroll moves by the event's share of a notch, so a touchpad, which sends many small events, scrolls as far as the
463
+ * fingers moved. 0 = units unknown: every event scrolls one line.
464
+ */
465
+ WheelDeltaPerNotch = 100;
466
+ /** Vsync time of the last frame the animators ran on (nanoseconds, the performance.now() timeline). */
467
+ FrameTimeNanos = 0;
180
468
  /** On-screen surface (SkiaBackdrop snapshots it). */
181
469
  get Surface() { return this.surface; }
182
470
  /**
@@ -220,12 +508,25 @@ export class Canvas {
220
508
  }
221
509
  }
222
510
  finally {
223
- surface.delete();
511
+ surface.dispose(); // its pixels too (CK.MakeSurface allocates them)
224
512
  }
225
513
  }
226
514
  Dispose() {
227
515
  this.disposed = true;
516
+ if (this.wakeTimer) {
517
+ clearTimeout(this.wakeTimer);
518
+ this.wakeTimer = 0;
519
+ }
520
+ this.Element.removeEventListener("webglcontextlost", this.onContextLost);
521
+ this.Element.removeEventListener("webglcontextrestored", this.onContextRestored);
522
+ window.removeEventListener("blur", this.onWindowInactive);
523
+ window.removeEventListener("focus", this.onWindowActive);
524
+ this.WindowActiveChanged.clear();
228
525
  this.Gestures = "Disabled";
526
+ this.ArrowsStartKeyboardNavigation = false;
527
+ this.tooltipController?.Dispose();
528
+ this.popupLayer?.Dispose();
529
+ this.HookPopupKeys(false);
229
530
  this.observer.disconnect();
230
531
  this.content?.Dispose();
231
532
  this.Content = undefined;
@@ -261,13 +562,24 @@ export class Canvas {
261
562
  if (!type)
262
563
  return;
263
564
  if (type === "Moved" && !this.activeTouchIds.has(e.pointerId)) {
565
+ if (e.pointerType === "touch")
566
+ return; // touch never hovers
567
+ const hx = e.offsetX * this.RenderingScale, hy = e.offsetY * this.RenderingScale;
568
+ if (this.activeTouchIds.size === 0) {
569
+ this.Hover.Move(this.content, hx, hy);
570
+ this.tooltip.OnPointerMove(this.Hover.Path, hx, hy);
571
+ }
572
+ if (this.popups.HasAny)
573
+ this.popups.PointerAt(hx, hy);
264
574
  if (e.pointerType === "mouse")
265
- this.UpdateCursor(e.offsetX, e.offsetY);
575
+ this.UpdateCursor();
266
576
  return;
267
- } // hover not ported (TouchActionResult.Pointer)
577
+ }
268
578
  if ((type === "Released" || type === "Cancelled") && !this.activeTouchIds.has(e.pointerId))
269
579
  return; // Up of a pointer that never pressed here
270
580
  // Capture so Up outside the element still arrives; throws for synthetic events (tests) — harmless.
581
+ if (type === "Pressed")
582
+ this.tooltip.CloseOnInput();
271
583
  if (type === "Pressed") {
272
584
  try {
273
585
  this.Element.setPointerCapture(e.pointerId);
@@ -289,8 +601,26 @@ export class Canvas {
289
601
  pd.PressedButtons = e.buttons;
290
602
  args.Pointer = pd;
291
603
  this.OnTouchAction(args);
604
+ if (type === "Released" || type === "Cancelled") {
605
+ this.claimedTouches.delete(e.pointerId);
606
+ this.UpdateTouchAction();
607
+ }
608
+ };
609
+ /** The mouse left the canvas: hover ends at once, also while content moves. */
610
+ onPointerLeave = (e) => {
611
+ if (e.pointerType === "touch")
612
+ return;
613
+ this.Hover.Leave();
614
+ this.tooltip.Reset();
615
+ if (this.popups.HasAny)
616
+ this.popups.PointerAt(undefined, undefined);
292
617
  };
293
618
  preventTouch = (e) => e.preventDefault();
619
+ /** Gestures="Enabled": touch / pen pointers whose Down a control used (see OnTouchAction). */
620
+ claimedTouches = new Set();
621
+ /** Gestures="Enabled": while a claimed touch is down the page may not take its drag. */
622
+ preventClaimedTouch = (e) => { if (this.claimedTouches.size > 0 && e.cancelable)
623
+ e.preventDefault(); };
294
624
  /** Called when no control handled a context-menu request; return true to suppress the browser's canvas menu. */
295
625
  ContextMenu;
296
626
  /** DOM contextmenu (right click / long press / Menu key) -> ContextMenuEventArgs routed through the tree like a tap. */
@@ -301,41 +631,76 @@ export class Canvas {
301
631
  const pointerType = e.pointerType;
302
632
  const source = pointerType === "touch" || pointerType === "pen" ? "touch" : pointerType === "mouse" || e.button === 2 ? "mouse" : "keyboard";
303
633
  const args = new ContextMenuEventArgs(new SKPoint(x, y), new SKPoint(x * scale, y * scale), source, e);
634
+ this.tooltip.CloseOnInput();
635
+ // over a popup window its content is asked; elsewhere the popups close and the request goes on, so a new menu can
636
+ // open there (C# PopupLayer ContextMenu)
637
+ const popupRoot = this.popups.HasInteractive ? this.popups.At(args.Pixels.X, args.Pixels.Y) : undefined;
638
+ if (popupRoot) {
639
+ popupRoot.ProcessContextMenu(args.Pixels, args);
640
+ e.preventDefault();
641
+ return;
642
+ }
643
+ if (this.popups.HasInteractive) {
644
+ this.popups.CloseAll(false);
645
+ this.AfterPopupsChanged();
646
+ }
304
647
  let handled = this.content?.ProcessContextMenu(args.Pixels, args) ?? false;
305
648
  if (!handled && this.ContextMenu)
306
649
  handled = this.ContextMenu(this, args) === true;
307
650
  if (handled)
308
651
  e.preventDefault();
309
652
  };
653
+ /**
654
+ * The Menu key, Shift+F10 or a screen reader's context-menu command on the control in keyboard focus (the DOM
655
+ * `contextmenu` of its overlay node): its context menu opens at its center, from it or the first control above it with
656
+ * a ContextMenu handler, then the Canvas' own (Source "keyboard", as every DrawnUI engine). True when one took it.
657
+ */
658
+ OpenContextMenuFromKeyboard(control, native) {
659
+ const r = control.GetAccessibilityPixelRect(), scale = this.RenderingScale;
660
+ const pixels = new SKPoint((r.Left + r.Right) / 2, (r.Top + r.Bottom) / 2);
661
+ const args = new ContextMenuEventArgs(new SKPoint(pixels.X / scale, pixels.Y / scale), pixels, "keyboard", native);
662
+ this.tooltip.CloseOnInput();
663
+ for (let c = control; c; c = c.Parent) {
664
+ if (!c.ContextMenu)
665
+ continue;
666
+ args.Control = c;
667
+ args.Local = new SKPoint(pixels.X - c.DrawingRect.Left, pixels.Y - c.DrawingRect.Top);
668
+ if (c.ContextMenu(c, args) === true)
669
+ return true;
670
+ }
671
+ args.Control = undefined;
672
+ return !!this.ContextMenu && this.ContextMenu(this, args) === true;
673
+ }
310
674
  cursorPointer = false;
311
675
  /**
312
676
  * DrawnUi.Blazor shows `cursor: pointer` over interactive controls through its overlay elements; here the overlay
313
- * is pointer-events:none, so the mouse position is tested against the accessibility snapshot (the accessible
314
- * controls' rects in points, already sorted and rate-limited), each hit control answering WantsPointerCursor
315
- * (itself tappable, or a tappable span of a label), and the canvas element's cursor is switched only when the
316
- * answer changes. Mouse moves only, no work without a mouse and none in the frame loop.
677
+ * is pointer-events:none, so the canvas decides from the hover hit path (Hover.Path: the controls under the mouse by
678
+ * the routing rules of ProcessGestures, so nothing below a popup that blocks gestures below): a control in the
679
+ * accessibility tree (it has a role) that answers WantsPointerCursor (itself tappable, or a tappable span of a label)
680
+ * shows the hand. A popup's close-on-background-tap wrapper has no role, so its backdrop shows none. The canvas
681
+ * element's cursor is switched only when the answer changes. Mouse moves only, none in the frame loop.
317
682
  */
318
- UpdateCursor(x, y) {
683
+ UpdateCursor() {
319
684
  let hit = false;
320
- const scale = this.RenderingScale;
321
- for (const n of this.AccessibilityManager.Snapshot) {
322
- if (x < n.Rect.Left || x >= n.Rect.Right || y < n.Rect.Top || y >= n.Rect.Bottom)
323
- continue;
324
- // the control decides (whole control, or a tappable span of a label); point in pixels relative to the control's
325
- // origin, taken from the snapshot rect (already carries the scroll / cache offset; a rotated control gets its bbox)
326
- if (n.Source.WantsPointerCursor((x - n.Rect.Left) * scale, (y - n.Rect.Top) * scale)) {
685
+ const path = this.Hover.Path, xs = this.Hover.PathX, ys = this.Hover.PathY;
686
+ for (let i = path.length - 1; i >= 0 && !hit; i--) {
687
+ const c = path[i];
688
+ if (c.IsAccessibilityElement && c.WantsPointerCursor(xs[i] - c.DrawingRect.Left, ys[i] - c.DrawingRect.Top))
327
689
  hit = true;
328
- break;
329
- }
330
690
  }
331
691
  if (hit !== this.cursorPointer) {
332
692
  this.cursorPointer = hit;
333
693
  this.Element.style.cursor = hit ? "pointer" : "";
334
694
  }
335
695
  }
336
- /** Mouse wheel -> TouchActionResult.Wheel (page scroll suppressed while gestures are enabled). */
696
+ /**
697
+ * Mouse wheel -> TouchActionResult.Wheel.
698
+ * Lock keeps every wheel on the canvas. Enabled shares it with the page, like DrawnUi.Blazor's
699
+ * TouchHandlingStyle.Manual: the page scrolls unless a control consumed this wheel. The browser needs that answer
700
+ * inside this handler, so the wheel is processed now instead of at the next frame (Blazor does the same, for the
701
+ * same reason); pending gestures are flushed first so the event order is kept.
702
+ */
337
703
  onWheel = (e) => {
338
- e.preventDefault();
339
704
  const rect = this.Element.getBoundingClientRect();
340
705
  const args = new TouchActionEventArgs();
341
706
  args.Id = -1;
@@ -343,32 +708,136 @@ export class Canvas {
343
708
  args.Scale = this.RenderingScale;
344
709
  args.Location = new SKPoint((e.clientX - rect.left) * this.RenderingScale, (e.clientY - rect.top) * this.RenderingScale);
345
710
  args.StartingLocation = args.Location;
346
- args.Wheel = { Delta: e.deltaY !== 0 ? e.deltaY : e.deltaX };
347
- this.OnGestureEvent(args, "Wheel");
711
+ // lines and pages to pixels, then the dominant axis (the .NET browser heads, fc8980c1); a vertical scroll leaves
712
+ // horizontal events alone (C# ba03cb20)
713
+ const factor = e.deltaMode === 1 ? 40 : e.deltaMode === 2 ? 800 : 1;
714
+ const horizontal = Math.abs(e.deltaX) > Math.abs(e.deltaY);
715
+ args.Wheel = { Delta: (horizontal ? e.deltaX : e.deltaY) * factor, IsHorizontal: horizontal };
716
+ this.tooltip.CloseOnInput();
717
+ if (this.gestures === "Lock") {
718
+ e.preventDefault();
719
+ this.OnGestureEvent(args, "Wheel");
720
+ return;
721
+ }
722
+ if (this.ProcessGestureNow(args, "Wheel"))
723
+ e.preventDefault();
348
724
  };
725
+ /**
726
+ * Processes one gesture immediately (after whatever is queued) and reports whether a control USED it: a consumer
727
+ * that marked the event Handled, or any consumer that is not a `BlockGesturesBelow` layer. A blocker returns itself
728
+ * for every gesture it keeps from the controls below (a shell page, a popup backdrop), which is not a use: counting
729
+ * it would block the page wheel over every shell app.
730
+ */
731
+ ProcessGestureNow(args, result) {
732
+ this.ProcessPendingGestures();
733
+ const root = this.content;
734
+ const consumed = root ? this.ProcessGestures(root, SkiaGesturesParameters.Create(result, args)) : null;
735
+ this.Update();
736
+ return !!consumed && (args.Handled || !consumed.BlockGesturesBelow);
737
+ }
738
+ /**
739
+ * The page axes a touch pan over the canvas hands to the browser: "pan-y" when the page (or a scrolling ancestor) can
740
+ * scroll vertically, "pan-x" horizontally, both, or "none". Mirrors MAUI's Gestures="Enabled" inside a native scroll
741
+ * view, where the parent takes the pans it scrolls in.
742
+ */
743
+ static PageScrollAxes(el) {
744
+ const scrolls = (v) => v === "auto" || v === "scroll" || v === "overlay";
745
+ const clips = (v) => v === "hidden" || v === "clip";
746
+ let x = false, y = false;
747
+ for (let n = el.parentElement; n && n !== document.body && n !== document.documentElement; n = n.parentElement) {
748
+ const st = getComputedStyle(n);
749
+ if (!y && scrolls(st.overflowY) && n.scrollHeight > n.clientHeight + 1)
750
+ y = true;
751
+ if (!x && scrolls(st.overflowX) && n.scrollWidth > n.clientWidth + 1)
752
+ x = true;
753
+ }
754
+ // the viewport scrolls unless html or body clips it
755
+ const root = document.scrollingElement ?? document.documentElement;
756
+ const hs = getComputedStyle(document.documentElement), bs = getComputedStyle(document.body);
757
+ if (!y && !clips(hs.overflowY) && !clips(bs.overflowY) && root.scrollHeight > root.clientHeight + 1)
758
+ y = true;
759
+ if (!x && !clips(hs.overflowX) && !clips(bs.overflowX) && root.scrollWidth > root.clientWidth + 1)
760
+ x = true;
761
+ // a canvas filling a framed document (a widget in an iframe): the page that scrolls is the parent, which a
762
+ // cross-origin frame cannot inspect, so assume it scrolls vertically; horizontal pans and taps stay on the canvas
763
+ if (!y && window.self !== window.top)
764
+ y = true;
765
+ return x && y ? "pan-x pan-y" : y ? "pan-y" : x ? "pan-x" : "none";
766
+ }
767
+ /**
768
+ * Gestures="Enabled" shares touch pans with the page like MAUI's Enabled inside a native scroll view: along an axis
769
+ * the page can scroll, the browser takes the pan (and sends pointercancel), taps and the other axis stay on the
770
+ * canvas. A page that cannot scroll, and Lock, keep every touch. The browser reads touch-action when a touch starts,
771
+ * so it is kept current ahead of time: on attach, when the window / html / body resize, and after every touch.
772
+ */
773
+ UpdateTouchAction = () => {
774
+ if (this.gestures === "Disabled")
775
+ return;
776
+ const pan = this.gestures === "Enabled" ? Canvas.PageScrollAxes(this.Element) : "none";
777
+ if (this.Element.style.touchAction !== pan)
778
+ this.Element.style.touchAction = pan;
779
+ };
780
+ pageObserver;
349
781
  AttachInput() {
350
782
  const el = this.Element;
351
- el.style.touchAction = "none";
783
+ this.UpdateTouchAction();
784
+ window.addEventListener("resize", this.UpdateTouchAction);
785
+ this.pageObserver = new ResizeObserver(this.UpdateTouchAction);
786
+ this.pageObserver.observe(document.documentElement);
787
+ this.pageObserver.observe(document.body);
352
788
  el.style.userSelect = "none";
353
789
  for (const t of ["pointerdown", "pointermove", "pointerup", "pointercancel"])
354
790
  el.addEventListener(t, this.onPointer);
791
+ el.addEventListener("pointerleave", this.onPointerLeave);
355
792
  el.addEventListener("contextmenu", this.onContextMenu);
356
793
  el.addEventListener("wheel", this.onWheel, { passive: false });
357
- if (this.gestures === "Lock")
794
+ window.addEventListener("blur", this.onWindowBlur);
795
+ if (this.gestures === "Lock") {
358
796
  el.addEventListener("touchmove", this.preventTouch, { passive: false });
797
+ // the canvas owns every touch (DrawnUi.Web applyGestureStyle, DrawnUi.Rust host): no iOS callout or text
798
+ // selection on a long press, and no rubber band / pull-down of the page starting on it
799
+ const st = el.style;
800
+ st.webkitUserSelect = "none";
801
+ st.webkitTouchCallout = "none";
802
+ this.pageOverscroll = [document.documentElement.style.overscrollBehavior, document.body.style.overscrollBehavior];
803
+ document.documentElement.style.overscrollBehavior = "none";
804
+ document.body.style.overscrollBehavior = "none";
805
+ }
806
+ else if (this.gestures === "Enabled")
807
+ el.addEventListener("touchmove", this.preventClaimedTouch, { passive: false });
359
808
  }
809
+ /** The page's own overscroll-behavior before Lock set it to none (html, body), put back on detach. */
810
+ pageOverscroll;
360
811
  DetachInput() {
361
812
  const el = this.Element;
362
813
  el.style.touchAction = "";
814
+ window.removeEventListener("resize", this.UpdateTouchAction);
815
+ this.pageObserver?.disconnect();
816
+ this.pageObserver = undefined;
363
817
  el.style.userSelect = "";
364
818
  for (const t of ["pointerdown", "pointermove", "pointerup", "pointercancel"])
365
819
  el.removeEventListener(t, this.onPointer);
820
+ el.removeEventListener("pointerleave", this.onPointerLeave);
366
821
  el.removeEventListener("contextmenu", this.onContextMenu);
367
822
  el.removeEventListener("wheel", this.onWheel);
823
+ window.removeEventListener("blur", this.onWindowBlur);
368
824
  el.removeEventListener("touchmove", this.preventTouch);
825
+ el.removeEventListener("touchmove", this.preventClaimedTouch);
826
+ if (this.pageOverscroll) {
827
+ const st = el.style;
828
+ st.webkitUserSelect = "";
829
+ st.webkitTouchCallout = "";
830
+ [document.documentElement.style.overscrollBehavior, document.body.style.overscrollBehavior] = this.pageOverscroll;
831
+ this.pageOverscroll = undefined;
832
+ }
833
+ this.claimedTouches.clear();
834
+ for (const id of [...this.longPressTimers.keys()])
835
+ this.DisarmLongPress(id);
836
+ this.longPressed.clear();
369
837
  this.activeTouchIds.clear();
370
838
  this.pointerDownArgs.clear();
371
839
  this.previousTouchArgs.clear();
840
+ this.fingers.Reset();
372
841
  }
373
842
  /** Port of DrawnUi.Blazor Canvas.OnTouchAction: per-pointer state machine producing Down / Panning / Tapped / Up. */
374
843
  OnTouchAction(args) {
@@ -376,12 +845,34 @@ export class Canvas {
376
845
  return;
377
846
  const id = args.Id;
378
847
  if (args.Type === "Pressed") {
848
+ this.ArmLongPress(id, args);
849
+ // the fingers for pinch and turn: the first restarts them, a second one makes the press no tap
850
+ if (this.activeTouchIds.size === 0) {
851
+ this.fingers.Restart(id, args.Location);
852
+ this.multiTouch = false;
853
+ }
854
+ else {
855
+ for (const [other, last] of this.previousTouchArgs)
856
+ this.fingers.AddMovement(other, last.Location); // their latest places
857
+ this.fingers.AddMovement(id, args.Location);
858
+ this.multiTouch = true;
859
+ }
379
860
  this.activeTouchIds.add(id);
380
861
  args.NumberOfTouches = this.activeTouchIds.size;
381
862
  args.StartingLocation = args.Location;
382
863
  args.IsInContact = true;
383
864
  this.pointerDownArgs.set(id, args);
384
865
  this.previousTouchArgs.set(id, args);
866
+ // Gestures="Enabled", touch or pen: page scrolling was left to touch-action alone, and iOS Safari still takes an
867
+ // off-axis drag from the page axis (pointercancel mid-gesture, w3c/pointerevents#303). So the Down is processed
868
+ // now, like the wheel (queued gestures first, same "used" rule): when a control used it the touch is claimed and
869
+ // its touchmoves are default-prevented until it ends. It is not queued as well, so it is processed exactly once and
870
+ // the Panning / Up that follow keep their order. An unclaimed touch shares the page as before.
871
+ if (this.gestures === "Enabled" && args.Pointer && args.Pointer.DeviceType !== "Mouse") {
872
+ if (this.ProcessGestureNow(args, "Down"))
873
+ this.claimedTouches.add(id);
874
+ return;
875
+ }
385
876
  this.OnGestureEvent(args, "Down");
386
877
  return;
387
878
  }
@@ -390,6 +881,11 @@ export class Canvas {
390
881
  const downArgs = this.pointerDownArgs.get(id);
391
882
  args.StartingLocation = downArgs ? downArgs.StartingLocation : args.Location;
392
883
  if (args.Type === "Moved") {
884
+ if (this.activeTouchIds.size > 1)
885
+ args.Manipulation = this.fingers.AddMovement(id, args.Location); // nothing for one finger
886
+ const threshold = Canvas.TappedCancelMoveThresholdPoints * Math.max(0.1, this.RenderingScale);
887
+ if (Math.abs(args.Distance.Total.X) >= threshold || Math.abs(args.Distance.Total.Y) >= threshold)
888
+ this.DisarmLongPress(id);
393
889
  if (args.Distance.Delta.X !== 0 || args.Distance.Delta.Y !== 0)
394
890
  this.OnGestureEvent(args, "Panning");
395
891
  this.previousTouchArgs.set(id, args);
@@ -397,7 +893,9 @@ export class Canvas {
397
893
  }
398
894
  if (args.Type === "Released" || args.Type === "Cancelled") {
399
895
  args.IsInContact = args.NumberOfTouches > 1;
400
- if (!args.IsInContact && downArgs && args.Type === "Released") {
896
+ const longPressed = this.longPressed.delete(id);
897
+ this.DisarmLongPress(id);
898
+ if (!args.IsInContact && downArgs && args.Type === "Released" && !longPressed && !this.multiTouch) {
401
899
  const threshold = Canvas.TappedCancelMoveThresholdPoints * Math.max(0.1, this.RenderingScale);
402
900
  if (Math.abs(args.Distance.Total.X) < threshold && Math.abs(args.Distance.Total.Y) < threshold)
403
901
  this.OnGestureEvent(args, "Tapped");
@@ -406,6 +904,38 @@ export class Canvas {
406
904
  this.previousTouchArgs.delete(id);
407
905
  this.pointerDownArgs.delete(id);
408
906
  this.activeTouchIds.delete(id);
907
+ if (this.activeTouchIds.size === 0)
908
+ this.fingers.Reset();
909
+ else
910
+ this.fingers.Lifted(id);
911
+ }
912
+ }
913
+ /** The fingers down, for TouchActionEventArgs.Manipulation (pinch and turn). */
914
+ fingers = new MultitouchTracker();
915
+ /** The press had a second finger: it is no tap (AppoMobi.Blazor.Gestures). */
916
+ multiTouch = false;
917
+ longPressTimers = new Map();
918
+ longPressed = new Set();
919
+ /** The long press of a new press: due LongPressTimeMs later unless the pointer moves away or lets go. */
920
+ ArmLongPress(id, down) {
921
+ this.DisarmLongPress(id);
922
+ this.longPressed.delete(id);
923
+ this.longPressTimers.set(id, window.setTimeout(() => {
924
+ this.longPressTimers.delete(id);
925
+ if (!this.activeTouchIds.has(id))
926
+ return;
927
+ this.longPressed.add(id);
928
+ const args = new TouchActionEventArgs();
929
+ Object.assign(args, down);
930
+ args.Location = down.StartingLocation ?? down.Location;
931
+ this.OnGestureEvent(args, "LongPressing");
932
+ }, Canvas.LongPressTimeMs));
933
+ }
934
+ DisarmLongPress(id) {
935
+ const t = this.longPressTimers.get(id);
936
+ if (t) {
937
+ clearTimeout(t);
938
+ this.longPressTimers.delete(id);
409
939
  }
410
940
  }
411
941
  OnGestureEvent(args, result) {
@@ -433,24 +963,155 @@ export class Canvas {
433
963
  static IsSavedGesture(type) {
434
964
  return type === "Panning" || type === "Wheel" || type === "Up";
435
965
  }
436
- /** Entry into the control tree, same shape as DrawnUi Canvas.ProcessGestures. */
966
+ // ---- arrows start keyboard navigation (C# 6aee5c51) ----
967
+ arrowsStart = false;
968
+ /**
969
+ * While no drawn control has keyboard focus (or only one behind the active modal), the arrow keys start keyboard
970
+ * 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
971
+ * for that. Once a control has focus the arrows work as usual (inside a list or a menu). Off by default, since games use
972
+ * the arrows as their own keys while nothing is focused: an app turns it on for its menu screens and off while playing.
973
+ */
974
+ get ArrowsStartKeyboardNavigation() { return this.arrowsStart; }
975
+ set ArrowsStartKeyboardNavigation(v) {
976
+ if (this.arrowsStart === v)
977
+ return;
978
+ this.arrowsStart = v;
979
+ if (v)
980
+ KeyboardManager.SubscribeNavigation(this.onArrowKey);
981
+ else
982
+ KeyboardManager.UnsubscribeNavigation(this.onArrowKey);
983
+ }
984
+ onArrowKey = (key, e) => {
985
+ const forward = key === "ArrowDown" || key === "ArrowRight" ? true : key === "ArrowUp" || key === "ArrowLeft" ? false : undefined;
986
+ // a page element, a drawn control's element or the editor's input has the keys: nothing to start
987
+ if (forward === undefined || this.disposed || KeyboardManager.IsOwnedByElement(e) || e.defaultPrevented)
988
+ return false;
989
+ const mgr = this.AccessibilityManager, focused = mgr.FocusedNode;
990
+ if (focused && !mgr.IsOutsideModal(focused))
991
+ return false;
992
+ const first = mgr.NextTabStop(undefined, forward);
993
+ if (!first)
994
+ return false;
995
+ e.preventDefault();
996
+ mgr.RequestKeyboardFocus(first);
997
+ this.Update();
998
+ return true;
999
+ };
1000
+ // ---- focus (C# DrawnView FocusedChild / ReportFocus, drawnui-cross 6ap) ----
1001
+ focusedChild;
1002
+ focusAtDown;
1003
+ tapNoFocus = false;
1004
+ reportingFocus = false;
1005
+ /**
1006
+ * A control that left the canvas (removed or disposed) is let go by the focus, the gesture dispatch and the tooltips,
1007
+ * so the last control that took input does not keep its page alive (C# 4cb28ab6). Checked once per frame.
1008
+ */
1009
+ ForgetGoneControls() {
1010
+ const gone = (c) => !!c && (c.IsDisposed || c.Superview !== this);
1011
+ if (gone(this.focusedChild))
1012
+ this.focusedChild = undefined;
1013
+ if (gone(this.focusAtDown))
1014
+ this.focusAtDown = undefined;
1015
+ if (gone(this.gestureOwner))
1016
+ this.gestureOwner = null;
1017
+ this.tooltipController?.ForgetGone(gone);
1018
+ }
1019
+ /** The control that has the canvas focus (an editor while it edits, a CanBeFocused control that was tapped). */
1020
+ get FocusedChild() { return this.focusedChild; }
1021
+ /**
1022
+ * 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
1023
+ * editor focused); undefined clears it. Nothing moves while the focused control has LockFocus. `setter` is a control
1024
+ * that focused itself already (an editor on its press) or the focused control letting go itself (Escape, submit).
1025
+ */
1026
+ ReportFocus(value, setter) {
1027
+ if (value === this.focusedChild || this.reportingFocus)
1028
+ return;
1029
+ if (this.focusedChild?.LockFocus && setter !== this.focusedChild)
1030
+ return;
1031
+ this.reportingFocus = true;
1032
+ try {
1033
+ if (value && value !== setter && !value.SetFrameworkFocus(true))
1034
+ return;
1035
+ const previous = this.focusedChild;
1036
+ this.focusedChild = value;
1037
+ if (previous && !previous.IsDisposed)
1038
+ previous.SetFrameworkFocus(false);
1039
+ }
1040
+ finally {
1041
+ this.reportingFocus = false;
1042
+ }
1043
+ }
1044
+ /** Entry into the control tree; on a completed tap the focus follows it (C# Canvas: focus only on Tapped). */
437
1045
  ProcessGestures(root, args) {
1046
+ if (args.Type === "Down") {
1047
+ this.focusAtDown = this.focusedChild;
1048
+ this.tapNoFocus = false;
1049
+ }
1050
+ const consumed = this.RouteGestures(root, args);
1051
+ // a control that claimed the focus during this gesture (an editor on its press) keeps it; a press that closed the
1052
+ // popup windows moves nothing
1053
+ if (args.Type === "Tapped" && !this.tapNoFocus && this.focusedChild === this.focusAtDown)
1054
+ this.ReportFocus(consumed ?? undefined);
1055
+ return consumed;
1056
+ }
1057
+ /** Same shape as DrawnUi Canvas.ProcessGestures. */
1058
+ RouteGestures(root, args) {
438
1059
  const info = () => new GestureEventProcessingInfo(args.Event.Location, SKPoint.Empty, SKPoint.Empty, null);
1060
+ const popups = this.popups, at = args.Event.Location;
1061
+ // the rest of a press that closed the popup windows goes nowhere (native menus)
1062
+ if (args.Type === "Down")
1063
+ popups.SwallowPress = false;
1064
+ if (popups.SwallowPress) {
1065
+ if (args.Type === "Up")
1066
+ popups.SwallowPress = false;
1067
+ return null;
1068
+ }
1069
+ // the wheel outside the popup windows closes them (what they opened from is about to move), before any owner takes it
1070
+ if (args.Type === "Wheel" && popups.HasInteractive && !popups.At(at.X, at.Y)) {
1071
+ popups.CloseAll(false);
1072
+ this.AfterPopupsChanged();
1073
+ }
1074
+ // the wheel goes to the press owner only while a press is held; between presses it goes by position, and it
1075
+ // never makes an owner: a wheel over a second scroll moves that one, not the last one the wheel moved
1076
+ // (DrawnUi.Rust input_router "the wheel goes to the owner of the press first"; C# keeps the last wheel consumer)
1077
+ const wheel = args.Type === "Wheel";
439
1078
  if (args.Type === "Down")
440
1079
  this.gestureOwner = null;
441
- else if (this.gestureOwner && Canvas.IsSavedGesture(args.Type)) {
1080
+ else if (this.gestureOwner && Canvas.IsSavedGesture(args.Type) && (!wheel || this.activeTouchIds.size > 0)) {
442
1081
  const owner = this.gestureOwner;
443
1082
  const alive = !!owner.Superview && owner.IsVisible && !owner.InputTransparent;
444
1083
  const consumed = alive ? owner.OnSkiaGestureEvent(args, info()) : null;
445
1084
  if (consumed) {
446
1085
  // it still wants the gesture: nobody else sees this one (C# skips the tree pass for a saved gesture)
447
- this.gestureOwner = args.Type === "Up" ? null : consumed;
1086
+ if (!wheel)
1087
+ this.gestureOwner = args.Type === "Up" ? null : consumed;
448
1088
  return consumed;
449
1089
  }
450
- this.gestureOwner = null; // it let go (a button whose press turned into a pan): route normally again
1090
+ // it let go (a button whose press turned into a pan): route normally again; a wheel it does not use goes by
1091
+ // position and leaves it the press
1092
+ if (!wheel)
1093
+ this.gestureOwner = null;
1094
+ }
1095
+ // over a popup window its controls take the gesture and nothing below sees it; a press elsewhere closes them
1096
+ if (popups.HasInteractive) {
1097
+ const popupRoot = popups.At(at.X, at.Y);
1098
+ if (popupRoot) {
1099
+ const used = popupRoot.ProcessGestures(args, info()) ?? popupRoot;
1100
+ if (!wheel)
1101
+ this.gestureOwner = args.Type !== "Up" ? used : null;
1102
+ return used;
1103
+ }
1104
+ if (args.Type === "Down") {
1105
+ this.tapNoFocus = true;
1106
+ popups.CloseAll(false);
1107
+ popups.SwallowPress = true;
1108
+ this.AfterPopupsChanged();
1109
+ return null;
1110
+ }
451
1111
  }
452
1112
  const consumed = root.ProcessGestures(args, info());
453
- this.gestureOwner = consumed && args.Type !== "Up" ? consumed : null;
1113
+ if (!wheel)
1114
+ this.gestureOwner = consumed && args.Type !== "Up" ? consumed : null;
454
1115
  return consumed;
455
1116
  }
456
1117
  }