### Install Project Dependencies
Source: https://github.com/springload/draftail/blob/main/docs/CONTRIBUTING.md
Commands to set up the local development environment by installing the required Node version and project dependencies.
```bash
nvm install
npm install
touch .env
```
--------------------------------
### Development Workflow Commands
Source: https://github.com/springload/draftail/blob/main/docs/CONTRIBUTING.md
Standard commands for managing the development lifecycle, including starting the server, linting, formatting, and running tests.
```bash
nvm use
npm run start
npm run lint
npm run format
npm run test:watch
npm run test:coverage
npm run report:coverage
npm run report:build
npm run report:size
npm run report:package
npm run
```
--------------------------------
### Update Toolbar Control Descriptions in Draftail
Source: https://github.com/springload/draftail/blob/main/CHANGELOG.md
This example shows how to update Draftail controls to leverage the new 'description' prop for enhanced tooltips, improving accessibility and user experience. It demonstrates adding descriptions to 'Header 3' and 'Bulleted list' controls.
```diff
blockTypes={[
{
type: BLOCK_TYPE.HEADER_THREE,
label: 'H3',
// Use a description to further convey what the control does.
+ description: 'Heading 3',
},
{
type: BLOCK_TYPE.UNORDERED_LIST_ITEM,
// The icon is enough – but use the new prop to help screen reader users.
- label: 'UL',
+ description: 'Bulleted list',
icon: 'icon-list-ul',
},
]}
```
--------------------------------
### Controlled Draftail Editor with State Management
Source: https://context7.com/springload/draftail/llms.txt
Illustrates using Draftail as a controlled component, managing the editor's state externally with React's useState hook. This example includes a word count display that updates in real-time as the user types.
```tsx
import React, { useState } from "react";
import { EditorState, RawDraftContentState } from "draft-js";
import {
DraftailEditor,
BLOCK_TYPE,
INLINE_STYLE,
createEditorStateFromRaw,
serialiseEditorStateToRaw,
} from "draftail";
const ControlledEditor = () => {
const [editorState, setEditorState] = useState(() =>
createEditorStateFromRaw({
blocks: [{ key: "a", text: "Start typing...", type: "unstyled" }],
entityMap: {},
})
);
const handleChange = (newState: EditorState) => {
setEditorState(newState);
// Get raw content for serialization
const rawContent = serialiseEditorStateToRaw(newState);
console.log("Current content:", rawContent);
};
const getWordCount = () => {
const content = editorState.getCurrentContent();
const text = content.getPlainText();
return text.trim().split(/\s+/).filter(Boolean).length;
};
return (
Word count: {getWordCount()}
);
};
```
--------------------------------
### Perform Editor Operations with DraftUtils
Source: https://context7.com/springload/draftail/llms.txt
Provides examples of using the DraftUtils API to manipulate blocks, entities, and selections within the Draft.js editor state. These utilities simplify tasks like resetting block types, updating entity data, and managing newline behavior.
```tsx
import { EditorState, Modifier, RichUtils } from "draft-js";
import { DraftUtils, BLOCK_TYPE, ENTITY_TYPE } from "draftail";
const editorState = /* your editor state */;
const selectedBlock = DraftUtils.getSelectedBlock(editorState);
const entityKey = DraftUtils.getSelectionEntity(editorState);
const entitySelection = DraftUtils.getEntitySelection(editorState, entityKey);
const newState = DraftUtils.resetBlockWithType(editorState, BLOCK_TYPE.HEADER_TWO, "New heading text");
const updatedState = DraftUtils.updateBlockEntity(editorState, blockWithEntity, { src: "new-image.jpg", alt: "Updated alt text" });
const stateWithHR = DraftUtils.addHorizontalRuleRemovingSelection(editorState);
const stateWithBR = DraftUtils.addLineBreak(editorState);
const stateWithoutBlock = DraftUtils.removeBlock(editorState, blockKey);
const stateWithoutEntity = DraftUtils.removeBlockEntity(editorState, entityKey, blockKey);
const newLineState = DraftUtils.handleNewLine(editorState, keyboardEvent);
const linkStrategy = DraftUtils.getEntityTypeStrategy(ENTITY_TYPE.LINK);
```
--------------------------------
### Project Release and Distribution
Source: https://github.com/springload/draftail/blob/main/docs/CONTRIBUTING.md
Commands used to build the distribution files, verify package size, and publish the package to the registry.
```bash
npm run dist
npm run report:size
npm run report:package
npm publish
```
--------------------------------
### Integrate draft-js-plugins with Draftail
Source: https://context7.com/springload/draftail/llms.txt
Demonstrates how to initialize plugins like hashtag, linkify, and emoji, and pass them to the DraftailEditor component. This enables advanced text features and requires importing corresponding CSS files.
```tsx
import React from "react";
import { DraftailEditor, BLOCK_TYPE, INLINE_STYLE } from "draftail";
import createHashtagPlugin from "draft-js-hashtag-plugin";
import createLinkifyPlugin from "draft-js-linkify-plugin";
import createEmojiPlugin from "draft-js-emoji-plugin";
import "draft-js-hashtag-plugin/lib/plugin.css";
import "draft-js-linkify-plugin/lib/plugin.css";
import "draft-js-emoji-plugin/lib/plugin.css";
const hashtagPlugin = createHashtagPlugin();
const linkifyPlugin = createLinkifyPlugin({
target: "_blank",
rel: "noopener noreferrer",
});
const emojiPlugin = createEmojiPlugin();
const { EmojiSuggestions, EmojiSelect } = emojiPlugin;
const EditorWithPlugins = () => (
);
```
--------------------------------
### Configure Draftail Command Palette
Source: https://context7.com/springload/draftail/llms.txt
Demonstrates how to enable and customize the slash-command palette in the DraftailEditor component. It includes configuration for block types, entity types, and custom actions like clearing content or inserting dynamic data.
```tsx
import React from "react";
import { DraftailEditor, DraftUtils, BLOCK_TYPE, ENTITY_TYPE } from "draftail";
const EditorWithCommandPalette = () => (
EditorState.createEmpty(),
},
{
type: "insert-date",
description: "Insert current date",
onSelect: ({ editorState }) => {
const date = new Date().toLocaleDateString();
const block = DraftUtils.getSelectedBlock(editorState);
return DraftUtils.resetBlockWithType(editorState, block.getType(), date);
},
},
],
},
]}
/>
);
```
--------------------------------
### Draftail: Customize Toolbar with Custom Controls
Source: https://context7.com/springload/draftail/llms.txt
Illustrates how to customize Draftail's toolbar by adding custom controls like a word counter and a 'clear formatting' button. It shows how to integrate these controls into different toolbar types (inline, block, meta) and configure custom toolbar layouts.
```tsx
import React from "react";
import {
DraftailEditor,
Toolbar,
FloatingToolbar,
BlockToolbar,
MetaToolbar,
InlineToolbar,
ToolbarButton,
BLOCK_TYPE,
INLINE_STYLE,
} from "draftail";
// Custom word count control for meta toolbar
const WordCount = ({ getEditorState }) => {
const editorState = getEditorState();
const content = editorState.getCurrentContent();
const text = content.getPlainText();
const words = text.trim().split(/\s+/).filter(Boolean).length;
const chars = text.length;
return (
{words} words | {chars} characters
);
};
// Custom formatting control
const CustomControl = ({ getEditorState, onChange }) => {
const clearFormatting = () => {
const editorState = getEditorState();
// Clear all inline styles from selection
let newState = editorState;
const styles = ["BOLD", "ITALIC", "UNDERLINE", "STRIKETHROUGH", "CODE"];
styles.forEach((style) => {
const currentStyle = newState.getCurrentInlineStyle();
if (currentStyle.has(style)) {
newState = RichUtils.toggleInlineStyle(newState, style);
}
});
onChange(newState);
};
return (
);
};
// Editor with custom toolbar configuration
const EditorWithCustomToolbars = () => (
(
<>
>
)}
bottomToolbar={MetaToolbar}
enableHorizontalRule
/>
);
// Editor with floating toolbar only
const MinimalEditor = () => (
);
```
--------------------------------
### Set Location with JavaScript
Source: https://github.com/springload/draftail/blob/main/public/index.html
This snippet demonstrates how to set the current location using JavaScript. It's a simple assignment that can be used to redirect the user or update the browser's URL.
```javascript
location = "https://www.draftail.org/";
```
--------------------------------
### Implement Block-Level Image Entities in Draftail
Source: https://context7.com/springload/draftail/llms.txt
This snippet demonstrates how to create a custom ImageSource component for selecting files and an ImageBlock component for rendering and editing images within the editor. It uses Draftail's entity system to manage atomic blocks.
```tsx
import React, { Component } from "react";
import { DraftailEditor, DraftUtils, ENTITY_TYPE } from "draftail";
class ImageSource extends Component {
onSelectImage = (e) => {
const { editorState, entityType, onComplete } = this.props;
const file = e.target.files[0];
if (!file) {
this.props.onClose();
return;
}
const reader = new FileReader();
reader.onload = (event) => {
const content = editorState.getCurrentContent();
const contentWithEntity = content.createEntity(
entityType.type,
"IMMUTABLE",
{ src: event.target.result, alt: file.name }
);
const entityKey = contentWithEntity.getLastCreatedEntityKey();
const nextState = AtomicBlockUtils.insertAtomicBlock(
EditorState.set(editorState, { currentContent: contentWithEntity }),
entityKey,
" "
);
onComplete(nextState);
};
reader.readAsDataURL(file);
};
render() {
return (