Merge branch 'main' into sync-test

This commit is contained in:
Aden Lindsay authored and GitHub committed 2026-10-22 16:27:22 +10:30
commit 4943d441e1
62 files changed
+2467 -960

No files matched your search

+54
View File
@@ -0,0 +1,54 @@
/** @jest-environment jsdom */
import { execFileSync } from "node:child_process";
import { runInNewContext } from "node:vm";
// Compile the actual Vite entry in Node (esbuild cannot run in jsdom's realm).
const bootScript = execFileSync(
process.execPath,
[
"--input-type=module",
"-e",
`
import { readFileSync } from "node:fs";
import { transformSync } from "esbuild";
process.stdout.write(transformSync(readFileSync("src/SEQTA.ts", "utf8"), {
loader: "ts", format: "cjs",
supported: { "dynamic-import": false },
define: { "import.meta.env.DEV": "false", "import.meta.hot": "undefined" },
}).code);
`,
],
{ 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();
runInNewContext(bootScript, {
document,
window,
console,
require: (module: string) => {
if (module === "webextension-polyfill") {
return { storage: { local: { get: async () => stored } } };
}
if (module.includes("errorPageKitten")) {
return { isSeqta404Page: () => true, mountErrorPageKitten: mount };
}
return {};
},
});
for (let i = 0; i < 10; i++) await Promise.resolve();
expect(mount).not.toHaveBeenCalled();
expect(
window.getComputedStyle(document.querySelector(".message")!).display,
).not.toBe("none");
},
);
+12 -12
View File
@@ -178,24 +178,24 @@ async function bootErrorPage() {
}
document.removeEventListener("readystatechange", watchTitle);
if (!isSeqta404Page()) return;
const stored = await storagePromise;
if ((stored.onoff ?? true) === false) return;
const kittenSettings = stored["plugin.error-page-kitten.settings"] as
| { enabled?: boolean }
| undefined;
if (kittenSettings?.enabled === false) return;
try {
if (!isSeqta404Page()) return;
const stored = await storagePromise;
if ((stored.onoff ?? true) === false) return;
const kittenSettings = stored["plugin.error-page-kitten.settings"] as
| { enabled?: boolean }
| undefined;
if (kittenSettings?.enabled === false) return;
mountErrorPageKitten();
document.getElementById("bsplus-404-flash-hide")?.remove();
} catch (error) {
document.getElementById("bsplus-404-flash-hide")?.remove();
document
.querySelectorAll(".bsplus-kitten-404-hidden")
.forEach((el) => el.classList.remove("bsplus-kitten-404-hidden"));
console.error("[BetterSEQTA+] Failed to boot 404 page:", error);
} finally {
document.getElementById("bsplus-404-flash-hide")?.remove();
}
}
@@ -230,4 +230,4 @@ function recoverFromStaleDevModuleGraph(error: unknown) {
console.error(
"[BetterSEQTA+] Dev module graph is still stale after recovery. Restart `npm run dev`, then reload this page.",
);
}
}
+209 -59
View File
@@ -661,92 +661,241 @@ html.bsplus-custom-title-pending #title > :not(#bsplus-title-root),
height: 28px !important;
}
/* Icon Only Sidebar - compact mode. When submenu is open, all styles are disabled so it behaves as normal sidebar. */
body.icon-only-sidebar:not(:has(#menu li.hasChildren:is(.active, .bsplus-active))) {
/* Icons-only keeps the root rail visible while a full submenu opens beside it. */
body.icon-only-sidebar {
--bsplus-icon-rail-space: 70px;
#menu {
width: 70px !important;
transition: width 0.4s cubic-bezier(0.4, 0, 0.2, 1);
overflow: visible !important;
}
#menu > ul {
position: static !important;
min-width: 0 !important;
overflow-x: visible !important;
overflow-x: hidden !important;
overflow-y: auto !important;
}
#content {
left: 70px !important;
transition: left 0.4s cubic-bezier(0.4, 0, 0.2, 1);
left: var(--bsplus-icon-rail-space) !important;
/* Reserve the panel before its reveal so it never covers page content. */
transition: none !important;
}
#menu .sub {
left: 70px !important;
transition: left 0.4s cubic-bezier(0.4, 0, 0.2, 1);
}
#menu li > label span,
#menu section > label span {
display: none !important;
}
#menu ul > li > svg {
display: none !important;
}
#menu ul li,
#menu ul section {
/* Keep root hitboxes and icons in place; only nested lists drill away. */
#menu#menu > ul > :is(li, section) {
width: 85% !important;
min-width: 0 !important;
max-width: 100% !important;
max-width: 70px !important;
margin: 8px auto !important;
padding: 8px !important;
justify-content: center !important;
box-sizing: border-box !important;
}
pointer-events: auto !important;
transform: none !important;
animation: none !important;
transition: background-color 150ms ease !important;
#menu li > label,
#menu section > label {
flex: 0 0 auto !important;
min-width: 0 !important;
justify-content: center !important;
overflow: visible !important;
}
> label {
position: relative;
font-size: 0 !important;
flex: 0 0 auto !important;
min-width: 0 !important;
justify-content: center !important;
overflow: visible !important;
transform: none !important;
#menu li > label > svg,
#menu section > label > svg {
margin: 0 auto !important;
flex-shrink: 0 !important;
}
/* Engage: hide text nodes in labels via font-size trick, restore SVG size */
#menu .logo-link li > label,
#menu .logo-link section > label {
font-size: 0 !important;
justify-content: center !important;
svg {
width: 24px !important;
height: 24px !important;
font-size: initial !important;
flex-shrink: 0 !important;
margin: 0 auto !important;
span {
display: none !important;
}
> svg {
margin: 0 auto !important;
flex-shrink: 0 !important;
}
}
> svg {
display: none !important;
}
}
/* Engage: hide chevron arrows on hasChildren items */
#menu .logo-link li > svg {
display: none !important;
#menu#menu > ul > .hasChildren {
position: static !important;
backdrop-filter: none !important;
contain: none !important;
}
#menu#menu > ul > .hasChildren:is(.active, .bsplus-active) {
/* Preserve the outer hover inset; the inner edge meets the panel. */
width: 92.5% !important;
margin-left: 7.5% !important;
margin-right: 0 !important;
border-radius: var(--bsplus-sidebar-radius, 12px) 0 0
var(--bsplus-sidebar-radius, 12px) !important;
background: var(--background-primary) !important;
transition: none !important;
color: var(--text-primary) !important;
}
#menu#menu > ul > .hasChildren:is(.active, .bsplus-active) > label {
/* Compensate for the extra inner fill, keeping the icon centered on the rail. */
transform: translateX(-2.625px) !important;
}
/* Keep the arc fixed; bleed its paint into the opaque panel to avoid a
fractional compositor gap at the rail edge when zoomed. */
#menu#menu > ul > .hasChildren:is(.active, .bsplus-active) > label::after {
content: "";
position: absolute;
pointer-events: none;
width: calc(var(--bsplus-sidebar-radius, 12px) + 1px);
right: calc((100% - 70px) / 2 - 1px);
top: calc(-8px - var(--bsplus-sidebar-radius, 12px));
bottom: calc(-8px - var(--bsplus-sidebar-radius, 12px));
background:
radial-gradient(
circle at 0 0,
transparent calc(var(--bsplus-sidebar-radius, 12px) - 0.5px),
var(--background-primary) var(--bsplus-sidebar-radius, 12px)
)
top / 100% var(--bsplus-sidebar-radius, 12px) no-repeat,
radial-gradient(
circle at 0 100%,
transparent calc(var(--bsplus-sidebar-radius, 12px) - 0.5px),
var(--background-primary) var(--bsplus-sidebar-radius, 12px)
)
bottom / 100% var(--bsplus-sidebar-radius, 12px) no-repeat,
linear-gradient(var(--background-primary), var(--background-primary))
center / 100% calc(100% - 2 * var(--bsplus-sidebar-radius, 12px))
no-repeat;
}
#menu > ul > .hasChildren > .sub {
left: 70px !important;
right: auto !important;
top: 71px !important;
margin-top: 0 !important;
width: min(
var(--bsplus-sidebar-width, 270px),
calc(100vw - 70px)
) !important;
background: var(--background-primary) !important;
color: var(--text-primary) !important;
border-right: 1px solid var(--border-color, rgba(128, 128, 128, 0.3)) !important;
visibility: hidden;
opacity: 1;
transform: translateX(-100%);
/* The matching clip keeps the visible edge at the rail during the slide. */
clip-path: inset(0 0 0 100%);
transition:
transform 0.3s ease,
clip-path 0.3s ease,
visibility 0s 0.3s;
.nav {
background: var(--background-primary) !important;
}
:is(.nav, .back, .backLabel, li, section, label, svg) {
color: var(--text-primary) !important;
}
svg:not([fill="none"]) {
fill: currentColor !important;
}
:is(li, section):hover {
background: color-mix(
in srgb,
var(--text-primary) 8%,
transparent
) !important;
}
:is(li, section):is(.active, .bsplus-active):not(.hasChildren) {
background: color-mix(
in srgb,
var(--text-primary) 14%,
transparent
) !important;
&::after {
background: var(--text-primary) !important;
box-shadow: 0 0 10px
color-mix(in srgb, var(--text-primary) 45%, transparent) !important;
}
}
.sub {
left: 0 !important;
right: auto !important;
width: 100% !important;
background: var(--background-primary) !important;
color: var(--text-primary) !important;
}
}
#menu > ul > .hasChildren:is(.active, .bsplus-active) > .sub {
visibility: visible;
opacity: 1;
transform: none;
clip-path: inset(0);
transition-delay: 0s;
}
/* Switching root folders retires the previous panel immediately. */
#menu:has(> ul > .hasChildren:is(.active, .bsplus-active))
> ul
> .hasChildren:not(:is(.active, .bsplus-active))
> .sub {
visibility: hidden;
transition-delay: 0s;
}
/* Full panel rows retain their preset shape with equal horizontal insets. */
#menu#menu .sub :is(li.item, section.item) {
box-sizing: border-box !important;
}
#menu#menu:not(.bsplus-sidebar-style-strip)
.sub
> ul:not(.bsplus-drill-rows)
> :is(li.item, section.item) {
margin-inline: auto !important;
}
#menu#menu.bsplus-sidebar-style-strip .sub :is(li.item, section.item) {
width: 100% !important;
margin-inline: 0 !important;
}
#menu.bsplus-icon-rail-switching > ul > .hasChildren > .sub {
transition: none !important;
}
#menu#menu.bsplus-sidebar-style-neon .sub li.active:not(.hasChildren) {
box-shadow:
0 0 0 1px color-mix(in srgb, var(--text-primary) 55%, transparent),
0 0 14px color-mix(in srgb, var(--text-primary) 40%, transparent),
inset 0 0 0 1px color-mix(in srgb, var(--text-primary) 12%, transparent) !important;
}
#menu#menu.bsplus-sidebar-indicator-outline .sub li.active:not(.hasChildren) {
background: transparent !important;
box-shadow:
inset 0 0 0 2px color-mix(in srgb, var(--text-primary) 55%, transparent),
0 0 0 1px color-mix(in srgb, var(--text-primary) 12%, transparent) !important;
}
/* Engage: hide the name/details in #userActions */
#menu #userActions .details {
display: none !important;
}
/* Compact BetterSEQTA mark instead of the full wordmark. */
&.student #menu > ul::before {
width: 70px !important;
background-size: 36px 36px !important;
background-position: center center !important;
}
}
body.icon-only-sidebar:has(
#menu > ul > .hasChildren:is(.active, .bsplus-active)
) {
--bsplus-icon-rail-space: calc(
70px + min(var(--bsplus-sidebar-width, 270px), calc(100vw - 70px))
);
}
[class*="notifications__items___"] {
@@ -1260,15 +1409,16 @@ html.transparencyEffects
transform: translatex(var(--bsplus-sidebar-width, 270px));
}
body.icon-only-sidebar:not(:has(#menu li.hasChildren:is(.active, .bsplus-active))) {
body.icon-only-sidebar {
#menu {
-webkit-transform: translatex(-70px);
transform: translatex(-70px);
}
.menuShown #content {
-webkit-transform: translatex(70px);
transform: translatex(70px);
}
#content { left: 0 !important; }
}
body.icon-only-sidebar.menuShown #content {
-webkit-transform: translatex(var(--bsplus-icon-rail-space)) !important;
transform: translatex(var(--bsplus-icon-rail-space)) !important;
}
}
+45 -116
View File
@@ -1,84 +1,69 @@
#menu ul:has(li.hasChildren:is(.active, .bsplus-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:is(.active, .bsplus-active))) {
#menu ul:not(:has(> li.hasChildren:is(.active, .bsplus-active))) {
overflow-y: scroll !important;
}
#menu > ul:has(li.hasChildren:is(.active, .bsplus-active)) > li::before,
#menu > ul:has(li.hasChildren:is(.active, .bsplus-active)) > li::after,
#menu > ul ul:has(li.hasChildren:is(.active, .bsplus-active)) > li::before,
#menu > ul ul:has(li.hasChildren:is(.active, .bsplus-active)) > li::after,
#menu > ul:has(li.hasChildren:is(.active, .bsplus-active)) > li > label,
#menu > ul:has(li.hasChildren:is(.active, .bsplus-active)) > li > svg,
#menu > ul ul:has(li.hasChildren:is(.active, .bsplus-active)) > li > label,
#menu > ul ul:has(li.hasChildren:is(.active, .bsplus-active)) > li > svg {
/* !important beats theme animations (e.g. Beach palm-slide forwards). */
transform: translateX(-320px) !important;
/* 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;
}
#menu ul > li > label,
#menu ul > li > svg {
transition: transform 0.3s ease;
}
/* Frontmost drill panel: rows move with `.sub` only — no separate enter animation. */
#menu
li.hasChildren:is(.active, .bsplus-active):not(
:has(.sub li.hasChildren:is(.active, .bsplus-active))
)
> .sub
> ul
> li,
#menu
li.hasChildren:is(.active, .bsplus-active):not(
:has(.sub li.hasChildren:is(.active, .bsplus-active))
)
> .sub
> ul
> li
> label,
#menu
li.hasChildren:is(.active, .bsplus-active):not(
:has(.sub li.hasChildren:is(.active, .bsplus-active))
)
> .sub
> ul
> li
> svg,
#menu
li.hasChildren:is(.active, .bsplus-active):not(
:has(.sub li.hasChildren:is(.active, .bsplus-active))
)
> .sub
> ul
> li::before,
#menu
li.hasChildren:is(.active, .bsplus-active):not(
:has(.sub li.hasChildren:is(.active, .bsplus-active))
)
> .sub
> ul
> li::after {
animation: none !important;
transition: none !important;
transform: none !important;
&::before,
&::after {
transform: none !important;
animation: none !important;
}
}
#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);
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))
#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))
#menu
> ul:has(li.hasChildren:is(.active, .bsplus-active))
> li:is(.active, .bsplus-active) {
background: transparent !important;
}
@@ -99,59 +84,3 @@
#menu {
--bsplus-slide-off: -320px;
}
/* Reverse slide when drilling back — label/svg motion is driven inline in JS
so text stays off-screen until `.active` clears. Pseudo-elements use CSS. */
#menu.bsplus-sidebar-returning ul.bsplus-drill-return-target > li::before,
#menu.bsplus-sidebar-returning ul.bsplus-drill-return-target > li::after {
animation: bsplus-sidebar-return 0.3s cubic-bezier(0.4, 0, 0.2, 1) both !important;
transition: none !important;
}
@keyframes bsplus-sidebar-return {
from {
transform: translateX(var(--bsplus-slide-off, -320px));
}
to {
transform: translateX(0);
}
}
/* Icon-only collapsed: submenu slides over narrow icons. */
body.icon-only-sidebar:not(:has(#menu li.hasChildren:is(.active, .bsplus-active)))
#menu
> ul:has(li.hasChildren:is(.active, .bsplus-active))
> li::before,
body.icon-only-sidebar:not(:has(#menu li.hasChildren:is(.active, .bsplus-active)))
#menu
> ul
ul:has(li.hasChildren:is(.active, .bsplus-active))
> li::before,
body.icon-only-sidebar:not(:has(#menu li.hasChildren:is(.active, .bsplus-active)))
#menu
> ul:has(li.hasChildren:is(.active, .bsplus-active))
> li
> label,
body.icon-only-sidebar:not(:has(#menu li.hasChildren:is(.active, .bsplus-active)))
#menu
> ul:has(li.hasChildren:is(.active, .bsplus-active))
> li
> svg,
body.icon-only-sidebar:not(:has(#menu li.hasChildren:is(.active, .bsplus-active)))
#menu
> ul
ul:has(li.hasChildren:is(.active, .bsplus-active))
> li
> label,
body.icon-only-sidebar:not(:has(#menu li.hasChildren:is(.active, .bsplus-active)))
#menu
> ul
ul:has(li.hasChildren:is(.active, .bsplus-active))
> li
> svg {
transform: translateX(-70px);
}
body.icon-only-sidebar #menu {
--bsplus-slide-off: -70px;
}
+65 -7
View File
@@ -33,13 +33,14 @@ body.bsplus-sidebar-right {
max-width: none !important;
}
&.icon-only-sidebar:not(:has(#menu li.hasChildren:is(.active, .bsplus-active))) {
&.icon-only-sidebar {
#menu {
width: 70px !important;
}
#content {
right: 70px !important;
right: var(--bsplus-icon-rail-space) !important;
transition: none !important;
}
#menu .sub {
@@ -71,7 +72,11 @@ body.bsplus-sidebar-right {
}
}
#menu li:is(.active, .hasChildren.bsplus-active) > .sub > ul > .item:not(.hasChildren)::before {
#menu
li:is(.active, .hasChildren.bsplus-active)
> .sub
> ul
> .item:not(.hasChildren)::before {
left: auto !important;
right: 0 !important;
border-radius: 0 8px 8px 0 !important;
@@ -96,16 +101,21 @@ body.bsplus-sidebar-right {
}
&.menuShown #content {
transform: translateX(calc(-1 * var(--bsplus-sidebar-width, 270px))) !important;
transform: translateX(
calc(-1 * var(--bsplus-sidebar-width, 270px))
) !important;
}
&.icon-only-sidebar:not(:has(#menu li.hasChildren:is(.active, .bsplus-active))) {
&.icon-only-sidebar {
#menu {
transform: translateX(70px) !important;
}
&.menuShown #content {
transform: translateX(-70px) !important;
right: 0 !important;
transform: translateX(
calc(-1 * var(--bsplus-icon-rail-space))
) !important;
}
}
@@ -127,7 +137,55 @@ body.bsplus-sidebar-right {
}
&.icon-only-sidebar.menuShown #container #content #title {
transform: translateX(70px) !important;
transform: translateX(var(--bsplus-icon-rail-space)) !important;
}
}
}
body.icon-only-sidebar.bsplus-sidebar-right {
#menu#menu > ul > .hasChildren:is(.active, .bsplus-active) {
margin-left: 0 !important;
margin-right: 7.5% !important;
border-radius: 0 var(--bsplus-sidebar-radius, 12px)
var(--bsplus-sidebar-radius, 12px) 0 !important;
> label {
transform: translateX(2.625px) !important;
}
}
#menu#menu > ul > .hasChildren:is(.active, .bsplus-active) > label::after {
right: auto;
left: calc((100% - 70px) / 2 - 1px);
background:
radial-gradient(
circle at 100% 0,
transparent calc(var(--bsplus-sidebar-radius, 12px) - 0.5px),
var(--background-primary) var(--bsplus-sidebar-radius, 12px)
)
top / 100% var(--bsplus-sidebar-radius, 12px) no-repeat,
radial-gradient(
circle at 100% 100%,
transparent calc(var(--bsplus-sidebar-radius, 12px) - 0.5px),
var(--background-primary) var(--bsplus-sidebar-radius, 12px)
)
bottom / 100% var(--bsplus-sidebar-radius, 12px) no-repeat,
linear-gradient(var(--background-primary), var(--background-primary))
center / 100% calc(100% - 2 * var(--bsplus-sidebar-radius, 12px))
no-repeat;
}
#menu > ul > .hasChildren > .sub {
left: auto !important;
right: 70px !important;
border-right: none !important;
border-left: 1px solid var(--border-color, rgba(128, 128, 128, 0.3)) !important;
transform: translateX(100%);
clip-path: inset(0 100% 0 0);
}
#menu > ul > .hasChildren:is(.active, .bsplus-active) > .sub {
transform: none;
clip-path: inset(0);
}
#menu > ul > .hasChildren > .sub .sub {
left: 0 !important;
right: auto !important;
}
}
+64 -55
View File
@@ -92,20 +92,22 @@ $sidebar-motion: 0.4s cubic-bezier(0.4, 0, 0.2, 1);
&.bsplus-sidebar-style-glass {
/* Never put backdrop-filter on an open folder — it becomes a clip
containing-block and hides `.sub` labels on Chromium/Edge. */
#{$item}:not(:has(> .sub)) {
margin: 0 8px 8px !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);
}
#{$item}:has(> .sub) {
background: transparent !important;
backdrop-filter: none !important;
-webkit-backdrop-filter: none !important;
box-shadow: none !important;
overflow: visible !important;
contain: none !important;
#{$item} {
&:not(:has(> .sub)) {
margin: 0 8px 8px !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);
}
&:has(> .sub) {
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;
@@ -145,16 +147,17 @@ $sidebar-motion: 0.4s cubic-bezier(0.4, 0, 0.2, 1);
}
}
&.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;
}
&.bsplus-sidebar-style-neon #{$item} {
margin: 0 8px 8px !important;
&.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) —— */
@@ -206,42 +209,48 @@ $sidebar-motion: 0.4s cubic-bezier(0.4, 0, 0.2, 1);
}
/* —— 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-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-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;
&.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;
}
}
}
}
+2 -1
View File
@@ -3,6 +3,7 @@
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";
const { hidePanel } = $props<{
@@ -90,7 +91,7 @@
<!-- 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"
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) }}
>
@@ -3,6 +3,7 @@
import browser from "webextension-polyfill";
import QRCode from "qrcode";
import { portal } from "../utils/portal";
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
let showQrModal = $state(false);
let qrDataUrl = $state<string | null>(null);
@@ -120,7 +121,7 @@
{#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-sm' : ''}"
class="fixed cursor-auto inset-0 z-[10000] flex justify-center items-center bg-black/50 {isStandalone ? 'backdrop-blur-sm' : ''} {$settingsState.DarkMode ? 'dark' : ''}"
role="button"
tabindex="-1"
onclick={(e) => {
@@ -1,6 +1,7 @@
<script lang="ts">
import { fade } from 'svelte/transition';
import { animate } from 'motion';
import { settingsState } from '@/seqta/utils/listeners/SettingsState';
let { onConfirm, onCancel, title, message } = $props<{
onConfirm: () => void;
@@ -27,7 +28,7 @@
</script>
<div
class="flex fixed inset-0 z-[10000] justify-center items-center bg-black/50"
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();
@@ -55,6 +55,7 @@
}
</script>
<div class="sidebar-appearance">
<div class="card">
<header class="card-header split">
<div>
@@ -94,7 +95,7 @@
<button
type="button"
id={`sidebar-style-${style.id}`}
class="option"
class={`option style-${style.id}`}
class:active
role="option"
aria-selected={active}
@@ -242,7 +243,13 @@
</div>
</div>
</div>
<style>
.sidebar-appearance {
container: sidebar-appearance / inline-size;
}
.card {
margin: 4px 0;
padding: 4px;
@@ -606,4 +613,78 @@
display: flex;
justify-content: flex-end;
}
@container sidebar-appearance (max-width: 500px) {
.preview-pane,
.thumb {
display: none;
}
.picker-body {
grid-template-columns: minmax(0, 1fr);
gap: 0;
}
.options {
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 0.5rem;
}
.option {
min-height: 2.5rem;
justify-content: center;
padding: 0.5rem;
}
.option.style-soft {
border-radius: 1rem;
box-shadow: 0 3px 8px rgb(0 0 0 / 0.2);
}
.option.style-pill {
border-radius: 999px;
}
.option.style-glass {
background: linear-gradient(135deg, rgb(148 163 184 / 0.24), rgb(148 163 184 / 0.08));
box-shadow: inset 0 0 0 1px rgb(148 163 184 / 0.35);
}
.option.style-sharp {
border-radius: 0.25rem;
}
.option.style-strip {
border-radius: 0;
border-left: 3px solid currentColor;
}
.option.style-neon {
box-shadow: 0 0 0 1px rgb(148 163 184 / 0.6), 0 0 12px rgb(148 163 184 / 0.4);
}
.option.active {
outline: 1px solid currentColor;
outline-offset: 2px;
}
.option-label {
font-size: 0.775rem;
}
.card-header.split {
gap: 0.5rem;
}
.card-header.split .title {
font-size: 0.875rem;
}
.card-header.split .subtitle {
font-size: 0.65rem;
}
.selected-meta {
display: none;
}
}
</style>
+22 -34
View File
@@ -1,50 +1,38 @@
<script lang="ts">
import { animate } from 'motion';
import { onMount } from "svelte";
import { standalone } from '../utils/standalone.svelte';
import { fullMotionEffectsEnabled } from '@/seqta/utils/performanceMode';
let { state, onChange } = $props<{ state: boolean, onChange: (newState: boolean) => void }>();
let handle: HTMLElement | null = null;
let { state: checked, onChange } = $props<{ state: boolean, onChange: (newState: boolean) => void }>();
const springParams = {
stiffness: 600,
damping: 30,
};
let motionReady = $state(false);
onMount(() => {
// Paint the hydrated position before enabling transitions for later toggles.
let frame = requestAnimationFrame(() => {
frame = requestAnimationFrame(() => { motionReady = true; });
});
return () => cancelAnimationFrame(frame);
});
const knobX = $derived(state ? (standalone.standalone ? 24 : 20) : 0);
const animateSwitch = (enabled: boolean) => {
if (!handle) return;
const x = enabled ? (standalone.standalone ? 24 : 20) : 0;
if (!fullMotionEffectsEnabled()) {
handle.style.transform = `translateX(${x}px)`;
return;
}
animate(
handle,
{ x },
{
type: 'spring',
stiffness: springParams.stiffness,
damping: springParams.damping,
}
);
};
$effect(() => animateSwitch(state));
const knobX = $derived(checked ? (standalone.standalone ? 24 : 20) : 0);
</script>
<div
class="flex w-14 p-1 cursor-pointer transition-all duration-150 rounded-full bg-gradient-to-tr select-none shadow-2xl ring-[1px] ring-[#DDDDDD]/30 dark:ring-[#38373D]/30 {state ? 'to-[#30D259]/80 from-[#30D259] dark:from-[#30D259]/40 dark:to-[#30D259]' : 'dark:from-[#38373D]/50 dark:to-[#38373D] to-[#DDDDDD]/50 from-[#DDDDDD]'}"
onclick={() => onChange(!state)}
onkeydown={(e) => e.key === "Enter" && onChange(!state)}
class="flex w-14 p-1 cursor-pointer transition-all duration-150 rounded-full bg-gradient-to-tr select-none shadow-2xl ring-[1px] ring-[#DDDDDD]/30 dark:ring-[#38373D]/30 {checked ? 'to-[#30D259]/80 from-[#30D259] dark:from-[#30D259]/40 dark:to-[#30D259]' : 'dark:from-[#38373D]/50 dark:to-[#38373D] to-[#DDDDDD]/50 from-[#DDDDDD]'}"
onclick={() => onChange(!checked)}
onkeydown={(e) => e.key === "Enter" && onChange(!checked)}
role="switch"
aria-checked={state}
aria-checked={checked}
tabindex="0"
>
<div
bind:this={handle}
class="w-6 h-6 bg-white dark:bg-[#FEFEFE] rounded-full drop-shadow-md transition-transform duration-200"
style={fullMotionEffectsEnabled() ? undefined : `transform: translateX(${knobX}px)`}
style={`transform: translateX(${knobX}px); transition-duration: ${motionReady && fullMotionEffectsEnabled() ? 200 : 0}ms`}
></div>
</div>
<style>
@media (prefers-reduced-motion: reduce) {
[role="switch"] > div { transition: none !important; }
}
</style>
+16 -42
View File
@@ -1,8 +1,8 @@
<script lang="ts">
import MotionDiv from "./MotionDiv.svelte";
import LazyPanel from "./LazyPanel.svelte";
import type { Component } from "svelte";
import { onMount } from "svelte";
import { fullMotionEffectsEnabled } from "@/seqta/utils/performanceMode";
type TabDef = {
title: string;
@@ -16,37 +16,6 @@
activeTab?: number;
}>();
let containerRef: HTMLElement | null = $state(null);
let tabWidth = $state(0);
let containerWidth = $state(0);
const springTransition = { type: "spring", stiffness: 250, damping: 25 };
function measureTabs() {
if (!containerRef || tabs.length === 0) return;
tabWidth = 100 / tabs.length;
containerRef.style.setProperty("--tab-width", `${tabWidth}%`);
containerWidth = containerRef.getBoundingClientRect().width;
}
const indicatorX = $derived((tabWidth * activeTab * containerWidth) / 100);
$effect(() => {
tabs.length;
if (!containerRef) return;
measureTabs();
requestAnimationFrame(measureTabs);
const ro =
typeof ResizeObserver !== "undefined"
? new ResizeObserver(measureTabs)
: null;
ro?.observe(containerRef);
return () => ro?.disconnect();
});
onMount(() => {
const handleMessage = (event: MessageEvent) => {
if (event.data === "popupClosed") {
@@ -60,12 +29,11 @@
<div class="flex flex-col h-full min-h-0">
<div class="top-0 z-10 shrink-0 text-[0.875rem] pb-0.5 mx-4 px-2 tab-width-container" role="tablist">
<div bind:this={containerRef} class="flex relative">
<MotionDiv
<div class="flex relative">
<div
class="absolute top-0 left-0 z-0 h-full bg-gradient-to-tr dark:from-[#38373D]/80 dark:to-[#38373D] from-[#DDDDDD]/80 to-[#DDDDDD] rounded-full opacity-40 tab-width"
animate={{ x: indicatorX }}
transition={springTransition}
/>
style={`width: ${100 / Math.max(1, tabs.length)}%; transform: translateX(${activeTab * 100}%); transition: transform ${fullMotionEffectsEnabled() ? 250 : 0}ms cubic-bezier(0.22, 1, 0.36, 1)`}
></div>
{#each tabs as { title }, index}
<button
role="tab"
@@ -78,17 +46,17 @@
{/each}
</div>
</div>
<div class="overflow-hidden px-4 flex-1 min-h-0">
<div class="relative overflow-hidden px-4 flex-1 min-h-0">
<div
class="tab-scroll-fade absolute inset-x-4 top-0 h-3 bg-gradient-to-b from-white/80 dark:from-zinc-800/80 to-transparent pointer-events-none z-[1]"
aria-hidden="true"
></div>
{#each tabs as tab, index (index)}
{#if activeTab === index}
<div
role="tabpanel"
class="focus:outline-none w-full h-full min-h-0 pt-2 overflow-y-auto no-scrollbar pb-6 tab active relative"
>
<div
class="sticky top-0 w-full h-3 -mb-3 bg-gradient-to-b from-white/80 dark:from-zinc-800/80 to-transparent pointer-events-none z-[1]"
aria-hidden="true"
></div>
{#if tab.loader}
<LazyPanel loader={tab.loader} props={tab.props} />
{:else if tab.Content}
@@ -99,3 +67,9 @@
{/each}
</div>
</div>
<style>
@media (prefers-reduced-motion: reduce) {
.tab-width { transition: none !important; }
}
</style>
@@ -4,9 +4,10 @@
import CloudPfpAvatar from "@/interface/components/CloudPfpAvatar.svelte";
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
let { alwaysShowUserName = false, onClick = undefined } = $props<{
let { alwaysShowUserName = false, onClick = undefined, compact = false } = $props<{
alwaysShowUserName?: boolean;
onClick?: () => void;
compact?: boolean;
}>();
let cloudState = $state(cloudAuth.state);
@@ -71,7 +72,7 @@
<button
type="button"
onclick={handleButtonClick}
class="flex h-12 items-center gap-2 rounded-full bg-zinc-100/80 px-4 text-sm font-medium text-zinc-700 transition-colors duration-150 hover:bg-zinc-200 hover:text-zinc-950 focus:outline-none dark:bg-zinc-900/50 dark:text-zinc-200 dark:hover:bg-zinc-700 dark:hover:text-white"
class="flex items-center gap-2 bg-zinc-100/80 font-medium text-zinc-700 transition-colors duration-150 hover:bg-zinc-200 hover:text-zinc-950 focus:outline-none dark:bg-zinc-900/50 dark:text-zinc-200 dark:hover:bg-zinc-700 dark:hover:text-white {compact ? 'h-8 rounded-lg px-3 text-[0.75rem]' : 'h-12 rounded-full px-4 text-sm'}"
>
{#if cloudState.isLoggedIn}
{#if cloudState.user?.pfpUrl}
@@ -17,6 +17,7 @@
showStoreTools,
onLogoClick,
onClose,
onToggleSize,
} = $props<{
searchTerm: string;
setSearchTerm: (term: string) => void;
@@ -25,6 +26,7 @@
showStoreTools: boolean;
onLogoClick: () => void;
onClose: () => void;
onToggleSize?: () => void;
}>();
const tabs: { id: SettingsPage; title: string }[] = [
@@ -115,6 +117,13 @@
<CloudHeader />
{/if}
{#if onToggleSize}
<button type="button" onclick={onToggleSize}
class="flex h-10 w-10 shrink-0 items-center justify-center text-zinc-500 transition-[color,transform] duration-150 hover:text-zinc-950 active:scale-[0.96] focus:outline-none dark:text-zinc-400 dark:hover:text-white"
aria-label="Collapse settings" title="Collapse settings" aria-expanded="true">
<span class="font-IconFamily text-2xl" aria-hidden="true">{"\uec06"}</span>
</button>
{/if}
<PlainCloseButton onclick={onClose} label="Close settings" />
</div>
</header>
+4 -2
View File
@@ -4,8 +4,10 @@ import settingsStyle from "./index.css?inline";
import contentShadowStyle from "./contentShadow.css?inline";
const shadowStyles = {
settings: settingsStyle,
content: contentShadowStyle,
// Registered properties are document-wide, including inside shadow roots.
// Keep Tailwind 3 gradients separate from a host's typed Tailwind 4 properties.
settings: settingsStyle.replaceAll("--tw-gradient", "--bs-gradient"),
content: contentShadowStyle.replaceAll("--tw-gradient", "--bs-gradient"),
} as const;
export type ShadowStyleVariant = keyof typeof shadowStyles;
+214 -15
View File
@@ -6,7 +6,8 @@
import { resolveExtensionAssetUrl } from "@/lib/extensionAssetUrl";
import { standalone as StandaloneStore } from "../utils/standalone.svelte";
import { onMount, onDestroy } from "svelte";
import { onMount, onDestroy, tick } from "svelte";
import { animate } from "motion";
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
import { isPerformanceMode } from "@/seqta/utils/performanceMode";
@@ -54,6 +55,8 @@
const BACKGROUND_CATEGORY_PREFIX = "background-category:";
let compactActiveTab = $state(0);
let expanded = $state(settingsState.settingsPopupExpanded === true);
let lastExpandedTab: number | null = null;
let activePage = $state<PageId>("settings");
let activeSection = $state("general");
let activeThemeView = $state<ThemeView>("theme-store");
@@ -89,18 +92,22 @@
{ id: "appearance", label: "Appearance" },
];
const appNav: NavItem[] = [
$effect(() => {
if (!$settingsState.devMode && activeSection === "advanced") activeSection = "general";
});
const appNav = $derived<NavItem[]>([
{ id: "timetable", label: "Timetable" },
{ id: "assessments", label: "Assessments" },
{ id: "features", label: "Features" },
{ id: "advanced", label: "Advanced" },
...($settingsState.devMode ? [{ id: "advanced", label: "Advanced" }] : []),
{ id: "shortcuts", label: "Shortcuts" },
];
]);
const settingsNavGroups = [
const settingsNavGroups = $derived([
{ label: "User Settings", items: userNav },
{ label: "App Settings", items: appNav },
];
]);
const themeNavGroups = [
{
@@ -275,7 +282,109 @@
showCloudPanel: openCloudPanel,
};
let settingsPanel = $state<HTMLElement>();
let settingsContent = $state<HTMLElement>();
let resizeSnapshot: HTMLElement | undefined;
let resizeAnimation: ReturnType<typeof animate> | undefined;
let resizeGeneration = 0;
const bounds = ["width", "height", "top", "right"] as const;
const clearMorphContent = () => {
resizeSnapshot?.remove();
resizeSnapshot = undefined;
if (settingsContent) {
settingsContent.style.removeProperty("width");
settingsContent.style.removeProperty("height");
settingsContent.style.removeProperty("opacity");
}
};
const clearResize = () => {
resizeGeneration++;
resizeAnimation?.stop();
resizeAnimation = undefined;
if (settingsPanel) for (const key of bounds) settingsPanel.style.removeProperty(key);
clearMorphContent();
};
const resizePanel = async (nextExpanded: boolean) => {
const panel = settingsPanel;
const content = settingsContent;
const generation = ++resizeGeneration;
const from = panel ? getComputedStyle(panel) : null;
const start = bounds.map((key) => parseFloat(from?.[key] ?? "0"));
resizeAnimation?.stop();
const motionEnabled = $settingsState.animations !== false && !$settingsState.performanceMode &&
!window.matchMedia("(prefers-reduced-motion: reduce)").matches;
const root = panel?.getRootNode() as ShadowRoot | Document | undefined;
const restoreFocus = !!content?.contains(root?.activeElement ?? null);
// A visual snapshot has no live component listeners or accessible controls.
// Include the current crossfade when a second click reverses the morph.
if (panel && content && motionEnabled) {
const snapshot = document.createElement("div");
snapshot.inert = true;
snapshot.setAttribute("aria-hidden", "true");
snapshot.setAttribute("data-settings-snapshot", "");
snapshot.style.cssText = `position:absolute;top:0;right:0;width:${panel.clientWidth}px;height:${panel.clientHeight}px;overflow:hidden;pointer-events:none;z-index:20;`;
snapshot.append(content.cloneNode(true));
if (resizeSnapshot) snapshot.append(resizeSnapshot.cloneNode(true));
snapshot.querySelectorAll("[id]").forEach((element) => element.removeAttribute("id"));
resizeSnapshot?.remove();
resizeSnapshot = snapshot;
panel.append(snapshot);
content.style.opacity = "0";
} else {
clearMorphContent();
}
expanded = nextExpanded;
await tick();
if (!panel || !content || generation !== resizeGeneration) return;
for (const key of bounds) panel.style.removeProperty(key);
if (restoreFocus) content.querySelector<HTMLButtonElement>(
`[aria-label="${nextExpanded ? "Collapse" : "Expand"} settings"]`,
)?.focus({ preventScroll: true });
if (!motionEnabled) return;
const targetStyle = getComputedStyle(panel);
const target = bounds.map((key) => parseFloat(targetStyle[key]));
// The incoming layout stays at its destination size while the outer bounds
// move, so compact text and images never stretch across the expanded panel.
content.style.width = `${panel.clientWidth}px`;
content.style.height = `${panel.clientHeight}px`;
bounds.forEach((key, index) => { panel.style[key] = `${start[index]}px`; });
resizeAnimation = animate(0, 1, {
type: "spring", stiffness: 420, damping: 36,
onUpdate: (progress) => {
if (generation !== resizeGeneration) return;
const opacity = Math.max(0, Math.min(1, progress));
content.style.opacity = String(opacity);
if (resizeSnapshot) resizeSnapshot.style.opacity = String(1 - opacity);
bounds.forEach((key, index) => {
panel.style[key] = `${start[index] + (target[index] - start[index]) * progress}px`;
});
},
onComplete: () => {
if (generation !== resizeGeneration) return;
for (const key of bounds) panel.style.removeProperty(key);
clearMorphContent();
resizeAnimation = undefined;
},
});
};
let restoreSizeAfterClose = false;
const resetClosedLayout = () => {
if (!restoreSizeAfterClose) return;
clearResize();
expanded = settingsState.settingsPopupExpanded === true;
restoreSizeAfterClose = false;
};
const closePopupsOnSettingsClose = () => {
resizeGeneration++;
resizeAnimation?.stop();
resizeAnimation = undefined;
if (expanded) syncCompactTab();
restoreSizeAfterClose = true;
if (document.getElementById("ExtensionPopup")?.style.opacity === "0") resetClosedLayout();
showColourPicker = false;
showFontPicker = false;
showCloudPanel = false;
@@ -289,6 +398,33 @@
}
};
const syncCompactTab = () => {
compactActiveTab = activePage === "settings"
? activeSection === "shortcuts" ? 1 : 0
: 2;
lastExpandedTab = compactActiveTab;
};
const toggleExpanded = () => {
settingsState.settingsPopupExpanded = !expanded;
if (expanded) {
syncCompactTab();
} else if (compactActiveTab === lastExpandedTab) {
void resizePanel(true);
return;
} else if (compactActiveTab === 1) {
activePage = "settings";
activeSection = "shortcuts";
} else if (compactActiveTab === 2) {
activePage = "themes";
activeThemeView = "theme-settings";
} else {
activePage = "settings";
if (activeSection === "shortcuts") activeSection = "general";
}
void resizePanel(!expanded);
};
const selectNavItem = (id: string) => {
if (activePage === "settings") {
settingsSearch = "";
@@ -310,6 +446,9 @@
};
const applyDestination = (destination: SettingsDestination) => {
clearResize();
restoreSizeAfterClose = false;
expanded = true;
activePage = destination.page;
if (destination.page === "settings") {
if (destination.section) {
@@ -341,6 +480,8 @@
onMount(() => {
settingsPopup.addListener(closePopupsOnSettingsClose);
window.addEventListener("bsplus:settings-hidden", resetClosedLayout);
window.addEventListener("bsplus:settings-opening", resetClosedLayout);
if (standalone) {
StandaloneStore.setStandalone(true);
@@ -386,6 +527,8 @@
window.addEventListener("keydown", onKeyDown);
return () => {
window.removeEventListener("bsplus:settings-hidden", resetClosedLayout);
window.removeEventListener("bsplus:settings-opening", resetClosedLayout);
window.removeEventListener("keydown", onKeyDown);
window.removeEventListener("bsplus:open-feedback", onOpenFeedback);
window.removeEventListener(SETTINGS_NAVIGATION_EVENT, onNavigateSettings);
@@ -393,6 +536,7 @@
});
onDestroy(() => {
clearResize();
settingsPopup.removeListener(closePopupsOnSettingsClose);
});
</script>
@@ -414,6 +558,7 @@
showStoreTools={isOfficialStoreView || activeThemeView === "community-themes"}
onLogoClick={handleDevModeToggle}
onClose={handleClose}
onToggleSize={standalone ? undefined : toggleExpanded}
/>
<!-- Body: left nav + content -->
@@ -596,13 +741,13 @@
class="flex h-full min-h-0 flex-col gap-2 overflow-hidden bg-white dark:bg-zinc-800 dark:text-white"
>
<div
class="grid shrink-0 place-items-center border-b border-zinc-200/40 dark:border-zinc-700/40"
class="grid shrink-0 items-center border-b border-zinc-200/40 dark:border-zinc-700/40 {standalone ? 'grid-cols-1' : 'grid-cols-[minmax(0,1fr)_44px] gap-2 px-2'}"
>
<!-- svelte-ignore a11y_no_noninteractive_element_interactions -->
<!-- svelte-ignore a11y_click_events_have_key_events -->
<img
src={resolveExtensionAssetUrl(darkLogo)}
class="w-4/5 dark:hidden"
class="min-w-0 dark:hidden {standalone ? 'mx-auto w-4/5' : 'h-auto w-full max-w-[296px] justify-self-center object-contain'}"
alt="BetterSEQTA+"
onclick={handleDevModeToggle}
/>
@@ -610,10 +755,17 @@
<!-- svelte-ignore a11y_click_events_have_key_events -->
<img
src={resolveExtensionAssetUrl(lightLogo)}
class="hidden w-4/5 dark:block"
class="hidden min-w-0 dark:block {standalone ? 'mx-auto w-4/5' : 'h-auto w-full max-w-[296px] justify-self-center object-contain'}"
alt="BetterSEQTA+"
onclick={handleDevModeToggle}
/>
{#if !standalone}
<button type="button" onclick={toggleExpanded}
class="mt-2 flex h-11 w-11 shrink-0 self-start items-center justify-center text-zinc-500 transition-[color,transform] duration-150 hover:text-zinc-950 active:scale-[0.96] focus:outline-none dark:text-zinc-400 dark:hover:text-white"
aria-label="Expand settings" title="Expand settings" aria-expanded="false">
<span class="font-IconFamily text-2xl" aria-hidden="true">{"\uebdb"}</span>
</button>
{/if}
</div>
<div class="min-h-0 flex-1 overflow-hidden">
@@ -653,7 +805,7 @@
</div>
{:else}
<div
class="absolute inset-0 z-50 flex items-center justify-center p-4 sm:p-6 {$settingsState.DarkMode
class="absolute inset-0 z-50 {$settingsState.DarkMode
? 'dark'
: ''}"
role="dialog"
@@ -662,22 +814,69 @@
>
<button
type="button"
class="absolute inset-0 bg-black/60 {$settingsState.performanceMode
? 'backdrop-blur-none'
: 'backdrop-blur-sm'} transition-colors duration-200"
class="settings-backdrop absolute inset-0 {expanded ? 'bg-black/60' : 'bg-transparent'} {expanded && !$settingsState.performanceMode
? 'backdrop-blur-sm'
: 'backdrop-blur-none'}"
class:settings-backdrop--motion={$settingsState.animations !== false && !$settingsState.performanceMode}
aria-label="Close settings"
onclick={handleClose}
></button>
<div
class="relative z-10 h-[min(860px,92vh)] w-[min(1180px,96vw)] no-scrollbar overflow-clip"
class="settings-panel absolute z-10 no-scrollbar overflow-clip bg-white dark:bg-zinc-800 shadow-2xl border border-zinc-200/60 dark:border-zinc-700/60"
class:settings-panel--expanded={expanded}
bind:this={settingsPanel}
data-settings-panel
>
{@render settingsShell()}
<div class="settings-content" bind:this={settingsContent}>
{#if expanded}
{@render settingsShell()}
{:else}
{@render compactSettings()}
{/if}
</div>
</div>
</div>
{/if}
<style>
.settings-content {
position: absolute;
top: 0;
right: 0;
width: 100%;
height: 100%;
}
.settings-panel {
width: min(384px, calc(100vw - 20px));
height: min(600px, calc(100vh - 95px));
top: min(80px, 10vh);
right: 10px;
border-radius: 1rem;
transform-origin: 70% 0;
}
.settings-panel--expanded {
border-radius: 0.75rem;
transform-origin: center;
width: min(1180px, 96vw);
height: min(860px, 92vh);
top: calc((100% - min(860px, 92vh)) / 2);
right: calc((100% - min(1180px, 96vw)) / 2);
}
.settings-backdrop--motion {
transition: background-color 200ms ease;
}
@media (prefers-reduced-motion: reduce) {
.settings-backdrop--motion {
transition: none;
}
}
</style>
{#if showColourPicker && ColourPickerComponent}
<ColourPickerComponent
hidePicker={() => {
@@ -89,9 +89,9 @@
{/if}
{#if plugin.disableToggle}
<div class="flex justify-between items-center px-5 py-4 {perfPaused ? 'pointer-events-none' : ''}">
<div class="flex justify-between items-center px-4 py-3 {perfPaused ? 'pointer-events-none' : ''}">
<div class="pr-4">
<h2 class="flex gap-2 items-center text-xl font-bold">
<h2 class="flex gap-2 items-center text-sm font-bold">
Enable {plugin.name}
{#if plugin.beta}
<span
@@ -101,7 +101,7 @@
</span>
{/if}
</h2>
<p class="text-base text-zinc-600 dark:text-zinc-300">{plugin.description}</p>
<p class="text-xs text-zinc-600 dark:text-zinc-300">{plugin.description}</p>
</div>
<div>
<Switch
@@ -128,10 +128,10 @@
{#if !perfPaused && (!plugin.disableToggle || ((pluginSettingsStore.values[plugin.pluginId]?.enabled as boolean | undefined) ?? true))}
{#each Object.entries(plugin.settings) as [key, setting] (key)}
{#if key !== "enabled" && !(key === "useCloudPfp" && !cloudState.isLoggedIn)}
<div class="flex justify-between items-center px-5 py-4">
<div class="flex justify-between items-center px-4 py-3">
<div class="pr-4">
<h2 class="text-xl font-bold">{setting.title || key}</h2>
<p class="text-base text-zinc-600 dark:text-zinc-300">{setting.description || ""}</p>
<h2 class="text-sm font-bold">{setting.title || key}</h2>
<p class="text-xs text-zinc-600 dark:text-zinc-300">{setting.description || ""}</p>
</div>
<div>
{#if setting.type === "boolean"}
@@ -14,10 +14,10 @@
</script>
{#if visible}
<div class="flex justify-between items-center px-5 py-5">
<div class="pr-5">
<h2 class="text-xl font-bold">{title}</h2>
<p class="text-base text-zinc-600 dark:text-zinc-300">{description}</p>
<div class="flex justify-between items-center px-4 py-3">
<div class="pr-4">
<h2 class="text-sm font-bold">{title}</h2>
<p class="text-xs text-zinc-600 dark:text-zinc-300">{description}</p>
</div>
<div class="shrink-0">
<Component {...props} />
@@ -61,13 +61,13 @@
class="p-1 my-1 from-white to-zinc-100 bg-gradient-to-br rounded-xl border shadow-sm border-zinc-200/50 dark:border-zinc-700/40 dark:to-zinc-900/50 dark:from-zinc-900/40"
>
{#if showCloudCardHeader}
<div class="flex justify-between items-center px-5 py-4">
<div class="flex justify-between items-center px-4 py-3">
<div class="pr-4">
<h2 class="text-xl font-bold">BetterSEQTA Cloud</h2>
<p class="text-base text-zinc-600 dark:text-zinc-300">Account & sync</p>
<h2 class="text-sm font-bold">BetterSEQTA Cloud</h2>
<p class="text-xs text-zinc-600 dark:text-zinc-300">Account & sync</p>
</div>
<div>
<CloudHeader alwaysShowUserName onClick={showCloudPanel} />
<CloudHeader compact alwaysShowUserName onClick={showCloudPanel} />
</div>
</div>
{/if}
@@ -1,7 +1,6 @@
<script lang="ts">
import Switch from "@/interface/components/Switch.svelte";
import Button from "@/interface/components/Button.svelte";
import SettingRow from "../SettingRow.svelte";
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
import { showPrivacyNotification } from "@/seqta/utils/Openers/OpenPrivacyNotification";
import { showThemeOfTheMonthPopupNow } from "@/seqta/utils/Openers/OpenThemeOfTheMonthPopup";
@@ -52,18 +51,6 @@
}
</script>
<SettingRow
title="BetterSEQTA+"
description="Enables BetterSEQTA+ features"
id={12}
Component={Switch}
{searchQuery}
props={{
state: $settingsState.onoff,
onChange: (isOn: boolean) => (settingsState.onoff = isOn),
}}
/>
{#if $settingsState.devMode && matchesSearch(
searchQuery,
"Developer Mode",
@@ -80,10 +67,10 @@
<div
class="flex-col p-1 my-1 bg-gradient-to-br from-white rounded-xl border shadow-sm to-zinc-100 border-zinc-200/50 dark:border-zinc-700/40 dark:to-zinc-900/50 dark:from-zinc-900/40"
>
<div class="flex justify-between items-center px-5 py-4">
<div class="flex justify-between items-center px-4 py-3">
<div class="pr-4">
<h2 class="text-xl font-bold">Developer Mode</h2>
<p class="text-base text-zinc-600 dark:text-zinc-300">
<h2 class="text-sm font-bold">Developer Mode</h2>
<p class="text-xs text-zinc-600 dark:text-zinc-300">
Enables developer mode, allowing you to test new features and changes.
</p>
</div>
@@ -94,10 +81,10 @@
/>
</div>
</div>
<div class="flex justify-between items-center px-5 py-4">
<div class="flex justify-between items-center px-4 py-3">
<div class="pr-4">
<h2 class="text-xl font-bold">Verbose logging</h2>
<p class="text-base text-zinc-600 dark:text-zinc-300">
<h2 class="text-sm font-bold">Verbose logging</h2>
<p class="text-xs text-zinc-600 dark:text-zinc-300">
Show diagnostic console output (indexer, theme manager, timetable colour patch, etc.)
</p>
</div>
@@ -108,10 +95,10 @@
/>
</div>
</div>
<div class="flex justify-between items-center px-5 py-4">
<div class="flex justify-between items-center px-4 py-3">
<div class="pr-4">
<h2 class="text-xl font-bold">Delay loading screen</h2>
<p class="text-base text-zinc-600 dark:text-zinc-300">
<h2 class="text-sm font-bold">Delay loading screen</h2>
<p class="text-xs text-zinc-600 dark:text-zinc-300">
Keep the loading overlay visible for 5 extra seconds so you can preview canvas variants.
</p>
</div>
@@ -122,10 +109,10 @@
/>
</div>
</div>
<div class="flex justify-between items-center px-5 py-4">
<div class="flex justify-between items-center px-4 py-3">
<div class="pr-4">
<h2 class="text-xl font-bold">Sensitive Hider</h2>
<p class="text-base text-zinc-600 dark:text-zinc-300">
<h2 class="text-sm font-bold">Sensitive Hider</h2>
<p class="text-xs text-zinc-600 dark:text-zinc-300">
Replace sensitive content with mock data
</p>
</div>
@@ -136,10 +123,10 @@
/>
</div>
</div>
<div class="flex justify-between items-center px-5 py-4">
<div class="flex justify-between items-center px-4 py-3">
<div class="pr-4">
<h2 class="text-xl font-bold">Mock Notices</h2>
<p class="text-base text-zinc-600 dark:text-zinc-300">
<h2 class="text-sm font-bold">Mock Notices</h2>
<p class="text-xs text-zinc-600 dark:text-zinc-300">
Use fake notice data on homepage instead of real data
</p>
</div>
@@ -150,10 +137,10 @@
/>
</div>
</div>
<div class="flex justify-between items-center px-5 py-4">
<div class="flex justify-between items-center px-4 py-3">
<div class="pr-4">
<h2 class="text-xl font-bold">Show Privacy Notification</h2>
<p class="text-base text-zinc-600 dark:text-zinc-300">
<h2 class="text-sm font-bold">Show Privacy Notification</h2>
<p class="text-xs text-zinc-600 dark:text-zinc-300">
Show the privacy notification popup on next page load
</p>
</div>
@@ -170,10 +157,10 @@
/>
</div>
</div>
<div class="flex justify-between items-center px-5 py-4">
<div class="flex justify-between items-center px-4 py-3">
<div class="pr-4">
<h2 class="text-xl font-bold">Show Theme of the Month</h2>
<p class="text-base text-zinc-600 dark:text-zinc-300">
<h2 class="text-sm font-bold">Show Theme of the Month</h2>
<p class="text-xs text-zinc-600 dark:text-zinc-300">
Fetch and show the current month's popup now (ignores dismissed state)
</p>
</div>
@@ -188,10 +175,10 @@
/>
</div>
</div>
<div class="flex justify-between items-center px-5 py-4">
<div class="flex justify-between items-center px-4 py-3">
<div class="pr-4">
<h2 class="text-xl font-bold">Export cloud settings JSON</h2>
<p class="text-base text-zinc-600 dark:text-zinc-300">
<h2 class="text-sm font-bold">Export cloud settings JSON</h2>
<p class="text-xs text-zinc-600 dark:text-zinc-300">
Download the same payload as cloud sync (OAuth tokens stripped). For debugging and server
testing.
</p>
@@ -203,14 +190,14 @@
<div class="flex flex-col gap-2 px-4 py-3">
<div class="flex justify-between items-start gap-3">
<div class="pr-4">
<h2 class="text-xl font-bold">API Base URL (session only)</h2>
<h2 class="text-sm font-bold">API Base URL (session only)</h2>
{#if isExtensionDevBuild}
<p class="text-base text-zinc-600 dark:text-zinc-300">
<p class="text-xs text-zinc-600 dark:text-zinc-300">
Extension dev builds always use production ({PRODUCTION_API_BASE}) for the theme store,
community submit, and related APIs. Build a release package to test a staging host override.
</p>
{:else}
<p class="text-base text-zinc-600 dark:text-zinc-300">
<p class="text-xs text-zinc-600 dark:text-zinc-300">
Override the content API host for this browser session. Cleared on restart. Affects
themes, theme of the month, and other server-driven content.
</p>
@@ -239,8 +226,8 @@
</div>
<div class="flex flex-col gap-2 px-4 py-3">
<div>
<h2 class="text-xl font-bold">GitHub latest version override</h2>
<p class="text-base text-zinc-600 dark:text-zinc-300">
<h2 class="text-sm font-bold">GitHub latest version override</h2>
<p class="text-xs text-zinc-600 dark:text-zinc-300">
Pretend a newer GitHub release exists to test the update badge. Only applies when dev mode
is on.
</p>
@@ -49,10 +49,10 @@
<div
class="p-1 my-1 from-white to-zinc-100 bg-gradient-to-br rounded-xl border shadow-sm border-zinc-200/50 dark:border-zinc-700/40 dark:to-zinc-900/50 dark:from-zinc-900/40"
>
<div class="flex justify-between items-center px-5 py-4">
<div class="flex justify-between items-center px-4 py-3">
<div class="pr-4">
<h2 class="text-xl font-bold">Adaptive Theme Colour</h2>
<p class="text-base text-zinc-600 dark:text-zinc-300">
<h2 class="text-sm font-bold">Adaptive Theme Colour</h2>
<p class="text-xs text-zinc-600 dark:text-zinc-300">
Change the theme colour based on the current class (e.g. when viewing a course or
assessments page)
</p>
@@ -66,11 +66,11 @@
</div>
{#if $settingsState.adaptiveThemeColour}
<div
class="flex justify-between items-center px-5 py-4 pl-7 border-t border-zinc-100 dark:border-zinc-700/50"
class="flex justify-between items-center px-4 py-3 pl-6 border-t border-zinc-100 dark:border-zinc-700/50"
>
<div class="pr-4">
<h2 class="text-xl font-bold">Soft Gradient</h2>
<p class="text-base text-zinc-600 dark:text-zinc-300">
<h2 class="text-sm font-bold">Soft Gradient</h2>
<p class="text-xs text-zinc-600 dark:text-zinc-300">
Use a soft gradient instead of a solid colour when viewing a class
</p>
</div>
@@ -82,11 +82,11 @@
</div>
</div>
<div
class="flex justify-between items-center px-5 py-4 pl-7 border-t border-zinc-100 dark:border-zinc-700/50"
class="flex justify-between items-center px-4 py-3 pl-6 border-t border-zinc-100 dark:border-zinc-700/50"
>
<div class="pr-4">
<h2 class="text-xl font-bold">Smooth colour transition</h2>
<p class="text-base text-zinc-600 dark:text-zinc-300">
<h2 class="text-sm font-bold">Smooth colour transition</h2>
<p class="text-xs text-zinc-600 dark:text-zinc-300">
Ease between class/subject colours when navigating instead of switching instantly
</p>
</div>
@@ -17,6 +17,16 @@
const isEngage = isSeqtaEngageExperience();
const generalOptions = $derived([
{
title: "BetterSEQTA+",
description: "Enables BetterSEQTA+ features",
id: 12,
Component: Switch,
props: {
state: $settingsState.onoff,
onChange: (isOn: boolean) => (settingsState.onoff = isOn),
},
},
{
title: "Performance Mode",
description:
@@ -170,20 +180,20 @@
<div
class="p-1 my-1 from-white to-zinc-100 bg-gradient-to-br rounded-xl border shadow-sm border-zinc-200/50 dark:border-zinc-700/40 dark:to-zinc-900/50 dark:from-zinc-900/40"
>
<div class="flex justify-between items-center px-5 py-4">
<div class="flex justify-between items-center px-4 py-3">
<div class="pr-4">
<h2 class="text-xl font-bold">Home Page Assessments</h2>
<p class="text-base text-zinc-600 dark:text-zinc-300">
<h2 class="text-sm font-bold">Home Page Assessments</h2>
<p class="text-xs text-zinc-600 dark:text-zinc-300">
Limit upcoming assessments shown on the home page by subject
</p>
</div>
</div>
<div
class="flex justify-between items-center px-5 py-4 pl-7 border-t border-zinc-100 dark:border-zinc-700/50"
class="flex justify-between items-center px-4 py-3 pl-6 border-t border-zinc-100 dark:border-zinc-700/50"
>
<div class="pr-4">
<h2 class="text-xl font-bold">Include Past Assessments</h2>
<p class="text-base text-zinc-600 dark:text-zinc-300">
<h2 class="text-sm font-bold">Include Past Assessments</h2>
<p class="text-xs text-zinc-600 dark:text-zinc-300">
Show past-due assessments from the upcoming list, matching the Assessments page
</p>
</div>
@@ -195,11 +205,11 @@
</div>
</div>
<div
class="flex justify-between items-center px-5 py-4 pl-7 border-t border-zinc-100 dark:border-zinc-700/50"
class="flex justify-between items-center px-4 py-3 pl-6 border-t border-zinc-100 dark:border-zinc-700/50"
>
<div class="pr-4">
<h2 class="text-xl font-bold">Maximum Subjects</h2>
<p class="text-base text-zinc-600 dark:text-zinc-300">
<h2 class="text-sm font-bold">Maximum Subjects</h2>
<p class="text-xs text-zinc-600 dark:text-zinc-300">
Number of subjects to include, ordered by soonest due date
</p>
</div>
@@ -217,11 +227,11 @@
/>
</div>
<div
class="flex justify-between items-center px-5 py-4 pl-7 border-t border-zinc-100 dark:border-zinc-700/50"
class="flex justify-between items-center px-4 py-3 pl-6 border-t border-zinc-100 dark:border-zinc-700/50"
>
<div class="pr-4">
<h2 class="text-xl font-bold">Maximum Assessments per Subject</h2>
<p class="text-base text-zinc-600 dark:text-zinc-300">
<h2 class="text-sm font-bold">Maximum Assessments per Subject</h2>
<p class="text-xs text-zinc-600 dark:text-zinc-300">
Assessments shown for each included subject
</p>
</div>
@@ -3,6 +3,16 @@ import { buildThemeBuilderCss } from "./themeBuilderDraft";
import { getFontPreset } from "@/seqta/ui/fonts/presets";
describe("buildSimpleTheme", () => {
it("paints the tint above an opaque photo when blur is disabled", () => {
const css = buildThemeBuilderCss(
getFontPreset("inter"),
["theme-bg-0"],
{ accentColor: "#00f", overlayOpacity: 0.5, backgroundBlurPx: 0 },
);
const backgroundLayers = css.match(/background-image: (.*) !important;/)?.[1];
expect(backgroundLayers).toMatch(/^linear-gradient\(.*\), var\(--theme-bg-0\)$/);
});
it("builds CSS with font import and image variables", () => {
const css = buildThemeBuilderCss(
getFontPreset("inter"),
+2 -3
View File
@@ -30,7 +30,7 @@ export function buildThemeBuilderCss(
imageVariables: string[],
draft: Pick<
ThemeBuilderDraft,
"accentColor" | "gradientEnd" | "gradientAngle" | "backgroundBlurPx" | "overlayOpacity"
"accentColor" | "gradientEnd" | "gradientAngle" | "backgroundBlurPx" | "overlayOpacity" | "customCssExtra"
>,
): string {
const importLine = font.googleUrl ? `@import url("${font.googleUrl}");\n` : "";
@@ -77,9 +77,8 @@ export function buildThemeBuilderCss(
background-attachment: fixed !important;
}`);
} else {
const bgLayers: string[] = [];
const bgLayers: string[] = [gradientLayer];
if (imageLayer) bgLayers.push(imageLayer);
bgLayers.push(gradientLayer);
rules.push(`#container {
background-image: ${bgLayers.join(", ")} !important;
background-size: cover !important;
@@ -1,7 +1,11 @@
<script lang="ts">
import { onMount, onDestroy } from "svelte";
import { fade } from "svelte/transition";
import type { Assessment } from "./types";
import type {
AnalyticsClassGroup,
AnalyticsClassOption,
Assessment,
} from "./types";
import {
loadGradeAnalytics,
syncGradeAnalytics,
@@ -13,6 +17,8 @@
import AnalyticsBarChart from "./AnalyticsBarChart.svelte";
import AssessmentTable from "./AssessmentTable.svelte";
import GradeRangeSlider from "./GradeRangeSlider.svelte";
import ClassGroupsPanel from "./ClassGroupsPanel.svelte";
import GradeInferencePanel from "./GradeInferencePanel.svelte";
import {
defaultCustomTimeRange,
filterAssessmentsByTimeRange,
@@ -22,13 +28,11 @@
type TimeRange,
} from "./timeRange";
import { openAnalyticsPrivacyPopup } from "./openAnalyticsPrivacyPopup";
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
import { animationsEnabled } from "@/seqta/utils/performanceMode";
import ClassGroupsPanel from "./ClassGroupsPanel.svelte";
import GradeInferencePanel from "./GradeInferencePanel.svelte";
import type { AnalyticsClassGroup, AnalyticsClassOption } from "./types";
import type { AnalyticsGradeInferenceSettings } from "./gradeInferenceSettings";
import { DEFAULT_ANALYTICS_GRADE_INFERENCE } from "./gradeInferenceSettings";
import {
DEFAULT_ANALYTICS_GRADE_INFERENCE,
type AnalyticsGradeInferenceSettings,
} from "./gradeInferenceSettings";
import {
loadClassGroups,
loadGradeInferenceSettings,
@@ -38,6 +42,11 @@
let { simpleMode = false } = $props<{ simpleMode?: boolean }>();
const LOAD_ERROR =
"Unable to load analytics. Check your connection, then select Refresh data.";
const SYNC_ERROR_WITH_DATA =
"Unable to sync. Showing saved data. Select Refresh data to try again.";
let analyticsData: Assessment[] | null = $state(null);
let loading = $state(true);
let syncing = $state(false);
@@ -61,14 +70,20 @@
DEFAULT_ANALYTICS_GRADE_INFERENCE,
);
let timeRangeTrigger: HTMLButtonElement | null = $state(null);
let subjectsTrigger: HTMLButtonElement | null = $state(null);
let timestampInterval: ReturnType<typeof setInterval> | null = null;
let contentReady = $state(false);
const fadeDuration = $derived(animationsEnabled() ? 200 : 0);
const formattedTimestamp = $derived(() => {
if (!lastUpdated) return "";
const showLoading = $derived(loading || !contentReady);
const hasData = $derived(!!analyticsData?.length);
const totalCount = $derived(analyticsData?.length ?? 0);
const formattedTimestamp = $derived.by(() => {
timestampRefresh;
return formatLastUpdated(lastUpdated);
return lastUpdated ? formatLastUpdated(lastUpdated) : "";
});
const activeClassGroup = $derived(
@@ -81,14 +96,15 @@
activeClassGroup && !showSubjectTrends ? activeClassGroup.name : undefined,
);
const uniqueSubjects = $derived(() => {
const uniqueSubjects = $derived.by(() => {
if (!analyticsData) return [];
return [...new Set(analyticsData.map((a) => a.subject))].sort();
});
const filteredData = $derived(() => {
const filteredData = $derived.by(() => {
if (!analyticsData) return [];
const [minG, maxG] = gradeRange;
const query = filterSearch.toLowerCase();
return analyticsData.filter((a) => {
if (activeClassKeys.length) {
const key = `${a.programmeID}-${a.metaclassID}`;
@@ -100,9 +116,9 @@
if (a.finalGrade < minG || a.finalGrade > maxG) return false;
}
if (
filterSearch &&
!a.title.toLowerCase().includes(filterSearch.toLowerCase()) &&
!a.subject.toLowerCase().includes(filterSearch.toLowerCase())
query &&
!a.title.toLowerCase().includes(query) &&
!a.subject.toLowerCase().includes(query)
) {
return false;
}
@@ -110,28 +126,58 @@
});
});
const timeScopedData = $derived(() =>
filterAssessmentsByTimeRange(filteredData(), timeRange, customTimeRange),
const timeScopedData = $derived(
filterAssessmentsByTimeRange(filteredData, timeRange, customTimeRange),
);
const gradedFiltered = $derived(() =>
timeScopedData().filter((a) => a.finalGrade !== undefined),
const gradedFiltered = $derived(
timeScopedData.filter((a) => a.finalGrade !== undefined),
);
const statsAverage = $derived.by(() => {
const graded = gradedFiltered();
if (!graded.length) return null;
const sum = graded.reduce((acc, a) => acc + (a.finalGrade ?? 0), 0);
return Math.round((sum / graded.length) * 10) / 10;
if (!gradedFiltered.length) return null;
const sum = gradedFiltered.reduce((acc, a) => acc + (a.finalGrade ?? 0), 0);
return Math.round((sum / gradedFiltered.length) * 10) / 10;
});
const statsSubjectCount = $derived(
new Set(timeScopedData().map((a) => a.subject)).size,
new Set(timeScopedData.map((a) => a.subject)).size,
);
const timeRangeLabel = $derived(getTimeRangeLabel(timeRange, customTimeRange));
const subjectsLabel = $derived.by(() => {
if (activeClassGroup) return activeClassGroup.name;
if (filterSubjects.length === 0) return "All subjects";
if (filterSubjects.length === 1) return filterSubjects[0];
return `${filterSubjects.length} selected`;
});
const hasActiveFilters = $derived(
!!(
filterSubjects.length ||
activeClassGroupId ||
filterSearch ||
gradeRange[0] !== 0 ||
gradeRange[1] !== 100
),
);
const resultsSummary = $derived.by(() => {
const shown = `${timeScopedData.length} of ${totalCount} assessments shown`;
return gradedFiltered.length !== timeScopedData.length
? `${shown} (${gradedFiltered.length} with grades)`
: shown;
});
const statusMessage = $derived.by(() => {
if (loading) return "Loading analytics…";
if (syncing) return "Syncing analytics…";
return hasData ? resultsSummary : "";
});
function formatLastUpdated(date: Date): string {
const now = new Date();
const diffMs = now.getTime() - date.getTime();
const diffMs = Date.now() - date.getTime();
const diffMins = Math.floor(diffMs / 60000);
const diffHours = Math.floor(diffMs / 3600000);
const diffDays = Math.floor(diffMs / 86400000);
@@ -152,8 +198,7 @@
await loadClassCatalog(result.assessments);
} catch (e) {
console.error("[BetterSEQTA+] Analytics sync failed:", e);
error =
"Failed to sync analytics data. Showing cached data if available.";
error = analyticsData?.length ? SYNC_ERROR_WITH_DATA : LOAD_ERROR;
} finally {
syncing = false;
}
@@ -166,16 +211,6 @@
activeClassGroupId = null;
}
function hasActiveFilters() {
return !!(
filterSubjects.length ||
activeClassGroupId ||
filterSearch ||
gradeRange[0] !== 0 ||
gradeRange[1] !== 100
);
}
function toggleSubject(subject: string) {
activeClassGroupId = null;
if (filterSubjects.includes(subject)) {
@@ -185,6 +220,13 @@
}
}
function selectAllSubjects() {
filterSubjects = [];
activeClassGroupId = null;
showSubjectsDropdown = false;
subjectsTrigger?.focus();
}
function selectClassGroup(group: AnalyticsClassGroup | null) {
activeClassGroupId = group?.id ?? null;
if (group) {
@@ -213,7 +255,15 @@
classCatalog = await loadAnalyticsClassCatalog(assessments);
}
const timeRangeLabel = $derived(() => getTimeRangeLabel(timeRange, customTimeRange));
function toggleTimeRangeDropdown() {
showSubjectsDropdown = false;
showTimeRangeDropdown = !showTimeRangeDropdown;
}
function toggleSubjectsDropdown() {
showTimeRangeDropdown = false;
showSubjectsDropdown = !showSubjectsDropdown;
}
function closeToolbarDropdowns() {
showSubjectsDropdown = false;
@@ -228,10 +278,22 @@
});
}
function handleWindowKeydown(event: KeyboardEvent) {
if (event.key !== "Escape") return;
if (showTimeRangeDropdown) {
showTimeRangeDropdown = false;
timeRangeTrigger?.focus();
} else if (showSubjectsDropdown) {
showSubjectsDropdown = false;
subjectsTrigger?.focus();
}
}
function selectTimeRange(value: TimeRange) {
timeRange = value;
if (value === "custom") customTimeRange = defaultCustomTimeRange();
showTimeRangeDropdown = false;
timeRangeTrigger?.focus();
}
onMount(async () => {
@@ -249,14 +311,18 @@
studentId = id;
classGroups = await loadClassGroups(location.origin, id);
gradeInference = await loadGradeInferenceSettings(location.origin, id);
await loadClassCatalog(result.assessments);
} catch {
} catch (e) {
console.warn(
"[BetterSEQTA+] Analytics student settings unavailable; class groups will not be saved:",
e,
);
classGroups = [];
classCatalog = await loadAnalyticsClassCatalog(result.assessments);
}
await loadClassCatalog(result.assessments);
} catch (e) {
console.error("[BetterSEQTA+] Failed to load analytics:", e);
analyticsData = [];
error = LOAD_ERROR;
} finally {
loading = false;
requestAnimationFrame(() => {
@@ -283,72 +349,34 @@
closeToolbarDropdowns();
}
}}
onkeydown={handleWindowKeydown}
/>
<div class="bsplus-analytics-root">
{#if error}
<p class="bsplus-analytics-sr-only" role="status">{statusMessage}</p>
{#if error && hasData}
<p class="bsplus-analytics-alert bsplus-analytics-animate" role="alert" transition:fade={{ duration: fadeDuration }}>
{error}
</p>
{/if}
{#snippet sidebarTitle()}
<header class="bsplus-analytics-sidebar-head bsplus-analytics-animate">
<h1>
Analytics
<div class="bsplus-analytics-layout bsplus-analytics-animate">
<aside class="bsplus-analytics-filters" aria-label="Analytics controls">
<header class="bsplus-analytics-sidebar-head bsplus-analytics-animate">
<h1>Analytics</h1>
{#if syncing}
<span class="bsplus-analytics-badge">
<span class="bsplus-analytics-badge-dot" aria-hidden="true"></span>
Syncing
</span>
{/if}
</h1>
</header>
{/snippet}
{#snippet sidebarActions()}
<div class="bsplus-analytics-sidebar-actions">
{#if lastUpdated}
<p class="bsplus-analytics-meta">Last updated: {formattedTimestamp()}</p>
{/if}
<button
type="button"
class="bsplus-analytics-btn bsplus-analytics-btn-privacy"
onclick={() => openAnalyticsPrivacyPopup()}
>
Privacy notice
</button>
<button
type="button"
class="bsplus-analytics-btn bsplus-analytics-btn-primary"
disabled={syncing}
onclick={() => runSync()}
>
{syncing ? "Syncing…" : "Refresh data"}
</button>
</div>
{/snippet}
{#if loading || !contentReady}
<div class="bsplus-analytics-layout bsplus-analytics-animate">
<aside class="bsplus-analytics-filters" aria-label="Analytics">
{@render sidebarTitle()}
{@render sidebarActions()}
</aside>
<div class="bsplus-analytics-main">
<div class="bsplus-analytics-loading">
<div class="bsplus-analytics-spinner" aria-label="Loading analytics"></div>
</div>
</div>
</div>
{:else if analyticsData && analyticsData.length > 0}
<div class="bsplus-analytics-layout bsplus-analytics-animate bsplus-analytics-delay-1">
<aside class="bsplus-analytics-filters" aria-label="Filters">
{@render sidebarTitle()}
</header>
{#if !showLoading && hasData}
<div class="bsplus-analytics-filters-head">
<h2 class="bsplus-analytics-filters-title">Filters</h2>
{#if hasActiveFilters()}
{#if hasActiveFilters}
<button
type="button"
class="bsplus-analytics-filters-clear"
@@ -359,38 +387,33 @@
{/if}
</div>
<div class="bsplus-analytics-filter-group" data-analytics-dropdown>
<span class="bsplus-analytics-field-label">Time period</span>
<div class="bsplus-analytics-filter-group">
<span class="bsplus-analytics-field-label" id="bsplus-analytics-time-label">Time period</span>
<div class="bsplus-analytics-dropdown" data-analytics-dropdown>
<button
bind:this={timeRangeTrigger}
type="button"
id="bsplus-analytics-time-trigger"
class="bsplus-analytics-dropdown-trigger"
onclick={(e) => {
e.stopPropagation();
showSubjectsDropdown = false;
showTimeRangeDropdown = !showTimeRangeDropdown;
}}
aria-expanded={showTimeRangeDropdown}
aria-haspopup="listbox"
aria-label="Time period for analytics"
aria-controls="bsplus-analytics-time-menu"
aria-labelledby="bsplus-analytics-time-label bsplus-analytics-time-trigger"
onclick={toggleTimeRangeDropdown}
>
{timeRangeLabel()}
{timeRangeLabel}
</button>
{#if showTimeRangeDropdown}
<div class="bsplus-analytics-dropdown-menu" role="listbox">
<div id="bsplus-analytics-time-menu" class="bsplus-analytics-dropdown-menu">
{#each TIME_RANGE_OPTIONS as option (option.value)}
{@const selected = timeRange === option.value}
<button
type="button"
class="bsplus-analytics-dropdown-item"
class:is-selected={selected}
role="option"
aria-selected={selected}
aria-pressed={selected}
onclick={() => selectTimeRange(option.value)}
>
<span class="bsplus-analytics-dropdown-check"
>{selected ? "✓" : ""}</span
>
<span class="bsplus-analytics-dropdown-check" aria-hidden="true">{selected ? "✓" : ""}</span>
<span>{option.label}</span>
</button>
{/each}
@@ -398,75 +421,67 @@
{/if}
</div>
{#if timeRange === "custom"}
<input
type="date"
class="bsplus-analytics-input"
bind:value={customTimeRange.from}
max={customTimeRange.to}
aria-label="Custom range start date"
/>
<input
type="date"
class="bsplus-analytics-input"
bind:value={customTimeRange.to}
min={customTimeRange.from}
aria-label="Custom range end date"
/>
<div class="bsplus-analytics-date-range">
<label class="bsplus-analytics-date-field">
<span class="bsplus-analytics-field-label">From</span>
<input
type="date"
class="bsplus-analytics-input"
bind:value={customTimeRange.from}
max={customTimeRange.to}
/>
</label>
<label class="bsplus-analytics-date-field">
<span class="bsplus-analytics-field-label">To</span>
<input
type="date"
class="bsplus-analytics-input"
bind:value={customTimeRange.to}
min={customTimeRange.from}
/>
</label>
</div>
{/if}
</div>
<div class="bsplus-analytics-filter-group" data-analytics-dropdown>
<span class="bsplus-analytics-field-label">Subjects</span>
<div class="bsplus-analytics-filter-group">
<span class="bsplus-analytics-field-label" id="bsplus-analytics-subjects-label">Subjects</span>
<div class="bsplus-analytics-dropdown" data-analytics-dropdown>
<button
bind:this={subjectsTrigger}
type="button"
id="bsplus-analytics-subjects-trigger"
class="bsplus-analytics-dropdown-trigger"
onclick={(e) => {
e.stopPropagation();
showTimeRangeDropdown = false;
showSubjectsDropdown = !showSubjectsDropdown;
}}
aria-expanded={showSubjectsDropdown}
aria-haspopup="listbox"
aria-controls="bsplus-analytics-subjects-menu"
aria-labelledby="bsplus-analytics-subjects-label bsplus-analytics-subjects-trigger"
onclick={toggleSubjectsDropdown}
>
{#if !activeClassGroup && filterSubjects.length === 0}
All subjects
{:else if activeClassGroup}
{activeClassGroup.name}
{:else if filterSubjects.length === 1}
{filterSubjects[0]}
{:else}
{filterSubjects.length} selected
{/if}
{subjectsLabel}
</button>
{#if showSubjectsDropdown}
<div class="bsplus-analytics-dropdown-menu" role="listbox">
{@const allSelected = !activeClassGroup && filterSubjects.length === 0}
<div id="bsplus-analytics-subjects-menu" class="bsplus-analytics-dropdown-menu">
<button
type="button"
class="bsplus-analytics-dropdown-item"
class:is-selected={!activeClassGroup && filterSubjects.length === 0}
onclick={() => {
filterSubjects = [];
activeClassGroupId = null;
showSubjectsDropdown = false;
}}
class:is-selected={allSelected}
aria-pressed={allSelected}
onclick={selectAllSubjects}
>
<span class="bsplus-analytics-dropdown-check"
>{!activeClassGroup && filterSubjects.length === 0 ? "✓" : ""}</span
>
All subjects
<span class="bsplus-analytics-dropdown-check" aria-hidden="true">{allSelected ? "✓" : ""}</span>
<span>All subjects</span>
</button>
{#each uniqueSubjects() as subject}
{#each uniqueSubjects as subject (subject)}
{@const selected = filterSubjects.includes(subject)}
<button
type="button"
class="bsplus-analytics-dropdown-item"
class:is-selected={selected}
aria-pressed={selected}
onclick={() => toggleSubject(subject)}
>
<span class="bsplus-analytics-dropdown-check"
>{selected ? "✓" : ""}</span
>
<span class="bsplus-analytics-dropdown-check" aria-hidden="true">{selected ? "✓" : ""}</span>
<span class="bsplus-analytics-filter-subject-name">{subject}</span>
</button>
{/each}
@@ -476,24 +491,25 @@
</div>
{#if !simpleMode}
<ClassGroupsPanel
classOptions={classCatalog}
groups={classGroups}
activeGroupId={activeClassGroupId}
onSelectGroup={selectClassGroup}
onSaveGroups={persistClassGroups}
/>
<ClassGroupsPanel
classOptions={classCatalog}
groups={classGroups}
activeGroupId={activeClassGroupId}
onSelectGroup={selectClassGroup}
onSaveGroups={persistClassGroups}
/>
<GradeInferencePanel
settings={gradeInference}
onSave={persistGradeInference}
disabled={syncing}
/>
<GradeInferencePanel
settings={gradeInference}
onSave={persistGradeInference}
disabled={syncing}
/>
{/if}
<div class="bsplus-analytics-filter-group">
<span class="bsplus-analytics-field-label">Search</span>
<label class="bsplus-analytics-field-label" for="bsplus-analytics-search">Search</label>
<input
id="bsplus-analytics-search"
type="search"
class="bsplus-analytics-input"
bind:value={filterSearch}
@@ -502,34 +518,64 @@
</div>
{#if !simpleMode}
<div class="bsplus-analytics-filter-group">
<span class="bsplus-analytics-field-label">Grade range</span>
<GradeRangeSlider bind:value={gradeRange} />
</div>
<div
class="bsplus-analytics-filter-group"
role="group"
aria-labelledby="bsplus-analytics-grade-label"
>
<span class="bsplus-analytics-field-label" id="bsplus-analytics-grade-label">Grade range</span>
<GradeRangeSlider bind:value={gradeRange} />
</div>
<div class="bsplus-analytics-filter-group">
<label class="bsplus-analytics-checkbox">
<input type="checkbox" bind:checked={showSubjectTrends} />
<span class="bsplus-analytics-checkmark" aria-hidden="true"></span>
<span>Per-subject trends</span>
</label>
</div>
<div class="bsplus-analytics-filter-group">
<label class="bsplus-analytics-checkbox">
<input type="checkbox" bind:checked={showSubjectTrends} />
<span class="bsplus-analytics-checkmark" aria-hidden="true"></span>
<span>Per-subject trends</span>
</label>
</div>
{/if}
{/if}
{@render sidebarActions()}
</aside>
<div class="bsplus-analytics-sidebar-actions">
{#if lastUpdated}
<p class="bsplus-analytics-meta">Last updated: {formattedTimestamp}</p>
{/if}
<button
type="button"
class="bsplus-analytics-btn bsplus-analytics-btn-privacy"
onclick={() => openAnalyticsPrivacyPopup()}
>
Privacy notice
</button>
<button
type="button"
class="bsplus-analytics-btn bsplus-analytics-btn-primary"
disabled={syncing}
onclick={() => runSync()}
>
{syncing ? "Syncing…" : "Refresh data"}
</button>
</div>
</aside>
<div class="bsplus-analytics-main">
<div class="bsplus-analytics-stats" aria-label="Summary statistics">
<div class="bsplus-analytics-main">
{#if showLoading}
<div class="bsplus-analytics-loading">
<div class="bsplus-analytics-spinner" aria-hidden="true"></div>
<p class="bsplus-analytics-meta">Loading analytics…</p>
</div>
{:else if hasData}
<div class="bsplus-analytics-stats bsplus-analytics-animate" aria-label="Summary statistics">
<div class="bsplus-analytics-stat">
<div class="bsplus-analytics-stat-label">Average grade</div>
<div class="bsplus-analytics-stat-value bsplus-analytics-stat-value-accent">
<div class="bsplus-analytics-stat-value">
{statsAverage !== null ? `${statsAverage}%` : "—"}
</div>
</div>
<div class="bsplus-analytics-stat">
<div class="bsplus-analytics-stat-label">Graded shown</div>
<div class="bsplus-analytics-stat-value">{gradedFiltered().length}</div>
<div class="bsplus-analytics-stat-value">{gradedFiltered.length}</div>
</div>
<div class="bsplus-analytics-stat">
<div class="bsplus-analytics-stat-label">Subjects</div>
@@ -537,52 +583,44 @@
</div>
</div>
<div class="bsplus-analytics-results">
<div class="bsplus-analytics-results bsplus-analytics-animate">
{#if !simpleMode}
<div class="bsplus-analytics-charts">
<div class="bsplus-analytics-chart-cell">
<AnalyticsAreaChart
data={gradedFiltered()}
{timeRange}
{customTimeRange}
showSubjectTrends={showSubjectTrends}
combinedLabel={combinedChartLabel}
/>
<div class="bsplus-analytics-charts">
<div class="bsplus-analytics-chart-cell">
<AnalyticsAreaChart
data={gradedFiltered}
{timeRange}
{customTimeRange}
{showSubjectTrends}
combinedLabel={combinedChartLabel}
/>
</div>
<div class="bsplus-analytics-chart-cell">
<AnalyticsBarChart data={gradedFiltered} {timeRange} {customTimeRange} />
</div>
</div>
<div class="bsplus-analytics-chart-cell">
<AnalyticsBarChart data={gradedFiltered()} {timeRange} {customTimeRange} />
</div>
</div>
{/if}
<AssessmentTable data={timeScopedData()} />
<AssessmentTable data={timeScopedData} />
</div>
<footer class="bsplus-analytics-footer">
<span>
{timeScopedData().length} of {analyticsData.length} assessments shown
{#if gradedFiltered().length !== timeScopedData().length}
({gradedFiltered().length} with grades)
{/if}
</span>
<footer class="bsplus-analytics-footer bsplus-analytics-animate">
<span>{resultsSummary}</span>
</footer>
</div>
</div>
{:else}
<div class="bsplus-analytics-layout bsplus-analytics-animate" transition:fade={{ duration: fadeDuration }}>
<aside class="bsplus-analytics-filters" aria-label="Analytics">
{@render sidebarTitle()}
{@render sidebarActions()}
</aside>
<div class="bsplus-analytics-main">
<div class="bsplus-analytics-empty">
<h2>No analytics data yet</h2>
<p>
Data syncs when you visit this page. Assessments with released marks will
appear here with trends and grade breakdowns.
</p>
{:else}
<div class="bsplus-analytics-empty bsplus-analytics-animate">
{#if error}
<h2>Analytics unavailable</h2>
<p role="alert">{error}</p>
{:else}
<h2>No analytics data yet</h2>
<p>
Data syncs when you visit this page. Assessments with released marks will
appear here with trends and grade breakdowns.
</p>
{/if}
</div>
</div>
{/if}
</div>
{/if}
</div>
</div>
@@ -21,7 +21,7 @@
let saving = $state(false);
$effect(() => {
draft = structuredClone(settings);
draft = $state.snapshot(settings);
});
function updateDraft(patch: Partial<AnalyticsGradeInferenceSettings>) {
@@ -0,0 +1,65 @@
import { afterEach, beforeEach, expect, it, jest } from "@jest/globals";
jest.mock("@/seqta/ui/AddBetterSEQTAElements", () => ({
getUserInfo: async () => ({ id: 12 }),
}));
jest.mock("@/seqta/utils/listeners/SettingsState", () => ({
settingsState: { hideSensitiveContent: false },
}));
jest.mock("@/seqta/ui/dev/hideSensitiveContent", () => ({
getMockGradeAnalyticsData: () => [],
}));
import { syncGradeAnalytics } from "./api";
import { loadAnalyticsCache, saveGradeInferenceSettings } from "./storage";
import { DEFAULT_ANALYTICS_GRADE_INFERENCE } from "./gradeInferenceSettings";
const origin = "https://school.seqta.com.au";
beforeEach(() => {
Object.defineProperty(globalThis, "location", {
configurable: true,
value: { origin },
});
});
afterEach(() => jest.restoreAllMocks());
it("removes cached custom rubric percentages when inference is disabled", async () => {
jest.spyOn(globalThis, "fetch").mockImplementation(async (url) =>
Response.json({
payload: String(url).includes("/load/subjects")
? []
: [
{
id: 1,
title: "Essay",
subject: "English",
due: "2026-07-20",
status: "MARKS_RELEASED",
results: { grade: "Highly accomplished" },
},
],
}),
);
await saveGradeInferenceSettings(origin, 12, {
...DEFAULT_ANALYTICS_GRADE_INFERENCE,
useCustomGradeBands: true,
gradeBands: [{ id: "band", label: "Highly accomplished", percent: 90 }],
});
expect((await syncGradeAnalytics()).assessments[0]).toMatchObject({
finalGrade: 90,
gradeSource: "customBand",
});
await saveGradeInferenceSettings(
origin,
12,
DEFAULT_ANALYTICS_GRADE_INFERENCE,
);
const refreshed = await syncGradeAnalytics();
expect(refreshed.assessments[0].finalGrade).toBeUndefined();
expect(refreshed.assessments[0].gradeSource).toBeUndefined();
expect(
(await loadAnalyticsCache(origin, 12))?.assessments[0].finalGrade,
).toBeUndefined();
});
+5 -1
View File
@@ -335,7 +335,11 @@ function mergeRawAssessments(
const letterGrade = extractLetterGrade(raw);
const existingItem = existingMap.get(id);
if (existingItem?.finalGrade !== undefined && finalGrade === undefined) {
if (
existingItem?.finalGrade !== undefined &&
finalGrade === undefined &&
(!existingItem.gradeSource || existingItem.gradeSource === "seqta")
) {
continue;
}
@@ -100,4 +100,17 @@ describe("resolveGradeFromAssessmentPayload", () => {
expect(resolved.finalGrade).toBe(72);
expect(resolved.source).toBe("customBand");
});
it("attributes unmatched conventional letters to the default scale", () => {
expect(
resolveGradeFromAssessmentPayload(
{ status: "MARKS_RELEASED", results: { grade: "A" } },
{
...DEFAULT_ANALYTICS_GRADE_INFERENCE,
useCustomGradeBands: true,
gradeBands: [{ id: "1", label: "Proficient", percent: 72 }],
},
),
).toMatchObject({ finalGrade: 85, source: "defaultLetter" });
});
});
@@ -37,7 +37,7 @@ function parseGradeString(value: unknown): string | undefined {
return s || undefined;
}
function percentFromGradeLabel(
function customPercentFromGradeLabel(
label: string | undefined,
settings: AnalyticsGradeInferenceSettings,
): number | undefined {
@@ -50,8 +50,6 @@ function percentFromGradeLabel(
}
}
}
const approx = approximatePercentFromLetterGrade(label);
if (approx !== undefined) return approx;
return undefined;
}
@@ -78,7 +76,9 @@ export function rollupPercentFromCriteria(
continue;
}
const letter = parseGradeString(row.results?.grade);
const mapped = percentFromGradeLabel(letter, settings);
const mapped =
customPercentFromGradeLabel(letter, settings) ??
approximatePercentFromLetterGrade(letter);
if (mapped !== undefined) {
parts.push({ percent: mapped, weight: criterionWeight(row) });
}
@@ -155,7 +155,7 @@ export function resolveGradeFromAssessmentPayload(
const letter = extractLetterFromPayload(assessment);
if (letter) {
const custom = settings.useCustomGradeBands
? percentFromGradeLabel(letter, settings)
? customPercentFromGradeLabel(letter, settings)
: undefined;
const finalGrade =
custom ?? approximatePercentFromLetterGrade(letter);
+77 -52
View File
@@ -23,7 +23,7 @@
--bsplus-analytics-text: var(--text-primary, #1a1a1a);
--bsplus-analytics-muted: color-mix(
in srgb,
var(--bsplus-analytics-text) 55%,
var(--bsplus-analytics-text) 65%,
transparent
);
--bsplus-analytics-border: color-mix(
@@ -35,6 +35,11 @@
--bsplus-analytics-shadow-hover: 0 8px 24px 8px rgba(0, 0, 0, 0.16);
/* Set on host via ui.ts from --better-main / user selectedColor */
--bsplus-analytics-accent: var(--better-main, #007bff);
--bsplus-analytics-accent-text: color-mix(
in srgb,
var(--bsplus-analytics-accent) 80%,
var(--bsplus-analytics-text)
);
--bsplus-analytics-chart-height: 300px;
--bsplus-analytics-stack-gap: 0.625rem;
/* Form controls — aligned with global SEQTA select styling */
@@ -103,7 +108,6 @@
.bsplus-analytics-animate {
opacity: 0;
animation: bsplus-analytics-fade-in-up 0.55s var(--bsplus-analytics-ease) both;
will-change: opacity, transform;
}
@media (prefers-reduced-motion: reduce) {
@@ -184,17 +188,17 @@
display: inline-flex;
align-items: center;
gap: 0.35rem;
margin-left: 0.75rem;
margin-inline-start: 0.75rem;
padding: 0.2rem 0.65rem;
border-radius: 999px;
font-size: 0.7rem;
font-size: 0.75rem;
font-weight: 600;
vertical-align: middle;
background: var(
--bsplus-analytics-accent-subtle,
color-mix(in srgb, var(--bsplus-analytics-accent) 18%, transparent)
);
color: var(--bsplus-analytics-accent);
color: var(--bsplus-analytics-text);
}
.bsplus-analytics-badge-dot {
@@ -212,6 +216,13 @@
}
}
@media (prefers-reduced-motion: reduce) {
.bsplus-analytics-badge-dot,
.bsplus-analytics-spinner {
animation: none;
}
}
/* ─── Buttons ─── */
.bsplus-analytics-btn {
display: inline-flex;
@@ -234,9 +245,8 @@
}
.bsplus-analytics-btn:focus-visible {
outline: none;
box-shadow: 0 0 0 3px
color-mix(in srgb, var(--bsplus-analytics-accent) 35%, transparent);
outline: 2px solid var(--bsplus-analytics-accent);
outline-offset: 2px;
}
.bsplus-analytics-btn-primary {
@@ -309,7 +319,7 @@
gap: 0.55rem;
min-width: 0;
position: relative;
padding-right: 0.375rem;
padding-inline-end: 0.375rem;
z-index: 4;
}
@@ -334,7 +344,7 @@
font-family: inherit;
font-size: 0.75rem;
font-weight: 600;
color: var(--bsplus-analytics-accent);
color: var(--bsplus-analytics-accent-text);
cursor: pointer;
white-space: nowrap;
text-decoration: underline;
@@ -351,9 +361,8 @@
}
.bsplus-analytics-filters-clear:focus-visible {
outline: none;
box-shadow: 0 0 0 3px
color-mix(in srgb, var(--bsplus-analytics-accent) 35%, transparent);
outline: 2px solid var(--bsplus-analytics-accent);
outline-offset: 2px;
border-radius: 4px;
}
@@ -382,18 +391,9 @@
padding-bottom: 0.15rem;
}
.bsplus-analytics-filter-group .bsplus-analytics-field-label {
font-size: 0.75rem;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.04em;
color: var(--bsplus-analytics-muted);
}
.bsplus-analytics-filter-subject-name {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
min-width: 0;
overflow-wrap: anywhere;
}
.bsplus-analytics-filters .bsplus-analytics-dropdown {
@@ -499,14 +499,11 @@
.bsplus-analytics-stat-value {
font-size: 1.125rem;
font-weight: 700;
font-variant-numeric: tabular-nums;
line-height: 1.2;
color: var(--bsplus-analytics-text);
}
.bsplus-analytics-stat-value-accent {
color: var(--bsplus-analytics-accent);
}
.bsplus-analytics-results {
display: flex;
flex-direction: column;
@@ -522,10 +519,10 @@
}
.bsplus-analytics-field-label {
font-size: 0.7rem;
font-size: 0.75rem;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.05em;
letter-spacing: 0.04em;
color: var(--bsplus-analytics-muted);
}
@@ -533,9 +530,9 @@
position: relative;
display: flex;
align-items: center;
height: 20px;
padding-left: 25px;
padding-right: 10px;
min-height: 24px;
padding-inline-start: 25px;
padding-inline-end: 10px;
font-size: 0.75rem;
font-weight: 500;
color: var(--bsplus-analytics-text);
@@ -556,8 +553,9 @@
.bsplus-analytics-checkmark {
position: absolute;
top: 0;
left: 0;
top: 50%;
inset-inline-start: 0;
transform: translateY(-50%);
box-sizing: content-box;
width: 15px;
height: 15px;
@@ -577,6 +575,11 @@
background: var(--item-colour, var(--better-main, var(--bsplus-analytics-accent)));
}
.bsplus-analytics-checkbox input:focus-visible ~ .bsplus-analytics-checkmark {
outline: 2px solid var(--bsplus-analytics-accent);
outline-offset: 2px;
}
.lc-legend-swatch-group {
gap: 8px;
}
@@ -692,16 +695,14 @@
.bsplus-analytics-select:focus,
.bsplus-analytics-input:focus {
outline: none;
outline: 2px solid var(--bsplus-analytics-accent);
outline-offset: 2px;
background-color: color-mix(
in srgb,
var(--bsplus-analytics-surface) 96%,
var(--bsplus-analytics-surface-2) 4%
);
border-color: var(--bsplus-analytics-accent);
box-shadow:
0 0 0 1px color-mix(in srgb, var(--bsplus-analytics-text) 12%, transparent),
0 0 0 3px color-mix(in srgb, var(--bsplus-analytics-accent) 22%, transparent);
}
.bsplus-analytics-filters .bsplus-analytics-dropdown-trigger:focus-visible {
@@ -751,16 +752,14 @@
}
.bsplus-analytics-range-value:focus {
outline: none;
outline: 2px solid var(--bsplus-analytics-accent);
outline-offset: 2px;
background-color: color-mix(
in srgb,
var(--bsplus-analytics-surface) 96%,
var(--bsplus-analytics-surface-2) 4%
);
border-color: var(--bsplus-analytics-accent);
box-shadow:
0 0 0 1px color-mix(in srgb, var(--bsplus-analytics-text) 12%, transparent),
0 0 0 3px color-mix(in srgb, var(--bsplus-analytics-accent) 22%, transparent);
}
.bsplus-analytics-range-value::-webkit-outer-spin-button,
@@ -789,7 +788,7 @@
font-family: inherit;
font-size: 0.875rem;
font-weight: 500;
text-align: left;
text-align: start;
color: var(--bsplus-analytics-text);
background-color: var(--bsplus-analytics-control-bg);
border: 2px solid var(--bsplus-analytics-control-border);
@@ -808,7 +807,7 @@
content: "";
position: absolute;
top: 50%;
right: 0.9rem;
inset-inline-end: 0.9rem;
width: 0.42rem;
height: 0.42rem;
border-right: 2px solid var(--bsplus-analytics-muted);
@@ -853,16 +852,14 @@
}
.bsplus-analytics-dropdown-trigger:focus-visible {
outline: none;
outline: 2px solid var(--bsplus-analytics-accent);
outline-offset: 2px;
background-color: color-mix(
in srgb,
var(--bsplus-analytics-surface) 96%,
var(--bsplus-analytics-surface-2) 4%
);
border-color: var(--bsplus-analytics-accent);
box-shadow:
0 0 0 1px color-mix(in srgb, var(--bsplus-analytics-text) 12%, transparent),
0 0 0 3px color-mix(in srgb, var(--bsplus-analytics-accent) 22%, transparent);
}
.bsplus-analytics-dropdown-trigger:focus-visible::after {
@@ -875,7 +872,7 @@
.bsplus-analytics-dropdown-menu {
position: absolute;
left: 0;
inset-inline-start: 0;
top: calc(100% + 0.35rem);
z-index: 5;
min-width: 14rem;
@@ -899,7 +896,7 @@
background: transparent;
font-family: inherit;
font-size: 0.8125rem;
text-align: left;
text-align: start;
color: var(--bsplus-analytics-text);
cursor: pointer;
transition: background 0.15s ease;
@@ -919,7 +916,7 @@
var(--bsplus-analytics-accent) 12%,
transparent
);
color: var(--bsplus-analytics-accent);
color: var(--bsplus-analytics-text);
font-weight: 600;
}
@@ -1727,6 +1724,7 @@
padding-bottom: 0;
color: var(--bsplus-analytics-muted);
font-size: 0.8125rem;
font-variant-numeric: tabular-nums;
}
/* ─── States ─── */
@@ -1741,6 +1739,8 @@
.bsplus-analytics-loading {
display: flex;
flex-direction: column;
gap: 0.75rem;
align-items: center;
justify-content: center;
min-height: 16rem;
@@ -1796,3 +1796,28 @@
.bsplus-analytics-root .accent-ring {
--tw-ring-color: var(--bsplus-analytics-accent);
}
.bsplus-analytics-sr-only {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
border: 0;
}
.bsplus-analytics-date-range {
display: flex;
flex-direction: column;
gap: 0.5rem;
margin-top: 0.25rem;
}
.bsplus-analytics-date-field {
display: flex;
flex-direction: column;
gap: 0.25rem;
}
@@ -0,0 +1,103 @@
import browser from "webextension-polyfill";
import localforage from "localforage";
import { BSPLUS_PENDING_THEME_ENSURE_AFTER_CLOUD_KEY } from "@/seqta/utils/cloudSettingsSync";
import { ThemeManager } from "./theme-manager";
jest.mock("localforage", () => {
const records = new Map<string, unknown>();
return {
getItem: jest.fn(async (key: string) => records.get(key) ?? null),
setItem: jest.fn(async (key: string, value: unknown) =>
records.set(key, value),
),
clear: jest.fn(async () => records.clear()),
};
});
jest.mock("@/seqta/utils/listeners/SettingsState", () => ({
settingsState: {},
}));
jest.mock("@/seqta/utils/performanceMode", () => ({
fullMotionEffectsEnabled: () => false,
}));
jest.mock("@/seqta/utils/DevApiBase", () => ({
getApiBase: () => "https://betterseqta.org",
}));
jest.mock("@/seqta/ui/colors/Manager", () => ({ updateAllColors: jest.fn() }));
jest.mock("@/seqta/ui/colors/customThemeAdaptiveBindings", () => ({}));
jest.mock("@/seqta/utils/patchThemeImagesPageContext", () => ({}));
jest.mock("@/utils/verboseLog", () => ({
verboseDebug: jest.fn(),
verboseInfo: jest.fn(),
}));
jest.mock("./theme-runtime", () => ({
validateThemeScript: () => true,
validateThemeDom: () => true,
}));
describe("cloud theme restoration", () => {
beforeEach(async () => {
await localforage.clear();
await browser.storage.local.set({
[BSPLUS_PENDING_THEME_ENSURE_AFTER_CLOUD_KEY]: "catalog-id",
});
jest.spyOn(console, "warn").mockImplementation(() => {});
});
afterEach(() => jest.restoreAllMocks());
it.each(["themes", "custom-themes"])(
"installs a missing %s catalog theme",
async (catalog) => {
const jsonUrl = "https://betterseqta.org/storage/theme.json";
(browser.runtime.sendMessage as jest.Mock).mockImplementation(
async ({ url }) => {
if (
url === `https://betterseqta.org/api/${catalog}/catalog-id/download`
) {
return {
data: { success: true, data: { theme_json_url: jsonUrl } },
};
}
if (url === jsonUrl)
return {
data: {
id: "catalog-id",
name: "Restored theme",
CustomCSS: "body { color: red; }",
},
};
return { error: "Not found" };
},
);
await ThemeManager.getInstance().prepareThemeAfterCloudSync();
expect(await localforage.getItem("catalog-id")).toMatchObject({
name: "Restored theme",
installedFromStore: catalog === "themes",
...(catalog === "custom-themes"
? { installedFromCommunity: true }
: {}),
});
expect(
await browser.storage.local.get(
BSPLUS_PENDING_THEME_ENSURE_AFTER_CLOUD_KEY,
),
).toEqual({});
},
);
it("keeps a failed download pending so a later page can retry", async () => {
(browser.runtime.sendMessage as jest.Mock).mockResolvedValue({
error: "Offline",
});
await ThemeManager.getInstance().prepareThemeAfterCloudSync();
expect(
await browser.storage.local.get(
BSPLUS_PENDING_THEME_ENSURE_AFTER_CLOUD_KEY,
),
).toEqual({
[BSPLUS_PENDING_THEME_ENSURE_AFTER_CLOUD_KEY]: "catalog-id",
});
});
});
+14 -9
View File
@@ -195,7 +195,7 @@ export class ThemeManager {
/**
* After cloud restore, IndexedDB/theme storage is only reachable from page context (not MV3 SW).
* Background sets BSPLUS_PENDING_THEME_ENSURE_AFTER_CLOUD_KEY; we fetch the store JSON here before setTheme().
* Background sets BSPLUS_PENDING_THEME_ENSURE_AFTER_CLOUD_KEY; we fetch catalog JSON here before setTheme().
* The resolved id matches cloud sync **`themeId` / `selectedTheme`**: it may be a standard theme uuid or a
* flavour (slave) variant id — **`downloadAndInstallStoreTheme`** is the same code path as the theme store installer.
*/
@@ -205,16 +205,21 @@ export class ThemeManager {
const pending = snap[BSPLUS_PENDING_THEME_ENSURE_AFTER_CLOUD_KEY];
if (pending === undefined) return;
await browser.storage.local.remove(BSPLUS_PENDING_THEME_ENSURE_AFTER_CLOUD_KEY);
if (typeof pending !== "string") return;
const id = pending.trim();
if (!id) return;
const id = typeof pending === "string" ? pending.trim() : "";
if (!id) {
await browser.storage.local.remove(BSPLUS_PENDING_THEME_ENSURE_AFTER_CLOUD_KEY);
return;
}
const existing = (await localforage.getItem(id)) as CustomTheme | null;
if (existing) return;
await this.downloadAndInstallStoreTheme({ id, name: id });
if (!existing) {
try {
await this.downloadAndInstallStoreTheme({ id, name: id });
} catch {
await this.downloadAndInstallCommunityTheme({ id });
}
}
await browser.storage.local.remove(BSPLUS_PENDING_THEME_ENSURE_AFTER_CLOUD_KEY);
} catch (e) {
console.warn("[ThemeManager] prepareThemeAfterCloudSync:", e);
}
+165
View File
@@ -0,0 +1,165 @@
/** @jest-environment jsdom */
import { PluginManager } from "./manager";
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
import { isPluginAllowedInPerformanceMode } from "@/seqta/utils/performanceMode";
jest.mock("@/seqta/utils/performanceMode", () => ({
isPluginAllowedInPerformanceMode: jest.fn(() => true),
}));
test("startup and performance synchronization share one plugin mount and cleanup", async () => {
const manager = PluginManager.getInstance();
let release!: () => void;
const ready = new Promise<void>((resolve) => {
release = resolve;
});
const cleanup = jest.fn();
manager.registerPlugin({
id: "grade-analytics",
name: "Analytics",
description: "",
version: "1",
settings: {},
run: async () => {
await ready;
const row = document.createElement("li");
row.dataset.key = "analytics";
document.body.append(row);
return () => {
row.remove();
cleanup();
};
},
});
const synchronization = manager.startPlugin("grade-analytics");
const startup = manager.startAllPlugins();
release();
await Promise.all([synchronization, startup]);
expect(document.querySelectorAll('[data-key="analytics"]')).toHaveLength(1);
await manager.stopPlugin("grade-analytics");
expect(document.querySelectorAll('[data-key="analytics"]')).toHaveLength(0);
expect(cleanup).toHaveBeenCalledTimes(1);
});
test.each(["plugin", "master", "performance"])(
"a redundant startup cannot cancel a pending %s disable",
async (disable) => {
const manager = PluginManager.getInstance();
const id = `pending-${disable}`;
const storageKey = `plugin.${id}.settings`;
let release!: () => void;
let enter!: () => void;
const ready = new Promise<void>((resolve) => {
release = resolve;
});
const entered = new Promise<void>((resolve) => {
enter = resolve;
});
const row = document.createElement("li");
const cleanup = jest.fn(() => row.remove());
settingsState.onoff = true;
manager.registerPlugin({
id,
name: "Pending",
description: "",
version: "1",
settings: {},
disableToggle: true,
run: async () => {
enter();
await ready;
document.body.append(row);
return cleanup;
},
});
const startup = manager.startPlugin(id);
await entered;
if (disable === "plugin")
settingsState.setKey(storageKey, { enabled: false });
if (disable === "master") settingsState.onoff = false;
if (disable === "performance")
jest.mocked(isPluginAllowedInPerformanceMode).mockReturnValue(false);
const stopping = manager.stopPlugin(id);
const redundantStartup = manager.startPlugin(id);
release();
await Promise.all([startup, stopping, redundantStartup]);
try {
expect(row.isConnected).toBe(false);
expect(manager.isPluginRunning(id)).toBe(false);
expect(cleanup).toHaveBeenCalledTimes(1);
} finally {
settingsState.onoff = true;
jest.mocked(isPluginAllowedInPerformanceMode).mockReturnValue(true);
}
},
);
test("disabling a plugin during startup cleans up its eventual mount", async () => {
const manager = PluginManager.getInstance();
let release!: () => void;
const ready = new Promise<void>((resolve) => {
release = resolve;
});
const row = document.createElement("li");
manager.registerPlugin({
id: "enhanced-navigation",
name: "Navigation",
description: "",
version: "1",
settings: {},
run: async () => {
await ready;
document.body.append(row);
return () => row.remove();
},
});
const startup = manager.startPlugin("enhanced-navigation");
const stopping = manager.stopPlugin("enhanced-navigation");
release();
await Promise.all([startup, stopping]);
expect(row.isConnected).toBe(false);
expect(manager.isPluginRunning("enhanced-navigation")).toBe(false);
});
test("re-enabling during a pending startup wins over an earlier stop", async () => {
const manager = PluginManager.getInstance();
let release!: () => void;
const ready = new Promise<void>((resolve) => {
release = resolve;
});
const row = document.createElement("li");
const cleanup = jest.fn(() => row.remove());
settingsState.setKey("plugin.background-music.settings", { enabled: true });
manager.registerPlugin({
id: "background-music",
name: "Music",
description: "",
version: "1",
settings: {},
disableToggle: true,
run: async () => {
await ready;
document.body.append(row);
return cleanup;
},
});
const startup = manager.startPlugin("background-music");
settingsState.setKey("plugin.background-music.settings", { enabled: false });
const stopping = manager.stopPlugin("background-music");
settingsState.setKey("plugin.background-music.settings", { enabled: true });
const restarting = manager.startPlugin("background-music");
release();
await Promise.all([startup, stopping, restarting]);
expect(row.isConnected).toBe(true);
expect(manager.isPluginRunning("background-music")).toBe(true);
expect(cleanup).not.toHaveBeenCalled();
await manager.stopPlugin("background-music");
});
+45 -25
View File
@@ -58,6 +58,8 @@ export class PluginManager {
private static instance: PluginManager;
private plugins: Map<string, Plugin<any, any>> = new Map();
private runningPlugins: Map<string, boolean> = new Map();
private startingPlugins: Map<string, Promise<void>> = new Map();
private pendingStops: Map<string, symbol> = new Map();
private eventBacklog: Map<string, any[]> = new Map();
private cleanupFunctions: Map<string, () => void> = new Map();
private apiDisposers: Map<string, () => void> = new Map();
@@ -162,6 +164,22 @@ export class PluginManager {
* @throws {Error} If the plugin is not found, or if an error occurs during plugin initialization or execution.
*/
public async startPlugin(pluginId: string): Promise<void> {
const plugin = this.plugins.get(pluginId);
if (plugin && !this.shouldStartPlugin(plugin)) return;
this.pendingStops.delete(pluginId);
const starting = this.startingPlugins.get(pluginId);
if (starting) return starting;
const promise = this.startPluginOnce(pluginId);
this.startingPlugins.set(pluginId, promise);
try {
await promise;
} finally {
this.startingPlugins.delete(pluginId);
}
}
private async startPluginOnce(pluginId: string): Promise<void> {
const plugin = this.plugins.get(pluginId);
if (!plugin) {
throw new Error(`Plugin "${pluginId}" not found`);
@@ -176,31 +194,6 @@ export class PluginManager {
const api = createPluginAPI(plugin);
this.apiDisposers.set(pluginId, api.dispose);
// Check if plugin is enabled before starting
if (plugin.disableToggle) {
const all = settingsState.getAll() as unknown as Record<string, unknown>;
const pluginSettings = all[`plugin.${pluginId}.settings`] as
| PluginSettingsStorage
| undefined;
const enabled =
pluginSettings?.enabled ?? plugin.defaultEnabled ?? true;
if (!enabled) {
this.disposePluginAPI(pluginId);
verboseInfo(
`Plugin "${pluginId}" is disabled, skipping initialization`,
);
return;
}
}
if (!isPluginAllowedInPerformanceMode(pluginId)) {
this.disposePluginAPI(pluginId);
verboseInfo(
`Plugin "${pluginId}" paused by performance mode`,
);
return;
}
// Inject plugin styles if provided
if (plugin.styles) {
const styleElement = document.createElement("style");
@@ -212,7 +205,19 @@ export class PluginManager {
// Wait for both settings and storage to be loaded before starting the plugin
await Promise.all([(api.settings as any).loaded, api.storage.loaded]);
if (!this.shouldStartPlugin(plugin)) {
this.removePluginStyles(pluginId);
this.disposePluginAPI(pluginId);
return;
}
const result = await plugin.run(api);
if (!this.shouldStartPlugin(plugin)) {
if (typeof result === "function") result();
this.removePluginStyles(pluginId);
this.disposePluginAPI(pluginId);
return;
}
if (typeof result === "function") {
this.cleanupFunctions.set(plugin.id, result);
}
@@ -232,6 +237,16 @@ export class PluginManager {
}
}
private shouldStartPlugin(plugin: Plugin): boolean {
if (settingsState.onoff === false || !isPluginAllowedInPerformanceMode(plugin.id)) {
return false;
}
if (!plugin.disableToggle) return true;
const all = settingsState.getAll() as unknown as Record<string, unknown>;
const stored = all[`plugin.${plugin.id}.settings`] as PluginSettingsStorage | undefined;
return stored?.enabled ?? plugin.defaultEnabled ?? true;
}
private removePluginStyles(pluginId: string): void {
const styleElement = this.styleElements.get(pluginId);
if (styleElement) {
@@ -295,6 +310,11 @@ export class PluginManager {
* @returns {Promise<void>} A promise that resolves when the plugin has been stopped.
*/
public async stopPlugin(pluginId: string): Promise<void> {
const stopRequest = Symbol();
this.pendingStops.set(pluginId, stopRequest);
await this.startingPlugins.get(pluginId)?.catch(() => {});
if (this.pendingStops.get(pluginId) !== stopRequest) return;
this.pendingStops.delete(pluginId);
this.removePluginStyles(pluginId);
this.disposePluginAPI(pluginId);
+4
View File
@@ -750,6 +750,10 @@ function updateSidebarAccessibility() {
const visibleEntries = new Set(
visibleList ? getDirectSidebarEntries(visibleList) : [],
);
if (document.body?.classList.contains("icon-only-sidebar")) {
const rootList = menu.querySelector(":scope > ul") as HTMLElement | null;
if (rootList) getDirectSidebarEntries(rootList).forEach((entry) => visibleEntries.add(entry));
}
const drillFolders = getDrillFolderChain(menu, visibleList);
const menuEntries = menu.querySelectorAll("li.item, section.item, li, section");
+1 -1
View File
@@ -104,7 +104,7 @@ function applyBetterseqtaLogoBackground(isDark: boolean) {
background-image: url("${fullUrl}") !important;
}
/* Icon-only sidebar: wordmark → compact mark (theme-aware). */
body.student.icon-only-sidebar:not(:has(#menu li.hasChildren:is(.active, .bsplus-active))) #menu > ul::before {
body.student.icon-only-sidebar #menu > ul::before {
background-image: url("${iconUrl}") !important;
}
`;
+1 -1
View File
@@ -111,7 +111,7 @@ export function parseNativeMenu(menu: HTMLElement): SidebarItem[] {
return [...list.children]
.filter((node): node is HTMLElement => node instanceof HTMLElement)
.map(parseEntry)
.map((entry) => parseEntry(entry))
.filter((item): item is SidebarItem => item != null);
}
+100 -41
View File
@@ -1,7 +1,7 @@
const MENU_RETURN_CLASS = "bsplus-sidebar-returning";
const LIST_RETURN_CLASS = "bsplus-drill-return-target";
const RETURN_MS = 300;
const RETURN_EASE = "cubic-bezier(0.4, 0, 0.2, 1)";
const ROWS_CLASS = "bsplus-drill-rows";
/** Count open folder levels (0 = root list only). */
export function getSidebarDrillDepth(
@@ -19,7 +19,9 @@ export function getSidebarDrillDepth(
if (!activeFolder) break;
depth += 1;
list = activeFolder.querySelector(":scope > .sub > ul") as HTMLElement | null;
list = activeFolder.querySelector(
":scope > .sub > ul",
) as HTMLElement | null;
}
return depth;
@@ -42,37 +44,74 @@ function getSidebarListAtDepth(
":scope > li.hasChildren.active, :scope > section.hasChildren.active",
) as HTMLElement | null;
if (!activeFolder) return list;
list = activeFolder.querySelector(":scope > .sub > ul") as HTMLElement | null;
list = activeFolder.querySelector(
":scope > .sub > ul",
) as HTMLElement | null;
depth += 1;
}
return list;
}
function getSlideOff(menu: HTMLElement): string {
const value = getComputedStyle(menu).getPropertyValue("--bsplus-slide-off").trim();
return value || "-320px";
}
function getReturnSlideNodes(list: HTMLElement): HTMLElement[] {
return [
...list.querySelectorAll<HTMLElement>(
":scope > li > label, :scope > li > svg, :scope > section > label, :scope > section > svg",
),
...list.querySelectorAll<HTMLElement>(":scope > li, :scope > section"),
];
}
function clearInlineReturnStyles(nodes: Iterable<HTMLElement>) {
function prepareRowSlide(list: HTMLElement) {
// The icons-only root rail remains visible next to the open panel.
if (
document.body?.classList.contains("icon-only-sidebar") &&
list.parentElement?.id === "menu"
)
return;
if (list.classList.contains(ROWS_CLASS)) return;
const nodes = getReturnSlideNodes(list);
// Read all auto/preset margins before changing any row's layout.
const margins = nodes.map((node) => getComputedStyle(node).marginLeft);
nodes.forEach((node, index) => {
node.style.setProperty("--bsplus-row-margin-left", margins[index]);
node.style.setProperty("margin-left", margins[index], "important");
});
list.classList.add(ROWS_CLASS);
// Establish a concrete start before native state changes (or an observer
// prepares a programmatically opened folder after its class changed).
void list.offsetWidth;
nodes.forEach((node) => node.style.removeProperty("margin-left"));
}
function clearRowSlide(nodes: Iterable<HTMLElement>) {
for (const node of nodes) {
node.style.removeProperty("transition");
node.style.removeProperty("transform");
node.style.removeProperty("margin-left");
node.style.removeProperty("--bsplus-row-margin-left");
node.parentElement?.classList.remove(ROWS_CLASS);
}
}
let returnTimer: ReturnType<typeof setTimeout> | null = null;
let lastAnimatedNodes: HTMLElement[] = [];
let lastDrillDepth = 0;
let menuObserver: MutationObserver | null = null;
let lastRootFolder: Element | null = null;
let swapFrame: number | null = null;
function rootFolder(menu: HTMLElement) {
return menu.querySelector(
":scope > ul > .hasChildren:is(.active, .bsplus-active)",
);
}
function swapRootPanel(menu: HTMLElement) {
if (!document.body?.classList.contains("icon-only-sidebar")) return;
if (swapFrame !== null) cancelAnimationFrame(swapFrame);
menu.classList.add("bsplus-icon-rail-switching");
swapFrame = requestAnimationFrame(() => {
swapFrame = requestAnimationFrame(() => {
swapFrame = null;
menu.classList.remove("bsplus-icon-rail-switching");
});
});
}
let backCaptureAttached = false;
function clearReturnClasses(menu: HTMLElement) {
@@ -97,39 +136,24 @@ export function runSidebarDrillReturn(
if (returnTimer) clearTimeout(returnTimer);
clearReturnClasses(menu);
clearInlineReturnStyles(lastAnimatedNodes);
lastAnimatedNodes = nodes;
const slideOff = getSlideOff(menu);
// Hold the off-screen transform before SEQTA clears `.active` and drops `:has()`.
for (const node of nodes) {
node.style.transition = "none";
node.style.transform = `translateX(${slideOff})`;
}
prepareRowSlide(list);
menu.classList.add(MENU_RETURN_CLASS);
list.classList.add(LIST_RETURN_CLASS);
lastDrillDepth = depth;
requestAnimationFrame(() => {
requestAnimationFrame(() => {
for (const node of nodes) {
node.style.transition = `transform ${RETURN_MS}ms ${RETURN_EASE}`;
node.style.transform = "translateX(0)";
}
});
});
returnTimer = setTimeout(() => {
returnTimer = null;
clearReturnClasses(menu);
clearInlineReturnStyles(nodes);
lastAnimatedNodes = [];
clearRowSlide(nodes);
}, RETURN_MS + 50);
}
function onDrillDepthChange(menu: HTMLElement) {
const currentRoot = rootFolder(menu);
if (lastRootFolder && currentRoot && lastRootFolder !== currentRoot)
swapRootPanel(menu);
lastRootFolder = currentRoot;
if (menu.classList.contains(MENU_RETURN_CLASS)) return;
const depth = getSidebarDrillDepth(menu);
@@ -137,16 +161,39 @@ function onDrillDepthChange(menu: HTMLElement) {
runSidebarDrillReturn(menu, depth);
return;
}
if (depth > lastDrillDepth) {
const outgoing = getSidebarListAtDepth(menu, lastDrillDepth);
if (outgoing) prepareRowSlide(outgoing);
}
lastDrillDepth = depth;
}
function onMenuClickCapture(event: MouseEvent) {
const menu = document.getElementById("menu");
if (!menu || menu.classList.contains(MENU_RETURN_CLASS)) return;
if (!menu) return;
const target = event.target;
if (!(target instanceof Element)) return;
if (!target.closest(".sub .back")) return;
if (!target.closest(".sub .back")) {
const folder = target.closest("li.hasChildren, section.hasChildren");
if (
folder &&
!folder.classList.contains("active") &&
folder.parentElement
) {
if (
folder.parentElement.parentElement === menu &&
rootFolder(menu) &&
rootFolder(menu) !== folder
)
swapRootPanel(menu);
if (returnTimer) clearTimeout(returnTimer);
returnTimer = null;
clearReturnClasses(menu);
prepareRowSlide(folder.parentElement);
}
return;
}
const depthBefore = getSidebarDrillDepth(menu);
if (depthBefore > 0) {
@@ -154,13 +201,18 @@ function onMenuClickCapture(event: MouseEvent) {
}
}
/** Drive the reverse slide when folder `.active` is cleared. */
/** Keep row motion together when native folder state changes. */
export function installSidebarDrillReturn(
menu: HTMLElement | null = document.getElementById("menu"),
) {
if (!menu || menuObserver) return;
lastDrillDepth = getSidebarDrillDepth(menu);
lastRootFolder = rootFolder(menu);
for (let depth = 0; depth < lastDrillDepth; depth++) {
const list = getSidebarListAtDepth(menu, depth);
if (list) prepareRowSlide(list);
}
menuObserver = new MutationObserver(() => {
onDrillDepthChange(menu);
@@ -183,12 +235,19 @@ export function uninstallSidebarDrillReturn() {
if (returnTimer) clearTimeout(returnTimer);
returnTimer = null;
lastDrillDepth = 0;
lastRootFolder = null;
if (swapFrame !== null) cancelAnimationFrame(swapFrame);
swapFrame = null;
const menu = document.getElementById("menu");
if (menu) {
menu.classList.remove("bsplus-icon-rail-switching");
clearReturnClasses(menu);
clearInlineReturnStyles(lastAnimatedNodes);
lastAnimatedNodes = [];
clearRowSlide(
menu.querySelectorAll<HTMLElement>(
`ul.${ROWS_CLASS} > li, ul.${ROWS_CLASS} > section`,
),
);
if (backCaptureAttached) {
menu.removeEventListener("click", onMenuClickCapture, true);
backCaptureAttached = false;
@@ -0,0 +1,52 @@
/** @jest-environment jsdom */
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
import { applySidebarLook, clearSidebarAppearance } from "./sidebarStyles";
jest.mock("@/seqta/utils/performanceMode", () => ({ isPerformanceMode: () => false }));
beforeEach(() => {
clearSidebarAppearance(document.getElementById("menu"));
document.body.innerHTML = "";
settingsState.sidebarDensity = "compact";
settingsState.sidebarActiveIndicator = "outline";
settingsState.sidebarWidth = "wide";
settingsState.sidebarPosition = "right";
});
test("early sidebar preparation and cleanup work before body exists", () => {
const body = document.body;
body.remove();
try {
expect(() => applySidebarLook(null)).not.toThrow();
expect(document.documentElement.style.getPropertyValue("--bsplus-sidebar-width")).toBe("320px");
expect(() => clearSidebarAppearance(null)).not.toThrow();
} finally {
document.documentElement.append(body);
}
});
test.each([false, true])("applies unchanged settings to a newly available menu (replacement: %s)", (replacement) => {
const initialMenu = replacement ? document.createElement("div") : null;
applySidebarLook(initialMenu);
const menu = document.createElement("div");
menu.id = "menu";
document.body.append(menu);
applySidebarLook(menu);
expect(menu.classList.contains("bsplus-sidebar-density-compact")).toBe(true);
expect(menu.classList.contains("bsplus-sidebar-indicator-outline")).toBe(true);
});
test("restores sidebar variables and classes after disable and re-enable", () => {
const menu = document.createElement("div");
applySidebarLook(menu);
clearSidebarAppearance(menu);
expect(document.documentElement.style.getPropertyValue("--bsplus-sidebar-width")).toBe("");
applySidebarLook(menu);
expect(document.documentElement.style.getPropertyValue("--bsplus-sidebar-width")).toBe("320px");
expect(menu.classList.contains("bsplus-sidebar-density-compact")).toBe(true);
expect(document.body.classList.contains("bsplus-sidebar-right")).toBe(true);
});
-1
View File
@@ -758,7 +758,6 @@ function createAssessmentDateDiv(date: string, value: any, datecase?: any) {
subject.innerText = element.title;
subject.classList.add("upcoming-assessment-title");
subject.onclick = function () {
document.querySelector("#menu ul")!.classList.add("noscroll");
location.href = `../#?page=/assessments/${element.programmeID}:${element.metaclassID}&item=${element.id}`;
};
detailsdiv.append(detailstitle, subject);
@@ -18,7 +18,7 @@ describe("shouldShowCoursesAssessmentsFixPopup", () => {
).toBe(true);
});
it("does not show when BetterSEQTA features are on unless What's New just closed", () => {
it("does not show when BetterSEQTA features are on", () => {
expect(
shouldShowCoursesAssessmentsFixPopup({
onoff: true,
@@ -27,18 +27,6 @@ describe("shouldShowCoursesAssessmentsFixPopup", () => {
).toBe(false);
});
it("shows after What's New even when BetterSEQTA features are already on", () => {
expect(
shouldShowCoursesAssessmentsFixPopup(
{
onoff: true,
coursesAssessmentsFixPopupShown: false,
},
{ afterWhatsNew: true },
),
).toBe(true);
});
it("does not show again after the user has seen it", () => {
expect(
shouldShowCoursesAssessmentsFixPopup(
@@ -46,7 +34,6 @@ describe("shouldShowCoursesAssessmentsFixPopup", () => {
onoff: false,
coursesAssessmentsFixPopupShown: true,
},
{ afterWhatsNew: true },
),
).toBe(false);
});
@@ -12,10 +12,8 @@ export type CoursesAssessmentsFixPopupState = {
export function shouldShowCoursesAssessmentsFixPopup(
state: CoursesAssessmentsFixPopupState = settingsState,
options?: { afterWhatsNew?: boolean },
): boolean {
if (state.coursesAssessmentsFixPopupShown) return false;
if (options?.afterWhatsNew) return true;
return state.onoff === false;
}
@@ -238,13 +236,12 @@ function setPopupButtonsDisabled(disabled: boolean) {
export function OpenCoursesAssessmentsFixPopup(
onDismissed?: () => void,
options?: { afterWhatsNew?: boolean },
) {
if (document.getElementById("whatsnewbk")) {
onDismissed?.();
return;
}
if (!shouldShowCoursesAssessmentsFixPopup(settingsState, options)) {
if (!shouldShowCoursesAssessmentsFixPopup(settingsState)) {
onDismissed?.();
return;
}
@@ -0,0 +1,96 @@
/** @jest-environment jsdom */
import { OpenThemeOfTheMonthPopup } from "./OpenThemeOfTheMonthPopup";
import { settingsState } from "../listeners/SettingsState";
jest.mock("../DevApiBase", () => ({
getApiBase: () => "https://example.test",
}));
jest.mock("./PopupManager", () => ({ closePopup: jest.fn() }));
jest.mock("../listeners/SettingsState", () => ({
settingsState: { animations: false },
}));
const entry = {
id: "totm-1",
month: "2026-10",
title: "October Theme",
description: "Preview",
cover_image: "https://example.test/cover.png",
theme_id: null,
theme: null,
created_at: 1,
updated_at: 1,
};
beforeEach(() => {
jest.useFakeTimers();
settingsState.themeOfTheMonthDismissedMonth = undefined;
document.body.innerHTML = "";
});
afterEach(() => {
document
.querySelector<HTMLButtonElement>(".themeOfTheMonthCardSecondary")
?.click();
jest.runOnlyPendingTimers();
jest.useRealTimers();
});
it.each([false, true])(
"click-away dismisses and records the month once (expanded: %s)",
async (expanded) => {
const onDismissed = jest.fn();
await OpenThemeOfTheMonthPopup(entry, onDismissed);
if (expanded)
document
.querySelector<HTMLButtonElement>(".themeOfTheMonthCardPopout")!
.click();
const outside = expanded
? document.getElementById("theme-of-the-month-backdrop")!
: document.body;
outside.click();
document.body.click();
jest.advanceTimersByTime(30_000);
expect(document.getElementById("theme-of-the-month-card")).toBeNull();
expect(document.getElementById("theme-of-the-month-backdrop")).toBeNull();
expect(settingsState.themeOfTheMonthDismissedMonth).toBe(entry.month);
expect(onDismissed).toHaveBeenCalledTimes(1);
},
);
it("keeps the card open while interacting with it and its fullscreen preview", async () => {
await OpenThemeOfTheMonthPopup(entry);
document.querySelector<HTMLElement>(".themeOfTheMonthCardBody")!.click();
document
.querySelector<HTMLImageElement>(".themeOfTheMonthCardImage")!
.click();
const overlay = document.getElementById("bsplus-popup-media-overlay")!;
expect(overlay).not.toBeNull();
overlay.querySelector<HTMLImageElement>("img")!.click();
overlay.click();
jest.advanceTimersByTime(180);
expect(document.getElementById("theme-of-the-month-card")).not.toBeNull();
expect(settingsState.themeOfTheMonthDismissedMonth).toBeUndefined();
document.body.click();
jest.advanceTimersByTime(180);
expect(document.getElementById("theme-of-the-month-card")).toBeNull();
});
it("ignores the opening click and cleans up an existing card when replaced", async () => {
const opener = document.createElement("button");
document.body.append(opener);
const oldDismissed = jest.fn();
opener.addEventListener(
"click",
() => void OpenThemeOfTheMonthPopup(entry, oldDismissed),
);
opener.click();
expect(document.getElementById("theme-of-the-month-card")).not.toBeNull();
const newDismissed = jest.fn();
await OpenThemeOfTheMonthPopup({ ...entry, month: "2026-11" }, newDismissed);
document.body.click();
jest.advanceTimersByTime(30_000);
expect(settingsState.themeOfTheMonthDismissedMonth).toBe("2026-11");
expect(newDismissed).toHaveBeenCalledTimes(1);
expect(oldDismissed).not.toHaveBeenCalled();
});
@@ -227,6 +227,7 @@ const TOTM_MORPH_MS = 550;
const TOTM_LAYOUT_SWAP_MS = TOTM_MORPH_MS / 2;
let themeOfTheMonthAnimGen = 0;
let cleanupThemeOfTheMonthPopup: (() => void) | undefined;
// ---------------------------------------------------------------------------
// Dimension helpers
@@ -675,6 +676,7 @@ export async function OpenThemeOfTheMonthPopup(
entry: ThemeOfTheMonthEntry,
onDismissed?: () => void,
): Promise<void> {
cleanupThemeOfTheMonthPopup?.();
document.getElementById("theme-of-the-month-card")?.remove();
document.getElementById("theme-of-the-month-backdrop")?.remove();
@@ -779,13 +781,29 @@ export async function OpenThemeOfTheMonthPopup(
);
};
const dismissWithCleanup = () => {
const cleanup = () => {
pauseAutoClose();
window.removeEventListener("resize", onResize);
backdrop.remove();
document.removeEventListener("keydown", onDocKey, true);
document.removeEventListener("click", onOutsideClick, true);
if (cleanupThemeOfTheMonthPopup === cleanup) cleanupThemeOfTheMonthPopup = undefined;
};
const dismissWithCleanup = () => {
cleanup();
closeThemeOfTheMonthCard(card, onDismissed);
};
const dismissForMonth = () => {
settingsState.themeOfTheMonthDismissedMonth = entry.month;
dismissWithCleanup();
};
const onOutsideClick = (event: MouseEvent) => {
const target = event.target;
if (target instanceof Node && card.contains(target)) return;
if (target instanceof Element && target.closest("#bsplus-popup-media-overlay")) return;
dismissForMonth();
};
cleanupThemeOfTheMonthPopup = cleanup;
autoCloseTimeout = window.setTimeout(dismissWithCleanup, 30_000);
card.addEventListener("mouseenter", pauseAutoClose, { once: true });
@@ -807,22 +825,12 @@ export async function OpenThemeOfTheMonthPopup(
toggleExpanded();
});
backdrop.addEventListener("click", () => {
if (!isExpanded || expandAnimating) return;
isExpanded = false;
void applyExpandedState(false);
});
document.addEventListener("keydown", onDocKey, true);
card.querySelector(".themeOfTheMonthCardSecondary")?.addEventListener("click", () => {
settingsState.themeOfTheMonthDismissedMonth = entry.month;
dismissWithCleanup();
});
card.querySelector(".themeOfTheMonthCardSecondary")?.addEventListener("click", dismissForMonth);
card.querySelector(".themeOfTheMonthCardPrimary")?.addEventListener("click", () => {
settingsState.themeOfTheMonthDismissedMonth = entry.month;
dismissWithCleanup();
dismissForMonth();
void openThemeStoreWithHighlight(linkedThemeId!);
});
@@ -852,6 +860,8 @@ export async function OpenThemeOfTheMonthPopup(
card.style.left = "0";
document.body.append(backdrop, card);
// Capture has already passed for the click that opened this card.
document.addEventListener("click", onOutsideClick, true);
// Set initial collapsed position instantly (no transition).
applyThemeOfTheMonthCardPosition(card, false, false);
@@ -886,4 +896,4 @@ export async function showThemeOfTheMonthPopupNow(): Promise<void> {
}
await OpenThemeOfTheMonthPopup(entry);
}
}
+3 -9
View File
@@ -16,7 +16,7 @@ type QueueStep = (goNext: () => void) => void;
/**
* Runs startup modals in order: What's New (if the extension just updated),
* Courses/Assessments fix notice (after What's New, or if features are off),
* Courses/Assessments fix notice (only if features are off),
* Theme of the Month (when the user hasn't dismissed this calendar month),
* then feedback reply notifications for pending submissions.
*/
@@ -32,14 +32,8 @@ export async function runStartupPopupQueue() {
steps.push((goNext) => OpenWhatsNewPopup(goNext));
}
if (
shouldShowCoursesAssessmentsFixPopup(settingsState, {
afterWhatsNew,
})
) {
steps.push((goNext) =>
OpenCoursesAssessmentsFixPopup(goNext, { afterWhatsNew }),
);
if (shouldShowCoursesAssessmentsFixPopup(settingsState)) {
steps.push((goNext) => OpenCoursesAssessmentsFixPopup(goNext));
}
// Fetch the Theme of the Month before queueing so we don't show an empty
@@ -0,0 +1,84 @@
import { afterEach, expect, it, jest } from "@jest/globals";
import {
listGoogleSyncedEvents,
listOutlookSyncedEvents,
} from "./remoteEvents";
afterEach(() => jest.restoreAllMocks());
it.each([
{ provider: "google", body: "invalid JSON" },
{ provider: "outlook", body: "invalid JSON" },
{
provider: "google",
body: JSON.stringify({ error: { message: "Invalid response" } }),
},
{ provider: "outlook", body: "{}" },
])(
"rejects malformed successful $provider listings ($body)",
async ({ provider, body }) => {
jest.spyOn(globalThis, "fetch").mockResolvedValue(new Response(body));
const range = { from: "2026-10-04", until: "2026-10-04" };
const listing =
provider === "google"
? listGoogleSyncedEvents("token", "calendar", range)
: listOutlookSyncedEvents("token", range);
await expect(listing).rejects.toThrow();
},
);
it.each(["google", "outlook"])(
"queries %s over complete local days across Sydney DST",
async (provider) => {
const zone = Intl.DateTimeFormat().resolvedOptions().timeZone;
const expected =
zone === "Australia/Sydney"
? ["2026-10-03T14:00:00.000Z", "2026-10-04T13:00:00.000Z"]
: zone === "UTC"
? ["2026-10-04T00:00:00.000Z", "2026-10-05T00:00:00.000Z"]
: null;
let requestedBounds: string[] = [];
jest.spyOn(globalThis, "fetch").mockImplementation(async (url) => {
const query = new URL(String(url)).searchParams;
requestedBounds =
provider === "google"
? [query.get("timeMin")!, query.get("timeMax")!]
: [query.get("startDateTime")!, query.get("endDateTime")!];
return Response.json(provider === "google" ? {} : { value: [] });
});
const range = { from: "2026-10-04", until: "2026-10-04" };
if (provider === "google")
await listGoogleSyncedEvents("token", "calendar", range);
else await listOutlookSyncedEvents("token", range);
if (expected) expect(requestedBounds).toEqual(expected);
else {
const [start, end] = requestedBounds.map((value) => new Date(value));
expect([
start.getDate(),
start.getHours(),
end.getDate(),
end.getHours(),
]).toEqual([4, 0, 5, 0]);
}
},
);
it("rejects an incomplete paginated listing rather than authorizing reconciliation", async () => {
jest
.spyOn(globalThis, "fetch")
.mockResolvedValueOnce(
Response.json({ items: [], nextPageToken: "second-page" }),
)
.mockResolvedValueOnce(
Response.json(
{ error: { message: "Page unavailable" } },
{ status: 400 },
),
);
await expect(
listGoogleSyncedEvents("token", "calendar", {
from: "2026-10-04",
until: "2026-10-04",
}),
).rejects.toThrow("Page unavailable");
});
+18 -9
View File
@@ -182,16 +182,13 @@ export function deleteOutlookCalendarEvent(
}
function toRfc3339Start(date: string): string {
return `${date}T00:00:00Z`;
return new Date(`${date}T00:00:00`).toISOString();
}
function toRfc3339EndExclusive(date: string): string {
const d = new Date(`${date}T12:00:00Z`);
d.setUTCDate(d.getUTCDate() + 1);
const y = d.getUTCFullYear();
const m = String(d.getUTCMonth() + 1).padStart(2, "0");
const day = String(d.getUTCDate()).padStart(2, "0");
return `${y}-${m}-${day}T00:00:00Z`;
const d = new Date(`${date}T00:00:00`);
d.setDate(d.getDate() + 1);
return d.toISOString();
}
function dateFromDateTime(value: string | undefined): string {
@@ -264,7 +261,7 @@ export async function listGoogleSyncedEvents(
{ method: "GET" },
refreshAccessToken,
);
const json = (await res.json().catch(() => ({}))) as {
const json = (await res.json()) as {
items?: GoogleListItem[];
nextPageToken?: string;
error?: { message?: string };
@@ -272,6 +269,15 @@ export async function listGoogleSyncedEvents(
if (!res.ok) {
throw new Error(json?.error?.message ?? `Google Calendar list failed (${res.status})`);
}
if (
!json ||
typeof json !== "object" ||
Array.isArray(json) ||
json.error ||
(json.items !== undefined && !Array.isArray(json.items))
) {
throw new Error("Invalid Google Calendar list response.");
}
for (const item of json.items ?? []) {
const mapped = googleItemToRemote(item, includeUnkeyed);
@@ -360,7 +366,7 @@ export async function listOutlookSyncedEvents(
},
refreshAccessToken,
);
const json = (await res.json().catch(() => ({}))) as {
const json = (await res.json()) as {
value?: OutlookListItem[];
"@odata.nextLink"?: string;
error?: { message?: string };
@@ -368,6 +374,9 @@ export async function listOutlookSyncedEvents(
if (!res.ok) {
throw new Error(json?.error?.message ?? `Outlook Calendar list failed (${res.status})`);
}
if (!Array.isArray(json?.value) || json.error) {
throw new Error("Invalid Outlook Calendar list response.");
}
for (const item of json.value ?? []) {
const mapped = outlookItemToRemote(item, includeUnkeyed);
+15 -1
View File
@@ -40,6 +40,7 @@ import {
writeGoogleCalendarState,
} from "@/seqta/utils/calendarSync/providerStorage";
import {
isDateInRange,
syncWindowRange,
trailingWeekRange,
wideCleanupRange,
@@ -199,6 +200,9 @@ export async function syncLessonsToCalendar(
syncWindowRange,
trailingWeekRange,
});
const currentMapKeys = new Set(
events.map((event) => eventMapKey(request.origin, event.seqtaKey)),
);
try {
const remoteEvents = await provider.listSyncedEvents(
@@ -207,11 +211,21 @@ export async function syncLessonsToCalendar(
refreshAccessToken,
);
mergeRemoteEventsIntoMap(eventMap, request.origin, remoteEvents, eventMapKey);
const remoteIds = new Set(remoteEvents.map((event) => event.id));
for (const key of currentMapKeys) {
const entry = normalizeEventMapEntry(eventMap[key]);
if (
entry?.date &&
isDateInRange(entry.date, reconcileRange) &&
!remoteIds.has(entry.id)
) {
delete eventMap[key];
}
}
} catch (err) {
verboseLog(`[BetterSEQTA+] ${provider.label} remote event list failed:`, err);
}
const currentMapKeys = new Set(events.map((event) => eventMapKey(request.origin, event.seqtaKey)));
let staleEntries = entriesToPrune(
eventMap,
request.origin,
@@ -1,10 +1,35 @@
import {
applyDownloadedEnvelope,
buildUploadPayload,
buildUploadPatch,
CLOUD_SETTINGS_SYNC_SCHEMA_VERSION,
diffSyncableStorage,
normalizeStorageForSync,
normalizeThemeIdForSync,
} from "./cloudSettingsSync";
import browser from "webextension-polyfill";
describe("calendar credentials stay device-local", () => {
const key = "bsplus_outlook_calendar";
const remoteConnection = { accessToken: "remote-access", refreshToken: "remote-refresh" };
it("excludes Outlook credentials from full and sparse uploads", () => {
const all = { DarkMode: true, [key]: remoteConnection };
expect(buildUploadPayload(all).data).toEqual({ DarkMode: true });
expect(buildUploadPatch(all, { DarkMode: true })).toBeNull();
});
it.each([undefined, { accessToken: "local-access", refreshToken: "local-refresh" }])(
"ignores Outlook credentials in old backups and preserves local connection %p",
async (localConnection) => {
if (localConnection) await browser.storage.local.set({ [key]: localConnection });
await applyDownloadedEnvelope({ data: { DarkMode: false, [key]: remoteConnection } });
const stored = await browser.storage.local.get();
expect(stored.DarkMode).toBe(false);
expect(stored[key]).toEqual(localConnection);
},
);
});
describe("normalizeStorageForSync", () => {
it("strips omitted auth and client-only keys", () => {
+2
View File
@@ -39,6 +39,7 @@ export const KEYS_OMITTED_FROM_CLOUD_UPLOAD = [
"cloudAccessToken",
"cloudUsername",
"bsplus_google_calendar",
"bsplus_outlook_calendar",
/** Anonymous feedback install id — device-local, never synced. */
"bsplus_install_id",
/** Pending feedback ids awaiting a reply notification — device-local. */
@@ -76,6 +77,7 @@ const AUTH_KEYS_TO_PRESERVE = [
"bsplus_client_id",
"bsplus_user",
"bsplus_google_calendar",
"bsplus_outlook_calendar",
] as const;
const OMIT_FROM_UPLOAD_EXACT = new Set<string>([
+1
View File
@@ -16,6 +16,7 @@ export function getDefaultSettingsState(): SettingsState {
return {
onoff: true,
settingsPopupExpanded: false,
animatedbk: true,
bksliderinput: "50",
transparencyEffects: false,
@@ -1,5 +1,134 @@
import { describe, expect, it } from "@jest/globals";
import { appointmentToLesson, parseSeqtaDateTime } from "./fetchTimetable";
import {
afterEach,
beforeEach,
describe,
expect,
it,
jest,
} from "@jest/globals";
import {
appointmentToLesson,
fetchAppointments,
fetchAssessmentsForCalendarSync,
fetchTimetableLessons,
parseSeqtaDateTime,
} from "./fetchTimetable";
describe("calendar source fetches", () => {
const range = { from: "2026-07-20", until: "2026-07-26" };
const sources = [
{
name: "assessments",
path: "/assessment/list/upcoming?",
load: fetchAssessmentsForCalendarSync,
empty: { payload: [] },
},
{
name: "appointments",
path: "/events/load",
load: fetchAppointments,
empty: { payload: [] },
},
{
name: "timetable",
path: "/load/timetable?",
load: fetchTimetableLessons,
empty: { payload: { items: [] } },
},
];
beforeEach(() => {
Object.defineProperty(globalThis, "location", {
configurable: true,
value: {
origin: "https://school.seqta.com.au",
pathname: "/",
hash: "",
href: "https://school.seqta.com.au/",
},
});
Object.defineProperty(globalThis, "document", {
configurable: true,
value: { body: { classList: { contains: () => false } } },
});
});
afterEach(() => jest.restoreAllMocks());
it("uses the same Engage child for timetable and assessment sync", async () => {
document.body.classList.contains = () => true;
const assessmentStudents: unknown[] = [];
const timetableStudents: unknown[] = [];
jest.spyOn(globalThis, "fetch").mockImplementation(async (url, init) => {
const path = String(url);
const body = JSON.parse(String(init?.body));
if (path.endsWith("/seqta/parent/load/timetable")) {
if (body.list)
return Response.json({ payload: [{ id: "42", name: "Child" }] });
timetableStudents.push(body.student);
return Response.json({ payload: { items: [] } });
}
if (path.endsWith("/seqta/parent/assessment/list/upcoming?")) {
assessmentStudents.push(body.student);
return Response.json({
payload: [
{ id: 1, title: "Essay", subject: "English", due: "2026-07-20" },
],
});
}
if (path.includes("/seqta/student/"))
return new Response("Wrong account endpoint", { status: 403 });
return Response.json({ payload: [] });
});
await expect(fetchTimetableLessons(range)).resolves.toEqual([]);
await expect(fetchAssessmentsForCalendarSync(range)).resolves.toMatchObject(
[{ id: 1, title: "Essay" }],
);
expect(timetableStudents).toEqual([42]);
expect(assessmentStudents).toEqual([42]);
});
it.each(sources)(
"rejects failed $name fetches instead of reporting an empty source",
async ({ path, load }) => {
jest.spyOn(globalThis, "fetch").mockImplementation(async (url) => {
if (String(url).endsWith(path))
return new Response("unavailable", { status: 503 });
return Response.json({
payload: String(url).endsWith("/login") ? { id: 12 } : [],
});
});
await expect(load(range)).rejects.toThrow("SEQTA request failed (503)");
},
);
it.each(sources)(
"rejects missing $name payloads that cannot authorize reconciliation",
async ({ path, load }) => {
jest.spyOn(globalThis, "fetch").mockImplementation(async (url) => {
if (String(url).endsWith(path))
return Response.json({ error: "Session expired" });
return Response.json({
payload: String(url).endsWith("/login") ? { id: 12 } : [],
});
});
await expect(load(range)).rejects.toThrow();
},
);
it.each(sources)(
"accepts a successfully fetched empty $name source",
async ({ path, load, empty }) => {
jest.spyOn(globalThis, "fetch").mockImplementation(async (url) => {
if (String(url).endsWith(path)) return Response.json(empty);
return Response.json({
payload: String(url).endsWith("/login") ? { id: 12 } : [],
});
});
await expect(load(range)).resolves.toEqual([]);
},
);
});
describe("parseSeqtaDateTime", () => {
it("parses SEQTA event timestamps", () => {
@@ -96,6 +96,14 @@ async function resolveLoginPayload(): Promise<SeqtaLoginPayload | undefined> {
}
export async function resolveStudentId(): Promise<number | undefined> {
if (isEngageParentContext()) {
const data = await postSeqtaJson<{ payload?: { id?: string | number }[] }>(
"/seqta/parent/load/timetable",
{ list: true },
);
const id = Array.isArray(data?.payload) ? Number(data.payload[0]?.id) : NaN;
return Number.isFinite(id) && id > 0 ? id : undefined;
}
const payload = await resolveLoginPayload();
const id = payload?.id ?? payload?.student;
return typeof id === "number" && Number.isFinite(id) ? id : undefined;
@@ -159,31 +167,31 @@ export function appointmentToLesson(item: SeqtaAppointmentPayload): SeqtaTimetab
export async function fetchAppointments(range: SyncDateRange): Promise<SeqtaTimetableLesson[]> {
if (isEngageParentContext()) return [];
try {
const person = await resolveStudentId();
if (person == null) return [];
const person = await resolveStudentId();
if (person == null)
throw new Error("Could not resolve student for calendar sync.");
const personType = await resolvePersonType();
const data = await postSeqtaJson<{ payload?: SeqtaAppointmentPayload[] }>(
"/seqta/student/events/load",
{
dateFrom: range.from,
dateTo: range.until,
person,
personType,
},
);
const personType = await resolvePersonType();
const data = await postSeqtaJson<{ payload?: SeqtaAppointmentPayload[] }>(
"/seqta/student/events/load",
{
dateFrom: range.from,
dateTo: range.until,
person,
personType,
},
);
const payload = Array.isArray(data?.payload) ? data.payload : [];
const lessons: SeqtaTimetableLesson[] = [];
for (const item of payload) {
const lesson = appointmentToLesson(item);
if (lesson) lessons.push(lesson);
}
return lessons;
} catch {
return [];
if (!Array.isArray(data?.payload)) {
throw new Error("Invalid SEQTA appointments response.");
}
const payload = data.payload;
const lessons: SeqtaTimetableLesson[] = [];
for (const item of payload) {
const lesson = appointmentToLesson(item);
if (lesson) lessons.push(lesson);
}
return lessons;
}
export async function fetchTimetableLessons(
@@ -191,17 +199,11 @@ export async function fetchTimetableLessons(
): Promise<SeqtaTimetableLesson[]> {
const { from, until } = range;
const coloursPromise = fetchSubjectColours();
const appointmentsPromise = fetchAppointments(range);
let lessons: SeqtaTimetableLesson[] = [];
if (isEngageParentContext()) {
const listJson = await postSeqtaJson<{ payload?: { id?: string | number }[] }>(
"/seqta/parent/load/timetable",
{ list: true },
);
const firstChild = Array.isArray(listJson?.payload) ? listJson.payload[0] : undefined;
const studentId = firstChild?.id;
const studentId = await resolveStudentId();
if (studentId == null) {
throw new Error("No student found on this parent account.");
}
@@ -209,7 +211,10 @@ export async function fetchTimetableLessons(
"/seqta/parent/load/timetable",
{ from, until, student: studentId },
);
lessons = Array.isArray(data?.payload?.items) ? data.payload.items : [];
if (!Array.isArray(data?.payload?.items)) {
throw new Error("Invalid SEQTA timetable response.");
}
lessons = data.payload.items;
} else {
const studentId = await resolveStudentId();
const body: Record<string, unknown> = { from, until };
@@ -219,11 +224,14 @@ export async function fetchTimetableLessons(
"/seqta/student/load/timetable?",
body,
);
lessons = Array.isArray(data?.payload?.items) ? data.payload.items : [];
if (!Array.isArray(data?.payload?.items)) {
throw new Error("Invalid SEQTA timetable response.");
}
lessons = data.payload.items;
}
const coloured = withSubjectColours(lessons, await coloursPromise);
const appointments = await appointmentsPromise;
const appointments = await fetchAppointments(range);
return [...coloured, ...appointments];
}
@@ -251,37 +259,38 @@ function assessmentDueInRange(due: string, range: SyncDateRange): boolean {
export async function fetchAssessmentsForCalendarSync(
range: SyncDateRange,
): Promise<CalendarSyncAssessment[]> {
try {
const studentId = await resolveStudentId();
if (studentId == null) return [];
const studentId = await resolveStudentId();
if (studentId == null)
throw new Error("Could not resolve student for calendar sync.");
const path = isEngageParentContext()
? "/seqta/parent/assessment/list/upcoming?"
: "/seqta/student/assessment/list/upcoming?";
const data = await postSeqtaJson<{ payload?: unknown[] }>(path, { student: studentId });
const payload = Array.isArray(data.payload) ? data.payload : [];
const out: CalendarSyncAssessment[] = [];
for (const raw of payload) {
if (!raw || typeof raw !== "object") continue;
const row = raw as Record<string, unknown>;
const id = Number(row.id);
const title = String(row.title ?? "").trim();
const due = parseAssessmentDue(row);
if (!id || !title || !due || !assessmentDueInRange(due, range)) continue;
if (row.status === "MARKS_RELEASED" || row.status === "CANCELLED") continue;
out.push({
id,
title,
subject: String(row.subject ?? row.code ?? "").trim(),
code: String(row.code ?? row.subject ?? "").trim(),
due,
status: row.status != null ? String(row.status) : undefined,
});
}
return out;
} catch (err) {
console.warn("[BetterSEQTA+] Assessment calendar fetch failed:", err);
return [];
const path = isEngageParentContext()
? "/seqta/parent/assessment/list/upcoming?"
: "/seqta/student/assessment/list/upcoming?";
const data = await postSeqtaJson<{ payload?: unknown[] }>(path, {
student: studentId,
});
if (!Array.isArray(data?.payload)) {
throw new Error("Invalid SEQTA assessments response.");
}
const payload = data.payload;
const out: CalendarSyncAssessment[] = [];
for (const raw of payload) {
if (!raw || typeof raw !== "object") continue;
const row = raw as Record<string, unknown>;
const id = Number(row.id);
const title = String(row.title ?? "").trim();
const due = parseAssessmentDue(row);
if (!id || !title || !due || !assessmentDueInRange(due, range)) continue;
if (row.status === "MARKS_RELEASED" || row.status === "CANCELLED") continue;
out.push({
id,
title,
subject: String(row.subject ?? row.code ?? "").trim(),
code: String(row.code ?? row.subject ?? "").trim(),
due,
status: row.status != null ? String(row.status) : undefined,
});
}
return out;
}
@@ -76,7 +76,9 @@ describe("syncLessonsToGoogleCalendar", () => {
});
jest.mocked(upsertGoogleCalendarEvent).mockResolvedValue("google-existing");
jest.mocked(deleteGoogleCalendarEvent).mockResolvedValue(undefined);
jest.mocked(listGoogleSyncedEvents).mockResolvedValue([]);
jest.mocked(listGoogleSyncedEvents).mockResolvedValue([
{ seqtaKey: `${ORIGIN}:cal:12345`, id: "google-existing", date: syncDate, fingerprint: "" },
]);
});
it("updates existing events and removes stale tracked events on full sync", async () => {
@@ -97,6 +99,7 @@ describe("syncLessonsToGoogleCalendar", () => {
});
it("creates events that are not yet tracked", async () => {
jest.mocked(listGoogleSyncedEvents).mockResolvedValue([]);
jest.mocked(readGoogleCalendarState).mockResolvedValue({
refreshToken: "refresh",
calendarId: "app-calendar-id",
@@ -152,6 +155,24 @@ describe("syncLessonsToGoogleCalendar", () => {
});
});
it.each([false, true])("repairs missing remote events only after a complete listing (list failed: %s)", async (listFailed) => {
const mapped = lessonToGoogleEvent(ORIGIN, baseLesson, Intl.DateTimeFormat().resolvedOptions().timeZone)!;
jest.mocked(readGoogleCalendarState).mockResolvedValue({
refreshToken: "refresh", calendarId: "app-calendar-id",
eventMap: { [`${ORIGIN}::${mapped.seqtaKey}`]: { id: "deleted-remotely", date: syncDate, fingerprint: eventFingerprint(mapped) } },
});
if (listFailed) jest.mocked(listGoogleSyncedEvents).mockRejectedValueOnce(new Error("Second page failed"));
else jest.mocked(listGoogleSyncedEvents).mockResolvedValueOnce([]);
const result = await syncLessonsToGoogleCalendar({ origin: ORIGIN, lessons: [baseLesson], mode: "full" }, getAccessToken);
if (listFailed) {
expect(upsertGoogleCalendarEvent).not.toHaveBeenCalled();
expect(result.skipped).toBe(1);
} else {
expect(upsertGoogleCalendarEvent).toHaveBeenCalledWith("test-token", "app-calendar-id", undefined, expect.any(Object), expect.any(Function));
expect(result.created).toBe(1);
}
});
it("deletes cancelled lessons that remain inside the sync window", async () => {
jest.mocked(readGoogleCalendarState).mockResolvedValue({
refreshToken: "refresh",
@@ -0,0 +1,39 @@
/** @jest-environment jsdom */
describe("master extension setting", () => {
afterEach(() => jest.useRealTimers());
it.each([false, true])("persists %s and queued preferences before reloading SEQTA tabs", async (enabled) => {
jest.useFakeTimers();
let browser: any;
let settings: typeof import("./SettingsState");
jest.isolateModules(() => {
browser = require("webextension-polyfill").default;
settings = require("./SettingsState");
});
await browser.storage.local.set({ onoff: !enabled });
await settings!.initializeSettingsState();
browser.runtime.sendMessage.mockClear();
const originalSet = browser.storage.local.set.getMockImplementation();
let finishWrite: () => Promise<void> = async () => {};
browser.storage.local.set.mockImplementationOnce((patch: Record<string, unknown>) => new Promise<void>((resolve) => {
finishWrite = async () => {
await originalSet(patch);
resolve();
};
}));
browser.runtime.sendMessage.mockImplementation(async () => {
expect(await browser.storage.local.get(null)).toMatchObject({ onoff: enabled, selectedFont: "inter" });
});
settings!.settingsState.selectedFont = "inter";
settings!.settingsState.onoff = enabled;
jest.advanceTimersByTime(300);
expect(browser.runtime.sendMessage).not.toHaveBeenCalled();
await finishWrite();
await Promise.resolve();
await Promise.resolve();
expect(browser.runtime.sendMessage).toHaveBeenCalledWith({ type: "reloadTabs" });
});
});
+9 -12
View File
@@ -107,18 +107,7 @@ class StorageManager {
return Reflect.get(target.data, prop);
},
set: (target, prop: keyof SettingsState, value) => {
if (typeof prop === "string" && isExcludedSettingsKey(prop)) {
void browser.storage.local.set({ [prop]: value });
return true;
}
const oldValue = target.data[prop];
// Only save if the reference actually changed
if (oldValue !== value) {
Reflect.set(target.data, prop, value);
void target.saveToStorage([prop as string]);
target.notifySettingChange(prop as string, value, oldValue);
}
target.setKey(prop, value);
return true;
},
deleteProperty: (target, prop: keyof SettingsState) => {
@@ -186,6 +175,13 @@ class StorageManager {
this.data[key] = value;
void this.saveToStorage([key as string]);
this.notifySettingChange(key as string, value, oldValue);
if (key === "onoff" && typeof value === "boolean") {
// Reload only after this switch and any queued preferences reach storage.
// This also covers Settings opened while the extension is disabled.
void this.flushPendingPatch()
.then(() => browser.runtime.sendMessage({ type: "reloadTabs" }))
.catch((error) => console.error("[BetterSEQTA+] Failed to save master setting", error));
}
}
}
@@ -247,6 +243,7 @@ class StorageManager {
}
private async flushPendingPatch(): Promise<void> {
if (this.saveTimeout) clearTimeout(this.saveTimeout);
this.saveTimeout = null;
if (this.bootstrapping || this.suppressWrites) return;
@@ -0,0 +1,37 @@
/** @jest-environment jsdom */
import { settingsState } from "./SettingsState";
import { StorageChangeHandler } from "./StorageChanges";
jest.mock("@/seqta/ui/colors/Manager", () => ({ updateAllColors: jest.fn() }));
jest.mock("@/seqta/utils/Render/renderShortcuts", () => ({
renderShortcuts: jest.fn(),
}));
jest.mock("@/seqta/utils/FilterUpcomingAssessments", () => ({
FilterUpcomingAssessments: jest.fn(),
}));
jest.mock("@/seqta/utils/Loaders/LoadHomePage", () => ({
registerHomeUpcomingSettingsListeners: jest.fn(),
}));
jest.mock("@/seqta/utils/menuItemVisibility", () => ({
scheduleMenuItemVisibility: jest.fn(),
}));
jest.mock("@/seqta/utils/Openers/menuOrder", () => ({
ChangeMenuItemPositions: jest.fn(),
}));
jest.mock("@/seqta/utils/performanceMode", () => ({
syncPerformanceModeEffects: jest.fn(),
}));
test("changing the selected font updates the page without reloading", () => {
new StorageChangeHandler();
settingsState.selectedFont = "inter";
expect(
document.documentElement.style.getPropertyValue(
"--betterseqta-font-family",
),
).toBe("Inter");
expect(
document.getElementById("betterseqta-font-override")?.textContent,
).toContain("font-family: Inter");
});
+1 -7
View File
@@ -1,5 +1,6 @@
import { settingsState } from "./SettingsState";
import { updateAllColors } from "@/seqta/ui/colors/Manager";
import { applySelectedFont } from "@/seqta/ui/fonts/Manager";
// Shortcuts rendering
import { renderShortcuts } from "@/seqta/utils/Render/renderShortcuts";
@@ -9,7 +10,6 @@ import { applyMenuItemVisibility, scheduleMenuItemVisibility } from "@/seqta/uti
import { ChangeMenuItemPositions } from "@/seqta/utils/Openers/menuOrder";
import { syncPerformanceModeEffects } from "@/seqta/utils/performanceMode";
import browser from "webextension-polyfill";
import type { CustomShortcut } from "@/types/storage";
export class StorageChangeHandler {
@@ -26,7 +26,6 @@ export class StorageChangeHandler {
);
settingsState.register("selectedTheme", () => void updateAllColors());
settingsState.register("DarkMode", this.handleDarkModeChange.bind(this));
settingsState.register("onoff", this.handleOnOffChange.bind(this));
settingsState.register("shortcuts", this.handleShortcutsChange.bind(this));
settingsState.register(
"customshortcuts",
@@ -71,11 +70,6 @@ export class StorageChangeHandler {
void updateAllColors();
}
private handleOnOffChange(newValue: boolean) {
if (newValue) return;
browser.runtime.sendMessage({ type: "reloadTabs" });
}
private handleCustomShortcutsChange(newValue: CustomShortcut[] | undefined) {
if (!Array.isArray(newValue)) return;
renderShortcuts();
@@ -0,0 +1,27 @@
/** @jest-environment jsdom */
import { settingsState } from "./listeners/SettingsState";
import {
animateSettingsClose,
animateSettingsOpen,
isSettingsHostVisiblyOpen,
} from "./settingsPopupAnimation";
test("a settings popup reopened during its close animation stays visible", () => {
jest.useFakeTimers();
try {
settingsState.animations = true;
const host = document.createElement("div");
document.body.append(host);
animateSettingsOpen(host);
jest.advanceTimersByTime(20);
animateSettingsClose(host);
jest.advanceTimersByTime(50);
animateSettingsOpen(host);
jest.advanceTimersByTime(250);
expect(isSettingsHostVisiblyOpen(host)).toBe(true);
expect(host.style.opacity).not.toBe("0");
} finally {
jest.useRealTimers();
}
});
+55 -37
View File
@@ -1,3 +1,4 @@
import { animate } from "motion";
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
export const HOST_OPEN_CLASS = "bsplus-settings-host--open";
@@ -19,51 +20,68 @@ function settingsPanel(host: HTMLElement): HTMLElement | null {
return host.shadowRoot?.querySelector<HTMLElement>("[data-settings-panel]") ?? null;
}
export function animateSettingsOpen(host: HTMLElement): void {
host.style.transform = "none";
host.classList.remove(HOST_CLOSING_CLASS, "hide");
const popupAnimations = new WeakMap<HTMLElement, {
progress: number;
animation?: ReturnType<typeof animate>;
}>();
function animatePopup(host: HTMLElement, opening: boolean): void {
const previous = popupAnimations.get(host);
previous?.animation?.stop();
const state = { progress: previous?.progress ?? 0, animation: undefined as ReturnType<typeof animate> | undefined };
popupAnimations.set(host, state);
if (opening) host.dispatchEvent(new Event("bsplus:settings-opening", { bubbles: true }));
const panel = settingsPanel(host);
if (!settingsState.animations) {
host.style.opacity = "1";
host.classList.add(HOST_OPEN_CLASS);
panel?.classList.add(PANEL_OPEN_CLASS);
const backdrop = host.shadowRoot?.querySelector<HTMLElement>(".settings-backdrop");
host.style.transform = "none";
host.style.transition = "none";
host.style.opacity = "1";
host.classList.toggle("hide", !opening);
host.classList.toggle(HOST_OPEN_CLASS, opening);
host.classList.toggle(HOST_CLOSING_CLASS, !opening);
panel?.classList.toggle(PANEL_OPEN_CLASS, opening);
const update = (progress: number) => {
state.progress = progress;
const opacity = String(Math.max(0, Math.min(1, progress)));
if (backdrop) backdrop.style.opacity = opacity;
if (panel) {
panel.style.transition = "none";
panel.style.opacity = opacity;
panel.style.transform = `scale(${Math.max(0, progress)})`;
}
};
const complete = () => {
if (popupAnimations.get(host) !== state) return;
update(opening ? 1 : 0);
if (!opening) {
host.classList.remove(HOST_CLOSING_CLASS);
host.style.opacity = "0";
host.dispatchEvent(new Event("bsplus:settings-hidden", { bubbles: true }));
}
state.animation = undefined;
};
const reducedMotion = window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
if (!panel || !settingsState.animations || settingsState.performanceMode || reducedMotion) {
complete();
return;
}
host.style.opacity = "";
host.classList.remove(HOST_OPEN_CLASS);
panel?.classList.remove(PANEL_OPEN_CLASS);
requestAnimationFrame(() => {
host.classList.add(HOST_OPEN_CLASS);
panel?.classList.add(PANEL_OPEN_CLASS);
update(state.progress);
state.animation = animate(state.progress, opening ? 1 : 0, {
type: "spring",
stiffness: opening ? 280 : 520,
damping: 20,
onUpdate: update,
onComplete: complete,
});
}
export function animateSettingsOpen(host: HTMLElement): void {
animatePopup(host, true);
}
export function animateSettingsClose(host: HTMLElement): void {
host.classList.add("hide");
const panel = settingsPanel(host);
if (!settingsState.animations) {
host.classList.remove(HOST_OPEN_CLASS, HOST_CLOSING_CLASS);
panel?.classList.remove(PANEL_OPEN_CLASS);
host.style.opacity = "0";
return;
}
host.classList.remove(HOST_OPEN_CLASS);
host.classList.add(HOST_CLOSING_CLASS);
panel?.classList.remove(PANEL_OPEN_CLASS);
const durationMs = document.documentElement.classList.contains("performanceMode")
? 160
: 200;
window.setTimeout(() => {
host.classList.remove(HOST_CLOSING_CLASS);
host.style.opacity = "0";
}, durationMs);
animatePopup(host, false);
}
let prefetchStarted = false;
+2
View File
@@ -26,6 +26,8 @@ export interface SettingsState {
};
menuorder: any[];
onoff: boolean;
/** Last popup size explicitly selected with the expand/collapse control. */
settingsPopupExpanded?: boolean;
selectedColor: string;
originalSelectedColor: string;
shortcuts: Shortcut[];