]> git.kianting.info Git - clo/blob - src/libclo/index.js
927c0af15dec3cee3cd8ef2cced87751286834b3
[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 util = __importStar(require("node:util"));
39 const breakLines = __importStar(require("./breakLines"));
40 /**
41 * TYPES
42 */
43 /**
44 * text direction
45 * LTR - left to right
46 * TTB - top to bottom
47 * etc.
48 */
49 var Direction;
50 (function (Direction) {
51 Direction[Direction["LTR"] = 0] = "LTR";
52 Direction[Direction["RTL"] = 1] = "RTL";
53 Direction[Direction["TTB"] = 2] = "TTB";
54 Direction[Direction["BTT"] = 3] = "BTT";
55 })(Direction || (exports.Direction = Direction = {}));
56 /**
57 * DEFAULT CONST PART
58 */
59 exports.A4_IN_PX = { "width": 793.7,
60 "height": 1122.5 };
61 exports.defaultTextStyle = {
62 family: "FreeSerif",
63 size: ptToPx(12),
64 textWeight: canva_1.TextWeight.REGULAR,
65 fontStyle: canva_1.FontStyle.ITALIC,
66 };
67 exports.defaultFrameStyle = {
68 directionInsideLine: Direction.LTR,
69 direction: Direction.TTB,
70 baseLineskip: ptToPx(15),
71 textStyle: exports.defaultTextStyle,
72 x: exports.A4_IN_PX.width * 0.10,
73 y: exports.A4_IN_PX.height * 0.10,
74 width: exports.A4_IN_PX.width * 0.80,
75 height: exports.A4_IN_PX.height * 0.80,
76 content: null,
77 };
78 /**
79 * definition for cjk scripts
80 * - Hani : Han Character
81 * - Hang : Hangul
82 * - Bopo : Bopomofo
83 * - Kana : Katakana
84 * - Hira : Hiragana
85 */
86 exports.cjkvBlocksInRegex = ["Hani", "Hang", "Bopo", "Kana", "Hira"];
87 exports.cjkvRegexPattern = new RegExp("((?:" +
88 exports.cjkvBlocksInRegex.map((x) => "\\p{Script_Extensions=" + x + "}").join("|") + ")+)", "gu");
89 /**
90 * FUNCTION PART
91 */
92 /**
93 * convert from ptToPx
94 * @param pt pt size value
95 * @returns the corresponding px value
96 */
97 function ptToPx(pt) {
98 return pt * 4.0 / 3.0;
99 }
100 exports.ptToPx = ptToPx;
101 /**
102 * REGISTER PART
103 */
104 /**
105 * convert '\n\n' to newline command ["nl"]
106 * @param arr the input `tkTree`
107 * @param clo the `Clo` object
108 * @returns the input tktree
109 */
110 function twoReturnsToNewline(arr, clo) {
111 var middle = [];
112 for (let i = 0; i < arr.length; i++) {
113 var item = arr[i];
114 if (!Array.isArray(item)) {
115 middle = middle.concat(item.split(/(\n\n)/g));
116 }
117 else {
118 middle.push(item);
119 }
120 }
121 var result = [];
122 for (let j = 0; j < middle.length; j++) {
123 var item = middle[j];
124 if (!Array.isArray(item) && item == "\n\n") {
125 result.push(["nl"]); // push a newline command to the result `tkTree`
126 }
127 else {
128 result.push(middle[j]);
129 }
130 }
131 return result;
132 }
133 exports.twoReturnsToNewline = twoReturnsToNewline;
134 /**
135 * split CJKV and non-CJKV
136 *
137 * @param arr : input tkTree
138 * @returns a splitted tkTree (by CJK and NonCJK)
139 * - Examples:
140 * ```
141 * [`many臺中daylight`] => [`many`, `臺中`, `dahylight`]
142 * ```
143 */
144 function splitCJKV(arr, clo) {
145 var result = [];
146 for (let i = 0; i < arr.length; i++) {
147 var item = arr[i];
148 if (!Array.isArray(item)) {
149 result = result.concat(item.split(exports.cjkvRegexPattern));
150 }
151 else {
152 result.push(item);
153 }
154 }
155 return result;
156 }
157 exports.splitCJKV = splitCJKV;
158 /**
159 * hyphenation for a clo document
160 * @param arr the array for a `tkTree`
161 * @param clo the Clo object
162 */
163 function hyphenForClo(arr, clo) {
164 let hyphenLanguage = clo.attrs["hyphenLanguage"];
165 let res = hyphenTkTree(arr, hyphenLanguage);
166 return res;
167 }
168 exports.hyphenForClo = hyphenForClo;
169 /**
170 * convert spaces to Breakpoint
171 * \s+ => ["bp" [\s+] ""]
172 * @param arr the tkTree input text stream
173 * @param clo the Clo object
174 * @returns the converted object
175 */
176 function spacesToBreakpoint(arr, clo) {
177 let spacePattern = /^([ \t]+)$/g;
178 var result = [];
179 for (let i = 0; i < arr.length; i++) {
180 var item = arr[i];
181 if (!Array.isArray(item) && item.match(spacePattern)) {
182 // push a breakpoint command to the result `tkTree`
183 result.push(['bp', [["hglue", "0.1"], item], ""]);
184 }
185 else {
186 result.push(item);
187 }
188 }
189 return result;
190 }
191 exports.spacesToBreakpoint = spacesToBreakpoint;
192 /**
193 * remove all the `` (empty string) in the arr
194 * @param arr the tkTree to be filtered
195 * @param clo the Clo file
196 */
197 function filterEmptyString(arr, clo) {
198 if (Array.isArray(arr)) {
199 arr.filter((x) => { return x != ``; });
200 }
201 return arr;
202 }
203 exports.filterEmptyString = filterEmptyString;
204 /**
205 * OTHER FUNCTIONS
206 */
207 /**
208 * hyphenate for a tkTree
209 * - hyphenation => ["bp", "", "-"]
210 * @param arr the tkTree array
211 * @param lang ISO 639 code for the language
212 */
213 function hyphenTkTree(arr, lang) {
214 // import corresponding hyphen language data and function
215 let hyphen = require("hyphen/" + lang);
216 let result = [];
217 for (let i = 0; i < arr.length; i++) {
218 let element = arr[i];
219 let splitter = "分"; // a CJKV
220 if (!Array.isArray(element)) {
221 let hyphenatedElement = hyphen.hyphenateSync(element, { hyphenChar: splitter });
222 let hyphenatedSplitted = hyphenatedElement.split(splitter);
223 var newSplitted = [];
224 for (var j = 0; j < hyphenatedSplitted.length - 1; j++) {
225 newSplitted.push(hyphenatedSplitted[j]);
226 // "bp" for breakpoint
227 newSplitted.push(["bp", "", "-"]); //insert a breakable point (bp) mark
228 }
229 newSplitted.push(hyphenatedSplitted[hyphenatedSplitted.length - 1]);
230 result = result.concat(newSplitted);
231 }
232 else {
233 result.push(element);
234 }
235 }
236 return result;
237 }
238 exports.hyphenTkTree = hyphenTkTree;
239 /**
240 * calculate the text width and Height with a given `TextStyle`
241 * @param preprocessed
242 * @param defaultFontStyle
243 */
244 function calculateTextWidthHeight(element, style) {
245 return __awaiter(this, void 0, void 0, function* () {
246 var res = [];
247 for (var i = 0; i < element.length; i++) {
248 res.push(yield calculateTextWidthHeightAux(element[i], style));
249 }
250 res = res.flat();
251 return res;
252 });
253 }
254 exports.calculateTextWidthHeight = calculateTextWidthHeight;
255 /**
256 * calculate the text width and Height with a given `TextStyle`
257 * @param preprocessed
258 * @param defaultFontStyle
259 */
260 function calculateTextWidthHeightAux(element, style) {
261 return __awaiter(this, void 0, void 0, function* () {
262 var result = [];
263 let fontPair = (0, canva_1.fontStyleTofont)(style);
264 if (fontPair.path.match(/\.ttc$/)) {
265 var font = yield fontkit.openSync(fontPair.path, fontPair.psName);
266 }
267 else {
268 var font = yield fontkit.openSync(fontPair.path);
269 }
270 if (!Array.isArray(element)) {
271 var run = font.layout(element, undefined, undefined, undefined, "ltr");
272 for (var j = 0; j < run.glyphs.length; j++) {
273 let runGlyphsItem = run.glyphs[j];
274 let item = {
275 x: null,
276 y: null,
277 textStyle: style,
278 direction: Direction.LTR,
279 width: (runGlyphsItem.advanceWidth) * (style.size) / 1000,
280 height: (runGlyphsItem.bbox.maxY - runGlyphsItem.bbox.minY) * (style.size) / 1000,
281 content: element[j],
282 minX: runGlyphsItem.bbox.minX,
283 maxX: runGlyphsItem.bbox.maxX,
284 minY: runGlyphsItem.bbox.minY,
285 maxY: runGlyphsItem.bbox.maxY
286 };
287 result.push(item);
288 }
289 return result;
290 }
291 else if (element[0] == "bp") {
292 var beforeNewLine = yield calculateTextWidthHeightAux(element[1], style);
293 if (Array.isArray(beforeNewLine)) {
294 beforeNewLine = beforeNewLine.flat();
295 }
296 let afterNewLine = yield calculateTextWidthHeightAux(element[2], style);
297 if (Array.isArray(afterNewLine)) {
298 afterNewLine = afterNewLine.flat();
299 }
300 let breakPointNode = {
301 original: beforeNewLine,
302 newLined: afterNewLine,
303 };
304 return breakPointNode;
305 }
306 else if (element[0] == "hglue" && !Array.isArray(element[1])) {
307 let hGlue = { stretchFactor: parseFloat(element[1]) };
308 return hGlue;
309 }
310 else {
311 return calculateTextWidthHeight(element, style);
312 }
313 });
314 }
315 exports.calculateTextWidthHeightAux = calculateTextWidthHeightAux;
316 /**
317 * whole document-representing class
318 */
319 class Clo {
320 constructor() {
321 this.preprocessors = [];
322 this.mainStream = [];
323 this.attrs = {
324 "page": exports.A4_IN_PX,
325 "defaultFrameStyle": exports.defaultFrameStyle,
326 "hyphenLanguage": 'en' // hyphenated in the language (in ISO 639)
327 };
328 // register the precessor functions
329 this.preprocessorRegister(splitCJKV);
330 this.preprocessorRegister(hyphenForClo);
331 this.preprocessorRegister(twoReturnsToNewline);
332 this.preprocessorRegister(spacesToBreakpoint);
333 this.preprocessorRegister(filterEmptyString);
334 }
335 setAttr(attr, val) {
336 Object.assign(this.attrs, attr, val);
337 }
338 getAttr(attr) {
339 if (Object.keys(this.attrs).length === 0) {
340 return this.attrs[attr];
341 }
342 else {
343 return undefined;
344 }
345 }
346 /**
347 * register a function of preprocessor
348 * @param f a function
349 */
350 preprocessorRegister(f) {
351 this.preprocessors.push(f);
352 }
353 generatePdf() {
354 return __awaiter(this, void 0, void 0, function* () {
355 // preprocessed
356 var preprocessed = this.mainStream;
357 for (var i = 0; i < this.preprocessors.length; i++) {
358 preprocessed = this.preprocessors[i](preprocessed, this);
359 }
360 // generate the width and height of the stream
361 let defaultFontStyle = this.attrs["defaultFrameStyle"].textStyle;
362 let a = yield calculateTextWidthHeight(preprocessed, defaultFontStyle);
363 // TODO
364 console.log(util.inspect(a, true, 100));
365 console.log(breakLines.totalCost(a, 3, 100));
366 });
367 }
368 }
369 exports.Clo = Clo;
370 /*
371 export let a = new Clo();
372 export default a; */