import { FieldSchema, StructureSchema } from '@ephox/boulder';
import { Fun } from '@ephox/katamari';
import { Receiving } from '../api/behaviour/Receiving';
import { Sandboxing } from '../api/behaviour/Sandboxing';
import * as AlloyTriggers from '../api/events/AlloyTriggers';
import * as SystemEvents from '../api/events/SystemEvents';
import * as Channels from '../api/messages/Channels';
const schema = StructureSchema.objOfOnly([
    FieldSchema.defaulted('isExtraPart', Fun.never),
    FieldSchema.optionObjOf('fireEventInstead', [
        FieldSchema.defaulted('event', SystemEvents.dismissRequested())
    ])
]);
const receivingConfig = (rawSpec) => {
    const c = receivingChannel(rawSpec);
    return Receiving.config({
        channels: c
    });
};
const receivingChannel = (rawSpec) => {
    const detail = StructureSchema.asRawOrDie('Dismissal', schema, rawSpec);
    return {
        [Channels.dismissPopups()]: {
            schema: StructureSchema.objOfOnly([
                FieldSchema.required('target')
            ]),
            onReceive: (sandbox, data) => {
                if (Sandboxing.isOpen(sandbox)) {
                    const isPart = Sandboxing.isPartOf(sandbox, data.target) || detail.isExtraPart(sandbox, data.target);
                    if (!isPart) {
                        detail.fireEventInstead.fold(() => Sandboxing.close(sandbox), (fe) => AlloyTriggers.emit(sandbox, fe.event));
                    }
                }
            }
        }
    };
};
export { receivingChannel, receivingConfig };
//# sourceMappingURL=Dismissal.js.map