Security News
Fluent Assertions Faces Backlash After Abandoning Open Source Licensing
Fluent Assertions is facing backlash after dropping the Apache license for a commercial model, leaving users blindsided and questioning contributor rights.
@sanity/block-tools
Advanced tools
Can format HTML, Slate JSON or Sanity block array into any other format.
@sanity/block-tools is a utility library for working with Sanity's block content. It provides tools for parsing, serializing, and manipulating block content, which is a rich text format used in Sanity's content management system.
Parsing Block Content
This feature allows you to parse HTML content into Sanity block content. The `htmlToBlocks` function converts HTML strings into an array of block objects that can be used within Sanity.
const { htmlToBlocks } = require('@sanity/block-tools');
const html = '<p>Hello, world!</p>';
const blocks = htmlToBlocks(html, { type: 'block' });
console.log(blocks);
Serializing Block Content
This feature allows you to serialize Sanity block content back into HTML. The `blocksToHtml` function takes an array of block objects and converts them into an HTML string.
const { blocksToHtml } = require('@sanity/block-tools');
const blocks = [{ _type: 'block', children: [{ _type: 'span', text: 'Hello, world!' }] }];
const html = blocksToHtml({ blocks });
console.log(html);
Custom Block Serializers
This feature allows you to define custom serializers for different block types. The `blocksToHtml` function can take a `serializers` object to customize how different block types are converted to HTML.
const { blocksToHtml } = require('@sanity/block-tools');
const blocks = [{ _type: 'block', children: [{ _type: 'span', text: 'Hello, world!' }] }];
const customSerializers = {
types: {
block: (props) => `<p style="color: red;">${props.children}</p>`
}
};
const html = blocksToHtml({ blocks, serializers: customSerializers });
console.log(html);
Draft.js is a rich text editor framework for React, built by Facebook. It provides a set of tools for building rich text editors, including parsing and serializing content. Compared to @sanity/block-tools, Draft.js is more focused on providing a complete editor experience, while @sanity/block-tools is more about manipulating block content.
Slate is another rich text editor framework for React. It provides a highly customizable and extensible architecture for building rich text editors. Like Draft.js, Slate offers tools for parsing and serializing content, but it also provides more flexibility in terms of editor customization. Compared to @sanity/block-tools, Slate is more focused on the editor experience rather than just content manipulation.
ProseMirror is a toolkit for building rich text editors. It provides a set of tools for parsing, serializing, and manipulating rich text content. ProseMirror is highly customizable and can be used to build complex editor experiences. Compared to @sanity/block-tools, ProseMirror offers more low-level control over the editor and content manipulation.
Various tools for processing Sanity block content
Let's start with a complete example:
import Schema from '@sanity/schema'
import blockTools from '@sanity/block-tools'
// Start with compiling a schema we can work against
const schema = Schema.compile({
name: 'myBlog',
types: [
{
type: 'object',
name: 'blogPost',
fields: [
{
title: 'Title',
type: 'string',
name: 'title'
},
{
title: 'Body',
name: 'body',
type: 'array',
of: [{type: 'block'}]
}
]
}
]
})
// The compiled schema type for the content type that holds the block array
const blockContentType = defaultSchema.get('blogPost')
.fields.find(field => field.name === 'body').type
// Convert HTML to blocks
const blocks = blockTools.htmlToBlocks(
'<html><body><h1>Hello world!</h1><body></html>',
{blockContentType}
)
// Convert a Slate state to blocks
const blocks = blockTools.slateStateToBlocks(slateJson, blockContentType)
// Convert blocks to a JSON serialized Slate state
const slateState = blockTools.blocksToSlateState(blocks, blockContentType)
// Get the feature-set of a blockContentType
const features = blockTools.getBlockContentFeatures(blockContentType)
htmlToBlocks(html, options)
(html deserializer)This will deserialize the input html (string) into blocks.
blockContentType
A compiled version of the block content schema type. When you give this option, the deserializer will respect the schema when deserializing to blocks. I.e. if the schema doesn't allow h2-styles, all h2 html-elements will deserialized to normal styled blocks.
parseHtml
The HTML-deserialization is done by default by the browser's native DOMParser.
On the server side you can give the function parseHtml
that parses the html into a DOMParser compatible model / API.
const jsdom = require('jsdom')
const {JSDOM} = jsdom
const blocks = blockTools.htmlToBlocks(
'<html><body><h1>Hello world!</h1><body></html>',
{
blockContentType,
parseHtml: html => new JSDOM(html).window.document
}
)
rules
You may add your own rules to deal with special HTML cases.
blockTools.htmlToBlocks(
'<html><body><pre><code>const foo = "bar"</code></pre></body></html>',
{
blockContentType: compiledBlockContentType,
parseHtml: html => new JSDOM(html),
rules: [
// Special rule for code blocks (wrapped in pre and code tag)
{
deserialize(el, next) {
if (el.tagName.toLowerCase() != 'pre') {
return undefined
}
const code = el.children[0]
const childNodes = code && code.tagName.toLowerCase() === 'code'
? code.childNodes
: el.childNodes
let text = ''
childNodes.forEach(node => {
text += node.textContent
})
return {
_type: 'span',
marks: ['code'],
text: text
}
}
}
]
}
)
blocksToSlateState(blocks, blockContentTypeSchema)
Convert blocks to a serialized Slate state respecting the input schema.
slateStateToBlocks(slateState, blockContentTypeSchema)
Convert a slate state to blocks respecting the input schema.
getBlockContentFeatures(blockContentType)
Will return an object with the features enabled for the input block content type.
{
enabledBlockAnnotations: ['link'],
enabledSpanDecorators: [
'strong',
'em',
'code',
'underline',
'strike-through'
],
enabledBlockStyles: [
'normal',
'h1',
'h2',
'h3',
'h4',
'h5',
'h6',
'blockquote'
]
}
FAQs
Can format HTML, Slate JSON or Sanity block array into any other format.
The npm package @sanity/block-tools receives a total of 155,013 weekly downloads. As such, @sanity/block-tools popularity was classified as popular.
We found that @sanity/block-tools demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 67 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Fluent Assertions is facing backlash after dropping the Apache license for a commercial model, leaving users blindsided and questioning contributor rights.
Research
Security News
Socket researchers uncover the risks of a malicious Python package targeting Discord developers.
Security News
The UK is proposing a bold ban on ransomware payments by public entities to disrupt cybercrime, protect critical services, and lead global cybersecurity efforts.