UNPKG

@snippetify/book-reader

Version:
87 lines (73 loc) 2.34 kB
const Events = require('./events') require('rangy/lib/rangy-textrange') const Selection = require('./models/Selection') const rangy = require('rangy/lib/rangy-highlighter') const classApplier = require('rangy/lib/rangy-classapplier') class SelectionManager { constructor () { this.events = {} this.rangy = rangy this.rootElement = document } static getInstance () { return new SelectionManager() } setRootElement (element) { this.rootElement = element return this } setEvents (events) { this.events = events return this } initDispatcher () { $(this.rootElement).on('click', e => { const event = this.create() if (event && !this.fromContextMenu(e)) { this.events.notify(Events.textSelected, event) } }).on('mousedown', e => { if (!this.fromContextMenu(e)) { this.removePrevious() } }) return this } fromContextMenu (e) { return $(e.target).parents('[data-type="context-menu"]').length > 0 } create () { const selection = this.rangy.getSelection() if (!selection.isCollapsed) { this.initHighlighter() this.highlighter.highlightSelection('selection') const endPage = parseInt($(selection.focusNode).parents('[data-no]').attr('data-no')) const endRef = parseFloat($(selection.focusNode).parent('p[data-id]').attr('data-pos')) const startPage = parseInt($(selection.anchorNode).parents('[data-no]').attr('data-no')) const startRef = parseFloat($(selection.anchorNode).parent('p[data-id]').attr('data-pos')) return new Selection({ pages: [startPage, endPage], content: selection.toString(), references: [startRef, endRef], serialized: this.getLast(this.highlighter.serialize()) }) } } getLast (value) { const items = value.split('|') return `${items[0]}|${items[items.length - 1]}` } removePrevious () { this.initHighlighter() this.highlighter.unhighlightSelection() return this } initHighlighter () { if (!this.highlighter) { this.highlighter = this.rangy.createHighlighter(document, 'TextRange') this.highlighter.addClassApplier(classApplier.createClassApplier('selection')) } } } module.exports = SelectionManager module.exports.default = SelectionManager