- const { server, site, option } = theme.artalk
- const avatarCdn = (option !== null && option.gravatar && option.gravatar.mirror) || ''
- const avatarDefault = (option !== null && option.gravatar && (option.gravatar.params || option.gravatar.default)) || ''

script.
  window.addEventListener('load', () => {
    const keyName = 'artalk-newest-comments'

    const changeContent = (content) => {
      if (content === '') return content

      content = content.replace(/<img.*?src="(.*?)"?[^\>]+>/ig, '[!{_p("aside.card_newest_comments.image")}]') // replace image link
      content = content.replace(/<a[^>]+?href=["']?([^"']+)["']?[^>]*>([^<]+)<\/a>/gi, '[!{_p("aside.card_newest_comments.link")}]') // replace url
      content = content.replace(/<pre><code>.*?<\/pre>/gi, '[!{_p("aside.card_newest_comments.code")}]') // replace code
      content = content.replace(/<[^>]+>/g,"") // remove html tag

      if (content.length > 150) {
        content = content.substring(0,150) + '...'
      }
      return content
    }

    const generateHtml = array => {
      let result = ''

      if (array.length) {
        for (let i = 0; i < array.length; i++) {
          result += '<div class=\'aside-list-item\'>'

          if (!{theme.newest_comments.avatar}) {
            const name = '!{theme.lazyload.enable ? "data-lazy-src" : "src"}'
            result += `<a href='${array[i].url}' class='thumbnail'><img ${name}='${array[i].avatar}' alt='${array[i].nick}'></a>`
          }

          result += `<div class='content'>
          <a class='comment' href='${array[i].url}' title='${array[i].content}'>${array[i].content}</a>
          <div class='name'><span>${array[i].nick} / </span><time datetime="${array[i].date}">${anzhiyu.diffDate(array[i].date, true)}</time></div>
          </div></div>`
        }
      } else {
        result += '!{_p("aside.card_newest_comments.zero")}'
      }

      let $dom = document.querySelector('#card-newest-comments .aside-list')
      $dom && ($dom.innerHTML= result)
      window.lazyLoadInstance && window.lazyLoadInstance.update()
      window.pjax && window.pjax.refresh($dom)
    }

    const getAvatarValue = async () => {
      const predefinedAvatarCdn = '!{avatarCdn}'
      const predefinedAvatarDefault = '!{avatarDefault}'

      const avatarDefaultFormat = e => e.startsWith('d=') ? e : `d=${e}`

      if (predefinedAvatarCdn && predefinedAvatarDefault) {
        return { avatarCdn: predefinedAvatarCdn, avatarDefault: avatarDefaultFormat(predefinedAvatarDefault) }
      }

      try {
        const res = await fetch('!{server}/api/v2/conf')
        const result = await res.json()
        const { mirror, params, default: defaults } = result.frontend_conf.gravatar
        const avatarCdn = predefinedAvatarCdn || mirror
        let avatarDefault = avatarDefaultFormat(predefinedAvatarDefault || params || defaults)
        return { avatarCdn, avatarDefault}
      } catch (e) {
        console.error(e)
        return { avatarCdn: predefinedAvatarCdn, avatarDefault: avatarDefaultFormat(predefinedAvatarDefault) }
      }
    }

    const searchParams = new URLSearchParams({
      'site_name': '!{site}',
      'limit': '!{theme.newest_comments.limit * 2}', // Fetch more comments to filter pending comments
    })

    const getComment = async () => {
      try {
        const res = await fetch(`!{server}/api/v2/stats/latest_comments?${searchParams}`)
        const result = await res.json()
        const { avatarCdn, avatarDefault } = await getAvatarValue()
        const artalk = result.data
          .filter(e => !e.is_pending) // Filter pending comments
          .slice(0, !{theme.newest_comments.limit}) // Limit the number of comments
          .map(e => {
            const avatar = avatarCdn && e.email_encrypted ? `${avatarCdn}${e.email_encrypted}?${avatarDefault}` : ''
            return {
              'avatar': avatar,
              'content': changeContent(e.content_marked),
              'nick': e.nick,
              'url': e.page_url,
              'date': e.date,
            }
          })
        saveToLocal.set(keyName, JSON.stringify(artalk), !{theme.newest_comments.storage}/(60*24))
        generateHtml(artalk)
      } catch (e) {
        console.log(e)
        const $dom = document.querySelector('#card-newest-comments .aside-list')
        $dom && ($dom.textContent= "!{_p('aside.card_newest_comments.error')}")
      }
    }

    const newestCommentInit = () => {
      if (document.querySelector('#card-newest-comments .aside-list')) {
        const data = saveToLocal.get(keyName)
        if (data) {
          generateHtml(JSON.parse(data))
        } else {
          getComment()
        }
      }
    }

    newestCommentInit()
    document.addEventListener('pjax:complete', newestCommentInit)
  })