Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

33.6 KB
Raw Blame
import {
    MakeLogicType,
    actions,
    afterMount,
    beforeUnmount,
    connect,
    kea,
    key,
    listeners,
    path,
    props,
    reducers,
    selectors,
} from 'kea'
import { beforeUnload } from 'kea-router'

import { CanvasDashboardActionType, captureCanvasAction } from '../canvasAnalytics'
import { canvasesPublishCreate, canvasesSourceRetrieve } from '../generated/api'
import type {
    CanvasApi,
    CanvasCapabilitiesApi,
    CanvasDiagnosticApi,
    CanvasSourceResponseApi,
    CanvasViewResponseApi,
} from '../generated/api.schemas'
import { canvasHistoryLogic } from '../history/canvasHistoryLogic'
import { canvasNewLogic } from '../newCanvas/canvasNewLogic'
import { canvasSceneLogic } from '../scene/canvasSceneLogic'
import { CanvasPanelTab } from '../sidePanel/canvasPanelTabs'
import { canvasSidePanelLogic } from '../sidePanel/canvasSidePanelLogic'
import { canvasChatLogic } from '../sidePanel/chat/canvasChatLogic'
import { BlockPropsRecord, blockDefinition, freshBlockProps } from './blockLibrary/blockDefinitions'
import { syncBlockLibrary } from './blockLibrary/blockLibrarySync'
import { CANVAS_ENTRY_PATH, canvasCapabilities } from './blockLibrary/blockProject'
import {
    SourceDropTarget,
    SourceFiles,
    SourceRange,
    blockRanges,
    duplicateRange,
    insertBlock,
    isJsxRange,
    moveRange,
    newBlockId,
    placeableTarget,
    removeRange,
    replaceElementText,
    updateBlockProps,
} from './blockLibrary/sourceEdits'
import {
    CanvasEditSelection,
    CanvasSourceEntry,
    applySourceFiles,
    describeChanges,
    isFreshRev,
    isRootSelection,
    isSourceDirty,
    loadSourceEntry,
    markSourceSaved,
    noteSourceChange,
    redoSourceEntry,
    resolveSourceConflict,
    setSourceConflict,
    setSourceMounted,
    setSourceSaving,
    undoSourceEntry,
} from './canvasSourceSnapshots'
import { analyticsBlockType, libraryLabel } from './libraryCatalog'
import type { SourceDragSource, SourceDropHit } from './sourceDrag'

// Matches PostHog Desktop: edits save shortly after the author stops, and the head is re-read
// while editing so a publish from elsewhere loads when there is nothing local to lose.
const SAVE_DEBOUNCE_MS = 700
const SOURCE_POLL_MS = 4_000

const SIDE_BY_SIDE_BLOCKS = new Set(['Metric', 'TopList', 'Funnel'])

export interface CanvasEditLogicProps {
    id: string
}

export interface CanvasEditKey {
    key: string
    metaKey: boolean
    ctrlKey: boolean
    shiftKey: boolean
}

export interface CanvasSaveStatus {
    saving: boolean
    dirty: boolean
    error: string | null
}

function besideSelection(selection: CanvasEditSelection, blockType: string): SourceDropTarget {
    const source = selection.source as SourceRange
    const pairs = selection.blockType === blockType && SIDE_BY_SIDE_BLOCKS.has(blockType)
    const grid = selection.layout.grid
    if (!pairs && grid) {
        return { ...grid, place: 'after' }
    }
    if (!pairs) {
        return { ...source, place: 'after' }
    }
    if (!selection.layout.inGrid) {
        return { ...source, place: 'right' }
    }
    const grow = selection.layout.grow
    return grow ? { ...source, place: 'after', grow } : { ...source, place: 'after' }
}

function saveErrorMessage(error: unknown): string {
    const data = (error as { data?: { detail?: string; diagnostics?: CanvasDiagnosticApi[] } } | null)?.data
    const diagnostic = data?.diagnostics?.find((item) => item.severity === 'error')
    if (diagnostic) {
        return diagnostic.path ? `${diagnostic.path}: ${diagnostic.message}` : diagnostic.message
    }
    return data?.detail || (error instanceof Error ? error.message : String(error))
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface canvasEditLogicValues {
    browseVersionId: string | null // canvasHistoryLogic
    editHandoff: string | null // canvasNewLogic
    canvas: CanvasApi | null // canvasSceneLogic
    currentProjectId: number | null // canvasSceneLogic
    isGenerating: boolean // canvasSceneLogic
    sandboxDocumentUrl: string | null // canvasSceneLogic
    view: CanvasViewResponseApi | null // canvasSceneLogic
    canRedoEdit: boolean
    canUndoEdit: boolean
    editUnavailableReason: string | null
    editing: boolean
    entry: CanvasSourceEntry | null
    finishAfterSave: boolean
    libraryOpen: boolean
    saveStatus: CanvasSaveStatus | null
    selection: CanvasEditSelection | null
    sourceEditing: boolean
    sourceError: string | null
    sourceLoading: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface canvasEditLogicActions {
    setDraft: (draft: string) => {
        draft: string
    } // canvasChatLogic
    setBrowseVersion: (versionId: string | null) => {
        versionId: string | null
    } // canvasHistoryLogic
    clearEditHandoff: () => {
        value: true
    } // canvasNewLogic
    loadBuilds: () => any // canvasSceneLogic
    loadView: () => any // canvasSceneLogic
    loadViewSuccess: (
        view: CanvasViewResponseApi | null,
        payload?: any
    ) => {
        payload?: any
        view: CanvasViewResponseApi | null
    } // canvasSceneLogic
    startPolling: () => {
        value: true
    } // canvasSceneLogic
    openTab: (
        tab: CanvasPanelTab,
        canvasId: string
    ) => {
        canvasId: string
        tab: CanvasPanelTab
    } // canvasSidePanelLogic
    setBlocksCanvasId: (canvasId: string | null) => {
        canvasId: string | null
    } // canvasSidePanelLogic
    switchTab: (tab: CanvasPanelTab) => {
        tab: CanvasPanelTab
    } // canvasSidePanelLogic
    addAfterSelection: (blockType: string) => {
        blockType: string
    }
    applyEdit: (
        files: SourceFiles,
        label: string,
        focusBlockId?: string | null,
        focusSource?: string | null
    ) => {
        files: SourceFiles
        focusBlockId: string | null
        focusSource: string | null
        label: string
    }
    askAgent: (message: string) => {
        message: string
    }
    conflictDetected: (versionId: string | null) => {
        versionId: string | null
    }
    dropBlock: (
        source: SourceDragSource,
        hit: SourceDropHit
    ) => {
        hit: SourceDropHit
        source: SourceDragSource
    }
    duplicateSelection: (selection: CanvasEditSelection) => {
        selection: CanvasEditSelection
    }
    editKey: (key: CanvasEditKey) => {
        key: CanvasEditKey
    }
    finishEditing: () => {
        value: true
    }
    frameMounted: (
        rev: number,
        root: SourceRange | null
    ) => {
        rev: number
        root: SourceRange | null
    }
    insertBlock: (
        blockType: string,
        target: SourceDropTarget,
        method: 'click' | 'drag'
    ) => {
        blockType: string
        method: 'click' | 'drag'
        target: SourceDropTarget
    }
    loadSource: () => {
        value: true
    }
    redoEdit: () => {
        value: true
    }
    removeSelection: (selection: CanvasEditSelection) => {
        selection: CanvasEditSelection
    }
    resolveConflict: (keepLocal: boolean) => {
        keepLocal: boolean
    }
    retrySave: () => {
        value: true
    }
    save: () => {
        value: true
    }
    saveFailed: (error: string) => {
        error: string
    }
    saveStarted: () => {
        value: true
    }
    saveSucceeded: (
        files: SourceFiles,
        versionId: string,
        noted: number
    ) => {
        files: SourceFiles
        noted: number
        versionId: string
    }
    select: (
        selection: CanvasEditSelection | null,
        byPointer?: boolean
    ) => {
        byPointer: boolean
        selection: CanvasEditSelection | null
    }
    setEditing: (editing: boolean) => {
        editing: boolean
    }
    setLibraryOpen: (open: boolean) => {
        open: boolean
    }
    setText: (
        selection: CanvasEditSelection,
        text: string
    ) => {
        selection: CanvasEditSelection
        text: string
    }
    sourceLoadFailed: (error: string) => {
        error: string
    }
    sourceLoaded: (source: CanvasSourceResponseApi) => {
        source: CanvasSourceResponseApi
    }
    sourceUnchanged: () => {
        value: true
    }
    undoEdit: () => {
        value: true
    }
    updateProps: (
        selection: CanvasEditSelection,
        props: BlockPropsRecord
    ) => {
        props: BlockPropsRecord
        selection: CanvasEditSelection
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface canvasEditLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        sourceEditing: (editing: boolean, browseVersionId: string | null) => boolean
        canUndoEdit: (entry: CanvasSourceEntry | null) => boolean
        canRedoEdit: (entry: CanvasSourceEntry | null) => boolean
        saveStatus: (entry: CanvasSourceEntry | null) => CanvasSaveStatus | null
        editUnavailableReason: (
            view: CanvasViewResponseApi | null,
            sandboxDocumentUrl: string | null,
            isGenerating: boolean
        ) => string | null
    }
}

export type canvasEditLogicType = MakeLogicType<
    canvasEditLogicValues,
    canvasEditLogicActions,
    CanvasEditLogicProps,
    canvasEditLogicMeta
>

/**
 * Manual editing of a canvas, ported from PostHog Desktop's block editor. The author edits the head
 * source in the draft sandbox: selecting, moving, inserting and changing blocks rewrites the files
 * locally, a snapshot stack backs undo and redo, and every change publishes a new version shortly after.
 */
export const canvasEditLogic = kea<canvasEditLogicType>([
    props({} as CanvasEditLogicProps),
    key((props) => props.id),
    path((key) => ['products', 'canvas', 'frontend', 'editing', 'canvasEditLogic', key]),
    connect((props: CanvasEditLogicProps) => ({
        values: [
            canvasSceneLogic({ id: props.id }),
            ['currentProjectId', 'view', 'canvas', 'isGenerating', 'sandboxDocumentUrl'],
            canvasHistoryLogic({ id: props.id }),
            ['browseVersionId'],
            canvasNewLogic,
            ['editHandoff'],
        ],
        actions: [
            canvasSceneLogic({ id: props.id }),
            ['loadView', 'loadViewSuccess', 'loadBuilds', 'startPolling'],
            canvasHistoryLogic({ id: props.id }),
            ['setBrowseVersion'],
            canvasSidePanelLogic,
            ['openTab', 'setBlocksCanvasId', 'switchTab'],
            canvasChatLogic({ id: props.id }),
            ['setDraft'],
            canvasNewLogic,
            ['clearEditHandoff'],
        ],
    })),
    actions({
        setEditing: (editing: boolean) => ({ editing }),
        finishEditing: true,
        loadSource: true,
        sourceLoaded: (source: CanvasSourceResponseApi) => ({ source }),
        sourceLoadFailed: (error: string) => ({ error }),
        sourceUnchanged: true,
        /** The frame mounted a rev of the files, and reports where the canvas's root element is. */
        frameMounted: (rev: number, root: SourceRange | null) => ({ rev, root }),
        select: (selection: CanvasEditSelection | null, byPointer: boolean = false) => ({ selection, byPointer }),
        setLibraryOpen: (open: boolean) => ({ open }),
        applyEdit: (
            files: SourceFiles,
            label: string,
            focusBlockId: string | null = null,
            focusSource: string | null = null
        ) => ({ files, label, focusBlockId, focusSource }),
        insertBlock: (blockType: string, target: SourceDropTarget, method: 'click' | 'drag') => ({
            blockType,
            target,
            method,
        }),
        addAfterSelection: (blockType: string) => ({ blockType }),
        dropBlock: (source: SourceDragSource, hit: SourceDropHit) => ({ source, hit }),
        removeSelection: (selection: CanvasEditSelection) => ({ selection }),
        duplicateSelection: (selection: CanvasEditSelection) => ({ selection }),
        updateProps: (selection: CanvasEditSelection, props: BlockPropsRecord) => ({ selection, props }),
        setText: (selection: CanvasEditSelection, text: string) => ({ selection, text }),
        editKey: (key: CanvasEditKey) => ({ key }),
        undoEdit: true,
        redoEdit: true,
        save: true,
        saveStarted: true,
        saveSucceeded: (files: SourceFiles, versionId: string, noted: number) => ({ files, versionId, noted }),
        saveFailed: (error: string) => ({ error }),
        retrySave: true,
        conflictDetected: (versionId: string | null) => ({ versionId }),
        resolveConflict: (keepLocal: boolean) => ({ keepLocal }),
        askAgent: (message: string) => ({ message }),
    }),
    reducers({
        finishAfterSave: [false, { finishEditing: () => true, setEditing: () => false }],
        editing: [
            false,
            {
                setEditing: (_, { editing }) => editing,
            },
        ],
        entry: [
            null as CanvasSourceEntry | null,
            {
                sourceLoaded: (state, { source }) => loadSourceEntry(state, source.project, source.current_version_id),
                frameMounted: (state, { rev, root }) => (state ? setSourceMounted(state, rev, root) : state),
                applyEdit: (state, { files, label, focusBlockId, focusSource }) =>
                    state ? applySourceFiles(noteSourceChange(state, label), files, focusBlockId, focusSource) : state,
                undoEdit: (state) => (state ? undoSourceEntry(state) : state),
                redoEdit: (state) => (state ? redoSourceEntry(state) : state),
                saveStarted: (state) => (state ? setSourceSaving(state, true) : state),
                saveSucceeded: (state, { files, versionId, noted }) =>
                    state ? markSourceSaved(state, files, versionId, noted) : state,
                saveFailed: (state, { error }) => (state ? setSourceSaving(state, false, error) : state),
                retrySave: (state) => (state ? setSourceSaving(state, false, null) : state),
                conflictDetected: (state, { versionId }) => (state ? setSourceConflict(state, versionId) : state),
                resolveConflict: (state, { keepLocal }) => (state ? resolveSourceConflict(state, keepLocal) : state),
            },
        ],
        sourceLoading: [
            false,
            {
                loadSource: () => true,
                sourceLoaded: () => false,
                sourceLoadFailed: () => false,
                sourceUnchanged: () => false,
            },
        ],
        sourceError: [
            null as string | null,
            {
                loadSource: () => null,
                sourceLoadFailed: (_, { error }) => error,
            },
        ],
        selection: [
            null as CanvasEditSelection | null,
            {
                select: (_, { selection }) => selection,
                setEditing: () => null,
            },
        ],
        // The Blocks tab shows the library while this is on, and the inspector for a selection otherwise.
        libraryOpen: [
            false,
            {
                setLibraryOpen: (_, { open }) => open,
                select: (state, { byPointer }) => (byPointer ? false : state),
            },
        ],
    }),
    selectors({
        // A browsed version shows instead of the editor, like PostHog Desktop.
        sourceEditing: [
            (s) => [s.editing, s.browseVersionId],
            (editing: boolean, browseVersionId: string | null): boolean => editing && !browseVersionId,
        ],
        canUndoEdit: [(s) => [s.entry], (entry: CanvasSourceEntry | null): boolean => (entry?.past.length ?? 0) > 0],
        canRedoEdit: [(s) => [s.entry], (entry: CanvasSourceEntry | null): boolean => (entry?.future.length ?? 0) > 0],
        saveStatus: [
            (s) => [s.entry],
            (entry: CanvasSourceEntry | null): CanvasSaveStatus | null =>
                entry
                    ? {
                          saving: entry.saving,
                          dirty: isSourceDirty(entry),
                          error: entry.saveError ?? (entry.conflict ? 'This canvas changed somewhere else' : null),
                      }
                    : null,
        ],
        /** Why the Edit toggle is off, or null when the canvas can be edited. */
        editUnavailableReason: [
            (s) => [s.view, s.sandboxDocumentUrl, s.isGenerating],
            (
                view: CanvasViewResponseApi | null,
                sandboxDocumentUrl: string | null,
                isGenerating: boolean
            ): string | null => {
                if (!view?.current_version_id) {
                    return 'This canvas has no source to edit yet.'
                }
                if (!sandboxDocumentUrl) {
                    return "Editing needs a separate canvas origin, and this PostHog instance doesn't have one set up."
                }
                if (isGenerating) {
                    return 'The agent is changing the canvas. Wait for it to finish.'
                }
                return null
            },
        ],
    }),
    listeners(({ actions, values, props, cache }) => {
        const track = (
            actionType: CanvasDashboardActionType,
            properties: Omit<Parameters<typeof captureCanvasAction>[1], 'dashboard_id'> = {}
        ): void => {
            captureCanvasAction(actionType, {
                dashboard_id: props.id,
                channel_id: values.canvas?.channel,
                ...properties,
            })
        }
        const blocked = (entry: CanvasSourceEntry): boolean => entry.saveError !== null || entry.conflict !== null
        const idle = (entry: CanvasSourceEntry | null): boolean => !!entry && !isSourceDirty(entry) && !entry.saving
        const scheduleSave = (): void => {
            const entry = values.entry
            if (!entry || !isSourceDirty(entry) || entry.saving || blocked(entry)) {
                cache.disposables.dispose('autosave')
                return
            }
            cache.disposables.add(
                () => {
                    const timer = setTimeout(() => actions.save(), SAVE_DEBOUNCE_MS)
                    return () => clearTimeout(timer)
                },
                'autosave',
                { pauseOnPageHidden: false }
            )
        }
        const note = (verb: string, selection: CanvasEditSelection): string =>
            `${verb} ${libraryLabel(selection.blockType, selection.tag).toLowerCase()}`
        const apply = (
            files: SourceFiles,
            label: string,
            focusBlockId: string | null = null,
            focusSource: string | null = null
        ): void => actions.applyEdit(syncBlockLibrary(files), label, focusBlockId, focusSource)
        const fresh = (rev: number): boolean => isFreshRev(values.entry, rev)

        return {
            finishEditing: () => {
                if (!values.entry || idle(values.entry)) {
                    actions.setEditing(false)
                } else {
                    actions.openTab('blocks', props.id)
                    actions.save()
                }
            },
            setEditing: ({ editing }) => {
                track('edit_toggle', { editing })
                actions.setBlocksCanvasId(editing ? props.id : null)
                if (editing) {
                    actions.setBrowseVersion(null)
                    actions.openTab(values.canvas?.generation_task_id ? 'chat' : 'blocks', props.id)
                    actions.loadSource()
                    cache.disposables.add(() => {
                        const timer = setInterval(() => {
                            if (idle(values.entry) && !values.sourceLoading) {
                                actions.loadSource()
                            }
                        }, SOURCE_POLL_MS)
                        return () => clearInterval(timer)
                    }, 'sourcePoll')
                    return
                }
                cache.disposables.dispose('sourcePoll')
                // Done saves what is still pending instead of waiting for the debounce.
                const entry = values.entry
                if (entry && isSourceDirty(entry) && !entry.saving && !blocked(entry)) {
                    cache.disposables.dispose('autosave')
                    actions.save()
                }
            },
            loadSource: async () => {
                if (!values.currentProjectId) {
                    actions.sourceLoadFailed('Pick a project to edit this canvas.')
                    return
                }
                try {
                    const source = await canvasesSourceRetrieve(String(values.currentProjectId), props.id)
                    if (cache.disposables.isDisposed) {
                        return
                    }
                    if (!source.project.files[CANVAS_ENTRY_PATH]?.trim()) {
                        actions.sourceLoadFailed('This canvas has no source to edit yet.')
                        return
                    }
                    const entry = values.entry
                    // Local edits are never replaced from here: a stale save conflicts instead.
                    if (!entry || (idle(entry) && entry.baseVersionId !== source.current_version_id)) {
                        actions.sourceLoaded(source)
                    } else {
                        actions.sourceUnchanged()
                    }
                } catch (error) {
                    if (!cache.disposables.isDisposed) {
                        actions.sourceLoadFailed(error instanceof Error ? error.message : 'Try again in a moment.')
                    }
                }
            },
            loadViewSuccess: ({ view }) => {
                const entry = values.entry
                if (values.editing && view && idle(entry) && entry?.baseVersionId !== view.current_version_id) {
                    actions.loadSource()
                }
            },
            select: ({ selection }) => {
                if (selection) {
                    actions.switchTab('blocks')
                }
            },
            insertBlock: ({ blockType, target, method }) => {
                const entry = values.entry
                const definition = blockDefinition(blockType)
                if (!entry || !definition) {
                    return
                }
                const blockId = newBlockId()
                const files = insertBlock(
                    entry.files,
                    target,
                    definition,
                    freshBlockProps(definition, entry.files),
                    blockId
                )
                if (files === entry.files) {
                    return
                }
                apply(files, `Added ${definition.label.toLowerCase()}`, definition.component ? blockId : null)
                if (definition.needsSetup) {
                    actions.setLibraryOpen(false)
                }
                actions.switchTab('blocks')
                track('block_insert', { block_type: blockType, method })
            },
            addAfterSelection: ({ blockType }) => {
                const entry = values.entry
                if (!entry) {
                    return
                }
                const selection = values.selection
                const root = entry.rootSource
                const group = blockDefinition(blockType)?.group
                const control =
                    group === 'Controls' && root ? blockRanges(entry.files, root.file, 'Controls').at(-1) : undefined
                if (control) {
                    actions.insertBlock(blockType, { ...control, place: 'after' }, 'click')
                    return
                }
                const controlSelected =
                    !!selection?.blockType && blockDefinition(selection.blockType)?.group === 'Controls'
                const besideAllowed = group === 'Controls' || !controlSelected
                if (selection?.source && !isRootSelection(entry, selection) && besideAllowed && fresh(selection.rev)) {
                    actions.insertBlock(blockType, besideSelection(selection, blockType), 'click')
                    return
                }
                const firstData = group === 'Data' && root ? blockRanges(entry.files, root.file, 'Data')[0] : undefined
                if (firstData) {
                    actions.insertBlock(blockType, { ...firstData, place: 'before' }, 'click')
                    return
                }
                if (!root || entry.mountedRev !== entry.rev) {
                    return
                }
                const inRoot: SourceDropTarget = { ...root, place: 'inside' }
                if (placeableTarget(entry, inRoot)) {
                    actions.insertBlock(blockType, inRoot, 'click')
                }
            },
            dropBlock: ({ source, hit }) => {
                const entry = values.entry
                if (!entry || !fresh(hit.rev) || !placeableTarget(entry, hit.target)) {
                    return
                }
                if (source.kind === 'new') {
                    actions.insertBlock(source.blockType, hit.target, 'drag')
                    return
                }
                const range = source.selection.source
                if (!range || !fresh(source.selection.rev) || !isJsxRange(entry.files, range)) {
                    return
                }
                const files = moveRange(entry.files, range, hit.target)
                if (files === entry.files) {
                    return
                }
                apply(files, note('Moved', source.selection), source.selection.blockId)
                track('block_move', { block_type: analyticsBlockType(source.selection.blockType) })
            },
            removeSelection: ({ selection }) => {
                const entry = values.entry
                if (!entry || !selection.source || !fresh(selection.rev) || isRootSelection(entry, selection)) {
                    return
                }
                apply(removeRange(entry.files, selection.source), note('Removed', selection))
                actions.select(null)
                track('block_remove', { block_type: analyticsBlockType(selection.blockType) })
            },
            duplicateSelection: ({ selection }) => {
                const entry = values.entry
                if (!entry || !selection.source || !fresh(selection.rev)) {
                    return
                }
                const blockId = newBlockId()
                apply(
                    duplicateRange(entry.files, selection.source, blockId),
                    note('Duplicated', selection),
                    selection.blockId ? blockId : null
                )
                track('block_duplicate', { block_type: analyticsBlockType(selection.blockType) })
            },
            updateProps: ({ selection, props: blockProps }) => {
                const entry = values.entry
                if (!entry || !selection.source || !selection.blockType || !fresh(selection.rev)) {
                    return
                }
                const files = updateBlockProps(entry.files, selection.source, selection.props, blockProps)
                if (files === entry.files) {
                    return
                }
                apply(
                    files,
                    note('Changed', selection),
                    selection.blockId,
                    selection.blockId ? null : `${selection.source.file}|${selection.source.start}`
                )
                actions.select({ ...selection, props: blockProps })
                track('block_edit', { block_type: analyticsBlockType(selection.blockType) })
            },
            setText: ({ selection, text }) => {
                const entry = values.entry
                if (!entry || !selection.source || !fresh(selection.rev)) {
                    return
                }
                const files = replaceElementText(entry.files, selection.source, text)
                if (files === entry.files) {
                    return
                }
                apply(files, 'Edited text', selection.blockId, `${selection.source.file}|${selection.source.start}`)
                track('text_edit', { block_type: analyticsBlockType(selection.blockType) })
            },
            editKey: ({ key }) => {
                const mod = key.metaKey || key.ctrlKey
                const selection = values.selection
                if (mod && key.key.toLowerCase() === 'z') {
                    if (key.shiftKey) {
                        actions.redoEdit()
                    } else {
                        actions.undoEdit()
                    }
                    return
                }
                if (!selection) {
                    return
                }
                if (key.key === 'Backspace' || key.key === 'Delete') {
                    actions.removeSelection(selection)
                    return
                }
                if (mod && key.key.toLowerCase() === 'd') {
                    actions.duplicateSelection(selection)
                }
            },
            undoEdit: () => {
                track('edit_undo')
                scheduleSave()
            },
            redoEdit: () => {
                track('edit_redo')
                scheduleSave()
            },
            applyEdit: scheduleSave,
            retrySave: scheduleSave,
            saveSucceeded: () => {
                scheduleSave()
                if (values.finishAfterSave && idle(values.entry)) {
                    actions.setEditing(false)
                }
            },
            resolveConflict: ({ keepLocal }) => {
                track('edit_conflict_resolve', { keep_local: keepLocal })
                if (keepLocal) {
                    scheduleSave()
                } else {
                    actions.loadSource()
                }
            },
            save: async () => {
                let entry = values.entry
                const projectId = values.currentProjectId
                if (!entry || !projectId || !isSourceDirty(entry) || entry.saving || blocked(entry)) {
                    return
                }
                actions.saveStarted()
                while (entry) {
                    const files = entry.files
                    const project = {
                        ...entry.project,
                        files,
                        capabilities: canvasCapabilities(entry.project.capabilities, files) as
                            | CanvasCapabilitiesApi
                            | undefined,
                    }
                    try {
                        const result = await canvasesPublishCreate(String(projectId), props.id, {
                            project,
                            prompt: describeChanges(entry.changes),
                            expected_current_version_id: entry.baseVersionId,
                        })
                        if (cache.disposables.isDisposed) {
                            entry = markSourceSaved(
                                cache.detachedEntry ?? entry,
                                files,
                                result.current_version_id,
                                entry.changes.length
                            )
                            cache.detachedEntry = entry
                            if (isSourceDirty(entry)) {
                                continue
                            }
                            return
                        }
                        actions.saveSucceeded(files, result.current_version_id, entry.changes.length)
                        track('edit_save', { success: true })
                        // The publish queued a build, so the header's build status and the timeline refresh.
                        actions.loadView()
                        actions.loadBuilds()
                        actions.startPolling()
                        return
                    } catch (error) {
                        if (cache.disposables.isDisposed) {
                            return
                        }
                        const status = (error as { status?: number } | null)?.status
                        if (status === 409) {
                            const data = (error as { data?: { current_version_id?: string | null } }).data
                            actions.conflictDetected(data?.current_version_id ?? null)
                            track('edit_conflict')
                            return
                        }
                        actions.saveFailed(saveErrorMessage(error))
                        track('edit_save', { success: false })
                        return
                    }
                }
            },
            askAgent: ({ message }) => {
                actions.setDraft(message)
                actions.openTab('chat', props.id)
            },
        }
    }),
    beforeUnload(({ values }) => ({
        enabled: () => !!values.entry && (isSourceDirty(values.entry) || values.entry.saving),
        message: 'Your canvas has unsaved changes. Wait for the save to finish before you leave.',
    })),
    beforeUnmount(({ values, actions, cache }) => {
        cache.detachedEntry = values.entry
        if (
            values.entry &&
            isSourceDirty(values.entry) &&
            !values.entry.saving &&
            !values.entry.saveError &&
            !values.entry.conflict
        ) {
            actions.save()
        }
        if (values.editing) {
            actions.setBlocksCanvasId(null)
        }
    }),
    afterMount(({ actions, values, props }) => {
        // Start blank on the start page lands here to add the first blocks.
        if (values.editHandoff === props.id) {
            actions.clearEditHandoff()
            actions.setEditing(true)
            actions.openTab('blocks', props.id)
        }
    }),
])