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 './components/bookmark-card.js';
import '../_common/components/button.js';
import './doc-bookmark-block.js';
import './edgeless-bookmark-block.js';
import { assertExists, Slot } from '@blockeditor/global/utils';
import { BlockElement } from '@blockeditor/lit';
import { html, render } from 'lit';
import { customElement, property, query, state } from 'lit/decorators.js';
import { EMBED_CARD_HEIGHT, EMBED_CARD_WIDTH } from '../_common/consts.js';
import { matchFlavours } from '../_common/utils/index.js';
import { AFFINE_DRAG_HANDLE_WIDGET, AffineDragHandleWidget, } from '../page-block/widgets/drag-handle/drag-handle.js';
import { captureEventTarget, convertDragPreviewDocToEdgeless, convertDragPreviewEdgelessToDoc, } from '../page-block/widgets/drag-handle/utils.js';
import { Bound } from '../surface-block/utils/bound.js';
import { BookmarkBlockSchema, } from './bookmark-model.js';
import { refreshBookmarkUrlData } from './utils.js';
let BookmarkBlockComponent = class BookmarkBlockComponent extends BlockElement {
    constructor() {
        super(...arguments);
        this.loading = false;
        this.loadingFailed = false;
        this.showCaption = false;
        this._isInSurface = false;
        this.slots = {
            loadingUpdated: new Slot(),
        };
        this._dragHandleOption = {
            flavour: BookmarkBlockSchema.model.flavour,
            edgeless: true,
            onDragStart: ({ state, startDragging, anchorBlockPath }) => {
                if (!anchorBlockPath)
                    return false;
                const anchorComponent = this.std.view.viewFromPath('block', anchorBlockPath);
                if (!anchorComponent ||
                    !matchFlavours(anchorComponent.model, [
                        BookmarkBlockSchema.model.flavour,
                    ]))
                    return false;
                const blockComponent = anchorComponent;
                const element = captureEventTarget(state.raw.target);
                const isDraggingByDragHandle = !!element?.closest(AFFINE_DRAG_HANDLE_WIDGET);
                const isDraggingByComponent = blockComponent.contains(element);
                const isInSurface = blockComponent.isInSurface;
                if (!isInSurface && (isDraggingByDragHandle || isDraggingByComponent)) {
                    this.host.selection.setGroup('note', [
                        this.host.selection.create('block', {
                            path: blockComponent.path,
                        }),
                    ]);
                    startDragging([blockComponent], state);
                    return true;
                }
                else if (isInSurface && isDraggingByDragHandle) {
                    const bookmarkPortal = blockComponent.closest('.edgeless-block-portal-bookmark');
                    assertExists(bookmarkPortal);
                    const dragPreviewEl = bookmarkPortal.cloneNode();
                    dragPreviewEl.style.transform = '';
                    dragPreviewEl.style.left = '0';
                    dragPreviewEl.style.top = '0';
                    render(blockComponent.host.renderModel(blockComponent.model), dragPreviewEl);
                    startDragging([blockComponent], state, dragPreviewEl);
                    return true;
                }
                return false;
            },
            onDragEnd: props => {
                const { state, draggingElements, dropBlockId } = props;
                if (draggingElements.length !== 1 ||
                    !matchFlavours(draggingElements[0].model, [
                        BookmarkBlockSchema.model.flavour,
                    ]))
                    return false;
                const blockComponent = draggingElements[0];
                const isInSurface = blockComponent.isInSurface;
                const target = captureEventTarget(state.raw.target);
                const isTargetEdgelessContainer = target?.classList.contains('edgeless') &&
                    target?.classList.contains('affine-block-children-container');
                if (isInSurface) {
                    if (dropBlockId) {
                        const style = blockComponent.model.style;
                        if (style === 'vertical' || style === 'cube') {
                            const { xywh } = blockComponent.model;
                            const bound = Bound.deserialize(xywh);
                            bound.w = EMBED_CARD_WIDTH.horizontal;
                            bound.h = EMBED_CARD_HEIGHT.horizontal;
                            this.page.updateBlock(blockComponent.model, {
                                style: 'horizontal',
                                xywh: bound.serialize(),
                            });
                        }
                    }
                    return convertDragPreviewEdgelessToDoc({
                        blockComponent,
                        ...props,
                    });
                }
                else if (isTargetEdgelessContainer) {
                    const style = blockComponent.model.style;
                    return convertDragPreviewDocToEdgeless({
                        blockComponent,
                        cssSelector: '.affine-bookmark-card',
                        width: EMBED_CARD_WIDTH[style],
                        height: EMBED_CARD_HEIGHT[style],
                        ...props,
                    });
                }
                return false;
            },
        };
        this.open = () => {
            let link = this.model.url;
            if (!link.match(/^[a-zA-Z]+:\/\//)) {
                link = 'https://' + link;
            }
            window.open(link, '_blank');
        };
        this.refreshData = () => {
            refreshBookmarkUrlData(this).catch(console.error);
        };
    }
    get isInSurface() {
        return this._isInSurface;
    }
    connectedCallback() {
        super.connectedCallback();
        if (!!this.model.caption && this.model.caption.length > 0) {
            this.showCaption = true;
        }
        const parent = this.host.page.getParent(this.model);
        this._isInSurface = parent?.flavour === 'affine:surface';
        if (!this.model.description && !this.model.title) {
            this.refreshData();
        }
        this.disposables.add(this.model.propsUpdated.on(({ key }) => {
            this.edgelessOrDocBookmark?.requestUpdate();
            if (key === 'url') {
                this.refreshData();
            }
        }));
        this.disposables.add(AffineDragHandleWidget.registerOption(this._dragHandleOption));
    }
    updated(changedProperties) {
        super.updated(changedProperties);
        if (changedProperties.has('loading')) {
            this.slots.loadingUpdated.emit();
        }
    }
    render() {
        return html `${this.isInSurface
            ? html `<affine-edgeless-bookmark
          .block=${this}
        ></affine-edgeless-bookmark>`
            : html `<affine-doc-bookmark .block=${this}></affine-doc-bookmark>`} `;
    }
};
__decorate([
    property({ attribute: false })
], BookmarkBlockComponent.prototype, "loading", void 0);
__decorate([
    property({ attribute: false })
], BookmarkBlockComponent.prototype, "loadingFailed", void 0);
__decorate([
    state()
], BookmarkBlockComponent.prototype, "showCaption", void 0);
__decorate([
    query('affine-edgeless-bookmark, affine-doc-bookmark')
], BookmarkBlockComponent.prototype, "edgelessOrDocBookmark", void 0);
__decorate([
    query('embed-card-caption')
], BookmarkBlockComponent.prototype, "captionElement", void 0);
BookmarkBlockComponent = __decorate([
    customElement('affine-bookmark')
], BookmarkBlockComponent);
export { BookmarkBlockComponent };
//# sourceMappingURL=bookmark-block.js.map