Files
monkey-ai-web/src/pages/WebsiteSettings/insightsModel.js
T
zhanjunhao 2aa9d73325 chore(repo): 移除重复版权文件头并纳入共享单测
集中保留原版权声明,移除文件头检查和全局测试忽略规则。验证:全量单测、受影响用例复测及静态检查通过。
2026-11-20 11:23:49 +08:00

201 lines
6.4 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { articleImageSource } from '../../components/common/ui/richTextImages.js';
import {
ARTICLE_BODY_LIMIT,
countArticleHtml,
} from '../../components/common/ui/richTextLength.js';
export const emptyInsights = () => ({
categories: [
{ id: 'company', name: '公司动态' },
{ id: 'product', name: '产品更新' },
{ id: 'industry', name: '行业洞察' },
],
articles: [],
});
export function createContentId() {
// randomUUID requires HTTPS; getRandomValues also works on HTTP admin sites.
return (
globalThis.crypto.randomUUID?.() ??
Array.from(globalThis.crypto.getRandomValues(new Uint8Array(16)), (byte) =>
byte.toString(16).padStart(2, '0'),
).join('')
);
}
export function categoryError(name, categories, id) {
const value = String(name ?? '').trim();
if (!value) return '请输入分类名称';
if (value.length > 12) return '分类名称不能超过 12 个字符';
if (
['全部内容', '全部分类'].includes(value) ||
categories.some((c) => c.id !== id && c.name === value)
)
return '分类名称已存在,请使用其他名称';
return '';
}
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();
return {
id: '',
title: '',
category: category === 'all' ? '' : category,
date: `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`,
summary: '',
tag: '',
body: '',
related: [],
};
}
export function articleErrors(article, insights) {
const errors = {};
for (const [key, label, limit, required] of [
['title', '文章标题', 80, true],
['summary', '文章描述', 200, true],
['tag', '角标标签', 12, false],
]) {
const text = String(article[key] ?? '').trim();
if (required && !text) errors[key] = `请输入${label}`;
else if (text.length > limit)
errors[key] = `${label}不能超过 ${limit} 个字符`;
}
// 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 (!isValidPublishDate(date))
errors.date = date ? '请选择有效的发布日期' : '请选择发布日期';
const body = String(article.body ?? '');
if (
!body.replace(/<[^>]*>/g, '').replace(/&nbsp;|&#160;|\s/g, '') &&
!/<img\s/i.test(body)
)
errors.body = '请输入文章正文';
else if (countArticleHtml(body) > ARTICLE_BODY_LIMIT)
errors.body = `文章正文不能超过 ${ARTICLE_BODY_LIMIT} 字`;
if (
/<(?:script|style|iframe|object|svg|math)\b|\son\w+\s*=|(?:javascript|blob):/i.test(
body,
) ||
[...body.matchAll(/<img\b[^>]*\bsrc\s*=\s*["']([^"']*)["'][^>]*>/gi)].some(
(match) => !articleImageSource(match[1]),
)
)
errors.body = '正文包含不支持的内容,请清除格式后重试';
if (
!Array.isArray(article.related) ||
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 = `最多选择 ${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) => ({
id: String(c.id),
name: String(c.name ?? '').trim(),
})),
articles: (data.articles || []).map((a) => ({
...Object.fromEntries(
ARTICLE_TEXT_FIELDS.map((key) => [key, String(a[key] ?? '').trim()]),
),
related: [...(a.related || [])],
})),
};
}
export function validateInsights(value) {
if (!value) return '';
if (!Array.isArray(value.categories) || !Array.isArray(value.articles))
return '动态与洞察配置格式不正确';
const { categories, articles } = value;
if (
categories.some(
(c) =>
!c?.id || c.id === 'all' || categoryError(c.name, categories, c.id),
) ||
new Set(categories.map((c) => c.id)).size !== categories.length
)
return '请检查内容分类配置';
if (new Set(articles.map((a) => a?.id)).size !== articles.length)
return '文章标识不能重复';
for (const article of articles) {
if (!article?.id) return '文章标识不能为空';
const errors = articleErrors(article, value);
if (Object.keys(errors).length)
return `${article.title || '未命名文章'}:${Object.values(errors)[0]}`;
}
return '';
}
export function removeArticle(insights, id) {
return {
...insights,
articles: insights.articles
.filter((a) => a.id !== id)
.map((a) => ({
...a,
related: a.related.filter((other) => other !== 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),
);
}
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 };
}