-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
layoutText.js
84 lines (73 loc) · 1.96 KB
/
layoutText.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import layoutEngine, {
bidi,
linebreaker,
justification,
scriptItemizer,
wordHyphenation,
textDecoration,
} from '@react-pdf/textkit';
import fontSubstitution from './fontSubstitution';
import getAttributedString from './getAttributedString';
const engines = {
bidi,
linebreaker,
justification,
textDecoration,
scriptItemizer,
wordHyphenation,
fontSubstitution,
};
const engine = layoutEngine(engines);
const getMaxLines = (node) => node.style?.maxLines;
const getTextOverflow = (node) => node.style?.textOverflow;
/**
* Get layout container for specific text node
*
* @param {number} width
* @param {number} height
* @param {Object} node
* @returns {Object} layout container
*/
const getContainer = (width, height, node) => {
const maxLines = getMaxLines(node);
const textOverflow = getTextOverflow(node);
return {
x: 0,
y: 0,
width,
maxLines,
height: height || Infinity,
truncateMode: textOverflow,
};
};
/**
* Get text layout options for specific text node
*
* @param {Object} node instance
* @returns {Object} layout options
*/
const getLayoutOptions = (fontStore, node) => ({
hyphenationPenalty: node.props.hyphenationPenalty,
shrinkWhitespaceFactor: { before: -0.5, after: -0.5 },
hyphenationCallback:
node.props.hyphenationCallback ||
fontStore?.getHyphenationCallback() ||
null,
});
/**
* Get text lines for given node
*
* @param {Object} node node
* @param {number} width container width
* @param {number} height container height
* @param {number} fontStore font store
* @returns {Object[]} layout lines
*/
const layoutText = (node, width, height, fontStore) => {
const attributedString = getAttributedString(fontStore, node);
const container = getContainer(width, height, node);
const options = getLayoutOptions(fontStore, node);
const lines = engine(attributedString, container, options);
return lines.reduce((acc, line) => [...acc, ...line], []);
};
export default layoutText;