@ai-matrx/office 0.3.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +15 -0
- package/dist/chunk-5T2M6LSI.js +529 -0
- package/dist/chunk-5T2M6LSI.js.map +1 -0
- package/dist/chunk-QZE7HBZB.cjs +529 -0
- package/dist/chunk-QZE7HBZB.cjs.map +1 -0
- package/dist/chunk-WKBWRG7N.js +209 -0
- package/dist/chunk-WKBWRG7N.js.map +1 -0
- package/dist/chunk-ZDZCCOUB.cjs +209 -0
- package/dist/chunk-ZDZCCOUB.cjs.map +1 -0
- package/dist/core.d.cts +5 -1
- package/dist/core.d.ts +5 -1
- package/dist/matrxImagePorts-JDFYE4QI.cjs +59 -0
- package/dist/matrxImagePorts-JDFYE4QI.cjs.map +1 -0
- package/dist/matrxImagePorts-VPBBUADM.js +59 -0
- package/dist/matrxImagePorts-VPBBUADM.js.map +1 -0
- package/dist/sheets-xlsx.cjs +525 -0
- package/dist/sheets-xlsx.cjs.map +1 -0
- package/dist/sheets-xlsx.d.cts +153 -0
- package/dist/sheets-xlsx.d.ts +153 -0
- package/dist/sheets-xlsx.js +525 -0
- package/dist/sheets-xlsx.js.map +1 -0
- package/dist/sheets.cjs +921 -0
- package/dist/sheets.cjs.map +1 -0
- package/dist/sheets.d.cts +605 -0
- package/dist/sheets.d.ts +605 -0
- package/dist/sheets.js +921 -0
- package/dist/sheets.js.map +1 -0
- package/dist/univer-collab.cjs +2 -78
- package/dist/univer-collab.cjs.map +1 -1
- package/dist/univer-collab.d.cts +7 -15
- package/dist/univer-collab.d.ts +7 -15
- package/dist/univer-collab.js +2 -78
- package/dist/univer-collab.js.map +1 -1
- package/dist/univer-realtime.cjs +102 -0
- package/dist/univer-realtime.cjs.map +1 -0
- package/dist/univer-realtime.d.cts +15 -0
- package/dist/univer-realtime.d.ts +15 -0
- package/dist/univer-realtime.js +80 -0
- package/dist/univer-realtime.js.map +1 -0
- package/dist/xlsx-to-univer-AQAXU3TC.cjs +7 -0
- package/dist/xlsx-to-univer-AQAXU3TC.cjs.map +1 -0
- package/dist/xlsx-to-univer-OPMMBWEW.js +7 -0
- package/dist/xlsx-to-univer-OPMMBWEW.js.map +1 -0
- package/package.json +41 -4
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/aidream/aidream/apps/shared/office/dist/sheets-xlsx.cjs","../src/sheets/univer-to-xlsx.ts","../src/sheets/import-workbook-file.ts"],"names":[],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACA;ACVA,oDAA0B;AAG1B,kDAA6B;AAC7B,yDAA+C;AAoCxC,SAAS,4BAAA,CAA6B,QAAA,EAAkC;AAC7E,EAAA,MAAM,WAAA,mBAAa,QAAA,CAAS,UAAA,UAAc,MAAA,CAAO,IAAA,kBAAK,QAAA,CAAS,MAAA,UAAU,CAAC,GAAC,GAAA;AAC3E,EAAA,MAAM,OAAA,EAAiC,CAAC,CAAA;AACxC,EAAA,IAAA,CAAA,MAAW,QAAA,GAAW,UAAA,EAAY;AAChC,IAAA,MAAM,MAAA,kBAAQ,QAAA,mBAAS,MAAA,4BAAA,CAAS,OAAO,GAAA;AACvC,IAAA,GAAA,CAAI,CAAC,KAAA,EAAO,QAAA;AACZ,IAAA,MAAA,CAAO,IAAA,CAAK,WAAA,CAAY,KAAA,EAAA,kBAAQ,KAAA,CAAM,IAAA,UAAQ,SAAA,CAAA,CAAS,KAAA,CAAM,CAAA,EAAG,EAAE,EAAA,GAAK,QAAQ,CAAC,CAAA;AAAA,EAClF;AACA,EAAA,OAAO,EAAE,OAAO,CAAA;AAClB;AAGA,MAAA,SAAsB,yBAAA,CACpB,QAAA,EACA,QAAA,EAAmD,CAAC,CAAA,EAC/B;AACrB,EAAA,OAAA,CAAQ,MAAM,mBAAA,CAAoB,QAAA,EAAU,OAAO,CAAA,CAAA,CAAG,KAAA;AACxD;AAGA,MAAA,SAAsB,oBAAA,CACpB,QAAA,EACA,QAAA,EAA6B,CAAC,CAAA,EACH;AAC3B,EAAA,GAAA,CAAI,OAAO,SAAA,IAAa,WAAA,EAAa,OAAO,EAAE,OAAA,EAAS,CAAC,EAAE,CAAA;AAC1D,EAAA,MAAM,SAAA,EAAW,CAAA,EAAA;AACF,EAAA;AACE,EAAA;AACT,IAAA;AACP,EAAA;AACY,EAAA;AACN,EAAA;AACT;AAIsB;AAIJ,EAAA;AACD,EAAA;AACC,EAAA;AACG,EAAA;AACH,EAAA;AAEV,EAAA;AACA,EAAA;AACU,EAAA;AACF,EAAA;AACG,EAAA;AACA,EAAA;AACF,EAAA;AAED,EAAA;AACH,EAAA;AACK,IAAA;AACF,IAAA;AACE,IAAA;AACC,IAAA;AACC,IAAA;AACJ,IAAA;AACA,IAAA;AACI,IAAA;AAChB,IAAA;AACgB,IAAA;AACD,IAAA;AACT,IAAA;AACK,IAAA;AACG,MAAA;AACd,IAAA;AACF,EAAA;AAEe,EAAA;AACC,EAAA;AAClB;AAEoB;AACF,EAAA;AACR,EAAA;AACE,EAAA;AACH,EAAA;AACT;AAEiB;AACA,EAAA;AACA,EAAA;AACD,EAAA;AAChB;AAEoB;AACT,EAAA;AACiC,EAAA;AAC1B,EAAA;AACF,EAAA;AACG,EAAA;AACA,EAAA;AACsB,EAAA;AACA,EAAA;AAC5B,EAAA;AACE,EAAA;AACG,EAAA;AACL,EAAA;AACI,EAAA;AACoC,EAAA;AACrC,EAAA;AACA,EAAA;AACG,EAAA;AACD,EAAA;AACF,EAAA;AACN,EAAA;AACyC,IAAA;AACnC,IAAA;AACG,MAAA;AACC,MAAA;AACH,MAAA;AACY,QAAA;AACvB,MAAA;AACF,IAAA;AACgB,IAAA;AAClB,EAAA;AACiB,EAAA;AACN,EAAA;AACb;AAEmB;AACA,EAAA;AACnB;AAEyD;AACrC,EAAA;AACH,EAAA;AACjB;AAEoB;AACD,EAAA;AACN,EAAA;AACC,IAAA;AACE,IAAA;AACC,IAAA;AACF,IAAA;AACC,MAAA;AACG,MAAA;AACC,MAAA;AACR,MAAA;AACA,MAAA;AACO,MAAA;AACuB,MAAA;AAC3B,MAAA;AACE,QAAA;AACA,QAAA;AACJ,QAAA;AACI,MAAA;AACD,QAAA;AACV,MAAA;AACY,MAAA;AACH,MAAA;AACI,MAAA;AACC,MAAA;AACH,MAAA;AACb,IAAA;AACF,EAAA;AACF;AAES;AACD,EAAA;AACU,EAAA;AACE,EAAA;AACN,IAAA;AACE,IAAA;AACF,IAAA;AACK,IAAA;AACA,IAAA;AACN,IAAA;AACM,IAAA;AACjB,EAAA;AACa,EAAA;AACK,EAAA;AACN,IAAA;AACE,IAAA;AACF,IAAA;AACK,IAAA;AACA,IAAA;AACA,IAAA;AACjB,EAAA;AACgB,EAAA;AACV,IAAA;AACY,MAAA;AACR,IAAA;AAER,IAAA;AACF,EAAA;AACe,EAAA;AACA,EAAA;AACC,IAAA;AAChB,EAAA;AACF;AAEkB;AACR,EAAA;AACQ,EAAA;AACC,IAAA;AACJ,MAAA;AACG,QAAA;AACC,QAAA;AACb,MAAA;AACF,IAAA;AACF,EAAA;AACO,EAAA;AACT;AAES;AACI,EAAA;AACI,IAAA;AACM,IAAA;AACL,MAAA;AACZ,MAAA;AACY,MAAA;AACA,MAAA;AACZ,MAAA;AACa,MAAA;AACA,MAAA;AACf,IAAA;AACsB,IAAA;AACT,IAAA;AACA,MAAA;AACL,MAAA;AACI,MAAA;AACG,MAAA;AACJ,IAAA;AACC,MAAA;AACE,MAAA;AACF,IAAA;AACL,MAAA;AACA,QAAA;AACH,QAAA;AACU,QAAA;AACC,QAAA;AACb,MAAA;AACS,IAAA;AACC,MAAA;AACZ,IAAA;AACS,IAAA;AACD,IAAA;AACF,IAAA;AACO,MAAA;AACZ,IAAA;AACc,IAAA;AACjB,EAAA;AACF;AAEmB;AAEF;AACI,EAAA;AACC,EAAA;AACT,EAAA;AACE,EAAA;AACK,EAAA;AACA,EAAA;AACF,EAAA;AACL,EAAA;AACC,EAAA;AACL,EAAA;AACT;AAES;AACI,EAAA;AACO,IAAA;AACJ,IAAA;AACA,IAAA;AACE,IAAA;AACE,IAAA;AACH,IAAA;AACU,IAAA;AACb,IAAA;AACM,MAAA;AACD,MAAA;AACN,QAAA;AACC,UAAA;AACM,YAAA;AACV,UAAA;AACA,UAAA;AACG,QAAA;AACM,UAAA;AACT,UAAA;AACG,QAAA;AACK,UAAA;AACR,UAAA;AACG,QAAA;AACK,UAAA;AACR,UAAA;AACG,QAAA;AACK,UAAA;AACR,UAAA;AACJ,MAAA;AACS,IAAA;AACI,MAAA;AACP,MAAA;AACE,QAAA;AACI,QAAA;AACC,QAAA;AACb,MAAA;AACS,IAAA;AACH,MAAA;AACE,QAAA;AACI,QAAA;AACD,QAAA;AACA,QAAA;AACX,MAAA;AACF,IAAA;AACU,IAAA;AACI,MAAA;AACZ,MAAA;AACF,IAAA;AACG,IAAA;AACL,EAAA;AACF;AAES;AACK,EAAA;AACF,EAAA;AACM,EAAA;AACD,IAAA;AACE,IAAA;AACjB,EAAA;AACa,EAAA;AACC,IAAA;AACd,EAAA;AACF;AAEoB;AACD,EAAA;AACnB;AAEoB;AACD,EAAA;AACH,IAAA;AACG,MAAA;AACA,MAAA;AACf,IAAA;AACF,EAAA;AACqB,EAAA;AACL,EAAA;AACA,EAAA;AACD,IAAA;AACC,IAAA;AACA,IAAA;AACA,IAAA;AACH,IAAA;AACK,MAAA;AAChB,IAAA;AACc,IAAA;AAChB,EAAA;AACiB,EAAA;AACC,IAAA;AACV,IAAA;AACO,IAAA;AACf,EAAA;AACkB,EAAA;AACpB;AAEe;AAOC,EAAA;AACE,EAAA;AACR,IAAA;AACS,IAAA;AACJ,IAAA;AACoB,IAAA;AACS,IAAA;AACxB,IAAA;AACH,IAAA;AACC,MAAA;AACJ,MAAA;AACC,IAAA;AACL,MAAA;AACU,QAAA;AACA,QAAA;AACN,MAAA;AACE,QAAA;AACV,MAAA;AACF,IAAA;AACY,IAAA;AACE,MAAA;AACZ,MAAA;AACF,IAAA;AACc,IAAA;AACE,IAAA;AACH,MAAA;AACG,MAAA;AACf,IAAA;AACH,EAAA;AACF;AAIS;AACU,EAAA;AAC4B,EAAA;AAClC,EAAA;AACC,IAAA;AACE,IAAA;AACA,IAAA;AACF,IAAA;AACC,IAAA;AACC,MAAA;AACE,MAAA;AACC,MAAA;AACF,MAAA;AACC,MAAA;AACF,MAAA;AACE,MAAA;AACC,MAAA;AACD,MAAA;AACF,MAAA;AACZ,IAAA;AACF,EAAA;AACgB,EAAA;AACJ,IAAA;AACA,IAAA;AACV,EAAA;AACa,EAAA;AACjB;AAES;AACS,EAAA;AACZ,EAAA;AACY,EAAA;AACT,IAAA;AACQ,MAAA;AACX,MAAA;AACG,IAAA;AACQ,MAAA;AACX,MAAA;AACF,IAAA;AACQ,MAAA;AACD,QAAA;AAEI,QAAA;AAKT,MAAA;AACJ,EAAA;AACe,EAAA;AACE,EAAA;AACnB;AAGsB;AACN,EAAA;AACJ,IAAA;AACR,IAAA;AACF,EAAA;AACa,EAAA;AACf;AD9EoB;AACA;AEpbX;AAgBO;AACI,EAAA;AAGF,EAAA;AAIP,IAAA;AACT,EAAA;AACkB,EAAA;AAIA,EAAA;AACT,IAAA;AACT,EAAA;AAEgB,EAAA;AAClB;AAEsB;AAId,EAAA;AAGE,EAAA;AAEF,EAAA;AACE,EAAA;AACS,EAAA;AACF,IAAA;AACD,IAAA;AACb,EAAA;AAOG,EAAA;AACA,EAAA;AACI,IAAA;AACN,IAAA;AACO,EAAA;AACC,IAAA;AACN,MAAA;AACA,MAAA;AACF,IAAA;AACF,EAAA;AAEkB,EAAA;AACF,EAAA;AACR,IAAA;AACO,IAAA;AACA,IAAA;AAGG,IAAA;AACZ,IAAA;AACL,EAAA;AACG,EAAA;AAEU,EAAA;AACA,IAAA;AACZ,IAAA;AACQ,IAAA;AACI,IAAA;AACb,EAAA;AACG,EAAA;AAKI,IAAA;AACU,IAAA;AAClB,EAAA;AAEa,EAAA;AACf;AFwYoB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/aidream/aidream/apps/shared/office/dist/sheets-xlsx.cjs","sourcesContent":[null,"/**\n * univerToXlsx — convert a Univer IWorkbookData snapshot to an .xlsx file.\n *\n * Symmetric counterpart to `xlsx-to-univer.ts`. Carries everything the xlsx\n * format can hold from what Univer holds: values, formulas, merged ranges,\n * cell styles and number formats, column widths, row heights, frozen panes,\n * data validation, conditional formatting, the header-row filter range,\n * notes, comment threads (as notes), cell links, and pictures.\n *\n * What it cannot carry is NAMED in the returned report and shown to the person\n * at export time — never dropped silently.\n *\n * Engine: ExcelJS (the xlsx reader/writer that holds styles, validation,\n * conditional formatting, notes, links and images; the registered\n * `xlsx-workbook` format writes values only). It is loaded on demand, so\n * the editor bundle does not pay for it until someone exports or imports.\n */\n\nimport { buildFile } from \"@ai-matrx/alchemy/operate\";\nimport type { WorkbookCellJson, WorkbookJson } from \"@ai-matrx/alchemy/operate/read\";\nimport type { ICellData, IWorkbookData, IWorksheetData } from \"@univerjs/core\";\nimport { downloadFile } from \"@ai-matrx/kit/download\";\nimport { loadExcelJs, type ExcelJSTypes } from \"@ai-matrx/print/xlsx-styled\";\nimport {\n H_ALIGN_OUT,\n RESOURCE,\n V_ALIGN_OUT,\n borderToExcel,\n colPxToChars,\n colorToArgb,\n readResource,\n rangeToA1,\n rowPxToPt,\n type RangeLike,\n type UniverResource,\n} from \"./xlsx-shared\";\n\nexport type ExportXlsxOptions = {\n /** File name without extension. Defaults to \"workbook\". */\n filename?: string;\n /** Reads a picture's bytes (a `matrx-file:` reference or a URL). Pictures it cannot read are reported. */\n resolveImage?: ExportImagePort;\n};\n\nexport type ExportImagePort = (\n source: string,\n) => Promise<{ bytes: Uint8Array; extension: \"png\" | \"jpeg\" | \"gif\" } | null>;\n\n/** What an export could not carry, in words for the person. Empty when nothing was lost. */\nexport type XlsxExportReport = { dropped: string[] };\n\ntype Snapshot = Partial<IWorkbookData>;\ntype Style = Record<string, unknown>;\ntype Json = Record<string, any>; // eslint-disable-line @typescript-eslint/no-explicit-any -- Univer resource payloads are untyped JSON\n\n// ─── the thin WorkbookJson path (values + merges), kept for other callers ───\n\n/** A Univer snapshot as the `xlsx-workbook` format's value (sheets of typed cells + merges). */\nexport function univerSnapshotToWorkbookJson(snapshot: Snapshot): WorkbookJson {\n const sheetOrder = snapshot.sheetOrder ?? Object.keys(snapshot.sheets ?? {});\n const sheets: WorkbookJson[\"sheets\"] = [];\n for (const sheetId of sheetOrder) {\n const sheet = snapshot.sheets?.[sheetId];\n if (!sheet) continue;\n sheets.push(sheetToJson(sheet, (sheet.name ?? sheetId).slice(0, 31) || \"Sheet1\"));\n }\n return { sheets };\n}\n\n/** Full-fidelity bytes. Does NOT trigger a download. */\nexport async function univerSnapshotToXlsxBytes(\n snapshot: Snapshot,\n options: Pick<ExportXlsxOptions, \"resolveImage\"> = {},\n): Promise<Uint8Array> {\n return (await buildXlsxFromUniver(snapshot, options)).bytes;\n}\n\n/** Convert + trigger a browser download; returns what could not be carried. */\nexport async function downloadUniverAsXlsx(\n snapshot: Snapshot,\n options: ExportXlsxOptions = {},\n): Promise<XlsxExportReport> {\n if (typeof document === \"undefined\") return { dropped: [] };\n const filename = `${(options.filename ?? \"workbook\").replace(/\\.xlsx$/i, \"\")}.xlsx`;\n const { bytes, report } = await buildXlsxFromUniver(snapshot, options);\n const blob = new Blob([bytes as BlobPart], {\n type: \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\",\n });\n downloadFile(filename, blob, blob.type);\n return report;\n}\n\n// ─── the full-fidelity writer ──────────────────────────────────────────────\n\nexport async function buildXlsxFromUniver(\n snapshot: Snapshot,\n options: Pick<ExportXlsxOptions, \"resolveImage\"> = {},\n): Promise<{ bytes: Uint8Array; report: XlsxExportReport }> {\n const ExcelJS = await loadExcelJs();\n const wb = new ExcelJS.Workbook();\n const dropped = new Set<string>();\n const resources = (snapshot.resources ?? []) as UniverResource[];\n const styles = (snapshot.styles ?? {}) as Record<string, Style>;\n\n const validation = readResource<Json>(resources, RESOURCE.validation) ?? {};\n const conditional = readResource<Json>(resources, RESOURCE.conditional) ?? {};\n const filters = readResource<Json>(resources, RESOURCE.filter) ?? {};\n const notes = readResource<Json>(resources, RESOURCE.note) ?? {};\n const comments = readResource<Json>(resources, RESOURCE.comments) ?? {};\n const drawings = readResource<Json>(resources, RESOURCE.drawing) ?? {};\n const tables = readResource<Json>(resources, RESOURCE.table) ?? {};\n\n const order = snapshot.sheetOrder ?? Object.keys(snapshot.sheets ?? {});\n for (const sheetId of order) {\n const sheet = snapshot.sheets?.[sheetId] as Partial<IWorksheetData> | undefined;\n if (!sheet) continue;\n const ws = wb.addWorksheet(uniqueName(wb, (sheet.name ?? sheetId).slice(0, 31) || \"Sheet1\"));\n writeCells(ws, sheet, styles);\n writeLayout(ws, sheet);\n const tab = colorToArgb(typeof sheet.tabColor === \"string\" ? sheet.tabColor : undefined);\n if (tab) ws.properties.tabColor = { argb: tab };\n writeValidation(ws, validation[sheetId], dropped);\n writeConditional(ws, conditional[sheetId], dropped);\n writeFilter(ws, filters[sheetId], dropped);\n writeNotes(ws, notes[sheetId], comments[sheetId], dropped);\n await writeImages(wb, ws, drawings[sheetId], options.resolveImage, dropped);\n if (tables[sheetId] && Object.keys(tables[sheetId]).length) {\n dropped.add(\"Tables are exported as plain ranges (their data and styling are kept)\");\n }\n }\n\n const buffer = await wb.xlsx.writeBuffer();\n return { bytes: new Uint8Array(buffer as ArrayBuffer), report: { dropped: [...dropped] } };\n}\n\nfunction uniqueName(wb: ExcelJSTypes.Workbook, name: string): string {\n let candidate = name;\n let n = 2;\n while (wb.getWorksheet(candidate)) candidate = `${name.slice(0, 28)} ${n++}`;\n return candidate;\n}\n\nfunction styleOf(cell: ICellData, styles: Record<string, Style>): Style | undefined {\n const s = cell.s;\n if (!s) return undefined;\n return typeof s === \"string\" ? styles[s] : (s as Style);\n}\n\nfunction applyStyle(target: ExcelJSTypes.Cell, st: Style | undefined): void {\n if (!st) return;\n const font: Partial<ExcelJSTypes.Font> = {};\n if (st.ff) font.name = String(st.ff);\n if (typeof st.fs === \"number\") font.size = st.fs;\n if (st.bl === 1) font.bold = true;\n if (st.it === 1) font.italic = true;\n if ((st.ul as Json | undefined)?.s === 1) font.underline = true;\n if ((st.st as Json | undefined)?.s === 1) font.strike = true;\n const fg = colorToArgb((st.cl as Json | undefined)?.rgb);\n if (fg) font.color = { argb: fg };\n if (Object.keys(font).length) target.font = font;\n const bg = colorToArgb((st.bg as Json | undefined)?.rgb);\n if (bg) target.fill = { type: \"pattern\", pattern: \"solid\", fgColor: { argb: bg } };\n const alignment: Partial<ExcelJSTypes.Alignment> = {};\n if (typeof st.ht === \"number\" && H_ALIGN_OUT[st.ht]) alignment.horizontal = H_ALIGN_OUT[st.ht] as ExcelJSTypes.Alignment[\"horizontal\"];\n if (typeof st.vt === \"number\" && V_ALIGN_OUT[st.vt]) alignment.vertical = V_ALIGN_OUT[st.vt] as ExcelJSTypes.Alignment[\"vertical\"];\n if (st.tb === 3) alignment.wrapText = true;\n if (Object.keys(alignment).length) target.alignment = alignment;\n const bd = st.bd as Json | undefined;\n if (bd) {\n const border: Partial<ExcelJSTypes.Borders> = {};\n for (const [key, side] of [[\"t\", \"top\"], [\"b\", \"bottom\"], [\"l\", \"left\"], [\"r\", \"right\"]] as const) {\n const b = bd[key] as Json | undefined;\n const style = borderToExcel(b?.s);\n if (style) {\n (border as Json)[side] = { style, color: { argb: colorToArgb(b?.cl?.rgb) ?? \"FF000000\" } };\n }\n }\n if (Object.keys(border).length) target.border = border;\n }\n const pattern = (st.n as Json | undefined)?.pattern;\n if (typeof pattern === \"string\" && pattern && pattern !== \"General\") target.numFmt = pattern;\n}\n\nfunction plainText(p: Json | undefined): string {\n return String(p?.body?.dataStream ?? \"\").replace(/\\r\\n$/, \"\").replace(/\\r\\n/g, \"\\n\");\n}\n\nfunction linkOf(p: Json | undefined): string | undefined {\n const ranges = p?.body?.customRanges as Json[] | undefined;\n return ranges?.find((r) => r.rangeType === 0 && r.properties?.url)?.properties?.url;\n}\n\nfunction writeCells(ws: ExcelJSTypes.Worksheet, sheet: Partial<IWorksheetData>, styles: Record<string, Style>): void {\n const cellData = sheet.cellData ?? {};\n for (const rKey of Object.keys(cellData)) {\n const r = Number(rKey);\n const row = cellData[r];\n if (!row || !Number.isFinite(r)) continue;\n for (const cKey of Object.keys(row)) {\n const c = Number(cKey);\n const cell = row[c] as ICellData | undefined;\n if (!cell || !Number.isFinite(c)) continue;\n const target = ws.getCell(r + 1, c + 1);\n const formula = typeof cell.f === \"string\" ? cell.f.replace(/^=/, \"\") : undefined;\n const rich = cell.p as Json | undefined;\n let value: ExcelJSTypes.CellValue = null;\n if (cell.v !== undefined && cell.v !== null && cell.v !== \"\") {\n if (cell.t === 3) value = Boolean(cell.v);\n else if (cell.t === 2 || typeof cell.v === \"number\") value = Number(cell.v);\n else value = String(cell.v);\n } else if (rich) {\n value = plainText(rich);\n }\n const url = linkOf(rich);\n if (url) value = { text: String(value ?? url), hyperlink: url };\n if (formula) value = { formula, result: (value as number | string | boolean | undefined) ?? undefined } as ExcelJSTypes.CellFormulaValue;\n if (value !== null && value !== \"\") target.value = value;\n applyStyle(target, styleOf(cell, styles));\n }\n }\n}\n\nfunction writeLayout(ws: ExcelJSTypes.Worksheet, sheet: Partial<IWorksheetData>): void {\n const defaultCol = sheet.defaultColumnWidth;\n const columns = sheet.columnData ?? {};\n for (const key of Object.keys(columns)) {\n const c = Number(key);\n const col = columns[c];\n if (!col) continue;\n const target = ws.getColumn(c + 1);\n if (typeof col.w === \"number\") target.width = colPxToChars(col.w);\n else if (defaultCol) target.width = colPxToChars(defaultCol);\n if (col.hd === 1) target.hidden = true;\n }\n const rows = sheet.rowData ?? {};\n for (const key of Object.keys(rows)) {\n const r = Number(key);\n const row = rows[r];\n if (!row) continue;\n const target = ws.getRow(r + 1);\n if (typeof row.h === \"number\") target.height = rowPxToPt(row.h);\n if (row.hd === 1) target.hidden = true;\n }\n for (const m of sheet.mergeData ?? []) {\n try {\n ws.mergeCells(m.startRow + 1, m.startColumn + 1, m.endRow + 1, m.endColumn + 1);\n } catch {\n /* an overlapping merge in a damaged snapshot: keep the first */\n }\n }\n const freeze = sheet.freeze;\n if (freeze && (freeze.xSplit > 0 || freeze.ySplit > 0)) {\n ws.views = [{ state: \"frozen\", xSplit: freeze.xSplit, ySplit: freeze.ySplit }];\n }\n}\n\nconst eachCell = (ranges: RangeLike[], fn: (row: number, col: number) => void, cap = 100_000): boolean => {\n let n = 0;\n for (const r of ranges) {\n for (let row = r.startRow; row <= r.endRow; row++) {\n for (let col = r.startColumn; col <= r.endColumn; col++) {\n if (++n > cap) return false;\n fn(row, col);\n }\n }\n }\n return true;\n};\n\nfunction writeValidation(ws: ExcelJSTypes.Worksheet, rules: Json[] | undefined, dropped: Set<string>): void {\n for (const rule of rules ?? []) {\n const type = String(rule.type);\n const base: Json = {\n allowBlank: rule.allowBlank !== false,\n showErrorMessage: rule.showErrorMessage !== false,\n errorTitle: rule.errorTitle,\n error: rule.error,\n showInputMessage: Boolean(rule.showInputMessage),\n promptTitle: rule.promptTitle,\n prompt: rule.prompt,\n };\n let dv: Json | null = null;\n if (type === \"list\" || type === \"listMultiple\") {\n const f1 = String(rule.formula1 ?? \"\");\n const isRange = /^=?'?[^,\"]*!?\\$?[A-Z]+\\$?\\d+(:\\$?[A-Z]+\\$?\\d+)?$/i.test(f1) && !f1.includes(\",\");\n dv = { ...base, type: \"list\", formulae: [isRange ? f1.replace(/^=/, \"\") : `\"${f1.replace(/\"/g, \"\")}\"`] };\n if (type === \"listMultiple\") dropped.add(\"Multi-select dropdowns become single-select\");\n } else if (type === \"checkbox\") {\n dv = { ...base, type: \"list\", formulae: ['\"TRUE,FALSE\"'] };\n dropped.add(\"Checkboxes become TRUE/FALSE dropdowns\");\n } else if ([\"whole\", \"decimal\", \"date\", \"time\", \"textLength\"].includes(type)) {\n dv = {\n ...base,\n type,\n operator: rule.operator ?? \"between\",\n formulae: [rule.formula1, rule.formula2].filter((f) => f !== undefined && f !== \"\"),\n };\n } else if (type === \"custom\") {\n dv = { ...base, type: \"custom\", formulae: [String(rule.formula1 ?? \"\").replace(/^=/, \"\")] };\n }\n if (!dv) continue;\n if (!dv.errorTitle) delete dv.errorTitle;\n const complete = eachCell((rule.ranges ?? []) as RangeLike[], (r, c) => {\n ws.getCell(r + 1, c + 1).dataValidation = dv as ExcelJSTypes.DataValidation;\n });\n if (!complete) dropped.add(\"Data validation on very large ranges was cut off\");\n }\n}\n\nconst NUMBER_OPS = new Set([\"greaterThan\", \"greaterThanOrEqual\", \"lessThan\", \"lessThanOrEqual\", \"equal\", \"notEqual\", \"between\", \"notBetween\"]);\n\nfunction cfStyle(style: Json | undefined): Json {\n const out: Json = {};\n const font: Json = {};\n const fg = colorToArgb(style?.cl?.rgb);\n if (fg) font.color = { argb: fg };\n if (style?.bl === 1) font.bold = true;\n if (style?.it === 1) font.italic = true;\n if (Object.keys(font).length) out.font = font;\n const bg = colorToArgb(style?.bg?.rgb);\n if (bg) out.fill = { type: \"pattern\", pattern: \"solid\", bgColor: { argb: bg } };\n return out;\n}\n\nfunction writeConditional(ws: ExcelJSTypes.Worksheet, rules: Json[] | undefined, dropped: Set<string>): void {\n for (const entry of rules ?? []) {\n const ranges = (entry.ranges ?? []) as RangeLike[];\n if (!ranges.length) continue;\n const ref = ranges.map(rangeToA1).join(\" \");\n const first = ranges[0]!;\n const topLeft = rangeToA1({ ...first, endRow: first.startRow, endColumn: first.startColumn });\n const rule = entry.rule as Json;\n let out: Json | null = null;\n if (rule?.type === \"highlightCell\") {\n const style = cfStyle(rule.style);\n switch (rule.subType) {\n case \"number\":\n if (NUMBER_OPS.has(rule.operator)) {\n out = { type: \"cellIs\", operator: rule.operator, formulae: Array.isArray(rule.value) ? rule.value : [rule.value], style };\n }\n break;\n case \"text\":\n if (rule.operator === \"containsText\") out = { type: \"containsText\", operator: \"containsText\", text: String(rule.value ?? \"\"), style };\n break;\n case \"duplicateValues\":\n out = { type: \"expression\", formulae: [`COUNTIF(${ref.split(\" \")[0]},${topLeft})>1`], style };\n break;\n case \"uniqueValues\":\n out = { type: \"expression\", formulae: [`COUNTIF(${ref.split(\" \")[0]},${topLeft})=1`], style };\n break;\n case \"formula\":\n out = { type: \"expression\", formulae: [String(rule.value ?? \"\").replace(/^=/, \"\")], style };\n break;\n }\n } else if (rule?.type === \"colorScale\" && Array.isArray(rule.config)) {\n const cfg = [...rule.config].sort((a: Json, b: Json) => a.index - b.index);\n out = {\n type: \"colorScale\",\n cfvo: cfg.map((c: Json) => ({ type: c.value?.type ?? \"min\", ...(c.value?.value !== undefined ? { value: c.value.value } : {}) })),\n color: cfg.map((c: Json) => ({ argb: colorToArgb(c.color) ?? \"FFFFFFFF\" })),\n };\n } else if (rule?.type === \"dataBar\") {\n out = {\n type: \"dataBar\",\n gradient: rule.config?.isGradient !== false,\n cfvo: [{ type: rule.config?.min?.type ?? \"min\" }, { type: rule.config?.max?.type ?? \"max\" }],\n color: { argb: colorToArgb(rule.config?.positiveColor) ?? \"FF638EC6\" },\n };\n }\n if (!out) {\n dropped.add(\"Some conditional formats (icon sets, top/bottom, average, date rules) are not written\");\n continue;\n }\n ws.addConditionalFormatting({ ref, rules: [{ ...out, priority: 1 }] } as ExcelJSTypes.ConditionalFormattingOptions);\n }\n}\n\nfunction writeFilter(ws: ExcelJSTypes.Worksheet, filter: Json | undefined, dropped: Set<string>): void {\n const ref = filter?.ref as RangeLike | undefined;\n if (!ref) return;\n ws.autoFilter = {\n from: { row: ref.startRow + 1, column: ref.startColumn + 1 },\n to: { row: ref.endRow + 1, column: ref.endColumn + 1 },\n };\n if ((filter?.filterColumns as unknown[] | undefined)?.length) {\n dropped.add(\"Which filter choices were applied is not saved (the filter arrows are)\");\n }\n}\n\nfunction threadText(c: Json): string {\n return String(c?.text?.dataStream ?? \"\").replace(/\\r\\n?$/, \"\").replace(/\\r\\n?/g, \"\\n\");\n}\n\nfunction writeNotes(ws: ExcelJSTypes.Worksheet, sheetNotes: Json | undefined, sheetComments: Json | Json[] | undefined, dropped: Set<string>): void {\n for (const [row, cols] of Object.entries(sheetNotes ?? {})) {\n for (const [col, note] of Object.entries(cols as Json)) {\n const text = String((note as Json).note ?? \"\");\n if (text) ws.getCell(Number(row) + 1, Number(col) + 1).note = text;\n }\n }\n const list: Json[] = Array.isArray(sheetComments) ? sheetComments : sheetComments ? Object.values(sheetComments).flat() : [];\n const threads = new Map<string, string[]>();\n for (const c of list) {\n if (!c?.ref) continue;\n const lines = threads.get(c.ref) ?? [];\n const who = c.authorName ?? c.personId ?? \"\";\n lines.push(`${who ? who + \": \" : \"\"}${threadText(c)}`);\n for (const child of (c.children ?? []) as Json[]) {\n lines.push(`${child.authorName ?? child.personId ?? \"\"}: ${threadText(child)}`);\n }\n threads.set(c.ref, lines);\n }\n for (const [ref, lines] of threads) {\n const cell = ws.getCell(ref);\n const existing = typeof cell.note === \"string\" ? cell.note : \"\";\n cell.note = [existing, ...lines].filter(Boolean).join(\"\\n\");\n }\n if (threads.size) dropped.add(\"Comment threads are written as cell notes (replies and resolved state are flattened)\");\n}\n\nasync function writeImages(\n wb: ExcelJSTypes.Workbook,\n ws: ExcelJSTypes.Worksheet,\n sheetDrawings: Json | undefined,\n resolve: ExportImagePort | undefined,\n dropped: Set<string>,\n): Promise<void> {\n const data = (sheetDrawings?.data ?? {}) as Record<string, Json>;\n for (const d of Object.values(data)) {\n if (d.drawingType !== 0 || !d.source) continue;\n const from = d.sheetTransform?.from;\n if (!from) continue;\n let bytes: Uint8Array | null = null;\n let extension: \"png\" | \"jpeg\" | \"gif\" = \"png\";\n const dataUrl = /^data:image\\/(png|jpeg|jpg|gif);base64,(.+)$/i.exec(String(d.source));\n if (dataUrl) {\n extension = dataUrl[1]!.toLowerCase() === \"gif\" ? \"gif\" : dataUrl[1]!.toLowerCase() === \"png\" ? \"png\" : \"jpeg\";\n bytes = Uint8Array.from(atob(dataUrl[2]!), (ch) => ch.charCodeAt(0));\n } else if (resolve) {\n try {\n const got = await resolve(String(d.source));\n if (got) ({ bytes, extension } = got);\n } catch {\n bytes = null;\n }\n }\n if (!bytes) {\n dropped.add(\"Some pictures could not be read and were left out\");\n continue;\n }\n const id = wb.addImage({ buffer: bytes as unknown as NonNullable<Parameters<typeof wb.addImage>[0][\"buffer\"]>, extension });\n ws.addImage(id, {\n tl: { col: from.column + (from.columnOffset ?? 0) / 64, row: from.row + (from.rowOffset ?? 0) / 20 },\n ext: { width: d.transform?.width ?? 200, height: d.transform?.height ?? 150 },\n });\n }\n}\n\n// ─── internals of the thin path ────────────────────────────────────────────\n\nfunction sheetToJson(sheet: Partial<IWorksheetData>, name: string): WorkbookJson[\"sheets\"][number] {\n const cellData = sheet.cellData ?? {};\n const rows: (WorkbookCellJson | null)[][] = [];\n for (const rKey of Object.keys(cellData)) {\n const r = Number(rKey);\n if (!Number.isFinite(r)) continue;\n const row = cellData[r];\n if (!row) continue;\n for (const cKey of Object.keys(row)) {\n const c = Number(cKey);\n if (!Number.isFinite(c)) continue;\n const cell = row[c];\n if (!cell) continue;\n const out = toWorkbookCell(cell);\n if (!out) continue;\n while (rows.length <= r) rows.push([]);\n const line = rows[r]!;\n while (line.length < c) line.push(null);\n line[c] = out;\n }\n }\n const merges = (sheet.mergeData ?? []).map((m) => ({\n s: { r: m.startRow, c: m.startColumn },\n e: { r: m.endRow, c: m.endColumn },\n }));\n return { name, rows, ...(merges.length ? { merges } : {}) };\n}\n\nfunction toWorkbookCell(cell: ICellData): WorkbookCellJson | null {\n const formula = typeof cell.f === \"string\" ? cell.f.replace(/^=/, \"\") : undefined;\n let out: WorkbookCellJson;\n switch (cell.t) {\n case 2:\n out = { t: \"n\", v: typeof cell.v === \"number\" ? cell.v : Number(cell.v ?? 0) };\n break;\n case 3:\n out = { t: \"b\", v: Boolean(cell.v) };\n break;\n default:\n out = {\n t: \"s\",\n v:\n cell.v === null || cell.v === undefined\n ? \"\"\n : typeof cell.v === \"object\"\n ? JSON.stringify(cell.v)\n : String(cell.v),\n };\n }\n if ((out.v === \"\" || out.v === null || out.v === undefined) && !formula) return null;\n return formula ? { ...out, f: formula } : out;\n}\n\n// Kept so existing callers of the registered-format path keep compiling.\nexport async function univerSnapshotToRegisteredXlsxBytes(snapshot: Snapshot): Promise<Uint8Array> {\n const built = await buildFile(\n { kind: \"registered\", format: \"workbook\", value: univerSnapshotToWorkbookJson(snapshot) },\n \"xlsx-workbook\",\n );\n return built.bytes;\n}\n","/**\n * Spreadsheet file → a NEW workbook, the ONE import path: the Workbooks home and the editor's\n * File → Import both run it. The file is parsed before anything is created (a malformed file leaves\n * no empty workbook behind), the lossless original is stashed (non-fatal), and a failed save rolls\n * the new row back.\n */\n\nimport { isServiceFailure } from \"@ai-matrx/records/core\";\n\nimport { getSheetsHost } from \"./ports\";\nimport {\n createWorkbook,\n discardFailedWorkbook,\n saveSnapshot,\n} from \"./workbook-service\";\n\n/**\n * Pre-flight import file check. We deliberately do NOT use the `accept`\n * attribute on the picker (it greys out everything in Drive / Google\n * Sheets pickers on iOS and many Android pickers), so we validate after\n * pick. Returns null when the file is accepted, or a short user-facing\n * reason string when it isn't.\n */\nexport function unsupportedFileReason(file: File): string | null {\n const name = file.name.toLowerCase();\n // Native, parseable formats.\n if (\n name.endsWith(\".xlsx\") ||\n name.endsWith(\".xls\") ||\n name.endsWith(\".csv\")\n ) {\n return null;\n }\n if (name.endsWith(\".tsv\") || name.endsWith(\".txt\")) return null; // SheetJS parses these too\n\n // Drive's \"Google Sheets\" shortcut is a tiny JSON pointer file that browsers cannot resolve into\n // the sheet; the Google Sheets import reads the real file through Google's own picker.\n if (name.endsWith(\".gsheet\")) {\n return \"A Google Sheets shortcut can't be uploaded. Use Import from Google Sheets.\";\n }\n // Anything else.\n return `\"${file.name}\" isn't a spreadsheet file. Supported: .xlsx, .xls, .csv. For a Google Sheet, use Import from Google Sheets.`;\n}\n\nexport async function importWorkbookFile(\n file: File,\n organizationId: string | null,\n): Promise<{ id: string; name: string; notCarried: string[] }> {\n const capturedOrganizationId = await getSheetsHost().ensureOrgId(organizationId);\n // Parse first — if the file is malformed, we surface the error\n // BEFORE creating an empty workbook the user would have to delete.\n const { xlsxToUniverWorkbook } =\n await import(\"./xlsx-to-univer\");\n const droppedOnImport: string[] = [];\n const { uploadImportedImage } = await import(\"../univer/matrxImagePorts\");\n const snapshot = await xlsxToUniverWorkbook(file, {\n uploadImage: uploadImportedImage,\n onDropped: (what) => droppedOnImport.push(what),\n });\n\n // Stash the lossless original in cld_files so users can download or\n // re-import the source later. Failure here is non-fatal — the workbook\n // import path is the primary deliverable, the original-file link is\n // a recoverability nicety (FK is ON DELETE SET NULL, so we'd nil out\n // the link if the file went away anyway). Log + continue on failure.\n let originalFileId: string | undefined;\n try {\n const uploaded = await getSheetsHost().uploadOriginalFile(file, { folderPath: \"Workbooks/Imports\" });\n originalFileId = uploaded.fileId;\n } catch (uploadErr) {\n console.warn(\n \"Workbook import: stashing original failed; continuing without link.\",\n uploadErr,\n );\n }\n\n const cleanName = file.name.replace(/\\.[^.]+$/, \"\") || \"Imported workbook\";\n const created = await createWorkbook({\n name: cleanName,\n description: `Imported from ${file.name}`,\n source: file.name.toLowerCase().endsWith(\".csv\")\n ? \"imported_csv\"\n : \"imported_xlsx\",\n organizationId: capturedOrganizationId,\n ...(originalFileId ? { originalFileId } : {}),\n });\n if (isServiceFailure(created)) throw new Error(created.error);\n\n const saved = await saveSnapshot({\n workbookId: created.data.id,\n snapshot,\n origin: \"imported\",\n label: file.name,\n });\n if (isServiceFailure(saved)) {\n // Roll back the workbook so we don't leave an empty husk on import\n // failure. Best-effort, and a HARD delete on purpose: this row was\n // created seconds ago by this same flow and never reached the user, so\n // tombstoning it would leave invisible litter instead of cleaning up.\n await discardFailedWorkbook(created.data.id);\n throw new Error(saved.error);\n }\n\n return { id: created.data.id, name: cleanName, notCarried: droppedOnImport };\n}\n"]}
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import { WorkbookJson } from '@ai-matrx/alchemy/operate/read';
|
|
2
|
+
import { IWorkbookData } from '@univerjs/core';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Shared vocabulary between the xlsx importer and exporter: how Univer's
|
|
6
|
+
* style numbers, colours and units map to the xlsx file's.
|
|
7
|
+
*
|
|
8
|
+
* Univer enums are written as numbers here so these helpers stay free of any
|
|
9
|
+
* Univer import (they run in tests and in both directions).
|
|
10
|
+
*/
|
|
11
|
+
declare const RESOURCE: {
|
|
12
|
+
readonly validation: "SHEET_DATA_VALIDATION_PLUGIN";
|
|
13
|
+
readonly conditional: "SHEET_CONDITIONAL_FORMATTING_PLUGIN";
|
|
14
|
+
readonly filter: "SHEET_FILTER_PLUGIN";
|
|
15
|
+
readonly note: "SHEET_NOTE_PLUGIN";
|
|
16
|
+
readonly comments: "SHEET_UNIVER_THREAD_COMMENT_PLUGIN";
|
|
17
|
+
readonly drawing: "SHEET_DRAWING_PLUGIN";
|
|
18
|
+
readonly table: "SHEET_TABLE_PLUGIN";
|
|
19
|
+
};
|
|
20
|
+
type UniverResource = {
|
|
21
|
+
name: string;
|
|
22
|
+
data: string;
|
|
23
|
+
};
|
|
24
|
+
declare function readResource<T = unknown>(resources: readonly UniverResource[] | undefined, name: string): T | undefined;
|
|
25
|
+
declare function writeResource(resources: UniverResource[], name: string, value: unknown): void;
|
|
26
|
+
/** Excel column width (characters) <-> Univer pixels. */
|
|
27
|
+
declare const colPxToChars: (px: number) => number;
|
|
28
|
+
declare const colCharsToPx: (chars: number) => number;
|
|
29
|
+
/** Excel row height (points) <-> Univer pixels. */
|
|
30
|
+
declare const rowPxToPt: (px: number) => number;
|
|
31
|
+
declare const rowPtToPx: (pt: number) => number;
|
|
32
|
+
/** Univer colour ("#rrggbb", "rgb(r,g,b)", "rgba(...)") -> ARGB hex, or undefined. */
|
|
33
|
+
declare function colorToArgb(input: string | undefined | null): string | undefined;
|
|
34
|
+
/** ARGB (or RGB) hex from a file -> Univer "#rrggbb". */
|
|
35
|
+
declare function argbToColor(argb: string | undefined | null): string | undefined;
|
|
36
|
+
declare const borderToExcel: (n: number | undefined) => string | undefined;
|
|
37
|
+
declare const borderFromExcel: (name: string | undefined) => number | undefined;
|
|
38
|
+
declare const H_ALIGN_OUT: Record<number, string>;
|
|
39
|
+
declare const V_ALIGN_OUT: Record<number, string>;
|
|
40
|
+
declare const H_ALIGN_IN: Record<string, number>;
|
|
41
|
+
declare const V_ALIGN_IN: Record<string, number>;
|
|
42
|
+
/** 0-based (row, col) -> "A1" (no $). */
|
|
43
|
+
declare function a1(row: number, col: number): string;
|
|
44
|
+
type RangeLike = {
|
|
45
|
+
startRow: number;
|
|
46
|
+
endRow: number;
|
|
47
|
+
startColumn: number;
|
|
48
|
+
endColumn: number;
|
|
49
|
+
};
|
|
50
|
+
declare const rangeToA1: (r: RangeLike) => string;
|
|
51
|
+
/** "A1" or "A1:C5" -> range (0-based), or null. */
|
|
52
|
+
declare function parseA1Range(ref: string): RangeLike | null;
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* univerToXlsx — convert a Univer IWorkbookData snapshot to an .xlsx file.
|
|
56
|
+
*
|
|
57
|
+
* Symmetric counterpart to `xlsx-to-univer.ts`. Carries everything the xlsx
|
|
58
|
+
* format can hold from what Univer holds: values, formulas, merged ranges,
|
|
59
|
+
* cell styles and number formats, column widths, row heights, frozen panes,
|
|
60
|
+
* data validation, conditional formatting, the header-row filter range,
|
|
61
|
+
* notes, comment threads (as notes), cell links, and pictures.
|
|
62
|
+
*
|
|
63
|
+
* What it cannot carry is NAMED in the returned report and shown to the person
|
|
64
|
+
* at export time — never dropped silently.
|
|
65
|
+
*
|
|
66
|
+
* Engine: ExcelJS (the xlsx reader/writer that holds styles, validation,
|
|
67
|
+
* conditional formatting, notes, links and images; the registered
|
|
68
|
+
* `xlsx-workbook` format writes values only). It is loaded on demand, so
|
|
69
|
+
* the editor bundle does not pay for it until someone exports or imports.
|
|
70
|
+
*/
|
|
71
|
+
|
|
72
|
+
type ExportXlsxOptions = {
|
|
73
|
+
/** File name without extension. Defaults to "workbook". */
|
|
74
|
+
filename?: string;
|
|
75
|
+
/** Reads a picture's bytes (a `matrx-file:` reference or a URL). Pictures it cannot read are reported. */
|
|
76
|
+
resolveImage?: ExportImagePort;
|
|
77
|
+
};
|
|
78
|
+
type ExportImagePort = (source: string) => Promise<{
|
|
79
|
+
bytes: Uint8Array;
|
|
80
|
+
extension: "png" | "jpeg" | "gif";
|
|
81
|
+
} | null>;
|
|
82
|
+
/** What an export could not carry, in words for the person. Empty when nothing was lost. */
|
|
83
|
+
type XlsxExportReport = {
|
|
84
|
+
dropped: string[];
|
|
85
|
+
};
|
|
86
|
+
type Snapshot = Partial<IWorkbookData>;
|
|
87
|
+
/** A Univer snapshot as the `xlsx-workbook` format's value (sheets of typed cells + merges). */
|
|
88
|
+
declare function univerSnapshotToWorkbookJson(snapshot: Snapshot): WorkbookJson;
|
|
89
|
+
/** Full-fidelity bytes. Does NOT trigger a download. */
|
|
90
|
+
declare function univerSnapshotToXlsxBytes(snapshot: Snapshot, options?: Pick<ExportXlsxOptions, "resolveImage">): Promise<Uint8Array>;
|
|
91
|
+
/** Convert + trigger a browser download; returns what could not be carried. */
|
|
92
|
+
declare function downloadUniverAsXlsx(snapshot: Snapshot, options?: ExportXlsxOptions): Promise<XlsxExportReport>;
|
|
93
|
+
declare function buildXlsxFromUniver(snapshot: Snapshot, options?: Pick<ExportXlsxOptions, "resolveImage">): Promise<{
|
|
94
|
+
bytes: Uint8Array;
|
|
95
|
+
report: XlsxExportReport;
|
|
96
|
+
}>;
|
|
97
|
+
declare function univerSnapshotToRegisteredXlsxBytes(snapshot: Snapshot): Promise<Uint8Array>;
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Full-fidelity .xlsx -> Univer reader (ExcelJS). The inverse of
|
|
101
|
+
* `univer-to-xlsx.ts`: styles, number formats, column widths, row heights,
|
|
102
|
+
* frozen panes, merges, data validation, conditional formatting, the filter
|
|
103
|
+
* range, notes, cell links and pictures. Free of Univer runtime imports (enums
|
|
104
|
+
* are numbers) so it runs under tests as well as in the browser.
|
|
105
|
+
*/
|
|
106
|
+
|
|
107
|
+
type XlsxImportOptions = {
|
|
108
|
+
/** Stores a picture and returns its file id; without it pictures are reported, not imported. */
|
|
109
|
+
uploadImage?: (bytes: Uint8Array, extension: string) => Promise<string>;
|
|
110
|
+
/** Called once per thing the file held that could not be carried. */
|
|
111
|
+
onDropped?: (what: string) => void;
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* xlsxToUniverWorkbook — parse a spreadsheet file into a Univer IWorkbookData
|
|
116
|
+
* suitable for `apiRef.createWorkbook(...)` and for persistence as the initial
|
|
117
|
+
* snapshot of a new workbook.
|
|
118
|
+
*
|
|
119
|
+
* ONE reader: ExcelJS (`xlsx-to-univer-excel`) holds styles, number formats,
|
|
120
|
+
* widths, heights, frozen panes, merges, validation, conditional formatting,
|
|
121
|
+
* filter range, notes, links and pictures. A file that is not already an
|
|
122
|
+
* .xlsx (.xls, .ods, .csv, .tsv) is first re-written as an .xlsx by the
|
|
123
|
+
* Alchemy workbook door — values, formulas and merges — and read by that same
|
|
124
|
+
* reader, so there is no second import path to drift.
|
|
125
|
+
*/
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Parse a spreadsheet file into a Univer workbook. Whatever could not be
|
|
129
|
+
* carried is reported through `options.onDropped` (the caller tells the person).
|
|
130
|
+
*/
|
|
131
|
+
declare function xlsxToUniverWorkbook(file: File, options?: XlsxImportOptions): Promise<Partial<IWorkbookData>>;
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Spreadsheet file → a NEW workbook, the ONE import path: the Workbooks home and the editor's
|
|
135
|
+
* File → Import both run it. The file is parsed before anything is created (a malformed file leaves
|
|
136
|
+
* no empty workbook behind), the lossless original is stashed (non-fatal), and a failed save rolls
|
|
137
|
+
* the new row back.
|
|
138
|
+
*/
|
|
139
|
+
/**
|
|
140
|
+
* Pre-flight import file check. We deliberately do NOT use the `accept`
|
|
141
|
+
* attribute on the picker (it greys out everything in Drive / Google
|
|
142
|
+
* Sheets pickers on iOS and many Android pickers), so we validate after
|
|
143
|
+
* pick. Returns null when the file is accepted, or a short user-facing
|
|
144
|
+
* reason string when it isn't.
|
|
145
|
+
*/
|
|
146
|
+
declare function unsupportedFileReason(file: File): string | null;
|
|
147
|
+
declare function importWorkbookFile(file: File, organizationId: string | null): Promise<{
|
|
148
|
+
id: string;
|
|
149
|
+
name: string;
|
|
150
|
+
notCarried: string[];
|
|
151
|
+
}>;
|
|
152
|
+
|
|
153
|
+
export { type ExportImagePort, type ExportXlsxOptions, H_ALIGN_IN, H_ALIGN_OUT, RESOURCE, type RangeLike, type UniverResource, V_ALIGN_IN, V_ALIGN_OUT, type XlsxExportReport, a1, argbToColor, borderFromExcel, borderToExcel, buildXlsxFromUniver, colCharsToPx, colPxToChars, colorToArgb, downloadUniverAsXlsx, importWorkbookFile, parseA1Range, rangeToA1, readResource, rowPtToPx, rowPxToPt, univerSnapshotToRegisteredXlsxBytes, univerSnapshotToWorkbookJson, univerSnapshotToXlsxBytes, unsupportedFileReason, writeResource, xlsxToUniverWorkbook };
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import { WorkbookJson } from '@ai-matrx/alchemy/operate/read';
|
|
2
|
+
import { IWorkbookData } from '@univerjs/core';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Shared vocabulary between the xlsx importer and exporter: how Univer's
|
|
6
|
+
* style numbers, colours and units map to the xlsx file's.
|
|
7
|
+
*
|
|
8
|
+
* Univer enums are written as numbers here so these helpers stay free of any
|
|
9
|
+
* Univer import (they run in tests and in both directions).
|
|
10
|
+
*/
|
|
11
|
+
declare const RESOURCE: {
|
|
12
|
+
readonly validation: "SHEET_DATA_VALIDATION_PLUGIN";
|
|
13
|
+
readonly conditional: "SHEET_CONDITIONAL_FORMATTING_PLUGIN";
|
|
14
|
+
readonly filter: "SHEET_FILTER_PLUGIN";
|
|
15
|
+
readonly note: "SHEET_NOTE_PLUGIN";
|
|
16
|
+
readonly comments: "SHEET_UNIVER_THREAD_COMMENT_PLUGIN";
|
|
17
|
+
readonly drawing: "SHEET_DRAWING_PLUGIN";
|
|
18
|
+
readonly table: "SHEET_TABLE_PLUGIN";
|
|
19
|
+
};
|
|
20
|
+
type UniverResource = {
|
|
21
|
+
name: string;
|
|
22
|
+
data: string;
|
|
23
|
+
};
|
|
24
|
+
declare function readResource<T = unknown>(resources: readonly UniverResource[] | undefined, name: string): T | undefined;
|
|
25
|
+
declare function writeResource(resources: UniverResource[], name: string, value: unknown): void;
|
|
26
|
+
/** Excel column width (characters) <-> Univer pixels. */
|
|
27
|
+
declare const colPxToChars: (px: number) => number;
|
|
28
|
+
declare const colCharsToPx: (chars: number) => number;
|
|
29
|
+
/** Excel row height (points) <-> Univer pixels. */
|
|
30
|
+
declare const rowPxToPt: (px: number) => number;
|
|
31
|
+
declare const rowPtToPx: (pt: number) => number;
|
|
32
|
+
/** Univer colour ("#rrggbb", "rgb(r,g,b)", "rgba(...)") -> ARGB hex, or undefined. */
|
|
33
|
+
declare function colorToArgb(input: string | undefined | null): string | undefined;
|
|
34
|
+
/** ARGB (or RGB) hex from a file -> Univer "#rrggbb". */
|
|
35
|
+
declare function argbToColor(argb: string | undefined | null): string | undefined;
|
|
36
|
+
declare const borderToExcel: (n: number | undefined) => string | undefined;
|
|
37
|
+
declare const borderFromExcel: (name: string | undefined) => number | undefined;
|
|
38
|
+
declare const H_ALIGN_OUT: Record<number, string>;
|
|
39
|
+
declare const V_ALIGN_OUT: Record<number, string>;
|
|
40
|
+
declare const H_ALIGN_IN: Record<string, number>;
|
|
41
|
+
declare const V_ALIGN_IN: Record<string, number>;
|
|
42
|
+
/** 0-based (row, col) -> "A1" (no $). */
|
|
43
|
+
declare function a1(row: number, col: number): string;
|
|
44
|
+
type RangeLike = {
|
|
45
|
+
startRow: number;
|
|
46
|
+
endRow: number;
|
|
47
|
+
startColumn: number;
|
|
48
|
+
endColumn: number;
|
|
49
|
+
};
|
|
50
|
+
declare const rangeToA1: (r: RangeLike) => string;
|
|
51
|
+
/** "A1" or "A1:C5" -> range (0-based), or null. */
|
|
52
|
+
declare function parseA1Range(ref: string): RangeLike | null;
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* univerToXlsx — convert a Univer IWorkbookData snapshot to an .xlsx file.
|
|
56
|
+
*
|
|
57
|
+
* Symmetric counterpart to `xlsx-to-univer.ts`. Carries everything the xlsx
|
|
58
|
+
* format can hold from what Univer holds: values, formulas, merged ranges,
|
|
59
|
+
* cell styles and number formats, column widths, row heights, frozen panes,
|
|
60
|
+
* data validation, conditional formatting, the header-row filter range,
|
|
61
|
+
* notes, comment threads (as notes), cell links, and pictures.
|
|
62
|
+
*
|
|
63
|
+
* What it cannot carry is NAMED in the returned report and shown to the person
|
|
64
|
+
* at export time — never dropped silently.
|
|
65
|
+
*
|
|
66
|
+
* Engine: ExcelJS (the xlsx reader/writer that holds styles, validation,
|
|
67
|
+
* conditional formatting, notes, links and images; the registered
|
|
68
|
+
* `xlsx-workbook` format writes values only). It is loaded on demand, so
|
|
69
|
+
* the editor bundle does not pay for it until someone exports or imports.
|
|
70
|
+
*/
|
|
71
|
+
|
|
72
|
+
type ExportXlsxOptions = {
|
|
73
|
+
/** File name without extension. Defaults to "workbook". */
|
|
74
|
+
filename?: string;
|
|
75
|
+
/** Reads a picture's bytes (a `matrx-file:` reference or a URL). Pictures it cannot read are reported. */
|
|
76
|
+
resolveImage?: ExportImagePort;
|
|
77
|
+
};
|
|
78
|
+
type ExportImagePort = (source: string) => Promise<{
|
|
79
|
+
bytes: Uint8Array;
|
|
80
|
+
extension: "png" | "jpeg" | "gif";
|
|
81
|
+
} | null>;
|
|
82
|
+
/** What an export could not carry, in words for the person. Empty when nothing was lost. */
|
|
83
|
+
type XlsxExportReport = {
|
|
84
|
+
dropped: string[];
|
|
85
|
+
};
|
|
86
|
+
type Snapshot = Partial<IWorkbookData>;
|
|
87
|
+
/** A Univer snapshot as the `xlsx-workbook` format's value (sheets of typed cells + merges). */
|
|
88
|
+
declare function univerSnapshotToWorkbookJson(snapshot: Snapshot): WorkbookJson;
|
|
89
|
+
/** Full-fidelity bytes. Does NOT trigger a download. */
|
|
90
|
+
declare function univerSnapshotToXlsxBytes(snapshot: Snapshot, options?: Pick<ExportXlsxOptions, "resolveImage">): Promise<Uint8Array>;
|
|
91
|
+
/** Convert + trigger a browser download; returns what could not be carried. */
|
|
92
|
+
declare function downloadUniverAsXlsx(snapshot: Snapshot, options?: ExportXlsxOptions): Promise<XlsxExportReport>;
|
|
93
|
+
declare function buildXlsxFromUniver(snapshot: Snapshot, options?: Pick<ExportXlsxOptions, "resolveImage">): Promise<{
|
|
94
|
+
bytes: Uint8Array;
|
|
95
|
+
report: XlsxExportReport;
|
|
96
|
+
}>;
|
|
97
|
+
declare function univerSnapshotToRegisteredXlsxBytes(snapshot: Snapshot): Promise<Uint8Array>;
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Full-fidelity .xlsx -> Univer reader (ExcelJS). The inverse of
|
|
101
|
+
* `univer-to-xlsx.ts`: styles, number formats, column widths, row heights,
|
|
102
|
+
* frozen panes, merges, data validation, conditional formatting, the filter
|
|
103
|
+
* range, notes, cell links and pictures. Free of Univer runtime imports (enums
|
|
104
|
+
* are numbers) so it runs under tests as well as in the browser.
|
|
105
|
+
*/
|
|
106
|
+
|
|
107
|
+
type XlsxImportOptions = {
|
|
108
|
+
/** Stores a picture and returns its file id; without it pictures are reported, not imported. */
|
|
109
|
+
uploadImage?: (bytes: Uint8Array, extension: string) => Promise<string>;
|
|
110
|
+
/** Called once per thing the file held that could not be carried. */
|
|
111
|
+
onDropped?: (what: string) => void;
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* xlsxToUniverWorkbook — parse a spreadsheet file into a Univer IWorkbookData
|
|
116
|
+
* suitable for `apiRef.createWorkbook(...)` and for persistence as the initial
|
|
117
|
+
* snapshot of a new workbook.
|
|
118
|
+
*
|
|
119
|
+
* ONE reader: ExcelJS (`xlsx-to-univer-excel`) holds styles, number formats,
|
|
120
|
+
* widths, heights, frozen panes, merges, validation, conditional formatting,
|
|
121
|
+
* filter range, notes, links and pictures. A file that is not already an
|
|
122
|
+
* .xlsx (.xls, .ods, .csv, .tsv) is first re-written as an .xlsx by the
|
|
123
|
+
* Alchemy workbook door — values, formulas and merges — and read by that same
|
|
124
|
+
* reader, so there is no second import path to drift.
|
|
125
|
+
*/
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Parse a spreadsheet file into a Univer workbook. Whatever could not be
|
|
129
|
+
* carried is reported through `options.onDropped` (the caller tells the person).
|
|
130
|
+
*/
|
|
131
|
+
declare function xlsxToUniverWorkbook(file: File, options?: XlsxImportOptions): Promise<Partial<IWorkbookData>>;
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Spreadsheet file → a NEW workbook, the ONE import path: the Workbooks home and the editor's
|
|
135
|
+
* File → Import both run it. The file is parsed before anything is created (a malformed file leaves
|
|
136
|
+
* no empty workbook behind), the lossless original is stashed (non-fatal), and a failed save rolls
|
|
137
|
+
* the new row back.
|
|
138
|
+
*/
|
|
139
|
+
/**
|
|
140
|
+
* Pre-flight import file check. We deliberately do NOT use the `accept`
|
|
141
|
+
* attribute on the picker (it greys out everything in Drive / Google
|
|
142
|
+
* Sheets pickers on iOS and many Android pickers), so we validate after
|
|
143
|
+
* pick. Returns null when the file is accepted, or a short user-facing
|
|
144
|
+
* reason string when it isn't.
|
|
145
|
+
*/
|
|
146
|
+
declare function unsupportedFileReason(file: File): string | null;
|
|
147
|
+
declare function importWorkbookFile(file: File, organizationId: string | null): Promise<{
|
|
148
|
+
id: string;
|
|
149
|
+
name: string;
|
|
150
|
+
notCarried: string[];
|
|
151
|
+
}>;
|
|
152
|
+
|
|
153
|
+
export { type ExportImagePort, type ExportXlsxOptions, H_ALIGN_IN, H_ALIGN_OUT, RESOURCE, type RangeLike, type UniverResource, V_ALIGN_IN, V_ALIGN_OUT, type XlsxExportReport, a1, argbToColor, borderFromExcel, borderToExcel, buildXlsxFromUniver, colCharsToPx, colPxToChars, colorToArgb, downloadUniverAsXlsx, importWorkbookFile, parseA1Range, rangeToA1, readResource, rowPtToPx, rowPxToPt, univerSnapshotToRegisteredXlsxBytes, univerSnapshotToWorkbookJson, univerSnapshotToXlsxBytes, unsupportedFileReason, writeResource, xlsxToUniverWorkbook };
|