Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion openspec/ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@
| 42 | `42-editor-mesh-repair` | 41 | v1.13.0. Диагностика и ремонт STL, Decimate, Smooth, Lay on Face, измерения, анализ нависаний |
| 43 | `43-editor-cut-split` | 41, 42 | v1.14.0. Plane Cut, Split на стол с соединителями (шипы, штифты, магниты, ласточкин хвост), инструмент «Отверстие» (винты, вставки, магниты) и текст на грани |
| 44 | `44-editor-face-tools` | 41, 42 | v1.15.0. Режимы выбора граней/рёбер (распознавание по мешу), Push/Pull, Fillet/Chamfer прямых и круговых рёбер, эскиз на грани с проекцией рёбер (Hole wizard перенесён в 43) |
| 45 | `45-editor-project-default` | 43, 44 | v2.0.0 (план, major: `/` ведёт в редактор). Файл проекта `.pkit` (ZIP: scene.json + сетки), автосохранение, редактор — вход по умолчанию, генераторы как вставляемые объекты |
| 45 | `45-editor-project-default` | 43, 44 | v2.0.0 (major: `/` ведёт в редактор, выбор генераторов переезжает на `/generators`). Файл проекта `.pkit` (ZIP: scene.json + сетки), автосохранение, редактор — вход по умолчанию, генераторы как вставляемые объекты (Send to Editor / Edit in generator) |

```mermaid
gantt
Expand Down
2 changes: 2 additions & 0 deletions openspec/changes/45-editor-project-default/.openspec.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-10-27
37 changes: 37 additions & 0 deletions openspec/changes/45-editor-project-default/design.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# Design

## Context

`39` made the document a small JSON description plus content-addressed meshes in IndexedDB — deliberately in the shape a file needs. `EDITOR.md` fixes the `.pkit` layout. Desktop editors (Blender `.blend`, Fusion `.f3d`, Tinkercad's cloud) set the user's expectations: Ctrl+S, recent files, crash recovery.

## Goals / Non-Goals

**Goals**: a self-contained, versioned, validated file; no data loss on crashes; the editor as the natural landing page without breaking anything else.
**Non-Goals**: cloud, collaboration, other CAD formats.

## Decisions

1. **Container.** ZIP written and read with `fflate` (already used for 3MF). Entries: `meta.json` (`{format:'pkit', formatVersion, app, appVersion, name, created, modified}`), `scene.json` (the document: objects, stacks, sketches, cuts; schema number, lengths in mm), `meshes/<sha256>.bin` (little-endian: magic `PKM1`, vertex count, index count, Float32 positions, Uint32 indices; file name = hash of the payload so identical meshes are stored once and integrity is checkable), `sketches/` is part of `scene.json` (no separate files in v1), `thumb.png`. Compression: meshes stored with deflate level 6 (float data compresses poorly but index data well); `scene.json` level 9.
2. **Versioning.** `formatVersion` is an integer independent of the app version. `migratePkit(raw)` upgrades older `scene.json` layouts step by step (reusing `migrateScene` of the editor); a file with a higher `formatVersion` opens with a warning ("created by a newer version, some data may be dropped when saving") and unknown fields are preserved in `extra` and written back unchanged.
3. **Guards.** Maximum archive 1 GB and uncompressed total 2 GB, at most 5 000 entries, entry paths must match `^(meta\.json|scene\.json|thumb\.png|meshes/[0-9a-f]{64}\.bin)$`, no directory traversal, per-entry size limit 512 MB, mesh hash verified on load (mismatch → that object marked "mesh corrupted" and logged), JSON size limit 50 MB. Violations refuse the file with a message and change nothing. Opening never executes anything.
4. **Save.** `saveProject()` serialises the current document and the meshes referenced by it (and by `originMeshId`), builds the ZIP off the main thread (worker with progress job), then either writes through a stored `FileSystemFileHandle` (File System Access API: `showSaveFilePicker` on first save, handle kept in IndexedDB with permission re-request) or downloads `<name>.pkit`. The dirty flag clears after a successful write; Save As always asks. File name defaults to the project name (sanitised).
5. **Open.** `openProject(file)`: guards → hashes → `migratePkit` → replace the working document (after the unsaved-changes prompt) → register meshes in the mesh store → clear history → fit the camera. Drag-and-drop of a `.pkit` anywhere on the page opens it; dropping STL files while a project is open imports them (as in `39`). The Open dialog also accepts STL (routed to import) for convenience.
6. **Dirty state and prompts.** `dirty` = document changed since last save or open (history pointer vs saved pointer, so undoing back to the saved state clears it). `beforeunload` prompts only when dirty. New and Open ask to save, discard or cancel.
7. **Autosave.** After 2 s of idle following a change (max every 30 s under constant editing), a snapshot `{projectId, time, scene, meshIds}` is written to IndexedDB (`pkit-autosave`) with the meshes already in the mesh store (no duplication); ring of 3 snapshots per project, 10 projects, oldest evicted and unreferenced meshes collected. On startup, if a snapshot is newer than the last saved/open time of the project (or no project was saved), a banner offers Restore or Discard. A `BroadcastChannel` with a per-project lock detects a second tab editing the same project and shows a warning on the later tab (read-only banner with "Take over").
8. **Recent projects.** `pkit-recent` in IndexedDB: `{id, name, modified, thumbnail (PNG blob ≤ 40 KB), handle?}`; with a stored handle the project reopens in one click (permission prompt if needed), otherwise it opens the latest autosave snapshot of that project, otherwise the entry offers the Open dialog. Thumbnails come from the viewport (offscreen render at 256 px) at save time.
9. **Entry route.** Router: `/` → `EditorMode` with `StartOverlay` shown while the project is empty and "unstarted" (not dismissed); `/editor` redirects to `/`; `/generators` is the old `StartPage` product chooser; unknown paths go to `/`. `lastSession` records `editor`, `gridfinity`… as before; "Continue" on the overlay restores the last project (autosave or recent). Header: the logo links to `/`; the product switcher shows Editor and Generators entries; inside a generator the logo text keeps the active product. Tests cover the redirects and that every old deep link still resolves.
10. **Generator round trip.** Each generator mode exposes its parts (`ModelResult`) and parameters. *Send to Editor*: for every part a mesh object is created (mesh into the store, source `mesh` plus `origin: {product, mode, params, part}`), grouped under one name; the editor opens at `/`. *Edit in generator*: stores a handoff record in IndexedDB `{id, product, mode, params, objectIds}`, navigates to the generator route with `?handoff=<id>`, the mode initialises its state from the record and persists to `<key>.handoff` instead of the main key (a `persistKey` override in `usePersistedState`), and `HandoffBar` shows "Back to editor". On return the new parts replace the meshes of the object(s) by id in one history step (transform and stack kept; if the part count changed, extra objects are added and missing ones are removed with a note in the log). Cutout and Keychain image modes depend on stored files; they are supported only when their stores still hold the files (otherwise the button is disabled with the reason).
11. **Compatibility.** No storage key changes. The previous `/` page content moves unchanged to `/generators`. The README and the beta notice mention the editor. The version is 2.0.0 per the semantic-versioning rule (moved route).

## Risks / Trade-offs

- **File System Access API** exists only in Chromium; other browsers fall back to downloads with no in-place save. The UI says which mode is active and the download path is always tested.
- **Large projects** (hundreds of MB of meshes) make save and autosave slow; saves run in a worker with progress, autosave is incremental because meshes are content-addressed and already stored.
- **Handoff complexity** (state under a separate key, return bar) touches every generator mode; implemented once in a shared hook and covered by a test per mode.
- **Behaviour change of `/`.** Users with the old bookmark see the editor; mitigated by the generators row on the start overlay and by keeping all deep links.
- **Autosave privacy**: snapshots stay in the browser; a "Clear local data" action in the project menu lists what is stored and removes it.

## Open Questions

- Whether the start overlay should show on every visit with an empty project or only the first time (assumed: whenever the scene is empty).
- Whether the thumbnails should be taken with a fixed camera (assumed: current camera, fit to scene).
30 changes: 30 additions & 0 deletions openspec/changes/45-editor-project-default/proposal.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# Proposal

## Why

The editor of `39`–`44` keeps its scene in the browser's storage: it survives a reload but cannot be moved to another computer, shared, versioned or backed up, and one cleared site-data setting loses everything. A real editor has a project file. It also still sits behind a chooser page as one of four products, although it is meant to be the main mode (`openspec/EDITOR.md`). This change closes the series: the `.pkit` project file, safe autosave and recovery, and making the editor the entry point of the site, with the generators reachable as a section and as sources of objects for the editor.

## What Changes

- **`.pkit` project files.** Save (download, or in place where the browser supports the File System Access API), Save As, Open (dialog and drag-and-drop anywhere on the page), New. The file is a ZIP (`scene.json`, `meshes/<hash>.bin`, `sketches/`, `thumb.png`, `meta.json`, format in `openspec/EDITOR.md`), with format versioning, migration of older files, a warning for newer ones, size and path guards, and hash verification of the meshes. A dirty marker in the header, a leave-page prompt when there are unsaved changes, project name editable in the header.
- **Autosave and recovery.** The working document is autosaved to IndexedDB shortly after each change (debounced) as the last three snapshots; after a crash or a closed tab the editor offers to restore the newest snapshot that is newer than the last save. Two tabs editing the same project are detected and warned.
- **Editor as the entry point (major).** `/` opens the editor with a start overlay on an empty project: New, Open, Recent projects (thumbnail, name, date), Import STL, Continue the last project, and a row of the generator cards. The previous product chooser moves to `/generators`; generator routes (`/gridfinity/…`, `/keychain/…`, `/rack/…`) and every storage key stay as they are. The header logo and the product switcher are adjusted; the footer, beta notice and `README` follow.
- **Generators ↔ editor.** In every generator mode a **Send to Editor** button puts the current model parts into the editor scene as objects that remember their origin (`product`, `mode`, parameters), and in the editor an object with an origin gets **Edit in generator**: it opens the generator preloaded with those parameters, with a persistent "Back to editor" bar; on return the object's mesh is replaced and its transform and stack are kept. While in this round trip the generator state is held under a separate handoff key, so the user's own saved generator settings are not overwritten.
- **Housekeeping.** The `lastSession` record gains the editor; the start-page art for the Editor from `39` is used on the overlay; strings and README updated.

## Capabilities

### New Capabilities
- `editor-project-file`: `.pkit` format, save/open/new, versioning, guards, dirty state.
- `editor-autosave`: autosave snapshots, recovery, multi-tab warning, recent projects.
- `editor-default-entry`: new entry route, start overlay, `/generators`, generator round trip.

### Modified Capabilities

## Impact

- New `src/editor/project/{pkit,migrate,zip,hash,autosave,recent,fileAccess}.ts` (React-free where possible), `src/features/editor/{ProjectMenu,StartOverlay,RecentList,RestoreBanner,HandoffBar}`, changes in `app/routes.tsx`, `StartPage` (becomes the generators chooser), `Header`, `AppShell`, `lastSession.ts`, the generator modes (Send to Editor button, `persistKey` override for handoff), `README.md`, `CHANGELOG.md`, strings in en and ru, tests. Uses `fflate` (already a dependency).
- Stored settings stay compatible (no migration needed); routes: `/` changes meaning and the chooser moves to `/generators` — the reason for a major version. Old deep links `#/gridfinity/box` etc. keep working.
- Out of scope: cloud storage or accounts, sharing links, version history/branches of a project, merging files, embedding generator parameters as live links (the round trip replaces the mesh), WebMCP tools for the editor (a later extension of `38`), importing other CAD formats (STEP, 3MF project files of slicers), password protection.
- Version 2.0.0 (major: the route `/` now opens the editor and the product chooser moves to `/generators`).
- Depends on: `43-editor-cut-split` and `44-editor-face-tools` (the complete document: cuts, stacks, faces), in the linear order of the editor series.
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
# Spec Delta

## Purpose
Defines autosave, recovery, multi-tab protection and recent projects.

## ADDED Requirements

### Requirement: Autosave
The Editor SHALL save snapshots of the working document to browser storage shortly after changes, keeping the three newest per project.

#### Scenario: Idle after change
- **WHEN** the user stops editing for two seconds
- **THEN** a snapshot is written without blocking the interface

#### Scenario: Constant editing
- **WHEN** the user edits continuously for two minutes
- **THEN** snapshots are written at least every 30 seconds

#### Scenario: Storage unavailable
- **WHEN** browser storage cannot be used
- **THEN** a warning is shown once and editing continues

### Requirement: Recovery
After an unexpected close the Editor SHALL offer to restore the newest snapshot that is newer than the last saved file.

#### Scenario: Crash
- **WHEN** the tab is closed with unsaved work and the editor is opened again
- **THEN** a banner offers Restore or Discard, and Restore brings back the document

#### Scenario: Nothing newer
- **WHEN** the last snapshot is older than the last save
- **THEN** no banner is shown

### Requirement: Second tab
The Editor SHALL detect another tab editing the same project and warn before the second one changes it.

#### Scenario: Two tabs
- **WHEN** the same project is open in two tabs
- **THEN** the later tab shows a notice with a Take over action and editing there is blocked until chosen

### Requirement: Recent projects
The Editor SHALL list recent projects with name, date and thumbnail and reopen them in one click where possible.

#### Scenario: Reopen
- **WHEN** the user clicks a recent project that has a stored file handle
- **THEN** it opens, asking for file permission if required

#### Scenario: No handle
- **WHEN** a recent project has no handle
- **THEN** the latest autosave of it opens, or the Open dialog is offered if none exists

### Requirement: Local data control
The Editor SHALL show what it stores locally (snapshots, recent list, meshes) with sizes and allow clearing it.

#### Scenario: Clear
- **WHEN** the user clears local data
- **THEN** snapshots, recent entries and unreferenced meshes are removed after a confirmation, and the saved files on disk are untouched
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
# Spec Delta

## Purpose
Defines the editor as the entry point of the site, the generators section and the round trip between generators and the editor.

## ADDED Requirements

### Requirement: Editor at the site root
The site SHALL open the editor at `/`, show a start overlay while the project is empty, and keep the product chooser at `/generators`.

#### Scenario: First visit
- **WHEN** a visitor opens the site
- **THEN** the editor opens with the overlay offering New, Open, Recent, Import STL and the generator cards

#### Scenario: Generators
- **WHEN** the visitor opens `/generators`
- **THEN** the chooser of Gridfinity, Keychain and Rack is shown as before

#### Scenario: Old deep links
- **WHEN** a visitor opens `#/gridfinity/box`, `#/keychain/shape`, `#/rack/case` or `#/baseplate`
- **THEN** the same mode opens as before this change, with its stored settings

#### Scenario: Editor path
- **WHEN** a visitor opens `#/editor`
- **THEN** they are sent to `/`

### Requirement: Start overlay
The start overlay SHALL offer to continue the last project, start a new one, open a file, import STL files, open a recent project and go to a generator, and SHALL disappear as soon as the project has content or the user dismisses it.

#### Scenario: Continue
- **WHEN** a previous project exists
- **THEN** Continue restores it from the latest autosave or recent entry

#### Scenario: Import from overlay
- **WHEN** the user drops an STL on the overlay
- **THEN** it is imported and the overlay closes

### Requirement: Navigation
The header SHALL link the logo to the editor, list the Editor and Generators in the product switcher, and keep the generator mode switchers inside the generators.

#### Scenario: From a generator
- **WHEN** the user clicks the logo inside a generator
- **THEN** the editor opens and the generator's state is kept

### Requirement: Send to Editor
Each generator mode SHALL offer Send to Editor, which adds the model parts to the editor scene as objects that remember their generator, mode and parameters.

#### Scenario: Send a baseplate
- **WHEN** the user sends a 4 × 3 baseplate from the generator
- **THEN** the editor opens with an object of that shape on the bed, named after the mode

#### Scenario: Several parts
- **WHEN** the model has several parts
- **THEN** one object per part is created and grouped

#### Scenario: Unavailable
- **WHEN** the mode needs a file that is no longer stored (for example a Cutout mesh)
- **THEN** the button is disabled with the reason

### Requirement: Edit in generator
An editor object with a generator origin SHALL offer Edit in generator, which opens the generator with the object's parameters and a Back to editor bar, and on return replaces the object's mesh while keeping its transform and stack, without overwriting the user's own saved generator settings.

#### Scenario: Round trip
- **WHEN** the user edits a baseplate in the generator, changes its width and returns
- **THEN** the object has the new width at the same position and rotation, and later opening the generator directly shows the user's earlier saved settings

#### Scenario: Part count changed
- **WHEN** the edit changes the number of parts
- **THEN** extra objects are added or missing ones removed in one history step and the log notes it

#### Scenario: Cancel
- **WHEN** the user leaves through Back to editor without changes
- **THEN** the object is unchanged and no history step is added
Loading
Loading