Compare commits

...

98 Commits

Author SHA1 Message Date
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
e215a4d498 fix: 修正GraphQL无法正常读取的问题
All checks were successful
deploy to server / build-and-deploy (push) Successful in 3m8s
- 将graphql查询文件移至server/assets,他们在构建后会以二进制形式写入server的存储中
- 在server端通过storage读取数据
2025-11-12 19:51:14 +08:00
50f0779a8e fix: 修正无法正常读取GraphQL的问题
All checks were successful
deploy to server / build-and-deploy (push) Successful in 3m22s
- 将GraphQL移至server/assets,在构建后会被写入server中
- 在server端通过storage读取数据
2025-11-12 19:49:17 +08:00
5ee6005ad1 refactor: 将前后端通信由app端移至server端
All checks were successful
deploy to server / build-and-deploy (push) Successful in 3m9s
- graphql请求的server端实现
- 文件请求的server端实现
2025-11-12 18:25:21 +08:00
a520775a8d refactor: 将文件请求由app端转到server端
All checks were successful
deploy to server / build-and-deploy (push) Successful in 3m2s
2025-11-12 18:19:21 +08:00
a5f3895794 refactor: 将数据获取从app端移至server端
- 调整数据获取位置以提升安全性
- 对于后端状态为Archived的数据,通过server控制不进行获取
2025-11-12 17:54:43 +08:00
58223734a2 feat: 前端请求添加Status控制
All checks were successful
deploy to server / build-and-deploy (push) Successful in 3m12s
- 产品页/解决方案页仅获取已发布条目
2025-11-12 14:50:55 +08:00
9163c7fe9a feat: 为前端请求添加Status控制
All checks were successful
deploy to server / build-and-deploy (push) Successful in 3m6s
- 在产品页/解决方案页等路由仅获取已发布条目
2025-11-12 14:48:51 +08:00
726c38a75d refactor: 重构项目的数据获取方法
All checks were successful
deploy to server / build-and-deploy (push) Successful in 3m1s
- 将相关数据获取由REST转为GraphQL
- 声明GraphQL模块
- 修改相关的Mapper与测试方法
2025-11-11 17:05:44 +08:00
81caa02d11 chore: 删除无用代码
All checks were successful
deploy to server / build-and-deploy (push) Successful in 3m30s
2025-11-11 17:02:02 +08:00
8213eec217 refactor: 关于我们页的API重构
Some checks failed
deploy to server / build-and-deploy (push) Has been cancelled
2025-11-11 17:01:18 +08:00
ac9e7b4436 refactor: 联系信息页的API重构 2025-11-11 16:58:40 +08:00
5ad6133252 refactor: 文档资料页的API重构 2025-11-11 16:55:41 +08:00
a07d77dde7 refactor: 问题列表的API重构 2025-11-11 16:49:58 +08:00
3e7b195002 refactor: 解决方案页的API重构 2025-11-11 16:43:08 +08:00
706b754905 refactor: 解决方案列表的API重构 2025-11-11 16:35:20 +08:00
0d77e97ad5 test: 完善测试 2025-11-11 16:15:05 +08:00
ac658e01ae refactor: 调整首页数据获取API
- 将首页的数据获取由REST重构为GraphQL
2025-11-11 16:14:58 +08:00
a93f508e85 refactor: 调整GraphQL导入形式
- 以纯文本形式导入
2025-11-11 16:08:24 +08:00
1290189d84 style: 格式化graphql文件 2025-11-11 16:01:20 +08:00
691dd34127 refactor: 产品页与产品列表的API重构
- 将产品页与产品列表的API由REST重构为GraphQL
- 修改Mapper与单元测试
2025-11-11 15:58:15 +08:00
7e7775ccc6 feat: 为Directus插件提供GraphQL支持
- 在Nuxt中引入GraphQL加载模块
- 为Directus引入GraphQl, Query
2025-11-11 15:52:27 +08:00
b234018f72 fix: 调整筛选条目排序权重
All checks were successful
deploy to server / build-and-deploy (push) Successful in 3m46s
- 以搜索条目匹配程度为标准排序
- 移除拼音支持
2025-11-10 17:28:24 +08:00
7b19f59409 fix: 调整筛选条目排序权重
All checks were successful
deploy to server / build-and-deploy (push) Successful in 3m49s
- 以搜索条目匹配程度为标准排序
- 移除拼音支持
2025-11-10 17:26:23 +08:00
9de6ab8799 fix: 调整模糊匹配阈值
All checks were successful
deploy to server / build-and-deploy (push) Successful in 3m6s
- 将阈值由0.3调整为0.6
2025-11-10 16:42:56 +08:00
86b0c29dcf fix: 调整模糊匹配阈值
Some checks failed
deploy to server / build-and-deploy (push) Has been cancelled
- 将阈值有0.3调整至0.6
2025-11-10 16:42:30 +08:00
352be1686a feat: 产品筛选器的模糊搜索
All checks were successful
deploy to server / build-and-deploy (push) Successful in 3m7s
- 引入前端依赖Fuse.js, pinyin-pro分别用于模糊匹配与拼音转换
- 新增Utils-fuzzyFilter,封装了Fuse的初始化/模糊匹配与相关工具函数
- 将前端由字符串匹配改为模糊匹配
2025-11-10 16:05:44 +08:00
710a0cdc5b feat: 支持拼音搜索
All checks were successful
deploy to server / build-and-deploy (push) Successful in 3m38s
- 使用pinyin-pro进行汉语拼音转换
- 调整搜索权重
2025-11-10 15:39:47 +08:00
4c8dfb5b56 feat: 产品筛选器的模糊搜索功能
- 引入纯前端依赖Fuse.js用于模糊匹配
- 新增Utils-fuzzyFilter封装Fuse的初始化与匹配
- 在前端将字符串匹配改为模糊匹配
2025-11-10 15:08:32 +08:00
007c8f9ce9 feat: 产品列表与解决方案列表的排序
All checks were successful
deploy to server / build-and-deploy (push) Successful in 3m4s
- 为产品/解决方案类型添加sort字段用于排序
- 各个栏目的类型按照sort升序排序
- 更新directus类型
2025-11-08 15:51:33 +08:00
142 changed files with 4559 additions and 1933 deletions

5
.graphqlrc.yaml Normal file
View File

@ -0,0 +1,5 @@
schema:
- 'http://192.168.86.5:8055/graphql':
headers:
Authorization: 'Bearer ixSWeViHIqwj6_r7NM-uZVR3NNOyBa_W'
documents: 'app/graphql/**/*.{graphql,js,ts,jsx,tsx}'

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"> <div class="product-detail">
<el-tabs v-model="activeName" class="product-tabs" stretch> <el-tabs v-model="activeName" class="product-tabs" stretch>
<el-tab-pane :label="$t('product-tab.details')" name="details"> <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>
<el-tab-pane :label="$t('product-tab.specs')" name="specs"> <el-tab-pane :label="$t('product-tab.specs')" name="specs">
<spec-table :data="product.specs" /> <spec-table :data="product.specs" />
@ -25,7 +33,13 @@
}, },
}); });
const hydrated = ref(false);
const activeName = ref('details'); // 默认选中概览标签 const activeName = ref('details'); // 默认选中概览标签
onMounted(() => {
hydrated.value = true;
});
</script> </script>
<style scoped> <style scoped>

View File

@ -38,6 +38,10 @@
<div class="product-info"> <div class="product-info">
<h1>{{ product.name }}</h1> <h1>{{ product.name }}</h1>
<p class="summary">{{ product.summary }}</p> <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>
</div> </div>
</template> </template>
@ -105,6 +109,10 @@
margin-bottom: 2rem; margin-bottom: 2rem;
} }
.discontinued-warning {
color: var(--el-color-error);
}
@media (max-width: 768px) { @media (max-width: 768px) {
.product-header { .product-header {
grid-template-columns: 1fr; 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"> <div class="search-results">
<NuxtLink <NuxtLink
v-for="hit in paginatedHits" v-for="hit in paginatedHits"
:key="`${hit.type}-${hit.id}`" :key="`${hit.sectionType}-${hit.id}`"
:to="localePath(resolveHitLink(hit))" :to="localePath(resolveHitLink(hit))"
> >
<el-card class="result-card"> <search-result-card
<h3 class="result-title">{{ hit.title }}</h3> :item="hit"
<p v-if="hit.summary" class="result-summary"> :type-label="getIndexLabel(hit.sectionType)"
{{ 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>
</NuxtLink> </NuxtLink>
</div> </div>
@ -72,7 +66,7 @@
const items = props.searchItems; const items = props.searchItems;
const filteredHits = computed(() => { const filteredHits = computed(() => {
if (props.category) { if (props.category) {
return items.filter((item) => item.type === props.category); return items.filter((item) => item.sectionType === props.category);
} else { } else {
return items; return items;
} }
@ -116,19 +110,19 @@
const slug = String(slugCandidate); const slug = String(slugCandidate);
if (item.type === 'product') { if (item.sectionType === 'product') {
return localePath({ path: `/products/${slug}` }); return localePath({ path: `/products/${slug}` });
} }
if (item.type === 'solution') { if (item.sectionType === 'solution') {
return localePath({ path: `/solutions/${slug}` }); return localePath({ path: `/solutions/${slug}` });
} }
if (item.type === 'document') { if (item.sectionType === 'document') {
return localePath({ path: `/download/${slug}` }); return localePath({ path: `/download/${slug}` });
} }
if (item.type === 'question') { if (item.sectionType === 'question') {
return localePath({ path: `/support/faq`, query: { focus: slug } }); return localePath({ path: `/support/faq`, query: { focus: slug } });
} }

View File

@ -22,17 +22,17 @@
}>(); }>();
const tabs = [ const tabs = [
{ name: 'all', label: '全部' }, { name: 'all', label: $t('all') },
{ name: 'product', label: '产品' }, { name: 'product', label: $t('search.sections.product') },
{ name: 'solution', label: '解决方案' }, { name: 'solution', label: $t('search.sections.solution') },
{ name: 'question', label: '相关问题' }, { name: 'question', label: $t('search.sections.faq') },
{ name: 'document', label: '文档资料' }, { name: 'document', label: $t('search.sections.document') },
]; ];
const resultCount = computed(() => { const resultCount = computed(() => {
const map: Record<string, number> = { all: props.searchItems.length }; const map: Record<string, number> = { all: props.searchItems.length };
for (const item of props.searchItems) { for (const item of props.searchItems) {
map[item.type] = (map[item.type] ?? 0) + 1; map[item.sectionType] = (map[item.sectionType] ?? 0) + 1;
} }
return map; return map;
}); });

View File

@ -2,16 +2,15 @@
<article class="solution-defail"> <article class="solution-defail">
<header class="solution-header"> <header class="solution-header">
<h1 class="solution-title">{{ solution.title }}</h1> <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> <p class="solution-summary">{{ solution.summary }}</p>
</header> </header>
<section class="solution-content"> <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> </section>
</article> </article>
</template> </template>
@ -23,6 +22,12 @@
default: null, default: null,
}, },
}); });
const hydrated = ref(false);
onMounted(() => {
hydrated.value = true;
});
</script> </script>
<style scoped> <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> <template>
<div class="question-category"> <div class="question-category">
<el-row class="hide-on-mobile" :gutter="12"> <el-row :gutter="12">
<el-col :span="8"> <el-col :span="12" :xs="12">
<span class="select-label">{{ <span class="select-label">{{
$t('product-filter.product-type') $t('product-filter.product-type')
}}</span> }}</span>
<el-select <el-select
v-model="model.selectedType" v-model="model.selectedProductType"
:placeholder="$t('product-filter.select-product-type')" :placeholder="$t('product-filter.select-product-type')"
clearable clearable
> >
@ -19,7 +19,7 @@
</el-select> </el-select>
</el-col> </el-col>
<el-col :span="8"> <el-col :span="12" :xs="12">
<span class="select-label">{{ <span class="select-label">{{
$t('product-filter.product-model') $t('product-filter.product-model')
}}</span> }}</span>
@ -37,7 +37,25 @@
</el-select> </el-select>
</el-col> </el-col>
<el-col :span="8"> <el-col :span="12" :xs="24">
<span class="select-label">
{{ $t('product-filter.question-type') }}
</span>
<el-select
v-model="model.selectedQuestionType"
:placeholder="$t('product-filter.select-question-type')"
clearable
>
<el-option
v-for="questionType in questionTypeOptions"
: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> <span class="select-label">{{ $t('product-filter.keyword') }}</span>
<el-input <el-input
v-model="model.keyword" v-model="model.keyword"
@ -47,52 +65,6 @@
/> />
</el-col> </el-col>
</el-row> </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-select
v-model="model.selectedType"
: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">
<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">
<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-row>
</div> </div>
</template> </template>
@ -101,19 +73,24 @@
defineProps({ defineProps({
productTypeOptions: { productTypeOptions: {
type: Array as () => Array<{ id: number; name: string }>, type: Array as () => Array<QuestionListProductType>,
default: () => [], default: () => [],
}, },
productOptions: { productOptions: {
type: Array as () => Array<{ id: number; name: string }>, type: Array as () => Array<QuestionListProduct>,
default: () => [],
},
questionTypeOptions: {
type: Array as () => Array<QuestionTypeView>,
default: () => [], default: () => [],
}, },
}); });
const model = defineModel<{ const model = defineModel<{
selectedProduct: string | null;
selectedProductType: string | null;
selectedQuestionType: string | null;
keyword: string; keyword: string;
selectedType: number | null;
selectedProduct: number | null;
}>(); }>();
</script> </script>
@ -132,18 +109,4 @@
height: 40px; height: 40px;
font-size: 0.9rem; 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> </style>

View File

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

View File

@ -122,6 +122,8 @@
const errorText = computed(() => error.value?.message ?? null); const errorText = computed(() => error.value?.message ?? null);
const fileMeta = computed(() => props.file ?? data.value ?? null); const fileMeta = computed(() => props.file ?? data.value ?? null);
logger.debug('FilePreviewer - fileMeta:', fileMeta.value);
/** 预览源地址:支持在 file.url 上追加额外 query如临时 token、inline */ /** 预览源地址:支持在 file.url 上追加额外 query如临时 token、inline */
const src = computed<string>(() => { const src = computed<string>(() => {
if (!fileMeta.value) return ''; if (!fileMeta.value) return '';

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

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

View File

@ -53,7 +53,7 @@
class="hide-on-mobile" class="hide-on-mobile"
type="info" type="info"
:underline="false" :underline="false"
href="http://cal.jinshen.cn" href="http://cal.3w.jinshen.cn"
target="_blank" target="_blank"
> >
<el-icon class="mdi mdi-calculator action-icon" /> <el-icon class="mdi mdi-calculator action-icon" />
@ -67,6 +67,12 @@
<el-dropdown-menu> <el-dropdown-menu>
<el-dropdown-item command="zh">简体中文</el-dropdown-item> <el-dropdown-item command="zh">简体中文</el-dropdown-item>
<el-dropdown-item command="en">English</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> </el-dropdown-menu>
</template> </template>
</el-dropdown> </el-dropdown>
@ -125,7 +131,9 @@
mode="vertical" mode="vertical"
@select="mobileMenuVisible = false" @select="mobileMenuVisible = false"
> >
<el-menu-item @click="openExternalLink('http://cal.jinshen.cn')"> <el-menu-item
@click="openExternalLink('http://cal.3w.jinshen.cn')"
>
{{ $t('navigation.calculator') }} {{ $t('navigation.calculator') }}
</el-menu-item> </el-menu-item>
</el-menu> </el-menu>
@ -140,6 +148,12 @@
<el-dropdown-menu> <el-dropdown-menu>
<el-dropdown-item command="zh">简体中文</el-dropdown-item> <el-dropdown-item command="zh">简体中文</el-dropdown-item>
<el-dropdown-item command="en">English</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> </el-dropdown-menu>
</template> </template>
</el-dropdown> </el-dropdown>

View File

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

View File

@ -8,7 +8,15 @@
:title="question.title" :title="question.title"
:name="question.id" :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-item>
</el-collapse> </el-collapse>
</div> </div>
@ -25,6 +33,8 @@
const activeNames = ref<(string | number)[]>([]); const activeNames = ref<(string | number)[]>([]);
const hydrated = ref(false);
// 当路由变化(包括初次挂载)时,检查是否需要聚焦 // 当路由变化(包括初次挂载)时,检查是否需要聚焦
watch( watch(
() => route.query.focus, () => route.query.focus,
@ -35,7 +45,7 @@
// 确保渲染完成后再操作 DOM // 确保渲染完成后再操作 DOM
await nextTick(); await nextTick();
const target = props.questions.find((q) => q.id === Number(focusId)); const target = props.questions.find((q) => q.id === focusId);
if (!target) return; if (!target) return;
// 展开目标项 // 展开目标项
@ -47,6 +57,10 @@
}, },
{ immediate: true } { immediate: true }
); );
onMounted(() => {
hydrated.value = true;
});
</script> </script>
<style scoped> <style scoped>

View File

@ -1,29 +1,17 @@
import { readSingleton } from '@directus/sdk';
export const useCompanyProfile = () => { export const useCompanyProfile = () => {
const { $directus } = useNuxtApp();
const { getDirectusLocale } = useLocalizations(); const { getDirectusLocale } = useLocalizations();
const locale = getDirectusLocale(); const locale = getDirectusLocale();
return useAsyncData(`company-profile-${locale}`, async () => { return useAsyncData(`company-profile-${locale}`, async () => {
return await $directus.request( try {
readSingleton('company_profile', { const data = await $fetch(`/api/cms/companyProfile`, {
fields: [ headers: { 'x-locale': locale },
'id', });
{
translations: ['id', 'content'], return data;
}, } catch (error) {
], logger.error('Error fetching company profile: ', error);
deep: { throw error;
translations: { }
_filter: {
languages_code: {
_eq: locale,
},
},
},
},
})
);
}); });
}; };

View File

@ -1,29 +1,17 @@
import { readSingleton } from '@directus/sdk';
export const useContactInfo = () => { export const useContactInfo = () => {
const { $directus } = useNuxtApp();
const { getDirectusLocale } = useLocalizations(); const { getDirectusLocale } = useLocalizations();
const locale = getDirectusLocale(); const locale = getDirectusLocale();
return useAsyncData(`contact-info-${locale}`, async () => { return useAsyncData(`contact-info-${locale}`, async () => {
return await $directus.request( try {
readSingleton('contact_info', { const data = await $fetch('/api/cms/contactInfo', {
fields: [ headers: { 'x-locale': locale },
'id', });
{
translations: ['id', 'content'], return data;
}, } catch (error) {
], logger.error('Error fetching contact info: ', error);
deep: { throw error;
translations: { }
_filter: {
languages_code: {
_eq: locale,
},
},
},
},
})
);
}); });
}; };

View File

@ -1,19 +1,14 @@
export const useDirectusFiles = () => { export const useDirectusFiles = () => {
const config = useRuntimeConfig();
const baseUrl = config.public.directus.url;
const getFileUrl = ( const getFileUrl = (
id?: string | null, id?: string | null,
options?: Record<string, string | number | boolean> options?: Record<string, string | number | boolean>
): string => { ): string => {
if (!id) return ''; if (!id) return '';
const query = options
? '?' + const params = new URLSearchParams(
new URLSearchParams( options as Record<string, string>
Object.entries(options).map(([key, value]) => [key, String(value)]) ).toString();
).toString() return `/api/assets/${id}${params ? `?${params}` : ''}`;
: '';
return `${baseUrl}/assets/${id}${query}`;
}; };
return { return {

View File

@ -1,8 +1,4 @@
export const useDirectusImage = () => { export const useDirectusImage = () => {
const config = useRuntimeConfig();
const baseUrl = config.public.directus.url;
const token = config.public.directus.token;
type DirectusAssetParams = { type DirectusAssetParams = {
width?: number; width?: number;
height?: number; height?: number;
@ -13,19 +9,11 @@ export const useDirectusImage = () => {
const getImageUrl = (id?: string | null, options?: DirectusAssetParams) => { const getImageUrl = (id?: string | null, options?: DirectusAssetParams) => {
if (!id) return ''; if (!id) return '';
const queryToken = token ? 'access_token=' + token : '';
const queryOptions = options const params = new URLSearchParams(
? new URLSearchParams( options as Record<string, string>
Object.fromEntries( ).toString();
Object.entries(options).map(([key, value]) => [key, String(value)]) return `/api/assets/${id}${params ? `?${params}` : ''}`;
)
).toString
: '';
const query =
queryToken || queryOptions
? `?${[queryToken, queryOptions].filter(Boolean).join('&')}`
: '';
return `${baseUrl}/assets/${id}${query}`;
}; };
return { getImageUrl }; return { getImageUrl };

View File

@ -1,67 +1,17 @@
import { readItems } from '@directus/sdk';
export const useDocumentList = () => { export const useDocumentList = () => {
const { $directus } = useNuxtApp();
const { getDirectusLocale } = useLocalizations(); const { getDirectusLocale } = useLocalizations();
const locale = getDirectusLocale(); const locale = getDirectusLocale();
return useAsyncData(`document-list-${locale}`, async () => { return useAsyncData(`document-list-${locale}`, async () => {
return await $directus.request( try {
readItems('product_documents', { const data = $fetch(`/api/cms/documentList`, {
fields: [ headers: { 'x-locale': locale },
'id', });
{
file: ['id', 'filesize', 'filename_download'], return data;
}, } catch (error) {
{ logger.error('Error fetching document list:', error);
translations: ['id', 'title'], throw error;
}, }
{
products: [
'id',
{
products_id: [
'id',
{
translations: ['id', 'name'],
},
{
product_type: [
'id',
{
translations: ['id', 'name'],
},
],
},
],
},
],
},
],
deep: {
translations: {
_filter: {
languages_code: { _eq: locale },
},
},
products: {
products_id: {
translations: {
_filter: {
languages_code: { _eq: locale },
},
},
product_type: {
translations: {
_filter: {
languages_code: { _eq: locale },
},
},
},
},
},
},
})
);
}); });
}; };

View File

@ -1,54 +1,17 @@
import { readSingleton } from '@directus/sdk';
export const useHomepage = () => { export const useHomepage = () => {
const { $directus } = useNuxtApp();
const { getDirectusLocale } = useLocalizations(); const { getDirectusLocale } = useLocalizations();
const locale = getDirectusLocale(); const locale = getDirectusLocale();
return useAsyncData(`homepage-${locale}`, async () => { return useAsyncData(`homepage-${locale}`, async () => {
return await $directus.request( try {
readSingleton('homepage', { const data = $fetch(`/api/cms/homepage`, {
fields: [ headers: { 'x-locale': locale },
'id', });
{
carousel: ['id', 'directus_files_id'], return data;
}, } catch (error) {
{ logger.error('Error fetching homepage:', error);
recommend_products: [ throw error;
'id', }
{
translations: ['id', 'name', 'summary'],
},
'cover',
],
},
{
recommend_solutions: [
'id',
{
translations: ['id', 'title', 'summary'],
},
'cover',
],
},
],
deep: {
recommend_products: {
translations: {
_filter: {
languages_code: { _eq: locale },
},
},
},
recommend_solutions: {
translations: {
_filter: {
languages_code: { _eq: locale },
},
},
},
},
})
);
}); });
}; };

View File

@ -1,110 +1,17 @@
import { readItem } from '@directus/sdk';
export const useProduct = (id: string) => { export const useProduct = (id: string) => {
const { $directus } = useNuxtApp();
const { getDirectusLocale } = useLocalizations(); const { getDirectusLocale } = useLocalizations();
const locale = getDirectusLocale(); const locale = getDirectusLocale();
return useAsyncData(`product-${id}-${locale}`, async () => { return useAsyncData(`product-${id}-${locale}`, async () => {
return await $directus.request( try {
readItem('products', id, { const data = await $fetch(`/api/cms/product/${id}`, {
fields: [ headers: { 'x-locale': locale },
'id', });
{ translations: ['id', 'name', 'summary', 'description'] },
{ return data;
images: [ } catch (error) {
'id', logger.error('Error fetching product: ', error);
{ throw error;
product_images_id: [ }
'id',
'image',
{ translations: ['id', 'caption'] },
],
},
],
},
{
specs: [
'id',
{
translations: ['*'],
},
{
specs: [
'id',
{
translations: ['id', 'key', 'value'],
},
],
},
],
},
{
faqs: [
'id',
{
questions_id: [
'id',
{
translations: ['id', 'title', 'content'],
},
],
},
],
},
{
documents: [
'id',
{
product_documents_id: [
'id',
{
file: ['id', 'filesize', 'filename_download'],
},
{
translations: ['id', 'title'],
},
],
},
],
},
],
deep: {
translations: {
_filter: {
languages_code: { _eq: locale },
},
},
images: {
product_images_id: {
translations: {
_filter: {
languages_code: { _eq: locale },
},
},
},
},
faqs: {
questions_id: {
translations: {
_filter: {
languages_code: { _eq: locale },
},
},
},
},
documents: {
documents_id: {
translations: {
_filter: {
languages_code: { _eq: locale },
},
},
},
},
},
})
);
}); });
}; };

View File

@ -1,43 +1,17 @@
import { readItems } from '@directus/sdk';
export const useProductList = () => { export const useProductList = () => {
const { $directus } = useNuxtApp();
const { getDirectusLocale } = useLocalizations(); const { getDirectusLocale } = useLocalizations();
const locale = getDirectusLocale(); const locale = getDirectusLocale();
return useAsyncData(`product-list-${locale}`, async () => { return useAsyncData(`product-list-${locale}`, async () => {
return await $directus.request( try {
readItems('products', { const data = await $fetch(`/api/cms/productList`, {
fields: [ headers: { 'x-locale': locale },
'id', });
{ translations: ['id', 'name', 'summary'] },
'cover', return data;
{ } catch (error) {
product_type: [ logger.error('Error fetching product list: ', error);
'id', throw error;
{ }
translations: ['id', 'name'],
},
'sort',
],
},
],
deep: {
translations: {
_filter: {
languages_code: { _eq: locale },
},
},
product_type: {
translations: {
_filter: {
languages_code: { _eq: locale },
},
},
},
},
})
);
}); });
}; };

View File

@ -1,63 +1,17 @@
import { readItems } from '@directus/sdk';
export const useQuestionList = () => { export const useQuestionList = () => {
const { $directus } = useNuxtApp();
const { getDirectusLocale } = useLocalizations(); const { getDirectusLocale } = useLocalizations();
const locale = getDirectusLocale(); const locale = getDirectusLocale();
return useAsyncData(`question-list-${locale}`, async () => { return useAsyncData(`question-list-${locale}`, async () => {
return await $directus.request( try {
readItems('questions', { const data = $fetch(`/api/cms/questionList`, {
fields: [ headers: { 'x-locale': locale },
'id', });
{
translations: ['*'], return data;
}, } catch (error) {
{ logger.error('Error fetching question list:', error);
products: [ throw error;
'id', }
{
products_id: [
'id',
{
product_type: [
'id',
{
translations: ['id', 'name'],
},
],
},
{ translations: ['id', 'name'] },
],
},
],
},
],
deep: {
translations: {
_filter: {
languages_code: { _eq: locale },
},
},
products: {
products_id: {
product_type: {
translations: {
_filter: {
languages_code: { _eq: locale },
},
},
},
translations: {
_filter: {
languages_code: { _eq: locale },
},
},
},
},
},
})
);
}); });
}; };

View File

@ -1,28 +1,17 @@
import { readItem } from '@directus/sdk';
export const useSolution = (id: string) => { export const useSolution = (id: string) => {
const { $directus } = useNuxtApp();
const { getDirectusLocale } = useLocalizations(); const { getDirectusLocale } = useLocalizations();
const locale = getDirectusLocale(); const locale = getDirectusLocale();
return useAsyncData(`solution-${id}-${locale}`, async () => { return useAsyncData(`solution-${id}-${locale}`, async () => {
return await $directus.request( try {
readItem('solutions', id, { const data = await $fetch(`/api/cms/solution/${id}`, {
fields: [ headers: { 'x-locale': locale },
'id', });
{
translations: ['*'], return data;
}, } catch (error) {
'create_at', logger.error('Error fetching solution: ', error);
], throw error;
deep: { }
translations: {
_filter: {
languages_code: { _eq: locale },
},
},
},
})
);
}); });
}; };

View File

@ -1,38 +1,17 @@
import { readItems } from '@directus/sdk';
export const useSolutionList = () => { export const useSolutionList = () => {
const { $directus } = useNuxtApp();
const { getDirectusLocale } = useLocalizations(); const { getDirectusLocale } = useLocalizations();
const locale = getDirectusLocale(); const locale = getDirectusLocale();
return useAsyncData(`solution-list-${locale}`, async () => { return useAsyncData(`solution-list-${locale}`, async () => {
return await $directus.request( try {
readItems('solutions', { const data = $fetch(`/api/cms/solutionList`, {
fields: [ headers: { 'x-locale': locale },
'id', });
'cover',
{ return data;
type: ['id', { translations: ['id', 'name'] }, 'sort'], } catch (error) {
}, logger.error('Error fetching solution list:', error);
{ throw error;
translations: ['id', 'title', 'summary'], }
},
],
deep: {
type: {
translations: {
_filter: {
languages_code: { _eq: locale },
},
},
},
translations: {
_filter: {
languages_code: { _eq: locale },
},
},
},
})
);
}); });
}; };

View File

@ -1,3 +1,2 @@
export * from './directus'; export * from './directus';
export * from './useLocalizations'; 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 type { Language as ElementLanguage } from 'element-plus/es/locale';
import zhCn from 'element-plus/es/locale/lang/zh-cn'; import zhCn from 'element-plus/es/locale/lang/zh-cn';
import en from 'element-plus/es/locale/lang/en'; 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', directus: 'en-US',
element: en, element: en,
}, },
es: {
directus: 'es-ES',
element: es,
},
ru: {
directus: 'ru-RU',
element: ru,
},
} satisfies Record<string, LocaleMapping>; } 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,178 +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: '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: '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,153 +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;
return {
id: raw.id,
product_type: type,
name: trans.name,
summary: trans.summary,
cover: raw.cover.toString(),
};
}
/**
* 将 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) => {
return {
id: item.id,
image: item.image.toString(),
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

@ -4,20 +4,29 @@
<app-breadcrumb class="breadcrumb" :items="breadcrumbItems" /> <app-breadcrumb class="breadcrumb" :items="breadcrumbItems" />
<div class="content"> <div class="content">
<markdown-renderer :content="content.content || ''" /> <!-- 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> -->
</div> </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"> <div class="button-group">
<NuxtLink :to="$localePath('/support/contact-us')"> <learn-more-card
<el-card class="card-button"> :title="$t('navigation.contact-info')"
<el-icon class="icon" size="80"> :icon="ElIconService"
<ElIconService /> :to="$localePath('/support/contact-us')"
</el-icon> />
<br /> <learn-more-card
{{ $t('navigation.contact-info') }} :title="$t('navigation.address')"
</el-card> :icon="ElIconMapLocation"
</NuxtLink> @click="openMap"
/>
</div> </div>
</div> </div>
<div v-else class="loading"> <div v-else class="loading">
@ -28,13 +37,16 @@
<script setup lang="ts"> <script setup lang="ts">
const localePath = useLocalePath(); const localePath = useLocalePath();
const hydrated = ref(false);
const breadcrumbItems = [ const breadcrumbItems = [
{ label: $t('navigation.home'), to: localePath('/') }, { label: $t('navigation.home'), to: localePath('/') },
{ label: $t('navigation.about-us') }, { label: $t('navigation.about-us') },
]; ];
const { data, pending, error } = await useCompanyProfile(); const { data: companyProfile, pending, error } = await useCompanyProfile();
const content = computed(() => toCompanyProfileView(data.value)); const openMap = () => {
window.open(localePath('/locate'));
};
watch(error, (value) => { watch(error, (value) => {
if (value) { if (value) {
@ -46,6 +58,10 @@
useHead({ useHead({
title: pageTitle, title: pageTitle,
}); });
onMounted(() => {
hydrated.value = true;
});
</script> </script>
<style scoped> <style scoped>
@ -64,14 +80,6 @@
margin-bottom: 2rem; margin-bottom: 2rem;
} }
:deep(.markdown-body p) {
text-indent: 2em;
}
:deep(.markdown-body h2) {
text-align: center;
}
:deep(.el-divider__text) { :deep(.el-divider__text) {
color: var(--el-color-info); color: var(--el-color-info);
font-size: 1em; font-size: 1em;
@ -82,25 +90,7 @@
justify-content: left; justify-content: left;
margin-top: 2rem; margin-top: 2rem;
margin-left: 2rem; margin-left: 2rem;
} gap: 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;
} }
.loading { .loading {
@ -109,4 +99,12 @@
align-items: center; align-items: center;
margin-top: 1rem; margin-top: 1rem;
} }
@media (max-width: 768px) {
.button-group {
align-items: center;
margin-left: 0;
gap: 0.5rem;
}
}
</style> </style>

View File

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

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

@ -0,0 +1,12 @@
<template>
<div>redirecting...</div>
</template>
<script setup lang="ts">
onMounted(async () => {
const platform = await getAutoMappedService();
// // ✔ 移动端能正常跳转
window.location.href = platform;
});
</script>

View File

@ -35,17 +35,9 @@
const localePath = useLocalePath(); const localePath = useLocalePath();
// //
const id = computed(() => route.params.slug as string); const id = route.params.slug as string;
const { data, pending, error } = await useProduct(id.value); const { data: product, 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 breadcrumbItems = computed(() => [ const breadcrumbItems = computed(() => [
{ label: $t('navigation.home'), to: localePath('/') }, { label: $t('navigation.home'), to: localePath('/') },
@ -61,8 +53,8 @@
// SEO // SEO
usePageSeo({ usePageSeo({
title: product.value.name || $t('page-title.products'), title: product.value?.name || $t('page-title.products'),
description: product.value.summary || '', description: product.value?.summary || '',
}); });
</script> </script>

View File

@ -1,7 +1,13 @@
<template> <template>
<div class="page-container"> <div class="page-container">
<div class="page-header"> <div class="page-header">
<h1 class="page-title">{{ $t('our-products') }}</h1> <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" /> <app-breadcrumb class="breadcrumb" :items="breadcrumbItems" />
</div> </div>
<div v-if="!pending" class="page-content"> <div v-if="!pending" class="page-content">
@ -37,7 +43,7 @@
const localePath = useLocalePath(); const localePath = useLocalePath();
const { getImageUrl } = useDirectusImage(); const { getImageUrl } = useDirectusImage();
const { data, pending, error } = useProductList(); const { data: products, pending, error } = await useProductList();
const activeNames = ref<string[]>([]); const activeNames = ref<string[]>([]);
@ -46,13 +52,6 @@
{ label: $t('navigation.products') }, { label: $t('navigation.products') },
]; ];
const productsRaw = computed(() => data.value ?? []);
const products = computed(() =>
productsRaw.value.map((item) => toProductListView(item))
);
logger.debug('products: ', products.value);
// 按类型分组 // 按类型分组
const groupedProducts = computed(() => { const groupedProducts = computed(() => {
const groups: Record<string, { data: ProductListView[]; sort: number }> = const groups: Record<string, { data: ProductListView[]; sort: number }> =
@ -109,13 +108,18 @@
.page-header { .page-header {
display: flex; display: flex;
margin-bottom: 1rem;
} }
.page-title { .page-title {
font-size: 2rem; font-size: 2rem;
font-weight: bold; font-weight: bold;
color: var(--el-color-primary); color: var(--el-color-primary);
margin-bottom: 1rem; }
.page-subtitle {
font-size: 0.8rem;
color: var(--el-text-color-secondary);
} }
.breadcrumb { .breadcrumb {

View File

@ -21,58 +21,36 @@
// i18n相关 // i18n相关
const { t } = useI18n(); const { t } = useI18n();
const { getDirectusLocale } = useLocalizations(); const { getDirectusLocale } = useLocalizations();
const directusLocale = getDirectusLocale(); const locale = getDirectusLocale();
// 路由相关 // 路由相关
const route = useRoute(); const route = useRoute();
// 搜索相关 // 搜索相关
const { search } = useMeilisearch();
const keyword = ref(''); const keyword = ref('');
if (typeof route.query.query === 'string' && route.query.query.trim()) {
keyword.value = route.query.query;
}
const { const {
data: sections, data: searchItems,
pending: loading, pending: loading,
error, error,
refresh, refresh,
} = await useAsyncData( } = useAsyncData(`meilisearch-${keyword.value}-${locale}`, async () => {
() => `search-${directusLocale}-${route.query.query ?? ''}`, try {
async () => { const data = await $fetch(`/api/search?query=${keyword.value}`, {
const q = String(route.query.query ?? '').trim(); headers: { 'x-locale': locale },
if (!q) return []; });
return await search(q, { limit: 12 }, directusLocale); return data;
} catch (error) {
logger.error('Error fetching search results: ', error);
throw error;
} }
); });
// 空Section过滤 const hasResults = computed(() => searchItems.value.length > 0);
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)
);
watch( watch(
() => route.query.query, () => route.query.query,
@ -84,6 +62,13 @@
} }
); );
watch(
() => locale,
async () => {
await refresh();
}
);
watch(error, (value) => { watch(error, (value) => {
if (value) { if (value) {
logger.error('数据获取失败: ', value); logger.error('数据获取失败: ', value);

View File

@ -26,17 +26,10 @@
const route = useRoute(); const route = useRoute();
const localePath = useLocalePath(); const localePath = useLocalePath();
// (documentId) //
const id = computed(() => route.params.slug as string); const id = route.params.slug as string;
const { data, pending, error } = await useSolution(id.value); const { data: solution, pending, error } = await useSolution(id);
const solution = computed(() => {
if (!data.value) {
return null;
}
return toSolutionView(data.value);
});
const breadcrumbItems = computed(() => [ const breadcrumbItems = computed(() => [
{ label: $t('navigation.home'), to: localePath('/') }, { label: $t('navigation.home'), to: localePath('/') },
@ -51,8 +44,8 @@
}); });
usePageSeo({ usePageSeo({
title: solution.value.title || $t('page-title.solutions'), title: solution.value?.title || $t('page-title.solutions'),
description: solution.value.summary || '', description: solution.value?.summary || '',
}); });
</script> </script>

View File

@ -1,7 +1,11 @@
<template> <template>
<div class="page-container"> <div class="page-container">
<div class="page-header"> <div class="page-header">
<h1 class="page-title">{{ $t('learn-our-solutions') }}</h1> <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" /> <app-breadcrumb class="breadcrumb" :items="breadcrumbItems" />
</div> </div>
<div v-if="!pending" class="solutions-container"> <div v-if="!pending" class="solutions-container">
@ -52,12 +56,7 @@
{ label: $t('navigation.solutions') }, { label: $t('navigation.solutions') },
]; ];
const { data, pending, error } = await useSolutionList(); const { data: solutions, pending, error } = await useSolutionList();
const solutionsRaw = computed(() => data.value ?? []);
const solutions = computed(() =>
solutionsRaw.value.map((item) => toSolutionListView(item))
);
const activeName = ref<string>('all'); const activeName = ref<string>('all');
@ -99,15 +98,20 @@
.page-header { .page-header {
display: flex; display: flex;
margin-bottom: 1rem;
} }
.page-title { .page-title {
font-size: 2rem; font-size: 2rem;
font-weight: bold; font-weight: bold;
margin-bottom: 1rem;
color: var(--el-color-primary); color: var(--el-color-primary);
} }
.page-subtitle {
font-size: 0.8rem;
color: var(--el-text-color-secondary);
}
.breadcrumb { .breadcrumb {
margin-left: auto; margin-left: auto;
} }

View File

@ -7,7 +7,15 @@
</div> </div>
<div v-if="!pending" class="page-content"> <div v-if="!pending" class="page-content">
<markdown-renderer :content="content.content || ''" /> <!-- 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> -->
</div> </div>
<div v-else class="loading"> <div v-else class="loading">
<el-skeleton :rows="5" animated /> <el-skeleton :rows="5" animated />
@ -17,14 +25,13 @@
<script setup lang="ts"> <script setup lang="ts">
const localePath = useLocalePath(); const localePath = useLocalePath();
const hydrated = ref(false);
const breadcrumbItems = [ const breadcrumbItems = [
{ label: $t('navigation.home'), to: localePath('/') }, { label: $t('navigation.home'), to: localePath('/') },
{ label: $t('navigation.support'), to: localePath('/support') }, { label: $t('navigation.support'), to: localePath('/support') },
{ label: $t('navigation.contact-info') }, { label: $t('navigation.contact-info') },
]; ];
const { data, pending, error } = await useContactInfo(); const { data: contactInfo, pending, error } = await useContactInfo();
const content = computed(() => toContactInfoView(data.value));
watch(error, (value) => { watch(error, (value) => {
if (value) { if (value) {
@ -36,6 +43,10 @@
usePageSeo({ usePageSeo({
title: pageTitle, title: pageTitle,
}); });
onMounted(() => {
hydrated.value = true;
});
</script> </script>
<style scoped> <style scoped>

View File

@ -10,12 +10,29 @@
<app-breadcrumb class="breadcrumb" :items="breadcrumbItems" /> <app-breadcrumb class="breadcrumb" :items="breadcrumbItems" />
</div> </div>
<div class="page-content"> <div class="page-content">
<product-filter <document-filter
v-model="filters" v-model="filters"
:product-type-options="productTypeOptions" :product-type-options="productTypeOptions"
:product-options="productOptions" :product-options="productOptions"
:document-type-options="documentTypeOptions"
/>
<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"
/> />
<document-list :documents="filteredDocuments" />
</div> </div>
</div> </div>
</div> </div>
@ -30,16 +47,34 @@
]; ];
const filters = reactive({ const filters = reactive({
selectedType: null as number | null, selectedDocumentType: null as string | null,
selectedProduct: null as number | null, selectedProductType: null as string | null,
selectedProduct: null as string | null,
keyword: '', keyword: '',
}); });
const { data, pending, error } = await useDocumentList(); const page = ref(1);
const documentsPerPage = 10;
const documents = computed( const { data: documents, pending, error } = await useDocumentList();
() => data?.value.map((item) => toDocumentListView(item)) ?? []
); 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 productTypeOptions = computed(() => {
const types: DocumentListProductType[] = []; const types: DocumentListProductType[] = [];
@ -56,13 +91,13 @@
}); });
const productOptions = computed(() => { const productOptions = computed(() => {
if (!filters.selectedType) return []; if (!filters.selectedProductType) return [];
const products: DocumentListProduct[] = []; const products: DocumentListProduct[] = [];
documents.value.forEach((doc: DocumentListView) => { documents.value.forEach((doc: DocumentListView) => {
doc.products?.forEach((product: DocumentListProduct) => { doc.products?.forEach((product: DocumentListProduct) => {
if ( if (
product.type.id === filters.selectedType && product.type.id === filters.selectedProductType &&
!products.some((item) => item.id === product.id) !products.some((item) => item.id === product.id)
) { ) {
products.push(product); products.push(product);
@ -73,30 +108,42 @@
return products; return products;
}); });
const filteredDocuments = computed(() => const filteredDocuments = computed(() => {
documents.value.filter((doc: DocumentListView) => { const fuzzyMatchedDocuments = fuzzyMatch(documents.value, {
keyword: filters.keyword,
keys: ['title'],
threshold: 0.6,
});
return fuzzyMatchedDocuments.filter((doc: DocumentListView) => {
const matchProduct = filters.selectedProduct const matchProduct = filters.selectedProduct
? doc.products?.some( ? doc.products?.some(
(product: DocumentListProduct) => (product: DocumentListProduct) =>
product.id === filters.selectedProduct product.id === filters.selectedProduct
) )
: filters.selectedType : filters.selectedProductType
? doc.products?.some( ? doc.products?.some(
(product: DocumentListProduct) => (product: DocumentListProduct) =>
product.type?.id === filters.selectedType product.type?.id === filters.selectedProductType
) )
: true; : true;
const matchKeyword = filters.keyword const matchDocumentType = filters.selectedDocumentType
? doc.title && doc.title.includes(filters.keyword) ? doc.type.id === filters.selectedDocumentType
: true; : true;
return matchProduct && matchKeyword; return matchProduct && matchDocumentType;
}) });
); });
const paginatedDocuments = computed(() => {
return filteredDocuments.value.slice(
(page.value - 1) * documentsPerPage,
page.value * documentsPerPage
);
});
watch( watch(
() => filters.selectedType, () => filters.selectedProductType,
() => { () => {
filters.selectedProduct = null; filters.selectedProduct = null;
} }
@ -136,12 +183,6 @@
margin-left: auto; margin-left: auto;
} }
.document-category {
padding: 0rem 2rem;
gap: 4px;
margin-bottom: 0.5rem;
}
.page-content { .page-content {
padding: 1rem 2rem 2rem; padding: 1rem 2rem 2rem;
} }
@ -156,4 +197,35 @@
height: 40px; height: 40px;
font-size: 0.9rem; font-size: 0.9rem;
} }
.pagination-container {
margin-top: 2rem;
}
: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> </style>

View File

@ -11,13 +11,23 @@
</div> </div>
<div class="page-content"> <div class="page-content">
<product-filter <question-filter
v-model="filters" v-model="filters"
:product-type-options="productTypeOptions" :product-type-options="productTypeOptions"
:product-options="productOptions" :product-options="productOptions"
:question-type-options="questionTypeOptions"
/> />
<question-list :questions="filteredQuestions" /> <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"
/>
</div> </div>
</div> </div>
</div> </div>
@ -25,24 +35,46 @@
<script setup lang="ts"> <script setup lang="ts">
const localePath = useLocalePath(); const localePath = useLocalePath();
const route = useRoute();
const filters = reactive({ const filters = reactive({
selectedType: null as number | null, selectedQuestionType: null as string | null,
selectedProduct: null as number | null, selectedProduct: null as string | null,
selectedProductType: null as string | null,
keyword: '', keyword: '',
}); });
const page = ref(1);
const questionsPerPage = 10;
const focusQuestionId = ref<string | null>(
route.query.focus as string | null
);
const breadcrumbItems = [ const breadcrumbItems = [
{ label: $t('navigation.home'), to: localePath('/') }, { label: $t('navigation.home'), to: localePath('/') },
{ label: $t('navigation.support'), to: localePath('/support') }, { label: $t('navigation.support'), to: localePath('/support') },
{ label: $t('navigation.faq') }, { label: $t('navigation.faq') },
]; ];
const { data, pending, error } = await useQuestionList(); const { data: questions, pending, error } = await useQuestionList();
const questions = computed( const questionTypeOptions = computed(() => {
() => data.value.map((item) => toQuestionListView(item)) ?? null 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 productTypeOptions = computed(() => {
const types: QuestionListProductType[] = []; const types: QuestionListProductType[] = [];
@ -58,12 +90,12 @@
}); });
const productOptions = computed(() => { const productOptions = computed(() => {
if (!filters.selectedType) return []; if (!filters.selectedProductType) return [];
const products: QuestionListProduct[] = []; const products: QuestionListProduct[] = [];
questions.value.forEach((q: QuestionListView) => { questions.value.forEach((q: QuestionListView) => {
q.products.forEach((product: QuestionListProduct) => { q.products.forEach((product: QuestionListProduct) => {
if ( if (
product.type.id === filters.selectedType && product.type.id === filters.selectedProductType &&
!products.some((p) => p.id === product.id) !products.some((p) => p.id === product.id)
) { ) {
products.push(product); products.push(product);
@ -74,30 +106,62 @@
}); });
const filteredQuestions = computed(() => { const filteredQuestions = computed(() => {
return questions.value.filter((question: QuestionListView) => { const fuzzyMatchedQuestions = fuzzyMatch(questions.value, {
keyword: filters.keyword,
keys: ['title'],
threshold: 0.6,
});
return fuzzyMatchedQuestions.filter((question: QuestionListView) => {
const matchProduct = filters.selectedProduct const matchProduct = filters.selectedProduct
? question.products?.some( ? question.products?.some(
(product: QuestionListProduct) => (product: QuestionListProduct) =>
product.id === filters.selectedProduct product.id === filters.selectedProduct
) )
: filters.selectedType : filters.selectedProductType
? question.products?.some( ? question.products?.some(
(product: QuestionListProduct) => (product: QuestionListProduct) =>
product.type.id === filters.selectedType product.type.id === filters.selectedProductType
) )
: true; : true;
const matchKeyword = filters.keyword const matchQuestionType = filters.selectedQuestionType
? (question.title && question.title.includes(filters.keyword)) || ? question.type.id === filters.selectedQuestionType
(question.content && question.content.includes(filters.keyword))
: true; : true;
return matchProduct && matchKeyword; return matchProduct && matchQuestionType;
}); });
}); });
const paginatedQuestions = computed(() => {
const start = (page.value - 1) * questionsPerPage;
const end = page.value * questionsPerPage;
return filteredQuestions.value.slice(start, end);
});
watch( 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; filters.selectedProduct = null;
} }
@ -140,4 +204,34 @@
.page-content { .page-content {
padding: 1rem 2rem 2rem; padding: 1rem 2rem 2rem;
} }
.pagination-container {
margin-top: 2rem;
}
: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> </style>

View File

@ -1,10 +1,11 @@
import { createDirectus, rest, staticToken } from '@directus/sdk'; import { createDirectus, rest, staticToken, graphql } from '@directus/sdk';
export default defineNuxtPlugin(() => { export default defineNuxtPlugin(() => {
const config = useRuntimeConfig(); const config = useRuntimeConfig();
const directus = createDirectus<Schema>(config.public.directus.url) const directus = createDirectus<Schema>(config.public.directus.url)
.with(rest()) .with(rest())
.with(graphql())
.with(staticToken(config.public.directus.token || '')); .with(staticToken(config.public.directus.token || ''));
return { return {
provide: { directus }, provide: { directus },

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 { expect, test, describe } from 'vitest';
import { formatFileSize, getFileExtension, formatFileExtension } from './file';
/** /**
* 单元测试: formatFileSize * 单元测试: formatFileSize

108
app/utils/fuzzyFilter.ts Normal file
View File

@ -0,0 +1,108 @@
import Fuse from 'fuse.js';
interface FuzzyFilterOptions<T> {
/** 匹配关键字 */
keyword: string;
/** 搜索字段 */
keys: Array<FuzzyKeyOf<T>>;
/** 模糊程度 (0~1越低越严格) */
threshold?: number;
/** 最小匹配字符数 */
minMatchCharLength?: number;
/** 当前语言 */
locale?: string;
}
/** 限定 keys 只能选择字符串字段 */
type FuzzyKeyOf<T> = {
[K in keyof T]: T[K] extends string ? K : never;
}[keyof T];
export function fuzzyMatch<T extends object>(
source: T[],
options: FuzzyFilterOptions<T>
): T[] {
const { keyword, keys, threshold = 0.35, minMatchCharLength = 1 } = options;
// --- 文本标准化函数 ---
const normalizeText = (text: string): string => {
const normalizedText = text.normalize('NFKC').toLowerCase().trim();
return normalizedText;
};
/**
* 类型安全的对象取值函数
*/
function getPropertyByPath<T>(
obj: T,
path: string | string[]
): string | undefined {
const keys = Array.isArray(path) ? path : path.split('.');
let value: unknown = obj;
for (const key of keys) {
if (value && typeof value === 'object' && key in value) {
value = (value as Record<string, unknown>)[key];
} else {
return undefined;
}
}
return typeof value === 'string' ? value : undefined;
}
// --- fallback 模糊匹配算法 ---
const fallbackFuzzyMatch = (text: string, pattern: string): boolean => {
const normalizedText = normalizeText(text);
const normalizedPattern = normalizeText(pattern);
let i = 0;
for (const char of normalizedPattern) {
i = normalizedText.indexOf(char, i);
if (i === -1) return false;
i++;
}
return true;
};
const k = keyword.trim();
if (!k) {
return source;
}
if (import.meta.client) {
// 客户端使用Fuze.js进行模糊匹配
const fuse = new Fuse<T>(source, {
keys: keys as string[],
threshold,
minMatchCharLength,
ignoreLocation: true,
findAllMatches: true,
isCaseSensitive: false,
getFn: (obj, path) => {
const value = getPropertyByPath(obj, path);
if (typeof value === 'string') {
const normalized = value
.normalize('NFKC')
.replace(/\s+/g, '')
.toLowerCase()
.trim();
return normalized;
}
return value;
},
});
const result = fuse.search(k);
return result.map((result) => result.item);
}
return source.filter((item) =>
keys.some((key) => {
const value = item[key];
return typeof value === 'string' ? fallbackFuzzyMatch(value, k) : false;
})
);
}

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; 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

@ -10,6 +10,7 @@
"result-count": "{count} results", "result-count": "{count} results",
"no-results": "No results found for \"{query}\".", "no-results": "No results found for \"{query}\".",
"no-query": "Enter a keyword to start searching.", "no-query": "Enter a keyword to start searching.",
"section": "Section",
"untitled": "Untitled", "untitled": "Untitled",
"sections": { "sections": {
"product": "Products", "product": "Products",
@ -22,8 +23,8 @@
"company-name": "Jinshen Machinary Manufacturing Co., Ltd.", "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.", "company-description": "We specialize in manufacturing a range of paper tube and can equipment, integrating design, manufacturing, sales, and service.",
"learn-more": "Learn More", "learn-more": "Learn More",
"products-desc": "We provide high-quality product solutions to meet various business needs.", "products-desc": "We provide the latest products an instant service support to meet various business needs of our customers.",
"solutions-desc": "Providing customized technology solutions for enterprises to accelerate digital transformation.", "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.", "support-desc": "24/7 professional technical support to ensure stable operation of your business.",
"quick-links": "Quick Links", "quick-links": "Quick Links",
"utilities": "Utilities", "utilities": "Utilities",
@ -37,7 +38,8 @@
"downloads": "Downloads", "downloads": "Downloads",
"faq": "FAQ", "faq": "FAQ",
"documents": "Documents", "documents": "Documents",
"calculator": "Calculator" "calculator": "Calculator",
"address": "Company Address"
}, },
"contact-info": "Contact Us", "contact-info": "Contact Us",
"telephone": "Telephone", "telephone": "Telephone",
@ -61,7 +63,9 @@
"back-to-home": "Back to Home", "back-to-home": "Back to Home",
"no-content-available": "No detailed information available", "no-content-available": "No detailed information available",
"loading": "Loading...", "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", "learn-our-solutions": "Learn Our Solutions",
"all": "All", "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.", "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", "keyword": "Keyword",
"select-product-type": "Select product type", "select-product-type": "Select product type",
"select-product-model": "Select product model", "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": { "document-meta": {
"size": "Size", "size": "Size",

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

@ -0,0 +1,130 @@
{
"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"
}
}

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

@ -0,0 +1,130 @@
{
"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": "Связанные документы"
}
}

View File

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

View File

@ -1,4 +1,6 @@
// https://nuxt.com/docs/api/configuration/nuxt-config // https://nuxt.com/docs/api/configuration/nuxt-config
import GraphQLLoader from 'vite-plugin-graphql-loader';
export default defineNuxtConfig({ export default defineNuxtConfig({
compatibilityDate: '2025-07-15', compatibilityDate: '2025-07-15',
devtools: { enabled: true }, devtools: { enabled: true },
@ -42,6 +44,10 @@ export default defineNuxtConfig({
}, },
directus: { directus: {
url: process.env.DIRECTUS_URL || 'http://localhost:8055', 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, token: process.env.DIRECTUS_TOKEN || undefined,
}, },
}, },
@ -66,6 +72,7 @@ export default defineNuxtConfig({
'@unocss/reset/tailwind.css', '@unocss/reset/tailwind.css',
'~/assets/scss/index.scss', '~/assets/scss/index.scss',
'~/assets/css/fonts.css', '~/assets/css/fonts.css',
'~/assets/css/typography.css',
'@mdi/font/css/materialdesignicons.min.css', '@mdi/font/css/materialdesignicons.min.css',
], ],
@ -90,6 +97,7 @@ export default defineNuxtConfig({
}, },
}, },
}, },
plugins: [GraphQLLoader()],
}, },
devServer: { devServer: {
@ -114,6 +122,8 @@ export default defineNuxtConfig({
locales: [ locales: [
{ code: 'en', language: 'en-US', name: 'English', file: 'en.json' }, { code: 'en', language: 'en-US', name: 'English', file: 'en.json' },
{ code: 'zh', language: 'zh-CN', name: '简体中文', file: 'zh.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', defaultLocale: 'zh',
strategy: 'prefix_except_default', strategy: 'prefix_except_default',

View File

@ -22,14 +22,20 @@
"@types/markdown-it": "^14.1.2", "@types/markdown-it": "^14.1.2",
"@unocss/nuxt": "^66.4.2", "@unocss/nuxt": "^66.4.2",
"@vueuse/nuxt": "^13.6.0", "@vueuse/nuxt": "^13.6.0",
"dom-serializer": "^2.0.0",
"domhandler": "^5.0.3",
"dompurify": "^3.2.6", "dompurify": "^3.2.6",
"element-plus": "^2.10.7", "element-plus": "^2.10.7",
"fuse.js": "^7.1.0",
"graphql": "^16.12.0",
"htmlparser2": "^10.0.0",
"markdown-it": "^14.1.0", "markdown-it": "^14.1.0",
"meilisearch": "^0.53.0", "meilisearch": "^0.53.0",
"nuxt": "^4.0.3", "nuxt": "^4.0.3",
"nuxt-directus": "5.7.0", "nuxt-directus": "5.7.0",
"sass": "^1.90.0", "sass": "^1.90.0",
"sharp": "^0.34.3", "sharp": "^0.34.3",
"vite-plugin-graphql-loader": "^4.0.4",
"vue": "^3.5.18", "vue": "^3.5.18",
"vue-router": "^4.5.1" "vue-router": "^4.5.1"
}, },

60
pnpm-lock.yaml generated
View File

@ -41,12 +41,27 @@ importers:
'@vueuse/nuxt': '@vueuse/nuxt':
specifier: ^13.6.0 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)) 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: dompurify:
specifier: ^3.2.6 specifier: ^3.2.6
version: 3.2.6 version: 3.2.6
element-plus: element-plus:
specifier: ^2.10.7 specifier: ^2.10.7
version: 2.11.2(vue@3.5.21(typescript@5.9.2)) version: 2.11.2(vue@3.5.21(typescript@5.9.2))
fuse.js:
specifier: ^7.1.0
version: 7.1.0
graphql:
specifier: ^16.12.0
version: 16.12.0
htmlparser2:
specifier: ^10.0.0
version: 10.0.0
markdown-it: markdown-it:
specifier: ^14.1.0 specifier: ^14.1.0
version: 14.1.0 version: 14.1.0
@ -65,6 +80,9 @@ importers:
sharp: sharp:
specifier: ^0.34.3 specifier: ^0.34.3
version: 0.34.3 version: 0.34.3
vite-plugin-graphql-loader:
specifier: ^4.0.4
version: 4.0.4
vue: vue:
specifier: ^3.5.18 specifier: ^3.5.18
version: 3.5.21(typescript@5.9.2) version: 3.5.21(typescript@5.9.2)
@ -3081,6 +3099,10 @@ packages:
resolution: {integrity: sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==} resolution: {integrity: sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==}
engines: {node: '>=0.12'} engines: {node: '>=0.12'}
entities@6.0.1:
resolution: {integrity: sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==}
engines: {node: '>=0.12'}
env-paths@2.2.1: env-paths@2.2.1:
resolution: {integrity: sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==} resolution: {integrity: sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==}
engines: {node: '>=6'} engines: {node: '>=6'}
@ -3495,6 +3517,16 @@ packages:
graphemer@1.4.0: graphemer@1.4.0:
resolution: {integrity: sha512-EtKwoO6kxCL9WO5xipiHTZlSzBm7WLT627TqC/uVRd0HKmq8NXyebnNYxDoBi7wt8eTWrUrKXCOVaFq9x1kgag==} resolution: {integrity: sha512-EtKwoO6kxCL9WO5xipiHTZlSzBm7WLT627TqC/uVRd0HKmq8NXyebnNYxDoBi7wt8eTWrUrKXCOVaFq9x1kgag==}
graphql-tag@2.12.6:
resolution: {integrity: sha512-FdSNcu2QQcWnM2VNvSCCDCVS5PpPqpzgFT8+GXzqJuoDd0CBncxCY278u4mhRO7tMgo2JjgJA5aZ+nWSQ/Z+xg==}
engines: {node: '>=10'}
peerDependencies:
graphql: ^0.9.0 || ^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^14.0.0 || ^15.0.0 || ^16.0.0
graphql@16.12.0:
resolution: {integrity: sha512-DKKrynuQRne0PNpEbzuEdHlYOMksHSUI8Zc9Unei5gTsMNA2/vMpoMz/yKba50pejK56qj98qM0SjYxAKi13gQ==}
engines: {node: ^12.22.0 || ^14.16.0 || ^16.0.0 || >=17.0.0}
gzip-size@6.0.0: gzip-size@6.0.0:
resolution: {integrity: sha512-ax7ZYomf6jqPTQ4+XCpUGyXKHk5WweS+e05MBO4/y3WJ5RkmPXNKvX+bx1behVILVwr6JSQvZAku021CHPXG3Q==} resolution: {integrity: sha512-ax7ZYomf6jqPTQ4+XCpUGyXKHk5WweS+e05MBO4/y3WJ5RkmPXNKvX+bx1behVILVwr6JSQvZAku021CHPXG3Q==}
engines: {node: '>=10'} engines: {node: '>=10'}
@ -3525,6 +3557,9 @@ packages:
hookable@5.5.3: hookable@5.5.3:
resolution: {integrity: sha512-Yc+BQe8SvoXH1643Qez1zqLRmbA5rCL+sSmk6TVos0LWVfNIB7PGncdlId77WzLGSIB5KaWgTaNTs2lNVEI6VQ==} resolution: {integrity: sha512-Yc+BQe8SvoXH1643Qez1zqLRmbA5rCL+sSmk6TVos0LWVfNIB7PGncdlId77WzLGSIB5KaWgTaNTs2lNVEI6VQ==}
htmlparser2@10.0.0:
resolution: {integrity: sha512-TwAZM+zE5Tq3lrEHvOlvwgj1XLWQCtaaibSN11Q+gGBAS7Y1uZSWwXXRe4iF6OXnaq1riyQAPFOBtYc77Mxq0g==}
http-errors@2.0.0: http-errors@2.0.0:
resolution: {integrity: sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==} resolution: {integrity: sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==}
engines: {node: '>= 0.8'} engines: {node: '>= 0.8'}
@ -5385,6 +5420,9 @@ packages:
vue-tsc: vue-tsc:
optional: true optional: true
vite-plugin-graphql-loader@4.0.4:
resolution: {integrity: sha512-lYnpQ2luV2fcuXmOJADljuktfMbDW00Y+6QS+Ek8Jz1Vdzlj/51LSGJwZqyjJ24a5YQ+o29Hr6el/5+nlZetvg==}
vite-plugin-inspect@11.3.3: vite-plugin-inspect@11.3.3:
resolution: {integrity: sha512-u2eV5La99oHoYPHE6UvbwgEqKKOQGz86wMg40CCosP6q8BkB6e5xPneZfYagK4ojPJSj5anHCrnvC20DpwVdRA==} resolution: {integrity: sha512-u2eV5La99oHoYPHE6UvbwgEqKKOQGz86wMg40CCosP6q8BkB6e5xPneZfYagK4ojPJSj5anHCrnvC20DpwVdRA==}
engines: {node: '>=14'} engines: {node: '>=14'}
@ -8991,6 +9029,8 @@ snapshots:
entities@4.5.0: {} entities@4.5.0: {}
entities@6.0.1: {}
env-paths@2.2.1: {} env-paths@2.2.1: {}
environment@1.1.0: {} environment@1.1.0: {}
@ -9476,6 +9516,13 @@ snapshots:
graphemer@1.4.0: {} graphemer@1.4.0: {}
graphql-tag@2.12.6(graphql@16.12.0):
dependencies:
graphql: 16.12.0
tslib: 2.8.1
graphql@16.12.0: {}
gzip-size@6.0.0: gzip-size@6.0.0:
dependencies: dependencies:
duplexer: 0.1.2 duplexer: 0.1.2
@ -9512,6 +9559,13 @@ snapshots:
hookable@5.5.3: {} 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: http-errors@2.0.0:
dependencies: dependencies:
depd: 2.0.0 depd: 2.0.0
@ -11722,6 +11776,12 @@ snapshots:
optionator: 0.9.4 optionator: 0.9.4
typescript: 5.9.2 typescript: 5.9.2
vite-plugin-graphql-loader@4.0.4:
dependencies:
graphql: 16.12.0
graphql-tag: 2.12.6(graphql@16.12.0)
magic-string: 0.30.19
vite-plugin-inspect@11.3.3(@nuxt/kit@3.19.2(magicast@0.3.5))(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)): vite-plugin-inspect@11.3.3(@nuxt/kit@3.19.2(magicast@0.3.5))(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)):
dependencies: dependencies:
ansis: 4.1.0 ansis: 4.1.0

36
server/api/assets/[id].ts Normal file
View File

@ -0,0 +1,36 @@
export default defineEventHandler(async (event) => {
const id = getRouterParam(event, 'id');
if (!id)
throw createError({
statusCode: 400,
statusMessage: 'ID parameter is required',
});
const url = new URL(`${useRuntimeConfig().public.directus.url}/assets/${id}`);
const query = getQuery(event);
Object.entries(query).forEach(([key, value]) => {
url.searchParams.set(key, String(value));
});
const token = useRuntimeConfig().public.directus.token || '';
const res = await fetch(url.toString(), {
headers: {
Authorization: `Bearer ${token}`,
},
});
if (!res.ok) {
throw createError({
statusCode: res.status,
statusMessage: `Failed to fetch asset: ${res.statusText}`,
});
}
const contentType =
res.headers.get('Content-Type') || 'application/octet-stream';
setHeader(event, 'Content-Type', contentType);
setHeader(event, 'Cache-Control', 'public, max-age=86400, immutable');
return res.body;
});

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

@ -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

@ -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

@ -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

@ -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

@ -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

@ -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

@ -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

@ -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);
});

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: 12 }, 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

@ -0,0 +1,9 @@
query GetCompanyProfile($locale: String!) {
company_profile {
id
translations(filter: { languages_code: { code: { _eq: $locale } } }) {
id
content
}
}
}

View File

@ -0,0 +1,9 @@
query GetContactInfo($locale: String!) {
contact_info {
id
translations(filter: { languages_code: { code: { _eq: $locale } } }) {
id
content
}
}
}

View File

@ -0,0 +1,38 @@
query GetDocumentList($locale: String!) {
product_documents(filter: { status: { _eq: "published" } }) {
id
file {
id
filesize
filename_download
}
translations(filter: { languages_code: { code: { _eq: $locale } } }) {
id
title
}
type {
id
translations(filter: { languages_code: { code: { _eq: $locale } } }) {
id
name
}
}
products {
id
products_id {
id
translations(filter: { languages_code: { code: { _eq: $locale } } }) {
id
name
}
product_type {
id
translations(filter: { languages_code: { code: { _eq: $locale } } }) {
id
name
}
}
}
}
}
}

View File

@ -0,0 +1,33 @@
query GetHomepage($locale: String!) {
homepage {
id
carousel {
id
directus_files_id {
id
}
}
recommend_products {
id
translations(filter: { languages_code: { code: { _eq: $locale } } }) {
id
name
summary
}
cover {
id
}
}
recommend_solutions {
id
translations(filter: { languages_code: { code: { _eq: $locale } } }) {
id
title
summary
}
cover {
id
}
}
}
}

View File

@ -0,0 +1,73 @@
query GetProduct($id: ID!, $locale: String!) {
products_by_id(id: $id) {
id
status
translations(filter: { languages_code: { code: { _eq: $locale } } }) {
id
name
summary
description
}
images {
id
product_images_id {
id
image {
id
}
translations(filter: { languages_code: { code: { _eq: $locale } } }) {
id
caption
}
}
}
specs {
id
translations(filter: { languages_code: { code: { _eq: $locale } } }) {
id
name
}
specs {
id
translations(filter: { languages_code: { code: { _eq: $locale } } }) {
id
key
value
}
}
}
faqs {
id
questions_id(filter: { status: { _eq: "published" } }) {
id
translations(filter: { languages_code: { code: { _eq: $locale } } }) {
id
title
content
}
}
}
documents {
id
product_documents_id(filter: { status: { _eq: "published" } }) {
id
type {
id
translations(filter: { languages_code: { code: { _eq: $locale } } }) {
id
name
}
}
file {
id
filesize
filename_download
}
translations(filter: { languages_code: { code: { _eq: $locale } } }) {
id
title
}
}
}
}
}

View File

@ -0,0 +1,22 @@
query GetProductList($locale: String!) {
products(filter: { status: { _eq: "in-production" } }) {
id
status
translations(filter: { languages_code: { code: { _eq: $locale } } }) {
id
name
summary
}
cover {
id
}
product_type {
id
translations(filter: { languages_code: { code: { _eq: $locale } } }) {
id
name
}
sort
}
}
}

View File

@ -0,0 +1,34 @@
query GetQuestionList($locale: String!) {
questions(filter: { status: { _eq: "published" } }) {
id
type {
id
translations(filter: { languages_code: { code: { _eq: $locale } } }) {
id
name
}
}
translations(filter: { languages_code: { code: { _eq: $locale } } }) {
id
title
content
}
products {
id
products_id {
id
product_type {
id
translations(filter: { languages_code: { code: { _eq: $locale } } }) {
id
name
}
}
translations(filter: { languages_code: { code: { _eq: $locale } } }) {
id
name
}
}
}
}
}

View File

@ -0,0 +1,12 @@
query GetSolution($id: ID!, $locale: String!) {
solutions_by_id(id: $id) {
id
translations(filter: { languages_code: { code: { _eq: $locale } } }) {
id
title
summary
content
}
create_at
}
}

View File

@ -0,0 +1,21 @@
query GetSolutionList($locale: String!) {
solutions(filter: { status: { _eq: "published" } }) {
id
cover {
id
}
type {
id
translations(filter: { languages_code: { code: { _eq: $locale } } }) {
id
name
}
sort
}
translations(filter: { languages_code: { code: { _eq: $locale } } }) {
id
title
summary
}
}
}

View File

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

View File

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

View File

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

View File

@ -8,10 +8,10 @@
* const view = toContactInfoView(rawContactInfo); * const view = toContactInfoView(rawContactInfo);
*/ */
export function toContactInfoView(raw: ContactInfo): ContactInfoView { export function toContactInfoView(raw: ContactInfo): ContactInfoView {
const trans = raw.translations?.[0] ?? { content: '' }; const trans = raw.translations?.[0];
return { return {
id: raw.id, id: raw.id.toString(),
content: trans.content, 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 { describe, test, expect } from 'vitest';
import { toHomepageView } from './homepageMapper';
/** /**
* 单元测试: toHomepageView * 单元测试: toHomepageView
@ -8,42 +9,58 @@ describe('toHomepageView', () => {
const rawData: Homepage = { const rawData: Homepage = {
id: 1, id: 1,
carousel: [ carousel: [
{ id: 1, directus_files_id: 'file-uuid-1' }, {
{ id: 2, directus_files_id: 'file-uuid-2' }, id: 1,
directus_files_id: {
id: 'file-uuid-1',
},
},
{
id: 2,
directus_files_id: {
id: 'file-uuid-2',
},
},
], ],
recommend_products: [ recommend_products: [
{ {
id: 1, id: 1,
translations: [{ id: 1, name: 'Product 1', summary: 'Summary 1' }], translations: [{ id: 1, name: 'Product 1', summary: 'Summary 1' }],
cover: 'cover-file-uuid-1', cover: {
id: 'cover-file-uuid-1',
},
}, },
{ {
id: 2, id: 2,
translations: [{ id: 2, name: 'Product 2', summary: 'Summary 2' }], translations: [{ id: 2, name: 'Product 2', summary: 'Summary 2' }],
cover: { id: 'cover-file-uuid-2' }, cover: {
id: 'cover-file-uuid-2',
},
}, },
], ],
recommend_solutions: [ recommend_solutions: [
{ {
id: 1, id: 1,
translations: [{ id: 1, title: 'Solution 1', summary: 'Summary 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({ expect(toHomepageView(rawData)).toEqual({
id: 1, id: '1',
carousel: ['file-uuid-1', 'file-uuid-2'], carousel: ['file-uuid-1', 'file-uuid-2'],
recommendProducts: [ recommendProducts: [
{ {
id: 1, id: '1',
name: 'Product 1', name: 'Product 1',
summary: 'Summary 1', summary: 'Summary 1',
cover: 'cover-file-uuid-1', cover: 'cover-file-uuid-1',
}, },
{ {
id: 2, id: '2',
name: 'Product 2', name: 'Product 2',
summary: 'Summary 2', summary: 'Summary 2',
cover: 'cover-file-uuid-2', cover: 'cover-file-uuid-2',
@ -51,7 +68,7 @@ describe('toHomepageView', () => {
], ],
recommendSolutions: [ recommendSolutions: [
{ {
id: 1, id: '1',
title: 'Solution 1', title: 'Solution 1',
summary: 'Summary 1', summary: 'Summary 1',
cover: 'cover-file-uuid-1', cover: 'cover-file-uuid-1',
@ -69,10 +86,10 @@ describe('toHomepageView', () => {
}; };
expect(toHomepageView(rawData)).toEqual({ expect(toHomepageView(rawData)).toEqual({
id: 1, id: '1',
carousel: [], carousel: [],
recommendProducts: [{ id: 1, name: '', summary: '', cover: null }], recommendProducts: [{ id: '1', name: '', summary: '', cover: '' }],
recommendSolutions: [{ id: 1, title: '', summary: '', cover: null }], recommendSolutions: [{ id: '1', title: '', summary: '', cover: '' }],
}); });
}); });
}); });

View File

@ -1,3 +1,5 @@
import { isObject } from '../utils/object';
/** /**
* Directus Homepage HomepageView * Directus Homepage HomepageView
* *
@ -11,19 +13,20 @@ export function toHomepageView(raw: Homepage): HomepageView {
const carousel = (raw.carousel ?? []) const carousel = (raw.carousel ?? [])
.filter(isObject<HomepageFile>) .filter(isObject<HomepageFile>)
.map((item) => item.directus_files_id) .map((item) => item.directus_files_id)
.filter((item) => typeof item === 'string'); .filter(isObject<DirectusFile>)
.map((file) => file.id);
const products = (raw.recommend_products ?? []) const products = (raw.recommend_products ?? [])
.filter(isObject<Product>) .filter(isObject<Product>)
.map((item) => { .map((item) => {
const cover = isObject<DirectusFile>(item.cover) const trans = item.translations?.[0];
? item.cover.id
: item.cover; const cover = isObject<DirectusFile>(item.cover) ? item.cover.id : '';
const trans = item.translations?.[0] ?? { name: '', summary: '' };
return { return {
id: item.id, id: item.id.toString(),
name: trans.name, name: trans?.name ?? '',
summary: trans.summary, summary: trans?.summary ?? '',
cover: cover, cover: cover,
} satisfies HomepageProductView; } satisfies HomepageProductView;
}); });
@ -31,21 +34,19 @@ export function toHomepageView(raw: Homepage): HomepageView {
const solutions = (raw.recommend_solutions ?? []) const solutions = (raw.recommend_solutions ?? [])
.filter(isObject<Solution>) .filter(isObject<Solution>)
.map((item) => { .map((item) => {
const cover = isObject<DirectusFile>(item.cover) const trans = item.translations?.[0];
? item.cover.id const cover = isObject<DirectusFile>(item.cover) ? item.cover.id : '';
: item.cover;
const trans = item.translations?.[0] ?? { title: '', summary: '' };
return { return {
id: item.id, id: item.id.toString(),
title: trans.title, title: trans?.title ?? '',
summary: trans.summary, summary: trans?.summary ?? '',
cover: cover, cover: cover,
} satisfies HomepageSolutionView; } satisfies HomepageSolutionView;
}); });
return { return {
id: raw.id, id: raw.id.toString(),
carousel: carousel ?? [], carousel: carousel ?? [],
recommendProducts: products ?? [], recommendProducts: products ?? [],
recommendSolutions: solutions ?? [], 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;
}

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