All files / client/src/components/features settings-dialog.tsx

75.47% Statements 80/106
60.6% Branches 20/33
76.92% Functions 20/26
78.21% Lines 79/101

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456                                          1x 1x 1x 1x 1x 1x 1x 1x 1x     1x                                 9x                                       18x                                       4x 2x 2x           4x 2x 2x     2x 2x       4x 2x 2x           4x                       4x   2x 2x 2x             4x 1x 1x   1x 1x 1x     1x           4x 2x 2x           4x                       4x                                                                                       3x 3x                 1x 1x 1x   1x 1x         1x 1x     1x           15x                                                                           54x                                                   1x                                                                                                                                                               4x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x           4x 3x 3x     3x 3x     3x     3x       4x 2x     4x 1x 1x       4x   4x                           1x            
import * as React from "react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
  DialogClose,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { ExternalExamplesSettings } from "@/components/features/external-examples-settings";
import { getServerCapabilities, type ServerCapabilities } from "@/lib/server-capabilities";
import { UnifiedScrollArea } from "@/components/ui/unified-scroll-area";
import {
  DEFAULT_EXPERIMENTAL_WORKSPACE_LAYOUT,
  EXPERIMENTAL_WORKSPACE_LAYOUT_CHANGE_EVENT,
  EXPERIMENTAL_WORKSPACE_LAYOUT_KEY,
} from "@/lib/experimental-workspace-layout";
 
const STORAGE_KEY = "unoBoardColor";
const DEFAULT_COLOR = "var(--color-brand-primary)";
const TOAST_DURATION_KEY = "unoToastDuration";
const DEFAULT_TOAST_SECONDS = 1;
const DEBUG_MODE_KEY = "unoDebugMode";
const PIN_MONITOR_VISIBLE_KEY = "unoPinMonitorVisible";
const DEFAULT_PIN_MONITOR_VISIBLE = false;
const FONT_SCALE_KEY = "unoFontScale";
const DEFAULT_FONT_SCALE = "1.0";
 
// Font scale options with labels showing both size name and px value
const FONT_SCALE_OPTIONS = [
  { value: "0.875", label: "S (12px)", px: 12 },
  { value: "1.0", label: "M (14px)", px: 14 },
  { value: "1.125", label: "L (16px)", px: 16 },
  { value: "1.25", label: "XL (18px)", px: 18 },
  { value: "1.5", label: "XXL (20px)", px: 20 },
] as const;
 
function SettingsSection({
  title,
  description,
  children,
}: {
  readonly title: string;
  readonly description?: string;
  readonly children: React.ReactNode;
}) {
  return (
    <section className="rounded-md border p-3">
      <div className="mb-3">
        <h3 className="text-ui-sm font-semibold text-foreground">{title}</h3>
        {description && <p className="mt-0.5 text-ui-xs text-muted-foreground">{description}</p>}
      </div>
      <div className="space-y-3">{children}</div>
    </section>
  );
}
 
function SettingsRow({
  label,
  description,
  children,
}: {
  readonly label: string;
  readonly description: React.ReactNode;
  readonly children: React.ReactNode;
}) {
  return (
    <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between sm:gap-5">
      <div className="min-w-0 flex-1">
        <div className="text-ui-sm font-medium text-foreground">{label}</div>
        <div className="mt-0.5 text-ui-xs leading-snug text-muted-foreground">{description}</div>
      </div>
      <div className="flex w-full min-w-0 shrink-0 items-center justify-end sm:w-auto sm:max-w-[55%]">{children}</div>
    </div>
  );
}
 
export default function SettingsDialog({
  open,
  onOpenChange,
  capabilities = getServerCapabilities(true),
}: {
  readonly open: boolean;
  readonly onOpenChange: (open: boolean) => void;
  readonly capabilities?: ServerCapabilities;
}) {
  const [color, setColor] = React.useState<string>(() => {
    try {
      return globalThis.localStorage.getItem(STORAGE_KEY) || DEFAULT_COLOR;
    } catch {
      return DEFAULT_COLOR;
    }
  });
 
  React.useEffect(() => {
    try {
      globalThis.localStorage.setItem(STORAGE_KEY, color);
    } catch {}
    // Dispatch a custom event so the Arduino board can update itself
    const ev = new CustomEvent("arduinoColorChange", { detail: { color } });
    document.dispatchEvent(ev);
  }, [color]);
 
  // Debug mode toggle (experimental)
  const [debugMode, setDebugMode] = React.useState<boolean>(() => {
    try {
      return globalThis.localStorage.getItem(DEBUG_MODE_KEY) === "1";
    } catch {
      return false;
    }
  });
 
  const setStoredDebug = (v: boolean) => {
    try {
      globalThis.localStorage.setItem(DEBUG_MODE_KEY, v ? "1" : "0");
    } catch {}
    setDebugMode(v);
    try {
      const ev = new CustomEvent("debugModeChange", { detail: { value: v } });
      document.dispatchEvent(ev);
    } catch {}
  };
 
  // Pin Monitor visibility toggle
  const [pinMonitorVisible, setPinMonitorVisible] = React.useState<boolean>(
    () => {
      try {
        const stored = globalThis.localStorage.getItem(PIN_MONITOR_VISIBLE_KEY);
        return stored === null ? DEFAULT_PIN_MONITOR_VISIBLE : stored === "1";
      } catch {
        return DEFAULT_PIN_MONITOR_VISIBLE;
      }
    },
  );
 
  const setStoredPinMonitorVisible = (v: boolean) => {
    try {
      globalThis.localStorage.setItem(PIN_MONITOR_VISIBLE_KEY, v ? "1" : "0");
    } catch {}
    setPinMonitorVisible(v);
    try {
      const ev = new CustomEvent("pinMonitorVisibleChange", {
        detail: { value: v },
      });
      document.dispatchEvent(ev);
    } catch {}
  };
 
  // Experimental workspace layout (disabled by default)
  const [experimentalWorkspaceLayout, setExperimentalWorkspaceLayout] =
    React.useState<boolean>(() => {
      try {
        return globalThis.localStorage.getItem(EXPERIMENTAL_WORKSPACE_LAYOUT_KEY) === "1";
      } catch {
        return DEFAULT_EXPERIMENTAL_WORKSPACE_LAYOUT;
      }
    });
 
  const setStoredExperimentalWorkspaceLayout = (value: boolean) => {
    try {
      globalThis.localStorage.setItem(EXPERIMENTAL_WORKSPACE_LAYOUT_KEY, value ? "1" : "0");
    } catch {}
    setExperimentalWorkspaceLayout(value);
    try {
      globalThis.dispatchEvent(
        new CustomEvent(EXPERIMENTAL_WORKSPACE_LAYOUT_CHANGE_EVENT, { detail: { value } }),
      );
    } catch {}
  };
 
  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent
        className="max-w-2xl gap-3"
        style={{
          maxHeight: "calc(100vh - var(--dialog-offset-top))",
          minHeight: 0,
          display: "flex",
          flexDirection: "column",
          overflow: "hidden",
        }}
      >
        <DialogHeader className="shrink-0">
          <DialogTitle>Settings</DialogTitle>
          <DialogDescription>
            Application settings and experimental tweaks for the simulator.
          </DialogDescription>
        </DialogHeader>
 
        <UnifiedScrollArea
          orientation="vertical"
          scrollbarVisibility="always"
          className="min-h-0 flex flex-1 flex-col px-1"
          viewportClassName="space-y-3 pb-1"
          viewportProps={{
            style: { minHeight: 0, height: "auto", flex: "1 1 auto" },
          }}
          style={{
            minHeight: 0,
            maxHeight: "calc(100vh - var(--dialog-offset-content))",
          }}
        >
          <ExternalExamplesSettings open={open} capabilities={capabilities} />
          <SettingsSection
            title="Appearance"
            description="Personalize the visual scale and Arduino board colors."
          >
            <SettingsRow
              label="UI Font Size"
              description="Scale the interface and editor text (S/M/L/XL/XXL)."
            >
              <select
                aria-label="ui font scale"
                defaultValue={(() => {
                  try {
                    return (
                      globalThis.localStorage.getItem(FONT_SCALE_KEY) ||
                      DEFAULT_FONT_SCALE
                    );
                  } catch {
                    return DEFAULT_FONT_SCALE;
                  }
                })()}
                onChange={(e) => {
                  const v = e.target.value;
                  try {
                    globalThis.localStorage.setItem(FONT_SCALE_KEY, v);
                  } catch {}
                  try {
                    document.documentElement.style.setProperty(
                      "--ui-font-scale",
                      v,
                    );
                  } catch {}
                  try {
                    const ev = new CustomEvent("uiFontScaleChange", {
                      detail: { value: Number.parseFloat(v) },
                    });
                    document.dispatchEvent(ev);
                  } catch {}
                }}
                className="h-[var(--ui-button-height)] rounded-md border border-input bg-background px-3 text-ui-sm text-foreground"
              >
                {FONT_SCALE_OPTIONS.map((option) => (
                  <option key={option.value} value={option.value}>
                    {option.label}
                  </option>
                ))}
              </select>
            </SettingsRow>
            <SettingsRow
              label="Arduino Color"
              description="Change the main board color (applies to the primary SVG)."
            >
              <div className="flex w-full items-start justify-between gap-3 sm:w-auto sm:min-w-[18rem]">
                <div className="flex shrink-0 flex-col items-center gap-1">
                  <div className="h-7 w-10 rounded border border-border" style={{ background: color }} aria-hidden="true" />
                  <Button size="sm" variant="outline" onClick={() => setColor(DEFAULT_COLOR)}>
                    Reset
                  </Button>
                </div>
                <div className="grid grid-cols-9 justify-items-end gap-1.5">
                  {[
                    "var(--color-brand-primary)",
                    "var(--color-brand-variant-1)",
                    "var(--color-brand-variant-2)",
                    "var(--color-brand-blue)",
                    "var(--color-brand-teal)",
                    "var(--color-green-dark)",
                    "var(--color-success-variant)",
                    "var(--color-status-success-dark)",
                    "var(--color-status-success)",
                    "var(--color-danger-soft)",
                    "var(--color-accent-orange-soft)",
                    "var(--color-accent-yellow-soft)",
                    "var(--color-status-warning)",
                    "var(--color-accent-amber)",
                    "var(--color-purple-1)",
                    "var(--color-purple-2)",
                    "var(--color-surface-dark)",
                    "var(--color-surface-muted)",
                  ].map((s) => (
                      <Button
                        key={s}
                        onClick={() => setColor(s)}
                        aria-label={`preset ${s}`}
                        title={s}
                        variant="outline"
                        size="icon"
                        style={{ background: s }}
                        className={`!h-6 !w-6 rounded-sm ${color.toLowerCase() === s.toLowerCase() ? "ring-2 ring-offset-1 ring-ring" : "border"}`}
                      />
                  ))}
                </div>
              </div>
            </SettingsRow>
          </SettingsSection>
 
          <SettingsSection
            title="Workspace & Interaction"
            description="Choose which workspace helpers are visible."
          >
            <SettingsRow
              label="Pin Monitor"
              description="Show the pin status monitor above the Arduino board."
            >
              <Checkbox
                checked={pinMonitorVisible}
                onCheckedChange={(v) => setStoredPinMonitorVisible(Boolean(v))}
                aria-label="show pin monitor"
                className="!h-[18px] !w-[18px] aspect-square shrink-0"
              />
            </SettingsRow>
            <SettingsRow
              label="Experimental Workspace Layout"
              description="Show code, simulation, and tutor as independently visible columns. Disabled by default."
            >
              <Checkbox
                checked={experimentalWorkspaceLayout}
                onCheckedChange={(value) => setStoredExperimentalWorkspaceLayout(Boolean(value))}
                aria-label="enable experimental workspace layout"
                className="!h-[18px] !w-[18px] aspect-square shrink-0"
              />
            </SettingsRow>
          </SettingsSection>
 
          <SettingsSection
            title="Feedback & Diagnostics"
            description="Control notification timing and optional diagnostic information."
          >
            <SettingsRow
              label="Toast Duration"
              description={'Change global toast expiry (0.5s steps). Choose "Infinite" to disable auto-hide.'}
            >
              <div className="w-full sm:min-w-[18rem]">
                <ToastDurationControl />
              </div>
            </SettingsRow>
            <SettingsRow
              label="Debug Mode"
              description={(
                <>
                  <span>Enable debug UI elements (telemetry displays, status light, CLI/GCC labels).</span>
                  <span className="mt-1 block">
                    <kbd className="rounded border bg-background px-1.5 py-0.5 text-[10px]">
                      {navigator.userAgent.toLowerCase().includes("mac") ? "⌘" : "Strg"}+D
                    </kbd>
                  </span>
                </>
              )}
            >
              <Checkbox
                checked={debugMode}
                onCheckedChange={(v) => setStoredDebug(Boolean(v))}
                aria-label="enable debug mode"
                className="!h-[18px] !w-[18px] aspect-square shrink-0"
              />
            </SettingsRow>
          </SettingsSection>
        </UnifiedScrollArea>
 
        <DialogFooter
          className="mt-3 shrink-0"
          style={{
            position: "sticky",
            bottom: 0,
            background: "transparent",
            zIndex: 2,
            boxShadow: "none",
          }}
        >
          <div className="flex w-full justify-end gap-2">
            <DialogClose asChild>
              <Button
                className="text-ui-foreground hover:bg-status-success-dark"
                style={{ backgroundColor: "var(--color-status-success)" }}
              >
                Done
              </Button>
            </DialogClose>
          </div>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
 
function ToastDurationControl() {
  const [sliderVal, setSliderVal] = React.useState<number>(() => {
    try {
      const v = globalThis.localStorage.getItem(TOAST_DURATION_KEY);
      if (v === null) return DEFAULT_TOAST_SECONDS * 2; // slider steps are 0.5s, so value = seconds*2
      Iif (v === "infinite") return 21;
      const ms = Number.parseInt(v, 10);
      Iif (Number.isNaN(ms)) return DEFAULT_TOAST_SECONDS * 2;
      const computed = Math.round((ms / 1000) * 2);
      Iif (computed < 1) return 1;
      Iif (computed > 20) return 20;
      return computed;
    } catch {
      return DEFAULT_TOAST_SECONDS * 2;
    }
  });
 
  const updateStored = (val: number) => {
    try {
      Iif (val === 21) {
        globalThis.localStorage.setItem(TOAST_DURATION_KEY, "infinite");
      } else {
        const ms = Math.round((val / 2) * 1000);
        globalThis.localStorage.setItem(TOAST_DURATION_KEY, String(ms));
      }
      // dispatch event for any listeners
      const ev = new CustomEvent("toastDurationChange", {
        detail: { value: val },
      });
      document.dispatchEvent(ev);
    } catch {}
  };
 
  React.useEffect(() => {
    updateStored(sliderVal);
  }, []);
 
  const onChange = (v: number) => {
    setSliderVal(v);
    updateStored(v);
  };
 
  const label =
    sliderVal === 21 ? "Infinite" : `${(sliderVal / 2).toFixed(1)}s`;
 
  return (
    <div className="flex flex-col gap-2">
      <div className="flex items-center justify-between">
        <div className="text-ui-sm">
          Duration: <span className="font-medium">{label}</span>
        </div>
        <div className="text-ui-xs text-muted-foreground">Step: 0.5s</div>
      </div>
      <input
        type="range"
        min={1}
        max={21}
        step={1}
        value={sliderVal}
        onChange={(e) => onChange(Number(e.target.value))}
        aria-label="toast duration"
      />
    </div>
  );
}