styles-xform.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. /* eslint-disable max-classes-per-file */
  2. const Enums = require('../../../doc/enums');
  3. const XmlStream = require('../../../utils/xml-stream');
  4. const BaseXform = require('../base-xform');
  5. const StaticXform = require('../static-xform');
  6. const ListXform = require('../list-xform');
  7. const FontXform = require('./font-xform');
  8. const FillXform = require('./fill-xform');
  9. const BorderXform = require('./border-xform');
  10. const NumFmtXform = require('./numfmt-xform');
  11. const StyleXform = require('./style-xform');
  12. const DxfXform = require('./dxf-xform');
  13. // custom numfmt ids start here
  14. const NUMFMT_BASE = 164;
  15. // =============================================================================
  16. // StylesXform is used to generate and parse the styles.xml file
  17. // it manages the collections of fonts, number formats, alignments, etc
  18. class StylesXform extends BaseXform {
  19. constructor(initialise) {
  20. super();
  21. this.map = {
  22. numFmts: new ListXform({tag: 'numFmts', count: true, childXform: new NumFmtXform()}),
  23. fonts: new ListXform({
  24. tag: 'fonts',
  25. count: true,
  26. childXform: new FontXform(),
  27. $: {'x14ac:knownFonts': 1},
  28. }),
  29. fills: new ListXform({tag: 'fills', count: true, childXform: new FillXform()}),
  30. borders: new ListXform({tag: 'borders', count: true, childXform: new BorderXform()}),
  31. cellStyleXfs: new ListXform({tag: 'cellStyleXfs', count: true, childXform: new StyleXform()}),
  32. cellXfs: new ListXform({
  33. tag: 'cellXfs',
  34. count: true,
  35. childXform: new StyleXform({xfId: true}),
  36. }),
  37. dxfs: new ListXform({tag: 'dxfs', always: true, count: true, childXform: new DxfXform()}),
  38. // for style manager
  39. numFmt: new NumFmtXform(),
  40. font: new FontXform(),
  41. fill: new FillXform(),
  42. border: new BorderXform(),
  43. style: new StyleXform({xfId: true}),
  44. cellStyles: StylesXform.STATIC_XFORMS.cellStyles,
  45. tableStyles: StylesXform.STATIC_XFORMS.tableStyles,
  46. extLst: StylesXform.STATIC_XFORMS.extLst,
  47. };
  48. if (initialise) {
  49. // StylesXform also acts as style manager and is used to build up styles-model during worksheet processing
  50. this.init();
  51. }
  52. }
  53. initIndex() {
  54. this.index = {
  55. style: {},
  56. numFmt: {},
  57. numFmtNextId: 164, // start custom format ids here
  58. font: {},
  59. border: {},
  60. fill: {},
  61. };
  62. }
  63. init() {
  64. // Prepare for Style Manager role
  65. this.model = {
  66. styles: [],
  67. numFmts: [],
  68. fonts: [],
  69. borders: [],
  70. fills: [],
  71. dxfs: [],
  72. };
  73. this.initIndex();
  74. // default (zero) border
  75. this._addBorder({});
  76. // add default (all zero) style
  77. this._addStyle({numFmtId: 0, fontId: 0, fillId: 0, borderId: 0, xfId: 0});
  78. // add default fills
  79. this._addFill({type: 'pattern', pattern: 'none'});
  80. this._addFill({type: 'pattern', pattern: 'gray125'});
  81. this.weakMap = new WeakMap();
  82. }
  83. render(xmlStream, model) {
  84. model = model || this.model;
  85. //
  86. // <fonts count="2" x14ac:knownFonts="1">
  87. xmlStream.openXml(XmlStream.StdDocAttributes);
  88. xmlStream.openNode('styleSheet', StylesXform.STYLESHEET_ATTRIBUTES);
  89. if (this.index) {
  90. // model has been built by style manager role (contains xml)
  91. if (model.numFmts && model.numFmts.length) {
  92. xmlStream.openNode('numFmts', {count: model.numFmts.length});
  93. model.numFmts.forEach(numFmtXml => {
  94. xmlStream.writeXml(numFmtXml);
  95. });
  96. xmlStream.closeNode();
  97. }
  98. if (!model.fonts.length) {
  99. // default (zero) font
  100. this._addFont({size: 11, color: {theme: 1}, name: 'Calibri', family: 2, scheme: 'minor'});
  101. }
  102. xmlStream.openNode('fonts', {count: model.fonts.length, 'x14ac:knownFonts': 1});
  103. model.fonts.forEach(fontXml => {
  104. xmlStream.writeXml(fontXml);
  105. });
  106. xmlStream.closeNode();
  107. xmlStream.openNode('fills', {count: model.fills.length});
  108. model.fills.forEach(fillXml => {
  109. xmlStream.writeXml(fillXml);
  110. });
  111. xmlStream.closeNode();
  112. xmlStream.openNode('borders', {count: model.borders.length});
  113. model.borders.forEach(borderXml => {
  114. xmlStream.writeXml(borderXml);
  115. });
  116. xmlStream.closeNode();
  117. this.map.cellStyleXfs.render(xmlStream, [{numFmtId: 0, fontId: 0, fillId: 0, borderId: 0, xfId: 0}]);
  118. xmlStream.openNode('cellXfs', {count: model.styles.length});
  119. model.styles.forEach(styleXml => {
  120. xmlStream.writeXml(styleXml);
  121. });
  122. xmlStream.closeNode();
  123. } else {
  124. // model is plain JSON and needs to be xformed
  125. this.map.numFmts.render(xmlStream, model.numFmts);
  126. this.map.fonts.render(xmlStream, model.fonts);
  127. this.map.fills.render(xmlStream, model.fills);
  128. this.map.borders.render(xmlStream, model.borders);
  129. this.map.cellStyleXfs.render(xmlStream, [{numFmtId: 0, fontId: 0, fillId: 0, borderId: 0, xfId: 0}]);
  130. this.map.cellXfs.render(xmlStream, model.styles);
  131. }
  132. StylesXform.STATIC_XFORMS.cellStyles.render(xmlStream);
  133. this.map.dxfs.render(xmlStream, model.dxfs);
  134. StylesXform.STATIC_XFORMS.tableStyles.render(xmlStream);
  135. StylesXform.STATIC_XFORMS.extLst.render(xmlStream);
  136. xmlStream.closeNode();
  137. }
  138. parseOpen(node) {
  139. if (this.parser) {
  140. this.parser.parseOpen(node);
  141. return true;
  142. }
  143. switch (node.name) {
  144. case 'styleSheet':
  145. this.initIndex();
  146. return true;
  147. default:
  148. this.parser = this.map[node.name];
  149. if (this.parser) {
  150. this.parser.parseOpen(node);
  151. }
  152. return true;
  153. }
  154. }
  155. parseText(text) {
  156. if (this.parser) {
  157. this.parser.parseText(text);
  158. }
  159. }
  160. parseClose(name) {
  161. if (this.parser) {
  162. if (!this.parser.parseClose(name)) {
  163. this.parser = undefined;
  164. }
  165. return true;
  166. }
  167. switch (name) {
  168. case 'styleSheet': {
  169. this.model = {};
  170. const add = (propName, xform) => {
  171. if (xform.model && xform.model.length) {
  172. this.model[propName] = xform.model;
  173. }
  174. };
  175. add('numFmts', this.map.numFmts);
  176. add('fonts', this.map.fonts);
  177. add('fills', this.map.fills);
  178. add('borders', this.map.borders);
  179. add('styles', this.map.cellXfs);
  180. add('dxfs', this.map.dxfs);
  181. // index numFmts
  182. this.index = {
  183. model: [],
  184. numFmt: [],
  185. };
  186. if (this.model.numFmts) {
  187. const numFmtIndex = this.index.numFmt;
  188. this.model.numFmts.forEach(numFmt => {
  189. numFmtIndex[numFmt.id] = numFmt.formatCode;
  190. });
  191. }
  192. return false;
  193. }
  194. default:
  195. // not quite sure how we get here!
  196. return true;
  197. }
  198. }
  199. // add a cell's style model to the collection
  200. // each style property is processed and cross-referenced, etc.
  201. // the styleId is returned. Note: cellType is used when numFmt not defined
  202. addStyleModel(model, cellType) {
  203. if (!model) {
  204. return 0;
  205. }
  206. // if we have no default font, add it here now
  207. if (!this.model.fonts.length) {
  208. // default (zero) font
  209. this._addFont({size: 11, color: {theme: 1}, name: 'Calibri', family: 2, scheme: 'minor'});
  210. }
  211. // if we have seen this style object before, assume it has the same styleId
  212. if (this.weakMap && this.weakMap.has(model)) {
  213. return this.weakMap.get(model);
  214. }
  215. const style = {};
  216. cellType = cellType || Enums.ValueType.Number;
  217. if (model.numFmt) {
  218. style.numFmtId = this._addNumFmtStr(model.numFmt);
  219. } else {
  220. switch (cellType) {
  221. case Enums.ValueType.Number:
  222. style.numFmtId = this._addNumFmtStr('General');
  223. break;
  224. case Enums.ValueType.Date:
  225. style.numFmtId = this._addNumFmtStr('mm-dd-yy');
  226. break;
  227. default:
  228. break;
  229. }
  230. }
  231. if (model.font) {
  232. style.fontId = this._addFont(model.font);
  233. }
  234. if (model.border) {
  235. style.borderId = this._addBorder(model.border);
  236. }
  237. if (model.fill) {
  238. style.fillId = this._addFill(model.fill);
  239. }
  240. if (model.alignment) {
  241. style.alignment = model.alignment;
  242. }
  243. if (model.protection) {
  244. style.protection = model.protection;
  245. }
  246. const styleId = this._addStyle(style);
  247. if (this.weakMap) {
  248. this.weakMap.set(model, styleId);
  249. }
  250. return styleId;
  251. }
  252. // given a styleId (i.e. s="n"), get the cell's style model
  253. // objects are shared where possible.
  254. getStyleModel(id) {
  255. // if the style doesn't exist return null
  256. const style = this.model.styles[id];
  257. if (!style) return null;
  258. // have we built this model before?
  259. let model = this.index.model[id];
  260. if (model) return model;
  261. // build a new model
  262. model = this.index.model[id] = {};
  263. // -------------------------------------------------------
  264. // number format
  265. if (style.numFmtId) {
  266. const numFmt = this.index.numFmt[style.numFmtId] || NumFmtXform.getDefaultFmtCode(style.numFmtId);
  267. if (numFmt) {
  268. model.numFmt = numFmt;
  269. }
  270. }
  271. function addStyle(name, group, styleId) {
  272. if (styleId || styleId === 0) {
  273. const part = group[styleId];
  274. if (part) {
  275. model[name] = part;
  276. }
  277. }
  278. }
  279. addStyle('font', this.model.fonts, style.fontId);
  280. addStyle('border', this.model.borders, style.borderId);
  281. addStyle('fill', this.model.fills, style.fillId);
  282. // -------------------------------------------------------
  283. // alignment
  284. if (style.alignment) {
  285. model.alignment = style.alignment;
  286. }
  287. // -------------------------------------------------------
  288. // protection
  289. if (style.protection) {
  290. model.protection = style.protection;
  291. }
  292. return model;
  293. }
  294. addDxfStyle(style) {
  295. if (style.numFmt) {
  296. // register numFmtId to use it during dxf-xform rendering
  297. style.numFmtId = this._addNumFmtStr(style.numFmt);
  298. }
  299. this.model.dxfs.push(style);
  300. return this.model.dxfs.length - 1;
  301. }
  302. getDxfStyle(id) {
  303. return this.model.dxfs[id];
  304. }
  305. // =========================================================================
  306. // Private Interface
  307. _addStyle(style) {
  308. const xml = this.map.style.toXml(style);
  309. let index = this.index.style[xml];
  310. if (index === undefined) {
  311. index = this.index.style[xml] = this.model.styles.length;
  312. this.model.styles.push(xml);
  313. }
  314. return index;
  315. }
  316. // =========================================================================
  317. // Number Formats
  318. _addNumFmtStr(formatCode) {
  319. // check if default format
  320. let index = NumFmtXform.getDefaultFmtId(formatCode);
  321. if (index !== undefined) return index;
  322. // check if already in
  323. index = this.index.numFmt[formatCode];
  324. if (index !== undefined) return index;
  325. index = this.index.numFmt[formatCode] = NUMFMT_BASE + this.model.numFmts.length;
  326. const xml = this.map.numFmt.toXml({id: index, formatCode});
  327. this.model.numFmts.push(xml);
  328. return index;
  329. }
  330. // =========================================================================
  331. // Fonts
  332. _addFont(font) {
  333. const xml = this.map.font.toXml(font);
  334. let index = this.index.font[xml];
  335. if (index === undefined) {
  336. index = this.index.font[xml] = this.model.fonts.length;
  337. this.model.fonts.push(xml);
  338. }
  339. return index;
  340. }
  341. // =========================================================================
  342. // Borders
  343. _addBorder(border) {
  344. const xml = this.map.border.toXml(border);
  345. let index = this.index.border[xml];
  346. if (index === undefined) {
  347. index = this.index.border[xml] = this.model.borders.length;
  348. this.model.borders.push(xml);
  349. }
  350. return index;
  351. }
  352. // =========================================================================
  353. // Fills
  354. _addFill(fill) {
  355. const xml = this.map.fill.toXml(fill);
  356. let index = this.index.fill[xml];
  357. if (index === undefined) {
  358. index = this.index.fill[xml] = this.model.fills.length;
  359. this.model.fills.push(xml);
  360. }
  361. return index;
  362. }
  363. // =========================================================================
  364. }
  365. StylesXform.STYLESHEET_ATTRIBUTES = {
  366. xmlns: 'http://schemas.openxmlformats.org/spreadsheetml/2006/main',
  367. 'xmlns:mc': 'http://schemas.openxmlformats.org/markup-compatibility/2006',
  368. 'mc:Ignorable': 'x14ac x16r2',
  369. 'xmlns:x14ac': 'http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac',
  370. 'xmlns:x16r2': 'http://schemas.microsoft.com/office/spreadsheetml/2015/02/main',
  371. };
  372. StylesXform.STATIC_XFORMS = {
  373. cellStyles: new StaticXform({
  374. tag: 'cellStyles',
  375. $: {count: 1},
  376. c: [{tag: 'cellStyle', $: {name: 'Normal', xfId: 0, builtinId: 0}}],
  377. }),
  378. dxfs: new StaticXform({tag: 'dxfs', $: {count: 0}}),
  379. tableStyles: new StaticXform({
  380. tag: 'tableStyles',
  381. $: {count: 0, defaultTableStyle: 'TableStyleMedium2', defaultPivotStyle: 'PivotStyleLight16'},
  382. }),
  383. extLst: new StaticXform({
  384. tag: 'extLst',
  385. c: [
  386. {
  387. tag: 'ext',
  388. $: {
  389. uri: '{EB79DEF2-80B8-43e5-95BD-54CBDDF9020C}',
  390. 'xmlns:x14': 'http://schemas.microsoft.com/office/spreadsheetml/2009/9/main',
  391. },
  392. c: [{tag: 'x14:slicerStyles', $: {defaultSlicerStyle: 'SlicerStyleLight1'}}],
  393. },
  394. {
  395. tag: 'ext',
  396. $: {
  397. uri: '{9260A510-F301-46a8-8635-F512D64BE5F5}',
  398. 'xmlns:x15': 'http://schemas.microsoft.com/office/spreadsheetml/2010/11/main',
  399. },
  400. c: [{tag: 'x15:timelineStyles', $: {defaultTimelineStyle: 'TimeSlicerStyleLight1'}}],
  401. },
  402. ],
  403. }),
  404. };
  405. // the stylemanager mock acts like StyleManager except that it always returns 0 or {}
  406. class StylesXformMock extends StylesXform {
  407. constructor() {
  408. super();
  409. this.model = {
  410. styles: [{numFmtId: 0, fontId: 0, fillId: 0, borderId: 0, xfId: 0}],
  411. numFmts: [],
  412. fonts: [{size: 11, color: {theme: 1}, name: 'Calibri', family: 2, scheme: 'minor'}],
  413. borders: [{}],
  414. fills: [
  415. {type: 'pattern', pattern: 'none'},
  416. {type: 'pattern', pattern: 'gray125'},
  417. ],
  418. };
  419. }
  420. // =========================================================================
  421. // Style Manager Interface
  422. // override normal behaviour - consume and dispose
  423. parseStream(stream) {
  424. stream.autodrain();
  425. return Promise.resolve();
  426. }
  427. // add a cell's style model to the collection
  428. // each style property is processed and cross-referenced, etc.
  429. // the styleId is returned. Note: cellType is used when numFmt not defined
  430. addStyleModel(model, cellType) {
  431. switch (cellType) {
  432. case Enums.ValueType.Date:
  433. return this.dateStyleId;
  434. default:
  435. return 0;
  436. }
  437. }
  438. get dateStyleId() {
  439. if (!this._dateStyleId) {
  440. const dateStyle = {
  441. numFmtId: NumFmtXform.getDefaultFmtId('mm-dd-yy'),
  442. };
  443. this._dateStyleId = this.model.styles.length;
  444. this.model.styles.push(dateStyle);
  445. }
  446. return this._dateStyleId;
  447. }
  448. // given a styleId (i.e. s="n"), get the cell's style model
  449. // objects are shared where possible.
  450. getStyleModel(/* id */) {
  451. return {};
  452. }
  453. }
  454. StylesXform.Mock = StylesXformMock;
  455. module.exports = StylesXform;