]> git.kianting.info Git - clo/blob - src/libclo/index.js
9d9e8a8ccad312a1d0ac40bbc6c07e02c4e83970
[clo] / src / libclo / index.js
1 "use strict";
2 var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3 if (k2 === undefined) k2 = k;
4 var desc = Object.getOwnPropertyDescriptor(m, k);
5 if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6 desc = { enumerable: true, get: function() { return m[k]; } };
7 }
8 Object.defineProperty(o, k2, desc);
9 }) : (function(o, m, k, k2) {
10 if (k2 === undefined) k2 = k;
11 o[k2] = m[k];
12 }));
13 var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14 Object.defineProperty(o, "default", { enumerable: true, value: v });
15 }) : function(o, v) {
16 o["default"] = v;
17 });
18 var __importStar = (this && this.__importStar) || function (mod) {
19 if (mod && mod.__esModule) return mod;
20 var result = {};
21 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22 __setModuleDefault(result, mod);
23 return result;
24 };
25 var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27 return new (P || (P = Promise))(function (resolve, reject) {
28 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31 step((generator = generator.apply(thisArg, _arguments || [])).next());
32 });
33 };
34 Object.defineProperty(exports, "__esModule", { value: true });
35 exports.Clo = exports.calculateTextWidthHeightAux = exports.calculateTextWidthHeight = exports.hyphenTkTree = exports.filterEmptyString = exports.spacesToBreakpoint = exports.hyphenForClo = exports.splitCJKV = exports.twoReturnsToNewline = exports.ptToPx = exports.cjkvRegexPattern = exports.cjkvBlocksInRegex = exports.defaultFrameStyle = exports.defaultTextStyle = exports.A4_IN_PX = exports.Direction = void 0;
36 const canva_1 = require("../canva");
37 const fontkit = __importStar(require("fontkit"));
38 const breakLines = __importStar(require("./breakLines"));
39 const PDFDocument = require('pdfkit');
40 const fs = __importStar(require("fs"));
41 /**
42 * TYPES
43 */
44 /**
45 * text direction
46 * LTR - left to right
47 * TTB - top to bottom
48 * etc.
49 */
50 var Direction;
51 (function (Direction) {
52 Direction[Direction["LTR"] = 0] = "LTR";
53 Direction[Direction["RTL"] = 1] = "RTL";
54 Direction[Direction["TTB"] = 2] = "TTB";
55 Direction[Direction["BTT"] = 3] = "BTT";
56 })(Direction || (exports.Direction = Direction = {}));
57 /**
58 * DEFAULT CONST PART
59 */
60 exports.A4_IN_PX = { "width": 793.7,
61 "height": 1122.5 };
62 exports.defaultTextStyle = {
63 family: "FreeSerif",
64 size: ptToPx(12),
65 textWeight: canva_1.TextWeight.REGULAR,
66 fontStyle: canva_1.FontStyle.ITALIC,
67 };
68 exports.defaultFrameStyle = {
69 directionInsideLine: Direction.LTR,
70 direction: Direction.TTB,
71 baseLineskip: ptToPx(15),
72 textStyle: exports.defaultTextStyle,
73 x: exports.A4_IN_PX.width * 0.10,
74 y: exports.A4_IN_PX.height * 0.10,
75 width: exports.A4_IN_PX.width * 0.80,
76 height: exports.A4_IN_PX.height * 0.80,
77 content: null,
78 };
79 /**
80 * definition for cjk scripts
81 * - Hani : Han Character
82 * - Hang : Hangul
83 * - Bopo : Bopomofo
84 * - Kana : Katakana
85 * - Hira : Hiragana
86 */
87 exports.cjkvBlocksInRegex = ["Hani", "Hang", "Bopo", "Kana", "Hira"];
88 exports.cjkvRegexPattern = new RegExp("((?:" +
89 exports.cjkvBlocksInRegex.map((x) => "\\p{Script_Extensions=" + x + "}").join("|") + ")+)", "gu");
90 /**
91 * FUNCTION PART
92 */
93 /**
94 * convert from ptToPx
95 * @param pt pt size value
96 * @returns the corresponding px value
97 */
98 function ptToPx(pt) {
99 return pt * 4.0 / 3.0;
100 }
101 exports.ptToPx = ptToPx;
102 /**
103 * REGISTER PART
104 */
105 /**
106 * convert '\n\n' to newline command ["nl"]
107 * @param arr the input `tkTree`
108 * @param clo the `Clo` object
109 * @returns the input tktree
110 */
111 function twoReturnsToNewline(arr, clo) {
112 var middle = [];
113 for (let i = 0; i < arr.length; i++) {
114 var item = arr[i];
115 if (!Array.isArray(item)) {
116 middle = middle.concat(item.split(/(\n\n)/g));
117 }
118 else {
119 middle.push(item);
120 }
121 }
122 var result = [];
123 for (let j = 0; j < middle.length; j++) {
124 var item = middle[j];
125 if (!Array.isArray(item) && item == "\n\n") {
126 result.push(["nl"]); // push a newline command to the result `tkTree`
127 }
128 else {
129 result.push(middle[j]);
130 }
131 }
132 return result;
133 }
134 exports.twoReturnsToNewline = twoReturnsToNewline;
135 /**
136 * split CJKV and non-CJKV
137 *
138 * @param arr : input tkTree
139 * @returns a splitted tkTree (by CJK and NonCJK)
140 * - Examples:
141 * ```
142 * [`many臺中daylight`] => [`many`, `臺中`, `dahylight`]
143 * ```
144 */
145 function splitCJKV(arr, clo) {
146 var result = [];
147 for (let i = 0; i < arr.length; i++) {
148 var item = arr[i];
149 if (!Array.isArray(item)) {
150 result = result.concat(item.split(exports.cjkvRegexPattern));
151 }
152 else {
153 result.push(item);
154 }
155 }
156 return result;
157 }
158 exports.splitCJKV = splitCJKV;
159 /**
160 * hyphenation for a clo document
161 * @param arr the array for a `tkTree`
162 * @param clo the Clo object
163 */
164 function hyphenForClo(arr, clo) {
165 let hyphenLanguage = clo.attrs["hyphenLanguage"];
166 let res = hyphenTkTree(arr, hyphenLanguage);
167 return res;
168 }
169 exports.hyphenForClo = hyphenForClo;
170 /**
171 * convert spaces to Breakpoint
172 * \s+ => ["bp" [\s+] ""]
173 * @param arr the tkTree input text stream
174 * @param clo the Clo object
175 * @returns the converted object
176 */
177 function spacesToBreakpoint(arr, clo) {
178 let spacePattern = /^([ \t]+)$/g;
179 var result = [];
180 for (let i = 0; i < arr.length; i++) {
181 var item = arr[i];
182 if (!Array.isArray(item) && item.match(spacePattern)) {
183 // push a breakpoint command to the result `tkTree`
184 result.push(['bp', [["hglue", "0.1"], item], ""]);
185 }
186 else {
187 result.push(item);
188 }
189 }
190 return result;
191 }
192 exports.spacesToBreakpoint = spacesToBreakpoint;
193 /**
194 * remove all the `` (empty string) in the arr
195 * @param arr the tkTree to be filtered
196 * @param clo the Clo file
197 */
198 function filterEmptyString(arr, clo) {
199 if (Array.isArray(arr)) {
200 arr.filter((x) => { return x != ``; });
201 }
202 return arr;
203 }
204 exports.filterEmptyString = filterEmptyString;
205 /**
206 * OTHER FUNCTIONS
207 */
208 /**
209 * hyphenate for a tkTree
210 * - hyphenation => ["bp", "", "-"]
211 * @param arr the tkTree array
212 * @param lang ISO 639 code for the language
213 */
214 function hyphenTkTree(arr, lang) {
215 // import corresponding hyphen language data and function
216 let hyphen = require("hyphen/" + lang);
217 let result = [];
218 for (let i = 0; i < arr.length; i++) {
219 let element = arr[i];
220 let splitter = "分"; // a CJKV
221 if (!Array.isArray(element)) {
222 let hyphenatedElement = hyphen.hyphenateSync(element, { hyphenChar: splitter });
223 let hyphenatedSplitted = hyphenatedElement.split(splitter);
224 var newSplitted = [];
225 for (var j = 0; j < hyphenatedSplitted.length - 1; j++) {
226 newSplitted.push(hyphenatedSplitted[j]);
227 // "bp" for breakpoint
228 newSplitted.push(["bp", "", "-"]); //insert a breakable point (bp) mark
229 }
230 newSplitted.push(hyphenatedSplitted[hyphenatedSplitted.length - 1]);
231 result = result.concat(newSplitted);
232 }
233 else {
234 result.push(element);
235 }
236 }
237 return result;
238 }
239 exports.hyphenTkTree = hyphenTkTree;
240 /**
241 * calculate the text width and Height with a given `TextStyle`
242 * @param preprocessed
243 * @param defaultFontStyle
244 */
245 function calculateTextWidthHeight(element, style) {
246 return __awaiter(this, void 0, void 0, function* () {
247 var res = [];
248 var styleCache = {};
249 var fontCache = {};
250 for (var i = 0; i < element.length; i++) {
251 let item = yield calculateTextWidthHeightAux(element[i], style, styleCache, fontCache);
252 styleCache = item[1];
253 fontCache = item[2];
254 res.push(item[0]);
255 }
256 res = res.flat();
257 return res;
258 });
259 }
260 exports.calculateTextWidthHeight = calculateTextWidthHeight;
261 /**
262 * calculate the text width and Height with a given `TextStyle`
263 * @param preprocessed
264 * @param defaultFontStyle
265 */
266 function calculateTextWidthHeightAux(element, style, styleCache, fontCache) {
267 return __awaiter(this, void 0, void 0, function* () {
268 var result = [];
269 var font;
270 if (style === styleCache) {
271 font = fontCache;
272 }
273 else {
274 let fontPair = (0, canva_1.fontStyleTofont)(style);
275 if (fontPair.path.match(/\.ttc$/)) {
276 font = yield fontkit.openSync(fontPair.path, fontPair.psName);
277 styleCache = style;
278 fontCache = font;
279 }
280 else {
281 font = yield fontkit.openSync(fontPair.path);
282 styleCache = style;
283 fontCache = font;
284 }
285 }
286 if (!Array.isArray(element)) {
287 var run = font.layout(element, undefined, undefined, undefined, "ltr");
288 for (var j = 0; j < run.glyphs.length; j++) {
289 let runGlyphsItem = run.glyphs[j];
290 let item = {
291 x: null,
292 y: null,
293 textStyle: style,
294 direction: Direction.LTR,
295 width: (runGlyphsItem.advanceWidth) * (style.size) / 1000 * 0.75,
296 height: (runGlyphsItem.bbox.maxY - runGlyphsItem.bbox.minY) * (style.size) / 1000 * 0.75,
297 content: element[j],
298 minX: runGlyphsItem.bbox.minX,
299 maxX: runGlyphsItem.bbox.maxX,
300 minY: runGlyphsItem.bbox.minY,
301 maxY: runGlyphsItem.bbox.maxY
302 };
303 result.push(item);
304 }
305 return [result, styleCache, fontCache];
306 }
307 else if (element[0] == "bp") {
308 var beforeNewLine = (yield calculateTextWidthHeightAux(element[1], style, styleCache, fontCache))[0];
309 if (Array.isArray(beforeNewLine)) {
310 beforeNewLine = beforeNewLine.flat();
311 }
312 let afterNewLine = (yield calculateTextWidthHeightAux(element[2], style, styleCache, fontCache))[0];
313 if (Array.isArray(afterNewLine)) {
314 afterNewLine = afterNewLine.flat();
315 }
316 let breakPointNode = {
317 original: beforeNewLine,
318 newLined: afterNewLine,
319 };
320 return [breakPointNode, styleCache, fontCache];
321 }
322 else if (element[0] == "hglue" && !Array.isArray(element[1])) {
323 let hGlue = { stretchFactor: parseFloat(element[1]) };
324 return [hGlue, styleCache, fontCache];
325 }
326 else {
327 return [yield calculateTextWidthHeight(element, style), styleCache, fontCache];
328 }
329 });
330 }
331 exports.calculateTextWidthHeightAux = calculateTextWidthHeightAux;
332 /**
333 * whole document-representing class
334 */
335 class Clo {
336 constructor() {
337 this.preprocessors = [];
338 this.mainStream = [];
339 this.attrs = {
340 "page": exports.A4_IN_PX,
341 "defaultFrameStyle": exports.defaultFrameStyle,
342 "hyphenLanguage": 'en' // hyphenated in the language (in ISO 639)
343 };
344 // register the precessor functions
345 this.preprocessorRegister(splitCJKV);
346 this.preprocessorRegister(hyphenForClo);
347 this.preprocessorRegister(twoReturnsToNewline);
348 this.preprocessorRegister(spacesToBreakpoint);
349 this.preprocessorRegister(filterEmptyString);
350 }
351 setAttr(attr, val) {
352 Object.assign(this.attrs, attr, val);
353 }
354 getAttr(attr) {
355 if (Object.keys(this.attrs).length === 0) {
356 return this.attrs[attr];
357 }
358 else {
359 return undefined;
360 }
361 }
362 /**
363 * register a function of preprocessor
364 * @param f a function
365 */
366 preprocessorRegister(f) {
367 this.preprocessors.push(f);
368 }
369 generatePdf() {
370 return __awaiter(this, void 0, void 0, function* () {
371 // preprocessed
372 var preprocessed = this.mainStream;
373 for (var i = 0; i < this.preprocessors.length; i++) {
374 preprocessed = this.preprocessors[i](preprocessed, this);
375 }
376 // generate the width and height of the stream
377 let defaultFontStyle = this.attrs.defaultFrameStyle.textStyle;
378 let a = yield calculateTextWidthHeight(preprocessed, defaultFontStyle);
379 let breakLineAlgorithms = new breakLines.BreakLineAlgorithm();
380 let segmentedNodes = breakLineAlgorithms.segmentedNodes(a, this.attrs.defaultFrameStyle.width);
381 let segmentedNodesToBox = this.segmentedNodesToFrameBox(segmentedNodes, this.attrs.defaultFrameStyle);
382 let boxesFixed = this.fixenBoxesPosition(segmentedNodesToBox);
383 // generate pdf
384 const doc = new PDFDocument({ size: 'A4' });
385 doc.pipe(fs.createWriteStream('output.pdf'));
386 this.grid(doc);
387 let styleCache = {};
388 let fontPairCache = { path: "", psName: "" };
389 yield this.putText(doc, boxesFixed, styleCache, fontPairCache);
390 // putChar
391 doc.end();
392 });
393 }
394 putText(doc, box, styleCache, fontPairCache) {
395 return __awaiter(this, void 0, void 0, function* () {
396 var fontPair;
397 if (box.textStyle !== null) {
398 if (box.textStyle == styleCache) {
399 fontPair = fontPairCache;
400 }
401 else {
402 fontPair = (0, canva_1.fontStyleTofont)(box.textStyle);
403 styleCache = box.textStyle;
404 fontPairCache = fontPair;
405 if (fontPair.path.match(/\.ttc$/g)) {
406 doc
407 .font(fontPair.path, fontPair.psName)
408 .fontSize(box.textStyle.size * 0.75);
409 }
410 else {
411 doc
412 .font(fontPair.path)
413 .fontSize(box.textStyle.size * 0.75); // 0.75 must added!
414 }
415 }
416 if (box.textStyle.color !== undefined) {
417 doc.fill(box.textStyle.color);
418 }
419 if (Array.isArray(box.content)) {
420 for (var k = 0; k < box.content.length; k++) {
421 let tmp = yield this.putText(doc, box.content[k], styleCache, fontPairCache);
422 doc = tmp[0];
423 styleCache = tmp[1];
424 fontPairCache = tmp[2];
425 }
426 }
427 else if (box.content !== null) {
428 yield doc.text(box.content, (box.x !== null ? box.x : undefined), (box.y !== null ? box.y : undefined));
429 }
430 }
431 return [doc, styleCache, fontPairCache];
432 });
433 }
434 ;
435 grid(doc) {
436 for (var j = 0; j < exports.A4_IN_PX.width; j += 5) {
437 if (j % 50 == 0) {
438 doc.save().fill('#000000')
439 .fontSize(8).text(j.toString(), j * 0.75, 50);
440 doc
441 .save()
442 .lineWidth(0.4)
443 .strokeColor("#dddddd")
444 .moveTo(j * 0.75, 0)
445 .lineTo(j * 0.75, 1000)
446 .stroke();
447 }
448 doc
449 .save()
450 .lineWidth(0.2)
451 .strokeColor("#dddddd")
452 .moveTo(j * 0.75, 0)
453 .lineTo(j * 0.75, 1000)
454 .stroke();
455 }
456 for (var i = 0; i < 1050; i += 5) {
457 if (i % 50 == 0) {
458 doc.save()
459 .fontSize(8).text(i.toString(), 50, i * 0.75);
460 doc
461 .save()
462 .lineWidth(0.4)
463 .strokeColor("#bbbbbb")
464 .moveTo(0, i * 0.75)
465 .lineTo(1000, i * 0.75)
466 .stroke();
467 }
468 doc
469 .save()
470 .lineWidth(0.2)
471 .strokeColor("#bbbbbb")
472 .moveTo(0, i * 0.75)
473 .lineTo(1000, i * 0.75)
474 .stroke();
475 }
476 doc
477 .save()
478 .moveTo(0, 200)
479 .lineTo(1000, 200)
480 .fill('#FF3300');
481 }
482 /**
483 * make all the nest boxes's position fixed
484 * @param box the main boxes
485 * @returns the fixed boxes
486 */
487 fixenBoxesPosition(box) {
488 var currX = (box.x !== null ? box.x : 0); // current x
489 var currY = (box.y !== null ? box.y : 0); // current y
490 if (Array.isArray(box.content)) {
491 for (var i = 0; i < box.content.length; i++) {
492 if (box.direction == Direction.LTR) {
493 box.content[i].x = currX;
494 box.content[i].y = currY;
495 let elementWidth = box.content[i].width;
496 if (elementWidth !== null) {
497 currX += elementWidth;
498 }
499 }
500 if (box.direction == Direction.TTB) {
501 box.content[i].x = currX;
502 box.content[i].y = currY;
503 let elementHeight = box.content[i].height;
504 if (elementHeight !== null) {
505 currY += elementHeight;
506 }
507 }
508 box.content[i] = this.fixenBoxesPosition(box.content[i]);
509 }
510 }
511 return box;
512 }
513 /**
514 * input a `segmentedNodes` and a layed `frame`, return a big `Box` that nodes is put in.
515 * @param segmentedNodes the segmentnodes to be input
516 * @param frame the frame to be layed out.
517 * @returns the big `Box`.
518 */
519 segmentedNodesToFrameBox(segmentedNodes, frame) {
520 let baseLineskip = frame.baseLineskip;
521 let boxArrayEmpty = [];
522 let bigBox = {
523 x: (frame.x !== null ? frame.x * 0.75 : null),
524 y: (frame.y !== null ? frame.y * 0.75 : null),
525 textStyle: frame.textStyle,
526 direction: frame.direction,
527 width: frame.width,
528 height: frame.height,
529 content: boxArrayEmpty,
530 };
531 var bigBoxContent = boxArrayEmpty;
532 let segmentedNodesFixed = segmentedNodes.map((x) => this.removeBreakPoints(x).flat());
533 let segmentedNodeUnglue = segmentedNodesFixed.map((x) => this.removeGlue(x, frame).flat());
534 for (var i = 0; i < segmentedNodeUnglue.length; i++) {
535 var currentLineSkip = baseLineskip;
536 var glyphMaxHeight = this.getGlyphMaxHeight(segmentedNodesFixed[i]);
537 if (currentLineSkip === null || glyphMaxHeight > currentLineSkip) {
538 currentLineSkip = glyphMaxHeight;
539 }
540 var currentLineBox = {
541 x: null,
542 y: null,
543 textStyle: exports.defaultTextStyle,
544 direction: frame.directionInsideLine,
545 width: frame.width,
546 height: currentLineSkip,
547 content: segmentedNodeUnglue[i],
548 };
549 bigBoxContent.push(currentLineBox);
550 }
551 bigBox.content = bigBoxContent;
552 return bigBox;
553 }
554 /**
555 * get the max height of the glyph`[a, b, c]`
556 * @param nodeLine the node line [a, b, c, ...]
557 * @returns
558 */
559 getGlyphMaxHeight(nodeLine) {
560 let segmentedNodeLineHeight = nodeLine.map((x) => { if ("height" in x && x.height > 0.0) {
561 return x.height;
562 }
563 else {
564 return 0.0;
565 } });
566 let maxHeight = Math.max(...segmentedNodeLineHeight);
567 return maxHeight;
568 }
569 removeGlue(nodeLine, frame) {
570 let breakLineAlgorithms = new breakLines.BreakLineAlgorithm();
571 let glueRemoved = nodeLine.filter((x) => !breakLineAlgorithms.isHGlue(x));
572 let onlyGlue = nodeLine.filter((x) => breakLineAlgorithms.isHGlue(x));
573 let sumStretchFactor = onlyGlue.map((x) => { if ("stretchFactor" in x) {
574 return x.stretchFactor;
575 }
576 else {
577 return 0;
578 } })
579 .reduce((acc, cur) => acc + cur, 0);
580 let glueRemovedWidth = glueRemoved.map((x) => { if ("width" in x) {
581 return x.width;
582 }
583 else {
584 return 0;
585 } })
586 .reduce((acc, cur) => acc + cur, 0);
587 let offset = frame.width * 0.75 - glueRemovedWidth;
588 var res = [];
589 for (var i = 0; i < nodeLine.length; i++) {
590 var ele = nodeLine[i];
591 if (breakLineAlgorithms.isHGlue(ele)) {
592 let tmp = {
593 x: null,
594 y: null,
595 textStyle: null,
596 direction: frame.directionInsideLine,
597 //width : 0, // ragged
598 width: ele.stretchFactor / sumStretchFactor * offset,
599 height: 0,
600 content: "",
601 };
602 res.push(tmp);
603 }
604 else {
605 res.push(ele);
606 }
607 }
608 return res;
609 }
610 /**
611 * remove breakpoints
612 * @param boxitemline boxitem in a line with a breakpoint
613 * @returns boxitemline with break points removed
614 */
615 removeBreakPoints(boxitemline) {
616 var res = [];
617 let breakLineAlgorithms = new breakLines.BreakLineAlgorithm();
618 for (var i = 0; i < boxitemline.length; i++) {
619 let ele = boxitemline[i];
620 if (breakLineAlgorithms.isBreakPoint(ele)) {
621 if (i == boxitemline.length - 1) {
622 res.push(ele.newLined);
623 }
624 else {
625 res.push(ele.original);
626 }
627 }
628 else {
629 res.push(ele);
630 }
631 }
632 return res;
633 }
634 }
635 exports.Clo = Clo;
636 /*
637 export let a = new Clo();
638 export default a; */