-
Notifications
You must be signed in to change notification settings - Fork 2.8k
Expand file tree
/
Copy pathindex.vue
More file actions
112 lines (109 loc) · 2.7 KB
/
index.vue
File metadata and controls
112 lines (109 loc) · 2.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
<template>
<div>
<vue3-menus v-model:open="isOpen" :event="eventVal" :zIndex="9999" :menus="menus" hasIcon>
<template #icon="{ menu }"
><AppIcon v-if="menu.icon" :iconName="menu.icon"></AppIcon
></template>
<template #label="{ menu }"> {{ menu.label }}</template>
</vue3-menus>
</div>
</template>
<script setup lang="ts">
import { Vue3Menus } from 'vue3-menus'
import { MsgSuccess } from '@/utils/message'
import bus from '@/bus'
import { ref, nextTick, onMounted } from 'vue'
import { t } from '@/locales'
const isOpen = ref<boolean>(false)
const eventVal = ref<any>({})
function getSelection() {
const selection = window.getSelection()
if (selection) {
if (selection.rangeCount === 0) return undefined
const range = selection.getRangeAt(0)
const fragment = range.cloneContents() // 克隆选区内容
const div = document.createElement('div')
div.appendChild(fragment)
if (div.textContent) {
return div.textContent.trim()
}
}
return undefined
}
/**
* 打开控制台
* @param event
*/
const openControl = (event: any) => {
const c = getSelection()
if (c) {
if (!isOpen.value) {
nextTick(() => {
eventVal.value = event
isOpen.value = true
})
} else {
clearSelectedText()
isOpen.value = false
}
event.preventDefault()
} else {
isOpen.value = false
}
}
const menus = ref([
{
label: t('common.copy'),
icon: 'app-copy',
click: () => {
const selectionText = getSelection()
if (selectionText) {
clearSelectedText()
if (
typeof navigator.clipboard === 'undefined' ||
typeof navigator.clipboard.writeText === 'undefined'
) {
const input = document.createElement('input')
input.setAttribute('value', selectionText)
document.body.appendChild(input)
input.select()
try {
if (document.execCommand('copy')) {
MsgSuccess(t('common.copySuccess'))
}
} finally {
document.body.removeChild(input)
}
} else {
navigator.clipboard.writeText(selectionText).then(() => {
MsgSuccess(t('common.copySuccess'))
})
}
}
},
},
{
label: t('chat.quote'),
icon: 'app-quote',
click: () => {
bus.emit('chat-input', getSelection())
clearSelectedText()
},
},
])
/**
* 清除选中文本
*/
const clearSelectedText = () => {
if (window.getSelection) {
const selection = window.getSelection()
if (selection) {
selection.removeAllRanges()
}
}
}
onMounted(() => {
bus.on('open-control', openControl)
})
</script>
<style lang="scss"></style>