]> git.kianting.info Git - clo/blob - src/libclo/index.js
665b35971f7fb38105559cef12b02bb105034973
[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 * 0.75,
74 y: exports.A4_IN_PX.height * 0.10 * 0.75,
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) * 0.75 / 1000,
281 height: (runGlyphsItem.bbox.maxY - runGlyphsItem.bbox.minY) * (style.size) * 0.75 / 1000,
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 console.log(this.attrs.defaultFrameStyle.width);
369 let segmentedNodesToBox = this.segmentedNodesToFrameBox(segmentedNodes, this.attrs.defaultFrameStyle);
370 let boxesFixed = this.fixenBoxesPosition(segmentedNodesToBox);
371 // generate pdf7
372 const doc = new PDFDocument({ size: 'A4' });
373 doc.pipe(fs.createWriteStream('output.pdf'));
374 this.grid(doc);
375 yield this.putText(doc, boxesFixed);
376 // putChar
377 doc.end();
378 });
379 }
380 putText(doc, box) {
381 return __awaiter(this, void 0, void 0, function* () {
382 if (box.textStyle !== null) {
383 let fontInfo = (0, canva_1.fontStyleTofont)(box.textStyle);
384 if (fontInfo.path.match(/\.ttc$/g)) {
385 doc
386 .font(fontInfo.path, fontInfo.psName)
387 .fontSize(box.textStyle.size * 0.75);
388 }
389 else {
390 doc
391 .font(fontInfo.path)
392 .fontSize(box.textStyle.size * 0.75);
393 }
394 if (box.textStyle.color !== undefined) {
395 doc.fill(box.textStyle.color);
396 }
397 if (Array.isArray(box.content)) {
398 for (var k = 0; k < box.content.length; k++) {
399 doc = yield this.putText(doc, box.content[k]);
400 }
401 }
402 else if (box.content !== null) {
403 console.log(box.content, box.x, box.y);
404 yield doc.text(box.content, (box.x !== null ? box.x : undefined), (box.y !== null ? box.y : undefined));
405 }
406 }
407 return doc;
408 });
409 }
410 ;
411 grid(doc) {
412 for (var j = 0; j < exports.A4_IN_PX.width; j += 5) {
413 if (j % 50 == 0) {
414 doc.save().fill('#000000')
415 .fontSize(8).text(j.toString(), j * 0.75, 50);
416 doc
417 .save()
418 .lineWidth(0.4)
419 .strokeColor("#dddddd")
420 .moveTo(j * 0.75, 0)
421 .lineTo(j * 0.75, 1000)
422 .stroke();
423 }
424 doc
425 .save()
426 .lineWidth(0.2)
427 .strokeColor("#dddddd")
428 .moveTo(j * 0.75, 0)
429 .lineTo(j * 0.75, 1000)
430 .stroke();
431 }
432 for (var i = 0; i < 1050; i += 5) {
433 if (i % 50 == 0) {
434 doc.save()
435 .fontSize(8).text(i.toString(), 50, i * 0.75);
436 doc
437 .save()
438 .lineWidth(0.4)
439 .strokeColor("#bbbbbb")
440 .moveTo(0, i * 0.75)
441 .lineTo(1000, i * 0.75)
442 .stroke();
443 }
444 doc
445 .save()
446 .lineWidth(0.2)
447 .strokeColor("#bbbbbb")
448 .moveTo(0, i * 0.75)
449 .lineTo(1000, i * 0.75)
450 .stroke();
451 }
452 doc
453 .save()
454 .moveTo(0, 200)
455 .lineTo(1000, 200)
456 .fill('#FF3300');
457 }
458 /**
459 * make all the nest boxes's position fixed
460 * @param box the main boxes
461 * @returns the fixed boxes
462 */
463 fixenBoxesPosition(box) {
464 console.log("~~~~~", box);
465 var currX = (box.x !== null ? box.x : 0); // current x
466 var currY = (box.y !== null ? box.y : 0); // current y
467 if (Array.isArray(box.content)) {
468 for (var i = 0; i < box.content.length; i++) {
469 if (box.direction == Direction.LTR) {
470 box.content[i].x = currX;
471 box.content[i].y = currY;
472 let elementWidth = box.content[i].width;
473 if (elementWidth !== null) {
474 currX += elementWidth;
475 }
476 }
477 if (box.direction == Direction.TTB) {
478 box.content[i].x = currX;
479 box.content[i].y = currY;
480 let elementHeight = box.content[i].height;
481 if (elementHeight !== null) {
482 currY += elementHeight;
483 }
484 }
485 box.content[i] = this.fixenBoxesPosition(box.content[i]);
486 }
487 }
488 return box;
489 }
490 /**
491 * input a `segmentedNodes` and a layed `frame`, return a big `Box` that nodes is put in.
492 * @param segmentedNodes the segmentnodes to be input
493 * @param frame the frame to be layed out.
494 * @returns the big `Box`.
495 */
496 segmentedNodesToFrameBox(segmentedNodes, frame) {
497 let baseLineskip = frame.baseLineskip;
498 let boxArrayEmpty = [];
499 let bigBox = {
500 x: frame.x,
501 y: frame.y,
502 textStyle: frame.textStyle,
503 direction: frame.direction,
504 width: frame.width,
505 height: frame.height,
506 content: boxArrayEmpty,
507 };
508 var bigBoxContent = boxArrayEmpty;
509 let segmentedNodesFixed = segmentedNodes.map((x) => this.removeBreakPoints(x).flat());
510 let segmentedNodeUnglue = segmentedNodesFixed.map((x) => this.removeGlue(x, frame).flat());
511 for (var i = 0; i < segmentedNodeUnglue.length; i++) {
512 var currentLineSkip = baseLineskip;
513 var glyphMaxHeight = this.getGlyphMaxHeight(segmentedNodesFixed[i]);
514 if (currentLineSkip === null || glyphMaxHeight > currentLineSkip) {
515 currentLineSkip = glyphMaxHeight;
516 }
517 var currentLineBox = {
518 x: null,
519 y: null,
520 textStyle: exports.defaultTextStyle,
521 direction: frame.directionInsideLine,
522 width: frame.width,
523 height: currentLineSkip,
524 content: segmentedNodeUnglue[i],
525 };
526 bigBoxContent.push(currentLineBox);
527 }
528 bigBox.content = bigBoxContent;
529 return bigBox;
530 }
531 /**
532 * get the max height of the glyph`[a, b, c]`
533 * @param nodeLine the node line [a, b, c, ...]
534 * @returns
535 */
536 getGlyphMaxHeight(nodeLine) {
537 let segmentedNodeLineHeight = nodeLine.map((x) => { if ("height" in x && x.height > 0.0) {
538 return x.height;
539 }
540 else {
541 return 0.0;
542 } });
543 let maxHeight = Math.max(...segmentedNodeLineHeight);
544 return maxHeight;
545 }
546 removeGlue(nodeLine, frame) {
547 let breakLineAlgorithms = new breakLines.BreakLineAlgorithm();
548 let glueRemoved = nodeLine.filter((x) => !breakLineAlgorithms.isHGlue(x));
549 let onlyGlue = nodeLine.filter((x) => breakLineAlgorithms.isHGlue(x));
550 let sumStretchFactor = onlyGlue.map((x) => { if ("stretchFactor" in x) {
551 return x.stretchFactor;
552 }
553 else {
554 return 0;
555 } })
556 .reduce((acc, cur) => acc + cur, 0);
557 let glueRemovedWidth = glueRemoved.map((x) => { if ("width" in x) {
558 return x.width;
559 }
560 else {
561 return 0;
562 } })
563 .reduce((acc, cur) => acc + cur, 0);
564 let offset = frame.width * 0.75 - glueRemovedWidth;
565 console.log("OFFSET", offset);
566 var res = [];
567 for (var i = 0; i < nodeLine.length; i++) {
568 var ele = nodeLine[i];
569 if (breakLineAlgorithms.isHGlue(ele)) {
570 let tmp = {
571 x: null,
572 y: null,
573 textStyle: null,
574 direction: frame.directionInsideLine,
575 width: ele.stretchFactor / sumStretchFactor * offset,
576 height: 0,
577 content: "",
578 };
579 res.push(tmp);
580 }
581 else {
582 res.push(ele);
583 }
584 }
585 return res;
586 }
587 /**
588 * remove breakpoints
589 * @param boxitemline boxitem in a line with a breakpoint
590 * @returns boxitemline with break points removed
591 */
592 removeBreakPoints(boxitemline) {
593 var res = [];
594 let breakLineAlgorithms = new breakLines.BreakLineAlgorithm();
595 for (var i = 0; i < boxitemline.length; i++) {
596 let ele = boxitemline[i];
597 if (breakLineAlgorithms.isBreakPoint(ele)) {
598 if (i == boxitemline.length - 1) {
599 res.push(ele.newLined);
600 }
601 else {
602 res.push(ele.original);
603 }
604 }
605 else {
606 res.push(ele);
607 }
608 }
609 return res;
610 }
611 }
612 exports.Clo = Clo;
613 /*
614 export let a = new Clo();
615 export default a; */