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

@prezly/slate-lists

v0.106.0

Published

The best Slate lists extension out there

Downloads

24,148

Readme

@prezly/slate-lists

The best Slate lists extension out there.

Demo: https://veu8mp.csb.app/ (source code).

API inspired by https://github.com/GitbookIO/slate-edit-list.

Version License

Table of contents

Demo

Live: https://ocbkit.csb.app/

Source code: https://codesandbox.io/s/prezly-slate-lists-demo-ocbkit?file=/src/MyEditor.tsx

Features

  • Nested lists
  • Customizable list types (ordered, bulleted, dashed - anything goes)
  • Transformations support multiple list items in selection
  • Normalizations recover from invalid structure (helpful when pasting)
  • Merges sibling lists of same type
  • Range.prototype.cloneContents monkey patch to improve edge cases that occur when copying lists

Constraints

  • There are two types of lists: ordered and unordered. You can initialize the plugin to work with any project-level data model via ListsSchema.

  • There is an assumption that there is a default text node type to which the plugin can convert list-related nodes (e.g. during normalization, or unwrapping lists). Normally, this is a paragraph block, but it's up to you.

Schema

  • a list node can only contain list item nodes

  • a list item node can contain either:

    • a list item text node
    • a pair of list item text node and a list node (in that order) (nesting lists)
  • a list node can either:

    • have no parent node
    • have a parent list item node

Sometimes code can be better than words. Here are example TypeScript interfaces that describe the above schema (some schema rules are not expressible in TypeScript, so please treat it just as a quick overview).

import { Node } from 'slate';

interface ListNode {
    children: ListItemNode[];
    type: 'ordered-list' | 'unordered-list'; // depends on your ListsSchema 
}

interface ListItemNode {
    children: [ListItemTextNode] | [ListItemTextNode, ListNode];
    type: 'list-item'; // depends on your ListsSchema
}

interface ListItemTextNode {
    children: Node[]; // by default everything is allowed here
    type: 'list-item-text'; // depends on your ListsSchema
}

Installation

npm

npm install --save @prezly/slate-lists

yarn

yarn add @prezly/slate-lists

User guide

0. Basic Editor

Let's start with a minimal Slate + React example which we will be adding lists support to. Nothing interesting here just yet.

Live example: https://codesandbox.io/s/prezly-slate-lists-user-guide-0-basic-editor-veu8mp?file=/src/MyEditor.tsx

import { useMemo, useState } from 'react';
import { createEditor, BaseElement, Descendant } from 'slate';
import { withHistory } from 'slate-history';
import { Editable, ReactEditor, RenderElementProps, Slate, withReact } from 'slate-react';

declare module 'slate' {
    interface CustomTypes {
        Element: { type: Type } & BaseElement;
    }
}

enum Type {
    PARAGRAPH = 'paragraph',
}

function renderElement({ element, attributes, children }: RenderElementProps) {
    switch (element.type) {
        case Type.PARAGRAPH:
            return <p {...attributes}>{children}</p>;
    }
}

const initialValue: Descendant[] = [{ type: Type.PARAGRAPH, children: [{ text: 'Hello world!' }] }];

export function MyEditor() {
    const [value, setValue] = useState(initialValue);
    const editor = useMemo(() => withHistory(withReact(createEditor())), []);

    return (
        <Slate editor={editor} value={value} onChange={setValue}>
            <Editable renderElement={renderElement} />
        </Slate>
    );
}

1. Define Lists Model

First, you're going to want to define the model to power the lists functionality.

You'll need at least three additional node types:

  1. List Node
  2. List Item Node
  3. List Item Text Node

Additionally, you may want to split List Node into two types: ordered list and unordered list. Or alternatively, achieve the split with an additional node property (like listNode: ListType).

In this example, for the sake of simplicity, we'll use two different node types:

  1. Ordered List Node
  2. Unordered List Node

Live example: https://codesandbox.io/s/prezly-slate-lists-user-guide-1-list-nodes-model-qyepe4?file=/src/MyEditor.tsx

 import { useMemo, useState } from 'react';
 import { createEditor, BaseElement, Descendant } from 'slate';
 import { withHistory } from 'slate-history';
 import { Editable, ReactEditor, RenderElementProps, Slate, withReact } from 'slate-react';

 declare module 'slate' {
     interface CustomTypes {
         Element: { type: Type } & BaseElement;
     }
 }
 
 enum Type {
     PARAGRAPH = 'paragraph',
+    ORDERED_LIST = 'ordered-list',
+    UNORDERED_LIST = 'unordered-list',
+    LIST_ITEM = 'list-item',
+    LIST_ITEM_TEXT = 'list-item-text',
 }
 
 function renderElement({ element, attributes, children }: RenderElementProps) {
     switch (element.type) {
         case Type.PARAGRAPH:
             return <p {...attributes}>{children}</p>;
+        case Type.ORDERED_LIST:
+            return <ol {...attributes}>{children}</ol>;
+        case Type.UNORDERED_LIST:
+            return <ul {...attributes}>{children}</ul>;
+        case Type.LIST_ITEM:
+            return <li {...attributes}>{children}</li>;
+        case Type.LIST_ITEM_TEXT:
+            return <div {...attributes}>{children}</div>;
     }
 }
 
 const initialValue: Descendant[] = [
     { type: Type.PARAGRAPH, children: [{ text: 'Hello world!' }] },
+    {
+        type: Type.ORDERED_LIST,
+        children: [
+            {
+                type: Type.LIST_ITEM,
+                children: [{ type: Type.LIST_ITEM_TEXT, children: [{ text: 'One' }] }],
+            },
+            {
+                type: Type.LIST_ITEM,
+                children: [{ type: Type.LIST_ITEM_TEXT, children: [{ text: 'Two' }] }],
+            },
+            {
+                type: Type.LIST_ITEM,
+                children: [{ type: Type.LIST_ITEM_TEXT, children: [{ text: 'Three' }] }],
+            },
+        ],
+    },
+    {
+        type: Type.UNORDERED_LIST,
+        children: [
+            {
+                type: Type.LIST_ITEM,
+                children: [{ type: Type.LIST_ITEM_TEXT, children: [{ text: 'Red' }] }],
+            },
+            {
+                type: Type.LIST_ITEM,
+                children: [{ type: Type.LIST_ITEM_TEXT, children: [{ text: 'Green' }] }],
+            },
+            {
+                type: Type.LIST_ITEM,
+                children: [{ type: Type.LIST_ITEM_TEXT, children: [{ text: 'Blue' }] }],
+            },
+        ],
+    },
 ];
 
 export function MyEditor() {
     const [value, setValue] = useState(initialValue);
     const editor = useMemo(() => withHistory(withReact(createEditor())), []);

     return (
         <Slate editor={editor} value={value} onChange={setValue}>
             <Editable renderElement={renderElement} />
         </Slate>
     );
 }

2. Define lists plugin schema and connect withLists plugin to your model.

withLists is a Slate plugin that enables normalizations which enforce schema constraints and recover from unsupported structures.

Live example: https://codesandbox.io/s/prezly-slate-lists-user-guide-2-add-withlists-plugin-r2xscj?file=/src/MyEditor.tsx

 import { useMemo, useState } from 'react';
 import { createEditor, BaseElement, Descendant, Element, Node } from 'slate';
 import { withHistory } from 'slate-history';
 import { Editable, ReactEditor, RenderElementProps, Slate, withReact } from 'slate-react';
+import { ListType, ListsSchema, withLists } from '@prezly/slate-lists';
 
 declare module 'slate' {
     interface CustomTypes {
         Element: { type: Type } & BaseElement;
     }
 }
 
 enum Type {
     PARAGRAPH = 'paragraph',
     ORDERED_LIST = 'ordered-list',
     UNORDERED_LIST = 'unordered-list',
     LIST_ITEM = 'list-item',
     LIST_ITEM_TEXT = 'list-item-text',
 }
 
+const schema: ListsSchema = {
+    isConvertibleToListTextNode(node: Node) {
+        return Element.isElementType(node, Type.PARAGRAPH);
+    },
+    isDefaultTextNode(node: Node) {
+        return Element.isElementType(node, Type.PARAGRAPH);
+    },
+    isListNode(node: Node, type?: ListType) {
+        if (type === ListType.ORDERED) {
+            return Element.isElementType(node, Type.ORDERED);
+        }
+        if (type === ListType.UNORDERED) {
+            return Element.isElementType(node, Type.UNORDERED);
+        }
+        return (
+            Element.isElementType(node, Type.ORDERED_LIST) ||
+            Element.isElementType(node, Type.UNORDERED_LIST)
+        );
+    },
+    isListItemNode(node: Node) {
+        return Element.isElementType(node, Type.LIST_ITEM);
+    },
+    isListItemTextNode(node: Node) {
+        return Element.isElementType(node, Type.LIST_ITEM_TEXT);
+    },
+    createDefaultTextNode(props = {}) {
+        return { children: [{ text: '' }], ...props, type: Type.PARAGRAPH };
+    },
+    createListNode(type: ListType = ListType.UNORDERED, props = {}) {
+        const nodeType = type === ListType.ORDERED ? Type.ORDERED_LIST : Type.UNORDERED_LIST;
+        return { children: [{ text: '' }], ...props, type: nodeType };
+    },
+    createListItemNode(props = {}) {
+        return { children: [{ text: '' }], ...props, type: Type.LIST_ITEM };
+    },
+    createListItemTextNode(props = {}) {
+        return { children: [{ text: '' }], ...props, type: Type.LIST_ITEM_TEXT };
+    },
+};
 
 function renderElement({ element, attributes, children }: RenderElementProps) {
     switch (element.type) {
         case Type.PARAGRAPH:
             return <p {...attributes}>{children}</p>;
         case Type.ORDERED_LIST:
             return <ol {...attributes}>{children}</ol>;
         case Type.UNORDERED_LIST:
             return <ul {...attributes}>{children}</ul>;
         case Type.LIST_ITEM:
             return <li {...attributes}>{children}</li>;
         case Type.LIST_ITEM_TEXT:
             return <div {...attributes}>{children}</div>;
     }
 }
 
 const initialValue: Descendant[] = [
     { type: Type.PARAGRAPH, children: [{ text: 'Hello world!' }] },
     {
         type: Type.ORDERED_LIST,
         children: [
             {
                 type: Type.LIST_ITEM,
                 children: [{ type: Type.LIST_ITEM_TEXT, children: [{ text: 'One' }] }],
             },
             {
                 type: Type.LIST_ITEM,
                 children: [{ type: Type.LIST_ITEM_TEXT, children: [{ text: 'Two' }] }],
             },
             {
                 type: Type.LIST_ITEM,
                 children: [{ type: Type.LIST_ITEM_TEXT, children: [{ text: 'Three' }] }],
             },
         ],
     },
     {
         type: Type.UNORDERED_LIST,
         children: [
             {
                 type: Type.LIST_ITEM,
                 children: [{ type: Type.LIST_ITEM_TEXT, children: [{ text: 'Red' }] }],
             },
             {
                 type: Type.LIST_ITEM,
                 children: [{ type: Type.LIST_ITEM_TEXT, children: [{ text: 'Green' }] }],
             },
             {
                 type: Type.LIST_ITEM,
                 children: [{ type: Type.LIST_ITEM_TEXT, children: [{ text: 'Blue' }] }],
             },
         ],
     },
 ];
 
 export function MyEditor() {
     const [value, setValue] = useState(initialValue);
+    const editor = useMemo(() => withLists(schema)(withHistory(withReact(createEditor()))), []);
 
     return (
         <Slate editor={editor} value={value} onChange={setValue}>
             <Editable renderElement={renderElement} />
         </Slate>
     );
 }

3. Add onKeyDown handler

@prezly/slate-lists comes with a pre-defined onKeyDown handler to implement keyboard interactions for lists. For example, pressing Tab in a list will indent the current list item one level deeper. Pressing Shift+Tab will raise the current list item one level up.

Live example: https://codesandbox.io/s/prezly-slate-lists-user-guide-4-add-onkeydown-handler-5wpqxv?file=/src/MyEditor.tsx

 import { useMemo, useState } from 'react';
 import { createEditor, BaseElement, Descendant, Element, Node } from 'slate';
 import { withHistory } from 'slate-history';
 import { Editable, ReactEditor, RenderElementProps, Slate, withReact } from 'slate-react';
+import { ListType, ListsSchema, onKeyDown, withLists } from '@prezly/slate-lists';
 
 declare module 'slate' {
     interface CustomTypes {
         Element: { type: Type } & BaseElement;
     }
 }
 
 enum Type {
     PARAGRAPH = 'paragraph',
     ORDERED_LIST = 'ordered-list',
     UNORDERED_LIST = 'unordered-list',
     LIST_ITEM = 'list-item',
     LIST_ITEM_TEXT = 'list-item-text',
 }
 
 const schema: ListsSchema = {
     isConvertibleToListTextNode(node: Node) {
         return Element.isElementType(node, Type.PARAGRAPH);
     },
     isDefaultTextNode(node: Node) {
         return Element.isElementType(node, Type.PARAGRAPH);
     },
     isListNode(node: Node, type: ListType) {
         if (type) {
             return Element.isElementType(node, type);
         }
         return (
             Element.isElementType(node, Type.ORDERED_LIST) ||
             Element.isElementType(node, Type.UNORDERED_LIST)
         );
     },
     isListItemNode(node: Node) {
         return Element.isElementType(node, Type.LIST_ITEM);
     },
     isListItemTextNode(node: Node) {
         return Element.isElementType(node, Type.LIST_ITEM_TEXT);
     },
     createDefaultTextNode(props = {}) {
         return { children: [{ text: '' }], ...props, type: Type.PARAGRAPH };
     },
     createListNode(type: ListType = ListType.UNORDERED, props = {}) {
           const nodeType = type === ListType.ORDERED ? Type.ORDERED_LIST : Type.UNORDERED_LIST;
           return { children: [{ text: '' }], ...props, type: nodeType };
     },
     createListItemNode(props = {}) {
         return { children: [{ text: '' }], ...props, type: Type.LIST_ITEM };
     },
     createListItemTextNode(props = {}) {
         return { children: [{ text: '' }], ...props, type: Type.LIST_ITEM_TEXT };
     },
 };
 
 function renderElement({ element, attributes, children }: RenderElementProps) {
     switch (element.type) {
         case Type.PARAGRAPH:
             return <p {...attributes}>{children}</p>;
         case Type.ORDERED_LIST:
             return <ol {...attributes}>{children}</ol>;
         case Type.UNORDERED_LIST:
             return <ul {...attributes}>{children}</ul>;
         case Type.LIST_ITEM:
             return <li {...attributes}>{children}</li>;
         case Type.LIST_ITEM_TEXT:
             return <div {...attributes}>{children}</div>;
         default:
             return <div {...attributes}>{children}</div>;
     }
 }
 
 const initialValue: Descendant[] = [
     { type: Type.PARAGRAPH, children: [{ text: 'Hello world!' }] },
     {
         type: Type.ORDERED_LIST,
         children: [
             {
                 type: Type.LIST_ITEM,
                 children: [{ type: Type.LIST_ITEM_TEXT, children: [{ text: 'One' }] }],
             },
             {
                 type: Type.LIST_ITEM,
                 children: [{ type: Type.LIST_ITEM_TEXT, children: [{ text: 'Two' }] }],
             },
             {
                 type: Type.LIST_ITEM,
                 children: [{ type: Type.LIST_ITEM_TEXT, children: [{ text: 'Three' }] }],
             },
         ],
     },
     {
         type: Type.UNORDERED_LIST,
         children: [
             {
                 type: Type.LIST_ITEM,
                 children: [{ type: Type.LIST_ITEM_TEXT, children: [{ text: 'Red' }] }],
             },
             {
                 type: Type.LIST_ITEM,
                 children: [{ type: Type.LIST_ITEM_TEXT, children: [{ text: 'Green' }] }],
             },
             {
                 type: Type.LIST_ITEM,
                 children: [{ type: Type.LIST_ITEM_TEXT, children: [{ text: 'Blue' }] }],
             },
         ],
     },
 ];
 
 export function MyEditor() {
     const [value, setValue] = useState(initialValue);
     const editor = useMemo(() => withLists(schema)(withHistory(withReact(createEditor()))), []);
 
     return (
         <Slate editor={editor} value={value} onChange={setValue}>
             <Editable
+                onKeyDown={(event) => onKeyDown(editor, event)}
                 renderElement={renderElement}
             />
         </Slate>
     );
 }

Good to go

Now you can use the API exposed on the ListsEditor functions.

Be sure to check the complete usage example.

API

There are JSDocs for all core functionality.

Only core API is documented although all utility functions are exposed. Should you ever need anything beyond the core API, please have a look at src/index.ts to see what's available.

ListsSchema

Lists schema wires the Lists plugin to your project-level defined Slate model. It is designed with 100% customization in mind, not depending on any specific node types, or non-core interfaces.

| Name | Description | |-------------------------------|------------------------------------------------------------------------------------------------------------------------| | isConvertibleToListTextNode | Check if a node can be converted to a list item text node. | | isDefaultTextNode | Check if a node is a plain default text node, that list item text node will become when it is unwrapped or normalized. | | isListNode | Check if a node is representing a list. | | isListItemNode | Check if a node is representing a list item. | | isListItemTextNode | Check if a node is representing a list item text. | | createDefaultTextNode | Create a plain default text node. List item text nodes become these when unwrapped or normalized. | | createListNode | Create a new list node of the given type. | | createListItemNode | Create a new list item node. | | createListItemTextNode | Create a new list item text node. |

withLists

withLists() is an all-in-one plugin initializer. It calls withListsSchema(), withListsReact(), and withListsNormalization() internall.

/**
 * Mutate the Editor instance by adding all lists plugin functionality on top of it.
 */
withLists(schema: ListsSchema) => (<T extends Editor>(editor: T) => T)

withListsSchema

Note: this is already included into withLists().

/**
 * Bind the given ListsSchema to the editor instance.
 * The schema is used by all lists operations.
 */
withListsSchema(schema: ListsSchema) => (<T extends Editor>(editor: T) => T)

withListsNormalization

Note: this is already included into withLists().

/**
 * Enable normalizations that enforce schema constraints and recover from unsupported cases.
 */
withListsNormalization<T extends Editor>(editor: T): T

withListsReact

Note: this is already included into withLists().

/**
 * Enables Range.prototype.cloneContents monkey patch to improve pasting behavior
 * in few edge cases.
 */
withListsReact<T extends ReactEditor>(editor: T): T

ListsEditor

ListsEditor is a namespace export with all list-related editor utility functions. Most of them require an instance of Editor as the first argument.

Warning: all ListsEditor methods expect a ListsSchema to be bound to the editor instance with withLists() function prior to using them.

Here are the functions methods:

/**
 * Check if editor.deleteBackward() is safe to call (it won't break the structure) at the given location 
 * (defaults to the current selection).
 */
isDeleteBackwardAllowed(editor: Editor, at?: Location | null) => boolean

/**
 * Returns true when editor has collapsed selection and the cursor is in an empty "list-item".
 */
isAtEmptyListItem(editor: Editor) => boolean

/**
 * Check if the given location is collapsed and the cursor is at the beginning of a "list-item"
 * (defaults to the current selection).
 */
isAtStartOfListItem(editor: Editor, at?: Location | null) => boolean

/**
 * Check if given "list-item" node contains a non-empty "list-item-text" node.
 */
isListItemContainingText(editor: Editor, node: Node) => boolean

/**
 * Returns all "lists" in a given location (defaults to the current selection).
 */
getLists(editor: Editor, at?: Range | null) => NodeEntry<Node>[]

/**
 * Returns all "list-items" in a given location (defaults to the current selection).
 */
getListItems(editor: Editor, at?: Range | null) => NodeEntry<Node>[]

/**
 * Returns the "type" of a given list node.
 */
getListType(editor: Editor, node: Node) => string

/**
 * Returns "list" node nested in "list-item" at a given path.
 * Returns null if there is no nested "list".
 */
getNestedList(editor: Editor, listItemPath: Path) => NodeEntry<Element> | null

/**
 * Returns parent "list" node of "list-item" at a given path.
 * Returns null if there is no parent "list".
 */
getParentList(editor: Editor, listItemPath: Path) => NodeEntry<Element> | null

/**
 * Returns parent "list-item" node of "list-item" at a given path.
 * Returns null if there is no parent "list-item".
 */
getParentListItem(editor: Editor, listItemPath: Path) => NodeEntry<Element> | null

/**
 * Sets "type" of all "list" nodes in the given location (defaults to the current selection).
 */
setListType(editor: Editor, listType: string, at?: Location | null) => void
    
/**
 * Increases nesting depth of all "list-items" in the given location (defaults to the current selection).
 * All nodes matching options.wrappableTypes in the selection will be converted to "list-items" and wrapped in a "list".
 */
increaseDepth(editor: Editor, at?: Location | null) => void

/**
 * Increases nesting depth of "list-item" at a given Path.
 */
increaseListItemDepth(editor: Editor, listItemPath: Path) => void

/**
 * Decreases nesting depth of all "list-items" in the given location (defaults to the current selection).
 * All "list-items" in the root "list" will become "default" nodes.
 */
decreaseDepth(editor: Editor, at?: Location | null) => void

/**
 * Decreases nesting depth of "list-item" at a given Path.
 */
decreaseListItemDepth(editor: Editor, listItemPath: Path) => void

/**
 * Moves all "list-items" from one "list" to the end of another "list".
 */
moveListItemsToAnotherList(editor: Editor, parameters: { at: NodeEntry<Node>; to: NodeEntry<Node>; }) => void

/**
 * Nests (moves) given "list" in a given "list-item".
 */
moveListToListItem(editor: Editor, parameters: { at: NodeEntry<Node>; to: NodeEntry<Node>; }) => void

/**
 * Collapses the given location (defaults to the current selection) by removing everything in it 
 * and if the cursor ends up in a "list-item" node, it will break that "list-item" into 2 nodes, 
 * splitting the text at the cursor location.
 */
splitListItem(editor: Editor, at?: Location | null) => void

/**
 * Unwraps all "list-items" at the given location (defaults to the current selection).
 * No list be left in the location after this operation.
 */
unwrapList(editor: Editor, at?: Location | null) => void

/**
 * All nodes matching `schema.isConvertibleToListItemText()` at the given location (defaults to the current selection)
 * will be converted to "list-items" and wrapped in "lists".
 */
wrapInList(editor: Editor, listType: ListType, at?: Location | null) => void

Brought to you by Prezly.