Debian Codegraph @

extensions/Math/modules/ve-math/tools/makeSvgsAndCss.js

raw symbols SCIP
1 #!/usr/bin/env node
2 'use strict';
3
4 /* eslint-disable no-use-before-define */
5
6 function generateCSS( symbolsFile, cssFile, inputType ) {
7 let cssRules = []; // Whole CSS rules
8 const
9 rerenderAll = process.argv.slice( 2 ).includes( '--all' ),
10 unmodifiedClasses = {},
11 cssClasses = {}, // Unique part of class name and whether baseline is shifted
12 generatedRules = [],
13 currentRule = [],
14 symbolList = [], // Symbols whose CSS rules need to be added or adjusted
15 cssPrefix = '.ve-ui-mwLatexSymbol-',
16 fs = require( 'fs' ),
17 http = require( 'http' ),
18 querystring = require( 'querystring' ),
19 mathoidMaxConnections = 20,
20 // If symbol.alignBaseline is true, a background-position property will be added to the
21 // CSS rule to shift the baseline of the SVG to be a certain proportion of the way up the
22 // button.
23 singleButtonHeight = 1.8, // Height of the single-height math dialog buttons in em
24 baseline = 0.65; // Proportion of the way down the button the baseline should be
25
26 // eslint-disable-next-line security/detect-non-literal-fs-filename
27 const symbolsData = fs.readFileSync( symbolsFile ).toString();
28 let cssData;
29 try {
30 // eslint-disable-next-line security/detect-non-literal-fs-filename
31 cssData = fs.readFileSync( cssFile ).toString();
32 } catch ( e ) {}
33
34 function encodeURIComponentForCSS( str ) {
35 return encodeURIComponent( str )
36 .replace( /[!'*()]/g, ( chr ) => '%' + chr.charCodeAt( 0 ).toString( 16 ) );
37 }
38
39 /**
40 * Make the className, replacing any non-alphanumerics with their character code
41 *
42 * The reverse of function would look like this, although we have no use for it yet:
43 *
44 * return className.replace( /_([0-9]+)_/g, ( all, one ) => String.fromCharCode( +one ) } );
45 *
46 * @param {string} tex TeX input
47 * @return {string} Class name
48 */
49 function texToClass( tex ) {
50 return tex.replace( /[^\w]/g, ( c ) => '_' + c.charCodeAt( 0 ) + '_' );
51 }
52
53 function makeRequest( symbol ) {
54 const
55 tex = symbol.tex || symbol.insert,
56 data = querystring.stringify( {
57 q: inputType === 'chem' ? '\\ce{' + tex + '}' : tex,
58 type: inputType
59 } ),
60 // API call to mathoid
61 options = {
62 host: 'localhost',
63 port: '10044',
64 path: '/',
65 method: 'POST',
66 headers: {
67 'Content-Type': 'application/x-www-form-urlencoded',
68 'Content-Length': Buffer.byteLength( data )
69 }
70 };
71 // Populate and make the API call
72 const request = http.request( options, ( res ) => {
73 let body = '';
74 res.setEncoding( 'utf8' );
75
76 res.on( 'data', ( innerData ) => {
77 body += innerData;
78 } );
79
80 res.on( 'end', () => {
81 const
82 className = texToClass( tex ),
83 bodyData = JSON.parse( body ),
84 svg = bodyData.svg;
85
86 if ( Object.prototype.hasOwnProperty.call( generatedRules, className ) ) {
87 console.log( className + ' already generated' );
88 onEnd();
89 return;
90 }
91
92 generatedRules[ className ] = true;
93
94 if ( !svg ) {
95 console.log( tex + ' FAILED: ' + body );
96 onEnd();
97 return;
98 }
99
100 let cssRule = cssPrefix + className + ' {\n' +
101 '\tbackground-image: url( data:image/svg+xml,' + encodeURIComponentForCSS( svg ) + ' );\n';
102
103 if ( symbol.alignBaseline ) {
104 // Convert buttonHeight from em to ex, because SVG height is given in ex. (This is an
105 // approximation, since the em:ex ratio differs from font to font.)
106 const buttonHeight = symbol.largeLayout ? singleButtonHeight * 4 : singleButtonHeight * 1.9931;
107 // height and verticalAlign rely on the format of the SVG parameters
108 // HACK: Adjust these by a factor of 0.8 to match VE's default font size of 0.8em
109 const height = parseFloat( bodyData.mathoidStyle.match( /height:\s*([\d.]+)ex/ )[ 1 ] ) * 0.8;
110 const verticalAlign = -parseFloat( bodyData.mathoidStyle.match( /vertical-align:\s*([-\d.]+)ex/ )[ 1 ] ) * 0.8;
111 // CSS percentage positioning is based on the difference between the image and container sizes
112 const heightDifference = buttonHeight - height;
113 const offset = 100 * ( verticalAlign - height + ( baseline * buttonHeight ) ) / heightDifference;
114
115 cssRule += '\tbackground-position: 50% ' + offset + '%;\n' +
116 '}';
117 cssRules.push( cssRule );
118 console.log( tex + ' -> ' + className );
119 } else {
120 cssRule += '}';
121 cssRules.push( cssRule );
122 console.log( tex + ' -> ' + className );
123 }
124 onEnd();
125
126 } );
127 } );
128 request.setTimeout( 10000 );
129 request.write( data );
130 request.end();
131 runNext();
132 }
133
134 function onEnd() {
135 count--;
136 runNext();
137 }
138
139 function runNext() {
140 if ( count < mathoidMaxConnections && symbolList.length ) {
141 count++;
142 makeRequest( symbolList.shift() );
143 }
144 if ( !symbolList.length && !count ) {
145 cssRules.sort();
146 // eslint-disable-next-line security/detect-non-literal-fs-filename
147 fs.writeFileSync(
148 cssFile,
149 '/*!\n' +
150 ' * This file is GENERATED by tools/makeSvgsAndCss.js\n' +
151 ' * DO NOT EDIT\n' +
152 ' */\n' +
153 '/* stylelint-disable plugin/no-unsupported-browser-features */' +
154 '\n' +
155 cssRules.join( '\n\n' ) +
156 '\n'
157 );
158 }
159 }
160
161 if ( cssData ) {
162 let currentClassName;
163 const cssLines = cssData.split( '\n' );
164 for ( let i = 0; i < cssLines.length; i++ ) {
165 if ( cssLines[ i ].indexOf( cssPrefix ) === 0 ) {
166 currentClassName = cssLines[ i ].slice( cssPrefix.length, -2 );
167 currentRule.push( cssLines[ i ] );
168 cssClasses[ currentClassName ] = false; // Default to false
169 } else if ( currentRule.length ) {
170 currentRule.push( cssLines[ i ] );
171 if ( cssLines[ i ].indexOf( '\tbackground-position' ) === 0 ) {
172 cssClasses[ currentClassName ] = true;
173 }
174 if ( cssLines[ i ].indexOf( '}' ) === 0 ) {
175 cssRules.push( currentRule.join( '\n' ) );
176 currentRule.splice( 0, currentRule.length );
177 }
178 }
179 }
180 }
181
182 const symbolObject = JSON.parse( symbolsData );
183 for ( const group in symbolObject ) {
184 const symbols = symbolObject[ group ];
185 for ( let i = 0; i < symbols.length; i++ ) {
186 const symbol = symbols[ i ];
187 if ( symbol.duplicate || symbol.notWorking ) {
188 continue;
189 }
190 const currentClassName = texToClass( symbol.tex || symbol.insert );
191 const alignBaseline = !symbol.alignBaseline;
192 // If symbol is not in the old CSS file, or its alignBaseline status has changed,
193 // add it to symbolList. Check to make sure it hasn't already been added.
194 if (
195 rerenderAll ||
196 cssClasses[ currentClassName ] === undefined ||
197 ( unmodifiedClasses[ currentClassName ] !== true &&
198 cssClasses[ currentClassName ] === alignBaseline )
199 ) {
200 symbolList.push( symbol );
201 } else {
202 // At the end of this loop, any CSS class names that aren't in unmodifiedClasses
203 // will be deleted from cssRules. cssRules will then only contain rules that will
204 // stay unmodified.
205 unmodifiedClasses[ currentClassName ] = true;
206 }
207 }
208 }
209
210 console.log( '----' );
211 console.log( 'Comparing ' + cssFile + ' and ' + symbolsFile );
212 console.log( Object.keys( cssClasses ).length + ' images found in ' + cssFile );
213 console.log( symbolList.length + ' symbols need rendering' );
214 if ( !rerenderAll ) {
215 console.log( Object.keys( unmodifiedClasses ).length + ' symbols already rendered' );
216 console.log( 'To re-render all symbols, use --all' );
217 }
218
219 // Keep only classes that will stay the same. Remove classes that are being adjusted and
220 // classes of symbols that have been deleted from the JSON.
221 cssRules = cssRules.filter( ( rule ) => {
222 const currentClassName = rule.split( '\n' )[ 0 ].slice( cssPrefix.length, -2 );
223 if ( unmodifiedClasses[ currentClassName ] ) {
224 return true;
225 }
226 console.log( 'Removing or adjusting: ' + currentClassName );
227 return false;
228 } );
229
230 let count = 0;
231 runNext();
232 }
233
234 generateCSS( '../mathSymbols.json', '../ve.ui.MWMathSymbols.css', 'tex' );
235 generateCSS( '../chemSymbols.json', '../ve.ui.MWChemSymbols.css', 'chem' );