-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjobber-keyboard-shortcuts-manual-install.js
More file actions
1608 lines (1379 loc) · 66.4 KB
/
Copy pathjobber-keyboard-shortcuts-manual-install.js
File metadata and controls
1608 lines (1379 loc) · 66.4 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
// ==UserScript==
// @name Jobber Keyboard Shortcuts
// @version 3.1
// @description A collection of super helpful keyboard shortcuts for Jobber.
// @author Ben Delaney
// @match https://secure.getjobber.com/*
// @grant none
// ==/UserScript==
// Jobber Actions Consolidated
// Version 3.1
// Author: Ben Delaney
/* ************************
KEYBOARD SHORTCUTS:
**************************
Global:
- CMD + \ : Toggle 'Activity Feed' side panel
- CMD + OPTION + \ : Toggle 'Messages' side panel
- CMD + ENTER : Click Save/Send Button (while in any Visit Modal, Note input, email form, text message form, or new note form.)
- CMD + / : Show keyboard shortcuts reference
While viewing a JOB VISIT Modal or Scheduler Popover:
- CMD + CTRL + E : Open visit Edit dialog (or click Edit in popover)
- CMD + CTRL + T : Open Text Reminder dialog
- SHIFT + N : Switch to Notes Tab
- SHIFT + I : Switch to Info Tab
While in the 'EDIT' mode of a Job Visit Modal:
- CMD + CTRL + A : Assign Crew
While on a Job page:
- SHIFT + V : Scroll to Scheduled visits section
While on Job, Invoice, or Quote pages:
- SHIFT + N : Start a new note
*/
(function() {
'use strict';
// ========================================
// UTILITY FUNCTIONS
// ========================================
// Utility function to normalize text
const normalizeText = (s) => (s || '').trim().toLowerCase();
const visitRequestViewDialogTitles = new Set(['visit', 'request', 'visit details', 'request details']);
const visitRequestAnyDialogTitles = new Set(['visit', 'request', 'visit details', 'request details', 'edit visit', 'edit request']);
const isElementVisible = (element) => {
if (!element) {
return false;
}
const style = window.getComputedStyle(element);
return style.display !== 'none' && style.visibility !== 'hidden' && element.getAttribute('aria-hidden') !== 'true' && element.getClientRects().length > 0;
};
const isVisitRequestViewDialogTitle = (titleText) => visitRequestViewDialogTitles.has(titleText);
const isVisitRequestDialogTitle = (titleText) => visitRequestAnyDialogTitles.has(titleText);
const getDialogTitleText = (dialog) => normalizeText(
dialog?.querySelector('.dialog-title.js-dialogTitle, #ATL-Modal-Header, [data-testid="modal-header"] h1, [data-testid="modal-header"] h2, [data-testid="modal-header"] [role="heading"]')?.textContent || ''
);
const isMac = navigator.platform.includes('Mac');
// Check if user is currently typing in an input field
const isUserTyping = () => {
const activeElement = document.activeElement;
return activeElement && (
activeElement.tagName === 'INPUT' ||
activeElement.tagName === 'TEXTAREA' ||
activeElement.tagName === 'SELECT' ||
activeElement.isContentEditable
);
};
const getElementActionText = (element) => normalizeText(
element?.textContent ||
element?.value ||
element?.getAttribute('aria-label') ||
element?.getAttribute('title') ||
''
);
const pressElement = (element) => {
if (!element) {
return;
}
element.focus?.({ preventScroll: true });
['pointerdown', 'mousedown', 'pointerup', 'mouseup'].forEach((eventType) => {
const EventConstructor = eventType.startsWith('pointer') && window.PointerEvent ? window.PointerEvent : window.MouseEvent;
const eventOptions = {
bubbles: true,
cancelable: true,
view: window,
button: 0,
buttons: eventType.endsWith('down') ? 1 : 0,
pointerId: 1,
pointerType: 'mouse',
isPrimary: true
};
try {
element.dispatchEvent(new EventConstructor(eventType, eventOptions));
} catch (error) {
element.dispatchEvent(new MouseEvent(eventType, eventOptions));
}
});
try {
element.click?.();
} catch (error) {
console.warn('Element click activation failed:', error);
}
};
const pressKeyOnElement = (element, key = 'Enter') => {
if (!element) {
return;
}
element.focus?.({ preventScroll: true });
const code = key === ' ' ? 'Space' : key;
['keydown', 'keyup'].forEach((eventType) => {
element.dispatchEvent(new KeyboardEvent(eventType, {
bubbles: true,
cancelable: true,
key,
code
}));
});
};
const getVisibleSendSubmitButton = (form) => Array.from(form.querySelectorAll('button[type="submit"], input[type="submit"]')).find((button) => {
const actionText = getElementActionText(button);
return isElementVisible(button) &&
!button.disabled &&
button.getAttribute('aria-disabled') !== 'true' &&
(actionText === 'send' || actionText.includes('send message') || actionText.includes('send text'));
}) || null;
const getActiveSendTextForm = () => {
const sendTextForms = Array.from(document.querySelectorAll('form')).map((form) => {
const textarea = form.querySelector('textarea[name="message"]');
const sendButton = getVisibleSendSubmitButton(form);
if (!textarea || !sendButton || !isElementVisible(form) || !isElementVisible(textarea)) {
return null;
}
const hasRecipientField = Boolean(
form.querySelector('input[aria-label="recipient" i], input#To, input[placeholder*="mobile" i], input[placeholder*="phone" i]')
);
const hasMessageLabel = Array.from(form.querySelectorAll('label')).some((label) => {
const labelFor = label.getAttribute('for');
return normalizeText(label.textContent) === 'message' || (textarea.id && labelFor === textarea.id);
});
const hasMessageCounter = Boolean(form.querySelector('[aria-label^="Message length" i], [aria-label*="characters" i]'));
const hasClientHubPreview = normalizeText(form.textContent).includes('your client can view') || normalizeText(form.textContent).includes('tap https://');
const isLegacySmsDialog = Boolean(form.closest('.js-sendToClientDialogSms'));
if (!hasRecipientField && !hasMessageLabel && !hasMessageCounter && !hasClientHubPreview && !isLegacySmsDialog) {
return null;
}
return { container: form, textarea, sendButton };
}).filter(Boolean);
const activeForm = sendTextForms.find(({ container, textarea, sendButton }) =>
textarea === document.activeElement || sendButton === document.activeElement || container.contains(document.activeElement)
);
if (activeForm) {
return activeForm;
}
const populatedForm = sendTextForms.find(({ textarea }) => textarea.value.trim());
if (populatedForm) {
return populatedForm;
}
if (sendTextForms.length) {
return sendTextForms[0];
}
return null;
};
const submitSendTextForm = ({ textarea, sendButton }) => {
if (textarea) {
['input', 'change'].forEach((eventType) => {
textarea.dispatchEvent(new Event(eventType, { bubbles: true }));
});
}
console.log('Send text form detected, clicking Send button');
sendButton.click();
};
// Check if we're in the Messages interface - robust detection
const isInMessagesInterface = () => {
// Check for various possible selectors for the send button
const sendButton =
getActiveSendTextForm() ||
document.querySelector('button[aria-label="send"]') ||
document.querySelector('button[aria-label="Send"]') ||
document.querySelector('button[aria-label="Send message"]') ||
document.querySelector('button[aria-label="Send Message"]') ||
// Check for send button by icon or class patterns
document.querySelector('button[type="submit"][aria-label*="end" i]') ||
// Check for Messages panel visibility
(document.querySelector('[data-testid="message-center"]') &&
document.querySelector('[data-testid="message-center"] button[type="submit"]')) ||
// Check for text message inbox panel
(document.querySelector('[aria-label*="Message" i]') &&
document.querySelector('form button[type="submit"]'));
return Boolean(sendButton);
};
const findMoreActionsButton = (container = document) => {
const candidates = Array.from(container.querySelectorAll(
'[aria-label="More Actions"], [aria-label^="More Actions" i], [data-custom-action-name*="More Actions" i], [role="button"][aria-haspopup="true"], button[aria-haspopup="true"]'
));
return candidates.find((candidate) => {
if (!isElementVisible(candidate)) {
return false;
}
const actionText = getElementActionText(candidate);
return actionText.includes('more actions') || Boolean(candidate.querySelector('button, svg[data-testid="more"]'));
}) || null;
};
// Get visit/request dialog information
const getVisitRequestDialog = ({ includeEdit = false } = {}) => {
const titleMatcher = includeEdit ? isVisitRequestDialogTitle : isVisitRequestViewDialogTitle;
const visibleDialogs = Array.from(document.querySelectorAll('[role="dialog"],.dialog-box,.modal')).reverse().filter(isElementVisible);
const titledDialog = visibleDialogs.find((candidate) => {
const titleText = getDialogTitleText(candidate);
return titleMatcher(titleText);
}) || null;
const fallbackDialog = titledDialog || visibleDialogs.find((candidate) => findMoreActionsButton(candidate)) || null;
const dialog = fallbackDialog;
const title = dialog?.querySelector('.dialog-title.js-dialogTitle') || null;
const titleText = normalizeText(title?.textContent || '');
const isValid = Boolean(titledDialog || (dialog && findMoreActionsButton(dialog)));
return { title, titleText, isValid, dialog: dialog || document };
};
const getActiveVisitRequestNoteForm = () => {
const { isValid, dialog } = getVisitRequestDialog();
if (!isValid || !isElementVisible(dialog)) {
return null;
}
const noteForms = Array.from(dialog.querySelectorAll('form')).map((form) => {
const textarea = form.querySelector('textarea[name="message"], textarea[name="note[message]"]');
const saveButton = Array.from(form.querySelectorAll('button[type="submit"], input[type="submit"]')).find((button) => isElementVisible(button));
if (!textarea || !saveButton || !isElementVisible(form) || !isElementVisible(textarea)) {
return null;
}
return { container: form, textarea, saveButton };
}).filter(Boolean);
const activeForm = noteForms.find(({ container, textarea, saveButton }) => textarea === document.activeElement || saveButton === document.activeElement || container.contains(document.activeElement));
if (activeForm) {
return activeForm;
}
const populatedForm = noteForms.find(({ textarea }) => textarea.value.trim());
if (populatedForm) {
return populatedForm;
}
if (noteForms.length) {
return noteForms[0];
}
return null;
};
const getLeaveNoteTextareaInForm = (form) => {
if (!form || !isElementVisible(form)) {
return null;
}
const labels = Array.from(form.querySelectorAll('label')).filter((label) =>
isElementVisible(label) && normalizeText(label.textContent) === 'leave a note'
);
for (const label of labels) {
const fieldId = label.getAttribute('for');
const textarea = fieldId ? document.getElementById(fieldId) : label.parentElement?.querySelector('textarea');
if (textarea && form.contains(textarea) && textarea.tagName === 'TEXTAREA' && isElementVisible(textarea)) {
return textarea;
}
}
return null;
};
const getVisibleSaveSubmitButton = (form) => Array.from(form.querySelectorAll('button[type="submit"], input[type="submit"]')).find((button) => {
const actionText = getElementActionText(button);
return isElementVisible(button) &&
!button.disabled &&
button.getAttribute('aria-disabled') !== 'true' &&
(actionText === 'save' || actionText.includes('save note'));
}) || null;
const getActiveNewNoteForm = () => {
const noteForms = Array.from(document.querySelectorAll('form')).map((form) => {
const textarea = getLeaveNoteTextareaInForm(form);
const saveButton = getVisibleSaveSubmitButton(form);
if (!textarea || !saveButton) {
return null;
}
return { container: form, textarea, saveButton };
}).filter(Boolean);
const activeForm = noteForms.find(({ container, textarea, saveButton }) =>
textarea === document.activeElement || saveButton === document.activeElement || container.contains(document.activeElement)
);
if (activeForm) {
return activeForm;
}
const populatedForm = noteForms.find(({ textarea }) => textarea.value.trim());
if (populatedForm) {
return populatedForm;
}
if (noteForms.length) {
return noteForms[0];
}
return null;
};
const submitNewNoteForm = ({ textarea, saveButton }) => {
if (textarea) {
['input', 'change', 'keyup'].forEach((eventType) => {
textarea.dispatchEvent(new Event(eventType, { bubbles: true }));
});
}
setTimeout(() => {
console.log('New note form detected, clicking Save button');
saveButton.click();
}, 150);
};
const getScrollableAncestor = (element) => {
let current = element?.parentElement || null;
while (current && current !== document.body && current !== document.documentElement) {
const style = window.getComputedStyle(current);
const canScrollY = /(auto|scroll)/.test(style.overflowY) && current.scrollHeight > current.clientHeight + 1;
if (canScrollY) {
return current;
}
current = current.parentElement;
}
return document.scrollingElement || document.documentElement;
};
const scrollElementIntoContainerView = (element, offset = 16) => {
const scrollContainer = getScrollableAncestor(element);
if (!scrollContainer || scrollContainer === document.documentElement || scrollContainer === document.body) {
const targetTop = element.getBoundingClientRect().top + window.scrollY - offset;
window.scrollTo({ top: Math.max(targetTop, 0), behavior: 'smooth' });
return scrollContainer;
}
const containerRect = scrollContainer.getBoundingClientRect();
const elementRect = element.getBoundingClientRect();
const targetTop = scrollContainer.scrollTop + elementRect.top - containerRect.top - offset;
scrollContainer.scrollTo({ top: Math.max(targetTop, 0), behavior: 'smooth' });
return scrollContainer;
};
// Scroll to a card/section by its heading text
const scrollToCardByTitle = (cardTitle, pagePathRegex, aliases = []) => {
// Check if we're on a supported page
if (pagePathRegex && !pagePathRegex.test(window.location.pathname)) {
console.log(`Not on a supported page for scrolling to ${cardTitle}`);
return;
}
const titleMatches = new Set([cardTitle, ...aliases].map(normalizeText));
const allTitles = document.querySelectorAll('.card-headerTitle, h1, h2, h3, h4, [role="heading"]');
let foundTitle = null;
for (const title of allTitles) {
if (isElementVisible(title) && titleMatches.has(normalizeText(title.textContent))) {
foundTitle = title;
break;
}
}
if (!foundTitle) {
console.log(`${cardTitle} section not found on this page`);
return;
}
const scrollTarget =
foundTitle.closest('div.card') ||
foundTitle.closest('section, article, [data-testid="ATL-Card"]') ||
foundTitle.parentElement;
if (scrollTarget) {
console.log(`Scrolling to ${foundTitle.textContent.trim() || cardTitle} section`);
scrollElementIntoContainerView(scrollTarget);
} else {
console.log('Could not find section element to scroll to');
}
};
// Create fetch with Jobber headers
const jobberFetch = (url) => {
const token = (document.querySelector('meta[name="csrf-token"]') || {}).content || '';
return fetch(url, {
method: 'GET',
credentials: 'same-origin',
headers: {
'Accept': '*/*;q=0.5, text/javascript, application/javascript, application/ecmascript, application/x-ecmascript',
'X-Requested-With': 'XMLHttpRequest',
...(token ? {'X-CSRF-Token': token} : {})
}
});
};
const openDialogFromHref = (actionHref, actionType) => {
jobberFetch(actionHref)
.then(response => response.ok ? response.text() : response.text().then(text => {
throw new Error(`HTTP ${response.status} ${response.statusText} :: ${text.slice(0, 200)}`);
}))
.then(js => {
try {
const parentWindow = parent.window || window;
if (typeof parentWindow.dialogBox === 'undefined') {
throw new Error('dialogBox constructor not available. Page may not be fully loaded.');
}
new Function(js)();
} catch (execError) {
console.warn('Script execution failed, attempting direct navigation:', execError);
window.location.href = actionHref;
}
})
.catch(error => {
console.error(error);
alert(`Could not open ${actionType}: ` + error.message);
});
};
// Check if modifier combo matches (platform-aware)
const isModifierCombo = (event, combo) => {
const combos = {
'cmd+ctrl': isMac ?
(event.metaKey && event.ctrlKey && !event.altKey && !event.shiftKey) :
(event.ctrlKey && event.altKey && !event.metaKey && !event.shiftKey),
'cmd+alt': isMac ?
(event.metaKey && event.altKey && !event.ctrlKey && !event.shiftKey) :
(event.ctrlKey && event.altKey && !event.metaKey && !event.shiftKey),
'cmd': isMac ?
(event.metaKey && !event.altKey && !event.ctrlKey && !event.shiftKey) :
(event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey),
'shift': event.shiftKey && !event.metaKey && !event.ctrlKey && !event.altKey
};
return combos[combo] || false;
};
const shortcutSections = [
{
title: 'Global',
shortcuts: [
{ combo: isMac ? 'COMMAND + /' : 'CTRL + /', description: 'Show this shortcuts reference' },
{ combo: isMac ? 'COMMAND + \\' : 'CTRL + \\', description: "Toggle '<strong>Activity Feed</strong>' side panel" },
{ combo: isMac ? 'COMMAND + OPTION + \\' : 'CTRL + ALT + \\', description: "Toggle '<strong>Messages</strong>' side panel" },
{ combo: isMac ? 'COMMAND + ENTER' : 'CTRL + ENTER', description: 'Click <strong>Save/Send</strong> button in visit modals, notes, email forms, text message forms, or new note forms' },
]
},
{
title: 'Visit / Request Modals',
shortcuts: [
{ combo: isMac ? 'COMMAND + CTRL + E' : 'CTRL + ALT + E', description: 'Open <strong>Edit</strong> dialog or click Edit in popover' },
{ combo: isMac ? 'COMMAND + CTRL + T' : 'CTRL + ALT + T', description: 'Open <strong>Text</strong> Reminder dialog' },
{ combo: isMac ? 'COMMAND + CTRL + A' : 'CTRL + ALT + A', description: '<strong>Assign</strong> crew' },
{ combo: 'SHIFT + N', description: 'Switch to <strong>Notes</strong> tab' },
{ combo: 'SHIFT + I', description: 'Switch to <strong>Info</strong> tab' },
]
},
{
title: 'Job / Invoice / Quote Pages',
shortcuts: [
{ combo: 'SHIFT + V', description: 'Scroll to <strong>Scheduled visits</strong> section (Job pages only)' },
{ combo: 'SHIFT + N', description: 'Start a new <strong>Note</strong>' }
]
}
];
let shortcutsModal;
let shortcutsOverlay;
let previousBodyOverflow;
const createShortcutsModal = () => {
if (shortcutsOverlay) {
return;
}
shortcutsOverlay = document.createElement('div');
shortcutsOverlay.id = 'jobber-shortcuts-overlay';
shortcutsOverlay.setAttribute('role', 'presentation');
shortcutsOverlay.style.cssText = [
'position: fixed',
'top: 0',
'left: 0',
'width: 100%',
'height: 100%',
'display: none',
'align-items: center',
'justify-content: center',
'background: rgba(17, 24, 39, 0.65)',
'z-index: 2147483000',
'padding: 24px',
'box-sizing: border-box'
].join(';');
shortcutsModal = document.createElement('div');
shortcutsModal.id = 'jobber-shortcuts-modal';
shortcutsModal.setAttribute('role', 'dialog');
shortcutsModal.setAttribute('aria-modal', 'true');
shortcutsModal.setAttribute('aria-labelledby', 'jobber-shortcuts-title');
shortcutsModal.setAttribute('tabindex', '-1');
shortcutsModal.style.cssText = [
'background: #ffffff',
'color: #1f2933',
'max-width: 640px',
'width: 100%',
'max-height: 80vh',
'overflow-y: auto',
'border-radius: 12px',
'box-shadow: 0 25px 80px rgba(15, 23, 42, 0.35)',
'padding: 28px 32px',
'box-sizing: border-box',
'font-family: "Helvetica Neue", Arial, sans-serif',
'position: relative'
].join(';');
const closeButton = document.createElement('button');
closeButton.type = 'button';
closeButton.setAttribute('aria-label', 'Close shortcuts reference');
closeButton.textContent = '×';
closeButton.style.cssText = [
'position: absolute',
'top: 12px',
'right: 16px',
'border: none',
'background: none',
'font-size: 26px',
'cursor: pointer',
'line-height: 1',
'color: #6b7280'
].join(';');
closeButton.addEventListener('mouseenter', () => {
closeButton.style.color = '#111827';
});
closeButton.addEventListener('mouseleave', () => {
closeButton.style.color = '#6b7280';
});
closeButton.addEventListener('click', () => {
hideShortcutsModal();
});
const title = document.createElement('h2');
title.id = 'jobber-shortcuts-title';
title.textContent = 'Keyboard Shortcuts';
title.style.cssText = [
'margin: 0 0 12px',
'font-size: 24px',
'font-weight: 600'
].join(';');
const subtitle = document.createElement('p');
subtitle.innerHTML = '<a href="https://github.com/bendelaney/jobber-keyboard-shortcuts" target="_blank" rel="noopener">more info</a>';
subtitle.style.cssText = [
'margin: 0 0 20px',
'color: #4b5563',
'font-size: 15px'
].join(';');
const listContainer = document.createElement('div');
listContainer.style.cssText = [
'display: grid',
'gap: 18px'
].join(';');
shortcutSections.forEach((section) => {
const sectionWrapper = document.createElement('section');
sectionWrapper.style.cssText = [
'border-top: 1px solid #e5e7eb',
'padding-top: 16px'
].join(';');
if (listContainer.childElementCount === 0) {
sectionWrapper.style.borderTop = 'none';
sectionWrapper.style.paddingTop = '0';
}
const sectionTitle = document.createElement('h3');
sectionTitle.textContent = section.title;
sectionTitle.style.cssText = [
'margin: 0 0 10px',
'font-size: 18px',
'font-weight: 700',
'text-transform: titlecase',
'color: #111827'
].join(';');
const list = document.createElement('ul');
list.style.cssText = [
'list-style: none',
'margin: 0',
'padding: 0',
'display: grid',
'gap: 8px'
].join(';');
section.shortcuts.forEach((shortcut) => {
const item = document.createElement('li');
item.style.cssText = [
'display: flex',
'justify-content: space-between',
'align-items: center',
'background: #f9fafb',
'border: 1px solid #e5e7eb',
'border-radius: 8px',
'padding: 10px 14px',
'gap: 16px'
].join(';');
const combo = document.createElement('span');
combo.innerHTML = shortcut.combo;
combo.style.cssText = [
'font-family: "SFMono-Regular", Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace',
'font-size: 13px',
'color: #111827'
].join(';');
const description = document.createElement('span');
description.innerHTML = shortcut.description;
description.style.cssText = [
'font-size: 14px',
'color: #374151',
'text-align: right'
].join(';');
item.appendChild(combo);
item.appendChild(description);
list.appendChild(item);
});
sectionWrapper.appendChild(sectionTitle);
sectionWrapper.appendChild(list);
listContainer.appendChild(sectionWrapper);
});
shortcutsModal.appendChild(closeButton);
shortcutsModal.appendChild(title);
shortcutsModal.appendChild(subtitle);
shortcutsModal.appendChild(listContainer);
shortcutsOverlay.appendChild(shortcutsModal);
shortcutsOverlay.addEventListener('click', () => {
hideShortcutsModal();
});
shortcutsModal.addEventListener('click', (event) => {
event.stopPropagation();
});
document.body.appendChild(shortcutsOverlay);
};
const hideShortcutsModal = () => {
if (!shortcutsOverlay) {
return;
}
shortcutsOverlay.style.display = 'none';
if (previousBodyOverflow !== undefined) {
document.body.style.overflow = previousBodyOverflow;
previousBodyOverflow = undefined;
}
};
const showShortcutsModal = () => {
createShortcutsModal();
if (!shortcutsOverlay) {
return;
}
previousBodyOverflow = document.body.style.overflow;
document.body.style.overflow = 'hidden';
shortcutsOverlay.style.display = 'flex';
shortcutsModal.focus({ preventScroll: true });
};
const toggleShortcutsModal = () => {
createShortcutsModal();
if (!shortcutsOverlay) {
return;
}
if (shortcutsOverlay.style.display === 'flex') {
hideShortcutsModal();
} else {
showShortcutsModal();
}
};
const isShortcutsModalVisible = () => shortcutsOverlay && shortcutsOverlay.style.display === 'flex';
// ========================================
// SHARED DIALOG OPENER
// ========================================
// Generic function to open action dialogs (Edit, Text Reminder, etc.)
function openActionDialog(actionType, searchCriteria) {
try {
const { isValid, dialog } = getVisitRequestDialog();
if (!isValid) {
alert('Open the Visit or Request modal first.');
return;
}
const button = dialog.querySelector('button[data-action-button="true"].js-dropdownButton,button.js-dropdownButton[data-action-button="true"]') ||
dialog.querySelector('button.js-dropdownButton') ||
findMoreActionsButton(dialog);
if (!button) {
alert('More Actions button not found.');
return;
}
let rawActions = button.getAttribute('data-action-button-actions');
if (!rawActions) {
// New Jobber UI: activate the React Aria trigger, then find and activate the menu item.
const innerButton = button.matches('button') ? null : button.querySelector('button');
pressElement(button);
const findAndClickItem = (attemptsLeft) => {
const menuItems = Array.from(document.querySelectorAll('[role="menuitem"], [role="option"]')).filter(isElementVisible);
for (const item of menuItems) {
const text = normalizeText(item.textContent);
const href = item.getAttribute('href') || '';
const id = item.id || '';
const iconName = item.querySelector('svg[data-testid]')?.getAttribute('data-testid') || '';
if (searchCriteria(text, href, id, iconName)) {
console.log(`Clicking ${actionType} in dropdown menu...`);
if (item.tagName === 'A' && href) {
pressElement(item);
} else if (href && /\.dialog\b/.test(href)) {
openDialogFromHref(href, actionType);
} else {
pressElement(item);
pressKeyOnElement(item, 'Enter');
}
return;
}
}
if (attemptsLeft === 9 && innerButton) {
pressElement(innerButton);
} else if (attemptsLeft === 7) {
pressKeyOnElement(button, 'Enter');
} else if (attemptsLeft === 5 && innerButton) {
pressKeyOnElement(innerButton, 'Enter');
}
if (attemptsLeft > 0) {
setTimeout(() => findAndClickItem(attemptsLeft - 1), 100);
} else {
pressElement(button); // close the menu
alert(`${actionType} action not found in dropdown menu.`);
}
};
setTimeout(() => findAndClickItem(12), 150);
return;
}
rawActions = rawActions.replace(/"/g, '"').replace(/&/g, '&');
let actionsArray;
try {
actionsArray = JSON.parse(rawActions);
} catch (e) {
alert('Could not parse actions JSON.');
return;
}
let actionHref = null;
for (const html of actionsArray) {
const tempDiv = document.createElement('div');
tempDiv.innerHTML = html;
const anchor = tempDiv.querySelector('a');
const text = normalizeText(tempDiv.textContent);
const href = (anchor && anchor.getAttribute('href')) || '';
const id = (anchor && anchor.id) || '';
if (anchor && searchCriteria(text, href, id)) {
actionHref = href;
break;
}
}
if (!actionHref) {
console.log('Available actions:', actionsArray);
alert(`${actionType} action not found.`);
return;
}
openDialogFromHref(actionHref, actionType);
} catch (error) {
console.error(error);
alert('Bookmarklet error: ' + error.message);
}
}
// Function 1: Open Edit Dialog (CMD+CTRL+E)
function openEditDialog() {
openActionDialog('Edit', (text, href, id, iconName) => {
return text === 'edit' || text.includes('edit') || iconName === 'edit' || /\/edit\.dialog\b/.test(href);
});
}
// Function 1b: Click Edit button in Popover Modal (scheduler view)
function clickEditInPopover() {
// Look for an open popover with data-mode="view"
const popover = document.querySelector('div[data-testid="popover"][data-open="true"][data-mode="view"]');
if (!popover) {
return false; // No popover found
}
// Find the Edit button inside the popover
// Structure: ._buttonContainer_*_1 > ._button_*_1 > button > span (text: "Edit")
const buttonContainer = popover.querySelector('[class*="_buttonContainer_"]');
if (!buttonContainer) {
return false;
}
// Find all buttons in the container and look for one with "Edit" text
const buttons = buttonContainer.querySelectorAll('button');
for (const button of buttons) {
const span = button.querySelector('span');
if (span && normalizeText(span.textContent) === 'edit') {
console.log('Edit button found in popover, clicking...');
button.click();
return true; // Successfully clicked
}
}
return false; // Edit button not found in popover
}
// Function 2: Open Text Reminder Dialog (CMD+CTRL+T)
function openTextReminderDialog() {
openActionDialog('Text Reminder', (text, href, id, iconName) => {
return id === 'sms' || iconName === 'sms' || text.includes('text reminder') || /\/comms\/sms\.dialog\b/.test(href);
});
}
// Function 3: Click Save Button (CMD+ENTER)
function clickSaveButton() {
// HIGHEST PRIORITY: Check for email dialog send button (Invoice/Quote emails)
const emailDialog = document.querySelector('.js-sendToClientDialog');
if (emailDialog && window.getComputedStyle(emailDialog.closest('.dialog-overlay, .dialog-box') || emailDialog).display !== 'none') {
const emailSendButton = emailDialog.querySelector('button.js-formSubmit[data-form="form.sendToClientDialog"], div.js-formSubmit[data-form="form.sendToClientDialog"]');
if (emailSendButton) {
console.log('Email dialog detected, clicking send button');
emailSendButton.click();
return;
}
}
// SECOND PRIORITY: Check for SMS/send text dialog send button
const smsDialog = document.querySelector('.js-sendToClientDialogSms');
if (smsDialog) {
const smsSendButton = smsDialog.querySelector('button.js-formSubmit[data-form="form.sendToClientDialogSms"]');
if (smsSendButton) {
console.log('SMS dialog detected, clicking send button');
smsSendButton.click();
return;
}
}
const activeSendTextForm = getActiveSendTextForm();
if (activeSendTextForm) {
submitSendTextForm(activeSendTextForm);
return;
}
// Visit/Request edit modal (new Jobber UI): find a visible "Save" submit button inside the dialog
const { isValid: visitEditValid, dialog: visitEditDialog } = getVisitRequestDialog({ includeEdit: true });
if (visitEditValid && visitEditDialog && visitEditDialog !== document) {
const submitButtons = Array.from(visitEditDialog.querySelectorAll('button[type="submit"], input[type="submit"]')).filter(isElementVisible);
const saveSubmit = submitButtons.find((button) => normalizeText(button.textContent || button.value || '') === 'save')
|| submitButtons.find((button) => normalizeText(button.textContent || button.value || '').includes('save'));
if (saveSubmit) {
console.log('Visit/Request edit modal detected, clicking Save submit button');
saveSubmit.click();
return;
}
}
// THIRD PRIORITY: Original to_do form save button
let saveButton = document.querySelector(
'a.button.button--green.js-spinOnClick.js-formSubmit[data-form="form.to_do"], ' +
'button.button.button--green.js-spinOnClick.js-formSubmit[data-form="form.to_do"]'
);
if (saveButton) {
saveButton.click();
return;
}
const activeNewNoteForm = getActiveNewNoteForm();
if (activeNewNoteForm) {
submitNewNoteForm(activeNewNoteForm);
return;
}
// FOURTH PRIORITY: Note forms, prioritize modal context over main page
console.log('Looking for note save functionality...');
let activeContainer = null;
let activeTextarea = null;
let activeSaveButton = null;
const activeVisitRequestNoteForm = getActiveVisitRequestNoteForm();
if (activeVisitRequestNoteForm) {
activeContainer = activeVisitRequestNoteForm.container;
activeTextarea = activeVisitRequestNoteForm.textarea;
activeSaveButton = activeVisitRequestNoteForm.saveButton;
console.log('Found active note form in visit/request modal');
}
// Strategy 1: Check if there's a dialog/modal open first
const modal = document.querySelector('.dialog-box, [role="dialog"], .modal');
if (!activeContainer && modal) {
console.log('Modal detected, looking for note form in modal...');
const modalNoteContainer = modal.querySelector('.js-noteContainer');
if (modalNoteContainer) {
const modalTextarea = modalNoteContainer.querySelector('textarea[name="note[message]"]');
const modalSaveButton = modalNoteContainer.querySelector('button.js-saveNote');
// Check if this modal note form is visible (not display:none)
const containerStyle = window.getComputedStyle(modalNoteContainer);
if (modalTextarea && modalSaveButton && containerStyle.display !== 'none') {
activeContainer = modalNoteContainer;
activeTextarea = modalTextarea;
activeSaveButton = modalSaveButton;
console.log('Found active note form in modal:', modalTextarea.id);
}
}
}
// Strategy 2: If no modal note found, look for focused textarea or one with content
if (!activeContainer) {
console.log('No modal note found, checking for focused/active textarea...');
const allTextareas = document.querySelectorAll('textarea[name="note[message]"]');
// Check for focused textarea first
for (const textarea of allTextareas) {
if (document.activeElement === textarea) {
const container = textarea.closest('.js-noteContainer');
const saveButton = container?.querySelector('button.js-saveNote');
if (container && saveButton && window.getComputedStyle(container).display !== 'none') {
activeContainer = container;
activeTextarea = textarea;
activeSaveButton = saveButton;
console.log('Found focused textarea:', textarea.id);
break;
}