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
43 changes: 37 additions & 6 deletions packages/server/src/html.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,23 +89,45 @@ const RELOAD_ICON = `<svg viewBox="0 0 16 16" aria-hidden="true" fill="currentCo
export function sessionsStatus(fetchedAt: number, now: number): string {
return `<p class="status"><span class="muted" id="sessions-age">Updated ${formatAge(now - fetchedAt)}</span>`
+ '<span class="error" id="sessions-error" hidden>Update failed · retrying</span>'
+ '<span class="error" id="sessions-signed-out" hidden>Signed out · reload to sign in again</span>'
+ `<button type="button" class="reload" id="sessions-reload" title="Reload" aria-label="Reload">${RELOAD_ICON}</button></p>`;
}

/**
* Keeps the sessions page current without reloading it: swaps in `/sessions/body` every minute while the tab
* is visible, and from GitHub rather than the server's cache when the reload button asks. Needs SECTIONS_SCRIPT.
*
* An expired IAP sign-in answers with a redirect to Google, which a fetch cannot follow; only reloading the page
* signs in again. That happens on its own unless the reader is typing or away, and at most once per page load.
*/
export const SESSIONS_SCRIPT = `(() => {
const AUTO_MS = 60000;
const container = document.getElementById('sessions');
const age = document.getElementById('sessions-age');
const error = document.getElementById('sessions-error');
const reload = document.getElementById('sessions-reload');
if (!container || !age || !error || !reload) return;
const signedOutNote = document.getElementById('sessions-signed-out');
if (!container || !age || !error || !reload || !signedOutNote) return;
let loadedAt = Date.now();
let inFlight = false;
let failed = false;
let signedOut = false;
let reloaded = false;

const typing = () => {
const active = document.activeElement;
return !!active && (active.isContentEditable || ['INPUT', 'TEXTAREA', 'SELECT'].includes(active.tagName));
};
const signOut = () => {
signedOut = true;
if (!reloaded && document.visibilityState === 'visible' && !typing()) {
reloaded = true;
location.reload();
return;
}
age.hidden = true;
signedOutNote.hidden = false;
};

const formatAge = ${formatAge.toString()};
const tick = () => {
Expand All @@ -114,13 +136,17 @@ export const SESSIONS_SCRIPT = `(() => {
};

const refresh = async fresh => {
if (inFlight) return;
if (inFlight || signedOut) return;
// Swapping the content would take focus from the control a keyboard user is on; the next tick tries again.
if (!fresh && container.contains(document.activeElement)) return;
inFlight = true;
reload.setAttribute('aria-busy', 'true');
try {
const res = await fetch('/sessions/body' + (fresh ? '?fresh=1' : ''), { credentials: 'same-origin', cache: 'no-store' });
const res = await fetch('/sessions/body' + (fresh ? '?fresh=1' : ''), { credentials: 'same-origin', cache: 'no-store', redirect: 'manual' });
if (res.type === 'opaqueredirect' || res.status === 401) {
signOut();
return;
}
if (!res.ok) throw new Error('HTTP ' + res.status);
const template = document.createElement('template');
template.innerHTML = await res.text();
Expand All @@ -135,19 +161,24 @@ export const SESSIONS_SCRIPT = `(() => {
} finally {
inFlight = false;
reload.removeAttribute('aria-busy');
error.hidden = !failed;
error.hidden = !failed || signedOut;
tick();
}
};

const due = () => failed || Date.now() - loadedAt >= AUTO_MS;
reload.addEventListener('click', () => refresh(true));
reload.addEventListener('click', () => {
if (signedOut) location.reload();
else refresh(true);
});
setInterval(() => {
tick();
if (document.visibilityState === 'visible' && due()) refresh(false);
}, 15000);
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'visible' && due()) refresh(false);
if (document.visibilityState !== 'visible') return;
if (signedOut) signOut();
else if (due()) refresh(false);
});
})();
`;
Expand Down
4 changes: 4 additions & 0 deletions packages/server/tests/http.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -469,6 +469,10 @@ describe('pull requests awaiting review', () => {
expect(sessionsScript.headers.get('content-type')).toContain('javascript');
expect(sessionsScript.body).toContain("'/sessions/body' + (fresh ? '?fresh=1' : '')");
expect(sessionsScript.body).toContain('applySections(template.content)');
expect(sessionsScript.body).toContain("redirect: 'manual'");
expect(sessionsScript.body).toContain("res.type === 'opaqueredirect' || res.status === 401");
expect(sessionsScript.body).toContain('location.reload()');
expect(page).toContain('<span class="error" id="sessions-signed-out" hidden>Signed out · reload to sign in again</span>');
const script = await api('/sections.js');
expect(script.headers.get('content-type')).toContain('javascript');
expect(script.body).toContain('localStorage');
Expand Down
41 changes: 41 additions & 0 deletions packages/ui/src/components/layout/signed-out-banner.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { useEffect, useSyncExternalStore } from 'react';
import { isSignedOut, reloadIfSafe, subscribeSignedOut } from '../../lib/sign-in';

export function SignedOutBanner() {
const signedOut = useSyncExternalStore(subscribeSignedOut, isSignedOut, () => false);

useEffect(() => {
if (!signedOut) {
return;
}
reloadIfSafe();
const onVisibility = () => {
if (document.visibilityState === 'visible') {
reloadIfSafe();
}
};
document.addEventListener('visibilitychange', onVisibility);
return () => document.removeEventListener('visibilitychange', onVisibility);
}, [signedOut]);

if (!signedOut) {
return null;
}

return (
<div
role="alert"
data-testid="signed-out-banner"
className="fixed top-0 inset-x-0 z-50 flex items-center gap-2 px-4 py-2 border-b border-deleted/40 bg-bg-secondary text-xs text-text"
>
<span className="font-medium">Your sign-in expired. Reload to sign in again.</span>
<button
type="button"
onClick={() => window.location.reload()}
className="px-2 py-0.5 rounded border border-accent/60 text-accent hover:bg-accent/15 cursor-pointer"
>
Reload
</button>
</div>
);
}
3 changes: 2 additions & 1 deletion packages/ui/src/hooks/use-tab-badge.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { useEffect, useRef } from 'react';
import { addBadge, titleWithCount, toHref } from '../lib/favicon-badge';
import { apiRequest } from '../lib/request';

/** Marks the browser tab and its title while `count` answers wait unseen. */
export function useTabBadge(count: number): void {
Expand Down Expand Up @@ -37,7 +38,7 @@ export function useTabBadge(count: number): void {
if (plainSvg.current !== null) {
badge(plainSvg.current);
} else {
void fetch(href)
void apiRequest(href)
.then(res => (res.ok ? res.text() : Promise.reject(new Error(res.statusText))))
.then(svg => {
plainSvg.current = svg;
Expand Down
9 changes: 5 additions & 4 deletions packages/ui/src/lib/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import type {
Tour,
} from '@diffity/api';
import { apiPath } from './base';
import { apiRequest } from './request';

export type {
GitHubDetails,
Expand All @@ -29,15 +30,15 @@ export type {
} from '@diffity/api';

async function apiFetch<T>(url: string, init?: RequestInit): Promise<T> {
const res = await fetch(apiPath(url), init);
const res = await apiRequest(apiPath(url), init);
if (!res.ok) {
throw new Error(await errorMessage(res));
}
return res.json();
}

async function apiVoid(url: string, init?: RequestInit): Promise<void> {
const res = await fetch(apiPath(url), init);
const res = await apiRequest(apiPath(url), init);
if (!res.ok) {
throw new Error(await errorMessage(res));
}
Expand Down Expand Up @@ -71,7 +72,7 @@ export function fetchRepoInfo(): Promise<RepoInfoResponse> {
}

export async function fetchThreads(sessionId: string, status?: ThreadStatus): Promise<CommentThread[]> {
const res = await fetch(apiPath(buildUrl('/api/threads', { session: sessionId, status })));
const res = await apiRequest(apiPath(buildUrl('/api/threads', { session: sessionId, status })));
if (!res.ok) {
return [];
}
Expand Down Expand Up @@ -135,7 +136,7 @@ export async function fetchFileContent(filePath: string): Promise<string[]> {
}

export async function fetchGitHubDetails(): Promise<GitHubDetails | null> {
const res = await fetch(apiPath('/api/github/details'));
const res = await apiRequest(apiPath('/api/github/details'));
if (!res.ok) {
return null;
}
Expand Down
25 changes: 25 additions & 0 deletions packages/ui/src/lib/request.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { markSignedOut, writeSettled, writeStarted } from './sign-in';

/**
* The server never redirects these requests; a redirect is IAP sending an expired sign-in to Google, which
* a fetch cannot follow. A 401 is diffity's own sign-in gone. A write may hold the reader's only copy of their
* text, so while one is under way, or after one failed this way, the page must not reload on its own.
*/
export async function apiRequest(url: string, init?: RequestInit): Promise<Response> {
const write = (init?.method ?? 'GET').toUpperCase() !== 'GET';
if (write) {
writeStarted();
}
try {
const res = await fetch(url, { ...init, redirect: 'manual' });
if (res.type === 'opaqueredirect' || res.status === 401) {
markSignedOut({ lostWrite: write });
throw new Error('Signed out');
}
return res;
} finally {
if (write) {
writeSettled();
}
}
}
87 changes: 87 additions & 0 deletions packages/ui/src/lib/sign-in.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
let signedOut = false;
let reloaded = false;
let lostWrite = false;
let writesInFlight = 0;
const listeners = new Set<() => void>();

export function isSignedOut(): boolean {
return signedOut;
}

export function markSignedOut(cause: { lostWrite?: boolean } = {}): void {
lostWrite ||= !!cause.lostWrite;
if (signedOut) {
return;
}
signedOut = true;
for (const listener of listeners) {
listener();
}
}

export function writeStarted(): void {
writesInFlight++;
}

export function writeSettled(): void {
writesInFlight--;
}

export function subscribeSignedOut(listener: () => void): () => void {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
}

export interface PageState {
visible: boolean;
/** Something the reader typed that a reload would throw away. */
hasDraft: boolean;
editing: boolean;
/** A save is under way, or failed on the expired sign-in; its text may live only in memory. */
unsavedWrite: boolean;
}

export function shouldAutoReload(state: PageState, alreadyReloaded: boolean): boolean {
return !alreadyReloaded && !state.unsavedWrite && state.visible && !state.hasDraft && !state.editing;
}

const TEXT_INPUT_TYPES = new Set(['', 'text', 'search', 'email', 'url', 'tel', 'password', 'number']);

export function readPageState(doc: Document = document): PageState {
const fields = [
...doc.querySelectorAll('textarea'),
...[...doc.querySelectorAll('input')].filter(input => TEXT_INPUT_TYPES.has(input.getAttribute('type')?.toLowerCase() ?? '')),
];
const active = doc.activeElement;
const editing = active instanceof HTMLElement
&& (active.isContentEditable || active instanceof HTMLInputElement || active instanceof HTMLTextAreaElement || active instanceof HTMLSelectElement);
return {
visible: doc.visibilityState === 'visible',
hasDraft: fields.some(field => field.value.trim() !== ''),
Comment thread
Copilot marked this conversation as resolved.
Resolved
editing,
unsavedWrite: lostWrite || writesInFlight > 0,
};
}

/**
* An expired IAP sign-in can only be renewed by loading the page again. Does that once per page load, and
* only when nothing the reader is in the middle of would be lost.
*/
export function reloadIfSafe(reload: () => void = () => window.location.reload(), state: PageState = readPageState()): boolean {
if (!shouldAutoReload(state, reloaded)) {
return false;
}
reloaded = true;
reload();
return true;
}

export function resetSignInForTests(): void {
signedOut = false;
reloaded = false;
lostWrite = false;
writesInFlight = 0;
listeners.clear();
}
2 changes: 2 additions & 0 deletions packages/ui/src/root.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { Toaster } from "sonner";
import NProgress from "nprogress";
import { queryClient } from "./lib/query-client";
import { ErrorPage } from "./components/error-page";
import { SignedOutBanner } from "./components/layout/signed-out-banner";
import { pagePath } from "./lib/base";
import "nprogress/nprogress.css";
import "./styles/app.css";
Expand Down Expand Up @@ -57,6 +58,7 @@ export default function App() {
<QueryClientProvider client={queryClient}>
<NavigationProgress />
<Outlet />
<SignedOutBanner />
<Toaster
position="bottom-right"
toastOptions={{
Expand Down
Loading
Loading