|
4 | 4 |
|
5 | 5 | const sanitizeHtml = require('sanitize-html');
|
6 | 6 | const trunc = require('trunc-html');
|
| 7 | +const { getByDot, setByDot } = require('feathers-hooks-common'); |
| 8 | +const { isEmpty } = require('lodash'); |
7 | 9 |
|
8 | 10 | const sanitizeOptions = {
|
9 |
| - allowedTags: [ 'br' ] |
| 11 | + allowedTags: ['p', 'br', 'a', 'span', 'blockquote'], |
| 12 | + allowedAttributes: { |
| 13 | + a: ['href', 'class', 'target', 'data-*' , 'contenteditable'], |
| 14 | + span: ['contenteditable', 'class', 'data-*'] |
| 15 | + }, |
10 | 16 | };
|
11 | 17 |
|
12 | 18 | module.exports = function (options = {}) { // eslint-disable-line no-unused-vars
|
13 | 19 | return function (hook) {
|
14 | 20 |
|
15 | 21 | options = Object.assign({ length: 120, field: 'content' }, options);
|
16 | 22 |
|
17 |
| - if(!hook.data || !hook.data[options.field]) { |
| 23 | + let content = getByDot(hook.data, options.field); |
| 24 | + |
| 25 | + if(!hook.data || isEmpty(content)) { |
18 | 26 | return hook;
|
19 | 27 | }
|
20 | 28 |
|
21 | 29 | try {
|
22 | 30 | /* eslint no-use-before-define: 0 */ // --> OFF
|
23 |
| - const content = sanitizeHtml(hook.data[options.field], sanitizeOptions) |
| 31 | + let contentSanitized = sanitizeHtml(content, sanitizeOptions) |
24 | 32 | .replace(/\<br\s*\>|\<br\s*\/\>/ig, "\n")
|
25 | 33 | .replace(/(\ ){2,}/ig, ' ')
|
26 | 34 | .trim();
|
27 |
| - hook.data[`${options.field}Excerpt`] = trunc(content, options.length, { |
28 |
| - ignoreTags: ['img', 'script', 'iframe'] |
29 |
| - }).html; |
| 35 | + |
| 36 | + contentBefore = trunc(content, 9999999999); |
| 37 | + const contentTruncated = trunc(contentSanitized, options.length); |
| 38 | + hook.app.debug('contentBefore'); |
| 39 | + hook.app.debug(contentBefore.text.length); |
| 40 | + hook.app.debug('contentTruncated'); |
| 41 | + hook.app.debug(contentTruncated.text.length); |
| 42 | + |
| 43 | + const hasMore = contentBefore.text.length > (contentTruncated.text.length + 20); |
| 44 | + setByDot(hook.data, 'hasMore', hasMore); |
| 45 | + |
| 46 | + // set excerpt |
| 47 | + setByDot(hook.data, `${options.field}Excerpt`, hasMore ? contentTruncated.html : content.replace(/(\ ){2,}/ig, ' ')) |
30 | 48 | } catch (err) {
|
31 |
| - throw new Error('Text content needed!'); |
| 49 | + throw new Error(err); |
32 | 50 | }
|
33 |
| - hook.data[options.field] = hook.data[options.field] |
34 |
| - .replace(/(\ ){2,}/ig, ' ') |
| 51 | + // trim content |
| 52 | + setByDot(hook.data, options.field, content.replace(/(\ ){2,}/ig, ' ')); |
35 | 53 |
|
36 |
| - return Promise.resolve(hook); |
| 54 | + return hook; |
37 | 55 | };
|
38 | 56 | };
|
0 commit comments