-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathvue-tribute.ts
82 lines (67 loc) · 2.27 KB
/
vue-tribute.ts
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
import { defineComponent, watch, h, onMounted, PropType, onBeforeUnmount, nextTick, Ref, ref, unref } from 'vue'
import Tribute, { TributeOptions } from 'tributejs'
type Maybe<T> = T | undefined
type MaybeRef<T> = T | Ref<T>
interface TributeElement extends HTMLElement {
tributeInstance?: Tribute<any> // eslint-disable-line @typescript-eslint/no-explicit-any
}
export const VueTribute = defineComponent({
name: 'VueTribute',
props: {
options: {
type: Object as PropType<MaybeRef<TributeOptions<any>>>, // eslint-disable-line @typescript-eslint/no-explicit-any
required: true,
},
},
setup(props, context) {
if (typeof Tribute === 'undefined') {
throw new Error('[vue-tribute] cannot locate tributejs.')
}
const root = ref<HTMLElement>()
const el = ref<TributeElement>()
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const attachTribute = (el: Ref<Maybe<TributeElement>>, options: MaybeRef<TributeOptions<any>> = props.options) => {
if (!el.value) return
const tribute = new Tribute(unref(options))
tribute.attach(el.value)
el.value.tributeInstance = tribute
}
onMounted(() => {
el.value = root.value?.childNodes[0] as TributeElement
if (!el.value) {
throw new Error('[vue-tribute] cannot find a suitable element to attach to.')
}
attachTribute(el)
el.value.addEventListener('tribute-replaced', e => {
e.target?.dispatchEvent(new Event('input', { bubbles: true }))
})
})
const detachTribute = (el: Ref<Maybe<TributeElement>>) => {
if (!el.value?.tributeInstance) return
el.value.tributeInstance.detach(el.value)
el.value.tributeInstance = undefined
delete el.value.dataset.tribute
}
onBeforeUnmount(() => {
detachTribute(el)
})
watch(
() => props.options,
async newOptions => {
if (el.value?.tributeInstance) {
await nextTick()
detachTribute(el)
await nextTick()
attachTribute(el, { ...newOptions })
}
},
{ deep: true }
)
return () =>
h(
'div',
{ class: 'v-tribute', ref: root },
[context.slots.default ? context.slots.default()[0] : null].filter(Boolean)
)
},
})