Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 19 additions & 2 deletions web/src/app.css
Original file line number Diff line number Diff line change
Expand Up @@ -538,19 +538,36 @@ html[data-navigation-direction]::view-transition-new(main-content) {
and set a system colour on everything inside them. */
nav :is(a, button):is([aria-current="page"], [aria-current="true"]),
[role="tab"][aria-selected="true"],
[role="radio"][aria-checked="true"]:not([data-slot^="radio"]) {
[role="radio"][aria-checked="true"]:not([data-slot^="radio"], [data-slot="color-swatch"]) {
forced-color-adjust: none;
border-color: Highlight;
background-color: Highlight;
color: HighlightText;
}
nav :is(a, button):is([aria-current="page"], [aria-current="true"]) *,
[role="tab"][aria-selected="true"] *,
[role="radio"][aria-checked="true"]:not([data-slot^="radio"]) * {
[role="radio"][aria-checked="true"]:not([data-slot^="radio"], [data-slot="color-swatch"]) * {
border-color: currentColor;
background-color: transparent;
color: inherit;
}

/* Color swatches keep their own colour in forced colors so the palette
still shows each choice. A CanvasText border frames every swatch on the
page, and a thicker Highlight border with an inner Canvas gap marks the
selected one without colliding with the outer focus-visible outline. */
[data-slot="color-swatch"] {
forced-color-adjust: none;
border: 1px solid CanvasText;
box-shadow: none;
}
[data-slot="color-swatch"][aria-checked="true"] {
border: 3px solid Highlight;
box-shadow: inset 0 0 0 2px Canvas;
}
[data-slot="color-swatch"]:disabled {
border-color: GrayText;
}
}

/* ================================================================
Expand Down
82 changes: 82 additions & 0 deletions web/src/pages/settings/ColorPalette.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import { useRef, type KeyboardEvent } from "react";
import { readingArrowKey } from "@/lib/direction";

export interface ColorPaletteProps {
colors: { hex: string; label: string }[];
selected: string;
onChange: (hex: string) => void;
disabled?: boolean;
labelId?: string;
descriptionId?: string;
}

export function ColorPalette({
colors,
selected,
onChange,
disabled,
labelId,
descriptionId,
}: ColorPaletteProps) {
const buttonRefs = useRef<(HTMLButtonElement | null)[]>([]);
const normalizedSelected = selected.toLowerCase();
const selectedIndex = colors.findIndex((color) => color.hex.toLowerCase() === normalizedSelected);
const tabbableIndex = selectedIndex >= 0 ? selectedIndex : 0;

function handleKeyDown(event: KeyboardEvent<HTMLButtonElement>, index: number) {
if (disabled || colors.length === 0) return;
if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) return;
const key = readingArrowKey(event);
let step = 0;
if (key === "ArrowRight" || key === "ArrowDown") {
step = 1;
} else if (key === "ArrowLeft" || key === "ArrowUp") {
step = -1;
} else {
return;
}
event.preventDefault();
const nextIndex = (index + step + colors.length) % colors.length;
const nextColor = colors[nextIndex];
if (!nextColor) return;
onChange(nextColor.hex);
buttonRefs.current[nextIndex]?.focus();
}

return (
<div
role="radiogroup"
aria-labelledby={labelId}
aria-describedby={descriptionId}
className={`flex flex-wrap gap-2 ${disabled ? "opacity-40" : ""}`}
>
{colors.map((color, index) => {
const isSelected = index === selectedIndex;
return (
<button
key={color.hex}
ref={(el) => {
buttonRefs.current[index] = el;
}}
type="button"
role="radio"
aria-checked={isSelected}
tabIndex={disabled ? undefined : index === tabbableIndex ? 0 : -1}
data-slot="color-swatch"
title={color.label}
aria-label={color.label}
onClick={() => onChange(color.hex)}
onKeyDown={(event) => handleKeyDown(event, index)}
disabled={disabled}
// The selected mark sits on the page, past a gap, so it stays
// visible whatever the swatch's own color is.
className={`h-7 w-7 rounded-full transition-transform hover:scale-110 ${
isSelected ? "ring-primary ring-offset-background ring-2 ring-offset-2" : ""
} ${color.hex === "#000000" ? "inset-ring inset-ring-white/20" : ""}`}
style={{ backgroundColor: color.hex }}
/>
);
})}
</div>
);
}
181 changes: 181 additions & 0 deletions web/src/pages/settings/SubtitleAppearanceSettings.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
import { cleanup, fireEvent, render, screen, within } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { DEFAULT_SUBTITLE_APPEARANCE, type SubtitleAppearance } from "@/lib/subtitleAppearance";

const mocks = vi.hoisted(() => ({
appearance: null as SubtitleAppearance | null,
saveAppearance: vi.fn(),
resetAppearance: vi.fn(),
}));

vi.mock("@/hooks/queries/subtitleAppearance", () => ({
useSubtitleAppearanceSetting: () => ({
appearance: mocks.appearance ?? DEFAULT_SUBTITLE_APPEARANCE,
isCustomized: false,
save: mocks.saveAppearance,
reset: mocks.resetAppearance,
isSaving: false,
}),
}));

vi.mock("@/hooks/queries/subtitleSync", () => ({
SUBTITLE_SYNC_MAX_MS: 5000,
useSubtitleSyncSetting: () => ({
offsetMs: 0,
isLoaded: true,
isSaving: false,
save: vi.fn().mockResolvedValue(undefined),
}),
}));

vi.mock("@/hooks/queries/settingValues", () => ({
useEffectiveSettings: () => ({ data: undefined }),
}));

vi.mock("@/hooks/queries/profileDefaults", () => ({
useProfileDefaultWriter: () => ({
save: vi.fn().mockResolvedValue(undefined),
reset: vi.fn().mockResolvedValue(undefined),
isSaving: false,
}),
}));

vi.mock("sonner", () => ({
toast: { success: vi.fn(), error: vi.fn() },
}));

import SubtitleAppearanceSettings from "./SubtitleAppearanceSettings";

class MockResizeObserver implements ResizeObserver {
observe() {}
unobserve() {}
disconnect() {}
}

describe("SubtitleAppearanceSettings color palettes", () => {
beforeEach(() => {
vi.stubGlobal("ResizeObserver", MockResizeObserver);
mocks.appearance = { ...DEFAULT_SUBTITLE_APPEARANCE };
mocks.saveAppearance.mockReset().mockResolvedValue(undefined);
mocks.resetAppearance.mockReset().mockResolvedValue(undefined);
});

afterEach(cleanup);

it("exposes selected state on all three color palettes as radiogroups", () => {
mocks.appearance = {
...DEFAULT_SUBTITLE_APPEARANCE,
fontColor: "#FACC15",
textOutline: true,
textOutlineColor: "#ef4444",
backgroundStyle: "box",
backgroundColor: "#1e3a5f",
};

render(<SubtitleAppearanceSettings />);

const cases = [
{ group: "Font color", selected: "Yellow", unselected: "White" },
{ group: "Outline color", selected: "Red", unselected: "Black" },
{ group: "Background color", selected: "Navy", unselected: "Black" },
];

for (const { group, selected, unselected } of cases) {
const radiogroup = screen.getByRole("radiogroup", { name: group });
const checked = within(radiogroup).getByRole("radio", { name: selected });
const other = within(radiogroup).getByRole("radio", { name: unselected });

expect(checked).toHaveAttribute("aria-checked", "true");
expect(checked).toHaveAttribute("tabindex", "0");
expect(other).toHaveAttribute("aria-checked", "false");
expect(other).toHaveAttribute("tabindex", "-1");
}
});

it("updates selection and roving tabindex on click and arrow keys", () => {
render(<SubtitleAppearanceSettings />);

const fontGroup = screen.getByRole("radiogroup", { name: "Font color" });
const white = within(fontGroup).getByRole("radio", { name: "White" });
const yellow = within(fontGroup).getByRole("radio", { name: "Yellow" });
const black = within(fontGroup).getByRole("radio", { name: "Black" });

white.focus();
fireEvent.keyDown(white, { key: "ArrowRight" });
expect(yellow).toHaveFocus();
expect(yellow).toHaveAttribute("aria-checked", "true");
expect(yellow).toHaveAttribute("tabindex", "0");
expect(white).toHaveAttribute("aria-checked", "false");
expect(white).toHaveAttribute("tabindex", "-1");

// Modifier chords stay out of the palette's arrow handling.
fireEvent.keyDown(yellow, { key: "ArrowLeft", altKey: true });
expect(yellow).toHaveAttribute("aria-checked", "true");

// ArrowLeft wraps from the first swatch to the last.
fireEvent.keyDown(yellow, { key: "ArrowLeft" });
expect(white).toHaveFocus();
fireEvent.keyDown(white, { key: "ArrowLeft" });
expect(black).toHaveFocus();
expect(black).toHaveAttribute("aria-checked", "true");

// ArrowDown wraps from the last swatch back to the first.
fireEvent.keyDown(black, { key: "ArrowDown" });
expect(white).toHaveFocus();
expect(white).toHaveAttribute("aria-checked", "true");

// Background color palette also supports click and keyboard navigation.
const bgGroup = screen.getByRole("radiogroup", { name: "Background color" });
const bgBlack = within(bgGroup).getByRole("radio", { name: "Black" });
const bgDarkGray = within(bgGroup).getByRole("radio", { name: "Dark Gray" });
const bgNavy = within(bgGroup).getByRole("radio", { name: "Navy" });
fireEvent.click(bgDarkGray);
expect(bgDarkGray).toHaveAttribute("aria-checked", "true");
expect(bgBlack).toHaveAttribute("aria-checked", "false");
fireEvent.keyDown(bgDarkGray, { key: "ArrowRight" });
expect(bgNavy).toHaveFocus();
expect(bgNavy).toHaveAttribute("aria-checked", "true");
});

it("supports keyboard navigation on Outline color when enabled", () => {
mocks.appearance = {
...DEFAULT_SUBTITLE_APPEARANCE,
textOutline: true,
textOutlineColor: "#000000",
};

render(<SubtitleAppearanceSettings />);

const outlineGroup = screen.getByRole("radiogroup", { name: "Outline color" });
const outlineBlack = within(outlineGroup).getByRole("radio", { name: "Black" });
const outlineWhite = within(outlineGroup).getByRole("radio", { name: "White" });

outlineBlack.focus();
fireEvent.keyDown(outlineBlack, { key: "ArrowRight" });
expect(outlineWhite).toHaveFocus();
expect(outlineWhite).toHaveAttribute("aria-checked", "true");
expect(outlineBlack).toHaveAttribute("aria-checked", "false");
});

it("keeps disabled palettes non-interactive while still exposing the checked swatch", () => {
mocks.appearance = {
...DEFAULT_SUBTITLE_APPEARANCE,
textOutline: false,
backgroundStyle: "none",
textOutlineColor: "#000000",
backgroundColor: "#374151",
};

render(<SubtitleAppearanceSettings />);

const outlineGroup = screen.getByRole("radiogroup", { name: "Outline color" });
const outlineBlack = within(outlineGroup).getByRole("radio", { name: "Black" });
expect(outlineBlack).toBeDisabled();
expect(outlineBlack).toHaveAttribute("aria-checked", "true");

const bgGroup = screen.getByRole("radiogroup", { name: "Background color" });
const bgDarkGray = within(bgGroup).getByRole("radio", { name: "Dark Gray" });
expect(bgDarkGray).toBeDisabled();
expect(bgDarkGray).toHaveAttribute("aria-checked", "true");
});
});
45 changes: 1 addition & 44 deletions web/src/pages/settings/SubtitleAppearanceSettings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ import {
import type { SubtitleAppearance } from "@/lib/subtitleAppearance";
import { toast } from "sonner";

import { ColorPalette } from "./ColorPalette";
import { ResetButton } from "./ResetButton";
import { isImeComposing } from "@/lib/imeComposition";

Expand All @@ -57,50 +58,6 @@ const PROFILE_KEYS: SettingKey[] = [
SETTING_KEYS.PLAYBACK_SHOW_FORCED_SUBTITLES,
];

interface ColorPaletteProps {
colors: { hex: string; label: string }[];
selected: string;
onChange: (hex: string) => void;
disabled?: boolean;
labelId?: string;
descriptionId?: string;
}

function ColorPalette({
colors,
selected,
onChange,
disabled,
labelId,
descriptionId,
}: ColorPaletteProps) {
return (
<div
role="group"
aria-labelledby={labelId}
aria-describedby={descriptionId}
className={`flex flex-wrap gap-2 ${disabled ? "opacity-40" : ""}`}
>
{colors.map((color) => (
<button
key={color.hex}
type="button"
title={color.label}
aria-label={color.label}
onClick={() => onChange(color.hex)}
disabled={disabled}
// The selected mark sits on the page, past a gap, so it stays
// visible whatever the swatch's own color is.
className={`h-7 w-7 rounded-full transition-transform hover:scale-110 ${
selected === color.hex ? "ring-primary ring-offset-background ring-2 ring-offset-2" : ""
} ${color.hex === "#000000" ? "inset-ring inset-ring-white/20" : ""}`}
style={{ backgroundColor: color.hex }}
/>
))}
</div>
);
}

/** A typed percentage value (1-100). A slider makes the low end — where a few
* percent is the difference between legible and invisible — fiddly to hit;
* typing the number directly doesn't have that problem. */
Expand Down
Loading