Asem75 commited on
Commit
fc3effa
·
verified ·
1 Parent(s): 561c8ae

Upload 2 files

Browse files
Files changed (1) hide show
  1. registry_app.js +62 -801
registry_app.js CHANGED
@@ -1,803 +1,64 @@
1
- const RegistryApp = (() => {
2
- const files = ['visual_states_registry','fiqh_time_registry','worship_fiqh_registry','islamic_events_registry','religious_content_registry','contextual_knowledge_registry','on_this_day_registry','user_time_markers_registry','announcements_guidance_registry','content_channels_registry','astronomy_events_registry','external_sources_registry'];
3
- const R = {}; let ui, visual, layout, lastFocus, currentKind, view, initialScroll = false;
4
- const $ = id => document.getElementById(id);
5
- const registry = name => R[name + '_registry'] || {rules:[],boundaries:[],madhhabs:{},legacy_rule_map:[],items:[],events:[],channels:[],providers:[],event_types:[],marker_types:{}};
6
- const array = value => Array.isArray(value) ? value : value ? [value] : [];
7
- const make = (tag,text) => {const e=document.createElement(tag);if(text!=null)e.textContent=text;return e;};
8
- const title = x => x.display?.title || x.content?.title || x.title_ar || x.title || x.label_ar || x.label || x.name || '';
9
- const screen = kind => ui.screensConfig.find(x=>x.id===kind);
10
- const noticeRoutes=()=>visual.runtime_styles.notice_screen_routes||{};
11
- const safeScreen=kind=>screen(kind)||screen(noticeRoutes().default)||ui.screensConfig[0];
12
- const reminderScreen=x=>noticeRoutes().reminder_types?.[x?.type]||noticeRoutes().default||'worship';
13
- const eventScreen=x=>x?.screen_id||noticeRoutes().content_actions?.[x?.action]||noticeRoutes().default||'worship';
14
- const rule = id => registry('worship_fiqh').rules.find(x=>x.id===id);
15
- const boundary = id => registry('fiqh_time').boundaries.find(x=>x.id===id);
16
- function icon(id){return visual.marker_icons?.[id]?.emoji || visual.worship_icons[id]?.emoji || visual.prayer_icons[id]?.emoji || visual.solar_icons[id]?.emoji || '';}
17
- function ruleTitle(x){return ui.ruleTitles[x.id] || visual.prayer_icons[x.id]?.label || visual.worship_icons[x.id]?.label || title(x) || ui.unknownTerm;}
18
- function term(value){
19
- if(typeof value!=='string')return String(value);
20
- if(ui.terms[value])return ui.terms[value];
21
- if(boundary(value))return boundary(value).label;
22
- // Translate identifier tokens even inside Arabic variant descriptions.
23
- return value.replace(/[a-z][a-z0-9]*(?:_[a-z0-9]+)+/g,key=>ui.terms[key]||boundary(key)?.label||ui.unknownTerm);
24
- }
25
- function textLines(data){
26
- if(!data)return '';
27
- if(typeof data==='string')return term(data);
28
- return Object.entries(data).filter(([k])=>ui.fields[k]).map(([k,v])=>ui.fields[k]+': '+term(v)).join('\n');
29
- }
30
- function button(label,action){const b=make('button',label);b.type='button';b.addEventListener('click',action);return b;}
31
- function safeURL(raw){try{const u=new URL(raw,location.href);return ['http:','https:'].includes(u.protocol)?u.href:null;}catch{return null;}}
32
- function link(parent,label,url){const href=safeURL(url);if(!href)return;const a=make('a',label);a.href=href;a.target='_blank';a.rel='noopener noreferrer';parent.appendChild(a);}
33
- function para(text){if(text)$('adaptivePopupBody').appendChild(make('p',text));}
34
- function show(kind,data,render){
35
- const overlay=$('adaptivePopup');if(overlay.hidden)lastFocus=document.activeElement;
36
- const target=safeScreen(kind);kind=target.id;currentKind=kind; view=()=>show(kind,data,render);
37
- $('adaptivePopupKind').textContent=target.title;
38
- $('adaptivePopupKind').hidden=data.compact===true;
39
- $('adaptivePopupTitle').textContent=data.title||'';
40
- $('adaptivePopupMedia').textContent=data.media||icon(target.icon);
41
- $('adaptivePopupMedia').hidden=data.compact===true;
42
- $('adaptivePopupBody').replaceChildren();$('adaptivePopupActions').replaceChildren();
43
- para(data.text);if(render)render();
44
- const n=$('adaptivePopupBody').textContent.length;
45
- $('adaptivePopupCard').dataset.size=n<90?'short':n<420?'medium':'long';
46
- overlay.hidden=false;document.body.style.overflow='hidden';$('adaptivePopupClose').focus();
47
- $('adaptivePopupCard').scrollTop=0;$('adaptivePopupBody').scrollTop=0;
48
- }
49
- function close(){ $('adaptivePopup').hidden=true;document.body.style.overflow='';lastFocus?.focus(); }
50
- function back(fn){$('adaptivePopupActions').appendChild(button(ui.back,fn));}
51
- function home(kind){show(kind,{title:screen(kind).title,text:ui.catalogue},()=>{
52
- screen(kind).groups.forEach(group=>$('adaptivePopupBody').appendChild(button(ui.groupTitles[group],()=>list(kind,group))));
53
- });}
54
- function records(group){
55
- switch(group){
56
- case 'worship': return registry('worship_fiqh').rules;
57
- case 'events': return registry('islamic_events').events.filter(x=>x.enabled!==false);
58
- case 'time': return registry('fiqh_time').boundaries;
59
- case 'markers': return Object.entries(registry('user_time_markers').marker_types).map(([id,x])=>({id,...x}));
60
- case 'announcements': return registry('announcements_guidance').enabled===false?[]:registry('announcements_guidance').items.filter(x=>x.enabled!==false);
61
- case 'channels': return registry('content_channels').channels;
62
- case 'knowledge': return registry('contextual_knowledge').items;
63
- case 'history': return registry('on_this_day').events;
64
- case 'astronomy': return registry('astronomy_events').event_types.filter(x=>x.enabled!==false);
65
- case 'quran': return registry('external_sources').providers.filter(x=>array(x.capabilities).some(c=>/^(quran_text|ayah_audio|recitations|audio_editions)$/.test(c)));
66
- case 'providers': return registry('external_sources').providers;
67
- default:return [];
68
- }
69
- }
70
- function list(kind,group){
71
- if(group==='markers'){remindersHome();return;}
72
- show(kind,{title:ui.groupTitles[group],text:group==='history'?ui.historyNote:group==='markers'?ui.markerNote:''},()=>{
73
- const rows=records(group);if(!R[ui.groupRegistry[group]+'_registry'])para(ui.unavailable);else if(!rows.length)para(ui.empty);
74
- rows.forEach(x=>$('adaptivePopupBody').appendChild(button(group==='worship'?ruleTitle(x):title(x),()=>detail(kind,group,x))));
75
- back(()=>home(kind));
76
- });
77
- }
78
- function ruleText(x){
79
- const parts=[textLines(x.common),x.note,x.critical,textLines(x.trigger)];
80
- Object.entries(x.madhhab||{}).forEach(([k,v])=>parts.push(registry('worship_fiqh').madhhabs[k]+':\n'+textLines(v)));
81
- array(x.windows).forEach(w=>parts.push(textLines(w)));
82
- return parts.filter(Boolean).map(term).join('\n\n');
83
- }
84
- function related(kind,x){
85
- const authority=x.authority_link||{};
86
- const ruleIds=[...array(authority.rule_id),...array(authority.rule_ids)];
87
- const timeIds=[...array(authority.boundary_id),...array(authority.boundary_ids),...array(authority.time_boundaries)];
88
- registry('religious_content').legacy_rule_map.filter(m=>m.legacy_id===x.id).forEach(m=>{
89
- ruleIds.push(...array(m.target_rule_id),...array(m.target_rule_ids),...array(m.worship_rule_id));
90
- timeIds.push(...array(m.target_boundary_id),...array(m.time_boundaries));
91
- });
92
- if(rule(x.id)){
93
- registry('religious_content').legacy_rule_map.filter(m=>[...array(m.target_rule_id),...array(m.target_rule_ids),...array(m.worship_rule_id)].includes(x.id)).forEach(m=>timeIds.push(...array(m.time_boundaries),...array(m.target_boundary_id)));
94
- }
95
- const returnView=view;
96
- [...new Set(ruleIds)].map(rule).filter(Boolean).forEach(r=>$('adaptivePopupBody').appendChild(button(ui.related+' — '+ruleTitle(r),()=>detail(kind,'worship',r,returnView))));
97
- [...new Set(timeIds)].map(boundary).filter(Boolean).forEach(b=>$('adaptivePopupBody').appendChild(button(ui.related+' — '+title(b),()=>detail(kind,'time',b,returnView))));
98
- }
99
- function detail(kind,group,x,returnView){
100
- if(group==='events'&&isAdhkar(x)){adhkarSettings(x.id);return;}
101
- let text=x.display?.text||x.content?.text||x.text||x.summary_ar||x.note||'';
102
- if(group==='time'){boundaryInfo(x,null,returnView||(()=>list(kind,group)));return;}
103
- if(group==='worship')text=ruleText(x);
104
- if(group==='quran'||group==='providers')text=ui.providerNote;
105
- if(group==='channels')text=ui.channelNote;
106
- if(group==='astronomy')text=ui.astronomyNote+(x.religious_relation?.note?'\n\n'+x.religious_relation.note:'');
107
- if(group==='markers'){reminderChoose();return;}
108
- if(x.date_note_ar)text+='\n\n'+x.date_note_ar;
109
- show(kind,{title:group==='worship'?ruleTitle(x):title(x),text,media:icon(x.icon_id||x.id)||icon(visual.event_action_mapping[x.action])},()=>{
110
- // References are links, never executable HTML from registries.
111
- if(group==='worship')array(x.sources).forEach(id=>{const s=registry('worship_fiqh').sources[id];if(s?.url)link($('adaptivePopupBody'),s.title,s.url);});
112
- if(group==='quran'||group==='providers')link($('adaptivePopupBody'),ui.source+' — '+x.name,x.documentation_url||x.base_url);
113
- if(x.source?.url)link($('adaptivePopupBody'),x.source.name||ui.source,x.source.url);
114
- if(group==='events'){
115
- if(x.calendar_rule?.requires_month_confirmation){para(ui.monthConfirmation.required);$('adaptivePopupActions').appendChild(button(ui.calendarSettings,calendarSettings));}
116
- if(x.user_schedule)$('adaptivePopupActions').appendChild(button(ui.seasonSchedule.title,()=>seasonSettings(x)));
117
- }
118
- array(x.references).forEach(r=>{if(typeof r==='string')para(r);else if(r.url)link($('adaptivePopupBody'),r.title||ui.source,r.url);});
119
- related(kind,x);back(returnView||(()=>list(kind,group)));
120
- });
121
- }
122
- let calculationMethod=null, prayerEngineReady=false;
123
- let observer=null, madhhab, solarDays=[], solarPeriods=[], timelineStart=0, timelineViewDate=null, lastSolarDay='', frameTimer;
124
- const getSaved=(key,fallback)=>{try{return JSON.parse(localStorage.getItem(key))??fallback;}catch{return fallback;}};
125
- const save=(key,value)=>{try{localStorage.setItem(key,JSON.stringify(value));}catch{}};
126
- function validLocation(x){return x&&Number.isFinite(x.lat)&&Number.isFinite(x.lng)&&Math.abs(x.lat)<=90&&Math.abs(x.lng)<=180;}
127
- function profile(){return registry('fiqh_time').calculation_profile;}
128
- function timeText(ms){return new Date(ms).toLocaleTimeString(document.documentElement.lang,{hour:'numeric',minute:'2-digit',hour12:true});}
129
- function dateKey(ms){const d=new Date(ms);return d.getFullYear()+'-'+d.getMonth()+'-'+d.getDate();}
130
- function calculationConfig(){return registry('fiqh_time').prayer_calculation;}
131
- function methodChoice(){const c=calculationConfig();return c?.methods.find(x=>x.id===calculationMethod);}
132
- function prayerParameters(lib,choice){
133
- let parameters;
134
- if(choice.engine_mode==='custom_angles'){
135
- parameters=lib.CalculationMethod.Other();
136
- parameters.method=choice.id;
137
- parameters.fajrAngle=Number(choice.fajr_angle);
138
- parameters.ishaAngle=Number(choice.isha_angle);
139
- parameters.adjustments={...parameters.adjustments,...(choice.adjustments||{})};
140
- }else{
141
- const factory=lib.CalculationMethod[choice.id];
142
- if(typeof factory!=='function')throw Error('unsupported prayer method');
143
- parameters=factory();
144
- }
145
- return parameters;
146
- }
147
- async function loadPrayerEngine(){
148
- const c=calculationConfig();if(!c)return;calculationMethod=getSaved(c.storage_key,c.default_method);
149
- if(calculationMethod!==c.legacy_option.id&&!c.methods.some(x=>x.id===calculationMethod))calculationMethod=c.default_method;
150
- if(window.adhan){prayerEngineReady=true;return;}
151
- await new Promise(resolve=>{const script=document.createElement('script');let finished=false;
152
- const done=()=>{if(finished)return;finished=true;clearTimeout(timer);prayerEngineReady=Boolean(window.adhan);resolve();};
153
- const timer=setTimeout(done,c.engine.timeout_ms);script.src=c.engine.url;script.onload=done;script.onerror=done;document.head.appendChild(script);
154
- });
155
- }
156
- function applyPrayerMethod(days){
157
- const choice=methodChoice();if(!choice)return;
158
- const c=calculationConfig(),lib=window.adhan;
159
- for(const d of days){
160
- if(!prayerEngineReady){d.methodUnavailable=true;continue;}
161
- try{
162
- const parameters=prayerParameters(lib,choice);
163
- const asrRule=rule('asr'),id=asrRule.madhhab?.[madhhab]?.start||asrRule.common?.start;
164
- const factor=profile().boundaries[id]?.factor,key=c.shadow_factor_to_madhab[String(factor)];
165
- if(!key||!lib.Madhab?.[key])throw Error('unsupported madhhab binding');
166
- parameters.madhab=lib.Madhab[key];
167
- const schoolBinding=c.madhhab_engine_bindings?.[madhhab];
168
- if(choice.id==='MoonsightingCommittee'&&schoolBinding?.moonsighting_shafaq&&lib.Shafaq?.[schoolBinding.moonsighting_shafaq])parameters.shafaq=lib.Shafaq[schoolBinding.moonsighting_shafaq];
169
- const confirmation=getSaved(c.ramadan_interval.storage_key,null);
170
- if(choice.id===c.ramadan_interval.method&&confirmation?.enabled&&confirmation.day===dateKey(new Date(new Date(d.day).getUTCFullYear(),new Date(d.day).getUTCMonth(),new Date(d.day).getUTCDate()).getTime()))parameters.ishaInterval=c.ramadan_interval.minutes;
171
- const utc=new Date(d.day),date=new Date(utc.getUTCFullYear(),utc.getUTCMonth(),utc.getUTCDate());
172
- const coordinates=new lib.Coordinates(observer.lat,observer.lng),times=new lib.PrayerTimes(coordinates,date,parameters);
173
- const next=new Date(date);next.setDate(next.getDate()+1);const tomorrow=new lib.PrayerTimes(coordinates,next,parameters);
174
- const number=value=>Number.isFinite(value?.getTime())?value.getTime():null;
175
- for(const [id,key] of Object.entries(c.output_bindings))d.boundaries[id]=number(times[key]);
176
- d.boundaries.true_dawn=d.boundaries.fajr;d.boundaries.next_true_dawn=number(tomorrow.fajr);
177
- for(const [id,def] of Object.entries(profile().boundaries))if(def.op==='fraction'){
178
- const a=d.boundaries[def.from],b=d.boundaries[def.to];d.boundaries[id]=a!=null&&b!=null?a+def.fraction*(b-a):null;
179
  }
180
- d.calculationMethod=choice.id;
181
- }catch{d.methodUnavailable=true;}
182
- }
183
- }
184
- function recalculate(){
185
- solarDays=[];solarPeriods=[];
186
- if(observer&&profile()&&registry('worship_fiqh').rules.length){
187
- for(const day of timelineCalculationDays())solarDays.push(SolarEngine.day(day,observer,profile(),registry('worship_fiqh'),madhhab));
188
- applyPrayerMethod(solarDays);
189
- solarPeriods=SolarEngine.periods(solarDays,profile(),registry('worship_fiqh'),madhhab,visual.runtime_styles,methodChoice()?calculationConfig().period_bindings:null);
190
- }
191
- lastSolarDay=dateKey(Date.now());buildNotices();buildRuler();tickSolar();
192
- }
193
- function timelineCalculationDays(){
194
- const days=new Set();
195
- for(const anchor of [Date.now(),timelineViewDate??Date.now()]){
196
- const d=new Date(anchor),base=Date.UTC(d.getFullYear(),d.getMonth(),d.getDate());
197
- for(let i=-2;i<=3;i++)days.add(base+i*86400000);
198
- }
199
- return [...days].sort((a,b)=>a-b);
200
- }
201
- function configureLocation(){
202
- show('worship',{title:ui.location,text:ui.deviceTime},()=>{
203
- const body=$('adaptivePopupBody');
204
- const p=profile();if(!p){para(ui.missingSolar);return;}
205
- const config=calculationConfig();if(config){
206
- const method=make('select');[config.legacy_option,...config.methods].forEach(x=>{const opt=make('option',x.label);opt.value=x.id;method.appendChild(opt);});method.value=calculationMethod;
207
- const field=make('label',ui.calculationMethod);field.appendChild(method);body.appendChild(field);
208
- const methodDetails=make('div');body.appendChild(methodDetails);
209
- const describeMethod=()=>{methodDetails.replaceChildren();const choice=methodChoice();if(choice?.note_ar)methodDetails.appendChild(make('p',choice.note_ar));if(choice)methodDetails.appendChild(make('p',ui.madhhabCalculationActive+' — '+registry('worship_fiqh').madhhabs[madhhab]));if(choice?.solar_sunset_is_independent)methodDetails.appendChild(make('p',ui.sunsetSeparation));if(choice?.daily_reference_url)link(methodDetails,ui.officialDailyTimes||ui.source,choice.daily_reference_url);if(choice?.method_reference_url)link(methodDetails,ui.calculationReference||ui.source,choice.method_reference_url);};
210
- method.addEventListener('change',()=>{calculationMethod=method.value;save(config.storage_key,calculationMethod);describeMethod();recalculate();});describeMethod();
211
- const ramadan=make('input');ramadan.type='checkbox';const confirmation=getSaved(config.ramadan_interval.storage_key,null);ramadan.checked=confirmation?.enabled&&confirmation.day===dateKey(Date.now());const row=make('label',ui.ramadanInterval);row.appendChild(ramadan);body.appendChild(row);
212
- ramadan.addEventListener('change',()=>{save(config.ramadan_interval.storage_key,{enabled:ramadan.checked,day:dateKey(Date.now())});recalculate();});
213
- para(ui.calculationMethodNote);if(!prayerEngineReady)para(ui.prayerEngineUnavailable);
214
- }
215
- body.appendChild(button(ui.gps,()=>{
216
- if(!navigator.geolocation){para(ui.locationFailed);return;}
217
- const status=make('p',ui.locating);body.appendChild(status);
218
- navigator.geolocation.getCurrentPosition(pos=>{
219
- observer={lat:pos.coords.latitude,lng:pos.coords.longitude,name:ui.gps};save('clock_observer_v1',observer);recalculate();close();
220
- },()=>status.textContent=ui.locationFailed,{timeout:15000,maximumAge:300000});
221
- }));
222
- p.locations.forEach(loc=>body.appendChild(button(loc.name,()=>{observer={...loc};save('clock_observer_v1',observer);recalculate();close();})));
223
- const lat=make('input'),lng=make('input');
224
- [[lat,ui.latitude,-90,90,observer?.lat],[lng,ui.longitude,-180,180,observer?.lng]].forEach(([e,label,min,max,val])=>{
225
- e.type='number';e.step='any';e.min=min;e.max=max;e.value=val??'';const field=make('label',label);field.appendChild(e);body.appendChild(field);
226
- });
227
- const select=make('select');Object.entries(registry('worship_fiqh').madhhabs||{}).forEach(([id,label])=>{const opt=make('option',label);opt.value=id;select.appendChild(opt);});select.value=madhhab;
228
- const field=make('label',ui.madhhab);field.appendChild(select);body.appendChild(field);
229
- select.addEventListener('change',()=>{madhhab=select.value;save('clock_madhhab_v1',madhhab);recalculate();});
230
- body.appendChild(button(ui.apply,()=>{
231
- if(lat.value===''||lng.value===''){para(ui.invalidLocation);return;}
232
- const loc={lat:Number(lat.value),lng:Number(lng.value)};if(!validLocation(loc)){para(ui.invalidLocation);return;}
233
- observer=loc;madhhab=select.value;save('clock_observer_v1',observer);save('clock_madhhab_v1',madhhab);recalculate();close();
234
- }));
235
- para(p.note_ar);
236
- });
237
- }
238
- function inHour(start){return solarPeriods.filter(p=>p.start<start+3600000&&(p.end>start||(p.point&&p.start>=start)));}
239
- function periodIcon(p){const key=visual.runtime_styles.rule_icons[p.id]||p.id;return icon(key)||visual.timeline_states[key]?.emoji||visual.timeline_states[p.state]?.emoji||'';}
240
- function boundaryKnowledge(id){
241
- return registry('contextual_knowledge').items.filter(x=>{const a=x.authority_link||{};return [...array(a.boundary_id),...array(a.boundary_ids),...array(a.time_boundaries)].includes(id);});
242
- }
243
- function boundaryKnowledgeScreen(def,returnView){
244
- show('content',{title:title(def),text:ui.knowledgeTopics},()=>{
245
- boundaryKnowledge(def.id).forEach(x=>$('adaptivePopupBody').appendChild(button(title(x),()=>detail('content','knowledge',x,()=>boundaryKnowledgeScreen(def,returnView)))));
246
- back(returnView);
247
- });
248
- }
249
- function boundaryInfo(def,t,returnView){
250
- const goBack=returnView||(()=>home('worship'));
251
- const summary=registry('contextual_knowledge').boundary_summaries?.[def.id];
252
- const entryRule=!methodChoice()&&(visual.runtime_styles.boundary_entry_rule_ids||[]).map(rule).find(r=>(r?.madhhab?.[madhhab]?.start||r?.common?.start)===def.id);
253
- show('worship',{title:title(def),text:t==null?'':timeText(t),media:entryRule?icon(visual.runtime_styles.rule_icons[entryRule.id]||entryRule.id):icon(def.id)},()=>{
254
- para(summary?.text||def.relation||def.note||ui.empty);
255
- if(summary?.estimate)para(summary.estimate);
256
- if(summary?.source_url)link($('adaptivePopupBody'),ui.source,summary.source_url);
257
- for(const id of visual.runtime_styles.boundary_entry_rule_ids||[]){const r=rule(id),choice=r?.madhhab?.[madhhab];
258
- if(!methodChoice()&&(choice?.start||r?.common?.start)===def.id)para(icon(visual.runtime_styles.rule_icons[r.id]||r.id)+' '+ruleTitle(r)+' — '+registry('worship_fiqh').madhhabs[madhhab]);
259
- }
260
- if(boundaryKnowledge(def.id).length)$('adaptivePopupActions').appendChild(button(ui.moreKnowledge,()=>boundaryKnowledgeScreen(def,()=>boundaryInfo(def,t,goBack))));
261
- back(goBack);
262
- });
263
- }
264
- function untimedMarkers(){return array(registry('contextual_knowledge').untimed_boundary_markers);}
265
- function markerButton(m,returnView){const def=boundary(m.boundary_id);return def?button(m.caption,()=>boundaryInfo(def,null,returnView)):null;}
266
- function periodTitle(p){return (p.displayEstimate?.label_ar||ruleTitle(p.rule))+(p.preference?' — '+ui.preferredPeriod:'');}
267
- function periodTime(p){return p.point?ui.calculatedBoundary+' — '+timeText(p.start)+'\n'+ui.pointNote:ui.from+' '+timeText(p.start)+' '+ui.to+' '+timeText(p.end)+(p.displayEndEstimate?' — '+p.displayEndEstimate.end_label_ar:'')+(p.displayEstimate?'\n'+ui.estimatedWindow:'');}
268
- function applyStatePaint(el,stateId){
269
- const s=visual.timeline_states[stateId];el.style.backgroundColor=s.color;el.style.color=s.text_color;
270
- if(s.pattern==='diagonal')el.style.backgroundImage='repeating-linear-gradient(135deg,transparent 0 6px,currentColor 6px 7px,transparent 7px 12px)';
271
- }
272
- function hourSettings(start){
273
- show('worship',{title:hourAccessibleLabel(new Date(start).getHours()),compact:true},()=>{
274
- $('adaptivePopupBody').appendChild(button(ui.adhkar.title,()=>adhkarHome(start)));
275
- $('adaptivePopupBody').appendChild(button(ui.worshipSchedules,()=>list('worship','events')));
276
- $('adaptivePopupActions').appendChild(button(ru().add,()=>reminderChoose(start)));
277
- $('adaptivePopupBody').appendChild(button(ru().settings,reminderSettings));
278
- $('adaptivePopupBody').appendChild(button(ru().tools,remindersHome));
279
- $('adaptivePopupBody').appendChild(button(ui.location,configureLocation));$('adaptivePopupBody').appendChild(button(ui.calendarSettings,calendarSettings));
280
- });
281
- }
282
- function periodDetails(p){
283
- show('worship',{title:periodTitle(p),text:periodTime(p),media:periodIcon(p)},()=>{
284
- para(visual.timeline_states[p.state].label+' — '+registry('worship_fiqh').madhhabs[madhhab]);
285
- if(p.conditional)para(p.activation==='after_prayer'?ui.conditionalWindow:ui.boundaryRestrictionWindow);
286
- para((boundary(p.startId)?.label||ui.terms[p.startId]||p.startId)+' ← '+(p.displayEndEstimate?.end_label_ar||boundary(p.endId)?.label||ui.terms[p.endId]||p.endId));if(p.calculationMethod)para(ui.methodTime+' — '+methodChoice()?.label);
287
- if(p.displayEstimate?.note_ar)para(p.displayEstimate.note_ar);
288
- if(p.rule.category===visual.runtime_styles.restriction_category)para(ui.solarRestrictionEstimate);
289
- $('adaptivePopupActions').appendChild(button(ui.fullRuling,()=>detail('content','worship',p.rule,()=>periodDetails(p))));
290
- });
291
- }
292
- function hourDetails(start){
293
- const rows=inHour(start),end=start+3600000;
294
- show('worship',{title:ui.hour+' — '+timeText(start),text:new Date(start).toLocaleDateString(document.documentElement.lang)},()=>{
295
- $('adaptivePopupActions').appendChild(button(ru().add,()=>reminderChoose(start)));
296
- if(!observer){para(ui.chooseLocation);$('adaptivePopupActions').appendChild(button(ui.location,configureLocation));return;}
297
- if(!profile()){para(ui.missingSolar);return;}
298
- para(ui.deviceTime+' · '+registry('worship_fiqh').madhhabs[madhhab]);
299
- const unique=new Map();rows.forEach(p=>unique.set(p.id+'-'+p.start+'-'+(p.preference||''),p));
300
- if(!rows.length)para(ui.noPeriod);
301
- for(const p of unique.values()){
302
- const state=visual.timeline_states[p.state];
303
- const card=button(periodIcon(p)+' '+periodTitle(p)+'\n'+state.label+'\n'+periodTime(p),()=>{
304
- show('worship',{title:periodTitle(p),text:periodTime(p),media:periodIcon(p)},()=>{
305
- para(visual.timeline_states[p.state].label+' — '+registry('worship_fiqh').madhhabs[madhhab]);
306
- if(p.conditional)para(p.activation==='after_prayer'?ui.conditionalWindow:ui.boundaryRestrictionWindow);
307
- $('adaptivePopupActions').appendChild(button(ui.fullRuling,()=>detail('content','worship',p.rule,()=>hourDetails(start))));
308
- back(()=>hourDetails(start));
309
- });
310
- });card.style.borderInlineStart='8px solid '+state.color;const swatch=make('span');swatch.className='state-swatch';swatch.setAttribute('aria-hidden','true');applyStatePaint(swatch,p.state);card.prepend(swatch);$('adaptivePopupBody').appendChild(card);
311
- }
312
- const points=[];for(const d of solarDays)for(const def of registry('fiqh_time').boundaries){const t=d.boundaries[def.id];if(t!=null&&t>=start&&t<end)points.push({def,t});}
313
- points.sort((a,b)=>a.t-b.t).forEach(({def,t})=>{
314
- untimedMarkers().filter(m=>m.before_boundary_id===def.id).forEach(m=>{const b=markerButton(m,()=>hourDetails(start));if(b)$('adaptivePopupBody').appendChild(b);});
315
- const b=button(icon(def.id)+' '+def.label+' — '+timeText(t),()=>boundaryInfo(def,t,()=>hourDetails(start)));b.dataset.boundaryId=def.id;$('adaptivePopupBody').appendChild(b);
316
- });
317
- matchingEvents(start,end).forEach(x=>$('adaptivePopupBody').appendChild(button(title(x),()=>detail('worship','events',x,()=>hourDetails(start)))));
318
- para(ui.conditionalNote);para(ui.estimated);
319
- });
320
- }
321
- function hijriParts(ms){
322
- const id=(visual.runtime_styles.current_time_calendars||[]).find(c=>c.adjustable)?.id||'islamic';
323
- return HijriCalendarEngine.parts(ms,{calendarId:id,offsetDays:getSaved('clock_calendar_adjustment_v1',0),maxOffsetDays:visual.runtime_styles.calendar_adjustment_limit,confirmations:getSaved(registry('islamic_events').calendar_confirmation?.storage_key,[])});
324
- }
325
- function eventCalendarMatches(event,ms,forBlocking=false){
326
- return HijriCalendarEngine.matches(event,ms,{parts:hijriParts,forBlocking});
327
- }
328
- function eventBlockedOn(event,ms){return (event.blocks_if||[]).some(id=>{const blocker=registry('islamic_events').events.find(e=>e.id===id&&e.enabled!==false);return blocker?eventCalendarMatches(blocker,ms,true):false;});}
329
- function eventEnabled(event){
330
- if(event.enabled===false)return false;const activation=event.activation;
331
- if(isAdhkar(event))return adhkarPreference(event).enabled;
332
- if(activation?.mode==='user_configurable')return Boolean(getSaved(activation.storage_key,activation.default_enabled===true));
333
- return true;
334
- }
335
- const adhkarConfig=()=>registry('islamic_events').reminder_preferences;
336
- const isAdhkar=event=>Boolean(adhkarConfig()&&event.action===adhkarConfig().event_action);
337
- const adhkarReady=()=>adhkarConfig()?.ui_contract_version===2;
338
- function seasonPreference(event){return getSaved(registry('islamic_events').scheduling_policy.season_preferences_key,{})[event.id]||{enabled:event.user_schedule?.default_enabled===true,weekdays:[],time:''};}
339
- function seasonSettings(event){
340
- const labels=ui.seasonSchedule,p=seasonPreference(event);
341
- show('worship',{title:title(event),text:labels.note},()=>{
342
- const enabled=reminderField(labels.enable,'checkbox','');enabled.checked=p.enabled;
343
- const weekdays=labels.weekdays.map((label,index)=>{const field=reminderField(label,'checkbox','');field.checked=p.weekdays.includes(index);return field;});
344
- const time=reminderField(labels.time,'time',p.time);
345
- $('adaptivePopupActions').appendChild(button(ru().save,()=>{
346
- const selected=weekdays.flatMap((field,index)=>field.checked?[index]:[]);
347
- if(enabled.checked&&(!selected.length||!/^([01]\d|2[0-3]):[0-5]\d$/.test(time.value))){para(labels.invalid);return;}
348
- const key=registry('islamic_events').scheduling_policy.season_preferences_key,state=getSaved(key,{});
349
- state[event.id]={enabled:enabled.checked,weekdays:selected,time:time.value};
350
- try{localStorage.setItem(key,JSON.stringify(state));}catch{para(ru().storageError);return;}
351
- buildNotices();buildRuler();detail(eventScreen(event),'events',event);
352
- }));back(()=>detail(eventScreen(event),'events',event));
353
- });
354
- }
355
- function adhkarPreference(event){
356
- const c=adhkarConfig(),saved=getSaved(c.storage_key,{}),value=saved[event.id];
357
- return {enabled:Boolean(getSaved(event.activation.storage_key,event.activation.default_enabled)),mode:c.default_mode,trigger:event.triggers[0].when,offset:0,time:'',sound:c.default_sound,...(value&&typeof value==='object'?value:{})};
358
- }
359
- function adhkarHome(selectedHour){show('worship',{title:ui.adhkar.title,text:ui.adhkar.note},()=>{
360
- if(!adhkarReady()){para(ui.adhkar.unavailable);return;}
361
- for(const event of registry('islamic_events').events.filter(isAdhkar)){
362
- const p=adhkarPreference(event);
363
- $('adaptivePopupBody').appendChild(button(title(event)+' — '+(p.enabled?ui.adhkar.enabled:ui.adhkar.disabled),()=>adhkarSettings(event.id,selectedHour)));
364
- }
365
- $('adaptivePopupActions').appendChild(button(ui.adhkar.custom,()=>reminderForm('adhkar',selectedHour)));
366
- back(()=>remindersHome(selectedHour));
367
- });}
368
- function adhkarSettings(id,selectedHour){
369
- const event=registry('islamic_events').events.find(e=>e.id===id&&isAdhkar(e));if(!event)return;
370
- const c=adhkarConfig(),p=adhkarPreference(event),a=ui.adhkar;
371
- show('worship',{title:title(event),text:a.note},()=>{
372
- const enabled=reminderField(a.enable,'checkbox','');enabled.checked=p.enabled;
373
- const mode=reminderSelect(a.mode,c.modes.map(id=>[id,a.modes[id]]),p.mode);
374
- const options=c.prayer_triggers.map(id=>[id,boundary(profile()?.notice_runtime?.trigger_bindings[id]?.boundary)?.label||id]);
375
- const trigger=reminderSelect(a.prayer,options,p.trigger),offset=reminderField(a.offset,'number',p.offset);
376
- offset.min=0;offset.max=c.offset_limit_minutes;
377
- const clock=reminderField(a.clock,'time',p.time),sound=reminderField(a.sound,'checkbox','');sound.checked=p.sound;
378
- const sync=()=>{const custom=mode.value==='clock';trigger.parentElement.hidden=custom;offset.parentElement.hidden=custom;clock.parentElement.hidden=!custom;};mode.addEventListener('change',sync);sync();
379
- para(a.locationNote);para(ru().closedBrowserNote);
380
- $('adaptivePopupActions').appendChild(button(ru().save,()=>{
381
- const n=Number(offset.value),validClock=/^([01]\d|2[0-3]):[0-5]\d$/.test(clock.value);
382
- if(enabled.checked&&((mode.value==='clock'&&!validClock)||(mode.value==='prayer_relative'&&(!c.prayer_triggers.includes(trigger.value)||!Number.isFinite(n)||n<0||n>c.offset_limit_minutes)))){para(a.invalid);return;}
383
- const state=getSaved(c.storage_key,{});state[id]={enabled:enabled.checked,mode:mode.value,trigger:trigger.value,offset:n,time:clock.value,sound:sound.checked};
384
- try{localStorage.setItem(c.storage_key,JSON.stringify(state));}catch{para(a.storageError);return;}
385
- if(sound.checked)enableReminderSound();buildNotices();buildRuler();adhkarHome(selectedHour);
386
- }));back(()=>adhkarHome(selectedHour));
387
- });
388
- }
389
- function matchingEvents(start,end){
390
- return registry('islamic_events').events.filter(e=>{
391
- if(!eventEnabled(e))return false;const c=e.calendar_rule||{},t=e.time_rule||{};
392
- if(e.display?.timeline===false||t.type==='conditional_prayer_relative'||t.type==='trigger_only'||!eventCalendarMatches(e,start)||eventBlockedOn(e,start))return false;
393
- if(['full_day_worship','full_day','season_window','month_window'].includes(t.type))return true;
394
- if(t.rule_id)return solarPeriods.some(p=>p.id===t.rule_id&&p.start<end&&p.end>start);
395
- if(t.start&&t.end){return solarDays.some(d=>d.boundaries[t.start]!=null&&d.boundaries[t.end]!=null&&d.boundaries[t.start]<end&&d.boundaries[t.end]>start);}
396
- if(Array.isArray(t.windows))return t.windows.some(w=>solarDays.some(d=>d.boundaries[w.start]!=null&&d.boundaries[w.end]!=null&&d.boundaries[w.start]<end&&d.boundaries[w.end]>start));
397
- return false;
398
- });
399
- }
400
- function prayerEntries(){
401
- const policy=visual.runtime_styles.prayer_entry_markers;if(!policy||policy.placement!=='start_only')return [];
402
- const ids=new Set(policy.rule_ids),seen=new Set();
403
- return solarPeriods.filter(p=>{
404
- if(!ids.has(p.id)||(!policy.include_preference_windows&&p.preference))return false;
405
- const key=p.id+':'+p.start;if(seen.has(key))return false;seen.add(key);return true;
406
- });
407
- }
408
- function indicatorState(now){
409
- const spec=visual.runtime_styles.solar_indicator;if(!spec)return null;
410
- if(!observer)return spec.unknown_state;
411
- const days=solarDays.filter(d=>dateKey(d.boundaries[spec.start_boundary])===dateKey(now));
412
- if(!days.length)return spec.unknown_state;
413
- const b=days[0].boundaries,a=b[spec.start_boundary],z=b[spec.end_boundary];
414
- if(a==null||z==null)return spec.unknown_state;
415
- return now>=a&&now<z?spec.day_state:spec.night_state;
416
- }
417
- function solarAltitude(now){return observer?SolarEngine.altitude(now,observer):null;}
418
- function paintCell(cell,start){
419
- const rows=inHour(start),end=start+3600000,style=visual.runtime_styles,controls=[];
420
- const lanes=style.timeline_lanes||[];
421
- lanes.forEach((stateId,lane)=>{
422
- const matching=rows.filter(p=>p.state===stateId);if(!matching.length)return;
423
- const track=make('span');track.className='time-track';track.style.top=(48+lane*21)+'px';track.dataset.state=stateId;
424
- const seen=new Set();
425
- matching.forEach(p=>{
426
- const key=p.start+':'+p.end;if(seen.has(key))return;seen.add(key);
427
- const part=button('',()=>periodDetails(p));part.className=p.point?'solar-point':'time-band';part.title=periodTitle(p)+' — '+periodTime(p);
428
- if(stateId==='prayer_time'){part.setAttribute('aria-hidden','true');part.tabIndex=-1;}else part.setAttribute('aria-label',periodTitle(p)+' — '+periodTime(p));
429
- part.style.left=((Math.max(start,p.start)-start)/3600000*100)+'%';
430
- if(!p.point)part.style.width=((Math.min(end,p.end)-Math.max(start,p.start))/3600000*100)+'%';
431
- applyStatePaint(part,stateId);part.style.top=(48+lane*21)+'px';part.style.height='17px';part.dataset.timelineTime=String(Math.max(start,p.start));controls.push(part);
432
- });
433
-
434
- });
435
- const entries=prayerEntries().filter(p=>p.start>=start&&p.start<end);
436
- if(entries.length){const strip=make('span');strip.className='hour-icons';
437
- for(const p of entries){const label=periodIcon(p)+' '+ruleTitle(p.rule)+(style.prayer_entry_markers.show_time?' '+timeText(p.start):'');const entry=button(label,()=>periodDetails(p));entry.setAttribute('aria-label',periodTitle(p)+' — '+timeText(p.start));entry.className='prayer-entry';entry.dataset.ruleId=p.id;entry.dataset.time=String(p.start);entry.dataset.timelineTime=String(p.start);entry.style.position='absolute';entry.style.top='6px';entry.style.left='4px';entry.style.zIndex='3';controls.push(entry);}
438
-
439
- }
440
- const marks=[];
441
- for(const d of solarDays)for(const id of style.boundary_markers||[]){
442
- const t=d.boundaries[id],def=boundary(id);if(!def||t==null||t<start||t>=end)continue;
443
- const entry=button((icon(id)?icon(id)+' ':'')+def.label+' '+timeText(t),()=>boundaryInfo(def,t));
444
- entry.dataset.boundaryId=id;entry.dataset.time=String(t);entry.dataset.timelineTime=String(t);entry.className='boundary-entry';marks.push(entry);
445
- }
446
- marks.sort((a,b)=>Number(a.dataset.time)-Number(b.dataset.time));
447
- marks.forEach((entry,index)=>{entry.style.top=(164+index*40)+'px';controls.push(entry);});
448
- const seenNotices=new Set();
449
- for(const notice of timedNotices){
450
- const event=notice.event,t=notice.at;
451
- const key=notice.key+':'+t;
452
- if(t<start||t>=end||seenNotices.has(key)||!eventEnabled(event)||event.display?.timeline===false)continue;
453
- seenNotices.add(key);
454
- const symbol=icon(visual.event_action_mapping[event.action]);
455
- const entry=button((symbol?symbol+' ':'')+(notice.trigger.popup?.title||notice.trigger.title||title(event))+' '+timeText(t),()=>detail(eventScreen(event),'events',event));
456
- entry.dataset.eventId=event.id;entry.dataset.time=String(t);entry.dataset.timelineTime=String(t);entry.className='event-marker';controls.push(entry);
457
- }
458
- controls.sort((a,b)=>Number(a.dataset.timelineTime)-Number(b.dataset.timelineTime)).forEach(x=>cell.appendChild(x));
459
- }
460
- function calendarText(c,now){
461
- try{const date=new Date(now),offset=Number(getSaved('clock_calendar_adjustment_v1',0));
462
- if(c.adjustable){const h=hijriParts(now);if(h?.confirmed)return [h.day,h.month,h.year].join('/')+' '+c.label;}
463
- if(c.adjustable&&Number.isInteger(offset)&&Math.abs(offset)<=visual.runtime_styles.calendar_adjustment_limit)date.setDate(date.getDate()+offset);
464
- return new Intl.DateTimeFormat(document.documentElement.lang,{calendar:c.id,year:'numeric',month:'long',day:'numeric'}).format(date)+' '+c.label;
465
- }catch{return ui.calendarUnavailable;}
466
- }
467
- function calendarSettings(){show('worship',{title:ui.calendarSettings,text:ui.calendarNote},()=>{
468
- const value=reminderField(ui.calendarAdjustment,'number',getSaved('clock_calendar_adjustment_v1',0));value.min=-visual.runtime_styles.calendar_adjustment_limit;value.max=visual.runtime_styles.calendar_adjustment_limit;value.step=1;
469
- $('adaptivePopupActions').appendChild(button(ui.apply,()=>{const n=Number(value.value);if(!Number.isInteger(n)||Math.abs(n)>visual.runtime_styles.calendar_adjustment_limit){para(ui.calendarInvalid);return;}save('clock_calendar_adjustment_v1',n);recalculate();close();}));
470
- $('adaptivePopupBody').appendChild(button(ui.monthConfirmation.title,monthConfirmation));
471
- });}
472
- function monthConfirmation(){
473
- const config=registry('islamic_events').calendar_confirmation,labels=ui.monthConfirmation;
474
- show('worship',{title:labels.title,text:labels.note},()=>{
475
- const h=hijriParts(Date.now()),year=reminderField(labels.year,'number',h?.year||''),month=reminderField(labels.month,'number',h?.month||'');
476
- year.min=1;year.step=1;month.min=1;month.max=12;month.step=1;
477
- const start=reminderField(labels.start,'date',''),length=reminderSelect(labels.length,config.length_options.map(n=>[String(n),String(n)]),String(config.length_options[0]));
478
- const confirmations=getSaved(config.storage_key,[]);
479
- confirmations.forEach(item=>{
480
- para(item.year+'/'+item.month+' — '+item.start+' — '+item.length);
481
- $('adaptivePopupBody').appendChild(button(labels.remove+' '+item.year+'/'+item.month,()=>{
482
- save(config.storage_key,confirmations.filter(x=>x!==item));recalculate();monthConfirmation();
483
- }));
484
- });
485
- $('adaptivePopupActions').appendChild(button(labels.save,()=>{
486
- const item={year:Number(year.value),month:Number(month.value),start:start.value,length:Number(length.value)};
487
- if(!HijriCalendarEngine.validConfirmation(item)){para(labels.invalid);return;}
488
- const rest=confirmations.filter(x=>x.year!==item.year||x.month!==item.month),a=Date.parse(item.start+'T00:00:00Z'),z=a+item.length*86400000;
489
- if(rest.some(x=>{const b=Date.parse(x.start+'T00:00:00Z');return a<b+x.length*86400000&&z>b;})){para(labels.invalid);return;}
490
- try{localStorage.setItem(config.storage_key,JSON.stringify([...rest,item]));}catch{para(ru().storageError);return;}
491
- recalculate();monthConfirmation();
492
- }));back(calendarSettings);
493
- });
494
- }
495
- function updateCurrentMarker(now){
496
- const width=Number($('ruler').dataset.cellWidth),marker=$('nowMarker');
497
- if(marker){marker.style.left=((now-timelineStart)/3600000*width)+'px';marker.hidden=now<timelineStart||now>=timelineStart+layout.total_hours*3600000;
498
- const state=indicatorState(now),paint=visual.timeline_states[state];
499
- const label=$('nowMarkerLabel');
500
- if(label){const calendars=visual.runtime_styles.current_time_calendars||[];
501
- label.textContent=(observer&&paint?.emoji?paint.emoji+' ':'')+timeText(now)+'\n'+calendars.map(c=>calendarText(c,now)).join('\n');
502
- const x=(now-timelineStart)/3600000*width,half=Math.min(135,$('shell').clientWidth/2);
503
- label.style.transform='translateX('+Math.max($('shell').scrollLeft-x,Math.min(-half,$('shell').scrollLeft+$('shell').clientWidth-2*half-x))+'px)';
504
- }marker.style.color=paint?.text_color||'';marker.style.backgroundColor=paint?.color||'';
505
- }
506
- }
507
- function tickSolar(){
508
- if(lastSolarDay!==dateKey(Date.now())){recalculate();return;}
509
- const now=Date.now();updateCurrentMarker(now);
510
- tickNotices(now);
511
- const status=$('solarStatus');
512
- if(!observer){status.textContent=ui.chooseLocation;return;}
513
- if(!profile()){status.textContent=ui.missingSolar;return;}
514
- if(!SolarEngine.ready()){status.textContent=ui.solarEngineUnavailable;return;}
515
- if(methodChoice()&&!prayerEngineReady){status.textContent=ui.prayerEngineUnavailable;return;}
516
- const upcoming=prayerEntries().filter(p=>p.start>now).sort((a,b)=>a.start-b.start)[0];
517
- const altitude=solarAltitude(now);
518
- status.textContent=(observer.name||observer.lat.toFixed(3)+', '+observer.lng.toFixed(3))+' · '+ui.deviceTime+' · '+ui.estimated;
519
- if(Number.isFinite(altitude))status.textContent+='\n'+(ui.solarAltitude||'ارتفاع الشمس')+': '+altitude.toFixed(1)+'° · '+(ui.solarGeometrySource||'حساب هندسي شمسي محلي');
520
- if(methodChoice())status.textContent+='\n'+ui.calculationMethod+': '+methodChoice().label;
521
- if(solarDays.some(d=>d.methodUnavailable))status.textContent+='\n'+ui.methodUnavailable;
522
- if(upcoming){const mins=Math.ceil((upcoming.start-now)/60000);status.textContent+='\n'+ui.nextPrayer+': '+ruleTitle(upcoming.rule)+' '+timeText(upcoming.start)+' — '+ui.remaining+' '+Math.floor(mins/60)+' '+ui.hours+' '+mins%60+' '+ui.minutes;}
523
- }
524
- function initSolar(){
525
- const candidate=getSaved('clock_observer_v1',null);observer=validLocation(candidate)?candidate:null;
526
- madhhab=getSaved('clock_madhhab_v1',profile()?.default_madhhab);
527
- if(!registry('worship_fiqh').madhhabs?.[madhhab])madhhab=profile()?.default_madhhab;
528
- $('locationButton').textContent=ui.location;$('locationButton').addEventListener('click',configureLocation);
529
- recalculate();frameTimer=setInterval(tickSolar,1000);
530
- }
531
- let timedNotices=[];const pendingTimedNotices=new Map();
532
- function buildNotices(){
533
- timedNotices=[];const runtime=profile()?.notice_runtime;if(!runtime)return;
534
- const localToday=new Date();localToday.setHours(0,0,0,0);
535
- const days=timelineCalculationDays();
536
- timedNotices=WorshipEventEngine.compile({events:registry('islamic_events').events,days,solarDays,periods:solarPeriods,runtime,
537
- policy:registry('islamic_events').scheduling_policy,enabled:eventEnabled,blocked:eventBlockedOn,matches:eventCalendarMatches,parts:hijriParts,
538
- preference:event=>isAdhkar(event)?adhkarPreference(event):null,seasonPreference,
539
- solarAvailable:Boolean(observer&&SolarEngine.ready()&&(!methodChoice()||prayerEngineReady)),
540
- defaultSound:getSaved(registry('user_time_markers').reminder_system?.storage_key,{})?.settings?.sound_enabled===true});
541
- const end=new Date(localToday);end.setDate(end.getDate()+4);
542
- const start=new Date(localToday);start.setDate(start.getDate()-2);
543
- timedNotices.push(...WorshipEventEngine.eclipses({astronomy:registry('astronomy_events'),event:registry('islamic_events').events.find(e=>e.id==='eclipse_prayer'),location:observer,start:start.getTime(),end:end.getTime()}));
544
- timedNotices.sort((a,b)=>a.at-b.at||b.priority-a.priority);
545
- for(const [key,pending] of pendingTimedNotices)if(!timedNotices.some(n=>n.key===key&&n.at===pending.at))pendingTimedNotices.delete(key);
546
- }
547
- function tickNotices(now){
548
- const runtime=profile()?.notice_runtime;if(!runtime)return;
549
- const ledger=getSaved('clock_popup_impressions_v1',{});
550
- for(const n of timedNotices)if(now>=n.at&&now-n.at<runtime.due_window_seconds*1000&&(n.expires==null||now<n.expires)&&(ledger[n.key]?.count||0)<n.max)pendingTimedNotices.set(n.key,n);
551
- if(!document.hidden&&$('adaptivePopup').hidden===false)return;
552
- for(const [key,n]of pendingTimedNotices)if(n.expires!=null&&now>=n.expires)pendingTimedNotices.delete(key);
553
- const due=[...pendingTimedNotices.values()].filter(n=>eventEnabled(n.event)&&(ledger[n.key]?.count||0)<n.max).sort((a,b)=>b.priority-a.priority||a.at-b.at)[0];
554
- if(!due)return;
555
- pendingTimedNotices.delete(due.key);
556
- // This records display counts only; it is never worship completion tracking.
557
- for(const [key,value] of Object.entries(ledger))if(now-value.at>7*86400000)delete ledger[key];
558
- ledger[due.key]={count:(ledger[due.key]?.count||0)+1,at:now};save('clock_popup_impressions_v1',ledger);
559
- const popup=due.trigger.popup||{};
560
- const kind=eventScreen(due.event),noticeTitle=popup.title||due.trigger.title||title(due.event),noticeText=popup.text||due.trigger.popup_text||due.event.display?.text||'';
561
- if(due.sound!==false)playReminderSound();notifySystem(noticeTitle,noticeText,{kind,eventId:due.event.id});
562
- if(!document.hidden&&$('adaptivePopup').hidden!==false)show(kind,{title:noticeTitle,text:noticeText,media:icon(visual.event_action_mapping[due.event.action])},()=>{
563
- back(()=>detail(kind,'events',due.event));
564
- });
565
- }
566
-
567
- let personal=null,personalReady=false,reminderAudio=null,notificationRegistration=null,personalNoticeKeys=new Set();
568
- async function enableReminderSound(){try{const Audio=window.AudioContext||window.webkitAudioContext;if(!Audio)return false;if(!reminderAudio)reminderAudio=new Audio();await reminderAudio.resume();return reminderAudio.state==='running';}catch{return false;}}
569
- async function playReminderSound(){if(!reminderAudio||!visual.reminder_audio)return false;try{if(reminderAudio.state!=='running')await reminderAudio.resume();if(reminderAudio.state!=='running')return false;const a=visual.reminder_audio,o=reminderAudio.createOscillator(),g=reminderAudio.createGain();o.frequency.value=a.frequency_hz;g.gain.value=a.gain;o.connect(g);g.connect(reminderAudio.destination);o.start();g.gain.exponentialRampToValueAtTime(0.001,reminderAudio.currentTime+a.duration_seconds);o.stop(reminderAudio.currentTime+a.duration_seconds);return true;}catch{return false;}}
570
- async function initNotifications(){
571
- if(window.isSecureContext!==true||!('serviceWorker' in navigator))return null;
572
- try{notificationRegistration=await navigator.serviceWorker.register('./sw.js');navigator.serviceWorker.addEventListener('message',e=>openNotificationData(e.data));return notificationRegistration;}catch{return null;}
573
- }
574
- function openNotificationData(data){if(!data)return;if(data.reminderId){const s=personal&&reminderAction(()=>personal.read()),x=s?.items.find(i=>i.id===data.reminderId);if(x)reminderDetail(x.id,undefined,data.kind||reminderScreen(x));return;}if(data.eventId){const x=registry('islamic_events').events.find(i=>i.id===data.eventId);if(x)detail(data.kind||eventScreen(x),'events',x);}}
575
- async function requestAlertPermission(){
576
- const soundPromise=enableReminderSound();let permissionPromise=Promise.resolve('unsupported');
577
- if('Notification' in window&&window.isSecureContext===true){try{permissionPromise=Notification.permission==='default'?Promise.resolve(Notification.requestPermission()).catch(()=>'error'):Promise.resolve(Notification.permission);}catch{permissionPromise=Promise.resolve('error');}}
578
- const [sound,permission]=await Promise.all([soundPromise,permissionPromise]);await initNotifications();return {sound,permission};
579
- }
580
- async function notifySystem(titleText,body,data){
581
- if(!('Notification' in window)||Notification.permission!=='granted'||window.isSecureContext!==true)return false;
582
- const options={body:String(body||'').slice(0,240),lang:document.documentElement.lang,tag:'muslim-clock-'+(data?.reminderId||data?.eventId||Date.now()),renotify:true,data};
583
- try{const reg=notificationRegistration||await initNotifications();if(reg){await reg.showNotification(titleText,options);return true;}new Notification(titleText,options);return true;}catch{return false;}
584
- }
585
-
586
- const ru=()=>ui.reminders;
587
- function reminderAction(fn){try{return fn();}catch(e){para(e.message==='invalid'?ru().invalid:ru().storageError);return null;}}
588
- function reminderDate(t){return new Date(t).toLocaleString(document.documentElement.lang,{dateStyle:'short',timeStyle:'short',hour12:true});}
589
- function localInput(t){const d=new Date(t),pad=x=>String(x).padStart(2,'0');return d.getFullYear()+'-'+pad(d.getMonth()+1)+'-'+pad(d.getDate())+'T'+pad(d.getHours())+':'+pad(d.getMinutes());}
590
- function reminderField(label,type,value){const wrap=make('label',label),input=make(type==='textarea'?'textarea':'input');if(type!=='textarea')input.type=type;input.value=value??'';wrap.appendChild(input);$('adaptivePopupBody').appendChild(wrap);return input;}
591
- function reminderSelect(label,options,value){const wrap=make('label',label),select=make('select');for(const [id,name] of options){const o=make('option',name);o.value=id;select.appendChild(o);}select.value=value;wrap.appendChild(select);$('adaptivePopupBody').appendChild(wrap);return select;}
592
- function reminderMoment(x){if(x.mode==='one_time')return x.target;if(x.mode==='recurring')return x.notice&&x.lastNotified!=null?x.lastNotified:personal.next(x,Date.now());if(x.mode==='pomodoro')return x.end;return null;}
593
- function reminderSummary(x){const u=ru();if(x.mode==='pomodoro')return (x.active?(x.phase==='waiting'?u.waitingPhase:x.phase==='work'?u.workPhase:u.breakPhase)+' · '+u.session+' '+x.session+' '+u.of+' '+x.total:u.finished)+'\n'+u.endAt+' '+reminderDate(x.end);const cadence=x.mode==='recurring'?u.repeatEvery+' '+personal.recurringSpec(x).every+' '+u.repeatUnits[personal.recurringSpec(x).unit]+' · ':'';return cadence+(x.notice?u.pending:u.scheduled)+' · '+reminderDate(reminderMoment(x));}
594
- function remindersHome(selectedHour,saved=false){
595
- show('worship',{title:ru().title,text:ru().scope},()=>{
596
- if(saved){const status=make('p',ru().saved);status.setAttribute('role','status');$('adaptivePopupBody').appendChild(status);}
597
- if(!personal){para(ru().missing);return;}
598
- const s=reminderAction(()=>personal.tick());if(!s)return;if(s.settings.sound_enabled)enableReminderSound();
599
- $('adaptivePopupActions').appendChild(button(ru().add,()=>reminderChoose(selectedHour)));
600
- $('adaptivePopupActions').appendChild(button(ru().settings,reminderSettings));
601
- $('adaptivePopupActions').appendChild(button(ui.adhkar.title,()=>adhkarHome(selectedHour)));
602
- $('adaptivePopupActions').appendChild(button(ui.worshipSchedules,()=>list('worship','events')));
603
- if(s.items.length)$('adaptivePopupActions').appendChild(button(ru().removeSelected,()=>remindersRemoveSelected(selectedHour)));
604
- if(!s.items.length)para(ru().empty);
605
- s.items.slice().sort((a,b)=>Boolean(b.notice)-Boolean(a.notice)||reminderMoment(a)-reminderMoment(b)).forEach(x=>{
606
- const type=registry('user_time_markers').marker_types[x.type];$('adaptivePopupBody').appendChild(button(icon(type.icon_id)+' '+type.label_ar+' — '+x.text.slice(0,100)+'\n'+reminderSummary(x),()=>reminderDetail(x.id,selectedHour)));
607
- });
608
- });
609
- }
610
- function remindersRemoveSelected(selectedHour){
611
- const state=reminderAction(()=>personal.read());if(!state)return;
612
- show('worship',{title:ru().removeSelected,text:ru().selectToRemove},()=>{
613
- const choices=state.items.map(item=>({id:item.id,input:reminderField(item.text,'checkbox','')}));
614
- $('adaptivePopupActions').appendChild(button(ru().delete,()=>{
615
- const selected=new Set(choices.filter(x=>x.input.checked).map(x=>x.id));
616
- if(!selected.size){para(ru().nothingSelected);return;}
617
- if(!window.confirm(ru().removeSelectedConfirm))return;
618
- const result=reminderAction(()=>{const current=personal.read();current.items=current.items.filter(x=>!selected.has(x.id));return personal.write(current);});
619
- if(result){refreshPersonal();remindersHome(selectedHour);}
620
- }));back(()=>remindersHome(selectedHour));
621
- });
622
- }
623
- function reminderChoose(selectedHour){if(!personal){remindersHome(selectedHour);return;}show('worship',{title:ru().add},()=>{
624
- for(const id of personal.config.enabled_types){const type=registry('user_time_markers').marker_types[id];$('adaptivePopupBody').appendChild(button(icon(type.icon_id)+' '+type.label_ar,()=>id==='adhkar'?adhkarHome(selectedHour):reminderForm(id,selectedHour)));}back(()=>remindersHome(selectedHour));
625
- });}
626
- function reminderForm(type,selectedHour,id){
627
- const s=reminderAction(()=>personal.read());if(!s)return;
628
- const old=s.items.find(x=>x.id===id),c=personal.config,types=registry('user_time_markers').marker_types;
629
- show('worship',{title:types[type].label_ar,media:icon(types[type].icon_id)},()=>{
630
- const category=reminderSelect(ru().type,c.enabled_types.map(key=>[key,icon(types[key].icon_id)+' '+types[key].label_ar]),old?.type||type);
631
- const mode=reminderSelect(ru().mode,c.scheduling_modes.map(key=>[key,ru().modes[key]]),old?.mode||c.type_behaviors[type]);
632
- const text=reminderField(ru().text,'textarea',old?.text);text.maxLength=c.limits.text_length;
633
- const religious=make('p',ru().religiousNote),notes=make('p',ru().notesNote);$('adaptivePopupBody').append(religious,notes);
634
- const groups={};
635
- const group=(key,fields,note)=>{const box=make('div');box.dataset.reminderMode=key;fields.forEach(field=>box.appendChild(field.parentElement));if(note)box.appendChild(make('p',note));$('adaptivePopupBody').appendChild(box);groups[key]=box;};
636
- const target=reminderField(ru().when,'datetime-local',old?.mode==='one_time'?localInput(old.target):selectedHour>Date.now()?localInput(selectedHour):'');
637
- const lead=reminderField(ru().lead,'number',old?.lead??s.settings.lead_minutes);lead.min=0;lead.max=c.limits.lead_minutes;
638
- group('one_time',[target,lead]);
639
- const defaults=c.default_recurring,spec=old?.mode==='recurring'?personal.recurringSpec(old):{startAt:selectedHour>Date.now()?selectedHour:Date.now()+defaults.start_delay_minutes*60000,every:defaults.every,unit:defaults.unit};
640
- const startAt=reminderField(ru().startsAt,'datetime-local',localInput(spec.startAt)),repeatEvery=reminderField(ru().repeatEvery,'number',spec.every);repeatEvery.min=1;repeatEvery.step=1;repeatEvery.max=c.limits.repeat_value;
641
- const repeatUnit=reminderSelect(ru().frequency,c.repeat_units.map(key=>[key,ru().repeatUnits[key]]),spec.unit);group('recurring',[startAt,repeatEvery,repeatUnit],ru().habitNote);
642
- const focus=old?.mode==='pomodoro'?old:c.default_focus;
643
- const focusAt=reminderField(ru().focusStartsAt,'datetime-local',old?.mode==='pomodoro'?(old.startAt>Date.now()?localInput(old.startAt):''):selectedHour>Date.now()?localInput(selectedHour):'');
644
- const work=reminderField(ru().work,'number',focus.work),rest=reminderField(ru().rest,'number',focus.rest),total=reminderField(ru().sessions,'number',focus.total);
645
- for(const e of [work,rest]){e.min=1;e.max=c.limits.duration_minutes;}total.min=1;total.step=1;total.max=c.limits.sessions;
646
- group('pomodoro',[focusAt,work,rest,total],ru().focusNote);
647
- const sound=reminderField(ru().sound,'checkbox','');sound.checked=old?.sound??c.default_alarm_sound;
648
- const sync=()=>{for(const [key,box]of Object.entries(groups))box.hidden=key!==mode.value;religious.hidden=!c.religious_types.includes(category.value);notes.hidden=category.value!=='note';$('adaptivePopupTitle').textContent=types[category.value].label_ar;$('adaptivePopupMedia').textContent=icon(types[category.value].icon_id);};
649
- category.addEventListener('change',sync);mode.addEventListener('change',sync);sync();
650
- $('adaptivePopupActions').appendChild(button(ru().save,()=>reminderAction(()=>{
651
- const start=mode.value==='pomodoro'?(focusAt.value?new Date(focusAt.value).getTime():null):new Date(startAt.value).getTime();
652
- const saved=personal.save({type:category.value,mode:mode.value,text:text.value,sound:sound.checked,target:new Date(target.value).getTime(),lead:lead.value,startAt:start,repeatEvery:repeatEvery.value,repeatUnit:repeatUnit.value,work:work.value,rest:rest.value,total:total.value},id);
653
- if(sound.checked)enableReminderSound();refreshPersonal();remindersHome(selectedHour,true);viewReminderOnTimeline(saved);
654
- })));back(()=>remindersHome(selectedHour));
655
- });
656
- }
657
- function reminderDetail(id,selectedHour,notificationKind,timelineAt){
658
- const s=reminderAction(()=>personal.read()),x=s?.items.find(x=>x.id===id);if(!x)return;
659
- show(notificationKind||'worship',{title:registry('user_time_markers').marker_types[x.type].label_ar,text:x.text+'\n\n'+reminderSummary(x),media:icon(registry('user_time_markers').marker_types[x.type].icon_id)},()=>{
660
- if(Number.isFinite(timelineAt))para(ru().when+' — '+reminderDate(timelineAt));
661
- $('adaptivePopupActions').appendChild(button(ru().showOnTimeline,()=>{close();viewReminderOnTimeline(x,timelineAt);}));
662
- if(personal.tracksStreak(x))para(ru().streak+': '+x.streak+' '+ru().occurrences);
663
- const act=(label,fn)=>$('adaptivePopupActions').appendChild(button(label,()=>reminderAction(()=>{fn();refreshPersonal();remindersHome(selectedHour);})));
664
- if(personal.tracksCompletion(x))act(ru().complete,()=>personal.complete(id));
665
- const recurringDue=x.mode==='recurring'?personal.schedule(x,Date.now()).due:null;
666
- if(personal.tracksStreak(x)&&recurringDue!=null&&recurringDue>=x.createdAt&&x.lastCompleted!==recurringDue)act(ru().habitComplete,()=>personal.complete(id));
667
- if(x.mode==='one_time')for(const o of personal.config.snooze_options)act(ru().snooze[o.id],()=>personal.snooze(id,o.id));
668
- if(x.notice)act(ru().acknowledge,()=>personal.acknowledge(id));
669
- $('adaptivePopupActions').appendChild(button(ru().edit,()=>reminderForm(x.type,selectedHour,id)));
670
- $('adaptivePopupActions').appendChild(button(ru().copy,async()=>{
671
- try{await navigator.clipboard.writeText(x.text);para(ru().copied);}catch{para(ru().copyManual);const e=reminderField(ru().text,'textarea',x.text);e.readOnly=true;e.focus();e.select();}
672
- }));
673
- $('adaptivePopupActions').appendChild(button(x.mode==='pomodoro'?ru().cancel:ru().delete,()=>{if(window.confirm(ru().deleteAsk))reminderAction(()=>{personal.remove(id);refreshPersonal();remindersHome(selectedHour);});}));
674
- back(()=>remindersHome(selectedHour));
675
- });
676
- }
677
- function reminderSettings(){const s=reminderAction(()=>personal.read());if(!s)return;show('worship',{title:ru().settings,text:ru().scope},()=>{
678
- const sound=reminderField(ru().sound,'checkbox','');sound.checked=s.settings.sound_enabled===true;
679
- $('adaptivePopupBody').appendChild(button(ru().enableAlerts,async()=>{const result=await requestAlertPermission();if(result.permission==='denied')para(ru().notificationDenied);else if(result.sound&&result.permission==='granted')para(ru().alertsReady);else if(result.permission==='unsupported')para(ru().notificationUnavailable);else para(ru().alertsPartlyReady);}));
680
- $('adaptivePopupBody').appendChild(button(ru().testSound,async()=>{if(await enableReminderSound())playReminderSound();else para(ru().soundUnavailable);}));para(ru().closedBrowserNote);
681
- const lead=reminderField(ru().lead,'number',s.settings.lead_minutes),evening=reminderField(ru().evening,'time',s.settings.evening_time),tomorrow=reminderField(ru().tomorrow,'time',s.settings.tomorrow_time);
682
- $('adaptivePopupActions').appendChild(button(ru().save,()=>reminderAction(()=>{personal.settings({lead_minutes:lead.value,evening_time:evening.value,tomorrow_time:tomorrow.value,sound_enabled:sound.checked});if(sound.checked)enableReminderSound();remindersHome();})));back(remindersHome);
683
- });}
684
- let personalSignature='',personalTimelineRows=[];
685
- function preparePersonalTimeline(items){
686
- personalTimelineRows=[];const end=timelineStart+layout.total_hours*3600000;
687
- for(const item of items)for(const at of personal.timelineOccurrences(item,timelineStart,end))personalTimelineRows.push({item,at});
688
- personalTimelineRows.sort((a,b)=>a.at-b.at);
689
- }
690
- function viewReminderOnTimeline(item,requestedAt){
691
- const at=Number.isFinite(requestedAt)?requestedAt:item.mode==='recurring'?personal.next(item,Date.now()):item.mode==='pomodoro'?(item.startAt??item.end):item.target;
692
- if(!Number.isFinite(at))return;
693
- if(at<timelineStart||at>=timelineStart+layout.total_hours*3600000){timelineViewDate=at;recalculate();}
694
- const width=Number($('ruler').dataset.cellWidth);$('shell').scrollLeft=Math.max(0,(Math.floor((at-timelineStart)/3600000)-1)*width);
695
- }
696
- function tickPersonal(){if(!personalReady)return;try{
697
- const s=personal.tick(),count=s.items.filter(x=>x.notice).length,b=$('reminderNotice');
698
- const pending=s.items.filter(x=>x.notice),key=x=>[x.id,x.notice,x.target,x.lastNotified,x.end].join(':'),currentKeys=new Set(pending.map(key)),fresh=pending.filter(x=>!personalNoticeKeys.has(key(x)));
699
- personalNoticeKeys=currentKeys;
700
- if(fresh.some(x=>x.sound??s.settings.sound_enabled))playReminderSound();
701
- fresh.forEach(x=>notifySystem(registry('user_time_markers').marker_types[x.type].label_ar,x.text,{kind:reminderScreen(x),reminderId:x.id}));
702
- if(fresh.length&&!document.hidden&&$('adaptivePopup').hidden!==false)reminderDetail(fresh[0].id,undefined,reminderScreen(fresh[0]));
703
- const message=count?ru().notice+' ('+count+')':'';
704
- if(b.textContent!==message)b.textContent=message;
705
- const live=$('reminderDialogNotice');if(live){if(live.textContent!==message)live.textContent=message;live.hidden=!count;}
706
- b.hidden=!count;
707
- const signature=JSON.stringify([timelineStart,s.items]);
708
- if(signature!==personalSignature){personalSignature=signature;preparePersonalTimeline(s.items);const ruler=$('ruler');for(const cell of Array.from(ruler.children).filter(x=>x.className==='hour')){for(const row of Array.from(cell.children).filter(x=>x.className==='personal-hour'))row.remove();paintPersonal(cell,Number(cell.dataset.start));}positionTimelineRows();}
709
- }catch{$('reminderNotice').hidden=false;$('reminderNotice').textContent=ru().storageError;}}
710
- function refreshPersonal(){personalSignature='';tickPersonal();}
711
- function initPersonal(){const c=registry('user_time_markers').reminder_system;
712
- const live=button('',()=>remindersHome());live.id='reminderDialogNotice';live.hidden=true;live.setAttribute('aria-live','assertive');live.setAttribute('aria-atomic','true');$('adaptivePopupCard').prepend(live);
713
- $('reminderButton').textContent=ru().tools;$('reminderButton').addEventListener('click',()=>remindersHome());$('reminderNotice').addEventListener('click',()=>remindersHome());
714
- const adhkarButton=$(adhkarConfig()?.entry_button_id||'adhkarButton');
715
- if(adhkarButton){adhkarButton.textContent=ui.adhkar.button;adhkarButton.addEventListener('click',()=>adhkarHome());}
716
- if(!c)return;personal=new PersonalReminderEngine(c,localStorage);personalReady=true;tickPersonal();setInterval(tickPersonal,registry('user_time_markers').reminder_system.poll_interval_ms);
717
- window.addEventListener('focus',refreshPersonal);window.addEventListener('storage',refreshPersonal);document.addEventListener('visibilitychange',()=>{if(!document.hidden)refreshPersonal();});
718
- document.addEventListener('pointerdown',()=>{try{if(personal?.read().settings.sound_enabled||registry('islamic_events').events.filter(isAdhkar).some(e=>{const p=adhkarPreference(e);return p.enabled&&p.sound;}))enableReminderSound();}catch{}},{passive:true});
719
- }
720
- function paintPersonal(cell,start){if(!personalReady)return;try{
721
- for(const {item:x,at} of personalTimelineRows.filter(row=>row.at>=start&&row.at<start+3600000)){
722
- const type=registry('user_time_markers').marker_types[x.type],row=button(icon(type.icon_id)+' '+x.text+' '+timeText(at),()=>reminderDetail(x.id,undefined,undefined,at));
723
- row.className='personal-hour';row.dataset.reminderId=x.id;row.dataset.timelineTime=String(at);row.setAttribute('aria-label',type.label_ar+' — '+x.text+' — '+reminderDate(at));cell.appendChild(row);
724
- }
725
- Array.from(cell.children).filter(x=>x.dataset.timelineTime).sort((a,b)=>Number(a.dataset.timelineTime)-Number(b.dataset.timelineTime)).forEach(x=>cell.appendChild(x));
726
- }catch{}}
727
-
728
- function twelveHourLabel(h){return (h%12||12)+':00 '+(h<12?ui.am:ui.pm);}
729
- function hourAccessibleLabel(h){return ui.hourOnly+' '+(h%12||12)+':00';}
730
- function buildRuler(){
731
- const shell=$('shell'),ruler=$('ruler'),width=Math.max(layout.minimum_cell_width,shell.clientWidth/layout.visible_cells);
732
- const oldWidth=Number(ruler.dataset.cellWidth)||width;const offset=shell.scrollLeft/oldWidth;
733
- ruler.replaceChildren();ruler.dataset.cellWidth=width;ruler.style.width=(layout.total_hours*width)+'px';
734
- const axis=make('div');axis.className='axis';axis.setAttribute('aria-hidden','true');ruler.appendChild(axis);
735
- const reference=new Date(timelineViewDate??Date.now()),start=new Date(reference);start.setHours(layout.start_hour,0,0,0);if(start>reference)start.setDate(start.getDate()-1);timelineStart=start.getTime();
736
- if(personalReady)preparePersonalTimeline(personal.read().items);
737
- const endDate=new Date(timelineStart+(layout.total_hours-1)*3600000);
738
- $('timelineDates').textContent=new Date(timelineStart).toLocaleDateString(document.documentElement.lang)+' — '+endDate.toLocaleDateString(document.documentElement.lang);
739
- $('timelineToday').hidden=timelineViewDate==null;
740
- for(let i=0;i<layout.total_hours;i++){
741
- const date=new Date(start.getTime()+i*3600000),label=twelveHourLabel(date.getHours());
742
- const b=make('div');const hourButton=button('',()=>hourSettings(date.getTime()));hourButton.className='hour-hit';hourButton.setAttribute('aria-label',hourAccessibleLabel(date.getHours()));b.appendChild(hourButton);
743
- b.className='hour';b.dataset.start=String(date.getTime());b.style.left=(i*width)+'px';b.style.width=width+'px';
744
- const tick=make('span');tick.className='tick';tick.setAttribute('aria-hidden','true');
745
- const caption=make('span',label);caption.className='label';caption.setAttribute('aria-hidden','true');hourButton.append(tick,caption);paintCell(b,date.getTime());paintPersonal(b,date.getTime());ruler.appendChild(b);
746
- }
747
- positionTimelineRows();
748
- const marker=make('div');marker.id='nowMarker';marker.className='now-marker';marker.setAttribute('aria-hidden','true');const markerLabel=make('span');markerLabel.id='nowMarkerLabel';markerLabel.className='now-marker-label';marker.appendChild(markerLabel);ruler.prepend(marker);
749
- shell.scrollLeft=initialScroll?offset*width:Math.max(0,Math.floor((Date.now()-start.getTime())/3600000)*width);initialScroll=true;updateCurrentMarker(Date.now());
750
- }
751
- function positionTimelineRows(){
752
- const ruler=$('ruler'),cells=[...ruler.querySelectorAll('.hour')];
753
- const upperHeight=Math.max(270,...cells.map(cell=>164+cell.querySelectorAll('.boundary-entry').length*40));
754
- let lowerRows=0;
755
- for(const cell of cells){
756
- cell.style.height=upperHeight+'px';
757
- const reminders=[...cell.querySelectorAll('.event-marker,.personal-hour')].sort((a,b)=>Number(a.dataset.timelineTime)-Number(b.dataset.timelineTime));
758
- const cellWidth=Number(ruler.dataset.cellWidth)||Number.parseFloat(cell.style.width)||160;
759
- const columns=Math.max(1,Math.min(reminders.length,Math.floor((cellWidth-8)/82)||1));
760
- const cardWidth=Math.max(58,(cellWidth-8-(columns-1)*6)/columns);
761
- reminders.forEach((entry,index)=>{
762
- const row=Math.floor(index/columns),column=index%columns;
763
- entry.style.top=(upperHeight+20+row*70)+'px';entry.style.bottom='auto';
764
- entry.style.left=(4+column*(cardWidth+6))+'px';entry.style.right='auto';entry.style.width=cardWidth+'px';
765
- });
766
- lowerRows=Math.max(lowerRows,Math.ceil(reminders.length/columns));
767
  }
768
- ruler.querySelector('.reminder-axis')?.remove();
769
- if(lowerRows){const axis=make('div');axis.className='reminder-axis';axis.setAttribute('aria-hidden','true');axis.style.top=(95+upperHeight+8)+'px';ruler.prepend(axis);}
770
- ruler.style.height=(95+upperHeight+(lowerRows?20+lowerRows*70:25))+'px';
771
- }
772
- async function start(){
773
- // No embedded domain-data fallback: a missing registry must remain visible.
774
- const results=await Promise.allSettled(files.map(async name=>{
775
- const controller=new AbortController(),timer=setTimeout(()=>controller.abort(),15000);
776
- try{const response=await fetch('./'+name+'.json',{cache:'no-store',signal:controller.signal});if(!response.ok)throw Error(name+'.json ('+response.status+')');R[name]=await response.json();}
777
- catch(e){throw Error(name+'.json: '+e.message);}finally{clearTimeout(timer);}
778
- }));
779
- visual=registry('visual_states');ui=visual?.ui;layout=visual?.ui_layout;
780
- if(visual?.ui_theme)Object.entries(visual.ui_theme).forEach(([key,val])=>document.documentElement.style.setProperty('--'+key,val));
781
- const errors=results.filter(r=>r.status==='rejected');
782
- if(!ui||!layout||!visual.runtime_styles){$('loadStatus').textContent=(ui?.loadError||'visual_states_registry.json')+'\n'+errors.map(r=>r.reason.message).join('\n');return;}
783
- document.title=ui.title;document.querySelectorAll('[data-ui]').forEach(e=>e.textContent=ui[e.dataset.ui]||'');
784
- document.querySelectorAll('[data-aria]').forEach(e=>e.setAttribute('aria-label',ui[e.dataset.aria]||''));
785
- await loadPrayerEngine();
786
- $('timelineToday').addEventListener('click',()=>{timelineViewDate=null;initialScroll=false;recalculate();});
787
- $('loadStatus').textContent=errors.length?ui.partialLoad+'\n'+errors.map(r=>r.reason.message).join('\n'):'';await initNotifications();initSolar();initPersonal();const legend=make('div');legend.className='timeline-legend';for(const id of visual.runtime_styles.timeline_lanes||[]){const item=make('span',visual.timeline_states[id].label),swatch=make('span');swatch.setAttribute('aria-hidden','true');applyStatePaint(swatch,id);item.prepend(swatch);legend.appendChild(item);}$('shell').after(legend);const annotations=make('div');annotations.className='untimed-markers';untimedMarkers().forEach(m=>{const b=markerButton(m);if(b)annotations.appendChild(b);});legend.after(annotations);window.addEventListener('resize',()=>{buildRuler();tickSolar();});$('shell').addEventListener('scroll',tickSolar);
788
- $('adaptivePopupClose').addEventListener('click',close);
789
- $('adaptivePopup').addEventListener('click',e=>{if(e.target===$('adaptivePopup'))close();});
790
- document.addEventListener('keydown',e=>{
791
- if($('adaptivePopup').hidden)return;
792
- if(e.key==='Escape'){e.preventDefault();close();}
793
- if(e.key==='Tab'){
794
- const nodes=[...$('adaptivePopup').querySelectorAll('button:not([hidden]),a[href],input,select,textarea')].filter(e=>!e.closest('[hidden]')),first=nodes[0],last=nodes[nodes.length-1];
795
- if(e.shiftKey&&document.activeElement===first){e.preventDefault();last.focus();}
796
- else if(!e.shiftKey&&document.activeElement===last){e.preventDefault();first.focus();}
797
- }
798
- });
799
- }
800
- return {start,home,close,records,detail,boundaryInfo,ruleText,remindersHome,reminderChoose,reminderForm,reminderDetail,reminderSettings,prayerEntries,indicatorState,twelveHourLabel,hourDetails,hourSettings,periodDetails,recalculate,configureLocation,tickPersonal,calendarText,applyPrayerMethod,solarState:()=>({observer,madhhab,solarDays,solarPeriods}),resolveLegacy(id){return registry('religious_content').legacy_rule_map.find(x=>x.legacy_id===id);}};
801
- })();
802
- window.PopupManager={open:(kind)=>RegistryApp.home(kind),close:()=>RegistryApp.close()};
803
- window.registryReady=RegistryApp.start();
 
1
+ {
2
+ "schema_name": "islamic_clock_celestial_simulation_registry",
3
+ "schema_version": "1.0.0",
4
+ "registry_id": "celestial_simulation_registry",
5
+ "project": "ساعة المسلم / الخط الزمني الروحي",
6
+ "purpose": "إعدادات العرض البصري لمحاكاة السماء والقبلة. لا يحتوي على أحكام فقهية أو مواقيت صلاة.",
7
+ "ownership": {
8
+ "owns": [
9
+ "ألوان السماء حسب ارتفاع الشمس",
10
+ "حساسية محاكاة القبلة البصرية",
11
+ "أحجام رموز الشمس والقمر والكعبة في العرض",
12
+ "نطاقات ظهور العناصر على الشاشة"
13
+ ],
14
+ "does_not_own": [
15
+ "حساب مواقيت الصلاة",
16
+ "الأحكام الفقهية",
17
+ "حدود النهي والاستحباب",
18
+ "محتوى الأذكار أو العبادات"
19
+ ]
20
+ },
21
+ "sky_color_model": {
22
+ "driver": "solar_altitude_deg",
23
+ "continuous_interpolation": true,
24
+ "description": "لون السماء ينتقل تدريجيًا مع ارتفاع الشمس، ولا يقفز بين الليل والنهار.",
25
+ "gradient_stops": [
26
+ { "at": -18, "label": "ليل فلكي", "color": "#071326" },
27
+ { "at": -12, "label": "فجر/شفق عميق", "color": "#15284b" },
28
+ { "at": -6, "label": "شفق مدني", "color": "#4b5f91" },
29
+ { "at": -1, "label": "قرب الأفق", "color": "#e08a5b" },
30
+ { "at": 4, "label": "شروق/غروب", "color": "#f4b46a" },
31
+ { "at": 15, "label": "صباح", "color": "#84c8f5" },
32
+ { "at": 45, "label": "نهار", "color": "#55b7ef" },
33
+ { "at": 75, "label": "شمس مرتفعة", "color": "#3fa7e5" }
34
+ ]
35
+ },
36
+ "objects": {
37
+ "sun": {
38
+ "visible_below_horizon_deg": -3,
39
+ "size_min_px": 26,
40
+ "size_max_px": 48
41
+ },
42
+ "moon": {
43
+ "visible_below_horizon_deg": -5,
44
+ "size_min_px": 22,
45
+ "size_max_px": 40,
46
+ "show_phase": true
47
+ },
48
+ "kaaba": {
49
+ "alignment_threshold_deg": 4,
50
+ "near_alignment_threshold_deg": 12,
51
+ "visible_when_compass_enabled": true
52
+ },
53
+ "shadow": {
54
+ "object_height_unit": 1,
55
+ "show_one_shadow": true,
56
+ "show_two_shadows": true
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
  }
58
+ },
59
+ "validation": {
60
+ "no_prayer_rulings": true,
61
+ "no_fixed_solar_minute_offsets": true,
62
+ "visual_only": true
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
  }
64
+ }