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

payload-visual-editor

v2.0.6

Published

Payload CMS plugin which provides a visual live editor directly in the Admin UI.

Downloads

1,305

Readme

Payload Visual Editor Plugin

Note This plugin provides a visual live preview, including a nice UI, for Payload

Version 0.x.x is compatible with Payload 1.x.x
Version 2.x.x is compatible with Payload 2.x.x

Core features:

  • Adds a visual editor component to your collections and globals:
    • Creates the visual editor UI in the Admin UIs edit view
    • Handles the live data exchange with your frontend

image

Installation

  yarn add payload-visual-editor
  # OR
  npm i payload-visual-editor

Basic Usage

In the plugins array of your Payload config, call the plugin with options:

// import plugin
import { visualEditor } from "payload-visual-editor";

// import styles
import "payload-visual-editor/dist/styles.scss";

const config = buildConfig({
  collections: [...],
  plugins: [
    visualEditor({
      previewUrl: () => `http://localhost:3001/pages/preview`,
      previewWidthInPercentage: 60,
      collections: {
        [COLLECTION_SLUG]: {
          previewUrl: () => `...` // optional individual preview url for each collection
        },
      },
      globals: {
        [GLOBAL_SLUG]: {
          previewUrl: () => `...` // optional individual preview url for each global
        },
      },
    }),
  ],
});

Options

  • previewUrl : ({ locale: string; }) => string | mandatory

    A function returning a string of the URL to your frontend preview route (e.g. https://localhost:3001/pages/preview). The locale property can be used if needed for preview localization.

  • defaultPreviewMode : "iframe" | "popup" | "none"

    Preferred preview mode while opening an edit page the first time. After toggling, the state will be saved in localStore. Default: "iframe"

  • previewWidthInPercentage : number

    Width of the iframe preview in percentage. Default: 50

  • collections / globals : Record<string, { previewUrl?: ({ locale: string; }) => string; }>

    An object with configs for all collections / globals which should enable the live preview. Use the collection / global slug as the key. If you don't want to override the previewUrl, just pass an empty object.

Localization

If you are using Localization with multiple locales, it can be very handy, to be able to adjust the preview URL based on the selected/current locale. You can pass locale to the previewUrl function in your payload config an place it, where your frontend needs it to be:

const config = buildConfig({
  collections: [...],
  plugins: [
    visualEditor({
      previewUrl: params => `https://localhost:3001/${params.locale}/pages/preview`
      ...
    }),
  ],
});

Relation Fallbacks

When adding blocks or editing relationship / upload fields, you will often encounter the issue that the data is incomplete. For instance, because no relation has been selected yet. However, when such fields are marked as required and there is no check for undefined values in the frontend, it can lead to unexpected errors in the rendering process.
To address this problem, fallbacks can be set up for the collections / globals. In cases where a field is required but no value has been selected, the fallback of the respective collection will be returned.

import { CollectionWithFallbackConfig } from "payload-visual-editor";

export const Tags: CollectionWithFallbackConfig<Tag> = {
    slug: "tags",
    fields: [
        {
            name: "name",
            type: "text",
            required: true,
        },
    ],
    custom: {
        fallback: {
            id: "",
            name: "Fallback Tag",
            createdAt: "",
            updatedAt: "",
        },
    },
};

Frontend Integration in React / Next.js

In the next.js route which will handle your life preview use this code snippet to get the live post data of your collection directly from payload. In this case it"s a collection with he name page.

const [page, setPage] = useState<Page | null>(null);

useEffect(() => {
    const listener = (event: MessageEvent) => {
        if (event.data.cmsLivePreviewData) {
            setPage(event.data.cmsLivePreviewData);
        }
    };

    window.addEventListener("message", listener, false);

    return () => {
        window.removeEventListener("message", listener);
    };
}, []);

You can now pass this to your render function and you can use all your payload collection data in there. For example like this:

return (
    <div>
        <header>
            <h1>{page.title}</h1>
        </header>
        <main>
            <RenderBlocks blocks={page.content} />
        </main>
    </div>
);

Since the document will only be send to the frontend after a field has been changed the preview page wouldn"t show any data on first render. To inform the cms to send the current document state to the frontend, send a ready message to the parent window, as soon as the DOM / react app is ready:

// react
useEffect(() => {
    (opener ?? parent).postMessage("ready", "*");
}, []);

// vanilla js
window.addEventListener("DOMContentLoaded", () => {
    (opener ?? parent).postMessage("ready", "*");
});

Development

This repo includes a demo project with payload as the backend and a simple website written in plain TypeScript. To start the demo, follow these steps:

  1. Start docker and wait until the containers are up:
docker-compose up
  1. Open another terminal and install root dependencies:
yarn docker:plugin:yarn
  1. Install dependencies of the payload example:
yarn docker:example:cms:yarn
  1. Run the payload dev server:
yarn docker:example:cms:dev
  1. Open another terminal and install dependencies of the frontend example:
yarn docker:example:website:yarn
  1. Start the dev server for the frontend:
yarn docker:example:website:dev
  • After changing collections, fields, etc., you can use yarn docker:example:cms:generate-types to create an updated interface file.
  • To connect with the node container, run yarn docker:shell.
  • To connect with the database container, run yarn docker:mongo.