diff --git a/.changeset/light-chicken-shake.md b/.changeset/light-chicken-shake.md new file mode 100644 index 0000000..91fe52e --- /dev/null +++ b/.changeset/light-chicken-shake.md @@ -0,0 +1,5 @@ +--- +"@graphcms/html-to-slate-ast": patch +--- + +fix: preserve graphassets images during HTML import diff --git a/packages/html-to-slate-ast/src/index.ts b/packages/html-to-slate-ast/src/index.ts index 450ab37..88c018e 100644 --- a/packages/html-to-slate-ast/src/index.ts +++ b/packages/html-to-slate-ast/src/index.ts @@ -54,11 +54,39 @@ const ELEMENT_TAGS: Record< ? el.getAttribute('title') : '(Image)'; if (href === null) return {}; + + // Fix text node when pasting images; sanitize URLs; + // if the image is not hosted on graphassets.com, we convert it to a link + if (href.includes('graphassets.com') === false) { + return { + type: 'link', + href: sanitizeUrl(href), + title, + openInNewTab: true, + }; + } + + // if href includes graphassets.com, we convert it to a image + // handle is always the last part of the href + const handle = href.split('/').pop(); + return { - type: 'link', - href: sanitizeUrl(href), - title, - openInNewTab: true, + type: 'image', + src: href, + ...(el.hasAttribute('title') && { title: el.getAttribute('title') }), + ...(el.hasAttribute('width') && { + width: Number(el.getAttribute('width')), + }), + ...(el.hasAttribute('height') && { + height: Number(el.getAttribute('height')), + }), + ...(el.hasAttribute('class') && { + className: el.getAttribute('class'), + }), + ...(el.hasAttribute('style') && { + style: el.getAttribute('style'), + }), + ...(handle && { handle }), }; }, PRE: () => ({ type: 'code-block' }), diff --git a/packages/html-to-slate-ast/test/index.test.ts b/packages/html-to-slate-ast/test/index.test.ts index 8e9da37..6288478 100644 --- a/packages/html-to-slate-ast/test/index.test.ts +++ b/packages/html-to-slate-ast/test/index.test.ts @@ -1189,6 +1189,29 @@ test('Converts an image pasted from Google Docs into a link node', () => { ); }); +test('Keeps image if it is hosted on hygraph', () => { + return htmlToSlateAST( + `` + ).then(ast => { + expect(ast).toStrictEqual([ + { + type: 'image', + src: + 'https://media.graphassets.com/output=format:webp/resize=,width:667,height:1000/8xrjYm4CR721mAZ1YAoy', + width: 600, + height: 1000, + title: "this is this image's title", + style: 'margin-left:0px;margin-top:0px;', + handle: '8xrjYm4CR721mAZ1YAoy', + children: [], + }, + ]); + }); +}); + test('Reshape an incorrectly structured table', () => { return htmlToSlateAST( '
'