Convert structured text field form value to valid structured text

Describe the issue:

  • I’m trying to render a real-time preview of fields in a sidebar panel plugin, that doesn’t require hitting save each time we want it to update.
  • One of the fields we use is a block with a structured text field
  • The schema for the structured text field accessed through ctx.formValues.<structuredTextField> doesn’t appear to be valid structured text
  • I assume there is some function that must take the form value and turn it into structured text that is accessed through the GraphQL api, but I cannot locate that when checking this library
  • If I use the react component, it throws errors about the structured text field not containing valid nodes

Questions:

  1. Why is the structured text field not valid structured text until retrieved from the graphql api?
  2. Is there an available utility to convert the structured text field into valid structured text?

(Optional) Do you have any sample code you can provide?

  • I have started writing a function to convert it to valid structured text, but this feels a little bit silly to have to do. For example, this is a starter for converting a paragraph element to valid children span elements.
type Span = {
  type: "span";
  value: string;
  marks: string[];
};

function transformObject(input: any) {
  return {
    type: input.type,
    children: input.children.map((child: any) => {
      let transformedChild: Span = {
        type: "span",
        value: child.text,
        marks: [],
      };

      if (child.strong) {
        transformedChild.marks.push("strong");
      }

      return transformedChild;
    }),
  };
}

Example input retrieved from ctx.formValues.:

[{"type":"paragraph","children":[{"text":"Test123"}]},{"type":"paragraph","children":[{"text":"Test 456","strong":true}]}]

Mapping each of these objects into my transformObject function returns this valid structured text, but why is this required?

[{"type":"paragraph","children":[{"type":"span","value":"Test123","marks":[]}]},{"type":"paragraph","children":[{"type":"span","value":"Test 456","marks":["strong"]}]}]

Hey @nroth,

Does ctx.formValuesToItem() do the trick?

It’s actually part of our plugins-sdk at the bottom of this page (Field extensions — Plugin SDK — DatoCMS) – sorry, there isn’t a way to deep-link to the particular entry, but if you cmd-F for ctx.formValuestoItem() you should see it. (Sorry, I’ll add that issue to our documentation updates and try to improve its visiblity)

In code, it lives here: plugins-sdk/packages/sdk/src/types.ts at master · datocms/plugins-sdk · GitHub

Thanks, that seems to have done the trick. I noticed that method, but for some reason thought it was for a different purpose.

1 Like

Awesome!

Edit: And thank you so much for the detailed problem description… it really helps :slight_smile: