11import { Client } from "@notionhq/client" ;
22import { ListBlockChildrenResponse } from "@notionhq/client/build/src/api-endpoints" ;
33import { NotionToMarkdown } from "notion-to-md" ;
4+ import markdownTable from "markdown-table" ;
45import {
56 ListBlockChildrenResponseResult ,
67 ListBlockChildrenResponseResults ,
@@ -22,6 +23,59 @@ export function setupCustomTransformers(
2223 notionColumnToMarkdown ( notionToMarkdown , notionClient , block )
2324 ) ;
2425
26+ // This is mostly a copy of the table handler from notion-to-md. The change is to handle newlines in the
27+ // notion cell content.
28+ notionToMarkdown . setCustomTransformer (
29+ "table" ,
30+ async ( block : ListBlockChildrenResponseResult ) => {
31+ const { id, has_children } = block as any ;
32+ const tableArr : string [ ] [ ] = [ ] ;
33+ if ( has_children ) {
34+ const tableRows = await getBlockChildren ( notionClient , id , 100 ) ;
35+ // console.log(">>", tableRows);
36+ const rowsPromise = tableRows ?. map ( async row => {
37+ const { type } = row as any ;
38+ const cells = ( row as any ) [ type ] [ "cells" ] ;
39+
40+ /**
41+ * this is more like a hack since matching the type text was
42+ * difficult. So converting each cell to paragraph type to
43+ * reuse the blockToMarkdown function
44+ */
45+ const cellStringPromise = cells . map (
46+ async ( cell : any ) =>
47+ await notionToMarkdown . blockToMarkdown ( {
48+ type : "paragraph" ,
49+ paragraph : { rich_text : cell } ,
50+ } as ListBlockChildrenResponseResult )
51+ ) ;
52+
53+ const cellStringArrRaw : string [ ] = await Promise . all (
54+ cellStringPromise
55+ ) ;
56+ // This is our patch to the original notion-to-md code.
57+ const cellStringArr = cellStringArrRaw . map ( c =>
58+ c
59+ // Trailing newlines are almost certainly not wanted, and converting to br's gives weird results
60+ . replace ( / [ \r \n ] + $ / , "" )
61+ // Preserving line breaks within cells can't be done in stock markdown. Since we're producing
62+ // mdx, which supports embedded HTML, we can handle it with <br/>.
63+ // I'm not sure exactly what line breaks might occur in the input, depending on platform,
64+ // so handle all the common cases.
65+ . replaceAll ( "\r\n" , "<br/>" )
66+ . replaceAll ( "\n" , "<br/>" )
67+ . replaceAll ( "\r" , "<br/>" )
68+ ) ;
69+ // console.log("~~", cellStringArr);
70+ tableArr . push ( cellStringArr ) ;
71+ // console.log(tableArr);
72+ } ) ;
73+ await Promise . all ( rowsPromise || [ ] ) ;
74+ }
75+ return markdownTable ( tableArr ) ;
76+ }
77+ ) ;
78+
2579 // Note: Pull.ts also adds an image transformer, but has to do that for each
2680 // page so we don't do it here.
2781}
0 commit comments