Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion apps/extension/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
"typecheck": "tsc -p tsconfig.json"
},
"dependencies": {
"@mdbase-dev/ui": "0.1.0-beta.123",
"@mdbase-dev/ui": "0.1.0-beta.124",
"@mdbase-reader/connect": "workspace:*",
"@mdbase-reader/core": "workspace:*",
"@mdbase-reader/platform": "workspace:*",
Expand Down
2 changes: 1 addition & 1 deletion apps/reader/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
},
"dependencies": {
"@citation-js/plugin-csl": "0.8.2",
"@mdbase-dev/ui": "0.1.0-beta.123",
"@mdbase-dev/ui": "0.1.0-beta.124",
"@mdbase-reader/connect": "workspace:*",
"@mdbase-reader/core": "workspace:*",
"@mdbase-reader/markdown-editor": "workspace:*",
Expand Down
2 changes: 2 additions & 0 deletions apps/reader/src/ReaderHeader.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { AppSwitcher } from "@mdbase-dev/ui/app-switcher";
import { shortcutLabel } from "@mdbase-dev/ui/command-palette";
import { useMdbaseMarkBusy } from "@mdbase-dev/ui/mark-activity";

import { CollectionPicker } from "./CollectionPicker.js";
import { DisplayMenu } from "./DisplayMenu.js";
Expand Down Expand Up @@ -204,6 +205,7 @@ function ConnectionState({
readonly directAccess: ReaderDirectAccessState;
}): JSX.Element {
const { snapshot, working, problem, request } = directAccess;
useMdbaseMarkBusy(state === "syncing" && "stream");
if (snapshot?.authority !== "connector" || state !== "connected") {
return <PlainConnectionState state={state} />;
}
Expand Down
17 changes: 13 additions & 4 deletions apps/reader/src/import-controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import {
type MigrationResult,
} from "@mdbase-reader/migration";

import { markFraction, withMarkProgress } from "./mark-activity.js";

import type { ReaderApplicationSession } from "@mdbase-reader/connect";
export interface ImportState {
plan: MigrationPlan | null;
Expand Down Expand Up @@ -150,10 +152,17 @@ export class ImportController {
this.update({ boundTarget: target.collectionId });
void this.task(async (signal) => {
this.update({ result: null });
const result = await runMigration(plan, target, signal, (progress) => {
this.update({ progress, message: `${progress.phase} — ${name}` });
saveProgress(plan.service, progress);
});
// The mark fills with the import and plays saved or error when it ends; a stop is quiet.
const result = await withMarkProgress(
(mark) =>
runMigration(plan, target, signal, (progress) => {
mark(markFraction(progress.completed, progress.total));
this.update({ progress, message: `${progress.phase} — ${name}` });
saveProgress(plan.service, progress);
}),
undefined,
signal,
);
this.client?.forget();
this.update({
result,
Expand Down
132 changes: 132 additions & 0 deletions apps/reader/src/mark-activity.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
/* eslint-disable @typescript-eslint/require-await -- the work under test is async by contract */
import { getMdbaseMarkActivity, resetMdbaseMarkActivity } from "@mdbase-dev/ui/mark-activity";
import { sourceId, type SourceSummary } from "@mdbase-reader/core";
import { afterEach, beforeEach, describe, expect, it } from "vitest";

import { markFraction, withMarkProgress } from "./mark-activity.js";
import { eachSource } from "./use-library-writes.js";

import type { BulkStatusProgress } from "./LibraryBulkBar.js";

const mark = (): ReturnType<typeof getMdbaseMarkActivity> => getMdbaseMarkActivity();

beforeEach(() => resetMdbaseMarkActivity());
afterEach(() => resetMdbaseMarkActivity());

describe("withMarkProgress", () => {
it("fills the mark while the work reports progress, then plays saved", async () => {
let seen: number | null = null;
const result = await withMarkProgress(async (update) => {
update(0.4);
seen = mark().progress;
return "done";
});
expect(result).toBe("done");
expect(seen).toBe(0.4);
expect(mark().progress).toBeNull();
expect(mark().signal?.kind).toBe("saved");
});

it("ends the way the result says", async () => {
await withMarkProgress(
async () => null,
() => "fail",
);
expect(mark()).toMatchObject({ progress: null, signal: { kind: "error" } });
resetMdbaseMarkActivity();
await withMarkProgress(
async () => null,
() => "cancel",
);
expect(mark()).toMatchObject({ progress: null, signal: null });
});

it("plays error when the work throws, and rethrows", async () => {
await expect(
withMarkProgress(async () => {
throw new Error("offline");
}),
).rejects.toThrow("offline");
expect(mark()).toMatchObject({ progress: null, signal: { kind: "error" } });
});

it("stops quietly when the work was aborted", async () => {
const controller = new AbortController();
await expect(
withMarkProgress(
async () => {
controller.abort();
throw new DOMException("Stopped", "AbortError");
},
undefined,
controller.signal,
),
).rejects.toThrow("Stopped");
expect(mark()).toMatchObject({ progress: null, signal: null });
});

it("never leaves the mark filling when deciding the outcome throws", async () => {
await expect(
withMarkProgress(
async () => 1,
() => {
throw new Error("bad outcome");
},
),
).rejects.toThrow("bad outcome");
expect(mark().progress).toBeNull();
});
});

describe("markFraction", () => {
it("is the share done, and nothing of nothing", () => {
expect(markFraction(3, 4)).toBe(0.75);
expect(markFraction(0, 0)).toBe(0);
});
});

describe("a bulk library update on the mark", () => {
const sources = ["a", "b", "c", "d"].map(
(id) => ({ id: sourceId(id) }) as unknown as SourceSummary,
);

it("fills with each source written and plays saved when all succeed", async () => {
const fills: (number | null)[] = [];
const reports: BulkStatusProgress[] = [];
await eachSource(
sources,
(value) => {
reports.push(value);
fills.push(mark().progress);
},
async () => undefined,
);
expect(reports.at(-1)).toEqual({ done: 4, total: 4, failed: 0 });
expect(fills).toEqual([0.25, 0.5, 0.75, 1]);
expect(mark()).toMatchObject({ progress: null, signal: { kind: "saved" } });
});

it("plays error when any source could not be updated", async () => {
const reports: BulkStatusProgress[] = [];
await eachSource(
sources,
(value) => reports.push(value),
async (source) => {
if (source.id === sourceId("c")) {
throw new Error("conflict");
}
},
);
expect(reports.at(-1)).toEqual({ done: 4, total: 4, failed: 1 });
expect(mark()).toMatchObject({ progress: null, signal: { kind: "error" } });
});

it("leaves the mark alone for an empty selection", async () => {
await eachSource(
[],
() => undefined,
async () => undefined,
);
expect(mark()).toMatchObject({ progress: null, signal: null });
});
});
37 changes: 37 additions & 0 deletions apps/reader/src/mark-activity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { trackMdbaseMarkProgress } from "@mdbase-dev/ui/mark-activity";

/** How a tracked operation ends on the mark: `finish` plays saved, `fail` plays error. */
export type MarkProgressOutcome = "finish" | "fail" | "cancel";

/**
* Shows `work`'s known progress on the app mark and always ends it. A result is ended by
* `outcome` (finished by default); a throw fails it, or cancels it quietly once `signal` is
* aborted, so a stopped operation never shakes the mark.
*/
export async function withMarkProgress<T>(
work: (update: (fraction: number) => void) => Promise<T>,
outcome: (result: T) => MarkProgressOutcome = () => "finish",
signal?: AbortSignal,
): Promise<T> {
const progress = trackMdbaseMarkProgress();
try {
const result = await work(progress.update);
progress[outcome(result)]();
return result;
} catch (reason) {
if (signal?.aborted) {
progress.cancel();
} else {
progress.fail();
}
throw reason;
} finally {
// Already ended above; this only guards against an `outcome` that throws.
progress.cancel();
}
}

/** `done` of `total` as a 0 to 1 fraction; nothing is done of nothing. */
export function markFraction(done: number, total: number): number {
return total > 0 ? done / total : 0;
}
11 changes: 10 additions & 1 deletion apps/reader/src/use-annotation-edit.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { signalMdbaseMark } from "@mdbase-dev/ui/mark-activity";
import { useEffect, useMemo, useState, useSyncExternalStore } from "react";

import { confirmAnnotationDiscard } from "./annotation-draft-actions.js";
Expand Down Expand Up @@ -79,8 +80,16 @@ export function useAnnotationEdit(props: AnnotationEditProps): AnnotationEditCon
if (locked || !session.ownsEditor(editorOwner) || !ready) {
return;
}
// Saving an already-saved annotation writes nothing, so the mark stays still.
const wrote = session.getSnapshot().status !== "saved";
void session.save().then(() => {
if (session.getSnapshot().status === "saved" && deletion.isMounted()) {
const after = session.getSnapshot();
if (wrote && after.status === "saved") {
signalMdbaseMark("saved");
} else if (wrote && (after.status === "error" || after.conflict)) {
signalMdbaseMark("error");
}
if (after.status === "saved" && deletion.isMounted()) {
onCancel();
}
});
Expand Down
23 changes: 13 additions & 10 deletions apps/reader/src/use-bibliography-export.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { signalMdbaseMark } from "@mdbase-dev/ui/mark-activity";
import { buildCslBibliography, serializeCslBibliography } from "@mdbase-reader/core";
import { useCallback, useMemo, useState } from "react";

Expand Down Expand Up @@ -27,33 +28,35 @@ export function useBibliographyExport(
readonly status: BibliographyExportStatus;
readonly message: string | null;
}>({ status: "idle", message: null });
const fail = useCallback((message: string): void => {
signalMdbaseMark("error");
setState({ status: "error", message });
}, []);
const save = useCallback(
(items: ReturnType<typeof buildCslBibliography>["items"]): void => {
if (!saveFile) {
setState({ status: "error", message: "File export is unavailable in this build." });
fail("File export is unavailable in this build.");
return;
}
if (items.length === 0) {
setState({ status: "error", message: "No valid citations are ready to export." });
fail("No valid citations are ready to export.");
return;
}
setState({ status: "exporting", message: null });
const contents = serializeCslBibliography(items);
void saveFile("references.json", new Blob([contents], { type: "application/json" }))
.then(() =>
.then(() => {
signalMdbaseMark("saved");
setState({
status: "success",
message: `Exported ${countLabel(items.length, "citation")}.`,
}),
)
});
})
.catch((reason: unknown) =>
setState({
status: "error",
message: readerErrorMessage(reason, "Reader could not export the bibliography."),
}),
fail(readerErrorMessage(reason, "Reader could not export the bibliography.")),
);
},
[saveFile],
[fail, saveFile],
);
const run = useCallback((): void => save(bibliography.items), [bibliography, save]);
const runFor = useCallback(
Expand Down
5 changes: 5 additions & 0 deletions apps/reader/src/use-citation-editor.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { signalMdbaseMark } from "@mdbase-dev/ui/mark-activity";
import {
citationCompletenessWarnings,
citekeyForCitation,
Expand Down Expand Up @@ -97,8 +98,12 @@ export function useCitationEditor(input: {
.then((updated) => {
input.onSaved(updated);
setStatusState({ sourceId: updated.id, value: "saved" });
// The editor's SaveNotice usually plays this too; the mark plays it once.
signalMdbaseMark("saved");
})
.catch((reason: unknown) => {
// The editor's SaveNotice never shows attention; the error is reported below the form.
signalMdbaseMark("error");
setStatusState({ sourceId: source.id, value: "idle" });
setErrorState({
sourceId: source.id,
Expand Down
18 changes: 14 additions & 4 deletions apps/reader/src/use-creation-saving.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { signalMdbaseMark } from "@mdbase-dev/ui/mark-activity";
import { useRef, useState, type RefObject } from "react";

import { saveAnnotationDraftToCollection } from "./annotation-draft-actions.js";
Expand Down Expand Up @@ -46,6 +47,12 @@ export function useCreationSaving(input: {
busy.current = false;
setSaving(false);
};
// The app mark confirms each annotation the person saves and shakes when one could not be.
const saved = (): void => signalMdbaseMark("saved");
const failed = (value: NonNullable<Problem>): void => {
signalMdbaseMark("error");
setProblem(value);
};
return {
busy,
saving,
Expand All @@ -72,8 +79,8 @@ export function useCreationSaving(input: {
},
value,
"",
() => undefined,
setProblem,
saved,
failed,
() => undefined,
);
},
Expand All @@ -83,12 +90,15 @@ export function useCreationSaving(input: {
return;
}
void saveAnnotationDraftToCollection(
() => buffer.clearIf(value),
() => {
buffer.clearIf(value);
saved();
},
value,
source,
surface,
create,
setProblem,
failed,
finish,
);
},
Expand Down
Loading