import { isObject } from 'lodash' ; import { saveAs } from '@elastic/filesaver' ; import { DataViewColumn , DataViewRow } from '../types' ; const LINE_FEED_CHARACTER = '\r\n' ; const nonAlphaNumRE = /[^a-zA-Z0-9]/ ; const allDoubleQuoteRE = /"/g ; function escape ( val , quoteValues ) { if ( isObject ( val ) ) { val = ( val as any ) . valueOf ( ) ; } val = String ( val ) ; if ( quoteValues && nonAlphaNumRE . test ( val ) ) { val = `"${ val . replace ( allDoubleQuoteRE , '""' ) }"` ; } return val ; } function buildCsv ( columns , rows , csvSeparator , quoteValues , valueFormatter ? ) { const header = columns . map ( ( col ) => escape ( col . name , quoteValues ) ) ; const orderedFieldNames = columns . map ( ( col ) => col . field ) ; const csvRows = rows . map ( ( row ) => { return orderedFieldNames . map ( ( field ) => escape ( valueFormatter ? valueFormatter ( row [ field ] ) : row [ field ] , quoteValues ) ) ; } ) ; return ( [ header , ... csvRows ] . map ( ( row ) => row . join ( csvSeparator ) ) . join ( LINE_FEED_CHARACTER ) + LINE_FEED_CHARACTER ) ; } export function exportAsCsv ( { filename , columns , rows , valueFormatter , csvSeparator , quoteValues , } ) { const type = 'text/csv;charset=utf-8' ; const csv = new Blob ( [ buildCsv ( columns , rows , csvSeparator , quoteValues , valueFormatter ) ] , { type , } ) ; saveAs ( csv , filename ) ; }