Coder Social home page Coder Social logo

block-content-to-hyperscript's Introduction

block-content-to-hyperscript

Render an array of block text from Sanity with HyperScript.

Installing

npm install --save @sanity/block-content-to-hyperscript

Usage

const h = require('hyperscript')
const blocksToHyperScript = require('@sanity/block-content-to-hyperscript')
const client = require('@sanity/client')({
  projectId: '<your project id>',
  dataset: '<some dataset>',
  useCdn: true
})

const serializers = {
  types: {
    code: props => h('pre', {className: props.node.language}, h('code', props.node.code))
  }
}

client.fetch('*[_type == "article"][0]').then(article => {
  const el = blocksToHyperScript({
    blocks: article.body,
    serializers: serializers
  })

  document.getElementById('root').appendChild(el)
})

Options

  • className - When more than one block is given, a container node has to be created. Passing a className will pass it on to the container. Note: see renderContainerOnSingleChild.
  • renderContainerOnSingleChild - When a single block is given as input, the default behavior is to not render any container. If you always want to render the container, pass true.
  • serializers - Specifies the functions to use for rendering content. Merged with default serializers.
  • serializers.types - Serializers for block types, see example above
  • serializers.marks - Serializers for marks - data that annotates a text child of a block. See example usage below.
  • serializers.list - Function to use when rendering a list node
  • serializers.listItem - Function to use when rendering a list item node
  • serializers.hardBreak - Function to use when transforming newline characters to a hard break (default: <br/>, pass false to render newline character)
  • serializers.container - Serializer for the container wrapping the blocks
  • serializers.unknownType - Override the default serializer for blocks of unknown type, if ignoreUnknownTypes is set to false (the default).
  • serializers.unknownMark - Override the default serializer for marks of unknown type. Defaults to a span without any styling.
  • imageOptions - When encountering image blocks, this defines which query parameters to apply in order to control size/crop mode etc.
  • ignoreUnknownTypes - By default (or when setting this property explicitly to true) it will output a hidden <div> with a warning. By setting this property to false, the renderer will throw an error when encountering unknown block types. The behavior of the unknown type rendering can be customized by specifying a serializer with serializers.unknownType.

In addition, in order to render images without materializing the asset documents, you should also specify:

  • projectId - The ID of your Sanity project.
  • dataset - Name of the Sanity dataset containing the document that is being rendered.

Examples

Rendering custom marks

const input = [
  {
    _type: 'block',
    children: [
      {
        _key: 'a1ph4',
        _type: 'span',
        marks: ['s0m3k3y'],
        text: 'Sanity'
      }
    ],
    markDefs: [
      {
        _key: 's0m3k3y',
        _type: 'highlight',
        color: '#E4FC5B'
      }
    ]
  }
]

const highlight = props => h('span', {style: {backgroundColor: props.mark.color}}, props.children)

const content = blocksToHyperScript({
  blocks: input,
  serializers: {marks: {highlight}}
})

Specifying image options

blocksToHyperScript({
  blocks: input,
  imageOptions: {w: 320, h: 240, fit: 'max'},
  projectId: 'myprojectid',
  dataset: 'mydataset'
})

Customizing default serializer for block-type

const BlockRenderer = props => {
  const style = props.node.style || 'normal'

  if (/^h\d/.test(style)) {
    const level = style.replace(/[^\d]/g, '')
    return h('h2', {className: `my-heading level-${level}`}, props.children)
  }

  return style === 'blockquote'
    ? h('blockquote', {className: 'my-block-quote'}, props.children)
    : h('p', {className: 'my-paragraph'}, props.children)
}

blocksToHyperScript({
  blocks: input,
  serializers: {types: {block: BlockRenderer}}
})

License

MIT-licensed. See LICENSE.

block-content-to-hyperscript's People

Contributors

bjoerge avatar nerdegutt avatar rexxars avatar skogsmaskin avatar vramdal avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

block-content-to-hyperscript's Issues

Error while fetching the blog from sanity to my template

same error
error - Error: Unknown block type "undefined", please specify a serializer for it in the serializers.types prop

  <PortableText
      // Pass in block content straight from Sanity.io
      content={blogs[0].content}
      projectId="oeqragbg"
      dataset="production"
      // Optionally override marks, decorators, blocks, etc. in a flat
      // structure without doing any gymnastics
      serializers = {{
        h1: (props) => <h1 style={{ color: "red" }} {...props} />,
        li: ({ children }) => <li className="special-list-item">{children}</li>,
        
      }}
    />

Originally posted by @bogambo in #10 (comment)

Handle unknown block types more gracefully

At the moment the BlockSerializer throws an error for unknown block types. Could the renderer just render nothing, or an error string, and emit a warning instead of throwing an error?

We use different serializers (react + react-native) for the same content, and we have several custom blocks. This means that it is a real risks for the serializers to get out of sync with the block content, and the result would be an ugly crash of the application.

Another case: We render block content in a mobile app. Even if the serializers get updated properly, a lot of users will not update the app immediately. This means that all old versions of the app would crash once a new block element is used in content that is also loaded by old apps.

Duplicate List Items

If you have a simple block with a bulleted list, where the list has a single list item in it, I get a duplicate list item.

<ul>
    <li></li>
</ul>
<li></li>

Instead of:

<ul>
    <li></li>
</ul>

Handling of marks on block types other than span

We are working on a custom PortableText parser in C#, with the possibility to also define some custom parsers for certain HTML elements.

In the example below, the blocks prop contains the output of our parser, but there is a problem, that makes it unrecognizable for @sanity/block-content-to-react. On line 20, our parser would add a marks: [], empty array, that stops the BlockContent rendering with the error:

Cannot read property '_type' of undefined

Removing/commenting out the line fixes the problem. Under the custom image block, we also have a _type: span item which similarily holds an empty marks: [] block, but causes no problem for BlockContent. Why is that?

https://codesandbox.io/s/young-platform-8kz1i?fontsize=14&hidenavigation=1&theme=light&file=/src/App.js:470-489

The code that fails:

const isPlain = typeof mark === 'string'
const markType = isPlain ? mark : mark._type
const serializer = props.serializers.marks[markType]

(Linking to the original Slack conversation with @kmelve https://sanity-io-land.slack.com/archives/C9Z7RC3V1/p1600687685152700)

Event props doesn't work

I would expect this to work, as it's working with hyperscript:

h(
  'button,
  {
    onclick: e => {
      console.log('You clicked me!');
    },
  },
  'Click me?'
)

But seems like those props are "swallowed" somehow.

Missing serializers for block type figure

Version 2.0.7

I'm making a website using the NextJS landing page template made by you guys: https://github.com/sanity-io/sanity-template-nextjs-landing-pages.

If I insert an image in a text box (type: portableText), it creates the following error:

Error: Unknown block type "figure", please specify a serializer for it in the 'serializers.types' prop

If I add the following code to src/serializers.js under funciton BlockSerializer(props), it fixes the error:

if (blockType === 'figure') {
    serializer = serializers.types['image'];
}

Is there any good way to fix this locally without editing the file directly inside node_modules, or will you guys be able to provide a fix within some days?

WebpackError: TypeError: urlBuilder is not a function Gatsby (on Build)

Hi!

I'm building a website with gatsby and sanity.io, on gatsby develop everything works fine, but during building I keep getting this error:

**WebpackError: TypeError: urlBuilder is not a function

  • getImageUrl.js:51 buildUrl
    node_modules/@sanity/block-content-to-hyperscript/lib/getImageUrl.js:51:1

  • serializers.js:110 ImageSerializer
    node_modules/@sanity/block-content-to-hyperscript/lib/serializers.js:110:1**

Does anyone know why ?

My getImageUrl.js looks like this:

"use strict";

var generateHelpUrl = require('@sanity/generate-help-url');

var urlBuilder = require('@sanity/image-url');

var objectAssign = require('object-assign');

var enc = encodeURIComponent;
var materializeError = "You must either:\n  - Pass `projectId` and `dataset` to the block renderer\n  - Materialize images to include the `url` field.\n\nFor more information, see ".concat(generateHelpUrl('block-content-image-materializing'));

var getQueryString = function getQueryString(options) {
  var query = options.imageOptions;
  var keys = Object.keys(query);

  if (!keys.length) {
    return '';
  }

  var params = keys.map(function (key) {
    return "".concat(enc(key), "=").concat(enc(query[key]));
  });
  return "?".concat(params.join('&'));
};

var buildUrl = function buildUrl(props) {
  var node = props.node,
      options = props.options;
  var projectId = options.projectId,
      dataset = options.dataset;
  var asset = node.asset;

  if (!asset) {
    throw new Error('Image does not have required `asset` property');
  }

  if (asset.url) {
    return asset.url + getQueryString(options);
  }

  if (!projectId || !dataset) {
    throw new Error(materializeError);
  }

  var ref = asset._ref;

  if (!ref) {
    throw new Error('Invalid image reference in block, no `_ref` found on `asset`');
  }
  console.log("node",node);
  return urlBuilder(objectAssign({
    projectId: projectId,
    dataset: dataset
  }, options.imageOptions || {})).image(node).toString();
};

module.exports = buildUrl;
//#sourceMappingURL=getImageUrl.js.map

And my gatsby-nide.js like this:

/**
 * Implement Gatsby's Node APIs in this file.
 *
 * See: https://www.gatsbyjs.org/docs/node-apis/
 */

const path = require('path');
// Get your list of languages from somewhere, env file, config.json, etc
// for sake of this snippet I am putting it here
const extraLanguages = ["pt","pl"]
const defaultLang = "en"; // English is currently the default so it isn't needed here.
const createLocalePage = (page, createPage) => {
  const { context, ...rest } = page
  createPage({
    ...rest,
    context: {
      ...context,
      locale: process.env.LOCALE,
    },
  })
  if (extraLanguages.length) {
    extraLanguages.forEach(code => {
      const { path, context, ...rest } = page
      createPage({
        ...rest,
        path: `/${code}${path}`,
        // every page for each language gets the language code as a prefix
        // to its path: "/es/blog/<some-slug>" for example
        context: {
          ...context,
          locale: code,
        },
      })
    })
  }
}
// You can delete this file if you're not using it
exports.createPages = async ({ actions, graphql }) => {
  const result = await graphql(`
    {
      allSanityPost {
        edges {
          node {
            slug {
              current
            }
          }
        }
      }
    }
  `);

  const projects = result.data.allSanityPost.edges.map(({ node }) => node);
  if (extraLanguages.length) {
    extraLanguages.forEach(code => {
      
      projects.forEach(project => {
        actions.createPage({
          path: code+"/"+project.slug.current,
          component: path.resolve('./src/templates/post.js'),
          context: {
            slug: project.slug.current,
            locale:code
          }
        });
      });
    })
  }
  if(defaultLang)
  {
    projects.forEach(project => {
      actions.createPage({
        path: project.slug.current,
        component: path.resolve('./src/templates/post.js'),
        context: {
          slug: project.slug.current,
          locale:defaultLang
        }
      });
    });
  }

};
exports.onCreatePage = ({ page, actions }) => {
  const { createPage, deletePage } = actions
  deletePage(page)
  createLocalePage(page, createPage)
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.