Inspect: Include only BOM char for excel files (#88994)

This commit is contained in:
Ivan Ortega Alba 2024-06-13 09:41:50 +02:00 committed by GitHub
parent ca2df58ab0
commit 080adaf987
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 33 additions and 1 deletions

View File

@ -38,10 +38,25 @@ describe('inspector download', () => {
const filename = call[1];
const text = await blob.text();
// By default the BOM character should not be included
expect(await hasBOM(blob)).toBe(false);
expect(text).toEqual(expected);
expect(filename).toEqual(`${title}-data-${dateTimeFormat(1400000000000)}.csv`);
}
);
it('should include the BOM character when useExcelHeader is true', async () => {
downloadDataFrameAsCsv(dataFrameFromJSON(json), 'test', { useExcelHeader: true });
const call = (saveAs as unknown as jest.Mock).mock.calls[0];
const blob = call[0];
const filename = call[1];
const text = await blob.text();
expect(await hasBOM(blob)).toBe(true);
expect(text).toEqual('sep=,\r\n"time","name","value"\r\n100,a,1');
expect(filename).toEqual(`test-data-${dateTimeFormat(1400000000000)}.csv`);
});
});
describe('downloadAsJson', () => {
@ -104,3 +119,19 @@ describe('inspector download', () => {
});
});
});
async function hasBOM(blob: Blob) {
const reader = new FileReader();
return new Promise<boolean>((resolve, reject) => {
reader.onload = (event: ProgressEvent<FileReader>) => {
if (event.target?.result instanceof ArrayBuffer) {
const arr = new Uint8Array(event.target.result);
resolve(arr[0] === 0xef && arr[1] === 0xbb && arr[2] === 0xbf); // Check for UTF-8 BOM
} else {
reject(new Error('Unexpected FileReader result type'));
}
};
reader.onerror = reject;
reader.readAsArrayBuffer(blob.slice(0, 3)); // Read only the first 3 bytes
});
}

View File

@ -57,8 +57,9 @@ export function downloadDataFrameAsCsv(
transformId: DataTransformerID = DataTransformerID.noop
) {
const dataFrameCsv = toCSV([dataFrame], csvConfig);
const bomChar = csvConfig?.useExcelHeader ? String.fromCharCode(0xfeff) : '';
const blob = new Blob([String.fromCharCode(0xfeff), dataFrameCsv], {
const blob = new Blob([bomChar, dataFrameCsv], {
type: 'text/csv;charset=utf-8',
});