prosemirror-link-preview
v2.0.11
Published
prosemirror-link-preview adds link preview node to your editor
Downloads
89
Readme
prosemirror-link-preview
Features
The ProseMirror-Link-Preview plugin offers several key features that enhance the user experience while editing:
Dynamic Link Previews: Whenever a valid URL is pasted into a ProseMirror document, the plugin automatically calls your callback function, which is one of the plugin's parameter, which fetches the necessary metadata, and the plugin renders a preview, providing a quick glimpse into the content behind the link.
Rich Preview Styles: The link previews generated by the plugin are visually appealing, making it easier to differentiate between regular text and linked content. The preview includes information such as the title, description, and an image associated with the link, where available.
Configurable Behavior: The plugin provides configuration options, allowing users to customize the behavior and appearance of link previews according to their specific needs. From adjusting the preview size to defining custom CSS styles, the plugin offers flexibility to match the desired editing environment.
How to use?
Installation: Install the plugin from your preferred package manager. For example, using npm, run the following command:
npm i -S prosemirror-link-preview
Import: Import the plugin into your project. You also need to import some utility functions from the plugin to help with the configuration process.
import { previewPlugin, addPreviewNode, apply, // for plain prosemirror createDecorations, // for plain prosemirror findPlaceholder, // for plain prosemirror applyYjs, // for yjs users createDecorationsYjs, // for yjs users findPlaceholderYjs, // for yjs users IDefaultoptions, } from "prosemirror-link-preview";
Import the CSS file for your setup. You can use your custom css to style the preview, here is an example(which is the actual css used by default)
import "prosemirror-link-preview/dist/styles/styles.css";
basic card structure
<div className="preview-root"> <div className="preview-image" /> <div className="preview-title" /> <div className="preview-description" /> </div>
Update nodes in the ProseMirror schema to have all the necessary properties with
addPreviewNode
const mySchema = new Schema({ nodes: addPreviewNode(schema.spec.nodes), marks: schema.spec.marks, });
Initialize the editor with the plugin
const v = new EditorView(document.querySelector("#editor") as HTMLElement, { state: EditorState.create({ doc: DOMParser.fromSchema(mySchema).parse(document.createElement("div")), plugins: [ ...exampleSetup({ schema: mySchema }), ySyncPlugin(yXmlFragment), yUndoPlugin(), previewPlugin( async (link: string) => { const data = await fetch("/api/link-preview", { method: "POST", body: JSON.stringify({ link, }), }); const { data: { url, title, description, images }, } = await data.json(); return { url, title, description, images }; }, applyYjs, createDecorationsYjs, findPlaceholderYjs {openLinkOnClick: true} as IDefaultoptions ), ], }), });
previewPlugin
requires 5 parameters:fetchLinkPreview
:(link: string) => Promise<{url: string, title: string, description: string, images: string[]}>
a function that takes a link and returns aPromise
that resolves to the link preview data, you can easily do this using next.js API routes or just usinglink-preview-js
library on your custom backendimport type { NextApiRequest, NextApiResponse } from "next"; import Cors from "cors"; import { getLinkPreview } from "link-preview-js"; // Initializing the cors middleware // You can read more about the available options here: https://github.com/expressjs/cors#configuration-options const cors = Cors({ methods: ["POST", "GET", "HEAD"], }); // Helper method to wait for a middleware to execute before continuing // And to throw an error when an error happens in a middleware function runMiddleware( req: NextApiRequest, res: NextApiResponse, fn: Function ) { return new Promise((resolve, reject) => { fn(req, res, (result: any) => { if (result instanceof Error) { return reject(result); } return resolve(result); }); }); } export default async function handler( req: NextApiRequest, res: NextApiResponse ) { // Run the middleware await runMiddleware(req, res, cors); const { link } = JSON.parse(req.body); console.log({ link }); const data = await getLinkPreview(link); // Rest of the API logic res.json({ data }); }
apply
: import fromprosemirror-link-preview
createDecorations
: import fromprosemirror-link-preview
findPlaceholder
: import fromprosemirror-link-preview
defaultOptions
:export interface IDefaultOptions { openLinkOnClick: boolean; // if true, onClick opens the original link in a new browser tab }
Fetching preview data
this does not happen automatically, you need to handle it yourself by providing the fetchLinkPreview
callback function
- this usually requires a backend using a 3rd party library like
link-preview-js
- you can use
linkpreview.net
API endpoint to fetch your preview data from the frontend - in case you are using nextjs, you can easily use our example above
- or any other tool you see fit