-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtokenizer.js
99 lines (98 loc) · 3.18 KB
/
tokenizer.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
var TextTokenizer = {
getWordDelimiters: [
" ", "\n", "\t", ".", ",", "?", ":", ";", "!", "-", "/"
],
getWords({fullText}){
const wordTokens = [];
if(fullText){
let currentWord = "";
let delimiter = "";
fullText.split("").forEach((currentLetter) => {
if(TextTokenizer.getWordDelimiters.indexOf(currentLetter) > -1){
delimiter += currentLetter
if(currentWord) {
wordTokens.push({currentWord});
currentWord = ""
}
} else {
if(delimiter){
wordTokens.push({
currentWord: delimiter
});
delimiter = ""
}
currentWord += currentLetter;
}
})
if(currentWord){
wordTokens.push({currentWord});
} else if(delimiter) {
wordTokens.push({
currentWord: delimiter
});
}
}
return wordTokens;
},
getWordWidth(attrs) {
const {
currentWord, fontFamily, fontSize, isBold, isItalic
} = attrs;
const canvas = document.getElementById("text-tokenizer-canvas");
const context = canvas.getContext("2d");
let font = "";
if(isBold){
font += "bold ";
}
if(isItalic) {
font += "italic ";
}
if(fontSize) {
font += fontSize + " ";
}
if(fontFamily) {
// if(/^\s+$/.test(currentWord)){
// font += "Times New Roman";
// } else {
// font += fontFamily;
// }
font += fontFamily;
}
context.font = font;
const metrics = context.measureText(currentWord);
if(/^\s+$/.test(currentWord)){
attrs.width = Math.ceil(metrics.width);
} else {
attrs.width = Math.round(metrics.width);
}
// attrs.height = Math.round(metrics.height);
return attrs;
},
breakByWidth({wordTokens, width}) {
const widthDivision = [];
let tempWidthCollection = [];
let currentWidth = 0;
wordTokens.forEach(wordToken => {
let tempWidth = currentWidth + wordToken.width;
if(tempWidth > width){
widthDivision.push(tempWidthCollection);
tempWidthCollection = [wordToken];
currentWidth = wordToken.width;
} else if (tempWidth == width) {
tempWidthCollection.push(wordToken);
widthDivision.push(tempWidthCollection);
tempWidthCollection = [];
currentWidth = 0;
} else {
currentWidth = tempWidth;
tempWidthCollection.push(wordToken);
}
})
if(tempWidthCollection.length){
widthDivision.push(tempWidthCollection);
}
return widthDivision;
}
}
export default TextTokenizer;
window.TextTokenizer = TextTokenizer;