import sanitizeHtml from 'sanitize-html'

export const sanitizeHtmlCustom = (data: string, baseURI?: string) =>
  sanitizeHtml(data, {
    // allows specific tags
    allowedTags: [
      'address',
      'article',
      'aside',
      'footer',
      'header',
      'h1',
      'h2',
      'h3',
      'h4',
      'h5',
      'h6',
      'hgroup',
      'main',
      'nav',
      'section',
      'blockquote',
      'dd',
      'div',
      'dl',
      'dt',
      'figcaption',
      'figure',
      'hr',
      'li',
      'main',
      'ol',
      'p',
      'pre',
      'ul',
      'a',
      'abbr',
      'b',
      'bdi',
      'bdo',
      'br',
      'cite',
      'code',
      'data',
      'dfn',
      'em',
      'i',
      'kbd',
      'mark',
      'q',
      'rb',
      'rp',
      'rt',
      'rtc',
      'ruby',
      's',
      'samp',
      'small',
      'span',
      'strong',
      'sub',
      'sup',
      'time',
      'u',
      'var',
      'wbr',
      'caption',
      'col',
      'colgroup',
      'table',
      'tbody',
      'td',
      'tfoot',
      'th',
      'thead',
      'tr',
      'video',
      'img',
    ],
    // specific filters, they're exclusive, if true then remove the tag
    exclusiveFilter(frame) {
      // remove images and videos that point to external domains
      if (frame.tag === 'video' || frame.tag === 'img') {
        const url = (
          frame.attribs as unknown as HTMLImageElement & HTMLVideoElement
        )['src']

        // source: https://stackoverflow.com/a/57047786

        const local = new URL(baseURI ?? document.baseURI)
        const remote = new URL(url, baseURI ?? document.baseURI)
        const isNotRelative =
          local.origin !== local.origin || local.hostname !== remote.hostname
        if (isNotRelative) {
          console.error(
            'A rendered img/video tag contains an external url in enclosed HTML code:',
            data
          )
        }
        return isNotRelative
      }

      // if other specific parameters won't pass,
      return false
    },
  })
