1
0
mirror of https://github.com/ianstormtaylor/slate.git synced 2025-02-23 16:55:23 +01:00
slate/docs/walkthroughs/02-adding-event-handlers.md
Sunny Hirai 08275f68f3
Custom TypeScript Types (#3835)
This PR adds better TypeScript types into Slate and is based on the proposal here: https://github.com/ianstormtaylor/slate/issues/3725

* Extend Slate's types like Element and Text

* Supports type discrimination (ie. if an element has type === "table" then we get a reduced set of properties)

* added custom types

* files

* more extensions

* files

* changed fixtures

* changes eslint file

* changed element.children to descendant

* updated types

* more type changes

* changed a lot of typing, still getting building errors

* extended text type in slate-react

* removed type assertions

* Clean up of custom types and a couple uneeded comments.

* Rename headingElement-true.tsx.tsx to headingElement-true.tsx

* moved basetext and baselement

* Update packages/slate/src/interfaces/text.ts

Co-authored-by: Brent Farese <25846953+BrentFarese@users.noreply.github.com>

* Fix some type issues with core functions.

* Clean up text and element files.

* Convert other types to extended types.

* Change the type of editor.marks to the appropriate type.

* Add version 100.0.0 to package.json

* Revert "Add version 100.0.0 to package.json"

This reverts commit 329e44e43d968700655b1c46f968bfd3147e7339.

* added custom types

* files

* more extensions

* files

* changed fixtures

* changes eslint file

* changed element.children to descendant

* updated types

* more type changes

* changed a lot of typing, still getting building errors

* extended text type in slate-react

* removed type assertions

* Clean up of custom types and a couple uneeded comments.

* Rename headingElement-true.tsx.tsx to headingElement-true.tsx

* moved basetext and baselement

* Update packages/slate/src/interfaces/text.ts

Co-authored-by: Brent Farese <25846953+BrentFarese@users.noreply.github.com>

* Fix some type issues with core functions.

* Clean up text and element files.

* Convert other types to extended types.

* Change the type of editor.marks to the appropriate type.

* Run linter.

* Remove key:string uknown from the base types.

* Clean up types after removing key:string unknown.

* Lint and prettier fixes.

* Implement custom-types

Co-authored-by: mdmjg <mdj308@nyu.edu>

* added custom types to examples

* reset yarn lock

* added ts to fixtures

* examples custom types

* Working fix

* ts-thesunny-try

* Extract interface types.

* Fix minor return type in create-editor.

* Fix the typing issue with Location having compile time CustomTypes

* Extract types for Transforms.

* Update README.

* Fix dependency on slate-history in slate-react

Co-authored-by: mdmjg <mdj308@nyu.edu>
Co-authored-by: Brent Farese <brentfarese@gmail.com>
Co-authored-by: Brent Farese <25846953+BrentFarese@users.noreply.github.com>
Co-authored-by: Tim Buckley <timothypbuckley@gmail.com>
2020-11-24 12:30:06 -08:00

2.6 KiB

Adding Event Handlers

Okay, so you've got Slate installed and rendered on the page, and when you type in it, you can see the changes reflected. But you want to do more than just type a plaintext string.

What makes Slate great is how easy it is to customize. Just like other React components you're used to, Slate allows you to pass in handlers that are triggered on certain events.

Let's use the onKeyDown handler to change the editor's content when we press a key.

Here's our app from earlier:

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

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

Now we add an onKeyDown handler:

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

  return (
    <Slate editor={editor} value={value} onChange={value => setValue(value)}>
      <Editable
        // Define a new handler which prints the key that was pressed.
        onKeyDown={event => {
          console.log(event.key)
        }}
      />
    </Slate>
  )
}

Cool, now when a key is pressed in the editor, its corresponding keycode is logged in the console.

Now we want to make it actually change the content. For the purposes of our example, let's implement turning all ampersand, &, keystrokes into the word and upon being typed.

Our onKeyDown handler might look like this:

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

  return (
    <Slate editor={editor} value={value} onChange={value => setValue(value)}>
      <Editable
        onKeyDown={event => {
          if (event.key === '&') {
            // Prevent the ampersand character from being inserted.
            event.preventDefault()
            // Execute the `insertText` method when the event occurs.
            editor.insertText('and')
          }
        }}
      />
    </Slate>
  )
}

With that added, try typing &, and you should see it suddenly become and instead!

This offers a sense of what can be done with Slate's event handlers. Each one will be called with the event object, and you can use your editor to perform commands in response. Simple!