wyswyg editor / block style editor / editorjs extention / editorjs plugin
Editor.js 에서 Inline Tool 예시
ref. 1 에서 설명하는 내용의 full code 이다. 아래 code를 .html
로 저장해서 확인해 보면 된다.
.html file 을 실행하면, 아래와 같은 화면을 볼 수 있다. 그림에서 ’Mark’메뉴가 새롭게 추가된 Inline Tool 이다.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
<script src="https://cdn.jsdelivr.net/npm/@editorjs/editorjs@latest"></script>
<script type="text/javascript">
class MarkerTool {
static get isInline() {
return true;
}
static get sanitize() {
return {
mark: {
class: 'cdx-marker'
}
};
}
constructor({
api
}) {
this.api = api
this.button = null;
this.state = false;
this.tag = 'mark';
this.class = 'cdx-marker';
}
render() {
// <button type="button" class="ce-inline-tool" data-tool="marker">Mark</button>
this.button = document.createElement('button');
this.button.type = 'button';
this.button.textContent = 'Mark';
this.button.classList.add(this.api.styles.inlineToolButton);
return this.button;
}
// When the text is block selected, this method is invoked
surround(range) {
if (this.state) {
// If highlights is already applied
this.unwrap(range);
return;
}
this.wrap(range);
}
wrap(range) {
const selectedText = range.extractContents();
const mark = document.createElement(this.tag);
mark.classList.add(this.class);
mark.appendChild(selectedText);
// Insert new element
range.insertNode(mark);
this.api.selection.expandToTag(mark);
}
unwrap(range) {
const mark = this.api.selection.findParentTag(this.tag, this.class);
const text = range.extractContents();
mark.remove();
range.insertNode(text);
}
checkState(selection) {
const text = selection.anchorNode;
if (!text) {
return;
}
const anchorElement = text instanceof Element ? text : text.parentElement;
this.state = !!anchorElement.closest('MARK');
}
};
</script>
<style type="text/css">
.simple-image {
padding: 20px 0;
}
.simple-image input {
width: 100%;
padding: 10px;
border: 1px solid #e4e4e4;
border-radius: 3px;
outline: none;
font-size: 14px;
}
</style>
</head>
<body>
<div id="editorjs"></div>
<button id="save-button">Save</button>
<pre id="output"></pre>
<script>
const editor = new EditorJS({
// logLevel: 'VERBOSE',
autofocus: true,
tools: {
marker: MarkerTool,
},
data: {
time: 1552744582955,
blocks: [
{
type: "paragraph",
data: {
"text": "dfsfd<mark class='cdx-marker'>sdf</mark>"
}
}
],
version: "2.11.10"
}
});
const saveButton = document.getElementById('save-button');
const output = document.getElementById('output');
saveButton.addEventListener('click', () => {
editor.save().then( savedData => {
console.log(savedData)
output.innerHTML = JSON.stringify(savedData, null, 4);
})
})
</script>
</body>
</html>
댓글 없음:
댓글 쓰기