-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.js
More file actions
3863 lines (3840 loc) · 123 KB
/
main.js
File metadata and controls
3863 lines (3840 loc) · 123 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
/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository of this plugin
*/
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// main.ts
var main_exports = {};
__export(main_exports, {
default: () => DashReaderPlugin
});
module.exports = __toCommonJS(main_exports);
var import_obsidian4 = require("obsidian");
// src/rsvp-view.ts
var import_obsidian2 = require("obsidian");
// src/services/micropause-service.ts
var _HeadingStrategy = class {
getMultiplier(word) {
const trimmed = word.trim();
const match = trimmed.match(/^\[H(\d)\]/);
if (!match)
return 1;
const level = parseInt(match[1]);
return _HeadingStrategy.MULTIPLIERS[level] || 1.5;
}
};
var HeadingStrategy = _HeadingStrategy;
HeadingStrategy.MULTIPLIERS = [0, 2, 1.8, 1.5, 1.3, 1.2, 1.1];
var CalloutStrategy = class {
constructor(multiplier) {
this.multiplier = multiplier;
}
getMultiplier(word) {
const trimmed = word.trim();
return /^\[CALLOUT:[\w-]+\]/.test(trimmed) ? this.multiplier : 1;
}
};
var SectionMarkerStrategy = class {
constructor(multiplier) {
this.multiplier = multiplier;
}
getMultiplier(word) {
const trimmed = word.trim();
return /^(\d+\.|[IVXLCDM]+\.|\w\.)/.test(trimmed) ? this.multiplier : 1;
}
};
var ListBulletStrategy = class {
constructor(multiplier) {
this.multiplier = multiplier;
}
getMultiplier(word) {
const trimmed = word.trim();
return /^[-*+•]/.test(trimmed) ? this.multiplier : 1;
}
};
var SentencePunctuationStrategy = class {
constructor(multiplier) {
this.multiplier = multiplier;
}
getMultiplier(word) {
return /[.!?]$/.test(word) ? this.multiplier : 1;
}
};
var OtherPunctuationStrategy = class {
constructor(multiplier) {
this.multiplier = multiplier;
}
getMultiplier(word) {
return /[;:,]$/.test(word) ? this.multiplier : 1;
}
};
var NumberStrategy = class {
constructor(multiplier) {
this.multiplier = multiplier;
}
getMultiplier(word) {
return /\d/.test(word) ? this.multiplier : 1;
}
};
var LongWordStrategy = class {
constructor(multiplier) {
this.multiplier = multiplier;
}
getMultiplier(word) {
return word.length > 8 ? this.multiplier : 1;
}
};
var ParagraphBreakStrategy = class {
constructor(multiplier) {
this.multiplier = multiplier;
}
getMultiplier(word) {
return word.includes("\n") ? this.multiplier : 1;
}
};
var MicropauseService = class {
constructor(settings) {
this.enabled = settings.enableMicropause;
this.strategies = [
new HeadingStrategy(),
new CalloutStrategy(settings.micropauseCallouts),
new SectionMarkerStrategy(settings.micropauseSectionMarkers),
new ListBulletStrategy(settings.micropauseListBullets),
new SentencePunctuationStrategy(settings.micropausePunctuation),
new OtherPunctuationStrategy(settings.micropauseOtherPunctuation),
new NumberStrategy(settings.micropauseNumbers),
new LongWordStrategy(settings.micropauseLongWords),
new ParagraphBreakStrategy(settings.micropauseParagraph)
];
}
/**
* Calculates the total multiplier for a word
* Applies all strategies and multiplies the results
*
* @param word - The word to analyze
* @returns Total multiplier (1.0 = no pause, >1.0 = longer pause)
*
* @example
* ```typescript
* const service = new MicropauseService(settings);
*
* service.calculateMultiplier("Hello"); // 1.0 (no special characteristics)
* service.calculateMultiplier("Hello!"); // 2.5 (sentence punctuation)
* service.calculateMultiplier("[H1]Title"); // 2.0 (heading)
* service.calculateMultiplier("Hello!\n"); // 6.25 (2.5 * 2.5 = punctuation * paragraph)
* ```
*/
calculateMultiplier(word) {
if (!this.enabled)
return 1;
let totalMultiplier = 1;
for (const strategy of this.strategies) {
const strategyMultiplier = strategy.getMultiplier(word);
totalMultiplier *= strategyMultiplier;
}
return totalMultiplier;
}
/**
* Updates service with new settings
* Recreates strategies with updated multipliers
*
* @param settings - New settings
*/
updateSettings(settings) {
this.enabled = settings.enableMicropause;
this.strategies = [
new HeadingStrategy(),
new CalloutStrategy(settings.micropauseCallouts),
new SectionMarkerStrategy(settings.micropauseSectionMarkers),
new ListBulletStrategy(settings.micropauseListBullets),
new SentencePunctuationStrategy(settings.micropausePunctuation),
new OtherPunctuationStrategy(settings.micropauseOtherPunctuation),
new NumberStrategy(settings.micropauseNumbers),
new LongWordStrategy(settings.micropauseLongWords),
new ParagraphBreakStrategy(settings.micropauseParagraph)
];
}
};
// src/rsvp-engine.ts
var RSVPEngine = class {
constructor(settings, onWordChange, onComplete, timeoutManager) {
this.words = [];
this.currentIndex = 0;
this.isPlaying = false;
this.timer = null;
this.startTime = 0;
this.startWpm = 0;
this.pausedTime = 0;
this.lastPauseTime = 0;
this.headings = [];
this.wordsReadInSession = 0;
this.settings = settings;
this.onWordChange = onWordChange;
this.onComplete = onComplete;
this.timeoutManager = timeoutManager;
this.micropauseService = new MicropauseService(settings);
}
setText(text, startPosition, startWordIndex) {
const cleaned = text.replace(/\n+/g, " \xA7\xA7LINEBREAK\xA7\xA7 ").replace(/[ \t]+/g, " ").trim();
this.words = cleaned.split(/\s+/);
this.extractHeadings();
this.words = this.words.map(
(word) => word === "\xA7\xA7LINEBREAK\xA7\xA7" ? "\n" : word
);
if (startWordIndex !== void 0) {
this.currentIndex = Math.max(0, Math.min(startWordIndex, this.words.length - 1));
} else if (startPosition !== void 0 && startPosition > 0) {
const textUpToCursor = text.substring(0, startPosition);
const wordsBeforeCursor = textUpToCursor.trim().split(/\s+/).length;
this.currentIndex = Math.min(wordsBeforeCursor, this.words.length - 1);
} else {
this.currentIndex = 0;
}
}
play() {
if (this.isPlaying)
return;
if (this.currentIndex >= this.words.length) {
this.currentIndex = 0;
}
this.isPlaying = true;
if (this.startTime === 0) {
this.startTime = Date.now();
this.startWpm = this.settings.wpm;
this.wordsReadInSession = 0;
} else if (this.lastPauseTime > 0) {
this.pausedTime += Date.now() - this.lastPauseTime;
this.lastPauseTime = 0;
}
this.displayNextWord();
}
pause() {
this.isPlaying = false;
if (this.timer !== null) {
this.timeoutManager.clearTimeout(this.timer);
this.timer = null;
}
this.lastPauseTime = Date.now();
}
stop() {
this.pause();
this.currentIndex = 0;
this.startTime = 0;
this.pausedTime = 0;
this.lastPauseTime = 0;
this.startWpm = 0;
this.wordsReadInSession = 0;
}
reset() {
this.stop();
}
rewind(steps = 10) {
this.currentIndex = Math.max(0, this.currentIndex - steps);
if (this.isPlaying) {
this.pause();
this.play();
} else {
this.displayCurrentWord();
}
}
forward(steps = 10) {
this.currentIndex = Math.min(this.words.length - 1, this.currentIndex + steps);
if (this.isPlaying) {
this.pause();
this.play();
} else {
this.displayCurrentWord();
}
}
displayCurrentWord() {
if (this.currentIndex >= this.words.length) {
return;
}
const chunk = this.getChunk(this.currentIndex);
this.onWordChange(chunk);
}
displayNextWord() {
if (!this.isPlaying || this.currentIndex >= this.words.length) {
if (this.currentIndex >= this.words.length) {
this.isPlaying = false;
this.onComplete();
}
return;
}
const chunk = this.getChunk(this.currentIndex);
this.onWordChange(chunk);
let delay = this.calculateDelay(chunk.text);
if (this.settings.enableSlowStart) {
const SLOW_START_WORDS = 5;
if (this.wordsReadInSession < SLOW_START_WORDS) {
const remainingSlowWords = SLOW_START_WORDS - this.wordsReadInSession;
const slowStartMultiplier = 1 + remainingSlowWords / SLOW_START_WORDS;
delay *= slowStartMultiplier;
}
}
this.wordsReadInSession++;
this.currentIndex += this.settings.chunkSize;
this.timer = this.timeoutManager.setTimeout(() => {
this.displayNextWord();
}, delay);
}
getChunk(startIndex) {
const endIndex = Math.min(
startIndex + this.settings.chunkSize,
this.words.length
);
const chunkWords = this.words.slice(startIndex, endIndex);
const text = chunkWords.join(" ");
return {
text,
index: startIndex,
delay: this.calculateDelay(text),
isEnd: endIndex >= this.words.length,
headingContext: this.getCurrentHeadingContext(startIndex)
};
}
getCurrentWpm() {
if (!this.settings.enableAcceleration || this.startTime === 0) {
return this.settings.wpm;
}
const elapsed = (Date.now() - this.startTime - this.pausedTime) / 1e3;
if (elapsed >= this.settings.accelerationDuration) {
return this.settings.accelerationTargetWpm;
}
const progress = elapsed / this.settings.accelerationDuration;
const wpmDiff = this.settings.accelerationTargetWpm - this.startWpm;
const currentWpm = this.startWpm + wpmDiff * progress;
return Math.round(currentWpm);
}
calculateDelay(text) {
const currentWpm = this.getCurrentWpm();
const baseDelay = 60 / currentWpm * 1e3;
const multiplier = this.micropauseService.calculateMultiplier(text);
return baseDelay * multiplier;
}
/**
* Extract all headings and callouts from the words array
* Headings are marked with [H1], [H2], etc.
* Callouts are marked with [CALLOUT:type] by the markdown parser
*
* Since text is split into words, we need to collect all words
* that belong to the same heading/callout title.
*/
extractHeadings() {
this.headings = [];
for (let i = 0; i < this.words.length; i++) {
const word = this.words[i];
const headingMatch = word.match(/^\[H(\d)\](.+)/);
if (headingMatch) {
const level = parseInt(headingMatch[1]);
const firstWord = headingMatch[2];
const titleWords = [firstWord];
let j = i + 1;
while (j < this.words.length) {
const nextWord = this.words[j];
if (nextWord === "\xA7\xA7LINEBREAK\xA7\xA7") {
break;
}
if (/^\[H\d\]/.test(nextWord) || /^\[CALLOUT:/.test(nextWord)) {
break;
}
titleWords.push(nextWord);
j++;
if (titleWords.length >= 20) {
break;
}
}
const text = titleWords.join(" ").trim();
this.headings.push({
level,
text,
wordIndex: i
});
continue;
}
const calloutMatch = word.match(/^\[CALLOUT:([\w-]+)\](.+)/);
if (calloutMatch) {
const calloutType = calloutMatch[1];
const firstWord = calloutMatch[2];
const titleWords = [firstWord];
let j = i + 1;
while (j < this.words.length) {
const nextWord = this.words[j];
if (nextWord === "\xA7\xA7LINEBREAK\xA7\xA7") {
break;
}
if (/^\[H\d\]/.test(nextWord) || /^\[CALLOUT:/.test(nextWord)) {
break;
}
titleWords.push(nextWord);
j++;
if (titleWords.length >= 20) {
break;
}
}
const text = titleWords.join(" ").trim();
this.headings.push({
level: 0,
// Special level for callouts
text,
wordIndex: i,
calloutType
});
}
}
}
/**
* Get the current heading context (breadcrumb) for a given word index
* Returns the hierarchical path of headings leading to the current position
*
* @param wordIndex - Word index to get context for
* @returns Heading context with breadcrumb path and current heading
*/
getCurrentHeadingContext(wordIndex) {
if (this.headings.length === 0) {
return { breadcrumb: [], current: null };
}
const relevantHeadings = this.headings.filter((h) => h.wordIndex <= wordIndex);
if (relevantHeadings.length === 0) {
return { breadcrumb: [], current: null };
}
const breadcrumb = [];
let currentLevel = 0;
for (const heading of relevantHeadings) {
if (heading.level <= currentLevel) {
while (breadcrumb.length > 0 && breadcrumb[breadcrumb.length - 1].level >= heading.level) {
breadcrumb.pop();
}
}
breadcrumb.push(heading);
currentLevel = heading.level;
}
return {
breadcrumb,
current: breadcrumb[breadcrumb.length - 1] || null
};
}
getProgress() {
return this.words.length > 0 ? this.currentIndex / this.words.length * 100 : 0;
}
getCurrentIndex() {
return this.currentIndex;
}
getTotalWords() {
return this.words.length;
}
getIsPlaying() {
return this.isPlaying;
}
setWpm(wpm) {
this.settings.wpm = Math.max(50, Math.min(1e3, wpm));
}
getWpm() {
return this.settings.wpm;
}
setChunkSize(size) {
this.settings.chunkSize = Math.max(1, Math.min(5, size));
}
getChunkSize() {
return this.settings.chunkSize;
}
getContext(contextWords = 3) {
const beforeStart = Math.max(0, this.currentIndex - contextWords);
const afterEnd = Math.min(this.words.length, this.currentIndex + this.settings.chunkSize + contextWords);
return {
before: this.words.slice(beforeStart, this.currentIndex),
after: this.words.slice(this.currentIndex + this.settings.chunkSize, afterEnd)
};
}
updateSettings(settings) {
this.settings = settings;
this.micropauseService.updateSettings(settings);
}
getEstimatedDuration() {
if (this.words.length === 0)
return 0;
const remainingWords = Math.max(0, this.words.length - this.currentIndex);
if (remainingWords === 0)
return 0;
const averageWpm = this.settings.enableAcceleration ? (this.settings.wpm + this.settings.accelerationTargetWpm) / 2 : this.settings.wpm;
return this.calculateAccurateRemainingTime(averageWpm);
}
calculateAccurateRemainingTime(wpm) {
if (this.words.length === 0 || this.currentIndex >= this.words.length)
return 0;
let totalTimeMs = 0;
const baseDelay = 60 / wpm * 1e3;
for (let i = this.currentIndex; i < this.words.length; i++) {
const word = this.words[i];
const multiplier = this.micropauseService.calculateMultiplier(word);
totalTimeMs += baseDelay * multiplier;
}
return Math.ceil(totalTimeMs / 1e3);
}
getRemainingWords() {
return Math.max(0, this.words.length - this.currentIndex);
}
getElapsedTime() {
if (this.startTime === 0)
return 0;
const now = this.isPlaying ? Date.now() : this.lastPauseTime || Date.now();
return Math.floor((now - this.startTime - this.pausedTime) / 1e3);
}
getRemainingTime() {
if (this.words.length === 0 || this.currentIndex >= this.words.length)
return 0;
const currentWpm = this.getCurrentWpm();
return this.calculateAccurateRemainingTime(currentWpm);
}
getCurrentWpmPublic() {
return this.getCurrentWpm();
}
/**
* Returns all headings extracted from the document
* Useful for navigation and section counting
*/
getHeadings() {
return this.headings;
}
};
// src/markdown-parser.ts
var MarkdownParser = class {
static parseToPlainText(markdown) {
let text = markdown;
text = text.replace(/^---[\s\S]*?---\n?/m, "");
const codeBlocks = [];
text = text.replace(/```[\w-]*\n?([\s\S]*?)```/g, (_match, code) => {
const index = codeBlocks.length;
codeBlocks.push(code);
return `___CODE_BLOCK_${index}___`;
});
text = text.replace(/`([^`]+)`/g, "$1");
text = text.replace(/!\[([^\]]*)\]\([^)]+\)/g, "");
text = text.replace(/\[([^\]]+)\]\([^)]+\)/g, "$1");
text = text.replace(/\[\[([^\]|]+)(\|([^\]]+))?\]\]/g, (_match, link, _pipe, alias) => {
return alias || link;
});
text = text.replace(/\*\*\*([^*]+)\*\*\*/g, "$1");
text = text.replace(/\*\*([^*]+)\*\*/g, "$1");
text = text.replace(/__([^_]+)__/g, "$1");
text = text.replace(/\*([^*\n]+)\*/g, "$1");
text = text.replace(/_([^_\n]+)_/g, "$1");
text = text.replace(/~~([^~]+)~~/g, "$1");
text = text.replace(/==([^=]+)==/g, "$1");
text = text.replace(/^(#{1,6})\s+(.+)$/gm, (_match, hashes, content) => {
const level = hashes.length;
return `[H${level}]${content}`;
});
text = text.replace(/^>\s*\[!([\w-]+)\]\s*(.*)$/gm, (_match, type, title) => {
const displayTitle = title.trim() || type;
return `[CALLOUT:${type}]${displayTitle}`;
});
text = text.replace(/^>\s*/gm, "");
text = text.replace(/^[\s]*[-*+]\s+/gm, "");
text = text.replace(/^[\s]*\d+\.\s+/gm, "");
text = text.replace(/^[\s]*[-*_]{3,}[\s]*$/gm, "");
text = text.replace(/(?:^|\s)(#[a-zA-Z0-9_/-]+)/g, "");
text = text.replace(/\[\^[^\]]+\]/g, "");
text = text.replace(/^\[\^[^\]]+\]:.*$/gm, "");
text = text.replace(/^---\s*Backlinks?\s*---[\s\S]*$/m, "");
text = text.replace(/^##?\s*Backlinks?[\s\S]*$/m, "");
text = text.replace(/<!--[\s\S]*?-->/g, "");
text = text.replace(/<[^>]+>/g, "");
text = text.replace(/\n{3,}/g, "\n\n");
text = text.replace(/^[ \t]+/gm, "");
text = text.replace(/[ \t]+$/gm, "");
text = text.replace(/___CODE_BLOCK_(\d+)___/g, (_match, index) => {
return codeBlocks[parseInt(index)] || "";
});
text = text.trim();
return text;
}
/**
* Parse le texte sélectionné en tenant compte du contexte Obsidian
*/
static parseSelection(text) {
return this.parseToPlainText(text);
}
};
// src/view-state.ts
var DEFAULT_VIEW_STATE = {
wordsRead: 0,
startTime: 0,
showingControls: false,
showingSettings: false,
showingStats: false,
currentWpm: 0,
currentChunkSize: 0,
currentFontSize: 0,
isLoading: false
};
var ViewState = class {
/**
* Creates a new ViewState instance
*
* @param initialState - Optional partial state to merge with defaults
*
* @example
* ```typescript
* // Default state
* const state = new ViewState();
*
* // With initial values
* const state = new ViewState({
* currentWpm: 300,
* showingControls: true
* });
* ```
*/
constructor(initialState = {}) {
this.listeners = /* @__PURE__ */ new Set();
this.state = { ...DEFAULT_VIEW_STATE, ...initialState };
}
/**
* Get a state value (type-safe)
*
* Uses TypeScript generics to ensure return type matches the requested key.
*
* @param key - State property to get
* @returns Current value of the property
*
* @example
* ```typescript
* const wpm: number = state.get('currentWpm');
* const showing: boolean = state.get('showingControls');
* ```
*/
get(key) {
return this.state[key];
}
/**
* Set a state value and notify listeners (type-safe)
*
* Updates the state property and notifies all subscribers if the value changed.
* Automatically skips notification if the new value equals the old value.
*
* @param key - State property to set
* @param value - New value for the property
*
* @example
* ```typescript
* state.set('currentWpm', 350);
* state.set('showingControls', true);
* state.set('loadedFileName', 'My Note.md');
* ```
*/
set(key, value) {
const oldValue = this.state[key];
if (oldValue === value)
return;
this.state[key] = value;
this.notify(key, value, oldValue);
}
/**
* Update multiple state values at once (batch update)
*
* Efficiently updates multiple properties in a single call. Each changed
* property will trigger its own notification to listeners.
*
* @param updates - Partial state object with properties to update
*
* @example
* ```typescript
* state.update({
* currentWpm: 350,
* showingControls: true,
* wordsRead: 42
* });
* ```
*/
update(updates) {
Object.entries(updates).forEach(([key, value]) => {
this.set(key, value);
});
}
/**
* Reset all state to default values
*
* Sets every state property back to its default value from DEFAULT_VIEW_STATE.
* Each reset property triggers a notification to listeners.
*
* @example
* ```typescript
* // After reading session, reset to defaults
* state.reset();
* ```
*/
reset() {
Object.entries(DEFAULT_VIEW_STATE).forEach(([key, value]) => {
this.set(key, value);
});
}
/**
* Subscribe to state changes (observer pattern)
*
* Registers a listener function that will be called whenever any state
* property changes. Returns an unsubscribe function for cleanup.
*
* **Error Handling**: Listener errors are caught and logged to prevent
* one broken listener from breaking all listeners.
*
* @param listener - Callback function to call on state changes
* @returns Unsubscribe function to remove the listener
*
* @example
* ```typescript
* // Subscribe and get unsubscribe function
* const unsubscribe = state.subscribe((key, value, oldValue) => {
* if (key === 'currentWpm') {
* console.log(`WPM changed from ${oldValue} to ${value}`);
* }
* });
*
* // Later, cleanup
* unsubscribe();
* ```
*/
subscribe(listener) {
this.listeners.add(listener);
return () => this.listeners.delete(listener);
}
/**
* Notify all listeners of a state change (internal)
*
* Calls each registered listener with the changed property details.
* Catches and logs errors to prevent one broken listener from affecting others.
*
* @param key - Name of the property that changed
* @param value - New value of the property
* @param oldValue - Previous value of the property
*
* @private
*/
notify(key, value, oldValue) {
this.listeners.forEach((listener) => {
try {
listener(key, value, oldValue);
} catch (error) {
console.error("DashReader: Error in state listener", error);
}
});
}
/**
* Get all state as a plain object (for debugging)
*
* Returns a shallow copy of the entire state object. Useful for logging
* or debugging state issues.
*
* @returns Readonly copy of the full state
*
* @example
* ```typescript
* console.log('Current state:', state.getAll());
* // Output: { wordsRead: 42, currentWpm: 350, showingControls: true, ... }
* ```
*/
getAll() {
return { ...this.state };
}
/**
* Toggle a boolean state value (helper)
*
* Convenience method for toggling boolean properties. Flips the value
* from true to false or false to true.
*
* @param key - Boolean property to toggle (showingControls, showingSettings, showingStats, isLoading)
*
* @example
* ```typescript
* // Toggle control panel visibility
* state.toggle('showingControls');
*
* // Toggle settings panel
* state.toggle('showingSettings');
* ```
*/
toggle(key) {
const currentValue = this.get(key);
this.set(key, !currentValue);
}
/**
* Increment a numeric state value (helper)
*
* Convenience method for incrementing numeric properties. Can add positive
* or negative deltas.
*
* @param key - Numeric property to increment (currently only wordsRead)
* @param delta - Amount to add (default: 1, can be negative)
*
* @example
* ```typescript
* // Increment words read by 1
* state.increment('wordsRead');
*
* // Increment by 5
* state.increment('wordsRead', 5);
*
* // Decrement by 1
* state.increment('wordsRead', -1);
* ```
*/
increment(key, delta = 1) {
const currentValue = this.get(key);
this.set(key, currentValue + delta);
}
};
// src/constants.ts
var CSS_CLASSES = {
// Main container
container: "dashreader-container",
// Toggle bar
toggleBar: "dashreader-toggle-bar",
toggleBtn: "dashreader-toggle-btn",
// Display area
display: "dashreader-display",
word: "dashreader-word",
welcome: "dashreader-welcome",
highlight: "dashreader-highlight",
// Context
contextBefore: "dashreader-context-before",
contextAfter: "dashreader-context-after",
// Progress
progressContainer: "dashreader-progress-container",
progressBar: "dashreader-progress-bar",
// Controls
controls: "dashreader-controls",
controlGroup: "dashreader-control-group",
controlLabel: "control-label",
// Settings
settings: "dashreader-settings",
settingGroup: "dashreader-setting-group",
settingLabel: "setting-label",
settingToggle: "setting-toggle",
// Stats
stats: "dashreader-stats",
statsText: "dashreader-stats-text",
wpmDisplay: "dashreader-wpm-display",
// Buttons
btn: "dashreader-btn",
playBtn: "play-btn",
pauseBtn: "pause-btn",
smallBtn: "small-btn",
// Value displays
wpmValue: "wpm-value",
wpmInlineValue: "wpm-inline-value",
chunkValue: "chunk-value",
fontValue: "font-value",
accelDurationValue: "accel-duration-value",
accelTargetValue: "accel-target-value",
// State classes
hidden: "hidden"
};
var TIMING = {
/** Delay before auto-loading content from editor (file-open event) */
autoLoadDelay: 300,
/** Shorter delay for leaf-change events (editor already active) */
autoLoadDelayShort: 200,
/** Very short delay for immediate operations */
autoLoadDelayVeryShort: 50,
/** Throttle interval for cursor/selection checks (prevents excessive checks) */
throttleDelay: 150,
/** CSS transition duration for smooth animations */
transitionDuration: 300
};
var TEXT_LIMITS = {
/** Minimum characters in selection to trigger auto-load */
minSelectionLength: 30,
/** Minimum characters in full document to load */
minContentLength: 50,
/** Minimum words in parsed text to display */
minParsedLength: 10
};
var INCREMENTS = {
/** WPM increment (25 = noticeable speed change) */
wpm: 25,
/** Chunk size increment (1 word at a time) */
chunkSize: 1,
/** Font size increment in pixels (4px = visible change) */
fontSize: 4,
/** Acceleration duration increment in seconds */
accelDuration: 5
};
var LIMITS = {
/** Font size range in pixels (20 = readable minimum, 120 = fills viewport) */
fontSize: { min: 20, max: 120 },
/** WPM range (50 = very slow, 5000 = ultra-fast speed reading limit) */
wpm: { min: 50, max: 5e3 },
/** Acceleration duration in seconds (10 = quick ramp, 120 = gradual) */
accelDuration: { min: 10, max: 120 }
};
var ICONS = {
/** Rewind to start button */
rewind: "\u23EE",
/** Play button */
play: "\u25B6",
/** Pause button */
pause: "\u23F8",
/** Skip forward button */
forward: "\u23ED",
/** Stop button */
stop: "\u23F9",
/** Increment (+) button */
increment: "+",
/** Decrement (−) button (using minus sign, not hyphen) */
decrement: "\u2212",
/** Settings toggle button */
settings: "\u2699\uFE0F",
/** Statistics toggle button */
stats: "\u{1F4CA}",
/** File/document indicator */
file: "\u{1F4C4}",
/** Celebration (reading complete) */
celebration: "\u{1F389}",
/** Book/reading indicator */
book: "\u{1F4D6}",
/** Expand to new tab */
expand: "\u2922"
};
var HEADING_MULTIPLIERS = {
/** H1 heading multiplier (1.5x base font = major section) */
h1: 1.5,
/** H2 heading multiplier (1.3x base font) */
h2: 1.3,
/** H3 heading multiplier (1.2x base font) */
h3: 1.2,
/** H4 heading multiplier (1.1x base font) */
h4: 1.1,
/** H5 heading multiplier (1.05x base font) */
h5: 1.05,
/** H6 heading multiplier (1x base font = same as body text) */
h6: 1
};
// src/dom-registry.ts
var DOMRegistry = class {
constructor() {
this.elements = /* @__PURE__ */ new Map();
}
/**
* Register a DOM element by key
*
* Stores an element reference for later retrieval and updates. Should be
* called once per element during UI construction.
*
* @param key - Type-safe key for the element (from DOMElementKey union)
* @param element - HTMLElement to store
*
* @example
* ```typescript
* const wpmValue = controlGroup.createSpan({ cls: CSS_CLASSES.wpmValue });
* this.dom.register('wpmValue', wpmValue);
* ```
*/
register(key, element) {
this.elements.set(key, element);
}
/**
* Get a registered DOM element
*
* Retrieves the stored element reference. Returns undefined if the key
* was never registered.
*
* @param key - Key of the element to retrieve
* @returns The HTMLElement if registered, undefined otherwise
*
* @example
* ```typescript
* const wpmEl = this.dom.get('wpmValue');
* if (wpmEl) {
* // Do something with the element
* }
* ```
*/
get(key) {
return this.elements.get(key);
}
/**
* Update text content of a registered element (XSS-safe)
*
* Uses Obsidian's setText() method which safely escapes HTML.
* Preferred over updateHTML() for displaying user-generated content.
*
* @param key - Key of the element to update
* @param text - Text content to set (string or number)
*
* @example
* ```typescript
* this.dom.updateText('wpmValue', 350);
* this.dom.updateText('statsText', 'Words: 42 / 1000');
* ```
*/
updateText(key, text) {
const element = this.elements.get(key);
if (element) {
element.setText(String(text));
}
}