Last active
October 7, 2022 21:38
-
-
Save kmelve/7b4e665818735da073daa7afaed50420 to your computer and use it in GitHub Desktop.
Markdown Paste Handling for Sanity Studio v2 using micromark
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Remember: | |
sanity install @sanity/code-input | |
yarn add micromark | |
*/ | |
import { micromark } from 'micromark' | |
import { htmlToBlocks } from '@sanity/block-tools' | |
export async function handlePaste(input) { | |
const { event, type, path } = input | |
const text = event.clipboardData.getData('text/plain') | |
if (text) { | |
const html = micromark(text) | |
if (html) { | |
const blocks = htmlToBlocks(html, type, { | |
rules: [ | |
{ | |
deserialize(el, next, block) { | |
if (!el || !el.children || (el.tagName && el.tagName.toLowerCase() !== 'pre')) { | |
return undefined | |
} | |
const codeElement = el.children[0] | |
const childNodes = | |
codeElement && codeElement.tagName.toLowerCase() === 'code' ? codeElement.childNodes : el.childNodes | |
let code = '' | |
childNodes.forEach((node) => { | |
code += '\n' + node.textContent + '\n' | |
}) | |
const language = codeElement && codeElement.className ? codeElement.className.replace('language-', '') : '' | |
return block({ | |
_type: 'code', | |
language, | |
code, | |
}) | |
}, | |
}, | |
] | |
}) | |
// return an insert patch | |
return { insert: blocks, path } | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { forwardRef } from 'react' | |
import { BlockEditor } from 'part:@sanity/form-builder' | |
import { handlePaste } from './handlePaste' | |
const CustomEditor = forwardRef((props, ref) => (<BlockEditor | |
{...props} | |
ref={ref} | |
onPaste={handlePaste} | |
/> | |
)) | |
export default { | |
name: 'post', | |
type: 'document', | |
title: 'Post', | |
fields: [ | |
{ | |
name: 'title', | |
type: 'string', | |
title: 'Title', | |
}, | |
{ | |
name: 'body', | |
type: 'array', | |
title: 'Body', | |
of: [{ type: 'block' }, { type: 'code' }], | |
inputComponent: CustomEditor, | |
} | |
] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment