chore(copyright): 2024
[curben-blog.git] / themes / chameleon / scripts / openGraph.js
blobe21a8d8272f9f418ac00346a59d0f5f2484985fe
1 'use strict'
2 /* global hexo */
4 /*
5 * Modified from the hexo version,
6 * https://github.com/hexojs/hexo/blob/master/lib/plugins/helper/open_graph.js
7 * to include https://github.com/hexojs/hexo/pull/3674
8 * and use WHATWG URL API
9 * https://nodejs.org/api/url.html#url_the_whatwg_url_api
12 const moment = require('moment')
13 const { escapeHTML, htmlTag, prettyUrls, stripHTML } = require('hexo-util')
14 const fullUrlFor = require('hexo-util').full_url_for
16 function meta (name, content) {
17   return `${htmlTag('meta', {
18     name,
19     content
20   })}\n`
23 function og (name, content) {
24   return `${htmlTag('meta', {
25     property: name,
26     content
27   })}\n`
30 function openGraphHelper () {
31   const { config, page } = this
32   let description = page.excerpt || ''
33   const author = config.author
34   const keywords = page.tags || ''
35   const title = page.title || config.title || ''
36   const type = (this.is_post() ? 'article' : 'website')
37   const url = prettyUrls(this.url, config.pretty_urls)
38   const screenshot = '/screenshot/' + prettyUrls(this.path, config.pretty_urls)
39   const siteName = config.title || ''
40   const published = page.date || ''
41   const updated = page.updated || ''
42   const language = config.language.replace('-', '_')
43   let result = ''
45   if (description) {
46     description = escapeHTML(stripHTML(description)
47       .trim()
48       .replace(/\n/g, ' ')
49       .substring(0, 200))
51     result += meta('description', description)
52   }
54   result += og('article:author', author)
56   if (keywords) {
57     keywords.forEach(tag => {
58       result += og('article:tag', tag.name)
59     })
60   }
62   result += og('og:type', type)
63   result += og('og:title', title)
64   result += og('og:url', url)
66   if (siteName) {
67     result += og('og:site_name', siteName)
68   }
70   if (description) {
71     result += og('og:description', description)
72   }
74   result += og('og:locale', language)
76   result += og('og:image', fullUrlFor.call(this, screenshot))
78   if (published) {
79     if ((moment.isMoment(published) || moment.isDate(published)) && !isNaN(published.valueOf())) {
80       // Skip timezone conversion
81       result += og('article:published_time', moment(published).format('YYYY-MM-DD[T00:00:00.000Z]'))
82     }
83   }
85   if (updated) {
86     if ((moment.isMoment(updated) || moment.isDate(updated)) && !isNaN(updated.valueOf())) {
87       result += og('article:modified_time', moment(updated).format('YYYY-MM-DD[T00:00:00.000Z]'))
88     }
89   }
91   return result.trim()
94 hexo.extend.helper.register('openGraph', openGraphHelper)