1
1
import { FieldType , fieldVoSchema , parseClipboardText , type IFieldVo } from '@teable/core' ;
2
+ import { z } from 'zod' ;
2
3
import { fromZodError } from 'zod-validation-error' ;
3
4
4
5
const teableHtmlMarker = 'data-teable-html-marker' ;
6
+ const teableHeader = 'data-teable-html-header' ;
5
7
6
8
export const serializerHtml = ( data : string , headers : IFieldVo [ ] ) => {
7
9
const tableData = parseClipboardText ( data ) ;
@@ -18,13 +20,8 @@ export const serializerHtml = (data: string, headers: IFieldVo[]) => {
18
20
. join ( '' ) } </tr>`;
19
21
} )
20
22
. join ( '' ) ;
21
- const headerContent = headers
22
- . map ( ( header ) => {
23
- return `<th id="${ header . id } " data-field="${ encodeURIComponent ( JSON . stringify ( header ) ) } ">${ header . name } </th>` ;
24
- } )
25
- . join ( '' ) ;
26
23
27
- return `<meta charset="utf-8"><table ${ teableHtmlMarker } ="1"><thead><tr> ${ headerContent } </tr></thead ><tbody>${ bodyContent } </tbody></table>` ;
24
+ return `<meta charset="utf-8"><table ${ teableHtmlMarker } ="1" ${ teableHeader } =" ${ encodeURIComponent ( JSON . stringify ( headers ) ) } " ><tbody>${ bodyContent } </tbody></table>` ;
28
25
} ;
29
26
30
27
export const extractTableHeader = ( html ?: string ) => {
@@ -34,23 +31,16 @@ export const extractTableHeader = (html?: string) => {
34
31
const parser = new DOMParser ( ) ;
35
32
const doc = parser . parseFromString ( html , 'text/html' ) ;
36
33
const table = doc . querySelector ( 'table' ) ;
37
- const headerRow = table ?. querySelector ( 'thead tr' ) ;
38
- const headerCells = headerRow ?. querySelectorAll ( 'th' ) || [ ] ;
39
-
40
- const headers = Array . from ( headerCells ) ;
41
- let error = '' ;
42
- const result = headers . map ( ( cell ) => {
43
- const fieldVoStr = cell . getAttribute ( 'data-field' ) ;
44
- const fieldVo = fieldVoStr ? JSON . parse ( decodeURIComponent ( fieldVoStr ) ) : undefined ;
45
-
46
- const validate = fieldVoSchema . safeParse ( fieldVo ) ;
47
- if ( validate . success ) {
48
- return fieldVo ;
49
- }
50
- error = fromZodError ( validate . error ) . message ;
51
- return undefined ;
52
- } ) as IFieldVo [ ] ;
53
- return error ? { result : undefined , error } : { result } ;
34
+ const headerStr = table ?. getAttribute ( teableHeader ) ;
35
+ const headers = headerStr ? JSON . parse ( decodeURIComponent ( headerStr ) ) : undefined ;
36
+ if ( ! headers ) {
37
+ return { result : undefined } ;
38
+ }
39
+ const validate = z . array ( fieldVoSchema ) . safeParse ( headers ) ;
40
+ if ( ! validate . success ) {
41
+ return { result : undefined , error : fromZodError ( validate . error ) . message } ;
42
+ }
43
+ return { result : validate . data } ;
54
44
} ;
55
45
56
46
export const isTeableHTML = ( html : string ) => {
0 commit comments