Compare commits
424 Commits
main
...
yuanlaide3
| Author | SHA1 | Date | |
|---|---|---|---|
| a137f3533c | |||
| 8e31b9e327 | |||
| 460dbcb447 | |||
| 81ecd45de4 | |||
| 059630ba2c | |||
| 1ac0fb2484 | |||
| d8816bbe42 | |||
| b410597d9c | |||
| 1143ef7b72 | |||
| 987e75c65a | |||
| ac8c461546 | |||
| f3032a6004 | |||
| a4d8023e1f | |||
| bb0adb0542 | |||
| a4c218fecc | |||
| 0d820b04f7 | |||
| 70c9c49b94 | |||
| 6d1bdb5d8b | |||
| 73b7b2a8df | |||
| b2063418fb | |||
| 21c342e389 | |||
| cbf91fa905 | |||
| 61495b5e90 | |||
| 185d4914a6 | |||
| e3bbb7c77a | |||
| 4044070867 | |||
| 41b0d15570 | |||
| aafb75bad3 | |||
| 6e19bc7aff | |||
| 94e852032b | |||
| 5ccbc5d4f4 | |||
| cf6d54e2bf | |||
| 19bcf64844 | |||
| a27ae6cba0 | |||
| 660ab27377 | |||
| d78a23602e | |||
| 7a6495fa33 | |||
| 61e7a0d859 | |||
| 4116bfcbb0 | |||
| 29e96a9357 | |||
| 88024cbd11 | |||
| 55a9ed5946 | |||
| 165edc38ee | |||
| b20ab5bf5d | |||
| 05d6ea1e96 | |||
| 4c58db0710 | |||
| d7bc1165f7 | |||
| a32cedad9e | |||
| 7f2e5d3934 | |||
| 616fac0312 | |||
| 2c1703acc5 | |||
| 82f1659649 | |||
| 1c88bcf99b | |||
| 793b988376 | |||
| 313c283d9b | |||
| b10bf472e3 | |||
| 1814fffc12 | |||
| 13da4f1c9f | |||
| c8fada4b9d | |||
| 6c3f90bf96 | |||
| 229c6aa969 | |||
| 00bf4bcfd6 | |||
| cb5878ad29 | |||
| d213c5a488 | |||
| 3ac8162d9c | |||
| 873e1efe73 | |||
| c1289cd6b1 | |||
| b7cfa61a34 | |||
| 52f952a6df | |||
| fa082f59c1 | |||
| d8785d9d41 | |||
| 0312d00642 | |||
| 39d4264389 | |||
| ef407d6008 | |||
| aac44de359 | |||
| 2708ac55d1 | |||
| 3d822ed641 | |||
| e88dc2b205 | |||
| 83fc02a279 | |||
| edc077eef7 | |||
| 30cda71749 | |||
| cb9234bdac | |||
| 10bc06f212 | |||
| c739d691a2 | |||
| 0ca64b7dcf | |||
| 88921e61d2 | |||
| 6b8b4acc96 | |||
| edea8c32de | |||
| 3f09dca054 | |||
| aa15518980 | |||
| 8597504b57 | |||
| a913961be5 | |||
| a2066285cd | |||
| 397589c4e6 | |||
| c3cb420bf5 | |||
| bec47d1860 | |||
| 117cbccbd7 | |||
| 7a76824fcf | |||
| 75bc8876b5 | |||
| 203c47e437 | |||
| 6eaebc7d75 | |||
| 575145eae9 | |||
| 81e85c804a | |||
| 6178f699ed | |||
| 2276291a4b | |||
| acbb89997b | |||
| e04f5aabc0 | |||
| 013eef46fb | |||
| d9c6e41ebe | |||
| e3e63899d8 | |||
| 9d2b76687c | |||
| 679c53c501 | |||
| a90245b201 | |||
| 897a8157e7 | |||
| e8db412595 | |||
| 08e4d866f5 | |||
| d4794a7be4 | |||
| d0a3976cda | |||
| 94be20d499 | |||
| a7dd0b302e | |||
| fd4fd61399 | |||
| 7808c63a79 | |||
| 82fd3839a9 | |||
| b60ea984e5 | |||
| 3713cd2cf6 | |||
| 83a5f358e2 | |||
| bd1a9a67e0 | |||
| 224b409455 | |||
| 1c5cc62368 | |||
| aa7d967422 | |||
| 9815f09c1f | |||
| fc61a02211 | |||
| aebe8b557f | |||
| dd90d60a14 | |||
| 960f4ebaaa | |||
| 9dabcc2135 | |||
| 337a9618ef | |||
| f48b8f0e41 | |||
| bb18dedc35 | |||
| 55c4d507db | |||
| 014f111cd1 | |||
| 181717a7ab | |||
| 112c9a2aa5 | |||
| 6617a0b36c | |||
| c9c062edcb | |||
| f37baad045 | |||
| ea504d8434 | |||
| eb46748ae0 | |||
| 2d7d7f731c | |||
| 783c10fc62 | |||
| 92e8823566 | |||
| a27e3518da | |||
| e4c9b7fd59 | |||
| 94f3631421 | |||
| 80d390886a | |||
| b93badedd4 | |||
| d1e6cc3122 | |||
| 2a2161c9d9 | |||
| 6470912498 | |||
| f628d7a0ef | |||
| b8387de6c6 | |||
| 2705038c36 | |||
| f05eebad43 | |||
| 1e0a06850a | |||
| a88ecb9529 | |||
| 34f8ae2322 | |||
| cf6b683ffc | |||
| 0cdb956065 | |||
| d3e8b62581 | |||
| e1ce2ae268 | |||
| c86e688e47 | |||
| 2014d27834 | |||
| 15a61fdc39 | |||
| c430c8971c | |||
| de52406be8 | |||
| e749209128 | |||
| fbf2dfdcee | |||
| 563ab9274f | |||
| 5cfee417be | |||
| 5ae4bbcbd3 | |||
| c0220492a2 | |||
| 24ae55867a | |||
| b2eb04ab98 | |||
| 7045a05a73 | |||
| 4adaa945a1 | |||
| eef59211d3 | |||
| 07c38c1b1b | |||
| de4314ec9b | |||
| 50a1c1c695 | |||
| 55a5a68517 | |||
| e6d47a3d78 | |||
| 32db276e68 | |||
| 04a1d3c287 | |||
| d124d58552 | |||
| c7810f16f7 | |||
| c3956f7bcd | |||
| 3ef3d05624 | |||
| 509b4d2238 | |||
| 053a279102 | |||
| 3cedbd7b6b | |||
| 7e4400267e | |||
| 1150dad0b5 | |||
| 16cfe039ba | |||
| c629562190 | |||
| 2e535b9d93 | |||
| 0b760e41a3 | |||
| f794a2ae27 | |||
| aee630b546 | |||
| 95194585d2 | |||
| 55c8e58f32 | |||
| 1bf8a4a9b2 | |||
| ea40123c76 | |||
| bf4fe97aa3 | |||
| 84f5cd4568 | |||
| 4ae21c5d7a | |||
| f7fb9f34f9 | |||
| 66a579d48c | |||
| 066ca61d97 | |||
| 2d8846c64c | |||
| ca4e7fd170 | |||
| 5d3663786c | |||
| cc7125361f | |||
| 8e218bb663 | |||
| 5f41febd70 | |||
| a74263016b | |||
| 1f1a642f99 | |||
| 2e85cfd78c | |||
| 638406567d | |||
| b0dad04b59 | |||
| f258987e0e | |||
| 750ed2dac7 | |||
| 6c7f7d4837 | |||
| 0858618e77 | |||
| 1143175990 | |||
| e9483e26e5 | |||
| b30ba914b9 | |||
| 4715f06b2f | |||
| 47098bddda | |||
| cb81aad784 | |||
| d8705398bb | |||
| 23426b168f | |||
| 26eac57dc2 | |||
| 47f21f391c | |||
| a2a637c320 | |||
| 5ca4509d5b | |||
| a7541d0598 | |||
| d6633b698a | |||
| 4d89454a17 | |||
| 4b5dda9c4c | |||
| 9f07967982 | |||
| 2337e3cacf | |||
| 46508c7d55 | |||
| c59abc9545 | |||
| fce936feee | |||
| cc39e06161 | |||
| 014046bc9e | |||
| 45830ebda4 | |||
| 062fb3be90 | |||
| 02644e1959 | |||
| 315bdc71ff | |||
| f3d9f397d7 | |||
| b799e67e54 | |||
| 06e3a4d796 | |||
| 17864427c1 | |||
| 851b5fe722 | |||
| c2b38476ea | |||
| e9ee61f509 | |||
| c01a026149 | |||
| 2e85e11e92 | |||
| efd7cdb8d7 | |||
| e51c03235f | |||
| 92700f9a21 | |||
| c0e64437f0 | |||
| 6fb0e264b8 | |||
| 64d3ac8f8a | |||
| 6c6822ca16 | |||
| b86e8e7fa6 | |||
| 7b83636c99 | |||
| d01b0d46e4 | |||
| db1d47f456 | |||
| de4b510c00 | |||
| 089da9181b | |||
| c1d4a68e26 | |||
| f7f1b1191e | |||
| f9d144159a | |||
| 3952517ac9 | |||
| 01e7c3e981 | |||
| ebe2963466 | |||
| 5847612a58 | |||
| 4a5bac7aa5 | |||
| e3c69e7e32 | |||
| 12a1422470 | |||
| 48235c18a5 | |||
| fe9cbcd21d | |||
| 87fbda698c | |||
| 39ab70510c | |||
| ea01bbd260 | |||
| b3dd1af674 | |||
| bbe3d75267 | |||
| f11146013e | |||
| 7c7e67df4a | |||
| f5badc550c | |||
| 25636f8133 | |||
| 08caa49b43 | |||
| 555443dc44 | |||
| fae1d77ba5 | |||
| 2f5f23d21a | |||
| 071db2d70c | |||
| fd6527aa38 | |||
| 605ca69238 | |||
| 8c32f78503 | |||
| 14ba88b645 | |||
| 4f44b4f574 | |||
| dcc261b0d0 | |||
| d6c994e8f0 | |||
| e604a41e14 | |||
| 51ae3b1308 | |||
| 2ec9aa990f | |||
| a23d57547b | |||
| dc2018ee17 | |||
| cbbb1e0327 | |||
| 1ab8a52c38 | |||
| 6027f0d6de | |||
| 048305eb23 | |||
| 8f1eb1f5fe | |||
| 70cb01cfc0 | |||
| 719d32b77b | |||
| fe6c000fc7 | |||
| d4c1e1d6a5 | |||
| e9c679e1aa | |||
| 65b49fe4d5 | |||
| 5a0c903346 | |||
| 6690788a17 | |||
| 9b5275b6f6 | |||
| 1abc53734b | |||
| 829444231c | |||
| ffd046fc0a | |||
| 0f9647e7c5 | |||
| 23b5e91d11 | |||
| b8112e20d6 | |||
| 31b22e7225 | |||
| e86c5d874e | |||
| 49479ea24e | |||
| 0e409247cd | |||
| 0b06ad56dc | |||
| a27925c24f | |||
| 1b2a8f83c2 | |||
| 81570dda30 | |||
| db941673fc | |||
| f58a6723de | |||
| 61243b8dd4 | |||
| b08d7a389b | |||
| a1fc8f5955 | |||
| d3c34c3698 | |||
| 6410257a25 | |||
| f836254381 | |||
| 21252dc2ad | |||
| cc2ca14133 | |||
| dc4b3df715 | |||
| 6745f2093e | |||
| 3781e54a32 | |||
| 1edda80d21 | |||
| a443121426 | |||
| 5e5e5cb1d5 | |||
| 2bd94a1e5a | |||
| 58883b02f3 | |||
| 92549b979e | |||
| a929cfedb4 | |||
| abd6c122d5 | |||
| f7b1552239 | |||
| b5077b6a33 | |||
| 9f40ebc09e | |||
| dfbcd0c9a5 | |||
| 800cdbc805 | |||
| 8d350b24e5 | |||
| a6189a5f9e | |||
| 00870e4554 | |||
| 233093bebb | |||
| d082baa06f | |||
| 5ac7f3cf95 | |||
| 7526143c7d | |||
| 4377ab919f | |||
| 7c703ace4f | |||
| 6837a5d934 | |||
| 474b3a1091 | |||
| e4c905d278 | |||
| fb133ced3c | |||
| da17911a9c | |||
| 988b36ebb4 | |||
| fe2c53b43e | |||
| 9ed2acb8ae | |||
| f36f9ce992 | |||
| bca90e959e | |||
| 1615f9aafe | |||
| 1f6e260711 | |||
| dba637af38 | |||
| 68ed022c95 | |||
| 22a89013d0 | |||
| 107b5dd71b | |||
| 63789124f4 | |||
| a2dd7eb6f1 | |||
| d0e74a0925 | |||
| ccbce61755 | |||
| b827aba722 | |||
| 836eeb080e | |||
| 31c6914880 | |||
| 1ee402b581 | |||
| b1491ad69e | |||
| a954f9cc49 | |||
| 3a310f0b98 | |||
| 70fbdce641 | |||
| 861c43a428 | |||
| 556ce9d132 | |||
| 5c56cfaaa7 | |||
| 6d704f7f5a | |||
| 7580d8b763 | |||
| 76afe5f433 | |||
| 0bc1b5e90c | |||
| 9fc34ef467 | |||
| 7a713e07e1 | |||
| bd778c0283 | |||
| fed3962965 | |||
| 6de74a3baf | |||
| a4f2823e75 |
155
.claude/commands/opsx/apply.md
Normal file
155
.claude/commands/opsx/apply.md
Normal 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
|
||||||
160
.claude/commands/opsx/archive.md
Normal file
160
.claude/commands/opsx/archive.md
Normal 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
|
||||||
172
.claude/commands/opsx/explore.md
Normal file
172
.claude/commands/opsx/explore.md
Normal 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
|
||||||
107
.claude/commands/opsx/propose.md
Normal file
107
.claude/commands/opsx/propose.md
Normal 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
|
||||||
143
.claude/commands/opsx/sync.md
Normal file
143
.claude/commands/opsx/sync.md
Normal 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
|
||||||
159
.claude/skills/openspec-apply-change/SKILL.md
Normal file
159
.claude/skills/openspec-apply-change/SKILL.md
Normal 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
|
||||||
117
.claude/skills/openspec-archive-change/SKILL.md
Normal file
117
.claude/skills/openspec-archive-change/SKILL.md
Normal 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
|
||||||
287
.claude/skills/openspec-explore/SKILL.md
Normal file
287
.claude/skills/openspec-explore/SKILL.md
Normal 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
|
||||||
111
.claude/skills/openspec-propose/SKILL.md
Normal file
111
.claude/skills/openspec-propose/SKILL.md
Normal 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
|
||||||
147
.claude/skills/openspec-sync-specs/SKILL.md
Normal file
147
.claude/skills/openspec-sync-specs/SKILL.md
Normal 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
33
.github/workflows/i18n-audit.yml
vendored
Normal 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
11
.gitignore
vendored
@@ -1,5 +1,14 @@
|
|||||||
/unpackage
|
/unpackage
|
||||||
/.hbuilderx
|
|
||||||
/.idea
|
/.idea
|
||||||
|
/.logs
|
||||||
/node_modules
|
/node_modules
|
||||||
/iconfont-preview.html
|
/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
13
.hbuilderx/launch.json
Normal 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
43
.husky/pre-commit
Normal 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
|
||||||
132
.local.config.js
132
.local.config.js
@@ -18,6 +18,10 @@ const localDevConfig = ({
|
|||||||
uniacid: 2811,
|
uniacid: 2811,
|
||||||
domain: 'https://xcx6.aigc-quickapp.com/',
|
domain: 'https://xcx6.aigc-quickapp.com/',
|
||||||
},
|
},
|
||||||
|
'2881': { // 防爆电器
|
||||||
|
uniacid: 2881,
|
||||||
|
domain: 'https://xcx6.aigc-quickapp.com/',
|
||||||
|
},
|
||||||
'2724': { // 生物菌肥
|
'2724': { // 生物菌肥
|
||||||
uniacid: 2724,
|
uniacid: 2724,
|
||||||
domain: 'https://xcx.aigc-quickapp.com/',
|
domain: 'https://xcx.aigc-quickapp.com/',
|
||||||
@@ -38,29 +42,117 @@ const localDevConfig = ({
|
|||||||
uniacid: 1,
|
uniacid: 1,
|
||||||
domain: 'https://test.aigc-quickapp.com',
|
domain: 'https://test.aigc-quickapp.com',
|
||||||
},
|
},
|
||||||
|
'11-test': { // 测试平台
|
||||||
|
uniacid: 11,
|
||||||
|
domain: 'https://test.aigc-quickapp.com',
|
||||||
|
},
|
||||||
|
'18-test': { // 测试平台
|
||||||
|
uniacid: 18,
|
||||||
|
domain: 'https://test.aigc-quickapp.com',
|
||||||
|
},
|
||||||
'local-2': { // 测试平台
|
'local-2': { // 测试平台
|
||||||
uniacid: 2,
|
uniacid: 2,
|
||||||
domain: 'http://localhost:8050/',
|
domain: 'http://localhost:8050/',
|
||||||
},
|
},
|
||||||
'100': {
|
'local-1': { // 测试平台
|
||||||
uniacid: 100,
|
uniacid: 1,
|
||||||
domain: 'https://5g.aigc-quickapp.com/',
|
domain: 'http://192.168.197.1:8050/',
|
||||||
},
|
// domain: 'http://localhost:8050/',
|
||||||
'1': {
|
|
||||||
uniacid: 1,
|
|
||||||
domain: 'https://5g.aigc-quickapp.com/',
|
|
||||||
},
|
|
||||||
'115': {
|
|
||||||
uniacid: 115,
|
|
||||||
domain: 'https://5g.aigc-quickapp.com/',
|
|
||||||
},
|
|
||||||
'47': { // 修改弹窗
|
|
||||||
uniacid: 47,
|
|
||||||
domain: 'https://5g.aigc-quickapp.com/',
|
|
||||||
},
|
|
||||||
'2075': { //
|
|
||||||
uniacid: 2075,
|
|
||||||
domain: 'https://xcx.aigc-quickapp.com/',
|
|
||||||
},
|
},
|
||||||
})['1']; // 选择要使用的环境配置
|
'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/',
|
||||||
|
},
|
||||||
|
'54': { // 测试平台
|
||||||
|
uniacid: 54,
|
||||||
|
domain: 'https://test.aigc-quickapp.com',
|
||||||
|
},
|
||||||
|
'2': { // 测试平台
|
||||||
|
uniacid: 2,
|
||||||
|
domain: 'https://test.aigc-quickapp.com',
|
||||||
|
},
|
||||||
|
'54': { // 测试平台
|
||||||
|
uniacid: 54,
|
||||||
|
domain: 'https://test.aigc-quickapp.com',
|
||||||
|
},
|
||||||
|
// })['5g-237']; // 商品分类,没有立即咨询文字
|
||||||
|
// })['5g-97']; // 大宗商品贸易,支持自定义字体大小、颜色
|
||||||
|
// })['5g-50']; // 燃气安全产品机器人,购物车无反应
|
||||||
|
// })['2821']; // 离型纸硅油纸
|
||||||
|
})['54']; // 低空经济
|
||||||
|
// })['48']; // 离型纸硅油纸
|
||||||
|
// })['2485']; // 验证电子表单前后端数据一致性
|
||||||
|
// })['5g-11']; // 数码
|
||||||
|
// })['5g-213']; // 选择要使用的环境配置
|
||||||
|
// })['2811']; // 选择要使用的环境配置
|
||||||
|
// })['local-11']; // 选择要使用的环境配置
|
||||||
|
// })['local-1']; // 本地
|
||||||
|
// })['local-2']; // 本地
|
||||||
|
// })['local-11']; // 本地
|
||||||
|
// })['1-test']; // test
|
||||||
|
// })['18-test']; // test
|
||||||
export default localDevConfig;
|
export default localDevConfig;
|
||||||
392
App.vue
392
App.vue
@@ -1,42 +1,357 @@
|
|||||||
<script>
|
<script>
|
||||||
import auth from 'common/js/auth.js';
|
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 {
|
import {
|
||||||
Weixin
|
Weixin
|
||||||
} from 'common/js/wx-jssdk.js';
|
} 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 {
|
export default {
|
||||||
mixins: [auth],
|
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) {
|
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);
|
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();
|
uni.hideTabBar();
|
||||||
|
|
||||||
// #ifdef MP
|
// #ifdef MP
|
||||||
const updateManager = uni.getUpdateManager();
|
if (uni.getUpdateManager) {
|
||||||
updateManager.onCheckForUpdate(function(res) {
|
const updateManager = uni.getUpdateManager();
|
||||||
// 请求完新版本信息的回调
|
updateManager.onCheckForUpdate(function(res) {
|
||||||
});
|
// 请求完新版本信息的回调
|
||||||
|
|
||||||
updateManager.onUpdateReady(function(res) {
|
|
||||||
uni.showModal({
|
|
||||||
title: '更新提示',
|
|
||||||
content: '新版本已经准备好,是否重启应用?',
|
|
||||||
success(res) {
|
|
||||||
if (res.confirm) {
|
|
||||||
// 新的版本已经下载好,调用 applyUpdate 应用新版本并重启
|
|
||||||
updateManager.applyUpdate();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
});
|
|
||||||
|
|
||||||
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
|
// #endif
|
||||||
|
|
||||||
// #ifdef H5
|
// #ifdef H5
|
||||||
@@ -45,27 +360,22 @@
|
|||||||
}
|
}
|
||||||
// #endif
|
// #endif
|
||||||
|
|
||||||
uni.onNetworkStatusChange(function(res) {
|
if (uni.onNetworkStatusChange) {
|
||||||
if (!res.isConnected) {
|
uni.onNetworkStatusChange(function(res) {
|
||||||
uni.showModal({
|
if (!res.isConnected) {
|
||||||
title: '网络失去链接',
|
uni.showModal({
|
||||||
content: '请检查网络链接',
|
title: Lang.lang('common.networkLost'),
|
||||||
showCancel: false
|
content: Lang.lang('common.networkCheck'),
|
||||||
});
|
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');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// /api/config/init 已在 step 2.5 await 过 (含 800ms 超时), 此处不再重复触发
|
||||||
|
// 原 fire-and-forget 注释: 不阻塞后续同步 commit
|
||||||
|
// 现在 init 已被升级为 "首次配置等待通道", 这里留空以避免重复 dispatch
|
||||||
|
|
||||||
// 插件是否存在
|
// 插件是否存在
|
||||||
if (uni.getStorageSync('addonIsExist')) {
|
if (uni.getStorageSync('addonIsExist')) {
|
||||||
this.$store.commit('setAddonIsExist', uni.getStorageSync('addonIsExist'));
|
this.$store.commit('setAddonIsExist', uni.getStorageSync('addonIsExist'));
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ image {
|
|||||||
/* #ifdef H5 */
|
/* #ifdef H5 */
|
||||||
height: calc(100vh - 88rpx);
|
height: calc(100vh - 88rpx);
|
||||||
/* #endif */
|
/* #endif */
|
||||||
/* #ifdef MP-WEIXIN */
|
/* #ifdef MP */
|
||||||
height: 100vh;
|
height: 100vh;
|
||||||
/* #endif */
|
/* #endif */
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5705,9 +5705,9 @@
|
|||||||
|
|
||||||
@font-face {
|
@font-face {
|
||||||
font-family: "iconj"; /* Project id 1752049 */
|
font-family: "iconj"; /* Project id 1752049 */
|
||||||
src: url('//at.alicdn.com/t/c/font_1752049_n0jw9cvfunm.woff2?t=1727498649486') format('woff2'),
|
src: url('https://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('https://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');
|
url('https://at.alicdn.com/t/c/font_1752049_n0jw9cvfunm.ttf?t=1727498649486') format('truetype');
|
||||||
}
|
}
|
||||||
|
|
||||||
.iconj {
|
.iconj {
|
||||||
|
|||||||
@@ -23,6 +23,22 @@ page {
|
|||||||
$base-color: #ff4544;
|
$base-color: #ff4544;
|
||||||
$base-help-color: #ffb644; //辅助颜色
|
$base-help-color: #ffb644; //辅助颜色
|
||||||
--tab-bar-height: 112rpx;
|
--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 {
|
.uni-input-input:-webkit-autofill {
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ view {
|
|||||||
background-size: 100% 260rpx;
|
background-size: 100% 260rpx;
|
||||||
background-repeat: no-repeat;
|
background-repeat: no-repeat;
|
||||||
|
|
||||||
// #ifdef MP-WEIXIN
|
// #ifdef MP
|
||||||
background-size: 100% 380rpx;
|
background-size: 100% 380rpx;
|
||||||
// #endif
|
// #endif
|
||||||
|
|
||||||
@@ -52,7 +52,7 @@ view {
|
|||||||
background: linear-gradient(180deg, $base-color 10%, $color-bg 100%);
|
background: linear-gradient(180deg, $base-color 10%, $color-bg 100%);
|
||||||
background-size: 100% 260rpx;
|
background-size: 100% 260rpx;
|
||||||
|
|
||||||
// #ifdef MP-WEIXIN
|
// #ifdef MP
|
||||||
background-size: 100% 380rpx;
|
background-size: 100% 380rpx;
|
||||||
// #endif
|
// #endif
|
||||||
|
|
||||||
@@ -462,7 +462,10 @@ view {
|
|||||||
background: #f6f6cb;
|
background: #f6f6cb;
|
||||||
text-align: left;
|
text-align: left;
|
||||||
padding: 10rpx 20rpx;
|
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 {
|
.order-submit {
|
||||||
position: fixed;
|
position: fixed;
|
||||||
@@ -1286,9 +1289,13 @@ view {
|
|||||||
margin-right: 10rpx;
|
margin-right: 10rpx;
|
||||||
line-height: 1;
|
line-height: 1;
|
||||||
font-size: 36rpx;
|
font-size: 36rpx;
|
||||||
background-image:linear-gradient(156deg, #814635 0%, #3A221B 100%);
|
// P0: 会员图标渐变 → var(--member-icon-grad-start/end)
|
||||||
-webkit-background-clip:text;
|
// 注: 暂用 placeholder 命名,后续如需主题化可加到 style_color.js
|
||||||
-webkit-text-fill-color:transparent;
|
// 兼容: 微信小程序 / 鸿蒙元服务 — 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{
|
.info{
|
||||||
|
|||||||
@@ -1,9 +1,10 @@
|
|||||||
import Config from './config.js'
|
import Config from './config.js'
|
||||||
import http from './http.js'
|
import http from './http.js'
|
||||||
import store from '@/store/index.js'
|
import store from '@/store/index.js'
|
||||||
|
import lang from './lang.js'
|
||||||
|
|
||||||
let currentConversationId = null;
|
let currentConversationId = null;
|
||||||
const CONVERSATION_KEY = 'ai_conversation_id';
|
export const CONVERSATION_KEY = 'ai_conversation_id';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 获取域名配置参数(避免重复代码)
|
* 获取域名配置参数(避免重复代码)
|
||||||
@@ -26,6 +27,203 @@ try {
|
|||||||
console.warn('读取会话ID失败:', e);
|
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 {
|
export default {
|
||||||
/**
|
/**
|
||||||
* 获取uniacid
|
* 获取uniacid
|
||||||
@@ -43,12 +241,12 @@ export default {
|
|||||||
const params = {
|
const params = {
|
||||||
url: '/api/kefu/chat',
|
url: '/api/kefu/chat',
|
||||||
data: {
|
data: {
|
||||||
user_id: store.state.memberInfo?.id || 'anonymous',
|
user_id: getUserId(),
|
||||||
stream: false,
|
stream: false,
|
||||||
inputs: {},
|
inputs: {},
|
||||||
query: message,
|
query: message,
|
||||||
response_mode: 'blocking', // 强制 blocking
|
response_mode: 'blocking', // 强制 blocking
|
||||||
user: store.state.memberInfo?.id || 'anonymous',
|
user: getUserId(),
|
||||||
conversation_id: this.getConversationId() || '',
|
conversation_id: this.getConversationId() || '',
|
||||||
...getDomainParams()
|
...getDomainParams()
|
||||||
},
|
},
|
||||||
@@ -76,143 +274,47 @@ export default {
|
|||||||
uniacid: this.getUniacid(),
|
uniacid: this.getUniacid(),
|
||||||
token: store.state.token
|
token: store.state.token
|
||||||
});
|
});
|
||||||
throw new Error('AI服务暂时不可用,请稍后重试');
|
throw new Error(lang.lang('aiService.serviceUnavailable'));
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 流式消息入口(自动适配平台)
|
* 流式消息入口(自动适配平台)
|
||||||
|
* 微信小程序:复用长连接 WebSocket
|
||||||
*/
|
*/
|
||||||
async sendStreamMessage(message, onChunk, onComplete) {
|
async sendStreamMessage(message, onChunk, onComplete) {
|
||||||
// #ifdef MP-WEIXIN
|
// #ifdef MP
|
||||||
return new Promise((resolve, reject) => {
|
// 先确保连接已就绪
|
||||||
const match = Config.baseUrl.match(/^(?:https?:\/\/|wss?:\/\/)([^\/\s:]+)/);
|
try {
|
||||||
const domain = match ? match[1] : '';
|
await ensureWebSocketConnected();
|
||||||
|
} catch (e) {
|
||||||
|
if (onComplete) onComplete({ error: e.message });
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
|
||||||
// 修复 5:Domain 提取失败时提前拒绝
|
// 设置当前消息回调
|
||||||
if (!domain) {
|
wsMessageContent = '';
|
||||||
const errorMsg = 'WebSocket 域名配置无效';
|
wsMessageActive = true;
|
||||||
console.error(errorMsg);
|
wsMessageOnChunk = onChunk || null;
|
||||||
reject(new Error(errorMsg));
|
wsMessageOnComplete = onComplete || null;
|
||||||
if (onComplete) onComplete({ error: errorMsg });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const wssUrl = `wss://${domain}/ws/aikefu`;
|
return new Promise((resolve, reject) => {
|
||||||
const socketTask = wx.connectSocket({
|
wsMessageResolve = resolve;
|
||||||
url: wssUrl,
|
wsMessageReject = reject;
|
||||||
header: {}
|
|
||||||
});
|
|
||||||
|
|
||||||
let content = '';
|
wsSocketTask.send({
|
||||||
let conversationId = '';
|
data: JSON.stringify({
|
||||||
let isAuthenticated = false;
|
action: 'chat',
|
||||||
let closedNormally = false;
|
uniacid: this.getUniacid(),
|
||||||
let settled = false;
|
query: message,
|
||||||
|
user_id: getUserId(),
|
||||||
// 安全地拒绝(防止重复调用)
|
conversation_id: this.getConversationId() || '',
|
||||||
function safeReject(error) {
|
...getDomainParams()
|
||||||
if (settled) return;
|
})
|
||||||
settled = true;
|
});
|
||||||
clearTimeout(timeout);
|
});
|
||||||
reject(error);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 安全地完成
|
|
||||||
function safeResolve(result) {
|
|
||||||
if (settled) return;
|
|
||||||
settled = true;
|
|
||||||
clearTimeout(timeout);
|
|
||||||
resolve(result);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 安全地触发 onComplete
|
|
||||||
function safeComplete(result) {
|
|
||||||
if (onComplete) onComplete(result);
|
|
||||||
}
|
|
||||||
|
|
||||||
socketTask.onOpen(() => {
|
|
||||||
socketTask.send({
|
|
||||||
data: JSON.stringify({
|
|
||||||
action: 'auth',
|
|
||||||
uniacid: this.getUniacid(),
|
|
||||||
token: store.state.token || 'test_token',
|
|
||||||
user_id: store.state.memberInfo?.id || 'anonymous'
|
|
||||||
})
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
socketTask.onMessage((res) => {
|
|
||||||
try {
|
|
||||||
const data = JSON.parse(res.data);
|
|
||||||
|
|
||||||
if (data.type === 'auth_success') {
|
|
||||||
isAuthenticated = true;
|
|
||||||
socketTask.send({
|
|
||||||
data: JSON.stringify({
|
|
||||||
action: 'chat',
|
|
||||||
uniacid: this.getUniacid(),
|
|
||||||
query: message,
|
|
||||||
user_id: store.state.memberInfo?.id || 'anonymous',
|
|
||||||
conversation_id: this.getConversationId() || '',
|
|
||||||
...getDomainParams()
|
|
||||||
})
|
|
||||||
});
|
|
||||||
} else if (data.type === 'auth_failed') {
|
|
||||||
const errorMsg = '认证失败,请重新登录';
|
|
||||||
console.error(errorMsg, data);
|
|
||||||
safeComplete({ error: errorMsg });
|
|
||||||
safeReject(new Error(errorMsg));
|
|
||||||
socketTask.close();
|
|
||||||
}
|
|
||||||
|
|
||||||
// 处理流式消息块
|
|
||||||
else if (data.event === 'message') {
|
|
||||||
const text = data.answer || data.content || data.text || '';
|
|
||||||
content += text;
|
|
||||||
if (onChunk) onChunk(text);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 处理流结束
|
|
||||||
else if (data.event === 'message_end') {
|
|
||||||
conversationId = data.conversation_id || '';
|
|
||||||
if (conversationId) {
|
|
||||||
this.setConversationId(conversationId);
|
|
||||||
}
|
|
||||||
closedNormally = true;
|
|
||||||
safeComplete({ content, conversation_id: conversationId });
|
|
||||||
safeResolve({ content, conversation_id: conversationId });
|
|
||||||
socketTask.close();
|
|
||||||
}
|
|
||||||
|
|
||||||
// 可选:处理 done
|
|
||||||
else if (data.type === 'done') {
|
|
||||||
}
|
|
||||||
|
|
||||||
} catch (e) {
|
|
||||||
console.error('WebSocket 消息解析失败:', e, '原始数据:', res.data);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
socketTask.onError((err) => {
|
|
||||||
const errorMsg = 'WebSocket 连接失败';
|
|
||||||
console.error(errorMsg, err);
|
|
||||||
safeComplete({ error: errorMsg });
|
|
||||||
safeReject(new Error(errorMsg));
|
|
||||||
});
|
|
||||||
|
|
||||||
socketTask.onClose(() => {
|
|
||||||
if (!closedNormally && !settled) {
|
|
||||||
const errorMsg = 'WebSocket 连接意外关闭';
|
|
||||||
console.error(errorMsg);
|
|
||||||
safeComplete({ error: errorMsg });
|
|
||||||
safeReject(new Error(errorMsg));
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
});
|
|
||||||
// #endif
|
// #endif
|
||||||
},
|
},
|
||||||
/**
|
/**
|
||||||
* HTTP 流式请求(仅 H5 使用)
|
* HTTP 流式请求(仅 H5 使用)
|
||||||
*/
|
*/
|
||||||
@@ -232,14 +334,14 @@ export default {
|
|||||||
inputs: {},
|
inputs: {},
|
||||||
query: message,
|
query: message,
|
||||||
response_mode: 'streaming',
|
response_mode: 'streaming',
|
||||||
user_id: store.state.memberInfo?.id || 'anonymous',
|
user_id: getUserId(),
|
||||||
conversation_id: this.getConversationId() || '',
|
conversation_id: this.getConversationId() || '',
|
||||||
...getDomainParams()
|
...getDomainParams()
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!response.ok || !response.body) {
|
if (!response.ok || !response.body) {
|
||||||
throw new Error('无效响应');
|
throw new Error(lang.lang('aiService.invalidResponse'));
|
||||||
}
|
}
|
||||||
|
|
||||||
const reader = response.body.getReader();
|
const reader = response.body.getReader();
|
||||||
@@ -266,15 +368,21 @@ export default {
|
|||||||
if (jsonStr && jsonStr !== '[DONE]') {
|
if (jsonStr && jsonStr !== '[DONE]') {
|
||||||
const data = JSON.parse(jsonStr);
|
const data = JSON.parse(jsonStr);
|
||||||
if (data.event === 'message') {
|
if (data.event === 'message') {
|
||||||
const text = data.answer || data.text || '';
|
var text = data.answer || data.text || '';
|
||||||
|
// 兼容嵌套 data.data 格式
|
||||||
|
if (!text && data.data) {
|
||||||
|
text = data.data.content || data.data.answer || '';
|
||||||
|
}
|
||||||
content += text;
|
content += text;
|
||||||
if (onChunk) onChunk(text);
|
if (onChunk) onChunk(text);
|
||||||
}
|
}
|
||||||
if (data.conversation_id) {
|
// 兼容两种层级:conversation_id 可能在顶层或 data.data 中
|
||||||
conversationId = data.conversation_id;
|
var cid = data.conversation_id || (data.data && data.data.conversation_id) || '';
|
||||||
|
if (cid) {
|
||||||
|
conversationId = cid;
|
||||||
}
|
}
|
||||||
if (data.event === 'message_end') {
|
if (data.event === 'message_end' || data.event === 'done') {
|
||||||
// 可提前结束
|
console.log('[AI SSE] 收到完成信号:', data.event, 'conversationId:', cid);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -291,12 +399,16 @@ export default {
|
|||||||
if (jsonStr) {
|
if (jsonStr) {
|
||||||
const data = JSON.parse(jsonStr);
|
const data = JSON.parse(jsonStr);
|
||||||
if (data.event === 'message') {
|
if (data.event === 'message') {
|
||||||
const text = data.answer || '';
|
var text = data.answer || data.text || '';
|
||||||
|
if (!text && data.data) {
|
||||||
|
text = data.data.content || data.data.answer || '';
|
||||||
|
}
|
||||||
content += text;
|
content += text;
|
||||||
if (onChunk) onChunk(text);
|
if (onChunk) onChunk(text);
|
||||||
}
|
}
|
||||||
if (data.conversation_id) {
|
var cid = data.conversation_id || (data.data && data.data.conversation_id) || '';
|
||||||
conversationId = data.conversation_id;
|
if (cid) {
|
||||||
|
conversationId = cid;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -304,6 +416,7 @@ export default {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
console.log('[AI SSE] 流完成, conversationId:', conversationId, 'content长度:', content.length);
|
||||||
if (onComplete) {
|
if (onComplete) {
|
||||||
onComplete({ content, conversation_id: conversationId });
|
onComplete({ content, conversation_id: conversationId });
|
||||||
}
|
}
|
||||||
@@ -327,7 +440,7 @@ export default {
|
|||||||
messageId: response.data?.message_id
|
messageId: response.data?.message_id
|
||||||
};
|
};
|
||||||
} else {
|
} else {
|
||||||
throw new Error(response.message || 'AI服务返回错误');
|
throw new Error(response.message || lang.lang('aiService.serviceResponseError'));
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
@@ -368,19 +481,19 @@ export default {
|
|||||||
* 生成新会话(如需)
|
* 生成新会话(如需)
|
||||||
*/
|
*/
|
||||||
async generateConversationId() {
|
async generateConversationId() {
|
||||||
const params = {
|
const params = {
|
||||||
url: '/api/kefu/createConversation',
|
url: '/api/kefu/createConversation',
|
||||||
data: {
|
data: {
|
||||||
uniacid: this.getUniacid(),
|
uniacid: this.getUniacid(),
|
||||||
token: store.state.token || 'test_token',
|
token: store.state.token || 'test_token',
|
||||||
user_id: store.state.memberInfo?.id || 'anonymous',
|
user_id: getUserId(),
|
||||||
member_id: store.state.memberInfo?.id || 'anonymous',
|
member_id: getUserId(),
|
||||||
...getDomainParams()
|
...getDomainParams()
|
||||||
},
|
},
|
||||||
header: {
|
header: {
|
||||||
'Content-Type': 'application/json'
|
'Content-Type': 'application/json'
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
const response = await http.sendRequest({
|
const response = await http.sendRequest({
|
||||||
...params,
|
...params,
|
||||||
async: false
|
async: false
|
||||||
@@ -402,16 +515,46 @@ export default {
|
|||||||
.filter(item => item === 'healthy').length > 0;
|
.filter(item => item === 'healthy').length > 0;
|
||||||
return {
|
return {
|
||||||
available,
|
available,
|
||||||
reason: available ? '服务正常' : '服务异常'
|
reason: available ? lang.lang('aiService.statusNormal') : lang.lang('aiService.statusAbnormal')
|
||||||
};
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
return {
|
return {
|
||||||
available: false,
|
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;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 清除会话历史(调用后端接口)
|
* 清除会话历史(调用后端接口)
|
||||||
*/
|
*/
|
||||||
@@ -438,15 +581,16 @@ export default {
|
|||||||
async getConversationHistory(params = {}) {
|
async getConversationHistory(params = {}) {
|
||||||
try {
|
try {
|
||||||
if (!params.conversation_id) {
|
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 = {
|
const requestData = {
|
||||||
uniacid: params.uniacid || this.getUniacid(),
|
uniacid: params.uniacid || this.getUniacid(),
|
||||||
conversation_id: params.conversation_id,
|
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,
|
limit: params.limit || 20,
|
||||||
offset: params.offset || 0,
|
offset: params.offset || 0,
|
||||||
member_id: params.member_id || store.state.memberInfo?.id || 'anonymous',
|
member_id: params.member_id || getUserId(),
|
||||||
token: params.token || '',
|
token: params.token || '',
|
||||||
...getDomainParams()
|
...getDomainParams()
|
||||||
};
|
};
|
||||||
@@ -467,11 +611,11 @@ export default {
|
|||||||
page_info: response.data?.page_info || { limit: 20, offset: 0 }
|
page_info: response.data?.page_info || { limit: 20, offset: 0 }
|
||||||
};
|
};
|
||||||
} else {
|
} else {
|
||||||
throw new Error(response.message || '获取会话历史失败');
|
throw new Error(response.message || lang.lang('aiService.getHistoryFailed'));
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('获取会话历史失败:', error);
|
console.error('获取会话历史失败:', error);
|
||||||
throw new Error(error.message || '获取会话历史时发生错误,请稍后重试');
|
throw new Error(error.message || lang.lang('aiService.getHistoryError'));
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
@@ -489,8 +633,8 @@ export default {
|
|||||||
}
|
}
|
||||||
const paramsObj = {
|
const paramsObj = {
|
||||||
uniacid: this.getUniacid(),
|
uniacid: this.getUniacid(),
|
||||||
user_id: store.state.memberInfo?.id || 'anonymous',
|
user_id: getUserId(),
|
||||||
member_id: store.state.memberInfo?.id || 'anonymous',
|
member_id: getUserId(),
|
||||||
token: store.state.token || 'test_token',
|
token: store.state.token || 'test_token',
|
||||||
query: message,
|
query: message,
|
||||||
conversation_id: conversationId || '',
|
conversation_id: conversationId || '',
|
||||||
@@ -522,7 +666,7 @@ export default {
|
|||||||
};
|
};
|
||||||
eventSource.onerror = (error) => {
|
eventSource.onerror = (error) => {
|
||||||
console.error('EventSource错误:', error);
|
console.error('EventSource错误:', error);
|
||||||
if (onError) onError({ error: '连接失败' });
|
if (onError) onError({ error: lang.lang('aiService.connectionFailed') });
|
||||||
window.currentEventSource = null;
|
window.currentEventSource = null;
|
||||||
};
|
};
|
||||||
return eventSource;
|
return eventSource;
|
||||||
@@ -532,7 +676,7 @@ export default {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
// #endif
|
// #endif
|
||||||
// #ifdef MP-WEIXIN
|
// #ifdef MP
|
||||||
console.warn('chatWithEventSource 不支持微信小程序');
|
console.warn('chatWithEventSource 不支持微信小程序');
|
||||||
return null;
|
return null;
|
||||||
// #endif
|
// #endif
|
||||||
@@ -548,9 +692,23 @@ export default {
|
|||||||
onComplete?.({ message: res.content, conversation_id: res.conversation_id });
|
onComplete?.({ message: res.content, conversation_id: res.conversation_id });
|
||||||
});
|
});
|
||||||
// #endif
|
// #endif
|
||||||
// #ifdef MP-WEIXIN
|
// #ifdef MP
|
||||||
console.warn('chatWithFetchStream 不支持微信小程序');
|
console.warn('chatWithFetchStream 不支持微信小程序');
|
||||||
return null;
|
return null;
|
||||||
// #endif
|
// #endif
|
||||||
}
|
},
|
||||||
|
|
||||||
|
// #ifdef MP
|
||||||
|
/**
|
||||||
|
* [微信小程序] 断开 WebSocket 长连接(页面离开时调用)
|
||||||
|
*/
|
||||||
|
disconnectWebSocket() {
|
||||||
|
disconnectWebSocket();
|
||||||
|
},
|
||||||
|
// #endif
|
||||||
|
// #ifdef H5
|
||||||
|
disconnectWebSocket() {
|
||||||
|
// H5 无 WebSocket 长连接,无需操作
|
||||||
|
},
|
||||||
|
// #endif
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -8,9 +8,11 @@ export default {
|
|||||||
/**
|
/**
|
||||||
* 获取用户登录凭证code
|
* 获取用户登录凭证code
|
||||||
*/
|
*/
|
||||||
getCode(callback) {
|
getCode(callback, fallbackFunc) {
|
||||||
|
console.log(`-----> auth.js getCode`)
|
||||||
// 微信小程序
|
// 微信小程序
|
||||||
// #ifdef MP-WEIXIN
|
// #ifdef MP-WEIXIN
|
||||||
|
console.log(`微信小程序登录`)
|
||||||
uni.login({
|
uni.login({
|
||||||
provider: 'weixin',
|
provider: 'weixin',
|
||||||
timeout: 3000,
|
timeout: 3000,
|
||||||
@@ -29,12 +31,15 @@ export default {
|
|||||||
.unionid;
|
.unionid;
|
||||||
typeof callback == 'function' && callback(this.authInfo);
|
typeof callback == 'function' && callback(this.authInfo);
|
||||||
} else {
|
} else {
|
||||||
|
fallbackFunc && fallbackFunc(res);
|
||||||
this.$util.showToast({
|
this.$util.showToast({
|
||||||
title: res.message ? res.message : '小程序配置错误'
|
title: res.message ? res.message : this.$lang('auth.miniProgramConfigError')
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
} else {
|
||||||
|
fallbackFunc && fallbackFunc(res);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
fail: (res) => {
|
fail: (res) => {
|
||||||
@@ -46,6 +51,7 @@ export default {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
// #endif
|
// #endif
|
||||||
|
fallbackFunc && fallbackFunc(res);
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
// #endif
|
// #endif
|
||||||
@@ -66,9 +72,10 @@ export default {
|
|||||||
.user_id;
|
.user_id;
|
||||||
typeof callback == 'function' && callback(this.authInfo);
|
typeof callback == 'function' && callback(this.authInfo);
|
||||||
} else {
|
} else {
|
||||||
|
fallbackFunc && fallbackFunc(res);
|
||||||
this.$util.showToast({
|
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) {
|
if (res.code >= 0) {
|
||||||
location.href = res.data;
|
location.href = res.data;
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
fail: err => {
|
||||||
|
fallbackFunc && fallbackFunc(err);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,20 +3,83 @@
|
|||||||
|
|
||||||
// 语言包配置
|
// 语言包配置
|
||||||
export const langConfig = {
|
export const langConfig = {
|
||||||
// 语言列表
|
// 语言列表 — 与后端 Lang.php::overrides() 白名单对齐
|
||||||
|
// 增删需要后端同步改 LangOverrideModel::normalizeAppType 旁的 $allow_lang
|
||||||
langList: ['zh-cn', 'en-us'],
|
langList: ['zh-cn', 'en-us'],
|
||||||
// 默认语言
|
// 默认语言
|
||||||
defaultLang: 'zh-cn',
|
defaultLang: 'zh-cn',
|
||||||
// 语言包加载方式:'lazy'(按需加载)或 'preload'(预加载)
|
// 语言包加载方式:'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 = {
|
export const themeConfig = {
|
||||||
// 主题列表
|
// 主题列表 — 与 style_color.js 顶层的 preset 名严格一致(8 个)
|
||||||
themeList: ['default', 'red', 'green', 'blue', 'pink', 'gold', 'purple', 'yellow', 'black'],
|
// 关键: 这里列出的名字必须能在 style_color.js (或后端 style_color.php 镜像) 中找到对应 preset
|
||||||
// 默认主题
|
// 历史上曾包含 'red' 但 style_color.js 从未定义 'red' preset, 切到 'red' 主题时
|
||||||
defaultTheme: 'default'
|
// 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配置
|
// API配置
|
||||||
@@ -31,11 +94,130 @@ export const apiConfig = {
|
|||||||
retryDelay: 1000
|
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 {
|
class ConfigExternal {
|
||||||
constructor() {
|
constructor() {
|
||||||
this.loadedConfigs = {};
|
this.loadedConfigs = {};
|
||||||
this.loadPromises = {};
|
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;
|
this.loadedConfigs[`lang_${lang}`] = langData;
|
||||||
resolve(langData);
|
resolve(langData);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(`加载语言包 ${lang} 失败:`, error);
|
// console.error(`加载语言包 ${lang} 失败:`, error);
|
||||||
reject(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 - 主题名称
|
* @param {string} theme - 主题名称
|
||||||
* @returns {Promise} - 加载结果
|
* @returns {Promise} - 加载结果
|
||||||
*/
|
*/
|
||||||
async loadTheme(theme = themeConfig.defaultTheme) {
|
async loadTheme(theme = themeConfig.defaultTheme) {
|
||||||
|
// 1) 先查已加载的内存缓存(包括远端拉取后写入的)
|
||||||
if (this.loadedConfigs[`theme_${theme}`]) {
|
if (this.loadedConfigs[`theme_${theme}`]) {
|
||||||
return 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}`]) {
|
if (this.loadPromises[`theme_${theme}`]) {
|
||||||
return this.loadPromises[`theme_${theme}`];
|
return this.loadPromises[`theme_${theme}`];
|
||||||
}
|
}
|
||||||
|
|
||||||
this.loadPromises[`theme_${theme}`] = new Promise((resolve, reject) => {
|
this.loadPromises[`theme_${theme}`] = new Promise((resolve, reject) => {
|
||||||
try {
|
try {
|
||||||
// 动态加载主题配置
|
// 动态加载主题配置 (webpack 替换为 stub 时,只返回 1 个 default preset)
|
||||||
const themeData = require(`@/common/js/style_color.js`)['default'][theme];
|
const themeData = require(`@/common/js/style_color.js`)['default'][theme];
|
||||||
// console.log('async themeData => ', themeData);
|
|
||||||
this.loadedConfigs[`theme_${theme}`] = themeData;
|
this.loadedConfigs[`theme_${theme}`] = themeData;
|
||||||
resolve(themeData);
|
resolve(themeData);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
// 发行版本,配置说明
|
// 发行版本,配置说明
|
||||||
let releaseCfg = undefined;
|
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 {
|
try {
|
||||||
if (site) { // 从site.js文件中获取配置, 针对微信小程序类
|
if (site) { // 从site.js文件中获取配置, 针对微信小程序类
|
||||||
releaseCfg = {
|
releaseCfg = {
|
||||||
@@ -11,7 +11,13 @@ try {
|
|||||||
uniacid: site.uniacid,
|
uniacid: site.uniacid,
|
||||||
}
|
}
|
||||||
} else {
|
} 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) {}
|
} catch (e) {}
|
||||||
// #endif
|
// #endif
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
* 整合各种客服方式,提供统一的调用接口
|
* 整合各种客服方式,提供统一的调用接口
|
||||||
*/
|
*/
|
||||||
import IMAGE_CONFIG from './image-config.js';
|
import IMAGE_CONFIG from './image-config.js';
|
||||||
|
import Platform from './platform.js';
|
||||||
|
|
||||||
export class CustomerService {
|
export class CustomerService {
|
||||||
constructor(vueInstance, externalConfig = null) {
|
constructor(vueInstance, externalConfig = null) {
|
||||||
@@ -30,28 +31,25 @@ export class CustomerService {
|
|||||||
return this.latestPlatformConfig;
|
return this.latestPlatformConfig;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 优先级:外部传入 > vuex store > 空对象
|
|
||||||
const servicerConfig = this.externalConfig || this.vm.$store.state.servicerConfig || {};
|
const servicerConfig = this.externalConfig || this.vm.$store.state.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;
|
const platformKey = platformMap[Platform.detect()] || Platform.detect();
|
||||||
|
let platformConfig = servicerConfig[platformKey] && typeof servicerConfig[platformKey] === 'object' ? servicerConfig[platformKey] : null;
|
||||||
|
|
||||||
// #ifdef H5
|
|
||||||
platformConfig = servicerConfig.h5 && typeof servicerConfig.h5 === 'object' ? servicerConfig.h5 : null;
|
|
||||||
// #endif
|
|
||||||
|
|
||||||
// #ifdef MP-WEIXIN
|
|
||||||
platformConfig = servicerConfig.weapp && typeof servicerConfig.weapp === 'object' ? servicerConfig.weapp : null;
|
|
||||||
// #endif
|
|
||||||
|
|
||||||
// #ifdef MP-ALIPAY
|
|
||||||
platformConfig = servicerConfig.aliapp && typeof servicerConfig.aliapp === 'object' ? servicerConfig.aliapp : null;
|
|
||||||
// #endif
|
|
||||||
|
|
||||||
// #ifdef PC
|
|
||||||
platformConfig = servicerConfig.pc && typeof servicerConfig.pc === 'object' ? servicerConfig.pc : null;
|
|
||||||
// #endif
|
|
||||||
|
|
||||||
// 防止空数组被当作有效配置
|
|
||||||
if (Array.isArray(platformConfig)) {
|
if (Array.isArray(platformConfig)) {
|
||||||
platformConfig = null;
|
platformConfig = null;
|
||||||
}
|
}
|
||||||
@@ -102,7 +100,7 @@ export class CustomerService {
|
|||||||
|
|
||||||
if (!config || !config.type) {
|
if (!config || !config.type) {
|
||||||
result.isValid = false;
|
result.isValid = false;
|
||||||
result.errors.push('客服类型未配置');
|
result.errors.push(this.vm.$lang('customerService.serviceTypeNotConfigured'));
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -140,12 +138,12 @@ export class CustomerService {
|
|||||||
// #ifdef H5
|
// #ifdef H5
|
||||||
window.location.href = aiChatUrl;
|
window.location.href = aiChatUrl;
|
||||||
// #endif
|
// #endif
|
||||||
uni.showToast({ title: '打开客服失败', icon: 'none' });
|
uni.showToast({ title: this.vm.$lang('customerService.openFailed'), icon: 'none' });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error('跳转 AI智能客服异常:', e);
|
console.error('跳转 AI智能客服异常:', e);
|
||||||
uni.showToast({ title: '打开客服失败', icon: 'none' });
|
uni.showToast({ title: this.vm.$lang('customerService.openFailed'), icon: 'none' });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -225,7 +223,7 @@ export class CustomerService {
|
|||||||
// 检查是否有企业微信配置
|
// 检查是否有企业微信配置
|
||||||
if (!config.wxwork_url && !config.corpid) {
|
if (!config.wxwork_url && !config.corpid) {
|
||||||
console.error('企业微信配置不完整,缺少 wxwork_url 或 corpid');
|
console.error('企业微信配置不完整,缺少 wxwork_url 或 corpid');
|
||||||
uni.showToast({ title: '企业微信配置不完整', icon: 'none' });
|
uni.showToast({ title: this.vm.$lang('customerService.wxworkConfigIncomplete'), icon: 'none' });
|
||||||
this.fallbackToPhoneCall();
|
this.fallbackToPhoneCall();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -269,12 +267,12 @@ export class CustomerService {
|
|||||||
},
|
},
|
||||||
fail: (err) => {
|
fail: (err) => {
|
||||||
console.error('【跳转第三方小程序失败】', err);
|
console.error('【跳转第三方小程序失败】', err);
|
||||||
uni.showToast({ title: '跳转失败,请稍后重试', icon: 'none' });
|
uni.showToast({ title: this.vm.$lang('customerService.jumpFailed'), icon: 'none' });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
// #endif
|
// #endif
|
||||||
// #ifdef H5
|
// #ifdef H5
|
||||||
uni.showToast({ title: '第三方小程序客服仅在微信小程序中可用', icon: 'none' });
|
uni.showToast({ title: this.vm.$lang('customerService.miniProgramOnly'), icon: 'none' });
|
||||||
// #endif
|
// #endif
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -284,11 +282,11 @@ export class CustomerService {
|
|||||||
// #ifdef H5
|
// #ifdef H5
|
||||||
window.location.href = config.third_url;
|
window.location.href = config.third_url;
|
||||||
// #endif
|
// #endif
|
||||||
// #ifdef MP-WEIXIN
|
// #ifdef MP
|
||||||
uni.setClipboardData({
|
uni.setClipboardData({
|
||||||
data: config.third_url,
|
data: config.third_url,
|
||||||
success: () => {
|
success: () => {
|
||||||
uni.showToast({ title: '链接已复制,请在浏览器打开', icon: 'none' });
|
uni.showToast({ title: this.vm.$lang('customerService.linkCopied'), icon: 'none' });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
// #endif
|
// #endif
|
||||||
@@ -352,9 +350,9 @@ export class CustomerService {
|
|||||||
// #ifdef H5
|
// #ifdef H5
|
||||||
window.open(serviceUrl, '_blank');
|
window.open(serviceUrl, '_blank');
|
||||||
// #endif
|
// #endif
|
||||||
// #ifdef MP-WEIXIN
|
// #ifdef MP
|
||||||
uni.setClipboardData({ data: serviceUrl });
|
uni.setClipboardData({ data: serviceUrl });
|
||||||
uni.showToast({ title: '客服链接已复制', icon: 'none' });
|
uni.showToast({ title: this.vm.$lang('customerService.customerLinkCopied'), icon: 'none' });
|
||||||
// #endif
|
// #endif
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -382,11 +380,11 @@ export class CustomerService {
|
|||||||
if (res.code === 0 && res.data?.mobile) {
|
if (res.code === 0 && res.data?.mobile) {
|
||||||
uni.makePhoneCall({ phoneNumber: res.data.mobile });
|
uni.makePhoneCall({ phoneNumber: res.data.mobile });
|
||||||
} else {
|
} else {
|
||||||
uni.showToast({ title: '暂无客服电话', icon: 'none' });
|
uni.showToast({ title: this.vm.$lang('customerService.noServicePhone'), icon: 'none' });
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
fail: () => {
|
fail: () => {
|
||||||
uni.showToast({ title: '获取客服电话失败', icon: 'none' });
|
uni.showToast({ title: this.vm.$lang('customerService.getPhoneFailed'), icon: 'none' });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -394,23 +392,23 @@ export class CustomerService {
|
|||||||
showNoServicePopup() {
|
showNoServicePopup() {
|
||||||
const siteInfo = this.vm.$store.state.siteInfo || {};
|
const siteInfo = this.vm.$store.state.siteInfo || {};
|
||||||
const message = siteInfo?.site_tel
|
const message = siteInfo?.site_tel
|
||||||
? `请联系客服,客服电话是 ${siteInfo.site_tel}`
|
? this.vm.$lang('customerService.callServiceTip', { phone: siteInfo.site_tel })
|
||||||
: '抱歉,商家暂无客服,请线下联系';
|
: this.vm.$lang('customerService.noServiceOffline');
|
||||||
uni.showModal({ title: '联系客服', content: message, showCancel: false });
|
uni.showModal({ title: this.vm.$lang('customerService.contactCustomerService'), content: message, showCancel: false });
|
||||||
}
|
}
|
||||||
|
|
||||||
showConfigErrorPopup(errors) {
|
showConfigErrorPopup(errors) {
|
||||||
uni.showModal({
|
uni.showModal({
|
||||||
title: '客服配置错误',
|
title: this.vm.$lang('customerService.configError'),
|
||||||
content: `配置有误:\n${errors.join('\n')}`,
|
content: this.vm.$lang('customerService.configErrorDetail', { errors: errors.join('\n') }),
|
||||||
showCancel: false
|
showCancel: false
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
fallbackToOriginalService() {
|
fallbackToOriginalService() {
|
||||||
uni.showModal({
|
uni.showModal({
|
||||||
title: '提示',
|
title: this.vm.$lang('customerService.tip'),
|
||||||
content: '无法直接添加企业微信,是否使用其他方式联系客服?',
|
content: this.vm.$lang('customerService.cannotAddWxwork'),
|
||||||
success: (res) => {
|
success: (res) => {
|
||||||
if (res.confirm) {
|
if (res.confirm) {
|
||||||
this.openWxworkService(true);
|
this.openWxworkService(true);
|
||||||
@@ -421,8 +419,8 @@ export class CustomerService {
|
|||||||
|
|
||||||
fallbackToPhoneCall() {
|
fallbackToPhoneCall() {
|
||||||
uni.showModal({
|
uni.showModal({
|
||||||
title: '提示',
|
title: this.vm.$lang('customerService.tip'),
|
||||||
content: '在线客服不可用,是否拨打电话联系客服?',
|
content: this.vm.$lang('customerService.onlineUnavailable'),
|
||||||
success: (res) => {
|
success: (res) => {
|
||||||
if (res.confirm) this.makePhoneCall();
|
if (res.confirm) this.makePhoneCall();
|
||||||
}
|
}
|
||||||
@@ -569,12 +567,12 @@ export class CustomerService {
|
|||||||
// #ifdef H5
|
// #ifdef H5
|
||||||
window.location.href = aiChatUrl;
|
window.location.href = aiChatUrl;
|
||||||
// #endif
|
// #endif
|
||||||
uni.showToast({ title: '打开客服失败', icon: 'none' });
|
uni.showToast({ title: this.vm.$lang('customerService.openFailed'), icon: 'none' });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error('跳转 AI智能客服异常:', e);
|
console.error('跳转 AI智能客服异常:', e);
|
||||||
uni.showToast({ title: '打开客服失败', icon: 'none' });
|
uni.showToast({ title: this.vm.$lang('customerService.openFailed'), icon: 'none' });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -582,7 +580,7 @@ export class CustomerService {
|
|||||||
* 打开客服选择对话框(预留方法)
|
* 打开客服选择对话框(预留方法)
|
||||||
*/
|
*/
|
||||||
openCustomerSelectPopupDialog() {
|
openCustomerSelectPopupDialog() {
|
||||||
uni.showToast({ title: '客服选择功能开发中', icon: 'none' });
|
uni.showToast({ title: this.vm.$lang('customerService.developing'), icon: 'none' });
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -612,7 +610,7 @@ export class CustomerService {
|
|||||||
if (qyweixinUrl) {
|
if (qyweixinUrl) {
|
||||||
window.location.href = qyweixinUrl;
|
window.location.href = qyweixinUrl;
|
||||||
} else {
|
} else {
|
||||||
uni.showToast({ title: '企业微信客服未配置', icon: 'none' });
|
uni.showToast({ title: this.vm.$lang('customerService.wxworkNotConfigured'), icon: 'none' });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
@@ -631,7 +629,7 @@ export class CustomerService {
|
|||||||
|
|
||||||
if (!validation.isValid) {
|
if (!validation.isValid) {
|
||||||
console.error('客服配置无效:', validation.errors);
|
console.error('客服配置无效:', validation.errors);
|
||||||
uni.showToast({ title: '客服暂不可用', icon: 'none' });
|
uni.showToast({ title: this.vm.$lang('customerService.serviceUnavailable'), icon: 'none' });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -648,14 +646,14 @@ export class CustomerService {
|
|||||||
// #ifdef MP-WEIXIN
|
// #ifdef MP-WEIXIN
|
||||||
if (!wxworkConfig?.enable || !wxworkConfig?.contact_url) {
|
if (!wxworkConfig?.enable || !wxworkConfig?.contact_url) {
|
||||||
console.warn('企业微信配置不完整,使用原生客服');
|
console.warn('企业微信配置不完整,使用原生客服');
|
||||||
uni.showToast({ title: '企业微信配置不完整', icon: 'none' });
|
uni.showToast({ title: this.vm.$lang('customerService.wxworkConfigIncomplete'), icon: 'none' });
|
||||||
}
|
}
|
||||||
// #endif
|
// #endif
|
||||||
|
|
||||||
// #ifdef H5
|
// #ifdef H5
|
||||||
if (!wxworkConfig?.contact_url && !platformConfig.wxwork_url) {
|
if (!wxworkConfig?.contact_url && !platformConfig.wxwork_url) {
|
||||||
console.error('企业微信链接未配置');
|
console.error('企业微信链接未配置');
|
||||||
uni.showToast({ title: '企业微信链接未配置', icon: 'none' });
|
uni.showToast({ title: this.vm.$lang('customerService.wxworkLinkNotConfigured'), icon: 'none' });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
// #endif
|
// #endif
|
||||||
@@ -664,12 +662,12 @@ export class CustomerService {
|
|||||||
// 直接调用统一处理方法,由 CustomerService 内部根据配置路由
|
// 直接调用统一处理方法,由 CustomerService 内部根据配置路由
|
||||||
try {
|
try {
|
||||||
this.handleCustomerClick({
|
this.handleCustomerClick({
|
||||||
sendMessageTitle: options.sendMessageTitle || '来自悬浮按钮的咨询',
|
sendMessageTitle: options.sendMessageTitle || this.vm.$lang('customerService.fromFloatButton'),
|
||||||
sendMessagePath: options.sendMessagePath || '/pages/index/index'
|
sendMessagePath: options.sendMessagePath || '/pages/index/index'
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('客服处理失败:', error);
|
console.error('客服处理失败:', error);
|
||||||
uni.showToast({ title: '打开客服失败', icon: 'none' });
|
uni.showToast({ title: this.vm.$lang('customerService.openFailed'), icon: 'none' });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -46,6 +46,12 @@ export default {
|
|||||||
openBottomNav: false,
|
openBottomNav: false,
|
||||||
isShowCopyRight: false,
|
isShowCopyRight: false,
|
||||||
|
|
||||||
|
// getDiyInfo 节流
|
||||||
|
diyInfoLoading: false, // 是否正在请求
|
||||||
|
lastDiyInfoTime: 0, // 上次成功加载的时间戳
|
||||||
|
lastDiyInfoLang: '', // 上次加载时的语言,语言切换时强制刷新
|
||||||
|
diyInfoTtl: 3 * 60 * 1000, // 3分钟内不重复请求
|
||||||
|
|
||||||
//启动广告
|
//启动广告
|
||||||
adv:{},
|
adv:{},
|
||||||
|
|
||||||
@@ -304,40 +310,71 @@ export default {
|
|||||||
}
|
}
|
||||||
|
|
||||||
},
|
},
|
||||||
async getDiyInfo() {
|
async getDiyInfo(force = false) {
|
||||||
let res = await this.$api.sendRequest({
|
// 节流:正在请求 / N 秒内已加载过 / 语言未变 -> 跳过
|
||||||
url: '/api/diyview/info',
|
const now = Date.now();
|
||||||
data: {
|
const currentLang = uni.getStorageSync("lang") || '';
|
||||||
id: this.id,
|
if (!force) {
|
||||||
name: this.name,
|
if (this.diyInfoLoading) return;
|
||||||
en_type:uni.getStorageSync("lang"),//获取语言底部
|
if (this.lastDiyInfoTime && (now - this.lastDiyInfoTime) < this.diyInfoTtl
|
||||||
},
|
&& this.lastDiyInfoLang === currentLang) {
|
||||||
async: false
|
return;
|
||||||
});
|
}
|
||||||
if (res.code != 0 || !res.data) {
|
}
|
||||||
|
|
||||||
|
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 (this.$refs.loadingCover) this.$refs.loadingCover.hide();
|
||||||
|
|
||||||
if (res.code == -3) {
|
if (res && res.code == -3) {
|
||||||
this.$util.showToast({
|
this.$util.showToast({
|
||||||
title: res.message
|
title: res.message
|
||||||
});
|
});
|
||||||
this.diyData = {};
|
// 保持原有数据结构,仅清空 value,避免鸿蒙下重新布局
|
||||||
|
this.diyData = { ...(this.diyData || {}), value: [] };
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
this.$util.showToast({
|
this.$util.showToast({
|
||||||
title: '未配置自定义页面数据'
|
title: this.$lang('diy.noDiyData')
|
||||||
});
|
});
|
||||||
this.diyData = {};
|
// 保持原有数据结构,仅清空 value,避免鸿蒙下重新布局
|
||||||
|
this.diyData = { ...(this.diyData || {}), value: [] };
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
this.lastDiyInfoTime = now;
|
||||||
|
this.lastDiyInfoLang = currentLang;
|
||||||
|
|
||||||
let diyDataValue = res.data;
|
let diyDataValue = res.data;
|
||||||
if (diyDataValue.value) {
|
if (diyDataValue.value) {
|
||||||
this.diyData = JSON.parse(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);
|
if (title) this.$langConfig.title(title);
|
||||||
|
|
||||||
this.mpCollect = this.diyData.global.mpCollect;
|
this.mpCollect = this.diyData.global.mpCollect;
|
||||||
@@ -560,7 +597,7 @@ export default {
|
|||||||
if (res.code == 0 && res.data) {
|
if (res.code == 0 && res.data) {
|
||||||
this.currentPosition = res.data.formatted_addresses.recommend; // 结合知名地点形成的描述性地址,更具人性化特点
|
this.currentPosition = res.data.formatted_addresses.recommend; // 结合知名地点形成的描述性地址,更具人性化特点
|
||||||
} else {
|
} else {
|
||||||
this.currentPosition = '未获取到定位';
|
this.currentPosition = this.$lang('diy.locationNotAvailable');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -572,7 +609,7 @@ export default {
|
|||||||
this.nearestStore = this.defaultStoreInfo;
|
this.nearestStore = this.defaultStoreInfo;
|
||||||
this.nearestStore.show_address = this.nearestStore.full_address.replace(/,/g, ' ') + ' ' + this.nearestStore.address;
|
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();
|
this.openChooseStorePopup();
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -582,7 +619,7 @@ export default {
|
|||||||
if (this.id) shareUrl += '?id=' + this.id;
|
if (this.id) shareUrl += '?id=' + this.id;
|
||||||
else if (this.name) shareUrl += '?name=' + this.name;
|
else if (this.name) shareUrl += '?name=' + this.name;
|
||||||
this.$util.setPublicShare({
|
this.$util.setPublicShare({
|
||||||
title: this.diyData.global.title,
|
title: this.$langConfig.getField(this.diyData.global, 'title'),
|
||||||
desc: '',
|
desc: '',
|
||||||
link: shareUrl,
|
link: shareUrl,
|
||||||
imgUrl: this.siteInfo ? this.$util.img(this.siteInfo.logo_square) : ''
|
imgUrl: this.siteInfo ? this.$util.img(this.siteInfo.logo_square) : ''
|
||||||
|
|||||||
15
common/js/empty-lang-stub.js
Normal file
15
common/js/empty-lang-stub.js
Normal 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: {}
|
||||||
|
};
|
||||||
169
common/js/empty-style-stub.js
Normal file
169
common/js/empty-style-stub.js
Normal 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 中移除以保持一致性
|
||||||
|
};
|
||||||
@@ -12,57 +12,13 @@
|
|||||||
* @createTime 2023-08-10
|
* @createTime 2023-08-10
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
import Platform from './platform.js'
|
||||||
|
|
||||||
class EventBus {
|
class EventBus {
|
||||||
constructor() {
|
constructor() {
|
||||||
this.events = new Map()
|
this.events = new Map()
|
||||||
this.domBridge = null
|
this.domBridge = null
|
||||||
this.platform = this.detectPlatform()
|
this.platform = Platform.detect()
|
||||||
}
|
|
||||||
|
|
||||||
// 检测平台
|
|
||||||
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'
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 设置 DOM 桥接
|
// 设置 DOM 桥接
|
||||||
|
|||||||
112
common/js/form-platform-mixin.js
Normal file
112
common/js/form-platform-mixin.js
Normal file
@@ -0,0 +1,112 @@
|
|||||||
|
/**
|
||||||
|
* form-platform-mixin.js
|
||||||
|
*
|
||||||
|
* 表单组件共用的平台检测 mixin
|
||||||
|
*
|
||||||
|
* 集中维护 3 个 computed:
|
||||||
|
* - platform 当前运行平台 key(与后端 formConfig.terminal 键名对齐)
|
||||||
|
* - platformAliases 后端键名 → 内部 platform 名 兼容层
|
||||||
|
* - platformConfigKeys 当前平台的有效配置键集合(用于从 formConfig.terminal 查找)
|
||||||
|
*
|
||||||
|
* 消费方:
|
||||||
|
* - components/ns-form/ns-form.vue
|
||||||
|
* - components/ns-newform/ns-newform.vue
|
||||||
|
* - 任何需要按端读取 formConfig.terminal.{h5|weapp|harmony|app} 的表单组件
|
||||||
|
*
|
||||||
|
* 设计原则:
|
||||||
|
* 1. 单一真值:避免 ns-form / ns-newform 各自维护导致漂移
|
||||||
|
* 2. 纯 computed mixin:不依赖 props/data/methods,便于跨组件复用
|
||||||
|
* 3. 不依赖 util.js 等其它模块,避免循环依赖
|
||||||
|
* 4. 通过 mixins: [...] 引入,组件侧不再写平台判断代码
|
||||||
|
*
|
||||||
|
* 用法:
|
||||||
|
* import formPlatformMixin from '@/common/js/form-platform-mixin.js';
|
||||||
|
* export default {
|
||||||
|
* mixins: [formPlatformMixin],
|
||||||
|
* computed: {
|
||||||
|
* config() {
|
||||||
|
* const cur = this.platform;
|
||||||
|
* const keys = this.platformConfigKeys;
|
||||||
|
* // ...
|
||||||
|
* }
|
||||||
|
* }
|
||||||
|
* };
|
||||||
|
*/
|
||||||
|
|
||||||
|
export default {
|
||||||
|
computed: {
|
||||||
|
/**
|
||||||
|
* 当前运行平台标识(与后端 formConfig.terminal 键名对齐)
|
||||||
|
* 后端 terminal 键:h5 / weapp / harmony / app / mp-alipay / mp-baidu / mp-toutiao
|
||||||
|
*/
|
||||||
|
platform() {
|
||||||
|
// #ifdef H5
|
||||||
|
return 'h5';
|
||||||
|
// #endif
|
||||||
|
// #ifdef MP-WEIXIN
|
||||||
|
return 'weapp';
|
||||||
|
// #endif
|
||||||
|
// #ifdef MP-ALIPAY
|
||||||
|
return 'mp-alipay';
|
||||||
|
// #endif
|
||||||
|
// #ifdef MP-BAIDU
|
||||||
|
return 'mp-baidu';
|
||||||
|
// #endif
|
||||||
|
// #ifdef MP-TOUTIAO
|
||||||
|
return 'mp-toutiao';
|
||||||
|
// #endif
|
||||||
|
// #ifdef APP-PLUS
|
||||||
|
return 'app';
|
||||||
|
// #endif
|
||||||
|
// #ifdef MP-HARMONY
|
||||||
|
return 'harmony';
|
||||||
|
// #endif
|
||||||
|
// #ifdef QUICKAPP-WEBVIEW
|
||||||
|
return 'quickapp';
|
||||||
|
// #endif
|
||||||
|
return 'h5';
|
||||||
|
},
|
||||||
|
/**
|
||||||
|
* 后端键名 → 内部 platform 名 兼容层
|
||||||
|
* canonical 与 platform() 返回值一致;别名为兼容 DB 旧 app_type(upgrade-to-ai-agent.sql)
|
||||||
|
* 及 uniapp / 设计器的历史命名。键名严格区分大小写。
|
||||||
|
*/
|
||||||
|
platformAliases() {
|
||||||
|
return {
|
||||||
|
'h5': 'h5',
|
||||||
|
'weapp': 'weapp',
|
||||||
|
'mp-weixin': 'weapp',
|
||||||
|
'wechat': 'weapp',
|
||||||
|
'harmony': 'harmony',
|
||||||
|
'app': 'app',
|
||||||
|
'app-plus': 'app',
|
||||||
|
'mp-alipay': 'mp-alipay',
|
||||||
|
'aliapp': 'mp-alipay',
|
||||||
|
'alipay': 'mp-alipay',
|
||||||
|
'mp-baidu': 'mp-baidu',
|
||||||
|
'baiduapp': 'mp-baidu',
|
||||||
|
'baidu': 'mp-baidu',
|
||||||
|
'mp-toutiao': 'mp-toutiao',
|
||||||
|
'toutiao': 'mp-toutiao'
|
||||||
|
};
|
||||||
|
},
|
||||||
|
/**
|
||||||
|
* 当前平台的有效配置键集合
|
||||||
|
* 用于 config() 中查找 formConfig.terminal 下的平台差异化配置:
|
||||||
|
* - 后端格式:formConfig.terminal = { h5: {...}, weapp: {...}, harmony: {...} }
|
||||||
|
* - 旧式扁平:formConfig[platformKey] = { ... }
|
||||||
|
* 返回所有映射到当前 platform 的后端键名,方便两种结构都能命中。
|
||||||
|
*/
|
||||||
|
platformConfigKeys() {
|
||||||
|
const cur = this.platform;
|
||||||
|
const aliases = this.platformAliases;
|
||||||
|
const keys = [];
|
||||||
|
Object.keys(aliases).forEach(k => {
|
||||||
|
if (aliases[k] === cur) keys.push(k);
|
||||||
|
});
|
||||||
|
// 加入当前平台名(兼容 formConfig[platform] 这种扁平写法)
|
||||||
|
if (keys.indexOf(cur) === -1) keys.push(cur);
|
||||||
|
return keys;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -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 {
|
export default {
|
||||||
onLoad() { },
|
onLoad() { },
|
||||||
onShow() {
|
onShow() {
|
||||||
// 刷新多语言
|
// remote-only 小程序/鸿蒙: boot 未完成时跳过 refresh,避免空翻译写入标题等
|
||||||
this.$langConfig.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: {
|
computed: {
|
||||||
// 是否是英文环境
|
// 是否是英文环境
|
||||||
isEnEnv() {
|
isEnEnv() {
|
||||||
return this.$langConfig.getCurrentLocale() === 'en-us';
|
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() {
|
themeStyle() {
|
||||||
return this.$store.state.themeStyle;
|
return this.$store.state.themeStyle;
|
||||||
},
|
},
|
||||||
@@ -22,6 +91,28 @@ export default {
|
|||||||
tabBarList() {
|
tabBarList() {
|
||||||
return this.$store.state.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() {
|
siteInfo() {
|
||||||
return this.$store.state.siteInfo;
|
return this.$store.state.siteInfo;
|
||||||
},
|
},
|
||||||
@@ -81,7 +172,7 @@ export default {
|
|||||||
return this.$store.state.diySeckillInterval;
|
return this.$store.state.diySeckillInterval;
|
||||||
},
|
},
|
||||||
tabBarHeight() {
|
tabBarHeight() {
|
||||||
return this.$store.state.tabBarHeight;
|
return this.shouldShowTabBar ? this.$store.state.tabBarHeight : '0rpx';
|
||||||
},
|
},
|
||||||
mapConfig() {
|
mapConfig() {
|
||||||
return this.$store.state.mapConfig;
|
return this.$store.state.mapConfig;
|
||||||
@@ -109,6 +200,13 @@ export default {
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
methods: {
|
methods: {
|
||||||
|
/**
|
||||||
|
* 当前平台类型(多端翻译隔离)
|
||||||
|
* 复用 Platform.getAppType(),与服务端 /api/BaseApi 的 $app_type 对齐
|
||||||
|
*/
|
||||||
|
getAppType() {
|
||||||
|
try { return Platform.getAppType() || '*'; } catch (e) { return '*'; }
|
||||||
|
},
|
||||||
|
|
||||||
// 颜色变浅(>0)、变深函数(<0)
|
// 颜色变浅(>0)、变深函数(<0)
|
||||||
lightenDarkenColor(color, amount) {
|
lightenDarkenColor(color, amount) {
|
||||||
@@ -155,6 +253,53 @@ export default {
|
|||||||
this.$store.dispatch('getCartNumber'); //重新获取购物车数据
|
this.$store.dispatch('getCartNumber'); //重新获取购物车数据
|
||||||
this.$util.redirectTo(this.$util.INDEX_PAGE_URL);
|
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: {
|
filters: {
|
||||||
|
|||||||
@@ -79,7 +79,7 @@ export default {
|
|||||||
},
|
},
|
||||||
methods: {
|
methods: {
|
||||||
// 处理商品详情数据
|
// 处理商品详情数据
|
||||||
handleGoodsSkuData() {
|
async handleGoodsSkuData() {
|
||||||
// this.navbarData.title = this.goodsSkuDetail.goods_name.length > 9 ? this.goodsSkuDetail.goods_name.substr(0, 9) + "..." : this.goodsSkuDetail.goods_name;
|
// this.navbarData.title = this.goodsSkuDetail.goods_name.length > 9 ? this.goodsSkuDetail.goods_name.substr(0, 9) + "..." : this.goodsSkuDetail.goods_name;
|
||||||
//设置标题
|
//设置标题
|
||||||
// this.$langConfig.title(this.navbarData.title);
|
// this.$langConfig.title(this.navbarData.title);
|
||||||
@@ -141,7 +141,7 @@ export default {
|
|||||||
});
|
});
|
||||||
this.goodsSkuDetail.swiperHeight = maxHeight + 'px';
|
this.goodsSkuDetail.swiperHeight = maxHeight + 'px';
|
||||||
|
|
||||||
this.goodsSkuDetail.unit = this.goodsSkuDetail.unit || "件";
|
this.goodsSkuDetail.unit = this.goodsSkuDetail.unit || this.$lang('unit.piece');
|
||||||
|
|
||||||
// 当前商品SKU规格
|
// 当前商品SKU规格
|
||||||
if (this.goodsSkuDetail.sku_spec_format) this.goodsSkuDetail.sku_spec_format = JSON.parse(this.goodsSkuDetail.sku_spec_format);
|
if (this.goodsSkuDetail.sku_spec_format) this.goodsSkuDetail.sku_spec_format = JSON.parse(this.goodsSkuDetail.sku_spec_format);
|
||||||
@@ -186,7 +186,7 @@ export default {
|
|||||||
|
|
||||||
// this.getBarrageData();
|
// this.getBarrageData();
|
||||||
if (this.addonIsExist.form) {
|
if (this.addonIsExist.form) {
|
||||||
this.getGoodsForm();
|
await this.getGoodsForm();
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
/**
|
/**
|
||||||
@@ -199,7 +199,7 @@ export default {
|
|||||||
if (this.$refs.goodsDetailView) {
|
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) {
|
if (this.swiperCurrent > this.goodsSkuDetail.sku_images.length) {
|
||||||
@@ -321,17 +321,54 @@ export default {
|
|||||||
},
|
},
|
||||||
/**
|
/**
|
||||||
* 获取商品表单
|
* 获取商品表单
|
||||||
|
* 后端 goodsform 接口与 info() 对齐,返回 {json_data, form_config(camelCase),
|
||||||
|
* form_name, form_tip, form_banner, show_banner, show_tip}。
|
||||||
|
* 全部字段都落到 goodsSkuDetail 上:表单字段 / 样式 / banner / tip 元数据,
|
||||||
|
* 给 detail.vue 的 diy-form 直接消费。所有分支都做兜底初始化,避免下游拿到 undefined。
|
||||||
*/
|
*/
|
||||||
getGoodsForm() {
|
async getGoodsForm() {
|
||||||
this.$api.sendRequest({
|
const res = await this.$api.sendRequest({
|
||||||
url: "/form/api/form/goodsform",
|
url: "/form/api/form/goodsform",
|
||||||
data: {
|
data: {
|
||||||
goods_id: this.goodsSkuDetail.goods_id
|
goods_id: this.goodsSkuDetail.goods_id
|
||||||
},
|
},
|
||||||
success: res => {
|
async: false
|
||||||
if (res.code == 0 && res.data) this.$set(this.goodsSkuDetail, 'goods_form', res.data);
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
const empty = () => {
|
||||||
|
this.$set(this.goodsSkuDetail, 'goods_form', []);
|
||||||
|
this.$set(this.goodsSkuDetail, 'goods_form_config', {});
|
||||||
|
this.$set(this.goodsSkuDetail, 'goods_form_name', '');
|
||||||
|
this.$set(this.goodsSkuDetail, 'goods_form_tip', '');
|
||||||
|
this.$set(this.goodsSkuDetail, 'goods_form_banner', '');
|
||||||
|
this.$set(this.goodsSkuDetail, 'goods_form_show_banner', false);
|
||||||
|
this.$set(this.goodsSkuDetail, 'goods_form_show_tip', false);
|
||||||
|
};
|
||||||
|
if (!res || res.code != 0 || !res.data) {
|
||||||
|
empty();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (Array.isArray(res.data)) {
|
||||||
|
// 旧版扁平数组兼容
|
||||||
|
empty();
|
||||||
|
this.$set(this.goodsSkuDetail, 'goods_form', res.data);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.$set(this.goodsSkuDetail, 'goods_form', res.data.json_data || []);
|
||||||
|
this.$set(this.goodsSkuDetail, 'goods_form_config', res.data.form_config || {});
|
||||||
|
this.$set(this.goodsSkuDetail, 'goods_form_name', res.data.form_name || '');
|
||||||
|
this.$set(this.goodsSkuDetail, 'goods_form_tip', res.data.form_tip || '');
|
||||||
|
this.$set(this.goodsSkuDetail, 'goods_form_banner', res.data.form_banner || '');
|
||||||
|
// show_banner/show_tip 后端存 0/1,归一化 boolean
|
||||||
|
this.$set(
|
||||||
|
this.goodsSkuDetail,
|
||||||
|
'goods_form_show_banner',
|
||||||
|
res.data.show_banner == 1 ? true : (res.data.show_banner === 0 ? false : true)
|
||||||
|
);
|
||||||
|
this.$set(
|
||||||
|
this.goodsSkuDetail,
|
||||||
|
'goods_form_show_tip',
|
||||||
|
res.data.show_tip == 1 ? true : (res.data.show_tip === 0 ? false : true)
|
||||||
|
);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -1,65 +1,172 @@
|
|||||||
import Config from './config.js'
|
import Config from './config.js'
|
||||||
import Util from './util.js'
|
import Util from './util.js'
|
||||||
import store from '@/store/index.js'
|
import store from '@/store/index.js'
|
||||||
|
import Platform from './platform.js'
|
||||||
|
|
||||||
// #ifdef H5
|
const { appType, appTypeName } = Platform.getPlatformInfo();
|
||||||
const app_type = Util.isWeiXin() ? 'wechat' : 'h5';
|
|
||||||
const app_type_name = Util.isWeiXin() ? '微信公众号' : 'H5';
|
|
||||||
// #endif
|
|
||||||
|
|
||||||
// #ifdef MP-WEIXIN
|
let _Lang = null;
|
||||||
const app_type = 'weapp';
|
function getLang() {
|
||||||
const app_type_name = '微信小程序';
|
if (!_Lang) {
|
||||||
// #endif
|
_Lang = require('./lang.js').default;
|
||||||
|
}
|
||||||
|
return _Lang;
|
||||||
|
}
|
||||||
|
|
||||||
// #ifdef MP-ALIPAY
|
const DEFAULT_TIMEOUT = 15000;
|
||||||
const app_type = 'aliapp';
|
const DEFAULT_MAX_RETRIES = 2;
|
||||||
const app_type_name = '支付宝小程序';
|
const RETRY_DELAY_BASE = 2000;
|
||||||
// #endif
|
|
||||||
|
|
||||||
// #ifdef MP-BAIDU
|
function _shouldRetry(errMsg) {
|
||||||
const app_type = 'baiduapp';
|
if (!errMsg) return false;
|
||||||
const app_type_name = '百度小程序';
|
if (errMsg === 'request:fail url not in domain list') return false;
|
||||||
// #endif
|
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
|
function _classifyError(errMsg, statusCode) {
|
||||||
const app_type = 'MP-TOUTIAO';
|
if (!errMsg && !statusCode) return 'unknown';
|
||||||
const app_type_name = '头条小程序';
|
if (errMsg === 'request:fail abort') return 'aborted';
|
||||||
// #endif
|
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
|
function _sleep(ms) {
|
||||||
const app_type = 'MP-QQ';
|
return new Promise(resolve => setTimeout(resolve, ms));
|
||||||
const app_type_name = 'QQ小程序';
|
}
|
||||||
// #endif
|
|
||||||
|
|
||||||
// #ifdef APP-PLUS
|
function _makeRequest(url, method, data, header, dataType, responseType, timeout) {
|
||||||
const app_type = 'app';
|
return new Promise((resolve, reject) => {
|
||||||
const app_type_name = 'APP';
|
uni.request({
|
||||||
// #endif
|
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 {
|
export default {
|
||||||
sendRequest(params) {
|
sendRequest(params) {
|
||||||
if (!Config.baseUrl) {
|
if (!Config.baseUrl) {
|
||||||
uni.showToast({
|
uni.showToast({
|
||||||
title: '未配置请求域名',
|
title: getLang().lang('http.baseUrlNotConfigured'),
|
||||||
'icon': 'none',
|
'icon': 'none',
|
||||||
duration: 10000
|
duration: 10000
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
var method = params.data != undefined ? 'POST' : 'GET', // 请求方式
|
const _isRemoteOnly = getLang().isRemoteOnly && getLang().isRemoteOnly();
|
||||||
url = (Config.baseUrl + params.url).replace(/(?<!:)\/+/g, '/'), // 请求路径
|
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 = {
|
data = {
|
||||||
app_type,
|
app_type: appType,
|
||||||
app_type_name
|
app_type_name: appTypeName
|
||||||
};
|
};
|
||||||
|
|
||||||
// token
|
|
||||||
data.token = store.state.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;
|
var default_store_info = store.state.defaultStoreInfo;
|
||||||
if (default_store_info) {
|
if (default_store_info) {
|
||||||
data.store_id = default_store_info.store_id;
|
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 (store_info) data.store_id = store_info.store_id;
|
||||||
|
|
||||||
// 参数
|
|
||||||
if (params.data != undefined) Object.assign(data, params.data);
|
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) {
|
if (params.async === false) {
|
||||||
//同步
|
return _requestWithRetry(params, url, method, data, header, dataType, responseType)
|
||||||
return new Promise((resolve, reject) => {
|
.then(res => {
|
||||||
uni.request({
|
typeof params.complete == 'function' && params.complete(res);
|
||||||
url: url,
|
return res;
|
||||||
method: method,
|
})
|
||||||
data: data,
|
.catch(err => {
|
||||||
header: params.header || {
|
typeof params.complete == 'function' && params.complete();
|
||||||
// 'Accept': 'application/json',
|
throw err;
|
||||||
'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);
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
});
|
|
||||||
} else {
|
} else {
|
||||||
//异步
|
_requestWithRetry(params, url, method, data, header, dataType, responseType)
|
||||||
uni.request({
|
.then(res => {
|
||||||
url: url,
|
typeof params.success == 'function' && params.success(res);
|
||||||
method: method,
|
typeof params.complete == 'function' && params.complete(res);
|
||||||
data: data,
|
})
|
||||||
header: params.header || {
|
.catch(err => {
|
||||||
// 'Accept': 'application/json',
|
typeof params.fail == 'function' && params.fail(err);
|
||||||
'content-type': 'application/x-www-form-urlencoded;application/json'
|
typeof params.complete == 'function' && params.complete();
|
||||||
},
|
});
|
||||||
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);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
uploadBase64(params) {
|
uploadBase64(params) {
|
||||||
@@ -196,8 +214,8 @@ export default {
|
|||||||
'content-type': 'application/x-www-form-urlencoded;application/json'
|
'content-type': 'application/x-www-form-urlencoded;application/json'
|
||||||
},
|
},
|
||||||
data: {
|
data: {
|
||||||
app_type,
|
app_type: appType,
|
||||||
app_type_name,
|
app_type_name: appTypeName,
|
||||||
images: params.base64
|
images: params.base64
|
||||||
},
|
},
|
||||||
dataType: 'json',
|
dataType: 'json',
|
||||||
@@ -218,8 +236,8 @@ export default {
|
|||||||
'content-type': 'application/x-www-form-urlencoded;application/json'
|
'content-type': 'application/x-www-form-urlencoded;application/json'
|
||||||
},
|
},
|
||||||
data: {
|
data: {
|
||||||
app_type,
|
app_type: appType,
|
||||||
app_type_name,
|
app_type_name: appTypeName,
|
||||||
path: params.path
|
path: params.path
|
||||||
},
|
},
|
||||||
dataType: 'json',
|
dataType: 'json',
|
||||||
@@ -239,8 +257,8 @@ export default {
|
|||||||
name: params.name || 'file',
|
name: params.name || 'file',
|
||||||
fileType: params.fileType || 'image',
|
fileType: params.fileType || 'image',
|
||||||
formData: {
|
formData: {
|
||||||
app_type,
|
app_type: appType,
|
||||||
app_type_name,
|
app_type_name: appTypeName,
|
||||||
},
|
},
|
||||||
header: {
|
header: {
|
||||||
'content-type': 'application/x-www-form-urlencoded;application/json'
|
'content-type': 'application/x-www-form-urlencoded;application/json'
|
||||||
|
|||||||
11
common/js/lang-empty-stub.js
Normal file
11
common/js/lang-empty-stub.js
Normal 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
440
common/js/lang-loader.js
Normal 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);
|
||||||
|
}
|
||||||
1476
common/js/lang.js
1476
common/js/lang.js
File diff suppressed because it is too large
Load Diff
@@ -7,14 +7,12 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import Util from './util.js'
|
import Util from './util.js'
|
||||||
|
import Lang from './lang.js';
|
||||||
|
|
||||||
var ERROR_CONF = {
|
var ERROR_CONF = {
|
||||||
KEY_ERR: 311,
|
KEY_ERR: 311,
|
||||||
KEY_ERR_MSG: 'key格式错误',
|
|
||||||
PARAM_ERR: 310,
|
PARAM_ERR: 310,
|
||||||
PARAM_ERR_MSG: '请求参数信息有误',
|
|
||||||
SYSTEM_ERR: 600,
|
SYSTEM_ERR: 600,
|
||||||
SYSTEM_ERR_MSG: '系统错误',
|
|
||||||
WX_ERR_CODE: 1000,
|
WX_ERR_CODE: 1000,
|
||||||
WX_OK_CODE: 200
|
WX_OK_CODE: 200
|
||||||
};
|
};
|
||||||
@@ -385,7 +383,7 @@ var Utils = {
|
|||||||
*/
|
*/
|
||||||
checkParamKeyEmpty(param, key) {
|
checkParamKeyEmpty(param, key) {
|
||||||
if (!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.fail(errconf);
|
||||||
param.complete(errconf);
|
param.complete(errconf);
|
||||||
return true;
|
return true;
|
||||||
@@ -410,7 +408,7 @@ var Utils = {
|
|||||||
checkLocation(param) {
|
checkLocation(param) {
|
||||||
var location = this.getLocationParam(param.location);
|
var location = this.getLocationParam(param.location);
|
||||||
if (!location || !location.latitude || !location.longitude) {
|
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.fail(errconf);
|
||||||
param.complete(errconf);
|
param.complete(errconf);
|
||||||
return false;
|
return false;
|
||||||
@@ -623,7 +621,7 @@ var Utils = {
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
default:{
|
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) {
|
constructor(options) {
|
||||||
if (!options.key) {
|
if (!options.key) {
|
||||||
throw Error('key值不能为空');
|
throw Error(Lang.lang('common.mapWxJssdk.keyCannotBeEmpty'));
|
||||||
}
|
}
|
||||||
this.key = options.key;
|
this.key = options.key;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import util from '@/common/js/util.js'
|
import util from '@/common/js/util.js'
|
||||||
import TransformCoordinate from './transformCoordinate.js'
|
import TransformCoordinate from './transformCoordinate.js'
|
||||||
|
import Lang from '@/common/js/lang.js'
|
||||||
|
|
||||||
function openMapByDefault(latitude, longitude, name) {
|
function openMapByDefault(latitude, longitude, name) {
|
||||||
uni.openLocation({
|
uni.openLocation({
|
||||||
@@ -8,7 +9,7 @@ function openMapByDefault(latitude, longitude, name) {
|
|||||||
name: name,
|
name: name,
|
||||||
fail: (e) => {
|
fail: (e) => {
|
||||||
uni.showModal({
|
uni.showModal({
|
||||||
content: '打开地图失败,请稍后重试'
|
content: Lang.lang('common.map.openMapFailed')
|
||||||
})
|
})
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
@@ -89,6 +90,7 @@ export default {
|
|||||||
let platform = util.getDeviceInfo().platform;
|
let platform = util.getDeviceInfo().platform;
|
||||||
switch (platform) {
|
switch (platform) {
|
||||||
case 'android':
|
case 'android':
|
||||||
|
case 'harmony':
|
||||||
openMapByAndroid(arr[1], arr[0], name)
|
openMapByAndroid(arr[1], arr[0], name)
|
||||||
break;
|
break;
|
||||||
case 'ios':
|
case 'ios':
|
||||||
|
|||||||
81
common/js/merge-theme.js
Normal file
81
common/js/merge-theme.js
Normal 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,
|
||||||
|
};
|
||||||
291
common/js/mp-share-default.js
Normal file
291
common/js/mp-share-default.js
Normal 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
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
import { EventSafety } from '@/common/js/event-safety.js'
|
import { EventSafety } from '@/common/js/event-safety.js'
|
||||||
import util from '@/common/js/util.js'
|
import util from '@/common/js/util.js'
|
||||||
|
import Lang from '@/common/js/lang.js'
|
||||||
|
|
||||||
export class NavigationHelper {
|
export class NavigationHelper {
|
||||||
constructor() {
|
constructor() {
|
||||||
@@ -260,7 +261,7 @@ export class NavigationHelper {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 显示用户友好的错误信息
|
// 显示用户友好的错误信息
|
||||||
this.showError('导航服务暂时不可用')
|
this.showError(Lang.lang('common.navigation.serviceUnavailable'))
|
||||||
}
|
}
|
||||||
|
|
||||||
// 显示错误提示
|
// 显示错误提示
|
||||||
|
|||||||
229
common/js/platform.js
Normal file
229
common/js/platform.js
Normal 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
978
common/js/privacy.js
Normal 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;
|
||||||
33
common/js/quickapp-pull-refresh.js
Normal file
33
common/js/quickapp-pull-refresh.js
Normal 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 */ }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,6 @@
|
|||||||
// 文件分享工具函数
|
// 文件分享工具函数
|
||||||
|
import Lang from './lang.js';
|
||||||
|
|
||||||
export default {
|
export default {
|
||||||
/**
|
/**
|
||||||
* 生成文件预览链接
|
* 生成文件预览链接
|
||||||
@@ -30,7 +32,7 @@ export default {
|
|||||||
* @param {string} title - 分享标题,默认使用文件名
|
* @param {string} title - 分享标题,默认使用文件名
|
||||||
* @param {string} desc - 分享描述,默认使用固定文案
|
* @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);
|
const filePreviewUrl = this.generateFilePreviewUrl(file);
|
||||||
|
|
||||||
@@ -44,17 +46,17 @@ export default {
|
|||||||
url: filePreviewUrl
|
url: filePreviewUrl
|
||||||
}).catch(err => {
|
}).catch(err => {
|
||||||
console.error('分享失败:', err);
|
console.error('分享失败:', err);
|
||||||
uni.showToast({ title: '分享失败', icon: 'none' });
|
uni.showToast({ title: Lang.lang('share.shareFailed'), icon: 'none' });
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
// 不支持 Web Share API 的浏览器
|
// 不支持 Web Share API 的浏览器
|
||||||
uni.setClipboardData({
|
uni.setClipboardData({
|
||||||
data: filePreviewUrl,
|
data: filePreviewUrl,
|
||||||
success: () => {
|
success: () => {
|
||||||
uni.showToast({ title: '链接已复制,请粘贴分享', icon: 'success' });
|
uni.showToast({ title: Lang.lang('share.linkCopied'), icon: 'success' });
|
||||||
},
|
},
|
||||||
fail: () => {
|
fail: () => {
|
||||||
uni.showToast({ title: '复制失败', icon: 'none' });
|
uni.showToast({ title: Lang.lang('share.copyFailed'), icon: 'none' });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -63,7 +65,7 @@ export default {
|
|||||||
// #ifdef MP-WEIXIN
|
// #ifdef MP-WEIXIN
|
||||||
// 微信小程序分享
|
// 微信小程序分享
|
||||||
uni.showActionSheet({
|
uni.showActionSheet({
|
||||||
itemList: ['发送给朋友', '分享到朋友圈'],
|
itemList: [Lang.lang('share.sendToFriend'), Lang.lang('share.shareToTimeline')],
|
||||||
success: (res) => {
|
success: (res) => {
|
||||||
if (res.tapIndex === 0) {
|
if (res.tapIndex === 0) {
|
||||||
// 发送给朋友
|
// 发送给朋友
|
||||||
@@ -71,10 +73,10 @@ export default {
|
|||||||
title: title,
|
title: title,
|
||||||
path: filePreviewUrl,
|
path: filePreviewUrl,
|
||||||
success: () => {
|
success: () => {
|
||||||
uni.showToast({ title: '分享成功', icon: 'success' });
|
uni.showToast({ title: Lang.lang('share.shareSuccess'), icon: 'success' });
|
||||||
},
|
},
|
||||||
fail: () => {
|
fail: () => {
|
||||||
uni.showToast({ title: '分享失败', icon: 'none' });
|
uni.showToast({ title: Lang.lang('share.shareFailed'), icon: 'none' });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
} else if (res.tapIndex === 1) {
|
} else if (res.tapIndex === 1) {
|
||||||
@@ -83,10 +85,10 @@ export default {
|
|||||||
title: desc,
|
title: desc,
|
||||||
path: filePreviewUrl,
|
path: filePreviewUrl,
|
||||||
success: () => {
|
success: () => {
|
||||||
uni.showToast({ title: '分享成功', icon: 'success' });
|
uni.showToast({ title: Lang.lang('share.shareSuccess'), icon: 'success' });
|
||||||
},
|
},
|
||||||
fail: () => {
|
fail: () => {
|
||||||
uni.showToast({ title: '分享失败', icon: 'none' });
|
uni.showToast({ title: Lang.lang('share.shareFailed'), icon: 'none' });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
415
common/js/splash-state.js
Normal file
415
common/js/splash-state.js
Normal 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
476
common/js/theme-override.js
Normal 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,
|
||||||
|
}
|
||||||
@@ -2,6 +2,8 @@
|
|||||||
* 将常用的Uniapp提供的函数,存放到这里,按需引用
|
* 将常用的Uniapp提供的函数,存放到这里,按需引用
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
import lang from './lang.js';
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 显示错误信息
|
* 显示错误信息
|
||||||
@@ -18,7 +20,7 @@ const showError = (err, useModal = false) => {
|
|||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
uni.showModal({
|
uni.showModal({
|
||||||
title: '错误提示',
|
title: lang.lang('uniappUtils.errorTip'),
|
||||||
content,
|
content,
|
||||||
showCancel: false,
|
showCancel: false,
|
||||||
})
|
})
|
||||||
@@ -51,7 +53,7 @@ export const copyTextAsync = (text, { copySuccess = '', copyFailed = '' } = {})
|
|||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
// 输入验证
|
// 输入验证
|
||||||
if (!text && text !== '') {
|
if (!text && text !== '') {
|
||||||
const error = new Error('复制文本不能为空');
|
const error = new Error(lang.lang('uniappUtils.copyTextEmpty'));
|
||||||
showError(error);
|
showError(error);
|
||||||
reject(error);
|
reject(error);
|
||||||
return;
|
return;
|
||||||
@@ -59,13 +61,13 @@ export const copyTextAsync = (text, { copySuccess = '', copyFailed = '' } = {})
|
|||||||
|
|
||||||
// 超时监测
|
// 超时监测
|
||||||
const timeoutId = setTimeout(() => {
|
const timeoutId = setTimeout(() => {
|
||||||
let error = new Error('复制操作长时间无响应,请检查相关权限及配置是否正确');
|
let error = new Error(lang.lang('uniappUtils.copyTimeout'));
|
||||||
// #ifdef MP-WEIXIN
|
// #ifdef MP-WEIXIN
|
||||||
error = new Error([
|
error = new Error([
|
||||||
'复制操作长时间无响应!',
|
lang.lang('uniappUtils.copyTimeoutTitle'),
|
||||||
'原因:',
|
lang.lang('uniappUtils.copyTimeoutReason'),
|
||||||
'1.微信平台->用户隐私保护指引->"剪贴板"功能未添加或审核未通过;',
|
lang.lang('uniappUtils.wechatClipboardReason1'),
|
||||||
'2.微信平台对剪贴板API调用频率有限制'
|
lang.lang('uniappUtils.wechatClipboardReason2')
|
||||||
].join('\r\n'));
|
].join('\r\n'));
|
||||||
// #endif
|
// #endif
|
||||||
showError(error, true);
|
showError(error, true);
|
||||||
@@ -96,7 +98,7 @@ export const copyTextAsync = (text, { copySuccess = '', copyFailed = '' } = {})
|
|||||||
clearTimeout(timeoutId);
|
clearTimeout(timeoutId);
|
||||||
try {
|
try {
|
||||||
uni.showToast({
|
uni.showToast({
|
||||||
title: err.message || err.errMsg || copyFailed || '复制失败',
|
title: err.message || err.errMsg || copyFailed || lang.lang('uniappUtils.copyFailed'),
|
||||||
icon: 'none',
|
icon: 'none',
|
||||||
duration: 2000
|
duration: 2000
|
||||||
});
|
});
|
||||||
|
|||||||
822
common/js/util-navigate.js
Normal file
822
common/js/util-navigate.js
Normal file
@@ -0,0 +1,822 @@
|
|||||||
|
/**
|
||||||
|
* 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] 是否解码 &
|
||||||
|
* @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;
|
||||||
|
}
|
||||||
|
|
||||||
|
// =============================================================
|
||||||
|
// extractInternalAppPath
|
||||||
|
// =============================================================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 从一个 URL 中提取"本 App 内部页面路径"。
|
||||||
|
*
|
||||||
|
* 背景 / 修复的 bug:
|
||||||
|
* 后台装修数据里,内部页面常被存成【绝对 URL】,例如
|
||||||
|
* https://host/hwappx/common/pages_tool/form/formdata?id=130
|
||||||
|
* diyRedirectTo 用 `wap_url.indexOf('http') != -1` 判断"外部链接",于是:
|
||||||
|
* - H5: 走 window.location.href → 整页刷新;点返回时整个 App 重启、启动屏重播、状态丢失
|
||||||
|
* - MP: 走 web-view → 本应原生跳转的内部页被塞进 web-view
|
||||||
|
* 本函数把这类"指向本 App 内部页面"的绝对 URL 还原成相对路径,
|
||||||
|
* 让 diyRedirectTo 改走内部页面分支(uni.navigateTo / SPA 跳转)。
|
||||||
|
*
|
||||||
|
* 判定规则(双闸门,避免误伤真正的外部站点):
|
||||||
|
* 闸门 1 —— host 校验(相对路径直接放行):
|
||||||
|
* 绝对 URL 的 host 必须与本 App 自己的域名【完全一致】(忽略端口, 大小写不敏感);
|
||||||
|
* 否则返回 null(视为真外链, 维持原逻辑)。
|
||||||
|
* ★ 完全一致是最严格的口径: 不同子域(如 xcx3 vs xcx6)、不同域名一律当外链,
|
||||||
|
* 彻底杜绝误伤 Shopify(xxx.myshopify.com/pages/about)、Facebook 等外站。
|
||||||
|
* 闸门 2 —— 路径校验:
|
||||||
|
* pathname 中出现以 App 页面根开头的段(pages / pages_xxx),
|
||||||
|
* 则从该段起截取为内部路径(以 '/' 开头),连同 query/hash 一起返回;
|
||||||
|
* 未命中返回 null。
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* const H = ['xcx6.aigc-quickapp.com']
|
||||||
|
* extractInternalAppPath('https://xcx6.aigc-quickapp.com/hwappx/common/pages_tool/form/formdata?id=1', H)
|
||||||
|
* // '/pages_tool/form/formdata?id=1' (域名完全一致 → 还原)
|
||||||
|
* extractInternalAppPath('https://xcx3.aigc-quickapp.com/hwappx/common/pages/index/index', H)
|
||||||
|
* // null (子域不同 → 维持外链)
|
||||||
|
* extractInternalAppPath('https://xxx.myshopify.com/pages/about-us', H)
|
||||||
|
* // null (外域名 → 维持外链,不误伤)
|
||||||
|
* extractInternalAppPath('/pages_goods/detail?id=9', H)
|
||||||
|
* // '/pages_goods/detail?id=9' (相对路径 → 内部)
|
||||||
|
*
|
||||||
|
* @param {string} url 绝对或相对 URL
|
||||||
|
* @param {string|string[]|true} [allowedHosts] 本 App 自己的域名(可传完整 URL 或纯 host,会自动提取);
|
||||||
|
* 传 `true` 表示【强制内部】—— 跳过 host 校验, 只要路径含 /pages 段就还原(用于 open_mode='internal')。
|
||||||
|
* @returns {string|null} 形如 '/pages_tool/form/formdata?id=1' 的内部路径,或 null
|
||||||
|
*/
|
||||||
|
export function extractInternalAppPath(url, allowedHosts) {
|
||||||
|
if (!url || typeof url !== 'string') return null;
|
||||||
|
let rest = url;
|
||||||
|
// 闸门 1: host 校验(完全一致);allowedHosts === true 时跳过(强制内部)
|
||||||
|
const hostMatch = rest.match(/^https?:\/\/([^/]*)/i);
|
||||||
|
if (hostMatch) {
|
||||||
|
if (allowedHosts !== true) {
|
||||||
|
const host = (hostMatch[1] || '').toLowerCase().replace(/:\d+$/, '');
|
||||||
|
const allow = _normalizeHostList(allowedHosts);
|
||||||
|
if (!host || allow.indexOf(host) === -1) return null; // 域名不完全一致 → 不改
|
||||||
|
}
|
||||||
|
rest = rest.substring(hostMatch[0].length);
|
||||||
|
}
|
||||||
|
// 闸门 2: 路径校验(找第一个"页面根段" /pages 或 /pages_xxx)
|
||||||
|
const pageMatch = rest.match(/\/pages(?:_[a-z0-9]+)?\//i);
|
||||||
|
if (!pageMatch) return null;
|
||||||
|
const internal = rest.substring(pageMatch.index);
|
||||||
|
return internal || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 把 allowedHosts 归一化成纯 host 数组(小写、去协议、去路径、去端口)。
|
||||||
|
* 入参每一项可以是完整 URL(https://host/xx/)或纯 host(host:port)。
|
||||||
|
* @param {string|string[]} hosts
|
||||||
|
* @returns {string[]}
|
||||||
|
*/
|
||||||
|
function _normalizeHostList(hosts) {
|
||||||
|
if (!hosts) return [];
|
||||||
|
const arr = Array.isArray(hosts) ? hosts : [hosts];
|
||||||
|
const out = [];
|
||||||
|
for (const h of arr) {
|
||||||
|
if (!h || typeof h !== 'string') continue;
|
||||||
|
let s = h.trim().toLowerCase();
|
||||||
|
const m = s.match(/^https?:\/\/([^/]*)/i);
|
||||||
|
if (m) s = m[1] || '';
|
||||||
|
else s = s.replace(/\/.*$/, ''); // 去掉可能带的 path
|
||||||
|
s = s.replace(/:\d+$/, ''); // 去端口
|
||||||
|
if (s) out.push(s);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 解析 link 的导航模式(统一开关)。用于 diyRedirectTo 决定内部页面绝对 URL 如何跳转。
|
||||||
|
*
|
||||||
|
* 取值来源(顶层字段 或 page_params 里, 大小写不敏感, 兼容驼峰 openMode):
|
||||||
|
* - open_mode = 'internal' | 'spa' → 'internal' 强制走内部 SPA(忽略域名是否一致)
|
||||||
|
* - open_mode = 'online' | 'web' → 'online' 强制走线上(H5 整页刷新 / MP web-view)
|
||||||
|
* - 未设置 / 其他 → 'auto' 自动: 域名完全一致才内部, 否则线上
|
||||||
|
*
|
||||||
|
* @param {Object} link
|
||||||
|
* @returns {'internal'|'online'|'auto'}
|
||||||
|
*/
|
||||||
|
export function resolveNavMode(link) {
|
||||||
|
if (!link || typeof link !== 'object') return 'auto';
|
||||||
|
const pp = (link.page_params && typeof link.page_params === 'object') ? link.page_params : {};
|
||||||
|
const raw = link.open_mode != null ? link.open_mode
|
||||||
|
: (link.openMode != null ? link.openMode
|
||||||
|
: (pp.open_mode != null ? pp.open_mode : pp.openMode));
|
||||||
|
const m = (typeof raw === 'string') ? raw.trim().toLowerCase() : '';
|
||||||
|
if (m === 'internal' || m === 'spa') return 'internal';
|
||||||
|
if (m === 'online' || m === 'web') return 'online';
|
||||||
|
return 'auto';
|
||||||
|
}
|
||||||
|
|
||||||
|
// =============================================================
|
||||||
|
// hasStaleUniacidInUrl
|
||||||
|
// =============================================================
|
||||||
|
// pickCurrentUniacid
|
||||||
|
// =============================================================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 从两个候选 uniacid 源中选出"系统当前 uniacid"。
|
||||||
|
*
|
||||||
|
* 用法(当前 diyRedirectTo 中的实际调用, 必须与 http.js 行 168 保持一致):
|
||||||
|
* pickCurrentUniacid(
|
||||||
|
* uni.getStorageSync('uniacid'), // 持久化, 登录/初始化写入
|
||||||
|
* Config.uniacid, // 编译期兜底
|
||||||
|
* )
|
||||||
|
*
|
||||||
|
* 优先级: 第一个参数非 0 → 选第一个; 否则选第二个非 0 值; 都没有 → 0。
|
||||||
|
* 0 视为"无 uniacid": 业务上 uniacid 不会是 0, parseInt 后为 0 也算无效。
|
||||||
|
*
|
||||||
|
* ★ 注意: 故意【不读 store.state.uniacid】。当前代码库里 store.state 上从未设置
|
||||||
|
* uniacid 字段(http.js 只用 storage/Config), 若引入 store 分支会出现
|
||||||
|
* "守卫用 A 真值, http 请求用 B 真值"的不一致。
|
||||||
|
*
|
||||||
|
* @param {*} primaryValue 第一候选(运行时持久化值)
|
||||||
|
* @param {*} secondaryValue 第二候选(编译期兜底)
|
||||||
|
* @returns {number} 选出的 uniacid; 都无效时返回 0
|
||||||
|
*/
|
||||||
|
export function pickCurrentUniacid(primaryValue, secondaryValue) {
|
||||||
|
const a = parseInt(primaryValue, 10);
|
||||||
|
if (a) return a; // 非 0 真值
|
||||||
|
const b = parseInt(secondaryValue, 10);
|
||||||
|
if (b) return b;
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// =============================================================
|
||||||
|
// hasStaleUniacidInUrl
|
||||||
|
// =============================================================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 检测 link.wap_url 中【URL 原生】的 uniacid query 与系统当前 uniacid 是否一致。
|
||||||
|
*
|
||||||
|
* 用途: uniacid 是平台租户 ID, 会随租户迁移 / 平台调整而变化。
|
||||||
|
* - 如果数据里的 wap_url 自带的 uniacid 与当前系统不一致,
|
||||||
|
* 说明这份装修数据可能是历史遗留或别的租户的(脏数据),
|
||||||
|
* 不应该被自动改写成内部 SPA(否则会跳到错租户的内页 / 拿错数据)。
|
||||||
|
* - 应当保守地走外链(整页 / web-view), 让原 URL(及其 uniacid)如实生效。
|
||||||
|
*
|
||||||
|
* 关键: 必须【在 resolveLinkUrl 抽走 query 之前】判断, 否则 URL 里的 uniacid 已经
|
||||||
|
* 被搬到 page_params 里, 分不清"URL 原生"还是"外加的"。
|
||||||
|
*
|
||||||
|
* 比较规则: 两侧 parseInt 后比较, 兼容 '2482' vs 2482、URL 编码、空值。
|
||||||
|
*
|
||||||
|
* @param {string} wap_url link.wap_url (resolveLinkUrl 之前的原始值)
|
||||||
|
* @param {string|number|null} currentUniacid 系统当前的 uniacid
|
||||||
|
* (0 / null / '' / undefined 一律视为"无当前 uniacid", 返回 false — 让上游决定怎么做)
|
||||||
|
* @returns {boolean} true = URL 原生 uniacid 与当前不一致(脏数据, 该强制走线上)
|
||||||
|
*/
|
||||||
|
export function hasStaleUniacidInUrl(wap_url, currentUniacid) {
|
||||||
|
if (!wap_url || typeof wap_url !== 'string') return false;
|
||||||
|
if (currentUniacid == null || currentUniacid === '' || currentUniacid === 0) return false;
|
||||||
|
const m = wap_url.match(/[?&]uniacid=([^&#]*)/i);
|
||||||
|
if (!m) return false;
|
||||||
|
let urlUniacid;
|
||||||
|
try { urlUniacid = decodeURIComponent(m[1]); } catch (e) { urlUniacid = m[1]; }
|
||||||
|
const cur = String(currentUniacid);
|
||||||
|
const a = parseInt(urlUniacid, 10);
|
||||||
|
const b = parseInt(cur, 10);
|
||||||
|
// 两侧都能 parse 成数字时按数字比; 否则按字符串比
|
||||||
|
if (!Number.isNaN(a) && !Number.isNaN(b)) return a !== b;
|
||||||
|
return urlUniacid !== cur;
|
||||||
|
}
|
||||||
|
|
||||||
|
// =============================================================
|
||||||
|
// 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 仅编码 URL 分隔符 / 边界相关字符,保留中文 / ASCII 字母数字原样
|
||||||
|
*
|
||||||
|
* 解决问题:
|
||||||
|
* - 微信小程序: 不会对 url 做整体 encode,只 split on '&' / '=',但 **不** decode 值
|
||||||
|
* 给 onLoad。所以 JS 必须 encode `&` `=` `?` `#` 空格(防止 query 边界被破坏),
|
||||||
|
* 但 **不能** encode 中文(否则 onLoad 拿到已编码字符串,显示成乱码)。
|
||||||
|
* - 鸿蒙元服务: 会整体 encode url(包括中文和已编码的 %xx)。
|
||||||
|
* 所以 JS 完全不 encode(让平台做)。见下面 mp-harmony 分支。
|
||||||
|
* - H5 / 快应用: 浏览器不 encode,JS 必须 encode 一次(用标准 encodeURIComponent)。
|
||||||
|
*
|
||||||
|
* @param {string} s 已 decode roundtrip 后的原文
|
||||||
|
* @returns {string}
|
||||||
|
*/
|
||||||
|
function _encodeUrlDelimiters(s) {
|
||||||
|
// 只 replace 这 5 个 URL 分隔 / 边界相关字符,其他(中文 / 字母 / 数字 / 标点等)原样
|
||||||
|
return s.replace(/[&=#?\s]/g, c => encodeURIComponent(c));
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
const platform = getPlatform();
|
||||||
|
|
||||||
|
// 微信小程序: split on '&' / '=' 解析 url,但不 decode value 给 onLoad。
|
||||||
|
// - 中文 / 字母 / 数字 → 原样保留(否则 onLoad 拿到 %xx 乱码)
|
||||||
|
// - `&` `=` `?` `#` 空格 → 必须 encode(否则 query 边界被破坏, src 等含 URL 的字段被截断,webview 打不开)
|
||||||
|
if (platform === 'mp-weixin') {
|
||||||
|
return _encodeUrlDelimiters(once);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 鸿蒙元服务: uni.navigateTo 内部整体 encode url(把中文、& 等都 encode)。
|
||||||
|
// JS 侧完全不 encode,直接返回 decode roundtrip 后的原文,让鸿蒙原生做唯一一次 encode。
|
||||||
|
// (再 encode 会双重编码 → onLoad 拿到 %E6%B2%99%E5%8F%91 乱码)
|
||||||
|
// webview URL 含 & 时, JS 不 encode,鸿蒙原生 encode 后 & 变 %26,webview 能正常打开。
|
||||||
|
if (platform === 'mp-harmony') {
|
||||||
|
return once;
|
||||||
|
}
|
||||||
|
|
||||||
|
// H5 / 华为快应用: 浏览器不自动编码, JS 侧必须主动 encode 一次(标准 encodeURIComponent)
|
||||||
|
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,
|
||||||
|
extractInternalAppPath,
|
||||||
|
parsePageParams,
|
||||||
|
resolveLinkUrl,
|
||||||
|
decodeEntity,
|
||||||
|
};
|
||||||
|
}
|
||||||
649
common/js/util-tabbar.js
Normal file
649
common/js/util-tabbar.js
Normal 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;
|
||||||
|
}
|
||||||
1111
common/js/util.js
1111
common/js/util.js
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,8 @@
|
|||||||
/**
|
/**
|
||||||
* 企业微信JS-SDK调用
|
* 企业微信JS-SDK调用
|
||||||
*/
|
*/
|
||||||
|
import Lang from './lang.js';
|
||||||
|
|
||||||
let WxWork = function () {
|
let WxWork = function () {
|
||||||
// 企业微信JS-SDK
|
// 企业微信JS-SDK
|
||||||
this.wxwork = null;
|
this.wxwork = null;
|
||||||
@@ -23,7 +25,7 @@ let WxWork = function () {
|
|||||||
// H5环境下的企业微信
|
// H5环境下的企业微信
|
||||||
this.wxwork = WWOpenData;
|
this.wxwork = WWOpenData;
|
||||||
} else {
|
} else {
|
||||||
console.error('企业微信JS-SDK未加载');
|
console.error(Lang.lang('wxworkJssdk.notLoaded'));
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -56,8 +58,8 @@ let WxWork = function () {
|
|||||||
*/
|
*/
|
||||||
this.addContact = function (params, success, fail) {
|
this.addContact = function (params, success, fail) {
|
||||||
if (!this.wxwork) {
|
if (!this.wxwork) {
|
||||||
console.error('企业微信JS-SDK未初始化');
|
console.error(Lang.lang('wxworkJssdk.notInitialized'));
|
||||||
if (fail) fail('企业微信JS-SDK未初始化');
|
if (fail) fail(Lang.lang('wxworkJssdk.notInitialized'));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -69,7 +71,7 @@ let WxWork = function () {
|
|||||||
if (res.err_msg === 'openUserProfile:ok') {
|
if (res.err_msg === 'openUserProfile:ok') {
|
||||||
if (success) success(res);
|
if (success) success(res);
|
||||||
} else {
|
} else {
|
||||||
console.error('打开用户资料失败:', res);
|
console.error(Lang.lang('wxworkJssdk.openUserProfileFailed'), res);
|
||||||
if (fail) fail(res.err_msg);
|
if (fail) fail(res.err_msg);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -87,8 +89,8 @@ let WxWork = function () {
|
|||||||
*/
|
*/
|
||||||
this.openCustomerService = function (params, success, fail) {
|
this.openCustomerService = function (params, success, fail) {
|
||||||
if (!this.wxwork) {
|
if (!this.wxwork) {
|
||||||
console.error('企业微信JS-SDK未初始化');
|
console.error(Lang.lang('wxworkJssdk.notInitialized'));
|
||||||
if (fail) fail('企业微信JS-SDK未初始化');
|
if (fail) fail(Lang.lang('wxworkJssdk.notInitialized'));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
73
common/mixin/i18n-lazy.js
Normal file
73
common/mixin/i18n-lazy.js
Normal 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();
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -12,7 +12,7 @@
|
|||||||
</view>
|
</view>
|
||||||
<image v-else class="left-img" :src="$util.img(value.titleStyle.leftImg)" mode="heightFix" show-menu-by-longpress></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'"
|
<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"
|
<view class="head-right"
|
||||||
:style="{ fontSize: value.titleStyle.moreFontSize * 2 + 'rpx', color: value.titleStyle.moreColor }"
|
:style="{ fontSize: value.titleStyle.moreFontSize * 2 + 'rpx', color: value.titleStyle.moreColor }"
|
||||||
@tap.stop="$util.redirectTo('/pages_promotion/bargain/list')">
|
@tap.stop="$util.redirectTo('/pages_promotion/bargain/list')">
|
||||||
@@ -45,18 +45,18 @@
|
|||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
<view class="num" v-if="item.is_bargaining">
|
<view class="num" v-if="item.is_bargaining">
|
||||||
已砍
|
{{ $lang('components-diy.diy-bargain.bargained') }}
|
||||||
<text>¥{{ (item.price - item.curr_price).toFixed(2) }}</text>
|
<text>¥{{ (item.price - item.curr_price).toFixed(2) }}</text>
|
||||||
,仅差
|
{{ $lang('components-diy.diy-bargain.onlyDiff') }}
|
||||||
<text>¥{{ item.curr_price }}</text>
|
<text>¥{{ item.curr_price }}</text>
|
||||||
</view>
|
</view>
|
||||||
<view class="num" v-else>
|
<view class="num" v-else>
|
||||||
最低可砍至
|
{{ $lang('components-diy.diy-bargain.minBargainTo') }}
|
||||||
<text>¥{{ item.floor_price }}</text>
|
<text>¥{{ item.floor_price }}</text>
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
<view class="progress" v-if="value.style == 'style-3'">
|
<view class="progress" v-if="value.style == 'style-3'">
|
||||||
最低可砍至
|
{{ $lang('components-diy.diy-bargain.minBargainTo') }}
|
||||||
<text class="num">¥{{ item.floor_price }}</text>
|
<text class="num">¥{{ item.floor_price }}</text>
|
||||||
</view>
|
</view>
|
||||||
<view class="price-wrap">
|
<view class="price-wrap">
|
||||||
@@ -75,7 +75,7 @@
|
|||||||
color: value.btnStyle.theme == 'diy' ? value.btnStyle.textColor : '',
|
color: value.btnStyle.theme == 'diy' ? value.btnStyle.textColor : '',
|
||||||
borderRadius: value.btnStyle.aroundRadius * 2 + 'rpx'
|
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>
|
</button>
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
@@ -96,7 +96,7 @@
|
|||||||
<view class="num"
|
<view class="num"
|
||||||
v-if="value.saleStyle.control && value.template == 'horizontal-slide' && value.style != 'style-2'"
|
v-if="value.saleStyle.control && value.template == 'horizontal-slide' && value.style != 'style-2'"
|
||||||
:style="{ color: value.theme == 'diy' ? value.saleStyle.color : '' }">
|
:style="{ color: value.theme == 'diy' ? value.saleStyle.color : '' }">
|
||||||
已砍{{ item.sale_num }}件
|
{{ $lang('components-diy.diy-bargain.soldCount', { num: item.sale_num }) }}
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
<view :class="['content', { 'multi-content': value.nameLineMode == 'multiple' }]"
|
<view :class="['content', { 'multi-content': value.nameLineMode == 'multiple' }]"
|
||||||
@@ -141,7 +141,7 @@
|
|||||||
<view class="num"
|
<view class="num"
|
||||||
v-if="value.saleStyle.control && value.template == 'horizontal-slide' && value.style != 'style-2'"
|
v-if="value.saleStyle.control && value.template == 'horizontal-slide' && value.style != 'style-2'"
|
||||||
:style="{ color: value.theme == 'diy' ? value.saleStyle.color : '' }">
|
:style="{ color: value.theme == 'diy' ? value.saleStyle.color : '' }">
|
||||||
已砍{{ item.sale_num }}件
|
{{ $lang('components-diy.diy-bargain.soldCount', { num: item.sale_num }) }}
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
<view :class="['content', { 'multi-content': value.nameLineMode == 'multiple' }]"
|
<view :class="['content', { 'multi-content': value.nameLineMode == 'multiple' }]"
|
||||||
@@ -461,7 +461,10 @@ scroll-view ::-webkit-scrollbar {
|
|||||||
align-items: center;
|
align-items: center;
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
height: 36rpx;
|
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;
|
border-radius: 24rpx;
|
||||||
padding: 2rpx;
|
padding: 2rpx;
|
||||||
|
|
||||||
@@ -474,7 +477,9 @@ scroll-view ::-webkit-scrollbar {
|
|||||||
text:nth-child(2) {
|
text:nth-child(2) {
|
||||||
padding: 6rpx 4rpx 4rpx;
|
padding: 6rpx 4rpx 4rpx;
|
||||||
background-color: #fff;
|
background-color: #fff;
|
||||||
color: #ffbd5b;
|
// P0: 砍价头文字色 → var(--pintuan-label-grad-start) 复用
|
||||||
|
// 兼容: 微信小程序 / 鸿蒙元服务 — color 接受 var() 无问题
|
||||||
|
color: var(--pintuan-label-grad-start, #ffbd5b);
|
||||||
border-radius: 50%;
|
border-radius: 50%;
|
||||||
transform: scale(0.6);
|
transform: scale(0.6);
|
||||||
font-weight: bold;
|
font-weight: bold;
|
||||||
@@ -576,7 +581,9 @@ scroll-view ::-webkit-scrollbar {
|
|||||||
width: auto;
|
width: auto;
|
||||||
height: 20rpx;
|
height: 20rpx;
|
||||||
border-radius: 20rpx;
|
border-radius: 20rpx;
|
||||||
background-color: #ffeadb;
|
// P0: 砍价浅底 → var(--bargain-promo-shallow)
|
||||||
|
// 兼容: 微信小程序 / 鸿蒙元服务 — background-color 接受 var() 无问题
|
||||||
|
background-color: var(--bargain-promo-shallow, #ffeadb);
|
||||||
position: relative;
|
position: relative;
|
||||||
|
|
||||||
&::after {
|
&::after {
|
||||||
@@ -584,7 +591,9 @@ scroll-view ::-webkit-scrollbar {
|
|||||||
width: 26rpx;
|
width: 26rpx;
|
||||||
height: 26rpx;
|
height: 26rpx;
|
||||||
border-radius: 50%;
|
border-radius: 50%;
|
||||||
background-color: #fa1a1a;
|
// P0: 砍价红圆点 → var(--bargain-promo-color)
|
||||||
|
// 兼容: 微信小程序 / 鸿蒙元服务 — background-color 接受 var() 无问题
|
||||||
|
background-color: var(--bargain-promo-color, #fa1a1a);
|
||||||
position: absolute;
|
position: absolute;
|
||||||
top: 50%;
|
top: 50%;
|
||||||
transform: translateY(-50%);
|
transform: translateY(-50%);
|
||||||
@@ -595,7 +604,9 @@ scroll-view ::-webkit-scrollbar {
|
|||||||
width: 0;
|
width: 0;
|
||||||
height: 20rpx;
|
height: 20rpx;
|
||||||
border-radius: 20rpx;
|
border-radius: 20rpx;
|
||||||
background-color: #fa1a1a;
|
// P0: 砍价红进度条 → var(--bargain-promo-color)
|
||||||
|
// 兼容: 微信小程序 / 鸿蒙元服务 — background-color 接受 var() 无问题
|
||||||
|
background-color: var(--bargain-promo-color, #fa1a1a);
|
||||||
position: relative;
|
position: relative;
|
||||||
|
|
||||||
.progress-bar {
|
.progress-bar {
|
||||||
@@ -618,7 +629,9 @@ scroll-view ::-webkit-scrollbar {
|
|||||||
line-height: 1;
|
line-height: 1;
|
||||||
|
|
||||||
text {
|
text {
|
||||||
color: #fa1a1a;
|
// P0: 砍价数字红 → var(--bargain-promo-color)
|
||||||
|
// 兼容: 微信小程序 / 鸿蒙元服务 — color 接受 var() 无问题
|
||||||
|
color: var(--bargain-promo-color, #fa1a1a);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,54 +1,39 @@
|
|||||||
<template>
|
<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="tab-bar" :style="{ backgroundColor: tabBarList.backgroundColor }">
|
||||||
<view class="tabbar-border"></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="item" v-for="(item, index) in tabBarList.list" :key="item.id" @tap.stop="redirectTo(item.link)">
|
||||||
<view class="bd">
|
<view class="bd">
|
||||||
<block v-if="item.link.wap_url == '/pages_goods/cart'">
|
<view class="icon" v-if="tabBarList.type == 1 || tabBarList.type == 2"
|
||||||
<view class="icon" v-if="tabBarList.type == 1 || tabBarList.type == 2"
|
:animation="isCartItem(item.link) ? cartAnimation : null"
|
||||||
:animation="cartAnimation" id="tabbarCart">
|
:id="isCartItem(item.link) ? 'tabbarCart' : null">
|
||||||
<block v-if="verify(item.link)">
|
<block v-if="verify(item.link)">
|
||||||
<image v-if="item.selected_icon_type == 'img'"
|
<image v-if="item.selected_icon_type == 'img'"
|
||||||
:src="$util.img(item.selectedIconPath)" />
|
:src="$util.img(item.selectedIconPath)" />
|
||||||
<diy-icon v-if="item.selected_icon_type == 'icon'" :icon="item.selectedIconPath"
|
<diy-icon v-if="item.selected_icon_type == 'icon'" :icon="item.selectedIconPath"
|
||||||
:value="item.selected_style ? item.selected_style : null"></diy-icon>
|
: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>
|
|
||||||
</block>
|
</block>
|
||||||
<block v-else>
|
<block v-else>
|
||||||
<view class="icon" v-if="tabBarList.type == 1 || tabBarList.type == 2">
|
<image v-if="item.icon_type == 'img'" :src="$util.img(item.iconPath)" />
|
||||||
<block v-if="verify(item.link)">
|
<diy-icon v-if="item.icon_type == 'icon'" :icon="item.iconPath"
|
||||||
<image v-if="item.selected_icon_type == 'img'"
|
:value="item.style ? item.style : null"></diy-icon>
|
||||||
: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>
|
|
||||||
</block>
|
</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"
|
<view class="label"
|
||||||
v-if="(tabBarList.type == 1 || tabBarList.type == 3) && tabBarList.theme == 'diy'"
|
v-if="(tabBarList.type == 1 || tabBarList.type == 3) && tabBarList.theme == 'diy'"
|
||||||
:style="{ color: verify(item.link) ? tabBarList.textHoverColor : tabBarList.textColor }">
|
:style="{ color: verify(item.link) ? tabBarList.textHoverColor : tabBarList.textColor }">
|
||||||
{{ lang == 'en-us' ? item.en_text : item.text }}
|
{{ $langConfig.getField(item, 'text') }}
|
||||||
</view>
|
</view>
|
||||||
<view class="label"
|
<view class="label"
|
||||||
v-if="(tabBarList.type == 1 || tabBarList.type == 3) && tabBarList.theme == 'default'"
|
v-if="(tabBarList.type == 1 || tabBarList.type == 3) && tabBarList.theme == 'default'"
|
||||||
:style="{ color: verify(item.link) ? 'var(--base-color)' : '#333333' }">
|
:style="{ color: verify(item.link) ? 'var(--base-color)' : '#333333' }">
|
||||||
{{ lang == 'en-us' ? item.en_text : item.text }}
|
{{ $langConfig.getField(item, 'text') }}
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
@@ -59,7 +44,8 @@
|
|||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script>
|
<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'
|
import DiyMinx from './minx.js'
|
||||||
// 底部导航栏
|
// 底部导航栏
|
||||||
export default {
|
export default {
|
||||||
@@ -76,7 +62,6 @@ export default {
|
|||||||
mixins: [DiyMinx],
|
mixins: [DiyMinx],
|
||||||
data() {
|
data() {
|
||||||
return {
|
return {
|
||||||
lang: uni.getStorageSync("lang"),
|
|
||||||
currentRoute: '', //当前页面路径
|
currentRoute: '', //当前页面路径
|
||||||
jumpFlag: true, //是否可以跳转,防止重复点击
|
jumpFlag: true, //是否可以跳转,防止重复点击
|
||||||
cartAnimation: {}
|
cartAnimation: {}
|
||||||
@@ -105,9 +90,25 @@ export default {
|
|||||||
});
|
});
|
||||||
},
|
},
|
||||||
computed: {
|
computed: {
|
||||||
|
// 当前语言(响应式):通过 componentRefresh 建立依赖,切语言时自动更新
|
||||||
|
// 不能直接用 uni.getStorageSync 作为 data,因为它不是响应式的
|
||||||
|
currentLang() {
|
||||||
|
// 通过 componentRefresh 建立响应式依赖
|
||||||
|
// 切语言时 store 中的 componentRefresh 会 +1,触发重新计算
|
||||||
|
this.componentRefresh;
|
||||||
|
return uni.getStorageSync("lang") || 'zh-cn';
|
||||||
|
},
|
||||||
cartChange() {
|
cartChange() {
|
||||||
return this.$store.state.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: {
|
watch: {
|
||||||
cartChange: function (nval, oval) {
|
cartChange: function (nval, oval) {
|
||||||
@@ -123,38 +124,148 @@ export default {
|
|||||||
this.cartAnimation = animation.export();
|
this.cartAnimation = animation.export();
|
||||||
}, 300);
|
}, 300);
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
|
// tabBarList 异步加载完成后, 补一次 updateCurrentRoute
|
||||||
|
// 修复: 冷启动时用户在 tabBarList 就绪前点击链接, 第一次 updateCurrentRoute 是 no-op
|
||||||
|
tabBarReady: {
|
||||||
|
handler(ready) {
|
||||||
|
if (ready) {
|
||||||
|
this.updateCurrentRoute();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
immediate: false,
|
||||||
|
},
|
||||||
},
|
},
|
||||||
methods: {
|
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() {
|
updateCurrentRoute() {
|
||||||
let currentPage = getCurrentPages()[getCurrentPages().length - 1];
|
const currentPages = getCurrentPages();
|
||||||
if (currentPage && currentPage.route) {
|
const currentPage = currentPages[currentPages.length - 1];
|
||||||
this.currentRoute = currentPage.route;
|
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) {
|
redirectTo(link) {
|
||||||
this.$emit('callback');
|
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) {
|
verify(link) {
|
||||||
if (link == null || link == '' || !link.wap_url) return false;
|
if (link == null || link == '' || !link.wap_url) return false;
|
||||||
|
|
||||||
// 标准化路径格式,确保比较的一致性
|
const currentPages = getCurrentPages();
|
||||||
let currentPageRoute = this.currentRoute ? '/' + this.currentRoute : '';
|
const currentPage = currentPages[currentPages.length - 1];
|
||||||
let linkUrl = link.wap_url;
|
const currentPageRoute = currentPage && currentPage.route
|
||||||
|
? this._normalizeRoute(currentPage.route)
|
||||||
|
: '';
|
||||||
|
|
||||||
// 首页特殊处理
|
// 读取当前页面 query 参数(兼容小程序与 H5)
|
||||||
if (linkUrl === this.$util.INDEX_PAGE_URL && this.name === 'DIY_VIEW_INDEX') {
|
let currentPageQuery = {};
|
||||||
return true;
|
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 (this.name === 'DIY_VIEW_INDEX') {
|
||||||
if (adaptSubpackageUrl(linkUrl) === currentPageRoute) {
|
// DIY_VIEW_INDEX 短路: 当 name 是 DIY_VIEW_INDEX 时, 任意匹配的 tab 都高亮
|
||||||
return true;
|
// 修复前: 只对 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 {
|
.tab-bar {
|
||||||
background-color: #fff;
|
background-color: #fff;
|
||||||
box-sizing: border-box;
|
box-sizing: border-box;
|
||||||
position: fixed;
|
/* ============================================================
|
||||||
left: 0;
|
* 固定在最底端,不能位置漂移(微信小程序 / 鸿蒙元服务 / 快应用 H5)
|
||||||
bottom: 0;
|
* ------------------------------------------------------------
|
||||||
|
* 现象(只在客户端小程序里复现,浏览器 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%;
|
width: 100%;
|
||||||
z-index: 998;
|
z-index: 2147483647 !important;
|
||||||
display: flex;
|
display: flex;
|
||||||
border-top: 2rpx solid #f5f5f5;
|
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: 0;
|
||||||
padding-bottom: constant(safe-area-inset-bottom);
|
padding-bottom: constant(safe-area-inset-bottom);
|
||||||
padding-bottom: env(safe-area-inset-bottom);
|
padding-bottom: env(safe-area-inset-bottom);
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -1,11 +1,20 @@
|
|||||||
<template>
|
<template>
|
||||||
<view data-component-name="diy-category" :class="['category-page-wrap', 'category-template-' + value.template]"
|
<view data-component-name="diy-category" :class="['category-page-wrap', 'category-template-' + value.template]"
|
||||||
:style="{ height: 'calc(100vh - ' + tabBarHeight + ')' }">
|
:style="{ height: 'calc(100vh - ' + tabBarHeight + ')' }">
|
||||||
|
<!-- 模板4: 顶部搜索框(图片样式) -->
|
||||||
|
<view class="search-box search-box-template-4" v-if="value.template == 4 && value.search"
|
||||||
|
@tap.stop="onClickSearch()">
|
||||||
|
<view class="search-content">
|
||||||
|
<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>
|
||||||
<!-- #ifdef MP-WEIXIN -->
|
<!-- #ifdef MP-WEIXIN -->
|
||||||
<!-- <block v-if="value.template == 4">
|
<!-- <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-box" v-if="value.search" @tap.stop="$util.redirectTo('/pages_tool/goods/search')" :style="navbarInnerStyle">
|
||||||
<view class="search-content">
|
<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>
|
<text class="iconfont icon-sousuo3"></text>
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
@@ -16,7 +25,7 @@
|
|||||||
<view class="search-box" v-if="value.search" @tap.stop="onClickSearch()"
|
<view class="search-box" v-if="value.search" @tap.stop="onClickSearch()"
|
||||||
:style="wxSearchHeight">
|
:style="wxSearchHeight">
|
||||||
<view class="search-content">
|
<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()"
|
confirm-type="search" @tap.stop="onClickSearch()"
|
||||||
disabled="true" />
|
disabled="true" />
|
||||||
<text class="iconfont icon-sousuo3"></text>
|
<text class="iconfont icon-sousuo3"></text>
|
||||||
@@ -26,16 +35,18 @@
|
|||||||
</view>
|
</view>
|
||||||
</block>
|
</block>
|
||||||
<!-- #endif -->
|
<!-- #endif -->
|
||||||
<!-- #ifdef H5 -->
|
<!-- #ifdef H5 || MP-HARMONY -->
|
||||||
<view class="search-box" v-if="value.search" @tap.stop="onClickSearch()">
|
|
||||||
|
<view class="search-box" v-if="value.search && value.template != 4" @tap.stop="onClickSearch()">
|
||||||
<view class="search-content">
|
<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" />
|
@tap.stop="onClickSearch()" disabled="true" />
|
||||||
<text class="iconfont icon-sousuo3"></text>
|
<text class="iconfont icon-sousuo3"></text>
|
||||||
</view>
|
</view>
|
||||||
<view class="iconfont" :class="{ 'icon-apps': !isList, 'icon-list': isList }"
|
<view class="iconfont" :class="{ 'icon-apps': !isList, 'icon-list': isList }"
|
||||||
@tap.stop.prevent="changeListStyle()"></view>
|
@tap.stop.prevent="changeListStyle()"></view>
|
||||||
</view>
|
</view>
|
||||||
|
|
||||||
<!-- #endif -->
|
<!-- #endif -->
|
||||||
<view class="template-four wx" v-if="value.template == 4">
|
<view class="template-four wx" v-if="value.template == 4">
|
||||||
<scroll-view scroll-x="true" class="template-four-wrap" :scroll-with-animation="true"
|
<scroll-view scroll-x="true" class="template-four-wrap" :scroll-with-animation="true"
|
||||||
@@ -51,7 +62,7 @@
|
|||||||
</scroll-view>
|
</scroll-view>
|
||||||
<view class="category-item-all" @tap.stop="$refs.templateFourPopup.open()">
|
<view class="category-item-all" @tap.stop="$refs.templateFourPopup.open()">
|
||||||
<view class="category-item-all-wrap">
|
<view class="category-item-all-wrap">
|
||||||
<text class="text">展开</text>
|
<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>
|
<image class="img" :src="$util.img('/public/uniapp/category/unfold.png')" mode="aspectFill" show-menu-by-longpress></image>
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
@@ -68,7 +79,7 @@
|
|||||||
</view>
|
</view>
|
||||||
</scroll-view>
|
</scroll-view>
|
||||||
<view class="pack-up" @tap.stop="$refs.templateFourPopup.close()">
|
<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>
|
<text class="iconfont icon-iconangledown-copy"></text>
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
@@ -79,31 +90,70 @@
|
|||||||
<block v-if="categoryTree.length">
|
<block v-if="categoryTree.length">
|
||||||
<scroll-view scroll-y="true" class="tree-wrap">
|
<scroll-view scroll-y="true" class="tree-wrap">
|
||||||
<view class="category-item-wrap">
|
<view class="category-item-wrap">
|
||||||
<view class="category-item" v-for="(item, index) in categoryTree" :key="index" :class="[
|
<!-- 模板4: 左侧显示一级分类(顶部轮播中的分类) -->
|
||||||
{ select: select == index },
|
<view v-if="value.template == 4">
|
||||||
{ 'border-bottom': value.template == 4 && select + 1 === index },
|
<view class="category-item" v-for="(item, index) in templateFourData" :key="'one-' + index" :class="[
|
||||||
{ 'border-top': value.template == 4 && select - 1 === index }
|
{ select: oneCategorySelect == index },
|
||||||
]" @tap.stop="switchOneCategory(index)">
|
{ 'border-bottom': oneCategorySelect + 1 === index },
|
||||||
<view class="">{{ item.category_name }}</view>
|
{ 'border-top': oneCategorySelect - 1 === index }
|
||||||
|
]" @tap.stop="templateFourOneFn(index)">
|
||||||
|
<view class="">{{ item.category_name }}</view>
|
||||||
|
</view>
|
||||||
|
</view>
|
||||||
|
<!-- 其他模板: 左侧显示二级分类 -->
|
||||||
|
<view v-else>
|
||||||
|
<view class="category-item" v-for="(item, index) in categoryTree" :key="index" :class="[
|
||||||
|
{ select: select == index },
|
||||||
|
{ 'border-bottom': value.template == 4 && select + 1 === index },
|
||||||
|
{ 'border-top': value.template == 4 && select - 1 === index }
|
||||||
|
]" @tap.stop="switchOneCategory(index)">
|
||||||
|
<view class="">{{ item.category_name }}</view>
|
||||||
|
</view>
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
</scroll-view>
|
</scroll-view>
|
||||||
|
|
||||||
<view class="right-flex-wrap">
|
<view class="right-flex-wrap">
|
||||||
<scroll-view scroll-y="true" class="content-wrap" v-if="value.template == 1 || loadType == 'all'"
|
<!-- 模板99 + 二级分类: 全局二级分类按钮(去重, 一直显示) + 商品列表 -->
|
||||||
ref="contentWrap" :scroll-into-view="categoryId" :scroll-with-animation="true"
|
<scroll-view scroll-y="true" class="content-wrap" v-if="value.template == 99 && template99Category"
|
||||||
@scroll="listenScroll" @touchstart="touchStart" :refresher-enabled="true"
|
:refresher-enabled="true" refresher-default-style="none"
|
||||||
refresher-default-style="none" :refresher-triggered="triggered" @refresherrefresh="onRefresh"
|
:refresher-triggered="triggered" @refresherrefresh="onRefresh" @refresherrestore="onRestore">
|
||||||
@refresherrestore="onRestore">
|
<diy-category-item :category="template99Category" :value="value" ref="categoryItem" :index="0" :select="0"
|
||||||
<view class="child-category" v-for="(item, index) in categoryTree" :key="index"
|
:oneCategorySelect="oneCategorySelect" :isList="isList"
|
||||||
:id="'category-' + index">
|
:currentOneCategory="categoryTree && categoryTree[select] ? categoryTree[select] : null"
|
||||||
<diy-category-item :category="item" :value="value" ref="categoryItem" :index="index"
|
:lastSecondCategoryName="lastSecondCategoryName"
|
||||||
:select="select" :oneCategorySelect="oneCategorySelect" :isList="isList"
|
@tologin="toLogin" @selectsku="selectSku($event, 0)" @addCart="addCartPoint"
|
||||||
@tologin="toLogin" @selectsku="selectSku($event, index)" @addCart="addCartPoint"
|
@saveSecondCategory="saveSecondCategoryName"></diy-category-item>
|
||||||
@loadfinish="getHeightArea"></diy-category-item>
|
</scroll-view>
|
||||||
</view>
|
|
||||||
<view class="end-tips" ref="endTips" :style="{ opacity: endTips }">已经到底了~</view>
|
<!-- 模板1: 仿京东/淘宝商品分类 - 按 template 2 的 part-load 逻辑, 切换一级分类时只渲染选中分类的子分类网格 -->
|
||||||
</scroll-view>
|
<scroll-view scroll-y="true" class="content-wrap" v-else-if="value.template == 1"
|
||||||
|
:refresher-enabled="true" refresher-default-style="none"
|
||||||
|
:refresher-triggered="triggered" @refresherrefresh="onRefresh" @refresherrestore="onRestore">
|
||||||
|
<view class="child-category-wrap" v-for="(item, index) in categoryTree" :key="index"
|
||||||
|
:id="'category-' + index" :style="{ display: select == index ? 'block' : 'none' }">
|
||||||
|
<diy-category-item :category="item" :value="value" ref="categoryItem" :index="index"
|
||||||
|
:select="select" :oneCategorySelect="oneCategorySelect" :isList="isList"
|
||||||
|
@tologin="toLogin" @selectsku="selectSku($event, index)" @addCart="addCartPoint"
|
||||||
|
@saveSecondCategory="saveSecondCategoryName"></diy-category-item>
|
||||||
|
</view>
|
||||||
|
</scroll-view>
|
||||||
|
|
||||||
|
<scroll-view scroll-y="true" class="content-wrap" v-else-if="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" :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" @saveSecondCategory="saveSecondCategoryName"></diy-category-item>
|
||||||
|
</view>
|
||||||
|
<view class="end-tips" ref="endTips" :style="{ opacity: endTips }">{{ $lang('components-diy.diy-category.reachedBottom') }}</view>
|
||||||
|
</scroll-view>
|
||||||
|
|
||||||
<view class="content-wrap"
|
<view class="content-wrap"
|
||||||
v-if="(value.template == 2 || value.template == 3 || value.template == 4) && loadType == 'part'">
|
v-if="(value.template == 2 || value.template == 3 || value.template == 4) && loadType == 'part'">
|
||||||
@@ -112,6 +162,7 @@
|
|||||||
<diy-category-item :category="item" :value="value" ref="categoryItem" :index="index"
|
<diy-category-item :category="item" :value="value" ref="categoryItem" :index="index"
|
||||||
:last="index == categoryTree.length - 1 ? true : false" :select="select"
|
:last="index == categoryTree.length - 1 ? true : false" :select="select"
|
||||||
:oneCategorySelect="oneCategorySelect" :isList="isList" @tologin="toLogin"
|
:oneCategorySelect="oneCategorySelect" :isList="isList" @tologin="toLogin"
|
||||||
|
:currentOneCategory="value.template == 4 && templateFourData[oneCategorySelect] ? templateFourData[oneCategorySelect] : null"
|
||||||
@selectsku="selectSku($event, index)" @addCart="addCartPoint"
|
@selectsku="selectSku($event, index)" @addCart="addCartPoint"
|
||||||
@switch="switchOneCategory"></diy-category-item>
|
@switch="switchOneCategory"></diy-category-item>
|
||||||
</view>
|
</view>
|
||||||
@@ -120,17 +171,20 @@
|
|||||||
</block>
|
</block>
|
||||||
<view class="category-empty" v-else>
|
<view class="category-empty" v-else>
|
||||||
<image :src="$util.img('public/uniapp/category/empty.png')" mode="widthFix" show-menu-by-longpress></image>
|
<image :src="$util.img('public/uniapp/category/empty.png')" mode="widthFix" show-menu-by-longpress></image>
|
||||||
<view class="tips">暂时没有分类哦!</view>
|
<view class="tips">{{ $lang('components-diy.diy-category.noCategory') }}</view>
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
<view class="category-empty" v-else>
|
<view class="category-empty" v-else>
|
||||||
<image :src="$util.img('public/uniapp/category/empty.png')" mode="widthFix" show-menu-by-longpress></image>
|
<image :src="$util.img('public/uniapp/category/empty.png')" mode="widthFix" show-menu-by-longpress></image>
|
||||||
<view class="tips">暂时没有分类哦!</view>
|
<view class="tips">{{ $lang('components-diy.diy-category.noCategory') }}</view>
|
||||||
</view>
|
</view>
|
||||||
|
|
||||||
<!-- <view class="cart-box" v-if="(value.template == 2 || value.template == 4) && value.quickBuy && storeToken && categoryTree && categoryTree.length">
|
<!-- 模板4: 底部购物车栏 -->
|
||||||
|
<view class="cart-box cart-box-template-4"
|
||||||
|
v-if="value.template == 4 && value.quickBuy && storeToken && categoryTree && categoryTree.length">
|
||||||
<view class="left-wrap">
|
<view class="left-wrap">
|
||||||
<view class="cart-icon" ref="cartIcon" :animation="cartAnimation" @tap.stop="$util.redirectTo('/pages_goods/cart')">
|
<view class="cart-icon" ref="cartIcon" :animation="cartAnimation"
|
||||||
|
@tap.stop="$util.redirectTo('/pages_goods/cart')">
|
||||||
<text class="iconfont icon-ziyuan1"></text>
|
<text class="iconfont icon-ziyuan1"></text>
|
||||||
<view class="num" v-if="cartNumber">{{ cartNumber < 99 ? cartNumber : '99+' }}</view>
|
<view class="num" v-if="cartNumber">{{ cartNumber < 99 ? cartNumber : '99+' }}</view>
|
||||||
</view>
|
</view>
|
||||||
@@ -141,9 +195,10 @@
|
|||||||
<text class="unit font-size-tag price-font">.{{ cartTotalMoney[1] ? cartTotalMoney[1] : '00' }}</text>
|
<text class="unit font-size-tag price-font">.{{ cartTotalMoney[1] ? cartTotalMoney[1] : '00' }}</text>
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
<view class="right-wrap"><button type="primary" class="settlement-btn" @tap.stop="settlement">去结算</button>
|
<view class="right-wrap"><button type="primary" class="settlement-btn"
|
||||||
|
@tap.stop="settlement">去结算</button>
|
||||||
</view>
|
</view>
|
||||||
</view> -->
|
</view>
|
||||||
|
|
||||||
<view class="cart-point" :style="{ left: item.left + 'px', top: item.top + 'px' }" :key="index"
|
<view class="cart-point" :style="{ left: item.left + 'px', top: item.top + 'px' }" :key="index"
|
||||||
v-for="(item, index) in carIconList"></view>
|
v-for="(item, index) in carIconList"></view>
|
||||||
@@ -192,12 +247,18 @@ export default {
|
|||||||
loadType: '',
|
loadType: '',
|
||||||
templateFourData: [],
|
templateFourData: [],
|
||||||
isList: false,
|
isList: false,
|
||||||
lang: uni.getStorageSync("lang")//en-us 英文
|
lang: uni.getStorageSync("lang"),
|
||||||
|
lastSecondCategoryName: '',
|
||||||
|
template99Category: null
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
created() {
|
created() {
|
||||||
this.getCategoryTree();
|
this.getCategoryTree();
|
||||||
this.loadType = this.value.goodsLevel == 1 && this.value.loadType == 'all' ? 'all' : 'part';
|
this.loadType = this.value.goodsLevel == 1 && this.value.loadType == 'all' ? 'all' : 'part';
|
||||||
|
// 模板4: 默认单列列表布局(图片样式)
|
||||||
|
if (this.value.template == 4) {
|
||||||
|
this.isList = true;
|
||||||
|
}
|
||||||
},
|
},
|
||||||
mounted() {
|
mounted() {
|
||||||
query = uni.createSelectorQuery().in(this);
|
query = uni.createSelectorQuery().in(this);
|
||||||
@@ -301,9 +362,20 @@ export default {
|
|||||||
},
|
},
|
||||||
/**
|
/**
|
||||||
* 获取高度区间
|
* 获取高度区间
|
||||||
|
*
|
||||||
|
* 鸿蒙 JSVM 在 mounted() 之前触发 onShow,导致 query 还是 undefined
|
||||||
|
* 加防御性检查,避免上线后第一次进入崩溃
|
||||||
*/
|
*/
|
||||||
getHeightArea(index) {
|
getHeightArea(index) {
|
||||||
let heightArea = [];
|
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
|
query
|
||||||
.selectAll('.content-wrap .child-category')
|
.selectAll('.content-wrap .child-category')
|
||||||
.boundingClientRect(data => {
|
.boundingClientRect(data => {
|
||||||
@@ -318,7 +390,7 @@ export default {
|
|||||||
})
|
})
|
||||||
.exec();
|
.exec();
|
||||||
this.heightArea = heightArea;
|
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 +420,77 @@ export default {
|
|||||||
return item;
|
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
|
* @param {Object} index
|
||||||
@@ -360,9 +499,11 @@ export default {
|
|||||||
if (index >= this.categoryTree.length) return;
|
if (index >= this.categoryTree.length) return;
|
||||||
this.select = index;
|
this.select = index;
|
||||||
this.categoryId = 'category-' + index;
|
this.categoryId = 'category-' + index;
|
||||||
// 阻止切换分类之后滚动事件也立即执行
|
|
||||||
this.scrollLock = true;
|
this.scrollLock = true;
|
||||||
},
|
},
|
||||||
|
saveSecondCategoryName(name) {
|
||||||
|
this.lastSecondCategoryName = name;
|
||||||
|
},
|
||||||
touchStart() {
|
touchStart() {
|
||||||
this.scrollLock = false;
|
this.scrollLock = false;
|
||||||
},
|
},
|
||||||
@@ -380,10 +521,10 @@ export default {
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (this.value.template != 1 && this.value.loadType == 'all' && this.heightArea[this.select][1] -
|
if (this.value.template != 1 && this.value.loadType == 'all' && this.heightArea[this.select][1] -
|
||||||
scrollTop - contentWrapHeight < 300) {
|
scrollTop - contentWrapHeight < 300) {
|
||||||
this.$refs.categoryItem[this.select].getGoodsList();
|
if (Array.isArray(this.$refs.categoryItem) && this.$refs.categoryItem[this.select]) this.$refs.categoryItem[this.select].getGoodsList();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
onRefresh() {
|
onRefresh() {
|
||||||
@@ -409,7 +550,7 @@ export default {
|
|||||||
success: res => {
|
success: res => {
|
||||||
if (res.code >= 0) {
|
if (res.code >= 0) {
|
||||||
let item = res.data;
|
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(',');
|
if (item.sku_images) item.sku_images = item.sku_images.split(',');
|
||||||
else item.sku_images = [];
|
else item.sku_images = [];
|
||||||
@@ -536,7 +677,7 @@ export default {
|
|||||||
},
|
},
|
||||||
// 操作多规格商品弹框后,刷新商品数据
|
// 操作多规格商品弹框后,刷新商品数据
|
||||||
refreshData() {
|
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() {
|
changeListStyle() {
|
||||||
this.isList = !this.isList;
|
this.isList = !this.isList;
|
||||||
@@ -609,7 +750,7 @@ export default {
|
|||||||
white-space: break-word;
|
white-space: break-word;
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
text-align: center;
|
text-align: center;
|
||||||
font-size: 10px;
|
font-size: var(--diy-category-tree-normal-size, 20rpx);
|
||||||
}
|
}
|
||||||
|
|
||||||
&.border-top {
|
&.border-top {
|
||||||
@@ -626,7 +767,7 @@ export default {
|
|||||||
view {
|
view {
|
||||||
color: #333;
|
color: #333;
|
||||||
font-weight: bold;
|
font-weight: bold;
|
||||||
font-size: $font-size-base;
|
font-size: var(--diy-category-tree-select-size, 28rpx);
|
||||||
}
|
}
|
||||||
|
|
||||||
&::before {
|
&::before {
|
||||||
@@ -751,7 +892,11 @@ export default {
|
|||||||
color: #333;
|
color: #333;
|
||||||
}
|
}
|
||||||
|
|
||||||
.money,
|
.money {
|
||||||
|
font-weight: bold;
|
||||||
|
color: var(--price-color);
|
||||||
|
}
|
||||||
|
|
||||||
.unit {
|
.unit {
|
||||||
font-weight: bold;
|
font-weight: bold;
|
||||||
color: var(--price-color);
|
color: var(--price-color);
|
||||||
@@ -807,6 +952,137 @@ export default {
|
|||||||
|
|
||||||
// 风格四
|
// 风格四
|
||||||
.category-template-4 {
|
.category-template-4 {
|
||||||
|
// 模板4 顶部搜索框(图片样式)
|
||||||
|
.search-box-template-4 {
|
||||||
|
padding: 20rpx 30rpx 16rpx;
|
||||||
|
background: #fff;
|
||||||
|
|
||||||
|
.search-content {
|
||||||
|
height: 64rpx;
|
||||||
|
background-color: #f5f5f5;
|
||||||
|
border-radius: 40rpx;
|
||||||
|
|
||||||
|
input {
|
||||||
|
height: 64rpx;
|
||||||
|
line-height: 64rpx;
|
||||||
|
padding: 0 30rpx 0 30rpx;
|
||||||
|
background: #f5f5f5;
|
||||||
|
border-radius: 40rpx;
|
||||||
|
font-size: 26rpx;
|
||||||
|
color: #333;
|
||||||
|
}
|
||||||
|
|
||||||
|
.iconfont {
|
||||||
|
font-size: 32rpx;
|
||||||
|
color: #89899a;
|
||||||
|
width: 70rpx;
|
||||||
|
text-align: center;
|
||||||
|
right: 10rpx;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 模板4 底部购物车栏(图片样式)
|
||||||
|
.cart-box-template-4 {
|
||||||
|
height: 110rpx;
|
||||||
|
padding: 0 30rpx;
|
||||||
|
background: #fff;
|
||||||
|
border-top: 1rpx solid #f0f0f0;
|
||||||
|
position: relative;
|
||||||
|
z-index: 10;
|
||||||
|
box-shadow: 0 -4rpx 12rpx rgba(0, 0, 0, 0.04);
|
||||||
|
|
||||||
|
.left-wrap {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.cart-icon {
|
||||||
|
width: 90rpx;
|
||||||
|
height: 90rpx;
|
||||||
|
position: relative;
|
||||||
|
margin-top: -10rpx;
|
||||||
|
|
||||||
|
.iconfont {
|
||||||
|
color: var(--btn-text-color, #fff);
|
||||||
|
width: 80rpx;
|
||||||
|
height: 80rpx;
|
||||||
|
background-color: $base-color;
|
||||||
|
border-radius: 50%;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
font-size: 40rpx;
|
||||||
|
box-shadow: 0 4rpx 12rpx rgba(255, 107, 53, 0.35);
|
||||||
|
}
|
||||||
|
|
||||||
|
.num {
|
||||||
|
position: absolute;
|
||||||
|
top: 0;
|
||||||
|
right: 0;
|
||||||
|
transform: translate(20%, 0);
|
||||||
|
display: inline-block;
|
||||||
|
box-sizing: border-box;
|
||||||
|
color: #fff;
|
||||||
|
line-height: 1.2;
|
||||||
|
text-align: center;
|
||||||
|
font-size: 24rpx;
|
||||||
|
padding: 0 8rpx;
|
||||||
|
min-width: 32rpx;
|
||||||
|
border-radius: 18rpx;
|
||||||
|
background-color: var(--price-color, #FF6B35);
|
||||||
|
border: 2rpx solid #fff;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.price {
|
||||||
|
margin-left: 16rpx;
|
||||||
|
display: flex;
|
||||||
|
align-items: baseline;
|
||||||
|
line-height: 1;
|
||||||
|
|
||||||
|
.title {
|
||||||
|
color: #333;
|
||||||
|
font-size: 28rpx;
|
||||||
|
}
|
||||||
|
|
||||||
|
.unit,
|
||||||
|
.money {
|
||||||
|
color: var(--price-color, #FF6B35);
|
||||||
|
font-weight: bold;
|
||||||
|
}
|
||||||
|
|
||||||
|
.unit {
|
||||||
|
font-size: 24rpx;
|
||||||
|
}
|
||||||
|
|
||||||
|
.money {
|
||||||
|
font-size: 36rpx;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.right-wrap {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.settlement-btn {
|
||||||
|
margin: 0;
|
||||||
|
width: 220rpx;
|
||||||
|
font-weight: bold;
|
||||||
|
border-radius: 50rpx;
|
||||||
|
height: 80rpx;
|
||||||
|
line-height: 80rpx;
|
||||||
|
font-size: 30rpx;
|
||||||
|
background: $base-color;
|
||||||
|
color: var(--btn-text-color, #fff);
|
||||||
|
|
||||||
|
&::after {
|
||||||
|
border: none;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
.search-box {
|
.search-box {
|
||||||
.search-content input {
|
.search-content input {
|
||||||
background-color: #f1f1f1;
|
background-color: #f1f1f1;
|
||||||
@@ -1033,4 +1309,218 @@ export default {
|
|||||||
border-bottom-right-radius: 8rpx;
|
border-bottom-right-radius: 8rpx;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ===================== 模板1 仿京东/淘宝商品分类样式 =====================
|
||||||
|
.category-template-1 {
|
||||||
|
.search-box {
|
||||||
|
padding: 20rpx 24rpx;
|
||||||
|
background: #fff;
|
||||||
|
|
||||||
|
.search-content {
|
||||||
|
background-color: #f5f5f5;
|
||||||
|
border-radius: 40rpx;
|
||||||
|
|
||||||
|
input {
|
||||||
|
background: #f5f5f5;
|
||||||
|
border-radius: 40rpx;
|
||||||
|
padding: 0 30rpx;
|
||||||
|
font-size: 26rpx;
|
||||||
|
color: #333;
|
||||||
|
}
|
||||||
|
|
||||||
|
.iconfont {
|
||||||
|
right: 16rpx;
|
||||||
|
color: #89899a;
|
||||||
|
font-size: 32rpx;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.content-box {
|
||||||
|
background: #fff;
|
||||||
|
|
||||||
|
.tree-wrap {
|
||||||
|
width: 170rpx;
|
||||||
|
background-color: #fff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.right-flex-wrap {
|
||||||
|
background: #fff;
|
||||||
|
|
||||||
|
.content-wrap {
|
||||||
|
background: #fff;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 穿透到子组件 diy-category-item: 调整 banner 横向内边距 + 分类网格容器为透明
|
||||||
|
::v-deep .category-adv {
|
||||||
|
padding: 0 20rpx;
|
||||||
|
margin-top: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
::v-deep .category-list {
|
||||||
|
margin: 0 20rpx;
|
||||||
|
border-radius: 0;
|
||||||
|
background: transparent;
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
::v-deep .category-title-with-lines {
|
||||||
|
padding: 30rpx 0 20rpx;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 穿透修复: 图片不需要灰色背景框,与目标图保持一致
|
||||||
|
::v-deep .img-box {
|
||||||
|
background: transparent !important;
|
||||||
|
border-radius: 0 !important;
|
||||||
|
width: 70% !important;
|
||||||
|
padding-bottom: 70% !important;
|
||||||
|
margin-bottom: 16rpx !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
::v-deep .img-box image {
|
||||||
|
width: 100% !important;
|
||||||
|
height: 100% !important;
|
||||||
|
left: 0 !important;
|
||||||
|
top: 0 !important;
|
||||||
|
transform: none !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 左侧分类栏样式
|
||||||
|
.tree-wrap .category-item {
|
||||||
|
padding: 28rpx 16rpx;
|
||||||
|
background-color: #fff;
|
||||||
|
border-radius: 0;
|
||||||
|
|
||||||
|
view {
|
||||||
|
color: #666;
|
||||||
|
font-size: 26rpx;
|
||||||
|
line-height: 1.3;
|
||||||
|
}
|
||||||
|
|
||||||
|
&.border-top,
|
||||||
|
&.border-bottom {
|
||||||
|
border-radius: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
&.select {
|
||||||
|
background: #fff;
|
||||||
|
|
||||||
|
view {
|
||||||
|
color: var(--base-color, #FF6B35);
|
||||||
|
font-weight: bold;
|
||||||
|
font-size: 28rpx;
|
||||||
|
}
|
||||||
|
|
||||||
|
&::before {
|
||||||
|
content: ' ';
|
||||||
|
width: 6rpx;
|
||||||
|
height: 32rpx;
|
||||||
|
background: var(--base-color, #FF6B35);
|
||||||
|
display: block;
|
||||||
|
position: absolute;
|
||||||
|
left: 0;
|
||||||
|
top: 50%;
|
||||||
|
transform: translateY(-50%);
|
||||||
|
border-radius: 0 6rpx 6rpx 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===================== 模板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>
|
</style>
|
||||||
@@ -17,7 +17,7 @@
|
|||||||
<view class="video-title" :style="[{ '--title-line-clamp': titleLineClamp }]">{{ value.videoTitle }}
|
<view class="video-title" :style="[{ '--title-line-clamp': titleLineClamp }]">{{ value.videoTitle }}
|
||||||
</view>
|
</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>
|
</view>
|
||||||
|
|
||||||
@@ -29,7 +29,7 @@
|
|||||||
<view class="play-icon-css"></view>
|
<view class="play-icon-css"></view>
|
||||||
</view>
|
</view>
|
||||||
<view class="video-stats-overlay" v-if="showViewCount && value.showViewCount">
|
<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>
|
</view>
|
||||||
<view class="video-info">
|
<view class="video-info">
|
||||||
@@ -37,7 +37,7 @@
|
|||||||
<view class="video-title" :style="[{ '--title-line-clamp': titleLineClamp }]">{{ value.videoTitle }}
|
<view class="video-title" :style="[{ '--title-line-clamp': titleLineClamp }]">{{ value.videoTitle }}
|
||||||
</view>
|
</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>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
|
|||||||
@@ -26,16 +26,16 @@
|
|||||||
</view>
|
</view>
|
||||||
<view class="coupon-num" :style="{ color: value.moneyColor }" v-else>
|
<view class="coupon-num" :style="{ color: value.moneyColor }" v-else>
|
||||||
<text class="coupon-size">{{ item.discount | moneyConduct }}</text>
|
<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 font-size-tag" :style="{ color: value.limitColor }">
|
<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>
|
</view>
|
||||||
<view class="coupon-get" :style="couponBtnStyle" v-if="item.useState == 0">
|
<view class="coupon-get" :style="couponBtnStyle" v-if="item.useState == 0">
|
||||||
{{ value.btnStyle.text }}
|
{{ value.btnStyle.text }}
|
||||||
</view>
|
</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>
|
</view>
|
||||||
|
|
||||||
</swiper-item>
|
</swiper-item>
|
||||||
@@ -61,16 +61,16 @@
|
|||||||
</view>
|
</view>
|
||||||
<view class="coupon-num" :style="{ color: value.moneyColor }" v-else>
|
<view class="coupon-num" :style="{ color: value.moneyColor }" v-else>
|
||||||
<text class="coupon-size">{{ item.discount | moneyConduct }}</text>
|
<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 font-size-tag" :style="{ color: value.limitColor }">
|
<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>
|
</view>
|
||||||
<view class="coupon-get" :style="couponBtnStyle" v-if="item.useState == 0">
|
<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>
|
||||||
<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>
|
||||||
</view>
|
</view>
|
||||||
</swiper-item>
|
</swiper-item>
|
||||||
@@ -95,20 +95,19 @@
|
|||||||
</view>
|
</view>
|
||||||
<view class="coupon-num" :style="{ color: value.moneyColor }" v-else>
|
<view class="coupon-num" :style="{ color: value.moneyColor }" v-else>
|
||||||
<text class="coupon-size">{{ item.discount | moneyConduct }}</text>
|
<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 font-size-tag">
|
<view class="coupon-type font-size-tag">
|
||||||
<text :style="{ color: value.limitColor }">{{ item.at_least > 0 ? '满' +
|
<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>
|
||||||
Number(item.at_least) + '元可用' : '无门槛优惠券' }}</text>
|
<view class="item-text" v-if="item.goods_type == 1">{{ $lang('components-diy.diy-coupon.allProductsAvailable') }}</view>
|
||||||
<view class="item-text" v-if="item.goods_type == 1">所有商品可用</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 == 2">指定商品可用</view>
|
<view class="item-text" v-else-if="item.goods_type == 3">{{ $lang('components-diy.diy-coupon.specifiedProductsUnavailable') }}</view>
|
||||||
<view class="item-text" v-else-if="item.goods_type == 3">指定商品不可用</view>
|
|
||||||
</view>
|
</view>
|
||||||
|
|
||||||
<view class="coupon-get" :style="couponBtnStyle" v-if="item.useState == 0">
|
<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>
|
||||||
<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>
|
</view>
|
||||||
</swiper-item>
|
</swiper-item>
|
||||||
</swiper>
|
</swiper>
|
||||||
@@ -133,16 +132,16 @@
|
|||||||
</view>
|
</view>
|
||||||
<view class="coupon-num" :style="{ color: value.moneyColor }" v-else>
|
<view class="coupon-num" :style="{ color: value.moneyColor }" v-else>
|
||||||
<text class="coupon-size">{{ item.discount | moneyConduct }}</text>
|
<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 font-size-tag" :style="{ color: value.limitColor }">
|
<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>
|
</view>
|
||||||
<view class="coupon-get" :style="couponBtnStyle" v-if="item.useState == 0">
|
<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>
|
||||||
<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>
|
</view>
|
||||||
</swiper-item>
|
</swiper-item>
|
||||||
</swiper>
|
</swiper>
|
||||||
@@ -160,11 +159,11 @@
|
|||||||
<view class="coupon-num" v-if="item.discount == '0.00'"
|
<view class="coupon-num" v-if="item.discount == '0.00'"
|
||||||
:style="{ color: value.moneyColor }">
|
:style="{ color: value.moneyColor }">
|
||||||
<text class="coupon-size">{{ item.money | moneyConduct }}</text>
|
<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>
|
||||||
<view class="coupon-num" v-else :style="{ color: value.moneyColor }">
|
<view class="coupon-num" v-else :style="{ color: value.moneyColor }">
|
||||||
<text class="coupon-size">{{ item.discount | moneyConduct }}</text>
|
<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>
|
</view>
|
||||||
<view class="coupon-line"></view>
|
<view class="coupon-line"></view>
|
||||||
@@ -173,14 +172,14 @@
|
|||||||
<view class="coupon-name" :style="{ color: value.nameColor }">{{
|
<view class="coupon-name" :style="{ color: value.nameColor }">{{
|
||||||
item.coupon_name }}</view>
|
item.coupon_name }}</view>
|
||||||
<text class="coupon-least" :style="{ color: value.limitColor }"
|
<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 }"
|
<text class="coupon-least" :style="{ color: value.limitColor }"
|
||||||
v-else>无门槛优惠券</text>
|
v-else>{{ $lang('components-diy.diy-coupon.noThresholdCoupon') }}</text>
|
||||||
</view>
|
</view>
|
||||||
<view class="coupon-get" :style="couponBtnStyle" v-if="item.useState == 0">{{
|
<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 class="coupon-get" :style="couponBtnStyle" v-if="parseInt(item.useState)">
|
||||||
去使用</view>
|
{{ $lang('components-diy.diy-coupon.goUse') }}</view>
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
@@ -204,9 +203,9 @@
|
|||||||
<view class="price-wrap">
|
<view class="price-wrap">
|
||||||
<text class="price" :style="{ color: value.moneyColor }">{{ (item.discount == '0.00'
|
<text class="price" :style="{ color: value.moneyColor }">{{ (item.discount == '0.00'
|
||||||
? item.money : item.discount) | moneyConduct }}</text>
|
? 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>
|
</view>
|
||||||
<text class="text">优惠券</text>
|
<text class="text">{{ $lang('components-diy.diy-coupon.coupon') }}</text>
|
||||||
</view>
|
</view>
|
||||||
<text class="btn" v-if="item.useState == 0" :style="{
|
<text class="btn" v-if="item.useState == 0" :style="{
|
||||||
color: value.btnStyle.textColor,
|
color: value.btnStyle.textColor,
|
||||||
@@ -222,11 +221,11 @@
|
|||||||
borderTopLeftRadius: value.btnStyle.aroundRadius * 2 + 'rpx',
|
borderTopLeftRadius: value.btnStyle.aroundRadius * 2 + 'rpx',
|
||||||
borderBottomLeftRadius: 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>
|
||||||
<text class="limit" :style="{ color: value.limitColor }"
|
<text class="limit" :style="{ color: value.limitColor }"
|
||||||
v-if="parseFloat(item.at_least) > 0">满{{ item.at_least | moneyConduct }}元使用</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>无门槛使用</text>
|
<text class="limit" :style="{ color: value.limitColor }" v-else>{{ $lang('components-diy.diy-coupon.noThresholdUse') }}</text>
|
||||||
</view>
|
</view>
|
||||||
|
|
||||||
<div v-if="computedCouponList.length <= 2" @tap.stop="$util.redirectTo('/pages_goods/category')"
|
<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 }">
|
<div class="coupon-content" :style="{ color: value.moneyColor }">
|
||||||
<span class="price">+</span>
|
<span class="price">+</span>
|
||||||
<span class="text">暂无优惠券</span>
|
<span class="text">{{ $lang('components-diy.diy-coupon.noCoupons') }}</span>
|
||||||
</div>
|
</div>
|
||||||
<span class="limit" :style="{ color: value.limitColor }">去逛逛</span>
|
<span class="limit" :style="{ color: value.limitColor }">{{ $lang('components-diy.diy-coupon.goBrowse') }}</span>
|
||||||
</div>
|
</div>
|
||||||
</swiper-item>
|
</swiper-item>
|
||||||
</swiper>
|
</swiper>
|
||||||
@@ -257,25 +256,24 @@
|
|||||||
<view class="coupon-num" v-if="item.discount == '0.00'"
|
<view class="coupon-num" v-if="item.discount == '0.00'"
|
||||||
:style="{ color: value.moneyColor }">
|
:style="{ color: value.moneyColor }">
|
||||||
<text class="coupon-size">{{ item.money | moneyConduct }}</text>
|
<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>
|
||||||
<view class="coupon-num" v-else :style="{ color: value.moneyColor }">
|
<view class="coupon-num" v-else :style="{ color: value.moneyColor }">
|
||||||
<text class="coupon-size">{{ item.discount | moneyConduct }}</text>
|
<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>
|
</view>
|
||||||
<view class="coupon-type">
|
<view class="coupon-type">
|
||||||
<text class="coupon-name" :style="{ color: value.limitColor }"
|
<text class="coupon-name" :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-name" :style="{ color: value.limitColor }" v-else>无门槛优惠券</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 }">有效期至{{
|
<view class="coupon-least" :style="{ color: value.limitColor }">{{ $lang('components-diy.diy-coupon.validUntil', { date: $util.timeStampTurnTime(item.end_time, 'yearmonthday') }) }}</view>
|
||||||
$util.timeStampTurnTime(item.end_time, 'yearmonthday') }}</view>
|
|
||||||
</view>
|
</view>
|
||||||
<view class="coupon-line"></view>
|
<view class="coupon-line"></view>
|
||||||
<view class="coupon-get" :style="couponBtnStyle" v-if="item.useState == 0">
|
<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>
|
||||||
<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>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
@@ -404,7 +402,7 @@ export default {
|
|||||||
couponTap(item, index) {
|
couponTap(item, index) {
|
||||||
if (item.count == item.lead_count) {
|
if (item.count == item.lead_count) {
|
||||||
this.$util.showToast({
|
this.$util.showToast({
|
||||||
title: '该优惠券已抢光'
|
title: this.$lang('components-diy.diy-coupon.couponSoldOut')
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -427,7 +425,7 @@ export default {
|
|||||||
var data = res.data;
|
var data = res.data;
|
||||||
let msg = res.message;
|
let msg = res.message;
|
||||||
if (res.code == 0) {
|
if (res.code == 0) {
|
||||||
msg = '领取成功';
|
msg = this.$lang('components-diy.diy-coupon.claimSuccess');
|
||||||
if (res.data.is_exist == 1) {
|
if (res.data.is_exist == 1) {
|
||||||
for (let i = 0; i < that.couponList.length; i++) {
|
for (let i = 0; i < that.couponList.length; i++) {
|
||||||
if (that.couponList[i].coupon_type_id == item.coupon_type_id) {
|
if (that.couponList[i].coupon_type_id == item.coupon_type_id) {
|
||||||
|
|||||||
@@ -20,7 +20,7 @@
|
|||||||
<view class="discount-price">
|
<view class="discount-price">
|
||||||
<view class="price-wrap" v-if="value.priceStyle.mainControl">
|
<view class="price-wrap" v-if="value.priceStyle.mainControl">
|
||||||
<text class="unit price-style small"
|
<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"
|
<text class="price price-style large"
|
||||||
:style="{ color: value.theme == 'diy' ? value.priceStyle.mainColor : '' }">{{
|
:style="{ color: value.theme == 'diy' ? value.priceStyle.mainColor : '' }">{{
|
||||||
item.commission_money.split('.')[0] }}</text>
|
item.commission_money.split('.')[0] }}</text>
|
||||||
@@ -33,14 +33,14 @@
|
|||||||
color: value.btnStyle.theme == 'diy' ? value.btnStyle.textColor : '',
|
color: value.btnStyle.theme == 'diy' ? value.btnStyle.textColor : '',
|
||||||
borderRadius: value.btnStyle.aroundRadius * 2 + 'rpx'
|
borderRadius: value.btnStyle.aroundRadius * 2 + 'rpx'
|
||||||
}" @tap.stop="followGoods(item, index)">
|
}" @tap.stop="followGoods(item, index)">
|
||||||
关注
|
{{ $lang('components-diy.diy-fenxiao-goods-list.follow') }}
|
||||||
</view>
|
</view>
|
||||||
<view class="sale-btn" v-if="value.btnStyle.control && item.is_collect == 1" :style="{
|
<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 + ')' : '',
|
background: value.btnStyle.theme == 'diy' ? 'linear-gradient(to right,' + value.btnStyle.bgColorStart + ',' + value.btnStyle.bgColorEnd + ')' : '',
|
||||||
color: value.btnStyle.theme == 'diy' ? value.btnStyle.textColor : '',
|
color: value.btnStyle.theme == 'diy' ? value.btnStyle.textColor : '',
|
||||||
borderRadius: value.btnStyle.aroundRadius * 2 + 'rpx'
|
borderRadius: value.btnStyle.aroundRadius * 2 + 'rpx'
|
||||||
}" @tap.stop="delFollowTip(item, index)">
|
}" @tap.stop="delFollowTip(item, index)">
|
||||||
取消关注
|
{{ $lang('components-diy.diy-fenxiao-goods-list.unfollow') }}
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
<view class="delete-price" v-if="value.priceStyle.lineControl"
|
<view class="delete-price" v-if="value.priceStyle.lineControl"
|
||||||
@@ -138,7 +138,7 @@ export default {
|
|||||||
},
|
},
|
||||||
success: res => {
|
success: res => {
|
||||||
if (res.code >= 0) {
|
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].is_collect = 1;
|
||||||
this.list[index].collect_id = res.data;
|
this.list[index].collect_id = res.data;
|
||||||
}
|
}
|
||||||
@@ -149,8 +149,8 @@ export default {
|
|||||||
//取消关注
|
//取消关注
|
||||||
delFollowTip(e, index) {
|
delFollowTip(e, index) {
|
||||||
uni.showModal({
|
uni.showModal({
|
||||||
title: '提示',
|
title: this.$lang('components-diy.diy-fenxiao-goods-list.tip'),
|
||||||
content: '确认取消关注该商品吗',
|
content: this.$lang('components-diy.diy-fenxiao-goods-list.confirmUnfollow'),
|
||||||
success: res => {
|
success: res => {
|
||||||
if (res.confirm) {
|
if (res.confirm) {
|
||||||
this.delFollow(e.collect_id, index);
|
this.delFollow(e.collect_id, index);
|
||||||
@@ -167,7 +167,7 @@ export default {
|
|||||||
success: res => {
|
success: res => {
|
||||||
let msg = '';
|
let msg = '';
|
||||||
if (res.code == 0) {
|
if (res.code == 0) {
|
||||||
msg = '取消成功';
|
msg = this.$lang('components-diy.diy-fenxiao-goods-list.cancelSuccess');
|
||||||
} else {
|
} else {
|
||||||
msg = res.message;
|
msg = res.message;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,103 +1,319 @@
|
|||||||
<template>
|
<template>
|
||||||
<view data-component-name="diy-form" class="diy-from" :style="style">
|
<view data-component-name="diy-form" class="diy-from" :style="diyFormStyle">
|
||||||
<view class="fui-cell-group">
|
<!-- Banner -->
|
||||||
<view class="fui-cell ">
|
<view v-if="value.show_banner && value.form_banner" class="form-banner" :style="bannerStyle">
|
||||||
<view class="fui-cell-label ">您的姓名</view>
|
<image :src="$util.img(value.form_banner)" mode="widthFix" class="banner-img" />
|
||||||
<view class="fui-cell-info">
|
</view>
|
||||||
<input v-model="Form.realname" class="fui-input" placeholder="请输入您的姓名" value=""></input>
|
<!-- 提示语 -->
|
||||||
</view>
|
<view v-if="value.show_tip && value.form_tip" class="form-tip" :style="tipStyle">{{ value.form_tip }}</view>
|
||||||
</view>
|
<!-- 表单组件 -->
|
||||||
<view class="fui-cell ">
|
<ns-newform
|
||||||
<view class="fui-cell-label">手机号码</view>
|
:data="formComponents"
|
||||||
<view class="fui-cell-info">
|
:customAttr="value"
|
||||||
<input v-model="Form.mobile" class="fui-input" maxlength="11" placeholder="请输入您的手机号"
|
:mode="mergedFormConfig.formLayout || 'horizontal'"
|
||||||
type="number"></input>
|
:formConfig="mergedFormConfig"
|
||||||
</view>
|
ref="nsNewform"
|
||||||
</view>
|
></ns-newform>
|
||||||
<view class="fui-cell ">
|
<!-- 提交按钮(外层 = form-bg + form-padding-x;按钮 = submit-bg + submit-color + input-height + input-radius)。
|
||||||
<view class="fui-cell-label">您的邮箱</view>
|
showSubmit=false 时由父级页面渲染自己的提交按钮并通过 ref 调用本组件的 verify()/getFormData()。 -->
|
||||||
<view class="fui-cell-info">
|
<view v-if="showSubmit" class="form-submit-wrap" :style="submitWrapStyle">
|
||||||
<input v-model="Form.mailbox" class="fui-input" placeholder="请输入您的邮箱" type="text"></input>
|
<view @click.stop="submitForm" class="form-submit" :style="submitStyle">{{ submitText }}</view>
|
||||||
</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>
|
</view>
|
||||||
<view @tap.stop="submitform" class="fui-btn btn-danger block mtop">提交信息</view>
|
|
||||||
</view>
|
</view>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
// 自定义表单
|
// 自定义表单
|
||||||
import DiyMinx from './minx.js'
|
import DiyMinx from './minx.js'
|
||||||
|
import NsNewform from '@/components/ns-newform/ns-newform.vue'
|
||||||
|
|
||||||
export default {
|
export default {
|
||||||
name: 'diy-from',
|
name: 'diy-from',
|
||||||
|
components: { NsNewform },
|
||||||
props: {
|
props: {
|
||||||
value: {
|
value: {
|
||||||
type: Object
|
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],
|
mixins: [DiyMinx],
|
||||||
data() {
|
data() {
|
||||||
return {
|
return {
|
||||||
loading: true,
|
formComponents: [] // 转换后的表单组件
|
||||||
markers: [],
|
|
||||||
Form: {
|
|
||||||
realname: '',
|
|
||||||
mobile: '',
|
|
||||||
mailbox: '',
|
|
||||||
citys: '',
|
|
||||||
remark: '',
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
created() {
|
created() {
|
||||||
|
this.initForm();
|
||||||
},
|
},
|
||||||
watch: {
|
watch: {
|
||||||
// 组件刷新监听
|
'value': {
|
||||||
componentRefresh: function (nval) {
|
deep: true,
|
||||||
// this.getDataList();
|
handler() {
|
||||||
|
// raw 模式:formData 由父级透传,跳过重跑 initForm(避免每次父组件 re-render 触发 ns-newform 的深拷贝 initFormData)
|
||||||
|
if (this.dataMode === 'raw') return;
|
||||||
|
this.initForm();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
computed: {
|
computed: {
|
||||||
markerst() {
|
|
||||||
return [{
|
|
||||||
id: 1,
|
|
||||||
latitude: this.value.list[0].lat,
|
|
||||||
longitude: this.value.list[0].lng
|
|
||||||
}]
|
|
||||||
},
|
|
||||||
style() {
|
style() {
|
||||||
var css = '';
|
var css = '';
|
||||||
css += 'background-color:' + this.value.contentBgColor + ';';
|
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-left-radius:' + this.value.topElementAroundRadius * 2 + 'rpx;';
|
||||||
css += 'border-top-right-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-left-radius:' + this.value.bottomElementAroundRadius * 2 + 'rpx;';
|
||||||
css += 'border-bottom-right-radius:' + this.value.bottomElementAroundRadius * 2 + 'rpx;';
|
css += 'border-bottom-right-radius:' + this.value.bottomElementAroundRadius * 2 + 'rpx;';
|
||||||
}
|
}
|
||||||
return css;
|
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'),
|
||||||
|
// 占位符:遗漏会被 ns-newform SCSS 默认值回退覆盖
|
||||||
|
placeholderColor: pick('placeholderColor', 'placeholder_color'),
|
||||||
|
placeholderFontSize: pick('placeholderFontSize', 'placeholder_font_size'),
|
||||||
|
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: {
|
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({
|
this.$api.sendRequest({
|
||||||
url: '/api/member/information',
|
url: '/form/api/form/create',
|
||||||
data: this.Form,
|
data: {
|
||||||
success: res => {
|
form_id: this.value.form_id || 0,
|
||||||
this.$util.showToast({
|
form_data: typeof submitFormData === 'string' ? submitFormData : JSON.stringify(submitFormData),
|
||||||
title: res.message
|
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 +324,54 @@ export default {
|
|||||||
<style lang="scss">
|
<style lang="scss">
|
||||||
.diy-from {
|
.diy-from {
|
||||||
background: #fff;
|
background: #fff;
|
||||||
padding-bottom: 20rpx;
|
padding: 0;
|
||||||
border-radius: 10rpx;
|
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>
|
</style>
|
||||||
@@ -7,7 +7,7 @@
|
|||||||
<view class="goods-img-wrap">
|
<view class="goods-img-wrap">
|
||||||
<image class="goods-img"
|
<image class="goods-img"
|
||||||
:src="$util.img(item.goods_image, { size: goodsValue.template == 'large-mode' ? 'big' : 'mid' })"
|
:src="$util.img(item.goods_image, { size: goodsValue.template == 'large-mode' ? 'big' : 'mid' })"
|
||||||
mode="widthFix" @error="imgError(index)"
|
:mode="imgMode" @error="imgError(index)"
|
||||||
:style="{ borderRadius: goodsValue.imgAroundRadius * 2 + 'rpx' }"
|
:style="{ borderRadius: goodsValue.imgAroundRadius * 2 + 'rpx' }"
|
||||||
show-menu-by-longpress />
|
show-menu-by-longpress />
|
||||||
<view class="sell-out" v-if="item.stock <= 0">
|
<view class="sell-out" v-if="item.stock <= 0">
|
||||||
@@ -60,7 +60,7 @@
|
|||||||
</view>
|
</view>
|
||||||
<view class="sale" v-if="goodsValue.saleStyle.control"
|
<view class="sale" v-if="goodsValue.saleStyle.control"
|
||||||
:style="{ color: goodsValue.theme == 'diy' ? goodsValue.saleStyle.color : '' }">
|
: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>
|
</view>
|
||||||
|
|
||||||
@@ -117,7 +117,7 @@
|
|||||||
:class="[goodsValue.ornament.type]" :style="goodsItemCss">
|
:class="[goodsValue.ornament.type]" :style="goodsItemCss">
|
||||||
<view class="goods-img-wrap">
|
<view class="goods-img-wrap">
|
||||||
<image class="goods-img" :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }"
|
<image class="goods-img" :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="imgMode" @error="imgError(index)"
|
||||||
:lazy-load="true" show-menu-by-longpress />
|
:lazy-load="true" show-menu-by-longpress />
|
||||||
<view class="sell-out" v-if="item.stock <= 0">
|
<view class="sell-out" v-if="item.stock <= 0">
|
||||||
<text class="iconfont icon-shuqing"></text>
|
<text class="iconfont icon-shuqing"></text>
|
||||||
@@ -168,7 +168,7 @@
|
|||||||
</view>
|
</view>
|
||||||
<view class="sale" v-if="goodsValue.saleStyle.control"
|
<view class="sale" v-if="goodsValue.saleStyle.control"
|
||||||
:style="{ color: goodsValue.theme == 'diy' ? goodsValue.saleStyle.color : '' }">
|
: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>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
@@ -184,7 +184,7 @@
|
|||||||
:class="[goodsValue.ornament.type]" :style="goodsItemCss">
|
:class="[goodsValue.ornament.type]" :style="goodsItemCss">
|
||||||
<view class="goods-img-wrap">
|
<view class="goods-img-wrap">
|
||||||
<image class="goods-img" :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }"
|
<image class="goods-img" :style="{ borderRadius: value.imgAroundRadius * 2 + 'rpx' }"
|
||||||
:src="$util.img(dataItem.goods_image, { size: 'mid' })" mode="widthFix"
|
:src="$util.img(dataItem.goods_image, { size: 'mid' })" :mode="imgMode"
|
||||||
@error="imgError(dataIndex)" :lazy-load="true" show-menu-by-longpress />
|
@error="imgError(dataIndex)" :lazy-load="true" show-menu-by-longpress />
|
||||||
<view class="sell-out" v-if="dataItem.stock <= 0">
|
<view class="sell-out" v-if="dataItem.stock <= 0">
|
||||||
<text class="iconfont icon-shuqing"></text>
|
<text class="iconfont icon-shuqing"></text>
|
||||||
@@ -238,7 +238,7 @@
|
|||||||
</view>
|
</view>
|
||||||
<view class="sale" v-if="goodsValue.saleStyle.control"
|
<view class="sale" v-if="goodsValue.saleStyle.control"
|
||||||
:style="{ color: goodsValue.theme == 'diy' ? goodsValue.saleStyle.color : '' }">
|
: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>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
@@ -302,6 +302,19 @@ export default {
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
computed: {
|
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() {
|
goodsListWarpCss() {
|
||||||
var obj = '';
|
var obj = '';
|
||||||
obj += 'background-color:' + this.goodsValue.componentBgColor + ';';
|
obj += 'background-color:' + this.goodsValue.componentBgColor + ';';
|
||||||
|
|||||||
@@ -53,7 +53,7 @@
|
|||||||
¥{{ showMarketPrice(dataItem) }}</view>
|
¥{{ showMarketPrice(dataItem) }}</view>
|
||||||
<view class="sale" v-if="goodsValue.saleStyle.control"
|
<view class="sale" v-if="goodsValue.saleStyle.control"
|
||||||
:style="{ color: goodsValue.theme == 'diy' ? goodsValue.saleStyle.color : '' }">
|
: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>
|
||||||
</view>
|
</view>
|
||||||
|
|||||||
@@ -291,77 +291,99 @@ export default {
|
|||||||
mixins: [DiyMinx],
|
mixins: [DiyMinx],
|
||||||
data() {
|
data() {
|
||||||
return {
|
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() {
|
created() {
|
||||||
this.diyGlobalData = JSON.parse(JSON.stringify(this.diyData));
|
this.processData();
|
||||||
|
},
|
||||||
|
mounted() {
|
||||||
|
if (this.diyData && this.diyData.value) {
|
||||||
|
this._notifyLoaded();
|
||||||
|
}
|
||||||
},
|
},
|
||||||
computed: {
|
computed: {
|
||||||
topNavColor() {
|
topNavColor() {
|
||||||
var color = '';
|
if (!this.diyData?.global) return '';
|
||||||
if (this.diyData.global.topNavBg) {
|
|
||||||
color = 'transparent';
|
const { topNavBg, topNavColor } = this.diyData.global;
|
||||||
if (this.scrollTop > 20) {
|
|
||||||
color = this.diyData.global.topNavColor;
|
if (topNavBg) {
|
||||||
} else {
|
return this.scrollTop > 20 ? topNavColor : 'transparent';
|
||||||
color = 'transparent';
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
color = this.diyData.global.topNavColor;
|
|
||||||
}
|
}
|
||||||
return color;
|
|
||||||
|
return topNavColor;
|
||||||
},
|
},
|
||||||
// 修改属性样式
|
|
||||||
setPagestyle() {
|
|
||||||
this.diyGlobalData.value.forEach((item, index) => {
|
|
||||||
item.pageStyle = '';
|
|
||||||
// 给每个组件增加位置属性,用于定位,搜索、分类导航等定位
|
|
||||||
// 如果是Tab组件内部的子组件,添加tabIndex前缀避免moduleIndex冲突
|
|
||||||
if (this.diyData.tabIndex !== undefined) {
|
|
||||||
item.moduleIndex = `${this.diyData.tabIndex}-${index + 1}`;
|
|
||||||
} else {
|
|
||||||
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() {
|
diyDataArray() {
|
||||||
let data = [],
|
if (!this.processedData) {
|
||||||
showModuleData = this.$store.state.diyGroupShowModule ? JSON.parse(this.$store.state
|
this.processData();
|
||||||
.diyGroupShowModule) : '';
|
}
|
||||||
|
|
||||||
if (showModuleData.length) {
|
const showModuleData = this.$store.state.diyGroupShowModule
|
||||||
if (showModuleData.includes('null')) return [];
|
? JSON.parse(this.$store.state.diyGroupShowModule)
|
||||||
|
: null;
|
||||||
|
|
||||||
let diyDataArr = this.setPagestyle;
|
if (!showModuleData || !showModuleData.length) {
|
||||||
diyDataArr.forEach((item, index) => {
|
return this.processedData || [];
|
||||||
if (showModuleData.includes(item.componentName)) {
|
}
|
||||||
data.push(item);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
} else data = this.setPagestyle;
|
|
||||||
|
|
||||||
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>
|
</script>
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
<template>
|
<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-view :class="['image-nav', value.showStyle == 'fixed' ? 'fixed-layout' : value.showStyle]"
|
||||||
:scroll-x="value.showStyle == 'singleSlide'">
|
:scroll-x="value.showStyle == 'singleSlide'">
|
||||||
<view class="uni-scroll-view-content">
|
<view class="uni-scroll-view-content">
|
||||||
@@ -54,12 +54,35 @@ export default {
|
|||||||
return {
|
return {
|
||||||
pageWidth: '',
|
pageWidth: '',
|
||||||
indicatorDots: false,
|
indicatorDots: false,
|
||||||
swiperCurrent: 0
|
swiperCurrent: 0,
|
||||||
|
// H5 鼠标拖拽状态(singleSlide 模式专用)
|
||||||
|
slideIsDragging: false,
|
||||||
|
slideDidDrag: false, // 5px 阈值后置 true,用于判断 mouseup 后是否拦截 click
|
||||||
|
slideStartX: 0,
|
||||||
|
slideStartScrollLeft: 0,
|
||||||
|
_suppressNextClick: false // 拖拽结束后拦截一次 click,防止误触发跳转
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
created() {
|
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: {
|
watch: {
|
||||||
componentRefresh(newValue) {
|
componentRefresh(newValue) {
|
||||||
// 监听组件刷新
|
// 监听组件刷新
|
||||||
@@ -115,6 +138,163 @@ export default {
|
|||||||
// 轮播切换
|
// 轮播切换
|
||||||
swiperChange(event) {
|
swiperChange(event) {
|
||||||
this.swiperCurrent = event.detail.current;
|
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 {
|
.image-nav-item {
|
||||||
flex-shrink: 0;
|
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 {
|
&.pageSlide {
|
||||||
|
|||||||
@@ -146,14 +146,14 @@
|
|||||||
<text class="unit">{{ $lang('common.currencySymbol') }}</text>
|
<text class="unit">{{ $lang('common.currencySymbol') }}</text>
|
||||||
<text>{{ showMarketPrice(item) }}</text>
|
<text>{{ showMarketPrice(item) }}</text>
|
||||||
</view>
|
</view>
|
||||||
<view class="sale font-size-activity-tag color-tip">已售{{
|
<view class="sale font-size-activity-tag color-tip">{{
|
||||||
item.sale_num }}{{ item.unit ? item.unit : '件' }}</view>
|
$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>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
<view v-if="!isloading && goodsList[pageIndex].list.length == 0">
|
<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>
|
</view>
|
||||||
</block>
|
</block>
|
||||||
</mescroll-uni>
|
</mescroll-uni>
|
||||||
@@ -193,7 +193,7 @@ export default {
|
|||||||
pageIndex: 0, //当前选中分类id
|
pageIndex: 0, //当前选中分类id
|
||||||
cateList: [{
|
cateList: [{
|
||||||
//header分类
|
//header分类
|
||||||
category_name: '首页'
|
category_name: ''
|
||||||
}],
|
}],
|
||||||
twoCategorylist: [], //二级分类
|
twoCategorylist: [], //二级分类
|
||||||
twoCategorylistId: 0, //二级分类所在的swiper
|
twoCategorylistId: 0, //二级分类所在的swiper
|
||||||
@@ -258,6 +258,9 @@ export default {
|
|||||||
return data;
|
return data;
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
created() {
|
||||||
|
this.cateList[0].category_name = this.$lang('components-diy.diy-index-page.home');
|
||||||
|
},
|
||||||
watch: {
|
watch: {
|
||||||
type(newVal, oldVal) {
|
type(newVal, oldVal) {
|
||||||
if (newVal) {
|
if (newVal) {
|
||||||
@@ -323,7 +326,7 @@ export default {
|
|||||||
let obj = {
|
let obj = {
|
||||||
list: []
|
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);
|
arr.push(obj);
|
||||||
this.cateList = arr.concat(res.data);
|
this.cateList = arr.concat(res.data);
|
||||||
Object.keys(this.cateList).forEach((key, index) => {
|
Object.keys(this.cateList).forEach((key, index) => {
|
||||||
|
|||||||
@@ -14,7 +14,7 @@
|
|||||||
</view>
|
</view>
|
||||||
<view class="fui-remark jump" style="padding-right: 20rpx; text-align: center; line-height: 140rpx;">
|
<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"
|
<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>
|
||||||
</view>
|
</view>
|
||||||
|
|||||||
@@ -12,9 +12,10 @@
|
|||||||
style="border-radius:6rpx;width: 60rpx;"></image>
|
style="border-radius:6rpx;width: 60rpx;"></image>
|
||||||
</view>
|
</view>
|
||||||
<view class="fui-cell-text" style="color:#333;">{{ item.title }}</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>
|
||||||
</view>
|
</view>
|
||||||
|
<ns-login ref="login"></ns-login>
|
||||||
</view>
|
</view>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
@@ -32,7 +33,6 @@ export default {
|
|||||||
data() {
|
data() {
|
||||||
return {
|
return {
|
||||||
loading: true,
|
loading: true,
|
||||||
lang: uni.getStorageSync("lang")//en-us 英文
|
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
created() {
|
created() {
|
||||||
@@ -63,7 +63,7 @@ export default {
|
|||||||
redirectTo(link) {
|
redirectTo(link) {
|
||||||
if (link.wap_url) {
|
if (link.wap_url) {
|
||||||
if (this.$util.getCurrRoute() == this.$util.MEMBER_PAGE_URL && !this.storeToken) {
|
if (this.$util.getCurrRoute() == this.$util.MEMBER_PAGE_URL && !this.storeToken) {
|
||||||
this.$refs?.login?.open(link.wap_url);
|
this.redirectTologin(link.wap_url)
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -26,11 +26,11 @@
|
|||||||
<image
|
<image
|
||||||
:src="liveInfo.anchor_img != '' ? $util.img(liveInfo.anchor_img) : $util.getDefaultImage().head"
|
:src="liveInfo.anchor_img != '' ? $util.img(liveInfo.anchor_img) : $util.getDefaultImage().head"
|
||||||
class="anchor-img" @error="liveInfo.anchor_img = $util.getDefaultImage().head" show-menu-by-longpress/>
|
class="anchor-img" @error="liveInfo.anchor_img = $util.getDefaultImage().head" show-menu-by-longpress/>
|
||||||
<text class="anchor-name">主播:{{ liveInfo.anchor_name }}</text>
|
<text class="anchor-name">{{ $lang('components-diy.diy-live.anchorPrefix') }}{{ liveInfo.anchor_name }}</text>
|
||||||
</block>
|
</block>
|
||||||
<text class="separate" v-if="value.isShowAnchorInfo && value.isShowLiveGood">|</text>
|
<text class="separate" v-if="value.isShowAnchorInfo && value.isShowLiveGood">|</text>
|
||||||
<block v-if="value.isShowLiveGood">
|
<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>
|
</block>
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
|
|||||||
@@ -13,7 +13,7 @@
|
|||||||
<div
|
<div
|
||||||
style="position:absolute;right:12rpx;bottom:48rpx;z-index:1;background:#4390FF;padding:0rpx 20rpx;border-radius:8rpx;color: #fff;"
|
style="position:absolute;right:12rpx;bottom:48rpx;z-index:1;background:#4390FF;padding:0rpx 20rpx;border-radius:8rpx;color: #fff;"
|
||||||
@tap.stop="handlerClick(item)">
|
@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>
|
</div>
|
||||||
</map>
|
</map>
|
||||||
</view>
|
</view>
|
||||||
@@ -71,7 +71,7 @@ export default {
|
|||||||
uni.openLocation({
|
uni.openLocation({
|
||||||
latitude: parseFloat(item.lat),
|
latitude: parseFloat(item.lat),
|
||||||
longitude: parseFloat(item.lng),
|
longitude: parseFloat(item.lng),
|
||||||
name: "一键导航",
|
name: this.$lang('components-diy.diy-map.navigate'),
|
||||||
})
|
})
|
||||||
},
|
},
|
||||||
async handlerClick(item) {
|
async handlerClick(item) {
|
||||||
|
|||||||
@@ -12,7 +12,7 @@
|
|||||||
<!-- #ifdef MP -->
|
<!-- #ifdef MP -->
|
||||||
<block
|
<block
|
||||||
v-if="(memberInfo.nickname.indexOf('u_') != -1 && memberInfo.nickname == memberInfo.username) || memberInfo.nickname == memberInfo.mobile">
|
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>
|
</block>
|
||||||
<view class="nickname" v-else>
|
<view class="nickname" v-else>
|
||||||
<text class="name" @tap.stop="getWxAuth">{{ memberInfo.nickname }}</text>
|
<text class="name" @tap.stop="getWxAuth">{{ memberInfo.nickname }}</text>
|
||||||
@@ -36,7 +36,7 @@
|
|||||||
<!-- #ifdef H5 -->
|
<!-- #ifdef H5 -->
|
||||||
<block
|
<block
|
||||||
v-if="$util.isWeiXin() && ((memberInfo.nickname.indexOf('u_') != -1 && memberInfo.nickname == memberInfo.username) || memberInfo.nickname == memberInfo.mobile)">
|
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>
|
</block>
|
||||||
<view class="nickname" v-else>
|
<view class="nickname" v-else>
|
||||||
<text class="name" @tap.stop="redirect('/pages_tool/member/info')">{{ memberInfo.nickname
|
<text class="name" @tap.stop="redirect('/pages_tool/member/info')">{{ memberInfo.nickname
|
||||||
@@ -69,8 +69,8 @@
|
|||||||
<image :src="$util.getDefaultImage().head" mode="widthFix" show-menu-by-longpress></image>
|
<image :src="$util.getDefaultImage().head" mode="widthFix" show-menu-by-longpress></image>
|
||||||
</view>
|
</view>
|
||||||
<view class="info">
|
<view class="info">
|
||||||
<view class="nickname"><text class="name">{{ $lang('login') }}</text></view>
|
<view class="nickname"><text class="name">{{ $lang('member.index.login') }}</text></view>
|
||||||
<view class="desc">{{ $lang('loginTpis') }}</view>
|
<view class="desc">{{ $lang('member.index.loginTips') }}</view>
|
||||||
</view>
|
</view>
|
||||||
|
|
||||||
<view v-if="ischina == 1"
|
<view v-if="ischina == 1"
|
||||||
@@ -85,19 +85,19 @@
|
|||||||
{{ memberInfo ? (parseFloat(memberInfo.balance) +
|
{{ memberInfo ? (parseFloat(memberInfo.balance) +
|
||||||
parseFloat(memberInfo.balance_money)).toFixed(2) : '--' }}
|
parseFloat(memberInfo.balance_money)).toFixed(2) : '--' }}
|
||||||
</view>
|
</view>
|
||||||
<view class="title">{{ $lang('balance') }}</view>
|
<view class="title">{{ $lang('member.index.balance') }}</view>
|
||||||
</view>
|
</view>
|
||||||
<view class="solid"></view>
|
<view class="solid"></view>
|
||||||
<view class="account-item" @tap.stop="redirect('/pages_tool/member/point_detail')">
|
<view class="account-item" @tap.stop="redirect('/pages_tool/member/point_detail')">
|
||||||
<view class="value price-font">{{ memberInfo ? parseFloat(memberInfo.point) : '--' }}</view>
|
<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>
|
||||||
<view class="solid"></view>
|
<view class="solid"></view>
|
||||||
<view class="account-item" @tap.stop="redirect('/pages_tool/member/coupon')">
|
<view class="account-item" @tap.stop="redirect('/pages_tool/member/coupon')">
|
||||||
<view class="value price-font">
|
<view class="value price-font">
|
||||||
{{ memberInfo && memberInfo.coupon_num != undefined ? memberInfo.coupon_num : '--' }}
|
{{ memberInfo && memberInfo.coupon_num != undefined ? memberInfo.coupon_num : '--' }}
|
||||||
</view>
|
</view>
|
||||||
<view class="title">{{ $lang('coupon') }}</view>
|
<view class="title">{{ $lang('member.index.coupon') }}</view>
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
<!--
|
<!--
|
||||||
@@ -172,19 +172,19 @@
|
|||||||
<view class="account-item" @tap.stop="redirect('/pages_tool/member/balance')">
|
<view class="account-item" @tap.stop="redirect('/pages_tool/member/balance')">
|
||||||
<view class="value price-font">{{ memberInfo ? (parseFloat(memberInfo.balance) +
|
<view class="value price-font">{{ memberInfo ? (parseFloat(memberInfo.balance) +
|
||||||
parseFloat(memberInfo.balance_money)).toFixed(2) : '--' }}</view>
|
parseFloat(memberInfo.balance_money)).toFixed(2) : '--' }}</view>
|
||||||
<view class="title">{{ $lang('balance') }}</view>
|
<view class="title">{{ $lang('member.index.balance') }}</view>
|
||||||
</view>
|
</view>
|
||||||
<view class="solid"></view>
|
<view class="solid"></view>
|
||||||
<view class="account-item" @tap.stop="redirect('/pages_tool/member/point_detail')">
|
<view class="account-item" @tap.stop="redirect('/pages_tool/member/point_detail')">
|
||||||
<view class="value price-font">{{ memberInfo ? parseFloat(memberInfo.point) : '--' }}</view>
|
<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>
|
||||||
<view class="solid"></view>
|
<view class="solid"></view>
|
||||||
<view class="account-item" @tap.stop="redirect('/pages_tool/member/coupon')">
|
<view class="account-item" @tap.stop="redirect('/pages_tool/member/coupon')">
|
||||||
<view class="value price-font">
|
<view class="value price-font">
|
||||||
{{ memberInfo && memberInfo.coupon_num != undefined ? memberInfo.coupon_num : '--' }}
|
{{ memberInfo && memberInfo.coupon_num != undefined ? memberInfo.coupon_num : '--' }}
|
||||||
</view>
|
</view>
|
||||||
<view class="title">{{ $lang('coupon') }}</view>
|
<view class="title">{{ $lang('member.index.coupon') }}</view>
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
@@ -194,13 +194,13 @@
|
|||||||
<uni-popup ref="completeInfoPopup" type="bottom" :maskClick="false">
|
<uni-popup ref="completeInfoPopup" type="bottom" :maskClick="false">
|
||||||
<view class="complete-info-wrap">
|
<view class="complete-info-wrap">
|
||||||
<view class="head">
|
<view class="head">
|
||||||
<text class="title">获取您的昵称、头像</text>
|
<text class="title">{{ $lang('components-diy.diy-member-info.completeInfoTitle') }}</text>
|
||||||
<text class="color-tip tips">获取用户头像、昵称完善个人资料,主要用于向用户提供具有辨识度的用户中心界面</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>
|
<text class="iconfont icon-close color-tip" @tap.stop="cancelCompleteInfo"></text>
|
||||||
</view>
|
</view>
|
||||||
<!-- #ifdef MP-WEIXIN -->
|
<!-- #ifdef MP-WEIXIN -->
|
||||||
<view class="item-wrap">
|
<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">
|
<button open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
|
||||||
<image :src="avatarUrl ? avatarUrl : $util.getDefaultImage().head"
|
<image :src="avatarUrl ? avatarUrl : $util.getDefaultImage().head"
|
||||||
@error="avatarUrl = $util.getDefaultImage().head" mode="aspectFill" show-menu-by-longpress/>
|
@error="avatarUrl = $util.getDefaultImage().head" mode="aspectFill" show-menu-by-longpress/>
|
||||||
@@ -208,13 +208,13 @@
|
|||||||
</button>
|
</button>
|
||||||
</view>
|
</view>
|
||||||
<view class="item-wrap">
|
<view class="item-wrap">
|
||||||
<text class="label">昵称</text>
|
<text class="label">{{ $lang('components-diy.diy-member-info.nicknameLabel') }}</text>
|
||||||
<input type="nickname" placeholder="请输入昵称" v-model="nickName" @blur="blurNickName" />
|
<input type="nickname" :placeholder="$lang('components-diy.diy-member-info.nicknamePlaceholder')" v-model="nickName" @blur="blurNickName" />
|
||||||
</view>
|
</view>
|
||||||
<!-- #endif -->
|
<!-- #endif -->
|
||||||
<!-- #ifdef MP-ALIPAY -->
|
<!-- #ifdef MP-ALIPAY -->
|
||||||
<view class="item-wrap">
|
<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"
|
<button open-type="getAuthorize" scope="userInfo" @getAuthorize="aliappGetUserinfo"
|
||||||
:plain="true" class="border-0">
|
:plain="true" class="border-0">
|
||||||
<image :src="avatarUrl ? avatarUrl : $util.getDefaultImage().head"
|
<image :src="avatarUrl ? avatarUrl : $util.getDefaultImage().head"
|
||||||
@@ -223,11 +223,11 @@
|
|||||||
</button>
|
</button>
|
||||||
</view>
|
</view>
|
||||||
<view class="item-wrap">
|
<view class="item-wrap">
|
||||||
<text class="label">昵称</text>
|
<text class="label">{{ $lang('components-diy.diy-member-info.nicknameLabel') }}</text>
|
||||||
<input type="nickname" placeholder="请输入昵称" v-model="nickName" @blur="blurNickName" />
|
<input type="nickname" :placeholder="$lang('components-diy.diy-member-info.nicknamePlaceholder')" v-model="nickName" @blur="blurNickName" />
|
||||||
</view>
|
</view>
|
||||||
<!-- #endif -->
|
<!-- #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>
|
</view>
|
||||||
</uni-popup>
|
</uni-popup>
|
||||||
</view>
|
</view>
|
||||||
@@ -493,8 +493,8 @@ export default {
|
|||||||
showMemberQrcode() {
|
showMemberQrcode() {
|
||||||
if (!this.memberInfo.mobile && !this.memberInfo.member_code) {
|
if (!this.memberInfo.mobile && !this.memberInfo.member_code) {
|
||||||
uni.showModal({
|
uni.showModal({
|
||||||
title: '提示',
|
title: this.$lang('components-diy.diy-member-info.tip'),
|
||||||
content: '使用会员码需先绑定手机号,是否绑定手机号?',
|
content: this.$lang('components-diy.diy-member-info.bindMobileTip'),
|
||||||
success: res => {
|
success: res => {
|
||||||
if (res.confirm) {
|
if (res.confirm) {
|
||||||
// #ifdef MP-WEIXIN
|
// #ifdef MP-WEIXIN
|
||||||
@@ -566,6 +566,10 @@ export default {
|
|||||||
this.$util.redirectTo(url);
|
this.$util.redirectTo(url);
|
||||||
}
|
}
|
||||||
// #endif
|
// #endif
|
||||||
|
|
||||||
|
// #ifndef MP || H5
|
||||||
|
this.$util.redirectTo(url);
|
||||||
|
// #endif
|
||||||
},
|
},
|
||||||
/**
|
/**
|
||||||
* 获取微信授权
|
* 获取微信授权
|
||||||
@@ -630,16 +634,19 @@ export default {
|
|||||||
});
|
});
|
||||||
},
|
},
|
||||||
openCompleteInfoPop(callback) {
|
openCompleteInfoPop(callback) {
|
||||||
this.$refs.completeInfoPopup.open(() => {
|
this.$refs.completeInfoPopup.open();
|
||||||
this.$store.commit('setBottomNavHidden', false); //显示底部导航
|
// 关闭时(setBottomNavHidden=false)由 saveCompleteInfo / cancelCompleteInfo 显式处理,
|
||||||
});
|
// 不在 open 回调里写 — 回调在"弹窗被销毁/页面被卸载"等异常路径下不保证触发,会卡住 TabBar 隐藏态
|
||||||
this.$store.commit('setBottomNavHidden', true); // 隐藏底部导航
|
// TabBar 根页面(如会员中心)不能藏 TabBar — 否则会被自己藏起来
|
||||||
|
if (!this.$util.isCurrentPageTabBarRoot()) {
|
||||||
|
this.$store.commit('setBottomNavHidden', true); // 隐藏底部导航
|
||||||
|
}
|
||||||
this.completeInfoCallback = callback;
|
this.completeInfoCallback = callback;
|
||||||
},
|
},
|
||||||
saveCompleteInfo() {
|
saveCompleteInfo() {
|
||||||
if (this.nickName.length == 0) {
|
if (this.nickName.length == 0) {
|
||||||
this.$util.showToast({
|
this.$util.showToast({
|
||||||
title: '请输入昵称'
|
title: this.$lang('components-diy.diy-member-info.pleaseEnterNickname')
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -678,7 +685,7 @@ export default {
|
|||||||
},
|
},
|
||||||
fail: () => {
|
fail: () => {
|
||||||
this.$util.showToast({
|
this.$util.showToast({
|
||||||
title: '上传失败'
|
title: this.$lang('components-diy.diy-member-info.uploadFailed')
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
@@ -709,7 +716,7 @@ export default {
|
|||||||
},
|
},
|
||||||
fail: () => {
|
fail: () => {
|
||||||
this.$util.showToast({
|
this.$util.showToast({
|
||||||
title: '头像拉取失败'
|
title: this.$lang('components-diy.diy-member-info.avatarPullFailed')
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
@@ -858,7 +865,11 @@ export default {
|
|||||||
height: 120rpx;
|
height: 120rpx;
|
||||||
border-top-left-radius: 10rpx;
|
border-top-left-radius: 10rpx;
|
||||||
border-top-right-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;
|
padding: 30rpx 40rpx;
|
||||||
box-sizing: border-box;
|
box-sizing: border-box;
|
||||||
|
|
||||||
@@ -939,7 +950,12 @@ export default {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.super-text {
|
.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-background-clip: text;
|
||||||
-webkit-text-fill-color: transparent;
|
-webkit-text-fill-color: transparent;
|
||||||
display: flex;
|
display: flex;
|
||||||
@@ -989,7 +1005,11 @@ export default {
|
|||||||
|
|
||||||
.super-member {
|
.super-member {
|
||||||
color: #8d4b16;
|
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-left-radius: 18rpx;
|
||||||
border-top-right-radius: 18rpx;
|
border-top-right-radius: 18rpx;
|
||||||
|
|
||||||
|
|||||||
@@ -5,15 +5,15 @@
|
|||||||
<view :class="['list-wrap', value.style]" :style="warpCss">
|
<view :class="['list-wrap', value.style]" :style="warpCss">
|
||||||
<view :class="['item', value.ornament.type]" v-for="(item, index) in list" :key="index"
|
<view :class="['item', value.ornament.type]" v-for="(item, index) in list" :key="index"
|
||||||
:style="itemCss" @tap.stop="handlerClick(item)">
|
: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"
|
<image class="cover-img" :src="$util.img(item.merch_image)" mode="widthFix"
|
||||||
@error="imgError(index)" show-menu-by-longpress />
|
@error="imgError(index)" show-menu-by-longpress />
|
||||||
</view>
|
</view>
|
||||||
<view class="info-wrap">
|
<view class="info-wrap">
|
||||||
<text class="title">{{ item.merch_name }}</text>
|
<text class="title" @tap.stop="handlerClick(item)">{{ item.merch_name }}</text>
|
||||||
<text class="desc">{{ item.desc }}</text>
|
<text class="desc">{{ item.desc }}</text>
|
||||||
<view class="read-wrap"></view>
|
<view class="read-wrap"></view>
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
@@ -27,14 +27,16 @@
|
|||||||
<view class="merch-nav-item graphic" v-for="(item, index) in list" :key="index"
|
<view class="merch-nav-item graphic" v-for="(item, index) in list" :key="index"
|
||||||
:style="{ width: 100 / 4 + '%' }" @tap.stop="handlerClick(item)">
|
:style="{ width: 100 / 4 + '%' }" @tap.stop="handlerClick(item)">
|
||||||
<view class="graphic-img" v-if="value.mode != 'text'"
|
<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
|
<image
|
||||||
:src="$util.img(item.merch_image) || $util.img('public/uniapp/default_img/goods.png')"
|
:src="$util.img(item.merch_image) || $util.img('public/uniapp/default_img/goods.png')"
|
||||||
mode="aspectFill" show-menu-by-longpress
|
mode="aspectFill" show-menu-by-longpress
|
||||||
style="max-width: 80rpx; max-height: 80rpx; border-radius: 50rpx;" />
|
style="max-width: 80rpx; max-height: 80rpx; border-radius: 50rpx;" />
|
||||||
</view>
|
</view>
|
||||||
<text class="graphic-text"
|
<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 }}
|
{{ item.merch_name }}
|
||||||
</text>
|
</text>
|
||||||
</view>
|
</view>
|
||||||
@@ -62,31 +64,31 @@ export default {
|
|||||||
list: [
|
list: [
|
||||||
/*{
|
/*{
|
||||||
merch_name:'品牌',
|
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_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_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_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_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_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_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,
|
loading: true,
|
||||||
|
|||||||
@@ -39,14 +39,14 @@
|
|||||||
item.update_time_day }}</text>
|
item.update_time_day }}</text>
|
||||||
</view>
|
</view>
|
||||||
<view class="notes-num">
|
<view class="notes-num">
|
||||||
<text v-show="value.readNum == 1 && item.is_show_read_num == 1">阅读 {{
|
<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>
|
item.initial_read_num + item.read_num }}</text>
|
||||||
</view>
|
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
</scroll-view>
|
</view>
|
||||||
|
</scroll-view>
|
||||||
|
|
||||||
<ns-login ref="login"></ns-login>
|
<ns-login ref="login"></ns-login>
|
||||||
</view>
|
</view>
|
||||||
|
|||||||
@@ -9,7 +9,8 @@
|
|||||||
<view class="notice-xian"></view>
|
<view class="notice-xian"></view>
|
||||||
<view class="main-wrap">
|
<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-wrap">
|
||||||
<view class="marquee" :style="marqueeStyle">
|
<view class="marquee" :style="marqueeStyle">
|
||||||
<text v-for="(item, index) in list" :key="index"
|
<text v-for="(item, index) in list" :key="index"
|
||||||
@@ -27,7 +28,8 @@
|
|||||||
<!-- 上下滚动 -->
|
<!-- 上下滚动 -->
|
||||||
<template v-if="value.scrollWay == 'upDown'">
|
<template v-if="value.scrollWay == 'upDown'">
|
||||||
<swiper :vertical="true" :duration="500" autoplay="true" circular="true">
|
<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"
|
<text class="beyond-hiding using-hidden"
|
||||||
:style="{ color: value.textColor, fontSize: value.fontSize * 2 + 'rpx', fontWeight: value.fontWeight }">
|
:style="{ color: value.textColor, fontSize: value.fontSize * 2 + 'rpx', fontWeight: value.fontWeight }">
|
||||||
{{ item.title }}
|
{{ item.title }}
|
||||||
@@ -42,11 +44,11 @@
|
|||||||
<uni-popup ref="noticePopup" type="center">
|
<uni-popup ref="noticePopup" type="center">
|
||||||
<view class="notice-popup">
|
<view class="notice-popup">
|
||||||
<view class="head-wrap" @tap.stop="closeNoticePopup">
|
<view class="head-wrap" @tap.stop="closeNoticePopup">
|
||||||
<text>公告</text>
|
<text>{{ $lang('components-diy.diy-notice.notice') }}</text>
|
||||||
<text class="iconfont icon-close"></text>
|
<text class="iconfont icon-close"></text>
|
||||||
</view>
|
</view>
|
||||||
<view class="content-wrap">{{ notice }}</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>
|
</view>
|
||||||
</uni-popup>
|
</uni-popup>
|
||||||
</view>
|
</view>
|
||||||
@@ -136,11 +138,11 @@ export default {
|
|||||||
});
|
});
|
||||||
} else if (!item) {
|
} else if (!item) {
|
||||||
this.$util.redirectTo('/pages_tool/notice/list');
|
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);
|
this.$util.diyRedirectTo(item.link);
|
||||||
} else {
|
} else {
|
||||||
// 如果不设置跳转链接,则点击弹框展示
|
// 如果不设置跳转链接,则点击弹框展示
|
||||||
this.notice = item.title;
|
this.notice = item.content || item.title || '';
|
||||||
this.$refs.noticePopup.open();
|
this.$refs.noticePopup.open();
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -3,23 +3,23 @@
|
|||||||
<view class="payment-qrocde-box">
|
<view class="payment-qrocde-box">
|
||||||
<view class="qrocde-left">
|
<view class="qrocde-left">
|
||||||
<view class="qrocde-desc">
|
<view class="qrocde-desc">
|
||||||
<text>门店消费时使用,支付时点击下方展示付款码</text>
|
<text>{{ $lang('components-diy.diy-payment-qrcode.description') }}</text>
|
||||||
<!-- <text class="iconfont icon-shuaxin"></text> -->
|
<!-- <text class="iconfont icon-shuaxin"></text> -->
|
||||||
</view>
|
</view>
|
||||||
<view class="qrocde-action">
|
<view class="qrocde-action">
|
||||||
<button type="primary" @tap.stop="toLink">
|
<button type="primary" @tap.stop="toLink">
|
||||||
<text class="iconfont icon-fukuanma"></text>
|
<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>
|
||||||
<button type="primary" @tap.stop="openPaymentPopup">
|
<button type="primary" @tap.stop="openPaymentPopup">
|
||||||
<text class="iconfont icon-saomafu"></text>
|
<text class="iconfont icon-saomafu"></text>
|
||||||
<text class="action-name">扫码付</text>
|
<text class="action-name">{{ $lang('components-diy.diy-payment-qrcode.scanToPay') }}</text>
|
||||||
</button>
|
</button>
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
<view class="qrocde-right">
|
<view class="qrocde-right">
|
||||||
<text class="iconfont icon-zhifu"></text>
|
<text class="iconfont icon-zhifu"></text>
|
||||||
<text class="name">门店支付</text>
|
<text class="name">{{ $lang('components-diy.diy-payment-qrcode.storePayment') }}</text>
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
|
|
||||||
@@ -27,11 +27,11 @@
|
|||||||
<uni-popup ref="paymentPopup" type="center">
|
<uni-popup ref="paymentPopup" type="center">
|
||||||
<view class="payment-popup">
|
<view class="payment-popup">
|
||||||
<view class="head-wrap" @tap.stop="closePaymentPopup">
|
<view class="head-wrap" @tap.stop="closePaymentPopup">
|
||||||
<text>提示</text>
|
<text>{{ $lang('components-diy.diy-payment-qrcode.popupTipTitle') }}</text>
|
||||||
<text class="iconfont icon-close"></text>
|
<text class="iconfont icon-close"></text>
|
||||||
</view>
|
</view>
|
||||||
<view class="content-wrap">扫码付请退出程序后直接使用微信扫一扫或返回上一页使用付款码进行支付</view>
|
<view class="content-wrap">{{ $lang('components-diy.diy-payment-qrcode.scanToPayTip') }}</view>
|
||||||
<button type="primary" @tap.stop="closePaymentPopup">我知道了</button>
|
<button type="primary" @tap.stop="closePaymentPopup">{{ $lang('components-diy.diy-payment-qrcode.gotIt') }}</button>
|
||||||
</view>
|
</view>
|
||||||
</uni-popup>
|
</uni-popup>
|
||||||
</view>
|
</view>
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
<template>
|
<template>
|
||||||
<view data-component-name="diy-picture" class="diy-picture" :style="style">
|
<view data-component-name="diy-picture" class="diy-picture" :style="style">
|
||||||
<view class="fui-picture">
|
<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)"
|
<image mode="widthFix" style="width: 100%;height:auto" :src="$util.img(item.imageUrl)"
|
||||||
v-if="item.link.wap_url" @tap.stop="handlerClick(item)" show-menu-by-longpress></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
|
<image mode="widthFix" style="width: 100%;height:auto" :src="$util.img(item.imageUrl)" v-else
|
||||||
@@ -11,6 +11,7 @@
|
|||||||
<image mode="widthFix" src="{{childitem.imgurl}}" style="{{bannerheight?'height:'+bannerheight+'px':'height:auto'}}"></image>
|
<image mode="widthFix" src="{{childitem.imgurl}}" style="{{bannerheight?'height:'+bannerheight+'px':'height:auto'}}"></image>
|
||||||
</view> -->
|
</view> -->
|
||||||
</view>
|
</view>
|
||||||
|
<ns-login ref="login"></ns-login>
|
||||||
</view>
|
</view>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
|
|||||||
@@ -21,11 +21,11 @@
|
|||||||
:style="{ color: value.theme == 'diy' ? value.groupStyle.bgColor : '', borderColor: value.theme == 'diy' ? value.groupStyle.bgColor : '' }">
|
:style="{ color: value.theme == 'diy' ? value.groupStyle.bgColor : '', borderColor: value.theme == 'diy' ? value.groupStyle.bgColor : '' }">
|
||||||
<text class="iconfont icon-yonghu3"
|
<text class="iconfont icon-yonghu3"
|
||||||
:style="{ backgroundColor: value.theme == 'diy' ? value.groupStyle.bgColor : '' }"></text>
|
: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>
|
||||||
<view v-if="value.saleStyle.control"
|
<view v-if="value.saleStyle.control"
|
||||||
:style="{ color: value.theme == 'diy' ? value.saleStyle.color : '', borderColor: value.theme == 'diy' ? value.saleStyle.color : '' }">
|
: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>
|
</view>
|
||||||
<view class="price-wrap">
|
<view class="price-wrap">
|
||||||
@@ -49,10 +49,9 @@
|
|||||||
borderRadius: value.btnStyle.aroundRadius * 2 + 'rpx'
|
borderRadius: value.btnStyle.aroundRadius * 2 + 'rpx'
|
||||||
}">
|
}">
|
||||||
<text class="text">{{ value.btnStyle.text }}</text>
|
<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 == 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">返¥{{
|
<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>
|
||||||
item.reward_type_num }}</text>
|
<text class="fan" v-if="item.reward_type == 3">{{ $lang('components-diy.diy-pinfan.backCoupon') }}</text>
|
||||||
<text class="fan" v-if="item.reward_type == 3">返优惠券</text>
|
|
||||||
</button>
|
</button>
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
@@ -78,21 +77,21 @@
|
|||||||
<view v-if="value.groupStyle.control" class="num">
|
<view v-if="value.groupStyle.control" class="num">
|
||||||
<text class="content-tuan-box"
|
<text class="content-tuan-box"
|
||||||
:style="{ color: value.theme == 'diy' ? value.groupStyle.color : '', backgroundColor: value.theme == 'diy' ? value.groupStyle.bgColor : '' }">
|
: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>
|
||||||
<text class="content-tuan-price"
|
<text class="content-tuan-price"
|
||||||
:style="{ color: value.theme == 'diy' ? value.groupStyle.bgColor : '' }"
|
:style="{ color: value.theme == 'diy' ? value.groupStyle.bgColor : '' }"
|
||||||
v-if="item.reward_type == 4">
|
v-if="item.reward_type == 4">
|
||||||
返{{ item.reward_type_num }}积分
|
{{ $lang('components-diy.diy-pinfan.backPoints', { num: item.reward_type_num }) }}
|
||||||
</text>
|
</text>
|
||||||
<text class="content-tuan-price"
|
<text class="content-tuan-price"
|
||||||
:style="{ color: value.theme == 'diy' ? value.groupStyle.bgColor : '' }"
|
:style="{ color: value.theme == 'diy' ? value.groupStyle.bgColor : '' }"
|
||||||
v-if="item.reward_type == 1 || item.reward_type == 2">
|
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>
|
||||||
<text class="content-tuan-price"
|
<text class="content-tuan-price"
|
||||||
:style="{ color: value.theme == 'diy' ? value.groupStyle.bgColor : '' }"
|
: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>
|
||||||
<view class="price-wrap" v-if="value.priceStyle.mainControl">
|
<view class="price-wrap" v-if="value.priceStyle.mainControl">
|
||||||
<text class="unit price-style small"
|
<text class="unit price-style small"
|
||||||
@@ -129,22 +128,22 @@
|
|||||||
<view v-if="value.groupStyle.control" class="num">
|
<view v-if="value.groupStyle.control" class="num">
|
||||||
<text class="content-tuan-box"
|
<text class="content-tuan-box"
|
||||||
:style="{ color: value.theme == 'diy' ? value.groupStyle.color : '', backgroundColor: value.theme == 'diy' ? value.groupStyle.bgColor : '' }">
|
: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>
|
||||||
<text class="content-tuan-price"
|
<text class="content-tuan-price"
|
||||||
:style="{ color: value.theme == 'diy' ? value.groupStyle.bgColor : '' }"
|
:style="{ color: value.theme == 'diy' ? value.groupStyle.bgColor : '' }"
|
||||||
v-if="item.reward_type == 4">
|
v-if="item.reward_type == 4">
|
||||||
返{{ item.reward_type_num }}积分
|
{{ $lang('components-diy.diy-pinfan.backPoints', { num: item.reward_type_num }) }}
|
||||||
</text>
|
</text>
|
||||||
<text class="content-tuan-price"
|
<text class="content-tuan-price"
|
||||||
:style="{ color: value.theme == 'diy' ? value.groupStyle.bgColor : '' }"
|
:style="{ color: value.theme == 'diy' ? value.groupStyle.bgColor : '' }"
|
||||||
v-if="item.reward_type == 1 || item.reward_type == 2">
|
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>
|
||||||
<text class="content-tuan-price"
|
<text class="content-tuan-price"
|
||||||
:style="{ color: value.theme == 'diy' ? value.groupStyle.bgColor : '' }"
|
:style="{ color: value.theme == 'diy' ? value.groupStyle.bgColor : '' }"
|
||||||
v-if="item.reward_type == 3">
|
v-if="item.reward_type == 3">
|
||||||
返优惠券
|
{{ $lang('components-diy.diy-pinfan.backCoupon') }}
|
||||||
</text>
|
</text>
|
||||||
</view>
|
</view>
|
||||||
<view class="price-wrap" v-if="value.priceStyle.mainControl">
|
<view class="price-wrap" v-if="value.priceStyle.mainControl">
|
||||||
|
|||||||
@@ -26,7 +26,7 @@
|
|||||||
</view>
|
</view>
|
||||||
<view :style="{ color: value.titleStyle.textColor }">
|
<view :style="{ color: value.titleStyle.textColor }">
|
||||||
<text>{{ value.titleStyle.virtualNum || headData.pintuan_count }}</text>
|
<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>
|
</view>
|
||||||
<view class="head-right"
|
<view class="head-right"
|
||||||
@@ -59,11 +59,11 @@
|
|||||||
}">
|
}">
|
||||||
<text class="iconfont icon-yonghu3"
|
<text class="iconfont icon-yonghu3"
|
||||||
:style="{ backgroundColor: value.theme == 'diy' ? value.groupStyle.bgColorStart : '' }"></text>
|
: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>
|
||||||
<view v-if="value.saleStyle.control"
|
<view v-if="value.saleStyle.control"
|
||||||
:style="{ color: value.theme == 'diy' ? value.saleStyle.color : '', borderColor: value.theme == 'diy' ? value.saleStyle.color : '' }">
|
: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>
|
||||||
</view>
|
</view>
|
||||||
|
|
||||||
@@ -110,7 +110,7 @@
|
|||||||
color: value.theme == 'diy' ? value.groupStyle.color : '',
|
color: value.theme == 'diy' ? value.groupStyle.color : '',
|
||||||
background: value.theme == 'diy' ? 'linear-gradient(to right,' + value.groupStyle.bgColorStart + ',' + value.groupStyle.bgColorEnd + ')' : ''
|
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>
|
</view>
|
||||||
<view :class="['content', { 'multi-content': value.nameLineMode == 'multiple' }]"
|
<view :class="['content', { 'multi-content': value.nameLineMode == 'multiple' }]"
|
||||||
@@ -148,10 +148,10 @@
|
|||||||
{{ '.' + item.pintuan_price.split('.')[1] }}
|
{{ '.' + item.pintuan_price.split('.')[1] }}
|
||||||
</text>
|
</text>
|
||||||
</view>
|
</view>
|
||||||
<view class="sale-action">去参团</view>
|
<view class="sale-action">{{ $lang('components-diy.diy-pintuan.joinGroup') }}</view>
|
||||||
</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>
|
||||||
</view>
|
</view>
|
||||||
</scroll-view>
|
</scroll-view>
|
||||||
@@ -170,7 +170,7 @@
|
|||||||
color: value.theme == 'diy' ? value.groupStyle.color : '',
|
color: value.theme == 'diy' ? value.groupStyle.color : '',
|
||||||
background: value.theme == 'diy' ? 'linear-gradient(to right,' + value.groupStyle.bgColorStart + ',' + value.groupStyle.bgColorEnd + ')' : ''
|
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>
|
</view>
|
||||||
<view :class="['content', { 'multi-content': value.nameLineMode == 'multiple' }]"
|
<view :class="['content', { 'multi-content': value.nameLineMode == 'multiple' }]"
|
||||||
@@ -192,7 +192,7 @@
|
|||||||
{{ '.' + item.pintuan_price.split('.')[1] }}
|
{{ '.' + item.pintuan_price.split('.')[1] }}
|
||||||
</text>
|
</text>
|
||||||
</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>
|
||||||
</view>
|
</view>
|
||||||
</swiper-item>
|
</swiper-item>
|
||||||
@@ -451,7 +451,10 @@ scroll-view ::-webkit-scrollbar {
|
|||||||
width: 40rpx;
|
width: 40rpx;
|
||||||
height: 40rpx;
|
height: 40rpx;
|
||||||
border-radius: 50%;
|
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;
|
margin-left: -14rpx;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -482,7 +485,10 @@ scroll-view ::-webkit-scrollbar {
|
|||||||
align-items: center;
|
align-items: center;
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
height: 36rpx;
|
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;
|
border-radius: 24rpx;
|
||||||
padding: 2rpx;
|
padding: 2rpx;
|
||||||
|
|
||||||
@@ -495,7 +501,9 @@ scroll-view ::-webkit-scrollbar {
|
|||||||
text:nth-child(2) {
|
text:nth-child(2) {
|
||||||
padding: 6rpx 4rpx 4rpx;
|
padding: 6rpx 4rpx 4rpx;
|
||||||
background-color: #fff;
|
background-color: #fff;
|
||||||
color: #ffbd5b;
|
// P0: 拼团头文字色 → var(--pintuan-label-grad-start) 复用
|
||||||
|
// 兼容: 微信小程序 / 鸿蒙元服务 — color 接受 var() 无问题
|
||||||
|
color: var(--pintuan-label-grad-start, #ffbd5b);
|
||||||
border-radius: 50%;
|
border-radius: 50%;
|
||||||
transform: scale(0.6);
|
transform: scale(0.6);
|
||||||
font-weight: bold;
|
font-weight: bold;
|
||||||
@@ -799,7 +807,10 @@ scroll-view ::-webkit-scrollbar {
|
|||||||
font-size: $font-size-tag;
|
font-size: $font-size-tag;
|
||||||
width: 94rpx;
|
width: 94rpx;
|
||||||
height: 44rpx;
|
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;
|
border-radius: 8rpx;
|
||||||
color: #fff;
|
color: #fff;
|
||||||
text-align: center;
|
text-align: center;
|
||||||
|
|||||||
@@ -91,14 +91,52 @@ export default {
|
|||||||
},
|
},
|
||||||
data() {
|
data() {
|
||||||
return {
|
return {
|
||||||
customHtml: ''
|
customHtml: '',
|
||||||
|
processedList: []
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
created() {
|
created() {
|
||||||
if (this.value.mode == 'custom-rubik-cube') {
|
this.processValue();
|
||||||
this.value.diyHtml = this.value.diyHtml.replace(/"/g, '"');
|
},
|
||||||
this.customHtml = htmlParser(this.value.diyHtml);
|
watch: {
|
||||||
} else {
|
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(/"/g, '"');
|
||||||
|
this.customHtml = htmlParser(diyHtml);
|
||||||
|
} else {
|
||||||
|
this.initList();
|
||||||
|
this.recalcLayout();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
// 根据当前 mode 派发到对应的 calcXxx
|
||||||
|
recalcLayout() {
|
||||||
var singleRow = {
|
var singleRow = {
|
||||||
'row1-of2': {
|
'row1-of2': {
|
||||||
ratio: 2,
|
ratio: 2,
|
||||||
@@ -125,34 +163,18 @@ export default {
|
|||||||
} else if (this.value.mode == 'row1-lt-of1-tp-of2-bm') {
|
} else if (this.value.mode == 'row1-lt-of1-tp-of2-bm') {
|
||||||
this.calcRowOneLeftOfOneTopOfTwoBottom();
|
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() {
|
initList() {
|
||||||
var obj = '';
|
if (!this.value.list || !Array.isArray(this.value.list)) {
|
||||||
obj += 'background-color:' + this.value.componentBgColor + ';';
|
this.processedList = [];
|
||||||
if (this.value.componentAngle == 'round') {
|
return;
|
||||||
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;
|
this.processedList = this.value.list.map((item, index) => {
|
||||||
}
|
const newItem = { ...item };
|
||||||
},
|
newItem.pageItemStyle = this.countBorderRadius(this.value.mode, index);
|
||||||
methods: {
|
return newItem;
|
||||||
|
});
|
||||||
|
},
|
||||||
/**
|
/**
|
||||||
* 魔方:单行多个,平分宽度
|
* 魔方:单行多个,平分宽度
|
||||||
* 公式:
|
* 公式:
|
||||||
|
|||||||
@@ -28,7 +28,8 @@
|
|||||||
@tap.stop="handlerSearchClick"
|
@tap.stop="handlerSearchClick"
|
||||||
:placeholderStyle="placeholderStyle" />
|
:placeholderStyle="placeholderStyle" />
|
||||||
<text class="search-content-btn" @tap.stop="handlerSearchClick"
|
<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>
|
||||||
<view class="img" v-if="value.iconType == 'img'"
|
<view class="img" v-if="value.iconType == 'img'"
|
||||||
@tap.stop="handlerRedirectToClick(value.searchLink)">
|
@tap.stop="handlerRedirectToClick(value.searchLink)">
|
||||||
|
|||||||
@@ -13,10 +13,10 @@
|
|||||||
</view>
|
</view>
|
||||||
<image v-else class="title-img" :src="$util.img(value.titleStyle.leftImg)" mode="heightFix" show-menu-by-longpress/>
|
<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"
|
<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 }">
|
<view class="time" :style="{ background: value.titleStyle.timeBgColor }">
|
||||||
<text :style="{ color: value.titleStyle.textColor }" class="seckill-title-name text">{{ isFuture ?
|
<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"
|
<text v-if="value.titleStyle.timeImageUrl"
|
||||||
:class="['seckill-title-name icon', value.titleStyle.timeImageUrl]"></text>
|
:class="['seckill-title-name icon', value.titleStyle.timeImageUrl]"></text>
|
||||||
<text class="hour number" :style="titleTimeStyle">{{ seckillH ? seckillH : '00' }}</text>
|
<text class="hour number" :style="titleTimeStyle">{{ seckillH ? seckillH : '00' }}</text>
|
||||||
@@ -62,8 +62,8 @@
|
|||||||
</view>
|
</view>
|
||||||
<view class="num"
|
<view class="num"
|
||||||
:style="{ color: value.theme == 'diy' ? value.saleStyle.color : '', borderColor: value.theme == 'diy' ? value.saleStyle.color : '' }">
|
: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 +
|
{{ $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' }}%
|
item.sale_num)) * 100).toFixed(2) : '0.00' }) }}
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
<view class="bottom-wrap">
|
<view class="bottom-wrap">
|
||||||
@@ -87,7 +87,7 @@
|
|||||||
</view>
|
</view>
|
||||||
<view class="price-font" v-else>
|
<view class="price-font" v-else>
|
||||||
<text
|
<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 : '' }"
|
<text :style="{ color: value.theme == 'diy' ? value.priceStyle.lineColor : '' }"
|
||||||
class="original-price">¥{{ item.price }}</text>
|
class="original-price">¥{{ item.price }}</text>
|
||||||
</view>
|
</view>
|
||||||
@@ -97,7 +97,7 @@
|
|||||||
color: value.btnStyle.theme == 'diy' ? value.btnStyle.textColor : '',
|
color: value.btnStyle.theme == 'diy' ? value.btnStyle.textColor : '',
|
||||||
borderRadius: value.btnStyle.aroundRadius * 2 + 'rpx'
|
borderRadius: value.btnStyle.aroundRadius * 2 + 'rpx'
|
||||||
}">
|
}">
|
||||||
{{ isFuture ? '即将开始' : value.btnStyle.text }}
|
{{ isFuture ? $lang('components-diy.diy-seckill.comingSoon') : value.btnStyle.text }}
|
||||||
</button>
|
</button>
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
@@ -140,7 +140,7 @@
|
|||||||
color: value.btnStyle.theme == 'diy' ? value.btnStyle.textColor : '',
|
color: value.btnStyle.theme == 'diy' ? value.btnStyle.textColor : '',
|
||||||
borderRadius: value.btnStyle.aroundRadius * 2 + 'rpx'
|
borderRadius: value.btnStyle.aroundRadius * 2 + 'rpx'
|
||||||
}">
|
}">
|
||||||
{{ isFuture ? '即将开始' : value.btnStyle.text }}
|
{{ isFuture ? $lang('components-diy.diy-seckill.comingSoon') : value.btnStyle.text }}
|
||||||
</button>
|
</button>
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
@@ -502,7 +502,7 @@ export default {
|
|||||||
toDetail(id) {
|
toDetail(id) {
|
||||||
if (this.isFuture) {
|
if (this.isFuture) {
|
||||||
this.$util.showToast({
|
this.$util.showToast({
|
||||||
title: '秒杀活动即将开启,敬请期待!'
|
title: this.$lang('components-diy.diy-seckill.seckillComingSoonTip')
|
||||||
});
|
});
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -796,12 +796,16 @@ scroll-view ::-webkit-scrollbar {
|
|||||||
height: 20rpx;
|
height: 20rpx;
|
||||||
border-radius: 20rpx;
|
border-radius: 20rpx;
|
||||||
margin-right: 20rpx;
|
margin-right: 20rpx;
|
||||||
background-color: #fcecd7;
|
// P0: 秒杀价签浅底 → var(--seckill-price-shallow)
|
||||||
|
// 兼容: 微信小程序 / 鸿蒙元服务 — background-color 接受 var() 无问题
|
||||||
|
background-color: var(--seckill-price-shallow, #fcecd7);
|
||||||
|
|
||||||
.curr {
|
.curr {
|
||||||
height: 20rpx;
|
height: 20rpx;
|
||||||
border-radius: 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 {
|
.content .progress {
|
||||||
.num {
|
.num {
|
||||||
color: #ff3d3d;
|
// P0: 秒杀进度数字红 → var(--seckill-promo-color)
|
||||||
|
// 兼容: 微信小程序 / 鸿蒙元服务 — color 接受 var() 无问题
|
||||||
|
color: var(--seckill-promo-color, #ff3d3d);
|
||||||
}
|
}
|
||||||
|
|
||||||
.bg {
|
.bg {
|
||||||
background-color: #ffd5d5;
|
// P0: 秒杀进度浅底 → var(--seckill-price-shallow) 复用
|
||||||
|
// 兼容: 微信小程序 / 鸿蒙元服务 — background-color 接受 var() 无问题
|
||||||
|
background-color: var(--seckill-price-shallow, #ffd5d5);
|
||||||
|
|
||||||
.curr {
|
.curr {
|
||||||
position: relative;
|
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;
|
white-space: nowrap;
|
||||||
font-weight: bold;
|
font-weight: bold;
|
||||||
line-height: 1;
|
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;
|
padding: 4rpx 4rpx 4rpx 10rpx;
|
||||||
border-top-right-radius: 10rpx;
|
border-top-right-radius: 10rpx;
|
||||||
border-bottom-right-radius: 10rpx;
|
border-bottom-right-radius: 10rpx;
|
||||||
|
|||||||
@@ -7,17 +7,17 @@
|
|||||||
<block v-if="globalStoreInfo && globalStoreInfo.store_id">
|
<block v-if="globalStoreInfo && globalStoreInfo.store_id">
|
||||||
<text class="title">{{ globalStoreInfo.store_name }}</text>
|
<text class="title">{{ globalStoreInfo.store_name }}</text>
|
||||||
<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 class="iconfont icon-right"></text>
|
||||||
</text>
|
</text>
|
||||||
</block>
|
</block>
|
||||||
<text class="title" v-else>定位中...</text>
|
<text class="title" v-else>{{ $lang('components-diy.diy-store.locating') }}</text>
|
||||||
</view>
|
</view>
|
||||||
<view class="address-wrap" :style="{ color: value.textColor }">
|
<view class="address-wrap" :style="{ color: value.textColor }">
|
||||||
<text class="iconfont icon-dizhi"></text>
|
<text class="iconfont icon-dizhi"></text>
|
||||||
<text v-if="globalStoreInfo && globalStoreInfo.store_id" @tap.stop="mapRoute" class="address">{{
|
<text v-if="globalStoreInfo && globalStoreInfo.store_id" @tap.stop="mapRoute" class="address">{{
|
||||||
globalStoreInfo.show_address }}</text>
|
globalStoreInfo.show_address }}</text>
|
||||||
<text v-else>获取当前位置...</text>
|
<text v-else>{{ $lang('components-diy.diy-store.gettingLocation') }}</text>
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
<view class="store-image" @tap.stop="selectStore()">
|
<view class="store-image" @tap.stop="selectStore()">
|
||||||
@@ -40,11 +40,11 @@
|
|||||||
<block v-if="globalStoreInfo && globalStoreInfo.store_id">
|
<block v-if="globalStoreInfo && globalStoreInfo.store_id">
|
||||||
<text class="title">{{ globalStoreInfo.store_name }}</text>
|
<text class="title">{{ globalStoreInfo.store_name }}</text>
|
||||||
<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 class="iconfont icon-right"></text>
|
||||||
</text>
|
</text>
|
||||||
</block>
|
</block>
|
||||||
<text class="title" v-else>定位中...</text>
|
<text class="title" v-else>{{ $lang('components-diy.diy-store.locating') }}</text>
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
<view class="store-icon" @tap.stop="search()"><text class="iconfont icon-sousuo3"
|
<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="title" :style="{ color: value.textColor }">{{ globalStoreInfo.store_name }}</text>
|
||||||
<text class="iconfont icon-unfold" :style="{ color: value.textColor }"></text>
|
<text class="iconfont icon-unfold" :style="{ color: value.textColor }"></text>
|
||||||
</block>
|
</block>
|
||||||
<text class="title" v-else>定位中...</text>
|
<text class="title" v-else>{{ $lang('components-diy.diy-store.locating') }}</text>
|
||||||
</view>
|
</view>
|
||||||
<view class="store-right-search">
|
<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()" />
|
@tap.stop="search()" />
|
||||||
<text class="iconfont icon-sousuo3" @tap.stop="search()"></text>
|
<text class="iconfont icon-sousuo3" @tap.stop="search()"></text>
|
||||||
</view>
|
</view>
|
||||||
|
|||||||
@@ -903,8 +903,8 @@ export default {
|
|||||||
|
|
||||||
// 如果 title 是字符串,保持原有逻辑
|
// 如果 title 是字符串,保持原有逻辑
|
||||||
if (typeof title === 'string' && title.includes('.')) {
|
if (typeof title === 'string' && title.includes('.')) {
|
||||||
// 包含点号的标题视为国际化键,使用全局挂载的 $lang 方法翻译
|
// 包含点号的标题视为国际化键,使用全局挂载的 $lang 方法翻译;缺失时回退 title 本身
|
||||||
return this.$lang ? this.$lang(title) : title;
|
return this.$lang ? this.$lang(title, title) : title;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 不包含点号的标题直接返回
|
// 不包含点号的标题直接返回
|
||||||
|
|||||||
@@ -208,7 +208,7 @@
|
|||||||
{{ value.text }}
|
{{ value.text }}
|
||||||
</text>
|
</text>
|
||||||
<text class="zone"
|
<text class="zone"
|
||||||
:style="{ fontSize: value.fontSize * 2 + 'rpx', fontWeight: value.fontWeight }">专区</text>
|
:style="{ fontSize: value.fontSize * 2 + 'rpx', fontWeight: value.fontWeight }">{{ $lang('components-diy.diy-text.zone') }}</text>
|
||||||
</view>
|
</view>
|
||||||
<text class="iconfont icon-danxuan-xuanzhong"
|
<text class="iconfont icon-danxuan-xuanzhong"
|
||||||
:style="{ color: value.textColor, fontWeight: value.fontWeight }"></text>
|
:style="{ color: value.textColor, fontWeight: value.fontWeight }"></text>
|
||||||
|
|||||||
@@ -64,7 +64,9 @@
|
|||||||
id="myVideo"
|
id="myVideo"
|
||||||
:src="video_url"
|
:src="video_url"
|
||||||
:controls="true"
|
:controls="true"
|
||||||
|
object-fit="contain"
|
||||||
@loadedmetadata="onPopupVideoLoaded"
|
@loadedmetadata="onPopupVideoLoaded"
|
||||||
|
@error="onPopupVideoError"
|
||||||
></video>
|
></video>
|
||||||
</view>
|
</view>
|
||||||
</uni-popup>
|
</uni-popup>
|
||||||
@@ -88,11 +90,14 @@ export default {
|
|||||||
pageWidth: '',
|
pageWidth: '',
|
||||||
indicatorDots: false,
|
indicatorDots: false,
|
||||||
swiperCurrent: 0,
|
swiperCurrent: 0,
|
||||||
video_url: ''
|
video_url: '',
|
||||||
|
popupVideoWidth: 0,
|
||||||
|
popupVideoHeight: 0,
|
||||||
|
windowWidth: 0
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
created() {
|
created() {
|
||||||
// 组件创建时的逻辑
|
this.initWindowWidth();
|
||||||
},
|
},
|
||||||
watch: {
|
watch: {
|
||||||
componentRefresh(newValue) {
|
componentRefresh(newValue) {
|
||||||
@@ -140,24 +145,33 @@ export default {
|
|||||||
// 弹窗视频容器样式
|
// 弹窗视频容器样式
|
||||||
popupVideoStyle() {
|
popupVideoStyle() {
|
||||||
let style = 'position:fixed;width:100%;left:0;';
|
let style = 'position:fixed;width:100%;left:0;';
|
||||||
|
const defaultRatio = 9 / 16;
|
||||||
|
|
||||||
if (this.popupVideoRatio) {
|
let ratio = defaultRatio;
|
||||||
// 根据视频比例设置位置
|
if (this.popupVideoWidth && this.popupVideoHeight) {
|
||||||
if (this.popupVideoRatio === 'portrait') {
|
ratio = this.popupVideoHeight / this.popupVideoWidth;
|
||||||
// 竖屏视频:居中显示,使用9/16比例
|
|
||||||
style += 'top:50%;transform:translateY(-50%);';
|
|
||||||
style += 'aspect-ratio: 9 / 16;';
|
|
||||||
} else {
|
|
||||||
// 横屏视频:靠近顶部显示,使用16/9比例
|
|
||||||
style += 'top:20%;';
|
|
||||||
style += 'aspect-ratio: 16 / 9;';
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// 默认:居中显示,使用竖屏比例
|
|
||||||
style += 'top:50%;transform:translateY(-50%);';
|
|
||||||
style += 'aspect-ratio: 9 / 16;';
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const isPortrait = ratio > 1;
|
||||||
|
|
||||||
|
if (isPortrait) {
|
||||||
|
style += 'top:50%;transform:translateY(-50%);';
|
||||||
|
} else {
|
||||||
|
style += 'top:20%;';
|
||||||
|
}
|
||||||
|
|
||||||
|
// #ifdef H5
|
||||||
|
style += 'padding-top: ' + (ratio * 100) + '%;';
|
||||||
|
// #endif
|
||||||
|
|
||||||
|
// #ifdef MP-WEIXIN
|
||||||
|
style += 'padding-top: ' + (ratio * 100) + '%;';
|
||||||
|
// #endif
|
||||||
|
|
||||||
|
// #ifdef MP-HARMONY
|
||||||
|
style += 'height: ' + (this.windowWidth * ratio) + 'px;';
|
||||||
|
// #endif
|
||||||
|
|
||||||
return style;
|
return style;
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -165,8 +179,8 @@ export default {
|
|||||||
// 显示视频播放弹窗
|
// 显示视频播放弹窗
|
||||||
showVideo(item) {
|
showVideo(item) {
|
||||||
this.video_url = item.videoUrl;
|
this.video_url = item.videoUrl;
|
||||||
// 重置视频比例为null,等待新的检测结果
|
this.popupVideoWidth = 0;
|
||||||
this.popupVideoRatio = null;
|
this.popupVideoHeight = 0;
|
||||||
this.$refs.videoPopup.open();
|
this.$refs.videoPopup.open();
|
||||||
},
|
},
|
||||||
|
|
||||||
@@ -175,6 +189,16 @@ export default {
|
|||||||
// 图片加载失败的处理逻辑
|
// 图片加载失败的处理逻辑
|
||||||
},
|
},
|
||||||
|
|
||||||
|
// 初始化窗口宽度
|
||||||
|
initWindowWidth() {
|
||||||
|
try {
|
||||||
|
const systemInfo = uni.getSystemInfoSync();
|
||||||
|
this.windowWidth = systemInfo.windowWidth || 375;
|
||||||
|
} catch (e) {
|
||||||
|
this.windowWidth = 375;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
// 弹窗视频加载完成事件
|
// 弹窗视频加载完成事件
|
||||||
onPopupVideoLoaded(event) {
|
onPopupVideoLoaded(event) {
|
||||||
this.$nextTick(() => {
|
this.$nextTick(() => {
|
||||||
@@ -198,13 +222,24 @@ export default {
|
|||||||
}
|
}
|
||||||
// #endif
|
// #endif
|
||||||
|
|
||||||
|
// 鸿蒙元服务端:通过事件对象获取视频宽高
|
||||||
|
// #ifdef MP-HARMONY
|
||||||
|
if (event && event.detail) {
|
||||||
|
width = event.detail.width || 0;
|
||||||
|
height = event.detail.height || 0;
|
||||||
|
}
|
||||||
|
// #endif
|
||||||
|
|
||||||
if (width && height) {
|
if (width && height) {
|
||||||
this.popupVideoRatio = width >= height ? 'landscape' : 'portrait';
|
this.popupVideoWidth = width;
|
||||||
} else {
|
this.popupVideoHeight = height;
|
||||||
// 获取失败,默认竖屏
|
|
||||||
this.popupVideoRatio = 'portrait';
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
},
|
||||||
|
|
||||||
|
// 弹窗视频错误事件
|
||||||
|
onPopupVideoError(event) {
|
||||||
|
console.error('Popup video load failed:', event);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -576,8 +611,9 @@ export default {
|
|||||||
|
|
||||||
.video-container {
|
.video-container {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
height: 300px;
|
|
||||||
position: relative;
|
position: relative;
|
||||||
|
overflow: hidden;
|
||||||
|
background-color: #000;
|
||||||
}
|
}
|
||||||
|
|
||||||
.adaptive-video {
|
.adaptive-video {
|
||||||
@@ -589,6 +625,22 @@ export default {
|
|||||||
left: 0;
|
left: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* #ifdef MP-WEIXIN */
|
||||||
|
.adaptive-video {
|
||||||
|
position: absolute;
|
||||||
|
top: 0;
|
||||||
|
left: 0;
|
||||||
|
}
|
||||||
|
/* #endif */
|
||||||
|
|
||||||
|
/* #ifdef MP-HARMONY */
|
||||||
|
.adaptive-video {
|
||||||
|
position: static;
|
||||||
|
display: block;
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
/* #endif */
|
||||||
|
|
||||||
.video-nav {
|
.video-nav {
|
||||||
padding: 16rpx;
|
padding: 16rpx;
|
||||||
box-sizing: border-box;
|
box-sizing: border-box;
|
||||||
|
|||||||
@@ -26,6 +26,23 @@
|
|||||||
:poster="posterUrl"
|
:poster="posterUrl"
|
||||||
:style="videoWarpCss"
|
:style="videoWarpCss"
|
||||||
controls
|
controls
|
||||||
|
object-fit="cover"
|
||||||
|
@loadedmetadata="onVideoLoaded"
|
||||||
|
@error="onVideoError"
|
||||||
|
></video>
|
||||||
|
<!-- #endif -->
|
||||||
|
|
||||||
|
<!-- 鸿蒙元服务端使用uni-app的video组件 -->
|
||||||
|
<!-- #ifdef MP-HARMONY -->
|
||||||
|
<video
|
||||||
|
ref="videoRef"
|
||||||
|
data-component-name="diy-video"
|
||||||
|
class="diy-video harmony-video"
|
||||||
|
:src="videoUrl"
|
||||||
|
:poster="posterUrl"
|
||||||
|
:style="videoWarpCss"
|
||||||
|
controls
|
||||||
|
object-fit="cover"
|
||||||
@loadedmetadata="onVideoLoaded"
|
@loadedmetadata="onVideoLoaded"
|
||||||
@error="onVideoError"
|
@error="onVideoError"
|
||||||
></video>
|
></video>
|
||||||
@@ -44,14 +61,17 @@ export default {
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
data() {
|
data() {
|
||||||
return {
|
return {
|
||||||
videoRatio: null, // 视频比例:'landscape'(横屏)或 'portrait'(竖屏)
|
videoWidth: 0,
|
||||||
videoUrl: '',
|
videoHeight: 0,
|
||||||
posterUrl: ''
|
videoUrl: '',
|
||||||
};
|
posterUrl: '',
|
||||||
},
|
windowWidth: 0
|
||||||
|
};
|
||||||
|
},
|
||||||
created() {
|
created() {
|
||||||
this.initVideoData();
|
this.initVideoData();
|
||||||
|
this.initWindowWidth();
|
||||||
},
|
},
|
||||||
mixins: [DiyMinx],
|
mixins: [DiyMinx],
|
||||||
watch: {
|
watch: {
|
||||||
@@ -78,18 +98,26 @@ export default {
|
|||||||
// 动态计算容器比例
|
// 动态计算容器比例
|
||||||
containerStyle() {
|
containerStyle() {
|
||||||
let style = '';
|
let style = '';
|
||||||
|
const defaultRatio = 9 / 16;
|
||||||
|
|
||||||
if (this.videoRatio === 'landscape') {
|
let ratio = defaultRatio;
|
||||||
// 横屏视频:16/9比例
|
if (this.videoWidth && this.videoHeight) {
|
||||||
style += 'aspect-ratio: 16 / 9;';
|
ratio = this.videoHeight / this.videoWidth;
|
||||||
} else if (this.videoRatio === 'portrait') {
|
|
||||||
// 竖屏视频:9/16比例
|
|
||||||
style += 'aspect-ratio: 9 / 16;';
|
|
||||||
} else {
|
|
||||||
// 未加载完成 → 默认使用竖屏比例
|
|
||||||
style += 'aspect-ratio: 9 / 16;';
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// #ifdef H5
|
||||||
|
style += 'padding-top: ' + (ratio * 100) + '%;';
|
||||||
|
// #endif
|
||||||
|
|
||||||
|
// #ifdef MP-WEIXIN
|
||||||
|
style += 'padding-top: ' + (ratio * 100) + '%;';
|
||||||
|
// #endif
|
||||||
|
|
||||||
|
// #ifdef MP-HARMONY
|
||||||
|
style += 'width: 100%;';
|
||||||
|
style += 'height: ' + (this.windowWidth * ratio) + 'px;';
|
||||||
|
// #endif
|
||||||
|
|
||||||
return style;
|
return style;
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -104,6 +132,16 @@ export default {
|
|||||||
// #endif
|
// #endif
|
||||||
},
|
},
|
||||||
|
|
||||||
|
// 初始化窗口宽度
|
||||||
|
initWindowWidth() {
|
||||||
|
try {
|
||||||
|
const systemInfo = uni.getSystemInfoSync();
|
||||||
|
this.windowWidth = systemInfo.windowWidth || 375;
|
||||||
|
} catch (e) {
|
||||||
|
this.windowWidth = 375;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
// 获取视频URL
|
// 获取视频URL
|
||||||
getVideoUrl() {
|
getVideoUrl() {
|
||||||
if (!this.value || !this.value.videoUrl) return '';
|
if (!this.value || !this.value.videoUrl) return '';
|
||||||
@@ -138,12 +176,13 @@ export default {
|
|||||||
const height = video.videoHeight;
|
const height = video.videoHeight;
|
||||||
|
|
||||||
if (width && height) {
|
if (width && height) {
|
||||||
this.videoRatio = width >= height ? 'landscape' : 'portrait';
|
this.videoWidth = width;
|
||||||
|
this.videoHeight = height;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
video.addEventListener('error', (e) => {
|
video.addEventListener('error', (e) => {
|
||||||
console.error('H5端预加载视频失败:', e);
|
console.error(this.$lang('components-diy.diy-video.h5PreloadFailed') + ':', e);
|
||||||
});
|
});
|
||||||
|
|
||||||
// 触发加载
|
// 触发加载
|
||||||
@@ -169,8 +208,16 @@ export default {
|
|||||||
}
|
}
|
||||||
// #endif
|
// #endif
|
||||||
|
|
||||||
|
// #ifdef MP-HARMONY
|
||||||
|
if (event && event.detail) {
|
||||||
|
width = event.detail.width || 0;
|
||||||
|
height = event.detail.height || 0;
|
||||||
|
}
|
||||||
|
// #endif
|
||||||
|
|
||||||
if (width && height) {
|
if (width && height) {
|
||||||
this.videoRatio = width >= height ? 'landscape' : 'portrait';
|
this.videoWidth = width;
|
||||||
|
this.videoHeight = height;
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
@@ -184,7 +231,7 @@ export default {
|
|||||||
|
|
||||||
// 视频错误事件
|
// 视频错误事件
|
||||||
onVideoError(event) {
|
onVideoError(event) {
|
||||||
console.error('视频加载失败:', event);
|
console.error(this.$lang('components-diy.diy-video.videoLoadFailed') + ':', event);
|
||||||
},
|
},
|
||||||
|
|
||||||
async handlerClick(videoUrl) {
|
async handlerClick(videoUrl) {
|
||||||
@@ -216,6 +263,11 @@ export default {
|
|||||||
/* H5端样式 */
|
/* H5端样式 */
|
||||||
/* #ifdef H5 */
|
/* #ifdef H5 */
|
||||||
.h5-video {
|
.h5-video {
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
position: absolute;
|
||||||
|
top: 0;
|
||||||
|
left: 0;
|
||||||
object-fit: cover;
|
object-fit: cover;
|
||||||
}
|
}
|
||||||
/* #endif */
|
/* #endif */
|
||||||
@@ -225,6 +277,19 @@ export default {
|
|||||||
.mp-video {
|
.mp-video {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
height: 100%;
|
height: 100%;
|
||||||
|
position: absolute;
|
||||||
|
top: 0;
|
||||||
|
left: 0;
|
||||||
|
}
|
||||||
|
/* #endif */
|
||||||
|
|
||||||
|
/* 鸿蒙元服务端样式 */
|
||||||
|
/* #ifdef MP-HARMONY */
|
||||||
|
.harmony-video {
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
display: block;
|
||||||
|
box-sizing: border-box;
|
||||||
}
|
}
|
||||||
/* #endif */
|
/* #endif */
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import lang from '@/common/js/lang.js';
|
||||||
|
|
||||||
// 微信视频号组件配置
|
// 微信视频号组件配置
|
||||||
export const wechatChannelConfig = {
|
export const wechatChannelConfig = {
|
||||||
// 图标相关
|
// 图标相关
|
||||||
@@ -56,10 +58,10 @@ export const wechatChannelConfig = {
|
|||||||
|
|
||||||
// 错误提示配置
|
// 错误提示配置
|
||||||
error: {
|
error: {
|
||||||
notWechat: '当前环境不是微信小程序',
|
notWechat: 'wechatChannel.notWechat',
|
||||||
lowVersion: '当前微信基础库版本过低,需要 2.19.2 或以上版本',
|
lowVersion: 'wechatChannel.lowVersion',
|
||||||
notSupported: '当前环境不支持微信视频号',
|
notSupported: 'wechatChannel.notSupported',
|
||||||
missingFields: '缺少必要字段: {field}',
|
missingFields: 'wechatChannel.missingFields',
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -108,7 +110,7 @@ export const wechatChannelUtil = {
|
|||||||
const requiredFields = ['feedId', 'finderUserName'];
|
const requiredFields = ['feedId', 'finderUserName'];
|
||||||
for (const field of requiredFields) {
|
for (const field of requiredFields) {
|
||||||
if (!item[field]) {
|
if (!item[field]) {
|
||||||
throw new Error(`缺少必要字段: ${field}`);
|
throw new Error(lang.lang(wechatChannelConfig.error.missingFields, { field }));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
@@ -128,7 +130,7 @@ export const wechatChannelUtil = {
|
|||||||
|
|
||||||
// 检查微信环境
|
// 检查微信环境
|
||||||
if (typeof wx === 'undefined') {
|
if (typeof wx === 'undefined') {
|
||||||
const err = new Error(wechatChannelConfig.error.notWechat);
|
const err = new Error(lang.lang(wechatChannelConfig.error.notWechat));
|
||||||
this.handleError(err, item);
|
this.handleError(err, item);
|
||||||
reject(err);
|
reject(err);
|
||||||
return;
|
return;
|
||||||
@@ -138,7 +140,7 @@ export const wechatChannelUtil = {
|
|||||||
const systemInfo = wx.getSystemInfoSync();
|
const systemInfo = wx.getSystemInfoSync();
|
||||||
const SDKVersion = systemInfo.SDKVersion;
|
const SDKVersion = systemInfo.SDKVersion;
|
||||||
if (this.versionCompare(SDKVersion, wechatChannelConfig.wechat.minSdkVersion) < 0) {
|
if (this.versionCompare(SDKVersion, wechatChannelConfig.wechat.minSdkVersion) < 0) {
|
||||||
const err = new Error(wechatChannelConfig.error.lowVersion);
|
const err = new Error(lang.lang(wechatChannelConfig.error.lowVersion));
|
||||||
this.handleError(err, item);
|
this.handleError(err, item);
|
||||||
reject(err);
|
reject(err);
|
||||||
return;
|
return;
|
||||||
@@ -158,7 +160,7 @@ export const wechatChannelUtil = {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
const err = new Error(wechatChannelConfig.error.notSupported);
|
const err = new Error(lang.lang(wechatChannelConfig.error.notSupported));
|
||||||
this.handleError(err, item);
|
this.handleError(err, item);
|
||||||
reject(err);
|
reject(err);
|
||||||
}
|
}
|
||||||
@@ -168,7 +170,7 @@ export const wechatChannelUtil = {
|
|||||||
// 统一错误处理
|
// 统一错误处理
|
||||||
handleError(err, item) {
|
handleError(err, item) {
|
||||||
console.error('微信视频号错误:', err);
|
console.error('微信视频号错误:', err);
|
||||||
const { message = '', errMsg = '微信视频播放失败!', errCode = -1 } = err;
|
const { message = '', errMsg = lang.lang('wechatChannel.playFailed'), errCode = -1 } = err;
|
||||||
|
|
||||||
// 错误码5: 表示用户点击了取消. openChannelsActivity:fail cancel
|
// 错误码5: 表示用户点击了取消. openChannelsActivity:fail cancel
|
||||||
if ([5].includes(errCode)) {
|
if ([5].includes(errCode)) {
|
||||||
|
|||||||
4
components-diy/placeholder/index.json
Normal file
4
components-diy/placeholder/index.json
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
{
|
||||||
|
"navigationBarTitleText": "",
|
||||||
|
"usingComponents": {}
|
||||||
|
}
|
||||||
21
components-diy/placeholder/index.vue
Normal file
21
components-diy/placeholder/index.vue
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
<template>
|
||||||
|
<!-- DIY 占位页(不可达,仅用于让 components-diy 成为微信真分包) -->
|
||||||
|
<view class="placeholder"></view>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
export default {
|
||||||
|
data() {
|
||||||
|
return {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.placeholder {
|
||||||
|
padding: 40rpx;
|
||||||
|
color: #999;
|
||||||
|
text-align: center;
|
||||||
|
font-size: 24rpx;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -57,10 +57,10 @@
|
|||||||
<view v-else-if="message.contentType == 'order'"><ns-chat-order :isCanSend="false" :orderId="message.order_id"></ns-chat-order></view>
|
<view v-else-if="message.contentType == 'order'"><ns-chat-order :isCanSend="false" :orderId="message.order_id"></ns-chat-order></view>
|
||||||
|
|
||||||
<view class="no-connect-box" v-if="message.contentType == 'noline'">
|
<view class="no-connect-box" v-if="message.contentType == 'noline'">
|
||||||
<view class="no-connect">客服不在线</view>
|
<view class="no-connect">{{ $lang('components.chat-message.customerOffline') }}</view>
|
||||||
</view>
|
</view>
|
||||||
<view class="no-connect-box" v-if="message.contentType == 'online'">
|
<view class="no-connect-box" v-if="message.contentType == 'online'">
|
||||||
<view class="no-connect">客服在线</view>
|
<view class="no-connect">{{ $lang('components.chat-message.customerOnline') }}</view>
|
||||||
</view>
|
</view>
|
||||||
<uni-popup ref="imgPopup" type="center">
|
<uni-popup ref="imgPopup" type="center">
|
||||||
<view class="imagePop">
|
<view class="imagePop">
|
||||||
|
|||||||
@@ -1,22 +1,28 @@
|
|||||||
<template>
|
<template>
|
||||||
|
<!-- Vue 2 / uni-app 单根约束:用 view 包一层 -->
|
||||||
|
<view>
|
||||||
<view v-if="pageCount === 1 || need" class="fixed-box"
|
<view v-if="pageCount === 1 || need" class="fixed-box"
|
||||||
:style="[customContainerStyle, {
|
:style="[customContainerStyle, {
|
||||||
height: containerHeight,
|
height: containerHeight,
|
||||||
|
bottom: containerBottom,
|
||||||
|
right: containerRight,
|
||||||
backgroundImage: bgUrl ? `url(${bgUrl})` : '',
|
backgroundImage: bgUrl ? `url(${bgUrl})` : '',
|
||||||
backgroundSize: 'cover'
|
backgroundSize: 'cover'
|
||||||
}]">
|
}]">
|
||||||
<!-- 中英文切换按钮 -->
|
<!-- 多语言切换按钮:根据语言数智能切换交互 -->
|
||||||
<view
|
<view
|
||||||
v-if="isLanguageSwitchEnabled && fixBtnShow"
|
v-if="isLanguageSwitchEnabled && fixBtnShow"
|
||||||
class="btn-item common-bg"
|
class="btn-item common-bg"
|
||||||
@click="toggleLanguage"
|
:style="btnItemStyle"
|
||||||
|
@click="handleLangButtonClick"
|
||||||
>
|
>
|
||||||
<text>{{ currentLangDisplayName }}</text>
|
<view class="lang-btn-text">{{ currentLangDisplayName }}</view>
|
||||||
</view>
|
</view>
|
||||||
<!-- 微信官方客服按钮-->
|
<!-- 微信官方客服按钮-->
|
||||||
<button
|
<button
|
||||||
v-if="fixBtnShow && hasValidKefuConfig && isWeappOfficialKefu"
|
v-if="fixBtnShow && hasValidKefuConfig && isWeappOfficialKefu"
|
||||||
class="btn-item common-bg"
|
class="btn-item common-bg"
|
||||||
|
:style="btnItemStyle"
|
||||||
open-type="contact"
|
open-type="contact"
|
||||||
>
|
>
|
||||||
<text class="icox icox-kefu" v-if="!kefuimg"></text>
|
<text class="icox icox-kefu" v-if="!kefuimg"></text>
|
||||||
@@ -26,6 +32,7 @@
|
|||||||
<view
|
<view
|
||||||
v-if="fixBtnShow && hasValidKefuConfig && !isWeappOfficialKefu && !showWeappSystemKefu"
|
v-if="fixBtnShow && hasValidKefuConfig && !isWeappOfficialKefu && !showWeappSystemKefu"
|
||||||
class="btn-item common-bg"
|
class="btn-item common-bg"
|
||||||
|
:style="btnItemStyle"
|
||||||
@click="handleUnifiedKefuClick"
|
@click="handleUnifiedKefuClick"
|
||||||
>
|
>
|
||||||
<image
|
<image
|
||||||
@@ -43,6 +50,7 @@
|
|||||||
<view
|
<view
|
||||||
v-if="fixBtnShow && hasValidKefuConfig && !isWeappOfficialKefu && showWeappSystemKefu"
|
v-if="fixBtnShow && hasValidKefuConfig && !isWeappOfficialKefu && showWeappSystemKefu"
|
||||||
class="btn-item common-bg"
|
class="btn-item common-bg"
|
||||||
|
:style="btnItemStyle"
|
||||||
@click="handleUnifiedKefuClick"
|
@click="handleUnifiedKefuClick"
|
||||||
>
|
>
|
||||||
<image
|
<image
|
||||||
@@ -60,31 +68,102 @@
|
|||||||
<button
|
<button
|
||||||
v-if="fixBtnShow && hasValidKefuConfig && showWeappSystemKefu"
|
v-if="fixBtnShow && hasValidKefuConfig && showWeappSystemKefu"
|
||||||
class="btn-item common-bg"
|
class="btn-item common-bg"
|
||||||
|
:style="btnItemStyle"
|
||||||
open-type="contact"
|
open-type="contact"
|
||||||
>
|
>
|
||||||
<text class="icox icox-kefu" v-if="!kefuimg"></text>
|
<text class="icox icox-kefu" v-if="!kefuimg"></text>
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
<!-- 电话按钮 -->
|
<!-- 电话按钮 -->
|
||||||
<view
|
<view
|
||||||
v-if="fixBtnShow"
|
v-if="fixBtnShow"
|
||||||
class="btn-item common-bg"
|
class="btn-item common-bg"
|
||||||
|
:style="[btnItemStyle, { backgroundImage: phoneimg ? `url(${phoneimg})` : '', backgroundSize: '100% 100%' }, customButtonStyle]"
|
||||||
@click="call"
|
@click="call"
|
||||||
:style="[{ backgroundImage: phoneimg ? `url(${phoneimg})` : '', backgroundSize: '100% 100%' }, customButtonStyle]"
|
|
||||||
>
|
>
|
||||||
<text class="iconfont icon-dianhua" v-if="!phoneimg"></text>
|
<text class="iconfont icon-dianhua" v-if="!phoneimg"></text>
|
||||||
</view>
|
</view>
|
||||||
|
|
||||||
</view>
|
</view>
|
||||||
|
|
||||||
|
<!-- 语言选择弹窗(底部弹出) -->
|
||||||
|
<view v-if="showLangPopup" class="lang-mask" @click="closeLangPicker">
|
||||||
|
<view class="lang-panel" @click.stop>
|
||||||
|
<view class="lang-panel-title">{{ i18n.langPickerTitle }}</view>
|
||||||
|
<view
|
||||||
|
v-for="(item, idx) in langList"
|
||||||
|
:key="item.value"
|
||||||
|
class="lang-item"
|
||||||
|
:class="{ 'lang-item-active': idx === currentLangIndex }"
|
||||||
|
@click="selectLanguage(idx)"
|
||||||
|
>
|
||||||
|
<text class="lang-item-name">{{ item.name }}</text>
|
||||||
|
<text v-if="idx === currentLangIndex" class="lang-item-check">✓</text>
|
||||||
|
</view>
|
||||||
|
<view class="lang-cancel" @click="closeLangPicker">{{ i18n.langPickerCancel }}</view>
|
||||||
|
</view>
|
||||||
|
</view>
|
||||||
|
</view>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
import { createCustomerService } from '@/common/js/customer-service.js';
|
import { createCustomerService } from '@/common/js/customer-service.js';
|
||||||
|
import i18nLazyMixin from '@/common/mixin/i18n-lazy.js';
|
||||||
|
|
||||||
|
// 语言短码映射表(currentLangDisplayName 展示用,可按需扩展)
|
||||||
|
// key: 语言 value,value: 显示短码(按钮上展示)
|
||||||
|
const LANG_DISPLAY_NAMES = {
|
||||||
|
'zh-cn': 'CN',
|
||||||
|
'zh-tw': 'TW',
|
||||||
|
'zh-hk': 'HK',
|
||||||
|
'en-us': 'EN',
|
||||||
|
'en-gb': 'EN',
|
||||||
|
'ja-jp': 'JP',
|
||||||
|
'ko-kr': 'KR',
|
||||||
|
'fr-fr': 'FR',
|
||||||
|
'de-de': 'DE',
|
||||||
|
'es-es': 'ES',
|
||||||
|
'ru-ru': 'RU',
|
||||||
|
'th-th': 'TH',
|
||||||
|
'vi-vn': 'VN',
|
||||||
|
'id-id': 'ID',
|
||||||
|
'ar-ae': 'AR',
|
||||||
|
'pt-pt': 'PT',
|
||||||
|
'ms-my': 'MY',
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 把语言 value(如 'en-us')转成展示短码(如 'EN')
|
||||||
|
* 1) 优先精确匹配 customMap(后端下发,可覆盖默认值)
|
||||||
|
* 2) 再回退到 LANG_DISPLAY_NAMES(前端默认)
|
||||||
|
* 3) 前缀匹配(后端 value 写了 'en' 而不是 'en-us' 也能匹配)
|
||||||
|
* 4) 兜底返回大写前缀
|
||||||
|
*
|
||||||
|
* @param {String} langValue 语言 value
|
||||||
|
* @param {Object} [customMap] 后端下发的覆盖映射(优先级最高)
|
||||||
|
*/
|
||||||
|
function getLangShortCode(langValue, customMap) {
|
||||||
|
if (!langValue) return '';
|
||||||
|
// 1) 后端覆盖 > 2) 默认映射
|
||||||
|
if (customMap && customMap[langValue]) return customMap[langValue];
|
||||||
|
if (LANG_DISPLAY_NAMES[langValue]) return LANG_DISPLAY_NAMES[langValue];
|
||||||
|
// 3) 前缀匹配:先后端,再默认
|
||||||
|
const prefix = String(langValue).split('-')[0].toLowerCase();
|
||||||
|
if (customMap) {
|
||||||
|
for (const key of Object.keys(customMap)) {
|
||||||
|
if (key.startsWith(prefix + '-')) return customMap[key];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const key of Object.keys(LANG_DISPLAY_NAMES)) {
|
||||||
|
if (key.startsWith(prefix + '-')) return LANG_DISPLAY_NAMES[key];
|
||||||
|
}
|
||||||
|
// 4) 兜底
|
||||||
|
return prefix.toUpperCase();
|
||||||
|
}
|
||||||
|
|
||||||
export default {
|
export default {
|
||||||
name: 'hover-nav',
|
name: 'hover-nav',
|
||||||
|
mixins: [i18nLazyMixin],
|
||||||
props: {
|
props: {
|
||||||
need: { type: Boolean, default: false }
|
need: { type: Boolean, default: false }
|
||||||
},
|
},
|
||||||
@@ -95,7 +174,28 @@ export default {
|
|||||||
shopInfo: null,
|
shopInfo: null,
|
||||||
currentLangIndex: 0,
|
currentLangIndex: 0,
|
||||||
langIndexMap: {},
|
langIndexMap: {},
|
||||||
|
langList: [],
|
||||||
|
langDisplayMap: { ...LANG_DISPLAY_NAMES }, // 后端 langDisplayNames 会覆盖默认值
|
||||||
|
showLangPopup: false, // 语言选择弹窗显隐
|
||||||
customerService: null,
|
customerService: null,
|
||||||
|
// ============================================================
|
||||||
|
// 布局参数(从 App.vue 的 :root CSS 变量读取,权威源在 App.vue)
|
||||||
|
// 关键设计:
|
||||||
|
// 1) data 中给 fallback 默认值(46/72/272/100),保证小程序/未挂载时也能用
|
||||||
|
// 2) H5 下 mounted() 中从 getComputedStyle 读 :root 上的 CSS 变量覆盖,
|
||||||
|
// 这样改 App.vue 的 CSS 变量,JS 端会自动跟随(真正的"动态化")
|
||||||
|
// 3) containerRight / containerBottom 公式都基于这 4 个变量
|
||||||
|
// ============================================================
|
||||||
|
layoutTopRight: 46, // --top-btn-right
|
||||||
|
layoutTopBottom: 272, // --top-btn-bottom
|
||||||
|
layoutTopSize: 72, // --top-btn-size(Top 按钮正方形边长)
|
||||||
|
layoutFloatingWidth: 100, // --floating-btn-width
|
||||||
|
// i18n-lazy mixin 要求:data 中预声明 i18n 字段(初值空串),
|
||||||
|
// 模板只读 this.i18n.xxx,真实翻译在 openLangPicker() 中 prepareI18n() 后才填入
|
||||||
|
i18n: {
|
||||||
|
langPickerTitle: '',
|
||||||
|
langPickerCancel: '',
|
||||||
|
},
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
computed: {
|
computed: {
|
||||||
@@ -114,12 +214,22 @@ export default {
|
|||||||
tel() {
|
tel() {
|
||||||
return this.shopInfo?.mobile || '';
|
return this.shopInfo?.mobile || '';
|
||||||
},
|
},
|
||||||
|
// 是否启用语言切换:
|
||||||
|
// 1) 依赖 shopInfo.ischina(后端业务开关)
|
||||||
|
// 2) 且可用语言数 >= 2(只有 1 种语言时不需要切)
|
||||||
isLanguageSwitchEnabled() {
|
isLanguageSwitchEnabled() {
|
||||||
return !!this.shopInfo?.ischina;
|
const info = this.$store && this.$store.state ? (this.$store.state.shopInfo || this.shopInfo) : this.shopInfo;
|
||||||
|
return !!(info && info.ischina) && Array.isArray(this.langList) && this.langList.length >= 2;
|
||||||
},
|
},
|
||||||
|
// 按钮上显示的文案:始终展示当前选中语言的短码
|
||||||
|
// 短码来源:initLanguage 已用合并后的 langDisplayMap 填充到 langList[i].name,
|
||||||
|
// 优先用后端 langDisplayNames,否则用前端 LANG_DISPLAY_NAMES
|
||||||
currentLangDisplayName() {
|
currentLangDisplayName() {
|
||||||
const lang = this.langIndexMap[this.currentLangIndex];
|
const list = this.langList;
|
||||||
return lang === 'zh-cn' ? 'EN' : 'CN';
|
if (!Array.isArray(list) || list.length === 0) return '';
|
||||||
|
const currentItem = list[this.currentLangIndex];
|
||||||
|
if (!currentItem) return '';
|
||||||
|
return currentItem.name || getLangShortCode(currentItem.value, this.langDisplayMap);
|
||||||
},
|
},
|
||||||
customContainerStyle() {
|
customContainerStyle() {
|
||||||
return this.shopInfo?.floatingButton?.container || {};
|
return this.shopInfo?.floatingButton?.container || {};
|
||||||
@@ -127,6 +237,32 @@ export default {
|
|||||||
customButtonStyle() {
|
customButtonStyle() {
|
||||||
return this.shopInfo?.floatingButton?.button || {};
|
return this.shopInfo?.floatingButton?.button || {};
|
||||||
},
|
},
|
||||||
|
// 所有 .btn-item 的 inline-style 兜底:
|
||||||
|
// 1) 测试发现 .btn-item 的 min-*/max-*/aspect-ratio/flex-shrink 等 !important
|
||||||
|
// 规则在 scoped 样式下,被某些 flex 布局的隐式约束吃掉,只 width/height/border-radius
|
||||||
|
// 生效,导致高度被压缩成 39.5px(从 41px),按钮显示为轻微椭圆。
|
||||||
|
// 2) inline-style 优先级高于 CSS class,直接锁死 72x72 + 正圆。
|
||||||
|
// 3) 用 max-width/max-height + flex-shrink 0 三重兜底,防止被任何层级的样式覆盖。
|
||||||
|
btnItemStyle() {
|
||||||
|
return {
|
||||||
|
width: '72rpx',
|
||||||
|
height: '72rpx',
|
||||||
|
'min-width': '72rpx',
|
||||||
|
'min-height': '72rpx',
|
||||||
|
'max-width': '72rpx',
|
||||||
|
'max-height': '72rpx',
|
||||||
|
'aspect-ratio': '1',
|
||||||
|
// border-radius 保留作 clip-path 不支持时的 fallback
|
||||||
|
'border-radius': '50%',
|
||||||
|
'flex-shrink': '0',
|
||||||
|
'flex-grow': '0',
|
||||||
|
'align-self': 'center',
|
||||||
|
'box-sizing': 'border-box',
|
||||||
|
padding: '0',
|
||||||
|
margin: '14rpx 0',
|
||||||
|
overflow: 'hidden',
|
||||||
|
};
|
||||||
|
},
|
||||||
unreadCount() {
|
unreadCount() {
|
||||||
const customerService = createCustomerService(this);
|
const customerService = createCustomerService(this);
|
||||||
return customerService.getUnreadCount();
|
return customerService.getUnreadCount();
|
||||||
@@ -159,7 +295,17 @@ export default {
|
|||||||
const customerService = createCustomerService(this);
|
const customerService = createCustomerService(this);
|
||||||
return customerService.hasValidKefuConfig();
|
return customerService.hasValidKefuConfig();
|
||||||
},
|
},
|
||||||
//根据显示的按钮数量动态计算容器高度
|
|
||||||
|
//根据显示的按钮数量动态计算容器高度
|
||||||
|
// 计算明细(buttonCount 按钮场景):
|
||||||
|
// 每个按钮槽位:72rpx(按钮,与 to-top 一致) + 14rpx(上 margin) + 14rpx(下 margin) = 100rpx
|
||||||
|
// 容器 padding:20rpx 上 + 20rpx 下 = 40rpx
|
||||||
|
// 总高度 (rpx):buttonCount × 100 + 40
|
||||||
|
// 修复:改返回 rpx 而非 px(原 *0.5 硬编码 iPhone 6 375px 转换比),
|
||||||
|
// 在微信小程序/其他设备(iPhone 13 390px、iPad 等)下由 uni-app 框架
|
||||||
|
// 按 windowWidth 动态换算,避免 4+ 按钮时容器偏小导致内容被裁切
|
||||||
|
// 关联:按钮尺寸与 to-top 同步(72rpx),所以槽位高度也是 100rpx;
|
||||||
|
// 之前按钮 80rpx 时槽位 108rpx,改为 72rpx 后槽位缩小 8rpx,容器整体更紧凑
|
||||||
containerHeight() {
|
containerHeight() {
|
||||||
if (!this.fixBtnShow) return '320rpx';
|
if (!this.fixBtnShow) return '320rpx';
|
||||||
|
|
||||||
@@ -167,37 +313,310 @@ export default {
|
|||||||
if (this.isLanguageSwitchEnabled) buttonCount++;
|
if (this.isLanguageSwitchEnabled) buttonCount++;
|
||||||
if (this.showWeappSystemKefu) buttonCount++;
|
if (this.showWeappSystemKefu) buttonCount++;
|
||||||
buttonCount++;
|
buttonCount++;
|
||||||
const totalRpx = 94 * buttonCount - 14;
|
const totalRpx = buttonCount * 100 + 40;
|
||||||
const pxValue = Math.round(totalRpx * 0.5);
|
|
||||||
|
|
||||||
return ` $ {pxValue}px`;
|
return `${totalRpx}rpx`;
|
||||||
}
|
},
|
||||||
|
// 浮动按钮组底部 bottom 动态计算(在 Top 按钮上方):
|
||||||
|
// Top 按钮是 72x72 正方形,顶部边界 = bottom + size = layoutTopBottom + layoutTopSize
|
||||||
|
// containerBottom = Top 顶部边界 + space
|
||||||
|
// ------------------------------------------------------------
|
||||||
|
// space 是经验调优值(非数学推导),手调结果:
|
||||||
|
// H5 : 18 * 5 = 90rpx
|
||||||
|
// MP-WEIXIN: 18 * 1 = 18rpx
|
||||||
|
// 为什么 H5 反而大、微信反而小:
|
||||||
|
// 虽然 rpx 单位定义相同(windowWidth/750),但 Top 按钮
|
||||||
|
// <image mode="widthFix"> 在不同平台渲染有视觉差异。
|
||||||
|
// H5 浏览器(WebKit/Blink)渲染时,图片元素可能保留更多
|
||||||
|
// 内边距/基线,视觉上比 72rpx 大,需要更大间距才不挤;
|
||||||
|
// 微信 Skia 严格按 width=72rpx 渲染,视觉紧凑,
|
||||||
|
// 18rpx 就能有清晰的呼吸感。
|
||||||
|
// 90/18 是按"视觉上不挤"原则手调出来的,反过来都不行。
|
||||||
|
// ------------------------------------------------------------
|
||||||
|
// 注意:安全区 var(--window-bottom) 由 CSS 的 margin-bottom 统一处理,
|
||||||
|
// 与 Top 按钮的 .mescroll-totop { margin-bottom: var(--window-bottom) } 一致,
|
||||||
|
// 两者会被安全区同步上推,space 保持不变
|
||||||
|
containerBottom() {
|
||||||
|
if (!this.fixBtnShow) return '240rpx';
|
||||||
|
let space = 18 * 5;
|
||||||
|
// #ifdef MP-WEIXIN
|
||||||
|
space = 18 * 1;
|
||||||
|
// #endif
|
||||||
|
return `${this.layoutTopBottom + this.layoutTopSize + space}rpx`;
|
||||||
|
},
|
||||||
|
// 浮动按钮组水平 right 动态计算(与 Top 按钮中心对齐):
|
||||||
|
// 公式: containerRight = TopRight + TopSize/2 - FloatingWidth/2
|
||||||
|
// 含义:让浮动容器中心落在 Top 按钮中心上
|
||||||
|
// 浮动中心 = containerRight + FloatingWidth/2
|
||||||
|
// Top 中心 = layoutTopRight + layoutTopSize/2
|
||||||
|
// 两者相等 → 中心对齐
|
||||||
|
// 例(46 + 36 - 50 = 32rpx)
|
||||||
|
// 注意:浮动容器 width(layoutFloatingWidth=100)比 Top(layoutTopSize=72)宽 28rpx,
|
||||||
|
// 无论怎么对齐都会有"左侧突出"现象。当前选 center 对齐,因为:
|
||||||
|
// - center 对齐(32rpx):左侧突出 14rpx,中心 0 错位 ← 当前
|
||||||
|
// - right edge 对齐(46rpx):左侧突出 28rpx,中心错位 14rpx
|
||||||
|
// center 对齐不仅中心精准,突出量也更小
|
||||||
|
containerRight() {
|
||||||
|
if (!this.fixBtnShow) return '0rpx';
|
||||||
|
const offset = this.layoutTopRight + this.layoutTopSize / 2 - this.layoutFloatingWidth / 2;
|
||||||
|
return `${offset}rpx`;
|
||||||
|
},
|
||||||
},
|
},
|
||||||
watch: {
|
watch: {
|
||||||
|
// 监听本地缓存
|
||||||
shopInfo: {
|
shopInfo: {
|
||||||
handler(newVal) {
|
handler(newVal) {
|
||||||
},
|
},
|
||||||
immediate: true
|
immediate: true
|
||||||
|
},
|
||||||
|
// 关键修复:
|
||||||
|
// store/index.js 初始 state 中**没有声明 shopInfo 字段**,
|
||||||
|
// setShopInfo 用的是 state.shopInfo = value 的直接赋值,Vue 2 对"后加属性"非响应式,
|
||||||
|
// 所以 watch('$store.state.shopInfo') / computed 都不会被触发(无效的依赖)。
|
||||||
|
//
|
||||||
|
// 正确做法:监听 initStatus(初始 state 已声明,是响应式的)。
|
||||||
|
// init 流程里 setShopInfo 在 setInitStatus(true) 之前调用,
|
||||||
|
// 所以 initStatus === true 时 shopInfo 一定已就绪。
|
||||||
|
'$store.state.initStatus': {
|
||||||
|
handler(newVal) {
|
||||||
|
if (newVal === true) {
|
||||||
|
const fromStore = this.$store && this.$store.state && this.$store.state.shopInfo;
|
||||||
|
if (fromStore) this.shopInfo = fromStore;
|
||||||
|
// 即便 store.shopInfo 不是响应式(属性后加),storage 是同步可读的,做兜底
|
||||||
|
if (!this.shopInfo) {
|
||||||
|
try {
|
||||||
|
const fromStorage = uni.getStorageSync('shopInfo');
|
||||||
|
if (fromStorage) this.shopInfo = fromStorage;
|
||||||
|
} catch (e) {}
|
||||||
|
}
|
||||||
|
// 关键:shopInfo 就绪后重新初始化 langList,
|
||||||
|
// 让 initLanguage 重新从 shopInfo.langList 读取并重算 currentLangIndex
|
||||||
|
// (created 阶段 shopInfo 可能还没到,那时只能兜底 $langConfig.list())
|
||||||
|
this.initLanguage();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
immediate: true
|
||||||
|
},
|
||||||
|
// 关键修复(全新启动无缓存场景):
|
||||||
|
// 旧逻辑: mounted() 中同步读一次 $store.state.themeColor 写到 this.$el.style.cssText
|
||||||
|
// 但 App.vue 的 boot 是异步的,首屏渲染时主题色还没就绪 → 写入被跳过
|
||||||
|
// 之后主题色就绪,但 hover-nav 不在页面 DOM 树里(已被 Teleport 到 body),
|
||||||
|
// 且**没有任何 watch 监听 themeColor 变化** → cssText 永远不更新
|
||||||
|
// 结果: --hover-nav-bg-color / --hover-nav-text-color 等变量读不到,
|
||||||
|
// 按钮 background-color 退到 transparent,box-shadow 退到 none,
|
||||||
|
// 按钮视觉上"消失"或样式错乱
|
||||||
|
//
|
||||||
|
// 新逻辑:
|
||||||
|
// - 首次启动(无缓存,themeColor 异步就绪): watch 监听 themeColor 变化,
|
||||||
|
// 就绪时注入 cssText
|
||||||
|
// - 刷新(有缓存,themeColor 同步就绪): immediate: true 在 watcher 创建时触发,
|
||||||
|
// 但此时 this.$el 还不存在(_applyThemeColor return),watch 之后再无变化,
|
||||||
|
// 导致 cssText 永远不注入
|
||||||
|
// - 修复: 移除 immediate,改在 mounted() 中 Teleport 完成后手动调一次
|
||||||
|
// _applyThemeColor(currentTc),此时 $el 已就位,同步路径也能正确注入
|
||||||
|
'$store.state.themeColor': {
|
||||||
|
handler(newTc) {
|
||||||
|
this._applyThemeColor(newTc);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
created() {
|
created() {
|
||||||
this.initLanguage();
|
this.initLanguage();
|
||||||
this.pageCount = getCurrentPages().length;
|
this.pageCount = getCurrentPages().length;
|
||||||
uni.getStorage({
|
|
||||||
key: 'shopInfo',
|
// 三源兜底(store / 同步 storage / 异步 storage),
|
||||||
success: (e) => {
|
// 任何一个先就绪就先使用,后续由 initStatus watcher 再次同步
|
||||||
this.shopInfo = e.data;
|
const fromStore = this.$store && this.$store.state && this.$store.state.shopInfo;
|
||||||
},
|
if (fromStore) {
|
||||||
fail: () => {
|
this.shopInfo = fromStore;
|
||||||
console.warn('未获取到 shopInfo,使用默认设置');
|
} else {
|
||||||
|
// initStatus 已为 true 但 store.shopInfo 暂时还是空(极少见,理论上不会发生)
|
||||||
|
// 直接从 storage 兜底
|
||||||
|
if (this.$store && this.$store.state && this.$store.state.initStatus === true) {
|
||||||
|
try {
|
||||||
|
const sync = uni.getStorageSync('shopInfo');
|
||||||
|
if (sync) this.shopInfo = sync;
|
||||||
|
} catch (e) {}
|
||||||
|
} else {
|
||||||
|
// 冷启动或未初始化:同步读 storage(上次会话的缓存)
|
||||||
|
try {
|
||||||
|
const sync = uni.getStorageSync('shopInfo');
|
||||||
|
if (sync) {
|
||||||
|
this.shopInfo = sync;
|
||||||
|
} else {
|
||||||
|
uni.getStorage({
|
||||||
|
key: 'shopInfo',
|
||||||
|
success: (e) => { this.shopInfo = e.data; },
|
||||||
|
fail: () => { console.warn('[hover-nav] 未获取到 shopInfo,使用默认设置'); }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.warn('[hover-nav] 读取 shopInfo 异常:', e);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
});
|
}
|
||||||
|
|
||||||
// 初始化 customerService 实例
|
// 初始化 customerService 实例
|
||||||
this.customerService = createCustomerService(this);
|
this.customerService = createCustomerService(this);
|
||||||
},
|
},
|
||||||
|
mounted() {
|
||||||
|
// 读取全局 CSS 变量(layout 参数),让 containerRight / containerBottom
|
||||||
|
// 可以跟着 App.vue 中的 :root 变量动态变化。
|
||||||
|
// H5 下 document.getComputedStyle 可用;小程序没有 document,
|
||||||
|
// 直接使用 data() 中的 fallback 默认值(46/72/272/100)。
|
||||||
|
// #ifdef H5
|
||||||
|
this.readLayoutVars();
|
||||||
|
// #endif
|
||||||
|
|
||||||
|
// ============================================================
|
||||||
|
// H5 下把 hover-nav 从页面 DOM 树搬到 document.body(Teleport)
|
||||||
|
// ------------------------------------------------------------
|
||||||
|
// 问题: 切换语言时 $langConfig.change() 内部调用 uni.reLaunch(),
|
||||||
|
// H5 的 reLaunch 会触发页面过渡动画(给页面容器加 transform)。
|
||||||
|
// CSS 规范: position: fixed 在 transform 父级下会失效,
|
||||||
|
// 变成相对于被 transform 的父级定位,导致 hover-nav 跟着
|
||||||
|
// 页面过渡一起"上移-下移"。
|
||||||
|
//
|
||||||
|
// 解决: 在 mounted() 中把 this.$el 搬到 document.body 下。
|
||||||
|
// 这样 hover-nav 不再是页面组件的子元素,页面过渡的 transform
|
||||||
|
// 完全不影响它。position: fixed 相对于 body(viewport) 正常工作。
|
||||||
|
//
|
||||||
|
// 副作用: 搬家后,页面根元素上的 CSS 变量(themeColor,如
|
||||||
|
// --hover-nav-bg-color)不再通过继承传递给 hover-nav,
|
||||||
|
// 因为 body 不在页面的 DOM 子树里。
|
||||||
|
// 修复: 由 watch('$store.state.themeColor') 监听主题色变化,
|
||||||
|
// 同步到 this.$el 的 inline style,让 hover-nav 自己持有这些 CSS 变量。
|
||||||
|
// 注意:必须在 mounted 中执行 Teleport,**之后** watch 才能找到
|
||||||
|
// 正确的 this.$el 元素;否则 watch 触发时,hover-nav 还在原父节点下,
|
||||||
|
// 主题色仍会通过页面继承自动应用,无需手动注入(但 Teleport 后会丢失)。
|
||||||
|
//
|
||||||
|
// 关键: mounted 末尾手动调一次 _applyThemeColor(currentTc),
|
||||||
|
// 解决刷新(有缓存,themeColor 同步就绪)场景下:
|
||||||
|
// - watch immediate 触发时 $el 不存在 → return
|
||||||
|
// - 之后 themeColor 已就绪、无变化 → watch 不再触发
|
||||||
|
// - → cssText 永远不注入
|
||||||
|
// 在这里调用能保证 $el 已就位,即使 themeColor 已有值也能正确注入。
|
||||||
|
//
|
||||||
|
// 注意: this.$el 是 Vue 组件的根元素(模板最外层的 <view>),
|
||||||
|
// 搬走它后 Vue 的响应式、事件、生命周期**完全不受影响**,
|
||||||
|
// 因为 Vue 的虚拟 DOM 与真实 DOM 位置解耦。
|
||||||
|
// 这是 Vue 2 的合法模式,等同于 Vue 3 的 <Teleport to="body">。
|
||||||
|
// ============================================================
|
||||||
|
// #ifdef H5
|
||||||
|
if (typeof document !== 'undefined' && document.body && this.$el) {
|
||||||
|
this._origParent = this.$el.parentNode;
|
||||||
|
document.body.appendChild(this.$el);
|
||||||
|
}
|
||||||
|
// #endif
|
||||||
|
|
||||||
|
// 关键: 手动同步当前 themeColor(覆盖 watch immediate 失效的场景)
|
||||||
|
// 详见上面的注释。_applyThemeColor 内部已判 $el 存在性,所有平台都安全。
|
||||||
|
this._applyThemeColor(this.$store && this.$store.state && this.$store.state.themeColor);
|
||||||
|
},
|
||||||
|
beforeDestroy() {
|
||||||
|
// H5 Teleport 还原:把元素从 body 移回原父节点,避免内存泄漏
|
||||||
|
// #ifdef H5
|
||||||
|
if (this._origParent && this.$el && this.$el.parentNode === document.body) {
|
||||||
|
this._origParent.appendChild(this.$el);
|
||||||
|
this._origParent = null;
|
||||||
|
}
|
||||||
|
// #endif
|
||||||
|
},
|
||||||
methods: {
|
methods: {
|
||||||
|
// #ifdef H5
|
||||||
|
/**
|
||||||
|
* 从 :root 读取 CSS 变量(App.vue 中定义)到 data,
|
||||||
|
* 让 containerRight / containerBottom 真正动态化。
|
||||||
|
* 任意一个变量解析失败都保留 data 中原值(fallback),不抛错。
|
||||||
|
*/
|
||||||
|
readLayoutVars() {
|
||||||
|
try {
|
||||||
|
if (typeof document === 'undefined') return; // SSR/非浏览器环境兜底
|
||||||
|
const root = document.documentElement;
|
||||||
|
const computed = getComputedStyle(root);
|
||||||
|
const getNum = (name, fallback) => {
|
||||||
|
const v = parseFloat(computed.getPropertyValue(name));
|
||||||
|
return Number.isFinite(v) ? v : fallback;
|
||||||
|
};
|
||||||
|
this.layoutTopRight = getNum('--top-btn-right', 46);
|
||||||
|
this.layoutTopBottom = getNum('--top-btn-bottom', 272);
|
||||||
|
this.layoutTopSize = getNum('--top-btn-size', 72);
|
||||||
|
this.layoutFloatingWidth = getNum('--floating-btn-width', 100);
|
||||||
|
} catch (e) {
|
||||||
|
console.warn('[hover-nav] 读取 CSS 变量失败,使用 fallback 默认值:', e);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
// #endif
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 把 themeColor 注入到 this.$el 的 cssText,
|
||||||
|
* 让 Teleport 到 body 后仍能读到 --hover-nav-bg-color 等 CSS 变量。
|
||||||
|
*
|
||||||
|
* 关键设计:
|
||||||
|
* - 用 data._appliedThemeColor 记录"已注入的 themeColor",
|
||||||
|
* 再次触发时**先剥离**旧值,再追加新值,避免重复拼接。
|
||||||
|
* - 主题切换时,旧值要先剥离(否则 cssText 会一直累积,文件膨胀)。
|
||||||
|
* - themeColor 为空时只剥离、不追加(themeColorSet action
|
||||||
|
* 内部会去重,不会频繁触发)。
|
||||||
|
*/
|
||||||
|
_applyThemeColor(tc) {
|
||||||
|
if (!this.$el || !this.$el.style) return;
|
||||||
|
// 1) 剥离旧注入(避免重复 + 处理主题切换场景)
|
||||||
|
if (this._appliedThemeColor) {
|
||||||
|
const cur = this.$el.style.cssText || '';
|
||||||
|
const suffix = ';' + this._appliedThemeColor;
|
||||||
|
if (cur.endsWith(suffix)) {
|
||||||
|
this.$el.style.cssText = cur.slice(0, -suffix.length);
|
||||||
|
}
|
||||||
|
this._appliedThemeColor = '';
|
||||||
|
}
|
||||||
|
// 2) 追加新值
|
||||||
|
if (tc) {
|
||||||
|
this._appliedThemeColor = tc;
|
||||||
|
this.$el.style.cssText = (this.$el.style.cssText || '') + ';' + tc;
|
||||||
|
}
|
||||||
|
},
|
||||||
initLanguage() {
|
initLanguage() {
|
||||||
this.langList = this.$langConfig.list();
|
// 数据源优先级:
|
||||||
|
// 1) shopInfo.langList(后端按租户/店铺动态下发的语言配置,推荐)
|
||||||
|
// 2) $langConfig.list()(前端 config 兜底,目前是 ['zh-cn','en-us'])
|
||||||
|
const info = (this.$store && this.$store.state && this.$store.state.shopInfo) || this.shopInfo;
|
||||||
|
|
||||||
|
// 合并短码映射:后端 langDisplayNames 覆盖前端默认 LANG_DISPLAY_NAMES
|
||||||
|
// 例:后端下发 { "zh-cn": "中文", "ja-jp": "日本語" } 时,
|
||||||
|
// - zh-cn 用 "中文" 而不是 "CN"
|
||||||
|
// - en-us 仍用默认的 "EN"
|
||||||
|
const backendMap = (info && info.langDisplayNames && typeof info.langDisplayNames === 'object' && !Array.isArray(info.langDisplayNames))
|
||||||
|
? info.langDisplayNames
|
||||||
|
: null;
|
||||||
|
this.langDisplayMap = backendMap
|
||||||
|
? Object.assign({}, LANG_DISPLAY_NAMES, backendMap) // 后端优先
|
||||||
|
: Object.assign({}, LANG_DISPLAY_NAMES);
|
||||||
|
const displayMap = this.langDisplayMap;
|
||||||
|
|
||||||
|
let rawList = null;
|
||||||
|
if (info && Array.isArray(info.langList) && info.langList.length > 0) {
|
||||||
|
// shopInfo 下发的可能是字符串数组 ['zh-cn','en-us'] 或 {value,name} 对象数组,都兼容
|
||||||
|
rawList = info.langList.map(item => {
|
||||||
|
if (typeof item === 'string') {
|
||||||
|
return { value: item, name: getLangShortCode(item, displayMap) };
|
||||||
|
}
|
||||||
|
// 对象形式:有 name 字段直接用,否则用合并后的映射
|
||||||
|
// (后端配置的 name 原样使用,不经过 $lang 翻译)
|
||||||
|
return { value: item.value, name: item.name || getLangShortCode(item.value, displayMap) };
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
// 兜底:用静态的 langConfig.langList + getLangShortCode 拼 {value, name}
|
||||||
|
// 关键:不要用 this.$langConfig.list(),那会读取 lang/{lang}/common.js 里的
|
||||||
|
// common.name(已经过 $lang 翻译),与需求"后端配什么就显示什么"冲突
|
||||||
|
const fallbackList = (this.$langConfig && this.$langConfig.langList) || [];
|
||||||
|
rawList = fallbackList.map(value => ({
|
||||||
|
value,
|
||||||
|
name: getLangShortCode(value, displayMap),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
this.langList = rawList;
|
||||||
this.langIndexMap = {};
|
this.langIndexMap = {};
|
||||||
for (let i = 0; i < this.langList.length; i++) {
|
for (let i = 0; i < this.langList.length; i++) {
|
||||||
this.langIndexMap[i] = this.langList[i].value;
|
this.langIndexMap[i] = this.langList[i].value;
|
||||||
@@ -219,19 +638,109 @@ export default {
|
|||||||
this.customerService.makePhoneCallByNumber(this.tel);
|
this.customerService.makePhoneCallByNumber(this.tel);
|
||||||
},
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 按钮点击的统一入口:
|
||||||
|
* - ≥3 种语言:弹底部选择器,用户选哪项就切到哪项
|
||||||
|
* - =2 种语言:走原 hover-nav 的循环逻辑(切到下一个)
|
||||||
|
*/
|
||||||
|
handleLangButtonClick() {
|
||||||
|
const list = this.langList;
|
||||||
|
if (!Array.isArray(list) || list.length < 2) return;
|
||||||
|
if (list.length >= 3) {
|
||||||
|
this.openLangPicker();
|
||||||
|
} else {
|
||||||
|
this.toggleLanguage();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 原 hover-nav 的循环切换逻辑(只有 2 种语言时使用)
|
||||||
|
* 点击 → 切到下一个语言
|
||||||
|
*/
|
||||||
toggleLanguage() {
|
toggleLanguage() {
|
||||||
this.currentLangIndex = this.currentLangIndex === 0 ? 1 : 0;
|
const list = this.langList;
|
||||||
const targetLang = this.langIndexMap[this.currentLangIndex];
|
if (!Array.isArray(list) || list.length === 0) {
|
||||||
|
console.warn('[hover-nav] 切换语言失败:langList 为空');
|
||||||
uni.setStorageSync("lang", targetLang);
|
return;
|
||||||
|
}
|
||||||
|
// 循环到下一个语言
|
||||||
|
this.currentLangIndex = (this.currentLangIndex + 1) % list.length;
|
||||||
|
const targetLang = list[this.currentLangIndex] && list[this.currentLangIndex].value;
|
||||||
|
if (!targetLang) {
|
||||||
|
console.warn('[hover-nav] 切换语言失败:目标语种为空', this.langIndexMap, this.currentLangIndex);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// 取当前页面路由(兼容 H5/Mini Program)
|
||||||
const pages = getCurrentPages();
|
const pages = getCurrentPages();
|
||||||
const currentPage = pages[pages.length - 1];
|
const currentPage = pages[pages.length - 1];
|
||||||
const currentRoute = currentPage.route;
|
const currentRoute = (currentPage && (currentPage.route || (currentPage.$page && currentPage.$page.path))) || 'pages/index/index';
|
||||||
|
const url = currentRoute.startsWith('/') ? currentRoute : '/' + currentRoute;
|
||||||
|
this.$langConfig.change(targetLang, url);
|
||||||
|
},
|
||||||
|
|
||||||
uni.reLaunch({
|
/**
|
||||||
url: '/' + currentRoute
|
* 打开语言选择器
|
||||||
});
|
*/
|
||||||
|
openLangPicker() {
|
||||||
|
if (!Array.isArray(this.langList) || this.langList.length < 2) {
|
||||||
|
// 只有 1 种语言(或 0 种)没必要打开选择器
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// 弹窗打开前一次性准备 i18n(此时 boot 已完成,$lang() 返回真实翻译)
|
||||||
|
this.prepareI18n();
|
||||||
|
this.showLangPopup = true;
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* i18n-lazy mixin 要求的方法:返回一个对象,key 与 data().i18n 字段一一对应
|
||||||
|
* 在 openLangPicker() 中调用,此时 Lang.boot() 已完成
|
||||||
|
*/
|
||||||
|
i18nPrepareFn() {
|
||||||
|
return {
|
||||||
|
langPickerTitle: this.$lang('components.hoverNav.langPickerTitle'),
|
||||||
|
langPickerCancel: this.$lang('components.hoverNav.langPickerCancel'),
|
||||||
|
};
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 关闭语言选择器
|
||||||
|
*/
|
||||||
|
closeLangPicker() {
|
||||||
|
this.showLangPopup = false;
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 选择某个语言
|
||||||
|
* @param {Number} idx 在 langList 中的下标
|
||||||
|
*/
|
||||||
|
selectLanguage(idx) {
|
||||||
|
if (!Array.isArray(this.langList) || idx < 0 || idx >= this.langList.length) {
|
||||||
|
console.warn('[hover-nav] selectLanguage 越界:', idx, this.langList);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// 同一个语言不切换
|
||||||
|
if (idx === this.currentLangIndex) {
|
||||||
|
this.showLangPopup = false;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.currentLangIndex = idx;
|
||||||
|
const targetLang = this.langList[idx].value;
|
||||||
|
this.showLangPopup = false;
|
||||||
|
|
||||||
|
// 取当前页面路由(兼容 H5/Mini Program)
|
||||||
|
const pages = getCurrentPages();
|
||||||
|
const currentPage = pages[pages.length - 1];
|
||||||
|
const currentRoute = (currentPage && (currentPage.route || (currentPage.$page && currentPage.$page.path))) || 'pages/index/index';
|
||||||
|
const url = currentRoute.startsWith('/') ? currentRoute : '/' + currentRoute;
|
||||||
|
|
||||||
|
// 使用统一的 $langConfig.change() 完成:
|
||||||
|
// 1) 写 storage + 失效缓存
|
||||||
|
// 2) 异步加载新语种 bundle/override
|
||||||
|
// 3) emitUpdated 触发 componentRefresh,所有 $lang() 重渲染
|
||||||
|
// 4) refresh 标题/tabbar
|
||||||
|
// 5) reLaunch 到当前路由,避免栈污染
|
||||||
|
this.$langConfig.change(targetLang, url);
|
||||||
},
|
},
|
||||||
|
|
||||||
handleUnifiedKefuClick() {
|
handleUnifiedKefuClick() {
|
||||||
@@ -247,7 +756,9 @@ export default {
|
|||||||
<style lang="scss" scoped>
|
<style lang="scss" scoped>
|
||||||
.fixed-box {
|
.fixed-box {
|
||||||
position: fixed;
|
position: fixed;
|
||||||
|
/* right 改由 inline-style(containerRight)动态计算,这里留旧值作 fallback */
|
||||||
right: 0rpx;
|
right: 0rpx;
|
||||||
|
/* bottom 改由 inline-style(containerBottom)动态计算,这里留旧值作 fallback */
|
||||||
bottom: 240rpx;
|
bottom: 240rpx;
|
||||||
/* #ifdef H5 */
|
/* #ifdef H5 */
|
||||||
bottom: 320rpx;
|
bottom: 320rpx;
|
||||||
@@ -257,11 +768,17 @@ export default {
|
|||||||
padding: 20rpx 0;
|
padding: 20rpx 0;
|
||||||
display: flex;
|
display: flex;
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
|
align-items: center;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
width: 100rpx;
|
/* width 改用 CSS 变量驱动,与 App.vue 的 --floating-btn-width 保持同步;
|
||||||
|
* JS 端(containerRight)也读同一个变量计算水平 right,
|
||||||
|
* 保证容器的实际宽度与 JS 计算用到的宽度始终一致。 */
|
||||||
|
width: var(--floating-btn-width, 100rpx);
|
||||||
box-sizing: border-box;
|
box-sizing: border-box;
|
||||||
transition: 0.3s;
|
transition: 0.3s;
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
|
/* 与 to-top.vue 的 .mescroll-totop 一致,适配 iPhoneX 等安全区 */
|
||||||
|
margin-bottom: var(--window-bottom);
|
||||||
}
|
}
|
||||||
|
|
||||||
.btn-item {
|
.btn-item {
|
||||||
@@ -274,10 +791,27 @@ export default {
|
|||||||
transition: 0.1s;
|
transition: 0.1s;
|
||||||
color: var(--hover-nav-text-color);
|
color: var(--hover-nav-text-color);
|
||||||
border-radius: 50%;
|
border-radius: 50%;
|
||||||
width: 80rpx;
|
width: 72rpx;
|
||||||
height: 80rpx;
|
height: 72rpx;
|
||||||
|
/* 关键:微信小程序的 <button> 元素有默认 appearance/background/border,
|
||||||
|
* 必须显式重置,否则 72rpx 高度会被默认样式吃掉,渲染成椭圆。 */
|
||||||
|
appearance: none;
|
||||||
|
-webkit-appearance: none;
|
||||||
|
background: transparent;
|
||||||
|
border: 0;
|
||||||
padding: 0;
|
padding: 0;
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
|
/* CSS 端兜底:即使 inline-style 失效,也能保证 1:1 比例 */
|
||||||
|
aspect-ratio: 1;
|
||||||
|
/* 锁死宽高,防止父级 flex 容器压缩 */
|
||||||
|
min-width: 72rpx;
|
||||||
|
min-height: 72rpx;
|
||||||
|
max-width: 72rpx;
|
||||||
|
max-height: 72rpx;
|
||||||
|
flex-shrink: 0;
|
||||||
|
flex-grow: 0;
|
||||||
|
align-self: center;
|
||||||
|
box-sizing: border-box;
|
||||||
}
|
}
|
||||||
|
|
||||||
.common-bg {
|
.common-bg {
|
||||||
@@ -292,17 +826,29 @@ export default {
|
|||||||
.icox {
|
.icox {
|
||||||
font-size: 36rpx;
|
font-size: 36rpx;
|
||||||
font-weight: bold;
|
font-weight: bold;
|
||||||
width: 100%;
|
|
||||||
height: 100%;
|
|
||||||
display: flex;
|
display: flex;
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
margin: 14rpx 0;
|
/* 不再设 width: 100% / height: 100% 再覆盖为 72rpx 的写法,
|
||||||
border-radius: 50rpx;
|
* 微信小程序/H5 对 width: 100% 在 flex 列布局里的高度计算有差异,
|
||||||
width: 80rpx;
|
* 直接固定 72x72 更稳。 */
|
||||||
height: 80rpx;
|
width: 72rpx;
|
||||||
|
height: 72rpx;
|
||||||
|
margin: 0;
|
||||||
|
border-radius: 50%;
|
||||||
padding: 0;
|
padding: 0;
|
||||||
position: relative;
|
position: relative;
|
||||||
|
box-sizing: border-box;
|
||||||
|
aspect-ratio: 1;
|
||||||
|
/* 立体效果:文字/图标本身与按钮同色,无法用普通阴影做出"凸起"。
|
||||||
|
* 这里用 text-shadow 做"凹陷雕刻"效果:
|
||||||
|
* - 上方一道更亮的阴影,模拟从顶部打光时文字上半部的高光;
|
||||||
|
* - 下方一道更暗的阴影,模拟文字下半部的背光。
|
||||||
|
* 两道同向偏移的小阴影叠加后,文字在按钮平面上被"压"出立体感。
|
||||||
|
* 用透明文字 + 阴影颜色与背景色相协调,保证按钮整体风格统一。 */
|
||||||
|
text-shadow:
|
||||||
|
0 1rpx 0 rgba(255, 255, 255, 0.45),
|
||||||
|
0 -1rpx 0 rgba(0, 0, 0, 0.18);
|
||||||
}
|
}
|
||||||
|
|
||||||
.iconfont text,
|
.iconfont text,
|
||||||
@@ -326,4 +872,91 @@ export default {
|
|||||||
align-items: center;
|
align-items: center;
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* 语言按钮内的短码文字(关键,之前缺失导致 CN/EN 文字撑大按钮变椭圆):
|
||||||
|
* 语言按钮的 inner 用 <view class="lang-btn-text"> 包裹文字,
|
||||||
|
* 如果没有这个规则,view 会用默认 font-size/line-height,
|
||||||
|
* "CN" / "EN" / "JP" 在中文/日文系统下会渲染成 32-40rpx 高,
|
||||||
|
* 撑高按钮导致 72rpx width × 38rpx height 的"伪正圆"实际是椭圆。 */
|
||||||
|
.lang-btn-text {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
font-size: 24rpx;
|
||||||
|
line-height: 1;
|
||||||
|
font-weight: 600;
|
||||||
|
letter-spacing: 0;
|
||||||
|
box-sizing: border-box;
|
||||||
|
overflow: hidden;
|
||||||
|
white-space: nowrap;
|
||||||
|
text-overflow: clip;
|
||||||
|
color: inherit;
|
||||||
|
font-weight: inherit;
|
||||||
|
/* 与 .iconfont 同一套凹陷雕刻式 text-shadow,保证语言文字也有立体感 */
|
||||||
|
text-shadow:
|
||||||
|
0 1rpx 0 rgba(255, 255, 255, 0.45),
|
||||||
|
0 -1rpx 0 rgba(0, 0, 0, 0.18);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 语言选择弹窗(底部弹出) */
|
||||||
|
.lang-mask {
|
||||||
|
position: fixed;
|
||||||
|
top: 0;
|
||||||
|
left: 0;
|
||||||
|
right: 0;
|
||||||
|
bottom: 0;
|
||||||
|
background: rgba(0, 0, 0, 0.5);
|
||||||
|
z-index: 999;
|
||||||
|
display: flex;
|
||||||
|
align-items: flex-end;
|
||||||
|
}
|
||||||
|
.lang-panel {
|
||||||
|
width: 100%;
|
||||||
|
background: #fff;
|
||||||
|
border-radius: 24rpx 24rpx 0 0;
|
||||||
|
padding: 20rpx 0 40rpx;
|
||||||
|
box-sizing: border-box;
|
||||||
|
/* #ifdef H5 */
|
||||||
|
padding-bottom: calc(40rpx + env(safe-area-inset-bottom));
|
||||||
|
/* #endif */
|
||||||
|
}
|
||||||
|
.lang-panel-title {
|
||||||
|
text-align: center;
|
||||||
|
font-size: 30rpx;
|
||||||
|
font-weight: bold;
|
||||||
|
color: #333;
|
||||||
|
padding: 20rpx 0 24rpx;
|
||||||
|
border-bottom: 1rpx solid #eee;
|
||||||
|
}
|
||||||
|
.lang-item {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
padding: 28rpx 40rpx;
|
||||||
|
font-size: 30rpx;
|
||||||
|
color: #333;
|
||||||
|
border-bottom: 1rpx solid #f5f5f5;
|
||||||
|
}
|
||||||
|
.lang-item-active {
|
||||||
|
color: #1989fa;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
.lang-item-name {
|
||||||
|
flex: 1;
|
||||||
|
}
|
||||||
|
.lang-item-check {
|
||||||
|
color: #1989fa;
|
||||||
|
font-size: 32rpx;
|
||||||
|
font-weight: bold;
|
||||||
|
}
|
||||||
|
.lang-cancel {
|
||||||
|
text-align: center;
|
||||||
|
padding: 28rpx 0;
|
||||||
|
margin-top: 16rpx;
|
||||||
|
color: #666;
|
||||||
|
font-size: 30rpx;
|
||||||
|
border-top: 1rpx solid #eee;
|
||||||
|
}
|
||||||
</style>
|
</style>
|
||||||
@@ -1,4 +1,8 @@
|
|||||||
<template>
|
<template>
|
||||||
|
<!-- #ifdef MP-HARMONY -->
|
||||||
|
<view></view>
|
||||||
|
<!-- #endif -->
|
||||||
|
<!-- #ifndef MP-HARMONY -->
|
||||||
<view class="loading-layer" v-if="isShow">
|
<view class="loading-layer" v-if="isShow">
|
||||||
<view class="loading-anim" v-if="themeStyle">
|
<view class="loading-anim" v-if="themeStyle">
|
||||||
<view class="box item">
|
<view class="box item">
|
||||||
@@ -6,6 +10,7 @@
|
|||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
|
<!-- #endif -->
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
@@ -84,10 +89,13 @@ export default {
|
|||||||
left: 15%;
|
left: 15%;
|
||||||
width: 70%;
|
width: 70%;
|
||||||
height: 70%;
|
height: 70%;
|
||||||
border-left-color: #FF4646;
|
// P0: 硬编码主色 → var(--base-color),主题切换时 loading 主色跟着变
|
||||||
|
// 兼容: 微信小程序 / 鸿蒙元服务 — border-color 接受 var() 值无问题
|
||||||
|
// JS 端 :style 绑定已用 themeStyle.main_color 走 inline 风格(原行 9),CSS 端用 var() 双保险
|
||||||
|
border-left-color: var(--base-color, #FF4646);
|
||||||
border-right-color: #C5C5C5 !important;
|
border-right-color: #C5C5C5 !important;
|
||||||
// border-right-color: rgba($color: #000000, $alpha: 0) !important;
|
// border-right-color: rgba($color: #000000, $alpha: 0) !important;
|
||||||
border-top-color: #FF4646 ;
|
border-top-color: var(--base-color, #FF4646);
|
||||||
border-bottom-color: #C5C5C5 !important;
|
border-bottom-color: #C5C5C5 !important;
|
||||||
// border-bottom-color: rgba($color: #000000, $alpha: 0) !important;
|
// border-bottom-color: rgba($color: #000000, $alpha: 0) !important;
|
||||||
animation: spin 0.6s linear normal infinite;
|
animation: spin 0.6s linear normal infinite;
|
||||||
|
|||||||
@@ -1,24 +1,26 @@
|
|||||||
// 全局配置
|
// 全局配置
|
||||||
// mescroll-body 和 mescroll-uni 通用
|
// mescroll-body 和 mescroll-uni 通用
|
||||||
|
import Lang from '@/common/js/lang.js';
|
||||||
|
|
||||||
const GlobalOption = {
|
const GlobalOption = {
|
||||||
down: {
|
down: {
|
||||||
// 其他down的配置参数也可以写,这里只展示了常用的配置:
|
// 其他down的配置参数也可以写,这里只展示了常用的配置:
|
||||||
textInOffset: '下拉刷新', // 下拉的距离在offset范围内的提示文本
|
textInOffset: Lang.lang('components.mescroll.down.textInOffset', '下拉刷新'), // 下拉的距离在offset范围内的提示文本
|
||||||
textOutOffset: '释放更新', // 下拉的距离大于offset范围的提示文本
|
textOutOffset: Lang.lang('components.mescroll.down.textOutOffset', '释放更新'), // 下拉的距离大于offset范围的提示文本
|
||||||
textLoading: '加载中 ...', // 加载中的提示文本
|
textLoading: Lang.lang('components.mescroll.down.textLoading', '加载中 ...'), // 加载中的提示文本
|
||||||
offset: 80, // 在列表顶部,下拉大于80px,松手即可触发下拉刷新的回调
|
offset: 80, // 在列表顶部,下拉大于80px,松手即可触发下拉刷新的回调
|
||||||
native: false // 是否使用系统自带的下拉刷新; 默认false; 仅在mescroll-body生效 (值为true时,还需在pages配置enablePullDownRefresh:true;详请参考mescroll-native的案例)
|
native: false // 是否使用系统自带的下拉刷新; 默认false; 仅在mescroll-body生效 (值为true时,还需在pages配置enablePullDownRefresh:true;详请参考mescroll-native的案例)
|
||||||
},
|
},
|
||||||
up: {
|
up: {
|
||||||
// 其他up的配置参数也可以写,这里只展示了常用的配置:
|
// 其他up的配置参数也可以写,这里只展示了常用的配置:
|
||||||
textLoading: '加载中 ...', // 加载中的提示文本
|
textLoading: Lang.lang('components.mescroll.up.textLoading', '加载中 ...'), // 加载中的提示文本
|
||||||
textNoMore: '', // 没有更多数据的提示文本
|
textNoMore: '', // 没有更多数据的提示文本
|
||||||
// textNoMore: '— 我是有底线的 —', // 没有更多数据的提示文本
|
// textNoMore: '— 我是有底线的 —', // 没有更多数据的提示文本
|
||||||
offset: 80, // 距底部多远时,触发upCallback
|
offset: 80, // 距底部多远时,触发upCallback
|
||||||
isBounce: false, // 默认禁止橡皮筋的回弹效果, 必读事项: http://www.mescroll.com/qa.html?v=190725#q25
|
isBounce: false, // 默认禁止橡皮筋的回弹效果, 必读事项: http://www.mescroll.com/qa.html?v=190725#q25
|
||||||
toTop: {
|
toTop: {
|
||||||
// 回到顶部按钮,需配置src才显示
|
// 回到顶部按钮,需配置src才显示
|
||||||
src: "http://www.mescroll.com/img/mescroll-totop.png?v=1", // 图片路径 (建议放入static目录, 如 /static/img/mescroll-totop.png )
|
src: "https://www.mescroll.com/img/mescroll-totop.png?v=1", // 图片路径 (建议放入static目录, 如 /static/img/mescroll-totop.png )
|
||||||
offset: 1000, // 列表滚动多少距离才显示回到顶部按钮,默认1000px
|
offset: 1000, // 列表滚动多少距离才显示回到顶部按钮,默认1000px
|
||||||
right: 20, // 到右边的距离, 默认20 (支持"20rpx", "20px", "20%"格式的值, 纯数字则默认单位rpx)
|
right: 20, // 到右边的距离, 默认20 (支持"20rpx", "20px", "20%"格式的值, 纯数字则默认单位rpx)
|
||||||
bottom: 120, // 到底部的距离, 默认120 (支持"20rpx", "20px", "20%"格式的值, 纯数字则默认单位rpx)
|
bottom: 120, // 到底部的距离, 默认120 (支持"20rpx", "20px", "20%"格式的值, 纯数字则默认单位rpx)
|
||||||
@@ -26,8 +28,8 @@ const GlobalOption = {
|
|||||||
},
|
},
|
||||||
empty: {
|
empty: {
|
||||||
use: true, // 是否显示空布局
|
use: true, // 是否显示空布局
|
||||||
icon: "http://www.mescroll.com/img/mescroll-empty.png?v=1", // 图标路径 (建议放入static目录, 如 /static/img/mescroll-empty.png )
|
icon: "https://www.mescroll.com/img/mescroll-empty.png?v=1", // 图标路径 (建议放入static目录, 如 /static/img/mescroll-empty.png )
|
||||||
tip: '~ 暂无相关数据 ~' // 提示
|
tip: Lang.lang('components.mescroll.empty.tip', '~ 暂无相关数据 ~') // 提示
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,18 @@
|
|||||||
* http://www.mescroll.com
|
* http://www.mescroll.com
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
import Lang from '@/common/js/lang.js';
|
||||||
|
|
||||||
|
// 国际化文本获取:优先从语言包读取,失败则使用默认值(向后兼容)
|
||||||
|
function __i18n(key, defaultVal) {
|
||||||
|
try {
|
||||||
|
var val = Lang.lang(key, defaultVal);
|
||||||
|
return val || defaultVal;
|
||||||
|
} catch (e) {
|
||||||
|
return defaultVal;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export default function MeScroll(options, isScrollBody) {
|
export default function MeScroll(options, isScrollBody) {
|
||||||
let me = this;
|
let me = this;
|
||||||
me.version = '1.2.3'; // mescroll版本号
|
me.version = '1.2.3'; // mescroll版本号
|
||||||
@@ -52,9 +64,9 @@ MeScroll.prototype.extendDownScroll = function(optDown) {
|
|||||||
outOffsetRate: 0.2, // 在列表顶部,下拉的距离大于offset时,改变下拉区域高度比例;值小于1且越接近0,高度变化越小,表现为越往下越难拉
|
outOffsetRate: 0.2, // 在列表顶部,下拉的距离大于offset时,改变下拉区域高度比例;值小于1且越接近0,高度变化越小,表现为越往下越难拉
|
||||||
bottomOffset: 20, // 当手指touchmove位置在距离body底部20px范围内的时候结束上拉刷新,避免Webview嵌套导致touchend事件不执行
|
bottomOffset: 20, // 当手指touchmove位置在距离body底部20px范围内的时候结束上拉刷新,避免Webview嵌套导致touchend事件不执行
|
||||||
minAngle: 45, // 向下滑动最少偏移的角度,取值区间 [0,90];默认45度,即向下滑动的角度大于45度则触发下拉;而小于45度,将不触发下拉,避免与左右滑动的轮播等组件冲突;
|
minAngle: 45, // 向下滑动最少偏移的角度,取值区间 [0,90];默认45度,即向下滑动的角度大于45度则触发下拉;而小于45度,将不触发下拉,避免与左右滑动的轮播等组件冲突;
|
||||||
textInOffset: '下拉刷新', // 下拉的距离在offset范围内的提示文本
|
textInOffset: __i18n('components.mescroll.down.textInOffset', '下拉刷新'), // 下拉的距离在offset范围内的提示文本
|
||||||
textOutOffset: '释放更新', // 下拉的距离大于offset范围的提示文本
|
textOutOffset: __i18n('components.mescroll.down.textOutOffset', '释放更新'), // 下拉的距离大于offset范围的提示文本
|
||||||
textLoading: '加载中 ...', // 加载中的提示文本
|
textLoading: __i18n('components.mescroll.down.textLoading', '加载中 ...'), // 加载中的提示文本
|
||||||
inited: null, // 下拉刷新初始化完毕的回调
|
inited: null, // 下拉刷新初始化完毕的回调
|
||||||
inOffset: null, // 下拉的距离进入offset范围内那一刻的回调
|
inOffset: null, // 下拉的距离进入offset范围内那一刻的回调
|
||||||
outOffset: null, // 下拉的距离大于offset那一刻的回调
|
outOffset: null, // 下拉的距离大于offset那一刻的回调
|
||||||
@@ -87,7 +99,7 @@ MeScroll.prototype.extendUpScroll = function(optUp) {
|
|||||||
},
|
},
|
||||||
noMoreSize: 5, // 如果列表已无数据,可设置列表的总数量要大于等于5条才显示无更多数据;避免列表数据过少(比如只有一条数据),显示无更多数据会不好看
|
noMoreSize: 5, // 如果列表已无数据,可设置列表的总数量要大于等于5条才显示无更多数据;避免列表数据过少(比如只有一条数据),显示无更多数据会不好看
|
||||||
offset: 80, // 距底部多远时,触发upCallback
|
offset: 80, // 距底部多远时,触发upCallback
|
||||||
textLoading: '加载中 ...', // 加载中的提示文本
|
textLoading: __i18n('components.mescroll.up.textLoading', '加载中 ...'), // 加载中的提示文本
|
||||||
textNoMore: '-- END --', // 没有更多数据的提示文本
|
textNoMore: '-- END --', // 没有更多数据的提示文本
|
||||||
inited: null, // 初始化完毕的回调
|
inited: null, // 初始化完毕的回调
|
||||||
showLoading: null, // 显示加载中的回调
|
showLoading: null, // 显示加载中的回调
|
||||||
@@ -112,7 +124,7 @@ MeScroll.prototype.extendUpScroll = function(optUp) {
|
|||||||
empty: {
|
empty: {
|
||||||
use: true, // 是否显示空布局
|
use: true, // 是否显示空布局
|
||||||
icon: null, // 图标路径
|
icon: null, // 图标路径
|
||||||
tip: '~ 暂无相关数据 ~', // 提示
|
tip: __i18n('components.mescroll.empty.tip', '~ 暂无相关数据 ~'), // 提示
|
||||||
btnText: '', // 按钮
|
btnText: '', // 按钮
|
||||||
btnClick: null, // 点击按钮的回调
|
btnClick: null, // 点击按钮的回调
|
||||||
onShow: null, // 是否显示的回调
|
onShow: null, // 是否显示的回调
|
||||||
|
|||||||
@@ -215,6 +215,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
methods: {
|
methods: {
|
||||||
|
scrollTo(y, t) {
|
||||||
|
this.mescroll.scrollTo(y, t);
|
||||||
|
},
|
||||||
//number,rpx,upx,px,% --> px的数值
|
//number,rpx,upx,px,% --> px的数值
|
||||||
toPx(num) {
|
toPx(num) {
|
||||||
if (typeof num === 'string') {
|
if (typeof num === 'string') {
|
||||||
@@ -278,10 +281,13 @@
|
|||||||
.select('#' + this.viewId);
|
.select('#' + this.viewId);
|
||||||
view.boundingClientRect(data => {
|
view.boundingClientRect(data => {
|
||||||
this.isExec = false;
|
this.isExec = false;
|
||||||
if (data) {
|
// 鸿蒙下 scroll-view 首次 layout 未完成时 data.height 可能为 0,
|
||||||
|
// 这种"假性成功"必须归入未拿到,触发重试,否则 clientHeight 永远卡在 0
|
||||||
|
if (data && data.height > 0) {
|
||||||
this.mescroll.setClientHeight(data.height);
|
this.mescroll.setClientHeight(data.height);
|
||||||
} else if (this.clientNum != 3) {
|
this.clientNum = null; // 成功一次,重置重试计数,后续业务可再次触发
|
||||||
// 极少部分情况,可能dom还未渲染完毕,递归获取,最多重试3次
|
} else if (this.clientNum == null || this.clientNum < 10) {
|
||||||
|
// 极少部分情况,可能dom还未渲染完毕,递归获取,最多重试10次
|
||||||
this.clientNum = this.clientNum == null ? 1 : this.clientNum + 1;
|
this.clientNum = this.clientNum == null ? 1 : this.clientNum + 1;
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
this.setClientHeight();
|
this.setClientHeight();
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
<template>
|
<template>
|
||||||
<!-- top="xxx"下拉布局往下偏移,防止被悬浮菜单遮住 -->
|
<!-- top="xxx"下拉布局往下偏移,防止被悬浮菜单遮住 -->
|
||||||
|
<!-- 鸿蒙下不要用 v-if="isInit",会导致内层 mescroll 创建被严重延迟,先 onReady 后 inner created -->
|
||||||
<mescroll
|
<mescroll
|
||||||
v-if="isInit"
|
|
||||||
:top="top"
|
:top="top"
|
||||||
:down="downOption"
|
:down="downOption"
|
||||||
:fixed="fixed"
|
:fixed="fixed"
|
||||||
@@ -14,8 +14,10 @@
|
|||||||
@emptyclick="emptyClick"
|
@emptyclick="emptyClick"
|
||||||
@init="mescrollInit"
|
@init="mescrollInit"
|
||||||
>
|
>
|
||||||
<!-- 数据列表 -->
|
<!-- 数据列表 - 鸿蒙下用 key 强制重建 slot DOM,绕过 ArkUI slot 响应式失效问题 -->
|
||||||
<slot name="list"></slot>
|
<view :key="listSlotKey">
|
||||||
|
<slot name="list"></slot>
|
||||||
|
</view>
|
||||||
</mescroll>
|
</mescroll>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
@@ -45,7 +47,10 @@ export default {
|
|||||||
onScroll: true
|
onScroll: true
|
||||||
},
|
},
|
||||||
scrollY: 0,
|
scrollY: 0,
|
||||||
isInit: false
|
// 鸿蒙下直接初始化为 true,避免 v-if 阻塞子组件创建导致 onReady 先于 inner mounted
|
||||||
|
isInit: true,
|
||||||
|
// 鸿蒙下用来强制重建 slot DOM 的 key
|
||||||
|
listSlotKey: 0
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
props: {
|
props: {
|
||||||
@@ -69,11 +74,45 @@ export default {
|
|||||||
},
|
},
|
||||||
created() {
|
created() {
|
||||||
if (this.size) this.upOption.page.size = this.size;
|
if (this.size) this.upOption.page.size = this.size;
|
||||||
this.isInit = true;
|
// #ifdef MP-HARMONY
|
||||||
|
// 鸿蒙下 ArkUI 对 slot 内 Vue 响应式更新失效,数据加载后强制重建 slot DOM
|
||||||
|
// 通过把 listSlotKey 自增,使 :key 变化,触发整个 slot 子树销毁重建
|
||||||
|
const oldUpCallback = this.upCallback;
|
||||||
|
this.upCallback = () => {
|
||||||
|
const ret = oldUpCallback.apply(this, arguments);
|
||||||
|
// 数据回来后 200ms 自增 key,强制 slot DOM 重建
|
||||||
|
setTimeout(() => {
|
||||||
|
this.listSlotKey = (this.listSlotKey || 0) + 1;
|
||||||
|
}, 200);
|
||||||
|
return ret;
|
||||||
|
};
|
||||||
|
// #endif
|
||||||
},
|
},
|
||||||
mounted() {
|
mounted() {
|
||||||
this.mescroll.resetUpScroll();
|
// 统一在 watcher 里触发首屏 resetUpScroll,这里不做任何事情
|
||||||
this.listenRefresh();
|
// (H5/微信下 mescroll 已在 mounted 前就绪;鸿蒙下 mounted 时机不可靠,所以都不在这里调)
|
||||||
|
},
|
||||||
|
watch: {
|
||||||
|
// 统一在 mescroll 实例就绪时触发首屏 resetUpScroll
|
||||||
|
// H5/微信下 inner 的 $emit('init') 同步触发,watcher 在 mounted 之前就 fire,正常加载
|
||||||
|
// 鸿蒙下 $emit 被延迟到 onReady 之后,watcher 在那时 fire,也能加载
|
||||||
|
mescroll: {
|
||||||
|
immediate: false,
|
||||||
|
handler(newVal) {
|
||||||
|
if (newVal && typeof newVal.resetUpScroll === 'function') {
|
||||||
|
// 避免重复触发
|
||||||
|
if (this._autoLoadTriggered) return;
|
||||||
|
this._autoLoadTriggered = true;
|
||||||
|
// 等下一个 tick,确保 outer 已挂载、meScroll 内部 setBodyHeight 等已执行
|
||||||
|
setTimeout(() => {
|
||||||
|
if (this.mescroll && typeof this.mescroll.resetUpScroll === 'function') {
|
||||||
|
this.mescroll.resetUpScroll();
|
||||||
|
this.listenRefresh();
|
||||||
|
}
|
||||||
|
}, 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
},
|
},
|
||||||
methods: {
|
methods: {
|
||||||
// mescroll组件初始化的回调,可获取到mescroll对象
|
// mescroll组件初始化的回调,可获取到mescroll对象
|
||||||
@@ -107,6 +146,14 @@ export default {
|
|||||||
},
|
},
|
||||||
listenRefresh() {
|
listenRefresh() {
|
||||||
this.$emit('listenRefresh', true);
|
this.$emit('listenRefresh', true);
|
||||||
|
},
|
||||||
|
/**
|
||||||
|
* 主动重建 slot DOM。
|
||||||
|
* 鸿蒙下通过 :key 变化重建的 .goods-item 元素 @click 事件绑定会丢失,
|
||||||
|
* 通过自增 listSlotKey 走 slot 重建路径可恢复事件绑定。
|
||||||
|
*/
|
||||||
|
forceSlotRebuild() {
|
||||||
|
this.listSlotKey = (this.listSlotKey || 0) + 1;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -9,7 +9,7 @@
|
|||||||
<text class="goods-price-sign color-base-text">¥</text>
|
<text class="goods-price-sign color-base-text">¥</text>
|
||||||
<text class="color-base-text">{{ goodsInfo.price }}</text>
|
<text class="color-base-text">{{ goodsInfo.price }}</text>
|
||||||
</view>
|
</view>
|
||||||
<view class="goods-option font-size-goods-tag disabled">已发送</view>
|
<view class="goods-option font-size-goods-tag disabled">{{ $lang('components.ns-chat-goods.sent') }}</view>
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
@@ -22,7 +22,7 @@
|
|||||||
<text class="goods-price-sign color-base-text">¥</text>
|
<text class="goods-price-sign color-base-text">¥</text>
|
||||||
<text class="color-base-text">{{ goodsDetail.price }}</text>
|
<text class="color-base-text">{{ goodsDetail.price }}</text>
|
||||||
</view>
|
</view>
|
||||||
<view class="goods-option font-size-goods-tag color-base-bg" @click="sendMsg('goods')">发送</view>
|
<view class="goods-option font-size-goods-tag color-base-bg" @click="sendMsg('goods')">{{ $lang('components.ns-chat-goods.send') }}</view>
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
|
|||||||
@@ -4,14 +4,14 @@
|
|||||||
<image :src="$util.img(orderdetails.order_goods ? orderdetails.order_goods[0].sku_image : '')" mode="aspectFill" show-menu-by-longpress></image>
|
<image :src="$util.img(orderdetails.order_goods ? orderdetails.order_goods[0].sku_image : '')" mode="aspectFill" show-menu-by-longpress></image>
|
||||||
<view class="goods-info">
|
<view class="goods-info">
|
||||||
<view class="goods-name">{{ orderdetails.order_goods ? orderdetails.order_goods[0].sku_name : '' }}</view>
|
<view class="goods-name">{{ orderdetails.order_goods ? orderdetails.order_goods[0].sku_name : '' }}</view>
|
||||||
<view class="font-size-goods-tag">订单状态:{{ orderdetails.order_status_name }}</view>
|
<view class="font-size-goods-tag">{{ $lang('components.nsChatOrder.orderStatus', { status: orderdetails.order_status_name }) }}</view>
|
||||||
<view class="font-size-goods-tag">配送方式:{{ orderdetails.delivery_type_name }}</view>
|
<view class="font-size-goods-tag">{{ $lang('components.nsChatOrder.deliveryMethod', { method: orderdetails.delivery_type_name }) }}</view>
|
||||||
<view class="goods-bottom">
|
<view class="goods-bottom">
|
||||||
<view class="goods-price color-base-text">
|
<view class="goods-price color-base-text">
|
||||||
<text class="goods-price-sign">¥</text>
|
<text class="goods-price-sign">¥</text>
|
||||||
<text>{{ orderdetails.order_goods ? orderdetails.order_goods[0].price : '' }}</text>
|
<text>{{ orderdetails.order_goods ? orderdetails.order_goods[0].price : '' }}</text>
|
||||||
</view>
|
</view>
|
||||||
<view class="goods-option font-size-goods-tag color-base-bg" @click="sendMsg('order')">发送</view>
|
<view class="goods-option font-size-goods-tag color-base-bg" @click="sendMsg('order')">{{ $lang('components.nsChatOrder.send') }}</view>
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
@@ -19,14 +19,14 @@
|
|||||||
<image :src="$util.img(orderInfo.order_goods ? orderInfo.order_goods[0].sku_image : '')" mode="aspectFill" show-menu-by-longpress></image>
|
<image :src="$util.img(orderInfo.order_goods ? orderInfo.order_goods[0].sku_image : '')" mode="aspectFill" show-menu-by-longpress></image>
|
||||||
<view class="goods-info">
|
<view class="goods-info">
|
||||||
<view class="goods-name">{{ orderInfo.order_goods ? orderInfo.order_goods[0].sku_name : '' }}</view>
|
<view class="goods-name">{{ orderInfo.order_goods ? orderInfo.order_goods[0].sku_name : '' }}</view>
|
||||||
<view class="font-size-goods-tag">订单状态:{{ orderInfo.order_status_name }}</view>
|
<view class="font-size-goods-tag">{{ $lang('components.nsChatOrder.orderStatus', { status: orderInfo.order_status_name }) }}</view>
|
||||||
<view class="font-size-goods-tag">配送方式:{{ orderInfo.delivery_type_name }}</view>
|
<view class="font-size-goods-tag">{{ $lang('components.nsChatOrder.deliveryMethod', { method: orderInfo.delivery_type_name }) }}</view>
|
||||||
<view class="goods-bottom">
|
<view class="goods-bottom">
|
||||||
<view class="goods-price color-base-text">
|
<view class="goods-price color-base-text">
|
||||||
<text class="goods-price-sign">¥</text>
|
<text class="goods-price-sign">¥</text>
|
||||||
<text>{{ orderInfo.order_goods ? orderInfo.order_goods[0].price : '' }}</text>
|
<text>{{ orderInfo.order_goods ? orderInfo.order_goods[0].price : '' }}</text>
|
||||||
</view>
|
</view>
|
||||||
<view class="goods-option font-size-goods-tag disabled">已发送</view>
|
<view class="goods-option font-size-goods-tag disabled">{{ $lang('components.nsChatOrder.sent') }}</view>
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
</view>
|
</view>
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user