Преглед изворни кода

✨ (dashboard-v6): 主导航「工具」子项改为弹窗,字典、语法手册挂到根路由

工具下的字典、语法手册、用户字典、标签、网盘点开都是弹窗(ToolModal),
右上角「在新标签页打开」开对应页面;弹窗关闭后不销毁,再开时状态还在。

- 字典、语法手册的独立页面从 /workspace/dictionary、/workspace/grammar-book
  移到根下的 /dictionary、/grammar-book(不在 workspace 布局里),旧地址不再保留
- 用户字典、标签、网盘仍是原 /workspace/* 路由
- 语法手册的检索词与选中术语进地址栏(?q=&id=&word=),弹窗带进新标签页、
  页面可刷新重入;检索结果改为由检索词与术语表派生,术语表异步到达后也能出结果
- 标签弹窗里点标签在新标签页打开详情
- dashboard-test:新增 tools-modal.spec.ts,grammar-pop 改用新路径

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
visuddhinanda пре 11 часа
родитељ
комит
b028681448

+ 1 - 1
dashboard-test/src/tests/grammar-pop.spec.ts

@@ -15,7 +15,7 @@ test('词典词卡的语法点:悬停显示 v3 的语法说明,不再请求
   });
   });
 
 
   // 词典释义正文里嵌的 grammar-pop 模板(如【阳】→ m)渲染成 GrammarPop
   // 词典释义正文里嵌的 grammar-pop 模板(如【阳】→ m)渲染成 GrammarPop
-  await page.goto('workspace/dictionary/buddha', { waitUntil: 'networkidle' });
+  await page.goto('dictionary/buddha', { waitUntil: 'networkidle' });
   const grammarLinks = page.locator('a.ant-typography').filter({ hasText: /^【.+】$/ });
   const grammarLinks = page.locator('a.ant-typography').filter({ hasText: /^【.+】$/ });
   await expect(grammarLinks.first()).toBeVisible({ timeout: 15_000 });
   await expect(grammarLinks.first()).toBeVisible({ timeout: 15_000 });
   const count = await grammarLinks.count();
   const count = await grammarLinks.count();

+ 89 - 0
dashboard-test/src/tests/tools-modal.spec.ts

@@ -0,0 +1,89 @@
+import { test, expect, type Page } from '@playwright/test';
+import { collect } from '../lib/collect.js';
+
+/**
+ * 主导航「工具」:每个子项都打开弹窗,右上角「在新标签页打开」开对应页面。
+ * 字典、语法手册的独立页面挂在根下(/dictionary、/grammar-book),其余仍是 /workspace/*。
+ */
+const openTool = async (page: Page, name: string) => {
+  const tools = page.getByRole('menuitem', { name: '工具' });
+  if ((await page.getByRole('menuitem', { name, exact: true }).count()) === 0) await tools.click();
+  await page.getByRole('menuitem', { name, exact: true }).click();
+  const dialog = page.getByRole('dialog').filter({ hasText: name });
+  await expect(dialog).toBeVisible();
+  return dialog;
+};
+
+const openInNewTab = async (page: Page, dialog: ReturnType<Page['getByRole']>) => {
+  const popup = page.waitForEvent('popup');
+  await dialog.getByRole('button', { name: '在新标签页打开' }).click();
+  const tab = await popup;
+  await tab.waitForLoadState('domcontentloaded');
+  return tab;
+};
+
+test('字典弹窗:查词后在新标签页打开 /dictionary/:word', async ({ page }) => {
+  const log = collect(page);
+  await page.goto('workspace', { waitUntil: 'networkidle' });
+  const before = page.url();
+
+  const dialog = await openTool(page, '字典');
+  // 主页面不跳转
+  expect(page.url()).toBe(before);
+  const input = dialog.getByRole('combobox', { name: 'search here' });
+  await input.fill('buddha');
+  // 候选词还在加载时回车不查(字典页同样如此),等候选出来
+  await page.waitForTimeout(1500);
+  await input.press('Enter');
+
+  const tab = await openInNewTab(page, dialog);
+  expect(new URL(tab.url()).pathname).toBe('/pcd-v2026/dictionary/buddha');
+  await tab.close();
+  log.dump('字典弹窗');
+});
+
+test('语法手册弹窗:检索与选中的术语带进新标签页 /grammar-book', async ({ page }) => {
+  await page.goto('workspace', { waitUntil: 'networkidle' });
+  const dialog = await openTool(page, '语法手册');
+
+  // 只检索:新标签页恢复检索词与结果列表
+  await dialog.getByPlaceholder('input search text').fill('a');
+  const first = dialog.locator('.ant-list-item').first();
+  await expect(first).toBeVisible();
+  const title = (await first.locator('.ant-list-item-meta-title').innerText()).trim();
+  let tab = await openInNewTab(page, dialog);
+  expect(new URL(tab.url()).pathname).toBe('/pcd-v2026/grammar-book');
+  expect(new URL(tab.url()).searchParams.get('q')).toBe('a');
+  await expect(tab.getByPlaceholder('input search text')).toHaveValue('a');
+  await expect(tab.locator('.ant-list-item-meta-title').first()).toHaveText(title);
+  await tab.close();
+
+  // 选中一条:新标签页打开的是这条术语
+  await first.click();
+  // 术语详情的标题是指向 /term/show/{id} 的链接
+  const termLink = dialog.locator('a[href*="/term/show/"]').first();
+  await expect(termLink).toBeVisible();
+  const termTitle = (await termLink.innerText()).trim();
+  tab = await openInNewTab(page, dialog);
+  const id = new URL(tab.url()).searchParams.get('id');
+  expect(id).toBeTruthy();
+  await expect(tab.locator(`a[href*="/term/show/${id}"]`).first()).toHaveText(termTitle);
+  console.log(`>>> 语法手册:q=a,选中 ${title} → ${termTitle}(${id})`);
+  await tab.close();
+});
+
+for (const [name, path] of [
+  ['用户字典', '/pcd-v2026/workspace/dict'],
+  ['标签', '/pcd-v2026/workspace/tag'],
+  ['网盘', '/pcd-v2026/workspace/driver'],
+] as const) {
+  test(`${name}弹窗 → ${path}`, async ({ page }) => {
+    await page.goto('workspace', { waitUntil: 'networkidle' });
+    const before = page.url();
+    const dialog = await openTool(page, name);
+    expect(page.url()).toBe(before);
+    const tab = await openInNewTab(page, dialog);
+    expect(new URL(tab.url()).pathname).toBe(path);
+    await tab.close();
+  });
+}

+ 2 - 1
dashboard-v6/src/Router.tsx

@@ -48,6 +48,8 @@ const router = createBrowserRouter(
       Component: RootLayout,
       Component: RootLayout,
       children: [
       children: [
         { index: true, Component: Home },
         { index: true, Component: Home },
+        // 字典、语法手册:/dictionary、/grammar-book
+        ...dictionaryRoutes,
         {
         {
           path: "anonymous",
           path: "anonymous",
           Component: AnonymousLayout,
           Component: AnonymousLayout,
@@ -116,7 +118,6 @@ const router = createBrowserRouter(
             ...tagRoutes,
             ...tagRoutes,
             ...driverRoutes,
             ...driverRoutes,
             ...dictRoutes,
             ...dictRoutes,
-            ...dictionaryRoutes,
             ...courseRoutes,
             ...courseRoutes,
             ...nissayaRoutes,
             ...nissayaRoutes,
             ...discussionRoutes,
             ...discussionRoutes,

+ 13 - 7
dashboard-v6/src/components/navigation/MainMenu.tsx

@@ -22,6 +22,8 @@ import {
 import React, { useState } from "react";
 import React, { useState } from "react";
 import RecentModal from "../recent/RecentModal.tsx";
 import RecentModal from "../recent/RecentModal.tsx";
 import SettingModal from "../setting/SettingModal.tsx";
 import SettingModal from "../setting/SettingModal.tsx";
+import ToolsModals from "./ToolsModals";
+import { isToolKey, type ToolKey } from "./tools";
 import { useIntl } from "react-intl";
 import { useIntl } from "react-intl";
 import { fullUrl } from "../../utils";
 import { fullUrl } from "../../utils";
 import { useActiveStudio } from "../../hooks/useActiveStudio";
 import { useActiveStudio } from "../../hooks/useActiveStudio";
@@ -186,6 +188,7 @@ const Widget = ({ onSearch }: Props) => {
 
 
   const [recentOpen, setRecentOpen] = useState(false);
   const [recentOpen, setRecentOpen] = useState(false);
   const [openSetting, setOpenSetting] = useState(false);
   const [openSetting, setOpenSetting] = useState(false);
+  const [tool, setTool] = useState<ToolKey>();
 
 
   /* ================= 菜单配置 ================= */
   /* ================= 菜单配置 ================= */
 
 
@@ -341,37 +344,36 @@ const Widget = ({ onSearch }: Props) => {
       key: "/workspace/tools",
       key: "/workspace/tools",
       icon: <ToolOutlined />,
       icon: <ToolOutlined />,
       label: intl.formatMessage({ id: "labels.tools" }),
       label: intl.formatMessage({ id: "labels.tools" }),
+      // 子项都打开弹窗(ToolsModals),弹窗里可「在新标签页打开」对应页面
       children: [
       children: [
         {
         {
-          key: "/workspace/dictionary",
+          key: "tool:dictionary",
           label: intl.formatMessage({
           label: intl.formatMessage({
             id: "columns.library.dict.title",
             id: "columns.library.dict.title",
           }),
           }),
-          activeId: "workspace.dictionary",
         },
         },
         {
         {
-          key: "/workspace/grammar-book",
+          key: "tool:grammar-book",
           label: intl.formatMessage({
           label: intl.formatMessage({
             id: "columns.library.palihandbook.title",
             id: "columns.library.palihandbook.title",
           }),
           }),
-          activeId: "workspace.grammar-book",
         },
         },
         {
         {
-          key: "/workspace/dict",
+          key: "tool:dict",
           label: intl.formatMessage({
           label: intl.formatMessage({
             id: "columns.studio.userdict.title",
             id: "columns.studio.userdict.title",
           }),
           }),
           activeId: "workspace.dict",
           activeId: "workspace.dict",
         },
         },
         {
         {
-          key: "/workspace/tag",
+          key: "tool:tag",
           label: intl.formatMessage({
           label: intl.formatMessage({
             id: "columns.studio.tag.title",
             id: "columns.studio.tag.title",
           }),
           }),
           activeId: "workspace.tag",
           activeId: "workspace.tag",
         },
         },
         {
         {
-          key: "/workspace/driver",
+          key: "tool:driver",
           label: intl.formatMessage({
           label: intl.formatMessage({
             id: "columns.studio.attachment.title",
             id: "columns.studio.attachment.title",
           }),
           }),
@@ -434,6 +436,9 @@ const Widget = ({ onSearch }: Props) => {
     } else if (key === "/workspace/setting") {
     } else if (key === "/workspace/setting") {
       setOpenSetting(true);
       setOpenSetting(true);
       return;
       return;
+    } else if (isToolKey(key)) {
+      setTool(key);
+      return;
     }
     }
     navigate(key);
     navigate(key);
   };
   };
@@ -458,6 +463,7 @@ const Widget = ({ onSearch }: Props) => {
         }}
         }}
       />
       />
       <SettingModal open={openSetting} onClose={() => setOpenSetting(false)} />
       <SettingModal open={openSetting} onClose={() => setOpenSetting(false)} />
+      <ToolsModals tool={tool} onClose={() => setTool(undefined)} />
     </>
     </>
   );
   );
 };
 };

+ 80 - 0
dashboard-v6/src/components/navigation/ToolModal.tsx

@@ -0,0 +1,80 @@
+import { Button, Modal, Space, Tooltip, Typography } from "antd";
+import { CloseOutlined, ExportOutlined } from "@ant-design/icons";
+import type { ReactNode } from "react";
+import { useIntl } from "react-intl";
+import { fullUrl } from "../../utils";
+
+interface IWidget {
+  open: boolean;
+  title: ReactNode;
+  /** 「在新标签页打开」的目标路径(站内路径,如 /dictionary/dhamma) */
+  url: string;
+  onClose: () => void;
+  children?: ReactNode;
+}
+
+/**
+ * 主导航「工具」各子项打开的弹窗:标题 + 右上角「在新标签页打开」「关闭」。
+ *
+ * 关闭后不销毁,再打开时状态还在(与搜索弹窗一致)。
+ * 弹窗里的链接一律新标签页打开,由各内容自己处理。
+ */
+const ToolModal = ({ open, title, url, onClose, children }: IWidget) => {
+  const intl = useIntl();
+
+  return (
+    <Modal
+      open={open}
+      onCancel={onClose}
+      footer={null}
+      closable={false}
+      width="min(1160px, calc(100vw - 32px))"
+      style={{ top: "5vh", paddingBottom: 0 }}
+      title={
+        <div
+          style={{
+            display: "flex",
+            alignItems: "center",
+            justifyContent: "space-between",
+            gap: 8,
+          }}
+        >
+          <Typography.Text strong ellipsis>
+            {title}
+          </Typography.Text>
+          <Space size={4}>
+            <Tooltip title={intl.formatMessage({ id: "search.open_full_page" })}>
+              <Button
+                type="text"
+                icon={<ExportOutlined />}
+                aria-label={intl.formatMessage({
+                  id: "search.open_full_page",
+                })}
+                onClick={() => window.open(fullUrl(url), "_blank")}
+              />
+            </Tooltip>
+            <Button
+              type="text"
+              icon={<CloseOutlined />}
+              onClick={onClose}
+              aria-label="close"
+            />
+          </Space>
+        </div>
+      }
+      styles={{
+        container: {
+          height: "90vh",
+          display: "flex",
+          flexDirection: "column",
+          overflow: "hidden",
+        },
+        body: { flex: 1, minHeight: 0, overflowY: "auto" },
+      }}
+    >
+      {children}
+    </Modal>
+  );
+};
+
+export default ToolModal;

+ 100 - 0
dashboard-v6/src/components/navigation/ToolsModals.tsx

@@ -0,0 +1,100 @@
+import { useState } from "react";
+import { useIntl } from "react-intl";
+
+import ToolModal from "./ToolModal";
+import Dictionary from "../dict/Dictionary";
+import GrammarBook from "../term/GrammarBook";
+import UserDictList from "../dict/UserDictList";
+import TagList from "../tag/TagList";
+import AttachmentList from "../attachment/AttachmentList";
+import { useAppSelector } from "../../hooks";
+import { lookupWord } from "../../reducers/command";
+import { currentUser } from "../../reducers/current-user";
+import { useActiveStudio } from "../../hooks/useActiveStudio";
+import { fullUrl } from "../../utils";
+import type { ToolKey } from "./tools";
+import {
+  grammarBookSearch,
+  type IGrammarBookState,
+} from "../term/grammarBookState";
+
+interface IWidget {
+  /** 当前打开的工具;undefined = 都关着 */
+  tool?: ToolKey;
+  onClose: () => void;
+}
+
+/**
+ * 「工具」的弹窗们。每个弹窗首次打开才渲染,关闭后不销毁。
+ * 「在新标签页打开」:字典、语法手册去根下的 /dictionary、/grammar-book,其余去原来的 /workspace/* 页面。
+ */
+const ToolsModals = ({ tool, onClose }: IWidget) => {
+  const intl = useIntl();
+  const user = useAppSelector(currentUser);
+  const { studioName } = useActiveStudio();
+  const [word, setWord] = useState<string>();
+  // 语法手册的检索词与选中术语,带进「在新标签页打开」的地址
+  const [grammarState, setGrammarState] = useState<IGrammarBookState>({});
+
+  // 字典结果里的巴利词点击查词走 redux 的 lookup,弹窗开着时跟上它(与 /dictionary 页面一致)
+  const dictOpen = tool === "tool:dictionary";
+  const lookup = useAppSelector(lookupWord);
+  // 渲染期派生(记上一次的值),不放 effect 里 setState
+  const [prevLookup, setPrevLookup] = useState(lookup);
+  if (lookup !== prevLookup) {
+    setPrevLookup(lookup);
+    if (dictOpen && typeof lookup === "string") setWord(lookup);
+  }
+
+  return (
+    <>
+      <ToolModal
+        open={dictOpen}
+        onClose={onClose}
+        title={intl.formatMessage({ id: "columns.library.dict.title" })}
+        url={word ? `/dictionary/${encodeURIComponent(word)}` : "/dictionary"}
+      >
+        <Dictionary word={word} onSearch={setWord} />
+      </ToolModal>
+      <ToolModal
+        open={tool === "tool:grammar-book"}
+        onClose={onClose}
+        title={intl.formatMessage({ id: "columns.library.palihandbook.title" })}
+        url={`/grammar-book${grammarBookSearch(grammarState)}`}
+      >
+        <GrammarBook onStateChange={setGrammarState} />
+      </ToolModal>
+      <ToolModal
+        open={tool === "tool:dict"}
+        onClose={onClose}
+        title={intl.formatMessage({ id: "columns.studio.userdict.title" })}
+        url="/workspace/dict"
+      >
+        <UserDictList studioName={user?.realName} />
+      </ToolModal>
+      <ToolModal
+        open={tool === "tool:tag"}
+        onClose={onClose}
+        title={intl.formatMessage({ id: "columns.studio.tag.title" })}
+        url="/workspace/tag"
+      >
+        <TagList
+          studioName={studioName}
+          onSelect={(tag) =>
+            window.open(fullUrl(`/workspace/tag/${tag.id}`), "_blank")
+          }
+        />
+      </ToolModal>
+      <ToolModal
+        open={tool === "tool:driver"}
+        onClose={onClose}
+        title={intl.formatMessage({ id: "columns.studio.attachment.title" })}
+        url="/workspace/driver"
+      >
+        <AttachmentList studioName={studioName} />
+      </ToolModal>
+    </>
+  );
+};
+
+export default ToolsModals;

+ 12 - 0
dashboard-v6/src/components/navigation/tools.ts

@@ -0,0 +1,12 @@
+/** 主导航「工具」的子项,值是菜单 key;点开的是弹窗(ToolsModals),不是路由 */
+export const TOOL_KEYS = [
+  "tool:dictionary",
+  "tool:grammar-book",
+  "tool:dict",
+  "tool:tag",
+  "tool:driver",
+] as const;
+export type ToolKey = (typeof TOOL_KEYS)[number];
+
+export const isToolKey = (key: string): key is ToolKey =>
+  (TOOL_KEYS as readonly string[]).includes(key);

+ 66 - 42
dashboard-v6/src/components/term/GrammarBook.tsx

@@ -1,5 +1,5 @@
 import { Button, Dropdown, Input, List } from "antd";
 import { Button, Dropdown, Input, List } from "antd";
-import { useEffect, useState } from "react";
+import { useEffect, useMemo, useState } from "react";
 import {
 import {
   ArrowLeftOutlined,
   ArrowLeftOutlined,
   FieldTimeOutlined,
   FieldTimeOutlined,
@@ -24,6 +24,7 @@ import { fetchPublicChannels, type Channel } from "../../api/channel";
 import { grammarTermFetch } from "../../load";
 import { grammarTermFetch } from "../../load";
 import TermModal from "./TermModal";
 import TermModal from "./TermModal";
 import { popRecent, pushRecent } from "./utils";
 import { popRecent, pushRecent } from "./utils";
+import type { IGrammarBookState } from "./grammarBookState";
 
 
 const { Search } = Input;
 const { Search } = Input;
 
 
@@ -31,12 +32,55 @@ interface IGrammarList {
   term: ITerm;
   term: ITerm;
   weight: number;
   weight: number;
 }
 }
-const GrammarBookWidget = () => {
+interface IWidget {
+  /** 初始状态(如从地址栏恢复),只在挂载时读一次 */
+  defaultState?: IGrammarBookState;
+  /** 状态变化时回报,供外部写进地址栏或拼「在新标签页打开」的链接 */
+  onStateChange?: (state: IGrammarBookState) => void;
+}
+
+/** 按检索词给系统语法术语打分排序 */
+function searchGrammar(
+  sysGrammar: ITerm[] | undefined,
+  keyWord: string,
+): IGrammarList[] | undefined {
+  if (keyWord.trim().length === 0) return undefined;
+  /**
+   * 权重算法
+   * 约靠近头,分数约高
+   * 剩余尾巴约短,分数越高
+   */
+  return sysGrammar
+    ?.map((item) => {
+      let weight = 0;
+      const wordBegin = item.word
+        .toLocaleLowerCase()
+        .indexOf(keyWord.toLocaleLowerCase());
+      if (wordBegin >= 0) {
+        weight += (1 / (wordBegin + 1)) * 1000;
+        const wordRemain = item.word.length - keyWord.length - wordBegin;
+        weight += (1 / (wordRemain + 1)) * 100;
+      }
+      const meaningBegin = (item.meaning + item.other_meaning)
+        .toLocaleLowerCase()
+        .indexOf(keyWord);
+      if (meaningBegin >= 0) {
+        weight += (1 / (meaningBegin + 1)) * 1000;
+        const meaningRemain = item.meaning.length - keyWord.length - wordBegin;
+        weight += (1 / (meaningRemain + 1)) * 100;
+      }
+      return { term: item, weight: weight };
+    })
+    .filter((value) => value.weight > 0)
+    .sort((a, b) => b.weight - a.weight);
+}
+
+const GrammarBookWidget = ({ defaultState, onStateChange }: IWidget) => {
   const intl = useIntl();
   const intl = useIntl();
 
 
-  const [result, setResult] = useState<IGrammarList[]>();
-  const [localTermId, setLocalTermId] = useState<string>();
-  const [localTermSearch, setLocalTermSearch] = useState<string>();
+  const [keyword, setKeyword] = useState(defaultState?.q ?? "");
+  const [localTermId, setLocalTermId] = useState(defaultState?.id);
+  const [localTermSearch, setLocalTermSearch] = useState(defaultState?.word);
   const [showRecent, setShowRecent] = useState(false);
   const [showRecent, setShowRecent] = useState(false);
   const [create, setCreate] = useState(false);
   const [create, setCreate] = useState(false);
   const [grammarChannel, setGrammarChannel] = useState<Channel>();
   const [grammarChannel, setGrammarChannel] = useState<Channel>();
@@ -47,6 +91,20 @@ const GrammarBookWidget = () => {
   const termId = searchWordId || localTermId;
   const termId = searchWordId || localTermId;
   const termSearch = searchWord || localTermSearch;
   const termSearch = searchWord || localTermSearch;
 
 
+  // 术语表是异步加载的:从地址栏带着检索词进来时,要等它到了再算结果,所以派生而不是在 onChange 里算
+  const result = useMemo(
+    () => searchGrammar(sysGrammar, keyword),
+    [sysGrammar, keyword],
+  );
+
+  useEffect(() => {
+    onStateChange?.({
+      q: keyword || undefined,
+      id: localTermId || undefined,
+      word: localTermSearch || undefined,
+    });
+  }, [keyword, localTermId, localTermSearch, onStateChange]);
+
   useEffect(() => {
   useEffect(() => {
     const name = "_System_Grammar_Term_zh-hans_";
     const name = "_System_Grammar_Term_zh-hans_";
     fetchPublicChannels({ system: true, search: name, per_page: 20 }).then(
     fetchPublicChannels({ system: true, search: name, per_page: 20 }).then(
@@ -95,48 +153,14 @@ const GrammarBookWidget = () => {
         />
         />
         <Search
         <Search
           placeholder="input search text"
           placeholder="input search text"
+          value={keyword}
           onChange={(event: React.ChangeEvent<HTMLInputElement>) => {
           onChange={(event: React.ChangeEvent<HTMLInputElement>) => {
             console.debug("on change", event.target.value);
             console.debug("on change", event.target.value);
             setLocalTermId(undefined);
             setLocalTermId(undefined);
             setLocalTermSearch(undefined);
             setLocalTermSearch(undefined);
             const keyWord = event.target.value;
             const keyWord = event.target.value;
-            if (keyWord.trim().length === 0) {
-              setShowRecent(true);
-            } else {
-              setShowRecent(false);
-            }
-            /**
-             * 权重算法
-             * 约靠近头,分数约高
-             * 剩余尾巴约短,分数越高
-             */
-            const search = sysGrammar
-              ?.map((item) => {
-                let weight = 0;
-                const wordBegin = item.word
-                  .toLocaleLowerCase()
-                  .indexOf(keyWord.toLocaleLowerCase());
-                if (wordBegin >= 0) {
-                  weight += (1 / (wordBegin + 1)) * 1000;
-                  const wordRemain =
-                    item.word.length - keyWord.length - wordBegin;
-                  weight += (1 / (wordRemain + 1)) * 100;
-                }
-                const meaningBegin = (item.meaning + item.other_meaning)
-                  .toLocaleLowerCase()
-                  .indexOf(keyWord);
-                if (meaningBegin >= 0) {
-                  weight += (1 / (meaningBegin + 1)) * 1000;
-                  const meaningRemain =
-                    item.meaning.length - keyWord.length - wordBegin;
-                  weight += (1 / (meaningRemain + 1)) * 100;
-                }
-                return { term: item, weight: weight };
-              })
-              .filter((value) => value.weight > 0)
-              .sort((a, b) => b.weight - a.weight);
-
-            setResult(search);
+            setKeyword(keyWord);
+            setShowRecent(keyWord.trim().length === 0);
           }}
           }}
           style={{ width: "100%" }}
           style={{ width: "100%" }}
         />
         />

+ 27 - 0
dashboard-v6/src/components/term/grammarBookState.ts

@@ -0,0 +1,27 @@
+/** 语法手册可重入的状态:检索词、选中的术语(按 id 或按词) */
+export interface IGrammarBookState {
+  q?: string;
+  id?: string;
+  word?: string;
+}
+
+/** 状态 → 地址栏查询串(/grammar-book?q=&id=&word=),空状态给空串 */
+export function grammarBookSearch(state: IGrammarBookState): string {
+  const params = new URLSearchParams();
+  if (state.q) params.set("q", state.q);
+  if (state.id) params.set("id", state.id);
+  if (state.word) params.set("word", state.word);
+  const search = params.toString();
+  return search ? `?${search}` : "";
+}
+
+/** 地址栏查询串 → 状态 */
+export function parseGrammarBookSearch(
+  params: URLSearchParams,
+): IGrammarBookState {
+  return {
+    q: params.get("q") ?? undefined,
+    id: params.get("id") ?? undefined,
+    word: params.get("word") ?? undefined,
+  };
+}

+ 10 - 7
dashboard-v6/src/pages/workspace/dictionary/index.tsx → dashboard-v6/src/pages/dictionary/index.tsx

@@ -1,17 +1,20 @@
 import { useEffect, useRef } from "react";
 import { useEffect, useRef } from "react";
+import { theme } from "antd";
 import { useIntl } from "react-intl";
 import { useIntl } from "react-intl";
 import { useNavigate, useParams } from "react-router";
 import { useNavigate, useParams } from "react-router";
 
 
-import Dictionary from "../../../components/dict/Dictionary";
-import { useAppSelector } from "../../../hooks";
-import { lookupWord } from "../../../reducers/command";
+import Dictionary from "../../components/dict/Dictionary";
+import { useAppSelector } from "../../hooks";
+import { lookupWord } from "../../reducers/command";
 
 
 /**
 /**
  * 字典(独立页面)
  * 字典(独立页面)
- * 查的词放在路由里(/workspace/dictionary/:word),刷新、分享、前进后退都能重入。
+ * 查的词放在路由里(/dictionary/:word),刷新、分享、前进后退都能重入。
+ * 不在 workspace 布局里;主导航「工具 → 字典」弹窗的「在新标签页打开」跳到这里。
  */
  */
 const Widget = () => {
 const Widget = () => {
   const intl = useIntl();
   const intl = useIntl();
+  const { token } = theme.useToken();
   const navigate = useNavigate();
   const navigate = useNavigate();
   const { word } = useParams();
   const { word } = useParams();
 
 
@@ -24,7 +27,7 @@ const Widget = () => {
   const search = (value?: string) => {
   const search = (value?: string) => {
     if (!value || value === lastWord.current) return;
     if (!value || value === lastWord.current) return;
     lastWord.current = value;
     lastWord.current = value;
-    navigate(`/workspace/dictionary/${encodeURIComponent(value)}`);
+    navigate(`/dictionary/${encodeURIComponent(value)}`);
   };
   };
 
 
   // 结果里的巴利词点击查词走的是 redux 的 lookup,这里跟上它。
   // 结果里的巴利词点击查词走的是 redux 的 lookup,这里跟上它。
@@ -39,11 +42,11 @@ const Widget = () => {
   }, [lookup]);
   }, [lookup]);
 
 
   return (
   return (
-    <>
+    <div style={{ minHeight: "100vh", background: token.colorBgContainer }}>
       {/* React 19 的 <title> 只接受单个字符串子节点 */}
       {/* React 19 的 <title> 只接受单个字符串子节点 */}
       <title>{`${word ? `${word} - ` : ""}${intl.formatMessage({ id: "columns.library.dict.title" })}`}</title>
       <title>{`${word ? `${word} - ` : ""}${intl.formatMessage({ id: "columns.library.dict.title" })}`}</title>
       <Dictionary word={word} onSearch={search} />
       <Dictionary word={word} onSearch={search} />
-    </>
+    </div>
   );
   );
 };
 };
 
 

+ 46 - 0
dashboard-v6/src/pages/grammar-book/index.tsx

@@ -0,0 +1,46 @@
+import { useCallback, useState } from "react";
+import { theme } from "antd";
+import { useIntl } from "react-intl";
+import { useSearchParams } from "react-router";
+
+import GrammarBook from "../../components/term/GrammarBook";
+import {
+  grammarBookSearch,
+  parseGrammarBookSearch,
+  type IGrammarBookState,
+} from "../../components/term/grammarBookState";
+
+/**
+ * 语法手册(独立页面)
+ * 与编辑器右边栏的语法手册面板是同一个组件。
+ * 不在 workspace 布局里;主导航「工具 → 语法手册」弹窗的「在新标签页打开」跳到这里。
+ * 检索词与选中的术语在地址栏里(?q=&id=&word=),刷新、分享都能重入。
+ */
+const Widget = () => {
+  const intl = useIntl();
+  const { token } = theme.useToken();
+  const [searchParams, setSearchParams] = useSearchParams();
+  // 只在挂载时读一次;之后由组件回报、写回地址栏
+  const [defaultState] = useState(() => parseGrammarBookSearch(searchParams));
+  const onStateChange = useCallback(
+    (state: IGrammarBookState) =>
+      setSearchParams(grammarBookSearch(state), { replace: true }),
+    [setSearchParams],
+  );
+
+  return (
+    <div style={{ minHeight: "100vh", background: token.colorBgContainer }}>
+      <div style={{ maxWidth: 960, margin: "0 auto", padding: 16 }}>
+        <title>
+          {intl.formatMessage({ id: "columns.library.palihandbook.title" })}
+        </title>
+        <GrammarBook
+          defaultState={defaultState}
+          onStateChange={onStateChange}
+        />
+      </div>
+    </div>
+  );
+};
+
+export default Widget;

+ 0 - 21
dashboard-v6/src/pages/workspace/grammar-book/index.tsx

@@ -1,21 +0,0 @@
-import { useIntl } from "react-intl";
-
-import GrammarBook from "../../../components/term/GrammarBook";
-
-/**
- * 语法手册(独立页面)
- * 与编辑器右边栏的语法手册面板是同一个组件。
- */
-const Widget = () => {
-  const intl = useIntl();
-  return (
-    <div style={{ maxWidth: 960, margin: "0 auto", padding: 16 }}>
-      <title>
-        {intl.formatMessage({ id: "columns.library.palihandbook.title" })}
-      </title>
-      <GrammarBook />
-    </div>
-  );
-};
-
-export default Widget;

+ 10 - 11
dashboard-v6/src/routes/dictionaryRoutes.ts

@@ -1,24 +1,23 @@
 // src/routes/dictionaryRoutes.ts
 // src/routes/dictionaryRoutes.ts
-// 编辑器右边栏的「字典」「语法手册」的独立页面。
+// 「字典」「语法手册」的独立页面,挂在根下(/dictionary、/grammar-book),不在 workspace 布局里:
+// 主导航「工具」里打开的是弹窗,弹窗「在新标签页打开」跳到这里。
 // 注意 /workspace/dict 是「用户字典」,不要混淆。
 // 注意 /workspace/dict 是「用户字典」,不要混淆。
 import { lazy } from "react";
 import { lazy } from "react";
 import type { RouteObject, UIMatch } from "react-router";
 import type { RouteObject, UIMatch } from "react-router";
 
 
-const WorkspaceDictionary = lazy(() => import("../pages/workspace/dictionary"));
-const WorkspaceGrammarBook = lazy(
-  () => import("../pages/workspace/grammar-book"),
-);
+const Dictionary = lazy(() => import("../pages/dictionary"));
+const GrammarBook = lazy(() => import("../pages/grammar-book"));
 
 
 const dictionaryRoutes: RouteObject[] = [
 const dictionaryRoutes: RouteObject[] = [
   {
   {
     path: "dictionary",
     path: "dictionary",
-    handle: { id: "workspace.dictionary", crumb: "dictionary" },
+    handle: { id: "dictionary", crumb: "dictionary" },
     children: [
     children: [
-      { index: true, Component: WorkspaceDictionary },
-      // 查词结果可重入:/workspace/dictionary/dhamma
+      { index: true, Component: Dictionary },
+      // 查词结果可重入:/dictionary/dhamma
       {
       {
         path: ":word",
         path: ":word",
-        Component: WorkspaceDictionary,
+        Component: Dictionary,
         handle: {
         handle: {
           crumb: (match: UIMatch) => match.params.word ?? "",
           crumb: (match: UIMatch) => match.params.word ?? "",
         },
         },
@@ -27,8 +26,8 @@ const dictionaryRoutes: RouteObject[] = [
   },
   },
   {
   {
     path: "grammar-book",
     path: "grammar-book",
-    Component: WorkspaceGrammarBook,
-    handle: { id: "workspace.grammar-book", crumb: "grammar-book" },
+    Component: GrammarBook,
+    handle: { id: "grammar-book", crumb: "grammar-book" },
   },
   },
 ];
 ];