-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
amazongpt.user.js
3099 lines (2786 loc) Β· 184 KB
/
amazongpt.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 AmazonGPT π€
// @description Adds the magic of AI to Amazon shopping
// @author KudoAI
// @namespace https://kudoai.com
// @version 2024.12.25.2
// @license MIT
// @icon https://amazongpt.kudoai.com/assets/images/icons/amazongpt/black-gold-teal/icon48.png?v=0fddfc7
// @icon64 https://amazongpt.kudoai.com/assets/images/icons/amazongpt/black-gold-teal/icon64.png?v=0fddfc7
// @compatible chrome except for Streaming Mode w/ Tampermonkey (use ScriptCat instead)
// @compatible firefox
// @compatible edge except for Streaming Mode w/ Tampermonkey (use ScriptCat instead)
// @compatible opera
// @compatible operagx
// @compatible brave except for Streaming Mode w/ Tampermonkey (use ScriptCat instead)
// @compatible vivaldi except for Streaming Mode w/ Tampermonkey (use ScriptCat instead)
// @compatible waterfox
// @compatible librewolf
// @compatible ghost
// @compatible qq
// @compatible whale
// @compatible kiwi
// @compatible mask
// @match *://www.amazon.com/*
// @match *://www.amazon.ae/*
// @match *://www.amazon.com.be/*
// @match *://www.amazon.ca/*
// @match *://www.amazon.cn/*
// @match *://www.amazon.co.jp/*
// @match *://www.amazon.co.uk/*
// @match *://www.amazon.co.za/*
// @match *://www.amazon.com.au/*
// @match *://www.amazon.com.br/*
// @match *://www.amazon.com.mx/*
// @match *://www.amazon.com.tr/*
// @match *://www.amazon.com/*
// @match *://www.amazon.de/*
// @match *://www.amazon.eg/*
// @match *://www.amazon.es/*
// @match *://www.amazon.fr/*
// @match *://www.amazon.in/*
// @match *://www.amazon.it/*
// @match *://www.amazon.nl/*
// @match *://www.amazon.pl/*
// @match *://www.amazon.sa/*
// @match *://www.amazon.se/*
// @match *://www.amazon.sg/*
// @exclude *://*.amazon.*/ap/signin*
// @include https://auth0.openai.com
// @connect api.binjie.fun
// @connect api.openai.com
// @connect api11.gptforlove.com
// @connect cdn.jsdelivr.net
// @connect chatai.mixerbox.com
// @connect chatgpt.com
// @connect update.greasyfork.org
// @connect fanyi.sogou.com
// @require https://cdn.jsdelivr.net/npm/@kudoai/chatgpt.js@3.4.0/dist/chatgpt.min.js#sha256-LfB3mqeB6Xiq2BDub1tn3BtvEiMcaWEp+I094MFpA+Q=
// @require https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.2.0/crypto-js.min.js#sha256-dppVXeVTurw1ozOPNE3XqhYmDJPOosfbKQcHyQSE58w=
// @require https://cdn.jsdelivr.net/npm/generate-ip@2.4.4/dist/generate-ip.min.js#sha256-aQQKAQcMgCu8IpJp9HKs387x0uYxngO+Fb4pc5nSF4I=
// @require https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js#sha256-g3pvpbDHNrUrveKythkPMF2j/J7UFoHbUyFQcFe1yEY=
// @require https://cdn.jsdelivr.net/npm/katex@0.16.10/dist/katex.min.js#sha256-n0UwfFeU7SR6DQlfOmLlLvIhWmeyMnIDp/2RmVmuedE=
// @require https://cdn.jsdelivr.net/npm/katex@0.16.10/dist/contrib/auto-render.min.js#sha256-e1fUJ6xicGd9r42DgN7SzHMzb5FJoWe44f4NbvZmBK4=
// @require https://cdn.jsdelivr.net/npm/marked@12.0.2/marked.min.js#sha256-Ffq85bZYmLMrA/XtJen4kacprUwNbYdxEKd0SqhHqJQ=
// @resource amzgptLSicon https://amazongpt.kudoai.com/assets/images/icons/amazongpt/black-gold-teal/icon64.png.b64?v=0fddfc7#sha256-0AAauajMY4eRCDUtqRMRqBl1gaxxF0mFt4eRnFGlU24=
// @resource amzgptDSicon https://amazongpt.kudoai.com/assets/images/icons/amazongpt/white/icon64.png.b64?v=1ac5561#sha256-qTQ5tnMF6XeH3UZkQOlJZvdE1nkn5/9srNKJqFtcCDo=
// @resource amzgptLSlogo https://amazongpt.kudoai.com/assets/images/logos/amazongpt/black-gold/logo509x74.png.b64?v=1ac5561#sha256-wSW1EtGtscP0ZcUweFBqKfswt3NzEjbKxn5COYyihVA=
// @resource amzgptDSlogo https://amazongpt.kudoai.com/assets/images/logos/amazongpt/white-teal/logo509x74.png.b64?v=1ac5561#sha256-EWstwtlU8+gXSM98gpr6OR3OZ63ttHVNp/NQ7IMzFDA=
// @resource hljsCSS https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/dark.min.css#sha256-v0N76BFFkH0dCB8bUr4cHSVN8A/zCaOopMuSmJWV/5w=
// @resource brsCSS https://assets.aiwebextensions.com/styles/rising-stars/dist/black.min.css?v=0cde30f9ae3ce99ae998141f6e7a36de9b0cc2e7#sha256-4nbm81/JSas4wmxFIdliBBzoEEHRZ057TpzNX1PoQIs=
// @resource wrsCSS https://assets.aiwebextensions.com/styles/rising-stars/dist/white.min.css?v=0cde30f9ae3ce99ae998141f6e7a36de9b0cc2e7#sha256-pW8xWWV6tm8Q6Ms+HWZv6+QzzTLJPyL1DyE18ywpVaE=
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_deleteValue
// @grant GM_cookie
// @grant GM_registerMenuCommand
// @grant GM_unregisterMenuCommand
// @grant GM_openInTab
// @grant GM_getResourceText
// @grant GM_xmlhttpRequest
// @grant GM.xmlHttpRequest
// @noframes
// @downloadURL https://update.greasyfork.org/scripts/500663/amazongpt.user.js
// @updateURL https://update.greasyfork.org/scripts/500663/amazongpt.meta.js
// @homepageURL https://amazongpt.kudoai.com
// @supportURL https://amazongpt.kudoai.com/issues
// @contributionURL https://github.com/sponsors/KudoAI
// ==/UserScript==
// Dependencies:
// β chatgpt.js (https://chatgpt.js.org) Β© 2023β2024 KudoAI & contributors under the MIT license
// β generate-ip (https://generate-ip.org) Β© 2024 Adam Lui & contributors under the MIT license
// β highlight.js (https://highlightjs.org) Β© 2006 Ivan Sagalaev under the BSD 3-Clause license
// β KaTeX (https://katex.org) Β© 2013β2020 Khan Academy & other contributors under the MIT license
// β Marked (https://marked.js.org) Β© 2018+ MarkedJS Β© 2011β2018 Christopher Jeffrey under the MIT license
(async () => {
// Init ENV context
const env = {
browser: { language: chatgpt.getUserLanguage() },
scriptManager: {
name: (() => { try { return GM_info.scriptHandler } catch (err) { return 'unknown' }})(),
version: (() => { try { return GM_info.version } catch (err) { return 'unknown' }})()
}
};
['Chrome', 'Firefox', 'Edge', 'Brave', 'Mobile'].forEach(platform =>
env.browser[`is${ platform == 'Firefox' ? 'FF' : platform }`] = chatgpt.browser['is' + platform]())
env.browser.isPortrait = env.browser.isMobile && (window.innerWidth < window.innerHeight)
env.scriptManager.supportsTooltips = env.scriptManager.name == 'Tampermonkey'
&& parseInt(env.scriptManager.version.split('.')[0]) >= 5
const xhr = typeof GM != 'undefined' && GM.xmlHttpRequest || GM_xmlhttpRequest
// Init APP data
const app = {
name: 'AmazonGPT', version: GM_info.script.version, symbol: 'π€',
configKeyPrefix: 'amazonGPT', cssPrefix: 'amazongpt',
chatgptJSver: /chatgpt\.js@([\d.]+)/.exec(GM_info.scriptMetaStr)[1],
urls: {
app: 'https://amazongpt.kudoai.com',
chatgptJS: 'https://chatgpt.js.org',
contributors: 'https://github.com/KudoAI/amazongpt/tree/main/docs/#-contributors',
gitHub: 'https://github.com/KudoAI/amazongpt',
greasyFork: 'https://greasyfork.org/scripts/500663-amazongpt',
publisher: 'https://www.kudoai.com',
relatedExtensions: 'https://github.com/adamlui/ai-web-extensions',
review: { greasyFork: 'https://greasyfork.org/scripts/500663-amazongpt/feedback#post-discussion' }
},
latestAssetCommitHash: '86e9341' // for cached messages.json
}
app.urls.support = app.urls.gitHub + '/issues/new'
app.urls.assetHost = app.urls.gitHub.replace('github.com', 'cdn.jsdelivr.net/gh') + `@${app.latestAssetCommitHash}`
app.urls.update = app.urls.greasyFork.replace('https://', 'https://update.')
.replace(/(\d+)-?([a-z-]*)$/i, (_, id, name) => `${id}/${ name || 'script' }.meta.js`)
app.msgs = {
appDesc: 'Adds AI to Amazon shopping',
menuLabel_proxyAPImode: 'Proxy API Mode',
menuLabel_autoFocusChatbar: 'Auto-Focus Chatbar',
menuLabel_whenStreaming: 'when streaming',
menuLabel_background: 'Background',
menuLabel_foreground: 'Foreground',
menuLabel_animations: 'Animations',
menuLabel_replyLanguage: 'Reply Language',
menuLabel_colorScheme: 'Color Scheme',
menuLabel_auto: 'Auto',
menuLabel_about: 'About',
menuLabel_settings: 'Settings',
about_version: 'Version',
about_poweredBy: 'Powered by',
about_openSourceCode: 'Open source code',
scheme_light: 'Light',
scheme_dark: 'Dark',
mode_proxy: 'Proxy Mode',
mode_streaming: 'Streaming Mode',
mode_autoScroll: 'Auto-Scroll',
mode_debug: 'Debug Mode',
tooltip_playAnswer: 'Play answer',
tooltip_fontSize: 'Font size',
tooltip_sendReply: 'Send reply',
tooltip_askRandQuestion: 'Ask random question',
tooltip_minimize: 'Minimize',
tooltip_restore: 'Restore',
tooltip_expand: 'Expand',
tooltip_shrink: 'Shrink',
tooltip_close: 'Close',
tooltip_copy: 'Copy',
tooltip_regen: 'Regenerate',
tooltip_reply: 'Reply',
tooltip_code: 'Code',
helptip_proxyAPImode: 'Uses a Proxy API for no-login access to AI',
helptip_streamingMode: 'Receive replies in a continuous text stream',
helptip_autoFocusChatbar: 'Auto-focus chatbar whenever it appears',
helptip_autoScroll: 'Auto-scroll responses as they generate in Streaming Mode',
helptip_bgAnimations: 'Show animated backgrounds in UI components',
helptip_fgAnimations: 'Show foreground animations in UI components',
helptip_replyLanguage: 'Language for AmazonGPT to reply in',
helptip_colorScheme: 'Scheme to display AmazonGPT UI components in',
helptip_debugMode: 'Show detailed logging in browser console',
placeholder_typeSomething: 'Type something',
prompt_updateReplyLang: 'Update reply language',
alert_langUpdated: 'Language updated',
alert_willReplyIn: 'will reply in',
alert_yourSysLang: 'your system language',
alert_choosePlatform: 'Choose a platform',
alert_updateAvail: 'Update available',
alert_newerVer: 'An update to',
alert_isAvail: 'is available',
alert_upToDate: 'Up-to-date',
alert_isUpToDate: 'is up-to-date',
alert_isUnsupportedIn: 'is unsupported in',
alert_whenUsing: 'when using',
alert_pleaseUse: 'Please use',
alert_instead: 'instead',
alert_unavailable: 'unavailable',
alert_isOnlyAvailFor: 'is only available for',
alert_and: 'and',
alert_userscriptMgrNoStream: 'Your userscript manager does not support returning stream responses',
alert_isCurrentlyOnlyAvailBy: 'is currently only available by',
alert_openAIsupportSoon: 'Support for OpenAI API will be added shortly',
alert_waitingFor: 'Waiting for',
alert_response: 'response',
alert_login: 'Please login',
alert_thenRefreshPage: 'then refresh this page',
alert_tooManyRequests: 'ChatGPT is flooded with too many requests',
alert_parseFailed: 'Failed to parse response JSON',
alert_checkCloudflare: 'Please pass Cloudflare security check',
alert_notWorking: 'is not working',
alert_ifIssuePersists: 'If issue persists',
alert_try: 'Try',
alert_switchingOn: 'switching on',
alert_switchingOff: 'switching off',
notif_copiedToClipboard: 'Copied to clipboard',
btnLabel_moreAIextensions: 'More AI Extensions',
btnLabel_rateUs: 'Rate Us',
btnLabel_getSupport: 'Get Support',
btnLabel_checkForUpdates: 'Check for Updates',
btnLabel_update: 'Update',
btnLabel_dismiss: 'Dismiss',
link_viewChanges: 'View changes',
state_on: 'On',
state_off: 'Off'
}
// Init DEBUG mode
const config = {}
const settings = {
load(...keys) {
if (Array.isArray(keys[0])) keys = keys[0] // use 1st array arg, else all comma-separated ones
keys.forEach(key => config[key] = GM_getValue(app.configKeyPrefix + '_' + key, false))
},
save(key, val) { GM_setValue(app.configKeyPrefix + '_' + key, val) ; config[key] = val }
} ; settings.load('debugMode')
// Define LOG props/functions
const log = {
styles: {
prefix: {
base: `color: white ; padding: 2px 3px 2px 5px ; border-radius: 2px ; ${
env.browser.isFF ? 'font-size: 13px ;' : '' }`,
info: 'background: linear-gradient(344deg, rgba(0,0,0,1) 0%,'
+ 'rgba(0,0,0,1) 39%, rgba(30,29,43,0.6026611328125) 93%)',
working: 'background: linear-gradient(342deg, rgba(255,128,0,1) 0%,'
+ 'rgba(255,128,0,0.9612045501794468) 57%, rgba(255,128,0,0.7539216370141807) 93%)' ,
success: 'background: linear-gradient(344deg, rgba(0,107,41,1) 0%,'
+ 'rgba(3,147,58,1) 39%, rgba(24,126,42,0.7735294801514356) 93%)',
warning: 'background: linear-gradient(344deg, rgba(255,0,0,1) 0%,'
+ 'rgba(232,41,41,0.9079832616640406) 57%, rgba(222,49,49,0.6530813008797269) 93%)',
caller: 'color: blue'
},
msg: { working: 'color: #ff8000', warning: 'color: red' }
},
regEx: {
greenVals: { caseInsensitive: /\b(?:true|\d+)\b|success\W?/i, caseSensitive: /\bON\b/ },
redVals: { caseInsensitive: /\bfalse\b|error\W?/i, caseSensitive: /\BOFF\b/ },
purpVals: /[ '"]\w+['"]?: / },
prettifyObj(obj) { return JSON.stringify(obj)
.replace(/([{,](?=")|":)/g, '$1 ') // append spaces to { and "
.replace(/((?<!\})\})/g, ' $1') // prepend spaces to }
.replace(/"/g, '\'') // replace " w/ '
},
toTitleCase(str) { return str.charAt(0).toUpperCase() + str.slice(1) }
} ; ['info', 'error', 'debug'].forEach(logType =>
log[logType] = function() {
if (logType == 'debug' && !config.debugMode) return
const args = Array.from(arguments).map(arg => typeof arg == 'object' ? JSON.stringify(arg) : arg)
const msgType = args.some(arg => /\.{3}$/.test(arg)) ? 'working'
: args.some(arg => /\bsuccess\b|!$/i.test(arg)) ? 'success'
: args.some(arg => /\b(?:error|fail)\b/i.test(arg)) || logType == 'error' ? 'warning'
: 'info'
const prefixStyle = log.styles.prefix.base + log.styles.prefix[msgType]
const baseMsgStyle = log.styles.msg[msgType], msgStyles = []
// Combine regex
const allPatterns = Object.values(log.regEx).flatMap(val =>
val instanceof RegExp ? [val] : Object.values(val).filter(val => val instanceof RegExp))
const combinedPattern = new RegExp(allPatterns.map(pattern => pattern.source).join('|'), 'g')
// Combine args into finalMsg, color chars
let finalMsg = logType == 'error' && args.length == 1 ? 'ERROR: ' : ''
args.forEach((arg, idx) => {
finalMsg += idx > 0 ? (idx == 1 ? ': ' : ' ') : '' // separate multi-args
finalMsg += arg?.toString().replace(combinedPattern, match => {
const matched = (
Object.values(log.regEx.greenVals).some(val => {
if (val.test(match)) { msgStyles.push('color: green', baseMsgStyle) ; return true }})
|| Object.values(log.regEx.redVals).some(val => {
if (val.test(match)) { msgStyles.push('color: red', baseMsgStyle) ; return true }}))
if (!matched && log.regEx.purpVals.test(match)) { msgStyles.push('color: #dd29f4', baseMsgStyle) }
return `%c${match}%c`
})
})
console[logType == 'error' ? logType : 'info'](
`${app.symbol} %c${app.name}%c ${ log.caller ? `${log.caller} Β» ` : '' }%c${finalMsg}`,
prefixStyle, log.styles.prefix.caller, baseMsgStyle, ...msgStyles
)
}
)
// LOCALIZE app.msgs for non-English users
if (!env.browser.language.startsWith('en')) {
log.debug('Localizing app messages...')
const localizedMsgs = await new Promise(resolve => {
const msgHostDir = app.urls.assetHost + '/greasemonkey/_locales/',
msgLocaleDir = ( env.browser.language ? env.browser.language.replace('-', '_') : 'en' ) + '/'
let msgHref = msgHostDir + msgLocaleDir + 'messages.json', msgXHRtries = 0
function fetchMsgs() { xhr({ method: 'GET', url: msgHref, onload: handleMsgs })}
function handleMsgs(resp) {
try { // to return localized messages.json
const msgs = JSON.parse(resp.responseText), flatMsgs = {}
for (const key in msgs) // remove need to ref nested keys
if (typeof msgs[key] == 'object' && 'message' in msgs[key])
flatMsgs[key] = msgs[key].message
resolve(flatMsgs)
} catch (err) { // if bad response
msgXHRtries++ ; if (msgXHRtries == 3) return resolve({}) // try original/region-stripped/EN only
msgHref = env.browser.language.includes('-') && msgXHRtries == 1 ? // if regional lang on 1st try...
msgHref.replace(/([^_]+_[^_]+)_[^/]*(\/.*)/, '$1$2') // ...strip region before retrying
: ( msgHostDir + 'en/messages.json' ) // else use default English messages
fetchMsgs()
}
}
fetchMsgs()
})
Object.assign(app.msgs, localizedMsgs)
log.debug(`Success! app.msgs = ${log.prettifyObj(app.msgs)}`)
}
// Init COMPATIBILITY flags
log.debug('Initializing compatibility flags...')
const streamingSupported = {
byBrowser: !(env.scriptManager.name == 'Tampermonkey'
&& (env.browser.isChrome || env.browser.isEdge || env.browser.isBrave)),
byScriptManager: /Tampermonkey|ScriptCat/.test(env.scriptManager.name)
}
log.debug(`Success! streamingSupported = ${log.prettifyObj(streamingSupported)}`)
// Init SETTINGS
log.debug('Initializing settings...')
Object.assign(settings, { controls: {
proxyAPIenabled: { type: 'toggle', icon: 'sunglasses',
label: app.msgs.menuLabel_proxyAPImode,
helptip: app.msgs.helptip_proxyAPImode },
streamingDisabled: { type: 'toggle', icon: 'signalStream',
label: app.msgs.mode_streaming,
helptip: app.msgs.helptip_streamingMode },
autoFocusChatbarDisabled: { type: 'toggle', mobile: false, icon: 'caretsInward',
label: app.msgs.menuLabel_autoFocusChatbar,
helptip: app.msgs.helptip_autoFocusChatbar },
autoScroll: { type: 'toggle', mobile: false, icon: 'arrowsDown',
label: `${app.msgs.mode_autoScroll} (${app.msgs.menuLabel_whenStreaming})`,
helptip: app.msgs.helptip_autoScroll },
bgAnimationsDisabled: { type: 'toggle', icon: 'sparkles',
label: `${app.msgs.menuLabel_background} ${app.msgs.menuLabel_animations}`,
helptip: app.msgs.helptip_bgAnimations },
fgAnimationsDisabled: { type: 'toggle', icon: 'sparkles',
label: `${app.msgs.menuLabel_foreground} ${app.msgs.menuLabel_animations}`,
helptip: app.msgs.helptip_fgAnimations },
replyLang: { type: 'prompt', icon: 'languageChars',
label: app.msgs.menuLabel_replyLanguage,
helptip: app.msgs.helptip_replyLanguage },
scheme: { type: 'modal', icon: 'scheme',
label: app.msgs.menuLabel_colorScheme,
helptip: app.msgs.helptip_colorScheme },
debugMode: { type: 'toggle', icon: 'bug',
label: app.msgs.mode_debug,
helptip: app.msgs.helptip_debugMode },
about: { type: 'modal', icon: 'questionMarkCircle',
label: `${app.msgs.menuLabel_about} ${app.name}...` }
}})
Object.assign(config, { minFontSize: 11, maxFontSize: 24, lineHeightRatio: 1.28 })
settings.load('autoFocusChatbarDisabled', 'autoScroll', 'bgAnimationsDisabled', 'expanded', 'fgAnimationsDisabled',
'fontSize', 'minimized', 'proxyAPIenabled', 'replyLanguage', 'scheme', 'streamingDisabled')
if (!config.replyLanguage) settings.save('replyLanguage', env.browser.language) // init reply language if unset
if (!config.fontSize) settings.save('fontSize', 14) // init reply font size if unset
if (!streamingSupported.byBrowser || !streamingSupported.byScriptManager)
settings.save('streamingDisabled', true) // disable Streaming in unspported env
log.debug(`Success! config = ${log.prettifyObj(config)}`)
// Init UI props
env.ui = { app: { scheme: config.scheme || ( chatgpt.isDarkMode() ? 'dark' : 'light' ) }}
// Init API props
const apis = {
'AIchatOS': {
endpoint: 'https://api.binjie.fun/api/generateStream',
expectedOrigin: {
url: 'https://chat18.aichatos68.com',
headers: {
'Accept': 'application/json, text/plain, */*', 'Priority': 'u=0', 'Sec-Fetch-Site': 'cross-site'
}
},
method: 'POST', streamable: true, accumulatesText: false, failFlags: ['εΎζ±ζε°', 'η³»η»ε
¬ε'],
userID: '#/chat/' + Date.now()
},
'GPTforLove': {
endpoint: 'https://api11.gptforlove.com/chat-process',
expectedOrigin: {
url: 'https://ai27.gptforlove.com',
headers: {
'Accept': 'application/json, text/plain, */*', 'Priority': 'u=0', 'Sec-Fetch-Site': 'same-site'
}
},
method: 'POST', streamable: true, accumulatesText: true,
failFlags: ['[\'"]?status[\'"]?:\\s*[\'"]Fail[\'"]']
},
'MixerBox AI': {
endpoint: 'https://chatai.mixerbox.com/api/chat/stream',
expectedOrigin: {
url: 'https://chatai.mixerbox.com',
headers: { 'Accept': '*/*', 'Alt-Used': 'chatai.mixerbox.com', 'Sec-Fetch-Site': 'same-origin' }
},
method: 'POST', streamable: true, accumulatesText: false
},
'OpenAI': {
endpoints: {
auth: 'https://auth0.openai.com',
completions: 'https://api.openai.com/v1/chat/completions',
session: 'https://chatgpt.com/api/auth/session'
},
expectedOrigin: {
url: 'https://chatgpt.com',
headers: { 'Accept': '*/*', 'Priority': 'u=4', 'Sec-Fetch-Site': 'same-site' }
},
method: 'POST', streamable: true
}
}
// Init INPUT EVENTS
const inputEvents = {} ; ['down', 'move', 'up'].forEach(action =>
inputEvents[action] = ( window.PointerEvent ? 'pointer' : env.browser.isMobile ? 'touch' : 'mouse' ) + action)
// Init ALERTS
Object.assign(app, { alerts: {
waitingResponse: `${app.msgs.alert_waitingFor} ${app.name} ${app.msgs.alert_response}...`,
login: `${app.msgs.alert_login} @ `,
checkCloudflare: `${app.msgs.alert_checkCloudflare} @ `,
tooManyRequests: `${app.msgs.alert_tooManyRequests}.`,
parseFailed: `${app.msgs.alert_parseFailed}.`,
proxyNotWorking: `${app.msgs.mode_proxy} ${app.msgs.alert_notWorking}.`,
openAInotWorking: `OpenAI API ${app.msgs.alert_notWorking}.`,
suggestProxy: `${app.msgs.alert_try} ${app.msgs.alert_switchingOn} ${app.msgs.mode_proxy}`,
suggestOpenAI: `${app.msgs.alert_try} ${app.msgs.alert_switchingOff} ${app.msgs.mode_proxy}`
}})
// Define MENU functions
const menu = {
ids: [], state: {
symbols: ['β', 'βοΈ'], separator: env.scriptManager.name == 'Tampermonkey' ? ' β ' : ': ',
words: [app.msgs.state_off.toUpperCase(), app.msgs.state_on.toUpperCase()]
},
register() {
// Add Proxy API Mode toggle
const pmLabel = menu.state.symbols[+config.proxyAPIenabled] + ' '
+ settings.controls.proxyAPIenabled.label + ' '
+ menu.state.separator + menu.state.words[+config.proxyAPIenabled]
menu.ids.push(GM_registerMenuCommand(pmLabel, toggle.proxyMode,
env.scriptManager.supportsTooltips ? { title: settings.controls.proxyAPIenabled.helptip } : undefined));
// Add About/Settings entries
['about', 'settings'].forEach(entryType => menu.ids.push(GM_registerMenuCommand(
entryType == 'about' ? `π‘ ${settings.controls.about.label}` : `βοΈ ${app.msgs.menuLabel_settings}`,
() => modals.open(entryType), env.scriptManager.supportsTooltips ? { title: ' ' } : undefined
)))
},
refresh() {
if (typeof GM_unregisterMenuCommand == 'undefined') {
log.debug('GM_unregisterMenuCommand not supported.') ; return }
for (const id of menu.ids) { GM_unregisterMenuCommand(id) } menu.register()
}
}
function updateCheck() {
log.caller = 'updateCheck()'
log.debug(`currentVer = ${app.version}`)
// Fetch latest meta
log.debug('Fetching latest userscript metadata...')
xhr({
method: 'GET', url: app.urls.update + '?t=' + Date.now(),
headers: { 'Cache-Control': 'no-cache' },
onload: resp => {
log.debug('Success! Response received')
// Compare versions, alert if update found
log.debug('Comparing versions...')
app.latestVer = /@version +(.*)/.exec(resp.responseText)[1]
for (let i = 0 ; i < 4 ; i++) { // loop thru subver's
const currentSubVer = parseInt(app.version.split('.')[i], 10) || 0,
latestSubVer = parseInt(app.latestVer.split('.')[i], 10) || 0
if (currentSubVer > latestSubVer) break // out of comparison since not outdated
else if (latestSubVer > currentSubVer) // if outdated
return modals.open('update', 'available')
}
// Alert to no update found, nav back to About
modals.open('update', 'unavailable')
}})
}
// Define FACTORY functions
const create = {
anchor(linkHref, displayContent, attrs = {}) {
const anchor = document.createElement('a'),
defaultAttrs = { href: linkHref, target: '_blank', rel: 'noopener' },
finalAttrs = { ...defaultAttrs, ...attrs }
Object.entries(finalAttrs).forEach(([attr, value]) => anchor.setAttribute(attr, value))
if (displayContent) anchor.append(displayContent)
return anchor
},
style(content) {
const style = document.createElement('style')
if (content) style.innerText = content
return style
},
svgElem(type, attrs) {
const elem = document.createElementNS('http://www.w3.org/2000/svg', type)
for (const attr in attrs) elem.setAttributeNS(null, attr, attrs[attr])
return elem
}
}
// Define FEEDBACK functions
function appAlert(...alerts) {
alerts = alerts.flat() // flatten array args nested by spread operator
appDiv.textContent = ''
const alertP = document.createElement('p')
alertP.id = `${app.cssPrefix}-alert` ; alertP.className = 'no-user-select'
alerts.forEach((alert, idx) => { // process each alert for display
let msg = app.alerts[alert] || alert // use string verbatim if not found in app.alerts
if (idx > 0) msg = ' ' + msg // left-pad 2nd+ alerts
if (msg.includes(app.alerts.login)) session.deleteOpenAIcookies()
if (msg.includes(app.alerts.waitingResponse)) alertP.classList.add('loading')
// Add login link to login msgs
if (msg.includes('@'))
msg += '<a class="alert-link" target="_blank" rel="noopener"'
+ ' href="https://chatgpt.com">chatgpt.com</a>,'
+ ` ${app.msgs.alert_thenRefreshPage}.`
+ ` (${app.msgs.alert_ifIssuePersists},`
+ ` ${( app.msgs.alert_try ).toLowerCase() }`
+ ` ${app.msgs.alert_switchingOn}`
+ ` ${app.msgs.mode_proxy})`
// Hyperlink app.msgs.alert_switching<On|Off>
const foundState = ['On', 'Off'].find(state =>
msg.includes(app.msgs['alert_switching' + state]) || new RegExp(`\\b${state}\\b`, 'i').test(msg))
if (foundState) { // hyperlink switch phrase for click listener to toggle.proxyMode()
const switchPhrase = app.msgs['alert_switching' + foundState] || 'switching ' + foundState.toLowerCase()
msg = msg.replace(switchPhrase, `<a class="alert-link" href="#">${switchPhrase}</a>`)
}
// Create/fill/append msg span
const msgSpan = document.createElement('span')
msgSpan.innerHTML = msg ; alertP.append(msgSpan)
// Activate toggle link if necessary
msgSpan.querySelector('[href="#"]')?.addEventListener('click', toggle.proxyMode)
})
appDiv.append(alertP)
}
function notify(msg, pos = '', notifDuration = '', shadow = 'shadow') {
// Strip state word to append styled one later
const foundState = menu.state.words.find(word => msg.includes(word))
if (foundState) msg = msg.replace(foundState, '')
// Show notification
chatgpt.notify(msg, pos, notifDuration, shadow)
const notif = document.querySelector('.chatgpt-notif:last-child')
// Prepend app icon
const notifIcon = icons.amzgpt.create('white')
notifIcon.style.cssText = 'width: 28px ; position: relative ; top: 4.8px ; margin-right: 8px'
notif.prepend(notifIcon)
// Append notif type icon
const iconStyles = 'width: 28px ; height: 28px ; position: relative ; top: 3.5px ; margin-left: 11px ;',
mode = Object.keys(settings.controls).find(key => settings.controls[key].label.includes(msg.trim()))
if (mode && !/(?:pre|suf)fix/.test(mode)) {
const modeIcon = icons[settings.controls[mode].icon].create()
modeIcon.style.cssText = iconStyles
+ ( // raise some icons
/focus|scroll/i.test(mode) ? 'top: 4px' : '' )
+ ( // shrink some icons
/animation|debug/i.test(mode) ? 'width: 23px ; height: 23px ; margin-top: 3px' : '' )
notif.append(modeIcon)
}
// Append styled state word
if (foundState) {
const styledStateSpan = document.createElement('span')
styledStateSpan.style.cssText = `font-weight: bold ; color: ${
foundState == menu.state.words[0] ? '#ef4848 ; text-shadow: rgba(255, 169, 225, 0.44) 2px 1px 5px'
: '#5cef48 ; text-shadow: rgba(255, 250, 169, 0.38) 2px 1px 5px' }`
styledStateSpan.append(foundState) ; notif.insertBefore(styledStateSpan, notif.children[2])
}
}
// Define MODAL functions
const modals = {
stack: [], // of types of undismissed modals
class: `${app.cssPrefix}-modal`,
alert(title = '', msg = '', btns = '', checkbox = '', width = '') { // generic one from chatgpt.alert()
const alertID = chatgpt.alert(title, msg, btns, checkbox, width),
alert = document.getElementById(alertID).firstChild
this.init(alert) // add classes/listeners/hack bg/glowup btns
return alert
},
open(modalType, modalSubType) { // custom ones
const modal = modalSubType ? modals[modalType][modalSubType]()
: (modals[modalType].show || modals[modalType])()
if (settings.controls[modalType]?.type != 'prompt') { // add to stack
this.stack.unshift(modalSubType ? `${modalType}_${modalSubType}` : modalType)
log.debug(`Modal stack: ${JSON.stringify(modals.stack)}`)
}
this.init(modal) // add classes/listeners/hack bg/glowup btns
this.observeRemoval(modal, modalType, modalSubType) // to maintain stack for proper nav
if (!modals.handlers.key.added) { // add key listener to dismiss modals
document.addEventListener('keydown', modals.handlers.key) ; modals.handlers.key.added = true }
},
init(modal) {
if (!this.styles) this.stylize() // to init/append stylesheet
// Add classes
modal.classList.add(this.class) ; modal.parentNode.classList.add(`${this.class}-bg`)
// Add listeners
modal.onwheel = modal.ontouchmove = event => event.preventDefault() // disable wheel/swipe scrolling
modal.onmousedown = modals.handlers.drag.mousedown // enable click-dragging
if (!modal.parentNode.className.includes('chatgpt-modal')) { // enable click-dismissing native modals
const dismissElems = [modal.parentNode, modal.querySelector('[class*=-close-btn]')]
dismissElems.forEach(elem => elem.onclick = modals.handlers.click)
}
// Hack BG
fillStarryBG(modal)
setTimeout(() => { // dim bg
modal.parentNode.style.backgroundColor = `rgba(67, 70, 72, ${
env.ui.app.scheme == 'dark' ? 0.62 : 0.33 })`
modal.parentNode.classList.add('animated')
}, 100) // delay for transition fx
// Glowup btns
if (env.ui.app.scheme == 'dark' && !config.fgAnimationsDisabled) toggle.btnGlow()
},
stylize() {
if (!this.styles) {
this.styles = document.createElement('style') ; this.styles.id = `${this.class}-styles`
document.head.append(this.styles)
}
this.styles.innerText = (
'@keyframes modal-zoom-fade-out {'
+ '0% { opacity: 1 } 50% { opacity: 0.25 ; transform: scale(1.05) }'
+ '100% { opacity: 0 ; transform: scale(1.35) }}'
+ '.chatgpt-modal > div {'
+ 'padding: 20px 30px 24px 17px !important ;' // increase alert padding
+ 'background-color: white !important ; color: black }'
+ '.chatgpt-modal p { margin: -8px 0 -14px 4px ; font-size: 22px ; line-height: 31px }'
+ `.chatgpt-modal a { color: #${ env.ui.app.scheme == 'dark' ? '00cfff' : '1e9ebb' } !important }`
+ '.modal-buttons {'
+ `margin: 35px -5px 2px ; ${ env.browser.isMobile ? -5 : -15 }px !important ; width: 100% }`
+ '.chatgpt-modal button {'
+ 'font-size: 1rem ; text-transform: uppercase ; min-width: 121px ;'
+ `padding: ${ env.browser.isMobile ? '7px' : '4px 10px' } !important ;`
+ 'cursor: pointer ; border-radius: 0 !important ; height: 39px ;'
+ 'border: 1px solid ' + ( env.ui.app.scheme == 'dark' ? 'white' : 'black' ) + '!important ;'
+ `${ env.ui.app.scheme == 'dark' ? 'background: none ; color: white' : '' }}`
+ '.primary-modal-btn { background: black !important ; color: white !important }'
+ '.chatgpt-modal button:hover { background-color: #9cdaff !important ; color: black !important }'
+ ( env.ui.app.scheme == 'dark' ? // darkmode chatgpt.alert() styles
( '.chatgpt-modal > div, .chatgpt-modal button:not(.primary-modal-btn) {'
+ 'background-color: black !important ; color: white !important }'
+ '.primary-modal-btn { background: hsl(186 100% 69%) !important ; color: black !important }'
+ '.chatgpt-modal a { color: #00cfff !important }'
+ '.chatgpt-modal button:hover {'
+ 'background-color: #00cfff !important ; color: black !important }' ) : '' )
+ `.${modals.class} { display: grid ; place-items: center }` // for centered icon/logo
+ '[class*=modal-close-btn] {'
+ 'position: absolute !important ; float: right ; top: 14px !important ; right: 16px !important ;'
+ 'cursor: pointer ; width: 33px ; height: 33px ; border-radius: 20px }'
+ `[class*=modal-close-btn] path {${ env.ui.app.scheme == 'dark' ? 'stroke: white ; fill: white'
: 'stroke: #9f9f9f ; fill: #9f9f9f' }}`
+ ( env.ui.app.scheme == 'dark' ? // invert dark mode hover paths
'[class*=modal-close-btn]:hover path { stroke: black ; fill: black }' : '' )
+ '[class*=modal-close-btn]:hover { background-color: #f2f2f2 }' // hover underlay
+ '[class*=modal-close-btn] svg { margin: 11.5px }' // center SVG for hover underlay
+ '[class*=-modal] h2 {'
+ 'font-size: 27px ; font-weight: bold ; line-height: 32px ; padding: 0 ;'
+ 'margin: 9px 0 22px !important ;'
+ `${ env.browser.isMobile ? 'text-align: center' // center on mobile
: 'justify-self: start' }}` // left-align on desktop
+ '[class*=-modal] p { justify-self: start ; font-size: 20px }'
+ '[class*=-modal] button { font-size: 14px }'
+ '[class*=-modal-bg] {'
+ 'pointer-events: auto ;' // override any disabling from site modals
+ 'position: fixed ; top: 0 ; left: 0 ; width: 100% ; height: 100% ;' // expand to full view-port
+ 'transition: background-color .25s ease !important ;' // speed to show bg dim
+ 'display: flex ; justify-content: center ; align-items: center ; z-index: 9999 }' // align
+ '[class*=-modal-bg].animated > div {'
+ 'z-index: 13456 ; opacity: 0.98 ; transform: translateX(0) translateY(0) }'
+ '[class$=-modal] {' // native modals + chatgpt.alert()s
+ 'position: absolute ;' // to be click-draggable
+ 'opacity: 0 ;' // to fade-in
+ `background-image: linear-gradient(180deg, ${
env.ui.app.scheme == 'dark' ? '#99a8a6 -200px, black 200px' : '#b6ebff -296px, white 171px' }) ;`
+ `border: 1px solid ${ env.ui.app.scheme == 'dark' ? 'white' : '#b5b5b5' } !important ;`
+ `color: ${ env.ui.app.scheme == 'dark' ? 'white' : 'black' } ;`
+ 'transform: translateX(-3px) translateY(7px) ;' // offset to move-in from
+ 'transition: opacity 0.65s cubic-bezier(.165,.84,.44,1),' // for fade-ins
+ 'transform 0.55s cubic-bezier(.165,.84,.44,1) !important }' // for move-ins
+ ( config.fgAnimationsDisabled || env.browser.isMobile ? '' : (
'[class$=-modal] button { transition: transform 0.15s ease }'
+ '[class$=-modal] button:hover { transform: scale(1.055) }' ))
// Glowing modal btns
+ ':root { --glow-color: hsl(186 100% 69%); }'
+ '.glowing-btn {'
+ 'perspective: 2em ; font-weight: 900 ; animation: border-flicker 2s linear infinite ;'
+ '-webkit-box-shadow: inset 0 0 0.5em 0 var(--glow-color), 0 0 0.5em 0 var(--glow-color) ;'
+ 'box-shadow: inset 0 0 0.5em 0 var(--glow-color), 0 0 0.5em 0 var(--glow-color) ;'
+ '-moz-box-shadow: inset 0 0 0.5em 0 var(--glow-color), 0 0 0.5em 0 var(--glow-color) }'
+ '.glowing-txt {'
+ 'animation: text-flicker 3s linear infinite ;'
+ '-webkit-text-shadow: 0 0 0.125em hsl(0 0% 100% / 0.3), 0 0 0.45em var(--glow-color) ;'
+ '-moz-text-shadow: 0 0 0.125em hsl(0 0% 100% / 0.3), 0 0 0.45em var(--glow-color) ;'
+ 'text-shadow: 0 0 0.125em hsl(0 0% 100% / 0.3), 0 0 0.45em var(--glow-color) }'
+ '.faulty-letter {'
+ 'opacity: 0.5 ; animation: faulty-flicker 2s linear infinite }'
+ ( !env.browser.isMobile ? 'background: var(--glow-color) ;'
+ 'transform: translateY(120%) rotateX(95deg) scale(1, 0.35)' : '' ) + '}'
+ '.glowing-btn::after {'
+ 'content: "" ; position: absolute ; top: 0 ; bottom: 0 ; left: 0 ; right: 0 ;'
+ 'opacity: 0 ; z-index: -1 ; box-shadow: 0 0 2em 0.2em var(--glow-color) ;'
+ 'background-color: var(--glow-color) ; transition: opacity 100ms linear }'
+ '.glowing-btn:hover { color: rgba(0, 0, 0, 0.8) ; text-shadow: none ; animation: none }'
+ '.glowing-btn:hover .glowing-txt { animation: none }'
+ '.glowing-btn:hover .faulty-letter { animation: none ; text-shadow: none ; opacity: 1 }'
+ '.glowing-btn:hover:before { filter: blur(1.5em) ; opacity: 1 }'
+ '.glowing-btn:hover:after { opacity: 1 }'
+ '@keyframes faulty-flicker {'
+ '0% { opacity: 0.1 } 2% { opacity: 0.1 } 4% { opacity: 0.5 } 19% { opacity: 0.5 }'
+ '21% { opacity: 0.1 } 23% { opacity: 1 } 80% { opacity: 0.5 } 83% { opacity: 0.4 }'
+ '87% { opacity: 1 }}'
+ '@keyframes text-flicker {'
+ '0% { opacity: 0.1 } 2% { opacity: 1 } 8% { opacity: 0.1 } 9% { opacity: 1 }'
+ '12% { opacity: 0.1 } 20% { opacity: 1 } 25% { opacity: 0.3 } 30% { opacity: 1 }'
+ '70% { opacity: 0.7 } 72% { opacity: 0.2 } 77% { opacity: 0.9 } 100% { opacity: 0.9 }}'
+ '@keyframes border-flicker {'
+ '0% { opacity: 0.1 } 2% { opacity: 1 } 4% { opacity: 0.1 } 8% { opacity: 1 }'
+ '70% { opacity: 0.7 } 100% { opacity: 1 }}'
// Settings modal
+ `#${app.cssPrefix}-settings {`
+ `min-width: ${ env.browser.isPortrait ? 288 : 755 }px ; max-width: 75vw ; margin: 12px 23px ;`
+ 'word-wrap: break-word ; border-radius: 15px ; box-shadow: 0 30px 60px rgba(0, 0, 0, .12) ;'
+ `${ env.ui.app.scheme == 'dark' ? 'stroke: white ; fill: white' : 'stroke: black ; fill: black' }}`
+ `#a${app.cssPrefix}-settings-title {`
+ 'font-weight: bold ; line-height: 19px ; text-align: center ;'
+ `margin: 0 ${ env.browser.isMobile ? 6 : 24 }px 8px 0 }`
+ `#${app.cssPrefix}-settings-title h4 {`
+ `font-size: ${ env.browser.isPortrait ? 26 : 31 }px ; font-weight: bold ; margin-top: -25px }`
+ `#${app.cssPrefix}-settings ul {`
+ 'list-style: none ; padding: 0 ; margin: 0 0 2px -3px ;' // hide bullets, close bottom gap
+ `width: ${ env.browser.isPortrait ? 100 : 50 }% }` // set width based on column cnt
+ `#${app.cssPrefix}-settings li {`
+ `color: ${ env.ui.app.scheme == 'dark' ? 'rgb(255, 255, 255, 0.65)' : 'rgba(0, 0, 0, 0.45)' } ;`
+ `fill: ${ env.ui.app.scheme == 'dark' ? 'rgb(255, 255, 255, 0.65)' : 'rgba(0, 0, 0, 0.45)' } ;`
+ `stroke: ${ env.ui.app.scheme == 'dark' ? 'rgb(255, 255, 255, 0.65)' : 'rgba(0, 0, 0, 0.45)' } ;`
+ 'list-style: none ; height: 37px ; font-size: 15.5px ; transition: transform 0.1s ease ;'
+ `color: ${ env.ui.app.scheme == 'dark' ? 'white' : 'black' } ;`
+ `padding: 6px 10px 4px ; border-bottom: 1px dotted ${ env.ui.app.scheme == 'dark' ? 'white' : 'black' } ;`
+ 'border-radius: 3px }' // make highlight strips slightly rounded
+ `#${app.cssPrefix}-settings li.active {`
+ `color: ${ env.ui.app.scheme == 'dark' ? 'rgb(255, 255, 255)' : 'rgba(0, 0, 0)' } ;` // for text
+ `fill: ${ env.ui.app.scheme == 'dark' ? 'rgb(255, 255, 255)' : 'rgba(0, 0, 0)' } ;` // for icons
+ `stroke: ${ env.ui.app.scheme == 'dark' ? 'rgb(255, 255, 255)' : 'rgba(0, 0, 0)' }}` // for icons
+ `#${app.cssPrefix}-settings li label {`
+ 'display: contents ; padding-right: 20px ;' // right-pad labels so toggles don't hug
+ 'font-weight: normal }' // override Amazon boldening
+ `#${app.cssPrefix}-settings li:last-of-type { border-bottom: none }` // remove last bottom-border
+ `#${app.cssPrefix}-settings li, #${app.cssPrefix}-settings li label { cursor: pointer }` // add finger on hover
+ `#${app.cssPrefix}-settings li:hover {`
+ 'opacity: 1 ;'
+ 'background: rgba(100, 149, 237, 0.88) ; color: white ; fill: white ; stroke: white ;'
+ `${ config.fgAnimationsDisabled || env.browser.isMobile ? '' : 'transform: scale(1.22)' }}`
+ `#${app.cssPrefix}-settings li > input { float: right }` // pos toggles
+ '#scheme-settings-entry > span { margin: 0 -2px }' // align Scheme status
+ '#scheme-settings-entry > span > svg {' // v-align/left-pad Scheme status icon
+ 'position: relative ; top: 3px ; margin-left: 4px }'
+ ( config.fgAnimationsDisabled ? '' // spin cycle arrows icon when scheme is Auto
: ( '#scheme-settings-entry svg:has([d^="M204-318q-22"]),'
+ '.chatgpt-notif svg:has([d^="M204-318q-22"]) { animation: rotation 5s linear infinite }' ))
+ '@keyframes rotation { from { transform: rotate(0deg) } to { transform: rotate(360deg) }}'
+ `#about-settings-entry span { color: ${ env.ui.app.scheme == 'dark' ? '#28ee28' : 'green' }}`
+ '#about-settings-entry > span {' // outer About status span
+ `width: ${ env.browser.isPortrait ? '15vw' : '95px' } ; height: 20px ; overflow: hidden ;`
+ `${ config.fgAnimationsDisabled ? '' : ( // fade edges
'mask-image: linear-gradient('
+ 'to right, transparent, black 20%, black 89%, transparent) ;'
+ '-webkit-mask-image: linear-gradient('
+ 'to right, transparent, black 20%, black 89%, transparent)' )}}`
+ '#about-settings-entry > span > div {'
+ `text-wrap: nowrap ; ${
config.fgAnimationsDisabled ? '' : 'animation: ticker linear 60s infinite' }}`
+ '@keyframes ticker { 0% { transform: translateX(100%) } 100% { transform: translateX(-2000%) }}'
+ `.about-em { color: ${ env.ui.app.scheme == 'dark' ? 'white' : 'green' } !important }`
)
},
observeRemoval(modal, modalType, modalSubType) { // to maintain stack for proper nav
const modalBG = modal.parentNode
new MutationObserver(([mutation], obs) => {
mutation.removedNodes.forEach(removedNode => { if (removedNode == modalBG) {
if (modals.stack[0].includes(modalSubType || modalType)) { // new modal not launched so nav back
modals.stack.shift() // remove this modal type from stack 1st
const prevModalType = modals.stack[0]
if (prevModalType) { // open it
modals.stack.shift() // remove type from stack since re-added on open
modals.open(prevModalType)
}
}
obs.disconnect()
}})
}).observe(modalBG.parentNode, { childList: true, subtree: true })
},
hide(modal) {
log.caller = 'modals.hide()'
log.debug(`Dismissing div#${modal?.id}...`)
const modalContainer = modal?.parentNode
if (!modalContainer) return
modalContainer.style.animation = 'modal-zoom-fade-out 0.135s ease-out'
setTimeout(() => { modalContainer.remove() ; log.debug(`Success! div#${modal?.id} dismissed`)
}, 155) // delay for fade-out
},
handlers: {
click(event) { // to dismiss native modals
log.caller = 'modals.handlers.click()'
const clickedElem = event.target
if (clickedElem == event.currentTarget || clickedElem.closest('[class*=-close-btn]')) {
const modal = (clickedElem.closest('[class*=-modal-bg]') || clickedElem).firstChild
log.debug(`Dismiss element of div#${modal?.id} clicked`)
modals.hide(modal)
}
},
drag: {
mousedown(event) { // find modal, attach listeners, init XY offsets
if (event.button != 0) return // prevent non-left-click drag
if (getComputedStyle(event.target).cursor == 'pointer') return // prevent drag on interactive elems
modals.handlers.drag.draggableElem = event.currentTarget
modals.handlers.drag.draggableElem.style.cursor = 'grabbing'
event.preventDefault(); // prevent sub-elems like icons being draggable
['mousemove', 'mouseup'].forEach(eventType =>
document.addEventListener(eventType, modals.handlers.drag[eventType]))
const draggableElemRect = modals.handlers.drag.draggableElem.getBoundingClientRect()
modals.handlers.drag.offsetX = event.clientX - draggableElemRect.left +21
modals.handlers.drag.offsetY = event.clientY - draggableElemRect.top +12
},
mousemove(event) { // drag modal
if (modals.handlers.drag.draggableElem) {
const newX = event.clientX - modals.handlers.drag.offsetX,
newY = event.clientY - modals.handlers.drag.offsetY
Object.assign(modals.handlers.drag.draggableElem.style, { left: `${newX}px`, top: `${newY}px` })
}
},
mouseup() { // remove listeners, reset modals.handlers.drags.draggableElem
modals.handlers.drag.draggableElem.style.cursor = 'inherit';
['mousemove', 'mouseup'].forEach(eventType =>
document.removeEventListener(eventType, modals.handlers.drag[eventType]))
modals.handlers.drag.draggableElem = null
}
},
key(event) { // to dismiss native modals
log.caller = 'modals.handlers.key()'
if (event.key.startsWith('Esc') || event.keyCode == 27) {
log.debug('Escape pressed')
const modal = document.querySelector('[class$=-modal]')
if (modal) modals.hide(modal)
}
}
},
about() {
log.caller = 'modals.about()'
log.debug('Showing About modal...')
// Show modal
const aboutModal = modals.alert('',
`π·οΈ ${app.msgs.about_version}: <span class="about-em">${app.version}</span>\n`
+ 'β‘ ' + ( app.msgs.about_poweredBy ) + ': '
+ `<a href="${app.urls.chatgptJS}" target="_blank" rel="noopener">chatgpt.js</a>`
+ ` v${app.chatgptJSver}\n`
+ 'π ' + ( app.msgs.about_openSourceCode )
+ `: <a href="${app.urls.gitHub}" target="_blank" rel="nopener">`
+ app.urls.gitHub + '</a>',
[ // buttons
function checkForUpdates() { updateCheck() },
function getSupport(){},
function rateUs() { modals.open('feedback') },
function moreAIextensions(){}
], '', 656 // modal width
)
// Add logo
const aboutHeaderLogo = logos.amzgpt.create() ; aboutHeaderLogo.width = 420
aboutHeaderLogo.style.cssText = `max-width: 98% ; margin: 15px ${
env.browser.isMobile ? 'auto' : '15.5%' } 17px`
aboutModal.insertBefore(aboutHeaderLogo, aboutModal.firstChild.nextSibling) // after close btn
// Center text
aboutModal.querySelector('h2').remove() // remove empty title h2
aboutModal.querySelector('p').style.cssText = (
'justify-self: center ; text-align: center ; overflow-wrap: anywhere ;'
+ `margin: ${ env.browser.isPortrait ? '6px 0 -16px' : '3px 0 -6px' }` )
// Hack buttons
aboutModal.querySelectorAll('button').forEach(btn => {
btn.style.cssText = 'height: 58px ; min-width: 136px ; text-align: center'
// Replace link buttons w/ clones that don't dismiss modal
if (/support|extensions/i.test(btn.textContent)) {
const btnClone = btn.cloneNode(true)
btn.parentNode.replaceChild(btnClone, btn) ; btn = btnClone
btn.onclick = () => modals.safeWinOpen(app.urls[
btn.textContent.includes(app.msgs.btnLabel_getSupport) ? 'support' : 'relatedExtensions' ])
}
// Prepend emoji + localize labels
if (/updates/i.test(btn.textContent))
btn.textContent = `π ${app.msgs.btnLabel_checkForUpdates}`
else if (/support/i.test(btn.textContent))
btn.textContent = `π§ ${app.msgs.btnLabel_getSupport}`
else if (/rate/i.test(btn.textContent))
btn.textContent = `β ${app.msgs.btnLabel_rateUs}`
else if (/extensions/i.test(btn.textContent))
btn.textContent = `π€ ${app.msgs.btnLabel_moreAIextensions}`
// Hide Dismiss button
else btn.style.display = 'none'
})
log.debug('Success! About Modal shown')
return aboutModal
},
feedback() {
log.caller = 'modals.feedback()'
log.debug('Showing Feedback modal...')
// Init buttons
let btns = [ function greasyFork() {} ]
if (modals.stack[1] != 'about') btns.push(function github(){})
// Show modal
const feedbackModal = modals.alert(`${app.msgs.alert_choosePlatform}:`, '', btns, '', 408)
// Center CTA
feedbackModal.querySelector('h2').style.justifySelf = 'center'
// Re-style button cluster
const btnsDiv = feedbackModal.querySelector('.modal-buttons')
btnsDiv.style.cssText += 'display: flex ; flex-wrap: wrap ; justify-content: center ;'
+ 'margin-top: -2px !important' // close gap between title/btns
// Hack buttons
btns = btnsDiv.querySelectorAll('button')
btns.forEach((btn, idx) => {
if (idx == 0) btn.style.display = 'none' // hide Dismiss button