Skip to content

packages/core/src/features/viz/lib/hover-data.tsx

Read as Markdown

This is the source snapshot used to build these API details. View this revision on GitHub.

Back to reference

1 import type { PibblNode } from "@pibbl/core";
2 import { withHooksForbidden } from "@pibbl/core/internal";
3 import type { HoverDataProps, HoverQueryContext } from "./hover-types.js";
4 import type { ResolvedContinuousScale, ScaleId } from "./types.js";
5 import { readScale } from "./scale-context.js";
6 /**
7  * Evaluates an ordinary synchronous query under the current scale scope.
8  *
9  * @param props - Hover query and child renderer receiving its result. See {@link HoverDataProps}.
10  * @returns Content rendered from the current hover query result. See {@link PibblNode}.
11  *
12  * @see {@link HoverDataProps}
13  * @see {@link PibblNode}
14  */
15 export function HoverData<T>({
16   query,
17   children,
18 }: HoverDataProps<T>): PibblNode {
19   if (typeof query !== "function" || typeof children !== "function")
20     throw new TypeError("HoverData requires query and children functions.");
21   const snapshots = new Map<ScaleId, ResolvedContinuousScale>();
22   let active = true;
23   const context: HoverQueryContext = {
24     scale(id) {
25       if (!active)
26         throw new Error(
27           "HoverData query context cannot be retained outside its invocation.",
28         );
29       let snapshot = snapshots.get(id);
30       if (!snapshot) {
31         const value = readScale(id, "HoverData");
32         if (!value) throw new TypeError("HoverData requires a scale ID.");
33         const resolved = value.get();
34         if (
35           resolved.type === "band" ||
36           resolved.type === "point" ||
37           resolved.type === "trading-time"
38         )
39           throw new TypeError(
40             "HoverData numeric queries require continuous scales.",
41           );
42         snapshot = resolved;
43         snapshots.set(id, snapshot);
44       }
45       return snapshot;
46     },
47   };
48   let result: T | undefined;
49   try {
50     result = withHooksForbidden(
51       "Pibbl hooks cannot be called inside a HoverData query.",
52       () => query(context),
53     );
54     if (
55       result != null &&
56       (typeof result === "object" || typeof result === "function") &&
57       typeof (result as { then?: unknown }).then === "function"
58     )
59       throw new TypeError(
60         "HoverData query must be synchronous; promises are unsupported.",
61       );
62   } finally {
63     active = false;
64   }
65   return withHooksForbidden(
66     "Pibbl hooks cannot be called inside a HoverData render callback; return a component instead.",
67     () => children(result),
68   );
69 }
70 

Documentation built with @pibbl/core 0.0.2, revision a1dcf8e. ALPHA — NOT FOR PRODUCTION USE.