mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-20 18:57:17 +03:00
fix(gui-plugins): drive the Office viewer worker with one explicit state machine (#61892)
This commit is contained in:
committed by
GitHub
Unverified
parent
aff43234c8
commit
2b6e6d8a70
@@ -1,7 +1,8 @@
|
||||
import { createSignal, For, onCleanup, Show, type Accessor } from "solid-js"
|
||||
import { For, onCleanup, Show, type Accessor } from "solid-js"
|
||||
import { createStore } from "solid-js/store"
|
||||
import { Loader } from "@opencode/ui/loader"
|
||||
import { createKeyed, createLatest, usePlugin } from "@opencode/plugin/gui"
|
||||
import { createLatest, usePlugin } from "@opencode/plugin/gui"
|
||||
import { createOfficeWorker, type WorkerClient } from "./office-worker"
|
||||
import { OfficePages, type PaintPage, type ScrollToPage } from "./pages"
|
||||
import {
|
||||
layerFont,
|
||||
@@ -11,7 +12,7 @@ import {
|
||||
type WordPageSize,
|
||||
type WordSpan,
|
||||
} from "./word-protocol"
|
||||
import { createWorkerClient, movableBuffer } from "./worker-rpc"
|
||||
import { WorkerClosedError } from "./worker-rpc"
|
||||
import type { FileViewerProps } from "@opencode/plugin/gui/file"
|
||||
|
||||
type Opened = {
|
||||
@@ -27,7 +28,7 @@ type Opened = {
|
||||
readonly finish: () => Promise<number>
|
||||
}
|
||||
|
||||
type Client = ReturnType<typeof createWorkerClient<WordMethods>>
|
||||
type Client = WorkerClient<WordMethods>
|
||||
|
||||
/** Scrolls the page column; set once the column mounts. */
|
||||
type Scroll = { to: ScrollToPage | undefined }
|
||||
@@ -44,105 +45,101 @@ type Lazy<T> = { value: T | undefined }
|
||||
* each page makes its text selectable, findable and readable, and its links followable.
|
||||
*/
|
||||
export default function OfficeDocument(props: FileViewerProps) {
|
||||
const ctx = usePlugin()
|
||||
const [opened, setOpened] = createSignal<Opened>()
|
||||
|
||||
// Syncs one document worker with the loaded bytes. Terminating it is what frees the engine's memory.
|
||||
createKeyed(
|
||||
() => props.bytes,
|
||||
(bytes) => {
|
||||
const controller = new AbortController()
|
||||
const worker = new Worker(new URL("./document.worker.ts", import.meta.url), { type: "module" })
|
||||
const client = createWorkerClient<WordMethods>(worker)
|
||||
|
||||
const fail = () => {
|
||||
if (controller.signal.aborted) return
|
||||
|
||||
controller.abort()
|
||||
props.onError()
|
||||
}
|
||||
|
||||
// A worker that dies after the pages showed takes them with it.
|
||||
worker.addEventListener("error", fail)
|
||||
worker.addEventListener("messageerror", fail)
|
||||
onCleanup(() => {
|
||||
controller.abort()
|
||||
client.close()
|
||||
setOpened(undefined)
|
||||
})
|
||||
|
||||
void open(client, bytes)
|
||||
.then((value) => {
|
||||
if (controller.signal.aborted) return
|
||||
|
||||
setOpened(value)
|
||||
|
||||
// The worker runs calls in order, so the full layout waits until the first pages have asked for their paints:
|
||||
// they do once the column is laid out and its observer reports them, which takes up to two frames.
|
||||
return new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)))
|
||||
.then(() => (controller.signal.aborted ? undefined : value.finish()))
|
||||
.then((count) => {
|
||||
if (count !== undefined && !controller.signal.aborted) props.onDetails([ctx.plural("pages", count)])
|
||||
})
|
||||
})
|
||||
.catch(fail)
|
||||
},
|
||||
)
|
||||
// A worker that dies after the pages showed takes them with it.
|
||||
const viewer = createOfficeWorker<WordMethods, Opened>({
|
||||
bytes: () => props.bytes,
|
||||
createWorker: () => new Worker(new URL("./document.worker.ts", import.meta.url), { type: "module" }),
|
||||
open: async (client, buffer, signal) => ({ value: await open(client, buffer, signal) }),
|
||||
onDetails: (details) => props.onDetails(details),
|
||||
onError: () => props.onError(),
|
||||
})
|
||||
|
||||
return (
|
||||
<Show
|
||||
when={opened()}
|
||||
when={viewer.opened()}
|
||||
keyed
|
||||
fallback={
|
||||
<div class="flex min-h-0 flex-1 items-center justify-center">
|
||||
<Loader />
|
||||
</div>
|
||||
<Show when={viewer.loading()}>
|
||||
<div class="flex min-h-0 flex-1 items-center justify-center">
|
||||
<Loader />
|
||||
</div>
|
||||
</Show>
|
||||
}
|
||||
>
|
||||
{(opened) => {
|
||||
const scroll: Scroll = { to: undefined }
|
||||
|
||||
const follow = (link: WordLink) => {
|
||||
if (link.kind === "external") return ctx.system.openExternal(link.url)
|
||||
|
||||
void opened()
|
||||
.bookmark(link.bookmark)
|
||||
.then(
|
||||
(target) => {
|
||||
if (target) scroll.to?.(target.index, target.y)
|
||||
},
|
||||
() => undefined,
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<OfficePages
|
||||
pages={opened().pages()}
|
||||
paint={opened().paint}
|
||||
label={(index) => ctx.t("page", { number: index + 1 })}
|
||||
overlay={(input) => (
|
||||
<WordTextLayer
|
||||
index={input.index}
|
||||
page={opened().pages()[input.index]}
|
||||
text={opened().text}
|
||||
follow={follow}
|
||||
/>
|
||||
)}
|
||||
text
|
||||
footer={(index) => (
|
||||
<Show when={opened().loading() && index === opened().pages().length - 1}>
|
||||
<Loader />
|
||||
</Show>
|
||||
)}
|
||||
onScrollTo={(scrollTo) => {
|
||||
scroll.to = scrollTo
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}}
|
||||
{(opened) => (
|
||||
<DocumentContent
|
||||
opened={opened.value}
|
||||
onDetails={(details) => props.onDetails(details)}
|
||||
onError={() => props.onError()}
|
||||
/>
|
||||
)}
|
||||
</Show>
|
||||
)
|
||||
}
|
||||
|
||||
/** One opened document's pages. A reloaded file mounts a new one. */
|
||||
function DocumentContent(props: {
|
||||
opened: Opened
|
||||
onDetails: (details: readonly string[]) => void
|
||||
onError: () => void
|
||||
}) {
|
||||
const ctx = usePlugin()
|
||||
const scroll: Scroll = { to: undefined }
|
||||
const controller = new AbortController()
|
||||
|
||||
onCleanup(() => controller.abort())
|
||||
|
||||
// The worker runs calls in order, so the full layout waits until the first pages have asked for their paints: they
|
||||
// do once the column is laid out and its observer reports them, which takes up to two frames.
|
||||
void new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)))
|
||||
.then(() => (controller.signal.aborted ? undefined : props.opened.finish()))
|
||||
.then(
|
||||
(count) => {
|
||||
if (count !== undefined && !controller.signal.aborted) props.onDetails([ctx.plural("pages", count)])
|
||||
},
|
||||
(error: Error) => {
|
||||
// A worker that stopped reports itself through the viewer's worker.
|
||||
if (!controller.signal.aborted && !(error instanceof WorkerClosedError)) props.onError()
|
||||
},
|
||||
)
|
||||
|
||||
const follow = (link: WordLink) => {
|
||||
if (link.kind === "external") return ctx.system.openExternal(link.url)
|
||||
|
||||
void props.opened.bookmark(link.bookmark).then(
|
||||
(target) => {
|
||||
if (target) scroll.to?.(target.index, target.y)
|
||||
},
|
||||
() => undefined,
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<OfficePages
|
||||
pages={props.opened.pages()}
|
||||
paint={props.opened.paint}
|
||||
label={(index) => ctx.t("page", { number: index + 1 })}
|
||||
overlay={(input) => (
|
||||
<WordTextLayer
|
||||
index={input.index}
|
||||
page={props.opened.pages()[input.index]}
|
||||
text={props.opened.text}
|
||||
follow={follow}
|
||||
/>
|
||||
)}
|
||||
text
|
||||
footer={(index) => (
|
||||
<Show when={props.opened.loading() && index === props.opened.pages().length - 1}>
|
||||
<Loader />
|
||||
</Show>
|
||||
)}
|
||||
onScrollTo={(scrollTo) => {
|
||||
scroll.to = scrollTo
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Transparent text over a page's painted glyphs. Positions are fractions of the page and sizes fractions of its width
|
||||
* (container query units), so the layer tracks the page's CSS size at once while a resize waits to repaint.
|
||||
@@ -221,10 +218,8 @@ function place(span: WordSpan) {
|
||||
}
|
||||
|
||||
/** Opens the bytes in the worker and returns as soon as the document's first pages can show. */
|
||||
async function open(client: Client, bytes: Uint8Array): Promise<Opened> {
|
||||
// The view owns its bytes, so they move to the worker rather than being copied.
|
||||
const buffer = movableBuffer(bytes)
|
||||
const first = await client.call("open", { bytes: buffer }, { transfer: [buffer] })
|
||||
async function open(client: Client, buffer: ArrayBuffer, signal: AbortSignal): Promise<Opened> {
|
||||
const first = await client.call("open", { bytes: buffer }, { transfer: [buffer], signal })
|
||||
const [layout, setLayout] = createStore({ pages: first.pages, loading: first.loading })
|
||||
|
||||
const layOut = async (): Promise<number> => {
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
import { createMemo, createSignal, onCleanup, untrack } from "solid-js"
|
||||
import { createKeyed } from "@opencode/plugin/gui"
|
||||
import {
|
||||
transitionWorker,
|
||||
workerLoading,
|
||||
workerOpened,
|
||||
type WorkerEffect,
|
||||
type WorkerEvent,
|
||||
type WorkerState,
|
||||
} from "./worker-machine"
|
||||
import { createWorkerClient, movableBuffer, type Methods } from "./worker-rpc"
|
||||
|
||||
/** The window's end of a viewer's worker. */
|
||||
export type WorkerClient<M extends Methods> = ReturnType<typeof createWorkerClient<M>>
|
||||
|
||||
/** What a viewer's open returns: what it shows the file with, and the facts the toolbar shows when it knows them. */
|
||||
export type OfficeOpened<T> = { readonly value: T; readonly details?: readonly string[] }
|
||||
|
||||
/** One attempt's worker, until it closes. */
|
||||
type Run = {
|
||||
readonly controller: AbortController
|
||||
readonly close: () => void
|
||||
readonly timer: ReturnType<typeof setTimeout>
|
||||
}
|
||||
|
||||
/**
|
||||
* Syncs one worker with the view's bytes: each new array opens in a worker of its own, and the previous one is
|
||||
* terminated, which frees its engine's memory. Open failures, timeouts and crashes report `onError` once per attempt.
|
||||
*/
|
||||
export function createOfficeWorker<M extends Methods, T>(options: {
|
||||
readonly bytes: () => Uint8Array
|
||||
/** Builds the worker; each caller keeps its own `new Worker(new URL(...))` so the bundler finds the script. */
|
||||
readonly createWorker: () => Worker
|
||||
/** Opens the bytes, which move to the worker; resolves undefined when the file cannot be opened. */
|
||||
readonly open: (
|
||||
client: WorkerClient<M>,
|
||||
buffer: ArrayBuffer,
|
||||
signal: AbortSignal,
|
||||
) => Promise<OfficeOpened<T> | undefined>
|
||||
readonly onDetails: (details: readonly string[]) => void
|
||||
readonly onError: () => void
|
||||
}) {
|
||||
const [workerState, setWorkerState] = createSignal<WorkerState<T>>({ status: "idle" })
|
||||
const runs = new Map<number, Run>()
|
||||
// Effects can dispatch while they run (reporting an error may unmount the view), so events apply one at a time.
|
||||
const queue: WorkerEvent<T>[] = []
|
||||
|
||||
const dispatch = (event: WorkerEvent<T>) => {
|
||||
queue.push(event)
|
||||
|
||||
if (queue.length === 1) drain()
|
||||
}
|
||||
|
||||
const drain = () => {
|
||||
const event = queue[0]
|
||||
|
||||
if (!event) return
|
||||
|
||||
const next = transitionWorker(untrack(workerState), event)
|
||||
|
||||
setWorkerState(() => next.state)
|
||||
next.effects.forEach(run)
|
||||
queue.shift()
|
||||
drain()
|
||||
}
|
||||
|
||||
const run = (effect: WorkerEffect) => {
|
||||
if (effect.type === "open-worker") return start(effect.attempt, effect.bytes, effect.timeoutMs)
|
||||
|
||||
if (effect.type === "cancel-open-timeout") return clearTimeout(runs.get(effect.attempt)?.timer)
|
||||
|
||||
if (effect.type === "close-worker") return close(effect.attempt)
|
||||
|
||||
if (effect.type === "report-details") return options.onDetails(effect.details)
|
||||
|
||||
options.onError()
|
||||
}
|
||||
|
||||
const start = (attempt: number, bytes: Uint8Array, timeoutMs: number) => {
|
||||
const controller = new AbortController()
|
||||
const worker = options.createWorker()
|
||||
const client = createWorkerClient<M>(worker)
|
||||
const crashed = () => dispatch({ type: "worker.crashed", attempt })
|
||||
|
||||
worker.addEventListener("error", crashed)
|
||||
worker.addEventListener("messageerror", crashed)
|
||||
runs.set(attempt, {
|
||||
controller,
|
||||
close: () => client.close(),
|
||||
timer: setTimeout(() => dispatch({ type: "open.timed-out", attempt }), timeoutMs),
|
||||
})
|
||||
|
||||
// The view owns its bytes, so they move to the worker rather than being copied.
|
||||
void options.open(client, movableBuffer(bytes), controller.signal).then(
|
||||
(opened) =>
|
||||
dispatch(
|
||||
opened
|
||||
? { type: "open.succeeded", attempt, value: opened.value, details: opened.details }
|
||||
: { type: "open.failed", attempt },
|
||||
),
|
||||
() => dispatch({ type: "open.failed", attempt }),
|
||||
)
|
||||
}
|
||||
|
||||
const close = (attempt: number) => {
|
||||
const entry = runs.get(attempt)
|
||||
|
||||
if (!entry) return
|
||||
|
||||
runs.delete(attempt)
|
||||
clearTimeout(entry.timer)
|
||||
entry.controller.abort()
|
||||
entry.close()
|
||||
}
|
||||
|
||||
createKeyed(options.bytes, (bytes) => dispatch({ type: "bytes.changed", bytes }))
|
||||
onCleanup(() => dispatch({ type: "disposed" }))
|
||||
|
||||
return {
|
||||
/** Whether the viewer shows its loader. */
|
||||
loading: createMemo(() => workerLoading(workerState())),
|
||||
/** The open file; a new object for each attempt. */
|
||||
opened: createMemo(() => workerOpened(workerState())),
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
import { onCleanup, Show } from "solid-js"
|
||||
import { Show } from "solid-js"
|
||||
import { createStore } from "solid-js/store"
|
||||
import { Loader } from "@opencode/ui/loader"
|
||||
import { createKeyed, usePlugin } from "@opencode/plugin/gui"
|
||||
import { usePlugin } from "@opencode/plugin/gui"
|
||||
import { createOfficeWorker, type WorkerClient } from "./office-worker"
|
||||
import { OfficePages, type PaintPage } from "./pages"
|
||||
import { paper } from "./paper"
|
||||
import {
|
||||
@@ -12,12 +13,13 @@ import {
|
||||
type VectorBitmap,
|
||||
type VectorRequest,
|
||||
} from "./slide-protocol"
|
||||
import { createWorkerClient, movableBuffer, SupersededError, WorkerClosedError } from "./worker-rpc"
|
||||
import { SupersededError, WorkerClosedError } from "./worker-rpc"
|
||||
import type { FileViewerProps } from "@opencode/plugin/gui/file"
|
||||
|
||||
type Opened = { readonly slides: readonly SlideSummary[]; readonly paint: PaintPage }
|
||||
type Client = WorkerClient<SlideMethods>
|
||||
|
||||
type Client = ReturnType<typeof createWorkerClient<SlideMethods>>
|
||||
/** An opened deck: its worker and its slides. */
|
||||
type Opened = { readonly client: Client; readonly slides: readonly SlideSummary[] }
|
||||
|
||||
/**
|
||||
* A read-only PowerPoint deck: every slide fitted to the pane and painted as it scrolls into view, with its speaker
|
||||
@@ -27,120 +29,95 @@ type Client = ReturnType<typeof createWorkerClient<SlideMethods>>
|
||||
export default function OfficePresentation(props: FileViewerProps) {
|
||||
const ctx = usePlugin()
|
||||
|
||||
const [state, setState] = createStore<{ opened: Opened | undefined; failed: boolean[] }>({
|
||||
opened: undefined,
|
||||
failed: [],
|
||||
})
|
||||
// A worker that stops, such as one out of memory, takes the deck with it.
|
||||
const viewer = createOfficeWorker<SlideMethods, Opened>({
|
||||
bytes: () => props.bytes,
|
||||
createWorker: () =>
|
||||
new Worker(new URL("./presentation.worker.ts", import.meta.url), { type: "module", name: "PowerPoint preview" }),
|
||||
open: async (client, buffer, signal) => {
|
||||
const slides = await client.call("open", { bytes: buffer }, { transfer: [buffer], signal })
|
||||
|
||||
// Syncs one deck's worker with the loaded bytes. Terminating the worker frees the engine's memory.
|
||||
createKeyed(
|
||||
() => props.bytes,
|
||||
(bytes) => {
|
||||
const controller = new AbortController()
|
||||
const status = { failed: false }
|
||||
|
||||
const worker = new Worker(new URL("./presentation.worker.ts", import.meta.url), {
|
||||
type: "module",
|
||||
name: "PowerPoint preview",
|
||||
})
|
||||
|
||||
const client = createWorkerClient<SlideMethods>(worker)
|
||||
|
||||
onCleanup(() => {
|
||||
controller.abort()
|
||||
client.close()
|
||||
setState({ opened: undefined, failed: [] })
|
||||
})
|
||||
|
||||
const fail = () => {
|
||||
if (controller.signal.aborted || status.failed) return
|
||||
|
||||
status.failed = true
|
||||
props.onError()
|
||||
}
|
||||
|
||||
// A worker that stops, such as one out of memory, takes the deck with it.
|
||||
worker.addEventListener("error", fail)
|
||||
worker.addEventListener("messageerror", fail)
|
||||
|
||||
const painted = (index: number, failed: boolean) => {
|
||||
if (!controller.signal.aborted) setState("failed", index, failed)
|
||||
}
|
||||
|
||||
// The view owns its bytes, so they move to the worker rather than being copied.
|
||||
const buffer = movableBuffer(bytes)
|
||||
|
||||
void client.call("open", { bytes: buffer }, { transfer: [buffer], signal: controller.signal }).then((slides) => {
|
||||
if (controller.signal.aborted) return
|
||||
|
||||
setState({ opened: { slides, paint: createPaint(client, painted) } })
|
||||
props.onDetails([ctx.plural("slides", slides.length)])
|
||||
}, fail)
|
||||
return { value: { client, slides }, details: [ctx.plural("slides", slides.length)] }
|
||||
},
|
||||
)
|
||||
onDetails: (details) => props.onDetails(details),
|
||||
onError: () => props.onError(),
|
||||
})
|
||||
|
||||
return (
|
||||
<Show
|
||||
when={state.opened}
|
||||
when={viewer.opened()}
|
||||
keyed
|
||||
fallback={
|
||||
<div class="flex min-h-0 flex-1 items-center justify-center">
|
||||
<Loader />
|
||||
</div>
|
||||
<Show when={viewer.loading()}>
|
||||
<div class="flex min-h-0 flex-1 items-center justify-center">
|
||||
<Loader />
|
||||
</div>
|
||||
</Show>
|
||||
}
|
||||
>
|
||||
{(opened) => (
|
||||
<OfficePages
|
||||
pages={opened().slides}
|
||||
paint={opened().paint}
|
||||
label={(index) => ctx.t("slide", { number: index + 1 })}
|
||||
overlay={(input) => (
|
||||
<>
|
||||
<Show when={opened().slides[input.index]?.hidden}>
|
||||
{/* Paper-coloured, like the slide itself, so a hidden slide fades the same way in every theme. */}
|
||||
<div class="pointer-events-none absolute inset-0 opacity-50" style={{ background: paper }} />
|
||||
</Show>
|
||||
<Show when={state.failed[input.index]}>
|
||||
<div class="absolute inset-0 flex items-center justify-center p-4">
|
||||
<p
|
||||
role="status"
|
||||
class="rounded-md bg-v2-background-bg-base px-3 py-1.5 text-12-regular text-v2-text-text-muted shadow-[var(--v2-elevation-raised)]"
|
||||
>
|
||||
{ctx.t("slideFailed")}
|
||||
</p>
|
||||
</div>
|
||||
</Show>
|
||||
</>
|
||||
)}
|
||||
footer={(index) => (
|
||||
<Show when={opened().slides[index]}>
|
||||
{(slide) => (
|
||||
<Show when={slide().hidden || slide().notes}>
|
||||
{/* Zero width and full minimum width: the slide sets the column's width, and long notes wrap to it. */}
|
||||
<div class="flex w-0 min-w-full flex-col items-start gap-1.5">
|
||||
<Show when={slide().hidden}>
|
||||
<span class="rounded-[4px] border border-v2-border-border-base px-1.5 text-11-regular text-v2-text-text-muted">
|
||||
{ctx.t("hiddenSlide")}
|
||||
</span>
|
||||
</Show>
|
||||
<Show when={slide().notes}>
|
||||
{(notes) => (
|
||||
<p
|
||||
role="note"
|
||||
aria-label={ctx.t("speakerNotes")}
|
||||
class="w-full select-text whitespace-pre-wrap [overflow-wrap:anywhere] text-12-regular text-v2-text-text-muted"
|
||||
>
|
||||
{notes()}
|
||||
</p>
|
||||
)}
|
||||
</Show>
|
||||
</div>
|
||||
{(opened) => <PresentationDeck opened={opened.value} />}
|
||||
</Show>
|
||||
)
|
||||
}
|
||||
|
||||
/** One opened deck's slides. A reloaded file mounts a new one, with no slide failed. */
|
||||
function PresentationDeck(props: { opened: Opened }) {
|
||||
const ctx = usePlugin()
|
||||
const [failed, setFailed] = createStore<boolean[]>([])
|
||||
const slides = () => props.opened.slides
|
||||
const paint = createPaint(props.opened.client, (index, value) => setFailed(index, value))
|
||||
|
||||
return (
|
||||
<OfficePages
|
||||
pages={slides()}
|
||||
paint={paint}
|
||||
label={(index) => ctx.t("slide", { number: index + 1 })}
|
||||
overlay={(input) => (
|
||||
<>
|
||||
<Show when={slides()[input.index]?.hidden}>
|
||||
{/* Paper-coloured, like the slide itself, so a hidden slide fades the same way in every theme. */}
|
||||
<div class="pointer-events-none absolute inset-0 opacity-50" style={{ background: paper }} />
|
||||
</Show>
|
||||
<Show when={failed[input.index]}>
|
||||
<div class="absolute inset-0 flex items-center justify-center p-4">
|
||||
<p
|
||||
role="status"
|
||||
class="rounded-md bg-v2-background-bg-base px-3 py-1.5 text-12-regular text-v2-text-text-muted shadow-[var(--v2-elevation-raised)]"
|
||||
>
|
||||
{ctx.t("slideFailed")}
|
||||
</p>
|
||||
</div>
|
||||
</Show>
|
||||
</>
|
||||
)}
|
||||
footer={(index) => (
|
||||
<Show when={slides()[index]}>
|
||||
{(slide) => (
|
||||
<Show when={slide().hidden || slide().notes}>
|
||||
{/* Zero width and full minimum width: the slide sets the column's width, and long notes wrap to it. */}
|
||||
<div class="flex w-0 min-w-full flex-col items-start gap-1.5">
|
||||
<Show when={slide().hidden}>
|
||||
<span class="rounded-[4px] border border-v2-border-border-base px-1.5 text-11-regular text-v2-text-text-muted">
|
||||
{ctx.t("hiddenSlide")}
|
||||
</span>
|
||||
</Show>
|
||||
)}
|
||||
<Show when={slide().notes}>
|
||||
{(notes) => (
|
||||
<p
|
||||
role="note"
|
||||
aria-label={ctx.t("speakerNotes")}
|
||||
class="w-full select-text whitespace-pre-wrap [overflow-wrap:anywhere] text-12-regular text-v2-text-text-muted"
|
||||
>
|
||||
{notes()}
|
||||
</p>
|
||||
)}
|
||||
</Show>
|
||||
</div>
|
||||
</Show>
|
||||
)}
|
||||
/>
|
||||
</Show>
|
||||
)}
|
||||
</Show>
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -36,12 +36,14 @@ import {
|
||||
type Painted,
|
||||
} from "./sheet-paint"
|
||||
import type { SheetFrameRequest, SheetLayout, SheetMethods, SheetTab, SheetViewport } from "./sheet-protocol"
|
||||
import { createWorkerClient, movableBuffer, SupersededError, WorkerClosedError } from "./worker-rpc"
|
||||
import { createOfficeWorker, type WorkerClient } from "./office-worker"
|
||||
import { SupersededError, WorkerClosedError } from "./worker-rpc"
|
||||
|
||||
/** The workbook worker's end in the window. */
|
||||
type Client = ReturnType<typeof createWorkerClient<SheetMethods>>
|
||||
type Client = WorkerClient<SheetMethods>
|
||||
|
||||
type Opened = { readonly client: Client; readonly tabs: readonly SheetTab[] }
|
||||
/** An opened workbook: its worker, its visible sheets and the layout of the sheet it opened on. */
|
||||
type Opened = { readonly client: Client; readonly tabs: readonly SheetTab[]; readonly layout: SheetLayout }
|
||||
|
||||
/** The sheet on show, and the cell a link asked for when one opened it. */
|
||||
type Shown = { readonly layout: SheetLayout; readonly target: CellAddr | undefined }
|
||||
@@ -70,80 +72,77 @@ const settleDelay = 150
|
||||
/** A read-only Excel workbook with a tab per visible sheet. */
|
||||
export default function OfficeSpreadsheet(props: FileViewerProps) {
|
||||
const ctx = usePlugin()
|
||||
|
||||
const viewer = createOfficeWorker<SheetMethods, Opened>({
|
||||
bytes: () => props.bytes,
|
||||
createWorker: () => new Worker(new URL("./spreadsheet.worker.ts", import.meta.url), { type: "module" }),
|
||||
open: async (client, buffer, signal) => {
|
||||
const opened = await client.call("open", { bytes: buffer }, { transfer: [buffer], signal })
|
||||
|
||||
if (!opened) return undefined
|
||||
|
||||
return {
|
||||
value: { client, tabs: opened.tabs, layout: opened.layout },
|
||||
details: [ctx.plural("sheets", opened.tabs.length)],
|
||||
}
|
||||
},
|
||||
onDetails: (details) => props.onDetails(details),
|
||||
onError: () => props.onError(),
|
||||
})
|
||||
|
||||
return (
|
||||
<Show
|
||||
when={viewer.opened()}
|
||||
keyed
|
||||
fallback={
|
||||
<Show when={viewer.loading()}>
|
||||
<div class="flex min-h-0 flex-1 items-center justify-center">
|
||||
<Loader />
|
||||
</div>
|
||||
</Show>
|
||||
}
|
||||
>
|
||||
{(opened) => <SpreadsheetWorkbook opened={opened.value} />}
|
||||
</Show>
|
||||
)
|
||||
}
|
||||
|
||||
/** One opened workbook: its sheet tabs and the grid of the sheet on show. A reloaded file mounts a new one. */
|
||||
function SpreadsheetWorkbook(props: { opened: Opened }) {
|
||||
const ctx = usePlugin()
|
||||
const panel = createUniqueId()
|
||||
|
||||
// `selecting` is the tab the user picked while its sheet opens in the worker.
|
||||
const [state, setState] = createStore<{
|
||||
opened: Opened | undefined
|
||||
shown: Shown | undefined
|
||||
selecting: number | undefined
|
||||
}>({
|
||||
opened: undefined,
|
||||
shown: undefined,
|
||||
const [state, setState] = createStore<{ shown: Shown; selecting: number | undefined }>({
|
||||
shown: { layout: props.opened.layout, target: undefined },
|
||||
selecting: undefined,
|
||||
})
|
||||
|
||||
// Syncs one workbook worker with the loaded bytes. Terminating it, when they change or the view closes, is what frees
|
||||
// the engine's memory.
|
||||
createKeyed(
|
||||
() => props.bytes,
|
||||
(bytes) => {
|
||||
const controller = new AbortController()
|
||||
const worker = new Worker(new URL("./spreadsheet.worker.ts", import.meta.url), { type: "module" })
|
||||
const client = createWorkerClient<SheetMethods>(worker)
|
||||
|
||||
const crash = () => {
|
||||
if (!controller.signal.aborted) props.onError()
|
||||
}
|
||||
|
||||
worker.addEventListener("error", crash)
|
||||
worker.addEventListener("messageerror", crash)
|
||||
|
||||
onCleanup(() => {
|
||||
controller.abort()
|
||||
client.close()
|
||||
setState({ opened: undefined, shown: undefined, selecting: undefined })
|
||||
})
|
||||
|
||||
// The view owns its bytes, so they move to the worker rather than being copied.
|
||||
const buffer = movableBuffer(bytes)
|
||||
|
||||
void client.call("open", { bytes: buffer }, { transfer: [buffer], signal: controller.signal }).then((opened) => {
|
||||
if (controller.signal.aborted) return
|
||||
|
||||
if (!opened) return props.onError()
|
||||
|
||||
setState({ opened: { client, tabs: opened.tabs }, shown: { layout: opened.layout, target: undefined } })
|
||||
props.onDetails([ctx.plural("sheets", opened.tabs.length)])
|
||||
}, crash)
|
||||
},
|
||||
)
|
||||
|
||||
const active = () => state.selecting ?? state.shown?.layout.info.activeSheet
|
||||
const active = () => state.selecting ?? state.shown.layout.info.activeSheet
|
||||
const picking: Picking = { controller: undefined }
|
||||
|
||||
const show = (index: number, target?: CellAddr) => {
|
||||
const opened = state.opened
|
||||
onCleanup(() => picking.controller?.abort())
|
||||
|
||||
if (!opened || (index === active() && !target)) return
|
||||
const show = (index: number, target?: CellAddr) => {
|
||||
if (index === active() && !target) return
|
||||
|
||||
picking.controller?.abort()
|
||||
|
||||
// Back to the sheet on show: the pick that was opening is withdrawn, and the grid stays.
|
||||
if (index === state.shown?.layout.info.activeSheet && !target) return void setState("selecting", undefined)
|
||||
if (index === state.shown.layout.info.activeSheet && !target) return void setState("selecting", undefined)
|
||||
|
||||
const controller = new AbortController()
|
||||
|
||||
picking.controller = controller
|
||||
setState("selecting", index)
|
||||
|
||||
void opened.client.call("show", { sheet: index }, { signal: controller.signal }).then(
|
||||
void props.opened.client.call("show", { sheet: index }, { signal: controller.signal }).then(
|
||||
(layout) => {
|
||||
// Replaced, not merged as a path setter would, so the grid below mounts afresh for the sheet.
|
||||
if (state.opened === opened) setState({ shown: { layout, target }, selecting: undefined })
|
||||
setState({ shown: { layout, target }, selecting: undefined })
|
||||
},
|
||||
(error: Error) => {
|
||||
if (state.opened !== opened || error instanceof WorkerClosedError) return
|
||||
if (error instanceof WorkerClosedError) return
|
||||
|
||||
// One sheet that fails to open leaves the others readable: the sheet on show stays.
|
||||
setState("selecting", undefined)
|
||||
@@ -154,14 +153,14 @@ export default function OfficeSpreadsheet(props: FileViewerProps) {
|
||||
|
||||
// A link to a hidden or missing sheet goes nowhere, as in Excel.
|
||||
const navigate = (name: string, cell: CellAddr) => {
|
||||
const tab = state.opened?.tabs.find((candidate) => candidate.name.toLowerCase() === name.toLowerCase())
|
||||
const tab = props.opened.tabs.find((candidate) => candidate.name.toLowerCase() === name.toLowerCase())
|
||||
|
||||
if (tab) show(tab.index, cell)
|
||||
}
|
||||
|
||||
// The arrow keys move between the sheet tabs and open the one they reach; only the open tab is in the Tab order.
|
||||
const roam = (event: KeyboardEvent & { currentTarget: HTMLDivElement }) => {
|
||||
const tabs = state.opened?.tabs ?? []
|
||||
const tabs = props.opened.tabs
|
||||
const current = tabs.findIndex((tab) => tab.index === active())
|
||||
const forward = getComputedStyle(event.currentTarget).direction === "rtl" ? "ArrowLeft" : "ArrowRight"
|
||||
const backward = forward === "ArrowRight" ? "ArrowLeft" : "ArrowRight"
|
||||
@@ -190,62 +189,51 @@ export default function OfficeSpreadsheet(props: FileViewerProps) {
|
||||
const tabID = (index: number | undefined) => `${panel}-tab-${index}`
|
||||
|
||||
return (
|
||||
<Show
|
||||
when={state.opened}
|
||||
fallback={
|
||||
<div class="flex min-h-0 flex-1 items-center justify-center">
|
||||
<Loader />
|
||||
<div class="flex min-h-0 flex-1 flex-col">
|
||||
<div
|
||||
id={panel}
|
||||
role={props.opened.tabs.length > 1 ? "tabpanel" : undefined}
|
||||
aria-labelledby={props.opened.tabs.length > 1 ? tabID(state.shown.layout.info.activeSheet) : undefined}
|
||||
class="flex min-h-0 flex-1"
|
||||
>
|
||||
{/* Each sheet gets its own grid, so its selection and scroll position start fresh. */}
|
||||
<Show when={state.shown} keyed>
|
||||
{(shown) => (
|
||||
<SpreadsheetGrid
|
||||
client={props.opened.client}
|
||||
layout={shown.layout}
|
||||
target={shown.target}
|
||||
onNavigate={navigate}
|
||||
/>
|
||||
)}
|
||||
</Show>
|
||||
</div>
|
||||
<Show when={props.opened.tabs.length > 1}>
|
||||
<div
|
||||
role="tablist"
|
||||
aria-label={ctx.t("sheet.tabs")}
|
||||
class="flex h-9 shrink-0 items-center gap-1 overflow-x-auto border-t border-v2-border-border-muted px-2"
|
||||
onKeyDown={roam}
|
||||
>
|
||||
<For each={props.opened.tabs}>
|
||||
{(tab) => (
|
||||
<button
|
||||
type="button"
|
||||
role="tab"
|
||||
id={tabID(tab.index)}
|
||||
aria-controls={panel}
|
||||
aria-selected={tab.index === active()}
|
||||
tabIndex={tab.index === active() ? 0 : -1}
|
||||
class="h-7 shrink-0 rounded-md px-2.5 text-13-regular text-text-weak hover:bg-v2-background-bg-layer-02 aria-selected:bg-v2-background-bg-layer-02 aria-selected:text-text-strong"
|
||||
onClick={() => show(tab.index)}
|
||||
>
|
||||
{tab.name}
|
||||
</button>
|
||||
)}
|
||||
</For>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
{(opened) => (
|
||||
<div class="flex min-h-0 flex-1 flex-col">
|
||||
<div
|
||||
id={panel}
|
||||
role={opened().tabs.length > 1 ? "tabpanel" : undefined}
|
||||
aria-labelledby={opened().tabs.length > 1 ? tabID(state.shown?.layout.info.activeSheet) : undefined}
|
||||
class="flex min-h-0 flex-1"
|
||||
>
|
||||
{/* Each sheet gets its own grid, so its selection and scroll position start fresh. */}
|
||||
<Show when={state.shown} keyed>
|
||||
{(shown) => (
|
||||
<SpreadsheetGrid
|
||||
client={opened().client}
|
||||
layout={shown.layout}
|
||||
target={shown.target}
|
||||
onNavigate={navigate}
|
||||
/>
|
||||
)}
|
||||
</Show>
|
||||
</div>
|
||||
<Show when={opened().tabs.length > 1}>
|
||||
<div
|
||||
role="tablist"
|
||||
aria-label={ctx.t("sheet.tabs")}
|
||||
class="flex h-9 shrink-0 items-center gap-1 overflow-x-auto border-t border-v2-border-border-muted px-2"
|
||||
onKeyDown={roam}
|
||||
>
|
||||
<For each={opened().tabs}>
|
||||
{(tab) => (
|
||||
<button
|
||||
type="button"
|
||||
role="tab"
|
||||
id={tabID(tab.index)}
|
||||
aria-controls={panel}
|
||||
aria-selected={tab.index === active()}
|
||||
tabIndex={tab.index === active() ? 0 : -1}
|
||||
class="h-7 shrink-0 rounded-md px-2.5 text-13-regular text-text-weak hover:bg-v2-background-bg-layer-02 aria-selected:bg-v2-background-bg-layer-02 aria-selected:text-text-strong"
|
||||
onClick={() => show(tab.index)}
|
||||
>
|
||||
{tab.name}
|
||||
</button>
|
||||
)}
|
||||
</For>
|
||||
</div>
|
||||
</Show>
|
||||
</div>
|
||||
)}
|
||||
</Show>
|
||||
</Show>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,214 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import {
|
||||
WORKER_OPEN_TIMEOUT_MS,
|
||||
transitionWorker,
|
||||
workerLoading,
|
||||
workerOpened,
|
||||
type WorkerEvent,
|
||||
type WorkerState,
|
||||
type WorkerTransition,
|
||||
} from "./worker-machine"
|
||||
|
||||
type Value = { readonly name: string }
|
||||
|
||||
const bytes = new Uint8Array([1, 2, 3])
|
||||
|
||||
const reloaded = new Uint8Array([4, 5, 6])
|
||||
|
||||
const opened = (attempt: number, details?: readonly string[]): WorkerEvent<Value> => ({
|
||||
type: "open.succeeded",
|
||||
attempt,
|
||||
value: { name: `file ${attempt}` },
|
||||
details,
|
||||
})
|
||||
|
||||
// Folds the events in order and returns the last transition.
|
||||
const replay = (events: readonly WorkerEvent<Value>[], state: WorkerState<Value> = { status: "idle" }) =>
|
||||
events.reduce<WorkerTransition<Value>>((last, event) => transitionWorker(last.state, event), { state, effects: [] })
|
||||
|
||||
describe("transitionWorker", () => {
|
||||
test("new bytes claim an attempt and start its worker with a bounded open", () => {
|
||||
const result = replay([{ type: "bytes.changed", bytes }])
|
||||
|
||||
expect(result).toEqual({
|
||||
state: { status: "opening", attempt: 1 },
|
||||
effects: [{ type: "open-worker", attempt: 1, bytes, timeoutMs: WORKER_OPEN_TIMEOUT_MS }],
|
||||
})
|
||||
expect(workerLoading(result.state)).toBe(true)
|
||||
expect(workerOpened(result.state)).toBeUndefined()
|
||||
})
|
||||
|
||||
test("a worker that crashes while opening reports the error once, not again when the open call rejects", () => {
|
||||
const crashed = replay([
|
||||
{ type: "bytes.changed", bytes },
|
||||
{ type: "worker.crashed", attempt: 1 },
|
||||
])
|
||||
|
||||
expect(crashed).toEqual({
|
||||
state: { status: "failed", attempt: 1 },
|
||||
effects: [{ type: "close-worker", attempt: 1 }, { type: "report-error" }],
|
||||
})
|
||||
|
||||
// The worker client rejects the pending open with WorkerClosedError when the worker dies.
|
||||
const rejected = transitionWorker(crashed.state, { type: "open.failed", attempt: 1 })
|
||||
|
||||
expect(rejected.state).toBe(crashed.state)
|
||||
expect(rejected.effects).toEqual([])
|
||||
expect(workerLoading(crashed.state)).toBe(false)
|
||||
})
|
||||
|
||||
test("an open reply that lands after the worker failed never shows the file or its details", () => {
|
||||
const crashed = replay([
|
||||
{ type: "bytes.changed", bytes },
|
||||
{ type: "worker.crashed", attempt: 1 },
|
||||
])
|
||||
|
||||
const late = transitionWorker(crashed.state, opened(1, ["3 slides"]))
|
||||
|
||||
expect(late.state).toBe(crashed.state)
|
||||
expect(late.effects).toEqual([])
|
||||
expect(workerOpened(late.state)).toBeUndefined()
|
||||
})
|
||||
|
||||
test("an open reports its details and shows the file", () => {
|
||||
const result = replay([{ type: "bytes.changed", bytes }, opened(1, ["2 sheets"])])
|
||||
|
||||
expect(result).toEqual({
|
||||
state: { status: "open", attempt: 1, value: { name: "file 1" } },
|
||||
effects: [
|
||||
{ type: "cancel-open-timeout", attempt: 1 },
|
||||
{ type: "report-details", details: ["2 sheets"] },
|
||||
],
|
||||
})
|
||||
expect(workerOpened(result.state) === result.state).toBe(true)
|
||||
expect(workerLoading(result.state)).toBe(false)
|
||||
expect(replay([{ type: "bytes.changed", bytes }, opened(1)]).effects).toEqual([
|
||||
{ type: "cancel-open-timeout", attempt: 1 },
|
||||
])
|
||||
})
|
||||
|
||||
test("a worker that crashes after the file showed takes it down once", () => {
|
||||
const crashed = replay([{ type: "bytes.changed", bytes }, opened(1), { type: "worker.crashed", attempt: 1 }])
|
||||
|
||||
expect(crashed).toEqual({
|
||||
state: { status: "failed", attempt: 1 },
|
||||
effects: [{ type: "close-worker", attempt: 1 }, { type: "report-error" }],
|
||||
})
|
||||
expect(workerOpened(crashed.state)).toBeUndefined()
|
||||
|
||||
const again = transitionWorker(crashed.state, { type: "worker.crashed", attempt: 1 })
|
||||
|
||||
expect(again.state).toBe(crashed.state)
|
||||
expect(again.effects).toEqual([])
|
||||
})
|
||||
|
||||
test("a file the worker cannot open, or one it hangs on, fails once and closes its worker", () => {
|
||||
for (const event of [
|
||||
{ type: "open.failed", attempt: 1 },
|
||||
{ type: "open.timed-out", attempt: 1 },
|
||||
] satisfies WorkerEvent<Value>[]) {
|
||||
const failed = replay([{ type: "bytes.changed", bytes }, event])
|
||||
|
||||
expect(failed).toEqual({
|
||||
state: { status: "failed", attempt: 1 },
|
||||
effects: [{ type: "close-worker", attempt: 1 }, { type: "report-error" }],
|
||||
})
|
||||
expect(transitionWorker(failed.state, opened(1)).state).toBe(failed.state)
|
||||
expect(transitionWorker(failed.state, { type: "worker.crashed", attempt: 1 }).effects).toEqual([])
|
||||
}
|
||||
})
|
||||
|
||||
test("a timeout after the file opened changes nothing", () => {
|
||||
const open = replay([{ type: "bytes.changed", bytes }, opened(1)])
|
||||
const timedOut = transitionWorker(open.state, { type: "open.timed-out", attempt: 1 })
|
||||
|
||||
expect(timedOut.state).toBe(open.state)
|
||||
expect(timedOut.effects).toEqual([])
|
||||
})
|
||||
|
||||
test("reloaded bytes close the previous worker, and its late results change nothing", () => {
|
||||
const reloading = replay([
|
||||
{ type: "bytes.changed", bytes },
|
||||
{ type: "bytes.changed", bytes: reloaded },
|
||||
])
|
||||
|
||||
expect(reloading).toEqual({
|
||||
state: { status: "opening", attempt: 2 },
|
||||
effects: [
|
||||
{ type: "close-worker", attempt: 1 },
|
||||
{ type: "open-worker", attempt: 2, bytes: reloaded, timeoutMs: WORKER_OPEN_TIMEOUT_MS },
|
||||
],
|
||||
})
|
||||
|
||||
for (const event of [
|
||||
opened(1),
|
||||
{ type: "open.failed", attempt: 1 },
|
||||
{ type: "open.timed-out", attempt: 1 },
|
||||
{ type: "worker.crashed", attempt: 1 },
|
||||
] satisfies WorkerEvent<Value>[]) {
|
||||
const stale = transitionWorker(reloading.state, event)
|
||||
|
||||
expect(stale.state).toBe(reloading.state)
|
||||
expect(stale.effects).toEqual([])
|
||||
}
|
||||
|
||||
expect(transitionWorker(reloading.state, { type: "open.timed-out", attempt: 2 })).toEqual({
|
||||
state: { status: "failed", attempt: 2 },
|
||||
effects: [{ type: "close-worker", attempt: 2 }, { type: "report-error" }],
|
||||
})
|
||||
})
|
||||
|
||||
test("reloading an open or failed file starts a fresh attempt", () => {
|
||||
expect(replay([{ type: "bytes.changed", bytes }, opened(1), { type: "bytes.changed", bytes: reloaded }])).toEqual({
|
||||
state: { status: "opening", attempt: 2 },
|
||||
effects: [
|
||||
{ type: "close-worker", attempt: 1 },
|
||||
{ type: "open-worker", attempt: 2, bytes: reloaded, timeoutMs: WORKER_OPEN_TIMEOUT_MS },
|
||||
],
|
||||
})
|
||||
expect(
|
||||
replay([
|
||||
{ type: "bytes.changed", bytes },
|
||||
{ type: "open.failed", attempt: 1 },
|
||||
{ type: "bytes.changed", bytes: reloaded },
|
||||
]),
|
||||
).toEqual({
|
||||
state: { status: "opening", attempt: 2 },
|
||||
effects: [{ type: "open-worker", attempt: 2, bytes: reloaded, timeoutMs: WORKER_OPEN_TIMEOUT_MS }],
|
||||
})
|
||||
})
|
||||
|
||||
test("disposal closes the active worker and ignores everything after it", () => {
|
||||
const opening = replay([{ type: "bytes.changed", bytes }, { type: "disposed" }])
|
||||
|
||||
expect(opening).toEqual({ state: { status: "disposed" }, effects: [{ type: "close-worker", attempt: 1 }] })
|
||||
expect(replay([{ type: "bytes.changed", bytes }, opened(1), { type: "disposed" }]).effects).toEqual([
|
||||
{ type: "close-worker", attempt: 1 },
|
||||
])
|
||||
expect(
|
||||
replay([{ type: "bytes.changed", bytes }, { type: "open.failed", attempt: 1 }, { type: "disposed" }]).effects,
|
||||
).toEqual([])
|
||||
expect(replay([{ type: "disposed" }]).effects).toEqual([])
|
||||
|
||||
for (const event of [
|
||||
{ type: "bytes.changed", bytes: reloaded },
|
||||
opened(1),
|
||||
{ type: "worker.crashed", attempt: 1 },
|
||||
{ type: "disposed" },
|
||||
] satisfies WorkerEvent<Value>[]) {
|
||||
const after = transitionWorker(opening.state, event)
|
||||
|
||||
expect(after.state).toBe(opening.state)
|
||||
expect(after.effects).toEqual([])
|
||||
}
|
||||
|
||||
expect(workerLoading(opening.state)).toBe(false)
|
||||
})
|
||||
|
||||
test("results before any bytes change nothing", () => {
|
||||
const idle: WorkerState<Value> = { status: "idle" }
|
||||
|
||||
expect(transitionWorker(idle, opened(0)).state).toBe(idle)
|
||||
expect(workerLoading(idle)).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,111 @@
|
||||
/**
|
||||
* How long a worker may take to open a file before the viewer gives up and the file view shows its binary placeholder.
|
||||
* Generous, because a large workbook parses for seconds on a slow machine; it only bounds an engine that hangs.
|
||||
*/
|
||||
export const WORKER_OPEN_TIMEOUT_MS = 60_000
|
||||
|
||||
/**
|
||||
* One Office viewer's worker. Each new set of bytes takes the next attempt number and a worker of its own, so a result
|
||||
* or crash whose attempt the state no longer holds is stale.
|
||||
*/
|
||||
export type WorkerState<T> =
|
||||
/** No bytes yet. */
|
||||
| { readonly status: "idle" }
|
||||
/** The attempt's worker is opening the bytes. */
|
||||
| { readonly status: "opening"; readonly attempt: number }
|
||||
/** The file shows; `value` is what the viewer needs to show it. */
|
||||
| { readonly status: "open"; readonly attempt: number; readonly value: T }
|
||||
/** The file could not be opened, or its worker stopped; the error was reported once. */
|
||||
| { readonly status: "failed"; readonly attempt: number }
|
||||
| { readonly status: "disposed" }
|
||||
|
||||
export type WorkerEvent<T> =
|
||||
/** The view received new bytes: a newly opened or reloaded file. */
|
||||
| { readonly type: "bytes.changed"; readonly bytes: Uint8Array }
|
||||
/** `details` are the facts about the file the toolbar shows, when the viewer knows them at open. */
|
||||
| {
|
||||
readonly type: "open.succeeded"
|
||||
readonly attempt: number
|
||||
readonly value: T
|
||||
readonly details: readonly string[] | undefined
|
||||
}
|
||||
/** The worker could not open the bytes, or its open call rejected. */
|
||||
| { readonly type: "open.failed"; readonly attempt: number }
|
||||
| { readonly type: "open.timed-out"; readonly attempt: number }
|
||||
/** The worker raised `error` or `messageerror`: it is gone, with whatever it showed. */
|
||||
| { readonly type: "worker.crashed"; readonly attempt: number }
|
||||
| { readonly type: "disposed" }
|
||||
|
||||
export type WorkerEffect =
|
||||
/** Starts the attempt's worker and open timeout, and opens the bytes in it. */
|
||||
| { readonly type: "open-worker"; readonly attempt: number; readonly bytes: Uint8Array; readonly timeoutMs: number }
|
||||
| { readonly type: "cancel-open-timeout"; readonly attempt: number }
|
||||
/** Ends the attempt's timeout, aborts its calls and terminates its worker, which frees the engine's memory. */
|
||||
| { readonly type: "close-worker"; readonly attempt: number }
|
||||
| { readonly type: "report-details"; readonly details: readonly string[] }
|
||||
| { readonly type: "report-error" }
|
||||
|
||||
export type WorkerTransition<T> = { readonly state: WorkerState<T>; readonly effects: readonly WorkerEffect[] }
|
||||
|
||||
const NONE: readonly WorkerEffect[] = []
|
||||
|
||||
export function transitionWorker<T>(state: WorkerState<T>, event: WorkerEvent<T>): WorkerTransition<T> {
|
||||
if (state.status === "disposed") return { state, effects: NONE }
|
||||
|
||||
if (event.type === "disposed") return { state: { status: "disposed" }, effects: closeActive(state) }
|
||||
|
||||
if (event.type === "bytes.changed") {
|
||||
const attempt = (state.status === "idle" ? 0 : state.attempt) + 1
|
||||
|
||||
return {
|
||||
state: { status: "opening", attempt },
|
||||
effects: [
|
||||
...closeActive(state),
|
||||
{ type: "open-worker", attempt, bytes: event.bytes, timeoutMs: WORKER_OPEN_TIMEOUT_MS },
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
// A failed attempt reported its error once: the open call that rejects after a crash, or a reply after a timeout,
|
||||
// changes nothing.
|
||||
if (state.status === "idle" || state.status === "failed" || event.attempt !== state.attempt)
|
||||
return { state, effects: NONE }
|
||||
|
||||
if (event.type === "worker.crashed")
|
||||
return {
|
||||
state: { status: "failed", attempt: state.attempt },
|
||||
effects: [...closeActive(state), { type: "report-error" }],
|
||||
}
|
||||
|
||||
if (state.status !== "opening") return { state, effects: NONE }
|
||||
|
||||
if (event.type === "open.succeeded") {
|
||||
const settled: WorkerEffect = { type: "cancel-open-timeout", attempt: state.attempt }
|
||||
|
||||
return {
|
||||
state: { status: "open", attempt: state.attempt, value: event.value },
|
||||
effects: event.details ? [settled, { type: "report-details", details: event.details }] : [settled],
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
state: { status: "failed", attempt: state.attempt },
|
||||
effects: [{ type: "close-worker", attempt: state.attempt }, { type: "report-error" }],
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether the viewer shows its loader: until the file opens, and never once it failed. */
|
||||
export function workerLoading<T>(state: WorkerState<T>) {
|
||||
return state.status === "idle" || state.status === "opening"
|
||||
}
|
||||
|
||||
/** The open file, one object per attempt, so a viewer keyed on it mounts afresh for a reloaded file. */
|
||||
export function workerOpened<T>(state: WorkerState<T>) {
|
||||
return state.status === "open" ? state : undefined
|
||||
}
|
||||
|
||||
function closeActive<T>(state: Exclude<WorkerState<T>, { status: "disposed" }>): readonly WorkerEffect[] {
|
||||
return state.status === "opening" || state.status === "open"
|
||||
? [{ type: "close-worker", attempt: state.attempt }]
|
||||
: NONE
|
||||
}
|
||||
Reference in New Issue
Block a user