mirror of
https://github.com/TryGhost/Ghost.git
synced 2024-12-15 11:34:24 +03:00
301e1b2419
refs #9200 - We have not yet counted the images within your html, this commit counts images based on the this algorithm: https://blog.medium.com/read-time-and-you-bc2048ab620c - Added imageCount utility, which counts images using an img-tag regex, amended from the general tag-regex found in wordCount - Added this imageCount to the {{reading_time}} helper, adding 12 seconds to the reading time for every image - The feature image is still counted as before - The first image adds 12 seconds, the second 11, the third 10, and so on - Images from the tenth onwards add 3 seconds to the reading time
63 lines
2.1 KiB
JavaScript
63 lines
2.1 KiB
JavaScript
// # Reading Time Helper
|
|
//
|
|
// Usage: `{{reading_time}}`
|
|
// or for translatable themes, with (t) translation helper's subexpressions:
|
|
// `{{reading_time seconds=(t "< 1 min read") minute=(t "1 min read") minutes=(t "% min read")}}`
|
|
// and in the theme translation file, for example Spanish es.json:
|
|
// "< 1 min read": "< 1 min de lectura",
|
|
// "1 min read": "1 min de lectura",
|
|
// "% min read": "% min de lectura",
|
|
//
|
|
// Returns estimated reading time for post
|
|
|
|
var proxy = require('./proxy'),
|
|
_ = require('lodash'),
|
|
schema = require('../data/schema').checks,
|
|
SafeString = proxy.SafeString,
|
|
localUtils = proxy.localUtils;
|
|
|
|
module.exports = function reading_time(options) {// eslint-disable-line camelcase
|
|
options = options || {};
|
|
options.hash = options.hash || {};
|
|
|
|
var html,
|
|
wordsPerMinute = 275,
|
|
wordsPerSecond = wordsPerMinute / 60,
|
|
wordCount,
|
|
imageCount,
|
|
readingTimeSeconds,
|
|
readingTimeMinutes,
|
|
readingTime,
|
|
seconds = _.isString(options.hash.seconds) ? options.hash.seconds : '< 1 min read',
|
|
minute = _.isString(options.hash.minute) ? options.hash.minute : '1 min read',
|
|
minutes = _.isString(options.hash.minutes) ? options.hash.minutes : '% min read';
|
|
|
|
// only calculate reading time for posts
|
|
if (!schema.isPost(this)) {
|
|
return null;
|
|
}
|
|
|
|
html = this.html;
|
|
imageCount = this.feature_image ? 1 : 0;
|
|
imageCount += localUtils.imageCount(html);
|
|
wordCount = localUtils.wordCount(html);
|
|
readingTimeSeconds = wordCount / wordsPerSecond;
|
|
|
|
for (var i = 12; i > 12 - imageCount; i -= 1) {
|
|
// add 12 seconds for the first image, 11 for the second, etc. limiting at 3
|
|
readingTimeSeconds += Math.max(i, 3);
|
|
}
|
|
|
|
readingTimeMinutes = Math.round(readingTimeSeconds / 60);
|
|
|
|
if (readingTimeSeconds < 60) {
|
|
readingTime = seconds;
|
|
} else if (readingTimeMinutes === 1) {
|
|
readingTime = minute;
|
|
} else {
|
|
readingTime = minutes.replace('%', readingTimeMinutes);
|
|
}
|
|
|
|
return new SafeString(readingTime);
|
|
};
|