Files
supabase/apps/studio/state/sql-editor/sql-editor-lifecycle.ts
T
Charis 16526bd6bf refactor(studio): extract SQL editor save mechanism + model folder lifecycle (4/9) (#47276)
## What

PR 4 of a stacked refactor of the SQL editor snippet/folder state. It
pulls the persistence logic out of the store into an injectable
mechanism, and replaces the folder `'new-folder'` id sentinel with an
explicit lifecycle — plus a concurrency bug fix that surfaced along the
way.

### Save mechanism (`sql-editor-save.ts`)

`createSaveMechanism({ state, upsertContent, createSQLSnippetFolder,
updateSQLSnippetFolder, invalidate, notify, debounceMs })` → `{
saveSnippet, createFolder, updateFolder }`. The store's subscribe now
dispatches to it; *when* to save still lives in the subscribe (the
scheduler/provider move is PR 5). Per-id debounce cache lives in the
factory closure (no module-global leak).

- **`saveSnippet`** reads the live store snippet, guards
`isLoadedSnippet` so a content-less snippet can **never PUT an empty
body** (directly unit-tested), then builds the payload + drives status
transitions + gated invalidation.
- **`toast` is injected** as a `Notifier` (new generic DI contract in
`lib/notifier.ts`) — the mechanism no longer imports sonner.
- **create vs rename are two named-arg functions**, not an `isNew`
branch; rollback is deterministic per operation instead of matching on
`error.message` text.
- **caught errors are `unknown`**, narrowed via the existing
`getErrorMessage` util with a generic fallback — no `any`.

### Folder lifecycle (replaces the `NEW_FOLDER_ID` sentinel)

- **`FolderStatus`** enum (`new_editing | new_saving | editing | saving
| idle`) collapses the persistence and progress axes into one enum —
same pattern as `SnippetStatus` — with `isNewFolder` / `isFolderEditing`
/ `isFolderSaving` predicates. Tagging a folder as new/persisted is now
an explicit field, not an id convention.
- New placeholders get a **unique local id** (`crypto.randomUUID`);
`NEW_FOLDER_ID` is deleted, which also lifts the accidental
one-unsaved-folder-at-a-time limit.

### Bug fix: folder-rename rollback race

The shared `lastUpdatedFolderName` field let two in-flight renames
clobber each other's rollback target (and a shared `finally` could wipe
it). Replaced by a **per-folder `previousName`** on
`StateSnippetFolder`, so concurrent renames of different folders are
isolated. A new test runs two failing renames concurrently and asserts
each restores its own previous name.

## Tests

`sql-editor-save.test.ts` (mechanism — fakes + fake timers, incl.
content-less no-PUT and concurrent-rename isolation) and
folder-lifecycle predicate tests. `pnpm --filter studio typecheck`
clean; 82 state/sql-editor unit tests pass.

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

* **New Features**
* Improved SQL editor folder handling with clearer create, rename, and
save states.
* Added a more consistent notification flow for successful and failed
save actions.

* **Bug Fixes**
* Improved rollback handling when folder renames fail, helping restore
the previous name reliably.
* Updated save behavior to better protect against duplicate or
out-of-order updates.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-06-25 11:08:26 -04:00

78 lines
3.1 KiB
TypeScript

import type { SnippetStatus } from '@/data/content/snippet-status'
/**
* True when the snippet has never been successfully written to the database.
* Gates content fetching and list invalidation, and marks locally-created
* snippets for the replication-lag 404 swallow in the `[id]` page.
*/
export function wasNeverPersisted(status: SnippetStatus | undefined): boolean {
return status === 'new' || status === 'new_saving' || status === 'new_save_failed'
}
/** True while a save request is in flight (whether first save or re-save). */
export function isSaving(status: SnippetStatus | undefined): boolean {
return status === 'new_saving' || status === 'saving'
}
/**
* True when the most recent save attempt failed (whether first save or
* re-save).
*/
export function isSaveFailed(status: SnippetStatus | undefined): boolean {
return status === 'new_save_failed' || status === 'save_failed'
}
/**
* Transition when a save request begins, preserving the never-persisted axis.
*/
export function statusOnSaveStart(status: SnippetStatus | undefined): SnippetStatus {
return wasNeverPersisted(status) ? 'new_saving' : 'saving'
}
/** Transition when a save succeeds — the snippet is now persisted and clean. */
export function statusOnSaveSuccess(): SnippetStatus {
return 'saved'
}
/** Transition when a save fails, preserving the never-persisted axis. */
export function statusOnSaveError(status: SnippetStatus | undefined): SnippetStatus {
return wasNeverPersisted(status) ? 'new_save_failed' : 'save_failed'
}
/**
* The lifecycle of a folder in the SQL editor nav, as a single set of
* mutually-exclusive states. Like SnippetStatus, this collapses two orthogonal
* axes — persistence (a locally-created placeholder vs a persisted folder) and
* progress (inline-name editing / save in flight / settled) — into one enum, so
* a folder can never be in a nonsensical combination (e.g. "new" yet "idle").
* The predicates below recover each axis.
*/
export type FolderStatus =
// Never persisted to the database (a locally-created placeholder):
| 'new_editing' // its name is being entered inline
| 'new_saving' // its create is in flight
// Persisted to the database:
| 'idle' // settled
| 'editing' // its name is being edited inline (rename)
| 'saving' // its rename is in flight
/** True for a locally-created placeholder folder that has not been persisted. */
export function isNewFolder(status: FolderStatus | undefined): boolean {
return status === 'new_editing' || status === 'new_saving'
}
/** True while the folder's name is being edited inline. */
export function isFolderEditing(status: FolderStatus | undefined): boolean {
return status === 'new_editing' || status === 'editing'
}
/** True while a folder create/rename is in flight. */
export function isFolderSaving(status: FolderStatus | undefined): boolean {
return status === 'new_saving' || status === 'saving'
}
/** Transition when a folder save begins, preserving the never-persisted axis. */
export function folderStatusOnSaveStart(status: FolderStatus): FolderStatus {
return isNewFolder(status) ? 'new_saving' : 'saving'
}