+import { html, render } from 'https://cdn.pika.dev/lit';
+
+const re_directive = /^{(\w+):\s*([^}]+)}$/;
+
+const el_song = document.getElementById('song');
+const song = [];
+
+const directive_handlers = {
+ title: value => {
+ document.getElementById('title').textContent = value;
+ document.title = `${value} - ChordPro Web`;
+ },
+ subtitle: value => document.getElementById('artist').textContent = value,
+ comment: value => song.push(html`<p class="comment">${value}</p>`),
+};
+
+function renderChordpro(text) {
+ let verseLines = null;
+ let verseHasChords = false;
+ song.length = 0;
+
+ for (let line of text.split('\n')) {
+ line = line.trim();
+ if (line.startsWith('#'))
+ continue;
+
+ let m;
+ if ((m = re_directive.exec(line)) !== null) {
+ const [_, directive, value] = m;
+ const handler = directive_handlers[directive];
+ if (handler)
+ handler(value);
+ else
+ console.warn('unknown directive:', line);
+ } else if (line === '') {
+ if (verseLines == null)
+ continue;
+ song.push(html`<p class="verse${verseHasChords ? ' chords' : ''}">${verseLines}</p>`);
+ verseLines = null;
+ verseHasChords = false;
+ } else {
+ if (verseLines == null)
+ verseLines = [];
+
+ // split line into parts on chords
+ const parts = [];
+ line.split(/(\[[^\]]+\])/).forEach(part => parts.push(
+ part[0] == '[' ? html`<span class="chord">${part.slice(1, -1)}</span>` : part
+ ));
+ verseHasChords ||= parts.length > 1;
+ parts.push('\n')
+ verseLines.push(parts);
+ }
+ }
+
+ render(song, el_song);
+}
+
+document.getElementById('open').addEventListener('change', async ev => renderChordpro(await ev.target.files[0].text()));