From 1c1eae68888c61adeec1aecee8c97819e52ad100 Mon Sep 17 00:00:00 2001 From: KnowSky404 Date: Tue, 27 Oct 2026 16:19:41 +0800 Subject: [PATCH] feat(ui): restore navigation hierarchy and actionable feedback --- .../plans/2026-10-27-ui-hierarchy-polish.md | 67 +++++ docs/wiki/Changelog.md | 15 + docs/wiki/Changelog.zh-CN.md | 11 + docs/wiki/User-Guide.md | 10 + docs/wiki/User-Guide.zh-CN.md | 8 + e2e/accessibility.spec.ts | 140 +-------- e2e/ui-polish.spec.ts | 265 ++++++++++++++++++ e2e/ui-workspace-fixture.ts | 155 ++++++++++ e2e/workspace-v2.spec.ts | 39 +-- src/app.css | 169 ++++++++--- src/lib/actions/tooltip.ts | 132 +++++++++ src/lib/i18n.ts | 176 ++++++++++++ src/routes/+layout.svelte | 132 ++++++++- src/routes/+page.svelte | 138 ++++++++- src/routes/aggregate/+page.svelte | 36 ++- src/routes/auth/+page.svelte | 4 + src/routes/exports/+page.svelte | 17 +- src/routes/gists/+page.svelte | 23 +- src/routes/nodes/+page.svelte | 62 ++-- src/routes/nodes/page-source.test.ts | 4 +- 20 files changed, 1357 insertions(+), 246 deletions(-) create mode 100644 docs/archive/plans/2026-10-27-ui-hierarchy-polish.md create mode 100644 e2e/ui-polish.spec.ts create mode 100644 e2e/ui-workspace-fixture.ts create mode 100644 src/lib/actions/tooltip.ts diff --git a/docs/archive/plans/2026-10-27-ui-hierarchy-polish.md b/docs/archive/plans/2026-10-27-ui-hierarchy-polish.md new file mode 100644 index 0000000..40b19d6 --- /dev/null +++ b/docs/archive/plans/2026-10-27-ui-hierarchy-polish.md @@ -0,0 +1,67 @@ +# UI hierarchy and interaction polish + +## Scope and isolation + +- Worktree: `/root/Clouds/SubMan-ui-polish` +- Branch: `feat/ui-hierarchy-polish` +- Base: `e015b6f650abfe8c3aa89cbf9c741495f783e465` +- Preserve the existing Primer palette, Svelte architecture, single cloud binding, + persistence boundary, and cloud-confirmed operation semantics. +- Local implementation and commit are authorized. Remote publication, merging, + Wiki publication, and production deployment require separate authorization. + +## Implementation + +1. Separate the brand toolbar and navigation with distinct surfaces and borders. + Align both with the content, enlarge the home-linked brand, surface connection + and pending states as text, and make overflowing navigation discoverable. +2. Provide shared, viewport-aware tooltips for icon actions with hover, keyboard + focus, Escape dismissal, and cleanup. Complete theme-menu keyboard behavior. +3. Restore dark primary-button emphasis, readable metadata, useful row hover and + focus states, search-icon spacing, larger touch controls, distinct filtered + empty states, and honest file-link affordances. Remove duplicate list actions + and status metadata without hiding the cloud confirmation state. +4. Adapt the overview to existing data with recent resources and publication + targets. Derive published URLs and dates from the confirmed binding baseline; + retain onboarding for empty workspaces and avoid a new activity storage path. +5. Group aggregation inputs into sources and optional advanced configuration. + Keep existing non-default configuration discoverable, preserve drafts and + protocol behavior, and explain saved rules, targets, and publication prerequisites. +6. Update both Wiki changelogs and verify the final patch before an atomic + Conventional Commit. + +## Validation + +- Bun 1.3.14; independent dependencies, generated output, Worker state, browser + contexts, and development ports in this worktree. +- Run docs checks, unit tests, Svelte/Worker type checks, lint, production build, + and affected Worker/browser checks. Use local mock Gists only. +- Browser plugin is unavailable; use Playwright Chromium. Verify all six routes, + light/dark themes, English/Chinese, desktop/mobile, tooltip hover/focus/Escape, + navigation overflow, theme keyboard interaction, search reset, file links, + overview states, and advanced configuration visibility. +- Inspect screenshots and console output. Record outcomes and limitations in the + handoff; retain the task worktree for review and any later authorized PR. + +## Execution record + +- Implemented all six steps with the existing design tokens and Octicons. Added + no dependency, business storage, public API, or cloud mutation behavior. +- Passed 679 unit tests, documentation validation (37 bilingual pages), Svelte and + Worker type checks (zero errors/warnings), lint, production builds, eight local + Cloudflare integration tests, the sing-box 1.14 check (15 generated outbounds), + and the local deployment-bundle dry run. +- Passed the full 56-case Playwright suite with one worker, matching CI. After + the final tooltip-listener cleanup, the eight UI cases and two settings cases + passed again. The five migration variants passed after fixing a test-only race + between checking readiness and interacting with a disappearing migration panel. +- Exploratory parallel runs exposed timing-sensitive existing delivery cases; + isolated checks passed on both the original baseline and the task branch. + Production delivery and migration behavior was preserved. +- Inspected all six routes at 1440px and narrow layouts at 390px and 320px, in + light/dark themes and English/Chinese. Browser console checks found no app + errors or warnings; no page overflow or framework error overlay was observed. +- Temporary browser artifacts and logs are outside the source worktree in + `/tmp/subman-ui-polish-qa`. Real GitHub Gists and production were not accessed. +- Delivery remains a local task commit and retained worktree. Push, PR review, + merge, main sync, and merged-branch cleanup have not been authorized. diff --git a/docs/wiki/Changelog.md b/docs/wiki/Changelog.md index d77742e..f7d8cc4 100644 --- a/docs/wiki/Changelog.md +++ b/docs/wiki/Changelog.md @@ -8,6 +8,21 @@ production deployment and real-provider acceptance require separate evidence. ## Unreleased +### 2026-10-27 - UI hierarchy and interaction polish + +- Separated the linked brand toolbar from navigation, aligned the header with the + page, and added visible cloud status, accessible tooltips, keyboard theme controls, + and a navigation overflow control on narrow screens. +- Restored primary-button emphasis in dark mode and readable list metadata; + removed duplicate node actions/status, fixed search spacing and filtered empty + states, enlarged touch actions, and made available Gist filenames real links. +- Adapted the overview to recent resources and confirmed publication metadata; + retained empty-workspace onboarding. Grouped advanced rule options and explained + save, preview, target, and publication prerequisites without changing cloud writes. +- Completed Chinese labels on these surfaces and localized resource timestamps; + kept browser test fixtures reusable and screenshots isolated per test. + + ### 2026-10-26 - Simplified application chrome - Replaced header status badges, Gist ID, and setup button with a compact status diff --git a/docs/wiki/Changelog.zh-CN.md b/docs/wiki/Changelog.zh-CN.md index d9f6197..e75e73a 100644 --- a/docs/wiki/Changelog.zh-CN.md +++ b/docs/wiki/Changelog.zh-CN.md @@ -7,6 +7,17 @@ ## 未发布 +### 2026-10-27 - 页面层级与交互优化 + +- 区分可返回首页的品牌工具栏与业务导航,统一页头和正文对齐;增加可见的云端状态、 + 支持悬停和键盘聚焦的图标提示、主题菜单键盘操作及小屏导航翻页入口。 +- 恢复暗色主按钮的强调色,提高列表辅助信息可读性;删除重复的新建入口和状态信息, + 修复搜索图标间距、区分空数据和筛选无结果,增大触摸按钮并让可用文件名成为真实链接。 +- 首页根据已有数据展示最近资源和已确认的发布信息,空工作区保留入门指引; + 聚合页收纳高级配置并说明保存、预览、目标与发布的关系,云端写入协议保持不变。 +- 补齐相关界面的中文标签并本地化资源更新时间;复用浏览器测试数据,按用例隔离截图。 + + ### 2026-10-26 - 精简页面与顶部工具栏 - 将顶部状态标签、Gist ID 和设置按钮收为状态、主题、GitHub 三个图标, diff --git a/docs/wiki/User-Guide.md b/docs/wiki/User-Guide.md index 78c8289..a49a31c 100644 --- a/docs/wiki/User-Guide.md +++ b/docs/wiki/User-Guide.md @@ -21,6 +21,11 @@ if data is missing or a document is rejected. ## Manage resources +The brand links to the overview. The header shows connection and pending cloud +states; icon labels appear on hover or keyboard focus. On narrow screens, use the +navigation arrow to reach additional pages. The overview shows onboarding for an +empty Workspace, then recent resources and confirmed publication metadata. + | Page | Purpose | | --- | --- | | `/auth` | Connection, token, delivery status, cloud reload, migration, and diagnostics | @@ -34,6 +39,11 @@ resolve duplicates before adding. Aggregates select nodes and subscriptions, exclude tags, filter protocols, apply regex renaming, add region flags, and sort by names, protocols, regions, priority keywords, or manual ordering. +Open **Advanced rule options** for protocol filtering, sorting, renaming, and +region flags. Existing non-default options open automatically when loading a rule. +Saving a rule or target stores configuration; publishing generates the output file. +For client exports, save profile changes and generate a current preview before publishing. + Subscription URLs must permit browser access. Fetches have a 15-second timeout and 4 MiB response limit; network/CORS, HTTP, size, encoding, and empty responses have separate errors. See the [export guide](../sing-box-export.md) for supported diff --git a/docs/wiki/User-Guide.zh-CN.md b/docs/wiki/User-Guide.zh-CN.md index 27a0489..b6d1eeb 100644 --- a/docs/wiki/User-Guide.zh-CN.md +++ b/docs/wiki/User-Guide.zh-CN.md @@ -16,6 +16,10 @@ SubMan 查找描述为 `SubMan-Data`、包含权威文档 `subman.json` 的私 ## 管理资源 +点击品牌可返回概览。页头直接显示连接与待云端确认状态,图标支持悬停和键盘聚焦提示。 +小屏幕可通过导航箭头查看后面的页面入口。空工作区显示入门指引,已有数据后展示最近资源 +和已确认的发布信息。 + | 页面 | 用途 | | --- | --- | | `/auth` | 连接、Token、发送状态、云端重载、迁移和诊断 | @@ -28,6 +32,10 @@ SubMan 查找描述为 `SubMan-Data`、包含权威文档 `subman.json` 的私 聚合规则可选择节点和订阅、排除标签、过滤协议、正则重命名、添加地区旗帜, 并按名称、协议、地区、优先关键词或手动拖拽排序。 +展开“高级规则选项”可设置协议过滤、排序、重命名和地区旗帜;加载已有非默认配置的规则时 +会自动展开。保存规则或目标只保存配置,发布才会生成输出文件。客户端导出需要先保存配置 +修改并生成最新预览,再发布。 + 订阅地址需要允许浏览器访问。请求超时为 15 秒,响应上限为 4 MiB;网络/CORS、HTTP、 大小、编码和空内容分别提示错误。[导出指南](../sing-box-export.zh-CN.md)说明支持的协议、 警告和 sing-box 1.14 兼容范围。 diff --git a/e2e/accessibility.spec.ts b/e2e/accessibility.spec.ts index 41c3b9a..fcdea00 100644 --- a/e2e/accessibility.spec.ts +++ b/e2e/accessibility.spec.ts @@ -1,145 +1,10 @@ import { expect, test } from "@playwright/test"; +import { seedUiWorkspace } from "./ui-workspace-fixture"; const routes = ["/", "/auth", "/nodes", "/aggregate", "/exports", "/gists"]; test.beforeEach(async ({ page, context }) => { - const now = "2026-10-23T10:00:00.000Z"; - const gistId = "accessibility-cloud"; - const data = { - nodes: [ - { - id: "accessibility-node", - name: "Accessibility Node", - type: "vless", - raw: "vless://00000000-0000-4000-8000-000000000001@example.com:443#A11y", - tags: [], - enabled: true, - updatedAt: now, - source: "single", - }, - ], - subscriptions: [], - aggregates: [], - publishTargets: [], - clientExports: [], - }; - const document = { - version: 2, - schemaVersion: 2, - workspaceId: `gist:${gistId}`, - revision: 0, - updatedAt: now, - lastMutationId: null, - data, - tombstones: { - nodes: [], - subscriptions: [], - aggregates: [], - publishTargets: [], - clientExports: [], - }, - }; - await context.route("https://api.github.com/**", async (route) => { - if ( - route.request().method() !== "GET" || - new URL(route.request().url()).pathname !== `/gists/${gistId}` - ) { - await route.abort("blockedbyclient"); - return; - } - await route.fulfill({ - json: { - id: gistId, - owner: { login: "e2e" }, - description: "SubMan-Data", - updated_at: now, - html_url: `https://gist.github.com/e2e/${gistId}`, - files: { - "subman.json": { - filename: "subman.json", - content: JSON.stringify(document), - truncated: false, - }, - }, - }, - }); - }); - await context.route("**/__e2e_seed__", (route) => - route.fulfill({ - status: 200, - contentType: "text/html", - body: "SubMan E2E seed", - }), - ); - await page.goto("/__e2e_seed__"); - await page.evaluate( - async ({ gistId, now, data, document }) => { - const database = await new Promise((resolve, reject) => { - const request = indexedDB.open("subman-workspace", 1); - request.onupgradeneeded = () => - request.result.createObjectStore("workspace-state"); - request.onsuccess = () => resolve(request.result); - request.onerror = () => reject(request.error); - }); - await new Promise((resolve, reject) => { - const transaction = database.transaction( - "workspace-state", - "readwrite", - ); - transaction.objectStore("workspace-state").put( - { - version: 1, - snapshot: { - ...data, - gists: [], - activeGistId: gistId, - activeGistFile: "subman.json", - lastUpdated: now, - }, - binding: { - version: 2, - gistId, - workspaceId: `gist:${gistId}`, - fileName: "subman.json", - revision: 0, - syncMode: "automatic", - baseline: document, - conflictBaseline: null, - }, - workspaces: {}, - leases: {}, - quarantines: [], - quarantinePayloads: {}, - nextFencingToken: 1, - migration: { - version: 1, - phase: "confirmed", - startedAt: now, - copiedAt: now, - validatedAt: now, - updatedAt: now, - confirmedAt: now, - cleanupCompletedAt: now, - }, - }, - "root", - ); - transaction.oncomplete = () => resolve(); - transaction.onerror = () => reject(transaction.error); - transaction.onabort = () => reject(transaction.error); - }); - database.close(); - sessionStorage.setItem( - "subman:auth:session:v2", - JSON.stringify({ - version: 2, - token: "fixture-accessibility-token", - lastLoginAt: now, - }), - ); - }, - { gistId, now, data, document }, - ); + await seedUiWorkspace(page, context); }); test.describe("basic route accessibility", () => { @@ -245,6 +110,7 @@ test("aggregate region dialog exposes focus and Escape behavior", async ({ page, }) => { await page.goto("/aggregate"); + await page.locator("details.gh-advanced-options > summary").click(); const openButton = page.getByRole("button", { name: "Browse Icons" }); await openButton.click(); diff --git a/e2e/ui-polish.spec.ts b/e2e/ui-polish.spec.ts new file mode 100644 index 0000000..b735a5b --- /dev/null +++ b/e2e/ui-polish.spec.ts @@ -0,0 +1,265 @@ +import { expect, test } from "@playwright/test"; +import { defaultUiData, seedUiWorkspace } from "./ui-workspace-fixture"; + +test("header tooltips support hover, focus, Escape, and viewport edges", async ({ + page, + context, +}) => { + await seedUiWorkspace(page, context); + await page.goto("/nodes"); + await expect(page.locator(".app-header-link-connected")).toBeVisible(); + const github = page.getByRole("link", { name: "Open project on GitHub" }); + await github.hover(); + const tip = page.getByRole("tooltip"); + await expect(tip).toHaveText("Open project on GitHub"); + const bounds = await tip.boundingBox(); + if (!bounds) throw new Error("Tooltip did not render"); + expect(bounds.x + bounds.width).toBeLessThanOrEqual( + (await page.evaluate(() => innerWidth)) - 7, + ); + await page.keyboard.press("Escape"); + await expect(tip).toHaveCount(0); + await github.focus(); + await expect(tip).toBeVisible(); + await expect(github).toHaveAttribute( + "aria-describedby", + (await tip.getAttribute("id")) as string, + ); + await expect(github).not.toHaveAttribute("title"); + await page.keyboard.press("Tab"); + await page.mouse.move(0, 0); + await expect(tip).toHaveCount(0); +}); + +test("theme menu supports keyboard selection and preserves primary emphasis in dark mode", async ({ + page, + context, +}) => { + await seedUiWorkspace(page, context); + await page.goto("/"); + await expect(page.locator(".app-header-link-connected")).toBeVisible(); + const trigger = page.locator(".theme-menu-button"); + await trigger.focus(); + await page.keyboard.press("Enter"); + await expect(page.getByRole("menuitemradio", { name: "Auto" })).toBeFocused(); + await page.keyboard.press("End"); + await expect(page.getByRole("menuitemradio", { name: "Dark" })).toBeFocused(); + await page.keyboard.press("Enter"); + await expect(page.locator("html")).toHaveAttribute("data-theme", "dark"); + await expect(trigger).toBeFocused(); + await expect(page.getByRole("menu", { name: "Theme" })).toHaveCount(0); + await expect(page.locator("main .gh-btn-primary").first()).toHaveCSS( + "background-color", + "rgb(35, 134, 54)", + ); + await trigger.click(); + await page.keyboard.press("Escape"); + await expect(trigger).toBeFocused(); + await expect(trigger).toHaveAttribute("aria-expanded", "false"); +}); + +test("node search distinguishes no matches and clears the complete filter", async ({ + page, + context, +}) => { + await seedUiWorkspace(page, context); + await page.goto("/nodes"); + await expect(page.locator(".app-header-link-connected")).toBeVisible(); + await expect( + page.getByRole("button", { name: "New Resource", exact: true }), + ).toHaveCount(1); + const search = page.getByRole("textbox", { + name: "Filter resources", + exact: true, + }); + await search.fill("missing-resource"); + await expect( + page.getByRole("heading", { name: "No matching resources" }), + ).toBeVisible(); + await expect(page.getByRole("heading", { name: "No nodes yet" })).toHaveCount( + 0, + ); + await page.locator("#resource-filter-status").click(); + await page + .getByRole("menu") + .getByRole("button", { name: "Disabled", exact: true }) + .click(); + await page.getByRole("button", { name: "Clear filters" }).click(); + await expect(search).toHaveValue(""); + await expect(page.locator("#resource-filter-status")).toContainText("All"); + await expect( + page.getByRole("button", { name: "Accessibility Node", exact: true }), + ).toBeVisible(); + await expect(search).toHaveCSS("padding-left", "36px"); +}); + +test("mobile navigation reveals settings and keeps the selected page visible", async ({ + page, + context, +}) => { + await page.setViewportSize({ width: 390, height: 844 }); + await page.emulateMedia({ reducedMotion: "reduce" }); + await seedUiWorkspace(page, context); + await page.goto("/"); + await expect(page.locator(".app-header-link-connected")).toBeVisible(); + for (let attempt = 0; attempt < 4; attempt++) { + const more = page.getByRole("button", { + name: "More navigation items", + exact: true, + }); + if (!(await more.count())) break; + const previous = await page + .locator("nav") + .evaluate((node) => node.scrollLeft); + await more.click(); + await expect + .poll(() => page.locator("nav").evaluate((node) => node.scrollLeft)) + .toBeGreaterThan(previous); + } + const settings = page + .getByRole("navigation", { name: "Primary" }) + .getByRole("link", { name: "Settings" }); + await expect(settings).toBeInViewport({ ratio: 1 }); + await settings.click(); + await expect(page).toHaveURL(/\/auth$/); + await expect(settings).toHaveAttribute("aria-current", "page"); + await expect(settings).toBeInViewport({ ratio: 1 }); + expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBe( + 390, + ); +}); + +test("overview changes from onboarding to recent resources and confirmed output metadata", async ({ + page, + context, +}) => { + const data = structuredClone(defaultUiData); + data.aggregates.push({ + id: "ui-rule", + name: "UI rule", + nodeIds: [data.nodes[0].id], + subscriptionIds: [], + excludeTagIds: [], + renameMap: {}, + allowedTypes: [], + updatedAt: "2026-10-23T10:00:00.000Z", + }); + data.publishTargets.push({ + id: "ui-target", + name: "Published target", + ruleId: "ui-rule", + fileName: "nodes.txt", + description: "", + isPublic: false, + lastPublishedAt: "2026-10-23T10:00:00.000Z", + lastPublishedUrl: + "https://gist.githubusercontent.com/e2e/accessibility-cloud/raw/nodes.txt", + lastPublishTransitionAt: null, + lastPublishTransitionFromFileName: null, + lastPublishTransitionToFileName: null, + lastPublishTransitionOutcome: null, + updatedAt: "2026-10-23T10:00:00.000Z", + }); + await seedUiWorkspace(page, context, data); + await page.goto("/"); + await expect(page.locator(".app-header-link-connected")).toBeVisible(); + await expect( + page.getByRole("heading", { name: "Recently updated" }), + ).toBeVisible(); + await expect( + page.getByRole("heading", { name: "Collect sources" }), + ).toHaveCount(0); + const publications = page.getByRole("region", { + name: "Publication targets", + }); + await expect( + publications.getByRole("link", { name: /Published target/ }), + ).toContainText("Last published"); + await expect(publications.getByText("nodes.txt")).toBeVisible(); +}); + +test("empty workspace retains onboarding and advanced controls keep drafts", async ({ + page, + context, +}) => { + await seedUiWorkspace(page, context, { + nodes: [], + subscriptions: [], + aggregates: [], + publishTargets: [], + clientExports: [], + }); + await page.goto("/"); + await expect(page.locator(".app-header-link-connected")).toBeVisible(); + await expect( + page.getByRole("heading", { name: "Collect sources" }), + ).toBeVisible(); + await page.goto("/aggregate"); + await expect(page.locator(".app-header-link-connected")).toBeVisible(); + const advanced = page.locator("details.gh-advanced-options"); + await expect(advanced).not.toHaveAttribute("open"); + await advanced.locator("summary").click(); + await page + .getByRole("textbox", { name: "Rename Rules", exact: true }) + .fill("Old = New"); + await advanced.locator("summary").click(); + await advanced.locator("summary").click(); + await expect( + page.getByRole("textbox", { name: "Rename Rules", exact: true }), + ).toHaveValue("Old = New"); + await expect( + page.getByText("Save a publish target before publishing.", { exact: true }), + ).toBeVisible(); +}); + +test("Gist filenames expose real raw links and accessible icon labels", async ({ + page, + context, +}) => { + await seedUiWorkspace(page, context); + await page.goto("/gists"); + await expect(page.locator(".app-header-link-connected")).toBeVisible(); + await expect( + page.getByRole("link", { name: "subman.json · Open Raw" }), + ).toHaveAttribute( + "href", + "https://gist.githubusercontent.com/e2e/accessibility-cloud/raw/subman.json", + ); + const copy = page.getByRole("button", { name: "Copy Raw URL", exact: true }); + await copy.focus(); + await expect(page.getByRole("tooltip")).toHaveText("Copy Raw URL"); +}); + +test("loading a saved rule exposes its existing advanced configuration", async ({ + page, + context, +}) => { + const data = structuredClone(defaultUiData); + data.aggregates.push({ + id: "advanced-rule", + name: "Configured rule", + nodeIds: [data.nodes[0].id], + subscriptionIds: [], + excludeTagIds: [], + renameMap: {}, + renameRules: ["Old = New"], + allowedTypes: ["vless"], + updatedAt: "2026-10-23T10:00:00.000Z", + }); + await seedUiWorkspace(page, context, data); + await page.goto("/aggregate"); + await expect(page.locator(".app-header-link-connected")).toBeVisible(); + await page.getByRole("button", { name: "New Rule", exact: true }).click(); + await page + .getByRole("button", { name: "Configured rule", exact: true }) + .click(); + await expect(page.locator("details.gh-advanced-options")).toHaveAttribute( + "open", + ); + await expect( + page.getByRole("textbox", { name: "Rename Rules", exact: true }), + ).toHaveValue("Old = New"); + await expect( + page.getByRole("button", { name: "VLESS", exact: true }), + ).toHaveAttribute("aria-pressed", "true"); +}); diff --git a/e2e/ui-workspace-fixture.ts b/e2e/ui-workspace-fixture.ts new file mode 100644 index 0000000..2f39364 --- /dev/null +++ b/e2e/ui-workspace-fixture.ts @@ -0,0 +1,155 @@ +import type { BrowserContext, Page } from "@playwright/test"; +import type { AppState } from "../../src/lib/models"; + +export type UiWorkspaceData = Pick< + AppState, + "nodes" | "subscriptions" | "aggregates" | "publishTargets" | "clientExports" +>; + +export const defaultUiData: UiWorkspaceData = { + nodes: [ + { + id: "accessibility-node", + name: "Accessibility Node", + type: "vless", + raw: "vless://00000000-0000-4000-8000-000000000001@example.com:443#A11y", + tags: [], + enabled: true, + updatedAt: "2026-10-23T10:00:00.000Z", + source: "single", + }, + ], + subscriptions: [], + aggregates: [], + publishTargets: [], + clientExports: [], +}; + +export async function seedUiWorkspace( + page: Page, + context: BrowserContext, + data: UiWorkspaceData = structuredClone(defaultUiData), +) { + const now = "2026-10-23T10:00:00.000Z"; + const gistId = "accessibility-cloud"; + + const document = { + version: 2, + schemaVersion: 2, + workspaceId: `gist:${gistId}`, + revision: 0, + updatedAt: now, + lastMutationId: null, + data, + tombstones: { + nodes: [], + subscriptions: [], + aggregates: [], + publishTargets: [], + clientExports: [], + }, + }; + await context.route("https://api.github.com/**", async (route) => { + if ( + route.request().method() !== "GET" || + new URL(route.request().url()).pathname !== `/gists/${gistId}` + ) { + await route.abort("blockedbyclient"); + return; + } + await route.fulfill({ + json: { + id: gistId, + owner: { login: "e2e" }, + description: "SubMan-Data", + updated_at: now, + html_url: `https://gist.github.com/e2e/${gistId}`, + files: { + "subman.json": { + filename: "subman.json", + raw_url: `https://gist.githubusercontent.com/e2e/${gistId}/raw/subman.json`, + size: JSON.stringify(document).length, + content: JSON.stringify(document), + truncated: false, + }, + }, + }, + }); + }); + await context.route("**/__e2e_seed__", (route) => + route.fulfill({ + status: 200, + contentType: "text/html", + body: "SubMan E2E seed", + }), + ); + await page.goto("/__e2e_seed__"); + await page.evaluate( + async ({ gistId, now, data, document }) => { + const database = await new Promise((resolve, reject) => { + const request = indexedDB.open("subman-workspace", 1); + request.onupgradeneeded = () => + request.result.createObjectStore("workspace-state"); + request.onsuccess = () => resolve(request.result); + request.onerror = () => reject(request.error); + }); + await new Promise((resolve, reject) => { + const transaction = database.transaction( + "workspace-state", + "readwrite", + ); + transaction.objectStore("workspace-state").put( + { + version: 1, + snapshot: { + ...data, + gists: [], + activeGistId: gistId, + activeGistFile: "subman.json", + lastUpdated: now, + }, + binding: { + version: 2, + gistId, + workspaceId: `gist:${gistId}`, + fileName: "subman.json", + revision: 0, + syncMode: "automatic", + baseline: document, + conflictBaseline: null, + }, + workspaces: {}, + leases: {}, + quarantines: [], + quarantinePayloads: {}, + nextFencingToken: 1, + migration: { + version: 1, + phase: "confirmed", + startedAt: now, + copiedAt: now, + validatedAt: now, + updatedAt: now, + confirmedAt: now, + cleanupCompletedAt: now, + }, + }, + "root", + ); + transaction.oncomplete = () => resolve(); + transaction.onerror = () => reject(transaction.error); + transaction.onabort = () => reject(transaction.error); + }); + database.close(); + sessionStorage.setItem( + "subman:auth:session:v2", + JSON.stringify({ + version: 2, + token: "fixture-accessibility-token", + lastLoginAt: now, + }), + ); + }, + { gistId, now, data, document }, + ); +} diff --git a/e2e/workspace-v2.spec.ts b/e2e/workspace-v2.spec.ts index b40c786..5acb71e 100644 --- a/e2e/workspace-v2.spec.ts +++ b/e2e/workspace-v2.spec.ts @@ -800,7 +800,7 @@ for (const { mobile, remembered, manual } of [ .fill(GIST_ID); await page.getByTestId("legacy-workspace-check").scrollIntoViewIfNeeded(); await page.screenshot({ - path: `/tmp/subman-manual-entry-${mobile ? "mobile" : "desktop"}.png`, + path: test.info().outputPath("manual-entry.png"), fullPage: false, }); await page @@ -813,7 +813,7 @@ for (const { mobile, remembered, manual } of [ const panel = page.getByTestId("legacy-migration"); await expect(panel).toBeVisible(); await expect(page).toHaveURL(/\/auth$/); - await expect(page).toHaveTitle("SubMan"); + await expect(page).toHaveTitle("Settings - SubMan"); await expect( page.getByRole("heading", { name: "Settings", exact: true }), ).toBeVisible(); @@ -833,7 +833,7 @@ for (const { mobile, remembered, manual } of [ ).toBe(true); await panel.scrollIntoViewIfNeeded(); await page.screenshot({ - path: `/tmp/subman-migration-${manual ? `manual-${manual}-${remembered ? "connected" : "signed-out"}` : remembered ? "existing" : mobile ? "mobile" : "desktop"}.png`, + path: test.info().outputPath("migration.png"), fullPage: false, }); if (remembered) @@ -862,24 +862,27 @@ for (const { mobile, remembered, manual } of [ ) .toBe(1); await expect - .poll(async () => { - if (!(await panel.isVisible())) return true; - return panel + .poll(() => + panel .getByRole("button", { name: "Migrate and load Workspace", exact: true, }) - .isEnabled(); - }) + .evaluateAll((buttons) => + buttons.every((button) => !button.hasAttribute("disabled")), + ), + ) .toBe(true); - if (await panel.isVisible()) { - await panel - .getByRole("button", { - name: "Migrate and load Workspace", - exact: true, - }) - .click(); - } + // The panel can disappear after readiness but before an optional retry. + await panel + .getByRole("button", { + name: "Migrate and load Workspace", + exact: true, + }) + .evaluateAll((buttons) => { + const button = buttons[0] as HTMLButtonElement | undefined; + if (button && !button.disabled) button.click(); + }); await expect(panel).toHaveCount(0); await expect( page.getByText( @@ -981,7 +984,7 @@ for (const mobile of [false, true]) { await seedIndexedDb(page, initial); await seedAuth(page, { session: "fixture-single-workspace-token" }); await page.goto("/auth"); - await expect(page).toHaveTitle("SubMan"); + await expect(page).toHaveTitle("Settings - SubMan"); await expect( page.getByRole("heading", { name: "Settings", exact: true }), ).toBeVisible(); @@ -1057,7 +1060,7 @@ for (const mobile of [false, true]) { ).toBeVisible(); await page.locator("#workspace-repair").scrollIntoViewIfNeeded(); await page.screenshot({ - path: `/tmp/subman-cloud-settings-${mobile ? "mobile" : "desktop"}.png`, + path: test.info().outputPath("cloud-settings.png"), animations: "disabled", }); expect( diff --git a/src/app.css b/src/app.css index b6152f0..0b71be4 100644 --- a/src/app.css +++ b/src/app.css @@ -25,6 +25,8 @@ --color-success-emphasis: var(--success-emphasis); --color-danger-emphasis: var(--danger-emphasis); --color-attention-emphasis: var(--attention-emphasis); + --text-sm: 1rem; + --text-xs: 0.857143rem; --shadow-sm: 0 1px 0 rgba(31, 35, 40, 0.04); --shadow-medium: 0 8px 24px rgba(140, 149, 159, 0.2); @@ -45,6 +47,11 @@ --accent-muted: rgba(9, 105, 218, 0.15); --accent-subtle: #ddf4ff; --success-emphasis: #1f883d; + --success-fg: #1a7f37; + --attention-fg: #9a6700; + --danger-fg: #cf222e; + --button-bg: linear-gradient(180deg, #f6f8fa 0%, #f3f4f6 100%); + --button-hover: #eef1f4; --danger-emphasis: #cf222e; --attention-emphasis: #bf8700; --header-bg: #24292f; @@ -75,6 +82,11 @@ --accent-muted: rgba(56, 139, 253, 0.22); --accent-subtle: rgba(56, 139, 253, 0.15); --success-emphasis: #238636; + --success-fg: #3fb950; + --attention-fg: #d29922; + --danger-fg: #f85149; + --button-bg: #212830; + --button-hover: #262c36; --danger-emphasis: #da3633; --attention-emphasis: #9e6a03; --header-bg: #010409; @@ -143,6 +155,11 @@ pre { text-decoration: underline; } +:where(a, button, summary):focus-visible { + outline: 2px solid var(--accent-fg); + outline-offset: 3px; +} + .gh-box { @apply overflow-hidden rounded-md border border-border-default bg-canvas-default; box-shadow: var(--shadow-sm); @@ -162,26 +179,19 @@ pre { .gh-btn { @apply inline-flex h-8 items-center justify-center gap-2 rounded-md border border-border-default px-3 py-1.5 text-sm font-medium text-fg-default transition-colors disabled:cursor-not-allowed disabled:opacity-60; - background: linear-gradient(180deg, #f6f8fa 0%, #f3f4f6 100%); + min-height: 32px; + background: var(--button-bg); box-shadow: var(--shadow-sm); } .gh-btn:hover { - background: #f3f4f6; + background: var(--button-hover); } .gh-btn:active { background: var(--canvas-inset); } -:root[data-theme="dark"] .gh-btn { - background: #212830; -} - -:root[data-theme="dark"] .gh-btn:hover { - background: #262c36; -} - .gh-btn-primary { border-color: color-mix(in srgb, var(--success-emphasis) 70%, black); background: var(--success-emphasis); @@ -197,7 +207,7 @@ pre { } .gh-btn-danger { - color: var(--danger-emphasis); + color: var(--danger-fg); } .gh-btn-danger:hover { @@ -444,23 +454,23 @@ input[type="checkbox"]:indeterminate { } .gh-list-header { - @apply flex items-center justify-between gap-3 border-b border-border-default bg-canvas-subtle px-4 py-2 text-[11px] font-semibold uppercase tracking-wide text-fg-muted; + @apply flex items-center justify-between gap-3 border-b border-border-default bg-canvas-subtle px-4 py-2 text-xs font-semibold text-fg-muted; } .gh-list-meta { - @apply flex flex-wrap items-center gap-x-3 gap-y-1 text-[11px] text-fg-muted; + @apply flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-fg-muted; } .gh-list-meta-code { - @apply max-w-full truncate rounded bg-canvas-subtle px-1.5 py-0.5 font-mono text-[10px]; + @apply max-w-full truncate rounded bg-canvas-subtle px-1.5 py-0.5 font-mono text-xs; } .gh-counter { - @apply inline-flex min-h-5 min-w-5 items-center justify-center rounded-full border border-border-default bg-canvas-subtle px-2 text-[11px] font-medium leading-none text-fg-muted; + @apply inline-flex min-h-5 min-w-5 items-center justify-center rounded-full border border-border-default bg-canvas-subtle px-2 text-xs font-medium leading-none text-fg-muted; } .gh-label { - @apply inline-flex min-h-5 items-center gap-1 rounded-md border border-border-default bg-canvas-subtle px-1.5 text-[11px] font-medium leading-none text-fg-muted; + @apply inline-flex min-h-5 items-center gap-1 rounded-md border border-border-default bg-canvas-subtle px-1.5 text-xs font-medium leading-none text-fg-muted; } .gh-label-muted { @@ -595,13 +605,14 @@ input[type="checkbox"]:indeterminate { @apply flex min-w-0 flex-col gap-4; } -.app-repo-inner, +.app-repo-meta, +.app-repo-tabs-track, .app-main-container { @apply mx-auto w-full max-w-[92rem] px-4 sm:px-6 lg:px-8; } .app-brand-mark { - @apply h-6 w-6 shrink-0 object-contain; + @apply h-8 w-8 shrink-0 object-contain; } .theme-menu { @@ -631,27 +642,23 @@ input[type="checkbox"]:indeterminate { } .app-header-link-connected { - color: var(--success-emphasis); + color: var(--success-fg); } .app-header-link-pending { - color: var(--attention-emphasis); + color: var(--attention-fg); } .app-header-link-danger { - color: var(--danger-emphasis); + color: var(--danger-fg); } .app-repo-shell { background: var(--canvas-default); } -.app-repo-inner { - @apply flex flex-col; -} - .app-repo-meta { - @apply mx-auto flex w-full items-center justify-between gap-3 px-4 py-3 sm:px-6 lg:px-8; + @apply flex min-h-16 items-center justify-between gap-3 py-3; } .app-repo-main { @@ -659,19 +666,38 @@ input[type="checkbox"]:indeterminate { } .app-repo-masthead { - @apply w-full border-b border-border-default bg-canvas-subtle; + @apply w-full bg-canvas-subtle; } .app-repo-tabs { - @apply w-full overflow-x-auto; + @apply w-full border-y border-border-default bg-canvas-default; } .app-repo-tabs-track { - @apply min-w-max px-4 sm:px-6 lg:px-8; + @apply flex min-w-0 items-center gap-1; +} + +.app-repo-tabs-track nav { + min-width: 0; + flex: 1; + scrollbar-width: none; + overscroll-behavior-x: contain; +} + +.app-repo-tabs-track nav::-webkit-scrollbar { + display: none; +} + +.app-nav-scroll { + @apply inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-md border border-border-default bg-canvas-subtle; +} + +.app-nav-scroll:hover { + background: var(--canvas-inset); } .app-repo-title { - @apply flex min-w-0 items-center gap-2 text-lg font-semibold leading-7; + @apply flex min-w-0 items-center gap-2.5 rounded-md text-lg font-semibold leading-7; color: var(--fg-default); } @@ -683,6 +709,83 @@ input[type="checkbox"]:indeterminate { @apply flex shrink-0 items-center gap-1; } +.app-header-link.app-workspace-control { + width: auto; + gap: 6px; + padding: 0 10px; + border: 1px solid var(--border-default); + background: var(--canvas-default); + font-size: 12px; + font-weight: 500; +} + +.app-workspace-control span { + max-width: 160px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.app-sync-notice { + @apply mb-4 flex flex-wrap items-center justify-between gap-2 rounded-md border border-border-default bg-canvas-default px-4 py-3 text-sm; +} + +.gh-tooltip { + position: fixed; + z-index: 300; + max-width: min(280px, calc(100vw - 16px)); + padding: 7px 10px; + border-radius: 6px; + background: var(--fg-default); + color: var(--canvas-default); + font-size: 12px; + font-weight: 500; + line-height: 1.5; + overflow-wrap: anywhere; + box-shadow: var(--shadow-medium); +} + +.nodes-filter-search .gh-input, +.gh-search-input.gh-input { + padding-left: 36px; +} + +.gh-static-title { + @apply min-w-0 truncate text-sm font-semibold text-fg-default; +} + +.gh-config-group { + @apply flex min-w-0 flex-col gap-4; +} + +.gh-advanced-options { + @apply rounded-md border border-border-default; +} + +.gh-advanced-options > summary { + @apply cursor-pointer rounded-md bg-canvas-subtle px-4 py-3 text-sm font-semibold; +} + +.gh-advanced-options[open] > summary { + border-bottom: 1px solid var(--border-default); + border-radius: 6px 6px 0 0; +} + +@media (max-width: 639px) { + .app-workspace-control span { + max-width: 100px; + } + + .app-header-link.app-workspace-control { + padding: 0 7px; + } + + .gh-row-actions > .gh-btn { + min-width: 40px; + min-height: 40px; + } +} + .app-main-container { @apply flex-1 py-5; } @@ -761,7 +864,7 @@ input[type="checkbox"]:indeterminate { } .badge { - @apply inline-flex min-h-5 items-center justify-center rounded-full border border-border-default bg-canvas-subtle px-2 text-[11px] font-medium leading-none text-fg-muted; + @apply inline-flex min-h-5 items-center justify-center rounded-full border border-border-default bg-canvas-subtle px-2 text-xs font-medium leading-none text-fg-muted; } .badge-success { @@ -775,7 +878,7 @@ input[type="checkbox"]:indeterminate { var(--success-emphasis) 8%, var(--canvas-default) ); - color: color-mix(in srgb, var(--success-emphasis) 86%, black); + color: var(--success-fg); } .badge-danger { @@ -789,7 +892,7 @@ input[type="checkbox"]:indeterminate { var(--danger-emphasis) 8%, var(--canvas-default) ); - color: color-mix(in srgb, var(--danger-emphasis) 86%, black); + color: var(--danger-fg); } .State { diff --git a/src/lib/actions/tooltip.ts b/src/lib/actions/tooltip.ts new file mode 100644 index 0000000..af7ade5 --- /dev/null +++ b/src/lib/actions/tooltip.ts @@ -0,0 +1,132 @@ +let nextTooltipId = 0; + +/** Add a short label to an interactive element without a native-title duplicate. */ +export function tooltip(node: HTMLElement, initialLabel: string) { + let label = initialLabel; + let bubble: HTMLDivElement | null = null; + let timer: ReturnType | undefined; + let hovered = false; + let focused = false; + let dismissed = false; + const id = `subman-tooltip-${++nextTooltipId}`; + const nativeTitle = node.getAttribute("title"); + node.removeAttribute("title"); + + function position() { + if (!bubble) return; + const anchor = node.getBoundingClientRect(); + const bounds = bubble.getBoundingClientRect(); + const left = Math.max( + 8, + Math.min( + anchor.left + anchor.width / 2 - bounds.width / 2, + window.innerWidth - bounds.width - 8, + ), + ); + const below = anchor.bottom + 8; + const top = + below + bounds.height <= window.innerHeight - 8 + ? below + : Math.max(8, anchor.top - bounds.height - 8); + bubble.style.left = `${left}px`; + bubble.style.top = `${top}px`; + } + + function hide() { + clearTimeout(timer); + if (!bubble) return; + document.removeEventListener("keydown", keydown); + window.removeEventListener("resize", position); + document.removeEventListener("scroll", hide, true); + bubble.remove(); + bubble = null; + const descriptions = (node.getAttribute("aria-describedby") ?? "") + .split(/\s+/) + .filter((value) => value && value !== id); + if (descriptions.length) + node.setAttribute("aria-describedby", descriptions.join(" ")); + else node.removeAttribute("aria-describedby"); + } + + function show() { + clearTimeout(timer); + if (!label || dismissed || bubble || (!hovered && !focused)) return; + bubble = document.createElement("div"); + bubble.id = id; + bubble.className = "gh-tooltip"; + bubble.setAttribute("role", "tooltip"); + bubble.textContent = label; + bubble.addEventListener("pointerenter", () => clearTimeout(timer)); + bubble.addEventListener("pointerleave", scheduleHide); + document.body.appendChild(bubble); + document.addEventListener("keydown", keydown); + window.addEventListener("resize", position); + document.addEventListener("scroll", hide, true); + node.setAttribute( + "aria-describedby", + [node.getAttribute("aria-describedby"), id].filter(Boolean).join(" "), + ); + position(); + } + + function scheduleHide() { + clearTimeout(timer); + if (!focused && !hovered) timer = setTimeout(hide, 120); + } + + function enter(event: PointerEvent) { + if (event.pointerType === "touch") return; + hovered = true; + dismissed = false; + clearTimeout(timer); + timer = setTimeout(show, 350); + } + function leave() { + hovered = false; + dismissed = false; + scheduleHide(); + } + function focus() { + focused = true; + dismissed = false; + show(); + } + function blur() { + focused = false; + dismissed = false; + scheduleHide(); + } + function dismiss() { + dismissed = true; + hide(); + } + function keydown(event: KeyboardEvent) { + if (event.key === "Escape") dismiss(); + } + node.addEventListener("pointerenter", enter); + node.addEventListener("pointerleave", leave); + node.addEventListener("focus", focus); + node.addEventListener("blur", blur); + node.addEventListener("click", dismiss); + + return { + update(nextLabel: string) { + label = nextLabel; + node.removeAttribute("title"); + if (!label) hide(); + if (bubble) { + bubble.textContent = label; + position(); + } + }, + destroy() { + hide(); + node.removeEventListener("pointerenter", enter); + node.removeEventListener("pointerleave", leave); + node.removeEventListener("focus", focus); + node.removeEventListener("blur", blur); + node.removeEventListener("click", dismiss); + if (nativeTitle !== null) node.setAttribute("title", nativeTitle); + }, + }; +} diff --git a/src/lib/i18n.ts b/src/lib/i18n.ts index 22b6b1b..ada05de 100644 --- a/src/lib/i18n.ts +++ b/src/lib/i18n.ts @@ -7,6 +7,182 @@ const STORAGE_KEY = "subman:locale:v1"; const DEFAULT_LOCALE: Locale = "en"; const zhCN: Record = { + Settings: "设置", + Title: "名称", + Actions: "操作", + Kind: "类型", + Size: "大小", + Theme: "主题", + Auto: "跟随系统", + Publish: "发布", + Download: "下载", + Edit: "编辑", + Close: "关闭", + Protocol: "协议", + "Single URI": "单个节点", + results: "项结果", + enabled: "项已启用", + Primary: "主导航", + "Open project on GitHub": "在 GitHub 查看项目", + "Setup GitHub": "连接 GitHub", + "Close menu": "关闭菜单", + "Close dialog": "关闭对话框", + "Dismiss notification": "关闭通知", + "Manage Sources": "管理来源", + "Collect sources": "添加来源", + "Compose rules": "配置规则", + "Publish output": "发布输出", + "Next actions": "开始使用", + "Add single URIs or upstream subscription URLs.": + "添加单个节点 URI 或上游订阅地址。", + "Filter, rename, and preview the output set.": "筛选、重命名并预览输出内容。", + "Write files to the workspace gist and copy raw URLs.": + "将文件发布到工作区 Gist,并复制原始链接。", + "New Resource": "新建资源", + "Filter resources": "筛选资源", + "Filter resources...": "搜索资源名称、地址或标签…", + "Filter status": "筛选状态", + "No nodes yet": "还没有节点", + "No subscriptions yet": "还没有订阅", + "Add node": "添加节点", + "Add subscription": "添加订阅", + "Add one URI or import a batch.": "添加一个节点 URI,也可以批量导入。", + "Add a feed URL to fetch nodes.": "添加订阅地址以获取节点。", + "Batch content": "批量导入内容", + "Common tags": "公共标签", + "Common tags for this batch...": "为本批资源添加标签…", + "One per line...": "每行填写一个地址…", + "Friendly name": "便于辨认的名称", + "Save Resource": "保存资源", + "Edit Node": "编辑节点", + "Edit Subscription": "编辑订阅", + "Edit node": "编辑节点", + "Edit subscription": "编辑订阅", + "Copy URI": "复制节点 URI", + "Copy node URI": "复制节点 URI", + "Copy URL": "复制地址", + "Delete node": "删除节点", + "Delete subscription": "删除订阅", + "Preview nodes": "预览节点", + "Close add resource panel": "关闭新增资源面板", + "Close edit modal": "关闭编辑窗口", + "Close subscription preview": "关闭订阅预览", + "Fetching subscription content...": "正在获取订阅内容…", + "Nodes Found": "获取到的节点", + "Confirm Deletion": "确认删除", + "Delete {name} forever?": "确定永久删除“{name}”吗?", + "Copied to clipboard": "已复制到剪贴板", + "Source: {source}": "来源:{source}", + "Updated {time}": "更新于 {time}", + "{count} tags": "{count} 个标签", + "URI warning: {issues}": "URI 提示:{issues}", + "Rule Definition": "规则配置", + "Rule Name": "规则名称", + "Exclude Tags": "排除标签", + "Source Nodes": "来源节点", + "Source Subscriptions": "来源订阅", + "Select nodes...": "选择节点…", + "Select subscriptions...": "选择订阅…", + "Allowed Protocols": "允许的协议", + "Leave empty to allow all protocols.": "不选择时允许所有协议。", + "Sort Mode": "排序方式", + "None (Original Order)": "不排序(保留原顺序)", + "Alphabetical (A-Z)": "按名称排序(A–Z)", + "By Protocol": "按协议排序", + "By Region": "按地区排序", + "Priority Keywords (per line)": "优先关键词(每行一个)", + "Rename Rules": "重命名规则", + "Region Flag Map": "地区旗帜映射", + "Browse Icons": "浏览旗帜", + "Auto-prepend Region Flags": "自动添加地区旗帜", + "Uses emoji flags based on country codes": "根据地区代码添加旗帜表情", + "Supports Regex: /pattern/flags = replacement (e.g. /^HK-(.*)/ = Hong Kong $1)": + "支持正则:/表达式/标志 = 替换内容(例如 /^HK-(.*)/ = 香港 $1)", + "New Rule": "新建规则", + "New target": "新建目标", + "Select Target": "选择目标", + "Binding Rule": "关联规则", + "Output File": "输出文件", + "Live Link": "已发布链接", + "Link copied to clipboard": "链接已复制到剪贴板", + "Preview Results": "预览结果", + "Preview failed": "预览失败", + "Select nodes or subs.": "请先选择节点或订阅。", + "No nodes matched criteria": "没有符合条件的节点", + "Connect to Publish": "连接后发布", + "Connect GitHub to sync and publish from a gist.": + "连接 GitHub 后即可同步和发布。", + "Go to Settings": "前往设置", + "Publish failed: {error}": "发布失败:{error}", + "Filter nodes": "筛选节点", + "Filter nodes...": "搜索节点…", + "Filter subscriptions": "筛选订阅", + "Filter subs...": "搜索订阅…", + "No nodes found": "没有匹配的节点", + "No subs found": "没有匹配的订阅", + "{count} nodes selected": "已选择 {count} 个节点", + "{count} subs selected": "已选择 {count} 个订阅", + "Built-in Region Flag Rules": "内置地区旗帜规则", + "Search code or keyword...": "搜索地区代码或关键词…", + "Close region flag rules": "关闭地区旗帜规则", + "Close preview results": "关闭预览结果", + "Close rule menu": "关闭规则菜单", + "Close source nodes menu": "关闭来源节点菜单", + "Close source subscriptions menu": "关闭来源订阅菜单", + "Copy preview line": "复制此条预览", + "Listen port must be between 1 and 65535": "监听端口必须介于 1 和 65535 之间", + "Repository Files": "工作区文件", + "View on GitHub": "在 GitHub 查看", + "Copy Raw URL": "复制原始链接", + "Open Raw": "打开原始文件", + "No raw URL": "没有原始链接", + "Delete File": "删除文件", + "Delete failed": "删除失败", + "SubMan home": "SubMan 首页", + "Awaiting cloud": "等待云端确认", + "Review connection": "处理连接问题", + "View sync status": "查看同步状态", + "More navigation items": "显示后面的导航项", + "Previous navigation items": "显示前面的导航项", + "No matching resources": "没有匹配的资源", + "Try another search or clear the filters.": + "请尝试其他关键词,或清除筛选条件。", + "Clear filters": "清除筛选", + "Recently updated": "最近更新", + "Add sources to start composing rules.": "添加来源后即可开始配置聚合规则。", + "Publication targets": "发布与导出", + "View files": "查看文件", + "Last published": "最近发布于", + "Not published": "尚未发布", + "Create a publish target or client export to keep a stable output file.": + "创建发布目标或客户端导出,生成具有稳定链接的输出文件。", + "Create client export": "创建客户端导出", + "Continue your workflow": "继续处理", + "Your sources are ready. Compose a rule to filter and organize them.": + "来源已就绪,可以通过聚合规则筛选和整理。", + "Preview your rules, then publish the output when it is ready.": + "预览规则效果,确认后发布输出文件。", + "Sources and filtering": "来源与筛选", + "Advanced rule options": "高级规则选项", + "Protocol, sorting, names and region flags": "协议、排序、重命名与地区旗帜", + "Sorting and names": "排序与命名", + "A target connects a saved rule to an output filename. Saving a target does not publish the file.": + "发布目标将已保存的规则关联到输出文件名。保存目标后,还需发布才能生成文件。", + "Resolve the output filename conflict before publishing.": + "请先处理输出文件名冲突,再发布。", + "Save a publish target before publishing.": "请先保存发布目标,再发布文件。", + "Save changes before publishing, or use Save and Publish.": + "请先保存修改再发布,也可以使用“保存并发布”。", + "Publish generates the output file from the saved rule.": + "发布会根据已保存的规则生成输出文件。", + "Select or create an export profile first.": "请先选择或创建导出配置。", + "Save the profile changes before generating a preview.": + "请先保存配置修改,再生成预览。", + "Generate a current preview before publishing.": "请先生成最新预览,再发布。", + "Resolve the preview errors before publishing.": + "请先处理预览中的错误,再发布。", + "Publish writes the previewed configuration to the cloud.": + "发布会将预览中的配置写入云端。", "Retained changes require Reload from Cloud before editing.": "请先通过“重新加载云端数据”处理历史改动,再继续编辑。", "Manage one cloud Workspace. Every change is saved to GitHub.": diff --git a/src/routes/+layout.svelte b/src/routes/+layout.svelte index acdd37a..7c32eea 100644 --- a/src/routes/+layout.svelte +++ b/src/routes/+layout.svelte @@ -3,11 +3,14 @@ import "../app.css"; import { onMount, tick } from "svelte"; import { get } from "svelte/store"; import { fade, fly, slide } from "svelte/transition"; +import { afterNavigate } from "$app/navigation"; import { page } from "$app/state"; +import { tooltip } from "$lib/actions/tooltip"; import Octicon from "$lib/components/Octicon.svelte"; import { t } from "$lib/i18n"; import { alert, + arrowRight, browser, check, code, @@ -61,8 +64,11 @@ const themeOptions: { { value: "dark", label: "Dark", icon: moon }, ]; +let shellMounted = false; $: activeThemeOption = - themeOptions.find((option) => option.value === $themeMode) ?? themeOptions[0]; + themeOptions.find( + (option) => option.value === (shellMounted ? $themeMode : "system"), + ) ?? themeOptions[0]; $: activeThemeLabel = $t(activeThemeOption.label); $: isWorkspaceConnected = Boolean( $authState.token && @@ -100,7 +106,89 @@ $: syncStatusLabel = } as const )[$workspaceSyncStatus.lifecycle]; $: workspaceControlLabel = `${$t(workspaceNeedsAttention ? "Repair" : isWorkspaceConnected ? "Manage Workspace" : "Setup GitHub")}: ${$t(syncStatusLabel)}${$workspaceSyncStatus.queueCount > 0 ? `, ${$t("{count} queued", { count: $workspaceSyncStatus.queueCount })}` : ""}`; +$: workspaceShortLabel = workspaceNeedsAttention + ? "Needs attention" + : workspaceBusy + ? "Syncing" + : workspacePending + ? "Awaiting cloud" + : isWorkspaceConnected + ? "Connected" + : "Not connected"; let themeMenuOpen = false; +let themeButton: HTMLButtonElement; +let themeMenu: HTMLDivElement; +let navigation: HTMLElement; +let navigationOverflows = false; +let navigationAtEnd = false; + +function updateNavigationOverflow() { + if (!navigation) return; + navigationOverflows = navigation.scrollWidth > navigation.clientWidth + 1; + navigationAtEnd = + navigation.scrollLeft + navigation.clientWidth >= + navigation.scrollWidth - 2; +} + +function revealActiveNavigation() { + const active = navigation?.querySelector( + '[aria-current="page"]', + ); + if (active) { + const offset = + active.getBoundingClientRect().left - + navigation.getBoundingClientRect().left; + if (offset < 0) navigation.scrollLeft += offset; + else if (offset + active.offsetWidth > navigation.clientWidth) + navigation.scrollLeft += + offset + active.offsetWidth - navigation.clientWidth; + } + updateNavigationOverflow(); +} + +afterNavigate(() => { + void tick().then(revealActiveNavigation); +}); + +async function toggleThemeMenu() { + themeMenuOpen = !themeMenuOpen; + if (themeMenuOpen) { + await tick(); + themeMenu + ?.querySelector('[aria-checked="true"]') + ?.focus(); + } +} + +function closeThemeMenu() { + themeMenuOpen = false; + themeButton?.focus(); +} + +function handleThemeKeydown(event: KeyboardEvent) { + if (!themeMenuOpen) return; + if (event.key === "Escape") { + event.preventDefault(); + closeThemeMenu(); + } else if (event.key === "Tab") { + themeMenuOpen = false; + themeButton?.focus(); + } else if (["ArrowDown", "ArrowUp", "Home", "End"].includes(event.key)) { + event.preventDefault(); + const items = Array.from( + themeMenu.querySelectorAll('[role="menuitemradio"]'), + ); + const current = items.indexOf(document.activeElement as HTMLButtonElement); + const next = + event.key === "Home" + ? 0 + : event.key === "End" + ? items.length - 1 + : (current + (event.key === "ArrowDown" ? 1 : -1) + items.length) % + items.length; + items[next]?.focus(); + } +} let confirmDialogElement: HTMLDivElement | null = null; let confirmButton: HTMLButtonElement | null = null; let confirmWasOpen = false; @@ -127,7 +215,7 @@ function isActive(pathname: string, href: string) { function handleThemeChange(nextTheme: ThemeMode) { themeMode.set(nextTheme); - themeMenuOpen = false; + closeThemeMenu(); } function handleConfirmKeydown(event: KeyboardEvent) { @@ -155,6 +243,9 @@ function handleConfirmKeydown(event: KeyboardEvent) { } onMount(() => { + shellMounted = true; + const navigationObserver = new ResizeObserver(revealActiveNavigation); + navigationObserver.observe(navigation); let cancelled = false; let stopAutoSync = () => {}; let stopAuth = () => {}; @@ -186,6 +277,7 @@ onMount(() => { }); return () => { + navigationObserver.disconnect(); cancelled = true; stopAuth(); stopAutoSync(); @@ -204,41 +296,45 @@ onMount(() => { + +
+ {$t(workspaceShortLabel)} {workspaceControlLabel}
- {#if themeMenuOpen} - -
+ + +
-
-
+ {#if $workspaceCloudStatus.phase === "ready" && (workspaceNeedsAttention || workspacePending)} +
+ {$t(syncStatusLabel)}{#if $workspaceSyncStatus.queueCount > 0} · {$t("{count} queued", { count: $workspaceSyncStatus.queueCount })}{/if} + {$t(workspaceNeedsAttention ? "Review connection" : "View sync status")} +
+ {/if} {#if page.url.pathname === "/auth" || ($authState.token && $workspaceCloudStatus.phase === "ready")} {:else} diff --git a/src/routes/+page.svelte b/src/routes/+page.svelte index 039d155..9b23e97 100644 --- a/src/routes/+page.svelte +++ b/src/routes/+page.svelte @@ -1,8 +1,107 @@ + + {$t("Aggregate")} - SubMan + +
@@ -1011,6 +1033,7 @@ function handleExcludeTagsInput() {
+

{$t("Sources and filtering")}

@@ -1137,6 +1160,9 @@ function handleExcludeTagsInput() {
+
+ {$t("Advanced rule options")}{$t("Protocol, sorting, names and region flags")} +
{$t("Allowed Protocols")}
@@ -1146,6 +1172,7 @@ function handleExcludeTagsInput() { type="button" class={cn("gh-btn gh-btn-sm", allowedTypes.includes(opt.id) ? "gh-btn-primary" : "bg-canvas-default")} on:click={() => (allowedTypes = toggleSelection(allowedTypes, opt.id))} + aria-pressed={allowedTypes.includes(opt.id)} > {opt.label} @@ -1155,6 +1182,7 @@ function handleExcludeTagsInput() {
+

{$t("Sorting and names")}

@@ -1191,11 +1219,13 @@ function handleExcludeTagsInput() {
+
+