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
16 changes: 10 additions & 6 deletions apps/portal/src/ConnectApp.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1264,13 +1264,14 @@ describe("ConnectApp", () => {
expect(calls("/v1/ui-configuration")).toBe(1);
});

it("uses one overview read when a visibility refresh settles before the paired focus event", async () => {
it.each(["visibilitychange", "focus"] as const)("uses one overview read after %s and its paired event", async first => {
render(<ConnectApp />);
await settle();
fireEvent(document, new Event("visibilitychange"));
await settle();
fireEvent(window, new Event("focus"));
await settle();
const events = first === "focus" ? ["focus", "visibilitychange"] : ["visibilitychange", "focus"];
for (const event of events) {
fireEvent(event === "focus" ? window : document, new Event(event));
await settle();
}
expect(overviewReads()).toEqual(["", omitted]);
});

Expand Down Expand Up @@ -1419,7 +1420,7 @@ describe("ConnectApp", () => {
const older = structuredClone(overview);
let resolveOlder: ((response: Response) => void) | undefined;
let overviewCall = 0;
vi.spyOn(document, "visibilityState", "get").mockReturnValue("visible");
const visibility = vi.spyOn(document, "visibilityState", "get").mockReturnValue("visible");
vi.mocked(fetch).mockImplementation(async (input) => {
const path = new URL(String(input)).pathname;
if (path === "/v1/account/sessions") return Response.json({ sessions: [] });
Expand All @@ -1442,6 +1443,9 @@ describe("ConnectApp", () => {
await act(async () => resolveOlder?.(Response.json(older)));
expect(await screen.findByRole("heading", { name: "Garden notes" })).toBeInTheDocument();

visibility.mockReturnValue("hidden");
fireEvent(document, new Event("visibilitychange"));
visibility.mockReturnValue("visible");
fireEvent(document, new Event("visibilitychange"));
expect(await screen.findByRole("heading", { name: "Newest collection" })).toBeInTheDocument();
expect(overviewCall).toBe(2);
Expand Down
22 changes: 11 additions & 11 deletions apps/portal/src/ConnectApp.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ import "@mdbase-dev/ui/feedback.css";
import { Select } from "@mdbase-dev/ui/select";
import { literal } from "./literal";
import { usePortalCommands } from "./portal-commands";
import { NativeStorageReads, useOverviewRefresh } from "./overview-refresh";
import { announceCollectionDeletion, NativeStorageReads, useOverviewRefresh } from "./overview-refresh";

type MemberRole = "viewer" | "editor";

Expand Down Expand Up @@ -118,7 +118,7 @@ function ConnectWorkspace({ onFeedbackContext }: { onFeedbackContext(view: Conne
const [busy, setBusy] = useState<ReadonlySet<string>>(() => new Set());
const busyRef = useRef(new Set<string>());
const refreshGenerationRef = useRef(0);
const refreshInFlightRef = useRef<{ promise: Promise<void>; signal: AbortSignal; nativeStorage: boolean } | null>(null);
const refreshInFlightRef = useRef<{ promise: Promise<void>; signal: AbortSignal; nativeStorage: boolean; mutationRevision: number } | null>(null);
const nativeStorageRef = useRef(new NativeStorageReads());
const mutationRevisionRef = useRef(0);
const optimisticRef = useRef(new Map<string, OptimisticAction>());
Expand Down Expand Up @@ -148,14 +148,14 @@ function ConnectWorkspace({ onFeedbackContext }: { onFeedbackContext(view: Conne
const refresh = useCallback((signal = lifecycleRef.current?.signal, animate = false, storageAgeMs?: number): Promise<void> => {
if (accountDeleted || !signal || signal.aborted) return Promise.resolve();
const nativeStorage = nativeStorageRef.current.due(storageAgeMs);
const mutationRevision = mutationRevisionRef.current;
const pending = refreshInFlightRef.current;
if (pending && !pending.signal.aborted) {
if (pending.nativeStorage || !nativeStorage) return pending.promise;
if (pending.mutationRevision === mutationRevision && (pending.nativeStorage || !nativeStorage)) return pending.promise;
return pending.promise.then(() => refresh(signal, animate, storageAgeMs));
}
setRefreshing(true);
const generation = ++refreshGenerationRef.current;
const mutationRevision = mutationRevisionRef.current;
const isCurrent = () => !signal.aborted && !lifecycleRef.current?.signal.aborted
&& generation === refreshGenerationRef.current && mutationRevision === mutationRevisionRef.current;
const failed = (reason: unknown) => {
Expand Down Expand Up @@ -201,7 +201,7 @@ function ConnectWorkspace({ onFeedbackContext }: { onFeedbackContext(view: Conne
});
}
})().catch(failed);
refreshInFlightRef.current = { promise: request, signal, nativeStorage };
refreshInFlightRef.current = { promise: request, signal, nativeStorage, mutationRevision };
const settled = () => {
if (refreshInFlightRef.current?.promise === request) {
refreshInFlightRef.current = null;
Expand All @@ -212,13 +212,12 @@ function ConnectWorkspace({ onFeedbackContext }: { onFeedbackContext(view: Conne
return request;
}, [accountDeleted]);

useOverviewRefresh(refresh, view);

function refreshAfterMutation(animate = false): Promise<void> {
const refreshAfterMutation = useCallback((animate = false): Promise<void> => {
mutationRevisionRef.current++;
const lifecycle = lifecycleRef.current?.signal;
return (refreshInFlightRef.current?.promise ?? Promise.resolve()).then(() => refresh(lifecycle, animate));
}
return refresh(undefined, animate);
}, [refresh]);

useOverviewRefresh(refresh, refreshAfterMutation, view);

useEffect(() => {
const update = () => setView(viewFromPath());
Expand Down Expand Up @@ -978,6 +977,7 @@ function DeleteCollectionDialog({ open, error, collection, busy, returnFocusRef,
async options => {
if (native) await management.deleteNativeCollection(collection.id, target.name, options);
else await management.deleteHostedCollection(collection.id, options);
announceCollectionDeletion();
},
false,
undefined,
Expand Down
1 change: 0 additions & 1 deletion apps/portal/src/authorization.css
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,6 @@
/* The list grows with the page. A nested box sized to the gap above the sticky
footer left room for one row on short windows; search narrows long lists. */
.collection-picker-list { border-block: 1px solid var(--line); }
.collection-picker input::placeholder { color: var(--color-text-muted); }
.collection-picker-option > span[aria-hidden] { min-width: 0; }
.installation-additional-collection { padding-right: var(--space-3); }
.installation-additional-collection label { display: flex; align-items: center; gap: var(--space-3); min-width: 0; }
Expand Down
36 changes: 26 additions & 10 deletions apps/portal/src/overview-refresh.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,14 @@ import type { ConnectView } from "./ConnectPrimitives";

/** `storageAgeMs`: include storage when the last successful storage read is at least this old. */
type Refresh = (signal?: AbortSignal, animate?: boolean, storageAgeMs?: number) => Promise<void>;
const collectionDeletionChannel = "mdbase-connect:collection-deleted";

export function announceCollectionDeletion(): void {
if (typeof BroadcastChannel === "undefined") return;
const channel = new BroadcastChannel(collectionDeletionChannel);
channel.postMessage(null);
channel.close();
}

/**
* Each native storage read wakes every held collection's log, so reads are
Expand All @@ -30,7 +38,7 @@ export class NativeStorageReads {
}

/** Refreshes on load, while visible, and when Account or Apps opens. */
export function useOverviewRefresh(refresh: Refresh, view: ConnectView): void {
export function useOverviewRefresh(refresh: Refresh, invalidate: () => Promise<void>, view: ConnectView): void {
useEffect(() => {
const controller = new AbortController();
void refresh(controller.signal, false, 0);
Expand All @@ -39,24 +47,25 @@ export function useOverviewRefresh(refresh: Refresh, view: ConnectView): void {
};
const refreshWhenVisible = whenVisible();
const refreshStorageWhenVisible = whenVisible(30_000);
let visibleAt = -Infinity;
const onVisibility = () => {
if (document.visibilityState !== "visible") return;
visibleAt = performance.now();
let resumedAt = -Infinity;
// Browsers can dispatch focus and visibility in either order on return.
const onResume = () => {
if (document.visibilityState !== "visible" || performance.now() - resumedAt < 250) return;
resumedAt = performance.now();
refreshStorageWhenVisible();
};
// Browsers often dispatch both events when returning to a tab.
const onFocus = () => {
if (performance.now() - visibleAt >= 250) refreshStorageWhenVisible();
const onVisibility = () => {
if (document.visibilityState === "hidden") resumedAt = -Infinity;
else onResume();
};
const timer = window.setInterval(refreshWhenVisible, 15_000);
document.addEventListener("visibilitychange", onVisibility);
window.addEventListener("focus", onFocus);
window.addEventListener("focus", onResume);
window.addEventListener("online", refreshWhenVisible);
return () => {
controller.abort();
document.removeEventListener("visibilitychange", onVisibility);
window.removeEventListener("focus", onFocus);
window.removeEventListener("focus", onResume);
window.removeEventListener("online", refreshWhenVisible);
window.clearInterval(timer);
};
Expand All @@ -66,4 +75,11 @@ export function useOverviewRefresh(refresh: Refresh, view: ConnectView): void {
if (view === "account") void refresh(undefined, false, 0);
if (view === "applications") void refresh();
}, [view, refresh]);

useEffect(() => {
if (view !== "applications" || typeof BroadcastChannel === "undefined") return;
const channel = new BroadcastChannel(collectionDeletionChannel);
channel.onmessage = () => { void invalidate(); };
return () => channel.close();
}, [view, invalidate]);
}
9 changes: 9 additions & 0 deletions apps/portal/src/styles.css
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,15 @@ body,
min-height: 100%;
}

:root {
--color-placeholder: var(--color-text-muted);
--portal-control-border: color-mix(in oklch, var(--color-text-muted) 80%, var(--color-surface));
}

:where(.mdbase-field, .mdbase-select, .mdbase-checkbox, .mdbase-switch) {
--color-border-strong: var(--portal-control-border);
}

.page-brand {
display: flex;
align-items: center;
Expand Down
19 changes: 19 additions & 0 deletions apps/portal/tests/review/scenarios.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,8 @@ const definitions = [
["signup-agreements", "/signup#verification=review-email", "Create an account", 0, state => { state.signedIn = false; }],
["forgot-password", "/forgot-password", "Reset your password", 0, state => { state.signedIn = false; }],
["reset-password", "/reset-password#reset=review-reset", "Choose a new password", 0, state => { state.signedIn = false; }],
["unsubscribe", "/unsubscribe#unsubscribe=review-email", "Unsubscribe from mdbase email", 0, state => { state.signedIn = false; }],
["device-approval", "/device", "Approval code", 0],
["onboarding-pending", "/getting-started", "Creating your first collection", 0, state => { state.onboarding = "pending"; }],
["onboarding-failed", "/getting-started", "We couldn't create your collection", 0, state => { state.onboarding = "failed"; }],
["empty-account", "/collections", "No collections", 0],
Expand Down Expand Up @@ -154,9 +156,26 @@ const definitions = [
["collection-overview", "/?collection=hosted-0", "Shared research library", 5],
["collection-storage", "/storage?collection=hosted-0", "Storage", 5],
["collection-access", "/access?collection=hosted-0", "Sam Okafor", 5],
["collection-invitation", "/access?collection=hosted-0", "researcher@example.com", 5, state => {
state.invitations["hosted-0"] = [{ id: "invite-researcher", collection_id: "hosted-0", target_mode: "email",
submitted_email: "researcher@example.com", role: "viewer", state: "pending", created_at: clock, expires_at: expires }];
}],
["applications", "/applications", "Apps", 5],
["app-installations", "/applications", "TaskNotes", 5, state => {
state.overview.installation_access = [{ application_id: "app-0", application_family_id: "app-0", application_name: "TaskNotes",
icon: null, application_origin: "https://tasknotes.mdbase.dev", device_kind: "app-runtime", created_at: clock,
connector_id: "connector-tasknotes", installation_id: "installation-tasknotes", create_collections: false,
collection_id: "collection-0", collection_name: "Field research", sync: "cloud_copy", available: true,
role: "owner", approved_optional_file_actions: [] }];
}],
["computers", "/computers", "Computers", 5],
["account-sessions", "/account", "Travel Safari", 5],
["account-deleted", "/account-deleted", "Your account has been deleted", 0, state => { state.signedIn = false; }],
["account-billing", "/account", "Manage billing", 5, state => {
state.account.backend = "next";
state.overview.billing = { available: true, plus: { status: "canceled", current_period_end: expires,
cancels_at: null, access_ends_at: expires } };
}],
["feedback", "/feedback", "Send feedback", 5],
["computer-offline", "/storage?collection=collection-2", "Storage", 5],
["revoking", "/storage?collection=hosted-0", "Disconnecting…", 5, state => { state.overview.hosted_collections[0].replicas[0].revocation_status = "revoking"; state.overview.grants[0].revocation_status = "revoking"; }],
Expand Down
2 changes: 1 addition & 1 deletion apps/portal/tests/review/server.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ export function reviewServer({ editorUrl = process.env.REVIEW_EDITOR_URL ?? "htt
if (path === "/v1/account/sessions" && method === "GET") return send({ sessions: state.sessions });
if (path === "/v1/account/sessions/revoke-others" && method === "POST") { state.sessions = state.sessions.filter(session => session.current); return send({ ok: true }); }
if (path.startsWith("/v1/account/sessions/") && method === "DELETE") { state.sessions = state.sessions.filter(session => session.id !== path.split("/").at(-1)); return send({ ok: true }); }
if (path === "/v1/account" && method === "GET") return send({ ...account(data), authentication: state.account.authentication, email_preferences: state.account.email_preferences });
if (path === "/v1/account" && method === "GET") return send({ ...account(data), backend: state.account.backend, authentication: state.account.authentication, email_preferences: state.account.email_preferences });
if (path === "/v1/account/email-preferences" && method === "PATCH") { Object.assign(state.account.email_preferences, body); return send({ email_preferences: state.account.email_preferences }); }
if (path === "/v1/account/password" && method === "PATCH") {
state.account.authentication.password.configured = true;
Expand Down
Loading
Loading