Ghost/core/server/helpers/ghost_head.js

207 lines
7.9 KiB
JavaScript
Raw Normal View History

// # Ghost Head Helper
// Usage: `{{ghost_head}}`
//
// Outputs scripts and other assets at the top of a Ghost theme
var proxy = require('./proxy'),
_ = require('lodash'),
debug = require('ghost-ignition').debug('ghost_head'),
getMetaData = proxy.metaData.get,
getAssetUrl = proxy.metaData.getAssetUrl,
escapeExpression = proxy.escapeExpression,
SafeString = proxy.SafeString,
filters = proxy.filters,
logging = proxy.logging,
settingsCache = proxy.settingsCache,
config = proxy.config,
🙇 Blog icon utils and publisher.logo for JSON-LD (#8297) refs #8221, closes #7688, refs #7558 🙇 Improve meta data publisher logo behaviour This is a follow-up PR for #8285. Reasons: The code changes of #8285 caused error messages when falling back to the default `favicon.ico`, as the `image-size` tool doesn't support `ico` files. This PR takes the logic to decide which logo needs to be listed in our schema into a new fn `blog_logo.js`. There we have now three decisions: 1. If we have a publication **logo**, we'll take that one 2. If we have no publication logo, but an **icon** we'll use this one. 3. If we have none of the above things, we fall back to our default `favicon.ico` Additional, we're hard coding image dimensions for whenever the logo is an `.ico` file and built and extra decision to not call `image-size` when the dimension are already given. I will create another follow-up PR, which checks the extension type for the file and offers it as a util. 🛠 Blog icon util refs #7688 Serve functionality around the blog icon in its own util: - getIconDimensions -> async function that takes the filepath of on ico file and returns its dimensions - isIcoImageType -> returns true if file has `.ico` extension - getIconType -> returns icon-type (`x-icon` or `png`) - getIconUrl -> returns the absolut or relativ URL for the favicon: `[subdirectory or not]favicon.[ico or png]` 📖 Get .ico sizes for meta data & logo improvement refs #7558 refs #8221 Use the new `blogIconUtil` in meta data to fetch the dimensions of `.ico` files. Improvements for `publisher.logo`: We're now returning a hard-coded 'faked' image dimensions value to render an `imageObject` and prevent error our schema (Google structured data). As soon as an image (`.ico` or non-`.ico`) is too large, but - in case of non-`.ico` - a square format, be set the image-dimensions to 60px width and height. This reduces the chances of getting constantly error messages from Googles' webmaster tools. - add getIconPath util
2017-04-11 19:32:06 +03:00
blogIconUtils = proxy.blogIcon;
function writeMetaTag(property, content, type) {
type = type || property.substring(0, 7) === 'twitter' ? 'name' : 'property';
return '<meta ' + type + '="' + property + '" content="' + content + '" />';
}
function finaliseStructuredData(metaData) {
var head = [];
_.each(metaData.structuredData, function (content, property) {
if (property === 'article:tag') {
_.each(metaData.keywords, function (keyword) {
if (keyword !== '') {
keyword = escapeExpression(keyword);
head.push(writeMetaTag(property,
escapeExpression(keyword)));
}
});
head.push('');
} else if (content !== null && content !== undefined) {
head.push(writeMetaTag(property,
escapeExpression(content)));
}
});
return head;
}
function getAjaxHelper(clientId, clientSecret) {
return '<script src="' +
getAssetUrl('public/ghost-sdk.js', true) +
'"></script>\n' +
'<script>\n' +
Prep shared API URL util for use on external sites refs #5942, #6150 There were a few key problems I was looking to solve with this: - Introduce a single point of truth for what the URL for accessing the API should be - Provide a simple way to configure the utility (much like a true SDK) As of this commit, this utility is still automatically available in a Ghost theme. To use it on an external site, the code would look like: ``` <script type="text/javascript" src="http://my-ghost-blog.com/shared/ghost-url.min.js"></script> <script type="text/javascript"> ghost.init({ clientId: "<your-client-id>", clientSecret: "<your-client-secret>" }); </script> ``` To achieve this, there have been a number of changes: - A new `apiUrl` function has been added to config, which calculates the correct URL. This needs to be unified with the other url generation functions as a separate piece of work. - The serveSharedFile middleware has been updated, so that it can serve files from / or /shared and to substitute `{{api-url}}` as it does `{{blog-url}}`. - ghost-url.js and ghost-url.min.js have been updated to be served via the serveSharedFile middleware - ghost-url.js has been changed slightly, to take the url from an inline variable which is substituted the first time it is served - `{{ghost_head}}` has been updated, removing the api url handling which is now in config/url.js and removing the configuration of the utility in favour of calling `init()` after the script is required - `{{ghost_head}}` has also had the meta tags for client id and secret removed - tests have been updated
2015-12-15 13:41:53 +03:00
'ghost.init({\n' +
'\tclientId: "' + clientId + '",\n' +
'\tclientSecret: "' + clientSecret + '"\n' +
'});\n' +
'</script>';
}
/**
* **NOTE**
* Express adds `_locals`, see https://github.com/expressjs/express/blob/4.15.4/lib/response.js#L962.
* But `options.data.root.context` is available next to `root._locals.context`, because
* Express creates a `renderOptions` object, see https://github.com/expressjs/express/blob/4.15.4/lib/application.js#L554
* and merges all locals to the root of the object. Very confusing, because the data is available in different layers.
*
* Express forwards the data like this to the hbs engine:
* {
* post: {}, - res.render('view', databaseResponse)
* context: ['post'], - from res.locals
* safeVersion: '1.x', - from res.locals
* _locals: {
* context: ['post'],
* safeVersion: '1.x'
* }
* }
*
* hbs forwards the data to any hbs helper like this
* {
* data: {
* blog: {},
* labs: {},
* config: {},
* root: {
* post: {},
* context: ['post'],
* locals: {...}
* }
* }
*
* `blog`, `labs` and `config` are the templateOptions, search for `hbs.updateTemplateOptions` in the code base.
* Also see how the root object gets created, https://github.com/wycats/handlebars.js/blob/v4.0.6/lib/handlebars/runtime.js#L259
*/
// We use the name ghost_head to match the helper for consistency:
module.exports = function ghost_head(options) { // eslint-disable-line camelcase
debug('begin');
// if server error page do nothing
if (options.data.root.statusCode >= 500) {
return;
}
var head = [],
dataRoot = options.data.root,
context = dataRoot._locals.context ? dataRoot._locals.context : null,
client = dataRoot._locals.client,
safeVersion = dataRoot._locals.safeVersion,
postCodeInjection = dataRoot && dataRoot.post ? dataRoot.post.codeinjection_head : null,
globalCodeinjection = settingsCache.get('ghost_head'),
useStructuredData = !config.isPrivacyDisabled('useStructuredData'),
referrerPolicy = config.get('referrerPolicy') ? config.get('referrerPolicy') : 'no-referrer-when-downgrade',
🙇 Blog icon utils and publisher.logo for JSON-LD (#8297) refs #8221, closes #7688, refs #7558 🙇 Improve meta data publisher logo behaviour This is a follow-up PR for #8285. Reasons: The code changes of #8285 caused error messages when falling back to the default `favicon.ico`, as the `image-size` tool doesn't support `ico` files. This PR takes the logic to decide which logo needs to be listed in our schema into a new fn `blog_logo.js`. There we have now three decisions: 1. If we have a publication **logo**, we'll take that one 2. If we have no publication logo, but an **icon** we'll use this one. 3. If we have none of the above things, we fall back to our default `favicon.ico` Additional, we're hard coding image dimensions for whenever the logo is an `.ico` file and built and extra decision to not call `image-size` when the dimension are already given. I will create another follow-up PR, which checks the extension type for the file and offers it as a util. 🛠 Blog icon util refs #7688 Serve functionality around the blog icon in its own util: - getIconDimensions -> async function that takes the filepath of on ico file and returns its dimensions - isIcoImageType -> returns true if file has `.ico` extension - getIconType -> returns icon-type (`x-icon` or `png`) - getIconUrl -> returns the absolut or relativ URL for the favicon: `[subdirectory or not]favicon.[ico or png]` 📖 Get .ico sizes for meta data & logo improvement refs #7558 refs #8221 Use the new `blogIconUtil` in meta data to fetch the dimensions of `.ico` files. Improvements for `publisher.logo`: We're now returning a hard-coded 'faked' image dimensions value to render an `imageObject` and prevent error our schema (Google structured data). As soon as an image (`.ico` or non-`.ico`) is too large, but - in case of non-`.ico` - a square format, be set the image-dimensions to 60px width and height. This reduces the chances of getting constantly error messages from Googles' webmaster tools. - add getIconPath util
2017-04-11 19:32:06 +03:00
favicon = blogIconUtils.getIconUrl(),
iconType = blogIconUtils.getIconType(favicon);
✨ [FEATURE] AMP⚡ (#7229) closes #6588, #7095 * `ImageObject` with image dimensions (#7152, #7151, #7153) - Returns meta data as promise - returns a new Promise from meta data - uses `Promise.props()` to resolve `getClient()` and `getMetaData()` - Adds 'image-size' util The util returns an object like this ``` { height: 50, url: 'http://myblog.com/images/cat.jpg', width: 50 }; ``` if the dimensions can be fetched and rejects with error, if not. In case we get a locally stored image or a not complete url (like `//www.gravatar.com/andsoon`), we add the protocol to the incomplete one and use `urlFor()` to get the absolute URL. If the request fails or `image-size` is not able to read the file, we reject with error. - adds 'image-size' module to dependencies - adds `getImageSizeFromUrl` function that returns image dimensions - In preparation of AMP support and to improve our schema.org JSON-LD and structured data, I made the following changes: - Changes the following properties to be `Objects`, which have a `url` property by default and a `dimensions` property, if `width` and `height` are available: - `metaData.coverImage` - `metaData.authorImage` - `metaData.blog.logo` - Checks cache by calling `getCachedImageSizeFromUrl`. If image dimensions were fetched already, returns them from cache instead of fetching them again. - If we have image dimensions on hand, the output in our JSON-LD changes from normal urls to be full `ImageObjects`. Applies to all images and logos. - Special case for `publisher.logo` as it has size restrictions: if the image doesn't fulfil the restrictions (<=600 width and <=60 height), we simply output the url instead, so like before. - Adds new property for schema.org JSON-LD: `mainEntityOfPage` as an Object. - Adds additional Open Graph data (if we have the image size): `og:image:width` and `og:image:height` - Adds/updates tests * AMP router and controller (#7171, #7157) Implements AMP in `/apps/`: - renders `amp.hbs` if route is `/:slug/amp/` - updates `setResponseContext` to set context to `['amp', 'post']` for a amp post and `['amp', 'page']` for a page, but will not render amp template for a page - updates `context_spec` - registers 'amp' as new internal app - adds the `amp.hbs` template to `core/server/apps/amp` which will be the default template for AMP posts. - adds `isAmpURL` to `post-lookup` * 🎨 Use `context` in meta as array (#7205) Instead of reading the first value of the context array, we're checking if it includes certain context values. This is a preparation change for AMP, where the context will be delivered as `['amp', 'post']`. * ✨ AMP helpers (#7174, #7216, #7215, #7223) - Adds AMP helpers `{{amp_content}}`, `{{amp_component}}` and `{{amp_ghost_head}}` to support AMP: - `{{amp_content}}`: - Adds `Amperize` as dependency - AMP app uses new helper `{{amp_content}}` to render AMP HTML - `Amperize` transforms regular HTML into AMP HTML - Adds test for `{{amp_content}}` helper - Adds 'Sanitize-HTML` as dependendy - After the HTML get 'amperized' we still might have some HTML tags, which are prohibited in AMP HTML, so we use `sanitize-html` to remove those. With every update, `Amperize` gets and it is able to transform more HTML tags, they valid AMP HTML tags (e. g. `video` and `amp-video`) and will therefore not be removed. - `{{amp_ghost_head}}`: - registers `{{amp_ghost_head}}` helper, but uses `{{ghost_head}}` code - uses `{{amp_ghost_head}}` in `amp.hbs` instead of `{{ghost_head}}` - `{{ghost_head}}`: - Render `amphtml` link in metadata for post, which links to the amp post (`getAmpUrl`) - Updates all test in metadata to support `amp` context - Changes context conditionals to work with full array instead of first array value - Adds conditionals, so no additional javascript gets rendered in `{{ghost_head}}` - Removes trailing `/amp/` in URLs, so only `amphtml` link on regular post renders it - Adds a conditional, so no code injection will be included, for an `amp` context. - `{{amp_components}}`: - AMP app uses new helper `{{amp_components}}` to render necessary script tags for AMP extended components as `amp-iframe`, `amp-anime` and `amp-form` - Adds test for `{{amp_components}}`
2016-08-22 19:49:27 +03:00
debug('preparation complete, begin fetch');
/**
* @TODO:
* - getMetaData(dataRoot, dataRoot) -> yes that looks confusing!
* - there is a very mixed usage of `data.context` vs. `root.context` vs `root._locals.context` vs. `this.context`
* - NOTE: getMetaData won't live here anymore soon, see https://github.com/TryGhost/Ghost/issues/8995
* - therefor we get rid of using `getMetaData(this, dataRoot)`
* - dataRoot has access to *ALL* locals, see function description
* - it should not break anything
*/
return getMetaData(dataRoot, dataRoot)
.then(function handleMetaData(metaData) {
debug('end fetch');
if (context) {
// head is our main array that holds our meta data
if (metaData.metaDescription && metaData.metaDescription.length > 0) {
head.push('<meta name="description" content="' + escapeExpression(metaData.metaDescription) + '" />');
}
head.push('<link rel="shortcut icon" href="' + favicon + '" type="image/' + iconType + '" />');
head.push('<link rel="canonical" href="' +
escapeExpression(metaData.canonicalUrl) + '" />');
head.push('<meta name="referrer" content="' + referrerPolicy + '" />');
// don't allow indexing of preview URLs!
if (_.includes(context, 'preview')) {
head.push(writeMetaTag('robots', 'noindex,nofollow', 'name'));
}
// show amp link in post when 1. we are not on the amp page and 2. amp is enabled
if (_.includes(context, 'post') && !_.includes(context, 'amp') && settingsCache.get('amp')) {
head.push('<link rel="amphtml" href="' +
escapeExpression(metaData.ampUrl) + '" />');
}
✨ [FEATURE] AMP⚡ (#7229) closes #6588, #7095 * `ImageObject` with image dimensions (#7152, #7151, #7153) - Returns meta data as promise - returns a new Promise from meta data - uses `Promise.props()` to resolve `getClient()` and `getMetaData()` - Adds 'image-size' util The util returns an object like this ``` { height: 50, url: 'http://myblog.com/images/cat.jpg', width: 50 }; ``` if the dimensions can be fetched and rejects with error, if not. In case we get a locally stored image or a not complete url (like `//www.gravatar.com/andsoon`), we add the protocol to the incomplete one and use `urlFor()` to get the absolute URL. If the request fails or `image-size` is not able to read the file, we reject with error. - adds 'image-size' module to dependencies - adds `getImageSizeFromUrl` function that returns image dimensions - In preparation of AMP support and to improve our schema.org JSON-LD and structured data, I made the following changes: - Changes the following properties to be `Objects`, which have a `url` property by default and a `dimensions` property, if `width` and `height` are available: - `metaData.coverImage` - `metaData.authorImage` - `metaData.blog.logo` - Checks cache by calling `getCachedImageSizeFromUrl`. If image dimensions were fetched already, returns them from cache instead of fetching them again. - If we have image dimensions on hand, the output in our JSON-LD changes from normal urls to be full `ImageObjects`. Applies to all images and logos. - Special case for `publisher.logo` as it has size restrictions: if the image doesn't fulfil the restrictions (<=600 width and <=60 height), we simply output the url instead, so like before. - Adds new property for schema.org JSON-LD: `mainEntityOfPage` as an Object. - Adds additional Open Graph data (if we have the image size): `og:image:width` and `og:image:height` - Adds/updates tests * AMP router and controller (#7171, #7157) Implements AMP in `/apps/`: - renders `amp.hbs` if route is `/:slug/amp/` - updates `setResponseContext` to set context to `['amp', 'post']` for a amp post and `['amp', 'page']` for a page, but will not render amp template for a page - updates `context_spec` - registers 'amp' as new internal app - adds the `amp.hbs` template to `core/server/apps/amp` which will be the default template for AMP posts. - adds `isAmpURL` to `post-lookup` * 🎨 Use `context` in meta as array (#7205) Instead of reading the first value of the context array, we're checking if it includes certain context values. This is a preparation change for AMP, where the context will be delivered as `['amp', 'post']`. * ✨ AMP helpers (#7174, #7216, #7215, #7223) - Adds AMP helpers `{{amp_content}}`, `{{amp_component}}` and `{{amp_ghost_head}}` to support AMP: - `{{amp_content}}`: - Adds `Amperize` as dependency - AMP app uses new helper `{{amp_content}}` to render AMP HTML - `Amperize` transforms regular HTML into AMP HTML - Adds test for `{{amp_content}}` helper - Adds 'Sanitize-HTML` as dependendy - After the HTML get 'amperized' we still might have some HTML tags, which are prohibited in AMP HTML, so we use `sanitize-html` to remove those. With every update, `Amperize` gets and it is able to transform more HTML tags, they valid AMP HTML tags (e. g. `video` and `amp-video`) and will therefore not be removed. - `{{amp_ghost_head}}`: - registers `{{amp_ghost_head}}` helper, but uses `{{ghost_head}}` code - uses `{{amp_ghost_head}}` in `amp.hbs` instead of `{{ghost_head}}` - `{{ghost_head}}`: - Render `amphtml` link in metadata for post, which links to the amp post (`getAmpUrl`) - Updates all test in metadata to support `amp` context - Changes context conditionals to work with full array instead of first array value - Adds conditionals, so no additional javascript gets rendered in `{{ghost_head}}` - Removes trailing `/amp/` in URLs, so only `amphtml` link on regular post renders it - Adds a conditional, so no code injection will be included, for an `amp` context. - `{{amp_components}}`: - AMP app uses new helper `{{amp_components}}` to render necessary script tags for AMP extended components as `amp-iframe`, `amp-anime` and `amp-form` - Adds test for `{{amp_components}}`
2016-08-22 19:49:27 +03:00
if (metaData.previousUrl) {
head.push('<link rel="prev" href="' +
escapeExpression(metaData.previousUrl) + '" />');
}
if (metaData.nextUrl) {
head.push('<link rel="next" href="' +
escapeExpression(metaData.nextUrl) + '" />');
}
if (!_.includes(context, 'paged') && useStructuredData) {
head.push('');
head.push.apply(head, finaliseStructuredData(metaData));
head.push('');
if (metaData.schema) {
head.push('<script type="application/ld+json">\n' +
JSON.stringify(metaData.schema, null, ' ') +
'\n </script>\n');
}
}
if (client && client.id && client.secret && !_.includes(context, 'amp')) {
head.push(getAjaxHelper(client.id, client.secret));
}
}
head.push('<meta name="generator" content="Ghost ' +
escapeExpression(safeVersion) + '" />');
head.push('<link rel="alternate" type="application/rss+xml" title="' +
escapeExpression(metaData.blog.title) + '" href="' +
escapeExpression(metaData.rssUrl) + '" />');
// no code injection for amp context!!!
if (!_.includes(context, 'amp')) {
if (!_.isEmpty(globalCodeinjection)) {
head.push(globalCodeinjection);
}
if (!_.isEmpty(postCodeInjection)) {
head.push(postCodeInjection);
}
}
return filters.doFilter('ghost_head', head);
})
.then(function afterFilters(head) {
debug('end');
return new SafeString(head.join('\n ').trim());
})
.catch(function handleError(err) {
logging.error(err);
// Return what we have so far (currently nothing)
return new SafeString(head.join('\n ').trim());
});
};