Skip to content

Instantly share code, notes, and snippets.

@joao-pedrozo
Created January 7, 2021 18:48
Show Gist options
  • Save joao-pedrozo/9b476f5d54b70c27a62487f675a1ae3f to your computer and use it in GitHub Desktop.
Save joao-pedrozo/9b476f5d54b70c27a62487f675a1ae3f to your computer and use it in GitHub Desktop.
import Base from '@/components/base';
const { $ } = window;
export default class extends Base {
constructor($element) {
super($element);
this.content = document.querySelectorAll('.leaflet-content__text');
this.$nextBtn = $("button[data-search='next']");
this.$prevBtn = $("button[data-search='previous']");
this.$input = $element.find('input');
this.currentIndex = -1;
this.$results = null;
this.currentClass = 'current';
this.offsetTop = 50;
this.handleInput = this.handleInput.bind(this);
this.jumpToNextIndex = this.jumpToNextIndex.bind(this);
this.jumpToPreviousIndex = this.jumpToPreviousIndex.bind(this);
}
handleListeners(state) {
this.$input[state]('input', this.handleInput);
// this.$input[state]('focus', this.handleFocus);
this.$nextBtn[state]('click', this.jumpToNextIndex);
this.$prevBtn[state]('click', this.jumpToPreviousIndex);
}
async handleInput() {
const { default: Mark } = await import('mark.js');
this.markInstance = new Mark(this.content);
if (this.markInstance) {
this.markInstance.unmark({
done: () => {
const searchValue = this.$input.val();
if (searchValue.length > 3) {
this.markInstance.mark(searchValue, {
separateWordSearch: true,
done: () => {
this.$results = document.querySelectorAll('.leaflet-content__text mark');
this.currentIndex = 0;
this.jumpTo();
},
});
}
},
});
} else {
setTimeout(() => {
this.handleInput();
}, 50);
}
}
async handleFocus() {
const { default: Mark } = await import('mark.js'); /* eslint-disable-line class-methods-use-this */
this.markInstance = new Mark(this.content);
}
jumpToNextIndex() {
if (this.currentIndex + 1 !== this.$results.length) {
this.currentIndex += 1;
this.jumpTo();
}
}
jumpToPreviousIndex() {
if (this.currentIndex) {
this.currentIndex -= 1;
this.jumpTo();
}
}
jumpTo() {
if (this.$results.length) {
let position;
const $current = $(this.$results[this.currentIndex]);
$(this.$results).removeClass(this.currentClass);
if ($current.length) {
$current.addClass(this.currentClass);
position = $current.offset().top - this.offsetTop;
window.scrollTo(0, position);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment