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;
};
import { assertExists } from '@blockeditor/global/utils';
import { WithDisposable } from '@blockeditor/lit';
import { computePosition, flip, inline, offset, shift } from '@floating-ui/dom';
import { html, LitElement } from 'lit';
import { customElement, property, query } from 'lit/decorators.js';
import { createLitPortal } from '../../../../components/portal.js';
import { BLOCK_ID_ATTR } from '../../../../consts.js';
import { BookmarkIcon, MoreVerticalIcon } from '../../../../icons/index.js';
import { LinkIcon, OpenIcon } from '../../../../icons/text.js';
import { ReferencePopupMoreMenu } from './reference-popup-more-menu-popup.js';
import { styles } from './styles.js';
let ReferencePopup = class ReferencePopup extends WithDisposable(LitElement) {
    constructor() {
        super(...arguments);
        this._moreMenuAbortController = null;
    }
    get referencePageId() {
        const pageId = this.inlineEditor.getFormat(this.targetInlineRange).reference
            ?.pageId;
        assertExists(pageId);
        return pageId;
    }
    connectedCallback() {
        super.connectedCallback();
        if (this.targetInlineRange.length === 0) {
            throw new Error('Cannot toggle reference popup on empty range');
        }
        const parent = this.blockElement.host.page.getParent(this.blockElement.model);
        assertExists(parent);
        this.disposables.add(parent.childrenUpdated.on(() => {
            const children = parent.children;
            if (children.includes(this.blockElement.model))
                return;
            this.abortController.abort();
        }));
    }
    updated() {
        assertExists(this.popupContainer);
        const range = this.inlineEditor.toDomRange(this.targetInlineRange);
        assertExists(range);
        const visualElement = {
            getBoundingClientRect: () => range.getBoundingClientRect(),
            getClientRects: () => range.getClientRects(),
        };
        computePosition(visualElement, this.popupContainer, {
            middleware: [
                offset(10),
                inline(),
                shift({
                    padding: 6,
                }),
            ],
        })
            .then(({ x, y }) => {
            const popupContainer = this.popupContainer;
            if (!popupContainer)
                return;
            popupContainer.style.left = `${x}px`;
            popupContainer.style.top = `${y}px`;
        })
            .catch(console.error);
    }
    get blockElement() {
        const blockElement = this.inlineEditor.rootElement.closest(`[${BLOCK_ID_ATTR}]`);
        assertExists(blockElement);
        return blockElement;
    }
    get std() {
        const std = this.blockElement.std;
        assertExists(std);
        return std;
    }
    _openPage() {
        const refPageId = this.referencePageId;
        const blockElement = this.blockElement;
        if (refPageId === blockElement.model.page.id)
            return;
        const pageElement = this.std.view.viewFromPath('block', [
            blockElement.model.page.root?.id ?? '',
        ]);
        assertExists(pageElement);
        pageElement.slots.pageLinkClicked.emit({ pageId: refPageId });
    }
    _convertToCardView() {
        const blockElement = this.blockElement;
        const page = blockElement.host.page;
        const parent = page.getParent(blockElement.model);
        assertExists(parent);
        const index = parent.children.indexOf(blockElement.model);
        const pageId = this.referencePageId;
        page.addBlock('affine:embed-linked-doc', { pageId }, parent, index + 1);
        const totalTextLength = this.inlineEditor.yTextLength;
        const inlineTextLength = this.targetInlineRange.length;
        if (totalTextLength === inlineTextLength) {
            page.deleteBlock(blockElement.model);
        }
        else {
            this.inlineEditor.insertText(this.targetInlineRange, this.pageTitle);
        }
        this.abortController.abort();
    }
    _toggleMoreMenu() {
        if (this._moreMenuAbortController) {
            this._moreMenuAbortController.abort();
            this._moreMenuAbortController = null;
            return;
        }
        this._moreMenuAbortController = new AbortController();
        const referencePopupMoreMenu = new ReferencePopupMoreMenu();
        referencePopupMoreMenu.abortController = this.abortController;
        referencePopupMoreMenu.inlineEditor = this.inlineEditor;
        referencePopupMoreMenu.targetInlineRange = this.targetInlineRange;
        createLitPortal({
            template: referencePopupMoreMenu,
            container: this.popupContainer,
            computePosition: {
                referenceElement: this.popupContainer,
                placement: 'top-end',
                middleware: [flip(), offset(4)],
                autoUpdate: true,
            },
            abortController: this._moreMenuAbortController,
        });
    }
    render() {
        return html `
      <div class="overlay-root blockeditor-overlay">
        <div class="affine-reference-popover-container">
          <div class="affine-reference-popover view">
            <icon-button size="32px" @click=${this._openPage}>
              ${OpenIcon}
              <affine-tooltip .offset=${12}
                >${'Click to open page'}</affine-tooltip
              >
            </icon-button>

            <span class="affine-reference-popover-dividing-line"></span>

            <div class="affine-reference-popover-view-selector">
              <icon-button
                size="24px"
                class="affine-reference-popover-view-selector-button link current-view"
                hover="false"
              >
                ${LinkIcon}
                <affine-tooltip .offset=${12}>${'Inline view'}</affine-tooltip>
              </icon-button>

              <icon-button
                size="24px"
                class="affine-reference-popover-view-selector-button embed"
                hover="false"
                @click=${() => this._convertToCardView()}
              >
                ${BookmarkIcon}
                <affine-tooltip .offset=${12}>${'Card view'}</affine-tooltip>
              </icon-button>
            </div>

            <span class="affine-reference-popover-dividing-line"></span>

            <icon-button size="24px" @click=${() => this._toggleMoreMenu()}>
              ${MoreVerticalIcon}
              <affine-tooltip .offset=${12}>More</affine-tooltip>
            </icon-button>
          </div>
        </div>
      </div>
    `;
    }
};
ReferencePopup.styles = styles;
__decorate([
    property({ attribute: false })
], ReferencePopup.prototype, "inlineEditor", void 0);
__decorate([
    property({ attribute: false })
], ReferencePopup.prototype, "targetInlineRange", void 0);
__decorate([
    property({ attribute: false })
], ReferencePopup.prototype, "pageTitle", void 0);
__decorate([
    property({ attribute: false })
], ReferencePopup.prototype, "abortController", void 0);
__decorate([
    query('.affine-reference-popover-container')
], ReferencePopup.prototype, "popupContainer", void 0);
ReferencePopup = __decorate([
    customElement('reference-popup')
], ReferencePopup);
export { ReferencePopup };
export function toggleReferencePopup(inlineEditor, targetInlineRange, pageTitle, abortController) {
    const popup = new ReferencePopup();
    popup.inlineEditor = inlineEditor;
    popup.targetInlineRange = targetInlineRange;
    popup.pageTitle = pageTitle;
    popup.abortController = abortController;
    document.body.appendChild(popup);
    return popup;
}
//# sourceMappingURL=reference-popup.js.map