### Install and Run TeX Editor Example
Source: https://github.com/facebook/draft-js/blob/main/examples/draft-0-10-0/tex/readme.md
Follow these commands to install dependencies and start the TeX editor example server. This will launch a local development server for the example.
```bash
yarn
cd examples/draft-0-10-0/tex
yarn
yarn start
```
--------------------------------
### Start Styleguidist Server
Source: https://github.com/facebook/draft-js/blob/main/examples/draft-0-10-0/playground/README.md
Run the Styleguidist development server using the npm script defined in package.json. This command will launch the style guide in your browser.
```sh
npm run styleguide
```
--------------------------------
### Install Dependencies for Universal Rendering Demo
Source: https://github.com/facebook/draft-js/blob/main/examples/draft-0-10-0/universal/readme.md
Install Draft.js and the demo's dependencies to set up the universal rendering example.
```bash
# in draft-js folder
yarn
pushd examples/draft-0-10-0/universal
yarn
```
--------------------------------
### Global Test Setup with src/setupTests.js
Source: https://github.com/facebook/draft-js/blob/main/examples/draft-0-10-0/playground/README.md
Example of a global test setup file (`src/setupTests.js`) that mocks browser APIs like `localStorage`. This file runs automatically before all tests.
```javascript
const localStorageMock = {
getItem: jest.fn(),
setItem: jest.fn(),
clear: jest.fn()
};
global.localStorage = localStorageMock
```
--------------------------------
### Start Local Development Server
Source: https://github.com/facebook/draft-js/blob/main/website/README.md
Starts a local development server for live previewing changes. Changes are reflected without server restarts.
```bash
yarn start
```
--------------------------------
### Install Project Dependencies
Source: https://github.com/facebook/draft-js/blob/main/website/README.md
Run this command to install all necessary project dependencies using Yarn.
```bash
yarn
```
--------------------------------
### Install Draft.js with npm
Source: https://github.com/facebook/draft-js/blob/main/README.md
Install Draft.js along with its React dependencies using npm. Ensure React and React DOM are also installed.
```bash
npm install --save draft-js react react-dom
```
--------------------------------
### Node.js Express Server for Static Files
Source: https://github.com/facebook/draft-js/blob/main/examples/draft-0-10-0/playground/README.md
A programmatic example using Node.js and Express to serve a Create React App build. This setup handles static file serving and directs all requests to index.html for client-side routing.
```javascript
const express = require('express');
const path = require('path');
const app = express();
app.use(express.static(path.join(__dirname, 'build')));
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
app.listen(9000);
```
--------------------------------
### Configure Web App Manifest for Start URL
Source: https://github.com/facebook/draft-js/blob/main/examples/draft-0-10-0/playground/README.md
Modify the web app manifest's start_url to '.' to ensure the app is served from the root path, compatible with client-side routers when installed to the homescreen.
```json
"start_url": ".",
```
--------------------------------
### Install Draft.js with Yarn
Source: https://github.com/facebook/draft-js/blob/main/README.md
Install Draft.js along with its React dependencies using Yarn. Ensure React and React DOM are also installed.
```bash
yarn add draft-js react react-dom
```
--------------------------------
### Deploy to Now
Source: https://github.com/facebook/draft-js/blob/main/examples/draft-0-10-0/playground/README.md
Install the 'now' CLI, build your app, navigate to the build directory, and run the 'now' command.
```sh
npm install -g now
npm run build
cd build
now --name your-project-name
```
--------------------------------
### Install and Run Serve for Static Deployment
Source: https://github.com/facebook/draft-js/blob/main/examples/draft-0-10-0/playground/README.md
Install the 'serve' package globally to deploy your Create React App production build. The '-s' flag indicates a static site, and the port can be specified with '-p'.
```sh
npm install -g serve
serve -s build
```
--------------------------------
### Install Dependencies with Yarn
Source: https://github.com/facebook/draft-js/blob/main/examples/draft-0-10-0/playground/README.md
Alternative installation command using Yarn for managing project dependencies. This achieves the same outcome as the npm installation.
```sh
yarn add husky lint-staged prettier
```
--------------------------------
### Rendering the Link Editor Example
Source: https://github.com/facebook/draft-js/blob/main/examples/draft-0-10-0/link/link.html
Initializes and renders the LinkEditorExample component into the DOM.
```javascript
ReactDOM.render(
,
document.getElementById('target')
);
```
--------------------------------
### Install jest-enzyme
Source: https://github.com/facebook/draft-js/blob/main/examples/draft-0-10-0/playground/README.md
Commands to install the `jest-enzyme` package using npm or yarn.
```sh
npm install --save jest-enzyme
```
```sh
yarn add jest-enzyme
```
--------------------------------
### Add Styleguidist Scripts to package.json
Source: https://github.com/facebook/draft-js/blob/main/examples/draft-0-10-0/playground/README.md
Integrate Styleguidist commands into your project's package.json scripts for easy execution. This allows you to start the Styleguidist server and build the style guide.
```diff
"scripts": {
+ "styleguide": "styleguidist server",
+ "styleguide:build": "styleguidist build",
"start": "react-scripts start",
```
--------------------------------
### Using jest-enzyme Matchers
Source: https://github.com/facebook/draft-js/blob/main/examples/draft-0-10-0/playground/README.md
Shows how to use the `jest-enzyme` library for more concise assertions with React components. Install `jest-enzyme` and import it in your test setup.
```javascript
expect(wrapper).toContainReact(welcome)
```
--------------------------------
### Install React Styleguidist
Source: https://github.com/facebook/draft-js/blob/main/examples/draft-0-10-0/playground/README.md
Add React Styleguidist as a project dependency using npm or yarn. This tool helps create a style guide and develop components in isolation.
```sh
npm install --save react-styleguidist
```
```sh
yarn add react-styleguidist
```
--------------------------------
### Install Husky, Lint-Staged, and Prettier
Source: https://github.com/facebook/draft-js/blob/main/examples/draft-0-10-0/playground/README.md
Install these npm packages to enable Git hooks for code formatting. These tools ensure code style consistency before commits.
```sh
npm install --save husky lint-staged prettier
```
--------------------------------
### Deploy to Netlify CDN
Source: https://github.com/facebook/draft-js/blob/main/examples/draft-0-10-0/playground/README.md
Install the Netlify CLI and deploy your build. Choose 'build' as the deployment path.
```sh
npm install netlify-cli
netlify deploy
```
--------------------------------
### Install Source Map Explorer
Source: https://github.com/facebook/draft-js/blob/main/examples/draft-0-10-0/playground/README.md
Install the source-map-explorer package to analyze JavaScript bundle sizes. This can be done using npm or yarn.
```sh
npm install --save source-map-explorer
```
```sh
yarn add source-map-explorer
```
--------------------------------
### Install node-sass-chokidar
Source: https://github.com/facebook/draft-js/blob/main/examples/draft-0-10-0/playground/README.md
Install the command-line interface for Sass. This package is recommended over `node-sass` due to performance and file detection improvements.
```sh
npm install --save node-sass-chokidar
```
--------------------------------
### Render Editor Example
Source: https://github.com/facebook/draft-js/blob/main/examples/draft-0-10-0/rich/rich.html
Mounts the RichEditorExample component into the DOM.
```javascript
ReactDOM.render( , document.getElementById('target') );
```
--------------------------------
### Install npm-run-all with Yarn
Source: https://github.com/facebook/draft-js/blob/main/examples/draft-0-10-0/playground/README.md
Alternatively, install `npm-run-all` using Yarn. This package helps in orchestrating multiple npm scripts.
```sh
yarn add npm-run-all
```
--------------------------------
### Get Block Type by Key
Source: https://github.com/facebook/draft-js/blob/main/docs/APIReference-ContentState.md
Example demonstrating how to get the type of a selected block using getBlockForKey. This is useful for conditional rendering or logic based on block types.
```javascript
var {editorState} = this.state;
var startKey = editorState.getSelection().getStartKey();
var selectedBlockType = editorState
.getCurrentContent()
.getBlockForKey(startKey)
.getType();
```
--------------------------------
### Example Fetch Request
Source: https://github.com/facebook/draft-js/blob/main/examples/draft-0-10-0/playground/README.md
When the proxy is configured, requests like this will be automatically forwarded to the backend server during development.
```javascript
fetch('/api/todos')
```
--------------------------------
### Rendering the Media Editor Example
Source: https://github.com/facebook/draft-js/blob/main/examples/draft-0-10-0/media/media.html
Initializes and renders the MediaEditorExample React component into the DOM element with the ID 'target'.
```javascript
ReactDOM.render( , document.getElementById('target') );
```
--------------------------------
### Install node-sass-chokidar with Yarn
Source: https://github.com/facebook/draft-js/blob/main/examples/draft-0-10-0/playground/README.md
Alternatively, install the Sass CLI using Yarn. This provides the same functionality as the npm installation.
```sh
yarn add node-sass-chokidar
```
--------------------------------
### Install Draft.js with npm or yarn
Source: https://github.com/facebook/draft-js/blob/main/docs/Overview.md
Use npm or yarn to install Draft.js along with its React dependencies. Consider installing a polyfill like babel-polyfill or es6-shim if targeting older browsers or environments lacking modern ECMAScript features.
```sh
npm install draft-js react react-dom
# or alternately
yarn add draft-js react react-dom
```
```sh
npm install draft-js react react-dom babel-polyfill
# or
yarn add draft-js react react-dom es6-shim
```
--------------------------------
### Install npm-run-all
Source: https://github.com/facebook/draft-js/blob/main/examples/draft-0-10-0/playground/README.md
Install `npm-run-all` to manage multiple npm scripts concurrently. This package is useful for running build and watch tasks in parallel.
```sh
npm install --save npm-run-all
```
--------------------------------
### create
Source: https://github.com/facebook/draft-js/blob/main/docs/APIReference-EditorState.md
Creates a new EditorState based on a configuration object for custom setups.
```APIDOC
## create config: EditorStateCreationConfig
### Description
Returns a new `EditorState` object based on a configuration object. Use this if you need custom configuration not available via the methods above.
### Parameters
#### Path Parameters
- **config** (EditorStateCreationConfig) - Required - The configuration object for creating the editor state.
```
--------------------------------
### Install gh-pages Package
Source: https://github.com/facebook/draft-js/blob/main/examples/draft-0-10-0/playground/README.md
This command installs the `gh-pages` package, which is a utility for deploying static sites to GitHub Pages. It can be installed using either npm or yarn.
```sh
npm install --save gh-pages
```
```sh
yarn add gh-pages
```
--------------------------------
### Install Enzyme with npm
Source: https://github.com/facebook/draft-js/blob/main/examples/draft-0-10-0/playground/README.md
Installs Enzyme and the necessary adapter for React 16 using npm. This is required for shallow rendering component tests.
```sh
npm install --save enzyme enzyme-adapter-react-16 react-test-renderer
```
--------------------------------
### Install Enzyme with yarn
Source: https://github.com/facebook/draft-js/blob/main/examples/draft-0-10-0/playground/README.md
Installs Enzyme and the necessary adapter for React 16 using yarn. This is required for shallow rendering component tests.
```sh
yarn add enzyme enzyme-adapter-react-16 react-test-renderer
```
--------------------------------
### Regex Strategies for Handles and Hashtags
Source: https://github.com/facebook/draft-js/blob/main/docs/Advanced-Topics-Decorators.md
Provides example strategy functions that use regular expressions to find occurrences of @-handles and #hashtags within a content block. These functions call a callback with the start and end indices of each match.
```javascript
// Note: these aren't very good regexes, don't use them!
const HANDLE_REGEX = /\@[\\w]+/g;
const HASHTAG_REGEX = /\#[\\w\u0590-\u05ff]+/g;
function handleStrategy(contentBlock, callback, contentState) {
findWithRegex(HANDLE_REGEX, contentBlock, callback);
}
function hashtagStrategy(contentBlock, callback, contentState) {
findWithRegex(HASHTAG_REGEX, contentBlock, callback);
}
function findWithRegex(regex, contentBlock, callback) {
const text = contentBlock.getText();
let matchArr, start;
while ((matchArr = regex.exec(text)) !== null) {
start = matchArr.index;
callback(start, start + matchArr[0].length);
}
}
```
--------------------------------
### Install React Bootstrap and Bootstrap (npm)
Source: https://github.com/facebook/draft-js/blob/main/examples/draft-0-10-0/playground/README.md
Installs React Bootstrap and Bootstrap version 3 using npm. This is a prerequisite for using React Bootstrap components.
```sh
npm install --save react-bootstrap bootstrap@3
```
--------------------------------
### Build Draft.js from Source
Source: https://github.com/facebook/draft-js/blob/main/README.md
Clone the Draft.js repository and build the library locally using Yarn. This is a prerequisite for running the examples.
```bash
git clone https://github.com/facebook/draft-js.git
cd draft-js
yarn install
yarn run build
```
--------------------------------
### Enable HTTPS in Development (Windows)
Source: https://github.com/facebook/draft-js/blob/main/examples/draft-0-10-0/playground/README.md
Start the development server with HTTPS enabled on Windows by setting the HTTPS environment variable to true in cmd.exe.
```bash
set HTTPS=true&&npm start
```
--------------------------------
### Install Yarn Dependency
Source: https://github.com/facebook/draft-js/blob/main/examples/draft-0-10-0/playground/README.md
Use this command to install a new dependency using yarn. This is an alternative to npm for managing project packages.
```sh
yarn add react-router
```
--------------------------------
### Install Storybook CLI Globally
Source: https://github.com/facebook/draft-js/blob/main/examples/draft-0-10-0/playground/README.md
Install the Storybook command-line interface globally to manage Storybook projects. This is the first step to integrating Storybook into your React application.
```sh
npm install -g @storybook/cli
```
--------------------------------
### Install npm Dependency
Source: https://github.com/facebook/draft-js/blob/main/examples/draft-0-10-0/playground/README.md
Use this command to install a new dependency using npm. This is useful for adding libraries like React Router to your project.
```sh
npm install --save react-router
```
--------------------------------
### Install React Bootstrap and Bootstrap (yarn)
Source: https://github.com/facebook/draft-js/blob/main/examples/draft-0-10-0/playground/README.md
Installs React Bootstrap and Bootstrap version 3 using yarn. This is an alternative to npm for managing project dependencies.
```sh
yarn add react-bootstrap bootstrap@3
```
--------------------------------
### Manually Format Project with Prettier
Source: https://github.com/facebook/draft-js/blob/main/examples/draft-0-10-0/playground/README.md
Execute this command to format your entire project using Prettier. This is useful for initial setup or when you need to format all files at once.
```sh
./node_modules/.bin/prettier --single-quote --write "src/**/*.{js,jsx}"
```
--------------------------------
### Enable HTTPS in Development (Linux/macOS)
Source: https://github.com/facebook/draft-js/blob/main/examples/draft-0-10-0/playground/README.md
Start the development server with HTTPS enabled on Linux or macOS by setting the HTTPS environment variable to true in Bash.
```bash
HTTPS=true npm start
```
--------------------------------
### Get Start Offset of Selection
Source: https://github.com/facebook/draft-js/blob/main/docs/APIReference-SelectionState.md
Returns the block-level character offset of the start position of the selection range.
```javascript
getStartOffset(): number
```
--------------------------------
### Configure Enzyme Adapter
Source: https://github.com/facebook/draft-js/blob/main/examples/draft-0-10-0/playground/README.md
Sets up the Enzyme adapter for React 16. This is typically done once in your test setup file.
```javascript
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
configure({ adapter: new Adapter() });
```
--------------------------------
### Get Start Key of Selection
Source: https://github.com/facebook/draft-js/blob/main/docs/APIReference-SelectionState.md
Returns the key of the block containing the start position of the selection range.
```javascript
getStartKey(): string
```
--------------------------------
### Serve Command Help
Source: https://github.com/facebook/draft-js/blob/main/examples/draft-0-10-0/playground/README.md
Display all available options and flags for the 'serve' command by running 'serve -h'.
```sh
serve -h
```
--------------------------------
### Initialize Storybook in Project
Source: https://github.com/facebook/draft-js/blob/main/examples/draft-0-10-0/playground/README.md
Run this command within your app's directory to automatically set up Storybook. Follow the on-screen prompts for configuration.
```sh
getstorybook
```
--------------------------------
### Extracting Selected Text using SelectionState
Source: https://github.com/facebook/draft-js/blob/main/docs/APIReference-SelectionState.md
This example demonstrates how to extract selected text from a ContentBlock using the start and end offsets derived from a SelectionState. It's useful for content manipulation operations where selection direction is irrelevant.
```javascript
var selectionState = editorState.getSelection();
var anchorKey = selectionState.getAnchorKey();
var currentContent = editorState.getCurrentContent();
var currentContentBlock = currentContent.getBlockForKey(anchorKey);
var start = selectionState.getStartOffset();
var end = selectionState.getEndOffset();
var selectedText = currentContentBlock.getText().slice(start, end);
```
--------------------------------
### Project Folder Structure
Source: https://github.com/facebook/draft-js/blob/main/examples/draft-0-10-0/playground/README.md
Illustrates the expected file and folder structure for a project created with Create React App. Key files like index.html and index.js must exist with exact filenames.
```bash
my-app/
README.md
node_modules/
package.json
public/
index.html
favicon.ico
src/
App.css
App.js
App.test.js
index.css
index.js
logo.svg
```
--------------------------------
### Sass Import Examples
Source: https://github.com/facebook/draft-js/blob/main/examples/draft-0-10-0/playground/README.md
Demonstrates how to import Sass files using the configured include paths. This allows for cleaner import statements for shared variables or external libraries.
```scss
@import 'styles/_colors.scss'; // assuming a styles directory under src/
@import 'nprogress/nprogress'; // importing a css file from the nprogress node module
```
--------------------------------
### Start Development Server
Source: https://github.com/facebook/draft-js/blob/main/examples/draft-0-10-0/playground/README.md
Runs the React application in development mode, enabling hot reloading and displaying lint errors in the console. Access the app at http://localhost:3000.
```bash
npm start
```
--------------------------------
### Firebase Project Initialization
Source: https://github.com/facebook/draft-js/blob/main/examples/draft-0-10-0/playground/README.md
This snippet shows the interactive prompts and configuration steps for initializing a Firebase project for hosting. It guides through associating a Firebase project, setting up database rules, and configuring the public directory for a single-page application.
```sh
=== Project Setup
First, let's associate this project directory with a Firebase project.
You can create multiple project aliases by running firebase use --add,
but for now we'll set up a default project.
? What Firebase project do you want to associate as default? Example app (example-app-fd690)
=== Database Setup
Firebase Realtime Database Rules allow you to define how your data should be
structured and when your data can be read from and written to.
? What file should be used for Database Rules? database.rules.json
✔ Database Rules for example-app-fd690 have been downloaded to database.rules.json.
Future modifications to database.rules.json will update Database Rules when you run
firebase deploy.
=== Hosting Setup
Your public directory is the folder (relative to your project directory) that
will contain Hosting assets to uploaded with firebase deploy. If you
have a build process for your assets, use your build's output directory.
? What do you want to use as your public directory? build
? Configure as a single-page app (rewrite all urls to /index.html)? Yes
✔ Wrote build/index.html
i Writing configuration info to firebase.json...
i Writing project information to .firebaserc...
✔ Firebase initialization complete!
```
--------------------------------
### Build for Production
Source: https://github.com/facebook/draft-js/blob/main/examples/draft-0-10-0/playground/README.md
Creates an optimized production build of the React application in the 'build' folder. This includes minification and filename hashing for efficient deployment.
```bash
npm run build
```
--------------------------------
### Add Flow to Create React App (npm)
Source: https://github.com/facebook/draft-js/blob/main/examples/draft-0-10-0/playground/README.md
Installs `flow-bin` and initializes Flow for a Create React App project using npm. This enables static type checking.
```sh
npm install --save flow-bin
```
```sh
npm run flow init
```
--------------------------------
### Deploy Website to GitHub Pages
Source: https://github.com/facebook/draft-js/blob/main/website/README.md
Builds the website and pushes it to the 'gh-pages' branch, convenient for GitHub Pages hosting.
```bash
GIT_USER= USE_SSH=true yarn deploy
```
--------------------------------
### Create and Merge SelectionState
Source: https://github.com/facebook/draft-js/blob/main/docs/APIReference-SelectionState.md
Demonstrates creating an empty SelectionState and merging properties to update it. Shows how to retrieve anchor and focus keys after an update.
```javascript
var selectionState = SelectionState.createEmpty('foo');
var updatedSelection = selectionState.merge({
focusKey: 'bar',
focusOffset: 0,
});
var anchorKey = updatedSelection.getAnchorKey(); // 'foo'
var focusKey = updatedSelection.getFocusKey(); // 'bar'
```
--------------------------------
### Jest Coverage Configuration Example
Source: https://github.com/facebook/draft-js/blob/main/examples/draft-0-10-0/playground/README.md
Override default Jest coverage configuration by adding supported keys to your package.json. This example shows how to set collectCoverageFrom, coverageThreshold, coverageReporters, and snapshotSerializers.
```json
{
"name": "your-package",
"jest": {
"collectCoverageFrom" : [
"src/**/*.{js,jsx}",
"!/node_modules/",
"!/path/to/dir/"
],
"coverageThreshold": {
"global": {
"branches": 90,
"functions": 90,
"lines": 90,
"statements": 90
}
},
"coverageReporters": ["text"],
"snapshotSerializers": ["my-serializer-module"]
}
}
```
--------------------------------
### Race Condition Example with onPaste
Source: https://github.com/facebook/draft-js/blob/main/docs/Advanced-Topics-EditorState-Race-Conditions.md
This example demonstrates a potential race condition when multiple event handlers attempt to update the EditorState asynchronously, leading to the last update overwriting previous ones.
```javascript
this.onPaste = function() {
this.setState({
editorState: removeEditorStyles(this.state.editorState),
});
};
```
--------------------------------
### Run GitHub Pages Deployment
Source: https://github.com/facebook/draft-js/blob/main/examples/draft-0-10-0/playground/README.md
This command initiates the deployment process to GitHub Pages. It first runs the `predeploy` script (which executes `npm run build`) and then uses `gh-pages` to deploy the contents of the `build` directory.
```sh
npm run deploy
```
--------------------------------
### Build Static Website Content
Source: https://github.com/facebook/draft-js/blob/main/website/README.md
Generates the static content for the website into the 'build' directory, ready for hosting.
```bash
yarn build
```
--------------------------------
### Integrate CSS Preprocessor with npm Scripts
Source: https://github.com/facebook/draft-js/blob/main/examples/draft-0-10-0/playground/README.md
Update `package.json` scripts to use `npm-run-all` for running CSS preprocessor tasks alongside React scripts. `npm start` now runs `watch-css` and `start-js` in parallel, while `npm build` runs `build-css` and `build-js` sequentially.
```diff
"scripts": {
"build-css": "node-sass-chokidar src/ -o src/",
"watch-css": "npm run build-css && node-sass-chokidar src/ -o src/ --watch --recursive",
- "start": "react-scripts start",
- "build": "react-scripts build",
+ "start-js": "react-scripts start",
+ "start": "npm-run-all -p watch-css start-js",
+ "build-js": "react-scripts build",
+ "build": "npm-run-all build-css build-js",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
}
```
--------------------------------
### getStartOffset()
Source: https://github.com/facebook/draft-js/blob/main/docs/APIReference-SelectionState.md
Returns the block-level character offset of the start position of the selection range.
```APIDOC
## getStartOffset()
### Description
Returns the block-level character offset of the start position of the selection range.
### Method
GET
### Endpoint
N/A (SDK Method)
### Returns
- **number**: The block-level character offset.
```
--------------------------------
### getStartKey()
Source: https://github.com/facebook/draft-js/blob/main/docs/APIReference-SelectionState.md
Returns the key of the block containing the start position of the selection range.
```APIDOC
## getStartKey()
### Description
Returns the key of the block containing the start position of the selection range.
### Method
GET
### Endpoint
N/A (SDK Method)
### Returns
- **string**: The key of the block.
```
--------------------------------
### Get current ContentState
Source: https://github.com/facebook/draft-js/blob/main/docs/APIReference-EditorState.md
Retrieve the current `ContentState` object from an `EditorState` instance.
```javascript
getCurrentContent(): ContentState
```
--------------------------------
### Get Last ContentBlock
Source: https://github.com/facebook/draft-js/blob/main/docs/APIReference-ContentState.md
Retrieves the very last ContentBlock in the editor's content.
```javascript
getLastBlock(): ContentBlock
```
--------------------------------
### Basic Draft.js Editor with Class Component
Source: https://github.com/facebook/draft-js/blob/main/docs/Overview.md
This example shows how to set up a basic Draft.js editor using a React class component. It initializes an empty editor state and provides an onChange handler to update the state.
```javascript
import React from 'react';
import ReactDOM from 'react-dom';
import {Editor, EditorState} from 'draft-js';
import 'draft-js/dist/Draft.css';
class MyEditor extends React.Component {
constructor(props) {
super(props);
this.state = {editorState: EditorState.createEmpty()};
this.onChange = editorState => this.setState({editorState});
}
render() {
return (
);
}
}
ReactDOM.render(, document.getElementById('container'));
```
--------------------------------
### Get First ContentBlock
Source: https://github.com/facebook/draft-js/blob/main/docs/APIReference-ContentState.md
Retrieves the very first ContentBlock in the editor's content.
```javascript
getFirstBlock(): ContentBlock
```
--------------------------------
### Add Flow to Create React App (yarn)
Source: https://github.com/facebook/draft-js/blob/main/examples/draft-0-10-0/playground/README.md
Installs `flow-bin` and initializes Flow for a Create React App project using yarn. This enables static type checking.
```sh
yarn add flow-bin
```
```sh
yarn flow init
```
--------------------------------
### Basic Draft.js Editor with React Hooks
Source: https://github.com/facebook/draft-js/blob/main/docs/Overview.md
This example demonstrates setting up a basic Draft.js editor using React Hooks for state management. It utilizes the `useState` hook to manage the editor state and provides an onChange handler.
```javascript
import React from 'react';
import ReactDOM from 'react-dom';
import {Editor, EditorState} from 'draft-js';
import 'draft-js/dist/Draft.css';
function MyEditor() {
const [editorState, setEditorState] = React.useState(
() => EditorState.createEmpty(),
);
return ;
}
ReactDOM.render(, document.getElementById('container'));
```
--------------------------------
### Get Selection State
Source: https://github.com/facebook/draft-js/blob/main/docs/APIReference-EditorState.md
Retrieves the currently rendered SelectionState. This property should not be managed manually.
```javascript
selection: SelectionState;
getSelection();
```
--------------------------------
### Netlify Client-Side Routing Configuration
Source: https://github.com/facebook/draft-js/blob/main/examples/draft-0-10-0/playground/README.md
To support pushState routing on Netlify, create a _redirects file in the public folder with rewrite rules.
```text
/* /index.html 200
```
--------------------------------
### Get current SelectionState
Source: https://github.com/facebook/draft-js/blob/main/docs/APIReference-EditorState.md
Retrieve the current `SelectionState` (cursor and selection range) from an `EditorState` instance.
```javascript
getSelection(): SelectionState
```
--------------------------------
### Code Splitting with Dynamic Import
Source: https://github.com/facebook/draft-js/blob/main/examples/draft-0-10-0/playground/README.md
Demonstrates code splitting using dynamic `import()` syntax. This loads a module chunk on demand, improving initial load performance.
```javascript
import React, { Component } from 'react';
class App extends Component {
handleClick = () => {
import('./moduleA')
.then(({ moduleA }) => {
// Use moduleA
})
.catch(err => {
// Handle failure
});
};
render() {
return (
);
}
}
export default App;
```
--------------------------------
### Get ContentBlock Data
Source: https://github.com/facebook/draft-js/blob/main/docs/APIReference-ContentBlock.md
Returns the immutable Map containing arbitrary data associated with the ContentBlock.
```javascript
const data = contentBlock.getData();
// Map { 'alignment': 'center' }
```
--------------------------------
### Get Inline Style at Offset
Source: https://github.com/facebook/draft-js/blob/main/docs/APIReference-ContentBlock.md
Retrieves the DraftInlineStyle at a specific character offset within the block.
```javascript
const inlineStyle = contentBlock.getInlineStyleAt(6);
// DraftInlineStyle { 'BOLD': true }
```
--------------------------------
### Get ContentBlock Depth
Source: https://github.com/facebook/draft-js/blob/main/docs/APIReference-ContentBlock.md
Returns the depth of the block, typically used for nested list items.
```javascript
const depth = contentBlock.getDepth();
// 0
```
--------------------------------
### Format Documentation Files
Source: https://github.com/facebook/draft-js/blob/main/website/README.md
Use this command to format documentation files with Prettier before submitting a Pull Request.
```bash
yarn format-docs
```
--------------------------------
### Get Entity: New Syntax
Source: https://github.com/facebook/draft-js/blob/main/docs/APIReference-APIMigration.md
Access an entity instance via ContentState in Draft.js v0.10.
```javascript
const entityInstance = contentState.getEntity(entityKey);
// entityKey is a string key associated with that entity when it was created
```
--------------------------------
### Create EditorState with configuration
Source: https://github.com/facebook/draft-js/blob/main/docs/APIReference-EditorState.md
Create an EditorState using a configuration object. This is a flexible way to initialize the editor state.
```javascript
const editorState = EditorState.create(config);
```
--------------------------------
### Get Direction Map
Source: https://github.com/facebook/draft-js/blob/main/docs/APIReference-EditorState.md
Retrieves a map of each block and its text direction. This is determined by UnicodeBidiService and should not be managed manually.
```javascript
directionMap: BlockMap;
getDirectionMap();
```
--------------------------------
### Travis CI Configuration for Draft.js Project
Source: https://github.com/facebook/draft-js/blob/main/examples/draft-0-10-0/playground/README.md
Example .travis.yml file to set up continuous integration for a Node.js project. It specifies the Node.js version, caches node_modules, and runs build and test scripts.
```yaml
language: node_js
node_js:
- 6
cache:
directories:
- node_modules
script:
- npm run build
- npm test
```
--------------------------------
### Get Focus Offset of Selection
Source: https://github.com/facebook/draft-js/blob/main/docs/APIReference-SelectionState.md
Returns the block-level character offset of the focus position of the selection range.
```javascript
getFocusOffset(): number
```
--------------------------------
### Get Focus Key of Selection
Source: https://github.com/facebook/draft-js/blob/main/docs/APIReference-SelectionState.md
Returns the key of the block containing the focus position of the selection range.
```javascript
getFocusKey(): string
```
--------------------------------
### Get Anchor Offset of Selection
Source: https://github.com/facebook/draft-js/blob/main/docs/APIReference-SelectionState.md
Returns the block-level character offset of the anchor position of the selection range.
```javascript
getAnchorOffset(): number
```
--------------------------------
### Get Anchor Key of Selection
Source: https://github.com/facebook/draft-js/blob/main/docs/APIReference-SelectionState.md
Returns the key of the block containing the anchor position of the selection range.
```javascript
getAnchorKey(): string
```
--------------------------------
### Configure package.json for Root-Relative Paths
Source: https://github.com/facebook/draft-js/blob/main/examples/draft-0-10-0/playground/README.md
Set 'homepage' to '.' in package.json to make all asset paths relative to index.html. This allows the app to be served from different base paths without rebuilding.
```json
"homepage": ".",
```
--------------------------------
### Get End Offset of Selection
Source: https://github.com/facebook/draft-js/blob/main/docs/APIReference-SelectionState.md
Returns the block-level character offset of the end position of the selection range.
```javascript
getEndOffset(): number
```
--------------------------------
### Get End Key of Selection
Source: https://github.com/facebook/draft-js/blob/main/docs/APIReference-SelectionState.md
Returns the key of the block containing the end position of the selection range.
```javascript
getEndKey(): string
```
--------------------------------
### Check Option Key Command - KeyBindingUtil
Source: https://github.com/facebook/draft-js/blob/main/docs/APIReference-KeyBindingUtil.md
Use this to check for the option key command.
```javascript
isOptionKeyCommand: function(
e: SyntheticKeyboardEvent
): boolean
```
--------------------------------
### Get ContentBlock Text
Source: https://github.com/facebook/draft-js/blob/main/docs/APIReference-ContentBlock.md
Retrieves the full plaintext content of the block, excluding any styling or entity information.
```javascript
const text = contentBlock.getText();
// 'Hello world!'
```
--------------------------------
### Get DraftInlineStyle from CharacterMetadata
Source: https://github.com/facebook/draft-js/blob/main/docs/APIReference-CharacterMetadata.md
Retrieves the DraftInlineStyle associated with this character. This is an OrderedSet of strings representing the inline styles.
```javascript
getStyle(): DraftInlineStyle
```
--------------------------------
### Add Deploy Scripts to package.json
Source: https://github.com/facebook/draft-js/blob/main/examples/draft-0-10-0/playground/README.md
This diff shows how to add `predeploy` and `deploy` scripts to your `package.json` file. The `predeploy` script ensures the build is run before deployment, and the `deploy` script uses `gh-pages` to deploy the build output.
```diff
"scripts": {
+ "predeploy": "npm run build",
+ "deploy": "gh-pages -d build",
"start": "react-scripts start",
"build": "react-scripts build",
```
--------------------------------
### Get Entity: Old Syntax
Source: https://github.com/facebook/draft-js/blob/main/docs/APIReference-APIMigration.md
Retrieve an entity instance using its key in older Draft.js versions.
```javascript
const entityInstance = Entity.get(entityKey);
// entityKey is a string key associated with that entity when it was created
```
--------------------------------
### Firebase Deployment Command
Source: https://github.com/facebook/draft-js/blob/main/examples/draft-0-10-0/playground/README.md
This snippet demonstrates the output of the `firebase deploy` command, indicating the progress and success of deploying database rules and hosting assets. It shows the final Hosting URL and Project Console link.
```sh
=== Deploying to 'example-app-fd690'...
i deploying database, hosting
✔ database: rules ready to deploy.
i hosting: preparing build directory for upload...
Uploading: [============================== ] 75%
✔ hosting: build folder uploaded successfully
✔ hosting: 8 files uploaded successfully
i starting release process (may take several minutes)...
✔ Deploy complete!
Project Console: https://console.firebase.google.com/project/example-app-fd690/overview
Hosting URL: https://example-app-fd690.firebaseapp.com
```
--------------------------------
### CSS Post-Processing with Autoprefixer
Source: https://github.com/facebook/draft-js/blob/main/examples/draft-0-10-0/playground/README.md
Demonstrates how CSS is automatically minified and vendor-prefixed by Autoprefixer. This ensures cross-browser compatibility without manual intervention.
```css
.App {
display: flex;
flex-direction: row;
align-items: center;
}
```
```css
.App {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-orient: horizontal;
-webkit-box-direction: normal;
-ms-flex-direction: row;
flex-direction: row;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
}
```
--------------------------------
### Create and Apply a Link Entity
Source: https://github.com/facebook/draft-js/blob/main/docs/Advanced-Topics-Entities.md
Demonstrates creating a 'LINK' entity with a URL and applying it to a selected range of text within the editor. This is useful for linkification.
```javascript
const contentState = editorState.getCurrentContent();
const contentStateWithEntity = contentState.createEntity('LINK', 'MUTABLE', {
url: 'http://www.zombo.com',
});
const entityKey = contentStateWithEntity.getLastCreatedEntityKey();
const contentStateWithLink = Modifier.applyEntity(
contentStateWithEntity,
selectionState,
entityKey,
);
const newEditorState = EditorState.set(editorState, {
currentContent: contentStateWithLink,
});
```
--------------------------------
### Decorator Strategy: Find Mutable Entities
Source: https://github.com/facebook/draft-js/blob/main/docs/APIReference-APIMigration.md
Example of a decorator strategy that uses contentState to find only mutable entities.
```javascript
const mutableEntityStrategy = function(contentBlock, callback, contentState) {
contentBlock.findEntityRanges(character => {
const entityKey = character.getEntity();
if (entityKey === null) {
return false;
}
// To look for certain types of entities,
// or entities with a certain mutability,
// you may need to get the entity from contentState.
// In this example we get only mutable entities.
return contentState.getEntity(entityKey).getMutability() === 'MUTABLE';
}, callback);
};
```
--------------------------------
### Manual Proxy Configuration in package.json
Source: https://github.com/facebook/draft-js/blob/main/examples/draft-0-10-0/playground/README.md
Configure proxy settings for specific API paths using an object in package.json. Supports http-proxy-middleware and http-proxy options.
```json
{
// ...
"proxy": {
"/api": {
"target": "",
"ws": true
// ...
}
}
// ...
}
```
--------------------------------
### Get All Blocks as Array
Source: https://github.com/facebook/draft-js/blob/main/docs/APIReference-ContentState.md
Returns all ContentBlocks within the ContentState as an array. Generally, using getBlockMap for iteration is preferred.
```javascript
getBlocksAsArray(): Array
```
--------------------------------
### Get Entity at Offset
Source: https://github.com/facebook/draft-js/blob/main/docs/APIReference-ContentBlock.md
Retrieves the entity key at a specific character offset within the block, if one exists.
```javascript
const entityKey = contentBlock.getEntityAt(6);
// 'my-entity-key'
```
--------------------------------
### Get an Entity by Key - Draft.js
Source: https://github.com/facebook/draft-js/blob/main/docs/APIReference-Entity.md
Retrieves the DraftEntityInstance for the specified key. Throws an error if no instance exists for that key.
```javascript
get(key: string): DraftEntityInstance
```
--------------------------------
### Configure API Proxy in package.json
Source: https://github.com/facebook/draft-js/blob/main/examples/draft-0-10-0/playground/README.md
Add this field to your `package.json` to tell the development server to proxy unknown requests to your API server. This is useful for serving your front-end and back-end from the same domain during development.
```json
"proxy": "http://localhost:4000",
```