drawnui-react 0.1.0-preview.42 → 0.1.0-preview.44

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.
@@ -5,17 +5,17 @@ import { HoverManager } from "./Hover";
5
5
  import { TooltipController } from "./Tooltips";
6
6
  import { PopupAnchor, PopupLayer } from "./PopupWindows";
7
7
  import { KeyboardManager } from "./KeyboardManager";
8
+ import { TouchEffect } from "./Gestures";
9
+ import { TextInputProxy } from "./TextInputProxy";
8
10
  import { Colors, SKRect } from "./Types";
9
11
  import { ContextMenuEventArgs, GestureEventProcessingInfo, MultitouchTracker, PointerData, SKPoint, SkiaGesturesParameters, TouchActionEventArgs, } from "./Gestures";
10
12
  export class Canvas {
11
13
  Element;
12
14
  /** Points a pointer may travel between Down and Up and still count as a tap (AppoMobi TouchEffect default). */
13
15
  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;
16
+ /** Alias of TouchEffect.LongPressTimeMsDefault: how long a press is held still to be a LongPressing. */
17
+ static get LongPressTimeMs() { return TouchEffect.LongPressTimeMsDefault; }
18
+ static set LongPressTimeMs(ms) { TouchEffect.LongPressTimeMsDefault = ms; }
19
19
  BackgroundColor = Colors.Transparent;
20
20
  /** Accelerated = WebGL surface, Default = software. Read once at first frame. */
21
21
  RenderingMode = "Accelerated";
@@ -84,7 +84,7 @@ export class Canvas {
84
84
  * tool drawing an overlay on `Surface.getCanvas()`). Made on first use: a canvas without listeners does no work.
85
85
  */
86
86
  get WasDrawnListeners() { return this.wasDrawnListeners ??= new Set(); }
87
- raiseWasDrawn = (f) => f(this);
87
+ raiseWasDrawn = (f) => Canvas.Guard("a WasDrawn listener", f, () => f(this));
88
88
  /**
89
89
  * Shows `content` over everything, opening from `anchor` the way native menus do: at a point (a right click, canvas
90
90
  * points), or below a rect or a control (a dropdown), flipped to the other side where it does not fit. It closes with
@@ -253,11 +253,8 @@ export class Canvas {
253
253
  const surface = this.surface;
254
254
  this.frameId = surface.requestAnimationFrame((c) => {
255
255
  this.frameId = 0;
256
- if (this.surface === surface && !this.disposed) {
257
- this.Draw(c);
258
- surface.flush();
259
- this.DrainDisposeQueue();
260
- }
256
+ if (this.surface === surface && !this.disposed)
257
+ this.DrawGuarded(c, surface);
261
258
  });
262
259
  }
263
260
  /** Deletes the current surface; a pending frame on it is cancelled first (drawing on a deleted surface faults). */
@@ -383,13 +380,12 @@ export class Canvas {
383
380
  const surface = this.surface;
384
381
  if (!surface || this.disposed || this.contextLost)
385
382
  return;
386
- this.Draw(surface.getCanvas());
387
- surface.flush();
388
- this.DrainDisposeQueue();
383
+ this.DrawGuarded(surface.getCanvas(), surface);
389
384
  }
390
385
  Draw(canvas) {
391
386
  const started = performance.now();
392
387
  this.ProcessPendingGestures();
388
+ this.ProcessTextSelectionFrame();
393
389
  // Animators run on the frame's vsync time (inside a rAF callback document.timeline.currentTime is the frame
394
390
  // timestamp), not on when this callback happened to start: callback starts drift by several ms around vsync
395
391
  // (measured 12..23 ms between frames shown 16.7 ms apart), and a game loop moving by speed * delta then
@@ -398,8 +394,8 @@ export class Canvas {
398
394
  this.FrameTimeNanos = Math.round(frameTime * 1_000_000);
399
395
  const executed = this.ExecuteAnimators(Math.round(frameTime * 1_000_000));
400
396
  const canRender = this.CanRender;
401
- if (canRender && !this.WasRendered)
402
- this.WillFirstTimeDraw?.(this, { Canvas: canvas, Surface: this.surface });
397
+ if (canRender && !this.WasRendered && this.WillFirstTimeDraw)
398
+ Canvas.Guard("WillFirstTimeDraw", this.WillFirstTimeDraw, () => this.WillFirstTimeDraw(this, { Canvas: canvas, Surface: this.surface }));
403
399
  canvas.clear(Super.ParseColor(this.BackgroundColor));
404
400
  const root = this.content;
405
401
  if (root) {
@@ -415,6 +411,7 @@ export class Canvas {
415
411
  this.popupLayer.Draw(top, top.Destination);
416
412
  this.tooltipController?.Draw(top, top.Destination);
417
413
  this.AccessibilityManager.OnFrameEnd(this.RenderingScale, this.Element.width, this.Element.height, () => this.Update());
414
+ TextInputProxy.AfterFrame(this);
418
415
  this.Hover.AfterFrame(this.content, this.activeTouchIds.size > 0);
419
416
  if (this.Hover.Paused)
420
417
  this.tooltipController?.Reset(); // content moves under the pointer
@@ -429,7 +426,8 @@ export class Canvas {
429
426
  if (executed > 0)
430
427
  this.Update(); // animators running: keep frames coming
431
428
  // C# order: WasDrawn at the end of the frame, then the frame counts as rendered
432
- this.WasDrawn?.(this);
429
+ if (this.WasDrawn)
430
+ Canvas.Guard("WasDrawn", this.WasDrawn, () => this.WasDrawn(this));
433
431
  const listeners = this.wasDrawnListeners;
434
432
  if (listeners !== undefined && listeners.size > 0)
435
433
  listeners.forEach(this.raiseWasDrawn);
@@ -489,6 +487,46 @@ export class Canvas {
489
487
  }
490
488
  static reportedAnimators = new WeakSet();
491
489
  /** An animator's callback threw: logged once for that animator, the frame goes on. */
490
+ /**
491
+ * One exception never stops the frame loop (drawnui-cross 6ch, DrawnUi.Net 3db4eba3): app code the frame runs (a
492
+ * listener, a gesture handler) is called through this; a throw is logged once per source and the frame goes on.
493
+ */
494
+ static Guard(what, source, call) {
495
+ try {
496
+ return call();
497
+ }
498
+ catch (e) {
499
+ if (!Canvas.reportedSources.has(source)) {
500
+ Canvas.reportedSources.add(source);
501
+ console.error(`DrawnUi: ${what} threw; the frame goes on`, e);
502
+ }
503
+ return undefined;
504
+ }
505
+ }
506
+ static reportedSources = new WeakSet();
507
+ /**
508
+ * Draws a frame and always shows it: a throw inside it (app drawing code) is logged once, the canvas state is reset and
509
+ * the frame loop goes on (a running animation or game keeps asking for frames).
510
+ */
511
+ DrawGuarded(canvas, surface) {
512
+ try {
513
+ this.Draw(canvas);
514
+ }
515
+ catch (e) {
516
+ canvas.restoreToCount(1);
517
+ if (!Canvas.reportedFrameError) {
518
+ Canvas.reportedFrameError = true;
519
+ console.error("DrawnUi: drawing a frame threw; the next frames go on", e);
520
+ }
521
+ if (this.AnimatingControls.size > 0)
522
+ this.Update();
523
+ }
524
+ finally {
525
+ surface.flush();
526
+ this.DrainDisposeQueue();
527
+ }
528
+ }
529
+ static reportedFrameError = false;
492
530
  static ReportAnimatorError(a, e) {
493
531
  if (Canvas.reportedAnimators.has(a))
494
532
  return;
@@ -654,6 +692,163 @@ export class Canvas {
654
692
  pointerDownArgs = new Map();
655
693
  previousTouchArgs = new Map();
656
694
  pendingGestures = [];
695
+ // ---- page text selection with the mouse, as in browsers (port of C# DrawnView.TextSelection, drawnui-cross 6cc) ----
696
+ // A main-button drag that starts on no interactive control selects the selectable labels (AccessibilityTextSelectable)
697
+ // it crosses, in reading order, the first and last partly. Idle cost: one check per gesture and per frame.
698
+ textDrag;
699
+ pageSelection = [];
700
+ pageSelectionKeys = false;
701
+ /**
702
+ * The text selected on the page: the labels a mouse drag selected, joined with new lines, in page order; else the
703
+ * selection of the label in focus. Empty when nothing is selected.
704
+ */
705
+ get SelectedText() {
706
+ if (this.pageSelection.length > 0)
707
+ return this.pageSelection.map((l) => l.SelectedText).filter((t) => t).join("\n");
708
+ return this.focusedChild?.SelectedText ?? "";
709
+ }
710
+ /** True while a mouse drag selection holds page text: the page, not a label, owns Ctrl+C. */
711
+ get OwnsTextSelectionKeys() { return this.pageSelection.some((l) => l.SelectionLength > 0); }
712
+ /** Puts SelectedText on the clipboard through Super.SetClipboardText. False when nothing is selected. */
713
+ CopyTextSelection() {
714
+ const text = this.SelectedText;
715
+ if (!text)
716
+ return false;
717
+ Super.SetClipboardText(text);
718
+ return true;
719
+ }
720
+ /** Drops the page text selection (every label a drag selected) and the selection of the label in focus. */
721
+ ClearTextSelection() {
722
+ for (const label of this.pageSelection)
723
+ label.ClearSelection();
724
+ this.pageSelection.length = 0;
725
+ this.focusedChild?.ClearSelection?.();
726
+ this.AttachPageSelectionKeys(false);
727
+ }
728
+ /**
729
+ * Before a gesture goes to the controls: a mouse drag that is selecting text keeps its moves (a scroll under it does
730
+ * not scroll), a main-button press drops the previous page selection. True when the gesture was used here.
731
+ */
732
+ PreviewTextSelectionGesture(args) {
733
+ const mouseMain = args.Event.Pointer?.DeviceType === "Mouse" && args.Event.Pointer.Button === "Left";
734
+ const drag = this.textDrag;
735
+ if (args.Type === "Down" && mouseMain) {
736
+ this.textDrag = undefined;
737
+ // a press on an open popup window (the menu that copies the selection) keeps it, as browsers keep a selection
738
+ // while their context menu is used
739
+ const onPopup = this.popups.HasInteractive && !!this.popups.At(args.Event.Location.X, args.Event.Location.Y);
740
+ if (this.pageSelection.length > 0 && !onPopup)
741
+ this.ClearTextSelection();
742
+ }
743
+ else if (args.Type === "Panning" && drag) {
744
+ drag.X = args.Event.Location.X;
745
+ drag.Y = args.Event.Location.Y;
746
+ drag.Moved = true;
747
+ this.UpdateTextDrag(drag);
748
+ this.Update();
749
+ return true;
750
+ }
751
+ else if (args.Type === "Up" && drag) {
752
+ if (drag.Moved)
753
+ this.UpdateTextDrag(drag);
754
+ this.textDrag = undefined;
755
+ }
756
+ return false;
757
+ }
758
+ /**
759
+ * After a mouse main-button press went to the controls: when it landed on no interactive control (empty space, a
760
+ * scroll's empty area, a selectable label), a drag from here selects text. Not inside a scroll that holds no
761
+ * selectable text: that one keeps scrolling by mouse drag.
762
+ */
763
+ AfterTextSelectionDown(args, consumed) {
764
+ if (args.Type !== "Down" || args.Event.Pointer?.DeviceType !== "Mouse" || args.Event.Pointer.Button !== "Left")
765
+ return;
766
+ if (consumed && !IsScroll(consumed) && !IsSelectableLabel(consumed))
767
+ return;
768
+ if (consumed && IsScroll(consumed) && consumed.ScrollBarOwnsGesture)
769
+ return; // a press on the scroll bar drags the bar
770
+ const collected = [];
771
+ if (this.content)
772
+ CollectSelectable(this.content, collected);
773
+ if (collected.length === 0)
774
+ return;
775
+ const labels = ReadingOrder(collected);
776
+ const x = args.Event.Location.X, y = args.Event.Location.Y;
777
+ const scroll = (consumed && IsScroll(consumed) ? consumed : undefined) ?? ScrollOf(consumed ?? undefined) ?? ScrollAt(labels, x, y);
778
+ if (scroll && !labels.some((l) => IsInside(l, scroll)))
779
+ return;
780
+ const [label, index] = Locate(labels, x, y);
781
+ if (!label)
782
+ return;
783
+ this.textDrag = { Labels: labels, StartLabel: label, StartIndex: index, Scroll: scroll, X: x, Y: y, Moved: false };
784
+ }
785
+ /** Frame start: while a drag holds the pointer past a scroll's top or bottom edge, the scroll follows it. */
786
+ ProcessTextSelectionFrame() {
787
+ const drag = this.textDrag;
788
+ if (!drag?.Scroll || !drag.Moved)
789
+ return;
790
+ const view = drag.Scroll.GetAccessibilityPixelRect();
791
+ if (view.Width <= 0 || view.Height <= 0)
792
+ return;
793
+ const past = drag.Y > view.Bottom ? drag.Y - view.Bottom : drag.Y < view.Top ? drag.Y - view.Top : 0;
794
+ if (past === 0)
795
+ return;
796
+ // faster the farther past the edge, as browsers do
797
+ const step = Math.min(Math.max(Math.abs(past) * 0.25, 2), 40) / this.RenderingScale * Math.sign(past);
798
+ drag.Scroll.ScrollTo(drag.Scroll.ViewportOffsetX, drag.Scroll.ViewportOffsetY - step, 0, true);
799
+ this.UpdateTextDrag(drag);
800
+ this.Update();
801
+ }
802
+ UpdateTextDrag(drag) {
803
+ const [endLabel, endIndex] = Locate(drag.Labels, drag.X, drag.Y);
804
+ if (!endLabel)
805
+ return;
806
+ const a = drag.Labels.indexOf(drag.StartLabel), b = drag.Labels.indexOf(endLabel);
807
+ if (a < 0 || b < 0)
808
+ return;
809
+ const [fromLabel, fromIndex, toLabel, toIndex] = a < b || (a === b && drag.StartIndex <= endIndex)
810
+ ? [a, drag.StartIndex, b, endIndex] : [b, endIndex, a, drag.StartIndex];
811
+ for (const label of this.pageSelection) {
812
+ const at = drag.Labels.indexOf(label);
813
+ if (at < fromLabel || at > toLabel)
814
+ label.ClearSelection();
815
+ }
816
+ this.pageSelection.length = 0;
817
+ for (let i = fromLabel; i <= toLabel; i++) {
818
+ const label = drag.Labels[i];
819
+ const start = i === fromLabel ? fromIndex : 0, end = i === toLabel ? toIndex : label.SelectableLength;
820
+ label.Select(start, Math.max(0, end - start));
821
+ this.pageSelection.push(label);
822
+ }
823
+ this.AttachPageSelectionKeys(this.OwnsTextSelectionKeys);
824
+ }
825
+ AttachPageSelectionKeys(attach) {
826
+ if (attach === this.pageSelectionKeys)
827
+ return;
828
+ this.pageSelectionKeys = attach;
829
+ if (attach)
830
+ KeyboardManager.Subscribe(this.onPageSelectionKey, Canvas.noChar);
831
+ else
832
+ KeyboardManager.Unsubscribe(this.onPageSelectionKey, Canvas.noChar);
833
+ }
834
+ static noChar = () => { };
835
+ onPageSelectionKey = (key, e) => {
836
+ // Esc keeps the selection, as in browsers: a click elsewhere drops it
837
+ if (KeyboardManager.IsOwnedByElement(e) || !KeyboardManager.IsControlPressed)
838
+ return;
839
+ if (key === "KeyC")
840
+ this.CopyTextSelection();
841
+ else if (key === "KeyA" && IsSelectableLabel(this.focusedChild)) {
842
+ // as for one label: Ctrl+A selects all of the label in focus
843
+ e.preventDefault();
844
+ const focused = this.focusedChild;
845
+ for (const label of this.pageSelection)
846
+ label.ClearSelection();
847
+ this.pageSelection.length = 0;
848
+ this.AttachPageSelectionKeys(false);
849
+ focused.SelectAll();
850
+ }
851
+ };
657
852
  onPointer = (e) => {
658
853
  const type = e.type === "pointerdown" ? "Pressed" :
659
854
  e.type === "pointermove" ? "Moved" :
@@ -688,6 +883,7 @@ export class Canvas {
688
883
  }
689
884
  const rect = this.Element.getBoundingClientRect();
690
885
  const args = new TouchActionEventArgs();
886
+ args.Timestamp = EventTime(e);
691
887
  args.Id = e.pointerId;
692
888
  args.Type = type;
693
889
  args.Scale = this.RenderingScale;
@@ -705,6 +901,16 @@ export class Canvas {
705
901
  this.claimedTouches.delete(e.pointerId);
706
902
  this.UpdateTouchAction();
707
903
  }
904
+ // a click on the focused field gives its input DOM focus again (desktop typing and IME); on touch that is done in the
905
+ // touchend (onTouchEnd), the only event iOS opens the soft keyboard from
906
+ if (type === "Released" && e.pointerType === "mouse")
907
+ TextInputProxy.FocusFromTap(e.clientX, e.clientY);
908
+ // the touch taps the browser delivered, for a double tap whose second tap it kept (onDoubleClick)
909
+ if (type === "Released" && e.pointerType !== "mouse" && !this.replayingTap) {
910
+ this.touchUps.push(performance.now());
911
+ if (this.touchUps.length > 2)
912
+ this.touchUps.shift();
913
+ }
708
914
  };
709
915
  /** The mouse left the canvas: hover ends at once, also while content moves. */
710
916
  onPointerLeave = (e) => {
@@ -716,6 +922,99 @@ export class Canvas {
716
922
  this.popups.PointerAt(undefined, undefined);
717
923
  };
718
924
  preventTouch = (e) => e.preventDefault();
925
+ // ---- the on-screen keyboard (C# DrawnView.Keyboard, drawnui-cross 6cj: SkiaScroll.AdaptToKeyboardAuto, off by default) ----
926
+ /** Points of this canvas, up from its bottom, that the on-screen keyboard covers (0 when none). */
927
+ KeyboardCovered = 0;
928
+ keyboardScroll;
929
+ onViewportResize = () => this.ApplyKeyboard();
930
+ /**
931
+ * Measures the part the keyboard covers (the visual viewport shrinks when it opens) and, when the focused text field sits
932
+ * in a scroll with AdaptToKeyboardAuto, hands that scroll the field and the covered height; the scroll it adapted lets go
933
+ * when the keyboard closes or the field moves to another scroll. Runs on viewport resizes and focus changes only.
934
+ */
935
+ ApplyKeyboard() {
936
+ const vv = typeof window !== "undefined" ? window.visualViewport : undefined;
937
+ if (!vv)
938
+ return;
939
+ const layoutH = window.innerHeight, visibleBottom = vv.offsetTop + vv.height;
940
+ // a keyboard shrinks the visual viewport against the layout viewport (a page zoom scales it instead)
941
+ const keyboard = layoutH - vv.height > 80 && Math.abs((vv.scale ?? 1) - 1) < 0.01;
942
+ const b = this.Element.getBoundingClientRect();
943
+ const covered = keyboard ? Math.max(0, Math.min(b.bottom, layoutH) - visibleBottom) : 0;
944
+ this.KeyboardCovered = covered;
945
+ let scroll;
946
+ const field = this.focusedChild;
947
+ if (covered > 0 && field?.IsFocused && field.CursorPosition !== undefined) {
948
+ for (let p = field.Parent; p && !scroll; p = p.Parent)
949
+ if (p.AdaptToKeyboardAuto)
950
+ scroll = p;
951
+ if (scroll) {
952
+ scroll.AdaptToKeyboardFor = field;
953
+ scroll.AdaptToKeyboardSize = covered;
954
+ }
955
+ }
956
+ // keyboard up, no focused field (between two fields): the adapted scroll keeps its room
957
+ if (covered > 0 && !scroll)
958
+ return;
959
+ if (this.keyboardScroll && this.keyboardScroll !== scroll) {
960
+ this.keyboardScroll.AdaptToKeyboardFor = undefined;
961
+ this.keyboardScroll.AdaptToKeyboardSize = 0;
962
+ }
963
+ this.keyboardScroll = scroll;
964
+ }
965
+ /** When the last touch releases came (ms), at most two. */
966
+ touchUps = [];
967
+ replayingTap = false;
968
+ /**
969
+ * iOS Safari (measured on an iPhone, iOS 26.6.1) takes the second tap of a double tap for itself: it sends no pointer or
970
+ * touch event for it, only click, click and dblclick. A dblclick that follows ONE touch release (the other browsers
971
+ * deliver both taps first) brings that tap back as a touch tap at its place, so a double tap reaches the controls (a 3D
972
+ * viewer's reset).
973
+ */
974
+ onDoubleClick = (e) => {
975
+ const now = performance.now(), recent = this.touchUps.filter((t) => now - t < 700);
976
+ this.touchUps.length = 0;
977
+ if (recent.length !== 1)
978
+ return;
979
+ const pointerId = 2_000_000 + Math.floor(now);
980
+ // the second tap happened just before the dblclick: dated by it, not by when a frame handles it
981
+ const at = { clientX: e.clientX, clientY: e.clientY, pointerId, pointerType: "touch", button: 0, isTrusted: true, timeStamp: e.timeStamp };
982
+ this.replayingTap = true;
983
+ try {
984
+ this.onPointer({ ...at, type: "pointerdown", buttons: 1 });
985
+ this.onPointer({ ...at, type: "pointerup", buttons: 0 });
986
+ }
987
+ finally {
988
+ this.replayingTap = false;
989
+ }
990
+ };
991
+ /**
992
+ * The end of a touch is the user gesture iOS opens the soft keyboard from (a focus() in pointerup does not open it): the
993
+ * press's gestures run now, inside it, so a field they focus focuses its input here, and a tap on the focused field gives
994
+ * its input focus again.
995
+ */
996
+ /** A finger or a pen is down on the canvas: a text field focused now takes its input focus in the touchend (onTouchEnd). */
997
+ get TouchPressed() {
998
+ for (const a of this.pointerDownArgs.values())
999
+ if (a.Pointer && a.Pointer.DeviceType !== "Mouse")
1000
+ return true;
1001
+ return false;
1002
+ }
1003
+ onTouchEnd = (e) => {
1004
+ TextInputProxy.TouchGesture = true;
1005
+ try {
1006
+ this.ProcessPendingGestures();
1007
+ }
1008
+ finally {
1009
+ TextInputProxy.TouchGesture = false;
1010
+ }
1011
+ const t = e.changedTouches[0];
1012
+ // the input has focus now: no compatibility mouse events or click follow, whose focus would go to the canvas host
1013
+ // and take the keyboard away again
1014
+ if (t && TextInputProxy.FocusFromTap(t.clientX, t.clientY, true) && e.cancelable)
1015
+ e.preventDefault();
1016
+ TextInputProxy.AfterTouchEnd();
1017
+ };
719
1018
  /** Gestures="Enabled": touch / pen pointers whose Down a control used (see OnTouchAction). */
720
1019
  claimedTouches = new Set();
721
1020
  /** Gestures="Enabled": while a claimed touch is down the page may not take its drag. */
@@ -725,20 +1024,38 @@ export class Canvas {
725
1024
  ContextMenu;
726
1025
  /** DOM contextmenu (right click / long press / Menu key) -> ContextMenuEventArgs routed through the tree like a tap. */
727
1026
  onContextMenu = (e) => {
728
- const rect = this.Element.getBoundingClientRect();
729
- const scale = this.RenderingScale;
730
- const x = e.clientX - rect.left, y = e.clientY - rect.top;
731
1027
  const pointerType = e.pointerType;
732
1028
  const source = pointerType === "touch" || pointerType === "pen" ? "touch" : pointerType === "mouse" || e.button === 2 ? "mouse" : "keyboard";
733
- const args = new ContextMenuEventArgs(new SKPoint(x, y), new SKPoint(x * scale, y * scale), source, e);
1029
+ // a long press: the browser's own contextmenu (Android Chrome) or the press's long press raises it, once (6cb); a
1030
+ // browser menu that comes first runs the long press before it (the word under the finger is selected first, C#
1031
+ // SkipRepeatedTouchContextMenu)
1032
+ if (source === "touch")
1033
+ this.LongPressNow(e.pointerId);
1034
+ // the press the menu comes from first, in the order it happened (the browser sends contextmenu at the press on macOS
1035
+ // and Linux, after the release on Windows): processed later, its press would close a menu that opens now
1036
+ else
1037
+ this.ProcessPendingGestures();
1038
+ const handled = source === "touch" ? this.RaiseTouchContextMenu(e.clientX, e.clientY, e) : this.RaiseContextMenu(e.clientX, e.clientY, source, e);
1039
+ if (handled)
1040
+ e.preventDefault();
1041
+ // a menu opened while the button is still down: the rest of that press goes nowhere (its release would tap the item
1042
+ // under it)
1043
+ if (source !== "touch" && this.activeTouchIds.size > 0 && this.popups.HasInteractive)
1044
+ this.popups.SwallowPress = true;
1045
+ };
1046
+ /** A context-menu request at a point of the page (client CSS px), routed through the tree like a tap; true when one took it. */
1047
+ RaiseContextMenu(clientX, clientY, source, native) {
1048
+ const rect = this.Element.getBoundingClientRect();
1049
+ const scale = this.RenderingScale;
1050
+ const x = clientX - rect.left, y = clientY - rect.top;
1051
+ const args = new ContextMenuEventArgs(new SKPoint(x, y), new SKPoint(x * scale, y * scale), source, native);
734
1052
  this.tooltip.CloseOnInput();
735
1053
  // over a popup window its content is asked; elsewhere the popups close and the request goes on, so a new menu can
736
1054
  // open there (C# PopupLayer ContextMenu)
737
1055
  const popupRoot = this.popups.HasInteractive ? this.popups.At(args.Pixels.X, args.Pixels.Y) : undefined;
738
1056
  if (popupRoot) {
739
1057
  popupRoot.ProcessContextMenu(args.Pixels, args);
740
- e.preventDefault();
741
- return;
1058
+ return true;
742
1059
  }
743
1060
  if (this.popups.HasInteractive) {
744
1061
  this.popups.CloseAll(false);
@@ -747,9 +1064,31 @@ export class Canvas {
747
1064
  let handled = this.content?.ProcessContextMenu(args.Pixels, args) ?? false;
748
1065
  if (!handled && this.ContextMenu)
749
1066
  handled = this.ContextMenu(this, args) === true;
750
- if (handled)
751
- e.preventDefault();
752
- };
1067
+ return handled;
1068
+ }
1069
+ // ---- a long press on touch raises the context menu (drawnui-cross 6cb) ----
1070
+ /** The touch or pen press going on: its context menu is raised once, by the browser's contextmenu or after its long press. */
1071
+ touchMenu;
1072
+ /** The long press of a touch press was just queued: its context menu follows the LongPressing (client CSS px). */
1073
+ touchMenuDue;
1074
+ /** A touch or pen press starts (on the canvas, or on selectable text of the overlay): its context menu is still to come. */
1075
+ StartTouchPress() { this.touchMenu = { Raised: false, Handled: false }; }
1076
+ /**
1077
+ * The context menu of the touch press now (Source "touch"), raised once per press whoever asks first: the browser's own
1078
+ * contextmenu (Android Chrome fires one on a long press) or the press's long press (iOS Safari fires none). True when a
1079
+ * handler took it: the browser's own menu is then suppressed where it can be.
1080
+ */
1081
+ RaiseTouchContextMenu(clientX, clientY, native) {
1082
+ const press = this.touchMenu ??= { Raised: false, Handled: false };
1083
+ if (press.Raised)
1084
+ return press.Handled;
1085
+ press.Raised = true;
1086
+ press.Handled = this.RaiseContextMenu(clientX, clientY, "touch", native ?? new MouseEvent("contextmenu", { clientX, clientY }));
1087
+ // the app showed its own menu: the drawn Copy button of a touch text selection steps aside, the selection stays
1088
+ if (press.Handled)
1089
+ this.focusedChild?.HideCopyButton?.();
1090
+ return press.Handled;
1091
+ }
753
1092
  /**
754
1093
  * The Menu key, Shift+F10 or a screen reader's context-menu command on the control in keyboard focus (the DOM
755
1094
  * `contextmenu` of its overlay node): its context menu opens at its center, from it or the first control above it with
@@ -803,6 +1142,7 @@ export class Canvas {
803
1142
  onWheel = (e) => {
804
1143
  const rect = this.Element.getBoundingClientRect();
805
1144
  const args = new TouchActionEventArgs();
1145
+ args.Timestamp = EventTime(e);
806
1146
  args.Id = -1;
807
1147
  args.Type = "Wheel";
808
1148
  args.Scale = this.RenderingScale;
@@ -832,7 +1172,8 @@ export class Canvas {
832
1172
  ProcessGestureNow(args, result) {
833
1173
  this.ProcessPendingGestures();
834
1174
  const root = this.content;
835
- const consumed = root ? this.ProcessGestures(root, SkiaGesturesParameters.Create(result, args)) : null;
1175
+ const gesture = SkiaGesturesParameters.Create(result, args);
1176
+ const consumed = root ? Canvas.Guard("a gesture handler", root, () => this.ProcessGestures(root, gesture)) ?? null : null;
836
1177
  this.Update();
837
1178
  return !!consumed && (args.Handled || !consumed.BlockGesturesBelow);
838
1179
  }
@@ -891,6 +1232,9 @@ export class Canvas {
891
1232
  el.addEventListener(t, this.onPointer);
892
1233
  el.addEventListener("pointerleave", this.onPointerLeave);
893
1234
  el.addEventListener("contextmenu", this.onContextMenu);
1235
+ el.addEventListener("touchend", this.onTouchEnd);
1236
+ el.addEventListener("dblclick", this.onDoubleClick);
1237
+ window.visualViewport?.addEventListener("resize", this.onViewportResize);
894
1238
  el.addEventListener("wheel", this.onWheel, { passive: false });
895
1239
  window.addEventListener("blur", this.onWindowBlur);
896
1240
  if (this.gestures === "Lock") {
@@ -920,6 +1264,10 @@ export class Canvas {
920
1264
  el.removeEventListener(t, this.onPointer);
921
1265
  el.removeEventListener("pointerleave", this.onPointerLeave);
922
1266
  el.removeEventListener("contextmenu", this.onContextMenu);
1267
+ el.removeEventListener("touchend", this.onTouchEnd);
1268
+ el.removeEventListener("dblclick", this.onDoubleClick);
1269
+ window.visualViewport?.removeEventListener("resize", this.onViewportResize);
1270
+ this.textDrag = undefined;
923
1271
  el.removeEventListener("wheel", this.onWheel);
924
1272
  window.removeEventListener("blur", this.onWindowBlur);
925
1273
  el.removeEventListener("touchmove", this.preventTouch);
@@ -946,6 +1294,8 @@ export class Canvas {
946
1294
  return;
947
1295
  const id = args.Id;
948
1296
  if (args.Type === "Pressed") {
1297
+ if (args.Pointer && args.Pointer.DeviceType !== "Mouse" && this.activeTouchIds.size === 0)
1298
+ this.StartTouchPress();
949
1299
  this.ArmLongPress(id, args);
950
1300
  // the fingers for pinch and turn: the first restarts them, a second one makes the press no tap
951
1301
  if (this.activeTouchIds.size === 0) {
@@ -1028,10 +1378,30 @@ export class Canvas {
1028
1378
  this.longPressed.add(id);
1029
1379
  const args = new TouchActionEventArgs();
1030
1380
  Object.assign(args, down);
1381
+ args.Timestamp = performance.now();
1031
1382
  args.Location = down.StartingLocation ?? down.Location;
1032
1383
  this.OnGestureEvent(args, "LongPressing");
1384
+ // on touch the context menu follows the long press (6cb), at the press point
1385
+ if (down.Pointer && down.Pointer.DeviceType !== "Mouse") {
1386
+ const rect = this.Element.getBoundingClientRect(), scale = Math.max(0.1, this.RenderingScale);
1387
+ this.touchMenuDue = { X: rect.left + args.Location.X / scale, Y: rect.top + args.Location.Y / scale };
1388
+ }
1033
1389
  }, Canvas.LongPressTimeMs));
1034
1390
  }
1391
+ /** The long press of a held touch, now (the browser's context menu came first): queued gestures first, then it; its timer is off. */
1392
+ LongPressNow(pointerId) {
1393
+ const id = this.longPressTimers.has(pointerId) ? pointerId : [...this.longPressTimers.keys()][0];
1394
+ const down = id === undefined ? undefined : this.pointerDownArgs.get(id);
1395
+ if (id === undefined || !down || !this.activeTouchIds.has(id))
1396
+ return;
1397
+ this.DisarmLongPress(id);
1398
+ this.longPressed.add(id);
1399
+ const args = new TouchActionEventArgs();
1400
+ Object.assign(args, down);
1401
+ args.Timestamp = performance.now();
1402
+ args.Location = down.StartingLocation ?? down.Location;
1403
+ this.ProcessGestureNow(args, "LongPressing");
1404
+ }
1035
1405
  DisarmLongPress(id) {
1036
1406
  const t = this.longPressTimers.get(id);
1037
1407
  if (t) {
@@ -1051,7 +1421,12 @@ export class Canvas {
1051
1421
  if (!root)
1052
1422
  return;
1053
1423
  for (const args of batch)
1054
- this.ProcessGestures(root, args);
1424
+ Canvas.Guard("a gesture handler", root, () => this.ProcessGestures(root, args));
1425
+ const due = this.touchMenuDue;
1426
+ if (due) {
1427
+ this.touchMenuDue = undefined;
1428
+ this.RaiseTouchContextMenu(due.X, due.Y);
1429
+ }
1055
1430
  }
1056
1431
  /**
1057
1432
  * The control that consumed the current gesture keeps it until it lets go (DrawnUi Canvas.HadInput). Without this a
@@ -1137,6 +1512,9 @@ export class Canvas {
1137
1512
  this.focusedChild = value;
1138
1513
  if (previous && !previous.IsDisposed)
1139
1514
  previous.SetFrameworkFocus(false);
1515
+ // the keyboard is up: the newly focused field goes above it too
1516
+ if (this.KeyboardCovered > 0)
1517
+ setTimeout(() => this.ApplyKeyboard(), 50);
1140
1518
  }
1141
1519
  finally {
1142
1520
  this.reportingFocus = false;
@@ -1148,7 +1526,12 @@ export class Canvas {
1148
1526
  this.focusAtDown = this.focusedChild;
1149
1527
  this.tapNoFocus = false;
1150
1528
  }
1529
+ // a mouse drag selecting page text keeps its moves: no scroll under it scrolls (the pointer is captured, so the
1530
+ // moves keep coming once it leaves the canvas and the scroll follows it past its edge)
1531
+ if (this.PreviewTextSelectionGesture(args))
1532
+ return null;
1151
1533
  const consumed = this.RouteGestures(root, args);
1534
+ this.AfterTextSelectionDown(args, consumed);
1152
1535
  // a control that claimed the focus during this gesture (an editor on its press) keeps it; a press that closed the
1153
1536
  // popup windows moves nothing
1154
1537
  if (args.Type === "Tapped" && !this.tapNoFocus && this.focusedChild === this.focusAtDown)
@@ -1211,8 +1594,96 @@ export class Canvas {
1211
1594
  }
1212
1595
  }
1213
1596
  const consumed = root.ProcessGestures(args, info());
1214
- if (!wheel)
1597
+ // a mouse move never makes an owner (DrawnUi.Net 62608ca7): a focused field takes every hover, and as the owner it
1598
+ // would get the next release of a press that began elsewhere
1599
+ if (!wheel && args.Type !== "Pointer")
1215
1600
  this.gestureOwner = consumed && args.Type !== "Up" ? consumed : null;
1216
1601
  return consumed;
1217
1602
  }
1218
1603
  }
1604
+ const IsScroll = (c) => !!c && "ScrollTo" in c && "ViewportOffsetY" in c;
1605
+ /**
1606
+ * When a browser event happened, on the performance.now() clock (its timeStamp; now when the browser gives none or a time
1607
+ * from another clock): a slow frame holds events back, and gestures are dated by when they happened.
1608
+ */
1609
+ function EventTime(e) {
1610
+ const now = performance.now(), t = e.timeStamp;
1611
+ return typeof t === "number" && t > 0 && t <= now + 1 ? t : now;
1612
+ }
1613
+ const IsSelectableLabel = (c) => !!c && c.AccessibilityTextSelectable && "TextIndexAtCanvas" in c;
1614
+ /**
1615
+ * Where a canvas point falls in the labels' order: inside a drawn label, its text index there; before a label (above it,
1616
+ * or left of it on its line), that label's start; past them all, the end of the last drawn one.
1617
+ */
1618
+ function Locate(labels, x, y) {
1619
+ let last;
1620
+ for (const label of labels) {
1621
+ const r = label.GetAccessibilityPixelRect();
1622
+ if (r.Width <= 0 || r.Height <= 0)
1623
+ continue;
1624
+ if (x >= r.Left && x < r.Right && y >= r.Top && y < r.Bottom)
1625
+ return [label, label.TextIndexAtCanvas(x, y)];
1626
+ if (y < r.Top || (y <= r.Bottom && x < r.Left))
1627
+ return [label, 0];
1628
+ last = label;
1629
+ }
1630
+ return last ? [last, last.SelectableLength] : [undefined, 0];
1631
+ }
1632
+ /**
1633
+ * The labels in reading order, as they are seen (the tree order is not: a page in two columns lists the left column's
1634
+ * labels first, and a drag in the right column would then start at a label below it): by top, labels whose tops are within
1635
+ * half the smaller height forming one line, read left to right.
1636
+ */
1637
+ function ReadingOrder(labels) {
1638
+ const rects = new Map(labels.map((l) => [l, l.GetAccessibilityPixelRect()]));
1639
+ const sorted = [...labels].sort((a, b) => rects.get(a).Top - rects.get(b).Top || rects.get(a).Left - rects.get(b).Left);
1640
+ for (let start = 0, i = 1; i <= sorted.length; i++) {
1641
+ if (i < sorted.length) {
1642
+ const first = rects.get(sorted[start]), next = rects.get(sorted[i]);
1643
+ if (next.Top - first.Top < Math.min(first.Height, next.Height) / 2)
1644
+ continue;
1645
+ }
1646
+ if (i - start > 1) {
1647
+ const line = sorted.slice(start, i).sort((a, b) => rects.get(a).Left - rects.get(b).Left);
1648
+ for (let k = 0; k < line.length; k++)
1649
+ sorted[start + k] = line[k];
1650
+ }
1651
+ start = i;
1652
+ }
1653
+ return sorted;
1654
+ }
1655
+ function CollectSelectable(control, into) {
1656
+ if (!control.IsVisible || control.IsDisposed)
1657
+ return;
1658
+ if (IsSelectableLabel(control))
1659
+ into.push(control);
1660
+ const views = "Views" in control ? control.Views : undefined;
1661
+ const content = views ? undefined : control.Content;
1662
+ for (const child of views ?? (content ? [content] : []))
1663
+ CollectSelectable(child, into);
1664
+ }
1665
+ function ScrollOf(control) {
1666
+ for (let p = control?.Parent; p; p = p.Parent)
1667
+ if (IsScroll(p))
1668
+ return p;
1669
+ return undefined;
1670
+ }
1671
+ /** The innermost drawn scroll around a selectable label whose viewport holds the point. */
1672
+ function ScrollAt(labels, x, y) {
1673
+ for (const label of labels) {
1674
+ for (let p = label.Parent; p; p = p.Parent) {
1675
+ if (!IsScroll(p))
1676
+ continue;
1677
+ const r = p.GetAccessibilityPixelRect();
1678
+ if (x >= r.Left && x < r.Right && y >= r.Top && y < r.Bottom)
1679
+ return p;
1680
+ }
1681
+ }
1682
+ return undefined;
1683
+ }
1684
+ function IsInside(control, ancestor) {
1685
+ for (let p = control.Parent; p; p = p.Parent)
1686
+ if (p === ancestor)
1687
+ return true;
1688
+ return false;
1689
+ }