Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add fallback method for CSV download #8452

Merged
merged 20 commits into from
May 16, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion frontend/lib/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@
"moment": "^2.29.4",
"moment-duration-format": "^2.3.2",
"moment-timezone": "^0.5.40",
"native-file-system-adapter": "^3.0.0",
"native-file-system-adapter": "^3.0.1",
"node-emoji": "^1.11.0",
"numbro": "^2.3.6",
"plotly.js": "^2.30.1",
Expand Down
103 changes: 82 additions & 21 deletions frontend/lib/src/components/widgets/DataFrame/hooks/useDataExporter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import {
toSafeString,
} from "@streamlit/lib/src/components/widgets/DataFrame/columns"
import { isNullOrUndefined } from "@streamlit/lib/src/util/utils"
import { logWarning } from "@streamlit/lib/src/util/log"
import { logError, logWarning } from "@streamlit/lib/src/util/log"

// Delimiter between cells
const CSV_DELIMITER = ","
Expand Down Expand Up @@ -76,6 +76,45 @@ type DataExporterReturn = {
exportToCsv: () => void
}

/**
* Writes CSV data to a specified writable stream using provided data table parameters.
* Initiates by writing a UTF-8 Byte Order Mark (BOM) for Excel compatibility, followed by
* column headers and rows constructed from the cell values obtained through `getCellContent`.
* The function handles encoding and CSV formatting, concluding by closing the writable stream.
*
* @param {WritableStreamDefaultWriter} writable - Target stream for CSV data.
* @param {DataEditorProps["getCellContent"]} getCellContent - The cell content getter compatible with glide-data-grid.
* @param {BaseColumn[]} columns - The columns of the table.
* @param {number} numRows - The number of rows of the current state.
*
* @returns {Promise<void>} Promise that resolves when the CSV has been fully written.
*/
async function writeCsv(
writable: WritableStreamDefaultWriter,
getCellContent: DataEditorProps["getCellContent"],
columns: BaseColumn[],
numRows: number
): Promise<void> {
const textEncoder = new TextEncoder()

// Write UTF-8 BOM for excel compatibility:
await writable.write(textEncoder.encode(CSV_UTF8_BOM))

// Write headers:
const headers: string[] = columns.map(column => column.name)
await writable.write(textEncoder.encode(toCsvRow(headers)))

for (let row = 0; row < numRows; row++) {
const rowData: any[] = []
columns.forEach((column: BaseColumn, col: number, _map) => {
rowData.push(column.getCellValue(getCellContent([col, row])))
})
// Write row to CSV:
await writable.write(textEncoder.encode(toCsvRow(rowData)))
}

await writable.close()
}
/**
* Custom hook that handles all the data export/download logic.
*
Expand All @@ -91,6 +130,8 @@ function useDataExporter(
numRows: number
): DataExporterReturn {
const exportToCsv = React.useCallback(async () => {
const timestamp = new Date().toISOString().slice(0, 16).replace(":", "-")
const suggestedName = `${timestamp}_export.csv`
try {
// Lazy import to prevent weird breakage in some niche cases
// (e.g. usage within the replay.io browser). The package works well
Expand All @@ -100,38 +141,58 @@ function useDataExporter(
const nativeFileSystemAdapter = await import(
"native-file-system-adapter"
)

const timestamp = new Date().toISOString().slice(0, 16).replace(":", "-")
const suggestedName = `${timestamp}_export.csv`

const fileHandle = await nativeFileSystemAdapter.showSaveFilePicker({
suggestedName,
types: [{ accept: { "text/csv": [".csv"] } }],
excludeAcceptAllOption: false,
})

const textEncoder = new TextEncoder()
const writer = await fileHandle.createWritable()
await writeCsv(writer, getCellContent, columns, numRows)
} catch (error) {
if (error instanceof Error && error.name === "AbortError") {
// The user has canceled the save dialog. Do nothing.
return
}

// Write UTF-8 BOM for excel compatibility:
await writer.write(textEncoder.encode(CSV_UTF8_BOM))
try {
logWarning(
"Failed to export data as CSV with FileSystem API, trying fallback method",
error
)
// Simulated WritableStream that builds CSV content in-memory for the Blob fallback method
let csvContent = ""

const inMemoryWriter = new WritableStream({
write: async chunk => {
csvContent += new TextDecoder("utf-8").decode(chunk)
},
close: async () => {},
})

// Write headers:
const headers: string[] = columns.map(column => column.name)
await writer.write(textEncoder.encode(toCsvRow(headers)))
await writeCsv(
inMemoryWriter.getWriter(),
getCellContent,
columns,
numRows
)

for (let row = 0; row < numRows; row++) {
const rowData: any[] = []
columns.forEach((column: BaseColumn, col: number, _map) => {
rowData.push(column.getCellValue(getCellContent([col, row])))
// Fallback to the old browser download method:
const blob = new Blob([csvContent], {
type: "text/csv;charset=utf-8;",
})
// Write row to CSV:
await writer.write(textEncoder.encode(toCsvRow(rowData)))
const url = URL.createObjectURL(blob)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

const link = document.createElement("a")
link.style.display = "none"
link.href = url
link.download = suggestedName
document.body.appendChild(link) // Required for FF
link.click()
document.body.removeChild(link) // Clean up
URL.revokeObjectURL(url) // Free up memory
} catch (error) {
logError("Failed to export data as CSV", error)
}

await writer.close()
} catch (error) {
logWarning("Failed to export data as CSV", error)
}
}, [columns, numRows, getCellContent])

Expand Down
8 changes: 4 additions & 4 deletions frontend/yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -11999,10 +11999,10 @@ nanoid@^3.3.4:
resolved "https://registry.yarnpkg.com/nanoid/-/nanoid-3.3.4.tgz#730b67e3cd09e2deacf03c027c81c9d9dbc5e8ab"
integrity sha512-MqBkQh/OHTS2egovRtLk45wEyNXwF+cokD+1YPf9u5VfJiRdAiRwB2froX5Co9Rh20xs4siNPm8naNotSD6RBw==

native-file-system-adapter@^3.0.0:
version "3.0.0"
resolved "https://registry.yarnpkg.com/native-file-system-adapter/-/native-file-system-adapter-3.0.0.tgz#602317f30fdc2495efe598055a0cda75c1c6e051"
integrity sha512-IXwQiLiS7UlrlUetr9rHp+6uAAHT3291w2FGse5rdrQ7YXKtZHaqC4+tEXHMXVcevwsJNB3c7q9KO1Iu3IxgLw==
native-file-system-adapter@^3.0.1:
version "3.0.1"
resolved "https://registry.yarnpkg.com/native-file-system-adapter/-/native-file-system-adapter-3.0.1.tgz#d8881903a94e17eac368c4c0e8805f98a4e2ddc1"
integrity sha512-ocuhsYk2SY0906LPc3QIMW+rCV3MdhqGiy7wV5Bf0e8/5TsMjDdyIwhNiVPiKxzTJLDrLT6h8BoV9ERfJscKhw==
optionalDependencies:
fetch-blob "^3.2.0"

Expand Down