@@ -13,7 +13,7 @@ const blockContentType = defaultSchema
1313 . fields . find ( field => field . name === 'body' ) . type
1414
1515function convertHTMLtoPortableText ( HTMLDoc ) {
16- if ( ! ( HTMLpattern . test ( HTMLDoc ) ) ) {
16+ if ( ! HTMLpattern . test ( HTMLDoc ) ) {
1717 return [ ]
1818 }
1919 const rules = [
@@ -47,26 +47,56 @@ function convertHTMLtoPortableText (HTMLDoc) {
4747 if ( el . tagName . toLowerCase ( ) !== 'pre' ) {
4848 return undefined
4949 }
50- const code = el . children [ 0 ]
51- const childNodes =
52- code && code . tagName . toLowerCase ( ) === 'code'
53- ? code . childNodes
50+ const codeElement = el . children [ 0 ]
51+ const codeElementNodes =
52+ codeElement && codeElement . tagName . toLowerCase ( ) === 'code'
53+ ? codeElement . childNodes
5454 : el . childNodes
55- let text = ''
56- childNodes . forEach ( node => {
57- text += node . textContent
55+ let code = ''
56+ codeElementNodes . forEach ( node => {
57+ code += node . textContent
5858 } )
59- /**
60- * use `block()` to add it to the
61- * root array, instead of as
62- * children of a block
63- * */
6459
60+ let language = 'text' ;
61+ if ( codeElement . className ) {
62+ language = codeElement . className . split ( "-" ) [ 1 ] ;
63+ }
6564 return block ( {
6665 _type : 'code' ,
67- text : text
66+ code : code ,
67+ language : language
6868 } )
6969 }
70+ } ,
71+ {
72+ deserialize ( el , next , block ) {
73+ if ( el . tagName === 'IMG' ) {
74+ return {
75+ _type : 'img' ,
76+ asset : {
77+ src : `${ el . getAttribute ( 'src' ) . replace ( / ^ \/ \/ / , 'https://' ) } ` ,
78+ alt : `${ el . getAttribute ( 'alt' ) } `
79+ }
80+ }
81+ }
82+
83+ if (
84+ el . tagName . toLowerCase ( ) === 'p' &&
85+ el . childNodes . length === 1 &&
86+ el . childNodes . tagName &&
87+ el . childNodes [ 0 ] . tagName . toLowerCase ( ) === 'img'
88+ ) {
89+ return {
90+ _type : 'img' ,
91+ asset : {
92+ src : `${ el . getAttribute ( 'src' ) . replace ( / ^ \/ \/ / , 'https://' ) } ` ,
93+ alt : `${ el . getAttribute ( 'alt' ) } `
94+ }
95+ }
96+ }
97+ // Only convert block-level images, for now
98+ return undefined
99+ }
70100 }
71101 ]
72102 /**
@@ -79,5 +109,4 @@ function convertHTMLtoPortableText (HTMLDoc) {
79109 parseHtml : html => new JSDOM ( html ) . window . document
80110 } )
81111}
82-
83- module . exports = convertHTMLtoPortableText
112+ module . exports = convertHTMLtoPortableText
0 commit comments