mirror of
https://github.com/keven1024/015.git
synced 2026-06-07 12:54:34 +00:00
Compare commits
133 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f1e956ad4c | ||
|
|
7793bef944 | ||
|
|
1fdd05f0ea | ||
|
|
7128a8c329 | ||
|
|
3cb878b770 | ||
|
|
05c3504627 | ||
|
|
9b1ba13ec3 | ||
|
|
2a4fac717a | ||
|
|
e897fe1ed3 | ||
|
|
0aae4c2d36 | ||
|
|
549bdd9f68 | ||
|
|
f956130b4f | ||
|
|
218b4cc6ac | ||
|
|
64a936835c | ||
|
|
b8e4bee050 | ||
|
|
7e90c54b27 | ||
|
|
ac8b6f642b | ||
|
|
af6ca85ff5 | ||
|
|
02900ab1f9 | ||
|
|
bdf7894e9b | ||
|
|
a8f504f377 | ||
|
|
cf92a50c82 | ||
|
|
848a0ff71b | ||
|
|
2f3acc76cd | ||
|
|
c89d1b554f | ||
|
|
71737ebedc | ||
|
|
b735200418 | ||
|
|
6084acb0d5 | ||
|
|
a601964459 | ||
|
|
8758325da3 | ||
|
|
18ca80bb1b | ||
|
|
958ca799da | ||
|
|
9a9418c564 | ||
|
|
0cb30b6293 | ||
|
|
8828924a1f | ||
|
|
3275b8f68f | ||
|
|
95ef5d261b | ||
|
|
52d041b4c2 | ||
|
|
2ff06946e1 | ||
|
|
4c6a18c063 | ||
|
|
bbf6ea561d | ||
|
|
1449664ca5 | ||
|
|
4a3ec790b7 | ||
|
|
f4a28e369f | ||
|
|
833079d495 | ||
|
|
a63d55b61d | ||
|
|
46c6cd84b5 | ||
|
|
84e747a909 | ||
|
|
a24bf24271 | ||
|
|
1226a7948e | ||
|
|
1e446a0240 | ||
|
|
b023876e0f | ||
|
|
ec1d70637b | ||
|
|
6934bba7a1 | ||
|
|
2e5da4f7e9 | ||
|
|
d8704a8aa8 | ||
|
|
2273c589f6 | ||
|
|
a14628718c | ||
|
|
528df24988 | ||
|
|
2a42ca8cde | ||
|
|
6edb1fe222 | ||
|
|
c841d8e1a2 | ||
|
|
e8b5f98260 | ||
|
|
706464ce3c | ||
|
|
b52d4c3a51 | ||
|
|
e9fc260cbc | ||
|
|
e37402ff63 | ||
|
|
35654372a6 | ||
|
|
018d13ea78 | ||
|
|
0e0f6bb1c5 | ||
|
|
7ba7af6100 | ||
|
|
55eb50faab | ||
|
|
87d337c2a1 | ||
|
|
2fc2f4ccf7 | ||
|
|
10a82a1751 | ||
|
|
a5a01a667e | ||
|
|
907f77aa66 | ||
|
|
ae2fbcc216 | ||
|
|
f1dc65b1d0 | ||
|
|
881d8e111a | ||
|
|
58ba3f6d50 | ||
|
|
788ef8df57 | ||
|
|
d0021f9468 | ||
|
|
a99790c9b1 | ||
|
|
249b9f2350 | ||
|
|
6a7e8f85ac | ||
|
|
3f5f8b3c97 | ||
|
|
f8b5b82179 | ||
|
|
0d4d89d4ec | ||
|
|
2af28b6a50 | ||
|
|
a1808a64cc | ||
|
|
499b931c04 | ||
|
|
1298bf79d3 | ||
|
|
83f6be0486 | ||
|
|
17fa39b830 | ||
|
|
55949d1f76 | ||
|
|
d3e7760aea | ||
|
|
7566ddb5f2 | ||
|
|
78624b302d | ||
|
|
759318813c | ||
|
|
a91345f39c | ||
|
|
123b1ec4fb | ||
|
|
79887d6c6c | ||
|
|
f1f10de051 | ||
|
|
80d60cc0a0 | ||
|
|
30d0abc2b5 | ||
|
|
8d3675cfa1 | ||
|
|
cb6b0fae6a | ||
|
|
6631e1e1a2 | ||
|
|
625399bdd9 | ||
|
|
10b79615b7 | ||
|
|
7c38773451 | ||
|
|
976011697c | ||
|
|
c25b41e20e | ||
|
|
3c031dcee9 | ||
|
|
d6c54de659 | ||
|
|
72ca69330f | ||
|
|
7f74441f5d | ||
|
|
28abd8d1a2 | ||
|
|
c50bb5d0bf | ||
|
|
95ab8b97da | ||
|
|
d6880dbf00 | ||
|
|
c871c55f79 | ||
|
|
82e9292b66 | ||
|
|
1d86f2bdf6 | ||
|
|
52cc89a73d | ||
|
|
af9a5b45d2 | ||
|
|
b26821a504 | ||
|
|
560387d8f1 | ||
|
|
b69af056aa | ||
|
|
707ade5dd2 | ||
|
|
b4570c5961 | ||
|
|
60a588c92a |
152
.claude/commands/opsx/apply.md
Normal file
152
.claude/commands/opsx/apply.md
Normal file
@@ -0,0 +1,152 @@
|
|||||||
|
---
|
||||||
|
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")
|
||||||
|
- 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
|
||||||
|
|
||||||
|
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
|
||||||
157
.claude/commands/opsx/archive.md
Normal file
157
.claude/commands/opsx/archive.md
Normal file
@@ -0,0 +1,157 @@
|
|||||||
|
---
|
||||||
|
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
|
||||||
|
- `artifacts`: List of artifacts with their status (`done` or other)
|
||||||
|
|
||||||
|
**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**
|
||||||
|
|
||||||
|
Check for delta specs at `openspec/changes/<name>/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 the archive directory if it doesn't exist:
|
||||||
|
```bash
|
||||||
|
mkdir -p openspec/changes/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 the change directory to archive
|
||||||
|
|
||||||
|
```bash
|
||||||
|
mv openspec/changes/<name> openspec/changes/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:** openspec/changes/archive/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:** openspec/changes/archive/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:** openspec/changes/archive/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:** openspec/changes/archive/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
|
||||||
173
.claude/commands/opsx/explore.md
Normal file
173
.claude/commands/opsx/explore.md
Normal file
@@ -0,0 +1,173 @@
|
|||||||
|
---
|
||||||
|
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. **Read existing artifacts for context**
|
||||||
|
- `openspec/changes/<name>/proposal.md`
|
||||||
|
- `openspec/changes/<name>/design.md`
|
||||||
|
- `openspec/changes/<name>/tasks.md`
|
||||||
|
- etc.
|
||||||
|
|
||||||
|
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
|
||||||
106
.claude/commands/opsx/propose.md
Normal file
106
.claude/commands/opsx/propose.md
Normal file
@@ -0,0 +1,106 @@
|
|||||||
|
---
|
||||||
|
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 at `openspec/changes/<name>/` 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
|
||||||
|
|
||||||
|
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
|
||||||
|
- `outputPath`: Where 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
|
||||||
|
- 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
|
||||||
156
.claude/skills/openspec-apply-change/SKILL.md
Normal file
156
.claude/skills/openspec-apply-change/SKILL.md
Normal file
@@ -0,0 +1,156 @@
|
|||||||
|
---
|
||||||
|
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.3.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")
|
||||||
|
- 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
|
||||||
|
|
||||||
|
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
|
||||||
114
.claude/skills/openspec-archive-change/SKILL.md
Normal file
114
.claude/skills/openspec-archive-change/SKILL.md
Normal file
@@ -0,0 +1,114 @@
|
|||||||
|
---
|
||||||
|
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.3.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
|
||||||
|
- `artifacts`: List of artifacts with their status (`done` or other)
|
||||||
|
|
||||||
|
**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**
|
||||||
|
|
||||||
|
Check for delta specs at `openspec/changes/<name>/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 the archive directory if it doesn't exist:
|
||||||
|
```bash
|
||||||
|
mkdir -p openspec/changes/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 the change directory to archive
|
||||||
|
|
||||||
|
```bash
|
||||||
|
mv openspec/changes/<name> openspec/changes/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:** openspec/changes/archive/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
|
||||||
288
.claude/skills/openspec-explore/SKILL.md
Normal file
288
.claude/skills/openspec-explore/SKILL.md
Normal file
@@ -0,0 +1,288 @@
|
|||||||
|
---
|
||||||
|
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.3.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. **Read existing artifacts for context**
|
||||||
|
- `openspec/changes/<name>/proposal.md`
|
||||||
|
- `openspec/changes/<name>/design.md`
|
||||||
|
- `openspec/changes/<name>/tasks.md`
|
||||||
|
- etc.
|
||||||
|
|
||||||
|
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
|
||||||
110
.claude/skills/openspec-propose/SKILL.md
Normal file
110
.claude/skills/openspec-propose/SKILL.md
Normal file
@@ -0,0 +1,110 @@
|
|||||||
|
---
|
||||||
|
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.3.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 at `openspec/changes/<name>/` 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
|
||||||
|
|
||||||
|
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
|
||||||
|
- `outputPath`: Where 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
|
||||||
|
- 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
|
||||||
156
.codex/skills/openspec-apply-change/SKILL.md
Normal file
156
.codex/skills/openspec-apply-change/SKILL.md
Normal file
@@ -0,0 +1,156 @@
|
|||||||
|
---
|
||||||
|
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.3.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")
|
||||||
|
- 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
|
||||||
|
|
||||||
|
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
|
||||||
114
.codex/skills/openspec-archive-change/SKILL.md
Normal file
114
.codex/skills/openspec-archive-change/SKILL.md
Normal file
@@ -0,0 +1,114 @@
|
|||||||
|
---
|
||||||
|
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.3.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
|
||||||
|
- `artifacts`: List of artifacts with their status (`done` or other)
|
||||||
|
|
||||||
|
**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**
|
||||||
|
|
||||||
|
Check for delta specs at `openspec/changes/<name>/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 the archive directory if it doesn't exist:
|
||||||
|
```bash
|
||||||
|
mkdir -p openspec/changes/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 the change directory to archive
|
||||||
|
|
||||||
|
```bash
|
||||||
|
mv openspec/changes/<name> openspec/changes/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:** openspec/changes/archive/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
|
||||||
288
.codex/skills/openspec-explore/SKILL.md
Normal file
288
.codex/skills/openspec-explore/SKILL.md
Normal file
@@ -0,0 +1,288 @@
|
|||||||
|
---
|
||||||
|
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.3.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. **Read existing artifacts for context**
|
||||||
|
- `openspec/changes/<name>/proposal.md`
|
||||||
|
- `openspec/changes/<name>/design.md`
|
||||||
|
- `openspec/changes/<name>/tasks.md`
|
||||||
|
- etc.
|
||||||
|
|
||||||
|
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
|
||||||
110
.codex/skills/openspec-propose/SKILL.md
Normal file
110
.codex/skills/openspec-propose/SKILL.md
Normal file
@@ -0,0 +1,110 @@
|
|||||||
|
---
|
||||||
|
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.3.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 at `openspec/changes/<name>/` 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
|
||||||
|
|
||||||
|
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
|
||||||
|
- `outputPath`: Where 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
|
||||||
|
- 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
|
||||||
@@ -13,6 +13,7 @@ jobs:
|
|||||||
node-version: '24'
|
node-version: '24'
|
||||||
- uses: pnpm/action-setup@v4
|
- uses: pnpm/action-setup@v4
|
||||||
with:
|
with:
|
||||||
|
version: latest
|
||||||
cache: true
|
cache: true
|
||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
run: |
|
run: |
|
||||||
|
|||||||
@@ -21,8 +21,9 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
images: fudaoyuanicu/015-app
|
images: fudaoyuanicu/015-app
|
||||||
tags: |
|
tags: |
|
||||||
type=pep440,pattern={{version}}
|
type=semver,pattern={{version}}
|
||||||
type=raw,value=latest,enable=${{ github.ref == format('refs/heads/{0}', 'main') }}
|
type=raw,value=edge,enable=${{ contains(github.ref_name, '-') }}
|
||||||
|
type=raw,value=latest,enable=${{ !contains(github.ref_name, '-') }}
|
||||||
- name: Set build time
|
- name: Set build time
|
||||||
id: build-time
|
id: build-time
|
||||||
run: |
|
run: |
|
||||||
@@ -56,8 +57,9 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
images: fudaoyuanicu/015-worker
|
images: fudaoyuanicu/015-worker
|
||||||
tags: |
|
tags: |
|
||||||
type=pep440,pattern={{version}}
|
type=semver,pattern={{version}}
|
||||||
type=raw,value=latest,enable=${{ github.ref == format('refs/heads/{0}', 'main') }}
|
type=raw,value=edge,enable=${{ contains(github.ref_name, '-') }}
|
||||||
|
type=raw,value=latest,enable=${{ !contains(github.ref_name, '-') }}
|
||||||
- name: Set build time
|
- name: Set build time
|
||||||
id: build-time
|
id: build-time
|
||||||
run: |
|
run: |
|
||||||
@@ -76,6 +78,7 @@ jobs:
|
|||||||
deploy:
|
deploy:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
needs: [build-app, build-worker]
|
needs: [build-app, build-worker]
|
||||||
|
if: ${{ !contains(github.ref_name, '-') }}
|
||||||
steps:
|
steps:
|
||||||
- name: Send deployment webhook
|
- name: Send deployment webhook
|
||||||
run: |
|
run: |
|
||||||
|
|||||||
BIN
.github/image/0.png
vendored
BIN
.github/image/0.png
vendored
Binary file not shown.
|
Before Width: | Height: | Size: 716 KiB After Width: | Height: | Size: 804 KiB |
5
.gitignore
vendored
5
.gitignore
vendored
@@ -22,7 +22,7 @@ logs
|
|||||||
.env
|
.env
|
||||||
.env.*
|
.env.*
|
||||||
!.env.example
|
!.env.example
|
||||||
config.yaml
|
/config.yaml
|
||||||
|
|
||||||
# Serwist
|
# Serwist
|
||||||
/front/public/sw*
|
/front/public/sw*
|
||||||
@@ -31,3 +31,6 @@ config.yaml
|
|||||||
# backend
|
# backend
|
||||||
**/uploads/**
|
**/uploads/**
|
||||||
**/tmp/**
|
**/tmp/**
|
||||||
|
|
||||||
|
# worker
|
||||||
|
pkg/mail/out/
|
||||||
|
|||||||
16
.vscode/launch.json
vendored
Normal file
16
.vscode/launch.json
vendored
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
{
|
||||||
|
// 使用 IntelliSense 了解相关属性。
|
||||||
|
// 悬停以查看现有属性的描述。
|
||||||
|
// 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387
|
||||||
|
"version": "0.2.0",
|
||||||
|
"configurations": [
|
||||||
|
{
|
||||||
|
"name": "Launch Backend",
|
||||||
|
"type": "go",
|
||||||
|
"request": "launch",
|
||||||
|
"mode": "auto",
|
||||||
|
"program": "${workspaceFolder}/backend",
|
||||||
|
"cwd": "${workspaceFolder}"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
23
Dockerfile
23
Dockerfile
@@ -1,25 +1,23 @@
|
|||||||
FROM node:22-alpine AS front-base
|
FROM node:22-alpine AS front-base
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
# Install dependencies only when needed
|
# Install dependencies only when needed
|
||||||
FROM front-base AS front-deps
|
|
||||||
RUN apk add --no-cache gcompat
|
|
||||||
WORKDIR /app
|
|
||||||
COPY . .
|
|
||||||
RUN corepack enable pnpm && pnpm i && pnpm --filter=015-front deploy dist --legacy
|
|
||||||
|
|
||||||
|
|
||||||
FROM front-base AS front-builder
|
FROM front-base AS front-builder
|
||||||
WORKDIR /app
|
RUN apk add --no-cache gcompat
|
||||||
COPY --from=front-deps /app/dist/ .
|
ENV CI=true
|
||||||
RUN corepack enable pnpm && pnpm build
|
ENV NODE_OPTIONS="--max-old-space-size=4096"
|
||||||
|
COPY . .
|
||||||
|
RUN corepack enable pnpm && pnpm i && pnpm --filter=015-front build && pnpm --dir pkg/mail export
|
||||||
|
|
||||||
FROM golang:1.25.5 AS backend-builder
|
FROM golang:1.26.3 AS backend-builder
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
# Workspace and module manifests for cache
|
# Workspace and module manifests for cache
|
||||||
COPY go.work go.work.sum ./
|
COPY go.work go.work.sum ./
|
||||||
COPY backend/ ./backend/
|
COPY backend/ ./backend/
|
||||||
COPY worker/ ./worker/
|
COPY worker/ ./worker/
|
||||||
COPY pkg/ ./pkg/
|
COPY pkg/ ./pkg/
|
||||||
|
# Inject built email templates so Go can embed them
|
||||||
|
COPY --from=front-builder /app/pkg/mail/out/ ./pkg/mail/out/
|
||||||
RUN go env -w GO111MODULE=on && go env -w GOPROXY=https://goproxy.cn,direct && \
|
RUN go env -w GO111MODULE=on && go env -w GOPROXY=https://goproxy.cn,direct && \
|
||||||
go mod download
|
go mod download
|
||||||
# Build from workspace root so pkg/utils, pkg/models, pkg/services resolve
|
# Build from workspace root so pkg/utils, pkg/models, pkg/services resolve
|
||||||
@@ -29,7 +27,6 @@ RUN CGO_ENABLED=0 GOOS=linux go build -o backend-bin ./backend
|
|||||||
FROM front-base AS runner
|
FROM front-base AS runner
|
||||||
ARG VERSION
|
ARG VERSION
|
||||||
ARG BUILD_TIME
|
ARG BUILD_TIME
|
||||||
WORKDIR /app
|
|
||||||
RUN apk add --no-cache curl openssl
|
RUN apk add --no-cache curl openssl
|
||||||
ENV NODE_ENV production
|
ENV NODE_ENV production
|
||||||
|
|
||||||
@@ -37,7 +34,7 @@ RUN addgroup --system --gid 1001 nodejs
|
|||||||
RUN adduser --system --uid 1001 nuxtjs
|
RUN adduser --system --uid 1001 nuxtjs
|
||||||
|
|
||||||
# Only `.output` folder is needed from the build stage
|
# Only `.output` folder is needed from the build stage
|
||||||
COPY --from=front-builder --chown=nuxtjs:nodejs /app/.output/ ./
|
COPY --from=front-builder --chown=nuxtjs:nodejs /app/front/.output/ ./
|
||||||
COPY --from=backend-builder /app/backend-bin /bin/backend
|
COPY --from=backend-builder /app/backend-bin /bin/backend
|
||||||
COPY 015.sh /app/015.sh
|
COPY 015.sh /app/015.sh
|
||||||
|
|
||||||
|
|||||||
46
README-zh.md
46
README-zh.md
@@ -42,15 +42,15 @@
|
|||||||
## 📸 截图预览
|
## 📸 截图预览
|
||||||
|
|
||||||
| 选择文件上传页面 | 输入文本上传页面 |
|
| 选择文件上传页面 | 输入文本上传页面 |
|
||||||
|---------------------------------------|-----------------------------------------------|
|
| ------------------------- | ------------------------- |
|
||||||
|  |  |
|
|  |  |
|
||||||
|
|
||||||
| 多选文件上传 | 文件上传进度热力图 |
|
| 多选文件上传 | 文件上传进度热力图 |
|
||||||
|------------------------------------------------|---------------------------------------------------|
|
| ------------------------- | ------------------------- |
|
||||||
|  |  |
|
|  |  |
|
||||||
|
|
||||||
| 文件上传进度条 | 文件上传成功页面 |
|
| 文件上传进度条 | 文件上传成功页面 |
|
||||||
|------------------------------------------------|-------------------------------------------------|
|
| ------------------------- | ------------------------- |
|
||||||
|  |  |
|
|  |  |
|
||||||
|
|
||||||
## 🚀 快速开始
|
## 🚀 快速开始
|
||||||
@@ -63,29 +63,13 @@
|
|||||||
|
|
||||||
2. 把 config.example.yaml 配置完成后改为 config.yaml
|
2. 把 config.example.yaml 配置完成后改为 config.yaml
|
||||||
|
|
||||||
|
|
||||||
3. 启动
|
|
||||||
```bash
|
|
||||||
docker compose up -d
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
||||||
## 🚀 快速开始
|
|
||||||
|
|
||||||
### Docker
|
|
||||||
|
|
||||||
1. 下载文件
|
|
||||||
- config.example.yaml
|
|
||||||
- docker-compose.yml
|
|
||||||
|
|
||||||
2. 把config.example.yaml配置完成后改为config.yaml
|
|
||||||
|
|
||||||
|
|
||||||
3. 启动
|
3. 启动
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
docker compose up -d
|
docker compose up -d
|
||||||
```
|
```
|
||||||
|
|
||||||
|
4. 访问 `http://localhost:8080`
|
||||||
|
|
||||||
## 🏗️ 技术架构
|
## 🏗️ 技术架构
|
||||||
|
|
||||||
@@ -130,15 +114,15 @@ docker compose up -d
|
|||||||
015/
|
015/
|
||||||
├── front/ # 前端应用 (Vue 3 + Nuxt 3)
|
├── front/ # 前端应用 (Vue 3 + Nuxt 3)
|
||||||
│ ├── components/ # Vue 组件
|
│ ├── components/ # Vue 组件
|
||||||
│ │ ├── pages/ # 页面路由
|
│ ├── pages/ # 页面路由
|
||||||
│ │ ├── composables/ # 组合式函数
|
│ ├── composables/ # 组合式函数
|
||||||
│ │ ├── i18n/ # 国际化文件
|
│ ├── i18n/ # 国际化文件
|
||||||
│ │ └── assets/ # 静态资源
|
│ ├── assets/ # 静态资源
|
||||||
│ └── middleware/ # 中间件
|
│ ├── plugins/ # Nuxt 插件
|
||||||
|
│ └── server/ # 服务端路由
|
||||||
├── backend/ # 后端服务 (Go + Echo)
|
├── backend/ # 后端服务 (Go + Echo)
|
||||||
│ ├── internal/ # 内部包
|
│ ├── internal/ # 内部包
|
||||||
│ │ ├── controllers/ # 控制器
|
│ │ ├── controllers/ # 控制器
|
||||||
│ │ ├── models/ # 数据模型
|
|
||||||
│ │ ├── services/ # 业务逻辑
|
│ │ ├── services/ # 业务逻辑
|
||||||
│ │ └── utils/ # 工具函数
|
│ │ └── utils/ # 工具函数
|
||||||
│ └── middleware/ # 中间件
|
│ └── middleware/ # 中间件
|
||||||
@@ -147,7 +131,7 @@ docker compose up -d
|
|||||||
│ │ ├── tasks/ # 任务处理器
|
│ │ ├── tasks/ # 任务处理器
|
||||||
│ │ └── utils/ # 工具函数
|
│ │ └── utils/ # 工具函数
|
||||||
│ └── middleware/ # 中间件
|
│ └── middleware/ # 中间件
|
||||||
└── tmp/ # 临时文件
|
└── pkg/ # 公共包
|
||||||
```
|
```
|
||||||
|
|
||||||
## 🔧 开发指南
|
## 🔧 开发指南
|
||||||
@@ -186,19 +170,19 @@ cd worker && go build -o worker .
|
|||||||
- 前端计算哈希和秒传
|
- 前端计算哈希和秒传
|
||||||
- 并发切片上传 (使用 Web Worker)
|
- 并发切片上传 (使用 Web Worker)
|
||||||
- 文件上传/文本上传和分享
|
- 文件上传/文本上传和分享
|
||||||
|
- 支持多文件上传
|
||||||
- 上传统计页面
|
- 上传统计页面
|
||||||
- 多语言支持
|
- 多语言支持
|
||||||
- 最大上传限制
|
- 最大上传限制
|
||||||
- 后端队列系统和 Worker 处理文件
|
- 后端队列系统和 Worker 处理文件
|
||||||
|
- 断点续传 (后端计算已上传部分并返回)
|
||||||
|
- 图片格式转换和压缩
|
||||||
|
|
||||||
### 计划功能 🚧
|
### 计划功能 🚧
|
||||||
|
|
||||||
- 断点续传 (后端计算已上传部分并返回)
|
|
||||||
- 图片格式转换和压缩
|
|
||||||
- 图片 OCR 复制
|
- 图片 OCR 复制
|
||||||
- 文档转 Markdown
|
- 文档转 Markdown
|
||||||
- 文本翻译/总结
|
- 文本翻译/总结
|
||||||
- 支持上传多文件
|
|
||||||
|
|
||||||
## 🤝 贡献指南
|
## 🤝 贡献指南
|
||||||
|
|
||||||
|
|||||||
58
README.md
58
README.md
@@ -42,17 +42,34 @@ English | [中文](README-zh.md)
|
|||||||
## 📸 Screenshots
|
## 📸 Screenshots
|
||||||
|
|
||||||
| File Selection Upload Page | Text Input Upload Page |
|
| File Selection Upload Page | Text Input Upload Page |
|
||||||
|---------------------------------------|-----------------------------------------------|
|
| -------------------------- | ------------------------- |
|
||||||
|  |  |
|
|  |  |
|
||||||
|
|
||||||
| Multiple File Upload | Upload Progress Heatmap |
|
| Multiple File Upload | Upload Progress Heatmap |
|
||||||
|------------------------------------------------|---------------------------------------------------|
|
| -------------------------- | ------------------------- |
|
||||||
|  |  |
|
|  |  |
|
||||||
|
|
||||||
| Upload Progress Bar | Upload Success Page |
|
| Upload Progress Bar | Upload Success Page |
|
||||||
|------------------------------------------------|-------------------------------------------------|
|
| -------------------------- | ------------------------- |
|
||||||
|  |  |
|
|  |  |
|
||||||
|
|
||||||
|
## 🚀 Quick Start
|
||||||
|
|
||||||
|
### Docker
|
||||||
|
|
||||||
|
1. Download files
|
||||||
|
- config.example.yaml
|
||||||
|
- docker-compose.yml
|
||||||
|
|
||||||
|
2. Rename config.example.yaml to config.yaml after configuration
|
||||||
|
|
||||||
|
3. Start
|
||||||
|
```bash
|
||||||
|
docker compose up -d
|
||||||
|
```
|
||||||
|
|
||||||
|
4. Visit `http://localhost:8080`
|
||||||
|
|
||||||
## 🏗️ Technical Architecture
|
## 🏗️ Technical Architecture
|
||||||
|
|
||||||
### Frontend Tech Stack
|
### Frontend Tech Stack
|
||||||
@@ -90,36 +107,21 @@ English | [中文](README-zh.md)
|
|||||||
- **Redis Cache** - Share information and file metadata caching
|
- **Redis Cache** - Share information and file metadata caching
|
||||||
- **Queue System** - Asynchronous task processing queue
|
- **Queue System** - Asynchronous task processing queue
|
||||||
|
|
||||||
## 🚀 Quick Start
|
|
||||||
|
|
||||||
### Docker
|
|
||||||
|
|
||||||
1. Download files
|
|
||||||
- config.example.yaml
|
|
||||||
- docker-compose.yml
|
|
||||||
|
|
||||||
2. Rename config.example.yaml to config.yaml after configuration
|
|
||||||
|
|
||||||
3. Start
|
|
||||||
```bash
|
|
||||||
docker compose up -d
|
|
||||||
```
|
|
||||||
|
|
||||||
## 📁 Project Structure
|
## 📁 Project Structure
|
||||||
|
|
||||||
```
|
```
|
||||||
015/
|
015/
|
||||||
├── front/ # Frontend application (Vue 3 + Nuxt 3)
|
├── front/ # Frontend application (Vue 3 + Nuxt 3)
|
||||||
│ ├── components/ # Vue components
|
│ ├── components/ # Vue components
|
||||||
│ │ ├── pages/ # Page routes
|
│ ├── pages/ # Page routes
|
||||||
│ │ ├── composables/ # Composable functions
|
│ ├── composables/ # Composable functions
|
||||||
│ │ ├── i18n/ # Internationalization files
|
│ ├── i18n/ # Internationalization files
|
||||||
│ │ └── assets/ # Static assets
|
│ ├── assets/ # Static assets
|
||||||
│ └── middleware/ # Middleware
|
│ ├── plugins/ # Nuxt plugins
|
||||||
|
│ └── server/ # Server-side routes
|
||||||
├── backend/ # Backend service (Go + Echo)
|
├── backend/ # Backend service (Go + Echo)
|
||||||
│ ├── internal/ # Internal packages
|
│ ├── internal/ # Internal packages
|
||||||
│ │ ├── controllers/ # Controllers
|
│ │ ├── controllers/ # Controllers
|
||||||
│ │ ├── models/ # Data models
|
|
||||||
│ │ ├── services/ # Business logic
|
│ │ ├── services/ # Business logic
|
||||||
│ │ └── utils/ # Utility functions
|
│ │ └── utils/ # Utility functions
|
||||||
│ └── middleware/ # Middleware
|
│ └── middleware/ # Middleware
|
||||||
@@ -128,7 +130,7 @@ docker compose up -d
|
|||||||
│ │ ├── tasks/ # Task processors
|
│ │ ├── tasks/ # Task processors
|
||||||
│ │ └── utils/ # Utility functions
|
│ │ └── utils/ # Utility functions
|
||||||
│ └── middleware/ # Middleware
|
│ └── middleware/ # Middleware
|
||||||
└── tmp/ # Temporary files
|
└── pkg/ # Shared packages
|
||||||
```
|
```
|
||||||
|
|
||||||
## 🔧 Development Guide
|
## 🔧 Development Guide
|
||||||
@@ -167,19 +169,19 @@ cd worker && go build -o worker .
|
|||||||
- Frontend hash calculation and instant transfer
|
- Frontend hash calculation and instant transfer
|
||||||
- Concurrent chunked upload (using Web Worker)
|
- Concurrent chunked upload (using Web Worker)
|
||||||
- File upload/text upload and sharing
|
- File upload/text upload and sharing
|
||||||
|
- Multiple file upload support
|
||||||
- Upload statistics page
|
- Upload statistics page
|
||||||
- Multi-language support
|
- Multi-language support
|
||||||
- Maximum upload limits
|
- Maximum upload limits
|
||||||
- Backend queue system and Worker file processing
|
- Backend queue system and Worker file processing
|
||||||
|
- Resume upload (backend calculates uploaded parts and returns)
|
||||||
|
- Image format conversion and compression
|
||||||
|
|
||||||
### Planned Features 🚧
|
### Planned Features 🚧
|
||||||
|
|
||||||
- Resume upload (backend calculates uploaded parts and returns)
|
|
||||||
- Image format conversion and compression
|
|
||||||
- Image OCR copy
|
- Image OCR copy
|
||||||
- Document to Markdown conversion
|
- Document to Markdown conversion
|
||||||
- Text translation/summarization
|
- Text translation/summarization
|
||||||
- Support for multiple file uploads
|
|
||||||
|
|
||||||
## 🤝 Contributing
|
## 🤝 Contributing
|
||||||
|
|
||||||
|
|||||||
55
backend/.air.toml
Normal file
55
backend/.air.toml
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
#:schema https://json.schemastore.org/any.json
|
||||||
|
|
||||||
|
root = "."
|
||||||
|
testdata_dir = "testdata"
|
||||||
|
tmp_dir = "tmp"
|
||||||
|
|
||||||
|
[build]
|
||||||
|
args_bin = []
|
||||||
|
bin = "./tmp/main"
|
||||||
|
cmd = "go build -o ./tmp/main ."
|
||||||
|
delay = 1000
|
||||||
|
entrypoint = ["./tmp/main"]
|
||||||
|
exclude_dir = ["assets", "tmp", "vendor", "testdata"]
|
||||||
|
exclude_file = []
|
||||||
|
exclude_regex = ["_test.go"]
|
||||||
|
exclude_unchanged = false
|
||||||
|
follow_symlink = false
|
||||||
|
full_bin = ""
|
||||||
|
include_dir = ["../pkg"]
|
||||||
|
include_ext = ["go", "tpl", "tmpl", "html"]
|
||||||
|
include_file = []
|
||||||
|
kill_delay = "0s"
|
||||||
|
log = "build-errors.log"
|
||||||
|
poll = false
|
||||||
|
poll_interval = 0
|
||||||
|
post_cmd = []
|
||||||
|
pre_cmd = []
|
||||||
|
rerun = false
|
||||||
|
rerun_delay = 500
|
||||||
|
send_interrupt = false
|
||||||
|
stop_on_error = false
|
||||||
|
|
||||||
|
[color]
|
||||||
|
app = ""
|
||||||
|
build = "yellow"
|
||||||
|
main = "magenta"
|
||||||
|
runner = "green"
|
||||||
|
watcher = "cyan"
|
||||||
|
|
||||||
|
[log]
|
||||||
|
main_only = false
|
||||||
|
silent = false
|
||||||
|
time = false
|
||||||
|
|
||||||
|
[misc]
|
||||||
|
clean_on_exit = false
|
||||||
|
|
||||||
|
[proxy]
|
||||||
|
app_port = 0
|
||||||
|
enabled = false
|
||||||
|
proxy_port = 0
|
||||||
|
|
||||||
|
[screen]
|
||||||
|
clear_on_rebuild = false
|
||||||
|
keep_scroll = true
|
||||||
@@ -5,15 +5,14 @@ go 1.25.5
|
|||||||
require (
|
require (
|
||||||
github.com/golang-jwt/jwt/v5 v5.3.1
|
github.com/golang-jwt/jwt/v5 v5.3.1
|
||||||
github.com/gorilla/sessions v1.4.0
|
github.com/gorilla/sessions v1.4.0
|
||||||
github.com/hibiken/asynq v0.25.1
|
github.com/hibiken/asynq v0.26.0
|
||||||
github.com/labstack/echo-contrib v0.50.0
|
|
||||||
github.com/labstack/echo/v5 v5.0.1
|
github.com/labstack/echo/v5 v5.0.1
|
||||||
github.com/matoous/go-nanoid/v2 v2.1.0
|
github.com/matoous/go-nanoid/v2 v2.1.0
|
||||||
github.com/samber/lo v1.52.0
|
github.com/samber/lo v1.53.0
|
||||||
github.com/spf13/cast v1.10.0
|
github.com/spf13/cast v1.10.0
|
||||||
github.com/stretchr/testify v1.11.1
|
github.com/stretchr/testify v1.11.1
|
||||||
go.uber.org/zap v1.27.1
|
go.uber.org/zap v1.27.1
|
||||||
golang.org/x/crypto v0.47.0
|
golang.org/x/crypto v0.49.0
|
||||||
)
|
)
|
||||||
|
|
||||||
require (
|
require (
|
||||||
@@ -21,15 +20,16 @@ require (
|
|||||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
|
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
|
||||||
github.com/google/uuid v1.6.0 // indirect
|
github.com/google/uuid v1.6.0 // indirect
|
||||||
github.com/gorilla/context v1.1.2 // indirect
|
|
||||||
github.com/gorilla/securecookie v1.1.2 // indirect
|
github.com/gorilla/securecookie v1.1.2 // indirect
|
||||||
github.com/pmezard/go-difflib v1.0.0 // indirect
|
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||||
github.com/redis/go-redis/v9 v9.17.3 // indirect
|
github.com/redis/go-redis/v9 v9.18.0 // indirect
|
||||||
github.com/robfig/cron/v3 v3.0.1 // indirect
|
github.com/robfig/cron/v3 v3.0.1 // indirect
|
||||||
|
go.uber.org/atomic v1.11.0 // indirect
|
||||||
go.uber.org/multierr v1.11.0 // indirect
|
go.uber.org/multierr v1.11.0 // indirect
|
||||||
golang.org/x/sys v0.40.0 // indirect
|
golang.org/x/net v0.52.0 // indirect
|
||||||
golang.org/x/text v0.33.0 // indirect
|
golang.org/x/sys v0.42.0 // indirect
|
||||||
golang.org/x/time v0.14.0 // indirect
|
golang.org/x/text v0.35.0 // indirect
|
||||||
|
golang.org/x/time v0.15.0 // indirect
|
||||||
google.golang.org/protobuf v1.36.11 // indirect
|
google.golang.org/protobuf v1.36.11 // indirect
|
||||||
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 // indirect
|
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 // indirect
|
||||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||||
|
|||||||
@@ -18,54 +18,56 @@ github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0=
|
|||||||
github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||||
github.com/gorilla/context v1.1.2 h1:WRkNAv2uoa03QNIc1A6u4O7DAGMUVoopZhkiXWA2V1o=
|
|
||||||
github.com/gorilla/context v1.1.2/go.mod h1:KDPwT9i/MeWHiLl90fuTgrt4/wPcv75vFAZLaOOcbxM=
|
|
||||||
github.com/gorilla/securecookie v1.1.2 h1:YCIWL56dvtr73r6715mJs5ZvhtnY73hBvEF8kXD8ePA=
|
github.com/gorilla/securecookie v1.1.2 h1:YCIWL56dvtr73r6715mJs5ZvhtnY73hBvEF8kXD8ePA=
|
||||||
github.com/gorilla/securecookie v1.1.2/go.mod h1:NfCASbcHqRSY+3a8tlWJwsQap2VX5pwzwo4h3eOamfo=
|
github.com/gorilla/securecookie v1.1.2/go.mod h1:NfCASbcHqRSY+3a8tlWJwsQap2VX5pwzwo4h3eOamfo=
|
||||||
github.com/gorilla/sessions v1.4.0 h1:kpIYOp/oi6MG/p5PgxApU8srsSw9tuFbt46Lt7auzqQ=
|
github.com/gorilla/sessions v1.4.0 h1:kpIYOp/oi6MG/p5PgxApU8srsSw9tuFbt46Lt7auzqQ=
|
||||||
github.com/gorilla/sessions v1.4.0/go.mod h1:FLWm50oby91+hl7p/wRxDth9bWSuk0qVL2emc7lT5ik=
|
github.com/gorilla/sessions v1.4.0/go.mod h1:FLWm50oby91+hl7p/wRxDth9bWSuk0qVL2emc7lT5ik=
|
||||||
github.com/hibiken/asynq v0.25.1 h1:phj028N0nm15n8O2ims+IvJ2gz4k2auvermngh9JhTw=
|
github.com/hibiken/asynq v0.26.0 h1:1Zxr92MlDnb1Zt/QR5g2vSCqUS03i95lUfqx5X7/wrw=
|
||||||
github.com/hibiken/asynq v0.25.1/go.mod h1:pazWNOLBu0FEynQRBvHA26qdIKRSmfdIfUm4HdsLmXg=
|
github.com/hibiken/asynq v0.26.0/go.mod h1:Qk4e57bTnWDoyJ67VkchuV6VzSM9IQW2nPvAGuDyw58=
|
||||||
|
github.com/klauspost/cpuid/v2 v2.0.9 h1:lgaqFMSdTdQYdZ04uHyN2d/eKdOMyi2YLSvlQIBFYa4=
|
||||||
|
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
|
||||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||||
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
||||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||||
github.com/labstack/echo-contrib v0.50.0 h1:MLTQdqME3BEBczV2thYz9yPT5sBhzkoUEpwAOY9llds=
|
|
||||||
github.com/labstack/echo-contrib v0.50.0/go.mod h1:oftqJL4enNg9ao1VLpVZmisVE5/8uwHtIYE4zTpqyWU=
|
|
||||||
github.com/labstack/echo/v5 v5.0.1 h1:60L7x1KMWRIJuaFqvnEHH322g+YnsMWq5Rzaeo6lcP4=
|
github.com/labstack/echo/v5 v5.0.1 h1:60L7x1KMWRIJuaFqvnEHH322g+YnsMWq5Rzaeo6lcP4=
|
||||||
github.com/labstack/echo/v5 v5.0.1/go.mod h1:SyvlSdObGjRXeQfCCXW/sybkZdOOQZBmpKF0bvALaeo=
|
github.com/labstack/echo/v5 v5.0.1/go.mod h1:SyvlSdObGjRXeQfCCXW/sybkZdOOQZBmpKF0bvALaeo=
|
||||||
github.com/matoous/go-nanoid/v2 v2.1.0 h1:P64+dmq21hhWdtvZfEAofnvJULaRR1Yib0+PnU669bE=
|
github.com/matoous/go-nanoid/v2 v2.1.0 h1:P64+dmq21hhWdtvZfEAofnvJULaRR1Yib0+PnU669bE=
|
||||||
github.com/matoous/go-nanoid/v2 v2.1.0/go.mod h1:KlbGNQ+FhrUNIHUxZdL63t7tl4LaPkZNpUULS8H4uVM=
|
github.com/matoous/go-nanoid/v2 v2.1.0/go.mod h1:KlbGNQ+FhrUNIHUxZdL63t7tl4LaPkZNpUULS8H4uVM=
|
||||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
github.com/redis/go-redis/v9 v9.17.3 h1:fN29NdNrE17KttK5Ndf20buqfDZwGNgoUr9qjl1DQx4=
|
github.com/redis/go-redis/v9 v9.18.0 h1:pMkxYPkEbMPwRdenAzUNyFNrDgHx9U+DrBabWNfSRQs=
|
||||||
github.com/redis/go-redis/v9 v9.17.3/go.mod h1:u410H11HMLoB+TP67dz8rL9s6QW2j76l0//kSOd3370=
|
github.com/redis/go-redis/v9 v9.18.0/go.mod h1:k3ufPphLU5YXwNTUcCRXGxUoF1fqxnhFQmscfkCoDA0=
|
||||||
github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=
|
github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=
|
||||||
github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro=
|
github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro=
|
||||||
github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
|
github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
|
||||||
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
|
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
|
||||||
github.com/samber/lo v1.52.0 h1:Rvi+3BFHES3A8meP33VPAxiBZX/Aws5RxrschYGjomw=
|
github.com/samber/lo v1.53.0 h1:t975lj2py4kJPQ6haz1QMgtId2gtmfktACxIXArw3HM=
|
||||||
github.com/samber/lo v1.52.0/go.mod h1:4+MXEGsJzbKGaUEQFKBq2xtfuznW9oz/WrgyzMzRoM0=
|
github.com/samber/lo v1.53.0/go.mod h1:4+MXEGsJzbKGaUEQFKBq2xtfuznW9oz/WrgyzMzRoM0=
|
||||||
github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY=
|
github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY=
|
||||||
github.com/spf13/cast v1.10.0/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo=
|
github.com/spf13/cast v1.10.0/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo=
|
||||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||||
|
github.com/zeebo/xxh3 v1.0.2 h1:xZmwmqxHZA8AI603jOQ0tMqmBr9lPeFwGg6d+xy9DC0=
|
||||||
|
github.com/zeebo/xxh3 v1.0.2/go.mod h1:5NWz9Sef7zIDm2JHfFlcQvNekmcEl9ekUZQQKCYaDcA=
|
||||||
|
go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
|
||||||
|
go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=
|
||||||
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
||||||
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
||||||
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
|
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
|
||||||
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
|
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
|
||||||
go.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=
|
go.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=
|
||||||
go.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
|
go.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
|
||||||
golang.org/x/crypto v0.47.0 h1:V6e3FRj+n4dbpw86FJ8Fv7XVOql7TEwpHapKoMJ/GO8=
|
golang.org/x/crypto v0.49.0 h1:+Ng2ULVvLHnJ/ZFEq4KdcDd/cfjrrjjNSXNzxg0Y4U4=
|
||||||
golang.org/x/crypto v0.47.0/go.mod h1:ff3Y9VzzKbwSSEzWqJsJVBnWmRwRSHt/6Op5n9bQc4A=
|
golang.org/x/crypto v0.49.0/go.mod h1:ErX4dUh2UM+CFYiXZRTcMpEcN8b/1gxEuv3nODoYtCA=
|
||||||
golang.org/x/net v0.49.0 h1:eeHFmOGUTtaaPSGNmjBKpbng9MulQsJURQUAfUwY++o=
|
golang.org/x/net v0.52.0 h1:He/TN1l0e4mmR3QqHMT2Xab3Aj3L9qjbhRm78/6jrW0=
|
||||||
golang.org/x/net v0.49.0/go.mod h1:/ysNB2EvaqvesRkuLAyjI1ycPZlQHM3q01F02UY/MV8=
|
golang.org/x/net v0.52.0/go.mod h1:R1MAz7uMZxVMualyPXb+VaqGSa3LIaUqk0eEt3w36Sw=
|
||||||
golang.org/x/sys v0.40.0 h1:DBZZqJ2Rkml6QMQsZywtnjnnGvHza6BTfYFWY9kjEWQ=
|
golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
|
||||||
golang.org/x/sys v0.40.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||||
golang.org/x/text v0.33.0 h1:B3njUFyqtHDUI5jMn1YIr5B0IE2U0qck04r6d4KPAxE=
|
golang.org/x/text v0.35.0 h1:JOVx6vVDFokkpaq1AEptVzLTpDe9KGpj5tR4/X+ybL8=
|
||||||
golang.org/x/text v0.33.0/go.mod h1:LuMebE6+rBincTi9+xWTY8TztLzKHc/9C1uBCG27+q8=
|
golang.org/x/text v0.35.0/go.mod h1:khi/HExzZJ2pGnjenulevKNX1W67CUy0AsXcNubPGCA=
|
||||||
golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI=
|
golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
|
||||||
golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4=
|
golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
|
||||||
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
||||||
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ func GetAbout(c *echo.Context) error {
|
|||||||
|
|
||||||
return utils.HTTPSuccessHandler(c, map[string]any{
|
return utils.HTTPSuccessHandler(c, map[string]any{
|
||||||
"bg_url": u.GetEnv("about.bg_url"),
|
"bg_url": u.GetEnv("about.bg_url"),
|
||||||
"content": u.GetEnvMapString("about.content"),
|
"content": u.GetEnvMap("about.content"),
|
||||||
"email": u.GetEnv("about.email"),
|
"email": u.GetEnv("about.email"),
|
||||||
"name": u.GetEnv("about.name"),
|
"name": u.GetEnv("about.name"),
|
||||||
"url": u.GetEnv("about.url"),
|
"url": u.GetEnv("about.url"),
|
||||||
|
|||||||
@@ -6,17 +6,49 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/labstack/echo/v5"
|
"github.com/labstack/echo/v5"
|
||||||
|
"github.com/samber/lo"
|
||||||
"github.com/spf13/cast"
|
"github.com/spf13/cast"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var defaultEnabledFeatures = []string{
|
||||||
|
"file-share",
|
||||||
|
"text-share",
|
||||||
|
}
|
||||||
|
|
||||||
|
func getEnabledKeys(config map[string]any) []string {
|
||||||
|
return lo.FilterMap(lo.Entries(config), func(e lo.Entry[string, any], _ int) (string, bool) {
|
||||||
|
node, ok := e.Value.(map[string]any)
|
||||||
|
return e.Key, ok && cast.ToBool(node["enabled"])
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
func GetConfig(c *echo.Context) error {
|
func GetConfig(c *echo.Context) error {
|
||||||
|
featureConfig := u.GetEnvMap("features")
|
||||||
|
defaultFeatureConfig := lo.SliceToMap(defaultEnabledFeatures, func(item string) (string, any) {
|
||||||
|
return item, map[string]any{
|
||||||
|
"enabled": true,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
featureConfig = lo.Assign(defaultFeatureConfig, featureConfig)
|
||||||
|
features := getEnabledKeys(featureConfig)
|
||||||
|
// textTranslateProviderConfig := u.GetEnvMap("features.text-translate.provider")
|
||||||
|
// textTranslateProviders := getEnabledKeys(textTranslateProviderConfig)
|
||||||
|
|
||||||
return utils.HTTPSuccessHandler(c, map[string]any{
|
return utils.HTTPSuccessHandler(c, map[string]any{
|
||||||
"site_title": u.GetEnvMapString("site.title"),
|
"site_title": u.GetEnvMap("site.title"),
|
||||||
"site_desc": u.GetEnvMapString("site.desc"),
|
"site_desc": u.GetEnvMap("site.desc"),
|
||||||
"site_url": u.GetEnv("site.url"),
|
"site_url": u.GetEnv("site.url"),
|
||||||
"site_icon": u.GetEnvWithDefault("site.icon", "/logo.png"),
|
"site_icon": u.GetEnvWithDefault("site.icon", "/logo.png"),
|
||||||
"site_bg_url": u.GetEnvWithDefault("site.bg_url", "https://img.fudaoyuan.icu/api/1/random/?scale_min=1.5&webp=true&md=false&format=302"),
|
"site_bg_url": u.GetEnvWithDefault("site.bg_url", "https://img.fudaoyuan.icu/api/1/random/?scale_min=1.5&webp=true&md=false&format=302"),
|
||||||
|
"site_enable_bg": cast.ToBool(u.GetEnvWithDefault("site.enable_bg", "true")),
|
||||||
"version": u.GetEnvWithDefault("VERSION", "dev"),
|
"version": u.GetEnvWithDefault("VERSION", "dev"),
|
||||||
"build_time": cast.ToInt(u.GetEnvWithDefault("BUILD_TIME", cast.ToString(time.Now().Unix()))),
|
"build_time": cast.ToInt(u.GetEnvWithDefault("BUILD_TIME", cast.ToString(time.Now().Unix()))),
|
||||||
|
"features": features,
|
||||||
|
"config": map[string]any{
|
||||||
|
// "text-translate": map[string]any{
|
||||||
|
// "provider": textTranslateProviders,
|
||||||
|
// },
|
||||||
|
},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,13 +2,17 @@ package controllers
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"backend/internal/utils"
|
"backend/internal/utils"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"pkg/models"
|
"pkg/models"
|
||||||
u "pkg/utils"
|
u "pkg/utils"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/golang-jwt/jwt/v5"
|
"github.com/golang-jwt/jwt/v5"
|
||||||
|
"github.com/hibiken/asynq"
|
||||||
"github.com/labstack/echo/v5"
|
"github.com/labstack/echo/v5"
|
||||||
|
"github.com/samber/lo"
|
||||||
"github.com/spf13/cast"
|
"github.com/spf13/cast"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -26,14 +30,13 @@ func DownloadShare(c *echo.Context) error {
|
|||||||
t, err := jwt.ParseWithClaims(token, &claims, func(token *jwt.Token) (interface{}, error) {
|
t, err := jwt.ParseWithClaims(token, &claims, func(token *jwt.Token) (interface{}, error) {
|
||||||
return []byte(u.GetEnv("share.download_secret")), nil
|
return []byte(u.GetEnv("share.download_secret")), nil
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil || !t.Valid {
|
||||||
return utils.HTTPErrorHandler(c, err)
|
return utils.HTTPErrorHandler(c, lo.Ternary(err != nil, err, ErrInvalidRequest))
|
||||||
}
|
}
|
||||||
if !t.Valid {
|
shareInfo, err := models.GetRedisShareInfo(claims.ShareId)
|
||||||
return utils.HTTPErrorHandler(c, ErrInvalidRequest)
|
if err != nil || shareInfo == nil {
|
||||||
|
return utils.HTTPErrorHandler(c, lo.Ternary(err != nil, err, ErrShareNotFound))
|
||||||
}
|
}
|
||||||
shareInfo, _ := models.GetRedisShareInfo(claims.ShareId)
|
|
||||||
|
|
||||||
if shareInfo.Type == models.ShareTypeFile {
|
if shareInfo.Type == models.ShareTypeFile {
|
||||||
fileInfo, _ := models.GetRedisFileInfo(shareInfo.Data)
|
fileInfo, _ := models.GetRedisFileInfo(shareInfo.Data)
|
||||||
uploadPath, err := u.GetUploadDirPath()
|
uploadPath, err := u.GetUploadDirPath()
|
||||||
@@ -81,7 +84,11 @@ func VaildateShare(c *echo.Context) error {
|
|||||||
return utils.HTTPErrorHandler(c, ErrInvalidSharePassword)
|
return utils.HTTPErrorHandler(c, ErrInvalidSharePassword)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// 如果下载次数为0,则设置为-1 防止空值问题
|
return u.WithLocker(context.Background(), "015:shareInfoMap:"+r.ShareId, 0, func(ctx context.Context) error {
|
||||||
|
shareInfo, err := models.GetRedisShareInfo(r.ShareId)
|
||||||
|
if err != nil || shareInfo == nil {
|
||||||
|
return utils.HTTPErrorHandler(c, lo.Ternary(err != nil, err, ErrShareNotFound))
|
||||||
|
}
|
||||||
if shareInfo.ViewNum < 1 {
|
if shareInfo.ViewNum < 1 {
|
||||||
return utils.HTTPErrorHandler(c, ErrInsufficientDownloadQuota)
|
return utils.HTTPErrorHandler(c, ErrInsufficientDownloadQuota)
|
||||||
}
|
}
|
||||||
@@ -111,13 +118,9 @@ func VaildateShare(c *echo.Context) error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
// download_nums 必须放在创建token的时候减掉,不然多线程下载会导致多次减掉
|
// download_nums 必须放在创建token的时候减掉,不然多线程下载会导致多次减掉
|
||||||
latestViewNum := shareInfo.ViewNum - 1
|
_, err = models.SetRedisShareInfo(r.ShareId, func(shareInfo *models.RedisShareInfo) *models.RedisShareInfo {
|
||||||
// 如果下载次数为0,则设置为-1 防止空值问题
|
shareInfo.ViewNum -= 1
|
||||||
if latestViewNum < 1 {
|
return shareInfo
|
||||||
latestViewNum = -1
|
|
||||||
}
|
|
||||||
err = models.SetRedisShareInfo(r.ShareId, models.RedisShareInfo{
|
|
||||||
ViewNum: latestViewNum,
|
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return utils.HTTPErrorHandler(c, err)
|
return utils.HTTPErrorHandler(c, err)
|
||||||
@@ -125,21 +128,24 @@ func VaildateShare(c *echo.Context) error {
|
|||||||
|
|
||||||
// 统计分享数
|
// 统计分享数
|
||||||
currentDate := time.Now().Format("2006-01-02")
|
currentDate := time.Now().Format("2006-01-02")
|
||||||
statData, _ := models.GetRedisStat(currentDate)
|
_, err = models.SetRedisStat(currentDate, func(stat *models.StatData) *models.StatData {
|
||||||
if statData == nil {
|
stat.DownloadNum += 1
|
||||||
statData = &models.StatData{
|
return stat
|
||||||
FileSize: 0,
|
})
|
||||||
FileNum: 0,
|
|
||||||
ShareNum: 0,
|
|
||||||
DownloadNum: 0,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
statData.DownloadNum += 1
|
|
||||||
err = models.SetRedisStat(currentDate, *statData)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return utils.HTTPErrorHandler(c, err)
|
return utils.HTTPErrorHandler(c, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if len(shareInfo.NotifyEmails) > 0 || len(shareInfo.NotifyWebhooks) > 0 {
|
||||||
|
payload, err := json.Marshal(map[string]string{
|
||||||
|
"share_id": r.ShareId,
|
||||||
|
"ip": c.RealIP(),
|
||||||
|
})
|
||||||
|
if err == nil {
|
||||||
|
_, _ = u.GetQueueClient().Enqueue(asynq.NewTask("share:notify", payload))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if shareInfo.Type == models.ShareTypeFile {
|
if shareInfo.Type == models.ShareTypeFile {
|
||||||
return utils.HTTPSuccessHandler(c, map[string]any{
|
return utils.HTTPSuccessHandler(c, map[string]any{
|
||||||
"token": downloadToken,
|
"token": downloadToken,
|
||||||
@@ -148,4 +154,5 @@ func VaildateShare(c *echo.Context) error {
|
|||||||
return utils.HTTPSuccessHandler(c, map[string]any{
|
return utils.HTTPSuccessHandler(c, map[string]any{
|
||||||
"token": downloadToken,
|
"token": downloadToken,
|
||||||
})
|
})
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ var (
|
|||||||
ErrInvalidFileSliceIndex = errors.New("InvalidFileSliceIndex") // 文件切片索引错误
|
ErrInvalidFileSliceIndex = errors.New("InvalidFileSliceIndex") // 文件切片索引错误
|
||||||
ErrInvalidFileSliceSize = errors.New("InvalidFileSliceSize") // 文件切片大小错误
|
ErrInvalidFileSliceSize = errors.New("InvalidFileSliceSize") // 文件切片大小错误
|
||||||
ErrIncompleteFileSlices = errors.New("IncompleteFileSlices") // 文件切片不完整
|
ErrIncompleteFileSlices = errors.New("IncompleteFileSlices") // 文件切片不完整
|
||||||
ErrFileMD5Mismatch = errors.New("FileMD5Mismatch") // 文件MD5不一致
|
ErrFileHashMismatch = errors.New("FileHashMismatch") // 文件Hash不一致
|
||||||
|
|
||||||
// 分享相关
|
// 分享相关
|
||||||
ErrShareFileNotFound = errors.New("ShareFileNotFound") // 分享文件不存在
|
ErrShareFileNotFound = errors.New("ShareFileNotFound") // 分享文件不存在
|
||||||
|
|||||||
@@ -13,7 +13,6 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/labstack/echo/v5"
|
"github.com/labstack/echo/v5"
|
||||||
"github.com/spf13/cast"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func CreateUploadTask(c *echo.Context) error {
|
func CreateUploadTask(c *echo.Context) error {
|
||||||
@@ -78,36 +77,33 @@ func CreateUploadTask(c *echo.Context) error {
|
|||||||
for r.FileSize/ChunkSize > 1000 {
|
for r.FileSize/ChunkSize > 1000 {
|
||||||
ChunkSize *= 2
|
ChunkSize *= 2
|
||||||
}
|
}
|
||||||
uploadTaskExpire := cast.ToInt64(u.GetEnvWithDefault("upload.remove_expire", "2")) * 3600
|
redisFileInfo, err := models.SetRedisFileInfo(fileId, func(fileInfo *models.RedisFileInfo) *models.RedisFileInfo {
|
||||||
newFileInfo := models.RedisFileInfo{
|
fileInfo.FileType = models.FileTypeInit
|
||||||
FileType: models.FileTypeInit,
|
fileInfo.FileInfo = models.FileInfo{
|
||||||
FileInfo: models.FileInfo{
|
|
||||||
FileSize: r.FileSize,
|
FileSize: r.FileSize,
|
||||||
MimeType: r.MimeType,
|
MimeType: r.MimeType,
|
||||||
FileHash: r.FileHash,
|
FileHash: r.FileHash,
|
||||||
ChunkSize: ChunkSize,
|
ChunkSize: ChunkSize,
|
||||||
},
|
|
||||||
CreatedAt: time.Now().Unix(),
|
|
||||||
Expire: uploadTaskExpire,
|
|
||||||
}
|
}
|
||||||
err = models.SetRedisFileInfo(fileId, newFileInfo)
|
return fileInfo
|
||||||
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return utils.HTTPErrorHandler(c, err)
|
return utils.HTTPErrorHandler(c, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
err = s.SetFileRemoveTask(fileId, time.Duration(uploadTaskExpire)*time.Second)
|
err = s.SetFileRemoveTask(fileId, time.Duration(redisFileInfo.Expire)*time.Second)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return utils.HTTPErrorHandler(c, err)
|
return utils.HTTPErrorHandler(c, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
return utils.HTTPSuccessHandler(c, map[string]any{
|
return utils.HTTPSuccessHandler(c, map[string]any{
|
||||||
"size": newFileInfo.FileSize,
|
"size": redisFileInfo.FileSize,
|
||||||
"mime_type": newFileInfo.MimeType,
|
"mime_type": redisFileInfo.MimeType,
|
||||||
"hash": newFileInfo.FileHash,
|
"hash": redisFileInfo.FileHash,
|
||||||
"type": newFileInfo.FileType,
|
"type": redisFileInfo.FileType,
|
||||||
"expire": newFileInfo.Expire,
|
"expire": redisFileInfo.Expire,
|
||||||
"id": fileId,
|
"id": fileId,
|
||||||
"chunk_size": newFileInfo.ChunkSize,
|
"chunk_size": redisFileInfo.ChunkSize,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -216,43 +212,37 @@ func FinishUploadTask(c *echo.Context) error {
|
|||||||
return utils.HTTPErrorHandler(c, err)
|
return utils.HTTPErrorHandler(c, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 计算文件MD5
|
// 计算文件SHA1
|
||||||
file, err := os.Open(mergeFilePath)
|
file, err := os.Open(mergeFilePath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return utils.HTTPErrorHandler(c, err)
|
return utils.HTTPErrorHandler(c, err)
|
||||||
}
|
}
|
||||||
defer file.Close() //nolint:errcheck
|
defer file.Close() //nolint:errcheck
|
||||||
|
|
||||||
file_hash, err := u.GetFileMd5(file)
|
file_hash, err := u.GetFileSHA1(file)
|
||||||
if err != nil || file_hash != fileInfo.FileHash {
|
if err != nil || file_hash != fileInfo.FileHash {
|
||||||
defer os.Remove(mergeFilePath) //nolint:errcheck
|
defer os.Remove(mergeFilePath) //nolint:errcheck
|
||||||
if err == nil {
|
if err == nil {
|
||||||
return utils.HTTPErrorHandler(c, ErrFileMD5Mismatch)
|
return utils.HTTPErrorHandler(c, ErrFileHashMismatch)
|
||||||
}
|
}
|
||||||
return utils.HTTPErrorHandler(c, err)
|
return utils.HTTPErrorHandler(c, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 更新文件信息
|
// 更新文件信息
|
||||||
err = models.SetRedisFileInfo(r.FileId, models.RedisFileInfo{
|
fileInfo, err = models.SetRedisFileInfo(r.FileId, func(fileInfo *models.RedisFileInfo) *models.RedisFileInfo {
|
||||||
FileType: models.FileTypeUpload,
|
fileInfo.FileType = models.FileTypeUpload
|
||||||
|
return fileInfo
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return utils.HTTPErrorHandler(c, err)
|
return utils.HTTPErrorHandler(c, err)
|
||||||
}
|
}
|
||||||
// 统计
|
// 统计
|
||||||
currentDate := time.Now().Format("2006-01-02")
|
currentDate := time.Now().Format("2006-01-02")
|
||||||
statData, _ := models.GetRedisStat(currentDate)
|
_, err = models.SetRedisStat(currentDate, func(stat *models.StatData) *models.StatData {
|
||||||
if statData == nil {
|
stat.FileSize += fileInfo.FileSize
|
||||||
statData = &models.StatData{
|
stat.FileNum += 1
|
||||||
FileSize: 0,
|
return stat
|
||||||
FileNum: 0,
|
})
|
||||||
ShareNum: 0,
|
|
||||||
DownloadNum: 0,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
statData.FileSize += fileInfo.FileSize
|
|
||||||
statData.FileNum += 1
|
|
||||||
err = models.SetRedisStat(currentDate, *statData)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return utils.HTTPErrorHandler(c, err)
|
return utils.HTTPErrorHandler(c, err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -28,7 +28,10 @@ type ShareConfig struct {
|
|||||||
HasPassword bool `json:"has_password"`
|
HasPassword bool `json:"has_password"`
|
||||||
Password string `json:"password"`
|
Password string `json:"password"`
|
||||||
HasNotify bool `json:"has_notify"`
|
HasNotify bool `json:"has_notify"`
|
||||||
NotifyEmail []string `json:"notify_email"`
|
NotifyTypes []string `json:"notify_types"`
|
||||||
|
NotifyEmails []string `json:"notify_emails"`
|
||||||
|
NotifyWebhooks []models.NotifyWebhook `json:"notify_webhooks"`
|
||||||
|
Locale string `json:"locale"`
|
||||||
HasPickupCode bool `json:"has_pickup_code"`
|
HasPickupCode bool `json:"has_pickup_code"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -73,16 +76,41 @@ func CreateShareInfo(c *echo.Context) error {
|
|||||||
password = hash
|
password = hash
|
||||||
}
|
}
|
||||||
|
|
||||||
err = models.SetRedisShareInfo(id, models.RedisShareInfo{
|
var notifyEmails []string
|
||||||
Data: r.Data,
|
var notifyWebhooks []models.NotifyWebhook
|
||||||
Type: r.Type,
|
if r.Config.HasNotify {
|
||||||
CreatedAt: time.Now().Unix(),
|
hasEmail, hasWebhook := false, false
|
||||||
Owner: owner,
|
for _, nt := range r.Config.NotifyTypes {
|
||||||
ViewNum: r.Config.ViewNum,
|
switch nt {
|
||||||
Password: password,
|
case "email":
|
||||||
// NotifyEmail: r.Config.NotifyEmail,
|
hasEmail = true
|
||||||
FileName: r.FileName,
|
case "webhook":
|
||||||
ExpireAt: ExpireTime.Unix(),
|
hasWebhook = true
|
||||||
|
default:
|
||||||
|
return utils.HTTPErrorHandler(c, ErrInvalidRequest)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if hasEmail {
|
||||||
|
notifyEmails = r.Config.NotifyEmails
|
||||||
|
}
|
||||||
|
if hasWebhook {
|
||||||
|
notifyWebhooks = r.Config.NotifyWebhooks
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = models.SetRedisShareInfo(id, func(shareInfo *models.RedisShareInfo) *models.RedisShareInfo {
|
||||||
|
shareInfo.Data = r.Data
|
||||||
|
shareInfo.Type = r.Type
|
||||||
|
shareInfo.CreatedAt = time.Now().Unix()
|
||||||
|
shareInfo.Owner = owner
|
||||||
|
shareInfo.ViewNum = r.Config.ViewNum
|
||||||
|
shareInfo.Password = password
|
||||||
|
shareInfo.FileName = r.FileName
|
||||||
|
shareInfo.NotifyEmails = notifyEmails
|
||||||
|
shareInfo.NotifyWebhooks = notifyWebhooks
|
||||||
|
shareInfo.Locale = r.Config.Locale
|
||||||
|
shareInfo.ExpireAt = ExpireTime.Unix()
|
||||||
|
return shareInfo
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return utils.HTTPErrorHandler(c, err)
|
return utils.HTTPErrorHandler(c, err)
|
||||||
@@ -128,17 +156,10 @@ func CreateShareInfo(c *echo.Context) error {
|
|||||||
|
|
||||||
// 统计分享数
|
// 统计分享数
|
||||||
currentDate := time.Now().Format("2006-01-02")
|
currentDate := time.Now().Format("2006-01-02")
|
||||||
statData, _ := models.GetRedisStat(currentDate)
|
_, err = models.SetRedisStat(currentDate, func(stat *models.StatData) *models.StatData {
|
||||||
if statData == nil {
|
stat.ShareNum += 1
|
||||||
statData = &models.StatData{
|
return stat
|
||||||
FileSize: 0,
|
})
|
||||||
FileNum: 0,
|
|
||||||
ShareNum: 0,
|
|
||||||
DownloadNum: 0,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
statData.ShareNum += 1
|
|
||||||
err = models.SetRedisStat(currentDate, *statData)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return utils.HTTPErrorHandler(c, err)
|
return utils.HTTPErrorHandler(c, err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import (
|
|||||||
var handleTaskMap = map[string]func(c *echo.Context) ([]byte, error){
|
var handleTaskMap = map[string]func(c *echo.Context) ([]byte, error){
|
||||||
"image:compress": task.HandleImageCompress,
|
"image:compress": task.HandleImageCompress,
|
||||||
"image:convert": task.HandleImageConvert,
|
"image:convert": task.HandleImageConvert,
|
||||||
|
"text:translate": task.HandleTextTranslate,
|
||||||
}
|
}
|
||||||
|
|
||||||
func CreateTask(c *echo.Context) error {
|
func CreateTask(c *echo.Context) error {
|
||||||
|
|||||||
45
backend/internal/controllers/task/text.go
Normal file
45
backend/internal/controllers/task/text.go
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
package task
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
|
||||||
|
"github.com/labstack/echo/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
var validProviders = map[string]bool{
|
||||||
|
"google": true,
|
||||||
|
"microsoft": true,
|
||||||
|
"deeplx": true,
|
||||||
|
"deepseek": true,
|
||||||
|
}
|
||||||
|
|
||||||
|
var validSources = map[string]bool{
|
||||||
|
"auto": true,
|
||||||
|
"zh-CN": true,
|
||||||
|
"en": true,
|
||||||
|
"ja": true,
|
||||||
|
"ko": true,
|
||||||
|
}
|
||||||
|
|
||||||
|
type TranslateTextRequest struct {
|
||||||
|
Text string `json:"text"`
|
||||||
|
Source string `json:"source"`
|
||||||
|
Target string `json:"target"`
|
||||||
|
Provider string `json:"provider"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func HandleTextTranslate(c *echo.Context) ([]byte, error) {
|
||||||
|
r := new(TranslateTextRequest)
|
||||||
|
if err := c.Bind(r); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if r.Text == "" || r.Target == "" || !validProviders[r.Provider] || !validSources[r.Source] {
|
||||||
|
return nil, ErrInvalidRequest
|
||||||
|
}
|
||||||
|
return json.Marshal(map[string]any{
|
||||||
|
"text": r.Text,
|
||||||
|
"source": r.Source,
|
||||||
|
"target": r.Target,
|
||||||
|
"provider": r.Provider,
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -71,18 +71,13 @@ func MergeFileSlices(fileId string, uploadPath string) (string, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return "", fmt.Errorf("打开切片文件失败: %v", err)
|
return "", fmt.Errorf("打开切片文件失败: %v", err)
|
||||||
}
|
}
|
||||||
defer sf.Close() //nolint:errcheck
|
|
||||||
for {
|
if _, err := io.CopyBuffer(destFile, sf, buffer); err != nil {
|
||||||
n, err := sf.Read(buffer)
|
sf.Close() //nolint:errcheck
|
||||||
if err == io.EOF {
|
return "", fmt.Errorf("合并切片文件失败: %v", err)
|
||||||
break
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
return "", fmt.Errorf("读取切片文件失败: %v", err)
|
|
||||||
}
|
|
||||||
if _, err := destFile.Write(buffer[:n]); err != nil {
|
|
||||||
return "", fmt.Errorf("写入合并文件失败: %v", err)
|
|
||||||
}
|
}
|
||||||
|
if err := sf.Close(); err != nil {
|
||||||
|
return "", fmt.Errorf("关闭切片文件失败: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return mergeFilePath, nil
|
return mergeFilePath, nil
|
||||||
|
|||||||
@@ -6,40 +6,36 @@ import (
|
|||||||
"github.com/labstack/echo/v5"
|
"github.com/labstack/echo/v5"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Option interface {
|
|
||||||
applyTo(*HTTPBaseResponse)
|
|
||||||
}
|
|
||||||
|
|
||||||
type HTTPBaseResponse struct {
|
type HTTPBaseResponse struct {
|
||||||
code int
|
code int
|
||||||
message string
|
message string
|
||||||
data map[string]any
|
data map[string]any
|
||||||
}
|
}
|
||||||
|
|
||||||
type HTTPBaseResponseProps func(props *HTTPBaseResponse) error
|
type HTTPBaseResponseProps func(props *HTTPBaseResponse)
|
||||||
|
|
||||||
type WithCode int
|
func WithCode(data int) HTTPBaseResponseProps {
|
||||||
|
return func(props *HTTPBaseResponse) {
|
||||||
func (o WithCode) applyTo(props *HTTPBaseResponse) {
|
props.code = data
|
||||||
props.code = int(o)
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
type WithMessage string
|
func WithMessage(data string) HTTPBaseResponseProps {
|
||||||
|
return func(props *HTTPBaseResponse) {
|
||||||
func (o WithMessage) applyTo(props *HTTPBaseResponse) {
|
props.message = data
|
||||||
props.message = string(o)
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
type WithData map[string]any
|
func WithData(data map[string]any) HTTPBaseResponseProps {
|
||||||
|
return func(props *HTTPBaseResponse) {
|
||||||
func (o WithData) applyTo(props *HTTPBaseResponse) {
|
props.data = data
|
||||||
props.data = o
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func HTTPBaseHandler(c *echo.Context, options ...Option) error {
|
func HTTPBaseHandler(c *echo.Context, options ...HTTPBaseResponseProps) error {
|
||||||
props := HTTPBaseResponse{code: http.StatusOK, message: "success", data: map[string]any{}}
|
props := HTTPBaseResponse{code: http.StatusOK, message: "success", data: map[string]any{}}
|
||||||
for _, option := range options {
|
for _, option := range options {
|
||||||
option.applyTo(&props)
|
option(&props)
|
||||||
}
|
}
|
||||||
|
|
||||||
return c.JSON(props.code, map[string]any{
|
return c.JSON(props.code, map[string]any{
|
||||||
@@ -50,9 +46,11 @@ func HTTPBaseHandler(c *echo.Context, options ...Option) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func HTTPSuccessHandler(c *echo.Context, data map[string]any, options ...HTTPBaseResponseProps) error {
|
func HTTPSuccessHandler(c *echo.Context, data map[string]any, options ...HTTPBaseResponseProps) error {
|
||||||
return HTTPBaseHandler(c, WithData(data))
|
options = append([]HTTPBaseResponseProps{WithData(data)}, options...)
|
||||||
|
return HTTPBaseHandler(c, options...)
|
||||||
}
|
}
|
||||||
|
|
||||||
func HTTPErrorHandler(c *echo.Context, err error, options ...HTTPBaseResponseProps) error {
|
func HTTPErrorHandler(c *echo.Context, err error, options ...HTTPBaseResponseProps) error {
|
||||||
return HTTPBaseHandler(c, WithMessage(err.Error()), WithCode(http.StatusBadRequest))
|
options = append([]HTTPBaseResponseProps{WithMessage(err.Error()), WithCode(http.StatusBadRequest)}, options...)
|
||||||
|
return HTTPBaseHandler(c, options...)
|
||||||
}
|
}
|
||||||
|
|||||||
16
backend/internal/utils/session.go
Normal file
16
backend/internal/utils/session.go
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
package utils
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/gorilla/sessions"
|
||||||
|
"github.com/labstack/echo/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
func GetSession(c *echo.Context, name string) (*sessions.Session, error) {
|
||||||
|
store, err := echo.ContextGet[sessions.Store](c, "_session_store")
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to get session store: %w", err)
|
||||||
|
}
|
||||||
|
return store.Get(c.Request(), name)
|
||||||
|
}
|
||||||
@@ -18,6 +18,15 @@ func main() {
|
|||||||
}
|
}
|
||||||
defer logger.Sync() //nolint:errcheck
|
defer logger.Sync() //nolint:errcheck
|
||||||
zap.ReplaceGlobals(logger)
|
zap.ReplaceGlobals(logger)
|
||||||
|
// redis
|
||||||
|
if err := utils.InitRedis(); err != nil {
|
||||||
|
logger.Fatal("redis init failed", zap.Error(err))
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
if err := utils.InitAsynq(); err != nil {
|
||||||
|
logger.Fatal("asynq init failed", zap.Error(err))
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
|
||||||
e := echo.New()
|
e := echo.New()
|
||||||
for _, middleware := range middlewares {
|
for _, middleware := range middlewares {
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
package middleware
|
package middleware
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"backend/internal/utils"
|
||||||
|
|
||||||
"github.com/gorilla/sessions"
|
"github.com/gorilla/sessions"
|
||||||
"github.com/labstack/echo-contrib/session"
|
|
||||||
"github.com/labstack/echo/v5"
|
"github.com/labstack/echo/v5"
|
||||||
gonanoid "github.com/matoous/go-nanoid/v2"
|
gonanoid "github.com/matoous/go-nanoid/v2"
|
||||||
)
|
)
|
||||||
@@ -11,7 +12,7 @@ import (
|
|||||||
func AuthMiddleware() echo.MiddlewareFunc {
|
func AuthMiddleware() echo.MiddlewareFunc {
|
||||||
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||||
return func(c *echo.Context) error {
|
return func(c *echo.Context) error {
|
||||||
sess, err := session.Get("session", c)
|
sess, err := utils.GetSession(c, "session")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,10 +2,15 @@ package middleware
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/gorilla/sessions"
|
"github.com/gorilla/sessions"
|
||||||
"github.com/labstack/echo-contrib/session"
|
|
||||||
"github.com/labstack/echo/v5"
|
"github.com/labstack/echo/v5"
|
||||||
)
|
)
|
||||||
|
|
||||||
func SessionMiddleware() echo.MiddlewareFunc {
|
func SessionMiddleware() echo.MiddlewareFunc {
|
||||||
return session.Middleware(sessions.NewCookieStore([]byte("secret")))
|
store := sessions.NewCookieStore([]byte("secret")) // TODO: 从配置中获取密钥
|
||||||
|
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||||
|
return func(c *echo.Context) error {
|
||||||
|
c.Set("_session_store", store)
|
||||||
|
return next(c)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -38,7 +38,7 @@ func TestGeneratePasswordHash(t *testing.T) {
|
|||||||
for _, tt := range tests {
|
for _, tt := range tests {
|
||||||
t.Run(tt.name, func(t *testing.T) {
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
// 设置环境变量
|
// 设置环境变量
|
||||||
u.InitEnv(u.EnvOption{
|
u.InitTestViper(u.EnvOption{
|
||||||
ConfigData: bytes.NewBuffer([]byte(fmt.Sprintf(`
|
ConfigData: bytes.NewBuffer([]byte(fmt.Sprintf(`
|
||||||
share:
|
share:
|
||||||
password_salt: %s
|
password_salt: %s
|
||||||
|
|||||||
@@ -16,6 +16,17 @@ redis:
|
|||||||
# (必填)redis 地址
|
# (必填)redis 地址
|
||||||
url: redis://redis:6379/0
|
url: redis://redis:6379/0
|
||||||
|
|
||||||
|
# 实例功能配置
|
||||||
|
features:
|
||||||
|
file-share:
|
||||||
|
enabled: true
|
||||||
|
text-share:
|
||||||
|
enabled: true
|
||||||
|
file-image-compress:
|
||||||
|
enabled: true
|
||||||
|
file-image-convert:
|
||||||
|
enabled: true
|
||||||
|
|
||||||
# 站点基本信息
|
# 站点基本信息
|
||||||
site:
|
site:
|
||||||
# 必填,对应你的公网域名
|
# 必填,对应你的公网域名
|
||||||
|
|||||||
@@ -2,14 +2,19 @@
|
|||||||
import { useQuery } from '@tanstack/vue-query'
|
import { useQuery } from '@tanstack/vue-query'
|
||||||
import { Skeleton } from '@/components/ui/skeleton'
|
import { Skeleton } from '@/components/ui/skeleton'
|
||||||
import getFileSize from '~/lib/getFileSize'
|
import getFileSize from '~/lib/getFileSize'
|
||||||
import SparkMD5 from 'spark-md5'
|
|
||||||
import useMyAppConfig from '@/composables/useMyAppConfig'
|
import useMyAppConfig from '@/composables/useMyAppConfig'
|
||||||
|
import { useFeatureMeta } from '@/composables/useFeatureMeta'
|
||||||
import Progress from '~/components/ui/progress/Progress.vue'
|
import Progress from '~/components/ui/progress/Progress.vue'
|
||||||
import renderI18n from '~/lib/renderI18n'
|
import renderI18n from '~/lib/renderI18n'
|
||||||
import { I18nT } from 'vue-i18n'
|
import { I18nT } from 'vue-i18n'
|
||||||
|
import { calcNativeHash } from '~/lib/calcFileHash'
|
||||||
|
import { Avatar, AvatarImage, AvatarFallback } from '@/components/ui/avatar'
|
||||||
|
import { Accordion, AccordionItem, AccordionTrigger, AccordionContent } from '@/components/ui/accordion'
|
||||||
|
import MarkdownRender from '@/components/MarkdownRender.vue'
|
||||||
|
|
||||||
const { locale } = useI18n()
|
const { locale } = useI18n()
|
||||||
const appConfig = useMyAppConfig()
|
const appConfig = useMyAppConfig()
|
||||||
|
const featureMeta = useFeatureMeta()
|
||||||
const { data, isLoading } = useQuery({
|
const { data, isLoading } = useQuery({
|
||||||
queryKey: ['about'],
|
queryKey: ['about'],
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
@@ -32,9 +37,12 @@ const { data, isLoading } = useQuery({
|
|||||||
})
|
})
|
||||||
const { t } = useI18n()
|
const { t } = useI18n()
|
||||||
|
|
||||||
const genUserAvatar = (email: string) => {
|
const { state: userAvatar } = useAsyncState(async () => {
|
||||||
return `https://www.gravatar.com/avatar/${SparkMD5.hash(email)}?d=retro`
|
if (!data?.value?.email) return null
|
||||||
}
|
const buffer = new TextEncoder().encode(data?.value?.email)
|
||||||
|
const hash = await calcNativeHash(buffer)
|
||||||
|
return `https://www.gravatar.com/avatar/${hash}?d=retro`
|
||||||
|
}, null)
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
@@ -86,7 +94,7 @@ const genUserAvatar = (email: string) => {
|
|||||||
"
|
"
|
||||||
>
|
>
|
||||||
<Avatar class="size-10">
|
<Avatar class="size-10">
|
||||||
<AvatarImage v-if="!!data?.avatar || !!data?.email" :src="data?.avatar || genUserAvatar(data?.email as string)" />
|
<AvatarImage v-if="!!data?.avatar || !!data?.email" :src="data?.avatar || (userAvatar as string)" />
|
||||||
<AvatarFallback class="bg-black/10 font-bold">
|
<AvatarFallback class="bg-black/10 font-bold">
|
||||||
{{ data?.name?.charAt(0)?.toUpperCase() }}
|
{{ data?.name?.charAt(0)?.toUpperCase() }}
|
||||||
</AvatarFallback>
|
</AvatarFallback>
|
||||||
@@ -107,6 +115,29 @@ const genUserAvatar = (email: string) => {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
<template v-if="isLoading">
|
||||||
|
<Skeleton class="w-full h-24 rounded-xl" />
|
||||||
|
</template>
|
||||||
|
<template v-else>
|
||||||
|
<div class="rounded-xl bg-white/50 flex flex-col p-3 gap-3">
|
||||||
|
<div class="font-semibold">{{ t('page.about.enabledFeatures') }}</div>
|
||||||
|
<div v-if="featureMeta.length" class="flex flex-row flex-wrap gap-2">
|
||||||
|
<div
|
||||||
|
v-for="feature in featureMeta"
|
||||||
|
:key="feature.key"
|
||||||
|
class="flex flex-row items-center gap-2 rounded-full bg-black/5 px-2 py-1 text-sm font-medium"
|
||||||
|
>
|
||||||
|
<div class="flex size-6 items-center justify-center rounded-full text-black/80" :style="feature.style">
|
||||||
|
<component :is="feature.icon" class="size-3.5" />
|
||||||
|
</div>
|
||||||
|
<span>{{ feature.label }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div v-else class="text-sm opacity-75">
|
||||||
|
{{ t('page.about.enabledFeaturesEmpty') }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
<template v-if="isLoading">
|
<template v-if="isLoading">
|
||||||
<Skeleton class="w-full h-16 rounded-xl" />
|
<Skeleton class="w-full h-16 rounded-xl" />
|
||||||
</template>
|
</template>
|
||||||
|
|||||||
@@ -1,34 +1,34 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { CurveType } from '@unovis/ts'
|
|
||||||
import { AreaChart } from '@/components/ui/chart-area'
|
|
||||||
import { cx } from 'class-variance-authority'
|
import { cx } from 'class-variance-authority'
|
||||||
import { useQuery } from '@tanstack/vue-query'
|
import { useQuery } from '@tanstack/vue-query'
|
||||||
import { Skeleton } from '@/components/ui/skeleton'
|
import { Skeleton } from '@/components/ui/skeleton'
|
||||||
import AboutChartTooltip from '@/components/AboutChartTooltip.vue'
|
|
||||||
import dayjs from 'dayjs'
|
import dayjs from 'dayjs'
|
||||||
|
import { filesize } from 'filesize'
|
||||||
import { times } from 'lodash-es'
|
import { times } from 'lodash-es'
|
||||||
|
import type { ChartConfig } from '@/components/ui/chart'
|
||||||
|
import { VisArea, VisAxis, VisLine, VisXYContainer } from '@unovis/vue'
|
||||||
|
import { ChartContainer, ChartTooltip, ChartCrosshair, ChartLegendContent, componentToString, ChartTooltipContent } from '@/components/ui/chart'
|
||||||
|
|
||||||
interface StatChartData {
|
interface StatChartData {
|
||||||
file_size: number
|
file_size: number
|
||||||
file_num: number
|
file_num: number
|
||||||
share_num: number
|
share_num: number
|
||||||
download_num: number
|
download_num: number
|
||||||
date: string
|
date: Date
|
||||||
}
|
}
|
||||||
|
|
||||||
interface QueueChartData {
|
interface QueueChartData {
|
||||||
processed: number
|
processed: number
|
||||||
failed: number
|
failed: number
|
||||||
date: string
|
date: Date
|
||||||
}
|
}
|
||||||
|
|
||||||
type ChartDataItem = StatChartData | QueueChartData
|
type ChartDataItem = StatChartData | QueueChartData
|
||||||
|
|
||||||
type ChartConfig = {
|
type AreaChartConfig = {
|
||||||
data: ChartDataItem[]
|
data: ChartDataItem[]
|
||||||
index: string
|
index: string
|
||||||
categories: string[]
|
config: ChartConfig
|
||||||
colors: string[]
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const { data, isLoading } = useQuery({
|
const { data, isLoading } = useQuery({
|
||||||
@@ -82,12 +82,12 @@ const chartTabs = computed(() => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
const currentChartTab = ref<'storage' | 'queue' | 'share' | 'download'>('storage')
|
const currentChartTab = ref<'storage' | 'queue' | 'share' | 'download'>('storage')
|
||||||
const currentChartData = computed((): ChartConfig => {
|
const currentChartData = computed((): AreaChartConfig => {
|
||||||
const { storage, queue } = data.value?.chart || {}
|
const { storage, queue } = data.value?.chart || {}
|
||||||
if (currentChartTab.value === 'queue') {
|
if (currentChartTab.value === 'queue') {
|
||||||
const queueData = times(30, (i) => {
|
const queueData = times(30, (i) => {
|
||||||
return {
|
return {
|
||||||
date: dayjs().subtract(i, 'day').format('YYYY-MM-DD'),
|
date: dayjs().subtract(i, 'day').toDate(),
|
||||||
processed: queue?.[dayjs().subtract(i, 'day').format('YYYY-MM-DD')]?.processed || 0,
|
processed: queue?.[dayjs().subtract(i, 'day').format('YYYY-MM-DD')]?.processed || 0,
|
||||||
failed: queue?.[dayjs().subtract(i, 'day').format('YYYY-MM-DD')]?.failed || 0,
|
failed: queue?.[dayjs().subtract(i, 'day').format('YYYY-MM-DD')]?.failed || 0,
|
||||||
}
|
}
|
||||||
@@ -95,12 +95,14 @@ const currentChartData = computed((): ChartConfig => {
|
|||||||
return {
|
return {
|
||||||
data: queueData,
|
data: queueData,
|
||||||
index: 'date' as const,
|
index: 'date' as const,
|
||||||
categories: ['processed', 'failed'] as const,
|
config: {
|
||||||
colors: ['#4ade80', '#f87171'],
|
processed: { color: '#4ade80', label: t('page.about.processed') },
|
||||||
|
failed: { color: '#f87171', label: t('page.about.failed') },
|
||||||
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const storageData = times(30, (i) => {
|
const storageData = times(30, (i) => {
|
||||||
const base = { date: dayjs().subtract(i, 'day').format('YYYY-MM-DD') }
|
const base = { date: dayjs().subtract(i, 'day').toDate() }
|
||||||
if (currentChartTab.value === 'share') {
|
if (currentChartTab.value === 'share') {
|
||||||
return {
|
return {
|
||||||
...base,
|
...base,
|
||||||
@@ -120,25 +122,31 @@ const currentChartData = computed((): ChartConfig => {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
let categories = ['file_size', 'file_num']
|
|
||||||
if (currentChartTab.value === 'share') {
|
if (currentChartTab.value === 'share') {
|
||||||
categories = ['share_num']
|
return {
|
||||||
|
data: storageData as ChartDataItem[],
|
||||||
|
index: 'date' as const,
|
||||||
|
config: {
|
||||||
|
share_num: { color: '#ea580c', label: t('page.about.share') },
|
||||||
|
},
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if (currentChartTab.value === 'download') {
|
if (currentChartTab.value === 'download') {
|
||||||
categories = ['download_num']
|
return {
|
||||||
|
data: storageData as ChartDataItem[],
|
||||||
|
index: 'date' as const,
|
||||||
|
config: {
|
||||||
|
download_num: { color: '#a3e635', label: t('page.about.download') },
|
||||||
|
},
|
||||||
}
|
}
|
||||||
let colors = ['#38bdf8', '#a78bfa']
|
|
||||||
if (currentChartTab.value === 'share') {
|
|
||||||
colors = ['#ea580c']
|
|
||||||
}
|
|
||||||
if (currentChartTab.value === 'download') {
|
|
||||||
colors = ['#a3e635']
|
|
||||||
}
|
}
|
||||||
return {
|
return {
|
||||||
data: storageData as ChartDataItem[],
|
data: storageData as ChartDataItem[],
|
||||||
index: 'date' as const,
|
index: 'date' as const,
|
||||||
categories,
|
config: {
|
||||||
colors,
|
file_size: { color: '#38bdf8', label: t('page.about.fileSize') },
|
||||||
|
file_num: { color: '#a78bfa', label: t('page.about.fileNum') },
|
||||||
|
},
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
</script>
|
</script>
|
||||||
@@ -167,21 +175,58 @@ const currentChartData = computed((): ChartConfig => {
|
|||||||
<div class="text-lg font-semibold">{{ tab.total }}</div>
|
<div class="text-lg font-semibold">{{ tab.total }}</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<AreaChart
|
<ChartContainer :config="currentChartData.config" class="h-64 w-full p-5" :cursor="false">
|
||||||
v-if="currentChartData"
|
<VisXYContainer :data="currentChartData.data" :x-domain="[dayjs().toDate(), dayjs().subtract(29, 'day').toDate()]">
|
||||||
class="h-64 w-full"
|
<VisArea
|
||||||
:key="currentChartTab"
|
:key="currentChartTab"
|
||||||
:index="currentChartData.index"
|
:x="(d: ChartDataItem) => d.date"
|
||||||
:data="currentChartData.data"
|
:y="Object.keys(currentChartData.config).map((key) => (d: ChartDataItem) => d?.[key as keyof ChartDataItem])"
|
||||||
:categories="currentChartData.categories"
|
:color="Object.values(currentChartData.config).map((c) => c.color)"
|
||||||
:show-grid-line="false"
|
:opacity="0.6"
|
||||||
:show-legend="false"
|
|
||||||
:show-y-axis="true"
|
|
||||||
:show-x-axis="true"
|
|
||||||
:colors="currentChartData.colors"
|
|
||||||
:custom-tooltip="AboutChartTooltip"
|
|
||||||
:curve-type="CurveType.CatmullRom"
|
|
||||||
/>
|
/>
|
||||||
|
<VisLine
|
||||||
|
:key="currentChartTab"
|
||||||
|
:x="(d: ChartDataItem) => d.date"
|
||||||
|
:y="Object.keys(currentChartData.config).map((key) => (d: ChartDataItem) => d?.[key as keyof ChartDataItem])"
|
||||||
|
:color="Object.values(currentChartData.config).map((c) => c.color)"
|
||||||
|
:line-width="1"
|
||||||
|
/>
|
||||||
|
<VisAxis
|
||||||
|
:key="currentChartTab"
|
||||||
|
type="x"
|
||||||
|
:tick-line="false"
|
||||||
|
:domain-line="false"
|
||||||
|
:grid-line="false"
|
||||||
|
:num-ticks="6"
|
||||||
|
:tick-format="
|
||||||
|
(d: Date) => {
|
||||||
|
return dayjs(d).format('MMM')
|
||||||
|
}
|
||||||
|
"
|
||||||
|
:tick-values="currentChartData.data.map((d) => d.date)"
|
||||||
|
/>
|
||||||
|
<ChartTooltip />
|
||||||
|
<ChartCrosshair
|
||||||
|
:key="currentChartTab"
|
||||||
|
:template="
|
||||||
|
componentToString(currentChartData.config, ChartTooltipContent, {
|
||||||
|
class: 'w-[14rem]',
|
||||||
|
labelFormatter: (d) => {
|
||||||
|
return dayjs(d).format('MM-DD')
|
||||||
|
},
|
||||||
|
valueFormatter: (value, key) => {
|
||||||
|
if (key === 'file_size' && typeof value === 'number') {
|
||||||
|
return filesize(value)
|
||||||
|
}
|
||||||
|
return String(value)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
"
|
||||||
|
:color="(d: any, i: number) => Object.values(currentChartData.config).map((c) => c.color as string)[i]"
|
||||||
|
/>
|
||||||
|
</VisXYContainer>
|
||||||
|
<ChartLegendContent />
|
||||||
|
</ChartContainer>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
</template>
|
</template>
|
||||||
|
|||||||
@@ -1,43 +0,0 @@
|
|||||||
<script setup lang="ts">
|
|
||||||
import getFileSize from '~/lib/getFileSize'
|
|
||||||
|
|
||||||
const props = defineProps<{
|
|
||||||
data: { name: string; value: string; color: string }[]
|
|
||||||
title: string
|
|
||||||
}>()
|
|
||||||
const dataKeyMap = {
|
|
||||||
file_size: {
|
|
||||||
'zh-CN': '文件大小',
|
|
||||||
en: 'File Size',
|
|
||||||
},
|
|
||||||
file_num: {
|
|
||||||
'zh-CN': '文件数量',
|
|
||||||
en: 'File Num',
|
|
||||||
},
|
|
||||||
processed: {
|
|
||||||
'zh-CN': '处理数量',
|
|
||||||
en: 'Processed',
|
|
||||||
},
|
|
||||||
failed: {
|
|
||||||
'zh-CN': '失败数量',
|
|
||||||
en: 'Failed',
|
|
||||||
},
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<template>
|
|
||||||
<div class="rounded-md bg-white p-2 flex flex-col gap-2">
|
|
||||||
<div class="text-sm font-medium">{{ title }}</div>
|
|
||||||
<div v-for="(item, index) in data" :key="index">
|
|
||||||
<div class="flex flex-row items-center gap-2">
|
|
||||||
<div class="h-5 w-2 rounded-full" :style="{ backgroundColor: item.color ?? '#222' }"></div>
|
|
||||||
<div class="text-xs font-medium">
|
|
||||||
{{ dataKeyMap?.[item.name as keyof typeof dataKeyMap]?.['en'] ?? item.name }}
|
|
||||||
</div>
|
|
||||||
<div class="text-sm">
|
|
||||||
{{ ['file_size']?.includes(item?.name) ? getFileSize(item.value) : item.value }}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
title?: string
|
title?: string
|
||||||
showBackButton?: boolean
|
showBackButton?: boolean
|
||||||
@@ -21,7 +22,7 @@ const router = useRouter()
|
|||||||
}
|
}
|
||||||
"
|
"
|
||||||
>
|
>
|
||||||
<LucideHome />
|
<LucideHome class="size-4" />
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
<slot />
|
<slot />
|
||||||
|
|||||||
32
front/components/CopyButton.vue
Normal file
32
front/components/CopyButton.vue
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import asyncWait from '~/lib/asyncWait'
|
||||||
|
import { toast } from 'vue-sonner'
|
||||||
|
import { LucideCheck, LucideCopy } from '@lucide/vue'
|
||||||
|
|
||||||
|
const isCopy = ref(false)
|
||||||
|
const props = defineProps<{
|
||||||
|
value: string
|
||||||
|
}>()
|
||||||
|
const { copy } = useClipboard()
|
||||||
|
const { t } = useI18n()
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
class="transition-all duration-300"
|
||||||
|
size="icon"
|
||||||
|
@click="
|
||||||
|
async () => {
|
||||||
|
await copy(props?.value)
|
||||||
|
isCopy = true
|
||||||
|
toast.success(t('common.copySuccess'))
|
||||||
|
await asyncWait(3000)
|
||||||
|
isCopy = false
|
||||||
|
}
|
||||||
|
"
|
||||||
|
>
|
||||||
|
<component :is="isCopy ? LucideCheck : LucideCopy" class="size-1/2" />
|
||||||
|
</Button>
|
||||||
|
</template>
|
||||||
@@ -1,23 +1,10 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import {
|
|
||||||
LucideShare,
|
|
||||||
LucideImage,
|
|
||||||
LucideBot,
|
|
||||||
LucideLanguages,
|
|
||||||
LucideFileText,
|
|
||||||
LucideImageMinus,
|
|
||||||
LucideArrowRightLeft,
|
|
||||||
LucideImagePlus,
|
|
||||||
LucideAudioLines,
|
|
||||||
LucideListMusic,
|
|
||||||
} from 'lucide-vue-next'
|
|
||||||
import { cx } from 'class-variance-authority'
|
|
||||||
import { isObject } from 'lodash-es'
|
|
||||||
import showDrawer from '@/lib/showDrawer'
|
import showDrawer from '@/lib/showDrawer'
|
||||||
import FileShareHandle from '@/components/Preprocessing/FileShareHandle.vue'
|
import FileShareHandle from '@/components/Preprocessing/FileShareHandle.vue'
|
||||||
import ImageConvertHandle from '@/components/Preprocessing/ImageConvertHandle.vue'
|
import ImageConvertHandle from '@/components/Preprocessing/ImageConvertHandle.vue'
|
||||||
|
import { useFeatureMeta, type FeatureKey } from '@/composables/useFeatureMeta'
|
||||||
import type { FileShareHandleProps } from '../Preprocessing/types'
|
import type { FileShareHandleProps } from '../Preprocessing/types'
|
||||||
const { t } = useI18n()
|
|
||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
hide: () => void
|
hide: () => void
|
||||||
file: File[]
|
file: File[]
|
||||||
@@ -25,43 +12,25 @@ const props = defineProps<{
|
|||||||
}>()
|
}>()
|
||||||
|
|
||||||
const isImage = computed(() => props.file.every((r) => r?.type?.startsWith('image/')))
|
const isImage = computed(() => props.file.every((r) => r?.type?.startsWith('image/')))
|
||||||
const isVideo = computed(() => props.file.every((r) => r?.type?.startsWith('video/')))
|
|
||||||
const isAudio = computed(() => props.file.every((r) => r?.type?.startsWith('audio/')))
|
|
||||||
const isMedia = computed(() => isImage.value || isVideo.value || isAudio.value)
|
|
||||||
|
|
||||||
const isPDF = computed(() => props.file.every((r) => r?.type?.startsWith('application/pdf')))
|
const featureMeta = useFeatureMeta()
|
||||||
const isDOC = computed(() => props.file.every((r) => r?.type?.startsWith('application/msword')))
|
|
||||||
const isXLS = computed(() => props.file.every((r) => r?.type?.startsWith('application/vnd.ms-excel')))
|
type ActionHandler = {
|
||||||
const isPPT = computed(() => props.file.every((r) => r?.type?.startsWith('application/vnd.ms-powerpoint')))
|
condition?: () => boolean
|
||||||
const isDocument = computed(() => isPDF.value || isDOC.value || isXLS.value || isPPT.value)
|
onClick: () => void
|
||||||
const actions = [
|
}
|
||||||
{
|
|
||||||
label: t('page.upload.file.handleType.file-share'),
|
const actionHandlers: Partial<Record<FeatureKey, ActionHandler>> = {
|
||||||
icon: LucideShare,
|
'file-share': {
|
||||||
className: 'bg-green-300',
|
onClick: () => showDrawer({ render: ({ hide }) => h(FileShareHandle, { ...props, hide }) }),
|
||||||
onClick: () => {
|
|
||||||
showDrawer({
|
|
||||||
render: ({ hide }) => h(FileShareHandle, { ...props, hide }),
|
|
||||||
})
|
|
||||||
},
|
},
|
||||||
|
'file-image-compress': {
|
||||||
|
condition: () => isImage.value,
|
||||||
|
onClick: () => props.onFileHandle({ type: 'file-image-compress', config: {} }),
|
||||||
},
|
},
|
||||||
isImage.value && {
|
'file-image-convert': {
|
||||||
label: t('page.upload.file.handleType.file-image-compress'),
|
condition: () => isImage.value,
|
||||||
icon: LucideImageMinus,
|
onClick: () => showDrawer({ render: ({ hide }) => h(ImageConvertHandle, { ...props, hide }) }),
|
||||||
className: 'bg-red-300',
|
|
||||||
onClick: () => {
|
|
||||||
props.onFileHandle({ type: 'file-image-compress', config: {} })
|
|
||||||
},
|
|
||||||
},
|
|
||||||
isImage.value && {
|
|
||||||
label: t('page.upload.file.handleType.file-image-convert'),
|
|
||||||
icon: LucideArrowRightLeft,
|
|
||||||
className: 'bg-purple-300',
|
|
||||||
onClick: () => {
|
|
||||||
showDrawer({
|
|
||||||
render: ({ hide }) => h(ImageConvertHandle, { ...props, hide }),
|
|
||||||
})
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
// isImage.value && {
|
// isImage.value && {
|
||||||
// label: '图片翻译', icon: LucideLanguages, className: 'bg-orange-300', onClick: () => {
|
// label: '图片翻译', icon: LucideLanguages, className: 'bg-orange-300', onClick: () => {
|
||||||
@@ -88,19 +57,24 @@ const actions = [
|
|||||||
// console.log('复制链接')
|
// console.log('复制链接')
|
||||||
// }
|
// }
|
||||||
// },
|
// },
|
||||||
]?.filter(isObject) as {
|
}
|
||||||
label: string
|
|
||||||
icon: any
|
const actions = computed(() =>
|
||||||
className: string
|
featureMeta.value
|
||||||
onClick: () => void
|
.filter((meta) => {
|
||||||
}[]
|
const { key } = meta || {}
|
||||||
|
const handler = actionHandlers?.[key]
|
||||||
|
return handler && (!handler.condition || handler.condition())
|
||||||
|
})
|
||||||
|
.map((meta) => ({ ...meta, onClick: actionHandlers[meta.key]!.onClick }))
|
||||||
|
)
|
||||||
</script>
|
</script>
|
||||||
<template>
|
<template>
|
||||||
<div class="flex flex-col gap-5 p-5">
|
<div class="flex flex-col gap-5 p-5 overflow-x-auto">
|
||||||
<div class="flex flex-row gap-2">
|
<div class="flex flex-row gap-2">
|
||||||
<div
|
<div
|
||||||
v-for="item in actions"
|
v-for="item in actions"
|
||||||
:key="item.label"
|
:key="item.key"
|
||||||
class="flex flex-col items-center gap-2 max-w-20"
|
class="flex flex-col items-center gap-2 max-w-20"
|
||||||
@click="
|
@click="
|
||||||
() => {
|
() => {
|
||||||
@@ -109,7 +83,7 @@ const actions = [
|
|||||||
}
|
}
|
||||||
"
|
"
|
||||||
>
|
>
|
||||||
<div :class="cx('size-14 flex justify-center items-center rounded-full mx-3', item?.className)">
|
<div class="size-14 flex justify-center items-center rounded-full mx-3" :style="item?.style">
|
||||||
<component :is="item?.icon" />
|
<component :is="item?.icon" />
|
||||||
</div>
|
</div>
|
||||||
<div class="text-xs truncate w-full text-center">{{ item?.label }}</div>
|
<div class="text-xs truncate w-full text-center">{{ item?.label }}</div>
|
||||||
|
|||||||
@@ -1,41 +1,29 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { cx } from "class-variance-authority";
|
import { cx } from 'class-variance-authority'
|
||||||
|
import type { Locale } from '@intlify/core-base'
|
||||||
|
|
||||||
const { availableLocales, setLocale, locale: currentLocale, t } = useI18n();
|
const props = defineProps<{
|
||||||
const route = useRoute();
|
hide: () => void
|
||||||
|
}>()
|
||||||
|
|
||||||
const localeMap = {
|
const { locales, setLocale, locale: currentLocale, t } = useI18n()
|
||||||
"zh-CN": "简体中文",
|
|
||||||
en: "English",
|
|
||||||
// 'ja': '日本語',
|
|
||||||
// 'ko': '한국어',
|
|
||||||
// 'fr': 'Français',
|
|
||||||
// 'de': 'Deutsch',
|
|
||||||
};
|
|
||||||
|
|
||||||
const switchLocale = async (locale: string) => {
|
const switchLocale = async (locale: Locale) => {
|
||||||
await setLocale(locale as keyof typeof localeMap);
|
await setLocale(locale)
|
||||||
navigateTo(route.path, {
|
props.hide()
|
||||||
external: true,
|
}
|
||||||
});
|
|
||||||
};
|
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div class="flex flex-col gap-1 py-2">
|
<div class="flex flex-col gap-1 py-2">
|
||||||
<div class="text-xl font-bold mb-3">{{ t("i18n.switchLocale") }}</div>
|
<div class="text-xl font-bold mb-3">{{ t('i18n.switchLocale') }}</div>
|
||||||
<div
|
<div
|
||||||
v-for="locale in availableLocales"
|
v-for="locale in locales"
|
||||||
:key="locale"
|
:key="locale.code"
|
||||||
:class="
|
:class="cx('rounded-md hover:bg-black/10 p-2 cursor-pointer', currentLocale === locale.code && 'bg-black/10 font-bold')"
|
||||||
cx(
|
@click="() => switchLocale(locale.code)"
|
||||||
'rounded-md hover:bg-black/10 p-2 cursor-pointer',
|
|
||||||
currentLocale === locale && 'bg-black/10 font-bold',
|
|
||||||
)
|
|
||||||
"
|
|
||||||
@click="() => switchLocale(locale)"
|
|
||||||
>
|
>
|
||||||
{{ localeMap?.[locale as keyof typeof localeMap] }}
|
{{ locale.name }}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import FormButton from '@/components/Field/FormButton.vue'
|
|||||||
import InputField from '@/components/Field/InputField.vue'
|
import InputField from '@/components/Field/InputField.vue'
|
||||||
import type { FormContext, GenericObject } from 'vee-validate'
|
import type { FormContext, GenericObject } from 'vee-validate'
|
||||||
import { toast } from 'vue-sonner'
|
import { toast } from 'vue-sonner'
|
||||||
|
const { t } = useI18n()
|
||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
share_id: string
|
share_id: string
|
||||||
hide: any
|
hide: any
|
||||||
@@ -15,14 +16,14 @@ const handleSubmit = async (form: FormContext<GenericObject, GenericObject>) =>
|
|||||||
const password = form.values.password
|
const password = form.values.password
|
||||||
const token = await getShareToken(props.share_id, { password })
|
const token = await getShareToken(props.share_id, { password })
|
||||||
if (!token) {
|
if (!token) {
|
||||||
toast.error('密码错误')
|
toast.error(t('page.shareView.passwall.passwordError'))
|
||||||
form.resetForm()
|
form.resetForm()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
props?.hide(token)
|
props?.hide(token)
|
||||||
return
|
return
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
toast.error('密码错误')
|
toast.error(t('page.shareView.passwall.passwordError'))
|
||||||
form.resetForm()
|
form.resetForm()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -31,9 +32,9 @@ const handleSubmit = async (form: FormContext<GenericObject, GenericObject>) =>
|
|||||||
<template>
|
<template>
|
||||||
<VeeForm>
|
<VeeForm>
|
||||||
<div class="flex flex-col gap-5">
|
<div class="flex flex-col gap-5">
|
||||||
<div class="text-xl font-bold">输入密码</div>
|
<div class="text-xl font-bold">{{ t('page.shareView.passwall.title') }}</div>
|
||||||
<InputField name="password" type="password" rules="required" placeholder="请输入密码" />
|
<InputField name="password" type="password" rules="required" :placeholder="t('page.shareView.passwall.passwordPlaceholder')" />
|
||||||
<FormButton @click="handleSubmit">提交</FormButton>
|
<FormButton @click="handleSubmit">{{ t('btn.submit') }}</FormButton>
|
||||||
</div>
|
</div>
|
||||||
</VeeForm>
|
</VeeForm>
|
||||||
</template>
|
</template>
|
||||||
|
|||||||
@@ -1,17 +1,18 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import QRCode from "qrcode";
|
import QRCode from 'qrcode'
|
||||||
|
const { t } = useI18n()
|
||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
hide: () => void;
|
hide: () => void
|
||||||
data: any;
|
data: any
|
||||||
}>();
|
}>()
|
||||||
const { state } = useAsyncState(async () => {
|
const { state } = useAsyncState(async () => {
|
||||||
return await QRCode.toDataURL(props.data);
|
return await QRCode.toDataURL(props.data)
|
||||||
}, null);
|
}, null)
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div class="flex flex-col gap-5">
|
<div class="flex flex-col gap-5">
|
||||||
<div class="text-xl font-bold">分享二维码</div>
|
<div class="text-xl font-bold">{{ t('page.result.qrCode.title') }}</div>
|
||||||
<div class="flex flex-row justify-center">
|
<div class="flex flex-row justify-center">
|
||||||
<img :src="state" v-if="!!state" />
|
<img :src="state" v-if="!!state" />
|
||||||
<Skeleton class="size-20" v-else />
|
<Skeleton class="size-20" v-else />
|
||||||
|
|||||||
@@ -1,49 +1,64 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { LucideShare, LucideImage, LucideBot, LucideLanguages } from 'lucide-vue-next'
|
|
||||||
import { cx } from 'class-variance-authority'
|
|
||||||
import showDrawer from '@/lib/showDrawer'
|
import showDrawer from '@/lib/showDrawer'
|
||||||
import TextShareHandle from '@/components/Preprocessing/TextShareHandle.vue'
|
import TextShareHandle from '@/components/Preprocessing/TextShareHandle.vue'
|
||||||
|
import { useFeatureMeta, type FeatureKey } from '@/composables/useFeatureMeta'
|
||||||
|
|
||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
hide: () => void
|
hide: () => void
|
||||||
text: string
|
text: string
|
||||||
onTextHandle: ({ type, config }: { type: string; config: any }) => void
|
onTextHandle: ({ type, config }: { type: string; config: any }) => void
|
||||||
}>()
|
}>()
|
||||||
const { t } = useI18n()
|
|
||||||
const actions = [
|
const featureMeta = useFeatureMeta()
|
||||||
{
|
|
||||||
label: t('page.upload.text.handleType.text-share'),
|
type ActionHandler = {
|
||||||
icon: LucideShare,
|
condition?: () => boolean
|
||||||
className: 'bg-green-300',
|
onClick: () => void
|
||||||
onClick: () => {
|
}
|
||||||
showDrawer({
|
|
||||||
render: ({ hide }) => h(TextShareHandle, { ...props, hide }),
|
const actionHandlers: Partial<Record<FeatureKey, ActionHandler>> = {
|
||||||
|
'text-share': {
|
||||||
|
onClick: () => showDrawer({ render: ({ hide }) => h(TextShareHandle, { ...props, hide }) }),
|
||||||
|
},
|
||||||
|
// 'text-translate': {
|
||||||
|
// onClick: () =>
|
||||||
|
// props.onTextHandle({
|
||||||
|
// type: 'text-translate',
|
||||||
|
// config: {
|
||||||
|
// source: 'auto',
|
||||||
|
// },
|
||||||
|
// }),
|
||||||
|
// },
|
||||||
|
// 'text-image-generate': {
|
||||||
|
// label: '生成配图', icon: LucideImage, className: 'bg-red-300',
|
||||||
|
// onClick: () => { console.log('复制链接') }
|
||||||
|
// },
|
||||||
|
// 'text-ai-ask': {
|
||||||
|
// label: '问大模型', icon: LucideBot, className: 'bg-blue-300',
|
||||||
|
// onClick: () => { console.log('复制链接') }
|
||||||
|
// },
|
||||||
|
// 'text-translate': {
|
||||||
|
// label: '文本翻译', icon: LucideLanguages, className: 'bg-orange-300',
|
||||||
|
// onClick: () => { console.log('复制链接') }
|
||||||
|
// },
|
||||||
|
}
|
||||||
|
|
||||||
|
const actions = computed(() =>
|
||||||
|
featureMeta.value
|
||||||
|
.filter((meta) => {
|
||||||
|
const { key } = meta || {}
|
||||||
|
const handler = actionHandlers?.[key]
|
||||||
|
return handler && (!handler.condition || handler.condition())
|
||||||
})
|
})
|
||||||
},
|
.map((meta) => ({ ...meta, onClick: actionHandlers[meta.key]!.onClick }))
|
||||||
},
|
)
|
||||||
// {
|
|
||||||
// label: '生成配图', icon: LucideImage, className: 'bg-red-300', onClick: () => {
|
|
||||||
// console.log('复制链接')
|
|
||||||
// }
|
|
||||||
// },
|
|
||||||
// {
|
|
||||||
// label: '问大模型', icon: LucideBot, className: 'bg-blue-300', onClick: () => {
|
|
||||||
// console.log('复制链接')
|
|
||||||
// }
|
|
||||||
// },
|
|
||||||
// {
|
|
||||||
// label: '文本翻译', icon: LucideLanguages, className: 'bg-orange-300', onClick: () => {
|
|
||||||
// console.log('复制链接')
|
|
||||||
// }
|
|
||||||
// },
|
|
||||||
]
|
|
||||||
</script>
|
</script>
|
||||||
<template>
|
<template>
|
||||||
<div class="flex flex-col gap-5 p-5">
|
<div class="flex flex-col gap-5 p-5 overflow-x-auto">
|
||||||
<div class="flex flex-row gap-2">
|
<div class="flex flex-row gap-2">
|
||||||
<div
|
<div
|
||||||
v-for="item in actions"
|
v-for="item in actions"
|
||||||
:key="item.label"
|
:key="item.key"
|
||||||
class="flex flex-col items-center gap-2 max-w-20"
|
class="flex flex-col items-center gap-2 max-w-20"
|
||||||
@click="
|
@click="
|
||||||
() => {
|
() => {
|
||||||
@@ -52,7 +67,7 @@ const actions = [
|
|||||||
}
|
}
|
||||||
"
|
"
|
||||||
>
|
>
|
||||||
<div :class="cx('size-14 flex justify-center items-center rounded-full mx-3', item?.className)">
|
<div class="size-14 flex justify-center items-center rounded-full mx-3" :style="item?.style">
|
||||||
<component :is="item?.icon" />
|
<component :is="item?.icon" />
|
||||||
</div>
|
</div>
|
||||||
<div class="text-xs truncate w-full text-center">{{ item?.label }}</div>
|
<div class="text-xs truncate w-full text-center">{{ item?.label }}</div>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import FileUpload from '@/components/FileUpload.vue'
|
|||||||
import { cx } from 'class-variance-authority'
|
import { cx } from 'class-variance-authority'
|
||||||
import type { RuleExpression } from 'vee-validate'
|
import type { RuleExpression } from 'vee-validate'
|
||||||
import Button from '../ui/button/Button.vue'
|
import Button from '../ui/button/Button.vue'
|
||||||
import { PlusIcon } from 'lucide-vue-next'
|
import { PlusIcon } from '@lucide/vue'
|
||||||
import { isEmpty } from 'lodash-es'
|
import { isEmpty } from 'lodash-es'
|
||||||
|
|
||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
@@ -12,14 +12,25 @@ const props = defineProps<{
|
|||||||
}>()
|
}>()
|
||||||
const { value, setValue } = useField<File[]>(props?.name, props?.rules)
|
const { value, setValue } = useField<File[]>(props?.name, props?.rules)
|
||||||
const { t } = useI18n()
|
const { t } = useI18n()
|
||||||
|
|
||||||
|
const filterOutSameFile = (files: File[] | undefined, targetFile: File[] | undefined) => {
|
||||||
|
return files?.filter((file) => !targetFile?.some((r) => r?.name === file?.name && r?.type === file?.type && r?.size === file?.size)) || []
|
||||||
|
}
|
||||||
|
|
||||||
|
useEventListener(document, 'paste', (evt: ClipboardEvent) => {
|
||||||
|
const { files } = evt.clipboardData || {}
|
||||||
|
if (files?.length) {
|
||||||
|
setValue([...filterOutSameFile(value?.value, Array.from(files)), ...Array.from(files)])
|
||||||
|
}
|
||||||
|
})
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<FileUpload
|
<FileUpload
|
||||||
@onChange="
|
@onChange="
|
||||||
(file) => {
|
(files) => {
|
||||||
// 这里没hash,我们姑且认为name和size,type都一样的为同一个文件
|
// 这里没hash,我们姑且认为name和size,type都一样的为同一个文件
|
||||||
setValue([...(value?.filter((r) => r?.name !== file?.name || r?.type !== file?.type || r?.size !== file?.size) || []), file])
|
setValue([...filterOutSameFile(value, files), ...files])
|
||||||
}
|
}
|
||||||
"
|
"
|
||||||
v-slot="{ isOverDropZone }"
|
v-slot="{ isOverDropZone }"
|
||||||
@@ -41,9 +52,7 @@ const { t } = useI18n()
|
|||||||
@click="
|
@click="
|
||||||
(e: any) => {
|
(e: any) => {
|
||||||
e.stopPropagation()
|
e.stopPropagation()
|
||||||
setValue(
|
setValue(filterOutSameFile(value, [item]))
|
||||||
value?.filter((r) => r?.name !== item?.name || r?.type !== item?.type || r?.size !== item?.size) || []
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
"
|
"
|
||||||
>
|
>
|
||||||
|
|||||||
@@ -1,16 +1,20 @@
|
|||||||
<template>
|
|
||||||
<Field :name="props.name" v-slot="{ field }">
|
|
||||||
<div class="flex flex-col gap-2">
|
|
||||||
<Label v-if="props.label">{{ props.label }}</Label>
|
|
||||||
<Input v-bind="{ ...field, ...$attrs }" />
|
|
||||||
</div>
|
|
||||||
</Field>
|
|
||||||
</template>
|
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { Label } from '@/components/ui/label'
|
import { Label } from '@/components/ui/label'
|
||||||
import { Input } from '@/components/ui/input'
|
import { Input } from '@/components/ui/input'
|
||||||
|
import type { RuleExpression } from 'vee-validate'
|
||||||
|
|
||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
name: string
|
name: string
|
||||||
label?: string
|
label?: string
|
||||||
|
rules?: RuleExpression<string>
|
||||||
}>()
|
}>()
|
||||||
|
|
||||||
|
const { value, errorMessage } = useField<string>(props.name, props.rules)
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="flex flex-col gap-2">
|
||||||
|
<Label v-if="props.label">{{ props.label }}</Label>
|
||||||
|
<Input v-model="value" :aria-invalid="!!errorMessage || undefined" v-bind="$attrs" />
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|||||||
37
front/components/Field/InputGroupField.vue
Normal file
37
front/components/Field/InputGroupField.vue
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { Label } from '@/components/ui/label'
|
||||||
|
import type { RuleExpression } from 'vee-validate'
|
||||||
|
const props = defineProps<{
|
||||||
|
name: string
|
||||||
|
label?: string
|
||||||
|
rules?: RuleExpression<string[]>
|
||||||
|
}>()
|
||||||
|
const { t } = useI18n()
|
||||||
|
const { value, setValue, errorMessage } = useField<string[]>(props.name, props?.rules)
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="flex flex-col gap-2">
|
||||||
|
<Label v-if="label">{{ label }}</Label>
|
||||||
|
<div v-for="(item, index) in value" class="flex flex-row gap-2 items-center">
|
||||||
|
<Input
|
||||||
|
:model-value="item"
|
||||||
|
@update:model-value="(v: string | number) => setValue(value.map((o, i) => (i === index ? String(v) : o)))"
|
||||||
|
:aria-invalid="!!errorMessage || undefined"
|
||||||
|
v-bind="$attrs"
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
class="bg-red-500/10 text-red-500 hover:bg-red-500 hover:text-white"
|
||||||
|
@click="setValue(value.filter((_, i) => i !== index))"
|
||||||
|
>
|
||||||
|
<LucideTrash class="size-4" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
<Button class="self-start" size="sm" @click="() => setValue([...(value || []), ''])">
|
||||||
|
<LucidePlus class="size-4" />
|
||||||
|
{{ t('common.add') }}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
102
front/components/Field/KvInputGroupField.vue
Normal file
102
front/components/Field/KvInputGroupField.vue
Normal file
@@ -0,0 +1,102 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { Label } from '@/components/ui/label'
|
||||||
|
import { AutocompleteAnchor, AutocompleteContent, AutocompleteInput, AutocompleteItem, AutocompleteRoot, AutocompleteViewport } from 'reka-ui'
|
||||||
|
import type { Component } from 'vue'
|
||||||
|
import InputField from '../Field/InputField.vue'
|
||||||
|
|
||||||
|
type KvInputValueComponentConfig = [(key: string) => boolean, Component]
|
||||||
|
|
||||||
|
type KvInputConfig = {
|
||||||
|
key?: {
|
||||||
|
placeholder?: string
|
||||||
|
enum?: string[]
|
||||||
|
}
|
||||||
|
value?: {
|
||||||
|
placeholder?: string
|
||||||
|
component?: KvInputValueComponentConfig[]
|
||||||
|
default?: Component
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const defaultConfig = {
|
||||||
|
key: {},
|
||||||
|
value: {
|
||||||
|
default: InputField,
|
||||||
|
},
|
||||||
|
} satisfies Required<KvInputConfig>
|
||||||
|
|
||||||
|
const props = defineProps<{
|
||||||
|
name: string
|
||||||
|
label?: string
|
||||||
|
config?: KvInputConfig
|
||||||
|
}>()
|
||||||
|
|
||||||
|
const { t } = useI18n()
|
||||||
|
const config = computed(() => {
|
||||||
|
return {
|
||||||
|
key: { ...defaultConfig.key, ...(props.config?.key ?? {}) },
|
||||||
|
value: { ...defaultConfig.value, ...(props.config?.value ?? {}) },
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
const { value, setValue } = useField<[string, string][]>(props.name)
|
||||||
|
|
||||||
|
const updateKey = (index: number, nextKey: string | number) => {
|
||||||
|
const next = [...(value.value ?? [])]
|
||||||
|
next[index] = [String(nextKey), next[index]?.[1] ?? '']
|
||||||
|
setValue(next)
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="flex flex-col gap-2">
|
||||||
|
<Label v-if="label">{{ label }}</Label>
|
||||||
|
<div v-for="([key, _], index) in value" class="flex flex-row gap-2 items-center">
|
||||||
|
<AutocompleteRoot class="basis-40 relative" :model-value="String(key ?? '')" @update:model-value="(v) => updateKey(index, v)">
|
||||||
|
<AutocompleteAnchor>
|
||||||
|
<AutocompleteInput
|
||||||
|
class="w-full placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input flex h-9 min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm"
|
||||||
|
:placeholder="config.key.placeholder"
|
||||||
|
>
|
||||||
|
</AutocompleteInput>
|
||||||
|
</AutocompleteAnchor>
|
||||||
|
<AutocompleteContent
|
||||||
|
v-if="config.key?.enum"
|
||||||
|
class="bg-popover border rounded-md shadow-md z-50 w-(--reka-autocomplete-trigger-width) absolute inset-x-0"
|
||||||
|
>
|
||||||
|
<AutocompleteViewport class="p-1">
|
||||||
|
<AutocompleteItem
|
||||||
|
v-for="opt in config.key?.enum"
|
||||||
|
:key="opt"
|
||||||
|
:value="opt"
|
||||||
|
class="relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-highlighted:bg-accent data-highlighted:text-accent-foreground"
|
||||||
|
>
|
||||||
|
{{ opt }}
|
||||||
|
</AutocompleteItem>
|
||||||
|
</AutocompleteViewport>
|
||||||
|
</AutocompleteContent>
|
||||||
|
</AutocompleteRoot>
|
||||||
|
<div class="flex-1">
|
||||||
|
<component
|
||||||
|
:is="config.value.component?.find(([isMatchCom]) => isMatchCom(key))?.[1] ?? config.value.default"
|
||||||
|
:name="`${props.name}[${index}][1]`"
|
||||||
|
:placeholder="config.value.placeholder"
|
||||||
|
class="w-full"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
class="bg-red-500/10 text-red-500 hover:bg-red-500 hover:text-white"
|
||||||
|
@click="() => setValue(value?.filter((_, i) => i !== index))"
|
||||||
|
>
|
||||||
|
<LucideTrash class="size-4" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
<Button type="button" class="self-start" size="sm" @click="() => setValue([...(value ?? []), ['', '']])">
|
||||||
|
<LucidePlus class="size-4" />
|
||||||
|
{{ t('common.add') }}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -1,13 +1,5 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import {
|
import { Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||||
Select,
|
|
||||||
SelectContent,
|
|
||||||
SelectGroup,
|
|
||||||
SelectItem,
|
|
||||||
SelectLabel,
|
|
||||||
SelectTrigger,
|
|
||||||
SelectValue,
|
|
||||||
} from '@/components/ui/select'
|
|
||||||
import type { RuleExpression } from 'vee-validate'
|
import type { RuleExpression } from 'vee-validate'
|
||||||
type SelectValue = string | number
|
type SelectValue = string | number
|
||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
@@ -19,13 +11,14 @@ const props = defineProps<{
|
|||||||
label?: string
|
label?: string
|
||||||
value: SelectValue
|
value: SelectValue
|
||||||
}[]
|
}[]
|
||||||
|
class?: string
|
||||||
}>()
|
}>()
|
||||||
const { value } = useField<SelectValue>(props.name, props?.rules)
|
const { value } = useField<SelectValue>(props.name, props?.rules)
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<Select v-model="value">
|
<Select v-model="value">
|
||||||
<SelectTrigger>
|
<SelectTrigger :class="class">
|
||||||
<SelectValue :placeholder="placeholder" />
|
<SelectValue :placeholder="placeholder" />
|
||||||
</SelectTrigger>
|
</SelectTrigger>
|
||||||
<SelectContent>
|
<SelectContent>
|
||||||
|
|||||||
25
front/components/Field/TextareaField.vue
Normal file
25
front/components/Field/TextareaField.vue
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { Label } from '@/components/ui/label'
|
||||||
|
import { Textarea } from '@/components/ui/textarea'
|
||||||
|
|
||||||
|
const props = withDefaults(
|
||||||
|
defineProps<{
|
||||||
|
name: string
|
||||||
|
label?: string
|
||||||
|
placeholder?: string
|
||||||
|
rows?: number
|
||||||
|
}>(),
|
||||||
|
{
|
||||||
|
rows: 3,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
const { value } = useField<string>(props.name)
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="flex flex-col gap-2">
|
||||||
|
<Label v-if="label">{{ label }}</Label>
|
||||||
|
<Textarea v-model="value" :placeholder="placeholder" :rows="rows" v-bind="$attrs" />
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -1,34 +1,15 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { cx } from 'class-variance-authority'
|
import { LucideFileAudio, LucideFileVideo, LucideFile, LucideFileCode, LucideFileArchive, LucideFileText } from '@lucide/vue'
|
||||||
export type filePreview = {
|
import type { filePreview } from './Index.vue'
|
||||||
type: string
|
|
||||||
name: string
|
|
||||||
size: number
|
|
||||||
}
|
|
||||||
|
|
||||||
import { LucideFileAudio, LucideFileVideo, LucideFile, LucideFileCode, LucideFileArchive, LucideFileText } from 'lucide-vue-next'
|
|
||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
file: File | filePreview
|
file: File | filePreview
|
||||||
class?: string
|
|
||||||
}>()
|
}>()
|
||||||
const imageUrl = computed(() => {
|
|
||||||
if (props?.file?.type?.startsWith('image/') && props?.file instanceof File) {
|
|
||||||
return URL.createObjectURL(props?.file)
|
|
||||||
}
|
|
||||||
return null
|
|
||||||
})
|
|
||||||
|
|
||||||
onUnmounted(() => {
|
|
||||||
if (imageUrl.value) {
|
|
||||||
URL.revokeObjectURL(imageUrl.value)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
const fileIcon = computed(() => {
|
const fileIcon = computed(() => {
|
||||||
const [baseType, type] = props?.file?.type?.split('/')
|
const [baseType, type] = props?.file?.type?.split('/')
|
||||||
if (baseType === 'video') {
|
// if (baseType === 'video') {
|
||||||
return LucideFileVideo
|
// return LucideFileVideo
|
||||||
}
|
// }
|
||||||
if (baseType === 'audio') {
|
if (baseType === 'audio') {
|
||||||
return LucideFileAudio
|
return LucideFileAudio
|
||||||
}
|
}
|
||||||
@@ -56,12 +37,5 @@ const fileIcon = computed(() => {
|
|||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div v-if="!!imageUrl" class="flex max-w-30 max-h-20">
|
<component :is="fileIcon" />
|
||||||
<div class="object-contain m-auto h-full">
|
|
||||||
<img :src="imageUrl" class="w-full h-full border border-black/20 rounded" />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div v-if="!imageUrl" :class="cx('flex justify-center items-center rounded-xl bg-white/80 size-16', props?.class)">
|
|
||||||
<component :is="fileIcon" class="size-[62.5%]" />
|
|
||||||
</div>
|
|
||||||
</template>
|
</template>
|
||||||
29
front/components/FileIcon/Image.vue
Normal file
29
front/components/FileIcon/Image.vue
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { isHeic, heicTo } from 'heic-to'
|
||||||
|
|
||||||
|
const props = defineProps<{
|
||||||
|
file: File
|
||||||
|
}>()
|
||||||
|
|
||||||
|
const { state: imageUrl } = useAsyncState(async () => {
|
||||||
|
let blob: Blob = props?.file
|
||||||
|
if (await isHeic(props?.file)) {
|
||||||
|
blob = await heicTo({
|
||||||
|
blob: props?.file,
|
||||||
|
type: 'image/jpeg',
|
||||||
|
quality: 1,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return URL.createObjectURL(blob)
|
||||||
|
}, null)
|
||||||
|
|
||||||
|
onUnmounted(() => {
|
||||||
|
if (imageUrl.value) {
|
||||||
|
URL.revokeObjectURL(imageUrl.value)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<img v-if="!!imageUrl" :src="imageUrl" />
|
||||||
|
</template>
|
||||||
61
front/components/FileIcon/Index.vue
Normal file
61
front/components/FileIcon/Index.vue
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { cx } from 'class-variance-authority'
|
||||||
|
import FileIcon from './File.vue'
|
||||||
|
import ImageIcon from './Image.vue'
|
||||||
|
import VideoIcon from './Video.vue'
|
||||||
|
import { fileTypeFromBuffer } from 'file-type'
|
||||||
|
|
||||||
|
export type filePreview = {
|
||||||
|
type: string
|
||||||
|
name: string
|
||||||
|
size: number
|
||||||
|
}
|
||||||
|
|
||||||
|
const props = withDefaults(
|
||||||
|
defineProps<{
|
||||||
|
file: File | filePreview
|
||||||
|
class?: string
|
||||||
|
size?: 'sm' | 'md' | 'lg'
|
||||||
|
}>(),
|
||||||
|
{
|
||||||
|
size: 'md',
|
||||||
|
}
|
||||||
|
)
|
||||||
|
const isFile = computed(() => props?.file instanceof File)
|
||||||
|
const { state: fileType } = useAsyncState(async () => {
|
||||||
|
if (!isFile.value) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
if (!!props?.file?.type) {
|
||||||
|
return props?.file?.type
|
||||||
|
}
|
||||||
|
const { mime } = (await fileTypeFromBuffer(await (props?.file as File)?.arrayBuffer())) || {}
|
||||||
|
return mime
|
||||||
|
}, null)
|
||||||
|
|
||||||
|
const isImage = computed(() => isFile.value && fileType.value?.startsWith('image/'))
|
||||||
|
const isVideo = computed(() => isFile.value && fileType.value?.startsWith('video/'))
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div v-if="isImage || isVideo" :class="cx('flex overflow-hidden', size === 'sm' && 'max-w-20 max-h-16', size === 'md' && 'max-w-30 max-h-20')">
|
||||||
|
<component
|
||||||
|
:is="isImage ? ImageIcon : VideoIcon"
|
||||||
|
:file="props?.file as File"
|
||||||
|
class="block max-w-full max-h-full object-contain border border-black/20 rounded"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
v-else
|
||||||
|
:class="
|
||||||
|
cx(
|
||||||
|
'flex justify-center items-center bg-white/80',
|
||||||
|
size === 'sm' && 'size-7 rounded-md',
|
||||||
|
size === 'md' && 'size-16 rounded-xl',
|
||||||
|
props?.class
|
||||||
|
)
|
||||||
|
"
|
||||||
|
>
|
||||||
|
<component :is="FileIcon" :file="props?.file" class="size-[62.5%]" />
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
27
front/components/FileIcon/Video.vue
Normal file
27
front/components/FileIcon/Video.vue
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import getVideoFileThumbnail from '@/lib/getVideoFileThumbnail'
|
||||||
|
|
||||||
|
const props = defineProps<{
|
||||||
|
file: File
|
||||||
|
}>()
|
||||||
|
|
||||||
|
const { state: thumbnailUrl } = useAsyncState(async () => {
|
||||||
|
if (props.file.type.startsWith('video/')) {
|
||||||
|
return await getVideoFileThumbnail(props.file)
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}, null)
|
||||||
|
|
||||||
|
onUnmounted(() => {
|
||||||
|
if (!!thumbnailUrl.value) {
|
||||||
|
URL.revokeObjectURL(thumbnailUrl.value)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div v-if="thumbnailUrl" class="relative grayscale-50 overflow-hidden">
|
||||||
|
<img :src="thumbnailUrl" class="object-contain block max-w-full max-h-full" />
|
||||||
|
<LucidePlay class="size-[40%] absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 text-white" />
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
<script lang="ts" setup>
|
<script lang="ts" setup>
|
||||||
import getFileSize from '~/lib/getFileSize'
|
import getFileSize from '~/lib/getFileSize'
|
||||||
import type { filePreview } from './FileIcon.vue'
|
import type { filePreview } from './FileIcon/Index.vue'
|
||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
value: File | filePreview
|
value: File | filePreview
|
||||||
}>()
|
}>()
|
||||||
|
|||||||
@@ -9,13 +9,13 @@ const props = defineProps<{
|
|||||||
const accept = computed(() => (props?.accept || ['*'])?.join(','))
|
const accept = computed(() => (props?.accept || ['*'])?.join(','))
|
||||||
|
|
||||||
const emit = defineEmits<{
|
const emit = defineEmits<{
|
||||||
(e: 'onChange', file: File): void
|
(e: 'onChange', file: File[]): void
|
||||||
}>()
|
}>()
|
||||||
|
|
||||||
const { isOverDropZone } = useDropZone(dropZoneRef, {
|
const { isOverDropZone } = useDropZone(dropZoneRef, {
|
||||||
onDrop: (file) => {
|
onDrop: (file) => {
|
||||||
if (file?.[0]) {
|
if (!!file && file?.length > 0) {
|
||||||
emit('onChange', file?.[0])
|
emit('onChange', file)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
// 指定要接收的数据类型
|
// 指定要接收的数据类型
|
||||||
@@ -26,7 +26,7 @@ const { isOverDropZone } = useDropZone(dropZoneRef, {
|
|||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
if (acceptType?.endsWith('*')) {
|
if (acceptType?.endsWith('*')) {
|
||||||
const [acceptTypePrefix,] = acceptType?.split('/')
|
const [acceptTypePrefix] = acceptType?.split('/')
|
||||||
if (!acceptTypePrefix) {
|
if (!acceptTypePrefix) {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
@@ -42,7 +42,7 @@ const { isOverDropZone } = useDropZone(dropZoneRef, {
|
|||||||
return false
|
return false
|
||||||
},
|
},
|
||||||
// 控制多文件拖放
|
// 控制多文件拖放
|
||||||
multiple: false,
|
multiple: true,
|
||||||
// 是否阻止未处理事件的默认行为
|
// 是否阻止未处理事件的默认行为
|
||||||
preventDefaultForUnhandled: false,
|
preventDefaultForUnhandled: false,
|
||||||
})
|
})
|
||||||
@@ -52,14 +52,14 @@ const { open, onChange } = useFileDialog({
|
|||||||
directory: false,
|
directory: false,
|
||||||
})
|
})
|
||||||
onChange((files) => {
|
onChange((files) => {
|
||||||
if (files?.[0]) {
|
if (!!files && files?.length > 0) {
|
||||||
emit('onChange', files?.[0])
|
emit('onChange', Array.from(files))
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div ref="dropZoneRef" @click="open">
|
<div ref="dropZoneRef" @click="() => open()">
|
||||||
<slot :isOverDropZone="isOverDropZone" />
|
<slot :isOverDropZone="isOverDropZone" />
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
@@ -1,35 +1,44 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { Drawer, DrawerContent } from '@/components/ui/drawer'
|
import { Drawer, DrawerContent } from '@/components/ui/drawer'
|
||||||
import { createVNode } from 'vue'
|
import type { VNode } from 'vue'
|
||||||
import useStore from '@/composables/useStore'
|
import useStore from '@/composables/useStore'
|
||||||
|
import { isFunction } from 'lodash-es'
|
||||||
|
|
||||||
|
type DrawerOnclose<T = unknown> = (data?: T) => Promise<void>
|
||||||
|
type DrawerRender<T = unknown> = VNode | ((props: { hide: DrawerOnclose<T> }) => VNode)
|
||||||
|
export type DrawerItem<T = unknown> = {
|
||||||
|
render?: DrawerRender<T>
|
||||||
|
onClose: DrawerOnclose<T>
|
||||||
|
key: string
|
||||||
|
visible: boolean
|
||||||
|
}
|
||||||
|
|
||||||
const store = useStore()
|
const store = useStore()
|
||||||
const currentDrawer = computed(() => store.drawer?.[store.drawer?.length - 1])
|
|
||||||
|
|
||||||
const render = computed(() => currentDrawer?.value?.render)
|
const Children = ({ drawer }: { drawer: DrawerItem }) => {
|
||||||
const hide = computed(() => currentDrawer?.value?.onClose)
|
if (!drawer.render) {
|
||||||
const Children = () =>
|
return null
|
||||||
render.value
|
}
|
||||||
? createVNode(render.value, {
|
return isFunction(drawer.render) ? drawer.render({ hide: drawer.onClose }) : drawer.render
|
||||||
hide: hide?.value,
|
}
|
||||||
})
|
|
||||||
: null
|
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<Drawer
|
<Drawer
|
||||||
:open="!!store.drawer?.[store.drawer?.length - 1]"
|
v-for="item in store.drawer"
|
||||||
|
:key="item.key"
|
||||||
|
:open="item.visible"
|
||||||
@update:open="
|
@update:open="
|
||||||
(open) => {
|
(open) => {
|
||||||
if (!open && store?.drawer?.length && hide) {
|
if (!open) {
|
||||||
hide()
|
item.onClose()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
"
|
"
|
||||||
>
|
>
|
||||||
<DrawerContent>
|
<DrawerContent>
|
||||||
<div class="mx-auto w-full max-w-lg pb-10 px-3">
|
<div class="mx-auto min-w-lg max-w-[80vw] pb-10 px-3">
|
||||||
<Children />
|
<Children :drawer="item" />
|
||||||
</div>
|
</div>
|
||||||
</DrawerContent>
|
</DrawerContent>
|
||||||
</Drawer>
|
</Drawer>
|
||||||
|
|||||||
@@ -45,7 +45,7 @@ const handleShowSpeedInfo = () => {
|
|||||||
:style="{
|
:style="{
|
||||||
height: `${clamp((i.value / Math.max(...(speedChartList?.map((r) => r.value) || [1]))) * 100, 1, 100)}%`,
|
height: `${clamp((i.value / Math.max(...(speedChartList?.map((r) => r.value) || [1]))) * 100, 1, 100)}%`,
|
||||||
}"
|
}"
|
||||||
:layoutId="i.timestamp"
|
:layoutId="String(i.timestamp)"
|
||||||
v-for="i in speedChartList"
|
v-for="i in speedChartList"
|
||||||
:key="i.timestamp"
|
:key="i.timestamp"
|
||||||
:initial="{ x: 10, opacity: 0 }"
|
:initial="{ x: 10, opacity: 0 }"
|
||||||
|
|||||||
@@ -1,11 +1,12 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { LucideSquare, LucideInfo, LucideFolders, LucideArrowUpFromLine, LucideCircleX, LucideCheckCircle, LucideLoaderCircle } from 'lucide-vue-next'
|
import { LucideSquare, LucideInfo, LucideFolders, LucideArrowUpFromLine, LucideCircleX, LucideCheckCircle, LucideLoaderCircle } from '@lucide/vue'
|
||||||
import Button from '@/components/ui/button/Button.vue'
|
import Button from '@/components/ui/button/Button.vue'
|
||||||
|
|
||||||
import getFileSize from '~/lib/getFileSize'
|
import getFileSize from '~/lib/getFileSize'
|
||||||
import { cx } from 'class-variance-authority'
|
import { cx } from 'class-variance-authority'
|
||||||
import asyncWorker from '@/lib/asyncWorker'
|
import asyncWorker from '@/lib/asyncWorker'
|
||||||
import calcFileHashWorker from '@/lib/calcFileHashWorker?worker'
|
import calcFileHashWorker from '@/lib/calcFileHashWorker?worker'
|
||||||
|
import { detectSupportedEngines } from '@/lib/calcFileHash'
|
||||||
import { clamp, get, isEmpty, isNumber, sample, shuffle, throttle, times } from 'lodash-es'
|
import { clamp, get, isEmpty, isNumber, sample, shuffle, throttle, times } from 'lodash-es'
|
||||||
import { nanoid } from 'nanoid'
|
import { nanoid } from 'nanoid'
|
||||||
import { toast } from 'vue-sonner'
|
import { toast } from 'vue-sonner'
|
||||||
@@ -137,11 +138,20 @@ watchEffect(async () => {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
const LARGE_FILE_THRESHOLD = 500 * 1024 * 1024 // 500 MB
|
||||||
|
|
||||||
const handleHash = async (fileId: string) => {
|
const handleHash = async (fileId: string) => {
|
||||||
const uploadfile = uploadfiles.value.find((item) => item.fileId === fileId)
|
const uploadfile = uploadfiles.value.find((item) => item.fileId === fileId)
|
||||||
if (!uploadfile?.file) return
|
if (!uploadfile?.file) return
|
||||||
uploadfile.procressType = 'hash'
|
uploadfile.procressType = 'hash'
|
||||||
const res = await asyncWorker(calcFileHashWorker, { data: { file: uploadfile.file } })
|
const supportedEngines = detectSupportedEngines()
|
||||||
|
if (supportedEngines.length === 0) {
|
||||||
|
throw new Error(t('page.progress.file.hashEngineNotFound'))
|
||||||
|
}
|
||||||
|
const preferredEngine = uploadfile.file.size >= LARGE_FILE_THRESHOLD ? 'wasm' : 'native'
|
||||||
|
const res = await asyncWorker(calcFileHashWorker, {
|
||||||
|
data: { file: uploadfile.file, engine: supportedEngines.includes(preferredEngine) ? preferredEngine : supportedEngines?.[0] },
|
||||||
|
})
|
||||||
const { hash } = res?.data || {}
|
const { hash } = res?.data || {}
|
||||||
uploadfile.hash = hash
|
uploadfile.hash = hash
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -44,7 +44,7 @@ const handleTextShare = ({ type, config }: { type: string; config: any }) => {
|
|||||||
}
|
}
|
||||||
"
|
"
|
||||||
>
|
>
|
||||||
<LucideX />
|
<LucideX class="size-4" />
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
<div class="flex flex-row gap-3">
|
<div class="flex flex-row gap-3">
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ const renderHtml = computed(() => {
|
|||||||
<div
|
<div
|
||||||
:class="
|
:class="
|
||||||
cx(
|
cx(
|
||||||
'prose prose-sm [&>*]:outline-none prose-p:my-1 prose-headings:my-2 prose-pre:mb-0 prose-blockquote:border-black/50 selection:bg-primary/20 break-all',
|
'prose prose-sm *:outline-none prose-p:my-1 prose-headings:my-2 prose-pre:mb-0 prose-blockquote:border-black/50 selection:bg-primary/20 break-all',
|
||||||
props?.class
|
props?.class
|
||||||
)
|
)
|
||||||
"
|
"
|
||||||
|
|||||||
@@ -1,7 +1,5 @@
|
|||||||
<template>
|
<template>
|
||||||
<div
|
<div class="flex flex-row bg-white/50 backdrop-blur-xl p-2 rounded-full gap-1 sticky top-0 z-10">
|
||||||
class="flex flex-row bg-white/50 backdrop-blur-xl p-2 rounded-full gap-1 sticky top-0 z-10"
|
|
||||||
>
|
|
||||||
<div
|
<div
|
||||||
v-for="item in routes"
|
v-for="item in routes"
|
||||||
:key="item.key"
|
:key="item.key"
|
||||||
@@ -10,16 +8,12 @@
|
|||||||
'flex flex-row items-center text-sm px-4 py-2 font-bold rounded-full relative select-none cursor-pointer',
|
'flex flex-row items-center text-sm px-4 py-2 font-bold rounded-full relative select-none cursor-pointer',
|
||||||
!isActive(item) && 'hover:bg-black/5',
|
!isActive(item) && 'hover:bg-black/5',
|
||||||
item?.name && 'gap-2',
|
item?.name && 'gap-2',
|
||||||
item?.className,
|
item?.className
|
||||||
)
|
)
|
||||||
"
|
"
|
||||||
@click="handleClick(item)"
|
@click="handleClick(item)"
|
||||||
>
|
>
|
||||||
<motion.div
|
<motion.div v-if="isActive(item)" layoutId="navbar-active" class="absolute inset-0 rounded-full w-full h-full bg-black/10" />
|
||||||
v-if="isActive(item)"
|
|
||||||
layoutId="navbar-active"
|
|
||||||
class="absolute inset-0 rounded-full w-full h-full bg-black/10"
|
|
||||||
/>
|
|
||||||
<component :is="item.icon" />
|
<component :is="item.icon" />
|
||||||
<div class="hidden sm:block">{{ item.name }}</div>
|
<div class="hidden sm:block">{{ item.name }}</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -27,64 +21,60 @@
|
|||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { cx } from "class-variance-authority";
|
import { cx } from 'class-variance-authority'
|
||||||
import { LucideClipboardType, LucidePaperclip } from "#components";
|
import { motion } from 'motion-v'
|
||||||
import { motion } from "motion-v";
|
import { LucideGlobe, LucideClipboardType, LucidePaperclip } from '@lucide/vue'
|
||||||
import { LucideGlobe } from "lucide-vue-next";
|
import showDrawer from '@/lib/showDrawer'
|
||||||
import showDrawer from "@/lib/showDrawer";
|
import I18nSwitchDrawer from './Drawer/I18nSwitchDrawer.vue'
|
||||||
import I18nSwitchDrawer from "./Drawer/I18nSwitchDrawer.vue";
|
const { t } = useI18n()
|
||||||
const { t } = useI18n();
|
const routes = computed(() => [
|
||||||
const routes = [
|
|
||||||
{
|
{
|
||||||
key: "about",
|
key: 'about',
|
||||||
icon: () =>
|
icon: () =>
|
||||||
h("img", {
|
h('img', {
|
||||||
class: "size-10 rounded-full border-2 border-white/50",
|
class: 'size-10 rounded-full border-2 border-white/50',
|
||||||
src: "/logo.png",
|
src: '/logo.png',
|
||||||
}),
|
}),
|
||||||
onClick: () => {
|
onClick: () => {
|
||||||
router.push("/about");
|
router.push('/about')
|
||||||
},
|
},
|
||||||
isActive: (item: { key: string }) => route.path?.endsWith(item.key),
|
isActive: (item: { key: string }) => route.path?.endsWith(item.key),
|
||||||
className: "!p-1.5",
|
className: '!p-1.5',
|
||||||
},
|
},
|
||||||
{ name: t("navbar.file"), key: "file", icon: LucidePaperclip },
|
{ name: t('navbar.file'), key: 'file', icon: LucidePaperclip },
|
||||||
{ name: t("navbar.text"), key: "text", icon: LucideClipboardType },
|
{ name: t('navbar.text'), key: 'text', icon: LucideClipboardType },
|
||||||
{
|
{
|
||||||
key: "i18n",
|
key: 'i18n',
|
||||||
icon: LucideGlobe,
|
icon: LucideGlobe,
|
||||||
onClick: () => {
|
onClick: () => {
|
||||||
showDrawer({
|
showDrawer({
|
||||||
render: () => h(I18nSwitchDrawer),
|
render: (props) => h(I18nSwitchDrawer, { ...props }),
|
||||||
});
|
})
|
||||||
},
|
},
|
||||||
className: "size-12 !p-1.5 justify-center items-center",
|
className: 'size-12 !p-1.5 justify-center items-center',
|
||||||
},
|
},
|
||||||
];
|
])
|
||||||
const route = useRoute();
|
const route = useRoute()
|
||||||
const router = useRouter();
|
const router = useRouter()
|
||||||
const type = computed(() => route?.query?.type);
|
const type = computed(() => route?.query?.type)
|
||||||
|
|
||||||
const isActive = (item: {
|
const isActive = (item: { key: string; isActive?: (item: { key: string }) => boolean }) => {
|
||||||
key: string;
|
const { key, isActive } = item || {}
|
||||||
isActive?: (item: { key: string }) => boolean;
|
return isActive ? isActive(item) : type.value === key
|
||||||
}) => {
|
}
|
||||||
const { key, isActive } = item || {};
|
|
||||||
return isActive ? isActive(item) : type.value === key;
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleClick = (item: { key: string; onClick?: () => void }) => {
|
const handleClick = (item: { key: string; onClick?: () => void }) => {
|
||||||
const { key, onClick } = item || {};
|
const { key, onClick } = item || {}
|
||||||
if (onClick) {
|
if (onClick) {
|
||||||
onClick();
|
onClick()
|
||||||
return;
|
return
|
||||||
}
|
}
|
||||||
router.push({
|
router.push({
|
||||||
path: "/",
|
path: '/',
|
||||||
query: {
|
query: {
|
||||||
...route.query,
|
...route.query,
|
||||||
type: key,
|
type: key,
|
||||||
},
|
},
|
||||||
});
|
})
|
||||||
};
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import SwitchField from '../Field/SwitchField.vue'
|
|
||||||
import InputField from '../Field/InputField.vue'
|
import InputField from '../Field/InputField.vue'
|
||||||
import SelectField from '../Field/SelectField.vue'
|
import SelectField from '../Field/SelectField.vue'
|
||||||
|
import SwitchField from '../Field/SwitchField.vue'
|
||||||
import FormButton from '../Field/FormButton.vue'
|
import FormButton from '../Field/FormButton.vue'
|
||||||
|
import NotifyConfigField from './NotifyConfigField.vue'
|
||||||
import type { FileShareHandleProps } from './types'
|
import type { FileShareHandleProps } from './types'
|
||||||
const { t } = useI18n()
|
const { t } = useI18n()
|
||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
@@ -14,8 +15,9 @@ const props = defineProps<{
|
|||||||
|
|
||||||
<template>
|
<template>
|
||||||
<VeeForm v-slot="{ values, setFieldValue }" :initialValues="{ download_nums: 1, expire_time: 1440 }">
|
<VeeForm v-slot="{ values, setFieldValue }" :initialValues="{ download_nums: 1, expire_time: 1440 }">
|
||||||
<div class="flex flex-col gap-3">
|
<div class="flex flex-col gap-3 max-h-[75vh]">
|
||||||
<h2 class="text-lg font-bold">{{ t('page.shareOptions.file.title') }}</h2>
|
<h2 class="text-lg font-bold">{{ t('page.shareOptions.file.title') }}</h2>
|
||||||
|
<div class="flex flex-col gap-3 flex-1 overflow-y-auto">
|
||||||
<div class="flex flex-row items-center gap-2 text-sm">
|
<div class="flex flex-row items-center gap-2 text-sm">
|
||||||
<SelectField
|
<SelectField
|
||||||
name="download_nums"
|
name="download_nums"
|
||||||
@@ -76,14 +78,7 @@ const props = defineProps<{
|
|||||||
rules="required"
|
rules="required"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div class="flex flex-row gap-3 min-h-9">
|
<NotifyConfigField :switchLabel="t('page.shareOptions.file.downloadNotify')" />
|
||||||
<SwitchField name="has_notify" :label="t('page.shareOptions.file.downloadNotify')" />
|
|
||||||
<InputField
|
|
||||||
v-if="!!values.has_notify"
|
|
||||||
name="notify_email"
|
|
||||||
:placeholder="t('page.shareOptions.file.emailPlaceholder')"
|
|
||||||
rules="required"
|
|
||||||
/>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<FormButton
|
<FormButton
|
||||||
|
|||||||
178
front/components/Preprocessing/NotifyConfigField.vue
Normal file
178
front/components/Preprocessing/NotifyConfigField.vue
Normal file
@@ -0,0 +1,178 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { Label } from '@/components/ui/label'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { useFormContext } from 'vee-validate'
|
||||||
|
import SelectField from '../Field/SelectField.vue'
|
||||||
|
import SwitchField from '../Field/SwitchField.vue'
|
||||||
|
import InputGroupField from '../Field/InputGroupField.vue'
|
||||||
|
import InputField from '../Field/InputField.vue'
|
||||||
|
import KvInputField from '../Field/KvInputGroupField.vue'
|
||||||
|
import TextareaField from '../Field/TextareaField.vue'
|
||||||
|
import { parseCurl } from 'sweet-curl-parser'
|
||||||
|
|
||||||
|
interface WebhookItem {
|
||||||
|
id: string
|
||||||
|
url: string
|
||||||
|
method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'
|
||||||
|
headers: [string, string][]
|
||||||
|
body?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
const { t } = useI18n()
|
||||||
|
const { values, setFieldValue } = useFormContext()
|
||||||
|
const expandedAdvanced = ref<Set<number>>(new Set())
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="flex flex-col gap-3">
|
||||||
|
<div class="flex flex-row gap-3 min-h-9 items-center">
|
||||||
|
<SwitchField name="has_notify" :label="t('page.shareOptions.file.downloadNotify')" />
|
||||||
|
<SelectField
|
||||||
|
v-if="values.has_notify"
|
||||||
|
name="notify_types"
|
||||||
|
:placeholder="t('page.shareOptions.notify.notifyVia')"
|
||||||
|
multiple
|
||||||
|
:options="[
|
||||||
|
{ label: t('page.shareOptions.notify.email'), value: 'email' },
|
||||||
|
{ label: t('page.shareOptions.notify.webhook'), value: 'webhook' },
|
||||||
|
]"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div v-if="!!values.has_notify && values.notify_types?.includes('email')">
|
||||||
|
<InputGroupField
|
||||||
|
name="notify_emails"
|
||||||
|
:placeholder="t('page.shareOptions.notify.emailPlaceholder')"
|
||||||
|
:label="t('page.shareOptions.notify.email')"
|
||||||
|
rules="email"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div v-if="!!values.has_notify && values.notify_types?.includes('webhook')" class="flex flex-col gap-2">
|
||||||
|
<Label>Webhook</Label>
|
||||||
|
<div v-for="(_, index) in (values.notify_webhooks as WebhookItem[]) || []" :key="index" class="flex flex-col gap-2 border rounded-md p-3">
|
||||||
|
<div class="flex flex-row gap-2 items-end">
|
||||||
|
<div class="flex flex-col gap-2">
|
||||||
|
<Label>{{ t('page.shareOptions.notify.webhookMethod') }}</Label>
|
||||||
|
<SelectField
|
||||||
|
:name="`notify_webhooks.${index}.method`"
|
||||||
|
:label="t('page.shareOptions.notify.webhookMethod')"
|
||||||
|
default-value="POST"
|
||||||
|
:options="[
|
||||||
|
{ label: 'GET', value: 'GET' },
|
||||||
|
{ label: 'POST', value: 'POST' },
|
||||||
|
{ label: 'PUT', value: 'PUT' },
|
||||||
|
{ label: 'PATCH', value: 'PATCH' },
|
||||||
|
{ label: 'DELETE', value: 'DELETE' },
|
||||||
|
]"
|
||||||
|
class="w-28"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div class="flex-1">
|
||||||
|
<InputField
|
||||||
|
:name="`notify_webhooks.${index}.url`"
|
||||||
|
:label="t('page.shareOptions.notify.webhookUrl')"
|
||||||
|
rules="required|url"
|
||||||
|
@blur="
|
||||||
|
(e: FocusEvent) => {
|
||||||
|
const input = (e?.target as HTMLInputElement)?.value
|
||||||
|
if (!input.startsWith('curl ')) return
|
||||||
|
try {
|
||||||
|
const { success, data } = parseCurl(input) || {}
|
||||||
|
if (!success) return
|
||||||
|
const { url, method, headers, body } = data || {}
|
||||||
|
setFieldValue(`notify_webhooks.${index}.url`, url?.fullUrl)
|
||||||
|
setFieldValue(`notify_webhooks.${index}.method`, method?.toUpperCase())
|
||||||
|
setFieldValue(
|
||||||
|
`notify_webhooks.${index}.headers`,
|
||||||
|
headers?.map((h: any) => [h.name, h.value])
|
||||||
|
)
|
||||||
|
if (body) setFieldValue(`notify_webhooks.${index}.body`, body)
|
||||||
|
expandedAdvanced = new Set([...expandedAdvanced, index])
|
||||||
|
} catch {}
|
||||||
|
}
|
||||||
|
"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
size="icon"
|
||||||
|
@click="
|
||||||
|
expandedAdvanced = new Set(
|
||||||
|
expandedAdvanced.has(index)
|
||||||
|
? [...expandedAdvanced].filter((expandedIndex) => expandedIndex !== index)
|
||||||
|
: [...expandedAdvanced, index]
|
||||||
|
)
|
||||||
|
"
|
||||||
|
>
|
||||||
|
<LucideSettings class="size-4" />
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
class="bg-red-500/10 text-red-500 hover:bg-red-500 hover:text-white"
|
||||||
|
@click="
|
||||||
|
() => {
|
||||||
|
setFieldValue(
|
||||||
|
'notify_webhooks',
|
||||||
|
((values.notify_webhooks as WebhookItem[]) || []).filter((_, itemIndex) => itemIndex !== index)
|
||||||
|
)
|
||||||
|
expandedAdvanced = new Set(
|
||||||
|
[...expandedAdvanced]
|
||||||
|
.filter((expandedIndex) => expandedIndex !== index)
|
||||||
|
.map((expandedIndex) => (expandedIndex > index ? expandedIndex - 1 : expandedIndex))
|
||||||
|
)
|
||||||
|
}
|
||||||
|
"
|
||||||
|
>
|
||||||
|
<LucideTrash class="size-4" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-show="expandedAdvanced.has(index)" class="flex flex-col gap-3 rounded-md border p-3">
|
||||||
|
<KvInputField
|
||||||
|
:name="`notify_webhooks.${index}.headers`"
|
||||||
|
:label="t('page.shareOptions.notify.webhookHeaders')"
|
||||||
|
:config="{
|
||||||
|
key: {
|
||||||
|
placeholder: t('page.shareOptions.notify.webhookHeaderKey'),
|
||||||
|
enum: ['Content-Type', 'User-Agent', 'Authorization', 'Accept', 'Content-Length'],
|
||||||
|
},
|
||||||
|
value: {
|
||||||
|
placeholder: t('page.shareOptions.notify.webhookHeaderValue'),
|
||||||
|
component: [
|
||||||
|
[
|
||||||
|
(key: string) => key === 'Content-Type',
|
||||||
|
({ ...props }) =>
|
||||||
|
h(SelectField, { ...props, options: [{ value: 'text/plain' }, { value: 'application/json' }] }),
|
||||||
|
],
|
||||||
|
],
|
||||||
|
},
|
||||||
|
}"
|
||||||
|
/>
|
||||||
|
<TextareaField
|
||||||
|
:name="`notify_webhooks.${index}.body`"
|
||||||
|
:label="t('page.shareOptions.notify.webhookBody')"
|
||||||
|
:rows="4"
|
||||||
|
placeholder='{"key": "value"}'
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="flex justify-start">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
size="sm"
|
||||||
|
@click="
|
||||||
|
setFieldValue('notify_webhooks', [
|
||||||
|
...((values.notify_webhooks as WebhookItem[]) || []),
|
||||||
|
{ url: '', method: 'POST', headers: [], body: '' },
|
||||||
|
])
|
||||||
|
"
|
||||||
|
>
|
||||||
|
<LucidePlus class="size-4" />
|
||||||
|
{{ t('common.add') }}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -1,8 +1,9 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import SwitchField from '../Field/SwitchField.vue'
|
|
||||||
import InputField from '../Field/InputField.vue'
|
import InputField from '../Field/InputField.vue'
|
||||||
import SelectField from '../Field/SelectField.vue'
|
import SelectField from '../Field/SelectField.vue'
|
||||||
|
import SwitchField from '../Field/SwitchField.vue'
|
||||||
import FormButton from '../Field/FormButton.vue'
|
import FormButton from '../Field/FormButton.vue'
|
||||||
|
import NotifyConfigField from './NotifyConfigField.vue'
|
||||||
import type { TextShareHandleProps } from './types'
|
import type { TextShareHandleProps } from './types'
|
||||||
const { t } = useI18n()
|
const { t } = useI18n()
|
||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
@@ -14,8 +15,9 @@ const props = defineProps<{
|
|||||||
|
|
||||||
<template>
|
<template>
|
||||||
<VeeForm v-slot="{ values, setFieldValue }" :initialValues="{ download_nums: 1, expire_time: 1440 }">
|
<VeeForm v-slot="{ values, setFieldValue }" :initialValues="{ download_nums: 1, expire_time: 1440 }">
|
||||||
<div class="flex flex-col gap-3">
|
<div class="flex flex-col gap-3 max-h-[75vh]">
|
||||||
<h2 class="text-lg font-bold">{{ t('page.shareOptions.text.title') }}</h2>
|
<h2 class="text-lg font-bold">{{ t('page.shareOptions.text.title') }}</h2>
|
||||||
|
<div class="flex flex-col gap-3 flex-1 overflow-y-auto">
|
||||||
<div class="flex flex-row items-center gap-2 text-sm">
|
<div class="flex flex-row items-center gap-2 text-sm">
|
||||||
<SelectField
|
<SelectField
|
||||||
name="download_nums"
|
name="download_nums"
|
||||||
@@ -76,14 +78,7 @@ const props = defineProps<{
|
|||||||
rules="required"
|
rules="required"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div class="flex flex-row gap-3 min-h-9">
|
<NotifyConfigField :switchLabel="t('page.shareOptions.text.readNotify')" />
|
||||||
<SwitchField name="has_notify" :label="t('page.shareOptions.text.readNotify')" />
|
|
||||||
<InputField
|
|
||||||
v-if="!!values.has_notify"
|
|
||||||
name="notify_email"
|
|
||||||
:placeholder="t('page.shareOptions.text.emailPlaceholder')"
|
|
||||||
rules="required"
|
|
||||||
/>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<FormButton
|
<FormButton
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
export type FileHandleKey = 'file-share' | 'file-image-compress' | 'file-image-convert'
|
export type FileHandleKey = 'file-share' | 'file-image-compress' | 'file-image-convert'
|
||||||
export type FileShareHandleProps = { type: FileHandleKey; config: Record<string, any> }
|
export type FileShareHandleProps = { type: FileHandleKey; config: Record<string, any> }
|
||||||
|
|
||||||
export type TextHandleKey = 'text-share'
|
export type TextHandleKey = 'text-share' | 'text-translate'
|
||||||
export type TextShareHandleProps = { type: TextHandleKey; config: Record<string, any> }
|
export type TextShareHandleProps = { type: TextHandleKey; config: Record<string, any> }
|
||||||
|
|||||||
@@ -2,8 +2,7 @@
|
|||||||
import { Button } from '@/components/ui/button'
|
import { Button } from '@/components/ui/button'
|
||||||
import FilePreviewView from '@/components/FilePreviewView.vue'
|
import FilePreviewView from '@/components/FilePreviewView.vue'
|
||||||
import { Input } from '@/components/ui/input'
|
import { Input } from '@/components/ui/input'
|
||||||
import { useClipboard } from '@vueuse/core'
|
import { useShare } from '@vueuse/core'
|
||||||
import { toast } from 'vue-sonner'
|
|
||||||
import { useQuery } from '@tanstack/vue-query'
|
import { useQuery } from '@tanstack/vue-query'
|
||||||
import useMyAppShare from '@/composables/useMyAppShare'
|
import useMyAppShare from '@/composables/useMyAppShare'
|
||||||
import useMyAppConfig from '@/composables/useMyAppConfig'
|
import useMyAppConfig from '@/composables/useMyAppConfig'
|
||||||
@@ -22,6 +21,7 @@ const { t } = useI18n()
|
|||||||
const { createFileShare } = useMyAppShare()
|
const { createFileShare } = useMyAppShare()
|
||||||
const { data } = useQuery({
|
const { data } = useQuery({
|
||||||
queryKey: ['create-share', ...props?.data?.files?.map((item) => item.id)],
|
queryKey: ['create-share', ...props?.data?.files?.map((item) => item.id)],
|
||||||
|
staleTime: Infinity,
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
const { files, config } = props?.data || {}
|
const { files, config } = props?.data || {}
|
||||||
const data = await createFileShare({
|
const data = await createFileShare({
|
||||||
@@ -44,16 +44,29 @@ watchEffect(() => {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
watchEffect(() => {
|
|
||||||
console.log('data', data?.value)
|
|
||||||
})
|
|
||||||
|
|
||||||
const appConfig = useMyAppConfig()
|
const appConfig = useMyAppConfig()
|
||||||
const getShareUrl = (id: string) => {
|
const getShareUrl = (id: string) => {
|
||||||
return `${appConfig?.value?.site_url}/s/${id}`
|
return `${appConfig?.value?.site_url}/s/${id}`
|
||||||
}
|
}
|
||||||
|
|
||||||
const { copy } = useClipboard()
|
const { share, isSupported: isShareSupported } = useShare()
|
||||||
|
|
||||||
|
const handleShare = async (id: string, fileName?: string) => {
|
||||||
|
await share({
|
||||||
|
title: fileName || 'File Share',
|
||||||
|
url: getShareUrl(id),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleShowQrCode = (id: string) => {
|
||||||
|
showDrawer({
|
||||||
|
render: ({ ...rest }) =>
|
||||||
|
h(QrCoreDrawer, {
|
||||||
|
...rest,
|
||||||
|
data: getShareUrl(id),
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
@@ -77,41 +90,33 @@ const { copy } = useClipboard()
|
|||||||
<div class="flex flex-row items-center gap-2 flex-1 min-w-0">
|
<div class="flex flex-row items-center gap-2 flex-1 min-w-0">
|
||||||
<FileIcon
|
<FileIcon
|
||||||
:file="props?.data?.files?.[data?.findIndex((i) => i?.id === file?.id) as number]?.file as File"
|
:file="props?.data?.files?.[data?.findIndex((i) => i?.id === file?.id) as number]?.file as File"
|
||||||
:class="cx('!size-7 !rounded-md shrink-0', selectedFile === file?.id && '!bg-white/50')"
|
size="sm"
|
||||||
|
:class="cx('shrink-0', selectedFile === file?.id && 'bg-white/50!')"
|
||||||
/>
|
/>
|
||||||
<div class="text-sm flex-1 truncate">{{ file?.file_name }}</div>
|
<div class="text-sm flex-1 truncate">{{ file?.file_name }}</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="flex flex-row items-center gap-2 shrink-0">
|
<div class="flex flex-row items-center gap-2 shrink-0">
|
||||||
<Button
|
<Button
|
||||||
|
v-if="isShareSupported"
|
||||||
variant="outline"
|
variant="outline"
|
||||||
:class="cx('bg-white/70', selectedFile === file?.id && '!bg-white/30 border-none hover:text-white/80')"
|
:class="cx('bg-white/70', selectedFile === file?.id && '!bg-white/30 border-none hover:text-white/80')"
|
||||||
size="icon"
|
size="icon"
|
||||||
@click="
|
@click.stop="handleShare(file?.id as string, file?.file_name)"
|
||||||
() => {
|
|
||||||
copy(getShareUrl(file?.id as string))
|
|
||||||
toast.success(t('page.result.file.copySuccess'))
|
|
||||||
}
|
|
||||||
"
|
|
||||||
>
|
>
|
||||||
<LucideCopy />
|
<LucideShare class="size-1/2" />
|
||||||
</Button>
|
</Button>
|
||||||
|
<CopyButton
|
||||||
|
:class="cx('bg-white/70', selectedFile === file?.id && '!bg-white/30 border-none hover:text-white/80')"
|
||||||
|
:value="getShareUrl(file?.id as string)"
|
||||||
|
@click.stop
|
||||||
|
/>
|
||||||
<Button
|
<Button
|
||||||
variant="outline"
|
variant="outline"
|
||||||
:class="cx('bg-white/70', selectedFile === file?.id && '!bg-white/30 border-none hover:text-white/80')"
|
:class="cx('bg-white/70', selectedFile === file?.id && '!bg-white/30 border-none hover:text-white/80')"
|
||||||
size="icon"
|
size="icon"
|
||||||
@click="
|
@click.stop="handleShowQrCode(file?.id as string)"
|
||||||
() => {
|
|
||||||
showDrawer({
|
|
||||||
render: ({ ...rest }) =>
|
|
||||||
h(QrCoreDrawer, {
|
|
||||||
...rest,
|
|
||||||
data: getShareUrl(file?.id as string),
|
|
||||||
}),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
"
|
|
||||||
>
|
>
|
||||||
<LucideQrCode />
|
<LucideQrCode class="size-1/2" />
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -133,19 +138,7 @@ const { copy } = useClipboard()
|
|||||||
<div class="rounded-xl flex flex-col bg-black/10 px-3 py-2 gap-1" v-if="selectedFileShare?.pickup_code">
|
<div class="rounded-xl flex flex-col bg-black/10 px-3 py-2 gap-1" v-if="selectedFileShare?.pickup_code">
|
||||||
<div class="flex flex-row justify-between w-full items-center">
|
<div class="flex flex-row justify-between w-full items-center">
|
||||||
<div class="text-xs font-semibold">{{ t('page.result.file.pickupCode') }}</div>
|
<div class="text-xs font-semibold">{{ t('page.result.file.pickupCode') }}</div>
|
||||||
<Button
|
<CopyButton class="bg-white/70 p-0 size-6" :value="selectedFileShare?.pickup_code as string" />
|
||||||
variant="outline"
|
|
||||||
class="bg-white/70 p-0 size-6"
|
|
||||||
size="icon"
|
|
||||||
@click="
|
|
||||||
() => {
|
|
||||||
copy(selectedFileShare?.pickup_code as string)
|
|
||||||
toast.success(t('page.result.file.copySuccess'))
|
|
||||||
}
|
|
||||||
"
|
|
||||||
>
|
|
||||||
<LucideCopy class="size-3" />
|
|
||||||
</Button>
|
|
||||||
</div>
|
</div>
|
||||||
<div class="flex flex-row gap-2">
|
<div class="flex flex-row gap-2">
|
||||||
<div v-for="s in selectedFileShare?.pickup_code" class="text-2xl font-light">
|
<div v-for="s in selectedFileShare?.pickup_code" class="text-2xl font-light">
|
||||||
@@ -160,36 +153,23 @@ const { copy } = useClipboard()
|
|||||||
<div class="flex flex-row gap-2">
|
<div class="flex flex-row gap-2">
|
||||||
<Input :model-value="getShareUrl(selectedFileShare?.id as string)" class="bg-white/70" readonly />
|
<Input :model-value="getShareUrl(selectedFileShare?.id as string)" class="bg-white/70" readonly />
|
||||||
<Button
|
<Button
|
||||||
|
v-if="isShareSupported"
|
||||||
variant="outline"
|
variant="outline"
|
||||||
class="bg-white/70"
|
class="bg-white/70"
|
||||||
size="icon"
|
size="icon"
|
||||||
@click="
|
@click="
|
||||||
() => {
|
handleShare(
|
||||||
copy(getShareUrl(selectedFileShare?.id as string))
|
selectedFileShare?.id as string,
|
||||||
toast.success(t('page.result.file.copySuccess'))
|
props?.data?.files?.[data?.findIndex((item) => item?.id === selectedFileShare?.id) as number]?.file?.name
|
||||||
}
|
)
|
||||||
"
|
"
|
||||||
>
|
>
|
||||||
<LucideCopy />
|
<LucideShare class="size-1/2" />
|
||||||
</Button>
|
</Button>
|
||||||
|
<CopyButton class="bg-white/70" :value="getShareUrl(selectedFileShare?.id as string)" />
|
||||||
|
|
||||||
<Button
|
<Button variant="outline" class="bg-white/70" size="icon" @click="handleShowQrCode(selectedFileShare?.id as string)">
|
||||||
variant="outline"
|
<LucideQrCode class="size-1/2" />
|
||||||
class="bg-white/70"
|
|
||||||
size="icon"
|
|
||||||
@click="
|
|
||||||
() => {
|
|
||||||
showDrawer({
|
|
||||||
render: ({ ...rest }) =>
|
|
||||||
h(QrCoreDrawer, {
|
|
||||||
...rest,
|
|
||||||
data: getShareUrl(selectedFileShare?.id as string),
|
|
||||||
}),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
"
|
|
||||||
>
|
|
||||||
<LucideQrCode />
|
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
<script lang="ts" setup>
|
<script lang="ts" setup>
|
||||||
import FileShareResult from '@/components/Result/FileShareResult.vue'
|
import FileShareResult from '@/components/Result/FileShareResult.vue'
|
||||||
import TextShareResult from '@/components/Result/TextShareResult.vue'
|
import TextShareResult from '@/components/Result/TextShareResult.vue'
|
||||||
|
import TextTranslateResult from '@/components/Result/TextTranslateResult.vue'
|
||||||
import ImageCompressResult from '@/components/Result/ImageCompressResult.vue'
|
import ImageCompressResult from '@/components/Result/ImageCompressResult.vue'
|
||||||
import ImageConvertResult from '@/components/Result/ImageConvertResult.vue'
|
import ImageConvertResult from '@/components/Result/ImageConvertResult.vue'
|
||||||
import type { filehandleData, handleComponent, handleKey, texthandleData } from './types'
|
import type { filehandleData, handleComponent, handleKey, texthandleData } from './types'
|
||||||
@@ -16,6 +17,7 @@ const emit = defineEmits<{
|
|||||||
const handleList: { component: handleComponent; key: handleKey }[] = [
|
const handleList: { component: handleComponent; key: handleKey }[] = [
|
||||||
{ component: FileShareResult, key: 'file-share' },
|
{ component: FileShareResult, key: 'file-share' },
|
||||||
{ component: TextShareResult, key: 'text-share' },
|
{ component: TextShareResult, key: 'text-share' },
|
||||||
|
{ component: TextTranslateResult, key: 'text-translate' },
|
||||||
{ component: ImageCompressResult, key: 'file-image-compress' },
|
{ component: ImageCompressResult, key: 'file-image-compress' },
|
||||||
{ component: ImageConvertResult, key: 'file-image-convert' },
|
{ component: ImageConvertResult, key: 'file-image-convert' },
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -1,8 +1,6 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { Button } from '@/components/ui/button'
|
import { Button } from '@/components/ui/button'
|
||||||
import { Input } from '@/components/ui/input'
|
import { Input } from '@/components/ui/input'
|
||||||
import { useClipboard } from '@vueuse/core'
|
|
||||||
import { toast } from 'vue-sonner'
|
|
||||||
import { useQuery } from '@tanstack/vue-query'
|
import { useQuery } from '@tanstack/vue-query'
|
||||||
import useMyAppShare from '@/composables/useMyAppShare'
|
import useMyAppShare from '@/composables/useMyAppShare'
|
||||||
import useMyAppConfig from '@/composables/useMyAppConfig'
|
import useMyAppConfig from '@/composables/useMyAppConfig'
|
||||||
@@ -37,7 +35,6 @@ const url = computed(() => {
|
|||||||
return `${appConfig?.value?.site_url}/s/${id}`
|
return `${appConfig?.value?.site_url}/s/${id}`
|
||||||
})
|
})
|
||||||
|
|
||||||
const { copy } = useClipboard()
|
|
||||||
const { t } = useI18n()
|
const { t } = useI18n()
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
@@ -60,19 +57,7 @@ const { t } = useI18n()
|
|||||||
<div class="rounded-xl flex flex-col bg-black/10 px-3 py-2 gap-1" v-if="data?.pickup_code">
|
<div class="rounded-xl flex flex-col bg-black/10 px-3 py-2 gap-1" v-if="data?.pickup_code">
|
||||||
<div class="flex flex-row justify-between w-full items-center">
|
<div class="flex flex-row justify-between w-full items-center">
|
||||||
<div class="text-xs font-semibold">{{ t('page.result.text.pickupCode') }}</div>
|
<div class="text-xs font-semibold">{{ t('page.result.text.pickupCode') }}</div>
|
||||||
<Button
|
<CopyButton class="bg-white/70 p-0 size-6" :value="data?.pickup_code as string" />
|
||||||
variant="outline"
|
|
||||||
class="bg-white/70 p-0 size-6"
|
|
||||||
size="icon"
|
|
||||||
@click="
|
|
||||||
() => {
|
|
||||||
copy(data?.pickup_code as string)
|
|
||||||
toast.success(t('page.result.text.copySuccess'))
|
|
||||||
}
|
|
||||||
"
|
|
||||||
>
|
|
||||||
<LucideCopy class="size-3" />
|
|
||||||
</Button>
|
|
||||||
</div>
|
</div>
|
||||||
<div class="flex flex-row gap-2">
|
<div class="flex flex-row gap-2">
|
||||||
<div v-for="s in data?.pickup_code" class="text-2xl font-light">
|
<div v-for="s in data?.pickup_code" class="text-2xl font-light">
|
||||||
@@ -86,19 +71,7 @@ const { t } = useI18n()
|
|||||||
<div class="text-sm font-semibold">{{ t('page.result.text.link') }}</div>
|
<div class="text-sm font-semibold">{{ t('page.result.text.link') }}</div>
|
||||||
<div class="flex flex-row gap-2">
|
<div class="flex flex-row gap-2">
|
||||||
<Input v-model="url" class="bg-white/70" readonly />
|
<Input v-model="url" class="bg-white/70" readonly />
|
||||||
<Button
|
<CopyButton class="bg-white/70" :value="url" />
|
||||||
variant="outline"
|
|
||||||
class="bg-white/70"
|
|
||||||
size="icon"
|
|
||||||
@click="
|
|
||||||
() => {
|
|
||||||
copy(url)
|
|
||||||
toast.success(t('page.result.text.copySuccess'))
|
|
||||||
}
|
|
||||||
"
|
|
||||||
>
|
|
||||||
<LucideCopy />
|
|
||||||
</Button>
|
|
||||||
|
|
||||||
<Button
|
<Button
|
||||||
variant="outline"
|
variant="outline"
|
||||||
|
|||||||
120
front/components/Result/TextTranslateResult.vue
Normal file
120
front/components/Result/TextTranslateResult.vue
Normal file
@@ -0,0 +1,120 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import VeeForm from '@/components/VeeForm.vue'
|
||||||
|
import MarkdownInputField from '@/components/Field/MarkdownInputField.vue'
|
||||||
|
import SelectField from '@/components/Field/SelectField.vue'
|
||||||
|
import FormButton from '@/components/Field/FormButton.vue'
|
||||||
|
import MarkdownRender from '@/components/MarkdownRender.vue'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { useClipboard } from '@vueuse/core'
|
||||||
|
import { toast } from 'vue-sonner'
|
||||||
|
import type { handleTextComponentProps } from './types'
|
||||||
|
|
||||||
|
const props = defineProps<handleTextComponentProps>()
|
||||||
|
console.log(props?.data)
|
||||||
|
|
||||||
|
const { t } = useI18n()
|
||||||
|
const { copy } = useClipboard()
|
||||||
|
const translatedText = ref('')
|
||||||
|
|
||||||
|
const languageOptions = computed(() => [
|
||||||
|
{ label: t('page.result.textTranslate.language.auto'), value: 'auto' },
|
||||||
|
{ label: t('page.result.textTranslate.language.zh-CN'), value: 'zh-CN' },
|
||||||
|
{ label: t('page.result.textTranslate.language.en'), value: 'en' },
|
||||||
|
{ label: t('page.result.textTranslate.language.ja'), value: 'ja' },
|
||||||
|
{ label: t('page.result.textTranslate.language.ko'), value: 'ko' },
|
||||||
|
])
|
||||||
|
|
||||||
|
const providerOptions = computed(() => [
|
||||||
|
{ label: 'Google', value: 'google' },
|
||||||
|
{ label: 'Microsoft', value: 'microsoft' },
|
||||||
|
{ label: 'DeepSeek', value: 'deepseek' },
|
||||||
|
// { label: 'DeepLX', value: 'deeplx' },
|
||||||
|
])
|
||||||
|
|
||||||
|
const handleCopyText = async (text?: string) => {
|
||||||
|
if (!text) return
|
||||||
|
await copy(text)
|
||||||
|
toast.success('复制成功')
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleRetranslate = async () => {
|
||||||
|
translatedText.value = ''
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<BaseCard class="flex flex-col gap-4" :title="t('page.result.textTranslate.title')" :showBackButton="true">
|
||||||
|
<VeeForm v-slot="{ values, setFieldValue }" :initialValues="{ ...data?.config, input: data?.text }">
|
||||||
|
<div class="flex flex-col gap-3">
|
||||||
|
<div class="flex flex-col gap-2">
|
||||||
|
<div class="flex flex-row justify-between items-end">
|
||||||
|
<div class="flex flex-col gap-1">
|
||||||
|
<Label class="text-xs">{{ t('page.result.textTranslate.sourceLanguage') }}</Label>
|
||||||
|
<SelectField
|
||||||
|
name="source"
|
||||||
|
class="bg-white/70"
|
||||||
|
:placeholder="t('page.result.textTranslate.sourceLanguage')"
|
||||||
|
default-value="auto"
|
||||||
|
:options="languageOptions"
|
||||||
|
rules="required"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div class="flex flex-row gap-1">
|
||||||
|
<Button variant="outline" class="bg-white/70" size="icon" @click="handleCopyText(values.input)">
|
||||||
|
<LucideCopy class="size-4" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<MarkdownInputField name="input" rules="required" class="max-h-[30vh] min-h-40 overflow-y-auto max-w-full" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="flex flex-row justify-center items-center gap-2">
|
||||||
|
<Button class="px-10">
|
||||||
|
<LucideArrowUpDown />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="flex flex-col gap-2">
|
||||||
|
<div class="flex justify-between gap-3 items-end">
|
||||||
|
<div class="flex flex-row gap-3">
|
||||||
|
<div class="flex flex-row justify-between">
|
||||||
|
<div class="flex flex-col gap-1">
|
||||||
|
<Label class="text-xs">{{ t('page.result.textTranslate.targetLanguage') }}</Label>
|
||||||
|
<SelectField
|
||||||
|
name="target"
|
||||||
|
class="bg-white/70"
|
||||||
|
:placeholder="t('page.result.textTranslate.targetLanguage')"
|
||||||
|
:options="languageOptions"
|
||||||
|
rules="required"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="flex flex-col gap-1">
|
||||||
|
<Label class="text-xs">{{ t('page.result.textTranslate.provider') }}</Label>
|
||||||
|
<SelectField
|
||||||
|
name="provider"
|
||||||
|
class="bg-white/70"
|
||||||
|
:placeholder="t('page.result.textTranslate.provider')"
|
||||||
|
default-value="mtranslate"
|
||||||
|
:options="providerOptions"
|
||||||
|
rules="required"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Button variant="outline" class="bg-white/70" size="icon" @click="handleCopyText(translatedText)">
|
||||||
|
<LucideCopy class="size-4" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
<div class="rounded-md bg-white/50 min-h-48 p-2">
|
||||||
|
<MarkdownRender :markdown="translatedText" class="prose prose-sm max-w-none min-h-40 max-h-[30vh]" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<FormButton @click="handleRetranslate" class="w-full">
|
||||||
|
<LucideLanguages class="size-4" />
|
||||||
|
{{ t('page.result.textTranslate.retranslate') }}
|
||||||
|
</FormButton>
|
||||||
|
</div>
|
||||||
|
</VeeForm>
|
||||||
|
</BaseCard>
|
||||||
|
</template>
|
||||||
@@ -4,7 +4,7 @@ import dayjs from 'dayjs'
|
|||||||
import duration from 'dayjs/plugin/duration'
|
import duration from 'dayjs/plugin/duration'
|
||||||
import relativeTime from 'dayjs/plugin/relativeTime'
|
import relativeTime from 'dayjs/plugin/relativeTime'
|
||||||
import { isBoolean } from 'lodash-es'
|
import { isBoolean } from 'lodash-es'
|
||||||
import { LucideCheck, LucideX } from 'lucide-vue-next'
|
import { LucideCheck, LucideX } from '@lucide/vue'
|
||||||
import { useQueryClient } from '@tanstack/vue-query'
|
import { useQueryClient } from '@tanstack/vue-query'
|
||||||
import showDrawer from '~/lib/showDrawer'
|
import showDrawer from '~/lib/showDrawer'
|
||||||
import { toast } from 'vue-sonner'
|
import { toast } from 'vue-sonner'
|
||||||
@@ -12,28 +12,31 @@ import PasswallShareDrawer from '~/components/Drawer/PasswallShareDrawer.vue'
|
|||||||
dayjs.extend(duration)
|
dayjs.extend(duration)
|
||||||
dayjs.extend(relativeTime)
|
dayjs.extend(relativeTime)
|
||||||
|
|
||||||
|
const { t } = useI18n()
|
||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
data: any
|
data: any
|
||||||
}>()
|
}>()
|
||||||
|
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient()
|
||||||
const { downloadFile, getShareToken } = useMyAppShare()
|
const { downloadFile, getShareToken } = useMyAppShare()
|
||||||
|
const token = ref<string>()
|
||||||
|
|
||||||
const handleDownload = async () => {
|
const handleDownload = async () => {
|
||||||
const { id } = props?.data || {}
|
const { id } = props?.data || {}
|
||||||
try {
|
try {
|
||||||
let token = null
|
if (!token.value) {
|
||||||
if (props?.data?.has_password) {
|
if (props?.data?.has_password) {
|
||||||
token = await showDrawer({
|
token.value = await showDrawer({
|
||||||
render: ({ ...rest }) => h(PasswallShareDrawer, { ...rest, share_id: id }),
|
render: ({ ...rest }) => h(PasswallShareDrawer, { ...rest, share_id: id }),
|
||||||
})
|
})
|
||||||
} else {
|
} else {
|
||||||
token = await getShareToken(id)
|
token.value = await getShareToken(id)
|
||||||
}
|
}
|
||||||
if (!token) {
|
if (!token.value) {
|
||||||
throw new Error('获取token失败')
|
throw new Error(t('page.shareView.fileShare.getTokenFailed'))
|
||||||
}
|
}
|
||||||
downloadFile(token)
|
}
|
||||||
|
downloadFile(token.value)
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
toast.error(error?.data?.message || error?.message || error)
|
toast.error(error?.data?.message || error?.message || error)
|
||||||
} finally {
|
} finally {
|
||||||
@@ -53,19 +56,19 @@ onMounted(() => {
|
|||||||
|
|
||||||
const fileShareInfo = computed(() => {
|
const fileShareInfo = computed(() => {
|
||||||
return [
|
return [
|
||||||
{ label: '需要密码', value: props?.data?.has_password ?? false },
|
{ label: t('page.shareView.fileShare.needPassword'), value: props?.data?.has_password ?? false },
|
||||||
{
|
{
|
||||||
label: '过期时间',
|
label: t('page.shareView.fileShare.expireTime'),
|
||||||
value: dayjs.duration(remaining.value, 'seconds').format(`D天 HH:mm:ss`),
|
value: dayjs.duration(remaining.value, 'seconds').format(t('page.shareView.fileShare.durationFormat')),
|
||||||
},
|
},
|
||||||
{ label: '剩余下载次数', value: props?.data?.download_nums ?? 0 },
|
{ label: t('page.shareView.fileShare.remainingDownloads'), value: props?.data?.download_nums ?? 0 },
|
||||||
]
|
]
|
||||||
})
|
})
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div class="flex flex-col gap-5 items-center">
|
<div class="flex flex-col gap-5 items-center">
|
||||||
<h1 class="text-xl font-bold">下载文件</h1>
|
<h1 class="text-xl font-bold">{{ t('page.shareView.fileShare.title') }}</h1>
|
||||||
<FilePreviewView :value="props?.data" />
|
<FilePreviewView :value="props?.data" />
|
||||||
<div class="flex flex-col gap-2 md:flex-row w-full">
|
<div class="flex flex-col gap-2 md:flex-row w-full">
|
||||||
<div class="flex flex-row md:flex-col md:gap-1 justify-between items-center md:flex-1" v-for="item in fileShareInfo">
|
<div class="flex flex-row md:flex-col md:gap-1 justify-between items-center md:flex-1" v-for="item in fileShareInfo">
|
||||||
@@ -75,7 +78,7 @@ const fileShareInfo = computed(() => {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="w-full">
|
<div class="w-full">
|
||||||
<AsyncButton @click="handleDownload" class="w-full">下载</AsyncButton>
|
<AsyncButton @click="handleDownload" class="w-full">{{ t('page.shareView.fileShare.downloadBtn') }}</AsyncButton>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|||||||
@@ -4,19 +4,17 @@ import AsyncButton from '@/components/ui/button/AsyncButton.vue'
|
|||||||
import duration from 'dayjs/plugin/duration'
|
import duration from 'dayjs/plugin/duration'
|
||||||
import relativeTime from 'dayjs/plugin/relativeTime'
|
import relativeTime from 'dayjs/plugin/relativeTime'
|
||||||
import { isBoolean } from 'lodash-es'
|
import { isBoolean } from 'lodash-es'
|
||||||
import { LucideCheck, LucideX } from 'lucide-vue-next'
|
import { LucideCheck, LucideX } from '@lucide/vue'
|
||||||
import { cx } from 'class-variance-authority'
|
import { cx } from 'class-variance-authority'
|
||||||
import { toast } from 'vue-sonner'
|
import { toast } from 'vue-sonner'
|
||||||
import MarkdownRender from '@/components/MarkdownRender.vue'
|
import MarkdownRender from '@/components/MarkdownRender.vue'
|
||||||
import { Button } from '@/components/ui/button'
|
|
||||||
import { LucideCopy } from 'lucide-vue-next'
|
|
||||||
import { useClipboard } from '@vueuse/core'
|
|
||||||
import showDrawer from '~/lib/showDrawer'
|
import showDrawer from '~/lib/showDrawer'
|
||||||
import PasswallShareDrawer from '~/components/Drawer/PasswallShareDrawer.vue'
|
import PasswallShareDrawer from '~/components/Drawer/PasswallShareDrawer.vue'
|
||||||
|
|
||||||
dayjs.extend(duration)
|
dayjs.extend(duration)
|
||||||
dayjs.extend(relativeTime)
|
dayjs.extend(relativeTime)
|
||||||
|
|
||||||
|
const { t } = useI18n()
|
||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
data: any
|
data: any
|
||||||
}>()
|
}>()
|
||||||
@@ -29,20 +27,18 @@ const expireSeconds = computed(() => {
|
|||||||
|
|
||||||
const { remaining, start } = useCountdown(expireSeconds.value)
|
const { remaining, start } = useCountdown(expireSeconds.value)
|
||||||
|
|
||||||
const { copy } = useClipboard()
|
|
||||||
|
|
||||||
onMounted(() => {
|
onMounted(() => {
|
||||||
start()
|
start()
|
||||||
})
|
})
|
||||||
|
|
||||||
const fileShareInfo = computed(() => {
|
const fileShareInfo = computed(() => {
|
||||||
return [
|
return [
|
||||||
{ label: '需要密码', value: props?.data?.has_password ?? false },
|
{ label: t('page.shareView.textShare.needPassword'), value: props?.data?.has_password ?? false },
|
||||||
{
|
{
|
||||||
label: '过期时间',
|
label: t('page.shareView.textShare.expireTime'),
|
||||||
value: dayjs.duration(remaining.value, 'seconds').format(`D天 HH:mm:ss`),
|
value: dayjs.duration(remaining.value, 'seconds').format(t('page.shareView.textShare.durationFormat')),
|
||||||
},
|
},
|
||||||
{ label: '剩余浏览次数', value: props?.data?.download_nums ?? 0 },
|
{ label: t('page.shareView.textShare.remainingViews'), value: props?.data?.download_nums ?? 0 },
|
||||||
]
|
]
|
||||||
})
|
})
|
||||||
const previewText = ref<string | null>(null)
|
const previewText = ref<string | null>(null)
|
||||||
@@ -72,20 +68,8 @@ const handlePreview = async () => {
|
|||||||
<template>
|
<template>
|
||||||
<div :class="cx('flex flex-col max-h-full', !!previewText ? 'gap-3' : 'gap-16 items-center')">
|
<div :class="cx('flex flex-col max-h-full', !!previewText ? 'gap-3' : 'gap-16 items-center')">
|
||||||
<div :class="cx('flex flex-row w-full', !!previewText ? 'justify-between' : 'justify-center')">
|
<div :class="cx('flex flex-row w-full', !!previewText ? 'justify-between' : 'justify-center')">
|
||||||
<h1 class="text-xl">查看文本</h1>
|
<h1 class="text-xl">{{ t('page.shareView.textShare.title') }}</h1>
|
||||||
<Button
|
<CopyButton v-if="!!previewText" :value="previewText as string" />
|
||||||
v-if="!!previewText"
|
|
||||||
variant="outline"
|
|
||||||
size="icon"
|
|
||||||
@click="
|
|
||||||
() => {
|
|
||||||
copy(previewText as string)
|
|
||||||
toast.success('复制成功')
|
|
||||||
}
|
|
||||||
"
|
|
||||||
>
|
|
||||||
<LucideCopy />
|
|
||||||
</Button>
|
|
||||||
</div>
|
</div>
|
||||||
<template v-if="!previewText">
|
<template v-if="!previewText">
|
||||||
<div class="flex flex-col gap-2 md:flex-row w-full">
|
<div class="flex flex-col gap-2 md:flex-row w-full">
|
||||||
@@ -96,7 +80,7 @@ const handlePreview = async () => {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="w-full">
|
<div class="w-full">
|
||||||
<AsyncButton @click="handlePreview" class="w-full">浏览</AsyncButton>
|
<AsyncButton @click="handlePreview" class="w-full">{{ t('page.shareView.textShare.viewBtn') }}</AsyncButton>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
<template v-else>
|
<template v-else>
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ import StarterKit from '@tiptap/starter-kit'
|
|||||||
import { Markdown } from 'tiptap-markdown'
|
import { Markdown } from 'tiptap-markdown'
|
||||||
import Placeholder from '@tiptap/extension-placeholder'
|
import Placeholder from '@tiptap/extension-placeholder'
|
||||||
import { cx } from 'class-variance-authority'
|
import { cx } from 'class-variance-authority'
|
||||||
|
import countWords from '@/lib/countWords'
|
||||||
|
const { t } = useI18n()
|
||||||
|
|
||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
modelValue?: string
|
modelValue?: string
|
||||||
@@ -15,6 +17,7 @@ const emit = defineEmits<{
|
|||||||
}>()
|
}>()
|
||||||
|
|
||||||
const editor = ref<Editor | undefined>(undefined)
|
const editor = ref<Editor | undefined>(undefined)
|
||||||
|
|
||||||
onMounted(() => {
|
onMounted(() => {
|
||||||
editor.value = new Editor({
|
editor.value = new Editor({
|
||||||
content: props.modelValue,
|
content: props.modelValue,
|
||||||
@@ -51,11 +54,17 @@ onUnmounted(() => {
|
|||||||
:editor="editor as any"
|
:editor="editor as any"
|
||||||
:class="
|
:class="
|
||||||
cx(
|
cx(
|
||||||
'prose prose-sm bg-white/50 rounded-md p-2 [&>*]:outline-none prose-p:my-1 prose-headings:my-2 prose-pre:mb-0 prose-blockquote:border-black/50 selection:bg-primary/20 max-w-full',
|
'prose prose-sm bg-white/50 rounded-md p-2 *:outline-none prose-p:my-1 prose-headings:my-2 prose-pre:mb-0 prose-blockquote:border-black/50 selection:bg-primary/20 max-w-full',
|
||||||
props.class
|
props.class
|
||||||
)
|
)
|
||||||
"
|
"
|
||||||
>
|
>
|
||||||
</editor-content>
|
</editor-content>
|
||||||
<!-- <BubbleMenuView :editor="editor as any" /> -->
|
<!-- <BubbleMenuView :editor="editor as any" /> -->
|
||||||
|
<div
|
||||||
|
v-if="modelValue?.length && modelValue?.length > 0"
|
||||||
|
class="absolute bottom-2 right-3 flex justify-end px-2 py-1 text-xs text-gray-400 select-none bg-white rounded-md"
|
||||||
|
>
|
||||||
|
{{ `${modelValue?.length ?? 0} ${t('common.length')} · ${countWords(modelValue ?? '')} ${t('common.words')}` }}
|
||||||
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
import type { AccordionTriggerProps } from 'reka-ui'
|
import type { AccordionTriggerProps } from 'reka-ui'
|
||||||
import type { HTMLAttributes } from 'vue'
|
import type { HTMLAttributes } from 'vue'
|
||||||
import { reactiveOmit } from '@vueuse/core'
|
import { reactiveOmit } from '@vueuse/core'
|
||||||
import { ChevronDown } from 'lucide-vue-next'
|
import { ChevronDown } from '@lucide/vue'
|
||||||
import { AccordionHeader, AccordionTrigger } from 'reka-ui'
|
import { AccordionHeader, AccordionTrigger } from 'reka-ui'
|
||||||
import { cn } from '@/lib/utils'
|
import { cn } from '@/lib/utils'
|
||||||
|
|
||||||
|
|||||||
@@ -1,179 +0,0 @@
|
|||||||
<script setup lang="ts" generic="T extends Record<string, any>">
|
|
||||||
import type { BaseChartProps } from ".";
|
|
||||||
import { type BulletLegendItemInterface, CurveType } from "@unovis/ts";
|
|
||||||
import { Area, Axis, Line } from "@unovis/ts";
|
|
||||||
import { VisArea, VisAxis, VisLine, VisXYContainer } from "@unovis/vue";
|
|
||||||
import { useMounted } from "@vueuse/core";
|
|
||||||
import { useId } from "reka-ui";
|
|
||||||
import { type Component, computed, ref } from "vue";
|
|
||||||
import { cn } from "@/lib/utils";
|
|
||||||
import { ChartCrosshair, ChartLegend, defaultColors } from "../chart";
|
|
||||||
|
|
||||||
const props = withDefaults(
|
|
||||||
defineProps<
|
|
||||||
BaseChartProps<T> & {
|
|
||||||
/**
|
|
||||||
* Render custom tooltip component.
|
|
||||||
*/
|
|
||||||
customTooltip?: Component;
|
|
||||||
/**
|
|
||||||
* Type of curve
|
|
||||||
*/
|
|
||||||
curveType?: CurveType;
|
|
||||||
/**
|
|
||||||
* Controls the visibility of gradient.
|
|
||||||
* @default true
|
|
||||||
*/
|
|
||||||
showGradiant?: boolean;
|
|
||||||
}
|
|
||||||
>(),
|
|
||||||
{
|
|
||||||
curveType: CurveType.MonotoneX,
|
|
||||||
filterOpacity: 0.2,
|
|
||||||
margin: () => ({ top: 0, bottom: 0, left: 0, right: 0 }),
|
|
||||||
showXAxis: true,
|
|
||||||
showYAxis: true,
|
|
||||||
showTooltip: true,
|
|
||||||
showLegend: true,
|
|
||||||
showGridLine: true,
|
|
||||||
showGradiant: true,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
const emits = defineEmits<{
|
|
||||||
legendItemClick: [d: BulletLegendItemInterface, i: number];
|
|
||||||
}>();
|
|
||||||
|
|
||||||
type KeyOfT = Extract<keyof T, string>;
|
|
||||||
type Data = (typeof props.data)[number];
|
|
||||||
|
|
||||||
const chartRef = useId();
|
|
||||||
|
|
||||||
const index = computed(() => props.index as KeyOfT);
|
|
||||||
const colors = computed(() =>
|
|
||||||
props.colors?.length ? props.colors : defaultColors(props.categories.length),
|
|
||||||
);
|
|
||||||
|
|
||||||
const legendItems = ref<BulletLegendItemInterface[]>(
|
|
||||||
props.categories.map((category, i) => ({
|
|
||||||
name: category,
|
|
||||||
color: colors.value[i],
|
|
||||||
inactive: false,
|
|
||||||
})),
|
|
||||||
);
|
|
||||||
|
|
||||||
const isMounted = useMounted();
|
|
||||||
|
|
||||||
function handleLegendItemClick(d: BulletLegendItemInterface, i: number) {
|
|
||||||
emits("legendItemClick", d, i);
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<template>
|
|
||||||
<div
|
|
||||||
:class="cn('w-full h-[400px] flex flex-col items-end', $attrs.class ?? '')"
|
|
||||||
>
|
|
||||||
<ChartLegend
|
|
||||||
v-if="showLegend"
|
|
||||||
v-model:items="legendItems"
|
|
||||||
@legend-item-click="handleLegendItemClick"
|
|
||||||
/>
|
|
||||||
|
|
||||||
<VisXYContainer
|
|
||||||
:style="{ height: isMounted ? '100%' : 'auto' }"
|
|
||||||
:margin="{ left: 20, right: 20 }"
|
|
||||||
:data="data"
|
|
||||||
>
|
|
||||||
<svg width="0" height="0">
|
|
||||||
<defs>
|
|
||||||
<linearGradient
|
|
||||||
v-for="(color, i) in colors"
|
|
||||||
:id="`${chartRef}-color-${i}`"
|
|
||||||
:key="i"
|
|
||||||
x1="0"
|
|
||||||
y1="0"
|
|
||||||
x2="0"
|
|
||||||
y2="1"
|
|
||||||
>
|
|
||||||
<template v-if="showGradiant">
|
|
||||||
<stop offset="5%" :stop-color="color" stop-opacity="0.4" />
|
|
||||||
<stop offset="95%" :stop-color="color" stop-opacity="0" />
|
|
||||||
</template>
|
|
||||||
<template v-else>
|
|
||||||
<stop offset="0%" :stop-color="color" />
|
|
||||||
</template>
|
|
||||||
</linearGradient>
|
|
||||||
</defs>
|
|
||||||
</svg>
|
|
||||||
|
|
||||||
<ChartCrosshair
|
|
||||||
v-if="showTooltip"
|
|
||||||
:colors="colors"
|
|
||||||
:items="legendItems"
|
|
||||||
:index="index"
|
|
||||||
:custom-tooltip="customTooltip"
|
|
||||||
/>
|
|
||||||
|
|
||||||
<template v-for="(category, i) in categories" :key="category">
|
|
||||||
<VisArea
|
|
||||||
:x="(d: Data, i: number) => i"
|
|
||||||
:y="(d: Data) => d[category]"
|
|
||||||
color="auto"
|
|
||||||
:curve-type="curveType"
|
|
||||||
:attributes="{
|
|
||||||
[Area.selectors.area]: {
|
|
||||||
fill: `url(#${chartRef}-color-${i})`,
|
|
||||||
},
|
|
||||||
}"
|
|
||||||
:opacity="
|
|
||||||
legendItems.find((item) => item.name === category)?.inactive
|
|
||||||
? filterOpacity
|
|
||||||
: 1
|
|
||||||
"
|
|
||||||
/>
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<template v-for="(category, i) in categories" :key="category">
|
|
||||||
<VisLine
|
|
||||||
:x="(d: Data, i: number) => i"
|
|
||||||
:y="(d: Data) => d[category]"
|
|
||||||
:color="colors[i]"
|
|
||||||
:curve-type="curveType"
|
|
||||||
:attributes="{
|
|
||||||
[Line.selectors.line]: {
|
|
||||||
opacity: legendItems.find((item) => item.name === category)
|
|
||||||
?.inactive
|
|
||||||
? filterOpacity
|
|
||||||
: 1,
|
|
||||||
},
|
|
||||||
}"
|
|
||||||
/>
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<VisAxis
|
|
||||||
v-if="showXAxis"
|
|
||||||
type="x"
|
|
||||||
:tick-format="xFormatter ?? ((v: number) => data[v]?.[index])"
|
|
||||||
:grid-line="false"
|
|
||||||
:tick-line="false"
|
|
||||||
tick-text-color="hsl(var(--vis-text-color))"
|
|
||||||
/>
|
|
||||||
<VisAxis
|
|
||||||
v-if="showYAxis"
|
|
||||||
type="y"
|
|
||||||
:tick-line="false"
|
|
||||||
:tick-format="yFormatter"
|
|
||||||
:domain-line="false"
|
|
||||||
:grid-line="showGridLine"
|
|
||||||
:attributes="{
|
|
||||||
[Axis.selectors.grid]: {
|
|
||||||
class: 'text-muted',
|
|
||||||
},
|
|
||||||
}"
|
|
||||||
tick-text-color="hsl(var(--vis-text-color))"
|
|
||||||
/>
|
|
||||||
|
|
||||||
<slot />
|
|
||||||
</VisXYContainer>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
@@ -1,74 +0,0 @@
|
|||||||
export { default as AreaChart } from "./AreaChart.vue";
|
|
||||||
|
|
||||||
import type { Spacing } from "@unovis/ts";
|
|
||||||
|
|
||||||
type KeyOf<T extends Record<string, any>> = Extract<keyof T, string>;
|
|
||||||
|
|
||||||
export interface BaseChartProps<T extends Record<string, any>> {
|
|
||||||
/**
|
|
||||||
* The source data, in which each entry is a dictionary.
|
|
||||||
*/
|
|
||||||
data: T[];
|
|
||||||
/**
|
|
||||||
* Select the categories from your data. Used to populate the legend and toolip.
|
|
||||||
*/
|
|
||||||
categories: KeyOf<T>[];
|
|
||||||
/**
|
|
||||||
* Sets the key to map the data to the axis.
|
|
||||||
*/
|
|
||||||
index: KeyOf<T>;
|
|
||||||
/**
|
|
||||||
* Change the default colors.
|
|
||||||
*/
|
|
||||||
colors?: string[];
|
|
||||||
/**
|
|
||||||
* Margin of each the container
|
|
||||||
*/
|
|
||||||
margin?: Spacing;
|
|
||||||
/**
|
|
||||||
* Change the opacity of the non-selected field
|
|
||||||
* @default 0.2
|
|
||||||
*/
|
|
||||||
filterOpacity?: number;
|
|
||||||
/**
|
|
||||||
* Function to format X label
|
|
||||||
*/
|
|
||||||
xFormatter?: (
|
|
||||||
tick: number | Date,
|
|
||||||
i: number,
|
|
||||||
ticks: number[] | Date[],
|
|
||||||
) => string;
|
|
||||||
/**
|
|
||||||
* Function to format Y label
|
|
||||||
*/
|
|
||||||
yFormatter?: (
|
|
||||||
tick: number | Date,
|
|
||||||
i: number,
|
|
||||||
ticks: number[] | Date[],
|
|
||||||
) => string;
|
|
||||||
/**
|
|
||||||
* Controls the visibility of the X axis.
|
|
||||||
* @default true
|
|
||||||
*/
|
|
||||||
showXAxis?: boolean;
|
|
||||||
/**
|
|
||||||
* Controls the visibility of the Y axis.
|
|
||||||
* @default true
|
|
||||||
*/
|
|
||||||
showYAxis?: boolean;
|
|
||||||
/**
|
|
||||||
* Controls the visibility of tooltip.
|
|
||||||
* @default true
|
|
||||||
*/
|
|
||||||
showTooltip?: boolean;
|
|
||||||
/**
|
|
||||||
* Controls the visibility of legend.
|
|
||||||
* @default true
|
|
||||||
*/
|
|
||||||
showLegend?: boolean;
|
|
||||||
/**
|
|
||||||
* Controls the visibility of gridline.
|
|
||||||
* @default true
|
|
||||||
*/
|
|
||||||
showGridLine?: boolean;
|
|
||||||
}
|
|
||||||
61
front/components/ui/chart/ChartContainer.vue
Normal file
61
front/components/ui/chart/ChartContainer.vue
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import type { HTMLAttributes } from 'vue'
|
||||||
|
import type { ChartConfig } from '.'
|
||||||
|
import { useId } from 'reka-ui'
|
||||||
|
import { computed, toRefs } from 'vue'
|
||||||
|
import { cn } from '@/lib/utils'
|
||||||
|
import { provideChartContext } from '.'
|
||||||
|
import ChartStyle from './ChartStyle.vue'
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
const props = defineProps<{
|
||||||
|
id?: HTMLAttributes['id']
|
||||||
|
class?: HTMLAttributes['class']
|
||||||
|
config: ChartConfig
|
||||||
|
cursor?: boolean
|
||||||
|
}>()
|
||||||
|
|
||||||
|
defineSlots<{
|
||||||
|
default: {
|
||||||
|
id: string
|
||||||
|
config: ChartConfig
|
||||||
|
}
|
||||||
|
}>()
|
||||||
|
|
||||||
|
const { config } = toRefs(props)
|
||||||
|
const uniqueId = useId()
|
||||||
|
const chartId = computed(() => `chart-${props.id || uniqueId.replace(/:/g, '')}`)
|
||||||
|
|
||||||
|
provideChartContext({
|
||||||
|
id: uniqueId,
|
||||||
|
config,
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div
|
||||||
|
data-slot="chart"
|
||||||
|
:data-chart="chartId"
|
||||||
|
:class="
|
||||||
|
cn(
|
||||||
|
`[&_.tick_text]:!fill-muted-foreground [&_.tick_line]:!stroke-border/50 [&_.recharts-curve.recharts-tooltip-cursor]:stroke-border [&_.recharts-polar-grid_[stroke='#ccc']]:stroke-border [&_.recharts-radial-bar-background-sector]:fill-muted [&_.recharts-rectangle.recharts-tooltip-cursor]:fill-muted [&_.recharts-reference-line_[stroke='#ccc']]:stroke-border flex flex-col aspect-video justify-center text-xs [&_.recharts-dot[stroke='#fff']]:stroke-transparent [&_.recharts-layer]:outline-hidden [&_.recharts-sector]:outline-hidden [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-surface]:outline-hidden [&_[data-vis-xy-container]]:h-full [&_[data-vis-single-container]]:h-full h-full [&_[data-vis-xy-container]]:w-full [&_[data-vis-single-container]]:w-full w-full `,
|
||||||
|
props.class
|
||||||
|
)
|
||||||
|
"
|
||||||
|
:style="{
|
||||||
|
'--vis-tooltip-padding': '0px',
|
||||||
|
'--vis-tooltip-background-color': 'transparent',
|
||||||
|
'--vis-tooltip-border-color': 'transparent',
|
||||||
|
'--vis-tooltip-text-color': 'none',
|
||||||
|
'--vis-tooltip-shadow-color': 'none',
|
||||||
|
'--vis-tooltip-backdrop-filter': 'none',
|
||||||
|
'--vis-crosshair-circle-stroke-color': '#0000',
|
||||||
|
'--vis-crosshair-line-stroke-width': cursor ? '1px' : '0px',
|
||||||
|
'--vis-font-family': 'var(--font-sans)',
|
||||||
|
}"
|
||||||
|
>
|
||||||
|
<slot :id="uniqueId" :config="config" />
|
||||||
|
<ChartStyle :id="chartId" />
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -1,51 +0,0 @@
|
|||||||
<script setup lang="ts">
|
|
||||||
import type { BulletLegendItemInterface } from "@unovis/ts";
|
|
||||||
import { omit } from "@unovis/ts";
|
|
||||||
import { VisCrosshair, VisTooltip } from "@unovis/vue";
|
|
||||||
import { type Component, createApp } from "vue";
|
|
||||||
import { ChartTooltip } from ".";
|
|
||||||
|
|
||||||
const props = withDefaults(
|
|
||||||
defineProps<{
|
|
||||||
colors: string[];
|
|
||||||
index: string;
|
|
||||||
items: BulletLegendItemInterface[];
|
|
||||||
customTooltip?: Component;
|
|
||||||
}>(),
|
|
||||||
{
|
|
||||||
colors: () => [],
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
// Use weakmap to store reference to each datapoint for Tooltip
|
|
||||||
const wm = new WeakMap();
|
|
||||||
function template(d: any) {
|
|
||||||
if (wm.has(d)) {
|
|
||||||
return wm.get(d);
|
|
||||||
} else {
|
|
||||||
const componentDiv = document.createElement("div");
|
|
||||||
const omittedData = Object.entries(omit(d, [props.index])).map(
|
|
||||||
([key, value]) => {
|
|
||||||
const legendReference = props.items.find((i) => i.name === key);
|
|
||||||
return { ...legendReference, value };
|
|
||||||
},
|
|
||||||
);
|
|
||||||
const TooltipComponent = props.customTooltip ?? ChartTooltip;
|
|
||||||
createApp(TooltipComponent, {
|
|
||||||
title: d[props.index].toString(),
|
|
||||||
data: omittedData,
|
|
||||||
}).mount(componentDiv);
|
|
||||||
wm.set(d, componentDiv.innerHTML);
|
|
||||||
return componentDiv.innerHTML;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function color(d: unknown, i: number) {
|
|
||||||
return props.colors[i] ?? "transparent";
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<template>
|
|
||||||
<VisTooltip :horizontal-shift="20" :vertical-shift="20" />
|
|
||||||
<VisCrosshair :template="template" :color="color" />
|
|
||||||
</template>
|
|
||||||
@@ -1,72 +0,0 @@
|
|||||||
<script setup lang="ts">
|
|
||||||
import type { BulletLegendItemInterface } from "@unovis/ts";
|
|
||||||
import { BulletLegend } from "@unovis/ts";
|
|
||||||
import { VisBulletLegend } from "@unovis/vue";
|
|
||||||
import { nextTick, onMounted, ref } from "vue";
|
|
||||||
import { buttonVariants } from "../button";
|
|
||||||
|
|
||||||
const props = withDefaults(
|
|
||||||
defineProps<{ items: BulletLegendItemInterface[] }>(),
|
|
||||||
{
|
|
||||||
items: () => [],
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
const emits = defineEmits<{
|
|
||||||
legendItemClick: [d: BulletLegendItemInterface, i: number];
|
|
||||||
"update:items": [payload: BulletLegendItemInterface[]];
|
|
||||||
}>();
|
|
||||||
|
|
||||||
const elRef = ref<HTMLElement>();
|
|
||||||
|
|
||||||
function keepStyling() {
|
|
||||||
const selector = `.${BulletLegend.selectors.item}`;
|
|
||||||
nextTick(() => {
|
|
||||||
const elements = elRef.value?.querySelectorAll(selector);
|
|
||||||
const classes = buttonVariants({ variant: "ghost", size: "sm" }).split(" ");
|
|
||||||
elements?.forEach((el) =>
|
|
||||||
el.classList.add(...classes, "!inline-flex", "!mr-2"),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
onMounted(() => {
|
|
||||||
keepStyling();
|
|
||||||
});
|
|
||||||
|
|
||||||
function onLegendItemClick(d: BulletLegendItemInterface, i: number) {
|
|
||||||
emits("legendItemClick", d, i);
|
|
||||||
const isBulletActive = !props.items[i].inactive;
|
|
||||||
const isFilterApplied = props.items.some((i) => i.inactive);
|
|
||||||
if (isFilterApplied && isBulletActive) {
|
|
||||||
// reset filter
|
|
||||||
emits(
|
|
||||||
"update:items",
|
|
||||||
props.items.map((item) => ({ ...item, inactive: false })),
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
// apply selection, set other item as inactive
|
|
||||||
emits(
|
|
||||||
"update:items",
|
|
||||||
props.items.map((item) =>
|
|
||||||
item.name === d.name
|
|
||||||
? { ...d, inactive: false }
|
|
||||||
: { ...item, inactive: true },
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
keepStyling();
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<template>
|
|
||||||
<div
|
|
||||||
ref="elRef"
|
|
||||||
class="w-max"
|
|
||||||
:style="{
|
|
||||||
'--vis-legend-bullet-size': '16px',
|
|
||||||
}"
|
|
||||||
>
|
|
||||||
<VisBulletLegend :items="items" :on-legend-item-click="onLegendItemClick" />
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
56
front/components/ui/chart/ChartLegendContent.vue
Normal file
56
front/components/ui/chart/ChartLegendContent.vue
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import type { HTMLAttributes } from 'vue'
|
||||||
|
import { computed, onMounted, ref } from 'vue'
|
||||||
|
import { cn } from '@/lib/utils'
|
||||||
|
import { useChart } from '.'
|
||||||
|
|
||||||
|
const props = withDefaults(
|
||||||
|
defineProps<{
|
||||||
|
hideIcon?: boolean
|
||||||
|
nameKey?: string
|
||||||
|
verticalAlign?: 'bottom' | 'top'
|
||||||
|
// payload?: any[]
|
||||||
|
class?: HTMLAttributes['class']
|
||||||
|
}>(),
|
||||||
|
{
|
||||||
|
verticalAlign: 'bottom',
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
const { id, config } = useChart()
|
||||||
|
|
||||||
|
const payload = computed(() =>
|
||||||
|
Object.entries(config.value).map(([key, value]) => {
|
||||||
|
return {
|
||||||
|
key: props.nameKey || key,
|
||||||
|
itemConfig: config.value[key],
|
||||||
|
}
|
||||||
|
})
|
||||||
|
)
|
||||||
|
|
||||||
|
const containerSelector = ref('')
|
||||||
|
onMounted(() => {
|
||||||
|
containerSelector.value = `[data-chart="chart-${id}"]>[data-vis-xy-container]`
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div v-if="containerSelector" :class="cn('flex items-center justify-center gap-4', verticalAlign === 'top' ? 'pb-3' : 'pt-3', props.class)">
|
||||||
|
<div
|
||||||
|
v-for="{ key, itemConfig } in payload"
|
||||||
|
:key="key"
|
||||||
|
:class="cn('[&>svg]:text-muted-foreground flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3')"
|
||||||
|
>
|
||||||
|
<component :is="itemConfig.icon" v-if="itemConfig?.icon" />
|
||||||
|
<div
|
||||||
|
v-else
|
||||||
|
class="h-2 w-2 shrink-0 rounded-[2px]"
|
||||||
|
:style="{
|
||||||
|
backgroundColor: itemConfig?.color,
|
||||||
|
}"
|
||||||
|
/>
|
||||||
|
|
||||||
|
{{ itemConfig?.label }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -1,74 +0,0 @@
|
|||||||
<script setup lang="ts">
|
|
||||||
import type { BulletLegendItemInterface } from "@unovis/ts";
|
|
||||||
import { omit } from "@unovis/ts";
|
|
||||||
import { VisTooltip } from "@unovis/vue";
|
|
||||||
import { type Component, createApp } from "vue";
|
|
||||||
import { ChartTooltip } from ".";
|
|
||||||
|
|
||||||
const props = defineProps<{
|
|
||||||
selector: string;
|
|
||||||
index: string;
|
|
||||||
items?: BulletLegendItemInterface[];
|
|
||||||
valueFormatter?: (tick: number, i?: number, ticks?: number[]) => string;
|
|
||||||
customTooltip?: Component;
|
|
||||||
}>();
|
|
||||||
|
|
||||||
// Use weakmap to store reference to each datapoint for Tooltip
|
|
||||||
const wm = new WeakMap();
|
|
||||||
function template(d: any, i: number, elements: (HTMLElement | SVGElement)[]) {
|
|
||||||
const valueFormatter = props.valueFormatter ?? ((tick: number) => `${tick}`);
|
|
||||||
if (props.index in d) {
|
|
||||||
if (wm.has(d)) {
|
|
||||||
return wm.get(d);
|
|
||||||
} else {
|
|
||||||
const componentDiv = document.createElement("div");
|
|
||||||
const omittedData = Object.entries(omit(d, [props.index])).map(
|
|
||||||
([key, value]) => {
|
|
||||||
const legendReference = props.items?.find((i) => i.name === key);
|
|
||||||
return { ...legendReference, value: valueFormatter(value) };
|
|
||||||
},
|
|
||||||
);
|
|
||||||
const TooltipComponent = props.customTooltip ?? ChartTooltip;
|
|
||||||
createApp(TooltipComponent, {
|
|
||||||
title: d[props.index],
|
|
||||||
data: omittedData,
|
|
||||||
}).mount(componentDiv);
|
|
||||||
wm.set(d, componentDiv.innerHTML);
|
|
||||||
return componentDiv.innerHTML;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
const data = d.data;
|
|
||||||
|
|
||||||
if (wm.has(data)) {
|
|
||||||
return wm.get(data);
|
|
||||||
} else {
|
|
||||||
const style = getComputedStyle(elements[i]);
|
|
||||||
const omittedData = [
|
|
||||||
{
|
|
||||||
name: data.name,
|
|
||||||
value: valueFormatter(data[props.index]),
|
|
||||||
color: style.fill,
|
|
||||||
},
|
|
||||||
];
|
|
||||||
const componentDiv = document.createElement("div");
|
|
||||||
const TooltipComponent = props.customTooltip ?? ChartTooltip;
|
|
||||||
createApp(TooltipComponent, {
|
|
||||||
title: d[props.index],
|
|
||||||
data: omittedData,
|
|
||||||
}).mount(componentDiv);
|
|
||||||
wm.set(d, componentDiv.innerHTML);
|
|
||||||
return componentDiv.innerHTML;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<template>
|
|
||||||
<VisTooltip
|
|
||||||
:horizontal-shift="20"
|
|
||||||
:vertical-shift="20"
|
|
||||||
:triggers="{
|
|
||||||
[selector]: template,
|
|
||||||
}"
|
|
||||||
/>
|
|
||||||
</template>
|
|
||||||
37
front/components/ui/chart/ChartStyle.vue
Normal file
37
front/components/ui/chart/ChartStyle.vue
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import type { HTMLAttributes } from 'vue'
|
||||||
|
import { Primitive } from 'reka-ui'
|
||||||
|
import { computed } from 'vue'
|
||||||
|
import { THEMES, useChart } from '.'
|
||||||
|
|
||||||
|
defineProps<{
|
||||||
|
id?: HTMLAttributes['id']
|
||||||
|
}>()
|
||||||
|
|
||||||
|
const { config } = useChart()
|
||||||
|
|
||||||
|
const colorConfig = computed(() => {
|
||||||
|
return Object.entries(config.value).filter(([, config]) => config.theme || config.color)
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<Primitive v-if="colorConfig.length" as="style">
|
||||||
|
{{
|
||||||
|
Object.entries(THEMES)
|
||||||
|
.map(
|
||||||
|
([theme, prefix]) => `
|
||||||
|
${prefix} [data-chart=${id}] {
|
||||||
|
${colorConfig
|
||||||
|
.map(([key, itemConfig]) => {
|
||||||
|
const color = itemConfig.theme?.[theme as keyof typeof itemConfig.theme] || itemConfig.color
|
||||||
|
return color ? ` --color-${key}: ${color};` : null
|
||||||
|
})
|
||||||
|
.join('\n')}
|
||||||
|
}
|
||||||
|
`
|
||||||
|
)
|
||||||
|
.join('\n')
|
||||||
|
}}
|
||||||
|
</Primitive>
|
||||||
|
</template>
|
||||||
@@ -1,40 +0,0 @@
|
|||||||
<script setup lang="ts">
|
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from "../card";
|
|
||||||
|
|
||||||
defineProps<{
|
|
||||||
title?: string;
|
|
||||||
data: {
|
|
||||||
name: string;
|
|
||||||
color: string;
|
|
||||||
value: any;
|
|
||||||
}[];
|
|
||||||
}>();
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<template>
|
|
||||||
<Card class="text-sm">
|
|
||||||
<CardHeader v-if="title" class="p-3 border-b">
|
|
||||||
<CardTitle>
|
|
||||||
{{ title }}
|
|
||||||
</CardTitle>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent class="p-3 min-w-[180px] flex flex-col gap-1">
|
|
||||||
<div v-for="(item, key) in data" :key="key" class="flex justify-between">
|
|
||||||
<div class="flex items-center">
|
|
||||||
<span class="w-2.5 h-2.5 mr-2">
|
|
||||||
<svg width="100%" height="100%" viewBox="0 0 30 30">
|
|
||||||
<path
|
|
||||||
d=" M 15 15 m -14, 0 a 14,14 0 1,1 28,0 a 14,14 0 1,1 -28,0"
|
|
||||||
:stroke="item.color"
|
|
||||||
:fill="item.color"
|
|
||||||
stroke-width="1"
|
|
||||||
/>
|
|
||||||
</svg>
|
|
||||||
</span>
|
|
||||||
<span>{{ item.name }}</span>
|
|
||||||
</div>
|
|
||||||
<span class="font-semibold ml-4">{{ item.value }}</span>
|
|
||||||
</div>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
</template>
|
|
||||||
110
front/components/ui/chart/ChartTooltipContent.vue
Normal file
110
front/components/ui/chart/ChartTooltipContent.vue
Normal file
@@ -0,0 +1,110 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import type { HTMLAttributes } from 'vue'
|
||||||
|
import type { ChartConfig } from '.'
|
||||||
|
import { computed } from 'vue'
|
||||||
|
import { cn } from '@/lib/utils'
|
||||||
|
|
||||||
|
const props = withDefaults(
|
||||||
|
defineProps<{
|
||||||
|
hideLabel?: boolean
|
||||||
|
hideIndicator?: boolean
|
||||||
|
indicator?: 'line' | 'dot' | 'dashed'
|
||||||
|
nameKey?: string
|
||||||
|
labelKey?: string
|
||||||
|
labelFormatter?: (d: number | Date) => string
|
||||||
|
valueFormatter?: (value: unknown, key: string) => string
|
||||||
|
payload?: Record<string, any>
|
||||||
|
config?: ChartConfig
|
||||||
|
class?: HTMLAttributes['class']
|
||||||
|
color?: string
|
||||||
|
x?: number | Date
|
||||||
|
}>(),
|
||||||
|
{
|
||||||
|
payload: () => ({}),
|
||||||
|
config: () => ({}),
|
||||||
|
indicator: 'dot',
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
// TODO: currently we use `createElement` and `render` to render the
|
||||||
|
// const chartContext = useChart(null)
|
||||||
|
|
||||||
|
const payload = computed(() => {
|
||||||
|
return Object.entries(props.payload)
|
||||||
|
.map(([key, value]) => {
|
||||||
|
// const key = `${props.nameKey || item.name || item.dataKey || "value"}`
|
||||||
|
const itemConfig = props.config[key]
|
||||||
|
const indicatorColor = props.config[key]?.color ?? props.payload.fill
|
||||||
|
|
||||||
|
return { key, value, itemConfig, indicatorColor }
|
||||||
|
})
|
||||||
|
.filter((i) => i.itemConfig)
|
||||||
|
})
|
||||||
|
|
||||||
|
const nestLabel = computed(() => Object.keys(props.payload).length === 1 && props.indicator !== 'dot')
|
||||||
|
const tooltipLabel = computed(() => {
|
||||||
|
if (props.hideLabel) return null
|
||||||
|
if (props.labelFormatter && props.x !== undefined) {
|
||||||
|
return props.labelFormatter(props.x)
|
||||||
|
}
|
||||||
|
return props.labelKey ? props.config[props.labelKey]?.label || props.payload[props.labelKey] : props.x
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div
|
||||||
|
:class="
|
||||||
|
cn('border-border/50 bg-background grid min-w-[8rem] items-start gap-1.5 rounded-lg border px-2.5 py-1.5 text-xs shadow-xl', props.class)
|
||||||
|
"
|
||||||
|
>
|
||||||
|
<slot>
|
||||||
|
<div v-if="!nestLabel && tooltipLabel" class="font-medium">
|
||||||
|
{{ tooltipLabel }}
|
||||||
|
</div>
|
||||||
|
<div class="grid gap-1.5">
|
||||||
|
<div
|
||||||
|
v-for="{ value, itemConfig, indicatorColor, key } in payload"
|
||||||
|
:key="key"
|
||||||
|
:class="
|
||||||
|
cn(
|
||||||
|
'[&>svg]:text-muted-foreground flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5',
|
||||||
|
indicator === 'dot' && 'items-center'
|
||||||
|
)
|
||||||
|
"
|
||||||
|
>
|
||||||
|
<component :is="itemConfig.icon" v-if="itemConfig?.icon" />
|
||||||
|
<template v-else-if="!hideIndicator">
|
||||||
|
<div
|
||||||
|
:class="
|
||||||
|
cn('shrink-0 rounded-[2px] border-(--color-border) bg-(--color-bg)', {
|
||||||
|
'h-2.5 w-2.5': indicator === 'dot',
|
||||||
|
'w-1': indicator === 'line',
|
||||||
|
'w-0 border-[1.5px] border-dashed bg-transparent': indicator === 'dashed',
|
||||||
|
'my-0.5': nestLabel && indicator === 'dashed',
|
||||||
|
})
|
||||||
|
"
|
||||||
|
:style="{
|
||||||
|
'--color-bg': indicatorColor,
|
||||||
|
'--color-border': indicatorColor,
|
||||||
|
}"
|
||||||
|
/>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<div :class="cn('flex flex-1 justify-between leading-none', nestLabel ? 'items-end' : 'items-center')">
|
||||||
|
<div class="grid gap-1.5">
|
||||||
|
<div v-if="nestLabel" class="font-medium">
|
||||||
|
{{ tooltipLabel }}
|
||||||
|
</div>
|
||||||
|
<span class="text-muted-foreground">
|
||||||
|
{{ itemConfig?.label || value }}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<span v-if="value" class="text-foreground font-mono font-medium tabular-nums">
|
||||||
|
{{ props.valueFormatter ? props.valueFormatter(value, key) : value.toLocaleString() }}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</slot>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -1,21 +1,26 @@
|
|||||||
export { default as ChartCrosshair } from "./ChartCrosshair.vue";
|
import type { Component, Ref } from 'vue'
|
||||||
export { default as ChartLegend } from "./ChartLegend.vue";
|
import { createContext } from 'reka-ui'
|
||||||
export { default as ChartSingleTooltip } from "./ChartSingleTooltip.vue";
|
|
||||||
export { default as ChartTooltip } from "./ChartTooltip.vue";
|
|
||||||
|
|
||||||
export function defaultColors(count: number = 3) {
|
export { default as ChartContainer } from './ChartContainer.vue'
|
||||||
const quotient = Math.floor(count / 2);
|
export { default as ChartLegendContent } from './ChartLegendContent.vue'
|
||||||
const remainder = count % 2;
|
export { default as ChartTooltipContent } from './ChartTooltipContent.vue'
|
||||||
|
export { componentToString } from './utils'
|
||||||
|
|
||||||
const primaryCount = quotient + remainder;
|
// Format: { THEME_NAME: CSS_SELECTOR }
|
||||||
const secondaryCount = quotient;
|
export const THEMES = { light: '', dark: '.dark' } as const
|
||||||
return [
|
|
||||||
...Array.from(new Array(primaryCount).keys()).map(
|
export type ChartConfig = {
|
||||||
(i) => `hsl(var(--vis-primary-color) / ${1 - (1 / primaryCount) * i})`,
|
[k in string]: {
|
||||||
),
|
label?: string | Component
|
||||||
...Array.from(new Array(secondaryCount).keys()).map(
|
icon?: string | Component
|
||||||
(i) =>
|
} & ({ color?: string; theme?: never } | { color?: never; theme: Record<keyof typeof THEMES, string> })
|
||||||
`hsl(var(--vis-secondary-color) / ${1 - (1 / secondaryCount) * i})`,
|
|
||||||
),
|
|
||||||
];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface ChartContextProps {
|
||||||
|
id: string
|
||||||
|
config: Ref<ChartConfig>
|
||||||
|
}
|
||||||
|
|
||||||
|
export const [useChart, provideChartContext] = createContext<ChartContextProps>('Chart')
|
||||||
|
|
||||||
|
export { VisCrosshair as ChartCrosshair, VisTooltip as ChartTooltip } from '@unovis/vue'
|
||||||
|
|||||||
42
front/components/ui/chart/utils.ts
Normal file
42
front/components/ui/chart/utils.ts
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
import type { ChartConfig } from '.'
|
||||||
|
import { isClient } from '@vueuse/core'
|
||||||
|
import { useId } from 'reka-ui'
|
||||||
|
import { h, render } from 'vue'
|
||||||
|
|
||||||
|
// Simple cache using a Map to store serialized object keys
|
||||||
|
const cache = new Map<string, string>()
|
||||||
|
|
||||||
|
// Convert object to a consistent string key
|
||||||
|
function serializeKey(key: Record<string, any>): string {
|
||||||
|
return JSON.stringify(key, Object.keys(key).sort())
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Constructor<P = any> {
|
||||||
|
__isFragment?: never
|
||||||
|
__isTeleport?: never
|
||||||
|
__isSuspense?: never
|
||||||
|
new (...args: any[]): {
|
||||||
|
$props: P
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function componentToString<P>(config: ChartConfig, component: Constructor<P>, props?: P) {
|
||||||
|
if (!isClient) return
|
||||||
|
|
||||||
|
// This function will be called once during mount lifecycle
|
||||||
|
const id = useId()
|
||||||
|
|
||||||
|
// https://unovis.dev/docs/auxiliary/Crosshair#component-props
|
||||||
|
return (_data: any, x: number | Date) => {
|
||||||
|
const data = 'data' in _data ? _data.data : _data
|
||||||
|
const serializedKey = `${id}-${serializeKey(data)}`
|
||||||
|
const cachedContent = cache.get(serializedKey)
|
||||||
|
if (cachedContent) return cachedContent
|
||||||
|
|
||||||
|
const vnode = h<unknown>(component, { ...props, payload: data, config, x })
|
||||||
|
const div = document.createElement('div')
|
||||||
|
render(vnode, div)
|
||||||
|
cache.set(serializedKey, div.innerHTML)
|
||||||
|
return div.innerHTML
|
||||||
|
}
|
||||||
|
}
|
||||||
89
front/components/ui/command/Command.vue
Normal file
89
front/components/ui/command/Command.vue
Normal file
@@ -0,0 +1,89 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import type { ListboxRootEmits, ListboxRootProps } from 'reka-ui'
|
||||||
|
import type { HTMLAttributes } from 'vue'
|
||||||
|
import { reactiveOmit } from '@vueuse/core'
|
||||||
|
import { ListboxRoot, useFilter, useForwardPropsEmits } from 'reka-ui'
|
||||||
|
import { reactive, ref, watch } from 'vue'
|
||||||
|
import { cn } from '@/lib/utils'
|
||||||
|
import { provideCommandContext } from '.'
|
||||||
|
|
||||||
|
const props = withDefaults(defineProps<ListboxRootProps & { class?: HTMLAttributes['class'] }>(), {
|
||||||
|
modelValue: '',
|
||||||
|
})
|
||||||
|
|
||||||
|
const emits = defineEmits<ListboxRootEmits>()
|
||||||
|
|
||||||
|
const delegatedProps = reactiveOmit(props, 'class')
|
||||||
|
|
||||||
|
const forwarded = useForwardPropsEmits(delegatedProps, emits)
|
||||||
|
|
||||||
|
const allItems = ref<Map<string, string>>(new Map())
|
||||||
|
const allGroups = ref<Map<string, Set<string>>>(new Map())
|
||||||
|
|
||||||
|
const { contains } = useFilter({ sensitivity: 'base' })
|
||||||
|
const filterState = reactive({
|
||||||
|
search: '',
|
||||||
|
filtered: {
|
||||||
|
/** The count of all visible items. */
|
||||||
|
count: 0,
|
||||||
|
/** Map from visible item id to its search score. */
|
||||||
|
items: new Map() as Map<string, number>,
|
||||||
|
/** Set of groups with at least one visible item. */
|
||||||
|
groups: new Set() as Set<string>,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
function filterItems() {
|
||||||
|
if (!filterState.search) {
|
||||||
|
filterState.filtered.count = allItems.value.size
|
||||||
|
// Do nothing, each item will know to show itself because search is empty
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reset the groups
|
||||||
|
filterState.filtered.groups = new Set()
|
||||||
|
let itemCount = 0
|
||||||
|
|
||||||
|
// Check which items should be included
|
||||||
|
for (const [id, value] of allItems.value) {
|
||||||
|
const score = contains(value, filterState.search)
|
||||||
|
filterState.filtered.items.set(id, score ? 1 : 0)
|
||||||
|
if (score) itemCount++
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check which groups have at least 1 item shown
|
||||||
|
for (const [groupId, group] of allGroups.value) {
|
||||||
|
for (const itemId of group) {
|
||||||
|
if (filterState.filtered.items.get(itemId)! > 0) {
|
||||||
|
filterState.filtered.groups.add(groupId)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
filterState.filtered.count = itemCount
|
||||||
|
}
|
||||||
|
|
||||||
|
watch(
|
||||||
|
() => filterState.search,
|
||||||
|
() => {
|
||||||
|
filterItems()
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
provideCommandContext({
|
||||||
|
allItems,
|
||||||
|
allGroups,
|
||||||
|
filterState,
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<ListboxRoot
|
||||||
|
data-slot="command"
|
||||||
|
v-bind="forwarded"
|
||||||
|
:class="cn('bg-popover text-popover-foreground flex h-full w-full flex-col overflow-hidden rounded-md', props.class)"
|
||||||
|
>
|
||||||
|
<slot />
|
||||||
|
</ListboxRoot>
|
||||||
|
</template>
|
||||||
36
front/components/ui/command/CommandDialog.vue
Normal file
36
front/components/ui/command/CommandDialog.vue
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import type { DialogRootEmits, DialogRootProps } from 'reka-ui'
|
||||||
|
import { useForwardPropsEmits } from 'reka-ui'
|
||||||
|
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||||
|
import Command from './Command.vue'
|
||||||
|
|
||||||
|
const props = withDefaults(
|
||||||
|
defineProps<
|
||||||
|
DialogRootProps & {
|
||||||
|
title?: string
|
||||||
|
description?: string
|
||||||
|
}
|
||||||
|
>(),
|
||||||
|
{
|
||||||
|
title: 'Command Palette',
|
||||||
|
description: 'Search for a command to run...',
|
||||||
|
}
|
||||||
|
)
|
||||||
|
const emits = defineEmits<DialogRootEmits>()
|
||||||
|
|
||||||
|
const forwarded = useForwardPropsEmits(props, emits)
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<Dialog v-slot="slotProps" v-bind="forwarded">
|
||||||
|
<DialogContent class="overflow-hidden p-0">
|
||||||
|
<DialogHeader class="sr-only">
|
||||||
|
<DialogTitle>{{ title }}</DialogTitle>
|
||||||
|
<DialogDescription>{{ description }}</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
<Command>
|
||||||
|
<slot v-bind="slotProps" />
|
||||||
|
</Command>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
</template>
|
||||||
22
front/components/ui/command/CommandEmpty.vue
Normal file
22
front/components/ui/command/CommandEmpty.vue
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import type { PrimitiveProps } from 'reka-ui'
|
||||||
|
import type { HTMLAttributes } from 'vue'
|
||||||
|
import { reactiveOmit } from '@vueuse/core'
|
||||||
|
import { Primitive } from 'reka-ui'
|
||||||
|
import { computed } from 'vue'
|
||||||
|
import { cn } from '@/lib/utils'
|
||||||
|
import { useCommand } from '.'
|
||||||
|
|
||||||
|
const props = defineProps<PrimitiveProps & { class?: HTMLAttributes['class'] }>()
|
||||||
|
|
||||||
|
const delegatedProps = reactiveOmit(props, 'class')
|
||||||
|
|
||||||
|
const { filterState } = useCommand()
|
||||||
|
const isRender = computed(() => !!filterState.search && filterState.filtered.count === 0)
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<Primitive v-if="isRender" data-slot="command-empty" v-bind="delegatedProps" :class="cn('py-6 text-center text-sm', props.class)">
|
||||||
|
<slot />
|
||||||
|
</Primitive>
|
||||||
|
</template>
|
||||||
46
front/components/ui/command/CommandGroup.vue
Normal file
46
front/components/ui/command/CommandGroup.vue
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import type { ListboxGroupProps } from 'reka-ui'
|
||||||
|
import type { HTMLAttributes } from 'vue'
|
||||||
|
import { reactiveOmit } from '@vueuse/core'
|
||||||
|
import { ListboxGroup, ListboxGroupLabel, useId } from 'reka-ui'
|
||||||
|
import { computed, onMounted, onUnmounted } from 'vue'
|
||||||
|
import { cn } from '@/lib/utils'
|
||||||
|
import { provideCommandGroupContext, useCommand } from '.'
|
||||||
|
|
||||||
|
const props = defineProps<
|
||||||
|
ListboxGroupProps & {
|
||||||
|
class?: HTMLAttributes['class']
|
||||||
|
heading?: string
|
||||||
|
}
|
||||||
|
>()
|
||||||
|
|
||||||
|
const delegatedProps = reactiveOmit(props, 'class')
|
||||||
|
|
||||||
|
const { allGroups, filterState } = useCommand()
|
||||||
|
const id = useId()
|
||||||
|
|
||||||
|
const isRender = computed(() => (!filterState.search ? true : filterState.filtered.groups.has(id)))
|
||||||
|
|
||||||
|
provideCommandGroupContext({ id })
|
||||||
|
onMounted(() => {
|
||||||
|
if (!allGroups.value.has(id)) allGroups.value.set(id, new Set())
|
||||||
|
})
|
||||||
|
onUnmounted(() => {
|
||||||
|
allGroups.value.delete(id)
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<ListboxGroup
|
||||||
|
v-bind="delegatedProps"
|
||||||
|
:id="id"
|
||||||
|
data-slot="command-group"
|
||||||
|
:class="cn('text-foreground overflow-hidden p-1', props.class)"
|
||||||
|
:hidden="isRender ? undefined : true"
|
||||||
|
>
|
||||||
|
<ListboxGroupLabel v-if="heading" data-slot="command-group-heading" class="px-2 py-1.5 text-xs font-medium text-muted-foreground">
|
||||||
|
{{ heading }}
|
||||||
|
</ListboxGroupLabel>
|
||||||
|
<slot />
|
||||||
|
</ListboxGroup>
|
||||||
|
</template>
|
||||||
43
front/components/ui/command/CommandInput.vue
Normal file
43
front/components/ui/command/CommandInput.vue
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import type { ListboxFilterProps } from 'reka-ui'
|
||||||
|
import type { HTMLAttributes } from 'vue'
|
||||||
|
import { reactiveOmit } from '@vueuse/core'
|
||||||
|
import { Search } from '@lucide/vue'
|
||||||
|
import { ListboxFilter, useForwardProps } from 'reka-ui'
|
||||||
|
import { cn } from '@/lib/utils'
|
||||||
|
import { useCommand } from '.'
|
||||||
|
|
||||||
|
defineOptions({
|
||||||
|
inheritAttrs: false,
|
||||||
|
})
|
||||||
|
|
||||||
|
const props = defineProps<
|
||||||
|
ListboxFilterProps & {
|
||||||
|
class?: HTMLAttributes['class']
|
||||||
|
}
|
||||||
|
>()
|
||||||
|
|
||||||
|
const delegatedProps = reactiveOmit(props, 'class')
|
||||||
|
|
||||||
|
const forwardedProps = useForwardProps(delegatedProps)
|
||||||
|
|
||||||
|
const { filterState } = useCommand()
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div data-slot="command-input-wrapper" class="flex h-9 items-center gap-2 border-b px-3">
|
||||||
|
<Search class="size-4 shrink-0 opacity-50" />
|
||||||
|
<ListboxFilter
|
||||||
|
v-bind="{ ...forwardedProps, ...$attrs }"
|
||||||
|
v-model="filterState.search"
|
||||||
|
data-slot="command-input"
|
||||||
|
auto-focus
|
||||||
|
:class="
|
||||||
|
cn(
|
||||||
|
'placeholder:text-muted-foreground flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden disabled:cursor-not-allowed disabled:opacity-50',
|
||||||
|
props.class
|
||||||
|
)
|
||||||
|
"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
80
front/components/ui/command/CommandItem.vue
Normal file
80
front/components/ui/command/CommandItem.vue
Normal file
@@ -0,0 +1,80 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import type { ListboxItemEmits, ListboxItemProps } from 'reka-ui'
|
||||||
|
import type { HTMLAttributes } from 'vue'
|
||||||
|
import { reactiveOmit, useCurrentElement } from '@vueuse/core'
|
||||||
|
import { ListboxItem, useForwardPropsEmits, useId } from 'reka-ui'
|
||||||
|
import { computed, onMounted, onUnmounted, ref } from 'vue'
|
||||||
|
import { cn } from '@/lib/utils'
|
||||||
|
import { useCommand, useCommandGroup } from '.'
|
||||||
|
|
||||||
|
const props = defineProps<ListboxItemProps & { class?: HTMLAttributes['class'] }>()
|
||||||
|
const emits = defineEmits<ListboxItemEmits>()
|
||||||
|
|
||||||
|
const delegatedProps = reactiveOmit(props, 'class')
|
||||||
|
|
||||||
|
const forwarded = useForwardPropsEmits(delegatedProps, emits)
|
||||||
|
|
||||||
|
const id = useId()
|
||||||
|
const { filterState, allItems, allGroups } = useCommand()
|
||||||
|
const groupContext = useCommandGroup()
|
||||||
|
|
||||||
|
const isRender = computed(() => {
|
||||||
|
if (!filterState.search) {
|
||||||
|
return true
|
||||||
|
} else {
|
||||||
|
const filteredCurrentItem = filterState.filtered.items.get(id)
|
||||||
|
// If the filtered items is undefined means not in the all times map yet
|
||||||
|
// Do the first render to add into the map
|
||||||
|
if (filteredCurrentItem === undefined) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check with filter
|
||||||
|
return filteredCurrentItem > 0
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
const itemRef = ref()
|
||||||
|
const currentElement = useCurrentElement(itemRef)
|
||||||
|
onMounted(() => {
|
||||||
|
if (!(currentElement.value instanceof HTMLElement)) return
|
||||||
|
|
||||||
|
// textValue to perform filter
|
||||||
|
allItems.value.set(id, currentElement.value.textContent ?? props.value?.toString() ?? '')
|
||||||
|
|
||||||
|
const groupId = groupContext?.id
|
||||||
|
if (groupId) {
|
||||||
|
if (!allGroups.value.has(groupId)) {
|
||||||
|
allGroups.value.set(groupId, new Set([id]))
|
||||||
|
} else {
|
||||||
|
allGroups.value.get(groupId)?.add(id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
onUnmounted(() => {
|
||||||
|
allItems.value.delete(id)
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<ListboxItem
|
||||||
|
v-if="isRender"
|
||||||
|
v-bind="forwarded"
|
||||||
|
:id="id"
|
||||||
|
ref="itemRef"
|
||||||
|
data-slot="command-item"
|
||||||
|
:class="
|
||||||
|
cn(
|
||||||
|
'data-[highlighted]:bg-accent data-[highlighted]:text-accent-foreground [&_svg:not([class*=\'text-\'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*=\'size-\'])]:size-4',
|
||||||
|
props.class
|
||||||
|
)
|
||||||
|
"
|
||||||
|
@select="
|
||||||
|
() => {
|
||||||
|
filterState.search = ''
|
||||||
|
}
|
||||||
|
"
|
||||||
|
>
|
||||||
|
<slot />
|
||||||
|
</ListboxItem>
|
||||||
|
</template>
|
||||||
25
front/components/ui/command/CommandList.vue
Normal file
25
front/components/ui/command/CommandList.vue
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import type { ListboxContentProps } from 'reka-ui'
|
||||||
|
import type { HTMLAttributes } from 'vue'
|
||||||
|
import { reactiveOmit } from '@vueuse/core'
|
||||||
|
import { ListboxContent, useForwardProps } from 'reka-ui'
|
||||||
|
import { cn } from '@/lib/utils'
|
||||||
|
|
||||||
|
const props = defineProps<ListboxContentProps & { class?: HTMLAttributes['class'] }>()
|
||||||
|
|
||||||
|
const delegatedProps = reactiveOmit(props, 'class')
|
||||||
|
|
||||||
|
const forwarded = useForwardProps(delegatedProps)
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<ListboxContent
|
||||||
|
data-slot="command-list"
|
||||||
|
v-bind="forwarded"
|
||||||
|
:class="cn('max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto', props.class)"
|
||||||
|
>
|
||||||
|
<div role="presentation">
|
||||||
|
<slot />
|
||||||
|
</div>
|
||||||
|
</ListboxContent>
|
||||||
|
</template>
|
||||||
17
front/components/ui/command/CommandSeparator.vue
Normal file
17
front/components/ui/command/CommandSeparator.vue
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import type { SeparatorProps } from 'reka-ui'
|
||||||
|
import type { HTMLAttributes } from 'vue'
|
||||||
|
import { reactiveOmit } from '@vueuse/core'
|
||||||
|
import { Separator } from 'reka-ui'
|
||||||
|
import { cn } from '@/lib/utils'
|
||||||
|
|
||||||
|
const props = defineProps<SeparatorProps & { class?: HTMLAttributes['class'] }>()
|
||||||
|
|
||||||
|
const delegatedProps = reactiveOmit(props, 'class')
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<Separator data-slot="command-separator" v-bind="delegatedProps" :class="cn('bg-border -mx-1 h-px', props.class)">
|
||||||
|
<slot />
|
||||||
|
</Separator>
|
||||||
|
</template>
|
||||||
14
front/components/ui/command/CommandShortcut.vue
Normal file
14
front/components/ui/command/CommandShortcut.vue
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import type { HTMLAttributes } from 'vue'
|
||||||
|
import { cn } from '@/lib/utils'
|
||||||
|
|
||||||
|
const props = defineProps<{
|
||||||
|
class?: HTMLAttributes['class']
|
||||||
|
}>()
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<span data-slot="command-shortcut" :class="cn('text-muted-foreground ml-auto text-xs tracking-widest', props.class)">
|
||||||
|
<slot />
|
||||||
|
</span>
|
||||||
|
</template>
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user