import { EntityChangedPayload } from '../../_contract-src/event-payloads/entity-changed/entity-changed-payload'; import { EventType } from '../../_contract-src/event-payloads/event-type'; import type { StructEventMessage } from '../../_contract-src/shared/struct-event-message'; import { isAllowedOrigin } from '../../_contract-src/setup/configure'; /** * Registers a listener for the event from Struct PIM where the current entity has changed. * Called whenever the entity context changes, providing updated session context * (slug, language, user, segments, etc.). * * The callback receives a {@link EntityChangedPayload} with the payload used to describe what entity changed. * Extension points of the types: tab, section, sidebar widget and property, might want to be notified about changes to the current entity. For example, if an extension is registered on a product tab, it will receive an event every time the user saves changes they have done to the product model * * @example * ```ts * struct.events.onEntityChangedEvent((ctx) => { * console.log(ctx.entityType, 'with id', ctx.entityId, 'changed :', ctx); * }); * ``` */ export function onEntityChangedEvent(callback: (payload: EntityChangedPayload) => void): () => void { const handler = (event: MessageEvent>) => { if (event.data?.eventType !== EventType.ENTITY_CHANGED) return; if (!isAllowedOrigin(event.origin)) return; callback(event.data.payload); }; window.addEventListener('message', handler); return () => window.removeEventListener('message', handler); }