Node's Perfect Mate

    @graphcms/html-to-slate-ast
    TypeScript icon, indicating that this package has built-in type declarations

    0.13.1 • Public • Published

    @graphcms/html-to-slate-ast

    HTML to Slate AST converter for the Hygraph's RichTextAST format.

    ⚠️ This converter outputs the custom flavour of Slate AST that is used at Hygraph, and will most likely not produce an output compatible with your own Slate implementation. But feel free to fork it and adapt it to your needs.

    Usage

    1. Install

    This package needs to have the packages slate and slate-hyperscript installed, and jsdom as well if you need to run the converter in nodejs.

    # for node or isomorphic usage, jsdom is required
    npm install jsdom
    
    # required peer-dependancies
    npm install slate@0.58.3 slate-hyperscript@0.58.3
    npm install @graphcms/html-to-slate-ast

    2. Convert your data

    ☝️ htmlToSlateAst returns a Promise

    import { htmlToSlateAST } from '@graphcms/html-to-slate-ast';
    
    const htmlString = '<div><p>test</p></div>'; // or import from a file or database
    const ast = await htmlToSlateAST(htmlString);

    3. Use it in your Content API mutations

    The output of this converstion is compatible with our RichTextAST GraphQL type and can be used to import content in your Rich Text fields.

    Example mutation:

    mutation newArticle($title: String!, $content: RichTextAST) {
      createArticle(data: { title: $title, content: $content }) {
        id
        title
        content {
          html
          raw
        }
      }
    }

    Output generated by htmlToSlateAST will represent the children array of the Slate editor object. However, when creating or updating the value of a Rich text field, you are setting the value of the editor node itself. This means that the output should be transformed into a Rich text compatible object, for example:

    const data = await client.request(newArticleQuery, {
      title: 'Example title for an article',
      content: { children: ast },
    });

    Here, in terms of Slate, $content is the editor node, so the $ast array must be assigned to the children key in that object.

    You can see the full example using graphql-request to mutate the data into Hygraph here

    See the docs about the Rich Text field type and Content Api mutations

    📝 License

    Licensed under the MIT License.


    Made with 💜 by Hygraph 👋 join our community!

    Install

    npm i @graphcms/html-to-slate-ast

    DownloadsWeekly Downloads

    456

    Version

    0.13.1

    License

    MIT

    Unpacked Size

    330 kB

    Total Files

    12

    Last publish

    Collaborators

    • rajatsharma
    • mahaveergcms
    • martian2lee
    • harish027
    • graphcms-owner
    • somus
    • jpedroschmitz