Skip to content

Commit

Permalink
Merge pull request #12 from motea927/dev
Browse files Browse the repository at this point in the history
feat: use reactivity value
  • Loading branch information
motea927 authored Jun 13, 2023
2 parents e39b5ab + 618b446 commit 09ed06d
Showing 1 changed file with 30 additions and 16 deletions.
46 changes: 30 additions & 16 deletions packages/core/directive.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { Directive } from 'vue'
import { watchEffect } from 'vue'
import type { BindingObj, Options } from './shared'
import {
getDefaultString,
Expand All @@ -14,25 +15,38 @@ export type SafeHtmlDirective = Directive<
string | (() => string) | BindingObj
>

export const vSafeHtml: SafeHtmlDirective = (el, binding) => {
if (!binding.value) return
const stopWatchMap = new WeakMap<HTMLElement, () => void>()

const bindingValue = getBindingValue(binding.value)
const defaultString =
typeof binding.value === 'string' || typeof binding.value === 'function'
? getDefaultString()
: getDefaultString(binding.value.defaultString)
const sanitizeConfig =
typeof binding.value === 'string' || typeof binding.value === 'function'
? undefined
: binding.value.sanitizeConfig
export const vSafeHtml: SafeHtmlDirective = {
beforeMount(el, binding) {
const stopWatch = watchEffect(() => {
if (!binding.value) return

if (handleDefaultString(el, bindingValue, defaultString, sanitizeConfig)) {
return
}
const bindingValue = getBindingValue(binding.value)
const defaultString =
typeof binding.value === 'string' || typeof binding.value === 'function'
? getDefaultString()
: getDefaultString(binding.value.defaultString)
const sanitizeConfig =
typeof binding.value === 'string' || typeof binding.value === 'function'
? undefined
: binding.value.sanitizeConfig

if (
handleDefaultString(el, bindingValue, defaultString, sanitizeConfig)
) {
return
}

const sanitizeResult = sanitizeHtml(bindingValue, sanitizeConfig)
el.innerHTML = sanitizeResult
const sanitizeResult = sanitizeHtml(bindingValue, sanitizeConfig)
el.innerHTML = sanitizeResult
})
stopWatchMap.set(el, stopWatch)
},
beforeUnmount(el) {
stopWatchMap.get(el)?.()
stopWatchMap.delete(el)
}
}

export const createDirective = (options?: Options) => {
Expand Down

0 comments on commit 09ed06d

Please sign in to comment.