3.3.0 ā€¢ Published 5 days ago

@contentful/live-preview v3.3.0

Weekly downloads
-
License
MIT
Repository
github
Last release
5 days ago

@contentful/live-preview

Live preview SDK for both the inspector mode connection + live content updates by Contentful.

Getting started

Requirements

  • Node.js: >=16.15.1

To install live preview simply run one of the following commands.

Installation

yarn add @contentful/live-preview

or

npm install @contentful/live-preview

Initializing the SDK

To establish a communication between your preview frontend and Contentful, you simply need to initialize the live preview SDK. This can be done by executing the following command:

import { ContentfulLivePreview } from '@contentful/live-preview';

...

ContentfulLivePreview.init({ locale: 'en-US'});

Init Configuration

The init command also accepts a configuration object that allows you to customize your live preview SDK experience. The following options are available:

import { ContentfulLivePreview } from '@contentful/live-preview';

...

ContentfulLivePreview.init({
  locale: 'set-your-locale-here', // This is required and allows you to set the locale once and have it reused throughout the preview
  enableInspectorMode: false, // This allows you to toggle the inspector mode which is on by default
  enableLiveUpdates: false, // This allows you to toggle the live updates which is on by default
  debugMode: false, // This allows you to toggle the debug mode which is off by default
});

Overriding Locale

It is possible to override the locale you set in the init command for a more flexible workflow. If you need to override the locale you can do so either in the getProps command like below:

ContentfulLivePreview.getProps({ entryId: id, fieldId: 'title', locale: 'fr' });

You can also override it when using our useContentfulLiveUpdates hook like below:

import { useContentfulLiveUpdates } from '@contentful/live-preview/react';

// ...
const updated = useContentfulLiveUpdates(originalData, { locale });
// ...

Inspector Mode (field tagging)

To use the inspector mode, you need to tag fields by adding the live preview data-attributes (data-contentful-entry-id, data-contentful-field-id) to the rendered HTML element output.

You can do this in React via our helper function.

The necessary styles for the live edit tags can be found in the @contentful/live-preview/style.css file.

import { ContentfulLivePreview } from '@contentful/live-preview';
import '@contentful/live-preview/style.css';
...

<h1 {...ContentfulLivePreview.getProps({ entryId: id, fieldId: 'title' })}>
  {title}
</h1>

Live Updates

Live Updates allow you to make changes in your editor and see the updates in real time. The updates are only happening on the client-side and in the live preview environment of Contentful.

import { useContentfulLiveUpdates } from '@contentful/live-preview/react';

// ...
const updated = useContentfulLiveUpdates(originalData);
// ...

Live updates with GraphQL

For the best experience of live updates together with GraphQL, we recommend to provide your query information to useContentfulLiveUpdates. This will benefit the performance of updates and provides support for GraphQL features (e.g. alias).

import gql from 'graphql-tag';

const query = gql`
  query posts {
    postCollection(where: { slug: "${slug}" }, preview: true, limit: 1) {
      items {
        __typename
        sys {
          id
        }
        slug
        title
        content: description
      }
    }
  }
`;

// ...
const updated = useContentfulLiveUpdates(originalData, { query });
// ...

Example Integrations

Vanilla Javascript

To use the Contentful Live Preview SDK with Javascript, you can use the following steps to add it to an existing project.

  1. Add the @contentful/live-preview package to your project
yarn add @contentful/live-preview

or

npm install @contentful/live-preview
  1. Initialize the SDK with the ContentfulLivePreview class' init function and add the stylesheet for field tagging as a stylesheet link.
<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Live Preview Example</title>
    <link
      rel="stylesheet"
      type="text/css"
      href="./node_modules/@contentful/live-preview/dist/style.css"
    />
    <script type="module">
      import { ContentfulLivePreview } from './node_modules/@contentful/live-preview/dist/index.js';

      ContentfulLivePreview.init({ locale: 'en-US' });
    </script>
  </head>
  <body></body>
</html>
  1. To use the inspector mode, you need to tag fields by adding the live preview data-attributes (data-contentful-entry-id, data-contentful-field-id) to your HTML element output.

You can do this via our helper function.

The necessary styles for the live edit tags can be found in the @contentful/live-preview/style.css file.

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Live Preview Example</title>
    <link
      rel="stylesheet"
      type="text/css"
      href="./node_modules/@contentful/live-preview/dist/style.css"
    />
    <script type="module">
      import { ContentfulLivePreview } from './node_modules/@contentful/live-preview/dist/index.js';

      ContentfulLivePreview.init({ locale: 'en-US' });

      const heading = document.getElementById('demo');

      /*
       * Example response
       *
       * const props = {
       *   'data-contentful-field-id': 'fieldId',
       *   'data-contentful-entry-id': 'entryId',
       *    'data-contentful-locale': 'en-US',
       *   }
       */
      const props = ContentfulLivePreview.getProps({ entryId: id, fieldId: title });

      for (const [key, value] of Object.entries(props)) {
        // change from hyphen to camelCase
        const formattedName = key.split('data-')[1].replace(/-([a-z])/g, function (m, w) {
          return w.toUpperCase();
        });

        heading.dataset[formattedName] = value;
      }
    </script>
  </head>
  <body>
    <h1 id="demo">Title</h1>
  </body>
</html>

4.To use the live updates feature you can make use of the subscribe function to listen to the data changes as shown below:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Live Preview Example</title>
    <link
      rel="stylesheet"
      type="text/css"
      href="./node_modules/@contentful/live-preview/dist/style.css"
    />
    <script type="module">
      import { ContentfulLivePreview } from './node_modules/@contentful/live-preview/dist/index.js';

      const locale = 'en-US';

      ContentfulLivePreview.init({ locale });

      /**
       * Subscribe to data changes from the Editor, returns a function to unsubscribe
       * Will be called once initially for the restored data
       */
      const unsubscribe = ContentfulLivePreview.subscribe({
        data,
        locale,
        callback,
      });
    </script>
  </head>
  <body></body>
</html>

That's it! You should now be able to use the Contentful Live Preview SDK with vanilla JS.

React

Integration with Next.js

You can find an example implementation in the examples/nextjs folder.

To use the Contentful Live Preview SDK with Next.js, you can either use one of the Contentful starter templates, or do the following steps to add it to an existing project.

  1. Add the @contentful/live-preview package to your project
yarn add @contentful/live-preview

or

npm install @contentful/live-preview
  1. Initialize the SDK with the ContentfulLivePreviewProvider and add the stylesheet for field tagging inside _app.tsx or _app.js. The ContentfulLivePreviewProvider accepts the same arguments as the init function.
import '@contentful/live-preview/style.css';
import { ContentfulLivePreviewProvider } from '@contentful/live-preview/react';

const CustomApp = ({ Component, pageProps }) => (
  <ContentfulLivePreviewProvider locale="en-US">
    <Component {...pageProps}>
  </ContentfulLivePreviewProvider>
)

This provides the possibility to only enable live updates and inspector mode inside draft mode:

import '@contentful/live-preview/style.css';
import { ContentfulLivePreviewProvider } from '@contentful/live-preview/react';

const CustomApp = ({ Component, pageProps }) => (
  <ContentfulLivePreviewProvider locale="en-US" enableInspectorMode={pageProps.draftMode} enableLiveUpdates={pageProps.draftMode}>
    <Component {...pageProps}>
  </ContentfulLivePreviewProvider>
)
  1. Add field tagging and live updates to your component
export default function BlogPost: ({ blogPost }) {
  const inspectorProps = useContentfulInspectorMode()
  // Live updates for this component
  const data = useContentfulLiveUpdates(
    blogPost
  );

  return (
    <Section>
      <Heading as="h1">{data.heading}</Heading>
      {/* Text is tagged and can be clicked to open the editor */}
      <Text
        as="p"
        {...inspectorProps({
          entryId: data.sys.id,
          fieldId: 'text',
        })}>
        {data.text}
      </Text>
    </Section>
  );
}

It doesn't matter if the data is loaded with getServerSideProps, getStaticProps or if you load it in any other way.It's necessary that the provided information to useContentfulLiveUpdate contains the sys.id for identification and only non-transformed fields can be updated.(For GraphQL also the __typename needs to be provided)

Tip: If you want to tag multiple fields of an entry, you can also provide initial arguments to the hook:

export default function BlogPost: ({ blogPost }) {
  const inspectorProps = useContentfulInspectorMode({ entryId: data.sys.id })

  return (
    <Section>
      <Heading as="h1" {...inspectorProps({ fieldId: 'heading' })}>{data.heading}</Heading>
      <Text as="p" {...inspectorProps({ fieldId: 'text' })}>
        {data.text}
      </Text>
    </Section>
  )
  1. Enable draft mode

We suggest using the draft mode and the Content Preview API for the best experience.

For a full guide checkout this free course

Due some security settings the draft mode is not always shared with the iframe.You can find a workaround in our examples

  1. In Contentful, configure the draft URL for your Next.js application in the Content preview settings. Once you open an entry with a configured preview URL, you can use the live preview and all its features.

That's it! You should now be able to use the Contentful live preview SDK with Next.js.

Integrating with Gatsby

šŸš§ Gatsby support is currently under development. Inspector mode is already supported, but some fields with live updates might not be working correctly

To use the Contentful live preview SDK with Gatsby, you can start with the gatsby starter contentful homepage

  1. Add the @contentful/live-preview package to your Gatsby project by running one of the following commands:
yarn add @contentful/live-preview

or

npm install @contentful/live-preview
  1. In your gatsby-browser.js file, import the live preview styles and initialize the SDK:
import '@contentful/live-preview/style.css';

import React from 'react';
import { ContentfulLivePreviewProvider } from '@contentful/live-preview/react';

export const wrapRootElement = ({ element }) => (
  <ContentfulLivePreviewProvider locale="en-US">{element}</ContentfulLivePreviewProvider>
);
  1. In order to tag fields and use live updates, you need to add the contentful_id property to the GraphQL schema. For example, to extend the HomepageHero interface:
interface HomepageHero implements Node & HomepageBlock {
  id: ID!
  contentful_id: String! # add this property
  heading: String!
  text: String
}

type ContentfulHomepageHero implements Node & HomepageHero & HomepageBlock @dontInfer {
  id: ID!
  contentful_id: String! # and also here
  heading: String!
  text: String
}
  1. Update the corresponding component to load the contentful_id property:
export const query = graphql`
  fragment HomepageHeroContent on HomepageHero {
    __typename
    id
    contentful_id # add this property
    heading
    text
  }
`;
  1. Add tagging and live updates to your component:
export default function Hero({ contentful_id, ...props }) {
  const inspectorProps = useContentfulInspectorMode();
  // Live updates for this component
  const data = useContentfulLiveUpdates({
    ...props,
    sys: { id: props.contentful_id },
  });

  return (
    <Section>
      <Heading as="h1">{data.heading}</Heading>
      {/* Text is tagged and can be clicked to open the editor */}
      <Text
        as="p"
        {...inspectorProps({
          entryId: contentful_id,
          fieldId: 'text',
        })}>
        {data.text}
      </Text>
    </Section>
  );
}
  1. In Contentful, define the preview environment and configure the preview URL for your Gatsby site. Once you open an entry with a configured preview URL, you can use the live preview and all its features.

That's it! You should now be able to use the Contentful live preview SDK with Gatsby.

Further Examples

For further examples see the ./examples directory.

Documentation

Code of Conduct

We want to provide a safe, inclusive, welcoming, and harassment-free space and experience for all participants, regardless of gender identity and expression, sexual orientation, disability, physical appearance, socioeconomic status, body size, ethnicity, nationality, level of experience, age, religion (or lack thereof), or other identity markers.

Read our full Code of Conduct.

License

The live preview package is open source software licensed as MIT.

3.2.0

5 days ago

3.3.0

5 days ago

3.1.0

10 days ago

3.0.2

13 days ago

3.0.1

16 days ago

3.0.0

23 days ago

3.0.0-alpha.36

23 days ago

3.0.0-alpha.37

23 days ago

3.0.0-alpha.35

26 days ago

3.0.0-alpha.34

1 month ago

2.17.4

1 month ago

3.0.0-alpha.29

1 month ago

3.0.0-alpha.28

1 month ago

3.0.0-alpha.30

1 month ago

3.0.0-alpha.32

1 month ago

3.0.0-alpha.31

1 month ago

3.0.0-alpha.33

1 month ago

3.0.0-alpha.25

2 months ago

3.0.0-alpha.27

2 months ago

3.0.0-alpha.26

2 months ago

3.0.0-alpha.24

2 months ago

3.0.0-alpha.23

2 months ago

3.0.0-alpha.19

2 months ago

3.0.0-alpha.21

2 months ago

3.0.0-alpha.20

2 months ago

3.0.0-alpha.22

2 months ago

3.0.0-alpha.16

2 months ago

3.0.0-alpha.18

2 months ago

3.0.0-alpha.17

2 months ago

3.0.0-alpha.14

2 months ago

3.0.0-alpha.13

2 months ago

3.0.0-alpha.15

2 months ago

3.0.0-alpha.12

2 months ago

3.0.0-alpha.10

2 months ago

3.0.0-alpha.11

2 months ago

3.0.0-alpha.9

3 months ago

3.0.0-alpha.8

3 months ago

3.0.0-alpha.7

3 months ago

3.0.0-alpha.6

3 months ago

3.0.0-alpha.5

3 months ago

3.0.0-alpha.4

3 months ago

3.0.0-alpha.3

3 months ago

2.17.3

3 months ago

2.17.2

3 months ago

2.17.1

3 months ago

2.15.2

3 months ago

3.0.0-alpha.1

3 months ago

3.0.0-alpha.2

3 months ago

2.15.0-alpha.16

3 months ago

2.15.0-alpha.15

3 months ago

2.15.0-alpha.14

4 months ago

2.15.0-alpha.13

4 months ago

2.15.0-alpha.12

4 months ago

2.15.1

4 months ago

2.15.0

4 months ago

2.13.0-alpha.11

4 months ago

2.13.0-alpha.10

4 months ago

2.13.0-alpha.9

4 months ago

2.14.0

5 months ago

2.13.0

5 months ago

2.13.0-alpha.8

5 months ago

2.13.0-alpha.7

5 months ago

2.13.0-alpha.6

5 months ago

2.13.0-alpha.5

5 months ago

2.13.0-alpha.3

5 months ago

2.13.0-alpha.4

5 months ago

2.12.5

5 months ago

2.12.3

5 months ago

2.12.4

5 months ago

2.11.0

7 months ago

2.11.1

7 months ago

2.4.5

10 months ago

2.8.0

9 months ago

2.11.8

6 months ago

2.9.2

8 months ago

2.5.6

9 months ago

2.11.9

6 months ago

2.9.1

8 months ago

2.5.5

9 months ago

2.11.6

6 months ago

2.9.4

8 months ago

2.11.7

6 months ago

2.9.3

8 months ago

2.11.4

7 months ago

2.9.6

8 months ago

2.11.5

6 months ago

2.9.5

8 months ago

2.11.2

7 months ago

2.9.8

7 months ago

2.11.3

7 months ago

2.9.7

7 months ago

2.11.10

6 months ago

2.11.11

6 months ago

2.11.12

6 months ago

2.11.13

6 months ago

2.10.1

7 months ago

2.10.0

7 months ago

2.7.0

9 months ago

2.7.2

9 months ago

2.7.1

9 months ago

2.4.10

10 months ago

2.4.11

10 months ago

2.13.0-alpha.1

5 months ago

2.13.0-alpha.2

5 months ago

2.13.0-alpha.0

5 months ago

2.4.7

10 months ago

2.4.6

10 months ago

2.4.9

10 months ago

2.4.8

10 months ago

2.6.1

9 months ago

2.6.0

9 months ago

2.6.3

9 months ago

2.6.2

9 months ago

2.7.3

9 months ago

2.12.0

5 months ago

2.5.0

10 months ago

2.5.2

10 months ago

2.5.1

10 months ago

2.9.0

8 months ago

2.5.4

9 months ago

2.5.3

10 months ago

2.6.4

9 months ago

2.12.1

5 months ago

2.12.2

5 months ago

2.4.4

10 months ago

2.4.3

10 months ago

2.4.2

10 months ago

1.15.0

12 months ago

1.14.1

12 months ago

1.14.0

12 months ago

1.13.0

1 year ago

1.12.0

1 year ago

1.17.1

12 months ago

1.17.0

12 months ago

1.16.0

12 months ago

2.3.0

11 months ago

2.2.1

11 months ago

2.2.0

11 months ago

2.1.1

12 months ago

2.0.2

12 months ago

2.4.1

11 months ago

2.4.0

11 months ago

2.3.1

11 months ago

2.1.0

12 months ago

2.0.1

12 months ago

2.0.0

12 months ago

1.11.0

1 year ago

1.10.0

1 year ago

1.9.0

1 year ago

1.7.2

1 year ago

1.8.0

1 year ago

1.7.1

1 year ago

1.7.0

1 year ago

1.6.1

1 year ago

1.6.0

1 year ago

1.5.0

1 year ago

1.4.0

1 year ago

1.3.1

1 year ago

1.3.0

1 year ago

1.2.0

1 year ago

1.1.0

1 year ago

1.0.3

1 year ago

1.0.2

1 year ago

1.0.1

1 year ago

1.0.0

1 year ago