Open History to see the last commit
1import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
2import { ChevronRightIcon, ExternalLinkIcon, SearchIcon } from "lucide-react";
3import { useAtomRefresh, useAtomValue } from "@effect/atom-react";
4import * as Cause from "effect/Cause";
5import * as Schema from "effect/Schema";
6import * as Effect from "effect/Effect";
7import * as Option from "effect/Option";
8import { FetchHttpClient, HttpClient } from "effect/http";
9import { Atom } from "effect/reactivity";
10import { msg, T, useGT, useMessages } from "gt-react";
11import { useState } from "react";
12
13import {
14 decodeThirdPartyLicenseManifest,
15 filterThirdPartyLicenseEntries,
16 formatLicenseBundles,
17 thirdPartyLicenseEntryKey,
18 type ThirdPartyLicenseEntry,
19} from "@t3tools/shared/thirdPartyLicenses";
20
21import { m } from "../../i18n/messages";
22import { Button } from "../ui/button";
23import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible";
24import { InputGroup, InputGroupAddon, InputGroupInput } from "../ui/input-group";
25import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
26import { SettingsPageContainer, SettingsSection } from "./settingsLayout";
27
28class LicenseManifestLoadError extends Schema.TaggedError<LicenseManifestLoadError>()(
29 "LicenseManifestLoadError",
30 { message: Schema.String },
31) {}
32
33// Not keepAlive: a failed load must not stick for the session, so each visit to the page loads
34// the manifest again (a static asset the HTTP cache serves).
35const licenseManifestAtom = Atom.make(
36 Effect.gen(function* () {
37 const response = yield* HttpClient.get(
38 `${import.meta.env.BASE_URL.replace(/\/$/, "")}/third-party-licenses.json`,
39 );
40 if (response.status < 200 || response.status >= 300) {
41 return yield* new LicenseManifestLoadError({
42 message: m(
43 msg("The license manifest request failed with status {status}.", {
44 status: String(response.status),
45 }),
46 ),
47 });
48 }
49 const body = yield* response.json;
50 return yield* Effect.try({
51 try: () => decodeThirdPartyLicenseManifest(body, m),
52 catch: (error) =>
53 new LicenseManifestLoadError({
54 message:
55 error instanceof Error
56 ? (thrownErrorMessage(error, m) ?? error.message)
57 : m(msg("The license manifest could not load.")),
58 }),
59 });
60 }).pipe(
61 Effect.catchTags({
62 HttpClientError: (error) =>
63 Effect.fail(new LicenseManifestLoadError({ message: error.message })),
64 }),
65 Effect.timeoutOrElse({
66 duration: "30 seconds",
67 orElse: () =>
68 Effect.fail(
69 new LicenseManifestLoadError({
70 message: m(msg("The license manifest took too long to load.")),
71 }),
72 ),
73 }),
74 Effect.provide(FetchHttpClient.layer),
75 ),
76).pipe(Atom.withLabel("settings:open-source-licenses"));
77
78function LicenseNoticeRow({
79 entry,
80 open,
81 onOpenChange,
82}: {
83 readonly entry: ThirdPartyLicenseEntry;
84 readonly open: boolean;
85 readonly onOpenChange: (open: boolean) => void;
86}) {
87 const gt = useGT();
88 const messages = useMessages();
89 return (
90 <Collapsible open={open} onOpenChange={onOpenChange}>
91 <article>
92 <div className="flex min-h-10 items-center hover:bg-muted/35 sm:min-h-9">
93 <CollapsibleTrigger className="group flex min-h-10 min-w-0 flex-1 items-center gap-2.5 px-3 text-left sm:min-h-9 sm:px-4">
94 <ChevronRightIcon
95 aria-hidden
96 className="size-3.5 shrink-0 text-muted-foreground transition-transform duration-200 group-data-panel-open:rotate-90"
97 />
98 <span className="flex min-w-0 flex-1 items-baseline gap-2">
99 <span className="truncate font-medium text-foreground">{entry.name}</span>
100 {entry.version ? (
101 <code className="shrink-0 text-xs text-muted-foreground">{entry.version}</code>
102 ) : null}
103 </span>
104 <span className="max-w-[42%] shrink-0 truncate text-xs text-muted-foreground">
105 {entry.license} · {formatLicenseBundles(entry.bundles, messages)}
106 </span>
107 </CollapsibleTrigger>
108 {entry.sourceUrl ? (
109 <Button
110 aria-label={gt("View project source for {name}", { name: entry.name })}
111 className="me-3 shrink-0 sm:me-4"
112 render={<a href={entry.sourceUrl} rel="noreferrer noopener" target="_blank" />}
113 size="icon-micro"
114 title={gt("Project source")}
115 variant="ghost-muted"
116 >
117 <ExternalLinkIcon aria-hidden className="size-3" />
118 </Button>
119 ) : null}
120 </div>
121 <CollapsiblePanel>
122 {open ? (
123 <div className="px-9 pt-1 pb-4 sm:px-10">
124 <pre className="max-w-[76ch] whitespace-pre-wrap break-words font-mono text-xs/5 text-foreground/80">
125 {entry.noticeText}
126 </pre>
127 </div>
128 ) : null}
129 </CollapsiblePanel>
130 </article>
131 </Collapsible>
132 );
133}
134
135function LicenseCount({
136 filteredCount,
137 totalCount,
138}: {
139 filteredCount: number;
140 totalCount: number;
141}) {
142 const gt = useGT();
143 return (
144 <p className="whitespace-nowrap text-xs font-normal text-muted-foreground tabular-nums">
145 {filteredCount === totalCount
146 ? gt("{count, plural, one {{count} notices} other {{count} notices}}", {
147 count: totalCount,
148 })
149 : gt("{filtered} of {total}", {
150 filtered: String(filteredCount),
151 total: String(totalCount),
152 })}
153 </p>
154 );
155}
156
157function LicenseHeaderAction({
158 query,
159 onQueryChange,
160 searchOpen,
161 onSearchOpenChange,
162 filteredCount,
163 totalCount,
164}: {
165 query: string;
166 onQueryChange: (value: string) => void;
167 searchOpen: boolean;
168 onSearchOpenChange: (open: boolean) => void;
169 filteredCount: number;
170 totalCount: number;
171}) {
172 const gt = useGT();
173 if (!searchOpen) {
174 return (
175 <div className="flex items-center gap-1.5">
176 <LicenseCount filteredCount={filteredCount} totalCount={totalCount} />
177 <Tooltip>
178 <TooltipTrigger
179 render={
180 <Button
181 aria-label={gt("Search open-source licenses")}
182 onClick={() => onSearchOpenChange(true)}
183 size="icon-micro"
184 type="button"
185 variant="ghost-muted"
186 >
187 <SearchIcon className="size-3" />
188 </Button>
189 }
190 />
191 <TooltipPopup side="top">
192 <T>Search licenses</T>
193 </TooltipPopup>
194 </Tooltip>
195 </div>
196 );
197 }
198
199 return (
200 <div className="flex items-center gap-2">
201 <div className="hidden sm:block">
202 <LicenseCount filteredCount={filteredCount} totalCount={totalCount} />
203 </div>
204 <InputGroup className="w-36 sm:w-44">
205 <InputGroupAddon>
206 <SearchIcon aria-hidden className="size-3" />
207 </InputGroupAddon>
208 <InputGroupInput
209 aria-label={gt("Search open-source licenses")}
210 autoFocus
211 onBlur={() => {
212 if (query.length === 0) onSearchOpenChange(false);
213 }}
214 onChange={(event) => onQueryChange(event.currentTarget.value)}
215 onKeyDown={(event) => {
216 if (event.key !== "Escape") return;
217 event.preventDefault();
218 event.stopPropagation();
219 // Unmounting the focused input lets the dialog move focus to a control whose
220 // tooltip would swallow the next Esc; the surface keeps Esc closing Settings.
221 event.currentTarget.closest<HTMLElement>("[data-app-modal]")?.focus();
222 onQueryChange("");
223 onSearchOpenChange(false);
224 }}
225 placeholder={gt("Search licenses")}
226 size="sm"
227 type="search"
228 value={query}
229 />
230 </InputGroup>
231 </div>
232 );
233}
234
235function LicenseManifestError({ message, onRetry }: { message: string; onRetry: () => void }) {
236 return (
237 <div className="flex flex-col items-start gap-3 px-3 py-5 sm:px-4">
238 <div className="flex flex-col gap-1">
239 <h3 className="text-sm font-medium text-foreground">
240 <T>Open-source notices are unavailable</T>
241 </h3>
242 <p className="max-w-[70ch] text-pretty text-xs leading-normal text-muted-foreground/80">
243 {message}
244 </p>
245 </div>
246 <Button type="button" size="xs" variant="outline" onClick={onRetry}>
247 <T>Try again</T>
248 </Button>
249 </div>
250 );
251}
252
253export function OpenSourceLicensesPanel() {
254 const gt = useGT();
255 const result = useAtomValue(licenseManifestAtom);
256 const retry = useAtomRefresh(licenseManifestAtom);
257 const [query, setQuery] = useState("");
258 const [searchOpen, setSearchOpen] = useState(false);
259 const [openEntryKey, setOpenEntryKey] = useState<string | null>(null);
260 const manifest = result._tag === "Success" ? result.value : null;
261 const entries = manifest?.entries ?? [];
262 const filteredEntries = filterThirdPartyLicenseEntries(entries, query);
263 const errorMessage =
264 result._tag === "Failure" && !result.waiting
265 ? Option.match(Cause.findErrorOption(result.cause), {
266 onNone: () => gt("The license manifest could not load."),
267 onSome: (error) => error.message,
268 })
269 : null;
270
271 return (
272 <SettingsPageContainer>
273 <SettingsSection
274 title={gt("Third-party notices")}
275 headerAction={
276 manifest ? (
277 <LicenseHeaderAction
278 query={query}
279 onQueryChange={setQuery}
280 searchOpen={searchOpen}
281 onSearchOpenChange={setSearchOpen}
282 filteredCount={filteredEntries.length}
283 totalCount={entries.length}
284 />
285 ) : null
286 }
287 >
288 {manifest ? (
289 <div className="text-base sm:text-sm">
290 {filteredEntries.length > 0 ? (
291 filteredEntries.map((entry) => {
292 const entryKey = thirdPartyLicenseEntryKey(entry);
293 return (
294 <LicenseNoticeRow
295 key={entryKey}
296 entry={entry}
297 open={openEntryKey === entryKey}
298 onOpenChange={(open) => setOpenEntryKey(open ? entryKey : null)}
299 />
300 );
301 })
302 ) : (
303 <p className="px-3 py-8 text-center text-sm/6 text-muted-foreground sm:px-4">
304 <T>No licenses match that search.</T>
305 </p>
306 )}
307 </div>
308 ) : errorMessage !== null ? (
309 <LicenseManifestError message={errorMessage} onRetry={retry} />
310 ) : (
311 <p className="px-3 py-5 text-sm/6 text-muted-foreground sm:px-4">
312 <T>Loading open-source notices…</T>
313 </p>
314 )}
315 </SettingsSection>
316 </SettingsPageContainer>
317 );
318}