@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
tsx 674 lines 23 KB
Raw
1 import { SettingsGroup } from "./SettingsGroup";
2 import { AuthSettingsWriteScope } from "@t3tools/contracts";
3 import { usePrimaryEnvironmentId, usePrimaryEnvironment } from "../../state/environments";
4 import { useEnvironmentScope, useEnvironmentsWithScope } from "../../state/session";
5 import { useServerConfigs } from "../../state/entities";
6 import { InfoIcon, Undo2Icon } from "lucide-react";
7 import {
8 DEFAULT_SERVER_SETTINGS,
9 isManagedSettingPath,
10 type ServerSettings,
11 } from "@t3tools/contracts";
12 import * as Equal from "effect/Equal";
13 import { useGT } from "gt-react";
14 import { useLocation, useNavigate } from "@tanstack/react-router";
15 import { createContext, type ComponentPropsWithoutRef, type ReactNode, useContext } from "react";
16
17 import {
18 PRIMARY_SETTINGS_UNAVAILABLE_MESSAGE,
19 usePrimarySettingsAvailable,
20 } from "../../hooks/useSettings";
21 import { cn } from "../../lib/utils";
22 import { WorkspacePageContainer, type WorkspacePageWidth } from "../WorkspacePageContainer";
23 import { Button } from "../ui/button";
24 import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
25 import { useOptionalSettingsScope } from "./SettingsScopeContext";
26 import { SettingsScopeSentence } from "./SettingsScopeSentence";
27 import {
28 isProjectScopedSettingKey,
29 listProjectOverrides,
30 type ProjectOverrideEntry,
31 scopedSettingsAreMixed,
32 scopedSettingsSource,
33 } from "./scopedSettings";
34 import { useClearProjectOverrides, useClearScopedSettings } from "./useScopedSettings";
35 import {
36 SettingInheritance,
37 type SettingInheritanceState,
38 type SettingOverridingProject,
39 } from "./SettingInheritance";
40
41 const EMPTY_SETTING_KEYS: readonly (keyof ServerSettings)[] = [];
42 const EMPTY_MANAGED_PATHS: readonly string[] = [];
43
44 declare module "@tanstack/react-router" {
45 interface HistoryState {
46 settingsTargetHighlight?: boolean;
47 }
48 }
49
50 interface SettingsSearchTargetContextValue {
51 readonly targetId: string | null;
52 readonly highlightTarget: boolean;
53 readonly onTargetHandled: () => void;
54 }
55
56 const noop = () => undefined;
57 const SettingsSearchTargetContext = createContext<SettingsSearchTargetContextValue>({
58 targetId: null,
59 highlightTarget: true,
60 onTargetHandled: noop,
61 });
62
63 function SettingsSearchTargetProvider({
64 targetId,
65 highlightTarget = true,
66 onTargetHandled = noop,
67 children,
68 }: {
69 targetId: string | null;
70 highlightTarget?: boolean;
71 onTargetHandled?: () => void;
72 children: ReactNode;
73 }) {
74 const value = { targetId, highlightTarget, onTargetHandled };
75 return <SettingsSearchTargetContext value={value}>{children}</SettingsSearchTargetContext>;
76 }
77
78 let pendingTargetScroll: AbortController | undefined;
79
80 function scrollAndFocusSettingsTarget(target: HTMLElement, highlight = true): void {
81 pendingTargetScroll?.abort();
82 const prefersReducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
83 const markedScrollTarget =
84 typeof target.querySelector === "function"
85 ? target.querySelector<HTMLElement>(":scope > [data-settings-scroll-target]")
86 : null;
87 const scrollTarget =
88 markedScrollTarget ??
89 (target.tagName === "SECTION" && target.firstElementChild
90 ? (target.firstElementChild as HTMLElement)
91 : target);
92
93 const scroll = () =>
94 scrollTarget.scrollIntoView({
95 behavior: prefersReducedMotion ? "auto" : "smooth",
96 block: "center",
97 });
98 scroll();
99 const panel = target.parentElement?.closest<HTMLElement>(
100 '[data-slot="collapsible-panel"][data-open]',
101 );
102 const heightTransition = () =>
103 panel
104 ?.getAnimations()
105 .find(
106 (animation) =>
107 animation instanceof CSSTransition && animation.transitionProperty === "height",
108 );
109 if (panel && (panel.hasAttribute("data-starting-style") || heightTransition())) {
110 const controller = new AbortController();
111 pendingTargetScroll = controller;
112 const { signal } = controller;
113 const finishScroll = () => {
114 if (signal.aborted) return;
115 controller.abort();
116 if (
117 panel.hasAttribute("data-open") &&
118 target.isConnected &&
119 document.activeElement === target
120 ) {
121 scroll();
122 }
123 };
124 const waitForHeight = () => {
125 const transition = heightTransition();
126 if (transition) {
127 void transition.finished.then(finishScroll, () => controller.abort());
128 } else {
129 finishScroll();
130 }
131 };
132 // Base UI clears the starting style before the height transition finishes.
133 if (panel.hasAttribute("data-starting-style")) {
134 const observer = new MutationObserver(() => {
135 if (!panel.hasAttribute("data-starting-style")) {
136 observer.disconnect();
137 waitForHeight();
138 }
139 });
140 observer.observe(panel, { attributes: true, attributeFilter: ["data-starting-style"] });
141 signal.addEventListener("abort", () => observer.disconnect(), { once: true });
142 } else {
143 waitForHeight();
144 }
145 target.addEventListener("blur", () => controller.abort(), { once: true, signal });
146 }
147 target.focus({ preventScroll: true });
148 target.classList.remove("settings-search-target-pulse");
149 if (!highlight || prefersReducedMotion) return;
150 void target.offsetWidth;
151 target.classList.add("settings-search-target-pulse");
152 target.addEventListener("blur", () => target.classList.remove("settings-search-target-pulse"), {
153 once: true,
154 });
155 }
156
157 export function useSettingsSearchTargetId(): string | null {
158 return useContext(SettingsSearchTargetContext).targetId;
159 }
160
161 export function useSettingsSearchTarget<T extends HTMLElement>(id: string | undefined) {
162 const { targetId, highlightTarget, onTargetHandled } = useContext(SettingsSearchTargetContext);
163 const isSearchTarget = id !== undefined && id === targetId;
164 const targetRef = (target: T | null) => {
165 if (target && isSearchTarget) {
166 scrollAndFocusSettingsTarget(target, highlightTarget);
167 onTargetHandled();
168 }
169 };
170
171 return targetRef;
172 }
173
174 export function SettingsSearchTarget({
175 children,
176 // `searchableSetting` names the target for search; as an HTML title it shows a native tooltip.
177 title: _searchTitle,
178 ...targetProps
179 }: ComponentPropsWithoutRef<"div">) {
180 const targetRef = useSettingsSearchTarget<HTMLDivElement>(targetProps.id);
181 return (
182 <div {...targetProps} ref={targetRef} tabIndex={targetProps.id ? -1 : targetProps.tabIndex}>
183 {children}
184 </div>
185 );
186 }
187
188 // Settings pickers reuse composer controls but match the bordered selects beside them.
189 export const SETTINGS_PICKER_TRIGGER_CLASSNAME =
190 "min-w-0 max-w-none shrink-0 border-input bg-background font-normal text-foreground shadow-xs/5 hover:bg-accent/50 dark:bg-input/32 [&_svg[data-composer-control-chevron]]:stroke-[1.75] [&_svg[data-composer-control-chevron]]:opacity-70";
191
192 export function PolicyTooltip({ children }: { readonly children: string }) {
193 const gt = useGT();
194 return (
195 <Tooltip>
196 <TooltipTrigger
197 delay={200}
198 render={
199 <Button
200 size="icon-micro"
201 variant="ghost-muted"
202 aria-label={gt("Background policy details")}
203 >
204 <InfoIcon className="size-3.5" />
205 </Button>
206 }
207 />
208 <TooltipPopup side="top">{children}</TooltipPopup>
209 </Tooltip>
210 );
211 }
212
213 export function SettingsSection({
214 title,
215 hideTitle = false,
216 icon,
217 titleAction,
218 headerAction,
219 variant = "grouped",
220 children,
221 className,
222 ...sectionProps
223 }: ComponentPropsWithoutRef<"section"> & {
224 title: string;
225 hideTitle?: boolean;
226 icon?: ReactNode;
227 titleAction?: ReactNode;
228 headerAction?: ReactNode;
229 variant?: "grouped" | "plain";
230 children: ReactNode;
231 }) {
232 const targetRef = useSettingsSearchTarget<HTMLElement>(sectionProps.id);
233
234 return (
235 <section
236 {...sectionProps}
237 ref={targetRef}
238 tabIndex={sectionProps.id ? -1 : sectionProps.tabIndex}
239 className={cn(!hideTitle && "space-y-2.5", className)}
240 >
241 {hideTitle ? (
242 <h2 className="sr-only">{title}</h2>
243 ) : (
244 <div
245 data-settings-scroll-target
246 className="flex min-h-7 flex-wrap items-start justify-between gap-x-4 gap-y-1 px-3 sm:px-4"
247 >
248 <div className="flex min-w-0 items-center gap-1">
249 <h2 className="flex min-h-7 items-center gap-2 text-base font-semibold text-foreground">
250 {icon}
251 {title}
252 </h2>
253 {titleAction}
254 </div>
255 {headerAction ? (
256 <div className="flex min-h-7 min-w-7 items-center justify-end">{headerAction}</div>
257 ) : null}
258 </div>
259 )}
260 <SettingsGroup data-settings-scroll-target={hideTitle ? "" : undefined} variant={variant}>
261 {children}
262 </SettingsGroup>
263 </section>
264 );
265 }
266
267 export function SettingsUnavailableGroup({
268 children,
269 message,
270 }: {
271 children: ReactNode;
272 message?: ReactNode;
273 }) {
274 if (message === undefined) return children;
275
276 return (
277 <div className="border-border/60 bg-muted/20 py-1.5">
278 <div className="flex items-start gap-2 px-3 py-2 text-xs leading-relaxed text-muted-foreground sm:px-4">
279 <InfoIcon className="mt-0.5 size-3.5 shrink-0 text-warning" />
280 <p>{message}</p>
281 </div>
282 <div className="[&_h3]:opacity-64 [&_p]:opacity-64">{children}</div>
283 </div>
284 );
285 }
286
287 function projectOverrides(
288 context: ReturnType<typeof useOptionalSettingsScope>,
289 scopedKeys: ReadonlyArray<keyof ServerSettings>,
290 ): SettingOverridingProject[] {
291 if (context === null || scopedKeys.length === 0) return [];
292 return listProjectOverrides(context.connectedEnvironments, scopedKeys).flatMap((entry) => {
293 const group = context.groups.find((candidate) =>
294 candidate.memberProjects.some(
295 (member) => member.environmentId === entry.environmentId && member.id === entry.projectId,
296 ),
297 );
298 if (!group) return [];
299 return [
300 {
301 ...entry,
302 label: group.displayName,
303 open: () =>
304 context.selectScope({
305 project: group.projectKey,
306 ...(context.search.machine ? { machine: context.search.machine } : {}),
307 }),
308 },
309 ];
310 });
311 }
312
313 export function SettingsRow({
314 title,
315 description,
316 status,
317 resetAction,
318 onResetOverride,
319 control,
320 serverScoped = false,
321 devicePreference = false,
322 settingKeys = EMPTY_SETTING_KEYS,
323 managedPaths = EMPTY_MANAGED_PATHS,
324 mixed: mixedOverride,
325 managed,
326 children,
327 className,
328 ...rowProps
329 }: Omit<ComponentPropsWithoutRef<"div">, "title"> & {
330 title: ReactNode;
331 description?: ReactNode;
332 status?: ReactNode;
333 resetAction?: ReactNode;
334 onResetOverride?: () => void;
335 control?: ReactNode;
336 serverScoped?: boolean;
337 /** Saved on this device, so a project cannot override it and the row is read-only there. */
338 devicePreference?: boolean;
339 settingKeys?: readonly (keyof ServerSettings)[];
340 /** Dot paths inside a setting, such as `storageCleanup.logsAfterDays`, an administrator can lock. */
341 managedPaths?: readonly string[];
342 mixed?: boolean;
343 /** Why an administrator's policy turns this row's control off, from the contract's denial helpers. */
344 managed?: string | undefined;
345 children?: ReactNode;
346 }) {
347 const gt = useGT();
348 const targetRef = useSettingsSearchTarget<HTMLDivElement>(rowProps.id);
349 const primarySettingsAvailable = usePrimarySettingsAvailable();
350 const context = useOptionalSettingsScope();
351 const primaryEnvironmentId = usePrimaryEnvironmentId();
352 const primaryEnvironment = usePrimaryEnvironment();
353 const primaryCanWrite = useEnvironmentScope(primaryEnvironmentId, AuthSettingsWriteScope);
354 const writableIds = useEnvironmentsWithScope(
355 context?.connectedEnvironments ?? [],
356 AuthSettingsWriteScope,
357 );
358 const canWriteSettings = context
359 ? context.connectedEnvironments.length > 0 &&
360 context.connectedEnvironments.every((target) => writableIds.has(target.environmentId))
361 : primaryCanWrite;
362 const serverConfigs = useServerConfigs();
363 // An administrator's lock on any target wins over every other reason a control is inert.
364 const lockablePaths = [...settingKeys, ...managedPaths];
365 const managedBy =
366 lockablePaths.length === 0
367 ? undefined
368 : (context
369 ? context.connectedEnvironments.map((environment) => environment.serverConfig)
370 : [primaryEnvironmentId === null ? undefined : serverConfigs.get(primaryEnvironmentId)]
371 )
372 .map((config) => config?.managedPolicy)
373 .find(
374 (policy) =>
375 policy !== undefined &&
376 lockablePaths.some((path) => isManagedSettingPath(policy, path)),
377 )?.organization;
378 const clearOverrides = useClearScopedSettings();
379 const clearProjectOverrides = useClearProjectOverrides();
380 const isProjectScope =
381 context !== null && (context.scope.kind === "project" || context.scope.kind === "checkout");
382 const scopedKeys = settingKeys.filter(isProjectScopedSettingKey);
383 const environmentWide = isProjectScope && serverScoped && scopedKeys.length === 0;
384 const deviceReadOnly = isProjectScope && devicePreference;
385 const mixed =
386 mixedOverride ?? (context !== null && scopedSettingsAreMixed(context.targets, settingKeys));
387 const source =
388 context && isProjectScope ? scopedSettingsSource(context.targets, scopedKeys) : null;
389 const unavailable =
390 serverScoped &&
391 (!canWriteSettings ||
392 !(context ? context.connectedEnvironments.length > 0 : primarySettingsAvailable));
393 const inheritedFrom =
394 source === "environment" && context?.scope.environmentIds.length === 1
395 ? (context.environments.find(
396 (environment) => environment.environmentId === context.scope.environmentIds[0],
397 )?.label ?? null)
398 : null;
399 const environmentSettingsById = new Map(
400 (context?.connectedEnvironments ?? []).flatMap((environment) =>
401 environment.serverConfig
402 ? [[environment.environmentId, environment.serverConfig.settings] as const]
403 : [],
404 ),
405 );
406 const overridingProjects = isProjectScope ? [] : projectOverrides(context, scopedKeys);
407 const renderedReset =
408 unavailable ||
409 deviceReadOnly ||
410 managedBy !== undefined ||
411 managed !== undefined ? null : isProjectScope && scopedKeys.length > 0 ? (
412 source === "project" || source === "mixed" ? (
413 <SettingResetButton
414 ariaLabel={
415 typeof title === "string"
416 ? gt("Reset {title} to default", { title })
417 : gt("Reset override to default")
418 }
419 tooltip={gt("Reset to inherited value")}
420 onClick={() => (onResetOverride ? onResetOverride() : clearOverrides(scopedKeys))}
421 />
422 ) : null
423 ) : (
424 resetAction
425 );
426 const inertControl = (message: string) => (
427 <Tooltip>
428 <TooltipTrigger
429 render={
430 <span
431 tabIndex={0}
432 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"
433 />
434 }
435 >
436 <div
437 inert
438 className="flex w-full items-center gap-2 opacity-50 @min-[32rem]/settings-row:w-auto"
439 >
440 {control}
441 </div>
442 </TooltipTrigger>
443 <TooltipPopup side="top">{message}</TooltipPopup>
444 </Tooltip>
445 );
446 const lackingPermissionMessage = () => {
447 const environments = context
448 ? context.connectedEnvironments
449 .filter((target) => !writableIds.has(target.environmentId))
450 .map((target) => target.label)
451 .join(", ")
452 : primaryEnvironment?.label;
453 return environments
454 ? gt("This connection lacks permission to change settings on {environments}.", {
455 environments,
456 })
457 : context
458 ? gt("This connection lacks permission to change settings on the selected environment.")
459 : gt("This connection lacks permission to change settings on the primary environment.");
460 };
461 const renderedControl =
462 managed !== undefined && control
463 ? inertControl(managed)
464 : managedBy !== undefined && control
465 ? inertControl(gt("Managed by {organization}.", { organization: managedBy }))
466 : unavailable && control
467 ? inertControl(
468 !canWriteSettings
469 ? lackingPermissionMessage()
470 : context
471 ? gt("Reconnect the selected environment to change this setting.")
472 : PRIMARY_SETTINGS_UNAVAILABLE_MESSAGE,
473 )
474 : environmentWide && control
475 ? inertControl(gt("Environment-wide setting. Select an environment to change it."))
476 : deviceReadOnly && control
477 ? inertControl(gt("Saved on this device. Select All projects to change it."))
478 : control;
479 const customized =
480 context !== null &&
481 settingKeys.some((key) =>
482 context.targets.some((candidate) => {
483 const environmentSettings = environmentSettingsById.get(candidate.environmentId);
484 return (
485 environmentSettings !== undefined &&
486 !Equal.equals(environmentSettings[key], DEFAULT_SERVER_SETTINGS[key])
487 );
488 }),
489 );
490 const inheritance: { state: SettingInheritanceState; summary: string } = mixed
491 ? { state: "mixed", summary: gt("Mixed across selected environments") }
492 : source === "project"
493 ? { state: "overridden", summary: gt("Overridden for this project") }
494 : source === "t3.json"
495 ? { state: "inherited", summary: gt("Inherited from the repository's t3.json") }
496 : source === "environment" && scopedKeys.length > 0
497 ? {
498 state: "inherited",
499 summary:
500 inheritedFrom === null
501 ? gt("Inherited from environment")
502 : gt("Inherited from {environment}", { environment: inheritedFrom }),
503 }
504 : customized
505 ? { state: "environment", summary: gt("Set on the environment") }
506 : { state: "default", summary: gt("Built-in default") };
507 const renderedInheritance =
508 context && serverScoped && settingKeys.length > 0 ? (
509 <SettingInheritance
510 state={inheritance.state}
511 summary={inheritance.summary}
512 targets={context.targets}
513 environments={context.connectedEnvironments}
514 keys={settingKeys}
515 overridingProjects={overridingProjects}
516 {...(canWriteSettings
517 ? {
518 onClearOverrides: (entries: readonly ProjectOverrideEntry[]) =>
519 clearProjectOverrides(entries, scopedKeys),
520 }
521 : {})}
522 />
523 ) : null;
524 const renderedStatus = status;
525
526 return (
527 <div
528 {...rowProps}
529 ref={targetRef}
530 tabIndex={rowProps.id ? -1 : rowProps.tabIndex}
531 data-slot="settings-row"
532 className={cn(
533 "group/settings-row @container/settings-row rounded-xl px-3 sm:px-4 aria-disabled:opacity-64 aria-disabled:[&_*]:text-muted-foreground",
534 children ? "pt-3 pb-1" : "py-3",
535 className,
536 )}
537 >
538 <div className="flex flex-col gap-3 @min-[32rem]/settings-row:grid @min-[32rem]/settings-row:grid-cols-[minmax(0,1fr)_auto] @min-[32rem]/settings-row:items-center @min-[32rem]/settings-row:gap-8">
539 <div className="min-w-0 flex-1 space-y-1">
540 <div className="flex min-h-5 items-center gap-1.5">
541 <h3 className="text-sm font-medium text-foreground">{title}</h3>
542 {renderedInheritance ? (
543 <span
544 className={cn(
545 "inline-flex h-5 w-5 shrink-0 items-center justify-center",
546 // Values set right here explain nothing new, so their marker waits for hover or focus.
547 (inheritance.state === "default" || inheritance.state === "environment") &&
548 overridingProjects.length === 0 &&
549 "opacity-0 group-hover/settings-row:opacity-100 has-focus-visible:opacity-100 has-data-popup-open:opacity-100",
550 )}
551 >
552 {renderedInheritance}
553 </span>
554 ) : null}
555 <span className="inline-flex h-5 w-5 shrink-0 items-center justify-center">
556 {renderedReset}
557 </span>
558 </div>
559 {description ? (
560 <p className="max-w-2xl text-pretty text-xs leading-normal text-muted-foreground">
561 {description}
562 </p>
563 ) : null}
564 {renderedStatus ? (
565 <div className="pt-0.5 text-xs text-muted-foreground">{renderedStatus}</div>
566 ) : null}
567 </div>
568 {renderedControl ? (
569 <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 @min-[32rem]/settings-row:[&_[data-slot=select-trigger]]:min-w-40">
570 {renderedControl}
571 </div>
572 ) : null}
573 </div>
574 {unavailable && children ? (
575 <div inert className="opacity-50">
576 {children}
577 </div>
578 ) : (
579 children
580 )}
581 </div>
582 );
583 }
584
585 export function SettingResetButton({
586 ariaLabel,
587 tooltip,
588 disabled = false,
589 onClick,
590 }: {
591 ariaLabel: string;
592 tooltip?: string;
593 disabled?: boolean;
594 onClick: () => void;
595 }) {
596 const gt = useGT();
597 return (
598 <Tooltip>
599 <TooltipTrigger
600 render={
601 <Button
602 size="icon-micro"
603 variant="ghost-muted"
604 aria-label={ariaLabel}
605 disabled={disabled}
606 onClick={(event) => {
607 event.stopPropagation();
608 onClick();
609 }}
610 >
611 <Undo2Icon className="size-3" />
612 </Button>
613 }
614 />
615 <TooltipPopup side="top">{tooltip ?? gt("Reset to default")}</TooltipPopup>
616 </Tooltip>
617 );
618 }
619
620 export function SettingsPageContainer({
621 children,
622 className,
623 width = "readable",
624 searchTargetFallbacks,
625 }: {
626 children: ReactNode;
627 className?: string;
628 width?: WorkspacePageWidth;
629 searchTargetFallbacks?: Readonly<Record<string, string | undefined>>;
630 }) {
631 const navigate = useNavigate();
632 const hash = useLocation({ select: (location) => location.hash });
633 const highlightTarget = useLocation({
634 select: (location) => location.state.settingsTargetHighlight !== false,
635 });
636 const targetId = hash.replace(/^#/, "") || null;
637 const clearTargetHash = () => {
638 void navigate({
639 hash: "",
640 replace: true,
641 resetScroll: false,
642 hashScrollIntoView: false,
643 state: { settingsTargetHighlight: true },
644 });
645 };
646
647 return (
648 <SettingsSearchTargetProvider
649 targetId={targetId === null ? null : (searchTargetFallbacks?.[targetId] ?? targetId)}
650 highlightTarget={highlightTarget}
651 onTargetHandled={clearTargetHash}
652 >
653 <div
654 className="topbar-scroll-fade scrollbar-gutter-both flex-1 overflow-y-auto"
655 data-settings-page-scroll
656 >
657 <WorkspacePageContainer width={width} className={cn("gap-8", className)}>
658 <SettingsScopeSentence />
659 {children}
660 </WorkspacePageContainer>
661 </div>
662 </SettingsSearchTargetProvider>
663 );
664 }
665
666 export function scrollToSettingsTarget(
667 targetId: string,
668 { highlight = true }: { readonly highlight?: boolean } = {},
669 ): boolean {
670 const target = document.getElementById(targetId);
671 if (!target) return false;
672 scrollAndFocusSettingsTarget(target, highlight);
673 return true;
674 }