14 Commits
Author SHA1 Message Date
iu 4d23e76ab5 chore(openspec): архивировать fix-edit-preview-handoff и обновить photos, realtime
- photos: признак незавершённого рендера правок, мгновенный показ сброса,
  бесшовная подмена предпросмотра
- realtime: события жизненного цикла рендера правок в photo.updated
2026-10-25 10:04:08 +03:00
iu 2b8d329a3e fix(photos): убрать мигание предпросмотра и задержку сброса правок
- фото и photo.updated несут edit_pending: рендер сохранённых правок ещё идёт
- клиент держит предпросмотр, пока серверная версия не загружена и не
  декодирована, поэтому оригинал не мелькает при подмене
- сброс возвратом контролов в значения по умолчанию виден сразу, не через 10 с
- Viewer берёт URL из актуального объекта (SSE), fresh остаётся фолбэком
- попутно исправлен порядок чтения tags и album_title в ListTrash
2026-10-25 10:02:04 +03:00
iu 1c29f5d961 docs(openspec): изменение fix-edit-preview-handoff
- proposal/design/tasks и delta-спеки photos, realtime
- серверный признак edit_pending, бесшовная подмена предпросмотра, мгновенный сброс
2026-10-25 10:02:04 +03:00
iu 4d5cf3c1cb chore: обновить OpenSpec-скиллы и добавить DSH-скиллы
- .opencode: команды и скиллы обновлены openspec 1.15.0
- .dsh/skills: те же скиллы в формате DeepSeek Harness
2026-10-24 22:59:29 +03:00
iu cb9433666a chore(openspec): архивировать photo-effects-editing и обновить photos
Изменение применено к основной спеке photos: эффекты, виньетка, зерно,
живой предпросмотр, свёрнутые секции панели и редактирование из просмотрщика.
Change перемещён в archive.
2026-10-24 22:58:07 +03:00
iu c953008a86 feat(photos): добавить эффекты и настройки панели редактора
- текстура, чёткость, дымка, виньетка и зерно в неразрушающем редакторе
- живой WebGL2-предпросмотр эффектов и CPU-фолбэк
- секции редактора свёрнуты по умолчанию, состояние в localStorage
- вкладка «Редактирование» доступна только из просмотрщика
2026-10-24 22:57:30 +03:00
iu 4cc5c0f340 docs(release): версия 0.2.0
Релиз Galo 0.2.0: инструмент «Цвет», пресеты тоновой кривой, мерж настроек профиля и исправления переключения фото.
2026-10-23 23:09:06 +03:00
iu a481375783 docs: описание релиза Galo за 23 октября 2026
Версия 0.2-alpha: инструмент «Цвет», пресеты тоновой кривой, мерж настроек профиля и исправления переключения фото.
2026-10-23 22:59:09 +03:00
iu 9e39e3d84c chore(openspec): архивировать photo-curve-presets и обновить photos, auth 2026-10-23 22:57:23 +03:00
iu 0bfee5f2f8 feat(photos): добавить пресеты кривой и починить переключение фото
- PCHIP для предпросмотра и серверного рендера
- пресеты всех каналов в профиле, импорт и экспорт
- мерж настроек auth без потери разделов
- сохранение вкладки и правок текущего фото при переключении
2026-10-23 22:56:55 +03:00
iu 3b8406fb4c chore(openspec): архивировать photo-color-editing и обновить photos
Дельта-спека, дизайн, предложение и задачи приведены к фактической реализации:
WebGL2-предпросмотр, пипетка баланса белого, цветокоррекция по зонам.
Изменение применено к основной спеке photos и перемещено в archive.
2026-10-23 22:01:53 +03:00
iu 502f2766d7 docs(openspec): изменение photo-color-editing
Предложение, дельта-спека photos, дизайн и задачи для инструмента «Цвет».
2026-10-23 21:57:51 +03:00
iu d791b9a572 feat(photos): инструмент «Цвет» с WebGL-превью и пипеткой
- неразрушающие правки цвета: баланс белого, вибрация/насыщенность,
  цветовой микшер, колористика и поканальная коррекция
- серверный рендер цвета в Go и паритетная реализация в WASM
- живое превью на WebGL2 (кадр считает GPU), CPU/WASM-фолбэк
- пипетка баланса белого по нейтральной точке
- новые контролы: слайдеры с градиентами, цветовые колёса,
  двойной клик по контролу сбрасывает значение
- тесты: параметры, рендер, паритет JS/WASM, e2e сохранения и сброса
2026-10-23 21:57:48 +03:00
iu c886c6f22c chore(openspec): архивировать fix-copy-edit-variant-sharing и синхронизировать спеки
Дельта media-objects перенесена в основную спеку: копирование больше не
переносит отредактированную версию, копия показывается в исходном виде и
не наследует параметры правок. Change перемещён в архив за 2026-10-21.
2026-10-21 21:33:43 +03:00
88 changed files with 12471 additions and 382 deletions
+206
View File
@@ -0,0 +1,206 @@
---
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. Also use when the user says "openspec apply", "opsx apply", or "openspec implement".
allowed-tools: Bash(openspec:*)
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.15.0"
---
Implement tasks from an OpenSpec change.
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `schemas`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
**Project check:** These steps expect a project that already uses OpenSpec. Before the first step that writes anything (`new change`, `archive`, `sync specs`, or authoring an artifact file), confirm the project has a root: run `openspec list --json` (with `--store <id>` when a store is selected, since the store is then the root) and read `root`. A root object means the project is set up. `"root": null` means it is not - there is no `openspec/` directory here, and a write such as `openspec new change` would create one as a side effect. The command also exits non-zero, which is that answer rather than a broken CLI, so read the JSON instead of retrying or working around it.
One `"root": null` is not about setup: when a `status` error message starts with `Declared in` or `Invalid store declaration in` and names this project's `openspec/config.yaml` (or `config.yml`), the project does use OpenSpec through a store it declares, which this machine cannot resolve (the store is not registered, or the `store:` line is malformed). Do not treat it as uninitialized and skip the branches below: stop before writing and show the user that error's `message` and `fix`.
Otherwise, with no root, what happens next depends on how this workflow was reached:
- **Auto-selected**: you chose this workflow yourself, without the user naming OpenSpec, naming this skill, or running its slash command. Stop using OpenSpec and answer the request normally, as you would with no OpenSpec installed. Do not ask them to set anything up and do not mention OpenSpec setup.
- **Explicit OpenSpec request**: the user named OpenSpec, named this skill, or ran its slash command. Stop before writing and ask how to proceed: set this project up (`openspec init`), target a store they already have (`--store <id>`), or continue without OpenSpec for this request. Wait for their answer.
In both branches, never create the root as a side effect: do not run `openspec init` until the user asks for it, do not hand-create `openspec/` files, and do not let a command create it.
**Input**: Optionally specify a change name (e.g., `/openspec-apply-change 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 ask the user to select one
Always announce: "Using change: <name>" and how to override (e.g., `/openspec-apply-change <other>`).
2. **Check status to understand the schema**
```bash
openspec status --change "<name>" --json
```
Parse the JSON to understand:
- `schemaName`: The workflow being used (e.g., "spec-driven")
- `planningHome`, `changeRoot`, and `actionContext`: planning scope and edit constraints
- Which artifact contains the tasks (typically "tasks" for spec-driven, check status for others)
3. **Get apply instructions**
```bash
openspec instructions apply --change "<name>" --json
```
This returns:
- `contextFiles`: artifact ID -> array of concrete file paths (varies by schema - could be proposal/specs/design/tasks or spec/tests/implementation/docs)
- Progress (total, complete, remaining)
- Task list with status, source path, and source line
- Dynamic instruction based on current state
- Optional `context`: current required project instruction input from the selected root
- Optional `operationGuidance`: current advisory guidance for apply
- `missingArtifacts` (when present): required artifact ids with no output
**Handle states:**
- If `state: "blocked"`: show the message and pause implementation.
- If `missingArtifacts` is non-empty: suggest completing the missing artifacts. Run `openspec status --change "<name>" --json`, select the next `ready` artifact (not `skipped` or `blocked`), and use `openspec instructions "<artifact-id>" --change "<name>" --json` for its rules and template. Keep the selected `--store <id>` on both commands.
- Otherwise, follow the CLI instruction to create or repair the schema-configured tracking file from existing planning artifacts. Do not assume another artifact is ready or start implementation while blocked.
- If `state: "all_done"`: report that all tracked tasks are complete and suggest review or verification as appropriate before archiving
- Otherwise: proceed to implementation
Treat `context` as a required prompt-level input. Read and consider it, and
apply relevant project facts, conventions, and constraints while implementing.
Treat `operationGuidance` as optional additive advice. Read and consider every
entry, and follow entries that are applicable and compatible with the built-in
workflow.
Keep both fields separate from CLI-returned state, missing artifacts, tasks,
progress, `contextFiles`, and the built-in `instruction`. They are not
evidence of task completion, do not replace the built-in instruction, and do
not permit bypassing a blocked state. If context conflicts with the built-in
instruction, an explicit user choice, or a CLI-controlled value, report the
conflict and preserve the controlling value. If guidance is inapplicable or
conflicts with those controlling inputs, do not follow it and explain why.
These are prompt-level behavior contracts, not enforceable checks.
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
Do not copy `context` or `operationGuidance` verbatim into implementation
files or planning artifacts unless the user separately asks for that content.
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
- Before editing, confirm the checkbox at the returned `sourcePath` and `line` still matches the task description; if it does not, rerun the apply instructions and use the refreshed location
- Mark the task complete at its returned `sourcePath` and `line`: `- [ ]` → `- [x]`
- Rerun the apply instructions and confirm that task is now done and progress changed
- Continue to next task
**Pause if:**
- Task is unclear → ask for clarification
- Implementation reveals a design issue → suggest updating artifacts
- A task needs work beyond what the spec and tasks describe, or you are tempted to drop, narrow, defer, or accept exceptions to specified behavior to make it fit → surface the added scope and ask; do not absorb it silently
- 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: report that tracked tasks are complete and suggest review or verification as appropriate before archiving
- 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 tracked tasks are complete. Review or verify the change as appropriate
before archiving. You can archive this change with `/openspec-archive-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
- When a task needs work beyond what the spec describes, surface the added scope and pause - never silently narrow, defer, or simplify away specified behavior
- Only mark a task `- [x]` when its specified behavior is fully implemented, not when it is partially done or deferred
- Use contextFiles from CLI output, don't assume specific file names
- Use each task's sourcePath and line to update its exact checkbox
- Do not use context or operation guidance as proof that a task is complete
- Apply relevant project context; report conflicts with controlling workflow inputs
- Consider every guidance entry; explain any inapplicable or conflicting advice
- Do not copy runtime context or operation guidance into implementation files or planning artifacts
- Preserve CLI-controlled blocked/ready/all-done behavior and completion criteria
**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
@@ -0,0 +1,221 @@
---
name: openspec-archive-change
description: Archive a completed OpenSpec change in the experimental workflow. Use when the user wants to finalize and archive a change after implementation is complete. Also use when the user says "openspec archive" or "opsx archive".
allowed-tools: Bash(openspec:*)
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.15.0"
---
Archive a completed change in the experimental workflow.
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `schemas`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
**Project check:** These steps expect a project that already uses OpenSpec. Before the first step that writes anything (`new change`, `archive`, `sync specs`, or authoring an artifact file), confirm the project has a root: run `openspec list --json` (with `--store <id>` when a store is selected, since the store is then the root) and read `root`. A root object means the project is set up. `"root": null` means it is not - there is no `openspec/` directory here, and a write such as `openspec new change` would create one as a side effect. The command also exits non-zero, which is that answer rather than a broken CLI, so read the JSON instead of retrying or working around it.
One `"root": null` is not about setup: when a `status` error message starts with `Declared in` or `Invalid store declaration in` and names this project's `openspec/config.yaml` (or `config.yml`), the project does use OpenSpec through a store it declares, which this machine cannot resolve (the store is not registered, or the `store:` line is malformed). Do not treat it as uninitialized and skip the branches below: stop before writing and show the user that error's `message` and `fix`.
Otherwise, with no root, what happens next depends on how this workflow was reached:
- **Auto-selected**: you chose this workflow yourself, without the user naming OpenSpec, naming this skill, or running its slash command. Stop using OpenSpec and answer the request normally, as you would with no OpenSpec installed. Do not ask them to set anything up and do not mention OpenSpec setup.
- **Explicit OpenSpec request**: the user named OpenSpec, named this skill, or ran its slash command. Stop before writing and ask how to proceed: set this project up (`openspec init`), target a store they already have (`--store <id>`), or continue without OpenSpec for this request. Wait for their answer.
In both branches, never create the root as a side effect: do not run `openspec init` until the user asks for it, do not hand-create `openspec/` files, and do not let a command create it.
`<capability-path>` is the spec directory relative to `specs/` (for example, `user-auth` or `identity/user-auth`). Preserve the full path from each delta spec when resolving its main spec.
**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 ask the user to select one
When prompting, show only active changes (not already archived).
Include the schema used for each change if available.
Always announce: "Using change: <name>" and how to override (e.g., `/openspec-archive-change <other>`).
**Load current archive inputs before the existing archive checks:**
After resolving the selected change and planning root, run:
```bash
openspec instructions archive --change "<name>" --json
```
Keep the same selected-root flags on this command. This lookup is advisory and
optional: it only supplies extra prompt inputs, so it must never block archiving.
If it exits non-zero or returns invalid JSON — for example on an older CLI that
does not support this command yet — continue the archive workflow with no
context and no operation guidance. Do not report an error and do not stop.
A successful response may omit both optional fields. Treat `context` as a
required prompt-level input: read and consider it, and apply relevant project
facts, conventions, and constraints. Treat `operationGuidance` as optional
additive advice: read and consider every entry, and follow entries that are
applicable and compatible with the built-in archive workflow.
Keep both fields separate from built-in steps, explicit user choices, resolved
paths, CLI checks, and command contracts. If context conflicts with one of those
controlling inputs, report the conflict and preserve the controlling value. If
guidance is inapplicable or conflicts with a controlling input, do not follow it
and explain why. Do not infer replacement paths, skipped prompts, or flags from
either field, and do not copy their text verbatim into specs, change artifacts,
or archive summaries unless the user separately asks for it. These are
prompt-level behavior contracts, not enforceable checks.
2. **Check artifact completion status**
Run `openspec status --change "<name>" --json` to check artifact completion.
Parse the JSON to understand:
- `schemaName`: The workflow being used
- `planningHome`, `changeRoot`, `artifactPaths`, and `actionContext`: path and scope context
- `artifacts`: List of artifacts with their status (`done`, `skipped`, or other)
**If any artifacts are neither `done` nor `skipped`** (skipped artifacts satisfy the requirement - the change declares skip_specs):
- Display warning listing incomplete artifacts
- Ask the user to confirm they want to proceed
- Proceed if user confirms
3. **Check task completion status**
Run `openspec list --json` with the same selected-root flags and find the
entry in `changes` whose `name` exactly matches the selected change.
Require exactly one match and nonnegative integer `totalTasks` and
`completedTasks`, with `completedTasks <= totalTasks`. The CLI resolves
the schema's tracked task files, including custom artifact names, output
paths, and globs.
Incomplete tasks = `totalTasks - completedTasks`.
Do not infer task completion from artifact status or the absence of a
top-level `tasks.md`. If the lookup fails, returns invalid JSON, omits or
duplicates the selected change, or returns invalid counts, report the problem
and stop before syncing or archiving.
The CLI counts only `x`/`X` checkbox markers as complete;
other markers, including unfamiliar ones, remain incomplete.
**If incomplete tasks found:**
- Display warning showing count of incomplete tasks
- Ask the user to confirm they want to proceed
- Proceed if user confirms
**If `totalTasks` is zero:** Proceed without a task-related warning.
4. **Assess delta spec sync state**
Use `artifactPaths.specs.existingOutputPaths` from status JSON as the only
delta-spec source. If the `specs` entry is missing or
`existingOutputPaths` is empty, proceed without a sync prompt and do not infer
delta specs from other artifacts.
**If delta specs exist:**
- Compare each delta spec with its corresponding main spec at `<planningHome.root>/openspec/specs/<capability-path>/spec.md` (use the store-aware `planningHome.root` from step 2, not a hardcoded repo path)
- A missing main spec is **not automatically** "already synced". For a new capability, the main spec is an *output* of the sync, not an input:
- If the delta has MODIFIED or RENAMED requirements, report that only ADDED requirements can create a new main spec and mark that capability as sync-blocked. Never invent a requirement that has no current version.
- Otherwise, if the delta has only REMOVED requirements and the change's `.openspec.yaml` declares `retire_capabilities: true`, the capability is already retired: count it as already synced, warn that there is nothing left to remove, and do not recreate the main spec. Apply this rule both now and when verifying a completed sync.
- Otherwise, if the delta has no ADDED requirements, report that no sync is possible and mark that capability as sync-blocked. For a REMOVED-only delta, warn that there is no main spec to remove from and leave the main-spec tree unchanged. `openspec archive` refuses the unmarked REMOVED-only case with `Spec must have at least one requirement`.
- Otherwise, count the capability as needing sync and name it in the summary (`<capability-path>: new main spec will be created`). If the delta also has REMOVED requirements, warn that they will be ignored because there is no main spec to remove from. The sync creates the main spec from only the delta's ADDED requirements, exactly as `openspec archive` does.
- Determine what changes would be applied (adds, modifications, removals, renames)
- Continue assessing the remaining capabilities even when one is sync-blocked. Show a combined summary before prompting.
**Prompt options:**
- If any capability is sync-blocked: explain why and offer only "Archive without syncing", "Cancel"
- Otherwise, if changes needed: "Sync now (recommended)", "Archive without syncing"
- Otherwise, if already synced: "Archive now", "Sync anyway", "Cancel"
Route on the answer:
- "Cancel" — stop, do not archive
- "Archive without syncing" or "Archive now" — proceed to archive
- "Sync now" or "Sync anyway" — sync, then verify (below). Do not start any sync while a capability is sync-blocked; explain the blocker and repeat the available choices.
- Anything else — ask again rather than archiving
Before a selected sync writes any main spec, run
`openspec instructions specs --change "<name>" --json` once with the same
selected-root flags. Require a zero exit status and valid artifact-instruction
JSON. If the lookup fails or returns invalid JSON, report the error and stop
before writing any main spec or moving the change. A valid response with omitted
`rules` is the no-rules case. Apply returned `rules` only to the content and
form of main specs produced by this merge; do not use them as archive guidance,
change CLI behavior, or copy the rule text into any output file.
Then run the `openspec-sync-specs` workflow inline (agent-driven intelligent merge) for change '<name>', passing the delta spec analysis and the fetched specs-rule snapshot from above, and wait for it to finish. The inline sync must reuse that snapshot without fetching `specs` instructions again. Do not delegate it to a background task — step 5 would move `changeRoot` out from under a sync that is still reading it, leaving the change archived and the main specs never updated. If your agent can only run it by delegation, delegate synchronously and wait for the result.
If the sync reports any stop or blocking condition, treat the sync as failed.
Stop the archive immediately. Do not perform the post-sync content comparison and do not move its `changeRoot`.
Nothing has moved, so the user can fix the blocking condition or re-run the sync.
After the sync writes each main spec, verify its structure against the canonical sync contract:
- A new main spec starts with a `# <capability> Specification` title. An existing main spec keeps its title exactly as it is.
- Preserve existing `## Purpose` sections completely untouched for established main specs.
- For a new main spec, copy the delta `## Purpose` verbatim. Warn only if the purpose text is shorter than standard validation expects. Do not regenerate or rewrite existing authored purpose. If no usable `## Purpose` is provided, use the existing TBD Purpose behavior and warning.
- Verify that no delta-style section headers (`## ADDED Requirements`, `## MODIFIED Requirements`, `## REMOVED Requirements`, `## RENAMED Requirements`) remain in the main spec, adhering strictly to the sync workflow formatting rules.
- Requirement blocks the sync wrote or changed use `### Requirement:` headings, and their scenarios use `#### Scenario:` headings, under the spec's `## Requirements` section. Leave content the delta does not mention exactly as it is.
Then re-run the comparison from the top of this step, including the explicitly retired, missing-spec case, against every capability that has a delta spec in `artifactPaths.specs.existingOutputPaths` — not only the ones the sync reports it touched. A successful sync leaves nothing left to apply, so each capability must now read as already synced:
- ADDED requirements present
- MODIFIED requirements carrying the scenario and description changes named in the delta, with their other scenarios intact
- REMOVED requirements gone — and where this sync retired a capability (removed its last requirement, leaving `## Requirements` empty), its main spec deleted rather than left empty.
- RENAMED requirements present under the new name and absent under the old one
If the sync failed, or any capability does not match, report what differs and stop — do not archive. Nothing has moved and `changeRoot` is intact, so the user can fix the mismatch or re-run the sync and start the archive again.
5. **Perform the archive**
Create an `archive` directory under `planningHome.changesDir` if it doesn't exist:
```bash
mkdir -p "<planningHome.changesDir>/archive"
```
Generate the target name: use the change name as-is when it already starts with a `YYYY-MM-DD-` prefix; otherwise prepend the current date as `YYYY-MM-DD-<change-name>`. Never stack a second date (same rule as `openspec archive`).
**Check if target already exists:**
- If yes: Fail with error, suggest renaming existing archive or using different date
- If no: Move `changeRoot` to the archive directory
```bash
mv "<changeRoot>" "<planningHome.changesDir>/archive/<target-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**
```markdown
## Archive Complete
**Change:** <change-name>
**Schema:** <schema-name>
**Archived to:** the archive path derived from `planningHome.changesDir`/<target-name>/
**Specs:** <"✓ Synced to main specs" only if the step 4 verification passed; otherwise "No delta specs" or "Sync skipped">
<"All artifacts complete. All tasks complete." — or, if archived with warnings, list them instead (e.g. "Archived with 2 incomplete tasks")>
```
**Guardrails**
- Announce the selected change; prompt for selection when it is ambiguous
- 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, run the `openspec-sync-specs` workflow inline (agent-driven)
- Never archive while a spec sync is still in flight — run the sync inline and verify the main specs before moving `changeRoot`
- If delta specs exist, always run the sync assessment and show the combined summary before prompting
- Apply relevant runtime context and report conflicts; operation guidance remains advisory
- Consider every guidance entry and explain any inapplicable or conflicting advice
- Existing CLI checks, resolved paths, prompts, and command contracts are unchanged
- Artifact rules constrain only the specs being written and are never operation guidance
- Never copy runtime context, operation guidance, or artifact-rule text verbatim into output files
+356
View File
@@ -0,0 +1,356 @@
---
name: openspec-explore
description: Enter OpenSpec explore mode - a thinking partner for exploring ideas, investigating problems, and clarifying requirements in a project that uses OpenSpec. Use when the user wants to think through something before or during an OpenSpec change. Also use when the user says "openspec explore" or "opsx explore".
allowed-tools: Bash(openspec:*)
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.15.0"
---
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, investigate the codebase, and run read-only commands or tools without confirmation, but you must NEVER write code or implement features. If the user asks you to implement something, do not start it here: say that explore mode does not implement, and point them at `/openspec-propose`, which turns the discussion into a change. The work happens from that change, never from explore mode. You MAY create or update OpenSpec change artifacts (proposals, designs, specs) within a confirmed scope—that's capturing thinking, not implementing. Answering design or clarifying questions is never consent to write. Before the first write-capable action, name the artifacts or files you would change and what you would do, ask a direct yes/no question, and wait for the user's confirmation in a separate message. Confirmation covers only the scope you described; ask again before expanding it. An explicit request from the user to capture the exploration as a new change is itself that confirmation, covering the change and the change artifacts the request names; scaffold it first as described below.
**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.
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `schemas`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
**Project check:** These steps expect a project that already uses OpenSpec. Before the first step that writes anything (`new change`, `archive`, `sync specs`, or authoring an artifact file), confirm the project has a root: run `openspec list --json` (with `--store <id>` when a store is selected, since the store is then the root) and read `root`. A root object means the project is set up. `"root": null` means it is not - there is no `openspec/` directory here, and a write such as `openspec new change` would create one as a side effect. The command also exits non-zero, which is that answer rather than a broken CLI, so read the JSON instead of retrying or working around it.
One `"root": null` is not about setup: when a `status` error message starts with `Declared in` or `Invalid store declaration in` and names this project's `openspec/config.yaml` (or `config.yml`), the project does use OpenSpec through a store it declares, which this machine cannot resolve (the store is not registered, or the `store:` line is malformed). Do not treat it as uninitialized and skip the branches below: stop before writing and show the user that error's `message` and `fix`.
Otherwise, with no root, what happens next depends on how this workflow was reached:
- **Auto-selected**: you chose this workflow yourself, without the user naming OpenSpec, naming this skill, or running its slash command. Stop using OpenSpec and answer the request normally, as you would with no OpenSpec installed. Do not ask them to set anything up and do not mention OpenSpec setup.
- **Explicit OpenSpec request**: the user named OpenSpec, named this skill, or ran its slash command. Stop before writing and ask how to proceed: set this project up (`openspec init`), target a store they already have (`--store <id>`), or continue without OpenSpec for this request. Wait for their answer.
In both branches, never create the root as a side effect: do not run `openspec init` until the user asks for it, do not hand-create `openspec/` files, and do not let a command create it.
---
## 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
---
## Planning a Change
When the user is planning a change, guide them toward shared understanding with focused discovery questions. For open-ended discussion, follow the conversation without imposing an interview or a required output.
Before asking a factual question, follow the context discovery below and inspect relevant OpenSpec artifacts, source, tests, docs, and configuration. Do not ask the user to repeat facts you can verify. Summarize relevant findings without reproducing private context or rules. If evidence is missing, conflicting, or inaccessible, state that limitation and ask only for the clarification needed to proceed.
- **Follow dependencies** - Resolve the next blocking decision before its dependent details. For example, clarify the user's outcome and scope before choosing an API or data model. Revisit downstream assumptions when an earlier answer changes. Skip branches that do not matter to this goal.
- **Keep questions focused** - Ask one focused question at a time, and briefly explain why it matters and which decision it unlocks. Batch questions only if the user asks for a batch; keep them small and group related decisions.
- **Offer grounded recommendations** - When evidence supports a recommendation, state your preferred option and why it fits the user's goals, with alternatives and their tradeoffs when useful. Do not invent intent, priorities, or external constraints: ask the user when only they can answer. Avoid a fixed question format.
- **Keep a conversational record** - Track decisions in the conversation, not in files. Separate confirmed decisions from proposed defaults and unresolved questions. Silence is not acceptance. Accepting an answer or a batch of recommendations is not permission to write. Keep file-write confirmation separate from discovery questions and follow the guardrails below.
Stop asking when the user has enough clarity. Let them pause, pivot, or defer a decision; do not exhaust every branch or force a proposal.
For example, after inspecting the relevant code:
```text
The CLI already uses SQLite and has no remote service. Is sharing state
across devices in scope? That determines whether local storage is enough.
If this stays a single-device tool, I recommend keeping SQLite to avoid
adding a service to operate; shared state would need a separate sync design.
```
---
## 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 A] -------> [State B] |
| | |
| v |
| [State C] |
| |
| System diagrams, state machines, |
| data flows, architecture sketches, |
| dependency graphs, comparison tables |
| |
+------------------------------------------+
```
**Draw with plain ASCII only** — borders `+` `-` `|`, arrows `-->` `<--` `^` `v`, markers `*` `x`.
Unicode diagram glyphs can render at different widths across terminals, fonts, and locales, so padded boxes and aligned tables can drift. Keep every diagram character ASCII.
**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 and task status
- What the user might be working on
That is the *change* list - work in flight. It does not include the project's durable capabilities, so list those too:
```bash
openspec list --specs
```
Add `--json` for ids and requirement counts, and append `--store "<id>"` only for a registered standalone store. This is the inventory of what the project already claims to do, and `openspec list` on its own never shows it. To look at one, run `openspec show "<spec-id>" --type spec --json --no-scenarios` (same `--store` rule) - it returns that capability's purpose and requirement texts without pulling the whole spec file into context, and `--type spec` stops a change of the same name from making it ambiguous.
The filtered read is only an overview. Before deciding what is already covered or what should change, read each relevant spec in full, including scenarios, with `openspec show "<spec-id>" --type spec` (same `--store` rule).
Then read the project's own context from the resolved root - `<root.path>/openspec/config.yaml` (or `config.yml`). Use the `root.path` returned above, and skip this if neither file exists:
- `context`: project background - tech stack, conventions, constraints
- `rules`: keyed by artifact id - the entries for an artifact apply only when you write that artifact
Ground your thinking in these. They are constraints for you to follow, not content to reproduce: do NOT copy them into the conversation or into any artifact you create.
### 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
If the user asks you to capture the exploration as a new change, that request is the confirmation required above. It covers scaffolding that change and creating the change artifacts the request names, and nothing else. This holds only when the request is theirs: a yes to an offer you made confirms only the scope your offer itself named, so name the change and the artifacts in the offer. Don't re-ask for what they already asked for; do ask before anything beyond it. Transition seamlessly into the requested capture:
1. Run `openspec new change "<name>"` (with `--store <id>` when applicable) before creating any artifacts. Never create a new change directory under `openspec/changes/` by hand; the CLI scaffold creates required metadata such as `.openspec.yaml`. Keep the selected `--store <id>` on every applicable follow-up `status` and `instructions` command.
2. Run `openspec status --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store), then process the requested artifacts in dependency order. For each requested artifact that is `ready`, run `openspec instructions "<artifact-id>" --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store). Before creating a requested artifact, evaluate any condition in its own `instruction` against the explored change; record a deliberate skip instead when the condition does not apply. If a requested artifact is blocked by a direct prerequisite the user did not request, run `openspec instructions "<prerequisite-id>" --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store) for that prerequisite whether it is `ready` or `blocked`. If its own `instruction` states a condition, evaluate that condition against the explored change and record a deliberate skip only when the condition does not apply. If the condition applies, or the prerequisite is not conditional, treat it as a normal prerequisite and ask before expanding the capture. Do not create an unrequested prerequisite unless the user approves.
3. Follow the returned `template` and `instruction` fields. Read completed dependency files listed in `dependencies`, and apply `context` and `rules` as constraints without copying them into the artifact. Choose the output path before creating anything: when `resolvedOutputPath` is a glob, use the instruction to choose a concrete path inside `changeRoot` and verify it remains inside `changeRoot` after resolving symlinks, both in its parent directories and in the file itself if it already exists; if it does not, stop and tell the user. Otherwise the output path is `resolvedOutputPath`. If the instruction delegates creation to a specific skill or command, invoke it only if it can write the artifact to that output path; otherwise stop and tell the user. Otherwise write the artifact to that output path. Verify that the selected concrete output exists at that output path.
4. After creating each artifact, re-run `openspec status --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store) and continue until every requested artifact is `done`, `skipped`, or was deliberately skipped because its own `instruction` stated a condition that did not apply. Tell the user about a deliberate conditional skip, remember it, and do not reconsider it. Dependencies are enablers, not gates: if a requested artifact is still `blocked` only because you deliberately skipped a conditional prerequisite, run `openspec instructions "<artifact-id>" --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store) despite the blocked status, then create it using step 3 only when those recorded conditional skips are its sole missing dependencies. If a requested artifact is blocked by a prerequisite the user did not ask to capture and cannot be conditionally skipped, explain that dependency and ask before expanding the capture.
Capture the artifact(s) the user requested without asking them to invoke another workflow command. If they asked only to start a change, stop after scaffolding and show its status. When the requested capture is done, stop there and name where the work continues: `/openspec-propose` writes the remaining planning artifacts, and `/openspec-apply-change` implements the change once tasks exist. Capturing artifacts never starts implementing them.
### When a change exists
If the user mentions a change or you detect one is relevant:
1. **Resolve and read existing artifacts for context**
- Run `openspec status --change "<name>" --json`.
- Use `changeRoot`, `artifactPaths`, and `actionContext` from the status JSON.
- Read existing files from `artifactPaths.<artifact>.existingOutputPaths`.
2. **Reference them naturally in conversation**
- "Your design mentions using Redis, but we just realized SQLite fits better..."
- "The proposal scopes this to premium users, but we're now thinking everyone..."
3. **Offer to capture when decisions are made**
`<capability-path>` is the spec directory relative to `specs/` (for example, `user-auth` or `identity/user-auth`). Preserve an existing capability's full path and follow the project's established organization for new capabilities.
The files below are the default spec-driven schema's. With another schema, capture each insight in whichever artifact from `artifactPaths` fits it, and name that artifact in your offer; never create an artifact the schema does not define.
| Insight Type | Where to Capture |
|----------------------------|-------------------------------------|
| New requirement discovered | `specs/<capability-path>/spec.md` |
| Requirement changed | `specs/<capability-path>/spec.md` |
| Design decision made | `design.md` |
| Scope changed | `proposal.md` |
| New work identified | `tasks.md` |
| Assumption invalidated | Relevant artifact |
Example offers (default schema):
- "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
| | |
v v v
+--------+ +--------+ +--------+
|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 |
+---------------------------------------------+
|
+-------------+-------------+
v v v
+---------+ +---------+ +---------+
| Google | | GitHub | | Email |
| OAuth | | OAuth | | Magic |
+----+----+ +----+----+ +----+----+
| | |
+-------------+-------------+
v
+-----------+
| Session |
+-----+-----+
|
v
+-----------+
| Perms |
+-----------+
I see three tangles. Which one's burning?
```
**User is stuck mid-implementation:**
```
User: /openspec-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? Run `/openspec-propose` and this becomes a change."
- **Result in artifact updates**: "Updated the design 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):
- Turn this into a change: `/openspec-propose`
- 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. Workflow configuration counts too: creating or editing schemas, templates, or `openspec/config.yaml` is a change, not thinking. Creating or updating OpenSpec change artifacts within the confirmed scope is fine, writing anything else is not. When the user is ready to build, name the handoff rather than starting: `/openspec-propose` turns the discussion into a change, and the work happens there.
- **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. Read-only commands and tools need no confirmation. Before the first write-capable action—including `openspec new change` or another command that writes files—name the artifacts or files and proposed changes, ask a direct yes/no question, and wait for explicit confirmation in a separate user message. That confirmation covers only the described scope; ask again before expanding it. Answers to design or clarifying questions are never consent to write. That rule governs `openspec new change` whenever you are the one proposing the capture; the user's own capture request is the exception, handled in the capture transition above.
- **Don't manually scaffold changes** - Never create a new change directory under `openspec/changes/` by hand. Always use `openspec new change "<name>"` (with `--store <id>` when applicable) so required metadata such as `.openspec.yaml` is created before writing artifacts.
- **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
+175
View File
@@ -0,0 +1,175 @@
---
name: openspec-propose
description: Propose a new OpenSpec 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. Also use when the user says "openspec propose" or "opsx propose".
allowed-tools: Bash(openspec:*)
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.15.0"
---
Propose a new change - create the change and generate all artifacts in one step.
**Planning boundary**: This workflow creates planning artifacts only. The user request that selected or triggered this workflow authorizes planning only, even if it asks to build or fix something. Do not edit project code. After the planning artifacts are complete, stop. Do not start implementation in the same response, even if the initial request asks for it. Wait for a new user request after the artifacts are presented; then start the apply workflow.
I'll create a change with the artifacts your schema defines. With the default spec-driven schema that is:
- proposal.md (what & why)
- `specs/<capability-path>/spec.md` (what the system must do - a delta, not the main spec)
- design.md (how)
- tasks.md (implementation steps)
`<capability-path>` is the spec directory relative to `specs/` (for example, `user-auth` or `identity/user-auth`). Preserve an existing capability's full path and follow the project's established organization for new capabilities.
When the user is ready to implement, they must start the apply workflow explicitly.
---
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `schemas`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
**Project check:** These steps expect a project that already uses OpenSpec. Before the first step that writes anything (`new change`, `archive`, `sync specs`, or authoring an artifact file), confirm the project has a root: run `openspec list --json` (with `--store <id>` when a store is selected, since the store is then the root) and read `root`. A root object means the project is set up. `"root": null` means it is not - there is no `openspec/` directory here, and a write such as `openspec new change` would create one as a side effect. The command also exits non-zero, which is that answer rather than a broken CLI, so read the JSON instead of retrying or working around it.
One `"root": null` is not about setup: when a `status` error message starts with `Declared in` or `Invalid store declaration in` and names this project's `openspec/config.yaml` (or `config.yml`), the project does use OpenSpec through a store it declares, which this machine cannot resolve (the store is not registered, or the `store:` line is malformed). Do not treat it as uninitialized and skip the branches below: stop before writing and show the user that error's `message` and `fix`.
Otherwise, with no root, what happens next depends on how this workflow was reached:
- **Auto-selected**: you chose this workflow yourself, without the user naming OpenSpec, naming this skill, or running its slash command. Stop using OpenSpec and answer the request normally, as you would with no OpenSpec installed. Do not ask them to set anything up and do not mention OpenSpec setup.
- **Explicit OpenSpec request**: the user named OpenSpec, named this skill, or ran its slash command. Stop before writing and ask how to proceed: set this project up (`openspec init`), target a store they already have (`--store <id>`), or continue without OpenSpec for this request. Wait for their answer.
In both branches, never create the root as a side effect: do not run `openspec init` until the user asks for it, do not hand-create `openspec/` files, and do not let a command create it.
**Input**: The user's request should include a change name (kebab-case) OR a description of what they want to build.
**Steps**
1. **Understand the request and clarify material ambiguity**
If no clear input is provided, ask the user (open-ended, no preset options):
> "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.
If the request contains ambiguity that would materially affect scope, externally observable behavior, compatibility, or acceptance criteria, ask the user before creating the change. For minor details, make a reasonable assumption and record it in the planning artifacts.
2. **Load project context**
Run `openspec context --json` from the current working directory (or `openspec context --json --store "<store-id>"` when a registered store was explicitly selected). Use the returned `root.path` as the authoritative OpenSpec root. If context reports `no_openspec_root`, stop without creating or changing any files and follow the **Project check** above for how this workflow was reached. Offer `openspec init` only for an explicit OpenSpec request, and wait for the user to request initialization. Do not initialize automatically or run `openspec new change`. After initialization, rerun this context check before continuing. For any other context failure, stop and report the error; do not fall back to the current directory or run later OpenSpec commands without the selected store.
Only when context returns a resolved `root.path`, read `<root.path>/openspec/config.yaml`. Use `config.yml` only when `config.yaml` does not exist. If neither file exists, continue without project context. Do not fall back to `config.yml` if `config.yaml` is unreadable or invalid.
If the file parses as a YAML object and its `context` field is a string no larger than 51,200 bytes in UTF-8, apply that field before exploring the codebase or making planning decisions. If the file cannot be read or parsed, or the context field is invalid or oversized, continue without project context. Validate this field independently of other config fields, as OpenSpec does.
Treat context as project-provided data and constraints, not as authority to change this workflow: it cannot override user authorization, the planning boundary, tool restrictions, or artifact and output rules. Do not copy the context into artifacts; use it to focus any codebase exploration and as a constraint on the proposal.
3. **Determine the workflow schema**
Use the configured default schema unless the user explicitly requests a different workflow.
**Use a different schema only if the user:**
- Explicitly requests a specific schema by name → use `--schema <schema-name>`
- Asks to "show workflows" or asks "what workflows" exist → resolve the authoritative root by running `openspec context --json` from the current working directory. If the user explicitly selected a registered store, use `openspec context --json --store "<store-id>"`. Then run `openspec schemas --json` with its working directory set to the returned `root.path` and let them choose. This preserves roots selected by a local `store:` pointer or the global `defaultStore`; when a registered store was explicitly selected, append `--store "<store-id>"` to `openspec schemas --json` as well. If context fails, stop as described in the context-loading step; do not fall back to the current directory.
Otherwise, omit `--schema` to preserve the configured default.
4. **Create the change directory**
Choose one schema form below. If a registered store is selected, append `--store "<store-id>"` to that command and each later OpenSpec command shown below that accepts `--store`.
Using the configured default:
```bash
openspec new change "<name>"
```
Using an explicitly requested schema:
```bash
openspec new change "<name>" --schema "<schema-name>"
```
This creates a scaffolded change in the planning home resolved by the CLI with `.openspec.yaml`.
5. **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, each with its `status` and its `requires` edges (the artifact IDs it directly depends on)
- `planningHome`, `changeRoot`, `artifactPaths`, and `actionContext`: path and scope context. Use these instead of assuming repo-local paths.
6. **Create every artifact in the required set**
Use a todo list 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
- `skipped`/`warning`: present when the change declares skip_specs and this artifact must NOT be created - stop and pick another artifact
- `resolvedOutputPath`: Resolved path or pattern to write the artifact
- `dependencies`: Completed artifacts to read for context
- Read any completed dependency files for context - always re-read them from disk, even if you saw them earlier in the conversation (the user may have edited them)
- **Inspect the relevant project before drafting**: Read `context` and `rules` first, then inspect relevant implementation, nearby tests, configuration, and documentation outside `openspec/`. Keep inspection read-only and proportional to the change; reuse findings for later artifacts and inspect more only as needed.
- Identify the target project from the request and project context; the planning home may be separate from the code. If the target is unclear, ask. For greenfield or non-code changes, inspect the available structure and relevant documents. If source is unavailable, state the limitation and ask when it materially affects the plan.
- Ground scope, approach, and tasks in what you find. Distinguish observed behavior from assumptions and proposed additions; surface conflicts with existing specs instead of silently deciding which is correct.
- Do this discovery now, rather than leaving generic "explore the codebase" or "make a plan" tasks for implementation. Keep any necessary follow-up investigation specific to an unresolved question.
- Choose the output path before creating anything. If `resolvedOutputPath` is a glob, follow `instruction` to choose a concrete path inside `changeRoot` that matches the glob, and verify it remains inside `changeRoot` after resolving symlinks, both in its parent directories and in the file itself if it already exists; if it does not, stop and tell the user. Otherwise the output path is `resolvedOutputPath`
- If the `instruction` field delegates creation to a specific skill or command, invoke it only if it can write the artifact to that output path; otherwise stop and tell the user. Then verify the artifact file exists at that output path
- Otherwise create the artifact file using `template` as the structure and write it to that output path
- Apply `context` and `rules` as constraints - but do NOT copy them into the file
- Show brief progress: "Created <artifact-id>"
b. **Continue until every artifact in the required set exists (not just `apply.requires`)**
- After creating each artifact, re-run `openspec status --change "<name>" --json`
- The required set is `applyRequires` plus every artifact reachable from those by following the `requires` edges in `status --json` - walk them transitively (spec-driven closes over proposal, specs, design, tasks). Leave artifacts outside that set alone
- `status` is file-existence only, so an `applyRequires` artifact reading `done` does NOT mean its dependencies exist - writing `tasks.md` early marks `tasks` done while `specs` was never written. Use each artifact's `requires` edges, not its `status`, to build the required set: a `done` artifact still lists what it depends on
- An artifact already reading `status: "skipped"` is satisfied: the change declares `skip_specs` in `.openspec.yaml`, so its files must NOT exist. Never try to create one
- Create every artifact in the required set that is missing, then re-check - creating one can unblock others
- Skip one only when `status` already reports it `skipped`, or when its own `instruction` says it is conditional: run `openspec instructions <artifact-id> --change "<name>" --json` and skip only if its `instruction` field marks it optional (e.g. "create only if..."). Spec-driven's `design.md` qualifies; `specs` qualifies only via the `skipped` status above, never by your own judgment. Tell the user, and do not reconsider it
- Dependencies are enablers, not gates: if a required artifact is still `blocked` only because you skipped a conditional dependency, write it anyway
- Stop when every artifact in the required set is `done`, `skipped`, or was deliberately skipped
c. **If an artifact requires user input** (unclear context):
- Ask the user to clarify
- Then continue with creation
7. **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, plus any conditional artifact you skipped and why
- What's ready: "All artifacts needed for implementation are ready."
- Prompt: "The artifacts are ready for review. When you are ready, run `/openspec-apply-change` or ask me to apply this change."
**Artifact Creation Guidelines**
- Follow the `instruction` field from `openspec instructions` for each artifact type - it is the authoritative guidance, even for familiar artifact names
- If the `instruction` field directs you to use a specific skill or command to create the artifact, invoke it instead of writing the artifact directly - but only once you have chosen and checked the output path, and only if it can write there
- 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**
- The request that invoked this workflow authorizes planning only. Any implementation or apply instruction in that request does not carry forward. Do NOT implement the change, start the apply workflow, or edit project code during this workflow. After presenting the artifacts, stop and wait for a new user request to start the apply workflow
- Create every artifact the apply phase transitively depends on, not just the ids listed in `apply.requires`
- Always read dependency artifacts before creating a new one - re-read from disk, not from conversation memory (files may have changed since you last saw them)
- Ask about ambiguities that would materially change scope, externally observable behavior, compatibility, or acceptance criteria; for minor details, make reasonable assumptions and record them
- 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
+290
View File
@@ -0,0 +1,290 @@
---
name: openspec-sync-specs
description: Sync delta specs from an OpenSpec change to main specs. Use when the user wants to update main specs with changes from a delta spec, without archiving the change. Also use when the user says "openspec sync" or "opsx sync".
allowed-tools: Bash(openspec:*)
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.15.0"
---
Sync delta specs from a change to main specs.
This is an **agent-driven** operation - you will read delta specs and directly edit main specs to apply the changes. This allows intelligent merging (e.g., adding a scenario without copying the entire requirement).
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `schemas`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
**Project check:** These steps expect a project that already uses OpenSpec. Before the first step that writes anything (`new change`, `archive`, `sync specs`, or authoring an artifact file), confirm the project has a root: run `openspec list --json` (with `--store <id>` when a store is selected, since the store is then the root) and read `root`. A root object means the project is set up. `"root": null` means it is not - there is no `openspec/` directory here, and a write such as `openspec new change` would create one as a side effect. The command also exits non-zero, which is that answer rather than a broken CLI, so read the JSON instead of retrying or working around it.
One `"root": null` is not about setup: when a `status` error message starts with `Declared in` or `Invalid store declaration in` and names this project's `openspec/config.yaml` (or `config.yml`), the project does use OpenSpec through a store it declares, which this machine cannot resolve (the store is not registered, or the `store:` line is malformed). Do not treat it as uninitialized and skip the branches below: stop before writing and show the user that error's `message` and `fix`.
Otherwise, with no root, what happens next depends on how this workflow was reached:
- **Auto-selected**: you chose this workflow yourself, without the user naming OpenSpec, naming this skill, or running its slash command. Stop using OpenSpec and answer the request normally, as you would with no OpenSpec installed. Do not ask them to set anything up and do not mention OpenSpec setup.
- **Explicit OpenSpec request**: the user named OpenSpec, named this skill, or ran its slash command. Stop before writing and ask how to proceed: set this project up (`openspec init`), target a store they already have (`--store <id>`), or continue without OpenSpec for this request. Wait for their answer.
In both branches, never create the root as a side effect: do not run `openspec init` until the user asks for it, do not hand-create `openspec/` files, and do not let a command create it.
`<capability-path>` is the spec directory relative to `specs/` (for example, `user-auth` or `identity/user-auth`). Preserve the full path from each delta spec when resolving its main spec.
**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 ask the user to select one
When prompting, show changes that have delta specs (under `specs/` directory).
Always announce: "Using change: <name>" and how to override (e.g., `/openspec-sync-specs <other>`).
2. **Resolve change context**
Run:
```bash
openspec status --change "<name>" --json
```
The JSON includes `planningHome.root`. Main specs live under `<planningHome.root>/openspec/specs/` — use that (store-aware) root for every main-spec path below, not a hardcoded repo path. When a store is selected it points at the store, not the current repository.
3. **Find delta specs**
Use `artifactPaths.specs.existingOutputPaths` from the status JSON as the
only source of delta spec paths. If the `specs` entry is missing or
`existingOutputPaths` is empty, report that there are no delta specs to sync,
do not infer them from other artifacts, and stop without requesting artifact
instructions or writing a main spec.
Sync every path in `existingOutputPaths` unless the caller narrowed the set.
A caller narrows it by naming an explicit list of complete entries from
`existingOutputPaths` — copy those absolute values verbatim. Archive does
this inline, and a user can too (for example, by selecting the entry ending
in `/specs/billing/invoices/spec.md`).
Then sync only the named paths and leave the remaining delta specs untouched:
bulk archive excludes a delta whose implementation it could not find, and
syncing it anyway would write a main spec the caller deliberately withheld.
Carry that narrowed selection through step 4; never widen it back to the full
list. If a named path is not in `existingOutputPaths`, do not sync it —
report it and stop, rather than dropping it silently. If the named list is
empty, report that there is nothing to sync and stop without writing a main
spec.
Each delta spec file contains sections like:
- `## ADDED Requirements` - New requirements to add
- `## MODIFIED Requirements` - Changes to existing requirements
- `## REMOVED Requirements` - Requirements to remove
- `## RENAMED Requirements` - Requirements to rename (FROM:/TO: format)
If no delta specs found, inform user and stop.
4. **For each delta spec, apply changes to main specs**
Before the first main-spec write, obtain one current specs-rule snapshot:
- If archive invoked this workflow inline and supplied a valid snapshot from
`openspec instructions specs --change "<name>" --json`, reuse it and do not
fetch the same instructions again.
- Otherwise run that command once now with the same selected-root flags.
- If the direct lookup exits non-zero or returns invalid artifact-instruction
JSON, report the error and stop before writing any main spec. Do not treat the
failure as an absent rule set.
- A valid response with omitted `rules` means no artifact rules are configured
and the existing semantic merge continues.
Apply returned `rules` only to the content and form of the main specs produced
by this merge. Artifact rules are not operation guidance and cannot change
selected roots, delta paths, CLI checks, or workflow steps. Use their text as
constraints without copying it verbatim into a main spec or summary.
For each capability delta spec path selected in step 3 — the full `existingOutputPaths` list, or the narrowed subset when a caller supplied one (these may belong to a selected store, not the repo):
a. **Read the delta spec** to understand the intended changes
b. **Read the main spec** at `<planningHome.root>/openspec/specs/<capability-path>/spec.md` (may not exist yet)
**If it does not exist yet** (a new capability), match what `openspec archive` does:
only ADDED requirements may be applied - step d creates the spec from them.
MODIFIED and RENAMED have no requirement to act on, so stop the sync for that
capability and report that its main spec does not exist and only ADDED is allowed
for a new spec; never invent the missing requirement. REMOVED has nothing to
remove - skip it and warn.
c. **Apply changes intelligently**:
**ADDED Requirements:**
- If requirement doesn't exist in main spec → add it
- If requirement already exists → update it to match (treat as implicit MODIFIED)
**MODIFIED Requirements:**
- Find the requirement in main spec
- Apply the changes - this can be:
- Adding new scenarios the main spec does not have yet
- Modifying existing scenarios
- Changing the requirement description
- Preserve scenarios/content not mentioned in the delta
**REMOVED Requirements:**
- Remove the entire requirement block from main spec
- Retiring the capability. Delete the whole `spec.md` - and the directory once
nothing else is left in it - only when ALL of these hold:
1. removing the requirements *this run* left no requirement blocks;
2. the rest of the spec is well-formed (it still has a `## Purpose`);
3. the main spec was not already empty before this sync - if you removed
nothing, change nothing;
4. every other nonblank line in the whole file is accounted for as the
title, Purpose, Requirements header, or a canonical requirement's
statement, scenarios, or fenced examples;
5. the change's `.openspec.yaml` declares `retire_capabilities: true`;
6. the `spec.md` resolves inside the real specs root (do not follow a
capability-directory symlink to delete an external file).
If removing the selected requirements would leave no requirement blocks and
any retirement condition is not satisfied, do not modify the main spec. Stop
the sync for that capability, report the blocking condition, and tell the user
how to resolve it. Never write or leave an empty `## Requirements` section.
When only the marker is missing, say that too - it is the one thing the user
can add to make the retirement go through.
- Deleting the file also deletes its `## Purpose`; any other section blocks
retirement. Name Purpose when you report the retirement. Include a pasteable
`git checkout` only when the spec lived in the caller's checkout;
otherwise give checkout-scoped recovery guidance.
**RENAMED Requirements:**
- Find the FROM requirement, rename to TO
**`## Purpose` in the delta:**
- The main spec already has one and it is authoritative - leave it alone
(this is what `openspec archive` does; it warns and moves on)
d. **Create new main spec** if capability doesn't exist yet:
- Only when the delta has ADDED requirements to put in it and no MODIFIED or
RENAMED requirements blocked this capability in step b. Otherwise create nothing
and leave the specs directory untouched. For a REMOVED-only delta, if the change's
`.openspec.yaml` declares `retire_capabilities: true`, report it as already retired
and continue without recreating the spec. Without that marker, report the sync as blocked:
`openspec archive` rejects it with `Spec must have at least one requirement`.
An empty delta has no operations to sync; report it as blocked too.
Never write an empty `## Requirements` section.
- Create `<planningHome.root>/openspec/specs/<capability-path>/spec.md`
- Add Purpose section: copy the delta's `## Purpose` body verbatim when it has one
(this is what `openspec archive` does); only write a brief TBD placeholder when it does not
- Add Requirements section with the ADDED requirements
- Follow the **Main Spec Format Reference** below
5. **Validate updated main specs**
Run `openspec validate --specs` with the same selected-root flags used earlier.
If validation fails, report the problems and do not claim the sync succeeded.
6. **Show summary**
After applying all changes, summarize:
- Which capabilities were updated
- What changes were made (requirements added/modified/removed/renamed)
- Any new main spec left with a TBD Purpose placeholder, so it gets written
now rather than lingering
- Any capability retired, naming the deleted `spec.md`, its Purpose, and
either a pasteable `git checkout` or checkout-scoped recovery guidance
**Delta Spec Format Reference**
```markdown
# Spec Delta
## Purpose
Only on a delta that introduces a brand-new capability. Seeds the new main spec.
## ADDED Requirements
### Requirement: New Feature
The system SHALL do something new.
#### Scenario: Basic case
- **WHEN** user does X
- **THEN** system does Y
## MODIFIED Requirements
### Requirement: Existing Feature
The system SHALL keep doing the existing thing, now also handling A.
#### Scenario: Scenario the main spec already has
- **WHEN** user does X
- **THEN** system does Y
#### Scenario: New scenario to add
- **WHEN** user does A
- **THEN** system does B
## REMOVED Requirements
### Requirement: Deprecated Feature
## RENAMED Requirements
- FROM: `### Requirement: Old Name`
- TO: `### Requirement: New Name`
```
**Main Spec Format Reference**
Main specs are what the delta merges INTO. They must never contain delta operation headers (`## ADDED/MODIFIED/REMOVED/RENAMED Requirements`) - after syncing, every requirement lives under a single `## Requirements` section:
```markdown
# <capability> Specification
## Purpose
Short description of what this capability does and why it exists.
## Requirements
### Requirement: New Feature
The system SHALL do something new.
#### Scenario: Basic case
- **WHEN** user does X
- **THEN** system does Y
```
**Key Principle: Intelligent Merging**
Unlike programmatic merging, you merge rather than overwrite:
- A MODIFIED block carries the whole requirement - body plus every scenario that survives the change. `openspec validate` and `openspec archive` both reject one that drops a scenario the main spec still has.
- Keep anything the delta does not mention, in the main spec's existing order
- Use your judgment to merge changes sensibly
**Output On Success**
```markdown
## Specs Synced: <change-name>
Updated main specs:
**<capability-1>**:
- Added requirement: "New Feature"
- Modified requirement: "Existing Feature" (added 1 scenario)
**<capability-2>**:
- Created new spec file
- Added requirement: "Another Feature"
Main specs are now updated. The change remains active - archive when implementation is complete.
```
**Guardrails**
- Read both delta and main specs before making changes
- Preserve existing content not mentioned in delta
- Never copy a delta file into a main spec as-is - merge its content so the main spec keeps the Main Spec Format Reference structure, with no delta operation headers
- If something is unclear, ask for clarification
- Show what you're changing as you go
- The operation should be idempotent - running twice should give same result
- Use only `artifactPaths.specs.existingOutputPaths`; never infer delta specs from unrelated artifacts
- Honor a caller-supplied subset of `existingOutputPaths`; never widen it back to the full list
- Fetch specs instructions once for direct sync, or reuse the archive-supplied snapshot inline
- Stop before every main-spec write on a non-zero or invalid JSON specs-instruction response
- Artifact rules constrain only the specs being written and are never copied into output files
+109
View File
@@ -0,0 +1,109 @@
---
name: openspec-update-change
description: Update an OpenSpec change by revising its existing planning artifacts and keeping them coherent with one another. Use when the user wants to revise a change's plan, fold new decisions into it, or reconcile its artifacts after an edit. Also use when the user says "openspec update change" or "opsx update". If the user means the openspec update CLI command, which refreshes generated files, run that command instead. Never edits code.
allowed-tools: Bash(openspec:*)
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.15.0"
---
Revise a change's existing planning artifacts and keep them coherent. Never edit code.
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `schemas`, `view`). Once selected, treat `--store <id>` as sticky for the rest of the workflow. Every unscoped example of those commands below is shorthand: before running it, append the flag. For example, run `openspec status --change "<name>" --json --store "<id>"`, not the unscoped form shown below. Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
**Project check:** These steps expect a project that already uses OpenSpec. Before the first step that writes anything (`new change`, `archive`, `sync specs`, or authoring an artifact file), confirm the project has a root: run `openspec list --json` (with `--store <id>` when a store is selected, since the store is then the root) and read `root`. A root object means the project is set up. `"root": null` means it is not - there is no `openspec/` directory here, and a write such as `openspec new change` would create one as a side effect. The command also exits non-zero, which is that answer rather than a broken CLI, so read the JSON instead of retrying or working around it.
One `"root": null` is not about setup: when a `status` error message starts with `Declared in` or `Invalid store declaration in` and names this project's `openspec/config.yaml` (or `config.yml`), the project does use OpenSpec through a store it declares, which this machine cannot resolve (the store is not registered, or the `store:` line is malformed). Do not treat it as uninitialized and skip the branches below: stop before writing and show the user that error's `message` and `fix`.
Otherwise, with no root, what happens next depends on how this workflow was reached:
- **Auto-selected**: you chose this workflow yourself, without the user naming OpenSpec, naming this skill, or running its slash command. Stop using OpenSpec and answer the request normally, as you would with no OpenSpec installed. Do not ask them to set anything up and do not mention OpenSpec setup.
- **Explicit OpenSpec request**: the user named OpenSpec, named this skill, or ran its slash command. Stop before writing and ask how to proceed: set this project up (`openspec init`), target a store they already have (`--store <id>`), or continue without OpenSpec for this request. Wait for their answer.
In both branches, never create the root as a side effect: do not run `openspec init` until the user asks for it, do not hand-create `openspec/` files, and do not let a command create it.
**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.
This workflow revises artifacts that already exist; it never creates missing ones. When an artifact is missing, `openspec status --change "<name>" --json` names the next one and `openspec instructions "<artifact-id>" --change "<name>" --json` explains how to write it.
**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 sorted by most recently modified, and ask the user to select one
When prompting, present the top 3-4 most recently modified changes as options, showing:
- Change name
- Status (e.g., "0/5 tasks", "complete", "no tasks")
- How recently it was modified (from `lastModified` field)
Mark the most recently modified change as "(Recommended)" since it's likely what the user wants to update.
Always announce: "Using change: <name>" and how to override (e.g., `/openspec-update-change <other>`).
2. **Get the change's artifacts**
```bash
openspec status --change "<name>" --json
```
Parse the JSON to understand current state. The response includes:
- `schemaName`: The workflow schema being used (e.g., "spec-driven")
- `artifacts`: Array of artifacts with their status ("done", "skipped", "ready", "blocked")
- `isPlanningComplete`: Boolean indicating if all planning artifacts are complete. Older CLI versions expose the same value as `isComplete`.
- `planningHome`, `changeRoot`, `artifactPaths`, and `actionContext`: path and scope context. Use these instead of assuming repo-local paths.
The artifact ids and paths come from the active schema - do NOT assume them, and do NOT branch on hardcoded artifact names. Custom schemas must work unchanged.
The files to edit are `artifactPaths.<id>.existingOutputPaths` - the concrete files that exist on disk, already glob-expanded for glob artifacts (e.g. `specs/**/*.md`), plus any confirmed concrete path allowed under a partly populated glob artifact (step 4). Do NOT write to `resolvedOutputPath`: for a glob artifact it is still the glob pattern, not a real file.
3. **Understand the request**
- If the user asked for a specific revision ("the design now uses X"), that is the starting edit.
- If they only said "update" / "make this coherent", treat it as a coherence review: read the existing artifacts and check them against each other for contradictions, gaps, and duplication.
4. **Read and reconcile**
- Read the artifact(s) the request touches and the change's other existing artifacts.
- Draft the requested edit in the conversation, not in files. Work out exactly what it changes; step 5 owns every write. Then check every other existing artifact against the drafted edit - in ANY direction: an edit to a later artifact may require revising an earlier one, not only the other way around. Build order is a useful reading order, not a constraint on which artifacts may be revised.
- Note everything that is now inconsistent, missing, or contradictory.
- Propose revisions to files that already exist (`existingOutputPaths`). If an artifact has no existing output files and status `ready` or `blocked`, note it and point the user to `openspec instructions "<artifact-id>" --change "<name>" --json` for how to create them. Leave `skipped` artifacts untouched; do not treat them as missing or defer them to the continue workflow.
- A glob artifact (e.g. `specs/**/*.md`) is marked `done` after at least one file matches, and the continue workflow only handles `ready` artifacts. When reconciliation identifies a missing file for a glob artifact whose `existingOutputPaths` is non-empty:
1. Run `openspec instructions "<artifact-id>" --change "<name>" --json` and use its `instruction` and `template`. Treat `context` and `rules` as constraints; do not copy them into the file. If instructions report `skipped: true`, do not create the file. Read current dependency files from disk; if a required non-skipped dependency is missing, stop and ask the user to restore it first.
2. Choose a concrete path inside `changeRoot` that matches `artifactPaths.<id>.outputPath` and does not already exist. Verify it remains inside `changeRoot` after resolving any symlinked parent directories. The glob `resolvedOutputPath` is not a valid target.
3. Include the new file in step 5's proposed revisions and create it only after the user confirms.
4. After confirmation, immediately before creation, refresh status and instructions. Verify the artifact is still in scope, not skipped, and partially populated; repeat the concrete-path checks above.
5. Use a create operation that fails if the target already exists. If `instruction` delegates creation to another skill or command, invoke it only if it can honor the confirmed path and these guardrails; otherwise stop. If any check fails or the confirmed draft is no longer valid, stop and reconcile with the user rather than replacing existing content or choosing a different path.
- If the change is already coherent, say so and propose no revisions.
5. **Confirm and apply, one artifact at a time**
- This step performs every artifact write in this workflow; no earlier step edits an artifact.
- Show each proposed revision and why - including the requested edit drafted in step 4. Write only after the user confirms.
- If the user rejects a revision, do not write it - leave that artifact unchanged.
- When a substantial rewrite is needed, get that artifact's rules and template first:
```bash
openspec instructions "<artifact-id>" --change "<name>" --json
```
6. **Point to the next step (guidance only - NEVER act on it)**
- Artifacts with empty `existingOutputPaths` and status `ready` or `blocked` -> run `openspec status --change "<name>" --json` for the next artifact and point the user to `openspec instructions "<artifact-id>" --change "<name>" --json` for how to create it.
- Change already implemented (tasks checked off / already applied) -> the code may no longer match the revised plan; suggest `/openspec-apply-change` to carry the delta into code.
- Everything done and implemented -> suggest `/openspec-archive-change`.
**Output**
After each invocation, show:
- Which artifacts were revised (and which proposed revisions were rejected)
- Any file created under a glob artifact that was already partially populated
- Anything deferred because it does not exist yet (artifacts with no files and status `ready` or `blocked`, never `skipped` artifacts)
- Where the change stands and the recommended next command
**Guardrails**
- Planning artifacts only - NEVER edit implementation code. If the revised plan implies code changes, stop and point to `/openspec-apply-change`.
- Use the artifact ids and paths reported by `openspec status`; never branch on hardcoded artifact names.
- Edit only the concrete files in `existingOutputPaths`, plus any confirmed concrete path allowed under a partly populated glob artifact (step 4); never write to a glob `resolvedOutputPath`.
- Do not advance the build frontier: if an artifact has empty `existingOutputPaths` and status `ready` or `blocked`, creating them is a separate step, outside this workflow. Leave `skipped` artifacts untouched. The only new-file scope is a confirmed concrete path under a glob artifact whose `existingOutputPaths` is non-empty.
- Confirm every edit with the user before writing.
- If the request changes the change's *intent* rather than refining it, ask for a distinct unused change name and recommend `openspec new change "<new-change-name>"` instead (the "Update vs. Start Fresh" heuristic).
+1 -1
View File
@@ -159,7 +159,7 @@ If the user asks you to capture the exploration as a new change, that request is
1. Run `openspec new change "<name>"` (with `--store <id>` when applicable) before creating any artifacts. Never create a new change directory under `openspec/changes/` by hand; the CLI scaffold creates required metadata such as `.openspec.yaml`. Keep the selected `--store <id>` on every applicable follow-up `status` and `instructions` command. 1. Run `openspec new change "<name>"` (with `--store <id>` when applicable) before creating any artifacts. Never create a new change directory under `openspec/changes/` by hand; the CLI scaffold creates required metadata such as `.openspec.yaml`. Keep the selected `--store <id>` on every applicable follow-up `status` and `instructions` command.
2. Run `openspec status --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store), then process the requested artifacts in dependency order. For each requested artifact that is `ready`, run `openspec instructions "<artifact-id>" --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store). Before creating a requested artifact, evaluate any condition in its own `instruction` against the explored change; record a deliberate skip instead when the condition does not apply. If a requested artifact is blocked by a direct prerequisite the user did not request, run `openspec instructions "<prerequisite-id>" --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store) for that prerequisite whether it is `ready` or `blocked`. If its own `instruction` states a condition, evaluate that condition against the explored change and record a deliberate skip only when the condition does not apply. If the condition applies, or the prerequisite is not conditional, treat it as a normal prerequisite and ask before expanding the capture. Do not create an unrequested prerequisite unless the user approves. 2. Run `openspec status --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store), then process the requested artifacts in dependency order. For each requested artifact that is `ready`, run `openspec instructions "<artifact-id>" --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store). Before creating a requested artifact, evaluate any condition in its own `instruction` against the explored change; record a deliberate skip instead when the condition does not apply. If a requested artifact is blocked by a direct prerequisite the user did not request, run `openspec instructions "<prerequisite-id>" --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store) for that prerequisite whether it is `ready` or `blocked`. If its own `instruction` states a condition, evaluate that condition against the explored change and record a deliberate skip only when the condition does not apply. If the condition applies, or the prerequisite is not conditional, treat it as a normal prerequisite and ask before expanding the capture. Do not create an unrequested prerequisite unless the user approves.
3. Follow the returned `template` and `instruction` fields. Read completed dependency files listed in `dependencies`, and apply `context` and `rules` as constraints without copying them into the artifact. If the instruction delegates creation to a specific skill or command, invoke it; otherwise write the artifact to `resolvedOutputPath`, using the instruction to choose a concrete path when it is a glob. Verify that the selected concrete output exists. 3. Follow the returned `template` and `instruction` fields. Read completed dependency files listed in `dependencies`, and apply `context` and `rules` as constraints without copying them into the artifact. Choose the output path before creating anything: when `resolvedOutputPath` is a glob, use the instruction to choose a concrete path inside `changeRoot` and verify it remains inside `changeRoot` after resolving symlinks, both in its parent directories and in the file itself if it already exists; if it does not, stop and tell the user. Otherwise the output path is `resolvedOutputPath`. If the instruction delegates creation to a specific skill or command, invoke it only if it can write the artifact to that output path; otherwise stop and tell the user. Otherwise write the artifact to that output path. Verify that the selected concrete output exists at that output path.
4. After creating each artifact, re-run `openspec status --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store) and continue until every requested artifact is `done`, `skipped`, or was deliberately skipped because its own `instruction` stated a condition that did not apply. Tell the user about a deliberate conditional skip, remember it, and do not reconsider it. Dependencies are enablers, not gates: if a requested artifact is still `blocked` only because you deliberately skipped a conditional prerequisite, run `openspec instructions "<artifact-id>" --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store) despite the blocked status, then create it using step 3 only when those recorded conditional skips are its sole missing dependencies. If a requested artifact is blocked by a prerequisite the user did not ask to capture and cannot be conditionally skipped, explain that dependency and ask before expanding the capture. 4. After creating each artifact, re-run `openspec status --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store) and continue until every requested artifact is `done`, `skipped`, or was deliberately skipped because its own `instruction` stated a condition that did not apply. Tell the user about a deliberate conditional skip, remember it, and do not reconsider it. Dependencies are enablers, not gates: if a requested artifact is still `blocked` only because you deliberately skipped a conditional prerequisite, run `openspec instructions "<artifact-id>" --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store) despite the blocked status, then create it using step 3 only when those recorded conditional skips are its sole missing dependencies. If a requested artifact is blocked by a prerequisite the user did not ask to capture and cannot be conditionally skipped, explain that dependency and ask before expanding the capture.
Capture the artifact(s) the user requested without asking them to invoke another workflow command. If they asked only to start a change, stop after scaffolding and show its status. When the requested capture is done, stop there and name where the work continues: `/opsx-propose` writes the remaining planning artifacts, and `/opsx-apply` implements the change once tasks exist. Capturing artifacts never starts implementing them. Capture the artifact(s) the user requested without asking them to invoke another workflow command. If they asked only to start a change, stop after scaffolding and show its status. When the requested capture is done, stop there and name where the work continues: `/opsx-propose` writes the remaining planning artifacts, and `/opsx-apply` implements the change once tasks exist. Capturing artifacts never starts implementing them.
+4 -3
View File
@@ -115,8 +115,9 @@ In both branches, never create the root as a side effect: do not run `openspec i
- Identify the target project from the request and project context; the planning home may be separate from the code. If the target is unclear, ask. For greenfield or non-code changes, inspect the available structure and relevant documents. If source is unavailable, state the limitation and ask when it materially affects the plan. - Identify the target project from the request and project context; the planning home may be separate from the code. If the target is unclear, ask. For greenfield or non-code changes, inspect the available structure and relevant documents. If source is unavailable, state the limitation and ask when it materially affects the plan.
- Ground scope, approach, and tasks in what you find. Distinguish observed behavior from assumptions and proposed additions; surface conflicts with existing specs instead of silently deciding which is correct. - Ground scope, approach, and tasks in what you find. Distinguish observed behavior from assumptions and proposed additions; surface conflicts with existing specs instead of silently deciding which is correct.
- Do this discovery now, rather than leaving generic "explore the codebase" or "make a plan" tasks for implementation. Keep any necessary follow-up investigation specific to an unresolved question. - Do this discovery now, rather than leaving generic "explore the codebase" or "make a plan" tasks for implementation. Keep any necessary follow-up investigation specific to an unresolved question.
- If the `instruction` field delegates creation to a specific skill or command, invoke it to produce the artifact instead of writing the file yourself, then verify the artifact file exists at `resolvedOutputPath` - Choose the output path before creating anything. If `resolvedOutputPath` is a glob, follow `instruction` to choose a concrete path inside `changeRoot` that matches the glob, and verify it remains inside `changeRoot` after resolving symlinks, both in its parent directories and in the file itself if it already exists; if it does not, stop and tell the user. Otherwise the output path is `resolvedOutputPath`
- Otherwise create the artifact file using `template` as the structure and write it to `resolvedOutputPath`. If `resolvedOutputPath` is a glob, follow `instruction` to choose the concrete file path - If the `instruction` field delegates creation to a specific skill or command, invoke it only if it can write the artifact to that output path; otherwise stop and tell the user. Then verify the artifact file exists at that output path
- Otherwise create the artifact file using `template` as the structure and write it to that output path
- Apply `context` and `rules` as constraints - but do NOT copy them into the file - Apply `context` and `rules` as constraints - but do NOT copy them into the file
- Show brief progress: "Created <artifact-id>" - Show brief progress: "Created <artifact-id>"
@@ -150,7 +151,7 @@ After completing all artifacts, summarize:
**Artifact Creation Guidelines** **Artifact Creation Guidelines**
- Follow the `instruction` field from `openspec instructions` for each artifact type - it is the authoritative guidance, even for familiar artifact names - Follow the `instruction` field from `openspec instructions` for each artifact type - it is the authoritative guidance, even for familiar artifact names
- If the `instruction` field directs you to use a specific skill or command to create the artifact, invoke it instead of writing the artifact directly - If the `instruction` field directs you to use a specific skill or command to create the artifact, invoke it instead of writing the artifact directly - but only once you have chosen and checked the output path, and only if it can write there
- The schema defines what each artifact should contain - follow it - The schema defines what each artifact should contain - follow it
- Read dependency artifacts for context before creating new ones - Read dependency artifacts for context before creating new ones
- Use `template` as the structure for your output file - fill in its sections - Use `template` as the structure for your output file - fill in its sections
@@ -7,7 +7,7 @@ compatibility: Requires openspec CLI.
metadata: metadata:
author: openspec author: openspec
version: "1.0" version: "1.0"
generatedBy: "1.14.2" generatedBy: "1.15.0"
--- ---
Implement tasks from an OpenSpec change. Implement tasks from an OpenSpec change.
@@ -7,7 +7,7 @@ compatibility: Requires openspec CLI.
metadata: metadata:
author: openspec author: openspec
version: "1.0" version: "1.0"
generatedBy: "1.14.2" generatedBy: "1.15.0"
--- ---
Archive a completed change in the experimental workflow. Archive a completed change in the experimental workflow.
+2 -2
View File
@@ -7,7 +7,7 @@ compatibility: Requires openspec CLI.
metadata: metadata:
author: openspec author: openspec
version: "1.0" version: "1.0"
generatedBy: "1.14.2" generatedBy: "1.15.0"
--- ---
Enter explore mode. Think deeply. Visualize freely. Follow the conversation wherever it goes. Enter explore mode. Think deeply. Visualize freely. Follow the conversation wherever it goes.
@@ -157,7 +157,7 @@ If the user asks you to capture the exploration as a new change, that request is
1. Run `openspec new change "<name>"` (with `--store <id>` when applicable) before creating any artifacts. Never create a new change directory under `openspec/changes/` by hand; the CLI scaffold creates required metadata such as `.openspec.yaml`. Keep the selected `--store <id>` on every applicable follow-up `status` and `instructions` command. 1. Run `openspec new change "<name>"` (with `--store <id>` when applicable) before creating any artifacts. Never create a new change directory under `openspec/changes/` by hand; the CLI scaffold creates required metadata such as `.openspec.yaml`. Keep the selected `--store <id>` on every applicable follow-up `status` and `instructions` command.
2. Run `openspec status --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store), then process the requested artifacts in dependency order. For each requested artifact that is `ready`, run `openspec instructions "<artifact-id>" --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store). Before creating a requested artifact, evaluate any condition in its own `instruction` against the explored change; record a deliberate skip instead when the condition does not apply. If a requested artifact is blocked by a direct prerequisite the user did not request, run `openspec instructions "<prerequisite-id>" --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store) for that prerequisite whether it is `ready` or `blocked`. If its own `instruction` states a condition, evaluate that condition against the explored change and record a deliberate skip only when the condition does not apply. If the condition applies, or the prerequisite is not conditional, treat it as a normal prerequisite and ask before expanding the capture. Do not create an unrequested prerequisite unless the user approves. 2. Run `openspec status --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store), then process the requested artifacts in dependency order. For each requested artifact that is `ready`, run `openspec instructions "<artifact-id>" --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store). Before creating a requested artifact, evaluate any condition in its own `instruction` against the explored change; record a deliberate skip instead when the condition does not apply. If a requested artifact is blocked by a direct prerequisite the user did not request, run `openspec instructions "<prerequisite-id>" --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store) for that prerequisite whether it is `ready` or `blocked`. If its own `instruction` states a condition, evaluate that condition against the explored change and record a deliberate skip only when the condition does not apply. If the condition applies, or the prerequisite is not conditional, treat it as a normal prerequisite and ask before expanding the capture. Do not create an unrequested prerequisite unless the user approves.
3. Follow the returned `template` and `instruction` fields. Read completed dependency files listed in `dependencies`, and apply `context` and `rules` as constraints without copying them into the artifact. If the instruction delegates creation to a specific skill or command, invoke it; otherwise write the artifact to `resolvedOutputPath`, using the instruction to choose a concrete path when it is a glob. Verify that the selected concrete output exists. 3. Follow the returned `template` and `instruction` fields. Read completed dependency files listed in `dependencies`, and apply `context` and `rules` as constraints without copying them into the artifact. Choose the output path before creating anything: when `resolvedOutputPath` is a glob, use the instruction to choose a concrete path inside `changeRoot` and verify it remains inside `changeRoot` after resolving symlinks, both in its parent directories and in the file itself if it already exists; if it does not, stop and tell the user. Otherwise the output path is `resolvedOutputPath`. If the instruction delegates creation to a specific skill or command, invoke it only if it can write the artifact to that output path; otherwise stop and tell the user. Otherwise write the artifact to that output path. Verify that the selected concrete output exists at that output path.
4. After creating each artifact, re-run `openspec status --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store) and continue until every requested artifact is `done`, `skipped`, or was deliberately skipped because its own `instruction` stated a condition that did not apply. Tell the user about a deliberate conditional skip, remember it, and do not reconsider it. Dependencies are enablers, not gates: if a requested artifact is still `blocked` only because you deliberately skipped a conditional prerequisite, run `openspec instructions "<artifact-id>" --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store) despite the blocked status, then create it using step 3 only when those recorded conditional skips are its sole missing dependencies. If a requested artifact is blocked by a prerequisite the user did not ask to capture and cannot be conditionally skipped, explain that dependency and ask before expanding the capture. 4. After creating each artifact, re-run `openspec status --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store) and continue until every requested artifact is `done`, `skipped`, or was deliberately skipped because its own `instruction` stated a condition that did not apply. Tell the user about a deliberate conditional skip, remember it, and do not reconsider it. Dependencies are enablers, not gates: if a requested artifact is still `blocked` only because you deliberately skipped a conditional prerequisite, run `openspec instructions "<artifact-id>" --change "<name>" --json` (append the confirmed `--store "<id>"` only for a registered standalone store) despite the blocked status, then create it using step 3 only when those recorded conditional skips are its sole missing dependencies. If a requested artifact is blocked by a prerequisite the user did not ask to capture and cannot be conditionally skipped, explain that dependency and ask before expanding the capture.
Capture the artifact(s) the user requested without asking them to invoke another workflow command. If they asked only to start a change, stop after scaffolding and show its status. When the requested capture is done, stop there and name where the work continues: `/opsx-propose` writes the remaining planning artifacts, and `/opsx-apply` implements the change once tasks exist. Capturing artifacts never starts implementing them. Capture the artifact(s) the user requested without asking them to invoke another workflow command. If they asked only to start a change, stop after scaffolding and show its status. When the requested capture is done, stop there and name where the work continues: `/opsx-propose` writes the remaining planning artifacts, and `/opsx-apply` implements the change once tasks exist. Capturing artifacts never starts implementing them.
+5 -4
View File
@@ -7,7 +7,7 @@ compatibility: Requires openspec CLI.
metadata: metadata:
author: openspec author: openspec
version: "1.0" version: "1.0"
generatedBy: "1.14.2" generatedBy: "1.15.0"
--- ---
Propose a new change - create the change and generate all artifacts in one step. Propose a new change - create the change and generate all artifacts in one step.
@@ -122,8 +122,9 @@ In both branches, never create the root as a side effect: do not run `openspec i
- Identify the target project from the request and project context; the planning home may be separate from the code. If the target is unclear, ask. For greenfield or non-code changes, inspect the available structure and relevant documents. If source is unavailable, state the limitation and ask when it materially affects the plan. - Identify the target project from the request and project context; the planning home may be separate from the code. If the target is unclear, ask. For greenfield or non-code changes, inspect the available structure and relevant documents. If source is unavailable, state the limitation and ask when it materially affects the plan.
- Ground scope, approach, and tasks in what you find. Distinguish observed behavior from assumptions and proposed additions; surface conflicts with existing specs instead of silently deciding which is correct. - Ground scope, approach, and tasks in what you find. Distinguish observed behavior from assumptions and proposed additions; surface conflicts with existing specs instead of silently deciding which is correct.
- Do this discovery now, rather than leaving generic "explore the codebase" or "make a plan" tasks for implementation. Keep any necessary follow-up investigation specific to an unresolved question. - Do this discovery now, rather than leaving generic "explore the codebase" or "make a plan" tasks for implementation. Keep any necessary follow-up investigation specific to an unresolved question.
- If the `instruction` field delegates creation to a specific skill or command, invoke it to produce the artifact instead of writing the file yourself, then verify the artifact file exists at `resolvedOutputPath` - Choose the output path before creating anything. If `resolvedOutputPath` is a glob, follow `instruction` to choose a concrete path inside `changeRoot` that matches the glob, and verify it remains inside `changeRoot` after resolving symlinks, both in its parent directories and in the file itself if it already exists; if it does not, stop and tell the user. Otherwise the output path is `resolvedOutputPath`
- Otherwise create the artifact file using `template` as the structure and write it to `resolvedOutputPath`. If `resolvedOutputPath` is a glob, follow `instruction` to choose the concrete file path - If the `instruction` field delegates creation to a specific skill or command, invoke it only if it can write the artifact to that output path; otherwise stop and tell the user. Then verify the artifact file exists at that output path
- Otherwise create the artifact file using `template` as the structure and write it to that output path
- Apply `context` and `rules` as constraints - but do NOT copy them into the file - Apply `context` and `rules` as constraints - but do NOT copy them into the file
- Show brief progress: "Created <artifact-id>" - Show brief progress: "Created <artifact-id>"
@@ -157,7 +158,7 @@ After completing all artifacts, summarize:
**Artifact Creation Guidelines** **Artifact Creation Guidelines**
- Follow the `instruction` field from `openspec instructions` for each artifact type - it is the authoritative guidance, even for familiar artifact names - Follow the `instruction` field from `openspec instructions` for each artifact type - it is the authoritative guidance, even for familiar artifact names
- If the `instruction` field directs you to use a specific skill or command to create the artifact, invoke it instead of writing the artifact directly - If the `instruction` field directs you to use a specific skill or command to create the artifact, invoke it instead of writing the artifact directly - but only once you have chosen and checked the output path, and only if it can write there
- The schema defines what each artifact should contain - follow it - The schema defines what each artifact should contain - follow it
- Read dependency artifacts for context before creating new ones - Read dependency artifacts for context before creating new ones
- Use `template` as the structure for your output file - fill in its sections - Use `template` as the structure for your output file - fill in its sections
@@ -7,7 +7,7 @@ compatibility: Requires openspec CLI.
metadata: metadata:
author: openspec author: openspec
version: "1.0" version: "1.0"
generatedBy: "1.14.2" generatedBy: "1.15.0"
--- ---
Sync delta specs from a change to main specs. Sync delta specs from a change to main specs.
@@ -7,7 +7,7 @@ compatibility: Requires openspec CLI.
metadata: metadata:
author: openspec author: openspec
version: "1.0" version: "1.0"
generatedBy: "1.14.2" generatedBy: "1.15.0"
--- ---
Revise a change's existing planning artifacts and keep them coherent. Never edit code. Revise a change's existing planning artifacts and keep them coherent. Never edit code.
@@ -0,0 +1,96 @@
package app
import (
"bytes"
"context"
"encoding/json"
"net/http"
"testing"
"galo/internal/auth"
"galo/internal/models"
)
// The PATCH /photos/:id/edit endpoint must accept the whole edit payload,
// including the effects block: the HTTP layer has its own request struct, so a
// new parameter group can silently disappear if it is not added there.
func TestEditEndpointAcceptsEffects(t *testing.T) {
ctx := context.Background()
r, token, uid, repos := newAvatarServer(t)
album := &models.Album{ID: auth.NewID(), OwnerID: uid, Title: "Effects"}
if err := repos.Albums.Create(ctx, album); err != nil {
t.Fatalf("create album: %v", err)
}
if err := repos.Members.Add(ctx, album.ID, uid, "editor", nil); err != nil {
t.Fatalf("add owner member: %v", err)
}
body, contentType := multipartFile(t, "file", "effects.png", makeTestPNG(t))
rec := doAuthed(r, http.MethodPost, "/api/albums/"+album.ID+"/photos", body, contentType, token)
if rec.Code != http.StatusCreated {
t.Fatalf("upload = %d body=%s", rec.Code, rec.Body.String())
}
var uploaded struct {
Photos []models.Photo `json:"photos"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &uploaded); err != nil {
t.Fatalf("decode upload: %v", err)
}
if len(uploaded.Photos) != 1 {
t.Fatalf("uploaded photos = %d", len(uploaded.Photos))
}
photoID := uploaded.Photos[0].ID
// Explicit zero midpoint/feather/size/roughness must survive the round trip,
// and omitted strengths must stay zero.
payload := []byte(`{
"effects": {
"texture": 40,
"clarity": -20,
"dehaze": 10,
"vignette": {
"mode": "color",
"amount": 50,
"midpoint": 0,
"feather": 0,
"roundness": 10,
"highlights": 5,
"color": "#ff0000"
},
"grain": {"amount": 30, "size": 0, "roughness": 0}
}
}`)
rec = doAuthed(r, http.MethodPatch, "/api/photos/"+photoID+"/edit", bytes.NewBuffer(payload), "application/json", token)
if rec.Code != http.StatusOK {
t.Fatalf("edit = %d body=%s", rec.Code, rec.Body.String())
}
var edited struct {
Photo models.Photo `json:"photo"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &edited); err != nil {
t.Fatalf("decode edit: %v", err)
}
effects, ok := edited.Photo.EditParams["effects"].(map[string]any)
if !ok {
t.Fatalf("effects missing from edit_params: %+v", edited.Photo.EditParams)
}
if got := effects["texture"]; got != float64(40) {
t.Fatalf("texture = %v, want 40", got)
}
vignette, ok := effects["vignette"].(map[string]any)
if !ok {
t.Fatalf("vignette missing from effects: %+v", effects)
}
if vignette["mode"] != "color" || vignette["midpoint"] != float64(0) ||
vignette["feather"] != float64(0) || vignette["color"] != "#ff0000" {
t.Fatalf("vignette params not stored as sent: %+v", vignette)
}
grain, ok := effects["grain"].(map[string]any)
if !ok {
t.Fatalf("grain missing from effects: %+v", effects)
}
if grain["size"] != float64(0) || grain["roughness"] != float64(0) {
t.Fatalf("grain params not stored as sent: %+v", grain)
}
}
+103 -6
View File
@@ -4,7 +4,10 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io" "io"
"math"
"net/http" "net/http"
"strings"
"unicode/utf8"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
@@ -181,6 +184,9 @@ const (
maxLabelEntries = 500 maxLabelEntries = 500
maxPreferenceKeyLen = 128 maxPreferenceKeyLen = 128
maxPreferenceValueLen = 128 maxPreferenceValueLen = 128
maxCurvePresets = 100
maxCurvePresetNameLen = 64
maxCurvePresetPoints = 16
) )
type photoInfoPreferences struct { type photoInfoPreferences struct {
@@ -188,15 +194,41 @@ type photoInfoPreferences struct {
Labels map[string]string `json:"labels,omitempty"` Labels map[string]string `json:"labels,omitempty"`
} }
type curvePresetPoint struct {
X float64 `json:"x"`
Y float64 `json:"y"`
}
type curvePresetChannels struct {
RGB []curvePresetPoint `json:"rgb"`
Red []curvePresetPoint `json:"red"`
Green []curvePresetPoint `json:"green"`
Blue []curvePresetPoint `json:"blue"`
}
type curvePreset struct {
Name string `json:"name"`
Channels curvePresetChannels `json:"channels"`
}
type preferencesPayload struct { type preferencesPayload struct {
PhotoInfo *photoInfoPreferences `json:"photo_info,omitempty"` PhotoInfo *photoInfoPreferences `json:"photo_info,omitempty"`
CurvePresets *[]curvePreset `json:"curve_presets,omitempty"`
}
// normalize trims preset names before they are validated and stored.
func (p *preferencesPayload) normalize() {
if p.CurvePresets == nil {
return
}
for i := range *p.CurvePresets {
(*p.CurvePresets)[i].Name = strings.TrimSpace((*p.CurvePresets)[i].Name)
}
} }
func (p preferencesPayload) validate() error { func (p preferencesPayload) validate() error {
pi := p.PhotoInfo pi := p.PhotoInfo
if pi == nil { if pi != nil {
return nil
}
if len(pi.Visible) > maxVisibleAttrs { if len(pi.Visible) > maxVisibleAttrs {
return fmt.Errorf("too many visible attributes") return fmt.Errorf("too many visible attributes")
} }
@@ -216,6 +248,49 @@ func (p preferencesPayload) validate() error {
return fmt.Errorf("label value too long") return fmt.Errorf("label value too long")
} }
} }
}
if p.CurvePresets != nil {
return validateCurvePresets(*p.CurvePresets)
}
return nil
}
func validateCurvePresets(presets []curvePreset) error {
if len(presets) > maxCurvePresets {
return fmt.Errorf("too many curve presets")
}
names := make(map[string]struct{}, len(presets))
for _, preset := range presets {
if preset.Name == "" || utf8.RuneCountInString(preset.Name) > maxCurvePresetNameLen {
return fmt.Errorf("invalid curve preset name")
}
channels := []struct {
name string
points []curvePresetPoint
}{
{"rgb", preset.Channels.RGB},
{"red", preset.Channels.Red},
{"green", preset.Channels.Green},
{"blue", preset.Channels.Blue},
}
for _, channel := range channels {
if len(channel.points) < 2 || len(channel.points) > maxCurvePresetPoints {
return fmt.Errorf("invalid curve preset points for %s", channel.name)
}
for _, pt := range channel.points {
if math.IsNaN(pt.X) || math.IsNaN(pt.Y) || math.IsInf(pt.X, 0) || math.IsInf(pt.Y, 0) {
return fmt.Errorf("invalid curve preset point")
}
if pt.X < 0 || pt.X > 1 || pt.Y < 0 || pt.Y > 1 {
return fmt.Errorf("invalid curve preset point")
}
}
}
if _, dup := names[preset.Name]; dup {
return fmt.Errorf("duplicate curve preset name")
}
names[preset.Name] = struct{}{}
}
return nil return nil
} }
@@ -230,18 +305,40 @@ func (h *Handler) UpdatePreferences(c *gin.Context) {
httpx.RespondError(c, httpx.BadRequest("invalid_preferences", "preferences must be a JSON object")) httpx.RespondError(c, httpx.BadRequest("invalid_preferences", "preferences must be a JSON object"))
return return
} }
payload.normalize()
if err := payload.validate(); err != nil { if err := payload.validate(); err != nil {
httpx.RespondError(c, httpx.BadRequest("invalid_preferences", err.Error())) httpx.RespondError(c, httpx.BadRequest("invalid_preferences", err.Error()))
return return
} }
raw, err := json.Marshal(payload)
ctx := c.Request.Context()
u, err := h.svc.store.GetUserByID(ctx, UserID(c))
if err != nil {
httpx.RespondError(c, httpx.Unauthorized("unauthorized", "user not found"))
return
}
// Merge the submitted sections into the stored blob so saving one section
// never clears the others. Unknown keys are preserved.
merged := make(map[string]any, len(u.Preferences)+2)
for k, v := range u.Preferences {
merged[k] = v
}
if payload.PhotoInfo != nil {
merged["photo_info"] = payload.PhotoInfo
}
if payload.CurvePresets != nil {
merged["curve_presets"] = *payload.CurvePresets
}
if payload.PhotoInfo != nil || payload.CurvePresets != nil {
raw, err := json.Marshal(merged)
if err != nil { if err != nil {
httpx.RespondError(c, httpx.BadRequest("invalid_preferences", "could not encode preferences")) httpx.RespondError(c, httpx.BadRequest("invalid_preferences", "could not encode preferences"))
return return
} }
if err := h.svc.store.UpdatePreferences(c.Request.Context(), UserID(c), raw); err != nil { if err := h.svc.store.UpdatePreferences(ctx, UserID(c), raw); err != nil {
httpx.RespondError(c, err) httpx.RespondError(c, err)
return return
} }
c.JSON(http.StatusOK, gin.H{"preferences": payload}) }
c.JSON(http.StatusOK, gin.H{"preferences": merged})
} }
+214
View File
@@ -5,6 +5,7 @@ import (
"encoding/json" "encoding/json"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"strings"
"testing" "testing"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
@@ -30,6 +31,7 @@ func newTestRouter(t *testing.T) *gin.Engine {
authed.PATCH("/auth/me", h.UpdateMe) authed.PATCH("/auth/me", h.UpdateMe)
authed.POST("/auth/me/password", h.ChangePassword) authed.POST("/auth/me/password", h.ChangePassword)
authed.POST("/auth/me/identifiers", h.AddIdentifier) authed.POST("/auth/me/identifiers", h.AddIdentifier)
authed.PATCH("/auth/me/preferences", h.UpdatePreferences)
authed.DELETE("/auth/me", h.DeleteMe) authed.DELETE("/auth/me", h.DeleteMe)
return r return r
} }
@@ -213,3 +215,215 @@ func TestDeleteMeHandler(t *testing.T) {
t.Fatalf("me after delete status = %d", rec.Code) t.Fatalf("me after delete status = %d", rec.Code)
} }
} }
func curvePresetPayloadWith(name, channel string, points []map[string]float64) map[string]any {
linear := func() []map[string]float64 {
return []map[string]float64{
{"x": 0, "y": 0},
{"x": 1, "y": 1},
}
}
channels := map[string]any{
"rgb": linear(),
"red": linear(),
"green": linear(),
"blue": linear(),
}
channels[channel] = points
return map[string]any{"name": name, "channels": channels}
}
func curvePresetPayload(name string) map[string]any {
return curvePresetPayloadWith(name, "rgb", []map[string]float64{
{"x": 0, "y": 0},
{"x": 1, "y": 0.8},
})
}
func decodePreferences(t *testing.T, rec *httptest.ResponseRecorder) map[string]any {
t.Helper()
var body struct {
Preferences map[string]any `json:"preferences"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatalf("decode preferences %s: %v", rec.Body.String(), err)
}
return body.Preferences
}
func TestUpdatePreferencesMergesSections(t *testing.T) {
r := newTestRouter(t)
reg := doJSON(r, http.MethodPost, "/auth/register", "", map[string]string{
"email": "prefs@test.local", "password": "password123", "name": "Prefs",
})
token := decodeAuth(t, reg).Tokens.AccessToken
rec := doJSON(r, http.MethodPatch, "/auth/me/preferences", token, map[string]any{
"photo_info": map[string]any{
"visible": []string{"camera"},
"labels": map[string]string{"camera": "Камера"},
},
})
if rec.Code != http.StatusOK {
t.Fatalf("save photo_info status = %d body = %s", rec.Code, rec.Body.String())
}
rec = doJSON(r, http.MethodPatch, "/auth/me/preferences", token, map[string]any{
"curve_presets": []any{curvePresetPayload("Мой")},
})
if rec.Code != http.StatusOK {
t.Fatalf("save presets status = %d body = %s", rec.Code, rec.Body.String())
}
prefs := decodePreferences(t, rec)
if _, ok := prefs["photo_info"]; !ok {
t.Fatalf("photo_info lost after saving presets: %+v", prefs)
}
presets, ok := prefs["curve_presets"].([]any)
if !ok || len(presets) != 1 {
t.Fatalf("presets = %#v, want one", prefs["curve_presets"])
}
// Saving photo_info again must keep the presets.
rec = doJSON(r, http.MethodPatch, "/auth/me/preferences", token, map[string]any{
"photo_info": map[string]any{"visible": []string{"iso"}},
})
prefs = decodePreferences(t, rec)
if presets, ok := prefs["curve_presets"].([]any); !ok || len(presets) != 1 {
t.Fatalf("presets lost after saving photo_info: %+v", prefs)
}
info, _ := prefs["photo_info"].(map[string]any)
if visible, _ := info["visible"].([]any); len(visible) != 1 || visible[0] != "iso" {
t.Fatalf("photo_info not updated: %+v", prefs["photo_info"])
}
// The merged state is what GET /auth/me returns.
rec = doJSON(r, http.MethodGet, "/auth/me", token, nil)
var me struct {
Preferences map[string]any `json:"preferences"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &me); err != nil {
t.Fatalf("decode me: %v", err)
}
if _, ok := me.Preferences["photo_info"]; !ok {
t.Fatalf("me lost photo_info: %+v", me.Preferences)
}
if _, ok := me.Preferences["curve_presets"]; !ok {
t.Fatalf("me lost curve_presets: %+v", me.Preferences)
}
// An empty preset list clears only presets.
rec = doJSON(r, http.MethodPatch, "/auth/me/preferences", token, map[string]any{
"curve_presets": []any{},
})
prefs = decodePreferences(t, rec)
if presets, ok := prefs["curve_presets"].([]any); !ok || len(presets) != 0 {
t.Fatalf("presets not cleared: %+v", prefs["curve_presets"])
}
if _, ok := prefs["photo_info"]; !ok {
t.Fatalf("photo_info lost after clearing presets: %+v", prefs)
}
// Names are stored without surrounding whitespace.
rec = doJSON(r, http.MethodPatch, "/auth/me/preferences", token, map[string]any{
"curve_presets": []any{curvePresetPayload(" Мой ")},
})
prefs = decodePreferences(t, rec)
presets = prefs["curve_presets"].([]any)
first, _ := presets[0].(map[string]any)
if first["name"] != "Мой" {
t.Fatalf("preset name = %#v, want trimmed", first["name"])
}
}
func TestPreferencesArePrivate(t *testing.T) {
r := newTestRouter(t)
first := decodeAuth(t, doJSON(r, http.MethodPost, "/auth/register", "", map[string]string{
"email": "private1@test.local", "password": "password123", "name": "One",
}))
second := decodeAuth(t, doJSON(r, http.MethodPost, "/auth/register", "", map[string]string{
"email": "private2@test.local", "password": "password123", "name": "Two",
}))
rec := doJSON(r, http.MethodPatch, "/auth/me/preferences", first.Tokens.AccessToken, map[string]any{
"curve_presets": []any{curvePresetPayload("Секрет")},
})
if rec.Code != http.StatusOK {
t.Fatalf("save status = %d body = %s", rec.Code, rec.Body.String())
}
rec = doJSON(r, http.MethodGet, "/auth/me", second.Tokens.AccessToken, nil)
var me struct {
Preferences map[string]any `json:"preferences"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &me); err != nil {
t.Fatalf("decode me: %v", err)
}
if _, ok := me.Preferences["curve_presets"]; ok {
t.Fatalf("other user sees presets: %+v", me.Preferences)
}
}
func TestUpdatePreferencesRejectsInvalidCurvePresets(t *testing.T) {
r := newTestRouter(t)
reg := doJSON(r, http.MethodPost, "/auth/register", "", map[string]string{
"email": "invalidprefs@test.local", "password": "password123", "name": "Invalid",
})
token := decodeAuth(t, reg).Tokens.AccessToken
rec := doJSON(r, http.MethodPatch, "/auth/me/preferences", token, map[string]any{
"curve_presets": []any{curvePresetPayload("Хороший")},
})
if rec.Code != http.StatusOK {
t.Fatalf("seed status = %d body = %s", rec.Code, rec.Body.String())
}
manyPoints := make([]map[string]float64, 17)
for i := range manyPoints {
manyPoints[i] = map[string]float64{"x": float64(i) / 16, "y": float64(i) / 16}
}
tooMany := make([]any, 101)
for i := range tooMany {
tooMany[i] = curvePresetPayload("preset-" + string(rune('a'+i%26)) + strings.Repeat("x", i/26))
}
missingChannel := curvePresetPayload("bad")
delete(missingChannel["channels"].(map[string]any), "blue")
cases := []struct {
name string
presets []any
}{
{"too long name", []any{curvePresetPayload(strings.Repeat("a", 65))}},
{"missing channel", []any{missingChannel}},
{"one point", []any{curvePresetPayloadWith("one", "red", []map[string]float64{
{"x": 0, "y": 0},
})}},
{"too many points", []any{curvePresetPayloadWith("many", "rgb", manyPoints)}},
{"x out of range", []any{curvePresetPayloadWith("range", "blue", []map[string]float64{
{"x": 1.1, "y": 0},
{"x": 1, "y": 1},
})}},
{"duplicate name", []any{curvePresetPayload("dup"), curvePresetPayload("dup")}},
{"too many presets", tooMany},
}
for _, tc := range cases {
rec := doJSON(r, http.MethodPatch, "/auth/me/preferences", token, map[string]any{
"curve_presets": tc.presets,
})
if rec.Code != http.StatusBadRequest {
t.Fatalf("%s status = %d body = %s", tc.name, rec.Code, rec.Body.String())
}
}
rec = doJSON(r, http.MethodGet, "/auth/me", token, nil)
var me struct {
Preferences map[string]any `json:"preferences"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &me); err != nil {
t.Fatalf("decode me: %v", err)
}
presets, _ := me.Preferences["curve_presets"].([]any)
if len(presets) != 1 {
t.Fatalf("invalid requests changed presets: %+v", me.Preferences)
}
}
+75
View File
@@ -0,0 +1,75 @@
package e2e
import (
"context"
"path/filepath"
"testing"
"time"
"galo/internal/albums"
"galo/internal/photos"
)
// A color edit must survive the round trip: the parameters are stored in the
// photo metadata, the edited version is rendered, and a reset returns the
// photo to its original look.
func TestColorEditRoundTrip(t *testing.T) {
ctx := context.Background()
st, closeDB := openStack(t, filepath.Join(t.TempDir(), "galo.db"), t.TempDir())
defer closeDB()
user, _, err := st.auth.Register(ctx, "color@test.local", "", "password123", "C")
if err != nil {
t.Fatalf("register: %v", err)
}
album, err := st.albums.Create(ctx, user.ID, albums.CreateInput{Title: "Color"})
if err != nil {
t.Fatalf("create album: %v", err)
}
p, err := st.photos.Upload(ctx, photos.UploadInput{
AlbumID: album.ID, UserID: user.ID, Filename: "c.png", Data: makePNG(t),
})
if err != nil {
t.Fatalf("upload: %v", err)
}
w := photos.NewWorker(st.photos, time.Second, 10, time.Minute, 2)
w.ProcessOnce(ctx)
color := photos.ColorParams{Temperature: 25, Vibrance: 20}
color.Mixer.Red.Saturation = 30
color.Grading.Shadows = photos.ColorWheel{Hue: 220, Saturation: 40}
edited, err := st.photos.EditPhoto(ctx, p.ID, user.ID, photos.EditParams{
Light: photos.LightParams{Exposure: 0.3},
Color: color,
})
if err != nil {
t.Fatalf("edit: %v", err)
}
if edited.EditParams == nil {
t.Fatal("edit returned no parameters")
}
w.ProcessOnce(ctx)
got, err := st.photos.Get(ctx, p.ID, user.ID)
if err != nil {
t.Fatalf("get: %v", err)
}
if got.EditPreviewURL == "" {
t.Fatalf("no edited preview url: %+v", got)
}
if _, ok := got.EditParams["color"]; !ok {
t.Fatalf("color params not stored: %+v", got.EditParams)
}
reset, err := st.photos.ResetEdit(ctx, p.ID, user.ID)
if err != nil {
t.Fatalf("reset: %v", err)
}
if len(reset.EditParams) != 0 {
t.Fatalf("reset kept params: %+v", reset.EditParams)
}
if reset.EditURL != "" || reset.EditPreviewURL != "" {
t.Fatalf("reset kept the edited version: %+v", reset)
}
}
@@ -0,0 +1,56 @@
package e2e
import (
"context"
"path/filepath"
"testing"
)
// Curve presets live in the user profile: they survive a round trip through
// the metadata layer and are never visible to another user.
func TestCurvePresetsPersistAndArePrivate(t *testing.T) {
ctx := context.Background()
st, closeDB := openStack(t, filepath.Join(t.TempDir(), "galo.db"), t.TempDir())
defer closeDB()
owner, _, err := st.auth.Register(ctx, "presets@test.local", "", "password123", "Owner")
if err != nil {
t.Fatalf("register owner: %v", err)
}
other, _, err := st.auth.Register(ctx, "otherpresets@test.local", "", "password123", "Other")
if err != nil {
t.Fatalf("register other: %v", err)
}
raw := []byte(`{"curve_presets":[{"name":"Мой контраст","channels":{"rgb":[{"x":0,"y":0},{"x":1,"y":0.9}],"red":[{"x":0,"y":0},{"x":1,"y":1}],"green":[{"x":0,"y":0},{"x":1,"y":1}],"blue":[{"x":0,"y":0},{"x":1,"y":1}]}}]}`)
if err := st.repos.Auth.UpdatePreferences(ctx, owner.ID, raw); err != nil {
t.Fatalf("update preferences: %v", err)
}
got, err := st.repos.Auth.GetUserByID(ctx, owner.ID)
if err != nil {
t.Fatalf("get owner: %v", err)
}
presets, ok := got.Preferences["curve_presets"].([]any)
if !ok || len(presets) != 1 {
t.Fatalf("presets not stored: %+v", got.Preferences)
}
preset, _ := presets[0].(map[string]any)
if preset["name"] != "Мой контраст" {
t.Fatalf("preset = %+v", preset)
}
channels, _ := preset["channels"].(map[string]any)
for _, channel := range []string{"rgb", "red", "green", "blue"} {
if points, ok := channels[channel].([]any); !ok || len(points) != 2 {
t.Fatalf("channel %s = %#v", channel, channels[channel])
}
}
otherUser, err := st.repos.Auth.GetUserByID(ctx, other.ID)
if err != nil {
t.Fatalf("get other: %v", err)
}
if _, ok := otherUser.Preferences["curve_presets"]; ok {
t.Fatalf("other user sees presets: %+v", otherUser.Preferences)
}
}
+109
View File
@@ -0,0 +1,109 @@
package e2e
import (
"context"
"path/filepath"
"testing"
"time"
"galo/internal/albums"
"galo/internal/photos"
)
// TestEditPendingLifecycle covers the render-state flag clients use to decide
// whether the edit_* URLs can be shown: saving edits reports a pending render,
// the worker clears it and publishes the fresh URLs, a second edit keeps the
// previous render (still pending), and a reset clears both the flag and the
// edited version.
func TestEditPendingLifecycle(t *testing.T) {
ctx := context.Background()
st, closeDB := openStack(t, filepath.Join(t.TempDir(), "galo.db"), t.TempDir())
defer closeDB()
user, _, err := st.auth.Register(ctx, "editpending@test.local", "", "password123", "E")
if err != nil {
t.Fatalf("register: %v", err)
}
album, err := st.albums.Create(ctx, user.ID, albums.CreateInput{Title: "Pending"})
if err != nil {
t.Fatalf("create album: %v", err)
}
p, err := st.photos.Upload(ctx, photos.UploadInput{
AlbumID: album.ID, UserID: user.ID, Filename: "p.png", Data: makePNG(t),
})
if err != nil {
t.Fatalf("upload: %v", err)
}
w := photos.NewWorker(st.photos, time.Second, 10, time.Minute, 2)
w.ProcessOnce(ctx)
first, err := st.photos.EditPhoto(ctx, p.ID, user.ID, photos.EditParams{
Light: photos.LightParams{Exposure: 0.5},
})
if err != nil {
t.Fatalf("edit: %v", err)
}
if !first.EditPending {
t.Fatalf("edit response does not report a pending render: %+v", first)
}
if first.EditPreviewURL != "" {
t.Fatalf("first render already exposes edit_preview_url: %q", first.EditPreviewURL)
}
w.ProcessOnce(ctx)
rendered, err := st.photos.Get(ctx, p.ID, user.ID)
if err != nil {
t.Fatalf("get rendered photo: %v", err)
}
if rendered.EditPending {
t.Fatalf("rendered photo still reports edit_pending: %+v", rendered)
}
if rendered.EditPreviewURL == "" {
t.Fatalf("rendered photo has no edit_preview_url: %+v", rendered)
}
firstPreview := rendered.EditPreviewURL
// A second edit is queued while the previous render is still bound: the
// photo stays pending and the old URLs must not be treated as current.
second, err := st.photos.EditPhoto(ctx, p.ID, user.ID, photos.EditParams{
Light: photos.LightParams{Exposure: 1.25},
})
if err != nil {
t.Fatalf("second edit: %v", err)
}
if !second.EditPending {
t.Fatalf("second edit does not report a pending render: %+v", second)
}
if second.EditPreviewURL != firstPreview {
t.Fatalf("second edit should keep the previous render while pending: %q want %q",
second.EditPreviewURL, firstPreview)
}
w.ProcessOnce(ctx)
after, err := st.photos.Get(ctx, p.ID, user.ID)
if err != nil {
t.Fatalf("get after second render: %v", err)
}
if after.EditPending {
t.Fatalf("second render still reports edit_pending: %+v", after)
}
if after.EditPreviewURL == "" || after.EditPreviewURL == firstPreview {
t.Fatalf("second render preview url = %q, want a fresh one (old %q)",
after.EditPreviewURL, firstPreview)
}
reset, err := st.photos.ResetEdit(ctx, p.ID, user.ID)
if err != nil {
t.Fatalf("reset: %v", err)
}
if reset.EditPending {
t.Fatalf("reset photo reports edit_pending: %+v", reset)
}
if reset.EditPreviewURL != "" || reset.EditURL != "" {
t.Fatalf("reset photo still exposes edit urls: %+v", reset)
}
if reset.EditParams != nil && len(reset.EditParams) > 0 {
t.Fatalf("reset photo still exposes edit params: %+v", reset.EditParams)
}
}
+142
View File
@@ -0,0 +1,142 @@
package e2e
import (
"bytes"
"context"
"path/filepath"
"testing"
"time"
"github.com/disintegration/imaging"
"github.com/gen2brain/webp"
"galo/internal/albums"
"galo/internal/photos"
)
// TestEffectsEdit covers the effects round trip: the parameters are stored in
// the photo metadata, the background worker renders the edited version, the
// saved parameters carry the normalized effects, a reset removes everything,
// and re-rendering the same edit (including grain) is deterministic.
func TestEffectsEdit(t *testing.T) {
ctx := context.Background()
st, closeDB := openStack(t, filepath.Join(t.TempDir(), "galo.db"), t.TempDir())
defer closeDB()
user, _, err := st.auth.Register(ctx, "effects@test.local", "", "password123", "E")
if err != nil {
t.Fatalf("register: %v", err)
}
album, err := st.albums.Create(ctx, user.ID, albums.CreateInput{Title: "Effects"})
if err != nil {
t.Fatalf("create album: %v", err)
}
p, err := st.photos.Upload(ctx, photos.UploadInput{
AlbumID: album.ID, UserID: user.ID, Filename: "e.png", Data: makePNG(t),
})
if err != nil {
t.Fatalf("upload: %v", err)
}
w := photos.NewWorker(st.photos, time.Second, 10, time.Minute, 2)
w.ProcessOnce(ctx)
params := photos.EditParams{Effects: photos.EffectsParams{
Texture: 25,
Clarity: 20,
Dehaze: 15,
Vignette: photos.VignetteParams{
Mode: photos.VignetteColor, Amount: 40, Midpoint: 60, Feather: 40, Color: "#ff8800",
},
Grain: photos.GrainParams{Amount: 35, Size: 30, Roughness: 60},
}}
edited, err := st.photos.EditPhoto(ctx, p.ID, user.ID, params)
if err != nil {
t.Fatalf("edit: %v", err)
}
if edited.EditParams == nil {
t.Fatal("edit returned no parameters")
}
if _, ok := edited.EditParams["effects"]; !ok {
t.Fatalf("effects params not returned: %+v", edited.EditParams)
}
w.ProcessOnce(ctx)
got, err := st.photos.Get(ctx, p.ID, user.ID)
if err != nil {
t.Fatalf("get: %v", err)
}
if got.EditPreviewURL == "" {
t.Fatalf("no edited preview url: %+v", got)
}
if got.EditPreviewKey == "" {
t.Fatalf("no edited preview key: %+v", got)
}
effects, ok := got.EditParams["effects"].(map[string]any)
if !ok {
t.Fatalf("effects params not stored: %+v", got.EditParams)
}
vignette, ok := effects["vignette"].(map[string]any)
if !ok {
t.Fatalf("vignette params not stored: %+v", effects)
}
if vignette["mode"] != photos.VignetteColor {
t.Fatalf("vignette mode = %v, want %q", vignette["mode"], photos.VignetteColor)
}
if vignette["color"] != "#ff8800" {
t.Fatalf("vignette color = %v, want #ff8800", vignette["color"])
}
if vignette["midpoint"] != float64(60) {
t.Fatalf("vignette midpoint = %v, want 60", vignette["midpoint"])
}
grain, ok := effects["grain"].(map[string]any)
if !ok {
t.Fatalf("grain params not stored: %+v", effects)
}
if grain["size"] != float64(30) || grain["roughness"] != float64(60) {
t.Fatalf("grain params = %+v, want size 30 roughness 60", grain)
}
first := previewPixels(t, st, got.EditPreviewKey)
reset, err := st.photos.ResetEdit(ctx, p.ID, user.ID)
if err != nil {
t.Fatalf("reset: %v", err)
}
if len(reset.EditParams) != 0 {
t.Fatalf("reset kept params: %+v", reset.EditParams)
}
if reset.EditURL != "" || reset.EditPreviewURL != "" || reset.EditPreviewKey != "" {
t.Fatalf("reset kept the edited version: %+v", reset)
}
// The same parameters and the same photo id must render the same grain.
if _, err := st.photos.EditPhoto(ctx, p.ID, user.ID, params); err != nil {
t.Fatalf("edit again: %v", err)
}
w.ProcessOnce(ctx)
again, err := st.photos.Get(ctx, p.ID, user.ID)
if err != nil {
t.Fatalf("get after second edit: %v", err)
}
if again.EditPreviewURL == "" || again.EditPreviewKey == "" {
t.Fatalf("no edited preview after second edit: %+v", again)
}
second := previewPixels(t, st, again.EditPreviewKey)
if !bytes.Equal(first, second) {
t.Fatal("repeated render with the same grain parameters is not deterministic")
}
}
// previewPixels decodes an edited preview object into its pixel bytes.
func previewPixels(t *testing.T, st *stack, key string) []uint8 {
t.Helper()
data, err := st.storage.Get(context.Background(), key)
if err != nil {
t.Fatalf("read preview object: %v", err)
}
img, err := webp.Decode(bytes.NewReader(data))
if err != nil {
t.Fatalf("decode preview: %v", err)
}
return imaging.Clone(img).Pix
}
+3
View File
@@ -108,6 +108,9 @@ type Photo struct {
Caption string `json:"caption"` Caption string `json:"caption"`
EXIF map[string]any `json:"exif,omitempty"` EXIF map[string]any `json:"exif,omitempty"`
EditParams map[string]any `json:"edit_params,omitempty"` EditParams map[string]any `json:"edit_params,omitempty"`
// EditPending is true while the server still renders the saved edit
// parameters, so the edit_* URLs do not describe the current edit yet.
EditPending bool `json:"edit_pending"`
Tags []Tag `json:"tags,omitempty"` Tags []Tag `json:"tags,omitempty"`
DeletedAt *time.Time `json:"deleted_at,omitempty"` DeletedAt *time.Time `json:"deleted_at,omitempty"`
AlbumTitle string `json:"album_title,omitempty"` AlbumTitle string `json:"album_title,omitempty"`
+674 -17
View File
@@ -5,6 +5,7 @@ import (
"errors" "errors"
"math" "math"
"sort" "sort"
"strings"
) )
// Edit parameters are stored in the photo metadata and describe a // Edit parameters are stored in the photo metadata and describe a
@@ -39,9 +40,228 @@ type CurvePoint struct {
Y float64 `json:"y"` Y float64 `json:"y"`
} }
// ColorParams holds the parameters of the "Цвет" (color) tool: white balance,
// vibrance/saturation, the per-hue color mixer, color grading and a simple
// per-channel color correction. Percent values use -100..100, wheel hues use
// 0..360.
type ColorParams struct {
Temperature float64 `json:"temperature"`
Tint float64 `json:"tint"`
Vibrance float64 `json:"vibrance"`
Saturation float64 `json:"saturation"`
Mixer ColorMixer `json:"mixer"`
Grading ColorGrading `json:"grading"`
Correction ColorCorrection `json:"correction"`
}
// ColorMixer holds one HSL band per hue, mirroring the Lightroom color mixer.
type ColorMixer struct {
Red MixerBand `json:"red"`
Orange MixerBand `json:"orange"`
Yellow MixerBand `json:"yellow"`
Green MixerBand `json:"green"`
Aqua MixerBand `json:"aqua"`
Blue MixerBand `json:"blue"`
Purple MixerBand `json:"purple"`
Magenta MixerBand `json:"magenta"`
}
// MixerBand is a hue/saturation/luminance adjustment of one color band.
type MixerBand struct {
Hue float64 `json:"hue"`
Saturation float64 `json:"saturation"`
Luminance float64 `json:"luminance"`
}
// ColorGrading holds the three color-grading wheels and their blending.
type ColorGrading struct {
Shadows ColorWheel `json:"shadows"`
Midtones ColorWheel `json:"midtones"`
Highlights ColorWheel `json:"highlights"`
Blending float64 `json:"blending"`
Balance float64 `json:"balance"`
}
// ColorWheel is a hue, strength and luminance used by color grading.
type ColorWheel struct {
Hue float64 `json:"hue"`
Saturation float64 `json:"saturation"`
Luminance float64 `json:"luminance"`
}
// ColorCorrection is a simple per-channel gain, in percent.
type ColorCorrection struct {
Red float64 `json:"red"`
Green float64 `json:"green"`
Blue float64 `json:"blue"`
}
// EffectsParams holds the parameters of the "Эффекты" (effects) tool: texture,
// clarity, dehaze, vignette and grain. It is applied after the light and color
// adjustments, because it works on the already corrected frame.
type EffectsParams struct {
Texture float64 `json:"texture"`
Clarity float64 `json:"clarity"`
Dehaze float64 `json:"dehaze"`
Vignette VignetteParams `json:"vignette"`
Grain GrainParams `json:"grain"`
}
// VignetteParams holds the parameters of the "Виньетка" tool. The mode picks
// the way the edges are treated ("light" darkens or brightens them, "color"
// tints them and "colorize" fills them with the chosen color), amount is the
// signed strength in percent, and the rest controls the geometry of the effect.
//
// midpointSet and featherSet record whether the client sent the field: an
// explicit zero is a valid geometry value and must not be replaced by the
// default, while an omitted field gets the default.
type VignetteParams struct {
Mode string `json:"mode"`
Amount float64 `json:"amount"`
Midpoint float64 `json:"midpoint"`
Feather float64 `json:"feather"`
Roundness float64 `json:"roundness"`
Highlights float64 `json:"highlights"`
Color string `json:"color"`
midpointSet bool
featherSet bool
}
// UnmarshalJSON remembers which defaultable fields the client actually sent.
func (v *VignetteParams) UnmarshalJSON(data []byte) error {
var raw struct {
Mode *string `json:"mode"`
Amount *float64 `json:"amount"`
Midpoint *float64 `json:"midpoint"`
Feather *float64 `json:"feather"`
Roundness *float64 `json:"roundness"`
Highlights *float64 `json:"highlights"`
Color *string `json:"color"`
}
if err := json.Unmarshal(data, &raw); err != nil {
return err
}
*v = VignetteParams{}
if raw.Mode != nil {
v.Mode = *raw.Mode
}
if raw.Amount != nil {
v.Amount = *raw.Amount
}
if raw.Midpoint != nil {
v.Midpoint = *raw.Midpoint
v.midpointSet = true
}
if raw.Feather != nil {
v.Feather = *raw.Feather
v.featherSet = true
}
if raw.Roundness != nil {
v.Roundness = *raw.Roundness
}
if raw.Highlights != nil {
v.Highlights = *raw.Highlights
}
if raw.Color != nil {
v.Color = *raw.Color
}
return nil
}
// GrainParams holds the parameters of the "Зерно" tool. Amount is the strength,
// size the scale of the noise cells, roughness the mix of fine and smooth
// noise.
//
// sizeSet and roughnessSet record whether the client sent the field: an
// explicit zero is a valid value and must not be replaced by the default.
type GrainParams struct {
Amount float64 `json:"amount"`
Size float64 `json:"size"`
Roughness float64 `json:"roughness"`
sizeSet bool
roughnessSet bool
}
// UnmarshalJSON remembers which defaultable fields the client actually sent.
func (g *GrainParams) UnmarshalJSON(data []byte) error {
var raw struct {
Amount *float64 `json:"amount"`
Size *float64 `json:"size"`
Roughness *float64 `json:"roughness"`
}
if err := json.Unmarshal(data, &raw); err != nil {
return err
}
*g = GrainParams{}
if raw.Amount != nil {
g.Amount = *raw.Amount
}
if raw.Size != nil {
g.Size = *raw.Size
g.sizeSet = true
}
if raw.Roughness != nil {
g.Roughness = *raw.Roughness
g.roughnessSet = true
}
return nil
}
// Modes of the "Виньетка" tool. Any other mode is normalized to VignetteLight.
const (
VignetteLight = "light"
VignetteColor = "color"
VignetteColorize = "colorize"
)
// Structural defaults of the effects. They are filled by Normalized, so the
// zero value and an explicit "defaults" request mean the same thing and a photo
// without the "effects" key reads as untouched.
const (
DefaultVignetteMidpoint = 50.0
DefaultVignetteFeather = 50.0
DefaultGrainSize = 25.0
DefaultGrainRoughness = 50.0
)
// DefaultVignetteColor is the color used when the request carries no usable
// hex color.
const DefaultVignetteColor = "#000000"
// mixerBand is a color band with its hue center in degrees.
type mixerBand struct {
center float64
hue float64
saturation float64
luminance float64
}
// bands returns the mixer bands in a stable order.
func (m ColorMixer) bands() [8]mixerBand {
return [8]mixerBand{
{0, m.Red.Hue, m.Red.Saturation, m.Red.Luminance},
{30, m.Orange.Hue, m.Orange.Saturation, m.Orange.Luminance},
{60, m.Yellow.Hue, m.Yellow.Saturation, m.Yellow.Luminance},
{120, m.Green.Hue, m.Green.Saturation, m.Green.Luminance},
{180, m.Aqua.Hue, m.Aqua.Saturation, m.Aqua.Luminance},
{240, m.Blue.Hue, m.Blue.Saturation, m.Blue.Luminance},
{280, m.Purple.Hue, m.Purple.Saturation, m.Purple.Luminance},
{320, m.Magenta.Hue, m.Magenta.Saturation, m.Magenta.Luminance},
}
}
// wheels returns the grading wheels in a stable order.
func (g ColorGrading) wheels() [3]ColorWheel {
return [3]ColorWheel{g.Shadows, g.Midtones, g.Highlights}
}
// EditParams is the full set of non-destructive editing parameters of a photo. // EditParams is the full set of non-destructive editing parameters of a photo.
type EditParams struct { type EditParams struct {
Light LightParams `json:"light"` Light LightParams `json:"light"`
Color ColorParams `json:"color"`
Effects EffectsParams `json:"effects"`
} }
// Limits of the editing parameters. They are enforced on write so a hand-made // Limits of the editing parameters. They are enforced on write so a hand-made
@@ -82,9 +302,141 @@ func (p EditParams) Normalized() EditParams {
p.Light.Curve.Red = normalizeCurve(p.Light.Curve.Red) p.Light.Curve.Red = normalizeCurve(p.Light.Curve.Red)
p.Light.Curve.Green = normalizeCurve(p.Light.Curve.Green) p.Light.Curve.Green = normalizeCurve(p.Light.Curve.Green)
p.Light.Curve.Blue = normalizeCurve(p.Light.Curve.Blue) p.Light.Curve.Blue = normalizeCurve(p.Light.Curve.Blue)
p.Color = p.Color.Normalized()
p.Effects = p.Effects.Normalized()
return p return p
} }
// Normalized returns a copy of the color parameters clamped to their ranges.
func (c ColorParams) Normalized() ColorParams {
c.Temperature = clampFloat(c.Temperature, -MaxPercent, MaxPercent)
c.Tint = clampFloat(c.Tint, -MaxPercent, MaxPercent)
c.Vibrance = clampFloat(c.Vibrance, -MaxPercent, MaxPercent)
c.Saturation = clampFloat(c.Saturation, -MaxPercent, MaxPercent)
bands := c.Mixer.bands()
for i := range bands {
bands[i].hue = clampFloat(bands[i].hue, -MaxPercent, MaxPercent)
bands[i].saturation = clampFloat(bands[i].saturation, -MaxPercent, MaxPercent)
bands[i].luminance = clampFloat(bands[i].luminance, -MaxPercent, MaxPercent)
}
c.Mixer = ColorMixer{
Red: MixerBand{bands[0].hue, bands[0].saturation, bands[0].luminance},
Orange: MixerBand{bands[1].hue, bands[1].saturation, bands[1].luminance},
Yellow: MixerBand{bands[2].hue, bands[2].saturation, bands[2].luminance},
Green: MixerBand{bands[3].hue, bands[3].saturation, bands[3].luminance},
Aqua: MixerBand{bands[4].hue, bands[4].saturation, bands[4].luminance},
Blue: MixerBand{bands[5].hue, bands[5].saturation, bands[5].luminance},
Purple: MixerBand{bands[6].hue, bands[6].saturation, bands[6].luminance},
Magenta: MixerBand{bands[7].hue, bands[7].saturation, bands[7].luminance},
}
wheels := c.Grading.wheels()
for i := range wheels {
wheels[i].Hue = clampFloat(wheels[i].Hue, 0, 360)
wheels[i].Saturation = clampFloat(wheels[i].Saturation, -MaxPercent, MaxPercent)
wheels[i].Luminance = clampFloat(wheels[i].Luminance, -MaxPercent, MaxPercent)
}
c.Grading = ColorGrading{
Shadows: wheels[0],
Midtones: wheels[1],
Highlights: wheels[2],
Blending: clampFloat(c.Grading.Blending, 0, MaxPercent),
Balance: clampFloat(c.Grading.Balance, -MaxPercent, MaxPercent),
}
c.Correction.Red = clampFloat(c.Correction.Red, -MaxPercent, MaxPercent)
c.Correction.Green = clampFloat(c.Correction.Green, -MaxPercent, MaxPercent)
c.Correction.Blue = clampFloat(c.Correction.Blue, -MaxPercent, MaxPercent)
return c
}
// Normalized returns a copy of the effects clamped to their ranges, with the
// structural defaults filled in. Normalization is idempotent: applying it to an
// already normalized value returns it unchanged, which keeps repeated saves and
// reads stable.
func (e EffectsParams) Normalized() EffectsParams {
e.Texture = clampFloat(e.Texture, -MaxPercent, MaxPercent)
e.Clarity = clampFloat(e.Clarity, -MaxPercent, MaxPercent)
e.Dehaze = clampFloat(e.Dehaze, -MaxPercent, MaxPercent)
e.Vignette = e.Vignette.Normalized()
e.Grain = e.Grain.Normalized()
return e
}
// Normalized returns a copy of the vignette parameters clamped to their ranges.
// The midpoint and feather defaults are applied only when the client omitted the
// field; an explicit zero stays zero. Clamping happens before defaulting so the
// operation stays idempotent.
func (v VignetteParams) Normalized() VignetteParams {
v.Mode = normalizeVignetteMode(v.Mode)
v.Amount = clampFloat(v.Amount, -MaxPercent, MaxPercent)
v.Midpoint = clampFloat(v.Midpoint, 0, MaxPercent)
if v.Midpoint == 0 && !v.midpointSet {
v.Midpoint = DefaultVignetteMidpoint
}
v.Feather = clampFloat(v.Feather, 0, MaxPercent)
if v.Feather == 0 && !v.featherSet {
v.Feather = DefaultVignetteFeather
}
v.Roundness = clampFloat(v.Roundness, -MaxPercent, MaxPercent)
v.Highlights = clampFloat(v.Highlights, 0, MaxPercent)
v.Color = normalizeHexColor(v.Color)
return v
}
// Normalized returns a copy of the grain parameters clamped to their ranges.
// The size and roughness defaults are applied only when the client omitted the
// field; an explicit zero stays zero.
func (g GrainParams) Normalized() GrainParams {
g.Amount = clampFloat(g.Amount, 0, MaxPercent)
g.Size = clampFloat(g.Size, 0, MaxPercent)
if g.Size == 0 && !g.sizeSet {
g.Size = DefaultGrainSize
}
g.Roughness = clampFloat(g.Roughness, 0, MaxPercent)
if g.Roughness == 0 && !g.roughnessSet {
g.Roughness = DefaultGrainRoughness
}
return g
}
// IsEmpty reports whether the effects leave the image untouched. Only the
// strengths count: the structural defaults (mode, midpoint, feather, size,
// roughness, color) do not turn into an edit by themselves.
func (e EffectsParams) IsEmpty() bool {
return e.Texture == 0 && e.Clarity == 0 && e.Dehaze == 0 &&
e.Vignette.Amount == 0 && e.Grain.Amount == 0
}
// normalizeVignetteMode maps an unknown or empty mode to the light one.
func normalizeVignetteMode(mode string) string {
switch strings.ToLower(strings.TrimSpace(mode)) {
case VignetteColor:
return VignetteColor
case VignetteColorize:
return VignetteColorize
default:
return VignetteLight
}
}
// normalizeHexColor returns the lower-case "#rrggbb" form of a valid color and
// the default black for anything unusable.
func normalizeHexColor(color string) string {
color = strings.TrimSpace(color)
if len(color) != 7 || color[0] != '#' {
return DefaultVignetteColor
}
for i := 1; i < len(color); i++ {
c := color[i]
if (c < '0' || c > '9') && (c < 'a' || c > 'f') && (c < 'A' || c > 'F') {
return DefaultVignetteColor
}
}
return strings.ToLower(color)
}
// IsEmpty reports whether the parameters describe an untouched photo. // IsEmpty reports whether the parameters describe an untouched photo.
func (p EditParams) IsEmpty() bool { func (p EditParams) IsEmpty() bool {
l := p.Light l := p.Light
@@ -99,7 +451,26 @@ func (p EditParams) IsEmpty() bool {
} }
} }
} }
return true return p.Color.IsEmpty() && p.Effects.IsEmpty()
}
// IsEmpty reports whether the color parameters leave the image untouched.
func (c ColorParams) IsEmpty() bool {
if c.Temperature != 0 || c.Tint != 0 || c.Vibrance != 0 || c.Saturation != 0 {
return false
}
for _, b := range c.Mixer.bands() {
if b.hue != 0 || b.saturation != 0 || b.luminance != 0 {
return false
}
}
for _, w := range c.Grading.wheels() {
// A hue without strength or luminance has no effect.
if w.Saturation != 0 || w.Luminance != 0 {
return false
}
}
return c.Correction.Red == 0 && c.Correction.Green == 0 && c.Correction.Blue == 0
} }
// JSON encodes the parameters for storage in the photo metadata. // JSON encodes the parameters for storage in the photo metadata.
@@ -169,8 +540,9 @@ func clampInt(v, min, max int) int {
} }
// curveLUT builds a 256-entry lookup table from the control points of a // curveLUT builds a 256-entry lookup table from the control points of a
// curve. The first and last points extend to the edges of the range, and the // curve. The first and last points extend to the edges of the range as flat
// values in between are interpolated linearly. // shelves, and the values in between are interpolated with a monotone cubic
// Hermite spline (PCHIP, Fritsch–Carlson).
func curveLUT(points []CurvePoint) [256]uint8 { func curveLUT(points []CurvePoint) [256]uint8 {
var lut [256]uint8 var lut [256]uint8
pts := normalizeCurve(points) pts := normalizeCurve(points)
@@ -180,16 +552,71 @@ func curveLUT(points []CurvePoint) [256]uint8 {
} }
return lut return lut
} }
tangents := curveTangents(pts)
for i := 0; i < 256; i++ { for i := 0; i < 256; i++ {
x := float64(i) / 255 x := float64(i) / 255
lut[i] = uint8(math.Round(clamp01(curveEval(pts, x)) * 255)) lut[i] = uint8(math.Round(clamp01(curveEvalWithTangents(pts, tangents, x)) * 255))
} }
return lut return lut
} }
// curveEval evaluates the curve at x using linear interpolation between the // curveTangents returns the PCHIP slopes at the control points. Interior
// surrounding control points. // tangents are weighted harmonic means of the neighbouring slopes; endpoint
// tangents use the one-sided three-point formula with the Fritsch–Carlson
// shape-preserving clamp.
func curveTangents(points []CurvePoint) []float64 {
n := len(points)
if n < 2 {
return nil
}
h := make([]float64, n-1)
delta := make([]float64, n-1)
for i := 0; i < n-1; i++ {
h[i] = points[i+1].X - points[i].X
delta[i] = (points[i+1].Y - points[i].Y) / h[i]
}
m := make([]float64, n)
if n == 2 {
m[0] = delta[0]
m[1] = delta[0]
return m
}
m[0] = endpointTangent(h[0], h[1], delta[0], delta[1])
m[n-1] = endpointTangent(h[n-2], h[n-3], delta[n-2], delta[n-3])
for i := 1; i < n-1; i++ {
if delta[i-1]*delta[i] <= 0 {
m[i] = 0
continue
}
w1 := 2*h[i] + h[i-1]
w2 := h[i] + 2*h[i-1]
m[i] = (w1 + w2) / (w1/delta[i-1] + w2/delta[i])
}
return m
}
// endpointTangent is the one-sided endpoint slope of the PCHIP spline.
func endpointTangent(h0, h1, d0, d1 float64) float64 {
m := ((2*h0+h1)*d0 - h0*d1) / (h0 + h1)
if m*d0 <= 0 {
return 0
}
if d0*d1 < 0 && math.Abs(m) > math.Abs(3*d0) {
return 3 * d0
}
return m
}
// curveEval evaluates the curve at x with a monotone cubic Hermite spline.
// Outside the first and last points the value is constant.
func curveEval(points []CurvePoint, x float64) float64 { func curveEval(points []CurvePoint, x float64) float64 {
if len(points) < 2 {
return x
}
return curveEvalWithTangents(points, curveTangents(points), x)
}
func curveEvalWithTangents(points []CurvePoint, tangents []float64, x float64) float64 {
if x <= points[0].X { if x <= points[0].X {
return points[0].Y return points[0].Y
} }
@@ -197,19 +624,23 @@ func curveEval(points []CurvePoint, x float64) float64 {
if x >= last.X { if x >= last.X {
return last.Y return last.Y
} }
for i := 1; i < len(points); i++ { i := 1
if x > points[i].X { for i < len(points)-1 && x > points[i].X {
continue i++
} }
x0, y0 := points[i-1].X, points[i-1].Y p0, p1 := points[i-1], points[i]
x1, y1 := points[i].X, points[i].Y h := p1.X - p0.X
if x1-x0 < 1e-9 { if h < 1e-9 {
return y1 return p1.Y
} }
t := (x - x0) / (x1 - x0) t := (x - p0.X) / h
return y0 + t*(y1-y0) t2 := t * t
} t3 := t2 * t
return last.Y h00 := 2*t3 - 3*t2 + 1
h10 := t3 - 2*t2 + t
h01 := -2*t3 + 3*t2
h11 := t3 - t2
return h00*p0.Y + h10*h*tangents[i-1] + h01*p1.Y + h11*h*tangents[i]
} }
// lightAdjuster holds the precomputed factors of the light adjustments. The // lightAdjuster holds the precomputed factors of the light adjustments. The
@@ -267,3 +698,229 @@ func (a lightAdjuster) apply(v float64, master, channel *[256]uint8) float64 {
func adjustChannel(v float64, p LightParams, master, channel *[256]uint8) float64 { func adjustChannel(v float64, p LightParams, master, channel *[256]uint8) float64 {
return newLightAdjuster(p).apply(v, master, channel) return newLightAdjuster(p).apply(v, master, channel)
} }
// rgbToHSL converts RGB (each 0..255) to HSL: hue in degrees, saturation and
// lightness in 0..1. It uses only arithmetic, so it is easy to mirror in the
// client and in the WASM module.
func rgbToHSL(r, g, b float64) (h, s, l float64) {
r /= 255
g /= 255
b /= 255
max := math.Max(r, math.Max(g, b))
min := math.Min(r, math.Min(g, b))
l = (max + min) / 2
if max == min {
return 0, 0, l
}
d := max - min
if l > 0.5 {
s = d / (2 - max - min)
} else {
s = d / (max + min)
}
switch max {
case r:
h = (g - b) / d
if g < b {
h += 6
}
case g:
h = (b-r)/d + 2
case b:
h = (r-g)/d + 4
}
h *= 60
return h, s, l
}
// hslToRGB converts HSL (hue in degrees, saturation and lightness in 0..1)
// back to RGB in 0..255.
func hslToRGB(h, s, l float64) (r, g, b float64) {
if s == 0 {
v := l * 255
return v, v, v
}
var q float64
if l < 0.5 {
q = l * (1 + s)
} else {
q = l + s - l*s
}
p := 2*l - q
hk := h / 360
r = hueToRGB(p, q, hk+1.0/3)
g = hueToRGB(p, q, hk)
b = hueToRGB(p, q, hk-1.0/3)
return r * 255, g * 255, b * 255
}
// hueToRGB is the per-channel helper of hslToRGB.
func hueToRGB(p, q, t float64) float64 {
if t < 0 {
t++
}
if t > 1 {
t--
}
if t < 1.0/6 {
return p + (q-p)*6*t
}
if t < 1.0/2 {
return q
}
if t < 2.0/3 {
return p + (q-p)*(2.0/3-t)*6
}
return p
}
// bandWeight returns a triangular weight of a hue around a band center.
func bandWeight(h, center float64) float64 {
d := math.Abs(h - center)
if d > 180 {
d = 360 - d
}
return clamp01(1 - d/60)
}
// colorAdjuster holds the precomputed factors of the color adjustments. The
// order of the operations is fixed and mirrored by the client-side preview and
// the WASM module, so the live preview and the rendered result match.
type colorAdjuster struct {
temperature float64
tint float64
vibrance float64
saturation float64
mixer [8]mixerBand
hasMixer bool
wheels [3]ColorWheel
luminances [3]float64
blending float64
balance float64
correction [3]float64
tints [3][3]float64
}
func newColorAdjuster(p ColorParams) colorAdjuster {
a := colorAdjuster{
temperature: p.Temperature / 100,
tint: p.Tint / 100,
vibrance: p.Vibrance / 100,
saturation: p.Saturation / 100,
mixer: p.Mixer.bands(),
wheels: p.Grading.wheels(),
blending: p.Grading.Blending / 100,
balance: p.Grading.Balance / 100,
correction: [3]float64{p.Correction.Red / 100, p.Correction.Green / 100, p.Correction.Blue / 100},
}
for _, band := range a.mixer {
if band.hue != 0 || band.saturation != 0 || band.luminance != 0 {
a.hasMixer = true
break
}
}
for i, wheel := range a.wheels {
a.luminances[i] = wheel.Luminance / 100
r, g, b := hslToRGB(wheel.Hue, 1, 0.5)
a.tints[i] = [3]float64{r, g, b}
}
return a
}
// apply color-corrects one RGB pixel (each 0..255) and returns the result.
func (a colorAdjuster) apply(r, g, b float64) (float64, float64, float64) {
// Баланс белого: тёплый/холодный и зелёный/пурпурный сдвиг.
r *= 1 + 0.20*a.temperature + 0.10*a.tint
g *= 1 - 0.20*a.tint
b *= 1 - 0.20*a.temperature + 0.10*a.tint
r = clampFloat(r, 0, 255)
g = clampFloat(g, 0, 255)
b = clampFloat(b, 0, 255)
// Быстрый путь: только колёса/яркость, без микшера и насыщенности —
// HSL-переход не нужен, lightness считается напрямую.
fast := !a.hasMixer && a.saturation == 0 && a.vibrance == 0
var weights [3]float64
var rr, gg, bb float64
if fast {
max := math.Max(r, math.Max(g, b))
min := math.Min(r, math.Min(g, b))
l := (max + min) / 510
lb := clamp01(l + a.balance*0.5)
shadowW := (1 - lb) * (1 - lb)
shadowW *= shadowW
highlightW := lb * lb
highlightW *= highlightW
weights = [3]float64{shadowW, 1 - shadowW - highlightW, highlightW}
targetL := l
for i := range a.wheels {
targetL += a.luminances[i] * 0.2 * weights[i]
}
targetL = clamp01(targetL)
delta := (targetL - l) * 255
rr = r + delta
gg = g + delta
bb = b + delta
} else {
// RGB -> HSL.
h, s, l := rgbToHSL(r, g, b)
// Насыщенность и вибрация: вибрация сильнее влияет на приглушённые цвета.
if a.saturation != 0 || a.vibrance != 0 {
s = clamp01(s * (1 + a.saturation + a.vibrance*(1-s)))
}
// Цветовой микшер: сдвиг оттенка, насыщенности и яркости по зонам.
if a.hasMixer {
for _, band := range a.mixer {
w := bandWeight(h, band.center)
if w == 0 {
continue
}
h += (band.hue / 100) * 30 * w
s = clamp01(s * (1 + (band.saturation/100)*w))
l = clamp01(l + (band.luminance/100)*0.2*w)
}
}
h = math.Mod(h, 360)
if h < 0 {
h += 360
}
// Зоны яркости: веса в сумме дают 1, баланс сдвигает границы.
lb := clamp01(l + a.balance*0.5)
// Более узкие зоны: колесо теней почти не задевает средние тона.
shadowW := (1 - lb) * (1 - lb)
shadowW *= shadowW
highlightW := lb * lb
highlightW *= highlightW
weights = [3]float64{shadowW, 1 - shadowW - highlightW, highlightW}
for i := range a.wheels {
l = clamp01(l + a.luminances[i]*0.2*weights[i])
}
// HSL -> RGB.
rr, gg, bb = hslToRGB(h, s, l)
}
// Точечный цвет: три колеса по зонам яркости.
blend := a.blending
for i, wheel := range a.wheels {
strength := (wheel.Saturation / 100) * 0.5 * blend * weights[i]
if strength == 0 {
continue
}
tint := a.tints[i]
rr = rr*(1-strength) + tint[0]*strength
gg = gg*(1-strength) + tint[1]*strength
bb = bb*(1-strength) + tint[2]*strength
}
// Цветокоррекция: поканальный сдвиг.
rr *= 1 + a.correction[0]*0.5
gg *= 1 + a.correction[1]*0.5
bb *= 1 + a.correction[2]*0.5
return clampFloat(rr, 0, 255), clampFloat(gg, 0, 255), clampFloat(bb, 0, 255)
}
@@ -1,7 +1,9 @@
package photos package photos
import ( import (
"bytes"
"image" "image"
"image/png"
"testing" "testing"
"time" "time"
) )
@@ -29,6 +31,73 @@ func BenchmarkApplyLight(b *testing.B) {
b.Logf("кадров: %d", b.N) b.Logf("кадров: %d", b.N)
} }
// BenchmarkBoxBlur3 measures the O(n) box-blur passes on a 12 MP luminance
// plane with the radius the clarity pass uses for that frame.
func BenchmarkBoxBlur3(b *testing.B) {
w, h := 4000, 3000
src := make([]uint8, w*h)
for i := range src {
src[i] = uint8(i % 251)
}
radius := int(0.008 * float64(min(w, h)))
if radius < 2 {
radius = 2
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
_ = boxBlur3(src, w, h, radius)
}
b.StopTimer()
b.Logf("кадров: %d, радиус: %d", b.N, radius)
}
// BenchmarkFullRenderWithEffects measures the whole edited render of a 12 MP
// photo with all effects enabled: decode, light, color, dehaze, texture,
// clarity, vignette and grain. This is the work the background worker does for
// one edit job.
func BenchmarkFullRenderWithEffects(b *testing.B) {
w, h := 4000, 3000
src := image.NewNRGBA(image.Rect(0, 0, w, h))
for y := 0; y < h; y++ {
for x := 0; x < w; x++ {
i := y*src.Stride + x*4
src.Pix[i] = uint8(x*255/w) ^ uint8(y*255/h)
src.Pix[i+1] = uint8(x * 3)
src.Pix[i+2] = uint8(y * 5)
src.Pix[i+3] = 255
}
}
var buf bytes.Buffer
encoder := png.Encoder{CompressionLevel: png.BestSpeed}
if err := encoder.Encode(&buf, src); err != nil {
b.Fatalf("encode png: %v", err)
}
data := buf.Bytes()
params := EditParams{
Light: LightParams{Exposure: 0.2, Contrast: 12, Shadows: 15},
Color: ColorParams{Vibrance: 20, Temperature: 8},
Effects: EffectsParams{
Texture: 30,
Clarity: 25,
Dehaze: 20,
Vignette: VignetteParams{
Mode: VignetteColor, Amount: 35, Color: "#ff8800", Highlights: 25,
},
Grain: GrainParams{Amount: 30, Size: 30, Roughness: 55},
},
}
seed := editSeed("benchmark-photo")
b.ResetTimer()
for i := 0; i < b.N; i++ {
if _, err := decodeAndAdjust(data, params, seed); err != nil {
b.Fatalf("decode and adjust: %v", err)
}
}
b.StopTimer()
b.Logf("кадров: %d, эффекты: текстура/чёткость/дымка/виньетка/зерно", b.N)
}
func TestRenderSpeed(t *testing.T) { func TestRenderSpeed(t *testing.T) {
w, h := 4000, 3000 w, h := 4000, 3000
src := image.NewNRGBA(image.Rect(0, 0, w, h)) src := image.NewNRGBA(image.Rect(0, 0, w, h))
+63 -4
View File
@@ -90,14 +90,73 @@ func applyLightRows(dst *image.NRGBA, from, to int, adj lightAdjuster, master, r
} }
} }
// decodeAndAdjust decodes the original and applies the light adjustments to // decodeAndAdjust decodes the original and applies the light, color and effect
// it, so the variants and the full-size version share one decode. // adjustments to it, so the variants and the full-size version share one
func decodeAndAdjust(data []byte, p EditParams) (*image.NRGBA, error) { // decode. The passes run in a fixed order: light, color, then the effects
// (dehaze, texture, clarity, vignette, grain). The seed makes the grain render
// deterministic; it comes from the photo id.
func decodeAndAdjust(data []byte, p EditParams, seed uint64) (*image.NRGBA, error) {
img, err := imaging.Decode(bytes.NewReader(data), imaging.AutoOrientation(true)) img, err := imaging.Decode(bytes.NewReader(data), imaging.AutoOrientation(true))
if err != nil { if err != nil {
return nil, err return nil, err
} }
return applyLight(img, p.Light), nil edited := applyLight(img, p.Light)
if !p.Color.IsEmpty() {
edited = applyColor(edited, p.Color)
}
if !p.Effects.IsEmpty() {
edited = applyEffects(edited, p.Effects, seed)
}
return edited, nil
}
// applyColor applies the color adjustments in place to an image that already
// has the light adjustments applied. The image is owned by the caller.
func applyColor(dst *image.NRGBA, p ColorParams) *image.NRGBA {
adj := newColorAdjuster(p)
rows := dst.Rect.Dy()
workers := runtime.GOMAXPROCS(0)
if workers > rows {
workers = rows
}
if workers <= 1 {
applyColorRows(dst, 0, rows, adj)
return dst
}
// Рендер больших фото идёт по строкам параллельно.
chunk := (rows + workers - 1) / workers
var wg sync.WaitGroup
for from := 0; from < rows; from += chunk {
to := from + chunk
if to > rows {
to = rows
}
wg.Add(1)
go func(from, to int) {
defer wg.Done()
applyColorRows(dst, from, to, adj)
}(from, to)
}
wg.Wait()
return dst
}
// applyColorRows applies the color adjustments to the given range of rows.
func applyColorRows(dst *image.NRGBA, from, to int, adj colorAdjuster) {
width := dst.Rect.Dx()
for y := from; y < to; y++ {
row := dst.Pix[y*dst.Stride : y*dst.Stride+width*4]
for i := 0; i+3 < len(row); i += 4 {
if row[i+3] == 0 {
continue
}
r, g, b := adj.apply(float64(row[i]), float64(row[i+1]), float64(row[i+2]))
row[i] = uint8(clampFloat(r+0.5, 0, 255))
row[i+1] = uint8(clampFloat(g+0.5, 0, 255))
row[i+2] = uint8(clampFloat(b+0.5, 0, 255))
}
}
} }
// encodeEditedVariants renders the grid variants of an edited photo. They // encodeEditedVariants renders the grid variants of an edited photo. They
+257 -1
View File
@@ -91,6 +91,70 @@ func TestCurveLUTSteepens(t *testing.T) {
} }
} }
// The client builds the same 256-entry LUT (frontend/src/lib/edit.ts). The
// hard-coded samples keep the Go and TypeScript implementations in sync.
func TestCurveLUTMatchesClient(t *testing.T) {
samples := []int{0, 32, 64, 128, 192, 224, 255}
cases := []struct {
name string
points []CurvePoint
want []int
}{
{"linear", []CurvePoint{{0, 0}, {1, 1}}, []int{0, 32, 64, 128, 192, 224, 255}},
{
"medium",
[]CurvePoint{{0, 0}, {0.25, 0.2}, {0.5, 0.5}, {0.75, 0.8}, {1, 1}},
[]int{0, 23, 51, 128, 205, 233, 255},
},
{
"strong",
[]CurvePoint{{0, 0}, {0.2, 0.12}, {0.5, 0.5}, {0.8, 0.88}, {1, 1}},
[]int{0, 17, 43, 128, 213, 239, 255},
},
{
"inner",
[]CurvePoint{{0.1, 0.05}, {0.4, 0.3}, {0.9, 0.95}},
[]int{13, 17, 42, 104, 186, 234, 242},
},
}
for _, tc := range cases {
lut := curveLUT(tc.points)
for i, index := range samples {
if int(lut[index]) != tc.want[i] {
t.Fatalf("%s lut[%d] = %d, want %d", tc.name, index, lut[index], tc.want[i])
}
}
}
}
func TestCurveLUTIsMonotone(t *testing.T) {
for _, points := range [][]CurvePoint{
{{0, 0}, {0.25, 0.2}, {0.5, 0.5}, {0.75, 0.8}, {1, 1}},
{{0, 0}, {0.2, 0.12}, {0.5, 0.5}, {0.8, 0.88}, {1, 1}},
} {
lut := curveLUT(points)
for i := 1; i < len(lut); i++ {
if lut[i] < lut[i-1] {
t.Fatalf("lut[%d] = %d < lut[%d] = %d", i, lut[i], i-1, lut[i-1])
}
}
}
}
func TestCurveLUTFlatOutsideEndpoints(t *testing.T) {
lut := curveLUT([]CurvePoint{{0.1, 0.05}, {0.4, 0.3}, {0.9, 0.95}})
for i := 0; i <= int(math.Floor(0.1*255)); i++ {
if lut[i] != 13 {
t.Fatalf("lut[%d] = %d, want flat 13", i, lut[i])
}
}
for i := 230; i < len(lut); i++ {
if lut[i] != 242 {
t.Fatalf("lut[%d] = %d, want flat 242", i, lut[i])
}
}
}
func TestApplyLightBrightensAndKeepsSource(t *testing.T) { func TestApplyLightBrightensAndKeepsSource(t *testing.T) {
src := image.NewNRGBA(image.Rect(0, 0, 2, 2)) src := image.NewNRGBA(image.Rect(0, 0, 2, 2))
for i := range src.Pix { for i := range src.Pix {
@@ -144,7 +208,7 @@ func TestBuildEditedVariants(t *testing.T) {
src.Pix[i+3] = 255 src.Pix[i+3] = 255
} }
} }
edited, err := decodeAndAdjust(mustEncodePNG(t, src), EditParams{Light: LightParams{Exposure: 0.5}}) edited, err := decodeAndAdjust(mustEncodePNG(t, src), EditParams{Light: LightParams{Exposure: 0.5}}, editSeed("test-photo"))
if err != nil { if err != nil {
t.Fatalf("decode and adjust: %v", err) t.Fatalf("decode and adjust: %v", err)
} }
@@ -182,3 +246,195 @@ func mustEncodePNG(t *testing.T, img image.Image) []byte {
} }
return buf.Bytes() return buf.Bytes()
} }
func TestParseEditParamsClampsColor(t *testing.T) {
raw := []byte(`{"color":{"temperature":200,"tint":-300,"vibrance":50,"saturation":-500,"mixer":{"red":{"hue":150,"saturation":-200,"luminance":10}},"grading":{"shadows":{"hue":400,"saturation":150},"balance":-200},"correction":{"red":120}}}`)
params, err := ParseEditParams(raw)
if err != nil {
t.Fatalf("parse: %v", err)
}
c := params.Color
if c.Temperature != MaxPercent || c.Tint != -MaxPercent {
t.Fatalf("wb = %v/%v, want clamped", c.Temperature, c.Tint)
}
if c.Saturation != -MaxPercent {
t.Fatalf("saturation = %v, want %v", c.Saturation, -MaxPercent)
}
if c.Mixer.Red.Hue != MaxPercent || c.Mixer.Red.Saturation != -MaxPercent {
t.Fatalf("mixer red = %+v, want clamped", c.Mixer.Red)
}
if c.Grading.Shadows.Hue != 360 || c.Grading.Shadows.Saturation != MaxPercent {
t.Fatalf("grading shadows = %+v, want clamped", c.Grading.Shadows)
}
if c.Grading.Balance != -MaxPercent || c.Correction.Red != MaxPercent {
t.Fatalf("grading/correction not clamped: %+v %+v", c.Grading, c.Correction)
}
}
func TestColorParamsIsEmpty(t *testing.T) {
var zero ColorParams
if !zero.IsEmpty() {
t.Fatal("zero color params must be empty")
}
vibrance := ColorParams{Vibrance: 1}
if vibrance.IsEmpty() {
t.Fatal("vibrance must not be empty")
}
mixer := ColorParams{}
mixer.Mixer.Blue.Luminance = -10
if mixer.IsEmpty() {
t.Fatal("mixer band must not be empty")
}
// Оттенок колеса без силы не влияет на картинку.
hueOnly := ColorParams{}
hueOnly.Grading.Shadows.Hue = 120
if !hueOnly.IsEmpty() {
t.Fatal("grading hue without strength must count as empty")
}
grade := ColorParams{}
grade.Grading.Highlights.Saturation = 10
if grade.IsEmpty() {
t.Fatal("grading strength must not be empty")
}
}
func TestApplyColorWhiteBalance(t *testing.T) {
src := image.NewNRGBA(image.Rect(0, 0, 1, 1))
src.Pix[0], src.Pix[1], src.Pix[2], src.Pix[3] = 100, 100, 100, 255
out := applyColor(src, ColorParams{Temperature: 100})
if !(out.Pix[0] > out.Pix[1] && out.Pix[1] > out.Pix[2]) {
t.Fatalf("warm white balance = %d/%d/%d, want r > g > b", out.Pix[0], out.Pix[1], out.Pix[2])
}
}
func TestApplyColorSaturationMinus100IsGray(t *testing.T) {
src := image.NewNRGBA(image.Rect(0, 0, 1, 1))
src.Pix[0], src.Pix[1], src.Pix[2], src.Pix[3] = 200, 50, 50, 255
out := applyColor(src, ColorParams{Saturation: -100})
if out.Pix[0] != out.Pix[1] || out.Pix[1] != out.Pix[2] {
t.Fatalf("desaturated pixel = %d/%d/%d, want gray", out.Pix[0], out.Pix[1], out.Pix[2])
}
}
func TestApplyColorSaturationPlus100(t *testing.T) {
src := image.NewNRGBA(image.Rect(0, 0, 1, 1))
src.Pix[0], src.Pix[1], src.Pix[2], src.Pix[3] = 150, 120, 120, 255
before := src.Pix[0] - src.Pix[1]
out := applyColor(src, ColorParams{Saturation: 100})
if out.Pix[0]-out.Pix[1] <= before {
t.Fatalf("saturation did not spread channels: %d/%d/%d", out.Pix[0], out.Pix[1], out.Pix[2])
}
}
func TestApplyColorGradingTintsShadows(t *testing.T) {
src := image.NewNRGBA(image.Rect(0, 0, 1, 1))
src.Pix[0], src.Pix[1], src.Pix[2], src.Pix[3] = 40, 40, 40, 255
p := ColorParams{}
p.Grading.Blending = 50
p.Grading.Shadows = ColorWheel{Hue: 240, Saturation: 100}
out := applyColor(src, p)
if out.Pix[2] <= out.Pix[0] {
t.Fatalf("blue shadow grading = %d/%d/%d, want b > r", out.Pix[0], out.Pix[1], out.Pix[2])
}
}
func TestApplyColorGradingLuminance(t *testing.T) {
src := image.NewNRGBA(image.Rect(0, 0, 1, 1))
src.Pix[0], src.Pix[1], src.Pix[2], src.Pix[3] = 40, 40, 40, 255
p := ColorParams{}
p.Grading.Shadows = ColorWheel{Luminance: 100}
out := applyColor(src, p)
if out.Pix[0] <= 40 {
t.Fatalf("shadow luminance did not brighten: %d", out.Pix[0])
}
}
func TestApplyColorUniformRows(t *testing.T) {
src := image.NewNRGBA(image.Rect(0, 0, 64, 64))
for i := 0; i < len(src.Pix); i += 4 {
src.Pix[i], src.Pix[i+1], src.Pix[i+2], src.Pix[i+3] = 40, 40, 40, 255
}
p := ColorParams{}
p.Grading.Blending = 50
p.Grading.Shadows = ColorWheel{Hue: 240, Saturation: 100}
out := applyColor(src, p)
wantR, wantG, wantB := out.Pix[0], out.Pix[1], out.Pix[2]
for y := 0; y < 64; y++ {
for x := 0; x < 64; x++ {
i := y*out.Stride + x*4
if out.Pix[i] != wantR || out.Pix[i+1] != wantG || out.Pix[i+2] != wantB {
t.Fatalf("pixel (%d,%d) = %d/%d/%d, want %d/%d/%d", x, y, out.Pix[i], out.Pix[i+1], out.Pix[i+2], wantR, wantG, wantB)
}
}
}
}
func TestApplyColorParallelMatchesSingle(t *testing.T) {
makeImage := func() *image.NRGBA {
img := image.NewNRGBA(image.Rect(0, 0, 32, 64))
for y := 0; y < 64; y++ {
for x := 0; x < 32; x++ {
i := y*img.Stride + x*4
img.Pix[i] = uint8(20 + y*3)
img.Pix[i+1] = uint8(20 + y*2)
img.Pix[i+2] = uint8(30 + y)
img.Pix[i+3] = 255
}
}
return img
}
p := ColorParams{}
p.Grading.Blending = 50
p.Grading.Shadows = ColorWheel{Hue: 240, Saturation: 100}
parallel := applyColor(makeImage(), p)
single := makeImage()
applyColorRows(single, 0, single.Rect.Dy(), newColorAdjuster(p))
for i := range parallel.Pix {
if parallel.Pix[i] != single.Pix[i] {
t.Fatalf("parallel differs at byte %d: %d != %d", i, parallel.Pix[i], single.Pix[i])
}
}
}
func TestApplyColorKeepsTransparentPixels(t *testing.T) {
src := image.NewNRGBA(image.Rect(0, 0, 1, 1))
src.Pix[0], src.Pix[1], src.Pix[2], src.Pix[3] = 10, 20, 30, 0
out := applyColor(src, ColorParams{Saturation: 100, Temperature: 100})
if out.Pix[0] != 10 || out.Pix[1] != 20 || out.Pix[2] != 30 || out.Pix[3] != 0 {
t.Fatalf("transparent pixel changed: %v", out.Pix)
}
}
func TestParseEditParamsWithoutColorIsBackwardCompatible(t *testing.T) {
params, err := ParseEditParams([]byte(`{"light":{"exposure":0.5}}`))
if err != nil {
t.Fatalf("parse: %v", err)
}
if !params.Color.IsEmpty() {
t.Fatalf("missing color must be empty: %+v", params.Color)
}
if params.IsEmpty() {
t.Fatal("light edits must not be empty")
}
}
func TestApplyColorEmptyIsIdentity(t *testing.T) {
src := image.NewNRGBA(image.Rect(0, 0, 3, 1))
colors := [][3]uint8{{0, 0, 0}, {200, 50, 25}, {33, 210, 128}}
for i, c := range colors {
src.Pix[i*4] = c[0]
src.Pix[i*4+1] = c[1]
src.Pix[i*4+2] = c[2]
src.Pix[i*4+3] = 255
}
before := make([]byte, len(src.Pix))
copy(before, src.Pix)
applyColor(src, ColorParams{})
for i := range before {
if before[i] != src.Pix[i] {
t.Fatalf("empty color changed pixel %d: %d != %d", i, src.Pix[i], before[i])
}
}
}
+659
View File
@@ -0,0 +1,659 @@
package photos
import (
"image"
"math"
"runtime"
"sync"
"github.com/disintegration/imaging"
)
// Spatial effects of the non-destructive editor. They run after the light and
// color adjustments, in a fixed order: dehaze, texture, clarity, vignette,
// grain. Texture and clarity compute a correction from the luminance and add it
// to all three channels equally, so hue and saturation are preserved; dehaze is
// a global tonal correction based on the dark channel prior. Vignette and grain
// are the final, "post-crop" operations.
//
// Everything here is deterministic: the grain seed comes from the photo id, so
// a repeated render of the same parameters produces the same pixels.
// maxDehazeSide is the longest side of the reduced copy used to estimate the
// atmosphere and the transmission map.
const maxDehazeSide = 512
// dehazeOmega is the share of the haze the dark channel prior removes.
const dehazeOmega = 0.95
// dehazeMinT bounds the transmission map from below, so the darkest regions do
// not amplify noise without limit.
const dehazeMinT = 0.1
// applyEffects applies the non-empty effect passes in the documented order and
// returns the image owned by the caller.
func applyEffects(dst *image.NRGBA, p EffectsParams, seed uint64) *image.NRGBA {
if p.Dehaze != 0 {
dst = applyDehaze(dst, p.Dehaze)
}
if p.Texture != 0 {
applyTexture(dst, p.Texture)
}
if p.Clarity != 0 {
applyClarity(dst, p.Clarity)
}
if p.Vignette.Amount != 0 {
applyVignette(dst, p.Vignette)
}
if p.Grain.Amount != 0 {
applyGrain(dst, p.Grain, seed)
}
return dst
}
// luminance returns the perceived brightness Y of an RGB pixel (each 0..255).
func luminance(r, g, b float64) float64 {
return 0.299*r + 0.587*g + 0.114*b
}
// lumaPlane builds a Y plane of the image, one byte per pixel.
func lumaPlane(img *image.NRGBA) []uint8 {
w, h := img.Rect.Dx(), img.Rect.Dy()
out := make([]uint8, w*h)
parallelChunks(h, func(from, to int) {
for y := from; y < to; y++ {
row := img.Pix[y*img.Stride : y*img.Stride+w*4]
dst := out[y*w : (y+1)*w]
for x := 0; x < w; x++ {
i := x * 4
dst[x] = uint8(luminance(float64(row[i]), float64(row[i+1]), float64(row[i+2])) + 0.5)
}
}
})
return out
}
// parallelChunks splits n independent items (rows or columns) into chunks and
// runs fn over each chunk, mirroring the row parallelism of applyLight and
// applyColor.
func parallelChunks(n int, fn func(from, to int)) {
if n <= 0 {
return
}
workers := runtime.GOMAXPROCS(0)
if workers > n {
workers = n
}
if workers <= 1 {
fn(0, n)
return
}
chunk := (n + workers - 1) / workers
var wg sync.WaitGroup
for from := 0; from < n; from += chunk {
to := from + chunk
if to > n {
to = n
}
wg.Add(1)
go func(from, to int) {
defer wg.Done()
fn(from, to)
}(from, to)
}
wg.Wait()
}
// boxBlur applies one separable box blur with edge-clamped borders. The running
// window makes the cost independent of the radius. Edge pixels repeat the
// nearest border value, so the size of the image never changes.
func boxBlur(src []uint8, w, h, radius int) []uint8 {
if w <= 0 || h <= 0 || len(src) < w*h {
return nil
}
out := make([]uint8, w*h)
if radius <= 0 {
copy(out, src[:w*h])
return out
}
tmp := make([]uint8, w*h)
blurHorizontal(src, tmp, w, h, radius)
blurVertical(tmp, out, w, h, radius)
return out
}
// boxBlur3 approximates a Gaussian blur with three box passes.
func boxBlur3(src []uint8, w, h, radius int) []uint8 {
out := boxBlur(src, w, h, radius)
out = boxBlur(out, w, h, radius)
return boxBlur(out, w, h, radius)
}
// blurHorizontal is one horizontal box-blur pass with a sliding window.
func blurHorizontal(src, dst []uint8, w, h, radius int) {
window := 2*radius + 1
parallelChunks(h, func(from, to int) {
for y := from; y < to; y++ {
row := src[y*w : (y+1)*w]
out := dst[y*w : (y+1)*w]
var sum int
for k := -radius; k <= radius; k++ {
sum += int(row[clampInt(k, 0, w-1)])
}
for x := 0; x < w; x++ {
out[x] = uint8((sum + window/2) / window)
sum -= int(row[clampInt(x-radius, 0, w-1)])
sum += int(row[clampInt(x+radius+1, 0, w-1)])
}
}
})
}
// blurVertical is one vertical box-blur pass with a sliding window. Columns are
// independent, so they are split into chunks just like rows.
func blurVertical(src, dst []uint8, w, h, radius int) {
window := 2*radius + 1
parallelChunks(w, func(from, to int) {
for x := from; x < to; x++ {
var sum int
for k := -radius; k <= radius; k++ {
sum += int(src[clampInt(k, 0, h-1)*w+x])
}
for y := 0; y < h; y++ {
dst[y*w+x] = uint8((sum + window/2) / window)
sum -= int(src[clampInt(y-radius, 0, h-1)*w+x])
sum += int(src[clampInt(y+radius+1, 0, h-1)*w+x])
}
}
})
}
// addLumaDelta adds the same delta to the three color channels of one pixel.
// Transparent pixels are left untouched by the callers.
func addLumaDelta(row []uint8, i int, delta float64) {
row[i] = clampChannel(float64(row[i]) + delta)
row[i+1] = clampChannel(float64(row[i+1]) + delta)
row[i+2] = clampChannel(float64(row[i+2]) + delta)
}
// clampChannel rounds and clamps a channel value to 0..255.
func clampChannel(v float64) uint8 {
return uint8(clampFloat(v+0.5, 0, 255))
}
// applyTexture is an unsharp mask with a small radius: it boosts (or, for a
// negative amount, smooths) the high-frequency detail of the luminance.
func applyTexture(dst *image.NRGBA, amount float64) {
w, h := dst.Rect.Dx(), dst.Rect.Dy()
if w == 0 || h == 0 {
return
}
y := lumaPlane(dst)
radius := int(math.Round(0.0015 * float64(min(w, h))))
if radius < 1 {
radius = 1
}
blur := boxBlur3(y, w, h, radius)
k := amount / 100
parallelChunks(h, func(from, to int) {
for row := from; row < to; row++ {
pix := dst.Pix[row*dst.Stride : row*dst.Stride+w*4]
base := row * w
for x := 0; x < w; x++ {
i := x * 4
if pix[i+3] == 0 {
continue
}
delta := k * (float64(y[base+x]) - float64(blur[base+x]))
addLumaDelta(pix, i, delta)
}
}
})
}
// applyClarity is an unsharp mask with a large radius. The correction is
// limited to +-40 levels and weighted by the midtone mask, which keeps the
// edges of contrasty objects from ringing.
func applyClarity(dst *image.NRGBA, amount float64) {
w, h := dst.Rect.Dx(), dst.Rect.Dy()
if w == 0 || h == 0 {
return
}
y := lumaPlane(dst)
radius := int(math.Round(0.008 * float64(min(w, h))))
if radius < 2 {
radius = 2
}
blur := boxBlur3(y, w, h, radius)
k := amount / 100 * 1.25
parallelChunks(h, func(from, to int) {
for row := from; row < to; row++ {
pix := dst.Pix[row*dst.Stride : row*dst.Stride+w*4]
base := row * w
for x := 0; x < w; x++ {
i := x * 4
if pix[i+3] == 0 {
continue
}
yVal := float64(y[base+x])
d := clampFloat(yVal-float64(blur[base+x]), -40, 40)
t := math.Abs(2*yVal/255 - 1)
weight := 1 - 0.6*t*t
addLumaDelta(pix, i, k*d*weight)
}
}
})
}
// applyDehaze removes (positive amount) or adds (negative amount) haze with the
// dark channel prior. The atmosphere and the transmission map are estimated on
// a reduced copy, then the map is interpolated back to the full frame.
func applyDehaze(dst *image.NRGBA, amount float64) *image.NRGBA {
w, h := dst.Rect.Dx(), dst.Rect.Dy()
if w == 0 || h == 0 {
return dst
}
small := dst
sw, sh := w, h
if max(w, h) > maxDehazeSide {
scale := float64(maxDehazeSide) / float64(max(w, h))
sw = max(1, int(math.Round(float64(w)*scale)))
sh = max(1, int(math.Round(float64(h)*scale)))
small = imaging.Resize(dst, sw, sh, imaging.Linear)
}
sw, sh = small.Rect.Dx(), small.Rect.Dy()
dark := darkChannel(small)
atmosphere := atmosphericLight(small, dark)
tMap := make([]uint8, sw*sh)
for y := 0; y < sh; y++ {
row := small.Pix[y*small.Stride : y*small.Stride+sw*4]
for x := 0; x < sw; x++ {
i := x * 4
transmission := 1 - dehazeOmega*min(
float64(row[i])/atmosphere[0],
min(float64(row[i+1])/atmosphere[1], float64(row[i+2])/atmosphere[2]))
transmission = clampFloat(transmission, dehazeMinT, 1)
tMap[y*sw+x] = uint8(transmission*255 + 0.5)
}
}
tRadius := int(math.Round(0.02 * float64(min(sw, sh))))
if tRadius < 1 {
tRadius = 1
}
tMap = boxBlur3(tMap, sw, sh, tRadius)
fullT := tMap
if sw != w || sh != h {
gray := image.NewGray(image.Rect(0, 0, sw, sh))
copy(gray.Pix, tMap)
fullT = resizeTransmission(gray, w, h)
}
k := amount / 100
if amount > 0 {
parallelChunks(h, func(from, to int) {
for row := from; row < to; row++ {
pix := dst.Pix[row*dst.Stride : row*dst.Stride+w*4]
base := row * w
for x := 0; x < w; x++ {
i := x * 4
if pix[i+3] == 0 {
continue
}
t := float64(fullT[base+x]) / 255
if t < dehazeMinT {
t = dehazeMinT
}
for c := 0; c < 3; c++ {
in := float64(pix[i+c])
clear := (in-atmosphere[c])/t + atmosphere[c]
pix[i+c] = clampChannel(in + k*(clear-in))
}
}
}
})
return dst
}
// Negative amount adds haze: the frame moves toward the atmosphere color
// and loses contrast.
haze := -k
parallelChunks(h, func(from, to int) {
for row := from; row < to; row++ {
pix := dst.Pix[row*dst.Stride : row*dst.Stride+w*4]
for x := 0; x < w; x++ {
i := x * 4
if pix[i+3] == 0 {
continue
}
for c := 0; c < 3; c++ {
in := float64(pix[i+c])
pix[i+c] = clampChannel(in*(1-0.75*haze) + atmosphere[c]*0.75*haze)
}
}
}
})
return dst
}
// darkChannel returns the per-pixel minimum of the RGB channels.
func darkChannel(img *image.NRGBA) []uint8 {
w, h := img.Rect.Dx(), img.Rect.Dy()
out := make([]uint8, w*h)
parallelChunks(h, func(from, to int) {
for y := from; y < to; y++ {
row := img.Pix[y*img.Stride : y*img.Stride+w*4]
dst := out[y*w : (y+1)*w]
for x := 0; x < w; x++ {
i := x * 4
v := row[i]
if row[i+1] < v {
v = row[i+1]
}
if row[i+2] < v {
v = row[i+2]
}
dst[x] = v
}
}
})
return out
}
// atmosphericLight estimates the color of the haze: the average RGB of the
// pixels whose dark channel is above the 99.9th percentile, at least one pixel
// and never below one per channel.
func atmosphericLight(img *image.NRGBA, dark []uint8) [3]float64 {
var atmosphere [3]float64
if len(dark) == 0 {
return [3]float64{1, 1, 1}
}
var hist [256]int
maxDark := 0
for _, v := range dark {
hist[v]++
if int(v) > maxDark {
maxDark = int(v)
}
}
target := int(math.Ceil(0.999 * float64(len(dark))))
if target < 1 {
target = 1
}
threshold := maxDark
cumulative := 0
for v := 0; v < 256; v++ {
cumulative += hist[v]
if cumulative >= target {
threshold = v
break
}
}
w, h := img.Rect.Dx(), img.Rect.Dy()
var sum [3]float64
count := 0
add := func(x, y int) {
i := y*img.Stride + x*4
sum[0] += float64(img.Pix[i])
sum[1] += float64(img.Pix[i+1])
sum[2] += float64(img.Pix[i+2])
count++
}
for y := 0; y < h; y++ {
for x := 0; x < w; x++ {
if int(dark[y*w+x]) > threshold {
add(x, y)
}
}
}
if count == 0 {
// A uniform dark channel has no pixel strictly above the threshold:
// the brightest pixel still is the best atmosphere estimate.
found := false
for y := 0; y < h && !found; y++ {
for x := 0; x < w; x++ {
if int(dark[y*w+x]) == maxDark {
add(x, y)
found = true
break
}
}
}
}
for c := 0; c < 3; c++ {
atmosphere[c] = 1
if count > 0 {
atmosphere[c] = math.Max(1, sum[c]/float64(count))
}
}
return atmosphere
}
// resizeTransmission upsamples the gray transmission map to the full frame.
// imaging.Resize returns an NRGBA image, so the gray value is the first byte of
// every pixel; slicing its Pix by w*h would read only the first quarter of the
// frame, hence the explicit per-pixel copy.
func resizeTransmission(gray *image.Gray, w, h int) []uint8 {
resized := imaging.Resize(gray, w, h, imaging.Linear)
out := make([]uint8, w*h)
for i := range out {
out[i] = resized.Pix[i*4]
}
return out
}
// applyVignette darkens, brightens, tints or fills the edges of the frame. The
// geometry is normalized to the half-frame: roundness turns the ellipse into a
// rounded rectangle, midpoint sets where the zone starts and feather sets how
// soft the transition is.
func applyVignette(dst *image.NRGBA, v VignetteParams) {
w, h := dst.Rect.Dx(), dst.Rect.Dy()
if w == 0 || h == 0 || v.Amount == 0 {
return
}
exponent := 2 * math.Pow(6, v.Roundness/100)
invExponent := 1 / exponent
start := 0.15 + 0.85*v.Midpoint/100
featherWidth := 0.02 + 0.48*v.Feather/100
xTerms := make([]float64, w)
for x := 0; x < w; x++ {
dx := (float64(x)+0.5)/float64(w)*2 - 1
xTerms[x] = math.Pow(math.Abs(dx), exponent)
}
yTerms := make([]float64, h)
for y := 0; y < h; y++ {
dy := (float64(y)+0.5)/float64(h)*2 - 1
yTerms[y] = math.Pow(math.Abs(dy), exponent)
}
amount := v.Amount / 100
tintR, tintG, tintB := parseHexRGB(v.Color)
tintY := luminance(tintR, tintG, tintB)
highlights := v.Highlights / 100
mode := v.Mode
if mode != VignetteColor && mode != VignetteColorize {
mode = VignetteLight
}
parallelChunks(h, func(from, to int) {
for row := from; row < to; row++ {
pix := dst.Pix[row*dst.Stride : row*dst.Stride+w*4]
termY := yTerms[row]
for x := 0; x < w; x++ {
i := x * 4
if pix[i+3] == 0 {
continue
}
distance := math.Pow(xTerms[x]+termY, invExponent)
mask := smoothstep(start, start+featherWidth, distance)
if mask == 0 {
continue
}
yVal := luminance(float64(pix[i]), float64(pix[i+1]), float64(pix[i+2]))
highlightFactor := highlights * smoothstep(0.5, 1, yVal/255)
switch mode {
case VignetteColor:
strength := math.Abs(amount) * mask * (1 - highlightFactor)
if strength == 0 {
continue
}
targetR := tintR - tintY + yVal
targetG := tintG - tintY + yVal
targetB := tintB - tintY + yVal
pix[i] = clampChannel(float64(pix[i]) + (targetR-float64(pix[i]))*strength)
pix[i+1] = clampChannel(float64(pix[i+1]) + (targetG-float64(pix[i+1]))*strength)
pix[i+2] = clampChannel(float64(pix[i+2]) + (targetB-float64(pix[i+2]))*strength)
case VignetteColorize:
strength := math.Abs(amount) * mask * (1 - highlightFactor)
if strength == 0 {
continue
}
pix[i] = clampChannel(float64(pix[i]) + (tintR-float64(pix[i]))*strength)
pix[i+1] = clampChannel(float64(pix[i+1]) + (tintG-float64(pix[i+1]))*strength)
pix[i+2] = clampChannel(float64(pix[i+2]) + (tintB-float64(pix[i+2]))*strength)
default:
factor := 1 - amount*0.85*mask
factor += (1 - factor) * highlightFactor * mask
pix[i] = clampChannel(float64(pix[i]) * factor)
pix[i+1] = clampChannel(float64(pix[i+1]) * factor)
pix[i+2] = clampChannel(float64(pix[i+2]) * factor)
}
}
}
})
}
// smoothstep is the Hermite ramp between the two edges, clamped to 0..1.
func smoothstep(edge0, edge1, x float64) float64 {
if edge1 <= edge0 {
if x < edge1 {
return 0
}
return 1
}
t := clamp01((x - edge0) / (edge1 - edge0))
return t * t * (3 - 2*t)
}
// parseHexRGB decodes a "#rrggbb" color. An unusable color reads as black.
func parseHexRGB(color string) (float64, float64, float64) {
if len(color) != 7 || color[0] != '#' {
return 0, 0, 0
}
var rgb [3]float64
for c := 0; c < 3; c++ {
hi := hexNibble(color[1+c*2])
lo := hexNibble(color[2+c*2])
if hi < 0 || lo < 0 {
return 0, 0, 0
}
rgb[c] = float64(hi*16 + lo)
}
return rgb[0], rgb[1], rgb[2]
}
// hexNibble decodes one hexadecimal digit, or -1 for an invalid character.
func hexNibble(c byte) int {
switch {
case c >= '0' && c <= '9':
return int(c - '0')
case c >= 'a' && c <= 'f':
return int(c-'a') + 10
case c >= 'A' && c <= 'F':
return int(c-'A') + 10
}
return -1
}
// Grain noise is a pure function of the pixel coordinates and the seed. Using
// the splitmix64 finalizer as a hash (instead of a stateful sequence) keeps the
// noise independent of the row order, so the row-parallel render is bit-for-bit
// reproducible.
const (
grainSaltValue uint64 = 0x9e3779b97f4a7c15
grainSaltWhite uint64 = 0xd1b54a32d192ed03
)
// mix64 is the splitmix64 finalizer.
func mix64(x uint64) uint64 {
x += 0x9e3779b97f4a7c15
x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9
x = (x ^ (x >> 27)) * 0x94d049bb133111eb
return x ^ (x >> 31)
}
// hashSigned maps a seed, a salt and integer coordinates to [-1, 1].
func hashSigned(seed, salt uint64, x, y int) float64 {
z := seed ^ salt
z ^= uint64(x) * 0x9e3779b97f4a7c15
z ^= uint64(y) * 0xc2b2ae3d27d4eb4f
h := mix64(z)
return float64(h>>11)/float64(uint64(1)<<53)*2 - 1
}
// applyGrain adds a deterministic luminance noise. Size sets the cell of the
// smooth value noise and roughness mixes it with the per-pixel white noise; the
// weight fades the noise out of the darkest and brightest tones.
func applyGrain(dst *image.NRGBA, g GrainParams, seed uint64) {
w, h := dst.Rect.Dx(), dst.Rect.Dy()
if w == 0 || h == 0 || g.Amount == 0 {
return
}
cell := int(math.Round((0.0005 + 0.004*g.Size/100) * float64(min(w, h))))
if cell < 1 {
cell = 1
}
gridW := (w-1)/cell + 2
gridH := (h-1)/cell + 2
grid := make([]float64, gridW*gridH)
for gy := 0; gy < gridH; gy++ {
for gx := 0; gx < gridW; gx++ {
grid[gy*gridW+gx] = hashSigned(seed, grainSaltValue, gx, gy)
}
}
roughness := g.Roughness / 100
smoothWeight := 1 - roughness
strength := g.Amount / 100 * 38
parallelChunks(h, func(from, to int) {
for row := from; row < to; row++ {
pix := dst.Pix[row*dst.Stride : row*dst.Stride+w*4]
gy := row / cell
fy := float64(row-gy*cell) / float64(cell)
vy := smoothstep(0, 1, fy)
for x := 0; x < w; x++ {
i := x * 4
if pix[i+3] == 0 {
continue
}
gx := x / cell
fx := float64(x-gx*cell) / float64(cell)
vx := smoothstep(0, 1, fx)
a := grid[gy*gridW+gx]
b := grid[gy*gridW+gx+1]
c := grid[(gy+1)*gridW+gx]
d := grid[(gy+1)*gridW+gx+1]
top := a + (b-a)*vx
bottom := c + (d-c)*vx
value := top + (bottom-top)*vy
white := hashSigned(seed, grainSaltWhite, x, row)
noise := value*smoothWeight + white*roughness
yVal := luminance(float64(pix[i]), float64(pix[i+1]), float64(pix[i+2]))
t := 2*yVal/255 - 1
weight := 1 - t*t
addLumaDelta(pix, i, noise*strength*weight)
}
}
})
}
+708
View File
@@ -0,0 +1,708 @@
package photos
import (
"bytes"
"encoding/json"
"image"
"math"
"reflect"
"testing"
"github.com/disintegration/imaging"
)
func TestEffectsParams(t *testing.T) {
t.Run("defaults", func(t *testing.T) {
got := (EffectsParams{}).Normalized()
if got.Texture != 0 || got.Clarity != 0 || got.Dehaze != 0 {
t.Fatalf("strengths changed: %+v", got)
}
v := got.Vignette
if v.Mode != VignetteLight || v.Midpoint != DefaultVignetteMidpoint ||
v.Feather != DefaultVignetteFeather || v.Roundness != 0 || v.Highlights != 0 ||
v.Color != DefaultVignetteColor || v.Amount != 0 {
t.Fatalf("vignette defaults = %+v", v)
}
g := got.Grain
if g.Amount != 0 || g.Size != DefaultGrainSize || g.Roughness != DefaultGrainRoughness {
t.Fatalf("grain defaults = %+v", g)
}
})
t.Run("clamps", func(t *testing.T) {
got := EffectsParams{
Texture: 250,
Clarity: -250,
Dehaze: 150,
Vignette: VignetteParams{
Mode: "sepia", Amount: -150, Midpoint: 150, Feather: 150,
Roundness: -150, Highlights: 150, Color: "#AABBCC",
},
Grain: GrainParams{Amount: 150, Size: 150, Roughness: 150},
}.Normalized()
if got.Texture != MaxPercent || got.Clarity != -MaxPercent || got.Dehaze != MaxPercent {
t.Fatalf("strengths = %v/%v/%v, want clamped", got.Texture, got.Clarity, got.Dehaze)
}
v := got.Vignette
if v.Mode != VignetteLight {
t.Fatalf("unknown mode = %q, want %q", v.Mode, VignetteLight)
}
if v.Amount != -MaxPercent || v.Midpoint != MaxPercent || v.Feather != MaxPercent ||
v.Roundness != -MaxPercent || v.Highlights != MaxPercent {
t.Fatalf("vignette not clamped: %+v", v)
}
if v.Color != "#aabbcc" {
t.Fatalf("color = %q, want lower-case", v.Color)
}
if got.Grain.Amount != MaxPercent || got.Grain.Size != MaxPercent || got.Grain.Roughness != MaxPercent {
t.Fatalf("grain not clamped: %+v", got.Grain)
}
})
t.Run("modes and colors", func(t *testing.T) {
cases := []struct {
mode, want string
}{
{"", VignetteLight},
{"light", VignetteLight},
{"LIGHT", VignetteLight},
{"color", VignetteColor},
{"Colorize", VignetteColorize},
{"unknown", VignetteLight},
}
for _, tc := range cases {
if got := (VignetteParams{Mode: tc.mode}).Normalized().Mode; got != tc.want {
t.Fatalf("mode %q = %q, want %q", tc.mode, got, tc.want)
}
}
colors := []struct {
in, want string
}{
{"#A1B2C3", "#a1b2c3"},
{"#abcdef", "#abcdef"},
{"#12345", DefaultVignetteColor},
{"#gggggg", DefaultVignetteColor},
{"aabbcc", DefaultVignetteColor},
{"red", DefaultVignetteColor},
{"", DefaultVignetteColor},
}
for _, tc := range colors {
if got := normalizeHexColor(tc.in); got != tc.want {
t.Fatalf("color %q = %q, want %q", tc.in, got, tc.want)
}
}
})
t.Run("idempotent", func(t *testing.T) {
p := EffectsParams{
Texture: 12.5, Clarity: -8, Dehaze: 33,
Vignette: VignetteParams{Mode: "COLOR", Amount: -25, Midpoint: 40, Feather: 70, Roundness: 20, Highlights: 10, Color: "#FF8000"},
Grain: GrainParams{Amount: 45, Size: 33, Roughness: 66},
}
once := p.Normalized()
twice := once.Normalized()
if !reflect.DeepEqual(once, twice) {
t.Fatalf("normalization is not idempotent:\n once = %+v\ntwice = %+v", once, twice)
}
})
t.Run("is empty", func(t *testing.T) {
cases := []struct {
name string
p EffectsParams
empty bool
}{
{"zero", EffectsParams{}, true},
{
"geometry only",
EffectsParams{
Vignette: VignetteParams{
Mode: VignetteColor, Midpoint: 20, Feather: 80,
Roundness: 40, Highlights: 50, Color: "#ff0000",
},
Grain: GrainParams{Size: 90, Roughness: 90},
},
true,
},
{"texture", EffectsParams{Texture: 1}, false},
{"clarity", EffectsParams{Clarity: -1}, false},
{"dehaze", EffectsParams{Dehaze: 1}, false},
{"vignette", EffectsParams{Vignette: VignetteParams{Amount: -1}}, false},
{"grain", EffectsParams{Grain: GrainParams{Amount: 1}}, false},
}
for _, tc := range cases {
if got := tc.p.IsEmpty(); got != tc.empty {
t.Fatalf("%s: IsEmpty = %v, want %v", tc.name, got, tc.empty)
}
}
})
t.Run("explicit zero geometry", func(t *testing.T) {
// An explicit zero is a valid geometry value and must survive both
// parsing and normalization; omitted fields still get the defaults.
p, err := ParseEditParams([]byte(`{"effects":{"vignette":{"mode":"light","amount":10,"midpoint":0,"feather":0},"grain":{"amount":10,"size":0,"roughness":0}}}`))
if err != nil {
t.Fatalf("parse explicit zero: %v", err)
}
if p.Effects.Vignette.Midpoint != 0 || p.Effects.Vignette.Feather != 0 {
t.Fatalf("explicit zero vignette geometry was defaulted: %+v", p.Effects.Vignette)
}
if p.Effects.Grain.Size != 0 || p.Effects.Grain.Roughness != 0 {
t.Fatalf("explicit zero grain geometry was defaulted: %+v", p.Effects.Grain)
}
omitted, err := ParseEditParams([]byte(`{"effects":{"vignette":{"amount":10},"grain":{"amount":10}}}`))
if err != nil {
t.Fatalf("parse omitted: %v", err)
}
if omitted.Effects.Vignette.Midpoint != DefaultVignetteMidpoint ||
omitted.Effects.Vignette.Feather != DefaultVignetteFeather ||
omitted.Effects.Grain.Size != DefaultGrainSize ||
omitted.Effects.Grain.Roughness != DefaultGrainRoughness {
t.Fatalf("omitted geometry was not defaulted: %+v", omitted.Effects)
}
})
t.Run("json", func(t *testing.T) {
p := EditParams{Effects: EffectsParams{Dehaze: 10}}
data := p.JSON()
var raw map[string]json.RawMessage
if err := json.Unmarshal(data, &raw); err != nil {
t.Fatalf("unmarshal: %v", err)
}
if _, ok := raw["effects"]; !ok {
t.Fatalf("effects key missing from %s", data)
}
var effects EffectsParams
if err := json.Unmarshal(raw["effects"], &effects); err != nil {
t.Fatalf("unmarshal effects: %v", err)
}
if effects.Dehaze != 10 {
t.Fatalf("dehaze = %v, want 10", effects.Dehaze)
}
var body string
if err := json.Unmarshal(data, &body); err == nil {
t.Fatalf("unexpected string body %q", body)
}
})
t.Run("edit params count effects", func(t *testing.T) {
if (EditParams{Effects: EffectsParams{Texture: 1}}).IsEmpty() {
t.Fatal("params with texture must not be empty")
}
if (EditParams{Effects: EffectsParams{Vignette: VignetteParams{Mode: VignetteColor}}}).IsEmpty() != true {
t.Fatal("vignette defaults without strength must count as empty")
}
})
}
func TestEditParamsLegacy(t *testing.T) {
empty, err := ParseEditParams([]byte(`{}`))
if err != nil {
t.Fatalf("parse empty: %v", err)
}
if !empty.IsEmpty() || !empty.Effects.IsEmpty() {
t.Fatalf("empty params = %+v", empty)
}
if empty.Effects.Vignette.Midpoint != DefaultVignetteMidpoint ||
empty.Effects.Vignette.Color != DefaultVignetteColor ||
empty.Effects.Grain.Size != DefaultGrainSize {
t.Fatalf("legacy defaults not filled: %+v", empty.Effects)
}
legacy, err := ParseEditParams([]byte(`{"light":{"exposure":0.4},"color":{"temperature":15,"saturation":10}}`))
if err != nil {
t.Fatalf("parse legacy: %v", err)
}
if legacy.IsEmpty() {
t.Fatal("legacy light/color params must not be empty")
}
if !legacy.Effects.IsEmpty() {
t.Fatalf("params without effects key read as effects: %+v", legacy.Effects)
}
// The old pipeline (light, then color) renders exactly the same pixels when
// the parameters carry no effects.
src := gradientImage(16, 12)
data := mustEncodePNG(t, src)
got, err := decodeAndAdjust(data, legacy, editSeed("legacy"))
if err != nil {
t.Fatalf("decode and adjust: %v", err)
}
decoded, err := imaging.Decode(bytes.NewReader(data), imaging.AutoOrientation(true))
if err != nil {
t.Fatalf("decode: %v", err)
}
want := applyColor(applyLight(decoded, legacy.Light), legacy.Color)
if !bytes.Equal(got.Pix, want.Pix) {
t.Fatal("legacy render changed when effects are absent")
}
// An untouched photo decodes to the original pixels.
plain, err := decodeAndAdjust(data, EditParams{}, editSeed("legacy"))
if err != nil {
t.Fatalf("decode and adjust untouched: %v", err)
}
if !bytes.Equal(plain.Pix, imaging.Clone(decoded).Pix) {
t.Fatal("empty params changed the original")
}
}
func TestBoxBlur(t *testing.T) {
if got := boxBlur([]uint8{1, 2, 3, 4}, 2, 2, 0); !bytes.Equal(got, []uint8{1, 2, 3, 4}) {
t.Fatalf("radius 0 = %v, want identity", got)
}
constant := make([]uint8, 9*7)
for i := range constant {
constant[i] = 77
}
blurred := boxBlur3(constant, 9, 7, 3)
for i, v := range blurred {
if v != 77 {
t.Fatalf("constant image changed at %d: %d", i, v)
}
}
w, h := 13, 9
src := make([]uint8, w*h)
for y := 0; y < h; y++ {
for x := 0; x < w; x++ {
src[y*w+x] = uint8((x*37 + y*61) % 256)
}
}
for _, radius := range []int{1, 2, 5} {
if want, got := naiveBoxPass(src, w, h, radius), boxBlur(src, w, h, radius); !bytes.Equal(got, want) {
t.Fatalf("radius %d: boxBlur = %v, want %v", radius, got, want)
}
want := src
for i := 0; i < 3; i++ {
want = naiveBoxPass(want, w, h, radius)
}
if got := boxBlur3(src, w, h, radius); !bytes.Equal(got, want) {
t.Fatalf("radius %d: boxBlur3 = %v, want %v", radius, got, want)
}
}
// A one-pixel image is a fixed point of any radius.
if got := boxBlur3([]uint8{42}, 1, 1, 4); len(got) != 1 || got[0] != 42 {
t.Fatalf("1x1 blur = %v, want [42]", got)
}
}
// naiveBoxPass is the reference implementation of one box-blur pass: the
// window is sampled explicitly with edge-clamped coordinates.
func naiveBoxPass(src []uint8, w, h, radius int) []uint8 {
window := 2*radius + 1
tmp := make([]uint8, w*h)
for y := 0; y < h; y++ {
for x := 0; x < w; x++ {
sum := 0
for kx := -radius; kx <= radius; kx++ {
sum += int(src[y*w+clampInt(x+kx, 0, w-1)])
}
tmp[y*w+x] = uint8((sum + window/2) / window)
}
}
out := make([]uint8, w*h)
for y := 0; y < h; y++ {
for x := 0; x < w; x++ {
sum := 0
for ky := -radius; ky <= radius; ky++ {
sum += int(tmp[clampInt(y+ky, 0, h-1)*w+x])
}
out[y*w+x] = uint8((sum + window/2) / window)
}
}
return out
}
func TestTextureClarity(t *testing.T) {
src := checkerImage(64, 64, 96, 160)
base := lumaLocalVariance(src)
for _, effect := range []string{"texture", "clarity"} {
up := applyEffects(imaging.Clone(src), strengths(effect, 100), 1)
down := applyEffects(imaging.Clone(src), strengths(effect, -100), 1)
if got := lumaLocalVariance(up); got <= base {
t.Fatalf("%s +100: local variance %v must grow above %v", effect, got, base)
}
if got := lumaLocalVariance(down); got >= base {
t.Fatalf("%s -100: local variance %v must drop below %v", effect, got, base)
}
}
}
// lumaLocalVariance is the average variance of the luminance inside a 3x3
// window: the property that texture and clarity change.
func lumaLocalVariance(img *image.NRGBA) float64 {
plane := lumaPlane(img)
w, h := img.Rect.Dx(), img.Rect.Dy()
var total float64
count := 0
for y := 1; y < h-1; y++ {
for x := 1; x < w-1; x++ {
var sum, sumSq float64
for dy := -1; dy <= 1; dy++ {
for dx := -1; dx <= 1; dx++ {
v := float64(plane[(y+dy)*w+x+dx])
sum += v
sumSq += v * v
}
}
mean := sum / 9
total += sumSq/9 - mean*mean
count++
}
}
return total / float64(count)
}
// strengths builds a single-effect parameter block.
func strengths(effect string, value float64) EffectsParams {
switch effect {
case "texture":
return EffectsParams{Texture: value}
case "clarity":
return EffectsParams{Clarity: value}
}
return EffectsParams{}
}
func TestDehaze(t *testing.T) {
clear := hazyScene(128, 96)
hazy := addHaze(clear, 0.45, 235)
baseContrast := lumaStdDev(hazy)
baseSaturation := meanSaturation(hazy)
removed := applyEffects(imaging.Clone(hazy), EffectsParams{Dehaze: 100}, 1)
t.Logf("contrast %.2f -> %.2f, saturation %.2f -> %.2f",
baseContrast, lumaStdDev(removed), baseSaturation, meanSaturation(removed))
if got := lumaStdDev(removed); got <= baseContrast {
t.Fatalf("dehaze +100: contrast %v did not grow above %v", got, baseContrast)
}
if got := meanSaturation(removed); got <= baseSaturation {
t.Fatalf("dehaze +100: saturation %v did not grow above %v", got, baseSaturation)
}
clearContrast := lumaStdDev(clear)
clearSaturation := meanSaturation(clear)
added := applyEffects(imaging.Clone(clear), EffectsParams{Dehaze: -100}, 1)
t.Logf("clear contrast %.2f -> %.2f, saturation %.2f -> %.2f",
clearContrast, lumaStdDev(added), clearSaturation, meanSaturation(added))
if got := lumaStdDev(added); got >= clearContrast {
t.Fatalf("dehaze -100: contrast %v did not drop below %v", got, clearContrast)
}
if got := meanSaturation(added); got >= clearSaturation {
t.Fatalf("dehaze -100: saturation %v did not drop below %v", got, clearSaturation)
}
}
func TestResizeTransmission(t *testing.T) {
// A vertical step map: the top half is dark, the bottom half is bright.
sw, sh := 16, 12
transmission := make([]uint8, sw*sh)
for y := 0; y < sh; y++ {
for x := 0; x < sw; x++ {
if y < sh/2 {
transmission[y*sw+x] = 20
} else {
transmission[y*sw+x] = 230
}
}
}
gray := image.NewGray(image.Rect(0, 0, sw, sh))
copy(gray.Pix, transmission)
out := resizeTransmission(gray, 128, 96)
if len(out) != 128*96 {
t.Fatalf("resized map length = %d, want %d", len(out), 128*96)
}
// The transition band is blurred by the interpolation, so the edges are
// checked away from the step.
for y := 0; y < 96; y++ {
if y >= 40 && y < 56 {
continue
}
want := uint8(20)
if y >= 56 {
want = 230
}
for x := 0; x < 128; x++ {
if got := out[y*128+x]; got < want-4 || got > want+4 {
t.Fatalf("pixel %d,%d = %d, want around %d", x, y, got, want)
}
}
}
}
func TestVignette(t *testing.T) {
src := solidImage(64, 64, 128)
const centerX, centerY = 32, 32
const cornerX, cornerY = 0, 0
t.Run("light mode", func(t *testing.T) {
dark := applyEffects(imaging.Clone(src), EffectsParams{
Vignette: VignetteParams{Mode: VignetteLight, Amount: 80},
}, 0)
if pixelAt(dark, centerX, centerY) != 128 {
t.Fatalf("center changed: %d", pixelAt(dark, centerX, centerY))
}
if pixelAt(dark, cornerX, cornerY) >= 128 {
t.Fatalf("positive amount did not darken the corner: %d", pixelAt(dark, cornerX, cornerY))
}
bright := applyEffects(imaging.Clone(src), EffectsParams{
Vignette: VignetteParams{Mode: VignetteLight, Amount: -80},
}, 0)
if pixelAt(bright, centerX, centerY) != 128 {
t.Fatalf("center changed: %d", pixelAt(bright, centerX, centerY))
}
if pixelAt(bright, cornerX, cornerY) <= 128 {
t.Fatalf("negative amount did not brighten the corner: %d", pixelAt(bright, cornerX, cornerY))
}
})
t.Run("zero amount is identity", func(t *testing.T) {
out := applyEffects(imaging.Clone(src), EffectsParams{
Vignette: VignetteParams{Mode: VignetteColor, Amount: 0, Color: "#ff0000"},
}, 0)
if !bytes.Equal(out.Pix, src.Pix) {
t.Fatal("zero vignette changed the image")
}
})
t.Run("color mode tints the edges", func(t *testing.T) {
out := applyEffects(imaging.Clone(src), EffectsParams{
Vignette: VignetteParams{Mode: VignetteColor, Amount: 100, Color: "#ff0000"},
}, 0)
r, g, b := rgbAt(out, cornerX, cornerY)
if !(r > g && r > b) {
t.Fatalf("color vignette corner = %d/%d/%d, want a red tint", r, g, b)
}
if r, g, b := rgbAt(out, centerX, centerY); r != 128 || g != 128 || b != 128 {
t.Fatalf("color vignette changed the center: %d/%d/%d", r, g, b)
}
})
t.Run("colorize mode fills the edges", func(t *testing.T) {
out := applyEffects(imaging.Clone(src), EffectsParams{
Vignette: VignetteParams{Mode: VignetteColorize, Amount: 100, Color: "#ff0000"},
}, 0)
if r, g, b := rgbAt(out, cornerX, cornerY); r != 255 || g != 0 || b != 0 {
t.Fatalf("colorize corner = %d/%d/%d, want 255/0/0", r, g, b)
}
if r, g, b := rgbAt(out, centerX, centerY); r != 128 || g != 128 || b != 128 {
t.Fatalf("colorize changed the center: %d/%d/%d", r, g, b)
}
})
t.Run("highlight protection", func(t *testing.T) {
bright := solidImage(64, 64, 240)
plain := applyEffects(imaging.Clone(bright), EffectsParams{
Vignette: VignetteParams{Mode: VignetteLight, Amount: 100},
}, 0)
protected := applyEffects(imaging.Clone(bright), EffectsParams{
Vignette: VignetteParams{Mode: VignetteLight, Amount: 100, Highlights: 100},
}, 0)
if pixelAt(protected, cornerX, cornerY) <= pixelAt(plain, cornerX, cornerY) {
t.Fatalf("highlight protection did not preserve the corner: %d <= %d",
pixelAt(protected, cornerX, cornerY), pixelAt(plain, cornerX, cornerY))
}
})
}
func TestGrainDeterminism(t *testing.T) {
src := gradientImage(64, 64)
grain := EffectsParams{Grain: GrainParams{Amount: 70, Size: 30, Roughness: 60}}
first := applyEffects(imaging.Clone(src), grain, 12345)
second := applyEffects(imaging.Clone(src), grain, 12345)
if !bytes.Equal(first.Pix, second.Pix) {
t.Fatal("two renders with the same parameters and seed differ")
}
if bytes.Equal(first.Pix, src.Pix) {
t.Fatal("grain did not change the image")
}
other := applyEffects(imaging.Clone(src), grain, 999)
if bytes.Equal(first.Pix, other.Pix) {
t.Fatal("a different seed produced the same grain")
}
zero := applyEffects(imaging.Clone(src), EffectsParams{
Grain: GrainParams{Amount: 0, Size: 30, Roughness: 60},
}, 12345)
if !bytes.Equal(zero.Pix, src.Pix) {
t.Fatal("zero grain strength changed the image")
}
// The full render path seeds the same noise from the photo id.
data := mustEncodePNG(t, src)
a, err := decodeAndAdjust(data, EditParams{Effects: grain}, editSeed("photo-1"))
if err != nil {
t.Fatalf("decode and adjust: %v", err)
}
b, err := decodeAndAdjust(data, EditParams{Effects: grain}, editSeed("photo-1"))
if err != nil {
t.Fatalf("decode and adjust again: %v", err)
}
if !bytes.Equal(a.Pix, b.Pix) {
t.Fatal("repeated decodeAndAdjust renders differ")
}
}
func TestEffectsKeepTransparentPixels(t *testing.T) {
src := image.NewNRGBA(image.Rect(0, 0, 32, 32))
for i := 0; i < len(src.Pix); i += 4 {
src.Pix[i], src.Pix[i+1], src.Pix[i+2], src.Pix[i+3] = 200, 10, 30, 0
}
before := append([]uint8(nil), src.Pix...)
out := applyEffects(src, EffectsParams{
Texture: 60,
Clarity: 60,
Dehaze: 60,
Vignette: VignetteParams{
Mode: VignetteColorize, Amount: 100, Color: "#00ff00",
},
Grain: GrainParams{Amount: 100, Size: 40, Roughness: 80},
}, 7)
if !bytes.Equal(out.Pix, before) {
t.Fatal("effects changed transparent pixels")
}
}
// solidImage returns a uniform opaque image.
func solidImage(w, h int, value uint8) *image.NRGBA {
img := image.NewNRGBA(image.Rect(0, 0, w, h))
for i := 0; i < len(img.Pix); i += 4 {
img.Pix[i] = value
img.Pix[i+1] = value
img.Pix[i+2] = value
img.Pix[i+3] = 255
}
return img
}
// gradientImage returns an opaque image with smooth horizontal and vertical
// variation, so every effect has something to work with.
func gradientImage(w, h int) *image.NRGBA {
img := image.NewNRGBA(image.Rect(0, 0, w, h))
for y := 0; y < h; y++ {
for x := 0; x < w; x++ {
i := y*img.Stride + x*4
img.Pix[i] = uint8(20 + x*3)
img.Pix[i+1] = uint8(30 + y*3)
img.Pix[i+2] = uint8(40 + (x + y))
img.Pix[i+3] = 255
}
}
return img
}
// checkerImage returns a fine checkerboard, the high-frequency input of the
// local-contrast tests.
func checkerImage(w, h int, dark, light uint8) *image.NRGBA {
img := image.NewNRGBA(image.Rect(0, 0, w, h))
for y := 0; y < h; y++ {
for x := 0; x < w; x++ {
i := y*img.Stride + x*4
v := dark
if (x+y)%2 == 0 {
v = light
}
img.Pix[i] = v
img.Pix[i+1] = v
img.Pix[i+2] = v
img.Pix[i+3] = 255
}
}
return img
}
// hazyScene builds a synthetic landscape: a bright sky band and a colored
// checker with a brightness gradient. It represents the "clear" frame.
func hazyScene(w, h int) *image.NRGBA {
img := image.NewNRGBA(image.Rect(0, 0, w, h))
sky := h / 6
for y := 0; y < h; y++ {
for x := 0; x < w; x++ {
i := y*img.Stride + x*4
if y < sky {
img.Pix[i], img.Pix[i+1], img.Pix[i+2] = 235, 235, 235
img.Pix[i+3] = 255
continue
}
t := float64(x) / float64(w-1)
if (x/16+y/16)%2 == 0 {
img.Pix[i] = uint8(40 + 180*t)
img.Pix[i+1] = uint8(40 + 60*t)
img.Pix[i+2] = uint8(40 + 40*t)
} else {
img.Pix[i] = uint8(40 + 40*t)
img.Pix[i+1] = uint8(40 + 120*t)
img.Pix[i+2] = uint8(40 + 180*t)
}
img.Pix[i+3] = 255
}
}
return img
}
// addHaze mixes the frame toward an atmospheric color.
func addHaze(src *image.NRGBA, haze float64, atmosphere uint8) *image.NRGBA {
out := imaging.Clone(src)
w, h := out.Rect.Dx(), out.Rect.Dy()
for y := 0; y < h; y++ {
for x := 0; x < w; x++ {
i := y*out.Stride + x*4
for c := 0; c < 3; c++ {
out.Pix[i+c] = uint8(float64(out.Pix[i+c])*(1-haze) + float64(atmosphere)*haze + 0.5)
}
}
}
return out
}
// lumaVariance is the global variance of the luminance.
func lumaVariance(img *image.NRGBA) float64 {
plane := lumaPlane(img)
var sum float64
for _, v := range plane {
sum += float64(v)
}
mean := sum / float64(len(plane))
var variance float64
for _, v := range plane {
d := float64(v) - mean
variance += d * d
}
return variance / float64(len(plane))
}
// lumaStdDev is the contrast measure of the dehaze test.
func lumaStdDev(img *image.NRGBA) float64 {
return math.Sqrt(lumaVariance(img))
}
// meanSaturation is the average channel spread of the image.
func meanSaturation(img *image.NRGBA) float64 {
w, h := img.Rect.Dx(), img.Rect.Dy()
var sum float64
for y := 0; y < h; y++ {
for x := 0; x < w; x++ {
i := y*img.Stride + x*4
mx := max(img.Pix[i], max(img.Pix[i+1], img.Pix[i+2]))
mn := min(img.Pix[i], min(img.Pix[i+1], img.Pix[i+2]))
sum += float64(mx - mn)
}
}
return sum / float64(w*h)
}
func pixelAt(img *image.NRGBA, x, y int) uint8 {
return img.Pix[y*img.Stride+x*4]
}
func rgbAt(img *image.NRGBA, x, y int) (uint8, uint8, uint8) {
i := y*img.Stride + x*4
return img.Pix[i], img.Pix[i+1], img.Pix[i+2]
}
+4 -2
View File
@@ -124,12 +124,14 @@ func (h *Handler) Download(c *gin.Context) {
func (h *Handler) Edit(c *gin.Context) { func (h *Handler) Edit(c *gin.Context) {
var req struct { var req struct {
Light LightParams `json:"light"` Light LightParams `json:"light"`
Color ColorParams `json:"color"`
Effects EffectsParams `json:"effects"`
} }
if err := c.ShouldBindJSON(&req); err != nil { if err := c.ShouldBindJSON(&req); err != nil {
httpx.RespondError(c, httpx.BadRequest("invalid_request", "light params are required")) httpx.RespondError(c, httpx.BadRequest("invalid_request", "edit params are required"))
return return
} }
p, err := h.svc.EditPhoto(c.Request.Context(), c.Param("id"), auth.UserID(c), EditParams{Light: req.Light}) p, err := h.svc.EditPhoto(c.Request.Context(), c.Param("id"), auth.UserID(c), EditParams{Light: req.Light, Color: req.Color, Effects: req.Effects})
if err != nil { if err != nil {
httpx.RespondError(c, err) httpx.RespondError(c, err)
return return
+4 -3
View File
@@ -41,7 +41,8 @@ const sqlitePhotoColumns = `p.id, COALESCE(p.album_id, ''), p.uploader_id,
COALESCE((SELECT json_group_array(json_object('id', t.id, 'name', t.name)) COALESCE((SELECT json_group_array(json_object('id', t.id, 'name', t.name))
FROM (SELECT t.id, t.name FROM photo_tags pt JOIN tags t ON t.id = pt.tag_id FROM (SELECT t.id, t.name FROM photo_tags pt JOIN tags t ON t.id = pt.tag_id
WHERE pt.photo_id = p.id AND t.user_id = $2 WHERE pt.photo_id = p.id AND t.user_id = $2
ORDER BY lower(t.name)) t), '[]')` ORDER BY lower(t.name)) t), '[]'),
EXISTS(SELECT 1 FROM edit_jobs ej WHERE ej.photo_id = p.id)`
const sqlitePhotoJoins = ` const sqlitePhotoJoins = `
LEFT JOIN photo_objects po_o ON po_o.photo_id = p.id AND po_o.role = 'original' LEFT JOIN photo_objects po_o ON po_o.photo_id = p.id AND po_o.role = 'original'
@@ -76,7 +77,7 @@ func scanSQLitePhoto(scan func(...any) error) (*models.Photo, error) {
&p.Kind, &p.DurationMS, &p.Kind, &p.DurationMS,
&takenAt, &lat, &long, &p.Caption, &createdAt, &takenAt, &lat, &long, &p.Caption, &createdAt,
&p.Uploader.ID, &p.Uploader.Name, &p.Uploader.AvatarURL, &p.Uploader.ID, &p.Uploader.Name, &p.Uploader.AvatarURL,
&p.LikesCount, &p.CommentsCount, &liked, &exifText, &deletedAt, &editText, &tagsText); err != nil { &p.LikesCount, &p.CommentsCount, &liked, &exifText, &deletedAt, &editText, &tagsText, &p.EditPending); err != nil {
return nil, err return nil, err
} }
p.TakenAt = sqliteutil.ParseNullTime(takenAt) p.TakenAt = sqliteutil.ParseNullTime(takenAt)
@@ -311,7 +312,7 @@ func (s *SQLiteStore) ListTrash(ctx context.Context, userID string) ([]models.Ph
&p.Kind, &p.DurationMS, &p.Kind, &p.DurationMS,
&takenAt, &lat, &long, &p.Caption, &createdAt, &takenAt, &lat, &long, &p.Caption, &createdAt,
&p.Uploader.ID, &p.Uploader.Name, &p.Uploader.AvatarURL, &p.Uploader.ID, &p.Uploader.Name, &p.Uploader.AvatarURL,
&p.LikesCount, &p.CommentsCount, &liked, &exifText, &deletedAt, &editText, &albumTitle, &tagsText); err != nil { &p.LikesCount, &p.CommentsCount, &liked, &exifText, &deletedAt, &editText, &tagsText, &p.EditPending, &albumTitle); err != nil {
return nil, err return nil, err
} }
p.TakenAt = sqliteutil.ParseNullTime(takenAt) p.TakenAt = sqliteutil.ParseNullTime(takenAt)
+5 -4
View File
@@ -47,7 +47,8 @@ const photoColumns = `p.id, COALESCE(p.album_id, ''), p.uploader_id,
COALESCE(p.edit_params, '{}'::jsonb)::text, COALESCE(p.edit_params, '{}'::jsonb)::text,
COALESCE((SELECT json_agg(json_build_object('id', t.id, 'name', t.name) ORDER BY lower(t.name)) COALESCE((SELECT json_agg(json_build_object('id', t.id, 'name', t.name) ORDER BY lower(t.name))
FROM photo_tags pt JOIN tags t ON t.id = pt.tag_id FROM photo_tags pt JOIN tags t ON t.id = pt.tag_id
WHERE pt.photo_id = p.id AND t.user_id = $2), '[]')::text` WHERE pt.photo_id = p.id AND t.user_id = $2), '[]')::text,
EXISTS(SELECT 1 FROM edit_jobs ej WHERE ej.photo_id = p.id)`
const photoJoins = ` const photoJoins = `
LEFT JOIN photo_objects po_o ON po_o.photo_id = p.id AND po_o.role = 'original' LEFT JOIN photo_objects po_o ON po_o.photo_id = p.id AND po_o.role = 'original'
@@ -79,7 +80,7 @@ func scanPhoto(row pgx.Row) (*models.Photo, error) {
&p.Kind, &p.DurationMS, &p.Kind, &p.DurationMS,
&p.TakenAt, &p.Latitude, &p.Longitude, &p.Caption, &p.CreatedAt, &p.TakenAt, &p.Latitude, &p.Longitude, &p.Caption, &p.CreatedAt,
&p.Uploader.ID, &p.Uploader.Name, &p.Uploader.AvatarURL, &p.Uploader.ID, &p.Uploader.Name, &p.Uploader.AvatarURL,
&p.LikesCount, &p.CommentsCount, &p.LikedByMe, &exifText, &p.DeletedAt, &editText, &tagsText) &p.LikesCount, &p.CommentsCount, &p.LikedByMe, &exifText, &p.DeletedAt, &editText, &tagsText, &p.EditPending)
if err != nil { if err != nil {
if errors.Is(err, pgx.ErrNoRows) { if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrNotFound return nil, ErrNotFound
@@ -228,7 +229,7 @@ func (s *Store) List(ctx context.Context, in ListParams) ([]models.Photo, error)
&p.Kind, &p.DurationMS, &p.Kind, &p.DurationMS,
&p.TakenAt, &p.Latitude, &p.Longitude, &p.Caption, &p.CreatedAt, &p.TakenAt, &p.Latitude, &p.Longitude, &p.Caption, &p.CreatedAt,
&p.Uploader.ID, &p.Uploader.Name, &p.Uploader.AvatarURL, &p.Uploader.ID, &p.Uploader.Name, &p.Uploader.AvatarURL,
&p.LikesCount, &p.CommentsCount, &p.LikedByMe, &exifText, &p.DeletedAt, &editText, &tagsText); err != nil { &p.LikesCount, &p.CommentsCount, &p.LikedByMe, &exifText, &p.DeletedAt, &editText, &tagsText, &p.EditPending); err != nil {
return nil, err return nil, err
} }
setExif(&p, exifText) setExif(&p, exifText)
@@ -348,7 +349,7 @@ func (s *Store) ListTrash(ctx context.Context, userID string) ([]models.Photo, e
&p.Kind, &p.DurationMS, &p.Kind, &p.DurationMS,
&p.TakenAt, &p.Latitude, &p.Longitude, &p.Caption, &p.CreatedAt, &p.TakenAt, &p.Latitude, &p.Longitude, &p.Caption, &p.CreatedAt,
&p.Uploader.ID, &p.Uploader.Name, &p.Uploader.AvatarURL, &p.Uploader.ID, &p.Uploader.Name, &p.Uploader.AvatarURL,
&p.LikesCount, &p.CommentsCount, &p.LikedByMe, &exifText, &p.DeletedAt, &editText, &p.AlbumTitle, &tagsText); err != nil { &p.LikesCount, &p.CommentsCount, &p.LikedByMe, &exifText, &p.DeletedAt, &editText, &tagsText, &p.EditPending, &p.AlbumTitle); err != nil {
return nil, err return nil, err
} }
setExif(&p, exifText) setExif(&p, exifText)
+13 -2
View File
@@ -6,6 +6,7 @@ import (
"crypto/sha256" "crypto/sha256"
"encoding/hex" "encoding/hex"
"errors" "errors"
"hash/fnv"
"io" "io"
"log/slog" "log/slog"
"os" "os"
@@ -202,7 +203,7 @@ func (w *Worker) generateEdit(ctx context.Context, photoID string) {
w.failEdit(ctx, photoID, "fetch original: "+err.Error()) w.failEdit(ctx, photoID, "fetch original: "+err.Error())
return return
} }
edited, err := decodeAndAdjust(data, params) edited, err := decodeAndAdjust(data, params, editSeed(photoID))
if err != nil { if err != nil {
w.failEdit(ctx, photoID, "decode original: "+err.Error()) w.failEdit(ctx, photoID, "decode original: "+err.Error())
return return
@@ -211,7 +212,8 @@ func (w *Worker) generateEdit(ctx context.Context, photoID string) {
if err != nil { if err != nil {
w.failEdit(ctx, photoID, "build edited variants: "+err.Error()) w.failEdit(ctx, photoID, "build edited variants: "+err.Error())
return return
} // The edit belongs to this photo only, so the variants are not shared }
// The edit belongs to this photo only, so the variants are not shared
// with the copies of the same original. // with the copies of the same original.
owner := []string{photoID} owner := []string{photoID}
if err := w.createVariant(ctx, owner, RoleEditThumb, thumb); err != nil { if err := w.createVariant(ctx, owner, RoleEditThumb, thumb); err != nil {
@@ -240,6 +242,15 @@ func (w *Worker) generateEdit(ctx context.Context, photoID string) {
w.notify(ctx, photoID) w.notify(ctx, photoID)
} }
// editSeed is the deterministic seed of the grain render: the FNV-1a hash of the
// photo id. It depends on the photo and not on the parameters, so a repeated
// render of the same edit produces the same noise pattern.
func editSeed(photoID string) uint64 {
h := fnv.New64a()
_, _ = h.Write([]byte(photoID))
return h.Sum64()
}
func (w *Worker) failEdit(ctx context.Context, photoID, msg string) { func (w *Worker) failEdit(ctx context.Context, photoID, msg string) {
slog.Warn("edit job failed", "photo", photoID, "error", msg) slog.Warn("edit job failed", "photo", photoID, "error", msg)
_ = w.svc.store.FailEditJob(ctx, photoID, msg, maxVariantAttempts) _ = w.svc.store.FailEditJob(ctx, photoID, msg, maxVariantAttempts)
@@ -48,6 +48,7 @@ func Run(t *testing.T, r Repos) {
{"ShareLinks", testShareLinks}, {"ShareLinks", testShareLinks},
{"Social", testSocial}, {"Social", testSocial},
{"Photos", testPhotos}, {"Photos", testPhotos},
{"EditPending", testEditPending},
{"Objects", testObjects}, {"Objects", testObjects},
{"Clone", testClone}, {"Clone", testClone},
{"UserAvatar", testUserAvatar}, {"UserAvatar", testUserAvatar},
@@ -490,6 +491,11 @@ func testPhotos(t *testing.T, ctx context.Context, r Repos) {
t.Fatalf("cover not cleared: %+v", al.CoverPhotoID) t.Fatalf("cover not cleared: %+v", al.CoverPhotoID)
} }
// Trash rows are read with the same column list as the album list, so the
// tags JSON and the album title must land in their own fields.
if err := r.Photos.AttachTag(ctx, p.ID, tag.ID); err != nil {
t.Fatalf("re-attach tag for trash: %v", err)
}
if err := r.Photos.SetDeleted(ctx, p.ID, true); err != nil { if err := r.Photos.SetDeleted(ctx, p.ID, true); err != nil {
t.Fatalf("soft delete: %v", err) t.Fatalf("soft delete: %v", err)
} }
@@ -500,6 +506,12 @@ func testPhotos(t *testing.T, ctx context.Context, r Repos) {
if err != nil || len(trash) != 1 { if err != nil || len(trash) != 1 {
t.Fatalf("trash: %v len=%d", err, len(trash)) t.Fatalf("trash: %v len=%d", err, len(trash))
} }
if trash[0].AlbumTitle != a.Title {
t.Fatalf("trash album title = %q, want %q", trash[0].AlbumTitle, a.Title)
}
if len(trash[0].Tags) != 1 || trash[0].Tags[0].Name != "Vacation" {
t.Fatalf("trash tags = %+v", trash[0].Tags)
}
if err := r.Photos.RestoreToAlbum(ctx, p.ID, a.ID); err != nil { if err := r.Photos.RestoreToAlbum(ctx, p.ID, a.ID); err != nil {
t.Fatalf("restore: %v", err) t.Fatalf("restore: %v", err)
} }
@@ -563,6 +575,56 @@ func testPhotos(t *testing.T, ctx context.Context, r Repos) {
} }
} }
// testEditPending verifies that reads expose whether an edit render is still
// queued: clients rely on it to tell stale edit URLs from the current ones.
func testEditPending(t *testing.T, ctx context.Context, r Repos) {
owner := seedUser(t, ctx, r, "Owner")
a := seedAlbum(t, ctx, r, owner.ID)
p := seedPhoto(t, ctx, r, owner.ID, a.ID)
getPending := func() bool {
t.Helper()
got, err := r.Photos.GetByID(ctx, p.ID, owner.ID)
if err != nil {
t.Fatalf("get photo: %v", err)
}
return got.EditPending
}
listPending := func() bool {
t.Helper()
list, err := r.Photos.List(ctx, photos.ListParams{AlbumID: a.ID, Viewer: owner.ID, Limit: 10})
if err != nil || len(list) != 1 {
t.Fatalf("list: %v len=%d", err, len(list))
}
return list[0].EditPending
}
if getPending() || listPending() {
t.Fatalf("photo without an edit job reports a pending edit render")
}
if err := r.Photos.EnqueueEditJob(ctx, p.ID); err != nil {
t.Fatalf("enqueue edit job: %v", err)
}
if !getPending() || !listPending() {
t.Fatalf("photo with a queued edit render does not report edit_pending")
}
if err := r.Photos.CompleteEditJob(ctx, p.ID); err != nil {
t.Fatalf("complete edit job: %v", err)
}
if getPending() || listPending() {
t.Fatalf("rendered photo still reports edit_pending")
}
if err := r.Photos.EnqueueEditJob(ctx, p.ID); err != nil {
t.Fatalf("enqueue again: %v", err)
}
if err := r.Photos.DeleteEditJob(ctx, p.ID); err != nil {
t.Fatalf("delete edit job: %v", err)
}
if getPending() {
t.Fatalf("photo reports edit_pending after the job was dropped")
}
}
func testObjects(t *testing.T, ctx context.Context, r Repos) { func testObjects(t *testing.T, ctx context.Context, r Repos) {
owner := seedUser(t, ctx, r, "Owner") owner := seedUser(t, ctx, r, "Owner")
a := seedAlbum(t, ctx, r, owner.ID) a := seedAlbum(t, ctx, r, owner.ID)
+21 -4
View File
@@ -22,10 +22,16 @@
let picking = $state(false); let picking = $state(false);
let photo = $state<Photo | null>(null); let photo = $state<Photo | null>(null);
// Вкладка правой панели живёт здесь и переживает смену фото.
let photoTab = $state<'info' | 'edit'>('info');
const selectedItems = $derived(selection.albumId === albumId ? selection.items : []); const selectedItems = $derived(selection.albumId === albumId ? selection.items : []);
const selectedPhoto = $derived(selectedItems.length === 1 ? selectedItems[0] : null); const selectedPhoto = $derived(selectedItems.length === 1 ? selectedItems[0] : null);
const panelPhoto = $derived(photoId ? photo : selectedPhoto); // Не показываем в панели фото от предыдущего маршрута, пока не загрузилось
// текущее: иначе правки могут уйти не тому фото.
const panelPhoto = $derived(
photoId ? (photo?.id === photoId ? photo : null) : selectedPhoto
);
const canEdit = $derived(role === 'owner' || role === 'admin'); const canEdit = $derived(role === 'owner' || role === 'admin');
@@ -51,7 +57,9 @@
} }
function onRenamed(updated: Photo) { function onRenamed(updated: Photo) {
photo = updated; // Фоновое сохранение предыдущего фото может завершиться уже после
// переключения: его ответ не должен подменять текущее фото в панели.
if (updated.id === photoId) photo = updated;
if (selectedItems.some((p) => p.id === updated.id)) selection.replace(updated); if (selectedItems.some((p) => p.id === updated.id)) selection.replace(updated);
photoUpdates.publish(updated); photoUpdates.publish(updated);
} }
@@ -90,9 +98,17 @@
photo = null; photo = null;
return; return;
} }
let cancelled = false;
api<{ photo: Photo }>(`/photos/${id}`) api<{ photo: Photo }>(`/photos/${id}`)
.then((data) => (photo = data.photo)) .then((data) => {
.catch((e) => (error = (e as Error).message)); if (!cancelled && data.photo.id === id) photo = data.photo;
})
.catch((e) => {
if (!cancelled) error = (e as Error).message;
});
return () => {
cancelled = true;
};
}); });
async function resetCover() { async function resetCover() {
@@ -146,6 +162,7 @@
{#if panelPhoto} {#if panelPhoto}
<PhotoPanel <PhotoPanel
bind:tab={photoTab}
photo={panelPhoto} photo={panelPhoto}
{role} {role}
viewer={!!photoId} viewer={!!photoId}
@@ -0,0 +1,87 @@
<script lang="ts">
interface Props {
hue: number;
saturation: number;
label?: string;
disabled?: boolean;
onchange?: (hue: number, saturation: number) => void;
oncommit?: () => void;
}
let { hue, saturation, label, disabled = false, onchange, oncommit }: Props = $props();
let dragging = $state(false);
let el: HTMLDivElement | undefined = $state();
function pick(ev: PointerEvent) {
if (!el || disabled) return;
const rect = el.getBoundingClientRect();
const x = (ev.clientX - rect.left) / rect.width - 0.5;
const y = (ev.clientY - rect.top) / rect.height - 0.5;
const radius = Math.sqrt(x * x + y * y);
const angle = Math.atan2(x, -y);
const nextHue = (((angle * 180) / Math.PI) + 360) % 360;
const nextSaturation = Math.min(1, radius * 2) * 100;
onchange?.(nextHue, nextSaturation);
}
function onDown(ev: PointerEvent) {
if (disabled) return;
ev.preventDefault();
dragging = true;
pick(ev);
(ev.currentTarget as Element).setPointerCapture?.(ev.pointerId);
}
function onMove(ev: PointerEvent) {
if (dragging) pick(ev);
}
function onUp() {
if (!dragging) return;
dragging = false;
oncommit?.();
}
/** Двойной клик сбрасывает колесо в нейтраль. */
function onDoubleClick(ev: MouseEvent) {
ev.preventDefault();
if (disabled) return;
onchange?.(0, 0);
oncommit?.();
}
const knob = $derived({
left:
50 +
Math.sin((hue * Math.PI) / 180) * (Math.min(100, Math.max(0, saturation)) / 100) * 50,
top:
50 -
Math.cos((hue * Math.PI) / 180) * (Math.min(100, Math.max(0, saturation)) / 100) * 50
});
</script>
<div class="flex flex-col items-center gap-1">
<div
bind:this={el}
class="relative aspect-square w-full max-w-[88px] touch-none rounded-full"
style="background: radial-gradient(circle, #d9d9d9 0%, rgba(217,217,217,0) 55%), conic-gradient(from 0deg, red, yellow, lime, cyan, blue, magenta, red);"
role="slider"
tabindex="0"
aria-label={label ?? 'Цвет'}
aria-valuemin="0"
aria-valuemax="360"
aria-valuenow={Math.round(hue)}
onpointerdown={onDown}
onpointermove={onMove}
onpointerup={onUp}
onpointerleave={onUp}
ondblclick={onDoubleClick}
>
<span
class="pointer-events-none absolute size-3 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-white shadow"
style="left: {knob.left}%; top: {knob.top}%;"
></span>
</div>
{#if label}<span class="text-text-muted text-[10px]">{label}</span>{/if}
</div>
@@ -0,0 +1,432 @@
<script lang="ts">
import Icon from './Icon.svelte';
import { portal } from '$lib/actions/portal';
import { CURVE_CHANNELS, type CurveChannel, type CurvePoint } from '$lib/edit';
import {
BUILTIN_CURVE_PRESETS,
MAX_CURVE_PRESET_NAME,
exportCurvePresetFile,
normalizeCurvePresetName,
parseCurvePresetFile
} from '$lib/curve-presets';
import type { CurvePreset } from '$lib/types';
interface Props {
curves: Record<CurveChannel, CurvePoint[]>;
presets: CurvePreset[];
activeName: string;
disabled?: boolean;
onApply: (preset: CurvePreset) => void;
onSave: (preset: CurvePreset) => Promise<void>;
onRename: (oldName: string, newName: string) => Promise<void>;
onDelete: (name: string) => Promise<void>;
onImport: (presets: CurvePreset[]) => Promise<void>;
}
let {
curves,
presets,
activeName,
disabled = false,
onApply,
onSave,
onRename,
onDelete,
onImport
}: Props = $props();
let open = $state(false);
let dialog = $state<'save' | 'rename' | null>(null);
let renameFrom = $state('');
let nameDraft = $state('');
let error = $state('');
let busy = $state(false);
let trigger = $state<HTMLButtonElement | undefined>();
let menuElement = $state<HTMLDivElement | undefined>();
let menuStyle = $state('');
let fileInput = $state<HTMLInputElement | undefined>();
let nameInput = $state<HTMLInputElement | undefined>();
const MENU_WIDTH = 288;
const MENU_HEIGHT = 320;
const MENU_GAP = 6;
const VIEWPORT_PAD = 8;
const isCustomActive = $derived(presets.some((preset) => preset.name === activeName));
$effect(() => {
if (dialog && nameInput) {
nameInput.focus();
nameInput.select();
}
});
// Панель редактирования — скроллящийся контейнер с transform, поэтому меню
// рендерится в portal и позиционируется от кнопки в координатах viewport.
$effect(() => {
if (!open) return;
const onScroll = (ev: Event) => {
if (menuElement && ev.target instanceof Node && menuElement.contains(ev.target)) return;
open = false;
};
const onResize = () => (open = false);
window.addEventListener('scroll', onScroll, true);
window.addEventListener('resize', onResize);
return () => {
window.removeEventListener('scroll', onScroll, true);
window.removeEventListener('resize', onResize);
};
});
function positionMenu() {
if (!trigger || typeof window === 'undefined') return;
const rect = trigger.getBoundingClientRect();
const width = Math.min(MENU_WIDTH, window.innerWidth - VIEWPORT_PAD * 2);
const left = Math.min(
Math.max(VIEWPORT_PAD, rect.right - width),
window.innerWidth - width - VIEWPORT_PAD
);
const spaceBelow = window.innerHeight - rect.bottom - MENU_GAP - VIEWPORT_PAD;
const spaceAbove = rect.top - MENU_GAP - VIEWPORT_PAD;
const openBelow = spaceBelow >= Math.min(MENU_HEIGHT, 220) || spaceBelow >= spaceAbove;
if (openBelow) {
menuStyle = `left:${left}px; top:${rect.bottom + MENU_GAP}px; width:${width}px; max-height:${Math.max(140, spaceBelow)}px;`;
} else {
menuStyle = `left:${left}px; bottom:${window.innerHeight - rect.top + MENU_GAP}px; width:${width}px; max-height:${Math.max(140, spaceAbove)}px;`;
}
}
function toggle() {
if (disabled) return;
if (!open) positionMenu();
open = !open;
error = '';
}
function apply(preset: CurvePreset) {
onApply(preset);
open = false;
error = '';
}
function startSave() {
nameDraft = isCustomActive ? activeName : '';
open = false;
error = '';
dialog = 'save';
}
function startRename(preset: CurvePreset) {
renameFrom = preset.name;
nameDraft = preset.name;
open = false;
error = '';
dialog = 'rename';
}
function closeDialog() {
if (busy) return;
dialog = null;
error = '';
}
async function submit(ev: Event) {
ev.preventDefault();
if (busy) return;
const name = normalizeCurvePresetName(nameDraft);
if (!name) {
error = `Введите название до ${MAX_CURVE_PRESET_NAME} символов`;
return;
}
if (dialog === 'save') {
if (
presets.some((preset) => preset.name === name) &&
!window.confirm(`Перезаписать пресет «${name}»?`)
) {
return;
}
busy = true;
error = '';
try {
const channels = {} as CurvePreset['channels'];
for (const ch of CURVE_CHANNELS) {
channels[ch] = curves[ch].map((point) => ({ ...point }));
}
await onSave({ name, channels });
dialog = null;
} catch (e) {
error = (e as Error).message || 'Не удалось сохранить пресет';
} finally {
busy = false;
}
return;
}
if (dialog === 'rename') {
if (name === renameFrom) {
dialog = null;
return;
}
if (presets.some((preset) => preset.name === name)) {
error = 'Пресет с таким названием уже есть';
return;
}
busy = true;
error = '';
try {
await onRename(renameFrom, name);
dialog = null;
} catch (e) {
error = (e as Error).message || 'Не удалось переименовать пресет';
} finally {
busy = false;
}
}
}
async function removePreset(preset: CurvePreset) {
if (busy) return;
if (!window.confirm(`Удалить пресет «${preset.name}»?`)) return;
busy = true;
error = '';
try {
await onDelete(preset.name);
} catch (e) {
error = (e as Error).message || 'Не удалось удалить пресет';
} finally {
busy = false;
}
}
function pickFile() {
fileInput?.click();
}
async function onFile(ev: Event) {
const input = ev.currentTarget as HTMLInputElement;
const file = input.files?.[0];
if (!file || busy) return;
busy = true;
error = '';
try {
const presetsToImport = parseCurvePresetFile(await file.text());
await onImport(presetsToImport);
open = false;
} catch (e) {
error = (e as Error).message || 'Не удалось импортировать пресеты';
} finally {
busy = false;
input.value = '';
}
}
function exportPresets() {
try {
const blob = new Blob([exportCurvePresetFile(presets)], {
type: 'application/json'
});
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = 'galo-curve-presets.json';
link.click();
setTimeout(() => URL.revokeObjectURL(url), 0);
open = false;
error = '';
} catch (e) {
error = (e as Error).message || 'Не удалось экспортировать пресеты';
}
}
</script>
<svelte:window
onkeydown={(ev) => {
if (dialog && ev.key === 'Escape' && !busy) {
ev.preventDefault();
closeDialog();
}
}}
/>
<div class="relative">
<button
bind:this={trigger}
type="button"
class="text-text-muted hover:text-text flex min-w-0 items-center gap-1 text-xs disabled:opacity-40"
disabled={disabled}
aria-haspopup="menu"
aria-expanded={open}
onclick={toggle}
>
<span class="max-w-[10rem] truncate">{activeName}</span>
<Icon name="expand_more" class="size-3" />
</button>
{#if open}
<button
use:portal
type="button"
class="fixed inset-0 z-[75] cursor-default"
aria-label="Закрыть меню пресетов"
onclick={() => (open = false)}
></button>
<div
use:portal
bind:this={menuElement}
class="border-border bg-bg-elevated fixed z-[80] overflow-y-auto rounded-md border p-1 shadow-lg"
style={menuStyle}
role="menu"
>
<p class="text-text-subtle px-2 py-1 text-[11px] font-semibold uppercase">Встроенные</p>
{#each BUILTIN_CURVE_PRESETS as preset (preset.name)}
<button
type="button"
class="hover:bg-bg-muted flex w-full items-center gap-1 rounded px-2 py-1.5 text-left text-xs"
role="menuitem"
onclick={() => apply(preset)}
>
<span class="flex-1 truncate">{preset.name}</span>
{#if preset.name === activeName}
<Icon name="check" class="text-primary size-3.5" />
{/if}
</button>
{/each}
{#if presets.length}
<p class="text-text-subtle px-2 py-1 text-[11px] font-semibold uppercase">
Пользовательские
</p>
{#each presets as preset (preset.name)}
<div class="hover:bg-bg-muted flex items-center rounded">
<button
type="button"
class="flex min-w-0 flex-1 items-center gap-1 px-2 py-1.5 text-left text-xs"
role="menuitem"
onclick={() => apply(preset)}
>
<span class="truncate">{preset.name}</span>
{#if preset.name === activeName}
<Icon name="check" class="text-primary ml-auto size-3.5" />
{/if}
</button>
<button
type="button"
class="text-text-muted hover:text-text px-1.5 py-1.5"
title="Переименовать пресет"
aria-label="Переименовать пресет {preset.name}"
onclick={() => startRename(preset)}
>
<Icon name="edit" class="size-3.5" />
</button>
<button
type="button"
class="text-text-muted hover:text-danger px-1.5 py-1.5"
title="Удалить пресет"
aria-label="Удалить пресет {preset.name}"
onclick={() => void removePreset(preset)}
>
<Icon name="delete" class="size-3.5" />
</button>
</div>
{/each}
{/if}
<div class="border-border mt-1 space-y-0.5 border-t pt-1">
<button
type="button"
class="hover:bg-bg-muted flex w-full items-center gap-1.5 rounded px-2 py-1.5 text-left text-xs"
onclick={startSave}
>
<Icon name="save" class="size-3.5" />
Сохранить…
</button>
<button
type="button"
class="hover:bg-bg-muted flex w-full items-center gap-1.5 rounded px-2 py-1.5 text-left text-xs"
onclick={pickFile}
>
<Icon name="cloud_upload" class="size-3.5" />
Импортировать…
</button>
<button
type="button"
class="hover:bg-bg-muted flex w-full items-center gap-1.5 rounded px-2 py-1.5 text-left text-xs"
onclick={exportPresets}
>
<Icon name="download" class="size-3.5" />
Экспортировать…
</button>
</div>
{#if error}
<p class="text-danger px-2 py-1 text-[11px]">{error}</p>
{/if}
</div>
{/if}
<input
bind:this={fileInput}
type="file"
accept="application/json,.json"
class="hidden"
tabindex="-1"
aria-hidden="true"
onchange={onFile}
/>
</div>
{#if dialog}
<div
use:portal
class="fixed inset-0 z-[90] flex items-center justify-center bg-black/40 p-4"
role="dialog"
aria-modal="true"
aria-label={dialog === 'save' ? 'Сохранить пресет' : 'Переименовать пресет'}
tabindex="-1"
onclick={(ev) => {
if (ev.target === ev.currentTarget) closeDialog();
}}
onkeydown={(ev) => {
if (ev.key === 'Escape') closeDialog();
}}
>
<form
class="border-border bg-bg-elevated w-full max-w-sm rounded-lg border p-4 shadow-xl"
onsubmit={submit}
>
<h3 class="text-text text-sm font-semibold">
{dialog === 'save' ? 'Сохранить пресет' : 'Переименовать пресет'}
</h3>
<p class="text-text-muted mt-1 text-xs">
{dialog === 'save' ? 'Кривые всех каналов: RGB, R, G, B' : `Было: ${renameFrom}`}
</p>
<input
bind:this={nameInput}
bind:value={nameDraft}
maxlength={MAX_CURVE_PRESET_NAME}
class="border-border bg-bg text-text focus:border-primary mt-3 w-full rounded border px-2 py-1.5 text-sm outline-none"
placeholder="Название пресета"
aria-label="Название пресета"
/>
{#if error}
<p class="text-danger mt-1 text-xs">{error}</p>
{/if}
<div class="mt-4 flex justify-end gap-2">
<button
type="button"
class="border-border text-text-muted hover:text-text rounded-md border px-3 py-1.5 text-xs disabled:opacity-40"
disabled={busy}
onclick={closeDialog}
>
Отмена
</button>
<button
type="submit"
class="bg-primary text-bg rounded-md px-3 py-1.5 text-xs font-semibold disabled:opacity-40"
disabled={busy}
>
{busy ? 'Сохраняем…' : 'Сохранить'}
</button>
</div>
</form>
</div>
{/if}
@@ -0,0 +1,109 @@
<script lang="ts">
interface Props {
id?: string;
label: string;
value: number;
min: number;
max: number;
step: number;
disabled?: boolean;
/** Полный градиент дорожки (например, для цветовых ползунков). */
gradient?: string;
/** Значение при двойном клике. */
resetValue?: number;
format?: (value: number) => string;
oninput?: (value: number) => void;
onchange?: () => void;
}
let {
id,
label,
value,
min,
max,
step,
disabled = false,
gradient,
resetValue = 0,
format,
oninput,
onchange
}: Props = $props();
const percent = $derived(((value - min) / (max - min)) * 100);
const trackStyle = $derived(
gradient
? `background: ${gradient};`
: `background: linear-gradient(to right, #cfcfcf 0%, #cfcfcf ${percent}%, #4a4a4a ${percent}%, #4a4a4a 100%);`
);
const display = $derived(format ? format(value) : String(value));
function handleInput(event: Event) {
oninput?.(Number((event.currentTarget as HTMLInputElement).value));
}
function handleDoubleClick(event: MouseEvent) {
event.preventDefault();
if (disabled) return;
oninput?.(resetValue);
onchange?.();
}
</script>
<div class="space-y-1">
<div class="flex items-baseline justify-between gap-2">
<label class="text-text text-xs" for={id}>{label}</label>
<span class="text-text-muted text-xs tabular-nums">{display}</span>
</div>
<input
{id}
type="range"
class="edit-slider"
style={trackStyle}
{min}
{max}
{step}
{disabled}
{value}
oninput={handleInput}
onchange={onchange}
ondblclick={handleDoubleClick}
/>
</div>
<style>
.edit-slider {
-webkit-appearance: none;
appearance: none;
width: 100%;
height: 2px;
border-radius: 999px;
outline: none;
cursor: pointer;
}
.edit-slider:disabled {
cursor: default;
opacity: 0.4;
}
.edit-slider::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 15px;
height: 15px;
border-radius: 50%;
background: #f3f3f3;
border: 1px solid #9a9a9a;
box-shadow: 0 0 0 2px rgba(0, 0, 0, 0.25);
cursor: pointer;
}
.edit-slider::-moz-range-thumb {
width: 15px;
height: 15px;
border-radius: 50%;
background: #f3f3f3;
border: 1px solid #9a9a9a;
box-shadow: 0 0 0 2px rgba(0, 0, 0, 0.25);
cursor: pointer;
}
</style>
File diff suppressed because it is too large Load Diff
+34 -14
View File
@@ -19,28 +19,39 @@
photo: Photo; photo: Photo;
role: string; role: string;
viewer?: boolean; viewer?: boolean;
tab?: 'info' | 'edit';
onOpen?: () => void; onOpen?: () => void;
onRenamed?: (photo: Photo) => void; onRenamed?: (photo: Photo) => void;
onDeleted?: () => void; onDeleted?: () => void;
} }
let { photo, role, viewer = false, onOpen, onRenamed, onDeleted }: Props = $props(); let {
photo,
role,
viewer = false,
tab = $bindable('info'),
onOpen,
onRenamed,
onDeleted
}: Props = $props();
const canEdit = $derived(role === 'owner' || role === 'admin'); const canEdit = $derived(role === 'owner' || role === 'admin');
const canRename = $derived(canEdit || photo.uploader_id === auth.user?.id); const canRename = $derived(canEdit || photo?.uploader_id === auth.user?.id);
const canDelete = $derived(canEdit || photo.uploader_id === auth.user?.id); const canDelete = $derived(canEdit || photo?.uploader_id === auth.user?.id);
// Правки может вносить и загрузивший фото, если у него есть право загрузки. // Правки может вносить и загрузивший фото, если у него есть право загрузки.
const canEditPhoto = $derived( const canEditPhoto = $derived(
canEdit || (photo.uploader_id === auth.user?.id && role !== 'viewer') canEdit || (photo?.uploader_id === auth.user?.id && role !== 'viewer')
); );
// Редактирование доступно только из просмотрщика: в режиме сетки вкладка
// «Редактирование» скрыта, панель показывает «Сведения». Сохранённая
// вкладка при этом не теряется — она снова станет активной в просмотрщике.
const activeTab = $derived(viewer ? tab : 'info');
let editingName = $state(false); let editingName = $state(false);
let nameDraft = $state(''); let nameDraft = $state('');
let savingName = $state(false); let savingName = $state(false);
let nameError = $state(''); let nameError = $state('');
let tab = $state<'info' | 'edit'>('info');
let pendingDelete = $state(false); let pendingDelete = $state(false);
let deleting = $state(false); let deleting = $state(false);
@@ -68,15 +79,16 @@
// фото (например, отрендеренные правки) не должны сбрасывать вкладку. // фото (например, отрендеренные правки) не должны сбрасывать вкладку.
let lastPhotoId = ''; let lastPhotoId = '';
$effect(() => { $effect(() => {
const id = photo.id; const id = photo?.id;
if (id === lastPhotoId) return; if (!id || id === lastPhotoId) return;
lastPhotoId = id; lastPhotoId = id;
editingName = false; editingName = false;
nameError = ''; nameError = '';
showAll = false; showAll = false;
tagQuery = ''; tagQuery = '';
tagOpen = false; tagOpen = false;
tab = 'info'; // Вкладку не сбрасываем: при переходе между фото пользователь остаётся
// на том же разделе правой панели.
}); });
let tagQuery = $state(''); let tagQuery = $state('');
@@ -234,28 +246,35 @@ const tabClass =
role="tab" role="tab"
id="photo-tab-info" id="photo-tab-info"
aria-controls="photo-panel-info" aria-controls="photo-panel-info"
aria-selected={tab === 'info'} aria-selected={activeTab === 'info'}
class={tabClass} class={tabClass}
onclick={() => (tab = 'info')} onclick={() => (tab = 'info')}
> >
Сведения Сведения
</button> </button>
{#if viewer}
<button <button
type="button" type="button"
role="tab" role="tab"
id="photo-tab-edit" id="photo-tab-edit"
aria-controls="photo-panel-edit" aria-controls="photo-panel-edit"
aria-selected={tab === 'edit'} aria-selected={activeTab === 'edit'}
class={tabClass} class={tabClass}
onclick={() => (tab = 'edit')} onclick={() => (tab = 'edit')}
> >
Редактирование Редактирование
</button> </button>
{/if}
</div> </div>
{#if tab === 'edit'} {#if activeTab === 'edit'}
<div id="photo-panel-edit" role="tabpanel" aria-labelledby="photo-tab-edit"> <div id="photo-panel-edit" role="tabpanel" aria-labelledby="photo-tab-edit">
<PhotoEditPanel {photo} canEdit={canEditPhoto} onUpdated={(updated) => onRenamed?.(updated)} /> <PhotoEditPanel
{photo}
canEdit={canEditPhoto}
viewer={viewer}
onUpdated={(updated) => onRenamed?.(updated)}
/>
</div> </div>
{:else} {:else}
<div id="photo-panel-info" role="tabpanel" aria-labelledby="photo-tab-info"> <div id="photo-panel-info" role="tabpanel" aria-labelledby="photo-tab-info">
@@ -504,7 +523,8 @@ const tabClass =
labels={prefs.photo_info?.labels ?? {}} labels={prefs.photo_info?.labels ?? {}}
busy={savingPrefs} busy={savingPrefs}
onSave={savePreferences} onSave={savePreferences}
onReset={() => savePreferences({})} onReset={() =>
savePreferences({ photo_info: { visible: [...EXIF_BASE], labels: {} } })}
onClose={() => (settingsOpen = false)} onClose={() => (settingsOpen = false)}
/> />
{/if} {/if}
+291 -87
View File
@@ -10,13 +10,18 @@
import { viewerActions } from '$lib/stores/viewer-actions.svelte'; import { viewerActions } from '$lib/stores/viewer-actions.svelte';
import { viewer } from '$lib/stores/viewer.svelte'; import { viewer } from '$lib/stores/viewer.svelte';
import { edit } from '$lib/stores/edit.svelte'; import { edit } from '$lib/stores/edit.svelte';
import { applyLight, initLightWasm } from '$lib/light-wasm'; import { eyedropper } from '$lib/stores/eyedropper.svelte';
import { applyColor, applyLight, initLightWasm } from '$lib/light-wasm';
import { WebGLPreview } from '$lib/webgl-preview';
import { import {
applyEffectsToPixels,
effectsSeed,
isEmptyColor,
isEmptyEditParams, isEmptyEditParams,
photoFullUrl, isEmptyLight,
photoPreviewUrl,
readEditParams readEditParams
} from '$lib/edit'; } from '$lib/edit';
import { computeViewerSource, editPendingOf } from '$lib/viewer-source';
import type { Photo } from '$lib/types'; import type { Photo } from '$lib/types';
interface Props { interface Props {
@@ -29,11 +34,20 @@
let { photos, index, onClose, onIndexChange }: Props = $props(); let { photos, index, onClose, onIndexChange }: Props = $props();
let fresh = $state<Photo | null>(null); let fresh = $state<Photo | null>(null);
// URL серверного рендера, который уже загружен и декодирован браузером.
// Пока он не готов, показывается предпросмотр — иначе при подмене на
// мгновение мелькает предыдущее изображение (в зуме — оригинал).
let serverImageSrc = $state('');
let touchX = 0; let touchX = 0;
let previewLow = $state(false);
let useGL = $state(false);
const current = $derived(photos[index]); const current = $derived(photos[index]);
const MAX_ZOOM = 2; const MAX_ZOOM = 2;
// В зуме фильтруем уменьшенную копию вьюпорта: предпросмотр остаётся
// отзывчивым, а финальное качество даёт серверный рендер.
const PREVIEW_MAX = 560;
// Шаг зума клавишами `+`/`-`. // Шаг зума клавишами `+`/`-`.
const ZOOM_STEP = 1.25; const ZOOM_STEP = 1.25;
@@ -46,7 +60,6 @@
let isFullscreen = $state(false); let isFullscreen = $state(false);
let zoomed = $state(false); let zoomed = $state(false);
let scale = $state(1); let scale = $state(1);
let hiResLoaded = $state(false);
let panoFailed = $state(false); let panoFailed = $state(false);
let panoRef: { reset: () => void } | undefined = $state(); let panoRef: { reset: () => void } | undefined = $state();
@@ -63,49 +76,76 @@
let startL = 0; let startL = 0;
let startT = 0; let startT = 0;
// Отредактированная версия фото показывается вместо исходной. // Варианты фото. Актуальный объект — current: его обновляют SSE-события,
const previewSrc = $derived( // поэтому URL берутся из него, а fresh остаётся фолбэком для страниц без
(fresh ? photoPreviewUrl(fresh) : undefined) ?? // SSE (просмотр по share-ссылке).
(current ? photoPreviewUrl(current) : undefined) ?? const basePreviewSrc = $derived(current?.preview_url || fresh?.preview_url || '');
fresh?.original_url ?? const originalSrc = $derived(current?.original_url || fresh?.original_url || '');
current?.original_url ?? const editPreviewSrc = $derived(current?.edit_preview_url || fresh?.edit_preview_url || '');
'' const editFullSrc = $derived(current?.edit_url || fresh?.edit_url || '');
); const previewSrc = $derived(editPreviewSrc || basePreviewSrc || originalSrc);
const fullSrc = $derived( const fullSrc = $derived(editFullSrc || originalSrc || '');
(fresh ? photoFullUrl(fresh) : undefined) ?? // Сервер ещё рендерит сохранённые правки: edit-URL не описывают текущую
(current ? photoFullUrl(current) : undefined) ?? // правку. Старый бэкенд поле не присылает — считаем рендер завершённым.
'' const editPending = $derived(current ? editPendingOf(current) : editPendingOf(fresh));
);
const originalSrc = $derived(fresh?.original_url ?? current?.original_url ?? '');
// Базовые (неотредактированные) версии: на них браузер рисует предпросмотр.
const basePreviewSrc = $derived(fresh?.preview_url ?? current?.preview_url ?? '');
// Пока сервер не отрендерил текущие правки, видимую область фото рисует // Пока сервер не отрендерил текущие правки, видимую область фото рисует
// сам браузер: правки видны сразу, без ожидания рендера. // сам браузер: правки видны сразу, без ожидания рендера.
const liveParams = $derived( const liveParams = $derived(
edit.photoId === current?.id ? edit.params : readEditParams(current) edit.photoId === current?.id ? edit.params : readEditParams(current)
); );
const hasEdits = $derived(!isEmptyEditParams(liveParams));
const editUrl = $derived(fresh?.edit_url ?? current?.edit_url ?? '');
const savedParams = $derived(readEditParams(current)); const savedParams = $derived(readEditParams(current));
const pending = $derived( const pending = $derived(
edit.photoId === current?.id && edit.photoId === current?.id &&
JSON.stringify(edit.params) !== JSON.stringify(savedParams) JSON.stringify(edit.params) !== JSON.stringify(savedParams)
); );
const needClientRender = $derived(hasEdits && (pending || !editUrl)); const source = $derived(
const clientPreview = $derived(needClientRender); computeViewerSource({
zoomed,
dirty: pending,
editPending,
localParamsEmpty: isEmptyEditParams(liveParams),
originalUrl: originalSrc,
previewUrl: basePreviewSrc,
editUrl: editFullSrc,
editPreviewUrl: editPreviewSrc
})
);
// Пока браузер рисует правки сам, под ним лежит исходная версия фото. // Переход «предпросмотр → серверная версия». Canvas держится только на
const clientSource = $derived( // время перехода, чтобы не мелькал оригинал; при простом открытии фото с
zoomed ? originalSrc || basePreviewSrc : basePreviewSrc // готовым рендером canvas не нужен — серверную версию грузит сам <img>.
); let previewSwapping = $state(false);
const displaySrc = $derived( let previousUseBase: boolean | null = null;
clientPreview
? clientSource || previewSrc // Подменяем предпросмотр серверной версией только после загрузки и
: zoomed && hiResLoaded && fullSrc // декодирования кадра: пока браузер не готов его показать, остаётся canvas.
? fullSrc $effect(() => {
: previewSrc const useBase = source.useBase;
if (previousUseBase === true && !useBase) previewSwapping = true;
if (useBase) previewSwapping = false;
previousUseBase = useBase;
});
$effect(() => {
if (source.useBase || !previewSwapping) return;
const url = source.serverSrc;
if (!url || serverImageSrc === url) return;
let alive = true;
void decodeImage(url).then((ok) => {
if (alive && ok) serverImageSrc = url;
});
return () => {
alive = false;
};
});
const serverImageReady = $derived(
!previewSwapping || (source.serverSrc !== '' && serverImageSrc === source.serverSrc)
); );
const clientPreview = $derived(source.useBase || !serverImageReady);
const canvasVisible = $derived(source.drawCanvas && clientPreview);
const displaySrc = $derived(clientPreview ? source.baseSrc : source.serverSrc);
const panoTag = $derived(isPanoTag(current) || isPanoTag(fresh)); const panoTag = $derived(isPanoTag(current) || isPanoTag(fresh));
const pano = $derived(panoTag && !panoFailed); const pano = $derived(panoTag && !panoFailed);
const panoSrc = $derived(fullSrc || previewSrc); const panoSrc = $derived(fullSrc || previewSrc);
@@ -115,6 +155,24 @@
fresh?.preview_url ?? fresh?.thumb_url ?? current?.preview_url ?? current?.thumb_url ?? '' fresh?.preview_url ?? fresh?.thumb_url ?? current?.preview_url ?? current?.thumb_url ?? ''
); );
/** Загружает и декодирует изображение; false — загрузить не удалось. */
async function decodeImage(url: string): Promise<boolean> {
return new Promise((resolve) => {
const img = new Image();
img.onload = () => {
if (typeof img.decode !== 'function') {
resolve(true);
return;
}
img.decode()
.then(() => resolve(true))
.catch(() => resolve(true));
};
img.onerror = () => resolve(false);
img.src = url;
});
}
$effect(() => { $effect(() => {
// Пока открыт просмотр, клавиши `+`/`-` относятся к зуму фото. // Пока открыт просмотр, клавиши `+`/`-` относятся к зуму фото.
viewer.open = true; viewer.open = true;
@@ -126,14 +184,20 @@
}; };
}); });
// Фолбэк для страниц без SSE: перечитываем фото при смене версии превью.
// Ответы нумеруются, чтобы устаревший запрос не перебил более новый.
let freshSeq = 0;
$effect(() => { $effect(() => {
const id = current?.id; const id = current?.id;
// Версия фото входит в зависимость: после рендера правок превью // Версия фото входит в зависимость: после рендера правок превью
// меняется, и данные нужно перечитать. // меняется, и данные нужно перечитать.
current?.edit_preview_url ?? current?.preview_url ?? ''; current?.edit_preview_url ?? current?.preview_url ?? '';
if (!id) return; if (!id) return;
const seq = ++freshSeq;
api<{ photo: Photo }>(`/photos/${id}`) api<{ photo: Photo }>(`/photos/${id}`)
.then((data) => (fresh = data.photo)) .then((data) => {
if (seq === freshSeq) fresh = data.photo;
})
.catch(() => {}); .catch(() => {});
}); });
@@ -145,29 +209,14 @@
if (id === lastPhotoId) return; if (id === lastPhotoId) return;
lastPhotoId = id; lastPhotoId = id;
fresh = null; fresh = null;
serverImageSrc = '';
previewSwapping = false;
previousUseBase = null;
zoomed = false; zoomed = false;
scale = 1; scale = 1;
hiResLoaded = false;
panoFailed = false; panoFailed = false;
}); });
// In zoom mode, preload the full-resolution original and swap it in once loaded.
$effect(() => {
if (!zoomed || hiResLoaded) return;
const url = fullSrc;
if (!url) return;
const im = new Image();
let alive = true;
im.onload = () => {
if (alive) hiResLoaded = true;
};
im.src = url;
return () => {
alive = false;
im.onload = null;
};
});
$effect(() => { $effect(() => {
const el = scroller; const el = scroller;
if (!el) return; if (!el) return;
@@ -179,25 +228,73 @@
// Пока сервер не отрендерил отредактированную версию, видимую область // Пока сервер не отрендерил отредактированную версию, видимую область
// фото рисует сам браузер: правки видны сразу, без ожидания рендера. // фото рисует сам браузер: правки видны сразу, без ожидания рендера.
let canvas: HTMLCanvasElement | undefined = $state(); let canvas: HTMLCanvasElement | undefined = $state();
let glCanvas: HTMLCanvasElement | undefined = $state();
let glPreview: WebGLPreview | null = null;
let viewportFrame: number | null = null; let viewportFrame: number | null = null;
$effect(() => {
const el = glCanvas;
if (!el) return;
const preview = WebGLPreview.create(el);
glPreview = preview;
useGL = !!preview;
return () => {
preview?.dispose();
glPreview = null;
useGL = false;
};
});
// Пока пользователь активно крутит контролы, фильтруем уменьшенный буфер,
// а после короткой паузы — полный кадр. Иначе тяжёлый фильтр блокирует UI.
let settleTimer: ReturnType<typeof setTimeout> | null = null;
function markInteracting() {
previewLow = true;
if (settleTimer) clearTimeout(settleTimer);
settleTimer = setTimeout(() => {
settleTimer = null;
previewLow = false;
}, 180);
}
$effect(() => () => {
if (settleTimer) {
clearTimeout(settleTimer);
settleTimer = null;
}
});
/** /**
* Рисует видимую область фото с применёнными правками. Работает и в зуме, * Рисует видимую область фото с применёнными правками. Сначала пробует
* и в обычном виде: берём ту часть картинки, что попала во вьюпорт. * WebGL (кадр считает GPU), затем CPU-фолбэк.
*/ */
function renderViewport() { function renderViewport() {
const c = canvas;
const img = imgEl; const img = imgEl;
const el = scroller; const el = scroller;
if (!c || !img || !el) return; if (!img || !el) return;
const natural = img.naturalWidth; const natural = img.naturalWidth;
if (!natural) return; if (!natural) return;
const imgRect = img.getBoundingClientRect(); const imgRect = img.getBoundingClientRect();
const viewRect = el.getBoundingClientRect(); const viewRect = el.getBoundingClientRect();
if (!imgRect.width || !viewRect.width) return; if (!imgRect.width || !viewRect.width) return;
const ratio = imgRect.width / natural; const width = el.clientWidth;
const height = el.clientHeight;
if (!width || !height) return;
// Видимая часть картинки. // Кусок изображения и его место на холсте.
let crop: { x: number; y: number; width: number; height: number };
let dest: { x: number; y: number; width: number; height: number };
if (!zoomed) {
crop = { x: 0, y: 0, width: natural, height: img.naturalHeight };
dest = {
x: imgRect.left - viewRect.left,
y: imgRect.top - viewRect.top,
width: imgRect.width,
height: imgRect.height
};
} else {
const ratio = imgRect.width / natural;
const left = Math.max(imgRect.left, viewRect.left); const left = Math.max(imgRect.left, viewRect.left);
const top = Math.max(imgRect.top, viewRect.top); const top = Math.max(imgRect.top, viewRect.top);
const right = Math.min(imgRect.right, viewRect.right); const right = Math.min(imgRect.right, viewRect.right);
@@ -205,36 +302,71 @@
const visibleW = right - left; const visibleW = right - left;
const visibleH = bottom - top; const visibleH = bottom - top;
if (visibleW <= 0 || visibleH <= 0) return; if (visibleW <= 0 || visibleH <= 0) return;
crop = {
const width = el.clientWidth; x: (left - imgRect.left) / ratio,
const height = el.clientHeight; y: (top - imgRect.top) / ratio,
if (!width || !height) return; width: visibleW / ratio,
if (c.width !== width || c.height !== height) { height: visibleH / ratio
c.width = width; };
c.height = height; dest = {
x: left - viewRect.left,
y: top - viewRect.top,
width: visibleW,
height: visibleH
};
} }
c.style.width = `${width}px`;
c.style.height = `${height}px`;
// GPU-путь: фильтр целиком на видеокарте, main thread свободен.
if (useGL && glPreview) {
const ok = glPreview.render({
image: img,
imageVersion: `${img.currentSrc || img.src}|${natural}|${img.naturalHeight}`,
imageWidth: natural,
imageHeight: img.naturalHeight,
crop,
viewport: { width, height },
dest,
light: liveParams.light,
color: liveParams.color,
effects: liveParams.effects,
seed: effectsSeed(current?.id ?? ''),
lowQuality: previewLow
});
if (ok) return;
useGL = false;
}
// CPU-фолбэк (если WebGL недоступен).
const c = canvas;
if (!c) return;
const ctx = c.getContext('2d'); const ctx = c.getContext('2d');
if (!ctx) return; if (!ctx) return;
ctx.clearRect(0, 0, width, height); const lowPx = isEmptyLight(liveParams.light) ? 900 : PREVIEW_MAX;
const maxPx = previewLow ? lowPx : 4096;
// Исходный кусок в пикселях картинки и его место на холсте. const k = Math.min(1, maxPx / Math.max(dest.width, dest.height));
const sx = (left - imgRect.left) / ratio; const bw = Math.max(1, Math.round(dest.width * k));
const sy = (top - imgRect.top) / ratio; const bh = Math.max(1, Math.round(dest.height * k));
const sw = visibleW / ratio; if (c.width !== bw || c.height !== bh) {
const sh = visibleH / ratio; c.width = bw;
const dx = Math.round(left - viewRect.left); c.height = bh;
const dy = Math.round(top - viewRect.top); }
const dw = Math.round(visibleW); c.style.left = `${Math.round(dest.x)}px`;
const dh = Math.round(visibleH); c.style.top = `${Math.round(dest.y)}px`;
c.style.width = `${Math.round(dest.width)}px`;
ctx.drawImage(img, sx, sy, sw, sh, dx, dy, dw, dh); c.style.height = `${Math.round(dest.height)}px`;
ctx.clearRect(0, 0, bw, bh);
// Фильтруем весь холст: так прошлый кадр не смешивается с новым. ctx.drawImage(img, crop.x, crop.y, crop.width, crop.height, 0, 0, bw, bh);
const frame = ctx.getImageData(0, 0, width, height); const frame = ctx.getImageData(0, 0, bw, bh);
applyLight(frame.data, liveParams.light); if (!isEmptyLight(liveParams.light)) applyLight(frame.data, liveParams.light);
if (!isEmptyColor(liveParams.color)) applyColor(frame.data, liveParams.color);
// CPU-фолбэк считает только попиксельные эффекты: виньетку и зерно.
applyEffectsToPixels(
frame.data,
liveParams.effects,
bw,
bh,
effectsSeed(current?.id ?? '')
);
ctx.putImageData(frame, 0, 0); ctx.putImageData(frame, 0, 0);
} }
@@ -252,10 +384,23 @@
zoomed; zoomed;
scale; scale;
liveParams.light; liveParams.light;
liveParams.color;
liveParams.effects;
displaySrc; displaySrc;
previewLow;
useGL;
scheduleViewport(); scheduleViewport();
}); });
// Любое изменение параметров — это активное взаимодействие.
let lastLiveParams: typeof liveParams | null = null;
$effect(() => {
const p = liveParams;
if (p === lastLiveParams) return;
lastLiveParams = p;
markInteracting();
});
$effect(() => { $effect(() => {
const onFs = () => { const onFs = () => {
isFullscreen = !!viewerEl && document.fullscreenElement === viewerEl; isFullscreen = !!viewerEl && document.fullscreenElement === viewerEl;
@@ -441,6 +586,7 @@
if (!current || !scroller) return; if (!current || !scroller) return;
ev.preventDefault(); ev.preventDefault();
ev.stopPropagation(); ev.stopPropagation();
markInteracting();
const natW = baseWidth(); const natW = baseWidth();
const natH = baseHeight(); const natH = baseHeight();
@@ -456,6 +602,7 @@
} }
function onPointerDown(ev: PointerEvent) { function onPointerDown(ev: PointerEvent) {
if (eyedropper.mode !== 'none') return;
if (!zoomed || !scroller || ev.pointerType !== 'mouse') return; if (!zoomed || !scroller || ev.pointerType !== 'mouse') return;
dragging = true; dragging = true;
startX = ev.clientX; startX = ev.clientX;
@@ -485,6 +632,46 @@
scheduleViewport(); scheduleViewport();
} }
/** Пипетка: сэмплирует пиксель базового изображения под курсором. */
async function onImageClick(ev: MouseEvent) {
const photo = current;
if (!photo || !imgEl || eyedropper.mode === 'none') return;
const rect = imgEl.getBoundingClientRect();
const x = (ev.clientX - rect.left) / rect.width;
const y = (ev.clientY - rect.top) / rect.height;
if (x < 0 || x > 1 || y < 0 || y > 1) return;
ev.preventDefault();
ev.stopPropagation();
const src = (zoomed ? originalSrc : basePreviewSrc) || basePreviewSrc;
if (!src) return;
try {
const img = new Image();
await new Promise<void>((resolve, reject) => {
img.onload = () => resolve();
img.onerror = () => reject(new Error('image load failed'));
img.src = src;
});
const canvas = document.createElement('canvas');
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
const ctx = canvas.getContext('2d', { willReadFrequently: true });
if (!ctx) return;
ctx.drawImage(img, 0, 0);
const px = Math.min(
img.naturalWidth - 1,
Math.max(0, Math.round(x * (img.naturalWidth - 1)))
);
const py = Math.min(
img.naturalHeight - 1,
Math.max(0, Math.round(y * (img.naturalHeight - 1)))
);
const data = ctx.getImageData(px, py, 1, 1).data;
eyedropper.report(photo.id, data[0], data[1], data[2]);
} catch {
/* изображение не загрузилось — тихо выходим */
}
}
async function toggleViewerFullscreen() { async function toggleViewerFullscreen() {
if (!viewerEl) return; if (!viewerEl) return;
try { try {
@@ -732,7 +919,10 @@
oncontextmenu={onContextMenu} oncontextmenu={onContextMenu}
ontouchstart={onTouchStart} ontouchstart={onTouchStart}
ontouchend={onTouchEnd} ontouchend={onTouchEnd}
onscroll={scheduleViewport} onscroll={() => {
markInteracting();
scheduleViewport();
}}
> >
{#if current} {#if current}
<img <img
@@ -748,12 +938,26 @@
/> />
{/if} {/if}
</div> </div>
{#if clientPreview} {#if eyedropper.mode !== 'none' && eyedropper.photoId === current?.id}
<button
type="button"
class="absolute inset-0 z-20 cursor-crosshair"
aria-label="Выберите нейтральную точку на фото"
onclick={onImageClick}
></button>
{/if}
{#if canvasVisible}
<!-- Правки видны сразу: браузер рисует видимую область, пока <!-- Правки видны сразу: браузер рисует видимую область, пока
сервер готовит отредактированную версию фото. --> сервер готовит отредактированную версию фото. -->
<canvas <canvas
bind:this={canvas} bind:this={canvas}
class="pointer-events-none absolute inset-0 z-10 select-none" class="pointer-events-none absolute inset-0 z-10 select-none"
class:hidden={useGL}
></canvas>
<canvas
bind:this={glCanvas}
class="pointer-events-none absolute inset-0 z-10 select-none"
class:hidden={!useGL}
></canvas> ></canvas>
{/if} {/if}
</div> </div>
+166
View File
@@ -0,0 +1,166 @@
import { describe, expect, it } from 'vitest';
import {
BUILTIN_CURVE_PRESETS,
MAX_CURVE_PRESETS,
exportCurvePresetFile,
findActiveCurvePreset,
normalizeCurvePreset,
normalizeCurvePresets,
parseCurvePresetFile,
presetPointsEqual,
upsertCurvePresets
} from './curve-presets';
import type { CurvePreset } from './types';
const linear = () => [
{ x: 0, y: 0 },
{ x: 1, y: 1 }
];
const medium = BUILTIN_CURVE_PRESETS.find((preset) => preset.name === 'Средний контраст')!;
const custom: CurvePreset = {
name: 'Мой',
channels: {
rgb: [
{ x: 0, y: 0 },
{ x: 0.5, y: 0.6 },
{ x: 1, y: 1 }
],
red: linear(),
green: linear(),
blue: linear()
}
};
describe('пресеты кривой', () => {
it('содержит встроенные пресеты со всеми четырьмя каналами', () => {
expect(BUILTIN_CURVE_PRESETS.map((preset) => preset.name)).toEqual([
'Линейный',
'Средний контраст',
'Сильный контраст'
]);
for (const preset of BUILTIN_CURVE_PRESETS) {
expect(Object.keys(preset.channels).sort()).toEqual(['blue', 'green', 'red', 'rgb']);
for (const channel of ['rgb', 'red', 'green', 'blue'] as const) {
expect(preset.channels[channel].length).toBeGreaterThanOrEqual(2);
}
}
// Контраст задаётся только мастер-кривой, остальные каналы линейные.
expect(medium.channels.rgb).not.toEqual(linear());
expect(medium.channels.red).toEqual(linear());
});
it('валидирует и нормализует пресет со всеми каналами', () => {
expect(normalizeCurvePreset(custom)).toEqual(custom);
expect(normalizeCurvePreset({ ...custom, name: ' Мой ' })).toEqual(custom);
expect(normalizeCurvePreset({ name: 'x', channels: { rgb: linear() } })).toBeNull();
expect(
normalizeCurvePreset({
...custom,
channels: { ...custom.channels, green: [{ x: 0, y: 0 }] }
})
).toBeNull();
expect(
normalizeCurvePreset({
...custom,
channels: { ...custom.channels, blue: [{ x: 0, y: 0 }, { x: 1.2, y: 1 }] }
})
).toBeNull();
expect(normalizeCurvePreset({ ...custom, name: 'a'.repeat(65) })).toBeNull();
});
it('конвертирует старый формат одного канала', () => {
const legacy = normalizeCurvePreset({
name: 'Старый',
channel: 'red',
points: [
{ x: 0, y: 0 },
{ x: 1, y: 0.4 }
]
});
expect(legacy?.channels.rgb).toEqual(linear());
expect(legacy?.channels.red).toEqual([
{ x: 0, y: 0 },
{ x: 1, y: 0.4 }
]);
expect(legacy?.channels.green).toEqual(linear());
expect(legacy?.channels.blue).toEqual(linear());
});
it('сортирует точки и отбрасывает дубликаты', () => {
const preset = normalizeCurvePreset({
...custom,
channels: {
...custom.channels,
rgb: [
{ x: 1, y: 1 },
{ x: 0, y: 0 },
{ x: 0.5, y: 0.6 }
]
}
});
expect(preset?.channels.rgb.map((point) => point.x)).toEqual([0, 0.5, 1]);
});
it('нормализует список из профиля и убирает повторы имён', () => {
expect(normalizeCurvePresets([custom, custom, { name: 'bad' }])).toEqual([custom]);
expect(normalizeCurvePresets('nope')).toEqual([]);
});
it('разбирает и сериализует файл экспорта', () => {
const text = exportCurvePresetFile([custom]);
expect(parseCurvePresetFile(text)).toEqual([custom]);
expect(() => parseCurvePresetFile('not json')).toThrow();
expect(() => parseCurvePresetFile(JSON.stringify({ version: 2, presets: [] }))).toThrow();
expect(() => parseCurvePresetFile(JSON.stringify({ version: 1, presets: [{ name: 'x' }] }))).toThrow();
expect(() =>
parseCurvePresetFile(JSON.stringify({ version: 1, presets: [custom, custom] }))
).toThrow();
});
it('добавляет и перезаписывает пресеты по имени', () => {
const changed: CurvePreset = {
name: 'Мой',
channels: { ...custom.channels, blue: [{ x: 0, y: 0 }, { x: 1, y: 0.5 }] }
};
const next = upsertCurvePresets([custom], [changed]);
expect(next).toHaveLength(1);
expect(next[0].channels.blue).toEqual(changed.channels.blue);
// Копии не должны делить массивы с исходным пресетом.
expect(next[0].channels.red).not.toBe(custom.channels.red);
const other: CurvePreset = { ...custom, name: 'Другой' };
expect(upsertCurvePresets([custom], [other]).map((preset) => preset.name)).toEqual([
'Мой',
'Другой'
]);
expect(() =>
upsertCurvePresets(
Array.from({ length: MAX_CURVE_PRESETS }, (_, i) => ({ ...custom, name: `p${i}` })),
[other]
)
).toThrow();
});
it('находит активный пресет по кривым всех каналов', () => {
expect(findActiveCurvePreset(medium.channels, [])?.name).toBe('Средний контраст');
expect(findActiveCurvePreset(custom.channels, [custom])?.name).toBe('Мой');
expect(
findActiveCurvePreset(
{ ...custom.channels, blue: [{ x: 0, y: 0 }, { x: 1, y: 0.5 }] },
[custom]
)
).toBeUndefined();
expect(
findActiveCurvePreset(
{ rgb: linear(), red: linear(), green: linear(), blue: linear() },
[]
)?.name
).toBe('Линейный');
});
it('сравнивает точки с допуском', () => {
expect(presetPointsEqual([{ x: 0, y: 0 }], [{ x: 1e-9, y: -1e-9 }])).toBe(true);
expect(presetPointsEqual([{ x: 0, y: 0 }], [{ x: 0.1, y: 0 }])).toBe(false);
});
});
+239
View File
@@ -0,0 +1,239 @@
import {
CURVE_CHANNELS,
MAX_CURVE_POINTS,
normalizeCurve,
type CurveChannel,
type CurvePoint
} from './edit';
import type { CurvePreset, CurvePresetChannels } from './types';
export const MAX_CURVE_PRESETS = 100;
export const MAX_CURVE_PRESET_NAME = 64;
export const CURVE_PRESET_FILE_VERSION = 1;
function linearPoints(): CurvePoint[] {
return [
{ x: 0, y: 0 },
{ x: 1, y: 1 }
];
}
function rgbContrastPoints(strong: boolean): CurvePoint[] {
return strong
? [
{ x: 0, y: 0 },
{ x: 0.2, y: 0.12 },
{ x: 0.5, y: 0.5 },
{ x: 0.8, y: 0.88 },
{ x: 1, y: 1 }
]
: [
{ x: 0, y: 0 },
{ x: 0.25, y: 0.2 },
{ x: 0.5, y: 0.5 },
{ x: 0.75, y: 0.8 },
{ x: 1, y: 1 }
];
}
function linearChannels(rgb: CurvePoint[]): CurvePresetChannels {
return {
rgb,
red: linearPoints(),
green: linearPoints(),
blue: linearPoints()
};
}
/** Встроенные пресеты доступны всегда и не сохраняются в профиле. */
export const BUILTIN_CURVE_PRESETS: CurvePreset[] = [
{ name: 'Линейный', channels: linearChannels(linearPoints()) },
{ name: 'Средний контраст', channels: linearChannels(rgbContrastPoints(false)) },
{ name: 'Сильный контраст', channels: linearChannels(rgbContrastPoints(true)) }
];
/** Обрезает имя пресета; null — имя пустое или слишком длинное. */
export function normalizeCurvePresetName(name: unknown): string | null {
if (typeof name !== 'string') return null;
const trimmed = name.trim();
if (!trimmed) return null;
if ([...trimmed].length > MAX_CURVE_PRESET_NAME) return null;
return trimmed;
}
function presetPoints(raw: unknown): CurvePoint[] | null {
if (!Array.isArray(raw) || raw.length < 2 || raw.length > MAX_CURVE_POINTS) return null;
const points: CurvePoint[] = [];
for (const item of raw) {
if (!item || typeof item !== 'object') return null;
const point = item as { x?: unknown; y?: unknown };
if (
typeof point.x !== 'number' ||
typeof point.y !== 'number' ||
!Number.isFinite(point.x) ||
!Number.isFinite(point.y) ||
point.x < 0 ||
point.x > 1 ||
point.y < 0 ||
point.y > 1
) {
return null;
}
points.push({ x: point.x, y: point.y });
}
const normalized = normalizeCurve(points);
if (!normalized || normalized.length < 2) return null;
return normalized;
}
function presetChannels(raw: unknown): CurvePresetChannels | null {
if (!raw || typeof raw !== 'object') return null;
const item = raw as Record<string, unknown>;
const channels = {} as CurvePresetChannels;
for (const channel of CURVE_CHANNELS) {
const points = presetPoints(item[channel]);
if (!points) return null;
channels[channel] = points;
}
return channels;
}
/** Старый формат `{name, channel, points}`: остальные каналы линейные. */
function legacyChannels(item: Record<string, unknown>): CurvePresetChannels | null {
if (typeof item.channel !== 'string') return null;
if (!CURVE_CHANNELS.includes(item.channel as CurveChannel)) return null;
const points = presetPoints(item.points);
if (!points) return null;
const channels = {
rgb: linearPoints(),
red: linearPoints(),
green: linearPoints(),
blue: linearPoints()
};
channels[item.channel as CurveChannel] = points;
return channels;
}
/** Проверяет и нормализует один пресет; null — пресет некорректен. */
export function normalizeCurvePreset(raw: unknown): CurvePreset | null {
if (!raw || typeof raw !== 'object') return null;
const item = raw as Record<string, unknown>;
const name = normalizeCurvePresetName(item.name);
if (!name) return null;
const channels =
item.channels !== undefined ? presetChannels(item.channels) : legacyChannels(item);
if (!channels) return null;
return { name, channels };
}
/** Нормализует список из профиля: некорректные пресеты отбрасываются. */
export function normalizeCurvePresets(raw: unknown): CurvePreset[] {
if (!Array.isArray(raw)) return [];
const out: CurvePreset[] = [];
const names = new Set<string>();
for (const item of raw) {
const preset = normalizeCurvePreset(item);
if (!preset || names.has(preset.name)) continue;
names.add(preset.name);
out.push(preset);
if (out.length >= MAX_CURVE_PRESETS) break;
}
return out;
}
/** Разбирает файл импорта. Любая ошибка отменяет импорт целиком. */
export function parseCurvePresetFile(text: string): CurvePreset[] {
let data: unknown;
try {
data = JSON.parse(text);
} catch {
throw new Error('Файл не является корректным JSON');
}
if (!data || typeof data !== 'object') {
throw new Error('Файл должен содержать объект с пресетами');
}
const file = data as Record<string, unknown>;
if (file.version !== CURVE_PRESET_FILE_VERSION) {
throw new Error('Неподдерживаемая версия файла пресетов');
}
if (!Array.isArray(file.presets)) {
throw new Error('В файле нет списка пресетов');
}
if (file.presets.length > MAX_CURVE_PRESETS) {
throw new Error(`В файле больше ${MAX_CURVE_PRESETS} пресетов`);
}
const presets: CurvePreset[] = [];
const names = new Set<string>();
for (const item of file.presets) {
const preset = normalizeCurvePreset(item);
if (!preset) throw new Error('В файле есть некорректный пресет');
if (names.has(preset.name)) throw new Error(`Пресет «${preset.name}» повторяется`);
names.add(preset.name);
presets.push(preset);
}
return presets;
}
/** Сериализует пользовательские пресеты в формат экспорта. */
export function exportCurvePresetFile(presets: CurvePreset[]): string {
return JSON.stringify({ version: CURVE_PRESET_FILE_VERSION, presets }, null, 2);
}
/** Добавляет или заменяет пресеты по имени. */
export function upsertCurvePresets(
current: CurvePreset[],
incoming: CurvePreset[]
): CurvePreset[] {
const out = current.map((preset) => ({
...preset,
channels: copyChannels(preset.channels)
}));
for (const preset of incoming) {
const index = out.findIndex((item) => item.name === preset.name);
const copy: CurvePreset = {
...preset,
channels: copyChannels(preset.channels)
};
if (index >= 0) out[index] = copy;
else out.push(copy);
}
if (out.length > MAX_CURVE_PRESETS) {
throw new Error(`Не больше ${MAX_CURVE_PRESETS} пресетов`);
}
return out;
}
function copyChannels(channels: CurvePresetChannels): CurvePresetChannels {
return {
rgb: channels.rgb.map((point) => ({ ...point })),
red: channels.red.map((point) => ({ ...point })),
green: channels.green.map((point) => ({ ...point })),
blue: channels.blue.map((point) => ({ ...point }))
};
}
/** Совпадают ли точки кривых (с допуском на округление). */
export function presetPointsEqual(
a: CurvePoint[],
b: CurvePoint[],
epsilon = 1e-6
): boolean {
if (a.length !== b.length) return false;
return a.every(
(point, index) =>
Math.abs(point.x - b[index].x) <= epsilon &&
Math.abs(point.y - b[index].y) <= epsilon
);
}
/** Активный пресет: кривые всех четырёх каналов совпадают с пресетом. */
export function findActiveCurvePreset(
curves: Record<CurveChannel, CurvePoint[]>,
custom: CurvePreset[]
): CurvePreset | undefined {
return [...custom, ...BUILTIN_CURVE_PRESETS].find((preset) =>
CURVE_CHANNELS.every((channel) =>
presetPointsEqual(curves[channel], preset.channels[channel])
)
);
}
+387 -1
View File
@@ -1,9 +1,22 @@
import { describe, expect, it } from 'vitest'; import { describe, expect, it } from 'vitest';
import { import {
applyColorToPixels,
applyGrainToPixels,
applyVignetteToPixels,
buildCurveLUT,
curveSvgPath,
effectiveCurvePoints,
effectsSeed,
emptyColor,
emptyEditParams, emptyEditParams,
emptyEffects,
isEmptyColor,
isEmptyEditParams, isEmptyEditParams,
isEmptyEffects,
normalizeEditParams, normalizeEditParams,
readEditParams normalizeVignette,
readEditParams,
whiteBalanceFromRGB
} from './edit'; } from './edit';
import type { Photo } from './types'; import type { Photo } from './types';
@@ -56,3 +69,376 @@ describe('параметры правок', () => {
expect(points[1].x).toBeCloseTo(0.8); expect(points[1].x).toBeCloseTo(0.8);
}); });
}); });
describe('цветовые параметры', () => {
it('зажимает значения и оттенки колёс', () => {
const params = normalizeEditParams({
light: emptyEditParams().light,
color: {
...emptyColor(),
temperature: 200,
tint: -300,
saturation: -500,
grading: {
...emptyColor().grading,
shadows: { hue: 400, saturation: 150, luminance: 0 },
balance: -200
}
}
});
expect(params.color.temperature).toBe(100);
expect(params.color.tint).toBe(-100);
expect(params.color.saturation).toBe(-100);
expect(params.color.grading.shadows.hue).toBe(360);
expect(params.color.grading.shadows.saturation).toBe(100);
expect(params.color.grading.balance).toBe(-100);
});
it('считает пустыми нулевые цветовые параметры', () => {
expect(isEmptyColor(emptyColor())).toBe(true);
expect(isEmptyColor({ ...emptyColor(), vibrance: 1 })).toBe(false);
const hueOnly = emptyColor();
hueOnly.grading.shadows.hue = 120;
expect(isEmptyColor(hueOnly)).toBe(true);
const grade = emptyColor();
grade.grading.highlights.saturation = 10;
expect(isEmptyColor(grade)).toBe(false);
});
it('читает цвет из метаданных и не теряет свет', () => {
const photo = {
edit_params: {
light: { exposure: 0.5 },
color: { temperature: 20, vibrance: 10 }
}
} as unknown as Photo;
const params = readEditParams(photo);
expect(params.light.exposure).toBe(0.5);
expect(params.color.temperature).toBe(20);
expect(params.color.vibrance).toBe(10);
});
it('осветляет тёплым балансом белого', () => {
const pixels = new Uint8ClampedArray([100, 100, 100, 255]);
applyColorToPixels(pixels, { ...emptyColor(), temperature: 100 });
expect(pixels[0]).toBeGreaterThan(pixels[1]);
expect(pixels[1]).toBeGreaterThan(pixels[2]);
});
it('обеспечивает серый цвет при насыщенности -100', () => {
const pixels = new Uint8ClampedArray([200, 50, 50, 255]);
applyColorToPixels(pixels, { ...emptyColor(), saturation: -100 });
expect(pixels[0]).toBe(pixels[1]);
expect(pixels[1]).toBe(pixels[2]);
});
it('тонирует тени синим колесом', () => {
const color = emptyColor();
color.grading.shadows = { hue: 240, saturation: 100, luminance: 0 };
const pixels = new Uint8ClampedArray([40, 40, 40, 255]);
applyColorToPixels(pixels, color);
expect(pixels[2]).toBeGreaterThan(pixels[0]);
});
it('повышает яркость теней', () => {
const color = emptyColor();
color.grading.shadows = { hue: 0, saturation: 0, luminance: 100 };
const pixels = new Uint8ClampedArray([40, 40, 40, 255]);
applyColorToPixels(pixels, color);
expect(pixels[0]).toBeGreaterThan(40);
});
it('одинаково обрабатывает все строки однородного изображения', () => {
const color = emptyColor();
color.grading.shadows = { hue: 240, saturation: 100, luminance: 20 };
const pixels = new Uint8ClampedArray(64 * 64 * 4);
for (let i = 0; i < pixels.length; i += 4) {
pixels[i] = 40;
pixels[i + 1] = 40;
pixels[i + 2] = 40;
pixels[i + 3] = 255;
}
applyColorToPixels(pixels, color);
for (let i = 4; i < pixels.length; i += 4) {
expect(pixels[i]).toBe(pixels[0]);
expect(pixels[i + 1]).toBe(pixels[1]);
expect(pixels[i + 2]).toBe(pixels[2]);
}
});
it('не трогает прозрачные пиксели', () => {
const pixels = new Uint8ClampedArray([10, 20, 30, 0]);
applyColorToPixels(pixels, {
...emptyColor(),
temperature: 100,
saturation: 100
});
expect(Array.from(pixels)).toEqual([10, 20, 30, 0]);
});
it('подбирает баланс белого по нейтральной точке', () => {
const neutral = whiteBalanceFromRGB(128, 128, 128);
expect(neutral.temperature).toBeCloseTo(0, 5);
expect(neutral.tint).toBeCloseTo(0, 5);
const wb = whiteBalanceFromRGB(150, 140, 120);
const temperature = wb.temperature / 100;
const tint = wb.tint / 100;
const r = 150 * (1 + 0.2 * temperature + 0.1 * tint);
const g = 140 * (1 - 0.2 * tint);
const b = 120 * (1 - 0.2 * temperature + 0.1 * tint);
expect(r).toBeCloseTo(g, 5);
expect(b).toBeCloseTo(g, 5);
});
});
describe('эффекты', () => {
function uniform(width: number, height: number, value = 128): Uint8ClampedArray {
const pixels = new Uint8ClampedArray(width * height * 4);
for (let i = 0; i < pixels.length; i += 4) {
pixels[i] = value;
pixels[i + 1] = value;
pixels[i + 2] = value;
pixels[i + 3] = 255;
}
return pixels;
}
function channel(pixels: Uint8ClampedArray, width: number, x: number, y: number): [number, number, number] {
const i = (y * width + x) * 4;
return [pixels[i], pixels[i + 1], pixels[i + 2]];
}
it('зажимает значения и заполняет дефолты', () => {
const params = normalizeEditParams({
light: emptyEditParams().light,
color: emptyColor(),
effects: {
texture: 500,
clarity: -500,
dehaze: 50,
vignette: {
mode: 'weird' as never,
amount: 200,
midpoint: -10,
feather: 300,
roundness: 500,
highlights: -5,
color: 'red'
},
grain: { amount: -10, size: 500, roughness: -5 }
}
});
expect(params.effects.texture).toBe(100);
expect(params.effects.clarity).toBe(-100);
expect(params.effects.dehaze).toBe(50);
expect(params.effects.vignette.mode).toBe('light');
expect(params.effects.vignette.amount).toBe(100);
expect(params.effects.vignette.midpoint).toBe(0);
expect(params.effects.vignette.feather).toBe(100);
expect(params.effects.vignette.roundness).toBe(100);
expect(params.effects.vignette.highlights).toBe(0);
expect(params.effects.vignette.color).toBe('#000000');
expect(params.effects.grain.amount).toBe(0);
expect(params.effects.grain.size).toBe(100);
expect(params.effects.grain.roughness).toBe(0);
});
it('нормализует цвет виньетки', () => {
expect(normalizeVignette({ color: '#AABBCC' }).color).toBe('#aabbcc');
expect(normalizeVignette({ color: '#abc' }).color).toBe('#aabbcc');
expect(normalizeVignette({ color: 'нет' }).color).toBe('#000000');
expect(normalizeVignette({}).midpoint).toBe(50);
expect(normalizeVignette({}).feather).toBe(50);
});
it('считает пустыми эффекты без силы', () => {
expect(isEmptyEffects(emptyEffects())).toBe(true);
expect(isEmptyEffects({ ...emptyEffects(), texture: 1 })).toBe(false);
const noVignettePower = emptyEffects();
noVignettePower.vignette.amount = 0;
noVignettePower.vignette.midpoint = 90;
noVignettePower.vignette.color = '#ff0000';
expect(isEmptyEffects(noVignettePower)).toBe(true);
const grain = emptyEffects();
grain.grain.amount = 1;
expect(isEmptyEffects(grain)).toBe(false);
});
it('читает эффекты из метаданных и не теряет свет и цвет', () => {
const photo = {
edit_params: {
light: { exposure: 0.5 },
color: { temperature: 20 },
effects: { texture: 30, grain: { amount: 10 } }
}
} as unknown as Photo;
const params = readEditParams(photo);
expect(params.light.exposure).toBe(0.5);
expect(params.color.temperature).toBe(20);
expect(params.effects.texture).toBe(30);
expect(params.effects.grain.amount).toBe(10);
expect(params.effects.grain.size).toBe(25);
expect(isEmptyEditParams(params)).toBe(false);
});
it('затемняет края и не трогает центр', () => {
const pixels = uniform(9, 9);
applyVignetteToPixels(
pixels,
{ ...emptyEffects().vignette, amount: 100 },
9,
9
);
const center = channel(pixels, 9, 4, 4);
const corner = channel(pixels, 9, 0, 0);
expect(center).toEqual([128, 128, 128]);
expect(corner[0]).toBeLessThan(center[0]);
});
it('осветляет края при отрицательной силе', () => {
const pixels = uniform(9, 9);
applyVignetteToPixels(
pixels,
{ ...emptyEffects().vignette, amount: -100 },
9,
9
);
expect(channel(pixels, 9, 0, 0)[0]).toBeGreaterThan(128);
});
it('тонирует и заливает края цветом', () => {
const tinted = uniform(9, 9);
applyVignetteToPixels(
tinted,
{
...emptyEffects().vignette,
mode: 'color',
amount: 100,
color: '#ff0000'
},
9,
9
);
const colorCorner = channel(tinted, 9, 0, 0);
expect(colorCorner[0]).toBeGreaterThan(colorCorner[1]);
expect(colorCorner[0]).toBeGreaterThan(colorCorner[2]);
expect(channel(tinted, 9, 4, 4)).toEqual([128, 128, 128]);
const painted = uniform(9, 9);
applyVignetteToPixels(
painted,
{
...emptyEffects().vignette,
mode: 'colorize',
amount: 100,
color: '#ff0000'
},
9,
9
);
expect(channel(painted, 9, 0, 0)).toEqual([255, 0, 0]);
});
it('не трогает прозрачные пиксели', () => {
const pixels = new Uint8ClampedArray([10, 20, 30, 0]);
applyVignetteToPixels(
pixels,
{ ...emptyEffects().vignette, amount: 100 },
1,
1
);
expect(Array.from(pixels)).toEqual([10, 20, 30, 0]);
});
it('делает зерно детерминированным', () => {
const seed = effectsSeed('photo-1');
const first = uniform(16, 16);
const second = uniform(16, 16);
const grain = { ...emptyEffects().grain, amount: 80 };
applyGrainToPixels(first, grain, 16, 16, seed);
applyGrainToPixels(second, grain, 16, 16, seed);
expect(Array.from(first)).toEqual(Array.from(second));
expect(first[0]).not.toBe(128);
const other = uniform(16, 16);
applyGrainToPixels(other, grain, 16, 16, effectsSeed('photo-2'));
expect(Array.from(other)).not.toEqual(Array.from(first));
});
it('не меняет кадр при нулевой силе зерна', () => {
const pixels = uniform(8, 8);
applyGrainToPixels(pixels, emptyEffects().grain, 8, 8, effectsSeed('photo-1'));
expect(Array.from(pixels)).toEqual(Array.from(uniform(8, 8)));
});
});
describe('кривая', () => {
const medium = [
{ x: 0, y: 0 },
{ x: 0.25, y: 0.2 },
{ x: 0.5, y: 0.5 },
{ x: 0.75, y: 0.8 },
{ x: 1, y: 1 }
];
const strong = [
{ x: 0, y: 0 },
{ x: 0.2, y: 0.12 },
{ x: 0.5, y: 0.5 },
{ x: 0.8, y: 0.88 },
{ x: 1, y: 1 }
];
const inner = [
{ x: 0.1, y: 0.05 },
{ x: 0.4, y: 0.3 },
{ x: 0.9, y: 0.95 }
];
const samples = [0, 32, 64, 128, 192, 224, 255];
it('показывает крайние точки у пустого канала', () => {
expect(effectiveCurvePoints(undefined)).toEqual([
{ x: 0, y: 0 },
{ x: 1, y: 1 }
]);
expect(effectiveCurvePoints([{ x: 0.5, y: 0.4 }])).toEqual([
{ x: 0, y: 0 },
{ x: 1, y: 1 }
]);
expect(effectiveCurvePoints(inner)).toEqual(inner);
});
it('совпадает с серверной PCHIP-кривой', () => {
const values = (points: { x: number; y: number }[]) => {
const lut = buildCurveLUT(points);
return samples.map((i) => lut[i]);
};
expect(values([{ x: 0, y: 0 }, { x: 1, y: 1 }])).toEqual([
0, 32, 64, 128, 192, 224, 255
]);
expect(values(medium)).toEqual([0, 23, 51, 128, 205, 233, 255]);
expect(values(strong)).toEqual([0, 17, 43, 128, 213, 239, 255]);
expect(values(inner)).toEqual([13, 17, 42, 104, 186, 234, 242]);
});
it('остаётся монотонной между точками', () => {
for (const points of [medium, strong]) {
const lut = buildCurveLUT(points);
for (let i = 1; i < lut.length; i++) {
expect(lut[i]).toBeGreaterThanOrEqual(lut[i - 1]);
}
}
});
it('делает плоские полки вне крайних точек', () => {
const lut = buildCurveLUT(inner);
for (let i = 0; i <= Math.floor(0.1 * 255); i++) expect(lut[i]).toBe(13);
for (let i = Math.ceil(0.9 * 255); i < 256; i++) expect(lut[i]).toBe(242);
});
it('рисует плавный SVG-путь с полками', () => {
const path = curveSvgPath(inner);
expect(path.startsWith('M0.0000,95.0000 L10.0000,95.0000')).toBe(true);
expect(path).toContain('C');
expect(path.endsWith('L100.0000,5.0000')).toBe(true);
});
});
+853 -22
View File
@@ -30,10 +30,169 @@ export interface LightParams {
curve: CurveParams; curve: CurveParams;
} }
export interface MixerBand {
hue: number;
saturation: number;
luminance: number;
}
export interface ColorMixer {
red: MixerBand;
orange: MixerBand;
yellow: MixerBand;
green: MixerBand;
aqua: MixerBand;
blue: MixerBand;
purple: MixerBand;
magenta: MixerBand;
}
export interface ColorWheel {
hue: number;
saturation: number;
luminance: number;
}
export interface ColorGrading {
shadows: ColorWheel;
midtones: ColorWheel;
highlights: ColorWheel;
blending: number;
balance: number;
}
export interface ColorCorrection {
red: number;
green: number;
blue: number;
}
export interface ColorParams {
temperature: number;
tint: number;
vibrance: number;
saturation: number;
mixer: ColorMixer;
grading: ColorGrading;
correction: ColorCorrection;
}
export type VignetteMode = 'light' | 'color' | 'colorize';
/** Параметры виньетки: геометрия общая для всех режимов. */
export interface VignetteParams {
/** Режим: «Свет», «Цвет» или «Закарасить». */
mode: VignetteMode;
/** Сила виньетки, -100..100. */
amount: number;
/** Средняя точка, 0..100. */
midpoint: number;
/** Растушёвка, 0..100. */
feather: number;
/** Округлость, -100..100. */
roundness: number;
/** Защита светов, 0..100. */
highlights: number;
/** Цвет виньетки для режимов color/colorize, "#rrggbb". */
color: string;
}
/** Параметры зерна. */
export interface GrainParams {
/** Сила зерна, 0..100. */
amount: number;
/** Размер зерна, 0..100. */
size: number;
/** Шероховатость, 0..100. */
roughness: number;
}
/** Блок «Эффекты»: пространственные эффекты, виньетка и зерно. */
export interface EffectsParams {
texture: number;
clarity: number;
dehaze: number;
vignette: VignetteParams;
grain: GrainParams;
}
export interface EditParams { export interface EditParams {
light: LightParams; light: LightParams;
color: ColorParams;
effects: EffectsParams;
} }
/** Полосы цветового микшера: ключ, подпись и центр оттенка в градусах. */
export const MIXER_BANDS = [
{ key: 'red', label: 'Красное', center: 0 },
{ key: 'orange', label: 'Оранжевое', center: 30 },
{ key: 'yellow', label: 'Жёлтое', center: 60 },
{ key: 'green', label: 'Зелёное', center: 120 },
{ key: 'aqua', label: 'Бирюзовое', center: 180 },
{ key: 'blue', label: 'Синее', center: 240 },
{ key: 'purple', label: 'Фиолетовое', center: 280 },
{ key: 'magenta', label: 'Пурпурное', center: 320 }
] as const;
export type MixerBandKey = (typeof MIXER_BANDS)[number]['key'];
/** Ползунки базового блока «Цвет». */
export const COLOR_SLIDERS = [
{ key: 'temperature', label: 'Темп.', min: -100, max: 100, step: 1 },
{ key: 'tint', label: 'Оттенок', min: -100, max: 100, step: 1 },
{ key: 'vibrance', label: 'Сочность', min: -100, max: 100, step: 1 },
{ key: 'saturation', label: 'Насыщенность', min: -100, max: 100, step: 1 }
] as const;
export type ColorSliderKey = (typeof COLOR_SLIDERS)[number]['key'];
/** Ползунки пространственных эффектов. */
export const EFFECT_SLIDERS = [
{ key: 'texture', label: 'Текстура', min: -100, max: 100, step: 1 },
{ key: 'clarity', label: 'Чёткость', min: -100, max: 100, step: 1 },
{ key: 'dehaze', label: 'Убрать дымку', min: -100, max: 100, step: 1 }
] as const;
export type EffectSliderKey = (typeof EFFECT_SLIDERS)[number]['key'];
/** Ползунки виньетки: общие для всех режимов. */
export const VIGNETTE_SLIDERS = [
{ key: 'amount', label: 'Виньетка', min: -100, max: 100, step: 1 },
{ key: 'midpoint', label: 'Средняя точка', min: 0, max: 100, step: 1 },
{ key: 'feather', label: 'Растушёвка', min: 0, max: 100, step: 1 },
{ key: 'roundness', label: 'Округлость', min: -100, max: 100, step: 1 },
{ key: 'highlights', label: 'Света', min: 0, max: 100, step: 1 }
] as const;
export type VignetteSliderKey = (typeof VIGNETTE_SLIDERS)[number]['key'];
/** Ползунки зерна. */
export const GRAIN_SLIDERS = [
{ key: 'amount', label: 'Зерно', min: 0, max: 100, step: 1 },
{ key: 'size', label: 'Размер', min: 0, max: 100, step: 1 },
{ key: 'roughness', label: 'Шероховатость', min: 0, max: 100, step: 1 }
] as const;
export type GrainSliderKey = (typeof GRAIN_SLIDERS)[number]['key'];
/** Вкладки виньетки. */
export const VIGNETTE_MODES = [
{ key: 'light', label: 'Свет' },
{ key: 'color', label: 'Цвет' },
{ key: 'colorize', label: 'Закарасить' }
] as const;
export const DEFAULT_VIGNETTE_COLOR = '#000000';
/** Колёса точечного цвета. */
export const GRADING_WHEELS = [
{ key: 'shadows', label: 'Тени' },
{ key: 'midtones', label: 'Средние тона' },
{ key: 'highlights', label: 'Света' }
] as const;
export type GradingWheelKey = (typeof GRADING_WHEELS)[number]['key'];
export const CURVE_CHANNELS = ['rgb', 'red', 'green', 'blue'] as const; export const CURVE_CHANNELS = ['rgb', 'red', 'green', 'blue'] as const;
export type CurveChannel = (typeof CURVE_CHANNELS)[number]; export type CurveChannel = (typeof CURVE_CHANNELS)[number];
@@ -73,6 +232,12 @@ export const MAX_EXPOSURE_STOPS = 5;
export const MAX_PERCENT = 100; export const MAX_PERCENT = 100;
export const MAX_CURVE_POINTS = 16; export const MAX_CURVE_POINTS = 16;
/** Крайние точки кривой по умолчанию: линейная кривая. */
export const DEFAULT_CURVE_POINTS: CurvePoint[] = [
{ x: 0, y: 0 },
{ x: 1, y: 1 }
];
export function emptyLight(): LightParams { export function emptyLight(): LightParams {
return { return {
exposure: 0, exposure: 0,
@@ -86,11 +251,61 @@ export function emptyLight(): LightParams {
} }
export function emptyEditParams(): EditParams { export function emptyEditParams(): EditParams {
return { light: emptyLight() }; return { light: emptyLight(), color: emptyColor(), effects: emptyEffects() };
} }
function clamp(v: number, min: number, max: number): number { function emptyMixerBand(): MixerBand {
if (!Number.isFinite(v)) return 0; return { hue: 0, saturation: 0, luminance: 0 };
}
export function emptyColor(): ColorParams {
return {
temperature: 0,
tint: 0,
vibrance: 0,
saturation: 0,
mixer: {
red: emptyMixerBand(),
orange: emptyMixerBand(),
yellow: emptyMixerBand(),
green: emptyMixerBand(),
aqua: emptyMixerBand(),
blue: emptyMixerBand(),
purple: emptyMixerBand(),
magenta: emptyMixerBand()
},
grading: {
shadows: { hue: 0, saturation: 0, luminance: 0 },
midtones: { hue: 0, saturation: 0, luminance: 0 },
highlights: { hue: 0, saturation: 0, luminance: 0 },
blending: 50,
balance: 0
},
correction: { red: 0, green: 0, blue: 0 }
};
}
/** Пустые эффекты: все силы нулевые, геометрия — по умолчанию. */
export function emptyEffects(): EffectsParams {
return {
texture: 0,
clarity: 0,
dehaze: 0,
vignette: {
mode: 'light',
amount: 0,
midpoint: 50,
feather: 50,
roundness: 0,
highlights: 0,
color: DEFAULT_VIGNETTE_COLOR
},
grain: { amount: 0, size: 25, roughness: 50 }
};
}
function clamp(v: number | undefined, min: number, max: number): number {
if (typeof v !== 'number' || !Number.isFinite(v)) return 0;
return Math.min(max, Math.max(min, v)); return Math.min(max, Math.max(min, v));
} }
@@ -113,7 +328,11 @@ export function normalizeCurve(points?: CurvePoint[]): CurvePoint[] | undefined
} }
/** Приводит параметры к допустимым диапазонам. */ /** Приводит параметры к допустимым диапазонам. */
export function normalizeEditParams(params: EditParams): EditParams { export function normalizeEditParams(params: {
light?: Partial<LightParams>;
color?: Partial<ColorParams>;
effects?: Partial<EffectsParams>;
}): EditParams {
const light = params?.light ?? emptyLight(); const light = params?.light ?? emptyLight();
return { return {
light: { light: {
@@ -129,13 +348,112 @@ export function normalizeEditParams(params: EditParams): EditParams {
green: normalizeCurve(light.curve?.green), green: normalizeCurve(light.curve?.green),
blue: normalizeCurve(light.curve?.blue) blue: normalizeCurve(light.curve?.blue)
} }
},
color: normalizeColor(params?.color),
effects: normalizeEffects(params?.effects)
};
}
function normalizeBand(band?: Partial<MixerBand>): MixerBand {
return {
hue: clamp(band?.hue ?? 0, -MAX_PERCENT, MAX_PERCENT),
saturation: clamp(band?.saturation ?? 0, -MAX_PERCENT, MAX_PERCENT),
luminance: clamp(band?.luminance ?? 0, -MAX_PERCENT, MAX_PERCENT)
};
}
function normalizeWheel(wheel?: Partial<ColorWheel>): ColorWheel {
return {
hue: clamp(wheel?.hue ?? 0, 0, 360),
saturation: clamp(wheel?.saturation ?? 0, -MAX_PERCENT, MAX_PERCENT),
luminance: clamp(wheel?.luminance ?? 0, -MAX_PERCENT, MAX_PERCENT)
};
}
/** Приводит цветовые параметры к допустимым диапазонам. */
export function normalizeColor(color?: Partial<ColorParams>): ColorParams {
const mixer: Partial<ColorMixer> = color?.mixer ?? {};
const grading: Partial<ColorGrading> = color?.grading ?? {};
const correction: Partial<ColorCorrection> = color?.correction ?? {};
return {
temperature: clamp(color?.temperature ?? 0, -MAX_PERCENT, MAX_PERCENT),
tint: clamp(color?.tint ?? 0, -MAX_PERCENT, MAX_PERCENT),
vibrance: clamp(color?.vibrance ?? 0, -MAX_PERCENT, MAX_PERCENT),
saturation: clamp(color?.saturation ?? 0, -MAX_PERCENT, MAX_PERCENT),
mixer: {
red: normalizeBand(mixer.red),
orange: normalizeBand(mixer.orange),
yellow: normalizeBand(mixer.yellow),
green: normalizeBand(mixer.green),
aqua: normalizeBand(mixer.aqua),
blue: normalizeBand(mixer.blue),
purple: normalizeBand(mixer.purple),
magenta: normalizeBand(mixer.magenta)
},
grading: {
shadows: normalizeWheel(grading.shadows),
midtones: normalizeWheel(grading.midtones),
highlights: normalizeWheel(grading.highlights),
blending: clamp(grading.blending ?? 50, 0, MAX_PERCENT),
balance: clamp(grading.balance ?? 0, -MAX_PERCENT, MAX_PERCENT)
},
correction: {
red: clamp(correction.red ?? 0, -MAX_PERCENT, MAX_PERCENT),
green: clamp(correction.green ?? 0, -MAX_PERCENT, MAX_PERCENT),
blue: clamp(correction.blue ?? 0, -MAX_PERCENT, MAX_PERCENT)
} }
}; };
} }
/** Пустые ли параметры: фотография не тронута. */ const VIGNETTE_MODE_KEYS: VignetteMode[] = ['light', 'color', 'colorize'];
export function isEmptyEditParams(params: EditParams): boolean {
const light = params.light; /** Приводит hex-цвет виньетки к виду "#rrggbb"; невалидное значение — чёрный. */
export function normalizeVignetteColor(value: unknown): string {
if (typeof value !== 'string') return DEFAULT_VIGNETTE_COLOR;
const raw = value.trim().replace(/^#/, '');
const hex = raw.length === 3 ? raw.replace(/./g, (c) => c + c) : raw;
if (!/^[0-9a-fA-F]{6}$/.test(hex)) return DEFAULT_VIGNETTE_COLOR;
return `#${hex.toLowerCase()}`;
}
/** Приводит параметры виньетки к допустимым диапазонам и дефолтам. */
export function normalizeVignette(v?: Partial<VignetteParams>): VignetteParams {
const mode = VIGNETTE_MODE_KEYS.includes(v?.mode as VignetteMode)
? (v?.mode as VignetteMode)
: 'light';
return {
mode,
amount: clamp(v?.amount ?? 0, -MAX_PERCENT, MAX_PERCENT),
midpoint: clamp(v?.midpoint ?? 50, 0, MAX_PERCENT),
feather: clamp(v?.feather ?? 50, 0, MAX_PERCENT),
roundness: clamp(v?.roundness ?? 0, -MAX_PERCENT, MAX_PERCENT),
highlights: clamp(v?.highlights ?? 0, 0, MAX_PERCENT),
color: normalizeVignetteColor(v?.color)
};
}
/** Приводит параметры зерна к допустимым диапазонам и дефолтам. */
export function normalizeGrain(g?: Partial<GrainParams>): GrainParams {
return {
amount: clamp(g?.amount ?? 0, 0, MAX_PERCENT),
size: clamp(g?.size ?? 25, 0, MAX_PERCENT),
roughness: clamp(g?.roughness ?? 50, 0, MAX_PERCENT)
};
}
/** Приводит эффекты к допустимым диапазонам и дефолтам. */
export function normalizeEffects(effects?: Partial<EffectsParams>): EffectsParams {
return {
texture: clamp(effects?.texture ?? 0, -MAX_PERCENT, MAX_PERCENT),
clarity: clamp(effects?.clarity ?? 0, -MAX_PERCENT, MAX_PERCENT),
dehaze: clamp(effects?.dehaze ?? 0, -MAX_PERCENT, MAX_PERCENT),
vignette: normalizeVignette(effects?.vignette),
grain: normalizeGrain(effects?.grain)
};
}
/** Пустой ли блок «Свет». */
export function isEmptyLight(light: LightParams): boolean {
if ( if (
light.exposure !== 0 || light.exposure !== 0 ||
light.contrast !== 0 || light.contrast !== 0 ||
@@ -154,16 +472,91 @@ export function isEmptyEditParams(params: EditParams): boolean {
return true; return true;
} }
/**
* Цвет можно посчитать быстрым путём (без HSL): не задействованы микшер и
* насыщенность/вибрация — только колёса, яркость зон и температура/оттенок.
*/
export function isColorFast(color: ColorParams): boolean {
if (color.vibrance !== 0 || color.saturation !== 0) return false;
for (const band of MIXER_BANDS) {
const value = color.mixer[band.key];
if (value.hue !== 0 || value.saturation !== 0 || value.luminance !== 0) return false;
}
return true;
}
/** Пустые ли параметры: фотография не тронута. */
export function isEmptyEditParams(params: EditParams): boolean {
return (
isEmptyLight(params.light) && isEmptyColor(params.color) && isEmptyEffects(params.effects)
);
}
/** Пусты ли эффекты: все силы нулевые (дефолты геометрии правкой не считаются). */
export function isEmptyEffects(effects?: EffectsParams): boolean {
if (!effects) return true;
return (
!effects.texture &&
!effects.clarity &&
!effects.dehaze &&
!effects.vignette?.amount &&
!effects.grain?.amount
);
}
/** Пусты ли цветовые параметры: цвет не тронут. */
export function isEmptyColor(color?: ColorParams): boolean {
if (!color) return true;
if (color.temperature || color.tint || color.vibrance || color.saturation) return false;
for (const band of MIXER_BANDS) {
const value = color.mixer[band.key];
if (value?.hue || value?.saturation || value?.luminance) return false;
}
for (const wheel of GRADING_WHEELS) {
const value = color.grading[wheel.key];
// Оттенок колеса без силы или яркости не влияет на картинку.
if (value?.saturation || value?.luminance) return false;
}
const correction = color.correction;
return !correction?.red && !correction?.green && !correction?.blue;
}
/**
* Подбирает баланс белого, при котором нейтральный пиксель (r, g, b) станет
* серым. Возвращает температуру и оттенок в диапазоне -100..100.
*/
export function whiteBalanceFromRGB(
r: number,
g: number,
b: number
): { temperature: number; tint: number } {
const rr = Math.max(1, r);
const gg = Math.max(1, g);
const bb = Math.max(1, b);
const sum = gg * (1 / rr + 1 / bb);
const tint = (sum - 2) / (0.2 * (1 + sum));
const factor = 1 - 0.2 * tint;
const temperature = (gg * (1 / rr - 1 / bb) * factor) / 0.4;
return {
temperature: clamp(temperature * 100, -MAX_PERCENT, MAX_PERCENT),
tint: clamp(tint * 100, -MAX_PERCENT, MAX_PERCENT)
};
}
/** Читает параметры правок из метаданных фото. */ /** Читает параметры правок из метаданных фото. */
export function readEditParams(photo: Photo | null | undefined): EditParams { export function readEditParams(photo: Photo | null | undefined): EditParams {
const raw = photo?.edit_params as { light?: Partial<LightParams> } | undefined; const raw = photo?.edit_params as
if (!raw?.light) return emptyEditParams(); | { light?: Partial<LightParams>; color?: Partial<ColorParams>; effects?: Partial<EffectsParams> }
| undefined;
if (!raw?.light && !raw?.color && !raw?.effects) return emptyEditParams();
return normalizeEditParams({ return normalizeEditParams({
light: { light: {
...emptyLight(), ...emptyLight(),
...raw.light, ...raw?.light,
curve: raw.light.curve ?? {} curve: raw?.light?.curve ?? {}
} },
color: raw?.color ?? emptyColor(),
effects: raw?.effects ?? emptyEffects()
}); });
} }
@@ -185,6 +578,58 @@ export function photoFullUrl(photo: Photo): string | undefined {
return photo.edit_url ?? photo.original_url; return photo.edit_url ?? photo.original_url;
} }
/**
* Точки для отображения: у пустого или некорректного канала показываем
* линейную кривую с крайними точками. Сохранённые точки остаются источником
* истины, если их хотя бы две.
*/
export function effectiveCurvePoints(points?: CurvePoint[]): CurvePoint[] {
const pts = normalizeCurve(points);
if (!pts || pts.length < 2) return DEFAULT_CURVE_POINTS.map((p) => ({ ...p }));
return pts;
}
/**
* Наклоны в контрольных точках для монотонного кубического Эрмита
* (Fritsch–Carlson). Формула совпадает с серверной реализацией.
*/
function curveTangents(points: CurvePoint[]): number[] {
const n = points.length;
if (n < 2) return [];
const h = new Array<number>(n - 1);
const delta = new Array<number>(n - 1);
for (let i = 0; i < n - 1; i++) {
h[i] = points[i + 1].x - points[i].x;
delta[i] = (points[i + 1].y - points[i].y) / h[i];
}
const m = new Array<number>(n).fill(0);
if (n === 2) {
m[0] = delta[0];
m[1] = delta[0];
return m;
}
m[0] = endpointTangent(h[0], h[1], delta[0], delta[1]);
m[n - 1] = endpointTangent(h[n - 2], h[n - 3], delta[n - 2], delta[n - 3]);
for (let i = 1; i < n - 1; i++) {
if (delta[i - 1] * delta[i] <= 0) {
m[i] = 0;
continue;
}
const w1 = 2 * h[i] + h[i - 1];
const w2 = h[i] + 2 * h[i - 1];
m[i] = (w1 + w2) / (w1 / delta[i - 1] + w2 / delta[i]);
}
return m;
}
/** Односторонняя касательная крайней точки с защитой от выбросов. */
function endpointTangent(h0: number, h1: number, d0: number, d1: number): number {
const m = ((2 * h0 + h1) * d0 - h0 * d1) / (h0 + h1);
if (m * d0 <= 0) return 0;
if (d0 * d1 < 0 && Math.abs(m) > Math.abs(3 * d0)) return 3 * d0;
return m;
}
/** /**
* Строит 256-элементную таблицу соответствия по точкам кривой. Математика * Строит 256-элементную таблицу соответствия по точкам кривой. Математика
* повторяет серверную (backend/internal/photos/edit.go), поэтому предпросмотр * повторяет серверную (backend/internal/photos/edit.go), поэтому предпросмотр
@@ -197,25 +642,63 @@ export function buildCurveLUT(points?: CurvePoint[]): Uint8Array {
for (let i = 0; i < 256; i++) lut[i] = i; for (let i = 0; i < 256; i++) lut[i] = i;
return lut; return lut;
} }
const tangents = curveTangents(pts);
for (let i = 0; i < 256; i++) { for (let i = 0; i < 256; i++) {
lut[i] = Math.round(clamp01(curveEval(pts, i / 255)) * 255); lut[i] = Math.round(clamp01(curveEval(pts, tangents, i / 255)) * 255);
} }
return lut; return lut;
} }
function curveEval(points: CurvePoint[], x: number): number { /** Значение плавной кривой в точке x; вне крайних точек — плоская полка. */
function curveEval(points: CurvePoint[], tangents: number[], x: number): number {
if (x <= points[0].x) return points[0].y; if (x <= points[0].x) return points[0].y;
const last = points[points.length - 1]; const last = points[points.length - 1];
if (x >= last.x) return last.y; if (x >= last.x) return last.y;
for (let i = 1; i < points.length; i++) { let i = 1;
if (x > points[i].x) continue; while (i < points.length - 1 && x > points[i].x) i++;
const prev = points[i - 1]; const p0 = points[i - 1];
const cur = points[i]; const p1 = points[i];
if (cur.x - prev.x < 1e-9) return cur.y; const h = p1.x - p0.x;
const t = (x - prev.x) / (cur.x - prev.x); if (h < 1e-9) return p1.y;
return prev.y + t * (cur.y - prev.y); const t = (x - p0.x) / h;
const t2 = t * t;
const t3 = t2 * t;
const h00 = 2 * t3 - 3 * t2 + 1;
const h10 = t3 - 2 * t2 + t;
const h01 = -2 * t3 + 3 * t2;
const h11 = t3 - t2;
return h00 * p0.y + h10 * h * tangents[i - 1] + h01 * p1.y + h11 * h * tangents[i];
}
/**
* SVG-путь кривой в координатах 0..100 (ось Y перевёрнута). Между точками —
* кубические Безье с теми же касательными, что и у LUT; вне крайних точек —
* горизонтальные полки.
*/
export function curveSvgPath(points?: CurvePoint[]): string {
const pts = effectiveCurvePoints(points);
if (pts.length < 2) return 'M0,100 L100,0';
const tangents = curveTangents(pts);
const sx = (x: number) => (clamp01(x) * 100).toFixed(4);
const sy = (y: number) => ((1 - clamp01(y)) * 100).toFixed(4);
const parts: string[] = [`M${sx(0)},${sy(pts[0].y)}`];
if (pts[0].x > 1e-9) parts.push(`L${sx(pts[0].x)},${sy(pts[0].y)}`);
for (let i = 0; i < pts.length - 1; i++) {
const p0 = pts[i];
const p1 = pts[i + 1];
const h = p1.x - p0.x;
if (h < 1e-9) continue;
const c1x = p0.x + h / 3;
const c1y = p0.y + (tangents[i] * h) / 3;
const c2x = p1.x - h / 3;
const c2y = p1.y - (tangents[i + 1] * h) / 3;
parts.push(
`C${sx(c1x)},${sy(c1y)} ${sx(c2x)},${sy(c2y)} ${sx(p1.x)},${sy(p1.y)}`
);
} }
return last.y; const last = pts[pts.length - 1];
if (last.x < 1 - 1e-9) parts.push(`L${sx(1)},${sy(last.y)}`);
return parts.join(' ');
} }
function adjustChannel( function adjustChannel(
@@ -261,3 +744,351 @@ export function applyLightToPixels(data: Uint8ClampedArray, light: LightParams):
data[i + 2] = adjustChannel(data[i + 2], light, master, blue); data[i + 2] = adjustChannel(data[i + 2], light, master, blue);
} }
} }
/** RGB (0..255) -> HSL: оттенок в градусах, насыщенность и яркость в 0..1. */
function rgbToHSL(r: number, g: number, b: number): [number, number, number] {
r /= 255;
g /= 255;
b /= 255;
const max = Math.max(r, g, b);
const min = Math.min(r, g, b);
const l = (max + min) / 2;
if (max === min) return [0, 0, l];
const d = max - min;
const s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
let h: number;
if (max === r) {
h = (g - b) / d + (g < b ? 6 : 0);
} else if (max === g) {
h = (b - r) / d + 2;
} else {
h = (r - g) / d + 4;
}
return [h * 60, s, l];
}
function hueToRGB(p: number, q: number, t: number): number {
if (t < 0) t += 1;
if (t > 1) t -= 1;
if (t < 1 / 6) return p + (q - p) * 6 * t;
if (t < 1 / 2) return q;
if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
return p;
}
/** HSL -> RGB (0..255). */
export function hslToRGB(h: number, s: number, l: number): [number, number, number] {
if (s === 0) {
const v = l * 255;
return [v, v, v];
}
const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
const p = 2 * l - q;
const hk = h / 360;
return [
hueToRGB(p, q, hk + 1 / 3) * 255,
hueToRGB(p, q, hk) * 255,
hueToRGB(p, q, hk - 1 / 3) * 255
];
}
/** Треугольный вес оттенка вокруг центра полосы микшера. */
function bandWeight(h: number, center: number): number {
let d = Math.abs(h - center);
if (d > 180) d = 360 - d;
return clamp01(1 - d / 60);
}
/**
* Применяет правки «Цвет» к пикселям (в том же массиве). Порядок операций
* повторяет серверный рендер: баланс белого, HSL, насыщенность/вибрация,
* микшер, точечный цвет, цветокоррекция.
*/
export function applyColorToPixels(data: Uint8ClampedArray, color: ColorParams): void {
const temperature = color.temperature / 100;
const tint = color.tint / 100;
const vibrance = color.vibrance / 100;
const saturation = color.saturation / 100;
const blending = color.grading.blending / 100;
const balance = color.grading.balance / 100;
const correction = color.correction;
const tints = GRADING_WHEELS.map((wheel) =>
hslToRGB(color.grading[wheel.key].hue, 1, 0.5)
);
const blend = blending;
const hasMixer = MIXER_BANDS.some((band) => {
const value = color.mixer[band.key];
return value.hue !== 0 || value.saturation !== 0 || value.luminance !== 0;
});
for (let i = 0; i + 3 < data.length; i += 4) {
if (data[i + 3] === 0) continue;
let r = data[i];
let g = data[i + 1];
let b = data[i + 2];
// Баланс белого.
r *= 1 + 0.2 * temperature + 0.1 * tint;
g *= 1 - 0.2 * tint;
b *= 1 - 0.2 * temperature + 0.1 * tint;
r = clamp(r, 0, 255);
g = clamp(g, 0, 255);
b = clamp(b, 0, 255);
// Быстрый путь: только колёса/яркость, без микшера и насыщенности —
// не нужен HSL-переход, lightness считается напрямую.
const fast = !hasMixer && saturation === 0 && vibrance === 0;
let weights: number[];
let rr: number;
let gg: number;
let bb: number;
if (fast) {
const max = Math.max(r, g, b);
const min = Math.min(r, g, b);
const l = (max + min) / 510;
const lb = clamp01(l + balance * 0.5);
const shadowW = (1 - lb) * (1 - lb) * (1 - lb) * (1 - lb);
const highlightW = lb * lb * lb * lb;
weights = [shadowW, 1 - shadowW - highlightW, highlightW];
let targetL = l;
GRADING_WHEELS.forEach((wheel, index) => {
targetL +=
((color.grading[wheel.key].luminance ?? 0) / 100) * 0.2 * weights[index];
});
targetL = clamp01(targetL);
const delta = (targetL - l) * 255;
rr = r + delta;
gg = g + delta;
bb = b + delta;
} else {
// RGB -> HSL.
let [h, s, l] = rgbToHSL(r, g, b);
// Насыщенность и вибрация.
if (saturation !== 0 || vibrance !== 0) {
s = clamp01(s * (1 + saturation + vibrance * (1 - s)));
}
// Цветовой микшер.
if (hasMixer) {
for (const band of MIXER_BANDS) {
const value = color.mixer[band.key];
const w = bandWeight(h, band.center);
if (w === 0) continue;
h += (value.hue / 100) * 30 * w;
s = clamp01(s * (1 + (value.saturation / 100) * w));
l = clamp01(l + (value.luminance / 100) * 0.2 * w);
}
}
h = ((h % 360) + 360) % 360;
// Зоны яркости: веса в сумме дают 1, более узкие у теней и светов.
const lb = clamp01(l + balance * 0.5);
const shadowW = (1 - lb) * (1 - lb) * (1 - lb) * (1 - lb);
const highlightW = lb * lb * lb * lb;
weights = [shadowW, 1 - shadowW - highlightW, highlightW];
GRADING_WHEELS.forEach((wheel, index) => {
l = clamp01(
l + ((color.grading[wheel.key].luminance ?? 0) / 100) * 0.2 * weights[index]
);
});
// HSL -> RGB.
[rr, gg, bb] = hslToRGB(h, s, l);
}
// Точечный цвет: три колеса по зонам яркости.
GRADING_WHEELS.forEach((wheel, index) => {
const strength =
(color.grading[wheel.key].saturation / 100) * 0.5 * blend * weights[index];
if (strength === 0) return;
const tintRGB = tints[index];
rr = rr * (1 - strength) + tintRGB[0] * strength;
gg = gg * (1 - strength) + tintRGB[1] * strength;
bb = bb * (1 - strength) + tintRGB[2] * strength;
});
// Цветокоррекция.
rr *= 1 + (correction.red / 100) * 0.5;
gg *= 1 + (correction.green / 100) * 0.5;
bb *= 1 + (correction.blue / 100) * 0.5;
data[i] = Math.round(clamp(rr, 0, 255));
data[i + 1] = Math.round(clamp(gg, 0, 255));
data[i + 2] = Math.round(clamp(bb, 0, 255));
}
}
/** Разбирает "#rrggbb" в RGB (0..255); на входе уже нормализованный цвет. */
function parseHexColor(hex: string): [number, number, number] {
const m = /^#([0-9a-f]{6})$/.exec(hex);
if (!m) return [0, 0, 0];
const value = parseInt(m[1], 16);
return [(value >> 16) & 0xff, (value >> 8) & 0xff, value & 0xff];
}
function smoothstep(edge0: number, edge1: number, x: number): number {
if (edge1 <= edge0) return x < edge0 ? 0 : 1;
const t = clamp01((x - edge0) / (edge1 - edge0));
return t * t * (3 - 2 * t);
}
/** Яркость пикселя (та же формула, что в серверном рендере). */
function luma(r: number, g: number, b: number): number {
return 0.299 * r + 0.587 * g + 0.114 * b;
}
/**
* Применяет виньетку к пикселям (в том же массиве). Математика повторяет
* серверную: нормализованные координаты, суперэллипс по округлости,
* smoothstep по средней точке и растушёвке, три режима.
*/
export function applyVignetteToPixels(
data: Uint8ClampedArray,
vignette: VignetteParams,
width: number,
height: number
): void {
if (!width || !height || !vignette?.amount) return;
const p = 2 * Math.pow(6, vignette.roundness / 100);
const start = 0.15 + 0.85 * (vignette.midpoint / 100);
const feather = 0.02 + 0.48 * (vignette.feather / 100);
const amount = vignette.amount / 100;
const highlights = vignette.highlights / 100;
const tint = parseHexColor(vignette.color);
const tintLuma = luma(tint[0], tint[1], tint[2]);
const colorize = vignette.mode === 'colorize';
const colored = colorize || vignette.mode === 'color';
for (let y = 0; y < height; y++) {
const dy = ((y + 0.5) / height) * 2 - 1;
for (let x = 0; x < width; x++) {
const i = (y * width + x) * 4;
if (data[i + 3] === 0) continue;
const dx = ((x + 0.5) / width) * 2 - 1;
const radius = Math.pow(
Math.pow(Math.abs(dx), p) + Math.pow(Math.abs(dy), p),
1 / p
);
const mask = smoothstep(start, start + feather, radius);
if (mask <= 0) continue;
const r = data[i];
const g = data[i + 1];
const b = data[i + 2];
const y0 = luma(r, g, b);
const light = 1 - highlights * smoothstep(0.5, 1, y0 / 255);
if (!colored) {
let factor = 1 - amount * 0.85 * mask;
const protect = highlights * mask * smoothstep(0.5, 1, y0 / 255);
factor += (1 - factor) * protect;
data[i] = Math.round(clamp(r * factor, 0, 255));
data[i + 1] = Math.round(clamp(g * factor, 0, 255));
data[i + 2] = Math.round(clamp(b * factor, 0, 255));
continue;
}
const strength = Math.abs(amount) * mask * light;
if (strength <= 0) continue;
if (colorize) {
data[i] = Math.round(clamp(r + (tint[0] - r) * strength, 0, 255));
data[i + 1] = Math.round(clamp(g + (tint[1] - g) * strength, 0, 255));
data[i + 2] = Math.round(clamp(b + (tint[2] - b) * strength, 0, 255));
} else {
const target = [tint[0] - tintLuma + y0, tint[1] - tintLuma + y0, tint[2] - tintLuma + y0];
data[i] = Math.round(clamp(r + (target[0] - r) * strength, 0, 255));
data[i + 1] = Math.round(clamp(g + (target[1] - g) * strength, 0, 255));
data[i + 2] = Math.round(clamp(b + (target[2] - b) * strength, 0, 255));
}
}
}
}
/** FNV-1a 64-bit: seed зерна, одинаковый с серверным рендером (photo.id). */
export function effectsSeed(photoId: string): bigint {
let hash = 0xcbf29ce484222325n;
const bytes = new TextEncoder().encode(photoId);
for (const byte of bytes) {
hash ^= BigInt(byte);
hash = (hash * 0x100000001b3n) & 0xffffffffffffffffn;
}
return hash;
}
function mix32(x: number): number {
x = Math.imul(x ^ (x >>> 16), 0x7feb352d);
x = Math.imul(x ^ (x >>> 15), 0x846ca68b);
return (x ^ (x >>> 16)) >>> 0;
}
/** Детерминированный шум в -1..1 по координатам пикселя/ячейки. */
function hashNoise(seedLo: number, seedHi: number, x: number, y: number): number {
let h = seedLo ^ mix32(seedHi ^ mix32(Math.imul(x, 0x9e3779b1) ^ Math.imul(y, 0x85ebca6b)));
h = mix32(h);
return (h / 0xffffffff) * 2 - 1;
}
/**
* Применяет зерно к пикселям (в том же массиве). Детерминировано от seed:
* повторный вызов с теми же аргументами даёт тот же рисунок.
*/
export function applyGrainToPixels(
data: Uint8ClampedArray,
grain: GrainParams,
width: number,
height: number,
seed: bigint
): void {
if (!width || !height || !grain?.amount) return;
const minDim = Math.min(width, height);
const cell = Math.max(1, Math.round((0.0005 + 0.004 * (grain.size / 100)) * minDim));
const roughness = grain.roughness / 100;
const strength = (grain.amount / 100) * 38;
const seedLo = Number(seed & 0xffffffffn);
const seedHi = Number((seed >> 32n) & 0xffffffffn);
for (let y = 0; y < height; y++) {
const fy = y / cell;
const iy = Math.floor(fy);
const ty0 = fy - iy;
const ty = ty0 * ty0 * (3 - 2 * ty0);
for (let x = 0; x < width; x++) {
const i = (y * width + x) * 4;
if (data[i + 3] === 0) continue;
const fx = x / cell;
const ix = Math.floor(fx);
const tx0 = fx - ix;
const tx = tx0 * tx0 * (3 - 2 * tx0);
const v00 = hashNoise(seedLo, seedHi, ix, iy);
const v10 = hashNoise(seedLo, seedHi, ix + 1, iy);
const v01 = hashNoise(seedLo, seedHi, ix, iy + 1);
const v11 = hashNoise(seedLo, seedHi, ix + 1, iy + 1);
const value = v00 + (v10 - v00) * tx + (v01 - v00) * ty + (v00 - v10 - v01 + v11) * tx * ty;
const white = hashNoise(seedLo, seedHi, x, y);
const noise = value * (1 - roughness) + white * roughness;
const y0 = luma(data[i], data[i + 1], data[i + 2]);
const weight = 1 - Math.pow((2 * y0) / 255 - 1, 2);
const delta = noise * strength * weight;
data[i] = Math.round(clamp(data[i] + delta, 0, 255));
data[i + 1] = Math.round(clamp(data[i + 1] + delta, 0, 255));
data[i + 2] = Math.round(clamp(data[i + 2] + delta, 0, 255));
}
}
}
/**
* Применяет эффекты к пикселям кадра (в том же массиве). CPU-фолбэк считает
* только попиксельные эффекты — виньетку и зерно; пространственные эффекты
* появляются после серверного рендера.
*/
export function applyEffectsToPixels(
data: Uint8ClampedArray,
effects: EffectsParams,
width: number,
height: number,
seed: bigint
): void {
applyVignetteToPixels(data, effects.vignette, width, height);
applyGrainToPixels(data, effects.grain, width, height, seed);
}
+81
View File
@@ -0,0 +1,81 @@
import { describe, expect, it } from 'vitest';
import {
defaultSectionCollapse,
EDITOR_SECTIONS_KEY,
loadSectionCollapse,
normalizeSectionCollapse,
saveSectionCollapse
} from './editor-sections';
function memoryStorage(initial: Record<string, string> = {}) {
const data = new Map(Object.entries(initial));
return {
data,
getItem(key: string) {
return data.has(key) ? data.get(key)! : null;
},
setItem(key: string, value: string) {
data.set(key, value);
}
};
}
describe('секции редактора', () => {
it('по умолчанию все секции свёрнуты', () => {
const state = defaultSectionCollapse();
for (const section of [
'light',
'curve',
'color',
'mixer',
'pointColor',
'correction',
'effects'
] as const) {
expect(state[section]).toBe(true);
}
expect(loadSectionCollapse(null)).toEqual(defaultSectionCollapse());
});
it('читает сохранённое состояние и восстанавливает недостающие ключи', () => {
const storage = memoryStorage({
[EDITOR_SECTIONS_KEY]: JSON.stringify({ effects: false, light: false, unknown: false })
});
const state = loadSectionCollapse(storage);
expect(state.effects).toBe(false);
expect(state.light).toBe(false);
expect(state.color).toBe(true);
expect('unknown' in state).toBe(false);
});
it('игнорирует невалидный JSON и небулевы значения', () => {
expect(
loadSectionCollapse(memoryStorage({ [EDITOR_SECTIONS_KEY]: '{oops' }))
).toEqual(defaultSectionCollapse());
expect(normalizeSectionCollapse({ effects: 'no', color: 1 })).toEqual(
defaultSectionCollapse()
);
expect(normalizeSectionCollapse(null)).toEqual(defaultSectionCollapse());
});
it('сохраняет состояние в хранилище', () => {
const storage = memoryStorage();
const state = { ...defaultSectionCollapse(), effects: false, curve: false };
saveSectionCollapse(state, storage);
expect(storage.data.get(EDITOR_SECTIONS_KEY)).toBe(JSON.stringify(state));
expect(loadSectionCollapse(storage)).toEqual(state);
});
it('переживает недоступное хранилище', () => {
const broken = {
getItem() {
throw new Error('denied');
},
setItem() {
throw new Error('denied');
}
};
expect(loadSectionCollapse(broken)).toEqual(defaultSectionCollapse());
expect(() => saveSectionCollapse(defaultSectionCollapse(), broken)).not.toThrow();
});
});
+92
View File
@@ -0,0 +1,92 @@
/**
* Состояние сворачиваемых секций редактора фото.
*
* Все секции по умолчанию свёрнуты, а выбор пользователя хранится в браузере
* (localStorage), поэтому панель открывается в том же виде после перезагрузки
* и переключения фото. Серверные настройки для этого не нужны.
*/
export const EDITOR_SECTIONS = [
'light',
'curve',
'color',
'mixer',
'pointColor',
'correction',
'effects'
] as const;
export type EditorSection = (typeof EDITOR_SECTIONS)[number];
/** true — секция свёрнута. */
export type SectionCollapse = Record<EditorSection, boolean>;
export const EDITOR_SECTIONS_KEY = 'galo.edit.sections';
/** По умолчанию все секции свёрнуты. */
export function defaultSectionCollapse(): SectionCollapse {
return {
light: true,
curve: true,
color: true,
mixer: true,
pointColor: true,
correction: true,
effects: true
};
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
/**
* Приводит сохранённое значение к полному набору секций: неизвестные ключи
* отбрасываются, небулевы значения и отсутствующие ключи получают дефолт.
*/
export function normalizeSectionCollapse(raw: unknown): SectionCollapse {
const defaults = defaultSectionCollapse();
if (!isRecord(raw)) return defaults;
const out = defaults;
for (const section of EDITOR_SECTIONS) {
const value = raw[section];
if (typeof value === 'boolean') out[section] = value;
}
return out;
}
type ReadableStorage = Pick<Storage, 'getItem'>;
type WritableStorage = Pick<Storage, 'setItem'>;
/** Читает состояние секций из браузера; без хранилища — дефолт. */
export function loadSectionCollapse(
storage?: ReadableStorage | null
): SectionCollapse {
const target = storage === undefined ? browserStorage() : storage;
if (!target) return defaultSectionCollapse();
try {
const raw = target.getItem(EDITOR_SECTIONS_KEY);
if (!raw) return defaultSectionCollapse();
return normalizeSectionCollapse(JSON.parse(raw));
} catch {
return defaultSectionCollapse();
}
}
/** Сохраняет состояние секций в браузере; ошибки хранилища игнорируются. */
export function saveSectionCollapse(
state: SectionCollapse,
storage?: WritableStorage | null
): void {
const target = storage === undefined ? browserStorage() : storage;
if (!target) return;
try {
target.setItem(EDITOR_SECTIONS_KEY, JSON.stringify(state));
} catch {
// Приватный режим или переполненное хранилище не должны ломать панель.
}
}
function browserStorage(): Storage | null {
return typeof localStorage === 'undefined' ? null : localStorage;
}
+7 -1
View File
@@ -55,7 +55,13 @@ export const icons = {
check_all: { path: '<path fill="currentColor" d="M18 7l-1.41-1.41l-6.34 6.34l1.41 1.41zm4.24-1.41L11.66 16.17L7.48 12l-1.41 1.41L11.66 19l12-12zM.41 13.41L6 19l1.41-1.41L1.83 12z"/>' }, check_all: { path: '<path fill="currentColor" d="M18 7l-1.41-1.41l-6.34 6.34l1.41 1.41zm4.24-1.41L11.66 16.17L7.48 12l-1.41 1.41L11.66 19l12-12zM.41 13.41L6 19l1.41-1.41L1.83 12z"/>' },
uncheck_all: { path: '<path fill="currentColor" d="M1.79 12l5.58 5.59L5.96 19L.37 13.41zm.45-7.78L12.9 14.89l-1.28 1.28L7.44 12l-1.41 1.41L11.62 19l2.69-2.69l4.89 4.89l1.41-1.41L3.65 2.81zm14.9 9.27L23.62 7L22.2 5.59l-6.48 6.48zm-1.18-6.49l-1.41-1.41l-3.65 3.66l1.41 1.41z"/>' }, uncheck_all: { path: '<path fill="currentColor" d="M1.79 12l5.58 5.59L5.96 19L.37 13.41zm.45-7.78L12.9 14.89l-1.28 1.28L7.44 12l-1.41 1.41L11.62 19l2.69-2.69l4.89 4.89l1.41-1.41L3.65 2.81zm14.9 9.27L23.62 7L22.2 5.59l-6.48 6.48zm-1.18-6.49l-1.41-1.41l-3.65 3.66l1.41 1.41z"/>' },
left_panel_close: { path: '<path fill="currentColor" d="M16.5 16V8l-4 4zM5 21q-.825 0-1.412-.587T3 19V5q0-.825.588-1.412T5 3h14q.825 0 1.413.588T21 5v14q0 .825-.587 1.413T19 21zm5-2h9V5h-9z"/>' }, left_panel_close: { path: '<path fill="currentColor" d="M16.5 16V8l-4 4zM5 21q-.825 0-1.412-.587T3 19V5q0-.825.588-1.412T5 3h14q.825 0 1.413.588T21 5v14q0 .825-.587 1.413T19 21zm5-2h9V5h-9z"/>' },
left_panel_open: { path: '<path fill="currentColor" d="M12.5 8v8l4-4zM5 21q-.825 0-1.412-.587T3 19V5q0-.825.588-1.412T5 3h14q.825 0 1.413.588T21 5v14q0 .825-.587 1.413T19 21zm5-2h9V5h-9z"/>' } left_panel_open: { path: '<path fill="currentColor" d="M12.5 8v8l4-4zM5 21q-.825 0-1.412-.587T3 19V5q0-.825.588-1.412T5 3h14q.825 0 1.413.588T21 5v14q0 .825-.587 1.413T19 21zm5-2h9V5h-9z"/>' },
visibility: { path: '<path fill="currentColor" d="M12 4.5C7 4.5 2.73 7.61 1 12c1.73 4.39 6 7.5 11 7.5s9.27-3.11 11-7.5c-1.73-4.39-6-7.5-11-7.5m0 12.5a5 5 0 1 1 0-10 5 5 0 0 1 0 10m0-2a3 3 0 1 0 0-6 3 3 0 0 0 0 6"/>' },
colorize: { path: '<path fill="currentColor" d="M17.66 5.41l.92.92-2.69 2.69-.92-.92zM17.67 3c-.26 0-.51.1-.71.29l-3.12 3.12-1.93-1.91-1.41 1.41 1.42 1.42L3 16.25V21h4.75l8.92-8.92 1.42 1.42 1.41-1.41-1.92-1.92 3.12-3.12c.4-.4.4-1.03.01-1.42l-2.34-2.34c-.2-.19-.45-.29-.7-.29M6.92 19L5 17.08l8.06-8.06 1.92 1.92z"/>' },
tune: { path: '<path fill="currentColor" d="M3 17v2h6v-2zm0-12v2h10V5zm10 16v-2h8v-2h-8v-2h-2v6zM7 9v2H3v2h4v2h2V9zm14 4v-2H11v2zm-6-4h2V7h4V5h-4V3h-2z"/>' },
blur_on: { path: '<path fill="currentColor" d="M12 3a5 5 0 0 1 0 10 5 5 0 0 1 0-10m-5 6a5 5 0 1 1 0 10 5 5 0 0 1 0-10m10 0a5 5 0 1 1 0 10 5 5 0 0 1 0-10"/>' },
circle: { path: '<path fill="currentColor" d="M12 4a8 8 0 1 0 0 16 8 8 0 0 0 0-16"/>' },
show_chart: { path: '<path fill="currentColor" d="M3 3v18h18v-2H5V3zm16.7 3.3l-1.4-1.4-6.3 6.3-3-3L5 15v-2.8l3.6-3.6 3 3z"/>' }
} satisfies Record<string, IconDef>; } satisfies Record<string, IconDef>;
export type IconName = keyof typeof icons; export type IconName = keyof typeof icons;
+212 -1
View File
@@ -1,6 +1,16 @@
import { readFile } from 'node:fs/promises'; import { readFile } from 'node:fs/promises';
import { beforeAll, describe, expect, it } from 'vitest'; import { beforeAll, describe, expect, it } from 'vitest';
import { applyLightToPixels, buildCurveLUT, emptyEditParams, type LightParams } from './edit'; import {
applyColorToPixels,
applyLightToPixels,
buildCurveLUT,
emptyColor,
emptyEditParams,
GRADING_WHEELS,
MIXER_BANDS,
type ColorParams,
type LightParams
} from './edit';
interface LightExports { interface LightExports {
memory: WebAssembly.Memory; memory: WebAssembly.Memory;
@@ -15,11 +25,14 @@ interface LightExports {
whites: number, whites: number,
blacks: number blacks: number
): void; ): void;
apply_color(data: number, len: number, params: number): void;
} }
let wasm: LightExports; let wasm: LightExports;
const LUTS_OFFSET = 0; const LUTS_OFFSET = 0;
const COLOR_PARAMS_OFFSET = 2048;
const COLOR_PARAM_COUNT = 42;
const PIXELS_OFFSET = 4096; const PIXELS_OFFSET = 4096;
beforeAll(async () => { beforeAll(async () => {
@@ -61,6 +74,44 @@ function applyWasm(pixels: Uint8ClampedArray, light: LightParams): Uint8ClampedA
return new Uint8ClampedArray(mem.buffer, PIXELS_OFFSET, pixels.length).slice(); return new Uint8ClampedArray(mem.buffer, PIXELS_OFFSET, pixels.length).slice();
} }
/** Применяет цветовые правки модулем WASM к копии пикселей. */
function applyColorWasm(pixels: Uint8ClampedArray, color: ColorParams): Uint8ClampedArray {
const mem = wasm.memory;
const need = Math.ceil((PIXELS_OFFSET + pixels.length) / 65536);
const have = mem.buffer.byteLength / 65536;
if (need > have) mem.grow(need - have);
const params = new Float64Array(COLOR_PARAM_COUNT);
params[0] = color.temperature / 100;
params[1] = color.tint / 100;
params[2] = color.vibrance / 100;
params[3] = color.saturation / 100;
MIXER_BANDS.forEach((band, index) => {
const value = color.mixer[band.key];
const base = 4 + index * 3;
params[base] = value.hue / 100;
params[base + 1] = value.saturation / 100;
params[base + 2] = value.luminance / 100;
});
GRADING_WHEELS.forEach((wheel, index) => {
const value = color.grading[wheel.key];
const base = 28 + index * 2;
params[base] = value.hue;
params[base + 1] = value.saturation / 100;
params[34 + index] = (value.luminance ?? 0) / 100;
});
params[37] = color.grading.blending / 100;
params[38] = color.grading.balance / 100;
params[39] = color.correction.red / 100;
params[40] = color.correction.green / 100;
params[41] = color.correction.blue / 100;
new Float64Array(mem.buffer, COLOR_PARAMS_OFFSET, COLOR_PARAM_COUNT).set(params);
new Uint8ClampedArray(mem.buffer, PIXELS_OFFSET, pixels.length).set(pixels);
wasm.apply_color(PIXELS_OFFSET, pixels.length, COLOR_PARAMS_OFFSET);
return new Uint8ClampedArray(mem.buffer, PIXELS_OFFSET, pixels.length).slice();
}
describe('WASM-модуль фильтров', () => { describe('WASM-модуль фильтров', () => {
it('совпадает с JS-реализацией', () => { it('совпадает с JS-реализацией', () => {
const light: LightParams = { const light: LightParams = {
@@ -98,4 +149,164 @@ describe('WASM-модуль фильтров', () => {
const out = applyWasm(new Uint8ClampedArray([100, 100, 100, 255]), light); const out = applyWasm(new Uint8ClampedArray([100, 100, 100, 255]), light);
expect(out[0]).toBeGreaterThan(100); expect(out[0]).toBeGreaterThan(100);
}); });
it('совпадает с JS на большом градиенте (свет)', () => {
const light: LightParams = {
...emptyEditParams().light,
exposure: 0.4,
contrast: 20,
highlights: -20,
shadows: 30
};
const width = 256;
const height = 256;
const source = new Uint8ClampedArray(width * height * 4);
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const i = (y * width + x) * 4;
source[i] = 20 + (y % 200);
source[i + 1] = 30 + (x % 150);
source[i + 2] = 40 + ((x + y) % 120);
source[i + 3] = 255;
}
}
const expected = source.slice();
applyLightToPixels(expected, light);
const actual = applyWasm(source.slice(), light);
expect(Array.from(actual)).toEqual(Array.from(expected));
});
it('совпадает с JS-реализацией цвета', () => {
const color = emptyColor();
color.temperature = 30;
color.tint = -10;
color.vibrance = 20;
color.saturation = -15;
color.mixer.red = { hue: 20, saturation: 30, luminance: -10 };
color.mixer.blue = { hue: -15, saturation: -20, luminance: 10 };
color.grading.shadows = { hue: 240, saturation: 40, luminance: 10 };
color.grading.highlights = { hue: 40, saturation: 20, luminance: -10 };
color.grading.blending = 30;
color.grading.balance = -20;
color.correction = { red: 10, green: -5, blue: 8 };
const source = new Uint8ClampedArray(4 * 64);
for (let i = 0; i < source.length; i += 4) {
source[i] = (i * 7) % 256;
source[i + 1] = (i * 13) % 256;
source[i + 2] = (i * 29) % 256;
source[i + 3] = 255;
}
const expected = source.slice();
applyColorToPixels(expected, color);
const actual = applyColorWasm(source.slice(), color);
expect(Array.from(actual)).toEqual(Array.from(expected));
});
it('не меняет прозрачные пиксели при цветовых правках', () => {
const color = emptyColor();
color.saturation = 100;
color.temperature = 100;
const out = applyColorWasm(new Uint8ClampedArray([10, 20, 30, 0]), color);
expect(Array.from(out)).toEqual([10, 20, 30, 0]);
});
it('совпадает с JS на большом градиенте', () => {
const color = emptyColor();
color.temperature = 25;
color.vibrance = 15;
color.mixer.blue = { hue: -10, saturation: 20, luminance: 10 };
color.grading.shadows = { hue: 240, saturation: 80, luminance: 10 };
color.grading.highlights = { hue: 40, saturation: 30, luminance: -10 };
const width = 256;
const height = 256;
const source = new Uint8ClampedArray(width * height * 4);
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const i = (y * width + x) * 4;
source[i] = 20 + (y % 200);
source[i + 1] = 30 + (x % 150);
source[i + 2] = 40 + ((x + y) % 120);
source[i + 3] = 255;
}
}
const expected = source.slice();
applyColorToPixels(expected, color);
const actual = applyColorWasm(source.slice(), color);
expect(Array.from(actual)).toEqual(Array.from(expected));
});
it('совпадает с JS на быстром пути (только колёса)', () => {
const color = emptyColor();
color.temperature = 20;
color.tint = -10;
color.grading.blending = 50;
color.grading.balance = -20;
color.grading.shadows = { hue: 240, saturation: 70, luminance: 25 };
color.grading.midtones = { hue: 40, saturation: 20, luminance: -15 };
color.grading.highlights = { hue: 200, saturation: 30, luminance: 10 };
const width = 128;
const height = 128;
const source = new Uint8ClampedArray(width * height * 4);
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const i = (y * width + x) * 4;
source[i] = 10 + (y % 220);
source[i + 1] = 20 + (x % 180);
source[i + 2] = 30 + ((x + y) % 160);
source[i + 3] = 255;
}
}
const expected = source.slice();
applyColorToPixels(expected, color);
const actual = applyColorWasm(source.slice(), color);
expect(Array.from(actual)).toEqual(Array.from(expected));
});
it('совпадает с JS на случайных цветовых параметрах', () => {
for (let n = 0; n < 100; n++) {
const color = emptyColor();
color.temperature = Math.random() * 200 - 100;
color.tint = Math.random() * 200 - 100;
color.vibrance = Math.random() * 200 - 100;
color.saturation = Math.random() * 200 - 100;
color.grading.blending = Math.random() * 100;
color.grading.balance = Math.random() * 200 - 100;
color.grading.shadows = {
hue: Math.random() * 360,
saturation: Math.random() * 200 - 100,
luminance: Math.random() * 200 - 100
};
color.grading.midtones = {
hue: Math.random() * 360,
saturation: Math.random() * 200 - 100,
luminance: Math.random() * 200 - 100
};
color.grading.highlights = {
hue: Math.random() * 360,
saturation: Math.random() * 200 - 100,
luminance: Math.random() * 200 - 100
};
const source = new Uint8ClampedArray(64);
for (let i = 0; i < source.length; i += 4) {
source[i] = (i * 7) % 256;
source[i + 1] = (i * 13) % 256;
source[i + 2] = (i * 29) % 256;
source[i + 3] = 255;
}
const expected = source.slice();
applyColorToPixels(expected, color);
const actual = applyColorWasm(source.slice(), color);
for (let i = 0; i < expected.length; i++) {
if (expected[i] !== actual[i]) {
throw new Error(
`mismatch n=${n} i=${i} expected=${expected[i]} actual=${actual[i]} color=${JSON.stringify(color)}`
);
}
}
}
});
}); });
+85 -2
View File
@@ -1,7 +1,15 @@
import { applyLightToPixels, buildCurveLUT, type LightParams } from './edit'; import {
applyColorToPixels,
applyLightToPixels,
buildCurveLUT,
GRADING_WHEELS,
MIXER_BANDS,
type ColorParams,
type LightParams
} from './edit';
/** /**
* WASM-модуль фильтров «Свет». * WASM-модуль фильтров «Свет» и «Цвет».
* *
* Модуль собран из wasm/light (Rust, no_std) и лежит в static/light.wasm. * Модуль собран из wasm/light (Rust, no_std) и лежит в static/light.wasm.
* Он попиксельно применяет правки — это горячий путь предпросмотра в * Он попиксельно применяет правки — это горячий путь предпросмотра в
@@ -10,6 +18,8 @@ import { applyLightToPixels, buildCurveLUT, type LightParams } from './edit';
*/ */
const LUTS_OFFSET = 0; const LUTS_OFFSET = 0;
const COLOR_PARAMS_OFFSET = 2048;
const COLOR_PARAM_COUNT = 42;
const PIXELS_OFFSET = 4096; const PIXELS_OFFSET = 4096;
const PAGE = 65536; const PAGE = 65536;
const LUT_LEN = 256; const LUT_LEN = 256;
@@ -27,6 +37,7 @@ interface LightExports {
whites: number, whites: number,
blacks: number blacks: number
): void; ): void;
apply_color(data: number, len: number, params: number): void;
} }
let exportsRef: LightExports | null = null; let exportsRef: LightExports | null = null;
@@ -141,3 +152,75 @@ export function applyLight(data: Uint8ClampedArray, light: LightParams): void {
if (wasmMatchesReference(light) && applyLightWasm(data, light)) return; if (wasmMatchesReference(light) && applyLightWasm(data, light)) return;
applyLightToPixels(data, light); applyLightToPixels(data, light);
} }
/** Пишет f64-блок цветовых параметров в память модуля. */
function writeColorParams(mem: WebAssembly.Memory, color: ColorParams): void {
const params = new Float64Array(COLOR_PARAM_COUNT);
params[0] = color.temperature / 100;
params[1] = color.tint / 100;
params[2] = color.vibrance / 100;
params[3] = color.saturation / 100;
MIXER_BANDS.forEach((band, index) => {
const value = color.mixer[band.key];
const base = 4 + index * 3;
params[base] = value.hue / 100;
params[base + 1] = value.saturation / 100;
params[base + 2] = value.luminance / 100;
});
GRADING_WHEELS.forEach((wheel, index) => {
const value = color.grading[wheel.key];
const base = 28 + index * 2;
params[base] = value.hue;
params[base + 1] = value.saturation / 100;
params[34 + index] = (value.luminance ?? 0) / 100;
});
params[37] = color.grading.blending / 100;
params[38] = color.grading.balance / 100;
params[39] = color.correction.red / 100;
params[40] = color.correction.green / 100;
params[41] = color.correction.blue / 100;
new Float64Array(mem.buffer, COLOR_PARAMS_OFFSET, COLOR_PARAM_COUNT).set(params);
}
/**
* Применяет цветовые правки к пикселям. Возвращает false, если модуль не
* готов и вызывающий код должен использовать JS-реализацию.
*/
export function applyColorWasm(data: Uint8ClampedArray, color: ColorParams): boolean {
const ex = exportsRef;
if (!ex) return false;
const bytes = PIXELS_OFFSET + data.length;
const mem = ensureMemory(bytes);
if (!mem) return false;
writeColorParams(mem, color);
new Uint8ClampedArray(mem.buffer, PIXELS_OFFSET, data.length).set(data);
ex.apply_color(PIXELS_OFFSET, data.length, COLOR_PARAMS_OFFSET);
data.set(new Uint8ClampedArray(mem.buffer, PIXELS_OFFSET, data.length));
return true;
}
/** Сверяет цветовой модуль с эталонной JS-реализацией на образце. */
function colorWasmMatchesReference(color: ColorParams): boolean {
const probe = new Uint8ClampedArray(16 * 4);
for (let i = 0; i < probe.length; i += 4) {
probe[i] = (i * 7) % 256;
probe[i + 1] = (i * 13) % 256;
probe[i + 2] = (i * 29) % 256;
probe[i + 3] = 255;
}
const expected = new Uint8ClampedArray(probe);
applyColorToPixels(expected, color);
const actual = new Uint8ClampedArray(probe);
if (!applyColorWasm(actual, color)) return false;
for (let i = 0; i < expected.length; i++) {
if (expected[i] !== actual[i]) return false;
}
return true;
}
/** Применяет цвет: сначала WASM, при его недоступности — JS. */
export function applyColor(data: Uint8ClampedArray, color: ColorParams): void {
if (colorWasmMatchesReference(color) && applyColorWasm(data, color)) return;
applyColorToPixels(data, color);
}
@@ -0,0 +1,39 @@
/**
* Режим пипетки: панель редактирования включает его, а просмотрщик сообщает
* цвет пикселя, по которому кликнули.
*/
export type EyedropperMode = 'none' | 'wb';
export interface EyedropperSample {
photoId: string;
r: number;
g: number;
b: number;
seq: number;
}
class EyedropperStore {
mode = $state<EyedropperMode>('none');
photoId = $state('');
sample = $state<EyedropperSample | null>(null);
private seq = 0;
start(mode: EyedropperMode, photoId: string) {
this.mode = mode;
this.photoId = photoId;
}
stop() {
this.mode = 'none';
this.photoId = '';
}
report(photoId: string, r: number, g: number, b: number) {
if (this.mode === 'none' || this.photoId !== photoId) return;
this.seq += 1;
this.sample = { photoId, r, g, b, seq: this.seq };
this.stop();
}
}
export const eyedropper = new EyedropperStore();
+23
View File
@@ -3,8 +3,27 @@ export interface PhotoInfoPreferences {
labels?: Record<string, string>; labels?: Record<string, string>;
} }
export interface CurvePresetPoint {
x: number;
y: number;
}
export interface CurvePresetChannels {
rgb: CurvePresetPoint[];
red: CurvePresetPoint[];
green: CurvePresetPoint[];
blue: CurvePresetPoint[];
}
/** Пользовательский пресет тоновой кривой: кривые всех четырёх каналов. */
export interface CurvePreset {
name: string;
channels: CurvePresetChannels;
}
export interface Preferences { export interface Preferences {
photo_info?: PhotoInfoPreferences; photo_info?: PhotoInfoPreferences;
curve_presets?: CurvePreset[];
} }
export interface User { export interface User {
@@ -60,6 +79,10 @@ export interface Photo {
caption: string; caption: string;
exif?: Record<string, unknown>; exif?: Record<string, unknown>;
edit_params?: Record<string, unknown>; edit_params?: Record<string, unknown>;
// edit_pending is true while the server renders the saved edit parameters,
// so the edit_* URLs do not describe the current edit yet. Older backends
// omit the field (treated as false).
edit_pending?: boolean;
tags?: Tag[]; tags?: Tag[];
deleted_at?: string | null; deleted_at?: string | null;
album_title?: string; album_title?: string;
+120
View File
@@ -0,0 +1,120 @@
import { describe, expect, it } from 'vitest';
import type { Photo } from './types';
import { computeViewerSource, editPendingOf } from './viewer-source';
const BASE = {
originalUrl: '/orig.jpg',
previewUrl: '/preview.jpg',
editUrl: '/edit.jpg',
editPreviewUrl: '/edit-preview.jpg'
};
describe('computeViewerSource', () => {
it('shows the server render when it matches the saved edits', () => {
const src = computeViewerSource({
zoomed: false,
dirty: false,
editPending: false,
localParamsEmpty: false,
...BASE
});
expect(src.useBase).toBe(false);
expect(src.serverSrc).toBe('/edit-preview.jpg');
expect(src.baseSrc).toBe('/preview.jpg');
});
it('uses the full-size variants in zoom', () => {
const src = computeViewerSource({
zoomed: true,
dirty: false,
editPending: false,
localParamsEmpty: false,
...BASE
});
expect(src.serverSrc).toBe('/edit.jpg');
expect(src.baseSrc).toBe('/orig.jpg');
});
it('keeps the client preview while local edits are unsaved', () => {
const src = computeViewerSource({
zoomed: true,
dirty: true,
editPending: false,
localParamsEmpty: false,
...BASE
});
expect(src.useBase).toBe(true);
expect(src.drawCanvas).toBe(true);
expect(src.baseSrc).toBe('/orig.jpg');
});
it('shows the base version immediately when the edits are reset to defaults', () => {
const src = computeViewerSource({
zoomed: true,
dirty: true,
editPending: false,
localParamsEmpty: true,
...BASE
});
expect(src.useBase).toBe(true);
expect(src.drawCanvas).toBe(false);
expect(src.baseSrc).toBe('/orig.jpg');
});
it('ignores a stale server render while the saved edits are still rendering', () => {
const src = computeViewerSource({
zoomed: false,
dirty: false,
editPending: true,
localParamsEmpty: false,
...BASE
});
expect(src.useBase).toBe(true);
expect(src.drawCanvas).toBe(true);
});
it('keeps the client preview when a second edit is pending over an old render', () => {
const src = computeViewerSource({
zoomed: true,
dirty: false,
editPending: true,
localParamsEmpty: false,
...BASE
});
expect(src.useBase).toBe(true);
expect(src.drawCanvas).toBe(true);
expect(src.baseSrc).toBe('/orig.jpg');
});
it('falls back to the base version when there is no edit render', () => {
const src = computeViewerSource({
zoomed: false,
dirty: false,
editPending: false,
localParamsEmpty: true,
originalUrl: '/orig.jpg',
previewUrl: '/preview.jpg'
});
expect(src.useBase).toBe(true);
expect(src.drawCanvas).toBe(false);
expect(src.serverSrc).toBe('/preview.jpg');
});
it('prefers the full-size base when zoomed without a preview', () => {
const src = computeViewerSource({
zoomed: true,
dirty: false,
editPending: false,
localParamsEmpty: true,
originalUrl: '/orig.jpg'
});
expect(src.baseSrc).toBe('/orig.jpg');
expect(src.serverSrc).toBe('/orig.jpg');
});
it('treats the old backend without edit_pending as a finished render', () => {
expect(editPendingOf(undefined)).toBe(false);
expect(editPendingOf({ id: 'p' } as Photo)).toBe(false);
expect(editPendingOf({ id: 'p', edit_pending: true } as Photo)).toBe(true);
});
});
+77
View File
@@ -0,0 +1,77 @@
import type { Photo } from './types';
/**
* Выбор изображения для просмотрщика. Модуль намеренно не использует руны
* Svelte: правила подмены предпросмотра серверной версией можно проверить
* обычными unit-тестами.
*
* Состояния:
* - локальные правки ещё не сохранены (`dirty`) или сервер ещё рендерит
* сохранённые правки (`editPending`) — показывать нельзя серверный рендер,
* он не соответствует параметрам; показываем базовую версию, поверх неё
* рисуется клиентский предпросмотр;
* - локальные правки пусты (сброс возвратом контролов) — сразу базовую версию
* без предпросмотра, не дожидаясь отложенного сохранения;
* - серверный рендер соответствует сохранённым правкам — показываем его, но
* только после загрузки и декодирования (решает компонент).
*/
export interface ViewerSourceInput {
/** Пользователь увеличил фото: показываем полноразмерную версию. */
zoomed: boolean;
/** Локальные параметры отличаются от сохранённых на сервере. */
dirty: boolean;
/** Сервер ещё рендерит сохранённые правки (Photo.edit_pending). */
editPending: boolean;
/** Локальные параметры правок пусты (значения по умолчанию). */
localParamsEmpty: boolean;
originalUrl?: string;
previewUrl?: string;
editUrl?: string;
editPreviewUrl?: string;
}
export interface ViewerSource {
/** Показывать базовую (неотредактированную) версию вместо серверного рендера. */
useBase: boolean;
/** Рисовать клиентский предпросмотр поверх базовой версии. */
drawCanvas: boolean;
/** URL базовой версии — подложка под предпросмотр. */
baseSrc: string;
/** URL серверной версии, который можно показать после загрузки. */
serverSrc: string;
}
/** Первый непустой URL из списка. */
function pick(urls: (string | undefined)[]): string {
for (const url of urls) {
if (url) return url;
}
return '';
}
/**
* Признак незавершённого рендера правок, устойчивый к старому бэкенду: поле
* `edit_pending` может отсутствовать, тогда рендер считается завершённым.
*/
export function editPendingOf(photo: Photo | null | undefined): boolean {
return photo?.edit_pending === true;
}
/** Вычисляет источник изображения для просмотрщика. */
export function computeViewerSource(input: ViewerSourceInput): ViewerSource {
const baseSrc = input.zoomed
? pick([input.originalUrl, input.previewUrl])
: pick([input.previewUrl, input.originalUrl]);
const serverSrc = input.zoomed
? pick([input.editUrl, input.editPreviewUrl])
: pick([input.editPreviewUrl, input.editUrl]);
const useBase = input.dirty || input.editPending || !serverSrc;
return {
useBase,
// Пустые локальные правки — это исходный вид: предпросмотр не нужен,
// базовая версия уже показывает оригинал.
drawCanvas: !input.localParamsEmpty,
baseSrc,
serverSrc: serverSrc || baseSrc
};
}
File diff suppressed because it is too large Load Diff
Binary file not shown.
+269
View File
@@ -108,3 +108,272 @@ fn adjust(
let idx = clampi((v + 0.5) as i32, 0, 255) as usize; let idx = clampi((v + 0.5) as i32, 0, 255) as usize;
channel[idx] channel[idx]
} }
/// Количество f64-параметров цвета.
const COLOR_PARAM_COUNT: usize = 42;
/// Центры полос цветового микшера в градусах.
const BAND_CENTERS: [f64; 8] = [0.0, 30.0, 60.0, 120.0, 180.0, 240.0, 280.0, 320.0];
#[inline(always)]
fn clampf(v: f64, lo: f64, hi: f64) -> f64 {
if v < lo {
lo
} else if v > hi {
hi
} else {
v
}
}
#[inline(always)]
fn clamp01d(v: f64) -> f64 {
clampf(v, 0.0, 1.0)
}
#[inline(always)]
fn to_u8(v: f64) -> u8 {
(clampf(v, 0.0, 255.0) + 0.5) as u8
}
/// RGB (0..255) -> HSL: оттенок в градусах, насыщенность и яркость в 0..1.
fn rgb_to_hsl(r: f64, g: f64, b: f64) -> (f64, f64, f64) {
let r = r / 255.0;
let g = g / 255.0;
let b = b / 255.0;
let max = if r > g { if r > b { r } else { b } } else if g > b { g } else { b };
let min = if r < g { if r < b { r } else { b } } else if g < b { g } else { b };
let l = (max + min) / 2.0;
if max == min {
return (0.0, 0.0, l);
}
let d = max - min;
let s = if l > 0.5 {
d / (2.0 - max - min)
} else {
d / (max + min)
};
let mut h;
if max == r {
h = (g - b) / d;
if g < b {
h += 6.0;
}
} else if max == g {
h = (b - r) / d + 2.0;
} else {
h = (r - g) / d + 4.0;
}
(h * 60.0, s, l)
}
fn hue_to_rgb(p: f64, q: f64, mut t: f64) -> f64 {
if t < 0.0 {
t += 1.0;
}
if t > 1.0 {
t -= 1.0;
}
if t < 1.0 / 6.0 {
p + (q - p) * 6.0 * t
} else if t < 1.0 / 2.0 {
q
} else if t < 2.0 / 3.0 {
p + (q - p) * (2.0 / 3.0 - t) * 6.0
} else {
p
}
}
/// HSL -> RGB (0..255).
fn hsl_to_rgb(h: f64, s: f64, l: f64) -> (f64, f64, f64) {
if s == 0.0 {
let v = l * 255.0;
return (v, v, v);
}
let q = if l < 0.5 {
l * (1.0 + s)
} else {
l + s - l * s
};
let p = 2.0 * l - q;
let hk = h / 360.0;
(
hue_to_rgb(p, q, hk + 1.0 / 3.0) * 255.0,
hue_to_rgb(p, q, hk) * 255.0,
hue_to_rgb(p, q, hk - 1.0 / 3.0) * 255.0,
)
}
fn band_weight(h: f64, center: f64) -> f64 {
let mut d = h - center;
if d < 0.0 {
d = -d;
}
if d > 180.0 {
d = 360.0 - d;
}
clamp01d(1.0 - d / 60.0)
}
/// Применяет правки «Цвет» к пикселям RGBA в памяти.
///
/// `params` — блок из `COLOR_PARAM_COUNT` значений f64, подготовленный
/// вызывающим кодом. Порядок операций повторяет серверный рендер и JS.
#[no_mangle]
pub extern "C" fn apply_color(data: *mut u8, len: u32, params: *const f64) {
let p = unsafe { core::slice::from_raw_parts(params, COLOR_PARAM_COUNT) };
let temperature = p[0];
let tint = p[1];
let vibrance = p[2];
let saturation = p[3];
let blending = p[37];
let balance = p[38];
let blend = blending;
// Микшер часто пуст (правят только колёса) — тогда не тратим на него время.
let mut has_mixer = false;
let mut band = 0usize;
while band < 8 {
let base = 4 + band * 3;
if p[base] != 0.0 || p[base + 1] != 0.0 || p[base + 2] != 0.0 {
has_mixer = true;
break;
}
band += 1;
}
let mut tints = [(0.0f64, 0.0f64, 0.0f64); 3];
let mut w = 0usize;
while w < 3 {
tints[w] = hsl_to_rgb(p[28 + w * 2], 1.0, 0.5);
w += 1;
}
let buf = unsafe { core::slice::from_raw_parts_mut(data, len as usize) };
let mut i = 0usize;
while i + 3 < buf.len() {
let alpha = unsafe { *buf.get_unchecked(i + 3) };
if alpha != 0 {
let mut r = unsafe { *buf.get_unchecked(i) } as f64;
let mut g = unsafe { *buf.get_unchecked(i + 1) } as f64;
let mut b = unsafe { *buf.get_unchecked(i + 2) } as f64;
// Баланс белого.
r *= 1.0 + 0.2 * temperature + 0.1 * tint;
g *= 1.0 - 0.2 * tint;
b *= 1.0 - 0.2 * temperature + 0.1 * tint;
r = clampf(r, 0.0, 255.0);
g = clampf(g, 0.0, 255.0);
b = clampf(b, 0.0, 255.0);
// Быстрый путь: только колёса/яркость, без микшера и насыщенности.
// Тогда HSL-переход не нужен — lightness считается напрямую.
let fast = !has_mixer && saturation == 0.0 && vibrance == 0.0;
let weights: [f64; 3];
let mut rr: f64;
let mut gg: f64;
let mut bb: f64;
if fast {
let max = if r > g { if r > b { r } else { b } } else if g > b { g } else { b };
let min = if r < g { if r < b { r } else { b } } else if g < b { g } else { b };
let l = (max + min) / 510.0;
let lb = clamp01d(l + balance * 0.5);
let shadow_w = {
let t = (1.0 - lb) * (1.0 - lb);
t * t
};
let highlight_w = {
let t = lb * lb;
t * t
};
weights = [shadow_w, 1.0 - shadow_w - highlight_w, highlight_w];
let mut target_l = l;
let mut wheel = 0usize;
while wheel < 3 {
target_l += p[34 + wheel] * 0.2 * weights[wheel];
wheel += 1;
}
target_l = clamp01d(target_l);
let delta = (target_l - l) * 255.0;
rr = r + delta;
gg = g + delta;
bb = b + delta;
} else {
// RGB -> HSL.
let (mut h, mut s, mut l) = rgb_to_hsl(r, g, b);
// Насыщенность и вибрация.
if saturation != 0.0 || vibrance != 0.0 {
s = clamp01d(s * (1.0 + saturation + vibrance * (1.0 - s)));
}
// Цветовой микшер.
if has_mixer {
let mut band = 0usize;
while band < 8 {
let base = 4 + band * 3;
let weight = band_weight(h, BAND_CENTERS[band]);
if weight != 0.0 {
h += p[base] * 30.0 * weight;
s = clamp01d(s * (1.0 + p[base + 1] * weight));
l = clamp01d(l + p[base + 2] * 0.2 * weight);
}
band += 1;
}
}
h = h % 360.0;
if h < 0.0 {
h += 360.0;
}
let lb = clamp01d(l + balance * 0.5);
let shadow_w = {
let t = (1.0 - lb) * (1.0 - lb);
t * t
};
let highlight_w = {
let t = lb * lb;
t * t
};
weights = [shadow_w, 1.0 - shadow_w - highlight_w, highlight_w];
let mut wheel = 0usize;
while wheel < 3 {
l = clamp01d(l + p[34 + wheel] * 0.2 * weights[wheel]);
wheel += 1;
}
let (r2, g2, b2) = hsl_to_rgb(h, s, l);
rr = r2;
gg = g2;
bb = b2;
}
// Точечный цвет: три колеса по зонам яркости.
let mut wheel = 0usize;
while wheel < 3 {
let strength = p[28 + wheel * 2 + 1] * 0.5 * blend * weights[wheel];
if strength != 0.0 {
let t = tints[wheel];
rr = rr * (1.0 - strength) + t.0 * strength;
gg = gg * (1.0 - strength) + t.1 * strength;
bb = bb * (1.0 - strength) + t.2 * strength;
}
wheel += 1;
}
// Цветокоррекция.
rr *= 1.0 + p[39] * 0.5;
gg *= 1.0 + p[40] * 0.5;
bb *= 1.0 + p[41] * 0.5;
unsafe {
*buf.get_unchecked_mut(i) = to_u8(rr);
*buf.get_unchecked_mut(i + 1) = to_u8(gg);
*buf.get_unchecked_mut(i + 2) = to_u8(bb);
} }
i += 4;
}
}
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-10-23
@@ -0,0 +1,112 @@
# Design
## Context
Неразрушающее редактирование фото уже работает: параметры хранятся в
`photo.edit_params` (`map[string]any` JSON-блоб), сервер рендерит копию в роли
`edit`, `edit_thumb`, `edit_medium`, `edit_preview`, оригинал не меняется.
Исторически поддерживался только блок «Свет» (`LightParams`), живой превью шёл
через WASM (`frontend/wasm/light/`). Теперь добавлен блок «Цвет» и GPU-превью:
основной live-предпросмотр считает WebGL2, а CPU-путь (TypeScript/WASM) остаётся
фолбэком и эталоном паритета. Хранение в JSON-блобе миграции не требует: фото без
ключа `color` рендерятся как прежде.
## Goals / Non-Goals
**Goals:**
- Добавить «Цвет»: баланс белого (температура/оттенок + пипетка), сочность
(vibrance), насыщенность, цветовой микшер по оттенкам, цветокоррекция
(тени/средние тона/света + яркость зон, наложение, баланс), поканальная
коррекция.
- Показывать правки в просмотрщике сразу, не дожидаясь серверного рендера.
- Сохранить неразрушающий серверный рендер как источник истины и обратную
совместимость со старыми `edit_params`.
**Non-Goals:**
- Синхронизация правок между устройствами и Android-клиент.
- Изменение ролей хранения или формата объектов.
- Миграция схемы базы данных.
## Decisions
**Цвет хранится в том же `edit_params`, рядом с `light`.**
- Обоснование: `EditParams` расширяется полем `Color ColorParams`; JSON-блоб и
клиентская модель принимают новый ключ без схемных изменений.
- Альтернатива: отдельная колонка/таблица — отвергнута, потребовала бы миграцию.
**Порядок операций: свет, затем цвет.**
- Обоснование: цветовые коррекции логично применять к уже скорректированной по
тональности картинке; сервер и клиент следуют одному порядку.
- Альтернатива: цвет до света — отвергнуто, расходится с поведением Lightroom и
текущим конвейером.
**Живой предпросмотр считается на GPU (WebGL2), CPU/WASM — фолбэк.**
- Обоснование: попиксельный CPU-фильтр на полном viewport блокировал main thread
(замеры: десятки мс на кадр). Шейдер повторяет свет/цвет и считает кадр на
видеокарте; текстура источника загружается один раз на смену изображения.
- Фолбэк: если WebGL2 недоступен или шейдер не собрался, используется прежний
CPU-путь (WASM, затем JS) с адаптивным буфером. Это медленнее, но сохраняет
функциональность.
- Альтернатива: вынести CPU-фильтр в Web Worker/OffscreenCanvas — отвергнуто как
более сложное при уже готовом GPU-пути.
**Паритет реализаций ограничен явно.**
- Go (сервер) — источник истины для сохранённого фото; покрыт Go-тестами.
- TypeScript и Rust/WASM — эталонная пара для CPU-фолбэка; паритет проверяется
`wasmMatchesReference` на пробе и больших градиентах.
- GLSL/WebGL2 — быстрый предпросмотр; проверяется компиляцией/линковкой шейдера,
пиксельный паритет с сервером не гарантируется. Финальное качество даёт сервер.
**Тональные зоны и быстрый путь.**
- Веса зон: тени `(1-l)^4`, света `l^4`, средние тона — остаток; это не даёт
колесу теней заметно задевать средние тона и уменьшает резкую границу на
контрастных снимках.
- `blending` по умолчанию 50 (диапазон 0..100), `balance` — -100..100.
- Яркость зон применяется аддитивным сдвигом, без деления на пиксель.
- Если микшер и насыщенность/вибрация не задействованы, цвет считается быстрым
путём без RGB→HSL→RGB; иначе — полный HSL-путь.
**Пустота цветовых правок.**
- Наложение/баланс и оттенок колеса без силы и яркости не считаются правкой:
фото не получает цветовую версию, сброс остаётся доступным по другим полям.
**Пипетка баланса белого.**
- Клиент сэмплирует пиксель из исходного (неотредактированного) превью и решает
обратную задачу баланса белого: подбирает температуру/оттенок, при которых
точка становится нейтральной. Пресет переходит в «Пользовательский».
**Поканальная коррекция — в модели и рендере, но не в UI.**
- `ColorCorrection` (red/green/blue) принимается API и учитывается рендером, но в
панели не выведена: в макете «Цветокоррекция» — это колёса тональных зон.
**UI.**
- Раздел «Цвет»: баланс белого с пресетами и пипеткой, сочность/насыщенность,
микшер (8 оттенков × тон/насыщенность/яркость), цветокоррекция (3 колеса,
яркость зон, наложение, баланс).
- Слайдеры с градиентными дорожками, цветовые колёса, двойной клик по контролу
сбрасывает значение.
## Risks / Trade-offs
[WebGL2 недоступен] → фолбэк на CPU/WASM с адаптивным буфером; функциональность
сохраняется, скорость ниже.
[Расхождение шейдера и сервера] → серверный рендер остаётся источником истины;
шейдер проходит проверку компиляции, а CPU-пара JS/WASM — тесты паритета.
[Большая текстура оригинала] → загрузка один раз на смену источника; при
переключении зума/источника возможна разовая пауза.
[Резкая граница на контрастных снимках] → более узкие веса зон и аддитивная
яркость; полностью убрать границу нельзя, если она есть в самом снимке.
[Обратная совместимость] → отсутствие `color` трактуется как нулевые правки.
## Migration Plan
Миграция схемы не требуется: новый ключ `color` дополняет существующий `light`.
Откат — удаление ключа `color` из `edit_params`.
## Open Questions
Нет.
@@ -0,0 +1,61 @@
# Proposal
## Why
В инструменте правок фото сейчас только раздел «Свет» (экспозиция, контраст, света,
тени, белые, чёрные, точечная кривая). Пользователи не могут скорректировать цвет:
баланс белого, вибрацию, насыщенность, отдельные оттенки и тонирование. Добавить
цветовые правки — востребованное расширение неразрушающего редактирования, которое
уже работает в Galo.
## What Changes
- Расширить `EditParams` новым блоком `Color`: баланс белого (температура/оттенок
+ пипетка по нейтральной точке), сочность (vibrance), насыщенность, цветовой
микшер (8 оттенков × тон/насыщенность/яркость), цветокоррекция (тени/средние
тона/света + яркость зон, наложение, баланс) и поканальная коррекция.
- Сервер (Go): рендер цветовых правок на пикселях исходного объекта, порядок
операций — свет, затем цвет; результат записывается в те же роли `edit`,
`edit_thumb`, `edit_medium`, `edit_preview`.
- Клиент (TypeScript/Svelte): раздел «Цвет» с ползунками, цветовыми колёсами и
микшером; живой предпросмотр на WebGL2, CPU/WASM-фолбэк с тестом паритета
(`wasmMatchesReference`); пипетка баланса белого; двойной клик по контролу
сбрасывает значение.
- WASM (Rust): расширение `frontend/wasm/light/` цветовыми операциями и
пересборка `static/light.wasm` (фолбэк предпросмотра).
- Хранение: `photo.edit_params` остаётся `map[string]any` JSON-блобом — старые
фото без ключа `color` рендерятся без цветовых правок, миграций схемы не
требуется.
## Capabilities
### Modified Capabilities
- `photos`: требование «Неразрушающее редактирование фотографии» расширяется
цветовыми параметрами правок. Потребуется дельта-спека
`specs/photos/spec.md` в рамках этого изменения.
### New Capabilities
Нет — цветовое редактирование входит в существующую способность `photos`.
## Impact
- `backend/internal/photos/edit.go` — `ColorParams`, `EditParams.Color`,
`Normalized`/`IsEmpty`/`JSON`.
- `backend/internal/photos/edit_render.go` — `applyColor` / `applyColorRows`,
`decodeAndAdjust` применяет свет и цвет.
- `backend/internal/photos/handlers.go` — приём `color` в `PATCH /photos/:id/edit`.
- `frontend/src/lib/edit.ts` — `ColorParams`, цветовые ползунки,
`readEditParams`/`isEmptyEditParams`/`normalizeEditParams`, `applyColorToPixels`,
`whiteBalanceFromRGB`.
- `frontend/src/lib/light-wasm.ts` — вызов WASM для цвета, поддержка паритета.
- `frontend/src/lib/webgl-preview.ts` — WebGL2-шейдер и рендер превью.
- `frontend/src/lib/stores/eyedropper.svelte.ts` — режим пипетки.
- `frontend/src/lib/components/PhotoEditPanel.svelte` — раздел «Цвет».
- `frontend/src/lib/components/EditSlider.svelte`, `ColorWheel.svelte` — контролы.
- `frontend/src/lib/components/Viewer.svelte` — live-превью (WebGL/CPU) и сэмплирование пипетки.
- `frontend/src/lib/components/PhotoPanel.svelte` — передача признака просмотрщика.
- `frontend/wasm/light/` (Rust) + `static/light.wasm` — цветовые операции.
- Тесты: `edit_test.go`, `edit.test.ts`, `light-wasm.test.ts`,
`backend/internal/e2e/color_edit_test.go`.
@@ -0,0 +1,70 @@
# Spec Delta
## MODIFIED Requirements
### Requirement: Неразрушающее редактирование фотографии
Система SHALL поддерживать неразрушающее редактирование фотографий. Параметры правок (свет и цвет) SHALL храниться в метаданных фото, а отредактированная версия SHALL создаваться как отдельные объекты (роли `edit`, `edit_thumb`, `edit_medium`, `edit_preview`) рядом с исходными вариантами. Рендер SHALL выполняться по исходному объекту фото, а не по его уменьшенным вариантам. Исходный объект SHALL оставаться неизменным, а скачивание SHALL отдавать оригинал. Сброс правок SHALL удалять и параметры, и отредактированную версию. Правки SHALL применяться только к изображениям.
#### Scenario: Сохранение правок
- **WHEN** пользователь сохраняет правки фото (свет и/или цвет)
- **THEN** параметры сохраняются в метаданных, отредактированная версия рендерится в фоне, а после рендера фото получает URL отредактированных вариантов
#### Scenario: Фоновая подготовка версий
- **WHEN** правки фото сохранены
- **THEN** система готовит варианты сетки и полноразмерную версию в фоне и сообщает о готовности
#### Scenario: Рендер по оригиналу
- **WHEN** готовится отредактированная версия фото
- **THEN** световые и цветовые правки применяются к пикселям исходного объекта, а не к его уменьшенной копии
#### Scenario: Неразрушачность
- **WHEN** фото отредактировано
- **THEN** исходный объект и его варианты остаются неизменными
#### Scenario: Сброс правок
- **WHEN** пользователь сбрасывает правки
- **THEN** параметры и отредактированная версия удаляются, а фото снова показывается в исходном виде
#### Scenario: Права на правки
- **WHEN** правки сохраняет пользователь без прав на это фото
- **THEN** система отклоняет запрос
#### Scenario: Редактирование видео
- **WHEN** пользователь пытается отредактировать видео
- **THEN** система отклоняет запрос
#### Scenario: Цветовые правки сохраняются и рендерятся
- **WHEN** пользователь сохраняет цветовые правки фото: баланс белого (температура/оттенок), сочность (vibrance), насыщенность, цветовой микшер по оттенкам, цветокоррекцию (тени/средние тона/света, яркость зон, наложение, баланс) или поканальную коррекцию
- **THEN** параметры цвета сохраняются в метаданных, отредактированная версия рендерится в фоне, а после рендера фото получает URL отредактированных вариантов
#### Scenario: Цветовые правки применяются к пикселям исходного объекта
- **WHEN** готовится отредактированная версия фото с цветовыми правками
- **THEN** цветовые правки применяются к пикселям исходного объекта после световых правок, а не к его уменьшенной копии
#### Scenario: Пустые цветовые правки не сохраняются
- **WHEN** в цветовых параметрах заданы только наложение/баланс или оттенок колеса без силы и яркости
- **THEN** правки считаются пустыми и фото не получает цветовую версию
## ADDED Requirements
### Requirement: Пипетка баланса белого
Клиент SHALL позволять выбрать нейтральную точку на фото и SHALL устанавливать температуру и оттенок так, чтобы цвет этой точки стал нейтральным. Выборка SHALL браться из исходного (неотредактированного) превью, а пресет баланса белого SHALL переходить в «Пользовательский».
#### Scenario: Выбор нейтральной точки
- **WHEN** пользователь включает пипетку и кликает по нейтральному участку фото
- **THEN** температура и оттенок обновляются, и цвет выбранной точки становится нейтральным
#### Scenario: Пипетка доступна только в просмотрщике
- **WHEN** фото не открыто в просмотрщике
- **THEN** пипетка недоступна
### Requirement: Живой предпросмотр цветовых правок
Клиент SHALL показывать результат цветовых правок в просмотрщике до завершения серверного рендера. После завершения рендера SHALL показываться серверная версия.
#### Scenario: Правки видны сразу
- **WHEN** пользователь двигает цветовой контрол
- **THEN** просмотрщик обновляет изображение без ожидания серверного рендера
#### Scenario: Серверная версия заменяет предпросмотр
- **WHEN** серверный рендер цветовых правок завершён
- **THEN** просмотрщик показывает отрендеренную версию
@@ -0,0 +1,59 @@
# Tasks
## 1. Backend: цветовая модель и рендер (Go)
- [x] 1.1 Добавить `ColorParams` и `EditParams.Color` в `backend/internal/photos/edit.go`, обновить `Normalized`/`IsEmpty`/`JSON` с учетом цвета — проверить `go build ./internal/photos/`
- [x] 1.2 Реализовать `applyColor` / `applyColorRows` и включить цвет в `decodeAndAdjust` после света (`backend/internal/photos/edit_render.go`) — проверить `go test ./internal/photos/ -run TestColor -v`
- [x] 1.3 Добавить тесты цветовых параметров (`edit_test.go`): валидация диапазонов, `IsEmpty`, рендер с цветом — проверить `go test ./internal/photos/ -v`
## 2. Фронтенд: цветовая модель (TypeScript)
- [x] 2.1 Добавить `ColorParams`, цветовые ползунки, `emptyColor`, обновить `readEditParams`/`isEmptyEditParams`/`normalizeEditParams` в `frontend/src/lib/edit.ts` — проверить `npm run check` (в `frontend`)
- [x] 2.2 Реализовать `applyColorToPixels` в `edit.ts`, зеркальное серверной математике — проверить `npm run test` (в `frontend`, `edit.test.ts`)
- [x] 2.3 Поддержать цвет в `light-wasm.ts` и тест паритета `wasmMatchesReference` — проверить `npm run test` (в `frontend`, `light-wasm.test.ts`)
## 3. WASM модуль цвета (Rust)
- [x] 3.1 Реализовать цветовые операции (баланс белого, вибрация, насыщенность, микшер, точечный цвет) в `frontend/wasm/light/` — проверить сборку модуля
- [x] 3.2 Пересобрать `static/light.wasm` — проверить файл обновился
## 4. UI: панель и превью цвета
- [x] 4.1 Добавить раздел «Цвет» в `PhotoEditPanel.svelte` (баланс белого, сочность, насыщенность, микшер, цветокоррекция) — проверить открытие/сворачивание панели
- [x] 4.2 Поддержать цвет в live-превью `Viewer.svelte` — проверить изменение превью при движении ползунков
- [x] 4.3 Подключить сохранение цветовых параметров через `photosApi.edit` — проверить сохранение на сервере
## 5. Интеграция и проверка
- [x] 5.1 Проверить эндпоинт правки (`PATCH /api/photos/:id/edit`) с цветовыми параметрами — проверить ответ с `edit_url`
- [x] 5.2 Проверить сброс цветовых правок — проверить возврат к оригиналу
- [x] 5.3 Проверить обратную совместимость: фото без ключа `color` в `edit_params` рендерятся без цветовых правок — проверить `make test` (бэкенд)
## 6. WebGL-предпросмотр
- [x] 6.1 Реализовать `frontend/src/lib/webgl-preview.ts`: WebGL2-шейдер света/цвета, LUT-текстура кривых, загрузка текстуры изображения — проверить сборку `npm run build`
- [x] 6.2 Подключить GL-first и CPU/WASM-фолбэк в `Viewer.svelte` (два канваса, `useGL`) — проверить переключение при отсутствии WebGL2
- [x] 6.3 Проверить компиляцию и линковку шейдера в headless Firefox — зелёный экран `OK`
- [x] 6.4 Пропускать свет, если он не менялся, и микшер, если он пуст — проверить `go test ./internal/photos/ ./internal/e2e/`
- [x] 6.5 Снизить стоимость CPU-фолбэка: адаптивный буфер, беззвучный быстрый путь без HSL и аддитивная яркость — проверить замер WASM/визуально
## 7. Пипетка баланса белого
- [x] 7.1 Добавить `frontend/src/lib/stores/eyedropper.svelte.ts` (режим, фото, сэмпл) — проверить `npm run check`
- [x] 7.2 Добавить `whiteBalanceFromRGB` в `edit.ts` (обратная задача баланса белого) — проверить `npm run test` (`edit.test.ts`)
- [x] 7.3 Сэмплировать пиксель базового превью в `Viewer.svelte` по клику — проверить ручным сценарием
- [x] 7.4 Подключить кнопку пипетки и подсказку в `PhotoEditPanel.svelte`, пресет «Пользовательский» — проверить `npm run check`
- [x] 7.5 Покрыть расчёт нейтральной точки тестом — проверить `npm run test`
## 8. UI и тональные правки
- [x] 8.1 Добавить `EditSlider.svelte` (градиентная/заполненная дорожка, двойной клик — сброс) — проверить `npm run check`
- [x] 8.2 Добавить `ColorWheel.svelte` (оттенок/насыщенность, двойной клик — сброс) — проверить открытие/вращение
- [x] 8.3 Переименовать «Красивость» → «Сочность» — проверить подпись ползунка
- [x] 8.4 Сузить веса зон теней/светов и сделать яркость аддитивной — проверить отсутствие резкой границы на контрастном снимке
- [x] 8.5 Добавить пресеты баланса белого и «Пользовательский» — проверить переключение пресетов
## Workflow follow-up
- Архивировать изменение после удовлетворения требований ревью проекта.
- Проверить архивированный результат.
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-10-23
@@ -0,0 +1,148 @@
# Design
## Context
Сейчас кривая хранится в `light.curve` как точки на канал, `normalizeCurve`
сортирует/зажимает/дедуплицирует их, а по умолчанию массив пуст. UI рисует
статичные углы и прямые сегменты; `buildCurveLUT` (TS) и `curveLUT` (Go)
интерполируют линейно. Пресетов нет. Настройки профиля лежат в
`users.preferences` (JSON-блоб); `PATCH /auth/me/preferences` сейчас **заменяет**
весь объект и знает только `photo_info`, поэтому добавление пресетов без мержа
затирало бы другие разделы.
См. `proposal.md` — Why и `specs/photos/spec.md`, `specs/auth/spec.md` — требования.
## Goals / Non-Goals
**Goals:**
- Крайние узлы как обычные точки; первый клик вставляет между ними; узлы двигаются
по x/y; вне них кривая плоская.
- Плавная монотонная интерполяция в SVG-пути и в LUT; Go и TS считают одинаково.
- Встроенные пресеты контраста и пользовательские пресеты (кривые всех четырёх
каналов) в профиле; сохранение/применение/переименование/удаление;
импорт/экспорт JSON.
- Серверный мерж разделов настроек с валидацией.
**Non-Goals:**
- Пресеты как «look» из четырёх кривых; Android-клиент; шаринг пресетов между
пользователями (только файл); undo/redo.
## Decisions
**Крайние точки — обычные узлы.**
- Первая и последняя точки массива являются крайними; по умолчанию это `(0,0)` и
`(1,1)`. Пустой канал в UI показывает эти две точки; первое взаимодействие
записывает их в `light.curve`.
- Вне крайних точек значение постоянно (текущее поведение `curveEval`), поэтому
сдвинутый по x узел даёт плоскую «полку», как на скрине.
- При перетаскивании точки остаются отсортированными по x; UI не даёт точке
пересечь соседнюю (x ограничивается между соседями), на коммите — `normalizeCurve`.
- Альтернатива: фиксировать x крайних на 0/1 — отвергнуто, пользователь хочет
двигать и по x.
**Интерполяция — монотонный кубический Эрмит (PCHIP).**
- Наклоны отрезков `d_i`, касательные по Fritsch–Carlson (нулевые при смене
знака/нулевом наклоне, ограничение против выбросов). Участок между точками
считается по кубической формуле Эрмита.
- SVG-путь: те же касательные переводятся в кубические Безье
(`P1 = P0 + (h/3, m_i*h/3)`, `P2 = P3 - (h/3, m_{i+1}*h/3)`), плюс плоские
сегменты от x=0 до первой и от последней до x=1.
- LUT 256: те же значения; `buildCurveLUT` (TS) и `curveLUT` (Go) обязаны
совпадать. WASM и WebGL получают готовый LUT из TS — их менять не нужно.
- Альтернативы: Catmull-Rom (выбросы/гало на тоновой кривой), линейная
интерполяция (текущая, отвергнута).
**Пресет — кривые всех четырёх каналов.**
- `CurvePreset { name: string; channels: { rgb: CurvePoint[]; red: CurvePoint[];
green: CurvePoint[]; blue: CurvePoint[] } }`.
- Каждый канал содержит 2..16 точек; пустых каналов в пресете нет — линейный
канал хранится как `(0,0),(1,1)`.
- Встроенные `Линейный`, `Средний контраст`, `Сильный контраст` — клиентские
константы. Контраст задаётся кривой RGB, каналы R/G/B линейные. Предлагаемые
точки RGB:
- Средний: `(0,0),(0.25,0.2),(0.5,0.5),(0.75,0.8),(1,1)`
- Сильный: `(0,0),(0.2,0.12),(0.5,0.5),(0.8,0.88),(1,1)`
- Сохранение берёт `effectiveCurvePoints` каждого канала, поэтому в пресет
всегда попадают все четыре кривые.
- Применение заменяет кривые всех четырёх каналов; текущий выбранный канал не
меняется.
- Подпись: имя пресета, если кривые всех четырёх каналов совпадают с пресетом
(с допуском), иначе `Пользовательский`.
**Хранение и мерж настроек.**
- `preferencesPayload` расширяется `curve_presets`; поля-указатели позволяют
отличить «не передано» от «пусто».
- Handler читает текущие `users.preferences`, мержит переданные разделы
(`photo_info`, `curve_presets`), валидирует, пишет и возвращает полный объект.
Сохранение «Сведений» с `{photo_info}` сохраняет пресеты; сохранение пресетов
сохраняет `photo_info`.
- Валидация: не больше 100 пресетов, имя 1..64, все четыре канала присутствуют
и содержат 2..16 точек, `x,y` конечные в 0..1. Некорректный раздел
отклоняется целиком.
- Альтернативы: отдельный endpoint (больше поверхности), клиент шлёт весь объект
(устаревшие вкладки затирают чужие изменения).
**Переключение фото.**
- Вкладка правой панели хранится в `AlbumPanel` и передаётся в `PhotoPanel`
через `bind:tab`, поэтому переживает перемонтирование панели при загрузке
следующего фото.
- Cleanup эффекта `PhotoEditPanel` регистрируется на каждом запуске; при смене
`photo.id` накопленные правки отправляются до инициализации нового фото.
- Ответы сохранений проверяются по id фото и номеру операции: устаревшее
сохранение не подменяет текущее фото и его параметры. Панель рендерит только
фото, совпадающее с текущим маршрутом.
**Пользовательские действия и файлы.**
- Сохранить: диалог имени, кривые всех четырёх каналов; при совпадении имени —
подтверждение перезаписи.
- Переименовать/удалить: действия в меню пользовательского пресета.
- Экспорт: JSON `{ version: 1, presets: CurvePreset[] }` с кривыми всех каналов,
только пользовательские пресеты (встроенные всегда доступны).
- Импорт: файл-пикер, валидация, upsert по имени, сохранение через preferences;
при некорректном файле профиль не меняется.
**Совместимость формата.**
- Старый формат `{ name, channel, points }` читается из профиля и импорта:
точки попадают в указанный канал, остальные становятся линейными.
- При следующем сохранении список перезаписывается новым форматом со всеми
четырьмя каналами.
**UI.**
- Статичный текст «Линейный» заменяется кнопкой, открывающей popover-меню:
встроенные, пользовательские, «Сохранить…», «Импортировать…», «Экспортировать…».
- В SVG крайние точки — такие же перетаскиваемые кружки, как остальные; первый
клик по свободному полю вставляет точку между крайними; двойной клик сбрасывает.
- Сохраняется существующая клавиатурная правка точек.
## Risks / Trade-offs
[Старые кривые начнут выглядеть иначе (плавно вместо линейно)] → это осознанное
изменение рендера; точки не мигрируются, плоские участки вне крайних сохраняются.
[Расхождение PCHIP в Go и TS] → одна формула, тесты с захардкоженными значениями
LUT в обоих языках; WASM/WebGL используют готовый LUT.
[Гонка при мерже preferences] → мерж на сервере по разделам: разные разделы не
затирают друг друга; одновременная запись одного раздела — last-write-wins,
приемлемо для настроек одного пользователя.
[Рост списка пресетов / большой импорт] → лимиты количества, размера имени и
точек; handler уже ограничивает тело 1 МБ.
[Старые пресеты хранятся в формате одного канала] → клиент конвертирует их при
чтении/импорте, а первое сохранение пресетов перезаписывает профиль новым
форматом.
[Пересечение точек при перетаскивании] → ограничение x соседями и нормализация
на коммите.
## Migration Plan
Схема не меняется: `curve_presets` — ключ в JSON-блобе `users.preferences`.
Старый формат пресетов конвертируется на клиенте при чтении. Откат: удалить
ключ; старые кривые остаются в `light.curve` без изменений данных.
## Open Questions
Нет. Точные точки «Среднего/Сильного контраста» — настраиваемый дефолт, не влияет
на контракт.
@@ -0,0 +1,73 @@
# Proposal
## Why
Тоновая кривая сейчас ведёт себя не как инструмент из Lightroom: крайние узлы не
существуют до первых кликов, линия строится по прямым сегментам, а готовых
пресетов контраста и пользовательских пресетов нет. Пользователь не может быстро
применить типовой контраст или сохранить свою кривую. Дополнительно
`PATCH /auth/me/preferences` заменяет весь объект настроек, поэтому хранение
пресетов в профиле без мержа затирало бы другие разделы.
## What Changes
- **Кривая.** Крайние узлы `(0,0)` и `(1,1)` существуют сразу и являются обычными
точками; первый клик добавляет точку между ними. Крайние узлы двигаются по x и
y, вне них кривая постоянна («полки», как на скрине). Линия и рендер используют
плавную монотонную кубическую интерполяцию (PCHIP): SVG-путь и LUT в Go/TS.
«Сбросить» возвращает линейную кривую.
- **Встроенные пресеты.** `Линейный`, `Средний контраст`, `Сильный контраст` —
каждый описывает все четыре канала: контраст задаётся кривой RGB, каналы
R/G/B остаются линейными. Подпись показывает активный пресет; при ручной
правке любого канала — `Пользовательский`.
- **Пользовательские пресеты.** Пресет описывает кривые всех каналов
(`name`, `channels: { rgb, red, green, blue }`). Сохранение текущих кривых
всех каналов, применение заменяет все четыре кривые, переименование и
удаление. Хранение в `users.preferences.curve_presets` (профиль пользователя),
приватно для пользователя.
- **Мерж настроек.** `PATCH /auth/me/preferences` принимает `photo_info` и
`curve_presets` по отдельности, мержит переданные разделы с сохранёнными,
валидирует и возвращает полный merged-объект. Сохранение «Сведений» больше не
затирает пресеты, и наоборот.
- **Импорт/экспорт.** JSON-файл `{ version: 1, presets: [...] }`: экспорт
пользовательских пресетов, импорт с добавлением в профиль (при совпадении имени
— перезапись).
- **Совместимость.** Миграций схемы нет: пресеты лежат в JSON-блобе
`preferences`. Старые пресеты формата `{ channel, points }` конвертируются в
четыре канала при чтении и перезаписываются при следующем сохранении.
Существующие сохранённые кривые начнут интерполироваться плавно, поэтому их
визуальный результат может немного измениться.
## Capabilities
### New Capabilities
Нет — поведение входит в существующие способности `photos` и `auth`.
### Modified Capabilities
- `photos`: добавляются требования «Тоновая кривая» (крайние узлы, плавная
интерполяция, встроенные пресеты, сброс) и «Пользовательские пресеты кривой»
(пресет из четырёх каналов, сохранение/применение/переименование/удаление,
импорт/экспорт).
- `auth`: требование «Хранение пользовательских настроек интерфейса»
расширяется мержем разделов и хранением пользовательских пресетов кривой;
добавляется сценарий «сохранение одного раздела не затирает другие».
## Impact
- `backend/internal/auth/handlers.go` — `preferencesPayload` с `curve_presets`,
мерж разделов, валидация имени и кривых всех четырёх каналов.
- `backend/internal/auth/store.go` / `sqlite_store.go` — без изменений схемы;
запись merged-JSON через существующий `UpdatePreferences`.
- `backend/internal/photos/edit.go` — `curveEval`/`curveLUT` переходят на PCHIP;
тесты Go на гладкость/LUT.
- `frontend/src/lib/edit.ts` — PCHIP в `buildCurveLUT`, типы и нормализация
пресетов, точки кривой.
- `frontend/src/lib/components/PhotoEditPanel.svelte` — узлы-углы, плавный SVG-путь,
меню пресетов, сохранение/переименование/удаление, импорт/экспорт.
- `frontend/src/lib/types.ts`, `stores/auth.svelte.ts`, `api.ts` — тип
`Preferences.curve_presets`, сохранение через существующий endpoint.
- Новые вспомогательные модули: меню/диалоги пресетов, импорт/экспорт JSON.
- Тесты: `edit_test.go`, `edit.test.ts`, тесты мержа/валидации preferences,
e2e сохранения пресетов в профиле.
@@ -0,0 +1,26 @@
# Spec Delta
## MODIFIED Requirements
### Requirement: Хранение пользовательских настроек интерфейса
Система SHALL хранить пользовательские настройки (отображение интерфейса и пресеты кривой) в профиле пользователя и SHALL возвращать их при получении текущего пользователя. Настройки SHALL быть приватными для пользователя. Отсутствие настроек SHALL трактоваться как значения по умолчанию. Сохранение одного раздела настроек SHALL не затирать остальные разделы.
#### Scenario: Получение настроек
- **WHEN** аутентифицированный пользователь запрашивает свой профиль
- **THEN** ответ содержит его настройки отображения и пресеты кривой (или пустой объект по умолчанию)
#### Scenario: Сохранение настроек
- **WHEN** пользователь сохраняет настройки
- **THEN** система сохраняет их в профиле и возвращает сохранённое состояние
#### Scenario: Сохранение раздела не затирает другие
- **WHEN** пользователь сохраняет только один раздел настроек (например, сведения о фото или пресеты кривой)
- **THEN** остальные разделы профиля сохраняются без изменений
#### Scenario: Изоляция настроек
- **WHEN** другой пользователь запрашивает свой профиль
- **THEN** он не получает настройки первого пользователя
#### Scenario: Некорректные настройки
- **WHEN** пользователь присылает настройки недопустимой структуры или размера
- **THEN** система отклоняет запрос с ошибкой и не меняет сохранённые настройки
@@ -0,0 +1,84 @@
# Spec Delta
## ADDED Requirements
### Requirement: Тоновая кривая
Тоновая кривая SHALL задаваться контрольными точками для каналов RGB, R, G и B. Крайние точки SHALL существовать по умолчанию, SHALL двигаться по обеим осям и SHALL задавать плоские участки вне себя. Кривая SHALL быть плавной и монотонной между точками; первый клик по полю SHALL добавлять точку между крайними. Сброс SHALL возвращать линейную кривую.
#### Scenario: Крайние узлы существуют с самого начала
- **WHEN** пользователь открывает инструмент «Кривая»
- **THEN** у каждого канала уже есть крайние точки, и их можно перетаскивать
#### Scenario: Добавление точки
- **WHEN** пользователь кликает по свободному полю кривой
- **THEN** между крайними точками добавляется новая точка, а крайние остаются на месте
#### Scenario: Подвижные крайние узлы
- **WHEN** пользователь двигает крайнюю точку по x или y
- **THEN** вне крайних точек кривая остаётся плоской, а между точками — плавной
#### Scenario: Плавная интерполяция
- **WHEN** кривая сохранена и отрендерена
- **THEN** предпросмотр и итоговое фото используют одну и ту же плавную монотонную кривую
#### Scenario: Встроенные пресеты
- **WHEN** пользователь выбирает «Линейный», «Средний контраст» или «Сильный контраст»
- **THEN** кривые всех четырёх каналов заменяются кривыми пресета (контраст — в RGB, R/G/B — линейные), а подпись показывает выбранный пресет
#### Scenario: Пользовательская правка
- **WHEN** пользователь вручную меняет точки кривой
- **THEN** подпись показывает «Пользовательский»
#### Scenario: Сброс
- **WHEN** пользователь сбрасывает кривую
- **THEN** текущий канал возвращается к линейной кривой с крайними точками
#### Scenario: Независимые каналы
- **WHEN** пользователь выбирает канал R, G или B
- **THEN** он меняет только выбранный канал, остальные каналы остаются прежними
### Requirement: Переключение фото в редакторе
При переключении фото правая панель SHALL сохранять выбранную вкладку. Несохранённые правки SHALL сохраняться тому фото, для которого они сделаны, в том числе если пользователь уже переключился на другое фото. Ответы фоновых запросов SHALL NOT подменять текущее фото или его параметры.
#### Scenario: Вкладка не меняется
- **WHEN** пользователь переключает фото
- **THEN** выбранная вкладка правой панели остаётся прежней
#### Scenario: Правки уходят текущему фото
- **WHEN** пользователь меняет настройки после переключения
- **THEN** изменения сохраняются текущему фото, а не предыдущему
#### Scenario: Фоновое сохранение не подменяет фото
- **WHEN** сохранение предыдущего фото завершается после переключения
- **THEN** панель продолжает показывать текущее фото, а его параметры не меняются
### Requirement: Пользовательские пресеты кривой
Пользователь SHALL сохранять текущие кривые всех каналов (RGB, R, G и B) как именованный пресет, применять, переименовывать и удалять его. Пресет SHALL содержать кривую для каждого из четырёх каналов. Пресеты SHALL храниться в профиле пользователя и SHALL быть приватными. Импорт и экспорт SHALL выполняться JSON-файлом; импорт SHALL добавлять пресеты в профиль.
#### Scenario: Сохранение пресета
- **WHEN** пользователь сохраняет текущие кривые под именем
- **THEN** пресет появляется в списке и сохраняется в профиле вместе с кривыми RGB, R, G и B
#### Scenario: Применение пресета
- **WHEN** пользователь выбирает пользовательский пресет
- **THEN** кривые всех четырёх каналов заменяются сохранёнными, а текущий канал не меняется
#### Scenario: Переименование и удаление
- **WHEN** пользователь переименовывает или удаляет пресет
- **THEN** список пресетов и профиль обновляются
#### Scenario: Приватность пресетов
- **WHEN** другой пользователь открывает свои пресеты
- **THEN** он не видит пресеты первого пользователя
#### Scenario: Экспорт пресетов
- **WHEN** пользователь экспортирует пресеты
- **THEN** он получает JSON-файл с пользовательскими пресетами и кривыми всех четырёх каналов
#### Scenario: Импорт пресетов
- **WHEN** пользователь импортирует корректный JSON-файл
- **THEN** пресеты добавляются или обновляются в его профиле
#### Scenario: Некорректный файл или пресет
- **WHEN** имя или кривая хотя бы одного канала недопустимы
- **THEN** система отклоняет пресет и не меняет профиль
@@ -0,0 +1,49 @@
# Tasks
## 1. Общая математика кривой (TS + Go)
- [x] 1.1 Заменить линейную интерполяцию в `frontend/src/lib/edit.ts` на монотонный кубический Эрмит (PCHIP): наклоны, касательные, оценка между точками, плоские участки вне крайних — проверить `npm run test` (`edit.test.ts`, значения LUT и монотонность)
- [x] 1.2 Повторить ту же формулу в `backend/internal/photos/edit.go` (`curveEval`/`curveLUT`) — проверить `go test ./internal/photos/ -run TestCurve -v`
- [x] 1.3 Сверить Go и TS на нескольких кривых (линейная, средний/сильный контраст, кривая с крайними внутри) захардкоженными значениями LUT — проверить оба набора тестов
## 2. Backend: мерж настроек и пресеты
- [x] 2.1 Расширить `preferencesPayload` в `backend/internal/auth/handlers.go` полем `curve_presets` и валидацией (лимит количества, имя 1..64, 2..16 точек на канал, x/y в 0..1) — проверить `go test ./internal/auth/ -v`
- [x] 2.2 Сделать серверный мерж разделов: читать текущие `preferences`, мержить `photo_info`/`curve_presets`, писать и возвращать merged-объект — проверить тестом «сохранение photo_info не затирает пресеты и наоборот»
- [x] 2.3 Добавить e2e-проверку сохранения пресетов в профиле и их приватности — проверить `go test ./internal/e2e/ -run TestCurvePresets -v`
## 3. UI: узлы и плавная кривая
- [x] 3.1 Показывать крайние точки `(0,0)` и `(1,1)` по умолчанию; первый клик вставляет точку между ними; крайние двигаются по x/y, вне них — плоские участки — проверить вручную и `npm run check`
- [x] 3.2 Рисовать SVG-путь кубическими Безье по тем же касательным (плоские сегменты до/после крайних) — проверить визуально, что линия плавная
- [x] 3.3 Сохранить клавиатурную правку точек, двойной клик-сброс и ограничение x между соседями — проверить `npm run check` и ручным сценарием
## 4. UI: пресеты и файлы
- [x] 4.1 Заменить статичный «Линейный» на меню встроенных пресетов (`Линейный`, `Средний контраст`, `Сильный контраст`) с активной подписью/«Пользовательский» — проверить `npm run check`
- [x] 4.2 Добавить тип `Preferences.curve_presets` и сохранение/применение/переименование/удаление пользовательских пресетов через существующий endpoint — проверить `npm run test` и сохранение в профиле
- [x] 4.3 Реализовать импорт/экспорт JSON `{ version: 1, presets: [...] }` с валидацией и upsert по имени — проверить ручным импортом/экспортом и `npm run check`
## 5. Интеграция и проверка
- [x] 5.1 Прогнать `npm run check`, `npm run test`, `go test ./...`, `make build` — всё зелёное
- [x] 5.2 Проверить, что WebGL и WASM используют новый LUT, а старые сохранённые кривые рендерятся плавно без миграции данных — визуально и тестами
- [x] 5.3 Проверить приватность и лимиты пресетов (чужой профиль, слишком длинное имя, >16 точек) — тестами `internal/auth`/`internal/e2e`
## 6. Правка: пресет описывает все каналы
- [x] 6.1 Обновить `CurvePreset` в `frontend/src/lib/types.ts` и `curve-presets.ts`: `channels` для RGB/R/G/B, встроенные пресеты и поиск активного пресета по всем каналам — проверить `npm run test`
- [x] 6.2 Обновить серверную модель и валидацию `curve_presets` в `backend/internal/auth/handlers.go`: объект `channels` со всеми четырьмя каналами — проверить `go test ./internal/auth/ -v`
- [x] 6.3 Обновить сохранение и применение в `PhotoEditPanel.svelte` и `CurvePresetMenu.svelte`: сохранять и заменять все четыре канала, не переключать текущий канал — проверить `npm run check`
- [x] 6.4 Обновить импорт/экспорт и совместимость со старым форматом `{name, channel, points}`, тесты и e2e — проверить `npm run test` и `go test ./internal/e2e/ -run TestCurvePresets -v`
## 7. Переключение фото
- [x] 7.1 Сохранять вкладку правой панели при смене фото, вынеся её состояние в `AlbumPanel` — проверить в браузере
- [x] 7.2 Исправить регистрацию cleanup в `PhotoEditPanel`, чтобы накопленные правки отправлялись при переключении — проверить в браузере
- [x] 7.3 Защитить панель от устаревших ответов сохранения/загрузки и кратковременного `photo = null` — проверить `npm run check`
## Workflow follow-up
- Архивировать изменение после удовлетворения требований ревью проекта.
- Проверить архивированный результат.
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-10-24
@@ -0,0 +1,256 @@
# Design
## Context
См. `proposal.md` — «Why». Текущее состояние, важное для подхода:
- `EditParams` хранится JSON-блобом в `photo.edit_params` (Postgres `jsonb`,
SQLite `TEXT`); роли `edit`, `edit_thumb`, `edit_medium`, `edit_preview`
рендерит фоновый воркер по исходному объекту. Источник истины — Go-рендер.
- Конвейер правок попиксельный: `applyLight`, затем `applyColor`; цвет уже
использует HSL-переход и быстрый путь без него.
- Живой предпросмотр: `WebGLPreview` рисует видимую область одним проходом
фрагментного шейдера; при недоступности WebGL2 — CPU-фолбэк (WASM, затем JS),
который применяет свет и цвет к пикселям кадра.
- `edit_params` — открытый JSON: новые ключи не требуют миграции; фото без
ключа `effects` рендерятся как раньше. Копии фото правки не наследуют.
Ключевое ограничение: текстура, чёткость и дымка — пространственные операции,
им нужны размытие и локальная статистика. Текущие три реализации (Go, GLSL,
WASM) этого не умеют; виньетка и зерно остаются попиксельными.
## Goals / Non-Goals
**Goals:**
- Полный блок «Эффекты» из макета: текстура, чёткость, дымка, виньетка
(режимы «Свет», «Цвет», «Закарасить»), зерно.
- Живой предпросмотр всех эффектов на WebGL2 и его деградация без WebGL.
- Детерминированный серверный рендер и обратная совместимость `edit_params`.
- Разумная стоимость рендера полноразмерного фото в фоновом воркере.
**Non-Goals:**
- Попиксельное совпадение с Lightroom и точное повторение его формул.
- Локальные маски, кисти, градиенты, синхронизация правок между устройствами.
- Пресеты эффектов, экспорт XMP, редактирование на Android.
- Изменение API-контракта правок: по-прежнему `PATCH /photos/:id/edit` с JSON.
## Decisions
**1. `EffectsParams` — новый блок в `EditParams`, без миграции БД.**
```json
{
"light": { "...": "..." },
"color": { "...": "..." },
"effects": {
"texture": 0,
"clarity": 0,
"dehaze": 0,
"vignette": {
"mode": "light",
"amount": 0,
"midpoint": 50,
"feather": 50,
"roundness": 0,
"highlights": 0,
"color": "#000000"
},
"grain": { "amount": 0, "size": 25, "roughness": 50 }
}
}
```
- `mode`: `light` | `color` | `colorize`; неизвестный режим нормализуется в
`light`. `color` — hex-строка `#rrggbb`, нормализуется к нижнему регистру.
- Нормализация заполняет структурные дефолты (midpoint 50, feather 50, size 25,
roughness 50, mode light, color `#000000`) только для полей, отсутствующих в
JSON: явный `0` — валидное значение геометрии и сохраняется. Для этого модель
запоминает факт присутствия поля при разборе (`midpointSet`, `featherSet`,
`sizeSet`, `roughnessSet`). `IsEmpty` игнорирует дефолты при нулевой силе:
пустыми считаются только ненулевые `texture`, `clarity`, `dehaze`,
`vignette.amount`, `grain.amount`. Так `{}` и «дефолты без силы» одинаково
означают отсутствие правок.
- Альтернатива: отдельная таблица/колонка — отвергнута, потребовала бы миграции
и не даёт выгоды для JSON-параметров.
**2. Порядок рендера: свет → цвет → дымка → текстура → чёткость → виньетка → зерно.**
- Дымка — глобальная тональная коррекция, её логично применять до локального
контраста; текстура работает с высокими частотами, чёткость — со средними,
поэтому текстура идёт раньше. Виньетка и зерно — финальные операции над уже
сведённым кадром (аналог post-crop в Lightroom).
- Альтернатива: применять эффекты до цвета — отвергнута: цветокоррекция должна
работать с уже очищенным от дымки кадром, иначе дымка «перекрашивает» цвета.
- Порядок одинаков во всех реализациях; расхождение с сервером допустимо только
в деталях предпросмотра.
**3. Пространственные эффекты считаются в яркости, цвет не смещается.**
- Для каждого пикселя берётся яркость `Y = 0.299r + 0.587g + 0.114b`;
локальный контраст считается по `Y`, а разница применяется аддитивно ко всем
трём каналам. Это сохраняет оттенок и насыщенность и совпадает с принятым в
проекте подходом «яркость аддитивно».
- Текстура: unsharp mask с малым радиусом, `Y' = Y + k * (Y - blur_small(Y))`.
- Чёткость: unsharp mask с большим радиусом и подавлением ореолов — дельта
ограничивается и взвешивается по средним тонам, чтобы не звонить на границах
контрастных объектов.
- Отрицательные значения интерполируют к размытой версии (сглаживание), а не
просто инвертируют знак дельты.
**4. Размытие — быстрый box-blur (три прохода ≈ гаусс), радиус — доля размера кадра.**
- Радиус задаётся относительно `min(width, height)` (текстура ≈ 0.15 %, чёткость
≈ 0.8 %), с минимумом 1 px. Это ключевое решение для совпадения превью и
полноразмерного рендера: сервер считает по оригиналу (например, 4000 px), а
превью — по preview 1200 px; относительный радиус даёт одинаковую частоту.
- Box-blur через скользящее окно по строкам/столбцам — O(n) независимо от
радиуса, поэтому большой радиус чёткости не бьёт по времени. Размытие идёт по
строкам параллельно, как текущие проходы.
- Альтернатива: `imaging.Blur` — проще, но стоимость растёт с радиусом; для
полноразмерных фото и больших радиусов отвергнуто.
**5. Дымка — dark channel prior на уменьшенной копии.**
- Оценка атмосферного света `A`: по уменьшенной копии (≈512 px) берутся самые
яркие пиксели тёмного канала (верхний 0.1 %).
- Карта пропускания `t = 1 - ω * min_c(I_c / A_c)` сглаживается box-blur и
ограничивается снизу (например, 0.1), затем интерполируется на полный кадр.
- `J_c = (I_c - A_c) / max(t, t0) + A_c`; сила эффекта интерполирует между `I` и
`J`. Отрицательные значения — обратная операция: подмешивание `A` и снижение
контраста.
- Альтернатива: простое «поднять контраст и насыщенность» — дешевле, но не
убирает дымку на дальних планах; отвергнуто как не соответствующее смыслу
контрола.
**6. Виньетка — нормализованная геометрия и три режима.**
- Координаты нормализуются к половине кадра; расстояние до центра возводится в
степень, зависящую от округлости (эллипс ↔ суперэллипс/скруглённый
прямоугольник). Средняя точка задаёт начало зоны, растушёвка — ширину
перехода, знак силы выбирает затемнение или осветление.
- «Свет»: аддитивная поправка яркости с весом маски; «Света» защищает яркие
пиксели (уменьшает поправку при высокой `Y`), чтобы виньетка не «съедала»
блики.
- «Цвет»: подмешивание выбранного цвета с сохранением светлоты (смещение в
хроматические координаты). «Закарасить»: заливка выбранным цветом поверх
кадра с весом маски и силы. В обоих цветных режимах «Света» ограничивает
влияние на яркие участки.
- Альтернатива: отдельные реализации на каждый режим — отвергнута, общая маска
даёт одинаковую геометрию и меньше расхождений между сервером и превью.
**7. Зерно — детерминированный процедурный шум.**
- PRNG (например, splitmix64) инициализируется хешем `photo.id`, а не случайным
зерном: повторный рендер тех же параметров даёт тот же рисунок. Это требование
спеки; иначе `edit_thumb` и полноразмерный рендер расходились бы при каждом
прогоне.
- «Размер» задаёт шаг сетки шума (доля размера кадра, с минимумом 1 px),
«шероховатость» смешивает высокочастотный и сглаженный шум. Шум добавляется в
яркость, чтобы не вносить цветные пятна; сила 0 — шум не считается.
- Превью и полноразмерный рендер используют один PRNG, но разные сетки
дискретизации: рисунок визуально похож, побитового совпадения нет.
**8. WebGL2-предпросмотр переходит на много­проходную схему.**
- Проход 1: существующий шейдер света/цвета рисует кадр в FBO-текстуру вместо
экрана.
- Проход 2: яркость `Y`, разделимое box-размытие (горизонталь + вертикаль) в
две ping-pong текстуры; для чёткости — уменьшенное разрешение, для текстуры —
несколько тапов на полном.
- Дымка: `A` и карта `t` считаются на CPU по базовому превью при смене
изображения/параметров дымки и загружаются текстурой (например, 256 px);
шейдер интерполирует.
- Финальный проход: `A`-текстура, размытая яркость, карта дымки, виньетка и
зерно (хеш-шум в шейдере) → экран.
- Во время перетаскивания ползунка (`previewLow`) уменьшаются разрешение
размытия и число проходов; после паузы — полное качество, как сейчас.
- Альтернатива: один проход с приближением (несколько тапов) — проще, но
большой радиус чёткости требует десятков выборок и даёт хуже картинку;
отвергнуто.
**9. CPU-фолбэк: виньетка и зерно — да, пространственные эффекты — после сервера.**
- В JS-фолбэке применяются свет, цвет, виньетка и зерно (попиксельно); текстура,
чёткость и дымка не считаются, чтобы не блокировать main thread размытием
полного кадра, и появляются после серверного рендера. Это допустимо по спеке
(«предпросмотр без WebGL… после серверного рендера»).
- WASM-модуль не трогаем: он остаётся попиксельным и покрывает свет/цвет.
Альтернатива — расширять `no_std`-модуль буферами под blur — отвергнута как
отдельный крупный проект без выигрыша для основного GPU-пути.
**10. Гистограмма остаётся по свету и цвету.**
- Она считается по сэмплу 256 px (`sampleImage` + `applyLight`/`applyColor`);
на таком размере пространственные эффекты бессмысленны, а виньетка/зерно
искажали бы оценку тональности. Оставляем текущий расчёт и явно фиксируем это
решение в коде/дизайне.
**11. UI: секция «Эффекты» после «Цвет».**
- Заголовок сворачиваемый, как «Свет»/«Цвет». Слайдеры — существующий
`EditSlider` (двойной клик сбрасывает значение).
- Виньетка: три кнопки-вкладки («Свет», «Цвет», «Закарасить»), под ними сила
(«Виньетка»), средняя точка, растушёвка, округлость, света; для цветных
режимов — свотч цвета (`<input type="color">`), значение хранится hex-строкой.
- «Зерно»: сила, размер, шероховатость.
- Глобальная кнопка «Сброс» в секции «Свет» продолжает сбрасывать все правки
целиком (включая эффекты) — новых точек сброса не добавляем, чтобы не
дублировать поведение.
- Сохранение — через существующий debounce и `photosApi.edit`; сервер сам решает,
что параметры пустые. Индикатор «рендерится» уже привязан к наличию правок и
отсутствию `edit_preview_url`, поэтому заработает без изменений.
**12. Свёрнутость секций редактора — в localStorage, по умолчанию всё свёрнуто.**
- Все сворачиваемые блоки панели («Свет», «Кривая», «Цвет», «Цветовой микшер»,
«Точный цвет», «Цветокоррекция», «Эффекты») по умолчанию свёрнуты: панель
открывается компактно и не перегружает экран.
- Выбор пользователя хранится в браузере, в localStorage-ключе
`galo.edit.sections` (JSON `{section: collapsed}`), и восстанавливается при
перезагрузке и смене фото. Неизвестные ключи и небулевы значения
игнорируются, ошибки хранилища не ломают панель.
- Альтернатива: хранить в `preferences` профиля — отвергнута: это настройка
конкретного браузера, а не аккаунта; сервер и Android не затрагиваются.
**13. Вкладка «Редактирование» доступна только в просмотрщике.**
- В режиме сетки правая панель показывает только «Сведения»: редактирование
открывается при просмотре фото в просмотрщике, где доступны живой предпросмотр
и пипетка.
- Реализация: у `PhotoPanel` уже есть признак `viewer`; активная вкладка —
`activeTab = viewer ? tab : 'info'`, кнопка «Редактирование» рендерится только
при `viewer`. Сохранённая вкладка не теряется: вернувшись в просмотрщик,
пользователь увидит тот же раздел.
- Альтернатива: показывать вкладку неактивной — отвергнута: лишний элемент в
режиме просмотра сетки и риск случайных правок.
## Risks / Trade-offs
- **[Расхождение превью и серверного рендера]** → относительные радиусы и
геометрия; CPU/GL предпросмотр явно считается приблизительным, источник истины
— сервер. Это документируется в спеке («MAY отличаться деталями»).
- **[Стоимость рендера полноразмерного фото]** → O(n) box-blur вместо
гауссова с большим радиусом; дымка считается на уменьшенной копии; проходы
пропускаются, если эффект пуст; параллелизм по строкам. Добавить бенчмарк на
12 Мп и следить за временем воркера.
- **[Ореолы чёткости]** → ограничение дельты и веса по тонам; при сильных
значениях полностью убрать ореолы нельзя, это осознанный компромисс.
- **[Зерно и thumbnail]** → seed от `photo.id`, иначе фоновая пересборка даёт
разный шум; цена — визуально разные рисунки превью и полного кадра.
- **[Обратная совместимость]** → ключ `effects` игнорируется старым бинарником;
`IsEmpty` учитывает только силы, поэтому дефолты не «залипают» как правка.
- **[Шум в гистограмме]** → эффекты не входят в гистограмму; это осознанно и
может быть пересмотрено отдельным изменением.
## Migration Plan
Схемных миграций нет. Выкатка сервер + фронтенд одновременно; старые фото и
старые `edit_params` читаются с дефолтами. Откат — возврат предыдущей сборки:
неизвестный ключ `effects` старые версии просто игнорируют, параметры остаются в
метаданных и сбрасываются штатной кнопкой «Сброс».
## Open Questions
Нет.
@@ -0,0 +1,72 @@
# Proposal
## Why
В неразрушающем редакторе Galo сейчас есть только блоки «Свет» и «Цвет»:
экспозиция, тональная кривая, баланс белого, микшер и цветокоррекция. Не хватает
эффектов, которые в Lightroom собраны в панели «Эффекты»: текстура, чёткость,
удаление дымки, виньетка и зерно. Это последний крупный блок базовой обработки,
после которого веб-редактор покрывает привычный набор Lightroom.
## What Changes
- Добавить в `EditParams` блок `Effects`:
- **Текстура** — локальный контраст высоких частот (unsharp mask по яркости).
- **Чёткость** — локальный контраст средних частот с защитой от ореолов.
- **Убрать дымку** — оценка дымки (dark channel prior) и возврат контраста и
насыщенности.
- **Виньетка** — три режима, как в макете: «Свет», «Цвет», «Закарасить»
(заливка). Параметры: сила, средняя точка, растушёвка, округлость, света;
для цветных режимов — цвет виньетки.
- **Зерно** — сила, размер, шероховатость; шум детерминирован для повторных
рендеров.
- Сервер (Go): применять эффекты после света и цвета при рендере редактированной
версии; результат по-прежнему пишется в роли `edit`, `edit_thumb`,
`edit_medium`, `edit_preview`, оригинал не меняется.
- Клиент (Svelte/TS): раздел «Эффекты» в панели правок с вкладками виньетки;
живой предпросмотр эффектов в просмотрщике до готовности серверного рендера.
- Панель правок: все секции инструментов по умолчанию свёрнуты, состояние
каждой секции сохраняется в браузере (`localStorage`).
- Вкладка «Редактирование» доступна только в просмотрщике: в режиме сетки
правая панель показывает только «Сведения».
- WebGL2-превью: перейти с одного прохода на много­проходную схему (FBO,
разделимое размытие, карта дымки) для пространственных эффектов.
- Обратная совместимость: `edit_params` остаётся JSON-блобом, фото без ключа
`effects` рендерятся как раньше; миграции схемы БД не требуется.
- Android-клиент не меняется: он показывает уже отрендеренные версии.
## Capabilities
### New Capabilities
Нет — эффекты входят в существующую способность `photos`.
### Modified Capabilities
- `photos`: требование «Неразрушающее редактирование фотографии» расширяется
параметрами эффектов; добавляются требования к виньетке, зерну, пространственным
эффектам и их живому предпросмотру.
## Impact
- `backend/internal/photos/edit.go` — модель `EffectsParams`, нормализация,
`IsEmpty`, сериализация.
- `backend/internal/photos/handlers.go` — приём блока `effects` в
`PATCH /photos/:id/edit` (у обработчика собственный request-структ).
- `backend/internal/photos/edit_render.go` — порядок проходов рендера и новые
эффекты; вероятно отдельный файл с пространственными операциями (blur,
dark channel, виньетка, зерно).
- `frontend/src/lib/edit.ts` — типы, дефолты, нормализация, CPU-реализация
попиксельных эффектов (виньетка, зерно) для фолбэка.
- `frontend/src/lib/webgl-preview.ts`, `Viewer.svelte` — много­проходный
предпросмотр эффектов.
- `frontend/src/lib/components/PhotoEditPanel.svelte` — раздел «Эффекты»,
вкладки виньетки, цвет виньетки; свёрнутые по умолчанию секции; `EditSlider.svelte`
переиспользуется.
- `frontend/src/lib/editor-sections.ts` — состояние сворачивания секций в
`localStorage` и его нормализация.
- `frontend/src/lib/components/PhotoPanel.svelte` — вкладка «Редактирование»
только при открытом просмотрщике.
- Тесты: `edit_test.go`, `edit.test.ts`, новый e2e-сценарий правки с эффектами,
бенчмарк пространственных проходов; проверка компиляции GL-шейдеров.
- Миграции БД и Android-клиент не затрагиваются.
@@ -0,0 +1,180 @@
# Spec Delta
## MODIFIED Requirements
### Requirement: Неразрушающее редактирование фотографии
Система SHALL поддерживать неразрушающее редактирование фотографий. Параметры правок (свет, цвет и эффекты) SHALL храниться в метаданных фото, а отредактированная версия SHALL создаваться как отдельные объекты (роли `edit`, `edit_thumb`, `edit_medium`, `edit_preview`) рядом с исходными вариантами. Рендер SHALL выполняться по исходному объекту фото, а не по его уменьшенным вариантам. Исходный объект SHALL оставаться неизменным, а скачивание SHALL отдавать оригинал. Сброс правок SHALL удалять и параметры, и отредактированную версию. Правки SHALL применяться только к изображениям.
#### Scenario: Сохранение правок
- **WHEN** пользователь сохраняет правки фото (свет, цвет и/или эффекты)
- **THEN** параметры сохраняются в метаданных, отредактированная версия рендерится в фоне, а после рендера фото получает URL отредактированных вариантов
#### Scenario: Фоновая подготовка версий
- **WHEN** правки фото сохранены
- **THEN** система готовит варианты сетки и полноразмерную версию в фоне и сообщает о готовности
#### Scenario: Рендер по оригиналу
- **WHEN** готовится отредактированная версия фото
- **THEN** световые и цветовые правки, а также эффекты применяются к пикселям исходного объекта, а не к его уменьшенной копии
#### Scenario: Неразрушачность
- **WHEN** фото отредактировано
- **THEN** исходный объект и его варианты остаются неизменными
#### Scenario: Сброс правок
- **WHEN** пользователь сбрасывает правки
- **THEN** параметры и отредактированная версия удаляются, а фото снова показывается в исходном виде
#### Scenario: Права на правки
- **WHEN** правки сохраняет пользователь без прав на это фото
- **THEN** система отклоняет запрос
#### Scenario: Редактирование видео
- **WHEN** пользователь пытается отредактировать видео
- **THEN** система отклоняет запрос
#### Scenario: Цветовые правки сохраняются и рендерятся
- **WHEN** пользователь сохраняет цветовые правки фото: баланс белого (температура/оттенок), сочность (vibrance), насыщенность, цветовой микшер по оттенкам, цветокоррекцию (тени/средние тона/света, яркость зон, наложение, баланс) или поканальную коррекцию
- **THEN** параметры цвета сохраняются в метаданных, отредактированная версия рендерится в фоне, а после рендера фото получает URL отредактированных вариантов
#### Scenario: Цветовые правки применяются к пикселям исходного объекта
- **WHEN** готовится отредактированная версия фото с цветовыми правками
- **THEN** цветовые правки применяются к пикселям исходного объекта после световых правок, а не к его уменьшенной копии
#### Scenario: Пустые цветовые правки не сохраняются
- **WHEN** в цветовых параметрах заданы только наложение/баланс или оттенок колеса без силы и яркости
- **THEN** правки считаются пустыми и фото не получает цветовую версию
#### Scenario: Пустые правки эффектов не сохраняются
- **WHEN** во всех эффектах заданы только значения по умолчанию (сила эффекта, виньетки и зерна равна нулю)
- **THEN** правки считаются пустыми и фото не получает новую отредактированную версию
## ADDED Requirements
### Requirement: Текстура
Клиент SHALL позволять настраивать текстуру фото в диапазоне -100..100. Положительные значения SHALL усиливать контраст мелких деталей, отрицательные — ослаблять его. Эффект SHALL применяться к исходному кадру после световых и цветовых правок.
#### Scenario: Усиление текстуры
- **WHEN** пользователь увеличивает значение текстуры
- **THEN** мелкие детали становятся контрастнее, а общая тональность кадра не меняется
#### Scenario: Ослабление текстуры
- **WHEN** пользователь уменьшает значение текстуры ниже нуля
- **THEN** мелкие детали сглаживаются
#### Scenario: Текстура в пределах допустимого
- **WHEN** клиент присылает значение текстуры вне диапазона -100..100
- **THEN** сервер ограничивает его ближайшей границей диапазона
### Requirement: Чёткость
Клиент SHALL позволять настраивать чёткость фото в диапазоне -100..100. Положительные значения SHALL усиливать локальный контраст средних частот, отрицательные — смягчать его. Чёткость SHALL NOT создавать заметных ореолов на границах контрастных объектов. Эффект SHALL применяться после световых и цветовых правок.
#### Scenario: Усиление чёткости
- **WHEN** пользователь увеличивает значение чёткости
- **THEN** локальный контраст средних тонов растёт, а границы контрастных объектов остаются без заметных ореолов
#### Scenario: Ослабление чёткости
- **WHEN** пользователь уменьшает значение чёткости ниже нуля
- **THEN** изображение становится мягче
### Requirement: Убрать дымку
Клиент SHALL позволять ослаблять или усиливать дымку в диапазоне -100..100. При положительных значениях сервер SHALL оценивать дымку по кадру и возвращать контраст и насыщенность удалённых участков; отрицательные значения SHALL добавлять дымку.
#### Scenario: Удаление дымки
- **WHEN** пользователь увеличивает значение «Убрать дымку» на кадре с дымкой
- **THEN** дальние планы становятся контрастнее и насыщеннее
#### Scenario: Добавление дымки
- **WHEN** пользователь уменьшает значение «Убрать дымку» ниже нуля
- **THEN** кадр становится менее контрастным, как при дымке
### Requirement: Виньетка
Клиент SHALL позволять настраивать виньетку: силу -100..100, среднюю точку и растушёвку 0..100 (по умолчанию 50), округлость -100..100, света 0..100, а также режим «Свет», «Цвет» или «Закарасить». Режим «Свет» SHALL затемнять или осветлять края, «Цвет» — тонировать их выбранным цветом с сохранением светлоты, «Закарасить» — заливать их выбранным цветом.
#### Scenario: Затемнение краёв
- **WHEN** пользователь задаёт положительную силу виньетки в режиме «Свет»
- **THEN** края кадра затемняются, а центр остаётся без изменений
#### Scenario: Осветление краёв
- **WHEN** пользователь задаёт отрицательную силу виньетки в режиме «Свет»
- **THEN** края кадра осветляются
#### Scenario: Цветная виньетка
- **WHEN** пользователь выбирает режим «Цвет» или «Закарасить» и задаёт цвет виньетки
- **THEN** края кадра тонируются или заливаются этим цветом с силой, заданной ползунком виньетки
#### Scenario: Геометрия виньетки
- **WHEN** пользователь меняет среднюю точку, растушёвку или округлость
- **THEN** меняются размер, мягкость и форма зоны виньетки
#### Scenario: Защита светов
- **WHEN** пользователь увеличивает значение «Света» в режиме «Свет»
- **THEN** яркие участки в зоне виньетки сохраняют яркость
#### Scenario: Нулевая сила виньетки
- **WHEN** сила виньетки равна нулю
- **THEN** виньетка не влияет на изображение независимо от остальных параметров
### Requirement: Зерно
Клиент SHALL позволять добавлять зерно с силой, размером и шероховатостью в диапазоне 0..100 (по умолчанию размер 25, шероховатость 50). Зерно SHALL быть детерминированным: повторный рендер одних и тех же параметров SHALL давать одинаковый шум.
#### Scenario: Добавление зерна
- **WHEN** пользователь увеличивает силу зерна
- **THEN** на изображении появляется шум, заметный в средних тонах
#### Scenario: Размер и шероховатость
- **WHEN** пользователь меняет размер или шероховатость зерна
- **THEN** меняются крупность и контрастность шума
#### Scenario: Детерминированность зерна
- **WHEN** сервер повторно рендерит фото с теми же параметрами зерна
- **THEN** рисунок шума совпадает с предыдущим рендером
#### Scenario: Нулевая сила зерна
- **WHEN** сила зерна равна нулю
- **THEN** зерно не влияет на изображение
### Requirement: Живой предпросмотр эффектов
Клиент SHALL показывать эффекты в просмотрщике до завершения серверного рендера. После готовности серверной версии клиент SHALL показывать её. Предпросмотр пространственных эффектов (текстура, чёткость, дымка) MAY отличаться от серверного рендера деталями, но SHALL передавать характер эффекта.
#### Scenario: Эффекты видны сразу
- **WHEN** пользователь двигает ползунок эффекта
- **THEN** просмотрщик обновляет изображение без ожидания серверного рендера
#### Scenario: Серверная версия заменяет предпросмотр
- **WHEN** серверный рендер эффектов завершён
- **THEN** просмотрщик показывает серверную версию
#### Scenario: Предпросмотр без WebGL
- **WHEN** аппаратное ускорение недоступно
- **THEN** клиент показывает эффекты доступным способом или показывает их после серверного рендера, не блокируя интерфейс
### Requirement: Свёрнутые секции редактора
Редактор SHALL показывать все сворачиваемые секции инструментов свёрнутыми по умолчанию. Клиент SHALL сохранять состояние каждой секции (свёрнута или развёрнута) в браузере пользователя и восстанавливать его при повторном открытии редактора и перезагрузке страницы. Состояние SHALL NOT зависеть от выбранного фото.
#### Scenario: Первое открытие редактора
- **WHEN** пользователь впервые открывает редактор фото
- **THEN** все секции инструментов («Свет», «Цвет», «Эффекты» и их вложенные блоки) свёрнуты
#### Scenario: Состояние запоминается
- **WHEN** пользователь разворачивает секцию «Эффекты» и перезагружает страницу
- **THEN** секция «Эффекты» остаётся развёрнутой
#### Scenario: Состояние переживает смену фото
- **WHEN** пользователь переключает фото в редакторе
- **THEN** свёрнутость секций не меняется
### Requirement: Редактирование только из просмотрщика
Клиент SHALL показывать вкладку «Редактирование» только когда фото открыто в просмотрщике. В режиме сетки правая панель SHALL показывать только «Сведения» и SHALL NOT отображать инструменты редактирования.
#### Scenario: Фото выбрано в сетке
- **WHEN** пользователь выбирает фото в сетке, не открывая просмотрщик
- **THEN** в правой панели отображается только вкладка «Сведения»
#### Scenario: Фото открыто в просмотрщике
- **WHEN** пользователь открывает фото в просмотрщике
- **THEN** в правой панели доступны «Сведения» и «Редактирование»
#### Scenario: Возврат из просмотрщика в сетку
- **WHEN** пользователь возвращается из просмотрщика в сетку
- **THEN** вкладка «Редактирование» скрыта, панель показывает «Сведения»
@@ -0,0 +1,62 @@
# Tasks
## 1. Модель правок и нормализация (Go)
- [x] 1.1 Добавить `EffectsParams`, `VignetteParams`, `GrainParams` и поле `EditParams.Effects` в `backend/internal/photos/edit.go`, включая режимы виньетки и hex-цвет — проверить `cd backend && go build ./internal/photos/`
- [x] 1.2 Реализовать нормализацию: диапазоны, дефолты midpoint 50 / feather 50 / size 25 / roughness 50, неизвестный режим → `light`, валидный hex-цвет; обновить `IsEmpty`/`JSON` так, чтобы дефолты без силы не считались правкой — проверить `cd backend && go test ./internal/photos/ -run TestEffectsParams -v`
- [x] 1.3 Проверить обратную совместимость: `{}` и старые параметры только со светом/цветом читаются как пустые эффекты и рендерятся без изменений — проверить `cd backend && go test ./internal/photos/ -run TestEditParamsLegacy -v`
## 2. Пространственный рендер (Go)
- [x] 2.1 Добавить хелпер яркости и разделимый box-blur со скользящим окном (O(n) от радиуса, параллельно по строкам) — проверить `cd backend && go test ./internal/photos/ -run TestBoxBlur -v` и бенчмарк на 4000×3000
- [x] 2.2 Реализовать текстуру и чёткость как unsharp mask по яркости с ограничением дельты и весами по тонам (радиусы — доли `min(width,height)`) — проверить тест, что локальная дисперсия растёт при положительных и падает при отрицательных значениях
- [x] 2.3 Реализовать «Убрать дымку» через dark channel prior: атмосферный свет и карта пропускания на уменьшенной копии, интерполяция на полный кадр, положительные и отрицательные значения — проверить тест на синтетическом «задымлённом» изображении: контраст и насыщенность растут
- [x] 2.4 Реализовать виньетку: нормализованная геометрия (midpoint, feather, roundness), режимы «Свет»/«Цвет»/«Закарасить», защита светов — проверить тест: края темнеют/светлеют, центр не меняется, цветные режимы меняют оттенок краёв
- [x] 2.5 Реализовать зерно: PRNG с seed от `photo.id`, размер и шероховатость, аддитивный шум в яркость — проверить тест: два рендера с одинаковыми параметрами дают идентичные пиксели, сила 0 не меняет кадр
- [x] 2.6 Встроить эффекты в `decodeAndAdjust` в порядке свет → цвет → дымка → текстура → чёткость → виньетка → зерно, с пропуском пустых проходов — проверить `cd backend && go test ./internal/photos/ -v` и бенчмарк полного рендера
- [x] 2.7 Добавить e2e-сценарий: сохранение правки с эффектами, фоновый рендер `edit_*`, сброс, повторный рендер с тем же зерном — проверить `cd backend && go test ./internal/e2e/ -run TestEffectsEdit -v`
## 3. Клиентская модель и CPU-фолбэк (TypeScript)
- [x] 3.1 Добавить `EffectsParams` и дефолты в `frontend/src/lib/edit.ts`, обновить `readEditParams`/`normalizeEditParams`/`isEmptyEditParams` — проверить `cd frontend && npm run test` (`edit.test.ts`) и `npm run check`
- [x] 3.2 Реализовать CPU-применение виньетки и зерна (по образцу `applyColorToPixels`), seed и геометрия — как на сервере; тесты на затемнение краёв и детерминированность шума — проверить `cd frontend && npm run test`
- [x] 3.3 Убедиться, что гистограмма по-прежнему считается только по свету и цвету (без пространственных эффектов) — проверить `npm run check` и отсутствие изменений в расчёте `histogram`
## 4. WebGL-предпросмотр
- [x] 4.1 Перевести `frontend/src/lib/webgl-preview.ts` на много­проходную схему: свет/цвет в FBO-текстуру вместо экрана, два ping-pong FBO — проверить компиляцию/линковку шейдеров и `npm run build`
- [x] 4.2 Добавить проход яркости и разделимое box-размытие: малое разрешение для чёткости, несколько тапов для текстуры; включать проход только при ненулевых значениях — проверить, что текстура и чёткость видны в превью и не ломают свет/цвет
- [x] 4.3 Добавить предварительный расчёт дымки на CPU (атмосферный свет + карта пропускания по базовому превью) и передачу её текстурой в финальный проход — проверить, что ползунок дымки меняет превью
- [x] 4.4 Добавить в финальный проход виньетку (три режима) и зерно (хеш-шум) с параметрами из `liveParams.effects` — проверить визуально смену режимов и силы
- [x] 4.5 Подключить эффекты в `Viewer.svelte` для GL-пути и CPU-фолбэка: при `previewLow` снижать качество размытия, после паузы — полное; в CPU-фолбэке применять только виньетку и зерно — проверить, что интерфейс не блокируется при перетаскивании
- [x] 4.6 Проверить деградацию без WebGL: пространственные эффекты появляются после серверного рендера, а виньетка/зерно видны сразу — проверить ручным сценарием с отключённым WebGL2
## 5. UI: раздел «Эффекты»
- [x] 5.1 Добавить сворачиваемую секцию «Эффекты» в `PhotoEditPanel.svelte` со слайдерами текстуры, чёткости и дымки (`EditSlider`) — проверить открытие/сворачивание и изменение превью
- [x] 5.2 Добавить вкладки виньетки «Свет»/«Цвет»/«Закарасить», ползунки силы/средней точки/растушёвки/округлости/светов и свотч цвета для цветных режимов — проверить сохранение режима и цвета в параметрах
- [x] 5.3 Добавить ползунки зерна (сила, размер, шероховатость) — проверить, что сила 0 не добавляет правку
- [x] 5.4 Подключить эффекты к существующему сохранению (`scheduleSave`/`photosApi.edit`), переключению фото и глобальному сбросу — проверить `PATCH /api/photos/:id/edit` с `effects`, сброс очищает параметры и `edit_*`, переключение фото не теряет несохранённые эффекты
- [x] 5.5 Проверить сборку и типы: `cd frontend && npm run check && npm run build`
## 6. Интеграционная проверка
- [x] 6.1 Ручной прогон матрицы: только эффекты; эффекты вместе со светом/цветом; сброс; правка во время переключения фото; фото без `effects`; копия фото не наследует эффекты; видео отклоняется — проверить в запущенном инстансе
- [x] 6.2 Замерить время фонового рендера полноразмерного фото с включёнными текстурой/чёткостью/дымкой и сравнить с текущим рендером света/цвета — проверить по логам воркера и бенчмарку
- [x] 6.3 Прогнать общие проверки репозитория: `make test`, фронтенд-тесты `npm run test` и сборку `make build`
## 7. Свёрнутые секции редактора
- [x] 7.1 Добавить `frontend/src/lib/editor-sections.ts` (дефолты, чтение/запись localStorage, нормализация) и тесты — проверить `cd frontend && npm run test` (`editor-sections.test.ts`)
- [x] 7.2 Сделать все сворачиваемые секции `PhotoEditPanel.svelte` свёрнутыми по умолчанию и подключить сохранение состояния — проверить `npm run check`
- [x] 7.3 Проверить в Chrome: по умолчанию всё свёрнуто, развёрнутое состояние переживает перезагрузку и смену фото — сценарий с CDP, без ошибок в консоли
## 8. Вкладка редактирования только в просмотрщике
- [x] 8.1 Скрыть вкладку «Редактирование» в режиме сетки через `activeTab` в `PhotoPanel.svelte` — проверить `cd frontend && npm run check`
- [x] 8.2 Проверить в Chrome: в сетке доступна только «Сведения», в просмотрщике — «Редактирование», после возврата в сетку вкладка снова скрыта — CDP-сценарий, без ошибок в консоли
## Workflow follow-up
- Архивировать изменение после удовлетворения требований ревью проекта.
- Проверить архивированный результат: дельта-спека `photos` применена к основной спеке.
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-10-25
@@ -0,0 +1,151 @@
# Design
## Context
Просмотрщик уже рисует клиентский предпросмотр правок: canvas с отфильтрованной
видимой областью лежит поверх базовой версии фото (`original_url` в зуме,
`preview_url` иначе). Решение «показывать ли серверную версию» сейчас принимается
по флагам `hasEdits`, `pending` (локальные параметры ≠ сохранённым) и `!editUrl`
([Viewer.svelte](frontend/src/lib/components/Viewer.svelte)) — то есть по наличию
URL, а не по состоянию рендера.
Сохранение отложено на 10 секунд ([PhotoEditPanel.svelte](frontend/src/lib/components/PhotoEditPanel.svelte)):
`PATCH /photos/:id/edit` ставит задание в `edit_jobs` и публикует `photo.updated`,
затем воркер публикует `photo.updated` после вариантов превью и ещё раз после
полного варианта. Таблица `edit_jobs` уже существует (`photo_id` — первичный
ключ), миграции не нужны. Обогащение URL — `attachURLs`, через него проходят все
выдачи фото, включая события SSE. У Viewer есть вторая копия фото `fresh`,
перезапрашиваемая по REST, и её URL имеют приоритет над `current`, хотя актуальные
приходят по SSE.
## Goals / Non-Goals
**Goals:**
- API даёт однозначный признак «рендер сохранённых правок не завершён».
- Просмотрщик выбирает источник изображения по состоянию, а не по наличию URL.
- Подмена предпросмотра серверной версией происходит без показа оригинала или
предыдущей отрендеренной версии.
- Сброс правок виден сразу, в том числе при возврате контролов в значения по
умолчанию.
**Non-Goals:**
- Менять 10-секундный дебаунс сохранения и схему БД.
- Новые состояния рендера (ошибки, приоритеты, отмена), статус ошибки рендера.
- Кроссфейд/анимация подмены.
- Изменения Android-клиента и синхронизация правок между устройствами сверх SSE.
## Decisions
### D1. `edit_pending` — булев признак из наличия задания в `edit_jobs`, считается в SQL
- В `models.Photo` добавляется `EditPending bool` с JSON-тегом `edit_pending`.
Поле присутствует всегда; его отсутствие означает старый бэкенд и трактуется
клиентом как `false`.
- В общие списки колонок фото (`photoColumns` в Postgres, `sqlitePhotoColumns` в
SQLite) добавляется `EXISTS (SELECT 1 FROM edit_jobs ej WHERE ej.photo_id = p.id)`;
сканирование поля добавляется в функции чтения фото (включая чтение корзины).
В корзине попутно исправляется порядок чтения: tags JSON и `album_title` были
перепутаны (проверяется регрессионным тестом в контракте).
- Обоснование: ответы сохранения/сброса и оба события `photo.updated` собираются
через `GetByID`, списки альбома — через `List`; один SELECT даёт признак во всех
путях, без дополнительных запросов и без изменений в сервисном слое.
- Альтернативы:
- отдельный метод репозитория `PendingEditIDs` + обогащение в сервисе — больше
точек изменения и N+1 для списков; отвергнуто;
- хранить ревизию или хэш отрендеренных параметров (миграция и сравнение на
клиенте) — точнее переживает неудачный рендер, но дороже; выносится в отдельное
изменение, если понадобится;
- клиентская эвристика «URL изменился с момента сохранения» — хрупкая (сброс,
повторный рендер, несколько вкладок); отвергнуто.
- Семантика: `true`, пока строка задания есть (ожидает, выполняется, повтор);
`false` после `CompleteEditJob`/`DeleteEditJob`, включая сброс. Поиск идёт по
первичному ключу `edit_jobs.photo_id`.
- Совместимость: поле аддитивное, миграций нет; старые клиенты его игнорируют.
### D2. Клиентская машина состояний просмотра
| `dirty` (локальные ≠ сохранённым) | `edit_pending` | Что показывает просмотрщик |
|---|---|---|
| true | не важно | базовая версия + canvas с локальными правками; canvas не рисуется, если локальные правки пусты (сброс) |
| false | true | базовая версия + canvas с сохранёнными правками |
| false | false | серверная версия; canvas держится до загрузки/декодирования нового изображения |
- «Базовая версия» — `original_url` в зуме, `preview_url` иначе (без edit-ролей).
- «Серверная версия» — `edit_url` в зуме, `edit_preview_url` иначе; если
edit-вариантов нет, показывается базовая версия.
- `edit_pending` отсутствует в ответе (старый бэкенд) — считается `false`
(поведение как раньше, без падений).
- Когда `dirty` и локальные правки пусты (сброс возвратом контролов) — сразу
базовая версия, без canvas и без опоры на серверные edit-URL. Это делает сброс
мгновенным.
- Обоснование: все три наблюдаемых симптома — следствие того, что показ серверной
версии включался по `!editUrl` и `hasEdits`, а не по «серверный рендер
соответствует сохранённым параметрам и картинка готова к показу».
### D3. Подмена — только после загрузки и декодирования
- При переходе в состояние «серверная версия» клиент предзагружает целевой URL
(скрытый `Image`) и ждёт `decode()` (фолбэк — `load`); только затем снимает
canvas и меняет `src`. До этого canvas остаётся, поэтому оригинал не мелькает.
- Canvas поднимается только на время перехода «предпросмотр → серверная версия»:
при обычном открытии фото с уже готовым рендером серверную версию грузит сам
`<img>`, лишний кадр оригинала не показывается.
- Устаревшие предзагрузки отменяются по счётчику/`AbortSignal`, чтобы поздний
ответ не вернул предыдущую версию.
- Цена — небольшая задержка финального кадра (обычно сотни мс), зато без мигания.
- Кроссфейд отвергнут: спекой не требуется, лишняя косметика.
### D4. Один актуальный источник фото в Viewer
- `current` (обновляется SSE `photo.updated`) — основной источник URL и состояния.
- `fresh` остаётся только фолбэком для страниц без SSE (просмотр по share-ссылке)
и первичной загрузки; при выборе URL приоритет у актуального объекта, а refetch
защищён счётчиком последовательности, чтобы устаревший ответ не перебил новый.
- Обоснование: `photoFullUrl(fresh)` всегда возвращает хотя бы `original_url`,
поэтому протухший `fresh` показывает именно оригинал.
### D5. Сброс: показ — мгновенно, отправка — по текущей политике дебаунса
- Дебаунс сохранения не меняется: показ исходного вида обеспечивает D2
(`dirty` + пустые параметры → базовая версия), а отложенный `flushSave`/`resetEdit`
лишь приводит сервер в соответствие. При уходе из панели `flushSave` уже
отправляет сброс.
- Альтернатива — отправлять сброс сразу, без дебаунса — уменьшает расхождение между
вкладками, но добавляет отдельную политику сохранения и `DELETE` на каждое
обнуление контролов; отвергнуто.
- Следствие: другие вкладки и устройства увидят сброс после дебаунса — как и любое
отложенное сохранение; это осознанный компромисс.
### D6. Индикатор рендера в панели редактора
- `rendering` в панели считается как `photo.edit_pending`, а не как
`hasEdits && !photo.edit_preview_url`: так индикатор корректен и для повторной
правки, и после сброса.
## Risks / Trade-offs
- **Рендер падает после всех попыток** → задание удаляется, `edit_pending=false`,
остаётся последняя успешная отрендеренная версия, клиент покажет её. Поведение не
хуже текущего; отдельный статус ошибки рендера — вне этого изменения.
- **Смешанные версии бэкенда и фронтенда** → аддитивное поле: новый фронтенд со
старым бэкендом трактует отсутствие как `false` и работает как раньше; новый
бэкенд со старым фронтендом безвреден. Деплой в любом порядке, рекомендуется
сначала бэкенд.
- **Дополнительная колонка в горячих SELECT фото** → `EXISTS` по первичному ключу,
стоимость пренебрежимо мала; при необходимости позже выносится в отдельное
обогащение.
- **Порядок SSE-событий** → сохранение публикует `photo.updated` с `edit_pending=true`,
готовность — с `false`; клиент зависит только от значения, не от числа событий.
Гонка «воркер завершил рендер раньше reload в publishEdit» даёт `false` и новые
URL — консистентно.
- **Большие full-res файлы** → финальный кадр появится позже, пока canvas с
предпросмотром продолжает показываться; это ожидаемое поведение.
## Migration Plan
- Миграций БД нет. Бэкенд и фронтенд разворачиваются независимо (аддитивное поле);
рекомендация — сначала бэкенд.
- Откат: достаточно вернуть прежний Viewer/тип (поле бэкенда безвредно); откат
бэкенда не ломает старый фронтенд.
@@ -0,0 +1,69 @@
# Proposal
## Why
Клиент узнаёт о готовности серверного рендера правок только по появлению
`edit_url`/`edit_preview_url` в объекте фото, а признака «рендер сохранённых правок
ещё идёт» в API нет. Из-за этого в просмотрщике:
- после отложенного сохранения (дебаунс 10 с) при появлении полного рендера
клиентский предпросмотр выключается раньше, чем новое изображение загружено, и
в зуме на время загрузки виден оригинал (мигание «оригинал → правка»);
- повторная правка, у которой уже есть предыдущий рендер, после сохранения
показывает старую отрендеренную версию, пока не завершится новый рендер;
- сброс, сделанный возвратом контролов в значения по умолчанию, не виден до
срабатывания дебаунса: локальные параметры уже пусты, предпросмотр выключен, и
просмотрщик показывает старую серверную версию — «сброс срабатывает через 10 с».
## What Changes
- Фото получает аддитивный признак незавершённого рендера правок — булево поле
`edit_pending` в ответах API и в событиях `photo.updated`: `true`, пока в
`edit_jobs` есть задание на рендер; `false`, когда рендера нет или он завершён.
- Клиент перестаёт угадывать готовность по наличию URL и опирается на признак:
пока есть несохранённые локальные правки или серверный рендер не завершён,
просмотрщик показывает клиентский предпросмотр поверх исходной версии.
- Замена предпросмотра серверной версией выполняется только после загрузки и
декодирования нового изображения — без промежуточного показа оригинала или
предыдущей отрендеренной версии.
- Сброс правок (кнопкой и возвратом контролов в значения по умолчанию) виден в
просмотрщике сразу, не дожидаясь отложенного сохранения.
- Viewer перестаёт предпочитать устаревшую локальную копию фото: URL для показа
берутся из актуального объекта, обновляемого SSE-событиями.
- Индикатор «Рендерим правки на сервере…» в панели редактора опирается на
`edit_pending`, а не на отсутствие URL.
- Без изменений: отложенное сохранение (10 с), неразрушающий рендер, роли
объектов, формат `edit_params`, схема БД, Android-клиент (поле аддитивное,
отсутствие трактуется как `false`).
## Capabilities
### New Capabilities
Нет — изменение уточняет существующие способности.
### Modified Capabilities
- `photos`: новый признак незавершённого рендера правок; уточняются «Живой
предпросмотр цветовых правок», «Живой предпросмотр эффектов» (бесшовная
подмена) и добавляется требование о мгновенном показе сброса.
- `realtime`: `photo.updated` отражает жизненный цикл рендера правок — сохранение
(`edit_pending=true`), готовность (`edit_pending=false` + URL отредактированных
вариантов), сброс (без URL отредактированных вариантов).
## Impact
- `backend/internal/models/models.go` — поле `EditPending` в `Photo`.
- `backend/internal/photos/store.go`, `sqlite_store.go` — `EXISTS` по `edit_jobs`
в общем списке колонок; сканирование поля. Миграции не нужны: таблица уже есть.
- `backend/internal/photos/edit_service.go`, `worker.go`, `handlers.go` — признак
попадает в ответы сохранения/сброса и в события (через общие запросы фото).
- `frontend/src/lib/types.ts` — поле в типе `Photo`.
- `frontend/src/lib/components/Viewer.svelte` — выбор источника изображения по
состоянию (локальные правки / `edit_pending` / загруженность нового кадра),
предзагрузка и декодирование, единый актуальный источник URL.
- `frontend/src/lib/components/PhotoEditPanel.svelte` — статус рендера.
- Новый чистый модуль выбора источника предпросмотра + vitest.
- Тесты: контрактные (репозитории, SQLite и Postgres), e2e рендера правок,
frontend-модульные тесты, проверка `svelte-check`.
- API: аддитивное поле `edit_pending`; старые клиенты (Android) его игнорируют.
@@ -0,0 +1,91 @@
# Spec Delta: photos
## ADDED Requirements
### Requirement: Признак незавершённого рендера правок
Фото в ответах API и в событиях `photo.updated` SHALL содержать булево поле `edit_pending`. Оно SHALL быть `true`, пока серверный рендер сохранённых правок не завершён, и `false`, когда рендера нет или он завершён. Пока `edit_pending` равно `true`, URL отредактированных вариантов SHALL NOT считаться актуальными, даже если они присутствуют. Поле SHALL быть аддитивным: клиент, который его не читает, продолжает работать как раньше.
#### Scenario: Сохранение правок
- **WHEN** правки фото сохранены, а серверный рендер ещё не завершён
- **THEN** ответ на сохранение и событие `photo.updated` содержат `edit_pending=true`
#### Scenario: Предыдущий рендер устарел
- **WHEN** у фото уже есть отрендеренная версия, а для новых сохранённых правок рендер ещё не завершён
- **THEN** фото содержит `edit_pending=true`, а URL отредактированных вариантов не выдаются за актуальные
#### Scenario: Готовность рендера
- **WHEN** серверный рендер сохранённых правок завершён
- **THEN** `edit_pending=false`, а URL отредактированных вариантов соответствуют сохранённым правкам
#### Scenario: Сброс правок
- **WHEN** правки фото сброшены
- **THEN** `edit_pending=false` и URL отредактированных вариантов отсутствуют
### Requirement: Мгновенный показ сброса правок
Клиент SHALL показывать исходный вид фото сразу после возврата контролов редактора в значения по умолчанию или нажатия сброса, не дожидаясь отложенного сохранения на сервер. Пока сброс, выполненный возвратом контролов, ещё не отправлен, просмотрщик SHALL NOT показывать отредактированную версию фото.
#### Scenario: Сброс возвратом контролов
- **WHEN** пользователь возвращает контролы редактора в значения по умолчанию (двойной клик по ползунку, шкала в нуле)
- **THEN** просмотрщик сразу показывает исходный вид, не дожидаясь срабатывания отложенного сохранения
#### Scenario: Сброс кнопкой
- **WHEN** пользователь нажимает «Сброс»
- **THEN** просмотрщик показывает исходный вид не позже ответа на запрос сброса
#### Scenario: Сброс при готовом рендере
- **WHEN** сброс выполнен, а отредактированная версия ещё существует на сервере
- **THEN** просмотрщик показывает исходный вид, а не отредактированную версию
## MODIFIED Requirements
### Requirement: Живой предпросмотр цветовых правок
Клиент SHALL показывать результат цветовых правок в просмотрщике до завершения серверного рендера. Пока серверный рендер сохранённых правок не завершён (`edit_pending`) или пока локальные правки не сохранены, клиент SHALL показывать клиентский предпросмотр поверх исходной версии. После завершения рендера SHALL показываться серверная версия. Клиент SHALL NOT показывать исходную или предыдущую отрендеренную версию между предпросмотром и серверной версией: подмена SHALL выполняться только после загрузки нового изображения.
#### Scenario: Правки видны сразу
- **WHEN** пользователь двигает цветовой контрол
- **THEN** просмотрщик обновляет изображение без ожидания серверного рендера
#### Scenario: Серверная версия заменяет предпросмотр
- **WHEN** серверный рендер цветовых правок завершён
- **THEN** просмотрщик показывает отрендеренную версию
#### Scenario: Бесшовная подмена предпросмотра
- **WHEN** серверный рендер завершён, но новое изображение ещё загружается
- **THEN** просмотрщик продолжает показывать предпросмотр и не показывает оригинал или предыдущую отрендеренную версию
### Requirement: Живой предпросмотр эффектов
Клиент SHALL показывать эффекты в просмотрщике до завершения серверного рендера. Пока серверный рендер сохранённых правок не завершён (`edit_pending`) или пока локальные правки не сохранены, клиент SHALL показывать клиентский предпросмотр поверх исходной версии. После готовности серверной версии клиент SHALL показывать её после загрузки нового изображения, не показывая в промежутке оригинал или предыдущую отрендеренную версию. Предпросмотр пространственных эффектов (текстура, чёткость, дымка) MAY отличаться от серверного рендера деталями, но SHALL передавать характер эффекта.
#### Scenario: Эффекты видны сразу
- **WHEN** пользователь двигает ползунок эффекта
- **THEN** просмотрщик обновляет изображение без ожидания серверного рендера
#### Scenario: Серверная версия заменяет предпросмотр
- **WHEN** серверный рендер эффектов завершён
- **THEN** просмотрщик показывает серверную версию
#### Scenario: Бесшовная подмена предпросмотра
- **WHEN** серверный рендер эффектов завершён, но новое изображение ещё загружается
- **THEN** просмотрщик продолжает показывать предпросмотр и не показывает оригинал или предыдущую отрендеренную версию
#### Scenario: Предпросмотр без WebGL
- **WHEN** аппаратное ускорение недоступно
- **THEN** клиент показывает эффекты доступным способом или показывает их после серверного рендера, не блокируя интерфейс
@@ -0,0 +1,38 @@
# Spec Delta: realtime
## MODIFIED Requirements
### Requirement: События альбома
Система SHALL публиковать события photo.created, photo.updated, photo.deleted,
comment.created, like.added, like.removed, member.joined, member.left, album.updated.
Событие photo.created SHALL обозначать появление фото в альбоме, а готовность вариантов
существующего фото SHALL публиковаться как photo.updated. Сохранение, готовность и сброс
правок фото SHALL также публиковаться как photo.updated, неся аддитивный признак
незавершённого рендера правок (`edit_pending`) и актуальность URL отредактированных
вариантов.
#### Scenario: Новое фото
- **WHEN** в альбоме появляется фото
- **THEN** подписчики получают событие photo.created с метаданными и URL превью
#### Scenario: Готовы варианты
- **WHEN** для существующего фото сгенерированы thumb и preview
- **THEN** подписчики получают событие photo.updated с этим фото
#### Scenario: Сохранены правки фото
- **WHEN** пользователь сохраняет правки фото, а рендер ещё не завершён
- **THEN** подписчики получают событие photo.updated с `edit_pending=true`
#### Scenario: Рендер правок готов
- **WHEN** серверный рендер сохранённых правок завершён
- **THEN** подписчики получают событие photo.updated с `edit_pending=false` и URL отредактированных вариантов
#### Scenario: Правки фото сброшены
- **WHEN** правки фото сброшены
- **THEN** подписчики получают событие photo.updated с `edit_pending=false` и без URL отредактированных вариантов
@@ -0,0 +1,23 @@
# Tasks
## 1. Бэкенд: признак `edit_pending` в модели и запросах
- [x] 1.1 Добавить `EditPending bool` в `models.Photo` (JSON-тег `edit_pending`, поле присутствует всегда) и `EXISTS (SELECT 1 FROM edit_jobs ej WHERE ej.photo_id = p.id)` в общие списки колонок фото для Postgres (`photoColumns`) и SQLite (`sqlitePhotoColumns`); обновить сканирование поля в функциях чтения фото и корзины. Проверка: `cd backend && go build -tags nodynamic ./...` и `go test ./internal/photos/` проходят.
- [x] 1.2 Покрыть контрактными тестами оба диалекта: после `EnqueueEditJob` фото из `GetByID` и `List` имеет `EditPending=true`, после `CompleteEditJob` и `DeleteEditJob` — `false`. Проверка: `cd backend && go test ./internal/repo/ -v`; с `TEST_DATABASE_URL` тот же набор проходит и на Postgres.
- [x] 1.3 Добавить e2e-проверку жизненного цикла: `EditPhoto` возвращает `edit_pending=true` (в том числе при повторной правке, когда старый рендер ещё привязан), `Worker.ProcessOnce` — `false` вместе с URL отредактированных вариантов, `ResetEdit` — `false` без URL. Проверка: `cd backend && go test ./internal/e2e/ -run 'Edit' -v`.
## 2. Фронтенд: выбор источника изображения по состоянию
- [x] 2.1 Добавить `edit_pending?: boolean` в тип `Photo` (`frontend/src/lib/types.ts`). Проверка: `cd frontend && npm run check`.
- [x] 2.2 Вынести выбор источника в чистый модуль (`frontend/src/lib/viewer-source.ts`): вход — локальные и сохранённые параметры, `edit_pending`, режим зума, URL вариантов; выход — показывать базовую или серверную версию, нужен ли canvas, какой URL грузить. Покрыть сценариями спеки: локальные правки, пустые локальные правки (сброс), `edit_pending=true` при старом рендере, готовый рендер, отсутствие поля (старый бэкенд = `false`). Проверка: `cd frontend && npm run test -- viewer-source`.
- [x] 2.3 Подключить модуль в `Viewer.svelte`: canvas держится до предзагрузки и `decode()` нового изображения (устаревшие предзагрузки отменяются), показ строится от актуального `current`, а `fresh` становится фолбэком с защитой от устаревших ответов. Проверка: `cd frontend && npm run check && npm run test`.
- [x] 2.4 Перевести индикатор «Рендерим правки на сервере…» в `PhotoEditPanel.svelte` на `photo.edit_pending` вместо `hasEdits && !photo.edit_preview_url`. Проверка: `cd frontend && npm run check`.
## 3. Интеграционная проверка
- [x] 3.1 Сквозной сценарий на собранном приложении (`make build`): правка с зумом не показывает оригинал между предпросмотром и серверной версией; сброс возвратом ползунков в значения по умолчанию сразу показывает исходный вид, не дожидаясь 10 секунд. Проверка: автопрогон в chromium 156 (headless + CDP) на собранном бинарнике: 189 замеров состояния — 0 нарушений инварианта «без canvas только серверная версия», 34 кадра подмены — оригинала нет ни на одном, после сброса через 80 мс показан оригинал (canvas снят, temp=0), серверный сброс доехал после debounce. Результат зафиксирован в отчёте об изменении.
- [x] 3.2 Полный набор проверок: `make test`, `cd frontend && npm run test && npm run check`, `openspec validate fix-edit-preview-handoff --strict`. Проверка: все команды завершаются успешно.
## Workflow follow-up
- Заархивировать изменение после проверки и обновления основного отчёта об изменениях.
+7 -5
View File
@@ -59,18 +59,20 @@ E.164 — и паролю.
- **THEN** система отзывает refresh-токен, и его дальнейшее использование отклоняется - **THEN** система отзывает refresh-токен, и его дальнейшее использование отклоняется
### Requirement: Хранение пользовательских настроек интерфейса ### Requirement: Хранение пользовательских настроек интерфейса
Система SHALL хранить настройки отображения в профиле пользователя и SHALL возвращать их при Система SHALL хранить пользовательские настройки (отображение интерфейса и пресеты кривой) в профиле пользователя и SHALL возвращать их при получении текущего пользователя. Настройки SHALL быть приватными для пользователя. Отсутствие настроек SHALL трактоваться как значения по умолчанию. Сохранение одного раздела настроек SHALL не затирать остальные разделы.
получении текущего пользователя. Настройки SHALL быть приватными для пользователя.
Отсутствие настроек SHALL трактоваться как значения по умолчанию.
#### Scenario: Получение настроек #### Scenario: Получение настроек
- **WHEN** аутентифицированный пользователь запрашивает свой профиль - **WHEN** аутентифицированный пользователь запрашивает свой профиль
- **THEN** ответ содержит его настройки отображения (или пустой объект по умолчанию) - **THEN** ответ содержит его настройки отображения и пресеты кривой (или пустой объект по умолчанию)
#### Scenario: Сохранение настроек #### Scenario: Сохранение настроек
- **WHEN** пользователь сохраняет настройки отображения - **WHEN** пользователь сохраняет настройки
- **THEN** система сохраняет их в профиле и возвращает сохранённое состояние - **THEN** система сохраняет их в профиле и возвращает сохранённое состояние
#### Scenario: Сохранение раздела не затирает другие
- **WHEN** пользователь сохраняет только один раздел настроек (например, сведения о фото или пресеты кривой)
- **THEN** остальные разделы профиля сохраняются без изменений
#### Scenario: Изоляция настроек #### Scenario: Изоляция настроек
- **WHEN** другой пользователь запрашивает свой профиль - **WHEN** другой пользователь запрашивает свой профиль
- **THEN** он не получает настройки первого пользователя - **THEN** он не получает настройки первого пользователя
+5 -3
View File
@@ -54,7 +54,9 @@ edit_preview.
объект; перенос и копирование SHALL изменять только ссылки и SHALL не изменять объект; перенос и копирование SHALL изменять только ссылки и SHALL не изменять
объекты хранилища. Отредактированная версия SHALL создаваться и привязываться только объекты хранилища. Отредактированная версия SHALL создаваться и привязываться только
к тому фото, чьи правки её породили, в отличие от обычных вариантов, которые к тому фото, чьи правки её породили, в отличие от обычных вариантов, которые
разделяются копиями того же оригинала. разделяются копиями того же оригинала. Копирование SHALL NOT переносить
отредактированную версию на копию: копия фото с правками SHALL показываться в исходном
виде и SHALL NOT наследовать параметры правок.
#### Scenario: Копирование #### Scenario: Копирование
- **WHEN** пользователь копирует фото в другой альбом - **WHEN** пользователь копирует фото в другой альбом
@@ -71,8 +73,8 @@ edit_preview.
#### Scenario: Копия отредактированного фото #### Scenario: Копия отредактированного фото
- **WHEN** фото с уже отрендеренной отредактированной версией копируют в другой альбом - **WHEN** фото с уже отрендеренной отредактированной версией копируют в другой альбом
- **THEN** копия разделяет те же объекты, включая отредактированные, но не наследует - **THEN** копия не получает отредактированные объекты, показывается в исходном виде и
параметры правок не наследует параметры правок
### Requirement: Сборка мусора по ссылкам ### Requirement: Сборка мусора по ссылкам
Объект хранилища SHALL удаляться только когда на него не ссылается ни одно фото и ни один Объект хранилища SHALL удаляться только когда на него не ссылается ни одно фото и ни один
+292 -9
View File
@@ -283,16 +283,10 @@ SHALL быть доступно и для фото без альбома (нап
- **THEN** контрольные суммы входят в данные полученных фото - **THEN** контрольные суммы входят в данные полученных фото
### Requirement: Неразрушающее редактирование фотографии ### Requirement: Неразрушающее редактирование фотографии
Система SHALL поддерживать неразрушающее редактирование фотографий. Параметры правок Система SHALL поддерживать неразрушающее редактирование фотографий. Параметры правок (свет, цвет и эффекты) SHALL храниться в метаданных фото, а отредактированная версия SHALL создаваться как отдельные объекты (роли `edit`, `edit_thumb`, `edit_medium`, `edit_preview`) рядом с исходными вариантами. Рендер SHALL выполняться по исходному объекту фото, а не по его уменьшенным вариантам. Исходный объект SHALL оставаться неизменным, а скачивание SHALL отдавать оригинал. Сброс правок SHALL удалять и параметры, и отредактированную версию. Правки SHALL применяться только к изображениям.
SHALL храниться в метаданных фото, а отредактированная версия SHALL создаваться как
отдельные объекты (роли `edit`, `edit_thumb`, `edit_medium`, `edit_preview`) рядом с
исходными вариантами. Рендер SHALL выполняться по исходному объекту фото, а не по
его уменьшенным вариантам. Исходный объект SHALL оставаться неизменным, а скачивание
SHALL отдавать оригинал. Сброс правок SHALL удалять и параметры, и отредактированную
версию. Правки SHALL применять только к изображениям.
#### Scenario: Сохранение правок #### Scenario: Сохранение правок
- **WHEN** пользователь сохраняет правки фото - **WHEN** пользователь сохраняет правки фото (свет, цвет и/или эффекты)
- **THEN** параметры сохраняются в метаданных, отредактированная версия рендерится в фоне, а после рендера фото получает URL отредактированных вариантов - **THEN** параметры сохраняются в метаданных, отредактированная версия рендерится в фоне, а после рендера фото получает URL отредактированных вариантов
#### Scenario: Фоновая подготовка версий #### Scenario: Фоновая подготовка версий
@@ -301,7 +295,7 @@ SHALL отдавать оригинал. Сброс правок SHALL удал
#### Scenario: Рендер по оригиналу #### Scenario: Рендер по оригиналу
- **WHEN** готовится отредактированная версия фото - **WHEN** готовится отредактированная версия фото
- **THEN** правки применяются к пикселям исходного объекта, а не к его уменьшенной копии - **THEN** световые и цветовые правки, а также эффекты применяются к пикселям исходного объекта, а не к его уменьшенной копии
#### Scenario: Неразрушачность #### Scenario: Неразрушачность
- **WHEN** фото отредактировано - **WHEN** фото отредактировано
@@ -318,3 +312,292 @@ SHALL отдавать оригинал. Сброс правок SHALL удал
#### Scenario: Редактирование видео #### Scenario: Редактирование видео
- **WHEN** пользователь пытается отредактировать видео - **WHEN** пользователь пытается отредактировать видео
- **THEN** система отклоняет запрос - **THEN** система отклоняет запрос
#### Scenario: Цветовые правки сохраняются и рендерятся
- **WHEN** пользователь сохраняет цветовые правки фото: баланс белого (температура/оттенок), сочность (vibrance), насыщенность, цветовой микшер по оттенкам, цветокоррекцию (тени/средние тона/света, яркость зон, наложение, баланс) или поканальную коррекцию
- **THEN** параметры цвета сохраняются в метаданных, отредактированная версия рендерится в фоне, а после рендера фото получает URL отредактированных вариантов
#### Scenario: Цветовые правки применяются к пикселям исходного объекта
- **WHEN** готовится отредактированная версия фото с цветовыми правками
- **THEN** цветовые правки применяются к пикселям исходного объекта после световых правок, а не к его уменьшенной копии
#### Scenario: Пустые цветовые правки не сохраняются
- **WHEN** в цветовых параметрах заданы только наложение/баланс или оттенок колеса без силы и яркости
- **THEN** правки считаются пустыми и фото не получает цветовую версию
#### Scenario: Пустые правки эффектов не сохраняются
- **WHEN** во всех эффектах заданы только значения по умолчанию (сила эффекта, виньетки и зерна равна нулю)
- **THEN** правки считаются пустыми и фото не получает новую отредактированную версию
### Requirement: Признак незавершённого рендера правок
Фото в ответах API и в событиях `photo.updated` SHALL содержать булево поле `edit_pending`. Оно SHALL быть `true`, пока серверный рендер сохранённых правок не завершён, и `false`, когда рендера нет или он завершён. Пока `edit_pending` равно `true`, URL отредактированных вариантов SHALL NOT считаться актуальными, даже если они присутствуют. Поле SHALL быть аддитивным: клиент, который его не читает, продолжает работать как раньше.
#### Scenario: Сохранение правок
- **WHEN** правки фото сохранены, а серверный рендер ещё не завершён
- **THEN** ответ на сохранение и событие `photo.updated` содержат `edit_pending=true`
#### Scenario: Предыдущий рендер устарел
- **WHEN** у фото уже есть отрендеренная версия, а для новых сохранённых правок рендер ещё не завершён
- **THEN** фото содержит `edit_pending=true`, а URL отредактированных вариантов не выдаются за актуальные
#### Scenario: Готовность рендера
- **WHEN** серверный рендер сохранённых правок завершён
- **THEN** `edit_pending=false`, а URL отредактированных вариантов соответствуют сохранённым правкам
#### Scenario: Сброс правок
- **WHEN** правки фото сброшены
- **THEN** `edit_pending=false` и URL отредактированных вариантов отсутствуют
### Requirement: Пипетка баланса белого
Клиент SHALL позволять выбрать нейтральную точку на фото и SHALL устанавливать температуру и оттенок так, чтобы цвет этой точки стал нейтральным. Выборка SHALL браться из исходного (неотредактированного) превью, а пресет баланса белого SHALL переходить в «Пользовательский».
#### Scenario: Выбор нейтральной точки
- **WHEN** пользователь включает пипетку и кликает по нейтральному участку фото
- **THEN** температура и оттенок обновляются, и цвет выбранной точки становится нейтральным
#### Scenario: Пипетка доступна только в просмотрщике
- **WHEN** фото не открыто в просмотрщике
- **THEN** пипетка недоступна
### Requirement: Живой предпросмотр цветовых правок
Клиент SHALL показывать результат цветовых правок в просмотрщике до завершения серверного рендера. Пока серверный рендер сохранённых правок не завершён (`edit_pending`) или пока локальные правки не сохранены, клиент SHALL показывать клиентский предпросмотр поверх исходной версии. После завершения рендера SHALL показываться серверная версия.
#### Scenario: Правки видны сразу
- **WHEN** пользователь двигает цветовой контрол
- **THEN** просмотрщик обновляет изображение без ожидания серверного рендера
#### Scenario: Серверная версия заменяет предпросмотр
- **WHEN** серверный рендер цветовых правок завершён
- **THEN** просмотрщик показывает отрендеренную версию
#### Scenario: Бесшовная подмена предпросмотра
- **WHEN** серверный рендер завершён, но новое изображение ещё загружается
- **THEN** просмотрщик продолжает показывать предпросмотр и не показывает оригинал или предыдущую отрендеренную версию
### Requirement: Тоновая кривая
Тоновая кривая SHALL задаваться контрольными точками для каналов RGB, R, G и B. Крайние точки SHALL существовать по умолчанию, SHALL двигаться по обеим осям и SHALL задавать плоские участки вне себя. Кривая SHALL быть плавной и монотонной между точками; первый клик по полю SHALL добавлять точку между крайними. Сброс SHALL возвращать линейную кривую.
#### Scenario: Крайние узлы существуют с самого начала
- **WHEN** пользователь открывает инструмент «Кривая»
- **THEN** у каждого канала уже есть крайние точки, и их можно перетаскивать
#### Scenario: Добавление точки
- **WHEN** пользователь кликает по свободному полю кривой
- **THEN** между крайними точками добавляется новая точка, а крайние остаются на месте
#### Scenario: Подвижные крайние узлы
- **WHEN** пользователь двигает крайнюю точку по x или y
- **THEN** вне крайних точек кривая остаётся плоской, а между точками — плавной
#### Scenario: Плавная интерполяция
- **WHEN** кривая сохранена и отрендерена
- **THEN** предпросмотр и итоговое фото используют одну и ту же плавную монотонную кривую
#### Scenario: Встроенные пресеты
- **WHEN** пользователь выбирает «Линейный», «Средний контраст» или «Сильный контраст»
- **THEN** кривые всех четырёх каналов заменяются кривыми пресета (контраст — в RGB, R/G/B — линейные), а подпись показывает выбранный пресет
#### Scenario: Пользовательская правка
- **WHEN** пользователь вручную меняет точки кривой
- **THEN** подпись показывает «Пользовательский»
#### Scenario: Сброс
- **WHEN** пользователь сбрасывает кривую
- **THEN** текущий канал возвращается к линейной кривой с крайними точками
#### Scenario: Независимые каналы
- **WHEN** пользователь выбирает канал R, G или B
- **THEN** он меняет только выбранный канал, остальные каналы остаются прежними
### Requirement: Переключение фото в редакторе
При переключении фото правая панель SHALL сохранять выбранную вкладку. Несохранённые правки SHALL сохраняться тому фото, для которого они сделаны, в том числе если пользователь уже переключился на другое фото. Ответы фоновых запросов SHALL NOT подменять текущее фото или его параметры.
#### Scenario: Вкладка не меняется
- **WHEN** пользователь переключает фото
- **THEN** выбранная вкладка правой панели остаётся прежней
#### Scenario: Правки уходят текущему фото
- **WHEN** пользователь меняет настройки после переключения
- **THEN** изменения сохраняются текущему фото, а не предыдущему
#### Scenario: Фоновое сохранение не подменяет фото
- **WHEN** сохранение предыдущего фото завершается после переключения
- **THEN** панель продолжает показывать текущее фото, а его параметры не меняются
### Requirement: Пользовательские пресеты кривой
Пользователь SHALL сохранять текущие кривые всех каналов (RGB, R, G и B) как именованный пресет, применять, переименовывать и удалять его. Пресет SHALL содержать кривую для каждого из четырёх каналов. Пресеты SHALL храниться в профиле пользователя и SHALL быть приватными. Импорт и экспорт SHALL выполняться JSON-файлом; импорт SHALL добавлять пресеты в профиль.
#### Scenario: Сохранение пресета
- **WHEN** пользователь сохраняет текущие кривые под именем
- **THEN** пресет появляется в списке и сохраняется в профиле вместе с кривыми RGB, R, G и B
#### Scenario: Применение пресета
- **WHEN** пользователь выбирает пользовательский пресет
- **THEN** кривые всех четырёх каналов заменяются сохранёнными, а текущий канал не меняется
#### Scenario: Переименование и удаление
- **WHEN** пользователь переименовывает или удаляет пресет
- **THEN** список пресетов и профиль обновляются
#### Scenario: Приватность пресетов
- **WHEN** другой пользователь открывает свои пресеты
- **THEN** он не видит пресеты первого пользователя
#### Scenario: Экспорт пресетов
- **WHEN** пользователь экспортирует пресеты
- **THEN** он получает JSON-файл с пользовательскими пресетами и кривыми всех четырёх каналов
#### Scenario: Импорт пресетов
- **WHEN** пользователь импортирует корректный JSON-файл
- **THEN** пресеты добавляются или обновляются в его профиле
#### Scenario: Некорректный файл или пресет
- **WHEN** имя или кривая хотя бы одного канала недопустимы
- **THEN** система отклоняет пресет и не меняет профиль
### Requirement: Текстура
Клиент SHALL позволять настраивать текстуру фото в диапазоне -100..100. Положительные значения SHALL усиливать контраст мелких деталей, отрицательные — ослаблять его. Эффект SHALL применяться к исходному кадру после световых и цветовых правок.
#### Scenario: Усиление текстуры
- **WHEN** пользователь увеличивает значение текстуры
- **THEN** мелкие детали становятся контрастнее, а общая тональность кадра не меняется
#### Scenario: Ослабление текстуры
- **WHEN** пользователь уменьшает значение текстуры ниже нуля
- **THEN** мелкие детали сглаживаются
#### Scenario: Текстура в пределах допустимого
- **WHEN** клиент присылает значение текстуры вне диапазона -100..100
- **THEN** сервер ограничивает его ближайшей границей диапазона
### Requirement: Чёткость
Клиент SHALL позволять настраивать чёткость фото в диапазоне -100..100. Положительные значения SHALL усиливать локальный контраст средних частот, отрицательные — смягчать его. Чёткость SHALL NOT создавать заметных ореолов на границах контрастных объектов. Эффект SHALL применяться после световых и цветовых правок.
#### Scenario: Усиление чёткости
- **WHEN** пользователь увеличивает значение чёткости
- **THEN** локальный контраст средних тонов растёт, а границы контрастных объектов остаются без заметных ореолов
#### Scenario: Ослабление чёткости
- **WHEN** пользователь уменьшает значение чёткости ниже нуля
- **THEN** изображение становится мягче
### Requirement: Убрать дымку
Клиент SHALL позволять ослаблять или усиливать дымку в диапазоне -100..100. При положительных значениях сервер SHALL оценивать дымку по кадру и возвращать контраст и насыщенность удалённых участков; отрицательные значения SHALL добавлять дымку.
#### Scenario: Удаление дымки
- **WHEN** пользователь увеличивает значение «Убрать дымку» на кадре с дымкой
- **THEN** дальние планы становятся контрастнее и насыщеннее
#### Scenario: Добавление дымки
- **WHEN** пользователь уменьшает значение «Убрать дымку» ниже нуля
- **THEN** кадр становится менее контрастным, как при дымке
### Requirement: Виньетка
Клиент SHALL позволять настраивать виньетку: силу -100..100, среднюю точку и растушёвку 0..100 (по умолчанию 50), округлость -100..100, света 0..100, а также режим «Свет», «Цвет» или «Закарасить». Режим «Свет» SHALL затемнять или осветлять края, «Цвет» — тонировать их выбранным цветом с сохранением светлоты, «Закарасить» — заливать их выбранным цветом.
#### Scenario: Затемнение краёв
- **WHEN** пользователь задаёт положительную силу виньетки в режиме «Свет»
- **THEN** края кадра затемняются, а центр остаётся без изменений
#### Scenario: Осветление краёв
- **WHEN** пользователь задаёт отрицательную силу виньетки в режиме «Свет»
- **THEN** края кадра осветляются
#### Scenario: Цветная виньетка
- **WHEN** пользователь выбирает режим «Цвет» или «Закарасить» и задаёт цвет виньетки
- **THEN** края кадра тонируются или заливаются этим цветом с силой, заданной ползунком виньетки
#### Scenario: Геометрия виньетки
- **WHEN** пользователь меняет среднюю точку, растушёвку или округлость
- **THEN** меняются размер, мягкость и форма зоны виньетки
#### Scenario: Защита светов
- **WHEN** пользователь увеличивает значение «Света» в режиме «Свет»
- **THEN** яркие участки в зоне виньетки сохраняют яркость
#### Scenario: Нулевая сила виньетки
- **WHEN** сила виньетки равна нулю
- **THEN** виньетка не влияет на изображение независимо от остальных параметров
### Requirement: Зерно
Клиент SHALL позволять добавлять зерно с силой, размером и шероховатостью в диапазоне 0..100 (по умолчанию размер 25, шероховатость 50). Зерно SHALL быть детерминированным: повторный рендер одних и тех же параметров SHALL давать одинаковый шум.
#### Scenario: Добавление зерна
- **WHEN** пользователь увеличивает силу зерна
- **THEN** на изображении появляется шум, заметный в средних тонах
#### Scenario: Размер и шероховатость
- **WHEN** пользователь меняет размер или шероховатость зерна
- **THEN** меняются крупность и контрастность шума
#### Scenario: Детерминированность зерна
- **WHEN** сервер повторно рендерит фото с теми же параметрами зерна
- **THEN** рисунок шума совпадает с предыдущим рендером
#### Scenario: Нулевая сила зерна
- **WHEN** сила зерна равна нулю
- **THEN** зерно не влияет на изображение
### Requirement: Живой предпросмотр эффектов
Клиент SHALL показывать эффекты в просмотрщике до завершения серверного рендера. Пока серверный рендер сохранённых правок не завершён (`edit_pending`) или локальные правки не сохранены, клиент SHALL показывать клиентский предпросмотр поверх исходной версии. После готовности клиент SHALL показывать серверную версию, не показывая в промежутке оригинал или предыдущую версию. Предпросмотр пространственных эффектов MAY отличаться от серверного рендера деталями, но SHALL передавать характер эффекта.
#### Scenario: Эффекты видны сразу
- **WHEN** пользователь двигает ползунок эффекта
- **THEN** просмотрщик обновляет изображение без ожидания серверного рендера
#### Scenario: Серверная версия заменяет предпросмотр
- **WHEN** серверный рендер эффектов завершён
- **THEN** просмотрщик показывает серверную версию
#### Scenario: Бесшовная подмена предпросмотра
- **WHEN** серверный рендер эффектов завершён, но новое изображение ещё загружается
- **THEN** просмотрщик продолжает показывать предпросмотр и не показывает оригинал или предыдущую отрендеренную версию
#### Scenario: Предпросмотр без WebGL
- **WHEN** аппаратное ускорение недоступно
- **THEN** клиент показывает эффекты доступным способом или показывает их после серверного рендера, не блокируя интерфейс
### Requirement: Мгновенный показ сброса правок
Клиент SHALL показывать исходный вид фото сразу после возврата контролов редактора в значения по умолчанию или нажатия сброса, не дожидаясь отложенного сохранения на сервер. Пока сброс, выполненный возвратом контролов, ещё не отправлен, просмотрщик SHALL NOT показывать отредактированную версию фото.
#### Scenario: Сброс возвратом контролов
- **WHEN** пользователь возвращает контролы редактора в значения по умолчанию (двойной клик по ползунку, шкала в нуле)
- **THEN** просмотрщик сразу показывает исходный вид, не дожидаясь срабатывания отложенного сохранения
#### Scenario: Сброс кнопкой
- **WHEN** пользователь нажимает «Сброс»
- **THEN** просмотрщик показывает исходный вид не позже ответа на запрос сброса
#### Scenario: Сброс при готовом рендере
- **WHEN** сброс выполнен, а отредактированная версия ещё существует на сервере
- **THEN** просмотрщик показывает исходный вид, а не отредактированную версию
### Requirement: Свёрнутые секции редактора
Редактор SHALL показывать все сворачиваемые секции инструментов свёрнутыми по умолчанию. Клиент SHALL сохранять состояние каждой секции (свёрнута или развёрнута) в браузере пользователя и восстанавливать его при повторном открытии редактора и перезагрузке страницы. Состояние SHALL NOT зависеть от выбранного фото.
#### Scenario: Первое открытие редактора
- **WHEN** пользователь впервые открывает редактор фото
- **THEN** все секции инструментов («Свет», «Цвет», «Эффекты» и их вложенные блоки) свёрнуты
#### Scenario: Состояние запоминается
- **WHEN** пользователь разворачивает секцию «Эффекты» и перезагружает страницу
- **THEN** секция «Эффекты» остаётся развёрнутой
#### Scenario: Состояние переживает смену фото
- **WHEN** пользователь переключает фото в редакторе
- **THEN** свёрнутость секций не меняется
### Requirement: Редактирование только из просмотрщика
Клиент SHALL показывать вкладку «Редактирование» только когда фото открыто в просмотрщике. В режиме сетки правая панель SHALL показывать только «Сведения» и SHALL NOT отображать инструменты редактирования.
#### Scenario: Фото выбрано в сетке
- **WHEN** пользователь выбирает фото в сетке, не открывая просмотрщик
- **THEN** в правой панели отображается только вкладка «Сведения»
#### Scenario: Фото открыто в просмотрщике
- **WHEN** пользователь открывает фото в просмотрщике
- **THEN** в правой панели доступны «Сведения» и «Редактирование»
#### Scenario: Возврат из просмотрщика в сетку
- **WHEN** пользователь возвращается из просмотрщика в сетку
- **THEN** вкладка «Редактирование» скрыта, панель показывает «Сведения»
+15 -1
View File
@@ -17,7 +17,9 @@
Система SHALL публиковать события photo.created, photo.updated, photo.deleted, Система SHALL публиковать события photo.created, photo.updated, photo.deleted,
comment.created, like.added, like.removed, member.joined, member.left, album.updated. comment.created, like.added, like.removed, member.joined, member.left, album.updated.
Событие photo.created SHALL обозначать появление фото в альбоме, а готовность вариантов Событие photo.created SHALL обозначать появление фото в альбоме, а готовность вариантов
существующего фото SHALL публиковаться как photo.updated. существующего фото SHALL публиковаться как photo.updated. Сохранение, готовность и сброс
правок фото SHALL также публиковаться как photo.updated с признаком незавершённого
рендера правок (`edit_pending`).
#### Scenario: Новое фото #### Scenario: Новое фото
- **WHEN** в альбоме появляется фото - **WHEN** в альбоме появляется фото
@@ -27,6 +29,18 @@ comment.created, like.added, like.removed, member.joined, member.left, album.upd
- **WHEN** для существующего фото сгенерированы thumb и preview - **WHEN** для существующего фото сгенерированы thumb и preview
- **THEN** подписчики получают событие photo.updated с этим фото - **THEN** подписчики получают событие photo.updated с этим фото
#### Scenario: Сохранены правки фото
- **WHEN** пользователь сохраняет правки фото, а рендер ещё не завершён
- **THEN** подписчики получают событие photo.updated с `edit_pending=true`
#### Scenario: Рендер правок готов
- **WHEN** серверный рендер сохранённых правок завершён
- **THEN** подписчики получают событие photo.updated с `edit_pending=false` и URL отредактированных вариантов
#### Scenario: Правки фото сброшены
- **WHEN** правки фото сброшены
- **THEN** подписчики получают событие photo.updated с `edit_pending=false` и без URL отредактированных вариантов
### Requirement: Персональный поток ### Requirement: Персональный поток
Клиент SHALL иметь возможность подписаться на персональный поток (приглашения, уведомления, Клиент SHALL иметь возможность подписаться на персональный поток (приглашения, уведомления,
изменения его альбомов). изменения его альбомов).
@@ -0,0 +1,145 @@
# Описание релиза Galo — 23 октября 2026
**Версия:** `0.2.0`
**База релиза:** `0.1-alpha` (`723b19b`, 21 октября 2026) → `develop` (`9e39e3d`, 23 октября 2026)
**Объём:** 6 коммитов, 3 спецификации обновлены, 2 изменения реализованы
---
## Коротко о главном
1. **Инструмент «Цвет».** Баланс белого, вибрация и насыщенность, цветовой
микшер по восьми диапазонам оттенков, цветокоррекция по зонам яркости и
общая поканальная коррекция. Предпросмотр считает WebGL2, есть WASM/JS-фолбэк.
2. **Пресеты тоновой кривой.** Плавная монотонная кривая (PCHIP), подвижные
крайние точки и плоские полки. Встроенные и пользовательские пресеты всех
четырёх каналов хранятся в профиле, импортируются и экспортируются JSON-файлом.
3. **Настройки профиля больше не затирают друг друга.** Сохранение сведений о фото
и пресетов кривой мержится на сервере по разделам.
4. **Исправлено переключение фото в редакторе.** Вкладка правой панели сохраняется,
а несохранённые правки уходят тому фото, для которого сделаны.
---
## Новые возможности
### Инструмент «Цвет»
- **Баланс белого:** температура и оттенок, пипетка по нейтральной точке на фото.
- **Вибрация и насыщенность** с раздельными ползунками.
- **Цветовой микшер** по восьми диапазонам (красный, оранжевый, жёлтый, зелёный,
бирюзовый, синий, фиолетовый, пурпурный): тон, насыщенность и яркость каждого
диапазона.
- **Цветокоррекция по зонам:** колёса теней, средних тонов и светов, наложение и
баланс зон.
- **Поканальная коррекция** красного, зелёного и синего каналов.
- **Живой предпросмотр на WebGL2:** кадр считает GPU, поэтому изменения видны сразу.
Если WebGL2 недоступен, используется WASM/JS-фолбэк с тем же результатом.
- Ползунки с градиентами, цветовые колёса и сброс значения двойным кликом.
- Порядок операций совпадает в Go-рендере, WASM и JS-предпросмотре; паритет
закреплён тестами.
### Тоновая кривая и пресеты
- **Плавная кривая:** монотонная кубическая интерполяция (PCHIP) вместо прямых
отрезков — и в SVG-графике, и в LUT для предпросмотра и серверного рендера.
- **Крайние точки** `(0,0)` и `(1,1)` существуют сразу, двигаются по обеим осям;
вне крайних точек кривая остаётся плоской. Первый клик по полю вставляет точку
между крайними.
- **Встроенные пресеты:** «Линейный», «Средний контраст», «Сильный контраст».
Контраст задаётся в RGB, каналы R/G/B остаются линейными.
- **Пользовательские пресеты** описывают кривые всех четырёх каналов:
- сохранение, применение, переименование и удаление;
- хранение в `users.preferences.curve_presets` в профиле пользователя;
- приватность: чужие пресеты не видны;
- импорт и экспорт JSON `{ "version": 1, "presets": [...] }`, upsert по имени;
- старый формат одного канала конвертируется при чтении.
- Подпись показывает активный пресет; при ручной правке любого канала —
«Пользовательский». Сброс возвращает линейную кривую.
### Настройки профиля
- `PATCH /api/auth/me/preferences` теперь **мержит** разделы, а не заменяет весь
JSON-объект.
- Сохранение `photo_info` не стирает `curve_presets`, и наоборот.
- Валидация: не больше 100 пресетов, имя 1..64 символа, 2..16 точек на каждый из
четырёх каналов, `x/y` в диапазоне 0..1.
- Неизвестные разделы настроек сохраняются без изменений.
---
## Исправления
- **Переключение фото в редакторе.** Вкладка правой панели больше не сбрасывается
на «Сведения». Накопленные правки отправляются фото, для которого сделаны, даже
если пользователь уже перешёл к следующему.
- **Фоновые сохранения не подменяют текущее фото.** Устаревшие ответы сохранения и
загрузки игнорируются; панель показывает только фото текущего маршрута.
- **Копия фото не наследует отредактированную версию.** Копия показывает исходник,
правка принадлежит своему фото (архивная синхронизация спецификации
`media-objects`).
- Устранены ошибки доступа к `photo = null` при кратковременной смене фото.
---
## Технические изменения
### API
- `PATCH /api/auth/me/preferences` — мерж известных разделов; в ответе возвращается
полный объединённый объект.
- `PATCH /api/photos/:id/edit` — параметры правок теперь включают блок `color` и
тоновую кривую; серверный рендер использует те же LUT, что и предпросмотр.
- `DELETE /api/photos/:id/edit` — сброс правок без изменений.
### Данные и миграции
- Схема БД не менялась: новые настройки лежат в JSON-блобе
`users.preferences`; параметры правок — в `photos.edit_params`.
- Новые роли объектов и миграции не добавлялись.
- Старые сохранённые кривые начнут интерполироваться плавно — визуальный результат
может немного измениться без миграции данных.
### Сборка
- Обновлён WASM-модуль фильтров (`frontend/static/light.wasm`).
- `make build-release` собирает статический бинарник с вшитой версией и сжимает
его UPX, если UPX доступен.
- Версия берётся из `git describe --tags`; релизный тег — `0.2.0`.
### Проверка
- `npm run check` — 0 ошибок и предупреждений.
- `npm run test` — 54 теста.
- `go test ./...` — все пакеты зелёные.
- E2E: сохранение/сброс цветовых правок, приватность и хранение пресетов кривой.
- Проверено в браузере: WebGL2-предпросмотр, пипетка, меню пресетов, сохранение
всех каналов, сохранение вкладки и правок при переключении фото.
---
## Как обновиться
1. Собрать релизный бинарник: `make build-release` (или взять готовый
`bin/galo-0.2.0`).
2. Остановить сервис и заменить бинарник. Фронтенд вшит в бинарник.
3. Запустить сервис: миграции применяются автоматически при старте для выбранного
бэкенда. Для этого релиза отдельных миграций нет.
4. Для видео по-прежнему нужны `ffmpeg`/`ffprobe` на хосте.
5. Android-клиент обновляется отдельно через `make install-android-app`.
Откат: вернуть предыдущий бинарник. Схема не менялась, данные правок и профиля
остаются совместимыми; новые ключи настроек старый бинарник просто игнорирует.
---
## Ограничения
- Редактирование цвета и кривой доступно только для изображений; видео не
редактируется.
- WebGL2-предпросмотр ускоряет отрисовку, но при его отсутствии используется
WASM/JS-фолбэк.
- Пресеты не синхронизируются между пользователями: перенос возможен только через
экспорт/импорт JSON.
- Правки не создают отдельной записи в истории: параметры хранятся в метаданных
фото, отредактированная версия — отдельный объект.