Skip to content
Merged
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
1 change: 1 addition & 0 deletions docs/design/system/decisions.md
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@ ledger: append-only
| 信息窗复制图标弱化档 | 新增 `--app-text-4`(spec §6 文本弱化档):信息窗复制路径 / 复制文件两图标默认色由 `--app-text-3` 降为该档,hover 提亮到 `--app-text`;该档仅用于低干扰辅助图标静息态,不用于任何文本;标题与路径保持左对齐 | editor-surface-batch24 / #1856 | 2026-11-30 |
| 画面按钮图标定案 | 取代台账「画面图标(#486):图片框构图(山与太阳)」行:控制条「画面」按钮改用「显示器 + 播放三角」(外框 + 底座 + 三角,单 `s` path,§2.1 安全区 / ≤6 笔画);新增 `visual` 概念键,与 `video` 文件类型图标(外框 + 三角)不同构图、不复用 path;两套图标源 + e2e mock 三处同步 | editor-surface-batch24 / #1857 | 2026-11-30 |
| 页签同比例收缩 | #1843 在固定上限模型上补「变窄时同比例收缩」:页签 `flex: 0 1 auto` + `min-width: 0` + `flex-shrink: 1`,移除 `calc-size(max-content, min(...))` 保底(WebKit 不支持),`--tab-min-width` 不再作收缩下限;短名按内容实际宽度、长名以 `--tab-max-width` 为上限并省略号收尾,全部页签在窗格变窄时按同一比例连续收缩 | #1843 | 2026-12-02 |
| 媒体表面默认固定暗色 | 音视频播放器的媒体表面(画面底色、底栏、控制条、菜单与 body 浮层)默认放入暗色 token 作用域(`data-media-theme="dark"`,复用 `.dark` 同一份暗色词表,不新增色值),另给「跟随应用主题」档恢复原行为;`tokens.css` 暗色块选择器由 `.dark` 扩为 `.dark, [data-media-theme="dark"]` | media-player-theme-switch / #1973 | 2026-12-02 |

**图标纪检 18px 高频裁决明细(11 行,spec §2.1 / §2.2 / §2.4)**

Expand Down
67 changes: 61 additions & 6 deletions e2e/player-theme.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,38 @@ const TINY_MP4 = readFileSync(
path.resolve(process.cwd(), "e2e/fixtures/tiny.mp4"),
).toString("base64");

async function openPlayer(page: Page): Promise<void> {
const EVIDENCE_DIR = process.env.EVIDENCE_DIR;
async function shot(page: Page, name: string): Promise<void> {
if (EVIDENCE_DIR) {
await page.screenshot({ path: path.join(EVIDENCE_DIR, `${name}.png`) });
}
}

async function openPlayer(
page: Page,
opts: { mediaTheme?: "follow" } = {},
): Promise<void> {
await page.addInitScript({ path: "./e2e/mocks/tauri-mock.js" });
if (opts.mediaTheme) {
// 真实配置加载路径:load_config 返回 follow,应用按配置归一化后进媒体表面。
await page.addInitScript((theme) => {
const w = window as unknown as {
__TAURI_INTERNALS__?: {
invoke?: (cmd: string, args?: unknown) => Promise<unknown>;
};
};
const internals = w.__TAURI_INTERNALS__;
if (!internals || typeof internals.invoke !== "function") return;
const orig = internals.invoke;
internals.invoke = async (cmd, args) => {
const res = await orig(cmd, args);
if (cmd === "load_config" && res && typeof res === "object") {
return { ...(res as Record<string, unknown>), mediaTheme: theme };
}
return res;
};
}, opts.mediaTheme);
}
await page.addInitScript(() => {
const w = window as unknown as Record<string, unknown>;
w.__biaoyue_media__ = [
Expand Down Expand Up @@ -145,10 +175,33 @@ const luminance = (rgb: string): number => {
return 0.299 * c[0] + 0.587 * c[1] + 0.114 * c[2];
};

test("浅色主题 + 默认配置:播放器固定暗色(#1973)", async ({ page }) => {
await openPlayer(page, {});
const c = await readChrome(page);
console.log("[player-theme dark-default]", JSON.stringify(c));

// 播放器底色 = 暗色 --app-bg(#131316),不是浅色底
expect(sameColor(c.playerBg, "#131316")).toBe(true);
// 控制条文字 = 暗色 --app-text(#d8dade)
expect(sameColor(c.controlColor, "#d8dade")).toBe(true);
await shot(page, "default-dark");

// body 浮层同源:倍速菜单底色 = 暗色 --app-surface(#1a1b1e)
await page.locator(".art-control[data-name='rate']").click();
await expect(page.locator(".rate-menu")).toBeVisible();
const rateMenuBg = await page.evaluate(
() =>
getComputedStyle(document.querySelector(".rate-menu")!).backgroundColor,
);
console.log("[player-theme dark-default rate]", rateMenuBg);
expect(sameColor(rateMenuBg, "#1a1b1e")).toBe(true);
await shot(page, "default-dark-menu");
});

test("浅色主题:播放器底/控制条非黑,文字随 app-text,强调色随 app-accent", async ({
page,
}) => {
await openPlayer(page);
await openPlayer(page, { mediaTheme: "follow" });
const c = await readChrome(page);
console.log("[player-theme light]", JSON.stringify(c));

Expand All @@ -171,11 +224,13 @@ test("浅色主题:播放器底/控制条非黑,文字随 app-text,强调
});

test("暗色主题:切换 .dark 后底色变暗且随暗色 token", async ({ page }) => {
await openPlayer(page);
await openPlayer(page, { mediaTheme: "follow" });
const light = await readChrome(page);
await shot(page, "follow-light");
await page.evaluate(() => document.documentElement.classList.add("dark"));
await page.waitForTimeout(200);
const dark = await readChrome(page);
await shot(page, "follow-dark-app");
console.log("[player-theme dark]", JSON.stringify(dark));

expect(isBlack(dark.playerBg)).toBe(false);
Expand Down Expand Up @@ -293,7 +348,7 @@ function readPopovers(page: Page): Promise<PopoverChrome> {
test("浅色主题:自研浮层与 Artplayer 浮层底色随 app-surface,文字随 app-text", async ({
page,
}) => {
await openPlayer(page);
await openPlayer(page, { mediaTheme: "follow" });

// 倍速菜单(单独打开读取,避免浮层互相关闭)
await page.locator(".art-control[data-name='rate']").click();
Expand Down Expand Up @@ -382,7 +437,7 @@ test("浅色主题:自研浮层与 Artplayer 浮层底色随 app-surface,文
});

test("暗色主题:浮层随 .dark 变深且文字随暗色 token", async ({ page }) => {
await openPlayer(page);
await openPlayer(page, { mediaTheme: "follow" });
await page.locator(".art-control[data-name='rate']").click();
await expect(page.locator(".rate-menu")).toBeVisible();
const light = await readPopovers(page);
Expand Down Expand Up @@ -437,7 +492,7 @@ test("暗色主题:浮层随 .dark 变深且文字随暗色 token", async ({ p
test("浅色主题:按钮悬停提示(hint 伪元素)非黑,随 app-surface/app-text(#1957)", async ({
page,
}) => {
await openPlayer(page);
await openPlayer(page, { mediaTheme: "follow" });
const r = await page.evaluate(() => {
const root = getComputedStyle(document.documentElement);
const token = (k: string) => root.getPropertyValue(k).trim();
Expand Down
2 changes: 1 addition & 1 deletion openspec/changes/media-player-theme-switch/design.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@

| 落点 | 位置 | 载体/符号 | 判据 |
|---|---|---|---|
| 规格 | docs/design/system/spec.md | — | 只消费既有 `--app-*` 语义色,不新增色值;暗色词表复用同一份定义 |
| 规格 | design-system:§6 | — | 只消费既有 `--app-*` 语义色,不新增色值;暗色词表复用同一份定义 |
| 存储 | src-tauri/src/config.rs | media_theme | `Option<String>`,camelCase 序列化为 `mediaTheme`,缺省 None 语义为 dark |
| 校验 | src-tauri/src/config.rs | validate_config | `check_enum` 仅接受 `dark|follow`,非法值拒绝且不落盘 |
| 桥接 | src/hooks/useConfig.ts | saveAppConfig | 读 store 的 `mediaTheme` 写盘;加载时未知值回落 `dark` |
Expand Down
2 changes: 1 addition & 1 deletion openspec/changes/media-player-theme-switch/tasks.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

## 1. 媒体主题开关

- [ ] 1.1 配置项 `mediaTheme` + 播放器默认暗色作用域(容器与 `body` 浮层同源),并改写既有的播放器主题默认态用例
- [x] 1.1 配置项 `mediaTheme` + 播放器默认暗色作用域(容器与 `body` 浮层同源),并改写既有的播放器主题默认态用例
- **数据面**: 规格,存储,校验,桥接,消费,回滚(六栏见 design.md「## 数据面」)
- [ ] 1.2 设置 → 外观 新增「音视频固定暗色背景」开关,接跟随档热应用与持久化,补开关与重启保持用例(Blocked by 1.1)
- **数据面**: 消费
45 changes: 44 additions & 1 deletion src-tauri/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,12 @@ pub struct AppConfig {
/// Default 给 Some(理由同 pane_mode);反序列化缺键仍回落 medium。
#[serde(default, skip_serializing_if = "Option::is_none")]
pub pane_scale: Option<String>,
/// 媒体表面主题(media-player-theme-switch / #1973):dark(固定暗色,缺省)/
/// follow(跟随应用主题)。缺省 None 的语义 = dark(前端归一化)。
/// `default` + `skip_serializing_if` 让老配置仍能读、新配置不多出空字段;
/// 补丁白名单由 `nested_defaults()` 显式登记(与 bodyFont 同一处理)。
#[serde(default, skip_serializing_if = "Option::is_none")]
pub media_theme: Option<String>,
}

/// 扩展包启用态(extension-package-v2 D5):settings 优先于旧 `.disabled` 标记。
Expand Down Expand Up @@ -326,6 +332,7 @@ impl Default for AppConfig {
// skip_serializing_if 跳出白名单,故预设键的 default 给 Some。
pane_mode: Some("standard".into()),
pane_scale: Some("medium".into()),
media_theme: None,
sidebar_left_visible: Some(true),
sidebar_right_visible: Some(false),
sidebar_left_width: Some(220.0),
Expand Down Expand Up @@ -724,6 +731,11 @@ pub fn validate_config(config: &AppConfig) -> Result<(), AppError> {
config.pane_scale.as_deref(),
&["small", "medium", "large"],
)?;
check_enum(
"mediaTheme",
config.media_theme.as_deref(),
&["dark", "follow"],
)?;
if let Some(spec) = &config.rail_view_spec {
check_enum(
"railViewSpec.layout",
Expand Down Expand Up @@ -1112,7 +1124,8 @@ fn nested_defaults() -> Value {
"searchHoverPreview": null,
"iconLabel": null,
"paneLayout": null,
"bodyFont": null
"bodyFont": null,
"mediaTheme": null
})
}

Expand Down Expand Up @@ -1296,6 +1309,7 @@ pub(crate) const SKILL_MAP: &str = r#"# Biaoyue 配置地图
| `readerSkin` | `paper` / `indigo` / `moss` / `clay`(兼容 `plain`) |
| `paneMode` | `simple` / `standard` / `hardcore` |
| `paneScale` | `small` / `medium` / `large` |
| `mediaTheme` | `dark` / `follow` |
| `propertyBar.displayStyle` | `list` / `dual` |
| `propertyBar.displayDefault.preview` / `.edit` | `show` / `collapse` / `hide` |
| `propertyBar.newDocVisible` | `true` / `false` |
Expand Down Expand Up @@ -2953,6 +2967,35 @@ mod tests {
}
}

#[test]
fn media_theme_patch_accepts_follow_and_rejects_light() {
let dir = temp_base("media_theme");
let base = dir.path();
write_user(base, r#"{"theme":"light"}"#);

// 缺省 = None(语义 dark),补丁边界必须接受合法键。
assert_eq!(load_config_at(base).unwrap().media_theme, None);
let patched = apply_patch_at(base, &serde_json::json!({"mediaTheme": "follow"}))
.expect("follow 应被接受");
assert_eq!(patched.media_theme.as_deref(), Some("follow"));
assert_eq!(
load_config_at(base).unwrap().media_theme.as_deref(),
Some("follow")
);

// 非法值:校验拒绝且不落盘(user 层字节不变)。
let after_follow = read_user(base);
let err = apply_patch_at(base, &serde_json::json!({"mediaTheme": "light"})).unwrap_err();
assert!(matches!(err, AppError::Validation { .. }), "got {err:?}");
assert_eq!(read_user(base), after_follow);
assert_eq!(
load_config_at(base).unwrap().media_theme.as_deref(),
Some("follow")
);
let user: Value = serde_json::from_str(&read_user(base)).unwrap();
assert_eq!(user["mediaTheme"], serde_json::json!("follow"));
}

#[test]
fn keyring_uses_platform_store_not_mock() {
// keyring v3 不默认开启任何平台凭据库 feature;缺失时静默退回内存 mock,
Expand Down
29 changes: 29 additions & 0 deletions src/__tests__/mediaPlayerHost.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@ import { describe, it, expect, afterEach, vi } from "vitest";
import { render, act } from "@testing-library/react";
import MediaPlayerHost from "../components/Content/MediaPlayerHost";
import { mediaPlayer } from "../components/Content/mediaPlayerState";
import { useEditorStore } from "../stores/editorStore";

afterEach(() => {
mediaPlayer.stop();
useEditorStore.getState().reset();
});

describe("MediaPlayerHost 媒体播放器宿主(无迷你条)", () => {
Expand Down Expand Up @@ -113,4 +115,31 @@ describe("MediaPlayerHost 媒体播放器宿主(无迷你条)", () => {
});
expect(fn).toHaveBeenCalledTimes(2);
});

it("默认(缺省)媒体主题 = dark:宿主挂 data-media-theme=dark", () => {
act(() => {
mediaPlayer.show({
filePath: "/tmp/clip.mp4",
url: "media://localhost/tmp/clip.mp4",
fileKind: "video",
});
});
const { container } = render(<MediaPlayerHost />);
const host = container.firstElementChild as HTMLElement;
expect(host.getAttribute("data-media-theme")).toBe("dark");
});

it("mediaTheme=follow:宿主不挂 data-media-theme", () => {
act(() => {
useEditorStore.getState().setConfig({ mediaTheme: "follow" });
mediaPlayer.show({
filePath: "/tmp/clip.mp4",
url: "media://localhost/tmp/clip.mp4",
fileKind: "video",
});
});
const { container } = render(<MediaPlayerHost />);
const host = container.firstElementChild as HTMLElement;
expect(host.getAttribute("data-media-theme")).toBeNull();
});
});
18 changes: 18 additions & 0 deletions src/__tests__/mediaTheme.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { describe, expect, it } from "vitest";
import { normalizeMediaTheme } from "../hooks/useConfig";

describe("normalizeMediaTheme(media-player-theme-switch / #1973)", () => {
it("缺省 / null / 未知值一律回落 dark", () => {
expect(normalizeMediaTheme(undefined)).toBe("dark");
expect(normalizeMediaTheme(null)).toBe("dark");
expect(normalizeMediaTheme("light")).toBe("dark");
expect(normalizeMediaTheme("DARK")).toBe("dark");
expect(normalizeMediaTheme("")).toBe("dark");
});

it("仅精确 follow 保留", () => {
expect(normalizeMediaTheme("follow")).toBe("follow");
expect(normalizeMediaTheme("follow ")).toBe("dark");
expect(normalizeMediaTheme("Follow")).toBe("dark");
});
});
18 changes: 11 additions & 7 deletions src/__tests__/styles/themeShadowTokens.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { fileURLToPath } from "node:url";
const tokensCss = readFileSync(
fileURLToPath(new URL("../../styles/tokens.css", import.meta.url)),
"utf8",
);
).replace(/\/\*[\s\S]*?\*\//g, "");

const SHADOW_KEYS = [
"--shadow-menu",
Expand All @@ -17,12 +17,16 @@ const SHADOW_KEYS = [
] as const;

function block(selector: string): string {
const escaped = selector.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const match = tokensCss.match(
new RegExp(`(?:^|\\n)\\s*${escaped}\\s*\\{([\\s\\S]*?)\\}`),
);
if (!match) throw new Error(`未找到 ${selector} 块`);
return match[1];
for (const m of tokensCss.matchAll(
/(?:^|\n)\s*([^{}]+?)\s*\{([\s\S]*?)\}/g,
)) {
const selectors = m[1]
.split(",")
.map((s) => s.trim())
.filter(Boolean);
if (selectors.includes(selector)) return m[2];
}
throw new Error(`未找到 ${selector} 块`);
}

function shadowTokens(selector: string): Map<string, string> {
Expand Down
11 changes: 10 additions & 1 deletion src/components/Content/MediaPlayerHost.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
type MediaPlayerState,
type MediaSource,
} from "./mediaPlayerState";
import { useEditorStore } from "../../stores/editorStore";
import VideoPlayer from "./VideoPlayer";

interface Rect {
Expand Down Expand Up @@ -93,6 +94,9 @@ function PaneMediaPlayer({
visible: boolean;
}) {
const hostRef = useRef<HTMLDivElement>(null);
const mediaDark = useEditorStore(
(s) => (s.config.mediaTheme ?? "dark") !== "follow",
);
const paneId = source.paneId ?? null;
const embedded = source.embedded === true;
const [paneRect, setPaneRect] = useState<{
Expand Down Expand Up @@ -150,7 +154,12 @@ function PaneMediaPlayer({
};

return (
<div ref={hostRef} style={style} data-media-pane={paneId ?? undefined}>
<div
ref={hostRef}
style={style}
data-media-pane={paneId ?? undefined}
data-media-theme={mediaDark ? "dark" : undefined}
>
<VideoPlayer
filePath={source.filePath}
url={source.url}
Expand Down
12 changes: 11 additions & 1 deletion src/components/Content/VideoPlayer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { invoke } from "@tauri-apps/api/core";
import { getCurrentWindow } from "@tauri-apps/api/window";
import { getActiveEditorView } from "../../editors/editorRef";
import { useStore } from "../../stores";
import { useEditorStore } from "../../stores/editorStore";
import Icon from "../Icon";
import { iconSvg, type IconName } from "../../ui/icons";
import { isMediaMuted, setMediaMuted, subscribeMediaMute } from "./mediaMute";
Expand Down Expand Up @@ -263,6 +264,9 @@ export default function VideoPlayer({
onTimeUpdate,
}: VideoPlayerProps) {
const rootRef = useRef<HTMLDivElement>(null);
const mediaDark = useEditorStore(
(s) => (s.config.mediaTheme ?? "dark") !== "follow",
);
const containerRef = useRef<HTMLDivElement>(null);
const canvasRef = useRef<HTMLCanvasElement>(null);
const artRef = useRef<Artplayer | null>(null);
Expand Down Expand Up @@ -2755,6 +2759,7 @@ export default function VideoPlayer({
return (
<div
ref={rootRef}
data-media-theme={mediaDark ? "dark" : undefined}
style={{
position: "relative",
display: "flex",
Expand Down Expand Up @@ -2864,7 +2869,12 @@ export default function VideoPlayer({

{popover &&
(popoverFixed
? createPortal(popoverPanel, document.body)
? createPortal(
<div data-media-theme={mediaDark ? "dark" : undefined}>
{popoverPanel}
</div>,
document.body,
)
: popoverPanel)}

{/* 时间戳笔记窗口:可拖动 + 可调整大小 */}
Expand Down
Loading
Loading