Code Cheatsheets
  • Code Cheatsheets
  • Chrome Shortcuts
  • General Debugging
  • Google Advanced
  • GraphQL
  • General Mac Shortcuts
  • markdown
  • Regular Expression
  • Tech to Try
  • Typora Shortcuts
  • All
    • Elm
    • Headless CMS
    • Java
    • Swift
    • Solana
    • Solidity
    • APIS
      • Chatwoot
      • Daily
      • DuckDuckGo
      • Facebook Login
      • Google APIS
      • Intercom
      • Mux
      • OpenAI
      • Reddit API
      • Segment
      • Sendgrid
      • Sentry (Debug In Prod)
      • Spotify
      • Stripe
      • Transloadit
      • Zendesk
    • Bash
      • IO in Bash
      • Kills
      • Makefile
      • awk
      • Bash_Profile
      • Cron
      • Curl
      • Diff
      • Emacs
      • Find
      • general
      • gGit
      • Grep
      • man
      • Editing File Metadata
      • Sed
      • Secure File Transfer Protocol
      • SSH
      • Vi
      • zip
      • ZSH
      • installed
        • ASDF
        • Bit
        • ffmpeg
        • Generact
        • Graphite
        • ngrok
        • Node Version Manager
        • Spell
        • Tmux
    • C++
      • ptrs
    • CS_Fundamentals
      • Authentication
      • Comparisons
      • Semaphore
      • Content Security Policy
      • Data Structures
      • Editors Comparison
      • Email
      • Encryption
      • Errors
      • Feature Flags
      • HTTP
      • IDs
      • Language Types
      • Microservices
      • Optimization
      • Password Hashing
      • Real Time Messaging Protocol
      • Real-Time
      • Sorting
      • StoringSecrets
      • Testing
      • WebRTC
      • Webhook
    • README
      • Advanced (Postgres?)
      • Database Desigm
      • Firebase
      • Hosts
      • Code Abstractions
      • General Mongo
      • Mongo Aggregation
      • Opensearch
      • Postgres
      • Setup
      • Redis
      • Tips
      • SQL
        • Aggregate
        • Foreign Key Constraints
        • JOINS
        • Optimizations
        • SQL Lite
    • Dev_Apps
      • Featured Shortcuts
      • Iterm2
      • Matlab/Octave
      • Notion
      • Retool
      • Slack
      • Tableplus
      • vimium
      • Featured Shortcuts
      • Warp
      • Windows Terminal
    • Docker
      • Build and Run
      • Docker-compose
      • Dockerfile
      • Multistage builds
      • Swarm
    • Elixir
      • OTP
      • Config
      • DateTime
      • Erlang
      • Errors
      • File
      • Functions
      • Math
      • Modules
      • Regex
      • Setup
      • Time
      • URI
      • Phoenix
        • Channels
        • Handling Controller Errors
        • Controllers
        • Deployment
        • Default File Structure
        • LiveView
        • Plugs
        • Presence
        • Router
        • Session
        • Setup
        • Testing
        • Phoenix.Token
        • Views
        • Workers
        • Ecto
          • ChangeSets and validations
          • Generators
          • Insert/Update
          • Many to Many
          • Migration
          • Query With Repo
          • Relations
          • Schema
        • packages
          • CorsPlug
          • ExRated
          • Ueberauth
      • Collections
        • Lists(linked)
        • Map
        • Set
        • String
        • Structs
        • Tuples
      • Packages
        • Genstage
        • Geolix
        • json
        • Logger
        • Nanoid
        • Oban
        • Redix
        • Sentry
        • Stripe
        • Swoosh
        • Timex
        • http
          • HTTP
          • HTTPoison
          • Tesla
      • Processes / Concurrency
        • Agent
        • Cron
        • GenServer (Generic Server)
        • Registry
        • Supervisors
        • Tasks
    • README
      • IO
      • JSON
      • assert
      • basics
      • control
      • dep
      • errors
      • files
      • func
      • GoRoutines
      • interfaces
      • math
      • request
      • server
      • structs
      • testing
      • time
      • README
        • arrays
        • maps
        • strings
    • HTML Basics
      • Forms
      • Fun
      • SEO
      • Favicon
      • Images
      • Optimizations
      • Scripts
      • overview
        • Handlesbars
        • jade&pug
        • mustache
    • PHP
      • AMP
      • Hack
      • requests
      • setup
    • Python
      • 2.7v3.5
      • advanced
      • Argparse
      • Async Options
      • Classes
      • Secrets
      • environments
      • Importing
      • JSON
      • Os
      • random
      • re
      • testing
      • Datetime
      • Django
        • Databases
        • Models
        • Router
        • Serializers
        • Setup
        • Views
        • packages
          • Secrets
      • General Iterables
        • Dictionaries
        • fancyDicts
        • Heap
        • List
        • Set
        • Strings
      • Flask
        • Blueprint
        • cli
        • Config
        • Deploying Options
        • flash
        • LoginManager
        • packages
        • Requests/Routing
        • RESPONSES
        • templating
        • packages
          • Cors
          • flask_mongoengine
          • Socket IO
        • Postgres in Flask
          • Flask-Migrate
          • Flask-SQLAlchemy
      • packages
        • AIOHTTP
        • Celery
        • cython
        • Environment Variables
        • Excel
        • Google
        • Jupyter Notebook
        • Langchain
        • matplotlib
        • Numpy
        • Pandas
        • PassLib
        • PIL
        • Python Reddit API Wrapper(PRAW)
        • Prisma*
        • Pydub
        • Pymongo
        • Pyppetter
        • Python Requests
        • SQL Alchemy
        • aws
          • AWS Boto3
          • Dynamo
    • README
      • class
      • collections
      • exceptions
      • functions
      • futures
      • guice
      • loops
      • objects
      • options
      • packages
      • pattern&conditional
      • performance&style
      • sbt(running)
      • Strings
      • subtyping
      • traits
  • CSS
    • Obscure
    • Animations
    • Background
    • border
    • colors
    • cursors
    • display
    • Fonts
    • gradients
    • Lists
    • Media Queries
    • Object-fit
    • Overflow
    • pseudoElements
    • Selectors Master Race
    • Transforms
    • Transitions
    • extras
      • Scss
    • Placing Common Tasks
      • HTML Content Box
      • columns
      • Flexbox
      • Grid
      • Position
      • tables
    • Tailwind
      • Animation
      • general
      • Media Queries
      • position
      • Setup
      • Size and Spacing
      • Text
      • Typography
  • Deployment Solutions
    • DNS
    • Digital Ocean
    • Cloudflare
    • Heroku
    • loadtesting
    • Nginx
    • Process Management
    • Redis
    • Socket Alternatives
    • Speed Optimizations
    • {Surge
    • Task Queues
    • Terraform
    • Vercel
    • AWS
      • Certificate Manager
      • Amplify
      • \Cloudfront
      • Cloudwatch
      • Codebuild
      • Codedeploy
      • Code Pipeline
      • Docker in AWS
      • EB
      • ELB (Elastic Load Balancing)
      • IAM roles
      • AWS Lambda (Serverless)
      • Simple Email Service
      • Simple Queue Service
      • Virtual Private Cloud (VPC)
      • Serverless
      • Zappa
      • EC2
        • Scripts
        • Types of EC2
        • EC2(Elastic Compute)
      • Storage
        • Aurora
        • Autoscaling
        • CustomEC2
        • DynamoDB
        • RDS(Relational DB Service)
        • S3(Simple Storage Service)
    • Cloud GPUS
      • Beam
      • Paperspace
      • Replicate
    • Google Cloud Platform
      • Compute
      • Network
    • Github
    • Render
  • Javascript
    • Async and Await
    • Closure
    • Dates
    • Debugging
    • Errors
    • ES6 Specific Features
    • Functions
    • Importing
    • Promises
    • regex
    • Making a request
    • Timeout
    • All
      • Bun
      • Angular
        • HTML
        • HTTP
        • bash
        • input
        • observable_Subject
        • router
        • typescript
      • Chrome Plugins
        • Browser Action
        • Config
        • Content Scripts
        • Context Menu
        • Deploying
        • Desktop Capture
        • Events
        • To Get Identity
        • Manifest
        • Messages
        • Notifications
        • Popup
        • Service Workers
        • Setup
        • Shortcuts / Commands
        • Chrome Storage
        • Tabs
        • Match Patterns
      • Electron
        • Deep Links
        • Deploying
        • Desktop Captuer
        • Dialog
        • Images
        • Menu
        • Messages
        • Differences Between Platforms
        • notarizing
        • Notifications
        • Renderer Process
        • screen
        • Storage Options
        • Tray
        • Windows
        • Electron Packages
          • Electron builder
          • Electron-is-Dev
          • Electron-Log
          • electron-store
          • Electron-Forge
          • Sentry
      • Node
        • Routing
        • ejs
        • Env
        • Errors in Express
        • Files*
        • Forms
        • Logging
        • Middleware
        • Req
        • require
        • Response
        • Setup for Nodejs/Express
        • db
          • Mongoose
          • IoRedis
          • Knex
          • MongoDB
          • Prisma
        • Packages
          • Commander
          • Config
          • Crypto
          • Dotenv
          • Grant
          • Helmet
          • Http-errors
          • Essential Middleware
          • Passport
          • puppeteer
          • Expressjs/session
    • bundlers
      • Parcel
      • Vite
      • Webpack
    • Collections
      • JSON
      • Array
      • Blob (Binary Large Object)
      • Classes
      • Map
      • Objects
      • Set
      • Strings
    • Packages
      • AI
      • AWS SDK
      • Babel
      • Bcrypt
      • Cheerio
      • Concurrently
      • Csv
      • Cypress
      • Eslint
      • Jest
      • Lodash
      • Matter
      • Monaco Editor
      • Use to compile SCSS
      • Prettier
      • Query-string
      • Socket.io
      • Supabase
      • Trpc
      • Zod
    • TypeScript
      • 3rd Party Types
      • Classes
      • Enum
      • Generics
      • Interfaces
      • Migration
      • Narrowing Types
      • Types
      • Utility Types
      • packages
        • TRPC
    • JS In the Browser
      • CORS
      • DOM Control
      • Shadow DOM
      • Audio
      • Canvas
      • Clipboard
      • Cookies?
      • Events
      • Iframe
      • Intersection Observers
      • Keyboard Input
      • Media
      • Navigator
      • Scroll
      • Serving an index.html
      • Storage
      • Web Workers
      • packages
        • Tabulator
        • Bowser
        • Boxicons
        • d3
        • mapbox
        • MouseTrap Key Bindings
        • Videojs
  • ML
    • Embedding
    • Github
    • Vector Store
    • Deploy
      • Beam Cloud
      • Paperspace
    • NLP
      • Pre-processing text
      • 2vectorizing
      • 3featureengineering
      • 4ml
      • 4ml2
      • Overview
      • nltk
    • lowlevel
      • ML BuzzWords Guide
      • Regularization
      • DataSets
      • basics
        • Datasets
        • GPU Optimization
        • Neural Nets
  • README
    • Images, Fonts, and Files
    • Children
    • Context
    • Deployment
    • useEffect
    • Errors in React
    • Events
    • Forms
    • Hooks
    • JSX
    • Lists
    • Optimization
    • Rendering
    • Server Components
    • Setting up React
    • State and Lifecycle
    • Style
    • Suspense
    • Next
      • Image
      • Route Handlers
      • App Router
      • Assets
      • Next Config
      • CSS
      • Deploying
      • Layouts
      • Adding Markdown
      • Metadata
      • App Router
      • Server Actions
      • Setup
      • PreAppRouter
        • SSR
        • Api Routes
        • Head
        • Layouts
        • Pages
      • packages
        • ContentLayer
        • MDX Enchanced
        • T3 Env
    • How to fetch Data
      • React Query
    • packages
      • SWR
      • Classnames
      • Color
      • DatePicker
      • Draggable
      • Emotion
      • React-Feather
      • Fluxible
      • General
      • Google Login
      • Intersection Observer
      • React Lazy Load
      • Script
      • Proptypes
      • React Router v6
      • Recharts
      • React-Select
      • ShadCn
      • Slate
      • React-Table
      • Tanstack Router
      • Telephone Input
      • Three-Fiber
      • React-Toastify
      • React-Tooltip
      • React Video JS
      • Waypoint
      • React-window
      • XState
    • How to manage state in React
      • Jotai
      • Mobx
      • Zustand
      • Redux
        • Immer
        • Middleware
        • Redux
        • Redux
        • Redux Toolkit
        • selectors
        • Setup
        • Thunk
    • All
      • Gatsby
        • Cli
        • Data Integrations
        • Link
        • Pages
        • Plugins
        • Setup
        • Style
        • Transformer
        • packages
          • MDX
          • TailwindCss
      • Prehooks
        • Class Components
        • Ref
        • State and Lifecycle
      • React Native
        • ListViews
        • SafeArea
        • Built-in Components
        • Networking
        • Gestures
        • Navigation
        • Notifications
        • Orientation
        • Style
        • Dimensions
        • Expo
          • Development Build
          • Env
          • Setup
        • packages
          • Reanimated
          • React Native View Shot
  • Rust
    • Error
    • Importing
    • Ownership
Powered by GitBook
On this page
  • Basic Usage
  • Event Handlers
  • Custom Blocks
  • Custom Formatting
  • Executing Commands
  • Saving to a Database
  • Editor
  • Transforms
  • Operations
  1. README
  2. packages

Slate

A text-editor framework built with React

yarn add slate slate-react

Concepts

  • Slate is pure JSON objects and any custom properties/actions are up to you, then you can render based on those custom properties

  • Root Editor node, container element nodes, and leaf level text nodes form a tree just like a DOM

  • Paths refer to node, points are a path and offset, and ranges have an anchor(start) and focus(end)

Basic Usage

import React, { useEffect, useMemo, useState } from "react";
import { createEditor } from 'slate';
import { Slate, Editable, withReact } from 'slate-react'

const App = () => {
  // Want editor to be stable across renders 
  const editor = useMemo(() => withReact(createEditor()), []);
  const [value, setValue] = useState([
    {
      type: 'paragraph',
      children: [{ text: 'A line of text in a paragraph.' }],
    },
  ]);

  //create shared Slate context
  return (
    <Slate editor={editor} value={value} onChange={value => setValue(value)}>
      <Editable />
    </Slate>
  )
}

Event Handlers

  return (
    <Slate editor={editor} value={value} onChange={value => setValue(value)}>
      <Editable
       onKeyDown={event => {
          if (event.key === '&') {
            // Stop ampersand insertion
            event.preventDefault()
            editor.insertText("and")
          }
        }}
      />
    </Slate>
  )

Custom Blocks

Default internal renderer is just div. Element renderers are just simple React components. Must render children as lowest leaf in component

const CodeElement = props => {
  return (
    <pre {...props.attributes}>
      <code>{props.children}</code>
    </pre>
  )
}

const DefaultElement = props => {
  return <p {...props.attributes}>{props.children}</p>
}

Use Transforms and events to enter the code block and the renderElement ft to alter it

import { Editor, Transforms } from 'slate'

//....
function App() {
  //............
 // Change renderer based on props
  const renderElement = useCallback(props => {
    switch (props.element.type) {
      case 'code':
        return <CodeElement {...props} />
      default:
        return <DefaultElement {...props} />
    }
  }, [])

    return (
    <Slate editor={editor} value={value} onChange={value => setValue(value)}>
      <Editable
        renderElement={renderElement}
        onKeyDown={event => {
            if (event.key === "`" && event.ctrlKey) {
              debug("ACTIVATE BLASTOFF");
              event.preventDefault();
              // Determine whether any of the currently selected blocks are code blocks.
              const [match] = Editor.nodes(editor, {
                match: (n) => n.type === "code",
              });
              // Toggle the block type depending on whether there's already a match.
              Transforms.setNodes(
                editor,
                { type: match ? "paragraph" : "code" },
                { match: (n) => Editor.isBlock(editor, n) }
              );
            }
        }}
      />
    </Slate>
  )

Custom Formatting

  const renderLeaf = useCallback(props => {
    return <Leaf {...props} />
  }, [])
    //......
        <Editable
        renderElement={renderElement}
        renderLeaf={renderLeaf}
        onKeyDown={event => {
                if(event.key === "b" && event.ctrlKey) {
            event.preventDefault();
            Transforms.setNodes(
              editor,
              { bold: true },
              // Apply it to text nodes, and split the text node up if the
              // selection is overlapping only part of it.
              { match: (n) => Text.isText(n), split: true }
            );
          }
              }}
        />

Slate breaks up text into leaves

// Define a React component to render leaves with bold text.
const Leaf = props => {
  return (
    <span
      {...props.attributes}
      style={{ fontWeight: props.leaf.bold ? 'bold' : 'normal' }}
    >
      {props.children}
    </span>
  )
}

Executing Commands

Augment editor object to handle your own rich text commands or use plugins, extracting lets you make a toolbar too

Everything put togther above, but using custom commands

const App = () => {
  const editor = useMemo(() => withReact(createEditor()), [])
  const [value, setValue] = useState([
    {
      type: 'paragraph',
      children: [{ text: 'A line of text in a paragraph.' }],
    },
  ])

  const renderElement = useCallback(props => {
    switch (props.element.type) {
      case 'code':
        return <CodeElement {...props} />
      default:
        return <DefaultElement {...props} />
    }
  }, [])

  const renderLeaf = useCallback(props => {
    return <Leaf {...props} />
  }, [])

  return (
    // Add a toolbar with buttons that call the same methods.
    <Slate editor={editor} value={value} onChange={value => setValue(value)}>
      <div>
        <button
          onMouseDown={event => {
            event.preventDefault()
            CustomEditor.toggleBoldMark(editor)
          }}
        >
          Bold
        </button>
        <button
          onMouseDown={event => {
            event.preventDefault()
            CustomEditor.toggleCodeBlock(editor)
          }}
        >
          Code Block
        </button>
      </div>
      <Editable
        editor={editor}
        renderElement={renderElement}
        renderLeaf={renderLeaf}
        onKeyDown={event => {
          if (!event.ctrlKey) {
            return
          }

          switch (event.key) {
            case '`': {
              event.preventDefault()
              CustomEditor.toggleCodeBlock(editor)
              break
            }

            case 'b': {
              event.preventDefault()
              CustomEditor.toggleBoldMark(editor)
              break
            }
          }
        }}
      />
    </Slate>
  )
}

Saving to a Database

Just use JSON.stringify/JSON.parse on the value.

const App = () => {
  const editor = useMemo(() => withReact(createEditor()), [])
  const [value, setValue] = useState(    JSON.parse(localStorage.getItem('content')) || [
      {
        type: 'paragraph',
        children: [{ text: 'A line of text in a paragraph.' }],
      },
    ])

  return (
    <Slate
      editor={editor}
      value={value}
      selection={selection}
      onChange={value => {
        setValue(value)
        // Save the value to Local Storage.
        const content = JSON.stringify(value)
        localStorage.setItem('content', content)
      }}
    >
      <Editable />
    </Slate>
  )
}

Editor

Commands act if user was performing, so happen at cursor

interface Editor {
  children: Node[]
  selection: Range | null
  operations: Operation[]
  marks: Record<string, any> | null
  // Schema-specific node behaviors.
  isInline: (element: Element) => boolean
  isVoid: (element: Element) => boolean
  normalizeNode: (entry: NodeEntry) => void
  onChange: () => void

  // Overrideable core actions.
  addMark: (key: string, value: any) => void
  apply: (operation: Operation) => void
  deleteBackward: (unit: 'character' | 'word' | 'line' | 'block') => void
  deleteForward: (unit: 'character' | 'word' | 'line' | 'block') => void
  deleteFragment: () => void
  insertBreak: () => void
  insertFragment: (fragment: Node[]) => void
  insertNode: (node: Node) => void
  insertText: (text: string) => void
  removeMark: (key: string) => void
}

Custom commands

const MyEditor = {
  ...Editor,

  insertParagraph(editor) {
    // ...
  },
}

Transforms

// Set a "bold" format on all of the text nodes in a range.
Transforms.setNodes(
  editor,
  { bold: true },
  {
    at: range,
    match: node => Text.isText(node),
    split: true,
  }
)

// Wrap the lowest block at a point in the document in a quote block.
Transforms.wrapNodes(
  editor,
  { type: 'quote', children: [] },
  {
    at: point,
    match: node => Editor.isBlock(editor, node),
    mode: 'lowest',
  }
)

// Insert new text to replace the text in a node at a specific path.
Transforms.insertText(editor, 'A new string of text.', { at: path })

// ...there are many more transforms!

Operations

Lower level version of everything that can happen to doc, not extensible

editor.apply({
  type: 'insert_text',
  path: [0, 0],
  offset: 15,
  text: 'A new string of text to be inserted.',
})

editor.apply({
  type: 'remove_node',
  path: [0, 0],
  node: {
    text: 'A line of text!',
  },
})

editor.apply({
  type: 'set_selection',
  properties: {
    anchor: { path: [0, 0], offset: 0 },
  },
  newProperties: {
    anchor: { path: [0, 0], offset: 15 },
  },
})
PreviousShadCnNextReact-Table

Last updated 5 years ago