-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
55 lines (41 loc) · 1.5 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
'use strict';
import shave from 'shave';
export default function (target, options = {}) {
if (!target) {
throw new Error('`target` is required');
}
if (typeof target === 'string') {
target = document.querySelectorAll(target);
}
const maxLines = options.maxLines || 2;
const className = `${options.classname || 'js-shave'}-text`;
const elements = target instanceof NodeList ? [...target] : [target];
elements.forEach(element => {
const textProp = element.textContent === undefined ? 'innerText' : 'textContent';
let shaveElement = element.querySelector(`.${className}`);
// Reset if we've been here before
if (shaveElement) {
const span = shaveElement.querySelector('.js-shave-char');
// Nuke the ellipsis
if (span) {
shaveElement.removeChild(span);
}
element[textProp] = element[textProp]; // eslint-disable-line no-self-assign
}
// Strip whitespace (textContent does not do whitespace normalization)
const spanText = element[textProp].replace(/[\n\r]+|[\s]{2,}/g, ' ').trim();
const spanHtml = `<span class="${className}">${spanText}</span>`;
element.innerHTML = spanHtml;
shaveElement = element.querySelector(`.${className}`);
const rects = shaveElement.getClientRects();
// Only shave if the text is long enough
if (rects.length > 1 && rects.length > maxLines) {
const rectHeight = rects[1].top - rects[0].top;
const maxHeight = rectHeight * maxLines;
if (maxHeight > 0) {
shave(shaveElement, maxHeight, options);
}
}
});
return elements;
}