-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinkedin-tool.user.js
7832 lines (6802 loc) · 216 KB
/
linkedin-tool.user.js
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
// ==UserScript==
// @name LinkedIn Tool
// @namespace [email protected]
// @match https://www.linkedin.com/*
// @noframes
// @version 5.97
// @author Mike Castle
// @description Minor enhancements to LinkedIn. Mostly just hotkeys.
// @license GPL-3.0-or-later; https://www.gnu.org/licenses/gpl-3.0-standalone.html
// @downloadURL https://github.com/nexushoratio/userscripts/raw/main/linkedin-tool.user.js
// @supportURL https://github.com/nexushoratio/userscripts/blob/main/linkedin-tool.md
// @require https://cdn.jsdelivr.net/npm/@violentmonkey/shortcut@1
// @require https://update.greasyfork.org/scripts/478188/1299734/NH_xunit.js
// @require https://update.greasyfork.org/scripts/477290/1333365/NH_base.js
// @require https://update.greasyfork.org/scripts/478349/1284417/NH_userscript.js
// @require https://update.greasyfork.org/scripts/478440/1304193/NH_web.js
// @require https://update.greasyfork.org/scripts/478676/1310174/NH_widget.js
// @grant GM.getValue
// @grant GM.setValue
// @grant window.onurlchange
// ==/UserScript==
/* global VM */
// eslint-disable-next-line max-lines-per-function
(async () => {
'use strict';
const NH = window.NexusHoratio.base.ensure([
{name: 'xunit', minVersion: 51},
{name: 'base', minVersion: 52},
{name: 'userscript', minVersion: 5},
{name: 'web', minVersion: 6},
{name: 'widget', minVersion: 27},
]);
/**
* Load options from storage.
*
* TODO: Over engineer this into having a schema that could be used for
* building an edit widget.
*
* Saved options will be augmented by any new defaults and resaved.
* @returns {object} - Options key/value pairs.
*/
async function loadOptions() {
const defaultOptions = {
enableDevMode: false,
enableScrollerChangesFocus: false,
enableIssue241ClickMethod: false,
enableIssue244Changes: false,
fakeErrorRate: 0.8,
};
const savedOptions = await NH.userscript.getValue('Options', {});
const options = {
...defaultOptions,
...savedOptions,
};
NH.userscript.setValue('Options', options);
return options;
}
const litOptions = await loadOptions();
NH.xunit.testing.enabled = litOptions.enableDevMode;
/* eslint-disable require-atomic-updates */
NH.base.Logger.configs = await NH.userscript.getValue('Logger');
document.addEventListener('visibilitychange', async () => {
if (document.visibilityState === 'hidden') {
await NH.userscript.setValue('Logger', NH.base.Logger.configs);
}
if (document.visibilityState === 'visible') {
NH.base.Logger.configs = await NH.userscript.getValue('Logger');
}
});
/* eslint-enable */
// TODO(#145): The if test is just here while developing.
if (!litOptions.enableDevMode) {
NH.base.Logger.config('Default').enabled = true;
}
const log = new NH.base.Logger('Default');
const globalKnownIssues = [
['Bob', 'Bob has no issues'],
['', 'Minor internal improvement'],
['#106', 'info view: more tabs: News, License'],
['#130', 'Factor hotkey handling out of SPA'],
['#156', 'Support <b>Profile</b> view'],
[
'#157', '<b>InvitationManager</b>: Invite not scrolling into ' +
'view upon refresh',
],
['#160', 'Support direct <b>JobView</b>'],
['#167', 'Refactor into libraries'],
[
'#169', '<b>JobCollections</b>: reading the details pane is ' +
'cumbersome',
],
[
'#208', '<code>Scroller</code>: If end-item is never viewable ' +
'(e.g., empty), cannot wrap',
],
['#209', 'Support <b>SearchResultsPeople</b> view'],
[
'#218', 'So some <code>Page</code> instances need to be reset on ' +
'revisit anyway?',
],
[
'#229', '<b>Jobs<b>: <em>Recent job searches</em> is ' +
'not scrolling properly',
],
[
'#230', '<b>JobCollections</b>: first/last never gets a ' +
'chance to work on job cards',
],
['#231', '<b>JobCollections</b>: Support delete/next type navigation'],
['#232', '<code>Scroller</code>: Change the focus UX'],
['#233', 'Support <b>Invitation Manager Sent Invites</b>'],
['#236', 'Support <b>Events</b> page'],
['#240', '<code>Scroller</code>: navbar height can change'],
['#242', 'Need to reconnect the LIT menu on certain pages'],
['#245', 'Revisit pages that use the terms "section{,s}" or "card{,s}"'],
['#253', 'Support <b>My Network Events</b> page'],
['#255', 'Support <b>Search appearances</b> page'],
['#256', 'Support <b>Verify</b> page'],
['#257', 'Support <b>Analytics & tools</b> page'],
];
const globalNewsContent = [
{
date: '2024-02-26',
issues: ['#240'],
subject: 'Move <code>Scroller</code> assignment from ctor to setter',
},
{
date: '2024-02-25',
issues: ['#240'],
subject: 'Use a setter to assign the managed <code>Scroller</code>',
},
{
date: '2024-02-25',
issues: ['#240'],
subject: 'Use optional chaining with <code>this.#scroller</code>',
},
{
date: '2024-02-22',
issues: ['#255', '#256', '#257'],
subject: 'Acknowledge a number a newly discovered pages',
},
{
date: '2024-02-15',
issues: ['#253'],
subject: 'Acknowledge <em>My Network Events</em> page',
},
{
date: '2024-02-15',
issues: ['#236'],
subject: 'Implement <kbd><kbd>S</kbd></kbd>hare current event',
},
{
date: '2024-02-15',
issues: ['#236'],
subject: 'Support the <em>Your events</em> collection',
},
{
date: '2024-02-14',
issues: ['#167'],
subject: 'Migrate to using <code>Service()</code> from lib/base',
},
{
date: '2024-02-13',
issues: ['#240'],
subject: 'Allow changing top/bottom margins in <code>Scroller</code>',
},
{
date: '2024-02-12',
issues: ['#236'],
subject: 'Implement <kbd><kbd>n</kbd></kbd>/<kbd><kbd>p</kbd></kbd> ' +
'secondary navigation within collections',
},
{
date: '2024-02-12',
issues: ['#167'],
subject: 'Bump version of lib/base.js being used',
},
{
date: '2024-02-11',
issues: ['#245'],
subject: 'Rework <em>My Network</em> to use the terms ' +
'<em>collection</em> and <em>individual</em>',
},
{
date: '2024-02-10',
issues: ['#167'],
subject: 'Migrate <code>Service</code> to lib/base',
},
{
date: '2024-02-09',
issues: ['#236'],
subject: 'Support primary navigation',
},
{
date: '2024-02-07',
issues: ['#242'],
subject: 'Wait for the <em>For Business</em> menu item to show up',
},
{
date: '2024-02-07',
issues: ['#240'],
subject: 'Attach a <code>ResizeObserver</code> to the global nav bar',
},
{
date: '2024-02-05',
issues: ['#236'],
subject: 'Initial <code>Events</code> support',
},
];
/**
* Implement HTML for a tabbed user interface.
*
* This version uses radio button/label pairs to select the active panel.
*
* @example
* const tabby = new TabbedUI('Tabby Cat');
* document.body.append(tabby.container);
* tabby.addTab(helpTabDefinition);
* tabby.addTab(docTabDefinition);
* tabby.addTab(contactTabDefinition);
* tabby.goto(helpTabDefinition.name); // Set initial tab
* tabby.next();
* const entry = tabby.tabs.get(contactTabDefinition.name);
* entry.classList.add('random-css');
* entry.innerHTML += '<p>More contact info.</p>';
*/
class TabbedUI {
/**
* @param {string} name - Used to distinguish HTML elements and CSS
* classes.
*/
constructor(name) {
this.#log = new NH.base.Logger(`TabbedUI ${name}`);
this.#name = name;
this.#idName = NH.base.safeId(name);
this.#id = NH.base.uuId(this.#idName);
this.#container = document.createElement('section');
this.#container.id = `${this.#id}-container`;
this.#installControls();
this.#container.append(this.#nav);
this.#installStyle();
this.#log.log(`${this.#name} constructed`);
}
/** @type {Element} */
get container() {
return this.#container;
}
/**
* @typedef {object} TabEntry
* @property {string} name - Tab name.
* @property {Element} label - Tab label, so CSS can be applied.
* @property {Element} panel - Tab panel, so content can be updated.
*/
/** @type {Map<string,TabEntry>} */
get tabs() {
const entries = new Map();
for (const label of this.#nav.querySelectorAll(
':scope > label[data-tabbed-name]'
)) {
entries.set(label.dataset.tabbedName, {label: label});
}
for (const panel of this.container.querySelectorAll(
`:scope > .${this.#idName}-panel`
)) {
entries.get(panel.dataset.tabbedName).panel = panel;
}
return entries;
}
/**
* A string of HTML or a prebuilt Element.
* @typedef {(string|Element)} TabContent
*/
/**
* @typedef {object} TabDefinition
* @property {string} name - Tab name.
* @property {TabContent} content - Initial content.
*/
/** @param {TabDefinition} tab - The new tab. */
addTab(tab) {
const me = 'addTab';
this.#log.entered(me, tab);
const {
name,
content,
} = tab;
const idName = NH.base.safeId(name);
const input = this.#createInput(name, idName);
const label = this.#createLabel(name, input, idName);
const panel = this.#createPanel(name, idName, content);
input.addEventListener('change', this.#onChange.bind(this, panel));
this.#nav.before(input);
this.#navSpacer.before(label);
this.container.append(panel);
const inputChecked =
`#${this.container.id} > ` +
`input[data-tabbed-name="${name}"]:checked`;
this.#style.textContent +=
`${inputChecked} ~ nav > [data-tabbed-name="${name}"] {` +
' border-bottom: 3px solid black;' +
'}\n';
this.#style.textContent +=
`${inputChecked} ~ div[data-tabbed-name="${name}"] {` +
' display: flex;' +
'}\n';
this.#log.leaving(me);
}
/** Activate the next tab. */
next() {
const me = 'next';
this.#log.entered(me);
this.#switchTab(1);
this.#log.leaving(me);
}
/** Activate the previous tab. */
prev() {
const me = 'prev';
this.#log.entered(me);
this.#switchTab(-1);
this.#log.leaving(me);
}
/** @param {string} name - Name of the tab to activate. */
goto(name) {
const me = 'goto';
this.#log.entered(me, name);
const controls = this.#getTabControls();
const control = controls.find(item => item.dataset.tabbedName === name);
control.click();
this.#log.leaving(me);
}
#container
#id
#idName
#log
#name
#nav
#navSpacer
#nextButton
#prevButton
#style
/** Installs basic CSS styles for the UI. */
#installStyle = () => {
this.#style = document.createElement('style');
this.#style.id = `${this.#id}-style`;
const styles = [
`#${this.container.id} {` +
' flex-grow: 1; overflow-y: hidden; display: flex;' +
' flex-direction: column;' +
'}',
`#${this.container.id} > input { display: none; }`,
`#${this.container.id} > nav { display: flex; flex-direction: row; }`,
`#${this.container.id} > nav button { border-radius: 50%; }`,
`#${this.container.id} > nav > label {` +
' cursor: pointer;' +
' margin-top: 1ex; margin-left: 1px; margin-right: 1px;' +
' padding: unset; color: unset !important;' +
'}',
`#${this.container.id} > nav > .spacer {` +
' margin-left: auto; margin-right: auto;' +
' border-right: 1px solid black;' +
'}',
`#${this.container.id} label::before { all: unset; }`,
`#${this.container.id} label::after { all: unset; }`,
// Panels are both flex items AND flex containers.
`#${this.container.id} .${this.#idName}-panel {` +
' display: none; overflow-y: auto; flex-grow: 1;' +
' flex-direction: column;' +
'}',
'',
];
this.#style.textContent = styles.join('\n');
document.head.prepend(this.#style);
}
/**
* Get the tab controls currently in the container.
* @returns {Element[]} - Control elements for the tabs.
*/
#getTabControls = () => {
const controls = Array.from(this.container.querySelectorAll(
':scope > input'
));
return controls;
}
/**
* Switch to an adjacent tab.
* @param {number} direction - Either 1 or -1.
* @fires Event#change
*/
#switchTab = (direction) => {
const me = 'switchTab';
this.#log.entered(me, direction);
const controls = this.#getTabControls();
this.#log.log('controls:', controls);
let idx = controls.findIndex(item => item.checked);
if (idx === NH.base.NOT_FOUND) {
idx = 0;
} else {
idx = (idx + direction + controls.length) % controls.length;
}
controls[idx].click();
this.#log.leaving(me);
}
/**
* @param {string} name - Human readable name for tab.
* @param {string} idName - Normalized to be CSS class friendly.
* @returns {Element} - Input portion of the tab.
*/
#createInput = (name, idName) => {
const me = 'createInput';
this.#log.entered(me);
const input = document.createElement('input');
input.id = `${this.#idName}-input-${idName}`;
input.name = `${this.#idName}`;
input.dataset.tabbedId = `${this.#idName}-input-${idName}`;
input.dataset.tabbedName = name;
input.type = 'radio';
this.#log.leaving(me, input);
return input;
}
/**
* @param {string} name - Human readable name for tab.
* @param {Element} input - Input element associated with this label.
* @param {string} idName - Normalized to be CSS class friendly.
* @returns {Element} - Label portion of the tab.
*/
#createLabel = (name, input, idName) => {
const me = 'createLabel';
this.#log.entered(me);
const label = document.createElement('label');
label.dataset.tabbedId = `${this.#idName}-label-${idName}`;
label.dataset.tabbedName = name;
label.htmlFor = input.id;
label.innerText = `[${name}]`;
this.#log.leaving(me, label);
return label;
}
/**
* @param {string} name - Human readable name for tab.
* @param {string} idName - Normalized to be CSS class friendly.
* @param {TabContent} content - Initial content.
* @returns {Element} - Panel portion of the tab.
*/
#createPanel = (name, idName, content) => {
const me = 'createPanel';
this.#log.entered(me);
const panel = document.createElement('div');
panel.dataset.tabbedId = `${this.#idName}-panel-${idName}`;
panel.dataset.tabbedName = name;
panel.classList.add(`${this.#idName}-panel`);
if (content instanceof Element) {
panel.append(content);
} else {
panel.innerHTML = content;
}
this.#log.leaving(me, panel);
return panel;
}
/**
* Event handler for change events. When the active tab changes, this
* will resend an 'expose' event to the associated panel.
* @param {Element} panel - The panel associated with this tab.
* @param {Event} evt - The original change event.
* @fires Event#expose
*/
#onChange = (panel, evt) => {
const me = 'onChange';
this.#log.entered(me, evt, panel);
panel.dispatchEvent(new Event('expose'));
this.#log.leaving(me);
}
/** Installs navigational control elements. */
#installControls = () => {
this.#nav = document.createElement('nav');
this.#nav.id = `${this.#id}-controls`;
this.#navSpacer = document.createElement('span');
this.#navSpacer.classList.add('spacer');
this.#prevButton = document.createElement('button');
this.#nextButton = document.createElement('button');
this.#prevButton.innerText = '←';
this.#nextButton.innerText = '→';
this.#prevButton.dataset.name = 'prev';
this.#nextButton.dataset.name = 'next';
this.#prevButton.addEventListener('click', () => this.prev());
this.#nextButton.addEventListener('click', () => this.next());
// XXX: Cannot get 'button' elements to style nicely, so cheating by
// wrapping them in a label.
const prevLabel = document.createElement('label');
const nextLabel = document.createElement('label');
prevLabel.append(this.#prevButton);
nextLabel.append(this.#nextButton);
this.#nav.append(this.#navSpacer, prevLabel, nextLabel);
}
}
/**
* An ordered collection of HTMLElements for a user to continuously scroll
* through.
*
* The dispatcher can be used the handle the following events:
* - 'out-of-range' - Scrolling went past one end of the collection. This
* is NOT an error condition, but rather a design feature.
* - 'change' - The value of item has changed.
* - 'activate' - The Scroller was activated.
* - 'deactivate' - The Scroller was deactivated.
*/
class Scroller {
/**
* Function that generates a, preferably, reproducible unique identifier
* for an Element.
* @callback uidCallback
* @param {Element} element - Element to examine.
* @returns {string} - A value unique to this element.
*/
/**
* Contains CSS selectors to first find a base element, then items that it
* contains.
* @typedef {object} ContainerItemsSelector
* @property {string} container - CSS selector to find the container
* element.
* @property {string} items - CSS selector to find the items inside the
* container.
*/
/**
* Function that finds an DOM element based upon another one.
*
* Useful for cases where CSS selectors are not sufficient.
* @callback ElementFinder
* @param {HTMLElement} element - Starting point.
* @returns {HTMLElement} - Found element.
*/
/**
* Common config for finding a clickable element inside the current item.
*
* This essentially configures a call to {@link NH.web.clickElement}.
* @typedef {object} ClickConfig
* @property {string[]} selectorArray - CSS selectors to use to find an
* element.
* @property {boolean} [matchSelf=false] - If a CSS selector would match
* base, then use it.
*/
/**
* There are two ways to describe what elements go into a Scroller:
* 1. An explicit container (base) element and selectors stemming from it.
* 2. An array of ContainerItemsSelector that can allow for multiple
* containers with items. This approach will also allow the Scroller to
* automatically wait for all container elements to exist during
* activation.
* @typedef {object} What
* @property {string} name - Name for this scroller, used for logging.
* @property {Element} base - The container to use as a base for selecting
* elements.
* @property {string[]} selectors - Array of CSS selectors to find
* elements to collect, calling base.querySelectorAll().
* @property {ContainerItemsSelector[]} containerItems - Array of
* ContainerItemsSelectors.
*/
/**
* @typedef {object} How
* @property {uidCallback} uidCallback - Callback to generate a uid.
* @property {string[]} [classes=[]] - Array of CSS classes to add/remove
* from an element as it becomes current.
* @property {boolean} [handleClicks=true] - Whether the scroller should
* watch for clicks and if one is inside an item, select it.
* @property {boolean} [autoActivate=false] - Whether to call the activate
* method at the end of construction.
* @property {boolean} [snapToTop=false] - Whether items should snap to
* the top of the window when coming into view.
* @property {number} [topMarginPixels=0] - Used to determine if scrolling
* should happen when {snapToTop} is false.
* @property {number} [bottomMarginPixels=0] - Used to determine if
* scrolling should happen when {snapToTop} is false.
* @property {string} [topMarginCSS='0'] - CSS applied to
* `scrollMarginTop`.
* @property {string} [bottomMarginCSS='0'] - CSS applied to
* `scrollMarginBottom`.
* @property {number} [waitForItemTimeout=3000] - Time to wait, in
* milliseconds, for existing item to reappear upon reactivation.
* @property {number} [containerTimeout=0] - Time to wait, in
* milliseconds, for a {ContainerItemsSelector.container} to show up.
* Some pages may not always provide all identified containers. The
* default of 0 disables timing out. NB: Any containers that timeout will
* not handle further activate() processing, such as handleClicks.
* @property {ElementFinder|ClickConfig} [clickConfig=null] - Configures
* how the click() method operates.
*/
/**
* @param {What} what - What we want to scroll.
* @param {How} how - How we want to scroll.
* @throws {Scroller.Exception} - On many construction problems.
*/
constructor(what, how) {
const WAIT_FOR_ITEM = 3000;
({
name: this.#name = 'Unnamed scroller',
base: this.#base,
selectors: this.#selectors,
containerItems: this.#containerItems = [],
} = what);
({
uidCallback: this.#uidCallback,
classes: this.#classes = [],
handleClicks: this.#handleClicks = true,
autoActivate: this.#autoActivate = false,
snapToTop: this.#snapToTop = false,
topMarginPixels: this.#topMarginPixels = 0,
bottomMarginPixels: this.#bottomMarginPixels = 0,
topMarginCSS: this.#topMarginCSS = '0',
bottomMarginCSS: this.#bottomMarginCSS = '0',
waitForItemTimeout: this.#waitForItemTimeout = WAIT_FOR_ITEM,
containerTimeout: this.#containerTimeout = 0,
clickConfig: this.#clickConfig = null,
} = how);
this.#validateInstance();
this.#mutationObserver = new MutationObserver(this.#mutationHandler);
this.#logger = new NH.base.Logger(`{${this.#name}}`);
this.logger.log('Scroller constructed', this);
if (this.#autoActivate) {
this.activate();
}
}
static Exception = class extends NH.base.Exception {}
/** @type {NH.base.Dispatcher} */
get dispatcher() {
return this.#dispatcher;
}
/** @type {Element} - Represents the current item. */
get item() {
const me = 'get item';
this.logger.entered(me);
if (this.#destroyed) {
const msg = `Tried to work with destroyed ${Scroller.name} ` +
`on ${this.#base}`;
this.logger.log(msg);
throw new Error(msg);
}
const items = this.#getItems();
let item = items.find(this.#matchItem);
if (!item) {
// We couldn't find the old id, so maybe it was rebuilt. Make a guess
// by trying the old index.
const idx = this.#historicalIdToIndex.get(this.#currentItemId);
if (typeof idx === 'number' && (0 <= idx && idx < items.length)) {
item = items[idx];
this.#bottomHalf(item);
}
}
this.logger.leaving(me, item);
return item;
}
/** @param {Element} val - Set the current item. */
set item(val) {
const me = 'set item';
this.logger.entered(me, val);
this.dull();
this.#bottomHalf(val);
this.logger.leaving(me);
}
/** @type {string} - Current item's uid. */
get itemUid() {
return this.#currentItemId;
}
/** @type {NH.base.Logger} */
get logger() {
return this.#logger;
}
/** @type {string} */
get name() {
return this.#name;
}
/**
* @param {number} [pixels=0] - Used to determine if scrolling should
* happen when {snapToTop} is false.
* @returns {Scroller} - This instance, for chaining.
*/
topMarginPixels(pixels = 0) {
this.#topMarginPixels = pixels;
return this;
}
/**
* @param {number} [pixels=0] - Used to determine if scrolling should
* happen when {snapToTop} is false.
* @returns {Scroller} - This instance, for chaining.
*/
bottomMarginPixels(pixels = 0) {
this.#bottomMarginPixels = pixels;
return this;
}
/**
* @param {string} [css='0'] - CSS applied to `scrollMarginTop`.
* @returns {Scroller} - This instance, for chaining.
*/
topMarginCSS(css = '0') {
this.#topMarginCSS = css;
return this;
}
/**
* @param {string} [css='0'] - CSS applied to `scrollMarginBottom`.
* @returns {Scroller} - This instance, for chaining.
*/
bottomMarginCSS(css = '0') {
this.#bottomMarginCSS = css;
return this;
}
/** Click either the current item OR document.activeElement. */
click() {
const me = 'click';
const item = this.item;
this.logger.entered(me, item);
if (item) {
if (this.#clickConfig instanceof Function) {
const result = this.#clickConfig(item);
if (result) {
result.click();
} else {
NH.web.postInfoAboutElement(item,
`the clickConfig function for ${this.name}`);
}
} else if (this.#clickConfig) {
if (!NH.web.clickElement(
item,
this.#clickConfig.selectorArray,
this.#clickConfig.matchSelf
)) {
NH.web.postInfoAboutElement(item,
`the clickConfig selectorArray for ${this.name}`);
}
} else {
NH.base.issues.post(`Scroller.click() for "${this.name}" was ` +
'called without a configuration');
}
} else {
document.activeElement.click();
}
this.logger.leaving(me);
}
/** Move to the next item in the collection. */
next() {
this.#scrollBy(1);
}
/** Move to the previous item in the collection. */
prev() {
this.#scrollBy(-1);
}
/** Jump to the first item in the collection. */
first() {
this.#jumpToEndItem(true);
}
/** Jump to last item in the collection. */
last() {
this.#jumpToEndItem(false);
}
/**
* Move to a specific item if possible.
* @param {Element} item - Item to go to.
*/
goto(item) {
this.item = item;
}
/**
* Move to a specific item if possible, by uid.
* @param {string} uid - The uid of a specific item.
* @returns {boolean} - Was able to goto the item.
*/
gotoUid(uid) {
const me = 'gotoUid';
this.logger.entered(me, uid);
const items = this.#getItems();
const item = items.find(el => uid === this.#uid(el));
let success = false;
if (item) {
this.item = item;
success = true;
}
this.logger.leaving(me, success, item);
return success;
}
/** Adds the registered CSS classes to the current element. */
shine() {
this.item?.classList.add(...this.#classes);
}
/** Removes the registered CSS classes from the current element. */
dull() {
this.item?.classList.remove(...this.#classes);
}
/** Bring current item back into view. */
show() {
this.#scrollToCurrentItem();
}
/** Focus on current item. */
focus() {
const me = 'focus';
this.logger.entered(me, litOptions.enableScrollerChangesFocus);
this.shine();
this.show();
if (litOptions.enableScrollerChangesFocus) {
this.logger.log('focusing', this.item);
NH.web.focusOnElement(this.item);
}
this.logger.leaving(me, 'current focus:', document.activeElement);
}
/**
* Activate the scroller.
* @fires 'out-of-range'
*/
async activate() {
const me = 'activate';
this.logger.entered(me);
const containers = new Set(
Array.from(await this.#waitForContainers())
.filter(x => x)
);
if (this.#base) {
containers.add(this.#base);
}
const watcher = this.#currentItemWatcher();
for (const container of containers) {
if (this.#handleClicks) {
this.#onClickElements.add(container);
container.addEventListener('click',
this.#onClick,
this.#clickOptions);
}
this.#mutationObserver.observe(container,
{childList: true, subtree: true});
}
this.logger.log('watcher:', await watcher);
this.#mutationDispatcher.on('records', this.#monitorConnectedness);
this.dispatcher.fire('activate', null);
this.logger.leaving(me);
}
/**
* Deactivate the scroller (but do not destroy it).
* @fires 'out-of-range'
*/
deactivate() {
this.#mutationDispatcher.off('records', this.#monitorConnectedness);
this.#mutationObserver.disconnect();
for (const container of this.#onClickElements) {
container.removeEventListener('click',
this.#onClick,
this.#clickOptions);
}
this.#onClickElements.clear();
this.dispatcher.fire('deactivate', null);
}
/** Mark instance as inactive and do any internal cleanup. */
destroy() {
const me = 'destroy';
this.logger.entered(me);
this.deactivate();
this.item = null;
this.#destroyed = true;
this.logger.leaving(me);
}
/**
* Determines if the item can be viewed. Usually this means the content
* is being loaded lazily and is not ready yet.
* @param {Element} item - The item to inspect.
* @returns {boolean} - Whether the item has viewable content.
*/
static #isItemViewable(item) {
return Boolean(item.clientHeight && item.innerText.length);
}
#autoActivate
#base
#bottomMarginCSS
#bottomMarginPixels
#classes
#clickConfig
#clickOptions = {capture: true};
#containerItems
#containerTimeout
#currentItem = null;
#currentItemId = null;
#destroyed = false;
#dispatcher = new NH.base.Dispatcher(
'change', 'out-of-range', 'activate', 'deactivate'
);
#handleClicks
#historicalIdToIndex = new Map();
#logger
#mutationDispatcher = new NH.base.Dispatcher('records');
#mutationObserver
#name
#onClickElements = new Set();
#selectors
#snapToTop
#stackTrace
#topMarginCSS
#topMarginPixels
#uidCallback