Compare commits

..

4 Commits

Author SHA1 Message Date
zhanjunhao ef93825c07 feat: 修改git忽略规则、playwright自动化登录验收 2026-11-17 10:25:52 +08:00
zhanjunhao d563fe7c76 feat(website): 对齐官网文章配置与展示顺序 2026-11-17 10:10:29 +08:00
zhanjunhao 34a7eca5c7 fix(market): 1.修复模型超市 模糊搜索-模型名称异常的问题
feat(table): 2.新增三中心表格统一策略:

- 覆盖 `/user-center/*`、`/org/*`、`/console/*`,包含系统设置。
- 自动识别最后一列的创建、查看、编辑、测试、详情、删除、设置、弹窗、API 回调等交互。
- 操作列统一显示“操作”,固定在右侧。
- 根据按钮和文字实际宽度测量,保持操作文字单行显示。
- 非操作宽表自动固定右侧末 4 / 3 / 2 / 1 列。
- 保留 Ant Design 官方横向滚动行为,不隐藏滚动条。
2026-11-17 10:10:28 +08:00
zhanjunhao 93128a77d3 feat(website): 文章发布时间精确到秒 2026-11-14 18:53:31 +08:00
35 changed files with 915 additions and 283 deletions
+8
View File
@@ -0,0 +1,8 @@
UI_ORG_NAME=测试企业1
UI_ORG_USER=test111
UI_ORG_PASS=2uT7anlhzR5w
UI_PERSONAL_USER=test222
UI_PERSONAL_PASS=12345678
UI_VISUAL_OFFSCREEN=1
UI_ADMIN_USER=ltadmin
UI_ADMIN_PASS=DoWtIMTli7njHYQeCNaR
-8
View File
@@ -56,14 +56,6 @@ lerna-debug.log*
.DS_Store
Thumbs.db
Desktop.ini
.env
.env.*
!.env.development
!.env.production
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
+37 -1
View File
@@ -1,6 +1,6 @@
# 变更记录(CHANGELOG)
> 状态:有效(持续追加) · 更新:2026-11-13 · 版本:v3.1
> 状态:有效(持续追加) · 更新:2026-11-16 · 版本:v3.1
对现状仍有影响的功能与修复记录,按日期倒序。改造、迁移、优化等一次性过程不在此记录。
@@ -8,6 +8,42 @@
**记录规则**:每条写“范围、变更、影响、回滚、关联”五项;回滚优先 `git revert <提交>`,提交含多项改动时按文件还原(`git checkout <提交>^ -- <文件>`),不整仓 reset。本文不作为规则依据。
## 2026-11-16
### 修复 · 筛选卡纯色背景、模型名称搜索与三中心表格固定列
- **范围**:使用记录两个页签的筛选卡、`/market` 搜索,以及 `/user-center/*`、`/org/*`、`/console/*`(含系统设置)的操作表格。
- **变更**:使用记录筛选卡移除渐变,浅色使用白色卡片底;模型搜索只匹配模型名称并忽略大小写与关键词首尾空格;三中心(含系统设置)识别末列交互并统一改为“操作”后固定右侧;无操作列且列宽超出容器时动态固定右侧末 4 / 3 / 2 / 1 列,恢复 Ant Design 官方横向滚动条。
- **影响**:保留接口、载荷、权限、分页、筛选及操作回调;普通详情文本列不纳入操作列,固定单元格使用不透明底色并保持窄屏可读。
- **回滚**:还原本次 `CenterActionTable`、`centerTablePolicy`、表格入口接入、`UsageRecord.css` 与 `useModelPricingData.jsx` 的变更,不涉及数据迁移。
- **关联**:`docs/standards/UI_COMPONENT_STANDARDS.md` 第 4、5.2 节,`docs/ui/USER_CENTER_SPEC.md` 第 4.2 节,`docs/ui/MODEL_MARKET_SPEC.md` 第 8 节。
### 功能 · 官网设置「动态与洞察」对齐官网列表与详情页
- **范围**:`/console/website-setting` 动态与洞察页签(文章列表、分类管理、新增 / 编辑文章抽屉)。
- **变更**:
- 文章字段收敛为官网实际使用的 `id`、`category`、`date`(`YYYY-MM-DD`,仅列表卡片展示)、`title`、`summary`(文章描述)、`tag`、`body`、`related`,移除详情副标题、目录开关与时分秒。
- 文章必须归属真实分类,“全部内容”仅作为筛选项。
- 目录预览只取正文 H2。
- 列表新增“角标”列;顺序即官网展示顺序,可上移 / 下移,不再按日期排序。
- 无分类时禁止新增文章。
- 允许保存空文章列表。
- **影响**:
- 全新官网配置,不兼容历史数据:读取时只保留上述字段,其他字段丢弃。
- 接口与提交结构不变。
- **回滚**:按文件还原 `src/pages/WebsiteSettings/{ArticleEditor.jsx,InsightsPanel.jsx,insightsModel.js,insightsContent.js,model.js,WebsiteSettings.css,README.md}`。
- **关联**:`src/pages/WebsiteSettings/README.md` 的“动态与洞察”一节。
## 2026-11-14
### 功能 · 官网设置文章发布时间精确到秒
- **范围**:`/console/website-setting` 动态与洞察页签的新增 / 编辑文章抽屉与文章列表。
- **变更**:发布日期由原生日期输入改为 `DatePicker`(`dateTime`),存储格式 `YYYY-MM-DD HH:mm:ss`;新建文章默认当前时间;校验按本地时间逐项检查年月日时分秒;列表“发布日期”列宽 140 → 180。
- **影响**:旧数据 `YYYY-MM-DD` 仍校验通过(编辑时显示 `00:00:00`),列表倒序排序对新旧格式均有效;官网前台读取 `date` 时需兼容带时分秒的值。
- **回滚**:按文件还原 `src/pages/WebsiteSettings/{ArticleEditor.jsx,InsightsPanel.jsx,insightsModel.js,insightsModel.test.js}`,不涉及数据迁移。
- **关联**:`src/pages/WebsiteSettings/README.md`。
## 2026-11-13
### UI · 两个超市的响应式留白与卡片布局
+4 -2
View File
@@ -1,6 +1,6 @@
# UI 公共组件与样式规范
> 状态:有效 · 适用:antd 6.7.0 · 更新:2026-11-11 · 版本:v2.1
> 状态:有效 · 适用:antd 6.7.0 · 更新:2026-11-16 · 版本:v2.2
所有后台页面共用的主题与组件标准。页面规范只记录与本文不同的部分;编码约定见 `DEV_STANDARDS.md`,外壳与布局见 `GLOBAL_UI_BASELINE.md`。
@@ -125,6 +125,7 @@ html.dark .km-page {
## 4. 表格搜索栏(筛选卡)
- 背景:使用不透明的卡片纯色;浅色为白色,深色沿用主题卡片色,不使用渐变背景。
- 字段竖排:标签在上(13px,次文字色,下距 8px),控件在下且宽度占满单元格。
- 栅格:列间距与行间距 16px;按页面宽度取 3–5 列(企业中心 3 列、控制台 4 列、用户中心 5 列,时间范围可跨 2 列);≤ 768px 单列。
- 操作:“重置”“搜索”位于右下,间距 8px;“搜索”为 primary 且 `htmlType='submit'`,回车提交。
@@ -148,7 +149,8 @@ html.dark .km-page {
- 每列显式 `width`,长文本 `ellipsis` 并配 `Tooltip`;金额与数量右对齐;时间统一格式,必要时日期与时间分两行。
- 状态列用 `Tag` 或 `Switch`(见第 11 节);启停开关请求中禁用,失败恢复原状态。
- 操作列放在最后,按钮为 `type='link' size='small'`,危险操作加 `danger`,同一行操作间距 8–10px;只有宽表才 `fixed: 'right'`;操作较多时折叠到“更多”下拉。
- 操作列放在最后,按钮为 `type='link' size='small'`,危险操作加 `danger`,同一行操作间距 8–10px;用户中心、企业中心、控制台(含系统设置)的操作列统一 `fixed: 'right'`;操作较多时折叠到“更多”下拉。
- 三中心表格通过 `CenterActionTable` 统一处理,最后一列存在创建、查看、编辑、测试、详情、删除、添加、设置、配置、弹窗 / 抽屉或请求交互时,列头统一显示“操作”并固定右侧,宽度按按钮 / 交互数量计算。没有操作列但估算列宽超出容器时,从右侧固定末 4 列,列数不足时降为 3、2、1 列。固定列使用不透明底色并保持表头层级;横向滚动条遵循 Ant Design 官方固定列表格行为,允许鼠标、触控板、触屏和键盘滚动,不隐藏滚动条。
- 列显隐只在已有列设置的表格中提供,统一使用 `ColumnSettings`(见 `docs/ui/TABLE_COLUMN_SETTINGS_SPEC.md`)。
### 5.3 状态
+2 -2
View File
@@ -1,6 +1,6 @@
# 后台 UI 全局基线
> 状态:有效 · 适用:antd 6.7.0 · 更新:2026-11-13 · 版本:v3.3
> 状态:有效 · 适用:antd 6.7.0 · 更新:2026-11-16 · 版本:v3.4
后台外壳与布局基线:顶栏、侧栏、公告、页头与内容边距、登录页,以及原型未定义场景、登录关卡与验收流程。主题与组件样式见 `UI_COMPONENT_STANDARDS.md`。
@@ -75,7 +75,7 @@
1. **内容边距**:读取 `user-center.css` 的 `--uc-page-pad-top/x/bottom`(桌面 30 / 36 / 36px,≤ 768px 为 16 / 16 / 24px)。普通页面根节点用 `.uc-page`;数据看板 `.uc-dashboard`、服务监控 `.user-center-service-page`(`calc(64px + 顶距)`,抵消宿主 `-mt-[64px]`)、下载页 `.weyai-download--embedded` 直接引用这些变量。企业功能页(`.org-*-page`、`.knowledge-page`、`.org-workbench`)走 `org-page.css`。禁止写死页面级边距或使用 `p-4 sm:p-6 lg:p-8`。工作区块间距 `--uc-layout-gap: 18px`。
2. **页头**:用户中心用 `<UserCenterPageHeader title subtitle extra />`,企业中心用 `OrgPageHeader`(内部复用前者)。面包屑 12 / 18px,距内容区顶 30px,父级 `--text-secondary`、当前项 `--text-primary`,分隔符左右 10px,与标题 24px;标题 28 / 32px / 650 / 字距 -0.6px(`--uc-heading`);副标题 14 / 22px、上距 6px(`--uc-subtitle`);页头与首块 18px;右侧操作放 `extra`(间距 8px,窄屏换行)。页面不得覆盖这些数值,数据看板只保留 hero 装饰层。
3. **面包屑登记**:用户中心在 `UserCenterBreadcrumb.jsx` 的 `pageTitles` 登记,显示“用户中心 / 当前页面”;企业中心在 `OrgBreadcrumb` 的 `orgPageGroups` 登记,分组页显示“分组 / 当前页面”,其他为“企业中心 / 当前页面”,未登记页面以标题兜底。带 hero 的企业功能页在 hero 内首个元素顶部放 `<OrgBreadcrumb />`。不在原本没有面包屑的页面新增导航;没有副标题文案时只传 `title`。
4. **滚动条**:全站滑块 `#8b8b8b`、悬停 `#636363`、宽高 6px、圆角 3px、轨道透明,值来自 `tokens.css` 的 `--brand-scroll` / `--brand-scroll-hover`,规则集中在 `src/index.css`。页面 CSS 与内联样式禁止设置 `scrollbar-width` / `scrollbar-color`(Chrome 121+ 设置后会忽略 `::-webkit-scrollbar`),标准属性只在 `@supports not selector(::-webkit-scrollbar)` 中给 Firefox。
4. **滚动条**:全站滑块 `#8b8b8b`、悬停 `#636363`、宽高 6px、圆角 3px、轨道透明,值来自 `tokens.css` 的 `--brand-scroll` / `--brand-scroll-hover`,规则集中在 `src/index.css`。页面 CSS 与内联样式禁止设置 `scrollbar-width` / `scrollbar-color`(Chrome 121+ 设置后会忽略 `::-webkit-scrollbar`),标准属性只在 `@supports not selector(::-webkit-scrollbar)` 中给 Firefox。三中心操作表格沿用 Ant Design 固定列表格的横向滚动行为,不隐藏滚动条。
5. **验证**:逐页核对左右边距、面包屑顶距、标题与副标题字号间距、滚动条静止与悬停颜色(桌面 / 移动 × 浅 / 深)。
### 4.5 登录页与认证顶栏
+2 -1
View File
@@ -1,6 +1,6 @@
# 模型超市 UI 规范(/market)
> 状态:有效 · 适用:antd 6.7.0 · 更新:2026-11-13 · 版本:v2.3
> 状态:有效 · 适用:antd 6.7.0 · 更新:2026-11-16 · 版本:v2.4
个人端模型超市 `/market` 的规范。本页为独立视觉页面,组件映射优先于公共规范。
@@ -109,6 +109,7 @@
## 8. 验收要点
- 搜索仅对 `model_name` 做不区分大小写的子串匹配,忽略关键词首尾空格;描述、标签、厂商名称不参与关键词匹配,其他筛选条件仍取交集;保留原前端防抖,不新增搜索请求。
- 视口 1920×1000 与 393×851,浅深主题;交互序列:默认厂商行 → 展开五组条件 → 选择分组 → 收起仍保持筛选与价格 → 重置 → 悬停卡片 → 键盘聚焦卡片 → 关键词搜索 → 选择厂商 → 空结果 → 整页滚动到底与厂商懒渲染 → 打开详情。
- 响应式补充 3840×2160、2560×1440、1920×1080、中屏及断点两侧、360×800;检查两侧留白、卡片宽度、正文换行、无横向溢出,以及筛选展开和详情在窄屏上的可达性。
- 与原型比较时使用同构模拟目录并标注;真实后端另行验证;整页 ≤ 0.5%、组件 ≤ 0.2%。
+3 -3
View File
@@ -1,6 +1,6 @@
# 用户中心 UI 规范(/user-center/\*)
> 状态:有效 · 适用:antd 6.7.0 · 更新:2026-11-11 · 版本:v2.2
> 状态:有效 · 适用:antd 6.7.0 · 更新:2026-11-16 · 版本:v2.3
个人登录后用户中心页面的规范,只记录与公共规范不同的部分;密钥管理、服务监控见各自规范。
@@ -76,9 +76,9 @@
### 4.2 使用记录
- 页签:纯文字页签(公共列表页签样式),与下方 20px,URL `?tab=` 同步并懒挂载。
- 筛选卡:5 列栅格,时间范围跨 2 列;带浅暖色渐变底(仅 `.usage-record-page`);操作“重置 / 搜索”右下。
- 筛选卡:5 列栅格,时间范围跨 2 列;背景使用 `--surface-card` 纯色(浅色为白色、深色为主题卡片色);操作“重置 / 搜索”右下。
- 列表卡:标题 15px / 600,导出、列设置位于卡头右侧;表头字重 400(公共标准为 500,待收敛)。
- 消费记录调用明细为固定列宽宽表,时间分两行(日期 11px、时间 15px / 600),操作列文字“查看”,随表格横向滚动。
- 消费记录调用明细为固定列宽宽表,时间分两行(日期 11px、时间 15px / 600),操作列文字“查看”,固定在右侧;横向滚动条保留 Ant Design 官方固定列表格行为,固定列兼容规则遵循公共规范第 5.2 节。
- 绘图与视频:三张统计卡(高 70px、间距 15px)+ 任务记录表。
- Webhook 示例为 `<pre class='ui-notify-code'>` +“复制”链接,复制提示沿用原文案。
+1 -1
View File
@@ -18,6 +18,7 @@ For commercial licensing, please contact support@quantumnous.com
*/
import React, { forwardRef } from 'react';
import Table from '../ui/CenterActionTable';
import {
Alert,
Button,
@@ -26,7 +27,6 @@ import {
Empty,
Form,
Modal,
Table,
Tabs,
theme,
} from 'antd';
@@ -18,7 +18,8 @@ For commercial licensing, please contact support@quantumnous.com
*/
import React, { useState } from 'react';
import { Modal, Button, Input, Table, Tag, Typography, Select } from 'antd';
import Table from '../../../ui/CenterActionTable';
import { Modal, Button, Input, Tag, Typography, Select } from 'antd';
import { Search } from 'lucide-react';
import { copy, showError, showInfo, showSuccess } from '../../../../helpers';
import { MODEL_TABLE_PAGE_SIZE } from '../../../../constants';
@@ -19,7 +19,8 @@ For commercial licensing, please contact support@quantumnous.com
import TableEmpty from '../../common/table/TableEmpty';
import React, { useMemo, useState } from 'react';
import { Button as AntButton, Table as AntTable } from 'antd';
import AntTable from '../../ui/CenterActionTable';
import { Button as AntButton } from 'antd';
import { Modal, Typography } from '@/components/ui';
import {
Coins,
+143
View File
@@ -0,0 +1,143 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, { forwardRef, useLayoutEffect, useRef, useState } from 'react';
import { Table, theme } from 'antd';
import { colord } from 'colord';
import { isCenterTableScope, prepareCenterColumns } from './centerTablePolicy';
import './center-table.css';
const CenterTable = forwardRef(function CenterTable(
{ columns, className, scroll, style, ...props },
ref,
) {
const { token } = theme.useToken();
const base = colord(token.colorBgContainer).toRgb();
const solidColor = (color) => {
const value = colord(color).toRgb();
return colord({
r: value.r * value.a + base.r * (1 - value.a),
g: value.g * value.a + base.g * (1 - value.a),
b: value.b * value.a + base.b * (1 - value.a),
a: 1,
}).toRgbString();
};
const tableRef = useRef(null);
const [width, setWidth] = useState(0);
const [measuredActionWidths, setMeasuredActionWidths] = useState({});
const scoped = isCenterTableScope(
typeof window === 'undefined' ? '' : window.location.pathname,
);
const prepared =
scoped && columns
? prepareCenterColumns(columns, width, measuredActionWidths)
: columns;
const enabled = prepared !== columns;
useLayoutEffect(() => {
if (!enabled) return;
const root = tableRef.current?.nativeElement;
if (!root) return;
const scroller = root.querySelector('.ant-table-content,.ant-table-body');
const previousTabIndex = scroller?.getAttribute('tabindex');
if (scroller && previousTabIndex === null) scroller.tabIndex = 0;
const update = () => setWidth(root.clientWidth);
update();
const measureActionWidths = () => {
const next = {};
root.querySelectorAll('th.center-action-cell').forEach((header) => {
const marker = [...header.classList].find((name) =>
name.startsWith('center-fixed-index-'),
);
if (!marker) return;
const cells = [...root.querySelectorAll(`td.${marker}`)].filter(
(element) => element.getBoundingClientRect().width > 0,
);
const cell = cells.find((candidate) =>
candidate.querySelector('button, a, [role="button"]'),
);
const controls = cell
? [...cell.querySelectorAll('button, a, [role="button"]')].filter(
(element) => element.getBoundingClientRect().width > 0,
)
: [];
const cellStyle = getComputedStyle(cell || header);
const padding =
(Number.parseFloat(cellStyle.paddingLeft) || 0) +
(Number.parseFloat(cellStyle.paddingRight) || 0);
const gap = Number.parseFloat(cellStyle.columnGap) || 8;
const contentWidth = controls.length
? controls.reduce(
(total, element) => total + element.getBoundingClientRect().width,
0,
) +
gap * Math.max(0, controls.length - 1)
: Math.max(...cells.map((candidate) => candidate.scrollWidth), 0) -
padding;
next[marker.replace('center-fixed-index-', '')] =
contentWidth + padding;
});
setMeasuredActionWidths((current) => {
const same =
Object.keys(next).length === Object.keys(current).length &&
Object.keys(next).every(
(key) => Math.abs(next[key] - current[key]) < 1,
);
return same ? current : next;
});
};
requestAnimationFrame(measureActionWidths);
const observer = new ResizeObserver(update);
observer.observe(root);
return () => {
observer.disconnect();
if (scroller && previousTabIndex === null)
scroller.removeAttribute('tabindex');
};
}, [enabled, width]);
return (
<Table
{...props}
ref={(instance) => {
tableRef.current = instance;
if (typeof ref === 'function') ref(instance);
else if (ref) ref.current = instance;
}}
columns={prepared}
className={[className, enabled && 'center-action-table']
.filter(Boolean)
.join(' ')}
scroll={enabled ? { ...scroll, x: scroll?.x || 'max-content' } : scroll}
style={
enabled
? {
'--center-table-bg': token.colorBgContainer,
'--center-table-head-bg': solidColor(token.colorFillAlter),
'--center-table-hover-bg': solidColor(token.controlItemBgHover),
'--center-table-selected-bg': solidColor(
token.controlItemBgActive,
),
...style,
}
: style
}
/>
);
});
export default CenterTable;
+55
View File
@@ -0,0 +1,55 @@
.center-action-table {
min-width: 0;
max-width: 100%;
}
.center-action-table .ant-table-tbody > tr > .center-fixed-cell {
z-index: 2;
background: var(--center-table-bg);
background-clip: padding-box;
}
.center-action-table .ant-table-thead > tr > .center-fixed-cell {
z-index: 3;
background: var(--ur-head-bg, var(--center-table-head-bg));
background-clip: padding-box;
}
.center-action-table .ant-table-tbody > tr:hover > .center-fixed-cell {
background: var(--center-table-hover-bg);
}
.center-action-table
.ant-table-tbody
> tr.ant-table-row-selected
> .center-fixed-cell {
background: var(--center-table-selected-bg);
}
.center-action-table .center-fixed-cell {
white-space: normal;
overflow-wrap: anywhere;
}
.center-action-table .center-action-cell {
white-space: nowrap;
}
.center-action-table
.center-action-cell
:where(
.ant-space,
.ant-flex,
.flex,
.km-actions,
.oc-row-actions,
.org-row-actions,
.console-module-row-actions,
.console-channel-key-actions,
.console-channel-model-actions,
.admin-tokens-row-actions,
.website-insights-row-actions
) {
flex-wrap: nowrap;
max-width: none;
}
+133
View File
@@ -0,0 +1,133 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import i18next from 'i18next';
export const isCenterTableScope = (pathname) =>
/^\/(user-center|org|console)(\/|$)/.test(pathname || '');
const titleText = (title) => {
if (typeof title === 'string') return title.trim();
if (Array.isArray(title)) return title.map(titleText).join('');
return title?.props ? titleText(title.props.children) : '';
};
export function isActionColumn(column) {
const title = titleText(column.title);
const key = String(column.key ?? column.dataIndex ?? '');
const source =
typeof column.render === 'function' ? column.render.toString() : '';
const titleSignal =
/^(操作|计费详情|编辑|测试|删除|添加|新增|设置|配置|创建|管理|actions?|operate|operations?)$/i.test(
title,
);
const detailTitleSignal = /^(详情|查看|打开|预览|结果|失败原因)$/i.test(
title,
);
const keySignal =
/^(actions|operate|operations|billingDetailAction|fail_reason|details?)$/i.test(
key,
) && typeof column.render === 'function';
const interactionSignal =
/\b(?:onClick|onOpen|onChange|Modal|Drawer|Popconfirm|Dropdown|Button|Link|API|request|fetch|navigate)\b/i.test(
source,
);
return Boolean(
titleSignal ||
keySignal ||
interactionSignal ||
(detailTitleSignal && (interactionSignal || key === 'fail_reason')),
);
}
const leafColumns = (columns) =>
columns.flatMap((column) =>
column.children ? leafColumns(column.children) : [column],
);
const columnTitleWidth = (column) => {
const title = titleText(column.title);
return Math.max(96, Math.min(260, 32 + [...title].length * 14));
};
const columnWidth = (column) => {
const width = Number(column.width);
return Number.isFinite(width) && width > 0 ? width : columnTitleWidth(column);
};
const actionWidth = (column, measuredWidth) => {
if (Number.isFinite(measuredWidth) && measuredWidth > 0)
return Math.ceil(Math.min(360, Math.max(56, measuredWidth)));
const source =
typeof column.render === 'function' ? column.render.toString() : '';
const count = (
source.match(
/<\s*(?:Button|Link|Dropdown|Popconfirm)\b|\b(?:Button|Link|Dropdown|Popconfirm|onClick|onOpen|onChange)\b/gi,
) || []
).length;
return Math.min(360, Math.max(56, 32 + Math.max(1, count) * 44));
};
const markFixedRight = (
column,
index,
action = false,
measuredWidths = {},
) => ({
...column,
fixed: 'right',
width: action
? actionWidth(column, measuredWidths[index])
: columnWidth(column),
...(action ? { title: i18next.t('操作') || '操作' } : {}),
className: [
column.className,
'center-fixed-cell',
action && 'center-action-cell',
`center-fixed-index-${index}`,
]
.filter(Boolean)
.join(' '),
});
export function prepareCenterColumns(columns, width = 0, measuredWidths = {}) {
const leaves = leafColumns(columns);
const last = leaves.at(-1);
const hasAction = last && isActionColumn(last);
const estimatedTotal = leaves.reduce(
(total, column) => total + columnWidth(column),
0,
);
const overflow = width > 0 && estimatedTotal > width;
const fixedCount = Math.max(1, Math.min(4, leaves.length));
const fallback =
!hasAction && overflow ? new Set(leaves.slice(-fixedCount)) : new Set();
let index = 0;
return columns.map(function mapColumn(column) {
if (column.children)
return { ...column, children: column.children.map(mapColumn) };
const columnIndex = index++;
if (hasAction && column === last)
return markFixedRight(column, columnIndex, true, measuredWidths);
if (fallback.has(column)) return markFixedRight(column, columnIndex);
if (column.fixed) return { ...column, width: columnWidth(column) };
return column;
});
}
+2 -1
View File
@@ -28,6 +28,7 @@ import {
paginationShowTotal,
} from './pagination';
import { overlayMask } from './overlayPolicy';
import CenterTable from './CenterActionTable';
import './pagination.css';
import { useIsMobile } from '../../hooks/common/useIsMobile';
import { useConsolePage } from '../console/ConsoleContext';
@@ -293,7 +294,7 @@ export function Table({
...props
}) {
const consolePage = useConsolePage();
const BaseTable = consolePage ? ConsoleTable : Ant.Table;
const BaseTable = consolePage ? ConsoleTable : CenterTable;
const unified = Boolean(pagination) && isCenterPaginationScope();
const Component = unified ? CenterPaginatedTable : BaseTable;
const expandable = expandedRowRender
@@ -157,17 +157,12 @@ export const useModelPricingData = () => {
}
// 搜索筛选
if (searchValue.length > 0) {
const searchTerm = searchValue.toLowerCase();
if (searchValue.trim().length > 0) {
const searchTerm = searchValue.trim().toLowerCase();
result = result.filter(
(model) =>
(model.model_name &&
model.model_name.toLowerCase().includes(searchTerm)) ||
(model.description &&
model.description.toLowerCase().includes(searchTerm)) ||
(model.tags && model.tags.toLowerCase().includes(searchTerm)) ||
(model.vendor_name &&
model.vendor_name.toLowerCase().includes(searchTerm)),
typeof model.model_name === 'string' &&
model.model_name.toLowerCase().includes(searchTerm),
);
}
+1 -1
View File
@@ -29,6 +29,7 @@ import {
import { writeClipboardText } from '../../helpers/clipboard';
import TableEmpty from '../../components/common/table/TableEmpty';
import React, { useState, useRef, useEffect, useContext } from 'react';
import Table from '../../components/ui/CenterActionTable';
import {
Alert,
Button,
@@ -38,7 +39,6 @@ import {
Input,
Spin,
Switch,
Table,
Tag,
Tooltip,
} from 'antd';
@@ -23,7 +23,8 @@ import {
} from '@/components/common/icons/ActionIcons';
import TableEmpty from '../../../components/common/table/TableEmpty';
import React, { useMemo } from 'react';
import { Card, Table, Tag } from 'antd';
import Table from '../../../components/ui/CenterActionTable';
import { Card, Tag } from 'antd';
import { Clock } from 'lucide-react';
import { Button, Pagination } from '@/components/ui';
import { useTaskLogsData } from '../../../hooks/task-logs/useTaskLogsData';
+2 -10
View File
@@ -23,16 +23,8 @@ import {
RefreshCw as ActionRefreshCw,
} from '@/components/common/icons/ActionIcons';
import React, { useState, useEffect, useCallback, useMemo } from 'react';
import {
Empty,
Spin,
Table,
Button,
Modal,
Tooltip,
Statistic,
theme,
} from 'antd';
import Table from '../../components/ui/CenterActionTable';
import { Empty, Spin, Button, Modal, Tooltip, Statistic, theme } from 'antd';
import { Server, ChevronRight, Clock } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { API, showError } from '../../helpers';
+3 -7
View File
@@ -6,7 +6,7 @@
.usage-record-page {
--ur-card-border: #e6e9ef;
--ur-card-shadow: 0 4px 24px rgba(15, 23, 42, 0.02);
--ur-filter-bg: linear-gradient(90deg, #fffdf8 0%, #ffffff 55%);
--ur-filter-bg: var(--surface-card);
--ur-label: #6b7789;
--ur-head-bg: #f8f9fc;
--ur-head-text: #687589;
@@ -29,13 +29,9 @@
html.dark .usage-record-page {
--ur-card-border: var(--border-subtle);
--ur-card-shadow: none;
--ur-filter-bg: linear-gradient(
90deg,
color-mix(in srgb, var(--ui-color-primary) 6%, var(--surface-card)) 0%,
var(--surface-card) 55%
);
--ur-filter-bg: var(--surface-card);
--ur-label: var(--text-secondary);
--ur-head-bg: var(--ui-color-fill-0);
--ur-head-bg: color-mix(in srgb, var(--text-primary) 4%, var(--surface-card));
--ur-head-text: var(--text-secondary);
--ur-row-split: var(--border-subtle);
--ur-time-date: var(--text-secondary);
+109 -122
View File
@@ -21,6 +21,7 @@ import {
Button,
Card,
Checkbox,
DatePicker,
Form,
Input,
Modal,
@@ -29,8 +30,8 @@ import {
TextArea,
Typography,
} from '@/components/ui';
import { articleErrors } from './insightsModel';
import { articleContentInfo, sanitizeArticleHtml } from './insightsContent';
import { articleErrors, RELATED_LIMIT } from './insightsModel';
import { articleHeadings, sanitizeArticleHtml } from './insightsContent';
import ArticleRichEditor from './ArticleRichEditor';
export default function ArticleEditor({ initial, insights, onApply, onClose }) {
@@ -52,8 +53,7 @@ export default function ArticleEditor({ initial, insights, onApply, onClose }) {
setErrors((previous) => ({ ...previous, [name]: '' }));
};
const close = () => {
if (JSON.stringify(draft) === JSON.stringify(initial) && !processingImage)
onClose();
if (!hasDraftChanges && !processingImage) onClose();
else
Modal.confirm({
title: '放弃本次编辑?',
@@ -66,7 +66,7 @@ export default function ArticleEditor({ initial, insights, onApply, onClose }) {
const apply = () => {
if (processingImage) return;
const article = { ...draft, body: sanitizeArticleHtml(draft.body) };
for (const key of ['title', 'summary', 'subtitle', 'tag'])
for (const key of ['title', 'summary', 'tag'])
article[key] = article[key].trim();
const nextErrors = articleErrors(article, insights);
setErrors(nextErrors);
@@ -82,7 +82,10 @@ export default function ArticleEditor({ initial, insights, onApply, onClose }) {
{children}
</Form.Slot>
);
const info = articleContentInfo(draft.body);
const categoryName = (id) =>
insights.categories.find((c) => c.id === id)?.name ?? '';
const headings = articleHeadings(draft.body);
const candidates = insights.articles.filter((a) => a.id !== draft.id);
return (
<SideSheet
visible
@@ -109,6 +112,59 @@ export default function ArticleEditor({ initial, insights, onApply, onClose }) {
>
基础信息
</Typography.Title>
<div className='grid grid-cols-1 gap-x-6 md:grid-cols-2'>
{field(
'category',
'所属分类',
<Select
aria-label='所属分类'
validateStatus={errors.category ? 'error' : 'default'}
aria-invalid={Boolean(errors.category)}
value={
insights.categories.some((c) => c.id === draft.category)
? draft.category
: undefined
}
placeholder='请选择文章分类'
style={{ width: '100%' }}
optionList={insights.categories.map((c) => ({
label: c.name,
value: c.id,
}))}
onChange={(value) => change('category', value)}
/>,
true,
)}
{field(
'date',
'发布日期',
<DatePicker
aria-label='发布日期'
status={errors.date ? 'error' : undefined}
aria-invalid={Boolean(errors.date)}
type='date'
format='YYYY-MM-DD'
placeholder='请选择发布日期'
style={{ width: '100%' }}
value={draft.date || undefined}
onChange={(value) => change('date', value)}
/>,
true,
)}
{field(
'tag',
'角标标签',
<Input
aria-label='角标标签'
validateStatus={errors.tag ? 'error' : 'default'}
aria-invalid={Boolean(errors.tag)}
value={draft.tag}
maxLength={12}
placeholder='例如 NEW、推荐,留空不展示'
onChange={(value) => change('tag', value)}
/>,
)}
</div>
{field(
'title',
'文章标题',
@@ -125,83 +181,21 @@ export default function ArticleEditor({ initial, insights, onApply, onClose }) {
/>,
true,
)}
<div className='grid grid-cols-1 gap-x-6 md:grid-cols-2'>
{field(
'category',
'所属分类',
<Select
aria-label='所属分类'
validateStatus={errors.category ? 'error' : 'default'}
aria-invalid={Boolean(errors.category)}
value={draft.category || undefined}
placeholder='请选择文章分类'
style={{ width: '100%' }}
optionList={[
{ label: '全部内容', value: 'all' },
...insights.categories.map((c) => ({
label: c.name,
value: c.id,
})),
]}
onChange={(value) => change('category', value)}
/>,
true,
)}
{field(
'date',
'发布日期',
<Input
aria-label='发布日期'
validateStatus={errors.date ? 'error' : 'default'}
aria-invalid={Boolean(errors.date)}
type='date'
value={draft.date}
onChange={(value) => change('date', value)}
/>,
true,
)}
</div>
{field(
'subtitle',
'详情副标题',
<Input
aria-label='详情副标题'
validateStatus={errors.subtitle ? 'error' : 'default'}
aria-invalid={Boolean(errors.subtitle)}
value={draft.subtitle}
maxLength={160}
placeholder='留空时使用卡片摘要作为副标题'
onChange={(value) => change('subtitle', value)}
/>,
)}
{field(
'summary',
'卡片摘要',
'文章描述',
<TextArea
aria-label='卡片摘要'
aria-label='文章描述'
validateStatus={errors.summary ? 'error' : 'default'}
aria-invalid={Boolean(errors.summary)}
value={draft.summary}
placeholder='请输入卡片摘要'
placeholder='请输入文章描述,用于列表卡片摘要与详情页标题下方'
maxCount={200}
rows={3}
onChange={(value) => change('summary', value)}
/>,
true,
)}
{field(
'tag',
'角标标签',
<Input
aria-label='角标标签'
validateStatus={errors.tag ? 'error' : 'default'}
aria-invalid={Boolean(errors.tag)}
value={draft.tag}
maxLength={12}
placeholder='例如 NEW、推荐'
onChange={(value) => change('tag', value)}
/>,
)}
<Typography.Title
heading={5}
className='website-insights-section-title website-insights-detail-title'
@@ -222,58 +216,46 @@ export default function ArticleEditor({ initial, insights, onApply, onClose }) {
</div>
<aside className='website-insights-aside'>
<Card title='文章目录'>
<Checkbox
checked={draft.toc}
onChange={(e) => change('toc', e.target.checked)}
>
根据正文标题自动生成
</Checkbox>
<div className='website-insights-toc'>
{!draft.toc ? (
<Typography.Text type='tertiary'>
已关闭目录展示
</Typography.Text>
) : info.headings.length ? (
info.headings.map((h, i) => (
<div
key={i}
style={{ paddingLeft: h.level === 'H3' ? 12 : 0 }}
>
{h.text}
</div>
))
) : (
<Typography.Text type='tertiary'>
添加 H2 / H3 标题后自动生成目录
</Typography.Text>
)}
</div>
<Typography.Text type='tertiary'>
根据正文 H2 标题自动生成,官网点击目录定位到对应标题。
</Typography.Text>
<ol className='website-insights-toc'>
{headings.map((text, i) => (
<li key={i}>{text}</li>
))}
</ol>
{!headings.length && (
<Typography.Text type='tertiary'>
正文暂无 H2 标题,官网将不展示目录项
</Typography.Text>
)}
</Card>
<Card title={`相关推荐(${draft.related.length} / 3)`}>
<Card
title={`相关推荐(${draft.related.length} / ${RELATED_LIMIT})`}
>
<div className='website-insights-related'>
{insights.articles
.filter((a) => a.id !== draft.id)
.map((a) => (
<Checkbox
key={a.id}
checked={draft.related.includes(a.id)}
disabled={
!draft.related.includes(a.id) && draft.related.length >= 3
}
onChange={(e) =>
change(
'related',
e.target.checked
? [...draft.related, a.id]
: draft.related.filter((id) => id !== a.id),
)
}
>
{a.title}
</Checkbox>
))}
{candidates.map((a) => (
<Checkbox
key={a.id}
checked={draft.related.includes(a.id)}
disabled={
!draft.related.includes(a.id) &&
draft.related.length >= RELATED_LIMIT
}
onChange={(e) =>
change(
'related',
e.target.checked
? [...draft.related, a.id]
: draft.related.filter((id) => id !== a.id),
)
}
>
{`${categoryName(a.category)} · ${a.title}`}
</Checkbox>
))}
</div>
{!insights.articles.some((a) => a.id !== draft.id) && (
{!candidates.length && (
<Typography.Text type='tertiary'>
暂无可推荐的其他文章
</Typography.Text>
@@ -284,10 +266,15 @@ export default function ArticleEditor({ initial, insights, onApply, onClose }) {
</Card>
<Card title='展示说明'>
<Typography.Paragraph type='tertiary'>
列表页:标题、摘要、分类、日期、角标。
列表页:分类、发布日期、角标、标题、文章描述,按列表顺序展示。
</Typography.Paragraph>
<Typography.Paragraph type='tertiary'>
详情页:分类、标题、文章描述、正文、目录(正文
H2),不展示发布日期。
</Typography.Paragraph>
<Typography.Text type='tertiary'>
详情页:副标题(留空时使用摘要)、正文、目录和推荐。
相关推荐按勾选顺序展示,最多 {RELATED_LIMIT}{' '}
篇;不勾选则官网不展示相关推荐。
</Typography.Text>
</Card>
</aside>
+75 -31
View File
@@ -40,6 +40,7 @@ import {
categoryError,
createContentId,
filterArticles,
moveArticle,
newArticle,
removeArticle,
} from './insightsModel';
@@ -56,6 +57,9 @@ export default function InsightsPanel({ value, onChange, disabled, error }) {
? category
: 'all';
const rows = filterArticles(value, keyword, activeCategory);
// Reordering only makes sense on the full list, which is the official site order.
const sortable = activeCategory === 'all' && !keyword.trim();
const hasCategories = value.categories.length > 0;
const count = (id) =>
id === 'all'
? value.articles.length
@@ -91,7 +95,7 @@ export default function InsightsPanel({ value, onChange, disabled, error }) {
};
const deleteCategory = (item) => {
if (count(item.id)) {
showError('该分类下仍有文章,请先调整文章所属分类,再删除分类。');
showError('该分类下仍有文章,请先将文章调整到其他分类,再删除分类。');
return;
}
Modal.confirm({
@@ -158,37 +162,68 @@ export default function InsightsPanel({ value, onChange, disabled, error }) {
title: '所属分类',
dataIndex: 'category',
width: 140,
render: (id) =>
id === 'all'
? '全部内容'
: value.categories.find((c) => c.id === id)?.name || '未分类',
render: (id) => value.categories.find((c) => c.id === id)?.name,
},
{
title: '角标',
dataIndex: 'tag',
width: 100,
render: (tag) => tag || '-',
},
{ title: '发布日期', dataIndex: 'date', width: 140 },
{
title: '操作',
key: 'actions',
width: 160,
render: (_, item) => (
<div className='website-insights-row-actions'>
<Button
type='link'
size='small'
disabled={disabled}
onClick={() => setArticle({ ...item, related: [...item.related] })}
>
编辑
</Button>
<Button
type='link'
size='small'
danger
disabled={disabled}
onClick={() => deleteArticle(item)}
>
删除
</Button>
</div>
),
width: 220,
render: (_, item) => {
const index = value.articles.findIndex((a) => a.id === item.id);
const move = (offset) => onChange(moveArticle(value, item.id, offset));
return (
<div className='website-insights-row-actions'>
<Button
type='link'
size='small'
disabled={disabled}
onClick={() =>
setArticle({ ...item, related: [...item.related] })
}
>
编辑
</Button>
<Button
type='link'
size='small'
aria-label={`上移${item.title}`}
title={sortable ? undefined : '请在全部分类且无搜索时调整顺序'}
disabled={disabled || !sortable || index <= 0}
onClick={() => move(-1)}
>
上移
</Button>
<Button
type='link'
size='small'
aria-label={`下移${item.title}`}
title={sortable ? undefined : '请在全部分类且无搜索时调整顺序'}
disabled={
disabled || !sortable || index >= value.articles.length - 1
}
onClick={() => move(1)}
>
下移
</Button>
<Button
type='link'
size='small'
danger
disabled={disabled}
onClick={() => deleteArticle(item)}
>
删除
</Button>
</div>
);
},
},
];
return (
@@ -304,7 +339,8 @@ export default function InsightsPanel({ value, onChange, disabled, error }) {
<Button
icon={<IconPlus />}
theme='solid'
disabled={disabled}
disabled={disabled || !hasCategories}
title={hasCategories ? undefined : '请先新增内容分类'}
onClick={() => {
setArticle(newArticle(activeCategory));
}}
@@ -313,11 +349,19 @@ export default function InsightsPanel({ value, onChange, disabled, error }) {
</Button>
</div>
</TableToolbar>
{!hasCategories && (
<Typography.Paragraph type='tertiary'>
请先新增内容分类,文章需归属一个分类后才能在官网展示。
</Typography.Paragraph>
)}
<Typography.Paragraph type='tertiary'>
列表顺序即官网展示顺序,新增文章默认排在最前,可在“全部分类”下上移或下移调整。
</Typography.Paragraph>
<CardTable
rowKey='id'
columns={columns}
dataSource={rows}
scroll={{ x: 860 }}
scroll={{ x: 1040 }}
empty={<TableEmpty />}
hidePagination
/>
@@ -337,12 +381,12 @@ export default function InsightsPanel({ value, onChange, disabled, error }) {
}
>
<Typography.Paragraph type='tertiary'>
“全部内容”为默认分类,也汇总展示全部文章;已有文章的自定义分类需先迁移文章再删除。
“全部内容”为官网默认筛选项,汇总展示全部文章,不能作为文章分类;已有文章的分类需先将文章调整到其他分类再删除。
</Typography.Paragraph>
<div className='website-insights-manage-row'>
<span>全部内容</span>
<Typography.Text type='tertiary'>
默认分类(不可删除)
默认筛选项(不可删除)
</Typography.Text>
</div>
{value.categories.map((c) => (
+21 -14
View File
@@ -64,30 +64,37 @@ ArticleEditor.jsx 承载文章新增/编辑抽屉,ArticleRichEditor.jsx 复用
工具栏采用独立的中性样式,避免项目 primary 按钮全局渐变影响编辑工具和选中状态。
默认保留公司动态、产品更新、行业洞察三个分类,文章为空,不向官网注入原型示例文章。
单篇文章结构:
字段对齐官网 weelink-open 的 `/insights` 列表页与 `/insight-detail?id=` 详情页,单篇文章结构:
```json
{
"id": "由前端生成的 UUID,后续可替换为后端 ID",
"id": "由前端生成的 UUID,官网详情页 ?id= 使用",
"category": "分类 id,必须是 categories 中的分类",
"date": "2026-11-16",
"title": "文章标题",
"category": "all",
"date": "2026-10-31",
"subtitle": "详情副标题,空值时由官网使用 summary",
"summary": "卡片摘要",
"summary": "文章描述:列表卡片摘要与详情页标题下方描述共用",
"tag": "NEW",
"body": "<h2>章节标题</h2><p>文章正文</p>",
"toc": true,
"related": []
}
```
必填:title(最多 80 字)、category、date、summary(最多 200 字)、body。
subtitle 最多 160 字,tag 最多 12 字,推荐最多 3 篇且不能选择自己。
正文 H2/H3 自动生成目录预览;toc 为是否展示目录,官网可从 body 提取标题。
“全部内容”是内置默认归属(category 为 all),也汇总展示所有分类的文章,不存入自定义 categories 数组。
新增文章默认归属当前分类,从全部内容新增时直接归属 all;自定义分类为空时也可新增文章。
分类名称最多 12 字,禁止空白、重名和系统保留名称;已有文章的自定义分类不能直接删除,可先迁移到全部内容。
删除文章同步清理其他文章的 related 引用。列表按发布日期倒序排列。
| 官网位置 | 使用字段 |
| -------------- | -------------------------------------------------------------------------------------------- |
| 列表页分类页签 | “全部内容” + `categories[].name`(按数组顺序) |
| 列表卡片 | 分类名称、`date`(官网格式化为 `YYYY.MM.DD`)、`tag`(为空不展示)、`title`、`summary`、`id` |
| 详情页头部 | 分类名称(标签与面包屑)、`title`、`summary` |
| 详情页正文 | `body` 富文本,官网渲染前需再次白名单清理 |
| 详情页目录 | 正文中的非空 H2,按出现顺序生成锚点,点击定位到对应标题 |
| 相关推荐 | `related` 按勾选顺序,最多 3 篇;为空时官网不展示该区块 |
必填:title(最多 80 字)、category、date、summary(最多 200 字)、body。tag 最多 12 字,推荐最多 3 篇且不能选择自己。
发布日期格式 `YYYY-MM-DD`,只用于列表卡片,详情页不展示;新增文章默认当天,不影响排序。
读取配置时只保留上述字段并去除首尾空白,不兼容其他历史字段。
“全部内容”仅是官网与后台的筛选项,不能作为文章分类。
没有任何分类时不能新增文章;已有文章的分类不能直接删除,需先将文章调整到其他分类。
文章数组顺序即官网展示顺序:新增文章排在最前,可在“全部分类”且无搜索时上移、下移。删除文章同步清理其他文章的 related 引用。
允许保存空文章列表,官网列表页显示“内容筹备中”空状态。
文章抽屉“保存”、分类编辑与文章删除只更新当前内存配置,不请求后端保存接口。
页面底部“保存”统一校验四个页签后,将整个配置序列化为 JSON 字符串调用 saveWebsiteSettings。
@@ -86,15 +86,13 @@
.website-insights-category,
.website-insights-toolbar,
.website-insights-manage-row,
.website-insights-editor-footer,
.website-rich-tools {
.website-insights-editor-footer {
display: flex;
align-items: center;
gap: 8px;
}
.website-insights-category-list,
.website-rich-tools,
.website-insights-editor-footer {
flex-wrap: wrap;
}
@@ -232,9 +230,13 @@
}
.website-insights-toc {
margin-top: 12px;
margin: 12px 0 0;
padding-left: 20px;
max-height: 240px;
overflow-y: auto;
line-height: 1.8;
overflow-wrap: anywhere;
list-style: decimal;
}
.website-insights-editor-footer {
+5 -8
View File
@@ -17,16 +17,13 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { sanitizeArticleHtml } from '../../components/common/ui/richTextContent.js';
import { countRichText } from '../../components/common/ui/richTextLength.js';
export { sanitizeArticleHtml };
export function articleContentInfo(html) {
// The website TOC is one level: every non-empty H2 in the body, in document order.
export function articleHeadings(html) {
const template = document.createElement('template');
template.innerHTML = sanitizeArticleHtml(html);
return {
count: countRichText(template.content.textContent),
headings: [...template.content.querySelectorAll('h2,h3')]
.map((h) => ({ level: h.tagName, text: h.textContent.trim() }))
.filter((h) => h.text),
};
return [...template.content.querySelectorAll('h2')]
.map((h) => h.textContent.trim())
.filter(Boolean);
}
+56 -39
View File
@@ -53,19 +53,35 @@ export function categoryError(name, categories, id) {
return '';
}
export function newArticle(category = 'all') {
export const RELATED_LIMIT = 3;
const pad = (value) => String(value).padStart(2, '0');
// Publish date is a local calendar day "YYYY-MM-DD" shown on the website list cards.
export function isValidPublishDate(value) {
const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
if (!match) return false;
const [year, month, day] = match.slice(1).map(Number);
const date = new Date(year, month - 1, day);
return (
date.getFullYear() === year &&
date.getMonth() === month - 1 &&
date.getDate() === day
);
}
// Website list card: category / date / tag / title / summary.
// Website detail page: category / title / summary / rich body (H2 table of contents) / related.
export function newArticle(category = '') {
const now = new Date();
const date = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`;
return {
id: '',
title: '',
category,
date,
subtitle: '',
category: category === 'all' ? '' : category,
date: `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`,
summary: '',
tag: '',
body: '',
toc: true,
related: [],
};
}
@@ -74,8 +90,7 @@ export function articleErrors(article, insights) {
const errors = {};
for (const [key, label, limit, required] of [
['title', '文章标题', 80, true],
['summary', '卡片摘要', 200, true],
['subtitle', '详情副标题', 160, false],
['summary', '文章描述', 200, true],
['tag', '角标标签', 12, false],
]) {
const text = String(article[key] ?? '').trim();
@@ -83,17 +98,11 @@ export function articleErrors(article, insights) {
else if (text.length > limit)
errors[key] = `${label}不能超过 ${limit} 个字符`;
}
if (
article.category !== 'all' &&
!insights.categories.some((c) => c.id === article.category)
)
// Every article needs a real category: the site renders it as the tag, breadcrumb and list filter.
if (!insights.categories.some((c) => c.id === article.category))
errors.category = '请选择所属分类';
const date = String(article.date ?? '');
if (
!/^\d{4}-\d{2}-\d{2}$/.test(date) ||
!Number.isFinite(Date.parse(date)) ||
new Date(date).toISOString().slice(0, 10) !== date
)
if (!isValidPublishDate(date))
errors.date = date ? '请选择有效的发布日期' : '请选择发布日期';
const body = String(article.body ?? '');
if (
@@ -114,40 +123,40 @@ export function articleErrors(article, insights) {
errors.body = '正文包含不支持的内容,请清除格式后重试';
if (
!Array.isArray(article.related) ||
article.related.length > 3 ||
article.related.length > RELATED_LIMIT ||
new Set(article.related).size !== article.related.length ||
article.related.some(
(id) => id === article.id || !insights.articles.some((a) => a.id === id),
)
)
errors.related = '最多选择 3 篇有效的其他文章';
errors.related = `最多选择 ${RELATED_LIMIT} 篇有效的其他文章`;
return errors;
}
const ARTICLE_TEXT_FIELDS = [
'id',
'title',
'category',
'date',
'summary',
'tag',
'body',
];
// Articles keep only the website schema with trimmed text; other insights keys are preserved
// per the page-config contract (unknown fields survive a save).
export function normalizeInsights(value) {
const data = value ?? emptyInsights();
return {
...data,
categories: (data.categories || []).map((c) => ({
...c,
id: String(c.id),
name: String(c.name ?? '').trim(),
})),
articles: (data.articles || []).map((a) => ({
...a,
...Object.fromEntries(
[
'id',
'title',
'category',
'date',
'subtitle',
'summary',
'tag',
'body',
].map((key) => [key, String(a[key] ?? '').trim()]),
ARTICLE_TEXT_FIELDS.map((key) => [key, String(a[key] ?? '').trim()]),
),
toc: a.toc !== false,
related: [...(a.related || [])],
})),
};
@@ -189,13 +198,21 @@ export function removeArticle(insights, id) {
};
}
// Array order is the display order on the official site.
export function filterArticles(insights, keyword, category) {
const query = keyword.trim().toLocaleLowerCase();
return insights.articles
.filter(
(a) =>
(category === 'all' || a.category === category) &&
`${a.title} ${a.summary}`.toLocaleLowerCase().includes(query),
)
.sort((a, b) => b.date.localeCompare(a.date));
return insights.articles.filter(
(a) =>
(category === 'all' || a.category === category) &&
`${a.title} ${a.summary}`.toLocaleLowerCase().includes(query),
);
}
export function moveArticle(insights, id, offset) {
const from = insights.articles.findIndex((a) => a.id === id);
const to = from + offset;
if (from < 0 || to < 0 || to >= insights.articles.length) return insights;
const articles = [...insights.articles];
[articles[from], articles[to]] = [articles[to], articles[from]];
return { ...insights, articles };
}
+2 -6
View File
@@ -168,15 +168,11 @@ export function validateField(key, rawValue) {
return '';
}
// An empty article list is valid: the official list page shows its "内容筹备中" empty state.
export function validateSettings(values) {
return Object.fromEntries(
[...new Set(TABS.flatMap((tab) => tab.fields))]
.map((key) => [
key,
key === 'insights' && !values.insights?.articles?.length
? '请完善动态与洞察的配置'
: validateField(key, values[key]),
])
.map((key) => [key, validateField(key, values[key])])
.filter(([, error]) => error),
);
}
+1
View File
@@ -48,6 +48,7 @@ const ui = await loadFrontendModule(
'../../hooks/common/useIsMobile': { useIsMobile: () => false },
'../console/ConsoleContext': context,
'../console/consoleTableAdapter': {},
'./CenterActionTable': Ant.Table,
'../console/ConsolePrimitives': {},
},
);
+114
View File
@@ -0,0 +1,114 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import assert from 'node:assert/strict';
import test from 'node:test';
import i18next from 'i18next';
import {
isActionColumn,
isCenterTableScope,
prepareCenterColumns,
} from '../../src/components/ui/centerTablePolicy.js';
test('center operation policy includes system settings and excludes unrelated routes', () => {
for (const path of [
'/user-center/usage-record',
'/org/tokens',
'/console/user',
'/console/setting',
'/console/setting/theme',
])
assert.equal(isCenterTableScope(path), true);
for (const path of ['/market', '/organization'])
assert.equal(isCenterTableScope(path), false);
});
test('pins operations and detail callbacks without changing data, renderers or input columns', () => {
const render = () => null;
const columns = [
{ key: 'name', width: 240, fixed: 'left' },
{ title: '类型', dataIndex: 'action', render },
{ title: '操作', key: 'actions', width: 160, render },
];
const result = prepareCenterColumns(columns, 1200);
assert.deepEqual(result[0], columns[0]);
assert.deepEqual(result[1], columns[1]);
assert.equal(result[2].fixed, 'right');
assert.equal(result[2].render, render);
assert.equal(columns[2].fixed, undefined);
assert.equal(isActionColumn(columns[1]), false);
assert.equal(
isActionColumn({ key: 'fail_reason', title: '详情', render }),
true,
);
assert.equal(isActionColumn({ title: '详情', dataIndex: 'detail' }), false);
assert.equal(
isActionColumn({ title: '操作人', dataIndex: 'operator' }),
false,
);
});
test('narrow containers release colliding left columns and bound the operation area', () => {
const columns = [
{ key: 'name', width: 240, fixed: 'left' },
{ title: '说明', width: 300, fixed: 'right' },
{ key: 'result', width: 300, render: () => null },
];
const result = prepareCenterColumns(columns, 300);
assert.equal(result[0].fixed, 'right');
assert.equal(result[1].fixed, 'right');
assert.equal(result[2].fixed, 'right');
assert.equal(result[2].width, 300);
assert.equal(columns[0].fixed, 'left');
});
test('renames interactive detail headers and sizes action columns from controls', () => {
const renderDetail = function renderDetail() {
return { onClick: true, Button: true };
};
const result = prepareCenterColumns(
[
{ key: 'name', width: 180 },
{ title: '详情', dataIndex: 'detail', render: renderDetail },
],
900,
);
assert.equal(result[1].title, '操作');
assert.equal(result[1].fixed, 'right');
assert.ok(result[1].width >= 120);
});
test('supports grouped headers and keeps ordinary tables intact', () => {
const render = () => null;
const grouped = [{ title: '记录', children: [{ title: '操作', render }] }];
assert.equal(
prepareCenterColumns(grouped, 800)[0].children[0].fixed,
'right',
);
const ordinary = [{ title: '金额', dataIndex: 'amount' }];
assert.deepEqual(prepareCenterColumns(ordinary, 300), ordinary);
});
test('recognizes translated operation headers without requiring a key', async () => {
await i18next.init({
lng: 'en',
resources: { en: { translation: { 操作: 'Actions' } } },
});
assert.equal(isActionColumn({ title: 'Actions', render: () => null }), true);
});
+103
View File
@@ -0,0 +1,103 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import assert from 'node:assert/strict';
import test from 'node:test';
import React from 'react';
import { loadFrontendModule } from './helpers/frontendModule.js';
async function search(query, filters = {}) {
const models = [
{
model_name: 'GPT-4o',
vendor_name: 'OpenAI',
description: '聊天模型',
tags: '热门',
enable_groups: ['default'],
},
{
model_name: 'Claude-Sonnet',
vendor_name: 'GPT',
description: 'GPT-4o',
tags: 'GPT',
enable_groups: ['vip'],
},
{
model_name: '中文模型-Pro',
vendor_name: 'other',
enable_groups: ['default'],
},
{ model_name: null, description: 'GPT', enable_groups: [] },
];
let index = 0;
const state = {
0: query,
7: filters.group || 'all',
10: filters.vendor || 'all',
17: models,
};
const react = {
...React,
useState: (initial) => [
Object.hasOwn(state, index) ? state[index++] : (++index, initial),
() => {},
],
useMemo: (fn) => fn(),
useEffect: () => {},
useRef: (initial) => ({ current: initial }),
useContext: () => [{}],
};
const { useModelPricingData: runHook } = await loadFrontendModule(
new URL(
'../../src/hooks/model-pricing/useModelPricingData.jsx',
import.meta.url,
),
{
react,
'../common/useEffectEvent': { useEffectEvent: (callback) => callback },
'react-i18next': { useTranslation: () => ({ t: (key) => key }) },
'../../helpers': {
API: { get: assert.fail },
copy: assert.fail,
getCurrencySymbol: () => '$',
showError: assert.fail,
showInfo: assert.fail,
showSuccess: assert.fail,
},
'@/components/ui': { Modal: {} },
'../../context/User': { UserContext: {} },
'../../context/Status': { StatusContext: {} },
},
);
return runHook().filteredModels.map((model) => model.model_name);
}
test('model search matches names only, ignoring case and surrounding spaces', async () => {
assert.deepEqual(await search(' gPt-4 '), ['GPT-4o']);
assert.deepEqual(await search('OpenAI'), []);
assert.deepEqual(await search('热门'), []);
assert.deepEqual(await search('模型'), ['中文模型-Pro']);
});
test('blank and missing names are safe; search still intersects existing filters', async () => {
assert.equal((await search(' ')).length, 4);
assert.deepEqual(await search('gpt', { vendor: 'GPT' }), []);
assert.deepEqual(await search('gpt', { group: 'vip' }), []);
assert.deepEqual(await search('son', { group: 'vip' }), ['Claude-Sonnet']);
});
+1
View File
@@ -163,6 +163,7 @@ async function modelTestFixture() {
),
Typography: { Text: 'Text' },
},
'../../../ui/CenterActionTable': 'Table',
'lucide-react': { Search: 'Search' },
'./model-test-modal.css': {},
'../../../../helpers': {},
+1
View File
@@ -416,6 +416,7 @@ const modules = {
'./form': {},
'./chat': {},
'../console/ConsoleContext': { useConsolePage: () => null },
'./CenterActionTable': Ant.Table,
'../console/ConsolePrimitives': {},
'../console/consoleTableAdapter': {},
};
+1
View File
@@ -51,6 +51,7 @@ const mocks = {
theme: { useToken: () => ({ token }) },
},
'react-i18next': {},
'../ui/CenterActionTable': 'table',
'../common/table/TableEmpty': () => null,
'./ConsoleContext': { useConsolePage: () => ({ page: { key: pageKey } }) },
};
+12 -10
View File
@@ -53,19 +53,24 @@ function validValues() {
};
}
test('save validation requires an article even when default categories exist', () => {
test('save validation allows an empty article list but rejects incomplete articles', () => {
assert.deepEqual(model.validateSettings(validValues()), {});
// The official list page has a "内容筹备中" empty state, so no article is required.
for (const insights of [
model.emptySettings().insights,
{ categories: [], articles: [] },
]) {
assert.deepEqual(model.validateSettings({ ...validValues(), insights }), {
insights: '请完善动态与洞察的配置',
});
assert.deepEqual(
model.validateSettings({ ...validValues(), insights }),
{},
);
}
const invalid = validValues();
invalid.insights.articles[0].body = '';
assert.ok(model.validateSettings(invalid).insights);
const uncategorized = validValues();
uncategorized.insights.articles[0].category = 'all';
assert.ok(model.validateSettings(uncategorized).insights);
});
test('saving incomplete insights cannot send uploads or a configuration write', async () => {
@@ -80,13 +85,10 @@ test('saving incomplete insights cannot send uploads or a configuration write',
'../../components/common/ui/richTextImages': richTextImages,
},
);
const incomplete = validValues();
incomplete.insights.articles[0].body = '';
await assert.rejects(
api.saveWebsiteSettings(
model.serializeSettings({
...validValues(),
insights: model.emptySettings().insights,
}),
),
api.saveWebsiteSettings(model.serializeSettings(incomplete)),
/请完整填写并检查官网设置/,
);
assert.deepEqual(requests, []);
+1
View File
@@ -40,6 +40,7 @@ test('settings tables share the log empty state while other console routes retai
react: React,
antd: Ant,
'react-i18next': { useTranslation: () => ({ t: (value) => value }) },
'../ui/CenterActionTable': Ant.Table,
'../common/table/TableEmpty': TableEmpty,
'./ConsoleContext': { useConsolePage: () => ({ page: { key } }) },
},
+1
View File
@@ -178,6 +178,7 @@ const { Table, Pagination } = loadUi({
'./form': {},
'./chat': {},
'../console/ConsoleContext': { useConsolePage: () => null },
'./CenterActionTable': Ant.Table,
'../console/ConsolePrimitives': {},
'../console/consoleTableAdapter': {},
});