import { getContext, setContext } from 'svelte';
import { FrameEditSession } from '../editing/FrameEditSession';
import { usePartConfig } from './usePartConfig.svelte';
const key = Symbol('frame-edit-session-context');
export const provideFrameEditSession = (partID) => {
    const partConfig = usePartConfig();
    let active = $state(undefined);
    const begin = (entities) => {
        active?.abort();
        const session = new FrameEditSession(entities, partConfig.updateFrame, partConfig.deleteFrame, () => {
            if (active === session)
                active = undefined;
        });
        active = session;
        return session;
    };
    // Drop any in-flight session when the partID changes — its snapshots reference
    // entities from the old world that useFrames will destroy, and aborting it
    // after the swap would write old frame names into the new part's config.
    let lastPartID;
    $effect.pre(() => {
        const id = partID();
        if (lastPartID !== undefined && lastPartID !== id) {
            active?.abort();
            active = undefined;
        }
        lastPartID = id;
    });
    setContext(key, {
        get current() {
            return active;
        },
        begin,
    });
};
export const useFrameEditSession = () => getContext(key);
