@snippetify/book-reader-component
Version:
Book Reader Component
58 lines (57 loc) • 2.39 kB
JavaScript
import rangy from 'rangy';
import 'rangy/lib/rangy-textrange';
import 'rangy/lib/rangy-classapplier';
import 'rangy/lib/rangy-highlighter';
import defaultConfig from '../config/config';
import { Decorator } from '../models/decorator';
export class DecoratorManager {
constructor() {
this.config = defaultConfig.decorator;
this.rangy = rangy;
this.rangy.init();
this.highlighter = this.rangy.createHighlighter(document, 'TextRange');
this.highlighter.addClassApplier(this.rangy.createClassApplier('note'));
this.highlighter.addClassApplier(this.rangy.createClassApplier('bookmark'));
this.highlighter.addClassApplier(this.rangy.createClassApplier('highlight'));
}
static getInstance() {
return new DecoratorManager();
}
setContainer(container) {
this.container = container;
return this;
}
print(decorators, container) {
this.setContainer(container);
decorators.forEach(v => this.printOne(v));
}
printOne(decorator) {
const selections = this.container.querySelectorAll('.selection');
if (selections.length > 0) {
selections.forEach(selection => {
selection.classList.remove('selection');
selection.classList.add(decorator.type);
selection.setAttribute('data-uuid', decorator.uuid);
selection.setAttribute('data-type', decorator.type);
Object.keys(decorator.style).forEach(key => selection.style[key] = decorator.style[key]);
});
}
else {
this.highlighter.classAppliers[decorator.type].elementProperties.style = decorator.style;
this.highlighter.classAppliers[decorator.type].elementAttributes['data-uuid'] = decorator.uuid;
this.highlighter.classAppliers[decorator.type].elementAttributes['data-type'] = decorator.type;
this.highlighter.deserialize(decorator.getSelerialized());
}
this.rangy.getSelection().removeAllRanges();
this.printIcon(decorator);
}
printIcon(decorator) {
const elem = this.container.querySelector(`[data-uuid="${decorator.uuid}"]`);
if (decorator.type === Decorator.NOTE_TYPE && elem.querySelectorAll('.note-icon').length === 0) {
elem.innerHTML += this.config.templates.note;
}
else if (decorator.type === Decorator.BOOKMARK_TYPE && elem.querySelectorAll('.bookmark-icon').length === 0) {
elem.innerHTML = this.config.templates.bookmark + elem.innerHTML;
}
}
}