notes/src/utils/modal.js
Benjamin A. Shelton c47bf0d0e0
Apparently there's a weird behavior in Android Chrome that this fixes.
The bug is that hitting "back" will trigger a cancel event and then the
dialog::backdrop will be removed first. The second "back" press will
remove the dialog or actually trigger history.back(), navigating back in
state.

The fix for this is to intercept the "cancel" event on the dialog and
then handle history management from there. Apparently this issue will be
triggered even if the history API isn't used, and the only way the user
can navigate normally with the dialog present is to actually hook into
the history API.

So, this is kind of a necessary change.

Annoying.

Thanks, Gemini, for the introspection and links.
2026-08-20 11:38:40 -06:00

311 lines
No EOL
10 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { aliases, defaulttx, meta, translations } from './meta.js';
import { hasLocalStorage } from './utils.js';
export const modal = (el) => {
};
function parseRef(ref) {
ref = ref.replace(/%3[Aa]/, ':').replace(/\+/, ' ');
const m = ref.match(/((\d+(\+|\s))?[a-zA-Z]+)(\+|\s)?([0-9]+)?\:?([0-9]+(-?[0-9]+)?)?/);
const book = m[1].toLowerCase();
const chapter = m[5];
const verses = m[6]?.replaceAll(/–/g, '-');
if (book === undefined) {
return {};
}
let refdata = {
ref: ref
};
if (book in aliases) {
refdata.book = aliases[book];
}
refdata.meta = meta[refdata.book];
refdata.fullTitle = () => {
let title = refdata.meta.title+' ';
title += refdata.chapter;
if (refdata.verses?.start > 0) {
title += ':'+refdata.verses.start;
}
if (refdata.verses?.end > 0 && refdata.verses?.end > refdata.verses?.start) {
title += '-'+refdata.verses.end;
}
return title;
};
if (chapter !== undefined) {
refdata['chapter'] = parseInt(chapter);
}
if (verses !== undefined) {
if (verses.indexOf('-') < 0) {
refdata['verses'] = {
start: parseInt(verses),
end: parseInt(verses)
};
} else {
refdata['verses'] = {
start: parseInt(verses.substring(0, verses.indexOf('-'))),
end: parseInt(verses.substring(verses.indexOf('-')+1))
};
}
}
if ('verses' in refdata) {
if (refdata.verses.start < 1) {
refdata.verses.start = 1;
}
if (refdata.verses.end < 1) {
refdata.verses.end = 1;
}
if (refdata.verses.start > refdata.verses.end) {
refdata.verses.end = refdata.verses.start;
}
}
return refdata;
}
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();
}
});
}
anchorClick(evt) {
const scripture = evt.target.attributes.getNamedItem('data-scripture');
const refs = parseRef(scripture.value);
const tx = refs.meta?.tx || 'BSB';
this.ref = refs;
evt.preventDefault();
this.dialog[0]?.showModal();
this.dialog[0]?.setAttribute('data-scripture', scripture.value);
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
}, '', '#dialog');
}
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();
}
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 (!('verses' in refs) || (c.number >= refs.verses.start && c.number <= refs.verses.end)) {
inSpan = true;
} else {
inSpan = false;
}
if (inSpan) {
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);
};