@gtkx/testing 2.0.0-beta.10 → 2.0.0-beta.11

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 (96) hide show
  1. package/README.md +8 -168
  2. package/dist/accessible-native.d.ts +1 -1
  3. package/dist/accessible-native.d.ts.map +1 -1
  4. package/dist/accessible-native.js +2 -2
  5. package/dist/accessible-native.js.map +1 -1
  6. package/dist/build-queries.d.ts +6 -7
  7. package/dist/build-queries.d.ts.map +1 -1
  8. package/dist/build-queries.js +24 -23
  9. package/dist/build-queries.js.map +1 -1
  10. package/dist/cleanup-registry.d.ts +2 -1
  11. package/dist/cleanup-registry.d.ts.map +1 -1
  12. package/dist/cleanup-registry.js +11 -4
  13. package/dist/cleanup-registry.js.map +1 -1
  14. package/dist/config.d.ts +3 -4
  15. package/dist/config.d.ts.map +1 -1
  16. package/dist/config.js.map +1 -1
  17. package/dist/matchers.d.ts +4 -6
  18. package/dist/matchers.d.ts.map +1 -1
  19. package/dist/matchers.js +2 -2
  20. package/dist/matchers.js.map +1 -1
  21. package/dist/pretty-widget.d.ts.map +1 -1
  22. package/dist/pretty-widget.js +13 -2
  23. package/dist/pretty-widget.js.map +1 -1
  24. package/dist/queries.d.ts.map +1 -1
  25. package/dist/queries.js +3 -2
  26. package/dist/queries.js.map +1 -1
  27. package/dist/render-hook.js +3 -3
  28. package/dist/render-hook.js.map +1 -1
  29. package/dist/render.d.ts +17 -17
  30. package/dist/render.d.ts.map +1 -1
  31. package/dist/render.js +62 -62
  32. package/dist/render.js.map +1 -1
  33. package/dist/role-naming.d.ts +2 -1
  34. package/dist/role-naming.d.ts.map +1 -1
  35. package/dist/role-naming.js +2 -1
  36. package/dist/role-naming.js.map +1 -1
  37. package/dist/screenshot.d.ts +10 -11
  38. package/dist/screenshot.d.ts.map +1 -1
  39. package/dist/screenshot.js +10 -11
  40. package/dist/screenshot.js.map +1 -1
  41. package/dist/suggestions.js +2 -2
  42. package/dist/suggestions.js.map +1 -1
  43. package/dist/traversal.d.ts +4 -3
  44. package/dist/traversal.d.ts.map +1 -1
  45. package/dist/traversal.js +11 -4
  46. package/dist/traversal.js.map +1 -1
  47. package/dist/types.d.ts +3 -5
  48. package/dist/types.d.ts.map +1 -1
  49. package/dist/types.js.map +1 -1
  50. package/dist/user-event/controller.js +2 -2
  51. package/dist/user-event/controller.js.map +1 -1
  52. package/dist/user-event/gesture.d.ts +1 -1
  53. package/dist/user-event/gesture.d.ts.map +1 -1
  54. package/dist/user-event/gesture.js +103 -29
  55. package/dist/user-event/gesture.js.map +1 -1
  56. package/dist/user-event/keyboard.d.ts.map +1 -1
  57. package/dist/user-event/keyboard.js +3 -2
  58. package/dist/user-event/keyboard.js.map +1 -1
  59. package/dist/user-event/list-row-click.js +1 -1
  60. package/dist/user-event/list-row-click.js.map +1 -1
  61. package/dist/user-event/selection.d.ts.map +1 -1
  62. package/dist/user-event/selection.js +1 -6
  63. package/dist/user-event/selection.js.map +1 -1
  64. package/dist/user-event/text.d.ts.map +1 -1
  65. package/dist/user-event/text.js +31 -27
  66. package/dist/user-event/text.js.map +1 -1
  67. package/dist/wait-for.d.ts.map +1 -1
  68. package/dist/wait-for.js +28 -21
  69. package/dist/wait-for.js.map +1 -1
  70. package/dist/widget-accessible-properties.d.ts +1 -1
  71. package/dist/widget-accessible-properties.d.ts.map +1 -1
  72. package/dist/widget-accessible-properties.js +61 -24
  73. package/dist/widget-accessible-properties.js.map +1 -1
  74. package/package.json +11 -11
  75. package/src/accessible-native.ts +3 -3
  76. package/src/build-queries.ts +26 -25
  77. package/src/cleanup-registry.ts +11 -5
  78. package/src/config.ts +3 -4
  79. package/src/matchers.ts +6 -8
  80. package/src/pretty-widget.ts +17 -2
  81. package/src/queries.ts +5 -2
  82. package/src/render-hook.tsx +3 -3
  83. package/src/render.tsx +66 -79
  84. package/src/role-naming.ts +2 -1
  85. package/src/screenshot.ts +10 -11
  86. package/src/suggestions.ts +2 -2
  87. package/src/traversal.ts +16 -6
  88. package/src/types.ts +3 -5
  89. package/src/user-event/controller.ts +2 -2
  90. package/src/user-event/gesture.ts +142 -33
  91. package/src/user-event/keyboard.ts +3 -2
  92. package/src/user-event/list-row-click.ts +1 -1
  93. package/src/user-event/selection.ts +1 -8
  94. package/src/user-event/text.ts +36 -32
  95. package/src/wait-for.ts +37 -30
  96. package/src/widget-accessible-properties.ts +76 -30
package/src/render.tsx CHANGED
@@ -1,17 +1,12 @@
1
- import type { CaughtErrorInfo, RootElement } from "@gtkx/react";
1
+ import type { CaughtErrorInfo, Root, RootElement } from "@gtkx/react";
2
2
  import * as Gtk from "@gtkx/gi/gtk";
3
- import {
4
- createReconcilerRoot,
5
- isRootElement,
6
- type ReconcilerRoot,
7
- setReconcilerErrorHandler,
8
- settleAccessible,
9
- } from "@gtkx/react/internal";
3
+ import { createRoot } from "@gtkx/react";
4
+ import { isRootElement, settleAccessible } from "@gtkx/react/internal";
10
5
  import { type ErrorInfo, type ReactNode, StrictMode } from "react";
11
6
  import type { RenderResult } from "./bound-queries.js";
12
7
  import type { QueryMap, RenderOptions, ScreenshotOptions } from "./types.js";
13
8
  import { runInAct, runWithActEnvironment } from "./act.js";
14
- import { addToCleanupQueue, runCleanup } from "./cleanup-registry.js";
9
+ import { addToCleanupQueue, runCleanup, runCleanupCallbacks } from "./cleanup-registry.js";
15
10
  import { getConfig } from "./config.js";
16
11
  import { scheduleWhenWindowReady } from "./frame-sync.js";
17
12
  import { createHarnessWindow, presentHarnessWindow } from "./harness-window.js";
@@ -25,12 +20,10 @@ import { requireWidget } from "./widget-target.js";
25
20
  import { findPresentedWindowFailure, findRenderedWindowFailure, mappedToplevels } from "./window-state.js";
26
21
  import { within } from "./within.js";
27
22
 
28
- /** A mounted render tracked so cleanup can unmount it. */
29
23
  type ActiveRender = {
30
- /** Root that rerenders drive and that cleanup tears the tree down through. */
31
- root: ReconcilerRoot;
32
- /** Harness window created for the render, null when it renders into a container the caller supplied. */
24
+ root: Root;
33
25
  window: Gtk.Window | null;
26
+ errors: RenderErrorState;
34
27
  };
35
28
 
36
29
  type ResolvedContainer = {
@@ -38,15 +31,13 @@ type ResolvedContainer = {
38
31
  window: Gtk.Window | null;
39
32
  };
40
33
 
41
- type ReconcilerErrorState = {
34
+ type RenderErrorState = {
42
35
  lastError: Error | null;
43
- isHandlerInstalled: boolean;
44
36
  };
45
37
 
46
38
  type WindowFailureReporter = (window: Gtk.Window) => string | null;
47
39
  type SettleAction = "render" | "rerender";
48
40
 
49
- const reconcilerErrors: ReconcilerErrorState = { lastError: null, isHandlerInstalled: false };
50
41
  const activeRenders: Set<ActiveRender> = new Set();
51
42
 
52
43
  const settleWindow = async (
@@ -75,15 +66,18 @@ const settleWindow = async (
75
66
  }
76
67
  };
77
68
 
78
- const update = async (element: ReactNode, root: ReconcilerRoot): Promise<void> => {
79
- await runInAct(() => {
80
- root.update(element);
81
- });
82
-
83
- if (reconcilerErrors.lastError) {
84
- const captured = reconcilerErrors.lastError;
85
- reconcilerErrors.lastError = null;
86
- throw captured;
69
+ const flushRender = async (active: ActiveRender, action: () => void): Promise<void> => {
70
+ try {
71
+ await runInAct(async () => {
72
+ action();
73
+ await Promise.resolve();
74
+ });
75
+
76
+ if (active.errors.lastError !== null) {
77
+ throw active.errors.lastError;
78
+ }
79
+ } finally {
80
+ active.errors.lastError = null;
87
81
  }
88
82
  };
89
83
 
@@ -92,29 +86,15 @@ const disposeActiveRender = async (active: ActiveRender): Promise<void> => {
92
86
  return;
93
87
  }
94
88
 
95
- await active.root.unmount(async (root) => {
96
- await update(null, root);
89
+ try {
90
+ await flushRender(active, active.root.unmount);
91
+ } finally {
97
92
  active.window?.destroy();
98
- });
99
- };
100
-
101
- const disposeAllActiveRenders = async (): Promise<void> => {
102
- for (const active of activeRenders) {
103
- await disposeActiveRender(active);
104
93
  }
105
94
  };
106
95
 
107
- const handleError = (error: unknown): void => {
108
- reconcilerErrors.lastError = error instanceof Error ? error : new Error(String(error));
109
- };
110
-
111
- const installErrorHandler = (): void => {
112
- if (reconcilerErrors.isHandlerInstalled) {
113
- return;
114
- }
115
-
116
- setReconcilerErrorHandler(handleError);
117
- reconcilerErrors.isHandlerInstalled = true;
96
+ const disposeAllActiveRenders = async (): Promise<void> => {
97
+ await runCleanupCallbacks(activeRenders.values().map((active) => () => disposeActiveRender(active)));
118
98
  };
119
99
 
120
100
  const resolveContainer = (container: RenderOptions["container"]): ResolvedContainer => {
@@ -191,16 +171,22 @@ const settleRender = async (
191
171
  await settleWindow(settleTarget(resolved, container), findFailure, action);
192
172
  };
193
173
 
194
- const renderErrorHandlers = <Q extends QueryMap>(options: RenderOptions<Q> | undefined) => ({
195
- onUncaughtError: handleError,
196
- onCaughtError: (error: unknown, errorInfo: CaughtErrorInfo): void => {
197
- handleError(error);
198
- options?.onCaughtError?.(error, errorInfo);
199
- },
200
- onRecoverableError: (error: unknown, errorInfo: ErrorInfo): void => {
201
- options?.onRecoverableError?.(error, errorInfo);
202
- },
203
- });
174
+ const renderErrorHandlers = <Q extends QueryMap>(errors: RenderErrorState, options: RenderOptions<Q> | undefined) => {
175
+ const handleError = (error: unknown): void => {
176
+ errors.lastError = error instanceof Error ? error : new Error(String(error));
177
+ };
178
+
179
+ return {
180
+ onUncaughtError: handleError,
181
+ onCaughtError: (error: unknown, errorInfo: CaughtErrorInfo): void => {
182
+ handleError(error);
183
+ options?.onCaughtError?.(error, errorInfo);
184
+ },
185
+ onRecoverableError: (error: unknown, errorInfo: ErrorInfo): void => {
186
+ options?.onRecoverableError?.(error, errorInfo);
187
+ },
188
+ };
189
+ };
204
190
 
205
191
  const applyEnableAnimations = (areAnimationsEnabled: boolean): void => {
206
192
  const settings = Gtk.Settings.getDefault();
@@ -211,41 +197,38 @@ const applyEnableAnimations = (areAnimationsEnabled: boolean): void => {
211
197
  };
212
198
 
213
199
  /**
214
- * Renders a React element into a GTK4 widget tree and returns queries
215
- * scoped to it along with controls for rerendering and unmounting. When no
216
- * container is supplied, a harness window is created and presented, and the editable it hands the
217
- * focus to keeps its text unselected, with its caret at the end. The returned promise settles once
218
- * the window the tree is shown in has been laid out and activation has arrived, so platform state
219
- * such as focus is already readable when it resolves. A presented harness window is waited on until
220
- * it is itself active; a window the caller or the tree owns is waited on until the application holds
221
- * activation, since only a present can claim it. Rendering into a container that is not shown waits
222
- * for nothing, and a window that never becomes readable within `windowActivationTimeout` throws an
223
- * error naming the condition that failed rather than resolving with unreadable platform state. A
224
- * tree mounted into a container that sits outside every toplevel, or inside a window that is not
225
- * visible, is out of reach of a pointer and a keyboard, so every `userEvent` helper aimed at it
226
- * rejects after `actionabilityTimeout` naming that condition, and `fireEvent` drives it instead.
200
+ * Renders React into native widgets and returns queries, debug helpers, and lifecycle controls.
227
201
  *
228
- * @param element The React element to render.
229
- * @param options Optional container, wrapper, custom queries, and other render settings.
230
- * @returns A render result with bound queries, debug helpers, and lifecycle controls.
231
- * @throws When the window the tree is shown in is not laid out and activated in time.
202
+ * @remarks
203
+ * Without a container, creates and presents a harness window. Its initially focused editable
204
+ * keeps its text unselected, with the caret at the end.
205
+ *
206
+ * Waits for layout and activation before resolving, so focus and other platform state can be
207
+ * read immediately. A new harness waits for its own activation; a caller-owned or rendered
208
+ * window waits for application activation, since only presentation can claim it. A container
209
+ * that is not shown requires no activation wait.
210
+ *
211
+ * Widgets outside all toplevels or inside a hidden window cannot receive pointer or keyboard
212
+ * input. `userEvent` rejects after `actionabilityTimeout`; use `fireEvent` to drive them directly.
213
+ *
214
+ * @param element React element to render.
215
+ * @param options Container, wrapper, custom queries, and render settings.
216
+ * @returns Bound queries, debug helpers, and rerender/unmount controls.
217
+ * @throws If a shown window is not laid out and activated within `windowActivationTimeout`.
232
218
  */
233
219
  const render = async <Q extends QueryMap = Record<never, never>>(
234
220
  element: ReactNode,
235
221
  options?: RenderOptions<Q>,
236
222
  ): Promise<RenderResult<Q>> => {
237
- installErrorHandler();
238
223
  applyEnableAnimations(options?.areAnimationsEnabled === true);
239
224
  const baseElement: Container = options?.baseElement ?? TOPLEVELS;
240
225
  const Wrapper = options?.wrapper;
241
226
  const resolved = resolveContainer(options?.container);
242
227
 
243
- const root = createReconcilerRoot({
244
- containerInfo: resolved.containerInfo,
245
- ...renderErrorHandlers(options),
246
- });
228
+ const errors: RenderErrorState = { lastError: null };
229
+ const root = createRoot(resolved.containerInfo, renderErrorHandlers(errors, options));
247
230
 
248
- const active: ActiveRender = { root, window: resolved.window };
231
+ const active: ActiveRender = { root, window: resolved.window, errors };
249
232
  activeRenders.add(active);
250
233
  addToCleanupQueue(disposeAllActiveRenders);
251
234
  addToCleanupQueue(clearScreen);
@@ -257,7 +240,9 @@ const render = async <Q extends QueryMap = Record<never, never>>(
257
240
  return options?.isReactStrictMode ? <StrictMode>{wrapped}</StrictMode> : wrapped;
258
241
  };
259
242
 
260
- await update(wrap(element), root);
243
+ await flushRender(active, () => {
244
+ root.render(wrap(element));
245
+ });
261
246
  presentHarnessWindow(resolved.window);
262
247
  await settleRender(resolved, options?.container, "render");
263
248
  const container = resolveResultContainer(resolved, options?.container, baseElement);
@@ -270,7 +255,9 @@ const render = async <Q extends QueryMap = Record<never, never>>(
270
255
  await disposeActiveRender(active);
271
256
  },
272
257
  rerender: async (newElement: ReactNode) => {
273
- await update(wrap(newElement), root);
258
+ await flushRender(active, () => {
259
+ root.render(wrap(newElement));
260
+ });
274
261
  await settleRender(resolved, options?.container, "rerender");
275
262
  },
276
263
  debug: (element: Container | Container[] = baseElement, debugOptions?: PrettyWidgetOptions) => {
@@ -95,5 +95,6 @@ const NAMING: Partial<Record<Gtk.AccessibleRole, number>> = {
95
95
  const namingFor = (role: Gtk.AccessibleRole): number => NAMING[role] ?? 0;
96
96
  const isNameProhibited = (role: Gtk.AccessibleRole): boolean => (namingFor(role) & PROHIBITED) !== 0;
97
97
  const isNameFromAuthor = (role: Gtk.AccessibleRole): boolean => (namingFor(role) & FROM_AUTHOR) !== 0;
98
+ const isNameFromContent = (role: Gtk.AccessibleRole): boolean => (namingFor(role) & FROM_CONTENT) !== 0;
98
99
 
99
- export { isNameFromAuthor, isNameProhibited };
100
+ export { isNameFromAuthor, isNameFromContent, isNameProhibited };
package/src/screenshot.ts CHANGED
@@ -330,18 +330,17 @@ const captureUntilPaintable = (
330
330
  };
331
331
 
332
332
  /**
333
- * Captures a PNG snapshot of a widget, retrying until it has a paintable size,
334
- * and writes the image to `options.path` when one is given, creating any
335
- * missing parent directories. Popovers open inside the widget render on their
336
- * own surfaces, so they are composited into the image at their on-screen
337
- * positions. A display that never presents a frame leaves GTK without a cached
338
- * render node, so the widget's contents are then snapshotted directly; when
339
- * even that yields nothing, the failure names the display instead of blaming
340
- * the widget.
333
+ * Captures a widget as PNG, retrying until it has a paintable size. Writes to `options.path`
334
+ * when supplied, creating missing parent directories.
341
335
  *
342
- * @param widget The widget to render to an image.
343
- * @param options Optional scale, timeout, retry interval, and output path.
344
- * @returns The base64-encoded PNG data along with its mime type and dimensions.
336
+ * @remarks
337
+ * Open popovers are composited at their on-screen positions. If the display has not presented
338
+ * a frame, captures widget contents directly instead of using GTK's cached render node.
339
+ * If that also fails, the error identifies the display's presentation failure.
340
+ *
341
+ * @param target Widget to capture.
342
+ * @param options Scale, timeout, retry interval, and output path.
343
+ * @returns Base64-encoded PNG data, MIME type, and dimensions.
345
344
  */
346
345
  const screenshot = async (target: Gtk.Accessible, options?: ScreenshotOptions): Promise<ScreenshotResult> => {
347
346
  const widget = requireWidget(target);
@@ -56,7 +56,7 @@ const roleSuggestion = (widget: Gtk.Widget, variant: Variant): Suggestion | unde
56
56
  return makeSuggestion("Role", variant, roleText);
57
57
  }
58
58
 
59
- return makeSuggestion("Role", variant, `${roleText}, { name: '${name}' }`);
59
+ return makeSuggestion("Role", variant, `${roleText}, { name: ${JSON.stringify(name)} }`);
60
60
  };
61
61
 
62
62
  const textSuggestion = (queryName: Method, variant: Variant, value: string | null): Suggestion | undefined => {
@@ -64,7 +64,7 @@ const textSuggestion = (queryName: Method, variant: Variant, value: string | nul
64
64
  return undefined;
65
65
  }
66
66
 
67
- return makeSuggestion(queryName, variant, `'${value}'`);
67
+ return makeSuggestion(queryName, variant, JSON.stringify(value));
68
68
  };
69
69
 
70
70
  /**
package/src/traversal.ts CHANGED
@@ -13,6 +13,7 @@ type QueryContainer = Gtk.Accessible | Gtk.EventController | Gtk.LayoutManager |
13
13
  */
14
14
  type Container = QueryContainer | Gtk.Application | typeof TOPLEVELS;
15
15
  type WidgetClass<T extends object> = abstract new (...args: never[]) => T;
16
+ type ChildContainer = Pick<Gtk.Widget, "getFirstChild">;
16
17
 
17
18
  /** Container sentinel that widens a query to every toplevel window currently open. */
18
19
  const TOPLEVELS: unique symbol = Symbol("gtkx.toplevels");
@@ -52,7 +53,7 @@ const traverseWidgetTree = function* (
52
53
  }
53
54
  };
54
55
 
55
- const children = function* (widget: Gtk.Widget): Generator<Gtk.Widget> {
56
+ const children = function* (widget: ChildContainer): Generator<Gtk.Widget> {
56
57
  let child = widget.getFirstChild();
57
58
 
58
59
  while (child) {
@@ -98,11 +99,13 @@ const mappedWidgets = function* (widget: Gtk.Widget, isParentMapped: boolean): G
98
99
  }
99
100
  };
100
101
 
101
- const relationCandidates = (widget: Gtk.Widget): Iterable<Gtk.Accessible>[] => {
102
+ const relationCandidates = function* (widget: Gtk.Widget): Generator<Iterable<Gtk.Accessible>> {
103
+ yield widget.listMnemonicLabels();
104
+ yield descendants(widget);
102
105
  const root = widget.getRoot();
103
- const tree: Iterable<Gtk.Accessible> = root instanceof Gtk.Widget ? traverseWidgetTree(root, isAnyWidget) : [];
104
-
105
- return [widget.listMnemonicLabels(), descendants(widget), tree];
106
+ if (root instanceof Gtk.Widget) {
107
+ yield traverseWidgetTree(root, isAnyWidget);
108
+ }
106
109
  };
107
110
 
108
111
  const resolveRoot = (container: QueryContainer): Gtk.Widget | null => {
@@ -126,12 +129,18 @@ const resolveRoot = (container: QueryContainer): Gtk.Widget | null => {
126
129
  };
127
130
 
128
131
  const roots = function* (container: Container): Generator<Gtk.Widget> {
129
- if (container === TOPLEVELS || isApplication(container)) {
132
+ if (container === TOPLEVELS) {
130
133
  yield* Gtk.Window.listToplevels();
131
134
 
132
135
  return;
133
136
  }
134
137
 
138
+ if (isApplication(container)) {
139
+ yield* container.getWindows();
140
+
141
+ return;
142
+ }
143
+
135
144
  const root = resolveRoot(container);
136
145
 
137
146
  if (root) {
@@ -168,5 +177,6 @@ export {
168
177
  relationCandidates,
169
178
  roots,
170
179
  traverse,
180
+ type ChildContainer,
171
181
  type Container,
172
182
  };
package/src/types.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import type * as Gtk from "@gtkx/gi/gtk";
2
2
  import type { CaughtErrorInfo, RootElement } from "@gtkx/react";
3
- import type { ComponentType, ErrorInfo, ReactNode } from "react";
3
+ import type { ComponentType, ErrorInfo, PropsWithChildren } from "react";
4
4
  import type { PrettyWidgetOptions } from "./pretty-widget.js";
5
5
  import type { Container } from "./traversal.js";
6
6
 
@@ -100,9 +100,7 @@ type ByRoleOptions<T extends Gtk.Accessible = Gtk.Accessible> = MatcherOptions<T
100
100
  };
101
101
 
102
102
  /** A React component that wraps rendered content, receiving it as its children. */
103
- type WrapperComponent = ComponentType<{
104
- children: ReactNode;
105
- }>;
103
+ type WrapperComponent = ComponentType<Required<PropsWithChildren>>;
106
104
 
107
105
  /** A custom query, taking the scope to search as its first argument and its matcher arguments after it. */
108
106
  type Query = (container: Container, ...args: never[]) => unknown;
@@ -259,7 +257,7 @@ type RenderHookResult<Result, Props> = {
259
257
  current: Result;
260
258
  };
261
259
  /** Re-invokes the hook, keeping the previous props when none are given. */
262
- rerender: (newProps?: Props) => Promise<void>;
260
+ rerender: (...args: [] | [newProps: Props]) => Promise<void>;
263
261
  /** Unmounts the component that calls the hook. */
264
262
  unmount: () => Promise<void>;
265
263
  };
@@ -74,9 +74,9 @@ const getController = <T extends Gtk.EventController>(
74
74
  widget: Gtk.Accessible,
75
75
  controllerType: ControllerConstructor<T>,
76
76
  ): T => {
77
- const [controller] = getAllControllers(widget, controllerType);
77
+ const controller = queryController(widget, controllerType);
78
78
 
79
- if (controller === undefined) {
79
+ if (controller === null) {
80
80
  throw new Error(`No ${controllerType.name} controller is attached to the widget`);
81
81
  }
82
82
 
@@ -1,5 +1,9 @@
1
+ import * as Gdk from "@gtkx/gi/gdk";
1
2
  import * as GObject from "@gtkx/gi/gobject";
2
3
  import * as Gtk from "@gtkx/gi/gtk";
4
+ import { t, toValueHandle, wrapHandle } from "@gtkx/runtime";
5
+ import { toValue } from "@gtkx/runtime/internal";
6
+ import { runInAct } from "../act.js";
3
7
  import { getAllControllers } from "./controller.js";
4
8
  import { dispatchOnControllers, dispatchOnOrCreateControllers } from "./dispatch.js";
5
9
  import { wrapEvent } from "./event-wrapper.js";
@@ -45,6 +49,10 @@ type DragInstancePatch = {
45
49
  getOffset?: Gtk.GestureDrag["getOffset"] | undefined;
46
50
  };
47
51
 
52
+ type ZoomInstancePatch = {
53
+ getBoundingBoxCenter?: Gtk.GestureZoom["getBoundingBoxCenter"] | undefined;
54
+ };
55
+
48
56
  type SavedDragState = {
49
57
  instance: DragInstancePatch;
50
58
  hasOwnStartPoint: boolean;
@@ -53,34 +61,14 @@ type SavedDragState = {
53
61
  previousOffset: DragInstancePatch["getOffset"];
54
62
  };
55
63
 
56
- const initValue = (gtype: GObject.Type, populate: (value: GObject.Value) => void): GObject.Value => {
57
- const value = new GObject.Value();
58
- value.init(gtype);
59
- populate(value);
60
-
61
- return value;
62
- };
63
-
64
64
  const buildDropValue = (content: DropContent): GObject.Value => {
65
65
  if (content instanceof GObject.Value) {
66
66
  return content;
67
67
  }
68
68
 
69
- if (typeof content === "string") {
70
- return initValue(GObject.TYPE_STRING, (v) => {
71
- v.setString(content);
72
- });
73
- }
74
-
75
- if (typeof content === "boolean") {
76
- return initValue(GObject.TYPE_BOOLEAN, (v) => {
77
- v.setBoolean(content);
78
- });
79
- }
69
+ const handle = typeof content === "number" ? toValue(t.float64, content) : toValueHandle(content);
80
70
 
81
- return initValue(GObject.TYPE_DOUBLE, (v) => {
82
- v.setDouble(content);
83
- });
71
+ return wrapHandle(handle, GObject.Value);
84
72
  };
85
73
 
86
74
  /** Enters a widget. */
@@ -105,7 +93,20 @@ const rotate = (widget: Gtk.Widget, angle: number, deltaAngle: number = angle):
105
93
  /** Zooms a widget's gestures. */
106
94
  const zoom = (widget: Gtk.Widget, scale: number): Promise<void> =>
107
95
  dispatchOnControllers(widget, Gtk.GestureZoom, (controller) => {
108
- controller.emit("scale-changed", scale);
96
+ const instance: ZoomInstancePatch = controller;
97
+ const hasOwnCenter = Object.hasOwn(instance, "getBoundingBoxCenter");
98
+ const previousCenter = instance.getBoundingBoxCenter;
99
+ instance.getBoundingBoxCenter = () => [true, widget.getWidth() / 2, widget.getHeight() / 2];
100
+
101
+ try {
102
+ controller.emit("scale-changed", scale);
103
+ } finally {
104
+ if (hasOwnCenter) {
105
+ instance.getBoundingBoxCenter = previousCenter;
106
+ } else {
107
+ delete instance.getBoundingBoxCenter;
108
+ }
109
+ }
109
110
  });
110
111
 
111
112
  /** Swipes a widget's gestures. */
@@ -219,34 +220,142 @@ const drag = async (widget: Gtk.Widget, dx: number, dy: number, options: DragOpt
219
220
  });
220
221
  };
221
222
 
222
- const emitDrop = (target: Gtk.Widget, content: DropContent, options: DropOptions): void => {
223
+ const didEmitAcceptedDrop = (target: Gtk.Widget, content: DropContent, options: DropOptions): boolean => {
223
224
  const dropTargets = getAllControllers(target, Gtk.DropTarget);
225
+ let isAccepted = false;
224
226
 
225
227
  for (const dropTarget of dropTargets) {
226
- dropTarget.emit("drop", buildDropValue(content), options.x ?? 0, options.y ?? 0);
228
+ isAccepted = dropTarget.emit("drop", buildDropValue(content), options.x ?? 0, options.y ?? 0) || isAccepted;
229
+ }
230
+
231
+ return isAccepted;
232
+ };
233
+
234
+ type ActiveDrag = {
235
+ source: Gtk.DragSource;
236
+ drag: Gdk.Drag;
237
+ };
238
+
239
+ type DragEnvironment = {
240
+ surface: Gdk.Surface;
241
+ device: Gdk.Device;
242
+ fallback: Gdk.ContentProvider | undefined;
243
+ };
244
+
245
+ const resolveDragEnvironment = (widget: Gtk.Widget, content: DropContent | undefined): DragEnvironment => {
246
+ const surface = widget.getNative()?.getSurface() ?? null;
247
+ const device = widget.getDisplay().getDefaultSeat()?.getPointer() ?? null;
248
+
249
+ if (surface === null || device === null) {
250
+ throw new Error("The drag source has no surface or pointer device");
251
+ }
252
+
253
+ return {
254
+ surface,
255
+ device,
256
+ fallback: content === undefined ? undefined : Gdk.ContentProvider.newForValue(buildDropValue(content)),
257
+ };
258
+ };
259
+
260
+ const beginDragSource = (source: Gtk.DragSource, environment: DragEnvironment): ActiveDrag => {
261
+ const provider = source.emit("prepare", 0, 0) ?? source.getContent() ?? environment.fallback;
262
+
263
+ if (provider === undefined) {
264
+ throw new Error("The drag source did not provide content");
265
+ }
266
+
267
+ const drag = Gdk.Drag.begin(environment.surface, environment.device, provider, source.getActions(), 0, 0);
268
+
269
+ if (drag === null) {
270
+ throw new Error("The display refused to begin the drag");
227
271
  }
272
+
273
+ return { source, drag };
274
+ };
275
+
276
+ const endDragSources = (activeDrags: ActiveDrag[], isAccepted: boolean): void => {
277
+ for (const { source, drag } of activeDrags) {
278
+ drag.dropDone(isAccepted);
279
+ source.emit("drag-end", drag, false);
280
+ }
281
+ };
282
+
283
+ const beginDragSources = (
284
+ widget: Gtk.Widget,
285
+ sources: Gtk.DragSource[],
286
+ content: DropContent | undefined,
287
+ ): ActiveDrag[] => {
288
+ const environment = resolveDragEnvironment(widget, content);
289
+ const activeDrags: ActiveDrag[] = [];
290
+
291
+ try {
292
+ for (const source of sources) {
293
+ const active = beginDragSource(source, environment);
294
+ activeDrags.push(active);
295
+ source.emit("drag-begin", active.drag);
296
+ }
297
+ } catch (error) {
298
+ endDragSources(activeDrags, false);
299
+ throw error;
300
+ }
301
+
302
+ return activeDrags;
303
+ };
304
+
305
+ const didEmitProviderValue = (provider: Gdk.ContentProvider, target: Gtk.DropTarget, options: DropOptions): boolean => {
306
+ const formats = target.getFormats();
307
+ const type = formats === null ? GObject.TYPE_INVALID : formats.matchGtype(provider.refFormats());
308
+
309
+ if (type === GObject.TYPE_INVALID) {
310
+ return false;
311
+ }
312
+
313
+ const value = new GObject.Value();
314
+ value.init(type);
315
+ provider.getValue(value);
316
+
317
+ return target.emit("drop", value, options.x ?? 0, options.y ?? 0);
318
+ };
319
+
320
+ const didEmitProviderDrop = (target: Gtk.Widget, drags: ActiveDrag[], options: DropOptions): boolean => {
321
+ const targets = getAllControllers(target, Gtk.DropTarget);
322
+
323
+ return drags.some(({ drag }) =>
324
+ targets.some((dropTarget) => didEmitProviderValue(drag.getContent(), dropTarget, options)),
325
+ );
228
326
  };
229
327
 
230
328
  /** Drops content on a widget. */
231
329
  const drop = (widget: Gtk.Widget, content: DropContent, options: DropOptions = {}): Promise<void> =>
232
330
  wrapEvent(widget, () => {
233
- emitDrop(widget, content, options);
331
+ didEmitAcceptedDrop(widget, content, options);
234
332
  });
235
333
 
236
334
  /** Drags content from one widget and drops it on another. */
237
335
  const dragAndDrop = async (
238
336
  source: Gtk.Widget,
239
337
  target: Gtk.Widget,
240
- content: DropContent,
338
+ content?: DropContent,
241
339
  options: DropOptions = {},
242
340
  ): Promise<void> => {
243
- await wrapEvent(source, () => {
244
- getAllControllers(source, Gtk.DragSource);
245
- });
341
+ let activeDrags: ActiveDrag[] = [];
342
+ let isAccepted = false;
246
343
 
247
- await wrapEvent(target, () => {
248
- emitDrop(target, content, options);
249
- });
344
+ try {
345
+ await wrapEvent(source, () => {
346
+ activeDrags = beginDragSources(source, getAllControllers(source, Gtk.DragSource), content);
347
+ });
348
+
349
+ await wrapEvent(target, () => {
350
+ isAccepted = content === undefined
351
+ ? didEmitProviderDrop(target, activeDrags, options)
352
+ : didEmitAcceptedDrop(target, content, options);
353
+ });
354
+ } finally {
355
+ await runInAct(() => {
356
+ endDragSources(activeDrags, isAccepted);
357
+ });
358
+ }
250
359
  };
251
360
 
252
361
  export {
@@ -100,14 +100,15 @@ const parseKeyToken = (token: string): { keyval: number; isPress: boolean; isRel
100
100
  };
101
101
 
102
102
  const parseCharAt = (input: string, i: number): ParseStep => {
103
- const keyval = input.codePointAt(i) ?? 0;
103
+ const character = input.codePointAt(i) ?? 0;
104
+ const keyval = Gdk.unicodeToKeyval(character);
104
105
 
105
106
  return {
106
107
  actions: [
107
108
  { keyval, isPress: true },
108
109
  { keyval, isPress: false },
109
110
  ],
110
- next: i + 1,
111
+ next: i + String.fromCodePoint(character).length,
111
112
  };
112
113
  };
113
114
 
@@ -20,7 +20,7 @@ const viewFor = (row: Gtk.Widget): Gtk.Widget | null => {
20
20
  const isViewSingleClickActivating = (row: Gtk.Widget): boolean => {
21
21
  const view = viewFor(row);
22
22
 
23
- return view === null ? false : callBooleanGetter(view, SINGLE_CLICK_ACTIVATE_GETTER) ?? false;
23
+ return view !== null && (callBooleanGetter(view, SINGLE_CLICK_ACTIVATE_GETTER) ?? false);
24
24
  };
25
25
 
26
26
  const selectRow = (row: Gtk.Widget): void => {