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

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