import { aliases, defaulttx, meta, translations } from './meta.js'; import { hasLocalStorage } from './utils.js'; const bookTransforms = { 'oba': { chapter: (ref) => { return 1; }, verse: (ref) => { const verses = ref.getVerse(); if (verses === null) { return ref.getChapter(); } return verses; }, fullTitle: (ref) => { return `${ref.meta.title} ${ref.verse}`; }, }, 'jud': { chapter: (ref) => { return 1; }, verse: (ref) => { const verses = ref.getVerse(); if (verses === null) { return ref.getChapter(); } return verses; }, fullTitle: (ref) => { return `${ref.meta.title} ${ref.verse}`; }, }, /*'psa': { match: { dn: 'lxx', }, chapter: (ref) => { return 999; } }*/ }; class Refs { constructor(book, chapter, verse, options) { // change ts to options // {sn: 'mt', dn: 'lxx'} // source/dest num this._book = aliases[book.toLowerCase()]; this._chapter = chapter; this._verse = verse; // Default source numbering is the Masoretic Text. this._options = {'sn': 'mt'}; if (options !== undefined) { this._options = options; } } fullTitle() { if (this._book in bookTransforms && 'fullTitle' in bookTransforms[this._book]) { return bookTransforms[this._book].fullTitle(this); } const verses = this.verse; const chapter = this.chapter; let title = this.meta.title; if (chapter.length === 2) { return `${title} ${chapter[0]}-${chapter[1]}`; } title = `${title} ${chapter[0]}`; if (!verses) { return title; } if (typeof(verses) === 'number' || verses.length === 1) { return title += `:${verses}`; } if (verses[1] === 'ff') { return title += `:${verses[0]}ff`; } return title += `:${verses[0]}-${verses[1]}`; } get book() { return this._book; } getChapter() { if (typeof(this._chapter) === 'number' || (typeof(this._chapter) === 'string' && this._chapter.indexOf('-') == -1)) { return [parseInt(this._chapter)]; } return [parseInt(this._chapter.substr(0, this._chapter.indexOf('-'))), parseInt(this._chapter.substr(this._chapter.indexOf('-')+1))]; } get chapter() { if (this._book in bookTransforms) { const bt = bookTransforms[this._book]; if ('match' in bt) { if ('dn' in bt.match && this._options.sn == bt.match.dn) { return this.getChapter(); } } const tx = bt; if ('chapter' in tx) { return tx['chapter'](this); } } return this.getChapter(); } getVerse() { if (!this._verse) { return null; } if (typeof(this._verse) === 'string' && this._verse.endsWith('ff')) { return [parseInt(this._verse.substring(0, this._verse.length-2)), 'ff']; } if (typeof(this._verse) === 'number' || (typeof(this._verse) === 'string' && this._verse.indexOf('-') == -1)) { return [parseInt(this._verse)]; } return [parseInt(this._verse.substring(0, this._verse.indexOf('-'))), parseInt(this._verse.substring(this._verse.indexOf('-')+1))]; } get verse() { if (this._book in bookTransforms) { const tx = bookTransforms[this._book]; if ('verse' in tx) { return tx['verse'](this); } } return this.getVerse(); } get meta() { if (this._book in meta) { return meta[this._book]; } return {}; } inVerseSpan(num) { const verses = this.verse; // If verse isn't set, we'll read the whole chapter. if (verses === null) { return true; } if (verses.length === 1) { return num === verses[0]; } if (num >= verses[0] && (num <= verses[1] || verses[1] === 'ff')) { return true; } return false; } } function parseRef(ref) { ref = ref // Limited URL decoding. .replace(/%3[Aa]/, ':') .replace(/\+/, ' ') // Logos will helpfully replace "-" with "–" in its reference spec. .replaceAll(/–/g, '-'); const m = ref.match(/((\d+(\+|\s))?[a-zA-Z]+)(\+|\s)?([0-9]+[-0-9]*)?\:?([0-9]+(-?[0-9]+)?)?/); const book = m[1].toLowerCase(); const chapter = m[5]; const verses = m[6]; return new Refs(book, chapter, verses); } window.Refs = Refs; window.parseRef = parseRef; class RenderScripture { translation = 'BSB'; dialog = null; sel = null; ls = false; ref = {}; constructor(dialog) { this.dialog = dialog; //history.replaceState({dialog: false}, ''); window.addEventListener('popstate', (evt) => { if (this.dialog[0]?.open) { this.closeDialog(); } }); this.dialog[0]?.addEventListener('close', () => { if (history.state && history.state.dialog) { history.back(); } }); this.dialog[0]?.addEventListener('cancel', (evt) => { evt.preventDefault(); history.back(); }); if (hasLocalStorage()) { this.ls = true; this.translation = localStorage.getItem('__translation') || 'BSB'; } const elems = document.querySelectorAll('a[data-scripture]'); elems.forEach((e) => { e.addEventListener('click', (evt) => { this.anchorClick(evt) }); }); const sel = this.dialog[0]?.querySelector('select.translation'); sel?.addEventListener('change', (evt) => { this.txnOnChange(evt) }); this.sel = sel; this.dialog[0]?.addEventListener('click', (evt) => { if (evt.target === this.dialog[0]) { this.closeDialog() } }); this.dialog[0]?.querySelector('button[data-close]')?.addEventListener('click', (evt) => { if (history.state?.dialog) { history.back(); } else { this.closeDialog(); } }); const url = new URL(document.URL); if (url.searchParams.get("cite") !== null) { history.replaceState({dialog: false}, '', ''); this.openDialog(url.searchParams.get("cite"), url.hash.substring(1)); } } anchorClick(evt) { const scripture = evt.target.attributes.getNamedItem('data-scripture')?.value; evt.preventDefault(); this.openDialog(scripture, evt.target.name); } buildTranslationList(sel) { sel?.replaceChildren(); for (const tx in translations) { const testament = meta[this.ref.book].ts; if (translations[tx][2].indexOf(testament) == -1) { continue; } const opt = document.createElement('option'); opt.setAttribute('value', tx); opt.insertAdjacentText('beforeend', translations[tx][0]); if (tx == this.translation) { opt.setAttribute('selected', 'selected'); } sel?.insertAdjacentElement('beforeend', opt); } } closeDialog() { this.dialog[0]?.close(); this.dialog[0]?.classList.add('hidden'); this.dialog[0]?.querySelector('article')?.replaceChildren(); //history.replaceState({}, '', ''); //history.back(); } openDialog(scripture, hash) { const refs = parseRef(scripture); this.ref = refs; this.dialog[0]?.showModal(); this.dialog[0]?.setAttribute('data-scripture', scripture); this.dialog[0]?.classList.remove("hidden"); this.dialog[0]?.querySelector('.spinner svg') .classList.remove('hidden'); this.buildTranslationList(this.sel); this.readScripture(refs); history.pushState({ dialog: true, scripture: scripture.value, tx: this.translation }, '', `?cite=${scripture}#${hash}`); } txnOnChange(evt) { const tx = evt.target.selectedOptions[0].value; this.translation = tx; if (this.ls) { localStorage.setItem('__translation', tx); } const refs = parseRef(this.dialog[0]?.getAttribute('data-scripture')); this.dialog[0]?.querySelector('article')?.replaceChildren(); this.dialog[0]?.querySelector('.spinner svg') .classList.remove('hidden'); this.readScripture(refs); } readScripture(refs) { // Current translation. let tx = this.translation; // Previous translation. const px = this.translation; const book = refs.book; const chapter = refs.chapter; const testament = meta[book].ts; // If the current translation doesn't contain the testament, switch to // the default translation that does. if (translations[tx][2].indexOf(testament) == -1) { tx = defaulttx[testament]; this.translation = tx; } const uri = `https://bible.helloao.org/api/${tx}/${book.toUpperCase()}/${chapter}.json`; fetch(uri) .then((response) => { if (!response.ok) { console.error('query failed'); console.log(response); return; } return response.json(); }) .then((response) => { this.render(response, refs); this.dialog[0]?.querySelector('.spinner svg') .classList.add('hidden'); // Switch translation back if it's forced to a different // translation from book availability. if (this.translation != px) { this.translation = px; } }); } render(response, refs) { const content = response?.chapter?.content; let inSpan = false; if (this.dialog === null || this.dialog === undefined) { return; } const section = document.createElement('section'); const article = this.dialog[0]?.querySelector('article'); let para = document.createElement('p'); const heading = document.createElement('h1'); heading.insertAdjacentText('beforeend', `${refs.fullTitle()}`); article.insertAdjacentElement('beforeend', heading); for (const c of content) { if (c.type === 'heading') { continue; } let verse = document.createElement('span'); switch (c.type) { case 'line_break': if (inSpan) { section.insertAdjacentElement('beforeend', para); para = document.createElement('p'); } break; case 'verse': if (!('number' in c)) { continue; } if (refs.inVerseSpan(c.number)) { verse.insertAdjacentText('beforeend', c.number); verse.classList.add('verse'); para.insertAdjacentElement('beforeend', verse); verse = document.createElement('span'); for (const v of c.content) { if (typeof(v) === 'string') { para.insertAdjacentText('beforeend', v+' '); continue } if ('lineBreak' in v) { if (para.innerHTML.length != 0 || para.innerText.length != 0) { section.insertAdjacentElement('beforeend', para); para = document.createElement('p'); } } if ('text' in v) { para.insertAdjacentText('beforeend', v.text); if ('poem' in v) { para.classList.add('poem-'+v.poem); if (para.innerHTML.length != 0 || para.innerText.length != 0) { section.insertAdjacentElement('beforeend', para); } para = document.createElement('p'); } } } } break; default: console.error('unhandled type:', c.type); } } section.insertAdjacentElement('beforeend', para); article.insertAdjacentElement('beforeend', section); } } export const bindModals = () => { const elems = document.querySelectorAll('a[data-scripture]'); const dialog = document.querySelectorAll('dialog[data-scripture]'); const renderer = new RenderScripture(dialog); };