How to use slate - 10 common examples

To help you get started, we’ve selected a few slate examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github enzoferey / slate-instant-replace / test / index.js View on Github external
it("should ignore the event", () => {
      const value = initialValue;
      const fakeTransform = fake();
      const plugins = [AutoReplacePlugin(fakeTransform)];
      let simulator = new Editor({ value, plugins });

      // Press enter
      simulator.run("onKeyDown", keyEvent("Enter"));

      expect(fakeTransform.callCount).to.equal(0);
    });
  });
github enzoferey / slate-instant-replace / test / getLastWord.js View on Github external
it("should return the last word", () => {
      const editor = new Editor({ value: Plain.deserialize("hello world") });

      // Anchor at the end of the first word
      expect(getLastWord(editor.moveForward(5))).to.equal("hello");

      // Anchor at the beginning of the second word
      expect(getLastWord(editor.moveForward(1))).to.equal("");

      // Anchor at the end of the second word
      expect(getLastWord(editor.moveForward(5))).to.equal("world");
    });
  });
github ahixon / slate-sync-bridge / test / slate / bridge.js View on Github external
fixtures(__dirname, 'commands', ({ module }) => {
      const { input, output, options = {}, plugins: module_plugins } = module
      const fn = module.default
      const editor = new Editor({
        plugins: module_plugins ? plugins.concat(module_plugins) : plugins,
      })
      const opts = { preserveSelection: true, ...options }
      // if (Object.keys(options).length) {
      //   throw new TypeError('bad test, cannot use options yet');
      // }

      const inputSyncDoc = toSyncDocument(input.document.toJSON());
      
      editor.setValue(input)
      fn(editor)
      
      // re-apply the operations from the test
      const actualSyncDoc = editor.operations.reduce((doc, op) => applyOperation(doc, op), inputSyncDoc);
      const actualDoc = toSlateDocument(actualSyncDoc)
github orbiting / publikator-frontend / lib / github / components / Editor / index.js View on Github external
documentChangeHandler (_, newEditorState) {
    const { data: { repository }, path, uncommittedChangesMutation } = this.props
    const { committedEditorState, uncommittedChanges } = this.state

    const serializedNewEditorState = Raw.serialize(newEditorState, {terse: true})
    const serializedCommittedEditorState = Raw.serialize(committedEditorState, {terse: true})
    if (JSON.stringify(serializedNewEditorState) !== JSON.stringify(serializedCommittedEditorState)) {
      this.store.set('editorState', serializedNewEditorState)
      this.store.set('commit', repository.commit)

      if (!uncommittedChanges) {
        this.setState({
          uncommittedChanges: true
        })
        uncommittedChangesMutation({
          login: repository.owner.login,
          repository: repository.name,
          path: path.split('/').slice(1).join('/'), // omit branch
          action: 'create'
        }).catch((error) => {
          console.log('uncommittedChangesMutation error')
github olymp / olymp / src / slate / editor.js View on Github external
render = () => {
    const { children, showUndo, onChange, readOnly, marks, nodes, plugins, className, spellcheck, style, blockTypes, ...rest } = this.props;
    const value = this.props.value || Plain.deserialize('');

    const undo = !!value && !!value.history && !!value.history.undos && !!value.history.undos['_head'] && value.history.undos['_head'].value;
    // console.log(undo);

    return (
      <div style="{{">
        
          {false &amp;&amp; undo &amp;&amp; undo.length ? (
            <button size="large" shape="circle"> onChange(value.transform().undo().apply())}&gt;
              <i aria-hidden="true">
            </i></button><i aria-hidden="true">
          ) : null}
        </i><i aria-hidden="true">
        {children}
        {readOnly !== true &amp;&amp; }
        {readOnly !== true &amp;&amp; }</i></div>
github este / este / components / editor / Editor.js View on Github external
const [value, setValue] = useState(() => {
    const model = elementsToSlateValue(
      page.element.id,
      elements,
      componentsById,
    );
    // For SSR.
    KeyUtils.resetGenerator();
    return Value.fromJSON(model);
  });
  const stylesById = useMemo(() => arrayOfItemsWithIdToObject(styles), [
github accordproject / template-studio-v2 / src / sagas / contractSaga.js View on Github external
marks: []
        }
      ]
    };

    const valueAsSlate = slateTransformer.fromMarkdown(clauseMd);
    const clauseNodeJSON = valueAsSlate.toJSON().document.nodes[0];
    const newSlateValueAsJSON = JSON.parse(JSON.stringify(slateValue.toJSON()));

    const { nodes } = newSlateValueAsJSON.document;

    // add the clause node to the Slate dom at current position
    // Temporary fix to separate clauses, adding the new paragraph at
    // end of splice. Convert this all back to markdown
    nodes.splice((currentPosition + 1), 0, clauseNodeJSON, paragraphSpaceNodeJSON);
    const realNewMd = slateTransformer.toMarkdown(Value.fromJSON(newSlateValueAsJSON));

    // update contract on store with new slate and md values
    yield put(actions.documentEdited(Value.fromJSON(newSlateValueAsJSON), realNewMd));
    const grammar = templateObj.parserManager.getTemplatizedGrammar();


    // Temporary roundtrip and rebuild grammar
    const grammarRound = roundTrip(grammar);
    templateObj.parserManager.buildGrammar(grammarRound);

    const sampleText = templateObj.getMetadata().getSamples().default;
    const model = templateObj.getModelManager().getModels();
    const logic = templateObj.getScriptManager().getLogic();
    const clauseTemplateId = uuidv4(); // unique identifier for a clause template

    // add a new clause template to the store so user can edit template
github sanity-io / sanity / packages / @sanity / form-builder / src / inputs / BlockEditor / utils / createPatchToOperations.ts View on Github external
// Set patches patching either string values or span objects
    if (patch.type === 'set') {
      const valueIsString = isString(patch.value)
      const patchSpan = valueIsString ? null : (patch.value as Span)
      const patchText = valueIsString ? patch.value : patchSpan.text
      // If single leaf, we can just replace the text with the current marks
      if (textNode.leaves.size === 1) {
        let marks
        // eslint-disable-next-line max-depth
        if (valueIsString) {
          marks = textNode.leaves.map(leaf => leaf.marks).get(0)
        } else {
          marks = Mark.createSet(patchSpan.marks.map(mark => ({type: mark})))
        }
        editor.replaceNodeByPath(textPath, Text.create({text: patchText, marks}))
        return editor.operations
      }

      // Build the new text
      workTextNode.leaves[leafIndex] = {
        object: 'leaf',
        text: patchText,
        marks: valueIsString
          ? node.leaves.get(leafIndex).marks
          : Mark.createSet(patchSpan.marks.map(mark => ({type: mark})))
      }
      // Replace it
      editor.replaceNodeByPath(textPath, Text.fromJSON(workTextNode))
      return editor.operations
    }
github Simon-Initiative / authoring-client / src / editors / content / learning / contiguoustext / utils.tsx View on Github external
const value = new wrappers[contentType](rawValue);
    const data = { value };
    return node.merge({ data });
  }

  // Handle Links
  if (contentType === 'Link') {
    delete rawValue.content;
    const value = new wrappers[contentType]().with(rawValue);
    const data = { value };
    return node.merge({ data });
  }

  // Cite, Extra, InputRef (or anthing else) just gets
  // stripped out and replaced with a text node
  return Text.create({ text: node.text });
}
github GitbookIO / slate-edit-code / lib / validation / validateNode.js View on Github external
validate(node) {
            const { nodes } = node;

            const toRemove = nodes.filterNot(n => n.object === 'text');
            if (!toRemove.isEmpty()) {
                // Remove them, and the rest
                // will be done in the next validation call.
                return { toRemove };
            } else if (nodes.size > 1) {
                // Else, there are only text nodes

                return { toJoin: nodes };
            } else if (nodes.size === 0) {
                return { toAdd: [Text.create()] };
            }

            // There is a single text node -> valid
            return null;
        },