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