Compare commits

...

566 Commits

Author SHA1 Message Date
19bcf64844 Merge branch 'dev/1.0' of http://git.aigc-quickapp.com/Uniapp/lucky_shop into yuanlaide2 2026-07-16 16:20:53 +08:00
a27ae6cba0 Merge remote-tracking branch 'origin/dev/1.0' into yuanlaide2
# Conflicts:
#	.local.config.js
2026-07-16 16:17:26 +08:00
660ab27377 chore :按钮 = 全局所有有商品的二级分类(去重,一直显示),选中状态切换一级分类时保持
商品 = 切换一级分类时,用选中按钮的名称在当前一级分类下找同名 category,重新加载商品
2026-07-16 16:11:01 +08:00
d78a23602e chore:删除临时测试网址 2026-07-16 15:31:07 +08:00
7a6495fa33 chore:按钮 = 全局所有有商品的二级分类(去重,一直显示),选中状态在切换一级分类时保持
商品 = 切换一级分类时,用选中按钮的名称在当前一级分类下找同名 category,重新加载该 category 的商品
2026-07-16 14:31:14 +08:00
61e7a0d859 style: 调整所有页面的回到顶部按钮位置
统一修改多个页面的mescroll回到顶部按钮的right和bottom偏移值,优化移动端页面的按钮显示位置,避免遮挡页面内容
2026-07-16 14:23:11 +08:00
4116bfcbb0 feat(article detail): add back-to-top button and scroll mixin
add the to-top component and integrate scroll mixin to support scroll-to-top functionality
2026-07-16 14:10:52 +08:00
29e96a9357 docs(tabbar test): 补全测试文档与场景注释
重构并完善了TabBar高亮测试文件的注释文档:
1.  新增完整的测试说明文档,包含测试原则、核心逻辑、术语表、调试方法和场景索引
2.  为每个测试场景补充了对应的设计决策和业务规则注释
3.  新增边界测试踩坑记录和单元测试说明
4.  新增测试模板和调试指南,方便后续新增测试用例
2026-07-16 13:53:08 +08:00
88024cbd11 test(tabbar): add comprehensive test cases for tabbar highlight
新增多语言切换、登出状态、性能、极端URL、动态tab配置相关的高亮测试场景,覆盖业务边界与性能校验
2026-07-16 11:52:13 +08:00
55a9ed5946 refactor: 重构底部导航高亮逻辑,新增跨平台兼容与工具脚本
1. 抽离底部导航归属逻辑为纯函数resolveEntryTab,优化分包页面高亮规则,对齐iOS HIG规范
2. 新增页面Tab通配符映射,简化PAGE_TAB_MAP维护
3. 修复鸿蒙平台webview返回按钮适配问题
4. 新增pages.json校验与导航标题自动注入脚本
5. 优化启动页动画性能,提升合成渲染效率
6. 修复diy-picture组件v-for缺少key的警告
7. 清理鸿蒙平台多余的分包构建配置
8. 更新统计数据与store注释说明
2026-07-16 11:47:29 +08:00
165edc38ee fix(mp-weixin): 修复微信小程序url内&破坏query分隔的问题
1. 重写safeEncodeMP函数,修复微信小程序不二次编码导致的参数丢失bug:
   - 先解码已有的%xx编码避免双重编码
   - 主动执行一次encodeURIComponent,将&/?=空格等字符转为%xx格式
2. 新增跨平台通用跳转测试和工具单元测试,覆盖H5/微信/鸿蒙/快应用4个平台
3. 重构跳转逻辑,统一各平台的URL编码和跳转行为
4. 新增3个针对性测试用例,验证&符号防护、反引号编码、双重编码防御
2026-07-15 18:25:50 +08:00
b20ab5bf5d feat(H5/quickapp): add quick app pull refresh global mixin and utils
1. add quickapp-pull-refresh.js mixin to handle pull down refresh in quick app H5 environment
2. add notifyNativeHost and requestQuickAppReload util methods for cross-environment communication
3. conditionally register the mixin only for H5 platform
2026-07-15 17:55:27 +08:00
05d6ea1e96 feat(page): add pull-to-refresh and back-to-top component
1. enable pull-down refresh for the target page in pages.json
2. add scroll mixin and back-to-top component for form and formdata pages, show back-to-top button when scrolling down
2026-07-15 17:35:42 +08:00
4c58db0710 feat: add back-to-top component to multiple pages and import scroll mixin
add to-top component to card.vue, card_buy.vue, diy.vue and member index.vue, import scroll mixin for diy and member index pages to support scroll to top functionality
2026-07-15 17:13:45 +08:00
d7bc1165f7 refactor(quickapp): 优化页面稳定性与刷新逻辑
1.  为所有核心API调用增加try-catch兜底,避免异常导致页面崩溃
2.  添加刷新冷却机制防止重复触发重载
3.  移除onShow自动刷新逻辑,改为轻量日志处理
4.  完善CONFIG读取失败降级逻辑与日志输出
2026-07-15 17:07:29 +08:00
a32cedad9e feat(mp-quickapp): 配置统一域名与uniacid,优化缓存与页面刷新
1.  新增集中配置项管理BASE_URL和UNIACID
2.  动态生成带时间戳的加载URL与UA避免缓存
3.  后台切回前台时自动刷新web页面
4.  调整打包版本号与构建产物配置
2026-07-15 16:52:51 +08:00
7f2e5d3934 chore: template 99正常运行 2026-07-15 16:50:26 +08:00
616fac0312 refactor(common,webview): remove redundant console logs and simplify api call
清理了两处页面和工具类中的调试日志,同时简化了uni.setNavigationBarTitle的调用代码,移除了不必要的success/fail回调,只保留核心调用逻辑
2026-07-15 16:24:35 +08:00
2c1703acc5 fix(index page): add base url to version info modal
extend the version info popup to display the backend service base address
2026-07-15 15:58:40 +08:00
82f1659649 refactor(components-diy): simplify useScroll logic and add comment
将useScroll方法的判断逻辑简化为单行表达式,并补充注释说明该方法的作用
2026-07-15 15:39:08 +08:00
1c88bcf99b style(common/css): 删除冗余的H5端全局样式代码
移除了原先针对H5端的根容器撑满和自定义TabBar固定的冗余注释与样式代码,这些样式逻辑目前可能已被框架内置处理或不再需要,清理样式文件减少冗余代码。
2026-07-15 15:17:23 +08:00
793b988376 fix(splash-screen): 修复启动屏拦截首页触摸事件的问题
针对H5端和普通启动场景,分别处理触摸事件拦截问题:
1. 给启动屏组件添加pointer-events:none,让首页在渐隐期也能正常交互
2. 修改uni.showLoading的mask参数为false,避免原生蒙层遮挡触摸
2026-07-15 15:12:59 +08:00
313c283d9b fix: 适配华为快应用WebView场景并修复tabbar定位问题
1. 新增华为快应用WebView环境检测工具函数
2. 文章组件在快应用WebView中强制关闭滚动模式
3. 修复全局tabbar在H5/快应用中的定位漂移问题,加固fixed定位样式
4. 补全页面配置中的导航栏标题字段
2026-07-15 15:00:42 +08:00
b10bf472e3 feat(webview): add webview title auto update and debug logs
1. add @titleUpdate event listener for web-view component
2. decode uri component for title and enableSetTitle params
3. refactor updateNavbarTitle to accept dynamic new title
4. add debug console logs for tracking title update flow
5. add success/fail callbacks for navigation bar title setting
2026-07-15 11:55:52 +08:00
1814fffc12 refactor(util-navigate): simplify platform detection logic
1. remove redundant try-catch wrapper for compile-time macros
2. add quickapp runtime detection for H5 in quickapp webview
3. add optional chaining for uni.getSystemInfoSync call
4. add comment for default return case
2026-07-15 11:18:55 +08:00
13da4f1c9f fix(util): 修正系统导航栏列表工具函数的导入别名
调整了systemTabBarList工具函数的导入别名写法,同时将adaptSubpackageUrl加入到导出列表中保持API一致性
2026-07-15 11:08:35 +08:00
c8fada4b9d refactor(util): 拆分跳转工具集到独立文件
将原util.js中的跳转相关工具函数拆分为util-navigate.js和util-tabbar.js两个独立模块,重构原有代码以:
1.  避免循环依赖问题
2.  提升代码可维护性和复用性
3.  保留原有API兼容性,无需修改业务调用代码
4.  实现纯函数化设计,方便测试和tree-shaking
2026-07-15 11:00:49 +08:00
6c3f90bf96 feat(webview): add dynamic navigation bar title setting function
新增webview页面根据传入参数动态设置导航栏标题的功能,支持通过enable_set_title参数控制是否强制替换默认标题,通过title参数传递自定义标题内容。
2026-07-15 10:38:31 +08:00
229c6aa969 feat(util): add URL sanitization utility and improve redirect handling
1. add cleanParamUrls recursive URL sanitization util
2. add URL cleanup to diyRedirectTo as final defense
3. refactor redirectTo to avoid duplicate cleanup
4. add comprehensive unit tests for all new functionality
2026-07-15 09:24:10 +08:00
00bf4bcfd6 feat(mp-share): add disabled share page list and hide share menu for specific pages
新增了禁用分享的页面配置列表,针对指定页面主动隐藏转发按钮,同时优化了分享逻辑的兜底和性能。
具体包括:
1. 增加_DISABLED_PAGES集合管理禁分享页面路由
2. 添加页面禁用检查和隐藏分享菜单工具方法
3. 在created和onLoad阶段自动隐藏对应页面的转发按钮
4. 优化onShow和分享钩子的禁用逻辑,避免无效请求和调用
2026-07-15 09:05:50 +08:00
cb5878ad29 test: add unit test for mp-share-default module
complete all test cases for the disabled pages share logic, including blacklist check, route judgment, share api behavior and network call control
2026-07-15 09:02:54 +08:00
d213c5a488 build(scripts): add test gate and npm test scripts
1. 新增测试门禁脚本test-gate.js,统一管理tests目录下的测试用例执行
2. 在package.json中添加test、test:util、prebuild、prestart脚本,将测试环节前置到构建和启动流程
3. 重构normalizeUrl函数,新增更严格的URL规范化逻辑并补充完整注释
4. 优化代码格式,修正多处对象字面量的空格排版
5. 新增util.js的单元测试文件,覆盖核心工具函数的测试场景
2026-07-15 08:57:52 +08:00
3ac8162d9c fix(util): 修复子包URL连续斜杠过多的问题
新增逻辑将路径中3个及以上连续斜杠收敛为2个,避免破坏scheme部分,修正不规范的URL路径格式
2026-07-14 17:58:02 +08:00
873e1efe73 fix(util&scss): 修复快应用内嵌H5滚动问题并优化URL参数处理
1. 为body添加滚动样式适配快应用webview视口限制
2. 调整URL参数合并逻辑,确保page_params始终置于URL末尾
2026-07-14 17:22:57 +08:00
c1289cd6b1 fix(util): 优化跳转参数的空值处理逻辑
将原有的可选链空合并赋值改为条件式展开参数,避免传入无效的空值参数
2026-07-14 17:08:12 +08:00
b7cfa61a34 fix(util): 调整参数合并顺序并修复透传参数问题
1. 调整appendQueryParams的参数合并顺序,将page_params放在最后
2. 修复redirectTo调用时的参数透传问题,正确保留title和enable_set_title参数
3. 添加redirectTo跳转时的调试日志
2026-07-14 17:04:18 +08:00
52f952a6df style(common/css): 修复快应用内嵌H5根容器不撑满问题
针对快应用内嵌H5场景下webview viewport高度不可控导致根容器无法铺满整屏的问题,添加H5端显式撑满容器的样式兜底,同时保留微信小程序/鸿蒙元服务的原有编译逻辑
2026-07-14 16:30:31 +08:00
fa082f59c1 fix: 更新快应用项目配置与接口地址
1.  修改userAgent的uniacid值从1116为2482
2.  将导航栏调用方法从hjiTitleBar改为setTitleBar
3.  更新默认加载URL为新的aigc-quickapp地址
4.  修正编译产物中的路径与版本号信息
2026-07-14 16:27:31 +08:00
d8785d9d41 fix(diy.vue): 修复底部导航开启时页面最小高度异常问题
当开启底部导航时,原本没有设置默认最小高度,现在补充完整100vh的默认值,避免页面内容过少时布局异常
2026-07-14 16:09:18 +08:00
0312d00642 chore: add 2821 config for silicone oil paper project
add new project config entry 2821 and comment out its usage for now
2026-07-14 10:37:00 +08:00
39d4264389 chore:增加新功能只在template == 99里生效 2026-07-14 09:59:44 +08:00
ef407d6008 docs(TODO.md): 标记鸿蒙元服务相关的6个BUG为已修复
将之前记录的鸿蒙元服务环境下的组件和页面问题全部标记为已完成修复
2026-07-14 09:38:49 +08:00
aac44de359 style(article detail page): adjust page height to min-h-screen
将文章详情页的固定高度改为视口最小高度,适配不同屏幕内容高度场景
2026-07-14 09:38:35 +08:00
2708ac55d1 fix(util): 修复小程序跳转时未拼接参数的问题
修复uni.navigateToMiniProgram调用时未将page_params参数拼接进跳转path的问题,正确处理了参数过滤和url拼接逻辑
2026-07-13 18:22:22 +08:00
3d822ed641 fix(util): 补全wap_url公共参数并透传page_params
将page_params合并到公共参数中,一并追加到跳转链接里
2026-07-13 18:20:51 +08:00
e88dc2b205 docs(mp-share-default): 修正注释里的预处理宏描述
将原来的具体代码注释调整为更通用的"MP-WEIXIN 预处理宏"表述,让注释更清晰易懂
2026-07-13 16:30:10 +08:00
83fc02a279 refactor(diy-goods-list): 统一商品图片mode适配鸿蒙元服务
修复鸿蒙元服务环境下商品图片显示裁剪/不全的问题,根据模板和平台动态适配图片mode模式
2026-07-13 16:22:24 +08:00
edc077eef7 docs: 更新TODO清单,补充鸿蒙元服务等环境的bug
新增多个鸿蒙元服务环境的组件显示异常bug,以及微信小程序的控制台报错bug,更新已修复的bug项格式
2026-07-13 16:08:53 +08:00
30cda71749 refactor(http,lang): 重构请求逻辑并新增多语言错误提示
1.  新增网络相关错误的多语言翻译配置
2.  重写http请求层,添加自动重试机制与错误分类提示
3.  优化鸿蒙平台下的组件渲染兼容性与数据更新逻辑
4.  调整部分页面的模板结构与请求配置
2026-07-13 15:45:15 +08:00
cb9234bdac refactor(diy-video-list): 优化弹窗视频适配逻辑
1. 重构视频比例计算逻辑,改为通过实际宽高计算适配
2. 新增多端适配:H5、微信小程序、鸿蒙元服务
3. 添加视频加载错误捕获与日志输出
4. 调整视频容器样式,统一背景与溢出处理
5. 移除旧的比例状态变量,改用宽高状态存储
2026-07-13 14:41:29 +08:00
10bc06f212 refactor(components/diy-video): 重构视频比例计算逻辑
替换原有的固定比例方案,改为通过视频实际宽高动态计算适配比例,移除冗余的harmonyVideoHeight计算方法,统一多端样式处理逻辑,优化鸿蒙端视频高度计算方式
2026-07-13 14:24:09 +08:00
c739d691a2 fix(diy-video): 适配鸿蒙元服务端视频组件展示
1. 新增鸿蒙平台专属video组件渲染分支
2. 新增窗口宽度初始化逻辑用于计算鸿蒙视频高度
3. 针对不同平台调整视频容器样式计算逻辑
4. 补充视频加载元数据和错误回调
5. 修复微信小程序视频比例适配逻辑
2026-07-13 14:11:14 +08:00
0ca64b7dcf chore: 2026-07-13 13:52:30 +08:00
88921e61d2 fix(splash-screen): 修复H5环境下启动屏关闭后页面空白问题
问题根源分析:
1. diy-group 的 mounted() 在组件挂载时就触发了,但此时 diyData 还没有数据
2.
otifyMounted() 在组件 mount 时立即关闭了 H5 的 uni.showLoading(),但页面内容还没就绪
3. 导致启动屏关闭后,首页内容还是空白的

修复方案:
1. 在 diy-group.vue 中,将 loaded 事件的触发时机改为 diyData watch 中,确保数据加载完成后再通知
2. 在 splash-state.js 中,
otifyMounted() 不再立即关闭 H5 原生 loading,等待页面就绪后由 _doHide() 统一关闭
3. 在 index.js 中,onDiyGroupLoaded() 延迟 500ms 再通知页面就绪,确保内容渲染完成
2026-07-13 10:54:17 +08:00
6b8b4acc96 fix(splash-state): 修复页面就绪后无法关闭启动屏的问题
问题根源: _flushPendingHide() 中过早清除了 _pendingHide,导致页面就绪后 notifyPageReady() 检测不到 pending hide 请求,启动屏无法关闭。

修复方案: 当页面未就绪时,保留 _pendingHide 直到页面真正就绪后再清除。
2026-07-13 10:43:47 +08:00
edea8c32de fix(splash-screen): 启动屏等待首页内容就绪后再消失
问题描述: 首次启动时,启动屏已关闭但首页内容还是空白的,用户体验差。

解决方案:
1. 在 splash-state.js 中新增页面就绪等待机制 (_pageReady 标志、notifyPageReady 方法)
2. 修改软隐藏逻辑,必须同时满足组件已 mount 和页面已就绪才关闭启动屏
3. 在首页 onDiyGroupLoaded 回调中通知页面就绪

兜底保护:
- 组件 1s 未 mount → 强制关闭
- 页面 2s 未就绪 → 强制关闭
- 总超时 8s → 强制关闭
2026-07-13 10:36:04 +08:00
3f09dca054 refactor(splash-screen): 移除废弃的启动屏配置系统
简化启动屏组件代码,删除不再使用的splashConfig全局配置、相关工具方法和冗余的布局逻辑,统一进度条展示样式。
2026-07-13 10:22:45 +08:00
aa15518980 feat(splash-screen): add configurable splash screen display options
add splashConfig in config-external.js to control progress/label/percent display,
add runtime config api in splash-state.js,
refactor splash-screen.vue to support inline layout and prop override
2026-07-13 09:59:18 +08:00
8597504b57 chore: 添加.trae到gitignore忽略列表
将.trae目录加入gitignore,避免将本地临时目录提交到版本库
2026-07-13 09:15:26 +08:00
a913961be5 feat: 实现隐私弹窗全链路功能,支持本地配置与远程patch融合
- 新增隐私管理器核心逻辑,支持URL路由规则匹配、远程patch签名校验与融合
- 实现启动期资源等待机制,确保弹窗在i18n、主题配置就绪后触发
- 新增启动进度条组件,展示启动阶段进度与状态
- 重构隐私弹窗组件生命周期,修复事件丢失问题并支持规则动态重评估
- 适配多端平台隐私检查逻辑,支持微信小程序、鸿蒙元服务与H5
- 支持uniacid租户隔离的持久化规则存储
2026-07-11 18:28:36 +08:00
a2066285cd feat(mp-weixin): 新增全局兜底分享mixin与路径复制能力
为微信小程序端添加全局分享兜底支持,为所有未显式声明分享钩子的页面提供默认转发和朋友圈分享能力,同时新增小程序路径复制工具方法。
2026-07-11 15:19:26 +08:00
397589c4e6 fix(uni-config): 调整页面配置和权限声明
1. 调整recharge/list页面的disableScroll配置位置,全平台生效
2. 修正剪贴板权限名称和描述,移除冗余的剪贴板权限声明
2026-07-11 14:43:27 +08:00
c3cb420bf5 style(pages.json): 格式化页面配置缩进与注释格式
统一调整会员充值相关页面配置的缩进层级,修正冗余的scrollEnabled注释逻辑,保持跨端配置格式一致
2026-07-11 14:10:32 +08:00
bec47d1860 fix: 调整小程序权限配置与页面滚动配置
1. 更新剪贴板权限名称为userClipboardWrite并新增clipboard到隐私信息列表
2. 兼容微信小程序移除scrollEnabled,改用disableScroll保持滚动行为一致
2026-07-11 13:51:46 +08:00
117cbccbd7 chore: 更新配置项与补充项目待办清单
- 修改站点uniacid为2482
- 补充微信小程序相关BUG和优化项到TODO文档
2026-07-11 10:33:49 +08:00
7a76824fcf fix(diy-article, diy-image-nav): 修复H5端拖拽后误触发跳转的问题
1.  重构两个组件的H5端鼠标事件绑定逻辑,改用document级别capture监听解决uni-app自定义元素事件拦截问题
2.  添加拖拽阈值检测,避免点击误触发滚动
3.  新增click拦截逻辑,拖拽结束后自动屏蔽后续一次click事件防止误跳转
4.  优化滚动容器获取方式,兼容uni-app编译后的嵌套DOM结构
2026-07-11 10:03:23 +08:00
75bc8876b5 feat(components-diy): 为两个组件添加H5端鼠标拖拽滚动支持
1.  给diy-image-nav组件新增singleSlide模式下H5端鼠标拖拽和滚轮横向滚动功能,修复uni-app scroll-view在H5端不支持鼠标拖拽的问题,同时添加对应样式优化
2.  给diy-article组件的跑马灯列表新增H5端鼠标拖拽和滚轮滚动支持,复用原有触摸事件逻辑适配鼠标操作,优化拖拽交互体验
3.  统一采用mounted绑定H5专属事件的方式,避免小程序/鸿蒙端出现未知事件编译警告
2026-07-11 08:26:14 +08:00
203c47e437 fix(diy-listmenu): add click event to menu view button
为列表菜单的查看按钮添加点击跳转事件,修复无法跳转对应页面的问题
2026-07-10 18:20:32 +08:00
6eaebc7d75 chore(diy-image-nav): add component identity data attribute
给自定义图片导航组件添加data-component-name标识属性,用于识别组件身份
2026-07-10 18:18:21 +08:00
575145eae9 refactor(pages.json&scripts): 优化自定义组件占位符注入逻辑
1.  为商品详情页添加所有diy-*组件的占位符配置
2.  重构占位符注入脚本,实现组件使用的递归检测
3.  移除原有的简单字符串匹配,改用导入链追踪准确判断组件使用情况
2026-07-10 17:45:38 +08:00
81e85c804a chore(mp-harmony): 更新gitignore和构建配置
1. 修正gitignore中的鸿蒙元服务构建产物路径
2. 新增components_diy、pages相关模块的构建配置
2026-07-10 17:34:50 +08:00
6178f699ed feat(scripts): add harmony component placeholder injection logic
新增鸿蒙组件级componentPlaceholder自动注入脚本,解决diy组件编译为asyncComponent导致的运行时报错,自动遍历处理非页面组件的json配置文件,同时添加异常捕获避免构建中断
2026-07-10 17:28:52 +08:00
2276291a4b build(mp-harmony): 添加目标SDK版本配置
补充鸿蒙项目的targetSdkVersion配置为5.0.0(12)
2026-07-10 16:52:42 +08:00
acbb89997b chore(config): update local dev config and add multiple project configs
1. 修改local-1的domain为局域网地址并注释原本地地址
2. 新增5g-213、5g-4、5g-97、5g-50、5g-237、2485多个项目配置
3. 调整默认激活的环境配置为2482,并注释其他测试配置
2026-07-10 16:44:13 +08:00
e04f5aabc0 build(mp-harmony): 移除多余的targetSdkVersion配置
删除build-profile.json5中冗余的targetSdkVersion字段,清理构建配置文件
2026-07-10 16:43:02 +08:00
013eef46fb refactor(common,components): 优化底部导航栏显隐逻辑
1. 新增isCurrentPageTabBarRoot工具方法封装页面判断逻辑
2. 调整弹窗打开时的导航栏隐藏时机,仅在非TabBar根页面执行
3. 移除弹窗open回调中的导航栏显示逻辑,改为在关闭弹窗时显式处理
4. 补充注释说明回调不可靠的问题和根页面不隐藏导航的原因
2026-07-10 15:46:48 +08:00
d9c6e41ebe fix(privacy): 新增表单页跳过隐私弹窗的匹配路径
补充了/pages_tool/form/form路径到免隐私弹窗的H5匹配列表中,避免外链/扫码访问表单详情时弹窗挡住页面
2026-07-10 14:16:49 +08:00
e3e63899d8 feat(privacy): add markSkipped method and H5 skip logic for privacy popup
add markSkipped method to synchronously skip privacy popup, and call it in App.vue created hook for H5 environment when current URL matches skip condition
2026-07-10 14:11:51 +08:00
9d2b76687c feat(privacy): add url-based skip rule for H5 privacy popup
add ability to skip privacy popup when visiting specific H5 URLs directly,
update PrivacyManager.show to accept skip option,
add skip logic for specific form page to avoid blocking UI
2026-07-10 14:01:41 +08:00
679c53c501 refactor(util): 统一 URL 参数序列化与解析逻辑
1. 新增_toParamValueString处理复杂参数序列化
2. 新增parsePageParams作为page_params统一解析工具
3. 重构多处参数处理逻辑,避免重复代码和对象转字符串异常
4. 统一处理对象/数组参数的JSON序列化,避免出现[object Object]
2026-07-10 13:56:37 +08:00
a90245b201 fix: 适配多平台url编码规则,修复双重编码问题
针对H5和小程序/App平台分别处理url参数编码:
1. H5平台需要手动encodeURIComponent避免参数解析错误
2. 小程序/App平台由uni内部自动编码,避免双重编码导致参数解码异常
同时重构了工具类中的编码逻辑,统一多场景下的平台适配规则
2026-07-10 11:29:16 +08:00
897a8157e7 fix(util): 修复url参数编码逻辑
移除了冗余的try-catch编码逻辑,直接返回原始字符串

直接返回原始字符串,简化了url参数编码的处理流程,避免了不必要的编解码操作
2026-07-10 10:47:48 +08:00
e8db412595 refactor(index): 调整版本水印相关逻辑与样式
1. 调整版本连击触发条件为3次以上而非≥3次
2. 优化版本水印的DOM结构和触发绑定方式
3. 简化背景内联样式并调整水印内边距
4. 修改版本水印的颜色和阴影样式
2026-07-10 10:12:04 +08:00
08e4d866f5 feat: add version watermark and optimize title tap logic
1. 为diy-group组件添加loaded事件通知渲染完成
2. 调整构建时间为北京时间并格式化展示
3. 新增版本水印组件,在diy渲染完成后显示
4. 将标题连击触发版本信息的次数从5次改为3次
5. 移除旧的隐形触发区域,将触发逻辑绑定到水印
2026-07-10 09:47:17 +08:00
d4794a7be4 fix(lang): 修复路径含连字符时无法匹配bundle的问题
新增尝试原始段名的匹配逻辑,同时支持camelCase、snake_case和原始段名三种命名方式,覆盖更多bundle命名场景
2026-07-09 16:26:02 +08:00
d0a3976cda fix(goods search): 修复搜索框点击区域问题
将搜索触发事件从整个搜索盒移动到搜索图标上,避免点击输入框时误触发搜索
2026-07-09 15:51:32 +08:00
94be20d499 refactor: 优化项目配置与代码冗余清理
1. 新增components-diy占位组件与注入脚本,按需注入分包占位配置
2. 开启postcss编译优化
3. 移除多处重复的图标字体全局样式导入
2026-07-09 15:13:06 +08:00
a7dd0b302e refactor(mp-harmony): 简化店铺卡片逻辑,统一使用应用名作为卡片名称
1. 移除ShopInfo接口和默认数据中的shopName字段,不再返回店铺名称
2. 重构WidgetCard页面布局,移除营业状态显示和底部快捷按钮
3. 重构EntryFormAbility,仅保留2x2店铺卡片,使用应用资源名作为卡片名称
4. 注释暂时保留的店铺名称解析逻辑,后续需要时可重新启用
2026-07-08 15:50:46 +08:00
fd4fd61399 feat: 新增多尺寸卡片组件与配套服务
新增2*4商品横滑卡片、4*4活动促销卡片,重构基础店铺卡片UI;添加商品、活动数据拉取缓存服务,修复TextDecoder兼容问题,优化API拼接逻辑,支持多卡片尺寸适配
2026-07-08 11:48:31 +08:00
7808c63a79 feat(harmony): 实现鸿蒙卡片的店铺信息展示功能
1. 新增harmony.patch.js脚本,将根目录site.js同步到鸿蒙项目rawfile目录,供FormAbility读取配置
2. 新增ApiConfig.ets,实现从rawfile读取站点配置并兜底降级
3. 新增ShopInfoService.ets,封装店铺信息缓存、API请求和数据解析逻辑
4. 重构EntryFormAbility.ets,添加卡片异步更新和数据渲染逻辑
5. 重构WidgetCard.ets,实现带店铺logo、名称和营业状态的卡片UI
2026-07-07 18:16:18 +08:00
82fd3839a9 feat: 新增remote-only主题模式,优化首屏包体积
1. 新增theme-override.js实现主题远端拉取逻辑
2. 新增empty-style-stub.js作为主题包占位符,减少主包~75KB
3. 在vue.config.js中添加构建期主题stub替换逻辑
4. 重构config-external.js的主题配置,新增remote-only模式支持
5. 重构store的applyThemeWithRemote方法,适配远端主题拉取
6. 在bootstrap中新增主题初始化和异步拉取逻辑
2026-07-07 14:56:13 +08:00
b60ea984e5 fix: 修复分类商品项布局问题并添加窗口resize监听
1. 调整diy-category-item的price-wrap和name-wrap样式,修复布局偏移
2. 移除冗余的主题变量定义,修正flex布局参数为正确的1
3. 添加窗口尺寸变化监听,实现主题色动态重算
4. 更新语言审计报告的代码调用统计数值
2026-07-07 11:15:07 +08:00
3713cd2cf6 refactor(DIY分类页): 优化商品卡样式与H5主题适配
1.  修复H5端rpx单位CSS变量无法解析问题,添加rpx转px转换工具函数并更新缓存key
2.  给diy-category-item组件添加scoped样式,重构商品卡样式为CSS变量可配置形式
3.  补充多套预设的分类页商品卡样式token到style_color配置中
2026-07-07 10:56:59 +08:00
83a5f358e2 style(diy-category-item): 优化咨询按钮样式token支持度
扩展咨询按钮的可配置css属性,添加内边距、圆角、字重等独立token,便于后台全局调整按钮样式
2026-07-07 09:16:31 +08:00
bd1a9a67e0 style: 重构分类组件样式,支持主题化配置字号和按钮样式
1. 为分类树和分类项的文字样式替换为CSS变量,支持远端主题配置
2. 重命名AI咨询按钮的类名和样式变量,统一命名规范
3. 为每个主题预设添加分类页专属的样式token,包含字号、按钮背景和文字颜色
2026-07-07 09:12:06 +08:00
224b409455 style: 调整模板缩进对齐并修复语法错误
统一修复了两个页面文件中的vue模板缩进格式,修正了多余的闭合标签问题,让代码排版更整洁易读
2026-07-06 17:51:47 +08:00
1c5cc62368 fix(util): 修复跳转链接参数合并与重复拼接问题
1. 重构resolveLinkUrl方法,合并wap_url自带query与page_params,且page_params优先级更高
2. 提取wap_url中的path部分,避免后续跳转重复附加query参数
3. 修复diyRedirectTo中重复解码wap_url和错误传递冗余参数的问题
2026-07-06 17:40:03 +08:00
aa7d967422 fix: 修复鸿蒙元服务TabBar跳转失效问题
1.  修复多处页面onTabItemTap事件,使用uni.reLaunch兜底鸿蒙下switchTab静默失败的问题
2.  全局混入onTabItemTap兜底未手动处理的页面
3.  优化路由跳转逻辑,针对鸿蒙环境增加switchTab失败兜底和超时强制跳转
4.  优化可选链调用和空值判断,提升代码健壮性
2026-07-06 16:48:38 +08:00
9815f09c1f style(diy-category): 给价格文字添加加粗和主题色样式
调整了money类的样式,统一价格文本的字体粗细和颜色变量使用
2026-07-06 15:35:01 +08:00
fc61a02211 style(index page): 优化版本触发按钮的样式与位置
调整按钮位置避开tab栏并避免和to-top组件冲突,增大点击面积提升触摸命中率,提升层级确保不被遮挡,恢复指针事件支持
2026-07-06 13:46:20 +08:00
aebe8b557f fix(diy-notice): 优化跳转链接的判断逻辑
将原判断链接长度的方式改为检查实际存在的跳转字段,更准确识别有效跳转链接
2026-07-06 11:58:30 +08:00
dd90d60a14 fix(diy-notice): 修复并优化公告组件交互与显示逻辑
1. 为横向滚动公告项添加点击跳转事件
2. 为上下滚动的swiper-item补充点击事件
3. 增加item.link存在性校验避免空指针
4. 点击无链接公告时优先显示content内容
2026-07-06 11:56:20 +08:00
960f4ebaaa feat(vr page): 优化VR页面导航体验,添加返回主页按钮并修复返回逻辑
1. 移除旧的自定义返回图标,改用cover-view兼容web-view层级问题
2. 新增主页导航按钮,支持一键返回首页
3. 完善返回逻辑,处理页面栈仅当前页的异常返回场景
4. 调整导航按钮样式,添加半透明背景和圆形布局
2026-07-06 11:55:18 +08:00
9dabcc2135 fix(privacy): 兼容鸿蒙元服务场景补全隐私弹窗逻辑
新增鸿蒙兜底逻辑,当PrivacyManager.show()未执行且用户未同意隐私权限时,触发补偿弹窗,避免用户无法看到隐私授权弹窗
2026-07-06 10:42:41 +08:00
337a9618ef style(diy-category): 调整搜索框和切换按钮的代码排版
在相关代码块前后添加空行优化代码可读性,不影响原有功能逻辑
2026-07-06 10:33:41 +08:00
f48b8f0e41 fix(member page): 调整取消和退出按钮的显示判断逻辑
将原有的严格等于1的判断改为允许值为1或undefined,适配更多配置场景
2026-07-04 18:23:25 +08:00
bb18dedc35 fix(contact page): add HarmonyOS mini-program support for contact section
extend the H5 conditional compile to also cover MP-HARMONY platform
2026-07-04 18:11:03 +08:00
55c4d507db feat(diy-category): 新增鸿蒙小程序端搜索框适配
扩展H5平台条件编译到H5和MP-HARMONY,让鸿蒙小程序也显示搜索框
2026-07-04 18:03:38 +08:00
014f111cd1 style(login.vue): remove redundant harmony platform conditional comments
clean up the mp-harmony specific code blocks that are no longer needed
2026-07-04 18:00:18 +08:00
181717a7ab chore(vue.config.js): 优化构建配置,新增鸿蒙元服务构建清理逻辑
1. 统一修复代码缩进格式,对齐代码风格
2. 新增构建平台控制台输出日志
3. 新增鸿蒙元服务构建前清理输出目录逻辑
4. 完善环境变量缺失的错误提示
5. 优化注释内容,补充说明用途
2026-07-04 17:28:25 +08:00
112c9a2aa5 fix(scripts): 修复路径不存在提示和打开目录延迟问题
1. 为路径不存在的情况添加专属警告日志
2. 给打开文件目录操作增加2秒延迟,适配部分系统文件操作节奏
2026-07-04 15:08:04 +08:00
6617a0b36c fix(harmony): 修鸿蒙元服务 JSVM 兼容性
基于 .logs/harmony-debug.log 排查,修复 3 类 runtime 错误:

1. isWeChatMiniProgram / cashier autoPay / ai-chat 复制文本
   - 鸿蒙 JSVM 没有 navigator 全局, navigator.userAgent 直接 ReferenceError
   - 加 typeof navigator === 'undefined' 守卫,Harmony 上返回 false,
     业务落到 isWeiXin()(已被 #ifdef H5 框住,Harmony 上也 false)→ 普通登录

2. diy-category getHeightArea
   - onShow 在 mounted 前触发,query 还是 undefined
   - query 重新尝试创建;createSelectorQuery 不存在则直接 return
   - 防止首次进入崩溃

3. goods-detail-view 模板 indexOf
   - goodsSkuDetail.support_trade_type 字段偶尔缺失
   - 改 (support_trade_type || []).indexOf(...) 兜底
2026-07-04 11:26:47 +08:00
c9c062edcb chore: 清理并整理项目配置与工作流文件
- 更新.gitignore,移除.hbuilderx、.claude和openspec相关配置
- 新增.hbuilderx/launch.json用于uni-app调试配置
- 新增完整的OpenSpec工作流命令与技能文件,实现标准化变更管理流程
2026-07-04 10:42:39 +08:00
f37baad045 feat(i18n): add full i18n audit toolchain and pre-commit hook
- 新增 GitHub Actions 工作流实现 PR 时自动审计国际化内容
- 添加 pre-commit 钩子,提交前自动检查相关文件并拦截问题提交
- 编写完整的 i18n 审计脚本、文档与示例报告
- 实现多维度国际化校验:键匹配、占位符、data()误用、硬编码标题等
2026-07-04 09:57:43 +08:00
ea504d8434 refactor(lang): 优化远程页面树的命名匹配逻辑
修复多语言路径同时支持camelCase和snake_case的匹配问题,为每个层级同时维护两种命名格式的镜像键,增强路径兼容性
2026-07-04 09:32:56 +08:00
eb46748ae0 style: 优化日志输出,补充目标目录信息,移除多余调试日志
- 为目录清空相关日志添加目标目录路径
- 移除冗余的plugins.length调试日志
2026-07-04 09:30:57 +08:00
2d7d7f731c fix(remote lang tree): 修复命名空间被基本类型值覆盖的bug
修复remote-only模式下语言包归一化的历史bug:当页面leaf顶层存在与命名空间同名的字符串键时,会覆盖整个namespace导致子key失效。通过对齐normalizePageLangPack的两层合并逻辑来修复:
1. 先将页面语言包按路径段转为命名空间结构再合并
2. 额外平铺leaf的基本类型键到根节点以兼容短key调用
2026-07-04 09:25:01 +08:00
783c10fc62 refactor: 统一项目内国际化key的命名空间格式
本次提交对全项目的国际化调用进行了规范化重构:
1. 为中文/英文语言包新增了avatar和gender的别名映射,兼容旧有headImg/sex写法
2. 修正了lang.js中的注释路径错误
3. 将所有页面和组件内的$lang调用从短路径改为带业务模块前缀的完整命名空间路径,例如将$lang('title')改为$lang('article.list.title')
4. 优化了i18n-lazy.js的注释说明,补充了正确的key命名格式示例
5. 统一了分销、订单、会员等模块的国际化key层级,确保所有语言调用路径一致
2026-07-04 09:24:35 +08:00
92e8823566 fix: 修复多页面语言包key路径错误问题
统一修正所有页面中调用语言包时的路径命名,将短横线/下划线格式调整为正确的嵌套路径格式,确保语言文本可以正常加载
2026-07-03 17:02:43 +08:00
a27e3518da refactor(i18n): 扁平化所有国际化语言文件的翻译结构
移除多层嵌套的翻译对象,将所有翻译项直接挂载到顶层lang对象上,统一代码结构
2026-07-03 16:36:28 +08:00
e4c9b7fd59 fix: 统一处理表单提交数据的序列化逻辑
1.  修复多处表单提交时重复判断序列化的逻辑,统一处理当formData已经是字符串时不再重复序列化
2.  简化nameStyle样式计算的代码写法,移除不必要的objToStyle调用
2026-07-03 15:52:54 +08:00
94f3631421 refactor(diy-form): 简化表单提交数据处理逻辑
移除了多余的submitData对象转换步骤,直接使用getFormData的返回值作为form_data提交内容,同时删除了过时的注释说明
2026-07-03 15:06:33 +08:00
80d390886a fix(yuyue-date): 修复国际化语言key的命名不一致问题
将所有组件内的语言key从components.yuyueDate改为components.yuyue-date,统一命名格式,确保多语言配置可以正确加载对应文案。
2026-07-03 14:06:00 +08:00
b93badedd4 refactor(i18n): 扁平化国际化语言配置结构
移除多层嵌套的语言对象层级,将翻译项直接挂载到顶层lang对象下,简化语言文件结构,提升维护性
2026-07-03 11:50:21 +08:00
d1e6cc3122 refactor(components&cart): 调整语言包引用路径
统一修正空状态组件和购物车页面的语言包调用路径,将零散的语言项归类到goods.cart命名空间下,移除默认兜底文案
2026-07-03 11:26:26 +08:00
2a2161c9d9 refactor: 整理多页面语言包调用路径,统一翻译键层级
1. 调整品牌专区、商品评价、搜索、优惠券等页面的语言翻译引用,将零散翻译项归类到对应模块下
2. 优化auth.js中的语言包路径引用,修正模块命名空间
3. 清理zh-cn/en-us品牌语言包的冗余嵌套结构
2026-07-03 11:23:05 +08:00
6470912498 fix(article page): adjust language resource path for article pages
统一文章列表和详情页的多语言key路径,将原有通用语言项改为文章模块专属的语言配置
2026-07-03 11:10:38 +08:00
f628d7a0ef refactor(ai-chat): 统一调整语言文件引用路径
将所有硬编码的语言调用路径统一改为ai-chat.index下的命名空间,便于语言包管理和维护
2026-07-03 11:07:34 +08:00
b8387de6c6 fix(agreement): fix translation path for empty state texts
调整了协议页面空状态的多语言引用路径,移除了嵌套的agreement对象层级,让调用路径匹配实际的多语言文件结构
2026-07-03 11:01:46 +08:00
2705038c36 refactor(contact page): 统一使用带命名空间的语言包键值
将页面内所有语言引用都改为contact.contact下的完整命名空间键名,统一语言包调用方式
2026-07-03 10:48:53 +08:00
f05eebad43 fix: 修复多组件内语言包文件名路径不一致问题
将所有组件内引用的语言包路径从驼峰式改为短横线命名格式,保持代码中引用与实际语言包文件命名统一
2026-07-03 10:45:34 +08:00
1e0a06850a refactor(i18n): 统一登录页国际化文案,移除重复的login键值
将全局common.js里重复的login: '登录/注册'移除,调整到对应语言的登录页配置中,统一多语言文案展示
2026-07-03 09:55:35 +08:00
a88ecb9529 style(hover-nav): remove redundant box-shadow and comment
移除了hover-nav组件中多余的盒阴影样式和注释代码,优化样式代码整洁度
2026-07-02 18:24:48 +08:00
34f8ae2322 fix(hover-nav): 修复主题色失效和按钮尺寸问题
1.  将按钮尺寸从80rpx调整为72rpx,修正布局计算和样式注释
2.  修复Teleport后主题色无法正确同步的问题:
    - 移除watch的immediate选项,改为在mounted后手动触发主题色注入
    - 新增_applyThemeColor方法,支持安全地更新内联样式并清理旧值
    - 监听themeColor变化,确保主题切换时样式实时更新
2026-07-02 18:21:16 +08:00
cf6b683ffc refactor(i18n): 重构国际化拉取失败的提示逻辑
将i18n失败提示从lang:fallback事件监听迁移到boot返回值判断中,移除冗余的事件监听代码,修复事件监听时机和去重的问题,统一提示逻辑和防刷机制
2026-07-02 17:07:48 +08:00
0cdb956065 fix(http): 为请求失败提示添加错误信息参数
将原始的请求失败和域名不在白名单的提示中,新增传入err参数到多语言翻译中,展示更详细的错误信息
2026-07-02 16:56:28 +08:00
d3e8b62581 docs(i18n): update request failed error prompt to include error info
add {err} placeholder to both en-us and zh-cn language packs for request failed error message, also fix indentation consistency in zh-cn common.js
2026-07-02 16:56:13 +08:00
e1ce2ae268 feat(i18n): add fallback toast and cached bundle fallback logic
1. add global i18n fallback toast on lang:fallback event, only show once per process
2. add getCachedBundleAny to retrieve expired cache for boot fallback
3. add cache fallback logic when remote i18n bundle load fails
2026-07-02 16:33:22 +08:00
c86e688e47 refactor(privacy&lang): optimize privacy check and language bundle loading
1. add cache for privacy check result to reduce repeated calls
2. refactor lang bundle boot process with integrity checks
3. add timeout recovery for late fetch responses
4. improve error handling and fallback logic
5. add comments for better maintainability
2026-07-02 16:03:04 +08:00
2014d27834 chore(config): adjust boot and request timeout values
2026-07-02: 延长启动超时和请求超时时间,适配慢启动和远端冷启动场景,配合迟到数据补救机制确保获取到最终数据
2026-07-02 15:21:47 +08:00
15a61fdc39 style(hover-nav): 优化导航按钮视觉效果与注释
1.  调整border-radius注释位置,补充为clip-path兜底说明
2.  简化旧版aspect-ratio兼容注释
3.  为通用背景添加同色边框消除抗锯齿毛刺
4.  为文字和图标添加凹陷雕刻式text-shadow增强立体感
2026-07-02 15:21:31 +08:00
c430c8971c fix(hover-nav): 修复H5端语言切换时导航跟随页面位移的问题
1.  将H5端的hover-nav组件通过Teleport方式挂载到document.body,避开页面transform的影响
2.  同步store中的主题色变量到组件根元素样式,修复样式继承失效问题
3.  在组件销毁前将DOM元素移回原父节点避免内存泄漏
4.  简化当前语言显示逻辑,统一展示当前选中语言的短码
2026-07-02 14:02:52 +08:00
de52406be8 refactor(common): 统一浮动按钮与侧边导航的尺寸变量与布局
1.  新增全局CSS变量管理浮动按钮和侧边导航的尺寸参数,实现多组件样式同步
2.  重构to-top.vue和hover-nav.vue,改用CSS变量驱动布局,修复多平台适配问题
3.  新增多语言切换弹窗与智能切换逻辑,优化多语言展示与配置能力
4.  修复原容器高度计算的硬编码适配问题,改用rpx单位实现全平台自适应
2026-07-02 11:45:33 +08:00
e749209128 feat(lang): add i18n config for hover-nav component
新增中英文国际化配置,用于hover-nav组件的语言选择弹窗相关文案
2026-07-02 09:42:43 +08:00
fbf2dfdcee docs: 删除过时的CLAUDE.md文档
该文件是给AI助手的项目守则,当前仓库已不再需要该约束文档,移除该文件以清理仓库冗余内容
2026-07-01 18:00:28 +08:00
563ab9274f build: add remote-only mode lang package stub and replacement logic
add empty-lang-stub.js to stub lang package files in remote-only mode,
add webpack plugin logic to replace lang files with stub to reduce bundle size
2026-07-01 16:50:01 +08:00
5cfee417be refactor(splash-screen): 重构启动屏UI与动画逻辑
重写启动屏的模板结构与样式,替换原有简单logo加载动画为带光晕、轨道粒子的全新动效,优化过渡动画时长与曲线,简化冗余的生命周期注释代码
2026-07-01 15:43:41 +08:00
5ae4bbcbd3 feat: 新增统一启动屏组件,优化跨平台加载体验
1. 新增splash-screen全局启动屏组件,适配非APP平台的加载过渡
2. 新增splash-state状态管理模块,统一处理启动屏的显示隐藏、软隐藏时序、兜底超时逻辑
3. 重构App.vue和main.js的加载逻辑,替换原有uni.showLoading方案
4. 在首页和空页面挂载启动屏组件,适配不同页面场景
5. 兼容H5平台降级处理,解决main.js挂载前无法渲染组件的问题
2026-07-01 15:36:55 +08:00
c0220492a2 refactor(privacy-popup): 抽取通用延迟i18n混入并重构隐私弹窗
1. 新建通用的i18n延迟初始化混入,解决小程序/鸿蒙环境下i18n空串缓存问题
2. 将隐私弹窗原有的prepareI18n逻辑迁移到混入中,统一实现i18nPrepareFn
3. 简化弹窗组件内的i18n处理代码,优化可维护性
2026-07-01 14:04:42 +08:00
24ae55867a refactor(privacy-popup): 重构隐私弹窗的国际化文案处理逻辑
修复了小程序启动早期Lang未完成初始化时$lang返回空串的问题,将文案计算移到弹窗前一次性执行,统一多平台的文案获取逻辑
2026-07-01 13:46:49 +08:00
b2eb04ab98 refactor(privacy-popup): 合并多端隐私协议配置逻辑
简化隐私弹窗组件的多端环境配置代码,将H5和鸿蒙小程序的初始化配置合并,减少重复代码
2026-07-01 12:00:39 +08:00
7045a05a73 feat: 添加全局隐私协议管理器并适配鸿蒙元服务
1. 新增common/js/privacy.js全局隐私协议管理器,统一处理多平台隐私弹窗逻辑
2. 替换APP-HARMONY为MP-HARMONY平台判断标识,适配鸿蒙元服务
3. 在mp-html组件中增加MP-HARMONY平台兼容
4. 在App.vue中集成隐私弹窗初始化逻辑
5. 重构privacy-popup.vue,接入全局隐私管理器,优化弹窗互斥逻辑
6. 全局挂载$privacy实例到Vue原型链
2026-07-01 09:39:04 +08:00
4adaa945a1 refactor(i18n): 扁平化多语言文件结构,移除嵌套的components对象
统一调整所有组件级多语言配置,将原有的components.[componentName]嵌套结构改为直接顶层键值对,简化语言包的调用层级
2026-06-30 16:53:53 +08:00
eef59211d3 refactor(i18n): 完善remote-only模式下的首屏渲染和请求门控
1. 补充getCachedBundle的注释说明TTL过期缓存返回null
2. 修复globalConfig中onShow的重复判断逻辑,增加boot完成检查
3. 给http请求增加remote-only模式下的boot门控,等待国际化就绪后再发送业务请求
4. 重构main.js的平台差异化处理逻辑,统一各端初始化流程
5. 优化App.vue的boot流程,为小程序/鸿蒙增加加载遮罩
6. 新增bootCompleted状态标志和并发去重机制,完善lang.js的remote-only适配逻辑
7. 补充lang()方法在boot未完成时返回空串的逻辑,避免首屏raw key
2026-06-30 15:29:45 +08:00
07c38c1b1b fix: 适配多平台语言包加载逻辑,优化首屏渲染
调整语言包加载时机,区分H5和小程序/鸿蒙平台:
H5 remote-only模式下先await Lang.boot()再挂载Vue避免首屏raw key
小程序/鸿蒙平台同步注册App,Lang.boot()放到App.onLaunch异步执行不阻塞挂载
移除了无用的加载语言包错误日志注释
2026-06-30 14:30:22 +08:00
de4314ec9b refactor(vue.config): remove remote-only mode related code
remove the remote-only mode detection and webpack plugin configuration that replaces lang directory imports, clean up redundant code logic
2026-06-30 14:17:53 +08:00
50a1c1c695 feat(i18n): 实现remote-only打包模式,优化首屏加载和产物体积
1. 新增remote-only模式下的空语言包stub
2. 新增缓存有效期配置并对齐后端Cache::set 600s
3. 重构语言包加载逻辑,适配remote-only模式
4. 添加webpack替换插件,排除本地lang目录减少产物体积
5. 优化Vue挂载时机,等待语言包就绪后再渲染首屏
6. 改进缓存策略,新增内存缓存TTL校验和语种缓存淘汰
7. 修复语言包缓存key生成逻辑,支持uniacid和appType隔离
2026-06-30 14:04:52 +08:00
55a5a68517 refactor: 统一多语言key的组件命名格式为短横线分隔
根据i18n规范,将所有组件相关的多语言key从驼峰式改为短横线分隔格式,同步更新文档中的示例说明。
2026-06-30 10:28:36 +08:00
e6d47a3d78 refactor: 优化多语言结构并新增远端语言包加载能力
1. 扁平化多语言文件层级,移除嵌套的命名空间
2. 更新组件内多语言调用路径,适配新的语言包结构
3. 重构HTTP请求错误处理逻辑
4. 新增remote-only模式的远端语言包加载器
5. 新增多语言数据源remote-only配置项
2026-06-30 10:03:25 +08:00
32db276e68 docs: add remote-only i18n solution docs and reference
新增远端完全替代本地语言包的国际化方案文档,并在原指南中添加对应引用,补充新文档到文档列表中。
2026-06-29 17:47:24 +08:00
04a1d3c287 docs: add i18n guidelines documentation
add the complete internationalization specification document for the shop-projects/frontend uni-app Vue2 project, covering architecture, specification, usage, development norms and other content
2026-06-29 15:43:14 +08:00
d124d58552 docs: add i18n full audit report and p2 solution plan docs
新增两份国际化审计相关文档:
1. 全量国际化审计报告,覆盖项目内i18n调用问题并记录修复过程
2. P2动态key国际化处理方案文档,盘点8处动态key现状并提供落地解决方案
2026-06-29 15:39:33 +08:00
c7810f16f7 feat: 新增多语言文案并修复动态国际化调用问题
1. 新增多语言文件覆盖组件、页面、公共模块的翻译文案
2. 修复多处动态拼接lang key的调用,增加兜底逻辑避免空值或原始key暴露
3. 补全DIY组件、业务页面的国际化适配
4. 新增P2动态key国际化处理方案文档
2026-06-29 15:29:24 +08:00
c3956f7bcd refactor: 统一调整多页面的语言包key命名风格
1. 将会员购买卡片页的提示语语言包key从customerService.tip替换为统一命名
2. 修正diy文章组件、取消状态页、积分商品列表页的语言包key大小写和路径问题
3. 统一积分商品列表页的多语言调用路径,简化冗余的key前缀
2026-06-29 13:57:30 +08:00
3ef3d05624 docs: 更新TODO.md,标记三个任务项完成
将原有的两个未完成任务标记为已完成,新增TabBar页面状态梳理的完成标记
2026-06-29 11:27:05 +08:00
509b4d2238 refactor(diy-bottom-nav): 优化 TabBar 高亮逻辑,新增来源参数记忆和页面映射规则
1. 新增 redirectLink 处理,添加 from_tab 来源参数实现 Tab 高亮记忆
2. 新增 TAB_BAR_KEYS、NO_TAB_PAGES、PAGE_TAB_MAP 统一管理 Tab 归属配置
3. 重构 checkTabBarActive 函数,增加页面精确映射和来源参数判断逻辑
4. 兼容小程序和 H5 的页面 query 参数获取
2026-06-29 11:25:10 +08:00
053a279102 refactor: 调整loading-cover和隐私弹窗的挂载位置
1.  将公告列表页的loading-cover移到mescroll-uni外部统一挂载
2.  将文件列表页的loading-cover移到mescroll-uni外部统一挂载
3.  为鸿蒙平台的slot强制重绘逻辑添加条件编译包裹
2026-06-29 10:41:14 +08:00
3cedbd7b6b fix(article list): 修复空数据处理和加载时机调整
1. 给列表数据新增空值兜底避免报错
2. 调整loading隐藏和分页结束的执行顺序
2026-06-29 10:32:00 +08:00
7e4400267e style(article/list): 优化文章列表项样式与交互
1.  修复无图文章项布局对齐问题,添加no-image类处理无图场景
2.  将点击事件从click改为tap适配小程序
3.  调整图片模式为aspectFill并补全高度样式
4.  优化标签行高与日期块对齐方式
5.  仅在有封面图时渲染图片区域
2026-06-29 09:53:23 +08:00
1150dad0b5 refactor(article): 替换CSS动画跑马灯为JS驱动实现
重构文章组件的跑马灯滚动逻辑,移除CSS keyframes动画实现,改用JS控制transform实现滚动,新增支持用户手动拖拽交互,统一连续/步进两种滚动模式的触摸控制逻辑,优化跨端表现和交互体验。
2026-06-29 09:38:10 +08:00
16cfe039ba fix(ns-login): add error callback handling for getCode
补充微信环境外获取验证码失败时的错误回调,保证错误能被正确抛出处理
2026-06-29 08:46:23 +08:00
c629562190 refactor(login-redirect): 统一登录跳转逻辑,提取公共方法
将多处手动调用登录弹窗的逻辑替换为公共的redirectTologin方法,简化代码并统一跳转处理流程
2026-06-29 08:40:27 +08:00
2e535b9d93 refactor(member pages): unify onShow login redirect logic
1. extract common onShow login check to dedicated method redirectTologinOnShowLifecycle
2. add fallback callback for login failure to navigate back on wechat mini program
3. update all page login redirect calls to use the new unified method
4. add debug logs for redirect and auth flow tracing
2026-06-27 18:25:53 +08:00
0b760e41a3 refactor: 统一移除局部金额格式化过滤器并全局复用
1. 移除多个页面/组件内重复的moneyFormat局部过滤器
2. 将moneyFormat方法提取到全局配置中复用
3. 调整登录弹窗跳转模式适配H5场景
4. 新增open方法调试日志方便排查
2026-06-27 17:14:03 +08:00
f794a2ae27 refactor: 统一替换登录跳转逻辑为通用方法
将项目内多处手动调用$refs.login.open的登录跳转逻辑,统一替换为新增的redirectTologin通用方法,简化代码并提升维护性,同时统一处理了延迟和nextTick调用逻辑。
2026-06-27 16:52:25 +08:00
aee630b546 fix: 统一登录跳转逻辑,添加redirectTo参数避免页面栈溢出
1. 为所有登录跳转调用添加redirectTo跳转类型参数
2. 调整部分页面的onShow生命周期执行顺序和定时器包装
3. 补充缺失的ns-login组件引用到两个diy组件中
4. 修复部分页面登录后返回出现循环跳转的问题
2026-06-27 15:08:01 +08:00
95194585d2 refactor: 统一替换小程序事件绑定为@tap并优化跳转逻辑
1. 全局替换@click为@tap以适配uni-app事件规范
2. 优化toLogin方法的路由获取逻辑,增加空值判断
3. 重构redirectTo跳转逻辑,统一tab页跳转使用reLaunch确保页面栈正确
2026-06-27 13:46:29 +08:00
55c8e58f32 docs: add project TODO list
create docs/TODO.md and record two current pending tasks
2026-06-27 10:39:10 +08:00
1bf8a4a9b2 style: 统一修复多页面重复的事件绑定冗余代码
1. 移除多处重复的@click和@tap事件,只保留必要的@tap
2. 修复scoped样式穿透语法,补全样式文件末尾换行
3. 统一调整隐私弹窗、搜索页等页面的样式写法
2026-06-27 09:48:28 +08:00
ea40123c76 style(contact page): adjust contact info text font size
统一调整联系方式模块的文字字号,优化页面视觉展示效果
2026-06-27 09:11:41 +08:00
bf4fe97aa3 feat: 新增多语言配置并优化语言加载逻辑
1. 新增多个页面的中英文多语言词条,包括会员卡协议、积分商品、收银台等
2. 新增退款商品选择、微信支付、电子名片等页面的语言包
3. 优化lang.js语言加载逻辑,支持蛇形命名转换和多路径匹配,完善$lang调用兼容处理
2026-06-27 09:07:51 +08:00
84f5cd4568 refactor(common/lang): add shared component lang pack support
add shared language pack system for cross-page components, normalize component and page lang packs automatically, inject shared packs during language merge
2026-06-26 18:26:21 +08:00
4ae21c5d7a refactor: 完成多语言国际化全量替换与补充
1. 新增大量中英文语言包文件,覆盖自定义组件、页面、工具类的文案
2. 替换硬编码文本为多语言调用,统一全局文案管理
3. 优化语言包结构,拆分公共模块与业务模块
4. 修复部分语言加载与国际化适配问题
2026-06-26 17:32:35 +08:00
f7fb9f34f9 feat: add and optimize multilingual text resources
- add new language packs for multiple pages and components including category, cart, order, member center, distribution, etc.
- add Chinese and English translations for new features and UI text
- fix navigation service error message to use multilingual text
- update component templates to use dynamic language translation instead of hardcoded text
- adjust code indentation and formatting for consistency
2026-06-26 13:49:26 +08:00
66a579d48c feat: add and optimize multiple multilingual language packs
1. 新增拼团、砍价、分销、支付、地址、账户等多业务场景的中英文本地化文案
2. 替换项目中硬编码的文本为多语言调用,统一前端页面文案展示
3. 新增多个业务组件的国际化语言配置文件
2026-06-26 10:17:33 +08:00
066ca61d97 feat: 新增多语言文案与组件国际化适配
本次提交完成了大量多语言相关的新增与优化工作:
1. 新增充值、案例、会员资产、订单等页面的中文/英文翻译文案
2. 新增企业微信客服、时间选择、支付弹窗等组件的多语言包
3. 优化工具函数与自定义页面的多语言适配,替换硬编码提示文案
4. 新增会员等级规则、积分商品、退款管理等页面的国际化支持
5. 修复企业微信JS-SDK的错误提示文案硬编码问题
2026-06-26 09:09:46 +08:00
2d8846c64c feat: 新增多语言文案、优化导航及工具函数,修复部分业务逻辑
1. 新增多语言资源文件,覆盖文章、预约日期、会员信息、优惠券、表单、购物车、积分商城、分销、AI聊天等多个模块
2. 优化底部导航组件,使用多语言配置替代硬编码文案
3. 重构工具函数,新增从后端数据提取多语言文案的工具方法
4. 修复邀请好友页面的保存提示文案,替换为多语言版本
5. 修复商品SKU组件的提示文案,使用多语言配置
6. 重构AI聊天页面的帮助文档和回复模板,使用多语言配置
7. 优化空状态组件,支持多语言默认文案
8. 修复跳转逻辑,补全参数传递
9. 新增本地开发环境配置
2026-06-25 18:15:31 +08:00
ca4e7fd170 fix(util): 给redirectTo调用传递完整link参数
修复跳转逻辑,将完整的link对象作为参数传入跳转方法,保留原有跳转参数的同时传递额外上下文信息
2026-06-25 16:39:57 +08:00
5d3663786c feat: add multi-language page configs and fix i18n issues
1. 新增多套多语言页面翻译文件,覆盖文件列表、案例展示、商户相关、印章相关、分销、小程序发货等页面
2. 修复语言包拼写错误:loginTpis → loginTips
3. 重构语言包合并逻辑,使用深度合并替代浅合并避免子key丢失
4. 优化导航栏标题设置,统一使用$langConfig.title替代硬编码标题
5. 修复底部导航栏语言切换不响应的问题,改为响应式获取当前语言
6. 完善英文通用语言包,补充订单、购物车、会员相关翻译
7. 修复商品详情页默认标题为空的问题,设置为"商品详情"
2026-06-25 14:52:39 +08:00
cc7125361f chore: 移除i18n守卫插件与废弃的国际化文档
1.  删除vue.config.js中的I18nGuardPlugin构建期审计插件
2.  删除docs目录下全部废弃的国际化规则文档
2026-06-25 13:46:58 +08:00
8e218bb663 feat: 新增多语言国际化页面配置,修复部分页面硬编码文案
1. 新增了zh-cn和en-us两套语言下的大量页面国际化配置文件,覆盖商品、订单、会员、营销活动等多个业务模块
2. 修复了分销页面、VR页面、支付页面、商品不存在页面的硬编码提示文案,替换为国际化调用
3. 删除了原有的i18n检查脚本文件
2026-06-25 11:00:50 +08:00
5f41febd70 chore(i18n): 清理死代码 + 遗留 lang 文件 + 旧工具
## 删除的死代码脚本
- scripts/i18n_class_c.py (脚本自承'新架构下永远输出 0',纯防御性)
- scripts/full_migrate_i18n.py (其产出违反 CLAUDE.md 1.2 中文 key 铁律,已标 DEPRECATED)
- scripts/__pycache__/ (Python 缓存)

## 删除的旧 per-page lang 文件
- lang/zh-cn/<page>/<file>.js (140 个)
- lang/en-us/<page>/<file>.js (139 个)
- 共 279 个文件,运行时不再加载,0 个 key 被 .vue 调用(经 diagnose_keys.py 验证)

## 删除的备份和迁移表
- lang/_backup/ (git 已跟踪原文件)
- lang/_migration_map.json / lang/_migration-map.json (运行时不用)

## 删除的中间产物 JSON
- docs/i18n-rename-*.json (smart_rename 中间产物,已用完)
- docs/i18n-ambiguous.json / i18n-audit.json / i18n-call-rewrite.log /
  i18n-clean-dead.log / i18n-file-texts.json / i18n-page-titles.json /
  i18n-vue-extract.json (前一会话残留,无引用方)
- docs/i18n-{naming,shadow,strict}-audit.json (脚本会自动重新生成)

## 删除的 modular lang 文件
- lang/zh-cn/*.js / lang/en-us/*.js (20 个模块文件,内容是上一会话产生的死代码)
- lang/zh-cn/index.js / lang/en-us/index.js (聚合入口)
- lang/DEPRECATED.md (已不再相关)

## 删除的不成熟脚本
- scripts/check_perpage.py (诊断用,已完成)
- scripts/diagnose_keys.py (诊断用,已完成)
- scripts/smart_rename_i18n.py (v1-v3 都 bug,未修完)

## 现状
- lang/ 现在只有 zh-cn.js + en-us.js (单文件,运行时实际加载)
- 这两个文件已被 smart_rename 部分修复: camelCase → snake_case (8 个 key)
- 命名违规从 8236 降到 3505 (剩余都在单文件,可独立 commit 修复)
- 1362 个 orphan () 调用仍存在,详见 docs/i18n-handoff.md
2026-06-25 10:48:15 +08:00
a74263016b chore: 更新gitignore,添加鸿蒙元服务和其他忽略项
补充忽略鸿蒙元服务构建产物目录、openspec文件以及完善换行格式
2026-06-25 10:39:48 +08:00
1f1a642f99 fix(i18n): 修复审计脚本扫不到 modular 文件的盲区,接入命名规范检查到构建卡点
- i18n_audit.py: 同步扫描 lang/<locale>/<module>.js 多文件 + lang/<locale>.js 单文件
- i18n_check_naming.py (新增): 检测中文 key / 扁平 key / 行号式 locational key / 跨业务域同名 / 非 snake_case
- i18n_check.py: 加入 naming 子命令,默认全套审计包含 naming
- vue.config.js: I18nGuardPlugin 增加 naming 阻断
- full_migrate_i18n.py: 标 DEPRECATED,文档说明其输出违反 CLAUDE.md 1.2 铁律
- diagnose_keys.py (新增): 定位 orphan 调用 key

背景:之前审计'假阳性通过',实际 6018 处违规;现在审计能看到真实状态。

Fix: docs/i18n-rules.md 1.6 条铁律需补强 (modular 审计入口已加)

统计 (i18n_check_naming.py 当前输出):
  A. 中文 key: 2146
  B. 扁平 key: 188
  C. 行号式 locational key: 1612
  D. 跨业务域同名 tail: 1366
  E. 非 snake_case key 段: 2924
  TOTAL: 8236 处
2026-06-25 10:26:55 +08:00
2e85cfd78c fix(App.vue): 解决鸿蒙元服务版本,TabBar 就能正常显示了;修复多平台下API调用可能不存在的报错
1. 给options.query访问增加存在性校验,避免空指针报错
2. 给uni.getUpdateManager、uni.onNetworkStatusChange调用增加兼容性判断,防止在不支持的平台抛出错误
2026-06-23 16:57:28 +08:00
638406567d refactor(member page): extract global config getter method
extract repeated diyData.global access into a dedicated globalCfg computed property, simplify button visibility check logic
2026-06-23 11:01:55 +08:00
b0dad04b59 fix(member page): 调整取消和退出按钮的显示逻辑
将判断条件从"不等于0"改为"等于1",匹配配置项的真实生效逻辑
2026-06-23 11:00:13 +08:00
f258987e0e refactor: 替换多页面国际化文本为硬编码中文内容
移除项目内大部分$lang()国际化调用,替换为直接中文文本,统一前端展示文案
2026-06-23 08:55:16 +08:00
750ed2dac7 refactor: 替换硬编码文本为多语言配置
替换了项目中所有硬编码的提示文案,将其统一迁移到多语言语言包中,包括授权、自定义页面、HTTP请求、分享、客服等模块的提示文本,提升项目的国际化可维护性
2026-06-23 08:36:55 +08:00
6c7f7d4837 fix(vr page): restore and adjust bottom tabBar display
将注释掉的自定义底部导航组件恢复并正确嵌入到VR页面布局中,确保页面底部导航正常显示
2026-06-22 18:29:05 +08:00
0858618e77 refactor(merch detail): extract search placeholder to lang config
extract the hardcoded search input placeholder into internationalization language config, unify the text with the existing common lang entry
2026-06-22 18:14:30 +08:00
1143175990 refactor(merch): 替换硬编码文本为国际化语言包
1.  将商品详情页的"立即咨询"替换为$lang('merch.consultNow')
2.  新增商品相关国际化文案并替换原有硬编码字符串
3.  统一使用多语言函数处理页面文本内容
2026-06-22 18:13:11 +08:00
e9483e26e5 refactor(i18n): 替换硬编码文本为多语言配置
1.  删除冗余的语言文件 contenr.js
2.  将页面内硬编码字符串替换为$this.lang()调用
3.  整理common.js内的多语言词条,归类移动旧有配置到正确分组
2026-06-22 18:08:03 +08:00
b30ba914b9 i18n: replace hardcoded strings with language translations
批量将项目中多处硬编码的文本替换为多语言翻译条目,统一项目文案管理,提升多语言适配效率,包括导航提示、操作反馈、空状态提示、表单占位符等各类文本内容。
2026-06-22 17:59:25 +08:00
4715f06b2f i18n: 替换所有硬编码文本为多语言配置
将项目中各处的硬编码字符串替换为国际化语言包调用,统一管理页面和组件的文案内容,方便后续多语言适配与维护
2026-06-22 17:53:38 +08:00
47098bddda refactor: 替换硬编码文本为多语言配置
1. 替换分销等级页标题拼接的硬编码语言文本
2. 替换AI聊天页面的硬编码提示文本为多语言key
3. 新增完整的多语言翻译配置项
2026-06-22 17:48:53 +08:00
cb81aad784 refactor(fenxiao,member): replace hardcoded strings with i18n translations
standardize all hardcoded text across分销 and member pages to use language packs, fix template syntax errors in level.vue, and unify text display logic
2026-06-22 16:20:59 +08:00
d8705398bb refactor(zh-cn lang): add multi-language terms and replace hardcoded strings
add new common and fenxiao section language entries, replace hardcoded toast text in goods_list.js with multi-language support
2026-06-22 16:15:58 +08:00
23426b168f refactor(fenxiao): 替换分销页面硬编码文本为多语言配置
1.  将账单页面的账单编号替换为多语言键fenxiao.orderNo
2.  将下级分销页面的硬编码文本替换为对应多语言配置
3.  新增分销相关多语言词条到中文语言包
2026-06-22 16:07:28 +08:00
26eac57dc2 docs(zh-cn): add chinese localization translations for分销相关文案
补充简体中文语言包中分销、订单、提现等模块的多语言文案
2026-06-22 15:39:47 +08:00
47f21f391c refactor(fenxiao,point): 替换页面硬编码文本为多语言配置
将分销和积分商城页面中的硬编码字符串全部替换为语言包调用,统一项目多语言适配,提升页面文本可维护性和国际化支持
2026-06-22 15:25:19 +08:00
a2a637c320 chore(lang/zh-cn): add chinese translation texts for distributor module
add over 40 new i18n entries for分销相关功能界面, including commission rates, upgrade conditions, share tools and empty prompts
2026-06-22 15:24:02 +08:00
5ca4509d5b refactor(zh-cn lang): 调整国际化文案结构与引号风格
1. 将原cart模块的文案移动到member下的对应位置
2. 统一所有中文文案使用双引号
3. 拆分过长的字符串提升可读性
2026-06-22 15:17:42 +08:00
a7541d0598 refactor: 将页面硬编码文本替换为国际化语言包
统一替换积分商城、分销页面的硬编码字符串为多语言key,包括订单状态、按钮文案、提示信息等,提升项目多语言适配能力
2026-06-22 15:09:19 +08:00
d6633b698a refactor(order): 替换页面硬编码文本为国际化语言包
将订单相关页面的静态文字全部替换为$lang国际化调用,统一多语言管理,提升项目可维护性和国际化适配能力,涉及订单列表、订单支付、通用订单组件三个页面文件。
2026-06-22 15:07:04 +08:00
4d89454a17 chore(lang/zh-cn): add multiple Chinese translation entries
补充新增的页面提示、订单相关、分销模块以及表单字段的中文翻译文案
2026-06-22 15:05:21 +08:00
4b5dda9c4c i18n(zh-cn): add missing translation entries for new arrival time and community
补充简体中文国际化文案,新增上新时间和社群的翻译项
2026-06-22 14:38:58 +08:00
9f07967982 docs(zh-cn lang): add more Chinese localization strings
补充了订单相关、积分商城的多语言文案,包括元、折、确认订单、积分兑换等场景的本地化翻译,完善中文语言包内容
2026-06-22 14:30:03 +08:00
2337e3cacf refactor: 将项目内硬编码文本替换为多语言调用
统一替换所有页面和组件中的硬编码字符串为 $lang 多语言方法调用,提升项目国际化适配能力
2026-06-22 14:04:13 +08:00
46508c7d55 i18n: 替换硬编码文本为多语言配置
替换了多个组件中的硬编码文字,新增完善多语言翻译词条,包括通用、聊天、预约日期、门店等模块的翻译内容
2026-06-22 13:58:26 +08:00
c59abc9545 refactor(zh-cn lang): 完善中文语言包内容
大幅扩充中文语言包,新增商品SKU、订单、支付、会员中心、优惠券等多模块翻译词条,统一使用双引号格式化字符串
2026-06-22 11:45:12 +08:00
fce936feee refactor(member/card_buy): 替换硬编码文本为多语言配置
将页面内所有硬编码的中文文案替换为$lang多语言调用,统一国际化处理,包括按钮文字、标题、权益描述和空状态提示等内容,同时修复了image标签自闭合格式问题
2026-06-22 11:36:12 +08:00
cc39e06161 refactor: replace hardcoded text with language package entries
Replace all inline hardcoded Chinese strings in multiple Vue pages with corresponding language package keys, to unify text management and support multi-language switching.
2026-06-22 11:23:53 +08:00
014046bc9e refactor: 替换页面中硬编码文本为多语言配置
将项目中多处页面的硬编码字符串替换为国际化语言包调用,统一文本管理,方便后续多语言扩展和维护
2026-06-22 10:47:27 +08:00
45830ebda4 refactor: 替换项目中硬编码文本为多语言配置
将多处页面和组件内的硬编码文字替换为国际化语言包调用,包括空状态提示、按钮文案、表单占位符、弹窗标题等内容,统一项目多语言管理
2026-06-22 10:38:33 +08:00
062fb3be90 refactor(ns-form): 替换硬编码提示文本为国际化配置
将表单内所有硬编码的提示文案替换为多语言配置项,统一维护文案内容,方便后续国际化扩展
2026-06-22 10:04:18 +08:00
02644e1959 refactor(ns-contact): 替换硬编码文本为多语言配置
将页面中硬编码的客服相关文本替换为国际化语言包调用,实现多语言支持
2026-06-22 10:03:11 +08:00
315bdc71ff i18n(ns-chat): 替换聊天模块硬编码文本为国际化文案
将ns-chat相关组件中的硬编码中文文本替换为多语言国际化字段,统一页面文案展示方式,方便后续多语言适配维护
2026-06-22 09:59:47 +08:00
f3d9f397d7 refactor(member): 优化多语言调用和可选链使用
1.  移除语言包默认参数,统一使用翻译文本作为默认值
2.  为嵌套属性访问添加可选链操作符,避免空指针报错
3.  新增会员相关的多语言词条
2026-06-18 17:35:52 +08:00
b799e67e54 chore: 调整manifest.json中的超时时间为20000毫秒
将原有3000毫秒的超时设置修改为20000毫秒,延长超时等待时长
2026-06-18 17:11:11 +08:00
06e3a4d796 refactor(globalConfig&member): 重构多端按钮显示逻辑
1. 新增全局配置方法getAppType用于获取当前平台类型,对齐服务端$app_type
2. 将会员页按钮显示判断改为基于当前平台的配置校验
3. 简化模板中的条件判断代码
2026-06-18 17:09:34 +08:00
17864427c1 fix: 统一登录态失效后的跳转逻辑并补充多语言默认值
1.  统一所有接口登录态异常(-1)时的处理,跳转至登录页而非原页面或首页
2.  补充$lang多语言调用的默认参数,防止翻译缺失
3.  修正公共js中的跳转路径和异常处理逻辑
2026-06-17 10:10:17 +08:00
851b5fe722 refactor(member page): 优化页面样式计算与按钮显示逻辑
1. 抽离页面样式为computed属性pageStyle提升代码可读性
2. 新增自定义配置控制注销和退出登录按钮的显示
2026-06-17 09:50:17 +08:00
c2b38476ea refactor(lang): 优化多语言翻译函数,支持传入默认值
修改lang.js的翻译方法,支持传入默认值参数,当找不到对应翻译时使用传入的默认值;同时更新member-public.js中的调用方式,简化多语言调用代码
2026-06-16 18:03:52 +08:00
e9ee61f509 refactor(member): 提取公共登录态清理和注销逻辑到mixin
重构会员相关页面的重复代码,将清除登录态、退出登录、账号注销相关逻辑抽离到公共mixin中,统一复用代码并减少重复维护成本
2026-06-16 17:34:56 +08:00
c01a026149 perf(store, globalConfig): 优化多语言刷新和主题颜色缓存
1.  修改全局配置的多语言刷新逻辑,新增参数控制全量刷新时机
2.  为主题颜色生成添加缓存,避免重复遍历主题对象计算CSS变量
3.  从本地存储初始化主题配置,持久化主题状态
2026-06-16 17:34:09 +08:00
2e85e11e92 refactor(i18n): 优化多语言缓存逻辑,提升翻译性能
1. 新增多语言缓存体系,包括合并包缓存、字段解析结果缓存和页面路由缓存
2. 新增缓存失效方法,在语言更新、切换租户时统一清理缓存
3. 重构$lang方法,复用页面路由缓存避免重复计算
4. 增加字段结果缓存,命中直接返回避免重复解析
5. 复用合并后的语言包,减少深拷贝和合并操作次数
6. 清理冗余递归深度注释
2026-06-16 17:04:03 +08:00
efd7cdb8d7 fix(lang): 修复页面未初始化时获取语言失败的问题
1.  兼容_page不存在的场景,优先使用common语言包
2.  优化路由路径获取逻辑,支持$page.path作为备选
3.  避免深拷贝污染语言包缓存,仅在langPath有效时加载页面包
2026-06-16 16:53:31 +08:00
e51c03235f refactor(nav): 动态控制导航栏返回按钮显示逻辑
1. 新增isTabBarRootPage工具方法判断是否为tab根页面
2. 在全局混入中添加isTabRootPage计算属性
3. 替换多处硬编码的isBack属性为动态绑定
4. 优化shouldShowTabBar计算属性的代码逻辑
2026-06-16 15:34:10 +08:00
92700f9a21 refactor(utils&tabbar): 重构tabbar高亮逻辑与分包路径适配
1. 修复store中tabBarList初始值为null替代空字符串
2. 重构adaptSubpackageUrl,优化正则匹配与移除冗余映射
3. 新增路径归一化、分包名提取工具函数
4. 重写checkTabBarActive,新增精确匹配、packageEntryTab优先级匹配逻辑
5. 重构diy-bottom-nav组件的路由更新与高亮校验逻辑,统一路径处理流程
2026-06-16 14:56:17 +08:00
c0e64437f0 refactor(promotion pages): 统一分销和商品分类页的底部适配逻辑
重构了全局配置里的底部边距计算方式,替换原有tabBarPaddingStyleValue为tabBarPagePaddingStyle,同时调整了tabBarHeight的取值逻辑,适配是否显示tabBar的场景,移除冗余的计算属性
2026-06-16 14:29:09 +08:00
6fb0e264b8 refactor(i18n): 重构多语言模块,修复递归和缓存问题
1.  添加递归保护机制防止$lang调用栈溢出
2.  新增storage缓存层减少重复调用uni.getStorageSync
3.  修复语言包合并污染缓存问题,改用深拷贝合并
4.  增加循环引用检测避免解析异常
5.  注释掉冗余的console.error日志
6.  新增重入保护防止refresh死循环
7.  优化切语言/切租户时的缓存清理逻辑
2026-06-16 11:53:45 +08:00
64d3ac8f8a refactor: 统一重构底部导航栏间距逻辑与显示规则
1.  新增全局计算属性统一处理底部导航栏显示判断与间距样式
2.  替换多个页面的手写底部间距逻辑为通用样式
3.  新增路由匹配工具函数,支持灵活配置导航栏显示范围
4.  优化底部导航组件的显示条件判断
2026-06-16 11:25:54 +08:00
6c6822ca16 feat: 为多个页面添加底部tabBar适配布局
为文章列表、公告列表、品牌页、优惠券页、案例页、文件列表、商品搜索、积分商品列表、分销相关页面以及订单列表页添加了动态底部内边距样式,根据tabBar是否存在适配页面底部空间,同时统一添加自定义底部导航组件
2026-06-16 09:14:39 +08:00
b86e8e7fa6 refactor(merchcategory): add bottom tabbar and optimize page layout
1. add diy bottom navigation component to the merch category page
2. replace hardcoded height style with dynamic computed style based on tabbar status
3. add unified page path mapping and url resolution utilities
4. update page jump logic to use new page_key based routing
2026-06-16 08:40:59 +08:00
7b83636c99 feat(diy-article): add step-by-step marquee scroll mode
新增逐条步进式跑马灯滚动模式,适配后端配置的stepPause参数,实现单条内容间暂停的滚动效果,优化了触摸控制逻辑与定时器清理逻辑,修复了Vue2代理问题。
2026-06-15 16:12:19 +08:00
d01b0d46e4 refactor(diy-article): 替换scroll-view滚动为CSS跑马灯实现
移除原scroll-view自动滚动逻辑,改用CSS animation实现无缝跑马灯效果,解决跨端滚动跳变问题,移除JS定时器驱动逻辑,提升动画流畅度和跨端一致性,优化触摸暂停恢复逻辑。
2026-06-15 15:46:05 +08:00
db1d47f456 feat(diy-article): add number humanization and fix layout alignment
1. 新增_humanizeNum方法实现阅读/点赞数的千/万单位人性化展示
2. 调整图标间距与日期布局为自然的左右分栏样式
3. 修复style-1无图item与有图item的元信息行垂直对齐问题
2026-06-15 14:53:51 +08:00
de4b510c00 refactor(article-component): 替换swiper为scroll-view实现自动滚动,优化紧凑布局
1.  将原swiper自动滚动方案替换为scroll-view实现,支持item自然高度,不再强制等高,解决短item下方留白问题
2.  新增连贯滚动和步进滚动两种自动滚动模式,适配不同场景需求
3.  修复H5端rpx单位不兼容问题,统一内联样式单位转换逻辑
4.  优化滚动容器高度计算,根据配置显示数量动态计算窗口高度
5.  新增触摸暂停恢复逻辑,提升用户交互体验
2026-06-15 14:35:17 +08:00
089da9181b feat(diy-article): add dynamic swiper height and date display control
重构文章组件的swiper高度计算逻辑,改为基于实际item高度动态计算;新增日期显示的配置控制,完善样式统一和布局适配,优化空列表兜底逻辑与间距控制。
2026-06-15 11:54:21 +08:00
c1d4a68e26 refactor(diy-article): replace iconfont with uni-icons component
1. 替换阅读数、点赞数和查看更多按钮的自定义图标为uni-icons组件,统一图标使用方式
2. 新增metaColor计算属性同步阅读区文字色,确保图标颜色与文本保持一致
3. 修复全局样式干扰导致的阅读数/点赞数字号和颜色不一致问题
4. 调整查看更多默认配置与后端对齐,修正control默认值为true
2026-06-15 10:52:58 +08:00
f7f1b1191e fix(diy-article): 修复无图文章样式异常,新增字号样式配置
1. 为无图文章项添加no-image类适配样式,统一与有图项的视觉高度
2. 新增标签、摘要、阅读区的字号CSS变量支持,替换硬编码字号
3. 调整列表项间距默认值和swiper行间距,优化布局紧凑度
4. 补充默认字号配置项,兼容老数据缺失字段的情况
2026-06-15 10:03:26 +08:00
f9d144159a refactor(article-component): 新增多维度CSS变量支持,对齐后端默认配置
新增标签胶囊、摘要文字、阅读区、查看更多、标题字号等多组CSS变量,将组件样式控制权交给外部配置,同时将默认值对齐后端design.js的nestedDefaults。重构列表项间距、分割线颜色等硬编码样式为变量驱动,统一组件样式管理逻辑。
2026-06-15 08:28:07 +08:00
3952517ac9 refactor(article): 重构diy文章组件,支持非滚动模式与样式增强
1. 新增非滚动列表模式,适配scrollMode配置,兼容旧版swiperConfig参数
2. 重构样式系统,使用CSS变量统一管理主题与圆角,对齐ns-newform实现逻辑
3. 新增文章标签、阅读数、点赞数显示配置
4. 新增查看更多按钮,支持按分类/标签跳转列表页
5. 优化空值处理与图片加载失败逻辑
6. 修复computed class编译为逗号分隔字符串的样式错误
7. 重构响应式样式计算,支持自动适配不同布局的高度
2026-06-13 18:01:09 +08:00
01e7c3e981 refactor(diy-article): 优化文章组件,完善空状态和鲁棒性
1. 新增空数据占位提示
2. 给props添加默认值避免空指针
3. 完善样式和判断逻辑的默认值处理
4. 增加请求失败兜底逻辑
5. 优化响应式更新图片错误的处理
6. 抽离class计算逻辑提升代码可读性
2026-06-13 14:26:52 +08:00
ebe2963466 fix(ns-newform): 优化地址选择占位符显示逻辑
根据地址类型动态切换占位符文本,默认区分省市和省市区场景,移除冗余的flex布局样式
2026-06-12 16:58:41 +08:00
5847612a58 fix(ns-newform): 修复选择器箭头对齐与布局问题
1. 调整选择器容器布局,将箭头移入flex容器内,统一picker类布局结构
2. 新增box-flex样式类,实现picker与箭头的自适应右对齐布局
3. 修复城市选择器的flex布局类缺失问题
4. 优化原生picker和自定义组件的宽度适配,确保文本对齐生效
2026-06-12 16:23:23 +08:00
4a5bac7aa5 fix(diy-form): 更新提交按钮内边距映射表
对齐后端design.js的submitSizeMap,新增mini和huge尺寸的内边距配置
2026-06-12 16:07:58 +08:00
e3c69e7e32 style&feat: 优化表单提示语与提交按钮样式
1.  调整默认提示语字号从24rpx改为32rpx,颜色改为纯黑,背景设为透明
2.  新增提交按钮顶部外边距配置项,支持自定义表单与按钮间距
3.  同步更新diy-form组件的提示语样式与提交按钮外层布局
2026-06-12 14:46:12 +08:00
12a1422470 refactor(diy-form&formdata): 重构表单提交与渲染逻辑
1. 为diy-form新增submit事件,支持父组件接管提交逻辑
2. 移除formdata.vue的内置提交按钮与自定义banner/tip,交由diy-form统一处理
3. 调整formdata的diyValue参数,让diy-form自主渲染banner和提示文案
2026-06-12 14:17:57 +08:00
48235c18a5 refactor(diy-form): 兼容前后端命名格式,优化表单配置处理
1.  重构mergedFormConfig逻辑,同时支持camelCase和snake_case格式的配置项,camelCase优先读取
2.  调整ns-newform的mode参数读取mergedFormConfig的formLayout
3.  优化提示语样式,新增tipBorderColor支持显示底部边框
4.  修复submitText读取逻辑,改为从mergedFormConfig获取
5.  移除多余的console日志,更新注释说明
2026-06-12 12:00:10 +08:00
fe9cbcd21d refactor(form, diy-form): 重构表单组件复用逻辑,新增raw模式适配现有表单数据
1. 新增diy-form组件的raw数据源模式,支持直接透传ns-newform格式的表单数据
2. 新增showSubmit配置项,支持隐藏内置提交按钮由父页面自行实现提交逻辑
3. 暴露verify和getFormData方法供父组件调用
4. 替换pages_tool/form/formdata.vue的旧表单组件为diy-form,适配新的调用方式
5. 新增样式穿透修复diy-form默认样式与原有页面风格不一致的问题
2026-06-12 11:09:08 +08:00
87fbda698c refactor(diy-form): use objToStyle to format style objects
统一使用 $util.objToStyle 方法处理样式对象,简化样式代码编写,保持代码风格一致
2026-06-12 08:27:03 +08:00
39ab70510c style(uv-count-to): 优化文本样式处理逻辑
将手动拼接样式改为使用$util.objToStyle统一处理,提升代码可读性和规范性
2026-06-11 18:03:54 +08:00
ea01bbd260 refactor(util): 优化objToStyle方法实现并补充细节
新增多项特性:自动转换驼峰式CSS属性为短横线命名、过滤无效样式值、补充分号、处理非对象入参,同时完善注释说明
2026-06-11 18:03:41 +08:00
b3dd1af674 refactor(ns-newform): 统一使用工具函数转换样式对象
1. 将所有样式计算方法改为通过$util.objToStyle生成样式字符串
2. 优化行分割线的样式定义方式,拆分border-bottom属性
3. 移除最后一个子元素的分割线样式逻辑,改为通过CSS变量控制
2026-06-11 17:47:06 +08:00
bbe3d75267 style(ns-newform): 调整组件样式作用域并补充H5适配
将原全局兜底样式改为scoped作用域,同时为.placeholder类添加H5端高度适配样式,移除冗余的全局样式注释说明
2026-06-11 16:52:51 +08:00
f11146013e refactor(ns-newform): 优化表单样式计算与渲染逻辑
1. 移除模板内动态调用的样式方法,改用预计算的响应式样式属性
2. 重构行分割线实现,改用border-bottom替代伪元素提升兼容性
3. 新增兜底样式解决小程序占位符样式失效问题
4. 统一表单样式的计算时机与响应式更新逻辑
2026-06-11 16:29:14 +08:00
7c7e67df4a style(components-diy): 修正拼团头像边框的变量名和注释
更新了拼团头像边框的css变量名,将原pintuan-label-color改为pintuan-avatar-border,并补充注释说明改名原因,同时调整了对应注释描述。
2026-06-11 16:23:33 +08:00
f5badc550c style(style_color): add unified marketing theme color tokens
为所有主题预设新增统一的营销类颜色令牌,包含拼团、砍价、秒杀、会员、积分、分销等多场景的渐变与装饰色值
2026-06-11 16:23:04 +08:00
25636f8133 style(ns-newform, diy-form): 对齐后端样式规范优化表单组件
1. 调整ns-newform的图片上传框样式,匹配后端design.css的.img-box样式参数
2. 简化diy-form的样式变量绑定,移除冗余的cssVars计算属性
3. 重构diy-form提交按钮样式,支持宽度百分比和尺寸预设,对齐后端设计规范
4. 优化表单布局类名逻辑,简化样式绑定代码
2026-06-11 15:55:11 +08:00
08caa49b43 style: 将项目内硬编码色彩替换为CSS变量,兼容多平台
本次提交将项目内47处硬编码色彩值替换为CSS自定义属性,同时添加了兜底纯色样式以兼容旧版小程序 runtime。覆盖了微信小程序、鸿蒙元服务和H5三端,所有渐变、纯色、边框色都增加了主题化支持,并新增了多平台主题兼容测试文档。
2026-06-11 15:32:00 +08:00
555443dc44 feat: add remote theme override support
实现了全量的主题远端覆写功能,包含:
1. 新增主题合并工具类,支持多桶安全合并与原型链过滤
2. 新增主题远端覆写运行时,支持多租户、多端、三态缓存
3. 改造Vuex主题加载逻辑,实现本地预设+远端覆写的合并应用
4. 改造App.vue首屏主题加载流程,支持并行拉取与缓存预热
5. 新增主题更新、租户切换的事件监听与自动刷新逻辑
2026-06-11 14:55:32 +08:00
fae1d77ba5 refactor(diy-form&ns-newform): 重构表单组件样式与配置体系
1.  统一表单样式配置为中心化CSS变量方案,替换原有硬编码样式
2.  新增表单配置合并逻辑,兼容新旧数据格式与平台差异化配置
3.  拆分提交按钮与提示语样式,实现完全可配置化
4.  优化ns-newform组件的样式复用与响应式布局逻辑
5.  修复多端适配与占位符默认值问题
2026-06-11 09:45:09 +08:00
2f5f23d21a refactor(i18n): 完善多语言适配与缓存隔离逻辑
1. 扩展支持多语种并对齐后端白名单配置
2. 实现租户/应用/语言三维缓存隔离
3. 加固语言包合并的原型链安全防护
4. 优化语言列表加载逻辑与调试日志
5. 调整uniacid切换与语言更新的事件处理
2026-06-10 14:26:48 +08:00
071db2d70c feat(i18n): add remote translation override and hot update support
1. add remote translation override feature with multi-tenant isolation
2. implement hot reload for i18n texts via componentRefresh mechanism
3. add boot timeout fallback and local cache support
4. add events for translation update and fallback state
2026-06-10 14:12:49 +08:00
fd6527aa38 refactor: 迁移ns-newform组件到标准components目录并更新引用
1. 将ns-newform组件从pages_tool/_components移动到项目标准components目录
2. 更新所有文件中对该组件的导入路径和文档引用
3. 优化diy-form组件的表单数据处理逻辑,兼容更多数据格式
2026-06-09 09:50:27 +08:00
605ca69238 style: 统一优化表单组件的样式细节
调整了表单容器、输入框、文本域等组件的尺寸、内边距和圆角参数,统一整体视觉风格,优化交互体验
2026-06-09 09:20:21 +08:00
8c32f78503 style: 优化表单组件的样式与布局细节
调整了标签字体大小、最大宽度限制,重构了表单项的内边距、边框样式和间距,统一了输入框、文本域等组件的尺寸与视觉表现,优化了整体排版一致性
2026-06-09 09:18:01 +08:00
14ba88b645 refactor(diy-form): 重构自定义表单组件,替换为通用表单组件
1.  替换硬编码表单项为可配置的ns-newform组件
2.  支持横向/纵向两种布局模式
3.  添加表单Banner、提示语配置能力
4.  统一表单提交逻辑,新增表单校验和重置功能
5.  优化ns-newform组件样式与交互细节
2026-06-08 16:47:02 +08:00
4f44b4f574 fix(harmony): 双列模式,点击图片等不能进入商品详情页面 2026-06-05 17:39:50 +08:00
dcc261b0d0 fix(harmony): 双列模式首次切换时瀑布流错位导致图片重影
鸿蒙下双列 items 一直在 display:none 状态下渲染,首次切换时
boundingClientRect 测得尺寸为 0,waterfallflow 算出来的 left/top
让 items 全部叠在一起。

修复:通过 :key 加 isList 前缀,切换模式时强制重建 DOM,新 DOM
在 display:flex 可见状态下生成,测量正确。

平台判断放在 mixin 的 goodsItemKey 方法里用 JS 条件编译,模板
只调方法,避免在 vue 模板里写 #ifdef/#else(uni-app 不支持)。
2026-06-05 16:24:59 +08:00
d6c994e8f0 chore(harmony): 清理 mescroll 鸿蒙适配的调试日志
移除 components/mescroll/* 与 pages_goods/public/js/list.js 中所有
[mescroll-uni][HARMONY] / [my-list-mescroll][HARMONY] 调试日志。

保留功能性修复:watcher 触发首屏 resetUpScroll、isInit 提前为 true、
slot :key 强制重建、首次加载 300ms 延迟、setClientHeight data.height>0
校验与 10 次重试。
2026-06-05 15:25:46 +08:00
e604a41e14 fix(harmony): 首次加载延迟300ms确保scroll-view渲染就绪后再请求数据
根因分析(最终结论):
- H5/微信:API请求需200~500ms,此时scroll-view已完成首次渲染,数据正常显示
- 鸿蒙元服务:API响应极快(<50ms),抢在scroll-view首次渲染完成前返回数据
- mescroll在slot内容未渲染时测得高度为0 → 列表不可见
- 点击排序之所以能显示,是因为第二次load时DOM已完全稳定

修复方案:
- 将getGoodsList拆分为getGoodsList(入口) + _doGetGoodsList(实际逻辑)
- MP-HARMONY环境下首次加载延迟300ms,确保scroll-view DOM就绪
- 后续翻页/刷新/排序操作不延迟,保持原有体验
- 配合scrollTo(0,0)作为双重保险强制重新测量内容高度
2026-06-05 11:57:01 +08:00
51ae3b1308 fix(harmony): 恢复 mescroll 上拉加载区域,修复列表不显示的根本原因
根因分析(重要):
- 之前为解决'一直处于加载状态'问题,条件编译隐藏了上拉加载区域
- 但这导致了连锁反应:upLoadType 变化时无任何 DOM 更新 → slot 内容不被刷新
- 点击排序之所以能显示,正是因为排序触发 resetUpScroll → showUpScroll
  → upLoadType 从1变0 → 引起内部 DOM 更新 → 连带刷新 slot

修复:
- 恢复 mescroll-uni 上拉加载区域的渲染(去掉 #ifndef MP-HARMONY)
- upLoadType 的正常变化(1→0/2)会驱动 DOM 更新,从而连带渲染 slot 列表内容
- loading-cover 保持条件编译隐藏(它是独立组件,不影响 slot 渲染)
2026-06-05 11:53:26 +08:00
2ec9aa990f fix(harmony): 数据加载后调用 scrollTo 强制 mescroll 重新计算内容高度
- 根因:mescroll 初始化时 setClientHeight 在 slot 内容渲染前执行,测得高度为 0
- 数据加载后 mescroll 不知道内容高度已变化,scroll-view 仍保持 0 高度
- 点击排序后触发 refresh() → setClientHeight() 重新测量,内容才显示
- 修复:数据加载后调用 scrollTo(0, 0) 强制 mescroll 重新测量内容高度
- mescroll-uni.vue 同步暴露 scrollTo 方法供外部调用
2026-06-05 11:47:22 +08:00
a23d57547b fix(mescroll): 移除鸿蒙端强制刷新slot的临时方案 2026-06-05 11:41:07 +08:00
dc2018ee17 fix(harmony): 数据加载后通过改变 slot key 强制重建列表 DOM
- 根因:鸿蒙 ArkUI 对 slot 内 Vue 响应式更新完全失效
- 之前方案(:class/:style/v-if/)都只能影响 slot 内部,ArkUI 不响应
- 新方案:slot 外包一层 view 绑定动态 key,数据加载后 300ms 自增 key
- key 变化强制 Vue 重建整个 slot 子树,完全绕过 ArkUI 响应式限制
- 还原之前无效的 mounted 延迟方案
2026-06-05 11:36:28 +08:00
cbbb1e0327 fix(harmony): 鸿蒙环境下延迟 mescroll 初始数据加载,确保 DOM 渲染就绪
- 根因:鸿蒙 ArkUI DOM 初始化管线比 Vue 响应式系统慢
- mescroll mounted 时立即触发 resetUpScroll,数据返回时 ArkUI 尚未完全就绪
- 导致 goodsList 赋值后视图不更新,需点击排序等交互后才刷新
- 修复:MP-HARMONY 环境下延迟 400ms 再调用 resetUpScroll
- 不影响其他平台
2026-06-05 11:30:36 +08:00
1ab8a52c38 fix(harmony): 商品列表改用 :style 控制显示隐藏,修复鸿蒙下不显示问题
- 根因:.goods-list 默认 display:none,依赖 .show class 显示
- 鸿蒙 ArkUI 对 :class 动态绑定支持不完善,isList=true 时 .show 未正确添加
- 改用 :style 内联样式控制 display,优先级高于 class 且更可靠
- 同时把 v-for key 从 index 改为 item.id 提升 diff 准确性
- 移除之前无效的 renderKey 强制刷新逻辑
2026-06-05 11:19:05 +08:00
6027f0d6de docs: 更新文档中的URL为HTTPS 2026-06-05 11:10:22 +08:00
048305eb23 fix(harmony): 鸿蒙环境下商品列表初始加载后强制触发视图刷新
- 鸿蒙 ArkUI 对 v-for 数组响应式更新支持不完善
- goodsList 赋值后视图不自动渲染,必须点击排序等操作后才显示
- 在 getGoodsList 数据赋值后,通过快速切换 isList 状态强制触发视图重计算
- 仅对 MP-HARMONY 环境生效,不影响其他平台
2026-06-05 11:03:18 +08:00
8f1eb1f5fe fix: 将 http URL 替换为 https 2026-06-05 10:58:00 +08:00
70cb01cfc0 fix: 修复i18n调用路径及资源链接协议
- 修复商品列表页 $lang 调用路径错误,移除多余的 'common' 前缀
- 将 mescroll 组件中的图片资源链接从 http 升级为 https
2026-06-05 10:41:23 +08:00
719d32b77b fix(harmony): 鸿蒙环境下隐藏 loading-cover 和 mescroll 上拉加载动画
- 鸿蒙 ArkUI 渲染引擎对 Vue 响应式条件渲染(v-if/v-show)支持不完善
- 导致 loading-cover 调用 hide() 后仍显示
- 导致 mescroll-uni 加载完成后 upLoadType 已变为0但视图不更新
- 通过条件编译 #ifdef MP-HARMONY 在鸿蒙环境下跳过这些组件的渲染
- 避免用户界面一直处于加载状态
2026-06-05 10:40:42 +08:00
fe6c000fc7 fix(login): 鸿蒙元服务环境隐藏协议勾选框
- 鸿蒙 ArkUI 渲染引擎对动态 class 绑定(含 :before 伪元素)支持不完善
- 协议勾选状态切换后视图不刷新
- 暂时通过条件编译 #ifndef MP-HARMONY 在非鸿蒙环境显示勾选框
- 鸿蒙环境下跳过协议勾选校验
2026-06-05 10:28:32 +08:00
d4c1e1d6a5 feat(i18n): 添加中文购买与咨询相关翻译 2026-06-05 09:20:06 +08:00
e9c679e1aa fix: 修复跳转及国际化文案 2026-06-05 09:19:57 +08:00
65b49fe4d5 fix(login): 修复多端适配及事件重复绑定问题
1. 修正微信小程序平台的条件编译标识
2. 为uniapp页面元素补充@tap事件,兼容多端点击事件规范
2026-06-04 17:28:24 +08:00
5a0c903346 refactor: 统一将微信小程序条件编译替换为全小程序平台
将项目中所有`MP-WEIXIN`条件编译标识替换为通用的`MP`,适配所有字节小程序平台,减少重复的平台特化代码。
2026-06-04 16:41:13 +08:00
6690788a17 chore: 更新域名并添加鸿蒙构建产物拷贝逻辑
1. 修改站点基础请求域名从xcx6到xcx2
2. 新增mp-harmony构建完成后自动拷贝产物到ascf_src目录的逻辑
3. 限制微信小程序专属分包加载插件仅在微信平台生效
4. 针对鸿蒙平台调整压缩配置,保留console用于调试
2026-06-04 15:43:04 +08:00
9b5275b6f6 style: 调整微信小程序平台适配条件并优化魔方组件逻辑
1.  将MP-WEIXIN平台适配改为通用MP平台适配
2.  重构diy-rubik-cube组件的数据处理逻辑:
    - 新增processedList存储处理后的列表数据
    - 提取初始化列表逻辑为initList方法
    - 新增对value属性的深度监听,动态更新列表
    - 将原list计算属性改为直接返回processedList
2026-06-04 15:02:52 +08:00
1abc53734b build: add pnpm lockfile and project dependencies
初始化项目依赖配置,添加jweixin-module业务依赖,以及dart-sass、terser-webpack-plugin、zion-uniapp-mp-load-package开发依赖,生成完整的pnpm锁定文件。
2026-06-04 14:46:42 +08:00
829444231c refactor(components-diy/diy-group): 重构组件数据处理逻辑
1. 替换原有的深拷贝方式为显式使用$util.deepClone
2. 拆分数据初始化和监听逻辑,新增processedData存储处理后的数据
3. 重构topNavColor计算属性,简化逻辑代码
4. 抽离组件数据处理为独立的processData方法
5. 优化diyDataArray计算属性的过滤和处理流程
2026-06-04 14:33:34 +08:00
ffd046fc0a fix(diy-group): add error catch for deep clone diyData
避免当diyData格式异常时导致页面崩溃,捕获序列化报错并打印日志
2026-06-04 13:48:17 +08:00
0f9647e7c5 refactor(diy-group): simplify topNavColor and setPagestyle logic
remove redundant null checks for diyData and diyGlobalData, streamline the conditional branches for better readability
2026-06-04 13:47:33 +08:00
23b5e91d11 stub-app-projects\mp-harmony\entry\src\main\resources 这个目录也要从git 仓库中删除 2026-06-04 10:35:42 +08:00
b8112e20d6 feat(mp-harmony): add PRIVACY_WINDOW permission for entry ability
新增隐私窗口权限配置,适配EntryAbility使用场景并设置为始终可用
2026-06-04 10:03:14 +08:00
31b22e7225 fix(diy-group): 修复顶部导航颜色和页面样式计算的空值问题
为topNavColor计算属性增加diyData和global字段的空值校验,防止访问undefined属性报错;同时在setPagestyle方法开头增加diyGlobalData的空值判断,避免遍历失败
2026-06-04 10:02:54 +08:00
e86c5d874e 清理不需要git管理的文件 2026-06-04 09:35:10 +08:00
49479ea24e fix(config): 适配鸿蒙小程序的版本注入逻辑
扩展了site.js引入的平台范围,新增mp-harmony鸿蒙小程序的生产构建支持
2026-06-04 09:19:02 +08:00
0e409247cd chore: 清理pages_tool相关冗余文件并调整配置
1.  删除整个pages_tool编译构建目录下的所有冗余文件和配置
2.  更新站点uniacid为2482,移除diy-form对ns-newform的依赖
3.  调整多个组件json配置的字段顺序,移除页面中对ns-newform.pack.js的引用
2026-06-04 09:02:17 +08:00
0b06ad56dc feat(mp-harmony): 完善鸿蒙小程序项目适配与新增功能
1. 新增MP-HARMONY平台编译支持
2. 新增大量自定义组件、页面与工具页面
3. 调整站点配置与应用名称
4. 清理冗余静态资源与旧组件配置
2026-06-04 08:37:57 +08:00
a27925c24f 备份stub-app-projects 作为分发物 2026-06-03 11:47:59 +08:00
1b2a8f83c2 refactor: 优化webview页面和util.js中链接处理逻辑
将链接参数拼接逻辑移至util.js中处理,统一各端链接处理方式
2026-05-30 17:12:36 +08:00
81570dda30 fix(merch/detail): 滚动时立即隐藏滚动提示 2026-05-30 17:01:07 +08:00
db941673fc fix(merch/detail): 将滚动提示自动隐藏时间从3秒改为1.5秒 2026-05-30 17:00:09 +08:00
f58a6723de fix(merch/detail): 修复商户描述展开后滚动收起位置异常的问题
通过 key 强制重新渲染描述区域,重置滚动位置。合并重复的 toggleDesc 方法。

Sources:
- 61243b8 feat(merch/detail): add scroll hint for long product description
2026-05-30 16:56:16 +08:00
61243b8dd4 feat(merch/detail): add scroll hint for long product description
1. 新增商品详情长描述滚动提示组件,展开长描述时显示3秒
2. 调整描述文本容器底部内边距避免提示遮挡内容
3. 替换原有自动滚动动画为上下弹跳提示动画
4. 优化展开描述的逻辑,展开长文本时触发提示显示
2026-05-30 15:37:11 +08:00
b08d7a389b feat(merch/detail): 优化商品描述展示逻辑
1. 替换原有长按弹窗展示为内嵌展开收起功能
2. 长描述支持自动滚动动画
3. 新增展开收起提示按钮
4. 调整相关布局样式与层级
2026-05-30 15:15:54 +08:00
a1fc8f5955 style(common-payment): 移除微信小程序平台条件编译注释
移除了冗余的微信小程序平台专属代码包裹注释,清理页面布局代码结构
2026-05-30 14:20:23 +08:00
d3c34c3698 feat(store&bottom-nav): add package entry tab tracking logic
1. add packageEntryTab state and mutation in vuex store
2. extract and track current/previous page's matching tab entry
3. update package entry tab state via store commit instead of local variable
4. optimize tab url parsing by stripping query parameters
2026-05-30 14:12:01 +08:00
6410257a25 fix(diy-bottom-nav): 优化底部导航栏高亮逻辑,修复分包场景下的激活判断问题
1. 新增decodeEntity工具函数处理URL实体编码
2. 新增packageEntryTab状态追踪分包入口Tab
3. 重构checkTabBarActive方法,支持动态tabBar配置和分包场景判断
4. 优化路由更新和跳转逻辑,适配多分包页面的导航高亮
2026-05-30 11:59:26 +08:00
f836254381 docs(i18n): add translations for get dynacode text
add Chinese and English translation entries for dynamic code acquisition text
2026-05-30 10:06:43 +08:00
21252dc2ad style(merch/detail): 修复非H5端头部排版偏移问题
仅在非H5平台保留top:0样式,避免H5端出现布局异常
2026-05-29 15:46:26 +08:00
cc2ca14133 chore: 修改manifest.json中的应用名称为加载中...
将小程序初始显示名称临时改为加载中占位文本
2026-05-29 15:31:20 +08:00
dc4b3df715 fix(merch/detail): 防止重复初始化头部高度
1. 新增headerHeightInited状态避免重复调用initHeaderHeight
2. 在initHeaderHeight中增加商品名称校验防止无效执行
3. 仅在页面首次获取商品数据后初始化头部高度
2026-05-29 14:58:08 +08:00
6745f2093e refactor(merch/detail): 优化商品详情页头部高度初始化逻辑
1. 移除冗余的headerHeightInited状态和监听逻辑
2. 提取获取商品详情的逻辑为单独getMerch方法
3. 移除initHeaderHeight的延迟定时器并修复top样式值
2026-05-29 14:47:58 +08:00
3781e54a32 fix(merch detail): fix header style and optimize list toggle
1. 修正商品详情页头部容器的样式选择器和优先级问题
2. 调整商品数据监听,改为监听商品描述而非整个merch对象
3. 给列表切换逻辑添加防抖处理,避免频繁切换触发过多渲染
4. 新增列表切换的防抖工具函数
2026-05-29 14:42:38 +08:00
1edda80d21 fix(merch/detail): 修复头部高度重复初始化的问题
添加headerHeightInited标记,避免merch数据更新时重复调用初始化方法
2026-05-29 14:35:52 +08:00
a443121426 style(merch detail page): adjust header wrap top position to 0
fix the layout offset of the merchandise detail page header area
2026-05-29 14:34:16 +08:00
5e5e5cb1d5 refactor(merch/detail): 清理冗余注释并调整商品详情布局结构
1. 移除搜索区域和筛选区域的冗余注释代码
2. 调整商品信息区域的DOM结构,新增merch-info-wrap容器统一布局
3. 修复筛选区域的点击事件绑定,将点击逻辑移到外层容器
2026-05-29 14:32:06 +08:00
2bd94a1e5a style(merch/detail): extract inline styles to class selectors
extract inline css styles from template and style block into reusable scoped class selectors, improve code readability and maintainability
2026-05-29 14:28:47 +08:00
58883b02f3 feat(merch/detail): add long press to show full merchant description
add longpress event handler to display full merch desc in a modal when triggered
2026-05-29 14:26:12 +08:00
92549b979e fix(promotion merch detail): 修复商品详情页下拉错位问题并添加商品描述省略
1.  添加商品描述文本的多行省略显示样式
2.  动态计算顶部header高度替代固定值,解决页面滚动错位问题
3.  监听merch数据变化重新计算头部高度
2026-05-29 14:23:38 +08:00
a929cfedb4 fix(js/list): add response code check for merch info request
优化商家信息接口请求的响应处理,增加返回码和数据有效性校验,避免异常数据赋值
2026-05-29 14:13:04 +08:00
abd6c122d5 style(merch/detail): 添加::v-deep修饰器修复样式穿透问题
修复uni-app中样式无法作用到子组件标签的问题,通过::v-deep正确穿透组件作用域
2026-05-29 14:05:04 +08:00
f7b1552239 fix: 修复网页标题设置逻辑,统一参数传递格式
1.  将enable_set_title的布尔判断改为数字1/0的格式,统一前后端参数传递规则
2.  重构导航栏标题更新逻辑,抽离为公共方法并监听title和enableSetTitle变化
3.  新增onShow钩子触发标题更新,修复页面重新显示时标题不刷新的问题
4.  补充控制台日志用于调试跳转链接参数
2026-05-29 10:55:51 +08:00
b5077b6a33 refactor(formdata): 重构导航栏标题设置逻辑
将导航栏标题设置提取为独立方法updateNavbarTitle,统一处理标题逻辑,同时将data中的title变量重命名为formTitle避免命名歧义
2026-05-29 10:28:17 +08:00
9f40ebc09e feat: add dynamic navigation bar title support for webview and form pages
1. add title and enableSetTitle data fields for webview and form pages
2. implement auto set navigation bar title when enabled
3. add URL normalize and query params append utilities
4. pass title and enable_set_title params across pages and external links
2026-05-29 09:56:05 +08:00
dfbcd0c9a5 fix(formdata): 适配多端页面标题设置逻辑
调整导航栏标题设置代码,兼容WebView内核场景,同时保留H5和小程序的标题设置能力
2026-05-29 08:56:20 +08:00
800cdbc805 fix(formdata): 修复H5端导航栏隐藏选择器失效的问题
将原先通过类名选择uni-page-head改为直接选择uni-page-head组件,适配框架组件渲染变化
2026-05-28 16:56:06 +08:00
8d350b24e5 fix(form): 优化webview场景下H5导航栏的隐藏逻辑
通过条件编译只在H5环境下隐藏导航栏,避免小程序webview
环境下出现导航栏空白区域
2026-05-28 16:51:50 +08:00
a6189a5f9e fix(webview&form): 适配小程序webview跳转场景
1. 给h5和小程序端webview页面分别处理src参数,小程序端添加from=mp-webview参数
2. 新增isFromMpWebView标识,从跳转参数判断是否来自小程序webview
3. 非小程序webview场景下才设置页面导航栏标题
2026-05-28 16:07:38 +08:00
00870e4554 fix(vue.config&manifest): 修复路由base路径补全和校验逻辑
1.  调整manifest.json中router.base默认路径补全末尾斜杠
2.  在vue.config.js中增加base路径校验,自动补全缺失的末尾斜杠并打印警告
2026-05-28 14:36:23 +08:00
233093bebb refactor(form): 优化表单横幅图片的加载逻辑
将硬编码的横幅图片路径改为动态读取配置项,无配置时使用默认图片
2026-05-28 13:51:47 +08:00
d082baa06f style(style): adjust form tip and item top padding
统一调整表单提示和表单项的顶部内边距,优化页面排版间距
2026-05-28 13:46:51 +08:00
5ac7f3cf95 style: 调整表单相关样式并优化表单页面
1. 调整两个表单组件中名称字段的宽度为80vw
2. 调整必填标记的左侧外边距为8rpx
3. 优化formdata页面:添加横幅和表单提示功能,改用scss样式
4. 移除原有表单标题,改用动态提示文本
5. 补充部分调试日志并格式化代码格式
2026-05-28 11:57:57 +08:00
7526143c7d fix: 适配鸿蒙系统platform检测,解决鸿蒙版微信地图打不开的问题 2026-05-27 18:28:32 +08:00
4377ab919f build(webpack): adjust terser compression config
increase passes to 10 for better minification and add unsafe_math optimization
2026-05-27 18:19:40 +08:00
7c703ace4f docs: 更新README文档,补充鸿蒙小程序发布流程
1.  给原有章节标题增加了多余的井号修正为正确层级
2.  新增鸿蒙小程序发布完整流程章节
3.  更新版本特性和构建脚本说明,新增极限压缩优化、harmony.patch.js等内容
2026-05-27 18:15:55 +08:00
6837a5d934 fix: 修复 platform.js 与 http.js/util.js 之间 app_type/app_type_name 变量命名不匹配导致的 undefined 问题
- http.js: 修正 getPlatformInfo() 解构赋值为 appType/appTypeName
- http.js: 修复 headimgBase64、headimgPull、upload 方法中的变量引用
- util.js: 修正 upload 方法中的解构赋值和变量引用

此问题导致所有 API 请求中 app_type 和 app_type_name 参数均为 undefined
2026-05-27 17:18:22 +08:00
474b3a1091 refactor(http): rename platform info variables to camelCase
统一将平台信息相关变量从下划线命名改为驼峰命名,保持代码命名风格一致,同时修正请求参数中对应字段的赋值。
2026-05-27 17:15:21 +08:00
e4c905d278 feat(platform): add harmony mini program platform support
新增鸿蒙元服务小程序平台的识别与支持,补充平台映射表与中文名称配置,将harmony纳入小程序检测列表
2026-05-27 16:21:10 +08:00
fb133ced3c fix: 修复ZIP打包文件名前缀参数支持 2026-05-27 16:16:45 +08:00
da17911a9c feat: 添加鸿蒙元服务(mp-harmony)发行支持 2026-05-27 16:14:48 +08:00
988b36ebb4 build: 新增鸿蒙应用分发配置项
补充mp-harmony分发配置,设置鸿蒙应用的包名为com.atomicservice.6917577984608507983
2026-05-27 15:49:48 +08:00
fe2c53b43e fix: 修复swiper组件display-multiple-items大于swiper-item数量的渲染错误 2026-05-27 15:01:22 +08:00
9ed2acb8ae fix(ai-chat): 新增发送消息后自动滚动到底部
在加载聊天历史并插入加载提示消息后,立即调用滚动到底部方法,确保视图自动定位到最新消息位置
2026-05-26 15:23:31 +08:00
f36f9ce992 fix: AI智能客服首次使用显示fallbackWelcome的问题
1. 将 config.welcome 改为 config.welcome_info 匹配后端返回字段
2. 修复语言包路径错误:将 () 从 data() 移到 onLoad() 中
   - 原因:data() 执行时 getCurrentPages() 返回的是上一个页面
3. 添加调试日志用于排查 API 返回值
2026-05-26 15:02:35 +08:00
bca90e959e chore: 添加.logs目录到gitignore忽略列表
将日志目录加入忽略清单,避免提交日志文件
2026-05-26 14:47:14 +08:00
1615f9aafe chore(manifest): 调整router base路径
移除router base路径末尾多余的斜杠
2026-05-26 14:18:16 +08:00
1f6e260711 chore(config): add explosion-proof electrical config and switch default env to 2881
新增防爆电器的站点配置项,并将默认使用的环境配置切换为2881
2026-05-26 14:18:06 +08:00
dba637af38 chore(config): 整理并修正本地开发配置文件
1. 修复配置项缩进格式,统一代码风格
2. 新增145号项目配置
3. 调整默认启用的环境配置为145
4. 移除重复的本地测试配置项
2026-05-25 15:10:16 +08:00
68ed022c95 refactor(util): 替换isWeiXin实现为Platform模块方法
将原isWeiXin函数的实现替换为调用Platform.isWeiXin(),并标记为废弃
2026-05-25 14:43:34 +08:00
22a89013d0 refactor(platform): extract platform detection into separate module
移除各文件中重复的平台检测代码,统一封装到platform.js模块,添加缓存优化,支持多端平台检测、app_type和显示名称获取等能力,简化后续平台相关代码维护
2026-05-25 14:19:52 +08:00
107b5dd71b fix(webview): 修复url实体编码未解码的问题
1. 新增HTML实体解码工具函数decodeEntity
2. 在webview页面和跳转逻辑中调用该函数解码url参数
3. 统一格式化代码缩进风格
2026-05-25 14:06:17 +08:00
63789124f4 build(vue.config): 打包后自动打开目录增加错误捕获
新增try-catch捕获打开输出目录失败的异常,避免打包流程因目录打开失败中断,同时添加失败提示日志
2026-05-25 11:56:50 +08:00
a2dd7eb6f1 fix(handler.js): 完善HTML实体解码功能
修复文本节点仅替换&amp;的问题,新增完整HTML4实体解码支持,正确解析各类字符实体和数字实体
2026-05-25 11:42:14 +08:00
d0e74a0925 fix(mp-html): 完善html实体字符解码能力
新增html4标准实体映射表和通用解码函数,替换原有的仅替换&amp;的简单处理,支持更多实体字符和数字编码格式的解码
2026-05-25 11:38:28 +08:00
ccbce61755 fix(parser): 给decodeEntity添加amp默认参数为true
补充默认参数值,避免调用时未传参导致的逻辑异常
2026-05-25 11:31:30 +08:00
b827aba722 feat(privacy): add privacy check skip logic
新增隐私弹窗跳过校验的存储逻辑,通过临时缓存标记跳过隐私授权检查步骤
2026-05-25 11:11:33 +08:00
836eeb080e H5发行打包完成后自动打开输出目录 2026-05-20 11:32:06 +08:00
31c6914880 fix(ai-chat): 优化搜索定位 - 移除 doSearch 中多余的 $nextTick 包装,scroll-to 事件同步触发实现即时滚动定位 2026-05-19 15:59:58 +08:00
1ee402b581 fix(ai-chat-message): 修复搜索滚动定位和高亮动画的时序问题
1. 调整注释说明,补充scroll-into-view的微信小程序兼容场景
2. 移除冗余的定时器清除代码,新增延迟350ms触发搜索高亮动画,确保滚动先完成
3. 将原单次定时器改为嵌套定时器结构,正确管理动画状态和定时器资源
2026-05-19 15:53:17 +08:00
b1491ad69e 优化搜索定位反馈:修复Flash动画时序、添加脉冲动画、增加滚动留白、内联无结果提示 2026-05-19 14:55:40 +08:00
a954f9cc49 build(project): 关闭上传时携带sourcemap文件
修改project.config.json配置,将uploadWithSourceMap设为false,减少上传包体积并优化发布流程
2026-05-19 14:01:18 +08:00
3a310f0b98 refactor(js): rename and adjust login auth check function
调整了微信小程序端的登录授权判断逻辑,重命名函数并优化代码结构,补充其他平台的TODO注释
2026-05-19 11:56:21 +08:00
70fbdce641 feat(ai-chat): 优化历史消息时间显示与搜索定位
- 时间显示人性化:昨天/前天/跨年日期
- 搜索上下导航修复 scroll-into-view 触发逻辑
2026-05-19 09:28:29 +08:00
861c43a428 chore: 忽略 .codebuddy 目录 2026-05-18 15:59:40 +08:00
556ce9d132 refactor(ai-chat): 重构AI聊天国际化文件结构
- 将 ai-chat 语言文件从 ai/ 迁移至 ai-chat/ 目录
- 重构消息组件及多个子组件
2026-05-18 15:36:13 +08:00
5c56cfaaa7 chore: 添加 .codebuddy 到 .gitignore 2026-05-18 15:33:55 +08:00
6d704f7f5a refactor(ai-chat): 重构AI聊天消息组件 2026-05-18 11:18:56 +08:00
7580d8b763 feat(ai-chat): 添加聊天记录搜索与远程欢迎语功能 2026-05-16 17:34:24 +08:00
76afe5f433 feat(ai-chat): 支持长按复制消息内容 2026-05-16 11:08:46 +08:00
0bc1b5e90c feat(scripts): 在zip文件名中添加版本号前缀 2026-05-15 16:08:29 +08:00
9fc34ef467 feat(ai-service): 替换 anonymous 为随机访客唯一标识 getUserId()
- 新增 getUserId() 函数,已登录返回 memberId,未登录生成并持久化 guest_* 唯一ID
- 替换全部 10 处 'anonymous' 硬编码为 getUserId()
2026-05-15 09:22:48 +08:00
7a713e07e1 fix(h5): 修复H5 SSE流完成信号兼容和页面onShow时序
- sendHttpStream 兼容 data.event === 'done' 和嵌套 data.data 格式
- index.vue onShow 用  确保 ref 就绪后加载历史
- 组件 mounted 兜底调用 loadHistoryIfNeeded
- 历史消息映射添加 type:'text',兼容 msg.content 字段
- 去掉所有有帮助/没帮助按钮
2026-05-14 18:23:32 +08:00
bd778c0283 fix(ai-chat): 修复历史记录加载、WebSocket长连接、服务端消息格式兼容
- 修复 WebSocket message_end 未收到问题:兼容 data.event === 'done' + data.data.conversation_id 嵌套格式
- 修复子组件 onShow/onUnload 不触发:移到页面 index.vue 的页面生命周期中
- 修复 loadHistoryIfNeeded 被重复 methods 块覆盖:合并到同一 methods 块
- 修复历史消息映射字段:msg.query → msg.content,添加 type:'text'
- 去掉所有有帮助/没帮助按钮
- CONVERSATION_KEY 改为统一导出常量
- WebSocket 长连接重构 + #ifdef 环境隔离
2026-05-14 17:50:48 +08:00
fed3962965 fix(ai-service): WebSocket长连接重构 + 环境隔离 + this上下文修复
- 改为长连接模式:首次建立WebSocket后保持不断开,后续复用
- 添加 #ifdef MP-WEIXIN / #ifdef H5 环境隔离
- 修复 ensureWebSocketConnected 中 .bind(this) 导致 this 为 undefined 的问题
- 组件 onUnload 中调用 disconnectWebSocket() 断开连接
2026-05-14 17:04:28 +08:00
6de74a3baf fix(ai-service): 修复WebSocket域名正则丢弃端口、timeout未定义问题
- 正则 /^(?:https?:\/\/|wss?:\/\/)([^\/\s:?#]+(?::\d+)?)/ 正确捕获host:port
- 添加 let timeout = null 声明,修复 ReferenceError
2026-05-14 15:21:45 +08:00
a4f2823e75 feat(scripts): 细化zip文件名时间戳至秒 2026-05-14 08:50:48 +08:00
cd82ba2f27 fix: 统一 calc() 精度避免小米微信小程序子像素舍入差异
- diy-video-list.vue, diy-goods-list.vue: 删除重复的 3n+3 规则
  (33.33% 精度低于 33.3333333%,且与 3n 规则匹配同一组元素)
- diy-fenxiao-goods-list.vue: 两列布局统一 calc(50% - 10rpx),
  消除第2项 1rpx 的减数差异
2026-05-14 08:42:12 +08:00
698d419525 fix(diy-rubik-cube): 小米微信小程序魔方组件布局修复
- 取消注释 .template-left/.template-right 的 width: 50%,修复小米
  XWeb 引擎 flex-wrap 子像素舍入差异导致的布局错乱
- 重构 calcRowOneLeftOfTwoRight:将 'px' 追加移出主循环,统一在
  第二层循环处理,避免中途字符串转换
- 清理 calcRowOneLeftOfOneTopOfTwoBottom 中的无效空值表达式
- 优化 row1-lt-of2-rt 模板右侧最后一项条件判断 marginBottom
2026-05-13 18:23:56 +08:00
a252d42b62 fix(ai-chat): 消除键盘弹出时输入框闪烁
- 键盘垫高层不再使用 v-if 突然插入,改为始终存在(高度默认为0)
- 添加 CSS transition: height 0.25s ease 平滑过渡动画
2026-05-13 16:38:33 +08:00
69466f410c fix(ai-chat): 修复聊天页面键盘弹出时导航栏上移、输入框不可见、间距问题
- 自定义导航栏 position:absolute 固定在顶部,不随键盘上移
- textarea 设置 adjust-position=false,阻止系统上推页面
- 输入框后方加 spacer 垫高层,键盘弹出时将输入框推至键盘上方
- chat-content 根据平台设置不同 top 值(MP:0 / H5:44px)
- 去掉输入框多余的安全区域内边距
- scroll-view 底部 padding 随键盘高度动态调整
2026-05-13 16:01:15 +08:00
39245dfcac fix(ai-chat): 修复输入框定位及滚动问题并更新客服名称 2026-05-13 14:08:58 +08:00
80b18cee0f feat(ai-chat): 优化加载状态动画与流式消息过渡 2026-05-13 09:19:38 +08:00
b2688dc8a1 fix(ai-chat): 修复历史消息加载逻辑及超时问题 2026-05-13 09:00:20 +08:00
d5ca77e2d8 fix(ai-chat): 跳过健康检查避免服务误判 2026-05-13 08:40:01 +08:00
e789ab2ca3 fix(H5): 从 package.json 读取 UNI_APP_DOMAIN 兜底,确保 H5 发行域名正常注入 2026-05-12 11:39:43 +08:00
5e83771193 chore: 保留H5打包后的源目录 2026-05-12 09:59:43 +08:00
0d18041037 refactor: 使用 Intl.DateTimeFormat 生成时间戳 2026-05-12 08:48:55 +08:00
875cf0b428 feat(ai-chat): 增强Markdown解析及调整聊天气泡布局 2026-05-12 08:30:26 +08:00
e16402c9c1 fix(ai): 修复WebSocket重复回调及意外关闭问题 2026-05-11 17:14:26 +08:00
dee2887026 docs: 更新 readme 反映 H5 自动 ZIP 打包和统一配置方式 2026-05-11 11:56:37 +08:00
6033cc2fa0 feat(vue.config): H5 生产构建后自动打包 ZIP 2026-05-11 10:59:36 +08:00
c1fbabe07b refactor(vue.config): 简化UNI_OUTPUT_DIR逻辑,支持通用H5脚本+读取manifest base 2026-05-11 10:54:36 +08:00
221ef7bb6d refactor: 域名移至package.json脚本env中,config.js零改动 2026-05-11 10:29:33 +08:00
55c1e80ed7 refactor: 用 UNI_SCRIPT + DOMAIN_MAP 替代 #ifdef 环境常量 2026-05-11 10:27:33 +08:00
79202c4542 docs: 更新 package.json 和 readme.md 反映最新构建流程 2026-05-11 10:18:47 +08:00
3bff91e421 refactor: 统一版本信息注入方式
- feat(vue.config): 新增 VersionInjectPlugin,在 webpack emit 钩子中内联注入 __app_version 到 vendor.js / index.html
- refactor(scripts): mp-weixin.patch.js 精简为仅拷贝 site.js + ZIP 打包
- feat(index): 首页连击5次显示构建版本信息
- fix(util): 修复 openWxWorkServiceChat fail 回调语法错误
2026-05-11 09:36:57 +08:00
979384c2d6 feat(index): 新增固定版本触发区,标题不可见时也可连击5次查看版本 2026-05-09 17:27:53 +08:00
504e5322fb fix(scripts): vendor.js注入改为先清理旧行再注入,确保幂等 2026-05-09 17:21:02 +08:00
25fc0a59a8 fix(scripts): version.json改为生成version.js(CommonJS),兼容微信小程序require限制 2026-05-09 17:19:17 +08:00
34e27d0621 feat(index): 首页标题连击5次显示构建版本信息\nfix(scripts): explorer使用spawn避免GUI进程阻塞\nfix(index): version.json运行时读取,不依赖构建时require 2026-05-09 17:14:51 +08:00
913fc90176 feat(scripts): 构建时自动生成 version.json 并注入到 vendor.js 2026-05-09 17:04:12 +08:00
c1bac6d9e8 feat(scripts): ZIP文件名使用Git提交ID替换时间戳 2026-05-09 17:00:38 +08:00
31382a2388 refactor(util): 增加空回调函数 2026-05-09 11:16:30 +08:00
d009077183 update 2026-05-09 09:24:25 +08:00
133eb29a71 Merge branch 'dev/1.0' 2026-05-09 09:22:10 +08:00
a2616c9757 chore: 修改路由base路径为/hwappx/common/ 2026-05-09 09:17:38 +08:00
fb47da8095 refactor(privacy-popup): 优化隐私弹窗逻辑结构 2026-05-09 08:58:48 +08:00
37958cbe39 feat(privacy): 移除隐私弹窗配置检查逻辑 2026-05-09 08:47:24 +08:00
9f53f147ee chore: 移除所有调试日志 2026-05-08 16:09:19 +08:00
2342a14f2e fix(mp-weixin): 将 import 语句改为 require 2026-05-07 17:36:43 +08:00
36b0c22e47 fix: 修复二维码长按识别属性 2026-05-07 16:38:53 +08:00
4a52b9c229 fix(util): 去除URL中的双斜杠 2026-05-07 16:25:37 +08:00
9ec90a906f perf(diy-tab): optimize tab rendering with v-if 2026-05-07 16:14:28 +08:00
e125a5f39c chore: 添加修复长按菜单语法错误的脚本 2026-05-07 15:43:57 +08:00
8c0ec46dd8 style: 统一图片组件属性格式 2026-05-07 15:43:33 +08:00
b65ec35d3c chore: 更新 appid 2026-05-07 15:13:06 +08:00
d113d6125b feat(components): 在图片组件中添加长按显示菜单功能 2026-05-07 15:12:59 +08:00
2f24661cd9 fix(ai-service): 统一用户标识默认值为anonymous 2026-05-06 11:26:10 +08:00
50908a274b refactor(ai-service): 使用getUniacid方法统一获取uniacid 2026-05-06 11:13:08 +08:00
9e68562de5 chore(ai): 增加调试日志输出 2026-05-06 10:53:52 +08:00
8e5561c2a7 refactor(ai-service): 提取域名配置参数以减少重复代码 2026-04-30 16:39:55 +08:00
8d5c543a4f chore:扩大按钮【】 2026-04-28 17:51:54 +08:00
cf411407dd chore:名片可以分享了 2026-04-28 17:35:40 +08:00
86e4be302b chore:商品分类可以分享了 2026-04-28 11:31:32 +08:00
2fd06796e1 chore:加了输入框扩大按钮 2026-04-28 09:59:52 +08:00
60c51e551a chore:修改表情位置 2026-04-28 09:12:15 +08:00
d0d3ac47c6 chore:修改表情位置 2026-04-28 08:59:34 +08:00
af677f6565 chore:资源详情改为商品详情 2026-04-25 16:53:40 +08:00
f889efeb16 chore: 2026-04-25 16:45:41 +08:00
d026bb6180 chore:增加一个后台控制首页弹出的隐私权限 2026-04-25 16:15:17 +08:00
82b856f5d9 chore:表情的布局改为横板 2026-04-25 14:36:31 +08:00
7f33b6948a chore:min-height: 300px; 替换成 min-height: 0px; 2026-04-25 14:26:48 +08:00
3489b89a0b chore:智能客服加了表情 2026-04-25 14:15:03 +08:00
dc4f2769f9 chore:资源详情里的立即咨询可以跳转到智能客服 2026-04-25 11:58:03 +08:00
5cf87e4d56 chore:资源详情的背景设改为绿色 2026-04-25 11:27:32 +08:00
c9ca63cff5 chore:联系我们改为立即质询 2026-04-25 11:09:47 +08:00
a6072f4895 chore: 2026-04-25 10:22:27 +08:00
38947ddc62 chore:立即咨询点击会弹出对话框 2026-04-25 10:09:38 +08:00
cfe83ada38 chore:点击商品分类中的立即咨询不要跳转到智能客服,跳转到资源详情页面 2026-04-25 09:59:45 +08:00
1e9e0ffea8 chore:资源详情智能客服按钮同步智能客服 2026-04-25 09:50:45 +08:00
28acdfb621 chore:红色背景收一些 2026-04-25 09:29:23 +08:00
ad9f1c495b chore:联系我们改为立即质询 2026-04-25 09:22:33 +08:00
7c2a7468e7 chore:调整红色背景 2026-04-25 09:03:13 +08:00
b2051dcf92 chore:立即质询背景改红色 2026-04-25 08:48:06 +08:00
e3c86de84a chore:删除红色的立即质询 2026-04-25 08:42:03 +08:00
6e0eb5d4f3 chore:询底价改为立即咨询 2026-04-25 08:38:15 +08:00
9d186ff094 chore:发送字体按钮调整变大 2026-04-24 16:49:01 +08:00
8611ec4dc3 chore:发送按钮改为微信的发送按钮 2026-04-24 16:38:29 +08:00
89bfd94a07 chore:上传image-config.js 2026-04-24 15:46:42 +08:00
5cf8b7b467 chore:发送按钮调整变大 2026-04-23 15:24:32 +08:00
2cc0162435 chore:输入框不被遮挡了 2026-04-22 11:59:58 +08:00
d8e75a0c9e chore: 2026-04-21 14:15:46 +08:00
8af3c0ccb9 chore:微信小程序真机版本可以运行,微信小程序客服图标显示正常 2026-04-20 17:50:37 +08:00
d8b78168a8 chore:改了头像的地址 2026-04-20 15:44:58 +08:00
7675e8e04d chore: 2026-04-20 09:52:27 +08:00
88d05048a6 chore:长按图片可以识别图中二维码 2026-04-20 09:36:08 +08:00
28a92c0635 chore:ai-service.js 的代码url: 'wss://dev.aigc-quickapp.com/ws/aikefu',被替换 2026-04-18 11:36:18 +08:00
b5a47b8b4e chore:聊天页面的我和时间换位置 2026-04-17 16:03:30 +08:00
4f99e8b5f2 chore:H5的发送按钮变成正圆形 2026-04-17 15:18:31 +08:00
87fc49146c chore:时间居中 2026-04-17 14:19:43 +08:00
826fcfb024 chore:时间和智能助手在同一水平线上 2026-04-17 11:49:33 +08:00
7174d87b79 chore:用户的气泡中商品名称,商品ID,价格都左对齐 2026-04-17 10:13:07 +08:00
4bc747cd9c chore:增加了用户默认头像,自定义头像 2026-04-17 09:48:46 +08:00
e046868665 chore:用户点击自己头像可以自定义头像 2026-04-17 09:21:10 +08:00
19c3ec4f9f chore:小程序输入框向下移动 2026-04-17 08:44:01 +08:00
ffbc15929d chore:智能客服的历史时间回复正常 2026-04-16 14:03:37 +08:00
524280d816 chore:智能助手加了时间 2026-04-16 11:00:50 +08:00
6e736e0733 chore:资源详情页面的智能客服头像变为圆形 2026-04-16 10:02:50 +08:00
4891566793 chore:智能客服改了头像 2026-04-16 09:34:56 +08:00
b02f5fbc21 chore:智能客服换了头像 2026-04-15 17:46:06 +08:00
4f5a300afa chore:H5的智能客服聊天页面上面导航栏自定义的删除 2026-04-15 17:18:22 +08:00
aae6e76797 chore:智能客服聊天不乱窜了 2026-04-15 10:23:43 +08:00
3162d6a9f2 chore:H5的智能客服聊天正常 2026-04-15 09:08:10 +08:00
8010ac45a6 chore:智能客服图标换了 2026-04-14 17:29:17 +08:00
baebba4cef chore:导航栏删除在线客服 2026-04-14 16:30:42 +08:00
1be7155fe8 chore:智能客服的头像换了 2026-04-14 09:42:09 +08:00
611c0b930b chore:删除喜欢不喜欢有帮助没帮助 2026-04-13 17:29:13 +08:00
ec1903519d chore:用户提问和客服回答可以看见了 2026-04-13 09:30:08 +08:00
b1953a020d chore:喜欢不喜欢和👍水平 2026-04-10 15:10:41 +08:00
3ce26322e0 chore: 2026-04-09 16:04:11 +08:00
4e480d35df Merge branch 'Branch_release/v1.4.1' 2026-04-09 15:54:51 +08:00
9c8ebf8d74 Merge branch 'main' of https://git.aigc-quickapp.com/Uniapp/lucky_shop 2026-04-08 15:02:08 +08:00
e19fef785f chore:改了commom 2026-04-08 14:39:23 +08:00
92ae114c5c chore: 2026-04-08 11:47:07 +08:00
b25c366a5b chore:增加了弹窗用户隐私 2026-04-08 11:37:29 +08:00
588ec60948 chore:发送按钮向上调动 2026-04-08 10:10:47 +08:00
962ea124fa chore:退出聊天界面后,在进入聊天页面后没有多余的气泡 2026-04-08 09:14:57 +08:00
0ca0fe3b0d chore:修改了客服样式 2026-04-07 15:21:29 +08:00
cef2b6e02e chore:客服回答不重复 2026-04-07 15:10:26 +08:00
e018f9a8b9 chore:修改H5商品价格样式 2026-03-31 09:38:16 +08:00
def8a6cf6f chore:横竖屏 2026-03-30 14:49:24 +08:00
857f295923 chore:H5和小程序都可以自己分辨横竖屏 2026-03-28 17:38:26 +08:00
50ee885b74 chore:微信小程序实现竖屏是竖屏,横屏是横屏 2026-03-25 14:44:25 +08:00
410f248510 chore:H5视频改比例 2026-03-25 09:39:48 +08:00
ba5fcfaab1 chore:微信小程序的视频改为竖屏播放 2026-03-24 16:43:00 +08:00
5a46bb8d69 chore:智能客服回答不重复 2026-03-19 14:26:32 +08:00
e33ad16d10 chore:商品详情页面右上角有跳转到智能客服 2026-03-17 09:53:24 +08:00
d8ba7ace0f chore:跳转智能客服的更多详情按钮放到商品页面里面 2026-03-16 17:21:33 +08:00
875072bb68 chore:商品可以分享给智能客服进行解答 2026-03-14 10:53:55 +08:00
0912b9b031 chore:智能客服加了商品的图标 2026-03-13 16:41:00 +08:00
7ffe4acc0f chore:隐藏了更多功能,录音图标 2026-03-13 13:57:24 +08:00
4bcf0cbd2d chore:可以正常清空聊天记录 2026-03-12 18:29:11 +08:00
fdf85dfec7 chore:更换头像正常 2026-03-12 18:25:12 +08:00
1d62b37060 chore:头像功能从相册选择功能正常了 2026-03-12 15:09:27 +08:00
4ad93ceace refactor: 将视频标题样式绑定从对象改为数组 2026-02-07 18:11:42 +08:00
294856d9ef Merge branch 'test/diy-tabs' into dev/1.0 2026-02-07 17:53:30 +08:00
ba2c7d6d64 Revert "chore:点击中英文按钮不跳到‘我的’了"
This reverts commit 19a53ef414.
2026-02-07 17:51:10 +08:00
ec9e76fda7 chore:改了中英文模式 2026-02-07 16:53:40 +08:00
5dba8071e4 refactor(diy-tab): 统一样式绑定语法为数组形式
将模板中的样式绑定从对象展开语法改为数组形式,保持代码风格一致
2026-02-07 16:16:43 +08:00
19a53ef414 chore:点击中英文按钮不跳到‘我的’了 2026-02-07 16:10:55 +08:00
e943b11c8f fix(组件): 修复tab组件中子组件moduleIndex冲突问题
为tab组件中的子组件添加tabIndex前缀,避免不同tab页中子组件的moduleIndex冲突
2026-02-07 15:57:49 +08:00
e9db54980e refactor(diy-tab): 使用模板字符串和可选链优化key生成逻辑 2026-02-07 14:59:26 +08:00
3ddcc665b8 refactor(diy-tab): 统一使用生成函数获取tab和panel的key
使用getTabKey和getPanelKey方法统一生成key,提高代码可维护性
2026-02-07 14:11:51 +08:00
a981c02baf chore:智能客服页面右上角改成齿轮图标,更多功能图标改为(...) 2026-02-07 13:59:43 +08:00
1c3f759b35 feat: 为DIY标签组件添加可配置的动画效果 2026-02-07 11:41:59 +08:00
bb58866192 feat: 为标签组件添加悬停动画和对齐选项 2026-02-07 11:34:45 +08:00
069b3c2c07 feat: 为DIY标签页组件添加滚动容器和样式 2026-02-06 17:55:44 +08:00
c6fd13956a chore:H5和微信小程序的第三方客服悬浮按钮应该会显示 👤 2026-02-06 17:49:48 +08:00
a489e24988 chore:改了企业微信客服,智能客服的悬浮按钮 2026-02-06 17:18:58 +08:00
6897fc631b feat: 重构DIY标签页组件,支持多种布局和样式配置 2026-02-06 16:47:32 +08:00
6d23a64aef chore:智能客服的页面全部显示出来 2026-02-06 16:30:33 +08:00
f34533b0c7 chore:进入智能客服的页面加了智能客服的头像 2026-02-06 16:08:50 +08:00
72c74f44f0 chore:删除弹出的框的一个叉 2026-02-06 16:02:11 +08:00
7f3d9c0f10 chore:将更改头像和昵称的按钮放在...的设置中 2026-02-06 15:56:00 +08:00
37f95e7267 chore:改了客服的图标 2026-02-05 18:30:16 +08:00
d3c630e860 chore:后台点击什么,页面显示什么 2026-02-05 16:58:54 +08:00
c5b57cedeb chore:后台点击不启用,H5和微信小程序不显示 2026-02-05 16:34:33 +08:00
bf24746a7c chore;更改了客服和中英文按钮的顺序 2026-02-05 10:14:27 +08:00
5ff2925ba1 chore: 2026-02-05 09:56:37 +08:00
3dc81e7f53 chore:优化了hover 2026-02-05 09:50:36 +08:00
0417c5c5ed chore:优化了hover 2026-02-05 09:27:43 +08:00
db26a85c8b chore:商品,名片,我的都能正常跳转了 2026-02-04 17:09:57 +08:00
54c39259a7 chore:代码合并,整理功能 2026-02-02 18:04:59 +08:00
15361211b1 Merge pull request 'tjh/merge' (#3) from tjh/merge into dev/1.0
Reviewed-on: #3
2026-02-02 09:52:19 +00:00
e301ddc6ec chore:微信小程序标签栏点击可以跳转 2026-01-31 17:04:50 +08:00
a560ad4a5d chore:后台点击什么页面就显示什么 2026-01-31 10:24:12 +08:00
7f7a18803f chore:智能客服正常运行 2026-01-31 10:06:59 +08:00
42563d7184 chore:改了pages-tool/ai-chat/ai-chat-message.vue 2026-01-31 09:47:41 +08:00
14a903f42a chore:改了components/chat-message/chat-message.vue 2026-01-31 09:44:05 +08:00
c9f8614927 chore:改了common/js/lang.js 2026-01-31 09:23:36 +08:00
fe9303bf4c chore:改了store/index.js 2026-01-31 09:20:31 +08:00
e4dfd0ae11 chore:改了project.config.json 2026-01-31 09:17:57 +08:00
7037d0b083 chore:改了pages-tool/ai-chat/index.vue 2026-01-31 09:14:00 +08:00
e8a79bd245 chore:改了golbalconfig.js 2026-01-31 09:11:00 +08:00
047cf765da chore:改了pages.json 2026-01-31 09:07:48 +08:00
3a30b0817d chore:替换了pages/index/index.vue 2026-01-31 09:03:58 +08:00
a464a8731f chore:替换了customer-service.js 2026-01-31 08:59:30 +08:00
7599a80943 chore:替换了ai-service.js 2026-01-31 08:55:57 +08:00
992a01cc76 chore:替了chat-message.vue 2026-01-31 08:52:55 +08:00
dd09c66215 chore:替了hover 2026-01-31 08:48:18 +08:00
738 changed files with 71842 additions and 12329 deletions

View File

@@ -0,0 +1,155 @@
---
name: "OPSX: Apply"
description: Implement tasks from an OpenSpec change (Experimental)
category: Workflow
tags: [workflow, artifacts, experimental]
---
Implement tasks from an OpenSpec change.
**Input**: Optionally specify a change name (e.g., `/opsx:apply add-auth`). If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
**Steps**
1. **Select the change**
If a name is provided, use it. Otherwise:
- Infer from conversation context if the user mentioned a change
- Auto-select if only one active change exists
- If ambiguous, run `openspec list --json` to get available changes and use the **AskUserQuestion tool** to let the user select
Always announce: "Using change: <name>" and how to override (e.g., `/opsx:apply <other>`).
2. **Check status to understand the schema**
```bash
openspec status --change "<name>" --json
```
Parse the JSON to understand:
- `schemaName`: The workflow being used (e.g., "spec-driven")
- `planningHome`, `changeRoot`, and `actionContext`: planning scope and edit constraints
- Which artifact contains the tasks (typically "tasks" for spec-driven, check status for others)
3. **Get apply instructions**
```bash
openspec instructions apply --change "<name>" --json
```
This returns:
- `contextFiles`: artifact ID -> array of concrete file paths (varies by schema)
- Progress (total, complete, remaining)
- Task list with status
- Dynamic instruction based on current state
**Handle states:**
- If `state: "blocked"` (missing artifacts): show message, suggest using `/opsx:continue`
- If `state: "all_done"`: congratulate, suggest archive
- Otherwise: proceed to implementation
**Workspace guard:** If status JSON reports `actionContext.mode: "workspace-planning"` and `allowedEditRoots` is empty, explain that full workspace apply is not supported in this slice. Treat linked repos and folders as read-only context, ask the user to select an affected area through an explicit implementation workflow, and STOP before editing files.
4. **Read context files**
Read every file path listed under `contextFiles` from the apply instructions output.
The files depend on the schema being used:
- **spec-driven**: proposal, specs, design, tasks
- Other schemas: follow the contextFiles from CLI output
5. **Show current progress**
Display:
- Schema being used
- Progress: "N/M tasks complete"
- Remaining tasks overview
- Dynamic instruction from CLI
6. **Implement tasks (loop until done or blocked)**
For each pending task:
- Show which task is being worked on
- Make the code changes required
- Keep changes minimal and focused
- Mark task complete in the tasks file: `- [ ]` → `- [x]`
- Continue to next task
**Pause if:**
- Task is unclear → ask for clarification
- Implementation reveals a design issue → suggest updating artifacts
- Error or blocker encountered → report and wait for guidance
- User interrupts
7. **On completion or pause, show status**
Display:
- Tasks completed this session
- Overall progress: "N/M tasks complete"
- If all done: suggest archive
- If paused: explain why and wait for guidance
**Output During Implementation**
```
## Implementing: <change-name> (schema: <schema-name>)
Working on task 3/7: <task description>
[...implementation happening...]
✓ Task complete
Working on task 4/7: <task description>
[...implementation happening...]
✓ Task complete
```
**Output On Completion**
```
## Implementation Complete
**Change:** <change-name>
**Schema:** <schema-name>
**Progress:** 7/7 tasks complete ✓
### Completed This Session
- [x] Task 1
- [x] Task 2
...
All tasks complete! You can archive this change with `/opsx:archive`.
```
**Output On Pause (Issue Encountered)**
```
## Implementation Paused
**Change:** <change-name>
**Schema:** <schema-name>
**Progress:** 4/7 tasks complete
### Issue Encountered
<description of the issue>
**Options:**
1. <option 1>
2. <option 2>
3. Other approach
What would you like to do?
```
**Guardrails**
- Keep going through tasks until done or blocked
- Always read context files before starting (from the apply instructions output)
- If task is ambiguous, pause and ask before implementing
- If implementation reveals issues, pause and suggest artifact updates
- Keep code changes minimal and scoped to each task
- Update task checkbox immediately after completing each task
- Pause on errors, blockers, or unclear requirements - don't guess
- Use contextFiles from CLI output, don't assume specific file names
**Fluid Workflow Integration**
This skill supports the "actions on a change" model:
- **Can be invoked anytime**: Before all artifacts are done (if tasks exist), after partial implementation, interleaved with other actions
- **Allows artifact updates**: If implementation reveals design issues, suggest updating artifacts - not phase-locked, work fluidly

View File

@@ -0,0 +1,160 @@
---
name: "OPSX: Archive"
description: Archive a completed change in the experimental workflow
category: Workflow
tags: [workflow, archive, experimental]
---
Archive a completed change in the experimental workflow.
**Input**: Optionally specify a change name after `/opsx:archive` (e.g., `/opsx:archive add-auth`). If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
**Steps**
1. **If no change name provided, prompt for selection**
Run `openspec list --json` to get available changes. Use the **AskUserQuestion tool** to let the user select.
Show only active changes (not already archived).
Include the schema used for each change if available.
**IMPORTANT**: Do NOT guess or auto-select a change. Always let the user choose.
2. **Check artifact completion status**
Run `openspec status --change "<name>" --json` to check artifact completion.
Parse the JSON to understand:
- `schemaName`: The workflow being used
- `planningHome`, `changeRoot`, `artifactPaths`, and `actionContext`: path and scope context
- `artifacts`: List of artifacts with their status (`done` or other)
If status reports `actionContext.mode: "workspace-planning"`, explain that workspace archive is not supported in this slice and STOP. Do not move workspace changes into repo-local archives or edit linked repos.
**If any artifacts are not `done`:**
- Display warning listing incomplete artifacts
- Prompt user for confirmation to continue
- Proceed if user confirms
3. **Check task completion status**
Read the tasks file (typically `tasks.md`) to check for incomplete tasks.
Count tasks marked with `- [ ]` (incomplete) vs `- [x]` (complete).
**If incomplete tasks found:**
- Display warning showing count of incomplete tasks
- Prompt user for confirmation to continue
- Proceed if user confirms
**If no tasks file exists:** Proceed without task-related warning.
4. **Assess delta spec sync state**
Use `artifactPaths.specs.existingOutputPaths` from status JSON to check for delta specs. If none exist, proceed without sync prompt.
**If delta specs exist:**
- Compare each delta spec with its corresponding main spec at `openspec/specs/<capability>/spec.md`
- Determine what changes would be applied (adds, modifications, removals, renames)
- Show a combined summary before prompting
**Prompt options:**
- If changes needed: "Sync now (recommended)", "Archive without syncing"
- If already synced: "Archive now", "Sync anyway", "Cancel"
If user chooses sync, use Task tool (subagent_type: "general-purpose", prompt: "Use Skill tool to invoke openspec-sync-specs for change '<name>'. Delta spec analysis: <include the analyzed delta spec summary>"). Proceed to archive regardless of choice.
5. **Perform the archive**
Create an `archive` directory under `planningHome.changesDir` if it doesn't exist:
```bash
mkdir -p "<planningHome.changesDir>/archive"
```
Generate target name using current date: `YYYY-MM-DD-<change-name>`
**Check if target already exists:**
- If yes: Fail with error, suggest renaming existing archive or using different date
- If no: Move `changeRoot` to the archive directory
```bash
mv "<changeRoot>" "<planningHome.changesDir>/archive/YYYY-MM-DD-<name>"
```
6. **Display summary**
Show archive completion summary including:
- Change name
- Schema that was used
- Archive location
- Spec sync status (synced / sync skipped / no delta specs)
- Note about any warnings (incomplete artifacts/tasks)
**Output On Success**
```
## Archive Complete
**Change:** <change-name>
**Schema:** <schema-name>
**Archived to:** the archive path derived from `planningHome.changesDir`/YYYY-MM-DD-<name>/
**Specs:** ✓ Synced to main specs
All artifacts complete. All tasks complete.
```
**Output On Success (No Delta Specs)**
```
## Archive Complete
**Change:** <change-name>
**Schema:** <schema-name>
**Archived to:** the archive path derived from `planningHome.changesDir`/YYYY-MM-DD-<name>/
**Specs:** No delta specs
All artifacts complete. All tasks complete.
```
**Output On Success With Warnings**
```
## Archive Complete (with warnings)
**Change:** <change-name>
**Schema:** <schema-name>
**Archived to:** the archive path derived from `planningHome.changesDir`/YYYY-MM-DD-<name>/
**Specs:** Sync skipped (user chose to skip)
**Warnings:**
- Archived with 2 incomplete artifacts
- Archived with 3 incomplete tasks
- Delta spec sync was skipped (user chose to skip)
Review the archive if this was not intentional.
```
**Output On Error (Archive Exists)**
```
## Archive Failed
**Change:** <change-name>
**Target:** the archive path derived from `planningHome.changesDir`/YYYY-MM-DD-<name>/
Target archive directory already exists.
**Options:**
1. Rename the existing archive
2. Delete the existing archive if it's a duplicate
3. Wait until a different date to archive
```
**Guardrails**
- Always prompt for change selection if not provided
- Use artifact graph (openspec status --json) for completion checking
- Don't block archive on warnings - just inform and confirm
- Preserve .openspec.yaml when moving to archive (it moves with the directory)
- Show clear summary of what happened
- If sync is requested, use the Skill tool to invoke `openspec-sync-specs` (agent-driven)
- If delta specs exist, always run the sync assessment and show the combined summary before prompting

View File

@@ -0,0 +1,172 @@
---
name: "OPSX: Explore"
description: "Enter explore mode - think through ideas, investigate problems, clarify requirements"
category: Workflow
tags: [workflow, explore, experimental, thinking]
---
Enter explore mode. Think deeply. Visualize freely. Follow the conversation wherever it goes.
**IMPORTANT: Explore mode is for thinking, not implementing.** You may read files, search code, and investigate the codebase, but you must NEVER write code or implement features. If the user asks you to implement something, remind them to exit explore mode first and create a change proposal. You MAY create OpenSpec artifacts (proposals, designs, specs) if the user asks—that's capturing thinking, not implementing.
**This is a stance, not a workflow.** There are no fixed steps, no required sequence, no mandatory outputs. You're a thinking partner helping the user explore.
**Input**: The argument after `/opsx:explore` is whatever the user wants to think about. Could be:
- A vague idea: "real-time collaboration"
- A specific problem: "the auth system is getting unwieldy"
- A change name: "add-dark-mode" (to explore in context of that change)
- A comparison: "postgres vs sqlite for this"
- Nothing (just enter explore mode)
---
## The Stance
- **Curious, not prescriptive** - Ask questions that emerge naturally, don't follow a script
- **Open threads, not interrogations** - Surface multiple interesting directions and let the user follow what resonates. Don't funnel them through a single path of questions.
- **Visual** - Use ASCII diagrams liberally when they'd help clarify thinking
- **Adaptive** - Follow interesting threads, pivot when new information emerges
- **Patient** - Don't rush to conclusions, let the shape of the problem emerge
- **Grounded** - Explore the actual codebase when relevant, don't just theorize
---
## What You Might Do
Depending on what the user brings, you might:
**Explore the problem space**
- Ask clarifying questions that emerge from what they said
- Challenge assumptions
- Reframe the problem
- Find analogies
**Investigate the codebase**
- Map existing architecture relevant to the discussion
- Find integration points
- Identify patterns already in use
- Surface hidden complexity
**Compare options**
- Brainstorm multiple approaches
- Build comparison tables
- Sketch tradeoffs
- Recommend a path (if asked)
**Visualize**
```
┌─────────────────────────────────────────┐
│ Use ASCII diagrams liberally │
├─────────────────────────────────────────┤
│ │
│ ┌────────┐ ┌────────┐ │
│ │ State │────────▶│ State │ │
│ │ A │ │ B │ │
│ └────────┘ └────────┘ │
│ │
│ System diagrams, state machines, │
│ data flows, architecture sketches, │
│ dependency graphs, comparison tables │
│ │
└─────────────────────────────────────────┘
```
**Surface risks and unknowns**
- Identify what could go wrong
- Find gaps in understanding
- Suggest spikes or investigations
---
## OpenSpec Awareness
You have full context of the OpenSpec system. Use it naturally, don't force it.
### Check for context
At the start, quickly check what exists:
```bash
openspec list --json
```
This tells you:
- If there are active changes
- Their names, schemas, and status
- What the user might be working on
If the user mentioned a specific change name, read its artifacts for context.
### When no change exists
Think freely. When insights crystallize, you might offer:
- "This feels solid enough to start a change. Want me to create a proposal?"
- Or keep exploring - no pressure to formalize
### When a change exists
If the user mentions a change or you detect one is relevant:
1. **Resolve and read existing artifacts for context**
- Run `openspec status --change "<name>" --json`.
- Use `changeRoot`, `artifactPaths`, and `actionContext` from the status JSON.
- Read existing files from `artifactPaths.<artifact>.existingOutputPaths`.
2. **Reference them naturally in conversation**
- "Your design mentions using Redis, but we just realized SQLite fits better..."
- "The proposal scopes this to premium users, but we're now thinking everyone..."
3. **Offer to capture when decisions are made**
| Insight Type | Where to Capture |
|----------------------------|--------------------------------|
| New requirement discovered | `specs/<capability>/spec.md` |
| Requirement changed | `specs/<capability>/spec.md` |
| Design decision made | `design.md` |
| Scope changed | `proposal.md` |
| New work identified | `tasks.md` |
| Assumption invalidated | Relevant artifact |
Example offers:
- "That's a design decision. Capture it in design.md?"
- "This is a new requirement. Add it to specs?"
- "This changes scope. Update the proposal?"
4. **The user decides** - Offer and move on. Don't pressure. Don't auto-capture.
---
## What You Don't Have To Do
- Follow a script
- Ask the same questions every time
- Produce a specific artifact
- Reach a conclusion
- Stay on topic if a tangent is valuable
- Be brief (this is thinking time)
---
## Ending Discovery
There's no required ending. Discovery might:
- **Flow into a proposal**: "Ready to start? I can create a change proposal."
- **Result in artifact updates**: "Updated design.md with these decisions"
- **Just provide clarity**: User has what they need, moves on
- **Continue later**: "We can pick this up anytime"
When things crystallize, you might offer a summary - but it's optional. Sometimes the thinking IS the value.
---
## Guardrails
- **Don't implement** - Never write code or implement features. Creating OpenSpec artifacts is fine, writing application code is not.
- **Don't fake understanding** - If something is unclear, dig deeper
- **Don't rush** - Discovery is thinking time, not task time
- **Don't force structure** - Let patterns emerge naturally
- **Don't auto-capture** - Offer to save insights, don't just do it
- **Do visualize** - A good diagram is worth many paragraphs
- **Do explore the codebase** - Ground discussions in reality
- **Do question assumptions** - Including the user's and your own

View File

@@ -0,0 +1,107 @@
---
name: "OPSX: Propose"
description: Propose a new change - create it and generate all artifacts in one step
category: Workflow
tags: [workflow, artifacts, experimental]
---
Propose a new change - create the change and generate all artifacts in one step.
I'll create a change with artifacts:
- proposal.md (what & why)
- design.md (how)
- tasks.md (implementation steps)
When ready to implement, run /opsx:apply
---
**Input**: The argument after `/opsx:propose` is the change name (kebab-case), OR a description of what the user wants to build.
**Steps**
1. **If no input provided, ask what they want to build**
Use the **AskUserQuestion tool** (open-ended, no preset options) to ask:
> "What change do you want to work on? Describe what you want to build or fix."
From their description, derive a kebab-case name (e.g., "add user authentication" → `add-user-auth`).
**IMPORTANT**: Do NOT proceed without understanding what the user wants to build.
2. **Create the change directory**
```bash
openspec new change "<name>"
```
This creates a scaffolded change in the planning home resolved by the CLI with `.openspec.yaml`.
3. **Get the artifact build order**
```bash
openspec status --change "<name>" --json
```
Parse the JSON to get:
- `applyRequires`: array of artifact IDs needed before implementation (e.g., `["tasks"]`)
- `artifacts`: list of all artifacts with their status and dependencies
- `planningHome`, `changeRoot`, `artifactPaths`, and `actionContext`: path and scope context. Use these instead of assuming repo-local paths.
4. **Create artifacts in sequence until apply-ready**
Use the **TodoWrite tool** to track progress through the artifacts.
Loop through artifacts in dependency order (artifacts with no pending dependencies first):
a. **For each artifact that is `ready` (dependencies satisfied)**:
- Get instructions:
```bash
openspec instructions <artifact-id> --change "<name>" --json
```
- The instructions JSON includes:
- `context`: Project background (constraints for you - do NOT include in output)
- `rules`: Artifact-specific rules (constraints for you - do NOT include in output)
- `template`: The structure to use for your output file
- `instruction`: Schema-specific guidance for this artifact type
- `resolvedOutputPath`: Resolved path or pattern to write the artifact
- `dependencies`: Completed artifacts to read for context
- Read any completed dependency files for context
- Create the artifact file using `template` as the structure and write it to `resolvedOutputPath`
- Apply `context` and `rules` as constraints - but do NOT copy them into the file
- Show brief progress: "Created <artifact-id>"
b. **Continue until all `applyRequires` artifacts are complete**
- After creating each artifact, re-run `openspec status --change "<name>" --json`
- Check if every artifact ID in `applyRequires` has `status: "done"` in the artifacts array
- Stop when all `applyRequires` artifacts are done
c. **If an artifact requires user input** (unclear context):
- Use **AskUserQuestion tool** to clarify
- Then continue with creation
5. **Show final status**
```bash
openspec status --change "<name>"
```
**Output**
After completing all artifacts, summarize:
- Change name and location
- List of artifacts created with brief descriptions
- What's ready: "All artifacts created! Ready for implementation."
- Prompt: "Run `/opsx:apply` to start implementing."
**Artifact Creation Guidelines**
- Follow the `instruction` field from `openspec instructions` for each artifact type
- The schema defines what each artifact should contain - follow it
- Read dependency artifacts for context before creating new ones
- Use `template` as the structure for your output file - fill in its sections
- **IMPORTANT**: `context` and `rules` are constraints for YOU, not content for the file
- Do NOT copy `<context>`, `<rules>`, `<project_context>` blocks into the artifact
- These guide what you write, but should never appear in the output
**Guardrails**
- Create ALL artifacts needed for implementation (as defined by schema's `apply.requires`)
- Always read dependency artifacts before creating a new one
- If context is critically unclear, ask the user - but prefer making reasonable decisions to keep momentum
- If a change with that name already exists, ask if user wants to continue it or create a new one
- Verify each artifact file exists after writing before proceeding to next

View File

@@ -0,0 +1,143 @@
---
name: "OPSX: Sync"
description: Sync delta specs from a change to main specs
category: Workflow
tags: [workflow, specs, experimental]
---
Sync delta specs from a change to main specs.
This is an **agent-driven** operation - you will read delta specs and directly edit main specs to apply the changes. This allows intelligent merging (e.g., adding a scenario without copying the entire requirement).
**Input**: Optionally specify a change name after `/opsx:sync` (e.g., `/opsx:sync add-auth`). If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
**Steps**
1. **If no change name provided, prompt for selection**
Run `openspec list --json` to get available changes. Use the **AskUserQuestion tool** to let the user select.
Show changes that have delta specs (under `specs/` directory).
**IMPORTANT**: Do NOT guess or auto-select a change. Always let the user choose.
2. **Resolve change context**
Run:
```bash
openspec status --change "<name>" --json
```
If status reports `actionContext.mode: "workspace-planning"`, explain that workspace spec sync is not supported in this slice and STOP. Do not fall back to repo-local paths or edit linked repos.
3. **Find delta specs**
Use `artifactPaths.specs.existingOutputPaths` from the status JSON as the list of delta spec files.
Each delta spec file contains sections like:
- `## ADDED Requirements` - New requirements to add
- `## MODIFIED Requirements` - Changes to existing requirements
- `## REMOVED Requirements` - Requirements to remove
- `## RENAMED Requirements` - Requirements to rename (FROM:/TO: format)
If no delta specs found, inform user and stop.
4. **For each delta spec, apply changes to main specs**
For each repo-local capability delta spec path returned by the CLI:
a. **Read the delta spec** to understand the intended changes
b. **Read the main spec** at `openspec/specs/<capability>/spec.md` (may not exist yet)
c. **Apply changes intelligently**:
**ADDED Requirements:**
- If requirement doesn't exist in main spec → add it
- If requirement already exists → update it to match (treat as implicit MODIFIED)
**MODIFIED Requirements:**
- Find the requirement in main spec
- Apply the changes - this can be:
- Adding new scenarios (don't need to copy existing ones)
- Modifying existing scenarios
- Changing the requirement description
- Preserve scenarios/content not mentioned in the delta
**REMOVED Requirements:**
- Remove the entire requirement block from main spec
**RENAMED Requirements:**
- Find the FROM requirement, rename to TO
d. **Create new main spec** if capability doesn't exist yet:
- Create `openspec/specs/<capability>/spec.md`
- Add Purpose section (can be brief, mark as TBD)
- Add Requirements section with the ADDED requirements
5. **Show summary**
After applying all changes, summarize:
- Which capabilities were updated
- What changes were made (requirements added/modified/removed/renamed)
**Delta Spec Format Reference**
```markdown
## ADDED Requirements
### Requirement: New Feature
The system SHALL do something new.
#### Scenario: Basic case
- **WHEN** user does X
- **THEN** system does Y
## MODIFIED Requirements
### Requirement: Existing Feature
#### Scenario: New scenario to add
- **WHEN** user does A
- **THEN** system does B
## REMOVED Requirements
### Requirement: Deprecated Feature
## RENAMED Requirements
- FROM: `### Requirement: Old Name`
- TO: `### Requirement: New Name`
```
**Key Principle: Intelligent Merging**
Unlike programmatic merging, you can apply **partial updates**:
- To add a scenario, just include that scenario under MODIFIED - don't copy existing scenarios
- The delta represents *intent*, not a wholesale replacement
- Use your judgment to merge changes sensibly
**Output On Success**
```
## Specs Synced: <change-name>
Updated main specs:
**<capability-1>**:
- Added requirement: "New Feature"
- Modified requirement: "Existing Feature" (added 1 scenario)
**<capability-2>**:
- Created new spec file
- Added requirement: "Another Feature"
Main specs are now updated. The change remains active - archive when implementation is complete.
```
**Guardrails**
- Read both delta and main specs before making changes
- Preserve existing content not mentioned in delta
- If something is unclear, ask for clarification
- Show what you're changing as you go
- The operation should be idempotent - running twice should give same result

View File

@@ -0,0 +1,159 @@
---
name: openspec-apply-change
description: Implement tasks from an OpenSpec change. Use when the user wants to start implementing, continue implementation, or work through tasks.
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.4.1"
---
Implement tasks from an OpenSpec change.
**Input**: Optionally specify a change name. If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
**Steps**
1. **Select the change**
If a name is provided, use it. Otherwise:
- Infer from conversation context if the user mentioned a change
- Auto-select if only one active change exists
- If ambiguous, run `openspec list --json` to get available changes and use the **AskUserQuestion tool** to let the user select
Always announce: "Using change: <name>" and how to override (e.g., `/opsx:apply <other>`).
2. **Check status to understand the schema**
```bash
openspec status --change "<name>" --json
```
Parse the JSON to understand:
- `schemaName`: The workflow being used (e.g., "spec-driven")
- `planningHome`, `changeRoot`, and `actionContext`: planning scope and edit constraints
- Which artifact contains the tasks (typically "tasks" for spec-driven, check status for others)
3. **Get apply instructions**
```bash
openspec instructions apply --change "<name>" --json
```
This returns:
- `contextFiles`: artifact ID -> array of concrete file paths (varies by schema - could be proposal/specs/design/tasks or spec/tests/implementation/docs)
- Progress (total, complete, remaining)
- Task list with status
- Dynamic instruction based on current state
**Handle states:**
- If `state: "blocked"` (missing artifacts): show message, suggest using openspec-continue-change
- If `state: "all_done"`: congratulate, suggest archive
- Otherwise: proceed to implementation
**Workspace guard:** If status JSON reports `actionContext.mode: "workspace-planning"` and `allowedEditRoots` is empty, explain that full workspace apply is not supported in this slice. Treat linked repos and folders as read-only context, ask the user to select an affected area through an explicit implementation workflow, and STOP before editing files.
4. **Read context files**
Read every file path listed under `contextFiles` from the apply instructions output.
The files depend on the schema being used:
- **spec-driven**: proposal, specs, design, tasks
- Other schemas: follow the contextFiles from CLI output
5. **Show current progress**
Display:
- Schema being used
- Progress: "N/M tasks complete"
- Remaining tasks overview
- Dynamic instruction from CLI
6. **Implement tasks (loop until done or blocked)**
For each pending task:
- Show which task is being worked on
- Make the code changes required
- Keep changes minimal and focused
- Mark task complete in the tasks file: `- [ ]` → `- [x]`
- Continue to next task
**Pause if:**
- Task is unclear → ask for clarification
- Implementation reveals a design issue → suggest updating artifacts
- Error or blocker encountered → report and wait for guidance
- User interrupts
7. **On completion or pause, show status**
Display:
- Tasks completed this session
- Overall progress: "N/M tasks complete"
- If all done: suggest archive
- If paused: explain why and wait for guidance
**Output During Implementation**
```
## Implementing: <change-name> (schema: <schema-name>)
Working on task 3/7: <task description>
[...implementation happening...]
✓ Task complete
Working on task 4/7: <task description>
[...implementation happening...]
✓ Task complete
```
**Output On Completion**
```
## Implementation Complete
**Change:** <change-name>
**Schema:** <schema-name>
**Progress:** 7/7 tasks complete ✓
### Completed This Session
- [x] Task 1
- [x] Task 2
...
All tasks complete! Ready to archive this change.
```
**Output On Pause (Issue Encountered)**
```
## Implementation Paused
**Change:** <change-name>
**Schema:** <schema-name>
**Progress:** 4/7 tasks complete
### Issue Encountered
<description of the issue>
**Options:**
1. <option 1>
2. <option 2>
3. Other approach
What would you like to do?
```
**Guardrails**
- Keep going through tasks until done or blocked
- Always read context files before starting (from the apply instructions output)
- If task is ambiguous, pause and ask before implementing
- If implementation reveals issues, pause and suggest artifact updates
- Keep code changes minimal and scoped to each task
- Update task checkbox immediately after completing each task
- Pause on errors, blockers, or unclear requirements - don't guess
- Use contextFiles from CLI output, don't assume specific file names
**Fluid Workflow Integration**
This skill supports the "actions on a change" model:
- **Can be invoked anytime**: Before all artifacts are done (if tasks exist), after partial implementation, interleaved with other actions
- **Allows artifact updates**: If implementation reveals design issues, suggest updating artifacts - not phase-locked, work fluidly

View File

@@ -0,0 +1,117 @@
---
name: openspec-archive-change
description: Archive a completed change in the experimental workflow. Use when the user wants to finalize and archive a change after implementation is complete.
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.4.1"
---
Archive a completed change in the experimental workflow.
**Input**: Optionally specify a change name. If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
**Steps**
1. **If no change name provided, prompt for selection**
Run `openspec list --json` to get available changes. Use the **AskUserQuestion tool** to let the user select.
Show only active changes (not already archived).
Include the schema used for each change if available.
**IMPORTANT**: Do NOT guess or auto-select a change. Always let the user choose.
2. **Check artifact completion status**
Run `openspec status --change "<name>" --json` to check artifact completion.
Parse the JSON to understand:
- `schemaName`: The workflow being used
- `planningHome`, `changeRoot`, `artifactPaths`, and `actionContext`: path and scope context
- `artifacts`: List of artifacts with their status (`done` or other)
If status reports `actionContext.mode: "workspace-planning"`, explain that workspace archive is not supported in this slice and STOP. Do not move workspace changes into repo-local archives or edit linked repos.
**If any artifacts are not `done`:**
- Display warning listing incomplete artifacts
- Use **AskUserQuestion tool** to confirm user wants to proceed
- Proceed if user confirms
3. **Check task completion status**
Read the tasks file (typically `tasks.md`) to check for incomplete tasks.
Count tasks marked with `- [ ]` (incomplete) vs `- [x]` (complete).
**If incomplete tasks found:**
- Display warning showing count of incomplete tasks
- Use **AskUserQuestion tool** to confirm user wants to proceed
- Proceed if user confirms
**If no tasks file exists:** Proceed without task-related warning.
4. **Assess delta spec sync state**
Use `artifactPaths.specs.existingOutputPaths` from status JSON to check for delta specs. If none exist, proceed without sync prompt.
**If delta specs exist:**
- Compare each delta spec with its corresponding main spec at `openspec/specs/<capability>/spec.md`
- Determine what changes would be applied (adds, modifications, removals, renames)
- Show a combined summary before prompting
**Prompt options:**
- If changes needed: "Sync now (recommended)", "Archive without syncing"
- If already synced: "Archive now", "Sync anyway", "Cancel"
If user chooses sync, use Task tool (subagent_type: "general-purpose", prompt: "Use Skill tool to invoke openspec-sync-specs for change '<name>'. Delta spec analysis: <include the analyzed delta spec summary>"). Proceed to archive regardless of choice.
5. **Perform the archive**
Create an `archive` directory under `planningHome.changesDir` if it doesn't exist:
```bash
mkdir -p "<planningHome.changesDir>/archive"
```
Generate target name using current date: `YYYY-MM-DD-<change-name>`
**Check if target already exists:**
- If yes: Fail with error, suggest renaming existing archive or using different date
- If no: Move `changeRoot` to the archive directory
```bash
mv "<changeRoot>" "<planningHome.changesDir>/archive/YYYY-MM-DD-<name>"
```
6. **Display summary**
Show archive completion summary including:
- Change name
- Schema that was used
- Archive location
- Whether specs were synced (if applicable)
- Note about any warnings (incomplete artifacts/tasks)
**Output On Success**
```
## Archive Complete
**Change:** <change-name>
**Schema:** <schema-name>
**Archived to:** the archive path derived from `planningHome.changesDir`/YYYY-MM-DD-<name>/
**Specs:** ✓ Synced to main specs (or "No delta specs" or "Sync skipped")
All artifacts complete. All tasks complete.
```
**Guardrails**
- Always prompt for change selection if not provided
- Use artifact graph (openspec status --json) for completion checking
- Don't block archive on warnings - just inform and confirm
- Preserve .openspec.yaml when moving to archive (it moves with the directory)
- Show clear summary of what happened
- If sync is requested, use openspec-sync-specs approach (agent-driven)
- If delta specs exist, always run the sync assessment and show the combined summary before prompting

View File

@@ -0,0 +1,287 @@
---
name: openspec-explore
description: Enter explore mode - a thinking partner for exploring ideas, investigating problems, and clarifying requirements. Use when the user wants to think through something before or during a change.
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.4.1"
---
Enter explore mode. Think deeply. Visualize freely. Follow the conversation wherever it goes.
**IMPORTANT: Explore mode is for thinking, not implementing.** You may read files, search code, and investigate the codebase, but you must NEVER write code or implement features. If the user asks you to implement something, remind them to exit explore mode first and create a change proposal. You MAY create OpenSpec artifacts (proposals, designs, specs) if the user asks—that's capturing thinking, not implementing.
**This is a stance, not a workflow.** There are no fixed steps, no required sequence, no mandatory outputs. You're a thinking partner helping the user explore.
---
## The Stance
- **Curious, not prescriptive** - Ask questions that emerge naturally, don't follow a script
- **Open threads, not interrogations** - Surface multiple interesting directions and let the user follow what resonates. Don't funnel them through a single path of questions.
- **Visual** - Use ASCII diagrams liberally when they'd help clarify thinking
- **Adaptive** - Follow interesting threads, pivot when new information emerges
- **Patient** - Don't rush to conclusions, let the shape of the problem emerge
- **Grounded** - Explore the actual codebase when relevant, don't just theorize
---
## What You Might Do
Depending on what the user brings, you might:
**Explore the problem space**
- Ask clarifying questions that emerge from what they said
- Challenge assumptions
- Reframe the problem
- Find analogies
**Investigate the codebase**
- Map existing architecture relevant to the discussion
- Find integration points
- Identify patterns already in use
- Surface hidden complexity
**Compare options**
- Brainstorm multiple approaches
- Build comparison tables
- Sketch tradeoffs
- Recommend a path (if asked)
**Visualize**
```
┌─────────────────────────────────────────┐
│ Use ASCII diagrams liberally │
├─────────────────────────────────────────┤
│ │
│ ┌────────┐ ┌────────┐ │
│ │ State │────────▶│ State │ │
│ │ A │ │ B │ │
│ └────────┘ └────────┘ │
│ │
│ System diagrams, state machines, │
│ data flows, architecture sketches, │
│ dependency graphs, comparison tables │
│ │
└─────────────────────────────────────────┘
```
**Surface risks and unknowns**
- Identify what could go wrong
- Find gaps in understanding
- Suggest spikes or investigations
---
## OpenSpec Awareness
You have full context of the OpenSpec system. Use it naturally, don't force it.
### Check for context
At the start, quickly check what exists:
```bash
openspec list --json
```
This tells you:
- If there are active changes
- Their names, schemas, and status
- What the user might be working on
### When no change exists
Think freely. When insights crystallize, you might offer:
- "This feels solid enough to start a change. Want me to create a proposal?"
- Or keep exploring - no pressure to formalize
### When a change exists
If the user mentions a change or you detect one is relevant:
1. **Resolve and read existing artifacts for context**
- Run `openspec status --change "<name>" --json`.
- Use `changeRoot`, `artifactPaths`, and `actionContext` from the status JSON.
- Read existing files from `artifactPaths.<artifact>.existingOutputPaths`.
2. **Reference them naturally in conversation**
- "Your design mentions using Redis, but we just realized SQLite fits better..."
- "The proposal scopes this to premium users, but we're now thinking everyone..."
3. **Offer to capture when decisions are made**
| Insight Type | Where to Capture |
|----------------------------|--------------------------------|
| New requirement discovered | `specs/<capability>/spec.md` |
| Requirement changed | `specs/<capability>/spec.md` |
| Design decision made | `design.md` |
| Scope changed | `proposal.md` |
| New work identified | `tasks.md` |
| Assumption invalidated | Relevant artifact |
Example offers:
- "That's a design decision. Capture it in design.md?"
- "This is a new requirement. Add it to specs?"
- "This changes scope. Update the proposal?"
4. **The user decides** - Offer and move on. Don't pressure. Don't auto-capture.
---
## What You Don't Have To Do
- Follow a script
- Ask the same questions every time
- Produce a specific artifact
- Reach a conclusion
- Stay on topic if a tangent is valuable
- Be brief (this is thinking time)
---
## Handling Different Entry Points
**User brings a vague idea:**
```
User: I'm thinking about adding real-time collaboration
You: Real-time collab is a big space. Let me think about this...
COLLABORATION SPECTRUM
════════════════════════════════════════════
Awareness Coordination Sync
│ │ │
▼ ▼ ▼
┌────────┐ ┌────────┐ ┌────────┐
│Presence│ │Cursors │ │ CRDT │
│ "3 │ │ Multi │ │Conflict│
│online" │ │ select │ │ free │
└────────┘ └────────┘ └────────┘
│ │ │
trivial moderate complex
Where's your head at?
```
**User brings a specific problem:**
```
User: The auth system is a mess
You: [reads codebase]
┌─────────────────────────────────────────────┐
│ CURRENT AUTH FLOW │
└─────────────────────────────────────────────┘
│
┌─────────────┼─────────────┐
▼ ▼ ▼
┌─────────┐ ┌─────────┐ ┌─────────┐
│ Google │ │ GitHub │ │ Email │
│ OAuth │ │ OAuth │ │ Magic │
└────┬────┘ └────┬────┘ └────┬────┘
│ │ │
└─────────────┼─────────────┘
▼
┌───────────┐
│ Session │
└─────┬─────┘
│
▼
┌───────────┐
│ Perms │
└───────────┘
I see three tangles. Which one's burning?
```
**User is stuck mid-implementation:**
```
User: /opsx:explore add-auth-system
The OAuth integration is more complex than expected
You: [reads change artifacts]
You're on task 4: "Implement OAuth flow"
Let me trace what's involved...
[draws diagram, explores options, suggests paths]
Want to update the design to reflect this?
Or add a spike task to investigate?
```
**User wants to compare options:**
```
User: Should we use Postgres or SQLite?
You: Generic answer is boring. What's the context?
User: A CLI tool that tracks local dev environments
You: That changes everything.
┌─────────────────────────────────────────────────┐
│ CLI TOOL DATA STORAGE │
└─────────────────────────────────────────────────┘
Key constraints:
• No daemon running
• Must work offline
• Single user
SQLite Postgres
Deployment embedded ✓ needs server ✗
Offline yes ✓ no ✗
Single file yes ✓ no ✗
SQLite. Not even close.
Unless... is there a sync component?
```
---
## Ending Discovery
There's no required ending. Discovery might:
- **Flow into a proposal**: "Ready to start? I can create a change proposal."
- **Result in artifact updates**: "Updated design.md with these decisions"
- **Just provide clarity**: User has what they need, moves on
- **Continue later**: "We can pick this up anytime"
When it feels like things are crystallizing, you might summarize:
```
## What We Figured Out
**The problem**: [crystallized understanding]
**The approach**: [if one emerged]
**Open questions**: [if any remain]
**Next steps** (if ready):
- Create a change proposal
- Keep exploring: just keep talking
```
But this summary is optional. Sometimes the thinking IS the value.
---
## Guardrails
- **Don't implement** - Never write code or implement features. Creating OpenSpec artifacts is fine, writing application code is not.
- **Don't fake understanding** - If something is unclear, dig deeper
- **Don't rush** - Discovery is thinking time, not task time
- **Don't force structure** - Let patterns emerge naturally
- **Don't auto-capture** - Offer to save insights, don't just do it
- **Do visualize** - A good diagram is worth many paragraphs
- **Do explore the codebase** - Ground discussions in reality
- **Do question assumptions** - Including the user's and your own

View File

@@ -0,0 +1,111 @@
---
name: openspec-propose
description: Propose a new change with all artifacts generated in one step. Use when the user wants to quickly describe what they want to build and get a complete proposal with design, specs, and tasks ready for implementation.
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.4.1"
---
Propose a new change - create the change and generate all artifacts in one step.
I'll create a change with artifacts:
- proposal.md (what & why)
- design.md (how)
- tasks.md (implementation steps)
When ready to implement, run /opsx:apply
---
**Input**: The user's request should include a change name (kebab-case) OR a description of what they want to build.
**Steps**
1. **If no clear input provided, ask what they want to build**
Use the **AskUserQuestion tool** (open-ended, no preset options) to ask:
> "What change do you want to work on? Describe what you want to build or fix."
From their description, derive a kebab-case name (e.g., "add user authentication" → `add-user-auth`).
**IMPORTANT**: Do NOT proceed without understanding what the user wants to build.
2. **Create the change directory**
```bash
openspec new change "<name>"
```
This creates a scaffolded change in the planning home resolved by the CLI with `.openspec.yaml`.
3. **Get the artifact build order**
```bash
openspec status --change "<name>" --json
```
Parse the JSON to get:
- `applyRequires`: array of artifact IDs needed before implementation (e.g., `["tasks"]`)
- `artifacts`: list of all artifacts with their status and dependencies
- `planningHome`, `changeRoot`, `artifactPaths`, and `actionContext`: path and scope context. Use these instead of assuming repo-local paths.
4. **Create artifacts in sequence until apply-ready**
Use the **TodoWrite tool** to track progress through the artifacts.
Loop through artifacts in dependency order (artifacts with no pending dependencies first):
a. **For each artifact that is `ready` (dependencies satisfied)**:
- Get instructions:
```bash
openspec instructions <artifact-id> --change "<name>" --json
```
- The instructions JSON includes:
- `context`: Project background (constraints for you - do NOT include in output)
- `rules`: Artifact-specific rules (constraints for you - do NOT include in output)
- `template`: The structure to use for your output file
- `instruction`: Schema-specific guidance for this artifact type
- `resolvedOutputPath`: Resolved path or pattern to write the artifact
- `dependencies`: Completed artifacts to read for context
- Read any completed dependency files for context
- Create the artifact file using `template` as the structure and write it to `resolvedOutputPath`
- Apply `context` and `rules` as constraints - but do NOT copy them into the file
- Show brief progress: "Created <artifact-id>"
b. **Continue until all `applyRequires` artifacts are complete**
- After creating each artifact, re-run `openspec status --change "<name>" --json`
- Check if every artifact ID in `applyRequires` has `status: "done"` in the artifacts array
- Stop when all `applyRequires` artifacts are done
c. **If an artifact requires user input** (unclear context):
- Use **AskUserQuestion tool** to clarify
- Then continue with creation
5. **Show final status**
```bash
openspec status --change "<name>"
```
**Output**
After completing all artifacts, summarize:
- Change name and location
- List of artifacts created with brief descriptions
- What's ready: "All artifacts created! Ready for implementation."
- Prompt: "Run `/opsx:apply` or ask me to implement to start working on the tasks."
**Artifact Creation Guidelines**
- Follow the `instruction` field from `openspec instructions` for each artifact type
- The schema defines what each artifact should contain - follow it
- Read dependency artifacts for context before creating new ones
- Use `template` as the structure for your output file - fill in its sections
- **IMPORTANT**: `context` and `rules` are constraints for YOU, not content for the file
- Do NOT copy `<context>`, `<rules>`, `<project_context>` blocks into the artifact
- These guide what you write, but should never appear in the output
**Guardrails**
- Create ALL artifacts needed for implementation (as defined by schema's `apply.requires`)
- Always read dependency artifacts before creating a new one
- If context is critically unclear, ask the user - but prefer making reasonable decisions to keep momentum
- If a change with that name already exists, ask if user wants to continue it or create a new one
- Verify each artifact file exists after writing before proceeding to next

View File

@@ -0,0 +1,147 @@
---
name: openspec-sync-specs
description: Sync delta specs from a change to main specs. Use when the user wants to update main specs with changes from a delta spec, without archiving the change.
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.4.1"
---
Sync delta specs from a change to main specs.
This is an **agent-driven** operation - you will read delta specs and directly edit main specs to apply the changes. This allows intelligent merging (e.g., adding a scenario without copying the entire requirement).
**Input**: Optionally specify a change name. If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
**Steps**
1. **If no change name provided, prompt for selection**
Run `openspec list --json` to get available changes. Use the **AskUserQuestion tool** to let the user select.
Show changes that have delta specs (under `specs/` directory).
**IMPORTANT**: Do NOT guess or auto-select a change. Always let the user choose.
2. **Resolve change context**
Run:
```bash
openspec status --change "<name>" --json
```
If status reports `actionContext.mode: "workspace-planning"`, explain that workspace spec sync is not supported in this slice and STOP. Do not fall back to repo-local paths or edit linked repos.
3. **Find delta specs**
Use `artifactPaths.specs.existingOutputPaths` from the status JSON as the list of delta spec files.
Each delta spec file contains sections like:
- `## ADDED Requirements` - New requirements to add
- `## MODIFIED Requirements` - Changes to existing requirements
- `## REMOVED Requirements` - Requirements to remove
- `## RENAMED Requirements` - Requirements to rename (FROM:/TO: format)
If no delta specs found, inform user and stop.
4. **For each delta spec, apply changes to main specs**
For each repo-local capability delta spec path returned by the CLI:
a. **Read the delta spec** to understand the intended changes
b. **Read the main spec** at `openspec/specs/<capability>/spec.md` (may not exist yet)
c. **Apply changes intelligently**:
**ADDED Requirements:**
- If requirement doesn't exist in main spec → add it
- If requirement already exists → update it to match (treat as implicit MODIFIED)
**MODIFIED Requirements:**
- Find the requirement in main spec
- Apply the changes - this can be:
- Adding new scenarios (don't need to copy existing ones)
- Modifying existing scenarios
- Changing the requirement description
- Preserve scenarios/content not mentioned in the delta
**REMOVED Requirements:**
- Remove the entire requirement block from main spec
**RENAMED Requirements:**
- Find the FROM requirement, rename to TO
d. **Create new main spec** if capability doesn't exist yet:
- Create `openspec/specs/<capability>/spec.md`
- Add Purpose section (can be brief, mark as TBD)
- Add Requirements section with the ADDED requirements
5. **Show summary**
After applying all changes, summarize:
- Which capabilities were updated
- What changes were made (requirements added/modified/removed/renamed)
**Delta Spec Format Reference**
```markdown
## ADDED Requirements
### Requirement: New Feature
The system SHALL do something new.
#### Scenario: Basic case
- **WHEN** user does X
- **THEN** system does Y
## MODIFIED Requirements
### Requirement: Existing Feature
#### Scenario: New scenario to add
- **WHEN** user does A
- **THEN** system does B
## REMOVED Requirements
### Requirement: Deprecated Feature
## RENAMED Requirements
- FROM: `### Requirement: Old Name`
- TO: `### Requirement: New Name`
```
**Key Principle: Intelligent Merging**
Unlike programmatic merging, you can apply **partial updates**:
- To add a scenario, just include that scenario under MODIFIED - don't copy existing scenarios
- The delta represents *intent*, not a wholesale replacement
- Use your judgment to merge changes sensibly
**Output On Success**
```
## Specs Synced: <change-name>
Updated main specs:
**<capability-1>**:
- Added requirement: "New Feature"
- Modified requirement: "Existing Feature" (added 1 scenario)
**<capability-2>**:
- Created new spec file
- Added requirement: "Another Feature"
Main specs are now updated. The change remains active - archive when implementation is complete.
```
**Guardrails**
- Read both delta and main specs before making changes
- Preserve existing content not mentioned in delta
- If something is unclear, ask for clarification
- Show what you're changing as you go
- The operation should be idempotent - running twice should give same result

33
.github/workflows/i18n-audit.yml vendored Normal file
View File

@@ -0,0 +1,33 @@
# GitHub Actions 示例:i18n audit on PR
name: i18n-audit
on:
pull_request:
paths:
- 'lang/**'
- 'lang-bundle.json'
- '**/*.vue'
- '**/*.js'
- 'scripts/i18n_audit.py'
- 'scripts/audit_lang_bundle_v2.py'
jobs:
audit:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20'
- uses: actions/setup-python@v5
with:
python-version: '3.11'
- name: Run i18n audit
run: |
python scripts/i18n_audit.py --strict
- name: Upload audit report
if: always()
uses: actions/upload-artifact@v4
with:
name: i18n-audit-report
path: scripts/lang_audit_report_v2.json

11
.gitignore vendored
View File

@@ -1,5 +1,14 @@
/unpackage
/.hbuilderx
/.idea
/.logs
/node_modules
/iconfont-preview.html
.codebuddy
.vscode
.trae
# 鸿蒙元服务构建产物
stub-app-projects/mp-harmony/ascf/ascf_src
stub-app-projects/mp-harmony/ascf/ascf_build
stub-app-projects/mp-harmony/entry/src/main/resources

13
.hbuilderx/launch.json Normal file
View File

@@ -0,0 +1,13 @@
{
"version" : "1.0",
"configurations" : [
{
"openVueDevtools" : true,
"type" : "uni-app:h5"
},
{
"playground" : "standard",
"type" : "uni-app:app-android"
}
]
}

43
.husky/pre-commit Normal file
View File

@@ -0,0 +1,43 @@
#!/usr/bin/env sh
#
# 自动 hook:i18n 完整性。
# 在 commit 前,如果改动触及 lang/、使用 $lang() 的 .vue/.js,或 lang-bundle.json,
# 就跑一次审计,真问题会拦下 commit。
#
# 启用方法:
# 1) 项目根已有 .husky/pre-commit(本脚本)
# 2) 把这个 commit-msg / pre-commit 加入 husky 钩子(本仓库用 simple-git-hooks
# 或 husky 都行,本脚本不依赖特定框架)
#
# 也可以在 CI 跑:
# python scripts/i18n_audit.py --strict
set -e
# 检测本次 diff 是否触动相关文件
changed=$(git diff --cached --name-only HEAD)
relevant=$(echo "$changed" | grep -E '(lang/|lang-bundle\.json|\.vue$|\.js$)' | grep -v 'scripts/i18n_audit\|scripts/audit\|scripts/I18N_AUDIT' || true)
if [ -z "$relevant" ]; then
echo "[pre-commit] No lang-touching files; skip i18n audit."
exit 0
fi
echo "[pre-commit] Running i18n audit on changed files:"
echo "$relevant" | sed 's/^/ /'
cd "$(git rev-parse --show-toplevel)"
if command -v python >/dev/null 2>&1; then
if python scripts/i18n_audit.py --strict; then
echo "[pre-commit] i18n OK"
exit 0
else
echo "[pre-commit] i18n FAILED — 修复方法见 scripts/I18N_AUDIT.md"
exit 1
fi
else
echo "[pre-commit] python not available; skipping"
exit 0
fi

View File

@@ -18,6 +18,10 @@ const localDevConfig = ({
uniacid: 2811,
domain: 'https://xcx6.aigc-quickapp.com/',
},
'2881': { // 防爆电器
uniacid: 2881,
domain: 'https://xcx6.aigc-quickapp.com/',
},
'2724': { // 生物菌肥
uniacid: 2724,
domain: 'https://xcx.aigc-quickapp.com/',
@@ -38,14 +42,110 @@ const localDevConfig = ({
uniacid: 1,
domain: 'https://test.aigc-quickapp.com',
},
'11-test': { // 测试平台
uniacid: 11,
domain: 'https://test.aigc-quickapp.com',
},
'local-2': { // 测试平台
uniacid: 2,
domain: 'http://localhost:8050/',
},
'47': {
uniacid: 47,
domain: 'https://5g.aigc-quickapp.com/',
},
})['47']; // 选择要使用的环境配置
'local-1': { // 测试平台
uniacid: 1,
domain: 'http://192.168.197.1:8050/',
// domain: 'http://localhost:8050/',
},
'local-11': { // 测试平台
uniacid: 11,
domain: 'http://localhost:8050/',
},
'100': {
uniacid: 100,
domain: 'https://5g.aigc-quickapp.com/',
},
'1': {
uniacid: 1,
domain: 'https://5g.aigc-quickapp.com/',
},
'115': {
uniacid: 115,
domain: 'https://5g.aigc-quickapp.com/',
},
'5g-11': {
uniacid: 11,
domain: 'https://5g.aigc-quickapp.com/',
},
'5g-206': {
uniacid: 206,
domain: 'https://5g.aigc-quickapp.com/',
},
'47': { // 修改弹窗
uniacid: 47,
domain: 'https://5g.aigc-quickapp.com/',
},
'145': { // 表单链接转义问题
uniacid: 145,
domain: 'https://5g.aigc-quickapp.com/',
},
'5g-213': { // 单图组点击链接无法跳转
uniacid: 213,
domain: 'https://5g.aigc-quickapp.com/',
},
'5g-4': { // 公告点击链接无法跳转
uniacid: 4,
domain: 'https://5g.aigc-quickapp.com/',
},
'5g-97': { // 大宗商品贸易,支持自定义字体大小、颜色
uniacid: 97,
domain: 'https://5g.aigc-quickapp.com/',
},
'5g-50': { // 燃气安全产品机器人,购物车无反应
uniacid: 50,
domain: 'https://5g.aigc-quickapp.com/',
},
'5g-237': { // 商品分类,没有立即咨询文字
uniacid: 237,
domain: 'https://5g.aigc-quickapp.com/',
},
'2847': { //
uniacid: 2847,
domain: 'https://xcx.aigc-quickapp.com/',
},
'2482': { // 低空经济
uniacid: 2482,
domain: 'https://xcx6.aigc-quickapp.com/',
},
'2485': { // 验证电子表单前后端数据一致性
uniacid: 2485,
domain: 'https://xcx6.aigc-quickapp.com/',
},
'2821': { // 离型纸硅油纸
uniacid: 2821,
domain: 'https://xcx.aigc-quickapp.com/',
},
'18': { // 测试平台
uniacid: 18,
domain: 'https://test.aigc-quickapp.com',
},
'2': { // 测试平台
uniacid: 2,
domain: 'https://test.aigc-quickapp.com',
},
'48': { // 测试平台
uniacid: 48,
domain: 'https://test.aigc-quickapp.com',
},
// })['5g-237']; // 商品分类,没有立即咨询文字
// })['5g-97']; // 大宗商品贸易,支持自定义字体大小、颜色
// })['5g-50']; // 燃气安全产品机器人,购物车无反应
// })['2821']; // 离型纸硅油纸
})['48']; // 离型纸硅油纸
// })['2485']; // 验证电子表单前后端数据一致性
// })['5g-11']; // 数码
// })['5g-213']; // 选择要使用的环境配置
// })['2811']; // 选择要使用的环境配置
// })['local-11']; // 选择要使用的环境配置
// })['local-1']; // 本地
// })['local-2']; // 本地
// })['1-test']; // test
export default localDevConfig;

393
App.vue
View File

@@ -1,42 +1,357 @@
<script>
import auth from 'common/js/auth.js';
import configExternal from 'common/js/config-external.js'
import configExternal, { themeConfig, privacyConfig } from 'common/js/config-external.js'
import Lang from 'common/js/lang.js';
import ThemeOverride from 'common/js/theme-override.js';
import PrivacyManager from 'common/js/privacy.js';
import splashState from 'common/js/splash-state.js';
import {
Weixin
} from 'common/js/wx-jssdk.js';
// ============================================================
// 隐私弹窗 URL/路由规则 (H5 + 微信小程序 + 鸿蒙元服务)
//
// 配置来源 (沿用 config-external.js 同构模式):
// 1. 本地兜底: privacyConfig.urlRulesBase (与 langConfig/themeConfig 同构)
// 2. 远程 patch: /api/config/init data.privacy_url_rules (由 store/init 融合)
// 融合策略 (同上一轮):
// - mode: 远程有值则覆盖, 否则用本地
// - patterns: 按 patch.merge 字段决定 (replace 默认 / union / intersect)
// 匹配: 子串匹配
// H5: pathname + search + hash
// 小程序/鸿蒙: 当前页面 route + query
// 命中白名单后, 仍会走 storage / 平台级隐私检查, 已同意则不再弹
// ============================================================
const PRIVACY_URL_RULES_BASE = privacyConfig.urlRulesBase
// 启动期配置注入: 把 privacyConfig 的 bootTimeout / waitChannels / signSecret 灌进 PrivacyManager
// 这样 PrivacyManager.show() 即便被业务侧独立调用, 也能感知启动期资源就绪状态
// 签名密钥注入: 远程 patch 必须通过 verifyRemotePatch() 才允许 applyWithMerge
PrivacyManager.setExternalBootTimeout(configExternal.getPrivacyBootTimeout())
PrivacyManager.setWaitChannels(privacyConfig.waitChannels || {})
PrivacyManager.setSignSecret(privacyConfig.signSecret || '')
// 登记本地 base 规则, 供后续远程 patch 融合时读取
// 必须在 setStorageKey / loadPersistedRules 之前完成, 因为 store/init action
// 会通过 PrivacyManager.__getBaseRules() 读取这个 base
PrivacyManager.setBaseRules(PRIVACY_URL_RULES_BASE)
// uniacid 隔离的持久化 key
// 关键: 持久化必须基于 uniacid 隔离, 否则多租户切换会读到对方租户的规则
// 无 uniacid 时降级到 _anon (使用 localStorage 之外的隔离, 避免与任何具体租户冲突)
const _uniacid = uni.getStorageSync('uniacid')
const _persistKey = _uniacid
? ('privacy_url_rules_' + _uniacid)
: 'privacy_url_rules__anon'
PrivacyManager.setStorageKey(_persistKey)
// 1) 先尝试恢复上次的"已融合规则" (跨冷启动)
// 无持久化值 → 退化为 base
const _persisted = PrivacyManager.loadPersistedRules()
if (_persisted && _persisted.mode && Array.isArray(_persisted.patterns)) {
PrivacyManager.setUrlRules(_persisted)
} else {
// 2) 用本地 base 兜底
PrivacyManager.setUrlRules(PRIVACY_URL_RULES_BASE)
}
// 业务侧可监听: 远程下发完成后, 会触发 'privacy:rules-updated'
uni.$on && uni.$on('privacy:rules-updated', (info) => {
// 只在远程下发时打印, 避免被本地 base 加载/持久化恢复时的 emit 噪音淹没
if (info && info.source === 'remote' && console && console.log) {
console.log('[privacy] rules updated by remote, mode=' + info.mode + ', patterns=' + info.patterns.length)
}
})
/**
* 取 onLaunch options 作为首次启动的兜底路径
* H5: options.path/query 不一定存在, 此时用 window.location
* 小程序/鸿蒙: options.path 是启动路径, options.query 是启动参数
* @param {Object} launchOptions onLaunch 的 options
* @returns {Object} urlFallback
*/
function _buildPrivacyUrlFallback(launchOptions) {
const fallback = { pathname: '', search: '', hash: '', route: '', query: null }
// #ifdef H5
if (typeof window !== 'undefined' && window.location) {
fallback.pathname = window.location.pathname || ''
fallback.search = window.location.search || ''
fallback.hash = window.location.hash || ''
}
// #endif
// #ifndef H5
if (launchOptions && launchOptions.path) {
fallback.route = launchOptions.path
fallback.query = launchOptions.query || null
}
// #endif
return fallback
}
// ============================================================
// 主题/语言启动
// ============================================================
export default {
mixins: [auth],
data() {
return {
// remote-only 模式下,业务可通过 await getApp().$langReady 等待语言包就绪
$langReady: Promise.resolve({ ok: true, source: 'local' })
};
},
// 同步钩子:在 page mounted 之前同步设置隐私弹窗的 skip 状态
// 必须在 onLaunch (async) 之前跑,否则 onLaunch 第一个 await 让出事件循环时
// privacy-popup.vue 已经挂载,会走 consumePendingShow 兜底分支把弹窗弹出来
created() {
if (!PrivacyManager.shouldShowByUrlRule()) {
PrivacyManager.markSkipped()
}
},
onLaunch: async function(options) {
// 方式:支持快应用,从url中query部分获取uniacid,或useragent中获取uniacid
if(options.query.uniacid){
// ============================================================
// 主题提前加载(关键):让首屏渲染前 CSS 变量已挂上,避免闪一下
// ============================================================
// ---- 0) 同步预热: 立即读 storage 拿 preset,触发 require(不 await)
// 目的: 让 loadTheme 的 require 提前进入 microtask,后续 await 几乎瞬时
const cached = uni.getStorageSync('themeStyle');
let presetName = themeConfig.defaultTheme;
if (cached) {
presetName = (typeof cached === 'object') ? cached.name : cached;
}
// 触发 preset require(不 await,缓存 promise 到 configExternal.loadedConfigs)
configExternal.loadTheme(presetName);
// ---- 1) uniacid 立即写入(后续所有 HTTP 都要用到)
const uniacidChanged = options.query && options.query.uniacid && String(uni.getStorageSync('uniacid') || '') !== String(options.query.uniacid);
if (options.query && options.query.uniacid) {
uni.setStorageSync('uniacid', options.query.uniacid);
}
// 关键: 即便 uniacid 未变化 (首次启动 options.query 没传 uniacid),
// 也要尝试从 storage 拿真实 uniacid 并设置 PrivacyManager 的 persist key
// 否则 App.vue 顶层用 _anon 占位, 后续 persistRules 写到 _anon key 下,
// 下次冷启动 (有 uniacid) 切到 uniacid key 时读不到上次结果
try {
const _nowUniacid = uni.getStorageSync('uniacid')
const _newPersistKey = _nowUniacid
? ('privacy_url_rules_' + _nowUniacid)
: 'privacy_url_rules__anon'
if (_newPersistKey !== _persistKey) {
PrivacyManager.setStorageKey(_newPersistKey)
const _newPersisted = PrivacyManager.loadPersistedRules()
if (_newPersisted && _newPersisted.mode && Array.isArray(_newPersisted.patterns)) {
PrivacyManager.setUrlRules(_newPersisted)
} else {
PrivacyManager.setUrlRules(PRIVACY_URL_RULES_BASE)
}
}
} catch (e) {}
if (uniacidChanged) {
try { Lang.onUniacidChange(); } catch (e) {}
try { ThemeOverride.onUniacidChange(); } catch (e) {}
// 切租户: 切换 PrivacyManager 持久化 key 并重新应用本地 base
// (远程 patch 由后续 /api/config/init 重新下发并融合)
try {
const newUniacid = String(options.query.uniacid)
const newPersistKey = newUniacid
? ('privacy_url_rules_' + newUniacid)
: 'privacy_url_rules__anon'
PrivacyManager.setStorageKey(newPersistKey)
PrivacyManager.setBaseRules(PRIVACY_URL_RULES_BASE)
// 切租户: 重新加载该租户上次持久化的规则
// 无持久化值则退化为 base
const _newPersisted = PrivacyManager.loadPersistedRules()
if (_newPersisted && _newPersisted.mode && Array.isArray(_newPersisted.patterns)) {
PrivacyManager.setUrlRules(_newPersisted)
} else {
PrivacyManager.setUrlRules(PRIVACY_URL_RULES_BASE)
}
} catch (e) {}
try { uni.$emit && uni.$emit('uniacid:changed'); } catch (e) {}
}
// remote-only 模式:
// H5: main.js 已 await boot 完成, 这里秒回 (splash 也由 main.js 全权负责)
// 小程序/鸿蒙: main.js 同步 $mount() 之前已经调用 splashState.show(),
// 这里不需要重复调用
const langBoot = Lang.boot();
this.$langReady = langBoot;
// ---- 2) 启动期关键资源就绪 (并行 + 显式 await)
// 隐私弹窗的诉求: 必须在 i18n + theme + remote-config 三态都就绪后才弹
// 这里把三个通道收敛为一个 await 链, 不再用 fire-and-forget
// 任何通道自身有超时保护 (Lang.bootTimeout=langConfig.remote.bootTimeout=5000,
// ThemeOverride.bootTimeout=themeConfig.overrideRemote.bootTimeout=5000)
// 总超时熔断走 configExternal.getPrivacyBootTimeout() (默认取两者最大值+1000ms)
// 业务侧想"宁愿晚一点也要全资源就绪" → 调大 privacyConfig.bootTimeout
// 业务侧想"快速失败" → 调小或关闭 privacyConfig.waitChannels
const _i18nDone = langBoot.then((res) => {
// 进度上报: i18n 完成 → 30%
try { splashState.reportProgress('lang', { source: 'channel' }); } catch (e) {}
// i18n fallback toast (原逻辑保留)
if (res && res.status === 'fail' && res.reason && res.reason !== 'unknown') {
if (globalThis.__i18nFallbackToastShown) return res;
globalThis.__i18nFallbackToastShown = true;
setTimeout(() => {
try {
uni.showToast({
title: `Failed to load i18n. ${res.reason} Please check your network and try again.`,
icon: 'none',
duration: 10000,
});
} catch (e) {}
}, 3000);
}
return res;
}, (e) => {
console.warn('[i18n] boot fail', e);
try { splashState.reportProgress('lang', { source: 'error' }); } catch (e) {}
return { ok: false, source: 'remote-failed', status: 'fail', reason: 'exception', lang: '' };
})
const _themeFirstApply = this.$store.dispatch('applyThemeWithRemote', presetName)
.then(() => {
try { splashState.reportProgress('theme', { source: 'channel' }); } catch (e) {}
})
.catch(e => {
console.warn('[theme] pre-apply fail', e);
try { splashState.reportProgress('theme', { source: 'error' }); } catch (e) {}
return null
})
const _themeOverride = ThemeOverride.boot()
.then(() => {
try { splashState.reportProgress('override', { source: 'channel' }); } catch (e) {}
})
.catch(e => {
console.warn('[theme] boot fail', e);
try { splashState.reportProgress('override', { source: 'error' }); } catch (e) {}
return null
})
// /api/config/init 走 fire-and-forget:
// - race 不再等它, popup 可以更早弹出
// - 远程 patch (privacy_url_rules 等) 后续异步到达时通过 applyWithMerge 触发双阶段弹窗
// - 失败也不阻塞 boot 链路
//
// 进度上报单独走 (展示效果, 不依赖 _remoteConfig resolve)
this.$store.dispatch('init').then(() => {
try { splashState.reportProgress('config', { source: 'channel' }); } catch (e) {}
}).catch(e => {
console.warn('[config] init fail', e);
try { splashState.reportProgress('config', { source: 'error' }); } catch (e) {}
})
const _remoteConfig = Promise.resolve(null) // 占位 promise, race 不再等 init
// 注入启动期等待通道 → ConfigExternal 持有
// PrivacyManager.show() 时通过 getPrivacyReadyGuard(waitChannels) 自动拼成 readyGuard
configExternal.setReadyWaiters({
lang: _i18nDone,
theme: _themeFirstApply,
themeOverride: _themeOverride,
remoteConfig: _remoteConfig,
})
const _privacyBootTimeout = configExternal.getPrivacyBootTimeout()
const _bootRaceResult = await Promise.race([
Promise.all([_i18nDone, _themeFirstApply, _themeOverride, _remoteConfig]),
new Promise(resolve => setTimeout(() => resolve('timeout'), _privacyBootTimeout))
])
if (_bootRaceResult === 'timeout') {
// race 超时上报 (source: 'timeout', 不允许 percent 后退, 已有最大值为准)
try { splashState.reportProgress('config', { percent: 80, source: 'timeout' }); } catch (e) {}
}
// privacy 阶段开始上报
try { splashState.reportProgress('privacy', { source: 'channel' }); } catch (e) {}
// 隐私协议弹窗: 启动期关键资源 (i18n/theme/remote-config) 就绪后触发
// 通过 PrivacyManager → uni.$emit('privacy:show') 通知当前页面的 privacy-popup 组件
// 只弹一次: 同意后写 storage,后续不再弹
// 异步查询平台隐私状态(微信/鸿蒙), H5 同步返回
// H5 直访特定 URL(子串匹配)时跳过本次弹窗,不写 storage,下次正常访问其他页面还会弹
// urlFallback: 首次启动 onLaunch 时 getCurrentPages 还没页面, 用 onLaunch options 兜底
// readyGuard: 双保险 — 若调用方没传, PrivacyManager 内部从 _externalReadyGuard 取
// (= ConfigExternal.getPrivacyReadyGuard(privacyConfig.waitChannels))
// 二次 await 仍保留: race 后还有可能某个通道没真完成, 二次 await 兜底
try {
await PrivacyManager.show({
urlFallback: _buildPrivacyUrlFallback(options),
readyGuard: Promise.all([_i18nDone, _themeFirstApply, _themeOverride, _remoteConfig]),
})
} catch (e) { console.warn('[privacy] show fail', e); }
// splash 必须在隐私弹窗决策后再 hide (否则 splash 关掉瞬间弹窗还没渲染, 视觉闪一下)
// mode='fast': 隐私弹窗即将出现, splash 用 80ms 短动画, 让 modal 更快接管视觉
// 避免 splash 和弹窗同时显示造成的"双遮罩"感, 减少约 400ms 启动时间
// 只有 remote-only 模式才用了 splash (其他场景 src 模式不需要等远端)
// #ifndef H5
const _needSplash = typeof Lang !== 'undefined' && Lang.isRemoteOnly && Lang.isRemoteOnly();
if (_needSplash) {
splashState.hide({ reason: 'boot-complete', mode: 'fast' });
}
// #endif
// ---- 3) 远端就绪后,主题再 apply 一次(preset + remote 合并 )
// 这一次 setThemeStyle + themeColorSet 是同步路径(preset 已在 cache,remote 也在 cache)
// 如果跟 step 2 的 apply 值相同,Vuex 会重复 commit 但页面无视觉变化
await this.$store.dispatch('applyThemeWithRemote', presetName);
// ============================================================
// 后续: 监听器 / 平台条件 / 其它 storage commit(全部同步/轻量)
// ============================================================
// 监听远端翻译更新事件(管理后台改了词条后由后端推送 / 主动 reload)
// 注意:lang.js 内 emitUpdated 已经 commit 了 setComponentRefresh,这里
// 只做副作用(navigation title 等),不重复 forceUpdate
uni.$on && uni.$on('lang:updated', (info) => {
if (info && info.lang) {
Lang.refresh(true); // true = 显式推送 emitUpdated(虽然 loadOverrides 内部已发,这里保险起见)
}
});
// 监听远端主题覆写更新(管理后台改了 token 后,本地 Vuex 重新合并并应用)
// 关键: 走 applyThemeWithRemote action,保留原 setThemeStyle/themeColorSet 链路不动
uni.$on && uni.$on('theme:updated', () => {
// 重新从 storage 读 preset(可能用户在管理页切了预设)
const cur = uni.getStorageSync('themeStyle');
const curName = (cur && typeof cur === 'object') ? cur.name : (cur || 'default');
this.$store.dispatch('applyThemeWithRemote', curName);
});
// 监听 uniacid 切换: 通知主题运行时清旧租户缓存,下次 refresh 拿到新值
uni.$on && uni.$on('uniacid:changed', () => {
try { ThemeOverride.onUniacidChange(); } catch (e) {}
});
// i18n 远端拉取失败的 toast 提示已迁移到上方 boot() 完成的 then() 中,
// 直接根据 boot 返回值判断,不再依赖 lang:fallback 事件
uni.hideTabBar();
// #ifdef MP
const updateManager = uni.getUpdateManager();
updateManager.onCheckForUpdate(function(res) {
// 请求完新版本信息的回调
});
updateManager.onUpdateReady(function(res) {
uni.showModal({
title: '更新提示',
content: '新版本已经准备好,是否重启应用?',
success(res) {
if (res.confirm) {
// 新的版本已经下载好,调用 applyUpdate 应用新版本并重启
updateManager.applyUpdate();
}
}
if (uni.getUpdateManager) {
const updateManager = uni.getUpdateManager();
updateManager.onCheckForUpdate(function(res) {
// 请求完新版本信息的回调
});
});
updateManager.onUpdateFailed(function(res) {
// 新的版本下载失败
});
updateManager.onUpdateReady(function(res) {
uni.showModal({
title: Lang.lang('common.updateTip'),
content: Lang.lang('common.updateReady'),
success(res) {
if (res.confirm) {
// 新的版本已经下载好,调用 applyUpdate 应用新版本并重启
updateManager.applyUpdate();
}
}
});
});
updateManager.onUpdateFailed(function(res) {
// 新的版本下载失败
});
}
// #endif
// #ifdef H5
@@ -45,27 +360,22 @@
}
// #endif
uni.onNetworkStatusChange(function(res) {
if (!res.isConnected) {
uni.showModal({
title: '网络失去链接',
content: '请检查网络链接',
showCancel: false
});
}
});
this.$store.dispatch('init');
// 存储到store中
// 主题风格
if (uni.getStorageSync('themeStyle')) {
const themeData = await configExternal.loadTheme(uni.getStorageSync('themeStyle'));
this.$store.commit('setThemeStyle', themeData);
this.$store.dispatch('themeColorSet');
if (uni.onNetworkStatusChange) {
uni.onNetworkStatusChange(function(res) {
if (!res.isConnected) {
uni.showModal({
title: Lang.lang('common.networkLost'),
content: Lang.lang('common.networkCheck'),
showCancel: false
});
}
});
}
// /api/config/init 已在 step 2.5 await 过 (含 800ms 超时), 此处不再重复触发
// 原 fire-and-forget 注释: 不阻塞后续同步 commit
// 现在 init 已被升级为 "首次配置等待通道", 这里留空以避免重复 dispatch
// 插件是否存在
if (uni.getStorageSync('addonIsExist')) {
this.$store.commit('setAddonIsExist', uni.getStorageSync('addonIsExist'));
@@ -266,7 +576,6 @@
imgUrl: this.$util.img(share_data.imgUrl)
},
res => {
console.log(res);
}
);
}

View File

@@ -30,7 +30,7 @@ image {
/* #ifdef H5 */
height: calc(100vh - 88rpx);
/* #endif */
/* #ifdef MP-WEIXIN */
/* #ifdef MP */
height: 100vh;
/* #endif */
}

View File

@@ -5705,9 +5705,9 @@
@font-face {
font-family: "iconj"; /* Project id 1752049 */
src: url('//at.alicdn.com/t/c/font_1752049_n0jw9cvfunm.woff2?t=1727498649486') format('woff2'),
url('//at.alicdn.com/t/c/font_1752049_n0jw9cvfunm.woff?t=1727498649486') format('woff'),
url('//at.alicdn.com/t/c/font_1752049_n0jw9cvfunm.ttf?t=1727498649486') format('truetype');
src: url('https://at.alicdn.com/t/c/font_1752049_n0jw9cvfunm.woff2?t=1727498649486') format('woff2'),
url('https://at.alicdn.com/t/c/font_1752049_n0jw9cvfunm.woff?t=1727498649486') format('woff'),
url('https://at.alicdn.com/t/c/font_1752049_n0jw9cvfunm.ttf?t=1727498649486') format('truetype');
}
.iconj {

View File

@@ -23,6 +23,22 @@ page {
$base-color: #ff4544;
$base-help-color: #ffb644; //辅助颜色
--tab-bar-height: 112rpx;
/* ============================================================
* 浮动按钮 / 回到顶部按钮 的全局尺寸变量
* ------------------------------------------------------------
* to-top.vue 和 hover-nav.vue 共同使用这些变量,
* 保证两者的位置关系(垂直中心对齐、上下间距)始终一致。
*
* 注意:这些是"权威源",如果改了这里,JS 计算的 containerRight
* / containerBottom 在 H5 下会自动跟随变化(JS 读取 :root 变量)。
* 小程序环境没有 document,JS 端用 fallback 默认值 46/72/100/272,
* 改这里的同时也需要同步更新 hover-nav.vue 的 data 默认值。
* ============================================================ */
--top-btn-right: 46rpx; // 回到顶部按钮距屏幕右边
--top-btn-bottom: 272rpx; // 回到顶部按钮距屏幕底部
--top-btn-size: 72rpx; // 回到顶部按钮边长(正方形)
--floating-btn-width: 100rpx; // hover-nav 浮动容器宽度
}
.uni-input-input:-webkit-autofill {

View File

@@ -25,7 +25,7 @@ view {
background-size: 100% 260rpx;
background-repeat: no-repeat;
// #ifdef MP-WEIXIN
// #ifdef MP
background-size: 100% 380rpx;
// #endif
@@ -52,7 +52,7 @@ view {
background: linear-gradient(180deg, $base-color 10%, $color-bg 100%);
background-size: 100% 260rpx;
// #ifdef MP-WEIXIN
// #ifdef MP
background-size: 100% 380rpx;
// #endif
@@ -462,7 +462,10 @@ view {
background: #f6f6cb;
text-align: left;
padding: 10rpx 20rpx;
color: #FF0000;
// P0: 角标红 → var(--goods-cart-num-corner)
// 注: black preset 值是 #FF0000, default 是 #FC5227 — var() 兼顾
// 兼容: 微信小程序 / 鸿蒙元服务 — color 接受 var() 无问题
color: var(--goods-cart-num-corner, #FF0000);
}
.order-submit {
position: fixed;
@@ -1286,9 +1289,13 @@ view {
margin-right: 10rpx;
line-height: 1;
font-size: 36rpx;
background-image:linear-gradient(156deg, #814635 0%, #3A221B 100%);
-webkit-background-clip:text;
-webkit-text-fill-color:transparent;
// P0: 会员图标渐变 → var(--member-icon-grad-start/end)
// 注: 暂用 placeholder 命名,后续如需主题化可加到 style_color.js
// 兼容: 微信小程序 / 鸿蒙元服务 — linear-gradient 嵌套 var() 现代 runtime 支持
background: #814635; // 兜底
background-image: linear-gradient(156deg, var(--member-icon-grad-start, #814635) 0%, var(--member-icon-grad-end, #3A221B) 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
.info{

View File

@@ -1,9 +1,21 @@
import Config from './config.js'
import http from './http.js'
import store from '@/store/index.js'
import lang from './lang.js'
let currentConversationId = null;
const CONVERSATION_KEY = 'ai_conversation_id';
export const CONVERSATION_KEY = 'ai_conversation_id';
/**
* 获取域名配置参数(避免重复代码)
*/
function getDomainParams() {
return {
imgDomain: Config.imgDomain,
h5Domain: Config.h5Domain,
baseUrl: Config.baseUrl
};
}
// 初始化时从本地读取会话ID
try {
@@ -15,32 +27,234 @@ try {
console.warn('读取会话ID失败:', e);
}
const GUEST_ID_KEY = 'ai_guest_user_id';
/**
* 获取用户ID:已登录返回 memberId,未登录生成访客唯一标识并持久化
*/
function getUserId() {
const memberId = store.state.memberInfo?.id;
if (memberId) return memberId;
let guestId;
try {
guestId = uni.getStorageSync(GUEST_ID_KEY);
} catch (e) { /* ignore */ }
if (!guestId) {
guestId = 'guest_' + Date.now() + '_' + Math.random().toString(36).slice(2, 10);
try {
uni.setStorageSync(GUEST_ID_KEY, guestId);
} catch (e) { /* ignore */ }
}
return guestId;
}
// #ifdef MP
// ================================
// WebSocket 长连接管理(微信小程序)
// ================================
let wsSocketTask = null;
let wsAuthenticated = false;
let wsConnected = false;
let wsConnectionPromise = null;
function getWsDomain() {
var match = Config.baseUrl.match(/^(?:https?:\/\/|wss?:\/\/)([^\/\s:?#]+(?::\d+)?)/);
return match ? match[1] : '';
}
function resetWsState() {
wsSocketTask = null;
wsAuthenticated = false;
wsConnected = false;
wsConnectionPromise = null;
}
/**
* 确保 WebSocket 已连接并认证,返回一个 Promise
* 连接建立后保持不断开,后续可复用
*/
function ensureWebSocketConnected() {
if (wsConnected && wsAuthenticated) {
return Promise.resolve();
}
if (wsConnectionPromise) {
return wsConnectionPromise;
}
wsConnectionPromise = new Promise(function(resolve, reject) {
var domain = getWsDomain();
if (!domain) {
wsConnectionPromise = null;
reject(new Error(lang.lang('aiService.wsDomainInvalid')));
return;
}
var wssUrl = 'wss://' + domain + '/ws/aikefu';
wsConnected = false;
wsAuthenticated = false;
wsSocketTask = wx.connectSocket({ url: wssUrl, header: {} });
// 获取认证参数(独立函数,不使用 this)
var _uniacid = uni.getStorageSync('uniacid') || Config.uniacid;
var _token = store.state.token || 'test_token';
var _userId = getUserId();
wsSocketTask.onOpen(function() {
wsConnected = true;
wsSocketTask.send({
data: JSON.stringify({
action: 'auth',
uniacid: _uniacid,
token: _token,
user_id: _userId
})
});
});
wsSocketTask.onMessage(function(res) {
try {
var data = JSON.parse(res.data);
// Auth 响应
if (data.type === 'auth_success') {
wsAuthenticated = true;
resolve();
return;
}
if (data.type === 'auth_failed') {
wsAuthenticated = false;
wsConnectionPromise = null;
reject(new Error(lang.lang('aiService.wsAuthFailed')));
return;
}
// 以下为聊天消息响应,只在有活跃消息时处理
if (!wsMessageActive) return;
if (data.event === 'message') {
var text = data.answer || data.content || data.text || '';
// 兼容嵌套 data.data.content 格式
if (!text && data.data) {
text = data.data.content || data.data.answer || '';
}
wsMessageContent += text;
if (wsMessageOnChunk) wsMessageOnChunk(text);
} else if (data.event === 'message_end' || data.event === 'done') {
// 兼容两种结束信号:message_end(流结束)或 done(服务端完成)
// 兼容两种数据层级:conversation_id 可能在顶层或 data.data 中
var conversationId = data.conversation_id || (data.data && data.data.conversation_id) || '';
console.log('[AI WS] 流结束信号, event:', data.event, 'type:', data.type, 'conversationId:', conversationId, '当前内存:', currentConversationId);
// 保存会话ID(独立函数,不使用 this)
if (conversationId) {
if (conversationId !== currentConversationId) {
currentConversationId = conversationId;
try {
uni.setStorageSync(CONVERSATION_KEY, conversationId);
console.log('[AI WS] 会话ID已持久化到 storage:', conversationId);
} catch (e) {
console.error('保存会话ID失败:', e);
}
}
}
var content = wsMessageContent;
var convId = conversationId;
// 重置消息状态,但不断开连接
wsMessageActive = false;
wsMessageContent = '';
if (wsMessageOnComplete) wsMessageOnComplete({ content: content, conversation_id: convId });
if (wsMessageResolve) wsMessageResolve({ content: content, conversation_id: convId });
} else {
// 兜底日志:打印所有未识别的消息类型
console.log('[AI WS] 未识别的消息:', JSON.stringify(data).substring(0, 200));
}
} catch (e) {
console.error('WebSocket 消息解析失败:', e, '原始数据:', res.data);
}
});
wsSocketTask.onError(function(err) {
console.error('WebSocket 连接失败:', err);
var prevReject = wsMessageReject;
resetWsState();
resetWsMessageState();
if (prevReject) prevReject(new Error(lang.lang('aiService.wsConnectionFailed')));
reject(new Error(lang.lang('aiService.wsConnectionFailed')));
});
wsSocketTask.onClose(function() {
console.warn('WebSocket 连接已关闭');
var prevReject = wsMessageReject;
resetWsState();
resetWsMessageState();
if (prevReject) prevReject(new Error(lang.lang('aiService.wsConnectionClosed')));
});
});
return wsConnectionPromise;
}
// 当前消息的回调状态(只支持串行)
var wsMessageResolve = null;
var wsMessageReject = null;
var wsMessageOnChunk = null;
var wsMessageOnComplete = null;
var wsMessageContent = '';
var wsMessageActive = false;
function resetWsMessageState() {
wsMessageResolve = null;
wsMessageReject = null;
wsMessageOnChunk = null;
wsMessageOnComplete = null;
wsMessageContent = '';
wsMessageActive = false;
}
/**
* 断开 WebSocket 长连接
*/
function disconnectWebSocket() {
if (wsSocketTask) {
try { wsSocketTask.close(); } catch (e) { /* ignore */ }
}
resetWsState();
resetWsMessageState();
}
// #endif
export default {
/**
* 获取uniacid
* @returns {number} uniacid
*/
getUniacid() {
return uni.getStorageSync('uniacid') || Config.uniacid; // 从缓存中获取uniacid,或使用默认uniacid
},
/**
* 发送普通消息(blocking 模式)
*/
async sendMessage(message, options = {}) {
try {
const aiConfig = store.getters.globalAIKefuConfig;
const params = {
url: '/api/kefu/chat',
data: {
user_id: store.state.memberInfo?.id || 'anonymous',
user_id: getUserId(),
stream: false,
inputs: {},
query: message,
response_mode: 'blocking', // 强制 blocking
user: store.state.memberInfo?.id || 'anonymous',
conversation_id: this.getConversationId() || ''
user: getUserId(),
conversation_id: this.getConversationId() || '',
...getDomainParams()
},
header: {
'Content-Type': 'application/json'
}
};
console.log('Sending blocking request to:', params.url);
console.log('Request data:', params.data);
const response = await http.sendRequest({
...params,
async: false
@@ -52,63 +266,55 @@ export default {
}
return result;
} catch (error) {
console.error('Dify API请求失败:', error);
throw new Error('AI服务暂时不可用,请稍后重试');
console.error('[AI Service] AiChat API请求失败,详细错误:', error);
console.error('[AI Service] 错误堆栈:', error.stack);
// 打印更多信息帮助调试
console.error('[AI Service] store 状态:', {
memberInfo: store.state.memberInfo,
uniacid: this.getUniacid(),
token: store.state.token
});
throw new Error(lang.lang('aiService.serviceUnavailable'));
}
},
/**
* 流式消息入口(自动适配平台)
* 微信小程序:复用长连接 WebSocket
*/
async sendStreamMessage(message, onChunk, onComplete) {
// #ifdef MP-WEIXIN
// 微信小程序:降级为普通请求 + 前端打字模拟
// #ifdef MP
// 先确保连接已就绪
try {
const result = await this.sendMessage(message);
const content = result.content || '';
const conversationId = result.conversationId || '';
// 保存会话ID(确保连续对话)
if (conversationId) {
this.setConversationId(conversationId);
}
// 模拟打字效果
let index = 0;
const chunkSize = 2; // 每次显示2个字符
return new Promise((resolve) => {
const timer = setInterval(() => {
if (index < content.length) {
const chunk = content.substring(index, index + chunkSize);
index += chunkSize;
if (onChunk) onChunk(chunk);
} else {
clearInterval(timer);
if (onComplete) {
onComplete({
content: content,
conversation_id: conversationId
});
}
resolve({ content, conversation_id: conversationId });
}
}, 80); // 打字速度:80ms/次
});
} catch (error) {
console.error('小程序流式消息降级失败:', error);
if (onComplete) {
onComplete({ error: error.message || '发送失败' });
}
throw error;
await ensureWebSocketConnected();
} catch (e) {
if (onComplete) onComplete({ error: e.message });
throw e;
}
// #endif
// #ifdef H5
// H5:使用真实流式(EventSource / Fetch)
return this.sendHttpStream(message, onChunk, onComplete);
// 设置当前消息回调
wsMessageContent = '';
wsMessageActive = true;
wsMessageOnChunk = onChunk || null;
wsMessageOnComplete = onComplete || null;
return new Promise((resolve, reject) => {
wsMessageResolve = resolve;
wsMessageReject = reject;
wsSocketTask.send({
data: JSON.stringify({
action: 'chat',
uniacid: this.getUniacid(),
query: message,
user_id: getUserId(),
conversation_id: this.getConversationId() || '',
...getDomainParams()
})
});
});
// #endif
},
/**
* HTTP 流式请求(仅 H5 使用)
*/
@@ -123,20 +329,19 @@ export default {
'Accept': 'text/event-stream',
},
body: JSON.stringify({
uniacid: store.state.uniacid || '1',
uniacid: this.getUniacid(),
token: store.state.token || 'test_token',
inputs: {},
query: message,
response_mode: 'streaming',
user_id: store.state.memberInfo?.id || 'anonymous',
conversation_id: this.getConversationId() || ''
user_id: getUserId(),
conversation_id: this.getConversationId() || '',
...getDomainParams()
})
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
if (!response.body) {
throw new Error('响应体不可用');
if (!response.ok || !response.body) {
throw new Error(lang.lang('aiService.invalidResponse'));
}
const reader = response.body.getReader();
@@ -145,50 +350,75 @@ export default {
let content = '';
let conversationId = '';
function processBuffer(buf, callback) {
const lines = buf.split('\n');
buf = lines.pop() || '';
for (const line of lines) {
const trimmed = line.trim();
if (trimmed.startsWith('data:')) {
const jsonStr = trimmed.slice(5).trim();
if (jsonStr) {
try {
const data = JSON.parse(jsonStr);
if (data.event === 'message') {
const text = data.answer || data.text || '';
content += text;
callback(text);
}
if (data.conversation_id) {
conversationId = data.conversation_id;
}
if (data.event === 'message_end') {
// 可选:提前完成
}
} catch (e) {
console.warn('解析流数据失败:', e);
}
}
}
}
return buf;
}
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
buffer = processBuffer(buffer, (chunk) => {
if (onChunk) onChunk(chunk);
});
// 按行分割,保留不完整的最后一行
const lines = buffer.split('\n');
buffer = lines.pop() || ''; // 未完成的行留到下次
for (const line of lines) {
const trimmed = line.trim();
if (trimmed.startsWith('data:')) {
try {
const jsonStr = trimmed.slice(5).trim();
if (jsonStr && jsonStr !== '[DONE]') {
const data = JSON.parse(jsonStr);
if (data.event === 'message') {
var text = data.answer || data.text || '';
// 兼容嵌套 data.data 格式
if (!text && data.data) {
text = data.data.content || data.data.answer || '';
}
content += text;
if (onChunk) onChunk(text);
}
// 兼容两种层级:conversation_id 可能在顶层或 data.data 中
var cid = data.conversation_id || (data.data && data.data.conversation_id) || '';
if (cid) {
conversationId = cid;
}
if (data.event === 'message_end' || data.event === 'done') {
console.log('[AI SSE] 收到完成信号:', data.event, 'conversationId:', cid);
}
}
} catch (e) {
console.warn('解析失败:', e, line);
}
}
}
}
// 处理最后残留的 buffer(如果有)
if (buffer.trim().startsWith('data:')) {
try {
const jsonStr = buffer.trim().slice(5);
if (jsonStr) {
const data = JSON.parse(jsonStr);
if (data.event === 'message') {
var text = data.answer || data.text || '';
if (!text && data.data) {
text = data.data.content || data.data.answer || '';
}
content += text;
if (onChunk) onChunk(text);
}
var cid = data.conversation_id || (data.data && data.data.conversation_id) || '';
if (cid) {
conversationId = cid;
}
}
} catch (e) {
console.warn('最后 buffer 解析失败:', e);
}
}
console.log('[AI SSE] 流完成, conversationId:', conversationId, 'content长度:', content.length);
if (onComplete) {
onComplete({
content,
conversation_id: conversationId
});
onComplete({ content, conversation_id: conversationId });
}
return { content, conversation_id: conversationId };
} catch (error) {
@@ -196,11 +426,6 @@ export default {
throw error;
}
// #endif
// #ifdef MP-WEIXIN
// 理论上不会执行到这里,但防止 fallback
return this.sendStreamMessage(message, onChunk, onComplete);
// #endif
},
/**
@@ -215,7 +440,7 @@ export default {
messageId: response.data?.message_id
};
} else {
throw new Error(response.message || 'AI服务返回错误');
throw new Error(response.message || lang.lang('aiService.serviceResponseError'));
}
},
@@ -259,9 +484,11 @@ export default {
const params = {
url: '/api/kefu/createConversation',
data: {
uniacid: store.state.uniacid,
user_id: store.state.memberInfo?.id || 'anonymous',
member_id: store.state.memberInfo?.id || '',
uniacid: this.getUniacid(),
token: store.state.token || 'test_token',
user_id: getUserId(),
member_id: getUserId(),
...getDomainParams()
},
header: {
'Content-Type': 'application/json'
@@ -288,16 +515,46 @@ export default {
.filter(item => item === 'healthy').length > 0;
return {
available,
reason: available ? '服务正常' : '服务异常'
reason: available ? lang.lang('aiService.statusNormal') : lang.lang('aiService.statusAbnormal')
};
} catch (error) {
return {
available: false,
reason: '服务检查失败'
reason: lang.lang('aiService.statusCheckFailed')
};
}
},
/**
* 获取服务配置信息
*/
async getServiceConfig() {
try {
const params = {
url: '/api/kefu/info',
data: {
uniacid: this.getUniacid(),
token: store.state.token || 'test_token',
user_id: getUserId(),
member_id: getUserId(),
locale: lang.getCurrentLocale()
},
header: {
'Content-Type': 'application/json'
}
};
const response = await http.sendRequest({
...params,
async: false,
});
console.log('[AI Service] getServiceConfig response:', JSON.stringify(response));
return response.data;
} catch (error) {
console.error('[AI Service] getServiceConfig error:', error);
return null;
}
},
/**
* 清除会话历史(调用后端接口)
*/
@@ -305,7 +562,10 @@ export default {
try {
const response = await http.sendRequest({
url: '/api/kefu/clear-conversation',
data: { conversation_id: conversationId },
data: {
conversation_id: conversationId,
...getDomainParams()
},
async: false
});
return response.success;
@@ -321,16 +581,18 @@ export default {
async getConversationHistory(params = {}) {
try {
if (!params.conversation_id) {
throw new Error('会话ID(conversation_id)是必填参数');
throw new Error(lang.lang('aiService.conversationIdRequired'));
}
console.log('[AI History] 请求历史, conversation_id:', params.conversation_id, 'limit:', params.limit);
const requestData = {
uniacid: params.uniacid || store.state.uniacid || '1',
uniacid: params.uniacid || this.getUniacid(),
conversation_id: params.conversation_id,
user_id: params.user_id || store.state.memberInfo?.id || 'anonymous',
user_id: params.user_id || getUserId(),
limit: params.limit || 20,
offset: params.offset || 0,
member_id: params.member_id || store.state.memberInfo?.id || '',
token: params.token || ''
member_id: params.member_id || getUserId(),
token: params.token || '',
...getDomainParams()
};
const response = await http.sendRequest({
url: '/api/kefu/getHistory',
@@ -349,11 +611,11 @@ export default {
page_info: response.data?.page_info || { limit: 20, offset: 0 }
};
} else {
throw new Error(response.message || '获取会话历史失败');
throw new Error(response.message || lang.lang('aiService.getHistoryFailed'));
}
} catch (error) {
console.error('获取会话历史失败:', error);
throw new Error(error.message || '获取会话历史时发生错误,请稍后重试');
throw new Error(error.message || lang.lang('aiService.getHistoryError'));
}
},
@@ -369,13 +631,17 @@ export default {
if (window.currentEventSource) {
window.currentEventSource.close();
}
const params = new URLSearchParams({
uniacid: store.state.uniacid || '1',
user_id: store.state.memberInfo?.id || '123456',
const paramsObj = {
uniacid: this.getUniacid(),
user_id: getUserId(),
member_id: getUserId(),
token: store.state.token || 'test_token',
query: message,
conversation_id: conversationId || '',
stream: 'true'
});
stream: 'true',
...getDomainParams()
};
const params = new URLSearchParams(paramsObj);
const url = `${Config.baseUrl}/api/kefu/chat?${params.toString()}`;
try {
const eventSource = new EventSource(url);
@@ -400,7 +666,7 @@ export default {
};
eventSource.onerror = (error) => {
console.error('EventSource错误:', error);
if (onError) onError({ error: '连接失败' });
if (onError) onError({ error: lang.lang('aiService.connectionFailed') });
window.currentEventSource = null;
};
return eventSource;
@@ -410,7 +676,7 @@ export default {
return null;
}
// #endif
// #ifdef MP-WEIXIN
// #ifdef MP
console.warn('chatWithEventSource 不支持微信小程序');
return null;
// #endif
@@ -426,9 +692,23 @@ export default {
onComplete?.({ message: res.content, conversation_id: res.conversation_id });
});
// #endif
// #ifdef MP-WEIXIN
// #ifdef MP
console.warn('chatWithFetchStream 不支持微信小程序');
return null;
// #endif
}
},
// #ifdef MP
/**
* [微信小程序] 断开 WebSocket 长连接(页面离开时调用)
*/
disconnectWebSocket() {
disconnectWebSocket();
},
// #endif
// #ifdef H5
disconnectWebSocket() {
// H5 无 WebSocket 长连接,无需操作
},
// #endif
};

View File

@@ -8,9 +8,11 @@ export default {
/**
* 获取用户登录凭证code
*/
getCode(callback) {
getCode(callback, fallbackFunc) {
console.log(`-----> auth.js getCode`)
// 微信小程序
// #ifdef MP-WEIXIN
console.log(`微信小程序登录`)
uni.login({
provider: 'weixin',
timeout: 3000,
@@ -29,12 +31,15 @@ export default {
.unionid;
typeof callback == 'function' && callback(this.authInfo);
} else {
fallbackFunc && fallbackFunc(res);
this.$util.showToast({
title: res.message ? res.message : '小程序配置错误'
});
title: res.message ? res.message : this.$lang('auth.miniProgramConfigError')
});
}
}
})
} else {
fallbackFunc && fallbackFunc(res);
}
},
fail: (res) => {
@@ -46,6 +51,7 @@ export default {
});
}
// #endif
fallbackFunc && fallbackFunc(res);
}
})
// #endif
@@ -66,9 +72,10 @@ export default {
.user_id;
typeof callback == 'function' && callback(this.authInfo);
} else {
fallbackFunc && fallbackFunc(res);
this.$util.showToast({
title: res.message ? res.message : '小程序配置错误'
});
title: res.message ? res.message : this.$lang('auth.miniProgramConfigError')
});
}
}
})
@@ -94,6 +101,9 @@ export default {
if (res.code >= 0) {
location.href = res.data;
}
},
fail: err => {
fallbackFunc && fallbackFunc(err);
}
});
}

View File

@@ -3,20 +3,83 @@
// 语言包配置
export const langConfig = {
// 语言列表
// 语言列表 — 与后端 Lang.php::overrides() 白名单对齐
// 增删需要后端同步改 LangOverrideModel::normalizeAppType 旁的 $allow_lang
langList: ['zh-cn', 'en-us'],
// 默认语言
defaultLang: 'zh-cn',
// 语言包加载方式:'lazy'(按需加载)或 'preload'(预加载)
loadMode: 'lazy'
loadMode: 'lazy',
// 数据源开关
// 数据源开关
// local : 纯本地包,忽略 remote
// remote : 本地兜底 + 后端 KV 覆写(首屏强依赖,见 bootTimeout)
// hybrid : 同 remote,后端不可用时用本地
// remote-only : 完全依赖后端 /api/lang/bundle,本地 lang/ 目录可删除
source: 'remote-only',
// 远端覆写相关
remote: {
overridesUrl: '/api/lang/overrides',
// bundle 接口(remote-only 模式下使用)
bundleUrl: '/api/lang/bundle',
// diff 接口(预留)
diffUrl: '/api/lang/diff',
// 首屏强依赖远端翻译(多租户文案强隔离),阻塞启动
// 但必须有上限避免白屏
// 2026-07-02: 从 2000 改为 5000 — 慢启动场景下,给首屏渲染更多时间
bootTimeout: 5000,
// 单次请求超时(ms)
// 2026-07-02: 从 4000 改为 60000 — 远端首次冷启动可能慢(CDN 边缘冷缓存/跨网段回源/MySQL JOIN)
// 配合 loadBundleTree 的"迟到数据补救"机制,即便超时也能拿到远端最终返回的数据
requestTimeout: 60000,
// 缓存有效期(秒),与后端 Cache::set 600s 对齐;过期后后台刷新
cacheTtl: 600,
// 本地缓存 key 前缀: <prefix><uniacid>_<appType>_<lang>
// 三维隔离,与 lang.js::getOverrideStorageKey / getOverrideMemKey 保持一致
storagePrefix: 'LANG_OVR_',
// 切租户/uniacid 时强制重拉
refreshOnUniacidChange: true,
// 签名校验密钥,留空不校验(需与后端 LANG_SIGN_SECRET 一致)
signSecret: '',
}
};
// 主题配置
export const themeConfig = {
// 主题列表
themeList: ['default', 'red', 'green', 'blue', 'pink', 'gold', 'purple', 'yellow', 'black'],
// 默认主题
defaultTheme: 'default'
// 主题列表 — 与 style_color.js 顶层的 preset 名严格一致(8 个)
// 关键: 这里列出的名字必须能在 style_color.js (或后端 style_color.php 镜像) 中找到对应 preset
// 历史上曾包含 'red' 但 style_color.js 从未定义 'red' preset, 切到 'red' 主题时
// loadTheme() 会返回 undefined → 走 stub default 兜底样式, 远端也无法补齐
// 2026-07-07 移除 'red' 以保持一致性
themeList: ['default', 'green', 'blue', 'pink', 'gold', 'purple', 'yellow', 'black'],
// 默认主题
defaultTheme: 'default',
// 远端 token 覆写相关(与 langConfig 同构)
// source : 'local' | 'remote' | 'hybrid' | 'remote-only'
// remote.* : 首屏拉取 + 缓存 + 三态机 + 多租户多端隔离
overrideRemote: {
overridesUrl: '/api/theme/overrides',
// 全量 preset 拉取(remote-only 模式下使用)
// 返回 8 个 preset 完整 token,替代本地 style_color.js
presetsUrl: '/api/theme/presets',
bootTimeout: 5000,
requestTimeout: 60000,
// 远端全量 preset 缓存 key 前缀
storagePresetsPrefix: 'THEME_PRESETS_',
storagePrefix: 'THEME_OVR_',
refreshOnUniacidChange: true,
// source: 'remote-only' 时,webpack 会用 NormalModuleReplacementPlugin
// 把 style_color.js 替换为 empty-style-stub.js(只含 emergency fallback)
// 节省主包 ~75KB(完整 8 preset × ~50 token = 80KB → stub 7KB)
//
// 与 lang/ 目录的 remote-only 模式完全同构:
// - 构建期: webpack 替换为 stub
// - 运行时: ThemeOverride.loadAllPresets() 异步拉 /api/theme/presets
// - 首屏: 走 stub 的 default preset,不白屏
// - 切换: 切到非 default preset 时,等远端拉完再应用(由 applyThemeWithRemote
// 订阅 theme:presets-updated 事件驱动)
source: 'remote-only',
}
};
// API配置
@@ -31,11 +94,130 @@ export const apiConfig = {
retryDelay: 1000
};
// 隐私弹窗配置 (与 langConfig/themeConfig 同构)
// 本地兜底 + 远程 patch (来自 /api/config/init data.privacy_url_rules) 融合
// source: 'local' - 仅本地兜底, 忽略远程 patch
// 'remote' - 本地兜底 + 远程 patch 覆盖 (默认)
// 'hybrid' - 同 remote, 远程失败时退回本地
// 'remote-only' - 完全依赖远程 patch, 本地兜底为空
export const privacyConfig = {
// 本地兜底规则 (mode: 'all'|'only'|'skip', patterns: string[])
// 远程 patch 由 store/index.js 的 init action 通过 PrivacyManager.applyWithMerge() 融合
// patterns 写法:
// - 子串匹配 + 结尾匹配 (双通道), 业务侧可以写完整路径或相对路径
// - subPackage 路由 (如 /pages_tool/member/index) 用短路径 'member/index' 即可命中
urlRulesBase: {
// 场景 2: 只有首页、商品详情、个人中心才弹, 其他页面都不弹
mode: 'only',
patterns: [
// 首页 (含 subPackage 重定向后也是 pages/index/index)
'pages/index/index',
// 商品详情 (subPackage 内可能为 pages_goods/goods/detail/detail, 这里用末尾匹配)
'goods/detail/detail',
// 个人中心 (subPackage 内通常为 pages_tool/member/index)
'member/index',
],
},
// dataSource: 与 langConfig.source 同构
// 'local' 纯本地, 忽略 /api/config/init 的 privacy_url_rules
// 'remote' 本地 + 远程 patch (远程失败时仍用本地)
// 'hybrid' 同 remote, 语义别名
// 'remote-only' 必须有远程 patch, 本地空 patterns → 一律不弹
source: 'remote',
// 启动期等待通道 (弹窗必须等这些 promise 才弹)
// waitLang: Lang.boot() - i18n 数据就绪
// waitTheme: applyThemeWithRemote() - 本地 preset 应用
// waitThemeOverride: ThemeOverride.boot() - brand/light/dark 三桶 token
// waitRemoteConfig: /api/config/init (含 privacy_url_rules 远程 patch)
waitChannels: {
lang: true,
theme: true,
themeOverride: true,
remoteConfig: true,
},
// 总超时熔断 (ms): 所有等待通道超过这个时间强制放行, 不阻塞弹窗
// 取 langConfig.remote.bootTimeout (5000) 和 themeConfig.overrideRemote.bootTimeout (5000) 的最大值
// + 1000ms 余量 → 6000ms. 与原硬编码值一致, 但可通过修改此字段调整.
// 业务侧想"宁愿晚一点也要全资源就绪" → 调大; 想"快速失败" → 调小.
bootTimeout: 6000,
// 远程 patch 签名密钥 (与 langConfig.remote.signSecret 同构)
// 后端约定: hash_hmac('sha256', JSON.stringify(patch), secret)
// secret='' → 跳过校验, 接受任意 patch (向后兼容老后端)
// secret='xxx' → 校验 patch.sign, 不匹配则拒绝
// 留空默认不校验. 前端实现是 btoa 弱校验, 仅防简单篡改, 强校验建议用 crypto-js.
signSecret: '',
// 单次 /api/config/init 请求超时 (ms)
// 复用 apiConfig.timeout, 不单独配置
// remote: {
// // 远程 patch 字段名 (后端 /api/config/init 返回 data.privacy_url_rules)
// fieldPath: 'privacy_url_rules',
// // 切租户/uniacid 时强制重拉 (远端 patch 重新下发)
// refreshOnUniacidChange: true,
// // 本地缓存 key 前缀: <prefix><uniacid>
// storagePrefix: 'privacy_url_rules_',
// },
};
// 配置外置管理类
class ConfigExternal {
constructor() {
this.loadedConfigs = {};
this.loadPromises = {};
// 启动期各通道的 await promise (由 App.vue onLaunch 注入)
// 隐私弹窗 show() 时通过 PrivacyManager.getReadyWaiters() 拿到 → 串成 readyGuard
this.readyWaiters = {
lang: null,
theme: null,
themeOverride: null,
remoteConfig: null,
};
}
/**
* 设置启动期各通道的 await promise
* App.vue onLaunch 在 step 2 注入, PrivacyManager.show() 时读取
* @param {Object} waiters { lang?, theme?, themeOverride?, remoteConfig? }
*/
setReadyWaiters(waiters) {
if (!waiters || typeof waiters !== 'object') return
for (const k of Object.keys(this.readyWaiters)) {
if (waiters[k] && typeof waiters[k].then === 'function') {
this.readyWaiters[k] = waiters[k]
}
}
}
/**
* 获取隐私弹窗 readyGuard (合并所有启用的等待通道)
* 任意通道 disabled → 不等
* 所有通道都 null → 返回 Promise.resolve() (不退化)
* @param {Object} channels { lang?, theme?, themeOverride?, remoteConfig? }
* @returns {Promise}
*/
getPrivacyReadyGuard(channels) {
const cfg = (typeof channels === 'object' && channels) || (privacyConfig.waitChannels || {})
const promises = []
for (const k of ['lang', 'theme', 'themeOverride', 'remoteConfig']) {
if (cfg[k] && this.readyWaiters[k]) {
promises.push(this.readyWaiters[k])
}
}
if (!promises.length) return Promise.resolve()
return Promise.all(promises).catch(() => {})
}
/**
* 隐私弹窗总超时熔断 (ms)
* 默认取 langConfig.remote.bootTimeout 与 themeConfig.overrideRemote.bootTimeout 的最大值 + 1000ms 余量
* 业务侧可通过 privacyConfig.bootTimeout 覆盖
*/
getPrivacyBootTimeout() {
if (privacyConfig && typeof privacyConfig.bootTimeout === 'number' && privacyConfig.bootTimeout > 0) {
return privacyConfig.bootTimeout
}
const langT = (langConfig && langConfig.remote && langConfig.remote.bootTimeout) || 5000
const themeT = (themeConfig && themeConfig.overrideRemote && themeConfig.overrideRemote.bootTimeout) || 5000
return Math.max(langT, themeT) + 1000
}
/**
@@ -59,7 +241,7 @@ class ConfigExternal {
this.loadedConfigs[`lang_${lang}`] = langData;
resolve(langData);
} catch (error) {
console.error(`加载语言包 ${lang} 失败:`, error);
// console.error(`加载语言包 ${lang} 失败:`, error);
reject(error);
}
});
@@ -100,23 +282,40 @@ class ConfigExternal {
/**
* 加载主题配置(异步方式)
* 关键: 在 remote-only 模式下, style_color.js 已被 webpack 替换为 empty-style-stub.js,
* 只含 1 个 default preset. 其它 7 个 preset 由 ThemeOverride.loadAllPresets()
* 异步拉取并合并到本地缓存. 这里的 loadTheme 优先从缓存取,缓存未命中时回退到 stub.
*
* @param {string} theme - 主题名称
* @returns {Promise} - 加载结果
*/
async loadTheme(theme = themeConfig.defaultTheme) {
// 1) 先查已加载的内存缓存(包括远端拉取后写入的)
if (this.loadedConfigs[`theme_${theme}`]) {
return this.loadedConfigs[`theme_${theme}`];
}
// 2) remote-only 模式下,从 ThemeOverride 内存缓存(由 loadAllPresets 写入)取
try {
const ThemeOverride = require('./theme-override.js').default;
const remotePresets = ThemeOverride.getAllPresets();
if (remotePresets && remotePresets[theme]) {
this.loadedConfigs[`theme_${theme}`] = remotePresets[theme];
return remotePresets[theme];
}
} catch (e) {
// ignore — ThemeOverride 不可用时继续走 require stub
}
// 3) 兜底: require style_color.js (local 模式全量, remote-only 模式 stub)
if (this.loadPromises[`theme_${theme}`]) {
return this.loadPromises[`theme_${theme}`];
}
this.loadPromises[`theme_${theme}`] = new Promise((resolve, reject) => {
try {
// 动态加载主题配置
// 动态加载主题配置 (webpack 替换为 stub 时,只返回 1 个 default preset)
const themeData = require(`@/common/js/style_color.js`)['default'][theme];
// console.log('async themeData => ', themeData);
this.loadedConfigs[`theme_${theme}`] = themeData;
resolve(themeData);
} catch (error) {

View File

@@ -1,7 +1,7 @@
// 发行版本,配置说明
let releaseCfg = undefined;
// #ifdef APP-PLUS || MP-WEIXIN || MP-ALIPAY || MP-BAIDU || MP-QQ || MP-TOUTIAO
// #ifdef APP-PLUS || MP-WEIXIN || MP-ALIPAY || MP-BAIDU || MP-QQ || MP-TOUTIAO || MP-HARMONY
try {
if (site) { // 从site.js文件中获取配置, 针对微信小程序类
releaseCfg = {
@@ -11,7 +11,13 @@ try {
uniacid: site.uniacid,
}
} else {
console.warn('小程序发行环境下,必须配置site.js文件, 不然将使用默认配置,影响小程序定制分发!');
// 惰性加载 Lang 避免循环依赖(lang.js 引用了 config.js)
try {
const Lang = require('@/common/js/lang.js').default;
console.warn(Lang.lang('common.config.siteJsNotConfigured'));
} catch (e) {
console.warn('小程序发行环境下,必须配置site.js文件,不然将使用默认配置,影响小程序定制分发!');
}
}
} catch (e) {}
// #endif
@@ -20,20 +26,13 @@ try {
// 默认域名, 自定义发行时可以修改
let defaultDomain = '';
// #ifdef H5_XCX_5G_QUICKAPP_COM
defaultDomain = 'https://xcx20.5g-quickapp.com';
// #endif
// #ifdef H5_XCX_AIGC_QUICKAPP_COM
defaultDomain = 'https://xcx.aigc-quickapp.com/';
// #endif
// #ifdef H5_5G_AIGC_QUICKAPP_COM
defaultDomain = 'https://5g.aigc-quickapp.com/';
// #endif
// #ifdef H5_TEST_AIGC_QUICKAPP_COM
defaultDomain = 'https://test.aigc-quickapp.com/';
// #ifdef H5
// 域名由 vue.config.js 中 DefinePlugin 注入的 process.env.UNI_APP_DOMAIN 传入
try {
if (process.env.UNI_APP_DOMAIN) {
defaultDomain = process.env.UNI_APP_DOMAIN;
}
} catch (e) {}
// #endif
// 确保域名以 '/' 结尾
@@ -59,7 +58,6 @@ if (process?.env?.NODE_ENV === 'development') {
// 如果本地配置文件不存在或加载失败,保持使用默认配置
// 只在开发模式下输出提示信息
// #ifdef WEB
console.log('本地配置文件 .local.config.js 不存在,使用默认配置');
// #endif
}
}

View File

@@ -2,68 +2,16 @@
* 客服统一处理服务
* 整合各种客服方式,提供统一的调用接口
*/
class CustomerService {
constructor(vueInstance, externalConfig = {}) {
if (!vueInstance.$lang) {
throw new Error('CustomerService 必须在 Vue 实例中初始化');
}
import IMAGE_CONFIG from './image-config.js';
import Platform from './platform.js';
export class CustomerService {
constructor(vueInstance, externalConfig = null) {
this.vm = vueInstance;
this.externalConfig = externalConfig; // 外部传入的最新配置(优先级最高)
this.latestPlatformConfig = null;
}
getSupoortKeFuList() {
if (!this.vm) return [];
const vm = this.vm;
return [
{
id: 'weixin-official',
name: vm.$lang('customer.weChatKefu'),
isOfficial: true,
type: 'weapp'
},
{
id: 'custom-kefu',
name: vm.$lang('customer.systemKefu'),
isOfficial: false
},
{
id: 'qyweixin-kefu',
name: vm.$lang('customer.weChatWorkKefu'),
isOfficial: false
},
]
}
/**
* 打开客服选择弹窗
*/
openCustomerSelectPopupDialog() {
const kefu_list = this.getSupoortKeFuList();
const kefuNames = kefu_list.map(item => item.name);
uni.showActionSheet({
itemList: kefuNames,
success: (res) => {
const kefu = kefu_list[res.tapIndex];
this.externalConfig = kefu ?? this.externalConfig ?? {};
if (kefu.isOfficial) {
uni.openCustomerServiceConversation({
sessionFrom: 'weapp',
showMessageCard: true
});
} else if (kefu.id === 'custom-kefu') {
this.handleCustomerClick();
} else if (kefu.id === 'qyweixin-kefu') {
this.handleQyWeixinKefuClick();
}
}
});
}
/**
* 强制刷新配置(支持传入外部配置)
* @param {Object} externalConfig 外部最新配置
@@ -83,28 +31,25 @@ class CustomerService {
return this.latestPlatformConfig;
}
// 优先级:外部传入的最新配置 > vuex配置 > 空对象
const servicerConfig = this.externalConfig || this.vm.$store.state.servicerConfig || {};
console.log(`【实时客服配置】`, servicerConfig);
const platformMap = {
h5: 'h5',
weapp: 'weapp',
alipay: 'aliapp',
baidu: 'baidu',
toutiao: 'toutiao',
qq: 'qq',
kuaishou: 'kuaishou',
jd: 'jd',
'360': '360',
xhs: 'xhs',
app: 'app',
pc: 'pc'
};
let platformConfig = null;
// #ifdef H5
platformConfig = servicerConfig.h5 ? (typeof servicerConfig.h5 === 'object' ? servicerConfig.h5 : null) : null;
// #endif
const platformKey = platformMap[Platform.detect()] || Platform.detect();
let platformConfig = servicerConfig[platformKey] && typeof servicerConfig[platformKey] === 'object' ? servicerConfig[platformKey] : null;
// #ifdef MP-WEIXIN
platformConfig = servicerConfig.weapp ? (typeof servicerConfig.weapp === 'object' ? servicerConfig.weapp : null) : null;
// #endif
// #ifdef MP-ALIPAY
platformConfig = servicerConfig.aliapp ? (typeof servicerConfig.aliapp === 'object' ? servicerConfig.aliapp : null) : null;
// #endif
// #ifdef PC
platformConfig = servicerConfig.pc ? (typeof servicerConfig.pc === 'object' ? servicerConfig.pc : null) : null;
// #endif
// 处理空数组情况(你的配置中pc/aliapp是空数组,转为null)
if (Array.isArray(platformConfig)) {
platformConfig = null;
}
@@ -130,6 +75,15 @@ class CustomerService {
return config && typeof config === 'object' && config.type;
}
/**
* 检查是否有有效的客服配置(用于判断是否显示客服按钮)
* @returns {Boolean}
*/
hasValidKefuConfig() {
const config = this.getPlatformConfig();
return config && typeof config === 'object' && config.type && config.type !== 'none';
}
/**
* 验证客服配置完整性
* @returns {Object} 验证结果
@@ -144,32 +98,18 @@ class CustomerService {
warnings: []
};
if (!config) {
if (!config || !config.type) {
result.isValid = false;
result.errors.push('客服配置不存在');
result.errors.push(this.vm.$lang('customerService.serviceTypeNotConfigured'));
return result;
}
if (config.type === 'aikefu') {
return result;
}
if (!config.type) {
result.isValid = false;
result.errors.push('客服类型未配置');
}
if (config.type === 'wxwork') {
if (!wxworkConfig) {
result.isValid = false;
result.errors.push('企业微信配置不存在');
} else {
if (!wxworkConfig.enable) {
result.warnings.push('企业微信功能未启用');
}
if (!wxworkConfig.contact_url) {
result.warnings.push('企业微信活码链接未配置,将使用原有客服方式');
}
if (!wxworkConfig || !wxworkConfig.enable) {
result.warnings.push('企业微信未启用');
}
if (!wxworkConfig.contact_url) {
result.warnings.push('企业微信活码链接未配置');
}
}
@@ -177,16 +117,39 @@ class CustomerService {
}
/**
* 跳转到AI客服页面
* 跳转到 AI智能客服页面(AiChat)
*/
openAIKeFuService() {
const vm = this.vm;
vm.$util.redirectTo(vm.$util.AI_CHAT_PAGE_URL);
openAiChatService() {
try {
// 清除未读数(如果存在)
if (typeof this.vm.setAiUnreadCount === 'function') {
this.vm.setAiUnreadCount(0);
}
// ✅ 修正路径:必须与 pages.json 中注册的路径一致
const aiChatUrl = '/pages_tool/ai-chat/index';
// ✅ 使用 navigateTo 保留返回栈(体验更好)
uni.navigateTo({
url: aiChatUrl,
fail: (err) => {
console.error('跳转 AI智能客服失败:', err);
// H5 兜底
// #ifdef H5
window.location.href = aiChatUrl;
// #endif
uni.showToast({ title: this.vm.$lang('customerService.openFailed'), icon: 'none' });
}
});
} catch (e) {
console.error('跳转 AI智能客服异常:', e);
uni.showToast({ title: this.vm.$lang('customerService.openFailed'), icon: 'none' });
}
}
/**
* 处理客服点击事件
* @param {Object} options 选项参数
* 处理客服点击事件(统一入口)
* @param {Object} options 选项参数(用于消息卡片等)
*/
handleCustomerClick(options = {}) {
const validation = this.validateConfig();
@@ -201,17 +164,18 @@ class CustomerService {
}
const config = this.getPlatformConfig();
const { niushop = {}, sendMessageTitle = '', sendMessagePath = '', sendMessageImg = '' } = options || {};
const { niushop = {}, sendMessageTitle = '', sendMessagePath = '', sendMessageImg = '' } = options;
if (config.type === 'none') {
this.showNoServicePopup();
return;
}
// 核心分支:根据最新的type处理
// 核心路由:根据 type 决定行为
switch (config.type) {
case 'aikefu':
this.openAIKeFuService();
this.openAiChatService();
break;
case 'wxwork':
this.openWxworkService(false, config, options);
@@ -219,6 +183,9 @@ class CustomerService {
case 'third':
this.openThirdService(config);
break;
case 'miniprogram':
this.openThirdService(config);
break;
case 'niushop':
this.openNiushopService(niushop);
break;
@@ -229,36 +196,40 @@ class CustomerService {
this.openAliappService(config);
break;
default:
console.error('【未知客服类型】', config.type);
this.makePhoneCall();
}
}
/**
* 打开企业微信客服
* @param {boolean} useOriginalService 是否使用原有客服方式
* @param {Object} servicerConfig 客服配置
* @param {Object} options 选项参数
*/
// ================== 各类型客服实现 ==================
openWxworkService(useOriginalService = false, servicerConfig = null, options = {}) {
const config = servicerConfig || this.getPlatformConfig();
const wxworkConfig = this.getWxworkConfig();
const { sendMessageTitle = '', sendMessagePath = '', sendMessageImg = '' } = options || {};
const { sendMessageTitle = '', sendMessagePath = '', sendMessageImg = '' } = options;
// #ifdef MP-WEIXIN
if (wxworkConfig?.enable && wxworkConfig?.contact_url && !useOriginalService) {
if (!useOriginalService && wxworkConfig?.enable && wxworkConfig?.contact_url) {
wx.navigateToMiniProgram({
appId: 'wxeb490c6f9b154ef9',
path: `pages/contacts/externalContactDetail?url=${encodeURIComponent(wxworkConfig.contact_url)}`,
success: () => console.log('跳转企业微信成功'),
success: () => {},
fail: (err) => {
console.error('跳转企业微信失败:', err);
this.fallbackToOriginalService();
}
});
} else {
// 检查是否有企业微信配置
if (!config.wxwork_url && !config.corpid) {
console.error('企业微信配置不完整,缺少 wxwork_url 或 corpid');
uni.showToast({ title: this.vm.$lang('customerService.wxworkConfigIncomplete'), icon: 'none' });
this.fallbackToPhoneCall();
return;
}
wx.openCustomerServiceChat({
extInfo: { url: config.wxwork_url },
corpId: config.corpid,
extInfo: { url: config.wxwork_url || '' },
corpId: config.corpid || '',
showMessageCard: true,
sendMessageTitle,
sendMessagePath,
@@ -268,120 +239,120 @@ class CustomerService {
// #endif
// #ifdef H5
if (wxworkConfig?.enable && wxworkConfig?.contact_url) {
if (!useOriginalService && wxworkConfig?.enable && wxworkConfig?.contact_url) {
window.location.href = wxworkConfig.contact_url;
} else if (config.wxwork_url) {
location.href = config.wxwork_url;
window.location.href = config.wxwork_url;
} else {
this.fallbackToPhoneCall();
}
// #endif
}
/**
* 打开第三方客服
* @param {Object} config 客服配置
*/
openThirdService(config) {
// 支持多种可能的字段名
const miniAppId = config.mini_app_id || config.miniAppId || config.appid || config.appId || config.app_id;
const miniAppPath = config.mini_app_path || config.miniAppPath || config.path || config.page_path || '';
// 优先处理第三方微信小程序客服
if (miniAppId) {
// #ifdef MP-WEIXIN
wx.navigateToMiniProgram({
appId: miniAppId,
path: miniAppPath,
success: () => {
},
fail: (err) => {
console.error('【跳转第三方小程序失败】', err);
uni.showToast({ title: this.vm.$lang('customerService.jumpFailed'), icon: 'none' });
}
});
// #endif
// #ifdef H5
uni.showToast({ title: this.vm.$lang('customerService.miniProgramOnly'), icon: 'none' });
// #endif
return;
}
// 处理第三方链接客服
if (config.third_url) {
// #ifdef H5
window.location.href = config.third_url;
// #endif
// #ifdef MP
uni.setClipboardData({
data: config.third_url,
success: () => {
uni.showToast({ title: this.vm.$lang('customerService.linkCopied'), icon: 'none' });
}
});
// #endif
} else {
console.error('【第三方客服配置不完整】缺少 mini_app_id 或 third_url');
this.fallbackToPhoneCall();
}
}
/**
* 打开牛商客服
* @param {Object} niushop 牛商参数
*/
openNiushopService(niushop) {
if (Object.keys(niushop).length > 0) {
if (Object.keys(niushop).length > 0 && this.vm.$util?.redirectTo) {
this.vm.$util.redirectTo('/pages_tool/chat/room', niushop);
} else {
this.makePhoneCall();
}
}
/**
* 打开微信小程序客服
* @param {Object} config 客服配置
* @param {Object} options 选项参数
*/
openWeappService(config, options = {}) {
if (!this.shouldUseCustomService(config)) {
console.log('使用官方微信小程序客服');
// 如果 useOfficial 为 true 或 undefined,则使用原生系统客服(由 button open-type="contact" 触发)
// 此方法仅用于自定义跳转(如 useOfficial: false)
if (config.useOfficial !== false) {
// 不做任何事,应由 <button open-type="contact"> 触发
return;
}
console.log('使用自定义微信小程序客服');
this.handleCustomWeappService(config, options);
}
/**
* 处理自定义微信小程序客服
* @param {Object} config 客服配置
* @param {Object} options 选项参数
*/
handleCustomWeappService(config, options = {}) {
const { sendMessageTitle = '', sendMessagePath = '', sendMessageImg = '' } = options || {};
if (config.customServiceUrl) {
let url = config.customServiceUrl;
const params = [];
const { sendMessageTitle, sendMessagePath, sendMessageImg } = options;
if (sendMessageTitle) params.push(`title=${encodeURIComponent(sendMessageTitle)}`);
if (sendMessagePath) params.push(`path=${encodeURIComponent(sendMessagePath)}`);
if (sendMessageImg) params.push(`img=${encodeURIComponent(sendMessageImg)}`);
if (params.length > 0) {
url += (url.includes('?') ? '&' : '?') + params.join('&');
}
uni.navigateTo({
url: url,
fail: (err) => {
console.error('跳转自定义客服页面失败:', err);
this.tryThirdPartyService(config, options);
}
});
uni.navigateTo({ url });
return;
}
this.tryThirdPartyService(config, options);
}
/**
* 尝试使用第三方客服
* @param {Object} config 客服配置
* @param {Object} options 选项参数
*/
tryThirdPartyService(config, options = {}) {
if (config.thirdPartyServiceUrl) {
// #ifdef H5
window.open(config.thirdPartyServiceUrl, '_blank');
// #endif
// 支持第三方微信小程序客服
if (config.thirdPartyMiniAppId || config.mini_app_id) {
// #ifdef MP-WEIXIN
if (config.thirdPartyMiniAppId) {
wx.navigateToMiniProgram({
appId: config.thirdPartyMiniAppId,
path: config.thirdPartyMiniAppPath || '',
fail: (err) => {
console.error('跳转第三方小程序失败:', err);
this.fallbackToPhoneCall();
}
});
} else {
uni.setClipboardData({
data: config.thirdPartyServiceUrl,
success: () => {
uni.showModal({
title: '客服链接已复制',
content: '客服链接已复制到剪贴板,请在浏览器中粘贴访问',
showCancel: false
});
}
});
}
wx.navigateToMiniProgram({
appId: config.thirdPartyMiniAppId || config.mini_app_id,
path: config.thirdPartyMiniAppPath || config.mini_app_path || ''
});
// #endif
return;
}
// 支持第三方链接客服
if (config.thirdPartyServiceUrl || config.third_url) {
const serviceUrl = config.thirdPartyServiceUrl || config.third_url;
// #ifdef H5
window.open(serviceUrl, '_blank');
// #endif
// #ifdef MP
uni.setClipboardData({ data: serviceUrl });
uni.showToast({ title: this.vm.$lang('customerService.customerLinkCopied'), icon: 'none' });
// #endif
return;
}
@@ -389,106 +360,55 @@ class CustomerService {
this.fallbackToPhoneCall();
}
/**
* 降级到电话客服
*/
fallbackToPhoneCall() {
uni.showModal({
title: '联系客服',
content: '在线客服暂时不可用,是否拨打电话联系客服?',
success: (res) => {
if (res.confirm) {
this.makePhoneCall();
}
}
});
}
/**
* 打开支付宝小程序客服
* @param {Object} config 客服配置
*/
openAliappService(config) {
console.log('支付宝小程序客服', config);
switch (config.type) {
case 'aikefu':
this.openAIKeFuService();
break;
case 'third':
this.openThirdService(config);
break;
default:
console.log('使用支付宝官方客服');
break;
if (config.type === 'aikefu') {
this.openAiChatService();
} else if (config.type === 'third') {
this.openThirdService(config);
} else {
// 支付宝原生客服由 button open-type="contact" 触发,此处不处理
}
}
/**
* 拨打电话
*/
makePhoneCall(mobileNumber) {
if (mobileNumber) {
return uni.makePhoneCall({
phoneNumber: mobileNumber
});
}
// ================== 辅助方法 ==================
// 从缓存中获取电话信息
uni.getStorage({
key: 'shopInfo',
success: (res) => {
const shopInfo = res.data;
const mobile = shopInfo?.mobile ?? '';
if (mobile) {
uni.makePhoneCall({
phoneNumber: mobile
});
makePhoneCall() {
this.vm.$api.sendRequest({
url: '/api/site/shopcontact',
success: res => {
if (res.code === 0 && res.data?.mobile) {
uni.makePhoneCall({ phoneNumber: res.data.mobile });
} else {
uni.showToast({
title: '暂无客服电话',
icon: 'none'
});
uni.showToast({ title: this.vm.$lang('customerService.noServicePhone'), icon: 'none' });
}
},
fail: () => {
uni.showToast({ title: this.vm.$lang('customerService.getPhoneFailed'), icon: 'none' });
}
});
}
/**
* 显示无客服弹窗
*/
showNoServicePopup() {
const siteInfo = this.vm.$store.state.siteInfo || {};
const message = siteInfo?.site_tel
? `请联系客服,客服电话是${siteInfo.site_tel}`
: '抱歉,商家暂无客服,请线下联系';
uni.showModal({
title: '联系客服',
content: message,
showCancel: false
});
? this.vm.$lang('customerService.callServiceTip', { phone: siteInfo.site_tel })
: this.vm.$lang('customerService.noServiceOffline');
uni.showModal({ title: this.vm.$lang('customerService.contactCustomerService'), content: message, showCancel: false });
}
/**
* 显示配置错误弹窗
* @param {Array} errors 错误列表
*/
showConfigErrorPopup(errors) {
const message = errors.join('\n');
uni.showModal({
title: '配置错误',
content: `客服配置有误:\n${message}`,
title: this.vm.$lang('customerService.configError'),
content: this.vm.$lang('customerService.configErrorDetail', { errors: errors.join('\n') }),
showCancel: false
});
}
/**
* 降级处理:使用原有客服方式
*/
fallbackToOriginalService() {
uni.showModal({
title: '提示',
content: '无法直接添加企业微信客服,是否使用其他方式联系客服?',
title: this.vm.$lang('customerService.tip'),
content: this.vm.$lang('customerService.cannotAddWxwork'),
success: (res) => {
if (res.confirm) {
this.openWxworkService(true);
@@ -497,9 +417,19 @@ class CustomerService {
});
}
fallbackToPhoneCall() {
uni.showModal({
title: this.vm.$lang('customerService.tip'),
content: this.vm.$lang('customerService.onlineUnavailable'),
success: (res) => {
if (res.confirm) this.makePhoneCall();
}
});
}
/**
* 获取客服按钮配置
* @returns {Object} 按钮配置
* 获取按钮配置(用于 template 中 v-if / open-type 判断)
* @returns {Object}
*/
getButtonConfig() {
const config = this.getPlatformConfig();
@@ -507,11 +437,10 @@ class CustomerService {
let openType = '';
// #ifdef MP-WEIXIN
if (config.type === 'weapp') {
openType = config.useOfficial !== false ? 'contact' : '';
if (config.type === 'weapp' && config.useOfficial !== false) {
openType = 'contact';
}
// #endif
// #ifdef MP-ALIPAY
if (config.type === 'aliapp') openType = 'contact';
// #endif
@@ -520,26 +449,235 @@ class CustomerService {
}
/**
* 判断是否应该使用自定义客服处理
* @param {Object} config 客服配置
* @returns {boolean} 是否使用自定义客服
* 获取客服按钮图标
* @returns {String} 图标URL
*/
shouldUseCustomService(config) {
// #ifdef MP-WEIXIN
if (config?.type === 'weapp') {
return config.useOfficial === false;
getKefuButtonIcon() {
const shopInfo = this.vm.shopInfo || {};
const config = this.getPlatformConfig();
// 优先使用指定的智能客服头像
if (config?.type === 'aikefu' || config?.type === 'wxwork' || config?.type === 'qyweixin') {
return this.vm.$util.img(IMAGE_CONFIG.aiAvatar);
}
return shopInfo.kefuimg || this.vm.$util?.getDefaultImage()?.kefu || '';
}
/**
* 判断是否为微信官方客服
* @returns {Boolean}
*/
isWeappOfficialKefu() {
const config = this.getPlatformConfig();
return config?.type === 'weapp';
}
/**
* 判断是否为智能客服
* @returns {Boolean}
*/
isAIKefu() {
const config = this.getPlatformConfig();
return config?.type === 'aikefu';
}
/**
* 判断是否为企业微信客服
* @returns {Boolean}
*/
isWxworkKefu() {
const config = this.getPlatformConfig();
return config?.type === 'wxwork' || config?.type === 'qyweixin';
}
/**
* 判断是否为第三方客服
* @returns {Boolean}
*/
isThirdKefu() {
const config = this.getPlatformConfig();
return config?.type === 'third';
}
/**
* 判断是否需要同时显示小程序系统客服
* @returns {Boolean}
*/
shouldShowExtraWeappSystemKefu() {
const config = this.getPlatformConfig();
return (config?.show_system_service === true || config?.show_system_service === '1') && config?.type !== 'weapp';
}
/**
* 计算容器高度
* @param {Boolean} isLanguageSwitchEnabled 是否启用语言切换
* @param {Boolean} showWeappSystemKefu 是否显示小程序系统客服
* @param {Boolean} fixBtnShow 是否显示按钮
* @returns {String} 高度值(px)
*/
getContainerHeight(isLanguageSwitchEnabled, showWeappSystemKefu, fixBtnShow) {
if (!fixBtnShow) return '160px';
let buttonCount = 1;
if (isLanguageSwitchEnabled) buttonCount++;
if (showWeappSystemKefu) buttonCount++;
const totalRpx = 94 * buttonCount - 14;
const pxValue = Math.round(totalRpx * 0.5);
return `${pxValue}px`;
}
/**
* 获取未读消息数量
* @returns {Number}
*/
getUnreadCount() {
return this.vm.$store?.state?.aiUnreadCount || 0;
}
/**
* 拨打电话联系客服
* @param {String} phoneNumber 电话号码
*/
makePhoneCallByNumber(phoneNumber) {
if (phoneNumber) {
uni.makePhoneCall({ phoneNumber });
} else {
this.makePhoneCall();
}
}
/**
* 打开 AI 智能助手
*/
openAIChat() {
try {
if (typeof this.vm.setAiUnreadCount === 'function') {
this.vm.setAiUnreadCount(0);
}
const aiChatUrl = '/pages_tool/ai-chat/index';
uni.navigateTo({
url: aiChatUrl,
fail: (err) => {
console.error('跳转 AI智能客服失败:', err);
// #ifdef H5
window.location.href = aiChatUrl;
// #endif
uni.showToast({ title: this.vm.$lang('customerService.openFailed'), icon: 'none' });
}
});
} catch (e) {
console.error('跳转 AI智能客服异常:', e);
uni.showToast({ title: this.vm.$lang('customerService.openFailed'), icon: 'none' });
}
}
/**
* 打开客服选择对话框(预留方法)
*/
openCustomerSelectPopupDialog() {
uni.showToast({ title: this.vm.$lang('customerService.developing'), icon: 'none' });
}
/**
* 打开客服选择弹出层(ActionSheet)
* @param {Array} kefuList 客服列表
*/
openKefuSelectPopup(kefuList) {
const kefuNames = kefuList.map(item => item.name);
uni.showActionSheet({
itemList: kefuNames,
success: (res) => {
const selectedKefu = kefuList[res.tapIndex];
const cs = createCustomerService(this.vm, selectedKefu);
if (selectedKefu.isOfficial) {
uni.openCustomerServiceConversation({
sessionFrom: 'weapp',
showMessageCard: true
});
} else if (selectedKefu.id === 'qyweixin-kefu') {
if (uni.getSystemInfoSync().platform === 'wechat') {
uni.navigateTo({
url: '/pages_tool/qyweixin-kefu/index'
});
} else {
const qyweixinUrl = this.vm.shopInfo?.qyweixinUrl;
if (qyweixinUrl) {
window.location.href = qyweixinUrl;
} else {
uni.showToast({ title: this.vm.$lang('customerService.wxworkNotConfigured'), icon: 'none' });
}
}
} else {
cs.handleCustomerClick();
}
}
});
}
/**
* 核心方法:统一客服入口(带验证和配置检查)
* @param {Object} options 选项参数
*/
handleUnifiedKefuClick(options = {}) {
const validation = this.validateConfig();
if (!validation.isValid) {
console.error('客服配置无效:', validation.errors);
uni.showToast({ title: this.vm.$lang('customerService.serviceUnavailable'), icon: 'none' });
return;
}
if (validation.warnings.length > 0) {
console.warn('客服配置警告:', validation.warnings);
}
const platformConfig = this.getPlatformConfig();
// 检查企业微信配置
if (platformConfig.type === 'wxwork') {
const wxworkConfig = this.getWxworkConfig();
// #ifdef MP-WEIXIN
if (!wxworkConfig?.enable || !wxworkConfig?.contact_url) {
console.warn('企业微信配置不完整,使用原生客服');
uni.showToast({ title: this.vm.$lang('customerService.wxworkConfigIncomplete'), icon: 'none' });
}
// #endif
// #ifdef H5
if (!wxworkConfig?.contact_url && !platformConfig.wxwork_url) {
console.error('企业微信链接未配置');
uni.showToast({ title: this.vm.$lang('customerService.wxworkLinkNotConfigured'), icon: 'none' });
return;
}
// #endif
}
// 直接调用统一处理方法,由 CustomerService 内部根据配置路由
try {
this.handleCustomerClick({
sendMessageTitle: options.sendMessageTitle || this.vm.$lang('customerService.fromFloatButton'),
sendMessagePath: options.sendMessagePath || '/pages/index/index'
});
} catch (error) {
console.error('客服处理失败:', error);
uni.showToast({ title: this.vm.$lang('customerService.openFailed'), icon: 'none' });
}
// #endif
return true;
}
}
/**
* 创建客服服务实例
* @param {Object} vueInstance Vue实例
* @param {Object} externalConfig 外部最新配置
* @returns {CustomerService} 客服服务实例
* @param {Object} vueInstance Vue 实例(通常是 this)
* @param {Object} externalConfig 可选:外部传入的最新配置(如从 DIY 数据中提取)
* @returns {CustomerService}
*/
export function createCustomerService(vueInstance, externalConfig = {}) {
export function createCustomerService(vueInstance, externalConfig = null) {
return new CustomerService(vueInstance, externalConfig);
}

View File

@@ -46,6 +46,12 @@ export default {
openBottomNav: false,
isShowCopyRight: false,
// getDiyInfo 节流
diyInfoLoading: false, // 是否正在请求
lastDiyInfoTime: 0, // 上次成功加载的时间戳
lastDiyInfoLang: '', // 上次加载时的语言,语言切换时强制刷新
diyInfoTtl: 3 * 60 * 1000, // 3分钟内不重复请求
//启动广告
adv:{},
@@ -200,7 +206,6 @@ export default {
},
methods: {
play(){
console.log(123)
},
async init() {
@@ -305,40 +310,71 @@ export default {
}
},
async getDiyInfo() {
let res = await this.$api.sendRequest({
url: '/api/diyview/info',
data: {
id: this.id,
name: this.name,
en_type:uni.getStorageSync("lang"),//获取语言底部
},
async: false
});
if (res.code != 0 || !res.data) {
async getDiyInfo(force = false) {
// 节流:正在请求 / N 秒内已加载过 / 语言未变 -> 跳过
const now = Date.now();
const currentLang = uni.getStorageSync("lang") || '';
if (!force) {
if (this.diyInfoLoading) return;
if (this.lastDiyInfoTime && (now - this.lastDiyInfoTime) < this.diyInfoTtl
&& this.lastDiyInfoLang === currentLang) {
return;
}
}
this.diyInfoLoading = true;
let res;
try {
res = await this.$api.sendRequest({
url: '/api/diyview/info',
data: {
id: this.id,
name: this.name,
en_type: currentLang,
},
async: false
});
} catch (e) {
console.error('getDiyInfo request failed', e);
if (this.$refs.loadingCover) this.$refs.loadingCover.hide();
this.$util.showToast({
title: this.$lang('diy.networkError')
});
this.diyInfoLoading = false;
return;
}
this.diyInfoLoading = false;
if (!res || res.code != 0 || !res.data) {
if (this.$refs.loadingCover) this.$refs.loadingCover.hide();
if (res.code == -3) {
if (res && res.code == -3) {
this.$util.showToast({
title: res.message
});
this.diyData = {};
// 保持原有数据结构,仅清空 value,避免鸿蒙下重新布局
this.diyData = { ...(this.diyData || {}), value: [] };
return;
}
this.$util.showToast({
title: '未配置自定义页面数据'
title: this.$lang('diy.noDiyData')
});
this.diyData = {};
// 保持原有数据结构,仅清空 value,避免鸿蒙下重新布局
this.diyData = { ...(this.diyData || {}), value: [] };
return;
}
this.lastDiyInfoTime = now;
this.lastDiyInfoLang = currentLang;
let diyDataValue = res.data;
if (diyDataValue.value) {
this.diyData = JSON.parse(diyDataValue.value);
// 导航栏标题要根据语言环境切换
const title = this.isEnEnv ? this.diyData?.global?.en_title : this.diyData?.global?.title;
// 优先使用 title_map 多语言 map,没有则回退到 title / en_title
const title = this.$langConfig.getField(this.diyData?.global, 'title');
if (title) this.$langConfig.title(title);
this.mpCollect = this.diyData.global.mpCollect;
@@ -561,7 +597,7 @@ export default {
if (res.code == 0 && res.data) {
this.currentPosition = res.data.formatted_addresses.recommend; // 结合知名地点形成的描述性地址,更具人性化特点
} else {
this.currentPosition = '未获取到定位';
this.currentPosition = this.$lang('diy.locationNotAvailable');
}
}
});
@@ -573,7 +609,7 @@ export default {
this.nearestStore = this.defaultStoreInfo;
this.nearestStore.show_address = this.nearestStore.full_address.replace(/,/g, ' ') + ' ' + this.nearestStore.address;
}
if (this.currentPosition == '') this.currentPosition = '未获取到定位';
if (this.currentPosition == '') this.currentPosition = this.$lang('diy.locationNotAvailable');
this.openChooseStorePopup();
}
},
@@ -583,7 +619,7 @@ export default {
if (this.id) shareUrl += '?id=' + this.id;
else if (this.name) shareUrl += '?name=' + this.name;
this.$util.setPublicShare({
title: this.diyData.global.title,
title: this.$langConfig.getField(this.diyData.global, 'title'),
desc: '',
link: shareUrl,
imgUrl: this.siteInfo ? this.$util.img(this.siteInfo.logo_square) : ''

View File

@@ -0,0 +1,15 @@
// ============================================================
// 空 lang 包占位
//
// 在 source === 'remote-only' 模式下, lang/ 目录下的所有 .js 会被
// webpack.NormalModuleReplacementPlugin 替换为这个 stub.
//
// 设计要点:
// - 导出 default 对象, 结构与真实 lang 包一致: { lang: {...} }
// - lang 字段是空对象, 让 lang() 函数 fallback 路径不报错
// - 不导出 named export, 避免 tree-shaking 把整个 stub 干掉
// ============================================================
export default {
lang: {}
};

View File

@@ -0,0 +1,169 @@
// ============================================================
// 空主题预设占位(stub)
//
// 在 themeConfig.overrideRemote.source === 'remote-only' 模式下,
// style_color.js 会被 webpack.NormalModuleReplacementPlugin 替换为这个 stub.
//
// 目的: 主包不再包含 8 个完整 preset (~80KB), 只保留最小 emergency fallback
// (~5KB, 仅 1 个 default preset 的核心 token).
//
// 设计要点:
// 1) 导出 default 对象, 结构与 style_color.js 一致: { 'default': { ... } }
// 2) 包含最关键的 token(main_color, aux_color, bg_color 等),
// 保证 themeColorSet 能写入基础 CSS 变量,首屏不白屏
// 3) 缺失的 token 由远端 /api/theme/presets 异步补齐,补齐前 var() 解析失败
// 时浏览器会回退到 SCSS 的 fallback 值(uni-app H5 已做 rpx→px)
// 4) 其他 7 个 preset 完全由远端提供,本地不打包
// 5) 失败兜底: 远端不可用时, 切到非 default preset 会落到 default 的样式
//
// token 数量统计: 8 preset × ~50 token = ~400 token. 完整 80KB.
// 1 preset × ~50 token = ~5KB. 节省 ~94%.
// ============================================================
export default {
'default': {
name: 'default',
main_color: '#F4391c',
aux_color: '#F7B500',
bg_color: '#FF4646',
bg_color_shallow: '#FF4646',
promotion_color: '#FF4646',
promotion_aux_color: '#F7B500',
main_color_shallow: '#FFF4F4',
price_color: 'rgb(252,82,39)',
btn_text_color: '#FFFFFF',
goods_price: 'rgb(252,82,39,1)',
promotion_tag: '#FF4646',
goods_card_bg: '#201A18',
goods_card_bg_shallow: '#7C7878',
goods_card_color: '#FFD792',
goods_coupon: '#FC5227',
goods_cart_num_corner: '#FC5227',
goods_btn_color: '#FF4646',
goods_btn_color_shallow: '#F7B500',
pintuan_label_bg: '#F7B500',
pintuan_label_color: '#FFFFFF',
pintuan_color: '#FA6400',
pintuan_promotion_color: '#FA3A1D',
pintuan_promotion_aux_color: '#FD9A01',
super_member_start_bg: '#7c7878',
super_member_end_bg: '#201a18',
super_member_start_text_color: '#FFDBA6',
super_member_end_text_color: '#FFEBCA',
bargain_promotion_color: '#F0353E',
bargain_promotion_aux_color: '#FD9A01',
seckill_promotion_color: '#F83530',
seckill_promotion_aux_color: '#FD9A01',
giftcard_promotion_color: '#FF3369',
giftcard_promotion_aux_color: '#F7B500',
groupby_promotion_color: '#E64136',
groupby_promotion_aux_color: '#F7B500',
hover_nav_bg_color: '#FFFC',
hover_nav_text_color: '#000',
// ===== DIY 分类页字号 token =====
diy_category_tree_select_size: '28rpx',
diy_category_tree_normal_size: '20rpx',
diy_category_item_title_size: '26rpx',
diy_category_item_goods_title_size:'28rpx',
diy_category_item_name_size: '24rpx',
diy_category_item_goods_name_size:'28rpx',
diy_category_item_goods_tag_size: '22rpx',
diy_category_item_consult_now_size:'26rpx',
diy_category_item_consult_now_bg: '#FF4646',
diy_category_item_consult_now_text: '#FFFFFF',
diy_category_item_consult_now_padding: '12rpx 30rpx',
diy_category_item_consult_now_radius: '40rpx',
diy_category_item_consult_now_weight: '500',
diy_category_item_consult_now_line_height:'1.2',
diy_category_item_consult_now_text_align: 'center',
diy_category_item_consult_now_white_space:'nowrap',
diy_category_item_consult_now_display: 'inline-block',
// ===== DIY 分类页 - 商品卡 token =====
diy_category_item_goods_name_line_height:1.3,
diy_category_item_goods_name_margin_top: '20rpx',
diy_category_item_discount_price_weight: 'bold',
diy_category_item_discount_price_line_height: 1,
diy_category_item_discount_price_margin_top: '16rpx',
diy_category_item_pro_info_margin_top: '16rpx',
diy_category_item_delete_price_size: '24rpx',
diy_category_item_delete_price_line_height: 1,
diy_category_item_delete_price_text_decoration:'line-through',
diy_category_item_member_price_tag_width: '60rpx',
diy_category_item_member_price_tag_height: '28rpx',
diy_category_item_member_price_tag_line_height: 1,
diy_category_item_member_price_tag_margin_left: '6rpx',
diy_category_item_info_wrap_padding: '0 20rpx',
diy_category_item_info_wrap_margin_top: '12rpx',
diy_category_item_footer_wrap_display: 'flex',
diy_category_item_footer_wrap_justify_content: 'space-between',
diy_category_item_footer_wrap_align_items: 'normal',
diy_category_item_footer_wrap_margin_top: 0,
diy_category_item_price_wrap_display: 'block',
diy_category_item_price_wrap_align_items: 'normal',
diy_category_item_price_wrap_flex_wrap: 'nowrap',
diy_category_item_price_wrap_justify_content: 'normal',
diy_category_item_price_wrap_margin_top: 0,
diy_category_item_name_wrap_flex: '1',
diy_category_item_consult_now_wrap_display: 'flex',
diy_category_item_consult_now_wrap_justify_content:'flex-end',
diy_category_item_consult_now_wrap_margin_top: 'auto',
diy_category_item_consult_now_wrap_padding_top: '10rpx',
diy_category_item_color_tip_color: '#909399',
diy_category_item_price_font_weight: 500,
// ===== 营销 token(全 8 preset 一致) =====
pintuan_label_grad_start: '#ffbd5b',
pintuan_label_grad_end: '#fd882e',
pintuan_avatar_border: '#ff3d3d',
pintuan_success_start: '#3edb73',
pintuan_success_end: '#1db576',
bargain_promo_shallow: '#ffeadb',
seckill_price_shallow: '#fcecd7',
seckill_price_start: '#fdbe6c',
seckill_discount_start: '#ff5f17',
seckill_discount_end: '#fe2f18',
member_card_gold_start: '#E3B66B',
member_card_gold_end: '#F7DAA5',
member_icon_grad_start: '#814635',
member_icon_grad_end: '#3A221B',
balance_page_bg_start: '#FE7849',
balance_page_bg_end: '#FF1959',
point_page_bg_start: '#FE7849',
point_page_bg_end: '#FF1959',
point_promo_start: '#F8F8F8',
point_promo_end: '#E74A32',
point_item_grad_start: '#F4402B',
point_item_grad_end: '#FD7C40',
invite_grad_start: '#ff2440',
invite_grad_end: '#ff7b7b',
promote_grad_start: '#ffe2ac',
promote_grad_end: '#fdc174',
fenxiao_withdraw_start: '#ff3c29',
fenxiao_withdraw_end: '#ff6f29',
level_1_grad_start: '#9BA7B1', level_1_grad_end: '#D3DEE6',
level_2_grad_start: '#F57E2A', level_2_grad_end: '#FAD494',
level_3_grad_start: '#F85151', level_3_grad_end: '#FF9999',
level_4_grad_start: '#78B8B4', level_4_grad_end: '#AFE6E2',
level_5_grad_start: '#4DA1E1', level_5_grad_end: '#58CBF0',
level_6_grad_start: '#81C636', level_6_grad_end: '#D1F677',
level_7_grad_start: '#6D7279', level_7_grad_end: '#A5AAB0',
level_8_grad_start: '#866DDB', level_8_grad_end: '#D49BFE',
level_9_grad_start: '#f1c74e', level_9_grad_end: '#f7dc81',
level_10_grad_start: '#418CCF', level_10_grad_end: '#9CC6F1',
}
// 其他 7 个 preset (green/blue/pink/gold/purple/yellow/black)
// 全部由远端 /api/theme/presets 异步提供
// 远端拉取前切到非 default preset,会回退到 default 样式
// 注: 历史曾尝试添加 'red' preset, 但前端 style_color.js 从未定义, 已在
// config-external.js themeList 中移除以保持一致性
};

View File

@@ -12,57 +12,13 @@
* @createTime 2023-08-10
*/
import Platform from './platform.js'
class EventBus {
constructor() {
this.events = new Map()
this.domBridge = null
this.platform = this.detectPlatform()
}
// 检测平台
detectPlatform() {
// #ifdef H5
return 'h5'
// #endif
// #ifdef MP-WEIXIN
return 'weapp'
// #endif
// #ifdef MP-ALIPAY
return 'alipay'
// #endif
// #ifdef MP-BAIDU
return 'baidu'
// #endif
// #ifdef MP-TOUTIAO
return 'toutiao'
// #endif
// #ifdef MP-QQ
return 'qq'
// #endif
// #ifdef MP-KUAISHOU
return 'kuaishou'
// #endif
// #ifdef MP-JD
return 'jd'
// #endif
// #ifdef MP-360
return '360'
// #endif
// #ifdef MP-XHS
return 'xhs'
// #endif
return 'unknown'
this.platform = Platform.detect()
}
// 设置 DOM 桥接

View File

@@ -1,14 +1,83 @@
import { Platform } from './platform.js';
// 内部 helper:获取当前页面实例
const _getCurrentPage = () => {
const pages = getCurrentPages();
return pages.length === 0 ? null : pages[pages.length - 1];
};
// 内部 helper:获取当前页面路由(统一提取 route 或 $page.path)
const _getCurrentRoute = (currentPage) => {
if (!currentPage) return '';
if (currentPage.route) return currentPage.route;
if (currentPage.$page && currentPage.$page.path) return currentPage.$page.path;
return '';
};
// 内部 helper:判断 tabBarList 是否已加载且有 list 配置
const _isValidTabBarList = (tabBarList) => {
return tabBarList && tabBarList.list;
};
// 内部 helper:规范化路由:无前导斜杠时补全
const _normalizeLeadingSlash = (route) => {
if (!route) return route;
return route.startsWith('/') ? route : '/' + route;
};
// 内部 helper:通过 $util 方法的安全调用
const _callUtil = (vm, method, ...args) => {
if (vm.$util && vm.$util[method]) {
return vm.$util[method](...args);
}
return null;
};
export default {
onLoad() { },
onShow() {
// 刷新多语言
this.$langConfig.refresh();
// remote-only 小程序/鸿蒙: boot 未完成时跳过 refresh,避免空翻译写入标题等
// H5 不受影响(main.js 已 await boot 后才 $mount)
if (this.$langConfig.isRemoteOnly && this.$langConfig.isRemoteOnly()) {
if (!this.$langConfig.isBootCompleted || !this.$langConfig.isBootCompleted()) {
return;
}
}
// 刷新多语言(仅刷新标题,不触发全页面 $forceUpdate)
// 全量刷新仅在语言包真正变化时由 lang.js emitUpdated 触发
this.$langConfig.refresh(false);
// TabBar 根页面时隐藏系统导航栏的返回按钮
// (uni-app 的系统导航栏在通过 navigateTo 跳转到 tab 页时可能残留返回键)
const tabBarList = this.$store.state.tabBarList;
if (!_isValidTabBarList(tabBarList)) return;
const currentRoute = _getCurrentRoute(_getCurrentPage());
if (!currentRoute) return;
const isRoot = _callUtil(this, 'isTabBarRootPage', currentRoute, tabBarList) || false;
if (isRoot) {
// #ifdef MP-WEIXIN || MP-BAIDU || MP-TOUTIAO || MP-QQ || MP-ALIPAY
try { uni.hideHomeButton(); } catch (e) { /* 兼容 */ }
// #endif
}
},
computed: {
// 是否是英文环境
isEnEnv() {
return this.$langConfig.getCurrentLocale() === 'en-us';
},
// 是否是非中文环境(用于多语言商品名/字段切换)
isNotZhEnv() {
return this.$langConfig.getCurrentLocale() !== 'zh-cn';
},
// 动态判断:当前页面是否是 TabBar 根页面(tab 根页不应显示返回按钮)
isTabRootPage() {
const tabBarList = this.$store.state.tabBarList;
if (!_isValidTabBarList(tabBarList)) return false;
const currentRoute = _getCurrentRoute(_getCurrentPage());
if (!currentRoute) return false;
return _callUtil(this, 'isTabBarRootPage', currentRoute, tabBarList) || false;
},
themeStyle() {
return this.$store.state.themeStyle;
},
@@ -22,6 +91,28 @@ export default {
tabBarList() {
return this.$store.state.tabBarList;
},
shouldShowTabBar() {
const tabBarList = this.$store.state.tabBarList;
if (!_isValidTabBarList(tabBarList)) return false;
const mode = tabBarList.page_visibility_mode;
const routeList = tabBarList.page_routes || [];
if (!mode || mode === 'all') return true;
if (mode === 'none') return false;
const currentPage = _getCurrentPage();
if (!currentPage) return true;
const currentRoute = _normalizeLeadingSlash(_getCurrentRoute(currentPage));
if (!currentRoute) return true;
const inList = _callUtil(this, 'isPageInRouteList', currentRoute, routeList) || false;
if (mode === 'whitelist') return inList;
if (mode === 'blacklist') return !inList;
return true;
},
tabBarPagePaddingStyle() {
return this.$util.objToStyle({
height: `calc(100vh - ${this.tabBarHeight})`,
paddingBottom: this.tabBarHeight
});
},
siteInfo() {
return this.$store.state.siteInfo;
},
@@ -65,6 +156,10 @@ export default {
componentRefresh() {
return this.$store.state.componentRefresh;
},
// AI客服配置
globalAIKefuConfig() {
return this.$store.state.globalAIKefuConfig;
},
// 客服配置
servicerConfig() {
return this.$store.state.servicerConfig;
@@ -77,7 +172,7 @@ export default {
return this.$store.state.diySeckillInterval;
},
tabBarHeight() {
return this.$store.state.tabBarHeight;
return this.shouldShowTabBar ? this.$store.state.tabBarHeight : '0rpx';
},
mapConfig() {
return this.$store.state.mapConfig;
@@ -105,6 +200,13 @@ export default {
}
},
methods: {
/**
* 当前平台类型(多端翻译隔离)
* 复用 Platform.getAppType(),与服务端 /api/BaseApi 的 $app_type 对齐
*/
getAppType() {
try { return Platform.getAppType() || '*'; } catch (e) { return '*'; }
},
// 颜色变浅(>0)、变深函数(<0)
lightenDarkenColor(color, amount) {
@@ -151,6 +253,53 @@ export default {
this.$store.dispatch('getCartNumber'); //重新获取购物车数据
this.$util.redirectTo(this.$util.INDEX_PAGE_URL);
}
},
/**
* 金额格式化输出
* @param {Object} money
*/
moneyFormat(money) {
if (isNaN(parseFloat(money))) return money;
return parseFloat(money).toFixed(2);
},
/**
* 重新定向到登录授权, 不区分生命周期
* @param {String} backUrl
* @param {Object} params 附加参数
* @param {Function} effectFnc 副作用函数, 登录授权失败的处理方式
*/
redirectTologin(backUrl = '', params = {}, effectFnc = ()=>{}) {
console.log(`------> redirectTologin`, backUrl);
setTimeout(() => {
this.$nextTick(() => {
let mode = 'navigateTo';
// #ifdef H5 || MP-HARMONY
mode = 'redirectTo'; // H5必须使用redirectTo, 不然点击返回箭头无法返回。
// #endif
this.$refs?.login?.open(backUrl, mode, effectFnc);
});
}, 0);
},
/**
* 重新定向到登录授权, 当页面显示的时候, 失败后,
* 原因:onLoad、onReady 只执行一次;
* 而且,有的页面不需要这个功能
* @param {String} backUrl
*/
redirectTologinOnShowLifecycle(backUrl) {
console.log(`------> redirectTologinOnShowLifecycle`, backUrl);
// #ifdef H5 || MP-HARMONY
this.redirectTologin(backUrl);
// #endif
// #ifdef MP-WEIXIN
this.redirectTologin(backUrl, {}, () => {
uni.navigateBack({delta: 1 });
})
// #endif
}
},
filters: {

View File

@@ -141,7 +141,7 @@ export default {
});
this.goodsSkuDetail.swiperHeight = maxHeight + 'px';
this.goodsSkuDetail.unit = this.goodsSkuDetail.unit || "件";
this.goodsSkuDetail.unit = this.goodsSkuDetail.unit || this.$lang('unit.piece');
// 当前商品SKU规格
if (this.goodsSkuDetail.sku_spec_format) this.goodsSkuDetail.sku_spec_format = JSON.parse(this.goodsSkuDetail.sku_spec_format);
@@ -164,7 +164,6 @@ export default {
// 商品详情
if (this.goodsSkuDetail.goods_content) this.goodsSkuDetail.goods_content = (this.goodsSkuDetail.goods_content);
console.log(this.goodsSkuDetail.goods_content)
// if (this.goodsSkuDetail.goods_content) this.goodsSkuDetail.goods_content = htmlParser(this.goodsSkuDetail.goods_content);
//商品服务
@@ -200,7 +199,7 @@ export default {
if (this.$refs.goodsDetailView) {
// 初始化商品详情视图数据
this.goodsSkuDetail.unit = this.goodsSkuDetail.unit || "件";
this.goodsSkuDetail.unit = this.goodsSkuDetail.unit || this.$lang('unit.piece');
// 解决轮播图数量不一致时,切换到第一个
if (this.swiperCurrent > this.goodsSkuDetail.sku_images.length) {

View File

@@ -316,11 +316,9 @@ function replaceVideo(html){
let rep = `<video style="width:100% !important;display:block;max-width: ${screenWidth} !important;"`;
var html = html.replace(/\\/g, '').replace(/<video/g, rep);
console.log(html)
html = html.replace(/<video [^>]*src=['"]([^'"]+)[^>]*>/gi, (match, capture) => {
return rep + ' src="' + util.img(capture) + '"/>';
});
// console.log(html)
return html;
}

View File

@@ -1,65 +1,172 @@
import Config from './config.js'
import Util from './util.js'
import store from '@/store/index.js'
import Platform from './platform.js'
// #ifdef H5
const app_type = Util.isWeiXin() ? 'wechat' : 'h5';
const app_type_name = Util.isWeiXin() ? '微信公众号' : 'H5';
// #endif
const { appType, appTypeName } = Platform.getPlatformInfo();
// #ifdef MP-WEIXIN
const app_type = 'weapp';
const app_type_name = '微信小程序';
// #endif
let _Lang = null;
function getLang() {
if (!_Lang) {
_Lang = require('./lang.js').default;
}
return _Lang;
}
// #ifdef MP-ALIPAY
const app_type = 'aliapp';
const app_type_name = '支付宝小程序';
// #endif
const DEFAULT_TIMEOUT = 15000;
const DEFAULT_MAX_RETRIES = 2;
const RETRY_DELAY_BASE = 2000;
// #ifdef MP-BAIDU
const app_type = 'baiduapp';
const app_type_name = '百度小程序';
// #endif
function _shouldRetry(errMsg) {
if (!errMsg) return false;
if (errMsg === 'request:fail url not in domain list') return false;
if (errMsg === 'request:fail abort') return false;
const retryableErrors = [
'request:fail timeout',
'request:fail connect',
'request:fail network'
];
return retryableErrors.some(err => errMsg.startsWith(err));
}
// #ifdef MP-TOUTIAO
const app_type = 'MP-TOUTIAO';
const app_type_name = '头条小程序';
// #endif
function _classifyError(errMsg, statusCode) {
if (!errMsg && !statusCode) return 'unknown';
if (errMsg === 'request:fail abort') return 'aborted';
if (errMsg && errMsg.indexOf('timeout') !== -1) return 'timeout';
if (errMsg && (errMsg.indexOf('connect') !== -1 || errMsg.indexOf('network') !== -1)) return 'networkError';
if (statusCode && statusCode >= 500) return 'serverError';
if (errMsg && errMsg.indexOf('url not in domain list') !== -1) return 'domainNotInList';
return 'unknown';
}
// #ifdef MP-QQ
const app_type = 'MP-QQ';
const app_type_name = 'QQ小程序';
// #endif
function _sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
// #ifdef APP-PLUS
const app_type = 'app';
const app_type_name = 'APP';
// #endif
function _makeRequest(url, method, data, header, dataType, responseType, timeout) {
return new Promise((resolve, reject) => {
uni.request({
url: url,
method: method,
data: data,
header: header,
dataType: dataType,
responseType: responseType,
timeout: timeout,
success: (res) => {
if (res.statusCode && [200, 500].indexOf(res.statusCode) == -1) {
reject({ errMsg: `request:fail statusCode=${res.statusCode}`, statusCode: res.statusCode });
return;
}
if (res.data.code == -3 && store.state.siteState > 0) {
store.commit('setSiteState', -3);
Util.redirectTo('/pages_tool/storeclose/storeclose', {}, 'reLaunch');
return;
}
if (res.data.refreshtoken) {
store.commit('setToken', res.data.refreshtoken);
}
if (res.data.code == -10009 || res.data.code == -10010) {
store.commit('setToken', '');
store.commit('setMemberInfo', '');
}
resolve(res.data);
},
fail: (res) => {
reject(res);
}
});
});
}
async function _requestWithRetry(params, url, method, data, header, dataType, responseType) {
const timeout = params.timeout || DEFAULT_TIMEOUT;
const maxRetries = params.noRetry ? 0 : (params.maxRetries || DEFAULT_MAX_RETRIES);
let lastError = null;
let lastStatusCode = null;
for (let attempt = 0; attempt <= maxRetries; attempt++) {
try {
const result = await _makeRequest(url, method, data, header, dataType, responseType, timeout);
return result;
} catch (err) {
lastError = err;
lastStatusCode = err && err.statusCode;
if (attempt >= maxRetries || !_shouldRetry(err.errMsg)) {
break;
}
const delay = RETRY_DELAY_BASE * Math.pow(2, attempt);
await _sleep(delay);
}
}
if (params.silentError) {
throw lastError;
}
const errorType = _classifyError(lastError && lastError.errMsg, lastStatusCode);
const lang = getLang();
if (errorType === 'domainNotInList') {
uni.showToast({
title: lang.lang('http.domainNotInList', { url: Config.baseUrl }),
'icon': 'none',
duration: 10000
});
} else {
const i18nKey = 'http.' + errorType;
uni.showToast({
title: lang.lang(i18nKey),
'icon': 'none',
duration: 10000
});
}
throw lastError;
}
export default {
sendRequest(params) {
if (!Config.baseUrl) {
uni.showToast({
title: '未配置请求域名',
title: getLang().lang('http.baseUrlNotConfigured'),
'icon': 'none',
duration: 10000
});
return;
}
var method = params.data != undefined ? 'POST' : 'GET', // 请求方式
url = (Config.baseUrl + params.url).replace(/(?<!:)\/+/g, '/'), // 请求路径
const _isRemoteOnly = getLang().isRemoteOnly && getLang().isRemoteOnly();
const _bootDone = getLang().isBootCompleted && getLang().isBootCompleted();
if (_isRemoteOnly && !_bootDone) {
let bootPromise = null;
try {
const app = getApp();
if (app && app.$langReady) bootPromise = app.$langReady;
} catch (e) {}
if (!bootPromise) bootPromise = getLang().boot();
if (params.async === false) {
return bootPromise.then(() => this._sendRequestNow(params));
} else {
bootPromise.then(() => this._sendRequestNow(params));
return;
}
}
return this._sendRequestNow(params);
},
_sendRequestNow(params) {
var method = params.data != undefined ? 'POST' : 'GET',
url = (Config.baseUrl + params.url).replace(/(?<!:)\/+/g, '/'),
data = {
app_type,
app_type_name
app_type: appType,
app_type_name: appTypeName
};
// token
data.token = store.state.token || '';
data.uniacid = uni.getStorageSync('uniacid') || Config.uniacid; // 从缓存中获取uniacid,或使用默认uniacid,支持快应用
data.uniacid = uni.getStorageSync('uniacid') || Config.uniacid;
// 门店id
var default_store_info = store.state.defaultStoreInfo;
if (default_store_info) {
data.store_id = default_store_info.store_id;
@@ -69,123 +176,34 @@ export default {
if (store_info) data.store_id = store_info.store_id;
// 参数
if (params.data != undefined) Object.assign(data, params.data);
const header = params.header || {
'content-type': 'application/x-www-form-urlencoded;application/json'
};
const dataType = params.dataType || 'json';
const responseType = params.responseType || 'text';
if (params.async === false) {
//同步
return new Promise((resolve, reject) => {
uni.request({
url: url,
method: method,
data: data,
header: params.header || {
// 'Accept': 'application/json',
'content-type': 'application/x-www-form-urlencoded;application/json'
},
dataType: params.dataType || 'json',
responseType: params.responseType || 'text',
success: (res) => {
// try {
// res.data = JSON.parse(res.data);
// } catch (e) {
// //TODO handle the exception
// console.log('api error:', e);
// }
if (res.data.code == -3 && store.state.siteState > 0) {
store.commit('setSiteState', -3);
Util.redirectTo('/pages_tool/storeclose/storeclose', {}, 'reLaunch');
return;
}
if (res.data.refreshtoken) {
store.commit('setToken', res.data.refreshtoken);
}
if (res.data.code == -10009 || res.data.code == -10010) {
store.commit('setToken', '');
store.commit('setMemberInfo', '');
}
resolve(res.data);
},
fail: (res) => {
if (res.errMsg && res.errMsg == 'request:fail url not in domain list') {
uni.showToast({
title: Config.baseUrl + '不在request 合法域名列表中',
'icon': 'none',
duration: 10000
});
return;
}
reject(res);
},
complete: (res) => {
if ((res.errMsg && res.errMsg != "request:ok") || (res.statusCode && [200, 500].indexOf(res.statusCode) == -1)) {
uni.showToast({
title: Config.baseUrl + '请求失败',
'icon': 'none',
duration: 10000
});
return;
}
reject(res.data);
}
return _requestWithRetry(params, url, method, data, header, dataType, responseType)
.then(res => {
typeof params.complete == 'function' && params.complete(res);
return res;
})
.catch(err => {
typeof params.complete == 'function' && params.complete();
throw err;
});
});
} else {
//异步
uni.request({
url: url,
method: method,
data: data,
header: params.header || {
// 'Accept': 'application/json',
'content-type': 'application/x-www-form-urlencoded;application/json'
},
dataType: params.dataType || 'json',
responseType: params.responseType || 'text',
success: (res) => {
// try {
// res.data = JSON.parse(res.data);
// } catch (e) {
// //TODO handle the exception
// console.log('api error:', e);
// }
if (res.data.code == -3 && store.state.siteState > 0) {
store.commit('setSiteState', -3);
Util.redirectTo('/pages_tool/storeclose/storeclose', {}, 'reLaunch');
return;
}
if (res.data.refreshtoken) {
store.commit('setToken', res.data.refreshtoken);
}
if (res.data.code == -10009 || res.data.code == -10010) {
store.commit('setToken', '');
store.commit('setMemberInfo', '');
}
typeof params.success == 'function' && params.success(res.data);
},
fail: (res) => {
if (res.errMsg && res.errMsg == 'request:fail url not in domain list') {
uni.showToast({
title: Config.baseUrl + '不在request 合法域名列表中',
'icon': 'none',
duration: 10000
});
return;
}
typeof params.fail == 'function' && params.fail(res);
},
complete: (res) => {
if ((res.errMsg && res.errMsg != "request:ok") || (res.statusCode && [200, 500].indexOf(res.statusCode) == -1)) {
uni.showToast({
title: Config.baseUrl + '请求失败',
'icon': 'none',
duration: 10000
});
return;
}
typeof params.complete == 'function' && params.complete(res.data);
}
});
_requestWithRetry(params, url, method, data, header, dataType, responseType)
.then(res => {
typeof params.success == 'function' && params.success(res);
typeof params.complete == 'function' && params.complete(res);
})
.catch(err => {
typeof params.fail == 'function' && params.fail(err);
typeof params.complete == 'function' && params.complete();
});
}
},
uploadBase64(params) {
@@ -196,8 +214,8 @@ export default {
'content-type': 'application/x-www-form-urlencoded;application/json'
},
data: {
app_type,
app_type_name,
app_type: appType,
app_type_name: appTypeName,
images: params.base64
},
dataType: 'json',
@@ -218,8 +236,8 @@ export default {
'content-type': 'application/x-www-form-urlencoded;application/json'
},
data: {
app_type,
app_type_name,
app_type: appType,
app_type_name: appTypeName,
path: params.path
},
dataType: 'json',
@@ -239,8 +257,8 @@ export default {
name: params.name || 'file',
fileType: params.fileType || 'image',
formData: {
app_type,
app_type_name,
app_type: appType,
app_type_name: appTypeName,
},
header: {
'content-type': 'application/x-www-form-urlencoded;application/json'

15
common/js/image-config.js Normal file
View File

@@ -0,0 +1,15 @@
/**
* 图片配置文件
* 将大图片上传到服务器后,请在此处配置网络URL
*/
// 替换为你上传后的实际图片URL
const IMAGE_CONFIG = {
// AI客服头像
aiAvatar: 'public/static/img/s-agent.jpg',
// 用户默认头像
userAvatar: 'public/static/img/s-user.jpg'
};
export default IMAGE_CONFIG;

View File

@@ -0,0 +1,11 @@
/**
* remote-only 模式下的空语言包 stub
*
* 当 source === 'remote-only' 时,webpack NormalModuleReplacementPlugin
* 会把所有 @/lang/ 下的 require 替换为这个文件,
* 避免本地 lang/ 目录被打进产物。
*
* 导出格式与真实语言包一致: { lang: {} }
*/
export const lang = {};
export default { lang };

440
common/js/lang-loader.js Normal file
View File

@@ -0,0 +1,440 @@
/**
* 远端语言包 bundle 加载器
*
* 职责:
* 1. 从后端 /api/lang/bundle 拉取完整语言树
* 2. 做本地 storage 缓存 + 内存缓存
* 3. 支持签名校验(可选)
* 4. 支持 diff 增量更新(预留)
* 5. 对外暴露 loadBundleTree / getCachedBundle / clearBundleCache
*
* 与 lang.js 的关系:
* 当 langConfig.source === 'remote-only' 时,lang.js 不再 require 本地 lang/ 文件,
* 而是直接复用本模块加载的 tree。
*/
import { langConfig } from './config-external.js';
import Config from './config.js';
import { Platform } from './platform.js';
const FORBIDDEN_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
// 内存缓存: { [memKey]: { version, tree, ts } }
const bundleCache = {};
// 关键修复: 缓存 fetchBundle 迟到的成功结果
// 即使 Promise.race 已 timeout, uni.request 内部可能继续完成
// 缓存这份迟到结果, 给上层 catch 后的"补救"逻辑使用
// 结构: { `${lang}_${appType}_${uniacid}`: { data, ts, lang, appType, uniacid } }
const _lastSuccessfulResult = {};
// 缓存 TTL(与 BUNDLE_CACHE_TTL 一致): 10 分钟
const _LAST_RESULT_TTL = 10 * 60 * 1000;
// 并发去重
const bundleInflight = {};
/**
* 三维隔离 key: <uniacid>_<appType>_<lang>
*/
function getBundleMemKey(uniacid, appType, lang) {
return `${uniacid || 0}_${appType || '*'}_${lang}`;
}
/**
* storage key: 与 memKey 维度一致
*/
function getBundleStorageKey(uniacid, appType, lang) {
return `${langConfig.remote.storagePrefix || 'LANG_BUNDLE_'}${getBundleMemKey(uniacid, appType, lang)}`;
}
function getCurrentLocale() {
try {
return uni.getStorageSync('lang') || langConfig.defaultLang || 'zh-cn';
} catch (e) {
return langConfig.defaultLang || 'zh-cn';
}
}
function getCurrentUniacid() {
try {
const u = uni.getStorageSync('uniacid');
return u ? parseInt(u, 10) || 0 : 0;
} catch (e) {
return 0;
}
}
function getCurrentAppType() {
try { return Platform.getAppType() || '*'; } catch (e) { return '*'; }
}
/**
* 深度合并两个对象,source 覆盖 target
*/
function deepMerge(target, source) {
if (target === null || typeof target !== 'object') return source;
if (source === null || typeof source !== 'object') return source;
if (Array.isArray(target) || Array.isArray(source)) return source;
for (const key in source) {
if (!Object.prototype.hasOwnProperty.call(source, key)) continue;
if (FORBIDDEN_KEYS.has(key)) continue;
const srcVal = source[key];
const tgtVal = target[key];
if (
srcVal !== null && typeof srcVal === 'object' && !Array.isArray(srcVal) &&
tgtVal !== null && typeof tgtVal === 'object' && !Array.isArray(tgtVal)
) {
target[key] = deepMerge(tgtVal, srcVal);
} else {
target[key] = srcVal;
}
}
return target;
}
/**
* 简易签名校验
* 后端: hash_hmac('sha256', version + json_encode(tree), secret)
* 前端: 同样算法
*/
function validateSign(tree, version, sign, secret) {
if (!secret || !sign) return true;
// 前端没有 crypto-js,用简单字符串拼接做校验(仅基础防篡改)
// 如需强校验,建议引入 crypto-js 或小程序/APP 端使用原生加密 API
// 关键修复: 用 try-catch 保护 btoa(),避免在小程序环境(无 btoa)中抛 ReferenceError
let _btoaResult = '';
try {
const payload = JSON.stringify(tree);
// 兼容小程序环境: 没有原生 btoa 时降级
if (typeof btoa === 'function') {
_btoaResult = btoa(version + ':' + payload).replace(/[^a-zA-Z0-9]/g, '').slice(0, 32);
} else if (typeof uni !== 'undefined' && typeof uni.arrayBufferToBase64 === 'function') {
// 微信小程序/uni-app 提供 arrayBufferToBase64
const _encoder = (typeof TextEncoder !== 'undefined')
? new TextEncoder().encode(version + ':' + payload)
: null;
if (_encoder) {
_btoaResult = uni.arrayBufferToBase64(_encoder.buffer).replace(/[^a-zA-Z0-9]/g, '').slice(0, 32);
}
}
} catch (e) {
// 签名计算失败也不应阻断 bundle 加载,静默失败
}
// 后端返回的是 hash_hmac('sha256', version + payload, secret)
// 这里只做格式校验,不强校验(因为无 crypto 库)
return typeof sign === 'string' && sign.length > 0;
}
// 缓存 TTL(ms): 与后端 Cache::set 600s 对齐,过期后后台刷新
const BUNDLE_CACHE_TTL = (langConfig.remote.cacheTtl || 600) * 1000;
/**
* 从 storage 读取缓存(检查 TTL 过期)
* @returns {Object|null} 未过期返回 {tree,version,ts}, 过期返回 null
*/
function readStorageCache(sk) {
try {
const cached = uni.getStorageSync(sk);
if (cached && cached.tree && typeof cached.tree === 'object') {
// TTL 检查: 超过 cacheTtl 视为过期
if (cached.ts && (Date.now() - cached.ts < BUNDLE_CACHE_TTL)) {
return cached;
}
}
} catch (e) {}
return null;
}
/**
* 检查内存缓存是否过期
*/
function isMemoryCacheExpired(record) {
if (!record || !record.ts) return true;
return (Date.now() - record.ts) >= BUNDLE_CACHE_TTL;
}
/**
* 写入 storage 缓存
*/
function writeStorageCache(sk, data) {
try {
uni.setStorageSync(sk, data);
} catch (e) {
// storage 写满时静默失败
}
}
/**
* 从后端拉取 bundle
*
* 关键修复: 即使 Promise.race 在 timeout 时已经 reject,
* uni.request 内部仍可能继续执行并成功返回。
* 之前这些"迟到"的成功响应被完全丢弃,导致:
* 1. fetchBundle 抛 timeout 错
* 2. _bootImpl 进 catch, 不写 remoteTreeCache
* 3. uni.request 终于成功, 但没人接收, 结果被 GC
* 现在改为: uni.request 完成后, **无论 Promise.race 状态如何**,
* 都把结果写入 _lastSuccessfulResult 缓存。
* _bootImpl 可以在 catch 后**主动等待**这份迟到数据(最多 3 秒),
* 从而真正用上远端返回的完整 bundle。
*/
async function fetchBundle(lang, appType, uniacid, timeout) {
const url = langConfig.remote.bundleUrl || '/api/lang/bundle';
const data = { lang };
if (appType && appType !== '*') data.app_type = appType;
// uniacid 必须传给后端,后端按 (uniacid × app_type) 二维查询租户专属覆写
if (uniacid !== undefined && uniacid !== null) data.uniacid = uniacid;
// 直接用 uni.request 包装 Promise,不依赖 http.sendRequest
// (sendRequest 的异步分支不返回 Promise,只有 async:false 分支才返回)
// 去重双斜杠: baseUrl 末尾可能带 /, bundleUrl 开头也带 /
const fullUrl = (Config.baseUrl || '').replace(/\/+$/, '') + url;
// 关键修复: 用一个 "completionLatch" 跟踪 uni.request 是否最终完成(成功或失败)
// 即使 Promise.race 已经 timeout reject, uni.request 内部仍可能继续完成
// 我们保留这份迟到结果到 _lastSuccessfulResult, 给上层补救的机会
const inflightKey = `${lang}_${appType}_${uniacid}`;
const res = await Promise.race([
new Promise((resolve, reject) => {
uni.request({
url: fullUrl,
method: 'POST',
data: data,
header: { 'content-type': 'application/x-www-form-urlencoded' },
dataType: 'json',
success: (response) => {
// 关键: 即使 Promise.race 已 reject, 仍然把成功结果写入全局缓存
// 给 loadBundleTree catch 后 "补救" 的机会
try {
if (response && response.data && response.data.code === 0 && response.data.data && response.data.data.tree) {
_lastSuccessfulResult[inflightKey] = {
data: response.data,
ts: Date.now(),
lang, appType, uniacid,
};
}
} catch (e) {}
resolve(response.data);
},
fail: (err) => {
reject(new Error(err.errMsg || 'bundle request failed'));
},
});
}),
new Promise((_, reject) => setTimeout(() => {
reject(new Error('timeout'));
}, timeout)),
]);
if (!res || res.code !== 0 || !res.data) {
throw new Error(res && res.message ? res.message : 'bundle fetch failed');
}
return res.data;
}
/**
* 加载 bundle tree
*
* @param {Object} options
* @param {string} lang 语言
* @param {string} [appType] 平台类型
* @param {number} [uniacid] 租户 id
* @param {boolean} [allowCache=true] 是否允许使用缓存
* @param {boolean} [force=false] 是否强制刷新
* @returns {Promise<{tree:Object, version:string, source:string}>}
*/
export async function loadBundleTree(options = {}) {
const lang = options.lang || getCurrentLocale();
const appType = options.appType || getCurrentAppType();
const uniacid = options.uniacid !== undefined ? options.uniacid : getCurrentUniacid();
const allowCache = options.allowCache !== false;
const force = options.force === true;
const mk = getBundleMemKey(uniacid, appType, lang);
const sk = getBundleStorageKey(uniacid, appType, lang);
if (bundleInflight[mk]) {
return bundleInflight[mk];
}
const task = (async () => {
try {
// 1) 内存缓存未过期直接返回
if (!force && allowCache && bundleCache[mk] && !isMemoryCacheExpired(bundleCache[mk])) {
return { tree: bundleCache[mk].tree, version: bundleCache[mk].version, source: 'memory' };
}
// 2) 读取 storage 缓存(已含 TTL 检查)
let cached = null;
if (!force && allowCache) {
cached = readStorageCache(sk);
if (cached && !bundleCache[mk]) {
bundleCache[mk] = cached;
}
}
// 3) 远端拉取
const timeout = langConfig.remote.requestTimeout || 4000;
const payload = await fetchBundle(lang, appType, uniacid, timeout);
const tree = payload.tree || {};
const version = String(payload.version || '');
const sign = payload.sign || '';
// 4) 签名校验(可选)
const secret = langConfig.remote.signSecret || '';
const signValid = validateSign(tree, version, sign, secret);
if (!signValid) {
throw new Error('bundle sign invalid');
}
// 5) 更新缓存
const record = { version, tree, ts: Date.now() };
bundleCache[mk] = record;
writeStorageCache(sk, record);
return { tree, version, source: 'remote' };
} catch (e) {
// 关键修复: 补救迟到数据
// fetchBundle 因 timeout 抛错时, uni.request 内部可能仍然成功(只是没 Promise 接收)
// 之前这些"迟到"数据被完全丢弃,导致 boot 失败后永远等不到远端数据
// 现在: catch 后等待 _lastSuccessfulResult 出现(最多 3 秒), 期间如果迟到数据到达则用之
const inflightKey = `${lang}_${appType}_${uniacid}`;
// 等待 _lastSuccessfulResult 出现(超时后 uni.request 内部 success 回调可能稍后才触发)
const waitStart = Date.now();
const WAIT_MAX_MS = 3000;
const WAIT_POLL_MS = 100;
while (Date.now() - waitStart < WAIT_MAX_MS) {
const lateResult = _lastSuccessfulResult[inflightKey];
if (lateResult && (Date.now() - lateResult.ts) < _LAST_RESULT_TTL) {
// 有"迟到"数据, 直接用
const resp = lateResult.data;
// resp 结构: { code, message, data: { version, tree, sign } }
const dataNode = resp && resp.data;
const tree = (dataNode && dataNode.tree) || {};
const version = String((dataNode && dataNode.version) || '');
const sign = (dataNode && dataNode.sign) || '';
const signValid = validateSign(tree, version, sign, langConfig.remote.signSecret || '');
if (signValid) {
const record = { version, tree, ts: Date.now() };
bundleCache[mk] = record;
writeStorageCache(sk, record);
return { tree, version, source: 'remote-late' };
}
}
// 等待 WAIT_POLL_MS
await new Promise((r) => setTimeout(r, WAIT_POLL_MS));
}
// 6) 失败时回退到缓存
// 关键修复: force=true 时**不回退**到 bundleCache
// 旧逻辑: force 失败 → 回退到旧 cache → 标记新 ts → 永远不被刷新 → bundle 缺 key
// 新逻辑: force 失败 → 抛错, 让上层 _bootImpl 进入 catch 块走真正的"无 cache 兜底"
if (force) {
throw e;
}
if (allowCache && bundleCache[mk]) {
return { tree: bundleCache[mk].tree, version: bundleCache[mk].version, source: 'cache', error: e.message };
}
throw e;
} finally {
delete bundleInflight[mk];
}
})();
bundleInflight[mk] = task;
return task;
}
/**
* 获取已缓存的 bundle(不触发网络请求)
* 注意: 受 TTL 限制,过期缓存返回 null
*/
export function getCachedBundle(options = {}) {
const lang = options.lang || getCurrentLocale();
const appType = options.appType || getCurrentAppType();
const uniacid = options.uniacid !== undefined ? options.uniacid : getCurrentUniacid();
const mk = getBundleMemKey(uniacid, appType, lang);
const sk = getBundleStorageKey(uniacid, appType, lang);
if (bundleCache[mk]) return bundleCache[mk];
const cached = readStorageCache(sk);
if (cached) {
bundleCache[mk] = cached;
return cached;
}
return null;
}
/**
* 获取任意已缓存的 bundle(不检查 TTL),仅用于 boot 失败兜底
*
* 与 getCachedBundle 的区别:
* - getCachedBundle: 受 BUNDLE_CACHE_TTL 限制,过期返回 null(用于日常 $lang 渲染)
* - getCachedBundleAny: 不检查 TTL,只要内存或 storage 中有就返回(用于失败兜底)
*
* 设计意图:
* boot() 强制重试失败时,如果用户本地还有哪怕过期的 bundle,
* 也比"$lang() 全返回空串"用户体验更好 — 至少能展示残缺文案。
* 这是显式的"宁可用过期缓存,也不空白"的取舍。
*
* 优先返回内存缓存(更快),其次返回 storage 缓存。
*
* @returns {{version:string, tree:Object, ts:number, source:'memory'|'storage'}|null}
*/
export function getCachedBundleAny(options = {}) {
const lang = options.lang || getCurrentLocale();
const appType = options.appType || getCurrentAppType();
const uniacid = options.uniacid !== undefined ? options.uniacid : getCurrentUniacid();
const mk = getBundleMemKey(uniacid, appType, lang);
const sk = getBundleStorageKey(uniacid, appType, lang);
// 1) 内存缓存优先(任意 TTL,过期也返回)
if (bundleCache[mk] && bundleCache[mk].tree) {
return { ...bundleCache[mk], source: 'memory' };
}
// 2) storage 兜底(任意 TTL,不调用 readStorageCache 因为它内部会查 TTL)
try {
const raw = uni.getStorageSync(sk);
if (raw && raw.tree && typeof raw.tree === 'object') {
// 写回内存缓存,方便下次 getCachedBundle / getCachedBundleAny 命中
bundleCache[mk] = raw;
return { ...raw, source: 'storage' };
}
} catch (e) { /* 忽略 */ }
return null;
}
/**
* 清除 bundle 缓存
*/
export function clearBundleCache(options = {}) {
const lang = options.lang || getCurrentLocale();
const appType = options.appType || getCurrentAppType();
const uniacid = options.uniacid !== undefined ? options.uniacid : getCurrentUniacid();
const mk = getBundleMemKey(uniacid, appType, lang);
const sk = getBundleStorageKey(uniacid, appType, lang);
delete bundleCache[mk];
try { uni.removeStorageSync(sk); } catch (e) {}
}
/**
* 检查是否有缓存可用(用于启动时快速判断)
*/
export function hasBundleCache(options = {}) {
return getCachedBundle(options) !== null;
}
/**
* 合并本地语言包与远端 bundle tree(混合模式用)
*/
export function mergeLocalWithBundle(localTree, bundleTree) {
if (!localTree || typeof localTree !== 'object') return bundleTree || {};
if (!bundleTree || typeof bundleTree !== 'object') return localTree || {};
return deepMerge(deepMerge({}, localTree), bundleTree);
}

File diff suppressed because it is too large Load Diff

View File

@@ -7,14 +7,12 @@
*/
import Util from './util.js'
import Lang from './lang.js';
var ERROR_CONF = {
KEY_ERR: 311,
KEY_ERR_MSG: 'key格式错误',
PARAM_ERR: 310,
PARAM_ERR_MSG: '请求参数信息有误',
SYSTEM_ERR: 600,
SYSTEM_ERR_MSG: '系统错误',
WX_ERR_CODE: 1000,
WX_OK_CODE: 200
};
@@ -385,7 +383,7 @@ var Utils = {
*/
checkParamKeyEmpty(param, key) {
if (!param[key]) {
var errconf = this.buildErrorConfig(ERROR_CONF.PARAM_ERR, ERROR_CONF.PARAM_ERR_MSG + key +'参数格式有误');
var errconf = this.buildErrorConfig(ERROR_CONF.PARAM_ERR, Lang.lang('common.mapWxJssdk.paramFormatError', { param: key }));
param.fail(errconf);
param.complete(errconf);
return true;
@@ -410,7 +408,7 @@ var Utils = {
checkLocation(param) {
var location = this.getLocationParam(param.location);
if (!location || !location.latitude || !location.longitude) {
var errconf = this.buildErrorConfig(ERROR_CONF.PARAM_ERR, ERROR_CONF.PARAM_ERR_MSG + ' location参数格式有误');
var errconf = this.buildErrorConfig(ERROR_CONF.PARAM_ERR, Lang.lang('common.mapWxJssdk.locationParamFormatError'));
param.fail(errconf);
param.complete(errconf);
return false;
@@ -623,7 +621,7 @@ var Utils = {
break;
}
default:{
param.complete(that.buildErrorConfig(ERROR_CONF.SYSTEM_ERR, ERROR_CONF.SYSTEM_ERR_MSG));
param.complete(that.buildErrorConfig(ERROR_CONF.SYSTEM_ERR, Lang.lang('common.mapWxJssdk.systemError')));
}
}
@@ -664,7 +662,7 @@ class QQMapWX {
*/
constructor(options) {
if (!options.key) {
throw Error('key值不能为空');
throw Error(Lang.lang('common.mapWxJssdk.keyCannotBeEmpty'));
}
this.key = options.key;
};

View File

@@ -1,5 +1,6 @@
import util from '@/common/js/util.js'
import TransformCoordinate from './transformCoordinate.js'
import Lang from '@/common/js/lang.js'
function openMapByDefault(latitude, longitude, name) {
uni.openLocation({
@@ -8,7 +9,7 @@ function openMapByDefault(latitude, longitude, name) {
name: name,
fail: (e) => {
uni.showModal({
content: '打开地图失败,请稍后重试'
content: Lang.lang('common.map.openMapFailed')
})
},
})
@@ -89,16 +90,14 @@ export default {
let platform = util.getDeviceInfo().platform;
switch (platform) {
case 'android':
console.log('运行Android上')
case 'harmony':
openMapByAndroid(arr[1], arr[0], name)
break;
case 'ios':
console.log('运行iOS上')
openMapByIos(arr[1], arr[0], name)
break;
default:
openMapByDefault(arr[1], arr[0], name)
console.log('运行在开发者工具上')
break;
}
// #endif

81
common/js/merge-theme.js Normal file
View File

@@ -0,0 +1,81 @@
/**
* 主题 token 合并工具
*
* 与 lang.js::applyOverrides 同构(都是"远端扁平覆写 map"按 key 路径合并),
* 差异:
* - 主题 token 是"扁平叶子"(如 main_color / bg_color),没有嵌套层级
* - 需要支持"三桶叠加":presetBase(本地预设) < brand(品牌色) < userMode(夜间/浅色)
* - value 是色值字符串(也允许空串 = 显式清空)
*
* 危险 key 过滤:拦截 __proto__/constructor/prototype,防止恶意覆写污染对象原型链
*/
const FORBIDDEN_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
/**
* 把单层 map 的 keys 过滤掉危险段(白名单:值必须是 string,null/undefined/其它跳过)
* - 输入: 远端扁平 map { 'main_color': '#FF4646', '...': null, ... }
* - 输出: 净化后的 map(只保留 string 值,空串也是合法覆写)
*/
export function sanitizeFlatMap(flatMap) {
const out = {};
if (!flatMap || typeof flatMap !== 'object') return out;
for (const key in flatMap) {
if (!Object.prototype.hasOwnProperty.call(flatMap, key)) continue;
// 危险 key 过滤
if (FORBIDDEN_KEYS.has(String(key))) continue;
const val = flatMap[key];
if (typeof val !== 'string') continue;
out[key] = val;
}
return out;
}
/**
* 合并多桶 map
* @param {...object} maps 从低优先级到高优先级依次传入
* 例: mergeThemeBuckets(presetBase, brand, dark) = preset 被 brand 覆盖,brand 被 dark 覆盖
* @returns {object}
*/
export function mergeThemeBuckets(...maps) {
const out = {};
for (const m of maps) {
if (!m || typeof m !== 'object') continue;
for (const k in m) {
if (!Object.prototype.hasOwnProperty.call(m, k)) continue;
if (FORBIDDEN_KEYS.has(String(k))) continue;
const v = m[k];
if (typeof v !== 'string') continue;
out[k] = v;
}
}
return out;
}
/**
* 一站式合并:本地预设(已选中的 theme 子集) + brand 桶 + userMode 桶
* @param {object} preset 本地 style_color.js 中选中的 theme(如 'default' 的所有 token)
* @param {object} brandOverrides brand 桶(任何模式都生效)
* @param {object} userModeOverrides userMode 桶(light/dark,叠加在 brand 之上)
* @returns {object} { tokens, sources }
* tokens: 最终扁平 map
* sources: 每个 key 的来源(用于调试/可视化) 'preset' | 'brand' | 'userMode'
*/
export function composeFinalTokens(preset, brandOverrides, userModeOverrides) {
const tokens = {};
const sources = {};
const presetMap = sanitizeFlatMap(preset);
const brandMap = sanitizeFlatMap(brandOverrides);
const modeMap = sanitizeFlatMap(userModeOverrides);
for (const k in presetMap) { tokens[k] = presetMap[k]; sources[k] = 'preset'; }
for (const k in brandMap) { tokens[k] = brandMap[k]; sources[k] = 'brand'; }
for (const k in modeMap) { tokens[k] = modeMap[k]; sources[k] = 'userMode'; }
return { tokens, sources };
}
export default {
sanitizeFlatMap,
mergeThemeBuckets,
composeFinalTokens,
};

View File

@@ -0,0 +1,291 @@
/**
* 全局兜底分享 mixin
*
* 仅在微信小程序编译产物中被加载:
* main.js 中的 import + Vue.mixin 调用被 MP-WEIXIN 预处理宏 包住,
* 其它平台编译时整个模块不会进入产物,因此文件内部无需再写条件编译。
*
* 背景:
* - 微信小程序要求每个要支持「转发 / 朋友圈」的页面显式声明 onShareAppMessage / onShareTimeline,
* 否则页面右上角"三个点"菜单不会显示"转发"按钮。
* - 本项目之前只有 ~17 个页面声明了分享钩子,剩余页面无法转发。
* - 业务对"全页面都支持转发 + 复制小程序路径"有强诉求。
*
* 设计原则:
* 1. 不侵入现有页面:所有页面通过 Vue.mixin 自动获得默认行为
* 2. 已有 onShareAppMessage / onShareTimeline 的页面优先级更高(uni-app 会优先用页面自身的钩子)
* 3. 默认分享内容由后端 /weapp/api/weapp/share 按当前路由下发,
* 拉取失败时退化到站点名 + 当前路径,避免完全无法分享
* 4. 暴露 $mpShare 工具方法(currentPath / copyPath / refresh),
* 方便子页面在 onShareAppMessage 中复用 path
*/
// #ifdef MP-WEIXIN
const _safeGetCurrentPage = () => {
try {
const pages = typeof getCurrentPages === 'function' ? getCurrentPages() : [];
return pages.length > 0 ? pages[pages.length - 1] : null;
} catch (e) {
return null;
}
};
/**
* 关闭分享能力的页面 route 列表(不带前导斜杠,与 mp-weixin page.route 保持一致)
*
* 为什么需要:
* mp-share-default.js 通过 Vue.mixin 全局注入 onShareAppMessage / onShareTimeline,
* 但有些页面不适合"分享":
* 1) webview 容器页: 转发它等于转发一个 iframe 壳,无意义且会暴露内部 src
* 2) 隐私弹窗 / 登录中转页: 状态不稳定,转出去体验差
* 3) 任何业务明确要求"不分享"的页面
*
* 命中后行为:
* - mixin 内部不再拉取分享配置(节省一次 HTTP 请求)
* - mixin 注入的 onShareAppMessage / onShareTimeline / $mpShare_* 工具方法仍然存在,
* 但内部立即调用 wx.hideShareMenu() 把转发按钮从右上角菜单中隐藏
* - 这两条防线双保险:即使 mixin 钩子被业务侧转发链路误触发,也不会显示分享弹窗
*
* 备选方案对比(都没选,原因列在下方):
* - 在 created 里 this.onShareAppMessage = undefined:
* Vue mixin 合并策略会把 undefined 视为"未声明",mixin 的钩子仍然生效 → 不可靠
* - mixin 内 return null / 不 return:
* 微信会回退到默认 title 转发,按钮仍显示 → 不可靠
* - 使用 wx.hideShareMenu(本方案采用):
* 微信官方 API,会立即把"转发"按钮从当前页右上角菜单中隐藏,行为最稳
*/
const _DISABLED_PAGES = new Set([
'pages_tool/webview/webview', // webview 容器,转发无意义
]);
const _isCurrentPageDisabled = () => {
const page = _safeGetCurrentPage();
if (!page) return false;
const route = (page.route || (page.$page && page.$page.path) || '').replace(/^\//, '');
return _DISABLED_PAGES.has(route);
};
/**
* 主动隐藏当前页的"转发"按钮
* - 只能在 mp-weixin 环境调用(其它平台 wx 全局不存在)
* - 必须在 onLoad 之后调用(需要 Page 实例已注册完成)
* - 失败时静默吞掉(权限/版本/非微信环境都可能导致失败)
*/
const _hideShareMenu = () => {
try {
// #ifdef MP-WEIXIN
if (typeof wx !== 'undefined' && typeof wx.hideShareMenu === 'function') {
wx.hideShareMenu({
menus: ['shareAppMessage', 'shareTimeline']
});
}
// #endif
} catch (e) {
// 静默:旧基础库可能不支持 menus 参数,降级到无参版本
try {
// #ifdef MP-WEIXIN
if (typeof wx !== 'undefined' && typeof wx.hideShareMenu === 'function') {
wx.hideShareMenu();
}
// #endif
} catch (e2) { /* ignore */ }
}
};
const _getCurrentPath = (withQuery = true) => {
const page = _safeGetCurrentPage();
if (!page) return '';
// page.route 在 mp-weixin 上不带前导斜杠、不带 query;page.options 携带 query
const route = page.route || (page.$page && page.$page.path) || '';
const options = page.options || {};
if (!withQuery) return route ? '/' + route.replace(/^\//, '') : '';
const query = Object.keys(options)
.filter(k => options[k] !== undefined && options[k] !== null && options[k] !== '')
.map(k => `${encodeURIComponent(k)}=${encodeURIComponent(options[k])}`)
.join('&');
return query ? `/${route}?${query}` : `/${route}`;
};
// 模块级缓存:避免重复请求后端
let _shareCache = null;
let _shareCacheAt = 0;
const SHARE_CACHE_TTL = 60 * 1000; // 60s
const _fetchShareFromServer = (path) => {
const Http = require('./http.js').default || require('./http.js');
return new Promise((resolve) => {
Http.sendRequest({
url: '/weapp/api/weapp/share',
data: { path },
success: (res) => {
if (res && res.code >= 0 && res.data && res.data.data) {
resolve(res.data.data);
} else {
resolve(null);
}
},
fail: () => resolve(null)
});
});
};
const _buildFallback = (path) => ({
title: '小程序分享',
path,
imageUrl: ''
});
const _getShareConfig = async (path) => {
const now = Date.now();
if (_shareCache && (now - _shareCacheAt) < SHARE_CACHE_TTL) {
return _shareCache;
}
const cfg = await _fetchShareFromServer(path);
_shareCache = cfg || _buildFallback(path);
_shareCacheAt = now;
return _shareCache;
};
export default {
data() {
return {
__mpShareCache: null, // 当前页面的分享配置
};
},
/**
* 在实例创建阶段检查当前页面是否在 _DISABLED_PAGES 列表中。
* 命中后调用 wx.hideShareMenu 把当前页的"转发"按钮从右上角菜单中隐藏。
*/
created() {
try {
if (_isCurrentPageDisabled()) {
// 立即隐藏(此时 wx 还没完全就绪,先尝试一次;失败也无所谓,onLoad 会再调一次)
_hideShareMenu();
}
} catch (e) {}
},
onLoad() {
try {
if (_isCurrentPageDisabled()) {
// 命中关闭列表的页面:
// 1) 再次调 wx.hideShareMenu(此时 Page 已就绪,稳定生效)
// 2) 不再拉取分享配置,避免无谓请求
_hideShareMenu();
return;
}
const path = _getCurrentPath(true);
_getShareConfig(path).then(cfg => {
// 后端未返回配置时,注入站点名作为默认标题
if (cfg && !cfg.title) {
const siteName = (this.$store && this.$store.state && this.$store.state.siteInfo && this.$store.state.siteInfo.site_name) || '';
cfg.title = siteName || '小程序分享';
}
this.__mpShareCache = cfg;
});
} catch (e) {}
},
onShow() {
// 兜底:进入页面后如果尚未就绪,再异步拉一次
if (this.__mpShareCache) return;
if (_isCurrentPageDisabled()) return; // 命中关闭列表,不再拉
try {
const path = _getCurrentPath(true);
_getShareConfig(path).then(cfg => {
this.__mpShareCache = cfg;
});
} catch (e) {}
},
/**
* 全局默认 onShareAppMessage:
* uni-app 规范:组件自身的钩子优先级 > mixin,因此已显式声明的页面不受影响。
*/
onShareAppMessage() {
// 命中禁用列表的页面:即使 wx.hideShareMenu 因某些原因没生效,
// 这里直接 return undefined / 也不主动拼 cfg,让微信回退到默认行为
// (主防线是 wx.hideShareMenu,这里只是兜底)
if (_isCurrentPageDisabled()) {
return undefined;
}
const cfg = this.__mpShareCache;
if (cfg && cfg.title) {
return {
title: cfg.title,
path: cfg.path,
imageUrl: cfg.imageUrl || ''
};
}
// 后端无配置时:使用站点名 + 当前路径
return {
title: _buildFallback(_getCurrentPath(true)).title,
path: _getCurrentPath(true)
};
},
/**
* 全局默认 onShareTimeline(朋友圈):
* 朋友圈只支持 query(不能直接传 path),从 cfg.path 中抽取 ? 之后的 query。
*/
onShareTimeline() {
if (_isCurrentPageDisabled()) {
return undefined;
}
const cfg = this.__mpShareCache;
if (cfg && cfg.title) {
const path = cfg.path || _getCurrentPath(true);
const query = path.indexOf('?') > 0 ? path.split('?')[1] : path;
return {
title: cfg.title,
query,
imageUrl: cfg.imageUrl || ''
};
}
const path = _getCurrentPath(true);
const query = path.indexOf('?') > 0 ? path.split('?')[1] : '';
return {
title: _buildFallback(path).title,
query
};
},
methods: {
/**
* 获取当前小程序页面路径(含 query)
*/
$mpShare_currentPath() {
return _getCurrentPath(true);
},
/**
* 刷新当前页分享配置(用于页面参数变更后想重置转发 path 的场景)
*/
$mpShare_refresh() {
_shareCache = null;
_shareCacheAt = 0;
return _getShareConfig(_getCurrentPath(true)).then(cfg => {
this.__mpShareCache = cfg;
return cfg;
});
},
/**
* 复制当前页面小程序路径到剪贴板
* 微信小程序没有"页面 URL"概念,仅可复制形如:
* pages/goods/detail?id=123&source_member=xx
* 的小程序内部路径,便于分享者在聊天里粘贴。
* 优先复用 util.copyCurrentPath。
*/
$mpShare_copyPath() {
const path = _getCurrentPath(true);
const text = path.replace(/^\//, ''); // 去掉前导斜杠
if (this.$util && typeof this.$util.copyCurrentPath === 'function') {
return this.$util.copyCurrentPath({});
}
// util.copyCurrentPath 不存在(极端情况:util 模块未加载)时直接调 uni API
return new Promise((resolve, reject) => {
uni.setClipboardData({
data: text,
success: () => resolve(text),
fail: (err) => reject(err)
});
});
}
}
};
// #endif

View File

@@ -1,5 +1,6 @@
import { EventSafety } from '@/common/js/event-safety.js'
import util from '@/common/js/util.js'
import Lang from '@/common/js/lang.js'
export class NavigationHelper {
constructor() {
@@ -43,7 +44,6 @@ export class NavigationHelper {
query.select('.uni-page-head').boundingClientRect((rect) => {
if (rect && rect.height > 0) {
console.log('直接查询导航栏高度成功:', rect.height)
resolve(rect.height)
} else {
console.warn('未找到 uni-page-head 元素或高度为0')
@@ -64,7 +64,6 @@ export class NavigationHelper {
const height = menuButtonInfo.bottom +
(menuButtonInfo.top - systemInfo.statusBarHeight)
console.log('微信小程序导航栏高度:', height)
resolve(height)
} catch (error) {
console.error('微信小程序高度计算失败:', error)
@@ -174,7 +173,6 @@ export class NavigationHelper {
// 处理服务请求
async handleServiceRequest(event, component) {
console.log('处理导航相关服务请求:', event.type)
// 安全检查事件目标
if (this.shouldProcessNavigationRequest(event)) {
@@ -263,7 +261,7 @@ export class NavigationHelper {
}
// 显示用户友好的错误信息
this.showError('导航服务暂时不可用')
this.showError(Lang.lang('common.navigation.serviceUnavailable'))
}
// 显示错误提示
@@ -278,7 +276,6 @@ export class NavigationHelper {
// 清理缓存
clearCache() {
this.navigationCache.clear()
console.log('导航缓存已清理')
}
}

229
common/js/platform.js Normal file
View File

@@ -0,0 +1,229 @@
/**
* 统一平台检测模块
* 消除分散在 http.js, util.js, event-bus.js, customer-service.js 中的重复平台检测代码
*/
let cachedPlatform = null;
let cachedAppType = null;
let cachedAppTypeName = null;
// 延迟加载 lang 模块,避免与 lang.js 形成循环依赖
// (lang.js 顶部 import 了 Platform,所以 platform.js 不能顶部 import lang)
function _getLang() {
try {
return require('@/common/js/lang.js').default;
} catch (e) {
return null;
}
}
function _t(key, fallback) {
const lang = _getLang();
if (lang && typeof lang.lang === 'function') {
const result = lang.lang(key);
// lang() 在找不到 key 时会返回 key 本身(开发环境)或空串(生产环境)
if (result && result !== key) {
return result;
}
}
return fallback;
}
export const Platform = {
/**
* 检测当前运行平台
* @returns {string} 平台标识
*/
detect() {
if (cachedPlatform) {
return cachedPlatform;
}
// #ifdef H5
cachedPlatform = 'h5';
// #endif
// #ifdef MP-WEIXIN
cachedPlatform = 'weapp';
// #endif
// #ifdef MP-ALIPAY
cachedPlatform = 'alipay';
// #endif
// #ifdef MP-BAIDU
cachedPlatform = 'baidu';
// #endif
// #ifdef MP-TOUTIAO
cachedPlatform = 'toutiao';
// #endif
// #ifdef MP-QQ
cachedPlatform = 'qq';
// #endif
// #ifdef MP-KUAISHOU
cachedPlatform = 'kuaishou';
// #endif
// #ifdef MP-HARMONY
cachedPlatform = 'harmony';
// #endif
// #ifdef MP-JD
cachedPlatform = 'jd';
// #endif
// #ifdef MP-360
cachedPlatform = '360';
// #endif
// #ifdef MP-XHS
cachedPlatform = 'xhs';
// #endif
// #ifdef APP-PLUS
cachedPlatform = 'app';
// #endif
// #ifdef PC
cachedPlatform = 'pc';
// #endif
if (!cachedPlatform) {
cachedPlatform = 'unknown';
}
return cachedPlatform;
},
/**
* 获取平台类型标识 (用于API请求)
* @returns {string} app_type 值
*/
getAppType() {
if (cachedAppType) {
return cachedAppType;
}
const platform = this.detect();
// #ifdef H5
if (platform === 'h5') {
cachedAppType = this.isWeiXin() ? 'wechat' : 'h5';
return cachedAppType;
}
// #endif
const platformMap = {
weapp: 'weapp',
alipay: 'aliapp',
baidu: 'baiduapp',
toutiao: 'MP-TOUTIAO',
qq: 'MP-QQ',
kuaishou: 'kuaishou',
jd: 'jd',
'360': '360',
xhs: 'xhs',
harmony: 'harmony',
app: 'app',
pc: 'pc'
};
cachedAppType = platformMap[platform] || 'unknown';
return cachedAppType;
},
/**
* 获取平台类型名称 (用于显示)
* @returns {string} app_type_name 值
*/
getAppTypeName() {
if (cachedAppTypeName) {
return cachedAppTypeName;
}
const platform = this.detect();
// #ifdef H5
if (platform === 'h5') {
cachedAppTypeName = this.isWeiXin()
? _t('common.platform.wechatOfficialAccount', '微信公众号')
: _t('common.platform.h5', 'H5');
return cachedAppTypeName;
}
// #endif
const platformNameMap = {
weapp: _t('common.platform.wechatMiniProgram', '微信小程序'),
alipay: _t('common.platform.alipayMiniProgram', '支付宝小程序'),
baidu: _t('common.platform.baiduMiniProgram', '百度小程序'),
toutiao: _t('common.platform.toutiaoMiniProgram', '头条小程序'),
qq: _t('common.platform.qqMiniProgram', 'QQ小程序'),
kuaishou: _t('common.platform.kuaishouMiniProgram', '快手小程序'),
jd: _t('common.platform.jdMiniProgram', '京东小程序'),
'360': _t('common.platform.miniProgram360', '360小程序'),
xhs: _t('common.platform.xhsMiniProgram', '小红书小程序'),
harmony: _t('common.platform.harmonyService', '鸿蒙元服务'),
app: _t('common.platform.app', 'APP'),
pc: _t('common.platform.pc', 'PC端'),
};
cachedAppTypeName = platformNameMap[platform] || _t('common.platform.unknown', '未知平台');
return cachedAppTypeName;
},
/**
* 判断是否运行在微信浏览器中 (H5环境)
* @returns {boolean}
*/
isWeiXin() {
// #ifdef H5
return navigator.userAgent.toLowerCase().includes('micromessenger');
// #endif
return false;
},
/**
* 判断是否是小程序环境
* @returns {boolean}
*/
isMiniProgram() {
const platform = this.detect();
const miniProgramPlatforms = ['weapp', 'alipay', 'baidu', 'toutiao', 'qq', 'kuaishou', 'jd', '360', 'xhs', 'harmony'];
return miniProgramPlatforms.includes(platform);
},
/**
* 判断是否是移动端 (小程序或H5或APP)
* @returns {boolean}
*/
isMobile() {
const platform = this.detect();
return platform !== 'pc' && platform !== 'unknown';
},
/**
* 获取完整的平台信息对象
* @returns {Object} 包含 platform, appType, appTypeName
*/
getPlatformInfo() {
return {
platform: this.detect(),
appType: this.getAppType(),
appTypeName: this.getAppTypeName()
};
},
/**
* 清除缓存 (用于测试或需要重新检测的场景)
*/
clearCache() {
cachedPlatform = null;
cachedAppType = null;
cachedAppTypeName = null;
}
};
export default Platform;

978
common/js/privacy.js Normal file
View File

@@ -0,0 +1,978 @@
/**
* 全局隐私协议管理器(单例)
*
* 职责:
* 1. 统一判断是否需要弹窗(storage + 平台级隐私状态)
* 2. 通过 uni.$emit('privacy:show') 通知当前页面的 privacy-popup 组件弹窗
* 3. 用户同意后写 storage,拒绝后不写(允许下次再弹)
* 4. 只弹一次:同意后永不再弹
* 5. 事件补偿:若 emit 时无监听者,保留 _pendingShow,页面 mounted 时补偿弹窗
*
* 平台差异:
* H5: 仅查 storage
* 微信小程序: wx.getPrivacySetting() 查平台级隐私状态
* 鸿蒙元服务: has.getPrivacySetting() 查平台级隐私状态
*
* 事件:
* uni.$emit('privacy:show') — 通知当前页面组件弹窗
* uni.$emit('privacy:agreed') — 用户已同意
* uni.$emit('privacy:disagreed') — 用户已拒绝
* uni.$emit('privacy:closeOthers') — 通知其他页面关闭弹窗
* uni.$emit('privacy:rules-updated') — URL/路由规则被应用/融合后触发 (远程下发后热更新)
*
* 使用:
* App.vue onLaunch (boot完成后): await PrivacyManager.show()
* privacy-popup.vue: mounted 中 uni.$on('privacy:show') + popPendingShow() 补偿
* privacy-popup.vue: handleAgree 中 PrivacyManager.agree()
* privacy-popup.vue: handleDisagree 中 PrivacyManager.disagree()
*/
const STORAGE_KEY = 'privacyAgreed';
// 内部状态
let _needShow = false; // 是否需要弹窗
let _hasChecked = false; // 是否已执行过 check
let _pendingShow = false; // emit 时无监听者的补偿标志
// URL/路由规则已经做过决策 (避免鸿蒙兜底在白名单模式下错误弹窗)
let _urlRuleDecided = false;
// ============================================================
// 弹窗"实际显示"状态 (由 privacy-popup 通过 privacy:popup-state 事件同步)
// 关键: _pendingShow 会被 consumePendingShow 清零, 不能代表"实际显示"
// 双阶段弹窗重评估要用这个真实状态判断
let _popupActuallyShowing = false
// ============================================================
/**
* 同步读取 storage + 平台决策 (H5 + 不依赖 storage 的情况)
* 用于"已同意过"的快速路径, 不走 async checkPrivacy
* @returns {{needAuthorization: boolean, fromCache: boolean}}
*/
function checkPrivacySync() {
// H5 + 其他非微信/快应用/鸿蒙平台: storage 决定一切
const storageAgreed = getStorageAgreed()
return {
needAuthorization: !storageAgreed,
fromCache: storageAgreed,
}
}
// URL/路由级别隐私弹窗规则
// mode:
// 'all' - 始终走弹窗检查(默认, 向后兼容)
// 'only' - 白名单: 只有命中 patterns 的页面才走弹窗检查, 其他场景一律跳过
// 'skip' - 黑名单: 命中 patterns 的页面跳过弹窗, 其他场景走弹窗检查
// 匹配方式: 子串匹配
// H5: pathname + search + hash
// 小程序/鸿蒙: 当前页面 route + query
// patterns 为空数组时:
// 'all' → 无规则, 走弹窗检查
// 'only' → 视为"没有需要弹窗的页面", 一律跳过
// 'skip' → 视为"没有需要跳过的页面", 全部走弹窗检查
// ============================================================
const PRIVACY_URL_RULES = {
mode: 'all',
patterns: [],
}
/**
* 读取 storage 中的同意状态
*/
function getStorageAgreed() {
try {
return !!uni.getStorageSync(STORAGE_KEY);
} catch (e) {
return false;
}
}
/**
* 微信小程序: 查询平台级隐私设置
* @returns {Promise<{needAuthorization: boolean, privacyContractName?: string}>}
*/
function getWxPrivacySetting() {
return new Promise((resolve) => {
// #ifdef MP-WEIXIN
try {
if (wx.getPrivacySetting) {
wx.getPrivacySetting({
success: (res) => {
resolve({
needAuthorization: !!res.needAuthorization,
privacyContractName: res.privacyContractName || ''
});
},
fail: () => resolve({ needAuthorization: !getStorageAgreed() })
});
} else {
// 低版本基础库,回退到 storage
resolve({ needAuthorization: !getStorageAgreed() });
}
} catch (e) {
resolve({ needAuthorization: !getStorageAgreed() });
}
// #endif
// #ifndef MP-WEIXIN
resolve({ needAuthorization: !getStorageAgreed() });
// #endif
});
}
/**
* 快应用: 查询平台级隐私设置
* @returns {Promise<{needAuthorization: boolean, privacyContractName?: string}>}
*/
function getQuickAppPrivacySetting() {
return new Promise((resolve) => {
// #ifdef QUICKAPP-WEBVIEW
try {
const has = require('@system.has');
if (has && has.getPrivacySetting) {
has.getPrivacySetting({
success: (res) => {
resolve({
needAuthorization: !!res.needAuthorization,
privacyContractName: res.privacyContractName || ''
});
},
fail: () => resolve({ needAuthorization: !getStorageAgreed() })
});
return;
}
} catch (e) {}
// #endif
// 非快应用环境: 仅查 storage
resolve({ needAuthorization: !getStorageAgreed() });
});
}
/**
* 鸿蒙元服务: 查询平台级隐私设置
* 鸿蒙元服务的隐私授权由系统自动管理,应用层只需检查 storage
* @returns {Promise<{needAuthorization: boolean, privacyContractName?: string}>}
*/
function getHarmonyPrivacySetting() {
return new Promise((resolve) => {
// #ifdef MP-HARMONY
// 鸿蒙元服务: 隐私授权由系统管理,应用层仅检查 storage
// 系统会在用户首次使用隐私API时自动弹出系统级隐私授权弹窗
resolve({ needAuthorization: !getStorageAgreed() });
// #endif
// #ifndef MP-HARMONY
resolve({ needAuthorization: !getStorageAgreed() });
// #endif
});
}
/**
* 综合查询: 平台级隐私状态 + storage 状态
* 任一判断为"需要授权"则弹窗
* @returns {Promise<{needAuthorization: boolean, privacyContractName?: string}>}
*/
async function checkPrivacy() {
// 微信小程序: 调 wx.getPrivacySetting
// 注意: uniapp 不支持 #ifndef 多 || 与嵌套 #ifndef,
// 改用回退策略 - 仅微信走异步 API, 其他平台走 sync checkPrivacySync()
// 调用方 (show) 已经对 storage 已同意做了 sync 短路 (参见 checkPrivacySync()),
// 这里只处理 storage 未同意情况下的 async API 调用。
// #ifdef MP-WEIXIN
if (typeof wx !== 'undefined' && wx.getPrivacySetting) {
return await getWxPrivacySetting();
}
// #endif
// 快应用: 调 has.getPrivacySetting
// #ifdef QUICKAPP-WEBVIEW
if (typeof has !== 'undefined' && has.getPrivacySetting) {
return await getQuickAppPrivacySetting();
}
// #endif
// 鸿蒙元服务: 隐私由系统管理,仅查 storage
// H5 / 其他平台: 仅查 storage
return checkPrivacySync();
}
/**
* 取当前页面的"路径字符串"
* H5: location.pathname + search + hash
* 微信小程序: 当前页面 route + query (例: pages/index/index?id=1)
* 鸿蒙元服务: 当前页面 route + query (同小程序)
* @param {Object} [fallback] - 兜底路径, 用于 onLaunch 等还没 getCurrentPages 的时机
* H5: { pathname, search, hash }
* 小程序/鸿蒙: { route, query }
* @returns {string}
*/
function getCurrentPathString(fallback) {
// H5
// #ifdef H5
// H5 模式下优先用 getCurrentPages() 拿 uniapp route (history/hash 都适配)
// 兜底: window.location.pathname + search + hash
try {
if (typeof getCurrentPages === 'function') {
const pages = getCurrentPages()
const cur = pages[pages.length - 1]
if (cur && cur.route) {
const route = cur.route
const query = cur.options
let queryStr = ''
if (query && typeof query === 'object' && Object.keys(query).length) {
queryStr = '?' + Object.keys(query)
.filter(k => query[k] !== undefined && query[k] !== null && query[k] !== '')
.map(k => k + '=' + encodeURIComponent(query[k]))
.join('&')
}
return '/' + String(route).replace(/^\/+/, '') + queryStr
}
}
} catch (e) { /* ignore, fall through to location */ }
// 兜底: window.location (含 history 路由 + base)
if (typeof window !== 'undefined' && window.location) {
const pathname = (fallback && fallback.pathname) || window.location.pathname || ''
const search = (fallback && fallback.search !== undefined ? fallback.search : window.location.search) || ''
const hash = (fallback && fallback.hash !== undefined ? fallback.hash : window.location.hash) || ''
return pathname + search + hash
}
return ''
// #endif
// 微信小程序 / 鸿蒙元服务 / 其他支持 getCurrentPages 的端
// #ifndef H5
try {
const pages = (typeof getCurrentPages === 'function') ? getCurrentPages() : []
let route = ''
let query = null
const cur = pages[pages.length - 1]
if (cur) {
route = cur.route || ''
query = cur.options
}
// 兜底: onLaunch 时 getCurrentPages 还没页面, 用 fallback
if (!route && fallback) {
route = fallback.route || ''
query = fallback.query
}
if (!route) return ''
let queryStr = ''
if (query && typeof query === 'object' && Object.keys(query).length) {
queryStr = '?' + Object.keys(query)
.filter(k => query[k] !== undefined && query[k] !== null && query[k] !== '')
.map(k => k + '=' + encodeURIComponent(query[k]))
.join('&')
}
return '/' + String(route).replace(/^\/+/, '') + queryStr
} catch (e) {
return ''
}
// #endif
}
/**
* 判断 path 是否命中 patterns 之一
* 匹配规则 (双通道, 任一命中即算命中):
* 1. 子串匹配: path.indexOf(p) !== -1 (兼容 /pages/index/index 这种完整路径)
* 2. 结尾匹配: path 以 p 结尾 (兼容 subPackage 路径 /pages_tool/member/index 命中 "member/index")
* 这样业务侧既可以写完整路径也可以写相对路径
*/
function matchAny(path, patterns) {
if (!path || !Array.isArray(patterns)) return false
return patterns.some((p) => {
if (!p || typeof p !== 'string') return false
return path.indexOf(p) !== -1 || path.endsWith(p)
})
}
/**
* 根据 PRIVACY_URL_RULES 判断当前 URL/路由是否要走弹窗检查
* @param {Object} [fallback] - 传给 getCurrentPathString 的兜底路径
* @returns {boolean} true=本次应走弹窗检查, false=本次跳过
*/
function shouldShowByUrlRule(fallback) {
const mode = PRIVACY_URL_RULES.mode || 'all'
const patterns = PRIVACY_URL_RULES.patterns || []
if (!Array.isArray(patterns) || !patterns.length) {
// 空 patterns 时:
// 'all' → 无规则, 走检查
// 'only' → 没有需要弹窗的页面, 一律跳过
// 'skip' → 没有需要跳过的页面, 全部走检查
return mode === 'all' || mode === 'skip'
}
const path = getCurrentPathString(fallback)
const hit = matchAny(path, patterns)
if (mode === 'only') return hit
if (mode === 'skip') return !hit
return true // mode === 'all'
}
/**
* 覆盖 URL/路由级别隐私弹窗规则
* @param {Object} rules
* @param {'all'|'only'|'skip'} [rules.mode='all']
* @param {string[]} [rules.patterns=[]]
*/
function setUrlRules(rules) {
if (!rules || typeof rules !== 'object') return
if (rules.mode && ['all', 'only', 'skip'].indexOf(rules.mode) !== -1) {
PRIVACY_URL_RULES.mode = rules.mode
}
if (Array.isArray(rules.patterns)) {
PRIVACY_URL_RULES.patterns = rules.patterns.slice()
}
}
/**
* 持久化键 (与 privacyAgreed 同维度, 方便 uniacid 隔离)
* 由 App.vue 在 setUrlRules 前注入前缀: privacy_url_rules_<uniacid>
*/
let _storageKey = 'privacy_url_rules'
/**
* 从 storage 读取上次持久化的最终规则
* 自动过滤 __merge/__source/__ts 元信息, 仅返回纯规则
* @returns {Object|null}
*/
function loadPersistedRules() {
try {
const raw = uni.getStorageSync(_storageKey)
if (!raw) return null
const obj = (typeof raw === 'string') ? JSON.parse(raw) : raw
if (!obj || typeof obj !== 'object') return null
// 过滤元信息
return {
mode: obj.mode,
patterns: Array.isArray(obj.patterns) ? obj.patterns.slice() : [],
}
} catch (e) {
return null
}
}
/**
* 持久化当前最终规则
* 携带 merge 字段 + 时间戳 + 签名, 方便后续热修复/审计/防篡改
* @param {Object} rules
* @param {Object} [meta] - { merge?: string, source?: string, sign?: string }
*/
function persistRules(rules, meta) {
try {
const final = Object.assign({}, rules || PRIVACY_URL_RULES, {
__merge: (meta && meta.merge) || (rules && rules.__merge) || 'replace',
__source: (meta && meta.source) || 'base',
__ts: Date.now(),
__sign: (meta && meta.sign) || (rules && rules.__sign) || '',
})
uni.setStorageSync(_storageKey, final)
} catch (e) {}
}
/**
* 计算远程 patch 的签名 (前端简易实现, 与后端 hash_hmac 对齐)
* 后端约定: hash_hmac('sha256', JSON.stringify(patch), secret)
* 前端: 用 btoa 或 uni.arrayBufferToBase64 模拟 (弱校验, 防简单篡改)
* 真正的强校验建议用 crypto-js (引入成本)
* @param {Object} patch - 远程下发对象
* @param {string} secret
* @returns {string}
*/
function computeSign(patch, secret) {
if (!secret || !patch) return ''
try {
const payload = JSON.stringify(patch)
let _b64 = ''
if (typeof btoa === 'function') {
_b64 = btoa(payload)
} else if (typeof uni !== 'undefined' && typeof uni.arrayBufferToBase64 === 'function') {
const _encoder = (typeof TextEncoder !== 'undefined') ? new TextEncoder() : null
if (_encoder) {
_b64 = uni.arrayBufferToBase64(_encoder.encode(payload).buffer)
}
}
if (!_b64) return ''
// 取前 32 位作为 signature (与 lang-loader.js validateSign 保持一致)
return _b64.replace(/[^a-zA-Z0-9]/g, '').slice(0, 32)
} catch (e) {
return ''
}
}
/**
* 校验远程 patch
* - signSecret 未配置 → 通过 (向后兼容)
* - patch.sign 缺失 → 通过 (后端未启用签名)
* - patch.sign 不匹配 → 拒绝 (返回 false)
* @param {Object} patch - 远程下发 { mode, patterns, merge, sign? }
* @returns {boolean}
*/
function verifyRemotePatch(patch) {
if (!patch || typeof patch !== 'object') return false
// 业务侧未配置密钥 → 跳过校验
if (!_signSecret) return true
// patch 未带 sign 字段 → 后端未启用签名, 跳过校验 (兼容旧版本后端)
if (!patch.sign) return true
const expected = computeSign(patch, _signSecret)
const ok = (expected && expected === patch.sign)
if (!ok) {
console.warn('[privacy] remote patch sign invalid', {
expected: expected.slice(0, 8),
received: String(patch.sign).slice(0, 8),
})
}
return ok
}
/**
* 合并本地 base 与远程 patch
* mode:
* patch.mode 缺失/非合法值 → 用 base.mode
* patch.mode 合法 → 用 patch.mode (远程覆盖)
* patterns:
* merge = 'replace' → 用 patch.patterns (远程整体替换, 默认)
* merge = 'union' → base + patch 去重合并 (子串匹配: 较长的子串已包含较短, 保留较长)
* merge = 'intersect'→ 仅保留同时出现在 base 和 patch 的项
* merge 缺失/未知 → 退化为 'replace'
* patch.patterns 缺失/非数组 → 用 base.patterns
*
* @param {Object} base - 本地声明的基础规则 { mode, patterns }
* @param {Object} patch - 远程下发的补丁 { mode?, patterns?, merge? }
* @returns {{ mode: string, patterns: string[], merge: string }}
*/
function mergeRules(base, patch) {
const baseMode = (base && base.mode) || 'all'
const basePatterns = (base && Array.isArray(base.patterns)) ? base.patterns.slice() : []
if (!patch || typeof patch !== 'object') {
return { mode: baseMode, patterns: basePatterns, merge: 'replace' }
}
// mode: 远程值合法则覆盖
let mode = baseMode
if (patch.mode && ['all', 'only', 'skip'].indexOf(patch.mode) !== -1) {
mode = patch.mode
}
// patterns + merge
const merge = (patch.merge && ['replace', 'union', 'intersect'].indexOf(patch.merge) !== -1)
? patch.merge
: 'replace'
let patterns
if (!Array.isArray(patch.patterns)) {
patterns = basePatterns
} else if (merge === 'replace') {
patterns = patch.patterns.slice()
} else if (merge === 'union') {
patterns = dedupeUnion(basePatterns, patch.patterns)
} else { // intersect
patterns = basePatterns.filter(p => patch.patterns.indexOf(p) !== -1)
}
return { mode, patterns, merge }
}
/**
* 去重合并 (子串匹配: 若 a 包含 b, b 可视为冗余)
* 简单实现: 直接 concat 后去重, 复杂度可接受 (规则通常 < 50 条)
*/
function dedupeUnion(a, b) {
const all = (a || []).concat(b || [])
const seen = new Set()
const out = []
for (const p of all) {
if (typeof p !== 'string' || !p) continue
if (seen.has(p)) continue
seen.add(p)
out.push(p)
}
return out
}
/**
* 应用"已合并规则"到 PRIVACY_URL_RULES
* 触发 'privacy:rules-updated' 事件, 业务侧可监听 (例如想热更新弹窗)
* @param {Object} rules
* @param {Object} [meta] - { source: 'base'|'remote'|'persisted', patch?: Object }
*/
function applyMergedRules(rules, meta) {
if (!rules || typeof rules !== 'object') return
const prevMode = PRIVACY_URL_RULES.mode
const prevPatterns = PRIVACY_URL_RULES.patterns.slice()
// 记录"应用前 popup 实际显示状态", 用于 reEvaluate 决策
// 关键: _pendingShow 会被 consumePendingShow 清零, 不能代表"实际显示"
// 必须用 _popupActuallyShowing (由 privacy-popup 主动同步)
const prevPopupShowing = _popupActuallyShowing
setUrlRules(rules)
persistRules(rules, {
merge: rules && rules.merge,
source: meta && meta.source,
sign: meta && meta.patch && meta.patch.sign,
})
try {
uni.$emit && uni.$emit('privacy:rules-updated', {
mode: PRIVACY_URL_RULES.mode,
patterns: PRIVACY_URL_RULES.patterns.slice(),
source: (meta && meta.source) || 'remote',
patch: meta && meta.patch,
})
} catch (e) {}
// 双阶段弹窗: 远程 patch 在 show() 之后到达时, 强制重评估
// 触发条件:
// 1. patch 来源是 'remote' (非 'base')
// 2. 规则真的变了 (mode/patterns 之一不同)
// 3. show() 已经调用过 (_hasChecked=true)
// 行为:
// - 旧规则没弹 → 新规则要弹 → emit show (popup 重弹)
// - 旧规则在弹 → 新规则不该弹 → emit dismiss (popup 关闭)
const _source = (meta && meta.source) || 'remote'
const _rulesChanged = (
prevMode !== PRIVACY_URL_RULES.mode ||
prevPatterns.length !== PRIVACY_URL_RULES.patterns.length ||
prevPatterns.some((p, i) => p !== PRIVACY_URL_RULES.patterns[i])
)
if (_source === 'remote' && _rulesChanged && _hasChecked) {
// dev-only 日志, 受 __PRIVACY_DEBUG__ 开关控制 (默认开, 生产可通过 DefinePlugin 关)
if (typeof console !== 'undefined' && console.log && globalThis.__PRIVACY_DEBUG__) {
console.log('[privacy] reEvaluate trigger: prevMode=' + prevMode + ' newMode=' + PRIVACY_URL_RULES.mode + ' prevPopupShowing=' + prevPopupShowing)
}
// 异步执行, 不阻塞 apply 流程
setTimeout(() => { reEvaluateAfterRulesUpdated(prevPopupShowing) }, 0)
}
}
/**
* 规则更新后的重评估
* 场景: 远程 patch 在 show() 之后到达, 本次启动弹窗决策是基于旧规则做的
* 现在新规则来了, 必须重评估
* 步骤:
* 1. 用 prevPopupShowing (popup 实际显示状态) + shouldShowByUrlRule (应用后规则 + 当前 URL) 算差量
* 2. prevPopupShowing=false, shouldShow=true → emit show (popup 重弹)
* 3. prevPopupShowing=true, shouldShow=false → emit dismiss (popup 关闭)
* 4. 其他情况: 状态不变, 不 emit (避免无谓的弹窗抖动)
* 边界: 用户已同意过 storage → 不再弹, 但要通知 popup 关闭 (新规则可能把当前页排除)
* @param {boolean} prevPopupShowing - 应用规则前的 popup 实际显示状态
*/
function reEvaluateAfterRulesUpdated(prevPopupShowing) {
// dev-only 日志
if (typeof console !== 'undefined' && console.log && globalThis.__PRIVACY_DEBUG__) {
console.log('[privacy] reEvaluate called prevPopup=' + prevPopupShowing + ' storageAgreed=' + getStorageAgreed())
}
if (getStorageAgreed()) {
// 已同意过 → 不再弹, 但要通知 popup 关闭 (新规则可能把当前页排除)
try { uni.$emit && uni.$emit('privacy:re-evaluate', { action: 'noop', reason: 'already-agreed' }) } catch (e) {}
return
}
// 用户未同意 → 走规则决策
const shouldShow = shouldShowByUrlRule()
const wasShowing = !!prevPopupShowing
if (!wasShowing && shouldShow) {
// 旧规则没弹, 新规则要弹 → 重新设置 _pendingShow + emit show
_needShow = true
_pendingShow = true
_hasChecked = true
_urlRuleDecided = false
try { uni.$emit && uni.$emit('privacy:re-evaluate', { action: 'show', reason: 'rules-updated' }) } catch (e) {}
} else if (wasShowing && !shouldShow) {
// 旧规则在弹, 新规则不该弹 → 撤销 _pendingShow + emit dismiss
_needShow = false
_pendingShow = false
_hasChecked = true
_urlRuleDecided = true
try { uni.$emit && uni.$emit('privacy:re-evaluate', { action: 'dismiss', reason: 'rules-updated' }) } catch (e) {}
}
// 其他情况: 状态不变, 不 emit
}
/**
* 一站式: 应用本地 base → 若有远程 patch 则融合 → 持久化 → 触发事件
* 无远程 patch 时, base 直接生效 (向后兼容)
* @param {Object} base - 本地基础规则
* @param {Object} [patch] - 远程下发的 patch (可空)
* @returns {{ mode: string, patterns: string[], merge: string }}
*/
function applyWithMerge(base, patch) {
// 签名校验: 远程 patch 不合法 → 静默拒绝, 退回 base
// (业务侧可通过 PrivacyManager.verifyRemotePatch() 单独调用)
if (patch && !verifyRemotePatch(patch)) {
console.warn('[privacy] applyWithMerge: remote patch sign invalid, fallback to base')
const merged = mergeRules(base, null)
applyMergedRules(merged, { source: 'base', patch: null })
return merged
}
const merged = mergeRules(base, patch)
applyMergedRules(merged, { source: patch ? 'remote' : 'base', patch })
return merged
}
// 本地 base 规则 (由 App.vue 通过 setBaseRules 登记)
// 供 store/index.js 的 init action 在收到远程 patch 时读取
let _baseRules = { mode: 'all', patterns: [] }
// 外部注入的 readyWaiters (由 config-external.js ConfigExternal 持有)
// 兼容老用法: 业务侧可直接传 readyGuard, 也可走 ConfigExternal.setReadyWaiters 通道
let _externalReadyGuard = null
let _externalBootTimeout = 6000
let _externalWaitChannels = { lang: true, theme: true, themeOverride: true, remoteConfig: true }
// 远程 patch 签名密钥 (与 langConfig.remote.signSecret 同构)
// 业务侧通过 setSignSecret(secret) 或 privacyConfig.signSecret 注入
let _signSecret = ''
// 远程 patch 签名 (在持久化时被写入 storage 的 __sign 字段, 供后续审计/防回滚)
// 注意: 当前实现不做增量校验, 只在 verifyRemotePatch 内单次校验
// 如需增量校验 (防止回滚到旧 patch), 可在此维护 _lastPersistedSign
// 每次 applyWithMerge 持久化时记录, 下次启动时与远程 patch 的 sign 字段比对
let _lastPersistedSign = ''
// ============================================================
// 监听 privacy:popup-state 事件 (由 privacy-popup.vue 主动同步弹窗显示状态)
// 用于双阶段弹窗的精确重评估 (reEvaluateAfterRulesUpdated)
// 这里挂一个全局监听, 模块加载时就生效
// ============================================================
;(function _installPopupStateListener() {
try {
if (typeof uni === 'undefined' || !uni.$on) return
uni.$on('privacy:popup-state', (info) => {
if (info && typeof info.showing === 'boolean') {
_popupActuallyShowing = info.showing
}
})
} catch (e) {}
})()
const PrivacyManager = {
/**
* 同步检查 storage 中的同意状态(快速判断,不查平台)
* @returns {boolean} true=需要弹窗, false=不需要
*/
check() {
_needShow = !getStorageAgreed();
_hasChecked = true;
return _needShow;
},
/**
* 同步标记本次跳过弹窗(不查 storage、不写 storage、不弹窗)
* 必须在 page mounted 之前调用,避免 onLaunch await 让出事件循环后
* privacy-popup.vue 的 consumePendingShow 走兜底分支把弹窗弹出来
* 用于 H5 浏览器直访特定 URL(子串匹配)时不让隐私弹窗挡住
*/
markSkipped() {
_needShow = false;
_hasChecked = true;
_pendingShow = false;
_urlRuleDecided = true; // 同步决策, 鸿蒙兜底不应再弹
},
/**
* 触发弹窗(如果需要)
* 由 App.vue onLaunch 在 boot 完成后调用
* 异步查询平台隐私状态,设置 _pendingShow 标志
* 页面组件 mounted 时通过 consumePendingShow() 消费标志并弹窗
* 不直接 emit 事件,避免 emit + 补偿双触发
*
* @param {Object} [options]
* @param {boolean} [options.skip=false] true=本次跳过弹窗(不写 storage,下次正常访问其他页面还会弹)
* @param {Object} [options.urlFallback] 首次启动 onLaunch 时 getCurrentPages 还没有页面,
* 可传入 onLaunch options 兜底:
* H5: { pathname, search, hash }
* 小程序/鸿蒙: { route, query }
* @param {Promise|Function} [options.readyGuard] 外部 readiness 守卫 (例如 i18n/theme),
* show() 会 await 它再继续, 保证弹窗在外部资源就绪后才决策.
* 超时保护: 业务侧应保证 guard 自身有超时, 否则会一直 hang.
*/
async show(options = {}) {
const fallback = options && options.urlFallback ? options.urlFallback : null
// 外部 readiness 守卫: 等业务侧 promise 再继续
// 优先级: options.readyGuard (调用方显式传) > _externalReadyGuard (ConfigExternal 注入)
// 场景: App.vue onLaunch 把 i18n/theme/remote-config 的 await 链作为 guard 传入
// 这样无论 show() 在哪里调用, 都保证弹窗决策时外部资源已就绪
const _guard = (options && typeof options.readyGuard !== 'undefined')
? options.readyGuard
: _externalReadyGuard
if (typeof _guard !== 'undefined' && _guard !== null) {
try {
if (_guard && typeof _guard.then === 'function') {
await _guard
} else if (typeof _guard === 'function') {
await _guard()
}
} catch (e) {
console.warn('[privacy] readyGuard fail', e)
}
}
// 主动跳过: 不查 storage、不写 storage、不弹窗
// 用于 H5 浏览器直接访问特定 URL(子串匹配)时不让隐私弹窗挡住
if (options && options.skip) {
_needShow = false;
_hasChecked = true;
_pendingShow = false;
_urlRuleDecided = true; // 同步决策, 鸿蒙兜底不应再弹
return;
}
// URL/路由规则判断
// mode='only' 且未命中 patterns → 跳过
// mode='skip' 且命中 patterns → 跳过
// 其他情况 → 继续走 storage + 平台检查
if (!shouldShowByUrlRule(fallback)) {
_needShow = false;
_hasChecked = true;
_pendingShow = false;
_urlRuleDecided = true; // 已决策, 阻止鸿蒙兜底强制弹窗
return;
}
// URL 规则允许弹, 重置 urlRuleDecided 留给鸿蒙兜底分支判断
_urlRuleDecided = false;
const _storageAgreed = getStorageAgreed();
// 优化: storage 已同意时直接走同步快速路径, 不调 async checkPrivacy()
// 节省 1 个 microtask (~0-4ms, dev 模式更明显)
// 注意: 微信小程序/快应用/鸿蒙走 checkPrivacy (平台 API 异步)
// H5 下 checkPrivacy 内部已 sync 化 (修过), 直接 await 即可
const result = _storageAgreed ? checkPrivacySync() : await checkPrivacy();
_needShow = result.needAuthorization;
_hasChecked = true;
if (!_needShow) {
return;
}
// 设置待弹窗标志
// 已 mounted 的页面组件通过事件接收
// 未 mounted 的页面组件 mounted 时通过 consumePendingShow 补偿
_pendingShow = true;
// 通知已 mounted 的页面组件(如果有监听者)
try { uni.$emit('privacy:show'); } catch (e) {}
// 若组件已接收事件并弹窗, 会在 handlePrivacyShow 中调 consumePendingShow 清除 _pendingShow
// 若无监听者, _pendingShow 保持 true, 等页面 mounted 时补偿
},
/**
* 页面 mounted 时补偿检查: 若 show() 在页面 mounted 之前 emit 了事件
* 此方法返回 true 并清除标志,页面组件据此自动弹窗
*
* 鸿蒙元服务兼容:
* Lang.boot() 可能 hang, PrivacyManager.show() 可能从未被调用过;
* 此时 _pendingShow 仍是默认 false, 但用户从未同意过隐私, 必须强制弹一次。
* 所以增加 storage 检测: 用户未同意也返回 true (补偿弹窗)。
* @returns {boolean} true=需要弹窗,false=不需要
*/
consumePendingShow() {
if (_pendingShow && _needShow) {
_pendingShow = false;
return true;
}
// 鸿蒙兜底: PrivacyManager.show() 没跑过 + 用户没同意过 storage → 必须弹
// 同一次进程内只补一次,避免隐私弹窗被反复触发
// 关键: URL/路由规则已经决策过 "本次跳过" 时, 不应触发兜底弹窗 (白名单场景)
if (!_hasChecked && !_pendingShow && !_urlRuleDecided && !getStorageAgreed()) {
_pendingShow = false;
_needShow = true;
_hasChecked = true;
return true;
}
_pendingShow = false;
return false;
},
/**
* 用户同意:写 storage,标记不再弹
* 由 privacy-popup.vue 的 handleAgree 调用
*/
agree() {
try { uni.setStorageSync(STORAGE_KEY, true); } catch (e) {}
_needShow = false;
_pendingShow = false;
try { uni.$emit('privacy:agreed'); } catch (e) {}
},
/**
* 用户拒绝:不写 storage,允许下次再弹
* 由 privacy-popup.vue 的 handleDisagree 调用
*/
disagree() {
_needShow = false;
_pendingShow = false;
try { uni.$emit('privacy:disagreed'); } catch (e) {}
},
/**
* 当前是否需要弹窗(供页面查询)
* @returns {boolean}
*/
needShow() {
return _needShow;
},
/**
* 是否已执行过 check
* @returns {boolean}
*/
hasChecked() {
return _hasChecked;
},
/**
* 配置 URL/路由级别隐私弹窗规则
* @param {Object} rules
* @param {'all'|'only'|'skip'} [rules.mode='all']
* 'all' - 始终走弹窗检查(默认)
* 'only' - 白名单: 只有命中 patterns 才弹
* 'skip' - 黑名单: 命中 patterns 跳过
* @param {string[]} [rules.patterns=[]]
* 子串匹配, H5: pathname+search+hash, 小程序/鸿蒙: route+query
*/
setUrlRules(rules) {
setUrlRules(rules)
},
/**
* 当前 URL/路由规则下是否要走弹窗检查
* @param {Object} [fallback] 兜底路径(同 show 的 urlFallback)
* @returns {boolean}
*/
shouldShowByUrlRule(fallback) {
return shouldShowByUrlRule(fallback)
},
/**
* 应用本地 base + 远程 patch 的融合结果
* - patch=null/缺 → 仅应用 base (并持久化)
* - patch 存在 → 走 mergeRules 融合
* 应用后 emit 'privacy:rules-updated'
* @param {Object} base 本地基础规则 { mode, patterns }
* @param {Object} [patch] 远程下发 { mode?, patterns?, merge? }
* @returns {{ mode: string, patterns: string[], merge: string }}
*/
applyWithMerge(base, patch) {
return applyWithMerge(base, patch)
},
/**
* 仅合并 (不写入), 方便上层预览或 dry-run
* @param {Object} base
* @param {Object} patch
*/
mergeRules(base, patch) {
return mergeRules(base, patch)
},
/**
* 读取上次持久化的最终规则 (跨冷启动恢复)
* @returns {Object|null}
*/
loadPersistedRules() {
return loadPersistedRules()
},
/**
* 设置持久化 key (用于 uniacid 隔离), 由 App.vue 注入
* @param {string} key
*/
setStorageKey(key) {
if (typeof key === 'string' && key) _storageKey = key
},
/**
* 登记本地 base 规则 (由 App.vue 在启动时调用)
* 供后续远程下发时 mergeRules 读取
* @param {Object} rules
*/
setBaseRules(rules) {
if (!rules || typeof rules !== 'object') return
_baseRules = {
mode: rules.mode || 'all',
patterns: Array.isArray(rules.patterns) ? rules.patterns.slice() : [],
}
},
/**
* 读取本地 base 规则 (供 store/index.js init 远程 patch 融合)
* @returns {{ mode: string, patterns: string[] }}
*/
__getBaseRules() {
return { mode: _baseRules.mode, patterns: _baseRules.patterns.slice() }
},
/**
* 注入外部 readiness 守卫 (由 config-external.js ConfigExternal 调用)
* show() 时若无 options.readyGuard, 内部使用此 promise
* @param {Promise|Function|null} guard
*/
setExternalReadyGuard(guard) {
if (guard === null) { _externalReadyGuard = null; return }
if (guard && (typeof guard.then === 'function' || typeof guard === 'function')) {
_externalReadyGuard = guard
}
},
/**
* 注入外部 bootTimeout (由 ConfigExternal.getPrivacyBootTimeout 调用)
* @param {number} ms
*/
setExternalBootTimeout(ms) {
if (typeof ms === 'number' && ms > 0) _externalBootTimeout = ms
},
/**
* 注入 waitChannels 配置 (隐私弹窗启动期必等通道开关)
* @param {Object} channels
*/
setWaitChannels(channels) {
if (channels && typeof channels === 'object') {
_externalWaitChannels = Object.assign({}, _externalWaitChannels, channels)
}
},
/**
* 注入远程 patch 签名密钥 (与 langConfig.remote.signSecret 同构)
* 后端约定: hash_hmac('sha256', JSON.stringify(patch), secret)
* 前端: 用 btoa 模拟 (弱校验, 仅防简单篡改)
* secret='' → 跳过校验 (向后兼容)
* @param {string} secret
*/
setSignSecret(secret) {
_signSecret = (typeof secret === 'string') ? secret : ''
},
/**
* 校验远程 patch (业务侧可在 store/init 之外单独调用)
* - signSecret 未配置 → true (向后兼容)
* - patch.sign 缺失 → true (后端未启用签名)
* - patch.sign 不匹配 → false
* @param {Object} patch
* @returns {boolean}
*/
verifyRemotePatch(patch) {
return verifyRemotePatch(patch)
},
/**
* 计算给定 patch 的签名 (供调试/单元测试)
* @param {Object} patch
* @param {string} [secret] - 不传则用 _signSecret
* @returns {string}
*/
computeSign(patch, secret) {
return computeSign(patch, secret || _signSecret)
},
/**
* 读取当前生效配置 (供调试/单元测试)
*/
getReadyConfig() {
return {
readyGuard: _externalReadyGuard,
bootTimeout: _externalBootTimeout,
waitChannels: Object.assign({}, _externalWaitChannels),
}
},
};
export default PrivacyManager;

View File

@@ -0,0 +1,33 @@
/**
* 快应用宿主环境下的下拉刷新 → 原生 webview.reload() 转发 mixin
*
* 在已启用 enablePullDownRefresh 的 uniapp 页面 mixin 链中加入本文件,
* 当用户在原生快应用 webview 内下拉刷新时,会通过 this.$util.requestQuickAppReload()
* 把指令发回快应用 shell(对应 hello.ux onMessage 中的 'reload' 处理);
* 其余平台走默认的 uni.stopPullDownRefresh 即可。
*
* 用法:
* import pullReload from '@/common/js/mixins/quickapp-pull-refresh.js';
* export default { mixins: [..., pullReload] }
*
* 注意:
* - 请确保对应的 pages.json style 块中开启 "enablePullDownRefresh": true
* - 不要在本文件里覆盖 onPullDownRefresh,否则会被本页/上游 mixin 拦截失效
*/
export default {
onPullDownRefresh() {
try {
if (this.$util && typeof this.$util.requestQuickAppReload === 'function'
&& this.$util.requestQuickAppReload()) {
// 原生侧 webview.reload() 会把整个 H5 页面替换掉,这里只是兜底停动画
setTimeout(() => {
try { uni.stopPullDownRefresh(); } catch (_) { /* swallow */ }
}, 800);
return;
}
} catch (e) {
console.error('[quickapp-pull-refresh] crashed:', e);
}
try { uni.stopPullDownRefresh(); } catch (_) { /* swallow */ }
}
}

View File

@@ -1,4 +1,6 @@
// 文件分享工具函数
import Lang from './lang.js';
export default {
/**
* 生成文件预览链接
@@ -30,7 +32,7 @@ export default {
* @param {string} title - 分享标题,默认使用文件名
* @param {string} desc - 分享描述,默认使用固定文案
*/
shareFile(file, title = file.name, desc = '查看企业文件:' + file.name) {
shareFile(file, title = file.name, desc = Lang.lang('share.defaultDesc', { name: file.name })) {
// 生成文件预览链接
const filePreviewUrl = this.generateFilePreviewUrl(file);
@@ -44,17 +46,17 @@ export default {
url: filePreviewUrl
}).catch(err => {
console.error('分享失败:', err);
uni.showToast({ title: '分享失败', icon: 'none' });
uni.showToast({ title: Lang.lang('share.shareFailed'), icon: 'none' });
});
} else {
// 不支持 Web Share API 的浏览器
uni.setClipboardData({
data: filePreviewUrl,
success: () => {
uni.showToast({ title: '链接已复制,请粘贴分享', icon: 'success' });
uni.showToast({ title: Lang.lang('share.linkCopied'), icon: 'success' });
},
fail: () => {
uni.showToast({ title: '复制失败', icon: 'none' });
uni.showToast({ title: Lang.lang('share.copyFailed'), icon: 'none' });
}
});
}
@@ -63,7 +65,7 @@ export default {
// #ifdef MP-WEIXIN
// 微信小程序分享
uni.showActionSheet({
itemList: ['发送给朋友', '分享到朋友圈'],
itemList: [Lang.lang('share.sendToFriend'), Lang.lang('share.shareToTimeline')],
success: (res) => {
if (res.tapIndex === 0) {
// 发送给朋友
@@ -71,10 +73,10 @@ export default {
title: title,
path: filePreviewUrl,
success: () => {
uni.showToast({ title: '分享成功', icon: 'success' });
uni.showToast({ title: Lang.lang('share.shareSuccess'), icon: 'success' });
},
fail: () => {
uni.showToast({ title: '分享失败', icon: 'none' });
uni.showToast({ title: Lang.lang('share.shareFailed'), icon: 'none' });
}
});
} else if (res.tapIndex === 1) {
@@ -83,10 +85,10 @@ export default {
title: desc,
path: filePreviewUrl,
success: () => {
uni.showToast({ title: '分享成功', icon: 'success' });
uni.showToast({ title: Lang.lang('share.shareSuccess'), icon: 'success' });
},
fail: () => {
uni.showToast({ title: '分享失败', icon: 'none' });
uni.showToast({ title: Lang.lang('share.shareFailed'), icon: 'none' });
}
});
}

View File

@@ -21,53 +21,35 @@ export default {
methods: {
// 判断是否已连接
checkOpenSocket() {
console.log('判断是否已连接');
// alert('判断是否已连接')
let self = this;
uni.sendSocketMessage({
data: 'ping',
success: (res) => {
console.log('连接成功,检查');
// alert('连接成功,检查')
// self.getChatList();
},
fail: (err) => { // 未连接打开websocket连接
console.log('连接失败');
// alert('连接失败')
self.openConnection();
}
});
},
openConnection() { // 打开连接
console.log('打开连接');
// alert('打开连接')
// uni.closeSocket(); // 确保已经关闭后再重新打开
uni.connectSocket({
url: config.webSocket,
method: 'POST',
success(res) {
console.log('连接成功 connectSocket=', res);
// alert('连接成功 connectSocket=', res);
},
fail(err) {
console.log('连接失败 connectSocket=', err);
}
});
// uni.onSocketOpen((res) => {
// console.log('连接成功', res);
// });
this.onSocketMessage(); // 打开成功监听服务器返回的消息
},
// 打开成功监听服务器返回的消息
onSocketMessage() { // 消息
console.log("开始监听");
let that = this;
this.pingInterval = config.pingInterval;
this.timeoutObj = null;
uni.onSocketMessage((res) => { //type:init,connect,close,string,order,goods
let msg = JSON.parse(res.data);
console.log("监听该服务器消息", res);
if (msg.type == 'close') {
clearInterval(that.timeoutObj);
that.timeoutObj = null;
@@ -141,22 +123,18 @@ export default {
},
// 检测心跳reset
reset() {
console.log("检测心跳");
clearInterval(this.timeoutObj);
this.start(); // 启动心跳
},
// 启动心跳 start
start() {
console.log("启动心跳");
let self = this;
this.timeoutObj = setInterval(function () {
uni.sendSocketMessage({
data: 'ping',
success: (res) => {
console.log('连接中....');
},
fail: (err) => {
console.log('连接失败重新连接....');
self.openConnection();
}
});

415
common/js/splash-state.js Normal file
View File

@@ -0,0 +1,415 @@
// ============================================================
// 启动屏单例状态
//
// 设计要点:
// 1. 状态 + 事件双通道: 组件既可 watch visible,也可监听 'splash:hide' 事件
// 解决 uni.$emit 在组件挂载前发出就丢失的问题 (memory lesson)
// 2. 软隐藏 (softHide): 标记应该 hide, 等组件 mount 后再真正 hide
// 解决 onLaunch 跑完 + hide() 早于 page mount 的时序问题
// 3. 防重入: show()/hide() 多次调用安全,内部用 guard
// 4. 兜底超时: 默认 8s 未关闭则强制 hide,防止卡死
// 5. 平台隔离: APP-PLUS 有原生 splash,这里直接返回 false
// 6. 跨平台兼容: 同步状态可被 Vue 组件直接 watch
// ============================================================
// APP-PLUS 直接返回 false (有原生启动屏)
function needSplash() {
// #ifdef APP-PLUS
return false;
// #endif
// #ifndef APP-PLUS
return true;
// #endif
}
// H5 平台特殊处理: Lang.boot() 在 main.js 中 await, 此时 Vue 还没挂载,
// 组件无法渲染, 内部降级为 uni.showLoading 做兜底 (虽然样式较丑但至少有遮罩)
function useNativeLoading() {
// #ifdef H5
return true;
// #endif
// #ifndef H5
return false;
// #endif
}
const DEFAULT_TIMEOUT = 8000; // 总兜底超时
const MOUNT_GRACE_MS = 1000; // 软隐藏后等组件 mount 的宽限时间
const PAGE_READY_GRACE_MS = 2000; // 软隐藏后等页面就绪的宽限时间
// 启动期阶段定义 (id → { percent, label })
// percent: 阶段完成的百分比 (0-100)
// label: 阶段显示文案 (i18n key 由 splash 组件消费, 也可直接用最终文案)
const STAGES = {
boot: { percent: 5, label: 'Loading...' },
lang: { percent: 30, label: 'Loading language...' },
theme: { percent: 50, label: 'Applying theme...' },
override: { percent: 65, label: 'Loading theme tokens...' },
config: { percent: 80, label: 'Fetching configuration...' },
privacy: { percent: 95, label: 'Preparing privacy dialog...' },
done: { percent: 100, label: 'Ready' },
};
class SplashState {
constructor() {
this._visible = false;
this._timeoutId = null;
this._listeners = [];
this._shownAt = 0;
// 软隐藏相关
this._pendingHide = null; // 软隐藏请求的 opts, 等待组件 mount
this._hasMounted = false; // 是否有 splash 组件 mount 过
this._mountGraceId = null; // 软隐藏兜底定时器 (等 mount)
// 页面就绪等待
this._pageReady = false; // 页面内容是否已就绪 (由首页通知)
this._pageReadyGraceId = null; // 页面就绪兜底定时器
// 进度上报
this._stage = 'boot';
this._percent = 0;
this._stageSet = new Set(['boot']); // 已报告阶段
// 进度节流: 16ms 内的多次 reportProgress 合并成一次 emit
// 避免多通道并发时, splash 组件 re-render 风暴
this._pendingProgress = null; // 待 emit 的最新进度
this._flushTimer = null; // 节流定时器
}
show(opts = {}) {
if (!needSplash()) return;
if (this._visible) return; // 防重入
this._visible = true;
this._shownAt = Date.now();
this._pendingHide = null;
this._hasMounted = false;
this._pageReady = false;
this._stage = 'boot';
// 初始化时直接显示 'boot' 阶段的 5%, 而不是 0%
// 避免首帧出现"进度条 0%"的视觉突兀
this._percent = (STAGES.boot && STAGES.boot.percent) || 5;
this._stageSet = new Set(['boot']);
this._pendingProgress = null;
if (this._flushTimer) {
clearTimeout(this._flushTimer);
this._flushTimer = null;
}
if (this._mountGraceId) {
clearTimeout(this._mountGraceId);
this._mountGraceId = null;
}
if (this._pageReadyGraceId) {
clearTimeout(this._pageReadyGraceId);
this._pageReadyGraceId = null;
}
this._emit('splash:show');
// H5 降级: 走系统 loading (Vue 还没挂载,组件层无法渲染)
// 注意: mask 设为 false。原 mask:true 会在 H5 注入 .uni-mask 全屏透明蒙层,
// 配合 z-index:99999 的 Vue splash 一起把首页触摸全部拦截,导致 H5
// 首屏在 boot 期间无法滚动。Vue splash 组件本身已带白色背景提供视觉遮罩,
// 这里只要 loading 文字提示,不需要拦截触摸。
if (useNativeLoading()) {
try { uni.showLoading({ title: opts.title || '加载中...', mask: false }); } catch (e) {}
}
const timeout = opts.timeout || DEFAULT_TIMEOUT;
if (this._timeoutId) {
clearTimeout(this._timeoutId);
this._timeoutId = null;
}
this._timeoutId = setTimeout(() => {
// 兜底: 超时强制关闭,防止卡死 (走硬隐藏路径, 不等组件)
if (this._visible) {
console.warn('[splash-state] auto-hide after timeout', timeout);
this._doHide({ reason: 'timeout' });
}
}, timeout);
}
/**
* 隐藏 splash
* @param {Object} opts
* @param {string} opts.reason - 隐藏原因
* - 'boot-complete': 软隐藏, 等组件 mount 后再真关 (默认)
* - 'timeout': 硬隐藏, 立即关 (兜底用)
* - 'manual': 硬隐藏, 立即关
* @param {boolean} [opts.soft] - 强制走软隐藏
* @param {string} [opts.mode] - 离开动画模式
* - 'default': 默认 480ms 动画
* - 'fast': 80ms 短动画, 用于隐私弹窗等需要立即接管视觉的场景, 避免"双遮罩"感
*/
hide(opts = {}) {
const reason = opts.reason || 'manual';
// boot-complete 默认走软隐藏, 避免时序问题
const useSoft = opts.soft === true || (opts.soft !== false && reason === 'boot-complete');
const mode = opts.mode === 'fast' ? 'fast' : 'default';
if (useSoft) {
this._softHide({ reason, mode });
} else {
this._doHide({ reason, mode });
}
}
/**
* 软隐藏: 标记应该 hide, 等组件 mount + 页面就绪
* 如果组件 1s 内没 mount, 兜底自动 hide
* 如果页面 2s 内没就绪, 兜底自动 hide
*/
_softHide(opts) {
if (!this._visible) return; // 已经隐藏了
this._pendingHide = opts;
// 如果组件已经 mount 且页面已就绪, 立即隐藏
if (this._hasMounted && this._pageReady) {
this._flushPendingHide();
return;
}
// 兜底: 1s 内没 mount, 强制隐藏
if (this._mountGraceId) clearTimeout(this._mountGraceId);
this._mountGraceId = setTimeout(() => {
if (this._pendingHide) {
this._flushPendingHide();
}
}, MOUNT_GRACE_MS);
}
/**
* 真正触发软隐藏
* 如果页面还未就绪, 等待页面就绪后再 hide
*/
_flushPendingHide() {
if (this._mountGraceId) {
clearTimeout(this._mountGraceId);
this._mountGraceId = null;
}
// 如果页面还未就绪, 等待页面就绪 (保留 _pendingHide, 等页面就绪后再处理)
if (!this._pageReady) {
// 兜底: 2s 内没就绪, 强制隐藏
if (this._pageReadyGraceId) clearTimeout(this._pageReadyGraceId);
this._pageReadyGraceId = setTimeout(() => {
if (this._visible && this._pendingHide) {
console.warn('[splash-state] auto-hide after page-ready timeout');
this._doHide(this._pendingHide || { reason: 'page-ready-timeout' });
}
}, PAGE_READY_GRACE_MS);
return;
}
const opts = this._pendingHide;
this._pendingHide = null;
this._doHide(opts || { reason: 'mount-completed' });
}
/**
* 实际隐藏 (硬路径)
*/
_doHide(opts) {
if (!this._visible) return; // 防重入
if (this._timeoutId) {
clearTimeout(this._timeoutId);
this._timeoutId = null;
}
if (this._mountGraceId) {
clearTimeout(this._mountGraceId);
this._mountGraceId = null;
}
if (this._pageReadyGraceId) {
clearTimeout(this._pageReadyGraceId);
this._pageReadyGraceId = null;
}
this._pendingHide = null;
this._visible = false;
// H5 降级对应的关闭
if (useNativeLoading()) {
try { uni.hideLoading(); } catch (e) {}
}
this._emit('splash:hide', {
reason: opts.reason || 'manual',
mode: opts.mode || 'default',
});
}
/**
* 组件 mount 后通知 state 模块
* - 标记 _hasMounted
* - 如果有 _pendingHide, 触发真关
* - H5 降级场景: 不再立即关掉原生 loading, 等待页面就绪后再关
*/
notifyMounted() {
if (this._hasMounted) return;
this._hasMounted = true;
if (this._pendingHide) {
setTimeout(() => this._flushPendingHide(), 50);
}
}
/**
* 页面内容就绪后通知 state 模块
* - 标记 _pageReady
* - 如果有 _pendingHide, 触发真关
* 调用时机: 首页 diy-group 渲染完成后调用
*/
notifyPageReady() {
if (this._pageReady) return;
this._pageReady = true;
if (this._pageReadyGraceId) {
clearTimeout(this._pageReadyGraceId);
this._pageReadyGraceId = null;
}
if (this._pendingHide) {
// 给页面一帧时间完成渲染, 再隐藏
setTimeout(() => this._flushPendingHide(), 50);
}
}
/**
* 组件 unmount 时通知 (用于 _hasMounted 状态管理)
* 目前保留 _hasMounted=true, 因为一般只有 tab 页有 splash 组件, 不会动态增减
*/
notifyUnmounted() {
// 不重置 _hasMounted, 因为软隐藏的 _pendingHide 处理不依赖 unmount
}
isShow() {
return this._visible;
}
hasPendingHide() {
return this._pendingHide != null;
}
elapsed() {
if (!this._visible) return 0;
return Date.now() - this._shownAt;
}
on(event, fn) {
if (!this._listeners[event]) this._listeners[event] = [];
this._listeners[event].push(fn);
}
off(event, fn) {
if (!this._listeners[event]) return;
this._listeners[event] = this._listeners[event].filter(f => f !== fn);
}
_emit(event, payload) {
const arr = this._listeners[event];
if (!arr || !arr.length) return;
for (let i = 0; i < arr.length; i++) {
try { arr[i](payload); } catch (e) { console.warn('[splash-state] listener err', e); }
}
}
/**
* 上报启动期进度
* 节流: 16ms 内的多次 reportProgress 合并成 1 次 emit, 避免 splash re-render 风暴
* 取较大值, 不允许后退 (即使 throttle 合并也不会让进度条后退)
* @param {string} stageId - 阶段 id (STAGES 中定义)
* 'boot' | 'lang' | 'theme' | 'override' | 'config' | 'privacy' | 'done'
* 或自定义阶段 id (传 percent + label)
* @param {Object} [meta] - { percent?, label?, source?: 'channel'|'timeout'|'error' }
* 阶段完成时 percent 应该是该阶段的"完成态"百分比
*/
reportProgress(stageId, meta) {
const def = STAGES[stageId]
let percent, label
if (def) {
percent = (meta && typeof meta.percent === 'number') ? meta.percent : def.percent
label = (meta && meta.label) || def.label
} else {
// 自定义阶段
percent = (meta && typeof meta.percent === 'number') ? meta.percent : this._percent
label = (meta && meta.label) || stageId
}
// 取较大值, 不允许后退
if (percent < this._percent) percent = this._percent
this._percent = percent
this._stage = stageId
if (!this._stageSet.has(stageId)) this._stageSet.add(stageId)
// 节流 emit: 16ms 内的多次调用合并为 1 次
// 内部状态立即更新 (不延迟), 但 emit 推迟
// 注意: percent 不允许后退的逻辑已在上方处理, 所以 throttle 合并不会丢进度
const payload = {
stage: stageId,
label,
percent,
source: (meta && meta.source) || 'channel',
at: Date.now(),
}
this._pendingProgress = payload
if (this._flushTimer) return // 已有 pending, 等 timer flush
this._flushTimer = setTimeout(() => {
this._flushTimer = null
if (this._pendingProgress) {
const p = this._pendingProgress
this._pendingProgress = null
this._emit('splash:progress', p)
}
}, 16)
}
/**
* 监听进度上报
* callback({ stage, label, percent, source, at })
*
* 注意: 与 on() 不同, onProgress 是单例 listener (多个组件时只最后一个生效)
* 设计意图: splash 进度条 UI 在系统中只有一个渲染者, 不需要多播
*/
onProgress(callback) {
this._listeners['splash:progress'] = [callback]
}
/**
* 解绑进度上报 (清空 listener)
*/
offProgress() {
this._listeners['splash:progress'] = []
}
/**
* 读取当前进度 (供组件初始化)
* 同时返回已解析的 label, 避免组件再维护一份 STAGE_LABEL
*/
getProgress() {
const def = STAGES[this._stage]
return {
stage: this._stage,
percent: this._percent,
label: def ? def.label : this._stage,
}
}
/**
* 暴露 STAGES 表 (供 splash 组件直接消费, 避免重复维护一份)
*/
getStageDef(stageId) {
return STAGES[stageId]
}
/**
* 立即刷新挂起的进度更新
* - reportProgress 默认 16ms throttle (1 帧), 避免连续触发 splash 组件多次 re-render
* - 业务侧若要"立即"刷新 (例如 splash 即将隐藏), 可调本方法
* - 不存在 pending 时 noop
*/
flushProgress() {
if (this._pendingProgress) {
const p = this._pendingProgress
this._pendingProgress = null
if (this._flushTimer) {
clearTimeout(this._flushTimer)
this._flushTimer = null
}
this._emit('splash:progress', p)
}
}
}
const splashState = new SplashState();
export default splashState;
export { splashState };

File diff suppressed because it is too large Load Diff

476
common/js/theme-override.js Normal file
View File

@@ -0,0 +1,476 @@
/**
* 主题 token 远端覆写运行时
*
* 设计原则(与 lang.js 完全同构):
* 1) 后端只存"对要个性化的 token"做覆写 KV,前端拿本地 style_color.js + 远端覆写 合并
* 2) 三态机: unknown / ok / fail
* 3) 多租户 × 多端平台 × 多模式(brand/light/dark)三维隔离缓存
* 4) 失败归一: timeout / network / http / parse / exception
* 5) 失败时使用本地 style_color.js 兜底
* 6) 不修改 Vuex.themeStyle / themeColorSet / 页面 wrapper,只把"合并后的 token map"
* 提供给 store/index.js 的 applyThemeWithRemote action 使用
*
* 暴露的 API:
* ThemeOverride.boot() 首屏阻塞拉取 + 缓存预热(失败静默)
* ThemeOverride.refresh(force) 重新拉取 + 重新应用
* ThemeOverride.getByTheme(theme) 取单个模式桶(brand/light/dark)的合并 KV
* ThemeOverride.getAll() { brand, light, dark }
* ThemeOverride.onUniacidChange() 切租户后清旧缓存
* ThemeOverride.getRemoteStatus() 'unknown' | 'ok' | 'fail'
* ThemeOverride.onRemoteStatusChange(fn) 订阅状态变化
* ThemeOverride.__debug_cache 内部缓存(测试用)
*
* 关键: 一次 boot 只发一次 HTTP 请求,后端 getAllByTenant 一次出 brand/light/dark 三桶
* 避免对每个 theme 单独请求造成的 3 倍带宽浪费
*/
import { themeConfig } from './config-external.js';
import Config from './config.js';
import http from './http.js';
import { Platform } from './platform.js';
const THEMES = ['brand', 'light', 'dark'];
// 远端覆写:内存缓存
// shape: { [theme]: { version, map, ts, global_version } }
const overrideCache = {};
// 远端全量 preset 内存缓存(remote-only 模式用)
// shape: { [presetName]: { ...tokenMap } }
const presetsCache = {};
// 远端覆写:并发去重(以"全量拉取"为粒度)
let allInflight = null;
// 远端全量 preset 拉取:并发去重
let presetsInflight = null;
// 远端可用性三态机
let remoteStatus = 'unknown';
let remoteStatusAt = 0;
const remoteStatusListeners = [];
// 配置项缓存
const REMOTE = (themeConfig && themeConfig.overrideRemote) || {};
/**
* 校验 source 配置:只接受 local / remote / hybrid,其它一律视为 remote(安全默认)
*/
function normalizeSource(s) {
return ['local', 'remote', 'hybrid'].includes(s) ? s : 'remote';
}
const SOURCE = normalizeSource(REMOTE.source || 'remote');
/**
* 远端失败原因归一
*/
function normalizeReason(s) {
const allow = ['timeout', 'network', 'http', 'parse', 'exception', 'unknown'];
return allow.includes(s) ? s : 'unknown';
}
/**
* 远端成功/失败状态机
*/
function setRemoteStatus(s, detail) {
if (remoteStatus === s) return;
const prev = remoteStatus;
remoteStatus = s;
remoteStatusAt = Date.now();
const safeDetail = {
reason: normalizeReason(detail && detail.reason),
theme: detail && detail.theme,
};
remoteStatusListeners.forEach(fn => {
try { fn(s, safeDetail); } catch (e) { /* 忽略监听器异常 */ }
});
try { uni.$emit && uni.$emit('theme:remote-status', { from: prev, to: s, ...safeDetail }); } catch (e) {}
if (s === 'fail') {
try { uni.$emit && uni.$emit('theme:fallback', { reason: safeDetail.reason }); } catch (e) {}
}
}
/**
* 获得当前租户 id
*/
function getCurrentUniacid() {
const u = uni.getStorageSync('uniacid');
return u ? parseInt(u, 10) || Config.uniacid : Config.uniacid;
}
/**
* 当前平台类型
*/
function getCurrentAppType() {
try { return Platform.getAppType() || '*'; } catch (e) { return '*'; }
}
/**
* 持久化 key: <prefix><uniacid>_<appType>_<theme>
*/
function getOverrideStorageKey(theme) {
const u = getCurrentUniacid();
const a = getCurrentAppType();
return `${REMOTE.storagePrefix || 'THEME_OVR_'}${u}_${a}_${theme}`;
}
/**
* 内存 cache key: <uniacid>_<appType>_<theme>
*/
function getOverrideMemKey(theme) {
return `${getCurrentUniacid()}_${getCurrentAppType()}_${theme}`;
}
/**
* 从 storage 预热单个 theme 桶到内存(首屏兜底)
* 仅在内存还没有该 key 时才读 storage,避免覆盖更新值
*/
function preheatFromStorage(theme) {
const mk = getOverrideMemKey(theme);
if (overrideCache[mk]) return;
try {
const cached = uni.getStorageSync(getOverrideStorageKey(theme));
if (cached && cached.map) {
overrideCache[mk] = {
version: cached.version || 0,
map: cached.map || {},
ts: cached.ts || 0,
global_version: cached.global_version || 0,
};
return;
}
} catch (e) { /* 忽略 */ }
overrideCache[mk] = { version: 0, map: {}, ts: 0, global_version: 0 };
}
/**
* 把"单次 HTTP 响应"按 by_theme 拆到 3 个内存桶 + 持久化
*/
function applyRemoteResponse(d) {
const byTheme = (d && d.by_theme && typeof d.by_theme === 'object') ? d.by_theme : {};
const gv = (d && d.global_version) || 0;
const ts = Date.now();
THEMES.forEach(theme => {
const remoteMap = (byTheme[theme] && typeof byTheme[theme] === 'object') ? byTheme[theme] : {};
const mk = getOverrideMemKey(theme);
const baseCache = overrideCache[mk] || { version: 0, map: {}, ts: 0, global_version: 0 };
const merged = Object.assign({}, baseCache.map, remoteMap);
overrideCache[mk] = {
version: gv,
map: merged,
ts,
global_version: gv,
};
try { uni.setStorageSync(getOverrideStorageKey(theme), overrideCache[mk]); } catch (e) {}
});
}
/**
* 取"3 个桶里最大的 global_version"(穿透缓存用)
*/
function maxCachedGlobalVersion() {
let gv = 0;
THEMES.forEach(t => {
const mk = getOverrideMemKey(t);
const c = overrideCache[mk];
if (c && c.global_version > gv) gv = c.global_version;
});
return gv;
}
/**
* 一次 HTTP 拉齐 3 个 theme 桶
* 这是 boot() / refresh() / onUniacidChange() 共用的"拉取入口"
*
* 关键: 1 次 HTTP, 拆 3 桶,避免对每个 theme 单独请求造成 3 倍浪费
*
* @returns {Promise<{ source:'cache'|'remote'|'local', ok:boolean, reason?:string, themes:string[] }>}
*/
async function loadAllOverrides() {
if (SOURCE === 'local') return { source: 'local', ok: true, themes: THEMES };
// 并发去重:同一刻只允许一个在飞
if (allInflight) return allInflight;
allInflight = (async () => {
// 1) 先预热 storage 兜底
THEMES.forEach(preheatFromStorage);
// 2) 一次 HTTP 拉齐 3 桶
try {
const res = await Promise.race([
http.sendRequest({
url: REMOTE.overridesUrl || '/api/theme/overrides',
data: {
global_version: maxCachedGlobalVersion(),
},
async: false,
}),
new Promise((r) => setTimeout(() => r({ code: -1, message: 'timeout' }), REMOTE.requestTimeout || 4000)),
]);
if (!res || res.code !== 0 || !res.data) {
const reason = !res ? 'network' : (res.code === -1 ? 'timeout' : (res.message || 'bad-response'));
setRemoteStatus('fail', { reason, theme: 'all' });
return { source: 'local', ok: false, reason, themes: THEMES };
}
applyRemoteResponse(res.data);
setRemoteStatus('ok', { theme: 'all' });
emitUpdated('all');
return { source: 'remote', ok: true, themes: THEMES };
} catch (e) {
setRemoteStatus('fail', { reason: 'exception', error: String(e && e.message || e), theme: 'all' });
return { source: 'local', ok: false, reason: 'exception', themes: THEMES };
}
})();
try {
return await allInflight;
} finally {
allInflight = null;
}
}
/**
* 触发"主题已更新"事件
* 注意:Vuex 的 themeColorSet action 已经在 setThemeStyle 后跑过,
* CSS 变量已挂到页面 wrapper 上,组件会自动刷新。
* 这里只发通知,方便业务代码(如自定义 JS 直读 themeStyle 的页面)主动 re-render。
*/
function emitUpdated(theme) {
try { uni.$emit && uni.$emit('theme:updated', { theme }); } catch (e) {}
}
// 远端全量 preset 持久化 key: <storagePresetsPrefix><uniacid>_<appType>
function getPresetsStorageKey() {
const u = getCurrentUniacid();
const a = getCurrentAppType();
return `${REMOTE.storagePresetsPrefix || 'THEME_PRESETS_'}${u}_${a}`;
}
// 远端全量 preset 内存 cache key
function getPresetsMemKey() {
return `${getCurrentUniacid()}_${getCurrentAppType()}`;
}
// 从 storage 预热全量 preset 到内存(首屏兜底)
function preheatPresetsFromStorage() {
const mk = getPresetsMemKey();
if (presetsCache[mk] && Object.keys(presetsCache[mk]).length) return;
try {
const cached = uni.getStorageSync(getPresetsStorageKey());
if (cached && typeof cached === 'object') {
presetsCache[mk] = cached;
return;
}
} catch (e) { /* 忽略 */ }
}
/**
* 一次 HTTP 拉齐 8 个 preset(remote-only 模式)
* 关键: 不阻塞首屏,失败静默. store/index.js 的 applyThemeWithRemote 会优先用
* 内存缓存(由 loadAllPresets 写入), 缓存未命中时回退到 webpack stub(只含 default).
*
* @returns {Promise<{ source:'cache'|'remote'|'local'|'skipped', ok:boolean, presets?:object, reason?:string }>}
*/
async function loadAllPresets() {
if (SOURCE === 'local') return { source: 'skipped', ok: true, presets: {} };
if (!REMOTE.presetsUrl) return { source: 'skipped', ok: false, reason: 'no-url' };
// 并发去重
if (presetsInflight) return presetsInflight;
presetsInflight = (async () => {
// 1) 先预热 storage 兜底
preheatPresetsFromStorage();
// 2) 一次 HTTP 拉齐 8 个 preset
try {
const res = await Promise.race([
http.sendRequest({
url: REMOTE.presetsUrl,
data: {},
async: false,
}),
new Promise((r) => setTimeout(() => r({ code: -1, message: 'timeout' }), REMOTE.requestTimeout || 4000)),
]);
if (!res || res.code !== 0 || !res.data) {
const reason = !res ? 'network' : (res.code === -1 ? 'timeout' : (res.message || 'bad-response'));
console.warn('[theme-presets] remote load fail, keep stub:', reason);
return { source: 'local', ok: false, reason };
}
// 3) 解析响应. 期望格式: { by_preset: { default: {...}, green: {...}, ... } }
const byPreset = (res.data.by_preset && typeof res.data.by_preset === 'object') ? res.data.by_preset : null;
if (!byPreset) {
console.warn('[theme-presets] response missing by_preset');
return { source: 'local', ok: false, reason: 'parse' };
}
// 4) 写入内存缓存 + 持久化
const mk = getPresetsMemKey();
presetsCache[mk] = byPreset;
try { uni.setStorageSync(getPresetsStorageKey(), byPreset); } catch (e) {}
// 5) 通知已更新
try { uni.$emit && uni.$emit('theme:presets-updated'); } catch (e) {}
return { source: 'remote', ok: true, presets: byPreset };
} catch (e) {
console.warn('[theme-presets] remote load exception:', e && e.message);
return { source: 'local', ok: false, reason: 'exception' };
}
})();
try {
return await presetsInflight;
} finally {
presetsInflight = null;
}
}
// 导出主体
export default {
SOURCE,
/**
* 阻塞式预热:App.onLaunch 在 Lang.boot 后调用
* 失败静默,不阻塞首屏
*
* @returns {Promise<{ok:boolean, source:'local'|'remote'|'cache'|'timeout', status:string, reason?:string, themes:string[]}>}
*/
async boot() {
if (SOURCE === 'local') {
return { ok: true, source: 'local', status: remoteStatus, themes: THEMES };
}
const bootTimeout = REMOTE.bootTimeout || 2000;
const t = new Promise((r) => setTimeout(() => r({ __timeout: true }), bootTimeout));
// 切租户检测
const currentUid = getCurrentUniacid();
try {
const lastUid = uni.getStorageSync('theme_last_uniacid');
if (lastUid && String(lastUid) !== String(currentUid)) {
this.onUniacidChange();
}
uni.setStorageSync('theme_last_uniacid', currentUid);
} catch (e) {}
const result = await Promise.race([loadAllOverrides(), t]);
if (result && result.__timeout) {
return { ok: false, source: 'timeout', status: 'fail', reason: 'timeout', themes: THEMES };
}
return {
ok: remoteStatus === 'ok',
source: remoteStatus === 'ok' ? 'remote' : 'local',
status: remoteStatus,
themes: THEMES,
};
},
/**
* 主动重新拉取(管理后台改了之后 EventBus 通知触发)
* @param {boolean} [force=false] true = 绕过缓存强刷
*/
async refresh(force = false) {
if (force) {
// 强刷:清掉内存 + 持久化缓存,逼 loadAllOverrides 走远端
THEMES.forEach(t => {
const mk = getOverrideMemKey(t);
if (overrideCache[mk]) overrideCache[mk] = { version: 0, map: {}, ts: 0, global_version: 0 };
try { uni.removeStorageSync(getOverrideStorageKey(t)); } catch (e) {}
});
}
return loadAllOverrides();
},
/**
* 切租户后清旧缓存
*/
onUniacidChange() {
if (SOURCE === 'local') return;
if (REMOTE.refreshOnUniacidChange === false) return;
THEMES.forEach(t => {
const sk = getOverrideStorageKey(t);
try { uni.removeStorageSync(sk); } catch (e) {}
delete overrideCache[getOverrideMemKey(t)];
});
// 同步清空全量 preset 缓存(remote-only 模式)
const psk = getPresetsStorageKey();
try { uni.removeStorageSync(psk); } catch (e) {}
delete presetsCache[getPresetsMemKey()];
loadAllOverrides();
},
/**
* 取某个 theme 桶(同步:有缓存返缓存;无缓存时该桶返回 {})
* store/index.js 的 applyThemeWithRemote action 直接用
* @param {'brand'|'light'|'dark'} theme
* @returns {object} 扁平 KV map (没有时返回 {})
*/
getByTheme(theme) {
const mk = getOverrideMemKey(theme);
const cached = overrideCache[mk];
return (cached && cached.map) ? cached.map : {};
},
/**
* 取所有 theme 桶
* @returns {{ brand: object, light: object, dark: object }}
*/
getAll() {
return {
brand: this.getByTheme('brand'),
light: this.getByTheme('light'),
dark: this.getByTheme('dark'),
};
},
/**
* 取全量 preset 内存缓存(remote-only 模式)
* store/index.js 的 applyThemeWithRemote 通过这个取到远端拉的全量 preset
* @returns {{ [presetName: string]: object }}
*/
getAllPresets() {
const mk = getPresetsMemKey();
return presetsCache[mk] || {};
},
/**
* 主动拉全量 preset(remote-only 模式)
* - 失败静默, 不抛错
* - 内存 + 持久化双写
* - 拉成功后发 uni.$emit('theme:presets-updated')
*
* @returns {Promise<{ source:'cache'|'remote'|'local'|'skipped', ok:boolean, presets?:object, reason?:string }>}
*/
loadAllPresets,
/**
* 当前远端状态
*/
getRemoteStatus() { return remoteStatus; },
/**
* 订阅远端状态变化
* @param {(status:string, detail:object) => void} fn
* @returns {() => void} unsubscribe
*/
onRemoteStatusChange(fn) {
if (typeof fn !== 'function') return () => {};
remoteStatusListeners.push(fn);
try { fn(remoteStatus, { at: remoteStatusAt, source: SOURCE }); } catch (e) {}
return () => {
const i = remoteStatusListeners.indexOf(fn);
if (i >= 0) remoteStatusListeners.splice(i, 1);
};
},
// 内部测试/调试用
__debug_overrideCache: overrideCache,
__debug_loadAllOverrides: loadAllOverrides,
}

View File

@@ -2,6 +2,8 @@
* 将常用的Uniapp提供的函数,存放到这里,按需引用
*/
import lang from './lang.js';
/**
* 显示错误信息
@@ -18,7 +20,7 @@ const showError = (err, useModal = false) => {
});
} else {
uni.showModal({
title: '错误提示',
title: lang.lang('uniappUtils.errorTip'),
content,
showCancel: false,
})
@@ -34,7 +36,6 @@ export const makePhoneCall = (mobile) => {
uni.makePhoneCall({
phoneNumber: `${mobile}`,
success(e) {
console.log(e);
}
});
} catch (err) {
@@ -52,7 +53,7 @@ export const copyTextAsync = (text, { copySuccess = '', copyFailed = '' } = {})
return new Promise((resolve, reject) => {
// 输入验证
if (!text && text !== '') {
const error = new Error('复制文本不能为空');
const error = new Error(lang.lang('uniappUtils.copyTextEmpty'));
showError(error);
reject(error);
return;
@@ -60,13 +61,13 @@ export const copyTextAsync = (text, { copySuccess = '', copyFailed = '' } = {})
// 超时监测
const timeoutId = setTimeout(() => {
let error = new Error('复制操作长时间无响应,请检查相关权限及配置是否正确');
let error = new Error(lang.lang('uniappUtils.copyTimeout'));
// #ifdef MP-WEIXIN
error = new Error([
'复制操作长时间无响应!',
'原因:',
'1.微信平台->用户隐私保护指引->"剪贴板"功能未添加或审核未通过;',
'2.微信平台对剪贴板API调用频率有限制'
lang.lang('uniappUtils.copyTimeoutTitle'),
lang.lang('uniappUtils.copyTimeoutReason'),
lang.lang('uniappUtils.wechatClipboardReason1'),
lang.lang('uniappUtils.wechatClipboardReason2')
].join('\r\n'));
// #endif
showError(error, true);
@@ -97,7 +98,7 @@ export const copyTextAsync = (text, { copySuccess = '', copyFailed = '' } = {})
clearTimeout(timeoutId);
try {
uni.showToast({
title: err.message || err.errMsg || copyFailed || '复制失败',
title: err.message || err.errMsg || copyFailed || lang.lang('uniappUtils.copyFailed'),
icon: 'none',
duration: 2000
});

623
common/js/util-navigate.js Normal file
View File

@@ -0,0 +1,623 @@
/**
* util-navigate.js
*
* 跳转链路专用的工具集 — 从 util.js 拆分出来
*
* 包含的函数(全部服务于 redirectTo / diyRedirectTo 跳转链路):
* - _toParamValueString : 把任意值序列化成可作为 URL 参数的字符串
* - parsePageParams : 把 page_params 还原成对象(JSON.parse 安全封装)
* - resolveLinkUrl : 解析 link 对象得到最终可跳转的 URL
* - cleanParamUrls : 递归清理任意对象/数组中所有"看起来像 URL"的字符串字段
* - normalizeUrl : 严格规范化 URL(不补协议/不补 host)
* - appendQueryParams : 给 URL 追加 query 参数
* - getPlatform : 跨平台检测(h5 / mp-weixin / mp-harmony / quickapp)
* - shouldEncodeUrl : 是否需要主动 encodeURIComponent(4 平台都 true)
* - _safeEncodeForPlatform : 跨平台统一的 safeEncode(decode roundtrip + encode 一次)
* - _navigateTo : 跨平台跳转 API 调度
*
* 设计原则:
* 1. 不依赖 util.js,避免循环依赖
* 2. 全部为普通函数(不挂在 default export 对象上),方便 tree-shaking 和测试
* 3. 行为完全兼容 util.js 旧版,util.js 通过 import 把这些方法挂载到 default export 上
* (所有调用方 this.$util.cleanParamUrls / this.$util.redirectTo 等都不需要改)
*
* 跨平台编码 / 跳转策略文档见 _safeEncodeForPlatform / _navigateTo 的注释
*/
// =============================================================
// 基础工具
// =============================================================
/**
* 把任意值序列化成可作为 URL 参数的字符串。
* - 对象/数组: JSON.stringify
* - null/undefined: ''
* - 其他: String(v)
*
* @param {*} v
* @returns {string}
*/
export function _toParamValueString(v) {
if (v === null || v === undefined) return '';
if (typeof v === 'object') return JSON.stringify(v);
return String(v);
}
/**
* 把 URL 上的 page_params 还原成对象。是 _toParamValueString 的逆操作。
* 容错策略: 任何解析失败都安全降级到 defaultValue,不抛异常。
*
* @example
* parsePageParams('{"a":1}') // { a: 1 }
* parsePageParams({a: 1}) // { a: 1 } (已是对象直接返回)
* parsePageParams('[object Object]') // {} (老 bug 残留安全降级)
* parsePageParams('') // {}
* parsePageParams(null) // {}
* parsePageParams(undefined) // {}
* parsePageParams('not json', {x:1}) // { x: 1 } (解析失败走默认值)
*
* @param {*} raw
* @param {Object} [defaultValue={}]
* @returns {Object}
*/
export function parsePageParams(raw, defaultValue = {}) {
if (raw == null) return Object.assign({}, defaultValue);
if (typeof raw === 'object') return raw;
if (typeof raw === 'string') {
try {
const parsed = JSON.parse(raw);
return typeof parsed === 'object' && parsed !== null
? parsed
: Object.assign({}, defaultValue);
} catch (e) {
return Object.assign({}, defaultValue);
}
}
return Object.assign({}, defaultValue);
}
// =============================================================
// resolveLinkUrl
// =============================================================
/**
* 解析 link 对象得到最终可跳转的 URL
* 同时把 wap_url 自带的 query 参数与 page_params 合并, 写入 link.page_params;
* 并把 link.wap_url 改为不含 query 的 path, 避免后续 redirectTo 二次编码
* 优先级: page_params > wap_url query (新机制优先)
*
* @param {Object} link
* @returns {string|null}
*/
export function resolveLinkUrl(link) {
if (!link) return null;
// 0. 把 wap_url 中的 query 合并到 page_params
if (link.wap_url) {
const decodedWap = decodeEntity(link.wap_url);
const queryIdx = decodedWap.indexOf('?');
if (queryIdx !== -1) {
const path = decodedWap.substring(0, queryIdx);
const queryStr = decodedWap.substring(queryIdx + 1);
const urlParams = {};
queryStr.split('&').forEach((kv) => {
if (!kv) return;
const eqIdx = kv.indexOf('=');
const k = eqIdx === -1 ? kv : kv.substring(0, eqIdx);
const v = eqIdx === -1 ? '' : kv.substring(eqIdx + 1);
if (k) urlParams[k] = v;
});
const pageParams = parsePageParams(link.page_params);
link.page_params = Object.assign({}, urlParams, pageParams);
link.wap_url = path;
}
}
// 1. 优先使用 page_key(新机制)
if (link.page_key) {
// 这里原本会调 resolvePageUrl(link.page_key, params),
// 但 util-navigate.js 不依赖 util.js,因此返回 link.wap_url
// (util.js 在 import 此模块后会用 page_key 重新解析)
const params = parsePageParams(link.page_params);
// 注: 完整 page_key 解析留给 util.js (它有 resolvePageUrl)
// 这里只做"wap_url 已被 resolveLinkUrl 处理过" 的返回
}
// 2. 回退: 旧的 wap_url(已被处理为不含 query 的 path)
if (link.wap_url) {
return link.wap_url;
}
return null;
}
/**
* decodeEntity — HTML 实体解码
* (从 util.js 顶层 export 搬过来, 跟其他跳转工具一起)
*
* 解码 &xxx; / &#xN; 等 HTML 实体
* 容错: 任何解析失败都返回原文
*
* @param {string} str
* @param {boolean} [amp=true] 是否解码 &amp;
* @returns {string}
*/
export function decodeEntity(str, amp) {
const html4Entities = {
nbsp: ' ', iexcl: '¡', cent: '¢', pound: '£', curren: '₣', yen: '¥',
brvbar: '§', sect: 'Ş', uml: '¨', copy: '©', ordf: 'ª', laquo: '«',
not: '¬', shy: '­®', macr: '¯', deg: '°', plusmn: '±', sup2: '²',
sup3: '³', acute: '´', micro: 'µ', para: '¶', middot: '·', cedil: '¸',
sup1: '¹', ordm: 'º', raquo: '»', frac14: '¼', frac12: '½', frac34: '¾',
iquest: '¿', agrave: 'à', aacute: 'á', acirc: 'â', atilde: 'ã', auml: 'ä',
aring: 'å', aelig: 'æ', ccedil: 'ç', egrave: 'è', eacute: 'é', ecirc: 'ê',
euml: 'ë', igrave: 'ì', iacute: 'í', icirc: 'î', iuml: 'ï', eth: 'ð',
ntilde: 'ñ', ograve: 'ò', oacute: 'ó', ocirc: 'ô', otilde: 'õ', ouml: 'ö',
times: 'ø', ugrave: 'ù', uacute: 'ú', ucirc: 'û', uuml: 'ü', yacute: 'ý',
thorn: 'þ', yuml: 'ÿ', fnof: 'ƒ', alpha: 'α', beta: 'β', gamma: 'γ',
delta: 'δ', epsilon: 'ε', zeta: 'ζ', eta: 'η', theta: 'θ', iota: 'ι',
kappa: 'κ', lambda: 'λ', mu: 'μ', nu: 'ν', xi: 'ξ', omicron: 'ο',
pi: 'π', rho: 'ρ', sigmaf: 'σ', sigma: 'σ', tau: 'τ', upsilon: 'υ',
phi: 'φ', chi: 'ψ', omega: 'ω',
};
amp = amp === undefined ? true : amp;
let i = str.indexOf('&');
while (i !== -1) {
const j = str.indexOf(';', i + 3);
let code;
if (j === -1) break;
if (str[i + 1] === '#') {
code = parseInt((str[i + 2] === 'x' ? '0' : '') + str.substring(i + 2, j));
if (!isNaN(code)) {
str = str.substring(0, i) + String.fromCharCode(code) + str.substring(j + 1);
}
} else {
code = str.substring(i + 1, j);
if (html4Entities[code] || (code === 'amp' && amp)) {
str = str.substring(0, i) + (html4Entities[code] || '&') + str.substring(j + 1);
}
}
i = str.indexOf('&', i + 1);
}
return str;
}
// =============================================================
// cleanParamUrls
// =============================================================
/**
* 递归清理任意对象/数组中所有"看起来像 URL"的字符串字段:
* - 去除反引号 / 各种空白 / 零宽字符
* - 修复 scheme 后多余斜杠(https:////host → https://host)
*
* "看起来像 URL" 的判定: 含 `://`(大小写不敏感)
* - 命中: 走清理
* - 不命中: 原样保留(name / title / 标识符等普通字符串字段不被误伤)
*
* 设计: 不限定 key 列表,递归遍历,新加任何 URL 字段都自动覆盖
*
* @param {*} value 任意值
* @returns {*} 与输入同结构的清理后值
*/
export function cleanParamUrls(value) {
// 内部递归函数,通过闭包引用自身,避免 this 绑定问题
const _clean = (v) => {
if (v === null || v === undefined) return v;
if (typeof v === 'string') {
if (/:\/\//i.test(v)) {
return v
.split('').filter((ch) =>
ch !== '`' && ch !== ' ' && ch !== '\t' && ch !== '\n' && ch !== '\r',
).join('')
.replace(/^(https?:\/\/)\/+/i, '$1');
}
return v;
}
if (Array.isArray(v)) {
return v.map((item) => _clean(item));
}
if (typeof v === 'object') {
const out = {};
for (const k of Object.keys(v)) {
out[k] = _clean(v[k]);
}
return out;
}
return v;
};
return _clean(value);
}
// =============================================================
// normalizeUrl
// =============================================================
/**
* 严格 URL 规范化(只规范化已有部分,绝不自动补充)
*
* 策略:
* 1) 预清理: 剥离反引号 / 各种空白 / BOM / 零宽字符(脏数据兜底)
* 2) 不补 https:// — 如果原串没有协议,保持没有
* 3) 不补 host — 如果原串没有 host,保持没有
* 4) 只对真实存在的部分做规范化: 协议小写、host 小写、path 解析 . ..、合并多 /、去默认端口、query 排序
* 5) scheme 后只允许恰好 2 个 '/',不允许 https:////host 这类畸形,遇到就返回 ''
*
* @param {string} urlString
* @returns {string} 标准化后的 URL;若输入无法解析为合法 URL 则返回空串 ''
*/
export function normalizeUrl(urlString) {
if (!urlString || typeof urlString !== 'string') return '';
// 1) 预清理: 反引号 / 各种空白 / BOM / 零宽字符
let url = urlString
.split('').filter((ch) => {
const code = ch.charCodeAt(0);
if (code <= 0x20) return false;
if (ch === '`') return false;
if (code === 0x3000) return false;
if (code === 0xFEFF || code === 0x200B ||
code === 0x200C || code === 0x200D ||
code === 0x2060) return false;
return true;
}).join('');
// 2) 解析协议(可选,允许缺失)
const protocolMatch = url.match(/^(https?):\/\//i);
let protocol = '';
let rest = url;
if (protocolMatch) {
protocol = protocolMatch[1].toLowerCase() + '://';
rest = url.substring(protocolMatch[0].length);
// scheme 后不能紧跟 '/',即不允许 https:////host
if (rest.charAt(0) === '/') {
console.warn('[normalizeUrl] scheme 后有多余的 /:', urlString);
return '';
}
} else {
rest = url;
}
// 3) 解析 hash
const hashIndex = rest.indexOf('#');
let hash = '';
let mainPart = rest;
if (hashIndex !== -1) {
hash = rest.substring(hashIndex);
mainPart = rest.substring(0, hashIndex);
}
// 4) 解析 query
const queryIndex = mainPart.indexOf('?');
let query = '';
let pathPart = mainPart;
if (queryIndex !== -1) {
query = mainPart.substring(queryIndex); // 包含 '?'
pathPart = mainPart.substring(0, queryIndex);
}
// 5) 解析 host
let hostname = '';
let port = '';
let pathname = pathPart;
if (protocol) {
const firstSlash = pathPart.indexOf('/');
const hostPort = firstSlash === -1 ? pathPart : pathPart.substring(0, firstSlash);
pathname = firstSlash === -1 ? '' : pathPart.substring(firstSlash);
if (hostPort) {
const colonIdx = hostPort.lastIndexOf(':');
if (colonIdx !== -1) {
hostname = hostPort.substring(0, colonIdx);
port = hostPort.substring(colonIdx + 1);
} else {
hostname = hostPort;
}
}
}
// 6) 规范化 host
let lowerHostname = '';
if (hostname) {
lowerHostname = hostname.toLowerCase();
if ((protocol === 'http://' && port === '80') ||
(protocol === 'https://' && port === '443')) {
port = '';
}
if (/[\/\s]/.test(lowerHostname)) {
console.warn('[normalizeUrl] host 含非法字符:', urlString);
return '';
}
}
// 7) 规范化 pathname
let normalizedPath = pathname;
if (normalizedPath) {
const segments = normalizedPath.split('/');
const resolved = [];
for (let i = 0; i < segments.length; i++) {
const seg = segments[i];
if (seg === '' || seg === '.') {
if (i === 0) resolved.push('');
continue;
}
if (seg === '..') {
if (resolved.length > 1) resolved.pop();
continue;
}
resolved.push(seg);
}
normalizedPath = resolved.join('/') || '/';
}
// 8) 规范化 query
let normalizedQuery = '';
if (query) {
const qs = query.substring(1);
if (qs) {
const pairs = qs.split('&').map((pair) => {
const eqIdx = pair.indexOf('=');
return eqIdx === -1
? { k: pair, v: '' }
: { k: pair.substring(0, eqIdx), v: pair.substring(eqIdx + 1) };
});
pairs.sort((a, b) => a.k.localeCompare(b.k));
normalizedQuery = '?' + pairs.map((p) => p.k + '=' + p.v).join('&');
}
}
// 9) 拼回
const portStr = port ? ':' + port : '';
const hostPart = lowerHostname ? lowerHostname + portStr : '';
const schemeAndHost = protocol + hostPart;
return schemeAndHost + normalizedPath + normalizedQuery + hash;
}
// =============================================================
// appendQueryParams
// =============================================================
/**
* 给 URL 追加 query 参数(已存在的 key 会被覆盖)
*
* @param {string} url
* @param {Object} params
* @returns {string}
*/
export function appendQueryParams(url, params) {
if (!url) return '';
if (!params) return url;
const hashIndex = url.indexOf('#');
let hash = '';
let targetUrl = url;
if (hashIndex !== -1) {
hash = url.substring(hashIndex);
targetUrl = url.substring(0, hashIndex);
}
const separator = targetUrl.includes('?') ? '&' : '?';
const queryString = Object.entries(params)
.filter(([, value]) => value !== undefined && value !== null)
// 对象/数组走 JSON.stringify,避免 String({}) 退化成 "[object Object]"
.map(([key, value]) => `${key}=${_toParamValueString(value)}`)
.join('&');
return targetUrl + separator + queryString + hash;
}
// =============================================================
// 跨平台检测 / 编码 / 跳转
// =============================================================
/**
* 平台检测 — 4 个目标平台:
* - 'h5' 浏览器
* - 'mp-weixin' 微信小程序
* - 'mp-harmony' 鸿蒙元服务
* - 'quickapp' 华为快应用 (实际是 H5 嵌入快应用 Webview)
*
* 测试覆盖: util.js 在 import 后,可在 default export 上设 __platform 强制指定
*/
export function getPlatform() {
// 1) 测试覆盖: 通过模块级 _testPlatform 注入
if (typeof globalThis !== 'undefined' && globalThis.__UTIL_NAVIGATE_TEST_PLATFORM__) {
return globalThis.__UTIL_NAVIGATE_TEST_PLATFORM__;
}
// 2) 编译时变量
// #ifdef MP-WEIXIN
return 'mp-weixin'
// #endif
// #ifdef MP-HARMONY
return 'mp-harmony'
// #endif
// 3) 运行时
if (navigator?.userAgent?.includes('mode-quickapp')) { // H5网页,如何判断自己在华为快应用的Webview中
return 'quickapp'
}
// #ifdef H5
try {
var ua = navigator?.userAgent;
if (ua) {
// 华为快应用内嵌 WebView 的 UA 关键字:HarmonyQuickApp / HuaweiQuickApp / HQABridge / QuickApp
const isQuickapp = /HarmonyQuickApp|HuaweiQuickApp|HQABridge|QuickApp/i.test(ua);
if (isQuickapp) {
return 'quickapp'
}
}
} catch (e) {}
// #endif
if (typeof process !== 'undefined' && process.env && process.env.UNI_PLATFORM) {
return process.env.UNI_PLATFORM;
}
if (typeof window !== 'undefined' && typeof window.location !== 'undefined' && typeof uni === 'undefined') {
return 'h5';
}
if (typeof uni !== 'undefined' && typeof uni.getSystemInfoSync === 'function') {
try {
const info = uni?.getSystemInfoSync();
const p = (info && info.platform) || '';
if (/harmony|ohos/i.test(p)) return 'mp-harmony';
if (info.mp === true || /miniprogram/i.test(info.appName || '')) return 'mp-weixin';
if (/quickapp|huawei/i.test(p)) return 'quickapp';
return 'h5';
} catch (e) { /* ignore */ }
}
// 默认返回
return 'h5';
}
/**
* 判断是否是在华为快应用的WebView中
* @returns
*/
export function isHarmonyQuickAppWebview() {
return getPlatform() === 'quickapp'
}
/**
* 是否需要 JS 侧主动 encodeURIComponent
* 4 平台都需要(true)
*/
export function shouldEncodeUrl() {
return true;
}
/**
* 跨平台 safeEncode(decode roundtrip + encode 一次)
*
* 4 平台编码行为:
* | 平台 | 宿主 | 内部自动 encode? | JS 侧需要 encode? |
* |-----------|---------------|------------------|------------------|
* | h5 | 浏览器 | 否 | 必须 |
* | mp-weixin | 微信原生 | 否 | 必须(否则微信把 & 当分隔符丢参数) |
* | mp-harmony| 鸿蒙原生 | 否 | 必须 |
* | quickapp | 华为快应用 Webview (本质 H5) | 否 | 必须 |
*
* 关键 bug 修复(2026-07-14):
* 微信小程序下, src 内嵌 URL 含 `&` `?` `=` 空格 反引号等特殊字符时,
* 若 JS 不主动 encode, 微信底层路由会把这些字符当成 top-level query 分隔符,
* 导致后续 key(id/uniacid/page_params) 全部丢失。
*
* @param {*} v
* @returns {string}
*/
export function _safeEncodeForPlatform(v) {
const s = _toParamValueString(v);
// decode roundtrip: 兼容上游已 encode 过的入参
let once = s;
try {
if (/%[0-9a-fA-F]{2}/.test(s)) {
once = decodeURIComponent(s);
}
} catch (e) {
once = s;
}
// 4 平台都主动 encode 一次
return encodeURIComponent(once);
}
/**
* 跨平台跳转 API 调度
*
* @param {Object} args
* @param {string} args.to
* @param {string} [args.mode='navigateTo']
* @param {string} [args.platform] 不传则自动 getPlatform()
* @returns {{ url: string, mode: string, api: string }}
*/
export function _navigateTo({ to, mode, platform } = {}) {
const p = platform || getPlatform();
const m = mode || 'navigateTo';
// H5: 用 window.location
if (p === 'h5') {
if (typeof window === 'undefined' || typeof window.location === 'undefined') {
console.warn('[navigate] H5 环境下没有 window.location');
return { url: to, mode: m, api: 'noop' };
}
try {
if (m === 'reLaunch' || m === 'redirectTo') {
window.location.replace(to);
} else {
window.location.href = to;
}
} catch (e) {
console.warn('[navigate] H5 跳转失败:', e);
}
return { url: to, mode: m, api: 'window.location' };
}
// 微信 / 鸿蒙 / 快应用: 走对应的 uni API
// (华为快应用实际是 H5 嵌入快应用 Webview, uni 全局可用)
if (typeof uni === 'undefined') {
console.warn('[navigate] 非 H5 环境下没有 uni 全局');
return { url: to, mode: m, api: 'noop' };
}
let api = 'navigateTo';
switch (m) {
case 'tabbar':
case 'switchTab':
// 鸿蒙元服务: uni.switchTab 静默失败, 用 reLaunch 兜底
// (微信 / 快应用: 正常用 uni.switchTab)
if (p === 'mp-harmony') {
uni.reLaunch({ url: to });
api = 'reLaunch';
} else {
uni.switchTab({ url: to });
api = 'switchTab';
}
break;
case 'redirectTo':
uni.redirectTo({ url: to });
api = 'redirectTo';
break;
case 'reLaunch':
uni.reLaunch({ url: to });
api = 'reLaunch';
break;
case 'navigateTo':
default:
uni.navigateTo({ url: to });
api = 'navigateTo';
break;
}
return { url: to, mode: m, api };
}
// =============================================================
// 兼容: 把所有函数打包到一个对象(用于 util.js 挂载到 default export)
// =============================================================
/**
* 把所有跳转相关函数打包到一个对象, util.js 把它挂载到 default export
* 上, 保持 this.$util.cleanParamUrls / this.$util.redirectTo 等 API 兼容
*
* @param {Object} [opts]
* @param {string} [opts.platform] 强制指定平台(测试用)
* @returns {Object}
*/
export function createNavigateApi(opts = {}) {
if (opts.platform) {
// 测试用: 注入到 globalThis,getPlatform 会优先读
if (typeof globalThis !== 'undefined') {
globalThis.__UTIL_NAVIGATE_TEST_PLATFORM__ = opts.platform;
}
}
return {
getPlatform,
shouldEncodeUrl,
_safeEncodeForPlatform,
_navigateTo,
cleanParamUrls,
normalizeUrl,
appendQueryParams,
parsePageParams,
resolveLinkUrl,
decodeEntity,
};
}

649
common/js/util-tabbar.js Normal file
View File

@@ -0,0 +1,649 @@
/**
* util-tabbar.js
*
* TabBar / 子包路径相关工具集 — 从 util.js 拆分出来
*
* 包含的函数(全部服务于 redirectTo / diyRedirectTo 的 tabBar 命中判断):
* - resolvePageUrl : 根据 page_key + params 解析得到实际跳转 URL
* - isPageInRouteList : 判断当前路由是否命中 page_routes 列表
* - resolveLinkUrl : 解析 link 对象得到最终 URL(合并 wap_url query 进 page_params)
* - systemTabBarList : 当前最新的 tabBar.list 配置
* - adaptSubpackageUrl : 子包路径前缀映射(/pages/order/ → /pages_order/)
* - _normalizePath : 归一化任意路径(私有,内部用)
* - isTabBarRootPage : 判断给定路径是否是 TabBar 根页面
* - isCurrentPageTabBarRoot : 判断**当前**页面是否是 TabBar 根页面(依赖 getCurrentPages/store)
* - checkTabBarActive : 检查 tabBar 是否激活
*
* 设计原则:
* 1. 不依赖 util.js,避免循环依赖
* 2. 纯函数为主(isCurrentPageTabBarRoot 除外,它依赖 getCurrentPages 和 store,
* 业务方在调用时手动注入 store 即可)
* 3. PAGE_KEY_MAP / NO_TAB_PAGES / PAGE_TAB_MAP / TAB_BAR_KEYS 仍然在 util.js(业务配置)
* util-tabbar.js 接受外部传入,提高复用性
*/
import { _toParamValueString } from './util-navigate.js';
// =============================================================
// PAGE_KEY → 实际 URL 解析
// =============================================================
/**
* 根据 page_key + params 解析得到实际跳转 URL
* @param {string} page_key 页面语义常量, 如 PAGE_GOODS_LIST
* @param {Object} params 页面参数(JSON 对象)
* @param {Object} [pageKeyMap={}] page_key → 实际路径的映射表(由调用方注入,通常是 PAGE_KEY_MAP)
* @returns {string|null} 实际 URL(已拼接参数)或 null(未匹配)
*/
export function resolvePageUrl(page_key, params = {}, pageKeyMap = {}) {
if (!page_key || !pageKeyMap[page_key]) {
return null;
}
let url = pageKeyMap[page_key];
if (params && typeof params === 'object' && Object.keys(params).length > 0) {
const parts = [];
Object.keys(params).forEach(function (key) {
const value = params[key];
if (value === null || value === undefined || value === '') return;
// 对象/数组走 JSON.stringify, 避免 String({}) 退化成 "[object Object]"
// 消费端 resolveLinkUrl 已用 JSON.parse 还原
const encodedValue = _toParamValueString(value);
// H5: 浏览器不自动编码, 需要手动 encodeURIComponent
// 小程序 / App: uni.navigateTo 会自动编码, 这里不能再 encode, 否则双重编码
// #ifdef H5
parts.push(key + '=' + encodeURIComponent(encodedValue));
// #endif
// #ifndef H5
parts.push(key + '=' + encodedValue);
// #endif
});
if (parts.length > 0) {
url = url + (url.indexOf('?') !== -1 ? '&' : '?') + parts.join('&');
}
}
return url;
}
/**
* 判断当前路由是否命中 page_routes 列表
* 支持 3 种写法, 可混合使用:
* 1) PAGE_KEY_MAP 的 key → 如 "PAGE_INDEX"
* 2) 实际页面路径 → 如 "/pages/index/index"
* 3) 通配符路径 → 如 "/pages_tool/*" 或 "PAGE_ORDER_*"
*
* @param {string} currentRoute 当前页面路径(会自动补 / 前缀)
* @param {string[]} routeList 后台配置的 page_routes 数组
* @param {Object} [pageKeyMap={}] PAGE_KEY_MAP
* @returns {boolean}
*/
export function isPageInRouteList(currentRoute, routeList, pageKeyMap = {}) {
if (!currentRoute || !routeList || !Array.isArray(routeList) || routeList.length === 0) {
return false;
}
const route = currentRoute.startsWith('/') ? currentRoute : '/' + currentRoute;
for (const item of routeList) {
if (!item || typeof item !== 'string') continue;
const entry = item.trim();
if (!entry) continue;
// 1) 通配符 /pages_tool/* 或 PAGE_ORDER_*
if (entry.endsWith('/*')) {
const prefix = entry.slice(0, -1);
if (route.startsWith(prefix)) return true;
continue;
}
if (entry.endsWith('_*') && pageKeyMap) {
const keyPrefix = entry.slice(0, -1);
const matchedPaths = [];
for (const k of Object.keys(pageKeyMap)) {
if (k.startsWith(keyPrefix) && pageKeyMap[k]) {
matchedPaths.push(pageKeyMap[k]);
}
}
for (const p of matchedPaths) {
const pn = p.startsWith('/') ? p : '/' + p;
const dirPrefix = pn.substring(0, pn.lastIndexOf('/') + 1);
if (route.startsWith(dirPrefix)) return true;
if (route === pn) return true;
}
continue;
}
// 2) PAGE_KEY 名称
if (pageKeyMap && pageKeyMap[entry]) {
let mapped = pageKeyMap[entry];
mapped = mapped.startsWith('/') ? mapped : '/' + mapped;
if (route === mapped) return true;
continue;
}
// 3) 实际路径
if (entry.startsWith('/')) {
if (route === entry) return true;
continue;
}
}
return false;
}
// =============================================================
// resolveLinkUrl
// =============================================================
/**
* 解析 link 对象得到最终可跳转的 URL
* 同时把 wap_url 自带的 query 参数与 page_params 合并, 写入 link.page_params;
* 并把 link.wap_url 改为不含 query 的 path, 避免后续 redirectTo 重复附加
* 优先级: page_params > wap_url query (新机制优先)
*
* @param {Object} link
* @param {Object} [opts]
* @param {Object} [opts.pageKeyMap={}] PAGE_KEY_MAP
* @param {Function} [opts.parsePageParams] page_params 解析函数(默认用 util-navigate 的)
* @param {Function} [opts.resolvePageUrlFn] page_key → URL 函数(默认用本文件内)
* @param {Function} [opts.decodeEntity] HTML 实体解码函数
* @returns {string|null}
*/
export function resolveLinkUrl(link, opts = {}) {
const {
pageKeyMap = {},
parsePageParams = null,
resolvePageUrlFn = null,
decodeEntity = null,
} = opts;
if (!link) return null;
// 0. 把 wap_url 中的 query 合并到 page_params
if (link.wap_url) {
const _decode = decodeEntity || ((s) => s);
const decodedWap = _decode(link.wap_url);
const queryIdx = decodedWap.indexOf('?');
if (queryIdx !== -1) {
const path = decodedWap.substring(0, queryIdx);
const queryStr = decodedWap.substring(queryIdx + 1);
const urlParams = {};
queryStr.split('&').forEach((kv) => {
if (!kv) return;
const eqIdx = kv.indexOf('=');
const k = eqIdx === -1 ? kv : kv.substring(0, eqIdx);
const v = eqIdx === -1 ? '' : kv.substring(eqIdx + 1);
if (k) urlParams[k] = v;
});
// 解析 page_params (可能是字符串或对象) — 走统一 helper
const _parse = parsePageParams || ((p) => (p && typeof p === 'object') ? p : {});
const pageParams = _parse(link.page_params);
// 合并: page_params 覆盖 urlParams (新机制优先)
link.page_params = Object.assign({}, urlParams, pageParams);
// 把 link.wap_url 改为不含 query 的 path
link.wap_url = path;
}
}
// 1. 优先使用 page_key(新机制)
if (link.page_key) {
const _parse = parsePageParams || ((p) => (p && typeof p === 'object') ? p : {});
const _resolvePageUrl = resolvePageUrlFn || ((key, params) => resolvePageUrl(key, params, pageKeyMap));
const params = _parse(link.page_params);
const url = _resolvePageUrl(link.page_key, params);
if (url) return url;
}
// 2. 回退: 旧的 wap_url(已被处理为不含 query 的 path)
if (link.wap_url) {
return link.wap_url;
}
return null;
}
// =============================================================
// TabBar 列表与适配
// =============================================================
/**
* 当前最新的 tabBar.list
* 注意: 该函数需要业务方传入 4 个常量(INDEX/CATEGORY/CONTACT/MEMBER)
* 通常由 util.js 在 import 后调用 _setSystemTabBarList 注入
*/
export function makeSystemTabBarList(indexUrl, categoryUrl, contactUrl, memberUrl) {
return [indexUrl, categoryUrl, contactUrl, memberUrl];
}
/**
* 适配子包路径
* 把老路径 /pages/xxx/ 映射到新路径 /pages_xxx/
*
* @param {string} url
* @returns {string}
*/
export function adaptSubpackageUrl(url) {
if (!url) return url;
// 定义前缀映射表(key=旧前缀, value=新分包前缀)
const urlPrefixMap = {
'/pages/promotion/': '/pages_promotion/',
'/pages/order/': '/pages_order/',
'/pages/goods/': '/pages_goods/',
'/pages/member/': '/pages_tool/member/',
'/pages/login/': '/pages_tool/login/',
'/pages/agreement/': '/pages_tool/agreement/',
'/pages/article/': '/pages_tool/article/',
'/pages/cases/': '/pages_tool/cases/',
'/pages/contact/': '/pages_tool/contact/',
'/pages/files/': '/pages_tool/files/',
'/pages/form/': '/pages_tool/form/',
'/pages/help/': '/pages_tool/help/',
'/pages/notice/': '/pages_tool/notice/',
'/pages/pay/': '/pages_tool/pay/',
'/pages/recharge/': '/pages_tool/recharge/',
'/pages/seal/': '/pages_tool/seal/',
'/pages/storeclose/': '/pages_tool/storeclose/',
'/pages/vr/': '/pages_tool/vr/',
'/pages/weapp/': '/pages_tool/weapp/',
'/pages/webview/': '/pages_tool/webview/',
};
const prefixes = Object.keys(urlPrefixMap);
if (prefixes.length === 0) return url;
const regex = new RegExp(
'^(' + prefixes.map((key) =>
key.replace(/\//g, '\\/').replace(/\*/g, '.*'),
).join('|') + ')',
);
function replacePrefix(str) {
return str.replace(regex, (match) => {
const newPrefix = urlPrefixMap[match];
return newPrefix || match;
});
}
// 兜底: 把 3 个及以上的连续 `/` 收敛为 2 个, 只动 path 部分
const collapsed = url.replace(/([^:])\/{3,}/g, '$1//');
return replacePrefix(collapsed);
}
// =============================================================
// TabBar 命中判断(私有辅助)
// =============================================================
/**
* 归一化任意路径: 确保以 '/' 开头, 去除 query, 适配子包
* (私有, 仅本模块内部使用)
*/
function _normalizePath(path) {
if (!path) return '';
const normalized = path.startsWith('/') ? path : '/' + path;
return adaptSubpackageUrl(normalized).split('?')[0];
}
/**
* 从归一化路径提取分包名(parts[1])
* (私有, 仅本模块内部使用)
*/
function _getPackageName(normalizedPath) {
const parts = normalizedPath.split('/');
return parts[1] || '';
}
/**
* 解析"当前分包的入口 tab URL"
*
* 把 diy-bottom-nav.vue#updateCurrentRoute 里的查找逻辑抽成纯函数,
* 方便单元测试覆盖所有跳转场景, 同时让组件代码变薄.
*
* 查找优先级 (2026-07-16 重构, 对齐 iOS HIG):
* 1) 当前页面精确命中某个 tab 根页面 → 它就是入口 (tab→tab 跳转)
* 2) 同包内导航 (上一包 == 当前包) → 用当前包的第一个 tab
* 例: /pages_goods/list → /pages_goods/detail → CATEGORY 高亮
* 3) 跨包导航 (上一包 != 当前包) → 历史栈倒序查找最近一次访问的 TabBar 页
* 例: home → diy → HOME 高亮 (从哪个 tab 出发, 非 tab 页就归属哪个 tab)
* 4) 跨包但历史栈中无 tab → 退到当前包第一个 tab
* 5) 深链无历史 → 返回 null (iOS HIG: 无来源时不点亮)
*
* 与 checkTabBarActive 的关系:
* - resolveEntryTab 写入 packageEntryTab[currentPackage]
* - checkTabBarActive 通过 _findMatchingTabUrl 读取
* - 两者都不会做"无历史时的同分包兜底", 保证 iOS HIG 行为
*
* @param {Object} opts
* @param {string} opts.currentPageRoute 当前页面路由 (已 _normalizeRoute, 不含 query)
* @param {Object} opts.tabBarList tabBar 配置对象 ($store.state.tabBarList)
* @param {string[]} [opts.historyRoutes=[]] 历史栈路由列表 (不含 query, 不含当前页;
* 已 _normalizeRoute 但未 adaptSubpackageUrl, 函数内部会适配)
* @param {Set<string>} [opts.noTabPages] NO_TAB_PAGES 集合 (含 login/pay/AI 等全屏流程页)
* 这些页视为"modal", 不参与包归属判定
* @returns {string|null} 入口 tab URL (已适配子包路径、不含 query) 或 null
*/
export function resolveEntryTab(opts = {}) {
const {
currentPageRoute = '',
tabBarList = null,
historyRoutes = [],
noTabPages = null,
} = opts;
if (!currentPageRoute || !tabBarList || !Array.isArray(tabBarList.list)) {
return null;
}
const tabUrls = tabBarList.list
.filter((item) => item && item.link && item.link.wap_url)
.map((item) => adaptSubpackageUrl(item.link.wap_url).split('?')[0]);
if (tabUrls.length === 0) return null;
const normalizedCurrent = currentPageRoute.split('?')[0];
const currentPackageName = _getPackageName(normalizedCurrent);
// 1) 当前页面精确命中某个 tab → 它就是入口
const exactMatch = tabUrls.find((url) => url === normalizedCurrent);
if (exactMatch) return exactMatch;
// 工具: 判定一个路由是否"参与归属判定"
// 跳过 null/空 + NO_TAB_PAGES (login/pay/AI 等 modal 页, 不算中间步骤)
const isSkippable = (route) => {
if (!route) return true;
if (noTabPages && typeof noTabPages.has === 'function') {
const normalized = adaptSubpackageUrl(route).split('?')[0];
if (noTabPages.has(normalized)) return true;
}
return false;
};
// 找出"最近的上一页"属于哪个包 (跳过 null/空 + NO_TAB_PAGES)
let lastPackageName = '';
let hasPrevPage = false;
if (Array.isArray(historyRoutes) && historyRoutes.length > 0) {
for (let i = historyRoutes.length - 1; i >= 0; i--) {
const route = historyRoutes[i];
if (isSkippable(route)) continue;
lastPackageName = _getPackageName(adaptSubpackageUrl(route).split('?')[0]);
hasPrevPage = true;
break;
}
}
const isSamePackage = hasPrevPage && lastPackageName === currentPackageName;
const isCrossPackage = hasPrevPage && lastPackageName !== currentPackageName;
// 2) 同包内导航: 用当前包的第一个 tab
// 业务约定: 包内"主入口" = tabBarList 中该包出现的第一个 tab
// 例: pages_goods 有 [CATEGORY, CART] 两个 tab, 用户在 goods 频道内任何页面都归 CATEGORY
// 理由: CATEGORY 是商品频道的入口, 比 CART (特定子场景) 更"通用", 视觉一致
// 注意: 业务侧 tab 配置顺序很关键, 若有 pages_goods 出现 3+ tab, 主入口必须是业务上正确的那个
if (isSamePackage) {
const samePackage = tabUrls.find((url) => _getPackageName(url) === currentPackageName);
if (samePackage) return samePackage;
}
// 3) 跨包导航: 历史栈倒序查找最近一次访问的 TabBar 页 → 来源 tab
// 规则: 从哪个 TabBar 出发, 非 tab 页就归属哪个 TabBar 高亮
// 注意: 跳过 NO_TAB_PAGES, 因为 login/pay 等是 modal, 不是真实的导航步骤
if (isCrossPackage) {
for (let i = historyRoutes.length - 1; i >= 0; i--) {
const route = historyRoutes[i];
if (isSkippable(route)) continue;
const normalized = adaptSubpackageUrl(route).split('?')[0];
const exactTab = tabUrls.find((url) => url === normalized);
if (exactTab) return exactTab;
}
// 4) 跨包但历史栈中无 tab → 退到当前包第一个 tab
const samePackage = tabUrls.find((url) => _getPackageName(url) === currentPackageName);
if (samePackage) return samePackage;
}
// 5) 深链无历史 / 跳过 NO_TAB_PAGES 后没找到 → 返回 null
return null;
}
/**
* 给定当前页面路径 + tab 配置, 返回当前页面所属的 tab URL
* 优先级: 精确匹配 > packageEntryTab
*
* 注意 (2026-07-16): 旧版本在 packageEntryTab 没命中时会回退到"同分包第一个 tab",
* 这导致深链冷启动时 /pages_tool/* 页被错误标成"我的"。
* 现在改为"找不到就返回 null", 后续 checkTabBarActive 也不会再兜底,
* 行为对齐 iOS HIG (深链无历史时, TabBar 不点亮)。
*
* (私有)
*/
function _findMatchingTabUrl(currentPagePath, tabBarList, packageEntryTab) {
if (!tabBarList || !tabBarList.list || !Array.isArray(tabBarList.list)) return null;
const tabUrls = tabBarList.list
.filter((item) => item.link && item.link.wap_url)
.map((item) => _normalizePath(item.link.wap_url));
const normalizedCurrent = _normalizePath(currentPagePath);
// 1) 精确匹配 → 当前页面就是 tab 页面
const exactMatch = tabUrls.find((url) => url === normalizedCurrent);
if (exactMatch) return exactMatch;
// 2) 通过 packageEntryTab(由 updateCurrentRoute/redirectTo 写入)
const packageName = _getPackageName(normalizedCurrent);
if (packageEntryTab && typeof packageEntryTab === 'object' && packageEntryTab[packageName]) {
const entryTab = packageEntryTab[packageName];
const normalizedEntry = _normalizePath(entryTab);
if (tabUrls.includes(normalizedEntry)) return normalizedEntry;
}
// 3) 不再做"同分包兜底" — 找不到就返回 null
// 深链冷启动场景下无历史可参考, iOS HIG 推荐 TabBar 不点亮
return null;
}
/**
* 通配符路径匹配 — 支持 '/pages_tool/member/*' 形式
*
* 规则:
* - pattern 必须以 '/*' 结尾
* - '*' 匹配"前缀之后的至少一个字符段"
* - 例: '/pages_tool/member/*' 匹配 '/pages_tool/member/info' 但不匹配 '/pages_tool/member'
*
* @param {string} path 当前路径 (已 _normalizePath)
* @param {string} pattern 通配符 pattern
* @returns {boolean}
*/
function _matchWildcardPath(path, pattern) {
if (!path || !pattern) return false;
if (!pattern.endsWith('/*')) return false;
const prefix = pattern.slice(0, -2); // 去掉 '/*'
// 必须有至少一个字符在 '/*' 之后, 即 path 比 prefix 长, 且以 prefix + '/' 开头
return path.length > prefix.length + 1 && path.startsWith(prefix + '/');
}
/**
* 在 PAGE_TAB_MAP (精确) + PAGE_TAB_WILDCARDS (通配) 中查找当前页面对应的 tab
*
* 优先级: 精确匹配 > 通配符匹配
* 返回值可以是:
* - tab URL 字符串 → 命中, 高亮该 tab
* - null → 显式声明"无 tab", 一定不高亮
* - undefined → 未声明, 调用方走兜底逻辑 (history-walk / 无 tab)
*
* @param {string} currentPath 当前页面路径 (已 _normalizePath)
* @param {Object} pageTabMap 精确绑定表 (PAGE_TAB_MAP)
* @param {Array<{pattern: string, tab: string}>} pageTabWildcards 通配符列表 (PAGE_TAB_WILDCARDS)
* @returns {string|null|undefined}
*/
export function lookupPageTabMap(currentPath, pageTabMap, pageTabWildcards) {
if (!currentPath) return undefined;
// 1) 精确匹配
if (pageTabMap && Object.prototype.hasOwnProperty.call(pageTabMap, currentPath)) {
return pageTabMap[currentPath];
}
// 2) 通配符匹配
if (Array.isArray(pageTabWildcards)) {
for (const entry of pageTabWildcards) {
if (entry && entry.pattern && _matchWildcardPath(currentPath, entry.pattern)) {
return entry.tab;
}
}
}
return undefined;
}
/**
* 判断给定路径是否是 TabBar 根页面(与 diy_bottom_nav 中任意一项精确相等)
*
* @param {string} pagePath 当前页面路径(可以带/不带前导斜杠、可以带 query)
* @param {Object|null} tabBarList tabBar 配置对象($store.state.tabBarList)
* @returns {boolean} 如果是 TabBar 根页面返回 true
*/
export function isTabBarRootPage(pagePath, tabBarList) {
if (!pagePath) return false;
if (!tabBarList || !tabBarList.list || !Array.isArray(tabBarList.list)) return false;
const normalizedCurrent = _normalizePath(pagePath);
if (!normalizedCurrent) return false;
return tabBarList.list.some((item) => {
if (!item || !item.link || !item.link.wap_url) return false;
const normalizedTab = _normalizePath(item.link.wap_url);
return normalizedTab === normalizedCurrent;
});
}
/**
* 判断**当前**页面是否是 TabBar 根页面
* 封装了 getCurrentPages() + isTabBarRootPage 的组合, 供业务组件在弹窗/操作前判断
*
* 调用方需要注入 getCurrentPages 和 store:
* isCurrentPageTabBarRoot({
* getCurrentPages: typeof getCurrentPages === 'function' ? getCurrentPages : null,
* store,
* tabBarList: null, // 不传则从 store.state.tabBarList 取
* })
*
* @param {Object} [opts={}]
* @param {Function} [opts.getCurrentPages]
* @param {Object} [opts.store]
* @param {Object} [opts.tabBarList]
* @returns {boolean}
*/
export function isCurrentPageTabBarRoot(opts = {}) {
try {
const gcp = opts.getCurrentPages || (typeof getCurrentPages === 'function' ? getCurrentPages : null);
if (!gcp) return false;
const pages = gcp();
if (!pages || !pages.length) return false;
const currentRoute = '/' + String(pages[pages.length - 1].route || '').replace(/^\//, '');
if (!currentRoute) return false;
const tabBarList = opts.tabBarList
|| (opts.store && opts.store.state ? opts.store.state.tabBarList : null);
return isTabBarRootPage(currentRoute, tabBarList);
} catch (e) {
return false;
}
}
/**
* 检查 tabBar 是否激活
*
* @param {string} linkUrl 链接路径 /pages/goods/category
* @param {string} currentPageRoute 当前页面路径 /pages_goods/category
* @param {Object} tabBarList tabBar 配置对象, 用于动态判断
* @param {Object} packageEntryTab 追踪每个分包的入口 Tab { 'pages_goods': '/pages_goods/category' }
* @param {Object} [currentPageQuery={}] 当前页面 query 参数, 用于读取 from_tab 来源记忆
* @param {Object} [opts={}]
* @param {Set} [opts.noTabPages] 独立流程页集合(NO_TAB_PAGES)
* @param {Object} [opts.pageTabMap] 页面级 Tab 精确绑定表(PAGE_TAB_MAP)
* @param {Array<{pattern: string, tab: string}>} [opts.pageTabWildcards=[]] 页面级 Tab 通配符表(PAGE_TAB_WILDCARDS)
* @returns {boolean} 是否激活
*/
export function checkTabBarActive(
linkUrl,
currentPageRoute,
tabBarList,
packageEntryTab,
currentPageQuery = {},
opts = {},
) {
const { noTabPages = null, pageTabMap = {}, pageTabWildcards = [] } = opts;
// __TABBAR_DEBUG__: 开启后打印每一步决策, 用于排查"为什么我的 tab 不亮"
// 开启方式 (任选一种):
// - 全局: window.__TABBAR_DEBUG__ = true
// - 本次: opts.debug = true
const DEBUG = (typeof globalThis !== 'undefined' && globalThis.__TABBAR_DEBUG__)
|| opts.debug === true;
const _log = DEBUG ? (...a) => console.log('[TABBAR]', ...a) : () => {};
_log('checkTabBarActive called', { linkUrl, currentPageRoute, hasTabBarList: !!tabBarList });
// 1) 归一化 linkUrl: 统一前导 '/' + 子包路径适配 + 去除 query
const normalizedLink = _normalizePath(linkUrl);
const normalizedCurrent = _normalizePath(currentPageRoute);
if (!normalizedLink) {
_log('step 1: no linkUrl → false');
return false;
}
// 2) 精确匹配: 当前页面就是 linkUrl 指向的页面
if (normalizedLink === normalizedCurrent) {
_log('step 2: exact match → true', { link: normalizedLink });
return true;
}
// 3) 独立流程页: 不点亮任何 Tab
if (noTabPages && noTabPages.has && noTabPages.has(normalizedCurrent)) {
_log('step 3: NO_TAB_PAGES hit → false', { current: normalizedCurrent });
return false;
}
// 4) 若传入 tabBarList, 使用动态判断逻辑
if (tabBarList && tabBarList.list && Array.isArray(tabBarList.list)) {
const tabUrls = tabBarList.list
.filter((item) => item.link && item.link.wap_url)
.map((item) => _normalizePath(item.link.wap_url));
// 检查当前 linkUrl 是否是合法的 tab URL
if (!tabUrls.includes(normalizedLink)) {
_log('step 4: link not in tabUrls → false', { link: normalizedLink });
return false;
}
// 5) 页面级 Tab 绑定 (精确 + 通配符)
// 返回值可能是: tab URL | null (显式无 tab) | undefined (未声明)
const mappedTabUrl = lookupPageTabMap(normalizedCurrent, pageTabMap, pageTabWildcards);
if (mappedTabUrl !== undefined) {
_log('step 5: pageTabMap hit', { current: normalizedCurrent, mapped: mappedTabUrl });
// null = 显式声明"无 tab", 字符串 = 该 tab 高亮
return mappedTabUrl !== null && normalizedLink === _normalizePath(mappedTabUrl);
}
_log('step 5: pageTabMap miss → 进入 step 6/7');
// 6) 来源记忆兜底: 从哪个 Tab 跳转过来, 就保持那个 Tab 高亮
const fromTab = currentPageQuery.from_tab;
if (fromTab) {
const normalizedFromTab = _normalizePath(fromTab);
if (tabUrls.includes(normalizedFromTab)) {
const hit = normalizedLink === normalizedFromTab;
_log('step 6: from_tab query', { fromTab, hit });
return hit;
}
}
_log('step 6: no from_tab');
// 7) 分包入口追踪: 通过 updateCurrentRoute/resolveEntryTab 写入的入口 tab
// 注意: _findMatchingTabUrl 不会做"同分包兜底",找不到就返回 null
const matchingTabUrl = _findMatchingTabUrl(currentPageRoute, tabBarList, packageEntryTab);
if (matchingTabUrl) {
const hit = normalizedLink === matchingTabUrl;
_log('step 7: packageEntryTab', { matchingTabUrl, hit });
return hit;
}
_log('step 7: packageEntryTab miss → step 8');
// 8) 不再做"同分包兜底" — 找不到任何来源 tab 时不高亮
// 深链冷启动 / 扫码进非 tab 页: TabBar 全不亮, 对齐 iOS HIG
_log('step 8: no source → false (iOS HIG)');
return false;
}
return false;
}

File diff suppressed because it is too large Load Diff

View File

@@ -55,7 +55,6 @@ let Weixin = function () {
typeof callback == 'function' && callback(res);
},
fail: (res) => {
console.log('获取收货地址 fail',res);
alert(JSON.stringify(res))
}
});

View File

@@ -1,6 +1,8 @@
/**
* 企业微信JS-SDK调用
*/
import Lang from './lang.js';
let WxWork = function () {
// 企业微信JS-SDK
this.wxwork = null;
@@ -23,7 +25,7 @@ let WxWork = function () {
// H5环境下的企业微信
this.wxwork = WWOpenData;
} else {
console.error('企业微信JS-SDK未加载');
console.error(Lang.lang('wxworkJssdk.notLoaded'));
return false;
}
@@ -56,8 +58,8 @@ let WxWork = function () {
*/
this.addContact = function (params, success, fail) {
if (!this.wxwork) {
console.error('企业微信JS-SDK未初始化');
if (fail) fail('企业微信JS-SDK未初始化');
console.error(Lang.lang('wxworkJssdk.notInitialized'));
if (fail) fail(Lang.lang('wxworkJssdk.notInitialized'));
return;
}
@@ -69,7 +71,7 @@ let WxWork = function () {
if (res.err_msg === 'openUserProfile:ok') {
if (success) success(res);
} else {
console.error('打开用户资料失败:', res);
console.error(Lang.lang('wxworkJssdk.openUserProfileFailed'), res);
if (fail) fail(res.err_msg);
}
});
@@ -87,8 +89,8 @@ let WxWork = function () {
*/
this.openCustomerService = function (params, success, fail) {
if (!this.wxwork) {
console.error('企业微信JS-SDK未初始化');
if (fail) fail('企业微信JS-SDK未初始化');
console.error(Lang.lang('wxworkJssdk.notInitialized'));
if (fail) fail(Lang.lang('wxworkJssdk.notInitialized'));
return;
}

73
common/mixin/i18n-lazy.js Normal file
View File

@@ -0,0 +1,73 @@
/**
* 延迟初始化 i18n mixin
*
* 问题背景:
* 微信小程序/鸿蒙元服务环境下, main.js 同步 $mount() 会导致组件 data() 在
* Lang.boot() 完成前求值. 此时 $lang() 在 remote-only 模式下返回空串,
* 把空串缓存到 data 字段后, 后续 boot 完成的 $forceUpdate 也无法让它重算.
*
* 解决思路:
* data() 中不能调 $lang(), 否则空串被永久缓存.
* 模板只读 this.i18n.xxx(始终是字符串, 初值为空).
* 需要显示前, 显式调一次 this.prepareI18n() — 此时 boot 必然已完成.
*
* 用法:
*
* // 1) 在 data() 中:
* data() {
* return {
* i18n: {
* title: '',
* descPrefix: '',
* privacyContractName: '',
* },
* // 准备文案时需要的动态上下文(可选)
* platformContractName: '',
* };
* }
*
* // 2) 在 methods 中实现 i18nPrepareFn, 返回一个新对象用于填充 this.i18n
* // 其中 key 用反引号 `` `your.module.title` `` 这类命名代表"业务模块的真实 key",
* // 请用业务组件实际使用的 key 替换(例如 'components.privacyPopup.title')
* methods: {
* i18nPrepareFn() {
* return {
* title: this.$lang(`your.module.title`),
* descPrefix: this.$lang('components.privacyPopup.descPrefix', { appName: '本应用' }),
* privacyContractName: this.platformContractName || this.$lang(`your.module.defaultContract`),
* };
* },
* }
*
* // 3) 在需要显示前调 this.prepareI18n()(来自 mixin)
* // 此时 Lang.boot() 必然已完成, $lang() 返回真实翻译
* popUp() {
* this.prepareI18n();
* this.showPop = true;
* }
*
* 模板中只读 i18n.xxx:
* ```html
* <view>{{ i18n.title }}</view>
* <view>{{ i18n.descPrefix }}</view>
* ```
*/
export default {
methods: {
/**
* 一次性计算所有 i18n 文案并写入 this.i18n
* 关键: 调用时机必须是 boot 完成之后(否则会缓存空串)
* 模板中读 this.i18n.xxx 永远拿到字符串
*
* 业务组件需要实现 i18nPrepareFn() 方法,
* 返回一个对象, key 与 data().i18n 字段一一对应
*/
prepareI18n() {
if (typeof this.i18nPrepareFn !== 'function') {
console.warn('[i18n-lazy] i18nPrepareFn() not implemented; this.i18n will not be filled');
return;
}
this.i18n = this.i18nPrepareFn();
},
},
};

View File

@@ -0,0 +1,38 @@
/**
* 微信小程序图片长按识别二维码 mixin
* 自动为页面中的所有 image 组件添加 show-menu-by-longpress 属性
*/
export default {
data() {
return {
// 需要排除的图片类名(不需要长按识别的)
excludeImageClass: ['no-longpress', 'swiper-image', 'banner-image']
}
},
mounted() {
// #ifdef MP-WEIXIN
this.$nextTick(() => {
this.addLongpressToImages()
})
// #endif
},
methods: {
/**
* 为页面中的所有 image 添加长按识别支持
*/
addLongpressToImages() {
// 获取当前页面所有 image 组件
const images = document.querySelectorAll && document.querySelectorAll('image')
if (images) {
images.forEach(img => {
// 检查是否需要排除
const className = img.className || ''
const shouldExclude = this.excludeImageClass.some(cls => className.includes(cls))
if (!shouldExclude) {
img.setAttribute('show-menu-by-longpress', 'true')
}
})
}
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -17,7 +17,7 @@
<view class="fui-audio style3" :style="{ background: value.background }" v-else>
<!-- <audio src="/static/audio/bgm.mp3" controls loop></audio> -->
<view class="img">
<image :src="$util.img(value.imageUrl)"></image>
<image :src="$util.img(value.imageUrl)" show-menu-by-longpress></image>
</view>
<view class="content">
<view class="name" :style="{ color: value.textcolor }">{{ value.text }}</view>
@@ -98,9 +98,7 @@ export default {
uni.setStorageSync('audio_list', audio_list)
}
}
console.log(uni.getStorageSync('audio_list'))
var n = this;
// console.log(a)
a.onPlay(function () {
var e = setInterval(function () {
var i = a.currentTime / a.duration * 100 + "%", s = Math.floor(Math.ceil(a.currentTime) / 60), o = (Math.ceil(a.currentTime) % 60 / 100).toFixed(2).slice(-2), r = Math.ceil(a.currentTime);
@@ -113,13 +111,12 @@ export default {
var s = n.$util.img(n.value.audioUrl), o = n.audios[n.value.id].seconds || 0, r = 0, u = 1;
0 == u && a.onEnded(function (e) {
c[t].status = !1, n.status = !1, c[t].seconds = 0, console.log(c), n.audios = c;
c[t].status = !1, n.status = !1, c[t].seconds = 0, n.audios = c;
});
var c = n.audios;
c[t] || (c[t] = {}), a.paused && 0 == o ? (a.src = s, a.play(), 1 == u && (a.loop = !0),
c[t].status = !0, n.status = !0, n.pauseOther(t)) : a.paused && o > 0 ? (a.play(), 0 == r ? a.seek(o) : a.seek(0),
c[t].status = !0, n.status = !0, n.pauseOther(t)) : (a.pause(), c[t].status = !1, n.status = !1), n.audios = c;
console.log(n.audios)
},
pauseOther: function (e) {
var t = this;
@@ -190,18 +187,14 @@ export default {
var u = s + ":" + o, c = that.audios;
c[t].audiowidth = i, c[t].Time = e, c[t].audiotime = u, c[t].seconds = r
that.audios = c
// console.log(c)
console.log(that.audios[that.value.id].audiotime)
that.audiotime = that.audios[that.value.id].audiotime
that.audiowidth = that.audios[that.value.id].audiowidth
console.log(i)
that.lyg = i
}, 1e3);
});
this.audioContext.onEnded(() => {
console.log('播放结束');
this.status = 0
});
}

View File

@@ -10,9 +10,9 @@
:style="{ fontSize: value.titleStyle.fontSize * 2 + 'rpx', color: value.titleStyle.textColor, fontWeight: value.titleStyle.fontWeight ? 'bold' : '' }">
{{ value.titleStyle.leftText }}
</view>
<image v-else class="left-img" :src="$util.img(value.titleStyle.leftImg)" mode="heightFix"></image>
<image v-else class="left-img" :src="$util.img(value.titleStyle.leftImg)" mode="heightFix" show-menu-by-longpress></image>
<view class="head-content" v-if="value.titleStyle.style == 'style-1'"
:style="{ color: value.titleStyle.textColor }">低至0元免费拿</view>
:style="{ color: value.titleStyle.textColor }">{{ $lang('components-diy.diy-bargain.freeGet') }}</view>
<view class="head-right"
:style="{ fontSize: value.titleStyle.moreFontSize * 2 + 'rpx', color: value.titleStyle.moreColor }"
@tap.stop="$util.redirectTo('/pages_promotion/bargain/list')">
@@ -28,7 +28,7 @@
<view class="img-wrap" :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }">
<image :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }"
:src="$util.img(item.goods_image, { size: 'mid' })" mode="widthFix"
@error="imageError(index)" />
@error="imageError(index)" show-menu-by-longpress/>
</view>
<view class="content"
v-if="value.goodsNameStyle.control || value.priceStyle.mainControl || value.btnStyle.control">
@@ -41,22 +41,22 @@
<view class="bg">
<view class="curr" :style="{ width: progress(item) * 2 + 'rpx' }">
<image class="progress-bar" mode="widthFix"
:src="$util.img('public/uniapp/bargain/progress_bar_01.png')" />
:src="$util.img('public/uniapp/bargain/progress_bar_01.png')" show-menu-by-longpress/>
</view>
</view>
<view class="num" v-if="item.is_bargaining">
已砍
{{ $lang('components-diy.diy-bargain.bargained') }}
<text>¥{{ (item.price - item.curr_price).toFixed(2) }}</text>
,仅差
{{ $lang('components-diy.diy-bargain.onlyDiff') }}
<text>¥{{ item.curr_price }}</text>
</view>
<view class="num" v-else>
最低可砍至
{{ $lang('components-diy.diy-bargain.minBargainTo') }}
<text>¥{{ item.floor_price }}</text>
</view>
</view>
<view class="progress" v-if="value.style == 'style-3'">
最低可砍至
{{ $lang('components-diy.diy-bargain.minBargainTo') }}
<text class="num">¥{{ item.floor_price }}</text>
</view>
<view class="price-wrap">
@@ -75,7 +75,7 @@
color: value.btnStyle.theme == 'diy' ? value.btnStyle.textColor : '',
borderRadius: value.btnStyle.aroundRadius * 2 + 'rpx'
}">
{{ item.is_bargaining ? '继续砍价' : value.btnStyle.text }}
{{ item.is_bargaining ? $lang('components-diy.diy-bargain.continueBargain') : value.btnStyle.text }}
</button>
</view>
</view>
@@ -89,14 +89,14 @@
<view class="img-wrap" :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }">
<image :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }"
:src="$util.img(item.goods_image, { size: 'mid' })" mode="widthFix"
@error="imageError(index)" :lazy-load="true" />
@error="imageError(index)" :lazy-load="true" show-menu-by-longpress/>
<image class="bg"
v-if="value.saleStyle.control && value.template == 'horizontal-slide' && value.style != 'style-2'"
:src="$util.img('public/uniapp/bargain/bg.png')" mode="widthFix" />
<view class="num"
v-if="value.saleStyle.control && value.template == 'horizontal-slide' && value.style != 'style-2'"
:style="{ color: value.theme == 'diy' ? value.saleStyle.color : '' }">
已砍{{ item.sale_num }}件
{{ $lang('components-diy.diy-bargain.soldCount', { num: item.sale_num }) }}
</view>
</view>
<view :class="['content', { 'multi-content': value.nameLineMode == 'multiple' }]"
@@ -134,14 +134,14 @@
<view class="img-wrap" :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }">
<image :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }"
:src="$util.img(item.goods_image, { size: 'mid' })" mode="widthFix"
@error="imageError(dataIndex)" :lazy-load="true" />
@error="imageError(dataIndex)" :lazy-load="true" show-menu-by-longpress/>
<image class="bg"
v-if="value.saleStyle.control && value.template == 'horizontal-slide' && value.style != 'style-2'"
:src="$util.img('public/uniapp/bargain/bg.png')" mode="widthFix" />
<view class="num"
v-if="value.saleStyle.control && value.template == 'horizontal-slide' && value.style != 'style-2'"
:style="{ color: value.theme == 'diy' ? value.saleStyle.color : '' }">
已砍{{ item.sale_num }}件
{{ $lang('components-diy.diy-bargain.soldCount', { num: item.sale_num }) }}
</view>
</view>
<view :class="['content', { 'multi-content': value.nameLineMode == 'multiple' }]"
@@ -461,7 +461,10 @@ scroll-view ::-webkit-scrollbar {
align-items: center;
justify-content: center;
height: 36rpx;
background: linear-gradient(270deg, #ffbd5b 0%, #fd882e 100%);
// P0: 砍价头渐变 → var(--pintuan-label-grad-start/end) 复用(同色系)
// 兼容: 微信小程序 / 鸿蒙元服务 — linear-gradient 嵌套 var() 现代 runtime 支持
background: #ffbd5b; // 兜底
background: linear-gradient(270deg, var(--pintuan-label-grad-start, #ffbd5b) 0%, var(--pintuan-label-grad-end, #fd882e) 100%);
border-radius: 24rpx;
padding: 2rpx;
@@ -474,7 +477,9 @@ scroll-view ::-webkit-scrollbar {
text:nth-child(2) {
padding: 6rpx 4rpx 4rpx;
background-color: #fff;
color: #ffbd5b;
// P0: 砍价头文字色 → var(--pintuan-label-grad-start) 复用
// 兼容: 微信小程序 / 鸿蒙元服务 — color 接受 var() 无问题
color: var(--pintuan-label-grad-start, #ffbd5b);
border-radius: 50%;
transform: scale(0.6);
font-weight: bold;
@@ -576,7 +581,9 @@ scroll-view ::-webkit-scrollbar {
width: auto;
height: 20rpx;
border-radius: 20rpx;
background-color: #ffeadb;
// P0: 砍价浅底 → var(--bargain-promo-shallow)
// 兼容: 微信小程序 / 鸿蒙元服务 — background-color 接受 var() 无问题
background-color: var(--bargain-promo-shallow, #ffeadb);
position: relative;
&::after {
@@ -584,7 +591,9 @@ scroll-view ::-webkit-scrollbar {
width: 26rpx;
height: 26rpx;
border-radius: 50%;
background-color: #fa1a1a;
// P0: 砍价红圆点 → var(--bargain-promo-color)
// 兼容: 微信小程序 / 鸿蒙元服务 — background-color 接受 var() 无问题
background-color: var(--bargain-promo-color, #fa1a1a);
position: absolute;
top: 50%;
transform: translateY(-50%);
@@ -595,7 +604,9 @@ scroll-view ::-webkit-scrollbar {
width: 0;
height: 20rpx;
border-radius: 20rpx;
background-color: #fa1a1a;
// P0: 砍价红进度条 → var(--bargain-promo-color)
// 兼容: 微信小程序 / 鸿蒙元服务 — background-color 接受 var() 无问题
background-color: var(--bargain-promo-color, #fa1a1a);
position: relative;
.progress-bar {
@@ -618,7 +629,9 @@ scroll-view ::-webkit-scrollbar {
line-height: 1;
text {
color: #fa1a1a;
// P0: 砍价数字红 → var(--bargain-promo-color)
// 兼容: 微信小程序 / 鸿蒙元服务 — color 接受 var() 无问题
color: var(--bargain-promo-color, #fa1a1a);
}
}
}

View File

@@ -1,54 +1,39 @@
<template>
<view data-component-name="diy-bottom-nav" v-if="tabBarList && tabBarList.list">
<view data-component-name="diy-bottom-nav" v-if="shouldShowTabBar">
<view class="tab-bar" :style="{ backgroundColor: tabBarList.backgroundColor }">
<view class="tabbar-border"></view>
<view class="item" v-for="(item, index) in tabBarList.list" :key="item.id" @tap.stop="redirectTo(item.link)">
<view class="bd">
<block v-if="item.link.wap_url == '/pages_goods/cart'">
<view class="icon" v-if="tabBarList.type == 1 || tabBarList.type == 2"
:animation="cartAnimation" id="tabbarCart">
<block v-if="verify(item.link)">
<image v-if="item.selected_icon_type == 'img'"
:src="$util.img(item.selectedIconPath)" />
<diy-icon v-if="item.selected_icon_type == 'icon'" :icon="item.selectedIconPath"
:value="item.selected_style ? item.selected_style : null"></diy-icon>
</block>
<block v-else>
<image v-if="item.icon_type == 'img'" :src="$util.img(item.iconPath)" />
<diy-icon v-if="item.icon_type == 'icon'" :icon="item.iconPath"
:value="item.style ? item.style : null"></diy-icon>
</block>
<view class="cart-count-mark font-size-activity-tag"
:class="{ max: item.link.wap_url == '/pages_goods/cart' && cartNumber > 99 }"
:style="{ background: 'var(--price-color)' }" v-if="cartNumber > 0">
{{ cartNumber > 99 ? '99+' : cartNumber }}
</view>
</view>
<view class="tabbar-border"></view>
<view class="item" v-for="(item, index) in tabBarList.list" :key="item.id" @tap.stop="redirectTo(item.link)">
<view class="bd">
<view class="icon" v-if="tabBarList.type == 1 || tabBarList.type == 2"
:animation="isCartItem(item.link) ? cartAnimation : null"
:id="isCartItem(item.link) ? 'tabbarCart' : null">
<block v-if="verify(item.link)">
<image v-if="item.selected_icon_type == 'img'"
:src="$util.img(item.selectedIconPath)" />
<diy-icon v-if="item.selected_icon_type == 'icon'" :icon="item.selectedIconPath"
:value="item.selected_style ? item.selected_style : null"></diy-icon>
</block>
<block v-else>
<view class="icon" v-if="tabBarList.type == 1 || tabBarList.type == 2">
<block v-if="verify(item.link)">
<image v-if="item.selected_icon_type == 'img'"
:src="$util.img(item.selectedIconPath)" />
<diy-icon v-if="item.selected_icon_type == 'icon'" :icon="item.selectedIconPath"
:value="item.selected_style ? item.selected_style : null"></diy-icon>
</block>
<block v-else>
<image v-if="item.icon_type == 'img'" :src="$util.img(item.iconPath)" />
<diy-icon v-if="item.icon_type == 'icon'" :icon="item.iconPath"
:value="item.style ? item.style : null"></diy-icon>
</block>
</view>
<image v-if="item.icon_type == 'img'" :src="$util.img(item.iconPath)" />
<diy-icon v-if="item.icon_type == 'icon'" :icon="item.iconPath"
:value="item.style ? item.style : null"></diy-icon>
</block>
<view class="cart-count-mark font-size-activity-tag"
:class="{ max: cartNumber > 99 }"
:style="{ background: 'var(--price-color)' }"
v-if="isCartItem(item.link) && cartNumber > 0">
{{ cartNumber > 99 ? '99+' : cartNumber }}
</view>
</view>
<view class="label"
v-if="(tabBarList.type == 1 || tabBarList.type == 3) && tabBarList.theme == 'diy'"
:style="{ color: verify(item.link) ? tabBarList.textHoverColor : tabBarList.textColor }">
{{ lang == 'en-us' ? item.en_text : item.text }}
{{ $langConfig.getField(item, 'text') }}
</view>
<view class="label"
v-if="(tabBarList.type == 1 || tabBarList.type == 3) && tabBarList.theme == 'default'"
:style="{ color: verify(item.link) ? 'var(--base-color)' : '#333333' }">
{{ lang == 'en-us' ? item.en_text : item.text }}
{{ $langConfig.getField(item, 'text') }}
</view>
</view>
</view>
@@ -59,7 +44,8 @@
</template>
<script>
import { adaptSubpackageUrl, checkTabBarActive } from '@/common/js/util.js'
import { adaptSubpackageUrl, checkTabBarActive, decodeEntity } from '@/common/js/util.js'
import { resolveEntryTab } from '@/common/js/util-tabbar.js'
import DiyMinx from './minx.js'
// 底部导航栏
export default {
@@ -76,7 +62,6 @@ export default {
mixins: [DiyMinx],
data() {
return {
lang: uni.getStorageSync("lang"),
currentRoute: '', //当前页面路径
jumpFlag: true, //是否可以跳转,防止重复点击
cartAnimation: {}
@@ -105,9 +90,25 @@ export default {
});
},
computed: {
// 当前语言(响应式):通过 componentRefresh 建立依赖,切语言时自动更新
// 不能直接用 uni.getStorageSync 作为 data,因为它不是响应式的
currentLang() {
// 通过 componentRefresh 建立响应式依赖
// 切语言时 store 中的 componentRefresh 会 +1,触发重新计算
this.componentRefresh;
return uni.getStorageSync("lang") || 'zh-cn';
},
cartChange() {
return this.$store.state.cartChange;
}
},
packageEntryTab() {
return this.$store.state.packageEntryTab;
},
// 响应 tabBarList 异步加载: 后端返回前 updateCurrentRoute 是 no-op,
// tabBarList 就绪后必须重跑一次, 否则冷启动+秒点链接会出现"先不高亮→再突然高亮"
tabBarReady() {
return this.tabBarList && this.tabBarList.list && this.tabBarList.list.length > 0;
},
},
watch: {
cartChange: function (nval, oval) {
@@ -123,38 +124,148 @@ export default {
this.cartAnimation = animation.export();
}, 300);
}
}
},
// tabBarList 异步加载完成后, 补一次 updateCurrentRoute
// 修复: 冷启动时用户在 tabBarList 就绪前点击链接, 第一次 updateCurrentRoute 是 no-op
tabBarReady: {
handler(ready) {
if (ready) {
this.updateCurrentRoute();
}
},
immediate: false,
},
},
methods: {
// 更新当前路由
// 统一归一化路径:currentPage.route 不带前导 '/',但 tab 的 wap_url 带前导 '/'
// 统一加前导 '/' 后再 split,确保 parts[1]=分包名、parts[2]=页面名
_normalizeRoute(route) {
if (!route) return '';
return route.startsWith('/') ? route : '/' + route;
},
// 从归一化路径中提取分包名(parts[1])
_getPackageName(normalizedRoute) {
const parts = normalizedRoute.split('?')[0].split('/');
return parts[1] || '';
},
// 判断某个链接是否指向购物车页面
isCartItem(link) {
if (!link || !link.wap_url) return false;
return adaptSubpackageUrl(link.wap_url).split('?')[0] === '/pages_goods/cart';
},
// 更新当前路由,追踪每个分包的入口 tab
updateCurrentRoute() {
let currentPage = getCurrentPages()[getCurrentPages().length - 1];
if (currentPage && currentPage.route) {
this.currentRoute = currentPage.route;
const currentPages = getCurrentPages();
const currentPage = currentPages[currentPages.length - 1];
if (!currentPage || !currentPage.route) return;
// 归一化:补全前导 '/',确保后续 split('/') 后 parts[1]=分包名
const newRoute = this._normalizeRoute(currentPage.route);
const currentPackageName = newRoute.split('?')[0].split('/')[1] || '';
if (this.tabBarList && this.tabBarList.list && currentPackageName) {
// 收集历史栈路由 (排除当前页, 已 _normalizeRoute)
// 注意: 组件里直接传 raw route 给 resolveEntryTab,
// 内部 adaptSubpackageUrl 会兜底处理老路径 /pages/member/ 等
const historyRoutes = currentPages.length >= 2
? currentPages.slice(0, -1).map((p) =>
p && p.route ? this._normalizeRoute(p.route) : null)
: [];
// 调用纯函数 resolveEntryTab 完成 4 步查找
// 规则: 从哪个 TabBar 出发, 非 tab 页就归属哪个 TabBar 高亮
// 修复: home → diy 微页面 等跨分包导航被"同分包第一个 tab"误判的问题
const entryTab = resolveEntryTab({
currentPageRoute: newRoute,
tabBarList: this.tabBarList,
historyRoutes,
// 传 NO_TAB_PAGES 进去, 让 login/pay/AI 等 modal 页不参与归属判定
// 例子: home → login → diy 应算作 home → diy (login 是 modal)
noTabPages: this.$util && this.$util.NO_TAB_PAGES ? this.$util.NO_TAB_PAGES : null,
});
if (entryTab) {
this.$store.commit('setPackageEntryTab', {
...this.packageEntryTab,
[currentPackageName]: entryTab
});
}
}
this.currentRoute = newRoute;
},
redirectTo(link) {
this.$emit('callback');
this.$util.diyRedirectTo(link);
const redirectLink = link ? { ...link } : link;
if (link && link.wap_url) {
const decodedUrl = decodeEntity(link.wap_url);
const adaptedUrl = adaptSubpackageUrl(decodedUrl);
const packageName = this._getPackageName(adaptedUrl);
if (packageName) {
this.$store.commit('setPackageEntryTab', {
...this.packageEntryTab,
[packageName]: adaptedUrl.split('?')[0]
});
}
// 若目标页面不是 TabBar 根页面,追加 from_tab 来源参数,
// 用于非 Tab 页面的 TabBar 高亮记忆
if (this.tabBarList && this.tabBarList.list) {
const tabUrls = this.tabBarList.list
.filter(item => item.link && item.link.wap_url)
.map(item => adaptSubpackageUrl(decodeEntity(item.link.wap_url)).split('?')[0]);
if (!tabUrls.includes(adaptedUrl.split('?')[0])) {
const currentPages = getCurrentPages();
const currentPage = currentPages[currentPages.length - 1];
const currentTab = currentPage && currentPage.route
? tabUrls.find(tabUrl => checkTabBarActive(tabUrl, '/' + currentPage.route, this.tabBarList, this.packageEntryTab))
: null;
if (currentTab) {
redirectLink.from_tab = currentTab;
}
}
}
}
this.$util.diyRedirectTo(redirectLink);
},
verify(link) {
if (link == null || link == '' || !link.wap_url) return false;
// 标准化路径格式,确保比较的一致性
let currentPageRoute = this.currentRoute ? '/' + this.currentRoute : '';
let linkUrl = link.wap_url;
const currentPages = getCurrentPages();
const currentPage = currentPages[currentPages.length - 1];
const currentPageRoute = currentPage && currentPage.route
? this._normalizeRoute(currentPage.route)
: '';
// 首页特殊处理
if (linkUrl === this.$util.INDEX_PAGE_URL && this.name === 'DIY_VIEW_INDEX') {
return true;
// 读取当前页面 query 参数(兼容小程序与 H5)
let currentPageQuery = {};
if (currentPage) {
if (currentPage.options) {
currentPageQuery = currentPage.options;
} else if (currentPage.$page && currentPage.$page.options) {
currentPageQuery = currentPage.$page.options;
} else if (currentPage.$route && currentPage.$route.query) {
currentPageQuery = currentPage.$route.query;
}
}
// 精确匹配当前路径
if (adaptSubpackageUrl(linkUrl) === currentPageRoute) {
return true;
if (this.name === 'DIY_VIEW_INDEX') {
// DIY_VIEW_INDEX 短路: 当 name 是 DIY_VIEW_INDEX 时, 任意匹配的 tab 都高亮
// 修复前: 只对 HOME (INDEX_PAGE_URL) 生效
// 修复后: 适用于所有 tab 页面 (如 merchant DIY 首页、cart DIY 首页 等)
// 前提: 当前页面本身就是该 tab 根, 链接 == 当前页 → step 1 早就命中
// 这个短路主要兜底: "DIY_VIEW_INDEX 页面 + tab 链接" 的强语义关联
const linkUrl = adaptSubpackageUrl(link.wap_url).split('?')[0];
const currentUrl = currentPageRoute.split('?')[0];
if (linkUrl === currentUrl) {
return true;
}
}
return checkTabBarActive(linkUrl, currentPageRoute);
return checkTabBarActive(link.wap_url, currentPageRoute, this.tabBarList, this.packageEntryTab, currentPageQuery);
}
}
};
@@ -178,13 +289,42 @@ export default {
.tab-bar {
background-color: #fff;
box-sizing: border-box;
position: fixed;
left: 0;
bottom: 0;
/* ============================================================
* 固定在最底端,不能位置漂移(微信小程序 / 鸿蒙元服务 / 快应用 H5)
* ------------------------------------------------------------
* 现象(只在客户端小程序里复现,浏览器 H5 没事):
* 页面带 navigationStyle:custom + 页面内有 scroll-view,
* 滚到底部时 .tab-bar 会被微信客户端的页面避让逻辑推上去,
* 出现"位置漂移"。
*
* 根因(微信小程序特性):
* 1) 微信小程序里 position:fixed 的 containing block 是 page
* 根容器(不是 viewport),可视区变化时 fixed 元素下沿会
* 跟着重算,造成漂移。
* 2) 父级一旦出现 transform/filter/will-change,fixed 的
* containing block 会被进一步改写,fixed 元素行为更不可控。
*
* 加固措施:
* - bottom: 0 !important 钉死下沿
* - 提升 z-index 到 2147483647,避免被其他 fixed 元素遮挡
* - transform: translateZ(0) 强制提升到独立合成层,降低父级
* transform 干扰;will-change:transform 提示浏览器持续合成
* - 微信小程序里 #ifdef MP-WEIXIN / #ifdef MP-HARMONY 走原生
* tabBar,diy-bottom-nav 通常不会同时存在,但保留兜底
* ============================================================ */
position: fixed !important;
left: 0 !important;
right: 0 !important;
bottom: 0 !important;
top: auto !important;
width: 100%;
z-index: 998;
z-index: 2147483647 !important;
display: flex;
border-top: 2rpx solid #f5f5f5;
/* 强制提升合成层,降低父级 transform/filter 改变 containing block 的概率 */
transform: translateZ(0) !important;
-webkit-transform: translateZ(0) !important;
will-change: transform !important;
padding-bottom: 0;
padding-bottom: constant(safe-area-inset-bottom);
padding-bottom: env(safe-area-inset-bottom);

View File

@@ -2,30 +2,70 @@
<view data-component-name="diy-category-item" class="item-wrap" :class="type">
<block v-if="type == 'category' && category.child_list && category.child_list.length">
<view class="category-adv" v-if="category.image_adv" @tap.stop="diyRedirectTo(category.link_url)">
<image :src="$util.img(category.image_adv)" mode="widthFix" />
</view>
<image :src="$util.img(category.image_adv)" mode="widthFix" show-menu-by-longpress />
</view>
<block v-if="value.level == 2">
<block v-if="value.template == 99">
<view class="second-category-btns">
<view class="second-category-btn"
v-for="(one, oneIndex) in category.child_list"
:key="oneIndex"
:class="{ selected: selectedSecondCategory == one.category_id }"
@tap="selectSecondCategory(one)">
{{ one.category_name }}
</view>
</view>
<view class="category-goods-list" v-if="selectedSecondCategory">
<view class="goods-list double-column show" :data-template="value.template" v-if="secondCategoryGoodsList.length">
<view class="goods-item" v-for="(item, index) in secondCategoryGoodsList" :key="index">
<view class="goods-img" @tap.stop="toDetail(item)">
<image :src="goodsImg(item.goods_image)" mode="widthFix" @error="imgError(index)" show-menu-by-longpress />
<view class="color-base-bg goods-tag" v-if="item.label_name">{{ item.label_name }}</view>
</view>
<view class="info-wrap">
<view class="name-wrap" @tap.stop="toDetail(item)">
<view class="goods-name">{{ isEnEnv ? item.en_goods_name : item.goods_name }}</view>
</view>
<view class="price-wrap">
<view class="discount-price">
<block v-if="item.isinformation == 0">
<text class="unit price-style small">{{ $lang('common.currencySymbol') }}</text>
<text class="price price-style large">{{ parseFloat(showPrice(item)).toFixed(2).split('.')[0] }}</text>
<text class="unit price-style small">.{{ parseFloat(showPrice(item)).toFixed(2).split('.')[1] }}</text>
</block>
</view>
</view>
</view>
</view>
</view>
</view>
<view class="category-goods-empty" v-if="selectedSecondCategory && !secondCategoryGoodsList.length && !loading">
<image :src="$util.img('public/uniapp/category/empty.png')" mode="widthFix" show-menu-by-longpress></image>
<view class="tips">{{ $lang('components-diy.diy-category.noCategory') }}</view>
</view>
</block>
<block v-else-if="value.level == 2">
<view class="category-title">{{ category.category_name }}</view>
<view class="category-list">
<view class="category-item" v-for="(one, oneIndex) in category.child_list" :key="oneIndex"
@tap.stop="$util.redirectTo('/pages_goods/list', { category_id: one.category_id })">
<view class="img-box">
<image :src="$util.img(one.image)" mode="widthFix" />
<image :src="$util.img(one.image)" mode="widthFix" show-menu-by-longpress />
</view>
<view class="name">{{ one.category_name }}</view>
</view>
</view>
</block>
<block v-if="value.level == 3">
<block v-else-if="value.level == 3">
<block v-for="(one, oneIndex) in category.child_list" :key="oneIndex">
<view class="category-title">{{ one.category_name }}</view>
<view class="category-list">
<view class="category-item" v-for="(two, twoIndex) in one.child_list" :key="twoIndex"
@tap.stop="$util.redirectTo('/pages_goods/list', { category_id: two.category_id })">
<view class="img-box">
<image :src="$util.img(two.image)" mode="widthFix" :lazy-load="true" />
<image :src="$util.img(two.image)" mode="widthFix" :lazy-load="true" show-menu-by-longpress />
</view>
<view class="name">{{ two.category_name }}</view>
</view>
@@ -44,7 +84,7 @@
:class="{ 'screen-category-4': value.template == 4 }" :scroll-with-animation="true"
:scroll-into-view="scrollIntoView">
<view class="item" id="category-2--1" :class="{ selected: categoryId == -1 }"
@tap.stop="selectCategory(-1)">全部</view>
@tap.stop="selectCategory(-1)">{{ $lang('components-diy.diy-category-item.all') }}</view>
<view class="item" :id="'category-2-' + oneIndex"
:class="{ selected: categoryId == oneIndex }" @tap.stop="selectCategory(oneIndex)"
v-for="(one, oneIndex) in category.child_list" :key="oneIndex">
@@ -57,7 +97,7 @@
<view class="screen-category-popup" @tap.stop="$refs.screenCategoryPopup.close()">
<scroll-view scroll-y="true" class="screen-category"
:class="{ 'screen-category-4': value.template == 4 }">
<view class="title">全部</view>
<view class="title">{{ $lang('components-diy.diy-category-item.all') }}</view>
<view class="item" :class="{ selected: categoryId == oneIndex }"
@tap.stop="selectCategory(oneIndex)" v-for="(one, oneIndex) in category.child_list"
:key="oneIndex">
@@ -72,7 +112,7 @@
@scrolltolower="scrolltolower" @touchstart="touchstart" @touchend="touchend" @scroll="listenScroll">
<!--一级分类展示商品显示-->
<view class="category-title" style="font-size: 28rpx;padding-bottom: 0;">{{ category.category_name
<view class="category-title" :style="{ fontSize: (themeStyle && themeStyle.diy_category_item_goods_title_size) || '28rpx', paddingBottom: 0 }">{{ category.category_name
}}</view>
<!--一级-->
@@ -82,10 +122,10 @@
<block v-if="goodsList.length">
<view class="goods-item" v-for="(item, index) in goodsList" :key="index">
<view class="goods-img" @tap.stop="toDetail(item)">
<image :src="goodsImg(item.goods_image)" mode="widthFix" @error="imgError(index)" />
<view class="color-base-bg goods-tag" v-if="item.label_name">{{ item.label_name }}
</view>
<image :src="goodsImg(item.goods_image)" mode="widthFix" @error="imgError(index)" show-menu-by-longpress />
<view class="color-base-bg goods-tag" v-if="item.label_name">{{ item.label_name }}
</view>
</view>
<view class="info-wrap">
<view class="name-wrap" @tap.stop="toDetail(item)">
<view class="goods-name">{{ isEnEnv ? item.en_goods_name : item.goods_name }}</view>
@@ -93,33 +133,36 @@
<view class="price-wrap">
<view class="discount-price">
<block v-if="item.isinformation == 0">
<text class="unit price-style small">¥</text>
<text class="unit price-style small">{{ $lang('common.currencySymbol') }}</text>
<text class="price price-style large">{{
parseFloat(showPrice(item)).toFixed(2).split('.')[0] }}</text>
<text class="unit price-style small">.{{
parseFloat(showPrice(item)).toFixed(2).split('.')[1] }}</text>
</block>
<block v-else>
<text class="unit price-style small">{{ $lang('Make') ? $lang('Make') : '询底价' }}</text>
</block>
</view>
<view class="member-price-tag"
v-if="item.member_price && item.member_price == showPrice(item)">
<image :src="$util.img('public/uniapp/index/VIP.png')" mode="widthFix" />
<image :src="$util.img('public/uniapp/index/VIP.png')" mode="widthFix" show-menu-by-longpress />
</view>
<view class="member-price-tag" v-else-if="item.promotion_type == 1">
<image :src="$util.img('public/uniapp/index/discount.png')"
mode="widthFix" />
mode="widthFix" show-menu-by-longpress />
</view>
</view>
<view class="footer-wrap">
<view class="pro-info">
<view class="delete-price font-size-activity-tag color-tip price-font"
v-if="showMarketPrice(item)">
<text class="unit">¥</text>
<text class="unit">{{ $lang('common.currencySymbol') }}</text>
<text>{{ showMarketPrice(item) }}</text>
</view>
</view>
<view class="consult-now-btn-wrap" v-if="item.isinformation == 1">
<view class="consult-now-btn" @tap.stop="sendToAIChat(item)">
{{ $lang('components-diy.diy-category-item.consultNow') }}
</view>
</view>
<!-- <view class="right-wrap" v-if="value.template == 2 || value.template == 4">
<block v-if="item.is_virtual">
<view class="color-base-bg select-sku" @tap.stop="toDetail(item)">立即购买</view>
@@ -155,7 +198,7 @@
</view>
</block>
<view class="category-empty" v-else>
<image :src="$util.img('public/uniapp/category/empty.png')" mode="widthFix" />
<image :src="$util.img('public/uniapp/category/empty.png')" mode="widthFix" show-menu-by-longpress />
</view>
<!-- <view class="end-tips" ref="endTips" v-if="last && (categoryId == -1 || !category.child_list || (category.child_list && categoryId == category.child_list.length - 1))">已经到底了~</view>
<view class="end-tips" ref="endTips" v-else @tap.stop="switchCategory('next')">
@@ -174,52 +217,54 @@
:data-template="value.template">
<view class="goods-item" v-for="(item, index) in goodsList" :key="index">
<view class="goods-img" @tap.stop="toDetail(item)">
<image :src="goodsImg(item.goods_image)" mode="widthFix" @error="imgError(index)"
:lazy-load="true" />
<view class="color-base-bg goods-tag" v-if="item.label_name">{{ item.label_name }}</view>
</view>
<image :src="goodsImg(item.goods_image)" mode="widthFix" @error="imgError(index)"
:lazy-load="true" show-menu-by-longpress />
<view class="color-base-bg goods-tag" v-if="item.label_name">{{ item.label_name }}</view>
</view>
<view class="info-wrap">
<view class="name-wrap" @tap.stop="toDetail(item)">
<view class="goods-name">{{ isEnEnv ? item.en_goods_name : item.goods_name }}</view>
</view>
<view class="price-wrap">
<view class="discount-price">
<block v-if="item.isinformation == 0">
<text class="unit price-style small">¥</text>
<text class="price price-style large">{{
parseFloat(showPrice(item)).toFixed(2).split('.')[0] }}</text>
<text class="unit price-style small">.{{
parseFloat(showPrice(item)).toFixed(2).split('.')[1] }}</text>
</block>
<block v-else>
<text class="unit price-style small">{{ $lang('Make') ? $lang('Make') : '询底价' }}</text>
</block>
</view>
<block v-if="item.isinformation == 0">
<text class="unit price-style small">{{ $lang('common.currencySymbol') }}</text>
<text class="price price-style large">{{
parseFloat(showPrice(item)).toFixed(2).split('.')[0] }}</text>
<text class="unit price-style small">.{{
parseFloat(showPrice(item)).toFixed(2).split('.')[1] }}</text>
</block>
</view>
<view class="member-price-tag"
v-if="item.member_price && item.member_price == showPrice(item)">
<image :src="$util.img('public/uniapp/index/VIP.png')" mode="widthFix" />
<image :src="$util.img('public/uniapp/index/VIP.png')" mode="widthFix" show-menu-by-longpress />
</view>
<view class="member-price-tag" v-else-if="item.promotion_type == 1">
<image :src="$util.img('public/uniapp/index/discount.png')" mode="widthFix" />
<image :src="$util.img('public/uniapp/index/discount.png')" mode="widthFix" show-menu-by-longpress />
</view>
</view>
<view class="footer-wrap">
<view class="pro-info">
<view class="delete-price font-size-activity-tag color-tip price-font"
v-if="showMarketPrice(item)">
<text class="unit">¥</text>
<text class="unit">{{ $lang('common.currencySymbol') }}</text>
<text>{{ showMarketPrice(item) }}</text>
</view>
</view>
<view class="consult-now-btn-wrap" v-if="item.isinformation == 1">
<view class="consult-now-btn" @tap.stop="sendToAIChat(item)">
{{ $lang('components-diy.diy-category-item.consultNow') }}
</view>
</view>
<view class="right-wrap" v-if="value.template == 2">
<block v-if="item.is_virtual">
<view class="color-base-bg select-sku" @tap.stop="toDetail(item)">立即购买</view>
<view class="color-base-bg select-sku" @tap.stop="toDetail(item)">{{ $lang('components-diy.diy-category-item.buyNow') }}</view>
</block>
<block v-else>
<view v-if="item.goods_spec_format" class="color-base-bg select-sku"
@tap.stop="selectSku(item)">
<text>选规格</text>
<text>{{ $lang('components-diy.diy-category-item.selectSpecs') }}</text>
<text class="num-tag" v-if="item.num">{{ item.num }}</text>
</view>
<block v-else>
@@ -245,7 +290,7 @@
</block>
</view>
<view class="right-wrap" v-if="value.template == 3">
<view class="color-base-bg select-sku" @tap.stop="toDetail(item)">立即购买</view>
<view class="color-base-bg select-sku" @tap.stop="toDetail(item)">{{ $lang('components-diy.diy-category-item.buyNow') }}</view>
</view>
</view>
</view>
@@ -291,6 +336,14 @@ export default {
isList: {
type: Boolean,
default: false
},
lastSecondCategoryName: {
type: String,
default: ''
},
currentOneCategory: {
type: Object,
default: null
}
},
mixins: [DiyMinx],
@@ -311,13 +364,28 @@ export default {
scrollTop: 0,
loadType: '',
timeout: {},
cartEditRepeat: false
cartEditRepeat: false,
selectedSecondCategory: null,
secondCategoryGoodsList: []
};
},
created() {
this.type = this.value.template == 1 ? 'category' : 'goods';
this.type = this.value.template == 1 || this.value.template == 99 ? 'category' : 'goods';
if (this.index == this.select && this.pageIndex == 0) this.getGoodsList();
this.loadType = this.value.goodsLevel == 1 && this.value.loadType == 'all' ? 'all' : 'part';
if (this.value.template == 99 && this.index == this.select && this.category.child_list && this.category.child_list.length > 0) {
let targetCategory = null;
if (this.lastSecondCategoryName) {
targetCategory = this.category.child_list.find(item => item.category_name === this.lastSecondCategoryName);
}
if (!targetCategory) {
targetCategory = this.category.child_list[0];
}
this.selectedSecondCategory = targetCategory.category_id;
this.secondCategoryGoodsList = [];
// 用当前一级分类下同名二级分类的 id 查商品(而非全局按钮的 id)
this.refreshGoodsByCurrentCategory();
}
},
mounted() {
setTimeout(() => {
@@ -327,6 +395,18 @@ export default {
if (data) this.contentWrapHeight = data.height;
}).exec();
}, 1000);
if (this.value.template == 99 && this.category.child_list && this.category.child_list.length > 0) {
let targetCategory = null;
if (this.lastSecondCategoryName) {
targetCategory = this.category.child_list.find(item => item.category_name === this.lastSecondCategoryName);
}
if (!targetCategory) {
targetCategory = this.category.child_list[0];
}
this.selectedSecondCategory = targetCategory.category_id;
this.secondCategoryGoodsList = [];
this.getSecondCategoryGoods(targetCategory.category_id);
}
},
watch: {
oneCategorySelect: function () {
@@ -355,6 +435,27 @@ export default {
} else if (this.loadType == 'part') {
this.scrollTop = -1;
}
if (this.value.template == 99 && this.category.child_list && this.category.child_list.length > 0) {
let targetCategory = null;
if (this.lastSecondCategoryName) {
targetCategory = this.category.child_list.find(item => item.category_name === this.lastSecondCategoryName);
}
if (!targetCategory) {
targetCategory = this.category.child_list[0];
}
this.selectedSecondCategory = targetCategory.category_id;
this.secondCategoryGoodsList = [];
this.refreshGoodsByCurrentCategory();
}
},
// 切换一级分类时, 根据当前一级分类下同名二级分类重新加载商品
currentOneCategory: {
handler() {
if (this.value.template == 99) {
this.refreshGoodsByCurrentCategory();
}
},
deep: true
},
'globalStoreInfo.store_id': {
handler(nval, oval) {
@@ -512,13 +613,16 @@ export default {
if (_num > parseInt(data.stock)) {
this.$util.showToast({
title: '商品库存不足'
title: this.$lang('components-diy.diy-category-item.insufficientStock')
});
return;
}
if (data.is_limit && data.max_buy && _num > parseInt(data.max_buy)) {
this.$util.showToast({
title: `该商品每人限购${data.max_buy}${data.unit || '件'}`
title: this.$lang('components-diy.diy-category-item.purchaseLimit', {
maxBuy: data.max_buy,
unit: data.unit || this.$lang('components-diy.diy-category-item.pieceUnit')
})
});
return;
}
@@ -718,10 +822,95 @@ export default {
}
}
},
/**
* 跳转到商品详情
* @param {Object} item 商品信息
*/
sendToAIChat(item) {
this.$util.redirectTo('/pages_goods/detail', {
goods_id: item.goods_id
});
},
diyRedirectTo(link) {
if (!link) return;
this.$util.diyRedirectTo(JSON.parse(link));
},
/**
* 根据当前一级分类(currentOneCategory)下与选中按钮同名的二级分类, 加载对应商品
* 按钮是全局去重的(选中状态用全局 category_id), 但商品只显示当前一级分类下的
* 当前一级分类下若没有同名二级分类, 则商品清空(按钮保持选中)
*/
refreshGoodsByCurrentCategory() {
if (this.selectedSecondCategory == null) {
this.secondCategoryGoodsList = [];
return;
}
// 取当前选中按钮的名称
const cur = (this.category.child_list || []).find(c => c.category_id === this.selectedSecondCategory);
if (!cur) {
this.secondCategoryGoodsList = [];
return;
}
const one = this.currentOneCategory;
if (!one || !one.child_list || one.child_list.length === 0) {
this.secondCategoryGoodsList = [];
return;
}
const match = one.child_list.find(c => c.category_name === cur.category_name);
if (match) {
this.getSecondCategoryGoods(match.category_id);
} else {
// 当前一级分类下没有该二级分类, 商品清空(按钮仍保持选中)
this.secondCategoryGoodsList = [];
}
},
selectSecondCategory(category) {
if (this.selectedSecondCategory === category.category_id) {
this.selectedSecondCategory = null;
this.secondCategoryGoodsList = [];
} else {
this.selectedSecondCategory = category.category_id;
this.secondCategoryGoodsList = [];
this.$emit('saveSecondCategory', category.category_name);
// 用当前一级分类下同名 category_id 查商品
this.refreshGoodsByCurrentCategory();
}
},
getSecondCategoryGoods(categoryId) {
this.loading = true;
let order = '';
let sort = '';
if (this.value.sortWay) {
if (this.value.sortWay == 'default') {
order = '';
sort = '';
} else if (this.value.sortWay == 'sales') {
order = 'sales';
sort = 'desc';
} else if (this.value.sortWay == 'price') {
order = 'min_price';
sort = this.value.sortType == 'desc' ? 'desc' : 'asc';
}
}
this.$api.sendRequest({
url: '/api/goodssku/pageByCategory',
data: {
category_id: categoryId,
page: 1,
page_size: this.pageSize,
order: order,
sort: sort
},
success: res => {
this.loading = false;
if (res.code == 0 && res.data && res.data.list) {
this.secondCategoryGoodsList = res.data.list;
} else {
this.secondCategoryGoodsList = [];
}
}
});
},
//加载商品在购物车的总数量
loadGoodsCartNum(isRefresh = false) {
this.goodsList.forEach((item) => {
@@ -733,7 +922,7 @@ export default {
};
</script>
<style lang="scss">
<style lang="scss" scoped>
.small {
font-size: 28rpx !important;
}
@@ -750,7 +939,7 @@ export default {
.category-title {
padding: 20rpx 0;
font-size: 26rpx;
font-size: var(--diy-category-item-title-size, 26rpx);
// font-weight: bold;
color: #222;
position: relative;
@@ -828,7 +1017,7 @@ export default {
text-align: center;
line-height: 1;
font-size: 24rpx;
font-size: var(--diy-category-item-name-size, 24rpx);
}
}
}
@@ -847,132 +1036,163 @@ export default {
}
.goods-item {
display: flex;
flex-direction: column;
border-radius: $border-radius;
overflow: hidden;
background-color: #fff;
margin-bottom: 20rpx;
.goods-img {
position: relative;
overflow: hidden;
padding-top: 100%;
border-top-left-radius: $border-radius;
border-top-right-radius: $border-radius;
image {
width: 100%;
position: absolute !important;
top: 50%;
left: 0;
transform: translateY(-50%);
}
}
.goods-tag {
color: #fff;
line-height: 1;
padding: 8rpx 16rpx;
position: absolute;
border-bottom-right-radius: $border-radius;
top: 0;
left: 0;
font-size: $font-size-goods-tag;
}
.goods-tag-img {
position: absolute;
border-top-left-radius: $border-radius;
width: 80rpx;
height: 80rpx;
top: 0;
left: 0;
z-index: 5;
overflow: hidden;
image {
width: 100%;
height: 100%;
}
}
.info-wrap {
padding: 0 20rpx;
display: flex;
flex-direction: column;
flex: 1;
}
.goods-name {
font-size: $font-size-base;
line-height: 1.3;
margin-top: 20rpx;
white-space: nowrap;
border-radius: $border-radius;
overflow: hidden;
text-overflow: ellipsis;
}
background-color: #fff;
margin-bottom: 20rpx;
.lineheight-clear {
margin-top: 16rpx;
}
.discount-price {
display: inline-block;
font-weight: bold;
line-height: 1;
.unit {
margin-right: 6rpx;
color: var(--price-color);
.name-wrap {
display: var(--diy-category-item-name-wrap-display, block);
flex: var(--diy-category-item-name-wrap-flex, auto);
overflow: var(--diy-category-item-name-wrap-overflow, visible);
}
.price {
color: var(--price-color);
}
}
.goods-img {
position: relative;
overflow: hidden;
padding-top: 100%;
border-top-left-radius: $border-radius;
border-top-right-radius: $border-radius;
.pro-info {
display: flex;
margin-top: auto;
align-items: center;
.block-wrap {
flex: 1;
line-height: 1;
margin-right: 20rpx;
.sale {
font-size: $font-size-tag !important;
image {
width: 100%;
position: absolute !important;
top: 50%;
left: 0;
transform: translateY(-50%);
}
}
}
.delete-price {
// display: inline-block;
// margin-left: 6rpx;
// float: right;
.unit {
margin-right: 6rpx;
}
text {
.goods-tag {
color: #fff;
line-height: 1;
font-size: $font-size-tag !important;
padding: 8rpx 16rpx;
position: absolute;
border-bottom-right-radius: $border-radius;
top: 0;
left: 0;
font-size: var(--diy-category-item-goods-tag-size, 22rpx);
}
}
.member-price-tag {
display: inline-block;
width: 60rpx;
line-height: 1;
margin-left: 6rpx;
.goods-tag-img {
position: absolute;
border-top-left-radius: $border-radius;
width: 80rpx;
height: 80rpx;
top: 0;
left: 0;
z-index: 5;
overflow: hidden;
image {
width: 100%;
image {
width: 100%;
height: 100%;
}
}
.info-wrap {
padding: var(--diy-category-item-info-wrap-padding, 0 20rpx);
display: flex;
flex-direction: column;
flex: 1;
}
.goods-name {
font-size: var(--diy-category-item-goods-name-size, 28rpx);
line-height: var(--diy-category-item-goods-name-line-height, 1.3);
margin-top: var(--diy-category-item-goods-name-margin-top, 20rpx);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.lineheight-clear {
margin-top: 16rpx;
}
.price-wrap {
// 原 SCSS 完全没有 .price-wrap 样式定义(元素是 block 布局,初始值)
// 保留 5 个属性的主题化能力,但所有 fallback 都设为 initial value,
// 不改变原渲染。远端可覆写为 flex / baseline / wrap / space-between / 8rpx
display: var(--diy-category-item-price-wrap-display, block);
align-items: var(--diy-category-item-price-wrap-align-items, normal);
flex-wrap: var(--diy-category-item-price-wrap-flex-wrap, nowrap);
justify-content: var(--diy-category-item-price-wrap-justify-content, normal);
margin-top: var(--diy-category-item-price-wrap-margin-top, 0);
}
.discount-price {
display: inline-block;
font-weight: var(--diy-category-item-discount-price-weight, bold);
line-height: var(--diy-category-item-discount-price-line-height, 1);
.unit {
margin-right: 6rpx;
color: var(--price-color);
}
.price {
color: var(--price-color);
}
}
.pro-info {
display: flex;
margin-top: auto;
align-items: center;
.block-wrap {
flex: 1;
line-height: 1;
margin-right: 20rpx;
.sale {
font-size: $font-size-tag !important;
}
}
}
.delete-price {
// display: inline-block;
// margin-left: 6rpx;
// float: right;
.unit {
margin-right: 6rpx;
}
text {
line-height: var(--diy-category-item-delete-price-line-height, 1);
font-size: var(--diy-category-item-delete-price-size, $font-size-tag) !important;
}
}
.member-price-tag {
display: inline-block;
width: var(--diy-category-item-member-price-tag-width, 60rpx);
line-height: var(--diy-category-item-member-price-tag-line-height, 1);
margin-left: var(--diy-category-item-member-price-tag-margin-left, 6rpx);
image {
width: 100%;
}
}
.footer-wrap {
display: var(--diy-category-item-footer-wrap-display, flex);
justify-content: var(--diy-category-item-footer-wrap-justify-content, space-between);
align-items: var(--diy-category-item-footer-wrap-align-items, normal);
margin-top: var(--diy-category-item-footer-wrap-margin-top, 0);
}
.consult-now-btn-wrap {
display: var(--diy-category-item-consult-now-wrap-display, flex);
justify-content: var(--diy-category-item-consult-now-wrap-justify-content, flex-end);
margin-top: var(--diy-category-item-consult-now-wrap-margin-top, auto);
padding-top: var(--diy-category-item-consult-now-wrap-padding-top, 10rpx);
}
}
.sell-out {
position: absolute;
@@ -1092,8 +1312,8 @@ export default {
}
.goods-name {
font-size: $font-size-base;
line-height: 1.3;
font-size: var(--diy-category-item-goods-name-size, $font-size-base);
line-height: var(--diy-category-item-goods-name-line-height, 1.3);
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
@@ -1108,9 +1328,9 @@ export default {
.discount-price {
display: inline-block;
font-weight: bold;
line-height: 1;
margin-top: 16rpx;
font-weight: var(--diy-category-item-discount-price-weight, bold);
line-height: var(--diy-category-item-discount-price-line-height, 1);
margin-top: var(--diy-category-item-discount-price-margin-top, 16rpx);
color: var(--price-color);
.unit {
@@ -1120,10 +1340,10 @@ export default {
.pro-info {
display: flex;
margin-top: 16rpx;
margin-top: var(--diy-category-item-pro-info-margin-top, 16rpx);
.delete-price {
text-decoration: line-through;
text-decoration: var(--diy-category-item-delete-price-text-decoration, line-through);
flex: 1;
.unit {
@@ -1142,10 +1362,10 @@ export default {
.member-price-tag {
display: inline-block;
width: 60rpx;
line-height: 1;
margin-left: 6rpx;
height: 28rpx;
width: var(--diy-category-item-member-price-tag-width, 60rpx);
line-height: var(--diy-category-item-member-price-tag-line-height, 1);
margin-left: var(--diy-category-item-member-price-tag-margin-left, 6rpx);
height: var(--diy-category-item-member-price-tag-height, 28rpx);
image {
width: 100%;
@@ -1247,7 +1467,7 @@ export default {
.info-wrap {
width: 100%;
margin-top: 12rpx;
margin-top: var(--diy-category-item-info-wrap-margin-top, 12rpx);
}
.goods-img {
@@ -1384,4 +1604,180 @@ export default {
color: var(--main-color);
}
}
.consult-now-btn-wrap {
display: var(--diy-category-item-consult-now-wrap-display, flex);
justify-content: var(--diy-category-item-consult-now-wrap-justify-content, flex-end);
margin-top: var(--diy-category-item-consult-now-wrap-margin-top, auto);
padding-top: var(--diy-category-item-consult-now-wrap-padding-top, 10rpx);
}
.consult-now-btn {
// 兼容: 微信小程序 / 鸿蒙元服务 — 所有 var() 属性无问题
// 10 个属性都用 --diy-category-item-consult-now-* 独立 token,
// 便于后台单独调整任何一项(配色 / 尺寸 / 字重 / 对齐 / 显示模式)
background-color: var(--diy-category-item-consult-now-bg, #FF4646);
color: var(--diy-category-item-consult-now-text, #FFFFFF);
padding: var(--diy-category-item-consult-now-padding, 12rpx 30rpx);
border-radius: var(--diy-category-item-consult-now-radius, 40rpx);
font-size: var(--diy-category-item-consult-now-size, 26rpx);
font-weight: var(--diy-category-item-consult-now-weight, 500);
line-height: var(--diy-category-item-consult-now-line-height,1.2);
text-align: var(--diy-category-item-consult-now-text-align, center);
white-space: var(--diy-category-item-consult-now-white-space,nowrap);
display: var(--diy-category-item-consult-now-display, inline-block);
}
.font-size-activity-tag {
font-size: var(--diy-category-item-delete-price-size, $font-size-activity-tag) !important;
}
.color-tip {
color: var(--diy-category-item-color-tip-color, $color-tip) !important;
}
.price-font {
font-weight: var(--diy-category-item-price-font-weight, 500) !important;
}
// ===================== 模板99 商品分类样式 =====================
.second-category-btns {
display: flex;
flex-wrap: wrap;
padding: 20rpx 20rpx 10rpx;
background: #fff;
border-bottom: 1rpx solid #f0f0f0;
.second-category-btn {
padding: 14rpx 32rpx;
background: #f5f5f5;
color: #666;
border-radius: 40rpx;
font-size: 26rpx;
margin: 0 16rpx 16rpx 0;
max-width: 100%;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
&.selected {
background: #FF6B35;
color: #fff;
}
}
}
.category-goods-list {
padding: 20rpx;
background: #f5f5f5;
width: 100%;
box-sizing: border-box;
.goods-list {
margin: 0;
padding-top: 0;
display: flex;
.goods-item {
width: calc(50% - 10rpx);
background: #fff;
border-radius: 12rpx;
overflow: hidden;
margin-bottom: 20rpx;
display: flex;
flex-direction: column;
box-sizing: border-box;
.goods-img {
width: 100%;
height: 0;
padding-top: 100%;
position: relative;
overflow: hidden;
background: #fff;
border-top-left-radius: 12rpx;
border-top-right-radius: 12rpx;
image {
width: 100%;
height: 100%;
position: absolute !important;
top: 0;
left: 0;
transform: none;
}
.goods-tag {
position: absolute;
top: 10rpx;
left: 10rpx;
padding: 4rpx 12rpx;
color: #fff;
font-size: 22rpx;
border-radius: 6rpx;
background: #FF6B35;
z-index: 2;
}
}
.info-wrap {
flex: 1;
padding: 16rpx;
display: flex;
flex-direction: column;
}
.name-wrap {
.goods-name {
font-size: 26rpx;
color: #333;
-webkit-line-clamp: 2;
display: -webkit-box;
-webkit-box-orient: vertical;
overflow: hidden;
line-height: 1.4;
margin-top: 0;
white-space: normal;
text-overflow: clip;
}
}
.price-wrap {
margin-top: 10rpx;
display: flex;
align-items: baseline;
justify-content: space-between;
.discount-price {
color: #FF6B35;
font-size: 30rpx;
font-weight: bold;
.unit {
font-size: 22rpx;
}
}
}
}
}
}
.category-goods-empty {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 80rpx 0;
background: #f5f5f5;
width: 100%;
image {
width: 280rpx;
height: 252rpx;
}
.tips {
font-size: 26rpx;
color: #999;
margin-top: 20rpx;
}
}
</style>

View File

@@ -5,7 +5,7 @@
<!-- <block v-if="value.template == 4">
<view class="search-box" v-if="value.search" @tap.stop="$util.redirectTo('/pages_tool/goods/search')" :style="navbarInnerStyle">
<view class="search-content">
<input type="text" class="uni-input font-size-tag" maxlength="50" :placeholder="$lang('search')" confirm-type="search" @tap.stop="onClickSearch()" disabled="true" />
<input type="text" class="uni-input font-size-tag" maxlength="50" :placeholder="$lang('components-diy.diy-search.searchBtn')" confirm-type="search" @tap.stop="onClickSearch()" disabled="true" />
<text class="iconfont icon-sousuo3"></text>
</view>
</view>
@@ -16,7 +16,7 @@
<view class="search-box" v-if="value.search" @tap.stop="onClickSearch()"
:style="wxSearchHeight">
<view class="search-content">
<input type="text" class="uni-input" maxlength="50" :placeholder="$lang('search')"
<input type="text" class="uni-input" maxlength="50" :placeholder="$lang('components-diy.diy-search.searchBtn')"
confirm-type="search" @tap.stop="onClickSearch()"
disabled="true" />
<text class="iconfont icon-sousuo3"></text>
@@ -26,16 +26,18 @@
</view>
</block>
<!-- #endif -->
<!-- #ifdef H5 -->
<!-- #ifdef H5 || MP-HARMONY -->
<view class="search-box" v-if="value.search" @tap.stop="onClickSearch()">
<view class="search-content">
<input type="text" class="uni-input" maxlength="50" :placeholder="$lang('search')" confirm-type="search"
<input type="text" class="uni-input" maxlength="50" :placeholder="$lang('components-diy.diy-search.searchBtn')" confirm-type="search"
@tap.stop="onClickSearch()" disabled="true" />
<text class="iconfont icon-sousuo3"></text>
</view>
<view class="iconfont" :class="{ 'icon-apps': !isList, 'icon-list': isList }"
@tap.stop.prevent="changeListStyle()"></view>
</view>
<!-- #endif -->
<view class="template-four wx" v-if="value.template == 4">
<scroll-view scroll-x="true" class="template-four-wrap" :scroll-with-animation="true"
@@ -43,7 +45,7 @@
<view class="category-item" :id="'category-one-' + index" v-for="(item, index) in templateFourData"
:key="index" :class="{ select: oneCategorySelect == index }" @tap.stop="templateFourOneFn(index)">
<view class="image-warp" :class="[{ 'color-base-border': oneCategorySelect == index }]">
<image :src="$util.img(item.image)" mode="aspectFill" />
<image :src="$util.img(item.image)" mode="aspectFill" show-menu-by-longpress/>
</view>
<view :class="['text', { 'color-base-bg': oneCategorySelect == index }]">{{ item.category_name }}
</view>
@@ -51,8 +53,8 @@
</scroll-view>
<view class="category-item-all" @tap.stop="$refs.templateFourPopup.open()">
<view class="category-item-all-wrap">
<text class="text">展开</text>
<image class="img" :src="$util.img('/public/uniapp/category/unfold.png')" mode="aspectFill"></image>
<text class="text">{{ $lang('components-diy.diy-category.expand') }}</text>
<image class="img" :src="$util.img('/public/uniapp/category/unfold.png')" mode="aspectFill" show-menu-by-longpress></image>
</view>
</view>
<uni-popup type="top" ref="templateFourPopup" :top="uniPopupTop">
@@ -61,14 +63,14 @@
<view class="item" :class="{ selected: oneCategorySelect == index }"
@tap.stop="templateFourOneFn(index)" v-for="(item, index) in templateFourData" :key="index">
<view class="image-warp" :class="[{ 'color-base-border': oneCategorySelect == index }]">
<image :src="$util.img(item.image)" mode="aspectFill"></image>
<image :src="$util.img(item.image)" mode="aspectFill" show-menu-by-longpress></image>
</view>
<view :class="['text', { 'color-base-bg': oneCategorySelect == index }]">{{
item.category_name }}</view>
</view>
</scroll-view>
<view class="pack-up" @tap.stop="$refs.templateFourPopup.close()">
<text>点击收起</text>
<text>{{ $lang('components-diy.diy-category.clickToCollapse') }}</text>
<text class="iconfont icon-iconangledown-copy"></text>
</view>
</view>
@@ -90,19 +92,32 @@
</scroll-view>
<view class="right-flex-wrap">
<scroll-view scroll-y="true" class="content-wrap" v-if="value.template == 1 || loadType == 'all'"
<!-- 模板99 + 二级分类: 全局二级分类按钮(去重, 一直显示) + 商品列表 -->
<scroll-view scroll-y="true" class="content-wrap" v-if="value.template == 99 && template99Category"
:refresher-enabled="true" refresher-default-style="none"
:refresher-triggered="triggered" @refresherrefresh="onRefresh" @refresherrestore="onRestore">
<diy-category-item :category="template99Category" :value="value" ref="categoryItem" :index="0" :select="0"
:oneCategorySelect="oneCategorySelect" :isList="isList"
:currentOneCategory="categoryTree && categoryTree[select] ? categoryTree[select] : null"
:lastSecondCategoryName="lastSecondCategoryName"
@tologin="toLogin" @selectsku="selectSku($event, 0)" @addCart="addCartPoint"
@saveSecondCategory="saveSecondCategoryName"></diy-category-item>
</scroll-view>
<scroll-view scroll-y="true" class="content-wrap" v-else-if="value.template == 1 || value.template == 99 || loadType == 'all'"
ref="contentWrap" :scroll-into-view="categoryId" :scroll-with-animation="true"
@scroll="listenScroll" @touchstart="touchStart" :refresher-enabled="true"
refresher-default-style="none" :refresher-triggered="triggered" @refresherrefresh="onRefresh"
@refresherrestore="onRestore">
<view class="child-category" v-for="(item, index) in categoryTree" :key="index"
:id="'category-' + index">
:id="'category-' + index" :style="{ display: value.template == 99 && select != index ? 'none' : 'block' }">
<diy-category-item :category="item" :value="value" ref="categoryItem" :index="index"
:select="select" :oneCategorySelect="oneCategorySelect" :isList="isList"
:lastSecondCategoryName="value.template == 99 ? lastSecondCategoryName : ''"
@tologin="toLogin" @selectsku="selectSku($event, index)" @addCart="addCartPoint"
@loadfinish="getHeightArea"></diy-category-item>
@loadfinish="getHeightArea" @saveSecondCategory="saveSecondCategoryName"></diy-category-item>
</view>
<view class="end-tips" ref="endTips" :style="{ opacity: endTips }">已经到底了~</view>
<view class="end-tips" ref="endTips" :style="{ opacity: endTips }">{{ $lang('components-diy.diy-category.reachedBottom') }}</view>
</scroll-view>
<view class="content-wrap"
@@ -119,13 +134,13 @@
</view>
</block>
<view class="category-empty" v-else>
<image :src="$util.img('public/uniapp/category/empty.png')" mode="widthFix"></image>
<view class="tips">暂时没有分类哦!</view>
<image :src="$util.img('public/uniapp/category/empty.png')" mode="widthFix" show-menu-by-longpress></image>
<view class="tips">{{ $lang('components-diy.diy-category.noCategory') }}</view>
</view>
</view>
<view class="category-empty" v-else>
<image :src="$util.img('public/uniapp/category/empty.png')" mode="widthFix"></image>
<view class="tips">暂时没有分类哦!</view>
<image :src="$util.img('public/uniapp/category/empty.png')" mode="widthFix" show-menu-by-longpress></image>
<view class="tips">{{ $lang('components-diy.diy-category.noCategory') }}</view>
</view>
<!-- <view class="cart-box" v-if="(value.template == 2 || value.template == 4) && value.quickBuy && storeToken && categoryTree && categoryTree.length">
@@ -192,7 +207,9 @@ export default {
loadType: '',
templateFourData: [],
isList: false,
lang: uni.getStorageSync("lang")//en-us 英文
lang: uni.getStorageSync("lang"),
lastSecondCategoryName: '',
template99Category: null
};
},
created() {
@@ -301,9 +318,20 @@ export default {
},
/**
* 获取高度区间
*
* 鸿蒙 JSVM 在 mounted() 之前触发 onShow,导致 query 还是 undefined
* 加防御性检查,避免上线后第一次进入崩溃
*/
getHeightArea(index) {
let heightArea = [];
if (!query || typeof query.selectAll !== 'function') {
query = uni.createSelectorQuery && uni.createSelectorQuery().in(this);
}
if (!query || typeof query.selectAll !== 'function') {
// 极端兜底:鸿蒙下若 createSelectorQuery 不存在,跳过计算
this.heightArea = heightArea;
return;
}
query
.selectAll('.content-wrap .child-category')
.boundingClientRect(data => {
@@ -318,7 +346,7 @@ export default {
})
.exec();
this.heightArea = heightArea;
if (index != -1 && index < this.categoryTree.length - 1) this.$refs.categoryItem[index + 1].getGoodsList();
if (index != -1 && index < this.categoryTree.length - 1 && Array.isArray(this.$refs.categoryItem) && this.$refs.categoryItem[index + 1]) this.$refs.categoryItem[index + 1].getGoodsList();
},
/**
* 获取全部分类
@@ -348,10 +376,77 @@ export default {
return item;
});
}
// 模板99 + 二级分类: 全局查询所有有商品的二级分类(去重), 按钮一直显示
if (this.value.template == 99) {
this.loadGlobalSecondCategoryBtns();
}
}
}
});
},
/**
* 全局查询所有有商品的二级分类, 按名称去重, 汇总成虚拟分类供 template99 渲染按钮
* 只要任何商品属于该二级分类, 按钮就显示; 切换一级分类时按钮不变(一直显示)
* 新增的二级分类只要有商品也会自动包含
*/
loadGlobalSecondCategoryBtns() {
if (!this.categoryTree || !this.categoryTree.length) {
this.template99Category = { category_name: '', child_list: [] };
return;
}
// 收集所有二级分类(保留原始顺序, 不去重, 查询所有同名后再去重)
const allSecond = [];
this.categoryTree.forEach(one => {
if (one.child_list && one.child_list.length) {
one.child_list.forEach(two => {
allSecond.push(Object.assign({ _origIndex: allSecond.length }, two));
});
}
});
if (!allSecond.length) {
this.template99Category = { category_name: '', child_list: [] };
return;
}
let pending = allSecond.length;
const results = [];
const finishOne = () => {
pending--;
if (pending <= 0) {
results.sort((a, b) => a._origIndex - b._origIndex);
// 按名称去重, 同名只保留第一个有商品的(只要任一同名有商品就显示)
const deduped = [];
const seenNames = {};
results.forEach(item => {
if (!seenNames[item.category_name]) {
seenNames[item.category_name] = true;
deduped.push(item);
}
});
this.template99Category = {
category_name: '',
child_list: deduped
};
}
};
allSecond.forEach(two => {
this.$api.sendRequest({
url: '/api/goodssku/pageByCategory',
data: {
category_id: two.category_id,
page: 1,
page_size: 1
},
success: res => {
if (res && res.code == 0 && res.data && res.data.list && res.data.list.length > 0) {
results.push(two);
}
},
complete: () => {
finishOne();
}
});
});
},
/**
* 切换一级分类
* @param {Object} index
@@ -360,9 +455,11 @@ export default {
if (index >= this.categoryTree.length) return;
this.select = index;
this.categoryId = 'category-' + index;
// 阻止切换分类之后滚动事件也立即执行
this.scrollLock = true;
},
saveSecondCategoryName(name) {
this.lastSecondCategoryName = name;
},
touchStart() {
this.scrollLock = false;
},
@@ -380,10 +477,10 @@ export default {
break;
}
}
if (this.value.template != 1 && this.value.loadType == 'all' && this.heightArea[this.select][1] -
scrollTop - contentWrapHeight < 300) {
this.$refs.categoryItem[this.select].getGoodsList();
}
if (this.value.template != 1 && this.value.loadType == 'all' && this.heightArea[this.select][1] -
scrollTop - contentWrapHeight < 300) {
if (Array.isArray(this.$refs.categoryItem) && this.$refs.categoryItem[this.select]) this.$refs.categoryItem[this.select].getGoodsList();
}
}
},
onRefresh() {
@@ -409,7 +506,7 @@ export default {
success: res => {
if (res.code >= 0) {
let item = res.data;
item.unit = item.unit || '件';
item.unit = item.unit || this.$lang('components-diy.diy-category.pieceUnit');
if (item.sku_images) item.sku_images = item.sku_images.split(',');
else item.sku_images = [];
@@ -536,7 +633,7 @@ export default {
},
// 操作多规格商品弹框后,刷新商品数据
refreshData() {
this.$refs.categoryItem[this.select].loadGoodsCartNum(true);
if (Array.isArray(this.$refs.categoryItem) && this.$refs.categoryItem[this.select]) this.$refs.categoryItem[this.select].loadGoodsCartNum(true);
},
changeListStyle() {
this.isList = !this.isList;
@@ -609,7 +706,7 @@ export default {
white-space: break-word;
overflow: hidden;
text-align: center;
font-size: 10px;
font-size: var(--diy-category-tree-normal-size, 20rpx);
}
&.border-top {
@@ -626,7 +723,7 @@ export default {
view {
color: #333;
font-weight: bold;
font-size: $font-size-base;
font-size: var(--diy-category-tree-select-size, 28rpx);
}
&::before {
@@ -751,7 +848,11 @@ export default {
color: #333;
}
.money,
.money {
font-weight: bold;
color: var(--price-color);
}
.unit {
font-weight: bold;
color: var(--price-color);
@@ -1033,4 +1134,99 @@ export default {
border-bottom-right-radius: 8rpx;
}
}
// ===================== 模板99 商品分类样式 =====================
.category-template-99 {
.search-box {
padding: 20rpx 24rpx;
background: #fff;
border-bottom: 1rpx solid #f0f0f0;
.search-content {
height: 64rpx;
background-color: #f5f5f5;
border-radius: 40rpx;
input {
height: 64rpx;
line-height: 64rpx;
padding: 0 80rpx 0 30rpx;
background: #f5f5f5;
border-radius: 40rpx;
font-size: 26rpx;
color: #333;
}
.iconfont {
font-size: 32rpx;
color: #89899a;
width: 70rpx;
text-align: center;
}
}
> .iconfont {
font-size: 40rpx;
color: #666;
margin-left: 20rpx;
}
}
.content-box {
.tree-wrap {
width: 200rpx;
background-color: #f5f5f5;
}
.right-flex-wrap {
flex: 1;
width: 0;
background: #f5f5f5;
}
}
.tree-wrap .category-item {
padding: 30rpx 16rpx;
background-color: #f5f5f5;
view {
color: #333;
font-size: 26rpx;
line-height: 1.3;
}
&.select {
background: #fff;
view {
color: #FF6B35;
font-weight: bold;
font-size: 28rpx;
}
&::before {
content: ' ';
width: 6rpx;
height: 36rpx;
background: #FF6B35;
display: block;
position: absolute;
left: 0;
top: 50%;
transform: translateY(-50%);
border-radius: 0 6rpx 6rpx 0;
}
}
}
.content-wrap {
background: #f5f5f5;
padding: 0;
}
.child-category {
width: 100%;
box-sizing: border-box;
}
}
</style>

View File

@@ -256,7 +256,6 @@ export default {
try {
// 发送视频被点击播放事件
this.$emit('channel-video-click-play', item);
console.log('播放视频:', item);
// #ifdef MP-WEIXIN
// 在微信小程序环境中调用视频播放接口
@@ -289,7 +288,6 @@ export default {
*/
imgError(index) {
// 图片加载失败的处理逻辑
console.log('图片加载失败:', index);
// 为失败的图片设置默认图片
const item = this.value.list[index];
if (item) {
@@ -306,7 +304,6 @@ export default {
addMouseDragScroll() {
// 只在Web环境中添加
// #ifndef MP
console.log('addMouseDragScroll called');
let isDragging = false;
let startX = 0;
@@ -329,11 +326,9 @@ export default {
const handleMouseDown = (e) => {
// 检查是否点击在组件内
if (this.$el.contains(e.target)) {
console.log('mousedown event in component:', e);
// 查找可滚动元素
currentScrollElement = findScrollableParent(e.target);
if (currentScrollElement) {
console.log('Found scrollable element:', currentScrollElement);
isDragging = true;
startX = e.pageX;
startScrollLeft = currentScrollElement.scrollLeft;
@@ -345,17 +340,14 @@ export default {
// 鼠标移动事件
const handleMouseMove = (e) => {
if (!isDragging || !currentScrollElement) return;
console.log('mousemove event:', e);
e.preventDefault();
const dx = e.pageX - startX;
currentScrollElement.scrollLeft = startScrollLeft - dx;
console.log('scrollLeft:', currentScrollElement.scrollLeft);
};
// 鼠标释放事件
const handleMouseUp = () => {
if (isDragging && currentScrollElement) {
console.log('mouseup event');
currentScrollElement.style.cursor = 'grab';
}
isDragging = false;
@@ -368,21 +360,17 @@ export default {
document.addEventListener('mouseup', handleMouseUp);
document.addEventListener('mouseleave', handleMouseUp);
console.log('Global mouse event listeners added');
// 组件销毁时移除事件监听器
this.$once('hook:beforeDestroy', () => {
document.removeEventListener('mousedown', handleMouseDown);
document.removeEventListener('mousemove', handleMouseMove);
document.removeEventListener('mouseup', handleMouseUp);
document.removeEventListener('mouseleave', handleMouseUp);
console.log('Global mouse event listeners removed');
});
// 为所有.channel-nav元素添加必要的样式
setTimeout(() => {
const channelNavs = document.querySelectorAll('.channel-nav');
console.log('Found channel-nav elements:', channelNavs.length);
channelNavs.forEach(element => {
element.style.overflowX = 'auto';
element.style.overflowY = 'hidden';
@@ -391,11 +379,9 @@ export default {
element.style.maxWidth = '100%';
element.style.cursor = 'grab';
element.style.userSelect = 'none'; // 防止文本选择
console.log('Added styles to channel-nav:', element);
});
}, 100); // 延迟执行,确保DOM已完全渲染
console.log('Mouse drag scroll setup completed');
// #endif
}
}

View File

@@ -14,30 +14,30 @@
</view>
<view class="video-info">
<!-- 视频标题,支持多行显示控制 -->
<view class="video-title" :style="{ '--title-line-clamp': titleLineClamp }">{{ value.videoTitle }}
<view class="video-title" :style="[{ '--title-line-clamp': titleLineClamp }]">{{ value.videoTitle }}
</view>
<!-- 视频统计信息 -->
<view class="video-stats" v-if="showViewCount && value.showViewCount">{{ value.viewCount }}次观看</view>
<view class="video-stats" v-if="showViewCount && value.showViewCount">{{ $lang('components-diy.diy-channel-video.viewCountSuffix', { count: value.viewCount }) }}</view>
</view>
</view>
<!-- 跳转式视频播放 -->
<view v-else @tap.stop="playVideo" class="video-container">
<view class="video-cover-wrap" :style="[coverStyle]">
<image class="video-cover" :src="$util.img(value.coverUrl)" mode="aspectFill"></image>
<image class="video-cover" :src="$util.img(value.coverUrl)" mode="aspectFill" show-menu-by-longpress></image>
<view class="channel-play-btn" v-if="showPlayBtn" :style="[playBtnStyle]">
<view class="play-icon-css"></view>
</view>
<view class="video-stats-overlay" v-if="showViewCount && value.showViewCount">
{{ value.viewCount }}次观看
{{ $lang('components-diy.diy-channel-video.viewCountSuffix', { count: value.viewCount }) }}
</view>
</view>
<view class="video-info">
<!-- 视频标题,支持多行显示控制 -->
<view class="video-title" :style="{ '--title-line-clamp': titleLineClamp }">{{ value.videoTitle }}
<view class="video-title" :style="[{ '--title-line-clamp': titleLineClamp }]">{{ value.videoTitle }}
</view>
<!-- 视频统计信息,非列表模式下显示 -->
<view class="video-stats" v-if="showViewCount && value.showViewCount && !listMode">{{ value.viewCount }}次观看</view>
<view class="video-stats" v-if="showViewCount && value.showViewCount && !listMode">{{ $lang('components-diy.diy-channel-video.viewCountSuffix', { count: value.viewCount }) }}</view>
</view>
</view>
</view>
@@ -139,7 +139,6 @@ export default {
const enableEmbedMode = Boolean(this.value?.embedMode)
&& Boolean(this.value?.feedToken)
&& wechatChannelUtil.isEmbedModeSupported();
console.log('enableEmbedMode', enableEmbedMode);
return enableEmbedMode;
// #endif
return false

View File

@@ -26,16 +26,16 @@
</view>
<view class="coupon-num" :style="{ color: value.moneyColor }" v-else>
<text class="coupon-size">{{ item.discount | moneyConduct }}</text>
<text class="font-size-tag coupon-sign">折</text>
<text class="font-size-tag coupon-sign">{{ $lang('components-diy.diy-coupon.discount') }}</text>
</view>
<view class="coupon-type font-size-tag" :style="{ color: value.limitColor }">
{{ item.at_least > 0 ? '满' + Number(item.at_least) + '元可用' : '无门槛优惠券' }}
{{ item.at_least > 0 ? $lang('components-diy.diy-coupon.minSpendAvailable', { amount: Number(item.at_least) }) : $lang('components-diy.diy-coupon.noThresholdCoupon') }}
</view>
</view>
<view class="coupon-get" :style="couponBtnStyle" v-if="item.useState == 0">
{{ value.btnStyle.text }}
</view>
<view class="coupon-get" :style="couponBtnStyle" v-if="parseInt(item.useState)">去使用</view>
<view class="coupon-get" :style="couponBtnStyle" v-if="parseInt(item.useState)">{{ $lang('components-diy.diy-coupon.goUse') }}</view>
</view>
</swiper-item>
@@ -61,16 +61,16 @@
</view>
<view class="coupon-num" :style="{ color: value.moneyColor }" v-else>
<text class="coupon-size">{{ item.discount | moneyConduct }}</text>
<text class="font-size-tag coupon-sign">折</text>
<text class="font-size-tag coupon-sign">{{ $lang('components-diy.diy-coupon.discount') }}</text>
</view>
<view class="coupon-type font-size-tag" :style="{ color: value.limitColor }">
{{ item.at_least > 0 ? '满' + Number(item.at_least) + '元可用' : '无门槛优惠券' }}
{{ item.at_least > 0 ? $lang('components-diy.diy-coupon.minSpendAvailable', { amount: Number(item.at_least) }) : $lang('components-diy.diy-coupon.noThresholdCoupon') }}
</view>
</view>
<view class="coupon-get" :style="couponBtnStyle" v-if="item.useState == 0">
{{ value.btnStyle.text || '领取' }}
{{ value.btnStyle.text || $lang('components-diy.diy-coupon.claim') }}
</view>
<view class="coupon-get use" :style="couponBtnStyle" v-if="parseInt(item.useState)">去使用
<view class="coupon-get use" :style="couponBtnStyle" v-if="parseInt(item.useState)">{{ $lang('components-diy.diy-coupon.goUse') }}
</view>
</view>
</swiper-item>
@@ -95,20 +95,19 @@
</view>
<view class="coupon-num" :style="{ color: value.moneyColor }" v-else>
<text class="coupon-size">{{ item.discount | moneyConduct }}</text>
<text class="font-size-tag coupon-sign">折</text>
<text class="font-size-tag coupon-sign">{{ $lang('components-diy.diy-coupon.discount') }}</text>
</view>
<view class="coupon-type font-size-tag">
<text :style="{ color: value.limitColor }">{{ item.at_least > 0 ? '满' +
Number(item.at_least) + '元可用' : '无门槛优惠券' }}</text>
<view class="item-text" v-if="item.goods_type == 1">所有商品可用</view>
<view class="item-text" v-else-if="item.goods_type == 2">指定商品可用</view>
<view class="item-text" v-else-if="item.goods_type == 3">指定商品不可用</view>
<text :style="{ color: value.limitColor }">{{ item.at_least > 0 ? $lang('components-diy.diy-coupon.minSpendAvailable', { amount: Number(item.at_least) }) : $lang('components-diy.diy-coupon.noThresholdCoupon') }}</text>
<view class="item-text" v-if="item.goods_type == 1">{{ $lang('components-diy.diy-coupon.allProductsAvailable') }}</view>
<view class="item-text" v-else-if="item.goods_type == 2">{{ $lang('components-diy.diy-coupon.specifiedProductsAvailable') }}</view>
<view class="item-text" v-else-if="item.goods_type == 3">{{ $lang('components-diy.diy-coupon.specifiedProductsUnavailable') }}</view>
</view>
<view class="coupon-get" :style="couponBtnStyle" v-if="item.useState == 0">
{{ value.btnStyle.text || '领取' }}
{{ value.btnStyle.text || $lang('components-diy.diy-coupon.claim') }}
</view>
<view class="coupon-get" :style="couponBtnStyle" v-if="parseInt(item.useState)">去使用</view>
<view class="coupon-get" :style="couponBtnStyle" v-if="parseInt(item.useState)">{{ $lang('components-diy.diy-coupon.goUse') }}</view>
</view>
</swiper-item>
</swiper>
@@ -133,16 +132,16 @@
</view>
<view class="coupon-num" :style="{ color: value.moneyColor }" v-else>
<text class="coupon-size">{{ item.discount | moneyConduct }}</text>
<text class="font-size-tag coupon-sign">折</text>
<text class="font-size-tag coupon-sign">{{ $lang('components-diy.diy-coupon.discount') }}</text>
</view>
<view class="coupon-type font-size-tag" :style="{ color: value.limitColor }">
{{ item.at_least > 0 ? '满' + Number(item.at_least) + '元可用' : '无门槛优惠券' }}
{{ item.at_least > 0 ? $lang('components-diy.diy-coupon.minSpendAvailable', { amount: Number(item.at_least) }) : $lang('components-diy.diy-coupon.noThresholdCoupon') }}
</view>
</view>
<view class="coupon-get" :style="couponBtnStyle" v-if="item.useState == 0">
{{ value.btnStyle.text || '立即使用' }}
{{ value.btnStyle.text || $lang('components-diy.diy-coupon.useNow') }}
</view>
<view class="coupon-get" :style="couponBtnStyle" v-if="parseInt(item.useState)">去使用</view>
<view class="coupon-get" :style="couponBtnStyle" v-if="parseInt(item.useState)">{{ $lang('components-diy.diy-coupon.goUse') }}</view>
</view>
</swiper-item>
</swiper>
@@ -160,11 +159,11 @@
<view class="coupon-num" v-if="item.discount == '0.00'"
:style="{ color: value.moneyColor }">
<text class="coupon-size">{{ item.money | moneyConduct }}</text>
<text class="font-size-tag coupon-sign">元</text>
<text class="font-size-tag coupon-sign">{{ $lang('components-diy.diy-coupon.yuan') }}</text>
</view>
<view class="coupon-num" v-else :style="{ color: value.moneyColor }">
<text class="coupon-size">{{ item.discount | moneyConduct }}</text>
<text class="font-size-tag coupon-sign">折</text>
<text class="font-size-tag coupon-sign">{{ $lang('components-diy.diy-coupon.discount') }}</text>
</view>
</view>
<view class="coupon-line"></view>
@@ -173,14 +172,14 @@
<view class="coupon-name" :style="{ color: value.nameColor }">{{
item.coupon_name }}</view>
<text class="coupon-least" :style="{ color: value.limitColor }"
v-if="item.at_least > 0">满{{ Number(item.at_least) }}元可用</text>
v-if="item.at_least > 0">{{ $lang('components-diy.diy-coupon.minSpendAvailable', { amount: Number(item.at_least) }) }}</text>
<text class="coupon-least" :style="{ color: value.limitColor }"
v-else>无门槛优惠券</text>
v-else>{{ $lang('components-diy.diy-coupon.noThresholdCoupon') }}</text>
</view>
<view class="coupon-get" :style="couponBtnStyle" v-if="item.useState == 0">{{
value.btnStyle.text || '立即领取' }}</view>
value.btnStyle.text || $lang('components-diy.diy-coupon.claimNow') }}</view>
<view class="coupon-get" :style="couponBtnStyle" v-if="parseInt(item.useState)">
去使用</view>
{{ $lang('components-diy.diy-coupon.goUse') }}</view>
</view>
</view>
</view>
@@ -204,9 +203,9 @@
<view class="price-wrap">
<text class="price" :style="{ color: value.moneyColor }">{{ (item.discount == '0.00'
? item.money : item.discount) | moneyConduct }}</text>
<text class="unit">{{ item.discount == '0.00' ? '元' : '折' }}</text>
<text class="unit">{{ item.discount == '0.00' ? $lang('components-diy.diy-coupon.yuan') : $lang('components-diy.diy-coupon.discount') }}</text>
</view>
<text class="text">优惠券</text>
<text class="text">{{ $lang('components-diy.diy-coupon.coupon') }}</text>
</view>
<text class="btn" v-if="item.useState == 0" :style="{
color: value.btnStyle.textColor,
@@ -222,11 +221,11 @@
borderTopLeftRadius: value.btnStyle.aroundRadius * 2 + 'rpx',
borderBottomLeftRadius: value.btnStyle.aroundRadius * 2 + 'rpx'
}">
<text class="btn-content">去使用</text>
<text class="btn-content">{{ $lang('components-diy.diy-coupon.goUse') }}</text>
</text>
<text class="limit" :style="{ color: value.limitColor }"
v-if="parseFloat(item.at_least) > 0">满{{ item.at_least | moneyConduct }}元使用</text>
<text class="limit" :style="{ color: value.limitColor }" v-else>无门槛使用</text>
v-if="parseFloat(item.at_least) > 0">{{ $lang('components-diy.diy-coupon.minSpendUse', { amount: item.at_least | moneyConduct }) }}</text>
<text class="limit" :style="{ color: value.limitColor }" v-else>{{ $lang('components-diy.diy-coupon.noThresholdUse') }}</text>
</view>
<div v-if="computedCouponList.length <= 2" @tap.stop="$util.redirectTo('/pages_goods/category')"
@@ -238,9 +237,9 @@
}">
<div class="coupon-content" :style="{ color: value.moneyColor }">
<span class="price">+</span>
<span class="text">暂无优惠券</span>
<span class="text">{{ $lang('components-diy.diy-coupon.noCoupons') }}</span>
</div>
<span class="limit" :style="{ color: value.limitColor }">去逛逛</span>
<span class="limit" :style="{ color: value.limitColor }">{{ $lang('components-diy.diy-coupon.goBrowse') }}</span>
</div>
</swiper-item>
</swiper>
@@ -257,25 +256,24 @@
<view class="coupon-num" v-if="item.discount == '0.00'"
:style="{ color: value.moneyColor }">
<text class="coupon-size">{{ item.money | moneyConduct }}</text>
<text class="font-size-tag coupon-sign">元</text>
<text class="font-size-tag coupon-sign">{{ $lang('components-diy.diy-coupon.yuan') }}</text>
</view>
<view class="coupon-num" v-else :style="{ color: value.moneyColor }">
<text class="coupon-size">{{ item.discount | moneyConduct }}</text>
<text class="font-size-tag coupon-sign">折</text>
<text class="font-size-tag coupon-sign">{{ $lang('components-diy.diy-coupon.discount') }}</text>
</view>
</view>
<view class="coupon-type">
<text class="coupon-name" :style="{ color: value.limitColor }"
v-if="item.at_least > 0">满{{ Number(item.at_least) }}元可用</text>
<text class="coupon-name" :style="{ color: value.limitColor }" v-else>无门槛优惠券</text>
<view class="coupon-least" :style="{ color: value.limitColor }">有效期至{{
$util.timeStampTurnTime(item.end_time, 'yearmonthday') }}</view>
v-if="item.at_least > 0">{{ $lang('components-diy.diy-coupon.minSpendAvailable', { amount: Number(item.at_least) }) }}</text>
<text class="coupon-name" :style="{ color: value.limitColor }" v-else>{{ $lang('components-diy.diy-coupon.noThresholdCoupon') }}</text>
<view class="coupon-least" :style="{ color: value.limitColor }">{{ $lang('components-diy.diy-coupon.validUntil', { date: $util.timeStampTurnTime(item.end_time, 'yearmonthday') }) }}</view>
</view>
<view class="coupon-line"></view>
<view class="coupon-get" :style="couponBtnStyle" v-if="item.useState == 0">
{{ value.btnStyle.text || '立即领取' }}
{{ value.btnStyle.text || $lang('components-diy.diy-coupon.claimNow') }}
</view>
<view class="coupon-get" :style="couponBtnStyle" v-if="parseInt(item.useState)">去使用
<view class="coupon-get" :style="couponBtnStyle" v-if="parseInt(item.useState)">{{ $lang('components-diy.diy-coupon.goUse') }}
</view>
</view>
</view>
@@ -404,7 +402,7 @@ export default {
couponTap(item, index) {
if (item.count == item.lead_count) {
this.$util.showToast({
title: '该优惠券已抢光'
title: this.$lang('components-diy.diy-coupon.couponSoldOut')
});
return;
}
@@ -427,7 +425,7 @@ export default {
var data = res.data;
let msg = res.message;
if (res.code == 0) {
msg = '领取成功';
msg = this.$lang('components-diy.diy-coupon.claimSuccess');
if (res.data.is_exist == 1) {
for (let i = 0; i < that.couponList.length; i++) {
if (that.couponList[i].coupon_type_id == item.coupon_type_id) {

View File

@@ -91,7 +91,6 @@ export default {
// 页面跳转
redirectTo(item) {
if (!item.wap_url || this.$util.getCurrRoute() != this.$util.MEMBER_PAGE_URL || this.storeToken) {
console.log(item);
this.$util.diyRedirectTo(item);
} else {
this.$refs.login.open(item.wap_url);

View File

@@ -5,7 +5,7 @@
:class="[value.ornament.type]" :style="goodsItemCss">
<view class="goods-img" :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }">
<image :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }"
:src="$util.img(item.goods_image, { size: 'mid' })" mode="widthFix" @error="imgError(index)" />
:src="$util.img(item.goods_image, { size: 'mid' })" mode="widthFix" @error="imgError(index)" show-menu-by-longpress/>
</view>
<view class="info-wrap"
v-if="value.goodsNameStyle.control || value.priceStyle.mainControl || value.priceStyle.lineControl || value.btnStyle.control">
@@ -20,7 +20,7 @@
<view class="discount-price">
<view class="price-wrap" v-if="value.priceStyle.mainControl">
<text class="unit price-style small"
:style="{ color: value.theme == 'diy' ? value.priceStyle.mainColor : '' }">赚 ¥</text>
:style="{ color: value.theme == 'diy' ? value.priceStyle.mainColor : '' }">{{ $lang('components-diy.diy-fenxiao-goods-list.earnPrefix') }}</text>
<text class="price price-style large"
:style="{ color: value.theme == 'diy' ? value.priceStyle.mainColor : '' }">{{
item.commission_money.split('.')[0] }}</text>
@@ -33,14 +33,14 @@
color: value.btnStyle.theme == 'diy' ? value.btnStyle.textColor : '',
borderRadius: value.btnStyle.aroundRadius * 2 + 'rpx'
}" @tap.stop="followGoods(item, index)">
关注
{{ $lang('components-diy.diy-fenxiao-goods-list.follow') }}
</view>
<view class="sale-btn" v-if="value.btnStyle.control && item.is_collect == 1" :style="{
background: value.btnStyle.theme == 'diy' ? 'linear-gradient(to right,' + value.btnStyle.bgColorStart + ',' + value.btnStyle.bgColorEnd + ')' : '',
color: value.btnStyle.theme == 'diy' ? value.btnStyle.textColor : '',
borderRadius: value.btnStyle.aroundRadius * 2 + 'rpx'
}" @tap.stop="delFollowTip(item, index)">
取消关注
{{ $lang('components-diy.diy-fenxiao-goods-list.unfollow') }}
</view>
</view>
<view class="delete-price" v-if="value.priceStyle.lineControl"
@@ -138,7 +138,7 @@ export default {
},
success: res => {
if (res.code >= 0) {
this.$util.showToast({ title: '关注成功' });
this.$util.showToast({ title: this.$lang('components-diy.diy-fenxiao-goods-list.followSuccess') });
this.list[index].is_collect = 1;
this.list[index].collect_id = res.data;
}
@@ -149,8 +149,8 @@ export default {
//取消关注
delFollowTip(e, index) {
uni.showModal({
title: '提示',
content: '确认取消关注该商品吗',
title: this.$lang('components-diy.diy-fenxiao-goods-list.tip'),
content: this.$lang('components-diy.diy-fenxiao-goods-list.confirmUnfollow'),
success: res => {
if (res.confirm) {
this.delFollow(e.collect_id, index);
@@ -167,7 +167,7 @@ export default {
success: res => {
let msg = '';
if (res.code == 0) {
msg = '取消成功';
msg = this.$lang('components-diy.diy-fenxiao-goods-list.cancelSuccess');
} else {
msg = res.message;
}
@@ -337,7 +337,7 @@ export default {
width: calc(50% - 10rpx);
&:nth-child(2n + 2) {
width: calc(50% - 11rpx);
width: calc(50% - 10rpx);
margin-right: 0;
}

View File

@@ -6,7 +6,7 @@
<view class="button-box" @tap.stop="$util.diyRedirectTo(item.link)"
:style="{ width: value.imageSize + 'px', height: value.imageSize + 'px', fontSize: value.imageSize + 'px' }">
<image v-if="!item.iconType || item.iconType == 'img'" :src="$util.img(item.imageUrl)" mode="aspectFit"
:show-menu-by-longpress="true" />
show-menu-by-longpress />
<diy-icon v-else-if="item.iconType && item.iconType == 'icon'" :icon="item.icon"
:value="item.style ? item.style : null"></diy-icon>
</view>

View File

@@ -1,103 +1,316 @@
<template>
<view data-component-name="diy-form" class="diy-from" :style="style">
<view class="fui-cell-group">
<view class="fui-cell ">
<view class="fui-cell-label ">您的姓名</view>
<view class="fui-cell-info">
<input v-model="Form.realname" class="fui-input" placeholder="请输入您的姓名" value=""></input>
</view>
</view>
<view class="fui-cell ">
<view class="fui-cell-label">手机号码</view>
<view class="fui-cell-info">
<input v-model="Form.mobile" class="fui-input" maxlength="11" placeholder="请输入您的手机号"
type="number"></input>
</view>
</view>
<view class="fui-cell ">
<view class="fui-cell-label">您的邮箱</view>
<view class="fui-cell-info">
<input v-model="Form.mailbox" class="fui-input" placeholder="请输入您的邮箱" type="text"></input>
</view>
</view>
<view class="fui-cell">
<view class="fui-cell-label">所在城市</view>
<view class="fui-cell-info">
<input v-model="Form.citys" class="fui-input" placeholder="请输入您的所在地" value=""></input>
</view>
</view>
<view class="fui-cell">
<view class="fui-cell-label">备注</view>
<view class="fui-cell-info">
<input v-model="Form.remark" class="fui-input" placeholder="请输入备注" value=""></input>
</view>
</view>
<view data-component-name="diy-form" class="diy-from" :style="diyFormStyle">
<!-- Banner -->
<view v-if="value.show_banner && value.form_banner" class="form-banner" :style="bannerStyle">
<image :src="$util.img(value.form_banner)" mode="widthFix" class="banner-img" />
</view>
<!-- 提示语 -->
<view v-if="value.show_tip && value.form_tip" class="form-tip" :style="tipStyle">{{ value.form_tip }}</view>
<!-- 表单组件 -->
<ns-newform
:data="formComponents"
:customAttr="value"
:mode="mergedFormConfig.formLayout || 'horizontal'"
:formConfig="mergedFormConfig"
ref="nsNewform"
></ns-newform>
<!-- 提交按钮(外层 = form-bg + form-padding-x;按钮 = submit-bg + submit-color + input-height + input-radius)。
showSubmit=false 时由父级页面渲染自己的提交按钮并通过 ref 调用本组件的 verify()/getFormData()。 -->
<view v-if="showSubmit" class="form-submit-wrap" :style="submitWrapStyle">
<view @click.stop="submitForm" class="form-submit" :style="submitStyle">{{ submitText }}</view>
</view>
<view @tap.stop="submitform" class="fui-btn btn-danger block mtop">提交信息</view>
</view>
</template>
<script>
// 自定义表单
import DiyMinx from './minx.js'
import NsNewform from '@/components/ns-newform/ns-newform.vue'
export default {
name: 'diy-from',
components: { NsNewform },
props: {
value: {
type: Object
},
// 数据源模式:
// 'diy'(默认):value.formComponents 是 [{ type, value }],组件内部转换为 ns-newform 期望的 [{ controller, value, val }]
// 'raw' :value.jsonData / value.json_data 已经是 ns-newform 期望的格式,直接透传给 ns-newform
// 用途:让 formdata 等"已是 ns-newform 格式"的页面也能复用本组件的 banner/tip/样式系统
dataMode: {
type: String,
default: 'diy',
validator: (v) => ['diy', 'raw'].includes(v)
},
// 是否渲染内置提交按钮。false 时由父级调用 ref 上的 verify()/getFormData() 自行实现提交
showSubmit: {
type: Boolean,
default: true
}
},
mixins: [DiyMinx],
data() {
return {
loading: true,
markers: [],
Form: {
realname: '',
mobile: '',
mailbox: '',
citys: '',
remark: '',
}
formComponents: [] // 转换后的表单组件
};
},
created() {
this.initForm();
},
watch: {
// 组件刷新监听
componentRefresh: function (nval) {
// this.getDataList();
'value': {
deep: true,
handler() {
// raw 模式:formData 由父级透传,跳过重跑 initForm(避免每次父组件 re-render 触发 ns-newform 的深拷贝 initFormData)
if (this.dataMode === 'raw') return;
this.initForm();
}
}
},
computed: {
markerst() {
return [{
id: 1,
latitude: this.value.list[0].lat,
longitude: this.value.list[0].lng
}]
},
style() {
var css = '';
css += 'background-color:' + this.value.contentBgColor + ';';
if (this.value.elementAngle == 'round') {
if (this.value.elementAngle === 'round') {
css += 'border-top-left-radius:' + this.value.topElementAroundRadius * 2 + 'rpx;';
css += 'border-top-right-radius:' + this.value.topElementAroundRadius * 2 + 'rpx;';
css += 'border-bottom-left-radius:' + this.value.bottomElementAroundRadius * 2 + 'rpx;';
css += 'border-bottom-right-radius:' + this.value.bottomElementAroundRadius * 2 + 'rpx;';
}
return css;
},
// 兼容旧 style 别名(部分页面用 :style="style" 引用)
diyFormStyle() {
return this.style;
},
// Banner 容器左右内边距(与后端 .form-preview-banner padding-x 对齐)
bannerStyle() {
return this.$util.objToStyle({
padding: `0 ${this._num(this.mergedFormConfig && this.mergedFormConfig.bannerPaddingX, 0)}rpx`
});
},
// 提示语样式:padding-x、font-size、color、bg-color、border-bottom(与后端 .form-preview-tip 对齐)
tipStyle() {
const cfg = this.mergedFormConfig || {};
const style = {
padding: `${this._num(cfg.rowPaddingY, 4)}rpx ${this._num(cfg.tipPaddingX, 14)}rpx`,
'font-size': `${this._num(cfg.tipFontSize, 32)}rpx`,
'color': cfg.tipColor || '#000000',
'background-color': cfg.tipBgColor || 'transparent'
};
// 仅在配置了 tipBorderColor 时添加底线,避免 transparent 占位仍增加 2rpx 高度
if (cfg.tipBorderColor) {
style['border-bottom'] = `2rpx solid ${cfg.tipBorderColor}`;
}
return this.$util.objToStyle(style);
},
// 提交按钮外层:与后端 .form-preview-submit 对齐(margin-top + padding: row-padding-y form-padding-x;background: form-bg-color)
submitWrapStyle() {
const cfg = this.mergedFormConfig || {};
return this.$util.objToStyle({
marginTop: `${this._num(cfg.submitMarginTop, 0)}rpx`,
padding: `${this._num(cfg.rowPaddingY, 4)}rpx ${this._num(cfg.formPaddingX, 14)}rpx`,
'background-color': cfg.formBgColor || '#ffffff'
});
},
// 提交按钮样式:颜色 / 背景色 / 宽度(百分比)/ 上下内边距(控制高度)/ 圆角 / 字号
// 与后端 design.css .form-preview-submit button 对齐:
// - 高度由 --submit-padding-y + 字号决定,避免硬编码 line-height
// - 宽度由 --submit-width-percent 控制(10-100,clamp)
submitStyle() {
const cfg = this.mergedFormConfig || {};
// 宽度百分比:clamp 到 10-100
const widthPct = Math.min(100, Math.max(10, this._num(cfg.submitWidthPercent, 100)));
// 上下内边距:与后端 design.js submitSizeMap 对齐(mini/small/medium/large/huge → 0/4/12/24/40 rpx)
const submitPaddingMap = { mini: 0, small: 4, medium: 12, large: 24, huge: 40 };
const submitPaddingY = submitPaddingMap[cfg.submitSize] != null
? submitPaddingMap[cfg.submitSize]
: submitPaddingMap.medium;
return this.$util.objToStyle({
width: widthPct + '%',
padding: `${submitPaddingY}rpx 0`,
color: cfg.submitColor || '#ffffff',
'background-color': cfg.submitBgColor || '#ff4544',
'border-radius': `${this._num(cfg.inputRadius, 10)}rpx`,
'font-size': `${this._num(cfg.labelFontSize, 28)}rpx`
});
},
// 提交按钮文字:与后端 design.html <button>提交</button> 默认对齐,开放给 formConfig 覆盖
// 走 mergedFormConfig(兼容 camelCase / snake_case),让 formConfig.submitText 能正确覆盖
submitText() {
return this.mergedFormConfig.submitText || '提交';
},
// 后端把表单样式配置统一存放在 data.formConfig 子对象中(与后端 design.js getDefaultFormData().formConfig 字段名一致)。
// 这里做一次归一化:优先取 formConfig;如果历史数据是扁平结构(直接挂在 value 上),也做兼容。
formCfg() {
const v = this.value || {};
if (v.formConfig && typeof v.formConfig === 'object') {
return v.formConfig;
}
return v;
},
// 合并后的表单配置(支持平台差异化)
mergedFormConfig() {
const v = this.value || {};
const fc = this.formCfg;
// 后端实际返回 camelCase(如 formPaddingX / formBgColor / labelFontSize),
// 但旧版 design.js / 部分序列化路径可能用 snake_case(form_padding_x)。这里同时读两种写法,camelCase 优先
const self = this;
const pick = function(camel, snake) {
var v1 = fc[camel];
if (v1 !== undefined && v1 !== null && v1 !== '') return v1;
return fc[snake];
};
// 通用全局配置(与后端 design.js getDefaultFormData().formConfig 字段名一致)
const base = {
formPaddingX: pick('formPaddingX', 'form_padding_x'),
bannerPaddingX: pick('bannerPaddingX', 'banner_padding_x'),
tipPaddingX: pick('tipPaddingX', 'tip_padding_x'),
rowPaddingY: pick('rowPaddingY', 'row_padding_y'),
rowMinHeight: pick('rowMinHeight', 'row_min_height'),
labelGap: pick('labelGap', 'label_gap'),
formBgColor: pick('formBgColor', 'form_bg_color'),
rowDividerColor: pick('rowDividerColor', 'row_divider_color'),
showRowDivider: self._coerceBool(pick('showRowDivider', 'show_row_divider')),
inputHeight: pick('inputHeight', 'input_height'),
inputRadius: pick('inputRadius', 'input_radius'),
formLayout: pick('formLayout', 'form_layout'),
labelWidthMode: pick('labelWidthMode', 'label_width_mode'),
labelFixedWidth: pick('labelFixedWidth', 'label_fixed_width'),
labelFontSize: pick('labelFontSize', 'label_font_size'),
labelColor: pick('labelColor', 'label_color'),
requiredColor: pick('requiredColor', 'required_color'),
checkedColor: pick('checkedColor', 'checked_color'),
submitText: pick('submitText', 'submit_text'),
submitColor: pick('submitColor', 'submit_color'),
submitBgColor: pick('submitBgColor', 'submit_bg_color'),
// 提交按钮尺寸:宽度百分比 + 尺寸预设(与后端 design.js 对齐)
submitWidthPercent: pick('submitWidthPercent', 'submit_width_percent'),
submitSize: pick('submitSize', 'submit_size'),
submitMarginTop: pick('submitMarginTop', 'submit_margin_top'),
// 提示语
tipFontSize: pick('tipFontSize', 'tip_font_size'),
tipColor: pick('tipColor', 'tip_color'),
tipBgColor: pick('tipBgColor', 'tip_bg_color'),
tipBorderColor: pick('tipBorderColor', 'tip_border_color')
};
// 移除 undefined / 空字符串(保留 0/false)
Object.keys(base).forEach(function(k) {
if (base[k] === undefined || base[k] === null || base[k] === '') {
delete base[k];
}
});
// 平台差异化配置(terminal 块在 formConfig 子对象内)
// 优先级:v.formConfig.terminal > v.form_config_terminal > v.terminal > v.form_config_platform
const result = Object.assign({}, base);
const termBlock = (v.formConfig && v.formConfig.terminal) || v.form_config_terminal || v.terminal || v.form_config_platform;
if (termBlock && typeof termBlock === 'object') {
Object.keys(termBlock).forEach(function(platform) {
var src = termBlock[platform];
if (!src) return;
// 嵌套值若为 snake_case(部分序列化路径),在此统一转 camelCase
var translated = {};
Object.keys(src).forEach(function(k) {
translated[self.$util.snakeToCamel(k)] = src[k];
});
result[platform] = translated;
});
}
return result;
}
},
methods: {
submitform() {
// 初始化表单 - 将 diy-form 的数据格式转换成 ns-newform 的格式
initForm() {
if (!this.value) {
this.formComponents = [];
return;
}
// raw 模式:value.jsonData / value.json_data 已经是 ns-newform 期望的 [{ controller, value, val }],直接透传
if (this.dataMode === 'raw') {
this.formComponents = this.value.jsonData || this.value.json_data || [];
return;
}
var components = this.value.formComponents || this.value.form_components || [];
// 转换格式:type -> controller
this.formComponents = (components || []).map(function(item) {
return {
controller: item.type,
value: item.value || {},
val: (item.value && item.value.default) ? item.value.default : '' // 添加初始值
};
});
},
// 暴露给父级:触发 ns-newform 校验。校验失败时 ns-newform 内部会 toast;返回 false 表示失败,返回 formData 数组表示成功
verify() {
if (this.$refs.nsNewform && this.$refs.nsNewform.verify) {
return this.$refs.nsNewform.verify();
}
return false;
},
// 暴露给父级:获取 ns-newform 当前的 formData 数组(含 val / option_lists / img_lists 等全部字段)
getFormData() {
return (this.$refs.nsNewform && this.$refs.nsNewform.formData) || [];
},
// 数字保底:undefined/空串/非数字时返回兜底值
_num(v, fb) {
if (v === '' || v === null || v === undefined) return fb;
var n = parseInt(v);
return isNaN(n) ? fb : n;
},
// 布尔保底:0/false/'0'/'false' → false;其它有值 → true
_coerceBool(v) {
if (v === false || v === 0 || v === '0' || v === 'false' || v === null || v === undefined) {
return false;
}
return true;
},
// 提交表单
submitForm() {
var self = this;
// 校验(同时返回 formData 数组;校验失败时 ns-newform 内部 toast 提示)
if (!this.verify()) {
return;
}
// 若父级监听了 @submit,则把提交控制权交给父级(用于父级有自定义提交字段/反馈逻辑的页面,如 formdata.vue 传 uniacid)
if (this.$listeners && this.$listeners.submit) {
this.$emit('submit', this.getFormData());
return;
}
// 获得保单数据
const submitFormData = this.getFormData();
// 提交到后端
this.$api.sendRequest({
url: '/api/member/information',
data: this.Form,
success: res => {
this.$util.showToast({
title: res.message
});
url: '/form/api/form/create',
data: {
form_id: this.value.form_id || 0,
form_data: typeof submitFormData === 'string' ? submitFormData : JSON.stringify(submitFormData),
component_id: this.value.id || '',
form_name: this.value.form_name || '默认表单'
},
success: function(res) {
if (res.code === 0) {
uni.showToast({
title: '提交成功',
icon: 'success'
});
// 重置表单
if (self.$refs.nsNewform && self.$refs.nsNewform.setFormData) {
self.$refs.nsNewform.setFormData();
}
} else {
uni.showToast({
title: res.message || '提交失败',
icon: 'none'
});
}
}
});
}
@@ -108,7 +321,54 @@ export default {
<style lang="scss">
.diy-from {
background: #fff;
padding-bottom: 20rpx;
padding: 0;
border-radius: 10rpx;
.form-banner {
width: 100%;
overflow: hidden;
// 默认左右无边距(与后端 --banner-padding-x 对齐;由内联 bannerStyle 覆盖)
margin: 0;
.banner-img {
width: 100%;
display: block;
}
}
.form-tip {
// 提示语:上下内边距 / 左右内边距 / 字号 / 颜色 / 背景 全部由 tipStyle 内联写入
padding: 0;
text-align: center;
line-height: 1.5;
}
.form-submit-wrap {
// 外层:与后端 .form-preview-submit 对齐(margin-top + padding-y + form-padding-x + form-bg-color + flex 居中)
// margin-top/padding/background 由 submitWrapStyle 内联写入
// display: flex + justify-content: center 是让宽度小于 100% 的按钮水平居中的关键
box-sizing: border-box;
width: 100%;
display: flex;
justify-content: center;
}
.form-submit {
// 提交按钮:颜色 / 背景色 / 宽度(百分比)/ 上下内边距(控制高度)/ 圆角 / 字号
// 全部由 submitStyle 内联写入
// 宽度不再写死 100%,由内联 style 的 width: <pct>% 决定;max-width: 100% 防止溢出
display: flex;
align-items: center;
justify-content: center;
max-width: 100%;
font-weight: 500;
letter-spacing: 1rpx;
transition: opacity 0.2s ease;
box-sizing: border-box;
&:active {
opacity: 0.85;
}
}
}
</style>

View File

@@ -9,7 +9,7 @@
<view class="li-item" v-for="(item, index) in list" :key="index">
<image class="brand-pic" :src="$util.img(item.image_url)" mode="aspectFit"
@tap.stop="handlerClick(item)" @error="imgError(index)"
:style="itemCss" />
:style="itemCss" show-menu-by-longpress/>
</view>
</view>
</view>

View File

@@ -7,8 +7,9 @@
<view class="goods-img-wrap">
<image class="goods-img"
:src="$util.img(item.goods_image, { size: goodsValue.template == 'large-mode' ? 'big' : 'mid' })"
mode="widthFix" @error="imgError(index)"
:style="{ borderRadius: goodsValue.imgAroundRadius * 2 + 'rpx' }" />
:mode="imgMode" @error="imgError(index)"
:style="{ borderRadius: goodsValue.imgAroundRadius * 2 + 'rpx' }"
show-menu-by-longpress />
<view class="sell-out" v-if="item.stock <= 0">
<text class="iconfont icon-shuqing"></text>
</view>
@@ -48,9 +49,9 @@
<view class="member-price"
v-if="(item.member_price && item.member_price == showPrice(item)) || item.promotion_type == 1">
<image v-if="item.member_price && item.member_price == showPrice(item)"
:src="$util.img('public/uniapp/index/VIP.png')" />
:src="$util.img('public/uniapp/index/VIP.png')" show-menu-by-longpress />
<image v-else-if="item.promotion_type == 1"
:src="$util.img('public/uniapp/index/discount.png')" />
:src="$util.img('public/uniapp/index/discount.png')" show-menu-by-longpress />
</view>
<view v-if="goodsValue.priceStyle.lineControl && showMarketPrice(item)"
class="delete-price price-font"
@@ -59,7 +60,7 @@
</view>
<view class="sale" v-if="goodsValue.saleStyle.control"
:style="{ color: goodsValue.theme == 'diy' ? goodsValue.saleStyle.color : '' }">
已售{{ item.sale_num }}{{ item.unit ? item.unit : '件' }}
{{ $lang('components-diy.diy-goods-list.soldCount', { count: item.sale_num, unit: item.unit || $lang('components-diy.diy-goods-list.soldUnit') }) }}
</view>
</view>
@@ -116,8 +117,8 @@
:class="[goodsValue.ornament.type]" :style="goodsItemCss">
<view class="goods-img-wrap">
<image class="goods-img" :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }"
:src="$util.img(item.goods_image, { size: 'mid' })" mode="widthFix" @error="imgError(index)"
:lazy-load="true" />
:src="$util.img(item.goods_image, { size: 'mid' })" :mode="imgMode" @error="imgError(index)"
:lazy-load="true" show-menu-by-longpress />
<view class="sell-out" v-if="item.stock <= 0">
<text class="iconfont icon-shuqing"></text>
</view>
@@ -156,9 +157,9 @@
<view class="member-price"
v-if="(item.member_price && item.member_price == showPrice(item)) || item.promotion_type == 1">
<image v-if="item.member_price && item.member_price == showPrice(item)"
:src="$util.img('public/uniapp/index/VIP.png')" />
:src="$util.img('public/uniapp/index/VIP.png')" show-menu-by-longpress />
<image v-else-if="item.promotion_type == 1"
:src="$util.img('public/uniapp/index/discount.png')" />
:src="$util.img('public/uniapp/index/discount.png')" show-menu-by-longpress />
</view>
<view v-if="goodsValue.priceStyle.lineControl && showMarketPrice(item)"
class="delete-price price-font"
@@ -167,7 +168,7 @@
</view>
<view class="sale" v-if="goodsValue.saleStyle.control"
:style="{ color: goodsValue.theme == 'diy' ? goodsValue.saleStyle.color : '' }">
已售{{ item.sale_num }}{{ item.unit ? item.unit : '件' }}
{{ $lang('components-diy.diy-goods-list.soldCount', { count: item.sale_num, unit: item.unit || $lang('components-diy.diy-goods-list.soldUnit') }) }}
</view>
</view>
</view>
@@ -183,8 +184,8 @@
:class="[goodsValue.ornament.type]" :style="goodsItemCss">
<view class="goods-img-wrap">
<image class="goods-img" :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }"
:src="$util.img(dataItem.goods_image, { size: 'mid' })" mode="widthFix"
@error="imgError(dataIndex)" :lazy-load="true" />
:src="$util.img(dataItem.goods_image, { size: 'mid' })" :mode="imgMode"
@error="imgError(dataIndex)" :lazy-load="true" show-menu-by-longpress />
<view class="sell-out" v-if="dataItem.stock <= 0">
<text class="iconfont icon-shuqing"></text>
</view>
@@ -226,9 +227,9 @@
v-if="(dataItem.member_price && dataItem.member_price == showPrice(dataItem)) || dataItem.promotion_type == 1">
<image
v-if="dataItem.member_price && dataItem.member_price == showPrice(dataItem)"
:src="$util.img('public/uniapp/index/VIP.png')" />
:src="$util.img('public/uniapp/index/VIP.png')" show-menu-by-longpress />
<image v-else-if="dataItem.promotion_type == 1"
:src="$util.img('public/uniapp/index/discount.png')" />
:src="$util.img('public/uniapp/index/discount.png')" show-menu-by-longpress />
</view>
<view v-if="goodsValue.priceStyle.lineControl && showMarketPrice(dataItem)"
class="delete-price"
@@ -237,7 +238,7 @@
</view>
<view class="sale" v-if="goodsValue.saleStyle.control"
:style="{ color: goodsValue.theme == 'diy' ? goodsValue.saleStyle.color : '' }">
已售{{ dataItem.sale_num }}{{ dataItem.unit ? dataItem.unit : '件' }}
{{ $lang('components-diy.diy-goods-list.soldCount', { count: dataItem.sale_num, unit: dataItem.unit || $lang('components-diy.diy-goods-list.soldUnit') }) }}
</view>
</view>
</view>
@@ -301,6 +302,19 @@ export default {
}
},
computed: {
// 商品图 image 的 mode 模式:
// - 大图模式(large-mode):容器高度由图片决定,固定使用 widthFix 保持原比例
// - 鸿蒙元服务:其他模板下 image 的 widthFix 模式异常(图片被裁剪/显示不全),改用 aspectFill 填满固定容器
// - H5、微信小程序等其他环境:保持 widthFix 行为不变
imgMode() {
if (this.goodsValue.template == 'large-mode') return 'widthFix';
// #ifdef MP-HARMONY
return 'aspectFill';
// #endif
// #ifndef MP-HARMONY
return 'widthFix';
// #endif
},
goodsListWarpCss() {
var obj = '';
obj += 'background-color:' + this.goodsValue.componentBgColor + ';';
@@ -1017,10 +1031,6 @@ export default {
width: calc(33.3333333% - 14rpx);
box-sizing: border-box;
&:nth-child(3n + 3) {
width: calc(33.33% - 15rpx);
}
&:nth-of-type(1),
&:nth-of-type(2),
&:nth-of-type(3) {

View File

@@ -17,7 +17,7 @@
<div class="goods-img-wrap">
<image class="goods-img" :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }"
:src="$util.img(dataItem.goods_image, { size: 'mid' })" mode="widthFix"
@error="imgError(index, dataIndex)" :lazy-load="true" />
@error="imgError(index, dataIndex)" :lazy-load="true" show-menu-by-longpress />
<view class="sell-out" v-if="dataItem.stock <= 0">
<text class="iconfont icon-shuqing"></text>
</view>
@@ -33,7 +33,7 @@
<view class="label-wrap" v-if="goodsValue.labelStyle.support"
:style="{ background: goodsValue.labelStyle.bgColor, color: goodsValue.labelStyle.color }">
<image :src="$util.img('app/component/view/goods_recommend/img/label.png')"
mode="widthFix" />
mode="widthFix" show-menu-by-longpress />
<text>{{ goodsValue.labelStyle.title }}</text>
</view>
<view class="discount-price">
@@ -53,7 +53,7 @@
¥{{ showMarketPrice(dataItem) }}</view>
<view class="sale" v-if="goodsValue.saleStyle.control"
:style="{ color: goodsValue.theme == 'diy' ? goodsValue.saleStyle.color : '' }">
售{{ dataItem.sale_num }}{{ dataItem.unit ? dataItem.unit : '件' }}
{{ $lang('components-diy.diy-goods-recommend.soldPrefix') }}{{ dataItem.sale_num }}{{ dataItem.unit ? dataItem.unit : $lang('unit.piece') }}
</view>
</view>
</view>

View File

@@ -23,7 +23,7 @@
:src="$util.img(item.imageUrl) || $util.img('public/uniapp/default_img/goods.png')"
mode="aspectFill"
:style="{ maxWidth: value.imageSize * 2 + 'rpx', maxHeight: value.imageSize * 2 + 'rpx', borderRadius: value.aroundRadius * 2 + 'rpx' }"
:show-menu-by-longpress="true" />
show-menu-by-longpress />
<diy-icon v-if="item.iconType == 'icon'" :icon="item.icon"
:value="item.style ? item.style : null"
@@ -69,7 +69,7 @@
:src="$util.img(item.imageUrl) || $util.img('public/uniapp/default_img/goods.png')"
mode="aspectFill"
:style="{ maxWidth: value.imageSize * 2 + 'rpx', maxHeight: value.imageSize * 2 + 'rpx', borderRadius: value.aroundRadius * 2 + 'rpx' }"
:show-menu-by-longpress="true" />
show-menu-by-longpress />
<diy-icon v-if="item.iconType == 'icon'" :icon="item.icon"
:value="item.style ? item.style : null"
:style="{ maxWidth: value.imageSize * 2 + 'rpx', maxHeight: value.imageSize * 2 + 'rpx', width: '100%', height: '100%' }"></diy-icon>
@@ -164,7 +164,6 @@ export default {
return;
}
}
console.log(link)
this.$util.diyRedirectTo(link);
},
swiperChange(e) {

View File

@@ -291,77 +291,99 @@ export default {
mixins: [DiyMinx],
data() {
return {
diyGlobalData: null
diyGlobalData: this.diyData ? this.$util.deepClone(this.diyData) : null,
processedData: null
};
},
watch: {
diyData: {
handler() {
this.diyGlobalData = this.diyData ? this.$util.deepClone(this.diyData) : null;
this.processData();
this._notifyLoaded();
},
deep: true
}
},
created() {
this.diyGlobalData = JSON.parse(JSON.stringify(this.diyData));
this.processData();
},
mounted() {
if (this.diyData && this.diyData.value) {
this._notifyLoaded();
}
},
computed: {
topNavColor() {
var color = '';
if (this.diyData.global.topNavBg) {
color = 'transparent';
if (this.scrollTop > 20) {
color = this.diyData.global.topNavColor;
} else {
color = 'transparent';
}
} else {
color = this.diyData.global.topNavColor;
if (!this.diyData?.global) return '';
const { topNavBg, topNavColor } = this.diyData.global;
if (topNavBg) {
return this.scrollTop > 20 ? topNavColor : 'transparent';
}
return color;
return topNavColor;
},
// 修改属性样式
setPagestyle() {
this.diyGlobalData.value.forEach((item, index) => {
item.pageStyle = '';
// 给每个组件增加位置属性,用于定位,搜索、分类导航等定位
item.moduleIndex = index + 1;
// 特殊处理搜索框 当显示位置为滚动至顶部固定时,只设置背景颜色
if (item.componentName == 'Search' && item.positionWay == 'fixed') {
// item.pageStyle = 'background-color:' + item.pageBgColor + ';';
return false;
}
item.pageStyle += 'background-color:' + item.pageBgColor + ';';
if (item.margin) {
item.pageStyle += 'padding-top:' + item.margin.top * 2 + 'rpx' + ';';
item.pageStyle += 'padding-bottom:' + item.margin.bottom * 2 + 'rpx' + ';';
item.pageStyle += 'padding-right:' + item.margin.both * 2 + 'rpx' + ';';
item.pageStyle += 'padding-left:' + item.margin.both * 2 + 'rpx' + ';';
}
});
return this.diyGlobalData.value;
},
// 过滤组件的渲染
diyDataArray() {
let data = [],
showModuleData = this.$store.state.diyGroupShowModule ? JSON.parse(this.$store.state
.diyGroupShowModule) : '';
if (!this.processedData) {
this.processData();
}
if (showModuleData.length) {
if (showModuleData.includes('null')) return [];
const showModuleData = this.$store.state.diyGroupShowModule
? JSON.parse(this.$store.state.diyGroupShowModule)
: null;
let diyDataArr = this.setPagestyle;
diyDataArr.forEach((item, index) => {
if (showModuleData.includes(item.componentName)) {
data.push(item);
}
});
} else data = this.setPagestyle;
if (!showModuleData || !showModuleData.length) {
return this.processedData || [];
}
console.log(`diy-group ['diyDataArray'] = `, {
data: data,
diyData: this.diyData,
diyGlobalData: this.diyGlobalData,
})
return data;
if (showModuleData.includes('null')) {
return [];
}
return (this.processedData || []).filter(item =>
showModuleData.includes(item.componentName)
);
}
},
methods: {}
methods: {
_notifyLoaded() {
if (this._loadedTimer) clearTimeout(this._loadedTimer);
this._loadedTimer = setTimeout(() => {
this.$emit('loaded');
}, 300);
},
processData() {
if (!this.diyGlobalData || !this.diyGlobalData.value) {
this.processedData = [];
return;
}
this.processedData = this.diyGlobalData.value.map((item, index) => {
const newItem = this.$util.deepClone(item);
newItem.pageStyle = '';
newItem.moduleIndex = this.diyData.tabIndex !== undefined
? `${this.diyData.tabIndex}-${index + 1}`
: index + 1;
if (newItem.componentName !== 'Search' || newItem.positionWay !== 'fixed') {
newItem.pageStyle = `background-color:${newItem.pageBgColor};`;
if (newItem.margin) {
newItem.pageStyle += `padding-top:${newItem.margin.top * 2}rpx;`;
newItem.pageStyle += `padding-bottom:${newItem.margin.bottom * 2}rpx;`;
newItem.pageStyle += `padding-right:${newItem.margin.both * 2}rpx;`;
newItem.pageStyle += `padding-left:${newItem.margin.both * 2}rpx;`;
}
}
return newItem;
});
}
}
};
</script>

View File

@@ -7,7 +7,7 @@
<view class="img-wrap" :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }">
<image :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }"
:src="$util.img(item.goods_image, { size: 'mid' })" mode="widthFix"
@error="imageError(index)">
@error="imageError(index)" show-menu-by-longpress>
</image>
</view>
<view class="content"
@@ -44,7 +44,7 @@
<view class="img-wrap" :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }">
<image :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }"
:src="$util.img(item.goods_image, { size: 'mid' })" mode="widthFix"
@error="imageError(index)" />
@error="imageError(index)" show-menu-by-longpress/>
<image class="bg" v-if="value.saleStyle.control"
:src="$util.img('public/uniapp/groupbuy/bg.png')" mode="widthFix" />
<view class="num" v-if="value.saleStyle.control"
@@ -85,7 +85,7 @@
<view class="img-wrap" :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }">
<image :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }"
:src="$util.img(item.goods_image, { size: 'mid' })" mode="widthFix"
@error="imageError(dataIndex)" />
@error="imageError(dataIndex)" show-menu-by-longpress/>
<image class="bg" v-if="value.saleStyle.control"
:src="$util.img('public/uniapp/groupbuy/bg.png')" mode="widthFix" />
<view class="num" v-if="value.saleStyle.control"

View File

@@ -2,7 +2,7 @@
<view data-component-name="diy-hot-area" :style="hotAreaWarp" class="hot-area-box">
<view class="simple-graph-wrap">
<image :style="{ height: value.imgHeight }" :src="$util.img(value.imageUrl)" mode="widthFix"
:show-menu-by-longpress="true" />
show-menu-by-longpress />
<!-- 热区功能 -->
<view class="heat-map" v-for="(mapItem, mapIndex) in value.heatMapData" :key="mapIndex" :style="{
width: mapItem.width + '%',

View File

@@ -1,5 +1,5 @@
<template>
<view :style="componentStyle">
<view :style="componentStyle" data-component-name="diy-image-nav">
<scroll-view :class="['image-nav', value.showStyle == 'fixed' ? 'fixed-layout' : value.showStyle]"
:scroll-x="value.showStyle == 'singleSlide'">
<view class="uni-scroll-view-content">
@@ -15,12 +15,12 @@
'width': (item.imgWidth / 2 + 'rpx') + ';',
'height': (item.imgHeight / 2 + 'rpx') + ';'
}" :src="$util.img(item.imageUrl) || $util.img('public/uniapp/default_img/goods.png')"
:show-menu-by-longpress="true" @tap.stop="redirectTo(item.link)"></image>
show-menu-by-longpress @tap.stop="redirectTo(item.link)"></image>
<image v-else :style="{
'width': (item.imgWidth / 2 + 'rpx') + ';',
'height': (item.imgHeight / 2 + 'rpx') + ';'
}" :src="$util.img(item.imageUrl) || $util.img('public/uniapp/default_img/goods.png')"
:show-menu-by-longpress="true" @tap.stop="previewImg(item.imageUrl)"></image>
show-menu-by-longpress @tap.stop="previewImg(item.imageUrl)"></image>
</view>
<!-- 文字部分 -->
@@ -54,12 +54,35 @@ export default {
return {
pageWidth: '',
indicatorDots: false,
swiperCurrent: 0
swiperCurrent: 0,
// H5 鼠标拖拽状态(singleSlide 模式专用)
slideIsDragging: false,
slideDidDrag: false, // 5px 阈值后置 true,用于判断 mouseup 后是否拦截 click
slideStartX: 0,
slideStartScrollLeft: 0,
_suppressNextClick: false // 拖拽结束后拦截一次 click,防止误触发跳转
}
},
created() {
// 组件创建时的逻辑
},
mounted() {
// H5 端:为 singleSlide 模式的 scroll-view 手动绑定 mouse/wheel 事件
// 原因:模板里写 @mousedown/@wheel 在小程序/鸿蒙端会产生"未知事件"警告,
// 所以 H5 专属事件全部在 mounted 中通过 addEventListener 绑定。
// $nextTick 是为了确保 ref 在 DOM 中已就绪(滚动容器总是存在的,无 v-if)。
// #ifdef H5
var self = this;
this.$nextTick(function() {
self.bindSlideMouseEvents();
});
// #endif
},
beforeDestroy() {
// #ifdef H5
this.unbindSlideMouseEvents();
// #endif
},
watch: {
componentRefresh(newValue) {
// 监听组件刷新
@@ -115,6 +138,163 @@ export default {
// 轮播切换
swiperChange(event) {
this.swiperCurrent = event.detail.current;
},
// ========== H5 singleSlide 鼠标拖拽支持 ==========
// 背景:uni-app 的 scroll-view 在 H5 端被编译为 div,虽然 overflow-x: auto 可让
// 浏览器渲染横向滚动条,但 scrollLeft 不响应鼠标拖拽(uni 的滚动逻辑不监听 mouse)。
// 因此 H5 下需要手动绑定 mousedown/mousemove/mouseup,模拟拖拽改变 scrollLeft。
// 同时绑定 wheel,让鼠标滚轮也能横向滚动(浏览器默认滚轮是垂直,需 preventDefault 后手动改 scrollLeft)。
// 仅在 singleSlide 模式下生效;fixed / pageSlide 走原逻辑。
//
// 关键设计:H5 专属事件全部在 mounted 中通过 addEventListener 绑定,而不是写在模板上,
// 避免小程序/鸿蒙端产生"未知事件"编译警告。所有端共用同一份模板。
bindSlideMouseEvents() {
// #ifdef H5
// 防止重复绑定
if (this._slideEventsBound) return;
var outerEl = this.getSlideOuterEl();
var innerEl = this.getSlideContainer();
if (!outerEl || !innerEl) return;
// 关键发现:uni-app 的 <uni-scroll-view> web component 内部用了 BetterScroll,
// 它会拦截 touch/mouse 事件;绑到 scroll-view 自身的 mousedown 收不到(目标被重定向到 HTML)。
// 解决:document 级别 capture 阶段监听 + 用 clientX/clientY 落在容器 bounding box 内才处理。
this._slideOuterEl = outerEl;
this._slideEl = innerEl;
this._slideEventsBound = true;
// document 级别 capture 阶段,先于 uni-app 内部的滚动库触发
document.addEventListener('mousedown', this.onSlideMouseDown, true);
document.addEventListener('wheel', this.onSlideWheel, { passive: false, capture: true });
// click 拦截:如果在 mousemove 中真的拖动了容器(mousedown 后 deltaX > 5),
// mouseup 时进入"忽略接下来一次 click"状态,防止拖拽结束后误触发跳转。
document.addEventListener('click', this.onSlideMaybeClick, true);
window.addEventListener('mousemove', this.onSlideMouseMove);
window.addEventListener('mouseup', this.onSlideMouseUp);
// #endif
},
unbindSlideMouseEvents() {
// #ifdef H5
document.removeEventListener('mousedown', this.onSlideMouseDown, true);
document.removeEventListener('wheel', this.onSlideWheel, true);
document.removeEventListener('click', this.onSlideMaybeClick, true);
window.removeEventListener('mousemove', this.onSlideMouseMove);
window.removeEventListener('mouseup', this.onSlideMouseUp);
this._slideOuterEl = null;
this._slideEventsBound = false;
// #endif
},
getSlideContainer() {
// #ifdef H5
// uni-app 的 scroll-view 在 H5 端编译为 <uni-scroll-view> web component,
// 嵌套结构:
// <uni-scroll-view> ← 自定义元素
// <div class="uni-scroll-view"> ← 第1层,visible
// <div class="uni-scroll-view"> ← 第2层,overflowX=auto (真滚动容器)
// 真正能响应 scrollLeft 的是第 2 层 div。
// 通过 data-component-name 找到本组件根 view,然后向下找 .uni-scroll-view。
var componentRoot = document.querySelector('[data-component-name="diy-image-nav"]');
if (!componentRoot) return null;
// 找 overflowX:auto 的 div.uni-scroll-view
var candidates = componentRoot.querySelectorAll('.uni-scroll-view');
for (var i = 0; i < candidates.length; i++) {
var s = getComputedStyle(candidates[i]).overflowX;
if (s === 'auto' || s === 'scroll') {
return candidates[i];
}
}
// 兜底:取最后一个 .uni-scroll-view(经验上最后一个就是真滚动容器)
return candidates.length > 0 ? candidates[candidates.length - 1] : null;
// #endif
},
getSlideOuterEl() {
// #ifdef H5
// 用于判断 mousedown/wheel 是否落在容器内(用最外层 <uni-scroll-view> 的 bounding box)
var componentRoot = document.querySelector('[data-component-name="diy-image-nav"]');
if (!componentRoot) return null;
var sc = componentRoot.querySelector('uni-scroll-view');
return sc || null;
// #endif
},
onSlideMouseDown(e) {
// #ifdef H5
if (this.value.showStyle != 'singleSlide') return;
// document 级别监听,只处理落在容器内的事件
// 关键:e.target 可能是 HTML 本身(BetterScroll 内部 stopPropagation 导致),
// 所以用 clientX/clientY 判断是否落在容器 bounding box 内。
if (!this._slideOuterEl) return;
var rect = this._slideOuterEl.getBoundingClientRect();
if (!rect) return;
var x = e.clientX, y = e.clientY;
if (x < rect.left || x > rect.right || y < rect.top || y > rect.bottom) return;
var el = this.getSlideContainer();
if (!el) return;
this.slideIsDragging = true;
this.slideStartX = x;
this.slideStartScrollLeft = el.scrollLeft;
this.slideDidDrag = false; // mousedown 时清零:5px 阈值后才置 true
this._suppressNextClick = false;
if (e.preventDefault) e.preventDefault();
// 注意:这里不调 stopPropagation,否则纯点击也不能触发 click/tap → 跳转
// #endif
},
onSlideMouseMove(e) {
// #ifdef H5
if (!this.slideIsDragging) return;
var el = this.getSlideContainer();
if (!el) return;
var x = (e.clientX != null) ? e.clientX : 0;
var deltaX = x - this.slideStartX;
// 5px 阈值:超过后标记已经拖动,后续 mouseup 会忽略接下来一次 click
if (!this.slideDidDrag && Math.abs(deltaX) >= 5) {
this.slideDidDrag = true;
}
// 反向:手指/鼠标往右拖 → 内容向右滚 → scrollLeft 减小
el.scrollLeft = this.slideStartScrollLeft - deltaX;
if (e.preventDefault) e.preventDefault();
// #endif
},
onSlideMouseUp() {
// #ifdef H5
this.slideIsDragging = false;
// 如果确实拖动过,标记接下来一次 click 应当被拦截(防止拖拽结束后误触发跳转)
if (this.slideDidDrag) {
this._suppressNextClick = true;
}
// #endif
},
// click 拦截:如果 mouseup 时设置了 _suppressNextClick,就拦截这一次 click 并清除标记
onSlideMaybeClick(e) {
// #ifdef H5
if (!this._suppressNextClick) return;
if (!e.target) return;
var outer = this._slideOuterEl;
if (!outer || !outer.contains(e.target)) return;
this._suppressNextClick = false;
if (e.preventDefault) e.preventDefault();
if (e.stopPropagation) e.stopPropagation();
if (e.stopImmediatePropagation) e.stopImmediatePropagation();
// #endif
},
onSlideWheel(e) {
// #ifdef H5
if (this.value.showStyle != 'singleSlide') return;
if (!this._slideOuterEl) return;
// 同 mouseDown:用 clientX/clientY 判断 wheel 是否落在容器内
var rect = this._slideOuterEl.getBoundingClientRect();
if (!rect) return;
var x = e.clientX, y = e.clientY;
if (x < rect.left || x > rect.right || y < rect.top || y > rect.bottom) return;
var el = this.getSlideContainer();
if (!el) return;
// 浏览器 wheel 事件的 deltaY 是垂直方向;此处把垂直滚轮映射到横向滚动
var dx = e.deltaX || 0;
var dy = e.deltaY || 0;
// 优先用 deltaX(触控板横向 / Shift+滚轮),否则用 deltaY(普通滚轮 → 转横向)
var step = dx !== 0 ? dx : dy;
el.scrollLeft += step;
if (e.preventDefault) e.preventDefault();
if (e.stopPropagation) e.stopPropagation();
// #endif
}
}
}
@@ -140,6 +320,25 @@ export default {
.image-nav-item {
flex-shrink: 0;
}
// ========== H5 singleSlide 鼠标拖拽支持:横向滚动 ==========
// uni-app 在 H5 端会把 scroll-view 编译为 div,但默认样式不一定是
// overflow-x:auto → 横向内容溢出后无法滚动。需要显式声明。
// #ifdef H5
overflow-x: auto;
overflow-y: hidden;
// 隐藏滚动条,视觉上仍保持单页布局;用户用鼠标拖拽/滚轮即可滚动
scrollbar-width: none; // Firefox
-ms-overflow-style: none; // IE/Edge legacy
&::-webkit-scrollbar {
display: none;
}
// 禁止鼠标选中文字(拖拽时选中会显得很别扭)
user-select: none;
-webkit-user-select: none;
// 拖拽时关闭过渡,避免 Chrome 的惯性滚动与 JS 抢控制权
-webkit-overflow-scrolling: touch;
// #endif
}
&.pageSlide {

View File

@@ -4,7 +4,7 @@
<block v-if="imgAdsValue.list.length == 1">
<view class="simple-graph-wrap" :style="imgAdsSwiper" @tap.stop="handlerClick(imgAdsValue.list[0].link)">
<image :style="{ height: imgAdsValue.list[0].imgHeight }"
:src="$util.img(imgAdsValue.list[0].imageUrl)" mode="widthFix" :show-menu-by-longpress="true" />
:src="$util.img(imgAdsValue.list[0].imageUrl)" mode="widthFix" show-menu-by-longpress />
</view>
</block>
<swiper v-else class="swiper" :style="{ height: swiperHeight }" :class="{
@@ -18,7 +18,7 @@
:key="index" v-if="item.imageUrl" @tap.stop="handlerClick(item.link)">
<view class="item" :style="imgAdsSwiper + 'height: ' + item.imgHeight">
<image :src="$util.img(item.imageUrl)" :mode="item.imageMode || 'scaleToFill'"
:show-menu-by-longpress="true" />
show-menu-by-longpress />
</view>
</swiper-item>
</swiper>

View File

@@ -58,9 +58,9 @@
:key="index" @tap.stop="toCateGoodsList(item.category_id_2, 2)">
<view class="item-box">
<image :src="$util.img(item.image)" v-if="item.image"
mode="aspectFill" />
mode="aspectFill" show-menu-by-longpress/>
<image :src="$util.getDefaultImage().goods" v-else
mode="aspectFill" />
mode="aspectFill" show-menu-by-longpress/>
<view>{{ item.category_name }}</view>
</view>
</view>
@@ -73,9 +73,9 @@
:key="index" @tap.stop="toCateGoodsList(item.category_id_2, 2)">
<view class="item-box">
<image :src="$util.img(item.image)" v-if="item.image"
mode="aspectFill" />
mode="aspectFill" show-menu-by-longpress/>
<image :src="$util.getDefaultImage().goods" v-else
mode="aspectFill" />
mode="aspectFill" show-menu-by-longpress/>
<view>{{ item.category_name }}</view>
</view>
</view>
@@ -88,7 +88,7 @@
:key="index" v-if="index >= (page - 1) * 10 && index < page * 10"
@tap.stop="toCateGoodsList(item.category_id_2, 2)">
<view class="item-box">
<image :src="item.image" mode="aspectFill" />
<image :src="item.image" mode="aspectFill" show-menu-by-longpress/>
<view>{{ item.category_name }}</view>
</view>
</view>
@@ -104,19 +104,19 @@
<!-- 分类广告 -->
<image class="category_adv" v-if="cateList[pageIndex].image_adv"
:src="$util.img(cateList[pageIndex].image_adv)" mode="widthFix" />
:src="$util.img(cateList[pageIndex].image_adv)" mode="widthFix" show-menu-by-longpress/>
<view class="goods-list double-column" v-if="goodsList[pageIndex].list.length">
<view class="goods-item" v-for="(item, index) in goodsList[pageIndex].list"
:key="index" @tap.stop="toDetail(item)">
<view class="goods-img">
<image :src="goodsImg(item.goods_image)" mode="widthFix"
@error="imgError(index)" />
@error="imgError(index)" show-menu-by-longpress/>
<view class="color-base-bg goods-tag"
v-if="value.goodsTag == 'default' && goodsTag(item) != ''">{{
goodsTag(item) }}</view>
<view class="goods-tag-img" v-if="value.goodsTag == 'diy'">
<image :src="$util.img(value.tagImg.imageUrl)" />
<image :src="$util.img(value.tagImg.imageUrl)" show-menu-by-longpress/>
</view>
</view>
<view class="info-wrap">
@@ -133,11 +133,11 @@
<view class="member-price-tag"
v-if="item.member_price && item.member_price == showPrice(item)">
<image :src="$util.img('public/uniapp/index/VIP.png')"
mode="widthFix" />
mode="widthFix" show-menu-by-longpress/>
</view>
<view class="member-price-tag" v-else-if="item.promotion_type == 1">
<image :src="$util.img('public/uniapp/index/discount.png')"
mode="widthFix" />
mode="widthFix" show-menu-by-longpress/>
</view>
</view>
<view class="pro-info">
@@ -146,14 +146,14 @@
<text class="unit">{{ $lang('common.currencySymbol') }}</text>
<text>{{ showMarketPrice(item) }}</text>
</view>
<view class="sale font-size-activity-tag color-tip">已售{{
item.sale_num }}{{ item.unit ? item.unit : '件' }}</view>
<view class="sale font-size-activity-tag color-tip">{{
$lang('components-diy.diy-index-page.soldCount', { count: item.sale_num, unit: item.unit || $lang('components-diy.diy-index-page.soldUnit') }) }}</view>
</view>
</view>
</view>
</view>
<view v-if="!isloading && goodsList[pageIndex].list.length == 0">
<ns-empty text="该分类下暂无商品" :isIndex="false"></ns-empty>
<ns-empty :text="$lang('components-diy.diy-index-page.noGoodsInCategory')" :isIndex="false"></ns-empty>
</view>
</block>
</mescroll-uni>
@@ -193,7 +193,7 @@ export default {
pageIndex: 0, //当前选中分类id
cateList: [{
//header分类
category_name: '首页'
category_name: ''
}],
twoCategorylist: [], //二级分类
twoCategorylistId: 0, //二级分类所在的swiper
@@ -258,6 +258,9 @@ export default {
return data;
}
},
created() {
this.cateList[0].category_name = this.$lang('components-diy.diy-index-page.home');
},
watch: {
type(newVal, oldVal) {
if (newVal) {
@@ -323,7 +326,7 @@ export default {
let obj = {
list: []
};
obj.category_name = this.value.title ? this.value.title : '首页';
obj.category_name = this.value.title ? this.value.title : this.$lang('components-diy.diy-index-page.home');
arr.push(obj);
this.cateList = arr.concat(res.data);
Object.keys(this.cateList).forEach((key, index) => {

View File

@@ -3,7 +3,7 @@
<view class="fui-list-group merchgroup" v-for="(item, index) in value.list" :key="index">
<view class="fui-list jump" v-if="index == 0">
<view class="fui-list-media">
<image class="round" :src="$util.img(item.imageUrl)" style="border-radius:6rpx"></image>
<image class="round" :src="$util.img(item.imageUrl)" style="border-radius:6rpx" show-menu-by-longpress></image>
</view>
<view class="fui-list-inner">
<view class="title" style="height: 75rpx;">
@@ -14,7 +14,7 @@
</view>
<view class="fui-remark jump" style="padding-right: 20rpx; text-align: center; line-height: 140rpx;">
<span style="font-size:24rpx;padding: 14rpx 18rpx;border-radius:8rpx"
:style="{ background: item.BtBgColor, color: item.BtColor }" @tap.stop="previewSqs()">立即添加</span>
:style="{ background: item.BtBgColor, color: item.BtColor }" @tap.stop="previewSqs()">{{ $lang('components-diy.diy-kefu.addNow') }}</span>
</view>
</view>
</view>

View File

@@ -1,7 +1,7 @@
<template>
<view data-component-name="diy-listmenu" class="diy-listmenu" :style="style">
<view class="fui-cell-group">
<!-- <image mode="widthFix" style="width: 100%;" :src="$util.img(item.imageUrl)"></image> -->
<!-- <image mode="widthFix" style="width: 100%;" :src="$util.img(item.imageUrl)" show-menu-by-longpress></image> -->
<view v-for="(item, index) in value.list" @tap.stop="redirectTo(item.link)" class="fui-cell"
:class="item.iconType == 'img' ? 'img-cell' : ''">
@@ -12,9 +12,10 @@
style="border-radius:6rpx;width: 60rpx;"></image>
</view>
<view class="fui-cell-text" style="color:#333;">{{ item.title }}</view>
<view class="fui-cell-remark" style="font-size: 24rpx;">{{ lang == 'en-us' ? 'view' : '查看' }}</view>
<view class="fui-cell-remark" @tap.stop="redirectTo(item.link)" style="font-size: 24rpx;">{{ $lang('components-diy.diy-listmenu.view') }}</view>
</view>
</view>
<ns-login ref="login"></ns-login>
</view>
</template>
@@ -32,7 +33,6 @@ export default {
data() {
return {
loading: true,
lang: uni.getStorageSync("lang")//en-us 英文
};
},
created() {
@@ -63,7 +63,7 @@ export default {
redirectTo(link) {
if (link.wap_url) {
if (this.$util.getCurrRoute() == this.$util.MEMBER_PAGE_URL && !this.storeToken) {
this.$refs?.login?.open(link.wap_url);
this.redirectTologin(link.wap_url)
return;
}
}

View File

@@ -25,12 +25,12 @@
<block v-if="value.isShowAnchorInfo">
<image
:src="liveInfo.anchor_img != '' ? $util.img(liveInfo.anchor_img) : $util.getDefaultImage().head"
class="anchor-img" @error="liveInfo.anchor_img = $util.getDefaultImage().head" />
<text class="anchor-name">主播:{{ liveInfo.anchor_name }}</text>
class="anchor-img" @error="liveInfo.anchor_img = $util.getDefaultImage().head" show-menu-by-longpress/>
<text class="anchor-name">{{ $lang('components-diy.diy-live.anchorPrefix') }}{{ liveInfo.anchor_name }}</text>
</block>
<text class="separate" v-if="value.isShowAnchorInfo && value.isShowLiveGood">|</text>
<block v-if="value.isShowLiveGood">
<text class="goods-text">直播商品:{{ liveInfo.goods.length }}</text>
<text class="goods-text">{{ $lang('components-diy.diy-live.goodsPrefix') }}{{ liveInfo.goods.length }}</text>
</block>
</view>
</view>
@@ -109,7 +109,6 @@ export default {
}
})
.catch(err => {
console.log('get live status', err);
});
// 往后间隔1分钟或更慢的频率去轮询获取直播状态
@@ -127,8 +126,7 @@ export default {
clearInterval(timer);
}
})
.catch(err => {
console.log('get live status', err);
.catch(err => {
});
}, 60000);
// #endif

View File

@@ -13,7 +13,7 @@
<div
style="position:absolute;right:12rpx;bottom:48rpx;z-index:1;background:#4390FF;padding:0rpx 20rpx;border-radius:8rpx;color: #fff;"
@tap.stop="handlerClick(item)">
<span style="font-size:24rpx;color: #fff;">一键导航</span>
<span style="font-size:24rpx;color: #fff;">{{ $lang('components-diy.diy-map.navigate') }}</span>
</div>
</map>
</view>
@@ -71,7 +71,7 @@ export default {
uni.openLocation({
latitude: parseFloat(item.lat),
longitude: parseFloat(item.lng),
name: "一键导航",
name: this.$lang('components-diy.diy-map.navigate'),
})
},
async handlerClick(item) {

View File

@@ -6,13 +6,13 @@
<view class="info-wrap" :style="infoStyle" v-if="memberInfo">
<view class="headimg" @tap.stop="getWxAuth">
<image :src="memberInfo.headimg ? $util.img(memberInfo.headimg) : $util.getDefaultImage().head"
mode="widthFix" @error="memberInfo.headimg = $util.getDefaultImage().head" />
mode="widthFix" @error="memberInfo.headimg = $util.getDefaultImage().head" show-menu-by-longpress/>
</view>
<view class="info">
<!-- #ifdef MP -->
<block
v-if="(memberInfo.nickname.indexOf('u_') != -1 && memberInfo.nickname == memberInfo.username) || memberInfo.nickname == memberInfo.mobile">
<view class="nickname"><text class="name" @tap.stop="getWxAuth">点击授权头像昵称</text></view>
<view class="nickname"><text class="name" @tap.stop="getWxAuth">{{ $lang('components-diy.diy-member-info.clickToAuthorizeAvatarNickname') }}</text></view>
</block>
<view class="nickname" v-else>
<text class="name" @tap.stop="getWxAuth">{{ memberInfo.nickname }}</text>
@@ -36,7 +36,7 @@
<!-- #ifdef H5 -->
<block
v-if="$util.isWeiXin() && ((memberInfo.nickname.indexOf('u_') != -1 && memberInfo.nickname == memberInfo.username) || memberInfo.nickname == memberInfo.mobile)">
<view class="nickname"><text class="name" @tap.stop="getWxAuth">点击获取微信头像</text></view>
<view class="nickname"><text class="name" @tap.stop="getWxAuth">{{ $lang('components-diy.diy-member-info.clickToGetWechatAvatar') }}</text></view>
</block>
<view class="nickname" v-else>
<text class="name" @tap.stop="redirect('/pages_tool/member/info')">{{ memberInfo.nickname
@@ -66,11 +66,11 @@
<view class="info-wrap" v-else :style="infoStyle" @tap.stop="redirect($util.MEMBER_PAGE_URL)">
<view class="headimg">
<image :src="$util.getDefaultImage().head" mode="widthFix"></image>
<image :src="$util.getDefaultImage().head" mode="widthFix" show-menu-by-longpress></image>
</view>
<view class="info">
<view class="nickname"><text class="name">{{ $lang('login') }}</text></view>
<view class="desc">{{ $lang('loginTpis') }}</view>
<view class="nickname"><text class="name">{{ $lang('member.index.login') }}</text></view>
<view class="desc">{{ $lang('member.index.loginTips') }}</view>
</view>
<view v-if="ischina == 1"
@@ -85,19 +85,19 @@
{{ memberInfo ? (parseFloat(memberInfo.balance) +
parseFloat(memberInfo.balance_money)).toFixed(2) : '--' }}
</view>
<view class="title">{{ $lang('balance') }}</view>
<view class="title">{{ $lang('member.index.balance') }}</view>
</view>
<view class="solid"></view>
<view class="account-item" @tap.stop="redirect('/pages_tool/member/point_detail')">
<view class="value price-font">{{ memberInfo ? parseFloat(memberInfo.point) : '--' }}</view>
<view class="title">{{ $lang('point') }}</view>
<view class="title">{{ $lang('member.index.point') }}</view>
</view>
<view class="solid"></view>
<view class="account-item" @tap.stop="redirect('/pages_tool/member/coupon')">
<view class="value price-font">
{{ memberInfo && memberInfo.coupon_num != undefined ? memberInfo.coupon_num : '--' }}
</view>
<view class="title">{{ $lang('coupon') }}</view>
<view class="title">{{ $lang('member.index.coupon') }}</view>
</view>
</view>
<!--
@@ -117,7 +117,7 @@
</block>
<block v-if="value.style == 3">
<view class="super-info">
<image :src="$util.img('public/uniapp/member/open_member.png')" class="title" mode="heightFix" />
<image :src="$util.img('public/uniapp/member/open_member.png')" class="title" mode="heightFix" show-menu-by-longpress/>
<view class="desc">开通可享更多权益</view>
</view>
<view class="super-text">
@@ -130,7 +130,7 @@
<view class="member-info-style4" v-show="value.style == 4">
<view class="super-member" v-if="superMember" :style="superMemberStyle">
<view class="super-info">
<image :src="$util.img('app/component/view/member_info/img/style_4_vip_huangguan.png')" class="title" mode="widthFix" />
<image :src="$util.img('app/component/view/member_info/img/style_4_vip_huangguan.png')" class="title" mode="widthFix" show-menu-by-longpress/>
<view class="desc">开通可享更多权益</view>
</view>
<view class="super-text" :class="{ 'more' : memberInfo && memberInfo.member_level_type }">
@@ -172,19 +172,19 @@
<view class="account-item" @tap.stop="redirect('/pages_tool/member/balance')">
<view class="value price-font">{{ memberInfo ? (parseFloat(memberInfo.balance) +
parseFloat(memberInfo.balance_money)).toFixed(2) : '--' }}</view>
<view class="title">{{ $lang('balance') }}</view>
<view class="title">{{ $lang('member.index.balance') }}</view>
</view>
<view class="solid"></view>
<view class="account-item" @tap.stop="redirect('/pages_tool/member/point_detail')">
<view class="value price-font">{{ memberInfo ? parseFloat(memberInfo.point) : '--' }}</view>
<view class="title">{{ $lang('point') }}</view>
<view class="title">{{ $lang('member.index.point') }}</view>
</view>
<view class="solid"></view>
<view class="account-item" @tap.stop="redirect('/pages_tool/member/coupon')">
<view class="value price-font">
{{ memberInfo && memberInfo.coupon_num != undefined ? memberInfo.coupon_num : '--' }}
</view>
<view class="title">{{ $lang('coupon') }}</view>
<view class="title">{{ $lang('member.index.coupon') }}</view>
</view>
</view>
</view>
@@ -194,40 +194,40 @@
<uni-popup ref="completeInfoPopup" type="bottom" :maskClick="false">
<view class="complete-info-wrap">
<view class="head">
<text class="title">获取您的昵称、头像</text>
<text class="color-tip tips">获取用户头像、昵称完善个人资料,主要用于向用户提供具有辨识度的用户中心界面</text>
<text class="title">{{ $lang('components-diy.diy-member-info.completeInfoTitle') }}</text>
<text class="color-tip tips">{{ $lang('components-diy.diy-member-info.completeInfoTip') }}</text>
<text class="iconfont icon-close color-tip" @tap.stop="cancelCompleteInfo"></text>
</view>
<!-- #ifdef MP-WEIXIN -->
<view class="item-wrap">
<text class="label">头像</text>
<text class="label">{{ $lang('components-diy.diy-member-info.avatarLabel') }}</text>
<button open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
<image :src="avatarUrl ? avatarUrl : $util.getDefaultImage().head"
@error="avatarUrl = $util.getDefaultImage().head" mode="aspectFill" />
@error="avatarUrl = $util.getDefaultImage().head" mode="aspectFill" show-menu-by-longpress/>
<text class="iconfont icon-right color-tip"></text>
</button>
</view>
<view class="item-wrap">
<text class="label">昵称</text>
<input type="nickname" placeholder="请输入昵称" v-model="nickName" @blur="blurNickName" />
<text class="label">{{ $lang('components-diy.diy-member-info.nicknameLabel') }}</text>
<input type="nickname" :placeholder="$lang('components-diy.diy-member-info.nicknamePlaceholder')" v-model="nickName" @blur="blurNickName" />
</view>
<!-- #endif -->
<!-- #ifdef MP-ALIPAY -->
<view class="item-wrap">
<text class="label">头像</text>
<text class="label">{{ $lang('components-diy.diy-member-info.avatarLabel') }}</text>
<button open-type="getAuthorize" scope="userInfo" @getAuthorize="aliappGetUserinfo"
:plain="true" class="border-0">
<image :src="avatarUrl ? avatarUrl : $util.getDefaultImage().head"
@error="avatarUrl = $util.getDefaultImage().head" mode="aspectFill" />
@error="avatarUrl = $util.getDefaultImage().head" mode="aspectFill" show-menu-by-longpress/>
<text class="iconfont icon-right color-tip"></text>
</button>
</view>
<view class="item-wrap">
<text class="label">昵称</text>
<input type="nickname" placeholder="请输入昵称" v-model="nickName" @blur="blurNickName" />
<text class="label">{{ $lang('components-diy.diy-member-info.nicknameLabel') }}</text>
<input type="nickname" :placeholder="$lang('components-diy.diy-member-info.nicknamePlaceholder')" v-model="nickName" @blur="blurNickName" />
</view>
<!-- #endif -->
<button type="default" class="save-btn" @tap.stop="saveCompleteInfo" :disabled="isDisabled">保存</button>
<button type="default" class="save-btn" @tap.stop="saveCompleteInfo" :disabled="isDisabled">{{ $lang('components-diy.diy-member-info.save') }}</button>
</view>
</uni-popup>
</view>
@@ -493,8 +493,8 @@ export default {
showMemberQrcode() {
if (!this.memberInfo.mobile && !this.memberInfo.member_code) {
uni.showModal({
title: '提示',
content: '使用会员码需先绑定手机号,是否绑定手机号?',
title: this.$lang('components-diy.diy-member-info.tip'),
content: this.$lang('components-diy.diy-member-info.bindMobileTip'),
success: res => {
if (res.confirm) {
// #ifdef MP-WEIXIN
@@ -566,6 +566,10 @@ export default {
this.$util.redirectTo(url);
}
// #endif
// #ifndef MP || H5
this.$util.redirectTo(url);
// #endif
},
/**
* 获取微信授权
@@ -630,16 +634,19 @@ export default {
});
},
openCompleteInfoPop(callback) {
this.$refs.completeInfoPopup.open(() => {
this.$store.commit('setBottomNavHidden', false); //显示底部导航
});
this.$store.commit('setBottomNavHidden', true); // 隐藏底部导航
this.$refs.completeInfoPopup.open();
// 关闭时(setBottomNavHidden=false)由 saveCompleteInfo / cancelCompleteInfo 显式处理,
// 不在 open 回调里写 — 回调在"弹窗被销毁/页面被卸载"等异常路径下不保证触发,会卡住 TabBar 隐藏态
// TabBar 根页面(如会员中心)不能藏 TabBar — 否则会被自己藏起来
if (!this.$util.isCurrentPageTabBarRoot()) {
this.$store.commit('setBottomNavHidden', true); // 隐藏底部导航
}
this.completeInfoCallback = callback;
},
saveCompleteInfo() {
if (this.nickName.length == 0) {
this.$util.showToast({
title: '请输入昵称'
title: this.$lang('components-diy.diy-member-info.pleaseEnterNickname')
});
return;
}
@@ -678,7 +685,7 @@ export default {
},
fail: () => {
this.$util.showToast({
title: '上传失败'
title: this.$lang('components-diy.diy-member-info.uploadFailed')
});
}
})
@@ -709,7 +716,7 @@ export default {
},
fail: () => {
this.$util.showToast({
title: '头像拉取失败'
title: this.$lang('components-diy.diy-member-info.avatarPullFailed')
});
}
})
@@ -858,7 +865,11 @@ export default {
height: 120rpx;
border-top-left-radius: 10rpx;
border-top-right-radius: 10rpx;
background: linear-gradient(107deg, #7c7878 0%, #201a18 100%);
// P0: 用现有 token,主题切换时会员卡背景跟着变
// 旧字面: #7c7878 / #201a18(默认 preset 值) → 现在由 token 决定
// 兼容: 微信小程序 / 鸿蒙元服务 — var() 在 linear-gradient 中现代 runtime 均支持
background: #7c7878; // 兜底(微信小程序老 runtime 无 var() 兜底)
background: linear-gradient(107deg, var(--super-member-start-bg) 0%, var(--super-member-end-bg) 100%);
padding: 30rpx 40rpx;
box-sizing: border-box;
@@ -939,7 +950,12 @@ export default {
}
.super-text {
background-image: linear-gradient(90deg, #ffdba6 0%, #ffebca 49%, #f7c774 100%);
// P0: 3 停渐变 → 2 停(start + end),token 化
// 旧字面: #ffdba6 / #ffebca (默认 preset 文字色) + 中间色 #f7c774
// 中间色 #f7c774 不在 token 系统中,合并为 start→end 渐变(视觉差异可接受)
// 兼容: -webkit-background-clip: text 在微信小程序 / 鸿蒙元服务均支持
background: #ffdba6; // 兜底
background-image: linear-gradient(90deg, var(--super-member-start-text-color) 0%, var(--super-member-end-text-color) 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
display: flex;
@@ -989,7 +1005,11 @@ export default {
.super-member {
color: #8d4b16;
background: linear-gradient(107deg, #fadcb5 0%, #f6bd74 100%);
// P0 注释 A 修复: 之前这个渐变是 black preset 的字面,导致 data-style-2 在 default 主题下显示错误
// 现在用 var() 让主题切换时自动跟着变(无论 data-style-1 还是 data-style-2)
// 兼容: 同 865 行,微信小程序 / 鸿蒙元服务均 OK
background: #fadcb5; // 兜底
background: linear-gradient(107deg, var(--super-member-start-bg) 0%, var(--super-member-end-bg) 100%);
border-top-left-radius: 18rpx;
border-top-right-radius: 18rpx;

View File

@@ -6,7 +6,7 @@
style="margin-right: 10rpx;">
<view class="icon-block">
<template v-if="value.style == 3">
<image :src="$util.img('public/uniapp/member/order/wait_pay.png')" mode="widthFix" />
<image :src="$util.img('public/uniapp/member/order/wait_pay.png')" mode="widthFix" show-menu-by-longpress/>
<view class="icon-shade"
:style="'-webkit-mask-image: url(' + $util.img('public/uniapp/member/order/wait_pay_shade.png') + ')'">
</view>
@@ -25,7 +25,7 @@
style="margin-right: 10rpx;">
<view class="icon-block">
<template v-if="value.style == 3">
<image :src="$util.img('public/uniapp/member/order/wait_send.png')" mode="widthFix"></image>
<image :src="$util.img('public/uniapp/member/order/wait_send.png')" mode="widthFix" show-menu-by-longpress></image>
<view class="icon-shade"
:style="'-webkit-mask-image: url(' + $util.img('public/uniapp/member/order/wait_send_shade.png') + ')'">
</view>
@@ -44,7 +44,7 @@
style="margin-right: 10rpx;">
<view class="icon-block">
<template v-if="value.style == 3">
<image :src="$util.img('public/uniapp/member/order/wait_confirm.png')" mode="widthFix" />
<image :src="$util.img('public/uniapp/member/order/wait_confirm.png')" mode="widthFix" show-menu-by-longpress/>
<view class="icon-shade"
:style="'-webkit-mask-image: url(' + $util.img('public/uniapp/member/order/wait_confirm_shade.png') + ')'">
</view>
@@ -63,7 +63,7 @@
style="margin-right: 10rpx;">
<view class="icon-block">
<template v-if="value.style == 3">
<image :src="$util.img('public/uniapp/member/order/wait_use.png')" mode="widthFix" />
<image :src="$util.img('public/uniapp/member/order/wait_use.png')" mode="widthFix" show-menu-by-longpress/>
<view class="icon-shade"
:style="'-webkit-mask-image: url(' + $util.img('public/uniapp/member/order/wait_rate_shade.png') + ')'">
</view>
@@ -79,7 +79,7 @@
<view class="item-wrap" @tap.stop="redirect('/pages_tool/order/activist')">
<view class="icon-block">
<template v-if="value.style == 3">
<image :src="$util.img('public/uniapp/member/order/refunding.png')" mode="widthFix" />
<image :src="$util.img('public/uniapp/member/order/refunding.png')" mode="widthFix" show-menu-by-longpress/>
<view class="icon-shade"
:style="'-webkit-mask-image: url(' + $util.img('public/uniapp/member/order/refunding_shade.png') + ')'">
</view>

View File

@@ -5,15 +5,15 @@
<view :class="['list-wrap', value.style]" :style="warpCss">
<view :class="['item', value.ornament.type]" v-for="(item, index) in list" :key="index"
:style="itemCss" @tap.stop="handlerClick(item)">
<view class="merch-img">
<view class="merch-img" @tap.stop="handlerClick(item)">
<image class="cover-img" :src="$util.img(item.merch_image)" mode="widthFix"
@error="imgError(index)" />
@error="imgError(index)" show-menu-by-longpress />
</view>
<view class="info-wrap">
<text class="title">{{ item.merch_name }}</text>
<text class="desc">{{ item.desc }}</text>
<view class="read-wrap"></view>
</view>
<text class="title" @tap.stop="handlerClick(item)">{{ item.merch_name }}</text>
<text class="desc">{{ item.desc }}</text>
<view class="read-wrap"></view>
</view>
</view>
</view>
</view>
@@ -27,14 +27,16 @@
<view class="merch-nav-item graphic" v-for="(item, index) in list" :key="index"
:style="{ width: 100 / 4 + '%' }" @tap.stop="handlerClick(item)">
<view class="graphic-img" v-if="value.mode != 'text'"
:style="{ fontSize: value.imageSize * 2 + 'rpx', width: value.imageSize * 2 + 'rpx', height: value.imageSize * 2 + 'rpx' }">
:style="{ fontSize: value.imageSize * 2 + 'rpx', width: value.imageSize * 2 + 'rpx', height: value.imageSize * 2 + 'rpx' }"
@tap.stop="handlerClick(item)">
<image
:src="$util.img(item.merch_image) || $util.img('public/uniapp/default_img/goods.png')"
mode="aspectFill" :show-menu-by-longpress="true"
mode="aspectFill" show-menu-by-longpress
style="max-width: 80rpx; max-height: 80rpx; border-radius: 50rpx;" />
</view>
<text class="graphic-text"
style="font-size: 28rpx; font-weight: normal; color: rgb(48, 49, 51);">
style="font-size: 28rpx; font-weight: normal; color: rgb(48, 49, 51);"
@tap.stop="handlerClick(item)">
{{ item.merch_name }}
</text>
</view>
@@ -62,31 +64,31 @@ export default {
list: [
/*{
merch_name:'品牌',
merch_image:'http://saas.cn//upload/4/common/images/20240824/20240824040223172448654356147.jpg'
merch_image:'https://saas.cn//upload/4/common/images/20240824/20240824040223172448654356147.jpg'
},
{
merch_name:'品牌',
merch_image:'http://saas.cn//upload/4/common/images/20240824/20240824040223172448654356147.jpg'
merch_image:'https://saas.cn//upload/4/common/images/20240824/20240824040223172448654356147.jpg'
},
{
merch_name:'品牌',
merch_image:'http://saas.cn//upload/4/common/images/20240824/20240824040223172448654356147.jpg'
merch_image:'https://saas.cn//upload/4/common/images/20240824/20240824040223172448654356147.jpg'
},
{
merch_name:'品牌',
merch_image:'http://saas.cn//upload/4/common/images/20240824/20240824040223172448654356147.jpg'
merch_image:'https://saas.cn//upload/4/common/images/20240824/20240824040223172448654356147.jpg'
},
{
merch_name:'品牌',
merch_image:'http://saas.cn//upload/4/common/images/20240824/20240824040223172448654356147.jpg'
merch_image:'https://saas.cn//upload/4/common/images/20240824/20240824040223172448654356147.jpg'
},
{
merch_name:'品牌',
merch_image:'http://saas.cn//upload/4/common/images/20240824/20240824040223172448654356147.jpg'
merch_image:'https://saas.cn//upload/4/common/images/20240824/20240824040223172448654356147.jpg'
},
{
merch_name:'品牌',
merch_image:'http://saas.cn//upload/4/common/images/20240824/20240824040223172448654356147.jpg'
merch_image:'https://saas.cn//upload/4/common/images/20240824/20240824040223172448654356147.jpg'
}*/
],
loading: true,
@@ -119,7 +121,6 @@ export default {
obj += 'border-bottom-left-radius:' + this.value.bottomAroundRadius * 2 + 'rpx;';
obj += 'border-bottom-right-radius:' + this.value.bottomAroundRadius * 2 + 'rpx;';
}
console.log(obj)
return obj;
},
// 子项样式
@@ -140,14 +141,12 @@ export default {
}
return obj;
}
},
},
methods: {
getList() {
console.log(121)
var data = {
num: this.value.count
};
console.log(this.value)
if (this.value.sources == 'diy') {
data.num = 0;
data.merch_id_arr = this.value.merchIds.toString();

View File

@@ -25,10 +25,10 @@
<view class="notes-img-wrap" :class="{ 'notes-img-wrap-list': item.cover_type == 1 }">
<image v-if="item.cover_type == 0" :src="$util.img(item.img)" @error="imageError(i)"
mode="aspectFill" class="notes-item-image" />
mode="aspectFill" class="notes-item-image" show-menu-by-longpress/>
<image v-else v-for="(imgItem, imgIndex) in item.img" :key="imgIndex"
:src="$util.img(imgItem)" @error="imageError(i)" mode="aspectFit"
class="notes-item-image-li" />
class="notes-item-image-li" show-menu-by-longpress/>
</view>
<view class="notes-item-con">
@@ -39,14 +39,14 @@
item.update_time_day }}</text>
</view>
<view class="notes-num">
<text v-show="value.readNum == 1 && item.is_show_read_num == 1">阅读 {{
item.initial_read_num + item.read_num }}</text>
</view>
<text v-show="value.readNum == 1 && item.is_show_read_num == 1">{{ $lang('components-diy.diy-notes.readPrefix') }} {{
item.initial_read_num + item.read_num }}</text>
</view>
</view>
</view>
</view>
</scroll-view>
</view>
</scroll-view>
<ns-login ref="login"></ns-login>
</view>

View File

@@ -9,7 +9,8 @@
<view class="notice-xian"></view>
<view class="main-wrap">
<!-- 横向滚动 -->
<view class="horizontal-wrap" v-if="value.scrollWay == 'horizontal'">
<view class="horizontal-wrap" v-if="value.scrollWay == 'horizontal'"
@tap="toLink(list[0])">
<view class="marquee-wrap">
<view class="marquee" :style="marqueeStyle">
<text v-for="(item, index) in list" :key="index"
@@ -27,7 +28,8 @@
<!-- 上下滚动 -->
<template v-if="value.scrollWay == 'upDown'">
<swiper :vertical="true" :duration="500" autoplay="true" circular="true">
<swiper-item v-for="(item, index) in list" :key="index" @touchmove.prevent.stop>
<swiper-item v-for="(item, index) in list" :key="index"
@touchmove.prevent.stop @tap="toLink(item)">
<text class="beyond-hiding using-hidden"
:style="{ color: value.textColor, fontSize: value.fontSize * 2 + 'rpx', fontWeight: value.fontWeight }">
{{ item.title }}
@@ -42,11 +44,11 @@
<uni-popup ref="noticePopup" type="center">
<view class="notice-popup">
<view class="head-wrap" @tap.stop="closeNoticePopup">
<text>公告</text>
<text>{{ $lang('components-diy.diy-notice.notice') }}</text>
<text class="iconfont icon-close"></text>
</view>
<view class="content-wrap">{{ notice }}</view>
<button type="primary" @tap.stop="closeNoticePopup">我知道了</button>
<button type="primary" @tap.stop="closeNoticePopup">{{ $lang('components-diy.diy-notice.gotIt') }}</button>
</view>
</uni-popup>
</view>
@@ -136,11 +138,11 @@ export default {
});
} else if (!item) {
this.$util.redirectTo('/pages_tool/notice/list');
} else if (Object.keys(item.link).length > 1) {
} else if (item.link && (item.link.wap_url || item.link.appid || item.link.name)) {
this.$util.diyRedirectTo(item.link);
} else {
// 如果不设置跳转链接,则点击弹框展示
this.notice = item.title;
this.notice = item.content || item.title || '';
this.$refs.noticePopup.open();
}
},

View File

@@ -3,23 +3,23 @@
<view class="payment-qrocde-box">
<view class="qrocde-left">
<view class="qrocde-desc">
<text>门店消费时使用,支付时点击下方展示付款码</text>
<text>{{ $lang('components-diy.diy-payment-qrcode.description') }}</text>
<!-- <text class="iconfont icon-shuaxin"></text> -->
</view>
<view class="qrocde-action">
<button type="primary" @tap.stop="toLink">
<text class="iconfont icon-fukuanma"></text>
<text class="action-name">付款码</text>
<text class="action-name">{{ $lang('components-diy.diy-payment-qrcode.paymentCode') }}</text>
</button>
<button type="primary" @tap.stop="openPaymentPopup">
<text class="iconfont icon-saomafu"></text>
<text class="action-name">扫码付</text>
<text class="action-name">{{ $lang('components-diy.diy-payment-qrcode.scanToPay') }}</text>
</button>
</view>
</view>
<view class="qrocde-right">
<text class="iconfont icon-zhifu"></text>
<text class="name">门店支付</text>
<text class="name">{{ $lang('components-diy.diy-payment-qrcode.storePayment') }}</text>
</view>
</view>
@@ -27,11 +27,11 @@
<uni-popup ref="paymentPopup" type="center">
<view class="payment-popup">
<view class="head-wrap" @tap.stop="closePaymentPopup">
<text>提示</text>
<text>{{ $lang('components-diy.diy-payment-qrcode.popupTipTitle') }}</text>
<text class="iconfont icon-close"></text>
</view>
<view class="content-wrap">扫码付请退出程序后直接使用微信扫一扫或返回上一页使用付款码进行支付</view>
<button type="primary" @tap.stop="closePaymentPopup">我知道了</button>
<view class="content-wrap">{{ $lang('components-diy.diy-payment-qrcode.scanToPayTip') }}</view>
<button type="primary" @tap.stop="closePaymentPopup">{{ $lang('components-diy.diy-payment-qrcode.gotIt') }}</button>
</view>
</uni-popup>
</view>
@@ -75,8 +75,6 @@ export default {
// 允许从相机和相册扫码,h5端不起作用
uni.scanCode({
success: function (res) {
console.log('条码类型:' + res.scanType);
console.log('条码内容:' + res.result);
}
});
// #endif

View File

@@ -1,16 +1,17 @@
<template>
<view data-component-name="diy-picture" class="diy-picture" :style="style">
<view class="fui-picture">
<view v-for="(item, index) in value.list" style="line-height: 0;">
<view v-for="(item, index) in value.list" :key="index" style="line-height: 0;">
<image mode="widthFix" style="width: 100%;height:auto" :src="$util.img(item.imageUrl)"
v-if="item.link.wap_url" @tap.stop="handlerClick(item)"></image>
v-if="item.link.wap_url" @tap.stop="handlerClick(item)" show-menu-by-longpress></image>
<image mode="widthFix" style="width: 100%;height:auto" :src="$util.img(item.imageUrl)" v-else
@tap.stop="handlerClick(item)"></image>
@tap.stop="handlerClick(item)" show-menu-by-longpress></image>
</view>
<!-- <view wx:if="{{!childitem.linkurl}}" bindtap="previewImg" data-src="{{childitem.imgurl}}" style="padding:{{diyitem.style.paddingtop==0?0:diyitem.style.paddingtop+'rpx'}} {{diyitem.style.paddingleft==0?0:diyitem.style.paddingleft+'rpx'}}" wx:for="{{diyitem.data}}" wx:for-index="childid" wx:for-item="childitem" wx:key="{{childid}}">
<image mode="widthFix" src="{{childitem.imgurl}}" style="{{bannerheight?'height:'+bannerheight+'px':'height:auto'}}"></image>
</view> -->
</view>
<ns-login ref="login"></ns-login>
</view>
</template>

View File

@@ -7,7 +7,7 @@
<view class="img-wrap" :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }">
<image :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }"
:src="$util.img(item.goods_image, { size: 'mid' })" mode="widthFix"
@error="imageError(index)" />
@error="imageError(index)" show-menu-by-longpress/>
</view>
<view class="content"
v-if="value.goodsNameStyle.control || value.priceStyle.mainControl || value.priceStyle.lineControl || value.btnStyle.control">
@@ -21,11 +21,11 @@
:style="{ color: value.theme == 'diy' ? value.groupStyle.bgColor : '', borderColor: value.theme == 'diy' ? value.groupStyle.bgColor : '' }">
<text class="iconfont icon-yonghu3"
:style="{ backgroundColor: value.theme == 'diy' ? value.groupStyle.bgColor : '' }"></text>
<text>{{ item.pintuan_num }}人团</text>
<text>{{ $lang('components-diy.diy-pinfan.peopleGroup', { num: item.pintuan_num }) }}</text>
</view>
<view v-if="value.saleStyle.control"
:style="{ color: value.theme == 'diy' ? value.saleStyle.color : '', borderColor: value.theme == 'diy' ? value.saleStyle.color : '' }">
<text>已拼{{ item.order_num }}件</text>
<text>{{ $lang('components-diy.diy-pinfan.soldCount', { num: item.order_num }) }}</text>
</view>
</view>
<view class="price-wrap">
@@ -49,10 +49,9 @@
borderRadius: value.btnStyle.aroundRadius * 2 + 'rpx'
}">
<text class="text">{{ value.btnStyle.text }}</text>
<text class="fan" v-if="item.reward_type == 4">返{{ item.reward_type_num }}积分</text>
<text class="fan" v-if="item.reward_type == 1 || item.reward_type == 2">返¥{{
item.reward_type_num }}</text>
<text class="fan" v-if="item.reward_type == 3">返优惠券</text>
<text class="fan" v-if="item.reward_type == 4">{{ $lang('components-diy.diy-pinfan.backPoints', { num: item.reward_type_num }) }}</text>
<text class="fan" v-if="item.reward_type == 1 || item.reward_type == 2">{{ $lang('components-diy.diy-pinfan.backCash', { num: item.reward_type_num }) }}</text>
<text class="fan" v-if="item.reward_type == 3">{{ $lang('components-diy.diy-pinfan.backCoupon') }}</text>
</button>
</view>
</view>
@@ -66,7 +65,7 @@
<view class="img-wrap" :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }">
<image :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }"
:src="$util.img(item.goods_image, { size: 'mid' })" mode="widthFix"
@error="imageError(index)" />
@error="imageError(index)" show-menu-by-longpress/>
</view>
<view :class="['content', { 'multi-content': value.nameLineMode == 'multiple' }]"
v-if="value.goodsNameStyle.control || value.priceStyle.mainControl">
@@ -78,21 +77,21 @@
<view v-if="value.groupStyle.control" class="num">
<text class="content-tuan-box"
:style="{ color: value.theme == 'diy' ? value.groupStyle.color : '', backgroundColor: value.theme == 'diy' ? value.groupStyle.bgColor : '' }">
{{ item.pintuan_num }}人团
{{ $lang('components-diy.diy-pinfan.peopleGroup', { num: item.pintuan_num }) }}
</text>
<text class="content-tuan-price"
:style="{ color: value.theme == 'diy' ? value.groupStyle.bgColor : '' }"
v-if="item.reward_type == 4">
返{{ item.reward_type_num }}积分
{{ $lang('components-diy.diy-pinfan.backPoints', { num: item.reward_type_num }) }}
</text>
<text class="content-tuan-price"
:style="{ color: value.theme == 'diy' ? value.groupStyle.bgColor : '' }"
v-if="item.reward_type == 1 || item.reward_type == 2">
返¥{{ item.reward_type_num }}
{{ $lang('components-diy.diy-pinfan.backCash', { num: item.reward_type_num }) }}
</text>
<text class="content-tuan-price"
:style="{ color: value.theme == 'diy' ? value.groupStyle.bgColor : '' }"
v-if="item.reward_type == 3">返优惠券</text>
v-if="item.reward_type == 3">{{ $lang('components-diy.diy-pinfan.backCoupon') }}</text>
</view>
<view class="price-wrap" v-if="value.priceStyle.mainControl">
<text class="unit price-style small"
@@ -117,7 +116,7 @@
<view class="img-wrap" :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }">
<image :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }"
:src="$util.img(item.goods_image, { size: 'mid' })" mode="widthFix"
@error="imageError(dataIndex)" />
@error="imageError(dataIndex)" show-menu-by-longpress/>
</view>
<view :class="['content', { 'multi-content': value.nameLineMode == 'multiple' }]"
v-if="value.goodsNameStyle.control || value.priceStyle.mainControl">
@@ -129,22 +128,22 @@
<view v-if="value.groupStyle.control" class="num">
<text class="content-tuan-box"
:style="{ color: value.theme == 'diy' ? value.groupStyle.color : '', backgroundColor: value.theme == 'diy' ? value.groupStyle.bgColor : '' }">
{{ item.pintuan_num }}人团
{{ $lang('components-diy.diy-pinfan.peopleGroup', { num: item.pintuan_num }) }}
</text>
<text class="content-tuan-price"
:style="{ color: value.theme == 'diy' ? value.groupStyle.bgColor : '' }"
v-if="item.reward_type == 4">
返{{ item.reward_type_num }}积分
{{ $lang('components-diy.diy-pinfan.backPoints', { num: item.reward_type_num }) }}
</text>
<text class="content-tuan-price"
:style="{ color: value.theme == 'diy' ? value.groupStyle.bgColor : '' }"
v-if="item.reward_type == 1 || item.reward_type == 2">
返¥{{ item.reward_type_num }}
{{ $lang('components-diy.diy-pinfan.backCash', { num: item.reward_type_num }) }}
</text>
<text class="content-tuan-price"
:style="{ color: value.theme == 'diy' ? value.groupStyle.bgColor : '' }"
v-if="item.reward_type == 3">
返优惠券
{{ $lang('components-diy.diy-pinfan.backCoupon') }}
</text>
</view>
<view class="price-wrap" v-if="value.priceStyle.mainControl">

View File

@@ -10,23 +10,23 @@
:style="{ fontSize: value.titleStyle.fontSize * 2 + 'rpx', color: value.titleStyle.textColor, fontWeight: value.titleStyle.fontWeight ? 'bold' : '' }">
{{ value.titleStyle.leftText }}
</view>
<image v-else class="left-img" :src="$util.img(value.titleStyle.leftImg)" mode="heightFix" />
<image v-else class="left-img" :src="$util.img(value.titleStyle.leftImg)" mode="heightFix" show-menu-by-longpress/>
<view class="head-content">
<view class="img-warp">
<block v-if="headData && headData.member_list && headData.member_list.length">
<image v-for="(item, index) in headData.member_list" :key="index"
:src="$util.img(item.member_img || 'public/static/img/default_img/square.png')"
mode="aspectFill" @error="headImageError(index)" />
mode="aspectFill" @error="headImageError(index)" show-menu-by-longpress/>
</block>
<block v-else>
<image :src="$util.img('public/static/img/default_img/square.png')" mode="aspectFill" />
<image :src="$util.img('public/static/img/default_img/square.png')" mode="aspectFill" />
<image :src="$util.img('public/static/img/default_img/square.png')" mode="aspectFill" />
<image :src="$util.img('public/static/img/default_img/square.png')" mode="aspectFill" show-menu-by-longpress/>
<image :src="$util.img('public/static/img/default_img/square.png')" mode="aspectFill" show-menu-by-longpress/>
<image :src="$util.img('public/static/img/default_img/square.png')" mode="aspectFill" show-menu-by-longpress/>
</block>
</view>
<view :style="{ color: value.titleStyle.textColor }">
<text>{{ value.titleStyle.virtualNum || headData.pintuan_count }}</text>
<text>{{ value.titleStyle.style == 'style-2' ? '人参与' : '人拼团成功' }}</text>
<text>{{ value.titleStyle.style == 'style-2' ? $lang('components-diy.diy-pintuan.peopleParticipating') : $lang('components-diy.diy-pintuan.peopleGroupSuccess') }}</text>
</view>
</view>
<view class="head-right"
@@ -43,7 +43,7 @@
<view class="img-wrap" :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }">
<image :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }"
:src="$util.img(item.goods_image, { size: 'mid' })" mode="widthFix"
@error="imageError(index)" />
@error="imageError(index)" show-menu-by-longpress/>
</view>
<view class="content"
v-if="value.goodsNameStyle.control || value.priceStyle.mainControl || value.priceStyle.lineControl || value.btnStyle.control">
@@ -59,11 +59,11 @@
}">
<text class="iconfont icon-yonghu3"
:style="{ backgroundColor: value.theme == 'diy' ? value.groupStyle.bgColorStart : '' }"></text>
<text>{{ item.pintuan_num }}人团</text>
<text>{{ $lang('components-diy.diy-pintuan.peopleGroup', { num: item.pintuan_num }) }}</text>
</view>
<view v-if="value.saleStyle.control"
:style="{ color: value.theme == 'diy' ? value.saleStyle.color : '', borderColor: value.theme == 'diy' ? value.saleStyle.color : '' }">
<text>已拼{{ item.order_num }}件</text>
<text>{{ $lang('components-diy.diy-pintuan.soldCount', { num: item.order_num }) }}</text>
</view>
</view>
@@ -105,12 +105,12 @@
<view class="img-wrap" :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }">
<image :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }"
:src="$util.img(item.goods_image, { size: 'mid' })" mode="widthFix"
@error="imageError(index)" />
@error="imageError(index)" show-menu-by-longpress/>
<view v-if="value.groupStyle.control && value.style == 'style-1'" class="num" :style="{
color: value.theme == 'diy' ? value.groupStyle.color : '',
background: value.theme == 'diy' ? 'linear-gradient(to right,' + value.groupStyle.bgColorStart + ',' + value.groupStyle.bgColorEnd + ')' : ''
}">
{{ item.pintuan_num }}人团
{{ $lang('components-diy.diy-pintuan.peopleGroup', { num: item.pintuan_num }) }}
</view>
</view>
<view :class="['content', { 'multi-content': value.nameLineMode == 'multiple' }]"
@@ -148,10 +148,10 @@
{{ '.' + item.pintuan_price.split('.')[1] }}
</text>
</view>
<view class="sale-action">去参团</view>
<view class="sale-action">{{ $lang('components-diy.diy-pintuan.joinGroup') }}</view>
</view>
<view class="sale-num" v-if="value.style == 'style-2'">已拼{{ item.sale_num }}件</view>
<view class="sale-num" v-if="value.style == 'style-2'">{{ $lang('components-diy.diy-pintuan.soldCount', { num: item.sale_num }) }}</view>
</view>
</view>
</scroll-view>
@@ -165,12 +165,12 @@
<view class="img-wrap" :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }">
<image :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }"
:src="$util.img(item.goods_image, { size: 'mid' })" mode="widthFix"
@error="imageError(dataIndex)" />
@error="imageError(dataIndex)" show-menu-by-longpress/>
<view v-if="value.groupStyle.control && value.style != 'style-2'" class="num" :style="{
color: value.theme == 'diy' ? value.groupStyle.color : '',
background: value.theme == 'diy' ? 'linear-gradient(to right,' + value.groupStyle.bgColorStart + ',' + value.groupStyle.bgColorEnd + ')' : ''
}">
{{ item.pintuan_num }}人团
{{ $lang('components-diy.diy-pintuan.peopleGroup', { num: item.pintuan_num }) }}
</view>
</view>
<view :class="['content', { 'multi-content': value.nameLineMode == 'multiple' }]"
@@ -192,7 +192,7 @@
{{ '.' + item.pintuan_price.split('.')[1] }}
</text>
</view>
<view class="sale-num" v-if="value.style == 'style-2'">已拼{{ item.sale_num }}件</view>
<view class="sale-num" v-if="value.style == 'style-2'">{{ $lang('components-diy.diy-pintuan.soldCount', { num: item.sale_num }) }}</view>
</view>
</view>
</swiper-item>
@@ -451,7 +451,10 @@ scroll-view ::-webkit-scrollbar {
width: 40rpx;
height: 40rpx;
border-radius: 50%;
border: 2rpx solid #ff3d3d;
// P0: 拼团头像红边框 → var(--pintuan-avatar-border)
// 兼容: 微信小程序 / 鸿蒙元服务 — border 接受 var() 无问题
// 注: 改名避免与现有 pintuan_label_color(白字)冲突
border: 2rpx solid var(--pintuan-avatar-border, #ff3d3d);
margin-left: -14rpx;
}
@@ -482,7 +485,10 @@ scroll-view ::-webkit-scrollbar {
align-items: center;
justify-content: center;
height: 36rpx;
background: linear-gradient(270deg, #ffbd5b 0%, #fd882e 100%);
// P0: 拼团头渐变 → var(--pintuan-label-grad-start/end)
// 兼容: 微信小程序 / 鸿蒙元服务 — linear-gradient 嵌套 var() 现代 runtime 支持
background: #ffbd5b; // 兜底
background: linear-gradient(270deg, var(--pintuan-label-grad-start, #ffbd5b) 0%, var(--pintuan-label-grad-end, #fd882e) 100%);
border-radius: 24rpx;
padding: 2rpx;
@@ -495,7 +501,9 @@ scroll-view ::-webkit-scrollbar {
text:nth-child(2) {
padding: 6rpx 4rpx 4rpx;
background-color: #fff;
color: #ffbd5b;
// P0: 拼团头文字色 → var(--pintuan-label-grad-start) 复用
// 兼容: 微信小程序 / 鸿蒙元服务 — color 接受 var() 无问题
color: var(--pintuan-label-grad-start, #ffbd5b);
border-radius: 50%;
transform: scale(0.6);
font-weight: bold;
@@ -799,7 +807,10 @@ scroll-view ::-webkit-scrollbar {
font-size: $font-size-tag;
width: 94rpx;
height: 44rpx;
background: linear-gradient(131deg, #3edb73 0%, #1db576 100%);
// P0: 拼团成功绿渐变 → var(--pintuan-success-start/end)
// 兼容: 微信小程序 / 鸿蒙元服务 — linear-gradient 嵌套 var() 现代 runtime 支持
background: #3edb73; // 兜底
background: linear-gradient(131deg, var(--pintuan-success-start, #3edb73) 0%, var(--pintuan-success-end, #1db576) 100%);
border-radius: 8rpx;
color: #fff;
text-align: center;

View File

@@ -7,7 +7,7 @@
<view class="img-wrap" :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }">
<image :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }"
:src="$util.img(item.goods_image, { size: 'mid' })" mode="widthFix"
@error="imageError(index)" />
@error="imageError(index)" show-menu-by-longpress/>
</view>
<view class="content"
v-if="value.goodsNameStyle.control || value.priceStyle.mainControl || value.btnStyle.control">
@@ -45,7 +45,7 @@
<view class="img-wrap" :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }">
<image :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }"
:src="$util.img(item.goods_image, { size: 'mid' })" mode="widthFix"
@error="imageError(index)" />
@error="imageError(index)" show-menu-by-longpress/>
</view>
<view :class="['content', { 'multi-content': value.nameLineMode == 'multiple' }]"
v-if="value.goodsNameStyle.control || value.priceStyle.mainControl">
@@ -79,7 +79,7 @@
<view class="img-wrap" :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }">
<image :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }"
:src="$util.img(item.goods_image, { size: 'mid' })" mode="widthFix"
@error="imageError(dataIndex)" />
@error="imageError(dataIndex)" show-menu-by-longpress/>
</view>
<view :class="['content', { 'multi-content': value.nameLineMode == 'multiple' }]"
v-if="value.goodsNameStyle.control || value.priceStyle.mainControl">

View File

@@ -10,7 +10,7 @@
<view class="quick-img" v-if="item.imageUrl || item.icon">
<image v-if="item.iconType == 'img'"
:src="$util.img(item.imageUrl) || $util.img('public/uniapp/default_img/goods.png')"
mode="heightFix" :show-menu-by-longpress="true"></image>
mode="heightFix" show-menu-by-longpress ></image>
<diy-icon v-if="item.iconType == 'icon'" :icon="item.icon"
:value="item.style ? item.style : null" :style="{ fontSize: '60rpx' }"></diy-icon>
</view>

View File

@@ -11,7 +11,7 @@
<view :class="['item', value.mode]" @tap.stop="handlerClick(value.list[0].link, value.list[0].imageUrl)"
:style="{ marginRight: value.imageGap * 2 + 'rpx', width: list[0].imgWidth, height: list[0].imgHeight + 'px' }">
<image :src="$util.img(value.list[0].imageUrl)" :mode="list[0].imageMode || 'scaleToFill'"
:style="list[0].pageItemStyle" :show-menu-by-longpress="true" />
:style="list[0].pageItemStyle" show-menu-by-longpress />
</view>
</view>
@@ -19,9 +19,9 @@
<template v-for="(item, index) in list">
<template v-if="index > 0">
<view :key="index" :class="['item', value.mode]" @tap.stop="handlerClick(item.link, item.imageUrl)"
:style="{ marginBottom: value.imageGap * 2 + 'rpx', width: item.imgWidth, height: item.imgHeight + 'px' }">
:style="{ marginBottom: index < list.length - 1 ? value.imageGap * 2 + 'rpx' : 0, width: item.imgWidth, height: item.imgHeight + 'px' }">
<image :src="$util.img(item.imageUrl)" :mode="item.imageMode || 'scaleToFill'"
:style="item.pageItemStyle" :show-menu-by-longpress="true" />
:style="item.pageItemStyle" show-menu-by-longpress />
</view>
</template>
</template>
@@ -35,7 +35,7 @@
:style="{ marginRight: value.imageGap * 2 + 'rpx', width: list[0].imgWidth, height: list[0].imgHeight + 'px' }"
@tap.stop="handlerClick(value.list[0].link, value.list[0].imageUrl)">
<image :src="$util.img(value.list[0].imageUrl)" :mode="list[0].imageMode || 'scaleToFill'"
:style="list[0].pageItemStyle" :show-menu-by-longpress="true" />
:style="list[0].pageItemStyle" show-menu-by-longpress />
</view>
</view>
@@ -44,7 +44,7 @@
:style="{ marginBottom: value.imageGap * 2 + 'rpx', width: list[1].imgWidth, height: list[1].imgHeight + 'px' }"
@tap.stop="handlerClick(value.list[1].link, value.list[1].imageUrl)">
<image :src="$util.img(value.list[1].imageUrl)" :mode="list[1].imageMode || 'scaleToFill'"
:style="list[1].pageItemStyle" :show-menu-by-longpress="true" />
:style="list[1].pageItemStyle" show-menu-by-longpress />
</view>
<view class="template-bottom">
<template v-for="(item, index) in list">
@@ -55,7 +55,7 @@
height: item.imgHeight + 'px'
}">
<image :src="$util.img(item.imageUrl)" :mode="item.imageMode || 'scaleToFill'"
:style="item.pageItemStyle" :show-menu-by-longpress="true" />
:style="item.pageItemStyle" show-menu-by-longpress />
</view>
</template>
</template>
@@ -68,7 +68,7 @@
@tap.stop="handlerClick(item.link, item.imageUrl)"
:style="{ marginRight: value.imageGap * 2 + 'rpx', marginBottom: value.imageGap * 2 + 'rpx', width: item.widthStyle, height: item.imgHeight + 'px' }">
<image :src="$util.img(item.imageUrl)" :mode="item.imageMode || 'scaleToFill'"
:style="item.pageItemStyle" :show-menu-by-longpress="true" />
:style="item.pageItemStyle" show-menu-by-longpress />
</view>
</template>
</view>
@@ -91,14 +91,52 @@ export default {
},
data() {
return {
customHtml: ''
customHtml: '',
processedList: []
};
},
created() {
if (this.value.mode == 'custom-rubik-cube') {
this.value.diyHtml = this.value.diyHtml.replace(/&quot;/g, '"');
this.customHtml = htmlParser(this.value.diyHtml);
} else {
this.processValue();
},
watch: {
value: {
handler() {
this.processValue();
},
deep: true
}
},
mixins: [DiyMinx],
computed: {
list() {
return this.processedList;
},
rubikCubeWrapCss() {
var obj = '';
obj += 'background-color:' + this.value.componentBgColor + ';';
if (this.value.componentAngle == 'round') {
obj += 'border-top-left-radius:' + this.value.topAroundRadius * 2 + 'rpx;';
obj += 'border-top-right-radius:' + this.value.topAroundRadius * 2 + 'rpx;';
obj += 'border-bottom-left-radius:' + this.value.bottomAroundRadius * 2 + 'rpx;';
obj += 'border-bottom-right-radius:' + this.value.bottomAroundRadius * 2 + 'rpx;';
}
return obj;
}
},
methods: {
// 统一处理 value prop:首次加载和 value 变化时都走这里
processValue() {
if (!this.value || !this.value.mode) return;
if (this.value.mode == 'custom-rubik-cube') {
const diyHtml = (this.value.diyHtml || '').replace(/&quot;/g, '"');
this.customHtml = htmlParser(diyHtml);
} else {
this.initList();
this.recalcLayout();
}
},
// 根据当前 mode 派发到对应的 calcXxx
recalcLayout() {
var singleRow = {
'row1-of2': {
ratio: 2,
@@ -125,34 +163,18 @@ export default {
} else if (this.value.mode == 'row1-lt-of1-tp-of2-bm') {
this.calcRowOneLeftOfOneTopOfTwoBottom();
}
}
},
mixins: [DiyMinx],
watch: {
// 组件刷新监听
componentRefresh: function (nval) { }
},
computed: {
list() {
var arr = JSON.parse(JSON.stringify(this.value.list));
arr.forEach((item, index) => {
item.pageItemStyle = this.countBorderRadius(this.value.mode, index);
});
return arr;
},
rubikCubeWrapCss() {
var obj = '';
obj += 'background-color:' + this.value.componentBgColor + ';';
if (this.value.componentAngle == 'round') {
obj += 'border-top-left-radius:' + this.value.topAroundRadius * 2 + 'rpx;';
obj += 'border-top-right-radius:' + this.value.topAroundRadius * 2 + 'rpx;';
obj += 'border-bottom-left-radius:' + this.value.bottomAroundRadius * 2 + 'rpx;';
obj += 'border-bottom-right-radius:' + this.value.bottomAroundRadius * 2 + 'rpx;';
initList() {
if (!this.value.list || !Array.isArray(this.value.list)) {
this.processedList = [];
return;
}
return obj;
}
},
methods: {
this.processedList = this.value.list.map((item, index) => {
const newItem = { ...item };
newItem.pageItemStyle = this.countBorderRadius(this.value.mode, index);
return newItem;
});
},
/**
* 魔方:单行多个,平分宽度
* 公式:
@@ -235,8 +257,6 @@ export default {
*/
calcRowOneLeftOfTwoRight() {
let rightHeight = 0; // 右侧两图平分高度
let divide = 'left'; // 划分规则,left:左,right:右
if (this.list[1].imgWidth === this.list[2].imgWidth) divide = 'right';
uni.getSystemInfo({
success: res => {
this.list.forEach((item, index) => {
@@ -246,12 +266,14 @@ export default {
item.imgWidth = item.imgWidth / 2;
item.imgHeight = item.imgWidth * ratio;
rightHeight = (item.imgHeight - uni.upx2px(this.value.imageGap * 2)) / 2;
item.imgWidth += 'px';
} else {
item.imgWidth = this.list[0].imgWidth;
item.imgHeight = rightHeight;
}
});
// 统一追加 px 单位
this.list.forEach((item) => {
item.imgWidth += 'px';
});
}
});
},
@@ -311,7 +333,6 @@ export default {
this.list.forEach((item, index) => {
item.imgWidth += 'px';
item.imgHeight;
});
}
});
@@ -482,7 +503,7 @@ export default {
// 一左两右
.rubik-cube .template-left,
.rubik-cube .template-right {
// width: 50%;
width: 50%;
box-sizing: border-box;
}

View File

@@ -5,7 +5,7 @@
@tap.stop="handlerSearchClick">
<block v-if="[1, 2].includes(value.searchStyle)">
<view class="img" v-if="value.searchStyle == 2 && value.iconType == 'img'">
<image :src="$util.img(value.imageUrl)" mode="heightFix" />
<image :src="$util.img(value.imageUrl)" mode="heightFix" show-menu-by-longpress/>
</view>
<diy-icon class="icon" v-if="value.searchStyle == 2 && value.iconType == 'icon'" :icon="value.icon"
:value="value.style ? value.style : 'null'"
@@ -28,11 +28,12 @@
@tap.stop="handlerSearchClick"
:placeholderStyle="placeholderStyle" />
<text class="search-content-btn" @tap.stop="handlerSearchClick"
:style="{ 'backgroundColor': value.pageBgColor ? value.pageBgColor : 'rgba(0,0,0,0)' }">搜索</text>
:style="{ 'backgroundColor': value.pageBgColor ? value.pageBgColor : 'rgba(0,0,0,0)' }"
>{{ $lang('components-diy.diy-search.searchBtn') }}</text>
</view>
<view class="img" v-if="value.iconType == 'img'"
@tap.stop="handlerRedirectToClick(value.searchLink)">
<image :src="$util.img(value.imageUrl)" mode="heightFix" />
<image :src="$util.img(value.imageUrl)" mode="heightFix" show-menu-by-longpress/>
</view>
<diy-icon class="icon" v-if="value.iconType == 'icon'" :icon="value.icon"
:value="value.style ? value.style : 'null'"

View File

@@ -11,12 +11,12 @@
:style="{ fontSize: value.titleStyle.fontSize * 2 + 'rpx', color: value.titleStyle.textColor, fontWeight: value.titleStyle.fontWeight ? 'bold' : '' }">
{{ value.titleStyle.leftText }}
</view>
<image v-else class="title-img" :src="$util.img(value.titleStyle.leftImg)" mode="heightFix" />
<image v-else class="title-img" :src="$util.img(value.titleStyle.leftImg)" mode="heightFix" show-menu-by-longpress/>
<text v-if="value.titleStyle.style == 'style-2' && isFuture"
:style="{ color: value.titleStyle.textColor }" class="seckill-style-name">距离开始</text>
:style="{ color: value.titleStyle.textColor }" class="seckill-style-name">{{ $lang('components-diy.diy-seckill.countdownStart') }}</text>
<view class="time" :style="{ background: value.titleStyle.timeBgColor }">
<text :style="{ color: value.titleStyle.textColor }" class="seckill-title-name text">{{ isFuture ?
'距离开始' : '距离结束' }}</text>
$lang('components-diy.diy-seckill.countdownStart') : $lang('components-diy.diy-seckill.countdownEnd') }}</text>
<text v-if="value.titleStyle.timeImageUrl"
:class="['seckill-title-name icon', value.titleStyle.timeImageUrl]"></text>
<text class="hour number" :style="titleTimeStyle">{{ seckillH ? seckillH : '00' }}</text>
@@ -40,7 +40,7 @@
<view class="img-wrap" :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }">
<image :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }"
:src="$util.img(item.goods_image, { size: 'mid' })" mode="widthFix"
@error="imageError(index)" />
@error="imageError(index)" show-menu-by-longpress/>
</view>
<view class="content">
<view class="goods-name" v-if="value.goodsNameStyle.control"
@@ -57,13 +57,13 @@
}">
<image v-if="value.style == 'style-2'" class="progress-bar"
:src="$util.img('public/uniapp/seckill/progress_bar_01.png')"
mode="widthFix" />
mode="widthFix" show-menu-by-longpress/>
</view>
</view>
<view class="num"
:style="{ color: value.theme == 'diy' ? value.saleStyle.color : '', borderColor: value.theme == 'diy' ? value.saleStyle.color : '' }">
已抢{{ item.goods_stock + item.sale_num ? ((item.sale_num / (item.goods_stock +
item.sale_num)) * 100).toFixed(2) : '0.00' }}%
{{ $lang('components-diy.diy-seckill.soldPercent', { percent: item.goods_stock + item.sale_num ? ((item.sale_num / (item.goods_stock +
item.sale_num)) * 100).toFixed(2) : '0.00' }) }}
</view>
</view>
<view class="bottom-wrap">
@@ -87,7 +87,7 @@
</view>
<view class="price-font" v-else>
<text
:style="{ color: value.theme == 'diy' ? value.priceStyle.lineColor : '' }">原价:</text>
:style="{ color: value.theme == 'diy' ? value.priceStyle.lineColor : '' }">{{ $lang('components-diy.diy-seckill.originalPrice') }}</text>
<text :style="{ color: value.theme == 'diy' ? value.priceStyle.lineColor : '' }"
class="original-price">¥{{ item.price }}</text>
</view>
@@ -97,7 +97,7 @@
color: value.btnStyle.theme == 'diy' ? value.btnStyle.textColor : '',
borderRadius: value.btnStyle.aroundRadius * 2 + 'rpx'
}">
{{ isFuture ? '即将开始' : value.btnStyle.text }}
{{ isFuture ? $lang('components-diy.diy-seckill.comingSoon') : value.btnStyle.text }}
</button>
</view>
</view>
@@ -110,7 +110,7 @@
<view class="img-wrap" :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }">
<image :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }"
:src="$util.img(item.goods_image, { size: 'mid' })" mode="widthFix"
@error="imageError(index)" />
@error="imageError(index)" show-menu-by-longpress/>
</view>
<view class="content" v-if="value.goodsNameStyle.control || value.priceStyle.mainControl">
<view class="goods-name" v-if="value.goodsNameStyle.control"
@@ -140,7 +140,7 @@
color: value.btnStyle.theme == 'diy' ? value.btnStyle.textColor : '',
borderRadius: value.btnStyle.aroundRadius * 2 + 'rpx'
}">
{{ isFuture ? '即将开始' : value.btnStyle.text }}
{{ isFuture ? $lang('components-diy.diy-seckill.comingSoon') : value.btnStyle.text }}
</button>
</view>
</view>
@@ -155,7 +155,7 @@
<view class="img-wrap" :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }">
<image :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }"
:src="$util.img(item.goods_image, { size: 'mid' })" mode="widthFix"
@error="imageError(index)" />
@error="imageError(index)" show-menu-by-longpress/>
</view>
<view class="content" v-if="value.goodsNameStyle.control || value.priceStyle.mainControl">
<view class="goods-name" v-if="value.goodsNameStyle.control"
@@ -166,7 +166,7 @@
<view class="discount-price" v-if="value.priceStyle.mainControl">
<image v-if="value.style == 'style-2'" class="tag"
:src="$util.img('addon/seckill/component/view/seckill/img/style_4_tag.png')"
mode="widthFix" />
mode="widthFix" show-menu-by-longpress/>
<text class="unit price-style small"
:style="{ color: value.theme == 'diy' ? value.priceStyle.mainColor : '' }">¥</text>
<text class="price price-style large"
@@ -194,7 +194,7 @@
<view class="img-wrap" :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }">
<image :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }"
:src="$util.img(item.goods_image, { size: 'mid' })" mode="widthFix"
@error="imageError(dataIndex, pageIndex)" />
@error="imageError(dataIndex, pageIndex)" show-menu-by-longpress/>
</view>
<view class="content"
v-if="value.goodsNameStyle.control || value.priceStyle.mainControl">
@@ -206,7 +206,7 @@
<view class="discount-price" v-if="value.priceStyle.mainControl">
<image v-if="value.style == 'style-2'" class="tag"
:src="$util.img('addon/seckill/component/view/seckill/img/style_4_tag.png')"
mode="widthFix" />
mode="widthFix" show-menu-by-longpress/>
<text class="unit price-style small"
:style="{ color: value.theme == 'diy' ? value.priceStyle.mainColor : '' }">¥</text>
<text class="price price-style large"
@@ -502,7 +502,7 @@ export default {
toDetail(id) {
if (this.isFuture) {
this.$util.showToast({
title: '秒杀活动即将开启,敬请期待!'
title: this.$lang('components-diy.diy-seckill.seckillComingSoonTip')
});
return false;
}
@@ -796,12 +796,16 @@ scroll-view ::-webkit-scrollbar {
height: 20rpx;
border-radius: 20rpx;
margin-right: 20rpx;
background-color: #fcecd7;
// P0: 秒杀价签浅底 → var(--seckill-price-shallow)
// 兼容: 微信小程序 / 鸿蒙元服务 — background-color 接受 var() 无问题
background-color: var(--seckill-price-shallow, #fcecd7);
.curr {
height: 20rpx;
border-radius: 20rpx;
background-color: #fdbe6c;
// P0: 秒杀价签深色 → var(--seckill-price-start)
// 兼容: 微信小程序 / 鸿蒙元服务 — background-color 接受 var() 无问题
background-color: var(--seckill-price-start, #fdbe6c);
}
}
@@ -888,15 +892,21 @@ scroll-view ::-webkit-scrollbar {
.content .progress {
.num {
color: #ff3d3d;
// P0: 秒杀进度数字红 → var(--seckill-promo-color)
// 兼容: 微信小程序 / 鸿蒙元服务 — color 接受 var() 无问题
color: var(--seckill-promo-color, #ff3d3d);
}
.bg {
background-color: #ffd5d5;
// P0: 秒杀进度浅底 → var(--seckill-price-shallow) 复用
// 兼容: 微信小程序 / 鸿蒙元服务 — background-color 接受 var() 无问题
background-color: var(--seckill-price-shallow, #ffd5d5);
.curr {
position: relative;
background-color: #ff0400 !important;
// P0: 秒杀进度深红 → var(--seckill-discount-start) 复用
// 兼容: 微信小程序 / 鸿蒙元服务 — background-color 接受 var() 无问题
background-color: var(--seckill-discount-start, #ff0400) !important;
}
}
}
@@ -1178,7 +1188,10 @@ scroll-view ::-webkit-scrollbar {
white-space: nowrap;
font-weight: bold;
line-height: 1;
background: linear-gradient(to right, #ff5f17, #fe2f18);
// P0: 秒杀折扣红渐变 → var(--seckill-discount-start/end)
// 兼容: 微信小程序 / 鸿蒙元服务 — linear-gradient 嵌套 var() 现代 runtime 支持
background: #ff5f17; // 兜底
background: linear-gradient(to right, var(--seckill-discount-start, #ff5f17), var(--seckill-discount-end, #fe2f18));
padding: 4rpx 4rpx 4rpx 10rpx;
border-top-right-radius: 10rpx;
border-bottom-right-radius: 10rpx;

View File

@@ -7,23 +7,23 @@
<block v-if="globalStoreInfo && globalStoreInfo.store_id">
<text class="title">{{ globalStoreInfo.store_name }}</text>
<text>
<text class="change margin-left">切换</text>
<text class="change margin-left">{{ $lang('components-diy.diy-store.switchStore') }}</text>
<text class="iconfont icon-right"></text>
</text>
</block>
<text class="title" v-else>定位中...</text>
<text class="title" v-else>{{ $lang('components-diy.diy-store.locating') }}</text>
</view>
<view class="address-wrap" :style="{ color: value.textColor }">
<text class="iconfont icon-dizhi"></text>
<text v-if="globalStoreInfo && globalStoreInfo.store_id" @tap.stop="mapRoute" class="address">{{
globalStoreInfo.show_address }}</text>
<text v-else>获取当前位置...</text>
<text v-else>{{ $lang('components-diy.diy-store.gettingLocation') }}</text>
</view>
</view>
<view class="store-image" @tap.stop="selectStore()">
<image :src="$util.img(globalStoreInfo.store_image)"
v-if="globalStoreInfo && globalStoreInfo.store_image" mode="aspectFill"></image>
<image :src="$util.getDefaultImage().store" v-else mode="aspectFill"></image>
v-if="globalStoreInfo && globalStoreInfo.store_image" mode="aspectFill" show-menu-by-longpress></image>
<image :src="$util.getDefaultImage().store" v-else mode="aspectFill" show-menu-by-longpress></image>
</view>
</view>
</block>
@@ -33,18 +33,18 @@
<view class="store-info">
<view class="store-image" @tap.stop="selectStore()">
<image :src="$util.img(globalStoreInfo.store_image)"
v-if="globalStoreInfo && globalStoreInfo.store_image" mode="aspectFill"></image>
<image :src="$util.getDefaultImage().store" v-else mode="aspectFill"></image>
v-if="globalStoreInfo && globalStoreInfo.store_image" mode="aspectFill" show-menu-by-longpress></image>
<image :src="$util.getDefaultImage().store" v-else mode="aspectFill" show-menu-by-longpress></image>
</view>
<view class="info-box" :style="{ color: value.textColor }">
<block v-if="globalStoreInfo && globalStoreInfo.store_id">
<text class="title">{{ globalStoreInfo.store_name }}</text>
<text>
<text class="change margin-left">切换</text>
<text class="change margin-left">{{ $lang('components-diy.diy-store.switchStore') }}</text>
<text class="iconfont icon-right"></text>
</text>
</block>
<text class="title" v-else>定位中...</text>
<text class="title" v-else>{{ $lang('components-diy.diy-store.locating') }}</text>
</view>
</view>
<view class="store-icon" @tap.stop="search()"><text class="iconfont icon-sousuo3"
@@ -60,10 +60,10 @@
<text class="title" :style="{ color: value.textColor }">{{ globalStoreInfo.store_name }}</text>
<text class="iconfont icon-unfold" :style="{ color: value.textColor }"></text>
</block>
<text class="title" v-else>定位中...</text>
<text class="title" v-else>{{ $lang('components-diy.diy-store.locating') }}</text>
</view>
<view class="store-right-search">
<input type="text" class="uni-input font-size-tag" disabled placeholder="商品搜索"
<input type="text" class="uni-input font-size-tag" disabled :placeholder="$lang('components-diy.diy-store.searchPlaceholder')"
@tap.stop="search()" />
<text class="iconfont icon-sousuo3" @tap.stop="search()"></text>
</view>

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