gen-tables.ts 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749
  1. /**
  2. * PptxGenJS: Table Generation
  3. */
  4. import { DEF_FONT_SIZE, DEF_SLIDE_MARGIN_IN, EMU, LINEH_MODIFIER, ONEPT, SLIDE_OBJECT_TYPES } from './core-enums'
  5. import { PresLayout, SlideLayout, TableCell, TableToSlidesProps, TableRow, TableRowSlide, TableCellProps } from './core-interfaces'
  6. import { getSmartParseNumber, inch2Emu, rgbToHex, valToPts } from './gen-utils'
  7. import PptxGenJS from './pptxgen'
  8. /**
  9. * Break cell text into lines based upon table column width (e.g.: Magic Happens Here(tm))
  10. * @param {TableCell} cell - table cell
  11. * @param {number} colWidth - table column width (inches)
  12. * @return {TableRow[]} - cell's text objects grouped into lines
  13. */
  14. function parseTextToLines(cell: TableCell, colWidth: number, verbose?: boolean): TableCell[][] {
  15. // FYI: CPL = Width / (font-size / font-constant)
  16. // FYI: CHAR:2.3, colWidth:10, fontSize:12 => CPL=138, (actual chars per line in PPT)=145 [14.5 CPI]
  17. // FYI: CHAR:2.3, colWidth:7 , fontSize:12 => CPL= 97, (actual chars per line in PPT)=100 [14.3 CPI]
  18. // FYI: CHAR:2.3, colWidth:9 , fontSize:16 => CPL= 96, (actual chars per line in PPT)=84 [ 9.3 CPI]
  19. const FOCO = 2.3 + (cell.options?.autoPageCharWeight ? cell.options.autoPageCharWeight : 0) // Character Constant
  20. const CPL = Math.floor((colWidth / ONEPT) * EMU) / ((cell.options?.fontSize ? cell.options.fontSize : DEF_FONT_SIZE) / FOCO) // Chars-Per-Line
  21. const parsedLines: TableCell[][] = []
  22. let inputCells: TableCell[] = []
  23. const inputLines1: TableCell[][] = []
  24. const inputLines2: TableCell[][] = []
  25. /*
  26. if (cell.options && cell.options.autoPageCharWeight) {
  27. let CHR1 = 2.3 + (cell.options && cell.options.autoPageCharWeight ? cell.options.autoPageCharWeight : 0) // Character Constant
  28. let CPL1 = ((colWidth / ONEPT) * EMU) / ((cell.options && cell.options.fontSize ? cell.options.fontSize : DEF_FONT_SIZE) / CHR1) // Chars-Per-Line
  29. console.log(`cell.options.autoPageCharWeight: '${cell.options.autoPageCharWeight}' => CPL: ${CPL1}`)
  30. let CHR2 = 2.3 + 0
  31. let CPL2 = ((colWidth / ONEPT) * EMU) / ((cell.options && cell.options.fontSize ? cell.options.fontSize : DEF_FONT_SIZE) / CHR2) // Chars-Per-Line
  32. console.log(`cell.options.autoPageCharWeight: '0' => CPL: ${CPL2}`)
  33. }
  34. */
  35. /**
  36. * EX INPUTS: `cell.text`
  37. * - string....: "Account Name Column"
  38. * - object....: { text:"Account Name Column" }
  39. * - object[]..: [{ text:"Account Name", options:{ bold:true } }, { text:" Column" }]
  40. * - object[]..: [{ text:"Account Name", options:{ breakLine:true } }, { text:"Input" }]
  41. */
  42. /**
  43. * EX OUTPUTS:
  44. * - string....: [{ text:"Account Name Column" }]
  45. * - object....: [{ text:"Account Name Column" }]
  46. * - object[]..: [{ text:"Account Name", options:{ breakLine:true } }, { text:"Input" }]
  47. * - object[]..: [{ text:"Account Name", options:{ breakLine:true } }, { text:"Input" }]
  48. */
  49. // STEP 1: Ensure inputCells is an array of TableCells
  50. if (cell.text && cell.text.toString().trim().length === 0) {
  51. // Allow a single space/whitespace as cell text (user-requested feature)
  52. inputCells.push({ _type: SLIDE_OBJECT_TYPES.tablecell, text: ' ' })
  53. } else if (typeof cell.text === 'number' || typeof cell.text === 'string') {
  54. inputCells.push({ _type: SLIDE_OBJECT_TYPES.tablecell, text: (cell.text || '').toString().trim() })
  55. } else if (Array.isArray(cell.text)) {
  56. inputCells = cell.text
  57. }
  58. if (verbose) {
  59. console.log('[1/4] inputCells')
  60. inputCells.forEach((cell, idx) => console.log(`[1/4] [${idx + 1}] cell: ${JSON.stringify(cell)}`))
  61. // console.log('...............................................\n\n')
  62. }
  63. // STEP 2: Group table cells into lines based on "\n" or `breakLine` prop
  64. /**
  65. * - EX: `[{ text:"Input Output" }, { text:"Extra" }]` == 1 line
  66. * - EX: `[{ text:"Input" }, { text:"Output", options:{ breakLine:true } }]` == 1 line
  67. * - EX: `[{ text:"Input\nOutput" }]` == 2 lines
  68. * - EX: `[{ text:"Input", options:{ breakLine:true } }, { text:"Output" }]` == 2 lines
  69. */
  70. let newLine: TableCell[] = []
  71. inputCells.forEach(cell => {
  72. // (this is always true, we just constructed them above, but we need to tell typescript b/c type is still string||Cell[])
  73. if (typeof cell.text === 'string') {
  74. if (cell.text.split('\n').length > 1) {
  75. cell.text.split('\n').forEach(textLine => {
  76. newLine.push({
  77. _type: SLIDE_OBJECT_TYPES.tablecell,
  78. text: textLine,
  79. options: { ...cell.options, ...{ breakLine: true } },
  80. })
  81. })
  82. } else {
  83. newLine.push({
  84. _type: SLIDE_OBJECT_TYPES.tablecell,
  85. text: cell.text.trim(),
  86. options: cell.options,
  87. })
  88. }
  89. if (cell.options?.breakLine) {
  90. if (verbose) console.log(`inputCells: new line > ${JSON.stringify(newLine)}`)
  91. inputLines1.push(newLine)
  92. newLine = []
  93. }
  94. }
  95. // Flush buffer
  96. if (newLine.length > 0) {
  97. inputLines1.push(newLine)
  98. newLine = []
  99. }
  100. })
  101. if (verbose) {
  102. console.log(`[2/4] inputLines1 (${inputLines1.length})`)
  103. inputLines1.forEach((line, idx) => console.log(`[2/4] [${idx + 1}] line: ${JSON.stringify(line)}`))
  104. // console.log('...............................................\n\n')
  105. }
  106. // STEP 3: Tokenize every text object into words (then it's really easy to assemble lines below without having to break text, add its `options`, etc.)
  107. inputLines1.forEach(line => {
  108. line.forEach(cell => {
  109. const lineCells: TableCell[] = []
  110. const cellTextStr = String(cell.text) // force convert to string (compiled JS is better with this than a cast)
  111. const lineWords = cellTextStr.split(' ')
  112. lineWords.forEach((word, idx) => {
  113. const cellProps = { ...cell.options }
  114. // IMPORTANT: Handle `breakLine` prop - we cannot apply to each word - only apply to very last word!
  115. if (cellProps?.breakLine) cellProps.breakLine = idx + 1 === lineWords.length
  116. lineCells.push({ _type: SLIDE_OBJECT_TYPES.tablecell, text: word + (idx + 1 < lineWords.length ? ' ' : ''), options: cellProps })
  117. })
  118. inputLines2.push(lineCells)
  119. })
  120. })
  121. if (verbose) {
  122. console.log(`[3/4] inputLines2 (${inputLines2.length})`)
  123. inputLines2.forEach(line => console.log(`[3/4] line: ${JSON.stringify(line)}`))
  124. // console.log('...............................................\n\n')
  125. }
  126. // STEP 4: Group cells/words into lines based upon space consumed by word letters
  127. inputLines2.forEach(line => {
  128. let lineCells: TableCell[] = []
  129. let strCurrLine = ''
  130. line.forEach(word => {
  131. // A: create new line when horizontal space is exhausted
  132. if (strCurrLine.length + word.text.length > CPL) {
  133. // if (verbose) console.log(`STEP 4: New line added: (${strCurrLine.length} + ${word.text.length} > ${CPL})`);
  134. parsedLines.push(lineCells)
  135. lineCells = []
  136. strCurrLine = ''
  137. }
  138. // B: add current word to line cells
  139. lineCells.push(word)
  140. // C: add current word to `strCurrLine` which we use to keep track of line's char length
  141. strCurrLine += word.text.toString()
  142. })
  143. // Flush buffer: Only create a line when there's text to avoid empty row
  144. if (lineCells.length > 0) parsedLines.push(lineCells)
  145. })
  146. if (verbose) {
  147. console.log(`[4/4] parsedLines (${parsedLines.length})`)
  148. parsedLines.forEach((line, idx) => console.log(`[4/4] [Line ${idx + 1}]:\n${JSON.stringify(line)}`))
  149. console.log('...............................................\n\n')
  150. }
  151. // Done:
  152. return parsedLines
  153. }
  154. /**
  155. * Takes an array of table rows and breaks into an array of slides, which contain the calculated amount of table rows that fit on that slide
  156. * @param {TableCell[][]} tableRows - table rows
  157. * @param {TableToSlidesProps} tableProps - table2slides properties
  158. * @param {PresLayout} presLayout - presentation layout
  159. * @param {SlideLayout} masterSlide - master slide
  160. * @return {TableRowSlide[]} array of table rows
  161. */
  162. export function getSlidesForTableRows(tableRows: TableCell[][] = [], tableProps: TableToSlidesProps = {}, presLayout: PresLayout, masterSlide?: SlideLayout): TableRowSlide[] {
  163. let arrInchMargins = DEF_SLIDE_MARGIN_IN
  164. let emuSlideTabW = EMU * 1
  165. let emuSlideTabH = EMU * 1
  166. let emuTabCurrH = 0
  167. let numCols = 0
  168. const tableRowSlides: TableRowSlide[] = []
  169. const tablePropX = getSmartParseNumber(tableProps.x, 'X', presLayout)
  170. const tablePropY = getSmartParseNumber(tableProps.y, 'Y', presLayout)
  171. const tablePropW = getSmartParseNumber(tableProps.w, 'X', presLayout)
  172. const tablePropH = getSmartParseNumber(tableProps.h, 'Y', presLayout)
  173. let tableCalcW = tablePropW
  174. function calcSlideTabH(): void {
  175. let emuStartY = 0
  176. if (tableRowSlides.length === 0) emuStartY = tablePropY || inch2Emu(arrInchMargins[0])
  177. if (tableRowSlides.length > 0) emuStartY = inch2Emu(tableProps.autoPageSlideStartY || tableProps.newSlideStartY || arrInchMargins[0])
  178. emuSlideTabH = (tablePropH || presLayout.height) - emuStartY - inch2Emu(arrInchMargins[2])
  179. // console.log(`| startY .......................................... = ${(emuStartY / EMU).toFixed(1)}`)
  180. // console.log(`| emuSlideTabH .................................... = ${(emuSlideTabH / EMU).toFixed(1)}`)
  181. if (tableRowSlides.length > 1) {
  182. // D: RULE: Use margins for starting point after the initial Slide, not `opt.y` (ISSUE #43, ISSUE #47, ISSUE #48)
  183. if (typeof tableProps.autoPageSlideStartY === 'number') {
  184. emuSlideTabH = (tablePropH || presLayout.height) - inch2Emu(tableProps.autoPageSlideStartY + arrInchMargins[2])
  185. } else if (typeof tableProps.newSlideStartY === 'number') {
  186. // @deprecated v3.3.0
  187. emuSlideTabH = (tablePropH || presLayout.height) - inch2Emu(tableProps.newSlideStartY + arrInchMargins[2])
  188. } else if (tablePropY) {
  189. emuSlideTabH = (tablePropH || presLayout.height) - inch2Emu((tablePropY / EMU < arrInchMargins[0] ? tablePropY / EMU : arrInchMargins[0]) + arrInchMargins[2])
  190. // Use whichever is greater: area between margins or the table H provided (dont shrink usable area - the whole point of over-riding Y on paging is to *increase* usable space)
  191. if (emuSlideTabH < tablePropH) emuSlideTabH = tablePropH
  192. }
  193. }
  194. }
  195. if (tableProps.verbose) {
  196. console.log('[[VERBOSE MODE]]')
  197. console.log('|-- TABLE PROPS --------------------------------------------------------|')
  198. console.log(`| presLayout.width ................................ = ${(presLayout.width / EMU).toFixed(1)}`)
  199. console.log(`| presLayout.height ............................... = ${(presLayout.height / EMU).toFixed(1)}`)
  200. console.log(`| tableProps.x .................................... = ${typeof tableProps.x === 'number' ? (tableProps.x / EMU).toFixed(1) : tableProps.x}`)
  201. console.log(`| tableProps.y .................................... = ${typeof tableProps.y === 'number' ? (tableProps.y / EMU).toFixed(1) : tableProps.y}`)
  202. console.log(`| tableProps.w .................................... = ${typeof tableProps.w === 'number' ? (tableProps.w / EMU).toFixed(1) : tableProps.w}`)
  203. console.log(`| tableProps.h .................................... = ${typeof tableProps.h === 'number' ? (tableProps.h / EMU).toFixed(1) : tableProps.h}`)
  204. console.log(`| tableProps.slideMargin .......................... = ${tableProps.slideMargin ? String(tableProps.slideMargin) : ''}`)
  205. console.log(`| tableProps.margin ............................... = ${String(tableProps.margin)}`)
  206. console.log(`| tableProps.colW ................................. = ${String(tableProps.colW)}`)
  207. console.log(`| tableProps.autoPageSlideStartY .................. = ${tableProps.autoPageSlideStartY}`)
  208. console.log(`| tableProps.autoPageCharWeight ................... = ${tableProps.autoPageCharWeight}`)
  209. console.log('|-- CALCULATIONS -------------------------------------------------------|')
  210. console.log(`| tablePropX ...................................... = ${tablePropX / EMU}`)
  211. console.log(`| tablePropY ...................................... = ${tablePropY / EMU}`)
  212. console.log(`| tablePropW ...................................... = ${tablePropW / EMU}`)
  213. console.log(`| tablePropH ...................................... = ${tablePropH / EMU}`)
  214. console.log(`| tableCalcW ...................................... = ${tableCalcW / EMU}`)
  215. }
  216. // STEP 1: Calculate margins
  217. {
  218. // Important: Use default size as zero cell margin is causing our tables to be too large and touch bottom of slide!
  219. if (!tableProps.slideMargin && tableProps.slideMargin !== 0) tableProps.slideMargin = DEF_SLIDE_MARGIN_IN[0]
  220. if (masterSlide && typeof masterSlide._margin !== 'undefined') {
  221. if (Array.isArray(masterSlide._margin)) arrInchMargins = masterSlide._margin
  222. else if (!isNaN(Number(masterSlide._margin))) { arrInchMargins = [Number(masterSlide._margin), Number(masterSlide._margin), Number(masterSlide._margin), Number(masterSlide._margin)] }
  223. } else if (tableProps.slideMargin || tableProps.slideMargin === 0) {
  224. if (Array.isArray(tableProps.slideMargin)) arrInchMargins = tableProps.slideMargin
  225. else if (!isNaN(tableProps.slideMargin)) arrInchMargins = [tableProps.slideMargin, tableProps.slideMargin, tableProps.slideMargin, tableProps.slideMargin]
  226. }
  227. if (tableProps.verbose) console.log(`| arrInchMargins .................................. = [${arrInchMargins.join(', ')}]`)
  228. }
  229. // STEP 2: Calculate number of columns
  230. {
  231. // NOTE: Cells may have a colspan, so merely taking the length of the [0] (or any other) row is not
  232. // ....: sufficient to determine column count. Therefore, check each cell for a colspan and total cols as reqd
  233. const firstRow = tableRows[0] || []
  234. firstRow.forEach(cell => {
  235. if (!cell) cell = { _type: SLIDE_OBJECT_TYPES.tablecell }
  236. const cellOpts = cell.options || null
  237. numCols += Number(cellOpts?.colspan ? cellOpts.colspan : 1)
  238. })
  239. if (tableProps.verbose) console.log(`| numCols ......................................... = ${numCols}`)
  240. }
  241. // STEP 3: Calculate width using tableProps.colW if possible
  242. if (!tablePropW && tableProps.colW) {
  243. tableCalcW = Array.isArray(tableProps.colW) ? tableProps.colW.reduce((p, n) => p + n) * EMU : tableProps.colW * numCols || 0
  244. if (tableProps.verbose) console.log(`| tableCalcW ...................................... = ${tableCalcW / EMU}`)
  245. }
  246. // STEP 4: Calculate usable width now that total usable space is known (`emuSlideTabW`)
  247. {
  248. emuSlideTabW = tableCalcW || inch2Emu((tablePropX ? tablePropX / EMU : arrInchMargins[1]) + arrInchMargins[3])
  249. if (tableProps.verbose) console.log(`| emuSlideTabW .................................... = ${(emuSlideTabW / EMU).toFixed(1)}`)
  250. }
  251. // STEP 5: Calculate column widths if not provided (emuSlideTabW will be used below to determine lines-per-col)
  252. if (!tableProps.colW || !Array.isArray(tableProps.colW)) {
  253. if (tableProps.colW && !isNaN(Number(tableProps.colW))) {
  254. const arrColW = []
  255. const firstRow = tableRows[0] || []
  256. firstRow.forEach(() => arrColW.push(tableProps.colW))
  257. tableProps.colW = []
  258. arrColW.forEach(val => {
  259. if (Array.isArray(tableProps.colW)) tableProps.colW.push(val)
  260. })
  261. } else {
  262. // No column widths provided? Then distribute cols.
  263. tableProps.colW = []
  264. for (let iCol = 0; iCol < numCols; iCol++) {
  265. tableProps.colW.push(emuSlideTabW / EMU / numCols)
  266. }
  267. }
  268. }
  269. // STEP 6: **MAIN** Iterate over rows, add table content, create new slides as rows overflow
  270. let newTableRowSlide: TableRowSlide = { rows: [] as TableRow[] }
  271. tableRows.forEach((row, iRow) => {
  272. // A: Row variables
  273. const rowCellLines: TableCell[] = []
  274. let maxCellMarTopEmu = 0
  275. let maxCellMarBtmEmu = 0
  276. // B: Create new row in data model, calc `maxCellMar*`
  277. let currTableRow: TableRow = []
  278. row.forEach(cell => {
  279. currTableRow.push({
  280. _type: SLIDE_OBJECT_TYPES.tablecell,
  281. text: [],
  282. options: cell.options,
  283. })
  284. /** FUTURE: DEPRECATED:
  285. * - Backwards-Compat: Oops! Discovered we were still using points for cell margin before v3.8.0 (UGH!)
  286. * - We cant introduce a breaking change before v4.0, so...
  287. */
  288. if (cell.options.margin && cell.options.margin[0] >= 1) {
  289. if (cell.options?.margin && cell.options.margin[0] && valToPts(cell.options.margin[0]) > maxCellMarTopEmu) maxCellMarTopEmu = valToPts(cell.options.margin[0])
  290. else if (tableProps?.margin && tableProps.margin[0] && valToPts(tableProps.margin[0]) > maxCellMarTopEmu) maxCellMarTopEmu = valToPts(tableProps.margin[0])
  291. if (cell.options?.margin && cell.options.margin[2] && valToPts(cell.options.margin[2]) > maxCellMarBtmEmu) maxCellMarBtmEmu = valToPts(cell.options.margin[2])
  292. else if (tableProps?.margin && tableProps.margin[2] && valToPts(tableProps.margin[2]) > maxCellMarBtmEmu) maxCellMarBtmEmu = valToPts(tableProps.margin[2])
  293. } else {
  294. if (cell.options?.margin && cell.options.margin[0] && inch2Emu(cell.options.margin[0]) > maxCellMarTopEmu) maxCellMarTopEmu = inch2Emu(cell.options.margin[0])
  295. else if (tableProps?.margin && tableProps.margin[0] && inch2Emu(tableProps.margin[0]) > maxCellMarTopEmu) maxCellMarTopEmu = inch2Emu(tableProps.margin[0])
  296. if (cell.options?.margin && cell.options.margin[2] && inch2Emu(cell.options.margin[2]) > maxCellMarBtmEmu) maxCellMarBtmEmu = inch2Emu(cell.options.margin[2])
  297. else if (tableProps?.margin && tableProps.margin[2] && inch2Emu(tableProps.margin[2]) > maxCellMarBtmEmu) maxCellMarBtmEmu = inch2Emu(tableProps.margin[2])
  298. }
  299. })
  300. // C: Calc usable vertical space/table height. Set default value first, adjust below when necessary.
  301. calcSlideTabH()
  302. emuTabCurrH += maxCellMarTopEmu + maxCellMarBtmEmu // Start row height with margins
  303. if (tableProps.verbose && iRow === 0) console.log(`| SLIDE [${tableRowSlides.length}]: emuSlideTabH ...... = ${(emuSlideTabH / EMU).toFixed(1)} `)
  304. // D: --==[[ BUILD DATA SET ]]==-- (iterate over cells: split text into lines[], set `lineHeight`)
  305. row.forEach((cell, iCell) => {
  306. const newCell: TableCell = {
  307. _type: SLIDE_OBJECT_TYPES.tablecell,
  308. _lines: null,
  309. _lineHeight: inch2Emu(
  310. ((cell.options?.fontSize ? cell.options.fontSize : tableProps.fontSize ? tableProps.fontSize : DEF_FONT_SIZE) *
  311. (LINEH_MODIFIER + (tableProps.autoPageLineWeight ? tableProps.autoPageLineWeight : 0))) /
  312. 100
  313. ),
  314. text: [],
  315. options: cell.options,
  316. }
  317. // E-1: Exempt cells with `rowspan` from increasing lineHeight (or we could create a new slide when unecessary!)
  318. if (newCell.options.rowspan) newCell._lineHeight = 0
  319. // E-2: The parseTextToLines method uses `autoPageCharWeight`, so inherit from table options
  320. newCell.options.autoPageCharWeight = tableProps.autoPageCharWeight ? tableProps.autoPageCharWeight : null
  321. // E-3: **MAIN** Parse cell contents into lines based upon col width, font, etc
  322. let totalColW = tableProps.colW[iCell]
  323. if (cell.options.colspan && Array.isArray(tableProps.colW)) {
  324. totalColW = tableProps.colW.filter((_cell, idx) => idx >= iCell && idx < idx + cell.options.colspan).reduce((prev, curr) => prev + curr)
  325. }
  326. // E-4: Create lines based upon available column width
  327. newCell._lines = parseTextToLines(cell, totalColW, false)
  328. // E-5: Add cell to array
  329. rowCellLines.push(newCell)
  330. })
  331. /** E: --==[[ PAGE DATA SET ]]==--
  332. * Add text one-line-a-time to this row's cells until: lines are exhausted OR table height limit is hit
  333. *
  334. * Design:
  335. * - Building cells L-to-R/loop style wont work as one could be 100 lines and another 1 line
  336. * - Therefore, build the whole row, one-line-at-a-time, across each table columns
  337. * - Then, when the vertical size limit is hit is by any of the cells, make a new slide and continue adding any remaining lines
  338. *
  339. * Implementation:
  340. * - `rowCellLines` is an array of cells, one for each column in the table, with each cell containing an array of lines
  341. *
  342. * Sample Data:
  343. * - `rowCellLines` ..: [ TableCell, TableCell, TableCell ]
  344. * - `TableCell` .....: { _type: 'tablecell', _lines: TableCell[], _lineHeight: 10 }
  345. * - `_lines` ........: [ {_type: 'tablecell', text: 'cell-1,line-1', options: {…}}, {_type: 'tablecell', text: 'cell-1,line-2', options: {…}} }
  346. * - `_lines` is TableCell[] (the 1-N words in the line)
  347. * {
  348. * _lines: [{ text:'cell-1,line-1' }, { text:'cell-1,line-2' }], // TOTAL-CELL-HEIGHT = 2
  349. * _lines: [{ text:'cell-2,line-1' }, { text:'cell-2,line-2' }], // TOTAL-CELL-HEIGHT = 2
  350. * _lines: [{ text:'cell-3,line-1' }, { text:'cell-3,line-2' }, { text:'cell-3,line-3' }, { text:'cell-3,line-4' }], // TOTAL-CELL-HEIGHT = 4
  351. * }
  352. *
  353. * Example: 2 rows, with the firstrow overflowing onto a new slide
  354. * SLIDE 1:
  355. * |--------|--------|--------|--------|
  356. * | line-1 | line-1 | line-1 | line-1 |
  357. * | | | line-2 | |
  358. * | | | line-3 | |
  359. * |--------|--------|--------|--------|
  360. *
  361. * SLIDE 2:
  362. * |--------|--------|--------|--------|
  363. * | | | line-4 | |
  364. * |--------|--------|--------|--------|
  365. * | line-1 | line-1 | line-1 | line-1 |
  366. * |--------|--------|--------|--------|
  367. */
  368. if (tableProps.verbose) console.log(`\n| SLIDE [${tableRowSlides.length}]: ROW [${iRow}]: START...`)
  369. let currCellIdx = 0
  370. let emuLineMaxH = 0
  371. let isDone = false
  372. while (!isDone) {
  373. const srcCell: TableCell = rowCellLines[currCellIdx]
  374. let tgtCell: TableCell = currTableRow[currCellIdx] // NOTE: may be redefined below (a new row may be created, thus changing this value)
  375. // 1: calc emuLineMaxH
  376. rowCellLines.forEach(cell => {
  377. if (cell._lineHeight >= emuLineMaxH) emuLineMaxH = cell._lineHeight
  378. })
  379. // 2: create a new slide if there is insufficient room for the current row
  380. if (emuTabCurrH + emuLineMaxH > emuSlideTabH) {
  381. if (tableProps.verbose) {
  382. console.log('\n|-----------------------------------------------------------------------|')
  383. // prettier-ignore
  384. console.log(`|-- NEW SLIDE CREATED (currTabH+currLineH > maxH) => ${(emuTabCurrH / EMU).toFixed(2)} + ${(srcCell._lineHeight / EMU).toFixed(2)} > ${emuSlideTabH / EMU}`)
  385. console.log('|-----------------------------------------------------------------------|\n\n')
  386. }
  387. // A: add current row slide or it will be lost (only if it has rows and text)
  388. if (currTableRow.length > 0 && currTableRow.map(cell => cell.text.length).reduce((p, n) => p + n) > 0) newTableRowSlide.rows.push(currTableRow)
  389. // B: add current slide to Slides array
  390. tableRowSlides.push(newTableRowSlide)
  391. // C: reset working/curr slide to hold rows as they're created
  392. const newRows: TableRow[] = []
  393. newTableRowSlide = { rows: newRows }
  394. // D: reset working/curr row
  395. currTableRow = []
  396. row.forEach(cell => currTableRow.push({ _type: SLIDE_OBJECT_TYPES.tablecell, text: [], options: cell.options }))
  397. // E: Calc usable vertical space/table height now as we may still be in the same row and code above ("C: Calc usable vertical space/table height.") calc may now be invalid
  398. calcSlideTabH()
  399. emuTabCurrH += maxCellMarTopEmu + maxCellMarBtmEmu // Start row height with margins
  400. if (tableProps.verbose) console.log(`| SLIDE [${tableRowSlides.length}]: emuSlideTabH ...... = ${(emuSlideTabH / EMU).toFixed(1)} `)
  401. // F: reset current table height for this new Slide
  402. emuTabCurrH = 0
  403. // G: handle repeat headers option /or/ Add new empty row to continue current lines into
  404. if ((tableProps.addHeaderToEach || tableProps.autoPageRepeatHeader) && tableProps._arrObjTabHeadRows) {
  405. tableProps._arrObjTabHeadRows.forEach(row => {
  406. const newHeadRow: TableRow = []
  407. let maxLineHeight = 0
  408. row.forEach(cell => {
  409. newHeadRow.push(cell)
  410. if (cell._lineHeight > maxLineHeight) maxLineHeight = cell._lineHeight
  411. })
  412. newTableRowSlide.rows.push(newHeadRow)
  413. emuTabCurrH += maxLineHeight // TODO: what about margins? dont we need to include cell margin in line height?
  414. })
  415. }
  416. // WIP: NEW: TEST THIS!!
  417. tgtCell = currTableRow[currCellIdx]
  418. }
  419. // 3: set array of words that comprise this line
  420. const currLine: TableCell[] = srcCell._lines.shift()
  421. // 4: create new line by adding all words from curr line (or add empty if there are no words to avoid "needs repair" issue triggered when cells have null content)
  422. if (Array.isArray(tgtCell.text)) {
  423. if (currLine) tgtCell.text = tgtCell.text.concat(currLine)
  424. else if (tgtCell.text.length === 0) tgtCell.text = tgtCell.text.concat({ _type: SLIDE_OBJECT_TYPES.tablecell, text: '' })
  425. // IMPORTANT: ^^^ add empty if there are no words to avoid "needs repair" issue triggered when cells have null content
  426. }
  427. // 5: increase table height by the curr line height (if we're on the last column)
  428. if (currCellIdx === rowCellLines.length - 1) emuTabCurrH += emuLineMaxH
  429. // 6: advance column/cell index (or circle back to first one to continue adding lines)
  430. currCellIdx = currCellIdx < rowCellLines.length - 1 ? currCellIdx + 1 : 0
  431. // 7: WIP: done?
  432. const brent = rowCellLines.map(cell => cell._lines.length).reduce((prev, next) => prev + next)
  433. if (brent === 0) isDone = true
  434. }
  435. // F: Flush/capture row buffer before it resets at the top of this loop
  436. if (currTableRow.length > 0) newTableRowSlide.rows.push(currTableRow)
  437. if (tableProps.verbose) {
  438. console.log(
  439. `- SLIDE [${tableRowSlides.length}]: ROW [${iRow}]: ...COMPLETE ...... emuTabCurrH = ${(emuTabCurrH / EMU).toFixed(2)} ( emuSlideTabH = ${(
  440. emuSlideTabH / EMU
  441. ).toFixed(2)} )`
  442. )
  443. }
  444. })
  445. // STEP 7: Flush buffer / add final slide
  446. tableRowSlides.push(newTableRowSlide)
  447. if (tableProps.verbose) {
  448. console.log('\n|================================================|')
  449. console.log(`| FINAL: tableRowSlides.length = ${tableRowSlides.length}`)
  450. tableRowSlides.forEach(slide => console.log(slide))
  451. console.log('|================================================|\n\n')
  452. }
  453. // LAST:
  454. return tableRowSlides
  455. }
  456. /**
  457. * Reproduces an HTML table as a PowerPoint table - including column widths, style, etc. - creates 1 or more slides as needed
  458. * @param {PptxGenJS} pptx - pptxgenjs instance
  459. * @param {string} tabEleId - HTMLElementID of the table
  460. * @param {ITableToSlidesOpts} options - array of options (e.g.: tabsize)
  461. * @param {SlideLayout} masterSlide - masterSlide
  462. */
  463. export function genTableToSlides(pptx: PptxGenJS, tabEleId: string, options: TableToSlidesProps = {}, masterSlide?: SlideLayout): void {
  464. const opts = options || {}
  465. opts.slideMargin = opts.slideMargin || opts.slideMargin === 0 ? opts.slideMargin : 0.5
  466. let emuSlideTabW = opts.w || pptx.presLayout.width
  467. const arrObjTabHeadRows: [TableCell[]?] = []
  468. const arrObjTabBodyRows: [TableCell[]?] = []
  469. const arrObjTabFootRows: [TableCell[]?] = []
  470. const arrColW: number[] = []
  471. const arrTabColW: number[] = []
  472. let arrInchMargins: [number, number, number, number] = [0.5, 0.5, 0.5, 0.5] // TRBL-style
  473. let intTabW = 0
  474. // REALITY-CHECK:
  475. if (!document.getElementById(tabEleId)) throw new Error('tableToSlides: Table ID "' + tabEleId + '" does not exist!')
  476. // STEP 1: Set margins
  477. if (masterSlide?._margin) {
  478. if (Array.isArray(masterSlide._margin)) arrInchMargins = masterSlide._margin
  479. else if (!isNaN(masterSlide._margin)) arrInchMargins = [masterSlide._margin, masterSlide._margin, masterSlide._margin, masterSlide._margin]
  480. opts.slideMargin = arrInchMargins
  481. } else if (opts?.slideMargin) {
  482. if (Array.isArray(opts.slideMargin)) arrInchMargins = opts.slideMargin
  483. else if (!isNaN(opts.slideMargin)) arrInchMargins = [opts.slideMargin, opts.slideMargin, opts.slideMargin, opts.slideMargin]
  484. }
  485. emuSlideTabW = (opts.w ? inch2Emu(opts.w) : pptx.presLayout.width) - inch2Emu(arrInchMargins[1] + arrInchMargins[3])
  486. if (opts.verbose) {
  487. console.log('[[VERBOSE MODE]]')
  488. console.log('|-- `tableToSlides` ----------------------------------------------------|')
  489. console.log(`| tableProps.h .................................... = ${opts.h}`)
  490. console.log(`| tableProps.w .................................... = ${opts.w}`)
  491. console.log(`| pptx.presLayout.width ........................... = ${(pptx.presLayout.width / EMU).toFixed(1)}`)
  492. console.log(`| pptx.presLayout.height .......................... = ${(pptx.presLayout.height / EMU).toFixed(1)}`)
  493. console.log(`| emuSlideTabW .................................... = ${(emuSlideTabW / EMU).toFixed(1)}`)
  494. }
  495. // STEP 2: Grab table col widths - just find the first availble row, either thead/tbody/tfoot, others may have colspans, who cares, we only need col widths from 1
  496. let firstRowCells = document.querySelectorAll(`#${tabEleId} tr:first-child th`)
  497. if (firstRowCells.length === 0) firstRowCells = document.querySelectorAll(`#${tabEleId} tr:first-child td`)
  498. firstRowCells.forEach((cellEle: Element) => {
  499. const cell = cellEle as HTMLTableCellElement
  500. if (cell.getAttribute('colspan')) {
  501. // Guesstimate (divide evenly) col widths
  502. // NOTE: both j$query and vanilla selectors return {0} when table is not visible)
  503. for (let idxc = 0; idxc < Number(cell.getAttribute('colspan')); idxc++) {
  504. arrTabColW.push(Math.round(cell.offsetWidth / Number(cell.getAttribute('colspan'))))
  505. }
  506. } else {
  507. arrTabColW.push(cell.offsetWidth)
  508. }
  509. })
  510. arrTabColW.forEach(colW => {
  511. intTabW += colW
  512. })
  513. // STEP 3: Calc/Set column widths by using same column width percent from HTML table
  514. arrTabColW.forEach((colW, idxW) => {
  515. const intCalcWidth = Number(((Number(emuSlideTabW) * ((colW / intTabW) * 100)) / 100 / EMU).toFixed(2))
  516. let intMinWidth = 0
  517. const colSelectorMin = document.querySelector(`#${tabEleId} thead tr:first-child th:nth-child(${idxW + 1})`)
  518. if (colSelectorMin) intMinWidth = Number(colSelectorMin.getAttribute('data-pptx-min-width'))
  519. const intSetWidth = 0
  520. const colSelectorSet = document.querySelector(`#${tabEleId} thead tr:first-child th:nth-child(${idxW + 1})`)
  521. if (colSelectorSet) intMinWidth = Number(colSelectorSet.getAttribute('data-pptx-width'))
  522. arrColW.push(intSetWidth || (intMinWidth > intCalcWidth ? intMinWidth : intCalcWidth))
  523. })
  524. if (opts.verbose) {
  525. console.log(`| arrColW ......................................... = [${arrColW.join(', ')}]`)
  526. }
  527. // STEP 4: Iterate over each table element and create data arrays (text and opts)
  528. // NOTE: We create 3 arrays instead of one so we can loop over body then show header/footer rows on first and last page
  529. const tableParts = ['thead', 'tbody', 'tfoot']
  530. tableParts.forEach(part => {
  531. document.querySelectorAll(`#${tabEleId} ${part} tr`).forEach((row: Element) => {
  532. const htmlRow = row as HTMLTableRowElement
  533. const arrObjTabCells: TableCell[] = []
  534. Array.from(htmlRow.cells).forEach(cell => {
  535. // A: Get RGB text/bkgd colors
  536. const arrRGB1 = window.getComputedStyle(cell).getPropertyValue('color').replace(/\s+/gi, '').replace('rgba(', '').replace('rgb(', '').replace(')', '').split(',')
  537. let arrRGB2 = window
  538. .getComputedStyle(cell)
  539. .getPropertyValue('background-color')
  540. .replace(/\s+/gi, '')
  541. .replace('rgba(', '')
  542. .replace('rgb(', '')
  543. .replace(')', '')
  544. .split(',')
  545. if (
  546. // NOTE: (ISSUE#57): Default for unstyled tables is black bkgd, so use white instead
  547. window.getComputedStyle(cell).getPropertyValue('background-color') === 'rgba(0, 0, 0, 0)' ||
  548. window.getComputedStyle(cell).getPropertyValue('transparent')
  549. ) {
  550. arrRGB2 = ['255', '255', '255']
  551. }
  552. // B: Create option object
  553. const cellOpts: TableCellProps = {
  554. align: null,
  555. bold:
  556. !!(window.getComputedStyle(cell).getPropertyValue('font-weight') === 'bold' ||
  557. Number(window.getComputedStyle(cell).getPropertyValue('font-weight')) >= 500),
  558. border: null,
  559. color: rgbToHex(Number(arrRGB1[0]), Number(arrRGB1[1]), Number(arrRGB1[2])),
  560. fill: { color: rgbToHex(Number(arrRGB2[0]), Number(arrRGB2[1]), Number(arrRGB2[2])) },
  561. fontFace:
  562. (window.getComputedStyle(cell).getPropertyValue('font-family') || '').split(',')[0].replace(/"/g, '').replace('inherit', '').replace('initial', '') ||
  563. null,
  564. fontSize: Number(window.getComputedStyle(cell).getPropertyValue('font-size').replace(/[a-z]/gi, '')),
  565. margin: null,
  566. colspan: Number(cell.getAttribute('colspan')) || null,
  567. rowspan: Number(cell.getAttribute('rowspan')) || null,
  568. valign: null,
  569. }
  570. if (['left', 'center', 'right', 'start', 'end'].includes(window.getComputedStyle(cell).getPropertyValue('text-align'))) {
  571. const align = window.getComputedStyle(cell).getPropertyValue('text-align').replace('start', 'left').replace('end', 'right')
  572. cellOpts.align = align === 'center' ? 'center' : align === 'left' ? 'left' : align === 'right' ? 'right' : null
  573. }
  574. if (['top', 'middle', 'bottom'].includes(window.getComputedStyle(cell).getPropertyValue('vertical-align'))) {
  575. const valign = window.getComputedStyle(cell).getPropertyValue('vertical-align')
  576. cellOpts.valign = valign === 'top' ? 'top' : valign === 'middle' ? 'middle' : valign === 'bottom' ? 'bottom' : null
  577. }
  578. // C: Add padding [margin] (if any)
  579. // NOTE: Margins translate: px->pt 1:1 (e.g.: a 20px padded cell looks the same in PPTX as 20pt Text Inset/Padding)
  580. if (window.getComputedStyle(cell).getPropertyValue('padding-left')) {
  581. cellOpts.margin = [0, 0, 0, 0]
  582. const sidesPad = ['padding-top', 'padding-right', 'padding-bottom', 'padding-left']
  583. sidesPad.forEach((val, idxs) => {
  584. cellOpts.margin[idxs] = Math.round(Number(window.getComputedStyle(cell).getPropertyValue(val).replace(/\D/gi, '')))
  585. })
  586. }
  587. // D: Add border (if any)
  588. if (
  589. window.getComputedStyle(cell).getPropertyValue('border-top-width') ||
  590. window.getComputedStyle(cell).getPropertyValue('border-right-width') ||
  591. window.getComputedStyle(cell).getPropertyValue('border-bottom-width') ||
  592. window.getComputedStyle(cell).getPropertyValue('border-left-width')
  593. ) {
  594. cellOpts.border = [null, null, null, null]
  595. const sidesBor = ['top', 'right', 'bottom', 'left']
  596. sidesBor.forEach((val, idxb) => {
  597. const intBorderW = Math.round(
  598. Number(
  599. window
  600. .getComputedStyle(cell)
  601. .getPropertyValue('border-' + val + '-width')
  602. .replace('px', '')
  603. )
  604. )
  605. let arrRGB = []
  606. arrRGB = window
  607. .getComputedStyle(cell)
  608. .getPropertyValue('border-' + val + '-color')
  609. .replace(/\s+/gi, '')
  610. .replace('rgba(', '')
  611. .replace('rgb(', '')
  612. .replace(')', '')
  613. .split(',')
  614. const strBorderC = rgbToHex(Number(arrRGB[0]), Number(arrRGB[1]), Number(arrRGB[2]))
  615. cellOpts.border[idxb] = { pt: intBorderW, color: strBorderC }
  616. })
  617. }
  618. // LAST: Add cell
  619. arrObjTabCells.push({
  620. _type: SLIDE_OBJECT_TYPES.tablecell,
  621. text: cell.innerText, // `innerText` returns <br> as "\n", so linebreak etc. work later!
  622. options: cellOpts,
  623. })
  624. })
  625. switch (part) {
  626. case 'thead':
  627. arrObjTabHeadRows.push(arrObjTabCells)
  628. break
  629. case 'tbody':
  630. arrObjTabBodyRows.push(arrObjTabCells)
  631. break
  632. case 'tfoot':
  633. arrObjTabFootRows.push(arrObjTabCells)
  634. break
  635. default:
  636. console.log(`table parsing: unexpected table part: ${part}`)
  637. break
  638. }
  639. })
  640. })
  641. // STEP 5: Break table into Slides as needed
  642. // Pass head-rows as there is an option to add to each table and the parse func needs this data to fulfill that option
  643. opts._arrObjTabHeadRows = arrObjTabHeadRows || null
  644. opts.colW = arrColW
  645. getSlidesForTableRows([...arrObjTabHeadRows, ...arrObjTabBodyRows, ...arrObjTabFootRows], opts, pptx.presLayout, masterSlide).forEach((slide, idxTr) => {
  646. // A: Create new Slide
  647. const newSlide = pptx.addSlide({ masterName: opts.masterSlideName || null })
  648. // B: DESIGN: Reset `y` to startY or margin after first Slide (ISSUE#43, ISSUE#47, ISSUE#48)
  649. if (idxTr === 0) opts.y = opts.y || arrInchMargins[0]
  650. if (idxTr > 0) opts.y = opts.autoPageSlideStartY || opts.newSlideStartY || arrInchMargins[0]
  651. if (opts.verbose) console.log(`| opts.autoPageSlideStartY: ${opts.autoPageSlideStartY} / arrInchMargins[0]: ${arrInchMargins[0]} => opts.y = ${opts.y}`)
  652. // C: Add table to Slide
  653. newSlide.addTable(slide.rows, { x: opts.x || arrInchMargins[3], y: opts.y, w: Number(emuSlideTabW) / EMU, colW: arrColW, autoPage: false })
  654. // D: Add any additional objects
  655. if (opts.addImage) {
  656. opts.addImage.options = opts.addImage.options || {}
  657. if (!opts.addImage.image || (!opts.addImage.image.path && !opts.addImage.image.data)) {
  658. console.warn('Warning: tableToSlides.addImage requires either `path` or `data`')
  659. } else {
  660. newSlide.addImage({
  661. path: opts.addImage.image.path,
  662. data: opts.addImage.image.data,
  663. x: opts.addImage.options.x,
  664. y: opts.addImage.options.y,
  665. w: opts.addImage.options.w,
  666. h: opts.addImage.options.h,
  667. })
  668. }
  669. }
  670. if (opts.addShape) newSlide.addShape(opts.addShape.shapeName, opts.addShape.options || {})
  671. if (opts.addTable) newSlide.addTable(opts.addTable.rows, opts.addTable.options || {})
  672. if (opts.addText) newSlide.addText(opts.addText.text, opts.addText.options || {})
  673. })
  674. }