var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var AffineAIMenuWidget_1;
import { assertExists, DisposableGroup, throttle, } from '@blockeditor/global/utils';
import { WidgetElement } from '@blockeditor/lit';
import { customElement } from 'lit/decorators.js';
import { getCurrentNativeRange, getInlineEditorByModel, isControlledKeyboardEvent, matchFlavours, } from '../../../_common/utils/index.js';
import { isPageComponent } from '../../../page-block/utils/guard.js';
import { getPopperPosition } from '../../../page-block/utils/position.js';
import { AIMenu } from './ai-menu-popover.js';
import { menuGroups } from './config.js';
let globalAbortController = new AbortController();
function showAIMenu({ pageElement, model, range, container = document.body, abortController = new AbortController(), options, triggerKey, }) {
    // Abort previous format quick bar
    globalAbortController.abort();
    globalAbortController = abortController;
    const disposables = new DisposableGroup();
    abortController.signal.addEventListener('abort', () => disposables.dispose());
    const aiMenu = new AIMenu();
    disposables.add(() => aiMenu.remove());
    aiMenu.model = model;
    aiMenu.abortController = abortController;
    aiMenu.options = options;
    aiMenu.pageElement = pageElement;
    aiMenu.triggerKey = triggerKey;
    // Handle position
    const updatePosition = throttle(() => {
        const aiMenuElement = aiMenu.aiMenuElement;
        assertExists(aiMenuElement, 'You should render the ai menu node even if no position');
        const position = getPopperPosition(aiMenuElement, range);
        aiMenu.updatePosition(position);
    }, 10);
    disposables.addFromEvent(window, 'resize', updatePosition);
    // FIXME(Flrande): It is not a best practice,
    // but merely a temporary measure for reusing previous components.
    // Mount
    container.appendChild(aiMenu);
    // Wait for the Node to be mounted
    setTimeout(updatePosition);
    return aiMenu;
}
export const AFFINE_AI_MENU_WIDGET = 'affine-ai-menu-widget';
let AffineAIMenuWidget = AffineAIMenuWidget_1 = class AffineAIMenuWidget extends WidgetElement {
    constructor() {
        super(...arguments);
        this.options = AffineAIMenuWidget_1.DEFAULT_OPTIONS;
        this._onKeyDown = (ctx) => {
            const eventState = ctx.get('keyboardState');
            const event = eventState.raw;
            console.log(222, event);
            const triggerKey = this.options.isTriggerKey(event);
            if (triggerKey === false)
                return;
            const text = this.host.selection.value.find(selection => selection.is('text'));
            // console.log(333, text, {...this.host})
            if (!text) {
                return;
            }
            const model = this.host.page.getBlockById(text.blockId);
            // console.log(444, model)
            if (!model || !model.text || model.text.length > 1) {
                return;
            }
            if (matchFlavours(model, ['affine:code']))
                return;
            const inlineEditor = getInlineEditorByModel(this.host, model);
            if (!inlineEditor)
                return;
            inlineEditor.slots.inlineRangeApply.once(() => {
                const pageElement = this.blockElement;
                if (!isPageComponent(pageElement)) {
                    throw new Error('AIMenuWidget should be used in PageBlock');
                }
                // Wait for dom update, see this case https://github.com/toeverything/blockeditor/issues/2611
                requestAnimationFrame(() => {
                    const curRange = getCurrentNativeRange();
                    showAIMenu({
                        pageElement,
                        model,
                        range: curRange,
                        triggerKey,
                        options: this.options,
                    });
                });
            });
        };
    }
    connectedCallback() {
        super.connectedCallback();
        this.handleEvent('keyDown', this._onKeyDown);
    }
};
AffineAIMenuWidget.DEFAULT_OPTIONS = {
    isTriggerKey: (event) => {
        // const triggerKeys = [];
        // console.log(111, event);
        // if (
        //   event.key === 'Process' &&
        //   event.code === 'Slash' &&
        //   !event.shiftKey
        // ) {
        //   return 'A';
        // }
        if (isControlledKeyboardEvent(event) || event.key.length !== 1)
            return false;
        // const triggerKey = triggerKeys.find(key => key === event.key);
        // if (!triggerKey) return false;
        // return triggerKey;
        return false;
    },
    menus: menuGroups,
};
AffineAIMenuWidget = AffineAIMenuWidget_1 = __decorate([
    customElement(AFFINE_AI_MENU_WIDGET)
], AffineAIMenuWidget);
export { AffineAIMenuWidget };
//# sourceMappingURL=index.js.map