Git Product home page Git Product logo

Comments (3)

dylans avatar dylans commented on May 25, 2024 1

It is indeed difficult to keep the examples safe as every version of TS potentially introduces changes that were not caught previously.

PRs are always welcome to update them.

from slate.

alexander-larsson avatar alexander-larsson commented on May 25, 2024

Sorry if this is not 100% related to this issue but I just started using Slate and got really confused by this when trying to get some code working based on the examples. Is it just the types that are wrong or does the type property for example in fact not exist on BaseElement (see one of the errors in the picture above) so the example code is wrong and based on some older version of Slate?

from slate.

maral avatar maral commented on May 25, 2024

Hi, I stumbled upon the very same thing and found a solution around the internet. However, it would be really nice if Slate's Docs already provided that - I really like everything about the design and philosophy of Slate, this was a turn off though. GitBook has the option to have multiple "tabs" in the docs to allow both JS and TS versions, see their examples.

Here is my take of correctly typed example from the 05-executing-commands walk through part:

'use client';

import React, { useCallback, useState } from 'react';
import type { BaseEditor, Descendant } from 'slate';
import { createEditor, Editor, Element, Transforms } from 'slate';
import type { ReactEditor, RenderElementProps, RenderLeafProps } from 'slate-react';
import { Editable, Slate, withReact } from 'slate-react';

type Paragraph = { type: 'paragraph'; children: CustomText[] };
type Code = { type: 'code'; children: CustomText[] };
type CustomElement = Paragraph | Code;
type CustomText = { text: string; bold: boolean };

declare module 'slate' {
  interface CustomTypes {
    Editor: BaseEditor & ReactEditor;
    Element: CustomElement;
    Text: CustomText;
  }
}

const initialValue: Descendant[] = [
  {
    type: 'paragraph',
    children: [{ text: 'A line of text in a paragraph.', bold: false }],
  },
];

const CustomEditor = {
  isBoldMarkActive(editor: Editor) {
    const marks = Editor.marks(editor);
    return marks ? marks.bold === true : false;
  },

  isCodeBlockActive(editor: Editor) {
    const [match] = Editor.nodes(editor, {
      match: n => Element.isElement(n) && n.type === 'code',
    });

    return !!match;
  },

  toggleBoldMark(editor: Editor) {
    const isActive = CustomEditor.isBoldMarkActive(editor);
    if (isActive) {
      Editor.removeMark(editor, 'bold');
    } else {
      Editor.addMark(editor, 'bold', true);
    }
  },

  toggleCodeBlock(editor: Editor) {
    const isActive = CustomEditor.isCodeBlockActive(editor);
    Transforms.setNodes(
      editor,
      { type: isActive ? undefined : 'code' },
      { match: n => Element.isElement(n) && Editor.isBlock(editor, n) }
    );
  },
};

export const EditorTest: React.FC = () => {
  const [editor] = useState(() => withReact(createEditor()));
  const renderElement = useCallback((props: RenderElementProps) => {
    switch (props.element.type) {
      case 'code':
        return <CodeElement {...props} />;
      default:
        return <DefaultElement {...props} />;
    }
  }, []);

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

  return (
    <div className='mx-auto max-w-2xl py-16 px-4 sm:py-24 sm:px-6 lg:max-w-7xl lg:px-8'>
      <Slate editor={editor} initialValue={initialValue}>
        <div className='flex mb-4 gap-2'>
          <button
            className='p-2 bg-blue-500 text-white rounded-md'
            onMouseDown={event => {
              event.preventDefault();
              CustomEditor.toggleBoldMark(editor);
            }}
          >
            Bold
          </button>
          <button
            className='p-2 bg-blue-500 text-white rounded-md'
            onMouseDown={event => {
              event.preventDefault();
              CustomEditor.toggleCodeBlock(editor);
            }}
          >
            Code Block
          </button>
        </div>
        <Editable
          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>
    </div>
  );
};

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

const DefaultElement = (props: RenderElementProps) => {
  return <p {...props.attributes}>{props.children}</p>;
};

const Leaf = (props: RenderLeafProps) => {
  return (
    <span
      {...props.attributes}
      style={{ fontWeight: props.leaf.bold ? 'bold' : 'normal', color: props.leaf.bold ? 'red' : 'black' }}
    >
      {props.children}
    </span>
  );
};

from slate.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.