Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

settingsLayout.tsx

560 lines18.1 KB

1import { SettingsGroup } from "./SettingsGroup";
2import { AuthSettingsWriteScope } from "@t3tools/contracts";
3import { usePrimaryEnvironmentId, usePrimaryEnvironment } from "../../state/environments";
4import { useEnvironmentScope, useEnvironmentsWithScope } from "../../state/session";
5import { InfoIcon, Undo2Icon } from "lucide-react";
6import { DEFAULT_SERVER_SETTINGS, type ServerSettings } from "@t3tools/contracts";
7import * as Equal from "effect/Equal";
8import { useLocation, useNavigate } from "@tanstack/react-router";
9import {
10 createContext,
11 type ComponentPropsWithoutRef,
12 type ReactNode,
13 useCallback,
14 useContext,
15 useEffect,
16 useMemo,
17 useState,
18} from "react";
19​
20import {
21 PRIMARY_SETTINGS_UNAVAILABLE_MESSAGE,
22 usePrimarySettingsAvailable,
23} from "../../hooks/useSettings";
24import { cn } from "../../lib/utils";
25import { WorkspacePageContainer, type WorkspacePageWidth } from "../WorkspacePageContainer";
26import { Button } from "../ui/button";
27import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
28import { useOptionalSettingsScope } from "./SettingsScopeContext";
29import { SettingsScopeSentence } from "./SettingsScopeSentence";
30import {
31 isProjectScopedSettingKey,
32 listProjectOverrides,
33 type ProjectOverrideEntry,
34 scopedSettingsAreMixed,
35 scopedSettingsSource,
36} from "./scopedSettings";
37import { useClearProjectOverrides, useClearScopedSettings } from "./useScopedSettings";
38import {
39 SettingInheritance,
40 type SettingInheritanceState,
41 type SettingOverridingProject,
42} from "./SettingInheritance";
43​
44const EMPTY_SETTING_KEYS: readonly (keyof ServerSettings)[] = [];
45​
46declare module "@tanstack/react-router" {
47 interface HistoryState {
48 settingsTargetHighlight?: boolean;
49 }
51​
52interface SettingsSearchTargetContextValue {
53 readonly targetId: string | null;
54 readonly highlightTarget: boolean;
55 readonly onTargetHandled: () => void;
57​
58const noop = () => undefined;
59const SettingsSearchTargetContext = createContext<SettingsSearchTargetContextValue>({
60 targetId: null,
61 highlightTarget: true,
62 onTargetHandled: noop,
63});
64​
65function SettingsSearchTargetProvider({
66 targetId,
67 highlightTarget = true,
68 onTargetHandled = noop,
69 children,
70}: {
71 targetId: string | null;
72 highlightTarget?: boolean;
73 onTargetHandled?: () => void;
74 children: ReactNode;
75}) {
76 const value = useMemo(
77 () => ({ targetId, highlightTarget, onTargetHandled }),
78 [highlightTarget, onTargetHandled, targetId],
79 );
80 return <SettingsSearchTargetContext value={value}>{children}</SettingsSearchTargetContext>;
82​
83function scrollAndFocusSettingsTarget(target: HTMLElement, highlight = true): void {
84 const prefersReducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
85 const markedScrollTarget =
86 typeof target.querySelector === "function"
87 ? target.querySelector<HTMLElement>(":scope > [data-settings-scroll-target]")
88 : null;
89 const scrollTarget =
90 markedScrollTarget ??
91 (target.tagName === "SECTION" && target.firstElementChild
92 ? (target.firstElementChild as HTMLElement)
93 : target);
94​
95 scrollTarget.scrollIntoView({
96 behavior: prefersReducedMotion ? "auto" : "smooth",
97 block: "center",
98 });
99 target.focus({ preventScroll: true });
100 target.classList.remove("settings-search-target-pulse");
101 if (!highlight || prefersReducedMotion) return;
102 void target.offsetWidth;
103 target.classList.add("settings-search-target-pulse");
104 target.addEventListener("blur", () => target.classList.remove("settings-search-target-pulse"), {
105 once: true,
106 });
108​
109export function useSettingsSearchTargetId(): string | null {
110 return useContext(SettingsSearchTargetContext).targetId;
112​
113export function useSettingsSearchTarget<T extends HTMLElement>(id: string | undefined) {
114 const { targetId, highlightTarget, onTargetHandled } = useContext(SettingsSearchTargetContext);
115 const isSearchTarget = id !== undefined && id === targetId;
116 const targetRef = useCallback(
117 (target: T | null) => {
118 if (target && isSearchTarget) {
119 scrollAndFocusSettingsTarget(target, highlightTarget);
120 onTargetHandled();
121 }
122 },
123 [highlightTarget, isSearchTarget, onTargetHandled],
124 );
125​
126 return targetRef;
128​
129export function SettingsSearchTarget({
130 children,
131 ...targetProps
132}: ComponentPropsWithoutRef<"div">) {
133 const targetRef = useSettingsSearchTarget<HTMLDivElement>(targetProps.id);
134 return (
135 <div {...targetProps} ref={targetRef} tabIndex={targetProps.id ? -1 : targetProps.tabIndex}>
136 {children}
137 </div>
138 );
140​
141export const SETTINGS_PICKER_TRIGGER_CLASSNAME = "min-w-0 max-w-none shrink-0";
142​
143export function PolicyTooltip({ children }: { readonly children: string }) {
144 return (
145 <Tooltip>
146 <TooltipTrigger
147 delay={200}
148 render={
149 <Button size="icon-micro" variant="ghost-muted" aria-label="Background policy details">
150 <InfoIcon className="size-3.5" />
151 </Button>
152 }
153 />
154 <TooltipPopup side="top">{children}</TooltipPopup>
155 </Tooltip>
156 );
158​
159export function useRelativeTimeTick(intervalMs = 1_000) {
160 const [nowMs, setNowMs] = useState(() => Date.now());
161 useEffect(() => {
162 const id = setInterval(() => setNowMs(Date.now()), intervalMs);
163 return () => clearInterval(id);
164 }, [intervalMs]);
165 return nowMs;
167​
168export function SettingsSection({
169 title,
170 hideTitle = false,
171 icon,
172 titleAction,
173 headerAction,
174 variant = "grouped",
175 children,
176 className,
177 ...sectionProps
178}: ComponentPropsWithoutRef<"section"> & {
179 title: string;
180 hideTitle?: boolean;
181 icon?: ReactNode;
182 titleAction?: ReactNode;
183 headerAction?: ReactNode;
184 variant?: "grouped" | "plain";
185 children: ReactNode;
186}) {
187 const targetRef = useSettingsSearchTarget<HTMLElement>(sectionProps.id);
188​
189 return (
190 <section
191 {...sectionProps}
192 ref={targetRef}
193 tabIndex={sectionProps.id ? -1 : sectionProps.tabIndex}
194 className={cn(!hideTitle && "space-y-2.5", className)}
195 >
196 {hideTitle ? (
197 <h2 className="sr-only">{title}</h2>
198 ) : (
199 <div
200 data-settings-scroll-target
201 className="flex min-h-7 items-start justify-between gap-4 px-3 sm:px-4"
202 >
203 <div className="flex min-w-0 items-center gap-1">
204 <h2 className="flex min-h-7 items-center gap-2 text-sm font-normal text-foreground/70">
205 {icon}
206 {title}
207 </h2>
208 {titleAction}
209 </div>
210 <div className="flex min-h-7 min-w-7 items-center justify-end">{headerAction}</div>
211 </div>
212 )}
213 <SettingsGroup data-settings-scroll-target={hideTitle ? "" : undefined} variant={variant}>
214 {children}
215 </SettingsGroup>
216 </section>
217 );
219​
220export function SettingsUnavailableGroup({
221 children,
222 message,
223}: {
224 children: ReactNode;
225 message?: ReactNode;
226}) {
227 if (message === undefined) return children;
228​
229 return (
230 <div className="border-border/60 bg-muted/20 py-1.5">
231 <div className="flex items-start gap-2 px-3 py-2 text-xs leading-relaxed text-muted-foreground sm:px-4">
232 <InfoIcon className="mt-0.5 size-3.5 shrink-0 text-warning" />
233 <p>{message}</p>
234 </div>
235 <div className="[&_h3]:opacity-64 [&_p]:opacity-64">{children}</div>
236 </div>
237 );
239​
240export function SettingsRow({
241 title,
242 description,
243 status,
244 resetAction,
245 onResetOverride,
246 control,
247 serverScoped = false,
248 settingKeys = EMPTY_SETTING_KEYS,
249 mixed: mixedOverride,
250 children,
251 className,
252 ...rowProps
253}: Omit<ComponentPropsWithoutRef<"div">, "title"> & {
254 title: ReactNode;
255 description?: ReactNode;
256 status?: ReactNode;
257 resetAction?: ReactNode;
258 onResetOverride?: () => void;
259 control?: ReactNode;
260 serverScoped?: boolean;
261 settingKeys?: readonly (keyof ServerSettings)[];
262 mixed?: boolean;
263 children?: ReactNode;
264}) {
265 const targetRef = useSettingsSearchTarget<HTMLDivElement>(rowProps.id);
266 const primarySettingsAvailable = usePrimarySettingsAvailable();
267 const context = useOptionalSettingsScope();
268 const primaryEnvironmentId = usePrimaryEnvironmentId();
269 const primaryEnvironment = usePrimaryEnvironment();
270 const primaryCanWrite = useEnvironmentScope(primaryEnvironmentId, AuthSettingsWriteScope);
271 const writableIds = useEnvironmentsWithScope(
272 context?.connectedEnvironments ?? [],
273 AuthSettingsWriteScope,
274 );
275 const canWriteSettings = context
276 ? context.connectedEnvironments.length > 0 &&
277 context.connectedEnvironments.every((target) => writableIds.has(target.environmentId))
278 : primaryCanWrite;
279 const clearOverrides = useClearScopedSettings();
280 const clearProjectOverrides = useClearProjectOverrides();
281 const isProjectScope =
282 context !== null && (context.scope.kind === "project" || context.scope.kind === "checkout");
283 const scopedKeys = settingKeys.filter(isProjectScopedSettingKey);
284 const environmentWide = isProjectScope && serverScoped && scopedKeys.length === 0;
285 const mixed =
286 mixedOverride ?? (context !== null && scopedSettingsAreMixed(context.targets, settingKeys));
287 const source =
288 context && isProjectScope ? scopedSettingsSource(context.targets, scopedKeys) : null;
289 const unavailable =
290 serverScoped &&
291 (!canWriteSettings ||
292 !(context ? context.connectedEnvironments.length > 0 : primarySettingsAvailable));
293 const inheritedFrom =
294 source === "environment" && context?.scope.environmentIds.length === 1
295 ? (context.environments.find(
296 (environment) => environment.environmentId === context.scope.environmentIds[0],
297 )?.label ?? "environment")
298 : "environment";
299 const environmentSettingsById = useMemo(
300 () =>
301 new Map(
302 (context?.connectedEnvironments ?? []).flatMap((environment) =>
303 environment.serverConfig
304 ? [[environment.environmentId, environment.serverConfig.settings] as const]
305 : [],
306 ),
307 ),
308 [context?.connectedEnvironments],
309 );
310 const overridingProjects = useMemo((): SettingOverridingProject[] => {
311 if (context === null || isProjectScope || scopedKeys.length === 0) return [];
312 return listProjectOverrides(context.connectedEnvironments, scopedKeys).flatMap((entry) => {
313 const group = context.groups.find((candidate) =>
314 candidate.memberProjects.some(
315 (member) => member.environmentId === entry.environmentId && member.id === entry.projectId,
316 ),
317 );
318 if (!group) return [];
319 return [
320 {
321 ...entry,
322 label: group.displayName,
323 open: () =>
324 context.selectScope({
325 project: group.projectKey,
326 ...(context.search.machine ? { machine: context.search.machine } : {}),
327 }),
328 },
329 ];
330 });
331 }, [context, isProjectScope, scopedKeys]);
332 const renderedReset = unavailable ? null : isProjectScope && scopedKeys.length > 0 ? (
333 source === "project" || source === "mixed" ? (
334 <SettingResetButton
335 label={typeof title === "string" ? title : "override"}
336 tooltip="Reset to inherited value"
337 onClick={() => (onResetOverride ? onResetOverride() : clearOverrides(scopedKeys))}
338 />
339 ) : null
340 ) : (
341 resetAction
342 );
343 const inertControl = (message: string) => (
344 <Tooltip>
345 <TooltipTrigger
346 render={
347 <span
348 tabIndex={0}
349 className="flex w-full items-center rounded-md outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring @min-[32rem]/settings-row:w-auto"
350 />
351 }
352 >
353 <div
354 inert
355 className="flex w-full items-center gap-2 opacity-50 @min-[32rem]/settings-row:w-auto"
356 >
357 {control}
358 </div>
359 </TooltipTrigger>
360 <TooltipPopup side="top">{message}</TooltipPopup>
361 </Tooltip>
362 );
363 const renderedControl =
364 unavailable && control
365 ? inertControl(
366 !canWriteSettings
367 ? `This connection lacks permission to change settings on ${
368 context
369 ? context.connectedEnvironments
370 .filter((target) => !writableIds.has(target.environmentId))
371 .map((target) => target.label)
372 .join(", ") || "the selected environment"
373 : (primaryEnvironment?.label ?? "the primary environment")
374 }.`
375 : context
376 ? "Reconnect the selected environment to change this setting."
377 : PRIMARY_SETTINGS_UNAVAILABLE_MESSAGE,
378 )
379 : environmentWide && control
380 ? inertControl("Environment-wide setting. Select an environment to change it.")
381 : control;
382 const customized =
383 context !== null &&
384 settingKeys.some((key) =>
385 context.targets.some((candidate) => {
386 const environmentSettings = environmentSettingsById.get(candidate.environmentId);
387 return (
388 environmentSettings !== undefined &&
389 !Equal.equals(environmentSettings[key], DEFAULT_SERVER_SETTINGS[key])
390 );
391 }),
392 );
393 const inheritance: { state: SettingInheritanceState; summary: string } = mixed
394 ? { state: "mixed", summary: "Mixed across selected environments" }
395 : source === "project"
396 ? { state: "overridden", summary: "Overridden for this project" }
397 : source === "t3.json"
398 ? { state: "inherited", summary: "Inherited from the repository's t3.json" }
399 : source === "environment" && scopedKeys.length > 0
400 ? { state: "inherited", summary: `Inherited from ${inheritedFrom}` }
401 : customized
402 ? { state: "environment", summary: "Set on the environment" }
403 : { state: "default", summary: "Built-in default" };
404 const renderedInheritance =
405 context && serverScoped && settingKeys.length > 0 ? (
406 <SettingInheritance
407 state={inheritance.state}
408 summary={inheritance.summary}
409 targets={context.targets}
410 environments={context.connectedEnvironments}
411 keys={settingKeys}
412 overridingProjects={overridingProjects}
413 {...(canWriteSettings
414 ? {
415 onClearOverrides: (entries: readonly ProjectOverrideEntry[]) =>
416 clearProjectOverrides(entries, scopedKeys),
417 }
418 : {})}
419 />
420 ) : null;
421 const renderedStatus = status;
422​
423 return (
424 <div
425 {...rowProps}
426 ref={targetRef}
427 tabIndex={rowProps.id ? -1 : rowProps.tabIndex}
428 data-slot="settings-row"
429 className={cn(
430 "@container/settings-row rounded-xl px-3 sm:px-4 aria-disabled:opacity-64 aria-disabled:[&_*]:text-muted-foreground",
431 children ? "pt-3 pb-1" : "py-3",
432 className,
433 )}
434 >
435 <div className="flex flex-col gap-3 @min-[32rem]/settings-row:grid @min-[32rem]/settings-row:grid-cols-[minmax(0,1fr)_minmax(10rem,auto)] @min-[32rem]/settings-row:items-center @min-[32rem]/settings-row:gap-8">
436 <div className="min-w-0 flex-1 space-y-1">
437 <div className="flex min-h-5 items-center gap-1.5">
438 <h3 className="text-sm font-medium text-foreground">{title}</h3>
439 {renderedInheritance ? (
440 <span className="inline-flex h-5 w-5 shrink-0 items-center justify-center">
441 {renderedInheritance}
442 </span>
443 ) : null}
444 <span className="inline-flex h-5 w-5 shrink-0 items-center justify-center">
445 {renderedReset}
446 </span>
447 </div>
448 {description ? (
449 <p className="max-w-xl text-xs leading-normal text-muted-foreground/80">
450 {description}
451 </p>
452 ) : null}
453 {renderedStatus ? (
454 <div className="pt-0.5 text-xs text-muted-foreground">{renderedStatus}</div>
455 ) : null}
456 </div>
457 {renderedControl ? (
458 <div className="flex w-full min-w-0 shrink-0 items-center gap-2 @min-[32rem]/settings-row:w-auto @min-[32rem]/settings-row:justify-end">
459 {renderedControl}
460 </div>
461 ) : null}
462 </div>
463 {unavailable && children ? (
464 <div inert className="opacity-50">
465 {children}
466 </div>
467 ) : (
468 children
469 )}
470 </div>
471 );
473​
474export function SettingResetButton({
475 label,
476 tooltip = "Reset to default",
477 disabled = false,
478 onClick,
479}: {
480 label: string;
481 tooltip?: string;
482 disabled?: boolean;
483 onClick: () => void;
484}) {
485 return (
486 <Tooltip>
487 <TooltipTrigger
488 render={
489 <Button
490 size="icon-micro"
491 variant="ghost-muted"
492 aria-label={`Reset ${label} to default`}
493 disabled={disabled}
494 onClick={(event) => {
495 event.stopPropagation();
496 onClick();
497 }}
498 >
499 <Undo2Icon className="size-3" />
500 </Button>
501 }
502 />
503 <TooltipPopup side="top">{tooltip}</TooltipPopup>
504 </Tooltip>
505 );
507​
508export function SettingsPageContainer({
509 children,
510 className,
511 width = "readable",
512}: {
513 children: ReactNode;
514 className?: string;
515 width?: WorkspacePageWidth;
516}) {
517 const navigate = useNavigate();
518 const hash = useLocation({ select: (location) => location.hash });
519 const highlightTarget = useLocation({
520 select: (location) => location.state.settingsTargetHighlight !== false,
521 });
522 const targetId = hash.replace(/^#/, "") || null;
523 const clearTargetHash = useCallback(() => {
524 void navigate({
525 hash: "",
526 replace: true,
527 resetScroll: false,
528 hashScrollIntoView: false,
529 state: { settingsTargetHighlight: true },
530 });
531 }, [navigate]);
532​
533 return (
534 <SettingsSearchTargetProvider
535 targetId={targetId}
536 highlightTarget={highlightTarget}
537 onTargetHandled={clearTargetHash}
538 >
539 <div
540 className="topbar-scroll-fade scrollbar-gutter-both flex-1 overflow-y-auto"
541 data-settings-page-scroll
542 >
543 <WorkspacePageContainer width={width} className={cn("gap-8", className)}>
544 <SettingsScopeSentence />
545 {children}
546 </WorkspacePageContainer>
547 </div>
548 </SettingsSearchTargetProvider>
549 );
551​
552export function scrollToSettingsTarget(
553 targetId: string,
554 { highlight = true }: { readonly highlight?: boolean } = {},
555): boolean {
556 const target = document.getElementById(targetId);
557 if (!target) return false;
558 scrollAndFocusSettingsTarget(target, highlight);
559 return true;