File size: 8,700 Bytes
39d421b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3610ba2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39d421b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3610ba2
39d421b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
/*
 ساعة المسلم — قراءة الأذكار (الصباح والمساء والنوم).
 - نصوص الأذكار من adhkar_reader_registry.json، ونص الآيات (quran_ref) من بيانات القرآن نفسها.
 - مصمَّمة لقارئ الشاشة: عناوين وفقرات عادية، النص حقيقي وليس aria-label، بلا أزرار أو تركيز يقطع القراءة.
 - للقراءة فقط: لا يوجد تتبّع إنجاز.
*/
(function () {
  'use strict';
  const base = new URL('.', document.currentScript.src);
  let configPromise;
  const node = (tag, text, cls) => { const n = document.createElement(tag); if (text != null) n.textContent = text; if (cls) n.className = cls; return n; };
  const button = (text, action) => { const b = node('button', text); b.type = 'button'; b.addEventListener('click', action); return b; };
  const fmt = (s, v) => String(s).replace(/\{(\w+)\}/g, (_, k) => String(v[k] ?? ''));

  function config() {
    if (!configPromise) configPromise = (async () => {
      const ctl = new AbortController(), t = setTimeout(() => ctl.abort(), 15000);
      try {
        const r = await fetch(new URL('adhkar_reader_registry.json', base), { cache: 'no-store', signal: ctl.signal });
        if (!r.ok) throw Error('adhkar_reader_registry.json HTTP ' + r.status);
        const c = await r.json();
        if (c.version !== 1 || !c.ui || !Array.isArray(c.categories) || !c.categories.length) throw Error('Invalid adhkar registry');
        for (const cat of c.categories) {
          if (!cat.id || !cat.title || !Array.isArray(cat.items)) throw Error('Invalid category');
          for (const it of cat.items) if (!(it.text || it.quran_ref) || !Number.isInteger(it.count) || it.count < 1) throw Error('Invalid dhikr in ' + cat.id);
        }
        return c;
      } finally { clearTimeout(t); }
    })().catch(e => { configPromise = null; throw e; });
    return configPromise;
  }
  const timesText = (ui, n) => n === 1 ? ui.once : n === 2 ? ui.twice : n <= 10 ? fmt(ui.few, { n }) : fmt(ui.many, { n });

  // "2:285-286" -> [[2,285],[2,286]]
  function parseRef(ref) {
    const m = /^(\d{1,3}):(\d{1,3})(?:-(\d{1,3}))?$/.exec(ref); if (!m) return [];
    const out = []; for (let a = Number(m[2]); a <= Number(m[3] || m[2]); a++) out.push(m[1] + ':' + a); return out;
  }
  // Verses come from the Quran data; the spoken text follows the reader's setting for screen readers.
  async function quranParts(ref) {
    const q = window.MuslimClockQuran; if (!q?.loadData) throw Error('quran');
    const source = await q.loadData(), speech = q.speechInfo ? await q.speechInfo() : { mode: 'original', visible: false, original: true, convert: t => t };
    const texts = parseRef(ref).map(k => source.byKey.get(k)?.text);
    if (!texts.length || texts.some(t => !t)) throw Error('verse');
    return { shown: texts.join(' '), spoken: speech.convert(texts.join(' ')), speech };
  }
  function putText(host, shown, spoken, speech) {
    host.lang = 'ar'; host.dir = 'rtl';
    if (speech.visible) host.append(document.createTextNode(spoken));
    else if (speech.original) host.append(document.createTextNode(shown));
    else { const s = node('span', shown); s.setAttribute('aria-hidden', 'true'); host.append(s, node('span', spoken, 'quran-sr-only')); }
  }
  function suggested(c, hour = new Date().getHours()) {
    return c.categories.find(cat => Number.isInteger(cat.from_hour) && Number.isInteger(cat.to_hour) &&
      (cat.from_hour <= cat.to_hour ? hour >= cat.from_hour && hour < cat.to_hour : hour >= cat.from_hour || hour < cat.to_hour));
  }
  // Which group does this alert belong to? Words in the event id / title first, then the alert's own time of day.
  async function categoryFor(info = {}) {
    const c = await config();
    const hay = (String(info.id || '') + ' ' + String(info.title || '')).toLowerCase();
    const hits = c.categories.filter(cat => (cat.keywords || []).some(k => hay.includes(String(k).toLowerCase())));
    if (hits.length === 1) return hits[0];
    const hour = new Date(Number.isFinite(info.at) ? info.at : Date.now()).getHours();
    const pool = hits.length ? { categories: hits } : c;
    return suggested(pool, hour) || suggested(c, hour) || hits[0] || c.categories[0];
  }
  // A button that opens exactly the matching group (no list to choose from).
  async function mountReadButton(parent, info, back) {
    const b = button('…', () => {}); b.disabled = true; parent.append(b);
    try {
      const c = await config(), cat = await categoryFor(info); if (!b.isConnected) return;
      b.textContent = (cat.emoji ? cat.emoji + ' ' : '📿 ') + fmt(c.ui.read_category, { title: cat.title }); b.disabled = false;
      b.onclick = () => open({ back, category: cat.id });
    } catch { if (b.isConnected) b.remove(); }
  }
  function panel(ui, root, back) {
    RegistryApp.openPanel('worship', { title: ui.title, compact: true }, () => {
      document.getElementById('adaptivePopupBody').append(root);
      if (back) document.getElementById('adaptivePopupActions').append(button(ui.back, back));
    });
    const card = document.getElementById('adaptivePopupCard'); if (card) card.dataset.size = 'long';
  }
  const landOn = h => { h.tabIndex = -1; setTimeout(() => h.focus(), 60); };

  async function open(options = {}) {
    let c;
    try { c = await config(); }
    catch (e) { const root = node('div', 'adhkar_reader_registry.json: ' + e.message); root.append(button('↻', () => open(options))); panel({ title: 'adhkar_reader_registry.json', back: '←' }, root, options.back); return; }
    const ui = c.ui, root = node('div', null, 'adhkar-reader'), view = node('div');
    const status = node('p'); status.setAttribute('role', 'status'); status.setAttribute('aria-live', 'polite');
    root.append(view, status);

    function list(land = true) {
      view.replaceChildren();
      const h = node('h3', ui.title); view.append(h, node('p', ui.intro));
      const s = suggested(c);
      if (s) { const b = button(fmt(ui.suggest, { title: s.title }), () => category(s.id)); view.append(b); }
      for (const cat of c.categories) {
        const b = button((cat.emoji ? cat.emoji + ' ' : '') + cat.title, () => category(cat.id));
        b.setAttribute('aria-label', cat.title + ' — ' + fmt(ui.count_items, { n: cat.items.length }));
        view.append(b);
      }
      if (land) landOn(h);
    }
    async function category(id) {
      const cat = c.categories.find(x => x.id === id); if (!cat) return;
      view.replaceChildren();
      const h = node('h3', cat.title); view.append(h);
      if (cat.time_hint) view.append(node('p', cat.time_hint));
      view.append(node('p', fmt(ui.category_note, { n: cat.items.length })));
      const n = cat.items.length;
      for (let i = 0; i < n; i++) {
        const it = cat.items[i], art = node('article', null, 'adhkar-item');
        art.style.cssText = 'border:1px solid var(--cell-border,#888);border-radius:12px;padding:10px;margin:10px 0';
        art.append(node('h4', fmt(ui.item_title, { i: i + 1, n })));
        const text = node('p', null, 'adhkar-text'); text.style.cssText = 'font-size:1.15em;line-height:2';
        if (it.quran_ref) {
          try { const part = await quranParts(it.quran_ref); putText(text, part.shown, part.spoken, part.speech); }
          catch { text.textContent = fmt(ui.quran_error, { ref: it.quran_ref }); }
        } else { text.lang = 'ar'; text.dir = 'rtl'; text.textContent = it.text; }
        art.append(text, node('p', fmt(ui.count, { times: timesText(ui, it.count) })));
        if (it.source) art.append(node('p', fmt(ui.source, { source: it.source }), 'quran-meta'));
        if (it.note) art.append(node('p', fmt(ui.note, { note: it.note }), 'quran-meta'));
        view.append(art);
      }
      view.append(button(ui.to_list, () => list()));
      landOn(h);
    }
    panel(ui, root, options.back);
    if (options.category) await category(options.category); else list();
  }

  async function mountEntry(parent, back) {
    const entry = button('…', () => {}); entry.disabled = true; parent.append(entry);
    try { const c = await config(); if (!entry.isConnected) return; entry.textContent = c.ui.open; entry.disabled = false; entry.onclick = () => open({ back }); }
    catch (e) { if (entry.isConnected) { entry.textContent = 'adhkar_reader_registry.json: ' + e.message; entry.disabled = false; entry.onclick = () => { entry.remove(); mountEntry(parent, back); }; } }
  }
  window.MuslimClockAdhkarReader = Object.freeze({ open, mountEntry, mountReadButton, categoryFor, categories: async () => (await config()).categories });
})();