storyblok / field-plugin

Create and deploy Storyblok Field Plugin
https://www.storyblok.com/docs/plugins/field-plugins/introduction
25 stars 3 forks source link

Add easy access to current block data object #387

Open mrsunshine opened 2 months ago

mrsunshine commented 2 months ago

Feature request: Current block data object in the root of your plugin.data or a util function which returns the object.

Use case you want to read data from a field from your current block. At the moment you have the blockUid in your plugin.data and you have t recursively search for the object with the given uid to get your block data object. Would be cool to either have the block object in the root of your plugin.data or a util function which returns the object. so not everybody has to implement his own search block function.

eunjae-lee commented 2 months ago

Hi @mrsunshine thanks for reaching out to us. If I understand this correctly, do you want a field plugin to be able to access other fields in the current story via blockUid?

mrsunshine commented 2 months ago

@eunjae-lee yes. All informations are there but difficult to access. Imagine you have field A and your field type plugin in the same block. Inside your field type plugin you want to use the value of the field A. Currently you have to use plugin.data.blockUid to recursively search through data.story.content to find the block object with blockUid. For easy use it would be helpfull to have either:

  1. the block object where the field type plugin on the root level plugin.data.block
  2. or a helper function which returns a block object by UUID

something like this:

...
const blockUid: string = plugin?.data?.blockUid || ''
const contentObj: Object | undefined = data?.story?.content;
const myBlock = searchBlock(contentObj, blockUid);

const searchBlock = (obj: Block, uid: string): Block | null => {
  if (obj._uid === uid) {
    return obj;
  }

  // Check nested objects and arrays
  for (let key of Object.keys(obj)) {
    const value = obj[key];
    if (Array.isArray(value)) {
      for (let item of value) {
        let result = searchBlock(item, uid);
        if (result) {
          return result;
        }
      }
    } else if (typeof value === 'object' && value !== null) {
      let result = searchBlock(value, uid);
      if (result) {
        return result;
      }
    }
  }

  return null; // Return null if the block is not found
}
eunjae-lee commented 2 months ago

@mrsunshine got it. Thanks for the clarification and thanks for providing this code snippet, which can be useful for others looking at this issue in the future 🙂 We will create an internal ticket to discuss about this, but I cannot tell any ETA, and whether or not we will ship this, though. Thanks for your contribution 💙