fndn/ui

Showcase

Web browser

A browser window: tabs that open, close and load, an address bar with suggestions, bookmarks, downloads, a main menu, and History and Settings pages.

Source

Only the system's components and token utilities; the layout is Tailwind.

showcases/web-browser/App.tsx
1/* A browser window: tabs that open, close and load; back, forward and reload; an address bar with
2 * suggestions; bookmarks; downloads; a main menu; History and Settings pages. All state lives here,
3 * the pieces are in toolbar.tsx and pages.tsx.
4 *
5 * Keyboard: Ctrl/⌘+L focuses the address bar. A real browser keeps Ctrl/⌘+T, W and Tab for itself,
6 * so the window also answers to Alt+T (new tab), Alt+W (close), Alt+Shift+T (reopen), Alt+1…9
7 * (switch), Alt+Y (history); Ctrl+T, W and Tab still work where the host lets them through.
8 * In the tab strip, arrows move between tabs and Delete closes the focused one (the Tabs' own).
9 *
10 * The layout: closable pill tabs in a header row over the toolbar, the bookmarks bar and the page.
11 * The first icon of every row (a tab's favicon, Back, the first bookmark) stands on one line, 14px
12 * from the window's edge. On a phone no strip: a tab-count button opens the open tabs as a sheet. */
13import { useEffect, useRef, useState, type KeyboardEvent, type MouseEvent } from "react";
14import { Progress, ScrollArea, Spinner, Tabs, Tooltip, Button } from "@fndn/react";
15import { Plus } from "@phosphor-icons/react";
16import { BOOKMARKS, CLI_DOWNLOAD, ENGINES, HISTORY, HOME, SETTINGS, VISITS, resolve, siteOf, type Visit } from "./data";
17import { Favicon, Page, type Settings } from "./pages";
18import { AddressBar, BookmarksBar, BrowserMenu, Downloads, NavButtons, TabSwitcher, suggestionsFor, useDownloads } from "./toolbar";
19
20type Tab = {
21 id: string;
22 /** The tab's own history: back and forward move `at` along it. */
23 stack: string[];
24 at: number;
25 loading: boolean;
26 /** The page on screen: the previous one stays until the next has loaded. */
27 page: string;
28};
29
30const urlOf = (tab: Tab) => tab.stack[tab.at] ?? HOME;
31const now = () => new Date().toTimeString().slice(0, 5);
32let seq = 3;
33
34export default function App() {
35 const [tabs, setTabs] = useState<Tab[]>([
36 { id: "t1", stack: ["harbor.dev/docs/getting-started"], at: 0, loading: false, page: "harbor.dev/docs/getting-started" },
37 { id: "t2", stack: ["status.harbor.dev"], at: 0, loading: false, page: "status.harbor.dev" },
38 { id: "t3", stack: ["fieldnotes.app/northwind/q4-planning"], at: 0, loading: false, page: "fieldnotes.app/northwind/q4-planning" },
39 ]);
40 const [active, setActive] = useState("t1");
41 const [closed, setClosed] = useState<Tab[]>([]);
42 const [settings, setSettings] = useState<Settings>({ bookmarksBar: true, askWhereToSave: false, zoom: "100%", engine: ENGINES[0]!.value });
43 const [bookmarks, setBookmarks] = useState(BOOKMARKS);
44 const [visits, setVisits] = useState<Visit[]>(VISITS);
45 const [downloads, setDownloads] = useDownloads();
46 const [downloadsOpen, setDownloadsOpen] = useState(false);
47 const [switcherOpen, setSwitcherOpen] = useState(false);
48 const root = useRef<HTMLDivElement>(null);
49 const timers = useRef(new Map<string, ReturnType<typeof setTimeout>>());
50 useEffect(() => () => timers.current.forEach(clearTimeout), []);
51
52 const tab = tabs.find((t) => t.id === active) ?? tabs[0]!;
53 const url = urlOf(tab);
54 const set = (patch: Partial<Settings>) => setSettings((s) => ({ ...s, ...patch }));
55 const update = (id: string, change: (t: Tab) => Tab) => setTabs((all) => all.map((t) => (t.id === id ? change(t) : t)));
56
57 /* a site "loads" for a moment (a spinner in its tab, a progress bar over the page; the previous
58 * page stays until then); the browser's own pages (ui://) show at once */
59 const local = (u: string) => u.startsWith("ui://");
60 const load = (id: string, to: string) => {
61 clearTimeout(timers.current.get(id));
62 if (local(to)) return update(id, (t) => ({ ...t, loading: false, page: to }));
63 update(id, (t) => ({ ...t, loading: true }));
64 timers.current.set(id, setTimeout(() => update(id, (t) => ({ ...t, loading: false, page: urlOf(t) })), 450 + Math.random() * 500));
65 };
66 const navigate = (text: string) => {
67 const to = resolve(text, settings.engine);
68 update(tab.id, (t) => ({ ...t, stack: [...t.stack.slice(0, t.at + 1), to], at: t.at + 1 }));
69 if (!local(to)) setVisits((v) => [{ url: to, time: now(), day: "today" }, ...v]);
70 load(tab.id, to);
71 };
72 const step = (by: number) => {
73 const at = Math.max(0, Math.min(tab.stack.length - 1, tab.at + by));
74 update(tab.id, (t) => ({ ...t, at }));
75 load(tab.id, tab.stack[at] ?? HOME);
76 };
77 const reload = () => load(tab.id, url);
78 const stop = () => { clearTimeout(timers.current.get(tab.id)); update(tab.id, (t) => ({ ...t, loading: false, page: urlOf(t) })); };
79
80 /* the address bar takes focus after the panel that holds it has rendered */
81 const [focusTick, setFocusTick] = useState(0);
82 const focusAddress = () => setFocusTick((n) => n + 1);
83 useEffect(() => {
84 if (!focusTick) return;
85 const input = root.current?.querySelector<HTMLInputElement>("[data-slot=tabs-content]:not([hidden]) [data-slot=combobox-input]");
86 input?.focus();
87 input?.select();
88 }, [focusTick]);
89
90 /* a shortcut or Delete that removes the focused panel or tab hands focus to the window, so the
91 * next shortcut still reaches it */
92 const first = useRef(true);
93 useEffect(() => {
94 if (first.current) { first.current = false; return; }
95 if (document.activeElement === document.body) root.current?.focus({ preventScroll: true });
96 }, [tab.id, tabs.length]);
97
98 const open = (to = HOME) => {
99 const id = `t${++seq}`;
100 setTabs((all) => [...all, { id, stack: [to], at: 0, loading: false, page: "" }]);
101 setActive(id);
102 load(id, to);
103 if (to === HOME) focusAddress();
104 };
105 /* closing the last tab leaves a new tab page, as a window that stays open would. The Tabs have
106 * already selected the neighbour (onValueChange) when they ask to close */
107 const close = (id: string) => {
108 const i = tabs.findIndex((t) => t.id === id);
109 const gone = tabs[i];
110 if (!gone) return;
111 setClosed((c) => [gone, ...c]);
112 const rest = tabs.filter((t) => t.id !== id);
113 if (rest.length === 0) {
114 const fresh = { id: `t${++seq}`, stack: [HOME], at: 0, loading: false, page: HOME };
115 setTabs([fresh]);
116 setActive(fresh.id);
117 return;
118 }
119 setTabs(rest);
120 if (id === active) setActive((rest[i] ?? rest[i - 1])!.id);
121 };
122 const reopen = (id = closed[0]?.id) => {
123 const t = closed.find((c) => c.id === id);
124 if (!t) return;
125 setClosed((c) => c.filter((x) => x.id !== id));
126 setTabs((all) => [...all, { ...t, page: "" }]);
127 setActive(t.id);
128 load(t.id, urlOf(t));
129 };
130 /* the browser's own pages open once: a second request switches to the open tab */
131 const openPage = (to: string) => {
132 const there = tabs.find((t) => urlOf(t) === to);
133 if (there) setActive(there.id); else open(to);
134 };
135
136 const menu = (value: string) => {
137 if (value === "new-tab") open();
138 else if (value === "reopen") reopen();
139 else if (value === "history") openPage(HISTORY);
140 else if (value === "settings") openPage(SETTINGS);
141 else if (value === "downloads") setDownloadsOpen(true);
142 else if (value.startsWith("closed:")) reopen(value.slice(7));
143 else if (value.startsWith("open:")) navigate(value.slice(5));
144 };
145
146 const shortcuts = (e: KeyboardEvent) => {
147 const mod = e.ctrlKey || e.metaKey;
148 const alt = e.altKey && !mod;
149 const key = e.code;
150 const run = (action: () => void) => { e.preventDefault(); action(); };
151 if (mod && key === "KeyL") return run(focusAddress);
152 if ((alt || mod) && !e.shiftKey && key === "KeyT") return run(() => open());
153 if (alt && e.shiftKey && key === "KeyT") return run(() => reopen());
154 if ((alt || mod) && key === "KeyW") return run(() => close(tab.id));
155 if (alt && key === "KeyY") return run(() => openPage(HISTORY));
156 if (alt && key === "KeyJ") return run(() => setDownloadsOpen(true));
157 const digit = /^Digit[1-9]$/.test(key) ? Number(key.slice(5)) : /^[1-9]$/.test(e.key) ? Number(e.key) : 0;
158 if (alt && digit) {
159 const to = digit === 9 ? tabs[tabs.length - 1] : tabs[digit - 1];
160 return to && run(() => setActive(to.id));
161 }
162 if (e.ctrlKey && key === "Tab") {
163 const i = tabs.findIndex((t) => t.id === tab.id);
164 return run(() => setActive(tabs[(i + (e.shiftKey ? -1 : 1) + tabs.length) % tabs.length]!.id));
165 }
166 };
167 /* a middle click closes a tab, as in every browser */
168 const auxClose = (e: MouseEvent) => {
169 const trigger = (e.target as HTMLElement).closest<HTMLElement>("[data-slot=tabs-trigger]");
170 if (e.button === 1 && trigger?.dataset.value) { e.preventDefault(); close(trigger.dataset.value); }
171 };
172 /* the Download link on the Getting started page: the toolbar's ring shows it arriving */
173 const download = () => setDownloads((l) => [{ id: `dl${++seq}`, received: 0, ...CLI_DOWNLOAD }, ...l]);
174
175 const site = siteOf(url);
176 const bookmarked = bookmarks.some((b) => b.url === url);
177 const zoom = parseInt(settings.zoom, 10) / 100;
178
179 const tabInfo = tabs.map((t) => ({ id: t.id, url: urlOf(t), loading: t.loading }));
180 /* the toolbar, the bookmarks bar and the page: the selected tab's panel, under the strip's line */
181 const body = (
182 <div className="flex h-full min-h-0 flex-col">
183 <div className="flex items-center gap-0.5 px-2 py-1.5">
184 <NavButtons canBack={tab.at > 0} canForward={tab.at < tab.stack.length - 1} loading={tab.loading} back={() => step(-1)} forward={() => step(1)} reload={reload} stop={stop} />
185 <AddressBar
186 url={url} secure={site.secure} bookmarked={bookmarked} go={navigate} suggestions={suggestionsFor(url, visits)} engine={settings.engine}
187 onBookmark={(on) => setBookmarks((b) => (on ? [...b, { url, label: site.title.split(/ [·—:] /)[0]! }] : b.filter((x) => x.url !== url)))}
188 />
189 <Downloads list={downloads} open={downloadsOpen} onOpenChange={setDownloadsOpen}
190 onCancel={(id) => setDownloads((l) => l.filter((d) => d.id !== id))} onClear={() => setDownloads((l) => l.filter((d) => d.received < d.size))} />
191 <TabSwitcher tabs={tabInfo} active={tab.id} open={switcherOpen} onOpenChange={setSwitcherOpen}
192 select={(id) => { setActive(id); setSwitcherOpen(false); }} close={close} newTab={() => { setSwitcherOpen(false); open(); }} />
193 <BrowserMenu closed={closed.map((t) => ({ id: t.id, url: urlOf(t) }))} bookmarks={bookmarks} bookmarksBar={settings.bookmarksBar} zoom={settings.zoom}
194 onSelect={menu} onBookmarksBar={(on) => set({ bookmarksBar: on })} onZoom={(z) => set({ zoom: z })} />
195 </div>
196 {/* shown or hidden, the bar opens or closes its row (instant from the keyboard) */}
197 <div className={`grid kbd-instant motion-size-reveal max-sm:hidden ${settings.bookmarksBar ? "grid-rows-[1fr]" : "grid-rows-[0fr]"}`}>
198 <div className="min-h-0 overflow-hidden"><BookmarksBar bookmarks={bookmarks} go={navigate} /></div>
199 </div>
200 <div className="relative flex min-h-0 flex-1 flex-col border-t border-line">
201 {tab.loading && <Progress className="absolute inset-x-0 top-0 z-1" size="sm" tone="accent" ariaLabel={`Loading ${site.title}`} />}
202 <ScrollArea key={tab.page} className="min-h-0 flex-1" aria-label={siteOf(tab.page).title}>
203 <div style={{ zoom }}>
204 {tab.page && <Page url={tab.page} go={navigate} reload={reload} download={download} settings={settings} set={set} visits={visits} clearHistory={() => setVisits([])} />}
205 </div>
206 </ScrollArea>
207 </div>
208 </div>
209 );
210
211 return (
212 <div ref={root} data-showcase="web-browser" tabIndex={-1} onKeyDown={shortcuts} onAuxClick={auxClose} className="flex h-full flex-col overflow-hidden bg-surface outline-none">
213 <Tabs
214 variant="pill"
215 closable
216 fill
217 inHeader
218 aria-label="Tabs"
219 value={tab.id}
220 onValueChange={setActive}
221 onClose={close}
222 closeLabel="Close tab"
223 /* a phone shows no strip: the tab-count button in the toolbar opens the tabs as a sheet. The
224 * header's 6px start inset puts the first favicon 14px from the edge, as Back and the first
225 * bookmark */
226 headerClass="h-9 gap-0.5 border-b border-line ps-1.5 pe-2 max-sm:hidden"
227 end={
228 <Tooltip content="New tab" shortcut="Alt+T">
229 <Button variant="ghost" size="sm" square muted aria-label="New tab" icon={<Plus data-slot="icon" weight="bold" />} onClick={() => open()} className="shrink-0" />
230 </Tooltip>
231 }
232 items={tabs.map((t) => ({
233 value: t.id,
234 label: siteOf(urlOf(t)).title,
235 icon: t.loading ? <Spinner decorative /> : <Favicon url={urlOf(t)} />,
236 content: t.id === tab.id ? body : null,
237 }))}
238 />
239 </div>
240 );
241}