Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'slate' in functional components in JavaScript. Our advanced machine learning engine meticulously scans each line of code, cross-referencing millions of open source libraries to ensure your implementation is not just functional, but also robust and secure. Elevate your React applications to new heights by mastering the art of handling side effects, API calls, and asynchronous operations with confidence and precision.
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);
});
});
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");
});
});
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)
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')
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 && undo && undo.length ? (
<button size="large" shape="circle"> onChange(value.transform().undo().apply())}>
<i aria-hidden="true">
</i></button><i aria-hidden="true">
) : null}
</i><i aria-hidden="true">
{children}
{readOnly !== true && }
{readOnly !== true && }</i></div>
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), [
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
// 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
}
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 });
}
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;
},