mirror of
https://github.com/BetterSEQTA/BetterSEQTA-Plus.git
synced 2026-12-07 04:03:49 +10:30
Compare commits
643
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6f07b39437 | ||
|
|
4d1577877a | ||
|
|
2c24826377 | ||
|
|
2083fe1262 | ||
|
|
f2b6b734d0 | ||
|
|
bca273e8d4 | ||
|
|
1bedf58e22 | ||
|
|
04602f10a2 | ||
|
|
c4934f2b8b | ||
|
|
712bcd6696 | ||
|
|
60be64b3ee | ||
|
|
5e4ce501a6 | ||
|
|
ab1197de0b | ||
|
|
63ab7a0b0e | ||
|
|
c1faab6e83 | ||
|
|
67033a0f8c | ||
|
|
2b46b1a9da | ||
|
|
6af30218a5 | ||
|
|
6b28d21a6c | ||
|
|
1aae8069f9 | ||
|
|
27520dc6ba | ||
|
|
52d5713234 | ||
|
|
7f42b50893 | ||
|
|
27269ac943 | ||
|
|
51b84f13b1 | ||
|
|
e3648330df | ||
|
|
64923cabbf | ||
|
|
5a5d30366f | ||
|
|
e2b1b6b81f | ||
|
|
92639ccf32 | ||
|
|
41ac78ab95 | ||
|
|
941597f197 | ||
|
|
896abaafe0 | ||
|
|
d5021fde4a | ||
|
|
009aae49e3 | ||
|
|
4708004ae3 | ||
|
|
848204d11c | ||
|
|
ec937ed57b | ||
|
|
919fb5a286 | ||
|
|
a63e6c168e | ||
|
|
98a6e7f161 | ||
|
|
5cd471c1b3 | ||
|
|
8e87bf17ba | ||
|
|
c52217e902 | ||
|
|
376ab65e3b | ||
|
|
a1aa5a1f55 | ||
|
|
54ae1a1417 | ||
|
|
d5cac1e5fa | ||
|
|
ee334c901b | ||
|
|
fc72d5ac5e | ||
|
|
3869a1f8d6 | ||
|
|
d4174ef006 | ||
|
|
6081b1446b | ||
|
|
6e2251159e | ||
|
|
1bd88ec81c | ||
|
|
d467339e91 | ||
|
|
db7fff63e3 | ||
|
|
c043d4dfaa | ||
|
|
0cb616ae95 | ||
|
|
009670e201 | ||
|
|
325f194638 | ||
|
|
0eeb10a057 | ||
|
|
0b6d01feaa | ||
|
|
e2a37b3ed3 | ||
|
|
3224f64875 | ||
|
|
0090368707 | ||
|
|
767c3b9e98 | ||
|
|
b55415c93b | ||
|
|
38f934c01f | ||
|
|
0f9b8efc40 | ||
|
|
9bfc0989c1 | ||
|
|
a967e2c2fb | ||
|
|
74fdd079dd | ||
|
|
29c31a2a22 | ||
|
|
0e3297636d | ||
|
|
d3fc4b0afd | ||
|
|
4d8445d7da | ||
|
|
29bdb0064d | ||
|
|
efa4f8b85c | ||
|
|
fea017bbd7 | ||
|
|
95908baa8e | ||
|
|
6868964366 | ||
|
|
4943d441e1 | ||
|
|
fb80457bd3 | ||
|
|
4e6978d860 | ||
|
|
db69e902ca | ||
|
|
9e16eaa543 | ||
|
|
8165b431e5 | ||
|
|
e3581bc940 | ||
|
|
47077f77d7 | ||
|
|
e78a03c4ad | ||
|
|
776c1e98d9 | ||
|
|
bd29ab62c6 | ||
|
|
5928414a1e | ||
|
|
d97cc86ab3 | ||
|
|
4d9b17df37 | ||
|
|
eb2bdbec2f | ||
|
|
5623c12904 | ||
|
|
b3b3763fc8 | ||
|
|
7eac66b2b0 | ||
|
|
242e4f3ff8 | ||
|
|
1ba5f1ef49 | ||
|
|
56571b7597 | ||
|
|
80287caacb | ||
|
|
6f4728aa18 | ||
|
|
9d8f0613cb | ||
|
|
aaf03129a5 | ||
|
|
7bc4c55619 | ||
|
|
e11358d728 | ||
|
|
80a1f7a7ba | ||
|
|
ef781a78ff | ||
|
|
d4cd2affe2 | ||
|
|
c1151cf501 | ||
|
|
74bdf3b07d | ||
|
|
6d33ef88aa | ||
|
|
7a8a3cb70e | ||
|
|
2c0642f418 | ||
|
|
4fbb75ac3f | ||
|
|
c150e79e1c | ||
|
|
a19b43ef37 | ||
|
|
5dba4ba8b5 | ||
|
|
d9c0fee06d | ||
|
|
b8a9721f1f | ||
|
|
a760a152dc | ||
|
|
72cce2cc55 | ||
|
|
da6a0f2ad3 | ||
|
|
6523238eed | ||
|
|
1f0163b775 | ||
|
|
d35ee91d90 | ||
|
|
545069aa88 | ||
|
|
9dfe38a483 | ||
|
|
364db59d17 | ||
|
|
06777702fa | ||
|
|
8df7edcb75 | ||
|
|
9f80ba11f1 | ||
|
|
b064f2df8f | ||
|
|
dc3b77f82b | ||
|
|
d980c01c81 | ||
|
|
1ce95f64e9 | ||
|
|
95acfc139d | ||
|
|
8ccddc1ae0 | ||
|
|
de75cb4666 | ||
|
|
e1408fe35d | ||
|
|
a93c3ccda7 | ||
|
|
7685df564d | ||
|
|
57a80d6b54 | ||
|
|
3c90498e4d | ||
|
|
4f10930f24 | ||
|
|
dde5096d1c | ||
|
|
a411d646ae | ||
|
|
6688a53acc | ||
|
|
d47658ed59 | ||
|
|
a8fe3e57f1 | ||
|
|
d4ff9d2567 | ||
|
|
8e453d3877 | ||
|
|
b7ee5a54da | ||
|
|
12833f9270 | ||
|
|
f0247428a0 | ||
|
|
f35b715f4e | ||
|
|
574de5ccbf | ||
|
|
0333f24a60 | ||
|
|
5d9821a642 | ||
|
|
b830f53069 | ||
|
|
eaf89d3f12 | ||
|
|
653b1d23c2 | ||
|
|
c2ddd67021 | ||
|
|
835620fd67 | ||
|
|
3b41fef253 | ||
|
|
07b29c8d31 | ||
|
|
ddbccecda2 | ||
|
|
defaf76144 | ||
|
|
d5882e2d66 | ||
|
|
318000009f | ||
|
|
fe7127a83c | ||
|
|
c5ab69ba82 | ||
|
|
88926aaee7 | ||
|
|
928f05ec8e | ||
|
|
b5347e2732 | ||
|
|
f926127687 | ||
|
|
17e077d531 | ||
|
|
87c320a1aa | ||
|
|
e732011f1e | ||
|
|
c439d8d88f | ||
|
|
c231a00db3 | ||
|
|
344458cc6f | ||
|
|
824cedca2f | ||
|
|
10db972ef4 | ||
|
|
a48d71ddd8 | ||
|
|
cf6e797510 | ||
|
|
c015c8a162 | ||
|
|
3ef1add585 | ||
|
|
3bac45032d | ||
|
|
b1fb8e8f10 | ||
|
|
fdf941b968 | ||
|
|
34c536c2d8 | ||
|
|
ef9d7cf7f8 | ||
|
|
27c8c3c24f | ||
|
|
b2187f4c61 | ||
|
|
1c3d1b745e | ||
|
|
2697b92981 | ||
|
|
5502f07721 | ||
|
|
4fda63dedd | ||
|
|
7779edb063 | ||
|
|
f4230e02b9 | ||
|
|
dcb4dd2f5e | ||
|
|
6c9bec4a99 | ||
|
|
6518999ac5 | ||
|
|
01223c466e | ||
|
|
95da84ff16 | ||
|
|
bdb1911e74 | ||
|
|
3213d0ca28 | ||
|
|
d34333ca38 | ||
|
|
2163f06de9 | ||
|
|
eae2e0587c | ||
|
|
fe1c2f0250 | ||
|
|
e6b8be6821 | ||
|
|
bd13042fe4 | ||
|
|
1045d38f47 | ||
|
|
9a9eb91a2d | ||
|
|
2135349038 | ||
|
|
b4aca7277b | ||
|
|
e0ee41c270 | ||
|
|
e10c5fe2c4 | ||
|
|
06be15b0ef | ||
|
|
174f47f8c2 | ||
|
|
006589ca76 | ||
|
|
abcbca3745 | ||
|
|
c368d89295 | ||
|
|
ca4cbea0f0 | ||
|
|
13f974d652 | ||
|
|
75c65b1d5e | ||
|
|
c02388750c | ||
|
|
e400890eee | ||
|
|
969c3bbdd5 | ||
|
|
670f9d73f3 | ||
|
|
fc124e71ed | ||
|
|
a409dc3f20 | ||
|
|
c9b9ad250e | ||
|
|
74a6ae5108 | ||
|
|
6b6a383159 | ||
|
|
410c953933 | ||
|
|
5df9169705 | ||
|
|
fadc06aa27 | ||
|
|
a106033b87 | ||
|
|
d99198ea12 | ||
|
|
79d68c812c | ||
|
|
37ae32be59 | ||
|
|
6f7788497a | ||
|
|
4b7aa8da75 | ||
|
|
2be27299a5 | ||
|
|
fadbca5969 | ||
|
|
f570e47e27 | ||
|
|
e3ec6c80d0 | ||
|
|
ecc89e864c | ||
|
|
a3bdb0fe09 | ||
|
|
5d8cb55b94 | ||
|
|
d10fca6c0f | ||
|
|
62ed702e64 | ||
|
|
8a5424c5a4 | ||
|
|
0e696e0175 | ||
|
|
b8709f6391 | ||
|
|
20a4078f60 | ||
|
|
ce3468e2ab | ||
|
|
b3a4182a52 | ||
|
|
7d18b2483f | ||
|
|
9bfd1bbf0e | ||
|
|
feaf4dced5 | ||
|
|
5c195f1148 | ||
|
|
70ccf89756 | ||
|
|
62a3d56bed | ||
|
|
14a322a128 | ||
|
|
160407dde6 | ||
|
|
c024fa1e5d | ||
|
|
57a1965a6d | ||
|
|
ec94376e1f | ||
|
|
9166bebef7 | ||
|
|
c9672b4d85 | ||
|
|
7a867ec8f4 | ||
|
|
ad67903b2d | ||
|
|
8b470d6817 | ||
|
|
6ab1f8a6a4 | ||
|
|
984719ce28 | ||
|
|
f75d2566dd | ||
|
|
3f1910f610 | ||
|
|
b535e87023 | ||
|
|
dd0830d349 | ||
|
|
b4a59330c5 | ||
|
|
314c555d87 | ||
|
|
bc75c9a2c7 | ||
|
|
a755d442bc | ||
|
|
824812ea9e | ||
|
|
24e38870a9 | ||
|
|
0878910043 | ||
|
|
ce18412405 | ||
|
|
4f6c978043 | ||
|
|
9093553ff1 | ||
|
|
acb2c682f3 | ||
|
|
3987871a6a | ||
|
|
9000cb28cd | ||
|
|
337f85c3cc | ||
|
|
9e521722f1 | ||
|
|
2b7c5e17b6 | ||
|
|
21bc6078d7 | ||
|
|
6c966a8c38 | ||
|
|
774be0ceed | ||
|
|
2356a49fcd | ||
|
|
efbc734d61 | ||
|
|
f5034ca0bc | ||
|
|
a1d95ebd40 | ||
|
|
943623e0fb | ||
|
|
a23eda1162 | ||
|
|
3d13202779 | ||
|
|
9f263c8c02 | ||
|
|
e8d1dadfa7 | ||
|
|
7a3cbb50cc | ||
|
|
eb49e8d7f1 | ||
|
|
65cd0a1c4f | ||
|
|
0007b55c03 | ||
|
|
93e0a2b123 | ||
|
|
1a8f025a04 | ||
|
|
f0358bec07 | ||
|
|
4f6916d8b3 | ||
|
|
fee79e8623 | ||
|
|
475b865000 | ||
|
|
304ce2e128 | ||
|
|
0bc6beb0f1 | ||
|
|
68173a8b75 | ||
|
|
7583d0ee47 | ||
|
|
6c79fe3588 | ||
|
|
c0a8a76105 | ||
|
|
6ad214bb09 | ||
|
|
b4598668d4 | ||
|
|
01e679eab6 | ||
|
|
f57bd107b9 | ||
|
|
aa5d193e55 | ||
|
|
da5bc7ab11 | ||
|
|
b0857054eb | ||
|
|
f721bf6609 | ||
|
|
2aecd63850 | ||
|
|
f35520029f | ||
|
|
95994fcd3a | ||
|
|
999f12e958 | ||
|
|
260afac294 | ||
|
|
678a958351 | ||
|
|
608fc96c4e | ||
|
|
577478ba7e | ||
|
|
23ccac4836 | ||
|
|
f6472ea9bd | ||
|
|
f3f4491f04 | ||
|
|
c987e4d54e | ||
|
|
cc7f2bc634 | ||
|
|
189a30a611 | ||
|
|
710c03f463 | ||
|
|
a875f35f1a | ||
|
|
e2cf9afbf9 | ||
|
|
a1131cf6cd | ||
|
|
3f493ac716 | ||
|
|
e64ef7f95c | ||
|
|
c118b5b8dd | ||
|
|
6535ec6932 | ||
|
|
fba5d09c75 | ||
|
|
b88d29967d | ||
|
|
1b87d20a27 | ||
|
|
7bd3158b05 | ||
|
|
7a4fa1e5bf | ||
|
|
f7d9199500 | ||
|
|
01cd5d1428 | ||
|
|
5178408f39 | ||
|
|
0b51db5434 | ||
|
|
9c47fa38ae | ||
|
|
5c4d7e1be3 | ||
|
|
acbbac8266 | ||
|
|
fa8f36f3d5 | ||
|
|
fcc856e798 | ||
|
|
44116edca5 | ||
|
|
37be31859f | ||
|
|
10667f17b4 | ||
|
|
0ca0c7cf43 | ||
|
|
a0038ac871 | ||
|
|
49824e9eab | ||
|
|
01eeb18638 | ||
|
|
3702443ece | ||
|
|
87ba75ff41 | ||
|
|
f9406fb469 | ||
|
|
690792fd62 | ||
|
|
f6ac112329 | ||
|
|
ec68cec0ca | ||
|
|
e2270602a3 | ||
|
|
8b1e5b2ee7 | ||
|
|
44a029057a | ||
|
|
249d1c1b4a | ||
|
|
6748b15024 | ||
|
|
8b26d07865 | ||
|
|
55d96a5e8f | ||
|
|
133a5197aa | ||
|
|
c0fa1576f3 | ||
|
|
48fbcde6ae | ||
|
|
89f50f774f | ||
|
|
1d9b8f3747 | ||
|
|
0a5359df72 | ||
|
|
2e9a643a8c | ||
|
|
39d0b60024 | ||
|
|
c7a6bf051c | ||
|
|
ea4a2c1ff0 | ||
|
|
71b7c9eb64 | ||
|
|
0cac3022f5 | ||
|
|
8b16a21d48 | ||
|
|
2085ebe189 | ||
|
|
01c657d247 | ||
|
|
1f26fb26d7 | ||
|
|
dbd8e2be8e | ||
|
|
6b5f00add0 | ||
|
|
1f5eef2fb1 | ||
|
|
1e6e57ddcd | ||
|
|
e18853ba3a | ||
|
|
140cd66c9b | ||
|
|
5684857456 | ||
|
|
24fee7a743 | ||
|
|
cef99b7278 | ||
|
|
aad5bcd97e | ||
|
|
423aaa6b84 | ||
|
|
97a1226eaf | ||
|
|
72cab5905e | ||
|
|
088b745600 | ||
|
|
8801d5a435 | ||
|
|
b63a3d95f3 | ||
|
|
eca8327420 | ||
|
|
05cf380e86 | ||
|
|
73f005d645 | ||
|
|
f2fa9c39a9 | ||
|
|
783ff65fb5 | ||
|
|
3e7ea3bc03 | ||
|
|
398029eecd | ||
|
|
a55cb84a69 | ||
|
|
94d54f65bf | ||
|
|
8123c5dd33 | ||
|
|
ac1ee702ae | ||
|
|
e657152e3f | ||
|
|
f667ff9e9b | ||
|
|
3c613f4938 | ||
|
|
04843a90fe | ||
|
|
834d585ac7 | ||
|
|
343fa7ca9f | ||
|
|
e049f34a5e | ||
|
|
d692f60291 | ||
|
|
a0367be686 | ||
|
|
aa6b15aa1b | ||
|
|
08342c3873 | ||
|
|
6527a33e38 | ||
|
|
43f125e45d | ||
|
|
49cc1e26c0 | ||
|
|
809a82f31d | ||
|
|
3c8c68ce2f | ||
|
|
18603026a3 | ||
|
|
52d13cbdc2 | ||
|
|
26c04f1c24 | ||
|
|
e11e402c80 | ||
|
|
bcc7d58ddd | ||
|
|
685c6ad771 | ||
|
|
4b0372aa56 | ||
|
|
27aa28740e | ||
|
|
6291b7d0a7 | ||
|
|
d9f0d89450 | ||
|
|
6ad221fcb5 | ||
|
|
f1c55e127c | ||
|
|
2f6e551e22 | ||
|
|
6edffd0306 | ||
|
|
50de668d01 | ||
|
|
8a05d85344 | ||
|
|
915ce6f5f1 | ||
|
|
67f98b13ad | ||
|
|
2a147c1d3a | ||
|
|
aae9aa6073 | ||
|
|
9a9885066f | ||
|
|
760d3349c2 | ||
|
|
ec0dd70a4b | ||
|
|
4b2184955a | ||
|
|
8d214ff6a3 | ||
|
|
441df9cdf2 | ||
|
|
e6e2789a82 | ||
|
|
70ceb50acd | ||
|
|
46d5c2e9fc | ||
|
|
725d2b2987 | ||
|
|
9581b793b5 | ||
|
|
3fc3f1191c | ||
|
|
098c79bc99 | ||
|
|
45b558373b | ||
|
|
3a2c438223 | ||
|
|
577287b8a8 | ||
|
|
1d13b054ee | ||
|
|
dc3423df13 | ||
|
|
9791454d62 | ||
|
|
17f648f3ce | ||
|
|
7d89733f96 | ||
|
|
a0e6bdfb20 | ||
|
|
ac76ce3f03 | ||
|
|
4bef51a3be | ||
|
|
781171d60a | ||
|
|
c01342a86c | ||
|
|
d73a9b2acf | ||
|
|
1d3643a1fc | ||
|
|
e50de00d08 | ||
|
|
8c87278850 | ||
|
|
520da46daf | ||
|
|
01f5e8f61d | ||
|
|
2faef2ae8d | ||
|
|
9d24d07c12 | ||
|
|
d21ce90a5c | ||
|
|
889175f3de | ||
|
|
7a70b008c8 | ||
|
|
4b251e0ea4 | ||
|
|
f242928682 | ||
|
|
d64962147a | ||
|
|
c2cd034556 | ||
|
|
1039ea8137 | ||
|
|
ead8cf80f3 | ||
|
|
1f0b2d6627 | ||
|
|
40d7ece12b | ||
|
|
098ab27a01 | ||
|
|
170b1cf5c3 | ||
|
|
004c3cc61d | ||
|
|
1b938e2748 | ||
|
|
652e84783b | ||
|
|
17c2685cae | ||
|
|
5e89507276 | ||
|
|
0204b97de8 | ||
|
|
d849951a66 | ||
|
|
1531afd046 | ||
|
|
add8a90c77 | ||
|
|
b9c3c2b5c5 | ||
|
|
1cc34c38a8 | ||
|
|
e5859f419a | ||
|
|
aadc295bdb | ||
|
|
af2ef23078 | ||
|
|
7150f03d77 | ||
|
|
a381de7c9b | ||
|
|
ce6a5cfdc4 | ||
|
|
de75468f2b | ||
|
|
011c1eddb4 | ||
|
|
c9443bad27 | ||
|
|
445aa9d071 | ||
|
|
14a2e93b3a | ||
|
|
3746b05af2 | ||
|
|
1d215d8c75 | ||
|
|
b4b1fed576 | ||
|
|
e0009ad8dc | ||
|
|
401947031b | ||
|
|
9da8e104a8 | ||
|
|
3aef2312d0 | ||
|
|
b402221477 | ||
|
|
8b6bda6dff | ||
|
|
eed8bac45a | ||
|
|
3b7bbc9bc6 | ||
|
|
9820595a70 | ||
|
|
0a33ca7f6e | ||
|
|
bba96d5159 | ||
|
|
d9fe70f442 | ||
|
|
32c5c8392b | ||
|
|
cc3f06b383 | ||
|
|
9ad90e9416 | ||
|
|
87fdda459a | ||
|
|
6c11bb8143 | ||
|
|
391fcfb9dd | ||
|
|
355c5f2d46 | ||
|
|
afdb4336f8 | ||
|
|
7a04b22b22 | ||
|
|
f594ed4902 | ||
|
|
f1afa74ee6 | ||
|
|
db3f0e0d81 | ||
|
|
aceefa16c0 | ||
|
|
89589fe3dc | ||
|
|
2afe2364e4 | ||
|
|
2c0f48877f | ||
|
|
8791038bcf | ||
|
|
aba2ba5bfa | ||
|
|
2b01834765 | ||
|
|
79c4fb511b | ||
|
|
14823dcc91 | ||
|
|
9d3494eb56 | ||
|
|
6af7c32c88 | ||
|
|
c205a52f03 | ||
|
|
a6d95f27ed | ||
|
|
f05cd66e88 | ||
|
|
a151e7a07e | ||
|
|
1f49fa4bae | ||
|
|
86d9cfe50c | ||
|
|
ae59640162 | ||
|
|
5f935cd819 | ||
|
|
90e3a946bf | ||
|
|
51c940cdd9 | ||
|
|
07ff6d25ca | ||
|
|
89fd9bbd89 | ||
|
|
c7033e61fb | ||
|
|
39f8cb1634 | ||
|
|
705c106da8 | ||
|
|
9b52bae404 | ||
|
|
9a002d18b0 | ||
|
|
3847ef4269 | ||
|
|
f0d0068a2e | ||
|
|
b89a6c634c | ||
|
|
29cfb4c792 | ||
|
|
5b590512ee | ||
|
|
3ff8ef144a | ||
|
|
d9abed1c5d | ||
|
|
82a789bbec | ||
|
|
ce6538f850 | ||
|
|
979ae7149f | ||
|
|
6e71437fe8 | ||
|
|
940ecf8714 | ||
|
|
e0cc2e0fdf | ||
|
|
5a19ef92e8 | ||
|
|
0a3781e9c2 | ||
|
|
a2e39c9d84 | ||
|
|
520abbb5c3 | ||
|
|
d0a11da15f | ||
|
|
fd5802f9a3 | ||
|
|
380d829d19 | ||
|
|
702528fb0c | ||
|
|
2c077bc755 | ||
|
|
fd86e57442 | ||
|
|
60ce18280e | ||
|
|
668dbfd78b | ||
|
|
810aa17f15 | ||
|
|
b64558e50a | ||
|
|
9b969bd708 | ||
|
|
1945f7c592 | ||
|
|
3e26d9af3c | ||
|
|
3c8d7e246b | ||
|
|
2e56518330 | ||
|
|
e67f3110e0 | ||
|
|
a67f4d2e25 | ||
|
|
d6025140fd | ||
|
|
88e9ddf29c | ||
|
|
11adc4f933 | ||
|
|
15691e8d94 | ||
|
|
754b8d0589 | ||
|
|
1d634d0da1 | ||
|
|
7136de90be | ||
|
|
466628479e | ||
|
|
9c08d0bac2 | ||
|
|
6c5320007f | ||
|
|
4734a443b4 | ||
|
|
7c38e1dc29 |
No files matched your search
@@ -1,397 +0,0 @@
|
||||
/** @type {import('dependency-cruiser').IConfiguration} */
|
||||
module.exports = {
|
||||
forbidden: [
|
||||
{
|
||||
name: "no-circular",
|
||||
severity: "warn",
|
||||
comment:
|
||||
"This dependency is part of a circular relationship. You might want to revise " +
|
||||
"your solution (i.e. use dependency inversion, make sure the modules have a single responsibility) ",
|
||||
from: {},
|
||||
to: {
|
||||
circular: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "no-orphans",
|
||||
comment:
|
||||
"This is an orphan module - it's likely not used (anymore?). Either use it or " +
|
||||
"remove it. If it's logical this module is an orphan (i.e. it's a config file), " +
|
||||
"add an exception for it in your dependency-cruiser configuration. By default " +
|
||||
"this rule does not scrutinize dot-files (e.g. .eslintrc.js), TypeScript declaration " +
|
||||
"files (.d.ts), tsconfig.json and some of the babel and webpack configs.",
|
||||
severity: "warn",
|
||||
from: {
|
||||
orphan: true,
|
||||
pathNot: [
|
||||
"(^|/)[.][^/]+[.](?:js|cjs|mjs|ts|cts|mts|json)$", // dot files
|
||||
"[.]d[.]ts$", // TypeScript declaration files
|
||||
"(^|/)tsconfig[.]json$", // TypeScript config
|
||||
"(^|/)(?:babel|webpack)[.]config[.](?:js|cjs|mjs|ts|cts|mts|json)$", // other configs
|
||||
],
|
||||
},
|
||||
to: {},
|
||||
},
|
||||
{
|
||||
name: "no-deprecated-core",
|
||||
comment:
|
||||
"A module depends on a node core module that has been deprecated. Find an alternative - these are " +
|
||||
"bound to exist - node doesn't deprecate lightly.",
|
||||
severity: "warn",
|
||||
from: {},
|
||||
to: {
|
||||
dependencyTypes: ["core"],
|
||||
path: [
|
||||
"^v8/tools/codemap$",
|
||||
"^v8/tools/consarray$",
|
||||
"^v8/tools/csvparser$",
|
||||
"^v8/tools/logreader$",
|
||||
"^v8/tools/profile_view$",
|
||||
"^v8/tools/profile$",
|
||||
"^v8/tools/SourceMap$",
|
||||
"^v8/tools/splaytree$",
|
||||
"^v8/tools/tickprocessor-driver$",
|
||||
"^v8/tools/tickprocessor$",
|
||||
"^node-inspect/lib/_inspect$",
|
||||
"^node-inspect/lib/internal/inspect_client$",
|
||||
"^node-inspect/lib/internal/inspect_repl$",
|
||||
"^async_hooks$",
|
||||
"^punycode$",
|
||||
"^domain$",
|
||||
"^constants$",
|
||||
"^sys$",
|
||||
"^_linklist$",
|
||||
"^_stream_wrap$",
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "not-to-deprecated",
|
||||
comment:
|
||||
"This module uses a (version of an) npm module that has been deprecated. Either upgrade to a later " +
|
||||
"version of that module, or find an alternative. Deprecated modules are a security risk.",
|
||||
severity: "warn",
|
||||
from: {},
|
||||
to: {
|
||||
dependencyTypes: ["deprecated"],
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "no-non-package-json",
|
||||
severity: "error",
|
||||
comment:
|
||||
"This module depends on an npm package that isn't in the 'dependencies' section of your package.json. " +
|
||||
"That's problematic as the package either (1) won't be available on live (2 - worse) will be " +
|
||||
"available on live with an non-guaranteed version. Fix it by adding the package to the dependencies " +
|
||||
"in your package.json.",
|
||||
from: {},
|
||||
to: {
|
||||
dependencyTypes: ["npm-no-pkg", "npm-unknown"],
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "not-to-unresolvable",
|
||||
comment:
|
||||
"This module depends on a module that cannot be found ('resolved to disk'). If it's an npm " +
|
||||
"module: add it to your package.json. In all other cases you likely already know what to do.",
|
||||
severity: "error",
|
||||
from: {},
|
||||
to: {
|
||||
couldNotResolve: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "no-duplicate-dep-types",
|
||||
comment:
|
||||
"Likely this module depends on an external ('npm') package that occurs more than once " +
|
||||
"in your package.json i.e. bot as a devDependencies and in dependencies. This will cause " +
|
||||
"maintenance problems later on.",
|
||||
severity: "warn",
|
||||
from: {},
|
||||
to: {
|
||||
moreThanOneDependencyType: true,
|
||||
// as it's pretty common to have a type import be a type only import
|
||||
// _and_ (e.g.) a devDependency - don't consider type-only dependency
|
||||
// types for this rule
|
||||
dependencyTypesNot: ["type-only"],
|
||||
},
|
||||
},
|
||||
|
||||
/* rules you might want to tweak for your specific situation: */
|
||||
|
||||
{
|
||||
name: "not-to-spec",
|
||||
comment:
|
||||
"This module depends on a spec (test) file. The sole responsibility of a spec file is to test code. " +
|
||||
"If there's something in a spec that's of use to other modules, it doesn't have that single " +
|
||||
"responsibility anymore. Factor it out into (e.g.) a separate utility/ helper or a mock.",
|
||||
severity: "error",
|
||||
from: {},
|
||||
to: {
|
||||
path: "[.](?:spec|test)[.](?:js|mjs|cjs|jsx|ts|mts|cts|tsx)$",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "not-to-dev-dep",
|
||||
severity: "error",
|
||||
comment:
|
||||
"This module depends on an npm package from the 'devDependencies' section of your " +
|
||||
"package.json. It looks like something that ships to production, though. To prevent problems " +
|
||||
"with npm packages that aren't there on production declare it (only!) in the 'dependencies'" +
|
||||
"section of your package.json. If this module is development only - add it to the " +
|
||||
"from.pathNot re of the not-to-dev-dep rule in the dependency-cruiser configuration",
|
||||
from: {
|
||||
path: "^(src)",
|
||||
pathNot: "[.](?:spec|test)[.](?:js|mjs|cjs|jsx|ts|mts|cts|tsx)$",
|
||||
},
|
||||
to: {
|
||||
dependencyTypes: ["npm-dev"],
|
||||
// type only dependencies are not a problem as they don't end up in the
|
||||
// production code or are ignored by the runtime.
|
||||
dependencyTypesNot: ["type-only"],
|
||||
pathNot: ["node_modules/@types/"],
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "optional-deps-used",
|
||||
severity: "info",
|
||||
comment:
|
||||
"This module depends on an npm package that is declared as an optional dependency " +
|
||||
"in your package.json. As this makes sense in limited situations only, it's flagged here. " +
|
||||
"If you're using an optional dependency here by design - add an exception to your" +
|
||||
"dependency-cruiser configuration.",
|
||||
from: {},
|
||||
to: {
|
||||
dependencyTypes: ["npm-optional"],
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "peer-deps-used",
|
||||
comment:
|
||||
"This module depends on an npm package that is declared as a peer dependency " +
|
||||
"in your package.json. This makes sense if your package is e.g. a plugin, but in " +
|
||||
"other cases - maybe not so much. If the use of a peer dependency is intentional " +
|
||||
"add an exception to your dependency-cruiser configuration.",
|
||||
severity: "warn",
|
||||
from: {},
|
||||
to: {
|
||||
dependencyTypes: ["npm-peer"],
|
||||
},
|
||||
},
|
||||
],
|
||||
options: {
|
||||
/* Which modules not to follow further when encountered */
|
||||
doNotFollow: {
|
||||
/* path: an array of regular expressions in strings to match against */
|
||||
path: ["node_modules"],
|
||||
},
|
||||
|
||||
/* Which modules to exclude */
|
||||
// exclude : {
|
||||
// /* path: an array of regular expressions in strings to match against */
|
||||
// path: '',
|
||||
// },
|
||||
|
||||
/* Which modules to exclusively include (array of regular expressions in strings)
|
||||
dependency-cruiser will skip everything not matching this pattern
|
||||
*/
|
||||
// includeOnly : [''],
|
||||
|
||||
/* List of module systems to cruise.
|
||||
When left out dependency-cruiser will fall back to the list of _all_
|
||||
module systems it knows of. It's the default because it's the safe option
|
||||
It might come at a performance penalty, though.
|
||||
moduleSystems: ['amd', 'cjs', 'es6', 'tsd']
|
||||
|
||||
As in practice only commonjs ('cjs') and ecmascript modules ('es6')
|
||||
are widely used, you can limit the moduleSystems to those.
|
||||
*/
|
||||
|
||||
// moduleSystems: ['cjs', 'es6'],
|
||||
|
||||
/*
|
||||
false: don't look at JSDoc imports (the default)
|
||||
true: dependency-cruiser will detect dependencies in JSDoc-style
|
||||
import statements. Implies "parser": "tsc", so the dependency-cruiser
|
||||
will use the typescript parser for JavaScript files.
|
||||
|
||||
For this to work the typescript compiler will need to be installed in the
|
||||
same spot as you're running dependency-cruiser from.
|
||||
*/
|
||||
// detectJSDocImports: true,
|
||||
|
||||
/* prefix for links in html and svg output (e.g. 'https://github.com/you/yourrepo/blob/main/'
|
||||
to open it on your online repo or `vscode://file/${process.cwd()}/` to
|
||||
open it in visual studio code),
|
||||
*/
|
||||
// prefix: `vscode://file/${process.cwd()}/`,
|
||||
|
||||
/* false (the default): ignore dependencies that only exist before typescript-to-javascript compilation
|
||||
true: also detect dependencies that only exist before typescript-to-javascript compilation
|
||||
"specify": for each dependency identify whether it only exists before compilation or also after
|
||||
*/
|
||||
tsPreCompilationDeps: true,
|
||||
|
||||
/* list of extensions to scan that aren't javascript or compile-to-javascript.
|
||||
Empty by default. Only put extensions in here that you want to take into
|
||||
account that are _not_ parsable.
|
||||
*/
|
||||
// extraExtensionsToScan: [".json", ".jpg", ".png", ".svg", ".webp"],
|
||||
|
||||
/* if true combines the package.jsons found from the module up to the base
|
||||
folder the cruise is initiated from. Useful for how (some) mono-repos
|
||||
manage dependencies & dependency definitions.
|
||||
*/
|
||||
// combinedDependencies: false,
|
||||
|
||||
/* if true leave symlinks untouched, otherwise use the realpath */
|
||||
// preserveSymlinks: false,
|
||||
|
||||
/* TypeScript project file ('tsconfig.json') to use for
|
||||
(1) compilation and
|
||||
(2) resolution (e.g. with the paths property)
|
||||
|
||||
The (optional) fileName attribute specifies which file to take (relative to
|
||||
dependency-cruiser's current working directory). When not provided
|
||||
defaults to './tsconfig.json'.
|
||||
*/
|
||||
tsConfig: {
|
||||
fileName: "tsconfig.json",
|
||||
},
|
||||
|
||||
/* Webpack configuration to use to get resolve options from.
|
||||
|
||||
The (optional) fileName attribute specifies which file to take (relative
|
||||
to dependency-cruiser's current working directory. When not provided defaults
|
||||
to './webpack.conf.js'.
|
||||
|
||||
The (optional) `env` and `arguments` attributes contain the parameters
|
||||
to be passed if your webpack config is a function and takes them (see
|
||||
webpack documentation for details)
|
||||
*/
|
||||
// webpackConfig: {
|
||||
// fileName: 'webpack.config.js',
|
||||
// env: {},
|
||||
// arguments: {}
|
||||
// },
|
||||
|
||||
/* Babel config ('.babelrc', '.babelrc.json', '.babelrc.json5', ...) to use
|
||||
for compilation
|
||||
*/
|
||||
// babelConfig: {
|
||||
// fileName: '.babelrc',
|
||||
// },
|
||||
|
||||
/* List of strings you have in use in addition to cjs/ es6 requires
|
||||
& imports to declare module dependencies. Use this e.g. if you've
|
||||
re-declared require, use a require-wrapper or use window.require as
|
||||
a hack.
|
||||
*/
|
||||
// exoticRequireStrings: [],
|
||||
|
||||
/* options to pass on to enhanced-resolve, the package dependency-cruiser
|
||||
uses to resolve module references to disk. The values below should be
|
||||
suitable for most situations
|
||||
|
||||
If you use webpack: you can also set these in webpack.conf.js. The set
|
||||
there will override the ones specified here.
|
||||
*/
|
||||
enhancedResolveOptions: {
|
||||
/* What to consider as an 'exports' field in package.jsons */
|
||||
exportsFields: ["exports"],
|
||||
/* List of conditions to check for in the exports field.
|
||||
Only works when the 'exportsFields' array is non-empty.
|
||||
*/
|
||||
conditionNames: ["import", "require", "node", "default", "types"],
|
||||
/* The extensions, by default are the same as the ones dependency-cruiser
|
||||
can access (run `npx depcruise --info` to see which ones that are in
|
||||
_your_ environment). If that list is larger than you need you can pass
|
||||
the extensions you actually use (e.g. [".js", ".jsx"]). This can speed
|
||||
up module resolution, which is the most expensive step.
|
||||
*/
|
||||
// extensions: [".js", ".jsx", ".ts", ".tsx", ".d.ts"],
|
||||
/* What to consider a 'main' field in package.json */
|
||||
mainFields: ["module", "main", "types", "typings"],
|
||||
/* A list of alias fields in package.jsons
|
||||
|
||||
See [this specification](https://github.com/defunctzombie/package-browser-field-spec) and
|
||||
the webpack [resolve.alias](https://webpack.js.org/configuration/resolve/#resolvealiasfields)
|
||||
documentation.
|
||||
|
||||
Defaults to an empty array (= don't use alias fields).
|
||||
*/
|
||||
// aliasFields: ["browser"],
|
||||
},
|
||||
|
||||
/* skipAnalysisNotInRules will make dependency-cruiser execute
|
||||
analysis strictly necessary for checking the rule set only.
|
||||
|
||||
See https://github.com/sverweij/dependency-cruiser/blob/main/doc/options-reference.md#skipanalysisnotinrules
|
||||
for details
|
||||
*/
|
||||
skipAnalysisNotInRules: true,
|
||||
|
||||
/* List of built-in modules to use on top of the ones node declares.
|
||||
|
||||
See https://github.com/sverweij/dependency-cruiser/blob/main/doc/options-reference.md#builtinmodules-influencing-what-to-consider-built-in--core-modules
|
||||
for details
|
||||
*/
|
||||
builtInModules: {
|
||||
add: [
|
||||
"bun",
|
||||
"bun:ffi",
|
||||
"bun:jsc",
|
||||
"bun:sqlite",
|
||||
"bun:test",
|
||||
"bun:wrap",
|
||||
"detect-libc",
|
||||
"undici",
|
||||
"ws",
|
||||
],
|
||||
},
|
||||
|
||||
reporterOptions: {
|
||||
dot: {
|
||||
/* pattern of modules that can be consolidated in the detailed
|
||||
graphical dependency graph. The default pattern in this configuration
|
||||
collapses everything in node_modules to one folder deep so you see
|
||||
the external modules, but their innards.
|
||||
*/
|
||||
collapsePattern: "node_modules/(?:@[^/]+/[^/]+|[^/]+)",
|
||||
|
||||
/* Options to tweak the appearance of your graph.See
|
||||
https://github.com/sverweij/dependency-cruiser/blob/main/doc/options-reference.md#reporteroptions
|
||||
for details and some examples. If you don't specify a theme
|
||||
dependency-cruiser falls back to a built-in one.
|
||||
*/
|
||||
// theme: {
|
||||
// graph: {
|
||||
// /* splines: "ortho" gives straight lines, but is slow on big graphs
|
||||
// splines: "true" gives bezier curves (fast, not as nice as ortho)
|
||||
// */
|
||||
// splines: "true"
|
||||
// },
|
||||
// }
|
||||
},
|
||||
archi: {
|
||||
/* pattern of modules that can be consolidated in the high level
|
||||
graphical dependency graph. If you use the high level graphical
|
||||
dependency graph reporter (`archi`) you probably want to tweak
|
||||
this collapsePattern to your situation.
|
||||
*/
|
||||
collapsePattern:
|
||||
"^(?:packages|src|lib(s?)|app(s?)|bin|test(s?)|spec(s?))/[^/]+|node_modules/(?:@[^/]+/[^/]+|[^/]+)",
|
||||
|
||||
/* Options to tweak the appearance of your graph. If you don't specify a
|
||||
theme for 'archi' dependency-cruiser will use the one specified in the
|
||||
dot section above and otherwise use the default one.
|
||||
*/
|
||||
// theme: { },
|
||||
},
|
||||
text: {
|
||||
highlightFocused: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
// generated: dependency-cruiser@16.10.0 on 2025-02-16T22:32:01.621Z
|
||||
@@ -0,0 +1,3 @@
|
||||
# Optional OAuth client ID overrides (secrets live on accounts.betterseqta.org)
|
||||
# GOOGLE_OAUTH_CLIENT_ID=your-id.apps.googleusercontent.com
|
||||
# OUTLOOK_OAUTH_CLIENT_ID=your-azure-application-client-id
|
||||
@@ -1,35 +0,0 @@
|
||||
{
|
||||
"env": {
|
||||
"browser": true,
|
||||
"commonjs": true,
|
||||
"es2021": true,
|
||||
"node": true
|
||||
},
|
||||
"extends": "eslint:recommended",
|
||||
"parserOptions": {
|
||||
"ecmaVersion": "latest",
|
||||
"sourceType": "module"
|
||||
},
|
||||
"rules": {
|
||||
// allow importing ts extensions
|
||||
"sort-imports": [
|
||||
"error",
|
||||
{
|
||||
"ignoreCase": true,
|
||||
"ignoreDeclarationSort": true,
|
||||
"ignoreMemberSort": false,
|
||||
"memberSyntaxSortOrder": ["none", "all", "multiple", "single"]
|
||||
}
|
||||
],
|
||||
"import/extensions": [
|
||||
"error",
|
||||
"ignorePackages",
|
||||
{
|
||||
"js": "never",
|
||||
"ts": "never",
|
||||
"tsx": "never"
|
||||
}
|
||||
]
|
||||
},
|
||||
"plugins": ["import"]
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
* text=auto eol=lf
|
||||
@@ -1,42 +1,51 @@
|
||||
name: Bug report
|
||||
description: Report an issue with the modpack in its unmodified state. For other issues, use Discord.
|
||||
description: Something in BetterSEQTA+ is broken. For questions, ask in Discord instead.
|
||||
labels: bug
|
||||
title: "[BUG]"
|
||||
title: "[BUG] "
|
||||
type: "Bug"
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
Before reporting an issue, [please search](https://github.com/BetterSEQTA/BetterSEQTA-Plus/issues) to make sure it has not already been reported (make sure to search closed issues as well!).
|
||||
Please [search existing issues](https://github.com/BetterSEQTA/BetterSEQTA-Plus/issues?q=is%3Aissue) first, including closed ones. For general help you'll get a faster answer in [Discord](https://discord.gg/YzmbnCDkat).
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Describe the bug
|
||||
description: Describe your issue. For general issues and questions you'll get a faster answer [from our Discord.](https://discord.gg/YzmbnCDkat)
|
||||
label: What happened?
|
||||
description: What went wrong, and what did you expect to happen instead?
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Steps to reproduce
|
||||
placeholder: |
|
||||
1. Open the timetable
|
||||
2. Click a class
|
||||
3. ...
|
||||
validations:
|
||||
required: false
|
||||
|
||||
- type: input
|
||||
attributes:
|
||||
label: Extension version
|
||||
description: What version of the extension are you using?
|
||||
placeholder: Find it by opening the config menu and clicking the about icon in the top right.
|
||||
description: Shown on your browser's extensions page (`chrome://extensions` or `about:addons`).
|
||||
placeholder: "1.0.0"
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: dropdown
|
||||
attributes:
|
||||
label: Browser
|
||||
description: Which Browser are you using?
|
||||
options:
|
||||
- Chrome
|
||||
- Firefox
|
||||
- Brave
|
||||
- Safari
|
||||
- DuckDuckGO
|
||||
- Microsoft Edge
|
||||
- Other Chromium-Based Browser
|
||||
- Other Non-Chromium-Based Browser
|
||||
- Brave
|
||||
- Opera
|
||||
- Other Chromium browser
|
||||
- Firefox
|
||||
- Safari
|
||||
- Other
|
||||
validations:
|
||||
required: true
|
||||
|
||||
@@ -44,14 +53,13 @@ body:
|
||||
attributes:
|
||||
label: Confirm
|
||||
options:
|
||||
- label: This bug report is about an issue with the extension itself. I have not modified the extension nor added any unsupported plugins. If this is not the case, I know that I should post the issue to the extension's Discord support channel instead.
|
||||
- label: I'm using an unmodified build from a store or GitHub release, without third-party plugins.
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Additional context
|
||||
description: Screenshots, video or any other information. Include photos of the console if possible
|
||||
placeholder: |
|
||||
Tip: You can attach images or log files by clicking this area to highlight it and then dragging files in.
|
||||
label: Screenshots and console output
|
||||
description: Screenshots, a video, or errors from the browser console all help.
|
||||
placeholder: Drag images or log files into this box to attach them.
|
||||
validations:
|
||||
required: false
|
||||
@@ -1,4 +1,7 @@
|
||||
contact_links:
|
||||
- name: BetterSEQTA Community Support
|
||||
- name: Discord
|
||||
url: https://discord.gg/YzmbnCDkat
|
||||
about: Join our discord for community updates, discussion, and more!
|
||||
about: Questions, help and community chat.
|
||||
- name: Documentation
|
||||
url: https://docs.betterseqta.org
|
||||
about: Guides for installing, making themes and writing plugins.
|
||||
@@ -1,52 +1,42 @@
|
||||
name: Feature request
|
||||
description: Suggest a new Feature to be added or replaced in BetterSeqtaPLUS
|
||||
description: Suggest something new for BetterSEQTA+ or a change to an existing feature.
|
||||
labels: enhancement
|
||||
title: "[FR]"
|
||||
|
||||
title: "[FR] "
|
||||
body:
|
||||
- type: checkboxes
|
||||
attributes:
|
||||
label: Confirm
|
||||
options:
|
||||
- label: "Is this feature request related to a Bug report?"
|
||||
required: false
|
||||
|
||||
- type: input
|
||||
attributes:
|
||||
label: Bug report link
|
||||
description: "If this feature request is related to a bug report, please insert the link to the bug report here"
|
||||
placeholder: "https://github.com/BetterSEQTA/BetterSEQTA-Plus/issues/..."
|
||||
validations:
|
||||
required: false
|
||||
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
## Feature details
|
||||
Before you request a feature, [please search](https://github.com/BetterSEQTA/BetterSEQTA-Plus/issues) if it has already been requested. (Make sure to check closed issues as well!)
|
||||
Please [search existing issues](https://github.com/BetterSEQTA/BetterSEQTA-Plus/issues?q=is%3Aissue) first, including closed ones, in case it's already been suggested.
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: What would you like?
|
||||
description: Describe the feature in as much detail as you can, and the problem it solves.
|
||||
placeholder: It would be great if...
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: dropdown
|
||||
attributes:
|
||||
label: Feature type
|
||||
multiple: false
|
||||
label: Type
|
||||
options:
|
||||
- Graphical
|
||||
- Functional
|
||||
- Not Sure
|
||||
- Visual / design
|
||||
- Functionality
|
||||
- Not sure
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: input
|
||||
attributes:
|
||||
label: Feature Details
|
||||
description: Please write, with as much detail as possible, what you would like to see from this feature.
|
||||
placeholder: it would be cool if
|
||||
label: Related bug report
|
||||
description: If this comes from a bug report, link it here.
|
||||
placeholder: https://github.com/BetterSEQTA/BetterSEQTA-Plus/issues/...
|
||||
validations:
|
||||
required: false
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Additional details
|
||||
description: Anything else that would help describe your vision (reference images, descriptions, etc)
|
||||
label: Anything else
|
||||
description: Mockups, reference images, or examples from other apps.
|
||||
validations:
|
||||
required: false
|
||||
@@ -1,114 +1,64 @@
|
||||
name: 🙋 New Contributor - Need Help Getting Started
|
||||
description: Perfect for first-time contributors who need guidance
|
||||
labels: ["help wanted", "documentation"]
|
||||
name: New contributor
|
||||
description: First time contributing? Tell us what you'd like to work on and we'll help you get started.
|
||||
labels: ["help wanted"]
|
||||
title: "[NEW CONTRIBUTOR] "
|
||||
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
## Hi there! 👋
|
||||
Welcome to BetterSEQTA+! We're excited to have you join our community.
|
||||
Welcome to BetterSEQTA+! Fill in what you can and a maintainer will point you in the right direction. For real-time help, join the [Discord](https://discord.gg/YzmbnCDkat).
|
||||
|
||||
- type: checkboxes
|
||||
attributes:
|
||||
label: Tell us about yourself (check all that apply)
|
||||
label: About you
|
||||
options:
|
||||
- label: "This is my first time contributing to open source"
|
||||
required: false
|
||||
- label: "I'm new to browser extensions"
|
||||
required: false
|
||||
- label: "I'm new to TypeScript/JavaScript"
|
||||
required: false
|
||||
- label: "I have some coding experience but new to this project"
|
||||
required: false
|
||||
|
||||
- type: checkboxes
|
||||
attributes:
|
||||
label: What would you like to work on? (check all that apply)
|
||||
options:
|
||||
- label: "Fix a bug 🐛"
|
||||
required: false
|
||||
- label: "Add a new feature ✨"
|
||||
required: false
|
||||
- label: "Improve documentation 📚"
|
||||
required: false
|
||||
- label: "Create a plugin 🧩"
|
||||
required: false
|
||||
- label: "Improve the UI/design 🎨"
|
||||
required: false
|
||||
- label: "Write tests 🧪"
|
||||
required: false
|
||||
- label: "Not sure - I want to help but need guidance!"
|
||||
required: false
|
||||
- label: This is my first open source contribution
|
||||
- label: I'm new to browser extensions
|
||||
- label: I'm new to TypeScript or Svelte
|
||||
- label: I've coded before but I'm new to this project
|
||||
|
||||
- type: checkboxes
|
||||
attributes:
|
||||
label: Have you read our guides?
|
||||
label: What would you like to work on?
|
||||
options:
|
||||
- label: "Getting Started Guide (see docs/GETTING_STARTED_CONTRIBUTING.md)"
|
||||
required: true
|
||||
- label: "Architecture Guide (see docs/ARCHITECTURE.md)"
|
||||
required: true
|
||||
- label: "Plugin Development Guide (see docs/plugins/README.md)"
|
||||
- label: Fixing a bug
|
||||
- label: A new feature
|
||||
- label: A plugin
|
||||
- label: UI and design
|
||||
- label: Tests
|
||||
- label: Documentation
|
||||
- label: Not sure yet, I'd like suggestions
|
||||
|
||||
- type: checkboxes
|
||||
attributes:
|
||||
label: Have you read the guides?
|
||||
options:
|
||||
- label: "[CONTRIBUTING.md](https://github.com/BetterSEQTA/BetterSEQTA-Plus/blob/main/CONTRIBUTING.md)"
|
||||
required: true
|
||||
- label: "The [architecture guide](https://docs.betterseqta.org/architecture/)"
|
||||
- label: "The [plugin development guide](https://docs.betterseqta.org/plugin-development/), if you're writing a plugin"
|
||||
|
||||
- type: checkboxes
|
||||
- type: dropdown
|
||||
attributes:
|
||||
label: Have you set up the development environment yet?
|
||||
label: Is your dev environment working?
|
||||
options:
|
||||
- label: Yes, everything works! 🎉
|
||||
required: false
|
||||
- label: Partially - I can run `npm run dev` but having some issues
|
||||
required: false
|
||||
- label: No, I need help with setup
|
||||
required: false
|
||||
- label: I tried but ran into errors (please describe below)
|
||||
required: false
|
||||
- Yes, `npm run dev` works
|
||||
- Partly, I'm running into issues
|
||||
- Not set up yet
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: input
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Errors
|
||||
description: "Please list any encountered errors here:"
|
||||
placeholder: "I am encountering issues with..."
|
||||
description: Paste any errors you've hit.
|
||||
render: shell
|
||||
validations:
|
||||
required: false
|
||||
|
||||
- type: input
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Questions or Issues
|
||||
description: "Tell us:
|
||||
1. What specifically would you like help with?
|
||||
2. Are you stuck on anything?
|
||||
3. Do you have any questions about the codebase?
|
||||
4. Is there anything in our documentation that's unclear?"
|
||||
placeholder: "I want help with..."
|
||||
label: Questions
|
||||
description: What would you like help with? Is anything in the docs unclear?
|
||||
validations:
|
||||
required: false
|
||||
|
||||
- type: input
|
||||
attributes:
|
||||
label: Ideas or Suggestions
|
||||
description: "If you have any ideas for features, improvements, or just want to share your thoughts:"
|
||||
placeholder: "It would be cool if I could help add..."
|
||||
validations:
|
||||
required: false
|
||||
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
## What happens next?
|
||||
|
||||
A maintainer will respond within 24-48 hours to:
|
||||
- Answer your questions
|
||||
- Suggest some good issues to work on
|
||||
- Help you with setup if needed
|
||||
- Point you to relevant documentation
|
||||
|
||||
Don't worry if you're new to this - we're here to help! Every expert was once a beginner. 🚀
|
||||
|
||||
**Join our [Discord server](https://discord.gg/YzmbnCDkat) for real-time help and community chat!**
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,14 +1,17 @@
|
||||
## Description
|
||||
## What does this change?
|
||||
|
||||
Please include a summary of the change and which issue is fixed. Please also include relevant motivation and context. List any dependencies that are required for this change.
|
||||
<!-- A short summary, and why it's needed. -->
|
||||
|
||||
Fixes # (issue)
|
||||
Fixes #
|
||||
|
||||
## Type of change
|
||||
|
||||
Please delete options that are not relevant.
|
||||
- [ ] Bug fix
|
||||
- [ ] New feature
|
||||
- [ ] Breaking change
|
||||
- [ ] Docs or tooling only
|
||||
|
||||
- [ ] Bug fix (non-breaking change which fixes an issue)
|
||||
- [ ] New feature (non-breaking change which adds functionality)
|
||||
- [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected)
|
||||
- [ ] This change requires a documentation update
|
||||
## Checklist
|
||||
|
||||
- [ ] `npm run lint`, `npm test` and `npm run build` pass
|
||||
- [ ] Tested on a SEQTA page
|
||||
@@ -0,0 +1,59 @@
|
||||
name: Build Extension
|
||||
description: Install dependencies, build Chrome and Firefox extensions, and package zips.
|
||||
|
||||
inputs:
|
||||
gh_release_update_check:
|
||||
description: Enable GitHub release update checker in the built extension.
|
||||
required: false
|
||||
default: "false"
|
||||
update_channel:
|
||||
description: Update channel baked into the build (stable or nightly).
|
||||
required: false
|
||||
default: stable
|
||||
build_label:
|
||||
description: Optional build label for nightly display (e.g. UTC build date).
|
||||
required: false
|
||||
default: ""
|
||||
release_repo:
|
||||
description: GitHub repo slug for the update checker (owner/name).
|
||||
required: false
|
||||
default: BetterSEQTA/BetterSEQTA-Plus
|
||||
|
||||
outputs:
|
||||
version:
|
||||
description: Version from package.json
|
||||
value: ${{ steps.version.outputs.version }}
|
||||
chrome_zip:
|
||||
description: Path to the Chrome extension zip
|
||||
value: ${{ steps.zip.outputs.chrome_zip }}
|
||||
firefox_zip:
|
||||
description: Path to the Firefox extension zip
|
||||
value: ${{ steps.zip.outputs.firefox_zip }}
|
||||
|
||||
runs:
|
||||
using: composite
|
||||
steps:
|
||||
- name: Setup Node and dependencies
|
||||
uses: ./.github/actions/setup-node-deps
|
||||
|
||||
- name: Read version
|
||||
id: version
|
||||
shell: bash
|
||||
run: echo "version=$(node -p "require('./package.json').version")" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Build extension
|
||||
shell: bash
|
||||
env:
|
||||
GH_RELEASE_UPDATE_CHECK: ${{ inputs.gh_release_update_check }}
|
||||
UPDATE_CHANNEL: ${{ inputs.update_channel }}
|
||||
GH_RELEASE_REPO: ${{ inputs.release_repo }}
|
||||
BUILD_LABEL: ${{ inputs.build_label }}
|
||||
run: npm run build
|
||||
|
||||
- name: Package zips
|
||||
id: zip
|
||||
shell: bash
|
||||
env:
|
||||
UPDATE_CHANNEL: ${{ inputs.update_channel }}
|
||||
BUILD_LABEL: ${{ inputs.build_label }}
|
||||
run: node scripts/package-extension-zips.mjs "${{ steps.version.outputs.version }}"
|
||||
@@ -0,0 +1,17 @@
|
||||
name: Run lint
|
||||
description: Run oxlint, the format check and the type check.
|
||||
|
||||
runs:
|
||||
using: composite
|
||||
steps:
|
||||
- name: Lint
|
||||
shell: bash
|
||||
run: npm run lint
|
||||
|
||||
- name: Format check
|
||||
shell: bash
|
||||
run: npm run format:check
|
||||
|
||||
- name: Type check
|
||||
shell: bash
|
||||
run: npm run typecheck
|
||||
@@ -0,0 +1,9 @@
|
||||
name: Run smoke tests
|
||||
description: Verify built extension dist output.
|
||||
|
||||
runs:
|
||||
using: composite
|
||||
steps:
|
||||
- name: Smoke tests
|
||||
shell: bash
|
||||
run: npm run test:smoke
|
||||
@@ -0,0 +1,9 @@
|
||||
name: Run unit tests
|
||||
description: Run Jest unit tests.
|
||||
|
||||
runs:
|
||||
using: composite
|
||||
steps:
|
||||
- name: Unit tests
|
||||
shell: bash
|
||||
run: npm run test:unit
|
||||
@@ -0,0 +1,15 @@
|
||||
name: Setup Node and dependencies
|
||||
description: Install Node.js 26.x and npm dependencies.
|
||||
|
||||
runs:
|
||||
using: composite
|
||||
steps:
|
||||
- name: Use Node.js 26.x
|
||||
uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version: 26.x
|
||||
cache: npm
|
||||
|
||||
- name: Install dependencies
|
||||
shell: bash
|
||||
run: npm ci
|
||||
@@ -0,0 +1 @@
|
||||
Experimental nightly build from `main`. May break. **Do not upload to Chrome Web Store or Firefox Add-ons.** Download, replace your sideloaded copy, and reload the extension.
|
||||
@@ -1,38 +0,0 @@
|
||||
name: NodeJS Build
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: ["main"]
|
||||
pull_request:
|
||||
branches: ["main"]
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
strategy:
|
||||
matrix:
|
||||
node-version: [20.x]
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Use Node.js ${{ matrix.node-version }}
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: ${{ matrix.node-version }}
|
||||
|
||||
- name: Build
|
||||
run: |
|
||||
npm install --legacy-peer-deps
|
||||
npm run build
|
||||
|
||||
- name: Zip dist folder
|
||||
run: |
|
||||
zip -r dist.zip dist
|
||||
|
||||
- name: Upload artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: dist-zip
|
||||
path: dist.zip
|
||||
@@ -0,0 +1,57 @@
|
||||
# Rebuilds main every night and replaces the assets on the "nightly" prerelease.
|
||||
# Runs on Windows because the layerchart Svelte build fails on Linux.
|
||||
|
||||
name: Nightly Release
|
||||
|
||||
on:
|
||||
schedule:
|
||||
# Midnight in Adelaide during daylight saving (UTC+10:30).
|
||||
- cron: "30 13 * * *"
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
env:
|
||||
NIGHTLY_TAG: nightly
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
|
||||
jobs:
|
||||
nightly:
|
||||
runs-on: windows-latest
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- name: Set build date
|
||||
id: build_date
|
||||
run: echo "date=$(TZ=Australia/Adelaide date +'%Y-%m-%d')" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Build extension
|
||||
id: build
|
||||
uses: ./.github/actions/build-extension
|
||||
with:
|
||||
gh_release_update_check: "true"
|
||||
update_channel: nightly
|
||||
build_label: ${{ steps.build_date.outputs.date }}
|
||||
release_repo: ${{ github.repository }}
|
||||
|
||||
- name: Ensure nightly release exists
|
||||
run: |
|
||||
TITLE="Nightly (${{ steps.build_date.outputs.date }})"
|
||||
if ! gh release view "${{ env.NIGHTLY_TAG }}" 2>/dev/null; then
|
||||
gh release create "${{ env.NIGHTLY_TAG }}" \
|
||||
--prerelease \
|
||||
--title "$TITLE" \
|
||||
--notes-file .github/nightly-release-notes.md
|
||||
else
|
||||
gh release edit "${{ env.NIGHTLY_TAG }}" --title "$TITLE"
|
||||
fi
|
||||
|
||||
- name: Upload nightly assets
|
||||
run: |
|
||||
gh release upload "${{ env.NIGHTLY_TAG }}" \
|
||||
--clobber \
|
||||
"${{ steps.build.outputs.chrome_zip }}" \
|
||||
"${{ steps.build.outputs.firefox_zip }}"
|
||||
@@ -0,0 +1,76 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches: ["main"]
|
||||
push:
|
||||
branches: ["main"]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
|
||||
jobs:
|
||||
lint:
|
||||
permissions:
|
||||
contents: read
|
||||
# The layerchart Svelte build fails on Linux, so CI runs on Windows.
|
||||
runs-on: windows-latest
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- name: Setup Node and dependencies
|
||||
uses: ./.github/actions/setup-node-deps
|
||||
|
||||
- name: Run lint
|
||||
uses: ./.github/actions/run-lint
|
||||
|
||||
unit-tests:
|
||||
permissions:
|
||||
contents: read
|
||||
runs-on: windows-latest
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- name: Setup Node and dependencies
|
||||
uses: ./.github/actions/setup-node-deps
|
||||
|
||||
- name: Run unit tests
|
||||
uses: ./.github/actions/run-unit-tests
|
||||
|
||||
build-and-smoke:
|
||||
permissions:
|
||||
contents: read
|
||||
needs: [lint, unit-tests]
|
||||
runs-on: windows-latest
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- name: Build extension
|
||||
id: build
|
||||
uses: ./.github/actions/build-extension
|
||||
with:
|
||||
gh_release_update_check: "false"
|
||||
|
||||
- name: Upload extension zips
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: extension-zips
|
||||
path: |
|
||||
${{ steps.build.outputs.chrome_zip }}
|
||||
${{ steps.build.outputs.firefox_zip }}
|
||||
|
||||
- name: Run smoke tests
|
||||
uses: ./.github/actions/run-smoke-tests
|
||||
+20
-15
@@ -1,23 +1,28 @@
|
||||
# npm
|
||||
# Dependencies
|
||||
node_modules/
|
||||
package-lock.json
|
||||
bun.lockb
|
||||
pnpm-lock.yaml
|
||||
yarn.lock
|
||||
|
||||
.parcel-cache
|
||||
# Build output
|
||||
betterseqtaplus-safari/
|
||||
coverage/
|
||||
dist/
|
||||
|
||||
# Copied in by postinstall
|
||||
src/public/resources/ort/ort-wasm-simd-threaded.jsep.mjs
|
||||
src/public/resources/ort/ort-wasm-simd-threaded.jsep.wasm
|
||||
src/public/resources/pdfjs/pdf.legacy.min.mjs
|
||||
src/public/resources/pdfjs/pdf.worker.min.mjs
|
||||
|
||||
# Environment
|
||||
.env
|
||||
.env.submit
|
||||
|
||||
dependency-graph.svg
|
||||
|
||||
# Build
|
||||
extension.zip
|
||||
build/
|
||||
dist/
|
||||
betterseqtaplus-safari/
|
||||
|
||||
.million/
|
||||
# Editors and OS
|
||||
.cursor/
|
||||
.idea/
|
||||
.vscode/
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
**/.DS_Store
|
||||
# Logs
|
||||
*.log
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"$schema": "./node_modules/oxfmt/configuration_schema.json",
|
||||
"ignorePatterns": [
|
||||
"betterseqtaplus-safari/",
|
||||
"coverage/",
|
||||
"dist/",
|
||||
"package-lock.json",
|
||||
"src/public/"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
{
|
||||
"$schema": "./node_modules/oxlint/configuration_schema.json",
|
||||
"plugins": ["typescript", "unicorn", "oxc", "import"],
|
||||
"categories": {
|
||||
"correctness": "error"
|
||||
},
|
||||
"env": {
|
||||
"builtin": true,
|
||||
"browser": true,
|
||||
"node": true
|
||||
},
|
||||
"globals": {
|
||||
"__ENABLE_GH_RELEASE_UPDATE_CHECK__": "readonly",
|
||||
"__GH_RELEASE_REPO__": "readonly",
|
||||
"__UPDATE_CHANNEL__": "readonly",
|
||||
"__BUILD_LABEL__": "readonly",
|
||||
"__GOOGLE_OAUTH_CLIENT_ID__": "readonly",
|
||||
"__OUTLOOK_OAUTH_CLIENT_ID__": "readonly"
|
||||
},
|
||||
"rules": {
|
||||
"no-unused-vars": [
|
||||
"error",
|
||||
{
|
||||
"ignoreRestSiblings": true,
|
||||
"argsIgnorePattern": "^_",
|
||||
"varsIgnorePattern": "^_",
|
||||
"caughtErrors": "none"
|
||||
}
|
||||
],
|
||||
"import/default": "off"
|
||||
},
|
||||
"ignorePatterns": ["src/public/**"]
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
build
|
||||
@@ -1,5 +0,0 @@
|
||||
{
|
||||
"tabWidth": 2,
|
||||
"useTabs": false,
|
||||
"semi": true
|
||||
}
|
||||
+3
-2
@@ -59,8 +59,9 @@ representative at an online or offline event.
|
||||
## Enforcement
|
||||
|
||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
||||
reported to the community leaders responsible for enforcement at
|
||||
N/A (literally sorry guys).
|
||||
reported to the community leaders responsible for enforcement by emailing
|
||||
[betterseqta.plus@gmail.com](mailto:betterseqta.plus@gmail.com) or messaging a
|
||||
moderator in the [Discord](https://discord.gg/YzmbnCDkat).
|
||||
All complaints will be reviewed and investigated promptly and fairly.
|
||||
|
||||
All community leaders are obligated to respect the privacy and security of the
|
||||
|
||||
+54
-61
@@ -1,72 +1,65 @@
|
||||
# Contributing to BetterSEQTA+
|
||||
|
||||
Hey there! 👋 Thanks for your interest in contributing to BetterSEQTA+! We're excited to have you join our community of contributors.
|
||||
Thanks for helping out! For anything bigger than a small fix, open an issue or ask in [Discord](https://discord.gg/YzmbnCDkat) first so we can agree on the approach.
|
||||
|
||||
## 🚀 New Contributors Start Here!
|
||||
## Setup
|
||||
|
||||
**Never contributed to an open source project before?** No worries! We've made it super easy to get started:
|
||||
You need Node.js 26+, Git and a Chromium browser (Chrome, Edge or Brave).
|
||||
|
||||
- **📖 Read our [Getting Started Guide](./docs/GETTING_STARTED_CONTRIBUTING.md)** - This walks you through everything step-by-step, from setting up your development environment to making your first pull request.
|
||||
- **🏗️ Understand the codebase** with our [Architecture Guide](./docs/ARCHITECTURE.md)
|
||||
- **🔧 Having issues?** Check our [Troubleshooting Guide](./docs/TROUBLESHOOTING.md)
|
||||
|
||||
We have lots of [`good first issue`](https://github.com/BetterSEQTA/BetterSEQTA-plus/labels/good%20first%20issue) labels that are perfect for beginners!
|
||||
|
||||
## Discussion Before Contributing
|
||||
|
||||
For significant changes, please first discuss what you'd like to change via:
|
||||
- Opening an issue
|
||||
- Joining our Discord server
|
||||
- Emailing the maintainers
|
||||
|
||||
This helps ensure your contribution aligns with the project's goals and saves you time!
|
||||
|
||||
## Community
|
||||
|
||||
Join our community channels to discuss the project, get help, and connect with other contributors:
|
||||
|
||||
- **Discord Server**: [Join our Discord](https://discord.gg/YzmbnCDkat)
|
||||
- **GitHub Discussions**: For longer-form conversations
|
||||
- **GitHub Issues**: For bug reports and feature requests
|
||||
|
||||
## Creating Plugins
|
||||
|
||||
If you're interested in creating plugins for BetterSEQTA+, check out our plugin development guides:
|
||||
|
||||
- [Creating Your First Plugin](./docs/plugins/creating-plugins.md)
|
||||
- [Plugin API Reference](./docs/advanced/plugin-api.md)
|
||||
|
||||
## Pull Request Process
|
||||
|
||||
1. It is recommended to start by opening an issue to discuss the change you wish to make. This will allow us to discuss the change and ensure it is a good fit for the project.
|
||||
2. Fork the repo and create your branch from `main`.
|
||||
3. When writing your pull request, make sure to use the pull request template.
|
||||
|
||||
### Pull Request Template
|
||||
|
||||
```
|
||||
## Description
|
||||
|
||||
Please include a summary of the change and which issue is fixed. Please also include relevant motivation and context. List any dependencies that are required for this change.
|
||||
|
||||
Fixes # (issue)
|
||||
|
||||
## Type of change
|
||||
|
||||
Please delete options that are not relevant.
|
||||
|
||||
- [ ] Bug fix (non-breaking change which fixes an issue)
|
||||
- [ ] New feature (non-breaking change which adds functionality)
|
||||
- [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected)
|
||||
- [ ] This change requires a documentation update
|
||||
```bash
|
||||
git clone https://github.com/YOUR_USERNAME/BetterSEQTA-Plus
|
||||
cd BetterSEQTA-Plus
|
||||
npm install
|
||||
npm run dev
|
||||
```
|
||||
|
||||
### Issues
|
||||
Then load the extension:
|
||||
|
||||
#### Create a new issue
|
||||
1. Open `chrome://extensions` and turn on Developer mode.
|
||||
2. Click **Load unpacked** and pick the `dist/chrome` folder.
|
||||
3. Open a SEQTA Learn page.
|
||||
|
||||
If you spot a problem with the readme or code, [search if an issue already exists](https://github.com/BetterSEQTA/BetterSEQTA-Plus/issues). If a related issue doesn't exist, you can open a new issue using a relevant [issue form](https://github.com/BetterSEQTA/BetterSEQTA-Plus/issues/new).
|
||||
For Firefox, run `npm run dev:firefox` and load `dist/firefox` from `about:debugging`.
|
||||
|
||||
#### Solve an issue
|
||||
## Project layout
|
||||
|
||||
Scan through our [existing issues](https://github.com/BetterSEQTA/BetterSEQTA-Plus/issues) to find one that interests you. You can narrow down the search using `labels` as filters. As a general rule, we don’t assign issues to anyone. If you find an issue to work on, you are welcome to open a PR with a fix.
|
||||
| Path | What's in it |
|
||||
| -------------------------------------- | --------------------------------------------- |
|
||||
| `src/SEQTA.ts` | Content script entry point |
|
||||
| `src/background.ts`, `src/background/` | Service worker |
|
||||
| `src/seqta/` | Everything injected into SEQTA pages |
|
||||
| `src/interface/` | Settings popup and theme store (Svelte) |
|
||||
| `src/plugins/` | Plugin system and built-in plugins |
|
||||
| `src/css/` | Injected styles and the shared Tailwind setup |
|
||||
| `lib/`, `scripts/` | Vite plugins and build scripts |
|
||||
|
||||
The [architecture guide](https://docs.betterseqta.org/architecture/) goes into more detail.
|
||||
|
||||
## Making changes
|
||||
|
||||
1. Branch from `main`, e.g. `git checkout -b fix/timetable-colours`.
|
||||
2. Keep each PR to one change and match the style of the surrounding code.
|
||||
3. Add tests for logic changes.
|
||||
4. Before opening the PR, check everything passes:
|
||||
|
||||
```bash
|
||||
npm run format
|
||||
npm run lint
|
||||
npm run typecheck
|
||||
npm test
|
||||
npm run build
|
||||
```
|
||||
|
||||
5. Use short conventional commit messages: `feat:`, `fix:`, `chore:`, `docs:`.
|
||||
6. Open the PR and fill in the template.
|
||||
|
||||
## Issues
|
||||
|
||||
Search [existing issues](https://github.com/BetterSEQTA/BetterSEQTA-Plus/issues) before opening a new one, and use the issue forms. [`good first issue`](https://github.com/BetterSEQTA/BetterSEQTA-Plus/labels/good%20first%20issue) and [`help wanted`](https://github.com/BetterSEQTA/BetterSEQTA-Plus/labels/help%20wanted) are good places to start. Issues aren't assigned, so just open a PR when you have a fix.
|
||||
|
||||
## More docs
|
||||
|
||||
- [Plugin development](https://docs.betterseqta.org/plugin-development/) and the [Plugin API](https://docs.betterseqta.org/plugin-api/)
|
||||
- [Theme creation](https://docs.betterseqta.org/theme-creation/)
|
||||
- [Troubleshooting](https://docs.betterseqta.org/troubleshooting/)
|
||||
- [Releases and CI](docs/RELEASES.md)
|
||||
@@ -3,124 +3,61 @@
|
||||
</a>
|
||||
|
||||
<p align="center">
|
||||
A beautiful 🤩 Chrome Extension that adds additional features and gives an overall better experience for <a href="https://educationhorizons.com/solutions/seqta/">SEQTA Learn.</a> <strong>Currently looking for contributors</strong> 🔥
|
||||
A browser extension that makes <a href="https://www.tes.com/en-au/for-schools/seqta">SEQTA</a> faster, nicer to look at and easier to use.
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a target="_blank" href="https://chrome.google.com/webstore/detail/betterseqta%20/afdgaoaclhkhemfkkkonemoapeinchel"><img src="https://user-images.githubusercontent.com/95666457/149519713-159d7ef7-2c21-4034-a616-f037ff46d9a4.png" alt="ChromeDownload" width="250"></a>
|
||||
<a target="_blank" href="https://discord.gg/YzmbnCDkat"><img src="https://github.com/BetterSEQTA/BetterSEQTA-Plus/assets/108050083/23055730-b16e-44c0-9bef-221d8545af92" width="240" style="border-radius:10%;" /></a>
|
||||
<a target="_blank" href="https://chromewebstore.google.com/detail/betterseqta+/afdgaoaclhkhemfkkkonemoapeinchel"><img src="https://user-images.githubusercontent.com/95666457/149519713-159d7ef7-2c21-4034-a616-f037ff46d9a4.png" alt="Available in the Chrome Web Store" width="250"></a>
|
||||
<a target="_blank" href="https://discord.gg/YzmbnCDkat"><img src="https://github.com/BetterSEQTA/BetterSEQTA-Plus/assets/108050083/23055730-b16e-44c0-9bef-221d8545af92" alt="Join the Discord" width="240" style="border-radius:10%;" /></a>
|
||||
</p>
|
||||
|
||||
<div>
|
||||
<img src="https://img.shields.io/chrome-web-store/users/afdgaoaclhkhemfkkkonemoapeinchel" />
|
||||
<img src="https://img.shields.io/chrome-web-store/rating/afdgaoaclhkhemfkkkonemoapeinchel" />
|
||||
</div>
|
||||
|
||||
## Table of contents
|
||||
|
||||
- [Features](#features)
|
||||
- [Creating Custom Themes](#creating-custom-themes)
|
||||
- [Getting Started](#getting-started)
|
||||
- [Running Development](#running-development)
|
||||
- [Building for production](#building-for-production)
|
||||
- [Folder Structure](#folder-structure)
|
||||
- [Contributors](#contributors)
|
||||
- [Credits](#credits)
|
||||
- [Star History](#star-history)
|
||||
<p align="center">
|
||||
<img src="https://img.shields.io/chrome-web-store/users/afdgaoaclhkhemfkkkonemoapeinchel" alt="Chrome Web Store users" />
|
||||
<img src="https://img.shields.io/chrome-web-store/rating/afdgaoaclhkhemfkkkonemoapeinchel" alt="Chrome Web Store rating" />
|
||||
</p>
|
||||
|
||||
## Features
|
||||
|
||||
- Dark mode
|
||||
- Custom Background/Themes
|
||||
- Improved Styling/CSS
|
||||
- Improved look for SEQTA Learn
|
||||
- Custom Home Page including:
|
||||
- Daily Lessons
|
||||
- Shortcuts
|
||||
- Easier Access Notices
|
||||
- Assessments
|
||||
- Options to remove certain items from the side menu
|
||||
- Grades calculator
|
||||
- Fully customisable themes and an official theme store
|
||||
- Notification for next lesson (sent 5 minutes before end of the lesson)
|
||||
- Browser Support
|
||||
- Chrome, Edge, Brave, Opera and other Chromium-Based browsers are supported
|
||||
- Firefox Supported: [here](https://addons.mozilla.org/en-US/firefox/addon/betterseqta-plus/)!
|
||||
- Safari (Experimental and not recommended - only available via compilation)
|
||||
- **Themes:** dark mode, custom colours and backgrounds, a community theme store and a theme creator.
|
||||
- **Home page:** today's lessons, upcoming assessments, notices and your own shortcuts in one place.
|
||||
- **Global search:** jump to assessments, messages, courses and notices from a keyboard shortcut.
|
||||
- **Assessments:** an overview board grouped by status, averages and weightings on the assessments page, and grade analytics with trends and charts.
|
||||
- **Timetable:** extra timetable tools, editable room and teacher names, calendar sync and opt-in classmates.
|
||||
- **Messages and notifications:** custom message folders and a local archive of notifications that outlasts SEQTA's own history.
|
||||
- **BetterSEQTA Cloud:** sign in to back up your settings and use your profile picture across devices.
|
||||
- **Extras:** hide side menu items, animated backgrounds, background music and the classic kitten 404 page.
|
||||
|
||||
## Creating Custom Themes
|
||||
Works in Chrome, Edge, Brave, Opera and other Chromium browsers, and in [Firefox](https://addons.mozilla.org/en-US/firefox/addon/betterseqta-plus/). Safari support is experimental and needs a build from source.
|
||||
|
||||
If you are looking to create custom themes, I would recommend you start at the official documentation [here](https://betterseqta.gitbook.io/betterseqta-docs). You can see some premade examples along with a compilation script that can be used to allow for CSS frameworks and libraries such as SCSS to be used [here](https://github.com/BetterSEQTA/BetterSEQTA-Theme-Generator).
|
||||
## Documentation
|
||||
|
||||
Don't worry- if you get stuck feel free to ask around in the [discord](https://discord.gg/YzmbnCDkat). We're open and happy to help out! Happy creating :)
|
||||
Guides for installing, making themes and writing plugins are at **[docs.betterseqta.org](https://docs.betterseqta.org)**. If you get stuck, ask in the [Discord](https://discord.gg/YzmbnCDkat).
|
||||
|
||||
## 🚀 Want to Contribute?
|
||||
## Contributing
|
||||
|
||||
**New contributors welcome!** 🎉 We've made it easy to get started:
|
||||
Contributions are welcome. Setup takes a few minutes:
|
||||
|
||||
- **👋 New to the project?** Start with our [Getting Started Guide](./docs/GETTING_STARTED_CONTRIBUTING.md)
|
||||
- **🏗️ Want to understand the code?** Check out our [Architecture Guide](./docs/ARCHITECTURE.md)
|
||||
- **🧩 Interested in plugins?** Read our [Plugin Development Guide](./docs/plugins/README.md)
|
||||
- **🐛 Found a bug?** Open an [issue](https://github.com/BetterSEQTA/BetterSEQTA-plus/issues) or fix it yourself!
|
||||
- **💬 Need help?** Join our [Discord community](https://discord.gg/YzmbnCDkat)
|
||||
|
||||
We have lots of https://github.com/BetterSEQTA/BetterSEQTA-Plus/labels/good%20first%20issue labels perfect for beginners!
|
||||
|
||||
## Quick Development Setup
|
||||
|
||||
**1. Fork & Clone**
|
||||
```bash
|
||||
git clone https://github.com/YOUR_USERNAME/BetterSEQTA-Plus
|
||||
cd BetterSEQTA-Plus
|
||||
```
|
||||
|
||||
**2. Install & Run**
|
||||
```bash
|
||||
npm install --legacy-peer-deps
|
||||
npm install
|
||||
npm run dev
|
||||
```
|
||||
|
||||
**3. Load in Browser**
|
||||
1. Go to `chrome://extensions`
|
||||
2. Enable "Developer mode"
|
||||
3. Click "Load unpacked" → Select `dist` folder
|
||||
4. Visit a SEQTA page to see it work! 🎉
|
||||
> [!WARNING]
|
||||
> Whenever you update the extension while not in dev mode, you will need to use the reload button on the extension page.
|
||||
Then open `chrome://extensions`, turn on Developer mode, click **Load unpacked** and pick `dist/chrome`.
|
||||
|
||||
📚 **Need more details?** Check our [detailed setup guide](./docs/GETTING_STARTED_CONTRIBUTING.md#your-first-30-minutes)
|
||||
See [CONTRIBUTING.md](CONTRIBUTING.md) for the full guide.
|
||||
|
||||
### Building for Production
|
||||
|
||||
```bash
|
||||
npm run build # Build for all browsers
|
||||
npm run zip # Package for distribution (requires 7-Zip)
|
||||
```
|
||||
|
||||
## Folder Structure
|
||||
|
||||
The folder structure is as follows:
|
||||
|
||||
- The `src` folder contains source files that are compiled to the build directory.
|
||||
|
||||
- The `src/plugins` folder contains vital loaders required for BetterSEQTA+ functionality.
|
||||
|
||||
- The `src/interface` folder contains source React & Svelte files that are required for the Settings page.
|
||||
|
||||
- The `dist` folder is where the compiled code ends up, this is the folder what you need to load into chrome as an unpacked extension for development.
|
||||
|
||||
## Contributors
|
||||
|
||||
<a href="https://github.com/betterseqta/betterseqta-plus/graphs/contributors">
|
||||
<img src="https://contrib.rocks/image?repo=betterseqta/betterseqta-plus" />
|
||||
<a href="https://github.com/BetterSEQTA/BetterSEQTA-Plus/graphs/contributors">
|
||||
<img src="https://contrib.rocks/image?repo=betterseqta/betterseqta-plus" alt="Contributors" />
|
||||
</a>
|
||||
|
||||
Want to contribute? [Click Here!](https://github.com/BetterSEQTA/BetterSEQTA-Plus/blob/main/CONTRIBUTING.md)
|
||||
|
||||
## Credits
|
||||
|
||||
This extension was initially developed by [Nulkem](https://github.com/Nulkem/betterseqta), was ported to manifest V3 by [MEGA-Dawg68](https://github.com/MEGA-Dawg68) and is currently under active development from lead developers [SethBurkart123](https://github.com/SethBurkart123) and [Crazypersonalph](https://github.com/Crazypersonalph) with help from other volunteers.
|
||||
Originally developed by [Nulkem](https://github.com/Nulkem/betterseqta).
|
||||
Ported to Manifest V3 by [MEGA-Dawg68](https://github.com/MEGA-Dawg68).
|
||||
Maintained by [SethBurkart123](https://github.com/SethBurkart123), [Crazypersonalph](https://github.com/Crazypersonalph) and the rest of the BetterSEQTA team.
|
||||
|
||||
## Star History
|
||||
## Star history
|
||||
|
||||
[](https://star-history.com/#BetterSEQTA/BetterSEQTA-Plus&Date)
|
||||
+5
-12
@@ -1,16 +1,9 @@
|
||||
# Security Policy
|
||||
# Security policy
|
||||
|
||||
## Supported Versions
|
||||
## Supported versions
|
||||
|
||||
Below here is the supported versions of BetterSEQTA+. Anything older than this is not supported and contains bugs.
|
||||
Only the latest release gets security fixes. Store installs update automatically. If you sideload from GitHub, grab the newest [release](https://github.com/BetterSEQTA/BetterSEQTA-Plus/releases).
|
||||
|
||||
| Version | Supported |
|
||||
| ------- | --------- |
|
||||
| 3.4.3 | ✅ |
|
||||
| < 3.4.3 | :x: |
|
||||
## Reporting a vulnerability
|
||||
|
||||
`*` May not work on other devices.
|
||||
|
||||
## Reporting a Vulnerability
|
||||
|
||||
If you find vulnerabilities, REPORT IT IMMEDIATELY. open the [advisories tab](https://github.com/BetterSEQTA/BetterSEQTA-Plus/security/advisories) on the left and click the green "report a vulnerability" button or use [this quick-link](https://github.com/BetterSEQTA/BetterSEQTA-Plus/security/advisories/new) to create a new report
|
||||
Please report vulnerabilities privately through [GitHub Security Advisories](https://github.com/BetterSEQTA/BetterSEQTA-Plus/security/advisories/new), not in a public issue.
|
||||
@@ -1,235 +0,0 @@
|
||||
# BetterSEQTA+ Architecture
|
||||
|
||||
Hey there! 👋 New to the codebase and feeling a bit lost? Don't worry - this guide will help you understand how everything fits together!
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- [Overview](#overview)
|
||||
- [High-Level Architecture](#high-level-architecture)
|
||||
- [Core Components](#core-components)
|
||||
- [Plugin System](#plugin-system)
|
||||
- [File Structure Explained](#file-structure-explained)
|
||||
- [Data Flow](#data-flow)
|
||||
- [Browser Extension Basics](#browser-extension-basics)
|
||||
|
||||
## Overview
|
||||
|
||||
BetterSEQTA+ is a browser extension that enhances SEQTA Learn by:
|
||||
- Adding new features through a plugin system
|
||||
- Providing customizable themes and UI improvements
|
||||
- Offering better navigation and user experience
|
||||
|
||||
Think of it like this: **SEQTA Learn + BetterSEQTA+ = Enhanced SEQTA Experience**
|
||||
|
||||
## High-Level Architecture
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ BROWSER EXTENSION │
|
||||
├─────────────────────────────────────────────────────────────┤
|
||||
│ │
|
||||
│ ┌─────────────────┐ ┌──────────────────┐ │
|
||||
│ │ Background │ │ Content Script │ │
|
||||
│ │ Script │ │ (SEQTA.ts) │ │
|
||||
│ │ │ │ │ │
|
||||
│ │ - Settings │◄───┤ - Page Detection│ │
|
||||
│ │ - Storage │ │ - Plugin Loading│ │
|
||||
│ │ - Updates │ │ - UI Injection │ │
|
||||
│ └─────────────────┘ └──────────────────┘ │
|
||||
│ │ │
|
||||
│ ┌─────────▼─────────┐ │
|
||||
│ │ Plugin System │ │
|
||||
│ │ │ │
|
||||
│ │ ┌─────────────┐ │ │
|
||||
│ │ │ Built-in │ │ │
|
||||
│ │ │ Plugins │ │ │
|
||||
│ │ │ │ │ │
|
||||
│ │ │ - Themes │ │ │
|
||||
│ │ │ - Search │ │ │
|
||||
│ │ │ - Timetable │ │ │
|
||||
│ │ │ - etc... │ │ │
|
||||
│ │ └─────────────┘ │ │
|
||||
│ └───────────────────┘ │
|
||||
│ │ │
|
||||
│ ┌─────────▼─────────┐ │
|
||||
│ │ Settings UI │ │
|
||||
│ │ (Svelte App) │ │
|
||||
│ │ │ │
|
||||
│ │ - Plugin Config │ │
|
||||
│ │ - Theme Creator │ │
|
||||
│ │ - General Settings│ │
|
||||
│ └───────────────────┘ │
|
||||
└─────────────────────────────────────────────────────────────┘
|
||||
│
|
||||
┌─────────▼─────────┐
|
||||
│ SEQTA Learn │
|
||||
│ Website │
|
||||
└───────────────────┘
|
||||
```
|
||||
|
||||
## Core Components
|
||||
|
||||
### 1. Entry Point (`src/SEQTA.ts`)
|
||||
This is where it all begins! When you visit a SEQTA page:
|
||||
1. Detects if you're on a SEQTA Learn page
|
||||
2. Injects our CSS styles
|
||||
3. Changes the favicon to BetterSEQTA+ icon
|
||||
4. Loads settings from storage
|
||||
5. Initializes the plugin system
|
||||
|
||||
### 2. Plugin System (`src/plugins/`)
|
||||
The heart of BetterSEQTA+! This is what makes it extensible:
|
||||
- **Plugin Manager**: Registers and manages all plugins
|
||||
- **Built-in Plugins**: Pre-made plugins (themes, search, etc.)
|
||||
- **Plugin API**: Provides plugins with tools to interact with SEQTA
|
||||
|
||||
### 3. Settings UI (`src/interface/`)
|
||||
A Svelte application that lets users:
|
||||
- Enable/disable plugins
|
||||
- Configure plugin settings
|
||||
- Create custom themes
|
||||
- Browse the theme store
|
||||
|
||||
### 4. Background Script (`src/background.ts`)
|
||||
Runs in the background and handles:
|
||||
- Extension-wide settings storage
|
||||
- Communication between different parts
|
||||
- Update notifications
|
||||
|
||||
## Plugin System
|
||||
|
||||
Our plugin system is what makes BetterSEQTA+ so powerful. Here's how it works:
|
||||
|
||||
### Plugin Lifecycle
|
||||
```
|
||||
Plugin Registration → Settings Loading → Plugin Initialization → Running → Cleanup
|
||||
```
|
||||
|
||||
### Built-in Plugins Overview
|
||||
|
||||
| Plugin | What it does | Files |
|
||||
|--------|-------------|-------|
|
||||
| **Themes** | Custom CSS themes and backgrounds | `src/plugins/built-in/themes/` |
|
||||
| **Global Search** | Search across all SEQTA content | `src/plugins/built-in/globalSearch/` |
|
||||
| **Timetable** | Enhanced timetable features | `src/plugins/built-in/timetable/` |
|
||||
| **Profile Picture** | Custom profile pictures | `src/plugins/built-in/profilePicture/` |
|
||||
| **Animated Background** | Moving background animations | `src/plugins/built-in/animatedBackground/` |
|
||||
|
||||
### Creating a Plugin
|
||||
Every plugin follows this structure:
|
||||
```typescript
|
||||
const myPlugin: Plugin = {
|
||||
id: "unique-plugin-id",
|
||||
name: "Human Readable Name",
|
||||
description: "What does this plugin do?",
|
||||
version: "1.0.0",
|
||||
settings: { /* user configurable options */ },
|
||||
run: async (api) => {
|
||||
// Your plugin code goes here!
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
## File Structure Explained
|
||||
|
||||
```
|
||||
src/
|
||||
├── SEQTA.ts # 🚀 Main entry point - start reading here!
|
||||
├── background.ts # 🔧 Background script for extension
|
||||
├── manifests/ # 📦 Browser extension manifests
|
||||
├── plugins/ # 🧩 Plugin system (the magic happens here!)
|
||||
│ ├── core/ # 🏗️ Plugin infrastructure
|
||||
│ ├── built-in/ # 🎁 Pre-made plugins
|
||||
│ └── index.ts # 📋 Plugin registration
|
||||
├── interface/ # 🎨 Settings UI (Svelte app)
|
||||
│ ├── pages/ # 📄 Settings pages
|
||||
│ ├── components/ # 🧱 Reusable UI components
|
||||
│ └── main.ts # 🏠 Settings app entry point
|
||||
├── seqta/ # 🔗 SEQTA-specific utilities
|
||||
│ ├── main.ts # 🎯 Core SEQTA modifications
|
||||
│ ├── ui/ # 🎨 UI manipulation helpers
|
||||
│ └── utils/ # 🛠️ Helper functions
|
||||
└── css/ # 💄 Styles and themes
|
||||
```
|
||||
|
||||
### Where to Start Reading?
|
||||
1. **New to the project?** Start with `src/SEQTA.ts`
|
||||
2. **Want to understand plugins?** Look at `src/plugins/core/types.ts`
|
||||
3. **Want to see a simple plugin?** Check out `src/plugins/built-in/profilePicture/`
|
||||
4. **Interested in the UI?** Explore `src/interface/main.ts`
|
||||
|
||||
## Data Flow
|
||||
|
||||
Here's how data flows through the system:
|
||||
|
||||
```
|
||||
User visits SEQTA → SEQTA.ts detects page → Loads settings from storage
|
||||
│
|
||||
▼
|
||||
Plugin Manager initializes → Each plugin gets API access → Plugins modify SEQTA
|
||||
│
|
||||
▼
|
||||
User opens settings → Svelte UI loads → Settings changed → Storage updated
|
||||
│
|
||||
▼
|
||||
Storage change detected → Plugins notified → UI updates automatically
|
||||
```
|
||||
|
||||
## Browser Extension Basics
|
||||
|
||||
Never worked on a browser extension before? Here's what you need to know:
|
||||
|
||||
### Content Scripts vs Background Scripts
|
||||
- **Content Script** (`SEQTA.ts`): Runs on SEQTA pages, can access and modify the page
|
||||
- **Background Script** (`background.ts`): Runs in the background, handles storage and messaging
|
||||
|
||||
### Manifest Files
|
||||
Each browser needs a slightly different manifest file:
|
||||
- `manifests/chrome.ts` - Chrome, Edge, Brave
|
||||
- `manifests/firefox.ts` - Firefox
|
||||
- `manifests/safari.ts` - Safari (experimental)
|
||||
|
||||
### Communication
|
||||
Different parts of the extension communicate using:
|
||||
- `browser.runtime.sendMessage()` - Send messages
|
||||
- `browser.storage` - Shared storage, but we have created a custom storage system that is easier to use:
|
||||
```ts
|
||||
settingsState.[the setting name] = [whatever you want to set it to]
|
||||
console.log(settingsState.[the setting name])
|
||||
```
|
||||
- Custom events for plugin communication
|
||||
|
||||
## Development Tips
|
||||
|
||||
### Debugging
|
||||
1. **Chrome DevTools**: Right-click → Inspect → Console tab
|
||||
2. **Extension Console**: `chrome://extensions` → BetterSEQTA+ → "Inspect views: background page"
|
||||
3. **Look for logs**: We log everything with `[BetterSEQTA+]` prefix
|
||||
|
||||
### Making Changes
|
||||
1. Edit code → Save → Browser auto-reloads extension → Refresh SEQTA page
|
||||
2. For UI changes: The dev server hot-reloads automatically
|
||||
3. For plugin changes: May need to disable/enable the plugin in settings
|
||||
|
||||
### Common Gotchas
|
||||
- Settings take a moment to load (use `api.settings.loaded` promise)
|
||||
- Some SEQTA elements load dynamically (use `api.seqta.onMount()`)
|
||||
- Plugin cleanup is important (always return a cleanup function)
|
||||
|
||||
## Next Steps
|
||||
|
||||
Ready to contribute? Here's what to do next:
|
||||
|
||||
1. **Read the code**: Start with `src/SEQTA.ts` and follow the flow
|
||||
2. **Try creating a simple plugin**: Follow our [plugin guide](./plugins/README.md)
|
||||
3. **Look at existing issues**: Check our [GitHub issues](https://github.com/BetterSEQTA/BetterSEQTA-plus/issues) for "good first issue" labels
|
||||
4. **Join our Discord**: Get help from the community!
|
||||
|
||||
## Questions?
|
||||
|
||||
Still confused about something? That's totally normal! Here are your options:
|
||||
- 💬 Ask in our [Discord server](https://discord.gg/YzmbnCDkat)
|
||||
- 🐛 Open an issue on GitHub
|
||||
- 📧 Email us at betterseqta.plus@gmail.com
|
||||
|
||||
Remember: **Every expert was once a beginner!** We're here to help you learn and contribute. 🚀
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,146 @@
|
||||
# BetterSEQTA Cloud — settings sync (server specification)
|
||||
|
||||
This document describes the HTTP API the BetterSEQTA+ extension expects for **cloud backup of extension settings**. The client is implemented in the extension repo; the accounts service (`accounts.betterseqta.org`) must implement these endpoints.
|
||||
|
||||
## Purpose
|
||||
|
||||
- Store **one JSON document per authenticated BetterSEQTA Cloud user** representing a snapshot of the extension’s `chrome.storage.local` data (theme, layout, plugin settings, `plugin.*` keys, etc.).
|
||||
- The extension **does not upload OAuth tokens** (`bsplus_token`, `bsplus_refresh_token`, `bsplus_client_id`, `bsplus_user`). Those remain only on the client.
|
||||
- **Download** replaces local storage with the stored snapshot, then the client reapplies the current device’s session tokens so the user stays signed in.
|
||||
|
||||
## Base URL
|
||||
|
||||
All routes below are relative to:
|
||||
|
||||
`https://accounts.betterseqta.org`
|
||||
|
||||
## Authentication
|
||||
|
||||
Every request must include:
|
||||
|
||||
```http
|
||||
Authorization: Bearer <access_token>
|
||||
```
|
||||
|
||||
Use the same **access tokens** issued by the existing BetterSEQTA+ OAuth flows (`/api/bsplus/login`, `/api/bsplus/refresh`). Resolve the user from the token; the document is scoped to that user.
|
||||
|
||||
## Endpoints
|
||||
|
||||
### `PUT /api/bsplus/settings/sync`
|
||||
|
||||
Upserts the caller’s settings backup. The server **merges** `data` into the stored JSON document; keys omitted from the patch are **not** deleted.
|
||||
|
||||
**Request body (JSON):**
|
||||
|
||||
```json
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"themeId": "uuid-string-or-empty",
|
||||
"data": {
|
||||
"DarkMode": true,
|
||||
"selectedTheme": "uuid-or-empty-string"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The extension sends a **sparse patch**: only keys that changed since the last successful upload (or, on first upload, keys that differ from schema defaults). A full snapshot is not required.
|
||||
|
||||
- **`schemaVersion`**: integer. The extension currently sends `1`. The server may reject unknown major versions or store it for future migrations.
|
||||
- **`themeId`**: optional but recommended duplicate of **`data.selectedTheme`**. Should be the UUID of the **installed** BetterSEQTA store theme (`selectedTheme`). This may be a normal theme id **or** a **flavour (slave) variant** id from themes with **`flavours[]`** — the extension uses it after restore to prefetch `theme.json` when missing locally (same **`GET …/themes/{id}/download`** as the store UI). Persist and return **`themeId`** in sync with **`data.selectedTheme`**.
|
||||
- **`data`**: object whose keys are storage keys (strings) and values are JSON-serializable values (same types as stored in `chrome.storage.local`).
|
||||
|
||||
**Success response:** HTTP `200` (or `201` if you prefer create semantics). Example:
|
||||
|
||||
```json
|
||||
{
|
||||
"updated_at": "2026-04-07T12:00:00.000Z",
|
||||
"patch": { "DarkMode": true }
|
||||
}
|
||||
```
|
||||
|
||||
`updated_at` should be an ISO 8601 timestamp of the save time. The extension displays success without requiring extra fields. Optional `patch` may echo the merged keys applied server-side.
|
||||
|
||||
**Error responses:** Standard JSON error body if applicable, e.g. `{ "error": "message" }`, with appropriate HTTP status (`401`, `413`, `422`, etc.).
|
||||
|
||||
---
|
||||
|
||||
### `GET /api/bsplus/settings/sync`
|
||||
|
||||
Returns the caller’s latest settings backup.
|
||||
|
||||
**Success response:** HTTP `200` with body:
|
||||
|
||||
```json
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"themeId": "uuid-string-or-empty",
|
||||
"data": {},
|
||||
"updated_at": "2026-04-07T12:00:00.000Z"
|
||||
}
|
||||
```
|
||||
|
||||
- **`data`**: required for restore; must be the same shape as accepted in `PUT` (flat map of storage keys).
|
||||
- **`themeId`**: optional; if present must match **`data.selectedTheme`** (see `PUT`).
|
||||
- **`schemaVersion`**: optional but recommended; should match what was stored.
|
||||
- **`updated_at`**: optional; included for UX if the client shows “last backup” time.
|
||||
|
||||
The extension resolves **`themeId`** (if non-empty), else **`data.selectedTheme`,** to [`resolveThemeIdForPostSyncDownload`](../src/seqta/utils/cloudSettingsSync.ts) after downloading the envelope — used only to reinstall theme assets from **`betterseqta.org`** when IndexedDB lacks that id (see **BetterSEQTA Cloud** flavour note in **[THEME_STORE_FLAVOURS_API](./THEME_STORE_FLAVOURS_API.md)** section “Cloud settings sync compatibility”).
|
||||
|
||||
**No backup yet:** HTTP **`404`**. The extension treats this as “nothing in the cloud” and shows an error to the user.
|
||||
|
||||
**Error responses:** `401` if the token is invalid, etc.
|
||||
|
||||
---
|
||||
|
||||
## Suggested database shape
|
||||
|
||||
Example relational layout:
|
||||
|
||||
| Column | Type | Notes |
|
||||
| ------------ | ------------ | -------------------------------------------------------------------------------------- |
|
||||
| `user_id` | FK → users | Unique per backup row (one row per user). |
|
||||
| `payload` | JSON / JSONB | Store `{ "schemaVersion", "data" }` or only `data` + separate `schema_version` column. |
|
||||
| `updated_at` | timestamptz | Set on each successful `PUT`. |
|
||||
|
||||
Unique constraint on `user_id`.
|
||||
|
||||
## Semantics
|
||||
|
||||
- **Merge on PUT:** each `PUT` deep-merges `data` into the stored backup for that user. Keys not present in the request body remain unchanged on the server.
|
||||
- **Full document on GET:** restore and poll download still receive the complete hydrated settings object.
|
||||
- **Optional later:** `If-Unmodified-Since` or a `revision` field for conflict detection (not required for v1).
|
||||
|
||||
## Security and privacy
|
||||
|
||||
- **Encryption at rest** for `payload` is recommended.
|
||||
- Payload may contain **school-related UI preferences** and plugin data; treat as **user data** under your privacy policy.
|
||||
- **Do not require or store** refresh/access tokens in the payload; the extension already strips them on upload.
|
||||
|
||||
### Never included in the sync payload (`chrome.storage.local` only)
|
||||
|
||||
The backup is a flat JSON map of **`chrome.storage.local`** keys. It does **not** include:
|
||||
|
||||
- **IndexedDB** — e.g. the Global Search index (`betterseqta-index` and related DBs) lives outside extension storage and is never serialized here.
|
||||
- **OAuth / session keys** — `bsplus_token`, `bsplus_refresh_token`, `bsplus_client_id`, `bsplus_user`, plus legacy `cloudAccessToken` / `cloudUsername`.
|
||||
- **Assessment Averages caches** — `plugin.assessments-average.storage.assessments`, `plugin.assessments-average.storage.weightings` (school assessment data).
|
||||
- **Keys under** `plugin.global-search.storage.*` — reserved so any future plugin storage cache there is not synced.
|
||||
- **Grade Analytics** — keys under `bsplus.analytics.*` (synced assessment cache and per-school chart preferences).
|
||||
- **`bsplus_cloud_settings_last_uploaded_snapshot`** — client-only normalized map last acked by PUT; used to compute sparse upload patches (not part of the cloud backup blob).
|
||||
- **`bsplus_cloud_settings_known_remote_updated_at`** — client-only watermark for auto-sync (not part of the cloud backup blob).
|
||||
|
||||
On restore, those keys are **not** taken from the server; the device keeps its current local values.
|
||||
|
||||
## Related endpoint: `GET /api/user/cloud-summary`
|
||||
|
||||
The extension may call **`GET /api/user/cloud-summary`** (same host, `Authorization: Bearer`) for a **small** JSON summary (e.g. whether DesQTA / BetterSEQTA+ cloud settings exist and **`bsplus.updated_at`** / **`schemaVersion`**). It does **not** return the large settings `data` blob.
|
||||
|
||||
- **Auto-sync flow:** compare `bsplus.updated_at` to a **client-only** watermark stored in extension storage as **`bsplus_cloud_settings_known_remote_updated_at`** (never uploaded, never applied from the server payload; preserved on restore).
|
||||
- If the server timestamp is newer (and `schemaVersion` is not ahead of the client), the client then calls **`GET /api/bsplus/settings/sync`** and applies the full envelope as usual.
|
||||
|
||||
This uses standard **WebExtension** APIs (`browser.alarms`, `runtime` messages, `storage`) and works on **Chromium and Firefox** builds.
|
||||
|
||||
## Client reference (extension)
|
||||
|
||||
- Upload (sparse patch): `buildUploadPatch` / `putSettingsOnce` in `src/background/cloudSettingsAutoSync.ts`; baseline from `bsplus_cloud_settings_last_uploaded_snapshot` or schema defaults; dev full export via `getSnapshotForUpload` / `buildUploadPayload` in `src/seqta/utils/cloudSettingsSync.ts` (strips OAuth-related keys, sensitive device keys, client-only metadata — includes **`themeId`** aligned with **`selectedTheme`**).
|
||||
- Download: resolve id via **`resolveThemeIdForPostSyncDownload`** → **`applyDownloadedEnvelope`** after `GET` → prefetch theme blobs in page context if needed (**`prepareThemeAfterCloudSync`** in **`ThemeManager`**) → reload SEQTA tabs; local auth keys, sensitive device keys, client-only watermark, and **`bsplus_pending_theme_ensure_after_cloud`** semantics preserved as documented above.
|
||||
- Auto sync (summary, debounced upload, alarms): `src/background/cloudSettingsAutoSync.ts`; content script triggers a poll on each verified SEQTA Learn/Engage page load (top frame) via `cloudSettingsPoll`.
|
||||
@@ -1,285 +0,0 @@
|
||||
# Getting Started as a Contributor
|
||||
|
||||
Welcome to BetterSEQTA+! 🎉 This guide will walk you through making your first contribution, even if you're completely new to the project.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- [Before You Start](#before-you-start)
|
||||
- [Your First 30 Minutes](#your-first-30-minutes)
|
||||
- [Making Your First Contribution](#making-your-first-contribution)
|
||||
- [Types of Contributions](#types-of-contributions)
|
||||
- [Finding Something to Work On](#finding-something-to-work-on)
|
||||
- [Development Workflow](#development-workflow)
|
||||
- [Getting Help](#getting-help)
|
||||
|
||||
## Before You Start
|
||||
|
||||
### What You'll Need
|
||||
- **Node.js** (v16 or higher) - [Download here](https://nodejs.org/)
|
||||
- **Git** - [Download here](https://git-scm.com/)
|
||||
- **A code editor** - We recommend [VS Code](https://code.visualstudio.com/)
|
||||
- **A Chromium browser** (Chrome, Edge, Brave) for testing (recommended, however you can use firefox although it requires being built every time you make a change)
|
||||
|
||||
### Helpful Background (but not required!)
|
||||
- Basic JavaScript/TypeScript knowledge
|
||||
- Some familiarity with HTML/CSS
|
||||
- Understanding of browser extensions (we'll teach you!)
|
||||
|
||||
**Don't worry if you're missing some of these!** We're happy to help you learn. 🤗
|
||||
|
||||
## Your First 30 Minutes
|
||||
|
||||
Let's get you up and running quickly:
|
||||
|
||||
### 1. Get the Code (3 minutes)
|
||||
```bash
|
||||
# Fork the repository on GitHub first, then:
|
||||
git clone https://github.com/YOUR_USERNAME/BetterSEQTA-plus.git
|
||||
cd BetterSEQTA-plus
|
||||
```
|
||||
|
||||
### 2. Install Dependencies (3 minutes)
|
||||
```bash
|
||||
npm install --legacy-peer-deps
|
||||
```
|
||||
|
||||
### 3. Start Development Server (2 minutes)
|
||||
```bash
|
||||
npm run dev
|
||||
```
|
||||
|
||||
### 4. Load Extension in Browser (4 minutes)
|
||||
1. Open Chrome and go to `chrome://extensions`
|
||||
2. Enable "Developer mode" (toggle in top right)
|
||||
3. Click "Load unpacked"
|
||||
4. Select the `dist` folder in your project
|
||||
5. Visit a SEQTA Learn page to see BetterSEQTA+ in action!
|
||||
|
||||
### 5. Make a Tiny Change (5 minutes)
|
||||
Let's prove everything works:
|
||||
1. Open `src/SEQTA.ts`
|
||||
2. Find the line that says `"[BetterSEQTA+] Successfully initialised"`
|
||||
3. Change it to `"[BetterSEQTA+] Successfully initialised - Hello [YOUR_NAME]!"`
|
||||
4. Save the file
|
||||
5. Go to `chrome://extensions`, click the refresh icon on BetterSEQTA+
|
||||
6. Refresh a SEQTA page and check the browser console (F12) - you should see your message!
|
||||
|
||||
### 6. Reset Your Change (3 minutes)
|
||||
```bash
|
||||
git checkout -- src/SEQTA.ts
|
||||
```
|
||||
|
||||
**Congratulations! 🎉 You've successfully set up BetterSEQTA+ for development!**
|
||||
|
||||
## Making Your First Contribution
|
||||
|
||||
### Easy First Contributions
|
||||
|
||||
Here are some great starter contributions:
|
||||
|
||||
1. **Fix a typo in documentation** - Super easy and always appreciated!
|
||||
2. **Improve error messages** - Make them more helpful
|
||||
3. **Add comments to code** - Help other contributors understand
|
||||
4. **Create a simple plugin** - Follow our plugin guide
|
||||
5. **Fix a bug you found** - If you found a bug, fix it!
|
||||
|
||||
### Step-by-Step: Your First Pull Request
|
||||
|
||||
#### Step 1: Pick an Issue
|
||||
- Go to our [Issues page](https://github.com/BetterSEQTA/BetterSEQTA-plus/issues)
|
||||
- Look for labels like:
|
||||
- `good first issue` - Perfect for beginners
|
||||
- `help wanted` - We'd love help with these
|
||||
- `documentation` - Improve our docs
|
||||
- `bug` - Fix something broken
|
||||
|
||||
#### Step 2: Claim the Issue
|
||||
Comment on the issue saying "I'd like to work on this!" We'll assign it to you.
|
||||
|
||||
#### Step 3: Create a Branch
|
||||
```bash
|
||||
git checkout -b fix-issue-123 # Replace 123 with the issue number
|
||||
```
|
||||
|
||||
#### Step 4: Make Your Changes
|
||||
- Follow the patterns you see in existing code
|
||||
- Test your changes thoroughly
|
||||
- Keep changes focused and small
|
||||
|
||||
#### Step 5: Test Everything
|
||||
```bash
|
||||
# Test the extension still loads
|
||||
npm run dev
|
||||
|
||||
# Test in browser
|
||||
# 1. Reload extension at chrome://extensions
|
||||
# 2. Visit SEQTA page
|
||||
# 3. Verify everything still works
|
||||
```
|
||||
|
||||
#### Step 6: Commit Your Changes
|
||||
```bash
|
||||
git add .
|
||||
git commit -m "Fix issue #123: Brief description of what you fixed"
|
||||
```
|
||||
|
||||
#### Step 7: Push and Create Pull Request
|
||||
```bash
|
||||
git push origin fix-issue-123
|
||||
```
|
||||
|
||||
Then go to GitHub and create a pull request with:
|
||||
- **Clear title**: "Fix issue #123: Brief description"
|
||||
- **Description**: Explain what you changed and why
|
||||
- **Testing**: Describe how you tested it
|
||||
|
||||
## Types of Contributions
|
||||
|
||||
### 🐛 Bug Fixes
|
||||
- Fix broken features
|
||||
- Improve error handling
|
||||
- Resolve compatibility issues
|
||||
|
||||
**Example**: "The theme selector doesn't work on Firefox"
|
||||
|
||||
### ✨ New Features
|
||||
- Add new plugins
|
||||
- Enhance existing functionality
|
||||
- Improve user experience
|
||||
|
||||
**Example**: "Add keyboard shortcuts for common actions"
|
||||
|
||||
### 📚 Documentation
|
||||
- Fix typos and unclear explanations
|
||||
- Add examples and tutorials
|
||||
- Improve code comments
|
||||
|
||||
**Example**: "Add more examples to the plugin guide"
|
||||
|
||||
### 🎨 Design & UI
|
||||
- Improve the settings interface
|
||||
- Make things more user-friendly
|
||||
- Add animations and polish
|
||||
|
||||
**Example**: "Make the theme creator more intuitive"
|
||||
|
||||
### 🔧 Technical Improvements
|
||||
- Refactor code for clarity
|
||||
- Add tests
|
||||
- Improve performance
|
||||
|
||||
**Example**: "Simplify the plugin loading logic"
|
||||
|
||||
## Finding Something to Work On
|
||||
|
||||
### Browse Issues by Label
|
||||
- [`good first issue`](https://github.com/BetterSEQTA/BetterSEQTA-plus/labels/good%20first%20issue) - Perfect for beginners
|
||||
- [`help wanted`](https://github.com/BetterSEQTA/BetterSEQTA-plus/labels/help%20wanted) - We need help with these
|
||||
- [`documentation`](https://github.com/BetterSEQTA/BetterSEQTA-plus/labels/documentation) - Improve our docs
|
||||
- [`bug`](https://github.com/BetterSEQTA/BetterSEQTA-plus/labels/bug) - Fix something broken
|
||||
- [`enhancement`](https://github.com/BetterSEQTA/BetterSEQTA-plus/labels/enhancement) - Add new features
|
||||
|
||||
### Create Your Own Issue
|
||||
Found a bug or have an idea? Create an issue first to discuss it!
|
||||
|
||||
### Plugin Ideas
|
||||
Want to create a plugin? Here are some ideas:
|
||||
- **Study Timer**: Track study time across SEQTA pages
|
||||
- **Grade Tracker**: Better visualization of grades over time
|
||||
- **Quick Notes**: Add notes to any SEQTA page
|
||||
- **Homework Reminder**: Smart notifications for upcoming due dates
|
||||
- **Custom Shortcuts**: User-defined keyboard shortcuts
|
||||
|
||||
## Development Workflow
|
||||
|
||||
### Daily Development
|
||||
```bash
|
||||
# Start working
|
||||
git pull origin main
|
||||
npm run dev
|
||||
|
||||
# Make changes, test, commit
|
||||
git add .
|
||||
git commit -m "Descriptive commit message"
|
||||
|
||||
# Push when ready
|
||||
git push origin your-branch-name
|
||||
```
|
||||
|
||||
### Before Submitting PR
|
||||
1. **Test thoroughly** - Make sure nothing breaks
|
||||
2. **Check console** - No new errors
|
||||
3. **Test in different browsers** - Chrome and Firefox
|
||||
4. **Update documentation** - If you changed how something works
|
||||
|
||||
### Code Style
|
||||
- Use TypeScript where possible
|
||||
- Follow existing naming conventions
|
||||
- Add comments for complex logic
|
||||
- Keep functions small and focused
|
||||
|
||||
## Getting Help
|
||||
|
||||
### Stuck? Here's How to Get Unstuck
|
||||
|
||||
1. **Check the docs** - [Architecture guide](./ARCHITECTURE.md) explains everything
|
||||
2. **Search existing issues** - Someone might have had the same problem
|
||||
3. **Ask in Discord** - Our community is super helpful
|
||||
4. **Create an issue** - If you found a bug or need help
|
||||
|
||||
### Discord Community
|
||||
Join our [Discord server](https://discord.gg/YzmbnCDkat) for:
|
||||
- Real-time help and discussion
|
||||
- Collaboration on features
|
||||
- Sharing ideas and feedback
|
||||
- Getting to know the community
|
||||
|
||||
### Code Review Process
|
||||
- All contributions need code review
|
||||
- We'll provide helpful feedback
|
||||
- Don't worry about making mistakes - we're here to help!
|
||||
- Reviews usually happen within 24-48 hours
|
||||
|
||||
## Common Questions
|
||||
|
||||
**Q: I'm new to browser extensions. Is this too advanced for me?**
|
||||
A: Not at all! We have lots of beginner-friendly issues, and our plugin system makes it easy to add features without understanding all the browser extension complexities.
|
||||
|
||||
**Q: How long does it take to get my first PR merged?**
|
||||
A: For simple fixes, usually 1-3 days. For larger features, it might take a week or two as we discuss the best approach.
|
||||
|
||||
**Q: I made a mistake in my PR. What do I do?**
|
||||
A: No worries! Just push more commits to the same branch and they'll be added to your PR automatically.
|
||||
|
||||
**Q: Can I work on multiple issues at once?**
|
||||
A: It's better to focus on one issue at a time, especially when starting out. This makes code review easier and reduces conflicts.
|
||||
|
||||
**Q: What if I start working on something and get stuck?**
|
||||
A: Ask for help! Create a draft PR with what you have so far, and we'll help you figure out the next steps.
|
||||
|
||||
## Recognition
|
||||
|
||||
All contributors get:
|
||||
- Recognition in our README
|
||||
- Contributor badge in Discord
|
||||
- Our eternal gratitude! 🙏
|
||||
|
||||
Significant contributors may also get:
|
||||
- Special Discord roles
|
||||
- Input on project direction
|
||||
- Maintainer status
|
||||
|
||||
## Next Steps
|
||||
|
||||
Ready to contribute? Here's what to do:
|
||||
|
||||
1. ✅ **Set up your development environment** (follow the 30-minute guide above)
|
||||
2. 🔍 **Find an issue to work on** (check the "good first issue" label)
|
||||
3. 💬 **Join our Discord** and introduce yourself
|
||||
4. 🚀 **Make your first contribution** and submit a PR
|
||||
|
||||
Remember: **Every expert was once a beginner!** We're excited to help you learn and grow as a contributor. Welcome to the team! 🎉
|
||||
|
||||
---
|
||||
|
||||
*Questions? Suggestions for improving this guide? Open an issue or message us on Discord!*
|
||||
+14
-50
@@ -1,55 +1,19 @@
|
||||
# BetterSEQTA+ Documentation
|
||||
# Docs
|
||||
|
||||
🚧 DOCS UNDER CONSTRUCTION! 🚧
|
||||
The main documentation lives at **[docs.betterseqta.org](https://docs.betterseqta.org/)**, built from [BetterSEQTA-Docs](https://github.com/BetterSEQTA/BetterSEQTA-Docs). Send fixes for those pages there.
|
||||
|
||||
Welcome to the BetterSEQTA+ documentation! This documentation will help you understand how BetterSEQTA+ works and how to extend it with plugins and new features.
|
||||
| Topic | Where |
|
||||
| --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| Installing | [docs.betterseqta.org/install](https://docs.betterseqta.org/install/) |
|
||||
| Architecture | [docs.betterseqta.org/architecture](https://docs.betterseqta.org/architecture/) |
|
||||
| Writing plugins | [Plugin development](https://docs.betterseqta.org/plugin-development/), [Plugin API](https://docs.betterseqta.org/plugin-api/), [Example plugin](https://docs.betterseqta.org/example-plugin/) |
|
||||
| Making themes | [docs.betterseqta.org/theme-creation](https://docs.betterseqta.org/theme-creation/) |
|
||||
| Troubleshooting | [docs.betterseqta.org/troubleshooting](https://docs.betterseqta.org/troubleshooting/) |
|
||||
|
||||
## Table of Contents
|
||||
These pages only live in this repo because they track the code closely:
|
||||
|
||||
### Getting Started
|
||||
- [RELEASES.md](RELEASES.md): CI, stable and nightly releases, and the update badge.
|
||||
- [CLOUD_SETTINGS_SYNC_SERVER.md](CLOUD_SETTINGS_SYNC_SERVER.md): the HTTP API the extension expects for cloud settings backup.
|
||||
- [CLOUD_SETTINGS_SYNC_OPTIONS.md](CLOUD_SETTINGS_SYNC_OPTIONS.md): every value that goes into a cloud backup and how it is stored.
|
||||
|
||||
- [Project Overview](./README.md) - This file
|
||||
- [Installation Guide](./installation.md) - How to install and set up BetterSEQTA+
|
||||
- [Getting Started Contributing](./GETTING_STARTED_CONTRIBUTING.md) - **Start here!** Complete beginner-friendly guide
|
||||
- [Architecture Guide](./ARCHITECTURE.md) - How BetterSEQTA+ works under the hood
|
||||
- [Contributing Guide](../CONTRIBUTING.md) - Official contribution guidelines
|
||||
- [Troubleshooting](./TROUBLESHOOTING.md) - Common issues and solutions
|
||||
|
||||
### Plugin System
|
||||
|
||||
- [Creating Your First Plugin](./plugins/README.md) - A comprehensive, beginner-friendly guide to creating plugins
|
||||
- [Plugin API Reference](./plugins/api-reference.md) - Detailed technical documentation of the plugin APIs
|
||||
|
||||
## Core Concepts
|
||||
|
||||
BetterSEQTA+ is built around several core concepts:
|
||||
|
||||
1. **Plugin System**: BetterSEQTA+ uses a plugin system to extend SEQTA with new features. Plugins are self-contained pieces of code that can be enabled or disabled by the user. Check out our [plugin guide](./plugins/README.md) to learn how to create your own!
|
||||
|
||||
2. **Type-Safe Settings**: Each plugin can define settings that are type-safe and automatically rendered in the settings UI. The settings system uses TypeScript decorators to make it easy to define settings with proper typing.
|
||||
|
||||
3. **Storage API**: Plugins can use the Storage API to persist data between sessions. The Storage API is also type-safe, ensuring that plugins can only access their own data.
|
||||
|
||||
4. **SEQTA Integration**: BetterSEQTA+ integrates with SEQTA Learn by injecting code into the page. This allows plugins to modify the SEQTA UI and add new features.
|
||||
|
||||
## Getting Help
|
||||
|
||||
If you need help with BetterSEQTA+, you can:
|
||||
|
||||
- [Open an Issue](https://github.com/SeqtaLearning/betterseqta-plus/issues) - Report bugs or request features
|
||||
- [Join the Discord](https://discord.gg/YzmbnCDkat) - Chat with the community
|
||||
- [Email the Maintainers](mailto:betterseqta.plus@gmail.com) - Contact the maintainers directly
|
||||
|
||||
## Contributing to the Documentation
|
||||
|
||||
We welcome contributions to the documentation! If you find something unclear or missing, please open an issue or submit a pull request.
|
||||
|
||||
To contribute to the documentation:
|
||||
|
||||
1. Fork the repository
|
||||
2. Make your changes to the documentation files
|
||||
3. Submit a pull request with a clear description of your changes
|
||||
|
||||
## License
|
||||
|
||||
BetterSEQTA+ is licensed under the [MIT License](../LICENSE).
|
||||
For contributing, see [CONTRIBUTING.md](../CONTRIBUTING.md).
|
||||
@@ -0,0 +1,58 @@
|
||||
# Releases, CI and the update badge
|
||||
|
||||
BetterSEQTA+ ships through the Chrome Web Store and Firefox Add-ons. GitHub also hosts sideload builds, and those builds can tell users when a newer one is out. This page covers how all of that is built.
|
||||
|
||||
## Workflows
|
||||
|
||||
| Workflow | Runs on | What it does |
|
||||
| ------------------------------------------------- | ---------------------------------------------------------------- | ----------------------------------------------------------------------------- |
|
||||
| [`pr-ci.yml`](../.github/workflows/pr-ci.yml) | Every pull request and push to `main` | Lint, unit tests, then build and smoke test. Uploads the zips as an artifact. |
|
||||
| [`nightly.yml`](../.github/workflows/nightly.yml) | Daily at 13:30 UTC (midnight in Adelaide during daylight saving) | Builds `main` and replaces the assets on the `nightly` prerelease. |
|
||||
|
||||
Both build through the shared [`build-extension`](../.github/actions/build-extension/action.yml) action: install with `npm ci`, run `npm run build` for Chrome and Firefox, then zip `dist/chrome` and `dist/firefox`. Nightly publishes with the default `GITHUB_TOKEN`, so it needs no extra secrets.
|
||||
|
||||
## Publishing a stable release
|
||||
|
||||
Stable releases are published by hand:
|
||||
|
||||
1. Bump `version` in `package.json` on `main` and push it.
|
||||
2. Build with the update checker, then zip:
|
||||
|
||||
```bash
|
||||
GH_RELEASE_UPDATE_CHECK=true UPDATE_CHANNEL=stable npm run build
|
||||
npm run zip
|
||||
```
|
||||
|
||||
3. Run `npm run release`. It creates the release for that version with generated notes and uploads `betterseqtaplus@{version}-chrome.zip` and `-firefox.zip`.
|
||||
|
||||
## Nightly builds
|
||||
|
||||
The `nightly` tag always points at the latest build of `main`. Each run renames the release to `Nightly (YYYY-MM-DD)` and replaces its zips (`betterseqtaplus-nightly-{date}-chrome.zip` and `-firefox.zip`). The release text comes from [`nightly-release-notes.md`](../.github/nightly-release-notes.md) when the release is first created.
|
||||
|
||||
Get it from [releases/tag/nightly](https://github.com/BetterSEQTA/BetterSEQTA-Plus/releases/tag/nightly).
|
||||
|
||||
GitHub builds are for sideloading only. Never upload them to an extension store.
|
||||
|
||||
## Build-time flags
|
||||
|
||||
Release builds pass these into Vite, which bakes them in through `define` in [`vite.config.ts`](../vite.config.ts). Their types live in [`src/env.d.ts`](../src/env.d.ts).
|
||||
|
||||
| Variable | Stable | Nightly | PRs and local builds |
|
||||
| ------------------------- | ------------------------------ | -------------- | -------------------- |
|
||||
| `GH_RELEASE_UPDATE_CHECK` | `true` | `true` | unset |
|
||||
| `UPDATE_CHANNEL` | `stable` | `nightly` | unset |
|
||||
| `GH_RELEASE_REPO` | `BetterSEQTA/BetterSEQTA-Plus` | same | same |
|
||||
| `BUILD_LABEL` | empty | UTC build date | empty |
|
||||
|
||||
Without `GH_RELEASE_UPDATE_CHECK=true`, the update checker is removed from the bundle entirely.
|
||||
|
||||
## Update badge
|
||||
|
||||
Release builds show an amber **Update — {version}** pill at the bottom of the settings sidebar when a newer build exists. Clicking it opens the releases page. The logic is in [`src/utils/githubReleaseUpdate.ts`](../src/utils/githubReleaseUpdate.ts):
|
||||
|
||||
- **Stable** compares the highest semver release tag (ignoring `nightly`) with the installed version.
|
||||
- **Nightly** compares the `nightly` release's publish time with the last one seen, stored as `lastSeenNightlyPublishedAt`. The first check after install only records it.
|
||||
|
||||
Checks run at most every 6 hours (`localStorage` key `bsplus_lastGhReleaseCheck`).
|
||||
|
||||
To test the badge without publishing, turn on dev mode (click the settings logo and type `dev`), then set **GitHub latest version override** in the Advanced section to a higher version such as `9.9.9`.
|
||||
@@ -1,348 +0,0 @@
|
||||
# Troubleshooting Guide
|
||||
|
||||
Having issues with BetterSEQTA+ development? This guide covers the most common problems and their solutions.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- [Installation Issues](#installation-issues)
|
||||
- [Development Server Issues](#development-server-issues)
|
||||
- [Browser Extension Issues](#browser-extension-issues)
|
||||
- [Plugin Development Issues](#plugin-development-issues)
|
||||
- [Build Issues](#build-issues)
|
||||
- [Still Stuck?](#still-stuck)
|
||||
|
||||
## Installation Issues
|
||||
|
||||
### ❌ "npm install" fails with peer dependency errors
|
||||
|
||||
**Problem**: You see errors about peer dependencies or conflicting packages.
|
||||
|
||||
**Solution**:
|
||||
```bash
|
||||
rm -rf node_modules package-lock.json
|
||||
npm install --legacy-peer-deps
|
||||
```
|
||||
|
||||
### ❌ "Cannot find module" errors
|
||||
|
||||
**Problem**: Node.js can't find required packages.
|
||||
|
||||
**Solutions**:
|
||||
1. **Clear and reinstall**:
|
||||
```bash
|
||||
rm -rf node_modules
|
||||
npm install --legacy-peer-deps
|
||||
```
|
||||
|
||||
2. **Check Node.js version**:
|
||||
```bash
|
||||
node --version # Should be v16 or higher
|
||||
```
|
||||
|
||||
3. **Try with npm cache clean**:
|
||||
```bash
|
||||
npm cache clean --force
|
||||
npm install --legacy-peer-deps
|
||||
```
|
||||
|
||||
### ❌ Permission errors on macOS/Linux
|
||||
|
||||
**Problem**: "EACCES" or permission denied errors.
|
||||
|
||||
**Solution**:
|
||||
```bash
|
||||
sudo chown -R $(whoami) ~/.npm
|
||||
sudo chown -R $(whoami) /usr/local/lib/node_modules
|
||||
```
|
||||
|
||||
## Development Server Issues
|
||||
|
||||
### ❌ "npm run dev" fails
|
||||
|
||||
**Problem**: Development server won't start.
|
||||
|
||||
**Solutions**:
|
||||
1. **Check if port is in use**:
|
||||
```bash
|
||||
lsof -i :5173 # Kill the process using the port
|
||||
```
|
||||
|
||||
2. **Clear dist folder**:
|
||||
```bash
|
||||
rm -rf dist
|
||||
npm run dev
|
||||
```
|
||||
|
||||
3. **Check for TypeScript errors**:
|
||||
```bash
|
||||
npx tsc --noEmit # Check for type errors
|
||||
```
|
||||
|
||||
### ❌ Changes not reflecting in browser
|
||||
|
||||
**Problem**: You make code changes but don't see them in the browser.
|
||||
|
||||
**Solutions**:
|
||||
1. **Reload the extension**:
|
||||
- Go to `chrome://extensions`
|
||||
- Find BetterSEQTA+ and click the refresh icon
|
||||
- Refresh your SEQTA page
|
||||
|
||||
2. **Check if dev server is running**:
|
||||
- Look for "Build completed" in your terminal
|
||||
- If not, restart `npm run dev`
|
||||
|
||||
3. **Hard refresh the page**:
|
||||
- Press `Ctrl+Shift+R` (or `Cmd+Shift+R` on Mac)
|
||||
|
||||
## Browser Extension Issues
|
||||
|
||||
### ❌ Extension doesn't load in Chrome
|
||||
|
||||
**Problem**: Extension appears in `chrome://extensions` but doesn't work.
|
||||
|
||||
**Solutions**:
|
||||
1. **Check for errors**:
|
||||
- Go to `chrome://extensions`
|
||||
- Click "Errors" button on BetterSEQTA+
|
||||
- Fix any JavaScript errors shown
|
||||
|
||||
2. **Verify manifest**:
|
||||
- Check if `dist/manifest.json` exists
|
||||
- Ensure it has proper structure
|
||||
|
||||
3. **Check permissions**:
|
||||
- Extension needs permission to access SEQTA pages
|
||||
- Click "Details" → "Site access" → "On all sites"
|
||||
|
||||
### ❌ Extension doesn't appear on SEQTA pages
|
||||
|
||||
**Problem**: Extension loads but doesn't modify SEQTA.
|
||||
|
||||
**Solutions**:
|
||||
1. **Check if you're on a SEQTA Learn page**:
|
||||
- URL should contain "seqta" or "learn"
|
||||
- Page title should include "SEQTA Learn"
|
||||
|
||||
2. **Check browser console**:
|
||||
- Press `F12` → Console tab
|
||||
- Look for "[BetterSEQTA+]" messages
|
||||
- If no messages, extension isn't running
|
||||
|
||||
3. **Verify page detection**:
|
||||
- Extension only runs on actual SEQTA Learn pages
|
||||
- Test on a real SEQTA instance
|
||||
|
||||
### ❌ Settings page won't open
|
||||
|
||||
**Problem**: Clicking the extension icon doesn't open settings.
|
||||
|
||||
**Solutions**:
|
||||
1. **Check popup errors**:
|
||||
- Right-click extension icon → "Inspect popup"
|
||||
- Look for JavaScript errors
|
||||
|
||||
2. **Clear extension storage**:
|
||||
```javascript
|
||||
// In browser console on any page:
|
||||
chrome.storage.local.clear()
|
||||
```
|
||||
|
||||
3. **Reload extension and try again**
|
||||
|
||||
## Plugin Development Issues
|
||||
|
||||
### ❌ My plugin doesn't appear in settings
|
||||
|
||||
**Problem**: Created a plugin but it's not showing up.
|
||||
|
||||
**Solutions**:
|
||||
1. **Check plugin registration**:
|
||||
- Ensure your plugin is imported in `src/plugins/index.ts`
|
||||
- Verify `pluginManager.registerPlugin(yourPlugin)` is called
|
||||
|
||||
2. **Check plugin structure**:
|
||||
```typescript
|
||||
// Ensure your plugin has all required fields
|
||||
const myPlugin: Plugin = {
|
||||
id: "unique-id", // Must be unique
|
||||
name: "Display Name",
|
||||
description: "What it does",
|
||||
version: "1.0.0",
|
||||
run: async (api) => {
|
||||
// Your code here
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
3. **Check for errors**:
|
||||
- Look in browser console for plugin loading errors
|
||||
|
||||
### ❌ Plugin settings not working
|
||||
|
||||
**Problem**: Plugin settings don't save or load properly.
|
||||
|
||||
**Solutions**:
|
||||
1. **Check settings definition**:
|
||||
```typescript
|
||||
import { defineSettings, booleanSetting } from "@/plugins/core/settingsHelpers";
|
||||
|
||||
const settings = defineSettings({
|
||||
myOption: booleanSetting({
|
||||
default: true,
|
||||
title: "My Option",
|
||||
description: "What this does"
|
||||
})
|
||||
});
|
||||
```
|
||||
|
||||
2. **Wait for settings to load**:
|
||||
```typescript
|
||||
run: async (api) => {
|
||||
await api.settings.loaded; // Wait for settings to load
|
||||
console.log(api.settings.myOption); // Now you can use settings
|
||||
}
|
||||
```
|
||||
|
||||
### ❌ Plugin API functions not working
|
||||
|
||||
**Problem**: `api.seqta.onMount()` or other API functions don't work.
|
||||
|
||||
**Solutions**:
|
||||
1. **Check selector specificity**:
|
||||
```typescript
|
||||
// Be specific with selectors
|
||||
api.seqta.onMount(".home-page", (element) => {
|
||||
// Your code
|
||||
});
|
||||
```
|
||||
|
||||
2. **Wait for elements**:
|
||||
```typescript
|
||||
// Some elements load after page navigation
|
||||
api.seqta.onPageChange((page) => {
|
||||
if (page === "home") {
|
||||
api.seqta.onMount(".home-content", (element) => {
|
||||
// Now element should exist
|
||||
});
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
## Build Issues
|
||||
|
||||
### ❌ "npm run build" fails
|
||||
|
||||
**Problem**: Production build fails with errors.
|
||||
|
||||
**Solutions**:
|
||||
1. **Check TypeScript errors**:
|
||||
```bash
|
||||
npx tsc --noEmit
|
||||
```
|
||||
|
||||
2. **Clear cache and rebuild**:
|
||||
```bash
|
||||
rm -rf dist node_modules
|
||||
npm install --legacy-peer-deps
|
||||
npm run build
|
||||
```
|
||||
|
||||
3. **Check for import errors**:
|
||||
- Ensure all imports use correct paths
|
||||
- Check for missing files
|
||||
|
||||
### ❌ Built extension doesn't work
|
||||
|
||||
**Problem**: `npm run build` succeeds but extension doesn't work.
|
||||
|
||||
**Solutions**:
|
||||
1. **Test the built extension**:
|
||||
- Load the `dist` folder as unpacked extension
|
||||
- Check console for errors
|
||||
|
||||
2. **Compare with dev version**:
|
||||
- If dev works but build doesn't, there might be a build configuration issue
|
||||
|
||||
3. **Check manifest generation**:
|
||||
- Verify `dist/manifest.json` looks correct
|
||||
- Compare with working version
|
||||
|
||||
## Common Error Messages
|
||||
|
||||
### "Cannot access contents of the URL"
|
||||
- **Cause**: Extension permissions issue
|
||||
- **Fix**: Go to `chrome://extensions` → BetterSEQTA+ → Details → Site access → "On all sites"
|
||||
|
||||
### "Extension context invalidated"
|
||||
- **Cause**: Extension was reloaded while page was open
|
||||
- **Fix**: Refresh the SEQTA page
|
||||
|
||||
### "Uncaught ReferenceError: browser is not defined"
|
||||
- **Cause**: Missing webextension-polyfill import
|
||||
- **Fix**: Add `import browser from "webextension-polyfill";` at top of file
|
||||
|
||||
### "Module not found: Can't resolve '@/...' "
|
||||
- **Cause**: TypeScript path mapping issue
|
||||
- **Fix**: Check `tsconfig.json` and `vite.config.ts` for path configuration
|
||||
|
||||
## Performance Issues
|
||||
|
||||
### Extension makes SEQTA slow
|
||||
1. **Check for memory leaks**:
|
||||
- Use Chrome DevTools → Performance tab
|
||||
- Look for growing memory usage
|
||||
|
||||
2. **Optimize plugin code**:
|
||||
- Remove unnecessary listeners
|
||||
- Clean up intervals/timeouts
|
||||
- Use efficient selectors
|
||||
|
||||
3. **Profile your changes**:
|
||||
- Test with extension disabled vs enabled
|
||||
- Identify which plugin is causing issues
|
||||
|
||||
## Still Stuck?
|
||||
|
||||
If none of these solutions work:
|
||||
|
||||
1. **🔍 Search existing issues**: [GitHub Issues](https://github.com/BetterSEQTA/BetterSEQTA-plus/issues)
|
||||
|
||||
2. **💬 Ask on Discord**: [Join our server](https://discord.gg/YzmbnCDkat) - fastest way to get help!
|
||||
|
||||
3. **📝 Create a new issue**: Include:
|
||||
- Your operating system
|
||||
- Node.js version (`node --version`)
|
||||
- Browser version
|
||||
- Exact error message
|
||||
- Steps to reproduce
|
||||
- What you've already tried
|
||||
|
||||
4. **📧 Email us**: betterseqta.plus@gmail.com for urgent issues
|
||||
|
||||
## Getting More Debug Info
|
||||
|
||||
### Enable verbose logging
|
||||
Add this to your plugin's `run` function:
|
||||
```typescript
|
||||
console.log("[DEBUG] Plugin starting:", api);
|
||||
```
|
||||
|
||||
### Check extension background page
|
||||
1. Go to `chrome://extensions`
|
||||
2. Click "Details" on BetterSEQTA+
|
||||
3. Click "Inspect views: background page"
|
||||
4. Check console for background script errors
|
||||
|
||||
### Export debug info
|
||||
Run this in browser console on a SEQTA page:
|
||||
```javascript
|
||||
console.log("Extension info:", {
|
||||
version: chrome.runtime.getManifest().version,
|
||||
url: window.location.href,
|
||||
userAgent: navigator.userAgent,
|
||||
storage: await chrome.storage.local.get()
|
||||
});
|
||||
```
|
||||
|
||||
Remember: **Don't give up!** Every developer faces these issues. The community is here to help, and solving these problems makes you a better developer. 💪
|
||||
@@ -1,268 +0,0 @@
|
||||
# Contributing to BetterSEQTA+
|
||||
|
||||
Thank you for your interest in contributing to BetterSEQTA+! This document provides guidelines and instructions for contributing to the project.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- [Code of Conduct](#code-of-conduct)
|
||||
- [Getting Started](#getting-started)
|
||||
- [Setting Up Your Development Environment](#setting-up-your-development-environment)
|
||||
- [Project Structure](#project-structure)
|
||||
- [Contributing Code](#contributing-code)
|
||||
- [Branching Strategy](#branching-strategy)
|
||||
- [Pull Request Process](#pull-request-process)
|
||||
- [Coding Standards](#coding-standards)
|
||||
- [Reporting Bugs](#reporting-bugs)
|
||||
- [Suggesting Features](#suggesting-features)
|
||||
- [Writing Documentation](#writing-documentation)
|
||||
- [Community](#community)
|
||||
|
||||
## Code of Conduct
|
||||
|
||||
BetterSEQTA+ is committed to providing a welcoming and inclusive environment for all contributors. We expect all participants to adhere to our Code of Conduct, which promotes respectful and harassment-free interaction.
|
||||
|
||||
Key points:
|
||||
|
||||
- Be respectful and inclusive
|
||||
- Focus on what is best for the community
|
||||
- Show empathy towards other community members
|
||||
- Be open to constructive feedback
|
||||
|
||||
## Getting Started
|
||||
|
||||
### Setting Up Your Development Environment
|
||||
|
||||
1. **Fork the Repository**
|
||||
|
||||
Start by forking the BetterSEQTA+ repository to your GitHub account.
|
||||
|
||||
2. **Clone Your Fork**
|
||||
|
||||
```bash
|
||||
git clone https://github.com/yourusername/betterseqta-plus.git
|
||||
cd betterseqta-plus
|
||||
```
|
||||
|
||||
3. **Install Dependencies**
|
||||
|
||||
```bash
|
||||
npm install
|
||||
```
|
||||
|
||||
4. **Set Up Development Environment**
|
||||
|
||||
```bash
|
||||
npm run dev
|
||||
```
|
||||
|
||||
5. **Install in Chrome/Firefox**
|
||||
|
||||
Follow the [installation instructions](./installation.md#development-installation) to load the development version into your browser.
|
||||
|
||||
### Project Structure
|
||||
|
||||
Understanding the project structure will help you navigate the codebase:
|
||||
|
||||
```
|
||||
betterseqta-plus/
|
||||
├── src/ # Source code
|
||||
│ ├── plugins/ # Plugin system
|
||||
│ │ ├── built-in/ # Built-in plugins
|
||||
│ │ ├── core/ # Plugin core functionality
|
||||
│ ├── settings/ # Settings system
|
||||
│ ├── utils/ # Utility functions
|
||||
│ ├── extension/ # Browser extension code
|
||||
├── docs/ # Documentation
|
||||
├── test/ # Test files
|
||||
├── dist/ # Build output (generated)
|
||||
├── package.json # Project dependencies
|
||||
├── tsconfig.json # TypeScript configuration
|
||||
└── README.md # Project README
|
||||
```
|
||||
|
||||
## Contributing Code
|
||||
|
||||
### Branching Strategy
|
||||
|
||||
We follow a simple branching strategy:
|
||||
|
||||
- `main` - The main development branch
|
||||
- `feature/*` - Feature branches
|
||||
- `bugfix/*` - Bug fix branches
|
||||
- `docs/*` - Documentation branches
|
||||
|
||||
Always create a new branch for your changes:
|
||||
|
||||
```bash
|
||||
git checkout -b feature/my-new-feature
|
||||
```
|
||||
|
||||
### Pull Request Process
|
||||
|
||||
1. **Keep PRs Focused**
|
||||
|
||||
Each pull request should address a single concern. If you're working on multiple features, create separate PRs for each.
|
||||
|
||||
2. **Write Clear Commit Messages**
|
||||
|
||||
Follow the conventional commits format:
|
||||
|
||||
```
|
||||
feat: add new feature
|
||||
fix: resolve bug with timetable
|
||||
docs: update installation instructions
|
||||
```
|
||||
|
||||
3. **Update Documentation**
|
||||
|
||||
If your changes require documentation updates, include them in the same PR.
|
||||
|
||||
4. **Run Tests**
|
||||
|
||||
Make sure all tests pass before submitting your PR:
|
||||
|
||||
```bash
|
||||
npm test
|
||||
```
|
||||
|
||||
5. **Submit Your PR**
|
||||
|
||||
When you're ready, push your branch and create a pull request on GitHub.
|
||||
|
||||
6. **Code Review**
|
||||
|
||||
All PRs will be reviewed by maintainers. Be responsive to feedback and make requested changes.
|
||||
|
||||
7. **Merge**
|
||||
|
||||
Once approved, a maintainer will merge your PR.
|
||||
|
||||
### Coding Standards
|
||||
|
||||
We follow TypeScript best practices and have a consistent code style:
|
||||
|
||||
1. **Use TypeScript**
|
||||
|
||||
All new code should be written in TypeScript with proper typing.
|
||||
|
||||
2. **Follow Existing Patterns**
|
||||
|
||||
Match the coding style of the existing codebase.
|
||||
|
||||
3. **Write Tests**
|
||||
|
||||
Add tests for new features and bug fixes.
|
||||
|
||||
4. **Document Your Code**
|
||||
|
||||
Add comments for complex logic and JSDoc comments for functions.
|
||||
|
||||
5. **Use Linters**
|
||||
|
||||
We use ESLint and Prettier. Run them before submitting your PR:
|
||||
|
||||
```bash
|
||||
npm run lint
|
||||
npm run format
|
||||
```
|
||||
|
||||
## Reporting Bugs
|
||||
|
||||
If you find a bug, please report it by creating an issue on GitHub:
|
||||
|
||||
1. **Search Existing Issues**
|
||||
|
||||
Check if the bug has already been reported.
|
||||
|
||||
2. **Use the Bug Report Template**
|
||||
|
||||
Fill in all sections of the bug report template:
|
||||
|
||||
- Description
|
||||
- Steps to reproduce
|
||||
- Expected behavior
|
||||
- Actual behavior
|
||||
- Screenshots (if applicable)
|
||||
- Environment (browser, OS, etc.)
|
||||
|
||||
3. **Be Specific**
|
||||
|
||||
The more details you provide, the easier it will be to fix the bug.
|
||||
|
||||
## Suggesting Features
|
||||
|
||||
We welcome feature suggestions! To suggest a new feature:
|
||||
|
||||
1. **Search Existing Suggestions**
|
||||
|
||||
Check if your idea has already been suggested.
|
||||
|
||||
2. **Use the Feature Request Template**
|
||||
|
||||
Fill in all sections of the feature request template:
|
||||
|
||||
- Description
|
||||
- Use case
|
||||
- Potential implementation
|
||||
- Alternatives considered
|
||||
|
||||
3. **Be Patient**
|
||||
|
||||
Feature requests are evaluated based on alignment with project goals, feasibility, and maintainer bandwidth.
|
||||
|
||||
## Writing Documentation
|
||||
|
||||
Good documentation is crucial for the project. To contribute to documentation:
|
||||
|
||||
1. **Identify Gaps**
|
||||
|
||||
Look for areas where documentation is missing or unclear.
|
||||
|
||||
2. **Follow Documentation Style**
|
||||
|
||||
Maintain a consistent style and format.
|
||||
|
||||
3. **Use Clear Language**
|
||||
|
||||
Write in simple, clear English. Avoid jargon when possible.
|
||||
|
||||
4. **Include Examples**
|
||||
|
||||
Code examples and screenshots help users understand.
|
||||
|
||||
5. **Submit a PR**
|
||||
|
||||
Follow the same process as code contributions, but create a branch with a `docs/` prefix.
|
||||
|
||||
## Community
|
||||
|
||||
Join our community channels to discuss the project, get help, and connect with other contributors:
|
||||
|
||||
- **Discord Server**: [Join our Discord](https://discord.gg/betterseqta)
|
||||
- **GitHub Discussions**: For longer-form conversations
|
||||
- **GitHub Issues**: For bug reports and feature requests
|
||||
|
||||
## Creating Plugins
|
||||
|
||||
If you're interested in creating plugins for BetterSEQTA+, check out our plugin development guides:
|
||||
|
||||
- [Creating Your First Plugin](./plugins/creating-plugins.md)
|
||||
- [Plugin API Reference](./advanced/plugin-api.md)
|
||||
|
||||
## Recognition
|
||||
|
||||
Contributors are recognized in several ways:
|
||||
|
||||
1. **CONTRIBUTORS.md**: All contributors are listed in this file
|
||||
2. **Release Notes**: Significant contributions are highlighted in release notes
|
||||
3. **Community Recognition**: Regular shout-outs in community channels
|
||||
|
||||
## Questions?
|
||||
|
||||
If you have any questions about contributing, please:
|
||||
|
||||
1. Check the documentation
|
||||
2. Ask in the Discord server
|
||||
3. Open a GitHub Discussion
|
||||
|
||||
Thank you for contributing to BetterSEQTA+! Your efforts help make SEQTA better for students and teachers everywhere.
|
||||
@@ -1,182 +0,0 @@
|
||||
# Installing BetterSEQTA+
|
||||
|
||||
This guide will walk you through the process of installing and setting up BetterSEQTA+ for development or usage.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Before you begin, make sure you have the following installed:
|
||||
|
||||
- [npm](https://www.npmjs.com/) (v7 or higher) or [Bun](https://bun.sh/) (recommended)
|
||||
- A modern web browser (Chrome, Firefox, Edge, etc.)
|
||||
|
||||
## Installation Methods
|
||||
|
||||
There are two ways to install BetterSEQTA+:
|
||||
|
||||
1. **For Users**: Install the browser extension
|
||||
2. **For Developers**: Clone the repository and set up the development environment
|
||||
|
||||
## For Users: Installing the Browser Extension
|
||||
|
||||
BetterSEQTA+ is available as a browser extension for Chrome, Firefox, and Edge.
|
||||
|
||||
### Chrome/Edge
|
||||
|
||||
1. Visit the [Chrome Web Store page for BetterSEQTA+](https://chrome.google.com/webstore/detail/betterseqta)
|
||||
2. Click the "Add to Chrome" button
|
||||
3. Confirm the installation when prompted
|
||||
4. The extension will be installed and ready to use
|
||||
|
||||
### Firefox
|
||||
|
||||
1. Visit the [Firefox Add-ons page for BetterSEQTA+](https://addons.mozilla.org/en-US/firefox/addon/betterseqta)
|
||||
2. Click the "Add to Firefox" button
|
||||
3. Confirm the installation when prompted
|
||||
4. The extension will be installed and ready to use
|
||||
|
||||
## For Developers: Setting Up the Development Environment
|
||||
|
||||
If you want to develop for BetterSEQTA+ or modify the code, follow these steps:
|
||||
|
||||
### 1. Clone the Repository
|
||||
|
||||
```bash
|
||||
git clone https://github.com/SeqtaLearning/betterseqta-plus.git
|
||||
cd betterseqta-plus
|
||||
```
|
||||
|
||||
### 2. Install Dependencies
|
||||
|
||||
Using npm:
|
||||
|
||||
```bash
|
||||
npm install --legacy-peer-deps
|
||||
```
|
||||
|
||||
Using Bun (recommended):
|
||||
|
||||
```bash
|
||||
bun install
|
||||
```
|
||||
|
||||
### 3. Set Up Environment Variables - Only required for pushing to extension stores from the command line
|
||||
|
||||
Copy the example environment file:
|
||||
|
||||
```bash
|
||||
cp .env.submit.example .env
|
||||
```
|
||||
|
||||
Edit the `.env` file with your SEQTA credentials and settings.
|
||||
|
||||
### 4. Start the Development Server
|
||||
|
||||
Using npm:
|
||||
|
||||
```bash
|
||||
npm run dev
|
||||
```
|
||||
|
||||
Using Bun:
|
||||
|
||||
```bash
|
||||
bun run dev
|
||||
```
|
||||
|
||||
This will start a development server and build the extension in watch mode.
|
||||
|
||||
### 5. Load the Extension in Your Browser
|
||||
|
||||
#### Chrome/Edge
|
||||
|
||||
1. Open Chrome/Edge and navigate to `chrome://extensions` or `edge://extensions`
|
||||
2. Enable "Developer mode" using the toggle in the top right
|
||||
3. Click "Load unpacked" and select the `dist` folder in your BetterSEQTA+ directory
|
||||
4. The extension should now appear in your extensions list
|
||||
|
||||
#### Firefox
|
||||
|
||||
1. Open Firefox and navigate to `about:debugging#/runtime/this-firefox`
|
||||
2. Click "Load Temporary Add-on..."
|
||||
3. Select the `manifest.json` file in the `dist` folder
|
||||
4. The extension should now appear in your add-ons list
|
||||
|
||||
### 6. Test Your Changes
|
||||
|
||||
After making changes to the code, the development server will automatically rebuild the extension. However, you may need to reload the extension in your browser to see the changes:
|
||||
|
||||
1. Go to the extensions page in your browser
|
||||
2. Find BetterSEQTA+ and click the reload icon
|
||||
3. Refresh any SEQTA Learn pages you have open
|
||||
|
||||
## Troubleshooting Installation
|
||||
|
||||
### Common Issues
|
||||
|
||||
#### "Cannot find module" errors
|
||||
|
||||
If you see errors about missing modules, try:
|
||||
|
||||
```bash
|
||||
rm -rf node_modules
|
||||
npm install
|
||||
```
|
||||
|
||||
Or with Bun:
|
||||
|
||||
```bash
|
||||
rm -rf node_modules
|
||||
bun install
|
||||
```
|
||||
|
||||
#### Extension not appearing in SEQTA
|
||||
|
||||
Make sure:
|
||||
|
||||
- You're visiting a SEQTA Learn page
|
||||
- The extension is enabled
|
||||
- You've refreshed the page after installing the extension
|
||||
|
||||
#### Development build not updating
|
||||
|
||||
Try:
|
||||
|
||||
1. Stopping the development server
|
||||
2. Clearing your browser cache
|
||||
3. Removing the extension from your browser
|
||||
4. Rebuilding the extension
|
||||
5. Loading it again
|
||||
|
||||
## Updating BetterSEQTA+
|
||||
|
||||
### For Users
|
||||
|
||||
Browser extensions update automatically, but you can manually check for updates:
|
||||
|
||||
- **Chrome/Edge**: Go to `chrome://extensions` or `edge://extensions`, enable Developer mode, and click "Update"
|
||||
- **Firefox**: Go to `about:addons`, click the gear icon, and select "Check for Updates"
|
||||
|
||||
### For Developers
|
||||
|
||||
If you're working on the code, pull the latest changes and reinstall dependencies:
|
||||
|
||||
```bash
|
||||
git pull
|
||||
npm install
|
||||
npm run dev
|
||||
```
|
||||
|
||||
Or with Bun:
|
||||
|
||||
```bash
|
||||
git pull
|
||||
bun install
|
||||
bun run dev
|
||||
```
|
||||
|
||||
## Next Steps
|
||||
|
||||
Now that you have BetterSEQTA+ installed, you can:
|
||||
|
||||
- [Getting Started with Plugins](./plugins/getting-started.md)
|
||||
- [Contribute to the project](../CONTRIBUTING.md)
|
||||
@@ -1,335 +0,0 @@
|
||||
# Example Plugin Template
|
||||
|
||||
This is a complete, working example of a simple BetterSEQTA+ plugin. You can copy this code and modify it to create your own plugin!
|
||||
|
||||
## What This Example Does
|
||||
|
||||
This plugin adds a friendly welcome message to the SEQTA homepage and lets users customize the message through settings.
|
||||
|
||||
## Complete Plugin Code
|
||||
|
||||
Create a new file in `src/plugins/built-in/my-first-plugin/index.ts`:
|
||||
|
||||
```typescript
|
||||
import type { Plugin } from "@/plugins/core/types";
|
||||
import { BasePlugin } from "@/plugins/core/settings";
|
||||
import {
|
||||
defineSettings,
|
||||
booleanSetting,
|
||||
stringSetting
|
||||
} from "@/plugins/core/settingsHelpers";
|
||||
import { Setting } from "@/plugins/core/settingsHelpers";
|
||||
|
||||
// Define the plugin settings
|
||||
const settings = defineSettings({
|
||||
enabled: booleanSetting({
|
||||
default: true,
|
||||
title: "Show Welcome Message",
|
||||
description: "Display a welcome message on the SEQTA homepage"
|
||||
}),
|
||||
customMessage: stringSetting({
|
||||
default: "Welcome to SEQTA! 🎉",
|
||||
title: "Custom Message",
|
||||
description: "The message to display on the homepage",
|
||||
maxLength: 100
|
||||
}),
|
||||
showEmoji: booleanSetting({
|
||||
default: true,
|
||||
title: "Show Emoji",
|
||||
description: "Include emojis in the welcome message"
|
||||
})
|
||||
});
|
||||
|
||||
// Create settings class
|
||||
class MyFirstPluginSettings extends BasePlugin<typeof settings> {
|
||||
@Setting(settings.enabled)
|
||||
enabled!: boolean;
|
||||
|
||||
@Setting(settings.customMessage)
|
||||
customMessage!: string;
|
||||
|
||||
@Setting(settings.showEmoji)
|
||||
showEmoji!: boolean;
|
||||
}
|
||||
|
||||
// Create settings instance
|
||||
const settingsInstance = new MyFirstPluginSettings();
|
||||
|
||||
// Define the plugin
|
||||
const myFirstPlugin: Plugin<typeof settings> = {
|
||||
id: "my-first-plugin",
|
||||
name: "My First Plugin",
|
||||
description: "Adds a customizable welcome message to the SEQTA homepage",
|
||||
version: "1.0.0",
|
||||
|
||||
// Link our settings
|
||||
settings: settingsInstance.settings,
|
||||
|
||||
// Mark as beta (optional)
|
||||
beta: true,
|
||||
|
||||
// Add some CSS styles (optional)
|
||||
styles: `
|
||||
.my-plugin-welcome {
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
color: white;
|
||||
padding: 20px;
|
||||
border-radius: 12px;
|
||||
margin: 20px;
|
||||
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
|
||||
text-align: center;
|
||||
font-size: 18px;
|
||||
animation: slideIn 0.5s ease-out;
|
||||
}
|
||||
|
||||
@keyframes slideIn {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(-20px);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
|
||||
.my-plugin-welcome .close-btn {
|
||||
float: right;
|
||||
background: rgba(255, 255, 255, 0.2);
|
||||
border: none;
|
||||
color: white;
|
||||
padding: 5px 10px;
|
||||
border-radius: 20px;
|
||||
cursor: pointer;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.my-plugin-welcome .close-btn:hover {
|
||||
background: rgba(255, 255, 255, 0.3);
|
||||
}
|
||||
`,
|
||||
|
||||
// Main plugin function
|
||||
run: async (api) => {
|
||||
console.log("[My First Plugin] Starting up! 🚀");
|
||||
|
||||
// Wait for settings to load
|
||||
await api.settings.loaded;
|
||||
|
||||
let welcomeElement: HTMLElement | null = null;
|
||||
|
||||
// Function to create the welcome message
|
||||
const createWelcomeMessage = () => {
|
||||
// Only show if enabled in settings
|
||||
if (!api.settings.enabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Remove existing message if it exists
|
||||
if (welcomeElement) {
|
||||
welcomeElement.remove();
|
||||
}
|
||||
|
||||
// Create the message element
|
||||
welcomeElement = document.createElement("div");
|
||||
welcomeElement.className = "my-plugin-welcome";
|
||||
|
||||
// Build the message content
|
||||
let message = api.settings.customMessage;
|
||||
if (!api.settings.showEmoji) {
|
||||
// Remove emojis if disabled
|
||||
message = message.replace(/[\u{1F600}-\u{1F64F}]|[\u{1F300}-\u{1F5FF}]|[\u{1F680}-\u{1F6FF}]|[\u{1F1E0}-\u{1F1FF}]|[\u{2600}-\u{26FF}]|[\u{2700}-\u{27BF}]/gu, '');
|
||||
}
|
||||
|
||||
welcomeElement.innerHTML = `
|
||||
<button class="close-btn" onclick="this.parentElement.remove()">×</button>
|
||||
<div>${message}</div>
|
||||
<small style="opacity: 0.8; margin-top: 10px; display: block;">
|
||||
Powered by My First Plugin
|
||||
</small>
|
||||
`;
|
||||
|
||||
return welcomeElement;
|
||||
};
|
||||
|
||||
// Function to add message to homepage
|
||||
const addToHomepage = () => {
|
||||
api.seqta.onMount(".home-page, .dashboard, [class*='home']", (homePage) => {
|
||||
console.log("[My First Plugin] Found homepage, adding welcome message");
|
||||
|
||||
const message = createWelcomeMessage();
|
||||
if (message) {
|
||||
// Add to the top of the homepage
|
||||
homePage.insertBefore(message, homePage.firstChild);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
// Add message when plugin starts
|
||||
addToHomepage();
|
||||
|
||||
// Re-add message when user navigates to homepage
|
||||
api.seqta.onPageChange((page) => {
|
||||
console.log("[My First Plugin] Page changed to:", page);
|
||||
if (page.includes("home") || page.includes("dashboard")) {
|
||||
// Small delay to let the page load
|
||||
setTimeout(addToHomepage, 500);
|
||||
}
|
||||
});
|
||||
|
||||
// Listen for settings changes and update the message
|
||||
api.settings.onChange("enabled", (enabled) => {
|
||||
console.log("[My First Plugin] Enabled setting changed:", enabled);
|
||||
if (enabled) {
|
||||
addToHomepage();
|
||||
} else if (welcomeElement) {
|
||||
welcomeElement.remove();
|
||||
welcomeElement = null;
|
||||
}
|
||||
});
|
||||
|
||||
api.settings.onChange("customMessage", (newMessage) => {
|
||||
console.log("[My First Plugin] Message changed:", newMessage);
|
||||
if (welcomeElement && api.settings.enabled) {
|
||||
// Update existing message
|
||||
addToHomepage();
|
||||
}
|
||||
});
|
||||
|
||||
api.settings.onChange("showEmoji", (showEmoji) => {
|
||||
console.log("[My First Plugin] Show emoji changed:", showEmoji);
|
||||
if (welcomeElement && api.settings.enabled) {
|
||||
// Update existing message
|
||||
addToHomepage();
|
||||
}
|
||||
});
|
||||
|
||||
// Return cleanup function (called when plugin is disabled)
|
||||
return () => {
|
||||
console.log("[My First Plugin] Cleaning up...");
|
||||
if (welcomeElement) {
|
||||
welcomeElement.remove();
|
||||
welcomeElement = null;
|
||||
}
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
export default myFirstPlugin;
|
||||
```
|
||||
|
||||
## How to Use This Example
|
||||
|
||||
### Step 1: Create the Plugin File
|
||||
1. Create a new folder: `src/plugins/built-in/my-first-plugin/`
|
||||
2. Create `index.ts` in that folder
|
||||
3. Copy the code above into `index.ts`
|
||||
|
||||
### Step 2: Register the Plugin
|
||||
Add this to `src/plugins/index.ts`:
|
||||
|
||||
```typescript
|
||||
// Add this import at the top
|
||||
import myFirstPlugin from "./built-in/my-first-plugin";
|
||||
|
||||
// Add this line where other plugins are registered
|
||||
pluginManager.registerPlugin(myFirstPlugin);
|
||||
```
|
||||
|
||||
### Step 3: Test It
|
||||
1. Run `npm run dev`
|
||||
2. Reload your extension in Chrome
|
||||
3. Visit a SEQTA page
|
||||
4. You should see your welcome message!
|
||||
5. Open BetterSEQTA+ settings to customize it
|
||||
|
||||
## Key Concepts Explained
|
||||
|
||||
### 1. Plugin Structure
|
||||
```typescript
|
||||
const myPlugin: Plugin = {
|
||||
id: "unique-id", // Must be unique across all plugins
|
||||
name: "Display Name", // Shown in settings
|
||||
description: "What it does", // Shown in settings
|
||||
version: "1.0.0", // Plugin version
|
||||
settings: settingsObject, // User-configurable options
|
||||
styles: "/* CSS here */", // Optional CSS styles
|
||||
run: async (api) => { // Main plugin code
|
||||
// Your code here
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
### 2. Settings System
|
||||
```typescript
|
||||
// Define what settings your plugin has
|
||||
const settings = defineSettings({
|
||||
myOption: booleanSetting({
|
||||
default: true,
|
||||
title: "My Option",
|
||||
description: "What this option does"
|
||||
})
|
||||
});
|
||||
|
||||
// Use in your plugin
|
||||
if (api.settings.myOption) {
|
||||
// Do something
|
||||
}
|
||||
```
|
||||
|
||||
### 3. SEQTA Integration
|
||||
```typescript
|
||||
// Wait for elements to appear
|
||||
api.seqta.onMount(".some-selector", (element) => {
|
||||
// Modify the element
|
||||
});
|
||||
|
||||
// Detect page changes
|
||||
api.seqta.onPageChange((page) => {
|
||||
if (page === "home") {
|
||||
// User navigated to homepage
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
### 4. Cleanup
|
||||
Always return a cleanup function to remove your changes when the plugin is disabled:
|
||||
|
||||
```typescript
|
||||
run: async (api) => {
|
||||
// Add your features
|
||||
|
||||
return () => {
|
||||
// Remove your features
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
## Customization Ideas
|
||||
|
||||
Want to modify this example? Here are some ideas:
|
||||
|
||||
1. **Change the styling**: Modify the CSS to use different colors, animations, or layouts
|
||||
2. **Add more settings**: Number settings, select dropdowns, hotkeys
|
||||
3. **Different trigger**: Show on different pages, or based on time of day
|
||||
4. **Add interactions**: Buttons that do things when clicked
|
||||
5. **Store data**: Use `api.storage` to remember user preferences
|
||||
6. **Communicate with other plugins**: Use `api.events` to send/receive events
|
||||
|
||||
## Next Steps
|
||||
|
||||
Once you've got this working:
|
||||
|
||||
1. **Experiment**: Try changing things and see what happens
|
||||
2. **Read other plugins**: Look at the built-in plugins for inspiration
|
||||
3. **Check the API docs**: Learn about all available API functions
|
||||
4. **Share your creation**: Show it off in Discord!
|
||||
|
||||
## Need Help?
|
||||
|
||||
- 💬 Ask in our [Discord server](https://discord.gg/YzmbnCDkat)
|
||||
- 📚 Read our [Plugin Development Guide](./README.md)
|
||||
- 🐛 Check the [Troubleshooting Guide](../TROUBLESHOOTING.md)
|
||||
- 📝 Open an issue on GitHub
|
||||
|
||||
Happy coding! 🎉
|
||||
@@ -1,297 +0,0 @@
|
||||
# Creating Plugins for BetterSEQTA+
|
||||
|
||||
Hey there! 👋 So you want to create a plugin for BetterSEQTA+? That's awesome! This guide will walk you through everything you need to know, from the very basics to more advanced features. Don't worry if you're new to this - we'll explain everything step by step.
|
||||
|
||||
## What is a Plugin?
|
||||
|
||||
In BetterSEQTA+, a plugin is like a mini-app that adds new features to SEQTA. Think of it as a piece of LEGO that you can snap onto SEQTA to make it do new things. For example, you could create a plugin that:
|
||||
|
||||
- Changes how SEQTA looks
|
||||
- Adds new buttons or features
|
||||
- Shows extra information on your timetable
|
||||
- Collects notifications in a better way
|
||||
- Really, anything you can imagine!
|
||||
|
||||
## Your First Plugin
|
||||
|
||||
Let's create a super simple plugin together. We'll make one that adds a friendly message to the SEQTA homepage. Here's what we'll need:
|
||||
|
||||
```typescript
|
||||
import type { Plugin } from "@/plugins/core/types";
|
||||
|
||||
const myFirstPlugin: Plugin = {
|
||||
// Every plugin needs these basic details
|
||||
id: "my-first-plugin",
|
||||
name: "My First Plugin",
|
||||
description: "Adds a friendly message to SEQTA",
|
||||
version: "1.0.0",
|
||||
|
||||
// This tells BetterSEQTA+ that users can turn our plugin on/off
|
||||
disableToggle: true,
|
||||
|
||||
// Optional: Mark your plugin as beta to show a "Beta" tag in settings
|
||||
beta: true,
|
||||
|
||||
// This is where the magic happens!
|
||||
run: async (api) => {
|
||||
// Wait for the homepage to load
|
||||
api.seqta.onMount(".home-page", (homePage) => {
|
||||
// Create our message
|
||||
const message = document.createElement("div");
|
||||
message.textContent = "Hello from my first plugin! 🎉";
|
||||
message.style.padding = "20px";
|
||||
message.style.backgroundColor = "#e9f5ff";
|
||||
message.style.borderRadius = "8px";
|
||||
message.style.margin = "20px";
|
||||
|
||||
// Add it to the page
|
||||
homePage.prepend(message);
|
||||
});
|
||||
|
||||
// Return a cleanup function that removes our message when the plugin is disabled
|
||||
return () => {
|
||||
const message = document.querySelector(".home-page > div");
|
||||
message?.remove();
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
export default myFirstPlugin;
|
||||
```
|
||||
|
||||
Let's break down what's happening here:
|
||||
|
||||
1. First, we import the `Plugin` type that tells TypeScript what a plugin should look like
|
||||
2. We create our plugin object with some basic information:
|
||||
- `id`: A unique name for your plugin (use lowercase and dashes)
|
||||
- `name`: A friendly name that users will see
|
||||
- `description`: Explain what your plugin does
|
||||
- `version`: Your plugin's version number
|
||||
3. We set `disableToggle: true` so users can turn our plugin on/off in settings
|
||||
4. We set `beta: true` to mark the plugin as beta
|
||||
5. The `run` function is where we put our plugin's code
|
||||
6. We use `api.seqta.onMount` to wait for the homepage to load
|
||||
7. We create and style a message element
|
||||
8. We return a cleanup function that removes our changes when the plugin is disabled
|
||||
|
||||
## The Plugin API
|
||||
|
||||
When your plugin runs, it gets access to a powerful API that lets you do all sorts of things. Let's look at what you can do:
|
||||
|
||||
### SEQTA API (`api.seqta`)
|
||||
|
||||
This helps you interact with SEQTA's pages:
|
||||
|
||||
```typescript
|
||||
// Wait for an element to appear on the page
|
||||
api.seqta.onMount(".some-class", (element) => {
|
||||
// Do something with the element
|
||||
});
|
||||
|
||||
// Know when the user changes pages
|
||||
api.seqta.onPageChange((page) => {
|
||||
console.log("User went to:", page);
|
||||
});
|
||||
|
||||
// Get the current page
|
||||
const currentPage = api.seqta.getCurrentPage();
|
||||
```
|
||||
|
||||
### Settings API (`api.settings`)
|
||||
|
||||
Want to let users customize your plugin? Use settings!
|
||||
|
||||
```typescript
|
||||
import { BasePlugin } from "@/plugins/core/settings";
|
||||
import {
|
||||
booleanSetting,
|
||||
defineSettings,
|
||||
Setting,
|
||||
} from "@/plugins/core/settingsHelpers";
|
||||
|
||||
// Define your settings
|
||||
const settings = defineSettings({
|
||||
showMessage: booleanSetting({
|
||||
default: true,
|
||||
title: "Show Welcome Message",
|
||||
description: "Show a friendly message on the homepage",
|
||||
}),
|
||||
});
|
||||
|
||||
// Create a class for your plugin
|
||||
class MyPluginClass extends BasePlugin<typeof settings> {
|
||||
@Setting(settings.showMessage)
|
||||
showMessage!: boolean;
|
||||
}
|
||||
|
||||
// Create your plugin
|
||||
const settingsInstance = new MyPluginClass();
|
||||
|
||||
const myPlugin: Plugin<typeof settings> = {
|
||||
// ... other plugin details ...
|
||||
settings: settingsInstance.settings,
|
||||
|
||||
run: async (api) => {
|
||||
// Use the setting
|
||||
if (api.settings.showMessage) {
|
||||
// Show the message
|
||||
}
|
||||
|
||||
// Listen for setting changes
|
||||
api.settings.onChange("showMessage", (newValue) => {
|
||||
if (newValue) {
|
||||
// Show the message
|
||||
} else {
|
||||
// Hide the message
|
||||
}
|
||||
});
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
### Storage API (`api.storage`)
|
||||
|
||||
Need to save some data? The storage API has got you covered:
|
||||
|
||||
```typescript
|
||||
// Save some data
|
||||
await api.storage.set("lastVisit", new Date().toISOString());
|
||||
|
||||
// Get it back later
|
||||
const lastVisit = await api.storage.get("lastVisit");
|
||||
|
||||
// Listen for changes
|
||||
api.storage.onChange("lastVisit", (newValue) => {
|
||||
console.log("Last visit updated:", newValue);
|
||||
});
|
||||
```
|
||||
|
||||
### Events API (`api.events`)
|
||||
|
||||
Want your plugin to be able to interface with other plugins? Then use events!
|
||||
|
||||
```typescript
|
||||
// Listen for an event
|
||||
api.events.on("myCustomEvent", (data) => {
|
||||
console.log("Got event:", data);
|
||||
});
|
||||
|
||||
// Send an event
|
||||
api.events.emit("myCustomEvent", { some: "data" });
|
||||
```
|
||||
|
||||
## Adding Styles
|
||||
|
||||
Want to make your plugin look pretty? You can add CSS styles:
|
||||
|
||||
```typescript
|
||||
const myPlugin: Plugin = {
|
||||
// ... other plugin details ...
|
||||
|
||||
// Add your CSS here
|
||||
styles: `
|
||||
.my-plugin-message {
|
||||
background: linear-gradient(135deg, #6e8efb, #a777e3);
|
||||
color: white;
|
||||
padding: 20px;
|
||||
border-radius: 12px;
|
||||
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
|
||||
margin: 20px;
|
||||
animation: slide-in 0.3s ease-out;
|
||||
}
|
||||
|
||||
@keyframes slide-in {
|
||||
from { transform: translateY(-20px); opacity: 0; }
|
||||
to { transform: translateY(0); opacity: 1; }
|
||||
}
|
||||
`,
|
||||
|
||||
run: async (api) => {
|
||||
// Your plugin code here
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
Here are some tips to make your plugin awesome:
|
||||
|
||||
1. **Always Clean Up**: When your plugin is disabled, clean up any changes you made:
|
||||
|
||||
```typescript
|
||||
run: async (api) => {
|
||||
// Add stuff to the page
|
||||
const element = document.createElement("div");
|
||||
document.body.appendChild(element);
|
||||
|
||||
// Return a cleanup function
|
||||
return () => {
|
||||
element.remove();
|
||||
};
|
||||
};
|
||||
```
|
||||
|
||||
2. **Use TypeScript**: It helps catch errors before they happen and makes your code easier to understand.
|
||||
|
||||
3. **Test Your Plugin**: Make sure it works in different situations:
|
||||
|
||||
- When SEQTA is loading
|
||||
- When the user switches pages
|
||||
- When the plugin is enabled/disabled
|
||||
- When settings are changed
|
||||
|
||||
4. **Keep It Fast**: Don't slow down SEQTA:
|
||||
|
||||
- Use `onMount` instead of intervals or timeouts
|
||||
- Clean up event listeners when they're not needed
|
||||
- Don't do heavy calculations on the main thread
|
||||
|
||||
5. **Make It User-Friendly**:
|
||||
- Add clear settings with good descriptions
|
||||
- Use `disableToggle: true` so users can turn it off if needed
|
||||
- Add helpful error messages if something goes wrong
|
||||
- Use `beta: true` for experimental features to let users know they're trying something new
|
||||
|
||||
## Plugin Metadata Options
|
||||
|
||||
Your plugin object supports several optional flags to customize how it appears and behaves:
|
||||
|
||||
```typescript
|
||||
const myPlugin: Plugin = {
|
||||
id: "my-plugin",
|
||||
name: "My Plugin",
|
||||
description: "What my plugin does",
|
||||
version: "1.0.0",
|
||||
|
||||
// Optional flags:
|
||||
disableToggle: true, // Show enable/disable toggle in settings
|
||||
defaultEnabled: false, // Start disabled by default (requires disableToggle: true)
|
||||
beta: true, // Show "Beta" tag in settings UI
|
||||
|
||||
// Your plugin code...
|
||||
run: async (api) => { /* ... */ },
|
||||
};
|
||||
```
|
||||
|
||||
- **`disableToggle`**: When `true`, users can enable/disable your plugin in settings
|
||||
- **`defaultEnabled`**: When `false`, your plugin starts disabled (only works with `disableToggle: true`)
|
||||
- **`beta`**: When `true`, shows an orange "Beta" tag next to your plugin name in settings
|
||||
|
||||
## Examples
|
||||
|
||||
Want to see more examples? Check out our built-in plugins:
|
||||
|
||||
- [themes](../../src/plugins/built-in/themes/index.ts): Shows how to change SEQTA's appearance
|
||||
- [notificationCollector](../../src/plugins/built-in/notificationCollector/index.ts): Shows how to work with SEQTA's notifications
|
||||
- [timetable](../../src/plugins/built-in/timetable/index.ts): Shows how to modify SEQTA's timetable view
|
||||
- [assessmentsAverage](../../src/plugins/built-in/assessmentsAverage/index.ts): Shows how to add new features to existing pages
|
||||
|
||||
## Need Help?
|
||||
|
||||
Got stuck? No worries! Here's where you can get help:
|
||||
|
||||
- Join our [Discord server](https://discord.gg/YzmbnCDkat)
|
||||
- Check out the built-in plugins in the `src/plugins/built-in` folder
|
||||
- Open an issue on our [GitHub page](https://github.com/betterseqta/betterseqta-plus/issues)
|
||||
|
||||
Happy coding and feel free to checkout the api reference [here](./api-reference.md)
|
||||
@@ -1,366 +0,0 @@
|
||||
# Plugin API Reference
|
||||
|
||||
This document provides detailed technical information about BetterSEQTA+'s plugin APIs. For a beginner-friendly introduction, see [Creating Your First Plugin](./README.md).
|
||||
|
||||
## Plugin Structure
|
||||
|
||||
Here's how a plugin is structured:
|
||||
|
||||
```typescript
|
||||
import type { Plugin } from "@/plugins/core/types";
|
||||
import { BasePlugin } from "@/plugins/core/settings";
|
||||
import {
|
||||
booleanSetting,
|
||||
defineSettings,
|
||||
Setting,
|
||||
} from "@/plugins/core/settingsHelpers";
|
||||
|
||||
// First, define your settings
|
||||
const settings = defineSettings({
|
||||
enabled: booleanSetting({
|
||||
default: true,
|
||||
title: "Enable Feature",
|
||||
description: "Turn this feature on or off",
|
||||
}),
|
||||
});
|
||||
|
||||
// Create a class to handle your settings
|
||||
class MyPluginClass extends BasePlugin<typeof settings> {
|
||||
@Setting(settings.enabled)
|
||||
enabled!: boolean;
|
||||
}
|
||||
|
||||
// Create an instance of your settings
|
||||
const settingsInstance = new MyPluginClass();
|
||||
|
||||
// Create your plugin
|
||||
const myPlugin: Plugin<typeof settings> = {
|
||||
id: "my-plugin",
|
||||
name: "My Plugin",
|
||||
description: "A cool plugin that does things",
|
||||
version: "1.0.0",
|
||||
settings: settingsInstance.settings,
|
||||
disableToggle: true,
|
||||
beta: true,
|
||||
|
||||
run: async (api) => {
|
||||
console.log("Plugin is running!");
|
||||
|
||||
// Do stuff when settings change
|
||||
api.settings.onChange("enabled", (enabled) => {
|
||||
if (enabled) {
|
||||
console.log("Feature enabled!");
|
||||
}
|
||||
});
|
||||
|
||||
// Return a cleanup function
|
||||
return () => {
|
||||
console.log("Plugin cleanup");
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
export default myPlugin;
|
||||
```
|
||||
|
||||
## Plugin Metadata
|
||||
|
||||
The plugin object supports several metadata fields and options:
|
||||
|
||||
```typescript
|
||||
interface Plugin {
|
||||
// Required fields
|
||||
id: string; // Unique identifier (lowercase, dashes)
|
||||
name: string; // Display name shown to users
|
||||
description: string; // Brief description of what the plugin does
|
||||
version: string; // Semantic version (e.g., "1.0.0")
|
||||
settings: PluginSettings; // Plugin settings object
|
||||
run: (api: PluginAPI) => void; // Main plugin function
|
||||
|
||||
// Optional fields
|
||||
styles?: string; // CSS styles to inject
|
||||
disableToggle?: boolean; // Show enable/disable toggle in settings
|
||||
defaultEnabled?: boolean; // Start enabled/disabled (requires disableToggle)
|
||||
beta?: boolean; // Show "Beta" tag in settings UI
|
||||
}
|
||||
```
|
||||
|
||||
### Metadata Options
|
||||
|
||||
- **`disableToggle`**: When `true`, users can enable/disable your plugin in the settings page
|
||||
- **`defaultEnabled`**: When `false`, your plugin starts disabled by default (only works with `disableToggle: true`)
|
||||
- **`beta`**: When `true`, displays an orange "Beta" tag next to your plugin name in the settings UI
|
||||
- **`styles`**: CSS string that gets injected into the page when your plugin runs
|
||||
|
||||
## SEQTA API
|
||||
|
||||
The SEQTA API helps you interact with SEQTA's pages:
|
||||
|
||||
```typescript
|
||||
import type { Plugin } from "@/plugins/core/types";
|
||||
|
||||
const seqtaPlugin: Plugin<typeof settings> = {
|
||||
id: "seqta-example",
|
||||
name: "SEQTA Example",
|
||||
description: "Shows how to use the SEQTA API",
|
||||
version: "1.0.0",
|
||||
settings: {},
|
||||
disableToggle: true,
|
||||
|
||||
run: async (api) => {
|
||||
// Wait for elements to appear
|
||||
const { unregister: timetableUnregister } = api.seqta.onMount(
|
||||
".timetable",
|
||||
(timetable) => {
|
||||
const button = document.createElement("button");
|
||||
button.textContent = "Export";
|
||||
timetable.appendChild(button);
|
||||
},
|
||||
);
|
||||
|
||||
// Track page changes
|
||||
const { unregister: pageUnregister } = api.seqta.onPageChange((page) => {
|
||||
console.log("User went to:", page);
|
||||
});
|
||||
|
||||
// Clean up when disabled
|
||||
return () => {
|
||||
timetableUnregister();
|
||||
pageUnregister();
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
export default seqtaPlugin;
|
||||
```
|
||||
|
||||
## Settings API
|
||||
|
||||
Here's how to add settings to your plugin:
|
||||
|
||||
```typescript
|
||||
import type { Plugin } from "@/plugins/core/types";
|
||||
import { BasePlugin } from "@/plugins/core/settings";
|
||||
import {
|
||||
booleanSetting,
|
||||
stringSetting,
|
||||
numberSetting,
|
||||
selectSetting,
|
||||
defineSettings,
|
||||
Setting,
|
||||
} from "@/plugins/core/settingsHelpers";
|
||||
|
||||
// Define your settings
|
||||
const settings = defineSettings({
|
||||
darkMode: booleanSetting({
|
||||
default: false,
|
||||
title: "Dark Mode",
|
||||
description: "Enable dark mode",
|
||||
}),
|
||||
userName: stringSetting({
|
||||
default: "",
|
||||
title: "User Name",
|
||||
description: "Your display name",
|
||||
placeholder: "Enter your name...",
|
||||
}),
|
||||
theme: selectSetting({
|
||||
default: "light",
|
||||
title: "Theme",
|
||||
description: "Choose your theme",
|
||||
options: [
|
||||
{ value: "light", label: "Light" },
|
||||
{ value: "dark", label: "Dark" },
|
||||
],
|
||||
}),
|
||||
});
|
||||
|
||||
// Create your settings class
|
||||
class ThemePluginClass extends BasePlugin<typeof settings> {
|
||||
@Setting(settings.darkMode)
|
||||
darkMode!: boolean;
|
||||
|
||||
@Setting(settings.userName)
|
||||
userName!: string;
|
||||
|
||||
@Setting(settings.theme)
|
||||
theme!: string;
|
||||
}
|
||||
|
||||
// Create the plugin
|
||||
const themePlugin: Plugin<typeof settings> = {
|
||||
id: "theme-example",
|
||||
name: "Theme Example",
|
||||
description: "Shows how to use settings",
|
||||
version: "1.0.0",
|
||||
settings: new ThemePluginClass().settings,
|
||||
disableToggle: true,
|
||||
|
||||
run: async (api) => {
|
||||
// Apply initial settings
|
||||
if (api.settings.darkMode) {
|
||||
document.body.classList.add("dark");
|
||||
}
|
||||
|
||||
// Listen for changes
|
||||
const { unregister } = api.settings.onChange("darkMode", (enabled) => {
|
||||
document.body.classList.toggle("dark", enabled);
|
||||
});
|
||||
|
||||
return () => {
|
||||
unregister();
|
||||
document.body.classList.remove("dark");
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
export default themePlugin;
|
||||
```
|
||||
|
||||
## Storage API
|
||||
|
||||
Here's how to use storage in your plugin:
|
||||
|
||||
```typescript
|
||||
import type { Plugin } from "@/plugins/core/types";
|
||||
|
||||
const storagePlugin: Plugin<typeof settings> = {
|
||||
id: "storage-example",
|
||||
name: "Storage Example",
|
||||
description: "Shows how to use storage",
|
||||
version: "1.0.0",
|
||||
settings: {},
|
||||
disableToggle: true,
|
||||
|
||||
run: async (api) => {
|
||||
// Wait for storage to be ready
|
||||
await api.storage.loaded;
|
||||
|
||||
// Save some data
|
||||
await api.storage.set("lastVisit", new Date().toISOString());
|
||||
|
||||
// Get saved data
|
||||
const lastVisit = await api.storage.get("lastVisit");
|
||||
console.log("Last visit:", lastVisit);
|
||||
|
||||
// Listen for changes
|
||||
const { unregister } = api.storage.onChange("lastVisit", (newValue) => {
|
||||
console.log("Last visit updated:", newValue);
|
||||
});
|
||||
|
||||
return () => {
|
||||
unregister();
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
export default storagePlugin;
|
||||
```
|
||||
|
||||
## Events API
|
||||
|
||||
Here's how to use events in your plugin:
|
||||
|
||||
```typescript
|
||||
import type { Plugin } from "@/plugins/core/types";
|
||||
|
||||
const eventsPlugin: Plugin<typeof settings> = {
|
||||
id: "events-example",
|
||||
name: "Events Example",
|
||||
description: "Shows how to use events",
|
||||
version: "1.0.0",
|
||||
settings: {},
|
||||
disableToggle: true,
|
||||
|
||||
run: async (api) => {
|
||||
// Listen for theme changes
|
||||
const { unregister: themeListener } = api.events.on(
|
||||
"theme.changed",
|
||||
(theme) => {
|
||||
console.log("Theme changed to:", theme);
|
||||
},
|
||||
);
|
||||
|
||||
// Listen for notifications
|
||||
const { unregister: notifyListener } = api.events.on(
|
||||
"notification.new",
|
||||
(notification) => {
|
||||
console.log("New notification:", notification);
|
||||
},
|
||||
);
|
||||
|
||||
// Clean up listeners
|
||||
return () => {
|
||||
themeListener();
|
||||
notifyListener();
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
export default eventsPlugin;
|
||||
```
|
||||
|
||||
## Performance Tips
|
||||
|
||||
Here's how to write efficient plugins:
|
||||
|
||||
```typescript
|
||||
import type { Plugin } from "@/plugins/core/types";
|
||||
|
||||
const efficientPlugin: Plugin<typeof settings> = {
|
||||
id: "efficient-example",
|
||||
name: "Efficient Example",
|
||||
description: "Shows performance best practices",
|
||||
version: "1.0.0",
|
||||
settings: {},
|
||||
disableToggle: true,
|
||||
|
||||
run: async (api) => {
|
||||
// ✅ Good: Use onMount
|
||||
const { unregister } = api.seqta.onMount(".timetable", (el) => {
|
||||
el.classList.add("enhanced");
|
||||
});
|
||||
|
||||
// ❌ Bad: Don't use intervals
|
||||
// const interval = setInterval(() => {
|
||||
// const el = document.querySelector('.timetable');
|
||||
// if (el) el.classList.add('enhanced');
|
||||
// }, 100);
|
||||
|
||||
// ✅ Good: Cache DOM elements
|
||||
const header = document.querySelector(".header");
|
||||
if (header) {
|
||||
// Reuse header instead of querying again
|
||||
}
|
||||
|
||||
// ✅ Good: Batch DOM updates
|
||||
const fragment = document.createDocumentFragment();
|
||||
for (let i = 0; i < 10; i++) {
|
||||
const div = document.createElement("div");
|
||||
fragment.appendChild(div);
|
||||
}
|
||||
document.body.appendChild(fragment);
|
||||
|
||||
return () => {
|
||||
unregister();
|
||||
// clearInterval(interval); // If you used the bad approach
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
export default efficientPlugin;
|
||||
```
|
||||
|
||||
Each plugin should be in its own file and exported as the default export. The plugin should:
|
||||
|
||||
1. Import necessary types and helpers
|
||||
2. Define settings if needed
|
||||
3. Create a settings class if using settings
|
||||
4. Create the plugin object with proper type annotation
|
||||
5. Export the plugin as default
|
||||
|
||||
Remember to always:
|
||||
|
||||
- Use proper TypeScript types
|
||||
- Clean up when your plugin is disabled
|
||||
- Handle errors gracefully
|
||||
- Follow the plugin structure shown above
|
||||
+17
-14
@@ -1,17 +1,20 @@
|
||||
export default {
|
||||
preset: 'ts-jest',
|
||||
testEnvironment: 'node',
|
||||
roots: ['<rootDir>/src'],
|
||||
testMatch: [
|
||||
'**/__tests__/**/*.ts',
|
||||
'**/?(*.)+(spec|test).ts'
|
||||
],
|
||||
preset: "ts-jest",
|
||||
testEnvironment: "node",
|
||||
roots: ["<rootDir>/src"],
|
||||
testMatch: ["**/__tests__/**/*.ts", "**/?(*.)+(spec|test).ts"],
|
||||
transform: {
|
||||
'^.+\\.ts$': 'ts-jest',
|
||||
"^.+\\.ts$": "ts-jest",
|
||||
"^.+\\.js$": ["ts-jest", { tsconfig: { allowJs: true } }],
|
||||
},
|
||||
moduleFileExtensions: ['ts', 'js', 'json'],
|
||||
collectCoverageFrom: [
|
||||
'src/**/*.ts',
|
||||
'!src/**/*.d.ts',
|
||||
],
|
||||
};
|
||||
transformIgnorePatterns: ["/node_modules/(?!(color|color-string|color-convert|color-name)/)"],
|
||||
moduleNameMapper: {
|
||||
"^@/(.*)\\?script(?:&(?:iife|module))?$": "<rootDir>/src/test/mocks/crxjsScriptPath.ts",
|
||||
"^@/lib/browser$": "<rootDir>/src/test/mocks/browser.ts",
|
||||
"^@/(.*)$": "<rootDir>/src/$1",
|
||||
"^color$": "<rootDir>/src/test/mocks/color.ts",
|
||||
},
|
||||
setupFilesAfterEnv: ["<rootDir>/src/test/jest.setup.ts"],
|
||||
moduleFileExtensions: ["ts", "js", "json"],
|
||||
collectCoverageFrom: ["src/**/*.ts", "!src/**/*.d.ts"],
|
||||
};
|
||||
+3
-35
@@ -1,42 +1,10 @@
|
||||
import fs from "fs";
|
||||
import fs from "node:fs";
|
||||
import mime from "mime-types";
|
||||
|
||||
/**
|
||||
* A Vite plugin designed to load files as base64 encoded data URLs.
|
||||
* This plugin intercepts module imports that have a `?base64` query parameter
|
||||
* appended to the file path. It then reads the targeted file, converts its content
|
||||
* to a base64 string, and constructs a data URL which is then exported as the
|
||||
* default export of a new JavaScript module.
|
||||
*
|
||||
* @example
|
||||
* // To use this loader, import a file with ?base64 query:
|
||||
* // import myImageBase64 from './path/to/myimage.png?base64';
|
||||
* // myImageBase64 will then be a string like "data:image/png;base64,..."
|
||||
*/
|
||||
export const base64Loader = {
|
||||
/**
|
||||
* The name of the Vite plugin.
|
||||
* @type {string}
|
||||
*/
|
||||
name: "base64-loader",
|
||||
/**
|
||||
* The core transformation function of the Vite plugin.
|
||||
* It is called by Vite for modules that might need transformation. This function
|
||||
* checks if the module ID includes the `?base64` query. If so, it reads the
|
||||
* specified file, converts it to a base64 data URL, and returns a new
|
||||
* JavaScript module that default exports this data URL.
|
||||
*
|
||||
* @param {any} _ The original code of the file. This parameter is unused by this loader.
|
||||
* @param {string} id The ID of the module being transformed. This string typically
|
||||
* contains the absolute file path and any query parameters
|
||||
* (e.g., "/path/to/file.png?base64").
|
||||
* @returns {string | null} If the module ID does not contain `?base64` query,
|
||||
* it returns `null` to indicate no transformation.
|
||||
* Otherwise, it returns a string of JavaScript code
|
||||
* that default exports the base64 data URL of the file.
|
||||
* For example: `export default 'data:image/png;base64,xxxx';`
|
||||
*/
|
||||
transform(_: any, id: string) {
|
||||
transform(_sourceCode: string, id: string) {
|
||||
void _sourceCode;
|
||||
const [filePath, query] = id.split("?");
|
||||
if (query !== "base64") return null;
|
||||
|
||||
|
||||
@@ -1,58 +0,0 @@
|
||||
// ref: https://stackoverflow.com/a/76920975
|
||||
import type { Plugin } from "vite";
|
||||
|
||||
/**
|
||||
* Creates a Vite plugin designed to gracefully handle the conclusion of the build process.
|
||||
* This plugin utilizes the `buildEnd` and `closeBundle` hooks provided by Vite.
|
||||
* It checks for errors at the end of the build:
|
||||
* - If an error occurred during the build (`buildEnd` hook receives an error), it logs the error
|
||||
* and explicitly exits the Node.js process with a status code of 1 (indicating failure).
|
||||
* - If the build completes without errors and the bundle is successfully generated
|
||||
* (`closeBundle` hook is called), it logs a success message and exits the process
|
||||
* with a status code of 0 (indicating success).
|
||||
* This explicit process exiting can be useful in CI/CD environments or scripts that
|
||||
* rely on the process status code to determine the build outcome.
|
||||
* The core logic for using these hooks to exit the process is inspired by
|
||||
* a solution found on StackOverflow (https://stackoverflow.com/a/76920975).
|
||||
*
|
||||
* @returns {Plugin} A Vite plugin object configured with `name`, `buildEnd`, and `closeBundle` hooks.
|
||||
*/
|
||||
export default function ClosePlugin(): Plugin {
|
||||
return {
|
||||
/**
|
||||
* The unique name of this Vite plugin. This name is used by Vite for identification
|
||||
* purposes and will appear in warnings, errors, and logs related to this plugin.
|
||||
* @type {string}
|
||||
*/
|
||||
name: "ClosePlugin", // required, will show up in warnings and errors
|
||||
|
||||
/**
|
||||
* A Vite hook that is called when the build process has finished, regardless of
|
||||
* whether it was successful or encountered an error.
|
||||
*
|
||||
* @param {Error} [error] An optional error object. If the build failed, this parameter
|
||||
* will contain the error that occurred. If the build was successful,
|
||||
* this parameter will be undefined or null.
|
||||
*/
|
||||
buildEnd(error) {
|
||||
if (error) {
|
||||
console.error("Error bundling");
|
||||
console.error(error);
|
||||
process.exit(1); // Exit with status 1 indicating an error
|
||||
} else {
|
||||
console.log("Build ended"); // Log successful completion of the build phase
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* A Vite hook that is called after the `buildEnd` hook, but only if the build
|
||||
* was successful (i.e., no errors were passed to `buildEnd`) and all output
|
||||
* files have been generated and written to disk. This signifies the successful
|
||||
* completion of the entire bundling process.
|
||||
*/
|
||||
closeBundle() {
|
||||
console.log("Bundle closed"); // Log successful closure of the bundle
|
||||
process.exit(0); // Exit with status 0 indicating a successful build
|
||||
},
|
||||
};
|
||||
}
|
||||
+3
-44
@@ -1,46 +1,5 @@
|
||||
import type { Browser, BuildTarget, Manifest } from "./types";
|
||||
import type { AnyCase } from "./utils";
|
||||
import type { Browser, BuildTarget, Manifest } from "./types.ts";
|
||||
|
||||
/**
|
||||
* Packages a given manifest object with a specific target browser identifier.
|
||||
* This function is typically used in multi-browser extension build processes
|
||||
* to create a configuration object that pairs the manifest data with the browser
|
||||
* it's intended for. The `AnyCase<Browser>` type for the browser parameter
|
||||
* implies that browser names like 'chrome', 'firefox', etc., can be provided
|
||||
* in various casings.
|
||||
*
|
||||
* @export
|
||||
* @param {Manifest} manifest The core manifest data for the extension,
|
||||
* compatible with `chrome.runtime.ManifestV3` as defined by the {@link Manifest} type.
|
||||
* @param {AnyCase<Browser>} browser The target browser identifier (e.g., 'chrome', 'firefox', 'CHROME').
|
||||
* Refers to the {@link Browser} type, allowing for flexible casing.
|
||||
* @returns {BuildTarget} An object that pairs the `manifest` with its target `browser`.
|
||||
* The structure is `{ manifest: Manifest; browser: AnyCase<Browser>; }`
|
||||
* as defined by the {@link BuildTarget} type.
|
||||
*/
|
||||
export function createManifest(
|
||||
manifest: Manifest,
|
||||
browser: AnyCase<Browser>,
|
||||
): BuildTarget {
|
||||
return {
|
||||
manifest,
|
||||
browser,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Defines a base manifest object.
|
||||
* This function is typically used to establish a common, shared foundation for an extension's manifest
|
||||
* (compatible with `chrome.runtime.ManifestV3` as per the {@link Manifest} type).
|
||||
* This base can then be extended or modified for different browsers or specific build configurations.
|
||||
* For example, you might define core permissions and properties here, and then add
|
||||
* browser-specific keys in subsequent steps.
|
||||
*
|
||||
* @export
|
||||
* @param {Manifest} manifest The core manifest data to be used as a base.
|
||||
* This should conform to the {@link Manifest} type structure.
|
||||
* @returns {Manifest} The provided manifest object, intended to serve as a reusable base.
|
||||
*/
|
||||
export function createManifestBase(manifest: Manifest): Manifest {
|
||||
return manifest;
|
||||
export function createManifest(manifest: Manifest, browser: Browser): BuildTarget {
|
||||
return { manifest, browser };
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import type { Plugin } from "vite";
|
||||
|
||||
/** Relative chunk/CSS URLs via chrome.runtime.getURL for content-script dynamic imports. */
|
||||
export function extensionChunkUrls(): Plugin {
|
||||
return {
|
||||
name: "extension-chunk-urls",
|
||||
config() {
|
||||
return {
|
||||
base: "./",
|
||||
experimental: {
|
||||
renderBuiltUrl(filename, { hostType, type }) {
|
||||
const path = filename.replace(/^\//, "");
|
||||
if (type === "chunk" && hostType === "js") {
|
||||
return { runtime: `chrome.runtime.getURL(${JSON.stringify(path)})` };
|
||||
}
|
||||
// JS-triggered CSS preloads only — extension HTML pages need static hrefs.
|
||||
if (type === "asset" && hostType === "js" && path.endsWith(".css")) {
|
||||
return { runtime: `chrome.runtime.getURL(${JSON.stringify(path)})` };
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import type { Plugin } from "vite";
|
||||
|
||||
/**
|
||||
* Firefox extension pages forbid eval / `Function` constructor. Some deps still emit:
|
||||
* - `Function(\`return this\`)()` (lodash-style global)
|
||||
* - `try { return Function(\`\`) / new Function("") … }` (feature probes, e.g. PDF.js / ORT)
|
||||
*/
|
||||
export function firefoxStripFunctionProbe(): Plugin {
|
||||
return {
|
||||
name: "firefox-strip-function-probe",
|
||||
apply: "build",
|
||||
enforce: "post",
|
||||
generateBundle(_options, bundle) {
|
||||
if ((process.env.MODE || "chrome").toLowerCase() !== "firefox") return;
|
||||
|
||||
const literalReplacements: [string, string][] = [
|
||||
['try{return new Function(""),!0}catch{return!1}', "return!1"],
|
||||
["try{return new Function(''),!0}catch{return!1}", "return!1"],
|
||||
['try{return new Function(""),true}catch{return false}', "return false"],
|
||||
["try{return new Function(''),true}catch{return false}", "return false"],
|
||||
// Empty template literal probe (minifier output)
|
||||
["try{return Function(``),!0}catch{return!1}", "return!1"],
|
||||
];
|
||||
|
||||
for (const chunk of Object.values(bundle)) {
|
||||
if (chunk.type !== "chunk" || typeof chunk.code !== "string") continue;
|
||||
let { code } = chunk;
|
||||
|
||||
code = code.replace(/Function\(`return this`\)\(\)/g, "(globalThis)");
|
||||
code = code.replace(/Function\("return this"\)\(\)/g, "(globalThis)");
|
||||
code = code.replace(/Function\('return this'\)\(\)/g, "(globalThis)");
|
||||
|
||||
for (const [from, to] of literalReplacements) {
|
||||
if (code.includes(from)) {
|
||||
code = code.split(from).join(to);
|
||||
}
|
||||
}
|
||||
|
||||
chunk.code = code;
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import type { Plugin } from "vite";
|
||||
|
||||
/**
|
||||
* crxjs 2.6.x only replaces the first `__LIVE_RELOAD__` in `@crx/client-worker`,
|
||||
* which crashes the service worker when the dev server reconnects.
|
||||
*/
|
||||
export default function fixCrxWorkerLiveReload(): Plugin {
|
||||
return {
|
||||
name: "fix-crx-worker-live-reload",
|
||||
apply: "serve",
|
||||
enforce: "post",
|
||||
transform(code, id) {
|
||||
if (!id.includes("@crx/client-worker") || !code.includes("__LIVE_RELOAD__")) {
|
||||
return;
|
||||
}
|
||||
return code.replaceAll("__LIVE_RELOAD__", "true");
|
||||
},
|
||||
};
|
||||
}
|
||||
+28
-58
@@ -1,70 +1,40 @@
|
||||
// vite-plugin-inline-worker-dev.ts
|
||||
// vite-plugin-inline-worker-dev.ts
|
||||
import { Plugin } from "vite";
|
||||
import fs from "fs/promises";
|
||||
import { build } from "esbuild";
|
||||
import { resolve } from "node:path";
|
||||
|
||||
/**
|
||||
* Creates a Vite plugin designed for bundling and inlining web worker scripts during development.
|
||||
* This plugin specifically targets module imports that include a `?inlineWorker` query parameter.
|
||||
* When such an import is encountered, the plugin bundles the worker script using `esbuild`
|
||||
* and then generates JavaScript code that inlines this bundled worker as a Blob,
|
||||
* creating the worker instance via `URL.createObjectURL()`.
|
||||
* The name "vite:inline-worker-dev" suggests it's primarily intended for development builds.
|
||||
*
|
||||
* @returns {Plugin} A Vite plugin object with `name` and `load` properties.
|
||||
*/
|
||||
/** Bundle worker entry points imported with `?inlineWorker` as Blob-backed Workers in dev. */
|
||||
export default function InlineWorkerDevPlugin(): Plugin {
|
||||
return {
|
||||
/**
|
||||
* The unique name of this Vite plugin.
|
||||
* @type {string}
|
||||
*/
|
||||
name: "vite:inline-worker-dev",
|
||||
/**
|
||||
* The Vite hook responsible for loading and transforming modules.
|
||||
* This function intercepts modules imported with `?inlineWorker`.
|
||||
* For such modules, it bundles the worker script and returns JavaScript code
|
||||
* that, when executed, will create an instance of this worker from an inlined Blob.
|
||||
*
|
||||
* @async
|
||||
* @param {string} id The path or ID of the module Vite is attempting to load,
|
||||
* potentially including query parameters (e.g., "/path/to/worker.ts?inlineWorker").
|
||||
* @returns {Promise<string | null>} A promise that resolves to:
|
||||
* - `null` if the module ID does not include `?inlineWorker`.
|
||||
* - A string of JavaScript code if the module is an inline worker.
|
||||
* This code will define a default export function (e.g., `InlineWorker`)
|
||||
* that, when called, creates and returns a new `Worker` instance
|
||||
* from the bundled and inlined worker script.
|
||||
*/
|
||||
async load(id) {
|
||||
if (id.includes("?inlineWorker")) {
|
||||
const [cleanPath] = id.split("?");
|
||||
// Note: Original code had `await fs.readFile(cleanPath, "utf-8");` but `code` wasn't used.
|
||||
// `esbuild` directly takes `cleanPath` as an entry point.
|
||||
const result = await build({
|
||||
entryPoints: [cleanPath], // esbuild uses the file path directly
|
||||
bundle: true,
|
||||
write: false, // We want the output in memory, not written to disk
|
||||
platform: "browser", // Target environment for the worker code
|
||||
format: "iife", // Immediately Invoked Function Expression, suitable for workers
|
||||
target: "esnext", // Transpile to modern JavaScript
|
||||
});
|
||||
if (!id.includes("?inlineWorker")) return null;
|
||||
|
||||
const workerCode = result.outputFiles[0].text;
|
||||
const [cleanPath] = id.split("?");
|
||||
const result = await build({
|
||||
entryPoints: [cleanPath],
|
||||
bundle: true,
|
||||
write: false,
|
||||
platform: "browser",
|
||||
format: "iife",
|
||||
target: "esnext",
|
||||
minify: true,
|
||||
conditions: ["onnxruntime-web-use-extern-wasm"],
|
||||
alias: {
|
||||
"@huggingface/transformers": resolve(
|
||||
"node_modules/@huggingface/transformers/dist/transformers.web.js",
|
||||
),
|
||||
},
|
||||
external: ["@/lib/browser"],
|
||||
});
|
||||
|
||||
// Construct JavaScript code that will create the worker from a Blob.
|
||||
// This code is what gets returned to Vite and replaces the original import.
|
||||
const workerBlobCode = `
|
||||
const code = ${JSON.stringify(workerCode)};
|
||||
export default function InlineWorker() {
|
||||
const blob = new Blob([code], { type: 'application/javascript' });
|
||||
return new Worker(URL.createObjectURL(blob), { type: 'module' });
|
||||
}
|
||||
`;
|
||||
return workerBlobCode;
|
||||
}
|
||||
return null; // Let Vite handle other modules normally
|
||||
const workerCode = result.outputFiles[0].text;
|
||||
return `
|
||||
const code = ${JSON.stringify(workerCode)};
|
||||
export default function InlineWorker() {
|
||||
const blob = new Blob([code], { type: 'application/javascript' });
|
||||
return new Worker(URL.createObjectURL(blob), { type: 'module' });
|
||||
}
|
||||
`;
|
||||
},
|
||||
};
|
||||
}
|
||||
+10
-66
@@ -11,35 +11,17 @@
|
||||
* or `node lib/publish.js --b firefox`
|
||||
*/
|
||||
|
||||
const glob = require("glob");
|
||||
const semver = require("semver");
|
||||
const { execSync } = require("child_process");
|
||||
const path = require("path");
|
||||
import { globSync } from "node:fs";
|
||||
import semver from "semver";
|
||||
import { execSync } from "node:child_process";
|
||||
|
||||
/**
|
||||
* Determines the latest version string from a list of filenames that include version numbers.
|
||||
* Filenames are expected to follow a pattern like `betterseqtaplus@3.4.5.1-chrome.zip`.
|
||||
* This function handles potential 4-part versions (e.g., `3.4.5.1`) by trimming them
|
||||
* to 3 parts (e.g., `3.4.5`) for comparison using the `semver` library. After identifying
|
||||
* the latest semver-compatible version, it returns the original full version string
|
||||
* (e.g., "3.4.5.1") that corresponds to this latest version.
|
||||
*
|
||||
* @param {string[]} files An array of filenames.
|
||||
* @returns {string | null} The latest version string (e.g., "3.4.5.1") found among the files,
|
||||
* or `null` if no valid version numbers are found or no files are provided.
|
||||
*/
|
||||
function getLatestVersion(files) {
|
||||
console.log("Files passed to getLatestVersion:", files);
|
||||
|
||||
const versions = files
|
||||
.map((file) => {
|
||||
const match = file.match(/@([\d\.]+)-/);
|
||||
console.log(
|
||||
"Matching file:",
|
||||
file,
|
||||
"Version found:",
|
||||
match ? match[1] : "None",
|
||||
);
|
||||
const match = file.match(/@([\d.]+)-/);
|
||||
console.log("Matching file:", file, "Version found:", match ? match[1] : "None");
|
||||
|
||||
if (!match) return null;
|
||||
|
||||
@@ -74,31 +56,18 @@ function getLatestVersion(files) {
|
||||
}
|
||||
|
||||
// Get the original full version string that matches the identified latest SemVer version
|
||||
const latestVersionData = versions.find(
|
||||
(v) => v.semverVersion === latestSemver,
|
||||
);
|
||||
const latestVersionData = versions.find((v) => v.semverVersion === latestSemver);
|
||||
const latestFullVersion = latestVersionData ? latestVersionData.fullVersion : null;
|
||||
|
||||
console.log("Final selected latest version:", latestFullVersion);
|
||||
return latestFullVersion;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the path to the latest built ZIP file for a specific browser.
|
||||
* It constructs a glob pattern based on the browser name (e.g., `dist/betterseqtaplus@*-*chrome.zip`),
|
||||
* finds all matching files, and then uses `getLatestVersion` to identify the version string
|
||||
* of the most recent file. Finally, it returns the full path to that specific file.
|
||||
*
|
||||
* @param {string} browser A string indicating the target browser (e.g., "chrome", "firefox").
|
||||
* @returns {string | undefined} The filepath string to the latest ZIP file for the specified browser,
|
||||
* or `undefined` if no matching file is found or if the latest version
|
||||
* cannot be determined.
|
||||
*/
|
||||
function getLatestFiles(browser) {
|
||||
const pattern = `dist/betterseqtaplus@*-*${browser}.zip`;
|
||||
console.log("Glob pattern:", pattern);
|
||||
|
||||
const files = glob.sync(pattern);
|
||||
const files = globSync(pattern);
|
||||
console.log("Files found for browser", browser, ":", files);
|
||||
|
||||
if (files.length === 0) {
|
||||
@@ -119,14 +88,6 @@ function getLatestFiles(browser) {
|
||||
return latestFile;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a ZIP file of the project's source code, excluding specified development-related
|
||||
* files and directories such as `node_modules`, `dist`, `.git`, etc.
|
||||
* It uses the `7z` command-line tool to perform the archiving.
|
||||
* The output filename is fixed as `dist/betterseqtaplus@latest-sources.zip`.
|
||||
*
|
||||
* @returns {string} The filename of the created ZIP file (e.g., `dist/betterseqtaplus@latest-sources.zip`).
|
||||
*/
|
||||
function zipSources() {
|
||||
const zipFileName = `dist/betterseqtaplus@latest-sources.zip`;
|
||||
|
||||
@@ -144,7 +105,7 @@ function zipSources() {
|
||||
.join(" ");
|
||||
|
||||
// Command to zip the current directory's contents into zipFileName, applying exclude patterns
|
||||
const zipCommand = `7z a ${zipFileName} . ${excludePatterns}`;
|
||||
const zipCommand = `7zz a ${zipFileName} . ${excludePatterns}`;
|
||||
|
||||
console.log("Zipping project sources with command:", zipCommand);
|
||||
execSync(zipCommand, { stdio: "inherit" }); // Execute synchronously and show output
|
||||
@@ -152,26 +113,9 @@ function zipSources() {
|
||||
return zipFileName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Orchestrates the extension publishing process for the specified browsers.
|
||||
* This function performs the following steps:
|
||||
* 1. Calls `getLatestFiles` to find the latest built ZIP for Chrome if "chrome" is in `browsers`.
|
||||
* 2. Calls `getLatestFiles` to find the latest built ZIP for Firefox if "firefox" is in `browsers`.
|
||||
* 3. Calls `zipSources` to create a source code ZIP if "firefox" is in `browsers` (required for Mozilla Add-ons).
|
||||
* 4. Validates that all required files were found and that at least one browser was specified. Exits if not.
|
||||
* 5. Constructs the `publish-extension` command-line string with the appropriate arguments
|
||||
* based on the found ZIP files for the specified browsers.
|
||||
* 6. Executes the constructed `publish-extension` command.
|
||||
*
|
||||
* @param {string[]} browsers An array of browser strings (e.g., ["chrome", "firefox"]) for which to publish the extension.
|
||||
*/
|
||||
function runPublishCommand(browsers) {
|
||||
const chromeZip = browsers.includes("chrome")
|
||||
? getLatestFiles("chrome")
|
||||
: null;
|
||||
const firefoxZip = browsers.includes("firefox")
|
||||
? getLatestFiles("firefox")
|
||||
: null;
|
||||
const chromeZip = browsers.includes("chrome") ? getLatestFiles("chrome") : null;
|
||||
const firefoxZip = browsers.includes("firefox") ? getLatestFiles("firefox") : null;
|
||||
// Sources are typically only needed for Firefox submissions
|
||||
const firefoxSourcesZip = browsers.includes("firefox") ? zipSources() : null;
|
||||
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import type { Plugin, ViteDevServer } from "vite";
|
||||
|
||||
/**
|
||||
* CRXJS + Vite 6 often corrupt content-script ESM bindings after HMR /
|
||||
* `[crx] runtime reload` — modules load but named/`default` exports are missing
|
||||
* until the dev server is restarted.
|
||||
*
|
||||
* Prefer invalidating the module graph + a full page reload over partial HMR.
|
||||
*/
|
||||
export default function stabilizeCrxDevHmr(): Plugin {
|
||||
let reloadTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
const scheduleFullReload = (s: ViteDevServer) => {
|
||||
if (reloadTimer) clearTimeout(reloadTimer);
|
||||
// Debounce cascading invalidations (e.g. many files in one save).
|
||||
reloadTimer = setTimeout(() => {
|
||||
reloadTimer = null;
|
||||
s.ws.send({ type: "full-reload", path: "*" });
|
||||
}, 50);
|
||||
};
|
||||
|
||||
return {
|
||||
name: "stabilize-crx-dev-hmr",
|
||||
apply: "serve",
|
||||
enforce: "pre",
|
||||
configureServer(s) {
|
||||
s.ws.on("bsplus:reset-module-graph", () => {
|
||||
s.moduleGraph.invalidateAll();
|
||||
scheduleFullReload(s);
|
||||
});
|
||||
},
|
||||
handleHotUpdate({ file, modules, server: viteServer }) {
|
||||
if (!file.replace(/\\/g, "/").includes("/src/")) return;
|
||||
if (file.includes("node_modules")) return;
|
||||
|
||||
const seen = new Set(modules);
|
||||
const queue = [...modules];
|
||||
while (queue.length) {
|
||||
const mod = queue.pop()!;
|
||||
viteServer.moduleGraph.invalidateModule(mod);
|
||||
for (const importer of mod.importers) {
|
||||
if (seen.has(importer)) continue;
|
||||
seen.add(importer);
|
||||
queue.push(importer);
|
||||
}
|
||||
}
|
||||
|
||||
scheduleFullReload(viteServer);
|
||||
// Skip Vite's partial HMR for these modules — it is what leaves exports empty.
|
||||
return [];
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
import fs from "fs";
|
||||
|
||||
/**
|
||||
* Creates a Vite plugin designed to improve the reliability of Hot Module Replacement (HMR)
|
||||
* for global CSS files.
|
||||
*
|
||||
* When a JavaScript/TypeScript module that imports a CSS file is updated, Vite's HMR
|
||||
* might not always reliably update the styles injected by that global CSS. This plugin
|
||||
* attempts to mitigate this by listening for hot updates. If an updated module
|
||||
* has direct importers that are CSS files (e.g., a JS file imports a global CSS file),
|
||||
* this plugin will "touch" those CSS files by updating their access and modification
|
||||
* timestamps using `fs.utimesSync`. This action can help signal to Vite or the browser
|
||||
* that the CSS file has changed, potentially triggering a more reliable style reload.
|
||||
*
|
||||
* @returns {import('vite').Plugin} A Vite plugin object configured with `name` and `handleHotUpdate` hooks.
|
||||
*/
|
||||
export default function touchGlobalCSSPlugin() {
|
||||
return {
|
||||
/**
|
||||
* The unique name of this Vite plugin.
|
||||
* This name is used by Vite for identification purposes and will appear in logs.
|
||||
* @type {string}
|
||||
*/
|
||||
name: "touch-global-css",
|
||||
/**
|
||||
* A Vite hook that is called when a module is hot-updated.
|
||||
* This function inspects the importers of the updated module. If any of these
|
||||
* importers are CSS files, their filesystem timestamps are updated ("touched").
|
||||
*
|
||||
* @param {object} context The context object provided by Vite's `handleHotUpdate` hook.
|
||||
* @param {Array<import('vite').ModuleNode>} context.modules An array of `ModuleNode` instances that have been updated.
|
||||
* This plugin specifically accesses `modules[0]._clientModule.importers`
|
||||
* to find CSS files that import the updated module.
|
||||
*/
|
||||
handleHotUpdate({ modules }) {
|
||||
// It's assumed `modules[0]` is the primary updated module of interest.
|
||||
// `_clientModule` and `importers` might be internal or less stable Vite APIs.
|
||||
const importers = modules[0]?._clientModule?.importers;
|
||||
if (importers) {
|
||||
importers.forEach((importer) => {
|
||||
// Check if the importer is a CSS file
|
||||
if (importer.file && importer.file.includes(".css")) {
|
||||
console.log("[touch-global-css] touching", importer.file);
|
||||
try {
|
||||
// Update the access and modification times of the CSS file to the current time
|
||||
fs.utimesSync(importer.file, new Date(), new Date());
|
||||
} catch (err) {
|
||||
console.error(`[touch-global-css] Error touching file ${importer.file}:`, err);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
+2
-232
@@ -1,240 +1,10 @@
|
||||
import type { ManifestV3Export } from "@crxjs/vite-plugin";
|
||||
import { type AnyCase, createEnum, ObjectValues } from "./utils";
|
||||
|
||||
/**
|
||||
* Enumerates supported JavaScript frameworks for project generation or configuration.
|
||||
*/
|
||||
export const FrameworkEnum = {
|
||||
React: "React",
|
||||
Vanilla: "Vanilla",
|
||||
Preact: "Preact",
|
||||
Lit: "Lit",
|
||||
Svelte: "Svelte",
|
||||
Vue: "Vue",
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* Enumerates supported web browsers, typically for targeting builds or configurations.
|
||||
*/
|
||||
export const BrowserEnum = {
|
||||
Chrome: "Chrome",
|
||||
Brave: "Brave",
|
||||
Opera: "Opera",
|
||||
Edge: "Edge",
|
||||
Firefox: "Firefox",
|
||||
Safari: "Safari",
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* @private
|
||||
* Enumerates supported programming languages for project setup.
|
||||
* This enum is not exported, suggesting it's for internal use within this module or related modules.
|
||||
*/
|
||||
const LanguageEnum = {
|
||||
TypeScript: "TypeScript",
|
||||
JavaScript: "JavaScript",
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* Enumerates supported styling options or libraries.
|
||||
*/
|
||||
export const StyleEnum = {
|
||||
Tailwind: "Tailwind",
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* Enumerates supported package managers.
|
||||
*/
|
||||
export const PackageManagerEnum = {
|
||||
Bun: "Bun",
|
||||
PnPm: "PnPm",
|
||||
Npm: "Npm",
|
||||
Yarn: "Yarn",
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* Defines the structure for browser-specific settings within a web extension manifest.
|
||||
* This is particularly used for Firefox (gecko) extensions to specify properties like
|
||||
* an extension ID, and minimum/maximum supported browser versions.
|
||||
* The structure is based on common manifest extensions for Firefox.
|
||||
* See: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/browser_specific_settings
|
||||
* The link in the original code (// see: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/firefox-webext-browser/index.d.ts)
|
||||
* also points to type definitions that include this structure.
|
||||
*
|
||||
* @property {object} [browser_specific_settings] - Container for browser-specific settings.
|
||||
* @property {object} [browser_specific_settings.gecko] - Settings specific to Gecko-based browsers (e.g., Firefox).
|
||||
* @property {string} [browser_specific_settings.gecko.id] - The unique identifier for the extension in Firefox.
|
||||
* @property {string} [browser_specific_settings.gecko.strict_min_version] - The minimum version of Firefox the extension is compatible with.
|
||||
* @property {string} [browser_specific_settings.gecko.strict_max_version] - The maximum version of Firefox the extension is compatible with.
|
||||
*/
|
||||
export type BrowserSpecificSettings = {
|
||||
browser_specific_settings?: {
|
||||
gecko?: {
|
||||
id: string;
|
||||
strict_min_version?: string;
|
||||
strict_max_version?: string;
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Represents the structure of a Chrome Manifest V3 file.
|
||||
* This type is an alias for `ManifestV3Export` from the `@crxjs/vite-plugin`,
|
||||
* which provides a comprehensive definition for Chrome extension manifests.
|
||||
*/
|
||||
export type Manifest = ManifestV3Export;
|
||||
|
||||
/** Alias for the `icons` property within a Chrome Manifest V3. */
|
||||
export type ManifestIcons = chrome.runtime.ManifestIcons;
|
||||
/** Alias for the `background` property within a Chrome Manifest V3. */
|
||||
export type ManifestBackground = chrome.runtime.ManifestV3["background"];
|
||||
/** Alias for the `content_scripts` property within a Chrome Manifest V3. */
|
||||
export type ManifestContentScripts =
|
||||
chrome.runtime.ManifestV3["content_scripts"];
|
||||
/** Alias for the `web_accessible_resources` property within a Chrome Manifest V3. */
|
||||
export type ManifestWebAccessibleResources =
|
||||
chrome.runtime.ManifestV3["web_accessible_resources"];
|
||||
/** Alias for the `commands` property within a Chrome Manifest V3. */
|
||||
export type ManifestCommands = chrome.runtime.ManifestV3["commands"];
|
||||
/** Alias for the `action` property (or `browser_action`/`page_action`) within a Chrome Manifest V3. */
|
||||
export type ManifestAction = chrome.runtime.ManifestV3["action"];
|
||||
/** Alias for the `permissions` property within a Chrome Manifest V3. */
|
||||
export type ManifestPermissions = chrome.runtime.ManifestV3["permissions"];
|
||||
/** Alias for the `options_ui` property within a Chrome Manifest V3. */
|
||||
export type ManifestOptionsUI = chrome.runtime.ManifestV3["options_ui"];
|
||||
/** Alias for the `chrome_url_overrides` property within a Chrome Manifest V3. */
|
||||
export type ManifestURLOverrides =
|
||||
chrome.runtime.ManifestV3["chrome_url_overrides"];
|
||||
export type Browser = "chrome" | "brave" | "edge" | "firefox" | "opera" | "safari";
|
||||
|
||||
/**
|
||||
* Creates a type that accepts a string literal `T` in either its capitalized or lowercase form.
|
||||
* Useful for defining types that should be case-insensitive for specific known strings.
|
||||
* @template T - A string literal type.
|
||||
*/
|
||||
export type BrowserName<T extends string> = Capitalize<T> | Lowercase<T>;
|
||||
|
||||
/**
|
||||
* Creates a record type where both keys and values are derived from a string literal `T`,
|
||||
* specifically using `BrowserName<T>` which allows for capitalized or lowercase forms.
|
||||
* This could be used to define an object where, for example, keys are 'Chrome' or 'chrome'
|
||||
* and values are also 'Chrome' or 'chrome'.
|
||||
* @template T - A string literal type, typically representing a browser name.
|
||||
*/
|
||||
export type BrowserEnumType<T extends string> = {
|
||||
[browser in BrowserName<T>]: BrowserName<T>;
|
||||
};
|
||||
|
||||
/**
|
||||
* Represents the target browser for a build, allowing for various casings of browser names
|
||||
* (e.g., "chrome", "Chrome", "CHROME") through the `AnyCase<Browser>` utility type.
|
||||
* `Browser` itself is a union of specific browser name strings (e.g., "Chrome" | "Firefox").
|
||||
*/
|
||||
export type BuildMode = AnyCase<Browser>;
|
||||
|
||||
/**
|
||||
* Defines an object structure that pairs a web extension `Manifest`
|
||||
* with its target `browser` (represented as `AnyCase<Browser>`).
|
||||
* This is commonly used in build processes to manage configurations for different browsers.
|
||||
*/
|
||||
export type BuildTarget = {
|
||||
manifest: Manifest;
|
||||
browser: AnyCase<Browser>;
|
||||
browser: Browser;
|
||||
};
|
||||
|
||||
/**
|
||||
* Defines the configuration options for a build process.
|
||||
* @property {"build" | "serve"} [command] - The type of build command (e.g., 'build' for production, 'serve' for development).
|
||||
* @property {AnyCase<Browser> | string | undefined} [mode] - The target build mode, typically a browser name (allowing various casings)
|
||||
* or potentially other custom mode strings.
|
||||
*/
|
||||
export type BuildConfig = {
|
||||
command?: "build" | "serve";
|
||||
mode?: AnyCase<Browser> | string | undefined;
|
||||
};
|
||||
|
||||
/**
|
||||
* Defines the structure for repository information, commonly found in `package.json`.
|
||||
* @property {string} type - The type of the repository (e.g., "git").
|
||||
* @property {string} [url] - The URL of the repository.
|
||||
* @property {Bugs} [bugs] - An object containing information about where to report bugs.
|
||||
*/
|
||||
export interface Repository {
|
||||
type: string;
|
||||
url?: string;
|
||||
bugs?: Bugs;
|
||||
}
|
||||
|
||||
/**
|
||||
* Defines the structure for bug reporting information, often part of the `Repository` interface.
|
||||
* @property {string} [url] - The URL of the issue tracker.
|
||||
* @property {string} [email] - The email address for reporting bugs.
|
||||
*/
|
||||
export interface Bugs {
|
||||
url?: string;
|
||||
email?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* A string literal union type representing supported browser names, derived from the values of `BrowserEnum`.
|
||||
* e.g., "Chrome" | "Firefox" | ...
|
||||
*/
|
||||
export type Browser = ObjectValues<typeof BrowserEnum>;
|
||||
|
||||
/**
|
||||
* A constant intended to provide access to browser names, potentially in various casings.
|
||||
* Its type `AnyCase<Browser>` suggests it can be used where case-insensitivity for browser names is needed.
|
||||
* The `createEnum(BrowserEnum)` call aims to produce a representation of browser names from `BrowserEnum`.
|
||||
* Note: `createEnum` from `lib/utils.ts` has a declared return type of `ObjectValues<T>` (a union of values),
|
||||
* while its implementation uses `Object.values()` which returns an array. This constant will hold the
|
||||
* runtime array value, but its JSDoc type refers to the more restrictive `AnyCase<Browser>` union type.
|
||||
*/
|
||||
export const Browser: AnyCase<Browser> = createEnum(BrowserEnum);
|
||||
|
||||
/**
|
||||
* A string literal union type representing supported package managers, derived from the values of `PackageManagerEnum`.
|
||||
* e.g., "Bun" | "PnPm" | "Npm" | "Yarn"
|
||||
*/
|
||||
export type PackageManager = ObjectValues<typeof PackageManagerEnum>;
|
||||
/**
|
||||
* A constant intended to provide access to package manager names, potentially in various casings.
|
||||
* Its type `AnyCase<PackageManager>` suggests it can be used where case-insensitivity for package manager names is needed.
|
||||
* Utilizes `createEnum(PackageManagerEnum)`. Refer to notes on `Browser` constant regarding `createEnum` behavior.
|
||||
*/
|
||||
export const PackageManager: AnyCase<PackageManager> =
|
||||
createEnum(PackageManagerEnum);
|
||||
|
||||
/**
|
||||
* A string literal union type representing supported JavaScript frameworks, derived from the values of `FrameworkEnum`.
|
||||
* e.g., "React" | "Vanilla" | ...
|
||||
*/
|
||||
export type Framework = ObjectValues<typeof FrameworkEnum>;
|
||||
/**
|
||||
* A constant intended to provide access to framework names, potentially in various casings.
|
||||
* Its type `AnyCase<Framework>` suggests it can be used where case-insensitivity for framework names is needed.
|
||||
* Utilizes `createEnum(FrameworkEnum)`. Refer to notes on `Browser` constant regarding `createEnum` behavior.
|
||||
*/
|
||||
export const Framework: AnyCase<Framework> = createEnum(FrameworkEnum);
|
||||
|
||||
/**
|
||||
* A string literal union type representing supported styling options, derived from the values of `StyleEnum`.
|
||||
* e.g., "Tailwind"
|
||||
*/
|
||||
export type Style = ObjectValues<typeof StyleEnum>;
|
||||
/**
|
||||
* A constant intended to provide access to style option names, potentially in various casings.
|
||||
* Its type `AnyCase<Style>` suggests it can be used where case-insensitivity for style names is needed.
|
||||
* Utilizes `createEnum(StyleEnum)`. Refer to notes on `Browser` constant regarding `createEnum` behavior.
|
||||
*/
|
||||
export const Style: AnyCase<Style> = createEnum(StyleEnum);
|
||||
|
||||
/**
|
||||
* A string literal union type representing supported programming languages, derived from the values of `LanguageEnum`.
|
||||
* e.g., "TypeScript" | "JavaScript"
|
||||
*/
|
||||
export type Language = ObjectValues<typeof LanguageEnum>;
|
||||
/**
|
||||
* A constant intended to provide access to programming language names, potentially in various casings.
|
||||
* Its type `AnyCase<Language>` suggests it can be used where case-insensitivity for language names is needed.
|
||||
* Utilizes `createEnum(LanguageEnum)`. Refer to notes on `Browser` constant regarding `createEnum` behavior.
|
||||
*/
|
||||
export const Language: AnyCase<Language> = createEnum(LanguageEnum);
|
||||
@@ -1,84 +0,0 @@
|
||||
/**
|
||||
* Extracts a union type of all values from the properties of an object type `T`.
|
||||
*
|
||||
* @template T - An object type (typically a Record or an enum-like object).
|
||||
* @example
|
||||
* type MyObject = { a: "foo", b: "bar", c: 123 };
|
||||
* type MyObjectValues = ObjectValues<MyObject>; // "foo" | "bar" | 123
|
||||
*/
|
||||
export type ObjectValues<T> = T[keyof T];
|
||||
|
||||
/**
|
||||
* Creates a union of an object's string values, often used to represent the set of possible values for an enum-like object.
|
||||
* Note: The implementation `Object.values(enumObj) as unknown as ObjectValues<T>` returns an array at runtime,
|
||||
* but the declared return type `ObjectValues<T>` is a union of the object's property values.
|
||||
* This type signature suggests it's intended to represent the set of possible string values from `enumObj`.
|
||||
*
|
||||
* @template T - An object type where keys are strings and values are strings (e.g., `const MyEnum = { VAL_A: "A", VAL_B: "B" }`).
|
||||
* @param {T} enumObj - The object from which to extract values.
|
||||
* @returns {ObjectValues<T>} A union type representing all possible string values of the `enumObj`.
|
||||
* For example, if `enumObj` is `{ A: "valA", B: "valB" }`, the return type is `"valA" | "valB"`.
|
||||
* (Runtime behavior of `Object.values()` is to return an array like `["valA", "valB"]`).
|
||||
*/
|
||||
export function createEnum<T extends Record<string, string>>(enumObj: T) {
|
||||
return Object.values(enumObj) as unknown as ObjectValues<T>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a union type that includes various case formats (uppercase, lowercase, capitalized, uncapitalized)
|
||||
* of a given string literal type `T`.
|
||||
*
|
||||
* @template T - A string literal type.
|
||||
* @example
|
||||
* type MyString = "example";
|
||||
* type MyStringAnyCase = AnyCase<MyString>; // "EXAMPLE" | "example" | "Example" | "example" (Uncapitalize<"Example"> is "example")
|
||||
*/
|
||||
export type AnyCase<T extends string> =
|
||||
| Uppercase<T>
|
||||
| Lowercase<T>
|
||||
| Capitalize<T>
|
||||
| Uncapitalize<T>;
|
||||
|
||||
/**
|
||||
* Creates a union type that includes various case formats (uppercase, lowercase, capitalized, uncapitalized)
|
||||
* of the union of two given string literal types `T` and `K`.
|
||||
* This is useful for representing a combined set of related string constants where case variations are permitted for each.
|
||||
*
|
||||
* @template T - A string literal type.
|
||||
* @template K - Another string literal type.
|
||||
* @example
|
||||
* type Lang1 = "english";
|
||||
* type Lang2 = "french";
|
||||
* type CombinedLangsAnyCase = AnyCaseLanguage<Lang1, Lang2>;
|
||||
* // Result includes: "ENGLISH" | "english" | "English" | "FRENCH" | "french" | "French" etc.
|
||||
* // for all case variations of "english" and "french".
|
||||
*/
|
||||
export type AnyCaseLanguage<T extends string, K extends string> =
|
||||
| Uppercase<T | K>
|
||||
| Lowercase<T | K>
|
||||
| Capitalize<T | K>
|
||||
| Uncapitalize<T | K>;
|
||||
|
||||
/**
|
||||
* Extracts a new object type containing only the keys of `T` whose properties are optional
|
||||
* (i.e., their type includes `undefined`). The values associated with these keys retain their original types.
|
||||
*
|
||||
* @template T - An object type.
|
||||
* @example
|
||||
* type MyObject = {
|
||||
* requiredProp: string;
|
||||
* optionalProp?: number;
|
||||
* anotherOptional?: boolean | undefined;
|
||||
* nullProp: string | null;
|
||||
* };
|
||||
* type MyOptionalProps = OptionalKeys<MyObject>;
|
||||
* // MyOptionalProps would be conceptually equivalent to:
|
||||
* // {
|
||||
* // optionalProp?: number;
|
||||
* // anotherOptional?: boolean | undefined;
|
||||
* // }
|
||||
* // The actual resulting type is an object type with only these optional keys.
|
||||
*/
|
||||
export type OptionalKeys<T> = {
|
||||
[K in keyof T as undefined extends T[K] ? K : never]: T[K];
|
||||
};
|
||||
Generated
+11123
File diff suppressed because it is too large.
Load diff
+97
-91
@@ -1,108 +1,114 @@
|
||||
{
|
||||
"name": "betterseqtaplus",
|
||||
"version": "3.4.11",
|
||||
"version": "3.7.6",
|
||||
"description": "Enhance SEQTA Learn's usability and aesthetics! A fork of BetterSEQTA to continue development and add heaps more features!",
|
||||
"keywords": [],
|
||||
"license": "MIT",
|
||||
"author": {
|
||||
"name": "SethBurkart123",
|
||||
"email": "betterseqta.plus@gmail.com",
|
||||
"url": "https://github.com/BetterSEQTA/BetterSEQTA-Plus"
|
||||
},
|
||||
"type": "module",
|
||||
"description": "Enhance SEQTA Learn's usability and aesthetics! A fork of BetterSEQTA to continue development add add heaps more features!",
|
||||
"browserslist": "> 0.5%, last 2 versions, not dead",
|
||||
"scripts": {
|
||||
"compile:layerchart": "node scripts/compile-layerchart-vendor.mjs",
|
||||
"postinstall": "node scripts/copy-runtime-assets.mjs && npm run compile:layerchart",
|
||||
"autoaudit": "npm audit && npm audit fix && npm run build",
|
||||
"dev": "cross-env MODE=chrome vite dev",
|
||||
"dev:firefox": "cross-env MODE=firefox vite build --watch",
|
||||
"build": "cross-env MODE=chrome vite build && cross-env MODE=firefox vite build",
|
||||
"compile": "npm i && npm run build",
|
||||
"build": "npm run compile:layerchart && cross-env MODE=chrome vite build && cross-env MODE=firefox vite build",
|
||||
"build:chrome": "cross-env MODE=chrome vite build",
|
||||
"build:firefox": "cross-env MODE=firefox vite build",
|
||||
"build:safari": "cross-env MODE=safari vite build",
|
||||
"build:dev": "cross-env MODE=chrome SOURCEMAP=true vite build && cross-env MODE=firefox SOURCEMAP=true vite build",
|
||||
"convert:safari": "xcrun safari-web-extension-converter dist/safari --project-location . --app-name $npm_package_name-safari",
|
||||
"dependency-graph": "depcruise src --include-only \"^src\" --output-type dot | dot -T svg > dependency-graph.svg",
|
||||
"release": "gh release create $npm_package_name@$npm_package_version ./dist/*.zip --generate-notes",
|
||||
"publish": "bun lib/publish.js --b",
|
||||
"zip": "bedframe zip"
|
||||
},
|
||||
"targets": {
|
||||
"prod": {
|
||||
"sourceMap": {
|
||||
"inline": false
|
||||
}
|
||||
}
|
||||
},
|
||||
"keywords": [],
|
||||
"author": {
|
||||
"name": "SethBurkart123",
|
||||
"email": "betterseqta.plus@gmail.com",
|
||||
"url": "https://github.com/BetterSEQTA/BetterSEQTA-plus"
|
||||
},
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"@babel/plugin-transform-runtime": "^7.26.9",
|
||||
"@babel/runtime": "^7.26.9",
|
||||
"@bedframe/cli": "^0.0.95",
|
||||
"@crxjs/vite-plugin": "^2.2.0",
|
||||
"@types/mime-types": "^3.0.1",
|
||||
"@types/react": "^19.0.10",
|
||||
"@types/react-dom": "^19.0.4",
|
||||
"cross-env": "^10.0.0",
|
||||
"dependency-cruiser": "^17.0.1",
|
||||
"eslint": "^9.33.0",
|
||||
"glob": "^11.0.1",
|
||||
"mime-types": "^3.0.1",
|
||||
"prettier": "^3.5.3",
|
||||
"process": "^0.11.10",
|
||||
"publish-browser-extension": "^3.0.1",
|
||||
"sass": "^1.85.1",
|
||||
"sass-loader": "^16.0.5",
|
||||
"semver": "^7.7.1",
|
||||
"tailwindcss": "3",
|
||||
"url": "^0.11.4"
|
||||
"lint": "oxlint --deny-warnings",
|
||||
"format": "oxfmt",
|
||||
"format:check": "oxfmt --check",
|
||||
"typecheck": "svelte-check --tsconfig ./tsconfig.json --fail-on-warnings",
|
||||
"test": "npm run test:unit",
|
||||
"test:unit": "cross-env NODE_OPTIONS=--no-experimental-webstorage jest",
|
||||
"test:smoke": "node scripts/smoke-test.mjs",
|
||||
"test:ci": "npm run test:unit && npm run build && npm run test:smoke",
|
||||
"release": "gh release create $npm_package_version --repo BetterSEQTA/BetterSEQTA-Plus ./dist/*.zip --generate-notes",
|
||||
"publish": "node lib/publish.js --b",
|
||||
"zip": "node scripts/package-extension-zips.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"@bedframe/core": "^0.0.46",
|
||||
"@codemirror/autocomplete": "^6.18.6",
|
||||
"@codemirror/commands": "^6.8.0",
|
||||
"@codemirror/autocomplete": "^6.20.4",
|
||||
"@codemirror/commands": "^6.11.1",
|
||||
"@codemirror/lang-css": "^6.3.1",
|
||||
"@codemirror/language": "^6.10.8",
|
||||
"@codemirror/search": "^6.5.10",
|
||||
"@codemirror/state": "^6.5.2",
|
||||
"@codemirror/view": "^6.36.4",
|
||||
"@sveltejs/vite-plugin-svelte": "^5.0.3",
|
||||
"@tailwindcss/forms": "^0.5.10",
|
||||
"@tsconfig/svelte": "^5.0.4",
|
||||
"@types/chrome": "^0.1.4",
|
||||
"@types/color": "^4.2.0",
|
||||
"@types/lodash": "^4.17.16",
|
||||
"@types/node": "^24.3.0",
|
||||
"@types/sortablejs": "^1.15.8",
|
||||
"@types/uuid": "^10.0.0",
|
||||
"@types/webextension-polyfill": "^0.12.3",
|
||||
"@uiw/codemirror-extensions-color": "^4.23.10",
|
||||
"@uiw/codemirror-theme-github": "^4.23.10",
|
||||
"autoprefixer": "^10.4.21",
|
||||
"canvas-confetti": "^1.9.3",
|
||||
"codemirror": "^6.0.1",
|
||||
"color": "^5.0.0",
|
||||
"dompurify": "^3.2.4",
|
||||
"embeddia": "^1.2.1",
|
||||
"embla-carousel-autoplay": "^8.5.2",
|
||||
"embla-carousel-svelte": "^8.5.2",
|
||||
"esbuild": "^0.25.3",
|
||||
"events": "^3.3.0",
|
||||
"flexsearch": "^0.8.147",
|
||||
"fuse.js": "^7.1.0",
|
||||
"idb": "^8.0.2",
|
||||
"@codemirror/language": "^6.13.1",
|
||||
"@codemirror/search": "^6.7.2",
|
||||
"@codemirror/state": "^6.7.6",
|
||||
"@codemirror/view": "^6.43.15",
|
||||
"@huggingface/transformers": "^3.8.1",
|
||||
"@uiw/codemirror-extensions-color": "^4.25.12",
|
||||
"@uiw/codemirror-theme-github": "^4.25.12",
|
||||
"canvas-confetti": "^1.9.4",
|
||||
"color": "^5.0.3",
|
||||
"d3-scale": "^4.0.2",
|
||||
"d3-shape": "^3.2.0",
|
||||
"dompurify": "^3.4.17",
|
||||
"embeddia": "^1.3.0",
|
||||
"embla-carousel-autoplay": "^8.6.0",
|
||||
"embla-carousel-svelte": "^8.6.0",
|
||||
"fuse.js": "^7.5.0",
|
||||
"layerchart": "^2.9.2",
|
||||
"localforage": "^1.10.0",
|
||||
"lodash": "^4.17.21",
|
||||
"mathjs": "^14.4.0",
|
||||
"million": "^3.1.11",
|
||||
"motion": "^12.4.12",
|
||||
"postcss": "^8.5.3",
|
||||
"react": "17",
|
||||
"react-best-gradient-color-picker": "3.0.11",
|
||||
"react-dom": "17",
|
||||
"rss-parser": "^3.13.0",
|
||||
"sortablejs": "^1.15.6",
|
||||
"svelte": "^5.22.6",
|
||||
"typescript": "^5.8.2",
|
||||
"uuid": "^11.1.0",
|
||||
"vite": "^6.2.1",
|
||||
"webextension-polyfill": "^0.12.0"
|
||||
"mathjs": "^15.2.0",
|
||||
"motion": "^14.9.0",
|
||||
"pdfjs-dist": "^6.5.438",
|
||||
"qrcode": "^1.5.4",
|
||||
"semver": "^7.7.1",
|
||||
"sortablejs": "^1.15.7",
|
||||
"svelte": "^5.57.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@crxjs/vite-plugin": "^3.0.0",
|
||||
"@jest/globals": "30.5.2",
|
||||
"@sveltejs/vite-plugin-svelte": "^7.3.1",
|
||||
"@tailwindcss/forms": "^0.5.11",
|
||||
"@tailwindcss/postcss": "^4.3.3",
|
||||
"@tsconfig/svelte": "^5.0.8",
|
||||
"@types/canvas-confetti": "^1.9.0",
|
||||
"@types/chrome": "^0.3.7",
|
||||
"@types/d3-scale": "^4.0.9",
|
||||
"@types/d3-shape": "^3.2.0",
|
||||
"@types/jest": "^30.0.0",
|
||||
"@types/mime-types": "^3.0.1",
|
||||
"@types/node": "^26.6.6",
|
||||
"@types/qrcode": "^1.5.6",
|
||||
"@types/semver": "^7.8.0",
|
||||
"@types/sortablejs": "^1.15.9",
|
||||
"cross-env": "^10.1.0",
|
||||
"esbuild": "^0.28.2",
|
||||
"jest": "^30.5.2",
|
||||
"jest-environment-jsdom": "^30.5.2",
|
||||
"mime-types": "^3.0.2",
|
||||
"oxfmt": "^0.75.0",
|
||||
"oxlint": "^1.90.0",
|
||||
"publish-browser-extension": "^6.2.0",
|
||||
"sass": "^1.107.1",
|
||||
"svelte-check": "^4.7.8",
|
||||
"tailwindcss": "^4.3.3",
|
||||
"ts-jest": "^29.4.15",
|
||||
"typescript": "~6.0.3",
|
||||
"vite": "^8.3.5"
|
||||
},
|
||||
"overrides": {
|
||||
"glob": "^14.0.3"
|
||||
},
|
||||
"browserslist": "> 0.5%, last 2 versions, not dead",
|
||||
"engines": {
|
||||
"node": ">=26"
|
||||
},
|
||||
"allowScripts": {
|
||||
"@parcel/watcher": false,
|
||||
"esbuild": false,
|
||||
"onnxruntime-node": false,
|
||||
"protobufjs": false,
|
||||
"sharp": false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
/**
|
||||
* Chrome trace analyzer — aggregates hotspots for BetterSEQTA+ optimization.
|
||||
* Usage: node scripts/analyze-trace.mjs <path-to-trace.json>
|
||||
*/
|
||||
import fs from "node:fs";
|
||||
|
||||
const path = process.argv[2];
|
||||
if (!path) {
|
||||
console.error("Usage: node scripts/analyze-trace.mjs <trace.json>");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const raw = fs.readFileSync(path, "utf8");
|
||||
const { traceEvents } = JSON.parse(raw);
|
||||
|
||||
const openStacks = new Map(); // key -> { name, cat, args, ts }
|
||||
|
||||
const byName = new Map();
|
||||
const byCat = new Map();
|
||||
const byUrl = new Map();
|
||||
const byFunction = new Map();
|
||||
const layoutEvents = [];
|
||||
const paintEvents = [];
|
||||
const longTasks = [];
|
||||
const timers = [];
|
||||
const observers = [];
|
||||
const hitTests = [];
|
||||
const betterseqtaHits = new Map();
|
||||
const ipcMessages = new Map();
|
||||
const gcEvents = [];
|
||||
|
||||
let minTs = Infinity;
|
||||
let maxTs = -Infinity;
|
||||
|
||||
function add(map, key, dur, count = 1) {
|
||||
const e = map.get(key) ?? { dur: 0, count: 0 };
|
||||
e.dur += dur;
|
||||
e.count += count;
|
||||
map.set(key, e);
|
||||
}
|
||||
|
||||
for (const ev of traceEvents) {
|
||||
if (ev.ts != null) {
|
||||
minTs = Math.min(minTs, ev.ts);
|
||||
maxTs = Math.max(maxTs, ev.ts);
|
||||
}
|
||||
|
||||
const ph = ev.ph;
|
||||
const name = ev.name ?? "";
|
||||
const cat = ev.cat ?? "";
|
||||
const args = ev.args ?? {};
|
||||
|
||||
if (ph === "b") {
|
||||
openStacks.set(`${ev.pid}:${ev.tid}:${ev.id ?? name}`, ev);
|
||||
continue;
|
||||
}
|
||||
|
||||
let dur = ev.dur ?? 0;
|
||||
if (ph === "e" && ev.id != null) {
|
||||
const start = openStacks.get(`${ev.pid}:${ev.tid}:${ev.id}`);
|
||||
if (start) dur = ev.ts - start.ts;
|
||||
}
|
||||
if (dur <= 0 && ph !== "X") continue;
|
||||
|
||||
add(byName, name, dur);
|
||||
|
||||
const catParts = cat.split(",").filter(Boolean);
|
||||
for (const c of catParts.length ? catParts : [cat || "(none)"]) {
|
||||
add(byCat, c, dur);
|
||||
}
|
||||
|
||||
const url =
|
||||
args.data?.url ?? args.url ?? args.fileName ?? args.data?.scriptName ?? args.data?.frame ?? "";
|
||||
if (url && typeof url === "string" && dur > 0) {
|
||||
add(byUrl, url.slice(0, 200), dur);
|
||||
}
|
||||
|
||||
const fn =
|
||||
(args.data?.functionName ?? args.functionName ?? args.data?.columnNumber != null)
|
||||
? `${args.data?.functionName ?? name}@${args.data?.url ?? ""}:${args.data?.lineNumber ?? "?"}`
|
||||
: "";
|
||||
if (fn && dur > 100) {
|
||||
add(byFunction, String(fn).slice(0, 250), dur);
|
||||
}
|
||||
|
||||
if (/Layout|UpdateLayoutTree|InvalidateLayout|LocalFrameView::performLayout/i.test(name)) {
|
||||
layoutEvents.push({ name, dur, ts: ev.ts, cat });
|
||||
}
|
||||
if (/Paint|Raster|DrawFrame|CompositeLayers|UpdateLayer/i.test(name)) {
|
||||
paintEvents.push({ name, dur, ts: ev.ts });
|
||||
}
|
||||
if (name === "RunTask" && dur > 50000) {
|
||||
longTasks.push({ dur, ts: ev.ts, cat, args: JSON.stringify(args).slice(0, 300) });
|
||||
}
|
||||
if (
|
||||
/Timer|setTimeout|setInterval|FireIdleCallback|requestAnimationFrame|RequestAnimationFrame/i.test(
|
||||
name,
|
||||
)
|
||||
) {
|
||||
timers.push({ name, dur, ts: ev.ts });
|
||||
}
|
||||
if (
|
||||
/MutationObserver|ResizeObserver|IntersectionObserver|DeliverObservations|NotifyMutation/i.test(
|
||||
name,
|
||||
)
|
||||
) {
|
||||
observers.push({ name, dur, ts: ev.ts });
|
||||
}
|
||||
if (/HitTest|FindElement|ElementAt/i.test(name)) {
|
||||
hitTests.push({ name, dur, ts: ev.ts });
|
||||
}
|
||||
if (/V8\.GC|GC_|MajorGC|MinorGC|IncrementalMarking/i.test(name)) {
|
||||
gcEvents.push({ name, dur, ts: ev.ts });
|
||||
}
|
||||
if (/IPC|MessagePort|postMessage/i.test(name)) {
|
||||
add(ipcMessages, name, dur);
|
||||
}
|
||||
|
||||
const blob = JSON.stringify(args);
|
||||
if (/betterseqta|BetterSEQTA|bsplus|SEQTA\.ts|monofile|AddBetterSEQTA/i.test(blob + name + url)) {
|
||||
const key = `${name} | ${(url || blob).slice(0, 120)}`;
|
||||
add(betterseqtaHits, key, dur);
|
||||
}
|
||||
}
|
||||
|
||||
function top(map, n = 40, minCount = 1) {
|
||||
return [...map.entries()]
|
||||
.filter(([, v]) => v.count >= minCount)
|
||||
.sort((a, b) => b[1].dur - a[1].dur)
|
||||
.slice(0, n)
|
||||
.map(([k, v]) => ({
|
||||
key: k,
|
||||
totalMs: (v.dur / 1000).toFixed(1),
|
||||
count: v.count,
|
||||
avgMs: (v.dur / v.count / 1000).toFixed(2),
|
||||
}));
|
||||
}
|
||||
|
||||
const traceDurationMs = ((maxTs - minTs) / 1000).toFixed(0);
|
||||
|
||||
console.log(
|
||||
JSON.stringify(
|
||||
{
|
||||
summary: {
|
||||
traceDurationMs,
|
||||
eventCount: traceEvents.length,
|
||||
layoutCount: layoutEvents.length,
|
||||
layoutTotalMs: (layoutEvents.reduce((s, e) => s + e.dur, 0) / 1000).toFixed(1),
|
||||
paintCount: paintEvents.length,
|
||||
paintTotalMs: (paintEvents.reduce((s, e) => s + e.dur, 0) / 1000).toFixed(1),
|
||||
longTaskCount: longTasks.length,
|
||||
longTaskTotalMs: (longTasks.reduce((s, e) => s + e.dur, 0) / 1000).toFixed(1),
|
||||
timerCount: timers.length,
|
||||
timerTotalMs: (timers.reduce((s, e) => s + e.dur, 0) / 1000).toFixed(1),
|
||||
observerCount: observers.length,
|
||||
observerTotalMs: (observers.reduce((s, e) => s + e.dur, 0) / 1000).toFixed(1),
|
||||
hitTestCount: hitTests.length,
|
||||
hitTestTotalMs: (hitTests.reduce((s, e) => s + e.dur, 0) / 1000).toFixed(1),
|
||||
gcCount: gcEvents.length,
|
||||
gcTotalMs: (gcEvents.reduce((s, e) => s + e.dur, 0) / 1000).toFixed(1),
|
||||
},
|
||||
topEventNames: top(byName, 50),
|
||||
topCategories: top(byCat, 30),
|
||||
topUrls: top(byUrl, 40),
|
||||
topFunctions: top(byFunction, 40, 1),
|
||||
topBetterseqta: top(betterseqtaHits, 50),
|
||||
topLongTasks: longTasks
|
||||
.sort((a, b) => b.dur - a.dur)
|
||||
.slice(0, 20)
|
||||
.map((e) => ({
|
||||
ms: (e.dur / 1000).toFixed(1),
|
||||
cat: e.cat,
|
||||
args: e.args,
|
||||
})),
|
||||
topLayout: layoutEvents
|
||||
.sort((a, b) => b.dur - a.dur)
|
||||
.slice(0, 15)
|
||||
.map((e) => ({
|
||||
name: e.name,
|
||||
ms: (e.dur / 1000).toFixed(2),
|
||||
})),
|
||||
topObservers: observers
|
||||
.sort((a, b) => b.dur - a.dur)
|
||||
.slice(0, 15)
|
||||
.map((e) => ({
|
||||
name: e.name,
|
||||
ms: (e.dur / 1000).toFixed(2),
|
||||
count: 1,
|
||||
})),
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
);
|
||||
@@ -0,0 +1,80 @@
|
||||
/**
|
||||
* Pre-compile layerchart `.svelte` sources to `.js` so Rollup/Vite CI builds succeed.
|
||||
*/
|
||||
import { compile } from "svelte/compiler";
|
||||
import { readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
|
||||
import { dirname, join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const root = join(dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const layerchartRoot = join(root, "node_modules", "layerchart");
|
||||
const layerchartDist = join(layerchartRoot, "dist");
|
||||
const stampPath = join(layerchartDist, ".bsplus-compiled");
|
||||
const COMPILE_ALGO_VERSION = "2";
|
||||
const importSuffixPattern = /\.svelte(?=['"])/g;
|
||||
|
||||
const exists = (path) => {
|
||||
try {
|
||||
statSync(path);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
if (!exists(layerchartDist)) {
|
||||
console.log("compile-layerchart-vendor: layerchart not installed, skipping");
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
const layerchartVersion = JSON.parse(
|
||||
readFileSync(join(layerchartRoot, "package.json"), "utf8"),
|
||||
).version;
|
||||
const stampContent = `${layerchartVersion}\n${COMPILE_ALGO_VERSION}`;
|
||||
|
||||
if (exists(stampPath) && readFileSync(stampPath, "utf8").trim() === stampContent) {
|
||||
console.log(
|
||||
`compile-layerchart-vendor: layerchart@${layerchartVersion} already compiled, skipping`,
|
||||
);
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
const walkFiles = (dir, files = []) => {
|
||||
for (const name of readdirSync(dir)) {
|
||||
if (name === "node_modules") continue;
|
||||
const path = join(dir, name);
|
||||
if (statSync(path).isDirectory()) walkFiles(path, files);
|
||||
else files.push(path);
|
||||
}
|
||||
return files;
|
||||
};
|
||||
|
||||
const patchSvelteImports = (content) => content.replace(importSuffixPattern, ".js");
|
||||
const stripRollupBreakingSyntax = (code) =>
|
||||
code.replace(/(\w+)\?(?=\s*[,)\]])/g, "$1").replace(/(\w+)\?(?=\s*:)/g, "$1");
|
||||
|
||||
const svelteFiles = walkFiles(layerchartDist).filter((f) => f.endsWith(".svelte"));
|
||||
|
||||
for (const sveltePath of svelteFiles) {
|
||||
const source = readFileSync(sveltePath, "utf8");
|
||||
if (!source.includes("<script")) continue;
|
||||
const compiled = compile(source, {
|
||||
filename: sveltePath,
|
||||
generate: "client",
|
||||
css: "injected",
|
||||
});
|
||||
writeFileSync(
|
||||
sveltePath.replace(/\.svelte$/, ".js"),
|
||||
stripRollupBreakingSyntax(patchSvelteImports(compiled.js.code)),
|
||||
);
|
||||
}
|
||||
|
||||
for (const filePath of walkFiles(layerchartDist).filter((f) => /\.(js|svelte|ts|mjs)$/.test(f))) {
|
||||
const content = readFileSync(filePath, "utf8");
|
||||
if (!content.includes(".svelte")) continue;
|
||||
const patched = patchSvelteImports(content);
|
||||
if (patched !== content) writeFileSync(filePath, patched);
|
||||
}
|
||||
|
||||
writeFileSync(stampPath, stampContent);
|
||||
console.log(`compile-layerchart-vendor: compiled ${svelteFiles.length} Svelte files`);
|
||||
@@ -0,0 +1,24 @@
|
||||
import { copyFileSync, mkdirSync } from "node:fs";
|
||||
import { dirname, join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const root = join(dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const resources = join(root, "src", "public", "resources");
|
||||
const files = [
|
||||
["pdfjs-dist/build/pdf.worker.min.mjs", "pdfjs/pdf.worker.min.mjs"],
|
||||
["pdfjs-dist/legacy/build/pdf.min.mjs", "pdfjs/pdf.legacy.min.mjs"],
|
||||
[
|
||||
"@huggingface/transformers/dist/ort-wasm-simd-threaded.jsep.mjs",
|
||||
"ort/ort-wasm-simd-threaded.jsep.mjs",
|
||||
],
|
||||
[
|
||||
"@huggingface/transformers/dist/ort-wasm-simd-threaded.jsep.wasm",
|
||||
"ort/ort-wasm-simd-threaded.jsep.wasm",
|
||||
],
|
||||
];
|
||||
|
||||
for (const [source, target] of files) {
|
||||
const output = join(resources, target);
|
||||
mkdirSync(dirname(output), { recursive: true });
|
||||
copyFileSync(join(root, "node_modules", source), output);
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
/**
|
||||
* Package Chrome/Firefox build folders into Windows-friendly zip files.
|
||||
*/
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { appendFileSync, existsSync, mkdirSync, readFileSync, unlinkSync } from "node:fs";
|
||||
import { dirname, join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const root = join(dirname(fileURLToPath(import.meta.url)), "..");
|
||||
|
||||
function zipDirectory(sourceRel, outRel) {
|
||||
const sourceDir = join(root, sourceRel);
|
||||
const outZip = join(root, outRel);
|
||||
if (!existsSync(sourceDir)) throw new Error(`Missing build output: ${sourceRel}`);
|
||||
|
||||
mkdirSync(dirname(outZip), { recursive: true });
|
||||
if (existsSync(outZip)) unlinkSync(outZip);
|
||||
|
||||
if (process.platform === "win32") {
|
||||
const esc = (s) => s.replace(/'/g, "''");
|
||||
execFileSync(
|
||||
"powershell",
|
||||
[
|
||||
"-NoProfile",
|
||||
"-Command",
|
||||
[
|
||||
"Add-Type -AssemblyName System.IO.Compression.FileSystem",
|
||||
`[IO.Compression.ZipFile]::CreateFromDirectory('${esc(sourceDir)}', '${esc(outZip)}')`,
|
||||
].join("; "),
|
||||
],
|
||||
{ stdio: "inherit" },
|
||||
);
|
||||
} else {
|
||||
execFileSync("zip", ["-r", "-q", outZip, "."], { cwd: sourceDir, stdio: "inherit" });
|
||||
}
|
||||
}
|
||||
|
||||
const pkg = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
|
||||
const version = process.argv[2] || pkg.version;
|
||||
const updateChannel = process.env.UPDATE_CHANNEL || "stable";
|
||||
const buildLabel = process.env.BUILD_LABEL || "";
|
||||
const base =
|
||||
updateChannel === "nightly" && buildLabel
|
||||
? `betterseqtaplus-nightly-${buildLabel}`
|
||||
: `${pkg.name}@${version}`;
|
||||
|
||||
const chromeZip = `dist/${base}-chrome.zip`;
|
||||
const firefoxZip = `dist/${base}-firefox.zip`;
|
||||
|
||||
zipDirectory("dist/chrome", chromeZip);
|
||||
zipDirectory("dist/firefox", firefoxZip);
|
||||
console.log(`Packaged ${chromeZip}\nPackaged ${firefoxZip}`);
|
||||
|
||||
if (process.env.GITHUB_OUTPUT) {
|
||||
appendFileSync(process.env.GITHUB_OUTPUT, `chrome_zip=${chromeZip}\nfirefox_zip=${firefoxZip}\n`);
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
const root = process.cwd();
|
||||
|
||||
function fail(message) {
|
||||
console.error(`[smoke-test] ${message}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
function assertManifest(browserDir) {
|
||||
const manifestPath = path.join(root, "dist", browserDir, "manifest.json");
|
||||
if (!fs.existsSync(manifestPath)) {
|
||||
fail(`Missing ${manifestPath} — run npm run build first`);
|
||||
}
|
||||
const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8"));
|
||||
if (!manifest.manifest_version) fail(`${browserDir} manifest missing manifest_version`);
|
||||
if (!manifest.name) fail(`${browserDir} manifest missing name`);
|
||||
if (!manifest.version) fail(`${browserDir} manifest missing version`);
|
||||
|
||||
const sw = manifest.background?.service_worker ?? manifest.background?.scripts?.[0] ?? null;
|
||||
if (sw) {
|
||||
const swPath = path.join(root, "dist", browserDir, sw);
|
||||
if (!fs.existsSync(swPath)) {
|
||||
fail(`${browserDir} service worker not found on disk: ${sw}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function assertAssets(browserDir) {
|
||||
const assetsDir = path.join(root, "dist", browserDir, "assets");
|
||||
if (!fs.existsSync(assetsDir)) {
|
||||
fail(`Missing assets directory: dist/${browserDir}/assets`);
|
||||
}
|
||||
const jsFiles = fs.readdirSync(assetsDir).filter((f) => f.endsWith(".js"));
|
||||
if (jsFiles.length === 0) {
|
||||
fail(`No JS assets in dist/${browserDir}/assets`);
|
||||
}
|
||||
}
|
||||
|
||||
for (const browser of ["chrome", "firefox"]) {
|
||||
assertManifest(browser);
|
||||
assertAssets(browser);
|
||||
}
|
||||
|
||||
console.log("[smoke-test] dist/chrome and dist/firefox look OK");
|
||||
@@ -0,0 +1,66 @@
|
||||
/** @jest-environment jsdom */
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { runInNewContext } from "node:vm";
|
||||
|
||||
// Compile the actual Vite entry and the 404 boot it loads in Node (esbuild
|
||||
// cannot run in jsdom's realm).
|
||||
const [bootScript, errorPageScript]: string[] = JSON.parse(
|
||||
execFileSync(
|
||||
process.execPath,
|
||||
[
|
||||
"--input-type=module",
|
||||
"-e",
|
||||
`
|
||||
import { readFileSync } from "node:fs";
|
||||
import { transformSync } from "esbuild";
|
||||
const compile = (file) => transformSync(readFileSync(file, "utf8"), {
|
||||
loader: "ts", format: "cjs",
|
||||
supported: { "dynamic-import": false },
|
||||
define: { "import.meta.env.DEV": "false", "import.meta.hot": "undefined" },
|
||||
}).code;
|
||||
process.stdout.write(JSON.stringify(["src/SEQTA.ts", "src/seqta/bootErrorPage.ts"].map(compile)));
|
||||
`,
|
||||
],
|
||||
{ encoding: "utf8" },
|
||||
),
|
||||
);
|
||||
|
||||
test.each([{ onoff: false }, { "plugin.error-page-kitten.settings": { enabled: false } }])(
|
||||
"disabled 404 customization preserves the native error message: %j",
|
||||
async (stored) => {
|
||||
document.head.innerHTML = "";
|
||||
document.body.innerHTML = '<div class="message">Page not found</div>';
|
||||
const mount = jest.fn();
|
||||
const requireMock = (module: string): unknown => {
|
||||
if (module === "@/seqta/bootErrorPage") {
|
||||
const loaded = { exports: {} };
|
||||
runInNewContext(errorPageScript, {
|
||||
document,
|
||||
window,
|
||||
console,
|
||||
module: loaded,
|
||||
exports: loaded.exports,
|
||||
require: requireMock,
|
||||
});
|
||||
return loaded.exports;
|
||||
}
|
||||
if (module === "@/lib/browser") {
|
||||
return { storage: { local: { get: async () => stored } } };
|
||||
}
|
||||
if (module.includes("errorPageKitten")) {
|
||||
return { isSeqta404Page: () => true, mountErrorPageKitten: mount };
|
||||
}
|
||||
return {};
|
||||
};
|
||||
runInNewContext(bootScript, {
|
||||
document,
|
||||
window,
|
||||
console,
|
||||
require: requireMock,
|
||||
});
|
||||
for (let i = 0; i < 10; i++) await Promise.resolve();
|
||||
|
||||
expect(mount).not.toHaveBeenCalled();
|
||||
expect(window.getComputedStyle(document.querySelector(".message")!).display).not.toBe("none");
|
||||
},
|
||||
);
|
||||
+22
-75
@@ -1,85 +1,32 @@
|
||||
import {
|
||||
initializeSettingsState,
|
||||
settingsState,
|
||||
} from "@/seqta/utils/listeners/SettingsState";
|
||||
import documentLoadCSS from "@/css/documentload.scss?inline";
|
||||
import icon48 from "@/resources/icons/icon-48.png?base64";
|
||||
import browser from "webextension-polyfill";
|
||||
// This content script runs on every website, so it only checks whether the page
|
||||
// is SEQTA and loads the rest of the extension on demand. Importing seqta/boot
|
||||
// statically here made every site download and parse the whole bundle.
|
||||
|
||||
import * as plugins from "@/plugins";
|
||||
import { main } from "@/seqta/main";
|
||||
import { delay } from "./seqta/utils/delay";
|
||||
import { initializeHideSensitiveToggle } from "@/seqta/utils/hideSensitiveToggle";
|
||||
import { recoverFromStaleDevModuleGraph } from "@/seqta/devModuleGraphRecovery";
|
||||
|
||||
export let MenuOptionsOpen = false;
|
||||
|
||||
var IsSEQTAPage = false;
|
||||
let hasSEQTAText = false;
|
||||
let isSeqtaPage = false;
|
||||
|
||||
// This check is placed outside of the document load event due to issues with EP (https://github.com/BetterSEQTA/BetterSEQTA-Plus/issues/84)
|
||||
if (document.childNodes[1]) {
|
||||
hasSEQTAText =
|
||||
document.childNodes[1].textContent?.includes(
|
||||
"Copyright (c) SEQTA Software",
|
||||
) ?? false;
|
||||
init();
|
||||
document.childNodes[1].textContent?.includes("Copyright (c) SEQTA Software") ?? false;
|
||||
isSeqtaPage =
|
||||
hasSEQTAText &&
|
||||
(document.title.includes("SEQTA Learn") || document.title.includes("SEQTA Engage"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes BetterSEQTA+ on a SEQTA page.
|
||||
*
|
||||
* This function performs the following steps:
|
||||
* 1. Verifies that the current page is a SEQTA page.
|
||||
* 2. Injects CSS styles for document loading.
|
||||
* 3. Changes the page's favicon.
|
||||
* 4. Initializes the extension's settings state.
|
||||
* 5. Sets default storage if settings are not already defined.
|
||||
* 6. Calls the main function to apply core BetterSEQTA+ modifications.
|
||||
* 7. Initializes legacy and new plugins if the extension is enabled.
|
||||
* 8. Logs success or error messages during initialization.
|
||||
*/
|
||||
async function init() {
|
||||
const hasSEQTATitle = document.title.includes("SEQTA Learn");
|
||||
|
||||
if (hasSEQTAText && hasSEQTATitle && !IsSEQTAPage) {
|
||||
// Verify we are on a SEQTA page
|
||||
IsSEQTAPage = true;
|
||||
console.info("[BetterSEQTA+] Verified SEQTA Page");
|
||||
|
||||
const documentLoadStyle = document.createElement("style");
|
||||
documentLoadStyle.textContent = documentLoadCSS;
|
||||
document.head.appendChild(documentLoadStyle);
|
||||
|
||||
const icon = document.querySelector(
|
||||
'link[rel*="icon"]',
|
||||
)! as HTMLLinkElement;
|
||||
icon.href = icon48; // Change the icon
|
||||
|
||||
try {
|
||||
await initializeSettingsState();
|
||||
|
||||
if (typeof settingsState.onoff === "undefined") {
|
||||
await browser.runtime.sendMessage({ type: "setDefaultStorage" });
|
||||
|
||||
await delay(5);
|
||||
}
|
||||
|
||||
await main();
|
||||
plugins.Monofile();
|
||||
|
||||
if (settingsState.onoff) {
|
||||
await plugins.initializePlugins();
|
||||
}
|
||||
|
||||
if (settingsState.devMode) {
|
||||
initializeHideSensitiveToggle();
|
||||
}
|
||||
|
||||
console.info(
|
||||
"[BetterSEQTA+] Successfully initialised BetterSEQTA+, starting to load assets.",
|
||||
);
|
||||
} catch (error: any) {
|
||||
console.error(error);
|
||||
}
|
||||
}
|
||||
if (hasSEQTAText) {
|
||||
void import("@/seqta/boot").then(({ boot }) => boot());
|
||||
}
|
||||
|
||||
// Standalone 404 documents never pass the SEQTA SPA gate above.
|
||||
if (!isSeqtaPage) {
|
||||
void import("@/seqta/bootErrorPage").then(({ bootErrorPage }) => bootErrorPage());
|
||||
}
|
||||
|
||||
if (import.meta.env.DEV) {
|
||||
window.addEventListener("unhandledrejection", (event) => {
|
||||
recoverFromStaleDevModuleGraph(event.reason);
|
||||
});
|
||||
}
|
||||
+706
-111
@@ -1,12 +1,59 @@
|
||||
import browser from "webextension-polyfill";
|
||||
import browser from "@/lib/browser";
|
||||
import type { SettingsState } from "@/types/storage";
|
||||
import { getDefaultSettingsState } from "@/seqta/utils/defaultSettings";
|
||||
import { ensureSyncableStorageDefaults } from "@/seqta/utils/ensureSyncableStorageDefaults";
|
||||
import { fetchNews } from "./background/news";
|
||||
import {
|
||||
initCloudSettingsAutoSync,
|
||||
performCloudSettingsDownloadWithRetry,
|
||||
performCloudSettingsUploadWithRetry,
|
||||
requestCloudSettingsDebouncedUpload,
|
||||
runCloudSettingsPoll,
|
||||
withSuppressedCloudAutoUpload,
|
||||
} from "./background/cloudSettingsAutoSync";
|
||||
import { getBsplusDeviceName } from "@/seqta/utils/bsplusDeviceName";
|
||||
import { isAllowedFetchUrl } from "@/seqta/utils/allowedFetchUrl";
|
||||
import {
|
||||
initCalendarBackground,
|
||||
registerGoogleCalendarMessageHandlers,
|
||||
registerOutlookCalendarMessageHandlers,
|
||||
type CalendarMessageHandlerMap,
|
||||
} from "./background/calendarBackground";
|
||||
import { createCustomThemesHandlers } from "./background/customThemesHandlers";
|
||||
import {
|
||||
createRemoteConfigHandlers,
|
||||
initRemoteConfigBackground,
|
||||
refreshRemoteConfig,
|
||||
} from "./background/remoteConfig";
|
||||
import { BSPLUS_INSTALL_REGISTERED_AT_KEY } from "@/seqta/utils/remoteConfig/storageKeys";
|
||||
import { DEFAULT_BACKGROUND_PENDING_KEY } from "@/seqta/ui/defaultBackgroundKey";
|
||||
import { handleSearchThemeStockPhotos } from "./background/searchThemeStockPhotos";
|
||||
import { bsplusApiQueryParams, withBsplusApiQuery } from "@/seqta/utils/bsplusClientContext";
|
||||
import { initTimetableClassmatesBackgroundSync } from "./background/timetableClassmatesSync";
|
||||
import { runStorageMigrations } from "./background/storageMigrations";
|
||||
|
||||
/**
|
||||
* Session-only dev-mode override of the content API base.
|
||||
*
|
||||
* Stored in a module-level variable (not `chrome.storage`) so it is wiped
|
||||
* automatically when the browser/service-worker process restarts. Content
|
||||
* scripts re-sync this on every page load via `setDevApiBase` so the value
|
||||
* survives transient service-worker terminations within the same browser
|
||||
* session.
|
||||
*/
|
||||
const DEFAULT_API_BASE = "https://betterseqta.org";
|
||||
let DEV_API_BASE: string | null = null;
|
||||
function apiBase(): string {
|
||||
// Extension dev builds always hit production (see DevApiBase.ts).
|
||||
if (import.meta.env.DEV) return DEFAULT_API_BASE;
|
||||
return DEV_API_BASE ?? DEFAULT_API_BASE;
|
||||
}
|
||||
|
||||
function reloadSeqtaPages() {
|
||||
const result = browser.tabs.query({});
|
||||
function open(tabs: any) {
|
||||
for (let tab of tabs) {
|
||||
if (tab.title.includes("SEQTA Learn")) {
|
||||
function open(tabs: chrome.tabs.Tab[]) {
|
||||
for (const tab of tabs) {
|
||||
if (tab.title?.includes("SEQTA Learn") || tab.title?.includes("SEQTA Engage")) {
|
||||
browser.tabs.reload(tab.id);
|
||||
}
|
||||
}
|
||||
@@ -14,133 +61,681 @@ function reloadSeqtaPages() {
|
||||
result.then(open, console.error);
|
||||
}
|
||||
|
||||
// @ts-ignore
|
||||
browser.runtime.onMessage.addListener(
|
||||
(request: any, _: any, sendResponse: (response?: any) => void) => {
|
||||
switch (request.type) {
|
||||
case "reloadTabs":
|
||||
reloadSeqtaPages();
|
||||
break;
|
||||
/** Callback for sending a response back to the message sender */
|
||||
type MessageSender = { (response?: unknown): void };
|
||||
|
||||
case "extensionPages":
|
||||
browser.tabs.query({}).then(function (tabs) {
|
||||
for (let tab of tabs) {
|
||||
if (tab.url?.includes("chrome-extension://")) {
|
||||
browser.tabs.sendMessage(tab.id!, request);
|
||||
}
|
||||
}
|
||||
});
|
||||
break;
|
||||
/** Runtime message payloads from extension pages / content scripts */
|
||||
type BackgroundRequest = Record<string, unknown>;
|
||||
|
||||
case "currentTab":
|
||||
browser.tabs
|
||||
.query({ active: true, currentWindow: true })
|
||||
.then(function (tabs) {
|
||||
browser.tabs
|
||||
.sendMessage(tabs[0].id!, request)
|
||||
.then(function (response) {
|
||||
sendResponse(response);
|
||||
});
|
||||
function reqString(req: BackgroundRequest, key: string): string | undefined {
|
||||
const value = req[key];
|
||||
return typeof value === "string" ? value : undefined;
|
||||
}
|
||||
|
||||
async function getAccessTokenFromStorage(): Promise<string | null> {
|
||||
const { bsplus_token } = await browser.storage.local.get("bsplus_token");
|
||||
return typeof bsplus_token === "string" && bsplus_token.length > 0 ? bsplus_token : null;
|
||||
}
|
||||
|
||||
/** Accept API + GitHub fallback shapes; always return `{ success, data?: { themes } }`. */
|
||||
function normalizeFetchThemesResponse(json: unknown): {
|
||||
success: boolean;
|
||||
data?: { themes: unknown[] };
|
||||
error?: string;
|
||||
} {
|
||||
if (!json || typeof json !== "object") {
|
||||
return { success: false, error: "Invalid themes response" };
|
||||
}
|
||||
const body = json as Record<string, unknown>;
|
||||
if (body.success === false) {
|
||||
return {
|
||||
success: false,
|
||||
error: typeof body.error === "string" ? body.error : "Failed to fetch themes",
|
||||
};
|
||||
}
|
||||
const data = body.data;
|
||||
let themes: unknown[] | null = null;
|
||||
if (data && typeof data === "object" && !Array.isArray(data)) {
|
||||
const nested = (data as Record<string, unknown>).themes;
|
||||
if (Array.isArray(nested)) themes = nested;
|
||||
} else if (Array.isArray(data)) {
|
||||
themes = data;
|
||||
}
|
||||
if (!themes && Array.isArray(body.themes)) {
|
||||
themes = body.themes;
|
||||
}
|
||||
if (!themes) {
|
||||
return { success: false, error: "Themes list missing from response" };
|
||||
}
|
||||
return { success: true, data: { themes } };
|
||||
}
|
||||
|
||||
function handleFetchThemes(_request: unknown, sendResponse: MessageSender): boolean {
|
||||
void (async () => {
|
||||
const token = await getAccessTokenFromStorage();
|
||||
const params = await bsplusApiQueryParams();
|
||||
params.set("type", "betterseqta");
|
||||
params.set("limit", "100");
|
||||
params.set("nocache", String(Date.now()));
|
||||
const apiUrl = `${apiBase()}/api/themes?${params}`;
|
||||
const githubUrl = `https://raw.githubusercontent.com/BetterSEQTA/BetterSEQTA-Themes/main/store/themes.json?nocache=${Date.now()}`;
|
||||
const headers: Record<string, string> = {};
|
||||
if (token) headers["Authorization"] = `Bearer ${token}`;
|
||||
fetch(apiUrl, { cache: "no-store", headers })
|
||||
.then(async (r) => {
|
||||
const json = await r.json();
|
||||
if (!r.ok) {
|
||||
throw new Error(
|
||||
(json &&
|
||||
typeof json === "object" &&
|
||||
"error" in json &&
|
||||
typeof (json as { error?: string }).error === "string"
|
||||
? (json as { error: string }).error
|
||||
: null) ?? `Themes API HTTP ${r.status}`,
|
||||
);
|
||||
}
|
||||
return normalizeFetchThemesResponse(json);
|
||||
})
|
||||
.then(sendResponse)
|
||||
.catch((err) => {
|
||||
console.warn("[Background] fetchThemes API failed, trying GitHub fallback:", err?.message);
|
||||
fetch(githubUrl, { cache: "no-store" })
|
||||
.then(async (r) => {
|
||||
if (!r.ok) throw new Error(`GitHub fallback HTTP ${r.status}`);
|
||||
const data = await r.json();
|
||||
const themes = Array.isArray(data) ? data : (data?.themes ?? []);
|
||||
return normalizeFetchThemesResponse({ success: true, data: { themes } });
|
||||
})
|
||||
.then(sendResponse)
|
||||
.catch((fallbackErr) => {
|
||||
console.error("[Background] fetchThemes GitHub fallback error:", fallbackErr);
|
||||
sendResponse({ success: false, error: fallbackErr?.message });
|
||||
});
|
||||
return true;
|
||||
});
|
||||
})();
|
||||
return true;
|
||||
}
|
||||
|
||||
case "githubTab":
|
||||
browser.tabs.create({ url: "github.com/BetterSEQTA/BetterSEQTA-Plus" });
|
||||
break;
|
||||
function handleFetchThemeDetails(request: BackgroundRequest, sendResponse: MessageSender): boolean {
|
||||
const { themeId } = request;
|
||||
if (!themeId || typeof themeId !== "string") {
|
||||
sendResponse({ success: false, error: "Missing themeId" });
|
||||
return false;
|
||||
}
|
||||
void (async () => {
|
||||
const token = await getAccessTokenFromStorage();
|
||||
const headers: Record<string, string> = {};
|
||||
if (token) headers["Authorization"] = `Bearer ${token}`;
|
||||
const detailUrl = await withBsplusApiQuery(
|
||||
`${apiBase()}/api/themes/${encodeURIComponent(themeId)}`,
|
||||
);
|
||||
fetch(detailUrl, { cache: "no-store", headers })
|
||||
.then((r) => r.json())
|
||||
.then(sendResponse)
|
||||
.catch((err) => {
|
||||
console.error("[Background] fetchThemeDetails error:", err);
|
||||
sendResponse({ success: false, error: err?.message });
|
||||
});
|
||||
})();
|
||||
return true;
|
||||
}
|
||||
|
||||
case "setDefaultStorage":
|
||||
SetStorageValue(getDefaultValues());
|
||||
break;
|
||||
function isTrustedSender(sender?: chrome.runtime.MessageSender): boolean {
|
||||
if (!sender) return false;
|
||||
if (sender.id && sender.id !== browser.runtime.id) return false;
|
||||
|
||||
case "sendNews":
|
||||
fetchNews(request.source ?? "australia", sendResponse);
|
||||
return true;
|
||||
|
||||
default:
|
||||
console.log("Unknown request type");
|
||||
const urls = [sender.url, sender.tab?.url].filter(Boolean) as string[];
|
||||
for (const pageUrl of urls) {
|
||||
if (pageUrl.startsWith("chrome-extension://") || pageUrl.startsWith("moz-extension://")) {
|
||||
return true;
|
||||
}
|
||||
try {
|
||||
if (isSeqtaOrigin(new URL(pageUrl).origin)) return true;
|
||||
} catch {}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function handleFetchFromUrl(
|
||||
request: BackgroundRequest,
|
||||
sendResponse: MessageSender,
|
||||
sender?: chrome.runtime.MessageSender,
|
||||
): boolean {
|
||||
if (!isTrustedSender(sender)) {
|
||||
sendResponse({ error: "Unauthorized sender" });
|
||||
return false;
|
||||
}
|
||||
const { url } = request;
|
||||
if (!url || typeof url !== "string") {
|
||||
sendResponse({ error: "Missing url" });
|
||||
return false;
|
||||
}
|
||||
if (!isAllowedFetchUrl(url)) {
|
||||
sendResponse({ error: "URL not allowed" });
|
||||
return false;
|
||||
}
|
||||
void (async () => {
|
||||
try {
|
||||
const headers: Record<string, string> = { Accept: "application/json" };
|
||||
if (request.auth === true) {
|
||||
const token = await getAccessTokenFromStorage();
|
||||
if (!token) {
|
||||
sendResponse({ error: "Not authenticated" });
|
||||
return;
|
||||
}
|
||||
headers.Authorization = `Bearer ${token}`;
|
||||
}
|
||||
const r = await fetch(url, { cache: "no-store", headers });
|
||||
const text = await r.text();
|
||||
if (!r.ok) {
|
||||
sendResponse({
|
||||
error: text?.slice(0, 200) || `HTTP ${r.status}`,
|
||||
httpStatus: r.status,
|
||||
});
|
||||
return;
|
||||
}
|
||||
try {
|
||||
sendResponse({ data: text ? JSON.parse(text) : {} });
|
||||
} catch {
|
||||
sendResponse({ error: "Invalid JSON response" });
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("[Background] fetchFromUrl error:", err);
|
||||
sendResponse({ error: (err as Error)?.message });
|
||||
}
|
||||
})();
|
||||
return true;
|
||||
}
|
||||
|
||||
async function parseJsonResponse(r: Response): Promise<unknown> {
|
||||
const text = await r.text();
|
||||
try {
|
||||
return text ? JSON.parse(text) : {};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
function handleCloudReserveClient(
|
||||
request: BackgroundRequest,
|
||||
sendResponse: MessageSender,
|
||||
): boolean {
|
||||
const redirect_uri =
|
||||
request.redirect_uri ?? "https://accounts.betterseqta.org/auth/bsplus/callback";
|
||||
fetch("https://accounts.betterseqta.org/api/bsplus/client/reserve", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ redirect_uri }),
|
||||
})
|
||||
.then(async (r) => {
|
||||
const data = await parseJsonResponse(r);
|
||||
const errorText =
|
||||
data && typeof data === "object" && "error" in data
|
||||
? String((data as { error?: unknown }).error)
|
||||
: undefined;
|
||||
if (!r.ok) sendResponse({ error: errorText ?? `Reserve failed (${r.status})` });
|
||||
else sendResponse(data);
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error("[Background] cloudReserveClient error:", err);
|
||||
sendResponse({ error: err?.message ?? "Network error" });
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
function handleCloudLogin(
|
||||
request: BackgroundRequest,
|
||||
sendResponse: MessageSender,
|
||||
sender?: chrome.runtime.MessageSender,
|
||||
): boolean {
|
||||
if (!isTrustedSender(sender)) {
|
||||
sendResponse({ error: "Unauthorized sender" });
|
||||
return false;
|
||||
}
|
||||
const client_id = reqString(request, "client_id");
|
||||
const redirect_uri = reqString(request, "redirect_uri");
|
||||
const login = reqString(request, "login");
|
||||
const password = reqString(request, "password");
|
||||
const device_name = reqString(request, "device_name");
|
||||
if (!client_id || !redirect_uri || !login || !password) {
|
||||
sendResponse({ error: "Missing client_id, redirect_uri, login, or password" });
|
||||
return false;
|
||||
}
|
||||
void (async () => {
|
||||
const loginBody: Record<string, string> = {
|
||||
client_id,
|
||||
redirect_uri,
|
||||
login,
|
||||
password,
|
||||
device_name: device_name ?? (await getBsplusDeviceName()),
|
||||
};
|
||||
try {
|
||||
const r = await fetch("https://accounts.betterseqta.org/api/bsplus/login", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(loginBody),
|
||||
});
|
||||
const data = await parseJsonResponse(r);
|
||||
const errorText =
|
||||
data && typeof data === "object" && "error" in data
|
||||
? String((data as { error?: unknown }).error)
|
||||
: undefined;
|
||||
if (!r.ok) sendResponse({ error: errorText ?? "Login failed" });
|
||||
else sendResponse(data);
|
||||
} catch (err) {
|
||||
console.error("[Background] cloudLogin error:", err);
|
||||
sendResponse({ error: (err as Error)?.message ?? "Network error" });
|
||||
}
|
||||
})();
|
||||
return true;
|
||||
}
|
||||
|
||||
function handleCloudStartLogin(request: BackgroundRequest, sendResponse: MessageSender): boolean {
|
||||
const client_id = reqString(request, "client_id");
|
||||
const redirect_uri = reqString(request, "redirect_uri");
|
||||
if (!client_id || !redirect_uri) {
|
||||
sendResponse({ error: "Missing client_id or redirect_uri" });
|
||||
return true;
|
||||
}
|
||||
const authorizeUrl = `https://accounts.betterseqta.org/login?redirect=${encodeURIComponent(`/oauth/authorize?client_id=${client_id}&redirect_uri=${encodeURIComponent(redirect_uri)}`)}`;
|
||||
browser.tabs
|
||||
.create({ url: authorizeUrl })
|
||||
.then(() => {
|
||||
sendResponse({ success: true });
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error("[Background] cloudStartLogin error:", err);
|
||||
sendResponse({ error: err?.message ?? "Failed to open login page" });
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
const CALLBACK_URL_PREFIX = "https://accounts.betterseqta.org/auth/bsplus/callback";
|
||||
|
||||
function initCloudLoginCallbackListener() {
|
||||
browser.tabs.onUpdated.addListener((tabId, changeInfo) => {
|
||||
if (changeInfo.url && changeInfo.url.startsWith(CALLBACK_URL_PREFIX)) {
|
||||
try {
|
||||
const url = new URL(changeInfo.url);
|
||||
const token = url.searchParams.get("token");
|
||||
const refreshToken = url.searchParams.get("refresh_token");
|
||||
const userId = url.searchParams.get("user_id");
|
||||
|
||||
if (token && refreshToken) {
|
||||
void (async () => {
|
||||
try {
|
||||
await browser.storage.local.set({
|
||||
bsplus_token: token,
|
||||
bsplus_refresh_token: refreshToken,
|
||||
});
|
||||
|
||||
const userRes = await fetch("https://accounts.betterseqta.org/api/auth/me", {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
});
|
||||
if (userRes.ok) {
|
||||
const user = await userRes.json();
|
||||
await browser.storage.local.set({ bsplus_user: user });
|
||||
} else if (userId) {
|
||||
await browser.storage.local.set({ bsplus_user: { id: userId } });
|
||||
}
|
||||
|
||||
void performCloudSettingsDownloadWithRetry(token).catch((err) => {
|
||||
console.warn("[Background] Cloud settings download after login:", err);
|
||||
});
|
||||
} catch (err) {
|
||||
console.error("[Background] Failed to process login callback:", err);
|
||||
}
|
||||
})();
|
||||
|
||||
void browser.tabs.remove(tabId);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("[Background] Error parsing callback URL:", err);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
initCloudLoginCallbackListener();
|
||||
|
||||
function handleCloudRefresh(request: BackgroundRequest, sendResponse: MessageSender): boolean {
|
||||
const { refresh_token, client_id } = request;
|
||||
if (!refresh_token || !client_id) {
|
||||
sendResponse({ error: "Missing refresh_token or client_id" });
|
||||
return false;
|
||||
}
|
||||
fetch("https://accounts.betterseqta.org/api/bsplus/refresh", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ refresh_token, client_id }),
|
||||
})
|
||||
.then(async (r) => {
|
||||
const data = await parseJsonResponse(r);
|
||||
const errorText =
|
||||
data && typeof data === "object" && "error" in data
|
||||
? String((data as { error?: unknown }).error)
|
||||
: undefined;
|
||||
if (!r.ok) sendResponse({ error: errorText ?? "Refresh failed" });
|
||||
else sendResponse(data);
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error("[Background] cloudRefresh error:", err);
|
||||
sendResponse({ error: err?.message ?? "Network error" });
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
function handleCloudSettingsUpload(
|
||||
_request: unknown,
|
||||
sendResponse: MessageSender,
|
||||
sender?: chrome.runtime.MessageSender,
|
||||
): boolean {
|
||||
if (!isTrustedSender(sender)) {
|
||||
sendResponse({ success: false, error: "Unauthorized sender" });
|
||||
return false;
|
||||
}
|
||||
void (async () => {
|
||||
try {
|
||||
const token = await getAccessTokenFromStorage();
|
||||
if (!token) {
|
||||
sendResponse({ success: false, error: "Not authenticated" });
|
||||
return;
|
||||
}
|
||||
const res = await performCloudSettingsUploadWithRetry(token);
|
||||
sendResponse({
|
||||
success: res.success,
|
||||
error: res.error,
|
||||
updated_at: res.updated_at,
|
||||
});
|
||||
} catch (err) {
|
||||
console.error("[Background] cloudSettingsUpload error:", err);
|
||||
sendResponse({
|
||||
success: false,
|
||||
error: err instanceof Error ? err.message : "Upload failed",
|
||||
});
|
||||
}
|
||||
})();
|
||||
return true;
|
||||
}
|
||||
|
||||
function handleCloudSettingsDownload(
|
||||
_request: unknown,
|
||||
sendResponse: MessageSender,
|
||||
sender?: chrome.runtime.MessageSender,
|
||||
): boolean {
|
||||
if (!isTrustedSender(sender)) {
|
||||
sendResponse({ success: false, error: "Unauthorized sender" });
|
||||
return false;
|
||||
}
|
||||
void (async () => {
|
||||
try {
|
||||
const token = await getAccessTokenFromStorage();
|
||||
if (!token) {
|
||||
sendResponse({ success: false, error: "Not authenticated" });
|
||||
return;
|
||||
}
|
||||
const res = await performCloudSettingsDownloadWithRetry(token);
|
||||
sendResponse({
|
||||
success: res.success,
|
||||
notFound: res.notFound,
|
||||
error: res.error,
|
||||
updated_at: res.updated_at,
|
||||
});
|
||||
} catch (err) {
|
||||
console.error("[Background] cloudSettingsDownload error:", err);
|
||||
sendResponse({
|
||||
success: false,
|
||||
error: err instanceof Error ? err.message : "Download failed",
|
||||
});
|
||||
}
|
||||
})();
|
||||
return true;
|
||||
}
|
||||
|
||||
function handleCloudFavorite(request: BackgroundRequest, sendResponse: MessageSender): boolean {
|
||||
const { themeId, action } = request;
|
||||
if (!themeId) {
|
||||
sendResponse({ success: false, error: "Theme ID required" });
|
||||
return false;
|
||||
}
|
||||
void (async () => {
|
||||
const token = await getAccessTokenFromStorage();
|
||||
if (!token) {
|
||||
sendResponse({ success: false, error: "Not authenticated" });
|
||||
return;
|
||||
}
|
||||
const isFavorite = action === "favorite";
|
||||
fetch(`${apiBase()}/api/themes/${themeId}/favorite`, {
|
||||
method: isFavorite ? "POST" : "DELETE",
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
})
|
||||
.then((r) => r.json())
|
||||
.then(sendResponse)
|
||||
.catch((err) => {
|
||||
console.error("[Background] cloudFavorite error:", err);
|
||||
sendResponse({ success: false, error: err?.message });
|
||||
});
|
||||
})();
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Handler for a message type; receives request, sendResponse, and optional sender (for tab routing) */
|
||||
type MessageHandler = {
|
||||
(
|
||||
request: BackgroundRequest,
|
||||
sendResponse: MessageSender,
|
||||
sender?: chrome.runtime.MessageSender,
|
||||
): boolean | void;
|
||||
};
|
||||
|
||||
function isSeqtaOrigin(origin: string): boolean {
|
||||
try {
|
||||
const u = new URL(origin);
|
||||
return u.hostname.includes("seqta") || u.hostname.endsWith(".edu.au");
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function handleSetDevApiBase(
|
||||
request: BackgroundRequest,
|
||||
_sendResponse: MessageSender,
|
||||
sender?: chrome.runtime.MessageSender,
|
||||
): boolean {
|
||||
if (!isTrustedSender(sender)) return false;
|
||||
if (import.meta.env.DEV) {
|
||||
DEV_API_BASE = null;
|
||||
return false;
|
||||
}
|
||||
const url = typeof request?.url === "string" ? request.url.trim() : null;
|
||||
if (url && /^https?:\/\//.test(url)) {
|
||||
DEV_API_BASE = url.replace(/\/$/, "");
|
||||
} else {
|
||||
DEV_API_BASE = null;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
const customThemesHandlers = createCustomThemesHandlers({
|
||||
apiBase,
|
||||
getAccessTokenFromStorage,
|
||||
});
|
||||
|
||||
const remoteConfigHandlers = createRemoteConfigHandlers(apiBase);
|
||||
|
||||
const MESSAGE_HANDLERS: Record<string, MessageHandler> = {
|
||||
...customThemesHandlers,
|
||||
...remoteConfigHandlers,
|
||||
searchThemeStockPhotos: handleSearchThemeStockPhotos,
|
||||
reloadTabs: () => reloadSeqtaPages(),
|
||||
setDevApiBase: handleSetDevApiBase,
|
||||
extensionPages: (req) => {
|
||||
browser.tabs.query({}).then((tabs) => {
|
||||
for (const tab of tabs) {
|
||||
if (tab.url?.includes("chrome-extension://")) browser.tabs.sendMessage(tab.id!, req);
|
||||
}
|
||||
});
|
||||
},
|
||||
currentTab: (req, sendResponse) => {
|
||||
browser.tabs.query({ active: true, currentWindow: true }).then((tabs) => {
|
||||
browser.tabs.sendMessage(tabs[0].id!, req).then(sendResponse);
|
||||
});
|
||||
return true;
|
||||
},
|
||||
githubTab: () => {
|
||||
void browser.tabs.create({ url: "github.com/BetterSEQTA/BetterSEQTA-Plus" });
|
||||
},
|
||||
setDefaultStorage: () => SetStorageValue(getDefaultValues()),
|
||||
ensureStorageDefaults: (_req, sendResponse) => {
|
||||
void ensureSyncableStorageDefaults()
|
||||
.then(() => sendResponse({ ok: true }))
|
||||
.catch((e) => {
|
||||
console.warn("[BetterSEQTA+] ensureStorageDefaults failed:", e);
|
||||
sendResponse({ ok: false });
|
||||
});
|
||||
return true;
|
||||
},
|
||||
sendNews: (req, sendResponse, sender) => {
|
||||
if (!isTrustedSender(sender)) {
|
||||
sendResponse({ error: "Unauthorized sender" });
|
||||
return false;
|
||||
}
|
||||
const source = typeof req.source === "string" ? req.source : undefined;
|
||||
void fetchNews(source).then((news) => sendResponse({ news }));
|
||||
return true;
|
||||
},
|
||||
fetchThemes: handleFetchThemes,
|
||||
fetchThemeDetails: handleFetchThemeDetails,
|
||||
fetchFromUrl: handleFetchFromUrl,
|
||||
cloudReserveClient: handleCloudReserveClient,
|
||||
cloudLogin: handleCloudLogin,
|
||||
cloudStartLogin: handleCloudStartLogin,
|
||||
cloudRefresh: handleCloudRefresh,
|
||||
cloudFavorite: handleCloudFavorite,
|
||||
cloudSettingsUpload: handleCloudSettingsUpload,
|
||||
cloudSettingsDownload: handleCloudSettingsDownload,
|
||||
cloudSettingsPoll: () => {
|
||||
void runCloudSettingsPoll();
|
||||
return false;
|
||||
},
|
||||
cloudSettingsRequestDebouncedUpload: () => {
|
||||
requestCloudSettingsDebouncedUpload();
|
||||
return false;
|
||||
},
|
||||
getSeqtaSession: (
|
||||
req: { baseUrl?: string },
|
||||
sendResponse: MessageSender,
|
||||
sender?: chrome.runtime.MessageSender,
|
||||
) => {
|
||||
(async () => {
|
||||
try {
|
||||
let tabId = sender?.tab?.id;
|
||||
let originForCheck: string | undefined = req.baseUrl;
|
||||
|
||||
if (tabId == null) {
|
||||
const tabs = await browser.tabs.query({ active: true, lastFocusedWindow: true });
|
||||
const tab = tabs[0];
|
||||
if (!tab?.id || !tab.url) {
|
||||
sendResponse({ appLink: null });
|
||||
return;
|
||||
}
|
||||
tabId = tab.id;
|
||||
if (!originForCheck) originForCheck = new URL(tab.url).origin;
|
||||
} else if (!originForCheck && sender?.tab?.url) {
|
||||
originForCheck = new URL(sender.tab.url).origin;
|
||||
}
|
||||
|
||||
if (!originForCheck || !isSeqtaOrigin(originForCheck)) {
|
||||
sendResponse({ appLink: null });
|
||||
return;
|
||||
}
|
||||
|
||||
const reply = (await browser.tabs.sendMessage(tabId, { type: "fetchSeqtaAppLink" })) as
|
||||
| { appLink?: string | null }
|
||||
| undefined;
|
||||
const appLink =
|
||||
typeof reply?.appLink === "string" && reply.appLink.length > 0 ? reply.appLink : null;
|
||||
sendResponse({ appLink });
|
||||
} catch (err) {
|
||||
console.error("[Background] getSeqtaSession error:", err);
|
||||
sendResponse({ appLink: null });
|
||||
}
|
||||
})();
|
||||
return true;
|
||||
},
|
||||
};
|
||||
|
||||
registerGoogleCalendarMessageHandlers(
|
||||
MESSAGE_HANDLERS as CalendarMessageHandlerMap,
|
||||
isTrustedSender,
|
||||
);
|
||||
registerOutlookCalendarMessageHandlers(
|
||||
MESSAGE_HANDLERS as CalendarMessageHandlerMap,
|
||||
isTrustedSender,
|
||||
);
|
||||
initCalendarBackground();
|
||||
|
||||
browser.runtime.onMessage.addListener(
|
||||
(
|
||||
request: BackgroundRequest,
|
||||
sender: chrome.runtime.MessageSender,
|
||||
sendResponse: MessageSender,
|
||||
) => {
|
||||
const handler = MESSAGE_HANDLERS[request.type as string];
|
||||
if (handler) {
|
||||
const result = handler(request, sendResponse, sender);
|
||||
return result === true;
|
||||
}
|
||||
console.log("Unknown request type");
|
||||
return false;
|
||||
},
|
||||
);
|
||||
|
||||
function detectLowEndDevice(): boolean {
|
||||
// Check for low-end hardware indicators
|
||||
const lowCoreCount = navigator.hardwareConcurrency && navigator.hardwareConcurrency < 4;
|
||||
const lowMemory = (navigator as any).deviceMemory && (navigator as any).deviceMemory <= 2;
|
||||
|
||||
return lowCoreCount || lowMemory;
|
||||
}
|
||||
|
||||
function getDefaultValues(): SettingsState {
|
||||
const isLowEndDevice = detectLowEndDevice();
|
||||
|
||||
return {
|
||||
onoff: true,
|
||||
animatedbk: true,
|
||||
bksliderinput: "50",
|
||||
transparencyEffects: false,
|
||||
lessonalert: true,
|
||||
defaultmenuorder: [],
|
||||
menuitems: {
|
||||
assessments: { toggle: true },
|
||||
courses: { toggle: true },
|
||||
dashboard: { toggle: true },
|
||||
documents: { toggle: true },
|
||||
forums: { toggle: true },
|
||||
goals: { toggle: true },
|
||||
home: { toggle: true },
|
||||
messages: { toggle: true },
|
||||
myed: { toggle: true },
|
||||
news: { toggle: true },
|
||||
notices: { toggle: true },
|
||||
portals: { toggle: true },
|
||||
reports: { toggle: true },
|
||||
settings: { toggle: true },
|
||||
timetable: { toggle: true },
|
||||
welcome: { toggle: true },
|
||||
},
|
||||
menuorder: [],
|
||||
subjectfilters: {},
|
||||
selectedTheme: "",
|
||||
selectedColor:
|
||||
"linear-gradient(40deg, rgba(201,61,0,1) 0%, RGBA(170, 5, 58, 1) 100%)",
|
||||
originalSelectedColor: "",
|
||||
DarkMode: true,
|
||||
animations: !isLowEndDevice,
|
||||
assessmentsAverage: true,
|
||||
defaultPage: "home",
|
||||
shortcuts: [
|
||||
{
|
||||
name: "Outlook",
|
||||
enabled: true,
|
||||
},
|
||||
{
|
||||
name: "Office",
|
||||
enabled: true,
|
||||
},
|
||||
{
|
||||
name: "Google",
|
||||
enabled: true,
|
||||
},
|
||||
],
|
||||
customshortcuts: [],
|
||||
lettergrade: false,
|
||||
newsSource: "australia",
|
||||
};
|
||||
return getDefaultSettingsState();
|
||||
}
|
||||
|
||||
function SetStorageValue(object: any) {
|
||||
for (var i in object) {
|
||||
browser.storage.local.set({ [i]: object[i] });
|
||||
}
|
||||
function SetStorageValue(object: SettingsState) {
|
||||
void withSuppressedCloudAutoUpload(() =>
|
||||
browser.storage.local.set(object as Record<string, unknown>),
|
||||
);
|
||||
}
|
||||
|
||||
browser.runtime.onInstalled.addListener(function (event) {
|
||||
browser.storage.local.remove(["justupdated"]);
|
||||
browser.storage.local.remove(["data"]);
|
||||
browser.storage.local.remove(["justupdated", "data"]);
|
||||
|
||||
const defaultsReady = ensureSyncableStorageDefaults();
|
||||
|
||||
if (event.reason == "install" || event.reason == "update") {
|
||||
browser.storage.local.set({ justupdated: true });
|
||||
}
|
||||
|
||||
if (event.reason === "update" && event.previousVersion) {
|
||||
void runStorageMigrations(event.previousVersion);
|
||||
void browser.storage.local.remove(BSPLUS_INSTALL_REGISTERED_AT_KEY).then(() => {
|
||||
void refreshRemoteConfig(apiBase);
|
||||
});
|
||||
reloadSeqtaPages();
|
||||
}
|
||||
|
||||
if (event.reason === "install") {
|
||||
void refreshRemoteConfig(apiBase);
|
||||
void browser.storage.local.set({ [DEFAULT_BACKGROUND_PENDING_KEY]: true });
|
||||
void defaultsReady
|
||||
.catch(() => undefined)
|
||||
.then(async () => {
|
||||
const key = "plugin.animated-background.settings";
|
||||
const { [key]: settings } = await browser.storage.local.get(key);
|
||||
await browser.storage.local.set({ [key]: { ...(settings as object), enabled: false } });
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
browser.runtime.onStartup.addListener(() => {
|
||||
void ensureSyncableStorageDefaults();
|
||||
});
|
||||
|
||||
initCloudSettingsAutoSync({ reloadSeqtaPages });
|
||||
initRemoteConfigBackground(apiBase);
|
||||
initTimetableClassmatesBackgroundSync();
|
||||
void ensureSyncableStorageDefaults();
|
||||
@@ -0,0 +1,571 @@
|
||||
import {
|
||||
GOOGLE_AUTH_URL,
|
||||
GOOGLE_CALENDAR_ACCOUNTS_NOT_READY_HINT,
|
||||
GOOGLE_CALENDAR_OAUTH_CALLBACK,
|
||||
GOOGLE_CALENDAR_REFRESH_URL,
|
||||
GOOGLE_CALENDAR_SCOPE,
|
||||
GOOGLE_CALENDAR_TOKEN_URL,
|
||||
GOOGLE_OAUTH_CLIENT_ID,
|
||||
googleOAuthRedirectUriHint,
|
||||
isGoogleCalendarConfigured,
|
||||
} from "@/config/googleCalendar";
|
||||
import {
|
||||
OUTLOOK_AUTH_URL,
|
||||
OUTLOOK_CALENDAR_ACCOUNTS_NOT_READY_HINT,
|
||||
OUTLOOK_CALENDAR_OAUTH_CALLBACK,
|
||||
OUTLOOK_CALENDAR_REFRESH_URL,
|
||||
OUTLOOK_CALENDAR_SCOPE,
|
||||
OUTLOOK_CALENDAR_TOKEN_URL,
|
||||
OUTLOOK_OAUTH_CLIENT_ID,
|
||||
isOutlookCalendarConfigured,
|
||||
outlookOAuthRedirectUriHint,
|
||||
} from "@/config/outlookCalendar";
|
||||
import {
|
||||
exchangeAccountsCode,
|
||||
refreshAccountsToken,
|
||||
type AccountsTokenPayload,
|
||||
} from "@/seqta/utils/calendarSync/accountsToken";
|
||||
import {
|
||||
CALENDAR_WEEKLY_ALARM,
|
||||
clampSyncWeeks,
|
||||
getAutoSyncWeekly,
|
||||
getSyncAssessmentDueDates,
|
||||
getSyncWeeksAhead,
|
||||
isAnyCalendarConnected,
|
||||
markWeeklySyncPending,
|
||||
readSharedCalendarSyncSettings,
|
||||
writeSharedCalendarSyncSettings,
|
||||
} from "@/seqta/utils/calendarSync/settings";
|
||||
import {
|
||||
clearGoogleCalendarState,
|
||||
readGoogleCalendarState,
|
||||
writeGoogleCalendarState,
|
||||
} from "@/seqta/utils/calendarSync/providerStorage";
|
||||
import { ensureGoogleAppCalendar } from "@/seqta/utils/googleCalendar/calendarProvisioning";
|
||||
import type {
|
||||
GoogleCalendarStatus,
|
||||
GoogleCalendarSyncResult,
|
||||
} from "@/seqta/utils/googleCalendar/types";
|
||||
import {
|
||||
clearOutlookCalendarState,
|
||||
readOutlookCalendarState,
|
||||
writeOutlookCalendarState,
|
||||
type OutlookCalendarStatus,
|
||||
} from "@/seqta/utils/calendarSync/providerStorage";
|
||||
import browser from "@/lib/browser";
|
||||
import { isSeqtaTab } from "@/seqta/utils/seqtaTabMatch";
|
||||
|
||||
const WEEKLY_PERIOD_MINUTES = 7 * 24 * 60;
|
||||
|
||||
export type CalendarMessageHandler = (
|
||||
request: unknown,
|
||||
sendResponse: (response?: unknown) => void,
|
||||
sender?: chrome.runtime.MessageSender,
|
||||
) => boolean | void;
|
||||
|
||||
export type CalendarMessageHandlerMap = Record<string, CalendarMessageHandler>;
|
||||
|
||||
type StoredTokens = {
|
||||
accessToken?: string;
|
||||
refreshToken?: string;
|
||||
expiresAt?: number;
|
||||
lastSyncAt?: number;
|
||||
lastSyncOrigin?: string;
|
||||
calendarId?: string;
|
||||
};
|
||||
|
||||
type OAuthTabFlowOptions = {
|
||||
callbackPrefix: string;
|
||||
timeoutMessage: string;
|
||||
cancelledMessage: string;
|
||||
tabOpenErrorMessage: string;
|
||||
timeoutMs?: number;
|
||||
};
|
||||
|
||||
type CalendarProviderBackend = {
|
||||
label: string;
|
||||
isConfigured: () => boolean;
|
||||
redirectHint: () => string;
|
||||
mismatchRe: RegExp;
|
||||
authUrl: string;
|
||||
clientId: string;
|
||||
scope: string;
|
||||
callback: string;
|
||||
tabOpts: Omit<OAuthTabFlowOptions, "callbackPrefix">;
|
||||
notConfiguredError: string;
|
||||
notConnectedError: string;
|
||||
signInFailed: string;
|
||||
read: () => Promise<StoredTokens>;
|
||||
write: (patch: Partial<StoredTokens> & { connectedAt?: number }) => Promise<unknown>;
|
||||
clear: () => Promise<unknown>;
|
||||
exchange: (code: string, redirectUri: string, verifier: string) => Promise<AccountsTokenPayload>;
|
||||
refresh: (refreshToken: string) => Promise<AccountsTokenPayload>;
|
||||
applyAuthParams: (authUrl: URL) => void;
|
||||
messagePrefix: string;
|
||||
afterConnect?: (accessToken: string) => Promise<Partial<StoredTokens>>;
|
||||
};
|
||||
|
||||
function createProviderBackend(
|
||||
config: Omit<CalendarProviderBackend, "exchange" | "refresh"> & {
|
||||
tokenUrl: string;
|
||||
refreshUrl: string;
|
||||
notReadyHint: string;
|
||||
includeErrorDescription?: boolean;
|
||||
},
|
||||
): CalendarProviderBackend {
|
||||
const { tokenUrl, refreshUrl, notReadyHint, includeErrorDescription, ...backend } = config;
|
||||
return {
|
||||
...backend,
|
||||
exchange: (code, redirectUri, verifier) =>
|
||||
exchangeAccountsCode(
|
||||
tokenUrl,
|
||||
code,
|
||||
redirectUri,
|
||||
verifier,
|
||||
notReadyHint,
|
||||
includeErrorDescription,
|
||||
),
|
||||
refresh: (refreshToken) =>
|
||||
refreshAccountsToken(refreshUrl, refreshToken, notReadyHint, includeErrorDescription),
|
||||
};
|
||||
}
|
||||
|
||||
const GOOGLE_BACKEND = createProviderBackend({
|
||||
label: "Google",
|
||||
isConfigured: isGoogleCalendarConfigured,
|
||||
redirectHint: googleOAuthRedirectUriHint,
|
||||
mismatchRe: /redirect_uri_mismatch|invalid_request/i,
|
||||
authUrl: GOOGLE_AUTH_URL,
|
||||
clientId: GOOGLE_OAUTH_CLIENT_ID,
|
||||
scope: GOOGLE_CALENDAR_SCOPE,
|
||||
callback: GOOGLE_CALENDAR_OAUTH_CALLBACK,
|
||||
tabOpts: {
|
||||
timeoutMessage: "Google sign-in timed out. Close the tab and try again.",
|
||||
cancelledMessage: "Google sign-in was cancelled.",
|
||||
tabOpenErrorMessage: "Could not open Google sign-in tab.",
|
||||
},
|
||||
notConfiguredError: "Google Calendar is not configured in this extension build.",
|
||||
notConnectedError: "Not connected to Google Calendar.",
|
||||
signInFailed: "Google sign-in failed",
|
||||
read: readGoogleCalendarState,
|
||||
write: writeGoogleCalendarState,
|
||||
clear: clearGoogleCalendarState,
|
||||
applyAuthParams(authUrl) {
|
||||
authUrl.searchParams.set("access_type", "offline");
|
||||
},
|
||||
messagePrefix: "googleCalendar",
|
||||
tokenUrl: GOOGLE_CALENDAR_TOKEN_URL,
|
||||
refreshUrl: GOOGLE_CALENDAR_REFRESH_URL,
|
||||
notReadyHint: GOOGLE_CALENDAR_ACCOUNTS_NOT_READY_HINT,
|
||||
async afterConnect(accessToken) {
|
||||
const state = await readGoogleCalendarState();
|
||||
const calendarId = await ensureGoogleAppCalendar(accessToken, state.calendarId);
|
||||
return { calendarId };
|
||||
},
|
||||
});
|
||||
|
||||
const OUTLOOK_BACKEND = createProviderBackend({
|
||||
label: "Microsoft",
|
||||
isConfigured: isOutlookCalendarConfigured,
|
||||
redirectHint: outlookOAuthRedirectUriHint,
|
||||
mismatchRe: /redirect_uri|invalid_request|AADSTS50011/i,
|
||||
authUrl: OUTLOOK_AUTH_URL,
|
||||
clientId: OUTLOOK_OAUTH_CLIENT_ID,
|
||||
scope: OUTLOOK_CALENDAR_SCOPE,
|
||||
callback: OUTLOOK_CALENDAR_OAUTH_CALLBACK,
|
||||
tabOpts: {
|
||||
timeoutMessage: "Microsoft sign-in timed out. Close the tab and try again.",
|
||||
cancelledMessage: "Microsoft sign-in was cancelled.",
|
||||
tabOpenErrorMessage: "Could not open Microsoft sign-in tab.",
|
||||
},
|
||||
notConfiguredError: "Outlook Calendar is not configured in this extension build.",
|
||||
notConnectedError: "Not connected to Outlook Calendar.",
|
||||
signInFailed: "Microsoft sign-in failed",
|
||||
read: readOutlookCalendarState,
|
||||
write: writeOutlookCalendarState,
|
||||
clear: clearOutlookCalendarState,
|
||||
applyAuthParams(authUrl) {
|
||||
authUrl.searchParams.set("response_mode", "query");
|
||||
},
|
||||
messagePrefix: "outlookCalendar",
|
||||
tokenUrl: OUTLOOK_CALENDAR_TOKEN_URL,
|
||||
refreshUrl: OUTLOOK_CALENDAR_REFRESH_URL,
|
||||
notReadyHint: OUTLOOK_CALENDAR_ACCOUNTS_NOT_READY_HINT,
|
||||
includeErrorDescription: true,
|
||||
});
|
||||
|
||||
function base64UrlEncode(buffer: ArrayBuffer): string {
|
||||
const bytes = new Uint8Array(buffer);
|
||||
let binary = "";
|
||||
for (const b of bytes) binary += String.fromCharCode(b);
|
||||
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
|
||||
}
|
||||
|
||||
function randomPkceVerifier(): string {
|
||||
const bytes = new Uint8Array(32);
|
||||
crypto.getRandomValues(bytes);
|
||||
return base64UrlEncode(bytes.buffer);
|
||||
}
|
||||
|
||||
async function pkceChallenge(verifier: string): Promise<string> {
|
||||
const data = new TextEncoder().encode(verifier);
|
||||
const digest = await crypto.subtle.digest("SHA-256", data);
|
||||
return base64UrlEncode(digest);
|
||||
}
|
||||
|
||||
function parseOAuthRedirectCode(responseUrl: string, providerLabel: string): string {
|
||||
const url = new URL(responseUrl);
|
||||
const err = url.searchParams.get("error");
|
||||
if (err) throw new Error(url.searchParams.get("error_description") ?? err);
|
||||
const code = url.searchParams.get("code");
|
||||
if (!code) throw new Error(`${providerLabel} sign-in did not return an authorization code.`);
|
||||
return code;
|
||||
}
|
||||
|
||||
function isOAuthCallbackUrl(url: string, callbackPrefix: string): boolean {
|
||||
if (!url.startsWith(callbackPrefix)) return false;
|
||||
const parsed = new URL(url);
|
||||
return parsed.searchParams.has("code") || parsed.searchParams.has("error");
|
||||
}
|
||||
|
||||
function waitForOAuthCallback(authTabId: number, opts: OAuthTabFlowOptions): Promise<string> {
|
||||
const timeoutMs = opts.timeoutMs ?? 10 * 60 * 1000;
|
||||
return new Promise((resolve, reject) => {
|
||||
const timeoutId = setTimeout(() => {
|
||||
cleanup();
|
||||
reject(new Error(opts.timeoutMessage));
|
||||
}, timeoutMs);
|
||||
|
||||
const cleanup = () => {
|
||||
clearTimeout(timeoutId);
|
||||
browser.tabs.onUpdated.removeListener(onUpdated);
|
||||
browser.tabs.onRemoved.removeListener(onRemoved);
|
||||
};
|
||||
|
||||
const finishFromUrl = (url: string, tabId: number) => {
|
||||
if (!isOAuthCallbackUrl(url, opts.callbackPrefix)) return false;
|
||||
cleanup();
|
||||
void browser.tabs.remove(tabId).catch(() => {});
|
||||
resolve(url);
|
||||
return true;
|
||||
};
|
||||
|
||||
const onRemoved = (tabId: number) => {
|
||||
if (tabId !== authTabId) return;
|
||||
cleanup();
|
||||
reject(new Error(opts.cancelledMessage));
|
||||
};
|
||||
|
||||
const onUpdated = (
|
||||
tabId: number,
|
||||
changeInfo: chrome.tabs.OnUpdatedInfo,
|
||||
tab: chrome.tabs.Tab,
|
||||
) => {
|
||||
if (tabId !== authTabId) return;
|
||||
const url = changeInfo.url ?? (changeInfo.status === "complete" ? tab.url : undefined);
|
||||
if (url) finishFromUrl(url, tabId);
|
||||
};
|
||||
|
||||
browser.tabs.onUpdated.addListener(onUpdated);
|
||||
browser.tabs.onRemoved.addListener(onRemoved);
|
||||
|
||||
void browser.tabs
|
||||
.get(authTabId)
|
||||
.then((tab) => {
|
||||
if (tab.url) finishFromUrl(tab.url, authTabId);
|
||||
})
|
||||
.catch(() => {});
|
||||
});
|
||||
}
|
||||
|
||||
async function openOAuthTab(authUrl: string, opts: OAuthTabFlowOptions): Promise<string> {
|
||||
const tab = await browser.tabs.create({ url: authUrl, active: true });
|
||||
if (tab.id === undefined) throw new Error(opts.tabOpenErrorMessage);
|
||||
return waitForOAuthCallback(tab.id, opts);
|
||||
}
|
||||
|
||||
function tokenExpiresAt(expiresIn?: number): number {
|
||||
return expiresIn ? Date.now() + expiresIn * 1000 : Date.now() + 3_600_000;
|
||||
}
|
||||
|
||||
async function getValidStoredAccessToken(provider: CalendarProviderBackend): Promise<string> {
|
||||
const state = await provider.read();
|
||||
const now = Date.now();
|
||||
if (state.accessToken && state.expiresAt && state.expiresAt > now + 60_000) {
|
||||
return state.accessToken;
|
||||
}
|
||||
if (!state.refreshToken) throw new Error(provider.notConnectedError);
|
||||
const refreshed = await provider.refresh(state.refreshToken);
|
||||
await provider.write({
|
||||
accessToken: refreshed.access_token,
|
||||
refreshToken: refreshed.refresh_token ?? state.refreshToken,
|
||||
expiresAt: tokenExpiresAt(refreshed.expires_in),
|
||||
});
|
||||
return refreshed.access_token;
|
||||
}
|
||||
|
||||
export function registerTrustedAsyncHandler(
|
||||
handlers: CalendarMessageHandlerMap,
|
||||
isTrustedSender: (sender?: chrome.runtime.MessageSender) => boolean,
|
||||
key: string,
|
||||
fn: (request: unknown) => Promise<unknown>,
|
||||
onError?: (err: unknown) => unknown,
|
||||
): void {
|
||||
handlers[key] = (request, sendResponse, sender) => {
|
||||
if (!isTrustedSender(sender)) {
|
||||
sendResponse({ success: false, error: "Unauthorized sender" });
|
||||
return false;
|
||||
}
|
||||
void fn(request)
|
||||
.then(sendResponse)
|
||||
.catch((err) => {
|
||||
sendResponse(
|
||||
onError?.(err) ?? {
|
||||
success: false,
|
||||
error: err instanceof Error ? err.message : "Request failed",
|
||||
},
|
||||
);
|
||||
});
|
||||
return true;
|
||||
};
|
||||
}
|
||||
|
||||
async function getGoogleCalendarStatus(): Promise<GoogleCalendarStatus> {
|
||||
const [state, shared, syncWeeksAhead, autoSyncWeekly, syncAssessmentDueDates] = await Promise.all(
|
||||
[
|
||||
readGoogleCalendarState(),
|
||||
readSharedCalendarSyncSettings(),
|
||||
getSyncWeeksAhead(),
|
||||
getAutoSyncWeekly(),
|
||||
getSyncAssessmentDueDates(),
|
||||
],
|
||||
);
|
||||
return {
|
||||
configured: isGoogleCalendarConfigured(),
|
||||
connected: !!(state.refreshToken || state.accessToken),
|
||||
lastSyncAt: state.lastSyncAt,
|
||||
lastWeeklySyncAt: shared.lastWeeklySyncAt,
|
||||
lastSyncOrigin: state.lastSyncOrigin,
|
||||
syncWeeksAhead,
|
||||
autoSyncWeekly,
|
||||
syncAssessmentDueDates,
|
||||
};
|
||||
}
|
||||
|
||||
async function getOutlookCalendarStatus(): Promise<OutlookCalendarStatus> {
|
||||
const state = await readOutlookCalendarState();
|
||||
return {
|
||||
configured: isOutlookCalendarConfigured(),
|
||||
connected: !!(state.refreshToken || state.accessToken),
|
||||
lastSyncAt: state.lastSyncAt,
|
||||
lastSyncOrigin: state.lastSyncOrigin,
|
||||
};
|
||||
}
|
||||
|
||||
async function connectCalendar(
|
||||
provider: CalendarProviderBackend,
|
||||
): Promise<GoogleCalendarSyncResult> {
|
||||
if (!provider.isConfigured()) {
|
||||
return { success: false, configured: false, error: provider.notConfiguredError };
|
||||
}
|
||||
|
||||
const redirectUri = provider.callback;
|
||||
const verifier = randomPkceVerifier();
|
||||
const challenge = await pkceChallenge(verifier);
|
||||
const authUrl = new URL(provider.authUrl);
|
||||
authUrl.searchParams.set("client_id", provider.clientId);
|
||||
authUrl.searchParams.set("response_type", "code");
|
||||
authUrl.searchParams.set("redirect_uri", redirectUri);
|
||||
authUrl.searchParams.set("scope", provider.scope);
|
||||
authUrl.searchParams.set("prompt", "consent");
|
||||
authUrl.searchParams.set("code_challenge", challenge);
|
||||
authUrl.searchParams.set("code_challenge_method", "S256");
|
||||
provider.applyAuthParams(authUrl);
|
||||
|
||||
let responseUrl: string;
|
||||
try {
|
||||
responseUrl = await openOAuthTab(authUrl.toString(), {
|
||||
callbackPrefix: provider.callback,
|
||||
...provider.tabOpts,
|
||||
});
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : provider.signInFailed;
|
||||
const mismatch = provider.mismatchRe.test(message) || provider.mismatchRe.test(String(err));
|
||||
return {
|
||||
success: false,
|
||||
configured: true,
|
||||
error: mismatch
|
||||
? `${provider.label} redirect URI mismatch. ${provider.redirectHint()}`
|
||||
: message.includes("cancel")
|
||||
? provider.tabOpts.cancelledMessage
|
||||
: message,
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const code = parseOAuthRedirectCode(responseUrl, provider.label);
|
||||
const tokens = await provider.exchange(code, redirectUri, verifier);
|
||||
const existing = await provider.read();
|
||||
await provider.write({
|
||||
accessToken: tokens.access_token,
|
||||
refreshToken: tokens.refresh_token ?? existing.refreshToken,
|
||||
expiresAt: tokenExpiresAt(tokens.expires_in),
|
||||
connectedAt: Date.now(),
|
||||
});
|
||||
if (provider.afterConnect) {
|
||||
const patch = await provider.afterConnect(tokens.access_token);
|
||||
if (patch && Object.keys(patch).length > 0) {
|
||||
await provider.write(patch);
|
||||
}
|
||||
}
|
||||
await ensureWeeklySyncAlarm();
|
||||
return { success: true, configured: true, connected: true };
|
||||
} catch (err) {
|
||||
return {
|
||||
success: false,
|
||||
configured: true,
|
||||
error: err instanceof Error ? err.message : provider.signInFailed,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function registerProviderHandlers(
|
||||
handlers: CalendarMessageHandlerMap,
|
||||
isTrustedSender: (sender?: chrome.runtime.MessageSender) => boolean,
|
||||
provider: CalendarProviderBackend,
|
||||
getStatus: () => Promise<unknown>,
|
||||
): void {
|
||||
const { messagePrefix, signInFailed } = provider;
|
||||
const errMsg = (err: unknown, fallback: string) =>
|
||||
err instanceof Error ? err.message : fallback;
|
||||
|
||||
registerTrustedAsyncHandler(
|
||||
handlers,
|
||||
isTrustedSender,
|
||||
`${messagePrefix}Connect`,
|
||||
() => connectCalendar(provider),
|
||||
(err) => ({ success: false, error: errMsg(err, signInFailed) }),
|
||||
);
|
||||
|
||||
registerTrustedAsyncHandler(
|
||||
handlers,
|
||||
isTrustedSender,
|
||||
`${messagePrefix}Disconnect`,
|
||||
async () => {
|
||||
await provider.clear();
|
||||
await ensureWeeklySyncAlarm();
|
||||
return { success: true };
|
||||
},
|
||||
(err) => ({ success: false, error: errMsg(err, "Disconnect failed") }),
|
||||
);
|
||||
|
||||
registerTrustedAsyncHandler(
|
||||
handlers,
|
||||
isTrustedSender,
|
||||
`${messagePrefix}Status`,
|
||||
getStatus,
|
||||
() => ({ configured: provider.isConfigured(), connected: false }),
|
||||
);
|
||||
|
||||
registerTrustedAsyncHandler(
|
||||
handlers,
|
||||
isTrustedSender,
|
||||
`${messagePrefix}GetAccessToken`,
|
||||
() =>
|
||||
getValidStoredAccessToken(provider).then((accessToken) => ({ success: true, accessToken })),
|
||||
(err) => ({ success: false, error: errMsg(err, "Token refresh failed") }),
|
||||
);
|
||||
}
|
||||
|
||||
export function registerGoogleCalendarMessageHandlers(
|
||||
handlers: CalendarMessageHandlerMap,
|
||||
isTrustedSender: (sender?: chrome.runtime.MessageSender) => boolean,
|
||||
): void {
|
||||
registerProviderHandlers(handlers, isTrustedSender, GOOGLE_BACKEND, getGoogleCalendarStatus);
|
||||
|
||||
registerTrustedAsyncHandler(
|
||||
handlers,
|
||||
isTrustedSender,
|
||||
"googleCalendarEnsureWeeklyAlarm",
|
||||
async () => {
|
||||
await ensureWeeklySyncAlarm();
|
||||
return { success: true };
|
||||
},
|
||||
(err) => ({
|
||||
success: false,
|
||||
error: err instanceof Error ? err.message : "Could not schedule weekly sync",
|
||||
}),
|
||||
);
|
||||
|
||||
registerTrustedAsyncHandler(
|
||||
handlers,
|
||||
isTrustedSender,
|
||||
"googleCalendarUpdateSyncSettings",
|
||||
async (request) => {
|
||||
const body = request as {
|
||||
syncWeeksAhead?: number;
|
||||
autoSyncWeekly?: boolean;
|
||||
syncAssessmentDueDates?: boolean;
|
||||
};
|
||||
const patch: Record<string, unknown> = {};
|
||||
if (body.syncWeeksAhead != null) patch.syncWeeksAhead = clampSyncWeeks(body.syncWeeksAhead);
|
||||
if (body.autoSyncWeekly != null) patch.autoSyncWeekly = !!body.autoSyncWeekly;
|
||||
if (body.syncAssessmentDueDates != null) {
|
||||
patch.syncAssessmentDueDates = !!body.syncAssessmentDueDates;
|
||||
}
|
||||
if (Object.keys(patch).length > 0) await writeSharedCalendarSyncSettings(patch);
|
||||
await ensureWeeklySyncAlarm();
|
||||
return { success: true, ...(await getGoogleCalendarStatus()) };
|
||||
},
|
||||
(err) => ({
|
||||
success: false,
|
||||
error: err instanceof Error ? err.message : "Could not update sync settings",
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export function registerOutlookCalendarMessageHandlers(
|
||||
handlers: CalendarMessageHandlerMap,
|
||||
isTrustedSender: (sender?: chrome.runtime.MessageSender) => boolean,
|
||||
): void {
|
||||
registerProviderHandlers(handlers, isTrustedSender, OUTLOOK_BACKEND, getOutlookCalendarStatus);
|
||||
}
|
||||
|
||||
export async function ensureWeeklySyncAlarm(): Promise<void> {
|
||||
const [connected, enabled] = await Promise.all([isAnyCalendarConnected(), getAutoSyncWeekly()]);
|
||||
if (!connected || !enabled) {
|
||||
await browser.alarms.clear(CALENDAR_WEEKLY_ALARM);
|
||||
return;
|
||||
}
|
||||
const existing = await browser.alarms.get(CALENDAR_WEEKLY_ALARM);
|
||||
if (!existing) {
|
||||
await browser.alarms.create(CALENDAR_WEEKLY_ALARM, { periodInMinutes: WEEKLY_PERIOD_MINUTES });
|
||||
}
|
||||
}
|
||||
|
||||
async function triggerWeeklySyncOnSeqtaTabs(): Promise<boolean> {
|
||||
const tabs = await browser.tabs.query({});
|
||||
let delivered = false;
|
||||
for (const tab of tabs) {
|
||||
if (tab.id == null || !isSeqtaTab(tab)) continue;
|
||||
try {
|
||||
await browser.tabs.sendMessage(tab.id, { type: "calendarRunWeeklySync" });
|
||||
delivered = true;
|
||||
} catch {
|
||||
// Tab may not have content script yet.
|
||||
}
|
||||
}
|
||||
return delivered;
|
||||
}
|
||||
|
||||
async function handleWeeklySyncAlarm(): Promise<void> {
|
||||
if (!(await isAnyCalendarConnected()) || !(await getAutoSyncWeekly())) return;
|
||||
if (!(await triggerWeeklySyncOnSeqtaTabs())) await markWeeklySyncPending();
|
||||
}
|
||||
|
||||
export function initCalendarBackground(): void {
|
||||
browser.alarms.onAlarm.addListener((alarm) => {
|
||||
if (alarm.name === CALENDAR_WEEKLY_ALARM) void handleWeeklySyncAlarm();
|
||||
});
|
||||
void ensureWeeklySyncAlarm();
|
||||
}
|
||||
@@ -0,0 +1,493 @@
|
||||
import browser from "@/lib/browser";
|
||||
import {
|
||||
ensureSyncableStorageDefaults,
|
||||
getSyncableStorageDefaults,
|
||||
} from "@/seqta/utils/ensureSyncableStorageDefaults";
|
||||
import {
|
||||
applyDownloadedEnvelope,
|
||||
BSPLUS_CLOUD_KNOWN_REMOTE_UPDATED_AT_KEY,
|
||||
BSPLUS_PENDING_THEME_ENSURE_AFTER_CLOUD_KEY,
|
||||
buildUploadPatch,
|
||||
CLOUD_SETTINGS_SYNC_SCHEMA_VERSION,
|
||||
isKeyIncludedInCloudUploadPayload,
|
||||
normalizeStorageForSync,
|
||||
resolveThemeIdForPostSyncDownload,
|
||||
saveLastUploadedSnapshot,
|
||||
getLastUploadedSnapshot,
|
||||
setKnownRemoteUpdatedAt,
|
||||
} from "@/seqta/utils/cloudSettingsSync";
|
||||
import { isRemoteCloudSyncDisabled } from "./remoteConfig";
|
||||
|
||||
const ACCOUNTS_BASE = "https://accounts.betterseqta.org";
|
||||
export const CLOUD_SUMMARY_URL = `${ACCOUNTS_BASE}/api/user/cloud-summary`;
|
||||
const CLOUD_SETTINGS_SYNC_URL = `${ACCOUNTS_BASE}/api/bsplus/settings/sync`;
|
||||
const REFRESH_URL = `${ACCOUNTS_BASE}/api/bsplus/refresh`;
|
||||
|
||||
const UPLOAD_DEBOUNCE_MS = 2000;
|
||||
const POLL_THROTTLE_MS = 24 * 60 * 60 * 1000;
|
||||
const POLL_THROTTLE_KEY = "bsplus_lastCloudPoll";
|
||||
const FETCH_TIMEOUT_MS = 30_000;
|
||||
|
||||
function fetchWithTimeout(url: string, init?: RequestInit): Promise<Response> {
|
||||
return fetch(url, { ...init, signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) });
|
||||
}
|
||||
|
||||
type CloudSummaryResponse = {
|
||||
desqta?: unknown;
|
||||
bsplus?: { updated_at: string; schemaVersion: number } | null;
|
||||
};
|
||||
|
||||
let reloadSeqtaPagesFn: (() => void) | null = null;
|
||||
let suppressAutoUploadDuringRestore = false;
|
||||
let debounceTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let pollInFlight: Promise<void> | null = null;
|
||||
let autoSyncInitialized = false;
|
||||
|
||||
function isAutoCloudSyncEnabled(all: Record<string, unknown>): boolean {
|
||||
return all.autoCloudSettingsSync !== false;
|
||||
}
|
||||
|
||||
type CloudJsonBody = {
|
||||
access_token?: string;
|
||||
refresh_token?: string;
|
||||
user?: unknown;
|
||||
error?: string;
|
||||
updated_at?: string;
|
||||
};
|
||||
|
||||
function asCloudJsonBody(data: unknown): CloudJsonBody {
|
||||
return data && typeof data === "object" ? (data as CloudJsonBody) : {};
|
||||
}
|
||||
|
||||
async function parseJsonResponse(r: Response): Promise<unknown> {
|
||||
const text = await r.text();
|
||||
try {
|
||||
return text ? JSON.parse(text) : {};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
async function getAccessToken(): Promise<string | null> {
|
||||
const { bsplus_token } = await browser.storage.local.get("bsplus_token");
|
||||
return typeof bsplus_token === "string" && bsplus_token.length > 0 ? bsplus_token : null;
|
||||
}
|
||||
|
||||
async function tryRefreshTokens(): Promise<boolean> {
|
||||
const result = await browser.storage.local.get([
|
||||
"bsplus_refresh_token",
|
||||
"bsplus_client_id",
|
||||
"bsplus_user",
|
||||
]);
|
||||
const refresh_token = result.bsplus_refresh_token as string | undefined;
|
||||
const client_id = result.bsplus_client_id as string | undefined;
|
||||
if (!refresh_token || !client_id) return false;
|
||||
|
||||
try {
|
||||
const r = await fetchWithTimeout(REFRESH_URL, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ refresh_token, client_id }),
|
||||
});
|
||||
const data = asCloudJsonBody(await parseJsonResponse(r));
|
||||
if (!r.ok || !data.access_token || !data.refresh_token) return false;
|
||||
|
||||
await browser.storage.local.set({
|
||||
bsplus_token: data.access_token,
|
||||
bsplus_refresh_token: data.refresh_token,
|
||||
bsplus_user: data.user ?? result.bsplus_user,
|
||||
});
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function isServerTimestampNewer(serverIso: string, localIso: string | undefined): boolean {
|
||||
const a = Date.parse(serverIso);
|
||||
if (Number.isNaN(a)) return false;
|
||||
if (localIso === undefined || localIso === "") return true;
|
||||
const b = Date.parse(localIso);
|
||||
if (Number.isNaN(b)) return true;
|
||||
return a > b;
|
||||
}
|
||||
|
||||
async function fetchCloudSummaryOnce(
|
||||
token: string,
|
||||
): Promise<
|
||||
{ ok: true; data: CloudSummaryResponse } | { ok: false; unauthorized: boolean; error?: string }
|
||||
> {
|
||||
try {
|
||||
const r = await fetchWithTimeout(CLOUD_SUMMARY_URL, {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
cache: "no-store",
|
||||
});
|
||||
const data = (await parseJsonResponse(r)) as CloudSummaryResponse;
|
||||
if (r.status === 401) return { ok: false, unauthorized: true };
|
||||
if (!r.ok) {
|
||||
return {
|
||||
ok: false,
|
||||
unauthorized: false,
|
||||
error: (data as { error?: string })?.error ?? `Summary failed (${r.status})`,
|
||||
};
|
||||
}
|
||||
return { ok: true, data };
|
||||
} catch (e) {
|
||||
return {
|
||||
ok: false,
|
||||
unauthorized: false,
|
||||
error: e instanceof Error ? e.message : "Network error",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchCloudSummaryWithAuthRetry(token: string): Promise<CloudSummaryResponse | null> {
|
||||
let t = token;
|
||||
for (let attempt = 0; attempt < 2; attempt++) {
|
||||
const res = await fetchCloudSummaryOnce(t);
|
||||
if (res.ok) return res.data;
|
||||
if (res.unauthorized && attempt === 0) {
|
||||
const refreshed = await tryRefreshTokens();
|
||||
if (!refreshed) break;
|
||||
const next = await getAccessToken();
|
||||
if (!next) break;
|
||||
t = next;
|
||||
continue;
|
||||
}
|
||||
if (res.error) console.warn("[BS+ cloud sync] cloud-summary:", res.error);
|
||||
break;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
type PutResult =
|
||||
| { ok: true; updated_at?: string; skipped?: boolean }
|
||||
| { ok: false; unauthorized: boolean; error?: string };
|
||||
|
||||
async function resolveUploadBaseline(
|
||||
normalized: Record<string, unknown>,
|
||||
watermark: string | undefined,
|
||||
): Promise<Record<string, unknown>> {
|
||||
const lastSnapshot = await getLastUploadedSnapshot();
|
||||
if (lastSnapshot) return lastSnapshot;
|
||||
|
||||
if (watermark) {
|
||||
await saveLastUploadedSnapshot(normalized);
|
||||
return normalized;
|
||||
}
|
||||
|
||||
return getSyncableStorageDefaults();
|
||||
}
|
||||
|
||||
async function putSettingsOnce(token: string): Promise<PutResult> {
|
||||
try {
|
||||
await ensureSyncableStorageDefaults();
|
||||
|
||||
const all = (await browser.storage.local.get()) as Record<string, unknown>;
|
||||
const normalized = normalizeStorageForSync(all);
|
||||
const watermark = all[BSPLUS_CLOUD_KNOWN_REMOTE_UPDATED_AT_KEY] as string | undefined;
|
||||
const baseline = await resolveUploadBaseline(normalized, watermark);
|
||||
const payload = buildUploadPatch(all, baseline);
|
||||
|
||||
if (!payload) {
|
||||
return { ok: true, skipped: true };
|
||||
}
|
||||
|
||||
const r = await fetchWithTimeout(CLOUD_SETTINGS_SYNC_URL, {
|
||||
method: "PUT",
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
const data = asCloudJsonBody(await parseJsonResponse(r));
|
||||
if (r.status === 401) return { ok: false, unauthorized: true };
|
||||
if (!r.ok) {
|
||||
return {
|
||||
ok: false,
|
||||
unauthorized: false,
|
||||
error: data.error ?? `Upload failed (${r.status})`,
|
||||
};
|
||||
}
|
||||
const updated_at = data.updated_at;
|
||||
await saveLastUploadedSnapshot(normalized);
|
||||
await setKnownRemoteUpdatedAt(updated_at);
|
||||
return { ok: true, updated_at };
|
||||
} catch (e) {
|
||||
return {
|
||||
ok: false,
|
||||
unauthorized: false,
|
||||
error: e instanceof Error ? e.message : "Upload failed",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export async function performCloudSettingsUploadWithRetry(
|
||||
token: string,
|
||||
): Promise<{ success: boolean; error?: string; updated_at?: string; skipped?: boolean }> {
|
||||
if (await isRemoteCloudSyncDisabled()) {
|
||||
return { success: false, error: "Cloud sync disabled by remote config", skipped: true };
|
||||
}
|
||||
let t = token;
|
||||
for (let attempt = 0; attempt < 2; attempt++) {
|
||||
const res = await putSettingsOnce(t);
|
||||
if (res.ok) {
|
||||
return { success: true, updated_at: res.updated_at, skipped: res.skipped };
|
||||
}
|
||||
if (res.unauthorized && attempt === 0) {
|
||||
const refreshed = await tryRefreshTokens();
|
||||
if (!refreshed) return { success: false, error: "Not authenticated" };
|
||||
const next = await getAccessToken();
|
||||
if (!next) return { success: false, error: "Not authenticated" };
|
||||
t = next;
|
||||
continue;
|
||||
}
|
||||
return { success: false, error: res.error ?? "Upload failed" };
|
||||
}
|
||||
return { success: false, error: "Upload failed" };
|
||||
}
|
||||
|
||||
type GetResult =
|
||||
| { ok: true; updated_at?: string }
|
||||
| { ok: false; notFound?: boolean; unauthorized: boolean; error?: string };
|
||||
|
||||
async function getSettingsAndApplyOnce(token: string): Promise<GetResult> {
|
||||
try {
|
||||
const r = await fetchWithTimeout(CLOUD_SETTINGS_SYNC_URL, {
|
||||
method: "GET",
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
cache: "no-store",
|
||||
});
|
||||
const data = asCloudJsonBody(await parseJsonResponse(r));
|
||||
if (r.status === 401) return { ok: false, unauthorized: true };
|
||||
if (r.status === 404) {
|
||||
return {
|
||||
ok: false,
|
||||
notFound: true,
|
||||
unauthorized: false,
|
||||
error: "No settings backup found in the cloud",
|
||||
};
|
||||
}
|
||||
if (!r.ok) {
|
||||
return {
|
||||
ok: false,
|
||||
unauthorized: false,
|
||||
error: data.error ?? `Download failed (${r.status})`,
|
||||
};
|
||||
}
|
||||
const themeIdToEnsure = resolveThemeIdForPostSyncDownload(data);
|
||||
await applyDownloadedEnvelope(data);
|
||||
if (themeIdToEnsure) {
|
||||
await browser.storage.local.set({
|
||||
[BSPLUS_PENDING_THEME_ENSURE_AFTER_CLOUD_KEY]: themeIdToEnsure,
|
||||
});
|
||||
} else {
|
||||
await browser.storage.local.remove(BSPLUS_PENDING_THEME_ENSURE_AFTER_CLOUD_KEY);
|
||||
}
|
||||
reloadSeqtaPagesFn?.();
|
||||
const updated_at = data?.updated_at as string | undefined;
|
||||
await setKnownRemoteUpdatedAt(updated_at);
|
||||
await saveLastUploadedSnapshot(
|
||||
normalizeStorageForSync((await browser.storage.local.get()) as Record<string, unknown>),
|
||||
);
|
||||
return { ok: true, updated_at };
|
||||
} catch (e) {
|
||||
return {
|
||||
ok: false,
|
||||
unauthorized: false,
|
||||
error: e instanceof Error ? e.message : "Download failed",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export async function performCloudSettingsDownloadWithRetry(
|
||||
token: string,
|
||||
): Promise<{ success: boolean; notFound?: boolean; error?: string; updated_at?: string }> {
|
||||
suppressAutoUploadDuringRestore = true;
|
||||
try {
|
||||
let t = token;
|
||||
for (let attempt = 0; attempt < 2; attempt++) {
|
||||
const res = await getSettingsAndApplyOnce(t);
|
||||
if (res.ok) return { success: true, updated_at: res.updated_at };
|
||||
if (res.unauthorized && attempt === 0) {
|
||||
const refreshed = await tryRefreshTokens();
|
||||
if (!refreshed) return { success: false, error: "Not authenticated" };
|
||||
const next = await getAccessToken();
|
||||
if (!next) return { success: false, error: "Not authenticated" };
|
||||
t = next;
|
||||
continue;
|
||||
}
|
||||
return {
|
||||
success: false,
|
||||
notFound: res.notFound,
|
||||
error: res.error ?? "Download failed",
|
||||
};
|
||||
}
|
||||
return { success: false, error: "Download failed" };
|
||||
} finally {
|
||||
suppressAutoUploadDuringRestore = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function maybeUploadBaseline(token: string): Promise<void> {
|
||||
const res = await performCloudSettingsUploadWithRetry(token);
|
||||
if (!res.success) {
|
||||
console.warn("[BS+ cloud sync] Baseline upload failed:", res.error);
|
||||
}
|
||||
}
|
||||
|
||||
async function downloadIfNeeded(token: string): Promise<void> {
|
||||
const res = await performCloudSettingsDownloadWithRetry(token);
|
||||
if (!res.success && !res.notFound) {
|
||||
console.warn("[BS+ cloud sync] Auto-download failed:", res.error);
|
||||
}
|
||||
}
|
||||
|
||||
async function runCloudSettingsPollInner(): Promise<void> {
|
||||
if (await isRemoteCloudSyncDisabled()) return;
|
||||
|
||||
const all = (await browser.storage.local.get()) as Record<string, unknown>;
|
||||
if (!isAutoCloudSyncEnabled(all)) return;
|
||||
|
||||
let token = await getAccessToken();
|
||||
if (!token) return;
|
||||
|
||||
const summary = await fetchCloudSummaryWithAuthRetry(token);
|
||||
if (!summary) return;
|
||||
|
||||
const bsplus = summary.bsplus;
|
||||
const watermark = all[BSPLUS_CLOUD_KNOWN_REMOTE_UPDATED_AT_KEY] as string | undefined;
|
||||
|
||||
if (
|
||||
bsplus &&
|
||||
typeof bsplus.schemaVersion === "number" &&
|
||||
bsplus.schemaVersion > CLOUD_SETTINGS_SYNC_SCHEMA_VERSION
|
||||
) {
|
||||
console.warn("[BS+ cloud sync] Server schemaVersion newer than client; skip auto-download");
|
||||
return;
|
||||
}
|
||||
|
||||
token = (await getAccessToken()) ?? token;
|
||||
|
||||
if (!watermark) {
|
||||
if (!bsplus?.updated_at) {
|
||||
await maybeUploadBaseline(token);
|
||||
return;
|
||||
}
|
||||
await downloadIfNeeded(token);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!bsplus?.updated_at) return;
|
||||
|
||||
if (isServerTimestampNewer(bsplus.updated_at, watermark)) {
|
||||
await downloadIfNeeded(token);
|
||||
}
|
||||
}
|
||||
|
||||
export function runCloudSettingsPoll(): Promise<void> {
|
||||
if (pollInFlight) return pollInFlight;
|
||||
pollInFlight = (async () => {
|
||||
try {
|
||||
const { [POLL_THROTTLE_KEY]: last } = await browser.storage.local.get(POLL_THROTTLE_KEY);
|
||||
if (Date.now() - (Number(last) || 0) < POLL_THROTTLE_MS) return;
|
||||
await runCloudSettingsPollInner();
|
||||
await browser.storage.local.set({ [POLL_THROTTLE_KEY]: Date.now() });
|
||||
} catch (e) {
|
||||
console.error("[BS+ cloud sync] Poll error:", e);
|
||||
} finally {
|
||||
pollInFlight = null;
|
||||
}
|
||||
})();
|
||||
return pollInFlight;
|
||||
}
|
||||
|
||||
function clearUploadDebounce(): void {
|
||||
if (debounceTimer) {
|
||||
clearTimeout(debounceTimer);
|
||||
debounceTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
function scheduleDebouncedUpload(): void {
|
||||
if (suppressAutoUploadDuringRestore) return;
|
||||
clearUploadDebounce();
|
||||
debounceTimer = setTimeout(() => {
|
||||
debounceTimer = null;
|
||||
void runDebouncedUploadJob();
|
||||
}, UPLOAD_DEBOUNCE_MS);
|
||||
}
|
||||
|
||||
/** Call after store theme install (and similar) so cloud upload runs even if storage events are flaky. */
|
||||
export function requestCloudSettingsDebouncedUpload(): void {
|
||||
void (async () => {
|
||||
if (await isRemoteCloudSyncDisabled()) return;
|
||||
const all = (await browser.storage.local.get()) as Record<string, unknown>;
|
||||
if (!isAutoCloudSyncEnabled(all)) return;
|
||||
if (suppressAutoUploadDuringRestore) return;
|
||||
if (!(await getAccessToken())) return;
|
||||
scheduleDebouncedUpload();
|
||||
})();
|
||||
}
|
||||
|
||||
async function runDebouncedUploadJob(): Promise<void> {
|
||||
if (await isRemoteCloudSyncDisabled()) return;
|
||||
const all = (await browser.storage.local.get()) as Record<string, unknown>;
|
||||
if (!isAutoCloudSyncEnabled(all)) return;
|
||||
const token = await getAccessToken();
|
||||
if (!token) return;
|
||||
const res = await performCloudSettingsUploadWithRetry(token);
|
||||
if (!res.success) {
|
||||
console.warn("[BS+ cloud sync] Auto-upload failed:", res.error);
|
||||
}
|
||||
}
|
||||
|
||||
async function syncAutoUploadWithStorage(): Promise<void> {
|
||||
const all = (await browser.storage.local.get()) as Record<string, unknown>;
|
||||
if (!isAutoCloudSyncEnabled(all)) {
|
||||
clearUploadDebounce();
|
||||
}
|
||||
}
|
||||
|
||||
function onStorageChanged(
|
||||
changes: Record<string, chrome.storage.StorageChange>,
|
||||
area: string,
|
||||
): void {
|
||||
if (area !== "local") return;
|
||||
|
||||
if (Object.hasOwn(changes, "autoCloudSettingsSync")) {
|
||||
void syncAutoUploadWithStorage();
|
||||
}
|
||||
|
||||
const keys = Object.keys(changes);
|
||||
if (!keys.some((k) => isKeyIncludedInCloudUploadPayload(k))) return;
|
||||
|
||||
void (async () => {
|
||||
if (await isRemoteCloudSyncDisabled()) return;
|
||||
const all = (await browser.storage.local.get()) as Record<string, unknown>;
|
||||
if (!isAutoCloudSyncEnabled(all)) return;
|
||||
if (suppressAutoUploadDuringRestore) return;
|
||||
if (!(await getAccessToken())) return;
|
||||
scheduleDebouncedUpload();
|
||||
})();
|
||||
}
|
||||
|
||||
export async function withSuppressedCloudAutoUpload<T>(
|
||||
operation: () => T | Promise<T>,
|
||||
): Promise<T> {
|
||||
suppressAutoUploadDuringRestore = true;
|
||||
try {
|
||||
return await operation();
|
||||
} finally {
|
||||
suppressAutoUploadDuringRestore = false;
|
||||
}
|
||||
}
|
||||
|
||||
export function initCloudSettingsAutoSync(deps: { reloadSeqtaPages: () => void }): void {
|
||||
reloadSeqtaPagesFn = deps.reloadSeqtaPages;
|
||||
if (autoSyncInitialized) return;
|
||||
autoSyncInitialized = true;
|
||||
browser.storage.onChanged.addListener(onStorageChanged);
|
||||
void runCloudSettingsPoll();
|
||||
}
|
||||
@@ -0,0 +1,350 @@
|
||||
import { normalizeCustomThemeApiResponse } from "@/seqta/utils/customThemes/parseApiEnvelope";
|
||||
import { bsplusApiQueryParams } from "@/seqta/utils/bsplusClientContext";
|
||||
import { base64ToBlob } from "@/seqta/utils/base64";
|
||||
|
||||
type MessageSender = { (response?: unknown): void };
|
||||
|
||||
type UploadFilePart = {
|
||||
fieldName: string;
|
||||
filename: string;
|
||||
mimeType: string;
|
||||
dataBase64: string;
|
||||
};
|
||||
|
||||
type UploadPayload = {
|
||||
themeZip?: UploadFilePart;
|
||||
looseFiles?: UploadFilePart[];
|
||||
submissionNotes?: string;
|
||||
};
|
||||
|
||||
function buildFormDataFromPayload(payload: UploadPayload): FormData {
|
||||
const form = new FormData();
|
||||
if (payload.themeZip) {
|
||||
const part = payload.themeZip;
|
||||
form.append(part.fieldName, base64ToBlob(part.dataBase64, part.mimeType), part.filename);
|
||||
}
|
||||
for (const part of payload.looseFiles ?? []) {
|
||||
form.append(part.fieldName, base64ToBlob(part.dataBase64, part.mimeType), part.filename);
|
||||
}
|
||||
if (payload.submissionNotes?.trim()) {
|
||||
form.append("submission_notes", payload.submissionNotes.trim());
|
||||
}
|
||||
return form;
|
||||
}
|
||||
|
||||
export function createCustomThemesHandlers(deps: {
|
||||
apiBase: () => string;
|
||||
getAccessTokenFromStorage: () => Promise<string | null>;
|
||||
}): Record<string, (request: Record<string, unknown>, sendResponse: MessageSender) => boolean> {
|
||||
async function readCustomThemesResponse(r: Response): Promise<Record<string, unknown>> {
|
||||
const text = await r.text();
|
||||
let body: unknown;
|
||||
try {
|
||||
body = text ? JSON.parse(text) : {};
|
||||
} catch {
|
||||
body = null;
|
||||
}
|
||||
const normalized = normalizeCustomThemeApiResponse(body, r.status, text);
|
||||
if (!r.ok || normalized.success === false) {
|
||||
console.error("[BetterSEQTA+ CustomThemes]", r.status, r.url, normalized);
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
async function customThemesJsonFetch(
|
||||
path: string,
|
||||
init: RequestInit = {},
|
||||
requireAuth = false,
|
||||
): Promise<Record<string, unknown>> {
|
||||
const headers: Record<string, string> = {
|
||||
Accept: "application/json",
|
||||
...(init.headers as Record<string, string> | undefined),
|
||||
};
|
||||
if (requireAuth) {
|
||||
const token = await deps.getAccessTokenFromStorage();
|
||||
if (!token) {
|
||||
return { success: false, error: "Not authenticated", httpStatus: 401 };
|
||||
}
|
||||
headers.Authorization = `Bearer ${token}`;
|
||||
}
|
||||
const url = `${deps.apiBase()}${path}`;
|
||||
const r = await fetch(url, {
|
||||
...init,
|
||||
headers,
|
||||
cache: "no-store",
|
||||
});
|
||||
return await readCustomThemesResponse(r);
|
||||
}
|
||||
|
||||
async function customThemesMultipartPost(
|
||||
path: string,
|
||||
payload: UploadPayload,
|
||||
): Promise<Record<string, unknown>> {
|
||||
const token = await deps.getAccessTokenFromStorage();
|
||||
if (!token) {
|
||||
return { success: false, error: "Not authenticated", httpStatus: 401 };
|
||||
}
|
||||
const form = buildFormDataFromPayload(payload);
|
||||
const url = `${deps.apiBase()}${path}`;
|
||||
const r = await fetch(url, {
|
||||
method: "POST",
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
body: form,
|
||||
cache: "no-store",
|
||||
});
|
||||
return await readCustomThemesResponse(r);
|
||||
}
|
||||
|
||||
function handleFetchCustomThemes(
|
||||
request: Record<string, unknown>,
|
||||
sendResponse: MessageSender,
|
||||
): boolean {
|
||||
void (async () => {
|
||||
try {
|
||||
const params = new URLSearchParams();
|
||||
params.set("type", "betterseqta");
|
||||
params.set("page", String(request.page ?? 1));
|
||||
params.set("limit", String(request.limit ?? 20));
|
||||
(await bsplusApiQueryParams()).forEach((value, key) => params.set(key, value));
|
||||
if (request.sort) params.set("sort", String(request.sort));
|
||||
const searchRaw = request.search;
|
||||
const search = typeof searchRaw === "string" ? searchRaw.trim() : "";
|
||||
const path = search
|
||||
? `/api/custom-themes/search?${params}&q=${encodeURIComponent(search)}`
|
||||
: `/api/custom-themes?${params}`;
|
||||
sendResponse(await customThemesJsonFetch(path));
|
||||
} catch (err) {
|
||||
console.error("[Background] fetchCustomThemes error:", err);
|
||||
sendResponse({
|
||||
success: false,
|
||||
error: err instanceof Error ? err.message : "Fetch failed",
|
||||
});
|
||||
}
|
||||
})();
|
||||
return true;
|
||||
}
|
||||
|
||||
function handleFetchMyCustomThemes(
|
||||
request: Record<string, unknown>,
|
||||
sendResponse: MessageSender,
|
||||
): boolean {
|
||||
void (async () => {
|
||||
try {
|
||||
const params = new URLSearchParams();
|
||||
params.set("page", String(request.page ?? 1));
|
||||
params.set("limit", String(request.limit ?? 20));
|
||||
params.set("type", "betterseqta");
|
||||
(await bsplusApiQueryParams()).forEach((value, key) => params.set(key, value));
|
||||
if (request.status) params.set("status", String(request.status));
|
||||
sendResponse(await customThemesJsonFetch(`/api/custom-themes/mine?${params}`, {}, true));
|
||||
} catch (err) {
|
||||
console.error("[Background] fetchMyCustomThemes error:", err);
|
||||
sendResponse({
|
||||
success: false,
|
||||
error: err instanceof Error ? err.message : "Fetch failed",
|
||||
});
|
||||
}
|
||||
})();
|
||||
return true;
|
||||
}
|
||||
|
||||
function handleFetchMyCustomThemeDetail(
|
||||
request: Record<string, unknown>,
|
||||
sendResponse: MessageSender,
|
||||
): boolean {
|
||||
const { themeId } = request;
|
||||
if (!themeId || typeof themeId !== "string") {
|
||||
sendResponse({ success: false, error: "Missing themeId" });
|
||||
return false;
|
||||
}
|
||||
void (async () => {
|
||||
try {
|
||||
sendResponse(
|
||||
await customThemesJsonFetch(
|
||||
`/api/custom-themes/mine/${encodeURIComponent(themeId)}`,
|
||||
{},
|
||||
true,
|
||||
),
|
||||
);
|
||||
} catch (err) {
|
||||
console.error("[Background] fetchMyCustomThemeDetail error:", err);
|
||||
sendResponse({
|
||||
success: false,
|
||||
error: err instanceof Error ? err.message : "Fetch failed",
|
||||
});
|
||||
}
|
||||
})();
|
||||
return true;
|
||||
}
|
||||
|
||||
function handleSubmitCustomTheme(
|
||||
request: Record<string, unknown>,
|
||||
sendResponse: MessageSender,
|
||||
): boolean {
|
||||
const payload = request.payload as UploadPayload | undefined;
|
||||
if (!payload?.themeZip && (!payload?.looseFiles || payload.looseFiles.length === 0)) {
|
||||
sendResponse({ success: false, error: "Missing upload files" });
|
||||
return false;
|
||||
}
|
||||
void (async () => {
|
||||
try {
|
||||
sendResponse(await customThemesMultipartPost("/api/custom-themes/mine", payload!));
|
||||
} catch (err) {
|
||||
console.error("[Background] submitCustomTheme error:", err);
|
||||
sendResponse({
|
||||
success: false,
|
||||
error: { message: err instanceof Error ? err.message : "Upload failed" },
|
||||
httpStatus: 0,
|
||||
});
|
||||
}
|
||||
})();
|
||||
return true;
|
||||
}
|
||||
|
||||
function handleReplaceCustomThemeFiles(
|
||||
request: Record<string, unknown>,
|
||||
sendResponse: MessageSender,
|
||||
): boolean {
|
||||
const { themeId, payload: payloadRaw } = request;
|
||||
if (!themeId || typeof themeId !== "string") {
|
||||
sendResponse({ success: false, error: "Missing themeId" });
|
||||
return false;
|
||||
}
|
||||
const payload =
|
||||
payloadRaw && typeof payloadRaw === "object" ? (payloadRaw as UploadPayload) : undefined;
|
||||
if (!payload?.themeZip && (!payload?.looseFiles || payload.looseFiles.length === 0)) {
|
||||
sendResponse({ success: false, error: "Missing upload files" });
|
||||
return false;
|
||||
}
|
||||
void (async () => {
|
||||
try {
|
||||
sendResponse(
|
||||
await customThemesMultipartPost(
|
||||
`/api/custom-themes/mine/${encodeURIComponent(themeId)}/files`,
|
||||
payload as UploadPayload,
|
||||
),
|
||||
);
|
||||
} catch (err) {
|
||||
console.error("[Background] replaceCustomThemeFiles error:", err);
|
||||
sendResponse({
|
||||
success: false,
|
||||
error: err instanceof Error ? err.message : "Upload failed",
|
||||
});
|
||||
}
|
||||
})();
|
||||
return true;
|
||||
}
|
||||
|
||||
function handleUpdateCustomThemeMetadata(
|
||||
request: Record<string, unknown>,
|
||||
sendResponse: MessageSender,
|
||||
): boolean {
|
||||
const { themeId, body } = request;
|
||||
if (!themeId || typeof themeId !== "string") {
|
||||
sendResponse({ success: false, error: "Missing themeId" });
|
||||
return false;
|
||||
}
|
||||
void (async () => {
|
||||
try {
|
||||
sendResponse(
|
||||
await customThemesJsonFetch(
|
||||
`/api/custom-themes/mine/${encodeURIComponent(themeId)}`,
|
||||
{
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(body ?? {}),
|
||||
},
|
||||
true,
|
||||
),
|
||||
);
|
||||
} catch (err) {
|
||||
console.error("[Background] updateCustomThemeMetadata error:", err);
|
||||
sendResponse({
|
||||
success: false,
|
||||
error: err instanceof Error ? err.message : "Update failed",
|
||||
});
|
||||
}
|
||||
})();
|
||||
return true;
|
||||
}
|
||||
|
||||
function handleDeleteCustomTheme(
|
||||
request: Record<string, unknown>,
|
||||
sendResponse: MessageSender,
|
||||
): boolean {
|
||||
const { themeId } = request;
|
||||
if (!themeId || typeof themeId !== "string") {
|
||||
sendResponse({ success: false, error: "Missing themeId" });
|
||||
return false;
|
||||
}
|
||||
void (async () => {
|
||||
try {
|
||||
sendResponse(
|
||||
await customThemesJsonFetch(
|
||||
`/api/custom-themes/mine/${encodeURIComponent(themeId)}`,
|
||||
{ method: "DELETE" },
|
||||
true,
|
||||
),
|
||||
);
|
||||
} catch (err) {
|
||||
console.error("[Background] deleteCustomTheme error:", err);
|
||||
sendResponse({
|
||||
success: false,
|
||||
error: err instanceof Error ? err.message : "Delete failed",
|
||||
});
|
||||
}
|
||||
})();
|
||||
return true;
|
||||
}
|
||||
|
||||
function handleFetchBsplusAdminMe(_request: unknown, sendResponse: MessageSender): boolean {
|
||||
void (async () => {
|
||||
try {
|
||||
sendResponse(await customThemesJsonFetch("/api/bsplus/admin/me", {}, true));
|
||||
} catch (err) {
|
||||
sendResponse({
|
||||
success: false,
|
||||
error: err instanceof Error ? err.message : "Fetch failed",
|
||||
});
|
||||
}
|
||||
})();
|
||||
return true;
|
||||
}
|
||||
|
||||
function handleFetchBsplusAdminThemes(
|
||||
request: Record<string, unknown>,
|
||||
sendResponse: MessageSender,
|
||||
): boolean {
|
||||
void (async () => {
|
||||
try {
|
||||
const params = new URLSearchParams();
|
||||
params.set("page", String(request.page ?? 1));
|
||||
params.set("limit", String(Math.min(Number(request.limit ?? 20) || 20, 100)));
|
||||
if (request.status) params.set("status", String(request.status));
|
||||
if (request.source) params.set("source", String(request.source));
|
||||
const searchRaw = request.search;
|
||||
const search = typeof searchRaw === "string" ? searchRaw.trim() : "";
|
||||
if (search) params.set("search", search);
|
||||
sendResponse(await customThemesJsonFetch(`/api/bsplus/admin/themes?${params}`, {}, true));
|
||||
} catch (err) {
|
||||
sendResponse({
|
||||
success: false,
|
||||
error: err instanceof Error ? err.message : "Fetch failed",
|
||||
});
|
||||
}
|
||||
})();
|
||||
return true;
|
||||
}
|
||||
|
||||
return {
|
||||
fetchCustomThemes: handleFetchCustomThemes,
|
||||
fetchMyCustomThemes: handleFetchMyCustomThemes,
|
||||
fetchMyCustomThemeDetail: handleFetchMyCustomThemeDetail,
|
||||
submitCustomTheme: handleSubmitCustomTheme,
|
||||
replaceCustomThemeFiles: handleReplaceCustomThemeFiles,
|
||||
updateCustomThemeMetadata: handleUpdateCustomThemeMetadata,
|
||||
deleteCustomTheme: handleDeleteCustomTheme,
|
||||
fetchBsplusAdminMe: handleFetchBsplusAdminMe,
|
||||
fetchBsplusAdminThemes: handleFetchBsplusAdminThemes,
|
||||
};
|
||||
}
|
||||
+51
-115
@@ -1,47 +1,16 @@
|
||||
import Parser from "rss-parser";
|
||||
import type { NewsFeed, NewsPayload } from "@/seqta/utils/newsFeed";
|
||||
|
||||
/**
|
||||
* Fetches news articles specifically for Australia from the NewsAPI.
|
||||
*
|
||||
* This function handles a specific case for fetching Australian news. It includes a
|
||||
* mechanism to retry the fetch operation by appending "%00" to the URL if a
|
||||
* rate limit error (`response.code == "rateLimited"`) is encountered. This is
|
||||
* likely a workaround for cache-busting or bypassing certain rate-limiting measures.
|
||||
*
|
||||
* @param {string} url The NewsAPI URL to fetch Australian news from.
|
||||
* @param {any} sendResponse A callback function (likely from a browser extension message listener)
|
||||
* to send the fetched news data back to the caller.
|
||||
* It's called with an object like `{ news: responseData }`.
|
||||
*/
|
||||
const fetchAustraliaNews = async (url: string, sendResponse: any) => {
|
||||
fetch(url)
|
||||
.then((result) => result.json())
|
||||
.then((response) => {
|
||||
if (response.code == "rateLimited") {
|
||||
fetchAustraliaNews((url += "%00"), sendResponse);
|
||||
} else {
|
||||
sendResponse({ news: response });
|
||||
}
|
||||
});
|
||||
};
|
||||
const NEWS_API_KEY = "17c0da766ba347c89d094449504e3080";
|
||||
const MAX_RATE_LIMIT_RETRIES = 3;
|
||||
const REQUEST_TIMEOUT_MS = 10_000;
|
||||
const DAY_MS = 86_400_000;
|
||||
|
||||
/**
|
||||
* A record mapping lowercase country codes (e.g., "usa", "canada") to an array
|
||||
* of RSS feed URLs for news sources in that country.
|
||||
*
|
||||
* @type {Record<string, string[]>}
|
||||
*/
|
||||
const rssFeedsByCountry: Record<string, string[]> = {
|
||||
usa: [
|
||||
"https://rss.nytimes.com/services/xml/rss/nyt/HomePage.xml",
|
||||
"https://www.huffpost.com/section/front-page/feed",
|
||||
"https://www.npr.org/rss/rss.php",
|
||||
],
|
||||
taiwan: [
|
||||
"https://news.ltn.com.tw/rss/all.xml",
|
||||
"https://www.taipeitimes.com/xml/index.rss",
|
||||
"https://international.thenewslens.com/rss",
|
||||
"https://feeds.npr.org/1001/rss.xml",
|
||||
],
|
||||
taiwan: ["https://news.ltn.com.tw/rss/all.xml", "https://www.taipeitimes.com/xml/index.rss"],
|
||||
hong_kong: [
|
||||
"https://rthk9.rthk.hk/rthk/news/rss/e_expressnews_elocal.xml",
|
||||
"https://www.scmp.com/rss/91/feed",
|
||||
@@ -50,101 +19,68 @@ const rssFeedsByCountry: Record<string, string[]> = {
|
||||
"https://critica.com.pa/rss.xml",
|
||||
"https://www.panamaamerica.com.pa/rss.xml",
|
||||
"https://noticiassin.com/feed/",
|
||||
"https://elcapitalfinanciero.com/feed/",
|
||||
],
|
||||
canada: [
|
||||
"https://www.cbc.ca/cmlink/rss-topstories",
|
||||
"https://calgaryherald.com/feed",
|
||||
"https://ottawacitizen.com/feed",
|
||||
"https://www.montrealgazette.com/feed",
|
||||
],
|
||||
singapore: [
|
||||
"https://www.straitstimes.com/news/singapore/rss.xml",
|
||||
"https://www.channelnewsasia.com/rssfeeds/8395986",
|
||||
],
|
||||
uk: [
|
||||
"http://feeds.bbci.co.uk/news/rss.xml",
|
||||
"https://www.theguardian.com/uk/rss",
|
||||
],
|
||||
uk: ["https://feeds.bbci.co.uk/news/rss.xml", "https://www.theguardian.com/uk/rss"],
|
||||
japan: [
|
||||
"https://www3.nhk.or.jp/nhkworld/en/news/feeds/",
|
||||
"https://www3.nhk.or.jp/rss/news/cat0.xml",
|
||||
"https://news.livedoor.com/topics/rss/int.xml",
|
||||
],
|
||||
netherlands: ["https://www.dutchnews.nl/feed/", "https://www.nrc.nl/rss/"],
|
||||
};
|
||||
|
||||
/**
|
||||
* Fetches news articles based on a specified source.
|
||||
*
|
||||
* The source can be:
|
||||
* 1. The string "australia": Fetches news from Australian sources via NewsAPI,
|
||||
* handled by the `fetchAustraliaNews` function.
|
||||
* 2. A lowercase country code (e.g., "usa", "canada"): Fetches news from a predefined
|
||||
* list of RSS feeds for that country, as specified in `rssFeedsByCountry`.
|
||||
* 3. A direct RSS feed URL (starting with "http"): Fetches news directly from this URL.
|
||||
*
|
||||
* The fetched articles are then sent back to the caller using the `sendResponse` callback.
|
||||
*
|
||||
* @param {string} source The news source identifier. This can be "australia", a
|
||||
* lowercase country code, or a direct RSS feed URL.
|
||||
* @param {any} sendResponse A callback function (typically from a browser extension
|
||||
* message listener, like `chrome.runtime.onMessage`)
|
||||
* used to send the fetched news data back to the caller.
|
||||
* It's called with an object like `{ news: { articles: [...] } }`.
|
||||
*/
|
||||
export async function fetchNews(source: string, sendResponse: any) {
|
||||
if (source === "australia") {
|
||||
const date = new Date();
|
||||
async function fetchAustraliaNews(): Promise<NewsPayload> {
|
||||
const from = new Date(Date.now() - 5 * DAY_MS).toISOString().slice(0, 10);
|
||||
let url = `https://newsapi.org/v2/everything?domains=abc.net.au&from=${from}&apiKey=${NEWS_API_KEY}`;
|
||||
|
||||
const from =
|
||||
date.getFullYear() +
|
||||
"-" +
|
||||
(date.getMonth() + 1) +
|
||||
"-" +
|
||||
(date.getDate() - 5);
|
||||
|
||||
const url = `https://newsapi.org/v2/everything?domains=abc.net.au&from=${from}&apiKey=17c0da766ba347c89d094449504e3080`;
|
||||
fetchAustraliaNews(url, sendResponse);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const parser = new Parser();
|
||||
let feeds: string[];
|
||||
console.log("fetchNews", source);
|
||||
|
||||
if (rssFeedsByCountry[source.toLowerCase()]) {
|
||||
// If the source is a country, fetch from predefined feeds
|
||||
feeds = rssFeedsByCountry[source.toLowerCase()];
|
||||
} else if (source.startsWith("http")) {
|
||||
// If the source is a URL, use it directly
|
||||
feeds = [source];
|
||||
} else {
|
||||
throw new Error(
|
||||
"Invalid source. Provide a country code or a valid RSS feed URL.",
|
||||
);
|
||||
}
|
||||
|
||||
const articlesPromises = feeds.map(async (feedUrl) => {
|
||||
try {
|
||||
const response = await fetch(feedUrl);
|
||||
const feedString = await response.text();
|
||||
const feed = await parser.parseString(feedString);
|
||||
|
||||
return feed.items.map((item) => ({
|
||||
title: item.title || "",
|
||||
description: item.contentSnippet || "",
|
||||
url: item.link || "",
|
||||
urlToImage: null,
|
||||
}));
|
||||
} catch (error) {
|
||||
console.error(`Failed to fetch RSS feed: ${feedUrl}`, error);
|
||||
return [];
|
||||
try {
|
||||
for (let attempt = 0; attempt <= MAX_RATE_LIMIT_RETRIES; attempt++) {
|
||||
const response = await fetch(url, { signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) });
|
||||
const data = await response.json();
|
||||
if (data.code !== "rateLimited") return { articles: data.articles ?? [] };
|
||||
url += "%00";
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("[BetterSEQTA+] Failed to fetch Australia news", error);
|
||||
}
|
||||
return { articles: [] };
|
||||
}
|
||||
|
||||
async function fetchFeed(url: string): Promise<NewsFeed> {
|
||||
const response = await fetch(url, { signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) });
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||||
return { url: response.url || url, xml: await response.text() };
|
||||
}
|
||||
|
||||
function feedsForSource(source: string): string[] | null {
|
||||
const preset = rssFeedsByCountry[source.toLowerCase()];
|
||||
if (preset) return preset;
|
||||
return /^https?:\/\//i.test(source) ? [source] : null;
|
||||
}
|
||||
|
||||
export async function fetchNews(source?: string): Promise<NewsPayload> {
|
||||
const normalizedSource = source?.trim() || "australia";
|
||||
if (normalizedSource === "australia") return fetchAustraliaNews();
|
||||
|
||||
const articlesArray = await Promise.all(articlesPromises);
|
||||
const articles = articlesArray.flat();
|
||||
const feedUrls = feedsForSource(normalizedSource);
|
||||
if (!feedUrls) {
|
||||
console.warn("[BetterSEQTA+] Invalid news source, falling back to Australia", normalizedSource);
|
||||
return fetchAustraliaNews();
|
||||
}
|
||||
|
||||
sendResponse({ news: { articles } });
|
||||
const results = await Promise.allSettled(feedUrls.map(fetchFeed));
|
||||
const feeds = results.flatMap((result, i) => {
|
||||
if (result.status === "fulfilled") return [result.value];
|
||||
console.error("[BetterSEQTA+] Failed to fetch RSS feed:", feedUrls[i], result.reason);
|
||||
return [];
|
||||
});
|
||||
return { feeds };
|
||||
}
|
||||
@@ -0,0 +1,369 @@
|
||||
import browser from "@/lib/browser";
|
||||
import { getBsplusDeviceName } from "@/seqta/utils/bsplusDeviceName";
|
||||
import { bsplusApiQueryParams, bsplusExtensionPayload } from "@/seqta/utils/bsplusClientContext";
|
||||
import { getOrCreateInstallId } from "@/seqta/utils/feedback/installId";
|
||||
import { isAllowedFetchUrl } from "@/seqta/utils/allowedFetchUrl";
|
||||
import {
|
||||
mergeGithubConfigFiles,
|
||||
normalizeRemoteConfigSnapshot,
|
||||
} from "@/seqta/utils/remoteConfig/normalize";
|
||||
import {
|
||||
BSPLUS_INSTALL_REGISTERED_AT_KEY,
|
||||
BSPLUS_REMOTE_CONFIG_ETAG_KEY,
|
||||
BSPLUS_REMOTE_CONFIG_FETCHED_AT_KEY,
|
||||
BSPLUS_REMOTE_CONFIG_LAST_HOSTNAME_KEY,
|
||||
BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY,
|
||||
BSPLUS_REMOTE_LAST_PRIMARY_OK_KEY,
|
||||
BS_STATUS_MANIFEST_URL,
|
||||
REGISTER_INTERVAL_MS,
|
||||
REMOTE_CONFIG_ALARM,
|
||||
REMOTE_CONFIG_POLL_MINUTES,
|
||||
} from "@/seqta/utils/remoteConfig/storageKeys";
|
||||
import type { RemoteConfigSnapshot } from "@/seqta/utils/remoteConfig/types";
|
||||
|
||||
type MessageSender = { (response?: unknown): void };
|
||||
|
||||
const ACCOUNTS_BASE = "https://accounts.betterseqta.org";
|
||||
|
||||
async function linkCloudInstall(token: string, installId: string): Promise<void> {
|
||||
try {
|
||||
const extension = bsplusExtensionPayload();
|
||||
const r = await fetch(`${ACCOUNTS_BASE}/api/bsplus/installs/link`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
installId,
|
||||
extensionVersion: extension.version,
|
||||
extension,
|
||||
deviceName: await getBsplusDeviceName(),
|
||||
lastSeenAt: new Date().toISOString(),
|
||||
}),
|
||||
cache: "no-store",
|
||||
});
|
||||
if (!r.ok) console.warn("[BetterSEQTA+] cloud install link failed:", r.status);
|
||||
} catch (e) {
|
||||
console.warn("[BetterSEQTA+] cloud install link failed:", e);
|
||||
}
|
||||
}
|
||||
|
||||
async function parseJson(r: Response): Promise<unknown> {
|
||||
const text = await r.text();
|
||||
try {
|
||||
return text ? JSON.parse(text) : {};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function readLastHostname(): Promise<string | undefined> {
|
||||
const stored = await browser.storage.local.get(BSPLUS_REMOTE_CONFIG_LAST_HOSTNAME_KEY);
|
||||
const hostname = stored[BSPLUS_REMOTE_CONFIG_LAST_HOSTNAME_KEY];
|
||||
return typeof hostname === "string" && hostname.length > 0 ? hostname : undefined;
|
||||
}
|
||||
|
||||
async function fetchGithubSnapshot(): Promise<RemoteConfigSnapshot | null> {
|
||||
try {
|
||||
const manifestRes = await fetch(BS_STATUS_MANIFEST_URL, { cache: "no-store" });
|
||||
if (!manifestRes.ok) return null;
|
||||
const manifest = (await parseJson(manifestRes)) as Record<string, unknown> | null;
|
||||
if (!manifest?.files || typeof manifest.files !== "object") return null;
|
||||
const base =
|
||||
BS_STATUS_MANIFEST_URL.replace(/manifest\.json$/, "") ||
|
||||
"https://raw.githubusercontent.com/BetterSEQTA/BS-Status/main/config/";
|
||||
const files: Record<string, unknown> = {};
|
||||
for (const [key, fileName] of Object.entries(manifest.files as Record<string, string>)) {
|
||||
if (typeof fileName !== "string") continue;
|
||||
const url = fileName.startsWith("http") ? fileName : `${base}${fileName}`;
|
||||
if (!isAllowedFetchUrl(url)) continue;
|
||||
const fr = await fetch(url, { cache: "no-store" });
|
||||
if (!fr.ok) continue;
|
||||
files[key] = await parseJson(fr);
|
||||
}
|
||||
return mergeGithubConfigFiles(manifest, files);
|
||||
} catch (e) {
|
||||
console.warn("[BetterSEQTA+] GitHub remote config fallback failed:", e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function registerInstall(apiBase: string, primaryOk: boolean, force = false): Promise<void> {
|
||||
if (!primaryOk) return;
|
||||
const stored = await browser.storage.local.get(BSPLUS_INSTALL_REGISTERED_AT_KEY);
|
||||
const last = Number(stored[BSPLUS_INSTALL_REGISTERED_AT_KEY] ?? 0);
|
||||
if (!force && Date.now() - last < REGISTER_INTERVAL_MS) return;
|
||||
|
||||
const installId = await getOrCreateInstallId();
|
||||
const extension = bsplusExtensionPayload();
|
||||
const { bsplus_token, bsplus_user } = await browser.storage.local.get([
|
||||
"bsplus_token",
|
||||
"bsplus_user",
|
||||
]);
|
||||
const token =
|
||||
typeof bsplus_token === "string" && bsplus_token.length > 0 ? bsplus_token : undefined;
|
||||
const userId =
|
||||
bsplus_user && typeof bsplus_user === "object" && "id" in bsplus_user
|
||||
? String((bsplus_user as { id: string }).id)
|
||||
: undefined;
|
||||
|
||||
const hostname = await readLastHostname();
|
||||
|
||||
const body = {
|
||||
installId,
|
||||
extensionVersion: extension.version,
|
||||
extension,
|
||||
userId,
|
||||
lastSeenAt: new Date().toISOString(),
|
||||
...(hostname ? { hostname } : {}),
|
||||
};
|
||||
|
||||
try {
|
||||
const headers: Record<string, string> = {
|
||||
Accept: "application/json",
|
||||
"Content-Type": "application/json",
|
||||
};
|
||||
if (token) headers.Authorization = `Bearer ${token}`;
|
||||
const r = await fetch(`${apiBase}/api/bsplus/installs/register`, {
|
||||
method: "POST",
|
||||
headers,
|
||||
body: JSON.stringify(body),
|
||||
cache: "no-store",
|
||||
});
|
||||
if (r.ok) {
|
||||
await browser.storage.local.set({
|
||||
[BSPLUS_INSTALL_REGISTERED_AT_KEY]: Date.now(),
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn("[BetterSEQTA+] install register failed:", e);
|
||||
}
|
||||
if (token) void linkCloudInstall(token, installId);
|
||||
}
|
||||
|
||||
export async function refreshRemoteConfig(apiBase: () => string): Promise<{
|
||||
snapshot: RemoteConfigSnapshot;
|
||||
fromNetwork: boolean;
|
||||
primaryOk: boolean;
|
||||
}> {
|
||||
const base = apiBase();
|
||||
const hostname = await readLastHostname();
|
||||
const params = await bsplusApiQueryParams();
|
||||
if (hostname) params.set("hostname", hostname);
|
||||
|
||||
const stored = await browser.storage.local.get([
|
||||
BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY,
|
||||
BSPLUS_REMOTE_CONFIG_ETAG_KEY,
|
||||
]);
|
||||
const etag = stored[BSPLUS_REMOTE_CONFIG_ETAG_KEY] as string | undefined;
|
||||
const prior = stored[BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY];
|
||||
|
||||
let primaryOk = false;
|
||||
let snapshot: RemoteConfigSnapshot | null = null;
|
||||
|
||||
try {
|
||||
const headers: Record<string, string> = { Accept: "application/json" };
|
||||
if (etag) headers["If-None-Match"] = etag;
|
||||
const r = await fetch(`${base}/api/bsplus/remote-config?${params}`, {
|
||||
cache: "no-store",
|
||||
headers,
|
||||
});
|
||||
if (r.status === 304 && prior) {
|
||||
primaryOk = true;
|
||||
snapshot = normalizeRemoteConfigSnapshot(prior);
|
||||
snapshot.source = "cache";
|
||||
} else if (r.ok) {
|
||||
primaryOk = true;
|
||||
const json = await parseJson(r);
|
||||
snapshot = normalizeRemoteConfigSnapshot(json);
|
||||
snapshot.source = "api";
|
||||
const newEtag = r.headers.get("ETag") ?? snapshot.etag;
|
||||
if (newEtag) snapshot.etag = newEtag;
|
||||
await browser.storage.local.set({
|
||||
[BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY]: snapshot,
|
||||
[BSPLUS_REMOTE_CONFIG_FETCHED_AT_KEY]: Date.now(),
|
||||
[BSPLUS_REMOTE_LAST_PRIMARY_OK_KEY]: true,
|
||||
...(newEtag ? { [BSPLUS_REMOTE_CONFIG_ETAG_KEY]: newEtag } : {}),
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn("[BetterSEQTA+] remote-config primary fetch failed:", e);
|
||||
}
|
||||
|
||||
if (!snapshot) {
|
||||
snapshot = await fetchGithubSnapshot();
|
||||
if (snapshot) {
|
||||
await browser.storage.local.set({
|
||||
[BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY]: snapshot,
|
||||
[BSPLUS_REMOTE_CONFIG_FETCHED_AT_KEY]: Date.now(),
|
||||
[BSPLUS_REMOTE_LAST_PRIMARY_OK_KEY]: false,
|
||||
});
|
||||
} else if (prior) {
|
||||
snapshot = normalizeRemoteConfigSnapshot(prior);
|
||||
snapshot.source = "cache";
|
||||
} else {
|
||||
snapshot = normalizeRemoteConfigSnapshot(null);
|
||||
}
|
||||
}
|
||||
|
||||
if (primaryOk) {
|
||||
await browser.storage.local.set({ [BSPLUS_REMOTE_LAST_PRIMARY_OK_KEY]: true });
|
||||
}
|
||||
|
||||
void registerInstall(base, primaryOk);
|
||||
return { snapshot, fromNetwork: primaryOk, primaryOk };
|
||||
}
|
||||
|
||||
export function initRemoteConfigBackground(apiBase: () => string): void {
|
||||
void refreshRemoteConfig(apiBase);
|
||||
|
||||
browser.alarms.create(REMOTE_CONFIG_ALARM, {
|
||||
periodInMinutes: REMOTE_CONFIG_POLL_MINUTES,
|
||||
});
|
||||
|
||||
browser.alarms.onAlarm.addListener((alarm) => {
|
||||
if (alarm.name === REMOTE_CONFIG_ALARM) void refreshRemoteConfig(apiBase);
|
||||
});
|
||||
|
||||
browser.storage.onChanged.addListener((changes, area) => {
|
||||
if (area !== "local") return;
|
||||
if (changes.bsplus_token || changes.bsplus_user) {
|
||||
void (async () => {
|
||||
const lastPrimary = await browser.storage.local.get(BSPLUS_REMOTE_LAST_PRIMARY_OK_KEY);
|
||||
const primaryOk = lastPrimary[BSPLUS_REMOTE_LAST_PRIMARY_OK_KEY] === true;
|
||||
if (primaryOk) {
|
||||
await registerInstall(apiBase(), true, true);
|
||||
} else {
|
||||
const res = await refreshRemoteConfig(apiBase);
|
||||
if (res.primaryOk) await registerInstall(apiBase(), true, true);
|
||||
else {
|
||||
const { bsplus_token } = await browser.storage.local.get("bsplus_token");
|
||||
if (typeof bsplus_token === "string" && bsplus_token) {
|
||||
void linkCloudInstall(bsplus_token, await getOrCreateInstallId());
|
||||
}
|
||||
}
|
||||
}
|
||||
})();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export function createRemoteConfigHandlers(
|
||||
apiBase: () => string,
|
||||
): Record<string, (request: unknown, sendResponse: MessageSender) => boolean> {
|
||||
function handleRefresh(_req: unknown, sendResponse: MessageSender): boolean {
|
||||
void refreshRemoteConfig(apiBase)
|
||||
.then((res) => sendResponse(res))
|
||||
.catch((err) =>
|
||||
sendResponse({
|
||||
error: err instanceof Error ? err.message : "Refresh failed",
|
||||
}),
|
||||
);
|
||||
return true;
|
||||
}
|
||||
|
||||
function handleGetSnapshot(_req: unknown, sendResponse: MessageSender): boolean {
|
||||
void browser.storage.local.get(BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY).then((stored) => {
|
||||
sendResponse({
|
||||
snapshot: normalizeRemoteConfigSnapshot(stored[BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY]),
|
||||
});
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
function handleSetPageContext(req: unknown, sendResponse: MessageSender): boolean {
|
||||
const { hostname: rawHostname } = req as { hostname?: unknown };
|
||||
const hostname = typeof rawHostname === "string" ? rawHostname.trim() : "";
|
||||
if (hostname) {
|
||||
void browser.storage.local
|
||||
.set({ [BSPLUS_REMOTE_CONFIG_LAST_HOSTNAME_KEY]: hostname })
|
||||
.then(() => sendResponse({ ok: true }));
|
||||
} else {
|
||||
sendResponse({ ok: false });
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function handleFetchRemoteThemePackage(req: unknown, sendResponse: MessageSender): boolean {
|
||||
const { packageId: rawPackageId } = req as { packageId?: unknown };
|
||||
const packageId = typeof rawPackageId === "string" ? rawPackageId.trim() : "";
|
||||
if (!packageId) {
|
||||
sendResponse({ error: "Missing packageId" });
|
||||
return false;
|
||||
}
|
||||
void (async () => {
|
||||
try {
|
||||
const hostname = await readLastHostname();
|
||||
const params = await bsplusApiQueryParams();
|
||||
if (hostname) params.set("hostname", hostname);
|
||||
const base = apiBase();
|
||||
const url = `${base}/api/bsplus/remote-theme-packages/${encodeURIComponent(packageId)}?${params}`;
|
||||
if (!isAllowedFetchUrl(url)) {
|
||||
sendResponse({ error: "URL not allowed" });
|
||||
return;
|
||||
}
|
||||
const r = await fetch(url, { cache: "no-store", headers: { Accept: "application/json" } });
|
||||
if (!r.ok) {
|
||||
sendResponse({ error: `HTTP ${r.status}` });
|
||||
return;
|
||||
}
|
||||
const json = await parseJson(r);
|
||||
if (!json || typeof json !== "object") {
|
||||
sendResponse({ error: "Invalid package response" });
|
||||
return;
|
||||
}
|
||||
sendResponse({ package: json });
|
||||
} catch (e) {
|
||||
sendResponse({
|
||||
error: e instanceof Error ? e.message : "Fetch failed",
|
||||
});
|
||||
}
|
||||
})();
|
||||
return true;
|
||||
}
|
||||
|
||||
function handleFetchRemoteThemePackageUrl(req: unknown, sendResponse: MessageSender): boolean {
|
||||
const { url: rawUrl } = req as { url?: unknown };
|
||||
const url = typeof rawUrl === "string" ? rawUrl.trim() : "";
|
||||
if (!url || !isAllowedFetchUrl(url)) {
|
||||
sendResponse({ error: "URL not allowed" });
|
||||
return false;
|
||||
}
|
||||
void (async () => {
|
||||
try {
|
||||
const r = await fetch(url, { cache: "no-store" });
|
||||
if (!r.ok) {
|
||||
sendResponse({ error: `HTTP ${r.status}` });
|
||||
return;
|
||||
}
|
||||
const theme = await parseJson(r);
|
||||
if (!theme || typeof theme !== "object") {
|
||||
sendResponse({ error: "Invalid theme JSON" });
|
||||
return;
|
||||
}
|
||||
sendResponse({ theme });
|
||||
} catch (e) {
|
||||
sendResponse({
|
||||
error: e instanceof Error ? e.message : "Fetch failed",
|
||||
});
|
||||
}
|
||||
})();
|
||||
return true;
|
||||
}
|
||||
|
||||
return {
|
||||
refreshRemoteConfig: handleRefresh,
|
||||
getRemoteConfigSnapshot: handleGetSnapshot,
|
||||
setRemoteConfigPageContext: handleSetPageContext,
|
||||
fetchRemoteThemePackage: handleFetchRemoteThemePackage,
|
||||
fetchRemoteThemePackageUrl: handleFetchRemoteThemePackageUrl,
|
||||
};
|
||||
}
|
||||
|
||||
export async function isRemoteCloudSyncDisabled(): Promise<boolean> {
|
||||
const stored = await browser.storage.local.get(BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY);
|
||||
const snap = normalizeRemoteConfigSnapshot(stored[BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY]);
|
||||
return snap.global.disableCloudSync === true;
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
type MessageSender = { (response?: unknown): void };
|
||||
|
||||
type StockPhotoResult = { title: string; thumbUrl: string; imageUrl: string };
|
||||
|
||||
export function handleSearchThemeStockPhotos(
|
||||
request: { query?: string; limit?: number },
|
||||
sendResponse: MessageSender,
|
||||
): boolean {
|
||||
const query = request.query?.trim();
|
||||
if (!query) {
|
||||
sendResponse({ success: false, error: "Missing query" });
|
||||
return false;
|
||||
}
|
||||
const limit = Math.min(Math.max(request.limit ?? 8, 1), 12);
|
||||
|
||||
void (async () => {
|
||||
try {
|
||||
const params = new URLSearchParams({
|
||||
action: "query",
|
||||
origin: "*",
|
||||
format: "json",
|
||||
generator: "search",
|
||||
gsrsearch: query,
|
||||
gsrnamespace: "6",
|
||||
gsrlimit: String(limit),
|
||||
prop: "imageinfo",
|
||||
iiprop: "url",
|
||||
iiurlwidth: "1400",
|
||||
});
|
||||
const res = await fetch(`https://commons.wikimedia.org/w/api.php?${params}`);
|
||||
const json = (await res.json()) as {
|
||||
query?: {
|
||||
pages?: Record<
|
||||
string,
|
||||
{ title?: string; imageinfo?: { thumburl?: string; url?: string }[] }
|
||||
>;
|
||||
};
|
||||
};
|
||||
const pages = json.query?.pages ?? {};
|
||||
const results: StockPhotoResult[] = Object.values(pages)
|
||||
.map((page) => {
|
||||
const info = page.imageinfo?.[0];
|
||||
if (!info?.url) return null;
|
||||
return {
|
||||
title: page.title?.replace(/^File:/, "") ?? "Photo",
|
||||
thumbUrl: info.thumburl ?? info.url,
|
||||
imageUrl: info.url,
|
||||
};
|
||||
})
|
||||
.filter((row): row is StockPhotoResult => row != null);
|
||||
|
||||
sendResponse({ success: true, results });
|
||||
} catch (err) {
|
||||
sendResponse({
|
||||
success: false,
|
||||
error: err instanceof Error ? err.message : "Search failed",
|
||||
});
|
||||
}
|
||||
})();
|
||||
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import semver from "semver";
|
||||
import browser from "@/lib/browser";
|
||||
|
||||
function crossedUpgrade(previousVersion: string, boundary: string): boolean {
|
||||
const prev = semver.coerce(previousVersion);
|
||||
const curr = semver.coerce(browser.runtime.getManifest().version);
|
||||
return prev != null && curr != null && !semver.lt(curr, boundary) && semver.lt(prev, boundary);
|
||||
}
|
||||
|
||||
/** One-time storage patches when crossing 3.6.5 / 3.6.6 / 3.7.0 (see git history on main). */
|
||||
export async function runStorageMigrations(previousVersion: string): Promise<void> {
|
||||
if (crossedUpgrade(previousVersion, "3.6.5")) {
|
||||
try {
|
||||
const key = "plugin.global-search.settings";
|
||||
const got = await browser.storage.local.get(key);
|
||||
const existing = (got[key] ?? {}) as Record<string, unknown>;
|
||||
await browser.storage.local.set({
|
||||
[key]: {
|
||||
...existing,
|
||||
enabled: true,
|
||||
transparencyEffects: true,
|
||||
runIndexingOnLoad: true,
|
||||
passiveIndexing: true,
|
||||
},
|
||||
});
|
||||
} catch (e) {
|
||||
console.warn("[BetterSEQTA+] Global Search 3.6.5 settings migration failed:", e);
|
||||
}
|
||||
}
|
||||
|
||||
if (crossedUpgrade(previousVersion, "3.6.6")) {
|
||||
try {
|
||||
await browser.storage.local.set({
|
||||
themeOfTheMonthDisabled: false,
|
||||
themeOfTheMonthLastSeenId: undefined,
|
||||
});
|
||||
} catch (e) {
|
||||
console.warn("[BetterSEQTA+] Theme of the Month 3.6.6 reset migration failed:", e);
|
||||
}
|
||||
}
|
||||
|
||||
if (crossedUpgrade(previousVersion, "3.7.0")) {
|
||||
try {
|
||||
await browser.storage.local.set({
|
||||
themeOfTheMonthLastSeenId: undefined,
|
||||
themeOfTheMonthDismissedMonth: undefined,
|
||||
});
|
||||
} catch (e) {
|
||||
console.warn("[BetterSEQTA+] Theme of the Month 3.7.0 dismissal migration failed:", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import browser from "@/lib/browser";
|
||||
|
||||
import { hasAnySyncOptInScope } from "@/plugins/built-in/timetableClassmates/syncScopes";
|
||||
import { isSeqtaTab } from "@/seqta/utils/seqtaTabMatch";
|
||||
|
||||
const ALARM_NAME = "timetable-classmates-sync";
|
||||
const ALARM_PERIOD_MINUTES = 8 * 60;
|
||||
|
||||
let initialized = false;
|
||||
|
||||
async function pingSeqtaTabs(): Promise<void> {
|
||||
const tabs = await browser.tabs.query({});
|
||||
for (const tab of tabs) {
|
||||
if (!isSeqtaTab(tab) || tab.id == null) continue;
|
||||
try {
|
||||
await browser.tabs.sendMessage(tab.id, { type: "timetableClassmatesSync" });
|
||||
} catch {
|
||||
/* content script not ready */
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function pingIfOptedIn(): Promise<void> {
|
||||
if (!(await hasAnySyncOptInScope())) return;
|
||||
await pingSeqtaTabs();
|
||||
}
|
||||
|
||||
export function initTimetableClassmatesBackgroundSync(): void {
|
||||
if (initialized) return;
|
||||
initialized = true;
|
||||
|
||||
void browser.alarms.create(ALARM_NAME, { periodInMinutes: ALARM_PERIOD_MINUTES });
|
||||
browser.alarms.onAlarm.addListener((alarm) => {
|
||||
if (alarm.name === ALARM_NAME) void pingIfOptedIn();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
/** Google Calendar OAuth — public client config. Token exchange is on accounts.betterseqta.org. */
|
||||
|
||||
const HARDCODED_GOOGLE_OAUTH_CLIENT_ID =
|
||||
"270834969641-f6t7jtpu6j0cemse8updj3rkos7nl0hf.apps.googleusercontent.com";
|
||||
|
||||
const envClientId =
|
||||
typeof __GOOGLE_OAUTH_CLIENT_ID__ !== "undefined" ? __GOOGLE_OAUTH_CLIENT_ID__ : "";
|
||||
|
||||
export const GOOGLE_OAUTH_CLIENT_ID: string =
|
||||
envClientId.trim() || HARDCODED_GOOGLE_OAUTH_CLIENT_ID.trim();
|
||||
|
||||
export const ACCOUNTS_BASE = "https://accounts.betterseqta.org";
|
||||
|
||||
export const GOOGLE_CALENDAR_OAUTH_CALLBACK = `${ACCOUNTS_BASE}/auth/google/calendar/callback`;
|
||||
export const GOOGLE_CALENDAR_TOKEN_URL = `${ACCOUNTS_BASE}/api/bsplus/google/calendar/token`;
|
||||
export const GOOGLE_CALENDAR_REFRESH_URL = `${ACCOUNTS_BASE}/api/bsplus/google/calendar/refresh`;
|
||||
|
||||
/** App-owned secondary calendar only — cannot read or modify the user's other calendars. */
|
||||
export const GOOGLE_CALENDAR_SCOPE = "https://www.googleapis.com/auth/calendar.app.created";
|
||||
|
||||
export const GOOGLE_AUTH_URL = "https://accounts.google.com/o/oauth2/v2/auth";
|
||||
export const GOOGLE_CALENDAR_API = "https://www.googleapis.com/calendar/v3";
|
||||
|
||||
export const BSPLUS_GOOGLE_CALENDAR_NAME = "BetterSEQTA+ Timetable";
|
||||
export const BSPLUS_GOOGLE_CALENDAR_DESCRIPTION =
|
||||
"School timetable lessons synced by the BetterSEQTA+ extension.";
|
||||
|
||||
export const BSPLUS_GOOGLE_CALENDAR_EVENT_PROP = "bsplusSeqtaKey";
|
||||
|
||||
export const GOOGLE_CALENDAR_SYNC_WEEKS = 12;
|
||||
export const GOOGLE_CALENDAR_SYNC_WEEKS_MIN = 1;
|
||||
export const GOOGLE_CALENDAR_SYNC_WEEKS_MAX = 52;
|
||||
|
||||
export function isGoogleCalendarConfigured(): boolean {
|
||||
return GOOGLE_OAUTH_CLIENT_ID.length > 0;
|
||||
}
|
||||
|
||||
export const GOOGLE_CALENDAR_ACCOUNTS_NOT_READY_HINT =
|
||||
"Google Calendar connect requires accounts.betterseqta.org — see docs/GOOGLE_CALENDAR_ACCOUNTS_CALLBACK.md";
|
||||
|
||||
export function googleOAuthRedirectUriHint(): string {
|
||||
return `Authorized redirect URI in Google Cloud Console must be: ${GOOGLE_CALENDAR_OAUTH_CALLBACK}`;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
/** Outlook Calendar OAuth — public client config. Token exchange is on accounts.betterseqta.org. */
|
||||
|
||||
import { ACCOUNTS_BASE } from "@/config/googleCalendar";
|
||||
|
||||
const HARDCODED_OUTLOOK_OAUTH_CLIENT_ID = "0b55168c-916c-4323-8f67-b3dd30af3c9e";
|
||||
|
||||
const envClientId =
|
||||
typeof __OUTLOOK_OAUTH_CLIENT_ID__ !== "undefined" ? __OUTLOOK_OAUTH_CLIENT_ID__ : "";
|
||||
|
||||
export const OUTLOOK_OAUTH_CLIENT_ID: string =
|
||||
envClientId.trim() || HARDCODED_OUTLOOK_OAUTH_CLIENT_ID.trim();
|
||||
|
||||
export const OUTLOOK_CALENDAR_OAUTH_CALLBACK = `${ACCOUNTS_BASE}/auth/microsoft/calendar/callback`;
|
||||
export const OUTLOOK_CALENDAR_TOKEN_URL = `${ACCOUNTS_BASE}/api/bsplus/microsoft/calendar/token`;
|
||||
export const OUTLOOK_CALENDAR_REFRESH_URL = `${ACCOUNTS_BASE}/api/bsplus/microsoft/calendar/refresh`;
|
||||
|
||||
export const OUTLOOK_CALENDAR_SCOPE = "offline_access Calendars.ReadWrite User.Read";
|
||||
|
||||
export const OUTLOOK_AUTH_URL = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize";
|
||||
|
||||
export const OUTLOOK_GRAPH_API = "https://graph.microsoft.com/v1.0";
|
||||
|
||||
export const BSPLUS_OUTLOOK_CALENDAR_EVENT_CATEGORY = "BetterSEQTA+";
|
||||
|
||||
export function isOutlookCalendarConfigured(): boolean {
|
||||
return OUTLOOK_OAUTH_CLIENT_ID.length > 0;
|
||||
}
|
||||
|
||||
export const OUTLOOK_CALENDAR_ACCOUNTS_NOT_READY_HINT =
|
||||
"Outlook Calendar connect requires accounts.betterseqta.org — see docs/OUTLOOK_CALENDAR_ACCOUNTS_CALLBACK.md";
|
||||
|
||||
export function outlookOAuthRedirectUriHint(): string {
|
||||
return `Authorized redirect URI in Azure must be: ${OUTLOOK_CALENDAR_OAUTH_CALLBACK}`;
|
||||
}
|
||||
@@ -17,10 +17,43 @@
|
||||
|
||||
@use "injected/popup.scss";
|
||||
|
||||
@font-face {
|
||||
font-family: "Roboto";
|
||||
src: url("https://fonts.gstatic.com/s/roboto/v50/KFO7CnqEu92Fr1ME7kSn66aGLdTylUAMa3yUBA.woff2")
|
||||
format("woff2");
|
||||
font-weight: 700;
|
||||
font-style: normal;
|
||||
font-display: swap;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "IconFamily";
|
||||
src: url("@/resources/fonts/IconFamily.woff") format("woff");
|
||||
font-weight: normal;
|
||||
font-style: normal;
|
||||
font-display: block;
|
||||
}
|
||||
|
||||
@layer base, override;
|
||||
|
||||
@layer override {
|
||||
.legacy-root,
|
||||
.legacy-root *:not(.iconFamily) {
|
||||
font-family: var(--betterseqta-font-family, Rubik), sans-serif !important;
|
||||
}
|
||||
|
||||
.iconFamily,
|
||||
.iconFamily *,
|
||||
[class~="iconFamily"],
|
||||
[class~="iconFamily"] * {
|
||||
font-family: "IconFamily" !important;
|
||||
}
|
||||
}
|
||||
|
||||
html {
|
||||
background: #161616 !important;
|
||||
background-color: #161616;
|
||||
font-family: Rubik, Roboto !important;
|
||||
font-family: Roboto, system-ui, -apple-system, sans-serif !important;
|
||||
}
|
||||
|
||||
.tooltip svg {
|
||||
@@ -77,9 +110,7 @@ html {
|
||||
transform-origin: top;
|
||||
transition: transform 0.2s;
|
||||
}
|
||||
body:has(.outside-container:not(.hide))
|
||||
#AddedSettings.tooltip:hover
|
||||
> .tooltiptext {
|
||||
body:has(.outside-container:not(.hide)) #AddedSettings.tooltip:hover > .tooltiptext {
|
||||
transform: scale(0);
|
||||
}
|
||||
.assessmenttooltip svg {
|
||||
|
||||
+1
-2
@@ -116,8 +116,7 @@ body {
|
||||
}
|
||||
|
||||
.cke_panel_listItem > a {
|
||||
|
||||
&:hover {
|
||||
background: #3d3d3e !important;
|
||||
}
|
||||
}
|
||||
}
|
||||
+2414
-522
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,51 @@
|
||||
html.performanceMode {
|
||||
--bs-settings-ease: 0.2s cubic-bezier(0.22, 1, 0.36, 1);
|
||||
--bs-motion-duration: 0.2s;
|
||||
--bs-motion-ease: cubic-bezier(0.22, 1, 0.36, 1);
|
||||
|
||||
backdrop-filter: none !important;
|
||||
-webkit-backdrop-filter: none !important;
|
||||
filter: none !important;
|
||||
|
||||
/* Inline page loaders only — boot overlay lives in #loading shadow DOM. */
|
||||
.bkloading-inline .big-circle,
|
||||
.bkloading-inline .small-circle,
|
||||
.bkloading-inline .outer-circle {
|
||||
animation: none !important;
|
||||
}
|
||||
|
||||
/* Custom title: cheaper hit-testing during mouse moves (trace showed many HitTests). */
|
||||
.bsplus-custom-title,
|
||||
#title.bsplus-custom-title {
|
||||
contain: layout style paint;
|
||||
}
|
||||
|
||||
/* Settings backdrop — skip expensive blur in performance mode. */
|
||||
#ExtensionPopup ~ *,
|
||||
.outside-container.hide {
|
||||
backdrop-filter: none !important;
|
||||
}
|
||||
}
|
||||
|
||||
html.performanceModeSimpleUi {
|
||||
.bsplus-analytics-charts,
|
||||
.bsplus-analytics-chart-cell {
|
||||
display: none !important;
|
||||
}
|
||||
}
|
||||
|
||||
/* Boot loading spinner uses shadow DOM; custom properties inherit from the host. */
|
||||
#loading.bkloading {
|
||||
--bk-stage-duration: 0.85s !important;
|
||||
--bk-spin-outer: 1s !important;
|
||||
--bk-spin-inner: 3s !important;
|
||||
--bk-spin-small: 3s !important;
|
||||
}
|
||||
|
||||
html.performanceMode.transparencyEffects,
|
||||
html.performanceMode .backdrop-blur-xl,
|
||||
html.performanceMode .backdrop-blur-sm,
|
||||
html.performanceMode [class*="backdrop-blur"] {
|
||||
backdrop-filter: none !important;
|
||||
-webkit-backdrop-filter: none !important;
|
||||
}
|
||||
+25
-13
@@ -14,11 +14,12 @@
|
||||
.outside-container {
|
||||
margin: 0;
|
||||
overflow: hidden;
|
||||
position: absolute;
|
||||
right: 10px;
|
||||
top: 80px;
|
||||
height: 590px;
|
||||
z-index: 20;
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
/* Above Engage React chrome / MUI layers; below rare fullscreen media overlays */
|
||||
z-index: 200000;
|
||||
transition-duration: 100ms;
|
||||
}
|
||||
|
||||
@@ -31,12 +32,23 @@
|
||||
}
|
||||
|
||||
#ExtensionPopup {
|
||||
border-radius: 1rem;
|
||||
filter: drop-shadow(0px 0px 20px rgba(0, 0, 0, 0.6));
|
||||
transform-origin: 70% 0;
|
||||
will-change: opacity, transform;
|
||||
transform: translateZ(0); // promotes GPU rendering
|
||||
transition:
|
||||
opacity 0.05s,
|
||||
transform 0.05s;
|
||||
border-radius: 0;
|
||||
filter: none;
|
||||
transform-origin: center center;
|
||||
opacity: 0;
|
||||
transition: opacity var(--bs-motion-duration, 0.2s) cubic-bezier(0.22, 1, 0.36, 1);
|
||||
}
|
||||
|
||||
#ExtensionPopup.bsplus-settings-host--open {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
#ExtensionPopup.bsplus-settings-host--closing {
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
/* Feedback modal scrollport — host overflow:hidden otherwise clips fixed overlays. */
|
||||
#ExtensionPopup.bsplus-feedback-open {
|
||||
overflow: auto !important;
|
||||
}
|
||||
@@ -1,22 +1,68 @@
|
||||
#menu ul:has(li.hasChildren.active) li.hasChildren.active {
|
||||
#menu
|
||||
ul:has(li.hasChildren:is(.active, .bsplus-active))
|
||||
li.hasChildren:is(.active, .bsplus-active) {
|
||||
box-shadow: inset 0px 0 var(--item-colour, transparent) !important;
|
||||
background: transparent !important;
|
||||
}
|
||||
|
||||
#menu ul:not(:has(li.hasChildren.active)) {
|
||||
#menu ul:not(:has(> li.hasChildren:is(.active, .bsplus-active))) {
|
||||
overflow-y: scroll !important;
|
||||
}
|
||||
|
||||
#menu > ul:has(li.hasChildren.active) > li::before,
|
||||
#menu > ul ul:has(li.hasChildren.active) > li::before,
|
||||
#menu > ul:has(li.hasChildren.active) > li > label,
|
||||
#menu > ul:has(li.hasChildren.active) > li > svg,
|
||||
#menu > ul ul:has(li.hasChildren.active) > li > label,
|
||||
#menu > ul ul:has(li.hasChildren.active) > li > svg {
|
||||
transform: translateX(-320px);
|
||||
/* Move the complete row, including hover fill, arrow and subject stripe.
|
||||
A transform on the folder itself would also move its absolute `.sub` panel.
|
||||
Resting margins are measured before drilling so auto margins interpolate. */
|
||||
#menu#menu ul.bsplus-drill-rows > :is(li, section) {
|
||||
margin-left: var(--bsplus-row-margin-left) !important;
|
||||
transition:
|
||||
margin-left 0.3s ease,
|
||||
background-color 0.2s ease,
|
||||
box-shadow 0.2s ease !important;
|
||||
animation: none !important;
|
||||
|
||||
> label,
|
||||
> svg,
|
||||
&::before,
|
||||
&::after {
|
||||
transform: none !important;
|
||||
animation: none !important;
|
||||
}
|
||||
}
|
||||
|
||||
#menu li.hasChildren:not(.active) li .sub {
|
||||
#menu#menu ul.bsplus-drill-rows:has(> .hasChildren:is(.active, .bsplus-active)) > :is(li, section) {
|
||||
margin-left: calc(var(--bsplus-row-margin-left) + var(--bsplus-slide-off, -320px)) !important;
|
||||
}
|
||||
|
||||
/* Incoming rows travel only with their native panel. */
|
||||
#menu .sub > ul:not(.bsplus-drill-rows) > li {
|
||||
&,
|
||||
> label,
|
||||
> svg,
|
||||
&::before,
|
||||
&::after {
|
||||
animation: none !important;
|
||||
transform: none !important;
|
||||
}
|
||||
}
|
||||
|
||||
#menu .sub {
|
||||
transition:
|
||||
transform 0.3s ease,
|
||||
left 0.4s cubic-bezier(0.4, 0, 0.2, 1);
|
||||
}
|
||||
|
||||
#menu
|
||||
.sub
|
||||
ul:has(> li.hasChildren:is(.active, .bsplus-active))
|
||||
> li:not(:is(.active, .bsplus-active)) {
|
||||
pointer-events: none !important;
|
||||
}
|
||||
|
||||
#menu > ul:has(li.hasChildren:is(.active, .bsplus-active)) > li:is(.active, .bsplus-active) {
|
||||
background: transparent !important;
|
||||
}
|
||||
|
||||
#menu li.hasChildren:not(:is(.active, .bsplus-active)) li .sub {
|
||||
display: none; // improves performance
|
||||
}
|
||||
|
||||
@@ -25,19 +71,10 @@
|
||||
padding-top: 2px;
|
||||
}
|
||||
|
||||
.sub:has(ul > li.hasChildren.active) > .nav > .back {
|
||||
.sub:has(ul > li.hasChildren:is(.active, .bsplus-active)) > .nav > .back {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
#menu ul > li > label,
|
||||
#menu ul > li > svg {
|
||||
transition: transform 0.3s ease;
|
||||
}
|
||||
|
||||
#menu .sub {
|
||||
transition: transform 0.3s ease;
|
||||
}
|
||||
|
||||
#menu > ul:has(li.hasChildren.active) > li.active {
|
||||
background: transparent !important;
|
||||
#menu {
|
||||
--bsplus-slide-off: -320px;
|
||||
}
|
||||
@@ -0,0 +1,263 @@
|
||||
/* Native sidebar style presets + Look (density / radius / indicator). */
|
||||
|
||||
$sidebar-motion: 0.4s cubic-bezier(0.4, 0, 0.2, 1);
|
||||
|
||||
@mixin accent-bar($shadow: 0.55) {
|
||||
content: "" !important;
|
||||
position: absolute !important;
|
||||
left: 0 !important;
|
||||
top: 10px !important;
|
||||
bottom: 10px !important;
|
||||
width: 4px !important;
|
||||
border-radius: 2px !important;
|
||||
background: #fff !important;
|
||||
box-shadow: 0 0 10px rgba(255, 255, 255, $shadow) !important;
|
||||
pointer-events: none !important;
|
||||
z-index: 3 !important;
|
||||
opacity: 1 !important;
|
||||
display: block !important;
|
||||
}
|
||||
|
||||
#menu.bsplus-styled-sidebar {
|
||||
$rootItem: "> ul > li.item";
|
||||
$subItem: ".sub li.item";
|
||||
$item: "#{$rootItem}, #{$subItem}";
|
||||
$rootLabel: "> ul > li.item > label:not(.toggle)";
|
||||
$subLabel: ".sub li.item > label:not(.toggle)";
|
||||
$label: "#{$rootLabel}, #{$subLabel}";
|
||||
$active: "> ul > li.item.active:not(.hasChildren), .sub li.item.active:not(.hasChildren)";
|
||||
|
||||
/* Look: base radius — layout transitions only on root rows (settings tweaks).
|
||||
Submenu rows must not animate margin/padding during folder drill slides. */
|
||||
#{$rootItem} {
|
||||
border-radius: var(--bsplus-sidebar-radius, 12px) !important;
|
||||
transition:
|
||||
padding $sidebar-motion,
|
||||
margin $sidebar-motion,
|
||||
border-radius $sidebar-motion,
|
||||
background-color 0.2s ease,
|
||||
box-shadow 0.2s ease;
|
||||
}
|
||||
|
||||
#{$subItem} {
|
||||
border-radius: var(--bsplus-sidebar-radius, 12px) !important;
|
||||
transition:
|
||||
background-color 0.2s ease,
|
||||
box-shadow 0.2s ease;
|
||||
}
|
||||
|
||||
#{$rootLabel} {
|
||||
min-height: 28px !important;
|
||||
transition:
|
||||
font-size $sidebar-motion,
|
||||
line-height $sidebar-motion,
|
||||
padding $sidebar-motion,
|
||||
margin $sidebar-motion;
|
||||
|
||||
> svg {
|
||||
transition:
|
||||
width $sidebar-motion,
|
||||
height $sidebar-motion,
|
||||
margin $sidebar-motion;
|
||||
}
|
||||
}
|
||||
|
||||
#{$subLabel} {
|
||||
min-height: 28px !important;
|
||||
transition: none;
|
||||
}
|
||||
|
||||
/* —— Style presets —— */
|
||||
&.bsplus-sidebar-style-soft {
|
||||
#{$item} {
|
||||
margin: 0 8px 10px !important;
|
||||
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.12);
|
||||
}
|
||||
#{$active} {
|
||||
box-shadow: 0 6px 18px rgba(0, 0, 0, 0.22);
|
||||
background: rgba(0, 0, 0, 0.38) !important;
|
||||
}
|
||||
}
|
||||
|
||||
&.bsplus-sidebar-style-pill {
|
||||
#{$item} {
|
||||
margin: 0 10px 8px !important;
|
||||
border-radius: 999px !important;
|
||||
}
|
||||
#{$active} {
|
||||
background: rgba(0, 0, 0, 0.4) !important;
|
||||
}
|
||||
}
|
||||
|
||||
&.bsplus-sidebar-style-glass {
|
||||
/* Never put backdrop-filter on a folder — it becomes a clip
|
||||
containing-block and hides `.sub` labels on Chromium/Edge. Lean rows
|
||||
blur; closed folders keep the translated glass surface without blur;
|
||||
open folders drop the fill entirely so `.sub` stays clip-safe. */
|
||||
#{$item} {
|
||||
&:not(:has(> .sub)) {
|
||||
margin: 4px 8px 4px !important;
|
||||
background: rgba(255, 255, 255, 0.1) !important;
|
||||
backdrop-filter: blur(10px);
|
||||
-webkit-backdrop-filter: blur(10px);
|
||||
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.14);
|
||||
}
|
||||
&:is(li, section).hasChildren:not(:is(.active, .bsplus-active)) {
|
||||
margin: 4px 8px 4px !important;
|
||||
background: rgba(255, 255, 255, 0.1) !important;
|
||||
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.14);
|
||||
}
|
||||
&:has(> .sub):is(.active, .bsplus-active) {
|
||||
background: transparent !important;
|
||||
backdrop-filter: none !important;
|
||||
-webkit-backdrop-filter: none !important;
|
||||
box-shadow: none !important;
|
||||
overflow: visible !important;
|
||||
contain: none !important;
|
||||
}
|
||||
}
|
||||
#{$active} {
|
||||
background: rgba(255, 255, 255, 0.2) !important;
|
||||
box-shadow:
|
||||
inset 0 0 0 1px rgba(255, 255, 255, 0.28),
|
||||
0 8px 20px rgba(0, 0, 0, 0.2);
|
||||
}
|
||||
}
|
||||
|
||||
&.bsplus-sidebar-style-sharp {
|
||||
#{$item},
|
||||
#{$active} {
|
||||
border-radius: 4px !important;
|
||||
}
|
||||
#{$item} {
|
||||
margin: 0 4px 4px !important;
|
||||
}
|
||||
#{$active} {
|
||||
background: rgba(0, 0, 0, 0.42) !important;
|
||||
}
|
||||
}
|
||||
|
||||
&.bsplus-sidebar-style-strip {
|
||||
#{$item} {
|
||||
margin: 0 0 2px !important;
|
||||
border-radius: 0 !important;
|
||||
background: transparent !important;
|
||||
box-shadow: none !important;
|
||||
}
|
||||
#{$active} {
|
||||
position: relative !important;
|
||||
background: rgba(255, 255, 255, 0.12) !important;
|
||||
box-shadow: none !important;
|
||||
&::after {
|
||||
@include accent-bar(0.55);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
&.bsplus-sidebar-style-neon {
|
||||
#{$active} {
|
||||
background: rgba(255, 255, 255, 0.1) !important;
|
||||
box-shadow:
|
||||
0 0 0 1px rgba(255, 255, 255, 0.55),
|
||||
0 0 14px rgba(255, 255, 255, 0.4),
|
||||
0 0 28px rgba(255, 255, 255, 0.22) !important;
|
||||
}
|
||||
#{$item} {
|
||||
margin: 0 8px 8px !important;
|
||||
}
|
||||
}
|
||||
|
||||
/* —— Density (comfortable = no class / no overrides) —— */
|
||||
&.bsplus-sidebar-density-compact {
|
||||
#{$item},
|
||||
#{$active} {
|
||||
padding: 6px 8px !important;
|
||||
min-height: 0 !important;
|
||||
}
|
||||
#{$item} {
|
||||
margin: 0 6px 4px !important;
|
||||
height: auto !important;
|
||||
}
|
||||
#{$label} {
|
||||
padding: 0 !important;
|
||||
margin: 0 !important;
|
||||
font-size: 13px !important;
|
||||
line-height: 1.2 !important;
|
||||
min-height: 20px !important;
|
||||
height: auto !important;
|
||||
white-space: nowrap !important;
|
||||
|
||||
> svg {
|
||||
width: 20px !important;
|
||||
height: 20px !important;
|
||||
margin: 0 8px 0 2px !important;
|
||||
flex-shrink: 0 !important;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
&.bsplus-sidebar-density-large {
|
||||
#{$item} {
|
||||
margin: 0 8px 10px !important;
|
||||
padding: 14px 12px !important;
|
||||
}
|
||||
#{$label} {
|
||||
padding: 0 !important;
|
||||
font-size: 17px !important;
|
||||
line-height: 1.25 !important;
|
||||
min-height: 30px !important;
|
||||
|
||||
> svg {
|
||||
width: 30px !important;
|
||||
height: 30px !important;
|
||||
margin: 0 10px 0 4px !important;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* —— Active indicator (fill = default, no class) —— */
|
||||
&.bsplus-sidebar-indicator-bar:not(.bsplus-sidebar-style-strip) {
|
||||
#{$active} {
|
||||
position: relative !important;
|
||||
background: rgba(255, 255, 255, 0.1) !important;
|
||||
box-shadow: none !important;
|
||||
&::after {
|
||||
@include accent-bar(0.45);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
&.bsplus-sidebar-indicator-outline {
|
||||
#{$active} {
|
||||
background: transparent !important;
|
||||
box-shadow:
|
||||
inset 0 0 0 2px rgba(255, 255, 255, 0.55),
|
||||
0 0 0 1px rgba(255, 255, 255, 0.12) !important;
|
||||
}
|
||||
}
|
||||
|
||||
&.bsplus-sidebar-indicator-underline:not(.bsplus-sidebar-style-strip) {
|
||||
#{$active} {
|
||||
position: relative !important;
|
||||
background: transparent !important;
|
||||
box-shadow: none !important;
|
||||
&::after {
|
||||
content: "" !important;
|
||||
position: absolute !important;
|
||||
left: 14px !important;
|
||||
right: 14px !important;
|
||||
bottom: 6px !important;
|
||||
top: auto !important;
|
||||
width: auto !important;
|
||||
height: 3px !important;
|
||||
border-radius: 999px !important;
|
||||
background: #fff !important;
|
||||
box-shadow: 0 0 8px rgba(255, 255, 255, 0.4) !important;
|
||||
pointer-events: none !important;
|
||||
z-index: 3 !important;
|
||||
opacity: 1 !important;
|
||||
display: block !important;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -23,7 +23,7 @@ html.transparencyEffects {
|
||||
/* Blurs */
|
||||
.search,
|
||||
.document,
|
||||
.border,
|
||||
.bsplus-rounded,
|
||||
.draggable,
|
||||
.notice,
|
||||
[class*="BasicPanel__BasicPanel___"],
|
||||
@@ -39,8 +39,6 @@ html.transparencyEffects {
|
||||
[class*="LabelList__selected___"],
|
||||
.buttonChecklist,
|
||||
.pane,
|
||||
.legacy-root button,
|
||||
.legacy-root a,
|
||||
[class*="MessageList__MessageList___"] {
|
||||
backdrop-filter: blur(80px);
|
||||
}
|
||||
@@ -51,7 +49,10 @@ html.transparencyEffects {
|
||||
backdrop-filter: blur(10px) !important;
|
||||
}
|
||||
|
||||
#menu,
|
||||
#menu {
|
||||
backdrop-filter: blur(var(--bsplus-sidebar-blur, 50px));
|
||||
}
|
||||
|
||||
.kanban-column,
|
||||
.whatsnewContainer,
|
||||
[class*="Message__Message___"] {
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 273 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 141 KiB |
@@ -0,0 +1,48 @@
|
||||
@import "tailwindcss" source("../");
|
||||
|
||||
@plugin "@tailwindcss/forms";
|
||||
|
||||
@custom-variant dark (&:is(.dark *));
|
||||
|
||||
@theme {
|
||||
--text-*: initial;
|
||||
--text-xs: 0.65rem;
|
||||
--text-sm: 0.775rem;
|
||||
--text-base: 0.65rem;
|
||||
--text-md: 0.65rem;
|
||||
--text-lg: 1rem;
|
||||
--text-xl: 1.25rem;
|
||||
--text-2xl: 1.5rem;
|
||||
--text-3xl: 1.875rem;
|
||||
--text-4xl: 2.25rem;
|
||||
--text-5xl: 3rem;
|
||||
--text-6xl: 4rem;
|
||||
--text-7xl: 5rem;
|
||||
--text-8xl: 6rem;
|
||||
--text-9xl: 8rem;
|
||||
--text-10xl: 10rem;
|
||||
--text-11xl: 12rem;
|
||||
--text-12xl: 14rem;
|
||||
--text-13xl: 16rem;
|
||||
--text-14xl: 18rem;
|
||||
|
||||
--font-IconFamily: IconFamily;
|
||||
|
||||
--animate-spin-fast: spin 0.4s linear infinite;
|
||||
|
||||
--aspect-theme: 5 / 1;
|
||||
}
|
||||
|
||||
@layer base {
|
||||
*,
|
||||
::after,
|
||||
::before,
|
||||
::backdrop,
|
||||
::file-selector-button {
|
||||
border-color: var(--color-gray-200, currentcolor);
|
||||
}
|
||||
|
||||
button {
|
||||
cursor: pointer;
|
||||
}
|
||||
}
|
||||
Vendored
+18
@@ -1,7 +1,9 @@
|
||||
declare module "*.mp4";
|
||||
declare module "*.webm";
|
||||
declare module "*.woff";
|
||||
declare module "*.scss";
|
||||
declare module "*.png";
|
||||
declare module "*.webp";
|
||||
declare module "*.html";
|
||||
declare module "*.svelte";
|
||||
|
||||
@@ -10,6 +12,22 @@ declare module "*?inlineWorker" {
|
||||
export default value;
|
||||
}
|
||||
|
||||
/** CRXJS dynamic content / main-world script path (relative to extension root). */
|
||||
declare module "*?script" {
|
||||
const path: string;
|
||||
export default path;
|
||||
}
|
||||
|
||||
declare module "*?script&iife" {
|
||||
const path: string;
|
||||
export default path;
|
||||
}
|
||||
|
||||
declare module "*?script&module" {
|
||||
const path: string;
|
||||
export default path;
|
||||
}
|
||||
|
||||
declare module "*.png?base64" {
|
||||
const value: string;
|
||||
export default value;
|
||||
|
||||
Vendored
+6
@@ -0,0 +1,6 @@
|
||||
declare const __ENABLE_GH_RELEASE_UPDATE_CHECK__: boolean;
|
||||
declare const __GH_RELEASE_REPO__: string;
|
||||
declare const __UPDATE_CHANNEL__: "stable" | "nightly";
|
||||
declare const __BUILD_LABEL__: string;
|
||||
declare const __GOOGLE_OAUTH_CLIENT_ID__: string;
|
||||
declare const __OUTLOOK_OAUTH_CLIENT_ID__: string;
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"last_updated": "2026-10-29T00:00:00.000Z",
|
||||
"whatsnew_html": "<div class=\"whatsnewTextContainer\"><h3>1. Agreement</h3><p>By installing or using BetterSEQTA+, you agree to these Terms of Service. If you do not agree, do not use the extension.</p><h3>2. The extension</h3><p>BetterSEQTA+ is a browser extension that enhances SEQTA Learn and SEQTA Engage on your device. Features may change over time.</p><h3>3. Your school account</h3><p>You must comply with your school’s policies when using SEQTA. BetterSEQTA+ does not replace your school’s terms.</p><h3>4. Acceptable use</h3><p>Do not use the extension to harm others, bypass security, or violate applicable law.</p><h3>5. Privacy</h3><p>Our Privacy Policy explains what data we process. See <a href=\"https://betterseqta.org/privacy\" target=\"_blank\" rel=\"noopener noreferrer\">betterseqta.org/privacy</a>.</p><h3>6. Changes</h3><p>We may update these terms. Material changes may require you to accept again in the extension.</p></div>"
|
||||
}
|
||||
@@ -1,7 +1,33 @@
|
||||
<script lang="ts">
|
||||
let { onClick, text } = $props<{ onClick: () => void, text: string, [key: string]: any }>();
|
||||
let {
|
||||
onClick,
|
||||
text,
|
||||
disabled = false,
|
||||
variant = "secondary",
|
||||
icon,
|
||||
class: className = "",
|
||||
}: {
|
||||
onClick: () => void;
|
||||
text: string;
|
||||
disabled?: boolean;
|
||||
variant?: "primary" | "secondary" | "ghost";
|
||||
icon?: string;
|
||||
class?: string;
|
||||
} = $props();
|
||||
|
||||
const variants = {
|
||||
primary: "bg-zinc-100 text-zinc-900 border-transparent enabled:hover:bg-white",
|
||||
secondary: "dark:bg-[#38373D]/50 bg-[#DDDDDD]/50 border-[#DDDDDD]/30 dark:border-[#38373D]/30 dark:text-white enabled:hover:brightness-125",
|
||||
ghost: "bg-transparent border-transparent dark:text-white enabled:hover:bg-zinc-200/60 dark:enabled:hover:bg-zinc-700/50",
|
||||
};
|
||||
</script>
|
||||
|
||||
<button onclick={onClick} class='px-5 py-1.5 text-[0.75rem] shadow-2xl border dark:bg-[#38373D]/50 bg-[#DDDDDD]/50 border-[#DDDDDD]/30 dark:border-[#38373D]/30 dark:text-white rounded-lg'>
|
||||
<button
|
||||
type="button"
|
||||
onclick={onClick}
|
||||
disabled={disabled}
|
||||
class="inline-flex items-center justify-center gap-1.5 px-5 py-1.5 text-[0.75rem] shadow-2xl border rounded-lg transition enabled:active:scale-[0.96] focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-zinc-400 disabled:cursor-not-allowed disabled:opacity-50 {variants[variant]} {className}"
|
||||
>
|
||||
{#if icon}<span class="font-IconFamily text-base" aria-hidden="true">{icon}</span>{/if}
|
||||
{text}
|
||||
</button>
|
||||
</button>
|
||||
@@ -0,0 +1,154 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from "svelte";
|
||||
import { animate } from "motion";
|
||||
import { delay } from "@/seqta/utils/delay.ts";
|
||||
import { cloudAuth } from "@/seqta/utils/CloudAuth";
|
||||
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
|
||||
import CloudPfpAvatar from "@/interface/components/CloudPfpAvatar.svelte";
|
||||
import Button from "./Button.svelte";
|
||||
|
||||
const { hidePanel }: {
|
||||
hidePanel: () => void;
|
||||
} = $props();
|
||||
|
||||
let cloudState = $state(cloudAuth.state);
|
||||
let background = $state<HTMLDivElement | null>(null);
|
||||
let content = $state<HTMLDivElement | null>(null);
|
||||
let loginError = $state<string | null>(null);
|
||||
|
||||
onMount(() => {
|
||||
const unsub = cloudAuth.subscribe((s) => {
|
||||
cloudState = s;
|
||||
});
|
||||
|
||||
if (background && content) {
|
||||
animate(
|
||||
background,
|
||||
{ opacity: [0, 1] },
|
||||
{ duration: 0.3, ease: [0.4, 0, 0.2, 1] }
|
||||
);
|
||||
animate(
|
||||
content,
|
||||
{ scale: [0.4, 1], opacity: [0, 1] },
|
||||
{ type: "spring", stiffness: 400, damping: 30 }
|
||||
);
|
||||
}
|
||||
|
||||
const handleEscapeKey = (e: KeyboardEvent) => {
|
||||
if (e.key === "Escape") closePanel();
|
||||
};
|
||||
document.addEventListener("keydown", handleEscapeKey);
|
||||
|
||||
return () => {
|
||||
unsub();
|
||||
document.removeEventListener("keydown", handleEscapeKey);
|
||||
};
|
||||
});
|
||||
|
||||
async function closePanel() {
|
||||
if (!background || !content) return;
|
||||
animate(
|
||||
content,
|
||||
{ scale: [1, 0.4], opacity: [1, 0] },
|
||||
{ type: "spring", stiffness: 400, damping: 30 }
|
||||
);
|
||||
animate(
|
||||
background,
|
||||
{ opacity: [1, 0] },
|
||||
{ ease: [0.4, 0, 0.2, 1] }
|
||||
);
|
||||
await delay(400);
|
||||
hidePanel();
|
||||
}
|
||||
|
||||
function handleBackgroundClick(event: MouseEvent) {
|
||||
if (event.target === background) closePanel();
|
||||
}
|
||||
|
||||
async function handleSignIn() {
|
||||
loginError = null;
|
||||
const result = await cloudAuth.startLogin();
|
||||
if (result.success) {
|
||||
closePanel();
|
||||
} else {
|
||||
loginError = result.error ?? "Failed to open login page";
|
||||
}
|
||||
}
|
||||
|
||||
async function handleLogout() {
|
||||
await cloudAuth.logout();
|
||||
}
|
||||
|
||||
function getInitials(): string {
|
||||
const u = cloudState.user;
|
||||
if (!u) return "?";
|
||||
if (u.displayName) return u.displayName.slice(0, 2).toUpperCase();
|
||||
if (u.username) return u.username.slice(0, 2).toUpperCase();
|
||||
if (u.email) return u.email.slice(0, 2).toUpperCase();
|
||||
return "?";
|
||||
}
|
||||
</script>
|
||||
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div
|
||||
bind:this={background}
|
||||
class="flex absolute top-0 left-0 z-50 justify-center items-center w-full h-full cursor-pointer bg-black/50 {$settingsState.DarkMode ? 'dark' : ''}"
|
||||
onclick={handleBackgroundClick}
|
||||
onkeydown={(e) => { if (e.key === "Enter") handleBackgroundClick(e as unknown as MouseEvent) }}
|
||||
>
|
||||
<div
|
||||
bind:this={content}
|
||||
class="p-5 w-[320px] bg-white rounded-xl border shadow-lg cursor-auto dark:bg-zinc-800 border-zinc-100 dark:border-zinc-700"
|
||||
>
|
||||
<h3 class="text-lg font-bold text-zinc-900 dark:text-white">BetterSEQTA Cloud</h3>
|
||||
<p class="mt-0.5 text-sm text-zinc-500 dark:text-zinc-400">Account & sync</p>
|
||||
|
||||
<div class="mt-4">
|
||||
{#if cloudState.isLoggedIn}
|
||||
<div class="flex flex-col gap-4">
|
||||
<div class="flex items-center gap-3">
|
||||
{#if cloudState.user?.pfpUrl}
|
||||
<CloudPfpAvatar
|
||||
user={cloudState.user}
|
||||
class="w-12 h-12 rounded-full object-cover ring-2 ring-zinc-200 dark:ring-zinc-600"
|
||||
/>
|
||||
{/if}
|
||||
{#if !cloudState.user?.pfpUrl}
|
||||
<div class="flex items-center justify-center w-12 h-12 rounded-full bg-zinc-300 dark:bg-zinc-600 text-zinc-700 dark:text-zinc-200 font-semibold text-base">
|
||||
{getInitials()}
|
||||
</div>
|
||||
{/if}
|
||||
<div class="min-w-0 flex-1">
|
||||
<p class="text-sm font-medium text-zinc-900 dark:text-white truncate">
|
||||
{cloudState.user?.displayName || cloudState.user?.username || cloudState.user?.email || "User"}
|
||||
</p>
|
||||
{#if cloudState.user?.email && cloudState.user?.email !== (cloudState.user?.displayName || cloudState.user?.username)}
|
||||
<p class="text-xs text-zinc-500 dark:text-zinc-400 truncate">{cloudState.user.email}</p>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onclick={handleLogout}
|
||||
class="w-full px-4 py-2.5 text-sm font-medium rounded-lg bg-zinc-200 dark:bg-zinc-700 text-zinc-900 dark:text-white hover:bg-zinc-300 dark:hover:bg-zinc-600 transition-colors duration-200"
|
||||
>
|
||||
Sign out
|
||||
</button>
|
||||
</div>
|
||||
{:else}
|
||||
<div class="flex flex-col gap-3">
|
||||
<p class="text-sm text-zinc-600 dark:text-zinc-400">
|
||||
Sign in to sync settings across devices, use your cloud profile picture, and more.
|
||||
</p>
|
||||
<Button class="w-full" icon={""} text="Sign in with BetterSEQTA Cloud" onClick={handleSignIn} />
|
||||
{#if loginError}
|
||||
<p class="text-xs text-red-600 dark:text-red-400">{loginError}</p>
|
||||
{/if}
|
||||
<p class="text-xs text-center text-zinc-400 dark:text-zinc-500">
|
||||
Opens accounts.betterseqta.org in a new tab
|
||||
</p>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,46 @@
|
||||
<script lang="ts">
|
||||
import { resolveCloudPfp, defaultAccountsPfpUrl } from "@/seqta/utils/cloudPfpCache";
|
||||
import type { CloudUser } from "@/seqta/utils/CloudAuth";
|
||||
|
||||
const { user, class: className = "" }: {
|
||||
user: CloudUser | null | undefined;
|
||||
class?: string;
|
||||
} = $props();
|
||||
|
||||
let avatarSrc = $state<string | undefined>(undefined);
|
||||
let revokeUrl: string | undefined;
|
||||
|
||||
$effect(() => {
|
||||
const u = user;
|
||||
if (revokeUrl) {
|
||||
URL.revokeObjectURL(revokeUrl);
|
||||
revokeUrl = undefined;
|
||||
}
|
||||
avatarSrc = undefined;
|
||||
|
||||
if (!u?.id) return;
|
||||
|
||||
const pfpUrl = u.pfpUrl ?? defaultAccountsPfpUrl(u.id);
|
||||
|
||||
let cancelled = false;
|
||||
void resolveCloudPfp(u.id, pfpUrl).then((resolved) => {
|
||||
if (cancelled || !resolved) return;
|
||||
if (resolved.fromCache) {
|
||||
revokeUrl = resolved.src;
|
||||
}
|
||||
avatarSrc = resolved.src;
|
||||
});
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
if (revokeUrl) {
|
||||
URL.revokeObjectURL(revokeUrl);
|
||||
revokeUrl = undefined;
|
||||
}
|
||||
};
|
||||
});
|
||||
</script>
|
||||
|
||||
{#if avatarSrc}
|
||||
<img src={avatarSrc} alt="" class={className} />
|
||||
{/if}
|
||||
@@ -0,0 +1,116 @@
|
||||
<script lang="ts">
|
||||
import browser from "@/lib/browser";
|
||||
import { cloudAuth } from "@/seqta/utils/CloudAuth";
|
||||
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
|
||||
import Button from "./Button.svelte";
|
||||
import Switch from "./Switch.svelte";
|
||||
|
||||
let { showDisclaimer }: {
|
||||
showDisclaimer: (onConfirm: () => void, onCancel: () => void) => void;
|
||||
} = $props();
|
||||
|
||||
let cloudState = $state(cloudAuth.state);
|
||||
let busy = $state(false);
|
||||
let statusMessage = $state<string | null>(null);
|
||||
let statusError = $state<string | null>(null);
|
||||
|
||||
$effect(() => {
|
||||
const unsub = cloudAuth.subscribe((s) => {
|
||||
cloudState = s;
|
||||
});
|
||||
return unsub;
|
||||
});
|
||||
|
||||
async function upload() {
|
||||
if (!cloudState.isLoggedIn) return;
|
||||
busy = true;
|
||||
statusError = null;
|
||||
statusMessage = null;
|
||||
try {
|
||||
const res = (await browser.runtime.sendMessage({
|
||||
type: "cloudSettingsUpload",
|
||||
})) as { success?: boolean; error?: string };
|
||||
if (res?.success) {
|
||||
statusMessage = "Settings uploaded.";
|
||||
} else {
|
||||
statusError = res?.error ?? "Upload failed";
|
||||
}
|
||||
} catch (e) {
|
||||
statusError = e instanceof Error ? e.message : "Upload failed";
|
||||
} finally {
|
||||
busy = false;
|
||||
}
|
||||
}
|
||||
|
||||
function promptDownload() {
|
||||
showDisclaimer(confirmDownload, () => {});
|
||||
}
|
||||
|
||||
async function confirmDownload() {
|
||||
if (!cloudState.isLoggedIn) return;
|
||||
busy = true;
|
||||
statusError = null;
|
||||
statusMessage = null;
|
||||
try {
|
||||
const res = (await browser.runtime.sendMessage({
|
||||
type: "cloudSettingsDownload",
|
||||
})) as { success?: boolean; error?: string; notFound?: boolean };
|
||||
if (res?.success) {
|
||||
statusMessage = "Settings restored.";
|
||||
} else {
|
||||
statusError = res?.error ?? "Download failed";
|
||||
}
|
||||
} catch (e) {
|
||||
statusError = e instanceof Error ? e.message : "Download failed";
|
||||
} finally {
|
||||
busy = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
{#if cloudState.isLoggedIn}
|
||||
<div class="flex flex-col gap-2.5">
|
||||
<div class="flex items-center justify-between gap-3">
|
||||
<div>
|
||||
<p class="text-[11px] font-semibold text-zinc-800 dark:text-zinc-100">Automatic sync</p>
|
||||
<p class="text-[10px] text-zinc-500 dark:text-zinc-400">Syncs settings when SEQTA loads and when you make changes</p>
|
||||
</div>
|
||||
<div class="shrink-0">
|
||||
<Switch
|
||||
state={$settingsState.autoCloudSettingsSync !== false}
|
||||
onChange={(isOn: boolean) => (settingsState.autoCloudSettingsSync = isOn)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<Button
|
||||
text={busy ? "Please wait\u2026" : "Upload"}
|
||||
onClick={upload}
|
||||
disabled={busy}
|
||||
/>
|
||||
<Button
|
||||
text={busy ? "Please wait\u2026" : "Download"}
|
||||
onClick={promptDownload}
|
||||
disabled={busy}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{#if statusMessage}
|
||||
<p class="text-[11px] text-emerald-600 dark:text-emerald-400">{statusMessage}</p>
|
||||
{/if}
|
||||
{#if statusError}
|
||||
<p class="text-[11px] text-red-600 dark:text-red-400">{statusError}</p>
|
||||
{/if}
|
||||
|
||||
<p class="text-[10px] text-zinc-400 dark:text-zinc-500">
|
||||
Passwords and tokens are never synced.
|
||||
<a
|
||||
href="https://betterseqta.org/privacy"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
class="font-medium text-emerald-600 underline decoration-emerald-600/50 underline-offset-2 hover:text-emerald-700 dark:text-emerald-400 dark:hover:text-emerald-300 rounded-xs"
|
||||
>Privacy policy</a>
|
||||
</p>
|
||||
</div>
|
||||
{/if}
|
||||
@@ -7,20 +7,19 @@
|
||||
import { indentWithTab, history, defaultKeymap, historyKeymap } from '@codemirror/commands';
|
||||
import { indentOnInput, indentUnit, bracketMatching, foldKeymap, syntaxHighlighting, defaultHighlightStyle } from '@codemirror/language';
|
||||
import { closeBrackets, autocompletion, closeBracketsKeymap, completionKeymap } from '@codemirror/autocomplete';
|
||||
import { highlightSpecialChars, drawSelection, rectangularSelection, crosshairCursor, highlightActiveLine, keymap, EditorView, dropCursor } from '@codemirror/view';
|
||||
import { highlightSpecialChars, drawSelection, rectangularSelection, crosshairCursor, highlightActiveLine, keymap, EditorView, dropCursor, type KeyBinding } from '@codemirror/view';
|
||||
import { color } from '@uiw/codemirror-extensions-color'
|
||||
import { Compartment } from '@codemirror/state';
|
||||
|
||||
// Theme
|
||||
import { githubLight, githubDark } from '@uiw/codemirror-theme-github';
|
||||
|
||||
// Language
|
||||
import { css } from "@codemirror/lang-css";
|
||||
|
||||
let editor = $state<HTMLDivElement | null>(null)
|
||||
let view: EditorView | null = null;
|
||||
let unsubSettings: (() => void) | undefined;
|
||||
let editorTheme = new Compartment();
|
||||
let { value, onChange, className } = $props<{value: string, onChange: (value: string) => void, className?: string}>()
|
||||
let { value, onChange, className }: {value: string, onChange: (value: string) => void, className?: string} = $props()
|
||||
|
||||
function createEditorState(initialContents: string) {
|
||||
let extensions = [
|
||||
@@ -46,7 +45,7 @@
|
||||
...historyKeymap,
|
||||
...foldKeymap,
|
||||
...completionKeymap,
|
||||
]),
|
||||
] as KeyBinding[]),
|
||||
EditorView.updateListener.of((update) => {
|
||||
if (update.docChanged) {
|
||||
onChange(update.state.doc.toString())
|
||||
@@ -73,7 +72,7 @@
|
||||
view = createEditorView(state, editor as HTMLElement);
|
||||
}
|
||||
|
||||
settingsState.subscribe((settings) => {
|
||||
unsubSettings = settingsState.subscribe((settings) => {
|
||||
if (view) {
|
||||
view.dispatch({
|
||||
effects: editorTheme.reconfigure(
|
||||
@@ -85,6 +84,7 @@
|
||||
});
|
||||
|
||||
onDestroy(() => {
|
||||
unsubSettings?.();
|
||||
if (view) {
|
||||
view.destroy();
|
||||
}
|
||||
|
||||
@@ -1,103 +0,0 @@
|
||||
div:has(> #rbgcp-wrapper) {
|
||||
background: transparent !important;
|
||||
}
|
||||
|
||||
#rbgcp-inputs-wrap {
|
||||
padding-top: 4px !important;
|
||||
margin-bottom: -8px;
|
||||
|
||||
#rbgcp-hex-input,
|
||||
#rbgcp-input {
|
||||
height: 28px !important;
|
||||
}
|
||||
}
|
||||
|
||||
.dark {
|
||||
#rbgcp-wrapper {
|
||||
div[style="padding-top: 11px; position: relative;"] div {
|
||||
color: white !important;
|
||||
}
|
||||
|
||||
#rbgcp-inputs-wrap #rbgcp-hex-input,
|
||||
#rbgcp-inputs-wrap #rbgcp-input {
|
||||
color: white !important;
|
||||
background-color: #37373b !important;
|
||||
border: none !important;
|
||||
}
|
||||
|
||||
div:has(> #rbgcp-solid-btn),
|
||||
div:has(> #rbgcp-advanced-btn),
|
||||
#rbgcp-color-model-btn > div,
|
||||
#rbgcp-gradient-controls-wrap {
|
||||
background-color: #37373b !important;
|
||||
color: white !important;
|
||||
|
||||
svg {
|
||||
circle {
|
||||
fill: white !important;
|
||||
}
|
||||
|
||||
polyline,
|
||||
line,
|
||||
g,
|
||||
path {
|
||||
stroke: white !important;
|
||||
}
|
||||
}
|
||||
|
||||
#rbgcp-radial-btn,
|
||||
#rbgcp-linear-btn {
|
||||
&[style*="background: white;"] {
|
||||
background-color: #28282b !important;
|
||||
}
|
||||
|
||||
svg {
|
||||
path,
|
||||
g,
|
||||
polyline,
|
||||
circle {
|
||||
stroke: white !important;
|
||||
fill: transparent !important;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
div:has(> #rbgcp-stop-input) svg {
|
||||
path {
|
||||
stroke: unset !important;
|
||||
fill: white !important;
|
||||
}
|
||||
}
|
||||
|
||||
#rbgcp-comparibles-btn svg path {
|
||||
fill: white !important;
|
||||
}
|
||||
|
||||
> div {
|
||||
color: white !important;
|
||||
|
||||
&[style*="background: white;"] {
|
||||
background: #28282b !important;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
div:has(> #rbgcp-degree-input) {
|
||||
width: 70px !important;
|
||||
}
|
||||
|
||||
#rbgcp-degree-input {
|
||||
width: 50px !important;
|
||||
}
|
||||
|
||||
#rbgcp-degree-input,
|
||||
#rbgcp-stop-input {
|
||||
color: white !important;
|
||||
}
|
||||
|
||||
#rbgcp-gradient-controls-wrap > div,
|
||||
#rbgcp-gradient-controls-wrap > div > div:not([role="button"]) {
|
||||
background-color: #37373b !important;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,102 +1,127 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from 'svelte'
|
||||
import ColourPicker from './ColourPicker.tsx';
|
||||
import ReactAdapter from './utils/ReactAdapter.svelte';
|
||||
import { animate } from 'motion';
|
||||
import { delay } from '@/seqta/utils/delay.ts'
|
||||
import { delay } from '@/seqta/utils/delay'
|
||||
import { settingsState } from '@/seqta/utils/listeners/SettingsState'
|
||||
import GradientPicker from './colourPicker/GradientPicker.svelte'
|
||||
|
||||
const { hidePicker, standalone = false, savePresets = true, customOnChange = null, customState = null } = $props<{
|
||||
hidePicker?: () => void,
|
||||
standalone?: boolean,
|
||||
savePresets?: boolean,
|
||||
customOnChange?: (color: string) => void,
|
||||
customState?: string
|
||||
}>();
|
||||
const PRESETS_KEY = 'colorPickerPresets';
|
||||
const MAX_PRESETS = 18;
|
||||
const DEFAULT_PRESETS = [
|
||||
"linear-gradient(30deg, rgba(229,209,218,1) 0%, RGBA(235,169,202,1) 46%, rgba(214,155,162,1) 100%)",
|
||||
"linear-gradient(40deg, rgba(201,61,0,1) 0%, RGBA(170, 5, 58, 1) 100%)",
|
||||
"linear-gradient(40deg, rgba(0, 141, 201, 0.76) 0%, rgba(8, 5, 170, 0.66) 100%)",
|
||||
"linear-gradient(40deg, rgba(0, 201, 20, 0.76) 0%, rgba(4, 160, 105, 0.66) 100%)",
|
||||
"linear-gradient(40deg, rgba(199, 20, 55, 0.76) 0%, rgba(95, 11, 160, 0.66) 100%)",
|
||||
"linear-gradient(40deg, rgba(24, 20, 199, 0.76) 0%, rgba(23, 173, 65, 0.66) 100%)",
|
||||
"radial-gradient(circle, rgba(20, 199, 178, 0.76) 32%, rgba(3, 120, 57, 0.66) 100%)",
|
||||
"radial-gradient(circle, rgba(13, 15, 145, 0.76) 12%, rgba(103, 3, 120, 0.66) 100%)",
|
||||
"linear-gradient(20deg, rgb(230, 21, 21) 0%, rgb(230, 109, 21) 12%, rgb(230, 34, 21) 26%, rgb(230, 21, 21) 39%, rgb(230, 84, 21) 48%, rgb(230, 34, 21) 58%, rgb(230, 96, 21) 69%, rgb(230, 34, 21) 80%, rgb(230, 71, 21) 89%, rgb(230, 21, 21) 100%)",
|
||||
"rgba(114, 1, 170, 0.89)",
|
||||
"rgba(93, 135, 63, 0.89)",
|
||||
"rgba(4, 4, 138, 0.77)",
|
||||
"rgba(21, 20, 20, 0.89)",
|
||||
"linear-gradient(340deg, rgb(205, 74, 82) 18%, rgba(132, 8, 8, 0.89) 46%, rgb(204, 78, 85) 72%)",
|
||||
"radial-gradient(circle, rgb(74, 205, 158) 0%, rgba(8, 72, 132, 0.89) 99%)",
|
||||
"rgba(17, 94, 89, 1)",
|
||||
"rgba(30, 64, 175, 0.89)",
|
||||
"rgba(134, 25, 143, 1)",
|
||||
"rgba(14, 165, 233, 0.9)",
|
||||
];
|
||||
|
||||
const {
|
||||
hidePicker,
|
||||
standalone = false,
|
||||
savePresets = true,
|
||||
customOnChange = null,
|
||||
customState = null,
|
||||
}: {
|
||||
hidePicker?: () => void;
|
||||
standalone?: boolean;
|
||||
savePresets?: boolean;
|
||||
customOnChange?: ((color: string) => void) | null;
|
||||
customState?: string | null;
|
||||
} = $props();
|
||||
|
||||
let background = $state<HTMLDivElement | null>(null);
|
||||
let content = $state<HTMLDivElement | null>(null);
|
||||
let presets = $state<string[]>(loadPresets());
|
||||
let current = $state(initialColour());
|
||||
|
||||
function initialColour(): string {
|
||||
return customState ?? settingsState.selectedColor ?? '';
|
||||
}
|
||||
|
||||
function loadPresets(): string[] {
|
||||
try {
|
||||
const saved = JSON.parse(localStorage.getItem(PRESETS_KEY) ?? 'null');
|
||||
return Array.isArray(saved) ? saved : DEFAULT_PRESETS;
|
||||
} catch {
|
||||
return DEFAULT_PRESETS;
|
||||
}
|
||||
}
|
||||
|
||||
function rememberPreset(colour: string) {
|
||||
if (!colour || presets[0] === colour) return;
|
||||
const updated = [colour, ...presets.filter((preset) => preset !== colour)].slice(0, MAX_PRESETS);
|
||||
localStorage.setItem(PRESETS_KEY, JSON.stringify(updated));
|
||||
}
|
||||
|
||||
function handleChange(colour: string) {
|
||||
current = colour;
|
||||
if (customOnChange) customOnChange(colour);
|
||||
else settingsState.selectedColor = colour;
|
||||
}
|
||||
|
||||
const closePicker = async () => {
|
||||
if (standalone) return;
|
||||
if (!background || !content) return;
|
||||
if (standalone || !background || !content) return;
|
||||
|
||||
animate(
|
||||
content,
|
||||
{ scale: [1, 0.4], opacity: [1, 0] },
|
||||
{
|
||||
type: 'spring',
|
||||
stiffness: 400,
|
||||
damping: 30
|
||||
}
|
||||
);
|
||||
|
||||
animate(
|
||||
background,
|
||||
{ opacity: [1, 0] },
|
||||
{ ease: [0.4, 0, 0.2, 1] }
|
||||
);
|
||||
animate(content, { scale: [1, 0.4], opacity: [1, 0] }, { type: 'spring', stiffness: 400, damping: 30 });
|
||||
animate(background, { opacity: [1, 0] }, { ease: [0.4, 0, 0.2, 1] });
|
||||
|
||||
await delay(400);
|
||||
hidePicker();
|
||||
hidePicker?.();
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
if (standalone) return;
|
||||
if (!background || !content) return;
|
||||
if (!standalone && background && content) {
|
||||
animate(background, { opacity: [0, 1] }, { duration: 0.3, ease: [0.4, 0, 0.2, 1] });
|
||||
animate(content, { scale: [0.4, 1], opacity: [0, 1] }, { type: 'spring', stiffness: 400, damping: 30 });
|
||||
}
|
||||
|
||||
animate(
|
||||
background,
|
||||
{ opacity: [0, 1] },
|
||||
{ duration: 0.3, ease: [0.4, 0, 0.2, 1] }
|
||||
);
|
||||
|
||||
animate(
|
||||
content,
|
||||
{ scale: [0.4, 1], opacity: [0, 1] },
|
||||
{
|
||||
type: 'spring',
|
||||
stiffness: 400,
|
||||
damping: 30
|
||||
}
|
||||
);
|
||||
|
||||
const handleEscapeKey = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape') {
|
||||
closePicker();
|
||||
}
|
||||
const handleEscapeKey = (event: KeyboardEvent) => {
|
||||
if (event.key === 'Escape') closePicker();
|
||||
};
|
||||
|
||||
document.addEventListener('keydown', handleEscapeKey);
|
||||
|
||||
return () => {
|
||||
document.removeEventListener('keydown', handleEscapeKey);
|
||||
if (savePresets && !customOnChange) rememberPreset(current);
|
||||
};
|
||||
});
|
||||
|
||||
function handleBackgroundClick(event: MouseEvent) {
|
||||
if (event.target === background) {
|
||||
closePicker();
|
||||
}
|
||||
if (event.target === background) closePicker();
|
||||
}
|
||||
</script>
|
||||
|
||||
{#if standalone}
|
||||
<div class="h-auto overflow-clip rounded-xl">
|
||||
<ReactAdapter customOnChange={customOnChange} customState={customState} savePresets={savePresets} el={ColourPicker} />
|
||||
<div class="h-auto {$settingsState.DarkMode ? 'dark' : ''}">
|
||||
<GradientPicker value={customState ?? current} onchange={handleChange} {presets} />
|
||||
</div>
|
||||
{:else}
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div
|
||||
bind:this={background}
|
||||
class="flex absolute top-0 left-0 z-50 justify-center items-center w-full h-full shadow-2xl cursor-pointer bg-black/20 border border-[#DDDDDD]/30 dark:border-[#38373D]/30"
|
||||
class="flex absolute top-0 left-0 z-50 justify-center items-center w-full h-full shadow-2xl cursor-pointer bg-black/20 border border-[#DDDDDD]/30 dark:border-[#38373D]/30 {$settingsState.DarkMode ? 'dark' : ''}"
|
||||
onclick={handleBackgroundClick}
|
||||
onkeydown={(e) => { e.key === 'Enter' && handleBackgroundClick }}
|
||||
onkeydown={(event) => { if (event.key === 'Enter') handleBackgroundClick(event as unknown as MouseEvent) }}
|
||||
>
|
||||
<div
|
||||
bind:this={content}
|
||||
class="p-4 h-auto bg-white rounded-xl border shadow-lg cursor-auto dark:bg-zinc-800 border-zinc-100 dark:border-zinc-700"
|
||||
>
|
||||
<ReactAdapter customOnChange={customOnChange} customState={customState} savePresets={savePresets} el={ColourPicker} />
|
||||
<GradientPicker value={current} onchange={handleChange} {presets} />
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
@@ -1,122 +0,0 @@
|
||||
import ColorPicker from "react-best-gradient-color-picker";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { settingsState } from "@/seqta/utils/listeners/SettingsState.ts";
|
||||
|
||||
const defaultPresets = [
|
||||
"linear-gradient(30deg, rgba(229,209,218,1) 0%, RGBA(235,169,202,1) 46%, rgba(214,155,162,1) 100%)",
|
||||
"linear-gradient(40deg, rgba(201,61,0,1) 0%, RGBA(170, 5, 58, 1) 100%)",
|
||||
"linear-gradient(40deg, rgba(0, 141, 201, 0.76) 0%, rgba(8, 5, 170, 0.66) 100%)",
|
||||
"linear-gradient(40deg, rgba(0, 201, 20, 0.76) 0%, rgba(4, 160, 105, 0.66) 100%)",
|
||||
"linear-gradient(40deg, rgba(199, 20, 55, 0.76) 0%, rgba(95, 11, 160, 0.66) 100%)",
|
||||
"linear-gradient(40deg, rgba(24, 20, 199, 0.76) 0%, rgba(23, 173, 65, 0.66) 100%)",
|
||||
"radial-gradient(circle, rgba(20, 199, 178, 0.76) 32%, rgba(3, 120, 57, 0.66) 100%)",
|
||||
"radial-gradient(circle, rgba(13, 15, 145, 0.76) 12%, rgba(103, 3, 120, 0.66) 100%)",
|
||||
"linear-gradient(20deg, rgb(230, 21, 21) 0%, rgb(230, 109, 21) 12%, rgb(230, 34, 21) 26%, rgb(230, 21, 21) 39%, rgb(230, 84, 21) 48%, rgb(230, 34, 21) 58%, rgb(230, 96, 21) 69%, rgb(230, 34, 21) 80%, rgb(230, 71, 21) 89%, rgb(230, 21, 21) 100%)",
|
||||
"rgba(114, 1, 170, 0.89)",
|
||||
"rgba(93, 135, 63, 0.89)",
|
||||
"rgba(4, 4, 138, 0.77)",
|
||||
"rgba(21, 20, 20, 0.89)",
|
||||
"linear-gradient(340deg, rgb(205, 74, 82) 18%, rgba(132, 8, 8, 0.89) 46%, rgb(204, 78, 85) 72%)",
|
||||
"radial-gradient(circle, rgb(74, 205, 158) 0%, rgba(8, 72, 132, 0.89) 99%)",
|
||||
"rgba(17, 94, 89, 1)",
|
||||
"rgba(30, 64, 175, 0.89)",
|
||||
"rgba(134, 25, 143, 1)",
|
||||
"rgba(14, 165, 233, 0.9)",
|
||||
];
|
||||
|
||||
interface PickerProps {
|
||||
customOnChange?: (color: string) => void;
|
||||
customState?: string;
|
||||
savePresets?: boolean;
|
||||
}
|
||||
|
||||
export default function Picker({
|
||||
customOnChange,
|
||||
customState,
|
||||
savePresets = true,
|
||||
}: PickerProps) {
|
||||
const [customThemeColor, setCustomThemeColor] = useState<string | null>();
|
||||
const [presets, setPresets] = useState<string[]>();
|
||||
|
||||
const latestValuesRef = useRef({
|
||||
customThemeColor,
|
||||
customOnChange,
|
||||
savePresets,
|
||||
presets,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (customState !== undefined && customState !== null) {
|
||||
setCustomThemeColor(customState);
|
||||
} else {
|
||||
setCustomThemeColor(settingsState.selectedColor ?? null);
|
||||
}
|
||||
|
||||
if (presets === undefined) {
|
||||
const savedPresets = localStorage.getItem("colorPickerPresets");
|
||||
setPresets(savedPresets ? JSON.parse(savedPresets) : defaultPresets);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
latestValuesRef.current = {
|
||||
customThemeColor,
|
||||
customOnChange,
|
||||
savePresets,
|
||||
presets,
|
||||
};
|
||||
}, [customThemeColor, customOnChange, savePresets, presets]);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
const { customThemeColor, customOnChange, savePresets, presets } =
|
||||
latestValuesRef.current;
|
||||
if (!(customThemeColor && !customOnChange && savePresets && presets))
|
||||
return;
|
||||
|
||||
// Only proceed if presets are different (avoid unnecessary updates)
|
||||
const existingIndex = presets.indexOf(customThemeColor);
|
||||
let updatedPresets;
|
||||
|
||||
if (existingIndex === 0) {
|
||||
// No need to update if the selected color is already the first element
|
||||
return;
|
||||
} else if (existingIndex > -1) {
|
||||
updatedPresets = [
|
||||
customThemeColor,
|
||||
...presets.slice(0, existingIndex),
|
||||
...presets.slice(existingIndex + 1),
|
||||
];
|
||||
} else {
|
||||
updatedPresets = [customThemeColor, ...presets].slice(0, 18);
|
||||
}
|
||||
|
||||
localStorage.setItem(
|
||||
"colorPickerPresets",
|
||||
JSON.stringify(updatedPresets),
|
||||
);
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (customThemeColor && !customOnChange) {
|
||||
settingsState.selectedColor = customThemeColor;
|
||||
}
|
||||
}, [customThemeColor, customOnChange]);
|
||||
|
||||
return (
|
||||
<ColorPicker
|
||||
disableDarkMode={true}
|
||||
presets={presets}
|
||||
value={customThemeColor ?? ""}
|
||||
onChange={(color: string) => {
|
||||
if (customOnChange) {
|
||||
customOnChange(color);
|
||||
setCustomThemeColor(color);
|
||||
} else {
|
||||
setCustomThemeColor(color);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
<script lang="ts">
|
||||
import { fade } from "svelte/transition";
|
||||
import browser from "@/lib/browser";
|
||||
import QRCode from "qrcode";
|
||||
import Button from "./Button.svelte";
|
||||
import { portal } from "../utils/portal";
|
||||
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
|
||||
|
||||
let showQrModal = $state(false);
|
||||
let qrDataUrl = $state<string | null>(null);
|
||||
let appLink = $state<string | null>(null);
|
||||
let errorMessage = $state<string | null>(null);
|
||||
let isLoading = $state(false);
|
||||
let isStandalone = $state(false);
|
||||
|
||||
function isExtensionPage(): boolean {
|
||||
return (
|
||||
window.location.protocol === "chrome-extension:" ||
|
||||
window.location.protocol === "moz-extension:"
|
||||
);
|
||||
}
|
||||
|
||||
function isSeqtaUrl(url: string): boolean {
|
||||
try {
|
||||
const u = new URL(url);
|
||||
return u.hostname.includes("seqta") || u.hostname.endsWith(".edu.au");
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeBaseUrl(url: string): string {
|
||||
try {
|
||||
const u = new URL(url);
|
||||
return u.origin;
|
||||
} catch {
|
||||
return url;
|
||||
}
|
||||
}
|
||||
|
||||
async function getAppLink(): Promise<string | null> {
|
||||
let baseUrl: string | undefined;
|
||||
|
||||
if (isExtensionPage()) {
|
||||
baseUrl = undefined;
|
||||
} else {
|
||||
baseUrl = normalizeBaseUrl(window.location.href);
|
||||
if (!isSeqtaUrl(baseUrl)) return null;
|
||||
}
|
||||
|
||||
const { appLink: link } = (await browser.runtime.sendMessage({
|
||||
type: "getSeqtaSession",
|
||||
baseUrl,
|
||||
})) as { appLink: string | null };
|
||||
return link ?? null;
|
||||
}
|
||||
|
||||
async function generateQrCode() {
|
||||
errorMessage = null;
|
||||
qrDataUrl = null;
|
||||
isLoading = true;
|
||||
|
||||
try {
|
||||
isStandalone = isExtensionPage();
|
||||
const link = await getAppLink();
|
||||
|
||||
if (!link) {
|
||||
if (isStandalone) {
|
||||
errorMessage =
|
||||
"Open SEQTA Learn in a tab and log in, then open settings from that tab to generate a QR code.";
|
||||
} else {
|
||||
errorMessage = "Please log in to SEQTA Learn first.";
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const dataUrl = await QRCode.toDataURL(link, { width: 256, margin: 2 });
|
||||
appLink = link;
|
||||
qrDataUrl = dataUrl;
|
||||
showQrModal = true;
|
||||
} catch (err) {
|
||||
console.error("[ConnectMobileApp] Failed to generate QR:", err);
|
||||
errorMessage = "Failed to generate QR code. Please try again.";
|
||||
} finally {
|
||||
isLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
function closeModal() {
|
||||
showQrModal = false;
|
||||
qrDataUrl = null;
|
||||
appLink = null;
|
||||
errorMessage = null;
|
||||
}
|
||||
|
||||
function openAppLink() {
|
||||
if (appLink) window.location.href = appLink;
|
||||
}
|
||||
|
||||
function downloadQrImage() {
|
||||
if (!qrDataUrl) return;
|
||||
const link = document.createElement("a");
|
||||
link.href = qrDataUrl;
|
||||
link.download = "desqta-login-qr.png";
|
||||
link.click();
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="flex flex-col gap-1 items-end">
|
||||
<Button onClick={generateQrCode} disabled={isLoading} text={isLoading ? "Generating..." : "Generate QR"} />
|
||||
{#if errorMessage}
|
||||
<p class="text-xs text-right text-amber-600 dark:text-amber-400">{errorMessage}</p>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
{#if showQrModal && qrDataUrl}
|
||||
<div
|
||||
use:portal
|
||||
class="fixed cursor-auto inset-0 z-10000 flex justify-center items-center bg-black/50 {isStandalone ? 'backdrop-blur-xs' : ''} {$settingsState.DarkMode ? 'dark' : ''}"
|
||||
role="button"
|
||||
tabindex="-1"
|
||||
onclick={(e) => {
|
||||
if (e.target === e.currentTarget) closeModal();
|
||||
}}
|
||||
onkeydown={(e) => {
|
||||
if (e.key === "Escape") closeModal();
|
||||
}}
|
||||
transition:fade={{ duration: 150 }}>
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div
|
||||
class="p-6 mx-4 w-full max-w-sm bg-white rounded-2xl shadow-2xl dark:bg-zinc-800"
|
||||
onclick={(e) => e.stopPropagation()}
|
||||
onkeydown={(e) => e.stopPropagation()}>
|
||||
<div class="flex justify-between items-center mb-4">
|
||||
<h2 class="text-lg font-bold text-zinc-900 dark:text-white">Scan with DesQTA</h2>
|
||||
<button
|
||||
type="button"
|
||||
onclick={closeModal}
|
||||
class="p-2 rounded-lg transition-colors text-zinc-500 hover:text-zinc-700 hover:bg-zinc-100 dark:hover:text-zinc-400 dark:hover:bg-zinc-700"
|
||||
aria-label="Close">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
<div class="flex justify-center p-4 bg-white rounded-xl dark:bg-zinc-900">
|
||||
<img src={qrDataUrl} alt="SEQTA Learn app link QR code" class="w-64 h-64" />
|
||||
</div>
|
||||
<div class="flex flex-col gap-2 mt-4">
|
||||
<button
|
||||
type="button"
|
||||
onclick={openAppLink}
|
||||
class="px-4 py-2.5 w-full text-sm font-medium text-white bg-indigo-600 rounded-lg transition-colors dark:bg-indigo-500 hover:bg-indigo-700 dark:hover:bg-indigo-600">
|
||||
Sign into DesQTA Desktop
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onclick={downloadQrImage}
|
||||
class="px-4 py-2 w-full text-xs font-medium rounded-lg border transition-colors text-zinc-500 dark:text-zinc-400 border-zinc-200 dark:border-zinc-600 hover:bg-zinc-50 dark:hover:bg-zinc-800/50">
|
||||
Download QR as image
|
||||
</button>
|
||||
</div>
|
||||
<p class="mt-2 text-sm text-center text-zinc-600 dark:text-zinc-400">
|
||||
Or scan this QR code with DesQTA on your phone.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
@@ -0,0 +1,74 @@
|
||||
<script lang="ts">
|
||||
import { fade } from 'svelte/transition';
|
||||
import { animate } from 'motion';
|
||||
import { settingsState } from '@/seqta/utils/listeners/SettingsState';
|
||||
|
||||
let { onConfirm, onCancel, title, message }: {
|
||||
onConfirm: () => void;
|
||||
onCancel: () => void;
|
||||
title: string;
|
||||
message: string;
|
||||
} = $props();
|
||||
|
||||
let modalElement: HTMLElement;
|
||||
|
||||
$effect(() => {
|
||||
if (modalElement) {
|
||||
animate(
|
||||
modalElement,
|
||||
{ scale: [0.9, 1], opacity: [0, 1] },
|
||||
{
|
||||
type: 'spring',
|
||||
stiffness: 300,
|
||||
damping: 25
|
||||
}
|
||||
);
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<div
|
||||
class="flex fixed inset-0 z-10000 justify-center items-center bg-black/50 {$settingsState.DarkMode ? 'dark' : ''}"
|
||||
style="position: fixed; top: 0; left: 0; right: 0; bottom: 0;"
|
||||
onclick={(e) => {
|
||||
if (e.target === e.currentTarget) onCancel();
|
||||
}}
|
||||
onkeydown={(e) => {
|
||||
if (e.key === 'Escape') onCancel();
|
||||
}}
|
||||
role="button"
|
||||
tabindex="-1"
|
||||
transition:fade={{ duration: 150 }}
|
||||
>
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div
|
||||
bind:this={modalElement}
|
||||
class="p-4 mx-4 w-full max-w-md bg-white rounded-2xl shadow-2xl dark:bg-zinc-800"
|
||||
onclick={(e) => e.stopPropagation()}
|
||||
onkeydown={(e) => e.stopPropagation()}
|
||||
>
|
||||
<h2 class="mb-3 text-xl font-bold text-gray-900 dark:text-white">
|
||||
{title}
|
||||
</h2>
|
||||
|
||||
<div class="mb-6 text-lg text-gray-700 whitespace-pre-line dark:text-gray-300">
|
||||
{message}
|
||||
</div>
|
||||
|
||||
<div class="flex gap-3 justify-end">
|
||||
<button
|
||||
onclick={onCancel}
|
||||
class="px-4 py-2 text-sm font-medium text-gray-700 bg-gray-100 rounded-lg transition-colors hover:bg-gray-200 dark:bg-zinc-700 dark:text-gray-200 dark:hover:bg-zinc-600"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
onclick={onConfirm}
|
||||
class="px-4 py-2 text-sm font-medium text-white bg-green-600 rounded-lg shadow-inner transition-colors hover:bg-green-700 dark:bg-green-500 dark:hover:bg-green-600"
|
||||
>
|
||||
Enable
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,574 @@
|
||||
<script lang="ts">
|
||||
import { fade, scale } from "svelte/transition";
|
||||
import { onMount } from "svelte";
|
||||
import Switch from "./Switch.svelte";
|
||||
import {
|
||||
FEEDBACK_CATEGORIES,
|
||||
FEEDBACK_MESSAGE_MAX,
|
||||
FEEDBACK_MESSAGE_MIN,
|
||||
type FeedbackCategory,
|
||||
} from "@/seqta/utils/feedback/constants";
|
||||
import {
|
||||
FeedbackApiError,
|
||||
addPendingFeedbackId,
|
||||
categoryLabel,
|
||||
fetchFeedbackStatusItem,
|
||||
fetchFeedbackStatusList,
|
||||
formatStatus,
|
||||
getInstanceHostname,
|
||||
hasReply,
|
||||
removePendingFeedbackIds,
|
||||
submitFeedback,
|
||||
validateFeedbackForm,
|
||||
type FeedbackStatusItem,
|
||||
} from "@/seqta/utils/feedback/client";
|
||||
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
|
||||
import Spinner from "./Spinner.svelte";
|
||||
|
||||
let { onClose, initialFeedbackId = null }: {
|
||||
onClose: () => void;
|
||||
initialFeedbackId?: string | null;
|
||||
} = $props();
|
||||
|
||||
let tab = $derived<"send" | "status">(
|
||||
typeof initialFeedbackId === "string" && initialFeedbackId ? "status" : "send",
|
||||
);
|
||||
let category = $state<FeedbackCategory>("bug");
|
||||
let subject = $state("");
|
||||
let message = $state("");
|
||||
let includeContact = $state(false);
|
||||
let contactName = $state("");
|
||||
let contactEmail = $state("");
|
||||
let includeInstance = $state(false);
|
||||
let submitting = $state(false);
|
||||
let errorMessage = $state<string | null>(null);
|
||||
let successId = $state<string | null>(null);
|
||||
let statusLoading = $state(false);
|
||||
let statusError = $state<string | null>(null);
|
||||
let statusItems = $state<FeedbackStatusItem[]>([]);
|
||||
let selectedItem = $state<FeedbackStatusItem | null>(null);
|
||||
|
||||
const instanceHostname = getInstanceHostname();
|
||||
const isDark = $derived(!!$settingsState.DarkMode);
|
||||
const busy = $derived(submitting || statusLoading);
|
||||
const fieldStyle = $derived(
|
||||
isDark
|
||||
? "background-color:#18181b;color:#fafafa;border-color:#52525b;color-scheme:dark"
|
||||
: "background-color:#fff;color:#18181b;border-color:#e4e4e7;color-scheme:light",
|
||||
);
|
||||
const field =
|
||||
"feedback-field w-full px-3 py-2.5 text-[18px] rounded-lg border focus:outline-hidden focus:ring-2 focus:ring-zinc-400";
|
||||
const btn =
|
||||
"px-4 py-2 text-[18px] font-medium rounded-lg transition-all duration-200 hover:scale-105 active:scale-95 focus:outline-hidden focus:ring-2 focus:ring-zinc-400 disabled:opacity-50";
|
||||
const btnMuted = $derived(
|
||||
`${btn} ${isDark ? "bg-zinc-700 text-zinc-200" : "bg-zinc-200 text-zinc-700"}`,
|
||||
);
|
||||
const btnPrimary = $derived(
|
||||
`${btn} ${isDark ? "bg-zinc-200 text-zinc-900" : "bg-zinc-800 text-white"}`,
|
||||
);
|
||||
|
||||
function isStatusDetailKey(key: string): boolean {
|
||||
return key.startsWith("status-") && key !== "status-list";
|
||||
}
|
||||
|
||||
const panelKey = $derived(
|
||||
tab === "send"
|
||||
? successId
|
||||
? "send-success"
|
||||
: "send-form"
|
||||
: selectedItem
|
||||
? `status-${selectedItem.id}`
|
||||
: "status-list",
|
||||
);
|
||||
|
||||
function errText(e: unknown): string {
|
||||
if (e instanceof FeedbackApiError) return e.message;
|
||||
return e instanceof Error ? e.message : "Something went wrong.";
|
||||
}
|
||||
|
||||
async function loadStatusList() {
|
||||
statusLoading = true;
|
||||
statusError = null;
|
||||
selectedItem = null;
|
||||
try {
|
||||
statusItems = await fetchFeedbackStatusList(10);
|
||||
} catch (e) {
|
||||
statusItems = [];
|
||||
statusError = errText(e);
|
||||
} finally {
|
||||
statusLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function openStatusItem(id: string) {
|
||||
statusLoading = true;
|
||||
statusError = null;
|
||||
try {
|
||||
selectedItem = await fetchFeedbackStatusItem(id);
|
||||
tab = "status";
|
||||
successId = null;
|
||||
if (selectedItem && hasReply(selectedItem)) {
|
||||
void removePendingFeedbackIds([selectedItem.id]);
|
||||
}
|
||||
} catch (e) {
|
||||
statusError = errText(e);
|
||||
} finally {
|
||||
statusLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
function selectTab(next: "send" | "status") {
|
||||
tab = next;
|
||||
errorMessage = null;
|
||||
statusError = null;
|
||||
successId = null;
|
||||
selectedItem = null;
|
||||
if (next === "status") void loadStatusList();
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
const host = document.getElementById("ExtensionPopup");
|
||||
host?.classList.add("bsplus-feedback-open");
|
||||
// Remove leaked global styles from earlier builds that portaled to body.
|
||||
document.getElementById("betterseqta-feedback-modal-styles")?.remove();
|
||||
|
||||
const handleEscapeKey = (e: KeyboardEvent) => {
|
||||
if (e.key === "Escape" && !busy) onClose();
|
||||
};
|
||||
document.addEventListener("keydown", handleEscapeKey);
|
||||
|
||||
if (typeof initialFeedbackId === "string" && initialFeedbackId) {
|
||||
void openStatusItem(initialFeedbackId);
|
||||
}
|
||||
|
||||
return () => {
|
||||
host?.classList.remove("bsplus-feedback-open");
|
||||
document.removeEventListener("keydown", handleEscapeKey);
|
||||
};
|
||||
});
|
||||
|
||||
async function handleSubmit() {
|
||||
const form = {
|
||||
category,
|
||||
subject,
|
||||
message,
|
||||
includeContact,
|
||||
contactName,
|
||||
contactEmail,
|
||||
includeInstance,
|
||||
};
|
||||
errorMessage = validateFeedbackForm(form);
|
||||
if (errorMessage) return;
|
||||
|
||||
submitting = true;
|
||||
try {
|
||||
const result = await submitFeedback(form);
|
||||
successId = result.id;
|
||||
void addPendingFeedbackId(result.id);
|
||||
} catch (e) {
|
||||
errorMessage = errText(e);
|
||||
} finally {
|
||||
submitting = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<!-- Backdrop click target — separate from dialog so inner clicks never bubble to a "close" handler. -->
|
||||
<div
|
||||
class="feedback-overlay fixed inset-0 z-99999 overflow-y-auto overscroll-contain {isDark
|
||||
? 'dark'
|
||||
: ''}"
|
||||
transition:fade={{ duration: $settingsState.animations ? 200 : 0 }}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="feedback-overlay__backdrop fixed inset-0 bg-black/50 backdrop-blur-xs border-0 p-0 cursor-default"
|
||||
aria-label="Close feedback"
|
||||
disabled={busy}
|
||||
onclick={() => {
|
||||
if (!busy) onClose();
|
||||
}}
|
||||
></button>
|
||||
|
||||
<div
|
||||
class="feedback-overlay__center relative z-1 flex min-h-full items-center justify-center p-4 sm:p-6 pointer-events-none"
|
||||
>
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div
|
||||
class="feedback-dialog pointer-events-auto w-full max-w-lg max-h-[min(90dvh,100%)] rounded-2xl shadow-2xl border text-[18px] {isDark
|
||||
? 'bg-zinc-800 text-white border-zinc-700'
|
||||
: 'bg-white text-zinc-900 border-zinc-200'}"
|
||||
onclick={(e) => e.stopPropagation()}
|
||||
onkeydown={(e) => e.stopPropagation()}
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby="feedback-modal-title"
|
||||
tabindex="-1"
|
||||
in:scale={{
|
||||
duration: $settingsState.animations ? 280 : 0,
|
||||
start: 0.92,
|
||||
opacity: 0,
|
||||
easing: (t) => 1 - Math.pow(1 - t, 3),
|
||||
}}
|
||||
>
|
||||
<div
|
||||
class="feedback-tabs shrink-0 flex gap-1 p-1 m-5 mb-0 rounded-full {isDark
|
||||
? 'bg-zinc-900'
|
||||
: 'bg-zinc-100'}"
|
||||
role="tablist"
|
||||
aria-label="Feedback views"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={tab === "send"}
|
||||
onclick={() => selectTab("send")}
|
||||
class="feedback-tab flex-1 px-3 py-2.5 rounded-full text-[18px] font-medium transition-all duration-200 {tab ===
|
||||
'send'
|
||||
? isDark
|
||||
? 'bg-zinc-700 text-white font-semibold shadow-xs'
|
||||
: 'bg-white text-zinc-900 font-semibold shadow-xs'
|
||||
: isDark
|
||||
? 'bg-transparent text-zinc-400 hover:text-zinc-200'
|
||||
: 'bg-transparent text-zinc-500 hover:text-zinc-800'}"
|
||||
>
|
||||
Send
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={tab === "status"}
|
||||
onclick={() => selectTab("status")}
|
||||
class="feedback-tab flex-1 px-3 py-2.5 rounded-full text-[18px] font-medium transition-all duration-200 {tab ===
|
||||
'status'
|
||||
? isDark
|
||||
? 'bg-zinc-700 text-white font-semibold shadow-xs'
|
||||
: 'bg-white text-zinc-900 font-semibold shadow-xs'
|
||||
: isDark
|
||||
? 'bg-transparent text-zinc-400 hover:text-zinc-200'
|
||||
: 'bg-transparent text-zinc-500 hover:text-zinc-800'}"
|
||||
>
|
||||
My feedback
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="feedback-panel__body overflow-y-auto overscroll-contain px-5 pb-5 pt-4">
|
||||
{#if panelKey === "send-success" && successId}
|
||||
<h2 id="feedback-modal-title" class="mb-3 text-xl font-bold">Thanks for the feedback</h2>
|
||||
<p class="mb-2 text-zinc-600 dark:text-zinc-300">Reference ID:</p>
|
||||
<p
|
||||
class="mb-4 px-3 py-2 font-mono text-base rounded-lg {isDark
|
||||
? 'bg-zinc-900'
|
||||
: 'bg-zinc-100'} break-all"
|
||||
>
|
||||
{successId}
|
||||
</p>
|
||||
<div class="flex gap-3 justify-end">
|
||||
<button
|
||||
type="button"
|
||||
class={btnMuted}
|
||||
onclick={() => successId && openStatusItem(successId)}>Check status</button
|
||||
>
|
||||
<button type="button" class={btnPrimary} onclick={onClose}>Done</button>
|
||||
</div>
|
||||
{:else if panelKey === "send-form"}
|
||||
<h2 id="feedback-modal-title" class="mb-1 text-xl font-bold">Send feedback</h2>
|
||||
<p class="mb-4 text-zinc-600 dark:text-zinc-400">
|
||||
Anonymous by default. Contact and school details are optional.
|
||||
</p>
|
||||
|
||||
<div class="flex flex-col gap-4">
|
||||
<label class="flex flex-col gap-1.5 font-medium">
|
||||
Category
|
||||
<select id="feedback-category" bind:value={category} class={field} style={fieldStyle}>
|
||||
{#each FEEDBACK_CATEGORIES as value (value)}
|
||||
<option {value} style={fieldStyle}>{categoryLabel(value)}</option>
|
||||
{/each}
|
||||
</select>
|
||||
</label>
|
||||
|
||||
<label class="flex flex-col gap-1.5 font-medium">
|
||||
Subject <span class="font-normal text-zinc-500">(optional)</span>
|
||||
<input
|
||||
type="text"
|
||||
maxlength={120}
|
||||
bind:value={subject}
|
||||
placeholder="Short summary"
|
||||
class={field}
|
||||
style={fieldStyle}
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label class="flex flex-col gap-1.5 font-medium">
|
||||
Message
|
||||
<textarea
|
||||
rows={5}
|
||||
maxlength={FEEDBACK_MESSAGE_MAX}
|
||||
bind:value={message}
|
||||
placeholder="What happened, or what would you like to see?"
|
||||
class="{field} resize-y min-h-[120px]"
|
||||
style={fieldStyle}
|
||||
></textarea>
|
||||
<span class="text-base font-normal text-zinc-500"
|
||||
>{message.trim().length}/{FEEDBACK_MESSAGE_MAX} (min {FEEDBACK_MESSAGE_MIN})</span
|
||||
>
|
||||
</label>
|
||||
|
||||
<div class="flex justify-between items-center gap-3">
|
||||
<div>
|
||||
<p class="font-medium">Include contact details</p>
|
||||
<p class="text-base text-zinc-500">Name and email so we can reply</p>
|
||||
</div>
|
||||
<Switch state={includeContact} onChange={(v) => (includeContact = v)} />
|
||||
</div>
|
||||
{#if includeContact}
|
||||
<input
|
||||
type="text"
|
||||
maxlength={80}
|
||||
bind:value={contactName}
|
||||
placeholder="Name"
|
||||
class={field}
|
||||
style={fieldStyle}
|
||||
/>
|
||||
<input
|
||||
type="email"
|
||||
maxlength={254}
|
||||
bind:value={contactEmail}
|
||||
placeholder="Email"
|
||||
class={field}
|
||||
style={fieldStyle}
|
||||
/>
|
||||
{/if}
|
||||
|
||||
<div class="flex justify-between items-center gap-3">
|
||||
<div>
|
||||
<p class="font-medium">Include SEQTA instance</p>
|
||||
<p class="text-base text-zinc-500">
|
||||
{#if instanceHostname}
|
||||
Hostname only: <span class="font-mono">{instanceHostname}</span>
|
||||
{:else}
|
||||
Open SEQTA first to detect hostname
|
||||
{/if}
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
state={includeInstance && !!instanceHostname}
|
||||
onChange={(v) => {
|
||||
if (instanceHostname) includeInstance = v;
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{#if errorMessage}
|
||||
<p class="text-red-600 dark:text-red-400" role="alert">{errorMessage}</p>
|
||||
{/if}
|
||||
|
||||
<p class="text-base text-zinc-500">
|
||||
Sent to betterseqta.org.
|
||||
<a
|
||||
href="https://betterseqta.org/privacy"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
class="underline">Privacy</a
|
||||
>
|
||||
</p>
|
||||
|
||||
<div class="flex gap-3 justify-end">
|
||||
<button type="button" class={btnMuted} onclick={onClose} disabled={submitting}
|
||||
>Cancel</button
|
||||
>
|
||||
<button type="button" class={btnPrimary} onclick={handleSubmit} disabled={submitting}>
|
||||
{submitting ? "Sending…" : "Send feedback"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{:else if isStatusDetailKey(panelKey) && selectedItem}
|
||||
<div class="flex items-start justify-between gap-3 mb-3">
|
||||
<h2 id="feedback-modal-title" class="text-xl font-bold">Feedback status</h2>
|
||||
<button
|
||||
type="button"
|
||||
class="{btnMuted} text-base! px-3! py-1.5!"
|
||||
onclick={() => {
|
||||
selectedItem = null;
|
||||
void loadStatusList();
|
||||
}}>Back</button
|
||||
>
|
||||
</div>
|
||||
<p class="mb-1 font-medium">
|
||||
{selectedItem.subject || "Untitled"} · {formatStatus(selectedItem.status)}
|
||||
</p>
|
||||
<p class="mb-4 font-mono text-base text-zinc-500 break-all">{selectedItem.id}</p>
|
||||
{#if hasReply(selectedItem)}
|
||||
<div
|
||||
class="p-3 mb-4 rounded-lg border {isDark
|
||||
? 'border-zinc-700 bg-zinc-900/50'
|
||||
: 'border-zinc-200 bg-zinc-50'}"
|
||||
>
|
||||
<p class="mb-1 text-base font-semibold uppercase tracking-wide text-zinc-500">
|
||||
Response
|
||||
</p>
|
||||
<p class="whitespace-pre-wrap">{selectedItem.response}</p>
|
||||
</div>
|
||||
{:else}
|
||||
<p class="mb-4 text-zinc-500">No response yet.</p>
|
||||
{/if}
|
||||
{#if statusError}<p class="mb-3 text-red-600 dark:text-red-400" role="alert">{statusError}</p
|
||||
>{/if}
|
||||
<div class="flex gap-3 justify-end">
|
||||
<button
|
||||
type="button"
|
||||
class={btnMuted}
|
||||
onclick={() => openStatusItem(selectedItem!.id)}
|
||||
disabled={statusLoading}
|
||||
>
|
||||
{statusLoading ? "Refreshing…" : "Refresh"}
|
||||
</button>
|
||||
<button type="button" class={btnPrimary} onclick={onClose}>Close</button>
|
||||
</div>
|
||||
{:else}
|
||||
<div class="flex items-start justify-between gap-3 mb-3">
|
||||
<h2 id="feedback-modal-title" class="text-xl font-bold">My feedback</h2>
|
||||
<button
|
||||
type="button"
|
||||
class="{btnMuted} text-base! px-3! py-1.5!"
|
||||
onclick={() => void loadStatusList()}
|
||||
disabled={statusLoading}
|
||||
>
|
||||
{statusLoading ? "…" : "Refresh"}
|
||||
</button>
|
||||
</div>
|
||||
{#if statusError}<p class="mb-3 text-red-600 dark:text-red-400" role="alert">{statusError}</p
|
||||
>{/if}
|
||||
{#if statusLoading && !statusItems.length}
|
||||
<div class="feedback-loading" aria-busy="true" aria-live="polite">
|
||||
<Spinner size="md" />
|
||||
<p class="text-zinc-500">Checking your feedback…</p>
|
||||
<div class="feedback-loading__skeleton" aria-hidden="true">
|
||||
<span></span>
|
||||
<span></span>
|
||||
<span></span>
|
||||
</div>
|
||||
</div>
|
||||
{:else if !statusItems.length}
|
||||
<p class="mb-4 text-zinc-500">No feedback yet.</p>
|
||||
<button type="button" class={btnPrimary} onclick={() => selectTab("send")}
|
||||
>Send feedback</button
|
||||
>
|
||||
{:else}
|
||||
<ul class="flex flex-col gap-2 mb-4">
|
||||
{#each statusItems as item (item.id)}
|
||||
<li>
|
||||
<button
|
||||
type="button"
|
||||
onclick={() => openStatusItem(item.id)}
|
||||
class="w-full p-3 text-left rounded-lg border transition-all duration-200 hover:scale-[1.01] focus:outline-hidden focus:ring-2 focus:ring-zinc-400 {isDark
|
||||
? 'border-zinc-700 bg-zinc-900/40'
|
||||
: 'border-zinc-200 bg-white'}"
|
||||
>
|
||||
<p class="text-base text-zinc-500 mb-0.5">
|
||||
{formatStatus(item.status)}{#if hasReply(item)} · Reply{/if} · {categoryLabel(
|
||||
item.category,
|
||||
)}
|
||||
</p>
|
||||
<p class="font-medium truncate">{item.subject || "Untitled"}</p>
|
||||
</button>
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
{/if}
|
||||
<div class="flex justify-end">
|
||||
<button type="button" class={btnMuted} onclick={onClose}>Close</button>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.feedback-overlay {
|
||||
-webkit-overflow-scrolling: touch;
|
||||
}
|
||||
|
||||
.feedback-overlay__backdrop:disabled {
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.feedback-dialog {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.feedback-panel__body {
|
||||
flex: 1 1 auto;
|
||||
min-height: 0;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
}
|
||||
|
||||
.feedback-tabs {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.feedback-tab {
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
line-height: 1.2;
|
||||
}
|
||||
|
||||
.feedback-loading {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 0.75rem;
|
||||
min-height: 14rem;
|
||||
padding: 1rem 0 1.5rem;
|
||||
}
|
||||
|
||||
.feedback-loading__skeleton {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
width: 100%;
|
||||
margin-top: 0.5rem;
|
||||
}
|
||||
|
||||
.feedback-loading__skeleton span {
|
||||
display: block;
|
||||
height: 3.5rem;
|
||||
border-radius: 0.5rem;
|
||||
background: color-mix(in srgb, currentColor 8%, transparent);
|
||||
animation: feedback-skeleton-pulse 1.2s ease-in-out infinite;
|
||||
}
|
||||
|
||||
.feedback-loading__skeleton span:nth-child(2) {
|
||||
animation-delay: 0.15s;
|
||||
}
|
||||
|
||||
.feedback-loading__skeleton span:nth-child(3) {
|
||||
animation-delay: 0.3s;
|
||||
}
|
||||
|
||||
@keyframes feedback-skeleton-pulse {
|
||||
0%,
|
||||
100% {
|
||||
opacity: 0.45;
|
||||
}
|
||||
50% {
|
||||
opacity: 0.9;
|
||||
}
|
||||
}
|
||||
|
||||
:global(.feedback-field),
|
||||
:global(.feedback-field option) {
|
||||
-webkit-text-fill-color: currentColor !important;
|
||||
caret-color: currentColor !important;
|
||||
}
|
||||
:global(.feedback-field::placeholder) {
|
||||
-webkit-text-fill-color: #a1a1aa !important;
|
||||
color: #a1a1aa !important;
|
||||
opacity: 1;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,147 @@
|
||||
<script lang="ts">
|
||||
import { fade } from "svelte/transition";
|
||||
import { onMount } from "svelte";
|
||||
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
|
||||
import { FONT_PRESETS, DEFAULT_FONT_ID, getFontPreset } from "@/seqta/ui/fonts/presets";
|
||||
import {
|
||||
applySelectedFont,
|
||||
buildFontPreviewCss,
|
||||
ensureFontPickerFontsLoaded,
|
||||
} from "@/seqta/ui/fonts/Manager";
|
||||
import { portal } from "@/interface/utils/portal";
|
||||
import { syncPageThemeToElement } from "@/interface/utils/syncPageTheme";
|
||||
import fontPickerStyles from "./fontPickerModal.css?inline";
|
||||
|
||||
let { hidePicker }: { hidePicker: () => void } = $props();
|
||||
|
||||
let rootEl = $state<HTMLElement | null>(null);
|
||||
let selectedId = $state(getFontPreset($settingsState.selectedFont).id);
|
||||
let styleEl: HTMLStyleElement | null = null;
|
||||
|
||||
function selectFont(id: string) {
|
||||
selectedId = id;
|
||||
settingsState.selectedFont = id;
|
||||
applySelectedFont(id);
|
||||
}
|
||||
|
||||
function resetToDefault() {
|
||||
selectFont(DEFAULT_FONT_ID);
|
||||
}
|
||||
|
||||
function handleBackdropClick(event: MouseEvent) {
|
||||
if (event.target === event.currentTarget) hidePicker();
|
||||
}
|
||||
|
||||
function syncTheme() {
|
||||
if (rootEl) syncPageThemeToElement(rootEl);
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
void ensureFontPickerFontsLoaded();
|
||||
|
||||
styleEl = document.getElementById(
|
||||
"betterseqta-font-picker-styles",
|
||||
) as HTMLStyleElement | null;
|
||||
if (!styleEl) {
|
||||
styleEl = document.createElement("style");
|
||||
styleEl.id = "betterseqta-font-picker-styles";
|
||||
document.head.appendChild(styleEl);
|
||||
}
|
||||
styleEl.textContent = `${fontPickerStyles}\n${buildFontPreviewCss()}`;
|
||||
|
||||
syncTheme();
|
||||
|
||||
const themeObserver = new MutationObserver(() => syncTheme());
|
||||
themeObserver.observe(document.documentElement, {
|
||||
attributes: true,
|
||||
attributeFilter: ["style", "class"],
|
||||
});
|
||||
|
||||
const handleEscapeKey = (event: KeyboardEvent) => {
|
||||
if (event.key === "Escape") hidePicker();
|
||||
};
|
||||
|
||||
document.addEventListener("keydown", handleEscapeKey);
|
||||
|
||||
return () => {
|
||||
themeObserver.disconnect();
|
||||
document.removeEventListener("keydown", handleEscapeKey);
|
||||
};
|
||||
});
|
||||
</script>
|
||||
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div
|
||||
bind:this={rootEl}
|
||||
use:portal={document.body}
|
||||
class="bsplus-font-picker-overlay bsplus-font-picker-root"
|
||||
onclick={handleBackdropClick}
|
||||
onkeydown={(event) => {
|
||||
if (event.key === "Enter" || event.key === " ") handleBackdropClick(event as unknown as MouseEvent);
|
||||
}}
|
||||
role="presentation"
|
||||
transition:fade={{ duration: 200 }}
|
||||
>
|
||||
<div
|
||||
class="bsplus-font-picker-dialog"
|
||||
onclick={(event) => event.stopPropagation()}
|
||||
onkeydown={(event) => event.stopPropagation()}
|
||||
role="dialog"
|
||||
tabindex="-1"
|
||||
aria-modal="true"
|
||||
aria-labelledby="font-picker-title"
|
||||
>
|
||||
<header class="bsplus-font-picker-header">
|
||||
<div class="bsplus-font-picker-header-actions">
|
||||
<button
|
||||
type="button"
|
||||
onclick={resetToDefault}
|
||||
disabled={selectedId === DEFAULT_FONT_ID}
|
||||
class="bsplus-font-picker-reset"
|
||||
aria-label="Reset font to default"
|
||||
>
|
||||
Reset to default
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onclick={hidePicker}
|
||||
class="bsplus-font-picker-done"
|
||||
aria-label="Close font picker"
|
||||
>
|
||||
Done
|
||||
</button>
|
||||
</div>
|
||||
<div class="bsplus-font-picker-header-text">
|
||||
<h2 id="font-picker-title" class="bsplus-font-picker-title">
|
||||
Choose a font
|
||||
</h2>
|
||||
<p class="bsplus-font-picker-desc">
|
||||
Choose a typeface for SEQTA Learn.
|
||||
</p>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div class="bsplus-font-picker-list">
|
||||
{#each FONT_PRESETS as preset (preset.id)}
|
||||
<button
|
||||
type="button"
|
||||
onclick={() => selectFont(preset.id)}
|
||||
class="bsplus-font-picker-option {selectedId === preset.id ? 'is-selected' : ''}"
|
||||
data-font-id={preset.id}
|
||||
>
|
||||
<div class="bsplus-font-picker-option-head">
|
||||
<span
|
||||
class="bsplus-font-picker-option-name"
|
||||
style="font-family: {preset.stack} !important;"
|
||||
>
|
||||
{preset.name}
|
||||
</span>
|
||||
{#if selectedId === preset.id}
|
||||
<span class="bsplus-font-picker-badge">Selected</span>
|
||||
{/if}
|
||||
</div>
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -1,10 +1,10 @@
|
||||
<script lang="ts">
|
||||
import { isValidHotkey, parseHotkey } from '@/plugins/built-in/globalSearch/src/utils/hotkeyUtils';
|
||||
|
||||
let { value, onChange } = $props<{
|
||||
let { value, onChange }: {
|
||||
value: string,
|
||||
onChange: (newValue: string) => void
|
||||
}>();
|
||||
} = $props();
|
||||
|
||||
let isRecording = $state(false);
|
||||
let recordedKeys = $state<Set<string>>(new Set());
|
||||
@@ -33,7 +33,6 @@
|
||||
};
|
||||
|
||||
const formatKeyForDisplay = (key: string): string => {
|
||||
// Map keys to their display format
|
||||
const isMac = navigator.platform.toUpperCase().indexOf('MAC') >= 0;
|
||||
const keyMap: Record<string, string> = {
|
||||
'ctrl': isMac ? '⌃' : 'Ctrl',
|
||||
@@ -70,7 +69,6 @@
|
||||
if (parsed.alt) parts.push('alt');
|
||||
if (parsed.shift) parts.push('shift');
|
||||
|
||||
// Add the main key
|
||||
if (parsed.key) parts.push(parsed.key);
|
||||
|
||||
return parts;
|
||||
@@ -78,7 +76,7 @@
|
||||
|
||||
const startRecording = () => {
|
||||
isRecording = true;
|
||||
recordedKeys.clear();
|
||||
recordedKeys = new Set();
|
||||
inputElement?.focus();
|
||||
};
|
||||
|
||||
@@ -87,12 +85,11 @@
|
||||
if (recordedKeys.has('esc')) {
|
||||
onChange('');
|
||||
isRecording = false;
|
||||
recordedKeys.clear();
|
||||
recordedKeys = new Set();
|
||||
inputElement?.blur();
|
||||
return;
|
||||
}
|
||||
|
||||
// Build the hotkey string
|
||||
const modifiers: string[] = [];
|
||||
let mainKey = '';
|
||||
|
||||
@@ -113,10 +110,16 @@
|
||||
}
|
||||
|
||||
isRecording = false;
|
||||
recordedKeys.clear();
|
||||
recordedKeys = new Set();
|
||||
inputElement?.blur();
|
||||
};
|
||||
|
||||
const addRecordedKey = (key: string) => {
|
||||
const next = new Set(recordedKeys);
|
||||
next.add(key);
|
||||
recordedKeys = next;
|
||||
};
|
||||
|
||||
const handleKeyDown = (e: KeyboardEvent) => {
|
||||
if (!isRecording) return;
|
||||
|
||||
@@ -125,15 +128,14 @@
|
||||
|
||||
const key = formatKeyForHotkey(e.key);
|
||||
|
||||
// Add modifiers
|
||||
if (e.ctrlKey) recordedKeys.add('ctrl');
|
||||
if (e.metaKey) recordedKeys.add('cmd');
|
||||
if (e.altKey) recordedKeys.add('alt');
|
||||
if (e.shiftKey) recordedKeys.add('shift');
|
||||
if (e.ctrlKey) addRecordedKey('ctrl');
|
||||
if (e.metaKey) addRecordedKey('cmd');
|
||||
if (e.altKey) addRecordedKey('alt');
|
||||
if (e.shiftKey) addRecordedKey('shift');
|
||||
|
||||
// Add the main key (ignore modifier keys themselves)
|
||||
if (!['ctrl', 'cmd', 'alt', 'shift'].includes(key)) {
|
||||
recordedKeys.add(key);
|
||||
addRecordedKey(key);
|
||||
}
|
||||
|
||||
// Auto-stop recording if we have a main key
|
||||
@@ -160,7 +162,6 @@
|
||||
}
|
||||
});
|
||||
|
||||
// Get the parts to display
|
||||
const hotkeyParts = $derived(isRecording
|
||||
? Array.from(recordedKeys).map(formatKeyForDisplay)
|
||||
: getHotkeyParts(value).map(formatKeyForDisplay));
|
||||
|
||||
Loaded 100 of 654 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user