npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

react-block-loader

v0.0.4

Published

A React component to load Block Protocol blocks from a URL

Downloads

1

Readme

WARNING

This package is not yet updated to Block Protocol version 0.2.

React Block Loader

A component which loads a Block Protocol block from a remote URL, and passes on the properties and functions you provide.

Usage

yarn install "react-block-loader"

Pass RemoteBlock (at a minimum) a source url (sourceUrl), the properties the block expects (blockProperties), and functions for it to call (blockProtocolFunctions), as set out in the specification.

import { RemoteBlock } from "react-block-loader";

const blockDependencies = {
  react: require("react"),
  "react-dom": require("react-dom"),
};

const BlockLoader = ({ blockSourceFolder: string }) => {
  const [blockMetadata, setBlockMetadata] = useState(null);

  useEffect(() => {
    fetch(`${blockSourceFolder}/block-metadata.json`)
      .then((resp) => resp.json())
      .then(setBlockMetadata);
  }, [componentId]);

  if (!blockMetadata) {
    return <div>Loading block metadata...</div>;
  }

  const blockProperties = {
    // block's own properties, entityId, linkedEntities, linkGroups, etc
  };

  const blockProtocolFunctions = {
    updateEntities: (actions) => {
      // persist block updates wherever you store them
    },
    // more Block Protocol Functions
  };

  return (
    <RemoteBlock
      blockMetadata={blockMetadata}
      blockProperties={blockProperties}
      blockProtocolFunctions={blockProtocolFunctions}
      externalDependencies={blockDependencies}
      LoadingIndicator={<h1>Optional custom loading indicator</h1>}
      onBlockLoaded={() =>
        console.log(`Block with componentId ${componentId} loaded.`)
      }
      sourceUrl={`${blockSourceFolder}/${blockMetadata.source}`}
    />
  );
};

Props

| name | type | required | default | description | | ------------------------ | -------------- | -------- | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | blockMetadata | object | no | | the block's block-metadata.json. Will be used to determine Web Component tag names (TBD soon). | | blockProperties | object | yes | | the block's own properties, and BP-specified properties (e.g. entityId, linkGroups) | | crossFrame | boolean | no | false | whether this block should make requests to the parent window for block source | | blockProtocolFunctions | object | yes | | the functions provided to blocks for reading and editing entity and link data (replaced by graph service in Þ 0.2) | | externalDependencies | object | no | | libraries which the block depends on but does not include in its package | | LoadingIndicator | ReactElement | no | <div>Loading...</div> | an element to display while the block is loading | | onBlockLoaded | function | no | | a callback, called when the block has been successfully parsed and loaded | | sourceUrl | string | yes | | the URL to the entry source file for the block |

External dependencies

A block may indicate externals in block-metadata.json (docs).

These are libraries the blocks expects the embedding application to supply it. For example, a block may rely on React, but assume that the embedding application will provide it, to save loading it multiple times on a page.

In order to provide blocks with these dependencies, pass an object where the key is <package-name>, and the value is require(<package-name>), e.g.

const blockDependencies = {
  react: require("react"),
  "react-dom": require("react-dom"),
};

Security

This component automatically fetches, parses, and renders the component from the file at the provided sourceUrl.

You should either make sure you trust the source, or sandbox the component so that it does not matter if it is malicious.

Source Fetching & Caching

Requests are cached by URL, so that each source URL only has to be fetched once, and parsed once (in the same window).

Inside iFrames

Where each RemoteBlock instance is loaded in its own iFrame, you can optionally pass crossFrame=true, and the block will send a message to the parent window requesting the text of the source file. This allows the parent window to keep a cache of text per sourceUrl, which is useful if you have multiple iFrames each loading the same remote block. Each iFrame will still have to parse the source.

See the following exports:

  • TextFromUrlRequestMessage – a type for the message request shape
  • TextFromUrlResponseMessage – a type for the response
  • isTextFromUrlRequestMessage – a typeguard for checking the request is of the type of interest
// in the parent window, listen for messages requesting text is fetched from a url
window.addEventListener("message", (requestMessage) => {
  if (isTextFromUrlRequestMessage(requestMessage)) {
    // Ideally you would have a Ref to the iFrame in which the component loads,
    // so that requests to fetch text from other iFrames are not processed.
    // this function otherwise will fetch any URL requested of it for any iFrame sending the correct message,
    // and will act with the origin of this window (potentially e.g. sending cookies when fetching the URL)
    if (source !== frameRef.current?.contentWindow) {
      return;
    }

    const { payload, requestId } = requestMessage.data;

    // implement memoizedFetch to cache the text by URL, to avoid fetching it for multiple blocks
    memoizedFetch(payload.url)
      .then((resp) => resp.text())
      .then((text) => {
        const responseMessage: TextFromUrlResponseMessage = {
          payload: { data: text },
          requestId,
        };
        requestMessage.source.postMessage(responseMessage, origin);
      });
  }
});

Blocks supported

The component will parse and render blocks which are defined as:

  • React components (i.e. a JavaScript file which exports a React component)
  • Web Components (i.e. a JavaScript file which exports a custom element class)
  • HTML (i.e. an HTML file, which may in turn load other assets)

For JavaScript files, the exported component must be one of:

  1. the default export from the file
  2. the only named export in the file
  3. an export named App

Acknowledgements

The useRemoteBlock hook was adapted from Paciolan/remote-component