2017-11-06 21:40:07 +03:00
|
|
|
// # Reading Time Helper
|
|
|
|
//
|
|
|
|
// Usage: `{{reading_time}}`
|
2018-01-09 16:50:57 +03:00
|
|
|
// 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",
|
2017-11-06 21:40:07 +03:00
|
|
|
//
|
|
|
|
// Returns estimated reading time for post
|
|
|
|
|
|
|
|
var proxy = require('./proxy'),
|
2018-01-09 16:50:57 +03:00
|
|
|
_ = require('lodash'),
|
2017-11-06 21:40:07 +03:00
|
|
|
schema = require('../data/schema').checks,
|
|
|
|
SafeString = proxy.SafeString,
|
2017-12-13 16:05:53 +03:00
|
|
|
localUtils = proxy.localUtils;
|
2017-11-06 21:40:07 +03:00
|
|
|
|
2018-01-09 16:50:57 +03:00
|
|
|
module.exports = function reading_time(options) {// eslint-disable-line camelcase
|
|
|
|
options = options || {};
|
|
|
|
options.hash = options.hash || {};
|
|
|
|
|
2017-11-06 21:40:07 +03:00
|
|
|
var html,
|
|
|
|
wordsPerMinute = 275,
|
|
|
|
wordsPerSecond = wordsPerMinute / 60,
|
|
|
|
wordCount,
|
|
|
|
imageCount,
|
|
|
|
readingTimeSeconds,
|
2018-01-09 16:50:57 +03:00
|
|
|
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';
|
2017-11-06 21:40:07 +03:00
|
|
|
|
|
|
|
// only calculate reading time for posts
|
|
|
|
if (!schema.isPost(this)) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
|
|
|
html = this.html;
|
|
|
|
imageCount = this.feature_image ? 1 : 0;
|
2018-03-05 11:30:15 +03:00
|
|
|
imageCount += localUtils.imageCount(html);
|
2017-12-13 16:05:53 +03:00
|
|
|
wordCount = localUtils.wordCount(html);
|
2017-11-06 21:40:07 +03:00
|
|
|
readingTimeSeconds = wordCount / wordsPerSecond;
|
|
|
|
|
2018-03-05 11:30:15 +03:00
|
|
|
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);
|
|
|
|
}
|
2017-11-06 21:40:07 +03:00
|
|
|
|
2018-01-09 16:50:57 +03:00
|
|
|
readingTimeMinutes = Math.round(readingTimeSeconds / 60);
|
|
|
|
|
2017-11-06 21:40:07 +03:00
|
|
|
if (readingTimeSeconds < 60) {
|
2018-01-09 16:50:57 +03:00
|
|
|
readingTime = seconds;
|
|
|
|
} else if (readingTimeMinutes === 1) {
|
|
|
|
readingTime = minute;
|
2017-11-06 21:40:07 +03:00
|
|
|
} else {
|
2018-01-09 16:50:57 +03:00
|
|
|
readingTime = minutes.replace('%', readingTimeMinutes);
|
2017-11-06 21:40:07 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
return new SafeString(readingTime);
|
|
|
|
};
|