Files
InvokeAI/invokeai/frontend/web/src/features/controlLayers/contexts/EntityIdentifierContext.ts
psychedelicious dd7d4da5e3 feat(ui): normalize all actions to accept an entityIdentifier
Previously, canvas actions specific to an entity type only needed the id of that entity type. This allowed you to pass in the id of an entity of the wrong type.

All actions for a specific entity now take a full entity identifier, and the entity identifier type can be narrowed.

`selectEntity` and `selectEntityOrThrow` now need a full entity identifier, and narrow their return values to a specific entity type _if_ the entity identifier is narrowed.

The types for canvas entities are updated with optional type parameters for this purpose.

All reducers, actions and components have been updated.
2024-09-06 22:56:24 +10:00

17 lines
847 B
TypeScript

import type { CanvasEntityIdentifier, CanvasEntityType } from 'features/controlLayers/store/types';
import { createContext, useContext } from 'react';
import { assert } from 'tsafe';
export const EntityIdentifierContext = createContext<CanvasEntityIdentifier | null>(null);
export const useEntityIdentifierContext = <T extends CanvasEntityType | undefined = CanvasEntityType>(
type?: T
): CanvasEntityIdentifier<T extends undefined ? CanvasEntityType : T> => {
const entityIdentifier = useContext(EntityIdentifierContext);
assert(entityIdentifier, 'useEntityIdentifier must be used within a EntityIdentifierProvider');
if (type) {
assert(entityIdentifier.type === type, 'useEntityIdentifier must be used with the correct type');
}
return entityIdentifier as CanvasEntityIdentifier<T extends undefined ? CanvasEntityType : T>;
};