]> git.kianting.info Git - clo/blob - src/libclo/index.js
2840b3d07f529131196341ba164538b064321326
[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 for (var i = 0; i < element.length; i++) {
249 res.push(yield calculateTextWidthHeightAux(element[i], style));
250 }
251 res = res.flat();
252 return res;
253 });
254 }
255 exports.calculateTextWidthHeight = calculateTextWidthHeight;
256 /**
257 * calculate the text width and Height with a given `TextStyle`
258 * @param preprocessed
259 * @param defaultFontStyle
260 */
261 function calculateTextWidthHeightAux(element, style) {
262 return __awaiter(this, void 0, void 0, function* () {
263 var result = [];
264 let fontPair = (0, canva_1.fontStyleTofont)(style);
265 if (fontPair.path.match(/\.ttc$/)) {
266 var font = yield fontkit.openSync(fontPair.path, fontPair.psName);
267 }
268 else {
269 var font = yield fontkit.openSync(fontPair.path);
270 }
271 if (!Array.isArray(element)) {
272 var run = font.layout(element, undefined, undefined, undefined, "ltr");
273 for (var j = 0; j < run.glyphs.length; j++) {
274 let runGlyphsItem = run.glyphs[j];
275 let item = {
276 x: null,
277 y: null,
278 textStyle: style,
279 direction: Direction.LTR,
280 width: (runGlyphsItem.advanceWidth) * (style.size) / 1000 * 0.75,
281 height: (runGlyphsItem.bbox.maxY - runGlyphsItem.bbox.minY) * (style.size) / 1000 * 0.75,
282 content: element[j],
283 minX: runGlyphsItem.bbox.minX,
284 maxX: runGlyphsItem.bbox.maxX,
285 minY: runGlyphsItem.bbox.minY,
286 maxY: runGlyphsItem.bbox.maxY
287 };
288 result.push(item);
289 }
290 return result;
291 }
292 else if (element[0] == "bp") {
293 var beforeNewLine = yield calculateTextWidthHeightAux(element[1], style);
294 if (Array.isArray(beforeNewLine)) {
295 beforeNewLine = beforeNewLine.flat();
296 }
297 let afterNewLine = yield calculateTextWidthHeightAux(element[2], style);
298 if (Array.isArray(afterNewLine)) {
299 afterNewLine = afterNewLine.flat();
300 }
301 let breakPointNode = {
302 original: beforeNewLine,
303 newLined: afterNewLine,
304 };
305 return breakPointNode;
306 }
307 else if (element[0] == "hglue" && !Array.isArray(element[1])) {
308 let hGlue = { stretchFactor: parseFloat(element[1]) };
309 return hGlue;
310 }
311 else {
312 return calculateTextWidthHeight(element, style);
313 }
314 });
315 }
316 exports.calculateTextWidthHeightAux = calculateTextWidthHeightAux;
317 /**
318 * whole document-representing class
319 */
320 class Clo {
321 constructor() {
322 this.preprocessors = [];
323 this.mainStream = [];
324 this.attrs = {
325 "page": exports.A4_IN_PX,
326 "defaultFrameStyle": exports.defaultFrameStyle,
327 "hyphenLanguage": 'en' // hyphenated in the language (in ISO 639)
328 };
329 // register the precessor functions
330 this.preprocessorRegister(splitCJKV);
331 this.preprocessorRegister(hyphenForClo);
332 this.preprocessorRegister(twoReturnsToNewline);
333 this.preprocessorRegister(spacesToBreakpoint);
334 this.preprocessorRegister(filterEmptyString);
335 }
336 setAttr(attr, val) {
337 Object.assign(this.attrs, attr, val);
338 }
339 getAttr(attr) {
340 if (Object.keys(this.attrs).length === 0) {
341 return this.attrs[attr];
342 }
343 else {
344 return undefined;
345 }
346 }
347 /**
348 * register a function of preprocessor
349 * @param f a function
350 */
351 preprocessorRegister(f) {
352 this.preprocessors.push(f);
353 }
354 generatePdf() {
355 return __awaiter(this, void 0, void 0, function* () {
356 // preprocessed
357 var preprocessed = this.mainStream;
358 for (var i = 0; i < this.preprocessors.length; i++) {
359 preprocessed = this.preprocessors[i](preprocessed, this);
360 }
361 // generate the width and height of the stream
362 let defaultFontStyle = this.attrs.defaultFrameStyle.textStyle;
363 let a = yield calculateTextWidthHeight(preprocessed, defaultFontStyle);
364 let breakLineAlgorithms = new breakLines.BreakLineAlgorithm();
365 // TODO
366 //console.log(breakLineAlgorithms.totalCost(a,70));
367 let segmentedNodes = breakLineAlgorithms.segmentedNodes(a, this.attrs.defaultFrameStyle.width);
368 let segmentedNodesToBox = this.segmentedNodesToFrameBox(segmentedNodes, this.attrs.defaultFrameStyle);
369 let boxesFixed = this.fixenBoxesPosition(segmentedNodesToBox);
370 // generate pdf7
371 const doc = new PDFDocument({ size: 'A4' });
372 doc.pipe(fs.createWriteStream('output.pdf'));
373 this.grid(doc);
374 yield this.putText(doc, boxesFixed);
375 // putChar
376 doc.end();
377 });
378 }
379 putText(doc, box) {
380 return __awaiter(this, void 0, void 0, function* () {
381 if (box.textStyle !== null) {
382 let fontInfo = (0, canva_1.fontStyleTofont)(box.textStyle);
383 if (fontInfo.path.match(/\.ttc$/g)) {
384 doc
385 .font(fontInfo.path, fontInfo.psName)
386 .fontSize(box.textStyle.size * 0.75);
387 }
388 else {
389 doc
390 .font(fontInfo.path)
391 .fontSize(box.textStyle.size * 0.75); // 0.75 must added!
392 }
393 if (box.textStyle.color !== undefined) {
394 doc.fill(box.textStyle.color);
395 }
396 if (Array.isArray(box.content)) {
397 for (var k = 0; k < box.content.length; k++) {
398 doc = yield this.putText(doc, box.content[k]);
399 }
400 }
401 else if (box.content !== null) {
402 yield doc.text(box.content, (box.x !== null ? box.x : undefined), (box.y !== null ? box.y : undefined));
403 }
404 }
405 return doc;
406 });
407 }
408 ;
409 grid(doc) {
410 for (var j = 0; j < exports.A4_IN_PX.width; j += 5) {
411 if (j % 50 == 0) {
412 doc.save().fill('#000000')
413 .fontSize(8).text(j.toString(), j * 0.75, 50);
414 doc
415 .save()
416 .lineWidth(0.4)
417 .strokeColor("#dddddd")
418 .moveTo(j * 0.75, 0)
419 .lineTo(j * 0.75, 1000)
420 .stroke();
421 }
422 doc
423 .save()
424 .lineWidth(0.2)
425 .strokeColor("#dddddd")
426 .moveTo(j * 0.75, 0)
427 .lineTo(j * 0.75, 1000)
428 .stroke();
429 }
430 for (var i = 0; i < 1050; i += 5) {
431 if (i % 50 == 0) {
432 doc.save()
433 .fontSize(8).text(i.toString(), 50, i * 0.75);
434 doc
435 .save()
436 .lineWidth(0.4)
437 .strokeColor("#bbbbbb")
438 .moveTo(0, i * 0.75)
439 .lineTo(1000, i * 0.75)
440 .stroke();
441 }
442 doc
443 .save()
444 .lineWidth(0.2)
445 .strokeColor("#bbbbbb")
446 .moveTo(0, i * 0.75)
447 .lineTo(1000, i * 0.75)
448 .stroke();
449 }
450 doc
451 .save()
452 .moveTo(0, 200)
453 .lineTo(1000, 200)
454 .fill('#FF3300');
455 }
456 /**
457 * make all the nest boxes's position fixed
458 * @param box the main boxes
459 * @returns the fixed boxes
460 */
461 fixenBoxesPosition(box) {
462 var currX = (box.x !== null ? box.x : 0); // current x
463 var currY = (box.y !== null ? box.y : 0); // current y
464 if (Array.isArray(box.content)) {
465 for (var i = 0; i < box.content.length; i++) {
466 if (box.direction == Direction.LTR) {
467 box.content[i].x = currX;
468 box.content[i].y = currY;
469 let elementWidth = box.content[i].width;
470 if (elementWidth !== null) {
471 currX += elementWidth;
472 }
473 }
474 if (box.direction == Direction.TTB) {
475 box.content[i].x = currX;
476 box.content[i].y = currY;
477 let elementHeight = box.content[i].height;
478 if (elementHeight !== null) {
479 currY += elementHeight;
480 }
481 }
482 box.content[i] = this.fixenBoxesPosition(box.content[i]);
483 }
484 }
485 return box;
486 }
487 /**
488 * input a `segmentedNodes` and a layed `frame`, return a big `Box` that nodes is put in.
489 * @param segmentedNodes the segmentnodes to be input
490 * @param frame the frame to be layed out.
491 * @returns the big `Box`.
492 */
493 segmentedNodesToFrameBox(segmentedNodes, frame) {
494 let baseLineskip = frame.baseLineskip;
495 let boxArrayEmpty = [];
496 let bigBox = {
497 x: (frame.x !== null ? frame.x * 0.75 : null),
498 y: (frame.y !== null ? frame.y * 0.75 : null),
499 textStyle: frame.textStyle,
500 direction: frame.direction,
501 width: frame.width,
502 height: frame.height,
503 content: boxArrayEmpty,
504 };
505 var bigBoxContent = boxArrayEmpty;
506 let segmentedNodesFixed = segmentedNodes.map((x) => this.removeBreakPoints(x).flat());
507 let segmentedNodeUnglue = segmentedNodesFixed.map((x) => this.removeGlue(x, frame).flat());
508 for (var i = 0; i < segmentedNodeUnglue.length; i++) {
509 var currentLineSkip = baseLineskip;
510 var glyphMaxHeight = this.getGlyphMaxHeight(segmentedNodesFixed[i]);
511 if (currentLineSkip === null || glyphMaxHeight > currentLineSkip) {
512 currentLineSkip = glyphMaxHeight;
513 }
514 var currentLineBox = {
515 x: null,
516 y: null,
517 textStyle: exports.defaultTextStyle,
518 direction: frame.directionInsideLine,
519 width: frame.width,
520 height: currentLineSkip,
521 content: segmentedNodeUnglue[i],
522 };
523 bigBoxContent.push(currentLineBox);
524 }
525 bigBox.content = bigBoxContent;
526 return bigBox;
527 }
528 /**
529 * get the max height of the glyph`[a, b, c]`
530 * @param nodeLine the node line [a, b, c, ...]
531 * @returns
532 */
533 getGlyphMaxHeight(nodeLine) {
534 let segmentedNodeLineHeight = nodeLine.map((x) => { if ("height" in x && x.height > 0.0) {
535 return x.height;
536 }
537 else {
538 return 0.0;
539 } });
540 let maxHeight = Math.max(...segmentedNodeLineHeight);
541 return maxHeight;
542 }
543 removeGlue(nodeLine, frame) {
544 let breakLineAlgorithms = new breakLines.BreakLineAlgorithm();
545 let glueRemoved = nodeLine.filter((x) => !breakLineAlgorithms.isHGlue(x));
546 let onlyGlue = nodeLine.filter((x) => breakLineAlgorithms.isHGlue(x));
547 let sumStretchFactor = onlyGlue.map((x) => { if ("stretchFactor" in x) {
548 return x.stretchFactor;
549 }
550 else {
551 return 0;
552 } })
553 .reduce((acc, cur) => acc + cur, 0);
554 let glueRemovedWidth = glueRemoved.map((x) => { if ("width" in x) {
555 return x.width;
556 }
557 else {
558 return 0;
559 } })
560 .reduce((acc, cur) => acc + cur, 0);
561 let offset = frame.width * 0.75 - glueRemovedWidth;
562 var res = [];
563 for (var i = 0; i < nodeLine.length; i++) {
564 var ele = nodeLine[i];
565 if (breakLineAlgorithms.isHGlue(ele)) {
566 let tmp = {
567 x: null,
568 y: null,
569 textStyle: null,
570 direction: frame.directionInsideLine,
571 //width : 0, // ragged
572 width: ele.stretchFactor / sumStretchFactor * offset,
573 height: 0,
574 content: "",
575 };
576 res.push(tmp);
577 }
578 else {
579 res.push(ele);
580 }
581 }
582 return res;
583 }
584 /**
585 * remove breakpoints
586 * @param boxitemline boxitem in a line with a breakpoint
587 * @returns boxitemline with break points removed
588 */
589 removeBreakPoints(boxitemline) {
590 var res = [];
591 let breakLineAlgorithms = new breakLines.BreakLineAlgorithm();
592 for (var i = 0; i < boxitemline.length; i++) {
593 let ele = boxitemline[i];
594 if (breakLineAlgorithms.isBreakPoint(ele)) {
595 if (i == boxitemline.length - 1) {
596 res.push(ele.newLined);
597 }
598 else {
599 res.push(ele.original);
600 }
601 }
602 else {
603 res.push(ele);
604 }
605 }
606 return res;
607 }
608 }
609 exports.Clo = Clo;
610 /*
611 export let a = new Clo();
612 export default a; */