Files
timi-tdesign-mobile/src/components/tiptap-editor/TiptapLinkButton.vue
T
2026-11-16 17:46:25 +08:00

117 lines
2.4 KiB
Vue

<template>
<t-button
:variant="active ? 'base' : 'text'"
:theme="active ? 'light' : 'default'"
@click="openDialog"
>
<t-icon name="link-1" />
</t-button>
<bottom-popup
v-model="visible"
placement="bottom"
title="插入链接"
left-button-text="取消"
right-button-text="插入"
@left-button-click="visible = false"
@right-button-click="onConfirm"
destroy-on-close
>
<t-form class="popup">
<t-form-item label="地址">
<t-input v-model="linkForm.href" borderless />
</t-form-item>
<t-form-item label="显示文本">
<t-input v-model="linkForm.text" borderless />
</t-form-item>
<t-form-item content-align="right">
<t-checkbox
class="sync"
v-model="linkForm.syncToHref"
borderless
>显示文本同步为链接</t-checkbox>
</t-form-item>
</t-form>
</bottom-popup>
</template>
<script lang="ts" setup>
import type { TiptapEditorInstance } from "timi-web/editor";
import BottomPopup from "../bottom-popup/index.vue";
defineOptions({
name: "TiptapLinkButton"
});
const props = defineProps<{
editor?: TiptapEditorInstance;
active: boolean;
}>();
const visible = ref(false);
const linkForm = reactive({
href: "",
text: "",
syncToHref: false
});
function openDialog() {
if (!props.editor) {
return;
}
const previousUrl = (props.editor.getAttributes("link").href as string) || "";
const selectedText = props.editor.state.doc.textBetween(
props.editor.state.selection.from,
props.editor.state.selection.to,
""
);
linkForm.href = previousUrl || "https://";
linkForm.text = selectedText || "";
linkForm.syncToHref = false;
visible.value = true;
}
function onConfirm() {
if (!props.editor) {
return;
}
const href = linkForm.href.trim();
if (!href) {
props.editor.chain().focus().unsetLink().run();
visible.value = false;
return;
}
const text = linkForm.syncToHref ? href : linkForm.text.trim();
if (text) {
props.editor
.chain()
.focus()
.insertContent({
type: "text",
text,
marks: [{ type: "link", attrs: { href } }]
})
.run();
} else {
props.editor.chain().focus().extendMarkRange("link").setLink({ href }).run();
}
visible.value = false;
}
</script>
<style lang="less" scoped>
.link-form {
gap: .75rem;
padding: 0 1rem calc(1rem + var(--tui-safe-bottom, 0px));
display: flex;
flex-direction: column;
}
.popup {
margin: 0;
.sync {
padding: 0;
}
}
</style>