chore: switch to oxlint and oxfmt and tidy ci

This commit is contained in:
Jones Jankovic committed 2026-11-02 20:54:47 +10:30
1 parent 6af30218a5
commit 2b46b1a9da
305 files changed
+3775 -5535

No files matched your search

+9 -1
View File
@@ -1,5 +1,5 @@
name: Run lint
description: Run ESLint on src.
description: Run oxlint, the format check and the type check.
runs:
using: composite
@@ -7,3 +7,11 @@ runs:
- name: Lint
shell: bash
run: npm run lint
- name: Format check
shell: bash
run: npm run format:check
- name: Type check
shell: bash
run: npm run typecheck
@@ -8,6 +8,7 @@ runs:
uses: actions/setup-node@v7
with:
node-version: 26.x
cache: npm
- name: Install dependencies
shell: bash
-1
View File
@@ -22,7 +22,6 @@ jobs:
run:
shell: bash
steps:
- uses: actions/checkout@v7
- name: Set build date
+7 -3
View File
@@ -6,6 +6,13 @@ on:
push:
branches: ["main"]
permissions:
contents: read
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
lint:
# The layerchart Svelte build fails on Linux, so CI runs on Windows.
@@ -22,9 +29,6 @@ jobs:
- name: Run lint
uses: ./.github/actions/run-lint
- name: Type check
run: npm run typecheck
unit-tests:
runs-on: windows-latest
defaults:
-57
View File
@@ -1,57 +0,0 @@
# Manual stable release. Bump the version in package.json on main first.
name: Release
on:
workflow_dispatch:
inputs:
version_updated:
description: I have already updated the version in package.json
type: boolean
required: true
default: false
permissions:
contents: write
env:
GH_TOKEN: ${{ github.token }}
jobs:
release:
runs-on: ubuntu-latest
steps:
- name: Confirm version was updated
if: inputs.version_updated != true
run: |
echo "Check the confirmation box: you must update package.json version before releasing."
exit 1
- uses: actions/checkout@v7
- name: Read version
id: version
run: echo "version=$(node -p "require('./package.json').version")" >> "$GITHUB_OUTPUT"
- name: Build extension
id: build
uses: ./.github/actions/build-extension
with:
gh_release_update_check: "true"
update_channel: stable
release_repo: ${{ github.repository }}
- name: Create release if missing
run: |
if ! gh release view "${{ steps.version.outputs.version }}" 2>/dev/null; then
gh release create "${{ steps.version.outputs.version }}" \
--title "${{ steps.version.outputs.version }}" \
--notes "Edit this release description on GitHub."
fi
- name: Upload release assets
run: |
gh release upload "${{ steps.version.outputs.version }}" \
--clobber \
"${{ steps.build.outputs.chrome_zip }}" \
"${{ steps.build.outputs.firefox_zip }}"
+10
View File
@@ -0,0 +1,10 @@
{
"$schema": "./node_modules/oxfmt/configuration_schema.json",
"ignorePatterns": [
"betterseqtaplus-safari/",
"coverage/",
"dist/",
"package-lock.json",
"src/public/"
]
}
+33
View File
@@ -0,0 +1,33 @@
{
"$schema": "./node_modules/oxlint/configuration_schema.json",
"plugins": ["typescript", "unicorn", "oxc", "import"],
"categories": {
"correctness": "error"
},
"env": {
"builtin": true,
"browser": true,
"node": true
},
"globals": {
"__ENABLE_GH_RELEASE_UPDATE_CHECK__": "readonly",
"__GH_RELEASE_REPO__": "readonly",
"__UPDATE_CHANNEL__": "readonly",
"__BUILD_LABEL__": "readonly",
"__GOOGLE_OAUTH_CLIENT_ID__": "readonly",
"__OUTLOOK_OAUTH_CLIENT_ID__": "readonly"
},
"rules": {
"no-unused-vars": [
"error",
{
"ignoreRestSiblings": true,
"argsIgnorePattern": "^_",
"varsIgnorePattern": "^_",
"caughtErrors": "none"
}
],
"import/default": "off"
},
"ignorePatterns": ["src/public/**"]
}
-5
View File
@@ -1,5 +0,0 @@
betterseqtaplus-safari/
coverage/
dist/
package-lock.json
src/public/
-5
View File
@@ -1,5 +0,0 @@
{
"tabWidth": 2,
"useTabs": false,
"semi": true
}
+2 -1
View File
@@ -24,7 +24,7 @@ For Firefox, run `npm run dev:firefox` and load `dist/firefox` from `about:debug
## Project layout
| Path | What's in it |
|------|--------------|
| -------------------------------------- | --------------------------------------------- |
| `src/SEQTA.ts` | Content script entry point |
| `src/background.ts`, `src/background/` | Service worker |
| `src/seqta/` | Everything injected into SEQTA pages |
@@ -43,6 +43,7 @@ The [architecture guide](https://docs.betterseqta.org/architecture/) goes into m
4. Before opening the PR, check everything passes:
```bash
npm run format
npm run lint
npm run typecheck
npm test
+74 -74
View File
@@ -69,7 +69,7 @@ Cloud settings sync is a **whole-snapshot backup** of extension local storage:
### When upload runs
| Trigger | Behaviour |
|---------|-----------|
| ------------------------------------------------------ | --------------------------------------------------------- |
| Any **included** `chrome.storage.local` key changes | Debounced upload after **2000 ms** (`UPLOAD_DEBOUNCE_MS`) |
| Manual upload (settings UI) | Immediate `PUT` |
| First poll with no cloud backup and no local watermark | Baseline upload |
@@ -84,7 +84,7 @@ Upload is skipped when:
### When download runs
| Trigger | Behaviour |
|---------|-----------|
| --------------------------------------------- | --------------------------------------------------------------------------------------- |
| Manual restore (settings UI) | `GET` → `applyDownloadedEnvelope` → theme prefetch → reload SEQTA tabs |
| Auto poll | If `bsplus.updated_at` from `GET /api/user/cloud-summary` is newer than local watermark |
| First poll with cloud backup but no watermark | Full download |
@@ -113,7 +113,7 @@ After download, if `themeId` / `selectedTheme` is non-empty, the service worker
`ensureSyncableStorageDefaults()` (`src/seqta/utils/ensureSyncableStorageDefaults.ts`) ensures every **cloud-syncable** key exists in `chrome.storage.local` with its default value if it was previously absent. This runs **locally only** so diffs against the last-uploaded snapshot (or schema defaults) are consistent. The PUT body is a **sparse patch** of changed keys only — defaults are not bulk-uploaded.
| When it runs | Context |
|--------------|---------|
| ----------------------------- | ----------------------------------------------------------- |
| `browser.runtime.onInstalled` | Service worker (install + update) |
| `browser.runtime.onStartup` | Service worker |
| Service worker load | `background.ts` (once at startup) |
@@ -156,7 +156,7 @@ Content-Type: application/json
Only keys that changed since the last successful upload appear in `data`. The server merges this patch into stored JSON; omitted keys are not deleted. Dev JSON export (`getSnapshotForUpload`) still returns the full normalized map for debugging.
| Top-level field | JSON type | Rules |
|-----------------|-----------|-------|
| --------------- | --------- | --------------------------------------------------------------------------------------------------------------------------- |
| `schemaVersion` | `number` | Always `1` today (`CLOUD_SETTINGS_SYNC_SCHEMA_VERSION`) |
| `themeId` | `string` | `normalizeThemeIdForSync(selectedTheme)` — trimmed; `""` if unset/invalid |
| `data` | `object` | Flat map: storage key → value. Same types as `chrome.storage.local`. No nesting convention beyond whatever each key stores. |
@@ -169,7 +169,7 @@ Same shape as the PUT body, plus optional:
{
"schemaVersion": 1,
"themeId": "…",
"data": { },
"data": {},
"updated_at": "2026-04-07T12:00:00.000Z"
}
```
@@ -192,7 +192,7 @@ Same shape as the PUT body, plus optional:
Every persisted setting is a **top-level key** in `chrome.storage.local`:
| Pattern | Example | Value shape |
|---------|---------|---------------|
| --------------- | ------------------------------------------------------- | -------------------------------------------- |
| Core setting | `DarkMode` | scalar or structured JSON |
| Plugin settings | `plugin.global-search.settings` | single JSON **object** with all plugin prefs |
| Plugin storage | `plugin.messageFolders.storage.folders` | one JSON value per property |
@@ -205,7 +205,7 @@ Plugin runtime storage uses `plugin.{pluginId}.storage.{propertyName}` — each
### Settings vs storage
| Mechanism | API | Persisted keys | Synced? |
|-----------|-----|----------------|---------|
| --------------------------------- | -------------------------------------- | ---------------------------------------- | ----------------------------- |
| `settingsState` / `SettingsState` | Proxy over in-memory + `storage.local` | Top-level keys (`onoff`, `menuitems`, …) | Yes (unless excluded) |
| Plugin `api.settings` | Proxy; one object per plugin | `plugin.{id}.settings` | Yes |
| Plugin `api.storage` | Proxy; one key per property | `plugin.{id}.storage.{prop}` | Yes, except excluded prefixes |
@@ -221,7 +221,7 @@ Implemented in `shouldOmitKeyFromCloudPayload(key)`:
### Exact key exclusions
| Key | Format if present locally | On restore |
|-----|---------------------------|------------|
| ------------------------------------------------ | ---------------------------------- | ----------------- |
| `bsplus_token` | `string` JWT | Keep device value |
| `bsplus_refresh_token` | `string` | Keep device value |
| `bsplus_client_id` | `string` UUID | Keep device value |
@@ -244,7 +244,7 @@ Implemented in `shouldOmitKeyFromCloudPayload(key)`:
"username": "optional",
"displayName": "optional",
"pfpUrl": "https://…",
"pfpHash": "abc123" ,
"pfpHash": "abc123",
"admin_level": 0
}
```
@@ -254,7 +254,7 @@ All fields except `id` are optional.
### Prefix exclusions
| Prefix | Matches |
|--------|---------|
| ------------------------------- | ------------------------------------------- |
| `plugin.global-search.storage.` | Any Global Search device cache key |
| `bsplus.analytics.` | Grade Analytics caches and chart mode prefs |
@@ -267,7 +267,7 @@ Prefix check: `key.startsWith(prefix)`.
Runs in `migrateLegacyToPluginSettings()` on **both** upload and download. Legacy keys are **removed** from `data` after migration. Migration only fills plugin settings fields that are still `undefined`.
| Legacy key | Legacy format | Target key | Target field | Conversion |
|------------|---------------|------------|--------------|------------|
| ----------------------- | ---------------------- | --------------------------------------- | ------------- | ------------------------------------------------------------------------------------ |
| `animatedbk` | `boolean` | `plugin.animated-background.settings` | `enabled` | `!!animatedbk` |
| `bksliderinput` | `string` `"0"`–`"100"` | `plugin.animated-background.settings` | `speed` | `speed = round((0.1 + (parseFloat(s) / 100) * 1.9) * 100) / 100` → range **0.1–2.0** |
| `assessmentsAverage` | `boolean` | `plugin.assessments-average.settings` | `enabled` | `!!assessmentsAverage` |
@@ -289,7 +289,7 @@ Top-level `chrome.storage.local` keys from `SettingsState` (`src/types/storage.t
#### `onoff`
| | |
|-|-|
| ----------- | --------------------------------------- |
| **Type** | `boolean` |
| **Default** | `true` |
| **UI** | Settings → “BetterSEQTA+” master switch |
@@ -298,7 +298,7 @@ Top-level `chrome.storage.local` keys from `SettingsState` (`src/types/storage.t
#### `DarkMode`
| | |
|-|-|
| ----------- | ----------------------- |
| **Type** | `boolean` |
| **Default** | `true` |
| **UI** | SEQTA UI / theme system |
@@ -307,7 +307,7 @@ Top-level `chrome.storage.local` keys from `SettingsState` (`src/types/storage.t
#### `selectedTheme`
| | |
|-|-|
| ----------- | ------------------------------------------------------------------------------------------------ |
| **Type** | `string` |
| **Default** | `""` |
| **UI** | Theme selector / store install |
@@ -320,7 +320,7 @@ Theme **asset blobs** (CSS, images) live in **localforage/IndexedDB**, not in th
#### `selectedColor`
| | |
|-|-|
| ----------- | -------------------------------------------------------------------------------------------------- |
| **Type** | `string` |
| **Default** | `"linear-gradient(40deg, rgba(201,61,0,1) 0%, RGBA(170, 5, 58, 1) 100%)"` |
| **UI** | Colour picker |
@@ -330,7 +330,7 @@ Theme **asset blobs** (CSS, images) live in **localforage/IndexedDB**, not in th
#### `originalSelectedColor`
| | |
|-|-|
| ----------- | --------------------------------------------------------- |
| **Type** | `string` |
| **Default** | `""` |
| **Purpose** | Colour before theme preview; restored when clearing theme |
@@ -339,7 +339,7 @@ Theme **asset blobs** (CSS, images) live in **localforage/IndexedDB**, not in th
#### `originalDarkMode`
| | |
|-|-|
| ----------- | ------------------------------ |
| **Type** | `boolean` |
| **Default** | undefined until theme preview |
| **Purpose** | Dark mode before theme preview |
@@ -348,7 +348,7 @@ Theme **asset blobs** (CSS, images) live in **localforage/IndexedDB**, not in th
#### `transparencyEffects`
| | |
|-|-|
| ----------- | ------------------------------- |
| **Type** | `boolean` |
| **Default** | `false` |
| **UI** | Settings → Transparency Effects |
@@ -357,7 +357,7 @@ Theme **asset blobs** (CSS, images) live in **localforage/IndexedDB**, not in th
#### `animations`
| | |
|-|-|
| ----------- | ----------------------------------------------------------------------------------------------- |
| **Type** | `boolean` |
| **Default** | `true` on normal devices; `false` if low-end (`hardwareConcurrency < 4` or `deviceMemory <= 2`) |
| **UI** | Settings → Animations |
@@ -366,7 +366,7 @@ Theme **asset blobs** (CSS, images) live in **localforage/IndexedDB**, not in th
#### `iconOnlySidebar`
| | |
|-|-|
| ----------- | ---------------------------- |
| **Type** | `boolean` |
| **Default** | `false` |
| **UI** | Settings → Icon Only Sidebar |
@@ -375,7 +375,7 @@ Theme **asset blobs** (CSS, images) live in **localforage/IndexedDB**, not in th
#### `selectedFont`
| | |
|-|-|
| ----------- | --------------------------------------------------- |
| **Type** | `string` |
| **Default** | undefined → runtime treats as `"rubik"` |
| **UI** | Settings → Interface Font |
@@ -390,7 +390,7 @@ Allowed ids:
#### `adaptiveThemeColour`
| | |
|-|-|
| ----------- | --------- |
| **Type** | `boolean` |
| **Default** | `false` |
| **Example** | `false` |
@@ -398,7 +398,7 @@ Allowed ids:
#### `adaptiveThemeGradient`
| | |
|-|-|
| ----------- | --------- |
| **Type** | `boolean` |
| **Default** | `false` |
| **Example** | `false` |
@@ -406,7 +406,7 @@ Allowed ids:
#### `adaptiveThemeColourTransition`
| | |
|-|-|
| ----------- | --------- |
| **Type** | `boolean` |
| **Default** | `true` |
| **Example** | `true` |
@@ -416,7 +416,7 @@ Allowed ids:
#### `defaultPage`
| | |
|-|-|
| ----------- | --------------------------------------------------------------------------------------------- |
| **Type** | `string` |
| **Default** | `"home"` |
| **UI** | Settings → Default Page |
@@ -426,7 +426,7 @@ Allowed ids:
#### `timeFormat`
| | |
|-|-|
| ----------- | ----------------------------------------- |
| **Type** | `string` |
| **Default** | undefined (24-hour behaviour) |
| **UI** | Settings → “12 Hour Time” switch |
@@ -436,7 +436,7 @@ Allowed ids:
#### `lessonalert`
| | |
|-|-|
| ----------- | ------------------------- |
| **Type** | `boolean` |
| **Default** | `true` |
| **Purpose** | Lesson alert on home page |
@@ -445,7 +445,7 @@ Allowed ids:
#### `menuitems`
| | |
|-|-|
| ----------- | ------------------------------------ |
| **Type** | `object` |
| **Default** | All sidebar items `{ toggle: true }` |
| **UI** | Menu editor overlay |
@@ -468,7 +468,7 @@ Keys (from `SettingsState`):
#### `menuorder`
| | |
|-|-|
| ------------- | --------------------------------------------------------------------------------------------------------------- |
| **Type** | `array` |
| **Default** | `[]` |
| **UI** | Menu editor (drag order) |
@@ -478,7 +478,7 @@ Keys (from `SettingsState`):
#### `defaultmenuorder`
| | |
|-|-|
| ------------- | ------------------------------------------------------ |
| **Type** | `array` |
| **Default** | `[]` (populated from DOM on first menu edit) |
| **Item type** | Same as `menuorder` — snapshot of school default order |
@@ -489,7 +489,7 @@ Keys (from `SettingsState`):
#### `shortcuts`
| | |
|-|-|
| -------------- | ------------------------------------------------------------------------------------- |
| **Type** | `array` |
| **Default** | Outlook, Office, Google — each `enabled: true` |
| **UI** | Settings → Shortcuts |
@@ -509,7 +509,7 @@ Keys (from `SettingsState`):
#### `customshortcuts`
| | |
|-|-|
| -------------- | --------------------------------------------------------------------------------- |
| **Type** | `array` |
| **Default** | `[]` |
| **UI** | Settings → Shortcuts → add custom |
@@ -534,7 +534,7 @@ Keys (from `SettingsState`):
#### `subjectfilters`
| | |
|-|-|
| ----------- | ----------------------------------------------------------------------------------- |
| **Type** | `object` |
| **Default** | `{}` |
| **UI** | Home / assessments subject filters |
@@ -544,7 +544,7 @@ Keys (from `SettingsState`):
#### `newsSource`
| | |
|-|-|
| ----------- | -------------------------------------------------------------------------------------------------------- |
| **Type** | `string` |
| **Default** | `"australia"` |
| **UI** | Settings → News Feed Source |
@@ -556,7 +556,7 @@ Keys (from `SettingsState`):
#### `autoCloudSettingsSync`
| | |
|-|-|
| ------------- | ---------------------------------------------------- |
| **Type** | `boolean` |
| **Default** | `true` |
| **UI** | Settings → Cloud Settings Sync |
@@ -568,7 +568,7 @@ Keys (from `SettingsState`):
#### `themeOfTheMonthDisabled`
| | |
|-|-|
| ----------- | ------------------------------------------------------------------------- |
| **Type** | `boolean` |
| **Default** | `false` |
| **UI** | Global Search plugin section → Theme of the Month switch (inverted in UI) |
@@ -577,7 +577,7 @@ Keys (from `SettingsState`):
#### `themeOfTheMonthDismissedMonth`
| | |
|-|-|
| ----------- | -------------------------- |
| **Type** | `string` |
| **Format** | `"YYYY-MM"` calendar month |
| **Example** | `"2026-06"` |
@@ -585,7 +585,7 @@ Keys (from `SettingsState`):
#### `themeOfTheMonthLastSeenId`
| | |
|-|-|
| ---------- | ------------------------------------------- |
| **Type** | `string` |
| **Status** | Deprecated; may still exist in old profiles |
| **Synced** | Yes if present |
@@ -595,28 +595,28 @@ Keys (from `SettingsState`):
#### `privacyStatementShown`
| | |
|-|-|
| ----------- | --------- |
| **Type** | `boolean` |
| **Example** | `true` |
#### `privacyStatementLastUpdated`
| | |
|-|-|
| ---------- | ----------------------------- |
| **Type** | `string` |
| **Format** | ISO date, e.g. `"2025-12-20"` |
#### `engageParentsAnnouncementShown`
| | |
|-|-|
| ----------- | ------------------------------------------- |
| **Type** | `boolean` |
| **Purpose** | SEQTA Engage parents announcement dismissed |
#### `bsCloudAutoSyncAnnouncementShown`
| | |
|-|-|
| ----------- | -------------------------------------- |
| **Type** | `boolean` |
| **Purpose** | Cloud auto-sync announcement dismissed |
@@ -625,7 +625,7 @@ Keys (from `SettingsState`):
#### `justupdated`
| | |
|-|-|
| ----------- | ------------------------------------------------------------- |
| **Type** | `boolean` |
| **Purpose** | Set `true` after extension update; drives startup popup queue |
| **Example** | `true` |
@@ -633,7 +633,7 @@ Keys (from `SettingsState`):
#### `devMode`
| | |
|-|-|
| ----------- | ------------------------- |
| **Type** | `boolean` |
| **Default** | undefined / false |
| **UI** | Hidden unlock in settings |
@@ -642,7 +642,7 @@ Keys (from `SettingsState`):
#### `hideSensitiveContent`
| | |
|-|-|
| ----------- | -------------------------- |
| **Type** | `boolean` |
| **UI** | Dev mode → Sensitive Hider |
| **Example** | `false` |
@@ -650,7 +650,7 @@ Keys (from `SettingsState`):
#### `mockNotices`
| | |
|-|-|
| ----------- | ----------------------- |
| **Type** | `boolean` |
| **UI** | Dev mode → Mock Notices |
| **Example** | `false` |
@@ -658,7 +658,7 @@ Keys (from `SettingsState`):
#### `devGhReleaseVersionOverride`
| | |
|-|-|
| ----------- | --------------------------------- |
| **Type** | `string` |
| **UI** | Dev mode → version override field |
| **Format** | Semver string, e.g. `"3.7.0"` |
@@ -667,7 +667,7 @@ Keys (from `SettingsState`):
#### `lastSeenNightlyPublishedAt`
| | |
|-|-|
| ----------- | ----------------------------------------------------- |
| **Type** | `string` |
| **Format** | ISO 8601 timestamp from GitHub release `published_at` |
| **Example** | `"2026-06-01T04:30:00Z"` |
@@ -677,7 +677,7 @@ Keys (from `SettingsState`):
#### `profile_picture_revision`
| | |
|-|-|
| ----------- | ------------------------------------------------------------------------- |
| **Type** | `number` |
| **Purpose** | Incremented when cloud/local profile picture changes; triggers UI refresh |
| **Not** | The image itself (stored in localforage `profile-picture-store`) |
@@ -694,7 +694,7 @@ Settings of type `component` or `button` are **not** auto-persisted by the plugi
### `plugin.animated-background.settings`
| Field | Type | Default | Range / notes |
|-------|------|---------|---------------|
| --------- | --------- | ------- | ---------------------------- |
| `enabled` | `boolean` | `true` | From `disableToggle` UI |
| `speed` | `number` | `1` | **0.1–2.0**, step 0.05 in UI |
@@ -705,7 +705,7 @@ Settings of type `component` or `button` are **not** auto-persisted by the plugi
### `plugin.assessments-average.settings`
| Field | Type | Default |
|-------|------|---------|
| ------------- | --------- | ------- |
| `enabled` | `boolean` | `false` |
| `lettergrade` | `boolean` | `false` |
@@ -716,7 +716,7 @@ Settings of type `component` or `button` are **not** auto-persisted by the plugi
### `plugin.notificationCollector.settings`
| Field | Type | Default |
|-------|------|---------|
| --------- | --------- | ------- |
| `enabled` | `boolean` | `true` |
```json
@@ -726,7 +726,7 @@ Settings of type `component` or `button` are **not** auto-persisted by the plugi
### `plugin.timetable.settings`
| Field | Type | Default |
|-------|------|---------|
| --------- | --------- | ------- |
| `enabled` | `boolean` | `true` |
```json
@@ -736,7 +736,7 @@ Settings of type `component` or `button` are **not** auto-persisted by the plugi
### `plugin.timetableEdit.settings`
| Field | Type | Default |
|-------|------|---------|
| --------- | --------- | ------- |
| `enabled` | `boolean` | `true` |
```json
@@ -746,7 +746,7 @@ Settings of type `component` or `button` are **not** auto-persisted by the plugi
### `plugin.global-search.settings`
| Field | Type | Default | Notes |
|-------|------|---------|-------|
| --------------------- | --------- | ----------------------- | ----------------------- |
| `enabled` | `boolean` | `false` | Plugin default off |
| `searchHotkey` | `string` | `"ctrl+k"` or `"cmd+k"` | See hotkey format below |
| `showRecentFirst` | `boolean` | `true` | |
@@ -776,7 +776,7 @@ Settings of type `component` or `button` are **not** auto-persisted by the plugi
### `plugin.profile-picture.settings`
| Field | Type | Default |
|-------|------|---------|
| ------------- | --------- | ------- |
| `enabled` | `boolean` | `false` |
| `useCloudPfp` | `boolean` | `false` |
@@ -789,7 +789,7 @@ When `useCloudPfp` is true, avatar URL comes from `bsplus_user.pfpUrl` (local au
### `plugin.messageFolders.settings`
| Field | Type | Default |
|-------|------|---------|
| --------------------------- | --------- | ------- |
| `enabled` | `boolean` | `true` |
| `showTagsInAllMessages` | `boolean` | `true` |
| `hideFolderedMessagesInAll` | `boolean` | `true` |
@@ -805,7 +805,7 @@ When `useCloudPfp` is true, avatar URL comes from `bsplus_user.pfpUrl` (local au
### `plugin.enhanced-navigation.settings`
| Field | Type | Default |
|-------|------|---------|
| ------------------- | --------- | ------- |
| `enabled` | `boolean` | `true` |
| `autoScrollOnClick` | `boolean` | `false` |
@@ -816,7 +816,7 @@ When `useCloudPfp` is true, avatar URL comes from `bsplus_user.pfpUrl` (local au
### `plugin.background-music.settings`
| Field | Type | Default | Range |
|-------|------|---------|-------|
| --------------- | --------- | ------- | ----- |
| `enabled` | `boolean` | `false` | |
| `volume` | `number` | `0.5` | 0–1 |
| `pauseOnHidden` | `boolean` | `true` | |
@@ -830,7 +830,7 @@ Audio blob: localforage `background-music-store` / `music` / key `audio-blob`
### `plugin.grade-analytics.settings`
| Field | Type | Default | Range |
|-------|------|---------|-------|
| --------------- | -------- | ------- | ----- |
| `cacheTtlHours` | `number` | `24` | 1–168 |
```json
@@ -866,7 +866,7 @@ Separate top-level keys per property: `plugin.{pluginId}.storage.{propertyName}`
```
| Field | Type | Notes |
|-------|------|-------|
| ------- | -------- | ------------------------------------------ |
| `id` | `string` | `Date.now().toString(36) + random` |
| `name` | `string` | Display name |
| `color` | `string` | Hex colour from preset palette |
@@ -947,7 +947,7 @@ Title → assessment id map (school data):
```
| Field | Type | Notes |
|-------|------|-------|
| --------------- | --------- | --------------------------------------------- |
| `weight` | `string` | e.g. `"25"`, `"processing"`, `"N/A"` |
| `fingerprint` | `string` | JSON-stringified assessment state fingerprint |
| `pluginVersion` | `number` | `WEIGHTING_SCHEMA_VERSION` (= 1) |
@@ -956,7 +956,7 @@ Title → assessment id map (school data):
### Notification Collector (`plugin.notificationCollector`)
| Key | Type | Example |
|-----|------|---------|
| ------------------------------------------------------------ | -------- | ---------------------------- |
| `plugin.notificationCollector.storage.lastNotificationCount` | `number` | `3` |
| `plugin.notificationCollector.storage.consecutiveErrors` | `number` | `0` |
| `plugin.notificationCollector.storage.lastCheckedTime` | `string` | `"2026-06-09T14:30:00.000Z"` |
@@ -1019,7 +1019,7 @@ Reserved for future device-local caches. No keys in use today; any key matching
These affect UX but **never** appear in the cloud `data` blob:
| Store | Location | Contents |
|-------|----------|----------|
| ------------------------------ | ------------------------------------------------------------- | ------------------------------------------------------------- |
| Global Search structured index | IndexedDB `betterseqta-index` | Searchable page text |
| Global Search vectors | IndexedDB `embeddiaDB` | Embedding index |
| Global Search schema version | `localStorage` key `betterseqta-index-version` | Index migration |
@@ -1039,7 +1039,7 @@ After cloud restore, devices may need to **rebuild** indexes, **re-upload** medi
### Inclusion test
```ts
isKeyIncludedInCloudUploadPayload(key) === !shouldOmitKeyFromCloudPayload(key)
isKeyIncludedInCloudUploadPayload(key) === !shouldOmitKeyFromCloudPayload(key);
```
Any new `chrome.storage.local` key syncs automatically unless added to:
@@ -1077,7 +1077,7 @@ Which synced keys can be changed directly by the user in the extension **setting
### Extension popup — Settings tab (`general.svelte`)
| Storage key / path | UI label | Control |
|--------------------|----------|---------|
| -------------------------------------------- | ------------------------ | ----------------------------------------------------------------- |
| `iconOnlySidebar` | Icon Only Sidebar | Switch |
| `animations` | Animations | Switch |
| `timeFormat` | 12 Hour Time | Switch (`"12"` / `"24"`) |
@@ -1099,7 +1099,7 @@ Which synced keys can be changed directly by the user in the extension **setting
Each row is `plugin.{id}.settings.{field}` unless noted. Component settings (upload UIs) change synced **preference** keys but not blob data in IndexedDB.
| Plugin | UI | Synced fields from UI |
|--------|-----|------------------------|
| -------------------------- | ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| **Animated Background** | Enable + Animation Speed slider | `enabled`, `speed` |
| **Assessment Averages** | Enable (+ disclaimer) + Letter Grades | `enabled`, `lettergrade` |
| **Notification Collector** | Enable only | `enabled` |
@@ -1120,7 +1120,7 @@ Each row is `plugin.{id}.settings.{field}` unless noted. Component settings (upl
#### Dev mode only (Settings tab, after typing “dev” on logo)
| Storage key | UI label |
|-------------|----------|
| ------------------------------------------------------ | ------------------------------------------------ |
| `devMode` | Developer Mode |
| `hideSensitiveContent` | Sensitive Hider |
| `mockNotices` | Mock Notices |
@@ -1132,7 +1132,7 @@ Dev **Export cloud settings JSON** downloads the upload payload; it does not cha
### Extension popup — Shortcuts tab (`shortcuts.svelte`)
| Storage key | UI |
|-------------|-----|
| ----------------- | ------------------------------------------------------------------------ |
| `shortcuts` | Toggle built-in shortcuts (Outlook, Office, Google, … from `links.json`) |
| `customshortcuts` | Add / delete custom shortcuts (name, URL, optional SVG icon) |
@@ -1141,7 +1141,7 @@ Changes use `settingsState.setKey()` so the SEQTA home page updates immediately
### Extension popup — Themes tab (`theme.svelte`)
| Storage key | UI |
|-------------|-----|
| ------------------------------------------- | --------------------------------------------------------------------------------- |
| `selectedTheme` | Install / select / clear store themes (`ThemeSelector`) |
| `selectedColor` | May change when applying a theme with a default colour |
| `originalSelectedColor`, `originalDarkMode` | Set internally during theme **preview** in theme manager (not dedicated controls) |
@@ -1151,7 +1151,7 @@ Animated background selection uses `BackgroundSelector` (local/custom background
### SEQTA page UI (outside settings popup)
| Storage key / path | Where | Control |
|--------------------|-------|---------|
| ---------------------------------------------------------- | --------------------------- | --------------------------------------------------------------- |
| `DarkMode` | SEQTA top bar | Sun/moon **Light/Dark** button |
| `menuorder`, `menuitems` | SEQTA sidebar | **Edit Sidebar Layout** overlay (drag order + per-item toggles) |
| `subjectfilters` | Home → upcoming assessments | Per-subject checkboxes (`#upcoming-filters`) |
@@ -1166,7 +1166,7 @@ Animated background selection uses `BackgroundSelector` (local/custom background
### Automatic / popup-only (synced, no dedicated settings control)
| Storage key / path | How it changes |
|--------------------|----------------|
| ------------------------------------------------------ | -------------------------------------------------- |
| `lessonalert` | Default only — **no UI** (read by home loader) |
| `privacyStatementShown`, `privacyStatementLastUpdated` | Privacy popup on first run (dev can reset) |
| `engageParentsAnnouncementShown` | Dismiss Engage parents announcement |
@@ -1181,7 +1181,7 @@ Animated background selection uses `BackgroundSelector` (local/custom background
### Synced plugin prefs with UI vs storage-only side effects
| User action in UI | Synced | Not synced |
|-------------------|--------|------------|
| -------------------------- | --------------------------------------------------- | -------------------------------------------------- |
| Upload profile picture | `useCloudPfp`, `profile_picture_revision` | Image blob (localforage) |
| Upload background music | `enabled`, `volume`, `pauseOnHidden` | Audio blob (localforage) |
| Install store theme | `selectedTheme`, often `selectedColor` / `DarkMode` | Theme assets (localforage) |
@@ -1208,7 +1208,7 @@ Implementation: `ensureSyncableStorageDefaults()` + `getSyncableStorageDefaults(
### What is not auto-initialized
| Category | Reason |
|----------|--------|
| ---------------------------------------------------------------- | ------------------------------------------------------------- |
| OAuth / session keys | Excluded from cloud; device-local |
| `plugin.*.storage.*` runtime data | Created when plugins run (folders, timetable overrides, etc.) |
| `bsplus.analytics.*` | Excluded device/school caches |
+3 -3
View File
@@ -74,7 +74,7 @@ Returns the caller’s latest settings backup.
{
"schemaVersion": 1,
"themeId": "uuid-string-or-empty",
"data": { },
"data": {},
"updated_at": "2026-04-07T12:00:00.000Z"
}
```
@@ -97,9 +97,9 @@ The extension resolves **`themeId`** (if non-empty), else **`data.selectedTheme`
Example relational layout:
| Column | Type | Notes |
|---------------|-------------|--------|
| ------------ | ------------ | -------------------------------------------------------------------------------------- |
| `user_id` | FK → users | Unique per backup row (one row per user). |
| `payload` | JSON / JSONB| Store `{ "schemaVersion", "data" }` or only `data` + separate `schema_version` column. |
| `payload` | JSON / JSONB | Store `{ "schemaVersion", "data" }` or only `data` + separate `schema_version` column. |
| `updated_at` | timestamptz | Set on each successful `PUT`. |
Unique constraint on `user_id`.
+1 -1
View File
@@ -3,7 +3,7 @@
The main documentation lives at **[docs.betterseqta.org](https://docs.betterseqta.org/)**, built from [BetterSEQTA-Docs](https://github.com/BetterSEQTA/BetterSEQTA-Docs). Send fixes for those pages there.
| Topic | Where |
|-------|-------|
| --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Installing | [docs.betterseqta.org/install](https://docs.betterseqta.org/install/) |
| Architecture | [docs.betterseqta.org/architecture](https://docs.betterseqta.org/architecture/) |
| Writing plugins | [Plugin development](https://docs.betterseqta.org/plugin-development/), [Plugin API](https://docs.betterseqta.org/plugin-api/), [Example plugin](https://docs.betterseqta.org/example-plugin/) |
+15 -14
View File
@@ -5,20 +5,25 @@ BetterSEQTA+ ships through the Chrome Web Store and Firefox Add-ons. GitHub also
## Workflows
| Workflow | Runs on | What it does |
|----------|---------|--------------|
| ------------------------------------------------- | ---------------------------------------------------------------- | ----------------------------------------------------------------------------- |
| [`pr-ci.yml`](../.github/workflows/pr-ci.yml) | Every pull request and push to `main` | Lint, unit tests, then build and smoke test. Uploads the zips as an artifact. |
| [`nightly.yml`](../.github/workflows/nightly.yml) | Daily at 13:30 UTC (midnight in Adelaide during daylight saving) | Builds `main` and replaces the assets on the `nightly` prerelease. |
| [`release.yml`](../.github/workflows/release.yml) | Manually only | Builds the version in `package.json` and publishes it as a release with that tag. |
Every build goes through the shared [`build-extension`](../.github/actions/build-extension/action.yml) action: install with `npm ci`, run `npm run build` for Chrome and Firefox, then zip `dist/chrome` and `dist/firefox`. The release workflows publish with the default `GITHUB_TOKEN`, so they need no extra secrets.
Both build through the shared [`build-extension`](../.github/actions/build-extension/action.yml) action: install with `npm ci`, run `npm run build` for Chrome and Firefox, then zip `dist/chrome` and `dist/firefox`. Nightly publishes with the default `GITHUB_TOKEN`, so it needs no extra secrets.
## Publishing a stable release
1. Bump `version` in `package.json` on `main` and push it.
2. Go to Actions → **Release** → **Run workflow** and tick the confirmation box.
3. On the first run for a version, edit the release title and notes on GitHub afterwards.
Stable releases are published by hand:
Running it again for the same version only replaces the zips (`betterseqtaplus@{version}-chrome.zip` and `-firefox.zip`).
1. Bump `version` in `package.json` on `main` and push it.
2. Build with the update checker, then zip:
```bash
GH_RELEASE_UPDATE_CHECK=true UPDATE_CHANNEL=stable npm run build
npm run zip
```
3. Run `npm run release`. It creates the release for that version with generated notes and uploads `betterseqtaplus@{version}-chrome.zip` and `-firefox.zip`.
## Nightly builds
@@ -30,20 +35,16 @@ GitHub builds are for sideloading only. Never upload them to an extension store.
## Build-time flags
Release workflows pass these into Vite, which bakes them in through `define` in [`vite.config.ts`](../vite.config.ts). Their types live in [`src/env.d.ts`](../src/env.d.ts).
Release builds pass these into Vite, which bakes them in through `define` in [`vite.config.ts`](../vite.config.ts). Their types live in [`src/env.d.ts`](../src/env.d.ts).
| Variable | Stable | Nightly | PRs and local builds |
|----------|--------|---------|----------------------|
| ------------------------- | ------------------------------ | -------------- | -------------------- |
| `GH_RELEASE_UPDATE_CHECK` | `true` | `true` | unset |
| `UPDATE_CHANNEL` | `stable` | `nightly` | unset |
| `GH_RELEASE_REPO` | `BetterSEQTA/BetterSEQTA-Plus` | same | same |
| `BUILD_LABEL` | empty | UTC build date | empty |
Without `GH_RELEASE_UPDATE_CHECK=true`, the update checker is removed from the bundle entirely. To try a release-style build locally:
```bash
GH_RELEASE_UPDATE_CHECK=true UPDATE_CHANNEL=stable npm run build
```
Without `GH_RELEASE_UPDATE_CHECK=true`, the update checker is removed from the bundle entirely.
## Update badge
-34
View File
@@ -1,34 +0,0 @@
import js from "@eslint/js";
import globals from "globals";
import tseslint from "typescript-eslint";
export default [
{ ignores: ["**/*.d.ts"] },
js.configs.recommended,
{
files: ["src/**/*.{js,ts}"],
languageOptions: {
parser: tseslint.parser,
ecmaVersion: "latest",
sourceType: "module",
globals: {
...globals.browser,
...globals.node,
__ENABLE_GH_RELEASE_UPDATE_CHECK__: "readonly",
__GH_RELEASE_REPO__: "readonly",
__UPDATE_CHANNEL__: "readonly",
__BUILD_LABEL__: "readonly",
},
},
rules: {
"no-unused-vars": "off",
"no-undef": "off",
"no-useless-escape": "off",
"no-prototype-builtins": "off",
"no-empty": "off",
"no-case-declarations": "off",
"no-irregular-whitespace": "off",
"no-async-promise-executor": "off",
},
},
];
+14 -23
View File
@@ -1,29 +1,20 @@
export default {
preset: 'ts-jest',
testEnvironment: 'node',
roots: ['<rootDir>/src'],
testMatch: [
'**/__tests__/**/*.ts',
'**/?(*.)+(spec|test).ts'
],
preset: "ts-jest",
testEnvironment: "node",
roots: ["<rootDir>/src"],
testMatch: ["**/__tests__/**/*.ts", "**/?(*.)+(spec|test).ts"],
transform: {
'^.+\\.ts$': 'ts-jest',
'^.+\\.js$': ['ts-jest', { tsconfig: { allowJs: true } }],
"^.+\\.ts$": "ts-jest",
"^.+\\.js$": ["ts-jest", { tsconfig: { allowJs: true } }],
},
transformIgnorePatterns: [
'/node_modules/(?!(color|color-string|color-convert|color-name)/)',
],
transformIgnorePatterns: ["/node_modules/(?!(color|color-string|color-convert|color-name)/)"],
moduleNameMapper: {
'^@/(.*)\\?script(?:&(?:iife|module))?$':
'<rootDir>/src/test/mocks/crxjsScriptPath.ts',
'^@/lib/browser$': '<rootDir>/src/test/mocks/browser.ts',
'^@/(.*)$': '<rootDir>/src/$1',
'^color$': '<rootDir>/src/test/mocks/color.ts',
"^@/(.*)\\?script(?:&(?:iife|module))?$": "<rootDir>/src/test/mocks/crxjsScriptPath.ts",
"^@/lib/browser$": "<rootDir>/src/test/mocks/browser.ts",
"^@/(.*)$": "<rootDir>/src/$1",
"^color$": "<rootDir>/src/test/mocks/color.ts",
},
setupFilesAfterEnv: ['<rootDir>/src/test/jest.setup.ts'],
moduleFileExtensions: ['ts', 'js', 'json'],
collectCoverageFrom: [
'src/**/*.ts',
'!src/**/*.d.ts',
],
setupFilesAfterEnv: ["<rootDir>/src/test/jest.setup.ts"],
moduleFileExtensions: ["ts", "js", "json"],
collectCoverageFrom: ["src/**/*.ts", "!src/**/*.d.ts"],
};
+804 -1007
View File
File diff suppressed because it is too large. Load diff
+45 -46
View File
@@ -1,12 +1,15 @@
{
"name": "betterseqtaplus",
"version": "3.7.6",
"type": "module",
"description": "Enhance SEQTA Learn's usability and aesthetics! A fork of BetterSEQTA to continue development and add heaps more features!",
"browserslist": "> 0.5%, last 2 versions, not dead",
"engines": {
"node": ">=26"
"keywords": [],
"license": "MIT",
"author": {
"name": "SethBurkart123",
"email": "betterseqta.plus@gmail.com",
"url": "https://github.com/BetterSEQTA/BetterSEQTA-Plus"
},
"type": "module",
"scripts": {
"compile:layerchart": "node scripts/compile-layerchart-vendor.mjs",
"postinstall": "node scripts/copy-runtime-assets.mjs && npm run compile:layerchart",
@@ -20,7 +23,9 @@
"build:safari": "cross-env MODE=safari vite build",
"build:dev": "cross-env MODE=chrome SOURCEMAP=true vite build && cross-env MODE=firefox SOURCEMAP=true vite build",
"convert:safari": "xcrun safari-web-extension-converter dist/safari --project-location . --app-name $npm_package_name-safari",
"lint": "eslint \"src/**/*.{js,ts}\"",
"lint": "oxlint --deny-warnings",
"format": "oxfmt",
"format:check": "oxfmt --check",
"typecheck": "svelte-check --tsconfig ./tsconfig.json --fail-on-warnings",
"test": "npm run test:unit",
"test:unit": "cross-env NODE_OPTIONS=--no-experimental-webstorage jest",
@@ -30,47 +35,6 @@
"publish": "node lib/publish.js --b",
"zip": "node scripts/package-extension-zips.mjs"
},
"keywords": [],
"author": {
"name": "SethBurkart123",
"email": "betterseqta.plus@gmail.com",
"url": "https://github.com/BetterSEQTA/BetterSEQTA-Plus"
},
"license": "MIT",
"devDependencies": {
"@crxjs/vite-plugin": "^3.0.0",
"@eslint/js": "^10.0.1",
"@sveltejs/vite-plugin-svelte": "^7.3.1",
"@tailwindcss/forms": "^0.5.11",
"@tailwindcss/postcss": "^4.3.3",
"@tsconfig/svelte": "^5.0.8",
"@types/canvas-confetti": "^1.9.0",
"@types/chrome": "^0.3.7",
"@types/d3-scale": "^4.0.9",
"@types/d3-shape": "^3.2.0",
"@types/jest": "^30.0.0",
"@types/mime-types": "^3.0.1",
"@types/node": "^26.6.6",
"@types/qrcode": "^1.5.6",
"@types/semver": "^7.8.0",
"@types/sortablejs": "^1.15.9",
"cross-env": "^10.1.0",
"esbuild": "^0.28.2",
"eslint": "^10.14.0",
"globals": "^17.14.0",
"jest": "^30.5.2",
"jest-environment-jsdom": "^30.5.2",
"mime-types": "^3.0.2",
"prettier": "^3.9.10",
"publish-browser-extension": "^6.2.0",
"sass": "^1.107.1",
"svelte-check": "^4.7.8",
"tailwindcss": "^4.3.3",
"ts-jest": "^29.4.15",
"typescript": "~6.0.3",
"typescript-eslint": "^8.72.1",
"vite": "^8.3.5"
},
"dependencies": {
"@codemirror/autocomplete": "^6.20.4",
"@codemirror/commands": "^6.11.1",
@@ -101,9 +65,44 @@
"sortablejs": "^1.15.7",
"svelte": "^5.57.3"
},
"devDependencies": {
"@crxjs/vite-plugin": "^3.0.0",
"@sveltejs/vite-plugin-svelte": "^7.3.1",
"@tailwindcss/forms": "^0.5.11",
"@tailwindcss/postcss": "^4.3.3",
"@tsconfig/svelte": "^5.0.8",
"@types/canvas-confetti": "^1.9.0",
"@types/chrome": "^0.3.7",
"@types/d3-scale": "^4.0.9",
"@types/d3-shape": "^3.2.0",
"@types/jest": "^30.0.0",
"@types/mime-types": "^3.0.1",
"@types/node": "^26.6.6",
"@types/qrcode": "^1.5.6",
"@types/semver": "^7.8.0",
"@types/sortablejs": "^1.15.9",
"cross-env": "^10.1.0",
"esbuild": "^0.28.2",
"jest": "^30.5.2",
"jest-environment-jsdom": "^30.5.2",
"mime-types": "^3.0.2",
"oxfmt": "^0.75.0",
"oxlint": "^1.90.0",
"publish-browser-extension": "^6.2.0",
"sass": "^1.107.1",
"svelte-check": "^4.7.8",
"tailwindcss": "^4.3.3",
"ts-jest": "^29.4.15",
"typescript": "~6.0.3",
"vite": "^8.3.5"
},
"overrides": {
"glob": "^14.0.3"
},
"browserslist": "> 0.5%, last 2 versions, not dead",
"engines": {
"node": ">=26"
},
"allowScripts": {
"@parcel/watcher": false,
"esbuild": false,
+37 -23
View File
@@ -13,7 +13,6 @@ if (!path) {
const raw = fs.readFileSync(path, "utf8");
const { traceEvents } = JSON.parse(raw);
const DURATION_PHASES = new Set(["X", "b", "e"]);
const openStacks = new Map(); // key -> { name, cat, args, ts }
const byName = new Map();
@@ -40,10 +39,6 @@ function add(map, key, dur, count = 1) {
map.set(key, e);
}
function stackKey(ev) {
return `${ev.pid}:${ev.tid}:${ev.name}:${ev.ts}`;
}
for (const ev of traceEvents) {
if (ev.ts != null) {
minTs = Math.min(minTs, ev.ts);
@@ -75,20 +70,13 @@ for (const ev of traceEvents) {
}
const url =
args.data?.url ??
args.url ??
args.fileName ??
args.data?.scriptName ??
args.data?.frame ??
"";
args.data?.url ?? args.url ?? args.fileName ?? args.data?.scriptName ?? args.data?.frame ?? "";
if (url && typeof url === "string" && dur > 0) {
add(byUrl, url.slice(0, 200), dur);
}
const fn =
args.data?.functionName ??
args.functionName ??
args.data?.columnNumber != null
(args.data?.functionName ?? args.functionName ?? args.data?.columnNumber != null)
? `${args.data?.functionName ?? name}@${args.data?.url ?? ""}:${args.data?.lineNumber ?? "?"}`
: "";
if (fn && dur > 100) {
@@ -104,10 +92,18 @@ for (const ev of traceEvents) {
if (name === "RunTask" && dur > 50000) {
longTasks.push({ dur, ts: ev.ts, cat, args: JSON.stringify(args).slice(0, 300) });
}
if (/Timer|setTimeout|setInterval|FireIdleCallback|requestAnimationFrame|RequestAnimationFrame/i.test(name)) {
if (
/Timer|setTimeout|setInterval|FireIdleCallback|requestAnimationFrame|RequestAnimationFrame/i.test(
name,
)
) {
timers.push({ name, dur, ts: ev.ts });
}
if (/MutationObserver|ResizeObserver|IntersectionObserver|DeliverObservations|NotifyMutation/i.test(name)) {
if (
/MutationObserver|ResizeObserver|IntersectionObserver|DeliverObservations|NotifyMutation/i.test(
name,
)
) {
observers.push({ name, dur, ts: ev.ts });
}
if (/HitTest|FindElement|ElementAt/i.test(name)) {
@@ -142,7 +138,9 @@ function top(map, n = 40, minCount = 1) {
const traceDurationMs = ((maxTs - minTs) / 1000).toFixed(0);
console.log(JSON.stringify({
console.log(
JSON.stringify(
{
summary: {
traceDurationMs,
eventCount: traceEvents.length,
@@ -166,15 +164,31 @@ console.log(JSON.stringify({
topUrls: top(byUrl, 40),
topFunctions: top(byFunction, 40, 1),
topBetterseqta: top(betterseqtaHits, 50),
topLongTasks: longTasks.sort((a, b) => b.dur - a.dur).slice(0, 20).map(e => ({
topLongTasks: longTasks
.sort((a, b) => b.dur - a.dur)
.slice(0, 20)
.map((e) => ({
ms: (e.dur / 1000).toFixed(1),
cat: e.cat,
args: e.args,
})),
topLayout: layoutEvents.sort((a, b) => b.dur - a.dur).slice(0, 15).map(e => ({
name: e.name, ms: (e.dur / 1000).toFixed(2),
topLayout: layoutEvents
.sort((a, b) => b.dur - a.dur)
.slice(0, 15)
.map((e) => ({
name: e.name,
ms: (e.dur / 1000).toFixed(2),
})),
topObservers: observers.sort((a, b) => b.dur - a.dur).slice(0, 15).map(e => ({
name: e.name, ms: (e.dur / 1000).toFixed(2), count: 1,
topObservers: observers
.sort((a, b) => b.dur - a.dur)
.slice(0, 15)
.map((e) => ({
name: e.name,
ms: (e.dur / 1000).toFixed(2),
count: 1,
})),
}, null, 2));
},
null,
2,
),
);
+4 -4
View File
@@ -33,7 +33,9 @@ const layerchartVersion = JSON.parse(
const stampContent = `${layerchartVersion}\n${COMPILE_ALGO_VERSION}`;
if (exists(stampPath) && readFileSync(stampPath, "utf8").trim() === stampContent) {
console.log(`compile-layerchart-vendor: layerchart@${layerchartVersion} already compiled, skipping`);
console.log(
`compile-layerchart-vendor: layerchart@${layerchartVersion} already compiled, skipping`,
);
process.exit(0);
}
@@ -49,9 +51,7 @@ const walkFiles = (dir, files = []) => {
const patchSvelteImports = (content) => content.replace(importSuffixPattern, ".js");
const stripRollupBreakingSyntax = (code) =>
code
.replace(/(\w+)\?(?=\s*[,)\]])/g, "$1")
.replace(/(\w+)\?(?=\s*:)/g, "$1");
code.replace(/(\w+)\?(?=\s*[,)\]])/g, "$1").replace(/(\w+)\?(?=\s*:)/g, "$1");
const svelteFiles = walkFiles(layerchartDist).filter((f) => f.endsWith(".svelte"));
+1 -4
View File
@@ -18,10 +18,7 @@ function assertManifest(browserDir) {
if (!manifest.name) fail(`${browserDir} manifest missing name`);
if (!manifest.version) fail(`${browserDir} manifest missing version`);
const sw =
manifest.background?.service_worker ??
manifest.background?.scripts?.[0] ??
null;
const sw = manifest.background?.service_worker ?? manifest.background?.scripts?.[0] ?? null;
if (sw) {
const swPath = path.join(root, "dist", browserDir, sw);
if (!fs.existsSync(swPath)) {
+2 -7
View File
@@ -21,10 +21,7 @@ const bootScript = execFileSync(
{ encoding: "utf8" },
);
test.each([
{ onoff: false },
{ "plugin.error-page-kitten.settings": { enabled: false } },
])(
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 = "";
@@ -47,8 +44,6 @@ test.each([
for (let i = 0; i < 10; i++) await Promise.resolve();
expect(mount).not.toHaveBeenCalled();
expect(
window.getComputedStyle(document.querySelector(".message")!).display,
).not.toBe("none");
expect(window.getComputedStyle(document.querySelector(".message")!).display).not.toBe("none");
},
);
+9 -27
View File
@@ -1,7 +1,4 @@
import {
initializeSettingsState,
settingsState,
} from "@/seqta/utils/listeners/SettingsState";
import { initializeSettingsState, settingsState } from "@/seqta/utils/listeners/SettingsState";
import documentLoadCSS from "@/css/documentload.scss?inline";
import icon48 from "@/resources/icons/icon-48.png?base64";
import browser from "@/lib/browser";
@@ -51,9 +48,7 @@ let hasSEQTAText = false;
// This check is placed outside of the document load event due to issues with EP (https://github.com/BetterSEQTA/BetterSEQTA-Plus/issues/84)
if (document.childNodes[1]) {
hasSEQTAText =
document.childNodes[1].textContent?.includes(
"Copyright (c) SEQTA Software",
) ?? false;
document.childNodes[1].textContent?.includes("Copyright (c) SEQTA Software") ?? false;
if (hasSEQTAText) {
installSeqtaMenuColourPatch();
installThemeImagePagePatch();
@@ -73,8 +68,7 @@ if (import.meta.env.DEV) {
async function init() {
if (
hasSEQTAText &&
(document.title.includes("SEQTA Learn") ||
document.title.includes("SEQTA Engage")) &&
(document.title.includes("SEQTA Learn") || document.title.includes("SEQTA Engage")) &&
!IsSEQTAPage
) {
IsSEQTAPage = true;
@@ -90,7 +84,6 @@ async function init() {
const observer = new MutationObserver((mutations) => {
for (const mutation of mutations) {
if (
mutation.type === "attributes" &&
mutation.target instanceof HTMLLinkElement &&
@@ -109,8 +102,6 @@ async function init() {
attributeFilter: ["href"],
});
try {
await initializeSettingsState();
initVerboseLogging();
@@ -152,9 +143,7 @@ async function init() {
sessionStorage.removeItem("bsplus-dev-export-recovery");
}
verboseInfo(
"[BetterSEQTA+] Successfully initialised BetterSEQTA+, starting to load assets.",
);
verboseInfo("[BetterSEQTA+] Successfully initialised BetterSEQTA+, starting to load assets.");
} catch (error) {
console.error(error);
recoverFromStaleDevModuleGraph(error);
@@ -167,22 +156,17 @@ function inject404FlashHide(): void {
if (document.getElementById("bsplus-404-flash-hide")) return;
const style = document.createElement("style");
style.id = "bsplus-404-flash-hide";
style.textContent =
"html,body{background:#333!important}.message{display:none!important}";
style.textContent = "html,body{background:#333!important}.message{display:none!important}";
(document.head ?? document.documentElement).appendChild(style);
}
async function bootErrorPage() {
if (IsSEQTAPage) return;
const { isSeqta404Page, mountErrorPageKitten } = await import(
"@/plugins/built-in/errorPageKitten"
);
const { isSeqta404Page, mountErrorPageKitten } =
await import("@/plugins/built-in/errorPageKitten");
const storagePromise = browser.storage.local.get([
"onoff",
"plugin.error-page-kitten.settings",
]);
const storagePromise = browser.storage.local.get(["onoff", "plugin.error-page-kitten.settings"]);
const watchTitle = () => {
if (isSeqta404Page()) inject404FlashHide();
@@ -221,9 +205,7 @@ async function bootErrorPage() {
}
function replaceIcons() {
document
.querySelectorAll<HTMLLinkElement>('link[rel*="icon"]')
.forEach((link) => {
document.querySelectorAll<HTMLLinkElement>('link[rel*="icon"]').forEach((link) => {
if (link.href !== icon48) {
link.href = icon48;
}
+38 -19
View File
@@ -117,7 +117,14 @@ function createProviderBackend(
return {
...backend,
exchange: (code, redirectUri, verifier) =>
exchangeAccountsCode(tokenUrl, code, redirectUri, verifier, notReadyHint, includeErrorDescription),
exchangeAccountsCode(
tokenUrl,
code,
redirectUri,
verifier,
notReadyHint,
includeErrorDescription,
),
refresh: (refreshToken) =>
refreshAccountsToken(refreshUrl, refreshToken, notReadyHint, includeErrorDescription),
};
@@ -255,8 +262,7 @@ function waitForOAuthCallback(authTabId: number, opts: OAuthTabFlowOptions): Pro
tab: chrome.tabs.Tab,
) => {
if (tabId !== authTabId) return;
const url =
changeInfo.url ?? (changeInfo.status === "complete" ? tab.url : undefined);
const url = changeInfo.url ?? (changeInfo.status === "complete" ? tab.url : undefined);
if (url) finishFromUrl(url, tabId);
};
@@ -282,9 +288,7 @@ function tokenExpiresAt(expiresIn?: number): number {
return expiresIn ? Date.now() + expiresIn * 1000 : Date.now() + 3_600_000;
}
async function getValidStoredAccessToken(
provider: CalendarProviderBackend,
): Promise<string> {
async function getValidStoredAccessToken(provider: CalendarProviderBackend): Promise<string> {
const state = await provider.read();
const now = Date.now();
if (state.accessToken && state.expiresAt && state.expiresAt > now + 60_000) {
@@ -327,14 +331,15 @@ export function registerTrustedAsyncHandler(
}
async function getGoogleCalendarStatus(): Promise<GoogleCalendarStatus> {
const [state, shared, syncWeeksAhead, autoSyncWeekly, syncAssessmentDueDates] =
await Promise.all([
const [state, shared, syncWeeksAhead, autoSyncWeekly, syncAssessmentDueDates] = await Promise.all(
[
readGoogleCalendarState(),
readSharedCalendarSyncSettings(),
getSyncWeeksAhead(),
getAutoSyncWeekly(),
getSyncAssessmentDueDates(),
]);
],
);
return {
configured: isGoogleCalendarConfigured(),
connected: !!(state.refreshToken || state.accessToken),
@@ -357,7 +362,9 @@ async function getOutlookCalendarStatus(): Promise<OutlookCalendarStatus> {
};
}
async function connectCalendar(provider: CalendarProviderBackend): Promise<GoogleCalendarSyncResult> {
async function connectCalendar(
provider: CalendarProviderBackend,
): Promise<GoogleCalendarSyncResult> {
if (!provider.isConfigured()) {
return { success: false, configured: false, error: provider.notConfiguredError };
}
@@ -383,8 +390,7 @@ async function connectCalendar(provider: CalendarProviderBackend): Promise<Googl
});
} catch (err) {
const message = err instanceof Error ? err.message : provider.signInFailed;
const mismatch =
provider.mismatchRe.test(message) || provider.mismatchRe.test(String(err));
const mismatch = provider.mismatchRe.test(message) || provider.mismatchRe.test(String(err));
return {
success: false,
configured: true,
@@ -465,7 +471,8 @@ function registerProviderHandlers(
handlers,
isTrustedSender,
`${messagePrefix}GetAccessToken`,
() => getValidStoredAccessToken(provider).then((accessToken) => ({ success: true, accessToken })),
() =>
getValidStoredAccessToken(provider).then((accessToken) => ({ success: true, accessToken })),
(err) => ({ success: false, error: errMsg(err, "Token refresh failed") }),
);
}
@@ -476,15 +483,25 @@ export function registerGoogleCalendarMessageHandlers(
): void {
registerProviderHandlers(handlers, isTrustedSender, GOOGLE_BACKEND, getGoogleCalendarStatus);
registerTrustedAsyncHandler(handlers, isTrustedSender, "googleCalendarEnsureWeeklyAlarm", async () => {
registerTrustedAsyncHandler(
handlers,
isTrustedSender,
"googleCalendarEnsureWeeklyAlarm",
async () => {
await ensureWeeklySyncAlarm();
return { success: true };
}, (err) => ({
},
(err) => ({
success: false,
error: err instanceof Error ? err.message : "Could not schedule weekly sync",
}));
}),
);
registerTrustedAsyncHandler(handlers, isTrustedSender, "googleCalendarUpdateSyncSettings", async (request) => {
registerTrustedAsyncHandler(
handlers,
isTrustedSender,
"googleCalendarUpdateSyncSettings",
async (request) => {
const body = request as {
syncWeeksAhead?: number;
autoSyncWeekly?: boolean;
@@ -499,10 +516,12 @@ export function registerGoogleCalendarMessageHandlers(
if (Object.keys(patch).length > 0) await writeSharedCalendarSyncSettings(patch);
await ensureWeeklySyncAlarm();
return { success: true, ...(await getGoogleCalendarStatus()) };
}, (err) => ({
},
(err) => ({
success: false,
error: err instanceof Error ? err.message : "Could not update sync settings",
}));
}),
);
}
export function registerOutlookCalendarMessageHandlers(
+3 -9
View File
@@ -103,8 +103,7 @@ function isServerTimestampNewer(serverIso: string, localIso: string | undefined)
async function fetchCloudSummaryOnce(
token: string,
): Promise<
| { ok: true; data: CloudSummaryResponse }
| { ok: false; unauthorized: boolean; error?: string }
{ ok: true; data: CloudSummaryResponse } | { ok: false; unauthorized: boolean; error?: string }
> {
try {
const r = await fetchWithTimeout(CLOUD_SUMMARY_URL, {
@@ -130,9 +129,7 @@ async function fetchCloudSummaryOnce(
}
}
async function fetchCloudSummaryWithAuthRetry(
token: string,
): Promise<CloudSummaryResponse | null> {
async function fetchCloudSummaryWithAuthRetry(token: string): Promise<CloudSummaryResponse | null> {
let t = token;
for (let attempt = 0; attempt < 2; attempt++) {
const res = await fetchCloudSummaryOnce(t);
@@ -355,9 +352,7 @@ async function runCloudSettingsPollInner(): Promise<void> {
typeof bsplus.schemaVersion === "number" &&
bsplus.schemaVersion > CLOUD_SETTINGS_SYNC_SCHEMA_VERSION
) {
console.warn(
"[BS+ cloud sync] Server schemaVersion newer than client; skip auto-download",
);
console.warn("[BS+ cloud sync] Server schemaVersion newer than client; skip auto-download");
return;
}
@@ -484,4 +479,3 @@ export function initCloudSettingsAutoSync(deps: { reloadSeqtaPages: () => void }
browser.storage.onChanged.addListener(onStorageChanged);
void runCloudSettingsPoll();
}
+3 -13
View File
@@ -21,18 +21,10 @@ function buildFormDataFromPayload(payload: UploadPayload): FormData {
const form = new FormData();
if (payload.themeZip) {
const part = payload.themeZip;
form.append(
part.fieldName,
base64ToBlob(part.dataBase64, part.mimeType),
part.filename,
);
form.append(part.fieldName, base64ToBlob(part.dataBase64, part.mimeType), part.filename);
}
for (const part of payload.looseFiles ?? []) {
form.append(
part.fieldName,
base64ToBlob(part.dataBase64, part.mimeType),
part.filename,
);
form.append(part.fieldName, base64ToBlob(part.dataBase64, part.mimeType), part.filename);
}
if (payload.submissionNotes?.trim()) {
form.append("submission_notes", payload.submissionNotes.trim());
@@ -137,9 +129,7 @@ export function createCustomThemesHandlers(deps: {
params.set("type", "betterseqta");
(await bsplusApiQueryParams()).forEach((value, key) => params.set(key, value));
if (request.status) params.set("status", String(request.status));
sendResponse(
await customThemesJsonFetch(`/api/custom-themes/mine?${params}`, {}, true),
);
sendResponse(await customThemesJsonFetch(`/api/custom-themes/mine?${params}`, {}, true));
} catch (err) {
console.error("[Background] fetchMyCustomThemes error:", err);
sendResponse({
+2 -8
View File
@@ -10,10 +10,7 @@ const rssFeedsByCountry: Record<string, string[]> = {
"https://rss.nytimes.com/services/xml/rss/nyt/HomePage.xml",
"https://feeds.npr.org/1001/rss.xml",
],
taiwan: [
"https://news.ltn.com.tw/rss/all.xml",
"https://www.taipeitimes.com/xml/index.rss",
],
taiwan: ["https://news.ltn.com.tw/rss/all.xml", "https://www.taipeitimes.com/xml/index.rss"],
hong_kong: [
"https://rthk9.rthk.hk/rthk/news/rss/e_expressnews_elocal.xml",
"https://www.scmp.com/rss/91/feed",
@@ -32,10 +29,7 @@ const rssFeedsByCountry: Record<string, string[]> = {
"https://www.straitstimes.com/news/singapore/rss.xml",
"https://www.channelnewsasia.com/rssfeeds/8395986",
],
uk: [
"https://feeds.bbci.co.uk/news/rss.xml",
"https://www.theguardian.com/uk/rss",
],
uk: ["https://feeds.bbci.co.uk/news/rss.xml", "https://www.theguardian.com/uk/rss"],
japan: [
"https://www3.nhk.or.jp/rss/news/cat0.xml",
"https://news.livedoor.com/topics/rss/int.xml",
+10 -30
View File
@@ -1,9 +1,6 @@
import browser from "@/lib/browser";
import { getBsplusDeviceName } from "@/seqta/utils/bsplusDeviceName";
import {
bsplusApiQueryParams,
bsplusExtensionPayload,
} from "@/seqta/utils/bsplusClientContext";
import { bsplusApiQueryParams, bsplusExtensionPayload } from "@/seqta/utils/bsplusClientContext";
import { getOrCreateInstallId } from "@/seqta/utils/feedback/installId";
import { isAllowedFetchUrl } from "@/seqta/utils/allowedFetchUrl";
import {
@@ -78,9 +75,7 @@ async function fetchGithubSnapshot(): Promise<RemoteConfigSnapshot | null> {
BS_STATUS_MANIFEST_URL.replace(/manifest\.json$/, "") ||
"https://raw.githubusercontent.com/BetterSEQTA/BS-Status/main/config/";
const files: Record<string, unknown> = {};
for (const [key, fileName] of Object.entries(
manifest.files as Record<string, string>,
)) {
for (const [key, fileName] of Object.entries(manifest.files as Record<string, string>)) {
if (typeof fileName !== "string") continue;
const url = fileName.startsWith("http") ? fileName : `${base}${fileName}`;
if (!isAllowedFetchUrl(url)) continue;
@@ -95,11 +90,7 @@ async function fetchGithubSnapshot(): Promise<RemoteConfigSnapshot | null> {
}
}
async function registerInstall(
apiBase: string,
primaryOk: boolean,
force = false,
): Promise<void> {
async function registerInstall(apiBase: string, primaryOk: boolean, force = false): Promise<void> {
if (!primaryOk) return;
const stored = await browser.storage.local.get(BSPLUS_INSTALL_REGISTERED_AT_KEY);
const last = Number(stored[BSPLUS_INSTALL_REGISTERED_AT_KEY] ?? 0);
@@ -259,10 +250,9 @@ export function initRemoteConfigBackground(apiBase: () => string): void {
});
}
export function createRemoteConfigHandlers(apiBase: () => string): Record<
string,
(request: unknown, sendResponse: MessageSender) => boolean
> {
export function createRemoteConfigHandlers(
apiBase: () => string,
): Record<string, (request: unknown, sendResponse: MessageSender) => boolean> {
function handleRefresh(_req: unknown, sendResponse: MessageSender): boolean {
void refreshRemoteConfig(apiBase)
.then((res) => sendResponse(res))
@@ -275,13 +265,9 @@ export function createRemoteConfigHandlers(apiBase: () => string): Record<
}
function handleGetSnapshot(_req: unknown, sendResponse: MessageSender): boolean {
void browser.storage.local
.get(BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY)
.then((stored) => {
void browser.storage.local.get(BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY).then((stored) => {
sendResponse({
snapshot: normalizeRemoteConfigSnapshot(
stored[BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY],
),
snapshot: normalizeRemoteConfigSnapshot(stored[BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY]),
});
});
return true;
@@ -300,10 +286,7 @@ export function createRemoteConfigHandlers(apiBase: () => string): Record<
return true;
}
function handleFetchRemoteThemePackage(
req: unknown,
sendResponse: MessageSender,
): boolean {
function handleFetchRemoteThemePackage(req: unknown, sendResponse: MessageSender): boolean {
const { packageId: rawPackageId } = req as { packageId?: unknown };
const packageId = typeof rawPackageId === "string" ? rawPackageId.trim() : "";
if (!packageId) {
@@ -341,10 +324,7 @@ export function createRemoteConfigHandlers(apiBase: () => string): Record<
return true;
}
function handleFetchRemoteThemePackageUrl(
req: unknown,
sendResponse: MessageSender,
): boolean {
function handleFetchRemoteThemePackageUrl(req: unknown, sendResponse: MessageSender): boolean {
const { url: rawUrl } = req as { url?: unknown };
const url = typeof rawUrl === "string" ? rawUrl.trim() : "";
if (!url || !isAllowedFetchUrl(url)) {
+6 -1
View File
@@ -29,7 +29,12 @@ export function handleSearchThemeStockPhotos(
});
const res = await fetch(`https://commons.wikimedia.org/w/api.php?${params}`);
const json = (await res.json()) as {
query?: { pages?: Record<string, { title?: string; imageinfo?: { thumburl?: string; url?: string }[] }> };
query?: {
pages?: Record<
string,
{ title?: string; imageinfo?: { thumburl?: string; url?: string }[] }
>;
};
};
const pages = json.query?.pages ?? {};
const results: StockPhotoResult[] = Object.values(pages)
+1 -2
View File
@@ -16,8 +16,7 @@ export const OUTLOOK_CALENDAR_REFRESH_URL = `${ACCOUNTS_BASE}/api/bsplus/microso
export const OUTLOOK_CALENDAR_SCOPE = "offline_access Calendars.ReadWrite User.Read";
export const OUTLOOK_AUTH_URL =
"https://login.microsoftonline.com/common/oauth2/v2.0/authorize";
export const OUTLOOK_AUTH_URL = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize";
export const OUTLOOK_GRAPH_API = "https://graph.microsoft.com/v1.0";
+87 -98
View File
@@ -1,4 +1,3 @@
@use "sass:meta";
@import url("https://fonts.googleapis.com/css?family=Rubik:300,400,500,600,700");
@@ -81,13 +80,20 @@ select {
select:hover {
background: var(--theme-secondary, var(--background-secondary)) !important;
border-color: var(--theme-offset-bg, var(--theme-secondary, var(--background-secondary))) !important;
border-color: var(
--theme-offset-bg,
var(--theme-secondary, var(--background-secondary))
) !important;
}
select:focus {
outline: none !important;
background: var(--theme-secondary, var(--background-secondary)) !important;
border-color: color-mix(in srgb, var(--text-primary) 18%, var(--theme-offset-bg, var(--theme-secondary, var(--background-secondary))) 82%) !important;
border-color: color-mix(
in srgb,
var(--text-primary) 18%,
var(--theme-offset-bg, var(--theme-secondary, var(--background-secondary))) 82%
) !important;
box-shadow: 0 0 0 1px color-mix(in srgb, var(--text-primary) 12%, transparent) !important;
}
@@ -506,7 +512,9 @@ ul.magicDelete > li.deleting {
pointer-events: auto;
}
#menu li.hasChildren:is(.active, .bsplus-active) > .sub:has(.hasChildren:is(.active, .bsplus-active)) {
#menu
li.hasChildren:is(.active, .bsplus-active)
> .sub:has(.hasChildren:is(.active, .bsplus-active)) {
pointer-events: none !important;
}
@@ -743,8 +751,7 @@ body.icon-only-sidebar {
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;
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;
@@ -778,9 +785,8 @@ body.icon-only-sidebar {
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;
linear-gradient(var(--background-primary), var(--background-primary)) center / 100%
calc(100% - 2 * var(--bsplus-sidebar-radius, 12px)) no-repeat;
}
#menu > ul > .hasChildren > .sub {
@@ -788,10 +794,7 @@ body.icon-only-sidebar {
right: auto !important;
top: 71px !important;
margin-top: 0 !important;
width: min(
var(--bsplus-sidebar-width, 270px),
calc(100vw - 70px)
) !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;
@@ -815,22 +818,13 @@ body.icon-only-sidebar {
fill: currentColor !important;
}
:is(li, section):hover {
background: color-mix(
in srgb,
var(--text-primary) 8%,
transparent
) !important;
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;
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;
box-shadow: 0 0 10px color-mix(in srgb, var(--text-primary) 45%, transparent) !important;
}
}
.sub {
@@ -903,14 +897,15 @@ body.icon-only-sidebar {
box-sizing: border-box !important;
margin-inline: 0 !important;
}
body:not(.icon-only-sidebar) #menu#menu.bsplus-sidebar-style-strip > ul > :is(li.item, section.item) {
body:not(.icon-only-sidebar)
#menu#menu.bsplus-sidebar-style-strip
> ul
> :is(li.item, section.item) {
width: calc(100% + 1px) !important;
box-sizing: border-box !important;
}
body.icon-only-sidebar:has(
#menu > ul > .hasChildren:is(.active, .bsplus-active)
) {
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))
);
@@ -1353,11 +1348,7 @@ html.transparencyEffects [class*="BasicPanel__BasicPanel___q92_U"] > ol > li {
border-bottom: none !important;
}
html.transparencyEffects
[class*="BasicPanel__BasicPanel___q92_U"]
> ol
> li
+ li {
html.transparencyEffects [class*="BasicPanel__BasicPanel___q92_U"] > ol > li + li {
border-top: 1px solid var(--theme-offset-bg);
}
@@ -1383,7 +1374,9 @@ html.transparencyEffects
}
#content {
transition: left 0.4s cubic-bezier(0.4, 0, 0.2, 1), transform 0.4s ease;
transition:
left 0.4s cubic-bezier(0.4, 0, 0.2, 1),
transform 0.4s ease;
left: var(--bsplus-sidebar-width, 270px);
background: unset;
}
@@ -1432,7 +1425,9 @@ html.transparencyEffects
-webkit-transform: translatex(-70px);
transform: translatex(-70px);
}
#content { left: 0 !important; }
#content {
left: 0 !important;
}
}
body.icon-only-sidebar.menuShown #content {
-webkit-transform: translatex(var(--bsplus-icon-rail-space)) !important;
@@ -2008,13 +2003,10 @@ html.transparencyEffects
margin: 20px auto 0px;
cursor: pointer;
}
.dark
[class*="notifications__detailsBody___"]
> [class*="notifications__subtitle___"] {
.dark [class*="notifications__detailsBody___"] > [class*="notifications__subtitle___"] {
color: #c1bcbc;
}
[class*="notifications__detailsBody___"]
> [class*="notifications__subtitle___"] {
[class*="notifications__detailsBody___"] > [class*="notifications__subtitle___"] {
font-size: 12px;
}
[class*="notifications__notifications___"] > button {
@@ -2028,9 +2020,7 @@ html.transparencyEffects
height: 25px;
width: 24px;
}
[class*="notifications__notifications___"]
> button
> [class*="notifications__bubble___"] {
[class*="notifications__notifications___"] > button > [class*="notifications__bubble___"] {
background: var(--better-alert-highlight);
width: 25px;
height: 25px;
@@ -2258,20 +2248,32 @@ iframe.userHTML {
background-color: var(--auto-background);
}
[class*="OverallResult__OverallResult___"] {
--fill-colour: var(--assessment-accent-colour, var(--item-colour, var(--container-accent, rgb(var(--theme-sel-bg-parts)))));
--fill-colour: var(
--assessment-accent-colour,
var(--item-colour, var(--container-accent, rgb(var(--theme-sel-bg-parts))))
);
}
[class*="OverallResult__OverallResult___"] [class*="Thermoscore__Thermoscore___"],
[class*="OverallResult__OverallResult___"] [class*="Thermoscore__fill___"],
[class*="OverallResult__OverallResult___"] > div > div {
--fill-colour: var(--assessment-accent-colour, var(--item-colour, var(--container-accent, rgb(var(--theme-sel-bg-parts)))));
--fill-colour: var(
--assessment-accent-colour,
var(--item-colour, var(--container-accent, rgb(var(--theme-sel-bg-parts))))
);
}
[class*="AssessableCriterion__header___"] {
--fill-colour: var(--assessment-accent-colour, var(--item-colour, var(--container-accent, rgb(var(--theme-sel-bg-parts)))));
--fill-colour: var(
--assessment-accent-colour,
var(--item-colour, var(--container-accent, rgb(var(--theme-sel-bg-parts))))
);
}
[class*="AssessableCriterion__header___"] [class*="Thermoscore__Thermoscore___"],
[class*="AssessableCriterion__header___"] [class*="Thermoscore__fill___"],
[class*="AssessableCriterion__header___"] > div > div > div {
--fill-colour: var(--assessment-accent-colour, var(--item-colour, var(--container-accent, rgb(var(--theme-sel-bg-parts)))));
--fill-colour: var(
--assessment-accent-colour,
var(--item-colour, var(--container-accent, rgb(var(--theme-sel-bg-parts))))
);
}
.dark [class*="Thermoscore__Thermoscore___"] {
border: 2px solid rgba(255, 255, 255, 0.3);
@@ -2468,13 +2470,10 @@ div:has(> [class*="AssessmentDetails__AssessmentDetails___"]) {
> [class*="SelectedAssessment__clearBtn___"] {
background: var(--better-main);
}
[class*="SelectedAssessment__SelectedAssessment___"]
> [class*="SelectedAssessment__meta___"] {
[class*="SelectedAssessment__SelectedAssessment___"] > [class*="SelectedAssessment__meta___"] {
border-bottom: 1px solid var(--better-main);
}
[class*="TabSet__TabSet___"]
> ol[class*="TabSet__tabs___"]
> li[class*="TabSet__selected___"] {
[class*="TabSet__TabSet___"] > ol[class*="TabSet__tabs___"] > li[class*="TabSet__selected___"] {
border-bottom-color: var(--better-main);
}
[class*="TabSet__TabSet___"] > ol[class*="TabSet__tabs___"] {
@@ -2597,15 +2596,7 @@ div.entry.class[style*="left: 46.5%"] {
div.entry.class[style*="width: 46.5%"] {
width: 50% !important;
}
.timetablepage
.dailycal
> .content
> .wrapper
> .days
> tbody
> tr
> td
> .entriesWrapper {
.timetablepage .dailycal > .content > .wrapper > .days > tbody > tr > td > .entriesWrapper {
min-width: 0;
width: auto !important;
}
@@ -2996,15 +2987,7 @@ body {
.forumView .assessment {
background: var(--better-main);
}
.dailycal
> .content
> .wrapper
> .days
> tbody
> tr
> td
> .entriesWrapper
> .entry {
.dailycal > .content > .wrapper > .days > tbody > tr > td > .entriesWrapper > .entry {
padding: 3px;
transition: opacity 0.2s ease-in-out;
}
@@ -3080,9 +3063,7 @@ body {
box-shadow: none;
}
[class*="MessageList__MessageList___"]
> ol
> li[class*="MessageList__unread___"]::before,
[class*="MessageList__MessageList___"] > ol > li[class*="MessageList__unread___"]::before,
[class*="MessageList__MessageList___"] > ol > li::before {
content: "";
position: absolute;
@@ -3094,9 +3075,7 @@ body {
transition: width 0.1s;
}
[class*="MessageList__MessageList___"]
> ol
> li[class*="MessageList__unread___"]::before {
[class*="MessageList__MessageList___"] > ol > li[class*="MessageList__unread___"]::before {
width: 3px;
}
.connectedNotificationsWrapper > div > button {
@@ -3152,16 +3131,11 @@ body:not(.clr-open) .clr-picker,
visibility: hidden !important;
}
.dark
[class*="MessageList__MessageList___"]
> ol
> li[class*="MessageList__selected___"] {
.dark [class*="MessageList__MessageList___"] > ol > li[class*="MessageList__selected___"] {
background: var(--background-secondary);
}
[class*="MessageList__MessageList___"]
> ol
> li[class*="MessageList__selected___"] {
[class*="MessageList__MessageList___"] > ol > li[class*="MessageList__selected___"] {
background: var(--background-secondary, rgb(228 225 225));
color: var(--text-primary);
box-shadow: none !important;
@@ -3793,12 +3767,16 @@ div.day-empty {
max-width: 16rem;
min-width: 10rem;
padding: 0.35rem 0.6rem;
transition: border-color 0.2s ease-in-out, color 0.2s ease-in-out;
transition:
border-color 0.2s ease-in-out,
color 0.2s ease-in-out;
}
.engage-child-select:focus {
outline: none;
box-shadow: 0 0 0 2px var(--background-primary), 0 0 0 4px rgba(59, 130, 246, 0.45);
box-shadow:
0 0 0 2px var(--background-primary),
0 0 0 4px rgba(59, 130, 246, 0.45);
}
#engage-day-container:has(> .day-empty) {
@@ -4321,14 +4299,16 @@ div.day-empty {
/* Lightweight popup motion (performance mode) — fade + scale, no blur springs. */
.whatsnewBackground.bsplus-popup-css-animate {
opacity: 0;
transition: opacity var(--bs-motion-duration, 0.2s) var(--bs-motion-ease, cubic-bezier(0.22, 1, 0.36, 1));
transition: opacity var(--bs-motion-duration, 0.2s)
var(--bs-motion-ease, cubic-bezier(0.22, 1, 0.36, 1));
.whatsnewContainer {
opacity: 0;
transform: scale(0.94);
transition:
opacity var(--bs-motion-duration, 0.2s) var(--bs-motion-ease, cubic-bezier(0.22, 1, 0.36, 1)),
transform var(--bs-motion-duration, 0.2s) var(--bs-motion-ease, cubic-bezier(0.22, 1, 0.36, 1));
transform var(--bs-motion-duration, 0.2s)
var(--bs-motion-ease, cubic-bezier(0.22, 1, 0.36, 1));
}
&.bsplus-popup-css-animate--open {
@@ -4777,7 +4757,9 @@ div.day-empty {
inset 0 0 0 1px color-mix(in srgb, var(--text-primary) 14%, transparent);
backdrop-filter: blur(8px);
-webkit-backdrop-filter: blur(8px);
transition: background 0.15s ease, transform 0.15s ease;
transition:
background 0.15s ease,
transform 0.15s ease;
}
.themeOfTheMonthCardPopoutIcon {
display: inline-flex;
@@ -4961,7 +4943,9 @@ div.day-empty {
border-radius: 9999px;
cursor: pointer;
background: color-mix(in srgb, var(--text-primary) 28%, transparent);
transition: background 0.15s ease, transform 0.15s ease;
transition:
background 0.15s ease,
transform 0.15s ease;
}
.themeOfTheMonthCardGalleryDotActive {
background: var(--better-pri, #6366f1);
@@ -5039,7 +5023,10 @@ div.day-empty {
padding: 0.5rem 0.85rem;
font-size: 0.84rem;
font-weight: 700;
transition: transform 0.15s ease, filter 0.15s ease, background 0.15s ease;
transition:
transform 0.15s ease,
filter 0.15s ease,
background 0.15s ease;
}
.themeOfTheMonthCardConfirmCancel {
background: color-mix(in srgb, var(--text-primary) 10%, transparent);
@@ -5151,7 +5138,9 @@ div.day-empty {
padding: 0.58rem 0.9rem;
font-size: 0.86rem;
font-weight: 700;
transition: background 0.15s ease, color 0.15s ease;
transition:
background 0.15s ease,
color 0.15s ease;
}
.themeOfTheMonthCardPrimary {
background: var(--better-pri, #6366f1);
@@ -5223,7 +5212,8 @@ div.day-empty {
animation: bsplusThemeHighlightPulse 1.4s ease-in-out 2;
}
@keyframes bsplusThemeHighlightPulse {
0%, 100% {
0%,
100% {
box-shadow: 0 0 0 0 color-mix(in srgb, var(--better-pri, #6366f1) 0%, transparent);
}
50% {
@@ -5233,7 +5223,9 @@ div.day-empty {
.popup-media-fullscreenable {
cursor: pointer;
transition: opacity 0.2s ease-in-out, transform 0.2s ease-in-out;
transition:
opacity 0.2s ease-in-out,
transform 0.2s ease-in-out;
}
.popup-media-fullscreenable:hover {
opacity: 0.95;
@@ -5448,10 +5440,7 @@ div.day-empty {
}
}
&:not(:hover)
.cke_button:not(.cke_button_on):not(
.cke_button__seqta-align-left:first-child
) {
&:not(:hover) .cke_button:not(.cke_button_on):not(.cke_button__seqta-align-left:first-child) {
transform: translateY(0);
visibility: hidden;
transition:
+3 -9
View File
@@ -29,12 +29,8 @@
}
}
#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;
#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. */
@@ -62,9 +58,7 @@
pointer-events: none !important;
}
#menu
> ul:has(li.hasChildren:is(.active, .bsplus-active))
> li:is(.active, .bsplus-active) {
#menu > ul:has(li.hasChildren:is(.active, .bsplus-active)) > li:is(.active, .bsplus-active) {
background: transparent !important;
}
+3 -3
View File
@@ -43,9 +43,9 @@
const scheduleIndicator = rafThrottle(updateIndicator);
$effect(() => {
selectedId;
groups;
trackEl;
void selectedId;
void groups;
void trackEl;
scheduleIndicator();
});
</script>
@@ -30,7 +30,9 @@ describe("parseColour", () => {
describe("parseValue", () => {
it("parses the default gradient", () => {
expect(parseValue("linear-gradient(45deg, rgba(17,88,131,1) 0%, rgba(18,106,98,1) 100%)")).toEqual({
expect(
parseValue("linear-gradient(45deg, rgba(17,88,131,1) 0%, rgba(18,106,98,1) 100%)"),
).toEqual({
kind: "linear",
angle: 45,
stops: [
@@ -41,7 +43,9 @@ describe("parseValue", () => {
});
it("parses radial gradients and skips the shape", () => {
const value = parseValue("radial-gradient(circle, rgba(20, 199, 178, 0.76) 32%, rgba(3, 120, 57, 0.66) 100%)");
const value = parseValue(
"radial-gradient(circle, rgba(20, 199, 178, 0.76) 32%, rgba(3, 120, 57, 0.66) 100%)",
);
expect(value.kind).toBe("radial");
expect(value.kind !== "solid" && value.stops.map((stop) => stop.position)).toEqual([32, 100]);
});
@@ -49,11 +53,16 @@ describe("parseValue", () => {
it("maps side keywords and fills missing stop positions", () => {
const value = parseValue("linear-gradient(to right, #000, #888, #fff)");
expect(value).toMatchObject({ kind: "linear", angle: 90 });
expect(value.kind !== "solid" && value.stops.map((stop) => stop.position)).toEqual([0, 50, 100]);
expect(value.kind !== "solid" && value.stops.map((stop) => stop.position)).toEqual([
0, 50, 100,
]);
});
it("treats plain colours as solid and falls back on garbage", () => {
expect(parseValue("rgba(4, 4, 138, 0.77)")).toEqual({ kind: "solid", colour: { r: 4, g: 4, b: 138, a: 0.77 } });
expect(parseValue("rgba(4, 4, 138, 0.77)")).toEqual({
kind: "solid",
colour: { r: 4, g: 4, b: 138, a: 0.77 },
});
expect(parseValue("not a colour").kind).toBe("solid");
});
});
@@ -23,7 +23,8 @@ const SIDE_ANGLES: Record<string, number> = {
"to left top": 315,
};
export const clamp = (value: number, min: number, max: number) => Math.min(max, Math.max(min, value));
export const clamp = (value: number, min: number, max: number) =>
Math.min(max, Math.max(min, value));
const round = (value: number, digits = 0) => {
const factor = 10 ** digits;
@@ -44,7 +45,8 @@ function hexToRgba(hex: string): Rgba | null {
function hslToRgba(h: number, s: number, l: number, a: number): Rgba {
const k = (n: number) => (n + h / 30) % 12;
const f = (n: number) => l - s * Math.min(l, 1 - l) * Math.max(-1, Math.min(k(n) - 3, 9 - k(n), 1));
const f = (n: number) =>
l - s * Math.min(l, 1 - l) * Math.max(-1, Math.min(k(n) - 3, 9 - k(n), 1));
return { r: Math.round(f(0) * 255), g: Math.round(f(8) * 255), b: Math.round(f(4) * 255), a };
}
@@ -63,12 +65,16 @@ export function parseColour(input: string): Rgba | null {
if (fn[1].startsWith("rgb")) {
const [r, g, b] = parts
.slice(0, 3)
.map((part) => clamp(Math.round(part.endsWith("%") ? parseFloat(part) * 2.55 : parseFloat(part)), 0, 255));
.map((part) =>
clamp(Math.round(part.endsWith("%") ? parseFloat(part) * 2.55 : parseFloat(part)), 0, 255),
);
return [r, g, b].some(Number.isNaN) ? null : { r, g, b, a };
}
const [h, s, l] = [parseFloat(parts[0]), parseFloat(parts[1]) / 100, parseFloat(parts[2]) / 100];
return [h, s, l].some(Number.isNaN) ? null : hslToRgba(((h % 360) + 360) % 360, clamp(s, 0, 1), clamp(l, 0, 1), a);
return [h, s, l].some(Number.isNaN)
? null
: hslToRgba(((h % 360) + 360) % 360, clamp(s, 0, 1), clamp(l, 0, 1), a);
}
export function formatColour({ r, g, b, a }: Rgba): string {
@@ -168,7 +174,8 @@ export function formatStops(stops: GradientStop[]): string {
export function formatValue(value: ColourValue): string {
if (value.kind === "solid") return formatColour(value.colour);
if (value.kind === "linear") return `linear-gradient(${round(value.angle)}deg, ${formatStops(value.stops)})`;
if (value.kind === "linear")
return `linear-gradient(${round(value.angle)}deg, ${formatStops(value.stops)})`;
return `radial-gradient(circle, ${formatStops(value.stops)})`;
}
+9 -27
View File
@@ -21,11 +21,7 @@
--bsplus-analytics-surface: var(--background-primary, #ffffff);
--bsplus-analytics-surface-2: var(--background-secondary, #f8fafc);
--bsplus-analytics-text: var(--text-primary, #1a1a1a);
--bsplus-analytics-muted: color-mix(
in srgb,
var(--bsplus-analytics-text) 55%,
transparent
);
--bsplus-analytics-muted: color-mix(in srgb, var(--bsplus-analytics-text) 55%, transparent);
--bsplus-analytics-border: color-mix(
in srgb,
var(--theme-offset-bg, var(--background-secondary, #e2e8f0)) 78%,
@@ -142,11 +138,7 @@
.bsplus-font-picker-reset:hover:not(:disabled) {
transform: scale(1.02);
background: color-mix(
in srgb,
var(--bsplus-analytics-surface-2) 80%,
transparent
);
background: color-mix(in srgb, var(--bsplus-analytics-surface-2) 80%, transparent);
}
.bsplus-font-picker-reset:active:not(:disabled) {
@@ -155,8 +147,7 @@
.bsplus-font-picker-reset:focus-visible {
outline: none;
box-shadow: 0 0 0 3px
color-mix(in srgb, var(--bsplus-analytics-accent) 35%, transparent);
box-shadow: 0 0 0 3px color-mix(in srgb, var(--bsplus-analytics-accent) 35%, transparent);
}
.bsplus-font-picker-reset:disabled {
@@ -180,8 +171,7 @@
cursor: pointer;
background: var(--bsplus-analytics-accent);
color: var(--text-color, #ffffff);
box-shadow: 0 2px 8px
color-mix(in srgb, var(--bsplus-analytics-accent) 40%, transparent);
box-shadow: 0 2px 8px color-mix(in srgb, var(--bsplus-analytics-accent) 40%, transparent);
transition:
transform 0.2s var(--bsplus-analytics-ease),
box-shadow 0.2s var(--bsplus-analytics-ease);
@@ -189,8 +179,7 @@
.bsplus-font-picker-done:hover {
transform: scale(1.03);
box-shadow: 0 4px 14px
color-mix(in srgb, var(--bsplus-analytics-accent) 45%, transparent);
box-shadow: 0 4px 14px color-mix(in srgb, var(--bsplus-analytics-accent) 45%, transparent);
}
.bsplus-font-picker-done:active {
@@ -199,8 +188,7 @@
.bsplus-font-picker-done:focus-visible {
outline: none;
box-shadow: 0 0 0 3px
color-mix(in srgb, var(--bsplus-analytics-accent) 35%, transparent);
box-shadow: 0 0 0 3px color-mix(in srgb, var(--bsplus-analytics-accent) 35%, transparent);
}
.bsplus-font-picker-list {
@@ -213,8 +201,7 @@
flex-direction: column;
gap: 0.65rem;
scrollbar-width: thin;
scrollbar-color: color-mix(in srgb, var(--bsplus-analytics-accent) 35%, transparent)
transparent;
scrollbar-color: color-mix(in srgb, var(--bsplus-analytics-accent) 35%, transparent) transparent;
}
.bsplus-font-picker-list::-webkit-scrollbar {
@@ -272,8 +259,7 @@
var(--bsplus-analytics-accent) 10%,
var(--bsplus-analytics-surface)
);
box-shadow: 0 4px 16px
color-mix(in srgb, var(--bsplus-analytics-accent) 22%, transparent);
box-shadow: 0 4px 16px color-mix(in srgb, var(--bsplus-analytics-accent) 22%, transparent);
}
.bsplus-font-picker-option-head {
@@ -302,10 +288,6 @@
border-radius: 999px;
font-size: 0.7rem;
font-weight: 600;
background: color-mix(
in srgb,
var(--bsplus-analytics-accent) 18%,
transparent
);
background: color-mix(in srgb, var(--bsplus-analytics-accent) 18%, transparent);
color: var(--bsplus-analytics-accent);
}
@@ -128,7 +128,7 @@
$effect(() => {
loadBackground();
selectedBackground
void selectedBackground;
});
onMount(() => {
+3 -11
View File
@@ -46,11 +46,7 @@ export async function readAllData(): Promise<BackgroundRecord[]> {
return items;
}
export async function writeData(
id: string,
type: string,
blob: Blob,
): Promise<void> {
export async function writeData(id: string, type: string, blob: Blob): Promise<void> {
const record = { id, type, blob };
const db = await openDatabase();
const tx = db.transaction(STORE, "readwrite");
@@ -79,9 +75,7 @@ export async function clearAllData(): Promise<void> {
await txDone(tx);
}
export async function getDataById(
id: string,
): Promise<BackgroundRecord | undefined> {
export async function getDataById(id: string): Promise<BackgroundRecord | undefined> {
const db = await openDatabase();
const tx = db.transaction(STORE, "readonly");
const item = await req(tx.objectStore(STORE).get(id));
@@ -100,9 +94,7 @@ export function isIndexedDBSupported(): boolean {
return "indexedDB" in window;
}
export async function hasEnoughStorageSpace(
requiredSpace: number,
): Promise<boolean> {
export async function hasEnoughStorageSpace(requiredSpace: number): Promise<boolean> {
if (!("storage" in navigator) || !navigator.storage.estimate) return true;
const { quota, usage } = await navigator.storage.estimate();
return quota == null || usage == null || quota - usage > requiredSpace;
@@ -1,6 +1,9 @@
import browser from "@/lib/browser";
import type { Theme } from "@/interface/types/Theme";
import { getCommunityInstalledThemeIds, getStoreInstalledThemeIds } from "@/interface/utils/themeListFilters";
import {
getCommunityInstalledThemeIds,
getStoreInstalledThemeIds,
} from "@/interface/utils/themeListFilters";
import { normalizeStoreTheme } from "@/interface/utils/themeStoreFlavours";
import { themeUpdates } from "@/interface/hooks/ThemeUpdates";
import { ThemeManager } from "@/plugins/built-in/themes/theme-manager";
@@ -125,9 +128,7 @@ export class CommunityThemesState {
limit: 50,
})) as { success?: boolean; data?: { themes?: unknown[] }; error?: unknown };
if (!res?.success || !Array.isArray(res.data?.themes)) {
throw new Error(
typeof res?.error === "string" ? res.error : "Could not load admin themes",
);
throw new Error(typeof res?.error === "string" ? res.error : "Could not load admin themes");
}
this.reviewThemes = res.data.themes
.map((row) => {
@@ -161,7 +162,9 @@ export class CommunityThemesState {
themeUpdates.triggerUpdate();
await this.refreshInstalledThemes();
this.selectedThemeId = installedId;
void browser.runtime.sendMessage({ type: "cloudSettingsRequestDebouncedUpload" }).catch(() => {});
void browser.runtime
.sendMessage({ type: "cloudSettingsRequestDebouncedUpload" })
.catch(() => {});
} catch (err) {
this.reviewPreviewError = err instanceof Error ? err.message : "Preview failed";
}
@@ -242,7 +245,9 @@ export class CommunityThemesState {
await this.themeManager.setTheme(installedId);
themeUpdates.triggerUpdate();
await this.refreshInstalledThemes();
void browser.runtime.sendMessage({ type: "cloudSettingsRequestDebouncedUpload" }).catch(() => {});
void browser.runtime
.sendMessage({ type: "cloudSettingsRequestDebouncedUpload" })
.catch(() => {});
}
async removeInstalledTheme(themeId: string) {
@@ -255,7 +260,9 @@ export class CommunityThemesState {
await this.themeManager.setTheme(themeId);
this.selectedThemeId = themeId;
themeUpdates.triggerUpdate();
void browser.runtime.sendMessage({ type: "cloudSettingsRequestDebouncedUpload" }).catch(() => {});
void browser.runtime
.sendMessage({ type: "cloudSettingsRequestDebouncedUpload" })
.catch(() => {});
}
async saveMetadata() {
@@ -338,13 +345,13 @@ export class CommunityThemesState {
});
$effect(() => {
this.statusFilter;
void this.statusFilter;
if (this.innerTab === "mine" && this.cloudLoggedIn) void this.loadMyThemes();
});
$effect(() => {
this.reviewStatusFilter;
this.reviewSourceFilter;
void this.reviewStatusFilter;
void this.reviewSourceFilter;
this.getSearchTerm();
if (this.innerTab === "review" && this.isAdmin) void this.loadReviewThemes();
});
+1 -3
View File
@@ -25,9 +25,7 @@ if (!mountPoint) {
// In production, Rollup may put this entry in a shared chunk that content
// scripts load via `import("@/interface/main")`. Only the settings page
// has `#app` — never throw on SEQTA tabs.
verboseInfo(
"[BetterSEQTA+] Settings bootstrap skipped (no #app — not the settings page)",
);
verboseInfo("[BetterSEQTA+] Settings bootstrap skipped (no #app — not the settings page)");
} else {
InjectCustomIcons();
+1 -3
View File
@@ -19,9 +19,7 @@ export default function renderSvelte(
if (mountPoint instanceof ShadowRoot || props.standalone === true) {
const styleElement = document.createElement("style");
styleElement.textContent = shadowStyles[shadowStyle];
(mountPoint instanceof ShadowRoot ? mountPoint : document.head).appendChild(
styleElement,
);
(mountPoint instanceof ShadowRoot ? mountPoint : document.head).appendChild(styleElement);
}
const app = mount(Component, {
@@ -59,8 +59,7 @@ class PluginSettingsStore {
private async load(): Promise<void> {
const { getAllPluginSettings } = await import("@/plugins");
this.plugins = getAllPluginSettings().filter(
(plugin) =>
!(isSeqtaEngageExperience() && plugin.pluginId === "global-search"),
(plugin) => !(isSeqtaEngageExperience() && plugin.pluginId === "global-search"),
) as PluginSettingsEntry[];
for (const plugin of this.plugins) {
+1 -4
View File
@@ -23,10 +23,7 @@ export type SettingsSectionSharedProps = {
searchQuery?: string;
};
export function matchesSearch(
searchQuery: string,
...parts: Array<string | undefined>
): boolean {
export function matchesSearch(searchQuery: string, ...parts: Array<string | undefined>): boolean {
const q = searchQuery.trim().toLowerCase();
return !q || parts.some((part) => part?.toLowerCase().includes(q));
}
+1 -1
View File
@@ -243,7 +243,7 @@
$effect(() => {
loadBackground();
selectedBackground
void selectedBackground;
});
$effect(() => {
+2 -6
View File
@@ -6,18 +6,14 @@ import type { Action } from "svelte/action";
* is rendered inside a shadow DOM. Falls back to document.body otherwise.
* Pass `document.body` to escape transformed/contained settings popups entirely.
*/
export const portal: Action<HTMLElement, HTMLElement | ShadowRoot | undefined> = (
node,
target,
) => {
export const portal: Action<HTMLElement, HTMLElement | ShadowRoot | undefined> = (node, target) => {
const root = node.getRootNode();
const dest = target ?? (root instanceof ShadowRoot ? root : document.body);
dest.appendChild(node);
return {
update(newTarget) {
const nextDest =
newTarget ?? (root instanceof ShadowRoot ? root : document.body);
const nextDest = newTarget ?? (root instanceof ShadowRoot ? root : document.body);
nextDest.appendChild(node);
},
destroy() {
+3 -12
View File
@@ -24,17 +24,11 @@ const ACCENT_CSS_VARS = [
function extractSolidColor(value: string): string | null {
const trimmed = value.trim();
if (!trimmed || trimmed === "initial") return null;
if (
trimmed.startsWith("#") ||
trimmed.startsWith("rgb") ||
trimmed.startsWith("hsl")
) {
if (trimmed.startsWith("#") || trimmed.startsWith("rgb") || trimmed.startsWith("hsl")) {
return trimmed;
}
if (trimmed.includes("gradient")) {
const match = trimmed.match(
/#[0-9A-Fa-f]{6}|#[0-9A-Fa-f]{3}|rgba?\([^)]+\)/i,
);
const match = trimmed.match(/#[0-9A-Fa-f]{6}|#[0-9A-Fa-f]{3}|rgba?\([^)]+\)/i);
return match?.[0] ?? null;
}
return null;
@@ -69,8 +63,5 @@ export function syncPageThemeToElement(target: HTMLElement): void {
target.style.setProperty("--bsplus-analytics-accent", accent);
target.style.setProperty("--better-main", accent);
target.classList.toggle(
"dark",
document.documentElement.classList.contains("dark"),
);
target.classList.toggle("dark", document.documentElement.classList.contains("dark"));
}
+12 -13
View File
@@ -3,21 +3,20 @@ import { getFontPreset } from "@/seqta/ui/fonts/presets";
describe("themeBuilderDraft", () => {
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 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"),
["theme-bg-0"],
{ accentColor: "#00f", gradientEnd: "#f0f" },
);
const css = buildThemeBuilderCss(getFontPreset("inter"), ["theme-bg-0"], {
accentColor: "#00f",
gradientEnd: "#f0f",
});
expect(css).toContain("Inter");
expect(css).toContain("var(--theme-bg-0)");
expect(css).toContain("#title");
@@ -39,8 +38,8 @@ describe("themeBuilderDraft", () => {
});
it("requires a name", () => {
expect(() =>
buildThemeFromDraft({ name: " ", accentColor: "#000", photoBlobs: [] }),
).toThrow("Theme name is required");
expect(() => buildThemeFromDraft({ name: " ", accentColor: "#000", photoBlobs: [] })).toThrow(
"Theme name is required",
);
});
});
+12 -5
View File
@@ -29,7 +29,12 @@ export function buildThemeBuilderCss(
imageVariables: string[],
draft: Pick<
ThemeBuilderDraft,
"accentColor" | "gradientEnd" | "gradientAngle" | "backgroundBlurPx" | "overlayOpacity" | "customCssExtra"
| "accentColor"
| "gradientEnd"
| "gradientAngle"
| "backgroundBlurPx"
| "overlayOpacity"
| "customCssExtra"
>,
): string {
const importLine = font.googleUrl ? `@import url("${font.googleUrl}");\n` : "";
@@ -45,9 +50,7 @@ export function buildThemeBuilderCss(
];
const imageLayer =
imageVariables.length > 0
? imageVariables.map((name) => `var(--${name})`).join(", ")
: "";
imageVariables.length > 0 ? imageVariables.map((name) => `var(--${name})`).join(", ") : "";
const gradientLayer = `linear-gradient(${angle}deg, color-mix(in srgb, ${draft.accentColor} ${Math.round(overlay * 100)}%, transparent), color-mix(in srgb, ${endColor} ${Math.round(overlay * 100)}%, transparent))`;
rules.push(`#container {
@@ -126,7 +129,11 @@ export function buildThemeFromDraft(draft: ThemeBuilderDraft): LoadedCustomTheme
defaultColour: draft.accentColor.trim() || "rgba(0, 123, 255, 1)",
CanChangeColour: true,
allowBackgrounds: true,
CustomCSS: buildThemeBuilderCss(font, CustomImages.map((i) => i.variableName), draft),
CustomCSS: buildThemeBuilderCss(
font,
CustomImages.map((i) => i.variableName),
draft,
),
CustomImages,
coverImage: photoBlobs[0] ?? null,
isEditable: true,
+2 -8
View File
@@ -1,9 +1,6 @@
import type { LoadedCustomTheme } from "@/types/CustomThemes";
export function handleImageUpload(
event: Event,
theme: LoadedCustomTheme,
): LoadedCustomTheme {
export function handleImageUpload(event: Event, theme: LoadedCustomTheme): LoadedCustomTheme {
const input = event.target as HTMLInputElement;
const file = input.files?.[0];
input.value = "";
@@ -22,10 +19,7 @@ export function handleImageUpload(
};
}
export function handleRemoveImage(
imageId: string,
theme: LoadedCustomTheme,
): LoadedCustomTheme {
export function handleRemoveImage(imageId: string, theme: LoadedCustomTheme): LoadedCustomTheme {
return {
...theme,
CustomImages: theme.CustomImages.filter((image) => image.id !== imageId),
+49 -47
View File
@@ -1,5 +1,5 @@
import type { CustomTheme } from '@/types/CustomThemes';
import type { Theme } from '@/interface/types/Theme';
import type { CustomTheme } from "@/types/CustomThemes";
import type { Theme } from "@/interface/types/Theme";
import {
getThemeApplyButtonStyles,
getCommunityInstalledThemeIds,
@@ -7,15 +7,17 @@ import {
isStoreThemeInstalled,
resolveLocalThemeInstallId,
resolveStoreVariantAccentColor,
} from './themeListFilters';
} from "./themeListFilters";
function makeCustomTheme(overrides: Partial<CustomTheme> & Pick<CustomTheme, 'id' | 'name'>): CustomTheme {
function makeCustomTheme(
overrides: Partial<CustomTheme> & Pick<CustomTheme, "id" | "name">,
): CustomTheme {
return {
description: '',
defaultColour: '#000000',
description: "",
defaultColour: "#000000",
CanChangeColour: true,
allowBackgrounds: true,
CustomCSS: '',
CustomCSS: "",
CustomImages: [],
coverImage: null,
isEditable: false,
@@ -24,78 +26,78 @@ function makeCustomTheme(overrides: Partial<CustomTheme> & Pick<CustomTheme, 'id
};
}
function makeStoreTheme(overrides: Partial<Theme> & Pick<Theme, 'id' | 'name'>): Theme {
function makeStoreTheme(overrides: Partial<Theme> & Pick<Theme, "id" | "name">): Theme {
return {
description: '',
coverImage: '',
description: "",
coverImage: "",
...overrides,
};
}
describe('resolveLocalThemeInstallId', () => {
it('keeps store ids and forks local imports that collide with store copies', () => {
expect(resolveLocalThemeInstallId('theme-1', null, true, false)).toBe('theme-1');
describe("resolveLocalThemeInstallId", () => {
it("keeps store ids and forks local imports that collide with store copies", () => {
expect(resolveLocalThemeInstallId("theme-1", null, true, false)).toBe("theme-1");
const forked = resolveLocalThemeInstallId(
'theme-1',
makeCustomTheme({ id: 'theme-1', name: 'Store', installedFromStore: true }),
"theme-1",
makeCustomTheme({ id: "theme-1", name: "Store", installedFromStore: true }),
false,
false,
);
expect(forked).not.toBe('theme-1');
expect(forked).not.toBe("theme-1");
expect(
resolveLocalThemeInstallId(
'theme-1',
makeCustomTheme({ id: 'theme-1', name: 'Local' }),
"theme-1",
makeCustomTheme({ id: "theme-1", name: "Local" }),
false,
false,
),
).toBe('theme-1');
).toBe("theme-1");
});
});
describe('installed theme id helpers', () => {
it('returns store-only and community-only ids', () => {
describe("installed theme id helpers", () => {
it("returns store-only and community-only ids", () => {
const themes = [
makeCustomTheme({ id: 'store-1', name: 'Store', installedFromStore: true }),
makeCustomTheme({ id: 'community-1', name: 'Community', installedFromCommunity: true }),
makeCustomTheme({ id: 'local-1', name: 'Local' }),
makeCustomTheme({ id: "store-1", name: "Store", installedFromStore: true }),
makeCustomTheme({ id: "community-1", name: "Community", installedFromCommunity: true }),
makeCustomTheme({ id: "local-1", name: "Local" }),
];
expect(getStoreInstalledThemeIds(themes)).toEqual(['store-1']);
expect(getCommunityInstalledThemeIds(themes)).toEqual(['community-1']);
expect(getStoreInstalledThemeIds(themes)).toEqual(["store-1"]);
expect(getCommunityInstalledThemeIds(themes)).toEqual(["community-1"]);
});
});
describe('isStoreThemeInstalled', () => {
it('matches master or flavour ids', () => {
describe("isStoreThemeInstalled", () => {
it("matches master or flavour ids", () => {
const theme = makeStoreTheme({
id: 'master-1',
name: 'Master',
flavours: [{ id: 'flavour-1', name: 'Dark', accent_color: '#000', cover_image: '' }],
id: "master-1",
name: "Master",
flavours: [{ id: "flavour-1", name: "Dark", accent_color: "#000", cover_image: "" }],
});
expect(isStoreThemeInstalled(theme, ['master-1'])).toBe(true);
expect(isStoreThemeInstalled(theme, ['flavour-1'])).toBe(true);
expect(isStoreThemeInstalled(theme, ['other'])).toBe(false);
expect(isStoreThemeInstalled(theme, ["master-1"])).toBe(true);
expect(isStoreThemeInstalled(theme, ["flavour-1"])).toBe(true);
expect(isStoreThemeInstalled(theme, ["other"])).toBe(false);
});
});
describe('resolveStoreVariantAccentColor', () => {
it('prefers installed colours then flavour accents', () => {
describe("resolveStoreVariantAccentColor", () => {
it("prefers installed colours then flavour accents", () => {
const theme = makeStoreTheme({
id: 'master-1',
name: 'Master',
flavours: [{ id: 'flavour-1', name: 'Dark', accent_color: '#112233', cover_image: '' }],
id: "master-1",
name: "Master",
flavours: [{ id: "flavour-1", name: "Dark", accent_color: "#112233", cover_image: "" }],
});
expect(resolveStoreVariantAccentColor(theme, 'flavour-1', { 'flavour-1': '#ff0000' })).toBe(
'#ff0000',
expect(resolveStoreVariantAccentColor(theme, "flavour-1", { "flavour-1": "#ff0000" })).toBe(
"#ff0000",
);
expect(resolveStoreVariantAccentColor(theme, 'flavour-1')).toBe('#112233');
expect(resolveStoreVariantAccentColor(theme, "flavour-1")).toBe("#112233");
});
});
describe('getThemeApplyButtonStyles', () => {
it('derives apply and applied styles from the accent colour', () => {
const styles = getThemeApplyButtonStyles('#ff0000');
expect(styles.apply).toContain('background-color: #FF0000');
expect(styles.applied).toContain('color: #FF0000');
describe("getThemeApplyButtonStyles", () => {
it("derives apply and applied styles from the accent colour", () => {
const styles = getThemeApplyButtonStyles("#ff0000");
expect(styles.apply).toContain("background-color: #FF0000");
expect(styles.applied).toContain("color: #FF0000");
});
});
+10 -10
View File
@@ -1,8 +1,8 @@
import type { CustomTheme } from '@/types/CustomThemes';
import type { Theme } from '@/interface/types/Theme';
import { parseCssColor } from '@/seqta/ui/colors/parseCssColor';
import type { CustomTheme } from "@/types/CustomThemes";
import type { Theme } from "@/interface/types/Theme";
import { parseCssColor } from "@/seqta/ui/colors/parseCssColor";
const DEFAULT_THEME_ACCENT = 'rgba(0, 123, 255, 1)';
const DEFAULT_THEME_ACCENT = "rgba(0, 123, 255, 1)";
/** Local themes: created in the editor or imported from a file (not store/community). */
export function isLocalCustomTheme(theme: CustomTheme): boolean {
@@ -15,7 +15,7 @@ export function isLocalCustomTheme(theme: CustomTheme): boolean {
*/
export function resolveLocalThemeInstallId(
themeId: string,
existing: Pick<CustomTheme, 'installedFromStore' | 'installedFromCommunity'> | null,
existing: Pick<CustomTheme, "installedFromStore" | "installedFromCommunity"> | null,
fromStore: boolean,
fromCommunity: boolean,
): string {
@@ -36,9 +36,7 @@ export function getStoreInstalledThemeIds(themes: CustomTheme[]): string[] {
/** Installed theme ids from the community API only (excludes file imports / custom copies). */
export function getCommunityInstalledThemeIds(themes: CustomTheme[]): string[] {
return themes
.filter((theme) => theme.installedFromCommunity === true)
.map((theme) => theme.id);
return themes.filter((theme) => theme.installedFromCommunity === true).map((theme) => theme.id);
}
export function isStoreThemeInstalled(theme: Theme, installedIds: string[]): boolean {
@@ -59,7 +57,9 @@ export function resolveStoreVariantAccentColor(
if (flavour?.accent_color?.trim()) return flavour.accent_color.trim();
if (variantId === theme.id) {
const firstFlavourAccent = theme.flavours?.find((entry) => entry.accent_color?.trim())?.accent_color?.trim();
const firstFlavourAccent = theme.flavours
?.find((entry) => entry.accent_color?.trim())
?.accent_color?.trim();
if (firstFlavourAccent) return firstFlavourAccent;
}
@@ -73,7 +73,7 @@ export type ThemeApplyButtonStyles = {
export function getThemeApplyButtonStyles(accentColor: string | undefined): ThemeApplyButtonStyles {
const parsed = parseCssColor(accentColor?.trim() || DEFAULT_THEME_ACCENT, DEFAULT_THEME_ACCENT);
const onAccent = parsed.lightness() >= 60 ? '#18181b' : '#ffffff';
const onAccent = parsed.lightness() >= 60 ? "#18181b" : "#ffffff";
return {
apply: `background-color: ${parsed.hex()}; color: ${onAccent};`,
@@ -1,7 +1,4 @@
import {
createDefaultThemeCoverSvg,
defaultThemeCoverDataUrl,
} from "./themePlaceholderCover";
import { createDefaultThemeCoverSvg, defaultThemeCoverDataUrl } from "./themePlaceholderCover";
describe("themePlaceholderCover", () => {
it("builds an svg cover placeholder", () => {
+2 -4
View File
@@ -7,8 +7,7 @@ export function isHiddenStoreTheme(theme: Theme): boolean {
/** Coerce API / fallback rows into the store `Theme` shape (camelCase images, safe strings). */
export function normalizeStoreTheme(raw: Record<string, unknown>): Theme {
const flavours = Array.isArray(raw.flavours)
? (raw.flavours as Record<string, unknown>[]).map(
(f): ThemeFlavour => ({
? (raw.flavours as Record<string, unknown>[]).map((f): ThemeFlavour => ({
id: String(f.id ?? ""),
name: String(f.name ?? ""),
accent_color: String(f.accent_color ?? f.accentColor ?? ""),
@@ -23,8 +22,7 @@ export function normalizeStoreTheme(raw: Record<string, unknown>): Theme {
: typeof f.downloadCount === "number"
? f.downloadCount
: undefined,
}),
)
}))
: undefined;
return {
+2 -4
View File
@@ -3,14 +3,12 @@ import { resolveExtensionAssetUrl } from "./extensionAssetUrl";
describe("resolveExtensionAssetUrl", () => {
it("returns already-resolved extension URLs unchanged", () => {
const url =
"chrome-extension://abc/assets/IconFamily-B8lopphU.woff";
const url = "chrome-extension://abc/assets/IconFamily-B8lopphU.woff";
expect(resolveExtensionAssetUrl(url)).toBe(url);
});
it("repairs accidental double extension URL prefix", () => {
const doubled =
"chrome-extension://abc/chrome-extension://abc/assets/IconFamily-B8lopphU.woff";
const doubled = "chrome-extension://abc/chrome-extension://abc/assets/IconFamily-B8lopphU.woff";
expect(resolveExtensionAssetUrl(doubled)).toBe(
"chrome-extension://abc/assets/IconFamily-B8lopphU.woff",
);
-1
View File
@@ -7,4 +7,3 @@ export function resolveExtensionAssetUrl(url: string): string {
if (/^(?:chrome|moz)-extension:\/\/|https?:|data:/.test(url)) return url;
return browser.runtime.getURL(url.replace(/^\/+/, ""));
}
+1 -2
View File
@@ -2,5 +2,4 @@
export const LUCIDE_MOON_PATH =
"M12,3C7.03,3 3,7.03 3,12C3,16.97 7.03,21 12,21C16.97,21 21,16.97 21,12C21,11.54 20.96,11.08 20.9,10.64C19.92,12.01 18.32,12.9 16.5,12.9C13.52,12.9 11.1,10.48 11.1,7.5C11.1,5.68 11.99,4.08 13.36,3.1C12.92,3.04 12.46,3 12,3Z";
export const LUCIDE_MOON_ICON_SVG =
`<path fill="currentColor" d="${LUCIDE_MOON_PATH}"/>`;
export const LUCIDE_MOON_ICON_SVG = `<path fill="currentColor" d="${LUCIDE_MOON_PATH}"/>`;
+1 -2
View File
@@ -2,5 +2,4 @@
export const LUCIDE_SUN_PATH =
"M12,7C9.24,7 7,9.24 7,12C7,14.76 9.24,17 12,17C14.76,17 17,14.76 17,12C17,9.24 14.76,7 12,7M2,13H4C4.55,13 5,12.55 5,12C5,11.45 4.55,11 4,11H2C1.45,11 1,11.45 1,12C1,12.55 1.45,13 2,13M20,13H22C22.55,13 23,12.55 23,12C23,11.45 22.55,11 22,11H20C19.45,11 19,11.45 19,12C19,12.55 19.45,13 20,13M11,2V4C11,4.55 11.45,5 12,5C12.55,5 13,4.55 13,4V2C13,1.45 12.55,1 12,1C11.45,1 11,1.45 11,2M11,20V22C11,22.55 11.45,23 12,23C12.55,23 13,22.55 13,22V20C13,19.45 12.55,19 12,19C11.45,19 11,19.45 11,20M5.99,4.58C5.6,4.19 4.96,4.19 4.58,4.58C4.19,4.96 4.19,5.6 4.58,5.99L5.64,7.05C6.03,7.44 6.67,7.44 7.05,7.05C7.44,6.67 7.44,6.03 7.05,5.64L5.99,4.58M18.36,16.95C17.97,16.56 17.33,16.56 16.95,16.95C16.56,17.33 16.56,17.97 16.95,18.36L18.01,19.42C18.4,19.81 19.04,19.81 19.42,19.42C19.81,19.04 19.81,18.4 19.42,18.01L18.36,16.95M19.42,5.99C19.81,5.6 19.81,4.96 19.42,4.58C19.04,4.19 18.4,4.19 18.01,4.58L16.95,5.64C16.56,6.03 16.56,6.67 16.95,7.05C17.33,7.44 17.97,7.44 18.36,7.05L19.42,5.99M7.05,18.36C7.44,17.97 7.44,17.33 7.05,16.95C6.67,16.56 6.03,16.56 5.64,16.95L4.58,18.01C4.19,18.4 4.19,19.04 4.58,19.42C4.96,19.81 5.6,19.81 5.99,19.42L7.05,18.36Z";
export const LUCIDE_SUN_ICON_SVG =
`<path fill="currentColor" d="${LUCIDE_SUN_PATH}"/>`;
export const LUCIDE_SUN_ICON_SVG = `<path fill="currentColor" d="${LUCIDE_SUN_PATH}"/>`;
+4 -7
View File
@@ -13,15 +13,14 @@ function extensionAssetUrl(relativePath: string): string {
* instead of CDN (required on SEQTA pages where page CSP blocks jsdelivr).
* Safe to call multiple times; must run before embeddia `initializeModel()`.
*/
export async function ensureTransformersEnv(
ortWasmBase?: string,
): Promise<void> {
export async function ensureTransformersEnv(ortWasmBase?: string): Promise<void> {
if (configured) return;
const { env } = await import("@huggingface/transformers");
const base = ortWasmBase ?? extensionAssetUrl(ORT_RESOURCE_DIR);
if (env.backends.onnx.wasm) env.backends.onnx.wasm.wasmPaths = base.endsWith("/") ? base : `${base}/`;
if (env.backends.onnx.wasm)
env.backends.onnx.wasm.wasmPaths = base.endsWith("/") ? base : `${base}/`;
configured = true;
}
@@ -32,9 +31,7 @@ export function getOrtWasmBaseUrl(): string {
}
/** For page-origin blob workers that cannot call `browser.runtime.getURL`. */
export async function configureTransformersEnvForBase(
ortWasmBase: string,
): Promise<void> {
export async function configureTransformersEnvForBase(ortWasmBase: string): Promise<void> {
configured = false;
await ensureTransformersEnv(ortWasmBase);
}
+4 -1
View File
@@ -3,7 +3,10 @@ import type { Manifest } from "../../lib/types.ts";
import baseManifest from "./manifest.json" with { type: "json" };
import pkg from "../../package.json" with { type: "json" };
type BrowserSpecificSettings = Extract<Manifest, { manifest_version: number }>["browser_specific_settings"];
type BrowserSpecificSettings = Extract<
Manifest,
{ manifest_version: number }
>["browser_specific_settings"];
const safariSettings = {
safari: {
+92 -57
View File
@@ -19,7 +19,7 @@ class ReactFiber {
elementType: fiber.elementType,
stateNode: fiber.stateNode,
hasState: !!fiber.stateNode?.state,
hasMemoizedState: !!fiber.memoizedState
hasMemoizedState: !!fiber.memoizedState,
});
}
});
@@ -35,11 +35,11 @@ class ReactFiber {
// Try multiple property name patterns for different React versions
const possibleKeys = [
'__reactFiber$', // React 16+
'__reactInternalFiber$', // React 15
'__reactInternalInstance$', // Older versions
'__reactFiber',
'__reactInternalInstance'
"__reactFiber$", // React 16+
"__reactInternalFiber$", // React 15
"__reactInternalInstance$", // Older versions
"__reactFiber",
"__reactInternalInstance",
];
for (const key of possibleKeys) {
@@ -50,7 +50,7 @@ class ReactFiber {
(name) =>
name.startsWith("__reactFiber") ||
name.startsWith("__reactInternalInstance") ||
name.startsWith("__reactInternalFiber")
name.startsWith("__reactInternalFiber"),
);
return fiberKey ? node[fiberKey] : null;
}
@@ -60,16 +60,18 @@ class ReactFiber {
while (current) {
// Use React's internal tag system to identify component types
// Based on React's WorkTags: ClassComponent = 1, FunctionComponent = 0
if (current.tag === 1) { // ClassComponent
if (current.tag === 1) {
// ClassComponent
return current.stateNode; // For class components, stateNode is the component instance
}
// For function components, look for hooks in memoizedState
if (current.tag === 0 || current.tag === 15) { // FunctionComponent or MemoComponent
if (current.tag === 0 || current.tag === 15) {
// FunctionComponent or MemoComponent
// Function components don't have setState, but we can still track them
if (current.memoizedState && current.type) {
return {
type: 'function',
type: "function",
hooks: current.memoizedState,
fiber: current,
forceUpdate: () => {
@@ -78,7 +80,7 @@ class ReactFiber {
current.alternate.expirationTime = 1;
}
current.expirationTime = 1;
}
},
};
}
}
@@ -87,7 +89,7 @@ class ReactFiber {
if (
current.stateNode &&
current.stateNode !== null &&
typeof current.stateNode === 'object' &&
typeof current.stateNode === "object" &&
(current.stateNode.setState || current.stateNode.forceUpdate)
) {
return current.stateNode;
@@ -118,7 +120,7 @@ class ReactFiber {
state = states.length === 1 ? states[0] : states;
}
// Fallback: try component hooks if available
else if (component?.type === 'function' && component?.hooks) {
else if (component?.type === "function" && component?.hooks) {
const states = this.extractStateFromHooks(component.hooks);
state = states.length === 1 ? states[0] : states;
}
@@ -152,10 +154,10 @@ class ReactFiber {
while (currentHook) {
if (this.debug) {
console.log(`Hook ${hookIndex}:`, {
type: currentHook.tag || 'unknown',
type: currentHook.tag || "unknown",
memoizedState: currentHook.memoizedState,
queue: currentHook.queue,
next: !!currentHook.next
next: !!currentHook.next,
});
}
@@ -164,13 +166,14 @@ class ReactFiber {
const state = currentHook.memoizedState;
// Priority 1: Check for useRef hooks with complex state in .current
if (!currentHook.queue &&
typeof state === 'object' &&
if (
!currentHook.queue &&
typeof state === "object" &&
state !== null &&
state.current !== undefined &&
typeof state.current === 'object' &&
state.current !== null) {
typeof state.current === "object" &&
state.current !== null
) {
// Check if this looks like a substantial state object (has multiple properties)
const currentKeys = Object.keys(state.current);
if (currentKeys.length > 2) {
@@ -180,12 +183,17 @@ class ReactFiber {
}
}
// Priority 2: useState hooks with queue
else if (currentHook.queue && typeof state !== 'function') {
else if (currentHook.queue && typeof state !== "function") {
states.push(state);
if (this.debug) console.log(` ✅ Found useState state:`, state);
}
// Priority 3: Other potential state objects (only if we haven't found main state)
else if (!mainStateFound && !currentHook.queue && typeof state === 'object' && state !== null) {
else if (
!mainStateFound &&
!currentHook.queue &&
typeof state === "object" &&
state !== null
) {
// Skip useEffect hooks (they have tag 36)
if (!(state.tag === 36 && state.create)) {
states.push(state);
@@ -193,7 +201,7 @@ class ReactFiber {
}
}
// Priority 4: Simple primitive state
else if (typeof state !== 'function' && typeof state !== 'object') {
else if (typeof state !== "function" && typeof state !== "object") {
states.push(state);
if (this.debug) console.log(` 🔹 Found primitive state:`, state);
}
@@ -209,10 +217,8 @@ class ReactFiber {
// If we found main state objects, prioritize and deduplicate them
if (mainStateFound && states.length > 1) {
const mainStates = states.filter(state =>
typeof state === 'object' &&
state !== null &&
Object.keys(state).length > 2
const mainStates = states.filter(
(state) => typeof state === "object" && state !== null && Object.keys(state).length > 2,
);
if (mainStates.length > 1) {
@@ -236,7 +242,10 @@ class ReactFiber {
});
if (this.debug) {
console.log(`🎯 Selected most comprehensive state from ${mainStates.length} candidates:`, largestState);
console.log(
`🎯 Selected most comprehensive state from ${mainStates.length} candidates:`,
largestState,
);
}
return [largestState];
@@ -249,17 +258,17 @@ class ReactFiber {
}
calculateStateComplexity(state) {
if (!state || typeof state !== 'object') return 0;
if (!state || typeof state !== "object") return 0;
let complexity = 0;
for (const [key, value] of Object.entries(state)) {
for (const value of Object.values(state)) {
complexity += 1; // Base point for each property
if (Array.isArray(value)) {
complexity += value.length * 0.1; // Arrays get points based on length
} else if (typeof value === 'object' && value !== null) {
} else if (typeof value === "object" && value !== null) {
complexity += Object.keys(value).length * 0.5; // Nested objects get points
} else if (typeof value === 'function') {
} else if (typeof value === "function") {
complexity += 2; // Functions are valuable
}
}
@@ -273,8 +282,7 @@ class ReactFiber {
if (typeof update === "function") {
component.setState((prevState) => {
const newState = update(prevState);
if (this.debug)
console.log("✅ Updated State (Functional):", newState);
if (this.debug) console.log("✅ Updated State (Functional):", newState);
return newState;
});
} else {
@@ -284,16 +292,17 @@ class ReactFiber {
...prevState,
...update,
};
if (this.debug)
console.log("✅ Updated State (Object Merge):", newState);
if (this.debug) console.log("✅ Updated State (Object Merge):", newState);
return newState;
});
}
}
// Handle function components - force re-render since we can't directly update hooks
else if (component?.type === 'function' && component?.forceUpdate) {
else if (component?.type === "function" && component?.forceUpdate) {
if (this.debug) {
console.log("⚠️ Function component detected - triggering re-render. Direct state update not possible.");
console.log(
"⚠️ Function component detected - triggering re-render. Direct state update not possible.",
);
}
component.forceUpdate();
}
@@ -337,7 +346,7 @@ function makeSerializable(obj, visited = new WeakSet(), depth = 0, maxDepth = 10
}
if (typeof obj === "function") {
return `[Function: ${obj.name || 'anonymous'}]`;
return `[Function: ${obj.name || "anonymous"}]`;
}
if (typeof obj !== "object") {
@@ -363,7 +372,9 @@ function makeSerializable(obj, visited = new WeakSet(), depth = 0, maxDepth = 10
tagName: obj.tagName,
id: obj.id || null,
className: obj.className || null,
attributes: obj.attributes ? Array.from(obj.attributes).map(attr => ({ name: attr.name, value: attr.value })) : []
attributes: obj.attributes
? Array.from(obj.attributes).map((attr) => ({ name: attr.name, value: attr.value }))
: [],
};
}
@@ -371,7 +382,7 @@ function makeSerializable(obj, visited = new WeakSet(), depth = 0, maxDepth = 10
return {
type: "Event",
eventType: obj.type,
target: obj.target?.tagName || null
target: obj.target?.tagName || null,
};
}
@@ -392,11 +403,14 @@ function makeSerializable(obj, visited = new WeakSet(), depth = 0, maxDepth = 10
return {
type: "ReactFiber",
tag: obj.tag,
elementType: typeof obj.elementType === 'function' ? obj.elementType.name || 'AnonymousComponent' : String(obj.elementType),
elementType:
typeof obj.elementType === "function"
? obj.elementType.name || "AnonymousComponent"
: String(obj.elementType),
key: obj.key,
hasState: !!obj.stateNode?.state,
hasMemoizedState: !!obj.memoizedState,
hasProps: !!obj.memoizedProps
hasProps: !!obj.memoizedProps,
};
}
@@ -410,7 +424,7 @@ function makeSerializable(obj, visited = new WeakSet(), depth = 0, maxDepth = 10
const serializableObj = {};
// Get own enumerable properties only to avoid prototype pollution
const ownKeys = Object.getOwnPropertyNames(obj).filter(key => {
const ownKeys = Object.getOwnPropertyNames(obj).filter((key) => {
try {
return obj.propertyIsEnumerable(key);
} catch {
@@ -425,13 +439,35 @@ function makeSerializable(obj, visited = new WeakSet(), depth = 0, maxDepth = 10
for (const key of processedKeys) {
try {
const dangerousKeys = [
'parentNode', 'parentElement', 'ownerDocument', 'children', 'childNodes',
'return', 'child', 'sibling', 'alternate', 'ref', // React Fiber circular refs
'_owner', '_source', '_self', '_debugOwner', '_debugSource', // React internals
'window', 'document', 'global', 'self', 'top', 'parent', // Global objects
'constructor', 'prototype', '__proto__', // Constructor/prototype chains
'addEventListener', 'removeEventListener', // Event handlers
'setState', 'forceUpdate', 'render' // React methods that might be functions
"parentNode",
"parentElement",
"ownerDocument",
"children",
"childNodes",
"return",
"child",
"sibling",
"alternate",
"ref", // React Fiber circular refs
"_owner",
"_source",
"_self",
"_debugOwner",
"_debugSource", // React internals
"window",
"document",
"global",
"self",
"top",
"parent", // Global objects
"constructor",
"prototype",
"__proto__", // Constructor/prototype chains
"addEventListener",
"removeEventListener", // Event handlers
"setState",
"forceUpdate",
"render", // React methods that might be functions
];
if (dangerousKeys.includes(key)) {
@@ -449,10 +485,9 @@ function makeSerializable(obj, visited = new WeakSet(), depth = 0, maxDepth = 10
// Handle symbols specifically (React context symbols)
if (typeof value === "symbol") {
value = `[Symbol: ${value.description || 'anonymous'}]`;
}
else if (typeof value === "function") {
value = `[Function: ${value.name || 'anonymous'}]`;
value = `[Symbol: ${value.description || "anonymous"}]`;
} else if (typeof value === "function") {
value = `[Function: ${value.name || "anonymous"}]`;
} else if (value && typeof value === "object") {
value = makeSerializable(value, visited, depth + 1, maxDepth);
}
@@ -464,7 +499,7 @@ function makeSerializable(obj, visited = new WeakSet(), depth = 0, maxDepth = 10
}
if (ownKeys.length > maxKeys) {
serializableObj['...'] = `[${ownKeys.length - maxKeys} more properties]`;
serializableObj["..."] = `[${ownKeys.length - maxKeys} more properties]`;
}
return serializableObj;
@@ -487,7 +522,7 @@ function deepFunctionCheck(obj, path = "") {
deepFunctionCheck(item, `${path}[${index}]`);
});
} else {
Object.keys(obj).forEach(key => {
Object.keys(obj).forEach((key) => {
deepFunctionCheck(obj[key], path ? `${path}.${key}` : key);
});
}
@@ -1,10 +1,6 @@
import { BasePlugin } from "../../core/settings";
import { type Plugin } from "@/plugins/core/types";
import {
defineSettings,
numberSetting,
Setting,
} from "@/plugins/core/settingsHelpers";
import { defineSettings, numberSetting, Setting } from "@/plugins/core/settingsHelpers";
import styles from "./styles.css?inline";
import {
removeAnimatedBackgroundLayers,
+1 -2
View File
@@ -5,8 +5,7 @@ import appstorelight from "@/resources/icons/dlappstore-light.svg";
import gplayicon from "@/resources/icons/googleplay.svg";
import styles from "./styles.css?inline";
const APPSTORE =
'a[href="https://itunes.apple.com/au/app/seqta-learn/id1143069793"]>img';
const APPSTORE = 'a[href="https://itunes.apple.com/au/app/seqta-learn/id1143069793"]>img';
const GOOGLEPLAY =
'a[href="https://play.google.com/store/apps/details?id=com.seqta.android.learn"]>img';
@@ -9,9 +9,7 @@ export async function requestEngageAssessmentPdf(params: {
}): Promise<string> {
const fileName = randomPdfFileName();
const response = await fetch(
`${location.origin}/seqta/parent/print/assessment?${Date.now()}`,
{
const response = await fetch(`${location.origin}/seqta/parent/print/assessment?${Date.now()}`, {
method: "POST",
headers: { "Content-Type": "application/json; charset=utf-8" },
credentials: "include",
@@ -21,13 +19,10 @@ export async function requestEngageAssessmentPdf(params: {
student: Number(params.studentID),
fileName,
}),
},
);
});
if (!response.ok) {
throw new Error(
`Failed to generate PDF: ${response.status} ${response.statusText}`,
);
throw new Error(`Failed to generate PDF: ${response.status} ${response.statusText}`);
}
const data = (await response.json()) as {
@@ -2,27 +2,19 @@ import { extractWeightFromCoversheetText } from "./extractWeightFromCoversheetTe
describe("extractWeightFromCoversheetText", () => {
it("matches Weight: N", () => {
expect(extractWeightFromCoversheetText("Due date ... Weight: 20 Subject")).toBe(
"20",
);
expect(extractWeightFromCoversheetText("Due date ... Weight: 20 Subject")).toBe("20");
});
it("matches Weighting: N%", () => {
expect(
extractWeightFromCoversheetText("Assessment Weighting: 12.5% of semester"),
).toBe("12.5");
expect(extractWeightFromCoversheetText("Assessment Weighting: 12.5% of semester")).toBe("12.5");
});
it("matches Assessment weight: N", () => {
expect(
extractWeightFromCoversheetText("Assessment weight: 15\nCriteria"),
).toBe("15");
expect(extractWeightFromCoversheetText("Assessment weight: 15\nCriteria")).toBe("15");
});
it("matches Weight of N%", () => {
expect(extractWeightFromCoversheetText("This task has a weight of 10%")).toBe(
"10",
);
expect(extractWeightFromCoversheetText("This task has a weight of 10%")).toBe("10");
});
it("returns null when no weighting is present", () => {
@@ -12,7 +12,6 @@ import {
} from "./utils.ts";
import { injectRubricCopyButtons, teardownRubricCopyButtons } from "./rubricCopy.ts";
let overrideListenerController: AbortController | null = null;
let wrapperColourObserver: MutationObserver | null = null;
let wrapperColourObserverTimeout: ReturnType<typeof setTimeout> | null = null;
@@ -36,11 +35,9 @@ const assessmentsAveragePlugin = {
// background handleWeightings completion can find them.
overrideListenerController?.abort();
overrideListenerController = new AbortController();
document.addEventListener(
"betterseqta:overrideChanged",
() => renderSubjectAverage(api),
{ signal: overrideListenerController.signal },
);
document.addEventListener("betterseqta:overrideChanged", () => renderSubjectAverage(api), {
signal: overrideListenerController.signal,
});
document.addEventListener(
"betterseqta:weightingsChanged",
() => renderSubjectAverage(api),
@@ -117,9 +114,7 @@ async function renderSubjectAverage(api: any) {
if (!assessmentsList) return;
// Remove existing subject average before re-rendering
Array.from(
assessmentsList.querySelectorAll(`[class*='AssessmentItem__title___']`),
)
Array.from(assessmentsList.querySelectorAll(`[class*='AssessmentItem__title___']`))
.find((el) => el.textContent === "Subject Average")
?.closest("[class*='AssessmentItem__AssessmentItem___']")
?.remove();
@@ -136,23 +131,15 @@ async function renderSubjectAverage(api: any) {
sampleAssessmentItem,
"AssessmentItem__metaContainer___",
);
const metaClass = getClassByPattern(
sampleAssessmentItem,
"AssessmentItem__meta___",
);
const metaClass = getClassByPattern(sampleAssessmentItem, "AssessmentItem__meta___");
const simpleResultClass = getClassByPattern(
sampleAssessmentItem,
"AssessmentItem__simpleResult___",
);
const titleClass = getClassByPattern(
sampleAssessmentItem,
"AssessmentItem__title___",
);
const titleClass = getClassByPattern(sampleAssessmentItem, "AssessmentItem__title___");
const assessmentItems = Array.from(
assessmentsList.querySelectorAll<HTMLElement>(
`[class*='AssessmentItem__AssessmentItem___']`,
),
assessmentsList.querySelectorAll<HTMLElement>(`[class*='AssessmentItem__AssessmentItem___']`),
).filter(
(item) =>
!item
@@ -160,31 +147,18 @@ async function renderSubjectAverage(api: any) {
?.textContent?.includes("Subject Average"),
);
const {
weightedTotal,
totalWeight,
hasInaccurateWeighting,
hasRefreshingWeighting,
count,
} = await processAssessments(api, assessmentItems);
const { weightedTotal, totalWeight, hasInaccurateWeighting, hasRefreshingWeighting, count } =
await processAssessments(api, assessmentItems);
if (!count || totalWeight === 0) return;
const thermoscoreElement = document.querySelector(
"[class*='Thermoscore__Thermoscore___']",
);
const thermoscoreElement = document.querySelector("[class*='Thermoscore__Thermoscore___']");
if (!thermoscoreElement) return;
const thermoscoreClass =
Array.from(thermoscoreElement.classList).find((c) =>
c.startsWith("Thermoscore__Thermoscore___"),
) || "";
const fillClass = getClassByPattern(
thermoscoreElement,
"Thermoscore__fill___",
);
const textClass = getClassByPattern(
thermoscoreElement,
"Thermoscore__text___",
);
const fillClass = getClassByPattern(thermoscoreElement, "Thermoscore__fill___");
const textClass = getClassByPattern(thermoscoreElement, "Thermoscore__text___");
const avg = weightedTotal / totalWeight;
const rounded = Math.ceil(avg / 5) * 5;
@@ -246,9 +220,9 @@ async function renderSubjectAverage(api: any) {
}
}
function applySubjectColourToOverallResult() {
const selectedAssessmentItem = document.querySelector(
"[class*='AssessmentItem__AssessmentItem___'][class*='selected___']",
) || document.querySelector(
const selectedAssessmentItem =
document.querySelector("[class*='AssessmentItem__AssessmentItem___'][class*='selected___']") ||
document.querySelector(
"[class*='Collapsible__content___'] [class*='AssessmentItem__AssessmentItem___']",
);
const assessmentThermoscore = selectedAssessmentItem?.querySelector(
@@ -263,10 +237,22 @@ function applySubjectColourToOverallResult() {
if (assessmentThermoscore && (overallResult || assessableCriterionHeaders.length > 0)) {
const accentColour =
getComputedStyle(assessmentThermoscore).getPropertyValue("--assessment-accent-colour").trim() ||
getComputedStyle(assessmentThermoscore)
.getPropertyValue("--assessment-accent-colour")
.trim() ||
getComputedStyle(assessmentThermoscore).getPropertyValue("--fill-colour").trim() ||
getComputedStyle(assessmentThermoscore.closest("[class*='Collapsible__Collapsible___']") || assessmentThermoscore).getPropertyValue("--assessment-accent-colour").trim() ||
getComputedStyle(assessmentThermoscore.closest("[class*='Collapsible__Collapsible___']") || assessmentThermoscore).getPropertyValue("--item-colour").trim();
getComputedStyle(
assessmentThermoscore.closest("[class*='Collapsible__Collapsible___']") ||
assessmentThermoscore,
)
.getPropertyValue("--assessment-accent-colour")
.trim() ||
getComputedStyle(
assessmentThermoscore.closest("[class*='Collapsible__Collapsible___']") ||
assessmentThermoscore,
)
.getPropertyValue("--item-colour")
.trim();
if (accentColour) {
overallResult?.style.setProperty("--assessment-accent-colour", accentColour);
overallResult?.style.setProperty("--fill-colour", accentColour);
@@ -152,9 +152,7 @@ function parseRubricTable(rubric: Element): RubricTableData | null {
lines.forEach((line) => {
const meta = line.querySelector("[class*='Rubric__meta___']");
const label = cellText(meta?.querySelector("[class*='Rubric__label___']"));
const criterion = cellText(
meta?.querySelector("[class*='Rubric__description___']"),
);
const criterion = cellText(meta?.querySelector("[class*='Rubric__description___']"));
const row: RubricCell[] = [
{ text: label, selected: false },
@@ -162,9 +160,7 @@ function parseRubricTable(rubric: Element): RubricTableData | null {
];
line.querySelectorAll("[class*='Rubric__descriptor___']").forEach((descriptor) => {
const text = cellText(
descriptor.querySelector("[class*='Rubric__description___']"),
);
const text = cellText(descriptor.querySelector("[class*='Rubric__description___']"));
const selected = Array.from(descriptor.classList).some((cls) =>
cls.startsWith("Rubric__selected___"),
);
@@ -198,10 +194,9 @@ function rubricToPlainText(table: RubricTableData): string {
const formatCell = (cell: RubricCell) =>
cell.selected && cell.text ? `${cell.text} (selected)` : cell.text;
return [
table.header.join("\t"),
...table.rows.map((row) => row.map(formatCell).join("\t")),
].join("\n");
return [table.header.join("\t"), ...table.rows.map((row) => row.map(formatCell).join("\t"))].join(
"\n",
);
}
const RUBRIC_PASTE_FONT_PT = 7;
@@ -222,16 +217,12 @@ function rubricPasteCellContent(text: string): string {
function rubricToHtmlTable(table: RubricTableData): string {
const baseFont = rubricPasteFontStyle();
const cellStyle =
`border:1px solid #000000;border-collapse:collapse;padding:4px;vertical-align:top;${baseFont}`;
const cellStyle = `border:1px solid #000000;border-collapse:collapse;padding:4px;vertical-align:top;${baseFont}`;
const headerStyle = `${cellStyle}background:#f3f4f6;font-weight:700;`;
const selectedStyle = `${cellStyle}background:#dbeafe;font-weight:600;`;
const headerRow = table.header
.map(
(heading) =>
`<th style="${headerStyle}">${rubricPasteCellContent(heading)}</th>`,
)
.map((heading) => `<th style="${headerStyle}">${rubricPasteCellContent(heading)}</th>`)
.join("");
const bodyRows = table.rows
@@ -258,7 +249,7 @@ function rubricToHtmlDocument(table: RubricTableData): string {
return [
"<!DOCTYPE html>",
"<html>",
"<head><meta charset=\"utf-8\"></head>",
'<head><meta charset="utf-8"></head>',
`<body style="${rubricPasteFontStyle()}">`,
rubricToHtmlTable(table),
"</body>",
@@ -348,8 +339,7 @@ function watchRubrics(root: ParentNode) {
}
export function injectRubricCopyButtons() {
const root =
document.querySelector("[class*='SelectedAssessment__']") ?? document;
const root = document.querySelector("[class*='SelectedAssessment__']") ?? document;
watchRubrics(root);
}
+48 -148
View File
@@ -7,10 +7,7 @@ import {
randomPdfFileName,
requestEngageAssessmentPdf,
} from "./engage.ts";
import {
ensurePdfjsWorker,
getPdfjsPageContextUrls,
} from "@/lib/pdfjsExtension.ts";
import { ensurePdfjsWorker, getPdfjsPageContextUrls } from "@/lib/pdfjsExtension.ts";
import * as pdfjs from "pdfjs-dist";
import { extractWeightFromCoversheetText } from "./extractWeightFromCoversheetText";
import { delay } from "@/seqta/utils/delay";
@@ -83,9 +80,7 @@ async function resolveAssessmentId(
if (!resolvedMarks) {
try {
const state = await ReactFiber.find(
"[class*='AssessmentList__items___']",
).getState();
const state = await ReactFiber.find("[class*='AssessmentList__items___']").getState();
resolvedMarks = collectMarksFromFiberState(state);
} catch {
resolvedMarks = [];
@@ -115,8 +110,7 @@ async function resolveAssessmentId(
}
export function computeFingerprint(mark: any): string {
const score =
mark?.results?.percentage ?? mark?.results?.score ?? null;
const score = mark?.results?.percentage ?? mark?.results?.score ?? null;
return JSON.stringify([
mark?.status ?? "",
Boolean(mark?.graded),
@@ -199,10 +193,7 @@ export function clearStuck(api: any) {
}
// Helper function to find actual class names by their base pattern
export const getClassByPattern = (
element: Element | Document,
basePattern: string,
): string => {
export const getClassByPattern = (element: Element | Document, basePattern: string): string => {
const classes = Array.from(element.querySelectorAll("*"))
.flatMap((el) => Array.from(el.classList))
.filter((className) => className.startsWith(basePattern));
@@ -271,16 +262,10 @@ function saveWeightingOverride(
return { ok: true };
}
function attachWeightInputListeners(
input: HTMLInputElement,
api: any,
assessmentID: string,
) {
function attachWeightInputListeners(input: HTMLInputElement, api: any, assessmentID: string) {
const save = () => {
const result = saveWeightingOverride(api, assessmentID, input.value);
input.style.borderColor = result.ok
? "rgba(128,128,128,0.35)"
: "rgba(255,80,80,0.6)";
input.style.borderColor = result.ok ? "rgba(128,128,128,0.35)" : "rgba(255,80,80,0.6)";
};
input.addEventListener("blur", save);
@@ -336,10 +321,7 @@ function updateWeightLabelContent(
const span = document.createElement("span");
span.className = "betterseqta-weight-value";
const baseText =
weighting && weighting !== "N/A"
? formatWeightDisplay(weighting)
: "N/A";
const baseText = weighting && weighting !== "N/A" ? formatWeightDisplay(weighting) : "N/A";
span.textContent = refreshing ? `${baseText} ↻` : baseText;
if (refreshing) {
span.style.opacity = "0.7";
@@ -375,25 +357,16 @@ function createWeightLabel(
const hasNativeLabel = !!statsContainer.querySelector(
`[class*='Label__Label___']:not(.betterseqta-weight-label)`,
);
statsContainer.style.justifyContent = hasNativeLabel
? "space-between"
: "flex-end";
statsContainer.style.justifyContent = hasNativeLabel ? "space-between" : "flex-end";
const resolvedAssessmentId =
assessmentID ?? assessmentItem.dataset.betterseqtaAssessmentId;
const resolvedAssessmentId = assessmentID ?? assessmentItem.dataset.betterseqtaAssessmentId;
const existingLabel = statsContainer.querySelector(
".betterseqta-weight-label",
) as HTMLElement | null;
if (existingLabel) {
updateWeightLabelContent(
existingLabel,
weighting,
resolvedAssessmentId,
api,
refreshing,
);
updateWeightLabelContent(existingLabel, weighting, resolvedAssessmentId, api, refreshing);
return;
}
@@ -425,13 +398,7 @@ function createWeightLabel(
const innerTextDiv = weightLabel.querySelector(`[class*='Label__innerText___']`);
if (innerTextDiv) innerTextDiv.textContent = "Weight";
updateWeightLabelContent(
weightLabel,
weighting,
resolvedAssessmentId,
api,
refreshing,
);
updateWeightLabelContent(weightLabel, weighting, resolvedAssessmentId, api, refreshing);
statsContainer.appendChild(weightLabel);
}
@@ -525,9 +492,7 @@ async function fetchPDFAsArrayBuffer(url: string): Promise<ArrayBuffer> {
}
if (!response.ok) {
throw new Error(
`Failed to fetch PDF: ${response.status} ${response.statusText}`,
);
throw new Error(`Failed to fetch PDF: ${response.status} ${response.statusText}`);
}
return await response.arrayBuffer();
@@ -546,8 +511,7 @@ async function fetchPDFAsArrayBuffer(url: string): Promise<ArrayBuffer> {
export async function extractPDFText(url: string): Promise<string> {
try {
if (isFirefox) {
const { lib: pdfLibUrl, worker: pdfWorkerUrl } =
getPdfjsPageContextUrls();
const { lib: pdfLibUrl, worker: pdfWorkerUrl } = getPdfjsPageContextUrls();
const pdfLibInj = escJsSingleQuoted(pdfLibUrl);
const pdfWorkerInj = escJsSingleQuoted(pdfWorkerUrl);
@@ -630,9 +594,7 @@ export async function extractPDFText(url: string): Promise<string> {
if (event.data.success) {
resolve(event.data.text);
} else {
reject(
new Error(event.data.error || "Failed to extract PDF text"),
);
reject(new Error(event.data.error || "Failed to extract PDF text"));
}
}
};
@@ -679,7 +641,6 @@ export async function extractPDFText(url: string): Promise<string> {
}
}
async function requestStudentAssessmentPdf(params: {
assessmentID: string | number;
metaclassID: string | number;
@@ -687,9 +648,7 @@ async function requestStudentAssessmentPdf(params: {
}): Promise<string> {
const fileName = randomPdfFileName();
const printResponse = await fetch(
`${location.origin}/seqta/student/print/assessment`,
{
const printResponse = await fetch(`${location.origin}/seqta/student/print/assessment`, {
method: "POST",
headers: { "Content-Type": "application/json; charset=utf-8" },
credentials: "include",
@@ -699,13 +658,10 @@ async function requestStudentAssessmentPdf(params: {
student: Number(params.studentID),
fileName,
}),
},
);
});
if (!printResponse.ok) {
throw new Error(
`Failed to generate PDF: ${printResponse.status} ${printResponse.statusText}`,
);
throw new Error(`Failed to generate PDF: ${printResponse.status} ${printResponse.statusText}`);
}
const data = (await printResponse.json()) as {
@@ -731,11 +687,7 @@ function getStudentAssessmentReportUrl(fileName: string): string {
return `${location.origin}/seqta/student/load/file?${params.toString()}`;
}
async function extractPDFTextWithRetry(
url: string,
attempts = 3,
delayMs = 1500,
): Promise<string> {
async function extractPDFTextWithRetry(url: string, attempts = 3, delayMs = 1500): Promise<string> {
let lastError: unknown;
for (let attempt = 0; attempt < attempts; attempt++) {
try {
@@ -759,9 +711,7 @@ async function handleWeightings(mark: any, api: any) {
const metaclassID = mark.metaclassID;
const fingerprint = computeFingerprint(mark);
const existing = api.storage.weightings[assessmentID] as
| WeightingEntry
| undefined;
const existing = api.storage.weightings[assessmentID] as WeightingEntry | undefined;
// Skip only when we already have a real numeric weight for this fingerprint.
// "N/A" / "processing" / in-flight refreshing must not permanently block retries.
@@ -875,10 +825,7 @@ async function handleWeightings(mark: any, api: any) {
},
};
} catch (error: any) {
console.error(
`[BetterSEQTA+] Weighting fetch failed for assessment ${assessmentID}:`,
error,
);
console.error(`[BetterSEQTA+] Weighting fetch failed for assessment ${assessmentID}:`, error);
api.storage.weightings = {
...api.storage.weightings,
[assessmentID]: {
@@ -893,9 +840,7 @@ async function handleWeightings(mark: any, api: any) {
}
export async function parseAssessments(api: any) {
const state = await ReactFiber.find(
"[class*='AssessmentList__items___']",
).getState();
const state = await ReactFiber.find("[class*='AssessmentList__items___']").getState();
const marks = [
...(state["marks"] ?? []),
@@ -917,18 +862,14 @@ export async function processAssessments(api: any, assessmentItems: HTMLElement[
let fiberMarks: MarkLike[];
try {
const state = await ReactFiber.find(
"[class*='AssessmentList__items___']",
).getState();
const state = await ReactFiber.find("[class*='AssessmentList__items___']").getState();
fiberMarks = collectMarksFromFiberState(state);
} catch {
fiberMarks = [];
}
for (const assessmentItem of assessmentItems) {
const titleEl = assessmentItem.querySelector(
`[class*='AssessmentItem__title___']`,
);
const titleEl = assessmentItem.querySelector(`[class*='AssessmentItem__title___']`);
if (!titleEl) continue;
const title = titleEl.textContent?.trim();
@@ -942,17 +883,13 @@ export async function processAssessments(api: any, assessmentItems: HTMLElement[
? (api.storage.weightings?.[assessmentID] as WeightingEntry | undefined)
: undefined;
const autoWeighting = entry?.weight;
const override = assessmentID
? api.storage.weightingOverrides?.[assessmentID]
: undefined;
const override = assessmentID ? api.storage.weightingOverrides?.[assessmentID] : undefined;
const weighting = override ?? autoWeighting;
const refreshing = !override && Boolean(entry?.refreshing);
createWeightLabel(assessmentItem, weighting, api, refreshing, assessmentID);
const gradeElement = assessmentItem.querySelector(
`[class*='Thermoscore__text___']`,
);
const gradeElement = assessmentItem.querySelector(`[class*='Thermoscore__text___']`);
if (!gradeElement) continue;
const grade = parseGrade(gradeElement.textContent || "");
if (grade <= 0) continue;
@@ -964,7 +901,7 @@ export async function processAssessments(api: any, assessmentItems: HTMLElement[
weighting === "processing"
) {
hasInaccurateWeighting = true;
continue
continue;
} else {
const weight = parseFloat(weighting);
@@ -1004,9 +941,9 @@ function resolveTabSetClasses(): Record<string, string> {
const resolved: Record<string, string> = {};
// First pass: scan live DOM elements (fast, covers currently-applied classes)
const allClasses = Array.from(
document.querySelectorAll('[class*="TabSet__"]'),
).flatMap((el) => Array.from(el.classList));
const allClasses = Array.from(document.querySelectorAll('[class*="TabSet__"]')).flatMap((el) =>
Array.from(el.classList),
);
for (const pattern of patterns) {
const found = allClasses.find((c) => c.startsWith(pattern));
@@ -1023,13 +960,10 @@ function resolveTabSetClasses(): Record<string, string> {
try {
for (const rule of Array.from(sheet.cssRules ?? [])) {
if (!(rule instanceof CSSStyleRule)) continue;
const selectorClasses =
rule.selectorText.match(/\.([\w-]+)/g) ?? [];
const selectorClasses = rule.selectorText.match(/\.([\w-]+)/g) ?? [];
for (const pattern of missing) {
if (!resolved[pattern]) {
const match = selectorClasses.find((c) =>
c.slice(1).startsWith(pattern),
);
const match = selectorClasses.find((c) => c.slice(1).startsWith(pattern));
if (match) resolved[pattern] = match.slice(1);
}
}
@@ -1062,9 +996,7 @@ async function resolveWeightingTabContext(api: any): Promise<WeightingTabContext
const selectedItem = document.querySelector(
"[class*='AssessmentItem__AssessmentItem___'][class*='selected___']",
) as HTMLElement | null;
const titleEl = selectedItem?.querySelector(
"[class*='AssessmentItem__title___']",
);
const titleEl = selectedItem?.querySelector("[class*='AssessmentItem__title___']");
const title = titleEl?.textContent?.trim();
const assessmentID =
selectedItem?.dataset.betterseqtaAssessmentId ??
@@ -1076,12 +1008,8 @@ async function resolveWeightingTabContext(api: any): Promise<WeightingTabContext
const rawWeight = entry?.weight;
const weightingUnavailable = rawWeight === "N/A";
const autoWeight =
rawWeight && rawWeight !== "processing" && rawWeight !== "N/A"
? rawWeight
: undefined;
const override = assessmentID
? api.storage.weightingOverrides?.[assessmentID]
: undefined;
rawWeight && rawWeight !== "processing" && rawWeight !== "N/A" ? rawWeight : undefined;
const override = assessmentID ? api.storage.weightingOverrides?.[assessmentID] : undefined;
const statusNote = !assessmentID
? ""
@@ -1100,12 +1028,8 @@ async function resolveWeightingTabContext(api: any): Promise<WeightingTabContext
};
}
function renderWeightingTabHtml(
sheet: HTMLElement,
context: WeightingTabContext,
) {
const { assessmentID, autoWeight, override, weightingUnavailable, statusNote } =
context;
function renderWeightingTabHtml(sheet: HTMLElement, context: WeightingTabContext) {
const { assessmentID, autoWeight, override, weightingUnavailable, statusNote } = context;
sheet.innerHTML = `
<style>
@@ -1130,7 +1054,7 @@ function renderWeightingTabHtml(
type="number"
min="0"
step="5"
placeholder="${weightingUnavailable ? "Enter weight" : autoWeight ?? ""}"
placeholder="${weightingUnavailable ? "Enter weight" : (autoWeight ?? "")}"
value="${override ?? ""}"
${!assessmentID ? "disabled" : ""}
style="
@@ -1153,17 +1077,9 @@ function renderWeightingTabHtml(
`;
}
function attachWeightingInputHandlers(
sheet: HTMLElement,
api: any,
assessmentID: string,
) {
const input = sheet.querySelector(
"#betterseqta-weight-override",
) as HTMLInputElement;
const statusEl = sheet.querySelector(
".betterseqta-save-status",
) as HTMLElement;
function attachWeightingInputHandlers(sheet: HTMLElement, api: any, assessmentID: string) {
const input = sheet.querySelector("#betterseqta-weight-override") as HTMLInputElement;
const statusEl = sheet.querySelector(".betterseqta-save-status") as HTMLElement;
const save = () => {
const raw = input.value.trim();
@@ -1192,8 +1108,7 @@ function attachWeightingInputHandlers(
});
input.addEventListener("input", () => {
input.style.borderColor = "rgba(128,128,128,0.3)";
if (statusEl.textContent === "Invalid. Must be 0 or greater.")
statusEl.textContent = "";
if (statusEl.textContent === "Invalid. Must be 0 or greater.") statusEl.textContent = "";
});
}
@@ -1205,21 +1120,14 @@ async function buildWeightingsTabContent(api: any, sheet: HTMLElement) {
}
export function injectWeightingsTab(api: any) {
const tabList = document.querySelector(
'[class*="TabSet__tabs___"]',
) as HTMLElement;
const container = document.querySelector(
'[class*="TabSet__tabContainer___"]',
) as HTMLElement;
const tabList = document.querySelector('[class*="TabSet__tabs___"]') as HTMLElement;
const container = document.querySelector('[class*="TabSet__tabContainer___"]') as HTMLElement;
if (!tabList || !container) return;
if (tabList.querySelector(".betterseqta-weightings-tab")) return;
const cls = resolveTabSetClasses();
const prefix = (tabList.querySelector("li") as HTMLElement).id.replace(
/-tab-\d+$/,
"",
);
const prefix = (tabList.querySelector("li") as HTMLElement).id.replace(/-tab-\d+$/, "");
const newIndex = tabList.querySelectorAll("li").length;
const newTab = document.createElement("li");
@@ -1246,15 +1154,11 @@ export function injectWeightingsTab(api: any) {
});
const allTabs = Array.from(tabList.querySelectorAll("li"));
const allSheets = Array.from(
container.querySelectorAll('[class*="tabsheet"]'),
);
const allSheets = Array.from(container.querySelectorAll('[class*="tabsheet"]'));
allTabs.forEach((tab, i) => {
tab.addEventListener("click", () => {
const currentIndex = allTabs.findIndex((t) =>
t.className.includes("TabSet__selected___"),
);
const currentIndex = allTabs.findIndex((t) => t.className.includes("TabSet__selected___"));
if (i === currentIndex) return;
const goingRight = currentIndex < 0 ? true : i > currentIndex;
@@ -1267,18 +1171,14 @@ export function injectWeightingsTab(api: any) {
allSheets[currentIndex].className = [
cls["TabSet__tabsheet___"],
cls["TabSet__hidden___"],
goingRight
? cls["TabSet__disappearToLeft___"]
: cls["TabSet__disappearToRight___"],
goingRight ? cls["TabSet__disappearToLeft___"] : cls["TabSet__disappearToRight___"],
].join(" ");
}
allSheets[i].className = [
cls["TabSet__tabsheet___"],
cls["TabSet__selected___"],
goingRight
? cls["TabSet__appearFromRight___"]
: cls["TabSet__appearFromLeft___"],
goingRight ? cls["TabSet__appearFromRight___"] : cls["TabSet__appearFromLeft___"],
].join(" ");
tab.className = cls["TabSet__selected___"];
@@ -70,7 +70,7 @@
);
function initSubjectFilters(): Record<string, boolean> {
const filters = { ...(settingsState.subjectfilters || {}) };
const filters = { ...settingsState.subjectfilters };
const missing = (data?.subjects ?? []).filter((s: any) => !Object.hasOwn(filters, s.code));
if (missing.length) {
for (const s of missing) filters[s.code] = true;
@@ -14,12 +14,9 @@ import { getUserInfo } from "@/seqta/utils/userInfo";
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
import { getMockAssessmentsData } from "@/seqta/ui/dev/hideSensitiveContent";
import { isSeqtaEngageExperience } from "@/seqta/utils/isSeqtaEngage";
import {
getEngageAssessmentsData,
} from "./engageApi";
import { getEngageAssessmentsData } from "./engageApi";
let cache: { time: number; engageAll?: boolean; studentId: number; data: any } | null =
null;
let cache: { time: number; engageAll?: boolean; studentId: number; data: any } | null = null;
const CACHE_MS = 10 * 60 * 1000;
async function fetchJSON(url: string, body: any) {
@@ -111,21 +108,15 @@ async function loadSubmissions(student: number, assessments: any[]) {
await Promise.all(
assessments.map(async (assessment) => {
try {
const res = await fetchJSON(
"/seqta/student/assessment/submissions/get",
{
const res = await fetchJSON("/seqta/student/assessment/submissions/get", {
assessment: assessment.id,
metaclass: assessment.metaclassID,
student,
},
);
});
submissionMap[assessment.id] = res.payload && res.payload.length > 0;
} catch (error) {
console.warn(
`Failed to fetch submission for assessment ${assessment.id}:`,
error,
);
console.warn(`Failed to fetch submission for assessment ${assessment.id}:`, error);
submissionMap[assessment.id] = false;
}
}),
@@ -153,10 +144,7 @@ async function getLearnAssessmentsData(studentId: number) {
else map[t.id] = t;
});
const allAssessments = filterAssessmentsForActiveSubjects(
Object.values(map),
subjects,
);
const allAssessments = filterAssessmentsForActiveSubjects(Object.values(map), subjects);
const submissions = await loadSubmissions(studentId, allAssessments);
allAssessments.forEach((assessment: any) => {
@@ -183,11 +171,7 @@ export async function getAssessmentsData() {
const studentId = (await getUserInfo()).id;
if (
cache &&
Date.now() - cache.time < CACHE_MS &&
cache.studentId === studentId
) {
if (cache && Date.now() - cache.time < CACHE_MS && cache.studentId === studentId) {
return cache.data;
}
@@ -144,8 +144,7 @@ async function loadEngageSubmissions(studentId: number, assessments: any[]) {
metaclass: assessment.metaclassID,
student: studentId,
});
submissionMap[assessment.id] =
Array.isArray(res.payload) && res.payload.length > 0;
submissionMap[assessment.id] = Array.isArray(res.payload) && res.payload.length > 0;
} catch (error) {
console.warn(
`[BetterSEQTA+] Failed to fetch Engage submission for assessment ${assessment.id}:`,
@@ -159,9 +158,7 @@ async function loadEngageSubmissions(studentId: number, assessments: any[]) {
return submissionMap;
}
async function loadEngageAssessmentsForStudent(
child: EngageChildPayload,
): Promise<any[]> {
async function loadEngageAssessmentsForStudent(child: EngageChildPayload): Promise<any[]> {
const studentId = Number(child.id);
const studentName = child.name ?? "Student";
const subjects = subjectsFromChild(child);
@@ -182,14 +179,13 @@ async function loadEngageAssessmentsForStudent(
else map[task.id] = task;
});
const assessments = filterAssessmentsForActiveSubjects(
Object.values(map),
subjects,
).map((assessment) => ({
const assessments = filterAssessmentsForActiveSubjects(Object.values(map), subjects).map(
(assessment) => ({
...assessment,
studentId,
studentName,
}));
}),
);
const submissions = await loadEngageSubmissions(studentId, assessments);
assessments.forEach((assessment) => {
@@ -14,10 +14,7 @@ export type OverviewIconName =
| "ellipsis-vertical"
| "exclamation-circle";
export const OVERVIEW_ICON_PATHS: Record<
OverviewIconName,
string | string[]
> = {
export const OVERVIEW_ICON_PATHS: Record<OverviewIconName, string | string[]> = {
"calendar-days":
"M6.75 3v2.25M17.25 3v2.25M3 18.75V7.5a2.25 2.25 0 012.25-2.25h13.5A2.25 2.25 0 0121 7.5v11.25m-18 0A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75m-18 0v-7.5A2.25 2.25 0 015.25 9h13.5A2.25 2.25 0 0121 11.25v7.5",
clock: "M12 6v6h4.5m4.5 0a9 9 0 11-18 0 9 9 0 0118 0z",
@@ -25,8 +22,7 @@ export const OVERVIEW_ICON_PATHS: Record<
"M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126zM12 15.75h.007v.008H12v-.008z",
"document-check":
"M10.125 2.25h-4.5c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9zm3.75 8.625a2.625 2.625 0 100-5.25 2.625 2.625 0 000 5.25zm0 0l-3 3m3-3l3 3",
"check-circle":
"M9 12.75L11.25 15 15 9.75M21 12a9 9 0 11-18 0 9 9 0 0118 0z",
"check-circle": "M9 12.75L11.25 15 15 9.75M21 12a9 9 0 11-18 0 9 9 0 0118 0z",
"book-open":
"M12 6.042A8.967 8.967 0 006 3.75c-1.052 0-2.062.18-3 .512v14.25A8.987 8.987 0 016 18c2.305 0 4.408.867 6 2.292m0-14.25a8.966 8.966 0 016-2.292c1.052 0 2.062.18 3 .512v14.25A8.987 8.987 0 0018 18a8.967 8.967 0 00-6 2.292m0-14.25v14.25",
calendar:
@@ -45,8 +41,7 @@ export const OVERVIEW_ICON_PATHS: Record<
],
"ellipsis-vertical":
"M12 6.75a.75.75 0 110-1.5.75.75 0 010 1.5zM12 12.75a.75.75 0 110-1.5.75.75 0 010 1.5zM12 18.75a.75.75 0 110-1.5.75.75 0 010 1.5z",
"exclamation-circle":
"M12 9v3.75m9-.75a9 9 0 11-18 0 9 9 0 0118 0zm-9 3.75h.008v.008H12v-.008z",
"exclamation-circle": "M12 9v3.75m9-.75a9 9 0 11-18 0 9 9 0 0118 0zm-9 3.75h.008v.008H12v-.008z",
};
export const STATUS_COLUMN_ICONS: Record<string, OverviewIconName> = {
@@ -5,17 +5,12 @@ import { renderErrorState, renderGrid, renderSkeletonLoader, teardownOverviewUi
import styles from "./styles.css?inline";
import { delay } from "@/seqta/utils/delay";
import { isSeqtaEngageExperience } from "@/seqta/utils/isSeqtaEngage";
import {
isEngageAssessmentOverviewRoute,
} from "@/seqta/utils/engageAssessmentStudent";
import { isEngageAssessmentOverviewRoute } from "@/seqta/utils/engageAssessmentStudent";
import { resolveEngageStudentId } from "./engageApi";
const OVERVIEW_MENU_CLASS = "betterseqta-assessments-overview-item";
function ensureOverviewMenuPosition(
menu: HTMLElement,
gridItem: HTMLElement,
) {
function ensureOverviewMenuPosition(menu: HTMLElement, gridItem: HTMLElement) {
if (menu.firstElementChild !== gridItem) {
menu.insertBefore(gridItem, menu.firstChild);
}
@@ -30,12 +25,7 @@ function isOverviewRoute() {
async function waitForAssessmentsSubmenu(): Promise<HTMLElement> {
if (!isSeqtaEngageExperience()) {
return (await waitForElm(
'[data-key="assessments"] > .sub > ul',
true,
100,
60,
)) as HTMLElement;
return (await waitForElm('[data-key="assessments"] > .sub > ul', true, 100, 60)) as HTMLElement;
}
return (await waitForElm(
@@ -107,11 +97,7 @@ const assessmentsOverviewPlugin: Plugin<{}> = {
if (isSeqtaEngageExperience()) {
const studentId = await resolveEngageStudentId();
window.history.pushState(
{},
"",
`/#?page=/assessments/${studentId}/overview`,
);
window.history.pushState({}, "", `/#?page=/assessments/${studentId}/overview`);
document.title = "Overview ― SEQTA Engage";
} else {
window.history.pushState({}, "", "/#?page=/assessments/overview");
@@ -121,21 +107,14 @@ const assessmentsOverviewPlugin: Plugin<{}> = {
const main = document.getElementById("main");
if (!main || requestId !== loadRequestId) return;
document
.querySelectorAll('[data-key="assessments"] .item')
.forEach((item) => {
document.querySelectorAll('[data-key="assessments"] .item').forEach((item) => {
item.classList.remove("active");
});
gridItem.classList.add("active");
document
.querySelector('[data-key="assessments"]')
?.classList.add("active");
document.querySelector('[data-key="assessments"]')?.classList.add("active");
main.innerHTML =
'<div id="grid-view-container" class="bsplus-overview-host"></div>';
const container = document.getElementById(
"grid-view-container",
) as HTMLElement;
main.innerHTML = '<div id="grid-view-container" class="bsplus-overview-host"></div>';
const container = document.getElementById("grid-view-container") as HTMLElement;
if (requestId !== loadRequestId) return;
@@ -148,10 +127,7 @@ const assessmentsOverviewPlugin: Plugin<{}> = {
} catch (err) {
if (requestId !== loadRequestId) return;
console.error("Failed to load assessments:", err);
renderErrorState(
container,
err instanceof Error ? err.message : "Unknown error",
);
renderErrorState(container, err instanceof Error ? err.message : "Unknown error");
}
}
@@ -8,11 +8,7 @@
--bsplus-overview-surface: var(--background-primary, #ffffff);
--bsplus-overview-surface-2: var(--background-secondary, #f8fafc);
--bsplus-overview-text: var(--text-primary, #1a1a1a);
--bsplus-overview-muted: color-mix(
in srgb,
var(--bsplus-overview-text) 55%,
transparent
);
--bsplus-overview-muted: color-mix(in srgb, var(--bsplus-overview-text) 55%, transparent);
--bsplus-overview-border: color-mix(
in srgb,
var(--theme-offset-bg, var(--background-secondary, #e2e8f0)) 78%,
@@ -157,8 +153,7 @@
.filter-select:focus {
outline: none;
border-color: var(--bsplus-overview-accent);
box-shadow: 0 0 0 3px
color-mix(in srgb, var(--bsplus-overview-accent) 22%, transparent);
box-shadow: 0 0 0 3px color-mix(in srgb, var(--bsplus-overview-accent) 22%, transparent);
}
.filter-select:hover {
@@ -317,7 +312,11 @@
}
.label-subject {
background: color-mix(in srgb, var(--subject-color, var(--bsplus-overview-accent)) 88%, transparent);
background: color-mix(
in srgb,
var(--subject-color, var(--bsplus-overview-accent)) 88%,
transparent
);
}
.label-student {
@@ -360,18 +359,13 @@
}
.menu-button:hover {
background: color-mix(
in srgb,
var(--bsplus-overview-surface-2) 90%,
transparent
) !important;
background: color-mix(in srgb, var(--bsplus-overview-surface-2) 90%, transparent) !important;
color: var(--bsplus-overview-text);
transform: scale(1.05) !important;
}
.menu-button:focus-visible {
box-shadow: 0 0 0 2px
color-mix(in srgb, var(--bsplus-overview-accent) 35%, transparent) !important;
box-shadow: 0 0 0 2px color-mix(in srgb, var(--bsplus-overview-accent) 35%, transparent) !important;
}
.menu-dropdown {
@@ -404,11 +398,7 @@
}
.menu-item:hover {
background: color-mix(
in srgb,
var(--bsplus-overview-surface-2) 90%,
transparent
);
background: color-mix(in srgb, var(--bsplus-overview-surface-2) 90%, transparent);
}
.menu-item.mark-completed {
@@ -879,8 +869,12 @@
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
@keyframes shimmer {
@@ -893,12 +887,7 @@
}
.skeleton-element {
background: linear-gradient(
90deg,
#f1f5f9 0%,
#e2e8f0 50%,
#f1f5f9 100%
);
background: linear-gradient(90deg, #f1f5f9 0%, #e2e8f0 50%, #f1f5f9 100%);
background-size: 1000px 100%;
animation: shimmer 2s infinite linear;
border-radius: 4px;
+6 -14
View File
@@ -38,17 +38,11 @@ const ACCENT_CSS_VARS = [
function extractSolidColor(value: string): string | null {
const trimmed = value.trim();
if (!trimmed || trimmed === "initial") return null;
if (
trimmed.startsWith("#") ||
trimmed.startsWith("rgb") ||
trimmed.startsWith("hsl")
) {
if (trimmed.startsWith("#") || trimmed.startsWith("rgb") || trimmed.startsWith("hsl")) {
return trimmed;
}
if (trimmed.includes("gradient")) {
const match = trimmed.match(
/#[0-9A-Fa-f]{6}|#[0-9A-Fa-f]{3}|rgba?\([^)]+\)/i,
);
const match = trimmed.match(/#[0-9A-Fa-f]{6}|#[0-9A-Fa-f]{3}|rgba?\([^)]+\)/i);
return match?.[0] ?? null;
}
return null;
@@ -71,18 +65,16 @@ function resolvePageAccentColor(): string {
function syncOverviewTheme(target: HTMLElement) {
const computed = getComputedStyle(document.documentElement);
for (const name of THEME_CSS_VARS) {
const value = document.documentElement.style.getPropertyValue(name).trim()
|| computed.getPropertyValue(name).trim();
const value =
document.documentElement.style.getPropertyValue(name).trim() ||
computed.getPropertyValue(name).trim();
if (value) target.style.setProperty(name, value);
}
const accent = resolvePageAccentColor();
target.style.setProperty("--bsplus-overview-accent", accent);
target.style.setProperty("--better-main", accent);
target.classList.toggle(
"dark",
document.documentElement.classList.contains("dark"),
);
target.classList.toggle("dark", document.documentElement.classList.contains("dark"));
}
function watchOverviewTheme(root: HTMLElement) {
@@ -87,17 +87,12 @@ export function assessmentBelongsToActiveSubjects(
): boolean {
if (!activeSubjects.length) return false;
const programme = Number(
assessment.programmeID ?? assessment.programme,
);
const metaclass = Number(
assessment.metaclassID ?? assessment.metaclass,
);
const programme = Number(assessment.programmeID ?? assessment.programme);
const metaclass = Number(assessment.metaclassID ?? assessment.metaclass);
if (programme && metaclass && !Number.isNaN(programme) && !Number.isNaN(metaclass)) {
return activeSubjects.some(
(subject) =>
subject.programme === programme && subject.metaclass === metaclass,
(subject) => subject.programme === programme && subject.metaclass === metaclass,
);
}
@@ -110,19 +105,10 @@ export function activeSubjectForAssessment(
assessment: Record<string, unknown>,
activeSubjects: OverviewSubject[],
): OverviewSubject | undefined {
const programme = Number(
assessment.programmeID ?? assessment.programme,
);
const metaclass = Number(
assessment.metaclassID ?? assessment.metaclass,
);
const programme = Number(assessment.programmeID ?? assessment.programme);
const metaclass = Number(assessment.metaclassID ?? assessment.metaclass);
if (
programme &&
metaclass &&
!Number.isNaN(programme) &&
!Number.isNaN(metaclass)
) {
if (programme && metaclass && !Number.isNaN(programme) && !Number.isNaN(metaclass)) {
const subject = activeSubjects.find(
(s) => s.programme === programme && s.metaclass === metaclass,
);
@@ -236,10 +222,7 @@ export function determineStatus(item: any, completed: readonly unknown[]): strin
}
export function getGradeValue(assessment: any): number | null {
if (
assessment.results?.percentage !== undefined &&
assessment.results.percentage !== null
) {
if (assessment.results?.percentage !== undefined && assessment.results.percentage !== null) {
return assessment.results.percentage;
}
+4 -13
View File
@@ -27,8 +27,7 @@ const settings = defineSettings({
}),
pauseOnHidden: booleanSetting({
title: "Pause when tab hidden",
description:
"Pause music when switching to another tab or minimizing the browser",
description: "Pause music when switching to another tab or minimizing the browser",
default: true,
}),
});
@@ -197,8 +196,7 @@ const backgroundMusicPlugin: Plugin<typeof settings> = {
type BgSettings = { volume?: number; pauseOnHidden?: boolean };
const vol = () => (api.settings as BgSettings).volume ?? 0.5;
const pauseOnHidden = () =>
(api.settings as BgSettings).pauseOnHidden ?? true;
const pauseOnHidden = () => (api.settings as BgSettings).pauseOnHidden ?? true;
const runEnsurePlayback = async () => {
if (!(await prepareAudio(vol()))) return;
@@ -246,11 +244,7 @@ const backgroundMusicPlugin: Plugin<typeof settings> = {
});
api.settings.onChange("pauseOnHidden" as never, (value: unknown) => {
if (
value === false &&
audio?.paused &&
document.visibilityState === "visible"
) {
if (value === false && audio?.paused && document.visibilityState === "visible") {
void ensurePlayback();
}
});
@@ -297,10 +291,7 @@ const backgroundMusicPlugin: Plugin<typeof settings> = {
pageChange.unregister();
document.removeEventListener("visibilitychange", onVisibility);
window.removeEventListener("pageshow", onUpdated);
window.removeEventListener(
"betterseqta-background-music-updated",
onUpdated,
);
window.removeEventListener("betterseqta-background-music-updated", onUpdated);
window.removeEventListener("betterseqta-background-music-stop", onStop);
if (resumeTimer) clearTimeout(resumeTimer);
disarmGesture();
@@ -8,7 +8,9 @@
border-radius: 999px;
background: color-mix(in srgb, var(--theme-primary, #1a1a1a) 92%, black 8%);
color: var(--text-primary, #fff);
font: 600 0.8125rem/1.25 system-ui, sans-serif;
font:
600 0.8125rem/1.25 system-ui,
sans-serif;
cursor: pointer;
box-shadow: 0 8px 24px rgb(0 0 0 / 0.35);
}
@@ -1,10 +1,6 @@
import type { Plugin } from "@/plugins/core/types";
import { BasePlugin } from "@/plugins/core/settings";
import {
booleanSetting,
defineSettings,
Setting,
} from "@/plugins/core/settingsHelpers";
import { booleanSetting, defineSettings, Setting } from "@/plugins/core/settingsHelpers";
const settings = defineSettings({
autoScrollOnClick: booleanSetting({
@@ -94,9 +90,7 @@ const getOrderedItems = (navigator: Element): HTMLElement[] => {
const items: HTMLElement[] = [];
const cover = navigator.querySelector<HTMLElement>("li.cover");
if (cover) items.push(cover);
const lessons = Array.from(
navigator.querySelectorAll<HTMLElement>("li.lesson"),
);
const lessons = Array.from(navigator.querySelectorAll<HTMLElement>("li.lesson"));
lessons.sort((a, b) => {
const wa = parseInt(a.dataset.week ?? "0", 10);
const wb = parseInt(b.dataset.week ?? "0", 10);
@@ -132,33 +126,24 @@ const scrollSelectedIntoView = (navigator: Element) => {
const selected = getSelected(navigator);
if (!selected) return;
const scroller =
findScrollableAncestor(selected) ?? (navigator as HTMLElement);
const scroller = findScrollableAncestor(selected) ?? (navigator as HTMLElement);
if (!scroller) return;
const scrollerRect = scroller.getBoundingClientRect();
const selectedRect = selected.getBoundingClientRect();
const offset =
selectedRect.top -
scrollerRect.top -
scroller.clientHeight / 2 +
selectedRect.height / 2;
selectedRect.top - scrollerRect.top - scroller.clientHeight / 2 + selectedRect.height / 2;
scroller.scrollTop = Math.max(
0,
Math.min(
scroller.scrollTop + offset,
scroller.scrollHeight - scroller.clientHeight,
),
Math.min(scroller.scrollTop + offset, scroller.scrollHeight - scroller.clientHeight),
);
};
const positionArrows = () => {
const container = document.getElementById(ARROW_CONTAINER_ID);
if (!container) return;
const ref =
document.getElementById("toolbar") ??
document.querySelector<HTMLElement>(".course");
const ref = document.getElementById("toolbar") ?? document.querySelector<HTMLElement>(".course");
if (!ref) return;
const rect = ref.getBoundingClientRect();
const arrowH = container.offsetHeight || 32;
@@ -189,12 +174,8 @@ const updateArrowState = (course: HTMLElement) => {
const selected = getSelected(nav);
const idx = selected ? items.indexOf(selected) : -1;
const prev = container.querySelector<HTMLButtonElement>(
'button[data-en-action="prev"]',
);
const next = container.querySelector<HTMLButtonElement>(
'button[data-en-action="next"]',
);
const prev = container.querySelector<HTMLButtonElement>('button[data-en-action="prev"]');
const next = container.querySelector<HTMLButtonElement>('button[data-en-action="next"]');
if (prev) prev.disabled = idx <= 0;
if (next) next.disabled = idx === -1 || idx >= items.length - 1;
};
@@ -223,13 +204,10 @@ const ensureArrows = (course: HTMLElement) => {
container.addEventListener("click", (e) => {
e.preventDefault();
e.stopPropagation();
const btn = (e.target as Element).closest<HTMLButtonElement>(
"button[data-en-action]",
);
const btn = (e.target as Element).closest<HTMLButtonElement>("button[data-en-action]");
if (!btn) return;
const liveCourse = document.querySelector<HTMLElement>(".course");
if (liveCourse)
navigate(liveCourse, btn.dataset.enAction as "prev" | "next");
if (liveCourse) navigate(liveCourse, btn.dataset.enAction as "prev" | "next");
});
}
@@ -242,9 +220,7 @@ const watchNavigator = (navigator: Element, onChange: () => void) => {
const observer = new MutationObserver((muts) => {
if (
muts.some(
(m) =>
(m.type === "attributes" && m.attributeName === "class") ||
m.type === "childList",
(m) => (m.type === "attributes" && m.attributeName === "class") || m.type === "childList",
)
) {
onChange();
@@ -266,9 +242,7 @@ const handleSlidePane = (pane: Element): (() => void) => {
requestAnimationFrame(() => scrollSelectedIntoView(navigator));
setTimeout(() => scrollSelectedIntoView(navigator), 50);
const observer = new MutationObserver(() =>
scrollSelectedIntoView(navigator),
);
const observer = new MutationObserver(() => scrollSelectedIntoView(navigator));
observer.observe(navigator, {
subtree: true,
attributes: true,
@@ -15,10 +15,7 @@ jest.mock("./styles.css?inline", () => ({
default: "/* test */",
}));
import errorPageKittenPlugin, {
isSeqta404Page,
mountErrorPageKitten,
} from "./index";
import errorPageKittenPlugin, { isSeqta404Page, mountErrorPageKitten } from "./index";
const REBRANDED_404_BODY = `
<div class="message">
@@ -86,7 +83,9 @@ describe("errorPageKitten", () => {
document.title = "SEQTA Learn";
document.body.innerHTML = '<div id="container"></div>';
const cleanup = await errorPageKittenPlugin.run({} as Parameters<typeof errorPageKittenPlugin.run>[0]);
const cleanup = await errorPageKittenPlugin.run(
{} as Parameters<typeof errorPageKittenPlugin.run>[0],
);
expect(getCard()).toBeNull();
expect(cleanup).toBeDefined();
@@ -33,9 +33,7 @@ function isSeqtaRebranded404Message(message: Element): boolean {
const body = normalizePageText(message.textContent ?? "");
return (
body.includes("We can't find the page you're looking for") &&
body.includes(
"It may have been moved, deleted or the link might be out of date.",
) &&
body.includes("It may have been moved, deleted or the link might be out of date.") &&
body.includes("Ref: 404")
);
}
@@ -5,7 +5,7 @@ html.bsplus-kitten-404 {
}
html.bsplus-kitten-404 body {
background: #333;
font-family: 'Trebuchet MS', sans-serif;
font-family: "Trebuchet MS", sans-serif;
font-size: 12pt;
color: #aaa;
margin: 8px;
@@ -24,7 +24,8 @@ html.bsplus-kitten-404 .bsplus-kitten-404 {
margin: 64px auto;
background: #222;
border-radius: 4px;
box-shadow: -1px -1px rgba(0, 0, 0, 0.5),
box-shadow:
-1px -1px rgba(0, 0, 0, 0.5),
1px 1px rgba(255, 255, 255, 0.2);
padding: 0 0 8px;
text-align: center;
@@ -32,7 +33,8 @@ html.bsplus-kitten-404 .bsplus-kitten-404 {
html.bsplus-kitten-404 .bsplus-kitten-404 > h1 {
background: #612;
background-image: repeating-linear-gradient(
background-image:
repeating-linear-gradient(
135deg,
rgba(0, 0, 0, 0),
rgba(0, 0, 0, 0) 8px,
+2 -7
View File
@@ -7,10 +7,7 @@ import {
} from "../../core/settingsHelpers";
import { isSeqtaEngageExperience, isSeqtaLoginPage } from "@/seqta/utils/isSeqtaEngage";
import styles from "./src/core/styles.css?inline";
import {
resetSearchIndexes,
notifyOpenTabsResetSearchIndex,
} from "./src/indexing/resetIndexes";
import { resetSearchIndexes, notifyOpenTabsResetSearchIndex } from "./src/indexing/resetIndexes";
import {
formatHotkeyForDisplay,
getDefaultSearchHotkey,
@@ -58,9 +55,7 @@ const settings = defineSettings({
try {
await notifyOpenTabsResetSearchIndex();
await resetSearchIndexes();
alert(
"Search index and storage were reset.\n\nReload this tab to regenerate the index.",
);
alert("Search index and storage were reset.\n\nReload this tab to regenerate the index.");
} catch (e) {
alert(
"Failed to reset index: " +
@@ -40,7 +40,7 @@ async function getCurrentLesson() {
}
const lessons = timetableData.payload.items.sort((a: any, b: any) =>
a.from.localeCompare(b.from)
a.from.localeCompare(b.from),
);
const currentTime = new Date();
@@ -74,9 +74,9 @@ async function navigateToSpecificLesson(lesson: any) {
await waitForElm(".course .navigator", true, 100, 100);
const today = new Date();
const todayDateString = today.toLocaleDateString('en-GB', {
day: 'numeric',
month: 'short'
const todayDateString = today.toLocaleDateString("en-GB", {
day: "numeric",
month: "short",
});
const weeks = document.querySelectorAll(".course .navigator .week");
@@ -108,8 +108,9 @@ async function navigateToSpecificLesson(lesson: any) {
}
}
const todayButton = Array.from(document.querySelectorAll('#toolbar .uiButton'))
.find(button => button.textContent?.trim() === 'Today') as HTMLElement;
const todayButton = Array.from(document.querySelectorAll("#toolbar .uiButton")).find(
(button) => button.textContent?.trim() === "Today",
) as HTMLElement;
if (todayButton) {
todayButton.click();
@@ -204,13 +205,16 @@ const staticCommands: StaticCommandItem[] = [
category: "action",
text: "Compose Message",
action: () => {
window.postMessage({
window.postMessage(
{
type: "triggerKeyboardEvent",
key: 'm',
code: 'KeyM',
key: "m",
code: "KeyM",
keyCode: 77,
altKey: true
}, location.origin);
altKey: true,
},
location.origin,
);
},
keywords: ["compose", "message", "dm", "direct message", "new message"],
priority: 3,
@@ -8,10 +8,7 @@ import { isIndexingPaused } from "../indexing/indexingPause";
import { cleanupSearchBar, mountSearchBar } from "./mountSearchBar";
import { IndexedDbManager } from "embeddia";
import { checkAndHandleUpdate } from "../utils/versionCheck";
import {
getStoredPassiveItems,
installPassiveObserver,
} from "../indexing/passiveObserver";
import { getStoredPassiveItems, installPassiveObserver } from "../indexing/passiveObserver";
import { globalSearchIndexingEnabled } from "@/seqta/utils/performanceMode";
function scheduleIdleIndexing(run: () => void): void {
@@ -69,10 +66,11 @@ const globalSearchPlugin: Pick<Plugin<GlobalSearchSettings>, "run"> = {
// @ts-ignore
window.globalSearchDebug = {
resetWorker: async () =>
(await import("../indexing/worker/vectorWorkerManager")).VectorWorkerManager.getInstance().resetWorker(),
(
await import("../indexing/worker/vectorWorkerManager")
).VectorWorkerManager.getInstance().resetWorker(),
passiveItems: getStoredPassiveItems,
runSelfTests: async () =>
(await import("../indexing/selfTests")).runGlobalSearchSelfTests(),
runSelfTests: async () => (await import("../indexing/selfTests")).runGlobalSearchSelfTests(),
};
if (globalSearchIndexingEnabled(!!api.settings.passiveIndexing)) {
@@ -83,10 +81,7 @@ const globalSearchPlugin: Pick<Plugin<GlobalSearchSettings>, "run"> = {
}
}
if (
globalSearchIndexingEnabled(!!api.settings.runIndexingOnLoad) &&
!isIndexingPaused()
) {
if (globalSearchIndexingEnabled(!!api.settings.runIndexingOnLoad) && !isIndexingPaused()) {
scheduleIdleIndexing(() => {
if (!isIndexingPaused()) void runIndexing();
});
@@ -18,12 +18,8 @@ type AppRef = {
const SEARCH_SVG =
'<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>';
async function resolveTriggerWrapper(
titleElement: Element,
): Promise<HTMLElement | null> {
const existing = titleElement.querySelector(
".search-trigger-wrapper",
) as HTMLElement | null;
async function resolveTriggerWrapper(titleElement: Element): Promise<HTMLElement | null> {
const existing = titleElement.querySelector(".search-trigger-wrapper") as HTMLElement | null;
if (existing) return existing;
const custom =
@@ -65,8 +61,7 @@ function buildTriggerWrapper() {
}
function triggerParts(searchWrapper: HTMLElement) {
const q = <T extends HTMLElement>(sel: string) =>
searchWrapper.querySelector(sel) as T;
const q = <T extends HTMLElement>(sel: string) => searchWrapper.querySelector(sel) as T;
return {
searchWrapper,
searchAnchor: q(".search-trigger-anchor"),
@@ -80,11 +75,7 @@ function triggerParts(searchWrapper: HTMLElement) {
};
}
export async function mountSearchBar(
titleElement: Element,
api: any,
appRef: AppRef,
) {
export async function mountSearchBar(titleElement: Element, api: any, appRef: AppRef) {
const preRendered = await resolveTriggerWrapper(titleElement);
if (preRendered?.dataset.bsplusSearchWired === "1") return;
@@ -132,8 +123,7 @@ export async function mountSearchBar(
const DONE_HOLD_MS = 5000;
const DONE_FADE_MS = 550;
const statusLooksRough = (s: string) => /\b(fail|error|cancel)\b/i.test(s);
const truncateStatus = (s: string, max = 44) =>
s.length > max ? s.slice(0, max - 1) + "…" : s;
const truncateStatus = (s: string, max = 44) => (s.length > max ? s.slice(0, max - 1) + "…" : s);
const clearDoneFlashTimer = () => {
if (doneFlashTimer) clearTimeout(doneFlashTimer);
@@ -147,12 +137,7 @@ export async function mountSearchBar(
progressBarWrapper.classList.remove("is-active", "is-rough-complete");
searchAnchor.classList.remove("is-indexing");
searchButton.classList.remove("is-indexing");
progressText.classList.remove(
"is-active",
"is-rough",
"is-fading-done",
"is-done-message",
);
progressText.classList.remove("is-active", "is-rough", "is-fading-done", "is-done-message");
progressBar.style.width = "0%";
progressText.textContent = "";
ranIndexingCycle = false;
@@ -179,9 +164,7 @@ export async function mountSearchBar(
searchAnchor.classList.remove("is-indexing");
searchButton.classList.remove("is-indexing");
progressText.classList.remove("is-fading-done");
progressText.textContent = rough
? truncateStatus(indexingStatus!, 52)
: "Done!";
progressText.textContent = rough ? truncateStatus(indexingStatus!, 52) : "Done!";
progressText.classList.toggle("is-rough", rough);
progressBarWrapper.classList.toggle("is-rough-complete", rough);
progressText.classList.add("is-active", "is-done-message");
@@ -219,9 +202,7 @@ export async function mountSearchBar(
if (completionEligible) {
if (doneFlashTimer !== null || doneFadeTimer !== null) return;
scheduleCompletionFlash(
indexingStatus != null && statusLooksRough(indexingStatus),
);
scheduleCompletionFlash(indexingStatus != null && statusLooksRough(indexingStatus));
return;
}
@@ -325,16 +306,11 @@ export function cleanupSearchBar(appRef: AppRef) {
appRef.clearDoneFlashTimer = undefined;
if (appRef.progressHandler) {
window.removeEventListener(
"indexing-progress",
appRef.progressHandler as EventListener,
);
window.removeEventListener("indexing-progress", appRef.progressHandler as EventListener);
appRef.progressHandler = null;
}
const searchWrapper = document.querySelector(
".search-trigger-wrapper",
) as HTMLElement | null;
const searchWrapper = document.querySelector(".search-trigger-wrapper") as HTMLElement | null;
const customOwns = Boolean(
document.querySelector("#title.bsplus-custom-title") ||
document.getElementById("bsplus-title-root"),
@@ -212,15 +212,10 @@
}
.search-progress-bar::after {
content: '';
content: "";
position: absolute;
inset: 0;
background: linear-gradient(
90deg,
transparent,
rgba(255, 255, 255, 0.28),
transparent
);
background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.28), transparent);
animation: shimmer 2s infinite;
}
/*
@@ -236,7 +231,10 @@
font-weight: 500;
opacity: 0;
transform: translateX(-4px);
transition: opacity 0.2s ease, transform 0.2s ease, color 0.25s ease;
transition:
opacity 0.2s ease,
transform 0.2s ease,
color 0.25s ease;
pointer-events: none;
max-width: 240px;
overflow: hidden;
@@ -43,8 +43,7 @@ export const coursesPayload = {
t: "English GEN 1",
i: 3830,
m: 29611,
document:
'{"document":{"modules":[{"uuid":"1641cf87-ae08-4bcb-832d-d5709d84d0c5"}]}}',
document: '{"document":{"modules":[{"uuid":"1641cf87-ae08-4bcb-832d-d5709d84d0c5"}]}}',
w: [
[
{ t: "", h: "", i: 248293, l: "", n: 0, o: "" },
@@ -86,8 +85,7 @@ export const documentsPayload = [
filename: "School Glossary.docx",
size: "14931",
context_uuid: "3162189c-2052-4f83-ad83-a66c57460ea2",
mimetype:
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
mimetype: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
created_date: "2021-08-04 12:55:55.102653+00",
title: "School Glossary",
uuid: "3162189c-2052-4f83-ad83-a66c57460ea2",
@@ -139,8 +137,7 @@ export const folioListPayload = {
export const folioEntryPayload = {
forum: 478,
contents:
'[[embed:raw|<p>Some <strong>reflection</strong> text.</p>]] Plain trailing text.',
contents: "[[embed:raw|<p>Some <strong>reflection</strong> text.</p>]] Plain trailing text.",
created: "2026-04-14 10:32:34.264641+00",
allow_comments: true,
author: { year: "Year 10", name: "Jacob Johannesburg", id: 3111 },
@@ -3,7 +3,7 @@ import type { IndexItem } from "./types";
import ReactFiber from "@/seqta/utils/ReactFiber";
import { delay } from "@/seqta/utils/delay";
import { verboseLog } from '@/utils/verboseLog';
import { verboseLog } from "@/utils/verboseLog";
interface MessageMetadata {
messageId: number;
author: string;
@@ -75,12 +75,12 @@ export const actionMap: Record<string, ActionHandler<any>> = {
});
// send a network request to mark as read
fetch('/seqta/student/save/message', {
fetch("/seqta/student/save/message", {
method: "POST",
credentials: "include",
body: JSON.stringify({
items: [item.metadata.messageId],
mode: 'x-read',
mode: "x-read",
read: true,
}),
});
@@ -104,7 +104,10 @@ export const actionMap: Record<string, ActionHandler<any>> = {
itemClone = JSON.parse(JSON.stringify(item));
metadata = itemClone.metadata || {};
} catch (e) {
console.warn("[Assessment Action] Failed to clone item, trying to clone metadata separately:", e);
console.warn(
"[Assessment Action] Failed to clone item, trying to clone metadata separately:",
e,
);
try {
// If full clone fails, try cloning just metadata
metadata = JSON.parse(JSON.stringify(item.metadata || {}));
@@ -112,7 +115,7 @@ export const actionMap: Record<string, ActionHandler<any>> = {
} catch (e2) {
console.warn("[Assessment Action] Failed to clone metadata, using direct access:", e2);
itemClone = item;
metadata = item.metadata || {} as AssessmentMetadata;
metadata = item.metadata || ({} as AssessmentMetadata);
}
}
@@ -153,49 +156,63 @@ export const actionMap: Record<string, ActionHandler<any>> = {
}
};
if (getMetadataValue('isMessageBased')) {
if (getMetadataValue("isMessageBased")) {
window.location.hash = `#?page=/messages`;
await waitForElm('[class*="Viewer__Viewer___"] > div', true, 20);
// Select the specific direct message
ReactFiber.find('[class*="Viewer__Viewer___"] > div').setState({
selected: new Set([getMetadataValue('messageId')]),
selected: new Set([getMetadataValue("messageId")]),
});
} else {
// Extract values - check both camelCase and PascalCase, and try multiple access methods
let programmeId = getMetadataValue('programmeId', 'programmeID');
let metaclassId = getMetadataValue('metaclassId', 'metaclassID');
let assessmentId = getMetadataValue('assessmentId', 'assessmentID');
let programmeId = getMetadataValue("programmeId", "programmeID");
let metaclassId = getMetadataValue("metaclassId", "metaclassID");
let assessmentId = getMetadataValue("assessmentId", "assessmentID");
// Fallback: try to extract assessmentId from item ID if metadata is missing
if ((assessmentId === undefined || assessmentId === null) && itemClone.id && itemClone.id.startsWith('assignment-')) {
const extractedId = itemClone.id.replace('assignment-', '');
if (
(assessmentId === undefined || assessmentId === null) &&
itemClone.id &&
itemClone.id.startsWith("assignment-")
) {
const extractedId = itemClone.id.replace("assignment-", "");
assessmentId = Number(extractedId) || extractedId;
verboseLog("[Assessment Action] Extracted assessmentId from item ID:", assessmentId);
}
// Convert to numbers, but preserve 0 as valid
if (programmeId !== undefined && programmeId !== null && programmeId !== '') {
if (programmeId !== undefined && programmeId !== null && programmeId !== "") {
const num = Number(programmeId);
programmeId = isNaN(num) ? programmeId : num;
}
if (metaclassId !== undefined && metaclassId !== null && metaclassId !== '') {
if (metaclassId !== undefined && metaclassId !== null && metaclassId !== "") {
const num = Number(metaclassId);
metaclassId = isNaN(num) ? metaclassId : num;
}
if (assessmentId !== undefined && assessmentId !== null && assessmentId !== '') {
if (assessmentId !== undefined && assessmentId !== null && assessmentId !== "") {
const num = Number(assessmentId);
assessmentId = isNaN(num) ? assessmentId : num;
}
// Check if values exist (including 0, which is a valid ID)
// Use typeof check to properly handle 0
const hasProgrammeId = programmeId !== undefined && programmeId !== null && programmeId !== '' && typeof programmeId === 'number';
const hasMetaclassId = metaclassId !== undefined && metaclassId !== null && metaclassId !== '' && typeof metaclassId === 'number';
const hasAssessmentId = assessmentId !== undefined && assessmentId !== null && assessmentId !== '' && typeof assessmentId === 'number';
const hasProgrammeId =
programmeId !== undefined &&
programmeId !== null &&
programmeId !== "" &&
typeof programmeId === "number";
const hasMetaclassId =
metaclassId !== undefined &&
metaclassId !== null &&
metaclassId !== "" &&
typeof metaclassId === "number";
const hasAssessmentId =
assessmentId !== undefined &&
assessmentId !== null &&
assessmentId !== "" &&
typeof assessmentId === "number";
if (hasProgrammeId && hasMetaclassId && hasAssessmentId) {
const url = `#?page=/assessments/${programmeId}:${metaclassId}&item=${assessmentId}`;
@@ -226,15 +243,11 @@ export const actionMap: Record<string, ActionHandler<any>> = {
}) as ActionHandler<any>,
subjectassessment: ((item: IndexItem) => {
navigateToHashRoute(
`/assessments/${item.metadata.programme}:${item.metadata.subjectId}`,
);
navigateToHashRoute(`/assessments/${item.metadata.programme}:${item.metadata.subjectId}`);
}) as ActionHandler<any>,
subjectcourse: ((item: IndexItem) => {
navigateToHashRoute(
`/courses/${item.metadata.programme}:${item.metadata.subjectId}`,
);
navigateToHashRoute(`/courses/${item.metadata.programme}:${item.metadata.subjectId}`);
}) as ActionHandler<any>,
forum: ((item: IndexItem) => {
@@ -322,8 +335,7 @@ export const actionMap: Record<string, ActionHandler<any>> = {
passive: ((item: IndexItem) => {
const md = (item.metadata ?? {}) as Record<string, unknown>;
const route = typeof md.route === "string" ? (md.route as string) : "";
const sourcePage =
typeof md.sourcePage === "string" ? (md.sourcePage as string) : "";
const sourcePage = typeof md.sourcePage === "string" ? (md.sourcePage as string) : "";
const routeParts = route
.replace(/^\/seqta\/student\/?/, "")
.replace(/^load\//, "")
@@ -347,24 +359,16 @@ export const actionMap: Record<string, ActionHandler<any>> = {
};
const programme = num("programme") ?? num("programmeId") ?? num("programmeID");
const metaclass =
num("metaclass") ?? num("metaclassId") ?? num("metaclassID");
const metaclass = num("metaclass") ?? num("metaclassId") ?? num("metaclassID");
const portalUuid = str("portalUuid") ?? str("uuid");
const forumId = num("forumId") ?? num("forum");
const year = num("year");
const assessmentId =
num("assessmentId") ??
num("assessmentID") ??
num("entityId") ??
num("id");
const assessmentId = num("assessmentId") ?? num("assessmentID") ?? num("entityId") ?? num("id");
const navigateToAssessment = (): void => {
if (programme !== undefined && metaclass !== undefined) {
const itemSuffix =
assessmentId !== undefined ? `&item=${assessmentId}` : "";
navigateToHashRoute(
`/assessments/${programme}:${metaclass}${itemSuffix}`,
);
const itemSuffix = assessmentId !== undefined ? `&item=${assessmentId}` : "";
navigateToHashRoute(`/assessments/${programme}:${metaclass}${itemSuffix}`);
return;
}
if (assessmentId !== undefined) {
@@ -302,10 +302,7 @@ export async function seqtaFetchPayload<T = any>(
const res = await seqtaFetchJson<T>(path, body, options);
return res.payload ?? null;
} catch (e) {
console.warn(
`[Global Search API] Request to ${normalizeSeqtaPath(path)} failed:`,
e,
);
console.warn(`[Global Search API] Request to ${normalizeSeqtaPath(path)} failed:`, e);
return null;
}
}
@@ -36,10 +36,7 @@ function attachConnection(db: IDBDatabase): void {
updateVersion(db.version);
}
function setupUpgradeHandler(
request: IDBOpenDBRequest,
extraStore?: string,
): void {
function setupUpgradeHandler(request: IDBOpenDBRequest, extraStore?: string): void {
request.onupgradeneeded = (event) => {
const db = request.result;
@@ -61,10 +58,7 @@ function openDatabase(version?: number, extraStore?: string): Promise<IDBDatabas
return new Promise((resolve, reject) => {
let request: IDBOpenDBRequest;
try {
request =
version != null
? indexedDB.open(DB_NAME, version)
: indexedDB.open(DB_NAME);
request = version != null ? indexedDB.open(DB_NAME, version) : indexedDB.open(DB_NAME);
} catch (error) {
reject(error);
return;
@@ -85,10 +79,7 @@ function wipeDatabase(): Promise<void> {
return deleteDatabaseWithRetries(DB_NAME);
}
function deleteDatabaseWithRetries(
name: string,
maxAttempts = 6,
): Promise<void> {
function deleteDatabaseWithRetries(name: string, maxAttempts = 6): Promise<void> {
return new Promise((resolve) => {
const attemptDelete = (attempt: number) => {
let req: IDBOpenDBRequest;
@@ -146,9 +137,7 @@ async function openDBInternal(): Promise<IDBDatabase> {
const domError = error as DOMException | undefined;
if (domError?.name === "VersionError") {
console.warn(
"[DB] localStorage version out of sync with IndexedDB; opening current version",
);
console.warn("[DB] localStorage version out of sync with IndexedDB; opening current version");
invalidateConnection();
try {
return await openDatabase();
@@ -293,9 +282,7 @@ export async function ensureStoresExist(stores: string[]): Promise<void> {
return;
}
const missing = uniqueStores.filter(
(store) => !db.objectStoreNames.contains(store),
);
const missing = uniqueStores.filter((store) => !db.objectStoreNames.contains(store));
if (missing.length === 0) return;
invalidateConnection();
@@ -334,9 +321,7 @@ async function withObjectStore<T>(
export async function getAll(store: string): Promise<any[]> {
try {
return await withObjectStore(store, "readonly", async (s) =>
idbRequest(s.getAll()),
);
return await withObjectStore(store, "readonly", async (s) => idbRequest(s.getAll()));
} catch (error) {
console.error(`Error in getAll for store ${store}:`, error);
return [];
@@ -345,20 +330,14 @@ export async function getAll(store: string): Promise<any[]> {
export async function get(store: string, key: string): Promise<any> {
try {
return await withObjectStore(store, "readonly", async (s) =>
idbRequest(s.get(key)),
);
return await withObjectStore(store, "readonly", async (s) => idbRequest(s.get(key)));
} catch (error) {
console.error(`Error in get for store ${store}, key ${key}:`, error);
return null;
}
}
export async function put(
store: string,
value: any,
key?: string,
): Promise<void> {
export async function put(store: string, value: any, key?: string): Promise<void> {
try {
await withObjectStore(store, "readwrite", async (s) => {
await idbRequest(key ? s.put(value, key) : s.put(value));
@@ -70,11 +70,7 @@ export function looksLikeSecretValue(value: unknown): boolean {
if (/^[A-Za-z0-9+/=._-]{32,}$/.test(trimmed) && !/[.,!?]/.test(trimmed)) {
// Reject obvious URLs and UUIDs (they're useful and not secret).
if (/^https?:\/\//i.test(trimmed)) return false;
if (
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(
trimmed,
)
) {
if (/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(trimmed)) {
return false;
}
return true;
@@ -119,10 +115,7 @@ const DEFAULT_EXTRACT_OPTIONS: Required<ExtractTextOptions> = {
maxStringLength: 8000,
};
export function extractTextFromValue(
value: unknown,
options: ExtractTextOptions = {},
): string {
export function extractTextFromValue(value: unknown, options: ExtractTextOptions = {}): string {
const opts = { ...DEFAULT_EXTRACT_OPTIONS, ...options };
const parts: string[] = [];
let remaining = opts.maxChars;
@@ -197,9 +190,7 @@ export function redactSensitive<T>(value: T, depth = 0): T {
if (depth >= 8) return value;
if (Array.isArray(value)) {
return value
.slice(0, 200)
.map((v) => redactSensitive(v, depth + 1)) as unknown as T;
return value.slice(0, 200).map((v) => redactSensitive(v, depth + 1)) as unknown as T;
}
if (typeof value === "object") {
const out: Record<string, unknown> = {};
@@ -11,7 +11,7 @@ import { isIndexingPaused } from "./indexingPause";
import { setIndexingActive } from "./indexingState";
import { isPluginBlockedByPerformanceMode } from "@/seqta/utils/performanceMode";
import { verboseDebug } from '@/utils/verboseLog';
import { verboseDebug } from "@/utils/verboseLog";
import { delay } from "@/seqta/utils/delay";
const META_STORE = "meta";
const LOCK_KEY = "bsq-indexer-lock";
@@ -104,10 +104,7 @@ function indexItemsEqual(a: IndexItem, b: IndexItem): boolean {
return indexItemStorageKey(a) === indexItemStorageKey(b);
}
async function diffAndStoreItems(
targetStore: string,
items: IndexItem[],
): Promise<void> {
async function diffAndStoreItems(targetStore: string, items: IndexItem[]): Promise<void> {
const validItems = items.filter((i) => i && i.id);
if (validItems.length !== items.length) {
console.warn(
@@ -116,9 +113,7 @@ async function diffAndStoreItems(
}
const existing = (await getAll(targetStore)) as IndexItem[];
const existingMap = new Map(
existing.filter((i) => i?.id).map((i) => [i.id, i]),
);
const existingMap = new Map(existing.filter((i) => i?.id).map((i) => [i.id, i]));
const newMap = new Map(validItems.map((i) => [i.id, i]));
const puts: Array<{ key: string; value: IndexItem }> = [];
@@ -194,8 +189,8 @@ function startHeartbeat() {
if (!lockId) return;
heartbeatTimer = setInterval(() => {
if (localStorage.getItem(LOCK_KEY)?.endsWith(lockId.split('-')[1])) {
const newLockId = `${Date.now()}-${lockId.split('-')[1]}`;
if (localStorage.getItem(LOCK_KEY)?.endsWith(lockId.split("-")[1])) {
const newLockId = `${Date.now()}-${lockId.split("-")[1]}`;
localStorage.setItem(LOCK_KEY, newLockId);
}
}, HEARTBEAT_INTERVAL);
@@ -247,9 +242,7 @@ export async function loadAllStoredItems(): Promise<IndexItem[]> {
console.error(`Error loading items for job store ${jobId}:`, error);
}
}
verboseDebug(
`[Indexer] Loaded ${all.length} items from all primary stores.`,
);
verboseDebug(`[Indexer] Loaded ${all.length} items from all primary stores.`);
return all;
}
@@ -275,10 +268,22 @@ function dispatchVectorProgress(
dispatchProgress(++completed, totalSteps, false, "Indexing finished", "Vectorization complete");
return completed;
} else if (status === "error") {
dispatchProgress(completed, totalSteps, false, "Vectorization failed", `Vectorization error: ${message}`);
dispatchProgress(
completed,
totalSteps,
false,
"Vectorization failed",
`Vectorization error: ${message}`,
);
return completed;
} else if (status === "cancelled") {
dispatchProgress(completed, totalSteps, false, "Vectorization cancelled", `Vectorization cancelled: ${message}`);
dispatchProgress(
completed,
totalSteps,
false,
"Vectorization cancelled",
`Vectorization cancelled: ${message}`,
);
return completed;
}
@@ -293,9 +298,7 @@ export async function runIndexing(): Promise<void> {
}
if (isIndexingPaused()) {
verboseDebug(
"[Indexer] Skipping indexing — index was reset; reload the page to rebuild.",
);
verboseDebug("[Indexer] Skipping indexing — index was reset; reload the page to rebuild.");
return;
}
@@ -324,44 +327,23 @@ export async function runIndexing(): Promise<void> {
for (const jobId of jobIds) {
if (isIndexingPaused()) {
verboseDebug(
"[Indexer] Indexing stopped — index was reset; reload the page to rebuild.",
);
dispatchProgress(
completedJobs,
totalSteps,
false,
"Indexing paused — reload to rebuild",
);
verboseDebug("[Indexer] Indexing stopped — index was reset; reload the page to rebuild.");
dispatchProgress(completedJobs, totalSteps, false, "Indexing paused — reload to rebuild");
return;
}
dispatchProgress(
completedJobs,
totalSteps,
true,
`Running job: ${jobs[jobId].label}`,
);
dispatchProgress(completedJobs, totalSteps, true, `Running job: ${jobs[jobId].label}`);
const job = jobs[jobId];
const lastRun = await getLastRunMeta(jobId);
if (!shouldRun(job, lastRun)) {
verboseDebug(
`%c[Indexer] Skipping job "${jobId}" (not due)`,
"color: gray",
);
verboseDebug(`%c[Indexer] Skipping job "${jobId}" (not due)`, "color: gray");
completedJobs++;
dispatchProgress(
completedJobs,
totalSteps,
true,
`Skipped job: ${job.label}`,
);
dispatchProgress(completedJobs, totalSteps, true, `Skipped job: ${job.label}`);
continue;
}
const getStoredItems = async (storeId?: string) =>
await getAll(storeId ?? jobId);
const getStoredItems = async (storeId?: string) => await getAll(storeId ?? jobId);
const setStoredItems = async (items: IndexItem[], storeId?: string) => {
const targetStore = storeId ?? jobId;
await diffAndStoreItems(targetStore, items);
@@ -422,12 +404,7 @@ export async function runIndexing(): Promise<void> {
}
completedJobs++;
dispatchProgress(
completedJobs,
totalSteps,
true,
`Finished job: ${job.label}`,
);
dispatchProgress(completedJobs, totalSteps, true, `Finished job: ${job.label}`);
}
let allItemsInPrimaryStores = await loadAllStoredItems();
@@ -451,7 +428,9 @@ export async function runIndexing(): Promise<void> {
// Pre-filter items to avoid initializing worker if nothing new
const vectorizedItemIds = await getVectorizedItemIds();
const newItemsToVectorize = allItemsInPrimaryStores.filter(item => !vectorizedItemIds.has(item.id));
const newItemsToVectorize = allItemsInPrimaryStores.filter(
(item) => !vectorizedItemIds.has(item.id),
);
if (newItemsToVectorize.length > 0) {
verboseDebug(
@@ -475,13 +454,7 @@ export async function runIndexing(): Promise<void> {
"color: red",
error,
);
dispatchProgress(
completedJobs,
totalSteps,
false,
"Vectorization failed",
String(error),
);
dispatchProgress(completedJobs, totalSteps, false, "Vectorization failed", String(error));
}
} else {
verboseDebug(
@@ -1,7 +1,4 @@
import {
isIndexingActive,
setIndexingActive,
} from "./indexingState";
import { isIndexingActive, setIndexingActive } from "./indexingState";
describe("indexingState", () => {
afterEach(() => {
@@ -1,6 +1,6 @@
import type { IndexItem, Job } from "../types";
import { verboseDebug } from '@/utils/verboseLog';
import { verboseDebug } from "@/utils/verboseLog";
import { delay } from "@/seqta/utils/delay";
import { getUserInfo } from "@/seqta/utils/userInfo";
const fetchJSON = async (url: string, body: any) => {
@@ -28,9 +28,7 @@ const fetchUpcomingAssessments = async (student: number) => {
const fetchSubjects = async () => {
try {
const res = await fetchJSON("/seqta/student/load/subjects?", {});
return res.payload
?.filter((s: any) => s.active === 1)
?.flatMap((s: any) => s.subjects) || [];
return res.payload?.filter((s: any) => s.active === 1)?.flatMap((s: any) => s.subjects) || [];
} catch (e) {
console.error("[Assignments job] Failed to fetch subjects:", e);
return [];
@@ -70,9 +68,12 @@ const fetchPastAssessments = async (student: number, subjects: any[]) => {
res.payload.tasks.forEach(processAssessment);
}
} catch (e) {
console.warn(`[Assignments job] Failed to fetch past assessments for subject ${subject.code || subject.subject || 'unknown'}:`, e);
console.warn(
`[Assignments job] Failed to fetch past assessments for subject ${subject.code || subject.subject || "unknown"}:`,
e,
);
}
})
}),
);
return Object.values(map);
@@ -118,14 +119,18 @@ export const assignmentsJob: Job = {
const { id: student } = await getUserInfo();
verboseDebug("[Assignments job] Starting indexing - fetching all assessments (upcoming and past)...");
verboseDebug(
"[Assignments job] Starting indexing - fetching all assessments (upcoming and past)...",
);
const [upcoming, subjects] = await Promise.all([
fetchUpcomingAssessments(student),
fetchSubjects(),
]);
verboseDebug(`[Assignments job] Fetched ${upcoming.length} upcoming assessments and ${subjects.length} subjects`);
verboseDebug(
`[Assignments job] Fetched ${upcoming.length} upcoming assessments and ${subjects.length} subjects`,
);
const past = await fetchPastAssessments(student, subjects);
@@ -188,7 +193,7 @@ export const assignmentsJob: Job = {
metaclass,
programmeID: programme,
metaclassID: metaclass,
isUpcoming: false
isUpcoming: false,
});
}
}
@@ -198,9 +203,11 @@ export const assignmentsJob: Job = {
const processedIds = new Set<string>();
const assessmentArray = Array.from(allAssessments.values());
const pastCount = assessmentArray.filter(a => !a.isUpcoming).length;
const upcomingCount = assessmentArray.filter(a => a.isUpcoming).length;
verboseDebug(`[Assignments job] Processing ${assessmentArray.length} total assessments (${upcomingCount} upcoming, ${pastCount} past)`);
const pastCount = assessmentArray.filter((a) => !a.isUpcoming).length;
const upcomingCount = assessmentArray.filter((a) => a.isUpcoming).length;
verboseDebug(
`[Assignments job] Processing ${assessmentArray.length} total assessments (${upcomingCount} upcoming, ${pastCount} past)`,
);
const batchSize = 15;
// The assessment details endpoint 404s, so details aren't fetched.
@@ -218,7 +225,6 @@ export const assignmentsJob: Job = {
processedIds.add(id);
const description = "";
const subjectName = assessment.subject || assessment.code || "Unknown Subject";
@@ -228,7 +234,9 @@ export const assignmentsJob: Job = {
const metaclassId = assessment.metaclassID || assessment.metaclass;
if (!programmeId || !metaclassId || !assessment.id) {
console.warn(`[Assignments job] Skipping assignment ${assessment.id} - missing required IDs:`, {
console.warn(
`[Assignments job] Skipping assignment ${assessment.id} - missing required IDs:`,
{
programmeId,
metaclassId,
assessmentId: assessment.id,
@@ -237,32 +245,36 @@ export const assignmentsJob: Job = {
programme: assessment.programme,
metaclass: assessment.metaclass,
assessment,
});
},
);
return null;
}
let finalProgrammeId: number | undefined;
let finalMetaclassId: number | undefined;
if (programmeId !== undefined && programmeId !== null && programmeId !== '') {
if (programmeId !== undefined && programmeId !== null && programmeId !== "") {
const num = Number(programmeId);
finalProgrammeId = isNaN(num) ? undefined : num;
}
if (metaclassId !== undefined && metaclassId !== null && metaclassId !== '') {
if (metaclassId !== undefined && metaclassId !== null && metaclassId !== "") {
const num = Number(metaclassId);
finalMetaclassId = isNaN(num) ? undefined : num;
}
if (finalProgrammeId === undefined || finalMetaclassId === undefined || !assessment.id) {
console.error(`[Assignments job] ❌ Skipping assignment ${assessment.id} - invalid IDs after conversion:`, {
console.error(
`[Assignments job] ❌ Skipping assignment ${assessment.id} - invalid IDs after conversion:`,
{
programmeId: finalProgrammeId,
metaclassId: finalMetaclassId,
assessmentId: assessment.id,
rawProgrammeId: programmeId,
rawMetaclassId: metaclassId,
assessment,
});
},
);
return null;
}
@@ -270,7 +282,8 @@ export const assignmentsJob: Job = {
id,
text: assessment.title || assessment.name || "Untitled Assignment",
category: "assignments",
content: `${description}\nSubject: ${subjectName}\nDue: ${assessment.due || "No due date"}`.trim(),
content:
`${description}\nSubject: ${subjectName}\nDue: ${assessment.due || "No due date"}`.trim(),
dateAdded: dueDate || Date.now(),
metadata: {
assessmentId: assessment.id,
@@ -302,10 +315,10 @@ export const assignmentsJob: Job = {
});
return item;
})
}),
);
batchItems.forEach(item => {
batchItems.forEach((item) => {
if (item) {
items.push(item);
}
@@ -316,20 +329,23 @@ export const assignmentsJob: Job = {
}
}
const newItemsCount = items.filter(item => !existingIds.has(item.id)).length;
const newItemsCount = items.filter((item) => !existingIds.has(item.id)).length;
const updatedItemsCount = items.length - newItemsCount;
verboseDebug(`[Assignments job] Indexed ${items.length} assignment items (${newItemsCount} new, ${updatedItemsCount} updated)`);
verboseDebug(
`[Assignments job] Indexed ${items.length} assignment items (${newItemsCount} new, ${updatedItemsCount} updated)`,
);
return items;
},
purge: (items) => {
// Old assignments stay searchable; only items missing required metadata are dropped.
return items.filter((i) => {
return i.metadata &&
return (
i.metadata &&
i.metadata.assessmentId &&
i.metadata.programmeId !== undefined &&
i.metadata.metaclassId !== undefined;
i.metadata.metaclassId !== undefined
);
});
},
};
@@ -3,7 +3,7 @@ import { seqtaFetchPayload } from "../api";
import { buildIndexItem } from "../extract";
import { htmlToPlainText } from "../utils";
import { verboseDebug } from '@/utils/verboseLog';
import { verboseDebug } from "@/utils/verboseLog";
/**
* Indexes per-subject course content from `/seqta/student/load/courses`.
*
@@ -36,9 +36,7 @@ interface CoursePayload {
document?: string;
}
const fetchActiveSubjects = async (): Promise<
SubjectsListPayload["subjects"]
> => {
const fetchActiveSubjects = async (): Promise<SubjectsListPayload["subjects"]> => {
const payload = await seqtaFetchPayload<SubjectsListPayload[]>(
"/seqta/student/load/subjects",
{},
@@ -50,11 +48,7 @@ const fetchActiveSubjects = async (): Promise<
if (!semester || !Array.isArray(semester.subjects)) continue;
if (semester.active !== 1) continue;
for (const subject of semester.subjects) {
if (
subject &&
Number.isFinite(subject.programme) &&
Number.isFinite(subject.metaclass)
) {
if (subject && Number.isFinite(subject.programme) && Number.isFinite(subject.metaclass)) {
out.push(subject);
}
}
@@ -129,13 +123,10 @@ export const coursesJob: Job = {
status: `Running job: Courses (${processedSubjects + 1}/${totalSubjects})`,
});
const payload = await seqtaFetchPayload<CoursePayload>(
"/seqta/student/load/courses",
{
const payload = await seqtaFetchPayload<CoursePayload>("/seqta/student/load/courses", {
programme: String(subject.programme),
metaclass: String(subject.metaclass),
},
);
});
if (!payload) {
processedSubjects++;
@@ -150,8 +141,7 @@ export const coursesJob: Job = {
"Course";
const lessonText = flattenLessonHtml(payload);
const courseCode =
(typeof payload.c === "string" && payload.c.trim()) || subject.code;
const courseCode = (typeof payload.c === "string" && payload.c.trim()) || subject.code;
const summary = [courseCode, lessonText]
.filter((s) => s && s.length > 0)
@@ -1,7 +1,7 @@
import type { IndexItem, Job } from "../types";
import { seqtaFetchPayload } from "../api";
import { verboseDebug } from '@/utils/verboseLog';
import { verboseDebug } from "@/utils/verboseLog";
/**
* Indexes file metadata from `/seqta/student/load/documents`.
*
@@ -87,10 +87,7 @@ export const documentsJob: Job = {
if (seen.has(id)) continue;
seen.add(id);
const title =
doc.title?.trim() ||
doc.filename?.trim() ||
`Document ${doc.file ?? uuid}`;
const title = doc.title?.trim() || doc.filename?.trim() || `Document ${doc.file ?? uuid}`;
const sizeText = prettySize(doc.size);
const mimeLabel = describeMime(doc.mimetype);
@@ -117,8 +114,7 @@ export const documentsJob: Job = {
fileId: doc.file,
filename: doc.filename,
mimetype: doc.mimetype,
sizeBytes:
typeof doc.size === "string" ? parseInt(doc.size, 10) : doc.size,
sizeBytes: typeof doc.size === "string" ? parseInt(doc.size, 10) : doc.size,
categoryId: category.id,
categoryName: category.category,
createdDate: doc.created_date,
@@ -3,7 +3,7 @@ import { seqtaFetchPayload } from "../api";
import { htmlToPlainText } from "../utils";
import { delay } from "@/seqta/utils/delay";
import { verboseDebug } from '@/utils/verboseLog';
import { verboseDebug } from "@/utils/verboseLog";
/**
* Indexes student folio entries from `/seqta/student/folio`.
*
@@ -61,10 +61,11 @@ export const folioJob: Job = {
const stored = await ctx.getStoredItems("folio");
const existing = new Map(stored.map((i) => [i.id, i]));
const list = await seqtaFetchPayload<FolioListPayload | null>(
"/seqta/student/folio",
{ mode: "list", page: 0, filters: {} },
);
const list = await seqtaFetchPayload<FolioListPayload | null>("/seqta/student/folio", {
mode: "list",
page: 0,
filters: {},
});
if (!list || !Array.isArray(list.list)) return [];
const items: IndexItem[] = [];
@@ -88,10 +89,10 @@ export const folioJob: Job = {
}
try {
const detail = await seqtaFetchPayload<FolioEntryPayload | null>(
"/seqta/student/folio",
{ mode: "load", id: entry.id },
);
const detail = await seqtaFetchPayload<FolioEntryPayload | null>("/seqta/student/folio", {
mode: "load",
id: entry.id,
});
const rawContents = detail?.contents ?? "";
const flattened = stripEmbedRaw(rawContents);
const content = flattened.slice(0, 4000);
@@ -21,9 +21,7 @@ export const forumsJob: Job = {
frequency: { type: "expiry", afterMs: 30 * 24 * 60 * 60 * 1000 }, // 30 days
run: async (ctx) => {
const existingIds = new Set(
(await ctx.getStoredItems("forums")).map((i) => i.id),
);
const existingIds = new Set((await ctx.getStoredItems("forums")).map((i) => i.id));
let list;
try {
@@ -61,7 +59,7 @@ export const forumsJob: Job = {
return items;
},
/** Keep only forums from the last year. */
/** Keep only forums from the last year. */
purge: (items) => {
const oneYearAgo = Date.now() - 365 * 24 * 60 * 60 * 1000;
return items.filter((i) => i.dateAdded >= oneYearAgo);
@@ -3,7 +3,7 @@ import { seqtaFetchPayload } from "../api";
import { extractTextFromValue } from "../extract";
import { delay } from "@/seqta/utils/delay";
import { verboseDebug } from '@/utils/verboseLog';
import { verboseDebug } from "@/utils/verboseLog";
/**
* Indexes student goals from `/seqta/student/load/goals`.
*
@@ -52,10 +52,10 @@ export const goalsJob: Job = {
for (const year of years) {
try {
const yearGoals = await seqtaFetchPayload<GoalEntry[] | null>(
"/seqta/student/load/goals",
{ mode: "list", year },
);
const yearGoals = await seqtaFetchPayload<GoalEntry[] | null>("/seqta/student/load/goals", {
mode: "list",
year,
});
if (!Array.isArray(yearGoals)) continue;
for (const goal of yearGoals) {
@@ -66,9 +66,9 @@ export const goalsJob: Job = {
if (seen.has(id)) continue;
seen.add(id);
const title =
goal.title?.trim() || goal.description?.slice(0, 80) || `Goal ${stableId}`;
const dateAdded = goal.updated || goal.created
const title = goal.title?.trim() || goal.description?.slice(0, 80) || `Goal ${stableId}`;
const dateAdded =
goal.updated || goal.created
? new Date(goal.updated ?? goal.created!).getTime() || Date.now()
: Date.now();
@@ -5,7 +5,7 @@ import { VectorWorkerManager } from "../worker/vectorWorkerManager";
import { loadAllStoredItems } from "../indexer";
import { publishDynamicItemsUpdate } from "../renderComponents";
import { verboseInfo, verboseLog } from '@/utils/verboseLog';
import { verboseInfo, verboseLog } from "@/utils/verboseLog";
const RATE_LIMIT_CONFIG = {
minDelay: 30,
maxDelay: 3000,
@@ -89,8 +89,7 @@ export const fetchMessageContent = async (
if (retryCount < RATE_LIMIT_CONFIG.maxRetries) {
const retryDelay =
RATE_LIMIT_CONFIG.baseDelay *
Math.pow(RATE_LIMIT_CONFIG.backoffMultiplier, retryCount);
RATE_LIMIT_CONFIG.baseDelay * Math.pow(RATE_LIMIT_CONFIG.backoffMultiplier, retryCount);
await delay(Math.min(retryDelay, RATE_LIMIT_CONFIG.maxDelay));
return fetchMessageContent(id, retryCount + 1);
}
@@ -99,17 +98,9 @@ export const fetchMessageContent = async (
}
};
function calculateAdaptiveDelay(
progress: MessagesProgress,
responseTime: number,
): number {
const {
currentDelay,
failedRequests,
lastSuccessTime,
circuitBreakerOpen,
consecutiveFailures,
} = progress;
function calculateAdaptiveDelay(progress: MessagesProgress, responseTime: number): number {
const { currentDelay, failedRequests, lastSuccessTime, circuitBreakerOpen, consecutiveFailures } =
progress;
const timeSinceLastSuccess = Date.now() - lastSuccessTime;
if (circuitBreakerOpen) {
@@ -118,17 +109,12 @@ function calculateAdaptiveDelay(
if (consecutiveFailures > 2 || failedRequests > 3 || responseTime > 3000) {
return Math.min(
currentDelay *
(RATE_LIMIT_CONFIG.backoffMultiplier + consecutiveFailures * 0.2),
currentDelay * (RATE_LIMIT_CONFIG.backoffMultiplier + consecutiveFailures * 0.2),
RATE_LIMIT_CONFIG.maxDelay,
);
}
if (
responseTime < 300 &&
timeSinceLastSuccess > 5000 &&
consecutiveFailures === 0
) {
if (responseTime < 300 && timeSinceLastSuccess > 5000 && consecutiveFailures === 0) {
return Math.max(currentDelay * 0.7, RATE_LIMIT_CONFIG.minDelay);
}
@@ -149,37 +135,23 @@ async function estimateMessageCount(): Promise<number> {
}
}
function calculateAdaptiveBatchSize(
progress: MessagesProgress,
responseTime: number,
): number {
function calculateAdaptiveBatchSize(progress: MessagesProgress, responseTime: number): number {
if (!RATE_LIMIT_CONFIG.adaptiveBatchSize) {
return progress.currentBatchSize;
}
const {
currentBatchSize,
failedRequests,
circuitBreakerOpen,
consecutiveFailures,
} = progress;
const { currentBatchSize, failedRequests, circuitBreakerOpen, consecutiveFailures } = progress;
if (circuitBreakerOpen) {
return RATE_LIMIT_CONFIG.minBatchSize;
}
if (consecutiveFailures > 1 || failedRequests > 2 || responseTime > 2500) {
return Math.max(
Math.floor(currentBatchSize * 0.6),
RATE_LIMIT_CONFIG.minBatchSize,
);
return Math.max(Math.floor(currentBatchSize * 0.6), RATE_LIMIT_CONFIG.minBatchSize);
}
if (failedRequests === 0 && responseTime < 800 && consecutiveFailures === 0) {
return Math.min(
Math.floor(currentBatchSize * 1.4),
RATE_LIMIT_CONFIG.maxBatchSize,
);
return Math.min(Math.floor(currentBatchSize * 1.4), RATE_LIMIT_CONFIG.maxBatchSize);
}
return currentBatchSize;
@@ -202,8 +174,7 @@ function checkCircuitBreaker(progress: MessagesProgress): boolean {
if (
progress.circuitBreakerOpen &&
now - progress.circuitBreakerOpenTime >
RATE_LIMIT_CONFIG.circuitBreakerResetTime
now - progress.circuitBreakerOpenTime > RATE_LIMIT_CONFIG.circuitBreakerResetTime
) {
progress.circuitBreakerOpen = false;
progress.consecutiveFailures = 0;
@@ -257,20 +228,11 @@ async function processMessagesInParallel(
return { processedItems, consecutiveExisting, updatedProgress, shouldStop };
}
for (
let i = 0;
i < messagesToProcess.length;
i += RATE_LIMIT_CONFIG.parallelRequests
) {
const batch = messagesToProcess.slice(
i,
i + RATE_LIMIT_CONFIG.parallelRequests,
);
for (let i = 0; i < messagesToProcess.length; i += RATE_LIMIT_CONFIG.parallelRequests) {
const batch = messagesToProcess.slice(i, i + RATE_LIMIT_CONFIG.parallelRequests);
if (i > 0) {
await delay(
Math.max(updatedProgress.currentDelay, RATE_LIMIT_CONFIG.parallelDelay),
);
await delay(Math.max(updatedProgress.currentDelay, RATE_LIMIT_CONFIG.parallelDelay));
}
const batchStartTime = Date.now();
@@ -336,20 +298,14 @@ async function processMessagesInParallel(
if (batchSuccesses > 0) {
updatedProgress.lastSuccessTime = Date.now();
updatedProgress.failedRequests = Math.max(
0,
updatedProgress.failedRequests - batchSuccesses,
);
updatedProgress.failedRequests = Math.max(0, updatedProgress.failedRequests - batchSuccesses);
}
if (batchFailures > 0) {
updatedProgress.failedRequests += batchFailures;
}
updatedProgress.currentDelay = calculateAdaptiveDelay(
updatedProgress,
batchResponseTime,
);
updatedProgress.currentDelay = calculateAdaptiveDelay(updatedProgress, batchResponseTime);
verboseLog(
`[Messages job] Processed parallel batch: ${batchSuccesses} successes, ${batchFailures} failures, ${batchResponseTime}ms total time`,
@@ -409,10 +365,7 @@ export const messagesJob: Job = {
);
}
} catch (error) {
console.warn(
"[Messages job] Failed to start streaming session:",
error,
);
console.warn("[Messages job] Failed to start streaming session:", error);
}
}
@@ -427,14 +380,8 @@ export const messagesJob: Job = {
const retryBatch = progress.retryQueue.slice(0, 10);
const retryBatches = [];
for (
let i = 0;
i < retryBatch.length;
i += RATE_LIMIT_CONFIG.parallelRequests
) {
retryBatches.push(
retryBatch.slice(i, i + RATE_LIMIT_CONFIG.parallelRequests),
);
for (let i = 0; i < retryBatch.length; i += RATE_LIMIT_CONFIG.parallelRequests) {
retryBatches.push(retryBatch.slice(i, i + RATE_LIMIT_CONFIG.parallelRequests));
}
for (const batch of retryBatches) {
@@ -458,10 +405,7 @@ export const messagesJob: Job = {
return { success: false, messageId, responseTime };
}
} catch (error) {
console.error(
`[Messages job] Retry failed for message ${messageId}:`,
error,
);
console.error(`[Messages job] Retry failed for message ${messageId}:`, error);
return { success: false, messageId, error };
}
});
@@ -478,9 +422,7 @@ export const messagesJob: Job = {
processedIdsSet.add(result.messageId.toString());
retrySuccesses++;
}
progress.retryQueue = progress.retryQueue.filter(
(mid) => mid !== result.messageId,
);
progress.retryQueue = progress.retryQueue.filter((mid) => mid !== result.messageId);
} else {
retryFailures++;
}
@@ -488,20 +430,14 @@ export const messagesJob: Job = {
if (retrySuccesses > 0) {
progress.lastSuccessTime = Date.now();
progress.failedRequests = Math.max(
0,
progress.failedRequests - retrySuccesses,
);
progress.failedRequests = Math.max(0, progress.failedRequests - retrySuccesses);
}
if (retryFailures > 0) {
progress.failedRequests += retryFailures;
}
progress.currentDelay = calculateAdaptiveDelay(
progress,
batchResponseTime,
);
progress.currentDelay = calculateAdaptiveDelay(progress, batchResponseTime);
verboseLog(
`[Messages job] Processed retry batch: ${retrySuccesses} successes, ${retryFailures} failures`,
@@ -511,9 +447,7 @@ export const messagesJob: Job = {
while (!progress.done) {
if (checkCircuitBreaker(progress)) {
console.warn(
"[Messages job] Circuit breaker is open, skipping processing",
);
console.warn("[Messages job] Circuit breaker is open, skipping processing");
await delay(RATE_LIMIT_CONFIG.maxDelay);
continue;
}
@@ -529,10 +463,7 @@ export const messagesJob: Job = {
progress.consecutiveFailures = 0;
progress.currentDelay = calculateAdaptiveDelay(progress, responseTime);
progress.currentBatchSize = calculateAdaptiveBatchSize(
progress,
responseTime,
);
progress.currentBatchSize = calculateAdaptiveBatchSize(progress, responseTime);
} catch (e) {
console.error("[Messages job] list fetch failed:", e);
progress.failedRequests++;
@@ -591,25 +522,15 @@ export const messagesJob: Job = {
`[Messages job] Streamed ${itemsToStream.length} items to vector worker (total: ${itemsStreamedToVector})`,
);
} catch (error) {
console.warn(
"[Messages job] Failed to stream items to vector worker:",
error,
);
console.warn("[Messages job] Failed to stream items to vector worker:", error);
}
}
if (processedItems.length > 0) {
try {
publishDynamicItemsUpdate(
await loadAllStoredItems(),
"messages",
processedItems.length,
);
publishDynamicItemsUpdate(await loadAllStoredItems(), "messages", processedItems.length);
} catch (error) {
console.warn(
"[Messages job] Failed to dispatch incremental search update:",
error,
);
console.warn("[Messages job] Failed to dispatch incremental search update:", error);
}
}
Loaded 100 of 305 files, more files were not shown because too many files have changed in this diff. Show more