|
| 1 | +<template> |
| 2 | + <div> |
| 3 | + <vue3-menus v-model:open="isOpen" :event="eventVal" :menus="menus" hasIcon> |
| 4 | + <template #icon="{ menu }" |
| 5 | + ><AppIcon v-if="menu.icon" :iconName="menu.icon"></AppIcon |
| 6 | + ></template> |
| 7 | + <template #label="{ menu }"> {{ menu.label }}</template> |
| 8 | + </vue3-menus> |
| 9 | + </div> |
| 10 | +</template> |
| 11 | +<script setup lang="ts"> |
| 12 | +import { Vue3Menus } from 'vue3-menus' |
| 13 | +import { MsgSuccess } from '@/utils/message' |
| 14 | +import AppIcon from '@/components/icons/AppIcon.vue' |
| 15 | +import bus from '@/bus' |
| 16 | +import { ref, nextTick, onMounted } from 'vue' |
| 17 | +const isOpen = ref<boolean>(false) |
| 18 | +const eventVal = ref({}) |
| 19 | +function getSelection() { |
| 20 | + const selection = window.getSelection() |
| 21 | + if (selection && selection.anchorNode == null) { |
| 22 | + return null |
| 23 | + } |
| 24 | + const text = selection?.anchorNode?.textContent |
| 25 | + return text && text.substring(selection.anchorOffset, selection.focusOffset) |
| 26 | +} |
| 27 | +/** |
| 28 | + * 打开控制台 |
| 29 | + * @param event |
| 30 | + */ |
| 31 | +const openControl = (event: any) => { |
| 32 | + const c = getSelection() |
| 33 | + isOpen.value = false |
| 34 | + if (c) { |
| 35 | + nextTick(() => { |
| 36 | + eventVal.value = event |
| 37 | + isOpen.value = true |
| 38 | + }) |
| 39 | + event.preventDefault() |
| 40 | + } |
| 41 | +} |
| 42 | +
|
| 43 | +const menus = ref([ |
| 44 | + { |
| 45 | + label: '复制', |
| 46 | + icon: 'app-copy', |
| 47 | + click: () => { |
| 48 | + const selectionText = getSelection() |
| 49 | + if (selectionText) { |
| 50 | + clearSelectedText() |
| 51 | + navigator.clipboard.writeText(selectionText).then(() => { |
| 52 | + MsgSuccess('复制成功') |
| 53 | + }) |
| 54 | + } |
| 55 | + } |
| 56 | + }, |
| 57 | + { |
| 58 | + label: '引用', |
| 59 | + icon: 'app-quote', |
| 60 | + click: () => { |
| 61 | + bus.emit('chat-input', getSelection()) |
| 62 | + clearSelectedText() |
| 63 | + } |
| 64 | + } |
| 65 | +]) |
| 66 | +/** |
| 67 | + * 清除选中文本 |
| 68 | + */ |
| 69 | +const clearSelectedText = () => { |
| 70 | + if (window.getSelection) { |
| 71 | + var selection = window.getSelection() |
| 72 | + if (selection) { |
| 73 | + selection.removeAllRanges() |
| 74 | + } |
| 75 | + } |
| 76 | +} |
| 77 | +onMounted(() => { |
| 78 | + bus.on('open-control', openControl) |
| 79 | +}) |
| 80 | +</script> |
| 81 | +<style lang="scss"></style> |
0 commit comments