Compare commits

..

1 Commits

Author SHA1 Message Date
695d27c5cb chore: merge dev/1.0 into main
包含以下修复:
- ai-chat 键盘弹出、输入框闪烁、滚动、WebSocket 等问题
- 小米微信小程序魔方组件布局修复
- 三处 calc() 精度统一避免小米子像素舍入差异
- H5 构建配置优化
2026-05-14 08:43:45 +08:00
785 changed files with 12961 additions and 95508 deletions

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,147 +0,0 @@
---
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

View File

@@ -1,33 +0,0 @@
# 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

83
.gitignore vendored
View File

@@ -1,86 +1,5 @@
/unpackage /unpackage
/.hbuilderx
/.idea /.idea
/.logs
/node_modules /node_modules
/iconfont-preview.html /iconfont-preview.html
.codebuddy
.vscode
.trae
# 本地调试配置 (含 uniacid / 域名, 每人不同, 不应入仓)
# 注意: 如果 .local.config.js 已经被之前的 commit 入仓,
# 需要手动 `git rm --cached .local.config.js` 并用 filter-branch
# 清理历史 (仅限团队协商后操作)
.local.config.js
# 鸿蒙元服务构建产物 (被 .gitignore 的只是产物, HAR 元数据需要 git 管理)
# 重要: ascf_build 根目录的元数据 (oh-package.json5 / Index.ets / build-profile.json5 / ...)
# 必须被 git 管理, 否则无法追踪 "module.name 被清空" 等回归。
# 这些元数据通过下方的 ! 取反规则显式纳入 git。
stub-app-projects/mp-harmony/ascf/ascf_src
stub-app-projects/mp-harmony/entry/src/main/resources/rawfile
# ascf_build/<pkg>/ 是 HAR 包定义
# 区分两类内容:
# 1. 必须入 git (元数据 / 构建配置 / HAR 入口):
# - oh-package.json5, build-profile.json5, hvigorfile.ts
# - obfuscation-rules.txt, src/main/module.json5
# - src/main/resources/base/element/string.json (HAR i18n)
# 2. 每次构建覆盖 (不应入 git):
# - src/main/resources/rawfile/** : 鸿蒙端从 ascf_src 同步的编译产物
# - Index.ets : 空壳文件, 无内容
# - build/, oh_modules/, .preview/, .cxx/, .test/, node_modules/
# rawfile/ 整体 ignore (鸿蒙端每次 Build 重新生成)
stub-app-projects/mp-harmony/ascf/ascf_build/**/rawfile/**
# Index.ets 是空壳 (每个包都是 0 字节), 不入 git
stub-app-projects/mp-harmony/ascf/ascf_build/**/Index.ets
# 其他产物目录
stub-app-projects/mp-harmony/ascf/ascf_build/**/build
stub-app-projects/mp-harmony/ascf/ascf_build/**/oh_modules
stub-app-projects/mp-harmony/ascf/ascf_build/**/.preview
stub-app-projects/mp-harmony/ascf/ascf_build/**/.cxx
stub-app-projects/mp-harmony/ascf/ascf_build/**/.test
stub-app-projects/mp-harmony/ascf/ascf_build/**/node_modules
# entry 下的产物
stub-app-projects/mp-harmony/entry/build
stub-app-projects/mp-harmony/entry/oh_modules
stub-app-projects/mp-harmony/entry/.preview
stub-app-projects/mp-harmony/entry/.cxx
stub-app-projects/mp-harmony/entry/.test
stub-app-projects/mp-harmony/entry/node_modules
# 鸿蒙工程顶层产物 (.hvigor / hvigor / .idea 已在根 .gitignore 范围或更精准的鸿蒙子 .gitignore)
stub-app-projects/mp-harmony/oh_modules
stub-app-projects/mp-harmony/.hvigor
stub-app-projects/mp-harmony/.idea
# 鸿蒙 hvigor 自身依赖
stub-app-projects/mp-harmony/hvigor
# Trae/IDE 临时文件
.hvigor/outputs
.trae_permission_check_*
# 本地测试脚本与产物归档(不入 git, 留本地复用)
# 内容: Playwright 截图 / 测试脚本 / 对比图 / 临时提交草稿
# 复用方式: cd _test_archive && python xxx.py
_test_archive/
# 兜底:防止任何临时测试文件被遗漏在根目录
# 名称以 _test_/_compare_/_auth_ 开头, 或 check_button.py 等
_test_*.png
_test_*.html
_compare*.png
_compare*.py
_auth_*.json
_commit_msg.txt
/check_button.py
# 鸿蒙签名材料 (敏感, 绝不能提交到公共 git)
# 仓库有 origin (github.com/Zajd/jsysq-uniapp) 是公开仓库, 签名材料必须 gitignore
stub-app-projects/mp-harmony/**/cert-profile
stub-app-projects/mp-harmony/**/.p12
stub-app-projects/mp-harmony/**/.p7b
stub-app-projects/mp-harmony/**/.cer
stub-app-projects/mp-harmony/**/.csr
stub-app-projects/mp-harmony/**/material

View File

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

View File

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

View File

@@ -9,7 +9,7 @@ const localDevConfig = ({
'576-xcx30.5g': { // 活性石灰装备 '576-xcx30.5g': { // 活性石灰装备
uniacid: 576, uniacid: 576,
domain: 'https://xcx30.5g-quickapp.com/', domain: 'https://xcx30.5g-quickapp.com/',
}, },
'2285': { // 数码喷墨墨水 '2285': { // 数码喷墨墨水
uniacid: 2285, uniacid: 2285,
domain: 'https://xcx.aigc-quickapp.com/', domain: 'https://xcx.aigc-quickapp.com/',
@@ -17,23 +17,19 @@ const localDevConfig = ({
'2811': { // POCT检测分析平台 '2811': { // POCT检测分析平台
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/',
}, },
'2505': { // 煤矿钻机 '2505': { // 煤矿钻机
uniacid: 2505, uniacid: 2505,
domain: 'https://xcx.aigc-quickapp.com/', domain: 'https://xcx.aigc-quickapp.com/',
}, },
'2777': { // 养老服务 '2777': { // 养老服务
uniacid: 2777, uniacid: 2777,
domain: 'https://xcx.aigc-quickapp.com/', domain: 'https://xcx.aigc-quickapp.com/',
}, },
'1': { // 开发平台 '1': { // 开发平台
uniacid: 1, uniacid: 1,
domain: 'https://dev.aigc-quickapp.com', domain: 'https://dev.aigc-quickapp.com',
@@ -42,165 +38,29 @@ 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/',
}, },
'local-1': { // 测试平台 '100': {
uniacid: 1, uniacid: 100,
domain: 'http://192.168.197.1:8050/', domain: 'https://5g.aigc-quickapp.com/',
// domain: 'http://localhost:8050/', },
}, '1': {
'192.168.8.118-1': { // 测试平台 uniacid: 1,
uniacid: 1, domain: 'https://5g.aigc-quickapp.com/',
domain: 'http://192.168.8.118:8050/', },
// domain: 'http://localhost:8050/', '115': {
}, uniacid: 115,
'local-11': { // 测试平台 domain: 'https://5g.aigc-quickapp.com/',
uniacid: 11, },
domain: 'http://localhost:8050/', '47': { // 修改弹窗
}, uniacid: 47,
'100': { domain: 'https://5g.aigc-quickapp.com/',
uniacid: 100, },
domain: 'https://5g.aigc-quickapp.com/', '2075': { //
}, uniacid: 2075,
'1': { domain: 'https://xcx.aigc-quickapp.com/',
uniacid: 1, },
domain: 'https://5g.aigc-quickapp.com/', })['1']; // 选择要使用的环境配置
},
'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/',
},
'5g-165': { // 鸡肉调理品, 优惠卷显示不全,及逻辑错误
uniacid: 165,
domain: 'https://5g.aigc-quickapp.com/',
},
'47': { // 修改弹窗
uniacid: 47,
domain: 'https://5g.aigc-quickapp.com/',
},
'145': { // 表单链接转义问题
uniacid: 145,
domain: 'https://5g.aigc-quickapp.com/',
},
'5g-213': { // 单图组点击链接无法跳转
uniacid: 213,
domain: 'https://5g.aigc-quickapp.com/',
},
'5g-4': { // 公告点击链接无法跳转
uniacid: 4,
domain: 'https://5g.aigc-quickapp.com/',
},
'5g-97': { // 大宗商品贸易,支持自定义字体大小、颜色
uniacid: 97,
domain: 'https://5g.aigc-quickapp.com/',
},
'5g-50': { // 燃气安全产品机器人,购物车无反应
uniacid: 50,
domain: 'https://5g.aigc-quickapp.com/',
},
'5g-237': { // 商品分类,没有立即咨询文字
uniacid: 237,
domain: 'https://5g.aigc-quickapp.com/',
},
'2847': { //
uniacid: 2847,
domain: 'https://xcx.aigc-quickapp.com/',
},
'2482': { // 低空经济
uniacid: 2482,
domain: 'https://xcx6.aigc-quickapp.com/',
},
'2485': { // 验证电子表单前后端数据一致性
uniacid: 2485,
domain: 'https://xcx6.aigc-quickapp.com/',
},
'2821': { // 离型纸硅油纸
uniacid: 2821,
domain: 'https://xcx.aigc-quickapp.com/',
},
'18': { // 测试平台
uniacid: 18,
domain: 'https://test.aigc-quickapp.com',
},
'2': { // 测试平台
uniacid: 2,
domain: 'https://test.aigc-quickapp.com',
},
'48': { // 测试平台
uniacid: 48,
domain: 'https://test.aigc-quickapp.com',
},
'test-12': { // 户外鞋,测试优惠券
uniacid: 12,
domain: 'https://test.aigc-quickapp.com',
},
'248': { // 大宗商品贸易,支持自定义字体大小、颜色
uniacid: 248,
domain: 'https://5g.aigc-quickapp.com/',
},
'228': { // 商品分类,没有立即咨询文字
uniacid: 228,
domain: 'https://5g.aigc-quickapp.com/',
},
'2797': { //气雾栽培机,视频组件安卓ios播放正常
uniacid: 2797,
domain: 'https://xcx.aigc-quickapp.com/',
},
'5g-95': { // 商品分类,没有立即咨询文字
uniacid: 95,
domain: 'https://5g.aigc-quickapp.com/',
},
'5g-160': { // 过瘤胃瘤胃保护,商品详情视频
uniacid: 160,
domain: 'https://5g.aigc-quickapp.com/',
},
'5g-268': { // 合成孔径雷达,一级分类背景字体颜色
uniacid: 268,
domain: 'https://5g.aigc-quickapp.com/',
},
'225-test': { // 测试平台
uniacid: 225,
domain: 'https://test.aigc-quickapp.com',
},
'192.168.8.118-321': { // 测试平台
uniacid: 321,
domain: 'http://192.168.8.118:8050/',
// domain: 'http://localhost:8050/',
},
// })['5g-237']; // 商品分类,没有立即咨询文字
// })['5g-97']; // 大宗商品贸易,支持自定义字体大小、颜色
// })['5g-50']; // 燃气安全产品机器人,购物车无反应
// })['2821']; // 离型纸硅油纸
// })['2482']; // 低空经济
// })['48']; // 离型纸硅油纸
// })['2485']; // 验证电子表单前后端数据一致性
// })['5g-11']; // 数码
// })['5g-213']; // 选择要使用的环境配置
// })['2881']; // 鸡肉调理品, 优惠卷显示不全,及逻辑错误
// })['2724']; // 生物菌肥
// })['2811']; // 选择要使用的环境配置
// })['local-11']; // 选择要使用的环境配置
})['2811']; // 本地
// })['local-2']; // 本地
// })['local-11']; // 本地
// })['1-test']; // test
// })['test-12']; // test
export default localDevConfig; export default localDevConfig;

419
App.vue
View File

@@ -1,386 +1,42 @@
<script> <script>
import auth from 'common/js/auth.js'; import auth from 'common/js/auth.js';
import configExternal, { themeConfig, privacyConfig } from 'common/js/config-external.js' import configExternal 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
// 主题提前加载(关键):让首屏渲染前 CSS 变量已挂上,避免闪一下 if(options.query.uniacid){
// ============================================================
// ---- 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 兜底
//
// 鸿蒙元服务(双轨制):
// 已接入平台隐私托管, 鸿蒙系统自动弹出系统级隐私弹窗.
// 应用层不调 PrivacyManager.show() (会和系统弹窗叠加被驳回).
// #ifdef MP-HARMONY
// 鸿蒙: 走平台隐私托管, markSkipped 写 storage
try {
await Promise.all([_i18nDone, _themeFirstApply, _themeOverride, _remoteConfig])
PrivacyManager.markSkipped()
} catch (e) { console.warn('[privacy] MP-HARMONY markSkipped fail', e); }
// #endif
// #ifndef MP-HARMONY
try {
await PrivacyManager.show({
urlFallback: _buildPrivacyUrlFallback(options),
readyGuard: Promise.all([_i18nDone, _themeFirstApply, _themeOverride, _remoteConfig]),
})
} catch (e) { console.warn('[privacy] show fail', e); }
// #endif
// splash 必须在隐私弹窗决策后再 hide (否则 splash 关掉瞬间弹窗还没渲染, 视觉闪一下)
// mode='fast': 隐私弹窗即将出现, splash 用 80ms 短动画, 让 modal 更快接管视觉
// 避免 splash 和弹窗同时显示造成的"双遮罩"感, 减少约 400ms 启动时间
// 只有 remote-only 模式才用了 splash (其他场景 src 模式不需要等远端)
//
// 关键 (鸿蒙 + 其他平台): 这里只发"软隐藏"信号, splash 实际关闭要等
// splashState._softHide() 看到 _hasMounted && _pageReady 才真关。
// _pageReady 由首页 diy-group 渲染完时调 notifyPageReady() 触发。
// 这样保证 splash **一直显示**, 直到首页 diy 内容真的渲染好,
// 避免 splash 关闭后到 diy 内容出现之间出现白屏。
//
// 鸿蒙端 (mode='strict'):
// 鸿蒙系统弹窗是用户视觉锚点, 应用层 splash 必须**真等到**diy 渲染好
// 才能关, 不走 MOUNT_GRACE_MS/PAGE_READY_GRACE_MS 软隐藏兜底
// (软隐藏兜底 1+2=3s 经常不够用, 会导致 splash 提前 hide → 白屏)
// strict 模式只受 DEFAULT_TIMEOUT=12s 总超时兜底, 实际由 notifyPageReady() 触发
// #ifndef H5
const _needSplash = typeof Lang !== 'undefined' && Lang.isRemoteOnly && Lang.isRemoteOnly();
if (_needSplash) {
// 所有平台都用 strict 模式: 不走 1+2s 软隐藏兜底
// splash 真等到 notifyPageReady (diy 渲染好) 或 notifyDiyLoadError (diy 错误) 才关
// DEFAULT_TIMEOUT=12s 总超时仍然兜底
// 避免 splash 提前关导致白屏
splashState.hide({ reason: 'boot-complete', mode: 'strict' });
}
// #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
if (uni.getUpdateManager) { const updateManager = uni.getUpdateManager();
const updateManager = uni.getUpdateManager(); updateManager.onCheckForUpdate(function(res) {
updateManager.onCheckForUpdate(function(res) { // 请求完新版本信息的回调
// 请求完新版本信息的回调 });
});
updateManager.onUpdateReady(function(res) { updateManager.onUpdateReady(function(res) {
uni.showModal({ uni.showModal({
title: Lang.lang('common.updateTip'), title: '更新提示',
content: Lang.lang('common.updateReady'), content: '新版本已经准备好,是否重启应用?',
success(res) { success(res) {
if (res.confirm) { if (res.confirm) {
// 新的版本已经下载好,调用 applyUpdate 应用新版本并重启 // 新的版本已经下载好,调用 applyUpdate 应用新版本并重启
updateManager.applyUpdate(); updateManager.applyUpdate();
}
} }
}); }
}); });
});
updateManager.onUpdateFailed(function(res) { updateManager.onUpdateFailed(function(res) {
// 新的版本下载失败 // 新的版本下载失败
}); });
}
// #endif // #endif
// #ifdef H5 // #ifdef H5
@@ -389,21 +45,26 @@
} }
// #endif // #endif
if (uni.onNetworkStatusChange) { uni.onNetworkStatusChange(function(res) {
uni.onNetworkStatusChange(function(res) { if (!res.isConnected) {
if (!res.isConnected) { uni.showModal({
uni.showModal({ title: '网络失去链接',
title: Lang.lang('common.networkLost'), content: '请检查网络链接',
content: Lang.lang('common.networkCheck'), showCancel: false
showCancel: false });
}); }
} });
});
}
// /api/config/init 已在 step 2.5 await 过 (含 800ms 超时), 此处不再重复触发 this.$store.dispatch('init');
// 原 fire-and-forget 注释: 不阻塞后续同步 commit
// 现在 init 已被升级为 "首次配置等待通道", 这里留空以避免重复 dispatch // 存储到store中
// 主题风格
if (uni.getStorageSync('themeStyle')) {
const themeData = await configExternal.loadTheme(uni.getStorageSync('themeStyle'));
this.$store.commit('setThemeStyle', themeData);
this.$store.dispatch('themeColorSet');
}
// 插件是否存在 // 插件是否存在
if (uni.getStorageSync('addonIsExist')) { if (uni.getStorageSync('addonIsExist')) {

View File

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

View File

@@ -118,8 +118,6 @@
.goods-video video { .goods-video video {
width: 100%; width: 100%;
height: 100%; height: 100%;
object-fit: contain;
object-position: center;
} }
.goods-video .uni-video-cover { .goods-video .uni-video-cover {

View File

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

View File

@@ -23,22 +23,6 @@ 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 {

View File

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

View File

@@ -1,58 +1,9 @@
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';
// ====== AI Agent Generalization (customer service is the first agent) ======
// setAgentId updates currentAgentId; default is agent_aikefu.
// Any sendMessage / sendStreamMessage / getServiceConfig call passes agent_id automatically.
//
// PR-7: 按 agent_id 路由 endpoint
// - agent_aikefu (默认智能客服) -> 走 aikefu addon (/api/kefu/* + /ws/aikefu)
// - 其他 agent (knowledge / quick_reply / sales / hr) -> 走 ai-agent addon (/api/aiagent/* + /ws/aiagent)
// - 前端不关心后端两个 addon 之间的差异,只关心 agent_id 路由
export const DEFAULT_AGENT_ID = 'agent_aikefu';
let currentAgentId = DEFAULT_AGENT_ID;
export const CONVERSATION_KEY = 'ai_conversation_id';
/**
* PR-7: agent_id -> 后端 addon 路由映射
*
* 规则:
* - agent_aikefu (默认智能客服) -> aikefu addon (老路径 /api/kefu/*)
* - 其他 agent -> aiagent addon (新路径 /api/aiagent/*)
*
* 后端两个 addon 完全独立:
* - aikefu: lucky_aikefu_config / conversation / message
* - aiagent: lucky_ai_agent_config / conversation / message
*/
function resolveAddonName(agentId) {
if (!agentId || agentId === 'agent_aikefu') return 'aikefu';
return 'aiagent';
}
/**
* PR-7: agent_id -> API endpoint URL
* agent_aikefu -> '/api/kefu/...' (兼容老路径)
* 其他 -> '/api/aiagent/...' (ai-agent 新路径)
*/
function resolveApiUrl(apiName) {
var addon = resolveAddonName(currentAgentId);
if (addon === 'aikefu') {
return '/api/kefu/' + apiName;
}
return '/api/aiagent/' + apiName;
}
/**
* PR-7: WebSocket URL 路径(/ws/{addonName})
*/
function resolveWsPath() {
return '/ws/' + resolveAddonName(currentAgentId);
}
/** /**
* 获取域名配置参数(避免重复代码) * 获取域名配置参数(避免重复代码)
@@ -75,220 +26,6 @@ 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;
}
/**
* 获取当前 AI Agent。
*/
function getAgentId() {
return currentAgentId || DEFAULT_AGENT_ID;
}
/**
* 设置当前 AI Agent。
*/
function setAgentId(agentId) {
if (agentId && typeof agentId === 'string') currentAgentId = agentId;
}
// #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;
}
// PR-7: WebSocket 路径按当前 agent_id 路由 — agent_aikefu 走 /ws/aikefu,其他走 /ws/aiagent
var wsPath = resolveWsPath();
var wssUrl = 'wss://' + domain + wsPath;
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',
agent_id: getAgentId(),
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
@@ -298,36 +35,20 @@ export default {
return uni.getStorageSync('uniacid') || Config.uniacid; // 从缓存中获取uniacid,或使用默认uniacid return uni.getStorageSync('uniacid') || Config.uniacid; // 从缓存中获取uniacid,或使用默认uniacid
}, },
/**
* PR-7: 获取当前 agent 对应的 addon 名称 (aikefu / aiagent)
*/
getAddonName() {
return resolveAddonName(currentAgentId);
},
/**
* PR-7: 获取当前 agent 对应的 API endpoint 前缀
*/
getApiPrefix() {
return resolveAddonName(currentAgentId) === 'aikefu' ? '/api/kefu' : '/api/aiagent';
},
/** /**
* 发送普通消息(blocking 模式) * 发送普通消息(blocking 模式)
* PR-7: URL 按 agent_id 路由
*/ */
async sendMessage(message, options = {}) { async sendMessage(message, options = {}) {
try { try {
const params = { const params = {
url: resolveApiUrl('chat'), url: '/api/kefu/chat',
data: { data: {
agent_id: getAgentId(), user_id: store.state.memberInfo?.id || 'anonymous',
user_id: getUserId(),
stream: false, stream: false,
inputs: {}, inputs: {},
query: message, query: message,
response_mode: 'blocking', response_mode: 'blocking', // 强制 blocking
user: getUserId(), user: store.state.memberInfo?.id || 'anonymous',
conversation_id: this.getConversationId() || '', conversation_id: this.getConversationId() || '',
...getDomainParams() ...getDomainParams()
}, },
@@ -349,61 +70,156 @@ export default {
} catch (error) { } catch (error) {
console.error('[AI Service] AiChat API请求失败,详细错误:', error); console.error('[AI Service] AiChat API请求失败,详细错误:', error);
console.error('[AI Service] 错误堆栈:', error.stack); console.error('[AI Service] 错误堆栈:', error.stack);
// 打印更多信息帮助调试
console.error('[AI Service] store 状态:', { console.error('[AI Service] store 状态:', {
memberInfo: store.state.memberInfo, memberInfo: store.state.memberInfo,
uniacid: this.getUniacid(), uniacid: this.getUniacid(),
token: store.state.token token: store.state.token
}); });
throw new Error(lang.lang('aiService.serviceUnavailable')); throw new Error('AI服务暂时不可用,请稍后重试');
} }
}, },
/** /**
* 流式消息入口(自动适配平台) * 流式消息入口(自动适配平台)
* 微信小程序:复用长连接 WebSocket
*/ */
async sendStreamMessage(message, onChunk, onComplete) { async sendStreamMessage(message, onChunk, onComplete) {
// #ifdef MP // #ifdef MP-WEIXIN
try { return new Promise((resolve, reject) => {
await ensureWebSocketConnected(); const match = Config.baseUrl.match(/^(?:https?:\/\/|wss?:\/\/)([^\/\s:]+)/);
} catch (e) { const domain = match ? match[1] : '';
if (onComplete) onComplete({ error: e.message });
throw e;
}
wsMessageContent = ''; // 修复 5:Domain 提取失败时提前拒绝
wsMessageActive = true; if (!domain) {
wsMessageOnChunk = onChunk || null; const errorMsg = 'WebSocket 域名配置无效';
wsMessageOnComplete = onComplete || null; console.error(errorMsg);
reject(new Error(errorMsg));
if (onComplete) onComplete({ error: errorMsg });
return;
}
return new Promise((resolve, reject) => { const wssUrl = `wss://${domain}/ws/aikefu`;
wsMessageResolve = resolve; const socketTask = wx.connectSocket({
wsMessageReject = reject; url: wssUrl,
header: {}
});
let content = '';
let conversationId = '';
let isAuthenticated = false;
let closedNormally = false;
let settled = false;
wsSocketTask.send({ // 安全地拒绝(防止重复调用)
data: JSON.stringify({ function safeReject(error) {
action: 'chat', if (settled) return;
agent_id: getAgentId(), settled = true;
uniacid: this.getUniacid(), clearTimeout(timeout);
query: message, reject(error);
user_id: getUserId(), }
conversation_id: this.getConversationId() || '',
...getDomainParams() // 安全地完成
}) 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 使用)
* PR-7: URL 按 agent_id 路由
*/ */
async sendHttpStream(message, onChunk, onComplete) { async sendHttpStream(message, onChunk, onComplete) {
// #ifdef H5 // #ifdef H5
try { try {
var chatUrl = resolveApiUrl('chat'); const url = Config.baseUrl + `/api/kefu/chat`;
var url = Config.baseUrl + chatUrl;
const response = await fetch(url, { const response = await fetch(url, {
method: 'POST', method: 'POST',
headers: { headers: {
@@ -416,32 +232,32 @@ export default {
inputs: {}, inputs: {},
query: message, query: message,
response_mode: 'streaming', response_mode: 'streaming',
agent_id: getAgentId(), 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(lang.lang('aiService.invalidResponse')); throw new Error('无效响应');
} }
const reader = response.body.getReader(); const reader = response.body.getReader();
const decoder = new TextDecoder('utf-8'); const decoder = new TextDecoder('utf-8');
let buffer = ''; let buffer = '';
let content = ''; let content = '';
let conversationId = ''; let conversationId = '';
while (true) { while (true) {
const { done, value } = await reader.read(); const { done, value } = await reader.read();
if (done) break; if (done) break;
buffer += decoder.decode(value, { stream: true }); buffer += decoder.decode(value, { stream: true });
// 按行分割,保留不完整的最后一行
const lines = buffer.split('\n'); const lines = buffer.split('\n');
buffer = lines.pop() || ''; buffer = lines.pop() || ''; // 未完成的行留到下次
for (const line of lines) { for (const line of lines) {
const trimmed = line.trim(); const trimmed = line.trim();
if (trimmed.startsWith('data:')) { if (trimmed.startsWith('data:')) {
@@ -450,19 +266,15 @@ 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') {
var text = data.answer || data.text || ''; const 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);
} }
var cid = data.conversation_id || (data.data && data.data.conversation_id) || ''; if (data.conversation_id) {
if (cid) { conversationId = data.conversation_id;
conversationId = cid;
} }
if (data.event === 'message_end' || data.event === 'done') { if (data.event === 'message_end') {
console.log('[AI SSE] 收到完成信号:', data.event, 'conversationId:', cid); // 可提前结束
} }
} }
} catch (e) { } catch (e) {
@@ -471,31 +283,27 @@ export default {
} }
} }
} }
// 处理最后残留的 buffer(如果有)
if (buffer.trim().startsWith('data:')) { if (buffer.trim().startsWith('data:')) {
try { try {
const jsonStr = buffer.trim().slice(5); const jsonStr = buffer.trim().slice(5);
if (jsonStr) { if (jsonStr) {
const data = JSON.parse(jsonStr); const data = JSON.parse(jsonStr);
if (data.event === 'message') { if (data.event === 'message') {
var text = data.answer || data.text || ''; const text = data.answer || '';
if (!text && data.data) {
text = data.data.content || data.data.answer || '';
}
content += text; content += text;
if (onChunk) onChunk(text); if (onChunk) onChunk(text);
} }
var cid = data.conversation_id || (data.data && data.data.conversation_id) || ''; if (data.conversation_id) {
if (cid) { conversationId = data.conversation_id;
conversationId = cid;
} }
} }
} catch (e) { } catch (e) {
console.warn('最后 buffer 解析失败:', e); console.warn('最后 buffer 解析失败:', e);
} }
} }
console.log('[AI SSE] 流完成, conversationId:', conversationId, 'content长度:', content.length);
if (onComplete) { if (onComplete) {
onComplete({ content, conversation_id: conversationId }); onComplete({ content, conversation_id: conversationId });
} }
@@ -519,7 +327,7 @@ export default {
messageId: response.data?.message_id messageId: response.data?.message_id
}; };
} else { } else {
throw new Error(response.message || lang.lang('aiService.serviceResponseError')); throw new Error(response.message || 'AI服务返回错误');
} }
}, },
@@ -558,23 +366,21 @@ export default {
/** /**
* 生成新会话(如需) * 生成新会话(如需)
* PR-7: URL 按 agent_id 路由
*/ */
async generateConversationId() { async generateConversationId() {
const params = { const params = {
url: resolveApiUrl('createConversation'), url: '/api/kefu/createConversation',
data: { data: {
agent_id: getAgentId(), 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
@@ -584,12 +390,11 @@ export default {
/** /**
* 获取服务状态 * 获取服务状态
* PR-7: URL 按 agent_id 路由
*/ */
async getServiceStatus() { async getServiceStatus() {
try { try {
const response = await http.sendRequest({ const response = await http.sendRequest({
url: resolveApiUrl('health'), url: '/api/kefu/health',
async: false, async: false,
data: {} data: {}
}); });
@@ -597,58 +402,24 @@ export default {
.filter(item => item === 'healthy').length > 0; .filter(item => item === 'healthy').length > 0;
return { return {
available, available,
reason: available ? lang.lang('aiService.statusNormal') : lang.lang('aiService.statusAbnormal') reason: available ? '服务正常' : '服务异常'
}; };
} catch (error) { } catch (error) {
return { return {
available: false, available: false,
reason: lang.lang('aiService.statusCheckFailed') reason: '服务检查失败'
}; };
} }
}, },
/**
* 获取服务配置信息
* PR-7: URL 按 agent_id 路由
*/
async getServiceConfig() {
try {
const params = {
url: resolveApiUrl('info'),
data: {
agent_id: getAgentId(),
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;
}
},
/** /**
* 清除会话历史(调用后端接口) * 清除会话历史(调用后端接口)
* PR-7: URL 按 agent_id 路由
*/ */
async clearConversation(conversationId) { async clearConversation(conversationId) {
try { try {
const response = await http.sendRequest({ const response = await http.sendRequest({
url: resolveApiUrl('clear-conversation'), url: '/api/kefu/clear-conversation',
data: { data: {
agent_id: getAgentId(),
conversation_id: conversationId, conversation_id: conversationId,
...getDomainParams() ...getDomainParams()
}, },
@@ -663,27 +434,24 @@ export default {
/** /**
* 获取会话历史 * 获取会话历史
* PR-7: URL 按 agent_id 路由
*/ */
async getConversationHistory(params = {}) { async getConversationHistory(params = {}) {
try { try {
if (!params.conversation_id) { if (!params.conversation_id) {
throw new Error(lang.lang('aiService.conversationIdRequired')); throw new Error('会话ID(conversation_id)是必填参数');
} }
console.log('[AI History] 请求历史, conversation_id:', params.conversation_id, 'limit:', params.limit);
const requestData = { const requestData = {
agent_id: params.agent_id || getAgentId(),
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 || getUserId(), user_id: params.user_id || store.state.memberInfo?.id || 'anonymous',
limit: params.limit || 20, limit: params.limit || 20,
offset: params.offset || 0, offset: params.offset || 0,
member_id: params.member_id || getUserId(), member_id: params.member_id || store.state.memberInfo?.id || 'anonymous',
token: params.token || '', token: params.token || '',
...getDomainParams() ...getDomainParams()
}; };
const response = await http.sendRequest({ const response = await http.sendRequest({
url: resolveApiUrl('getHistory'), url: '/api/kefu/getHistory',
data: requestData, data: requestData,
header: { header: {
'Content-Type': 'application/json' 'Content-Type': 'application/json'
@@ -699,11 +467,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 || lang.lang('aiService.getHistoryFailed')); throw new Error(response.message || '获取会话历史失败');
} }
} catch (error) { } catch (error) {
console.error('获取会话历史失败:', error); console.error('获取会话历史失败:', error);
throw new Error(error.message || lang.lang('aiService.getHistoryError')); throw new Error(error.message || '获取会话历史时发生错误,请稍后重试');
} }
}, },
@@ -713,7 +481,6 @@ export default {
/** /**
* [H5 Only] EventSource 流式聊天(备用) * [H5 Only] EventSource 流式聊天(备用)
* PR-7: URL 按 agent_id 路由
*/ */
chatWithEventSource(message, conversationId = '', onMessage, onComplete, onError) { chatWithEventSource(message, conversationId = '', onMessage, onComplete, onError) {
// #ifdef H5 // #ifdef H5
@@ -721,10 +488,9 @@ export default {
window.currentEventSource.close(); window.currentEventSource.close();
} }
const paramsObj = { const paramsObj = {
agent_id: getAgentId(),
uniacid: this.getUniacid(), uniacid: this.getUniacid(),
user_id: getUserId(), user_id: store.state.memberInfo?.id || 'anonymous',
member_id: getUserId(), member_id: store.state.memberInfo?.id || 'anonymous',
token: store.state.token || 'test_token', token: store.state.token || 'test_token',
query: message, query: message,
conversation_id: conversationId || '', conversation_id: conversationId || '',
@@ -732,8 +498,7 @@ export default {
...getDomainParams() ...getDomainParams()
}; };
const params = new URLSearchParams(paramsObj); const params = new URLSearchParams(paramsObj);
var chatUrl = resolveApiUrl('chat'); const url = `${Config.baseUrl}/api/kefu/chat?${params.toString()}`;
const url = `${Config.baseUrl}${chatUrl}?${params.toString()}`;
try { try {
const eventSource = new EventSource(url); const eventSource = new EventSource(url);
window.currentEventSource = eventSource; window.currentEventSource = eventSource;
@@ -746,9 +511,9 @@ export default {
if (onMessage) onMessage(data.answer || ''); if (onMessage) onMessage(data.answer || '');
} }
if (data.event === 'message_end') { if (data.event === 'message_end') {
if (onComplete) onComplete({ if (onComplete) onComplete({
conversation_id: data.conversation_id, conversation_id: data.conversation_id,
message: aiMessage message: aiMessage
}); });
} }
} catch (error) { } catch (error) {
@@ -757,7 +522,7 @@ export default {
}; };
eventSource.onerror = (error) => { eventSource.onerror = (error) => {
console.error('EventSource错误:', error); console.error('EventSource错误:', error);
if (onError) onError({ error: lang.lang('aiService.connectionFailed') }); if (onError) onError({ error: '连接失败' });
window.currentEventSource = null; window.currentEventSource = null;
}; };
return eventSource; return eventSource;
@@ -767,7 +532,7 @@ export default {
return null; return null;
} }
// #endif // #endif
// #ifdef MP // #ifdef MP-WEIXIN
console.warn('chatWithEventSource 不支持微信小程序'); console.warn('chatWithEventSource 不支持微信小程序');
return null; return null;
// #endif // #endif
@@ -778,49 +543,14 @@ export default {
*/ */
async chatWithFetchStream(message, conversationId = '', onMessage, onComplete, onError) { async chatWithFetchStream(message, conversationId = '', onMessage, onComplete, onError) {
// #ifdef H5 // #ifdef H5
// 实际逻辑已在 sendHttpStream 中实现,此处可复用或留空
return this.sendHttpStream(message, onMessage, (res) => { return this.sendHttpStream(message, onMessage, (res) => {
onComplete?.({ message: res.content, conversation_id: res.conversation_id }); onComplete?.({ message: res.content, conversation_id: res.conversation_id });
}); });
// #endif // #endif
// #ifdef MP // #ifdef MP-WEIXIN
console.warn('chatWithFetchStream 不支持微信小程序'); console.warn('chatWithFetchStream 不支持微信小程序');
return null; return null;
// #endif // #endif
}, }
};
// #ifdef MP
/**
* [微信小程序] 断开 WebSocket 长连接(页面离开时调用)
*/
disconnectWebSocket() {
disconnectWebSocket();
},
// #endif
// #ifdef H5
disconnectWebSocket() {
// H5 无 WebSocket 长连接,无需操作
},
// #endif
/**
* Set current AI Agent (default aikefu; link system passes agent_id).
* PR-7: 切换 agent 时, 如果跨 addon 则断开 WebSocket 重连 (路径变了)
* @param {string} agentId
*/
setAgentId(agentId) {
var oldAddon = resolveAddonName(currentAgentId);
setAgentId(agentId);
var newAddon = resolveAddonName(currentAgentId);
if (oldAddon !== newAddon) {
try { disconnectWebSocket(); } catch (e) { /* ignore */ }
}
},
/**
* Get current AI Agent.
* @returns {string}
*/
getAgentId() {
return getAgentId();
},
};

View File

@@ -8,11 +8,9 @@ export default {
/** /**
* 获取用户登录凭证code * 获取用户登录凭证code
*/ */
getCode(callback, fallbackFunc) { getCode(callback) {
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,
@@ -31,15 +29,12 @@ 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 : this.$lang('auth.miniProgramConfigError') title: res.message ? res.message : '小程序配置错误'
}); });
} }
} }
}) })
} else {
fallbackFunc && fallbackFunc(res);
} }
}, },
fail: (res) => { fail: (res) => {
@@ -51,7 +46,6 @@ export default {
}); });
} }
// #endif // #endif
fallbackFunc && fallbackFunc(res);
} }
}) })
// #endif // #endif
@@ -72,10 +66,9 @@ 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 : this.$lang('auth.miniProgramConfigError') title: res.message ? res.message : '小程序配置错误'
}); });
} }
} }
}) })
@@ -101,9 +94,6 @@ export default {
if (res.code >= 0) { if (res.code >= 0) {
location.href = res.data; location.href = res.data;
} }
},
fail: err => {
fallbackFunc && fallbackFunc(err);
} }
}); });
} }

View File

@@ -3,83 +3,20 @@
// 语言包配置 // 语言包配置
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 个) // 主题列表
// 关键: 这里列出的名字必须能在 style_color.js (或后端 style_color.php 镜像) 中找到对应 preset themeList: ['default', 'red', 'green', 'blue', 'pink', 'gold', 'purple', 'yellow', 'black'],
// 历史上曾包含 'red' 但 style_color.js 从未定义 'red' preset, 切到 'red' 主题时 // 默认主题
// loadTheme() 会返回 undefined → 走 stub default 兜底样式, 远端也无法补齐 defaultTheme: '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配置
@@ -94,130 +31,11 @@ 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
} }
/** /**
@@ -241,7 +59,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);
} }
}); });
@@ -282,40 +100,23 @@ 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) {

View File

@@ -1,7 +1,7 @@
// 发行版本,配置说明 // 发行版本,配置说明
let releaseCfg = undefined; let releaseCfg = undefined;
// #ifdef APP-PLUS || MP-WEIXIN || MP-ALIPAY || MP-BAIDU || MP-QQ || MP-TOUTIAO || MP-HARMONY // #ifdef APP-PLUS || MP-WEIXIN || MP-ALIPAY || MP-BAIDU || MP-QQ || MP-TOUTIAO
try { try {
if (site) { // 从site.js文件中获取配置, 针对微信小程序类 if (site) { // 从site.js文件中获取配置, 针对微信小程序类
releaseCfg = { releaseCfg = {
@@ -11,13 +11,7 @@ try {
uniacid: site.uniacid, uniacid: site.uniacid,
} }
} else { } else {
// 惰性加载 Lang 避免循环依赖(lang.js 引用了 config.js) console.warn('小程序发行环境下,必须配置site.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

View File

@@ -3,8 +3,6 @@
* 整合各种客服方式,提供统一的调用接口 * 整合各种客服方式,提供统一的调用接口
*/ */
import IMAGE_CONFIG from './image-config.js'; import IMAGE_CONFIG from './image-config.js';
import Platform from './platform.js';
import PAGE_KEY_MAP from './util.js';
export class CustomerService { export class CustomerService {
constructor(vueInstance, externalConfig = null) { constructor(vueInstance, externalConfig = null) {
@@ -32,25 +30,28 @@ 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'
};
const platformKey = platformMap[Platform.detect()] || Platform.detect(); let platformConfig = null;
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;
} }
@@ -101,7 +102,7 @@ export class CustomerService {
if (!config || !config.type) { if (!config || !config.type) {
result.isValid = false; result.isValid = false;
result.errors.push(this.vm.$lang('customerService.serviceTypeNotConfigured')); result.errors.push('客服类型未配置');
return result; return result;
} }
@@ -119,16 +120,6 @@ export class CustomerService {
/** /**
* 跳转到 AI智能客服页面(AiChat) * 跳转到 AI智能客服页面(AiChat)
*
* 注意:不在此处注入 __dyu=FloatBtn。
* 该标记原本是 diy-float-btn.vue 用来告诉 ai-chat "我是从浮动按钮来的,请隐藏底部 tabBar"。
* 此方法是 customer-service.js 的**通用 AI 客服入口**,被多处复用:
* - hover-nav(悬浮客服按钮)
* - 商品详情页 / 会员中心 / 个人中心 等的"联系客服"按钮
* - DIY 浮动按钮(diy-float-btn 内部已自行注入 __dyu=FloatBtn,这里再注入会重复)
* 若在此处统一注入,会让所有 AI 客服入口都隐藏底部 tabBar,语义错误且侵入性过强。
* hover-nav 需要隐藏 tabBar 的场景,由 hover-nav.vue#handleUnifiedKefuClick
* 自行注入 __dyu=FloatBtn(与 diy-float-btn.vue#onFloatBtnClick 一致)。
*/ */
openAiChatService() { openAiChatService() {
try { try {
@@ -138,7 +129,7 @@ export class CustomerService {
} }
// ✅ 修正路径:必须与 pages.json 中注册的路径一致 // ✅ 修正路径:必须与 pages.json 中注册的路径一致
const aiChatUrl = PAGE_KEY_MAP.AI_CHAT_PAGE_URL; const aiChatUrl = '/pages_tool/ai-chat/index';
// ✅ 使用 navigateTo 保留返回栈(体验更好) // ✅ 使用 navigateTo 保留返回栈(体验更好)
uni.navigateTo({ uni.navigateTo({
@@ -149,12 +140,12 @@ export class CustomerService {
// #ifdef H5 // #ifdef H5
window.location.href = aiChatUrl; window.location.href = aiChatUrl;
// #endif // #endif
uni.showToast({ title: this.vm.$lang('customerService.openFailed'), icon: 'none' }); uni.showToast({ title: '打开客服失败', icon: 'none' });
} }
}); });
} catch (e) { } catch (e) {
console.error('跳转 AI智能客服异常:', e); console.error('跳转 AI智能客服异常:', e);
uni.showToast({ title: this.vm.$lang('customerService.openFailed'), icon: 'none' }); uni.showToast({ title: '打开客服失败', icon: 'none' });
} }
} }
@@ -234,7 +225,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: this.vm.$lang('customerService.wxworkConfigIncomplete'), icon: 'none' }); uni.showToast({ title: '企业微信配置不完整', icon: 'none' });
this.fallbackToPhoneCall(); this.fallbackToPhoneCall();
return; return;
} }
@@ -278,12 +269,12 @@ export class CustomerService {
}, },
fail: (err) => { fail: (err) => {
console.error('【跳转第三方小程序失败】', err); console.error('【跳转第三方小程序失败】', err);
uni.showToast({ title: this.vm.$lang('customerService.jumpFailed'), icon: 'none' }); uni.showToast({ title: '跳转失败,请稍后重试', icon: 'none' });
} }
}); });
// #endif // #endif
// #ifdef H5 // #ifdef H5
uni.showToast({ title: this.vm.$lang('customerService.miniProgramOnly'), icon: 'none' }); uni.showToast({ title: '第三方小程序客服仅在微信小程序中可用', icon: 'none' });
// #endif // #endif
return; return;
} }
@@ -293,11 +284,11 @@ export class CustomerService {
// #ifdef H5 // #ifdef H5
window.location.href = config.third_url; window.location.href = config.third_url;
// #endif // #endif
// #ifdef MP // #ifdef MP-WEIXIN
uni.setClipboardData({ uni.setClipboardData({
data: config.third_url, data: config.third_url,
success: () => { success: () => {
uni.showToast({ title: this.vm.$lang('customerService.linkCopied'), icon: 'none' }); uni.showToast({ title: '链接已复制,请在浏览器打开', icon: 'none' });
} }
}); });
// #endif // #endif
@@ -361,9 +352,9 @@ export class CustomerService {
// #ifdef H5 // #ifdef H5
window.open(serviceUrl, '_blank'); window.open(serviceUrl, '_blank');
// #endif // #endif
// #ifdef MP // #ifdef MP-WEIXIN
uni.setClipboardData({ data: serviceUrl }); uni.setClipboardData({ data: serviceUrl });
uni.showToast({ title: this.vm.$lang('customerService.customerLinkCopied'), icon: 'none' }); uni.showToast({ title: '客服链接已复制', icon: 'none' });
// #endif // #endif
return; return;
} }
@@ -391,11 +382,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: this.vm.$lang('customerService.noServicePhone'), icon: 'none' }); uni.showToast({ title: '暂无客服电话', icon: 'none' });
} }
}, },
fail: () => { fail: () => {
uni.showToast({ title: this.vm.$lang('customerService.getPhoneFailed'), icon: 'none' }); uni.showToast({ title: '获取客服电话失败', icon: 'none' });
} }
}); });
} }
@@ -403,23 +394,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
? this.vm.$lang('customerService.callServiceTip', { phone: siteInfo.site_tel }) ? `请联系客服,客服电话是 ${siteInfo.site_tel}`
: this.vm.$lang('customerService.noServiceOffline'); : '抱歉,商家暂无客服,请线下联系';
uni.showModal({ title: this.vm.$lang('customerService.contactCustomerService'), content: message, showCancel: false }); uni.showModal({ title: '联系客服', content: message, showCancel: false });
} }
showConfigErrorPopup(errors) { showConfigErrorPopup(errors) {
uni.showModal({ uni.showModal({
title: this.vm.$lang('customerService.configError'), title: '客服配置错误',
content: this.vm.$lang('customerService.configErrorDetail', { errors: errors.join('\n') }), content: `配置有误:\n${errors.join('\n')}`,
showCancel: false showCancel: false
}); });
} }
fallbackToOriginalService() { fallbackToOriginalService() {
uni.showModal({ uni.showModal({
title: this.vm.$lang('customerService.tip'), title: '提示',
content: this.vm.$lang('customerService.cannotAddWxwork'), content: '无法直接添加企业微信,是否使用其他方式联系客服?',
success: (res) => { success: (res) => {
if (res.confirm) { if (res.confirm) {
this.openWxworkService(true); this.openWxworkService(true);
@@ -430,8 +421,8 @@ export class CustomerService {
fallbackToPhoneCall() { fallbackToPhoneCall() {
uni.showModal({ uni.showModal({
title: this.vm.$lang('customerService.tip'), title: '提示',
content: this.vm.$lang('customerService.onlineUnavailable'), content: '在线客服不可用,是否拨打电话联系客服?',
success: (res) => { success: (res) => {
if (res.confirm) this.makePhoneCall(); if (res.confirm) this.makePhoneCall();
} }
@@ -562,9 +553,6 @@ export class CustomerService {
/** /**
* 打开 AI 智能助手 * 打开 AI 智能助手
*
* 注意:不在此处注入 __dyu=FloatBtn,理由同 openAiChatService()。
* 由调用方(hover-nav.vue 等)按需注入。
*/ */
openAIChat() { openAIChat() {
try { try {
@@ -572,7 +560,7 @@ export class CustomerService {
this.vm.setAiUnreadCount(0); this.vm.setAiUnreadCount(0);
} }
const aiChatUrl = PAGE_KEY_MAP.AI_CHAT_PAGE_URL; const aiChatUrl = '/pages_tool/ai-chat/index';
uni.navigateTo({ uni.navigateTo({
url: aiChatUrl, url: aiChatUrl,
@@ -581,12 +569,12 @@ export class CustomerService {
// #ifdef H5 // #ifdef H5
window.location.href = aiChatUrl; window.location.href = aiChatUrl;
// #endif // #endif
uni.showToast({ title: this.vm.$lang('customerService.openFailed'), icon: 'none' }); uni.showToast({ title: '打开客服失败', icon: 'none' });
} }
}); });
} catch (e) { } catch (e) {
console.error('跳转 AI智能客服异常:', e); console.error('跳转 AI智能客服异常:', e);
uni.showToast({ title: this.vm.$lang('customerService.openFailed'), icon: 'none' }); uni.showToast({ title: '打开客服失败', icon: 'none' });
} }
} }
@@ -594,7 +582,7 @@ export class CustomerService {
* 打开客服选择对话框(预留方法) * 打开客服选择对话框(预留方法)
*/ */
openCustomerSelectPopupDialog() { openCustomerSelectPopupDialog() {
uni.showToast({ title: this.vm.$lang('customerService.developing'), icon: 'none' }); uni.showToast({ title: '客服选择功能开发中', icon: 'none' });
} }
/** /**
@@ -624,7 +612,7 @@ export class CustomerService {
if (qyweixinUrl) { if (qyweixinUrl) {
window.location.href = qyweixinUrl; window.location.href = qyweixinUrl;
} else { } else {
uni.showToast({ title: this.vm.$lang('customerService.wxworkNotConfigured'), icon: 'none' }); uni.showToast({ title: '企业微信客服未配置', icon: 'none' });
} }
} }
} else { } else {
@@ -643,7 +631,7 @@ export class CustomerService {
if (!validation.isValid) { if (!validation.isValid) {
console.error('客服配置无效:', validation.errors); console.error('客服配置无效:', validation.errors);
uni.showToast({ title: this.vm.$lang('customerService.serviceUnavailable'), icon: 'none' }); uni.showToast({ title: '客服暂不可用', icon: 'none' });
return; return;
} }
@@ -660,14 +648,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: this.vm.$lang('customerService.wxworkConfigIncomplete'), icon: 'none' }); uni.showToast({ title: '企业微信配置不完整', 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: this.vm.$lang('customerService.wxworkLinkNotConfigured'), icon: 'none' }); uni.showToast({ title: '企业微信链接未配置', icon: 'none' });
return; return;
} }
// #endif // #endif
@@ -676,12 +664,12 @@ export class CustomerService {
// 直接调用统一处理方法,由 CustomerService 内部根据配置路由 // 直接调用统一处理方法,由 CustomerService 内部根据配置路由
try { try {
this.handleCustomerClick({ this.handleCustomerClick({
sendMessageTitle: options.sendMessageTitle || this.vm.$lang('customerService.fromFloatButton'), sendMessageTitle: options.sendMessageTitle || '来自悬浮按钮的咨询',
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: this.vm.$lang('customerService.openFailed'), icon: 'none' }); uni.showToast({ title: '打开客服失败', icon: 'none' });
} }
} }
} }

View File

@@ -1,7 +1,6 @@
import WxMap from 'common/js/map-wx-jssdk.js'; import WxMap from 'common/js/map-wx-jssdk.js';
import Config from '@/common/js/config.js'; import Config from '@/common/js/config.js';
import util from '@/common/js/util.js'; import util from '@/common/js/util.js';
import { classifyHttpError, httpErrorKey } from '@/common/js/http-error.js';
let systemInfo = util.getDeviceInfo(); let systemInfo = util.getDeviceInfo();
@@ -46,21 +45,10 @@ export default {
diyRoute: '', // 页面路由 diyRoute: '', // 页面路由
openBottomNav: false, openBottomNav: false,
isShowCopyRight: false, isShowCopyRight: false,
// getDiyInfo 节流
diyInfoLoading: false, // 是否正在请求
lastDiyInfoTime: 0, // 上次成功加载的时间戳
lastDiyInfoLang: '', // 上次加载时的语言,语言切换时强制刷新
diyInfoTtl: 3 * 60 * 1000, // 3分钟内不重复请求
// diy 数据网络加载失败时的页面内错误提示(比 showModal 在各端更可靠)
diyLoadError: false,
diyLoadErrorMsg: '',
diyLoadErrorUrl: '', // 出错的网络请求地址
//启动广告 //启动广告
adv: {}, adv:{},
}; };
}, },
onLoad(option) { onLoad(option) {
@@ -123,10 +111,10 @@ export default {
// 关闭定位 // 关闭定位
this.enterDefaultStore(); this.enterDefaultStore();
} }
}, },
onShow() { onShow() {
this.init(); this.init();
}, },
onHide() { onHide() {
@@ -211,12 +199,12 @@ export default {
} }
}, },
methods: { methods: {
play() { play(){
}, },
async init() { async init() {
// 定位信息过期后,重新获取定位 // 定位信息过期后,重新获取定位
if (this.mapConfig.wap_is_open == 1 && this.locationStorage && this.locationStorage.is_expired) { if(this.mapConfig.wap_is_open == 1 && this.locationStorage && this.locationStorage.is_expired) {
this.$util.getLocation({ this.$util.getLocation({
fail: (res) => { fail: (res) => {
// 拒绝定位,进入默认总店 // 拒绝定位,进入默认总店
@@ -232,7 +220,6 @@ export default {
} }
} }
console.log('[DIY][init] calling getDiyInfo, storeToken=', !!this.storeToken);
await this.getDiyInfo(); await this.getDiyInfo();
//获取启动广告 //获取启动广告
await this.getDiyAdv(); await this.getDiyAdv();
@@ -290,7 +277,7 @@ export default {
}, 50); }, 50);
// #endif // #endif
}, },
async getDiyAdv() { async getDiyAdv(){
//启动广告 //启动广告
let res = await this.$api.sendRequest({ let res = await this.$api.sendRequest({
url: '/api/diyview/getstartadv', url: '/api/diyview/getstartadv',
@@ -299,13 +286,13 @@ export default {
}); });
this.adv = res.value this.adv = res.value
// 弹框形式,首次弹出 1,每次弹出 0 // 弹框形式,首次弹出 1,每次弹出 0
if (this.adv.advshow == 1) { if(this.adv.advshow == 1){
setTimeout(() => { setTimeout(() => {
if (res.value.advtype == 1) { if (res.value.advtype == 1) {
var popwindow_count = uni.getStorageSync(this.id + this.name + '_popwindow_count'); var popwindow_count = uni.getStorageSync(this.id + this.name + '_popwindow_count');
if ((this.$refs.uniPopupWindow && popwindow_count == '') || ( if ((this.$refs.uniPopupWindow && popwindow_count == '') || (
this.$refs.uniPopupWindow && popwindow_count == 1)) { this.$refs.uniPopupWindow && popwindow_count == 1)) {
this.$refs.uniPopupWindow.open(); this.$refs.uniPopupWindow.open();
uni.setStorageSync(this.id + this.name + '_popwindow_count', 1); uni.setStorageSync(this.id + this.name + '_popwindow_count', 1);
} }
@@ -315,165 +302,62 @@ export default {
} }
}, 500); }, 500);
} }
}, },
// 无法从网络获取 diy 数据时:在页面内渲染错误横幅(各端可靠、一定可见) async getDiyInfo() {
// 同时通过 uni.$emit 通知 splash-state 关闭启动屏 (否则 strict 模式永远不关) let res = await this.$api.sendRequest({
// @param {Object|string} [err] 网络异常对象 {errMsg, statusCode} / 服务端消息字符串 url: '/api/diyview/info',
// @param {string} [url] 出错的请求地址(完整 URL),用于横幅展示 data: {
// @param {string} [errorType] 错误类型: 'network' | 'no-response' | 'business' id: this.id,
_showDiyLoadError(err, url, errorType) { name: this.name,
this.diyLoadErrorMsg = this._buildDiyErrorMsg(err); en_type:uni.getStorageSync("lang"),//获取语言底部
this.diyLoadErrorUrl = url || ''; },
this.diyLoadError = true; async: false
// 通知 splash: diy 加载失败, 启动屏应该让位给错误横幅 });
// 用 uni.$emit 而非直接 import splash-state, 避免循环依赖 if (res.code != 0 || !res.data) {
// reason 拼成 'diy-{errorType}-error' 方便业务方区分 (splash:diy-error 事件)
const reason = errorType ? `diy-${errorType}-error` : 'diy-load-error'
try { uni.$emit && uni.$emit('diy:load-error', { reason, errorType, err, url }); } catch (e) { }
},
// 根据错误信息组织更详细的提示文案
// 说明:remote-only 模式下 $lang 可能返回空串,故统一用 `|| 中文兜底` 保证非空
_buildDiyErrorMsg(err) {
const info = classifyHttpError(err);
// 服务端明确返回的业务消息(字符串):直接透传
if (info.type === 'business') return info.raw;
const key = httpErrorKey(info.type);
let reason = this.$lang(key);
// HTTP 状态码类错误:把 statusCode 拼到 reason 后面
if (info.statusCode) reason += '(' + info.statusCode + ')';
// empty / unknown 不走模板,直接返回通用网络异常
if (info.type === 'empty' || info.type === 'unknown') return reason;
const tpl = this.$lang('diy.loadFailTpl', { reason });
return tpl;
},
// 错误横幅「重试」入口
retryDiyInfo() {
this.diyLoadError = false;
this.diyLoadErrorMsg = '';
this.diyLoadErrorUrl = '';
this.getDiyInfo(true);
},
async getDiyInfo(force = false) {
// 节流:正在请求 / N 秒内已加载过 / 语言未变 -> 跳过
const now = Date.now();
const currentLang = uni.getStorageSync("lang") || '';
console.log('[DIY][getDiyInfo] start', 'force=', force, 'id=', this.id, 'name=', this.name, 'lang=', currentLang, 'loading=', this.diyInfoLoading, 'lastAt=', this.lastDiyInfoTime, 'lastLang=', this.lastDiyInfoLang);
if (!force) {
if (this.diyInfoLoading) {
console.log('[DIY][getDiyInfo] skip: already loading');
return;
}
if (this.lastDiyInfoTime && (now - this.lastDiyInfoTime) < this.diyInfoTtl
&& this.lastDiyInfoLang === currentLang) {
console.log('[DIY][getDiyInfo] skip: throttled by ttl');
return;
}
}
this.diyInfoLoading = true;
let res;
// 出错时用于展示的完整请求地址(Request URL),与 http.js 拼接/归一化方式保持一致
const diyInfoUrl = '/api/diyview/info';
const diyInfoFullUrl = ((Config.baseUrl || '') + diyInfoUrl).replace(/(?<!:)\/+/g, '/');
try {
res = await this.$api.sendRequest({
url: diyInfoUrl,
data: {
id: this.id,
name: this.name,
en_type: currentLang,
},
async: false
});
} catch (e) {
console.error('[DIY][getDiyInfo] request failed', e);
if (this.$refs.loadingCover) this.$refs.loadingCover.hide();
this.diyInfoLoading = false;
// 无法从网络获取数据时,页面内显示错误横幅并提供重试(带详细原因 + 请求地址)
// errorType='network': 网络异常 (uni.request catch)
this._showDiyLoadError(e, diyInfoFullUrl, 'network');
return;
}
this.diyInfoLoading = false;
console.log('[DIY][getDiyInfo] got response', 'code=', res && res.code, 'hasData=', !!(res && res.data), 'valueType=', res && res.data && typeof res.data.value, 'valueLen=', res && res.data && (typeof res.data.value === 'string' ? res.data.value.length : (res.data.value ? res.data.value.length : null)));
if (!res || res.code != 0 || !res.data) {
console.warn('[DIY][getDiyInfo] invalid response', JSON.stringify(res));
if (this.$refs.loadingCover) this.$refs.loadingCover.hide(); if (this.$refs.loadingCover) this.$refs.loadingCover.hide();
// 完全没有拿到网络响应,视为无法从网络获取数据,页面内显示错误横幅 if (res.code == -3) {
if (!res) {
// errorType='no-response': 完全没有 res 对象
this._showDiyLoadError(null, diyInfoFullUrl, 'no-response');
// 保持原有数据结构,仅清空 value,避免鸿蒙下重新布局
this.diyData = { ...(this.diyData || {}), value: [] };
return;
}
if (res && res.code == -3) {
this.$util.showToast({ this.$util.showToast({
title: res.message title: res.message
}); });
// 保持原有数据结构,仅清空 value,避免鸿蒙下重新布局 this.diyData = {};
this.diyData = { ...(this.diyData || {}), value: [] };
return; return;
} }
// 拿到响应但业务失败 / 无数据(如接口 404 返回 200+错误码、code!=0) this.$util.showToast({
// 同样视为无法获取到 diy 数据,页面内显示错误横幅 title: '未配置自定义页面数据'
// errorType='business': 业务失败 (code!=0 / 消息提示) });
this._showDiyLoadError(res && res.message, diyInfoFullUrl, 'business'); this.diyData = {};
// 保持原有数据结构,仅清空 value,避免鸿蒙下重新布局
this.diyData = { ...(this.diyData || {}), value: [] };
return; return;
} }
this.lastDiyInfoTime = now;
this.lastDiyInfoLang = currentLang;
// 成功加载后清除错误提示
this.diyLoadError = false;
this.diyLoadErrorMsg = '';
this.diyLoadErrorUrl = '';
let diyDataValue = res.data; let diyDataValue = res.data;
if (diyDataValue.value) { if (diyDataValue.value) {
try { this.diyData = JSON.parse(diyDataValue.value);
this.diyData = JSON.parse(diyDataValue.value);
} catch (parseErr) {
console.error('[DIY][getDiyInfo] JSON.parse(value) failed', parseErr, 'value preview=', String(diyDataValue.value).slice(0, 200));
throw parseErr;
}
console.log('[DIY][getDiyInfo] parsed diyData', 'globalKeys=', this.diyData && this.diyData.global ? Object.keys(this.diyData.global) : null, 'valueCount=', this.diyData && this.diyData.value && this.diyData.value.length, 'topIndexValue before=', this.topIndexValue);
// 导航栏标题要根据语言环境切换 // 导航栏标题要根据语言环境切换
// 优先使用 title_map 多语言 map,没有则回退到 title / en_title const title = this.isEnEnv ? this.diyData?.global?.en_title : this.diyData?.global?.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;
this.setPublicShare(); this.setPublicShare();
/* if (this.diyData.global.popWindow && this.diyData.global.popWindow.imageUrl) { /* if (this.diyData.global.popWindow && this.diyData.global.popWindow.imageUrl) {
// 弹框形式,首次弹出 1,每次弹出 0 // 弹框形式,首次弹出 1,每次弹出 0
setTimeout(() => { setTimeout(() => {
if (this.diyData.global.popWindow.count == 1) { if (this.diyData.global.popWindow.count == 1) {
var popwindow_count = uni.getStorageSync(this.id + this.name + '_popwindow_count'); var popwindow_count = uni.getStorageSync(this.id + this.name + '_popwindow_count');
if ((this.$refs.uniPopupWindow && popwindow_count == '') || ( if ((this.$refs.uniPopupWindow && popwindow_count == '') || (
this.$refs.uniPopupWindow && popwindow_count == 1)) { this.$refs.uniPopupWindow && popwindow_count == 1)) {
this.$refs.uniPopupWindow.open();
uni.setStorageSync(this.id + this.name + '_popwindow_count', 1);
}
} else if (this.diyData.global.popWindow.count == 0) {
this.$refs.uniPopupWindow.open(); this.$refs.uniPopupWindow.open();
uni.setStorageSync(this.id + this.name + '_popwindow_count', 0); uni.setStorageSync(this.id + this.name + '_popwindow_count', 1);
} }
}, 500); } else if (this.diyData.global.popWindow.count == 0) {
}*/ this.$refs.uniPopupWindow.open();
uni.setStorageSync(this.id + this.name + '_popwindow_count', 0);
}
}, 500);
}*/
// 修改diy数据结构排序 // 修改diy数据结构排序
let searchIndex = -1; let searchIndex = -1;
@@ -537,9 +421,6 @@ export default {
this.openBottomNav = this.diyData.global.openBottomNav; this.openBottomNav = this.diyData.global.openBottomNav;
} }
this.isShowCopyRight = true; this.isShowCopyRight = true;
console.log('[DIY][getDiyInfo] done', 'topIndexValue after=', this.topIndexValue && this.topIndexValue.componentName, 'valueCount=', this.diyData.value.length, 'openBottomNav=', this.openBottomNav, 'isShowCopyRight=', this.isShowCopyRight);
} else {
console.warn('[DIY][getDiyInfo] no value in res.data', JSON.stringify(diyDataValue).slice(0, 200));
} }
}, },
closePopupWindow() { closePopupWindow() {
@@ -679,7 +560,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.$lang('diy.locationNotAvailable'); this.currentPosition = '未获取到定位';
} }
} }
}); });
@@ -691,7 +572,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 = this.$lang('diy.locationNotAvailable'); if (this.currentPosition == '') this.currentPosition = '未获取到定位';
this.openChooseStorePopup(); this.openChooseStorePopup();
} }
}, },
@@ -701,7 +582,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.$langConfig.getField(this.diyData.global, 'title'), title: 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) : ''

View File

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

View File

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

View File

@@ -12,13 +12,57 @@
* @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 = Platform.detect() this.platform = this.detectPlatform()
}
// 检测平台
detectPlatform() {
// #ifdef H5
return 'h5'
// #endif
// #ifdef MP-WEIXIN
return 'weapp'
// #endif
// #ifdef MP-ALIPAY
return 'alipay'
// #endif
// #ifdef MP-BAIDU
return 'baidu'
// #endif
// #ifdef MP-TOUTIAO
return 'toutiao'
// #endif
// #ifdef MP-QQ
return 'qq'
// #endif
// #ifdef MP-KUAISHOU
return 'kuaishou'
// #endif
// #ifdef MP-JD
return 'jd'
// #endif
// #ifdef MP-360
return '360'
// #endif
// #ifdef MP-XHS
return 'xhs'
// #endif
return 'unknown'
} }
// 设置 DOM 桥接 // 设置 DOM 桥接

View File

@@ -44,7 +44,7 @@ export class EventSafety {
// 安全的方法 // 安全的方法
matches: (selector) => EventSafety.safeMatches(target, selector), matches: (selector) => EventSafety.safeMatches(target, selector),
// 数据集 // 数据集
dataset: target?.dataset || {} dataset: target.dataset || {}
} }
return safeTarget return safeTarget

View File

@@ -1,112 +0,0 @@
/**
* 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;
}
}
};

View File

@@ -1,83 +1,14 @@
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,避免空翻译写入标题等 // 刷新多语言
// H5 不受影响(main.js 已 await boot 后才 $mount) this.$langConfig.refresh();
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;
}, },
@@ -91,28 +22,6 @@ 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;
}, },
@@ -172,7 +81,7 @@ export default {
return this.$store.state.diySeckillInterval; return this.$store.state.diySeckillInterval;
}, },
tabBarHeight() { tabBarHeight() {
return this.shouldShowTabBar ? this.$store.state.tabBarHeight : '0rpx'; return this.$store.state.tabBarHeight;
}, },
mapConfig() { mapConfig() {
return this.$store.state.mapConfig; return this.$store.state.mapConfig;
@@ -200,13 +109,6 @@ 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) {
@@ -253,53 +155,6 @@ 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: {

View File

@@ -79,127 +79,114 @@ export default {
}, },
methods: { methods: {
// 处理商品详情数据 // 处理商品详情数据
async handleGoodsSkuData() { handleGoodsSkuData() {
// 鸿蒙兼容: 外层包 try/catch, 任何同步抛错都不会导致 page 整体空白 // this.navbarData.title = this.goodsSkuDetail.goods_name.length > 9 ? this.goodsSkuDetail.goods_name.substr(0, 9) + "..." : this.goodsSkuDetail.goods_name;
try { //设置标题
if (this.goodsSkuDetail.config) { // this.$langConfig.title(this.navbarData.title);
this.navbarData.navBarSwitch = this.goodsSkuDetail.config.nav_bar_switch; if (this.goodsSkuDetail.config) {
this.navbarData.navBarSwitch = this.goodsSkuDetail.config.nav_bar_switch;
}
this.whetherCollection = this.goodsSkuDetail.is_collect; // 用户关注商品状态
this.modifyGoodsInfo();
// 初始化商品详情视图数据
if (this.$refs.goodsDetailView) this.$refs.goodsDetailView.init({
sku_id: this.skuId,
goods_id: this.goodsSkuDetail.goods_id,
preview: this.preview,
source_member: this.source_member,
posterParams: this.posterParams,
posterApi: this.posterApi,
shareUrl: this.shareUrl,
goodsRoute: this.goodsRoute,
isVirtual: this.goodsSkuDetail.is_virtual,
deliveryType: this.goodsSkuDetail.express_type,
whetherCollection: this.goodsSkuDetail.is_collect,
evaluateConfig: this.goodsSkuDetail.evaluate_config,
evaluateList: this.goodsSkuDetail.evaluate_list,
evaluateCount: this.goodsSkuDetail.evaluate_count
});
//媒体
if (this.goodsSkuDetail.video_url) this.switchMedia = "video";
if (!Array.isArray(this.goodsSkuDetail.sku_images)) {
if (this.goodsSkuDetail.sku_images) this.goodsSkuDetail.sku_images = this.goodsSkuDetail.sku_images.split(",");
else this.goodsSkuDetail.sku_images = [];
}
// 多规格时合并主图
if (this.goodsSkuDetail.goods_spec_format && this.goodsSkuDetail.goods_image) {
if (!Array.isArray(this.goodsSkuDetail.goods_image)) this.goodsSkuDetail.goods_image = this.goodsSkuDetail.goods_image.split(",");
this.goodsSkuDetail.sku_images = this.goodsSkuDetail.goods_image.concat(this.goodsSkuDetail.sku_images);
}
let maxHeight = '';
let systemInfo = uni.getSystemInfoSync();
this.goodsSkuDetail.goods_image_list.forEach((item, index) => {
if (typeof item.pic_spec == "string")
item.pic_spec = item.pic_spec.split('*');
let ratio = item.pic_spec[0] / systemInfo.windowWidth;
item.pic_spec[0] = item.pic_spec[0] / ratio;
item.pic_spec[1] = item.pic_spec[1] / ratio;
if (!maxHeight || maxHeight > item.pic_spec[1]) {
maxHeight = item.pic_spec[1];
} }
});
this.goodsSkuDetail.swiperHeight = maxHeight + 'px';
this.whetherCollection = this.goodsSkuDetail.is_collect; // 用户关注商品状态 this.goodsSkuDetail.unit = this.goodsSkuDetail.unit || "件";
this.modifyGoodsInfo(); // 当前商品SKU规格
if (this.goodsSkuDetail.sku_spec_format) this.goodsSkuDetail.sku_spec_format = JSON.parse(this.goodsSkuDetail.sku_spec_format);
// 初始化商品详情视图数据 // 商品属性
try { if (this.goodsSkuDetail.goods_attr_format) {
if (this.$refs && this.$refs.goodsDetailView) { let goods_attr_format = JSON.parse(this.goodsSkuDetail.goods_attr_format);
this.$refs.goodsDetailView.init({ this.goodsSkuDetail.goods_attr_format = this.$util.unique(goods_attr_format, "attr_id");
sku_id: this.skuId, for (var i = 0; i < this.goodsSkuDetail.goods_attr_format.length; i++) {
goods_id: this.goodsSkuDetail.goods_id, for (var j = 0; j < goods_attr_format.length; j++) {
preview: this.preview, if (this.goodsSkuDetail.goods_attr_format[i].attr_id == goods_attr_format[j].attr_id && this.goodsSkuDetail.goods_attr_format[i].attr_value_id != goods_attr_format[j].attr_value_id) {
source_member: this.source_member, this.goodsSkuDetail.goods_attr_format[i].attr_value_name += "、" + goods_attr_format[j].attr_value_name;
posterParams: this.posterParams,
posterApi: this.posterApi,
shareUrl: this.shareUrl,
goodsRoute: this.goodsRoute,
isVirtual: this.goodsSkuDetail.is_virtual,
deliveryType: this.goodsSkuDetail.express_type,
whetherCollection: this.goodsSkuDetail.is_collect,
evaluateConfig: this.goodsSkuDetail.evaluate_config,
evaluateList: this.goodsSkuDetail.evaluate_list,
evaluateCount: this.goodsSkuDetail.evaluate_count
});
}
} catch (e) {
console.error('goodsDetailView.init failed:', e);
}
//媒体
if (this.goodsSkuDetail.video_url) this.switchMedia = "video";
if (!Array.isArray(this.goodsSkuDetail.sku_images)) {
if (this.goodsSkuDetail.sku_images) this.goodsSkuDetail.sku_images = this.goodsSkuDetail.sku_images.split(",");
else this.goodsSkuDetail.sku_images = [];
}
// 多规格时合并主图
if (this.goodsSkuDetail.goods_spec_format && this.goodsSkuDetail.goods_image) {
if (!Array.isArray(this.goodsSkuDetail.goods_image)) this.goodsSkuDetail.goods_image = this.goodsSkuDetail.goods_image.split(",");
this.goodsSkuDetail.sku_images = this.goodsSkuDetail.goods_image.concat(this.goodsSkuDetail.sku_images);
}
let maxHeight = '';
let systemInfo = uni.getSystemInfoSync();
this.goodsSkuDetail.goods_image_list.forEach((item, index) => {
if (typeof item.pic_spec == "string")
item.pic_spec = item.pic_spec.split('*');
let ratio = item.pic_spec[0] / systemInfo.windowWidth;
item.pic_spec[0] = item.pic_spec[0] / ratio;
item.pic_spec[1] = item.pic_spec[1] / ratio;
if (!maxHeight || maxHeight > item.pic_spec[1]) {
maxHeight = item.pic_spec[1];
}
});
this.goodsSkuDetail.swiperHeight = maxHeight + 'px';
this.goodsSkuDetail.unit = this.goodsSkuDetail.unit || this.$lang('unit.piece');
// 当前商品SKU规格
if (this.goodsSkuDetail.sku_spec_format) this.goodsSkuDetail.sku_spec_format = JSON.parse(this.goodsSkuDetail.sku_spec_format);
// 商品属性
if (this.goodsSkuDetail.goods_attr_format) {
let goods_attr_format = JSON.parse(this.goodsSkuDetail.goods_attr_format);
this.goodsSkuDetail.goods_attr_format = this.$util.unique(goods_attr_format, "attr_id");
for (var i = 0; i < this.goodsSkuDetail.goods_attr_format.length; i++) {
for (var j = 0; j < goods_attr_format.length; j++) {
if (this.goodsSkuDetail.goods_attr_format[i].attr_id == goods_attr_format[j].attr_id && this.goodsSkuDetail.goods_attr_format[i].attr_value_id != goods_attr_format[j].attr_value_id) {
this.goodsSkuDetail.goods_attr_format[i].attr_value_name += "、" + goods_attr_format[j].attr_value_name;
}
} }
} }
} }
}
// 商品SKU格式 // 商品SKU格式
if (this.goodsSkuDetail.goods_spec_format) this.goodsSkuDetail.goods_spec_format = JSON.parse(this.goodsSkuDetail.goods_spec_format); if (this.goodsSkuDetail.goods_spec_format) this.goodsSkuDetail.goods_spec_format = JSON.parse(this.goodsSkuDetail.goods_spec_format);
// 商品详情 // 商品详情
if (this.goodsSkuDetail.goods_content) this.goodsSkuDetail.goods_content = (this.goodsSkuDetail.goods_content); if (this.goodsSkuDetail.goods_content) this.goodsSkuDetail.goods_content = (this.goodsSkuDetail.goods_content);
// if (this.goodsSkuDetail.goods_content) this.goodsSkuDetail.goods_content = htmlParser(this.goodsSkuDetail.goods_content); // if (this.goodsSkuDetail.goods_content) this.goodsSkuDetail.goods_content = htmlParser(this.goodsSkuDetail.goods_content);
//商品服务 //商品服务
if (this.goodsSkuDetail.goods_service) { if (this.goodsSkuDetail.goods_service) {
for (let i in this.goodsSkuDetail.goods_service) { for (let i in this.goodsSkuDetail.goods_service) {
this.goodsSkuDetail.goods_service[i]['icon'] = this.goodsSkuDetail.goods_service[i]['icon'] ? JSON.parse(this.goodsSkuDetail.goods_service[i]['icon']) : ''; this.goodsSkuDetail.goods_service[i]['icon'] = this.goodsSkuDetail.goods_service[i]['icon'] ? JSON.parse(this.goodsSkuDetail.goods_service[i]['icon']) : '';
}
} }
}
this.contactData = { this.contactData = {
title: this.goodsSkuDetail.sku_name, title: this.goodsSkuDetail.sku_name,
path: this.shareUrl, path: this.shareUrl,
img: this.$util.img(this.goodsSkuDetail.sku_image, { img: this.$util.img(this.goodsSkuDetail.sku_image, {
size: 'big' size: 'big'
}) })
}; };
try { if (this.$refs.goodsPromotion) this.$refs.goodsPromotion.refresh(this.goodsSkuDetail.goods_promotion);
if (this.$refs && this.$refs.goodsPromotion) {
this.$refs.goodsPromotion.refresh(this.goodsSkuDetail.goods_promotion);
}
} catch (e) { console.error('goodsPromotion refresh failed:', e); }
// 性能优化: 商品表单(留言表单)仅在商品详情打开"立即留言"弹窗时才需要, if (this.goodsRoute != '/pages_goods/detail') this.setPublicShare();
// 不再阻塞首次渲染。改为在后台并发请求, 用户真正打开弹窗时数据已就绪。
try { // this.getBarrageData();
this._goodsFormPromise = this.getGoodsForm(); if (this.addonIsExist.form) {
} catch (e) { this.getGoodsForm();
console.error('getGoodsForm kicked off failed:', e);
}
} catch (e) {
console.error('handleGoodsSkuData failed:', e);
} }
}, },
/** /**
@@ -212,7 +199,7 @@ export default {
if (this.$refs.goodsDetailView) { if (this.$refs.goodsDetailView) {
// 初始化商品详情视图数据 // 初始化商品详情视图数据
this.goodsSkuDetail.unit = this.goodsSkuDetail.unit || this.$lang('unit.piece'); this.goodsSkuDetail.unit = this.goodsSkuDetail.unit || "件";
// 解决轮播图数量不一致时,切换到第一个 // 解决轮播图数量不一致时,切换到第一个
if (this.swiperCurrent > this.goodsSkuDetail.sku_images.length) { if (this.swiperCurrent > this.goodsSkuDetail.sku_images.length) {
@@ -334,76 +321,17 @@ 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。
*/ */
async getGoodsForm() { getGoodsForm() {
// 防御: sku 切换/数据未到时 goods_id 可能为 0/空, 此时直接走空数据分支, this.$api.sendRequest({
// 避免后端拿到非法 goods_id 导致 4xx/5xx 后还把脏数据塞给前端。 url: "/form/api/form/goodsform",
if (!this.goodsSkuDetail || !this.goodsSkuDetail.goods_id) { data: {
const emptyFn = () => { goods_id: this.goodsSkuDetail.goods_id
this.$set(this.goodsSkuDetail, 'goods_form', []); },
this.$set(this.goodsSkuDetail, 'goods_form_config', {}); success: res => {
this.$set(this.goodsSkuDetail, 'goods_form_name', ''); if (res.code == 0 && res.data) this.$set(this.goodsSkuDetail, 'goods_form', res.data);
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);
};
emptyFn();
return;
}
let res;
try {
res = await this.$api.sendRequest({
url: "/form/api/form/goodsform",
data: {
goods_id: this.goodsSkuDetail.goods_id,
format: 'object'
},
async: false
});
} catch (e) {
console.warn('getGoodsForm request failed', e);
res = null;
}
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)
);
} }
}, },
/** /**

View File

@@ -1,101 +0,0 @@
/**
* 通用网络/接口错误分类器
*
* 适用场景:
* - uniapp 各端统一错误分类(diy.js / 商品 / 订单 / 自定义页面等)
* - 任意传入 {statusCode, errMsg, message} 形式错误对象的位置
*
* 设计要点:
* 1) 与 Vue / $lang 解耦:不调用任何 i18n 函数,只返回分类结果 + 原始错误字段
* 调用方拿到 type 后,自行决定使用 $lang('http.timeout') / $lang('http.serverError')
* 或其它命名空间的文案,完全保持各模块原有的 key 命名习惯
* 2) 通用网络/接口错误统一映射到 common.http.* 命名空间:
* - http.networkError: 通用网络异常(兜底)
* - http.timeout: 请求超时
* - http.serverError: 服务器错误(5xx)
* - http.notFound: 接口不存在(404)
* - http.auth: 无访问权限(401/403)
* - http.unknown: 其他非 2xx
* 3) 兼容多种错误对象形态:
* - uniapp request: { statusCode, errMsg, data }
* - axios: { response: { status }, message }
* - fetch / 原生: { message, name }
*
* @param {Object|string} err 错误对象或后端业务消息字符串
* @returns {{ type: string, statusCode?: number, errMsg?: string, raw?: any }}
* - type 取值:
* 'business' - 后端返回的业务消息字符串(已透传到 raw)
* 'empty' - 错误对象为空
* 'notFound' - HTTP 404
* 'server' - HTTP 5xx
* 'auth' - HTTP 401 / 403
* 'request' - 其它非 2xx 状态码
* 'timeout' - errMsg 含 timeout
* 'network' - errMsg 含 connect / network / fail
* 'unknown' - 无法分类
* - statusCode: 若有则原样返回
* - errMsg: 归一后的原始消息
* - raw: 原始输入,方便调用方进一步处理
*/
export function classifyHttpError(err) {
// 1) 无错误对象
if (!err) {
return { type: 'empty', raw: err };
}
// 2) 后端直接返回的业务消息(字符串)
if (typeof err === 'string') {
return { type: 'business', raw: err };
}
// 3) 字段归一(兼容 uni / axios / 原生 Error)
const statusCode = err.statusCode
?? err.response?.status
?? err.status;
const errMsg = err.errMsg || err.message || '';
if (statusCode) {
if (statusCode === 404) return { type: 'notFound', statusCode, errMsg, raw: err };
if (statusCode >= 500) return { type: 'server', statusCode, errMsg, raw: err };
if (statusCode === 401 || statusCode === 403) return { type: 'auth', statusCode, errMsg, raw: err };
return { type: 'request', statusCode, errMsg, raw: err };
}
if (/timeout/i.test(errMsg)) {
return { type: 'timeout', errMsg, raw: err };
}
if (/(connect|network|fail)/i.test(errMsg)) {
return { type: 'network', errMsg, raw: err };
}
return { type: 'unknown', errMsg, raw: err };
}
/**
* 根据 classifyHttpError 的结果,映射到 common.http.* 命名空间的 i18n key
*
* 通用网络/接口错误统一走 http.*,调用方通过 $lang(key) 解析文案。
* 原 diy.errTimeout 这类 key 已合并到 http.*,保持项目国际化更专业。
*
* @param {string} type classifyHttpError 返回的 type
* @returns {string|null} 对应的 http.* key;type='business' 时返回 null(透传 raw)
*/
export function httpErrorKey(type) {
switch (type) {
case 'empty': return 'http.networkError';
case 'business': return null; // 透传,不用 key
case 'notFound': return 'http.notFound';
case 'server': return 'http.serverError';
case 'auth': return 'http.auth';
case 'request': return 'http.unknown';
case 'timeout': return 'http.timeout';
case 'network': return 'http.networkError';
case 'unknown':
default: return 'http.networkError';
}
}
export default {
classifyHttpError,
httpErrorKey,
};

View File

@@ -1,188 +1,65 @@
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'
const { appType, appTypeName } = Platform.getPlatformInfo(); // #ifdef H5
const app_type = Util.isWeiXin() ? 'wechat' : 'h5';
const app_type_name = Util.isWeiXin() ? '微信公众号' : 'H5';
// #endif
let _Lang = null; // #ifdef MP-WEIXIN
function getLang() { const app_type = 'weapp';
if (!_Lang) { const app_type_name = '微信小程序';
_Lang = require('./lang.js').default; // #endif
}
return _Lang;
}
const DEFAULT_TIMEOUT = 15000; // #ifdef MP-ALIPAY
const DEFAULT_MAX_RETRIES = 2; const app_type = 'aliapp';
const RETRY_DELAY_BASE = 2000; const app_type_name = '支付宝小程序';
// #endif
function _shouldRetry(errMsg) { // #ifdef MP-BAIDU
if (!errMsg) return false; const app_type = 'baiduapp';
if (errMsg === 'request:fail url not in domain list') return false; const app_type_name = '百度小程序';
if (errMsg === 'request:fail abort') return false; // #endif
const retryableErrors = [
'request:fail timeout',
'request:fail connect',
'request:fail network'
];
return retryableErrors.some(err => errMsg.startsWith(err));
}
function _classifyError(errMsg, statusCode) { // #ifdef MP-TOUTIAO
if (!errMsg && !statusCode) return 'unknown'; const app_type = 'MP-TOUTIAO';
if (errMsg === 'request:fail abort') return 'aborted'; const app_type_name = '头条小程序';
if (errMsg && errMsg.indexOf('timeout') !== -1) return 'timeout'; // #endif
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';
}
function _sleep(ms) { // #ifdef MP-QQ
return new Promise(resolve => setTimeout(resolve, ms)); const app_type = 'MP-QQ';
} const app_type_name = 'QQ小程序';
// #endif
function _makeRequest(url, method, data, header, dataType, responseType, timeout) { // #ifdef APP-PLUS
const reqId = 'req_' + Date.now() + '_' + Math.floor(Math.random() * 10000); const app_type = 'app';
const reqStart = Date.now(); const app_type_name = 'APP';
console.log('[HTTP][REQUEST]', reqId, method, url, JSON.stringify({ // #endif
data: data,
header: header,
dataType: dataType,
responseType: responseType,
timeout: timeout
}));
return new Promise((resolve, reject) => {
uni.request({
url: url,
method: method,
data: data,
header: header,
dataType: dataType,
responseType: responseType,
timeout: timeout,
success: (res) => {
console.log('[HTTP][RESPONSE]', reqId, method, url, 'statusCode=', res.statusCode, 'cost=', (Date.now() - reqStart) + 'ms', JSON.stringify(res.data));
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) => {
console.error('[HTTP][FAIL]', reqId, method, url, 'cost=', (Date.now() - reqStart) + 'ms', JSON.stringify(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 {
if (attempt > 0) {
console.log('[HTTP][RETRY]', method, url, 'attempt=', attempt, 'maxRetries=', maxRetries);
}
const result = await _makeRequest(url, method, data, header, dataType, responseType, timeout);
return result;
} catch (err) {
lastError = err;
lastStatusCode = err && err.statusCode;
console.warn('[HTTP][RETRY-FAIL]', method, url, 'attempt=', attempt, 'errMsg=', err && err.errMsg, 'statusCode=', lastStatusCode);
if (attempt >= maxRetries || !_shouldRetry(err.errMsg)) {
break;
}
const delay = RETRY_DELAY_BASE * Math.pow(2, attempt);
console.log('[HTTP][RETRY-WAIT]', method, url, 'delay=', delay + 'ms');
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: getLang().lang('http.baseUrlNotConfigured'), title: '未配置请求域名',
'icon': 'none', 'icon': 'none',
duration: 10000 duration: 10000
}); });
return; return;
} }
const _isRemoteOnly = getLang().isRemoteOnly && getLang().isRemoteOnly(); var method = params.data != undefined ? 'POST' : 'GET', // 请求方式
const _bootDone = getLang().isBootCompleted && getLang().isBootCompleted(); url = (Config.baseUrl + params.url).replace(/(?<!:)\/+/g, '/'), // 请求路径
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: appType, app_type,
app_type_name: appTypeName app_type_name
}; };
// token
data.token = store.state.token || ''; data.token = store.state.token || '';
data.uniacid = uni.getStorageSync('uniacid') || Config.uniacid; data.uniacid = uni.getStorageSync('uniacid') || Config.uniacid; // 从缓存中获取uniacid,或使用默认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;
@@ -192,38 +69,126 @@ 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) //同步
.then(res => { return new Promise((resolve, reject) => {
typeof params.complete == 'function' && params.complete(res); uni.request({
return res; url: url,
}) method: method,
.catch(err => { data: data,
typeof params.complete == 'function' && params.complete(); header: params.header || {
throw err; // 'Accept': 'application/json',
'content-type': 'application/x-www-form-urlencoded;application/json'
},
dataType: params.dataType || 'json',
responseType: params.responseType || 'text',
success: (res) => {
// try {
// res.data = JSON.parse(res.data);
// } catch (e) {
// //TODO handle the exception
// console.log('api error:', e);
// }
if (res.data.code == -3 && store.state.siteState > 0) {
store.commit('setSiteState', -3);
Util.redirectTo('/pages_tool/storeclose/storeclose', {}, 'reLaunch');
return;
}
if (res.data.refreshtoken) {
store.commit('setToken', res.data.refreshtoken);
}
if (res.data.code == -10009 || res.data.code == -10010) {
store.commit('setToken', '');
store.commit('setMemberInfo', '');
}
resolve(res.data);
},
fail: (res) => {
if (res.errMsg && res.errMsg == 'request:fail url not in domain list') {
uni.showToast({
title: Config.baseUrl + '不在request 合法域名列表中',
'icon': 'none',
duration: 10000
});
return;
}
reject(res);
},
complete: (res) => {
if ((res.errMsg && res.errMsg != "request:ok") || (res.statusCode && [200, 500].indexOf(res.statusCode) == -1)) {
uni.showToast({
title: Config.baseUrl + '请求失败',
'icon': 'none',
duration: 10000
});
return;
}
reject(res.data);
}
}); });
});
} else { } else {
_requestWithRetry(params, url, method, data, header, dataType, responseType) //异步
.then(res => { uni.request({
typeof params.success == 'function' && params.success(res); url: url,
typeof params.complete == 'function' && params.complete(res); method: method,
}) data: data,
.catch(err => { header: params.header || {
typeof params.fail == 'function' && params.fail(err); // 'Accept': 'application/json',
typeof params.complete == 'function' && params.complete(); 'content-type': 'application/x-www-form-urlencoded;application/json'
}); },
dataType: params.dataType || 'json',
responseType: params.responseType || 'text',
success: (res) => {
// try {
// res.data = JSON.parse(res.data);
// } catch (e) {
// //TODO handle the exception
// console.log('api error:', e);
// }
if (res.data.code == -3 && store.state.siteState > 0) {
store.commit('setSiteState', -3);
Util.redirectTo('/pages_tool/storeclose/storeclose', {}, 'reLaunch');
return;
}
if (res.data.refreshtoken) {
store.commit('setToken', res.data.refreshtoken);
}
if (res.data.code == -10009 || res.data.code == -10010) {
store.commit('setToken', '');
store.commit('setMemberInfo', '');
}
typeof params.success == 'function' && params.success(res.data);
},
fail: (res) => {
if (res.errMsg && res.errMsg == 'request:fail url not in domain list') {
uni.showToast({
title: Config.baseUrl + '不在request 合法域名列表中',
'icon': 'none',
duration: 10000
});
return;
}
typeof params.fail == 'function' && params.fail(res);
},
complete: (res) => {
if ((res.errMsg && res.errMsg != "request:ok") || (res.statusCode && [200, 500].indexOf(res.statusCode) == -1)) {
uni.showToast({
title: Config.baseUrl + '请求失败',
'icon': 'none',
duration: 10000
});
return;
}
typeof params.complete == 'function' && params.complete(res.data);
}
});
} }
}, },
uploadBase64(params) { uploadBase64(params) {
console.log('[HTTP][REQUEST] uploadBase64', Config.baseUrl + '/api/upload/headimgBase64');
uni.request({ uni.request({
url: Config.baseUrl + '/api/upload/headimgBase64', url: Config.baseUrl + '/api/upload/headimgBase64',
method: 'POST', method: 'POST',
@@ -231,24 +196,21 @@ export default {
'content-type': 'application/x-www-form-urlencoded;application/json' 'content-type': 'application/x-www-form-urlencoded;application/json'
}, },
data: { data: {
app_type: appType, app_type,
app_type_name: appTypeName, app_type_name,
images: params.base64 images: params.base64
}, },
dataType: 'json', dataType: 'json',
responseType: 'text', responseType: 'text',
success: res => { success: res => {
console.log('[HTTP][RESPONSE] uploadBase64', 'statusCode=', res.statusCode, JSON.stringify(res.data));
typeof params.success == 'function' && params.success(res.data); typeof params.success == 'function' && params.success(res.data);
}, },
fail: () => { fail: () => {
console.error('[HTTP][FAIL] uploadBase64', JSON.stringify(res));
typeof params.fail == 'function' && params.fail(res); typeof params.fail == 'function' && params.fail(res);
} }
}); });
}, },
pullImage(params) { pullImage(params) {
console.log('[HTTP][REQUEST] pullImage', Config.baseUrl + '/api/upload/headimgPull', 'path=', params.path);
uni.request({ uni.request({
url: Config.baseUrl + '/api/upload/headimgPull', url: Config.baseUrl + '/api/upload/headimgPull',
method: 'POST', method: 'POST',
@@ -256,42 +218,37 @@ export default {
'content-type': 'application/x-www-form-urlencoded;application/json' 'content-type': 'application/x-www-form-urlencoded;application/json'
}, },
data: { data: {
app_type: appType, app_type,
app_type_name: appTypeName, app_type_name,
path: params.path path: params.path
}, },
dataType: 'json', dataType: 'json',
responseType: 'text', responseType: 'text',
success: res => { success: res => {
console.log('[HTTP][RESPONSE] pullImage', 'statusCode=', res.statusCode, JSON.stringify(res.data));
typeof params.success == 'function' && params.success(res.data); typeof params.success == 'function' && params.success(res.data);
}, },
fail: () => { fail: () => {
console.error('[HTTP][FAIL] pullImage', JSON.stringify(res));
typeof params.fail == 'function' && params.fail(res); typeof params.fail == 'function' && params.fail(res);
} }
}); });
}, },
upload(params) { upload(params) {
console.log('[HTTP][REQUEST] upload', Config.baseUrl + params.url, 'name=', params.name || 'file');
uni.uploadFile({ uni.uploadFile({
url: Config.baseUrl + params.url, url: Config.baseUrl + params.url,
filePath: params.filePath, filePath: params.filePath,
name: params.name || 'file', name: params.name || 'file',
fileType: params.fileType || 'image', fileType: params.fileType || 'image',
formData: { formData: {
app_type: appType, app_type,
app_type_name: appTypeName, app_type_name,
}, },
header: { header: {
'content-type': 'application/x-www-form-urlencoded;application/json' 'content-type': 'application/x-www-form-urlencoded;application/json'
}, },
success: (res) => { success: (res) => {
console.log('[HTTP][RESPONSE] upload', Config.baseUrl + params.url, 'statusCode=', res.statusCode, res.data);
typeof params.success == 'function' && params.success(JSON.parse(res.data)); typeof params.success == 'function' && params.success(JSON.parse(res.data));
}, },
fail: (res) => { fail: (res) => {
console.error('[HTTP][FAIL] upload', Config.baseUrl + params.url, JSON.stringify(res));
typeof params.fail == 'function' && params.fail(res); typeof params.fail == 'function' && params.fail(res);
} }
}); });

View File

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

View File

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

File diff suppressed because it is too large Load Diff

View File

@@ -7,12 +7,14 @@
*/ */
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
}; };
@@ -383,7 +385,7 @@ var Utils = {
*/ */
checkParamKeyEmpty(param, key) { checkParamKeyEmpty(param, key) {
if (!param[key]) { if (!param[key]) {
var errconf = this.buildErrorConfig(ERROR_CONF.PARAM_ERR, Lang.lang('common.mapWxJssdk.paramFormatError', { param: key })); var errconf = this.buildErrorConfig(ERROR_CONF.PARAM_ERR, ERROR_CONF.PARAM_ERR_MSG + key +'参数格式有误');
param.fail(errconf); param.fail(errconf);
param.complete(errconf); param.complete(errconf);
return true; return true;
@@ -408,7 +410,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, Lang.lang('common.mapWxJssdk.locationParamFormatError')); var errconf = this.buildErrorConfig(ERROR_CONF.PARAM_ERR, ERROR_CONF.PARAM_ERR_MSG + ' location参数格式有误');
param.fail(errconf); param.fail(errconf);
param.complete(errconf); param.complete(errconf);
return false; return false;
@@ -621,7 +623,7 @@ var Utils = {
break; break;
} }
default:{ default:{
param.complete(that.buildErrorConfig(ERROR_CONF.SYSTEM_ERR, Lang.lang('common.mapWxJssdk.systemError'))); param.complete(that.buildErrorConfig(ERROR_CONF.SYSTEM_ERR, ERROR_CONF.SYSTEM_ERR_MSG));
} }
} }
@@ -662,7 +664,7 @@ class QQMapWX {
*/ */
constructor(options) { constructor(options) {
if (!options.key) { if (!options.key) {
throw Error(Lang.lang('common.mapWxJssdk.keyCannotBeEmpty')); throw Error('key值不能为空');
} }
this.key = options.key; this.key = options.key;
}; };

View File

@@ -1,6 +1,5 @@
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({
@@ -9,7 +8,7 @@ function openMapByDefault(latitude, longitude, name) {
name: name, name: name,
fail: (e) => { fail: (e) => {
uni.showModal({ uni.showModal({
content: Lang.lang('common.map.openMapFailed') content: '打开地图失败,请稍后重试'
}) })
}, },
}) })
@@ -90,7 +89,6 @@ 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':

View File

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

View File

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

View File

@@ -1,6 +1,5 @@
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() {
@@ -261,7 +260,7 @@ export class NavigationHelper {
} }
// 显示用户友好的错误信息 // 显示用户友好的错误信息
this.showError(Lang.lang('common.navigation.serviceUnavailable')) this.showError('导航服务暂时不可用')
} }
// 显示错误提示 // 显示错误提示

View File

@@ -1,229 +0,0 @@
/**
* 统一平台检测模块
* 消除分散在 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;

View File

@@ -1,993 +0,0 @@
/**
* 全局隐私协议管理器(单例)
*
* 职责:
* 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() });
});
}
/**
* 鸿蒙元服务: 已接入平台隐私托管, 应用层不再调任何系统 API
* 仅为兼容历史代码保留此函数 (被 checkPrivacy() 调用), 内部只走 storage 路径
* @returns {Promise<{needAuthorization: boolean}>}
*/
function getHarmonyPrivacySetting() {
return new Promise((resolve) => {
resolve({ needAuthorization: !getStorageAgreed() });
});
}
/**
* 综合查询: 平台级隐私状态 + 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
// 鸿蒙元服务: 调系统 getPrivacySetting (无 API 时 getHarmonyPrivacySetting 内部回退 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 即可
// 鸿蒙元服务: 不调任何系统 API, 不弹自建弹窗 (走平台托管)
const result = _storageAgreed ? checkPrivacySync() : await checkPrivacy();
_needShow = result.needAuthorization;
_hasChecked = true;
if (!_needShow) {
return;
}
// #ifdef MP-HARMONY
// 鸿蒙元服务: 已接入平台隐私托管, 由鸿蒙系统自动弹出系统级隐私弹窗
// 应用层不再 emit 'privacy:show' 触发自建 privacy-popup.vue
// 标记已决策, 防止 consumePendingShow 兜底分支在 page mounted 时再次弹自建弹窗
_needShow = false;
_pendingShow = false;
_urlRuleDecided = true;
console.log('[privacy] MP-HARMONY: 已委托鸿蒙平台隐私托管, 不触发自建弹窗');
return;
// #endif
// 其他平台: 设置待弹窗标志 + emit 触发自建弹窗
// 已 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 (补偿弹窗)。
*
* 鸿蒙元服务(双轨制):
* 已接入平台隐私托管, 由鸿蒙系统自动弹出系统级隐私弹窗,
* 应用层不再 emit/弹自建弹窗, 兜底分支也必须返回 false, 否则会与
* 鸿蒙系统级弹窗叠加出现"多次弹出"。
* @returns {boolean} true=需要弹窗,false=不需要
*/
consumePendingShow() {
// #ifdef MP-HARMONY
// 鸿蒙元服务: 已接入平台隐私托管, 不弹自建弹窗
return false;
// #endif
if (_pendingShow && _needShow) {
_pendingShow = false;
return true;
}
// 兜底: PrivacyManager.show() 没跑过 + 用户没同意过 storage → 必须弹
// 同一次进程内只补一次,避免隐私弹窗被反复触发
// 关键: URL/路由规则已经决策过 "本次跳过" 时, 不应触发兜底弹窗 (白名单场景)
if (!_hasChecked && !_pendingShow && !_urlRuleDecided && !getStorageAgreed()) {
_pendingShow = false;
_needShow = true;
_hasChecked = true;
return true;
}
_pendingShow = false;
return false;
},
/**
* 用户同意:写 storage,标记不再弹
* 由 privacy-popup.vue 的 handleAgree 调用
*/
agree() {
try { uni.setStorageSync(STORAGE_KEY, true); } catch (e) {}
_needShow = false;
_pendingShow = false;
try { uni.$emit('privacy:agreed'); } catch (e) {}
},
/**
* 用户拒绝:不写 storage,允许下次再弹
* 由 privacy-popup.vue 的 handleDisagree 调用
*/
disagree() {
_needShow = false;
_pendingShow = false;
try { uni.$emit('privacy:disagreed'); } catch (e) {}
},
/**
* 当前是否需要弹窗(供页面查询)
* @returns {boolean}
*/
needShow() {
return _needShow;
},
/**
* 是否已执行过 check
* @returns {boolean}
*/
hasChecked() {
return _hasChecked;
},
/**
* 配置 URL/路由级别隐私弹窗规则
* @param {Object} rules
* @param {'all'|'only'|'skip'} [rules.mode='all']
* 'all' - 始终走弹窗检查(默认)
* 'only' - 白名单: 只有命中 patterns 才弹
* 'skip' - 黑名单: 命中 patterns 跳过
* @param {string[]} [rules.patterns=[]]
* 子串匹配, H5: pathname+search+hash, 小程序/鸿蒙: route+query
*/
setUrlRules(rules) {
setUrlRules(rules)
},
/**
* 当前 URL/路由规则下是否要走弹窗检查
* @param {Object} [fallback] 兜底路径(同 show 的 urlFallback)
* @returns {boolean}
*/
shouldShowByUrlRule(fallback) {
return shouldShowByUrlRule(fallback)
},
/**
* 应用本地 base + 远程 patch 的融合结果
* - patch=null/缺 → 仅应用 base (并持久化)
* - patch 存在 → 走 mergeRules 融合
* 应用后 emit 'privacy:rules-updated'
* @param {Object} base 本地基础规则 { mode, patterns }
* @param {Object} [patch] 远程下发 { mode?, patterns?, merge? }
* @returns {{ mode: string, patterns: string[], merge: string }}
*/
applyWithMerge(base, patch) {
return applyWithMerge(base, patch)
},
/**
* 仅合并 (不写入), 方便上层预览或 dry-run
* @param {Object} base
* @param {Object} patch
*/
mergeRules(base, patch) {
return mergeRules(base, patch)
},
/**
* 读取上次持久化的最终规则 (跨冷启动恢复)
* @returns {Object|null}
*/
loadPersistedRules() {
return loadPersistedRules()
},
/**
* 设置持久化 key (用于 uniacid 隔离), 由 App.vue 注入
* @param {string} key
*/
setStorageKey(key) {
if (typeof key === 'string' && key) _storageKey = key
},
/**
* 登记本地 base 规则 (由 App.vue 在启动时调用)
* 供后续远程下发时 mergeRules 读取
* @param {Object} rules
*/
setBaseRules(rules) {
if (!rules || typeof rules !== 'object') return
_baseRules = {
mode: rules.mode || 'all',
patterns: Array.isArray(rules.patterns) ? rules.patterns.slice() : [],
}
},
/**
* 读取本地 base 规则 (供 store/index.js init 远程 patch 融合)
* @returns {{ mode: string, patterns: string[] }}
*/
__getBaseRules() {
return { mode: _baseRules.mode, patterns: _baseRules.patterns.slice() }
},
/**
* 注入外部 readiness 守卫 (由 config-external.js ConfigExternal 调用)
* show() 时若无 options.readyGuard, 内部使用此 promise
* @param {Promise|Function|null} guard
*/
setExternalReadyGuard(guard) {
if (guard === null) { _externalReadyGuard = null; return }
if (guard && (typeof guard.then === 'function' || typeof guard === 'function')) {
_externalReadyGuard = guard
}
},
/**
* 注入外部 bootTimeout (由 ConfigExternal.getPrivacyBootTimeout 调用)
* @param {number} ms
*/
setExternalBootTimeout(ms) {
if (typeof ms === 'number' && ms > 0) _externalBootTimeout = ms
},
/**
* 注入 waitChannels 配置 (隐私弹窗启动期必等通道开关)
* @param {Object} channels
*/
setWaitChannels(channels) {
if (channels && typeof channels === 'object') {
_externalWaitChannels = Object.assign({}, _externalWaitChannels, channels)
}
},
/**
* 注入远程 patch 签名密钥 (与 langConfig.remote.signSecret 同构)
* 后端约定: hash_hmac('sha256', JSON.stringify(patch), secret)
* 前端: 用 btoa 模拟 (弱校验, 仅防简单篡改)
* secret='' → 跳过校验 (向后兼容)
* @param {string} secret
*/
setSignSecret(secret) {
_signSecret = (typeof secret === 'string') ? secret : ''
},
/**
* 校验远程 patch (业务侧可在 store/init 之外单独调用)
* - signSecret 未配置 → true (向后兼容)
* - patch.sign 缺失 → true (后端未启用签名)
* - patch.sign 不匹配 → false
* @param {Object} patch
* @returns {boolean}
*/
verifyRemotePatch(patch) {
return verifyRemotePatch(patch)
},
/**
* 计算给定 patch 的签名 (供调试/单元测试)
* @param {Object} patch
* @param {string} [secret] - 不传则用 _signSecret
* @returns {string}
*/
computeSign(patch, secret) {
return computeSign(patch, secret || _signSecret)
},
/**
* 读取当前生效配置 (供调试/单元测试)
*/
getReadyConfig() {
return {
readyGuard: _externalReadyGuard,
bootTimeout: _externalBootTimeout,
waitChannels: Object.assign({}, _externalWaitChannels),
}
},
};
export default PrivacyManager;

View File

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

View File

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

View File

@@ -1,698 +0,0 @@
// ============================================================
// 启动屏单例状态
//
// 设计要点:
// 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
}
// 总兜底超时档位 (show 时可覆盖):
// 12000 (12s): 默认档, 启动体验优先 (大多数网络环境够用, 略比 10s 宽松)
// 17000 (17s): 中档, 慢网/冷启动 (1s+ 启动 + 3-5s i18n 远端 + 1-3s diy 拉取 + 缓冲)
// 22000 (22s): 慢网档, 极弱网环境 (1s+ 启动 + 5-8s i18n 远端 + 3-5s diy 拉取 + 缓冲)
// 低于 12000 不推荐: 用户感知的"启动卡"窗口期不够, 但业务方仍可传 < 12000 测试用
// 业务方覆盖: splashState.show({ timeout: 17000 })
// 注意: DEFAULT_TIMEOUT 仍是兜底 (无 opts.timeout), 不能被业务方传更低
// 严防因为 timeout 太短导致用户看到白屏.
// 设计思路: 各档位比"刚好够用"多 2s 缓冲, 弱网/慢网络环境兜底更稳
const DEFAULT_TIMEOUT = 12000; // 总兜底超时 (默认 12s)
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() 自动选档)
// _networkType: 'wifi' | '4g' | '5g' | '3g' | '2g' | 'none' | 'unknown'
// _networkReady: false 表示还没检测完 (splash 显示中第一次构造时常见)
// _networkReady 后, 网络变化时通过 onNetworkStatusChange 实时更新
this._networkType = 'unknown';
this._networkReady = false;
// 启动网络检测 (异步, 不阻塞 splash 显示)
this._initNetworkDetect();
// 监听 diy 加载失败事件 (diy.js 通过 uni.$emit 触发)
// 收到后调 notifyDiyLoadError (严格模式下必须能关闭 splash)
// 解耦: splash-state 不直接 import diy.js
// 透传 reason / errorType / err / url 给业务方监听 splash:diy-error 使用
try {
if (typeof uni !== 'undefined' && uni.$on) {
uni.$on('diy:load-error', (payload) => {
try { this.notifyDiyLoadError(payload || {}) } catch (e) {}
})
}
} catch (e) {}
}
/**
* 初始化网络检测
* - 调 uni.getNetworkType 异步获取当前网络类型
* - 监听 uni.onNetworkStatusChange 实时更新
* - H5 平台降级: 调 navigator.onLine, 不支持细粒度网络类型
* 失败保护: try-catch 包, 任意失败都保持 _networkType='unknown' (不会破坏 splash)
*/
_initNetworkDetect() {
try {
// #ifdef H5
// H5 平台: navigator.onLine 是粗粒度, 只能判断在线/离线
// 仅在 navigator.onLine 是明确 boolean (true/false) 时才是 H5
// Node 24+ 有 navigator 但 onLine 是 undefined, 不算 H5 (走下面 uni.getNetworkType)
if (typeof navigator !== 'undefined' && typeof navigator.onLine === 'boolean') {
// 初始检测: 用 _updateNetworkType (内部会触发事件)
this._updateNetworkType(navigator.onLine ? 'wifi' : 'none', { source: 'h5-initial' })
// 监听 online/offline 事件
if (typeof window !== 'undefined' && window.addEventListener) {
window.addEventListener('online', () => {
this._updateNetworkType('wifi', { source: 'h5-online', isConnected: true })
})
window.addEventListener('offline', () => {
this._updateNetworkType('none', { source: 'h5-offline', isConnected: false })
})
}
return
}
// navigator.onLine 不是 boolean (Node/SSR) - 走 uni.getNetworkType
// #endif
// #ifndef H5
if (typeof uni === 'undefined' || !uni.getNetworkType) {
// 不可用: 用 _updateNetworkType 设 unknown (会触发事件)
this._updateNetworkType('unknown', { source: 'no-uni-api' })
return
}
// 异步获取当前网络类型
uni.getNetworkType({
success: (res) => {
this._updateNetworkType((res && res.networkType) || 'unknown', { source: 'uni-initial' })
},
fail: () => {
this._updateNetworkType('unknown', { source: 'uni-initial-fail' })
},
})
// 监听网络变化
if (uni.onNetworkStatusChange) {
uni.onNetworkStatusChange((res) => {
const newType = (res && res.networkType)
|| (res && res.isConnected === false ? 'none' : 'unknown')
this._updateNetworkType(newType, {
source: 'uni-change',
isConnected: res && typeof res.isConnected === 'boolean' ? res.isConnected : undefined,
})
})
}
// #endif
} catch (e) {
// 任意失败都用 unknown, 不影响 splash
this._updateNetworkType('unknown', { source: 'init-error' })
}
}
/**
* 根据当前网络环境选档
* - 离线 (none): 4000 (4s, 让 diy 错误信号有时间触发)
* - 弱网 (2g/3g): 22000 (22s 慢网档, 多 2s 缓冲)
* - 正常 (4g/5g/wifi): 12000 (12s 默认档, 多 2s 缓冲)
* - 未知 (unknown): 17000 (17s 中档, 保守)
* - 网络未就绪: 12000 (DEFAULT_TIMEOUT, 保守)
*/
_pickTimeoutByNetwork() {
if (!this._networkReady) return DEFAULT_TIMEOUT // 网络检测未就绪, 用默认
switch (this._networkType) {
case 'none': return 4000 // 离线: 4s 兜底
case '2g':
case '3g': return 22000 // 弱网: 22s 慢网档
case '4g':
case '5g':
case 'wifi': return 12000 // 正常: 12s 默认档
case 'unknown':
default: return 17000 // 未知: 17s 中档 (保守)
}
}
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) {}
}
// 业务方可通过 opts.timeout 覆盖, 但不能低于 5000ms (低于此值给 warn, 仍生效)
// 原因: 启动期 i18n/theme/remote-config 远端加载最少 1-2s, diy 加载 1-3s
// timeout 低于 5s 会经常触发兜底强关, 用户看到白屏
// 测试场景允许传 < 5000ms (因为 mock 环境快), 仍生效但 warn
// 优先级: opts.timeout (业务方显式) > _pickTimeoutByNetwork() (自动选档) > DEFAULT_TIMEOUT
const MIN_RECOMMENDED_TIMEOUT = 5000
let timeout
if (opts.timeout) {
timeout = opts.timeout
if (opts.timeout < MIN_RECOMMENDED_TIMEOUT) {
console.warn(
`[splash-state] timeout=${opts.timeout}ms 低于推荐下限 ${MIN_RECOMMENDED_TIMEOUT}ms, ` +
`可能导致启动期白屏. 生产环境建议 10000-20000ms.`
)
}
} else {
// 自动选档: 根据当前网络环境选 timeout
timeout = this._pickTimeoutByNetwork()
}
this._armTimeout(timeout);
}
/**
* 设置/重设 splash 总超时兜底
* - 由 show() 初始化, 或 _updateNetworkType() 在网络变化时调用
* - 关键: 网络从好→差时延长, 差→好时缩短, 保证用户不会过早/过晚看到白屏
*/
_armTimeout(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);
}
/**
* 网络变化时更新 _networkType, 并按需重启 splash 兜底
* @param {string} newType 新的网络类型
* @param {Object} [meta] 附加信息 { isConnected, source: 'h5-online' | 'uni-change' | ... }
* @returns {boolean} 是否真的更新了 (新旧不同时为 true)
*/
_updateNetworkType(newType, meta) {
newType = newType || 'unknown'
const oldType = this._networkType
const changed = oldType !== newType
// 关键: 即使 type 没变, _networkReady 也要设 true
// 原因: 首次调用 _updateNetworkType 是从 _initNetworkDetect 进来
// 此时 _networkType='unknown' (初始), 可能 newType 也是 'unknown' (uni 不可用)
// 但 _networkReady 仍要从 false → true (让 _pickTimeoutByNetwork 工作)
this._networkReady = true
if (!changed) return false
this._networkType = newType
// 网络变化时: 如果 splash 还 visible, 重启兜底 (用新档)
// 业务场景:
// - wifi → 2g: 启动期远端慢, 兜底延长, 避免过早强关
// - 2g → wifi: 兜底缩短, 避免过晚强关
// - any → none: 兜底缩短到 4s, 让 diy 错误信号更快触发
// - none → any: 兜底恢复正常档, 给足时间
const shouldReboot = this._visible && this._pendingHide === null
// 关键: 仅当 splash 还没进入"软隐藏"阶段时重启兜底
// _pendingHide 不为 null 表示业务方已调 hide(), 等 notifyPageReady/DiyLoadError 即可
// 此时网络变化不影响兜底 (业务方已接管决策)
if (shouldReboot) {
const newTimeout = this._pickTimeoutByNetwork()
this._armTimeout(newTimeout)
}
// 发 splash:network-change 事件 (业务方监听)
// payload: { from, to, isConnected, retryRecommended, rebootSplashTimeout }
// retryRecommended: 从 none 恢复时建议重试 (业务方重调 diy 接口)
// rebootSplashTimeout: 是否重启了 splash 兜底 (true/false)
const eventPayload = {
from: oldType,
to: newType,
isConnected: meta && typeof meta.isConnected === 'boolean' ? meta.isConnected : newType !== 'none',
retryRecommended: oldType === 'none' && newType !== 'none', // 离线→在线, 建议重试
rebootSplashTimeout: shouldReboot,
source: (meta && meta.source) || 'unknown',
}
this._emit('splash:network-change', eventPayload)
return true
}
/**
* 隐藏 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 短动画, 用于隐私弹窗等需要立即接管视觉的场景, 避免"双遮罩"感
* - 'strict': 严格模式, 不走 MOUNT_GRACE_MS / PAGE_READY_GRACE_MS 兜底,
* 只等 notifyPageReady() 或 DEFAULT_TIMEOUT 总超时
* 适用于: 已接入平台托管的系统弹窗 (鸿蒙),
* splash 必须真等到首页 diy 内容渲染好才能关
*/
hide(opts = {}) {
const reason = opts.reason || 'manual';
const useStrict = opts.mode === 'strict' || opts._strict === true;
// boot-complete 默认走软隐藏, 避免时序问题
const useSoft = useStrict || opts.soft === true || (opts.soft !== false && reason === 'boot-complete');
// strict 模式复用 fast 动画
const mode = useStrict ? 'fast' : (opts.mode === 'fast' ? 'fast' : 'default');
if (useSoft) {
// 传递完整 opts, _softHide 内部能识别 mode='strict' 或 _strict
this._softHide(opts);
} else {
this._doHide({ reason, mode });
}
}
/**
* 软隐藏: 标记应该 hide, 等组件 mount + 页面就绪
* 如果组件 1s 内没 mount, 兜底自动 hide
* 如果页面 2s 内没就绪, 兜底自动 hide
*
* strict 模式 (鸿蒙已接入平台托管):
* 不走 MOUNT_GRACE_MS / PAGE_READY_GRACE_MS 兜底
* 只等 notifyMounted() + notifyPageReady() 或 DEFAULT_TIMEOUT 总超时
* 保证 splash 一定等到首页 diy 内容真的渲染好
*/
_softHide(opts) {
if (!this._visible) return; // 已经隐藏了
this._pendingHide = opts;
// strict 模式识别: mode='strict' 或 _strict=true
const useStrict = opts && (opts.mode === 'strict' || opts._strict === true);
// 如果组件已经 mount 且页面已就绪, 立即隐藏
if (this._hasMounted && this._pageReady) {
this._flushPendingHide();
return;
}
// strict 模式: 不设 mountGraceId 兜底, 只等 notifyPageReady
// (DEFAULT_TIMEOUT 在 show() 设置的 _timeoutId 兜底)
if (useStrict) {
return;
}
// 兜底: 1s 内没 mount, 强制隐藏
if (this._mountGraceId) clearTimeout(this._mountGraceId);
this._mountGraceId = setTimeout(() => {
if (this._pendingHide) {
this._flushPendingHide();
}
}, MOUNT_GRACE_MS);
}
/**
* 真正触发软隐藏
* 如果页面还未就绪, 等待页面就绪后再 hide
* strict 模式 (鸿蒙): 不设 pageReadyGraceId 兜底, 只等 notifyPageReady()
*/
_flushPendingHide() {
if (this._mountGraceId) {
clearTimeout(this._mountGraceId);
this._mountGraceId = null;
}
// 已被 notifyDiyLoadError 拿走 _pendingHide 并自己 _doHide: noop
// 原因: notifyMounted 50ms 后会调 _flushPendingHide, 但 _pendingHide 已被 notifyDiyLoadError 消费
// 不应再调 _doHide (避免重复发 splash:hide 或时序错乱)
if (!this._pendingHide) return;
const _opts = this._pendingHide
const useStrict = _opts && (_opts.mode === 'strict' || _opts._strict === true)
// 如果页面还未就绪, 等待页面就绪 (保留 _pendingHide, 等页面就绪后再处理)
if (!this._pageReady) {
// strict 模式: 不设 pageReadyGraceId, 只等 notifyPageReady()
// 总超时由 show() 里的 _timeoutId 兜底 (DEFAULT_TIMEOUT=8s)
if (useStrict) {
return;
}
// 兜底: 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' });
}
/**
* 实际隐藏 (硬路径)
* @param {Object} opts
* @param {string} [opts.reason='manual'] 隐藏原因
* @param {string} [opts.mode='default'] 动画模式
* @param {boolean} [opts._silent=false] true=不发 splash:hide 事件
* 适用于 notifyDiyLoadError: 已经发了 splash:diy-error, 不能再发 splash:hide
*/
_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) {}
}
// _silent=true: 业务方已经从 notifyDiyLoadError 收了 splash:diy-error, 这里不发 splash:hide
if (opts._silent) return;
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);
}
}
/**
* diy 加载失败时通知 (网络异常/业务失败/无响应)
* - 任何模式: 真关 splash (不能无限等, 错误已显示在页面横幅上)
* - 触发独立事件 'splash:diy-error' (不是 'splash:hide')
* 业务方可监听此事件做: 错误上报 / 自定义错误展示 / 区分错误类型
* 调用时机: diy 错误横幅出现后 (diy.js._showDiyLoadError)
*
* @param {Object} [opts]
* @param {string} [opts.reason='diy-load-error'] 隐藏原因
* 用于 'splash:diy-error' 事件的 payload, 业务方可区分:
* - 'diy-network-error': 网络异常 (uni.request catch)
* - 'diy-no-response': 无响应 (res 为空)
* - 'diy-business-error': 业务失败 (code!=0)
* @param {string} [opts.errorType] 错误类型: 'network' | 'business' | 'no-response'
* @param {Object|string} [opts.err] 原始错误对象
* @param {string} [opts.url] 出错的请求地址
*/
notifyDiyLoadError(opts = {}) {
// 已 _pageReady=true (notifyPageReady 之后): noop
// 原因: 业务方先调 notifyPageReady (diy 渲染好) 之后又调 notifyDiyLoadError (重复调用或时序错乱)
// 不应再触发 splash:diy-error (已经发过 splash:hide)
if (this._pageReady) return;
// 复用 notifyPageReady 的关闭逻辑 (页面就绪 = 错误状态也算"就绪")
// 原因: 错误状态页 (diyLoadError=true) 已经有 UI 反馈, splash 真关不卡视觉
this._pageReady = true
// 清除所有兜底, 真关 (strict 模式严格依赖 notifyPageReady/notifyDiyLoadError)
if (this._pageReadyGraceId) {
clearTimeout(this._pageReadyGraceId)
this._pageReadyGraceId = null
}
if (this._mountGraceId) {
clearTimeout(this._mountGraceId)
this._mountGraceId = null
}
// 触发独立事件 (不发 splash:hide, 让业务方区分正常 hide 和 diy 错误)
this._emit('splash:diy-error', {
reason: opts.reason || 'diy-load-error',
errorType: opts.errorType,
err: opts.err,
url: opts.url,
})
// 关键: 直接 _doHide 关闭 splash, **不**走 _flushPendingHide
// 原因: _flushPendingHide 内部会 _doHide → 触发 splash:hide 事件
// notifyDiyLoadError 路径**只**应发 splash:diy-error, 不应发 splash:hide
// (业务方根据事件类型区分, 不能混淆)
if (this._pendingHide) {
// 把 _pendingHide 取出, 直接 _doHide 关闭
// _silent=true 让 _doHide 不发 splash:hide (因为已经发了 splash:diy-error)
const _pendingOpts = this._pendingHide
this._pendingHide = null
setTimeout(() => this._doHide({ ..._pendingOpts, _silent: true }), 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

View File

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

View File

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

View File

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

View File

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

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -1,92 +0,0 @@
// iOS 微信小程序 <video> 兼容工具
// 问题背景:
// 1) 弹窗内的 <video> 用 autoplay 不可靠——popup 初始隐藏,autoplay 在隐藏态不触发,
// 等 popup 显示后也不会重新 autoplay,导致"安卓有时能播、iOS 不能";
// 2) iOS 对同一个 <video> 实例在 src 重绑 / 弹窗重开 / 播放结束后,不会自动重新加载,
// 需要靠 :key 重建实例或 seek(0) 才能重播;
// 3) iOS 微信不支持 webm / vp9 / hevc / ogv 等封装或编码,会直接黑屏;
// 4) H5 端(含微信内置浏览器)$nextTick 调 play() 太快,弹窗动画未完时浏览器内部
// 会自动 pause(),导致 "The play() request was interrupted by a call to pause()" 错误。
// 这里统一提供"格式检测"与"在视频可见后触发播放"的能力,供各视频组件复用。
//
// 重要:微信小程序的 <video>.play() 不要求用户手势(与 H5 不同),只要在视频元素
// 已经渲染、popup 已经显示后调用即可。因此请务必在 uni-popup 的 @change(show=true)
// 回调里调用本方法,而不是在 open() 里紧跟着 $nextTick 调用(那时元素尚未可见)。
// iOS 微信 <video> 已知不支持的封装/编码(仅按扩展名做保守判断,用于给出友好提示)
const UNSUPPORTED_EXT_ON_IOS = ['webm', 'ogv', 'ogg', 'mov', 'm4v', 'hevc', 'av1', '3gp'];
// 取 URL 中的小写扩展名(忽略查询参数与 hash)
export function getVideoExt(url) {
if (!url || typeof url !== 'string') return '';
const clean = url.split('?')[0].split('#')[0];
const idx = clean.lastIndexOf('.');
if (idx < 0) return '';
return clean.slice(idx + 1).toLowerCase();
}
// 该地址在 iOS 上是否很可能无法播放(基于扩展名的保守判断)
export function isLikelyUnsupportedOnIOS(url) {
const ext = getVideoExt(url);
if (!ext) return false;
return UNSUPPORTED_EXT_ON_IOS.indexOf(ext) !== -1;
}
// 在"视频已经渲染、popup 已经显示"的前提下触发播放。
// 必须在 uni-popup 的 @change(show=true) 回调里调用,此时 <video> 元素已可见,
// createVideoContext 才能拿到有效实例。
// videoId: <video> 的 id;instance: 当前组件/页面实例(组件内必传)。
export function playVideoInContext(videoId, instance) {
if (!videoId || !instance) return;
// H5 端需要更长延迟:等 uni-popup 动画播完(~350ms),否则浏览器内部会自动
// pause() 导致 "play() interrupted by pause()" 错误;小程序端 $nextTick 即可。
// #ifdef H5
const delay = 400;
// #endif
// #ifndef H5
const delay = 0;
// #endif
const doPlay = () => {
let ctx = null;
try {
ctx = uni.createVideoContext(videoId, instance);
} catch (e) {
console.error('[video-helper] createVideoContext failed:', e);
return;
}
if (!ctx) return;
try {
ctx.play();
} catch (e) {
console.error('[video-helper] play() failed, will retry:', e);
// H5 端首次 play() 常被浏览器自动 pause() 打断,延迟重试一次
// #ifdef H5
setTimeout(() => {
try { ctx.play(); } catch (retryErr) {
console.error('[video-helper] retry play() also failed:', retryErr);
}
}, 300);
// #endif
}
};
if (delay > 0) {
// H5:先等 nextTick(DOM 更新),再等 delay(弹窗动画完成)
if (typeof instance.$nextTick === 'function') {
instance.$nextTick(() => setTimeout(doPlay, delay));
} else {
setTimeout(doPlay, delay);
}
} else {
// 小程序端:nextTick 即可
if (typeof instance.$nextTick === 'function') {
instance.$nextTick(doPlay);
} else {
doPlay();
}
}
}

View File

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

View File

@@ -1,73 +0,0 @@
/**
* 延迟初始化 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

View File

@@ -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 }">{{ $lang('components-diy.diy-bargain.freeGet') }}</view> :style="{ color: value.titleStyle.textColor }">低至0元免费拿</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 ? $lang('components-diy.diy-bargain.continueBargain') : value.btnStyle.text }} {{ item.is_bargaining ? '继续砍价' : 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 : '' }">
{{ $lang('components-diy.diy-bargain.soldCount', { num: item.sale_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 : '' }">
{{ $lang('components-diy.diy-bargain.soldCount', { num: item.sale_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,10 +461,7 @@ scroll-view ::-webkit-scrollbar {
align-items: center; align-items: center;
justify-content: center; justify-content: center;
height: 36rpx; height: 36rpx;
// P0: 砍价头渐变 → var(--pintuan-label-grad-start/end) 复用(同色系) background: linear-gradient(270deg, #ffbd5b 0%, #fd882e 100%);
// 兼容: 微信小程序 / 鸿蒙元服务 — 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;
@@ -477,9 +474,7 @@ 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;
// P0: 砍价头文字色 → var(--pintuan-label-grad-start) 复用 color: #ffbd5b;
// 兼容: 微信小程序 / 鸿蒙元服务 — 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;
@@ -581,9 +576,7 @@ scroll-view ::-webkit-scrollbar {
width: auto; width: auto;
height: 20rpx; height: 20rpx;
border-radius: 20rpx; border-radius: 20rpx;
// P0: 砍价浅底 → var(--bargain-promo-shallow) background-color: #ffeadb;
// 兼容: 微信小程序 / 鸿蒙元服务 — background-color 接受 var() 无问题
background-color: var(--bargain-promo-shallow, #ffeadb);
position: relative; position: relative;
&::after { &::after {
@@ -591,9 +584,7 @@ scroll-view ::-webkit-scrollbar {
width: 26rpx; width: 26rpx;
height: 26rpx; height: 26rpx;
border-radius: 50%; border-radius: 50%;
// P0: 砍价红圆点 → var(--bargain-promo-color) background-color: #fa1a1a;
// 兼容: 微信小程序 / 鸿蒙元服务 — background-color 接受 var() 无问题
background-color: var(--bargain-promo-color, #fa1a1a);
position: absolute; position: absolute;
top: 50%; top: 50%;
transform: translateY(-50%); transform: translateY(-50%);
@@ -604,9 +595,7 @@ scroll-view ::-webkit-scrollbar {
width: 0; width: 0;
height: 20rpx; height: 20rpx;
border-radius: 20rpx; border-radius: 20rpx;
// P0: 砍价红进度条 → var(--bargain-promo-color) background-color: #fa1a1a;
// 兼容: 微信小程序 / 鸿蒙元服务 — background-color 接受 var() 无问题
background-color: var(--bargain-promo-color, #fa1a1a);
position: relative; position: relative;
.progress-bar { .progress-bar {
@@ -629,9 +618,7 @@ scroll-view ::-webkit-scrollbar {
line-height: 1; line-height: 1;
text { text {
// P0: 砍价数字红 → var(--bargain-promo-color) color: #fa1a1a;
// 兼容: 微信小程序 / 鸿蒙元服务 — color 接受 var() 无问题
color: var(--bargain-promo-color, #fa1a1a);
} }
} }
} }

View File

@@ -1,56 +1,65 @@
<template> <template>
<!-- 修复底部 TabBar 频闪: <view data-component-name="diy-bottom-nav" v-if="tabBarList && tabBarList.list">
微信小程序等环境下 `shouldShowTabBar` 在 tabBarList 异步加载期间会从 false→true 短暂切换, <view class="tab-bar" :style="{ backgroundColor: tabBarList.backgroundColor }">
配合 `v-if` 会让整个 tab 组件树卸载/重建 -> 视觉频闪 + tabBar 占用空间反复占位/释放导致上方内容跳动。
改为 `v-show`, 只切换可见性, 内部 tab 始终在 DOM 中(无 tabBarList 时只渲染空壳占位)。 -->
<view data-component-name="diy-bottom-nav" v-show="shouldShowTabBar">
<!-- tabBarList 未就绪时仍保留 placeholder 占位, 避免上方内容在加载完成后突跳 -->
<view v-if="tabBarList && tabBarList.list && tabBarList.list.length" 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">
<view class="icon" v-if="tabBarList.type == 1 || tabBarList.type == 2" <block v-if="item.link.wap_url == '/pages_goods/cart'">
:animation="isCartItem(item.link) ? cartAnimation : null" <view class="icon" v-if="tabBarList.type == 1 || tabBarList.type == 2"
:id="isCartItem(item.link) ? 'tabbarCart' : null"> :animation="cartAnimation" id="tabbarCart">
<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>
<block v-else> <block v-else>
<image v-if="item.icon_type == 'img'" :src="$util.img(item.iconPath)" /> <image v-if="item.icon_type == 'img'" :src="$util.img(item.iconPath)" />
<diy-icon v-if="item.icon_type == 'icon'" :icon="item.iconPath" <diy-icon v-if="item.icon_type == 'icon'" :icon="item.iconPath"
:value="item.style ? item.style : null"></diy-icon> :value="item.style ? item.style : null"></diy-icon>
</block> </block>
<view class="cart-count-mark font-size-activity-tag" <view class="cart-count-mark font-size-activity-tag"
:class="{ max: cartNumber > 99 }" :class="{ max: item.link.wap_url == '/pages_goods/cart' && cartNumber > 99 }"
:style="{ background: 'var(--price-color)' }" :style="{ background: 'var(--price-color)' }" v-if="cartNumber > 0">
v-if="isCartItem(item.link) && cartNumber > 0"> {{ cartNumber > 99 ? '99+' : cartNumber }}
{{ cartNumber > 99 ? '99+' : cartNumber }} </view>
</view> </view>
</view> </block>
<block v-else>
<view class="icon" v-if="tabBarList.type == 1 || tabBarList.type == 2">
<block v-if="verify(item.link)">
<image v-if="item.selected_icon_type == 'img'"
:src="$util.img(item.selectedIconPath)" />
<diy-icon v-if="item.selected_icon_type == 'icon'" :icon="item.selectedIconPath"
:value="item.selected_style ? item.selected_style : null"></diy-icon>
</block>
<block v-else>
<image v-if="item.icon_type == 'img'" :src="$util.img(item.iconPath)" />
<diy-icon v-if="item.icon_type == 'icon'" :icon="item.iconPath"
:value="item.style ? item.style : null"></diy-icon>
</block>
</view>
</block>
<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 }">
{{ $langConfig.getField(item, 'text') }} {{ lang == 'en-us' ? item.en_text : 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' }">
{{ $langConfig.getField(item, 'text') }} {{ lang == 'en-us' ? item.en_text : item.text }}
</view> </view>
</view> </view>
</view> </view>
</view> </view>
<!-- 解决fixed定位后底部导航栏塌陷问题: 始终保留 placeholder, 避免内容随 tabBar 可见性跳 --> <!-- 解决fixed定位后底部导航栏塌陷问题 -->
<view class="tab-bar-placeholder"></view> <view class="tab-bar-placeholder"></view>
</view> </view>
</template> </template>
<script> <script>
import { adaptSubpackageUrl, checkTabBarActive, decodeEntity } from '@/common/js/util.js' import { adaptSubpackageUrl, checkTabBarActive } 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 {
@@ -67,6 +76,7 @@ export default {
mixins: [DiyMinx], mixins: [DiyMinx],
data() { data() {
return { return {
lang: uni.getStorageSync("lang"),
currentRoute: '', //当前页面路径 currentRoute: '', //当前页面路径
jumpFlag: true, //是否可以跳转,防止重复点击 jumpFlag: true, //是否可以跳转,防止重复点击
cartAnimation: {} cartAnimation: {}
@@ -95,25 +105,9 @@ 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) {
@@ -129,148 +123,38 @@ 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() {
const currentPages = getCurrentPages(); let currentPage = getCurrentPages()[getCurrentPages().length - 1];
const currentPage = currentPages[currentPages.length - 1]; if (currentPage && currentPage.route) {
if (!currentPage || !currentPage.route) return; this.currentRoute = currentPage.route;
// 归一化:补全前导 '/',确保后续 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');
const redirectLink = link ? { ...link } : link; this.$util.diyRedirectTo(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(); // 标准化路径格式,确保比较的一致性
const currentPage = currentPages[currentPages.length - 1]; let currentPageRoute = this.currentRoute ? '/' + this.currentRoute : '';
const currentPageRoute = currentPage && currentPage.route let linkUrl = link.wap_url;
? this._normalizeRoute(currentPage.route)
: '';
// 读取当前页面 query 参数(兼容小程序与 H5) // 首页特殊处理
let currentPageQuery = {}; if (linkUrl === this.$util.INDEX_PAGE_URL && this.name === 'DIY_VIEW_INDEX') {
if (currentPage) { return true;
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') { // 精确匹配当前路径
// DIY_VIEW_INDEX 短路: 当 name 是 DIY_VIEW_INDEX 时, 任意匹配的 tab 都高亮 if (adaptSubpackageUrl(linkUrl) === currentPageRoute) {
// 修复前: 只对 HOME (INDEX_PAGE_URL) 生效 return true;
// 修复后: 适用于所有 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(link.wap_url, currentPageRoute, this.tabBarList, this.packageEntryTab, currentPageQuery); return checkTabBarActive(linkUrl, currentPageRoute);
} }
} }
}; };
@@ -294,42 +178,13 @@ export default {
.tab-bar { .tab-bar {
background-color: #fff; background-color: #fff;
box-sizing: border-box; box-sizing: border-box;
/* ============================================================ position: fixed;
* 固定在最底端,不能位置漂移(微信小程序 / 鸿蒙元服务 / 快应用 H5) left: 0;
* ------------------------------------------------------------ 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: 2147483647 !important; z-index: 998;
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

View File

@@ -1,20 +1,11 @@
<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('components-diy.diy-search.searchBtn')" confirm-type="search" @tap.stop="onClickSearch()" disabled="true" /> <input type="text" class="uni-input font-size-tag" maxlength="50" :placeholder="$lang('search')" confirm-type="search" @tap.stop="onClickSearch()" disabled="true" />
<text class="iconfont icon-sousuo3"></text> <text class="iconfont icon-sousuo3"></text>
</view> </view>
</view> </view>
@@ -25,7 +16,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('components-diy.diy-search.searchBtn')" <input type="text" class="uni-input" maxlength="50" :placeholder="$lang('search')"
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>
@@ -35,18 +26,16 @@
</view> </view>
</block> </block>
<!-- #endif --> <!-- #endif -->
<!-- #ifdef H5 || MP-HARMONY --> <!-- #ifdef H5 -->
<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('components-diy.diy-search.searchBtn')" confirm-type="search" <input type="text" class="uni-input" maxlength="50" :placeholder="$lang('search')" 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"
@@ -62,7 +51,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">{{ $lang('components-diy.diy-category.expand') }}</text> <text class="text">展开</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>
@@ -79,97 +68,42 @@
</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>{{ $lang('components-diy.diy-category.clickToCollapse') }}</text> <text>点击收起</text>
<text class="iconfont icon-iconangledown-copy"></text> <text class="iconfont icon-iconangledown-copy"></text>
</view> </view>
</view> </view>
</uni-popup> </uni-popup>
</view> </view>
<!-- 全屏骨架占位 (只显示: 左分类树 + 右商品网格 + 底部空隙, 不画 navbar/TabBar,
避免与小程序/H5 顶部 navbar / diy-bottom-nav 错位)。
通过 v-if 拿到 categoryTreeLoading 时按真实布局骨架填充。
search-box / 商品 nav-bar 由外层 category.vue 渲染, 不在本组件里动它 -->
<view class="category-page-skeleton" v-if="categoryTreeLoading">
<view class="skeleton-content">
<view class="skeleton-tree">
<view class="skeleton-tree-item" v-for="n in 8" :key="n"></view>
</view>
<view class="skeleton-grid">
<view class="skeleton-card" v-for="n in 6" :key="n"></view>
</view>
</view>
</view>
<view class="content-box" v-if="categoryTree"> <view class="content-box" v-if="categoryTree">
<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">
<!-- 模板4: 左侧显示一级分类(顶部轮播中的分类) --> <view class="category-item" v-for="(item, index) in categoryTree" :key="index" :class="[
<view v-if="value.template == 4"> { select: select == index },
<view class="category-item" v-for="(item, index) in templateFourData" :key="index" :class="[ { 'border-bottom': value.template == 4 && select + 1 === index },
{ select: oneCategorySelect == index }, { 'border-top': value.template == 4 && select - 1 === index }
{ 'border-bottom': oneCategorySelect + 1 === index }, ]" @tap.stop="switchOneCategory(index)">
{ 'border-top': oneCategorySelect - 1 === index } <view class="">{{ item.category_name }}</view>
]" @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 },
{ 'first-category-item': index == 0 && value.template == 99 }
]" @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">
<!-- 模板99 + 二级分类: 全局二级分类按钮(去重, 一直显示) + 商品列表 --> <scroll-view scroll-y="true" class="content-wrap" v-if="value.template == 1 || loadType == 'all'"
<scroll-view scroll-y="true" class="content-wrap" v-if="value.template == 99 && template99Category" ref="contentWrap" :scroll-into-view="categoryId" :scroll-with-animation="true"
:refresher-enabled="true" refresher-default-style="none" @scroll="listenScroll" @touchstart="touchStart" :refresher-enabled="true"
:refresher-triggered="triggered" @refresherrefresh="onRefresh" @refresherrestore="onRestore"> refresher-default-style="none" :refresher-triggered="triggered" @refresherrefresh="onRefresh"
<diy-category-item :category="template99Category" :value="value" ref="categoryItem" :index="0" :select="0" @refresherrestore="onRestore">
:oneCategorySelect="oneCategorySelect" :isList="isList" <view class="child-category" v-for="(item, index) in categoryTree" :key="index"
:currentOneCategory="categoryTree && categoryTree[select] ? categoryTree[select] : null" :id="'category-' + index">
:lastSecondCategoryName="lastSecondCategoryName" <diy-category-item :category="item" :value="value" ref="categoryItem" :index="index"
@tologin="toLogin" @selectsku="selectSku($event, 0)" @addCart="addCartPoint" :select="select" :oneCategorySelect="oneCategorySelect" :isList="isList"
@saveSecondCategory="saveSecondCategoryName"></diy-category-item> @tologin="toLogin" @selectsku="selectSku($event, index)" @addCart="addCartPoint"
</scroll-view> @loadfinish="getHeightArea"></diy-category-item>
</view>
<!-- 模板1: 仿京东/淘宝商品分类 - 按 template 2 的 part-load 逻辑, 切换一级分类时只渲染选中分类的子分类网格 --> <view class="end-tips" ref="endTips" :style="{ opacity: endTips }">已经到底了~</view>
<scroll-view scroll-y="true" class="content-wrap" v-else-if="value.template == 1" </scroll-view>
: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 : ''"
:currentOneCategory="categoryTree && categoryTree[select] ? categoryTree[select] : null"
@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'">
@@ -178,7 +112,6 @@
<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>
@@ -187,16 +120,17 @@
</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">{{ $lang('components-diy.diy-category.noCategory') }}</view> <view class="tips">暂时没有分类哦!</view>
</view> </view>
</view> </view>
<view class="category-empty" v-else>
<image :src="$util.img('public/uniapp/category/empty.png')" mode="widthFix" show-menu-by-longpress></image>
<view class="tips">暂时没有分类哦!</view>
</view>
<!-- 模板4: 底部购物车栏 --> <!-- <view class="cart-box" v-if="(value.template == 2 || value.template == 4) && value.quickBuy && storeToken && categoryTree && categoryTree.length">
<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" <view class="cart-icon" ref="cartIcon" :animation="cartAnimation" @tap.stop="$util.redirectTo('/pages_goods/cart')">
@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>
@@ -207,13 +141,12 @@
<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" <view class="right-wrap"><button type="primary" class="settlement-btn" @tap.stop="settlement">去结算</button>
@tap.stop="settlement">去结算</button>
</view> </view>
</view> </view> -->
<view class="cart-point" v-for="(item, index) in carIconList" :key="index" <view class="cart-point" :style="{ left: item.left + 'px', top: item.top + 'px' }" :key="index"
:style="{ left: item.left + 'px', top: item.top + 'px' }"></view> v-for="(item, index) in carIconList"></view>
<ns-goods-sku-category ref="skuSelect" @refresh="refreshData" @addCart="addCartPoint"></ns-goods-sku-category> <ns-goods-sku-category ref="skuSelect" @refresh="refreshData" @addCart="addCartPoint"></ns-goods-sku-category>
</view> </view>
@@ -259,23 +192,12 @@ export default {
loadType: '', loadType: '',
templateFourData: [], templateFourData: [],
isList: false, isList: false,
lang: uni.getStorageSync("lang"), lang: uni.getStorageSync("lang")//en-us 英文
lastSecondCategoryName: '',
template99Category: null,
// 修复体验: 进入页面初期显示 "暂未分类" 然后又变成有数据的体验很差
// 用 categoryTreeLoading 区分"还在请求"和"真的没分类", 请求未完成时
// 显示骨架占位而非空态文案
categoryTreeLoading: true,
}; };
}, },
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);
@@ -303,14 +225,7 @@ export default {
}, },
watch: { watch: {
// 组件刷新监听 // 组件刷新监听
componentRefresh: function (nval) { }, componentRefresh: function (nval) { }
categoryTreeLoading: function (nval, oval) {
if (nval === false && oval === true) {
this.$nextTick(() => {
if (!this.heightArea.length) this.getHeightArea(-1);
});
}
}
}, },
computed: { computed: {
cartTotalMoney() { cartTotalMoney() {
@@ -384,30 +299,11 @@ export default {
this.$store.dispatch('getCartNumber'); this.$store.dispatch('getCartNumber');
if (!this.heightArea.length) this.getHeightArea(-1); if (!this.heightArea.length) this.getHeightArea(-1);
}, },
/** /**
* 获取高度区间 * 获取高度区间
*
* 鸿蒙 JSVM 在 mounted() 之前触发 onShow,导致 query 还是 undefined
* 加防御性检查,避免上线后第一次进入崩溃
*/ */
getHeightArea(index) { getHeightArea(index) {
// 节流: 500ms 内的重复请求复用上次结果, 避免每次 onShow 都跑 selectAll 触发频闪
const now = Date.now();
if (this._lastHeightAreaTime && now - this._lastHeightAreaTime < 500 && this.heightArea && this.heightArea.length) {
if (index != -1 && index < this.categoryTree.length - 1 && Array.isArray(this.$refs.categoryItem) && this.$refs.categoryItem[index + 1]) this.$refs.categoryItem[index + 1].getGoodsList();
return;
}
this._lastHeightAreaTime = now;
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 => {
@@ -422,13 +318,12 @@ export default {
}) })
.exec(); .exec();
this.heightArea = heightArea; this.heightArea = heightArea;
if (index != -1 && index < this.categoryTree.length - 1 && Array.isArray(this.$refs.categoryItem) && this.$refs.categoryItem[index + 1]) this.$refs.categoryItem[index + 1].getGoodsList(); if (index != -1 && index < this.categoryTree.length - 1) this.$refs.categoryItem[index + 1].getGoodsList();
}, },
/** /**
* 获取全部分类 * 获取全部分类
*/ */
getCategoryTree() { getCategoryTree() {
this.categoryTreeLoading = true;
this.$api.sendRequest({ this.$api.sendRequest({
url: '/api/goodscategory/tree', url: '/api/goodscategory/tree',
data: { data: {
@@ -453,85 +348,10 @@ export default {
return item; return item;
}); });
} }
// 模板99 + 二级分类: 全局查询所有有商品的二级分类(去重), 按钮一直显示
if (this.value.template == 99) {
this.loadGlobalSecondCategoryBtns();
}
} }
},
fail: () => {
// 失败也保证 loading 关闭, 让骨架替换为"暂无分类"空态
this.categoryTree = this.categoryTree || [];
},
complete: () => {
// 无论成功失败都关闭 loading 骨架
this.categoryTreeLoading = false;
} }
}); });
}, },
/**
* 全局查询所有有商品的二级分类, 按名称去重, 汇总成虚拟分类供 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
@@ -540,11 +360,9 @@ 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;
}, },
@@ -562,10 +380,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) {
if (Array.isArray(this.$refs.categoryItem) && this.$refs.categoryItem[this.select]) this.$refs.categoryItem[this.select].getGoodsList(); this.$refs.categoryItem[this.select].getGoodsList();
} }
} }
}, },
onRefresh() { onRefresh() {
@@ -591,7 +409,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 || this.$lang('components-diy.diy-category.pieceUnit'); item.unit = item.unit || '件';
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 = [];
@@ -718,7 +536,7 @@ export default {
}, },
// 操作多规格商品弹框后,刷新商品数据 // 操作多规格商品弹框后,刷新商品数据
refreshData() { refreshData() {
if (Array.isArray(this.$refs.categoryItem) && this.$refs.categoryItem[this.select]) this.$refs.categoryItem[this.select].loadGoodsCartNum(true); this.$refs.categoryItem[this.select].loadGoodsCartNum(true);
}, },
changeListStyle() { changeListStyle() {
this.isList = !this.isList; this.isList = !this.isList;
@@ -740,12 +558,11 @@ export default {
} }
.content-box { .content-box {
flex: 1; flex: 1;
height: 0; height: 0;
display: flex; display: flex;
align-items: flex-start;
.tree-wrap { .tree-wrap {
width: 170rpx; width: 170rpx;
height: 100%; height: 100%;
background-color: #f5f5f5; background-color: #f5f5f5;
@@ -784,15 +601,15 @@ export default {
padding: 26rpx 28rpx; padding: 26rpx 28rpx;
box-sizing: border-box; box-sizing: border-box;
position: relative; position: relative;
background-color: var(--diy-category-tree-normal-bg-color, #f5f5f5); background-color: #f5f5f5;
view { view {
color: var(--diy-category-tree-normal-text-color, #222222); color: #222222;
width: 100%; width: 100%;
white-space: break-word; white-space: break-word;
overflow: hidden; overflow: hidden;
text-align: center; text-align: center;
font-size: var(--diy-category-tree-normal-size, 20rpx); font-size: 10px;
} }
&.border-top { &.border-top {
@@ -804,12 +621,12 @@ export default {
} }
&.select { &.select {
background: var(--diy-category-tree-select-bg-color, #fff); background: #fff;
view { view {
color: var(--diy-category-tree-select-text-color, #333); color: #333;
font-weight: bold; font-weight: bold;
font-size: var(--diy-category-tree-select-size, 28rpx); font-size: $font-size-base;
} }
&::before { &::before {
@@ -934,11 +751,7 @@ 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);
@@ -992,219 +805,8 @@ export default {
opacity: 0; opacity: 0;
} }
// 全屏骨架占位 — 不画 navbar/TabBar (由外层 category.vue 渲染), 避免错位
// 兼容鸿蒙元服务 (JSVM 对 gap 支持不一): 用 margin 兜底替代 gap
.category-page-skeleton {
flex: 1;
height: 0; // 与 .content-box 一致, 让 flex 子项撑开父容器剩余高度
display: flex;
background-color: #f4f6fa;
.skeleton-content {
flex: 1;
display: flex;
min-height: 0;
.skeleton-tree {
width: 170rpx;
background-color: #f5f5f5;
padding: 20rpx 0;
box-sizing: border-box;
display: flex;
flex-direction: column;
// #ifndef MP-HARMONY
gap: 18rpx;
// #endif
flex-shrink: 0;
.skeleton-tree-item {
height: 40rpx;
// #ifndef MP-HARMONY
margin: 0 28rpx;
// #endif
// #ifdef MP-HARMONY
margin: 9rpx 28rpx; // 18rpx 间距 上下各 9rpx, 替代 gap:18rpx
// #endif
border-radius: 12rpx;
background: linear-gradient(90deg, #ececec 25%, #f5f5f5 37%, #ececec 63%);
background-size: 400% 100%;
animation: category-skeleton-shimmer 1.4s ease infinite;
}
}
.skeleton-grid {
flex: 1;
padding: 24rpx;
display: flex;
flex-wrap: wrap;
align-content: flex-start;
// #ifndef MP-HARMONY
gap: 16rpx;
// #endif
background-color: #f4f6fa;
min-width: 0;
.skeleton-card {
width: calc((100% - 32rpx) / 3);
height: 220rpx;
// #ifdef MP-HARMONY
margin: 8rpx;
// #endif
border-radius: 16rpx;
background: linear-gradient(90deg, #ececec 25%, #f5f5f5 37%, #ececec 63%);
background-size: 400% 100%;
animation: category-skeleton-shimmer 1.4s ease infinite;
}
}
}
}
@keyframes category-skeleton-shimmer {
0% {
background-position: 100% 50%;
}
100% {
background-position: 0 50%;
}
}
// 风格四 // 风格四
.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;
@@ -1431,244 +1033,4 @@ 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: var(--diy-category-tree-normal-bg-color, #f5f5f5);
border-radius: 0;
view {
color: var(--diy-category-tree-normal-text-color, #222222);
font-size: 26rpx;
line-height: 1.3;
}
&.border-top,
&.border-bottom {
border-radius: 0;
}
&.select {
background: var(--diy-category-tree-select-bg-color, #fff);
view {
color: var(--diy-category-tree-select-text-color, #333);
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: var(--diy-category-tree-normal-bg-color, #f5f5f5);
white-space: normal;
word-break: break-all;
view {
color: var(--diy-category-tree-normal-text-color, #222222);
font-size: 26rpx;
line-height: 1.5;
}
&.select {
background: var(--diy-category-tree-select-bg-color, #fff);
border-bottom: 1rpx solid #f0f0f0;
view {
color: var(--diy-category-tree-select-text-color, #333);
font-weight: bold;
font-size: 28rpx;
}
&::before {
content: ' ';
width: 6rpx;
height: 36rpx;
background: #FF4646;
display: block;
position: absolute;
left: 0;
top: 50%;
transform: translateY(-50%);
border-radius: 0 6rpx 6rpx 0;
}
}
}
// 模板99: 第一个分类项固定高度,与右侧二级分类按钮区域对齐
.tree-wrap .category-item.first-category-item {
height: 100rpx;
display: flex;
align-items: center;
white-space: nowrap;
overflow: hidden;
view {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
}
.content-wrap {
background: #f5f5f5;
padding: 0;
// #ifdef H5
::-webkit-scrollbar {
display: none;
width: 0;
height: 0;
background: transparent;
}
// #endif
}
.child-category {
width: 100%;
box-sizing: border-box;
}
}
</style> </style>

View File

@@ -265,7 +265,7 @@ export default {
// #ifndef MP-WEIXIN // #ifndef MP-WEIXIN
if (item?.channelType === 'wechat') { if (item?.channelType === 'wechat') {
uni.showToast({ uni.showToast({
title: this.$lang('wechatChannel.wechatMpOnly'), title: '视频号仅支持在微信小程序环境中播放',
icon: 'none', icon: 'none',
duration: 2000 duration: 2000
}); });

View File

@@ -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">{{ $lang('components-diy.diy-channel-video.viewCountSuffix', { count: value.viewCount }) }}</view> <view class="video-stats" v-if="showViewCount && value.showViewCount">{{ 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">
{{ $lang('components-diy.diy-channel-video.viewCountSuffix', { count: value.viewCount }) }} {{ 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">{{ $lang('components-diy.diy-channel-video.viewCountSuffix', { count: value.viewCount }) }}</view> <view class="video-stats" v-if="showViewCount && value.showViewCount && !listMode">{{ value.viewCount }}次观看</view>
</view> </view>
</view> </view>
</view> </view>

View File

@@ -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">{{ $lang('components-diy.diy-coupon.discount') }}</text> <text class="font-size-tag coupon-sign">折</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 ? $lang('components-diy.diy-coupon.minSpendAvailable', { amount: Number(item.at_least) }) : $lang('components-diy.diy-coupon.noThresholdCoupon') }} {{ item.at_least > 0 ? '满' + Number(item.at_least) + '元可用' : '无门槛优惠券' }}
</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)">{{ $lang('components-diy.diy-coupon.goUse') }}</view> <view class="coupon-get" :style="couponBtnStyle" v-if="parseInt(item.useState)">去使用</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">{{ $lang('components-diy.diy-coupon.discount') }}</text> <text class="font-size-tag coupon-sign">折</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 ? $lang('components-diy.diy-coupon.minSpendAvailable', { amount: Number(item.at_least) }) : $lang('components-diy.diy-coupon.noThresholdCoupon') }} {{ item.at_least > 0 ? '满' + Number(item.at_least) + '元可用' : '无门槛优惠券' }}
</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 || $lang('components-diy.diy-coupon.claim') }} {{ value.btnStyle.text || '领取' }}
</view> </view>
<view class="coupon-get use" :style="couponBtnStyle" v-if="parseInt(item.useState)">{{ $lang('components-diy.diy-coupon.goUse') }} <view class="coupon-get use" :style="couponBtnStyle" v-if="parseInt(item.useState)">去使用
</view> </view>
</view> </view>
</swiper-item> </swiper-item>
@@ -95,19 +95,20 @@
</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">{{ $lang('components-diy.diy-coupon.discount') }}</text> <text class="font-size-tag coupon-sign">折</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 ? $lang('components-diy.diy-coupon.minSpendAvailable', { amount: Number(item.at_least) }) : $lang('components-diy.diy-coupon.noThresholdCoupon') }}</text> <text :style="{ color: value.limitColor }">{{ item.at_least > 0 ? '满' +
<view class="item-text" v-if="item.goods_type == 1">{{ $lang('components-diy.diy-coupon.allProductsAvailable') }}</view> Number(item.at_least) + '元可用' : '无门槛优惠券' }}</text>
<view class="item-text" v-else-if="item.goods_type == 2">{{ $lang('components-diy.diy-coupon.specifiedProductsAvailable') }}</view> <view class="item-text" v-if="item.goods_type == 1">所有商品可用</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 == 2">指定商品可用</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 || $lang('components-diy.diy-coupon.claim') }} {{ value.btnStyle.text || '领取' }}
</view> </view>
<view class="coupon-get" :style="couponBtnStyle" v-if="parseInt(item.useState)">{{ $lang('components-diy.diy-coupon.goUse') }}</view> <view class="coupon-get" :style="couponBtnStyle" v-if="parseInt(item.useState)">去使用</view>
</view> </view>
</swiper-item> </swiper-item>
</swiper> </swiper>
@@ -132,16 +133,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">{{ $lang('components-diy.diy-coupon.discount') }}</text> <text class="font-size-tag coupon-sign">折</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 ? $lang('components-diy.diy-coupon.minSpendAvailable', { amount: Number(item.at_least) }) : $lang('components-diy.diy-coupon.noThresholdCoupon') }} {{ item.at_least > 0 ? '满' + Number(item.at_least) + '元可用' : '无门槛优惠券' }}
</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 || $lang('components-diy.diy-coupon.useNow') }} {{ value.btnStyle.text || '立即使用' }}
</view> </view>
<view class="coupon-get" :style="couponBtnStyle" v-if="parseInt(item.useState)">{{ $lang('components-diy.diy-coupon.goUse') }}</view> <view class="coupon-get" :style="couponBtnStyle" v-if="parseInt(item.useState)">去使用</view>
</view> </view>
</swiper-item> </swiper-item>
</swiper> </swiper>
@@ -159,11 +160,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">{{ $lang('components-diy.diy-coupon.yuan') }}</text> <text class="font-size-tag coupon-sign">元</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">{{ $lang('components-diy.diy-coupon.discount') }}</text> <text class="font-size-tag coupon-sign">折</text>
</view> </view>
</view> </view>
<view class="coupon-line"></view> <view class="coupon-line"></view>
@@ -172,14 +173,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">{{ $lang('components-diy.diy-coupon.minSpendAvailable', { amount: Number(item.at_least) }) }}</text> v-if="item.at_least > 0">满{{ Number(item.at_least) }}元可用</text>
<text class="coupon-least" :style="{ color: value.limitColor }" <text class="coupon-least" :style="{ color: value.limitColor }"
v-else>{{ $lang('components-diy.diy-coupon.noThresholdCoupon') }}</text> v-else>无门槛优惠券</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 || $lang('components-diy.diy-coupon.claimNow') }}</view> value.btnStyle.text || '立即领取' }}</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>
</view> </view>
@@ -203,9 +204,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' ? $lang('components-diy.diy-coupon.yuan') : $lang('components-diy.diy-coupon.discount') }}</text> <text class="unit">{{ item.discount == '0.00' ? '元' : '折' }}</text>
</view> </view>
<text class="text">{{ $lang('components-diy.diy-coupon.coupon') }}</text> <text class="text">优惠券</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,
@@ -221,11 +222,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">{{ $lang('components-diy.diy-coupon.goUse') }}</text> <text class="btn-content">去使用</text>
</text> </text>
<text class="limit" :style="{ color: value.limitColor }" <text class="limit" :style="{ color: value.limitColor }"
v-if="parseFloat(item.at_least) > 0">{{ $lang('components-diy.diy-coupon.minSpendUse', { amount: item.at_least | moneyConduct }) }}</text> v-if="parseFloat(item.at_least) > 0">满{{ item.at_least | moneyConduct }}元使用</text>
<text class="limit" :style="{ color: value.limitColor }" v-else>{{ $lang('components-diy.diy-coupon.noThresholdUse') }}</text> <text class="limit" :style="{ color: value.limitColor }" v-else>无门槛使用</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')"
@@ -237,9 +238,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">{{ $lang('components-diy.diy-coupon.noCoupons') }}</span> <span class="text">暂无优惠券</span>
</div> </div>
<span class="limit" :style="{ color: value.limitColor }">{{ $lang('components-diy.diy-coupon.goBrowse') }}</span> <span class="limit" :style="{ color: value.limitColor }">去逛逛</span>
</div> </div>
</swiper-item> </swiper-item>
</swiper> </swiper>
@@ -256,24 +257,25 @@
<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">{{ $lang('components-diy.diy-coupon.yuan') }}</text> <text class="font-size-tag coupon-sign">元</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">{{ $lang('components-diy.diy-coupon.discount') }}</text> <text class="font-size-tag coupon-sign">折</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">{{ $lang('components-diy.diy-coupon.minSpendAvailable', { amount: Number(item.at_least) }) }}</text> v-if="item.at_least > 0">满{{ Number(item.at_least) }}元可用</text>
<text class="coupon-name" :style="{ color: value.limitColor }" v-else>{{ $lang('components-diy.diy-coupon.noThresholdCoupon') }}</text> <text class="coupon-name" :style="{ color: value.limitColor }" v-else>无门槛优惠券</text>
<view class="coupon-least" :style="{ color: value.limitColor }">{{ $lang('components-diy.diy-coupon.validUntil', { date: $util.timeStampTurnTime(item.end_time, 'yearmonthday') }) }}</view> <view class="coupon-least" :style="{ color: value.limitColor }">有效期至{{
$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 || $lang('components-diy.diy-coupon.claimNow') }} {{ value.btnStyle.text || '立即领取' }}
</view> </view>
<view class="coupon-get" :style="couponBtnStyle" v-if="parseInt(item.useState)">{{ $lang('components-diy.diy-coupon.goUse') }} <view class="coupon-get" :style="couponBtnStyle" v-if="parseInt(item.useState)">去使用
</view> </view>
</view> </view>
</view> </view>
@@ -402,7 +404,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: this.$lang('components-diy.diy-coupon.couponSoldOut') title: '该优惠券已抢光'
}); });
return; return;
} }
@@ -425,7 +427,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 = this.$lang('components-diy.diy-coupon.claimSuccess'); msg = '领取成功';
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) {

View File

@@ -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 : '' }">{{ $lang('components-diy.diy-fenxiao-goods-list.earnPrefix') }}</text> :style="{ color: value.theme == 'diy' ? value.priceStyle.mainColor : '' }">赚 ¥</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.$lang('components-diy.diy-fenxiao-goods-list.followSuccess') }); this.$util.showToast({ title: '关注成功' });
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: this.$lang('components-diy.diy-fenxiao-goods-list.tip'), title: '提示',
content: this.$lang('components-diy.diy-fenxiao-goods-list.confirmUnfollow'), content: '确认取消关注该商品吗',
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 = this.$lang('components-diy.diy-fenxiao-goods-list.cancelSuccess'); msg = '取消成功';
} else { } else {
msg = res.message; msg = res.message;
} }

View File

@@ -3,7 +3,7 @@
:class="{ left_top: value.bottomPosition == 1, right_top: value.bottomPosition == 2, left_bottom: value.bottomPosition == 3, right_bottom: value.bottomPosition == 4 }" :class="{ left_top: value.bottomPosition == 1, right_top: value.bottomPosition == 2, left_bottom: value.bottomPosition == 3, right_bottom: value.bottomPosition == 4 }"
:style="style"> :style="style">
<block v-for="(item, index) in value.list" :key="index"> <block v-for="(item, index) in value.list" :key="index">
<view class="button-box" @tap.stop="onFloatBtnClick(item)" <view class="button-box" @tap.stop="$util.diyRedirectTo(item.link)"
:style="{ width: value.imageSize + 'px', height: value.imageSize + 'px', fontSize: value.imageSize + 'px' }"> :style="{ width: value.imageSize + 'px', height: value.imageSize + 'px', fontSize: value.imageSize + 'px' }">
<image v-if="!item.iconType || item.iconType == 'img'" :src="$util.img(item.imageUrl)" mode="aspectFit" <image v-if="!item.iconType || item.iconType == 'img'" :src="$util.img(item.imageUrl)" mode="aspectFit"
show-menu-by-longpress /> show-menu-by-longpress />
@@ -44,44 +44,7 @@ export default {
componentRefresh: function (nval) { } componentRefresh: function (nval) { }
}, },
components: {}, components: {},
methods: { methods: {},
/**
* 浮动按钮点击处理:
* 在跳转前给 link 注入 __dyu=FloatBtn 来源标记,
* 让目标页面(尤其是 ai-chat)能识别"来自浮动按钮"从而隐藏底部 tabBar,
* 与"从底部导航栏点击进入时显示并高亮 tabBar"的场景并存。
*
* 为什么用 __dyu 这种 3 字符命名:
* - 双下划线 __ 前缀 + 3 位字母(dy-ui 框架) 是前端约定俗成的"系统内部保留字段"标志
* (如 __proto__, __esModule),业务方配置 link 时几乎不可能使用这种短命名 → 与业务参数零冲突
* - URL 中占用空间极小,不污染业务 query 字符串
* - 未来如需扩展其他组件的入口来源,可继续使用 __dyu 前缀(如 __dyu=Banner / __dyu=Nav)
*
* 实现要点:
* - 浅拷贝 item.link 避免污染原数据(可能被 v-for 复用)
* - 把标记写入 page_params,diyRedirectTo → redirectTo 会自动拼到 URL query,
* 目标页 onLoad(options) 可直接读取
* - 同时在 wap_url 末尾追加/合并 __dyu=FloatBtn 兜底:某些路径不走 page_params 拼接
*/
onFloatBtnClick(item) {
if (!item || !item.link) return;
const link = { ...item.link };
link.page_params = Object.assign({}, link.page_params || {}, {
__dyu: 'FloatBtn'
});
// 兜底:直接把标记拼到 wap_url query,防止 page_params 在某些分支未被透传
if (link.wap_url && typeof link.wap_url === 'string' && link.wap_url.indexOf('http') === -1) {
const sep = link.wap_url.indexOf('?') === -1 ? '?' : '&';
// 避免重复追加(精确匹配 __dyu= 而不是 __dyu,避免误伤可能的 __dyu_other)
if (link.wap_url.indexOf('__dyu=') === -1) {
link.wap_url = link.wap_url + sep + '__dyu=FloatBtn';
}
}
this.$util.diyRedirectTo(link);
},
},
computed: { computed: {
style() { style() {
let style = {}, let style = {},

View File

@@ -1,354 +1,103 @@
<template> <template>
<view data-component-name="diy-form" class="diy-from" :style="diyFormStyle"> <view data-component-name="diy-form" class="diy-from" :style="style">
<!-- Banner --> <view class="fui-cell-group">
<!-- 鸿蒙元服务运行时在首次 _render 时 value 可能还是 undefined, <view class="fui-cell ">
下面所有 value.xxx 模板表达式都必须用 `value && value.xxx` 守护, <view class="fui-cell-label ">您的姓名</view>
否则会触发 MP 编译器注入的 propsToData 观察者(对应编译产物里 <view class="fui-cell-info">
r=function(){var o=this.value.show_banner...this.$mp.data...}) <input v-model="Form.realname" class="fui-input" placeholder="请输入您的姓名" value=""></input>
报 "Cannot read properties of undefined (reading 'show_banner')"。 --> </view>
<view v-if="value && value.show_banner && value.form_banner" class="form-banner" :style="bannerStyle"> </view>
<image :src="$util.img(value.form_banner)" mode="widthFix" class="banner-img" /> <view class="fui-cell ">
</view> <view class="fui-cell-label">手机号码</view>
<!-- 提示语 --> <view class="fui-cell-info">
<view v-if="value && value.show_tip && value.form_tip" class="form-tip" :style="tipStyle">{{ value && value.form_tip }}</view> <input v-model="Form.mobile" class="fui-input" maxlength="11" placeholder="请输入您的手机号"
<!-- 表单组件 --> type="number"></input>
<ns-newform </view>
:data="formComponents" </view>
:customAttr="value" <view class="fui-cell ">
:mode="mergedFormConfig.formLayout || 'horizontal'" <view class="fui-cell-label">您的邮箱</view>
:formConfig="mergedFormConfig" <view class="fui-cell-info">
ref="nsNewform" <input v-model="Form.mailbox" class="fui-input" placeholder="请输入您的邮箱" type="text"></input>
></ns-newform> </view>
<!-- 提交按钮(外层 = form-bg + form-padding-x;按钮 = submit-bg + submit-color + input-height + input-radius)。 </view>
showSubmit=false 时由父级页面渲染自己的提交按钮并通过 ref 调用本组件的 verify()/getFormData()。 --> <view class="fui-cell">
<view v-if="showSubmit" class="form-submit-wrap" :style="submitWrapStyle"> <view class="fui-cell-label">所在城市</view>
<view @click.stop="handleSubmit" class="form-submit" :style="submitStyle">{{ submitText }}</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>
// 自定义表单 // 自定义表单
// 提交接管三档(不依赖 $listeners / 事件机制,跨 H5 / MP / 鸿蒙一致):
// 1) 默认 → showSubmit=true + 不传 onSubmit → 内置按钮 + 内置 defaultSubmit
// 2) 复用按钮、自定义逻辑 → showSubmit=true + :onSubmit="fn" → 内置按钮 + 父级 fn
// 3) 完全自定义 UI → showSubmit=false + :onSubmit="fn" 或 ref.verify()/getFormData() → 父级全控
// 注:type: Function prop 在 uni-app MP 端走 Vue runtime 注入,机制与 ns-navbar.customBack 一致
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
},
// 父级可选地接管提交:传入函数 prop 时,verify 通过后由它处理 formData;
// 不传时走组件内置 defaultSubmit(兜底)。default 必须是 null,不能写成函数返回 null
onSubmit: {
type: Function,
default: null
} }
}, },
mixins: [DiyMinx], mixins: [DiyMinx],
data() { data() {
return { return {
formComponents: [] // 转换后的表单组件 loading: true,
markers: [],
Form: {
realname: '',
mobile: '',
mailbox: '',
citys: '',
remark: '',
}
}; };
}, },
created() { created() {
this.initForm();
}, },
watch: { watch: {
'value': { // 组件刷新监听
deep: true, componentRefresh: function (nval) {
handler() { // this.getDataList();
// 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() {
// 鸿蒙元服务运行时首次 _render 时 this.value 可能还是 undefined,必须全程加护
var css = ''; var css = '';
var v = this.value || {}; css += 'background-color:' + this.value.contentBgColor + ';';
css += 'background-color:' + (v.contentBgColor || '') + ';'; if (this.value.elementAngle == 'round') {
if (v.elementAngle === 'round') { css += 'border-top-left-radius:' + this.value.topElementAroundRadius * 2 + 'rpx;';
css += 'border-top-left-radius:' + (v.topElementAroundRadius || 0) * 2 + 'rpx;'; css += 'border-top-right-radius:' + this.value.topElementAroundRadius * 2 + 'rpx;';
css += 'border-top-right-radius:' + (v.topElementAroundRadius || 0) * 2 + 'rpx;'; css += 'border-bottom-left-radius:' + this.value.bottomElementAroundRadius * 2 + 'rpx;';
css += 'border-bottom-left-radius:' + (v.bottomElementAroundRadius || 0) * 2 + 'rpx;'; css += 'border-bottom-right-radius:' + this.value.bottomElementAroundRadius * 2 + 'rpx;';
css += 'border-bottom-right-radius:' + (v.bottomElementAroundRadius || 0) * 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 || '提交';
},
// 父级是否接管提交(集中判断,便于以后替换机制;避免多个调用点各自 typeof 校验)
hasCustomSubmit() {
return typeof this.onSubmit === 'function';
},
// 后端把表单样式配置统一存放在 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'),
labelFontWeight: pick('labelFontWeight', 'label_font_weight'),
labelAutoMaxWidth: pick('labelAutoMaxWidth', 'label_auto_max_width'),
requiredColor: pick('requiredColor', 'required_color'),
checkedColor: pick('checkedColor', 'checked_color'),
// 占位符:遗漏会被 ns-newform SCSS 默认值回退覆盖
placeholderColor: pick('placeholderColor', 'placeholder_color'),
placeholderFontSize: pick('placeholderFontSize', 'placeholder_font_size'),
// textarea 显示行数 / 行高(透传给 ns-newform,与 ns-form 保持一致)
// 不传时 ns-newform 走自己的默认 4 行 / 44rpx
textareaRows: pick('textareaRows', 'textarea_rows'),
textareaLineHeight: pick('textareaLineHeight', 'textarea_line_height'),
// 输入框视觉增强(与 ns-newform 对齐)
inputBorderColor: pick('inputBorderColor', 'input_border_color'),
inputBgColor: pick('inputBgColor', 'input_bg_color'),
inputFocusBorderColor: pick('inputFocusBorderColor', 'input_focus_border_color'),
inputFocusBgColor: pick('inputFocusBgColor', 'input_focus_bg_color'),
submitText: pick('submitText', 'submit_text'),
submitColor: pick('submitColor', 'submit_color'),
submitBgColor: pick('submitBgColor', 'submit_bg_color'),
// 提交按钮尺寸:宽度百分比 + 尺寸预设(与后端 design.js 对齐)
submitWidthPercent: pick('submitWidthPercent', 'submit_width_percent'),
submitSize: pick('submitSize', 'submit_size'),
submitMarginTop: pick('submitMarginTop', 'submit_margin_top'),
// 提示语
tipFontSize: pick('tipFontSize', 'tip_font_size'),
tipColor: pick('tipColor', 'tip_color'),
tipBgColor: pick('tipBgColor', 'tip_bg_color'),
tipBorderColor: pick('tipBorderColor', 'tip_border_color')
};
// 移除 undefined / 空字符串(保留 0/false)
Object.keys(base).forEach(function(k) {
if (base[k] === undefined || base[k] === null || base[k] === '') {
delete base[k];
}
});
// 平台差异化配置(terminal 块在 formConfig 子对象内)
// 优先级:v.formConfig.terminal > v.form_config_terminal > v.terminal > v.form_config_platform
const result = Object.assign({}, base);
const termBlock = (v.formConfig && v.formConfig.terminal) || v.form_config_terminal || v.terminal || v.form_config_platform;
if (termBlock && typeof termBlock === 'object') {
Object.keys(termBlock).forEach(function(platform) {
var src = termBlock[platform];
if (!src) return;
// 嵌套值若为 snake_case(部分序列化路径),在此统一转 camelCase
var translated = {};
Object.keys(src).forEach(function(k) {
translated[self.$util.snakeToCamel(k)] = src[k];
});
result[platform] = translated;
});
}
return result;
} }
}, },
methods: { methods: {
// 初始化表单 - 将 diy-form 的数据格式转换成 ns-newform 的格式 submitform() {
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;
},
// 统一提交入口:内置按钮 / 父级 ref 调用都走这里
// 不依赖 $listeners / 事件机制(MP 端 $listeners 为 undefined),跨端一致
handleSubmit() {
// 校验(同时返回 formData 数组;校验失败时 ns-newform 内部 toast 提示)
if (!this.verify()) {
return;
}
const formData = this.getFormData();
// 父级显式接管:function prop 在 H5 / MP / 鸿蒙一致可用
if (this.hasCustomSubmit) {
return this.onSubmit(formData);
}
// 兜底:内置 sendRequest 流程
this.defaultSubmit(formData);
},
// 公共兜底实现:默认的 /form/api/form/create 流程;
// 父级若需"先自定义、失败回退",可经 ref.defaultSubmit(formData) 调用
defaultSubmit(submitFormData) {
var self = this;
this.$api.sendRequest({ this.$api.sendRequest({
url: '/form/api/form/create', url: '/api/member/information',
data: { data: this.Form,
form_id: this.value.form_id || 0, success: res => {
form_data: typeof submitFormData === 'string' ? submitFormData : JSON.stringify(submitFormData), this.$util.showToast({
component_id: this.value.id || '', title: res.message
form_name: this.value.form_name || '默认表单' });
},
success: function(res) {
if (res.code === 0) {
uni.showToast({
title: self.$lang('submitSuccess'),
icon: 'success'
});
// 重置表单
if (self.$refs.nsNewform && self.$refs.nsNewform.setFormData) {
self.$refs.nsNewform.setFormData();
}
} else {
uni.showToast({
title: res.message || self.$lang('submitFail'),
icon: 'none'
});
}
} }
}); });
} }
@@ -359,54 +108,7 @@ export default {
<style lang="scss"> <style lang="scss">
.diy-from { .diy-from {
background: #fff; background: #fff;
padding: 0; padding-bottom: 20rpx;
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>

View File

@@ -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="imgMode" @error="imgError(index)" mode="widthFix" @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 : '' }">
{{ $lang('components-diy.diy-goods-list.soldCount', { count: item.sale_num, unit: item.unit || $lang('components-diy.diy-goods-list.soldUnit') }) }} 已售{{ item.sale_num }}{{ item.unit ? item.unit : '件' }}
</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="imgMode" @error="imgError(index)" :src="$util.img(item.goods_image, { size: 'mid' })" mode="widthFix" @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 : '' }">
{{ $lang('components-diy.diy-goods-list.soldCount', { count: item.sale_num, unit: item.unit || $lang('components-diy.diy-goods-list.soldUnit') }) }} 已售{{ item.sale_num }}{{ item.unit ? item.unit : '件' }}
</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="imgMode" :src="$util.img(dataItem.goods_image, { size: 'mid' })" mode="widthFix"
@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 : '' }">
{{ $lang('components-diy.diy-goods-list.soldCount', { count: dataItem.sale_num, unit: dataItem.unit || $lang('components-diy.diy-goods-list.soldUnit') }) }} 已售{{ dataItem.sale_num }}{{ dataItem.unit ? dataItem.unit : '件' }}
</view> </view>
</view> </view>
</view> </view>
@@ -302,19 +302,6 @@ 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 + ';';

View File

@@ -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 : '' }">
{{ $lang('components-diy.diy-goods-recommend.soldPrefix') }}{{ dataItem.sale_num }}{{ dataItem.unit ? dataItem.unit : $lang('unit.piece') }} 售{{ dataItem.sale_num }}{{ dataItem.unit ? dataItem.unit : '件' }}
</view> </view>
</view> </view>
</view> </view>

View File

@@ -159,10 +159,7 @@
<!-- 商品推荐 --> <!-- 商品推荐 -->
<diy-goods-recommend :value="item"></diy-goods-recommend> <diy-goods-recommend :value="item"></diy-goods-recommend>
</template> </template>
<template v-if="item.componentName == 'DiyRecommendCode'">
<!-- 自定义推荐码组件 -->
<diy-recommend-code :value="item"></diy-recommend-code>
</template>
<template v-if="item.componentName == 'GoodsBrand'"> <template v-if="item.componentName == 'GoodsBrand'">
<!-- 商品品牌 --> <!-- 商品品牌 -->
<diy-goods-brand :value="item"></diy-goods-brand> <diy-goods-brand :value="item"></diy-goods-brand>
@@ -294,103 +291,77 @@ export default {
mixins: [DiyMinx], mixins: [DiyMinx],
data() { data() {
return { return {
diyGlobalData: this.diyData ? this.$util.deepClone(this.diyData) : null, diyGlobalData: null
processedData: null
}; };
}, },
watch: {
diyData: {
handler() {
this.diyGlobalData = this.diyData ? this.$util.deepClone(this.diyData) : null;
this.processData();
this._notifyLoaded();
},
deep: true
}
},
created() { created() {
console.log('[DIY-GROUP][created] hasDiyData=', !!this.diyData, 'valueLen=', this.diyData && this.diyData.value && this.diyData.value.length); this.diyGlobalData = JSON.parse(JSON.stringify(this.diyData));
this.processData();
},
mounted() {
console.log('[DIY-GROUP][mounted] hasDiyData=', !!this.diyData, 'valueLen=', this.diyData && this.diyData.value && this.diyData.value.length);
if (this.diyData && this.diyData.value) {
this._notifyLoaded();
}
}, },
computed: { computed: {
topNavColor() { topNavColor() {
if (!this.diyData?.global) return ''; var color = '';
if (this.diyData.global.topNavBg) {
const { topNavBg, topNavColor } = this.diyData.global; color = 'transparent';
if (this.scrollTop > 20) {
if (topNavBg) { color = this.diyData.global.topNavColor;
return this.scrollTop > 20 ? topNavColor : 'transparent'; } else {
} color = 'transparent';
}
return topNavColor; } else {
}, color = this.diyData.global.topNavColor;
diyDataArray() { }
if (!this.processedData) { return color;
this.processData(); },
} // 修改属性样式
setPagestyle() {
const showModuleData = this.$store.state.diyGroupShowModule this.diyGlobalData.value.forEach((item, index) => {
? JSON.parse(this.$store.state.diyGroupShowModule) item.pageStyle = '';
: null; // 给每个组件增加位置属性,用于定位,搜索、分类导航等定位
// 如果是Tab组件内部的子组件,添加tabIndex前缀避免moduleIndex冲突
if (!showModuleData || !showModuleData.length) { if (this.diyData.tabIndex !== undefined) {
return this.processedData || []; item.moduleIndex = `${this.diyData.tabIndex}-${index + 1}`;
} } else {
item.moduleIndex = index + 1;
if (showModuleData.includes('null')) { }
return [];
} // 特殊处理搜索框 当显示位置为滚动至顶部固定时,只设置背景颜色
if (item.componentName == 'Search' && item.positionWay == 'fixed') {
return (this.processedData || []).filter(item => // item.pageStyle = 'background-color:' + item.pageBgColor + ';';
showModuleData.includes(item.componentName) return false;
); }
}
}, item.pageStyle += 'background-color:' + item.pageBgColor + ';';
methods: { if (item.margin) {
_notifyLoaded() { item.pageStyle += 'padding-top:' + item.margin.top * 2 + 'rpx' + ';';
console.log('[DIY-GROUP][_notifyLoaded] enter, will emit loaded in 300ms'); item.pageStyle += 'padding-bottom:' + item.margin.bottom * 2 + 'rpx' + ';';
if (this._loadedTimer) clearTimeout(this._loadedTimer); item.pageStyle += 'padding-right:' + item.margin.both * 2 + 'rpx' + ';';
this._loadedTimer = setTimeout(() => { item.pageStyle += 'padding-left:' + item.margin.both * 2 + 'rpx' + ';';
console.log('[DIY-GROUP][_notifyLoaded] emit loaded');
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;
}); });
return this.diyGlobalData.value;
},
// 过滤组件的渲染
diyDataArray() {
let data = [],
showModuleData = this.$store.state.diyGroupShowModule ? JSON.parse(this.$store.state
.diyGroupShowModule) : '';
if (showModuleData.length) {
if (showModuleData.includes('null')) return [];
let diyDataArr = this.setPagestyle;
diyDataArr.forEach((item, index) => {
if (showModuleData.includes(item.componentName)) {
data.push(item);
}
});
} else data = this.setPagestyle;
return data;
} }
} },
methods: {}
}; };
</script> </script>

View File

@@ -1,5 +1,5 @@
<template> <template>
<view :style="componentStyle" data-component-name="diy-image-nav"> <view :style="componentStyle">
<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,35 +54,12 @@ 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) {
// 监听组件刷新 // 监听组件刷新
@@ -138,163 +115,6 @@ 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
} }
} }
} }
@@ -320,25 +140,6 @@ 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 {

View File

@@ -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">已售{{
$lang('components-diy.diy-index-page.soldCount', { count: item.sale_num, unit: item.unit || $lang('components-diy.diy-index-page.soldUnit') }) }}</view> item.sale_num }}{{ item.unit ? item.unit : '件' }}</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="$lang('components-diy.diy-index-page.noGoodsInCategory')" :isIndex="false"></ns-empty> <ns-empty text="该分类下暂无商品" :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,9 +258,6 @@ 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) {
@@ -326,7 +323,7 @@ export default {
let obj = { let obj = {
list: [] list: []
}; };
obj.category_name = this.value.title ? this.value.title : this.$lang('components-diy.diy-index-page.home'); obj.category_name = this.value.title ? this.value.title : '首页';
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) => {

View File

@@ -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()">{{ $lang('components-diy.diy-kefu.addNow') }}</span> :style="{ background: item.BtBgColor, color: item.BtColor }" @tap.stop="previewSqs()">立即添加</span>
</view> </view>
</view> </view>
</view> </view>

View File

@@ -12,10 +12,9 @@
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" @tap.stop="redirectTo(item.link)" style="font-size: 24rpx;">{{ $lang('components-diy.diy-listmenu.view') }}</view> <view class="fui-cell-remark" style="font-size: 24rpx;">{{ lang == 'en-us' ? 'view' : '查看' }}</view>
</view> </view>
</view> </view>
<ns-login ref="login"></ns-login>
</view> </view>
</template> </template>
@@ -33,6 +32,7 @@ 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.redirectTologin(link.wap_url) this.$refs?.login?.open(link.wap_url);
return; return;
} }
} }

View File

@@ -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">{{ $lang('components-diy.diy-live.anchorPrefix') }}{{ liveInfo.anchor_name }}</text> <text class="anchor-name">主播:{{ 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">{{ $lang('components-diy.diy-live.goodsPrefix') }}{{ liveInfo.goods.length }}</text> <text class="goods-text">直播商品:{{ liveInfo.goods.length }}</text>
</block> </block>
</view> </view>
</view> </view>

View File

@@ -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;">{{ $lang('components-diy.diy-map.navigate') }}</span> <span style="font-size:24rpx;color: #fff;">一键导航</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: this.$lang('components-diy.diy-map.navigate'), name: "一键导航",
}) })
}, },
async handlerClick(item) { async handlerClick(item) {

View File

@@ -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">{{ $lang('components-diy.diy-member-info.clickToAuthorizeAvatarNickname') }}</text></view> <view class="nickname"><text class="name" @tap.stop="getWxAuth">点击授权头像昵称</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">{{ $lang('components-diy.diy-member-info.clickToGetWechatAvatar') }}</text></view> <view class="nickname"><text class="name" @tap.stop="getWxAuth">点击获取微信头像</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('member.index.login') }}</text></view> <view class="nickname"><text class="name">{{ $lang('login') }}</text></view>
<view class="desc">{{ $lang('member.index.loginTips') }}</view> <view class="desc">{{ $lang('loginTpis') }}</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('member.index.balance') }}</view> <view class="title">{{ $lang('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('member.index.point') }}</view> <view class="title">{{ $lang('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('member.index.coupon') }}</view> <view class="title">{{ $lang('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('member.index.balance') }}</view> <view class="title">{{ $lang('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('member.index.point') }}</view> <view class="title">{{ $lang('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('member.index.coupon') }}</view> <view class="title">{{ $lang('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">{{ $lang('components-diy.diy-member-info.completeInfoTitle') }}</text> <text class="title">获取您的昵称、头像</text>
<text class="color-tip tips">{{ $lang('components-diy.diy-member-info.completeInfoTip') }}</text> <text class="color-tip tips">获取用户头像、昵称完善个人资料,主要用于向用户提供具有辨识度的用户中心界面</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">{{ $lang('components-diy.diy-member-info.avatarLabel') }}</text> <text class="label">头像</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">{{ $lang('components-diy.diy-member-info.nicknameLabel') }}</text> <text class="label">昵称</text>
<input type="nickname" :placeholder="$lang('components-diy.diy-member-info.nicknamePlaceholder')" v-model="nickName" @blur="blurNickName" /> <input type="nickname" placeholder="请输入昵称" 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">{{ $lang('components-diy.diy-member-info.avatarLabel') }}</text> <text class="label">头像</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">{{ $lang('components-diy.diy-member-info.nicknameLabel') }}</text> <text class="label">昵称</text>
<input type="nickname" :placeholder="$lang('components-diy.diy-member-info.nicknamePlaceholder')" v-model="nickName" @blur="blurNickName" /> <input type="nickname" placeholder="请输入昵称" v-model="nickName" @blur="blurNickName" />
</view> </view>
<!-- #endif --> <!-- #endif -->
<button type="default" class="save-btn" @tap.stop="saveCompleteInfo" :disabled="isDisabled">{{ $lang('components-diy.diy-member-info.save') }}</button> <button type="default" class="save-btn" @tap.stop="saveCompleteInfo" :disabled="isDisabled">保存</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: this.$lang('components-diy.diy-member-info.tip'), title: '提示',
content: this.$lang('components-diy.diy-member-info.bindMobileTip'), content: '使用会员码需先绑定手机号,是否绑定手机号?',
success: res => { success: res => {
if (res.confirm) { if (res.confirm) {
// #ifdef MP-WEIXIN // #ifdef MP-WEIXIN
@@ -566,10 +566,6 @@ export default {
this.$util.redirectTo(url); this.$util.redirectTo(url);
} }
// #endif // #endif
// #ifndef MP || H5
this.$util.redirectTo(url);
// #endif
}, },
/** /**
* 获取微信授权 * 获取微信授权
@@ -634,19 +630,16 @@ export default {
}); });
}, },
openCompleteInfoPop(callback) { openCompleteInfoPop(callback) {
this.$refs.completeInfoPopup.open(); this.$refs.completeInfoPopup.open(() => {
// 关闭时(setBottomNavHidden=false)由 saveCompleteInfo / cancelCompleteInfo 显式处理, this.$store.commit('setBottomNavHidden', false); //显示底部导航
// 不在 open 回调里写 — 回调在"弹窗被销毁/页面被卸载"等异常路径下不保证触发,会卡住 TabBar 隐藏态 });
// TabBar 根页面(如会员中心)不能藏 TabBar — 否则会被自己藏起来 this.$store.commit('setBottomNavHidden', true); // 隐藏底部导航
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: this.$lang('components-diy.diy-member-info.pleaseEnterNickname') title: '请输入昵称'
}); });
return; return;
} }
@@ -685,7 +678,7 @@ export default {
}, },
fail: () => { fail: () => {
this.$util.showToast({ this.$util.showToast({
title: this.$lang('components-diy.diy-member-info.uploadFailed') title: '上传失败'
}); });
} }
}) })
@@ -716,7 +709,7 @@ export default {
}, },
fail: () => { fail: () => {
this.$util.showToast({ this.$util.showToast({
title: this.$lang('components-diy.diy-member-info.avatarPullFailed') title: '头像拉取失败'
}); });
} }
}) })
@@ -865,11 +858,7 @@ 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;
// P0: 用现有 token,主题切换时会员卡背景跟着变 background: linear-gradient(107deg, #7c7878 0%, #201a18 100%);
// 旧字面: #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;
@@ -950,12 +939,7 @@ export default {
} }
.super-text { .super-text {
// P0: 3 停渐变 → 2 停(start + end),token 化 background-image: linear-gradient(90deg, #ffdba6 0%, #ffebca 49%, #f7c774 100%);
// 旧字面: #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;
@@ -1005,11 +989,7 @@ export default {
.super-member { .super-member {
color: #8d4b16; color: #8d4b16;
// P0 注释 A 修复: 之前这个渐变是 black preset 的字面,导致 data-style-2 在 default 主题下显示错误 background: linear-gradient(107deg, #fadcb5 0%, #f6bd74 100%);
// 现在用 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;
@@ -1509,4 +1489,4 @@ export default {
border-top-left-radius: 30rpx !important; border-top-left-radius: 30rpx !important;
border-top-right-radius: 30rpx !important; border-top-right-radius: 30rpx !important;
} }
</style> </style>

View File

@@ -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" @tap.stop="handlerClick(item)"> <view class="merch-img">
<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" @tap.stop="handlerClick(item)">{{ item.merch_name }}</text> <text class="title">{{ 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,16 +27,14 @@
<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>
@@ -64,31 +62,31 @@ export default {
list: [ list: [
/*{ /*{
merch_name:'品牌', merch_name:'品牌',
merch_image:'https://saas.cn//upload/4/common/images/20240824/20240824040223172448654356147.jpg' merch_image:'http://saas.cn//upload/4/common/images/20240824/20240824040223172448654356147.jpg'
}, },
{ {
merch_name:'品牌', merch_name:'品牌',
merch_image:'https://saas.cn//upload/4/common/images/20240824/20240824040223172448654356147.jpg' merch_image:'http://saas.cn//upload/4/common/images/20240824/20240824040223172448654356147.jpg'
}, },
{ {
merch_name:'品牌', merch_name:'品牌',
merch_image:'https://saas.cn//upload/4/common/images/20240824/20240824040223172448654356147.jpg' merch_image:'http://saas.cn//upload/4/common/images/20240824/20240824040223172448654356147.jpg'
}, },
{ {
merch_name:'品牌', merch_name:'品牌',
merch_image:'https://saas.cn//upload/4/common/images/20240824/20240824040223172448654356147.jpg' merch_image:'http://saas.cn//upload/4/common/images/20240824/20240824040223172448654356147.jpg'
}, },
{ {
merch_name:'品牌', merch_name:'品牌',
merch_image:'https://saas.cn//upload/4/common/images/20240824/20240824040223172448654356147.jpg' merch_image:'http://saas.cn//upload/4/common/images/20240824/20240824040223172448654356147.jpg'
}, },
{ {
merch_name:'品牌', merch_name:'品牌',
merch_image:'https://saas.cn//upload/4/common/images/20240824/20240824040223172448654356147.jpg' merch_image:'http://saas.cn//upload/4/common/images/20240824/20240824040223172448654356147.jpg'
}, },
{ {
merch_name:'品牌', merch_name:'品牌',
merch_image:'https://saas.cn//upload/4/common/images/20240824/20240824040223172448654356147.jpg' merch_image:'http://saas.cn//upload/4/common/images/20240824/20240824040223172448654356147.jpg'
}*/ }*/
], ],
loading: true, loading: true,

View File

@@ -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">{{ $lang('components-diy.diy-notes.readPrefix') }} {{ <text v-show="value.readNum == 1 && item.is_show_read_num == 1">阅读 {{
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>
</view> </scroll-view>
</scroll-view>
<ns-login ref="login"></ns-login> <ns-login ref="login"></ns-login>
</view> </view>

View File

@@ -9,8 +9,7 @@
<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"
@@ -28,8 +27,7 @@
<!-- 上下滚动 --> <!-- 上下滚动 -->
<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" <swiper-item v-for="(item, index) in list" :key="index" @touchmove.prevent.stop>
@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 }}
@@ -44,11 +42,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>{{ $lang('components-diy.diy-notice.notice') }}</text> <text>公告</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">{{ $lang('components-diy.diy-notice.gotIt') }}</button> <button type="primary" @tap.stop="closeNoticePopup">我知道了</button>
</view> </view>
</uni-popup> </uni-popup>
</view> </view>
@@ -138,11 +136,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 (item.link && (item.link.wap_url || item.link.appid || item.link.name)) { } else if (Object.keys(item.link).length > 1) {
this.$util.diyRedirectTo(item.link); this.$util.diyRedirectTo(item.link);
} else { } else {
// 如果不设置跳转链接,则点击弹框展示 // 如果不设置跳转链接,则点击弹框展示
this.notice = item.content || item.title || ''; this.notice = item.title;
this.$refs.noticePopup.open(); this.$refs.noticePopup.open();
} }
}, },

View File

@@ -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>{{ $lang('components-diy.diy-payment-qrcode.description') }}</text> <text>门店消费时使用,支付时点击下方展示付款码</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">{{ $lang('components-diy.diy-payment-qrcode.paymentCode') }}</text> <text class="action-name">付款码</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">{{ $lang('components-diy.diy-payment-qrcode.scanToPay') }}</text> <text class="action-name">扫码付</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">{{ $lang('components-diy.diy-payment-qrcode.storePayment') }}</text> <text class="name">门店支付</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>{{ $lang('components-diy.diy-payment-qrcode.popupTipTitle') }}</text> <text>提示</text>
<text class="iconfont icon-close"></text> <text class="iconfont icon-close"></text>
</view> </view>
<view class="content-wrap">{{ $lang('components-diy.diy-payment-qrcode.scanToPayTip') }}</view> <view class="content-wrap">扫码付请退出程序后直接使用微信扫一扫或返回上一页使用付款码进行支付</view>
<button type="primary" @tap.stop="closePaymentPopup">{{ $lang('components-diy.diy-payment-qrcode.gotIt') }}</button> <button type="primary" @tap.stop="closePaymentPopup">我知道了</button>
</view> </view>
</uni-popup> </uni-popup>
</view> </view>

View File

@@ -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" :key="index" style="line-height: 0;"> <view v-for="(item, index) in value.list" 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,7 +11,6 @@
<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>

View File

@@ -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>{{ $lang('components-diy.diy-pinfan.peopleGroup', { num: item.pintuan_num }) }}</text> <text>{{ 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>{{ $lang('components-diy.diy-pinfan.soldCount', { num: item.order_num }) }}</text> <text>已拼{{ item.order_num }}件</text>
</view> </view>
</view> </view>
<view class="price-wrap"> <view class="price-wrap">
@@ -49,9 +49,10 @@
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">{{ $lang('components-diy.diy-pinfan.backPoints', { num: item.reward_type_num }) }}</text> <text class="fan" v-if="item.reward_type == 4">返{{ item.reward_type_num }}积分</text>
<text class="fan" v-if="item.reward_type == 1 || item.reward_type == 2">{{ $lang('components-diy.diy-pinfan.backCash', { 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 == 3">{{ $lang('components-diy.diy-pinfan.backCoupon') }}</text> item.reward_type_num }}</text>
<text class="fan" v-if="item.reward_type == 3">返优惠券</text>
</button> </button>
</view> </view>
</view> </view>
@@ -77,21 +78,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 : '' }">
{{ $lang('components-diy.diy-pinfan.peopleGroup', { num: item.pintuan_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">
{{ $lang('components-diy.diy-pinfan.backPoints', { num: item.reward_type_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">
{{ $lang('components-diy.diy-pinfan.backCash', { num: item.reward_type_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">{{ $lang('components-diy.diy-pinfan.backCoupon') }}</text> v-if="item.reward_type == 3">返优惠券</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"
@@ -128,22 +129,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 : '' }">
{{ $lang('components-diy.diy-pinfan.peopleGroup', { num: item.pintuan_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">
{{ $lang('components-diy.diy-pinfan.backPoints', { num: item.reward_type_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">
{{ $lang('components-diy.diy-pinfan.backCash', { num: item.reward_type_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">

View File

@@ -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' ? $lang('components-diy.diy-pintuan.peopleParticipating') : $lang('components-diy.diy-pintuan.peopleGroupSuccess') }}</text> <text>{{ value.titleStyle.style == 'style-2' ? '人参与' : '人拼团成功' }}</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>{{ $lang('components-diy.diy-pintuan.peopleGroup', { num: item.pintuan_num }) }}</text> <text>{{ 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>{{ $lang('components-diy.diy-pintuan.soldCount', { num: item.order_num }) }}</text> <text>已拼{{ 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 + ')' : ''
}"> }">
{{ $lang('components-diy.diy-pintuan.peopleGroup', { num: item.pintuan_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">{{ $lang('components-diy.diy-pintuan.joinGroup') }}</view> <view class="sale-action">去参团</view>
</view> </view>
<view class="sale-num" v-if="value.style == 'style-2'">{{ $lang('components-diy.diy-pintuan.soldCount', { num: item.sale_num }) }}</view> <view class="sale-num" v-if="value.style == 'style-2'">已拼{{ 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 + ')' : ''
}"> }">
{{ $lang('components-diy.diy-pintuan.peopleGroup', { num: item.pintuan_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'">{{ $lang('components-diy.diy-pintuan.soldCount', { num: item.sale_num }) }}</view> <view class="sale-num" v-if="value.style == 'style-2'">已拼{{ item.sale_num }}件</view>
</view> </view>
</view> </view>
</swiper-item> </swiper-item>
@@ -451,10 +451,7 @@ scroll-view ::-webkit-scrollbar {
width: 40rpx; width: 40rpx;
height: 40rpx; height: 40rpx;
border-radius: 50%; border-radius: 50%;
// P0: 拼团头像红边框 → var(--pintuan-avatar-border) border: 2rpx solid #ff3d3d;
// 兼容: 微信小程序 / 鸿蒙元服务 — border 接受 var() 无问题
// 注: 改名避免与现有 pintuan_label_color(白字)冲突
border: 2rpx solid var(--pintuan-avatar-border, #ff3d3d);
margin-left: -14rpx; margin-left: -14rpx;
} }
@@ -485,10 +482,7 @@ scroll-view ::-webkit-scrollbar {
align-items: center; align-items: center;
justify-content: center; justify-content: center;
height: 36rpx; height: 36rpx;
// P0: 拼团头渐变 → var(--pintuan-label-grad-start/end) background: linear-gradient(270deg, #ffbd5b 0%, #fd882e 100%);
// 兼容: 微信小程序 / 鸿蒙元服务 — 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;
@@ -501,9 +495,7 @@ 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;
// P0: 拼团头文字色 → var(--pintuan-label-grad-start) 复用 color: #ffbd5b;
// 兼容: 微信小程序 / 鸿蒙元服务 — 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;
@@ -807,10 +799,7 @@ scroll-view ::-webkit-scrollbar {
font-size: $font-size-tag; font-size: $font-size-tag;
width: 94rpx; width: 94rpx;
height: 44rpx; height: 44rpx;
// P0: 拼团成功绿渐变 → var(--pintuan-success-start/end) background: linear-gradient(131deg, #3edb73 0%, #1db576 100%);
// 兼容: 微信小程序 / 鸿蒙元服务 — 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;

File diff suppressed because it is too large Load Diff

View File

@@ -91,52 +91,14 @@ export default {
}, },
data() { data() {
return { return {
customHtml: '', customHtml: ''
processedList: []
}; };
}, },
created() { created() {
this.processValue(); if (this.value.mode == 'custom-rubik-cube') {
}, this.value.diyHtml = this.value.diyHtml.replace(/&quot;/g, '"');
watch: { this.customHtml = htmlParser(this.value.diyHtml);
value: { } else {
handler() {
this.processValue();
},
deep: true
}
},
mixins: [DiyMinx],
computed: {
list() {
return this.processedList;
},
rubikCubeWrapCss() {
var obj = '';
obj += 'background-color:' + this.value.componentBgColor + ';';
if (this.value.componentAngle == 'round') {
obj += 'border-top-left-radius:' + this.value.topAroundRadius * 2 + 'rpx;';
obj += 'border-top-right-radius:' + this.value.topAroundRadius * 2 + 'rpx;';
obj += 'border-bottom-left-radius:' + this.value.bottomAroundRadius * 2 + 'rpx;';
obj += 'border-bottom-right-radius:' + this.value.bottomAroundRadius * 2 + 'rpx;';
}
return obj;
}
},
methods: {
// 统一处理 value prop:首次加载和 value 变化时都走这里
processValue() {
if (!this.value || !this.value.mode) return;
if (this.value.mode == 'custom-rubik-cube') {
const diyHtml = (this.value.diyHtml || '').replace(/&quot;/g, '"');
this.customHtml = htmlParser(diyHtml);
} else {
this.initList();
this.recalcLayout();
}
},
// 根据当前 mode 派发到对应的 calcXxx
recalcLayout() {
var singleRow = { var singleRow = {
'row1-of2': { 'row1-of2': {
ratio: 2, ratio: 2,
@@ -163,18 +125,34 @@ 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();
} }
}, }
initList() { },
if (!this.value.list || !Array.isArray(this.value.list)) { mixins: [DiyMinx],
this.processedList = []; watch: {
return; // 组件刷新监听
} componentRefresh: function (nval) { }
this.processedList = this.value.list.map((item, index) => { },
const newItem = { ...item }; computed: {
newItem.pageItemStyle = this.countBorderRadius(this.value.mode, index); list() {
return newItem; var arr = JSON.parse(JSON.stringify(this.value.list));
arr.forEach((item, index) => {
item.pageItemStyle = this.countBorderRadius(this.value.mode, index);
}); });
return arr;
}, },
rubikCubeWrapCss() {
var obj = '';
obj += 'background-color:' + this.value.componentBgColor + ';';
if (this.value.componentAngle == 'round') {
obj += 'border-top-left-radius:' + this.value.topAroundRadius * 2 + 'rpx;';
obj += 'border-top-right-radius:' + this.value.topAroundRadius * 2 + 'rpx;';
obj += 'border-bottom-left-radius:' + this.value.bottomAroundRadius * 2 + 'rpx;';
obj += 'border-bottom-right-radius:' + this.value.bottomAroundRadius * 2 + 'rpx;';
}
return obj;
}
},
methods: {
/** /**
* 魔方:单行多个,平分宽度 * 魔方:单行多个,平分宽度
* 公式: * 公式:

View File

@@ -28,8 +28,7 @@
@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)' }" :style="{ 'backgroundColor': value.pageBgColor ? value.pageBgColor : 'rgba(0,0,0,0)' }">搜索</text>
>{{ $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)">

View File

@@ -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">{{ $lang('components-diy.diy-seckill.countdownStart') }}</text> :style="{ color: value.titleStyle.textColor }" class="seckill-style-name">距离开始</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 ?
$lang('components-diy.diy-seckill.countdownStart') : $lang('components-diy.diy-seckill.countdownEnd') }}</text> '距离开始' : '距离结束' }}</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 : '' }">
{{ $lang('components-diy.diy-seckill.soldPercent', { percent: item.goods_stock + item.sale_num ? ((item.sale_num / (item.goods_stock + 已抢{{ 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 : '' }">{{ $lang('components-diy.diy-seckill.originalPrice') }}</text> :style="{ color: value.theme == 'diy' ? value.priceStyle.lineColor : '' }">原价:</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 ? $lang('components-diy.diy-seckill.comingSoon') : value.btnStyle.text }} {{ isFuture ? '即将开始' : 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 ? $lang('components-diy.diy-seckill.comingSoon') : value.btnStyle.text }} {{ isFuture ? '即将开始' : 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: this.$lang('components-diy.diy-seckill.seckillComingSoonTip') title: '秒杀活动即将开启,敬请期待!'
}); });
return false; return false;
} }
@@ -796,16 +796,12 @@ scroll-view ::-webkit-scrollbar {
height: 20rpx; height: 20rpx;
border-radius: 20rpx; border-radius: 20rpx;
margin-right: 20rpx; margin-right: 20rpx;
// P0: 秒杀价签浅底 → var(--seckill-price-shallow) background-color: #fcecd7;
// 兼容: 微信小程序 / 鸿蒙元服务 — background-color 接受 var() 无问题
background-color: var(--seckill-price-shallow, #fcecd7);
.curr { .curr {
height: 20rpx; height: 20rpx;
border-radius: 20rpx; border-radius: 20rpx;
// P0: 秒杀价签深色 → var(--seckill-price-start) background-color: #fdbe6c;
// 兼容: 微信小程序 / 鸿蒙元服务 — background-color 接受 var() 无问题
background-color: var(--seckill-price-start, #fdbe6c);
} }
} }
@@ -892,21 +888,15 @@ scroll-view ::-webkit-scrollbar {
.content .progress { .content .progress {
.num { .num {
// P0: 秒杀进度数字红 → var(--seckill-promo-color) color: #ff3d3d;
// 兼容: 微信小程序 / 鸿蒙元服务 — color 接受 var() 无问题
color: var(--seckill-promo-color, #ff3d3d);
} }
.bg { .bg {
// P0: 秒杀进度浅底 → var(--seckill-price-shallow) 复用 background-color: #ffd5d5;
// 兼容: 微信小程序 / 鸿蒙元服务 — background-color 接受 var() 无问题
background-color: var(--seckill-price-shallow, #ffd5d5);
.curr { .curr {
position: relative; position: relative;
// P0: 秒杀进度深红 → var(--seckill-discount-start) 复用 background-color: #ff0400 !important;
// 兼容: 微信小程序 / 鸿蒙元服务 — background-color 接受 var() 无问题
background-color: var(--seckill-discount-start, #ff0400) !important;
} }
} }
} }
@@ -1188,10 +1178,7 @@ scroll-view ::-webkit-scrollbar {
white-space: nowrap; white-space: nowrap;
font-weight: bold; font-weight: bold;
line-height: 1; line-height: 1;
// P0: 秒杀折扣红渐变 → var(--seckill-discount-start/end) background: linear-gradient(to right, #ff5f17, #fe2f18);
// 兼容: 微信小程序 / 鸿蒙元服务 — 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;

View File

@@ -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">{{ $lang('components-diy.diy-store.switchStore') }}</text> <text class="change margin-left">切换</text>
<text class="iconfont icon-right"></text> <text class="iconfont icon-right"></text>
</text> </text>
</block> </block>
<text class="title" v-else>{{ $lang('components-diy.diy-store.locating') }}</text> <text class="title" v-else>定位中...</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>{{ $lang('components-diy.diy-store.gettingLocation') }}</text> <text v-else>获取当前位置...</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">{{ $lang('components-diy.diy-store.switchStore') }}</text> <text class="change margin-left">切换</text>
<text class="iconfont icon-right"></text> <text class="iconfont icon-right"></text>
</text> </text>
</block> </block>
<text class="title" v-else>{{ $lang('components-diy.diy-store.locating') }}</text> <text class="title" v-else>定位中...</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>{{ $lang('components-diy.diy-store.locating') }}</text> <text class="title" v-else>定位中...</text>
</view> </view>
<view class="store-right-search"> <view class="store-right-search">
<input type="text" class="uni-input font-size-tag" disabled :placeholder="$lang('components-diy.diy-store.searchPlaceholder')" <input type="text" class="uni-input font-size-tag" disabled placeholder="商品搜索"
@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>

View File

@@ -903,8 +903,8 @@ export default {
// 如果 title 是字符串,保持原有逻辑 // 如果 title 是字符串,保持原有逻辑
if (typeof title === 'string' && title.includes('.')) { if (typeof title === 'string' && title.includes('.')) {
// 包含点号的标题视为国际化键,使用全局挂载的 $lang 方法翻译;缺失时回退 title 本身 // 包含点号的标题视为国际化键,使用全局挂载的 $lang 方法翻译
return this.$lang ? this.$lang(title, title) : title; return this.$lang ? this.$lang(title) : title;
} }
// 不包含点号的标题直接返回 // 不包含点号的标题直接返回

View File

@@ -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 }">{{ $lang('components-diy.diy-text.zone') }}</text> :style="{ fontSize: value.fontSize * 2 + 'rpx', fontWeight: value.fontWeight }">专区</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>

View File

@@ -54,23 +54,17 @@
<!-- 视频播放弹窗 --> <!-- 视频播放弹窗 -->
<uni-popup ref="videoPopup" type="center" style="background:transparent;width:100%;height:100%;"> <uni-popup ref="videoPopup" type="center" style="background:transparent;width:100%;height:100%;">
<view class="video-container" :style="popupVideoStyle"> <view class="video-container" :style="popupVideoStyle">
<video <video
:key="video_url"
ref="popupVideoRef" ref="popupVideoRef"
class="adaptive-video" class="adaptive-video"
:autoPauseIfNavigate="true" :autoPauseIfNavigate="true"
:autoPauseIfOpenNative="true" :autoPauseIfOpenNative="true"
:autoplay="false" :autoplay="false"
:enableAutoRotation="true" :enableAutoRotation="true"
id="myVideo" id="myVideo"
:src="video_url" :src="video_url"
:controls="true" :controls="true"
object-fit="contain"
playsinline
webkit-playsinline
x5-playsinline
@loadedmetadata="onPopupVideoLoaded" @loadedmetadata="onPopupVideoLoaded"
@error="onPopupVideoError"
></video> ></video>
</view> </view>
</uni-popup> </uni-popup>
@@ -94,14 +88,11 @@ 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) {
@@ -148,23 +139,34 @@ export default {
// 弹窗视频容器样式 // 弹窗视频容器样式
popupVideoStyle() { popupVideoStyle() {
// 容器横向铺满,黑色背景填满左右边界 let style = 'position:fixed;width:100%;left:0;';
// 视频用 object-fit:contain 保持原比例居中,左右黑边由容器黑色背景填充
let style = 'position:fixed;width:100%;height:50vh;left:50%;top:50%;transform:translate(-50%,-50%);border-radius:0;'; if (this.popupVideoRatio) {
// 根据视频比例设置位置
if (this.popupVideoRatio === 'portrait') {
// 竖屏视频:居中显示,使用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;';
}
return style; return style;
} }
}, },
methods: { methods: {
// 显示视频播放弹窗 // 显示视频播放弹窗
showVideo(item) { showVideo(item) {
let url = item.videoUrl || ''; this.video_url = item.videoUrl;
// 处理视频URL:完整链接直接使用,否则通过 $util.img() 转换 // 重置视频比例为null,等待新的检测结果
if (url && url.indexOf('http://') !== 0 && url.indexOf('https://') !== 0) { this.popupVideoRatio = null;
url = this.$util.img(url);
}
this.video_url = url;
this.popupVideoWidth = 0;
this.popupVideoHeight = 0;
this.$refs.videoPopup.open(); this.$refs.videoPopup.open();
}, },
@@ -172,16 +174,6 @@ export default {
imgError(index) { imgError(index) {
// 图片加载失败的处理逻辑 // 图片加载失败的处理逻辑
}, },
// 初始化窗口宽度
initWindowWidth() {
try {
const systemInfo = uni.getSystemInfoSync();
this.windowWidth = systemInfo.windowWidth || 375;
} catch (e) {
this.windowWidth = 375;
}
},
// 弹窗视频加载完成事件 // 弹窗视频加载完成事件
onPopupVideoLoaded(event) { onPopupVideoLoaded(event) {
@@ -206,24 +198,13 @@ 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.popupVideoWidth = width; this.popupVideoRatio = width >= height ? 'landscape' : 'portrait';
this.popupVideoHeight = height; } else {
// 获取失败,默认竖屏
this.popupVideoRatio = 'portrait';
} }
}); });
},
// 弹窗视频错误事件
onPopupVideoError(event) {
console.error('Popup video load failed:', event);
} }
} }
} }
@@ -595,9 +576,8 @@ 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 {

View File

@@ -11,9 +11,6 @@
:style="videoWarpCss" :style="videoWarpCss"
controls controls
preload="metadata" preload="metadata"
playsinline
webkit-playsinline
x5-playsinline
@loadedmetadata="onVideoLoaded" @loadedmetadata="onVideoLoaded"
@click="handlerClick(videoUrl)" @click="handlerClick(videoUrl)"
></video> ></video>
@@ -29,23 +26,6 @@
: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>
@@ -64,17 +44,14 @@ export default {
} }
}, },
data() { data() {
return { return {
videoWidth: 0, videoRatio: null, // 视频比例:'landscape'(横屏)或 'portrait'(竖屏)
videoHeight: 0, videoUrl: '',
videoUrl: '', posterUrl: ''
posterUrl: '', };
windowWidth: 0 },
};
},
created() { created() {
this.initVideoData(); this.initVideoData();
this.initWindowWidth();
}, },
mixins: [DiyMinx], mixins: [DiyMinx],
watch: { watch: {
@@ -101,26 +78,18 @@ export default {
// 动态计算容器比例 // 动态计算容器比例
containerStyle() { containerStyle() {
let style = ''; let style = '';
const defaultRatio = 9 / 16;
let ratio = defaultRatio; if (this.videoRatio === 'landscape') {
if (this.videoWidth && this.videoHeight) { // 横屏视频:16/9比例
ratio = this.videoHeight / this.videoWidth; style += 'aspect-ratio: 16 / 9;';
} else if (this.videoRatio === 'portrait') {
// 竖屏视频:9/16比例
style += 'aspect-ratio: 9 / 16;';
} else {
// 未加载完成 → 默认使用竖屏比例
style += 'aspect-ratio: 9 / 16;';
} }
// #ifdef H5
style += 'height:0;padding-top: ' + (ratio * 100) + '%;';
// #endif
// #ifdef MP-WEIXIN
style += 'height:0;padding-top: ' + (ratio * 100) + '%;';
// #endif
// #ifdef MP-HARMONY
style += 'width: 100%;';
style += 'height: ' + (this.windowWidth * ratio) + 'px;';
// #endif
return style; return style;
} }
}, },
@@ -135,16 +104,6 @@ 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 '';
@@ -179,13 +138,12 @@ export default {
const height = video.videoHeight; const height = video.videoHeight;
if (width && height) { if (width && height) {
this.videoWidth = width; this.videoRatio = width >= height ? 'landscape' : 'portrait';
this.videoHeight = height;
} }
}); });
video.addEventListener('error', (e) => { video.addEventListener('error', (e) => {
console.error(this.$lang('components-diy.diy-video.h5PreloadFailed') + ':', e); console.error('H5端预加载视频失败:', e);
}); });
// 触发加载 // 触发加载
@@ -211,16 +169,8 @@ 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.videoWidth = width; this.videoRatio = width >= height ? 'landscape' : 'portrait';
this.videoHeight = height;
} }
}, },
@@ -234,7 +184,7 @@ export default {
// 视频错误事件 // 视频错误事件
onVideoError(event) { onVideoError(event) {
console.error(this.$lang('components-diy.diy-video.videoLoadFailed') + ':', event); console.error('视频加载失败:', event);
}, },
async handlerClick(videoUrl) { async handlerClick(videoUrl) {
@@ -266,11 +216,6 @@ 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 */
@@ -280,19 +225,6 @@ 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>

View File

@@ -1,5 +1,3 @@
import lang from '@/common/js/lang.js';
// 微信视频号组件配置 // 微信视频号组件配置
export const wechatChannelConfig = { export const wechatChannelConfig = {
// 图标相关 // 图标相关
@@ -58,10 +56,10 @@ export const wechatChannelConfig = {
// 错误提示配置 // 错误提示配置
error: { error: {
notWechat: 'wechatChannel.notWechat', notWechat: '当前环境不是微信小程序',
lowVersion: 'wechatChannel.lowVersion', lowVersion: '当前微信基础库版本过低,需要 2.19.2 或以上版本',
notSupported: 'wechatChannel.notSupported', notSupported: '当前环境不支持微信视频号',
missingFields: 'wechatChannel.missingFields', missingFields: '缺少必要字段: {field}',
}, },
}; };
@@ -110,7 +108,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(lang.lang(wechatChannelConfig.error.missingFields, { field })); throw new Error(`缺少必要字段: ${field}`);
} }
} }
return true; return true;
@@ -130,7 +128,7 @@ export const wechatChannelUtil = {
// 检查微信环境 // 检查微信环境
if (typeof wx === 'undefined') { if (typeof wx === 'undefined') {
const err = new Error(lang.lang(wechatChannelConfig.error.notWechat)); const err = new Error(wechatChannelConfig.error.notWechat);
this.handleError(err, item); this.handleError(err, item);
reject(err); reject(err);
return; return;
@@ -140,7 +138,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(lang.lang(wechatChannelConfig.error.lowVersion)); const err = new Error(wechatChannelConfig.error.lowVersion);
this.handleError(err, item); this.handleError(err, item);
reject(err); reject(err);
return; return;
@@ -160,7 +158,7 @@ export const wechatChannelUtil = {
} }
}); });
} else { } else {
const err = new Error(lang.lang(wechatChannelConfig.error.notSupported)); const err = new Error(wechatChannelConfig.error.notSupported);
this.handleError(err, item); this.handleError(err, item);
reject(err); reject(err);
} }
@@ -170,7 +168,7 @@ export const wechatChannelUtil = {
// 统一错误处理 // 统一错误处理
handleError(err, item) { handleError(err, item) {
console.error('微信视频号错误:', err); console.error('微信视频号错误:', err);
const { message = '', errMsg = lang.lang('wechatChannel.playFailed'), errCode = -1 } = err; const { message = '', errMsg = '微信视频播放失败!', errCode = -1 } = err;
// 错误码5: 表示用户点击了取消. openChannelsActivity:fail cancel // 错误码5: 表示用户点击了取消. openChannelsActivity:fail cancel
if ([5].includes(errCode)) { if ([5].includes(errCode)) {

View File

@@ -1,4 +0,0 @@
{
"navigationBarTitleText": "",
"usingComponents": {}
}

View File

@@ -1,21 +0,0 @@
<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>

View File

@@ -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">{{ $lang('components.chat-message.customerOffline') }}</view> <view class="no-connect">客服不在线</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">{{ $lang('components.chat-message.customerOnline') }}</view> <view class="no-connect">客服在线</view>
</view> </view>
<uni-popup ref="imgPopup" type="center"> <uni-popup ref="imgPopup" type="center">
<view class="imagePop"> <view class="imagePop">

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