Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
5391 lines (5012 loc) · 284 KB
/
Copy pathscript.js
File metadata and controls
5391 lines (5012 loc) · 284 KB
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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* =============================================================
SURAH META: [ayahs, type]
============================================================= */
// نوع السورة: [عدد الآيات, النوع] — 🕋=مكية 🕌=مدنية
const SMETA_AR = [
[7, '🕋 مكية'], [286, '🕌 مدنية'], [200, '🕌 مدنية'], [176, '🕌 مدنية'], [120, '🕌 مدنية'],
[165, '🕋 مكية'], [206, '🕋 مكية'], [75, '🕌 مدنية'], [129, '🕌 مدنية'], [109, '🕋 مكية'],
[123, '🕋 مكية'], [111, '🕋 مكية'], [43, '🕌 مدنية'], [52, '🕋 مكية'], [99, '🕋 مكية'],
[128, '🕋 مكية'], [111, '🕋 مكية'], [110, '🕋 مكية'], [98, '🕋 مكية'], [135, '🕋 مكية'],
[112, '🕋 مكية'], [78, '🕌 مدنية'], [118, '🕋 مكية'], [64, '🕌 مدنية'], [77, '🕋 مكية'],
[227, '🕋 مكية'], [93, '🕋 مكية'], [88, '🕋 مكية'], [69, '🕋 مكية'], [60, '🕋 مكية'],
[34, '🕋 مكية'], [30, '🕋 مكية'], [73, '🕌 مدنية'], [54, '🕋 مكية'], [45, '🕋 مكية'],
[83, '🕋 مكية'], [182, '🕋 مكية'], [88, '🕋 مكية'], [75, '🕋 مكية'], [85, '🕋 مكية'],
[54, '🕋 مكية'], [53, '🕋 مكية'], [89, '🕋 مكية'], [59, '🕋 مكية'], [37, '🕋 مكية'],
[35, '🕋 مكية'], [38, '🕌 مدنية'], [29, '🕌 مدنية'], [18, '🕌 مدنية'], [45, '🕋 مكية'],
[60, '🕋 مكية'], [49, '🕋 مكية'], [62, '🕋 مكية'], [55, '🕋 مكية'], [78, '🕋 مكية'],
[96, '🕋 مكية'], [29, '🕌 مدنية'], [22, '🕌 مدنية'], [24, '🕌 مدنية'], [13, '🕌 مدنية'],
[14, '🕌 مدنية'], [11, '🕌 مدنية'], [11, '🕌 مدنية'], [18, '🕌 مدنية'], [12, '🕌 مدنية'],
[12, '🕌 مدنية'], [30, '🕋 مكية'], [52, '🕋 مكية'], [52, '🕋 مكية'], [44, '🕋 مكية'],
[28, '🕋 مكية'], [28, '🕋 مكية'], [20, '🕋 مكية'], [56, '🕋 مكية'], [40, '🕋 مكية'],
[31, '🕌 مدنية'], [50, '🕋 مكية'], [40, '🕋 مكية'], [46, '🕋 مكية'], [42, '🕋 مكية'],
[29, '🕋 مكية'], [19, '🕋 مكية'], [36, '🕋 مكية'], [25, '🕋 مكية'], [22, '🕋 مكية'],
[17, '🕋 مكية'], [19, '🕋 مكية'], [26, '🕋 مكية'], [30, '🕋 مكية'], [20, '🕋 مكية'],
[15, '🕋 مكية'], [21, '🕋 مكية'], [11, '🕋 مكية'], [8, '🕋 مكية'], [8, '🕋 مكية'],
[19, '🕋 مكية'], [5, '🕋 مكية'], [8, '🕌 مدنية'], [8, '🕌 مدنية'], [11, '🕋 مكية'],
[11, '🕋 مكية'], [8, '🕋 مكية'], [3, '🕋 مكية'], [9, '🕋 مكية'], [5, '🕋 مكية'],
[4, '🕋 مكية'], [7, '🕋 مكية'], [3, '🕋 مكية'], [6, '🕌 مدنية'], [3, '🕌 مدنية'],
[5, '🕋 مكية'], [4, '🕋 مكية'], [5, '🕋 مكية'], [6, '🕋 مكية']
];
const SMETA_EN = [
[7, '🕋 Meccan'], [286, '🕌 Medinan'], [200, '🕌 Medinan'], [176, '🕌 Medinan'], [120, '🕌 Medinan'],
[165, '🕋 Meccan'], [206, '🕋 Meccan'], [75, '🕌 Medinan'], [129, '🕌 Medinan'], [109, '🕋 Meccan'],
[123, '🕋 Meccan'], [111, '🕋 Meccan'], [43, '🕌 Medinan'], [52, '🕋 Meccan'], [99, '🕋 Meccan'],
[128, '🕋 Meccan'], [111, '🕋 Meccan'], [110, '🕋 Meccan'], [98, '🕋 Meccan'], [135, '🕋 Meccan'],
[112, '🕋 Meccan'], [78, '🕌 Medinan'], [118, '🕋 Meccan'], [64, '🕌 Medinan'], [77, '🕋 Meccan'],
[227, '🕋 Meccan'], [93, '🕋 Meccan'], [88, '🕋 Meccan'], [69, '🕋 Meccan'], [60, '🕋 Meccan'],
[34, '🕋 Meccan'], [30, '🕋 Meccan'], [73, '🕌 Medinan'], [54, '🕋 Meccan'], [45, '🕋 Meccan'],
[83, '🕋 Meccan'], [182, '🕋 Meccan'], [88, '🕋 Meccan'], [75, '🕋 Meccan'], [85, '🕋 Meccan'],
[54, '🕋 Meccan'], [53, '🕋 Meccan'], [89, '🕋 Meccan'], [59, '🕋 Meccan'], [37, '🕋 Meccan'],
[35, '🕋 Meccan'], [38, '🕌 Medinan'], [29, '🕌 Medinan'], [18, '🕌 Medinan'], [45, '🕋 Meccan'],
[60, '🕋 Meccan'], [49, '🕋 Meccan'], [62, '🕋 Meccan'], [55, '🕋 Meccan'], [78, '🕋 Meccan'],
[96, '🕋 Meccan'], [29, '🕌 Medinan'], [22, '🕌 Medinan'], [24, '🕌 Medinan'], [13, '🕌 Medinan'],
[14, '🕌 Medinan'], [11, '🕌 Medinan'], [11, '🕌 Medinan'], [18, '🕌 Medinan'], [12, '🕌 Medinan'],
[12, '🕌 Medinan'], [30, '🕋 Meccan'], [52, '🕋 Meccan'], [52, '🕋 Meccan'], [44, '🕋 Meccan'],
[28, '🕋 Meccan'], [28, '🕋 Meccan'], [20, '🕋 Meccan'], [56, '🕋 Meccan'], [40, '🕋 Meccan'],
[31, '🕌 Medinan'], [50, '🕋 Meccan'], [40, '🕋 Meccan'], [46, '🕋 Meccan'], [42, '🕋 Meccan'],
[29, '🕋 Meccan'], [19, '🕋 Meccan'], [36, '🕋 Meccan'], [25, '🕋 Meccan'], [22, '🕋 Meccan'],
[17, '🕋 Meccan'], [19, '🕋 Meccan'], [26, '🕋 Meccan'], [30, '🕋 Meccan'], [20, '🕋 Meccan'],
[15, '🕋 Meccan'], [21, '🕋 Meccan'], [11, '🕋 Meccan'], [8, '🕋 Meccan'], [8, '🕋 Meccan'],
[19, '🕋 Meccan'], [5, '🕋 Meccan'], [8, '🕌 Medinan'], [8, '🕌 Medinan'], [11, '🕋 Meccan'],
[11, '🕋 Meccan'], [8, '🕋 Meccan'], [3, '🕋 Meccan'], [9, '🕋 Meccan'], [5, '🕋 Meccan'],
[4, '🕋 Meccan'], [7, '🕋 Meccan'], [3, '🕋 Meccan'], [6, '🕌 Medinan'], [3, '🕌 Medinan'],
[5, '🕋 Meccan'], [4, '🕋 Meccan'], [5, '🕋 Meccan'], [6, '🕋 Meccan']
];
let surahs = [
{ n: 1, name: "الفاتحة" }, { n: 2, name: "البقرة" }, { n: 3, name: "آل عمران" },
{ n: 4, name: "النساء" }, { n: 5, name: "المائدة" }, { n: 6, name: "الأنعام" },
{ n: 7, name: "الأعراف" }, { n: 8, name: "الأنفال" }, { n: 9, name: "التوبة" },
{ n: 10, name: "يونس" }, { n: 11, name: "هود" }, { n: 12, name: "يوسف" },
{ n: 13, name: "الرعد" }, { n: 14, name: "إبراهيم" }, { n: 15, name: "الحجر" },
{ n: 16, name: "النحل" }, { n: 17, name: "الإسراء" }, { n: 18, name: "الكهف" },
{ n: 19, name: "مريم" }, { n: 20, name: "طه" }, { n: 21, name: "الأنبياء" },
{ n: 22, name: "الحج" }, { n: 23, name: "المؤمنون" }, { n: 24, name: "النور" },
{ n: 25, name: "الفرقان" }, { n: 26, name: "الشعراء" }, { n: 27, name: "النمل" },
{ n: 28, name: "القصص" }, { n: 29, name: "العنكبوت" }, { n: 30, name: "الروم" },
{ n: 31, name: "لقمان" }, { n: 32, name: "السجدة" }, { n: 33, name: "الأحزاب" },
{ n: 34, name: "سبأ" }, { n: 35, name: "فاطر" }, { n: 36, name: "يس" },
{ n: 37, name: "الصافات" }, { n: 38, name: "ص" }, { n: 39, name: "الزمر" },
{ n: 40, name: "غافر" }, { n: 41, name: "فصلت" }, { n: 42, name: "الشورى" },
{ n: 43, name: "الزخرف" }, { n: 44, name: "الدخان" }, { n: 45, name: "الجاثية" },
{ n: 46, name: "الأحقاف" }, { n: 47, name: "محمد" }, { n: 48, name: "الفتح" },
{ n: 49, name: "الحجرات" }, { n: 50, name: "ق" }, { n: 51, name: "الذاريات" },
{ n: 52, name: "الطور" }, { n: 53, name: "النجم" }, { n: 54, name: "القمر" },
{ n: 55, name: "الرحمن" }, { n: 56, name: "الواقعة" }, { n: 57, name: "الحديد" },
{ n: 58, name: "المجادلة" }, { n: 59, name: "الحشر" }, { n: 60, name: "الممتحنة" },
{ n: 61, name: "الصف" }, { n: 62, name: "الجمعة" }, { n: 63, name: "المنافقون" },
{ n: 64, name: "التغابن" }, { n: 65, name: "الطلاق" }, { n: 66, name: "التحريم" },
{ n: 67, name: "الملك" }, { n: 68, name: "القلم" }, { n: 69, name: "الحاقة" },
{ n: 70, name: "المعارج" }, { n: 71, name: "نوح" }, { n: 72, name: "الجن" },
{ n: 73, name: "المزمل" }, { n: 74, name: "المدثر" }, { n: 75, name: "القيامة" },
{ n: 76, name: "الإنسان" }, { n: 77, name: "المرسلات" }, { n: 78, name: "النبأ" },
{ n: 79, name: "النازعات" }, { n: 80, name: "عبس" }, { n: 81, name: "التكوير" },
{ n: 82, name: "الانفطار" }, { n: 83, name: "المطففين" }, { n: 84, name: "الانشقاق" },
{ n: 85, name: "البروج" }, { n: 86, name: "الطارق" }, { n: 87, name: "الأعلى" },
{ n: 88, name: "الغاشية" }, { n: 89, name: "الفجر" }, { n: 90, name: "البلد" },
{ n: 91, name: "الشمس" }, { n: 92, name: "الليل" }, { n: 93, name: "الضحى" },
{ n: 94, name: "الشرح" }, { n: 95, name: "التين" }, { n: 96, name: "العلق" },
{ n: 97, name: "القدر" }, { n: 98, name: "البينة" }, { n: 99, name: "الزلزلة" },
{ n: 100, name: "العاديات" }, { n: 101, name: "القارعة" }, { n: 102, name: "التكاثر" },
{ n: 103, name: "العصر" }, { n: 104, name: "الهمزة" }, { n: 105, name: "الفيل" },
{ n: 106, name: "قريش" }, { n: 107, name: "الماعون" }, { n: 108, name: "الكوثر" },
{ n: 109, name: "الكافرون" }, { n: 110, name: "النصر" }, { n: 111, name: "المسد" },
{ n: 112, name: "الإخلاص" }, { n: 113, name: "الفلق" }, { n: 114, name: "الناس" }
];
/* ============ API ============ */
const API = {
ar: { s: 'https://www.mp3quran.net/api/v3/suwar?language=ar', r: 'https://www.mp3quran.net/api/v3/reciters?language=ar' },
en: { s: 'https://www.mp3quran.net/api/v3/suwar?language=eng', r: 'https://www.mp3quran.net/api/v3/reciters?language=eng' }
};
/* ============ TRANSLATIONS ============ */
const T = {
ar: {
play: '▶ تشغيل', pause: '⏸ إيقاف',
repLabel: '🔄 ', repModes: ['٠', '١', '٢', '٣', '∞'],
statusDef: 'الرجاء اختيار القارئ والمصحف والسورة.',
readySt: (s, r, m) => `🎧 ${s} — ${r}`,
dlPfx: '📥 تحميل: ',
srchPh: '🔍 ابحث...', srchNote: '💡 اكتب حرفاً للتصفية',
recLbl: 'اختر القارئ:', moshLbl: 'اختر المصحف:', surahLbl: 'اختر السورة:',
volLbl: '🔊', spdLbl: 'سرعة:', stopLbl: 'إيقاف بعد:',
stopOpts: {
none: 'لا يوجد', endSurah: 'انتهاء السورة', endMoshaf: 'انتهاء المصحف',
'5': '5 دق', '10': '10 دق', '15': '15 دق', '20': '20 دق', '30': '30 دق',
'45': '45 دق', '60': 'ساعة', '120': 'ساعتان', '180': '3 ساعات',
'240': '4 ساعات', '300': '5 ساعات', '360': '6 ساعات', '420': '7 ساعات'
},
randRec: 'قارئ عشوائي', randSurah: 'سورة عشوائية', favTitle: 'مفضل',
bmTitle: 'إضافة إشارة', bmHeader: '📌 الإشارات المرجعية',
statsHeader: '📊 إحصائيات', statCountLbl: 'جلسات', statMinLbl: 'دقيقة',
notifFin: (n) => `انتهت تلاوة سورة ${n}`, notifTimer: 'انتهى المؤقّت.',
bmPrompt: 'ملاحظة / رقم آية (اختياري):', bmAdded: '✅ إشارة مرجعية مضافة.',
favSet: '⭐ تم تعيين المفضل.', favUnset: 'تم إزالة المفضل.',
dlSurah: '📥 تحميل السورة', hideDl: '🔼 إخفاء',
recentHeader: '⏱️ آخر ما استمعت إليه',
ayahsLbl: 'آية', appTitle: 'مشغل القرآن الكريم',
expLbl: '📤 تصدير', stopTimerLbl: 'ينتهي بعد:',
shareDlgTitle: 'مشاركة', shareDeepLbl: 'مشاركة التلاوة في التطبيق',
shareDeepSub: 'يفتح نفس القارئ والسورة والآية مباشرة',
shareAyahLbl: 'مشاركة نص الآية الحالية',
shareAyahSub: 'نسخ ومشاركة الآية بالرسم العثماني مع الرابط',
shareWebLbl: 'مشاركة رابط التطبيق العام',
shareWebSub: 'يفتح الصفحة الرئيسية لمشغل القرآن الكريم', shareSurahLbl: 'مشاركة ملف الصوت المباشر (MP3)',
shareSurahSub: 'رابط استماع وتحميل مباشر لملف السورة', shareCancelLbl: 'إلغاء',
installTitle: 'ثبّت التطبيق', installSub: 'استمع من شاشتك الرئيسية',
installBtn: 'تثبيت',
dInstallTitle: 'ثبّت التطبيق على حاسوبك',
dInstallSub: 'يعمل بدون إنترنت — وصول سريع من سطح المكتب',
dInstallBtn: '📥 تثبيت',
rangeFromLbl: 'من:', rangeToLbl: 'إلى:',
allSurahsTitle: '📚 قائمة السور', allLinksTitle: '📥 روابط تحميل السور',
cardsBtn: '🃏 بطاقات', linksBtn: '🔗 روابط',
dlHint: '💡 انقر الرابط لتحميل السورة',
clearBm: '🗑️ مسح الإشارات', clearStats: '🗑️ مسح الإحصائيات',
mtabPlayer: '🎵 المشغل', mtabText: '📖 النص',
projRadio: '📻 راديو القرآن', projDb: '🗄️ قاعدة بيانات القرآن',
recSearchPh: '🔍 بحث...',
qcfLoading: n => n ? `⏳ تحميل خطوط المصحف… ${n}` : '⏳ تحميل خطوط المصحف…',
qcfReady: '🕋 خطوط المصحف جاهزة',
qcfPartial: '⚠️ تعذّر تحميل بعض الصفحات — عُرضت آياتها بالنص العادي',
qcfError: '⚠️ تعذّر تحميل خطوط المصحف — عُرض النص العادي',
tajweedLoading: n => n ? `⏳ تحميل خط التجويد… ${n}` : '⏳ تحميل خط التجويد…',
tajweedReady: '🎨 خط التجويد جاهز',
tajweedPartial: '⚠️ تعذّر تحميل بعض صفحات خط التجويد — عُرضت آياتها بالنص العادي',
tajweedError: '⚠️ تعذّر تحميل خط التجويد — عُرض النص العادي',
copiedOk: '✅ تم النسخ إلى الحافظة',
qpTitle: 'القرآن الكريم',
qpTabText: '📖 النص', qpTabInfo: 'ℹ️ المعلومات', qpTabMushaf: '🖼️ المصحف',
optUthmani: '🕌 رسم عثماني', optPrint: '📝 نص مطبوع', optSimple: '✏️ نص عادي', optQcf: '🕋 خط المصحف', optTajweed: '🎨 خط التجويد',
optBlock: '≡ كل آية بسطر', optInline: '⋯ متتاليات',
qpSearchPh: '🔍 ابحث في السورة (بدون حركات) أو برقم الآية...',
qpAutoScrollLbl: 'متزامن تقريباً مع التلاوة',
qpShare: 'مشاركة', qpClear: 'مسح البيانات', qpClose: 'إغلاق', qpSettings: 'الإعدادات', qpSearchToggle: 'بحث في السورة', qpCornerToggle: 'إظهار / إخفاء الأزرار والأدوات',
qpFontMinus: 'تصغير خط النص', qpFontPlus: 'تكبير خط النص',
radio: '📻 مشروع القرآن راديو'
},
en: {
play: '▶ Play', pause: '⏸ Pause',
repLabel: '🔄 ', repModes: ['0', '1', '2', '3', '∞'],
statusDef: 'Please select a reciter, moshaf and surah.',
readySt: (s, r, m) => `🎧 ${s} — ${r}`,
dlPfx: '📥 Download: ',
srchPh: '🔍 Search...', srchNote: '💡 Type to filter',
recLbl: 'Select reciter:', moshLbl: 'Select moshaf:', surahLbl: 'Select surah:',
volLbl: '🔊', spdLbl: 'Speed:', stopLbl: 'Stop after:',
stopOpts: {
none: 'None', endSurah: 'End of surah', endMoshaf: 'End of moshaf',
'5': '5 min', '10': '10 min', '15': '15 min', '20': '20 min', '30': '30 min',
'45': '45 min', '60': '1 hr', '120': '2 hr', '180': '3 hr',
'240': '4 hr', '300': '5 hr', '360': '6 hr', '420': '7 hr'
},
randRec: 'Random reciter', randSurah: 'Random surah', favTitle: 'Favorite',
bmTitle: 'Add bookmark', bmHeader: '📌 Bookmarks',
statsHeader: '📊 Stats', statCountLbl: 'sessions', statMinLbl: 'min',
notifFin: (n) => `Finished playing ${n}`, notifTimer: 'Timer finished.',
bmPrompt: 'Note / verse number (optional):', bmAdded: '✅ Bookmark added.',
favSet: '⭐ Added to favorites.', favUnset: 'Removed from favorites.',
dlSurah: '📥 Download', hideDl: '🔼 Hide',
recentHeader: '⏱️ Recently played',
ayahsLbl: 'verses', appTitle: 'Quran Player',
expLbl: '📤 Export', stopTimerLbl: 'Stops in:',
shareDlgTitle: 'Share', shareDeepLbl: 'Share recitation in app',
shareDeepSub: 'Opens the exact reciter, surah & ayah',
shareAyahLbl: 'Share current ayah text',
shareAyahSub: 'Copy or share Uthmani verse text with link',
shareWebLbl: 'Share general app link',
shareWebSub: 'Opens Quran Player home page', shareSurahLbl: 'Share direct MP3 audio link',
shareSurahSub: 'Direct listen / download MP3 file', shareCancelLbl: 'Cancel',
installTitle: 'Install App', installSub: 'Listen from your home screen',
installBtn: 'Install',
dInstallTitle: 'Install App on Desktop',
dInstallSub: 'Works offline — quick access from your desktop',
dInstallBtn: '📥 Install',
rangeFromLbl: 'From:', rangeToLbl: 'To:',
allSurahsTitle: '📚 Surah List', allLinksTitle: '📥 Surah Download Links',
cardsBtn: '🃏 Cards', linksBtn: '🔗 Links',
dlHint: '💡 Click the link to download the surah',
clearBm: '🗑️ Clear Bookmarks', clearStats: '🗑️ Clear Stats',
mtabPlayer: '🎵 Player', mtabText: '📖 Text',
projRadio: '📻 Quran Radio', projDb: '🗄️ Quran Database',
recSearchPh: '🔍 Search...',
qcfLoading: n => n ? `⏳ Loading mushaf fonts… ${n}` : '⏳ Loading mushaf fonts…',
qcfReady: '🕋 Mushaf fonts ready',
qcfPartial: '⚠️ Some pages failed — those verses shown as plain text',
qcfError: '⚠️ Mushaf fonts failed to load — plain text shown',
tajweedLoading: n => n ? `⏳ Loading tajweed font… ${n}` : '⏳ Loading tajweed font…',
tajweedReady: '🎨 Tajweed font ready',
tajweedPartial: '⚠️ Some tajweed pages failed to load — plain text shown',
tajweedError: '⚠️ Tajweed font failed to load — plain text shown',
copiedOk: '✅ Copied to clipboard',
qpTitle: 'The Noble Quran',
qpTabText: '📖 Text', qpTabInfo: 'ℹ️ Info', qpTabMushaf: '🖼️ Mushaf',
optUthmani: '🕌 Uthmani', optPrint: '📝 Print', optSimple: '✏️ Plain', optQcf: '🕋 Mushaf font', optTajweed: '🎨 Tajweed font',
optBlock: '≡ One ayah per line', optInline: '⋯ Flowing text',
qpSearchPh: '🔍 Search in surah (without diacritics) or by ayah number...',
qpAutoScrollLbl: 'Roughly synced with the recitation',
qpShare: 'Share', qpClear: 'Clear data', qpClose: 'Close', qpSettings: 'Settings', qpSearchToggle: 'Search in surah', qpCornerToggle: 'Show / hide buttons & tools',
qpFontMinus: 'Decrease text size', qpFontPlus: 'Increase text size',
radio: '📻 Quran Radio project'
}
};
/* ============ STATE ============ */
let lang = 'ar', theme = 'default';
let reciters = [], rIdx = null, mIdx = null, sIdx = null;
let repeatMode = 0, repeatCount = 0, autoNext = true;
let isPlaying = false, isMuted = false, volBefore = 70;
let stopTimer = null, stopEndTime = null, stopTimerTick = null;
let favR = null, favM = null;
let bookmarks = [], stats = { count: 0, times: {}, total: 0 };
let recent = [];
let dragging = false;
let deferredPrompt = null;
let qcfChipState = '', qcfChipProgress = '';
let autoPlayOnChange = (localStorage.getItem('autoPlayOnChange') ?? '1') === '1';
let playReqId = 0;
function escHTML(str) {
return String(str ?? '').replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
}
/* ============ PRECISION AYAH TIMINGS ENGINE ============ */
const PRECISION_RECITERS = [
{ qid: 4, ar: "أبو بكر الشاطري", en: "Abu Bakr al-Shatri", m_ar: "حفص عن عاصم (مزامنة دقيقة 🎯)", m_en: "Hafs an Asim (Precise Verse Sync 🎯)" },
{ qid: 19, ar: "أحمد بن علي العجمي", en: "Ahmed Al-Ajamy", m_ar: "حفص عن عاصم (مزامنة دقيقة 🎯)", m_en: "Hafs an Asim (Precise Verse Sync 🎯)" },
{ qid: 13, ar: "سعد الغامدي", en: "Saad Al-Ghamdi", m_ar: "حفص عن عاصم (مزامنة دقيقة 🎯)", m_en: "Hafs an Asim (Precise Verse Sync 🎯)" },
{ qid: 10, ar: "سعود الشريم", en: "Sa`ud ash-Shuraym", m_ar: "حفص عن عاصم (مزامنة دقيقة 🎯)", m_en: "Hafs an Asim (Precise Verse Sync 🎯)" },
{ qid: 17, ar: "سهل ياسين", en: "Sahl Yasin", m_ar: "حفص عن عاصم (مزامنة دقيقة 🎯)", m_en: "Hafs an Asim (Precise Verse Sync 🎯)" },
{ qid: 43, ar: "صلاح البدير", en: "Salah Al-Budair", m_ar: "حفص عن عاصم (مزامنة دقيقة 🎯)", m_en: "Hafs an Asim (Precise Verse Sync 🎯)" },
{ qid: 18, ar: "صلاح بو خاطر", en: "Salah Bukhatir", m_ar: "حفص عن عاصم (مزامنة دقيقة 🎯)", m_en: "Hafs an Asim (Precise Verse Sync 🎯)" },
{ qid: 2, ar: "عبد الباسط عبد الصمد (مرتل)", en: "AbdulBaset AbdulSamad (Murattal)", m_ar: "حفص عن عاصم - مرتل (مزامنة دقيقة 🎯)", m_en: "Murattal (Precise Verse Sync 🎯)" },
{ qid: 1, ar: "عبد الباسط عبد الصمد (مجود)", en: "AbdulBaset AbdulSamad (Tajweed)", m_ar: "المصحف المجود (مزامنة دقيقة 🎯)", m_en: "Mujawwad (Precise Verse Sync 🎯)" },
{ qid: 3, ar: "عبد الرحمن السديس", en: "Abdur-Rahman as-Sudais", m_ar: "حفص عن عاصم (مزامنة دقيقة 🎯)", m_en: "Hafs an Asim (Precise Verse Sync 🎯)" },
{ qid: 11, ar: "عبد المحسن القاسم", en: "Abdul Muhsin al-Qasim", m_ar: "حفص عن عاصم (مزامنة دقيقة 🎯)", m_en: "Hafs an Asim (Precise Verse Sync 🎯)" },
{ qid: 14, ar: "فارس عباد", en: "Fares Abbad", m_ar: "حفص عن عاصم (مزامنة دقيقة 🎯)", m_en: "Hafs an Asim (Precise Verse Sync 🎯)" },
{ qid: 9, ar: "محمد صديق المنشاوي (مرتل)", en: "Mohamed Siddiq al-Minshawi (Murattal)", m_ar: "حفص عن عاصم - مرتل (مزامنة دقيقة 🎯)", m_en: "Murattal (Precise Verse Sync 🎯)" },
{ qid: 8, ar: "محمد صديق المنشاوي (مجود)", en: "Mohamed Siddiq al-Minshawi (Tajweed)", m_ar: "المصحف المجود — تلاوة نقية", m_en: "Mujawwad (High Quality)", audioServer: "https://cdn.mp3quran.net/audio/muhammad-minshawi/r2/" },
{ qid: 6, ar: "محمود خليل الحصري (مرتل)", en: "Mahmoud Khalil Al-Husary (Murattal)", m_ar: "حفص عن عاصم - مرتل (مزامنة دقيقة 🎯)", m_en: "Murattal (Precise Verse Sync 🎯)" },
{ qid: 12, ar: "محمود خليل الحصري (المعلم)", en: "Mahmoud Khalil Al-Husary (Teacher)", m_ar: "المصحف المعلم (مزامنة دقيقة 🎯)", m_en: "Muallim (Precise Verse Sync 🎯)" },
{ qid: 7, ar: "مشاري راشد العفاسي", en: "Mishari Rashid al-`Afasy", m_ar: "حفص عن عاصم (مزامنة دقيقة 🎯)", m_en: "Murattal (Precise Verse Sync 🎯)" },
{ qid: 5, ar: "هاني الرفاعي", en: "Hani ar-Rifai", m_ar: "حفص عن عاصم (مزامنة دقيقة 🎯)", m_en: "Hafs an Asim (Precise Verse Sync 🎯)" }
];
let currentAyahTimestamps = null;
let precisionAudioUrl = null;
let pendingResumeAyah = null;
const timestampsCache = new Map();
/* بحث ثنائي موحّد للعثور على رقم الآية عند الزمن بالمللي ثانية */
function findAyahAtMs(curMs) {
if (!currentAyahTimestamps || !currentAyahTimestamps.length) return null;
let low = 0, high = currentAyahTimestamps.length - 1;
while (low <= high) {
const mid = (low + high) >> 1;
const seg = currentAyahTimestamps[mid];
if (curMs >= seg.timestamp_from && curMs < seg.timestamp_to) {
return parseInt(seg.verse_key.split(':')[1], 10);
}
if (curMs < seg.timestamp_from) high = mid - 1;
else low = mid + 1;
}
const last = currentAyahTimestamps[currentAyahTimestamps.length - 1];
if (curMs >= last.timestamp_from) {
return parseInt(last.verse_key.split(':')[1], 10);
}
return null;
}
/* الحصول على رقم الآية الحالية أثناء الاستماع بدقة */
function getCurrentAyahNumber() {
if (!audio || (!audio.currentTime && audio.currentTime !== 0)) return null;
if (audio.currentTime <= 0 && isNaN(audio.duration)) return null;
const exact = findAyahAtMs(Math.floor((audio.currentTime || 0) * 1000));
if (exact !== null) return exact;
if (audio.duration && ayahsData && ayahsData.length) {
const ratio = Math.min(1, Math.max(0, audio.currentTime / audio.duration));
return Math.min(ayahsData.length, Math.max(1, Math.floor(ratio * ayahsData.length) + 1));
}
return null;
}
function getPrecisionReciters(currentLang) {
const isAr = currentLang !== 'en';
const allSurahsList = Array.from({ length: 114 }, (_, i) => i + 1).join(',');
return PRECISION_RECITERS.map(pr => ({
id: `precision_${pr.qid}`,
name: (isAr ? pr.ar : pr.en) + ' 🎯',
cleanName: isAr ? pr.ar : pr.en,
isPrecision: true,
precisionQid: pr.qid,
audioServer: pr.audioServer || null,
moshaf: [
{
id: `m_prec_${pr.qid}`,
name: isAr ? pr.m_ar : pr.m_en,
server: pr.audioServer || `https://api.quran.com/api/v4/chapter_recitations/${pr.qid}/`,
surah_total: 114,
surah_list: allSurahsList,
isPrecision: true,
precisionQid: pr.qid
}
]
}));
}
function mergeReciters(rawList, currentLang) {
const prec = getPrecisionReciters(currentLang);
const pure = (rawList || []).filter(r => r && !r.isPrecision && !String(r.id || '').startsWith('precision_'));
return [...prec, ...pure];
}
async function fetchPrecisionAudioData(qid, surahN) {
const cacheKey = `${qid}_${surahN}`;
if (timestampsCache.has(cacheKey)) {
return timestampsCache.get(cacheKey);
}
// معالجة خاصة للشيخ المنشاوي مجود (سيرفر صوتي نقي وموثوق من mp3quran)
if (qid === 8) {
const sPadded = String(surahN).padStart(3, '0');
const result = {
audioUrl: `https://cdn.mp3quran.net/audio/muhammad-minshawi/r2/${sPadded}.mp3`,
timestamps: []
};
timestampsCache.set(cacheKey, result);
return result;
}
try {
const lsCached = lsJSON('ts_' + cacheKey);
if (lsCached && lsCached.audioUrl) {
timestampsCache.set(cacheKey, lsCached);
return lsCached;
}
} catch (e) { }
try {
const resp = await fetch(`https://api.quran.com/api/v4/chapter_recitations/${qid}/${surahN}?segments=true`);
if (!resp.ok) throw new Error('Segments API failed');
const data = await resp.json();
const af = data.audio_file;
if (af && af.audio_url) {
// تنظيف الرابط وإزالة أي شرطات مكررة //
const cleanUrl = af.audio_url.replace(/([^:])\/\/+/g, '$1/');
const result = {
audioUrl: cleanUrl,
timestamps: af.timestamps || []
};
timestampsCache.set(cacheKey, result);
try { lsSave('ts_' + cacheKey, JSON.stringify(result)); } catch (e) { }
return result;
}
} catch (err) {
console.warn('Precision segments fetch fallback:', err);
}
return null;
}
/* ============ TOASTS (إشعارات شفافة وذكية) ============ */
let toastTimer = null;
function showToast(msg, type, duration = 3000) {
const host = $('toastHost');
if (!host) { if (statusDiv) statusDiv.textContent = msg; return; }
host.querySelectorAll('.toast').forEach(t => t.remove());
const el = document.createElement('div');
el.className = 'toast' + (type ? ' toast-' + type : '');
el.setAttribute('role', 'status');
el.textContent = msg;
el.title = lang === 'ar' ? 'انقر للإغلاق السريع' : 'Click to dismiss';
el.onclick = () => {
clearTimeout(toastTimer);
el.classList.remove('show');
setTimeout(() => { try { el.remove(); } catch (e) { } }, 200);
};
host.appendChild(el);
requestAnimationFrame(() => el.classList.add('show'));
clearTimeout(toastTimer);
toastTimer = setTimeout(() => {
el.classList.remove('show');
setTimeout(() => { try { el.remove(); } catch (e) { } }, 250);
}, duration);
}
/* ============ DOM ============ */
const $ = id => document.getElementById(id);
const audio = $('audio');
const recSel = $('reciter'), moshSel = $('moshaf'), surahSel = $('surah');
const statusDiv = $('status');
const playBtn = $('playBtn'), repBtn = $('repeatBtn');
const prevBtn = $('prevBtn'), nextBtn = $('nextBtn'), muteBtn = $('muteBtn');
const volCtrl = $('volCtrl'), volVal = $('volVal');
const speedCtrl = $('speedCtrl'), speedVal = $('speedVal');
const stopSel = $('stopAfter');
const stopTimerDisplay = $('stopTimerDisplay');
const stopTimerClock = $('stopTimerClock');
const stopTimerLabel = $('stopTimerLabel');
const stopCancelBtn = $('stopCancelBtn');
const progTrack = $('progTrack'), progThumb = $('progThumb');
const tElapsed = $('tElapsed'), tRemaining = $('tRemaining');
const npCard = $('npCard'), eqWrap = $('eqWrap');
const npSurah = $('npSurah'), npReciter = $('npReciter'), npBadges = $('npBadges');
const surahSearch = $('surahSearch'), recSearch = $('reciterSearch');
const dlBtn = $('dlBtn'); // dlAllBtnCards/dlAllBtnLinks declared below
const dlSection = $('dlSection'), allSection = $('allSection');
const dlLink = $('dlLink'), allList = $('allList');
const bmBtn = $('bmBtn'), bmSection = $('bmSection'), bmList = $('bmList');
const recentSection = $('recentSection'), recentList = $('recentList');
const statsSection = $('statsSection');
const themeBtn = $('themeBtn'), paletteBtn = $('paletteBtn'), palettePanel = $('palettePanel');
const langBtn = $('langBtn'), shareBtn = $('shareBtn'), infoBtn = $('infoBtn');
const shortcutsPanel = $('shortcutsPanel');
const shareOverlay = $('shareOverlay');
const installBanner = $('installBanner'), installBtn = $('installBtn'), installClose = $('installClose');
const expBtn = $('expBtn');
const randRecBtn = $('randRecBtn'), randSurahBtn = $('randSurahBtn'), favBtn = $('favBtn');
// Quran text panel
const textViewBtn = $('textViewBtn');
const appLayout = $('appLayout');
const quranPanel = $('quranPanel');
const qpClose = $('qpClose');
const qpBody = $('qpBody');
const qpSearchBar = $('qpSearchBar');
const qpTitle = $('qpTitle');
const qpMeta = $('qpMeta');
const qpSearch = $('qpSearch');
const qpReciterSel = $('qpReciterSel'), qpSurahSel = $('qpSurahSel');
const qpSearchToggleBtn = $('qpSearchToggleBtn'), qpSettingsBtn = $('qpSettingsBtn');
const qpCornerToggleBtn = $('qpCornerToggleBtn');
const qpMobFontMinus = $('qpMobFontMinus'), qpMobFontPlus = $('qpMobFontPlus');
const qpAutoScroll = $('qpAutoScroll');
// حالة لوحة النص — تُعلَن هنا، تُعرَّف في قسم QURAN PANEL
let textPanelOpen = false;
// Desktop install bar
const desktopInstallBar = $('desktopInstallBar');
const dInstallBtn = $('dInstallBtn');
const dInstallClose = $('dInstallClose');
/* ============ PWA ============ */
// المانيفست والأيقونة و Service Worker ملفات حقيقية (manifest.json / icon.svg / sw.js)
// — التسجيل من blob: URL مرفوض في المتصفحات ولا يعمل.
(() => {
if ('serviceWorker' in navigator && location.protocol !== 'file:') {
navigator.serviceWorker.register('sw.js').catch(e => console.warn('SW:', e));
}
// Install prompt
window.addEventListener('beforeinstallprompt', e => {
e.preventDefault(); deferredPrompt = e;
installBanner.classList.add('show'); // mobile bottom banner
if (desktopInstallBar) desktopInstallBar.classList.add('show'); // desktop bar
});
window.addEventListener('appinstalled', () => {
installBanner.classList.remove('show');
if (desktopInstallBar) desktopInstallBar.classList.remove('show');
});
})();
/* ============ SPLASH ============ */
window.addEventListener('load', () => {
setTimeout(() => {
$('splash').classList.add('hide');
setTimeout(() => $('splash').remove(), 500);
}, 700);
});
/* ============ LOAD RECITERS ============ */
// قراءة JSON من localStorage بأمان
function lsJSON(k) { try { return JSON.parse(ls(k) || 'null'); } catch (e) { return null; } }
// تهيئة الواجهة بعد توفر قائمة القراء (من الكاش أو الشبكة)
function initAfterReciters() {
buildReciterList();
updateStopOpts(); // الخيارات أولاً كي تستعيد الإعدادات المحفوظة قيمها
loadSettings();
migrateStopDefault(); // الافتراضي «لا يوجد»
updateRecOpts();
loadBookmarks(); loadStats(); loadRecent();
updateFavIcon();
updateUI();
if (typeof initTajweedLegend === 'function') initTajweedLegend();
}
async function loadReciters() {
const saved = ls('language'); if (saved === 'en' || saved === 'ar') lang = saved;
// عرض فوري لقائمة القرّاء المعتمدين أولاً لضمان عدم بقاء القائمة فارغة نهائياً
reciters = getPrecisionReciters(lang);
buildReciterList();
// 1) عرض فوري من الكاش المحلي إن وُجد (stale-while-revalidate)
const cacheKey = 'recitersCache_' + lang;
const cached = lsJSON(cacheKey);
let usedCache = false;
const cachedList = Array.isArray(cached) ? cached : (cached && Array.isArray(cached.reciters) ? cached.reciters : null);
if (cachedList && cachedList.length) {
reciters = mergeReciters(cachedList, lang);
usedCache = true;
initAfterReciters();
}
// 2) جلب نسخة حديثة من الشبكة وتحديث الكاش
try {
const resp = await fetch(API[lang].r);
const data = await resp.json();
const fresh = Array.isArray(data.reciters) ? data.reciters : (Array.isArray(data) ? data : (data.data || []));
if (Array.isArray(fresh) && fresh.length) {
const mergedFresh = mergeReciters(fresh, lang);
const freshStr = JSON.stringify(mergedFresh);
if (!usedCache) {
reciters = mergedFresh;
lsSave(cacheKey, freshStr);
initAfterReciters();
} else if (freshStr !== JSON.stringify(cached)) {
lsSave(cacheKey, freshStr);
// لا نستبدل القائمة أثناء استخدامها — فقط إذا لم يبدأ المستخدم اختياراً
if (!isPlaying && rIdx === null) { reciters = mergedFresh; buildReciterList(); }
}
}
} catch (e) {
if (!usedCache) {
reciters = getPrecisionReciters(lang);
initAfterReciters();
}
}
await loadSurahNames();
restoreStopTimer();
const handledShared = handleHashShortcuts();
if (!handledShared) setTimeout(() => autoStartSession(), 350);
}
function buildReciterList(filterQ = '') {
const t = T[lang];
recSel.innerHTML = '';
const ph = document.createElement('option'); ph.value = ''; ph.textContent = t.recLbl.replace(/[::]$/, '');
recSel.appendChild(ph);
reciters.forEach((r, i) => {
if (!r || !r.name) return;
if (filterQ && !r.name.toLowerCase().includes(filterQ.toLowerCase())) return;
const opt = document.createElement('option'); opt.value = i;
opt.textContent = (favR === i ? '⭐ ' : '') + r.name;
recSel.appendChild(opt);
});
if (rIdx !== null && rIdx >= 0 && rIdx < reciters.length) {
recSel.value = rIdx;
} else {
recSel.value = '';
if (rIdx !== null && (rIdx < 0 || rIdx >= reciters.length)) rIdx = null;
}
syncMobileSelectors();
}
/* مزامنة القوائم المنسدلة المباشرة للقارئ والسورة في شاشة نص الجوال */
function syncMobileSelectors() {
if (qpReciterSel && recSel) {
if (qpReciterSel.options.length !== recSel.options.length) {
qpReciterSel.innerHTML = recSel.innerHTML;
} else {
Array.from(recSel.options).forEach((o, i) => {
if (qpReciterSel.options[i] && qpReciterSel.options[i].textContent !== o.textContent) {
qpReciterSel.options[i].textContent = o.textContent;
}
});
}
qpReciterSel.value = rIdx !== null ? String(rIdx) : '';
}
if (qpSurahSel && surahSel) {
if (qpSurahSel.options.length !== surahSel.options.length) {
qpSurahSel.innerHTML = surahSel.innerHTML;
}
qpSurahSel.value = sIdx !== null ? String(sIdx) : '';
}
}
async function loadSurahNames() {
// عرض فوري من الكاش ثم تحديث بالخلفية
const cacheKey = 'suwarCache_' + lang;
const cached = lsJSON(cacheKey);
if (Array.isArray(cached) && cached.length) {
surahs = cached;
buildSurahList();
buildRangeSelects();
}
try {
const resp = await fetch(API[lang].s);
const data = await resp.json();
const list = data.suwar || data.data || (Array.isArray(data) ? data : null);
if (list && Array.isArray(list)) {
const mapped = list.map(it => ({ n: parseInt(it.id || it.number || it.index), name: it.name || it.english_name || it.surah_name || it.native }));
lsSave(cacheKey, JSON.stringify(mapped));
surahs = mapped;
buildSurahList();
buildRangeSelects(); // مدى السور
}
} catch (e) { console.warn('surah names fallback'); }
}
/* ============ BUILD LISTS ============ */
function buildMoshafList() {
const t = T[lang];
// نحفظ السورة الحالية لنتابع من مكانها إن وُجدت لدى القارئ الجديد
const keepSurah = (sIdx !== null && surahs[sIdx]) ? surahs[sIdx].n : null;
moshSel.innerHTML = `<option value="">${t.moshLbl.replace(/[::]$/, '')}</option>`;
surahSel.innerHTML = `<option value="">${t.surahLbl.replace(/[::]$/, '')}</option>`;
if (rIdx === null || !reciters[rIdx] || !Array.isArray(reciters[rIdx].moshaf)) {
mIdx = null; sIdx = null;
updateStatus();
return;
}
reciters[rIdx].moshaf.forEach((m, i) => {
const o = document.createElement('option'); o.value = i; o.textContent = m.name; moshSel.appendChild(o);
});
mIdx = null; sIdx = null;
// اختيار تلقائي للمصحف الأول فور اختيار القارئ — يوفّر نقرة ويبدأ الاستماع مباشرة
if (reciters[rIdx].moshaf.length) {
const list = reciters[rIdx].moshaf;
const hasSurah = (mi, n) => {
try { return (list[mi]?.surah_list || '').split(',').map(Number).includes(n); } catch (e) { return false; }
};
let pick = 0;
// إن لم يحتوِ المصحف الأول السورة الحالية اخترنا مصحفاً يحتويها
// (يبقى المصحف الأول هو الأصل، ويمنع فقدان موضع الاستماع)
if (keepSurah !== null && !hasSurah(0, keepSurah)) {
const alt = list.findIndex((_, i) => hasSurah(i, keepSurah));
if (alt > 0) pick = alt;
}
mIdx = pick; moshSel.value = String(pick);
if (keepSurah !== null && hasSurah(pick, keepSurah)) {
const idx = surahs.findIndex(x => x.n === keepSurah);
if (idx >= 0) sIdx = idx;
}
buildSurahList();
}
updateStatus();
}
function buildSurahList(filterQ = '') {
const t = T[lang];
surahSel.innerHTML = `<option value="">${t.surahLbl.replace(/[::]$/, '')}</option>`;
if (rIdx !== null && mIdx !== null && reciters[rIdx] && reciters[rIdx].moshaf && reciters[rIdx].moshaf[mIdx]) {
const m = reciters[rIdx].moshaf[mIdx];
const avail = (m.surah_list || '').split(',').map(Number);
avail.forEach(num => {
const s = surahs.find(x => x.n === num); if (!s) return;
if (filterQ && !s.name.toLowerCase().includes(filterQ.toLowerCase()) && !String(num).includes(filterQ)) return;
const o = document.createElement('option'); o.value = surahs.indexOf(s);
o.textContent = `${s.n}. ${s.name}`; surahSel.appendChild(o);
});
}
if (sIdx !== null && sIdx >= 0 && (!surahs.length || sIdx < surahs.length)) {
surahSel.value = sIdx;
} else if (sIdx !== null) {
sIdx = null;
}
if (qpSurahSel) {
qpSurahSel.innerHTML = surahSel.innerHTML;
qpSurahSel.value = sIdx !== null ? String(sIdx) : '';
}
updateStatus();
}
/* ============ AUDIO URL ============ */
function audioUrl() {
if (rIdx === null || mIdx === null || sIdx === null) return '';
const r = reciters[rIdx];
if (!r) return '';
if (r.isPrecision && precisionAudioUrl) return precisionAudioUrl;
if (r.audioServer) {
return r.audioServer + String(surahs[sIdx].n).padStart(3, '0') + '.mp3';
}
const m = r.moshaf && r.moshaf[mIdx];
if (!m) return '';
if (m.server && m.server.startsWith('http')) {
if (m.server.includes('quran.com')) return precisionAudioUrl || '';
return m.server + String(surahs[sIdx].n).padStart(3, '0') + '.mp3';
}
return '';
}
/* تحضير بيانات المزامنة والرابط الصوتي مسبقاً عند اختيار قارئ متزامن (حتى قبل ضغط تشغيل) */
async function prefetchPrecisionCurrent() {
syncAutoScrollBanner();
if (rIdx === null || sIdx === null) return;
const r = reciters[rIdx];
const s = surahs[sIdx];
if (!r || !s || !r.isPrecision) {
currentAyahTimestamps = null;
syncAutoScrollBanner();
return;
}
if (r.audioServer) {
precisionAudioUrl = r.audioServer + String(s.n).padStart(3, '0') + '.mp3';
currentAyahTimestamps = null;
updateDlLink();
syncAutoScrollBanner();
return;
}
const pData = await fetchPrecisionAudioData(r.precisionQid, s.n);
if (rIdx !== null && reciters[rIdx] === r && sIdx !== null && surahs[sIdx] === s && pData && pData.audioUrl) {
precisionAudioUrl = pData.audioUrl;
currentAyahTimestamps = pData.timestamps || [];
updateDlLink();
syncAutoScrollBanner();
}
}
/* ============ PLAY ============ */
async function playAudio() {
if (rIdx === null || mIdx === null || sIdx === null) {
statusDiv.textContent = T[lang].statusDef;
return;
}
const reqId = ++playReqId;
const r = reciters[rIdx];
const s = surahs[sIdx];
const surahN = s ? s.n : (sIdx + 1);
const resumeTarget = pendingResumeAyah;
pendingResumeAyah = null;
const resumeTargetAyah = (resumeTarget && resumeTarget.surahNum === surahN) ? resumeTarget.ayah : null;
if (r && r.isPrecision) {
if (r.audioServer) {
precisionAudioUrl = r.audioServer + String(surahN).padStart(3, '0') + '.mp3';
currentAyahTimestamps = null;
if (audio.src !== precisionAudioUrl) {
audio.src = precisionAudioUrl;
audio.load();
}
syncAutoScrollBanner();
} else {
statusDiv.innerHTML = `<span style="color:var(--primary)">⏳ ${lang === 'ar' ? 'جاري تجهيز التلاوة المتزامنة مع الآيات…' : 'Loading synchronized recitation…'}</span>`;
const pData = await fetchPrecisionAudioData(r.precisionQid, surahN);
if (reqId !== playReqId) return; // حارس السباق عند تغيير السورة أو القارئ بسرعة
if (pData && pData.audioUrl) {
precisionAudioUrl = pData.audioUrl;
currentAyahTimestamps = pData.timestamps || [];
if (audio.src !== pData.audioUrl) {
audio.src = pData.audioUrl;
audio.load();
}
syncAutoScrollBanner();
if (autoHighlight && textPanelOpen && ayahsData.length) {
setTimeout(() => highlightCurrentPosition(), 60);
}
} else {
precisionAudioUrl = null;
currentAyahTimestamps = null;
const url = audioUrl();
if (!url) { statusDiv.textContent = T[lang].statusDef; return; }
if (audio.src !== url) { audio.src = url; audio.load(); }
syncAutoScrollBanner();
}
}
} else {
precisionAudioUrl = null;
currentAyahTimestamps = null;
const url = audioUrl();
if (!url) { statusDiv.textContent = T[lang].statusDef; return; }
if (audio.src !== url) { audio.src = url; audio.load(); }
syncAutoScrollBanner();
}
// استكمال التلاوة من نفس الآية عند تغيير القارئ أو النقر على آية قبل التشغيل
if (resumeTargetAyah && resumeTargetAyah > 0) {
let sought = false;
const applyAyahSeek = () => {
if (sought || reqId !== playReqId) return;
sought = true;
let targetSec = 0;
if (currentAyahTimestamps && currentAyahTimestamps.length) {
const vKey = `${surahN}:${resumeTargetAyah}`;
const seg = currentAyahTimestamps.find(t => t.verse_key === vKey);
if (seg && typeof seg.timestamp_from === 'number') {
targetSec = seg.timestamp_from / 1000;
}
} else if (audio.duration && ayahsData && ayahsData.length) {
targetSec = Math.max(0, ((resumeTargetAyah - 1) / ayahsData.length) * audio.duration);
}
if (targetSec >= 0) {
try {
audio.currentTime = targetSec;
highlightCurrentPosition();
showToast(lang === 'ar' ? `الانتقال إلى الآية ${resumeTargetAyah} ⏱️` : `Jumped to Ayah ${resumeTargetAyah} ⏱️`, 'info');
} catch (e) { }
}
};
if (audio.readyState >= 1 && audio.duration) {
applyAyahSeek();
} else {
audio.addEventListener('loadedmetadata', applyAyahSeek, { once: true });
audio.addEventListener('canplay', applyAyahSeek, { once: true });
}
}
const savedSpeed = parseFloat(speedCtrl.value) || 1;
audio.playbackRate = savedSpeed;
audio.play().catch(e => console.warn('Audio play error:', e));
updateDlLink();
updateNP();
setupMediaSession();
updateStatus();
}
/* مساعد موحّد لاختيار القارئ والمصحف والسورة مع تحديث الواجهة */
function selectReciterMoshafSurah(ri, mi, si, shouldPlay = false) {
if (ri !== null && ri !== undefined && ri >= 0 && ri < reciters.length) {
recSel.value = ri; rIdx = ri; buildMoshafList();
}
const mo = (rIdx !== null && reciters[rIdx] && reciters[rIdx].moshaf) || [];
if (mi !== null && mi !== undefined && mi >= 0 && mi < mo.length) {
moshSel.value = mi; mIdx = mi; buildSurahList();
}
if (si !== null && si !== undefined && si >= 0 && si < surahs.length) {
surahSel.value = si;
sIdx = (surahSel.value === String(si)) ? si : (surahSel.value === '' ? null : parseInt(surahSel.value));
}
syncMobileSelectors();
updateStatus(); updateDlLink(); updateFavIcon(); renderNP(); saveSettings();
prefetchPrecisionCurrent();
onSurahChangeForText();
if (shouldPlay) playAudio();
}
/* مطابقة القارئ والمصحف والسورة بالمعرّف الثابت (لتفادي تغير الترتيب عند تبديل اللغة) */
function resolveSavedIndices(p) {
if (!p) return { ri: null, mi: null, si: null };
const num = v => (v === null || v === undefined || v === '') ? null : parseInt(v);
let ri = null, mi = null, si = null;
if (p.recId !== undefined && p.recId !== null) {
const foundR = reciters.findIndex(r => String(r.id) === String(p.recId));
if (foundR >= 0) ri = foundR;
}
if (ri === null) ri = num(p.rIdx);
if (ri !== null && (isNaN(ri) || ri < 0 || ri >= reciters.length)) ri = null;
if (ri !== null) {
const mList = reciters[ri]?.moshaf || [];
if (p.moshId !== undefined && p.moshId !== null) {
const foundM = mList.findIndex(m => String(m.id) === String(p.moshId));
if (foundM >= 0) mi = foundM;
}
if (mi === null) mi = num(p.mIdx);
if (mi !== null && (isNaN(mi) || mi < 0 || mi >= mList.length)) mi = 0;
}
if (p.surahNum !== undefined && p.surahNum !== null) {
const foundS = surahs.findIndex(s => s.n === parseInt(p.surahNum));
if (foundS >= 0) si = foundS;
}
if (si === null) si = num(p.sIdx);
if (si !== null && (isNaN(si) || si < 0 || si >= surahs.length)) si = null;
return { ri, mi, si };
}
/* استكمال من آخر موضع */
function resumeLast() {
const p = lsJSON('lastPos');
if (!p) return;
const { ri, mi, si } = resolveSavedIndices(p);
if (ri !== null && si !== null) {
selectReciterMoshafSurah(ri, mi, si, true);
audio.addEventListener('loadeddata', () => {
audio.currentTime = p.time || 0;
}, { once: true });
}
}
/* ── استكمال الجلسة تلقائياً عند فتح التطبيق ── */
let pendingResume = null; // { si, time }
function autoStartSession() {
const p = lsJSON('lastPos') || lsJSON('settings');
let { ri, mi, si } = resolveSavedIndices(p);
if (ri === null || isNaN(ri) || ri < 0 || ri >= reciters.length) {
const afasyIdx = reciters.findIndex(r => r.cleanName && (r.cleanName.includes('مشاري') || r.cleanName.includes('Afasy')));
ri = afasyIdx >= 0 ? afasyIdx : 0;
mi = 0;
const isFriday = new Date().getDay() === 5;
si = isFriday ? 17 : 0;
}
if (ri < 0 || ri >= reciters.length) return;
selectReciterMoshafSurah(ri, mi, si, false);
const t = p ? (parseFloat(p.time) || 0) : 0;
if (t > 0 && sIdx !== null) pendingResume = { si: sIdx, time: t };
openTextPanel();
}
/* ============ NOW PLAYING ============ */
function renderNP() {
if (rIdx === null || sIdx === null) { npCard.classList.add('hidden'); return; }
npCard.classList.remove('hidden');
const s = surahs[sIdx], r = reciters[rIdx];
npSurah.textContent = s.name; npReciter.textContent = r.name;
npBadges.innerHTML = '';
const meta = (lang === 'ar' ? SMETA_AR : SMETA_EN)[sIdx];
if (meta) {
const b1 = document.createElement('span'); b1.className = 'badge'; b1.textContent = meta[0] + ' ' + T[lang].ayahsLbl; npBadges.appendChild(b1);
const b2 = document.createElement('span'); b2.className = 'badge'; b2.textContent = meta[1]; npBadges.appendChild(b2);
}
if (r && r.isPrecision) {
const syncB = document.createElement('span');
syncB.className = 'badge';
syncB.textContent = lang === 'ar' ? '🎯 متزامن بالمللي ثانية' : '🎯 Millisecond Sync';
syncB.style.background = 'linear-gradient(135deg, #059669, #10b981)';
syncB.style.color = '#ffffff';
syncB.style.fontWeight = '700';
npBadges.appendChild(syncB);
}
updateFloatingBar(); // تحديث الشريط العائم
}
// تُستدعى عند بدء تشغيل فعلي فقط — تحديث البطاقة + إضافة لقائمة "آخر ما استمعت إليه"
function updateNP() {
renderNP();
if (rIdx !== null && sIdx !== null) addRecent(rIdx, mIdx, sIdx);
}
/* ============ PROGRESS BAR ============ */
// شريط التقدم: الجزء المُشغَّل يمتد من اليسار (LTR ثابت داخل prog-ltr-wrap)
const progElapsed = document.getElementById('progElapsed');
// حفظ آخر موضع: مخنوق كل 3 ثوانٍ (الكتابة المتزامنة لـ localStorage مكلفة عند كل timeupdate)
let lastPosSavedAt = 0;
function saveLastPos(force) {
if (rIdx === null || sIdx === null) return;
const now = Date.now();
if (!force && now - lastPosSavedAt < 3000) return;
lastPosSavedAt = now;
let time = audio.currentTime || 0;
// لا نمحو الموضع المحفوظ إن لم يبدأ تشغيل فعلي بعد (الصوت لم يُحمّل)
if (!time && (!audio.src || !isFinite(audio.duration) || !audio.duration)) {
const prev = lsJSON('lastPos');
if (prev && prev.rIdx === rIdx && prev.sIdx === sIdx && (prev.time || 0) > 0) time = prev.time;
}
lsSave('lastPos', JSON.stringify({
rIdx, mIdx, sIdx,
recId: reciters[rIdx]?.id ?? null,
moshId: reciters[rIdx]?.moshaf?.[mIdx]?.id ?? null,
surahNum: surahs[sIdx]?.n ?? null,
time
}));
}
window.addEventListener('pagehide', () => saveLastPos(true));
// الحفظ عند إخفاء التطبيق (تبديل التطبيقات/قفل الشاشة على الجوال)
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'hidden') saveLastPos(true);
});
function updateProg() {
if (dragging) return;
const dur = audio.duration || 0, cur = audio.currentTime || 0;
// تقييد النسبة بين 0 و100 لثبات بصري كامل (LTR)
const pct = dur > 0 ? Math.max(0, Math.min(100, cur / dur * 100)) : 0;
// progElapsed = الجزء المُشغَّل (يمتد من اليسار)
progElapsed.style.width = pct + '%';
// progThumb = النقطة تتحرك مع الجزء المُشغَّل
progThumb.style.left = pct + '%';
tElapsed.textContent = fmtTime(cur);
tRemaining.textContent = '−' + fmtTime(Math.max(0, dur - cur));
saveLastPos();
}
function seekTo(e) {
const rect = progTrack.getBoundingClientRect();
const x = (e.clientX || e.touches?.[0]?.clientX || 0) - rect.left;