(element: HTMLTableElement | string, rootDocument: Document = document)
| 269 | */ |
| 270 | // eslint-disable-next-line no-restricted-globals |
| 271 | export function htmlToGridSettings(element: HTMLTableElement | string, rootDocument: Document = document) { |
| 272 | const settingsObj: Record<string, unknown> = {}; |
| 273 | const fragment = rootDocument.createDocumentFragment(); |
| 274 | const tempElem = rootDocument.createElement('div'); |
| 275 | |
| 276 | fragment.appendChild(tempElem); |
| 277 | |
| 278 | let checkElement: HTMLTableElement | string | null = element; |
| 279 | |
| 280 | if (typeof checkElement === 'string') { |
| 281 | // Use replaceTdCellsWithTextContent so nested <td> (e.g. Excel shape cells) are matched correctly |
| 282 | const normalizedHTML = replaceTdCellsWithTextContent(checkElement); |
| 283 | |
| 284 | tempElem.insertAdjacentHTML('afterbegin', normalizedHTML); |
| 285 | checkElement = tempElem.querySelector<HTMLTableElement>('table'); |
| 286 | } |
| 287 | |
| 288 | if (!checkElement || !isHTMLTable(checkElement as HTMLElement)) { |
| 289 | return; |
| 290 | } |
| 291 | |
| 292 | const el: HTMLTableElement = checkElement as HTMLTableElement; |
| 293 | const generator = tempElem.querySelector('meta[name$="enerator"]') as HTMLMetaElement | null; |
| 294 | const hasRowHeaders = el.querySelector('tbody th') !== null; |
| 295 | const trElement = el.querySelector('tr') as HTMLTableRowElement | null; |
| 296 | const countCols = !trElement ? 0 : (Array.from(trElement.cells) |
| 297 | .reduce((cols: number, cell: HTMLTableCellElement) => cols + cell.colSpan, 0)) - (hasRowHeaders ? 1 : 0); |
| 298 | const fixedRowsBottom: HTMLTableRowElement[] = el.tFoot && Array.from(el.tFoot.rows) || []; |
| 299 | const fixedRowsTop: HTMLTableRowElement[] = []; |
| 300 | let hasColHeaders = false; |
| 301 | let thRowsLen = 0; |
| 302 | let countRows = 0; |
| 303 | |
| 304 | if (el.tHead) { |
| 305 | const thRows = Array.from(el.tHead.rows).filter((tr: HTMLTableRowElement) => { |
| 306 | const isDataRow = tr.querySelector('td') !== null; |
| 307 | |
| 308 | if (isDataRow) { |
| 309 | fixedRowsTop.push(tr); |
| 310 | } |
| 311 | |
| 312 | return !isDataRow; |
| 313 | }); |
| 314 | |
| 315 | thRowsLen = thRows.length; |
| 316 | hasColHeaders = thRowsLen > 0; |
| 317 | |
| 318 | if (thRowsLen > 1) { |
| 319 | settingsObj.nestedHeaders = Array.from(thRows).reduce((rows: unknown[], row: HTMLTableRowElement) => { |
| 320 | const headersRow = Array.from(row.cells).reduce( |
| 321 | (headers: unknown[], header: HTMLTableCellElement, currentIndex: number) => { |
| 322 | if (hasRowHeaders && currentIndex === 0) { |
| 323 | return headers; |
| 324 | } |
| 325 | |
| 326 | const { |
| 327 | colSpan: colspan, |
| 328 | innerHTML, |
no test coverage detected
searching dependent graphs…