Created
March 28, 2023 12:25
-
-
Save notchris/1d5f2db9a20d84cff61a8c54e05f2e65 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from "react"; | |
import { Editor } from "slate"; | |
import { useSlate } from "slate-react"; | |
const name = "color_picker"; | |
let color = "#000000"; | |
const baseClass = "rich-text__button"; | |
const isMarkActive = (editor, format) => { | |
const leaves = Editor.marks(editor); | |
return leaves ? /^#[0-9A-F]{6}$/i.test(leaves[format]) : false; | |
}; | |
const toggleLeaf = (editor, format, color) => { | |
const isActive = isMarkActive(editor, format); | |
console.log(isActive); | |
if (isActive) { | |
Editor.removeMark(editor, format); | |
} else { | |
Editor.addMark(editor, format, color); | |
} | |
}; | |
const ColorInput = ({ color }) => { | |
return <input onChange={onChange} type="color"></input>; | |
}; | |
const onChange = (event) => { | |
color = event.target.value; | |
console.log(color); | |
}; | |
const input = <ColorInput color={color}></ColorInput>; | |
const LeafButton = ({ format, children, color }) => { | |
const editor = useSlate(); | |
const active = isMarkActive(editor, format); | |
if (active) { | |
const leafValue = Editor.marks(editor)[format]; | |
} | |
return ( | |
<button | |
type="button" | |
className={[ | |
baseClass, | |
isMarkActive(editor, format) && `${baseClass}__button--active`, | |
] | |
.filter(Boolean) | |
.join(" ")} | |
onMouseDown={(event) => { | |
event.preventDefault(); | |
toggleLeaf(editor, format, color); | |
}} | |
> | |
{active ? "Remove Color" : "Apply Color"} | |
</button> | |
); | |
}; | |
const Button = ({ format, children }) => { | |
const editor = useSlate(); | |
const active = isMarkActive(editor, format); | |
return ( | |
<div> | |
{input} | |
<LeafButton format={name} color={color}> | |
{{ children }} | |
</LeafButton> | |
</div> | |
); | |
}; | |
const Leaf = ({ attributes, leaf, children }) => { | |
if (leaf[name]) { | |
return ( | |
<span | |
style={{ | |
color: leaf[name], | |
}} | |
{...attributes} | |
> | |
{children} | |
</span> | |
); | |
} | |
return <span {...attributes}>{children}</span>; | |
}; | |
export default { | |
name, | |
Button, | |
Leaf, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment