UNPKG

2.94 kBJavaScriptView Raw
1
2const { db } = require('../db/db');
3const { swu, convert } = require('@sutton-signwriting/core');
4
5/**
6 * Function that normalizes an SWU sign for a center of 500,500
7 * @function swu.signNormalize
8 * @param {string} swuSign - an SWU sign with optional style string
9 * @returns {string} normalized sign
10 * @example
11 * // using promise.then
12 * swu.signNormalize('𝠃𝤟𝤩񋛩𝣵𝤐񀀒𝤇𝣤񋚥𝤐𝤆񀀚𝣮𝣭').then( norm => {
13 * console.log(norm)
14 * })
15 * @example
16 * // using async/await
17 * const norm = await swu.signNormalize('𝠃𝤟𝤩񋛩𝣵𝤐񀀒𝤇𝣤񋚥𝤐𝤆񀀚𝣮𝣭')
18 */
19const signNormalize = async (swuSign) => {
20 const blank = '';
21 const parsed = swu.parse.sign(swuSign);
22 if (!parsed.spatials) return blank;
23
24 const symbols = parsed.spatials.map((spatial) => spatial.symbol);
25 const syms = await db.query(`select id, width, height from symbol where id in (${symbols.map(s => convert.swu2id(s)).join(',')})`);
26 if (!syms.length) return blank;
27 const symbolsizes = syms.reduce((obj, row) => {
28 obj[convert.id2swu(row.id)] = row
29 return obj;
30 }, {})
31 const bbox = (symbols) => {
32 const x1 = Math.min(...symbols.map(spatial => spatial.coord[0]));
33 const y1 = Math.min(...symbols.map(spatial => spatial.coord[1]));
34 const x2 = Math.max(...symbols.map(spatial => spatial.coord[0] + parseInt(symbolsizes[spatial.symbol].width)));
35 const y2 = Math.max(...symbols.map(spatial => spatial.coord[1] + parseInt(symbolsizes[spatial.symbol].height)));
36 return {
37 x1: x1,
38 y1: y1,
39 x2: x2,
40 y2: y2
41 };
42 }
43
44 const hrange = swu.ranges['hcenter'];
45 const hsyms = parsed.spatials.filter((spatial) => {
46 const dec = parseInt(spatial.symbol.slice(1, 4), 16);
47 return (hrange[0] <= dec && hrange[1] >= dec);
48 })
49
50 const vrange = swu.ranges['vcenter'];
51 const vsyms = parsed.spatials.filter((spatial) => {
52 const dec = parseInt(spatial.symbol.slice(1, 4), 16);
53 return (vrange[0] <= dec && vrange[1] >= dec);
54 })
55
56 let abox = bbox(parsed.spatials);
57 let max = [abox.x2, abox.y2];
58 if (hsyms.length) {
59 const hbox = bbox(hsyms);
60 abox.x1 = hbox.x1;
61 abox.x2 = hbox.x2;
62 }
63 if (vsyms.length) {
64 const vbox = bbox(vsyms);
65 abox.y1 = vbox.y1;
66 abox.y2 = vbox.y2;
67 }
68
69 const offset = [parseInt((abox.x2 + abox.x1) / 2) - 500, parseInt((abox.y2 + abox.y1) / 2) - 500]
70 return (parsed.sequence ? '𝠀' + parsed.sequence.join('') : '') +
71 parsed.box + convert.coord2swu([max[0] - offset[0], max[1] - offset[1]]) +
72 parsed.spatials.map(spatial => spatial.symbol + convert.coord2swu([spatial.coord[0] - offset[0], spatial.coord[1] - offset[1]])).join('') +
73 (parsed.style || '');
74}
75
76if (require.main === module) {
77 signNormalize(process.argv[2]).then( res => {
78 console.log(res);
79 })
80} else {
81 module.exports = { signNormalize }
82}