Compare commits

...

84 Commits

Author SHA1 Message Date
66adf7f545 fix: 修正面包屑导航的显示逻辑
All checks were successful
deploy to server / build-and-deploy (push) Successful in 3m7s
- 竖屏下不显示面包屑导航
2025-12-27 17:06:03 +08:00
f87b977c87 fix: 调整面包屑导航的显示逻辑
- 在移动端隐藏面包屑导航
2025-12-27 17:05:41 +08:00
601c4abe53 fix: 修正计算器连接
All checks were successful
deploy to server / build-and-deploy (push) Successful in 3m3s
- 域名改为cal.jinshen.cn
2025-12-26 15:01:35 +08:00
b71ee98129 feat: 为Apple/PWA进行图标适配
All checks were successful
deploy to server / build-and-deploy (push) Successful in 3m23s
2025-12-24 14:56:28 +08:00
7611d4f079 fix: 调整页面渲染机制
All checks were successful
deploy to server / build-and-deploy (push) Successful in 3m9s
- 懒加载:部分页面添加懒加载机制,在用户访问时先加载静态资源在获取动态资源
- 骨架屏机制:各个页面的骨架屏渲染有el-skeleton自身模板控制
- 布局调整:部分页面布局调整
- i18n文本: 新增国际化文本redirecting
2025-12-19 13:28:54 +08:00
76fb3ddcb7 fix: 重定向页布局调整
All checks were successful
deploy to server / build-and-deploy (push) Successful in 2m54s
2025-12-19 13:26:48 +08:00
aa26731731 fix: 补全骨架屏渲染机制
- 补全各个页面的骨架屏渲染机制修改
2025-12-19 13:26:26 +08:00
f2533767d2 fix: 调整关于我们页面渲染机制
All checks were successful
deploy to server / build-and-deploy (push) Successful in 3m3s
- 骨架屏:骨架屏由el-skeleton模板控制
2025-12-19 12:53:01 +08:00
f1116491b6 fix: 调整解决方案列表渲染机制
- 骨架屏:解决方案列表页骨架屏渲染由el-skeleton模板控制
2025-12-19 12:48:36 +08:00
537a6b0bd6 fix: 调整产品列表页渲染机制
- 渲染机制:产品列表页懒加载采用el-skeleton自身模板机制
- 布局调整:调整产品页/骨架屏在竖屏下的布局
2025-12-19 12:00:42 +08:00
bcc08a53ea fix: 调整服务支持页面渲染模式
- 将条件渲染由div判断改为el-skeleton template
2025-12-19 11:38:33 +08:00
fa1a22b286 feat: 服务支持页懒加载
- 骨架屏调整:服务支持页骨架屏布局调整
- 懒加载:服务支持页添加懒加载机制
2025-12-19 11:17:32 +08:00
8c720b7ac3 fix: 修正查询/搜索无法完全显示的问题
All checks were successful
deploy to server / build-and-deploy (push) Successful in 3m7s
- 扩大查询/搜索的最大条目数
2025-12-18 15:05:57 +08:00
33c0b9cc43 fix: 修正搜索条目无法完全显示的问题
- 为查询/搜索添加更大的limit
2025-12-18 15:05:17 +08:00
fcaf595b73 feat: 添加ICP跳转链接
All checks were successful
deploy to server / build-and-deploy (push) Successful in 3m13s
2025-12-13 16:08:38 +08:00
ef20832761 feat: 页脚添加ICP跳转链接
All checks were successful
deploy to server / build-and-deploy (push) Successful in 3m11s
- ICP跳转: 点击备案号跳转到工信部网站
2025-12-13 16:07:49 +08:00
03a692afb5 feat: 页面描述 & 停产产品标示
All checks were successful
deploy to server / build-and-deploy (push) Successful in 2m59s
- 页面描述:产品列表与解决方案列表添加页面描述
- 停产标示:对于已停产产品,在产品详情页添加已停产标示
- 视图变更:产品视图添加Status字段,用于标示已停产产品
- 文案变更与补全:调整部分页面UI文案,并补全各个语言的新增文案
2025-12-10 14:10:03 +08:00
7b21def74f feat: 补全i18n翻译
All checks were successful
deploy to server / build-and-deploy (push) Successful in 2m59s
- 翻译补全: 补全英语、西班牙语、俄语的翻译
2025-12-10 14:06:58 +08:00
783d482e0a feat: 产品/解决方案列表页描述
- 页面描述:为产品列表与解决方案列表添加页面描述
- 停产提示:在产品列表中提示停产产品使用搜索功能
2025-12-10 14:00:05 +08:00
62ec215340 feat: 产品视图模型添加状态
- 产品状态:从Directus Schema获取Product的Status字段
- 视图字段:添加Status字段用于标示产品状态
- 测试方法:为Status字段添加单元测试
2025-12-10 13:35:00 +08:00
e02f975217 fix: 修正计算器跳转链接
All checks were successful
deploy to server / build-and-deploy (push) Successful in 3m9s
- 修正页面在竖屏状态下页面无法正确跳转到计算器页面的问题
2025-12-08 13:48:25 +08:00
5530776035 feat: 搜索页图片预览 & 文档列表显示文档类型
All checks were successful
deploy to server / build-and-deploy (push) Successful in 3m21s
- 缩略图预览: 搜索页栏目右侧添加缩略图预览功能
- 细分类型: 搜索页栏目添加细分类型展示:如产品(原纸分切机)
- 接口调整:
调整可选字段类型使其符合搜索引擎索引格式;将搜索条目中的type改为sectionType用于大类分类,并将type作为细分类型使用
- 文档类型: 文档页添加文档类型展示功能,当用户未指定文档类型时,在标题右侧显示文档类型
- 查询调整: 产品查询添加文档类型查询

ISSUE: Resolve #94
2025-12-05 17:23:34 +08:00
63cdff9c41 feat: 为文档库添加文档类型显示功能
All checks were successful
deploy to server / build-and-deploy (push) Successful in 3m10s
- 功能添加:在文档列表中,当未指定文档类型时,在标题右侧显示文档类型
- 查询更改:产品查询添加文档类型查询方法
- mapper更改:productDocumentView添加文档类型
2025-12-05 17:18:48 +08:00
f1398a5545 feat: 为搜索条目添加细分类型
- 类型细分:有原先的四大分类添加细分类型,例如产品(原纸分切机)
- 接口调整:原先的type分类改为sectionType并将type作为细分类型使用
2025-12-05 16:49:09 +08:00
36d24a4740 fix: 可选字段处理
- 为搜索条目中的可选字段进行判断并处理
2025-12-05 16:25:57 +08:00
c9b5b1fad9 feat: 为搜索页栏目添加图片缩略图功能
- 图片预览:产品与解决方案栏目添加缩略图功能
- 组件提取:在搜索结果页,将单个搜索结果单独提取为组件SearchResultCard
2025-12-05 14:56:24 +08:00
246a0b9d4f refactor(mapper): 为Server端的Mapper添加空值处理与类型控制逻辑
All checks were successful
deploy to server / build-and-deploy (push) Successful in 2m53s
- 空值处理与类型控制:为相关关系型字段的数据处理添加空值处理与类型控制
- 目录结构调整:分离Product/ProductList与Solution/SolutionList
- 修复bug:修复产品页与解决方案页无法正常触发404逻辑的问题
2025-12-04 17:57:07 +08:00
c3ac7c0985 fix: 修正产品/解决方案在归档后无法正常触发404 UI的问题
All checks were successful
deploy to server / build-and-deploy (push) Successful in 3m0s
2025-12-04 17:52:36 +08:00
63c3e2e364 refactor: 重构解决方案相关Mapper
- 空值处理与类型控制:为关系型字段添加空值处理与类型控制逻辑
- 目录结构调整:分离SolutionList与Solution相关的Mapper为不同的文件
2025-12-04 17:40:04 +08:00
1245df497b refactor: 重构产品相关Mapper
- 空值处理与类型控制:为相关关系型字段的数据处理添加空值处理与类型控制
- 调整目录结构:将文件目录按照实际查询划分为Product和ProductList两个文件
2025-12-04 17:38:43 +08:00
f081a3b33a feat(support): 为文档库/相关问题页面添加类型筛选功能
All checks were successful
deploy to server / build-and-deploy (push) Successful in 3m1s
- 功能添加:文档库/FAQ页添加类型筛选功能
- 类型同步:前端补全问题类型与文档类型的类型标注,与后端移至
- 查询变更:GraphQL查询增添文档/问题类型查询
- 组件分离:将原先文档库与FAQ页共用的ProductFilter分离为两个不同的组件:DocumentFilter与QuestionFilter
- i18n文本补全:为新增的相关文本补全国际化翻译
2025-12-03 18:00:03 +08:00
3c6bff4d31 chore: 删除无用组件
All checks were successful
deploy to server / build-and-deploy (push) Successful in 3m4s
- 文档页与问题页的筛选器分离为两个不同的组件,原先product-filter删除
2025-12-03 17:58:26 +08:00
5011448902 chore: 补全i18n文本
All checks were successful
deploy to server / build-and-deploy (push) Successful in 2m55s
- 补全俄语与西班牙语的i18n翻译
2025-12-03 17:53:18 +08:00
53f3e99d90 feat: 文档库页面添加文档类型筛选功能
- 功能添加:添加按照文档类型筛选文档的功能
- 组件更改:将筛选器由product-filter改为document-filter
2025-12-03 17:47:57 +08:00
815df40745 style: 删除无用class 2025-12-03 17:33:28 +08:00
c27337a145 feat: 文档库查询添加文档类型字段
- graphQL查询修改:添加type字段查询
- 视图模型字段更新:添加DocumentTypeView视图模型并为DocumentList类型添加type字段
- mapper更新: 添加DocumentType的转换方法
2025-12-03 17:30:16 +08:00
3fb721f278 test: 修改测试用例 2025-12-03 17:17:34 +08:00
a4dc28fc97 feat: 问题列表添加问题类型筛选功能
All checks were successful
deploy to server / build-and-deploy (push) Successful in 3m4s
- 功能添加:添加问题筛选功能
- 组件更改:将product-filter改为question-filter
- 文本添加:i18n文本添加
2025-12-03 16:59:11 +08:00
55a35b5498 chore: 调整字段名
- 将问题类型的类型名字段命名由type改为name
2025-12-03 16:56:57 +08:00
f4ec82a150 feat: 相关问题查询添加问题类型查询
- 查询语句更改:添加type字段
- mapper增添:添加type字段的mapper
- 视图模型更改:QuestionListView添加type字段
2025-12-03 15:53:20 +08:00
c82fea48b8 chore: 类型同步
- 后端CMS为问题/文档添加类型字段,前端同步更改
2025-12-03 14:26:20 +08:00
39a23fb382 feat: 计算器跳转链接修改
All checks were successful
deploy to server / build-and-deploy (push) Successful in 3m14s
- 将纸管计算工具跳转链接修改为正式版本版本
2025-12-02 17:03:47 +08:00
871b203a5e feat: 调整计算器URL
- 将计算器链接改为云服务器上的服务
2025-12-02 17:01:25 +08:00
b746247ccc feat(pagination): 问题库/文档库的分页功能实现
All checks were successful
deploy to server / build-and-deploy (push) Successful in 3m18s
- 为文档库/问题库实现分页功能,当前按照一页10个栏目分页
- 问题跳转时确保能够正常触发分页逻辑与聚焦逻辑
- 调整部分graphQL改动导致的类型匹配问题
2025-12-02 15:31:25 +08:00
97069815dc feat: 常见问题页面分页逻辑
All checks were successful
deploy to server / build-and-deploy (push) Successful in 3m31s
- el-pagination提供分页功能
- 从搜索页跳转到本路由时,自动跳转并聚焦指定问题
2025-12-02 15:29:06 +08:00
5194c72695 feat: 文档库分页功能
- el-pagination提供分页功能
2025-12-02 14:49:26 +08:00
dbe75ee080 fix: 调整变量类型
- 将id相关类型由number修改为string,符合graphQL规范
2025-12-02 14:33:10 +08:00
4471851c62 fix: 补全缺失的i18n文本
All checks were successful
deploy to server / build-and-deploy (push) Successful in 3m15s
- 搜索栏目与搜索卡片内部分文本补全
2025-11-24 14:23:13 +08:00
15a75f965b fix: 补全搜索页面缺失的翻译内容
All checks were successful
deploy to server / build-and-deploy (push) Successful in 3m13s
- 栏目标题、搜索卡片类型翻译
2025-11-24 14:18:41 +08:00
5a4cef52be feat: 添加西班牙语与俄语适配
All checks were successful
deploy to server / build-and-deploy (push) Successful in 3m5s
- 西班牙语与俄语i18n文本
- 对应语言切换选项
2025-11-21 16:53:03 +08:00
30ffc7e557 feat: 添加机器翻译标注
All checks were successful
deploy to server / build-and-deploy (push) Successful in 3m1s
2025-11-21 16:51:49 +08:00
c4b9ed7bae feat: 补全i18n文本
Some checks failed
deploy to server / build-and-deploy (push) Has been cancelled
- 补全西班牙语与俄语文本
2025-11-21 16:50:05 +08:00
fc6c922ac3 feat: 站点的语言切换选项添加西班牙语与俄语选项
All checks were successful
deploy to server / build-and-deploy (push) Successful in 3m18s
- WIP: i18n文本尚未完善
2025-11-20 15:35:20 +08:00
54389b32ac fix: 修改地图开启逻辑
All checks were successful
deploy to server / build-and-deploy (push) Successful in 3m7s
- 当单击公司地址时,先在新标签页开启locate路由,再异步定向到合适的地图服务商页面
2025-11-19 15:04:51 +08:00
d8002a8265 fix: 修改地图开启逻辑
All checks were successful
deploy to server / build-and-deploy (push) Successful in 3m4s
- 当单击公司地址时,先在新标签页开启locate路由,再异步定向到合适的地图服务商页面
2025-11-19 15:03:59 +08:00
51042c395a feat: 修改地图服务的跳转链接
All checks were successful
deploy to server / build-and-deploy (push) Successful in 2m45s
- 将高德地图改为百度地图
2025-11-19 14:06:47 +08:00
6cf964e8f7 feat: 修改地图服务跳转链接
All checks were successful
deploy to server / build-and-deploy (push) Successful in 2m57s
- 将高德地图改为百度地图
2025-11-19 14:05:28 +08:00
456f2c69f2 fix: 调整地图跳转逻辑
All checks were successful
deploy to server / build-and-deploy (push) Successful in 3m10s
- 新增locate页,用于地图跳转
- 调整about页卡片布局
2025-11-18 17:04:29 +08:00
6f005c1404 fix: 调整地图跳转逻辑
Some checks failed
deploy to server / build-and-deploy (push) Has been cancelled
- 新增locate页,用于地图跳转
- 调整about页卡片布局
2025-11-18 17:03:40 +08:00
1ab6d92226 feat: about页面添加公司地址跳转功能
All checks were successful
deploy to server / build-and-deploy (push) Successful in 3m3s
- 外部链接跳转:点击公司地址时,跳转带外部地图服务商链接
- 智能跳转: 根据用户的连接情况,自动选择google地图或者高德地图
2025-11-18 14:16:39 +08:00
67629ed518 feat: about页面添加公司地址跳转功能
All checks were successful
deploy to server / build-and-deploy (push) Successful in 3m21s
- 外部链接跳转:点击公司地址时,跳转带外部地图服务商链接
- 智能跳转: 根据用户的连接情况,自动选择google地图或者高德地图
2025-11-18 14:11:43 +08:00
fe8a0e7656 fix: 修复specs无法正常转换的问题
All checks were successful
deploy to server / build-and-deploy (push) Successful in 3m8s
- 修正查询语句: 补全spces的id字段
2025-11-17 14:48:36 +08:00
a82872c1c1 fix: 修复specs无法正常转换的问题
All checks were successful
deploy to server / build-and-deploy (push) Successful in 3m12s
- 修正GraphQL查询语句:补全Specs的id字段
2025-11-17 14:46:46 +08:00
02ecb18147 fix: 问题列表无法聚焦问题
All checks were successful
deploy to server / build-and-deploy (push) Successful in 3m20s
- 将类型标注中的id字段改为string,与GraphQL返回类型一致
- 问题id比较随之更改为字符串匹配
- 删除无用导出

ISSUE: Resolve #83
2025-11-15 16:39:06 +08:00
05c970d1e7 chore: 删除无用导出
All checks were successful
deploy to server / build-and-deploy (push) Successful in 3m19s
- 删除useMeilisearch
2025-11-15 16:33:52 +08:00
496548afa4 fix: 修复前端类型标注与GraphQL访问数据不同的问题
- 将类型标注中的id字段改为string
2025-11-15 16:33:30 +08:00
6f08701847 fix: 修复无法搜索问题
All checks were successful
deploy to server / build-and-deploy (push) Successful in 2m51s
- 将搜索服务移至Server端
2025-11-14 14:59:03 +08:00
17bb8adee3 fix: 修复Server搜索问题
All checks were successful
deploy to server / build-and-deploy (push) Successful in 3m7s
- 将meilisearch搜索服务移至Server端
2025-11-14 14:57:55 +08:00
b2b631ed46 fix: 暂时将html渲染回滚到v-html
All checks were successful
deploy to server / build-and-deploy (push) Successful in 2m59s
- 暂时弃用html-renderer,改为v-html
- html-typography增添表格样式
2025-11-14 13:30:25 +08:00
ec9a097ef5 fix: 暂时弃用html-renderer将html渲染回滚到v-html
All checks were successful
deploy to server / build-and-deploy (push) Successful in 2m56s
- 增添table样式
2025-11-14 13:29:00 +08:00
3fb28c3f00 test: 优化测试代码
All checks were successful
deploy to server / build-and-deploy (push) Successful in 3m6s
- 显式导入相关依赖以避免Vitest的依赖问题

ISSUE: close: #46
2025-11-14 12:34:59 +08:00
d7bd034d7d test: 优化测试代码
All checks were successful
deploy to server / build-and-deploy (push) Successful in 3m5s
- 显式导入相关依赖以避免相关问题
2025-11-14 12:23:49 +08:00
341a9c4066 refactor: 将页面的Markdown渲染改为HTML渲染
All checks were successful
deploy to server / build-and-deploy (push) Successful in 2m57s
- 前后端通信:后端相关字段由Markdown改为WYSIWYG,前端做出响应更改
- 页面显示调整: 移除解决方案页创建日期显示
- 工具添加: 添加Asset处理方法,将CMS域名URL重写为Server API URL
- 代码整理:移除部分弃用代码

ISSUES: Close: #40 Resolve: #24
2025-11-14 11:48:17 +08:00
ee1597d2c3 fix: 调整URL转换的baseURL
All checks were successful
deploy to server / build-and-deploy (push) Successful in 2m54s
- 将baseURL由directus_url转为directus_public_url
2025-11-14 11:42:29 +08:00
17d10a7d80 chore: 移除部分无用代码
All checks were successful
deploy to server / build-and-deploy (push) Successful in 3m37s
2025-11-14 11:06:09 +08:00
54d0e297ea feat: 将Markdown渲染改为HTML渲染
- CMS相关字段由Markdown改为WYSIWYG,前端做出对应更改
- AssetUrl重写:将CMS地址重写为本地API
2025-11-14 11:06:00 +08:00
644dfa329c fix: 删除解决方案页的创建日期显示 2025-11-14 09:55:35 +08:00
100b79f99b feat: 将Solution的内容渲染有Markdown改为Html 2025-11-14 09:54:41 +08:00
f4f7e490b4 fix: 修正服务支持页面文本错误
All checks were successful
deploy to server / build-and-deploy (push) Successful in 2m56s
2025-11-14 08:06:00 +08:00
6418587738 fix: 修正服务支持页面描述文本错误
All checks were successful
deploy to server / build-and-deploy (push) Successful in 3m0s
2025-11-14 08:04:34 +08:00
6983f6568d feat!: 将QuestionList的内容渲染由Markdown改为HTML
All checks were successful
deploy to server / build-and-deploy (push) Successful in 3m10s
- 后端CMS字段由Markdown改为WYSIWYG因此前端做出对应修改
2025-11-14 00:07:31 +08:00
c860621e7a feat!: 将QuestionList的内容渲染由Markdown改为HTML
All checks were successful
deploy to server / build-and-deploy (push) Successful in 6m51s
- 后端CMS字段由Markdown改为WYSIWYG因此前端做出对应修改
2025-11-14 00:00:05 +08:00
154943815d refactor: 将Data到ViewModel的转换由App转移至Server端
All checks were successful
deploy to server / build-and-deploy (push) Successful in 3m42s
- 将逻辑转移到Server端后,简化前端逻辑
2025-11-13 20:51:09 +08:00
23f2700c0f refactor: 将Data到ViewModel的转换由App转移至Server端
All checks were successful
deploy to server / build-and-deploy (push) Successful in 3m15s
- 将逻辑转移到Server端后,简化前端逻辑
2025-11-13 20:45:43 +08:00
133 changed files with 4389 additions and 1885 deletions

View File

@ -0,0 +1,95 @@
.html-typography {
padding: 10px;
line-height: 1.6;
}
.html-typography h1 {
color: var(--el-color-primary);
font-size: 1.5em;
margin-bottom: 0.5em;
text-align: center;
}
.html-typography h2 {
color: var(--el-color-primary);
font-size: 1.5em;
margin-bottom: 0.5em;
}
.html-typography h3 {
color: var(--el-color-primary);
font-size: 1.2em;
margin-bottom: 0.5em;
}
.html-typography p {
text-indent: 2em;
text-align: justify;
margin: 0.5em 0;
margin-bottom: 1em;
}
.html-typography ol {
list-style-type: decimal;
padding-left: 2em;
margin-bottom: 1em;
}
.html-typography ul {
list-style-type: disc;
padding-left: 2em;
margin-bottom: 1em;
}
.html-typography hr {
border: none;
border-top: 1px solid var(--el-border-color);
margin: 20px 0;
}
/* 表格基础样式 */
.html-typography table {
width: 100%;
border-collapse: collapse;
border: 1px solid var(--el-border-color);
margin: 1em 0;
table-layout: auto;
font-size: 14px;
}
/* 单元格通用样式 */
.html-typography th,
.html-typography td {
border: 1px solid var(--el-border-color);
padding: 8px 12px;
text-align: left;
vertical-align: middle;
word-break: break-word;
}
/* 表头样式 */
.html-typography th {
background-color: var(--el-fill-color-light);
color: var(--el-text-color-primary);
font-weight: 600;
}
/* 行 hover 效果 */
.html-typography tbody tr:hover {
background-color: var(--el-fill-color-light-hover);
}
/* 交替行背景 */
.html-typography tbody tr:nth-child(odd) {
background-color: var(--el-fill-color-lighter);
}
/* 表格标题(如有 caption */
.html-typography table caption {
caption-side: top;
text-align: left;
padding: 8px 0;
font-size: 14px;
font-weight: 600;
color: var(--el-text-color-primary);
}

View File

@ -0,0 +1,107 @@
<template>
<component
:is="wrapperTag"
v-bind="wrapperProps"
class="learn-more-wrapper"
@click="handleAsyncClick"
>
<el-card class="learn-more-card">
<el-icon class="icon" size="80">
<component :is="icon" />
</el-icon>
<br />
{{ title }}
</el-card>
</component>
</template>
<script setup lang="ts">
const props = defineProps({
title: {
type: String,
default: '',
},
icon: {
type: Object,
default: null,
},
to: {
type: String,
default: null,
},
href: {
type: [String, Function],
default: null,
},
});
// 包裹器标签
const wrapperTag = computed(() => {
if (props.to) return resolveComponent('NuxtLink');
if (props.href) return 'a';
return 'div';
});
// 包裹器属性
const wrapperProps = computed(() => {
// Nuxt 内部跳转
if (props.to) {
return { to: props.to };
}
// 外部跳转(字符串)
if (typeof props.href === 'string') {
return {
href: props.href,
target: '_blank',
rel: 'noopener noreferrer',
};
}
// 其他情况href 是异步函数 → 不在这里处理
return { href: '#' };
});
async function handleAsyncClick(event: Event) {
if (typeof props.href === 'function') {
event.preventDefault();
const url = await props.href();
window.open(url, '_blank', 'noopener,noreferrer');
}
}
</script>
<style scoped>
.learn-more-card {
width: 20%;
min-width: 200px;
padding: 20px;
margin: 0 auto;
cursor: pointer;
text-align: center;
font-size: 1.5em;
}
.learn-more-card:hover {
transform: translateY(-4px);
box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}
.icon {
padding: 10px;
}
@media (max-width: 768px) {
.learn-more-wrapper {
display: flex;
justify-content: center;
align-items: center;
width: 100%;
}
.learn-more-card {
width: 80%;
min-width: 0;
}
}
</style>

View File

@ -2,7 +2,15 @@
<div class="product-detail">
<el-tabs v-model="activeName" class="product-tabs" stretch>
<el-tab-pane :label="$t('product-tab.details')" name="details">
<markdown-renderer :content="product.description || ''" />
<!-- eslint-disable-next-line vue/no-v-html -->
<div class="html-typography" v-html="product?.description || ''" />
<!-- <div v-if="!hydrated" v-html="product.description || ''" /> -->
<!-- <div v-else> -->
<!-- <html-renderer -->
<!-- class="html-typography" -->
<!-- :html="product.description || ''" -->
<!-- /> -->
<!-- </div> -->
</el-tab-pane>
<el-tab-pane :label="$t('product-tab.specs')" name="specs">
<spec-table :data="product.specs" />
@ -25,7 +33,13 @@
},
});
const hydrated = ref(false);
const activeName = ref('details'); // 默认选中概览标签
onMounted(() => {
hydrated.value = true;
});
</script>
<style scoped>

View File

@ -38,6 +38,10 @@
<div class="product-info">
<h1>{{ product.name }}</h1>
<p class="summary">{{ product.summary }}</p>
<p v-if="product.status === 'discontinued'" class="discontinued-warning">
<el-icon><ElIconWarning /></el-icon>
{{ $t('product-discontinued-warning') }}
</p>
</div>
</div>
</template>
@ -105,6 +109,10 @@
margin-bottom: 2rem;
}
.discontinued-warning {
color: var(--el-color-error);
}
@media (max-width: 768px) {
.product-header {
grid-template-columns: 1fr;

View File

@ -0,0 +1,75 @@
<template>
<el-card class="result-card">
<el-row>
<el-col :span="12">
<h3 class="result-title">{{ item.title }}</h3>
<p v-if="item.summary" class="result-summary">
{{ item.summary }}
</p>
<p v-if="item.sectionType" class="result-type">
<span>{{ $t('search.section') }}: </span>
<span class="result-type-name">{{ typeLabel }}</span>
<span v-if="item.type" class="result-type-name"
>({{ item.type }})</span
>
</p>
</el-col>
<el-col :span="12" class="image-col">
<el-image
v-if="item.thumbnail"
:src="item.thumbnail"
:alt="item.title"
style="width: 150px"
/>
</el-col>
</el-row>
</el-card>
</template>
<script setup lang="ts">
defineProps<{
item: SearchItemView;
typeLabel: string;
}>();
</script>
<style scoped>
.result-card {
border-radius: 12px;
transition: box-shadow 0.2s ease;
}
.result-card:hover {
box-shadow: 0 12px 24px rgba(0, 0, 0, 0.06);
}
.result-title {
font-size: 1.2rem;
font-weight: 600;
color: var(--el-color-primary);
display: inline-block;
}
.result-summary {
font-size: 0.95rem;
color: var(--el-text-color-regular);
margin-bottom: 0.5rem;
line-height: 1.6;
}
.result-type {
font-size: 0.8rem;
color: var(--el-text-color-secondary);
}
.result-type-name {
margin-left: 4px;
color: var(--el-color-primary);
}
.image-col {
display: flex;
justify-content: end;
align-items: center;
}
</style>

View File

@ -3,19 +3,13 @@
<div class="search-results">
<NuxtLink
v-for="hit in paginatedHits"
:key="`${hit.type}-${hit.id}`"
:key="`${hit.sectionType}-${hit.id}`"
:to="localePath(resolveHitLink(hit))"
>
<el-card class="result-card">
<h3 class="result-title">{{ hit.title }}</h3>
<p v-if="hit.summary" class="result-summary">
{{ hit.summary }}
</p>
<p v-if="hit.type" class="result-type">
<span>内容类型: </span>
<span class="result-type-name">{{ getIndexLabel(hit.type) }}</span>
</p>
</el-card>
<search-result-card
:item="hit"
:type-label="getIndexLabel(hit.sectionType)"
/>
</NuxtLink>
</div>
@ -72,7 +66,7 @@
const items = props.searchItems;
const filteredHits = computed(() => {
if (props.category) {
return items.filter((item) => item.type === props.category);
return items.filter((item) => item.sectionType === props.category);
} else {
return items;
}
@ -116,19 +110,19 @@
const slug = String(slugCandidate);
if (item.type === 'product') {
if (item.sectionType === 'product') {
return localePath({ path: `/products/${slug}` });
}
if (item.type === 'solution') {
if (item.sectionType === 'solution') {
return localePath({ path: `/solutions/${slug}` });
}
if (item.type === 'document') {
if (item.sectionType === 'document') {
return localePath({ path: `/download/${slug}` });
}
if (item.type === 'question') {
if (item.sectionType === 'question') {
return localePath({ path: `/support/faq`, query: { focus: slug } });
}

View File

@ -22,17 +22,17 @@
}>();
const tabs = [
{ name: 'all', label: '全部' },
{ name: 'product', label: '产品' },
{ name: 'solution', label: '解决方案' },
{ name: 'question', label: '相关问题' },
{ name: 'document', label: '文档资料' },
{ name: 'all', label: $t('all') },
{ name: 'product', label: $t('search.sections.product') },
{ name: 'solution', label: $t('search.sections.solution') },
{ name: 'question', label: $t('search.sections.faq') },
{ name: 'document', label: $t('search.sections.document') },
];
const resultCount = computed(() => {
const map: Record<string, number> = { all: props.searchItems.length };
for (const item of props.searchItems) {
map[item.type] = (map[item.type] ?? 0) + 1;
map[item.sectionType] = (map[item.sectionType] ?? 0) + 1;
}
return map;
});
@ -47,3 +47,9 @@
currentPage.value = 1; // 重置页码
});
</script>
<style scoped>
.el-tabs {
width: 100%;
}
</style>

View File

@ -2,16 +2,15 @@
<article class="solution-defail">
<header class="solution-header">
<h1 class="solution-title">{{ solution.title }}</h1>
<dl class="solution-meta">
<dt class="visually-hidden">CreatedAt:</dt>
<dd class="solution-date">
{{ new Date(solution.createAt).toLocaleDateString() }}
</dd>
</dl>
<p class="solution-summary">{{ solution.summary }}</p>
</header>
<section class="solution-content">
<markdown-renderer :content="solution?.content || ''" />
<!-- eslint-disable-next-line vue/no-v-html -->
<div class="html-typography" v-html="solution?.content || ''" />
<!-- <div v-if="!hydrated" v-html="solution?.content || ''" /> -->
<!-- <div v-else> -->
<!-- <html-renderer class="html-typography" :html="solution.content || ''" /> -->
<!-- </div> -->
</section>
</article>
</template>
@ -23,6 +22,12 @@
default: null,
},
});
const hydrated = ref(false);
onMounted(() => {
hydrated.value = true;
});
</script>
<style scoped>

View File

@ -0,0 +1,113 @@
<template>
<div class="document-category">
<el-row :gutter="12">
<el-col :span="12" :xs="12">
<span class="select-label">{{
$t('product-filter.product-type')
}}</span>
<el-select
v-model="model.selectedProductType"
:placeholder="$t('product-filter.select-product-type')"
clearable
>
<el-option
v-for="type in productTypeOptions"
:key="type.id"
:label="type.name"
:value="type.id"
/>
</el-select>
</el-col>
<el-col :span="12" :xs="12">
<span class="select-label">{{
$t('product-filter.product-model')
}}</span>
<el-select
v-model="model.selectedProduct"
:placeholder="$t('product-filter.select-product-model')"
clearable
>
<el-option
v-for="product in productOptions"
:key="product.id"
:label="product.name"
:value="product.id"
/>
</el-select>
</el-col>
<el-col :span="12" :xs="24">
<span class="select-label">
{{ $t('product-filter.document-type') }}
</span>
<el-select
v-model="model.selectedDocumentType"
:placeholder="$t('product-filter.select-document-type')"
clearable
>
<el-option
v-for="questionType in documentTypeOptions"
:key="questionType.id"
:label="questionType.name"
:value="questionType.id"
/>
</el-select>
</el-col>
<el-col :span="12" :xs="24">
<span class="select-label">{{ $t('product-filter.keyword') }}</span>
<el-input
v-model="model.keyword"
:placeholder="$t('product-filter.enter-keyword')"
clearable
:prefix-icon="Search"
/>
</el-col>
</el-row>
</div>
</template>
<script setup lang="ts">
import { Search } from '@element-plus/icons-vue';
defineProps({
productTypeOptions: {
type: Array as () => Array<DocumentListProductType>,
default: () => [],
},
productOptions: {
type: Array as () => Array<DocumentListProduct>,
default: () => [],
},
documentTypeOptions: {
type: Array as () => Array<DocumentTypeView>,
default: () => [],
},
});
const model = defineModel<{
selectedProduct: string | null;
selectedProductType: string | null;
selectedDocumentType: string | null;
keyword: string;
}>();
</script>
<style scoped>
.document-category {
margin-bottom: 1rem;
padding: 0 0;
}
.select-label {
color: var(--el-text-color-secondary);
font-size: 0.9rem;
}
:deep(.el-select__wrapper),
:deep(.el-input__wrapper) {
height: 40px;
font-size: 0.9rem;
}
</style>

View File

@ -1,12 +1,12 @@
<template>
<div class="question-category">
<el-row class="hide-on-mobile" :gutter="12">
<el-col :span="8">
<el-row :gutter="12">
<el-col :span="12" :xs="12">
<span class="select-label">{{
$t('product-filter.product-type')
}}</span>
<el-select
v-model="model.selectedType"
v-model="model.selectedProductType"
:placeholder="$t('product-filter.select-product-type')"
clearable
>
@ -19,7 +19,7 @@
</el-select>
</el-col>
<el-col :span="8">
<el-col :span="12" :xs="12">
<span class="select-label">{{
$t('product-filter.product-model')
}}</span>
@ -37,54 +37,25 @@
</el-select>
</el-col>
<el-col :span="8">
<span class="select-label">{{ $t('product-filter.keyword') }}</span>
<el-input
v-model="model.keyword"
:placeholder="$t('product-filter.enter-keyword')"
clearable
:prefix-icon="Search"
/>
</el-col>
</el-row>
<el-row class="display-on-mobile" :gutter="12">
<el-col :span="12">
<span class="select-label">{{
$t('product-filter.product-type')
}}</span>
<el-col :span="12" :xs="24">
<span class="select-label">
{{ $t('product-filter.question-type') }}
</span>
<el-select
v-model="model.selectedType"
:placeholder="$t('product-filter.select-product-type')"
v-model="model.selectedQuestionType"
:placeholder="$t('product-filter.select-question-type')"
clearable
>
<el-option
v-for="type in productTypeOptions"
:key="type.id"
:label="type.name"
:value="type.id"
v-for="questionType in questionTypeOptions"
:key="questionType.id"
:label="questionType.name"
:value="questionType.id"
/>
</el-select>
</el-col>
<el-col :span="12">
<span class="select-label">{{
$t('product-filter.product-model')
}}</span>
<el-select
v-model="model.selectedProduct"
:placeholder="$t('product-filter.select-product-model')"
clearable
>
<el-option
v-for="product in productOptions"
:key="product.id"
:label="product.name"
:value="product.id"
/>
</el-select>
</el-col>
</el-row>
<el-row class="display-on-mobile">
<el-col :span="12" :xs="24">
<span class="select-label">{{ $t('product-filter.keyword') }}</span>
<el-input
v-model="model.keyword"
@ -92,6 +63,7 @@
clearable
:prefix-icon="Search"
/>
</el-col>
</el-row>
</div>
</template>
@ -101,19 +73,24 @@
defineProps({
productTypeOptions: {
type: Array as () => Array<{ id: number; name: string }>,
type: Array as () => Array<QuestionListProductType>,
default: () => [],
},
productOptions: {
type: Array as () => Array<{ id: number; name: string }>,
type: Array as () => Array<QuestionListProduct>,
default: () => [],
},
questionTypeOptions: {
type: Array as () => Array<QuestionTypeView>,
default: () => [],
},
});
const model = defineModel<{
selectedProduct: string | null;
selectedProductType: string | null;
selectedQuestionType: string | null;
keyword: string;
selectedType: number | null;
selectedProduct: number | null;
}>();
</script>
@ -132,18 +109,4 @@
height: 40px;
font-size: 0.9rem;
}
.display-on-mobile {
display: none;
}
@media (max-width: 768px) {
.hide-on-mobile {
display: none;
}
.display-on-mobile {
display: flex;
margin-bottom: 1rem;
}
}
</style>

View File

@ -7,7 +7,17 @@
@click="handleClick(doc.fileId)"
>
<div class="document-info">
<h3>{{ doc.title }}</h3>
<div class="document-title">
<h3>
{{ doc.title }}
<span v-if="showCategory && doc.type" class="document-category">
|
</span>
<span v-if="showCategory && doc.type" class="document-category">
{{ doc.type.name }}
</span>
</h3>
</div>
<div class="document-content">
<span v-if="doc.size" class="document-meta"
>{{ $t('document-meta.size') }}: {{ formatFileSize(doc.size) }}
@ -28,6 +38,10 @@
type: Array as () => Array<ProductDocumentView>,
default: () => [],
},
showCategory: {
type: Boolean,
default: true,
},
});
const localePath = useLocalePath();
@ -63,6 +77,15 @@
color: var(--el-text-color-secondary);
}
.document-title {
margin-bottom: 0.5rem;
}
.document-category {
font-size: 0.75rem;
color: var(--el-text-color-secondary);
}
.download-button {
margin-left: auto;
}

View File

@ -0,0 +1,30 @@
export default defineComponent({
name: 'HtmlRenderer',
props: {
html: {
type: String,
required: true,
},
map: {
type: Object as () => HtmlRenderMap,
default: () => defaultHtmlRenderMap,
},
allowUnknown: {
type: Boolean,
default: true,
},
},
setup(props, { attrs }) {
const nodes: VNode[] = useHtmlRenderer(props.html, {
map: props.map,
allowUnknownTags: props.allowUnknown,
});
logger.debug('nodes: ', nodes);
// 渲染函数:直接返回 VNode 数组
return () => h('div', { ...attrs }, nodes);
},
});

View File

@ -84,7 +84,12 @@
&copy; {{ currentYear }} {{ $t('company-name') }}.
{{ $t('all-rights-reserved') }}
</p>
<p>备案号: 浙ICP备12003709号-5</p>
<p>
备案号:
<a href="https://beian.miit.gov.cn/" target="_blank"
>浙ICP备12003709号-5</a
>
</p>
</div>
<!-- <div class="footer-links-bottom"> -->
<!-- <NuxtLink :to="$localePath('/privacy')">{{ -->

View File

@ -67,6 +67,12 @@
<el-dropdown-menu>
<el-dropdown-item command="zh">简体中文</el-dropdown-item>
<el-dropdown-item command="en">English</el-dropdown-item>
<el-dropdown-item command="es"
>Español(Machine Translate)</el-dropdown-item
>
<el-dropdown-item command="ru"
>Русский(Machine Translate)</el-dropdown-item
>
</el-dropdown-menu>
</template>
</el-dropdown>
@ -140,6 +146,12 @@
<el-dropdown-menu>
<el-dropdown-item command="zh">简体中文</el-dropdown-item>
<el-dropdown-item command="en">English</el-dropdown-item>
<el-dropdown-item command="es"
>Español(Machine Translate)</el-dropdown-item
>
<el-dropdown-item command="ru"
>Русский(Machine Translate)</el-dropdown-item
>
</el-dropdown-menu>
</template>
</el-dropdown>

View File

@ -13,11 +13,8 @@
const props = defineProps<Props>();
const contentWithAbsoluteUrls = convertMedia(props.content);
// 将 Markdown 转换成 HTML
const safeHtml = computed(() => renderMarkdown(contentWithAbsoluteUrls));
// const safeHtml = computed(() => renderMarkdown(props.content))
const safeHtml = computed(() => renderMarkdown(props.content));
const container = ref<HTMLElement | null>(null);

View File

@ -8,7 +8,15 @@
:title="question.title"
:name="question.id"
>
<markdown-renderer :content="question.content || ''" />
<!-- eslint-disable-next-line vue/no-v-html -->
<div class="html-typography" v-html="question.content || ''" />
<!-- <div v-if="!hydrated" v-html="question.content" /> -->
<!-- <div v-else> -->
<!-- <html-renderer -->
<!-- class="html-typography" -->
<!-- :html="question.content || ''" -->
<!-- /> -->
<!-- </div> -->
</el-collapse-item>
</el-collapse>
</div>
@ -25,6 +33,8 @@
const activeNames = ref<(string | number)[]>([]);
const hydrated = ref(false);
// 当路由变化(包括初次挂载)时,检查是否需要聚焦
watch(
() => route.query.focus,
@ -35,18 +45,32 @@
// 确保渲染完成后再操作 DOM
await nextTick();
const target = props.questions.find((q) => q.id === Number(focusId));
const target = props.questions.find((q) => q.id === focusId);
if (!target) return;
// 展开目标项
activeNames.value = [target.id];
await nextTick();
await new Promise((resolve) => setTimeout(resolve, 100)); // 等待动画完成
// 平滑滚动到对应位置
// const el = document.querySelector(`#q-${target.id}`);
// el?.scrollIntoView({ behavior: 'smooth', block: 'start' });
setTimeout(() => {
const el = document.querySelector(`#q-${target.id}`);
el?.scrollIntoView({ behavior: 'smooth', block: 'start' });
el?.scrollIntoView({
behavior: 'smooth',
block: 'start',
});
}, 200); // 与 el-collapse 的 transition 时间匹配
},
{ immediate: true }
);
onMounted(() => {
hydrated.value = true;
});
</script>
<style scoped>

View File

@ -1,3 +1,2 @@
export * from './directus';
export * from './useLocalizations';
export * from './useMeilisearch';

View File

@ -0,0 +1,80 @@
import { h, type VNode } from 'vue';
import { parseDocument } from 'htmlparser2';
import type { Element, Text, Node } from 'domhandler';
/** 标签映射的类型key=标签名value=渲染函数 */
export type HtmlRenderMap = Record<
string,
(node: Element, children: VNode[]) => VNode
>;
export interface HtmlRenderOptions {
/** 自定义标签渲染映射 */
map?: HtmlRenderMap;
/** 默认是否将未知标签渲染为原生标签(默认 true */
allowUnknownTags?: boolean;
}
export const useHtmlRenderer = (
html: string,
options: HtmlRenderOptions = {}
) => {
const { map = {}, allowUnknownTags = true } = options;
const doc = parseDocument(html);
function render(node: Node): VNode | string | null {
// 文本节点
if (node.type === 'text') {
const textNode = node as Text;
const content = textNode.data;
// ❗忽略"纯空白" 文本(换行、空格)
if (!content || /^\s+$/.test(content)) {
return null;
}
return content;
}
// 标签节点
if (node.type === 'tag') {
const elem = node as Element;
const rawName = elem.name ?? '';
const name = rawName.trim().toLowerCase();
// 标签名有效性校验
const isValidTag = /^[a-zA-Z][a-zA-Z0-9-]*$/.test(name);
if (!isValidTag) {
logger.warn(`Invalid tag name ignored: "${rawName}"`);
return null;
}
const children: VNode[] = (elem.children || [])
.map((child) => render(child))
.filter(Boolean) as VNode[];
// 自定义映射
if (map[name]) {
return map[name](elem, children);
}
// 默认将未知标签渲染为原生标签
if (allowUnknownTags) {
return h(name, elem.attribs || {}, children);
}
// 忽略无法渲染节点
return null;
}
return null;
}
const nodes = doc.children
.map((child) => render(child))
.filter(Boolean) as VNode[];
return nodes;
};

View File

@ -1,6 +1,8 @@
import type { Language as ElementLanguage } from 'element-plus/es/locale';
import zhCn from 'element-plus/es/locale/lang/zh-cn';
import en from 'element-plus/es/locale/lang/en';
import es from 'element-plus/es/locale/lang/es';
import ru from 'element-plus/es/locale/lang/ru';
/**
* 应用语言映射结构
@ -28,6 +30,14 @@ export const localeMap = {
directus: 'en-US',
element: en,
},
es: {
directus: 'es-ES',
element: es,
},
ru: {
directus: 'ru-RU',
element: ru,
},
} satisfies Record<string, LocaleMapping>;
/** 应用支持的语言键类型 **/

View File

@ -1,133 +0,0 @@
import { MeiliSearch } from 'meilisearch';
import type { SearchParams } from 'meilisearch';
const parseIndexes = (
indexes: string | string[] | undefined,
locale?: string
): string[] => {
if (!indexes) {
return [];
}
let suffix = '';
if (locale) {
suffix = `_${locale}`;
}
if (Array.isArray(indexes)) {
return indexes.map((item) => `${item.trim()}${suffix}`).filter(Boolean);
}
return indexes
.split(',')
.map((item) => `${item.trim()}${suffix}`)
.filter(Boolean);
};
export const useMeilisearch = () => {
const runtimeConfig = useRuntimeConfig();
const indexes = computed(() =>
parseIndexes(runtimeConfig.public?.meili?.indexes)
);
let meiliClient: MeiliSearch | null = null;
const ensureClient = () => {
if (meiliClient) return meiliClient;
const host = runtimeConfig.public?.meili?.host;
if (!host) {
logger.warn('Meilisearch host is not configured.');
return null;
}
const apiKey = runtimeConfig.public?.meili?.searchKey;
meiliClient = new MeiliSearch({
host,
apiKey: apiKey || undefined,
});
return meiliClient;
};
/**
* 泛型搜索函数
* @template T 文档类型, 如 MeiliProductIndex
* ---
* @param query 搜索关键词
* @param params 其他搜索参数
* @returns 搜索结果数组
*/
async function search<
K extends MeiliSearchItemType = MeiliSearchItemType,
T extends MeiliIndexMap[K] = MeiliIndexMap[K],
>(
query: string,
params: SearchParams = {},
searchLocale?: string
): Promise<SearchSection<T>[]> {
const trimmedQuery = query.trim();
if (!trimmedQuery) {
return [];
}
const client = ensureClient();
if (!client) {
return [];
}
const activeIndexes = indexes.value as K[];
if (!activeIndexes.length) {
logger.warn('No Meilisearch indexes configured.');
return [];
}
const rawIndexMap = Object.fromEntries(
activeIndexes.map((index) => [`${index}_${searchLocale}`, index])
);
const indexesWithLocale = activeIndexes.map(
(index) => index + (searchLocale ? `_${searchLocale}` : '')
);
const requests = indexesWithLocale.map(async (indexUid) => {
const response = await client.index(indexUid).search<T>(trimmedQuery, {
limit: params.limit ?? 10,
...params,
});
return {
indexUid,
response,
} satisfies RawSearchSection<T>;
});
const settled = await Promise.allSettled(requests);
settled
.filter(
(result): result is PromiseRejectedResult =>
result.status === 'rejected'
)
.forEach((result) => {
logger.error('Meilisearch query failed', result.reason);
});
return settled
.filter(
(result): result is PromiseFulfilledResult<RawSearchSection<T>> =>
result.status === 'fulfilled'
)
.map((result) => {
const { indexUid, response } = result.value;
return {
indexUid: indexUid,
rawIndex: rawIndexMap[indexUid],
hits: response.hits,
estimatedTotalHits:
response.estimatedTotalHits ?? response.hits.length,
processingTimeMs: response.processingTimeMs ?? 0,
};
});
}
return {
search,
indexes,
};
};

View File

@ -1,106 +0,0 @@
import { describe, test, expect } from 'vitest';
/**
* 单元测试: toProductDocumentView
*/
describe('toProductDocumentView', () => {
test('convert raw data with fileId to ProductDocumentView correctly', () => {
const rawData: ProductDocument = {
id: 1,
file: 'rand-om__-uuid-1234',
translations: [{ id: 10, title: 'Document Title' }],
};
expect(toProductDocumentView(rawData)).toEqual({
id: 1,
fileId: 'rand-om__-uuid-1234',
filename: undefined,
title: 'Document Title',
url: 'http://localhost:8055/assets/rand-om__-uuid-1234',
size: undefined,
});
});
test('convert raw data with fileMeta to ProductDocumentView correctly', () => {
const rawData: ProductDocument = {
id: 1,
file: {
id: 'rand-om__-uuid-1234',
filename_download: 'document.pdf',
filesize: 2048,
},
translations: [{ id: 10, title: 'Document Title' }],
};
expect(toProductDocumentView(rawData)).toEqual({
id: 1,
fileId: 'rand-om__-uuid-1234',
filename: 'document.pdf',
title: 'Document Title',
url: 'http://localhost:8055/assets/rand-om__-uuid-1234',
size: 2048,
});
});
test('convert raw data with missing translations', () => {
const rawData: ProductDocument = {
id: 1,
file: 'rand-om__-uuid-1234',
translations: [],
};
expect(toProductDocumentView(rawData)).toEqual({
id: 1,
fileId: 'rand-om__-uuid-1234',
filename: undefined,
title: '',
url: 'http://localhost:8055/assets/rand-om__-uuid-1234',
size: undefined,
});
});
});
/**
* 单元测试: toDocumentListView
*/
describe('toProductDocumentView', () => {
test('convert raw data with fileId to DocumentListView correctly', () => {
const rawData: ProductDocument = {
id: 1,
file: 'rand-om__-uuid-1234',
translations: [{ id: 10, title: 'Document Title' }],
products: [
{
id: 10,
products_id: {
id: 1,
translations: [{ id: 1, name: 'Product A' }],
product_type: {
id: 1,
translations: [{ id: 1, name: 'Type A' }],
},
},
},
],
};
expect(toDocumentListView(rawData)).toEqual({
id: 1,
fileId: 'rand-om__-uuid-1234',
filename: undefined,
title: 'Document Title',
url: 'http://localhost:8055/assets/rand-om__-uuid-1234',
size: undefined,
products: [
{
id: 1,
name: 'Product A',
type: {
id: 1,
name: 'Type A',
},
},
],
});
});
});

View File

@ -1,79 +0,0 @@
/**
* 将 Directus 返回的 Document 数据转换为 ProductDocumentView 视图模型
*
* @param raw: 原始的 Document 数据
* @returns 转换后的 ProductDocumentView 对象
*
* @example
* const view = toProductDocumentView(rawDocument);
*/
export function toProductDocumentView(
raw: ProductDocument
): ProductDocumentView {
const trans = raw.translations?.[0] ?? {
title: '',
};
const fileId = typeof raw.file === 'string' ? raw.file : raw.file?.id;
const file = raw.file as DirectusFile;
const { getFileUrl } = useDirectusFiles();
const url = getFileUrl(fileId);
return {
id: raw.id,
fileId: fileId,
filename: file.filename_download,
title: trans.title,
url: url,
size: file.filesize,
};
}
/**
* 将 Directus 返回的 Document 数据转换为 DocumentListView 视图模型
*
* @param raw: 原始的 Document 数据
* @returns 转换后的 DocumentListView 对象
*
* @example
* const view = toDocumentListView(rawDocument);
*/
export function toDocumentListView(raw: ProductDocument): DocumentListView {
const trans = raw.translations?.[0] ?? { title: '' };
const fileId = typeof raw.file === 'string' ? raw.file : raw.file?.id;
const file = raw.file as DirectusFile;
const { getFileUrl } = useDirectusFiles();
const url = getFileUrl(fileId);
const related_products: DocumentListProduct[] = raw.products
?.filter(isObject<ProductsProductDocument>)
.map((item) => item.products_id)
.filter(isObject<Product>)
.map((item) => {
const productType =
isObject<ProductType>(item.product_type) &&
({
id: item.product_type.id,
name: item.product_type.translations?.[0]?.name,
} satisfies DocumentListProductType);
return {
id: item.id,
name: item.translations?.[0]?.name,
type: productType,
};
});
return {
id: raw.id,
fileId: fileId,
filename: file.filename_download,
title: trans.title,
url: url,
size: file.filesize,
products: related_products,
};
}

View File

@ -1,182 +0,0 @@
import { describe, test, expect } from 'vitest';
/**
* 单元测试: toProductListView
*/
describe('toProductListView', () => {
test('convert raw data to ProductListView correctly', () => {
const rawData: Product = {
id: 1,
translations: [
{ id: 10, name: 'Product Name', summary: 'Product Summary' },
],
cover: {
id: 'cover-file-uuid-1234',
},
product_type: {
id: 1,
translations: [{ id: 20, name: 'Type Name' }],
sort: 1,
},
};
expect(toProductListView(rawData)).toEqual({
id: 1,
name: 'Product Name',
summary: 'Product Summary',
cover: 'cover-file-uuid-1234',
product_type: {
id: 1,
name: 'Type Name',
sort: 1,
},
});
});
test('convert raw data with missing translations', () => {
const rawData: Product = {
id: 1,
translations: [],
cover: {
id: 'cover-file-uuid-1234',
},
product_type: {
id: 20,
translations: [],
sort: 1,
},
};
expect(toProductListView(rawData)).toEqual({
id: 1,
name: '',
summary: '',
cover: 'cover-file-uuid-1234',
product_type: {
id: 20,
name: '',
sort: 1,
},
});
});
});
/**
* 单元测试: toProductSpecView
*/
describe('toProductSpecView', () => {
test('convert raw data to ProductSpecView correctly', () => {
const rawData: ProductSpec = {
id: 1,
translations: [{ id: 1, key: 'Key', value: 'Value' }],
};
expect(toProductSpecView(rawData)).toEqual({
id: 1,
key: 'Key',
value: 'Value',
});
});
test('convert raw data with missing translations', () => {
const rawData: ProductSpec = {
id: 1,
translations: [],
};
expect(toProductSpecView(rawData)).toEqual({
id: 1,
key: '',
value: '',
});
});
});
/**
* 单元测试: toProductSpecGroupView
*/
describe('toProductSpecGroupView', () => {
test('convert raw data to ProductSpecGroupView correctly', () => {
const rawData: ProductSpecGroup = {
id: 1,
translations: [{ id: 1, name: 'Group Name' }],
specs: [
{ id: 1, translations: [{ id: 1, key: 'Key1', value: 'Value1' }] },
{ id: 2, translations: [{ id: 2, key: 'Key2', value: 'Value2' }] },
],
};
expect(toProductSpecGroupView(rawData)).toEqual({
id: 1,
name: 'Group Name',
specs: [
{ id: 1, key: 'Key1', value: 'Value1' },
{ id: 2, key: 'Key2', value: 'Value2' },
],
});
});
test('convert raw data with missing translations', () => {
const rawData: ProductSpecGroup = {
id: 1,
translations: [],
specs: [],
};
expect(toProductSpecGroupView(rawData)).toEqual({
id: 1,
name: '',
specs: [],
});
});
});
/**
* 单元测试: toProductView
*/
describe('toProductView', () => {
test('convert raw data to ProductView correctly', () => {
const rawData: Product = {
id: 1,
translations: [
{
id: 1,
name: 'Product Name',
summary: 'Product Summary',
description: 'Product Description',
},
],
};
expect(toProductView(rawData)).toEqual({
id: 1,
name: 'Product Name',
summary: 'Product Summary',
description: 'Product Description',
product_type: '',
images: [],
documents: [],
faqs: [],
specs: [],
});
});
test('convert raw data with missing translations', () => {
const rawData: Product = {
id: 1,
translations: [],
};
expect(toProductView(rawData)).toEqual({
id: 1,
name: '',
summary: '',
description: '',
product_type: '',
images: [],
documents: [],
faqs: [],
specs: [],
});
});
});

View File

@ -1,156 +0,0 @@
/**
* 将Directus返回的ProductType数据转换为ProductTypeView视图模型
*
* @param raw: 原始的ProductType数据
* @returns 转换后的ProductTypeView对象
*
* @example
* const view = toProductTypeView(rawProductType);
*/
export function toProductTypeView(raw: ProductType): ProductTypeView {
const trans = raw.translations?.[0] ?? { name: '' };
return {
id: raw.id,
name: trans.name,
sort: raw?.sort ?? 999,
};
}
/**
* 将 Directus返回的 Product 数据转换为 ProductListView 视图模型
*
* @param raw: 原始的 Product 数据
* @returns 转换后的 ProductListView 对象
*
* @example
* const view = toProductListView(rawProduct);
*/
export function toProductListView(raw: Product): ProductListView {
const trans = raw.translations?.[0] ?? { name: '', summary: '' };
const type = isObject<ProductType>(raw.product_type)
? toProductTypeView(raw.product_type)
: undefined;
const cover = isObject<DirectusFile>(raw.cover) ? raw.cover.id : '';
return {
id: raw.id,
product_type: type,
name: trans.name,
summary: trans.summary,
cover: cover,
};
}
/**
* 将 Directus 返回的 ProductSpecGroup 数据转换为 ProductSpecGroupView 视图模型
*
* @param raw: 原始的 ProductSpecGroup 数据
* @returns 转换后的 ProductSpecGroupView 对象
*
* @example
* const view = toProductSpecGroupView(rawSpecGroup);
*/
export function toProductSpecGroupView(
raw: ProductSpecGroup
): ProductSpecGroupView {
const trans = raw.translations?.[0] ?? {
name: '',
};
return {
id: raw.id,
name: trans.name,
specs: raw.specs
.filter(isObject<ProductSpec>)
.map((item) => toProductSpecView(item)),
};
}
/**
* 将 Directus 返回的 ProductSpec 数据转换为 ProductSpecView 视图模型
*
* @param raw: 原始的 ProductSpec 数据
* @returns 转换后的 ProductSpecView 对象
*
* @example
* const view = toProductSpecView(rawSpecGroup);
*/
export function toProductSpecView(raw: ProductSpec): ProductSpecView {
const trans = raw.translations?.[0] ?? {
key: '',
value: '',
};
return {
id: raw.id,
key: trans.key,
value: trans.value,
};
}
/**
* 将 Directus 返回的 Product 数据转换为 ProductView 视图模型
*
* @param raw: 原始的 Product 数据
* @returns 转换后的 ProductView 对象
*
* @example
* const view = toProductView(rawProduct);
*/
export function toProductView(raw: Product): ProductView {
const trans = raw.translations?.[0] ?? {
name: '',
summary: '',
description: '',
};
const images = (raw.images ?? [])
.filter(isObject<ProductsProductImage>)
.map((item) => item.product_images_id)
.filter(isObject<ProductImage>)
.map((item) => {
const image = isObject<DirectusFile>(item.image) ? item.image.id : '';
return {
id: item.id,
image: image,
caption: item.translations?.[0]?.caption || '',
};
});
const specs = (raw.specs ?? [])
.filter(isObject<ProductSpecGroup>)
.map((item) => toProductSpecGroupView(item));
const faqs = (raw.faqs ?? [])
.filter(isObject<ProductsQuestion>)
.map((item) => item.questions_id)
.filter(isObject<Question>)
.map((item) => toProductQuestionView(item));
const documents = (raw.documents ?? [])
.filter(isObject<ProductsProductDocument>)
.map((item) => item.product_documents_id)
.filter(isObject<ProductDocument>)
.map((item) => toProductDocumentView(item));
return {
id: raw.id,
product_type:
typeof raw.product_type === 'string'
? raw.product_type
: typeof raw.product_type === 'object' && raw.product_type
? raw.product_type.translations[0].name || ''
: '',
name: trans.name,
summary: trans.summary,
images: images,
description: trans.description,
specs: specs,
faqs: faqs,
documents: documents,
};
}

View File

@ -1,113 +0,0 @@
import { describe, expect, test } from 'vitest';
/**
* 单元测试: toProductQuestionView
*/
describe('toProductQuestionView', () => {
test('convert raw data to ProductQuestionView correctly', () => {
const rawData: Question = {
id: 1,
translations: [
{ id: 1, title: 'Question Title', content: 'Question Answer' },
],
};
expect(toProductQuestionView(rawData)).toEqual({
id: 1,
title: 'Question Title',
content: 'Question Answer',
});
});
test('convert raw data with missing translations', () => {
const rawData: Question = {
id: 1,
translations: [],
};
expect(toProductQuestionView(rawData)).toEqual({
id: 1,
title: '',
content: '',
});
});
});
/**
* 单元测试: toQuestionListView
*/
describe('toQuestionListView', () => {
test('convert raw data to QuestionListView correctly', () => {
const rawData: Question = {
id: 1,
translations: [
{ id: 1, title: 'Question Title', content: 'Question Answer' },
],
products: [
{
id: 1,
products_id: {
id: 1,
translations: [{ id: 1, name: 'Product Name' }],
product_type: {
id: 1,
translations: [{ id: 1, name: 'Type Name' }],
},
},
},
],
};
expect(toQuestionListView(rawData)).toEqual({
id: 1,
title: 'Question Title',
content: 'Question Answer',
products: [
{
id: 1,
name: 'Product Name',
type: {
id: 1,
name: 'Type Name',
},
},
],
});
});
test('convert raw data with missing translations', () => {
const rawData: Question = {
id: 1,
translations: [],
products: [
{
id: 1,
products_id: {
id: 1,
translations: [],
product_type: {
id: 1,
translations: [],
},
},
},
],
};
expect(toQuestionListView(rawData)).toEqual({
id: 1,
title: '',
content: '',
products: [
{
id: 1,
name: '',
type: {
id: 1,
name: '',
},
},
],
});
});
});

View File

@ -1,59 +0,0 @@
/**
* 将 Directus 返回的 Question 数据转换为 ProductQuestionView 视图模型
*
* @param raw: 原始的 Question 数据
* @returns 转换后的 ProductQuestionView 对象
*
* @example
* const view = toProductQuestionView(rawQuestion);
*/
export function toProductQuestionView(raw: Question): ProductQuestionView {
const trans = raw.translations?.[0] ?? { title: '', content: '' };
return {
id: raw.id,
title: trans.title,
content: trans.content,
};
}
/**
* 将 Directus 返回的 Question 数据转换为 QuestionListView 视图模型
*
* @param raw: 原始的 Question 数据
* @returns 转换后的 QuestionListView 对象
* ---
* @example
* const view = toQuestionListView(rawQuestion);
*/
export function toQuestionListView(raw: Question): QuestionListView {
const trans = raw.translations?.[0] ?? { title: '', content: '' };
const related_products: QuestionListProduct[] = (raw.products ?? [])
.filter(isObject<ProductsQuestion>)
.map((item) => item.products_id)
.filter(isObject<Product>)
.map((item) => {
const translations = item.translations[0] ?? { name: '' };
const product_type =
isObject<ProductType>(item.product_type) &&
({
id: item.product_type.id,
name: item.product_type.translations[0]?.name ?? '',
} satisfies QuestionListProductType);
return {
id: item.id,
name: translations.name,
type: product_type,
};
});
return {
id: raw.id,
title: trans.title,
content: trans.content,
products: related_products,
};
}

View File

@ -1,98 +0,0 @@
import { describe, test, expect } from 'vitest';
/**
* 单元测试: toSolutionListView
*/
describe('toSolutionListView', () => {
test('convert raw data to SolutionListView correctly', () => {
const rawData: Solution = {
id: 1,
translations: [
{ id: 1, title: 'Solution Title', summary: 'Solution Summary' },
],
type: {
id: 1,
translations: [{ id: 1, name: 'Type Name' }],
sort: 1,
},
};
expect(toSolutionListView(rawData)).toEqual({
id: 1,
title: 'Solution Title',
summary: 'Solution Summary',
solution_type: {
id: 1,
name: 'Type Name',
sort: 1,
},
});
});
test('convert raw data with missing translations', () => {
const rawData: Solution = {
id: 1,
translations: [],
type: {
id: 1,
translations: [],
sort: null,
},
};
expect(toSolutionListView(rawData)).toEqual({
id: 1,
title: '',
summary: '',
solution_type: {
id: 1,
name: '',
sort: 999,
},
});
});
});
/**
* 单元测试: toSolutionView
*/
describe('toSolutionView', () => {
test('convert raw data to SolutionView correctly', () => {
const rawData: Solution = {
id: 1,
translations: [
{
id: 1,
title: 'Solution Title',
summary: 'Solution Summary',
content: 'Solution Content',
},
],
create_at: '2023-01-01T00:00:00Z',
};
expect(toSolutionView(rawData)).toEqual({
id: 1,
title: 'Solution Title',
summary: 'Solution Summary',
content: 'Solution Content',
createAt: '2023-01-01T00:00:00Z',
});
});
test('convert raw data with missing translations', () => {
const rawData: Solution = {
id: 1,
translations: [],
create_at: '2023-01-01T00:00:00Z',
};
expect(toSolutionView(rawData)).toEqual({
id: 1,
title: '',
summary: '',
content: '',
createAt: '2023-01-01T00:00:00Z',
});
});
});

View File

@ -1,77 +0,0 @@
/**
* 将 Directus 返回的 SolutionType 数据转换为 SolutionTypeView 视图模型
*
* @param raw: 原始的 SolutionType 数据
* @returns 转换后的 SolutionTypeView 对象
*
* ---
*
* @example
* const view = toSolutionTypeView(rawSolutionType);
*/
export function toSolutionTypeView(raw: SolutionType): SolutionTypeView {
const trans = raw.translations?.[0] ?? { name: '' };
return {
id: raw.id,
name: trans.name,
sort: raw?.sort ?? 999,
};
}
/**
* 将 Directus 返回的 Solution 数据转换为 SolutionListView 视图模型
*
* @param raw: 原始的 Solution 数据
* @returns 转换后的 SolutionListView 对象
*
* ---
*
* @example
* const view = toSolutionListView(rawSolution);
*/
export function toSolutionListView(raw: Solution): SolutionListView {
const trans = raw.translations?.[0] ?? {
title: '',
summary: '',
};
const type = isObject<SolutionType>(raw.type)
? toSolutionTypeView(raw.type)
: undefined;
return {
id: raw.id,
title: trans.title,
summary: trans.summary,
solution_type: type,
cover: isObject<DirectusFile>(raw.cover) ? raw.cover.id : raw.cover,
};
}
/**
* 将 Directus 返回的 Solution 数据转换为 SolutionView 视图模型
*
* @param raw: 原始的 Solution 数据
* @returns 转换后的 SolutionView 对象
*
* ---
*
* @example
* const view = toSolutionView(rawSolution);
*/
export function toSolutionView(raw: Solution): SolutionView {
const trans = raw.translations?.[0] ?? {
title: '',
summary: '',
content: '',
};
return {
id: raw.id,
title: trans.title,
summary: trans.summary,
content: trans.content,
createAt: raw.create_at,
};
}

View File

@ -1,23 +0,0 @@
/**
* 文档视图模型
* 用于文档列表渲染的数据结构
*/
export interface ProductDocumentView {
/** 唯一标识符 **/
id: number;
/** 文件UUID **/
fileId: string;
/** 文件名 **/
filename: string;
/** 文档标题 **/
title: string;
/** 文档大小 **/
size: number;
/** 文档链接 **/
url: string;
}

View File

@ -1,14 +0,0 @@
/**
* 常见问题视图模型
* 用于产品页常见问题渲染的数据结构
*/
export interface ProductQuestionView {
/** 唯一标识符 **/
id: number;
/** 问题标题 **/
title: string;
/** 问题内容 **/
content: string;
}

View File

@ -1,29 +0,0 @@
/**
* 产品规格模型
* 用于产品规格渲染的数据结构
*/
export interface ProductSpecView {
/** 唯一标识符 **/
id: number;
/** 规格名称 **/
key: string;
/** 规格值 **/
value: string;
}
/**
* 产品规格表模型
* 用于产品规格表渲染的数据结构
*/
export interface ProductSpecGroupView {
/** 唯一标识符 **/
id: number;
/** 规格组名称 **/
name: string;
/** 规格组 **/
specs: ProductSpecView[];
}

View File

@ -1,38 +0,0 @@
interface ImageView {
id: number;
image: string;
caption: string;
}
/**
* 产品视图模型
* 用于产品详情页(/products/[slug])渲染的数据结构
*/
export interface ProductView {
/** 唯一标识符 **/
id: number;
/** 产品名称 **/
name: string;
/** 产品简介 **/
summary: string;
/** 产品类型 **/
product_type: string;
/** 产品图片 **/
images: ImageView[];
/** 产品详情 **/
description: string;
/** 产品规格 **/
specs: ProductSpecGroupView[];
/** 产品常见问题 **/
faqs: ProductQuestionView[];
/** 产品文档 **/
documents: ProductDocumentView[];
}

View File

@ -1,40 +1,55 @@
<template>
<div class="page-container">
<div v-if="!pending">
<app-breadcrumb class="breadcrumb" :items="breadcrumbItems" />
<div class="content">
<markdown-renderer :content="content.content || ''" />
</div>
<el-skeleton :loading="pending" :rows="10" animated>
<template #default>
<!-- eslint-disable-next-line vue/no-v-html -->
<div class="html-typography" v-html="companyProfile?.content || ''" />
<!-- <div v-if="!hydrated" v-html="companyProfile.content || ''" /> -->
<!-- <div v-else> -->
<!-- <html-renderer -->
<!-- class="html-typography" -->
<!-- :html="companyProfile.content || ''" -->
<!-- /> -->
<!-- </div> -->
<el-divider content-position="left">{{ $t('learn-more') }}</el-divider>
<el-divider content-position="left">{{
$t('learn-more')
}}</el-divider>
<div class="button-group">
<NuxtLink :to="$localePath('/support/contact-us')">
<el-card class="card-button">
<el-icon class="icon" size="80">
<ElIconService />
</el-icon>
<br />
{{ $t('navigation.contact-info') }}
</el-card>
</NuxtLink>
<learn-more-card
:title="$t('navigation.contact-info')"
:icon="ElIconService"
:to="$localePath('/support/contact-us')"
/>
<learn-more-card
:title="$t('navigation.address')"
:icon="ElIconMapLocation"
@click="openMap"
/>
</div>
</div>
<div v-else class="loading">
<el-skeleton :rows="5" animated />
</template>
</el-skeleton>
</div>
</div>
</template>
<script setup lang="ts">
const localePath = useLocalePath();
const hydrated = ref(false);
const breadcrumbItems = [
{ label: $t('navigation.home'), to: localePath('/') },
{ label: $t('navigation.about-us') },
];
const { data, pending, error } = await useCompanyProfile();
const { data, pending, error } = useCompanyProfile();
const content = computed(() => toCompanyProfileView(data.value));
const companyProfile = computed(() => data.value ?? null);
const openMap = () => {
window.open(localePath('/locate'));
};
watch(error, (value) => {
if (value) {
@ -46,6 +61,10 @@
useHead({
title: pageTitle,
});
onMounted(() => {
hydrated.value = true;
});
</script>
<style scoped>
@ -64,14 +83,6 @@
margin-bottom: 2rem;
}
:deep(.markdown-body p) {
text-indent: 2em;
}
:deep(.markdown-body h2) {
text-align: center;
}
:deep(.el-divider__text) {
color: var(--el-color-info);
font-size: 1em;
@ -82,25 +93,7 @@
justify-content: left;
margin-top: 2rem;
margin-left: 2rem;
}
.card-button {
width: 20%;
min-width: 200px;
padding: 20px;
margin: 0 auto;
cursor: pointer;
text-align: center;
font-size: 1.5em;
}
.card-button:hover {
transform: translateY(-4px);
box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}
.icon {
padding: 10px;
gap: 2rem;
}
.loading {
@ -109,4 +102,16 @@
align-items: center;
margin-top: 1rem;
}
@media (max-width: 768px) {
.button-group {
align-items: center;
margin-left: 0;
gap: 0.5rem;
}
.breadcrumb {
display: none;
}
}
</style>

View File

@ -4,11 +4,17 @@
<h1 class="page-title">{{ $t('navigation.downloads') }}</h1>
<app-breadcrumb class="breadcrumb" :items="breadcrumbItems" />
</div>
<div v-if="!pending" class="page-content">
<div class="page-content">
<el-skeleton
:loading="pending"
:rows="6"
animated
:throttle="{ leading: 500, trailing: 500 }"
>
<template #default>
<file-card :file-id="id" :file="file" />
</div>
<div v-else>
<el-skeleton :rows="6" animated />
</template>
</el-skeleton>
</div>
</div>
</template>
@ -66,4 +72,10 @@
.breadcrumb {
margin-left: auto;
}
@media (max-width: 768px) {
.breadcrumb {
display: none;
}
}
</style>

View File

@ -1,24 +1,14 @@
<template>
<div class="homepage">
<homepage-carousel :homepage-data="homepageData" :pending="pending" />
<homepage-product-section
:homepage-data="homepageData"
:pending="pending"
/>
<homepage-solution-section
:homepage-data="homepageData"
:pending="pending"
/>
<homepage-carousel :homepage-data="data" :pending="pending" />
<homepage-product-section :homepage-data="data" :pending="pending" />
<homepage-solution-section :homepage-data="data" :pending="pending" />
</div>
</template>
<script setup lang="ts">
const { data, pending, error } = await useHomepage();
const homepageData = computed(() => {
return toHomepageView(data.value);
});
const pageTilte = $t('page-title.homepage');
watch(error, (value) => {

28
app/pages/locate.vue Normal file
View File

@ -0,0 +1,28 @@
<template>
<div class="page-container">
<h1>{{ $t('redirecting') }}</h1>
</div>
</template>
<script setup lang="ts">
onMounted(async () => {
const platform = await getAutoMappedService();
// // ✔ 移动端能正常跳转
window.location.href = platform;
});
</script>
<style scoped>
.page-container {
display: flex;
justify-content: center;
align-items: center;
min-height: 80vh;
}
h1 {
font-size: 1.5rem;
font-weight: bold;
}
</style>

View File

@ -1,6 +1,5 @@
<template>
<div class="page-container">
<div v-if="!pending">
<div v-if="product">
<!-- 面包屑导航 -->
<app-breadcrumb class="breadcrumb" :items="breadcrumbItems" />
@ -19,15 +18,6 @@
/>
</div>
</div>
<div v-else class="loading">
<el-skeleton style="--el-skeleton-circle-size: 400px">
<template #template>
<el-skeleton-item variant="circle" />
</template>
</el-skeleton>
<el-skeleton :rows="5" animated />
</div>
</div>
</template>
<script setup lang="ts">
@ -37,16 +27,7 @@
// 获取路由参数
const id = route.params.slug as string;
const { data, pending, error } = await useProduct(id);
const rawProduct = computed(() => data.value ?? null);
const product = computed(() => {
if (rawProduct.value === null) {
return null;
}
return toProductView(rawProduct.value);
});
const { data: product, error } = await useProduct(id);
const breadcrumbItems = computed(() => [
{ label: $t('navigation.home'), to: localePath('/') },
@ -62,8 +43,8 @@
// SEO
usePageSeo({
title: product.value.name || $t('page-title.products'),
description: product.value.summary || '',
title: product.value?.name || $t('page-title.products'),
description: product.value?.summary || '',
});
</script>

View File

@ -1,10 +1,35 @@
<template>
<div class="page-container">
<div class="page-header">
<div>
<h1 class="page-title">{{ $t('our-products') }}</h1>
<p class="page-subtitle">
{{ $t('products-desc') }}{{ $t('find-discontinued-products') }}
</p>
</div>
<app-breadcrumb class="breadcrumb" :items="breadcrumbItems" />
</div>
<div v-if="!pending" class="page-content">
<div>
<el-skeleton
animated
:loading="pending"
:throttle="{ leading: 500, trailing: 500 }"
>
<template #template>
<div v-for="i in 3" :key="i" class="products-container">
<el-skeleton-item variant="h1" class="skeleton-collapse" />
<div class="skeleton-group-list">
<el-skeleton-item
v-for="j in 3"
:key="j"
variant="rect"
class="skeleton-card"
/>
</div>
</div>
</template>
<template #default>
<div class="products-container">
<el-collapse v-model="activeNames" class="product-collapse">
<el-collapse-item
@ -26,9 +51,8 @@
</el-collapse-item>
</el-collapse>
</div>
</div>
<div v-else>
<el-skeleton :rows="6" animated />
</template>
</el-skeleton>
</div>
</div>
</template>
@ -37,7 +61,7 @@
const localePath = useLocalePath();
const { getImageUrl } = useDirectusImage();
const { data, pending, error } = await useProductList();
const { data: products, pending, error } = await useProductList();
const activeNames = ref<string[]>([]);
@ -46,14 +70,6 @@
{ label: $t('navigation.products') },
];
const productsRaw = computed(() => data.value ?? []);
const products = computed(() =>
productsRaw.value.map((item) => toProductListView(item))
);
logger.debug('产品列表数据: ', products.value);
// 按类型分组
const groupedProducts = computed(() => {
const groups: Record<string, { data: ProductListView[]; sort: number }> =
@ -110,13 +126,18 @@
.page-header {
display: flex;
margin-bottom: 1rem;
}
.page-title {
font-size: 2rem;
font-weight: bold;
color: var(--el-color-primary);
margin-bottom: 1rem;
}
.page-subtitle {
font-size: 0.8rem;
color: var(--el-text-color-secondary);
}
.breadcrumb {
@ -148,6 +169,50 @@
justify-content: flex-start;
}
.skeleton-collapse {
height: 50px;
width: 100%;
}
.skeleton-group-list {
display: flex;
flex-wrap: wrap;
gap: 40px;
justify-content: flex-start;
margin-bottom: 2rem;
}
.skeleton-card {
width: 30%;
height: 250px;
margin-right: 1rem;
}
@media (max-width: 1200px) {
.skeleton-card {
width: 45%;
}
}
@media (max-width: 768px) {
.group-list {
justify-content: center;
align-items: center;
}
.skeleton-group-list {
justify-content: center;
align-items: center;
}
.skeleton-card {
width: 90%;
}
.breadcrumb {
display: none;
}
}
:deep(.el-collapse-item__header) {
padding: 30px auto;
font-size: 1.5rem;

View File

@ -1,11 +1,23 @@
<template>
<div class="search-page">
<search-header v-model="keyword" />
<div v-if="loading" class="search-state">
<el-skeleton :rows="4" animated />
</div>
<search-tabs v-else-if="hasResults" :search-items="searchItems" />
<div v-else class="search-state">
<div class="search-state">
<el-skeleton
:loading="loading"
animated
:throttle="{ leading: 500, trailing: 500 }"
>
<template #template>
<el-skeleton-item
v-for="i in 10"
:key="i"
variant="rect"
class="skeleton-item"
/>
</template>
<template #default>
<search-tabs v-if="hasResults" :search-items="searchItems" />
<div v-else>
<el-empty
:description="
route.query.query
@ -14,6 +26,9 @@
"
/>
</div>
</template>
</el-skeleton>
</div>
</div>
</template>
@ -21,58 +36,36 @@
// i18n相关
const { t } = useI18n();
const { getDirectusLocale } = useLocalizations();
const directusLocale = getDirectusLocale();
const locale = getDirectusLocale();
// 路由相关
const route = useRoute();
// 搜索相关
const { search } = useMeilisearch();
const keyword = ref('');
if (typeof route.query.query === 'string' && route.query.query.trim()) {
keyword.value = route.query.query;
}
const {
data: sections,
data: searchItems,
pending: loading,
error,
refresh,
} = await useAsyncData(
() => `search-${directusLocale}-${route.query.query ?? ''}`,
async () => {
const q = String(route.query.query ?? '').trim();
if (!q) return [];
return await search(q, { limit: 12 }, directusLocale);
} = useAsyncData(`meilisearch-${keyword.value}-${locale}`, async () => {
try {
const data = await $fetch(`/api/search?query=${keyword.value}`, {
headers: { 'x-locale': locale },
});
return data;
} catch (error) {
logger.error('Error fetching search results: ', error);
throw error;
}
);
});
// 空Section过滤
const filteredSections = computed(() =>
sections.value.filter((section) => section.hits.length > 0)
);
const typeMap = {
products: 'products',
solutions: 'solutions',
questions: 'questions',
product_documents: 'product_documents',
} as const;
// 展平hits
const hits = computed(() =>
filteredSections.value.flatMap((section) => {
const type = typeMap[section.rawIndex as keyof typeof typeMap];
if (!type) return [];
return section.hits.map((hit) => ({ type, content: hit }));
})
);
const searchItems = computed(() =>
hits.value.map((hit) => {
return toSearchItemView(hit.content, hit.type);
})
);
const hasResults = computed(() =>
filteredSections.value.some((section) => section.hits.length > 0)
);
const hasResults = computed(() => searchItems.value.length > 0);
watch(
() => route.query.query,
@ -84,6 +77,13 @@
}
);
watch(
() => locale,
async () => {
await refresh();
}
);
watch(error, (value) => {
if (value) {
logger.error('数据获取失败: ', value);
@ -111,7 +111,11 @@
.search-state {
display: flex;
justify-content: center;
padding: 3rem 0;
}
.skeleton-item {
height: 80px;
margin-bottom: 1rem;
}
@media (max-width: 640px) {

View File

@ -1,6 +1,5 @@
<template>
<div class="page-container">
<div v-if="!pending">
<div v-if="solution">
<div class="page-header">
<app-breadcrumb class="breadcrumb" :items="breadcrumbItems" />
@ -16,10 +15,6 @@
/>
</div>
</div>
<div v-else class="loading">
<el-skeleton :rows="5" animated />
</div>
</div>
</template>
<script setup lang="ts">
@ -29,14 +24,7 @@
// 获取路由参数
const id = route.params.slug as string;
const { data, pending, error } = await useSolution(id);
const solution = computed(() => {
if (!data.value) {
return null;
}
return toSolutionView(data.value);
});
const { data: solution, error } = await useSolution(id);
const breadcrumbItems = computed(() => [
{ label: $t('navigation.home'), to: localePath('/') },
@ -51,8 +39,8 @@
});
usePageSeo({
title: solution.value.title || $t('page-title.solutions'),
description: solution.value.summary || '',
title: solution.value?.title || $t('page-title.solutions'),
description: solution.value?.summary || '',
});
</script>

View File

@ -1,10 +1,33 @@
<template>
<div class="page-container">
<div class="page-header">
<div>
<h1 class="page-title">{{ $t('learn-our-solutions') }}</h1>
<p class="page-subtitle">{{ $t('solutions-desc') }}</p>
</div>
<app-breadcrumb class="breadcrumb" :items="breadcrumbItems" />
</div>
<div v-if="!pending" class="solutions-container">
<div class="solutions-container">
<el-skeleton
:loading="pending"
animated
:throttle="{
leading: 500,
trailing: 500,
}"
>
<template #template>
<div class="skeleton-group-list">
<el-skeleton-item
v-for="i in 12"
:key="i"
variant="rect"
class="skeleton-card"
/>
</div>
</template>
<template #default>
<el-tabs v-model="activeName" class="solutions-tabs">
<el-tab-pane :label="$t('all')" name="all">
<div class="solution-list">
@ -36,9 +59,8 @@
</div>
</el-tab-pane>
</el-tabs>
</div>
<div v-else>
<el-skeleton :rows="6" animated />
</template>
</el-skeleton>
</div>
</div>
</template>
@ -52,12 +74,9 @@
{ label: $t('navigation.solutions') },
];
const { data, pending, error } = await useSolutionList();
const { data, pending, error } = useSolutionList();
const solutionsRaw = computed(() => data.value ?? []);
const solutions = computed(() =>
solutionsRaw.value.map((item) => toSolutionListView(item))
);
const solutions = computed(() => data.value ?? []);
const activeName = ref<string>('all');
@ -99,15 +118,20 @@
.page-header {
display: flex;
margin-bottom: 1rem;
}
.page-title {
font-size: 2rem;
font-weight: bold;
margin-bottom: 1rem;
color: var(--el-color-primary);
}
.page-subtitle {
font-size: 0.8rem;
color: var(--el-text-color-secondary);
}
.breadcrumb {
margin-left: auto;
}
@ -119,4 +143,38 @@
margin-bottom: 2rem;
gap: 40px;
}
.skeleton-group-list {
display: flex;
flex-wrap: wrap;
gap: 20px;
justify-content: flex-start;
margin-bottom: 2rem;
}
.skeleton-card {
width: 30%;
height: 200px;
}
@media (max-width: 1200px) {
.skeleton-card {
width: 45%;
}
}
@media (max-width: 768px) {
.skeleton-group-list {
justify-content: center;
align-items: center;
}
.skeleton-card {
width: 90%;
}
.breadcrumb {
display: none;
}
}
</style>

View File

@ -6,25 +6,40 @@
<app-breadcrumb class="breadcrumb" :items="breadcrumbItems" />
</div>
<div v-if="!pending" class="page-content">
<markdown-renderer :content="content.content || ''" />
</div>
<div v-else class="loading">
<el-skeleton :rows="5" animated />
<div class="page-content">
<el-skeleton
:rows="10"
:loading="pending"
animated
:throttle="{ leading: 500, trailing: 500 }"
>
<template #default>
<!-- eslint-disable-next-line vue/no-v-html -->
<div class="html-typography" v-html="contactInfo?.content || ''" />
<!-- <div v-if="!hydrated" v-html="contactInfo?.content || ''" /> -->
<!-- <div v-else> -->
<!-- <html-renderer -->
<!-- class="html-typography" -->
<!-- :html="contactInfo?.content || ''" -->
<!-- /> -->
<!-- </div> -->
</template>
</el-skeleton>
</div>
</div>
</template>
<script setup lang="ts">
const localePath = useLocalePath();
const hydrated = ref(false);
const breadcrumbItems = [
{ label: $t('navigation.home'), to: localePath('/') },
{ label: $t('navigation.support'), to: localePath('/support') },
{ label: $t('navigation.contact-info') },
];
const { data, pending, error } = await useContactInfo();
const { data, pending, error } = useContactInfo();
const content = computed(() => toContactInfoView(data.value));
const contactInfo = computed(() => data.value ?? null);
watch(error, (value) => {
if (value) {
@ -36,6 +51,10 @@
usePageSeo({
title: pageTitle,
});
onMounted(() => {
hydrated.value = true;
});
</script>
<style scoped>
@ -68,4 +87,10 @@
:deep(.markdown-body ul) {
list-style-type: none;
}
@media (max-width: 768px) {
.breadcrumb {
display: none;
}
}
</style>

View File

@ -1,21 +1,60 @@
<template>
<div class="page-container">
<div v-if="pending">
<el-skeleton :rows="5" animated />
</div>
<div v-else>
<div>
<support-tabs model-value="documents" />
<div class="page-header">
<h1 class="page-title">{{ $t('navigation.documents') }}</h1>
<app-breadcrumb class="breadcrumb" :items="breadcrumbItems" />
</div>
<div class="page-content">
<product-filter
<document-filter
v-model="filters"
:product-type-options="productTypeOptions"
:product-options="productOptions"
:document-type-options="documentTypeOptions"
/>
<document-list :documents="filteredDocuments" />
<el-skeleton
:loading="pending"
animated
:throttle="{
leading: 500,
trailing: 500,
}"
>
<template #template>
<div class="flex flex-col gap-xl">
<el-skeleton-item
variant="rect"
style="width: 100%; height: 100px"
/>
<el-skeleton-item
v-for="i in 10"
:key="i"
variant="h1"
style="height: 60px"
/>
</div>
</template>
<template #default>
<document-list
:documents="paginatedDocuments"
:show-category="
filters.selectedDocumentType === null ||
filters.selectedDocumentType === undefined
"
/>
<el-pagination
v-model:current-page="page"
class="justify-center pagination-container"
layout="prev, pager, next"
hide-on-single-page
:page-size="documentsPerPage"
:total="filteredDocuments.length"
/>
</template>
</el-skeleton>
</div>
</div>
</div>
@ -30,16 +69,36 @@
];
const filters = reactive({
selectedType: null as number | null,
selectedProduct: null as number | null,
selectedDocumentType: null as string | null,
selectedProductType: null as string | null,
selectedProduct: null as string | null,
keyword: '',
});
const { data, pending, error } = await useDocumentList();
const page = ref(1);
const documentsPerPage = 10;
const documents = computed(
() => data?.value.map((item) => toDocumentListView(item)) ?? []
);
const { data, pending, error } = useDocumentList();
const documents = computed(() => data.value ?? []);
const documentTypeOptions = computed(() => {
const types: DocumentTypeView[] = [];
documents.value.forEach((doc: DocumentListView) => {
if (!types.some((item) => item.id === doc.type.id)) {
if (doc.type.id === '-1') {
types.push({
id: '-1',
name: $t('product-filter.misc'),
});
} else {
types.push(doc.type);
}
}
});
return types;
});
const productTypeOptions = computed(() => {
const types: DocumentListProductType[] = [];
@ -56,13 +115,13 @@
});
const productOptions = computed(() => {
if (!filters.selectedType) return [];
if (!filters.selectedProductType) return [];
const products: DocumentListProduct[] = [];
documents.value.forEach((doc: DocumentListView) => {
doc.products?.forEach((product: DocumentListProduct) => {
if (
product.type.id === filters.selectedType &&
product.type.id === filters.selectedProductType &&
!products.some((item) => item.id === product.id)
) {
products.push(product);
@ -85,19 +144,30 @@
(product: DocumentListProduct) =>
product.id === filters.selectedProduct
)
: filters.selectedType
: filters.selectedProductType
? doc.products?.some(
(product: DocumentListProduct) =>
product.type?.id === filters.selectedType
product.type?.id === filters.selectedProductType
)
: true;
return matchProduct;
const matchDocumentType = filters.selectedDocumentType
? doc.type.id === filters.selectedDocumentType
: true;
return matchProduct && matchDocumentType;
});
});
const paginatedDocuments = computed(() => {
return filteredDocuments.value.slice(
(page.value - 1) * documentsPerPage,
page.value * documentsPerPage
);
});
watch(
() => filters.selectedType,
() => filters.selectedProductType,
() => {
filters.selectedProduct = null;
}
@ -137,12 +207,6 @@
margin-left: auto;
}
.document-category {
padding: 0rem 2rem;
gap: 4px;
margin-bottom: 0.5rem;
}
.page-content {
padding: 1rem 2rem 2rem;
}
@ -157,4 +221,41 @@
height: 40px;
font-size: 0.9rem;
}
.pagination-container {
margin-top: 2rem;
}
@media (max-width: 768px) {
.breadcrumb {
display: none;
}
}
:deep(.el-pagination) {
.btn-prev,
.btn-next {
.el-icon {
font-size: 24px;
}
}
.el-pager {
gap: 0.5rem;
}
.el-pager li {
font-size: 1rem;
/* border: 1px solid #409eff; */
border-radius: 50%;
&:hover {
background-color: #ecf5ff;
}
&.is-active {
background-color: var(--el-color-primary);
color: #fff;
}
}
}
</style>

View File

@ -1,9 +1,5 @@
<template>
<div class="page-container">
<div v-if="pending" class="flex justify-center items-center h-64">
<el-skeleton :rows="6" animated />
</div>
<div v-else>
<support-tabs model-value="faq" />
<div class="page-header">
<h1 class="page-title">{{ $t('navigation.faq') }}</h1>
@ -11,38 +7,89 @@
</div>
<div class="page-content">
<product-filter
<question-filter
v-model="filters"
:product-type-options="productTypeOptions"
:product-options="productOptions"
:question-type-options="questionTypeOptions"
/>
<question-list :questions="filteredQuestions" />
<el-skeleton
:loading="pending"
animated
:throttle="{ leading: 500, trailing: 500 }"
>
<template #template>
<div class="flex flex-col gap-xl">
<el-skeleton-item
v-for="i in 10"
:key="i"
variant="h1"
style="height: 80px"
/>
</div>
</template>
<template #default>
<question-list :questions="paginatedQuestions" />
<el-pagination
v-model:current-page="page"
class="justify-center pagination-container"
layout="prev, pager, next"
hide-on-single-page
:page-size="questionsPerPage"
:total="filteredQuestions.length"
/>
</template>
</el-skeleton>
</div>
</div>
</template>
<script setup lang="ts">
const localePath = useLocalePath();
const route = useRoute();
const filters = reactive({
selectedType: null as number | null,
selectedProduct: null as number | null,
selectedQuestionType: null as string | null,
selectedProduct: null as string | null,
selectedProductType: null as string | null,
keyword: '',
});
const page = ref(1);
const questionsPerPage = 10;
const focusQuestionId = ref<string | null>(
route.query.focus as string | null
);
const breadcrumbItems = [
{ label: $t('navigation.home'), to: localePath('/') },
{ label: $t('navigation.support'), to: localePath('/support') },
{ label: $t('navigation.faq') },
];
const { data, pending, error } = await useQuestionList();
const { data, pending, error } = useQuestionList();
const questions = computed(
() => data.value.map((item) => toQuestionListView(item)) ?? null
);
const questions = computed(() => data.value ?? []);
const questionTypeOptions = computed(() => {
const types: QuestionTypeView[] = [];
questions.value.forEach((q: QuestionListView) => {
if (!types.some((t) => t.id === q.type.id)) {
if (q.type.id === '-1') {
types.push({
id: '-1',
name: $t('product-filter.misc'),
});
} else {
types.push(q.type);
}
}
});
return types;
});
const productTypeOptions = computed(() => {
const types: QuestionListProductType[] = [];
@ -58,12 +105,12 @@
});
const productOptions = computed(() => {
if (!filters.selectedType) return [];
if (!filters.selectedProductType) return [];
const products: QuestionListProduct[] = [];
questions.value.forEach((q: QuestionListView) => {
q.products.forEach((product: QuestionListProduct) => {
if (
product.type.id === filters.selectedType &&
product.type.id === filters.selectedProductType &&
!products.some((p) => p.id === product.id)
) {
products.push(product);
@ -85,19 +132,51 @@
(product: QuestionListProduct) =>
product.id === filters.selectedProduct
)
: filters.selectedType
: filters.selectedProductType
? question.products?.some(
(product: QuestionListProduct) =>
product.type.id === filters.selectedType
product.type.id === filters.selectedProductType
)
: true;
return matchProduct;
const matchQuestionType = filters.selectedQuestionType
? question.type.id === filters.selectedQuestionType
: true;
return matchProduct && matchQuestionType;
});
});
const paginatedQuestions = computed(() => {
const start = (page.value - 1) * questionsPerPage;
const end = page.value * questionsPerPage;
return filteredQuestions.value.slice(start, end);
});
watch(
() => filters.selectedType,
focusQuestionId,
async (focusId) => {
if (!focusId) return;
if (!import.meta.client) return;
await nextTick();
const question = filteredQuestions.value.find((q) => q.id === focusId);
if (!question) return;
const targetIndex = filteredQuestions.value.indexOf(question);
const targetPage = Math.floor(targetIndex / questionsPerPage) + 1;
onMounted(() => {
if (page.value !== targetPage) {
page.value = targetPage;
}
});
},
{ immediate: true }
);
watch(
() => filters.selectedProductType,
() => {
filters.selectedProduct = null;
}
@ -140,4 +219,40 @@
.page-content {
padding: 1rem 2rem 2rem;
}
.pagination-container {
margin-top: 2rem;
}
@media (max-width: 768px) {
.breadcrumb {
display: none;
}
}
:deep(.el-pagination) {
.btn-prev,
.btn-next {
.el-icon {
font-size: 24px;
}
}
.el-pager {
gap: 0.5rem;
}
.el-pager li {
font-size: 1rem;
/* border: 1px solid #409eff; */
border-radius: 50%;
&:hover {
background-color: #ecf5ff;
}
&.is-active {
background-color: var(--el-color-primary);
color: #fff;
}
}
}
</style>

View File

@ -137,5 +137,9 @@
grid-template-columns: 1fr;
gap: 20px;
}
.breadcrumb {
display: none;
}
}
</style>

45
app/utils/autoMap.ts Normal file
View File

@ -0,0 +1,45 @@
async function testSpeed(url: string, timeout = 1500) {
const start = performance.now();
try {
await Promise.race([
fetch(url, { method: 'HEAD', mode: 'no-cors' }),
new Promise((_, reject) => setTimeout(() => reject('timeout'), timeout)),
]);
return performance.now() - start;
} catch {
return Infinity; // unreachable or timed out
}
}
async function selectBestMap() {
const testTargets = {
// amap: 'https://www.amap.com/favicon.ico',
baidu: 'https://map.baidu.com/favicon.ico',
google: 'https://maps.google.com/favicon.ico',
};
const results: Record<string, number> = {};
for (const key in testTargets) {
results[key] = await testSpeed(testTargets[key]);
}
logger.debug(results);
// 根据延迟排序,选择最稳最快的平台
return Object.entries(results).sort((a, b) => a[1] - b[1])[0][0];
}
export async function getAutoMappedService(): Promise<string> {
const target = {
// amap: 'https://surl.amap.com/2dYNorIJ1dgoN',
baidu: 'https://j.map.baidu.com/f9/c3x',
google: 'https://maps.app.goo.gl/9LqvMwEq7VaRkqnM6',
};
const fastestMap = await selectBestMap();
return target[fastestMap];
}

View File

@ -1,4 +1,5 @@
import { expect, test, describe } from 'vitest';
import { formatFileSize, getFileExtension, formatFileExtension } from './file';
/**
* 单元测试: formatFileSize

View File

@ -0,0 +1,30 @@
import type { HtmlRenderMap } from '@/composables/useHtmlRenderer';
import { h } from 'vue';
import MarkdownTable from '@/components/shared/MarkdownTable.vue';
export const defaultHtmlRenderMap: HtmlRenderMap = {
h1: (_, children) => h('h1', {}, children),
h2: (_, children) => h('h2', {}, children),
p: (_, children) => h('p', {}, children),
// table: (_, children) => h('div', {}, [h('table', {}, children)]),
table: (node) => {
const { headers, rows } = parseHtmlTable(node);
return h(
'div',
{},
h(MarkdownTable, {
headers,
rows,
})
);
},
img: (node) =>
h('img', {
src: node.attribs?.src,
}),
};

View File

@ -18,17 +18,3 @@ export function renderMarkdown(content: string): string {
return dirtyHtml;
}
export function convertMedia(content: string): string {
// 通过正则表达式替换Markdown中的图片链接
// ![alt text](image-url) -> ![alt text](strapiMedia(image-url))
if (!content) return '';
const contentWithAbsoluteUrls = content.replace(
/!\[([^\]]*)\]\((\/uploads\/[^)]+)\)/g,
(_, alt, url) => `![${alt}](${useStrapiMedia(url)})`
);
return contentWithAbsoluteUrls;
}

90
app/utils/parseTable.ts Normal file
View File

@ -0,0 +1,90 @@
import type { Element, Node } from 'domhandler';
export interface ParsedTable {
headers: string[];
rows: Record<string, string>[];
}
const isElement = (n: Node): n is Element => n.type === 'tag';
export function parseHtmlTable(table: Element): ParsedTable {
if (table.name !== 'table') {
throw new Error('parseHtmlTable: node is not <table>');
}
// 获取 table 下的所有 tag 子节点
const getChildren = (node: Node): Element[] =>
isElement(node) ? node.children.filter(isElement) : [];
// ---- 找 thead / tbody ----
const children = getChildren(table);
const thead = children.find((n) => n.name === 'thead');
const tbody = children.find((n) => n.name === 'tbody');
if (!tbody) {
return { headers: [], rows: [] };
}
const bodyRows = getChildren(tbody).filter((n) => n.name === 'tr');
if (bodyRows.length === 0) {
return { headers: [], rows: [] };
}
// ---- 1. 表头 ----
let headerCells: Element[] = [];
if (thead) {
// 如果 Directus 有 thead一般不会
const headerRow = getChildren(thead).find((n) => n.name === 'tr');
headerCells = headerRow
? getChildren(headerRow).filter((n) => n.name === 'th' || n.name === 'td')
: [];
} else {
// Directus 情况:没有 thead → 用 tbody 第一行作为 header
headerCells = getChildren(bodyRows[0]).filter(
(n) => n.name === 'th' || n.name === 'td'
);
}
logger.info(headerCells);
const headers = headerCells.map((cell, i) => {
const text = cell.children
.filter((c) => c.type === 'text')
.map((t) => t.data.trim())
.filter(Boolean)
.join('');
return text || `${i + 1}`;
});
// ---- 2. 数据行 ----
// 如果没有 thead则跳过第一行它是 header
const dataRows = thead ? bodyRows : bodyRows.slice(1);
const rows = dataRows.map((row) => {
const cells = getChildren(row).filter(
(n) => n.name === 'td' || n.name === 'th'
);
const record: Record<string, string> = {};
headers.forEach((header, i) => {
const cell = cells[i];
if (!cell) {
record[header] = '';
} else {
const text = cell.children
.filter((c) => c.type === 'text')
.map((t) => t.data.trim())
.filter(Boolean)
.join('');
record[header] = text;
}
});
return record;
});
logger.info(headers, rows);
return { headers, rows };
}

View File

@ -1,17 +0,0 @@
import { pinyin } from 'pinyin-pro';
/**
* 将汉语文本转换为拼音形式
*/
export function transliterateText(input: string): string {
if (!input) return '';
const text = input.normalize('NFKC').trim();
// 检测是否包含中文字符
if (/[\u4e00-\u9fa5]/.test(text)) {
return pinyin(text, { toneType: 'none', type: 'array' }).join('');
}
// 否则返回原文本
return text;
}

View File

@ -10,6 +10,7 @@
"result-count": "{count} results",
"no-results": "No results found for \"{query}\".",
"no-query": "Enter a keyword to start searching.",
"section": "Section",
"untitled": "Untitled",
"sections": {
"product": "Products",
@ -22,8 +23,8 @@
"company-name": "Jinshen Machinary Manufacturing Co., Ltd.",
"company-description": "We specialize in manufacturing a range of paper tube and can equipment, integrating design, manufacturing, sales, and service.",
"learn-more": "Learn More",
"products-desc": "We provide high-quality product solutions to meet various business needs.",
"solutions-desc": "Providing customized technology solutions for enterprises to accelerate digital transformation.",
"products-desc": "We provide the latest products an instant service support to meet various business needs of our customers.",
"solutions-desc": "We offer diversified technical solutions for enterprises, supporting various fields such as industry and packaging.",
"support-desc": "24/7 professional technical support to ensure stable operation of your business.",
"quick-links": "Quick Links",
"utilities": "Utilities",
@ -37,7 +38,8 @@
"downloads": "Downloads",
"faq": "FAQ",
"documents": "Documents",
"calculator": "Calculator"
"calculator": "Calculator",
"address": "Company Address"
},
"contact-info": "Contact Us",
"telephone": "Telephone",
@ -61,7 +63,9 @@
"back-to-home": "Back to Home",
"no-content-available": "No detailed information available",
"loading": "Loading...",
"our-products": "Our Products",
"our-products": "Our Latest Products",
"find-discontinued-products": "To find discontinued products, please use the search function.",
"product-discontinued-warning": "Product is discontinued and may no longer receive immediate support or updates",
"learn-our-solutions": "Learn Our Solutions",
"all": "All",
"support-page-desc": "Zhejiang Jinshen Machinery Manufacturing Co., Ltd is committed to providing high-quality products and services to our customers. For products such as paper tube machines, slitting machines, and paper straw equipment, we offer comprehensive after-sales support to ensure our customers can use our products with confidence.",
@ -77,7 +81,12 @@
"keyword": "Keyword",
"select-product-type": "Select product type",
"select-product-model": "Select product model",
"enter-keyword": "Enter keyword"
"enter-keyword": "Enter keyword",
"question-type": "Question Type",
"select-question-type": "Select question type",
"document-type": "Document Type",
"select-document-type": "Select document type",
"misc": "Misc"
},
"document-meta": {
"size": "Size",
@ -118,5 +127,6 @@
"specs": "Specifications",
"faq": "FAQ",
"documents": "Documents"
}
},
"redirecting": "Redirecting..."
}

131
i18n/locales/es.json Normal file
View File

@ -0,0 +1,131 @@
{
"back": "Volver",
"not-found": "Página no encontrada",
"search-placeholder": "Buscar...",
"search": {
"title": "Búsqueda en el sitio",
"head-title": "Búsqueda",
"search-button": "Buscar",
"results-for": "Resultados de la búsqueda para \"{query}\"",
"result-count": "{count} resultados",
"no-results": "No se encontraron coincidencias para \"{query}\".",
"no-query": "Ingrese una palabra clave para comenzar a buscar.",
"section": "sección",
"untitled": "sin título",
"sections": {
"product": "Productos",
"solution": "Soluciones",
"faq": "FAQ",
"document": "Documentaciones",
"default": "Otros contenidos"
}
},
"company-name": "Jinshen Machinary Manufacturing Co., Ltd.",
"company-description": "Especializado en la producción de una serie de equipos de tubos y latas de papel, integrando diseño, fabricación, ventas y servicio.",
"learn-more": "Saber más",
"products-desc": "Ofrecemos los últimos productos y un servicio de asistencia instantáneo para satisfacer las diversas necesidades comerciales de nuestros clientes.",
"solutions-desc": "Ofrecemos soluciones técnicas diversificadas para empresas, prestando apoyo en diversos campos, como la industria y el embalaje.",
"support-desc": "Soporte técnico profesional 24/7, asegurando la estabilidad de su negocio.",
"quick-links": "Enlaces rápidos",
"utilities": "Herramientas útiles",
"navigation": {
"home": "Inicio",
"products": "Productos",
"solutions": "Soluciones",
"support": "Soporte",
"about-us": "Sobre nosotros",
"contact-info": "Información de contacto",
"downloads": "Descargas",
"faq": "FAQ",
"documents": "Documentaciones",
"calculator": "Herramienta de cálculo de tubos de papel",
"address": "Dirección de la empresa"
},
"contact-info": "Contáctenos",
"telephone": "Teléfono",
"email": "Correo electrónico",
"address": "Dirección",
"company-address": "No. 689 Qiushi Road, Wutong Industrial Zone, Tongxiang City, Zhejiang Province, China",
"follow-us": "Síguenos",
"all-rights-reserved": "All rights reserved",
"privacy-policy": "Política de privacidad",
"terms-of-service": "Términos del servicio",
"sitemap": "Mapa del sitio",
"product-details": "Detalles del producto",
"product-not-found": "Producto no encontrado",
"product-not-found-desc": "Lo sentimos, el producto que busca no existe o ha sido eliminado.",
"back-to-products": "Volver a la lista de productos",
"solution-not-found": "Solución no encontrada",
"solution-not-found-desc": "Lo sentimos, la solución que busca no existe o ha sido eliminada.",
"back-to-solutions": "Volver a la lista de soluciones",
"page-not-found": "Página no encontrada",
"page-not-found-desc": "Lo sentimos, la página que busca no existe o ha sido eliminada.",
"back-to-home": "Volver al inicio",
"no-content-available": "No hay información disponible",
"loading": "Cargando...",
"our-products": "Nuestros últimos productos",
"find-discontinued-products": "Para encontrar productos descatalogados, utilice la función de búsqueda.",
"product-discontinued-warning": "Este producto ha sido descontinuado y puede que ya no reciba soporte o actualizaciones inmediatas.",
"learn-our-solutions": "Aprenda sobre nuestras soluciones",
"all": "Todo",
"support-page-desc": "Zhejiang Jinshen Machinery Manufacturing Co., Ltd se dedica a proporcionar productos y servicios de alta calidad a los clientes. Para máquinas de tubos de papel, máquinas de corte y pajitas de papel, ofrecemos un servicio postventa integral para garantizar que los clientes puedan usar nuestros productos con confianza.",
"support-card-desc": {
"faq": "Hemos compilado respuestas a preguntas frecuentes para ayudarle a resolver dudas rápidamente.",
"documents": "Proporcionamos manuales de productos, especificaciones técnicas y otros documentos para la comodidad del usuario.",
"contact-info": "Contáctenos por teléfono o correo electrónico, y le brindaremos servicio presencial."
},
"product-filter": {
"product-type": "Tipo de producto",
"product-model": "Modelo del producto",
"keyword": "Palabra clave",
"select-product-type": "Seleccione el tipo de producto",
"select-product-model": "Seleccione modelo de producto",
"enter-keyword": "Ingrese palabra clave",
"misc": "Varios",
"document-type": "Tipo de documento",
"select-document-type": "Seleccionar tipo de documento",
"question-type": "Tipo de pregunta",
"select-question-type": "Seleccionar tipo de pregunta"
},
"document-meta": {
"size": "Tamaño",
"format": "Formato",
"type": "Tipo",
"upload-at": "Fecha de carga"
},
"document-action": {
"download": "Descargar",
"open-in-new-tab": "Abrir en una nueva pestaña",
"preview": "Vista previa"
},
"mobile-menu": {
"title": "Menú",
"navigation": "Navegación del sitio",
"utilities": "Herramientas útiles"
},
"homepage": {
"recommended-products": "Productos recomendados",
"recommended-products-desc": "Explore nuestros productos seleccionados para satisfacer sus diversas necesidades. Ya sea tecnología innovadora o diseño clásico, ofrecemos opciones de calidad para usted.",
"recommended-solutions": "Soluciones recomendadas",
"recommended-solutions-desc": "Aprenda sobre nuestras soluciones personalizadas, que le ayudarán a optimizar sus procesos de negocio y mejorar la eficiencia."
},
"page-title": {
"homepage": "Página principal",
"products": "Productos",
"solutions": "Soluciones",
"support": "Soporte",
"faq": "FAQ",
"documents": "Documentos",
"contact-us": "Contáctenos",
"download": "Descarga de documentos",
"preview": "Vista previa de documentos",
"about-us": "Sobre nosotros"
},
"product-tab": {
"details": "Detalles",
"specs": "Especificaciones",
"faq": "FAQ",
"documents": "Documentos"
},
"redirecting": "Redirigiendo..."
}

131
i18n/locales/ru.json Normal file
View File

@ -0,0 +1,131 @@
{
"back": "Назад",
"not-found": "Страница не найдена",
"search-placeholder": "Поиск...",
"search": {
"title": "Поиск на сайте",
"head-title": "Поиск",
"search-button": "Поиск",
"results-for": "Результаты поиска для \"{query}\"",
"result-count": "Всего {count} результатов",
"no-results": "Ничего не найдено по запросу \"{query}\".",
"no-query": "Введите ключевые слова для начала поиска.",
"section": "раздел",
"untitled": "Без названия",
"sections": {
"product": "Продукты",
"solution": "Решения",
"faq": "Часто задаваемые вопросы",
"document": "Документация",
"default": "Другие материалы"
}
},
"company-name": "Jinshen Machinary Manufacturing Co., Ltd.",
"company-description": "Профессионально производим оборудование для бумажных трубок и канистр, услуги по проектированию, производству, продаже и сервисному обслуживанию.",
"learn-more": "Узнать больше",
"products-desc": "Мы предоставляем новейшие продукты и мгновенную сервисную поддержку для удовлетворения различных бизнес-потребностей наших клиентов.",
"solutions-desc": "Мы предлагаем разнообразные технические решения для предприятий, поддерживая различные области, такие как промышленность и упаковка.",
"support-desc": "Профессиональная техническая поддержка 24/7, обеспечивающая стабильную работу вашего бизнеса.",
"quick-links": "Быстрые ссылки",
"utilities": "Полезные инструменты",
"navigation": {
"home": "Главная",
"products": "Центр продуктов",
"solutions": "Решения",
"support": "Поддержка",
"about-us": "О нас",
"contact-info": "Контактная информация",
"downloads": "Файлы для скачивания",
"faq": "Часто задаваемые вопросы",
"documents": "Документация",
"calculator": "Калькулятор бумажных трубок",
"address": "Адрес компании"
},
"contact-info": "Свяжитесь с нами",
"telephone": "Телефон",
"email": "Электронная почта",
"address": "Адрес",
"company-address": "No. 689 Qiushi Road, Wutong Industrial Zone, Tongxiang City, Zhejiang Province, China",
"follow-us": "Следуйте за нами",
"all-rights-reserved": "All rights reserved",
"privacy-policy": "Политика конфиденциальности",
"terms-of-service": "Условия обслуживания",
"sitemap": "Карта сайта",
"product-details": "Детали продукта",
"product-not-found": "Продукт не найден",
"product-not-found-desc": "Извините, продукт, который вы ищете, не существует или был удален.",
"back-to-products": "Вернуться к списку продуктов",
"solution-not-found": "Решение не найдено",
"solution-not-found-desc": "Извините, решение, которое вы ищете, не существует или было удалено.",
"back-to-solutions": "Вернуться к списку решений",
"page-not-found": "Страница не найдена",
"page-not-found-desc": "Извините, страница, которую вы ищете, не существует или была удалена.",
"back-to-home": "Вернуться на главную",
"no-content-available": "Нет доступной информации",
"loading": "Загрузка...",
"our-products": "Наши последние продукты",
"find-discontinued-products": "Чтобы найти другие продукты, используйте функцию поиска.",
"product-discontinued-warning": "Этот продукт снят с производства и может больше не получать мгновенную поддержку или обновления",
"learn-our-solutions": "Узнайте о наших решениях",
"all": "Все",
"support-page-desc": "Zhejiang Jinshen Machinery Manufacturing Co., Ltd Стремится предоставлять клиентам высококачественные продукты и услуги. Мы предлагаем послепродажное обслуживание для таких продуктов, как машины для бумажных трубок и соломинок, обеспечивая уверенность клиентов в использовании нашей продукции.",
"support-card-desc": {
"faq": "Мы собрали ответы на часто задаваемые вопросы, чтобы помочь вам быстро решить свои проблемы.",
"documents": "Предоставляем документацию, такую как руководства по продуктам, технические спецификации, для удобства пользователей.",
"contact-info": "Свяжитесь с нами по телефону или электронной почте, и мы оперативно вам поможем."
},
"product-filter": {
"product-type": "Тип продукта",
"product-model": "Модель продукта",
"keyword": "Ключевое слово",
"select-product-type": "Выберите тип продукта",
"select-product-model": "Выберите модель продукта",
"enter-keyword": "Введите ключевое слово",
"misc": "разное",
"document-type": "Тип документа",
"question-type": "Тип вопроса",
"select-document-type": "Выберите тип документа",
"select-question-type": "Выберите тип вопроса"
},
"document-meta": {
"size": "Размер",
"format": "Формат",
"type": "Тип",
"upload-at": "Дата загрузки"
},
"document-action": {
"download": "Скачать",
"open-in-new-tab": "Открыть в новой вкладке",
"preview": "Предварительный просмотр"
},
"mobile-menu": {
"title": "Меню",
"navigation": "Навигация по сайту",
"utilities": "Полезные инструменты"
},
"homepage": {
"recommended-products": "Рекомендуемые продукты",
"recommended-products-desc": "Исследуйте наши тщательно отобранные продукты, которые удовлетворят все ваши потребности. Мы предлагаем как инновационные технологии, так и классические решения.",
"recommended-solutions": "Рекомендуемые решения",
"recommended-solutions-desc": "Узнайте о наших индивидуальных решениях, чтобы оптимизировать бизнес-процессы и повысить эффективность."
},
"page-title": {
"homepage": "Главная",
"products": "Центр продуктов",
"solutions": "Решения",
"support": "Поддержка",
"faq": "Часто задаваемые вопросы",
"documents": "Документация",
"contact-us": "Свяжитесь с нами",
"download": "Скачать докумен",
"preview": "Просмотр документа",
"about-us": "О нас"
},
"product-tab": {
"details": "Детали продукта",
"specs": "Технические спецификации",
"faq": "Часто задаваемые вопросы",
"documents": "Связанные документы"
},
"redirecting": "Перенаправление..."
}

View File

@ -10,6 +10,7 @@
"result-count": "共 {count} 条结果",
"no-results": "没有找到与 “{query}” 匹配的内容。",
"no-query": "请输入关键字开始搜索。",
"section": "内容类型",
"untitled": "未命名条目",
"sections": {
"product": "产品",
@ -22,8 +23,8 @@
"company-name": "金申机械制造有限公司",
"company-description": "专业生产一系列纸管、纸罐设备,集设计、制造、销售、服务于一体。",
"learn-more": "了解更多",
"products-desc": "我们提供高质量的产品解决方案,满足各种业务需求。",
"solutions-desc": "为企业提供定制化的技术解决方案,助力数字化转型。",
"products-desc": "我们提供最新的产品与即时的服务支持,满足客户的各类业务需求。",
"solutions-desc": "我们为企业提供多样化的技术解决方案,在工业、包装等多种领域提供支持。",
"support-desc": "7x24小时专业技术支持确保您的业务稳定运行。",
"quick-links": "快速链接",
"utilities": "实用工具",
@ -37,7 +38,8 @@
"downloads": "文件下载",
"faq": "常见问题",
"documents": "文档资料",
"calculator": "纸管计算工具"
"calculator": "纸管计算工具",
"address": "公司地址"
},
"contact-info": "联系我们",
"telephone": "电话",
@ -61,10 +63,12 @@
"back-to-home": "返回首页",
"no-content-available": "暂无详细信息",
"loading": "加载中...",
"our-products": "我们的产品",
"our-products": "我们的最新产品",
"find-discontinued-products": "如需查找其他产品,请使用搜索功能",
"product-discontinued-warning": "本产品已停产,可能不再提供即时的支持或更新",
"learn-our-solutions": "了解我们的解决方案",
"all": "全部",
"support-page-desc": "金申机械制造有限公司致力于为客户提供优质的产品与服务。针对纸管机、分纸机、纸吸管等产品,我们提供全方位的售后服务,确保客户能够安心地使用我们的产品。公司名可用占位符代替",
"support-page-desc": "金申机械制造有限公司致力于为客户提供优质的产品与服务。针对纸管机、分纸机、纸吸管等产品,我们提供全方位的售后服务,确保客户能够安心地使用我们的产品。",
"support-card-desc": {
"faq": "我们为用户整理了常见问题的答案,帮助您快速解决疑惑。",
"documents": "提供产品手册、技术规格等文档资料,方便用户查阅。",
@ -76,7 +80,12 @@
"keyword": "关键词",
"select-product-type": "选择产品类型",
"select-product-model": "选择产品系列",
"enter-keyword": "输入关键词"
"enter-keyword": "输入关键词",
"question-type": "问题类型",
"select-question-type": "选择问题类型",
"document-type": "文档类型",
"select-document-type": "选择文档类型",
"misc": "其他"
},
"document-meta": {
"size": "大小",
@ -117,5 +126,6 @@
"specs": "技术规格",
"faq": "常见问题",
"documents": "相关文档"
}
},
"redirecting": "正在跳转..."
}

View File

@ -20,7 +20,17 @@ export default defineNuxtConfig({
htmlAttrs: {
lang: 'zh',
},
link: [{ rel: 'icon', type: 'image/x-icon', href: '/jinshen-logo.ico' }],
link: [
{ rel: 'icon', type: 'image/x-icon', href: '/jinshen-logo.ico' },
{
rel: 'apple-touch-icon',
href: '/jinshen-logo.png',
},
{
rel: 'manifest',
href: '/manifest.json',
},
],
},
},
@ -44,6 +54,10 @@ export default defineNuxtConfig({
},
directus: {
url: process.env.DIRECTUS_URL || 'http://localhost:8055',
publicUrl:
process.env.DIRECTUS_PUBLIC_URL ||
process.env.DIRECTUS_URL ||
'http://localhost:8055',
token: process.env.DIRECTUS_TOKEN || undefined,
},
},
@ -68,6 +82,7 @@ export default defineNuxtConfig({
'@unocss/reset/tailwind.css',
'~/assets/scss/index.scss',
'~/assets/css/fonts.css',
'~/assets/css/typography.css',
'@mdi/font/css/materialdesignicons.min.css',
],
@ -117,6 +132,8 @@ export default defineNuxtConfig({
locales: [
{ code: 'en', language: 'en-US', name: 'English', file: 'en.json' },
{ code: 'zh', language: 'zh-CN', name: '简体中文', file: 'zh.json' },
{ code: 'es', language: 'es-ES', name: 'Español', file: 'es.json' },
{ code: 'ru', language: 'ru-RU', name: 'Русский', file: 'ru.json' },
],
defaultLocale: 'zh',
strategy: 'prefix_except_default',

View File

@ -22,10 +22,13 @@
"@types/markdown-it": "^14.1.2",
"@unocss/nuxt": "^66.4.2",
"@vueuse/nuxt": "^13.6.0",
"dom-serializer": "^2.0.0",
"domhandler": "^5.0.3",
"dompurify": "^3.2.6",
"element-plus": "^2.10.7",
"fuse.js": "^7.1.0",
"graphql": "^16.12.0",
"htmlparser2": "^10.0.0",
"markdown-it": "^14.1.0",
"meilisearch": "^0.53.0",
"nuxt": "^4.0.3",

25
pnpm-lock.yaml generated
View File

@ -41,6 +41,12 @@ importers:
'@vueuse/nuxt':
specifier: ^13.6.0
version: 13.9.0(magicast@0.3.5)(nuxt@4.1.2(@parcel/watcher@2.5.1)(@types/node@24.4.0)(@vue/compiler-sfc@3.5.21)(db0@0.3.2)(eslint@9.35.0(jiti@2.5.1))(ioredis@5.7.0)(magicast@0.3.5)(optionator@0.9.4)(rollup@4.50.2)(sass@1.92.1)(terser@5.44.0)(typescript@5.9.2)(vite@7.1.5(@types/node@24.4.0)(jiti@2.5.1)(sass@1.92.1)(terser@5.44.0)(yaml@2.8.1))(yaml@2.8.1))(vue@3.5.21(typescript@5.9.2))
dom-serializer:
specifier: ^2.0.0
version: 2.0.0
domhandler:
specifier: ^5.0.3
version: 5.0.3
dompurify:
specifier: ^3.2.6
version: 3.2.6
@ -53,6 +59,9 @@ importers:
graphql:
specifier: ^16.12.0
version: 16.12.0
htmlparser2:
specifier: ^10.0.0
version: 10.0.0
markdown-it:
specifier: ^14.1.0
version: 14.1.0
@ -3090,6 +3099,10 @@ packages:
resolution: {integrity: sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==}
engines: {node: '>=0.12'}
entities@6.0.1:
resolution: {integrity: sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==}
engines: {node: '>=0.12'}
env-paths@2.2.1:
resolution: {integrity: sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==}
engines: {node: '>=6'}
@ -3544,6 +3557,9 @@ packages:
hookable@5.5.3:
resolution: {integrity: sha512-Yc+BQe8SvoXH1643Qez1zqLRmbA5rCL+sSmk6TVos0LWVfNIB7PGncdlId77WzLGSIB5KaWgTaNTs2lNVEI6VQ==}
htmlparser2@10.0.0:
resolution: {integrity: sha512-TwAZM+zE5Tq3lrEHvOlvwgj1XLWQCtaaibSN11Q+gGBAS7Y1uZSWwXXRe4iF6OXnaq1riyQAPFOBtYc77Mxq0g==}
http-errors@2.0.0:
resolution: {integrity: sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==}
engines: {node: '>= 0.8'}
@ -9013,6 +9029,8 @@ snapshots:
entities@4.5.0: {}
entities@6.0.1: {}
env-paths@2.2.1: {}
environment@1.1.0: {}
@ -9541,6 +9559,13 @@ snapshots:
hookable@5.5.3: {}
htmlparser2@10.0.0:
dependencies:
domelementtype: 2.3.0
domhandler: 5.0.3
domutils: 3.2.2
entities: 6.0.1
http-errors@2.0.0:
dependencies:
depd: 2.0.0

BIN
public/logo196x196.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

BIN
public/logo512x512.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

20
public/manifest.json Normal file
View File

@ -0,0 +1,20 @@
{
"name": "金申机械制造有限公司",
"short_name": "金申机械",
"icons": [
{
"src": "/logo196x196.png",
"sizes": "196x196",
"type": "image/png"
},
{
"src": "/logo512x512.png",
"sizes": "512x512",
"type": "image/png"
}
],
"start_url": ".",
"display": "standalone",
"background_color": "#ffffff",
"theme_color": "#0f172a"
}

View File

@ -0,0 +1,15 @@
import { companyProfileService } from '~~/server/services/cms/companyProfileService';
export default defineEventHandler(async (event) => {
const locale = getHeader(event, 'x-locale') || 'zh-CN';
const companyProfile = await companyProfileService.getCompanyProfile(locale);
companyProfile.content = rewriteAssetUrls(
companyProfile.content,
useRuntimeConfig().public.directus.publicUrl,
'/api/assets'
);
return companyProfile;
});

View File

@ -1,24 +0,0 @@
import { directus } from '~~/server/utils/directus';
import { loadAssetAsString } from '~~/server/utils/serverAssets';
export default defineEventHandler(async (event) => {
const query = await loadAssetAsString(
'assets:server',
'graphql/companyProfile.graphql'
);
if (!query)
throw createError({ statusCode: 500, message: 'GraphQL query not found' });
const locale = getHeader(event, 'x-locale') || 'zh-CN';
const data = await directus.query<{ company_profile: CompanyProfile }>(
query,
{
locale: locale,
}
);
const companyProfile = data?.company_profile;
return companyProfile;
});

View File

@ -0,0 +1,15 @@
import { contactInfoService } from '~~/server/services/cms/contactInfoService';
export default defineEventHandler(async (event) => {
const locale = getHeader(event, 'x-locale') || 'zh-CN';
const contactInfo = await contactInfoService.getContactInfo(locale);
contactInfo.content = rewriteAssetUrls(
contactInfo.content,
useRuntimeConfig().public.directus.publicUrl,
'/api/assets'
);
return contactInfo;
});

View File

@ -1,21 +0,0 @@
import { directus } from '~~/server/utils/directus';
import { loadAssetAsString } from '~~/server/utils/serverAssets';
export default defineEventHandler(async (event) => {
const query = await loadAssetAsString(
'assets:server',
'graphql/contactInfo.graphql'
);
if (!query)
throw createError({ statusCode: 500, message: 'GraphQL query not found' });
const locale = getHeader(event, 'x-locale') || 'zh-CN';
const data = await directus.query<{ contact_info: ContactInfo }>(query, {
locale: locale,
});
const contactInfo = data?.contact_info;
return contactInfo;
});

View File

@ -0,0 +1,7 @@
import { documentService } from '~~/server/services/cms/documentService';
export default defineEventHandler(async (event) => {
const locale = getHeader(event, 'x-locale') || 'zh-CN';
return documentService.getDocumentList(locale);
});

View File

@ -1,24 +0,0 @@
import { directus } from '~~/server/utils/directus';
import { loadAssetAsString } from '~~/server/utils/serverAssets';
export default defineEventHandler(async (event) => {
const query = await loadAssetAsString(
'assets:server',
'graphql/documentList.graphql'
);
if (!query)
throw createError({ statusCode: 500, message: 'GraphQL query not found' });
const locale = getHeader(event, 'x-locale') || 'zh-CN';
const data = await directus.query<{ product_documents: ProductDocument[] }>(
query,
{
locale: locale,
}
);
const documents = data?.product_documents;
return documents;
});

View File

@ -0,0 +1,7 @@
import { homepageService } from '~~/server/services/cms/homepageService';
export default defineEventHandler(async (event) => {
const locale = getHeader(event, 'x-locale') || 'zh-CN';
return homepageService.getHomepage(locale);
});

View File

@ -1,21 +0,0 @@
import { directus } from '~~/server/utils/directus';
import { loadAssetAsString } from '~~/server/utils/serverAssets';
export default defineEventHandler(async (event) => {
const query = await loadAssetAsString(
'assets:server',
'graphql/homepage.graphql'
);
if (!query)
throw createError({ statusCode: 500, message: 'GraphQL query not found' });
const locale = getHeader(event, 'x-locale') || 'zh-CN';
const data = await directus.query<{ homepage: Homepage }>(query, {
locale: locale,
});
const homepage = data?.homepage;
return homepage;
});

View File

@ -0,0 +1,21 @@
import { productService } from '~~/server/services/cms/productService';
export default defineEventHandler(async (event) => {
const id = getRouterParam(event, 'id');
if (!id)
throw createError({
statusCode: 400,
statusMessage: 'Product ID is required',
});
const locale = getHeader(event, 'x-locale') || 'zh-CN';
const product = await productService.getProductById(id, locale);
product.description = rewriteAssetUrls(
product.description,
useRuntimeConfig().public.directus.publicUrl,
'/api/assets'
);
return product;
});

View File

@ -1,33 +0,0 @@
import { directus } from '~~/server/utils/directus';
import { loadAssetAsString } from '~~/server/utils/serverAssets';
export default defineEventHandler(async (event) => {
const id = getRouterParam(event, 'id');
if (!id)
throw createError({
statusCode: 400,
statusMessage: 'Product ID is required',
});
const query = await loadAssetAsString(
'assets/server',
'graphql/product.graphql'
);
if (!query)
throw createError({ statusCode: 500, message: 'GraphQL query not found' });
const locale = getHeader(event, 'x-locale') || 'zh-CN';
const data = await directus.query<{ products_by_id: Product }>(query, {
id: id,
locale: locale,
});
const product = data?.products_by_id;
if (!product || product.status === 'archived') {
throw createError({ statusCode: 404, statusMessage: 'Product not found' });
}
return product;
});

View File

@ -0,0 +1,6 @@
import { productService } from '~~/server/services/cms/productService';
export default defineEventHandler(async (event) => {
const locale = getHeader(event, 'x-locale') || 'zh-CN';
return productService.getProductList(locale);
});

View File

@ -1,21 +0,0 @@
import { directus } from '~~/server/utils/directus';
import { loadAssetAsString } from '~~/server/utils/serverAssets';
export default defineEventHandler(async (event) => {
const query = await loadAssetAsString(
'assets:server',
'graphql/productList.graphql'
);
if (!query)
throw createError({ statusCode: 500, message: 'GraphQL query not found' });
const locale = getHeader(event, 'x-locale') || 'zh-CN';
const data = await directus.query<{ products: Product[] }>(query, {
locale: locale,
});
const products = data?.products || [];
return products;
});

View File

@ -0,0 +1,16 @@
import { questionService } from '~~/server/services/cms/questionService';
export default defineEventHandler(async (event) => {
const locale = getHeader(event, 'x-locale') || 'zh-CN';
const questions = await questionService.getQuestionList(locale);
questions.forEach((question) => {
question.content = rewriteAssetUrls(
question.content,
useRuntimeConfig().public.directus.publicUrl,
'/api/assets'
);
});
return questions;
});

View File

@ -1,21 +0,0 @@
import { directus } from '~~/server/utils/directus';
import { loadAssetAsString } from '~~/server/utils/serverAssets';
export default defineEventHandler(async (event) => {
const query = await loadAssetAsString(
'assets:server',
'graphql/questionList.graphql'
);
if (!query)
throw createError({ statusCode: 500, message: 'GraphQL query not found' });
const locale = getHeader(event, 'x-locale') || 'zh-CN';
const data = await directus.query<{ questions: Question[] }>(query, {
locale: locale,
});
const questions = data?.questions || [];
return questions;
});

View File

@ -0,0 +1,22 @@
import { solutionService } from '~~/server/services/cms/solutionService';
export default defineEventHandler(async (event) => {
const id = getRouterParam(event, 'id');
if (!id)
throw createError({
statusCode: 400,
statusMessage: 'Solution ID is required',
});
const locale = getHeader(event, 'x-locale') || 'zh-CN';
const solution = await solutionService.getSolutionById(id, locale);
solution.content = rewriteAssetUrls(
solution.content,
useRuntimeConfig().public.directus.publicUrl,
'/api/assets'
);
return solution;
});

View File

@ -1,33 +0,0 @@
import { directus } from '~~/server/utils/directus';
import { loadAssetAsString } from '~~/server/utils/serverAssets';
export default defineEventHandler(async (event) => {
const id = getRouterParam(event, 'id');
if (!id)
throw createError({
statusCode: 400,
statusMessage: 'Solution ID is required',
});
const query = await loadAssetAsString(
'assets:server',
'graphql/solution.graphql'
);
if (!query)
throw createError({ statusCode: 500, message: 'GraphQL query not found' });
const locale = getHeader(event, 'x-locale') || 'zh-CN';
const data = await directus.query<{ solutions_by_id: Solution }>(query, {
id: id,
locale: locale,
});
const solution = data?.solutions_by_id;
if (!solution || solution.status === 'archived') {
throw createError({ statusCode: 404, statusMessage: 'Solution not found' });
}
return solution;
});

View File

@ -0,0 +1,7 @@
import { solutionService } from '~~/server/services/cms/solutionService';
export default defineEventHandler(async (event) => {
const locale = getHeader(event, 'x-locale') || 'zh-CN';
return solutionService.getSolutionList(locale);
});

View File

@ -1,21 +0,0 @@
import { directus } from '~~/server/utils/directus';
import { loadAssetAsString } from '~~/server/utils/serverAssets';
export default defineEventHandler(async (event) => {
const query = await loadAssetAsString(
'assets:server',
'graphql/solutionList.graphql'
);
if (!query)
throw createError({ statusCode: 500, message: 'GraphQL query not found' });
const locale = getHeader(event, 'x-locale') || 'zh-CN';
const data = await directus.query<{ solutions: Solution[] }>(query, {
locale: locale,
});
const solutions = data?.solutions || [];
return solutions;
});

37
server/api/search.get.ts Normal file
View File

@ -0,0 +1,37 @@
import { toSearchItemView } from '../mappers/searchItemMapper';
import { getMeiliService } from '../services/search';
export default defineEventHandler(async (event) => {
const query = getQuery(event);
const q = String(query.query || '');
const locale = getHeader(event, 'x-locale') || 'zh-CN';
logger.info(`Search query: "${q}" for locale: "${locale}"`);
if (!q) return [];
const meili = getMeiliService();
const sections = await meili.search(q, { limit: 500 }, locale);
// 空Section过滤
const filteredSections = sections.filter(
(section) => section.hits.length > 0
);
const typeMap = {
products: 'products',
solutions: 'solutions',
questions: 'questions',
product_documents: 'product_documents',
} as const;
const hits = filteredSections.flatMap((section) => {
const type = typeMap[section.rawIndex as keyof typeof typeMap];
if (!type) return [];
return section.hits.map((hit) => ({ type, content: hit }));
});
return hits.map((hit) => {
return toSearchItemView(hit.content, hit.type);
});
});

View File

@ -1,5 +1,5 @@
query GetDocumentList($locale: String!) {
product_documents(filter: { status: { _eq: "published" } }) {
product_documents(filter: { status: { _eq: "published" } }, limit: 500) {
id
file {
id
@ -10,6 +10,13 @@ query GetDocumentList($locale: String!) {
id
title
}
type {
id
translations(filter: { languages_code: { code: { _eq: $locale } } }) {
id
name
}
}
products {
id
products_id {

View File

@ -28,6 +28,7 @@ query GetProduct($id: ID!, $locale: String!) {
name
}
specs {
id
translations(filter: { languages_code: { code: { _eq: $locale } } }) {
id
key
@ -50,6 +51,13 @@ query GetProduct($id: ID!, $locale: String!) {
id
product_documents_id(filter: { status: { _eq: "published" } }) {
id
type {
id
translations(filter: { languages_code: { code: { _eq: $locale } } }) {
id
name
}
}
file {
id
filesize

View File

@ -1,5 +1,5 @@
query GetProductList($locale: String!) {
products(filter: { status: { _eq: "in-production" } }) {
products(filter: { status: { _eq: "in-production" } }, limit: 200) {
id
status
translations(filter: { languages_code: { code: { _eq: $locale } } }) {

View File

@ -1,6 +1,13 @@
query GetQuestionList($locale: String!) {
questions(filter: { status: { _eq: "published" } }) {
questions(filter: { status: { _eq: "published" } }, limit: 500) {
id
type {
id
translations(filter: { languages_code: { code: { _eq: $locale } } }) {
id
name
}
}
translations(filter: { languages_code: { code: { _eq: $locale } } }) {
id
title

View File

@ -1,5 +1,5 @@
query GetSolutionList($locale: String!) {
solutions(filter: { status: { _eq: "published" } }) {
solutions(filter: { status: { _eq: "published" } }, limit: 200) {
id
cover {
id

View File

@ -1,30 +1,33 @@
import { expect, test, describe } from 'vitest';
import { toCompanyProfileView } from './companyProfileMapper';
/**
* 单元测试: companyProfileMapper
*/
describe('companyProfileMapper', () => {
const baseData: CompanyProfile = {
id: 1,
translations: [{ id: 10, content: 'This is raw data of company profile' }],
};
test('convert raw data to CompanyProfileView correctly', () => {
const rawData: CompanyProfile = {
id: 1,
translations: [
{ id: 10, content: 'This is raw data of company profile' },
],
...baseData,
};
expect(toCompanyProfileView(rawData)).toEqual({
id: 1,
id: '1',
content: 'This is raw data of company profile',
});
});
test('convert raw data with missing translations', () => {
const rawData: CompanyProfile = {
id: 1,
...baseData,
translations: [],
};
expect(toCompanyProfileView(rawData)).toEqual({
id: 1,
id: '1',
content: '',
});
});

View File

@ -8,10 +8,10 @@
* const view = toCompanyProfileView(rawCompanyProfile);
*/
export function toCompanyProfileView(raw: CompanyProfile): CompanyProfileView {
const trans = raw.translations?.[0] ?? { content: '' };
const trans = raw.translations?.[0];
return {
id: raw.id,
content: trans.content,
id: raw.id.toString(),
content: trans?.content ?? '',
};
}

View File

@ -1,29 +1,33 @@
import { describe, test, expect } from 'vitest';
import { toContactInfoView } from './contactInfoMapper';
/**
* 单元测试: contactInfoMapper
*/
describe('contactInfoMapper', () => {
test('convert raw data to ContactInfoView correctly', () => {
const rawData: ContactInfo = {
const baseData: ContactInfo = {
id: 1,
translations: [{ id: 10, content: 'This is raw data of contact info' }],
};
test('convert raw data to ContactInfoView correctly', () => {
const rawData: ContactInfo = {
...baseData,
};
expect(toContactInfoView(rawData)).toEqual({
id: 1,
id: '1',
content: 'This is raw data of contact info',
});
});
test('convert raw data with missing translations', () => {
const rawData: ContactInfo = {
id: 1,
...baseData,
translations: [],
};
expect(toContactInfoView(rawData)).toEqual({
id: 1,
id: '1',
content: '',
});
});

View File

@ -8,10 +8,10 @@
* const view = toContactInfoView(rawContactInfo);
*/
export function toContactInfoView(raw: ContactInfo): ContactInfoView {
const trans = raw.translations?.[0] ?? { content: '' };
const trans = raw.translations?.[0];
return {
id: raw.id,
content: trans.content,
id: raw.id.toString(),
content: trans?.content ?? '',
};
}

View File

@ -0,0 +1,106 @@
import { describe, test, expect } from 'vitest';
import { toDocumentListView, toDocumentTypeView } from './documentMapper';
/**
* 单元测试: toDocumentTypeView
*/
describe('toDocumentTypeView', () => {
const baseData: DocumentType = {
id: 1,
translations: [{ id: 1, name: 'Type Name' }],
};
test('convert raw data to DocumentTypeView correctly', () => {
const rawData: DocumentType = {
...baseData,
};
expect(toDocumentTypeView(rawData)).toEqual({
id: '1',
name: 'Type Name',
});
});
test('convert raw data with missing translations', () => {
const rawData: DocumentType = {
...baseData,
translations: [],
};
expect(toDocumentTypeView(rawData)).toEqual({
id: '1',
name: '',
});
});
test('convert null input to default DocumentTypeView', () => {
const rawData: DocumentType | null = null;
expect(toDocumentTypeView(rawData)).toEqual({
id: '-1',
name: '',
});
});
});
/**
* 单元测试: toDocumentListView
*/
describe('toDocumentListView', () => {
const baseData: ProductDocument = {
id: 1,
type: {
id: 1,
translations: [
{
id: 1,
name: 'Type A',
},
],
},
file: {
id: 'rand-om__-uuid-1234',
filename_download: 'document.pdf',
filesize: 2048,
},
translations: [{ id: 10, title: 'Document Title' }],
products: [
{
id: 10,
products_id: {
id: 1,
translations: [{ id: 1, name: 'Product A' }],
product_type: {
id: 1,
translations: [{ id: 1, name: 'Type A' }],
},
},
},
],
};
test('convert raw data with fileMeta to DocumentListView correctly', () => {
const rawData: ProductDocument = { ...baseData };
expect(toDocumentListView(rawData)).toEqual({
id: '1',
fileId: 'rand-om__-uuid-1234',
filename: 'document.pdf',
title: 'Document Title',
url: '/api/assets/rand-om__-uuid-1234',
size: 2048,
type: {
id: '1',
name: 'Type A',
},
products: [
{
id: '1',
name: 'Product A',
type: {
id: '1',
name: 'Type A',
},
},
],
});
});
});

View File

@ -0,0 +1,79 @@
import { isObject } from '../../server/utils/object';
/**
* 将 Directus 返回的 DocumentType 数据转换为 DocumentTypeView 视图模型
*
* @param raw: 原始的 DocumentType 数据
* @returns 转换后的 DocumentTypeView 对象
*
* @example
* const view = toDocumentTypeView(rawDocumentType);
*/
export function toDocumentTypeView(
raw: DocumentType | string | null
): DocumentTypeView {
if (typeof raw === 'string' || raw === null) {
return {
id: '-1',
name: '',
} satisfies DocumentTypeView;
}
const trans = raw.translations?.[0];
return {
id: raw.id.toString(),
name: trans?.name ?? '',
};
}
/**
* 将 Directus 返回的 Document 数据转换为 DocumentListView 视图模型
*
* @param raw: 原始的 Document 数据
* @returns 转换后的 DocumentListView 对象
*
* @example
* const view = toDocumentListView(rawDocument);
*/
export function toDocumentListView(raw: ProductDocument): DocumentListView {
const trans = raw.translations?.[0];
const type = toDocumentTypeView(raw.type ?? null);
const file = isObject<DirectusFile>(raw.file) ? raw.file : undefined;
const fileId = file?.id ?? '';
const url = `/api/assets/${fileId}`;
const related_products: DocumentListProduct[] = (raw.products ?? [])
.filter(isObject<ProductsProductDocument>)
.map((item) => item.products_id)
.filter(isObject<Product>)
.map((item) => {
const productType = isObject<ProductType>(item.product_type)
? ({
id: item.product_type.id.toString(),
name: item.product_type.translations?.[0]?.name ?? '',
} satisfies DocumentListProductType)
: ({
id: '',
name: '',
} satisfies DocumentListProductType);
return {
id: item.id.toString(),
name: item.translations?.[0]?.name ?? '',
type: productType,
};
});
return {
id: raw.id.toString(),
fileId: fileId,
filename: file?.filename_download ?? '',
title: trans?.title ?? '',
url: url,
size: file?.filesize ?? 0,
type: type,
products: related_products,
};
}

View File

@ -1,4 +1,5 @@
import { describe, test, expect } from 'vitest';
import { toHomepageView } from './homepageMapper';
/**
* 单元测试: toHomepageView
@ -25,35 +26,41 @@ describe('toHomepageView', () => {
{
id: 1,
translations: [{ id: 1, name: 'Product 1', summary: 'Summary 1' }],
cover: 'cover-file-uuid-1',
cover: {
id: 'cover-file-uuid-1',
},
},
{
id: 2,
translations: [{ id: 2, name: 'Product 2', summary: 'Summary 2' }],
cover: { id: 'cover-file-uuid-2' },
cover: {
id: 'cover-file-uuid-2',
},
},
],
recommend_solutions: [
{
id: 1,
translations: [{ id: 1, title: 'Solution 1', summary: 'Summary 1' }],
cover: 'cover-file-uuid-1',
cover: {
id: 'cover-file-uuid-1',
},
},
],
};
expect(toHomepageView(rawData)).toEqual({
id: 1,
id: '1',
carousel: ['file-uuid-1', 'file-uuid-2'],
recommendProducts: [
{
id: 1,
id: '1',
name: 'Product 1',
summary: 'Summary 1',
cover: 'cover-file-uuid-1',
},
{
id: 2,
id: '2',
name: 'Product 2',
summary: 'Summary 2',
cover: 'cover-file-uuid-2',
@ -61,7 +68,7 @@ describe('toHomepageView', () => {
],
recommendSolutions: [
{
id: 1,
id: '1',
title: 'Solution 1',
summary: 'Summary 1',
cover: 'cover-file-uuid-1',
@ -79,10 +86,10 @@ describe('toHomepageView', () => {
};
expect(toHomepageView(rawData)).toEqual({
id: 1,
id: '1',
carousel: [],
recommendProducts: [{ id: 1, name: '', summary: '', cover: null }],
recommendSolutions: [{ id: 1, title: '', summary: '', cover: null }],
recommendProducts: [{ id: '1', name: '', summary: '', cover: '' }],
recommendSolutions: [{ id: '1', title: '', summary: '', cover: '' }],
});
});
});

View File

@ -1,3 +1,5 @@
import { isObject } from '../utils/object';
/**
* Directus Homepage HomepageView
*
@ -17,14 +19,14 @@ export function toHomepageView(raw: Homepage): HomepageView {
const products = (raw.recommend_products ?? [])
.filter(isObject<Product>)
.map((item) => {
const cover = isObject<DirectusFile>(item.cover)
? item.cover.id
: item.cover;
const trans = item.translations?.[0] ?? { name: '', summary: '' };
const trans = item.translations?.[0];
const cover = isObject<DirectusFile>(item.cover) ? item.cover.id : '';
return {
id: item.id,
name: trans.name,
summary: trans.summary,
id: item.id.toString(),
name: trans?.name ?? '',
summary: trans?.summary ?? '',
cover: cover,
} satisfies HomepageProductView;
});
@ -32,21 +34,19 @@ export function toHomepageView(raw: Homepage): HomepageView {
const solutions = (raw.recommend_solutions ?? [])
.filter(isObject<Solution>)
.map((item) => {
const cover = isObject<DirectusFile>(item.cover)
? item.cover.id
: item.cover;
const trans = item.translations?.[0] ?? { title: '', summary: '' };
const trans = item.translations?.[0];
const cover = isObject<DirectusFile>(item.cover) ? item.cover.id : '';
return {
id: item.id,
title: trans.title,
summary: trans.summary,
id: item.id.toString(),
title: trans?.title ?? '',
summary: trans?.summary ?? '',
cover: cover,
} satisfies HomepageSolutionView;
});
return {
id: raw.id,
id: raw.id.toString(),
carousel: carousel ?? [],
recommendProducts: products ?? [],
recommendSolutions: solutions ?? [],

View File

@ -0,0 +1,125 @@
import { describe, expect, test } from 'vitest';
import { toProductTypeView, toProductListView } from './productListMapper';
/**
* 单元测试: toProductTypeView
*/
describe('toProductTypeView', () => {
const baseData: ProductType = {
id: 1,
translations: [
{
id: 1,
name: 'Type Name',
},
],
sort: 5,
};
test('convert raw data to ProductTypeView correctly', () => {
const rawData: ProductType = { ...baseData };
expect(toProductTypeView(rawData)).toEqual({
id: '1',
name: 'Type Name',
sort: 5,
});
});
test('convert raw data with missing translations', () => {
const rawData: ProductType = {
...baseData,
translations: [],
};
expect(toProductTypeView(rawData)).toEqual({
id: '1',
name: '',
sort: 5,
});
});
test('convert raw data with missing sort', () => {
const rawData: ProductType = {
...baseData,
sort: undefined,
};
expect(toProductTypeView(rawData)).toEqual({
id: '1',
name: 'Type Name',
sort: 999,
});
});
test('convert null input to default value', () => {
const rawData: ProductType | string | null = null;
expect(toProductTypeView(rawData)).toEqual({
id: '-1',
name: '',
sort: 999,
});
});
});
/**
* 单元测试: toProductListView
*/
describe('toProductListView', () => {
test('convert raw data to ProductListView correctly', () => {
const rawData: Product = {
id: 1,
translations: [
{ id: 10, name: 'Product Name', summary: 'Product Summary' },
],
cover: {
id: 'cover-file-uuid-1234',
},
product_type: {
id: 1,
translations: [{ id: 20, name: 'Type Name' }],
sort: 1,
},
};
expect(toProductListView(rawData)).toEqual({
id: '1',
name: 'Product Name',
summary: 'Product Summary',
cover: 'cover-file-uuid-1234',
product_type: {
id: '1',
name: 'Type Name',
sort: 1,
},
});
});
test('convert raw data with missing translations', () => {
const rawData: Product = {
id: 1,
translations: [],
cover: {
id: 'cover-file-uuid-1234',
},
product_type: {
id: 20,
translations: [],
sort: 1,
},
};
expect(toProductListView(rawData)).toEqual({
id: '1',
name: '',
summary: '',
cover: 'cover-file-uuid-1234',
product_type: {
id: '20',
name: '',
sort: 1,
},
});
});
});

View File

@ -0,0 +1,54 @@
import { isObject } from '../../server/utils/object';
/**
* 将Directus返回的ProductType数据转换为ProductTypeView视图模型
*
* @param raw: 原始的ProductType数据
* @returns 转换后的ProductTypeView对象
*
* @example
* const view = toProductTypeView(rawProductType);
*/
export function toProductTypeView(
raw: ProductType | string | null
): ProductTypeView {
if (typeof raw === 'string' || raw === null) {
return {
id: '-1',
name: '',
sort: 999,
} satisfies ProductTypeView;
}
const trans = raw.translations?.[0] ?? { name: '' };
return {
id: raw.id.toString(),
name: trans.name,
sort: raw?.sort ?? 999,
} satisfies ProductTypeView;
}
/**
* 将 Directus返回的 Product 数据转换为 ProductListView 视图模型
*
* @param raw: 原始的 Product 数据
* @returns 转换后的 ProductListView 对象
*
* @example
* const view = toProductListView(rawProduct);
*/
export function toProductListView(raw: Product): ProductListView {
const trans = raw.translations?.[0];
const type = toProductTypeView(raw.product_type ?? null);
const cover = isObject<DirectusFile>(raw.cover) ? raw.cover.id : '';
return {
id: raw.id.toString(),
product_type: type,
name: trans?.name ?? '',
summary: trans?.summary ?? '',
cover: cover,
} satisfies ProductListView;
}

View File

@ -0,0 +1,526 @@
import { describe, test, expect } from 'vitest';
import {
toProductImageView,
toProductSpecView,
toProductSpecGroupView,
toProductQuestionView,
toProductDocumentView,
toProductView,
} from './productMapper';
/**
* 单元测试: toProductImageView
*/
describe('toProductImageView', () => {
const baseData: Array<ProductsProductImage> = [
{
id: 1,
product_images_id: {
id: 1,
image: {
id: 'rand-om__-uuid-1234',
},
translations: [
{
id: 1,
caption: 'Image Caption',
},
],
},
},
{
id: 2,
product_images_id: {
id: 2,
image: {
id: 'rand-om__-uuid-5678',
},
translations: [
{
id: 2,
caption: 'Image Caption 2',
},
],
},
},
];
test('convert raw data to ProductImageView correctly', () => {
const rawData: Array<ProductsProductImage> = [...baseData];
expect(toProductImageView(rawData)).toEqual([
{
id: '1',
image: 'rand-om__-uuid-1234',
caption: 'Image Caption',
},
{
id: '2',
image: 'rand-om__-uuid-5678',
caption: 'Image Caption 2',
},
]);
});
test('convert raw data with missing translations', () => {
const rawData: Array<ProductsProductImage> = [
{
id: 1,
product_images_id: {
id: 1,
image: {
id: 'rand-om__-uuid-1234',
},
translations: [],
},
},
];
expect(toProductImageView(rawData)).toEqual([
{
id: '1',
image: 'rand-om__-uuid-1234',
caption: '',
},
]);
});
test('convert empty array to empty ProductImageView array', () => {
const rawData: Array<ProductsProductImage> = [];
expect(toProductImageView(rawData)).toEqual([]);
});
test('convert input with wrong type to default value', () => {
const rawData: string[] = ['1', '2'];
expect(toProductImageView(rawData)).toEqual([
{
id: '1',
image: '',
caption: '',
},
{
id: '2',
image: '',
caption: '',
},
]);
});
});
/**
* 单元测试: toProductSpecView
*/
describe('toProductSpecView', () => {
const baseData: ProductSpec[] = [
{
id: 1,
translations: [
{
id: 1,
key: 'key 1',
value: 'value 1',
},
],
},
{
id: 2,
translations: [
{
id: 2,
key: 'key 2',
value: 'value 2',
},
],
},
];
test('convert raw data to ProductSpecView correctly', () => {
const rawData: ProductSpec[] = [...baseData];
expect(toProductSpecView(rawData)).toEqual([
{
id: '1',
key: 'key 1',
value: 'value 1',
},
{
id: '2',
key: 'key 2',
value: 'value 2',
},
]);
});
test('convert raw data with missing translations', () => {
const rawData: ProductSpec[] = [{ id: 1, translations: [] }];
expect(toProductSpecView(rawData)).toEqual([
{
id: '1',
key: '',
value: '',
},
]);
});
test('convert empty input to empty array', () => {
const rawData: ProductSpec[] = [];
expect(toProductSpecView(rawData)).toEqual([]);
});
test('convert input with wrong type to default value', () => {
const rawData: string[] = ['1', '2'];
expect(toProductSpecView(rawData)).toEqual([
{
id: '1',
key: '',
value: '',
},
{
id: '2',
key: '',
value: '',
},
]);
});
});
/**
* 单元测试: toProductSpecGroupView
*/
describe('toProductSpecGroupView', () => {
test('convert raw data to ProductSpecGroupView correctly', () => {
const rawData: ProductSpecGroup[] = [
{
id: 1,
translations: [{ id: 1, name: 'Group Name' }],
specs: [
{ id: 1, translations: [{ id: 1, key: 'Key1', value: 'Value1' }] },
{ id: 2, translations: [{ id: 2, key: 'Key2', value: 'Value2' }] },
],
},
];
expect(toProductSpecGroupView(rawData)).toEqual([
{
id: '1',
name: 'Group Name',
specs: [
{ id: '1', key: 'Key1', value: 'Value1' },
{ id: '2', key: 'Key2', value: 'Value2' },
],
},
]);
});
test('convert raw data with missing translations', () => {
const rawData: ProductSpecGroup[] = [
{
id: 1,
translations: [],
specs: [],
},
];
expect(toProductSpecGroupView(rawData)).toEqual([
{
id: '1',
name: '',
specs: [],
},
]);
});
test('convert input with wrong type to default value', () => {
const rawData: string[] = ['1', '2'];
expect(toProductSpecGroupView(rawData)).toEqual([
{
id: '1',
name: '',
specs: [],
},
{
id: '2',
name: '',
specs: [],
},
]);
});
test('convert empty ar ray to empty ProductSpecGroupView array', () => {
const rawData: ProductSpec[] = [];
expect(toProductSpecGroupView(rawData)).toEqual([]);
});
});
/**
* 单元测试: toProductQuestionView
*/
describe('toProductQuestionView', () => {
test('convert raw data to ProductQuestionView correctly', () => {
const rawData: ProductsQuestion[] = [
{
id: 1,
questions_id: {
id: 1,
translations: [
{
id: 1,
title: 'Question Title',
content: 'Question Content',
},
],
},
},
];
expect(toProductQuestionView(rawData)).toEqual([
{
id: '1',
title: 'Question Title',
content: 'Question Content',
},
]);
});
test('convert raw data with missing translations', () => {
const rawData: ProductsQuestion[] = [
{
id: 1,
questions_id: {
id: 1,
translations: [],
},
},
];
expect(toProductQuestionView(rawData)).toEqual([
{
id: '1',
title: '',
content: '',
},
]);
});
test('convert empty array to empty ProductQuestionView array', () => {
const rawData: ProductsQuestion[] = [];
expect(toProductQuestionView(rawData)).toEqual([]);
});
test('convert input with wrong type to default value', () => {
const rawData: string[] = ['1', '2'];
expect(toProductQuestionView(rawData)).toEqual([
{
id: '1',
title: '',
content: '',
},
{
id: '2',
title: '',
content: '',
},
]);
});
});
/**
* 单元测试: toProductDocumentView
*/
describe('toProductDocumentView', () => {
test('convert raw data to ProductDocumentView correctly', () => {
const rawData: ProductsProductDocument[] = [
{
id: 1,
product_documents_id: {
id: 1,
file: {
id: 'rand-om__-uuid-1234',
filesize: 1000,
filename_download: 'doc1.pdf',
},
type: {
id: 1,
translations: [
{
id: 1,
name: 'manual',
},
],
},
translations: [
{
id: 1,
title: 'Document Title 1',
},
],
},
},
];
expect(toProductDocumentView(rawData)).toEqual([
{
id: '1',
fileId: 'rand-om__-uuid-1234',
filename: 'doc1.pdf',
title: 'Document Title 1',
type: {
id: '1',
name: 'manual',
},
size: 1000,
url: '/api/assets/rand-om__-uuid-1234',
},
]);
});
test('convert raw data with missing translations', () => {
const rawData: ProductsProductDocument[] = [
{
id: 1,
product_documents_id: {
id: 1,
file: {
id: 'rand-om__-uuid-1234',
filesize: 1000,
filename_download: 'doc1.pdf',
},
translations: [],
},
},
];
expect(toProductDocumentView(rawData)).toEqual([
{
id: '1',
fileId: 'rand-om__-uuid-1234',
filename: 'doc1.pdf',
title: '',
type: {
id: '-1',
name: '',
},
size: 1000,
url: '/api/assets/rand-om__-uuid-1234',
},
]);
});
test('convert empty array to empty ProductDocumentView array', () => {
const rawData: ProductsProductDocument[] = [];
expect(toProductDocumentView(rawData)).toEqual([]);
});
test('convert input with wrong type to default value', () => {
const rawData: string[] = ['1', '2'];
expect(toProductDocumentView(rawData)).toEqual([
{
id: '1',
fileId: '',
filename: '',
title: '',
size: 0,
type: {
id: '-1',
name: '',
},
url: '',
},
{
id: '2',
fileId: '',
filename: '',
title: '',
size: 0,
type: {
id: '-1',
name: '',
},
url: '',
},
]);
});
});
/**
* 单元测试: toProductView
*/
describe('toProductView', () => {
const baseData: Product = {
id: 1,
status: 'in-production',
translations: [
{
id: 1,
name: 'Product Name',
summary: 'Product Summary',
description: 'Product Description',
},
],
};
test('convert raw data to ProductView correctly', () => {
const rawData: Product = {
...baseData,
};
expect(toProductView(rawData)).toEqual({
id: '1',
status: 'in-production',
name: 'Product Name',
summary: 'Product Summary',
description: 'Product Description',
images: [],
documents: [],
faqs: [],
specs: [],
});
});
test('convert raw data with missing translations', () => {
const rawData: Product = {
...baseData,
translations: [],
};
expect(toProductView(rawData)).toEqual({
id: '1',
status: 'in-production',
name: '',
summary: '',
description: '',
images: [],
documents: [],
faqs: [],
specs: [],
});
});
test('conert raw data with missing status', () => {
const rawData: Product = {
...baseData,
status: undefined,
};
expect(toProductView(rawData)).toEqual({
id: '1',
status: 'discontinued',
name: 'Product Name',
summary: 'Product Summary',
description: 'Product Description',
images: [],
documents: [],
faqs: [],
specs: [],
});
});
});

View File

@ -0,0 +1,243 @@
import { isObject } from '../../server/utils/object';
import { toDocumentTypeView } from './documentMapper';
/**
* 将 Directus 返回的 ProductImage 数据转换为 ProductImageView 视图模型
*
* @param raw: 原始的 ProductsProductImage 数据
* @returns 转换后的 ProductImageView 对象
*
* @example
* const view = toProductImageView(rawProductImage);
*/
export function toProductImageView(
raw: (ProductsProductImage | string)[]
): ProductImageView[] {
return (raw ?? []).map((item) => {
if (!isObject<ProductsProductImage>(item))
return {
id: item,
image: '',
caption: '',
} satisfies ProductImageView;
const image = item.product_images_id;
if (!isObject<ProductImage>(image))
return {
id: item.id.toString(),
image: '',
caption: '',
} satisfies ProductImageView;
const trans = image.translations?.[0];
return {
id: item.id.toString(),
image: isObject<DirectusFile>(image.image) ? image.image.id : '',
caption: trans?.caption || '',
} satisfies ProductImageView;
});
}
/**
* 将 Directus 返回的 ProductSpecGroup 数据转换为 ProductSpecGroupView 视图模型
*
* @param raw: 原始的 ProductSpecGroup 数据
* @returns 转换后的 ProductSpecGroupView 对象
*
* @example
* const view = toProductSpecGroupView(rawSpecGroup);
*/
export function toProductSpecGroupView(
raw: (ProductSpecGroup | string)[]
): ProductSpecGroupView[] {
return (raw ?? []).map((item) => {
if (!isObject<ProductSpecGroup>(item)) {
return {
id: item,
name: '',
specs: [],
} satisfies ProductSpecGroupView;
}
const trans = item.translations?.[0];
const specs = toProductSpecView(item?.specs ?? []);
return {
id: item.id.toString(),
name: trans?.name ?? '',
specs: specs,
} satisfies ProductSpecGroupView;
});
}
/**
* 将 Directus 返回的 ProductSpec 数据转换为 ProductSpecView 视图模型
*
* @param raw: 原始的 ProductSpec 数据
* @returns 转换后的 ProductSpecView 对象
*
* @example
* const view = toProductSpecView(rawSpecGroup);
*/
export function toProductSpecView(
raw: (ProductSpec | string)[]
): ProductSpecView[] {
return (raw ?? []).map((item) => {
if (!isObject<ProductSpec>(item)) {
return {
id: item,
key: '',
value: '',
} satisfies ProductSpecView;
}
const trans = item.translations?.[0];
return {
id: item.id.toString(),
key: trans?.key ?? '',
value: trans?.value ?? '',
} satisfies ProductSpecView;
});
}
/**
* 将 Directus 返回的 ProductQuestion 数据转换为 ProductQuestionView 视图模型
*
* @param raw: 原始的ProductQuestion 数据
* @returns 转换后的 ProductQuestionView 对象
*
* @example
* const view = toProductQuestionView(rawQuestion);
*/
export function toProductQuestionView(
raw: (ProductsQuestion | string)[]
): ProductQuestionView[] {
return (raw ?? []).map((item) => {
if (!isObject<ProductsQuestion>(item)) {
return {
id: item,
title: '',
content: '',
} satisfies ProductQuestionView;
}
const question = item.questions_id;
if (!isObject<Question>(question)) {
return {
id: item.id.toString(),
title: '',
content: '',
} satisfies ProductQuestionView;
}
const trans = question.translations?.[0];
return {
id: item.id.toString(),
title: trans?.title ?? '',
content: trans?.content ?? '',
} satisfies ProductQuestionView;
});
}
/**
* 将 Directus 返回的 ProductDocument 数据转换为 ProductDocumentView 视图模型
*
* @param raw: 原始的ProductDocument 数据
* @returns 转换后的 ProductDocumentView 对象
*
* @example
* const view = toProductDocumentView(rawDocument);
*/
export function toProductDocumentView(
raw: (ProductsProductDocument | string)[]
): ProductDocumentView[] {
return (raw ?? []).map((item) => {
if (!isObject<ProductsProductDocument>(item)) {
return {
id: item,
fileId: '',
filename: '',
size: 0,
title: '',
url: '',
type: {
id: '-1',
name: '',
},
} satisfies ProductDocumentView;
}
const document = item.product_documents_id;
if (!isObject<ProductDocument>(document)) {
return {
id: item.id.toString(),
fileId: '',
filename: '',
size: 0,
title: '',
url: '',
type: {
id: '-1',
name: '',
},
} satisfies ProductDocumentView;
}
const file = isObject<DirectusFile>(document.file)
? document.file
: undefined;
const url = file ? `/api/assets/${file.id}` : '';
const trans = document.translations?.[0];
const typeView = toDocumentTypeView(document.type ?? null);
return {
id: item.id.toString(),
fileId: file?.id ?? '',
filename: file?.filename_download ?? '',
size: file?.filesize ?? 0,
title: trans?.title ?? '',
url: url,
type: typeView,
} satisfies ProductDocumentView;
});
}
/**
* 将 Directus 返回的 Product 数据转换为 ProductView 视图模型
*
* @param raw: 原始的 Product 数据
* @returns 转换后的 ProductView 对象
*
* @example
* const view = toProductView(rawProduct);
*/
export function toProductView(raw: Product): ProductView {
const trans = raw.translations?.[0];
const status = raw.status ?? 'discontinued';
const images = toProductImageView(raw.images ?? []);
const specs = toProductSpecGroupView(raw.specs ?? []);
const faqs = toProductQuestionView(raw.faqs ?? []);
const documents = toProductDocumentView(raw.documents ?? []);
return {
id: raw.id.toString(),
status: status,
name: trans?.name ?? '',
summary: trans?.summary ?? '',
images: images,
description: trans?.description ?? '',
specs: specs,
faqs: faqs,
documents: documents,
} satisfies ProductView;
}

View File

@ -0,0 +1,139 @@
import { describe, expect, test } from 'vitest';
import { toQuestionListView, toQuestionTypeView } from './questionMapper';
/**
* 单元测试: toQuestionTypeView
*/
describe('toQuestionTypeView', () => {
const baseData: QuestionType = {
id: 1,
translations: [{ id: 1, name: 'Type Name' }],
};
test('convert raw data to QuestionTypeView correctly', () => {
const rawData: QuestionType = {
...baseData,
};
expect(toQuestionTypeView(rawData)).toEqual({
id: '1',
name: 'Type Name',
});
});
test('convert raw data with missing translations', () => {
const rawData: QuestionType = {
...baseData,
translations: [],
};
expect(toQuestionTypeView(rawData)).toEqual({
id: '1',
name: '',
});
});
test('convert null input to default QuestionTypeView', () => {
const rawData: QuestionType | null = null;
expect(toQuestionTypeView(rawData)).toEqual({
id: '-1',
name: '',
});
});
});
/**
* 单元测试: toQuestionListView
*/
describe('toQuestionListView', () => {
const baseData: Question = {
id: 1,
type: {
id: 1,
translations: [{ id: 1, name: 'Type Name' }],
},
translations: [
{ id: 1, title: 'Question Title', content: 'Question Answer' },
],
products: [
{
id: 1,
products_id: {
id: 1,
translations: [{ id: 1, name: 'Product Name' }],
product_type: {
id: 1,
translations: [{ id: 1, name: 'Type Name' }],
},
},
},
],
};
test('convert raw data to QuestionListView correctly', () => {
const rawData: Question = {
...baseData,
};
expect(toQuestionListView(rawData)).toEqual({
id: '1',
type: {
id: '1',
name: 'Type Name',
},
title: 'Question Title',
content: 'Question Answer',
products: [
{
id: '1',
name: 'Product Name',
type: {
id: '1',
name: 'Type Name',
},
},
],
});
});
test('convert raw data with missing translations', () => {
const rawData: Question = {
...baseData,
translations: [],
products: [
{
id: 1,
products_id: {
id: 1,
translations: [],
product_type: {
id: 1,
translations: [],
},
},
},
],
};
expect(toQuestionListView(rawData)).toEqual({
id: '1',
type: {
id: '1',
name: 'Type Name',
},
title: '',
content: '',
products: [
{
id: '1',
name: '',
type: {
id: '1',
name: '',
},
},
],
});
});
});

View File

@ -0,0 +1,74 @@
import { isObject } from '../../server/utils/object';
/**
* 将 Directus 返回的 QuestionType 类型转换为 QuestionTypeView 视图模型
*
* @param raw: 原始的 QuestionType 数据
* @returns 转换后的 QuestionTypeView 对象
*
* @example
* const view = toQuestionTypeView(rawQuestionType);
*/
export function toQuestionTypeView(
raw: QuestionType | string | null
): QuestionTypeView {
if (typeof raw === 'string' || raw === null) {
return {
id: '-1',
name: '',
} satisfies QuestionTypeView;
}
const trans = raw.translations?.[0];
return {
id: raw.id.toString(),
name: trans?.name ?? '',
};
}
/**
* 将 Directus 返回的 Question 数据转换为 QuestionListView 视图模型
*
* @param raw: 原始的 Question 数据
* @returns 转换后的 QuestionListView 对象
* ---
* @example
* const view = toQuestionListView(rawQuestion);
*/
export function toQuestionListView(raw: Question): QuestionListView {
const trans = raw.translations?.[0];
const type = toQuestionTypeView(raw.type ?? null);
const related_products: QuestionListProduct[] = (raw.products ?? [])
.filter(isObject<ProductsQuestion>)
.map((item) => item.products_id)
.filter(isObject<Product>)
.map((item) => {
const translations = item.translations?.[0];
const product_type = isObject<ProductType>(item.product_type)
? ({
id: item.product_type.id.toString(),
name: item.product_type.translations?.[0]?.name ?? '',
} satisfies QuestionListProductType)
: ({
id: '',
name: '',
} satisfies QuestionListProductType);
return {
id: item.id.toString(),
name: translations?.name ?? '',
type: product_type,
};
});
return {
id: raw.id.toString(),
type: type,
title: trans?.title ?? '',
content: trans?.content ?? '',
products: related_products,
};
}

View File

@ -12,5 +12,5 @@ export function toSearchItemView<T extends MeiliSearchItemType>(
type: T
): SearchItemView {
const converter = converters[type];
return converter ? converter(item) : null;
return converter(item);
}

Some files were not shown because too many files have changed in this diff Show More