Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

2.8 KB
Raw Blame
import { useRef, useState } from "react";

import {
  REACT_PROBES,
  ReactProbeHost,
  useProbeCustomElement,
} from "./ReactProbes";
import { createProbes } from "./probes";
import type { ReactMode } from "./types";
import { describeError, getEnv } from "./utils";

// A data app that, from inside the sandbox, probes each way a bundle might reach
// across the isolation boundary and reports the first sign of the outcome:
// `isolated:` (held) or `reached:` (crossed). The spec asserts every probe
// reports `isolated:`.
export function ProbesPage() {
  const env = getEnv();
  const [result, setResult] = useState("pending");
  const [probeId, setProbeId] = useState<string | null>(null);
  const [reactMode, setReactMode] = useState<ReactMode | null>(null);
  const firedRef = useRef(false);
  const timerRef = useRef<number | undefined>(undefined);
  const currentProbeRef = useRef<string | null>(null);

  useProbeCustomElement(setResult);

  // If a probe never reports, `no-probe-observed` fails the spec (the probe
  // never fired) rather than hanging.
  const arm = (id: string) => {
    currentProbeRef.current = id;
    window.clearTimeout(timerRef.current);
    setProbeId(id);
    setResult("pending");
    timerRef.current = window.setTimeout(
      () => setResult((r) => (r === "pending" ? "no-probe-observed" : r)),
      20000,
    );
  };

  const reportFor = (id: string) => (value: string) => {
    if (currentProbeRef.current === id) {
      setResult(value);
    }
  };

  const fire = (id: string) => {
    arm(id);

    try {
      createProbes(env, reportFor(id))
        .find((p) => p.id === id)
        ?.run();
    } catch (err) {
      setResult(`isolated:${describeError(err)}`);
    }
  };

  const probes = createProbes(env, setResult);

  return (
    <div data-testid="data-app-isolation" style={{ padding: 24 }}>
      <h1>Isolation probe</h1>
      <div data-testid="isolation-result" data-probe-id={probeId ?? ""}>
        {result}
      </div>

      <div style={{ display: "flex", gap: 8, marginTop: 16, flexWrap: "wrap" }}>
        {probes.map((probe) => (
          <button
            key={probe.id}
            data-testid={`isolation-${probe.id}`}
            onClick={() => fire(probe.id)}
          >
            {probe.label}
          </button>
        ))}
        {REACT_PROBES.map((probe) => (
          <button
            key={probe.id}
            data-testid={`isolation-${probe.id}`}
            onClick={() => {
              arm(probe.id);
              firedRef.current = false;
              setReactMode(probe.mode);
            }}
          >
            {probe.label}
          </button>
        ))}
      </div>

      <ReactProbeHost
        mode={reactMode}
        env={env}
        report={setResult}
        firedRef={firedRef}
      />
    </div>
  );
}