Skip to content

Instantly share code, notes, and snippets.

@pjchender
Created July 23, 2018 09:36
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pjchender/f9cc547a555ebf263b834a82e11fd859 to your computer and use it in GitHub Desktop.
Save pjchender/f9cc547a555ebf263b834a82e11fd859 to your computer and use it in GitHub Desktop.
Quill + Rails + Stimulus
<!-- ./app/views/posts/_form.html.erb -->
<div class="form-group mb-3">
<%= content_fields.label :body, class: 'col-form-label' %>
<div data-controller="quill-editor">
<div data-target="quill-editor.container" style="min-height: 250px;"></div>
<%= content_fields.text_area :body, class: 'form-control d-none', placeholder: 'Content' %>
</div>
</div>
// ./app/javascript/stylesheets/application.scss
@import '~quill/dist/quill.snow';
// ./app/javascript/controllers/quill_editor_controller.js
import { Controller } from "stimulus";
import Quill from 'quill';
export default class extends Controller {
static targets = ['container'];
connect() {
this.quillInit();
}
quillInit() {
this.containerTargets.forEach(containerTarget => {
const quill = new Quill(containerTarget, this.quillOption);
const textareaElement = containerTarget.nextElementSibling;
if (textareaElement.type !== 'textarea') {
console.warn('You have to put <textarea> after <div data-target="quill-editor.container">')
return;
}
if (textareaElement.value !== '') {
quill.setContents(JSON.parse(textareaElement.value)['ops']);
}
quill.on('text-change', function() {
let delta = quill.getContents();
textareaElement.value = JSON.stringify(delta);
})
})
}
get quillOption() {
return {
modules: {
toolbar: this.toolbarOption
},
placeholder: 'Type something here...',
readOnly: false,
theme: 'snow',
}
}
get toolbarOption() {
return {
container: [
[{ 'size': ['small', false, 'large', 'huge'] }], // custom dropdown
['bold', 'italic', 'underline', 'strike'], // toggled buttons
['link', 'image'],
[{ 'color': [] }, { 'background': [] }],
]
}
}
}
import { Controller } from 'stimulus';
import Quill from 'quill';
export default class extends Controller {
connect() {
this.element.innerHTML = this.quillInnerHTML();
}
quillInnerHTML() {
if (this.params === '') {
return;
}
let emptyElement = document.createElement('div');
const quill = new Quill(emptyElement);
quill.setContents(JSON.parse(this.params)['ops']);
return quill.root.innerHTML;
}
// Use getter to clean code
get params() {
return this.data.get('params');
}
}
<!-- ./app/views/posts/show.html.erb -->
<div data-controller="quill-viewer"
data-quill-viewer-params="<%= content.body %>"
>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment