diff --git a/.github/actions/run-lint/action.yml b/.github/actions/run-lint/action.yml index 5987b41e..47a10919 100644 --- a/.github/actions/run-lint/action.yml +++ b/.github/actions/run-lint/action.yml @@ -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 diff --git a/.github/actions/setup-node-deps/action.yml b/.github/actions/setup-node-deps/action.yml index 354db1e1..43f01e55 100644 --- a/.github/actions/setup-node-deps/action.yml +++ b/.github/actions/setup-node-deps/action.yml @@ -8,6 +8,7 @@ runs: uses: actions/setup-node@v7 with: node-version: 26.x + cache: npm - name: Install dependencies shell: bash diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index 43443acb..cfc37626 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -22,7 +22,6 @@ jobs: run: shell: bash steps: - - uses: actions/checkout@v7 - name: Set build date diff --git a/.github/workflows/pr-ci.yml b/.github/workflows/pr-ci.yml index 3088e073..1b75a9fe 100644 --- a/.github/workflows/pr-ci.yml +++ b/.github/workflows/pr-ci.yml @@ -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: diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml deleted file mode 100644 index aa5f9a9d..00000000 --- a/.github/workflows/release.yml +++ /dev/null @@ -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 }}" diff --git a/.oxfmtrc.json b/.oxfmtrc.json new file mode 100644 index 00000000..69db2843 --- /dev/null +++ b/.oxfmtrc.json @@ -0,0 +1,10 @@ +{ + "$schema": "./node_modules/oxfmt/configuration_schema.json", + "ignorePatterns": [ + "betterseqtaplus-safari/", + "coverage/", + "dist/", + "package-lock.json", + "src/public/" + ] +} diff --git a/.oxlintrc.json b/.oxlintrc.json new file mode 100644 index 00000000..4ae67196 --- /dev/null +++ b/.oxlintrc.json @@ -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/**"] +} diff --git a/.prettierignore b/.prettierignore deleted file mode 100644 index 384ac341..00000000 --- a/.prettierignore +++ /dev/null @@ -1,5 +0,0 @@ -betterseqtaplus-safari/ -coverage/ -dist/ -package-lock.json -src/public/ diff --git a/.prettierrc b/.prettierrc deleted file mode 100644 index a5cd8192..00000000 --- a/.prettierrc +++ /dev/null @@ -1,5 +0,0 @@ -{ - "tabWidth": 2, - "useTabs": false, - "semi": true -} diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a476c818..5951a5bb 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -23,15 +23,15 @@ 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 | -| `src/interface/` | Settings popup and theme store (Svelte) | -| `src/plugins/` | Plugin system and built-in plugins | -| `src/css/` | Injected styles and the shared Tailwind setup | -| `lib/`, `scripts/` | Vite plugins and build scripts | +| Path | What's in it | +| -------------------------------------- | --------------------------------------------- | +| `src/SEQTA.ts` | Content script entry point | +| `src/background.ts`, `src/background/` | Service worker | +| `src/seqta/` | Everything injected into SEQTA pages | +| `src/interface/` | Settings popup and theme store (Svelte) | +| `src/plugins/` | Plugin system and built-in plugins | +| `src/css/` | Injected styles and the shared Tailwind setup | +| `lib/`, `scripts/` | Vite plugins and build scripts | The [architecture guide](https://docs.betterseqta.org/architecture/) goes into more detail. @@ -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 diff --git a/docs/CLOUD_SETTINGS_SYNC_OPTIONS.md b/docs/CLOUD_SETTINGS_SYNC_OPTIONS.md index 69b9393a..f83d7790 100644 --- a/docs/CLOUD_SETTINGS_SYNC_OPTIONS.md +++ b/docs/CLOUD_SETTINGS_SYNC_OPTIONS.md @@ -68,12 +68,12 @@ 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 | -| `requestCloudSettingsDebouncedUpload()` | Same debounced path (e.g. after theme install) | +| 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 | +| `requestCloudSettingsDebouncedUpload()` | Same debounced path (e.g. after theme install) | Upload is skipped when: @@ -83,11 +83,11 @@ 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 | +| 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 | Download is skipped when server `schemaVersion` > client `CLOUD_SETTINGS_SYNC_SCHEMA_VERSION` (currently `1`). @@ -112,13 +112,13 @@ 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) | -| `initializeSettingsState()` | SEQTA content script + extension settings page (first init) | -| Before each cloud upload | `putSettingsOnce()` in `cloudSettingsAutoSync.ts` | +| When it runs | Context | +| ----------------------------- | ----------------------------------------------------------- | +| `browser.runtime.onInstalled` | Service worker (install + update) | +| `browser.runtime.onStartup` | Service worker | +| Service worker load | `background.ts` (once at startup) | +| `initializeSettingsState()` | SEQTA content script + extension settings page (first init) | +| Before each cloud upload | `putSettingsOnce()` in `cloudSettingsAutoSync.ts` | Rules: @@ -155,11 +155,11 @@ 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. | +| 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. | ### `GET /api/bsplus/settings/sync` response @@ -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" } ``` @@ -191,12 +191,12 @@ 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 | -| Analytics cache | `bsplus.analytics.v2.https://school.seqta.com.au.12345` | structured cache (excluded) | +| 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 | +| Analytics cache | `bsplus.analytics.v2.https://school.seqta.com.au.12345` | structured cache (excluded) | Plugin settings use `plugin.{pluginId}.settings` where `pluginId` matches the plugin registration id (e.g. `messageFolders`, not `message-folders`). @@ -204,11 +204,11 @@ 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 | +| 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 | Component/button plugin settings (`type: "component"` | `"button"`) are **not** written by the settings proxy loop; only scalar settings defined in `plugin.settings` are persisted automatically. The settings UI may still write `enabled` and other keys via `browser.storage.local.set` directly. @@ -220,20 +220,20 @@ 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 | -| `bsplus_user` | `CloudUser` object (see below) | Keep device value | -| `cloudAccessToken` | `string` (legacy) | Keep device value | -| `cloudUsername` | `string` (legacy) | Keep device value | -| `plugin.assessments-average.storage.assessments` | object | Keep device value | -| `plugin.assessments-average.storage.weightings` | object | Keep device value | -| `bsplus_cloud_settings_known_remote_updated_at` | ISO `string` | Keep device value | -| `bsplus_cloud_settings_last_uploaded_snapshot` | `object` (normalized syncable map) | Keep device value | -| `bsplus_lastCloudPoll` | `number` (ms) | Keep device value | -| `bsplus_pending_theme_ensure_after_cloud` | `string` (theme id) | Keep device value | +| 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 | +| `bsplus_user` | `CloudUser` object (see below) | Keep device value | +| `cloudAccessToken` | `string` (legacy) | Keep device value | +| `cloudUsername` | `string` (legacy) | Keep device value | +| `plugin.assessments-average.storage.assessments` | object | Keep device value | +| `plugin.assessments-average.storage.weightings` | object | Keep device value | +| `bsplus_cloud_settings_known_remote_updated_at` | ISO `string` | Keep device value | +| `bsplus_cloud_settings_last_uploaded_snapshot` | `object` (normalized syncable map) | Keep device value | +| `bsplus_lastCloudPoll` | `number` (ms) | Keep device value | +| `bsplus_pending_theme_ensure_after_cloud` | `string` (theme id) | Keep device value | #### `bsplus_user` shape (local only, never uploaded) @@ -244,7 +244,7 @@ Implemented in `shouldOmitKeyFromCloudPayload(key)`: "username": "optional", "displayName": "optional", "pfpUrl": "https://…", - "pfpHash": "abc123" , + "pfpHash": "abc123", "admin_level": 0 } ``` @@ -253,10 +253,10 @@ 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 | +| Prefix | Matches | +| ------------------------------- | ------------------------------------------- | +| `plugin.global-search.storage.` | Any Global Search device cache key | +| `bsplus.analytics.` | Grade Analytics caches and chart mode prefs | Prefix check: `key.startsWith(prefix)`. @@ -266,13 +266,13 @@ 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` | -| `lettergrade` | `boolean` | `plugin.assessments-average.settings` | `lettergrade` | `!!lettergrade` | -| `notificationCollector` | `boolean` only | `plugin.notificationCollector.settings` | `enabled` | copy boolean | +| 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` | +| `lettergrade` | `boolean` | `plugin.assessments-average.settings` | `lettergrade` | `!!lettergrade` | +| `notificationCollector` | `boolean` only | `plugin.notificationCollector.settings` | `enabled` | copy boolean | **Example:** legacy `bksliderinput: "50"` → `speed: 1.05` because `0.1 + 0.5 * 1.9 = 1.05`. @@ -288,98 +288,98 @@ Top-level `chrome.storage.local` keys from `SettingsState` (`src/types/storage.t #### `onoff` -| | | -|-|-| -| **Type** | `boolean` | -| **Default** | `true` | -| **UI** | Settings → “BetterSEQTA+” master switch | -| **Example** | `true` | +| | | +| ----------- | --------------------------------------- | +| **Type** | `boolean` | +| **Default** | `true` | +| **UI** | Settings → “BetterSEQTA+” master switch | +| **Example** | `true` | #### `DarkMode` -| | | -|-|-| -| **Type** | `boolean` | -| **Default** | `true` | -| **UI** | SEQTA UI / theme system | -| **Example** | `true` | +| | | +| ----------- | ----------------------- | +| **Type** | `boolean` | +| **Default** | `true` | +| **UI** | SEQTA UI / theme system | +| **Example** | `true` | #### `selectedTheme` -| | | -|-|-| -| **Type** | `string` | -| **Default** | `""` | -| **UI** | Theme selector / store install | -| **Format** | BetterSEQTA store theme UUID, **flavour (slave) variant** id, or empty string for no store theme | -| **Wire** | Duplicated as top-level `themeId` on upload (trimmed) | -| **Example** | `"f47ac10b-58cc-4372-a567-0e02b2c3d479"` or `""` | +| | | +| ----------- | ------------------------------------------------------------------------------------------------ | +| **Type** | `string` | +| **Default** | `""` | +| **UI** | Theme selector / store install | +| **Format** | BetterSEQTA store theme UUID, **flavour (slave) variant** id, or empty string for no store theme | +| **Wire** | Duplicated as top-level `themeId` on upload (trimmed) | +| **Example** | `"f47ac10b-58cc-4372-a567-0e02b2c3d479"` or `""` | Theme **asset blobs** (CSS, images) live in **localforage/IndexedDB**, not in this key. After restore, only the id is synced; assets are re-fetched if missing. #### `selectedColor` -| | | -|-|-| -| **Type** | `string` | -| **Default** | `"linear-gradient(40deg, rgba(201,61,0,1) 0%, RGBA(170, 5, 58, 1) 100%)"` | -| **UI** | Colour picker | -| **Format** | Any valid CSS `background` value: hex (`#c93d00`), `rgb()`, `rgba()`, `linear-gradient(...)`, etc. | -| **Example** | `"#c93d00"` or `"linear-gradient(40deg, rgba(201,61,0,1) 0%, RGBA(170, 5, 58, 1) 100%)"` | +| | | +| ----------- | -------------------------------------------------------------------------------------------------- | +| **Type** | `string` | +| **Default** | `"linear-gradient(40deg, rgba(201,61,0,1) 0%, RGBA(170, 5, 58, 1) 100%)"` | +| **UI** | Colour picker | +| **Format** | Any valid CSS `background` value: hex (`#c93d00`), `rgb()`, `rgba()`, `linear-gradient(...)`, etc. | +| **Example** | `"#c93d00"` or `"linear-gradient(40deg, rgba(201,61,0,1) 0%, RGBA(170, 5, 58, 1) 100%)"` | #### `originalSelectedColor` -| | | -|-|-| -| **Type** | `string` | -| **Default** | `""` | +| | | +| ----------- | --------------------------------------------------------- | +| **Type** | `string` | +| **Default** | `""` | | **Purpose** | Colour before theme preview; restored when clearing theme | -| **Example** | `"#c93d00"` | +| **Example** | `"#c93d00"` | #### `originalDarkMode` -| | | -|-|-| -| **Type** | `boolean` | -| **Default** | undefined until theme preview | +| | | +| ----------- | ------------------------------ | +| **Type** | `boolean` | +| **Default** | undefined until theme preview | | **Purpose** | Dark mode before theme preview | -| **Example** | `true` | +| **Example** | `true` | #### `transparencyEffects` -| | | -|-|-| -| **Type** | `boolean` | -| **Default** | `false` | -| **UI** | Settings → Transparency Effects | -| **Example** | `false` | +| | | +| ----------- | ------------------------------- | +| **Type** | `boolean` | +| **Default** | `false` | +| **UI** | Settings → Transparency Effects | +| **Example** | `false` | #### `animations` -| | | -|-|-| -| **Type** | `boolean` | +| | | +| ----------- | ----------------------------------------------------------------------------------------------- | +| **Type** | `boolean` | | **Default** | `true` on normal devices; `false` if low-end (`hardwareConcurrency < 4` or `deviceMemory <= 2`) | -| **UI** | Settings → Animations | -| **Example** | `true` | +| **UI** | Settings → Animations | +| **Example** | `true` | #### `iconOnlySidebar` -| | | -|-|-| -| **Type** | `boolean` | -| **Default** | `false` | -| **UI** | Settings → Icon Only Sidebar | -| **Example** | `false` | +| | | +| ----------- | ---------------------------- | +| **Type** | `boolean` | +| **Default** | `false` | +| **UI** | Settings → Icon Only Sidebar | +| **Example** | `false` | #### `selectedFont` -| | | -|-|-| -| **Type** | `string` | -| **Default** | undefined → runtime treats as `"rubik"` | -| **UI** | Settings → Interface Font | -| **Format** | Font preset id from `src/seqta/ui/fonts/presets.ts` | +| | | +| ----------- | --------------------------------------------------- | +| **Type** | `string` | +| **Default** | undefined → runtime treats as `"rubik"` | +| **UI** | Settings → Interface Font | +| **Format** | Font preset id from `src/seqta/ui/fonts/presets.ts` | Allowed ids: @@ -389,67 +389,67 @@ Allowed ids: #### `adaptiveThemeColour` -| | | -|-|-| -| **Type** | `boolean` | -| **Default** | `false` | -| **Example** | `false` | +| | | +| ----------- | --------- | +| **Type** | `boolean` | +| **Default** | `false` | +| **Example** | `false` | #### `adaptiveThemeGradient` -| | | -|-|-| -| **Type** | `boolean` | -| **Default** | `false` | -| **Example** | `false` | +| | | +| ----------- | --------- | +| **Type** | `boolean` | +| **Default** | `false` | +| **Example** | `false` | #### `adaptiveThemeColourTransition` -| | | -|-|-| -| **Type** | `boolean` | -| **Default** | `true` | -| **Example** | `true` | +| | | +| ----------- | --------- | +| **Type** | `boolean` | +| **Default** | `true` | +| **Example** | `true` | ### Navigation & layout #### `defaultPage` -| | | -|-|-| -| **Type** | `string` | -| **Default** | `"home"` | -| **UI** | Settings → Default Page | +| | | +| ----------- | --------------------------------------------------------------------------------------------- | +| **Type** | `string` | +| **Default** | `"home"` | +| **UI** | Settings → Default Page | | **Allowed** | `"home"`, `"dashboard"`, `"timetable"`, `"welcome"`, `"messages"`, `"documents"`, `"reports"` | -| **Example** | `"home"` | +| **Example** | `"home"` | #### `timeFormat` -| | | -|-|-| -| **Type** | `string` | -| **Default** | undefined (24-hour behaviour) | -| **UI** | Settings → “12 Hour Time” switch | -| **Values** | `"12"` when enabled; `"24"` when disabled | -| **Example** | `"12"` | +| | | +| ----------- | ----------------------------------------- | +| **Type** | `string` | +| **Default** | undefined (24-hour behaviour) | +| **UI** | Settings → “12 Hour Time” switch | +| **Values** | `"12"` when enabled; `"24"` when disabled | +| **Example** | `"12"` | #### `lessonalert` -| | | -|-|-| -| **Type** | `boolean` | -| **Default** | `true` | +| | | +| ----------- | ------------------------- | +| **Type** | `boolean` | +| **Default** | `true` | | **Purpose** | Lesson alert on home page | -| **Example** | `true` | +| **Example** | `true` | #### `menuitems` -| | | -|-|-| -| **Type** | `object` | +| | | +| ----------- | ------------------------------------ | +| **Type** | `object` | | **Default** | All sidebar items `{ toggle: true }` | -| **UI** | Menu editor overlay | -| **Shape** | `{ [menuKey]: { toggle: boolean } }` | +| **UI** | Menu editor overlay | +| **Shape** | `{ [menuKey]: { toggle: boolean } }` | Keys (from `SettingsState`): @@ -467,34 +467,34 @@ Keys (from `SettingsState`): #### `menuorder` -| | | -|-|-| -| **Type** | `array` | -| **Default** | `[]` | -| **UI** | Menu editor (drag order) | +| | | +| ------------- | --------------------------------------------------------------------------------------------------------------- | +| **Type** | `array` | +| **Default** | `[]` | +| **UI** | Menu editor (drag order) | | **Item type** | `string` — SEQTA menu `data-key` values (e.g. `"home"`, `"timetable"`, `"analytics"` for plugin-injected items) | -| **Example** | `["home", "timetable", "assessments", "messages"]` | +| **Example** | `["home", "timetable", "assessments", "messages"]` | #### `defaultmenuorder` -| | | -|-|-| -| **Type** | `array` | -| **Default** | `[]` (populated from DOM on first menu edit) | +| | | +| ------------- | ------------------------------------------------------ | +| **Type** | `array` | +| **Default** | `[]` (populated from DOM on first menu edit) | | **Item type** | Same as `menuorder` — snapshot of school default order | -| **Example** | `["home", "dashboard", "timetable"]` | +| **Example** | `["home", "dashboard", "timetable"]` | ### Shortcuts #### `shortcuts` -| | | -|-|-| -| **Type** | `array` | -| **Default** | Outlook, Office, Google — each `enabled: true` | -| **UI** | Settings → Shortcuts | -| **Item shape** | `{ "name": string, "enabled": boolean }` | -| **Notes** | `name` matches keys in `src/seqta/content/links.json` (e.g. `"Outlook"`, `"YouTube"`) | +| | | +| -------------- | ------------------------------------------------------------------------------------- | +| **Type** | `array` | +| **Default** | Outlook, Office, Google — each `enabled: true` | +| **UI** | Settings → Shortcuts | +| **Item shape** | `{ "name": string, "enabled": boolean }` | +| **Notes** | `name` matches keys in `src/seqta/content/links.json` (e.g. `"Outlook"`, `"YouTube"`) | **Example:** @@ -508,14 +508,14 @@ Keys (from `SettingsState`): #### `customshortcuts` -| | | -|-|-| -| **Type** | `array` | -| **Default** | `[]` | -| **UI** | Settings → Shortcuts → add custom | -| **Item shape** | `{ "name": string, "url": string, "icon": string }` | -| **`url`** | Full URL with protocol, e.g. `"https://example.com"` | -| **`icon`** | Inline **SVG markup string** OR single fallback character (first letter of title) | +| | | +| -------------- | --------------------------------------------------------------------------------- | +| **Type** | `array` | +| **Default** | `[]` | +| **UI** | Settings → Shortcuts → add custom | +| **Item shape** | `{ "name": string, "url": string, "icon": string }` | +| **`url`** | Full URL with protocol, e.g. `"https://example.com"` | +| **`icon`** | Inline **SVG markup string** OR single fallback character (first letter of title) | **Example:** @@ -533,155 +533,155 @@ Keys (from `SettingsState`): #### `subjectfilters` -| | | -|-|-| -| **Type** | `object` | -| **Default** | `{}` | -| **UI** | Home / assessments subject filters | -| **Shape** | `{ [subjectCode: string]: boolean }` — `false` hides subject; missing key = visible | -| **Example** | `{ "10MAT": false, "10ENG": true }` | +| | | +| ----------- | ----------------------------------------------------------------------------------- | +| **Type** | `object` | +| **Default** | `{}` | +| **UI** | Home / assessments subject filters | +| **Shape** | `{ [subjectCode: string]: boolean }` — `false` hides subject; missing key = visible | +| **Example** | `{ "10MAT": false, "10ENG": true }` | #### `newsSource` -| | | -|-|-| -| **Type** | `string` | -| **Default** | `"australia"` | -| **UI** | Settings → News Feed Source | +| | | +| ----------- | -------------------------------------------------------------------------------------------------------- | +| **Type** | `string` | +| **Default** | `"australia"` | +| **UI** | Settings → News Feed Source | | **Allowed** | `australia`, `usa`, `uk`, `taiwan`, `hong_kong`, `panama`, `canada`, `singapore`, `japan`, `netherlands` | -| **Example** | `"australia"` | +| **Example** | `"australia"` | ### Cloud sync preference #### `autoCloudSettingsSync` -| | | -|-|-| -| **Type** | `boolean` | -| **Default** | `true` | -| **UI** | Settings → Cloud Settings Sync | +| | | +| ------------- | ---------------------------------------------------- | +| **Type** | `boolean` | +| **Default** | `true` | +| **UI** | Settings → Cloud Settings Sync | | **Semantics** | Sync runs when **not** strictly `false` (default-on) | -| **Example** | `true` | +| **Example** | `true` | ### Theme of the Month #### `themeOfTheMonthDisabled` -| | | -|-|-| -| **Type** | `boolean` | -| **Default** | `false` | -| **UI** | Global Search plugin section → Theme of the Month switch (inverted in UI) | -| **Example** | `false` | +| | | +| ----------- | ------------------------------------------------------------------------- | +| **Type** | `boolean` | +| **Default** | `false` | +| **UI** | Global Search plugin section → Theme of the Month switch (inverted in UI) | +| **Example** | `false` | #### `themeOfTheMonthDismissedMonth` -| | | -|-|-| -| **Type** | `string` | -| **Format** | `"YYYY-MM"` calendar month | -| **Example** | `"2026-06"` | +| | | +| ----------- | -------------------------- | +| **Type** | `string` | +| **Format** | `"YYYY-MM"` calendar month | +| **Example** | `"2026-06"` | #### `themeOfTheMonthLastSeenId` -| | | -|-|-| -| **Type** | `string` | +| | | +| ---------- | ------------------------------------------- | +| **Type** | `string` | | **Status** | Deprecated; may still exist in old profiles | -| **Synced** | Yes if present | +| **Synced** | Yes if present | ### One-time announcements & privacy #### `privacyStatementShown` -| | | -|-|-| -| **Type** | `boolean` | -| **Example** | `true` | +| | | +| ----------- | --------- | +| **Type** | `boolean` | +| **Example** | `true` | #### `privacyStatementLastUpdated` -| | | -|-|-| -| **Type** | `string` | +| | | +| ---------- | ----------------------------- | +| **Type** | `string` | | **Format** | ISO date, e.g. `"2025-12-20"` | #### `engageParentsAnnouncementShown` -| | | -|-|-| -| **Type** | `boolean` | +| | | +| ----------- | ------------------------------------------- | +| **Type** | `boolean` | | **Purpose** | SEQTA Engage parents announcement dismissed | #### `bsCloudAutoSyncAnnouncementShown` -| | | -|-|-| -| **Type** | `boolean` | +| | | +| ----------- | -------------------------------------- | +| **Type** | `boolean` | | **Purpose** | Cloud auto-sync announcement dismissed | ### Update & developer flags #### `justupdated` -| | | -|-|-| -| **Type** | `boolean` | +| | | +| ----------- | ------------------------------------------------------------- | +| **Type** | `boolean` | | **Purpose** | Set `true` after extension update; drives startup popup queue | -| **Example** | `true` | +| **Example** | `true` | #### `devMode` -| | | -|-|-| -| **Type** | `boolean` | -| **Default** | undefined / false | -| **UI** | Hidden unlock in settings | -| **Example** | `true` | +| | | +| ----------- | ------------------------- | +| **Type** | `boolean` | +| **Default** | undefined / false | +| **UI** | Hidden unlock in settings | +| **Example** | `true` | #### `hideSensitiveContent` -| | | -|-|-| -| **Type** | `boolean` | -| **UI** | Dev mode → Sensitive Hider | -| **Example** | `false` | +| | | +| ----------- | -------------------------- | +| **Type** | `boolean` | +| **UI** | Dev mode → Sensitive Hider | +| **Example** | `false` | #### `mockNotices` -| | | -|-|-| -| **Type** | `boolean` | -| **UI** | Dev mode → Mock Notices | -| **Example** | `false` | +| | | +| ----------- | ----------------------- | +| **Type** | `boolean` | +| **UI** | Dev mode → Mock Notices | +| **Example** | `false` | #### `devGhReleaseVersionOverride` -| | | -|-|-| -| **Type** | `string` | -| **UI** | Dev mode → version override field | -| **Format** | Semver string, e.g. `"3.7.0"` | -| **Example** | `"99.0.0"` | +| | | +| ----------- | --------------------------------- | +| **Type** | `string` | +| **UI** | Dev mode → version override field | +| **Format** | Semver string, e.g. `"3.7.0"` | +| **Example** | `"99.0.0"` | #### `lastSeenNightlyPublishedAt` -| | | -|-|-| -| **Type** | `string` | -| **Format** | ISO 8601 timestamp from GitHub release `published_at` | -| **Example** | `"2026-06-01T04:30:00Z"` | +| | | +| ----------- | ----------------------------------------------------- | +| **Type** | `string` | +| **Format** | ISO 8601 timestamp from GitHub release `published_at` | +| **Example** | `"2026-06-01T04:30:00Z"` | ### Profile picture helper #### `profile_picture_revision` -| | | -|-|-| -| **Type** | `number` | +| | | +| ----------- | ------------------------------------------------------------------------- | +| **Type** | `number` | | **Purpose** | Incremented when cloud/local profile picture changes; triggers UI refresh | -| **Not** | The image itself (stored in localforage `profile-picture-store`) | -| **Example** | `3` | +| **Not** | The image itself (stored in localforage `profile-picture-store`) | +| **Example** | `3` | --- @@ -693,10 +693,10 @@ 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 | +| Field | Type | Default | Range / notes | +| --------- | --------- | ------- | ---------------------------- | +| `enabled` | `boolean` | `true` | From `disableToggle` UI | +| `speed` | `number` | `1` | **0.1–2.0**, step 0.05 in UI | ```json { "enabled": true, "speed": 1.05 } @@ -704,9 +704,9 @@ Settings of type `component` or `button` are **not** auto-persisted by the plugi ### `plugin.assessments-average.settings` -| Field | Type | Default | -|-------|------|---------| -| `enabled` | `boolean` | `false` | +| Field | Type | Default | +| ------------- | --------- | ------- | +| `enabled` | `boolean` | `false` | | `lettergrade` | `boolean` | `false` | ```json @@ -715,9 +715,9 @@ Settings of type `component` or `button` are **not** auto-persisted by the plugi ### `plugin.notificationCollector.settings` -| Field | Type | Default | -|-------|------|---------| -| `enabled` | `boolean` | `true` | +| Field | Type | Default | +| --------- | --------- | ------- | +| `enabled` | `boolean` | `true` | ```json { "enabled": true } @@ -725,9 +725,9 @@ Settings of type `component` or `button` are **not** auto-persisted by the plugi ### `plugin.timetable.settings` -| Field | Type | Default | -|-------|------|---------| -| `enabled` | `boolean` | `true` | +| Field | Type | Default | +| --------- | --------- | ------- | +| `enabled` | `boolean` | `true` | ```json { "enabled": true } @@ -735,9 +735,9 @@ Settings of type `component` or `button` are **not** auto-persisted by the plugi ### `plugin.timetableEdit.settings` -| Field | Type | Default | -|-------|------|---------| -| `enabled` | `boolean` | `true` | +| Field | Type | Default | +| --------- | --------- | ------- | +| `enabled` | `boolean` | `true` | ```json { "enabled": true } @@ -745,14 +745,14 @@ 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` | | -| `transparencyEffects` | `boolean` | `true` | Search bar blur | -| `runIndexingOnLoad` | `boolean` | `true` | | -| `passiveIndexing` | `boolean` | `true` | Index visited pages | +| Field | Type | Default | Notes | +| --------------------- | --------- | ----------------------- | ----------------------- | +| `enabled` | `boolean` | `false` | Plugin default off | +| `searchHotkey` | `string` | `"ctrl+k"` or `"cmd+k"` | See hotkey format below | +| `showRecentFirst` | `boolean` | `true` | | +| `transparencyEffects` | `boolean` | `true` | Search bar blur | +| `runIndexingOnLoad` | `boolean` | `true` | | +| `passiveIndexing` | `boolean` | `true` | Index visited pages | ```json { @@ -775,9 +775,9 @@ Settings of type `component` or `button` are **not** auto-persisted by the plugi ### `plugin.profile-picture.settings` -| Field | Type | Default | -|-------|------|---------| -| `enabled` | `boolean` | `false` | +| Field | Type | Default | +| ------------- | --------- | ------- | +| `enabled` | `boolean` | `false` | | `useCloudPfp` | `boolean` | `false` | ```json @@ -788,11 +788,11 @@ 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` | +| Field | Type | Default | +| --------------------------- | --------- | ------- | +| `enabled` | `boolean` | `true` | +| `showTagsInAllMessages` | `boolean` | `true` | +| `hideFolderedMessagesInAll` | `boolean` | `true` | ```json { @@ -804,9 +804,9 @@ When `useCloudPfp` is true, avatar URL comes from `bsplus_user.pfpUrl` (local au ### `plugin.enhanced-navigation.settings` -| Field | Type | Default | -|-------|------|---------| -| `enabled` | `boolean` | `true` | +| Field | Type | Default | +| ------------------- | --------- | ------- | +| `enabled` | `boolean` | `true` | | `autoScrollOnClick` | `boolean` | `false` | ```json @@ -815,11 +815,11 @@ 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` | | +| Field | Type | Default | Range | +| --------------- | --------- | ------- | ----- | +| `enabled` | `boolean` | `false` | | +| `volume` | `number` | `0.5` | 0–1 | +| `pauseOnHidden` | `boolean` | `true` | | ```json { "enabled": true, "volume": 0.75, "pauseOnHidden": true } @@ -829,9 +829,9 @@ Audio blob: localforage `background-music-store` / `music` / key `audio-blob` ### `plugin.grade-analytics.settings` -| Field | Type | Default | Range | -|-------|------|---------|-------| -| `cacheTtlHours` | `number` | `24` | 1–168 | +| Field | Type | Default | Range | +| --------------- | -------- | ------- | ----- | +| `cacheTtlHours` | `number` | `24` | 1–168 | ```json { "cacheTtlHours": 48 } @@ -865,11 +865,11 @@ 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 | +| Field | Type | Notes | +| ------- | -------- | ------------------------------------------ | +| `id` | `string` | `Date.now().toString(36) + random` | +| `name` | `string` | Display name | +| `color` | `string` | Hex colour from preset palette | | `emoji` | `string` | Inline SVG icon markup (not unicode emoji) | #### `plugin.messageFolders.storage.messageAssignments` @@ -946,20 +946,20 @@ 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) | -| `refreshing` | `boolean` | optional; background refetch in progress | +| Field | Type | Notes | +| --------------- | --------- | --------------------------------------------- | +| `weight` | `string` | e.g. `"25"`, `"processing"`, `"N/A"` | +| `fingerprint` | `string` | JSON-stringified assessment state fingerprint | +| `pluginVersion` | `number` | `WEIGHTING_SCHEMA_VERSION` (= 1) | +| `refreshing` | `boolean` | optional; background refetch in progress | ### 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"` | +| 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"` | All **synced** (not under an excluded prefix). @@ -1018,17 +1018,17 @@ 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 | -| Installed themes | localforage (default instance) | `CustomTheme` objects keyed by theme id; index `customThemes` | -| Profile picture upload | localforage `profile-picture-store` / `profilePicture` | Image blob | -| Cloud PFP cache | localforage `cloud-pfp-store` / `cloudPfp` | Cached avatar blobs | -| Background music | localforage `background-music-store` / `music` / `audio-blob` | Audio blob | -| Dev API override | `sessionStorage` `bsplus_dev_api_base` | Staging server URL | -| Engage student context | `localStorage` `bsplus.engageTimetable.student.{origin}` | Current student id | +| 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 | +| Installed themes | localforage (default instance) | `CustomTheme` objects keyed by theme id; index `customThemes` | +| Profile picture upload | localforage `profile-picture-store` / `profilePicture` | Image blob | +| Cloud PFP cache | localforage `cloud-pfp-store` / `cloudPfp` | Cached avatar blobs | +| Background music | localforage `background-music-store` / `music` / `audio-blob` | Audio blob | +| Dev API override | `sessionStorage` `bsplus_dev_api_base` | Staging server URL | +| Engage student context | `localStorage` `bsplus.engageTimetable.student.{origin}` | Current student id | After cloud restore, devices may need to **rebuild** indexes, **re-upload** media, or **re-download** themes even when synced settings reference them. @@ -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: @@ -1076,41 +1076,41 @@ 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"`) | -| `transparencyEffects` | Transparency Effects | Switch | -| `defaultPage` | Default Page | Select | -| `newsSource` | News Feed Source | Select | -| `selectedColor` | Custom Theme Colour | Button → colour picker modal | -| `selectedFont` | Interface Font | Button → font picker modal | -| `adaptiveThemeColour` | Adaptive Theme Colour | Switch | -| `adaptiveThemeGradient` | Soft Gradient | Switch (when adaptive colour on) | -| `adaptiveThemeColourTransition` | Smooth colour transition | Switch (when adaptive colour on) | -| `menuorder`, `menuitems`, `defaultmenuorder` | Edit Sidebar Layout | Button → opens editor **on the SEQTA tab** (not inside the popup) | -| `themeOfTheMonthDisabled` | Theme of the Month | Switch (under Global Search plugin block) | -| `autoCloudSettingsSync` | Automatic sync | Switch (BetterSEQTA Cloud card, signed in only) | -| `onoff` | BetterSEQTA+ | Switch (bottom of tab) | +| Storage key / path | UI label | Control | +| -------------------------------------------- | ------------------------ | ----------------------------------------------------------------- | +| `iconOnlySidebar` | Icon Only Sidebar | Switch | +| `animations` | Animations | Switch | +| `timeFormat` | 12 Hour Time | Switch (`"12"` / `"24"`) | +| `transparencyEffects` | Transparency Effects | Switch | +| `defaultPage` | Default Page | Select | +| `newsSource` | News Feed Source | Select | +| `selectedColor` | Custom Theme Colour | Button → colour picker modal | +| `selectedFont` | Interface Font | Button → font picker modal | +| `adaptiveThemeColour` | Adaptive Theme Colour | Switch | +| `adaptiveThemeGradient` | Soft Gradient | Switch (when adaptive colour on) | +| `adaptiveThemeColourTransition` | Smooth colour transition | Switch (when adaptive colour on) | +| `menuorder`, `menuitems`, `defaultmenuorder` | Edit Sidebar Layout | Button → opens editor **on the SEQTA tab** (not inside the popup) | +| `themeOfTheMonthDisabled` | Theme of the Month | Switch (under Global Search plugin block) | +| `autoCloudSettingsSync` | Automatic sync | Switch (BetterSEQTA Cloud card, signed in only) | +| `onoff` | BetterSEQTA+ | Switch (bottom of tab) | #### Plugin blocks on Settings tab 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` | -| **Timetable Enhancer** | Enable only | `enabled` | -| **Edit Rooms & Teachers** | Enable only | `enabled` | -| **Global Search** | Enable + hotkey + 4 toggles + Reset Index button | `enabled`, `searchHotkey`, `showRecentFirst`, `transparencyEffects`, `runIndexingOnLoad`, `passiveIndexing` — Reset Index does **not** sync index data | -| **Custom Profile Picture** | Enable + Use cloud PFP (if signed in) + upload/remove | `enabled`, `useCloudPfp`; upload updates `profile_picture_revision` (image blob **not** synced) | -| **Message Folders** | Enable + 2 toggles | `enabled`, `showTagsInAllMessages`, `hideFolderedMessagesInAll` | -| **Enhanced Navigation** | Enable + Auto-scroll | `enabled`, `autoScrollOnClick` | -| **Background Music** | Enable + volume + pause on hidden + upload | `enabled`, `volume`, `pauseOnHidden`; audio blob **not** synced | -| **Grade Analytics** | Cache duration (hours) slider only | `cacheTtlHours` | +| 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` | +| **Timetable Enhancer** | Enable only | `enabled` | +| **Edit Rooms & Teachers** | Enable only | `enabled` | +| **Global Search** | Enable + hotkey + 4 toggles + Reset Index button | `enabled`, `searchHotkey`, `showRecentFirst`, `transparencyEffects`, `runIndexingOnLoad`, `passiveIndexing` — Reset Index does **not** sync index data | +| **Custom Profile Picture** | Enable + Use cloud PFP (if signed in) + upload/remove | `enabled`, `useCloudPfp`; upload updates `profile_picture_revision` (image blob **not** synced) | +| **Message Folders** | Enable + 2 toggles | `enabled`, `showTagsInAllMessages`, `hideFolderedMessagesInAll` | +| **Enhanced Navigation** | Enable + Auto-scroll | `enabled`, `autoScrollOnClick` | +| **Background Music** | Enable + volume + pause on hidden + upload | `enabled`, `volume`, `pauseOnHidden`; audio blob **not** synced | +| **Grade Analytics** | Cache duration (hours) slider only | `cacheTtlHours` | **Not shown on Settings tab** (empty `settings` + no enable toggle → card hidden): @@ -1119,75 +1119,75 @@ 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 | +| Storage key | UI label | +| ------------------------------------------------------ | ------------------------------------------------ | +| `devMode` | Developer Mode | +| `hideSensitiveContent` | Sensitive Hider | +| `mockNotices` | Mock Notices | | `privacyStatementShown`, `privacyStatementLastUpdated` | Show Privacy Notification (resets to show popup) | -| `devGhReleaseVersionOverride` | GitHub latest version override (text field) | +| `devGhReleaseVersionOverride` | GitHub latest version override (text field) | Dev **Export cloud settings JSON** downloads the upload payload; it does not change storage. ### 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) | +| Storage key | UI | +| ----------------- | ------------------------------------------------------------------------ | +| `shortcuts` | Toggle built-in shortcuts (Outlook, Office, Google, … from `links.json`) | +| `customshortcuts` | Add / delete custom shortcuts (name, URL, optional SVG icon) | Changes use `settingsState.setKey()` so the SEQTA home page updates immediately via `StorageChangeHandler` → `renderShortcuts()` (embedded settings run in the content script, where `storage.onChanged` does not fire for local writes). Empty arrays are persisted explicitly (`customshortcuts: []`) so cloud restore and other devices clear removed shortcuts. ### 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 | +| 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) | Animated background selection uses `BackgroundSelector` (local/custom backgrounds); store theme id still goes to `selectedTheme`. ### 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`) | -| `subjectfilters` | Assessments → Overview | Subject filter UI in overview grid | -| `plugin.messageFolders.storage.folders` | Messages page | Create/edit/delete folders | -| `plugin.messageFolders.storage.messageAssignments` | Messages page | Assign messages to folders | -| `plugin.timetableEdit.storage.timetableOverrides` | Timetable | Edit room/teacher on a class | -| `plugin.timetableEdit.storage.timetableOverridesBySubject` | Timetable | Subject-level overrides | -| `plugin.assessments-average.storage.weightingOverrides` | Assessments page | Per-assessment “Override %” inputs | -| Global Search | SEQTA | Hotkey opens search bar (hotkey set in Settings) | +| 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`) | +| `subjectfilters` | Assessments → Overview | Subject filter UI in overview grid | +| `plugin.messageFolders.storage.folders` | Messages page | Create/edit/delete folders | +| `plugin.messageFolders.storage.messageAssignments` | Messages page | Assign messages to folders | +| `plugin.timetableEdit.storage.timetableOverrides` | Timetable | Edit room/teacher on a class | +| `plugin.timetableEdit.storage.timetableOverridesBySubject` | Timetable | Subject-level overrides | +| `plugin.assessments-average.storage.weightingOverrides` | Assessments page | Per-assessment “Override %” inputs | +| Global Search | SEQTA | Hotkey opens search bar (hotkey set in Settings) | ### 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 | -| `bsCloudAutoSyncAnnouncementShown` | Dismiss cloud sync announcement | -| `themeOfTheMonthDismissedMonth` | Dismiss Theme of the Month popup | -| `justupdated` | Set `true` after extension update | -| `lastSeenNightlyPublishedAt` | Dismiss / acknowledge GitHub nightly update badge | -| `profile_picture_revision` | Incremented when profile picture changes | -| `plugin.notificationCollector.storage.*` | Written by notification poll loop | -| Legacy `animatedbk`, `bksliderinput`, etc. | Migrated to plugin settings; no longer shown in UI | +| 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 | +| `bsCloudAutoSyncAnnouncementShown` | Dismiss cloud sync announcement | +| `themeOfTheMonthDismissedMonth` | Dismiss Theme of the Month popup | +| `justupdated` | Set `true` after extension update | +| `lastSeenNightlyPublishedAt` | Dismiss / acknowledge GitHub nightly update badge | +| `profile_picture_revision` | Incremented when profile picture changes | +| `plugin.notificationCollector.storage.*` | Written by notification poll loop | +| Legacy `animatedbk`, `bksliderinput`, etc. | Migrated to plugin settings; no longer shown in UI | ### 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) | -| Global Search indexing | Plugin settings toggles | IndexedDB `betterseqta-index`, `embeddiaDB` | -| Assessment averages | `lettergrade`, overrides | `storage.assessments`, `storage.weightings` caches | -| Grade Analytics TTL slider | `cacheTtlHours` | `bsplus.analytics.*` caches | +| 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) | +| Global Search indexing | Plugin settings toggles | IndexedDB `betterseqta-index`, `embeddiaDB` | +| Assessment averages | `lettergrade`, overrides | `storage.assessments`, `storage.weightings` caches | +| Grade Analytics TTL slider | `cacheTtlHours` | `bsplus.analytics.*` caches | ### Never in settings UI (excluded from sync entirely) @@ -1207,14 +1207,14 @@ 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 | -| `plugin.assessments-average.storage.assessments` / `.weightings` | Excluded school caches | -| `plugin.global-search.storage.*` | Excluded prefix | -| Client-only watermarks | Never uploaded | +| 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 | +| `plugin.assessments-average.storage.assessments` / `.weightings` | Excluded school caches | +| `plugin.global-search.storage.*` | Excluded prefix | +| Client-only watermarks | Never uploaded | ### Settings persistence and live UI diff --git a/docs/CLOUD_SETTINGS_SYNC_SERVER.md b/docs/CLOUD_SETTINGS_SYNC_SERVER.md index 4e265ebe..c06146f2 100644 --- a/docs/CLOUD_SETTINGS_SYNC_SERVER.md +++ b/docs/CLOUD_SETTINGS_SYNC_SERVER.md @@ -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" } ``` @@ -96,11 +96,11 @@ 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. | -| `updated_at` | timestamptz | Set on each successful `PUT`. | +| Column | Type | Notes | +| ------------ | ------------ | -------------------------------------------------------------------------------------- | +| `user_id` | FK → users | Unique per backup row (one row per user). | +| `payload` | JSON / JSONB | Store `{ "schemaVersion", "data" }` or only `data` + separate `schema_version` column. | +| `updated_at` | timestamptz | Set on each successful `PUT`. | Unique constraint on `user_id`. diff --git a/docs/README.md b/docs/README.md index b68cdc15..81bf62c0 100644 --- a/docs/README.md +++ b/docs/README.md @@ -2,13 +2,13 @@ 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/) | +| Topic | Where | +| --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Installing | [docs.betterseqta.org/install](https://docs.betterseqta.org/install/) | +| Architecture | [docs.betterseqta.org/architecture](https://docs.betterseqta.org/architecture/) | | Writing plugins | [Plugin development](https://docs.betterseqta.org/plugin-development/), [Plugin API](https://docs.betterseqta.org/plugin-api/), [Example plugin](https://docs.betterseqta.org/example-plugin/) | -| Making themes | [docs.betterseqta.org/theme-creation](https://docs.betterseqta.org/theme-creation/) | -| Troubleshooting | [docs.betterseqta.org/troubleshooting](https://docs.betterseqta.org/troubleshooting/) | +| Making themes | [docs.betterseqta.org/theme-creation](https://docs.betterseqta.org/theme-creation/) | +| Troubleshooting | [docs.betterseqta.org/troubleshooting](https://docs.betterseqta.org/troubleshooting/) | These pages only live in this repo because they track the code closely: diff --git a/docs/RELEASES.md b/docs/RELEASES.md index dd85c7c7..81eec418 100644 --- a/docs/RELEASES.md +++ b/docs/RELEASES.md @@ -4,21 +4,26 @@ 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. | +| 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. | -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 | +| 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 diff --git a/eslint.config.js b/eslint.config.js deleted file mode 100644 index 4accbffa..00000000 --- a/eslint.config.js +++ /dev/null @@ -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", - }, - }, -]; diff --git a/jest.config.js b/jest.config.js index d19f5dea..66fe5be5 100644 --- a/jest.config.js +++ b/jest.config.js @@ -1,29 +1,20 @@ export default { - preset: 'ts-jest', - testEnvironment: 'node', - roots: ['/src'], - testMatch: [ - '**/__tests__/**/*.ts', - '**/?(*.)+(spec|test).ts' - ], + preset: "ts-jest", + testEnvironment: "node", + roots: ["/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))?$': - '/src/test/mocks/crxjsScriptPath.ts', - '^@/lib/browser$': '/src/test/mocks/browser.ts', - '^@/(.*)$': '/src/$1', - '^color$': '/src/test/mocks/color.ts', + "^@/(.*)\\?script(?:&(?:iife|module))?$": "/src/test/mocks/crxjsScriptPath.ts", + "^@/lib/browser$": "/src/test/mocks/browser.ts", + "^@/(.*)$": "/src/$1", + "^color$": "/src/test/mocks/color.ts", }, - setupFilesAfterEnv: ['/src/test/jest.setup.ts'], - moduleFileExtensions: ['ts', 'js', 'json'], - collectCoverageFrom: [ - 'src/**/*.ts', - '!src/**/*.d.ts', - ], -}; + setupFilesAfterEnv: ["/src/test/jest.setup.ts"], + moduleFileExtensions: ["ts", "js", "json"], + collectCoverageFrom: ["src/**/*.ts", "!src/**/*.d.ts"], +}; diff --git a/package-lock.json b/package-lock.json index db720d09..834d0b55 100644 --- a/package-lock.json +++ b/package-lock.json @@ -41,7 +41,6 @@ }, "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", @@ -58,19 +57,17 @@ "@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", + "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", - "typescript-eslint": "^8.72.1", "vite": "^8.3.5" }, "engines": { @@ -646,30 +643,6 @@ "dev": true, "license": "MIT" }, - "node_modules/@cacheable/memory": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/@cacheable/memory/-/memory-2.2.0.tgz", - "integrity": "sha512-CTLKqLItRCEixEAewD3/j9DB3/o96gpTPD4eJ1v+DGOlxZRZncRQkGYqqnAGCscYd6RNeXfGeiuCphsPtqyIfQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@cacheable/utils": "^2.5.0", - "@keyv/bigmap": "^1.3.1", - "hookified": "^1.15.1", - "keyv": "^5.6.0" - } - }, - "node_modules/@cacheable/utils": { - "version": "2.5.0", - "resolved": "https://registry.npmjs.org/@cacheable/utils/-/utils-2.5.0.tgz", - "integrity": "sha512-buipgOVDkkPXNR5+xBpDw7Zk2n1EvU7qBJCNUcL7rhQ//kfpOXPAvQ511Os0vpLYJ1pZnvudNytkQt2hst3wqA==", - "dev": true, - "license": "MIT", - "dependencies": { - "hashery": "^1.5.1", - "keyv": "^5.6.0" - } - }, "node_modules/@codemirror/autocomplete": { "version": "6.20.4", "resolved": "https://registry.npmjs.org/@codemirror/autocomplete/-/autocomplete-6.20.4.tgz", @@ -1375,134 +1348,6 @@ "node": ">=18" } }, - "node_modules/@eslint-community/eslint-utils": { - "version": "4.10.1", - "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.10.1.tgz", - "integrity": "sha512-cuadcxVFE8sDK6iWJbs8Sn0av2Nrh2QSGQhVlBW9AaAHqHwjWsZHT8LJ4hFGPh7ASBV2deFdM7H/DPjulmh8rg==", - "dev": true, - "license": "MIT", - "dependencies": { - "eslint-visitor-keys": "^3.4.3" - }, - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - }, - "funding": { - "url": "https://opencollective.com/eslint" - }, - "peerDependencies": { - "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0" - } - }, - "node_modules/@eslint-community/eslint-utils/node_modules/eslint-visitor-keys": { - "version": "3.4.3", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz", - "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - }, - "funding": { - "url": "https://opencollective.com/eslint" - } - }, - "node_modules/@eslint-community/regexpp": { - "version": "4.12.2", - "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.12.2.tgz", - "integrity": "sha512-EriSTlt5OC9/7SXkRSCAhfSxxoSUgBm33OH+IkwbdpgoqsSsUg7y3uh+IICI/Qg4BBWr3U2i39RpmycbxMq4ew==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^12.0.0 || ^14.0.0 || >=16.0.0" - } - }, - "node_modules/@eslint/config-array": { - "version": "0.23.5", - "resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.23.5.tgz", - "integrity": "sha512-Y3kKLvC1dvTOT+oGlqNQ1XLqK6D1HU2YXPc52NmAlJZbMMWDzGYXMiPRJ8TYD39muD/OTjlZmNJ4ib7dvSrMBA==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@eslint/object-schema": "^3.0.5", - "debug": "^4.3.1", - "minimatch": "^10.2.4" - }, - "engines": { - "node": "^20.19.0 || ^22.13.0 || >=24" - } - }, - "node_modules/@eslint/config-helpers": { - "version": "0.7.0", - "resolved": "https://registry.npmjs.org/@eslint/config-helpers/-/config-helpers-0.7.0.tgz", - "integrity": "sha512-DObd/KKUsU+FaFv4PLxSRenpXfQWmPXXP3pPZ6/K1PCrMu2vQpMDMuQe/BqYeoLcz8ro0bVDF1RxOJgfVEdhUw==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@eslint/core": "^1.2.1" - }, - "engines": { - "node": "^20.19.0 || ^22.13.0 || >=24" - } - }, - "node_modules/@eslint/core": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/@eslint/core/-/core-1.2.1.tgz", - "integrity": "sha512-MwcE1P+AZ4C6DWlpin/OmOA54mmIZ/+xZuJiQd4SyB29oAJjN30UW9wkKNptW2ctp4cEsvhlLY/CsQ1uoHDloQ==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@types/json-schema": "^7.0.15" - }, - "engines": { - "node": "^20.19.0 || ^22.13.0 || >=24" - } - }, - "node_modules/@eslint/js": { - "version": "10.0.1", - "resolved": "https://registry.npmjs.org/@eslint/js/-/js-10.0.1.tgz", - "integrity": "sha512-zeR9k5pd4gxjZ0abRoIaxdc7I3nDktoXZk2qOv9gCNWx3mVwEn32VRhyLaRsDiJjTs0xq/T8mfPtyuXu7GWBcA==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^20.19.0 || ^22.13.0 || >=24" - }, - "funding": { - "url": "https://eslint.org/donate" - }, - "peerDependencies": { - "eslint": "^10.0.0" - }, - "peerDependenciesMeta": { - "eslint": { - "optional": true - } - } - }, - "node_modules/@eslint/object-schema": { - "version": "3.0.5", - "resolved": "https://registry.npmjs.org/@eslint/object-schema/-/object-schema-3.0.5.tgz", - "integrity": "sha512-vqTaUEgxzm+YDSdElad6PiRoX4t8VGDjCtt05zn4nU810UIx/uNEV7/lZJ6KwFThKZOzOxzXy48da+No7HZaMw==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": "^20.19.0 || ^22.13.0 || >=24" - } - }, - "node_modules/@eslint/plugin-kit": { - "version": "0.7.3", - "resolved": "https://registry.npmjs.org/@eslint/plugin-kit/-/plugin-kit-0.7.3.tgz", - "integrity": "sha512-IkO+/KEUvwbVpiURZg+P7zF74z5Jxe0UgJxVni+RtoHQ6IZieXaO02kmadomap/q+l6bc/jdPGGqTjhuZnuz1Q==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@eslint/core": "^1.2.1", - "levn": "^0.4.1" - }, - "engines": { - "node": "^20.19.0 || ^22.13.0 || >=24" - } - }, "node_modules/@floating-ui/core": { "version": "1.8.0", "resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.8.0.tgz", @@ -1549,72 +1394,6 @@ "sharp": "^0.34.1" } }, - "node_modules/@humanfs/core": { - "version": "0.19.2", - "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.2.tgz", - "integrity": "sha512-UhXNm+CFMWcbChXywFwkmhqjs3PRCmcSa/hfBgLIb7oQ5HNb1wS0icWsGtSAUNgefHeI+eBrA8I1fxmbHsGdvA==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@humanfs/types": "^0.15.0" - }, - "engines": { - "node": ">=18.18.0" - } - }, - "node_modules/@humanfs/node": { - "version": "0.16.8", - "resolved": "https://registry.npmjs.org/@humanfs/node/-/node-0.16.8.tgz", - "integrity": "sha512-gE1eQNZ3R++kTzFUpdGlpmy8kDZD/MLyHqDwqjkVQI0JMdI1D51sy1H958PNXYkM2rAac7e5/CnIKZrHtPh3BQ==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@humanfs/core": "^0.19.2", - "@humanfs/types": "^0.15.0", - "@humanwhocodes/retry": "^0.4.0" - }, - "engines": { - "node": ">=18.18.0" - } - }, - "node_modules/@humanfs/types": { - "version": "0.15.0", - "resolved": "https://registry.npmjs.org/@humanfs/types/-/types-0.15.0.tgz", - "integrity": "sha512-ZZ1w0aoQkwuUuC7Yf+7sdeaNfqQiiLcSRbfI08oAxqLtpXQr9AIVX7Ay7HLDuiLYAaFPu8oBYNq/QIi9URHJ3Q==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": ">=18.18.0" - } - }, - "node_modules/@humanwhocodes/module-importer": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz", - "integrity": "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": ">=12.22" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/nzakas" - } - }, - "node_modules/@humanwhocodes/retry": { - "version": "0.4.3", - "resolved": "https://registry.npmjs.org/@humanwhocodes/retry/-/retry-0.4.3.tgz", - "integrity": "sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": ">=18.18" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/nzakas" - } - }, "node_modules/@img/colour": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz", @@ -2661,30 +2440,6 @@ "@jridgewell/sourcemap-codec": "^1.4.14" } }, - "node_modules/@keyv/bigmap": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/@keyv/bigmap/-/bigmap-1.3.1.tgz", - "integrity": "sha512-WbzE9sdmQtKy8vrNPa9BRnwZh5UF4s1KTmSK0KUVLo3eff5BlQNNWDnFOouNpKfPKDnms9xynJjsMYjMaT/aFQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "hashery": "^1.4.0", - "hookified": "^1.15.0" - }, - "engines": { - "node": ">= 18" - }, - "peerDependencies": { - "keyv": "^5.6.0" - } - }, - "node_modules/@keyv/serialize": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/@keyv/serialize/-/serialize-1.1.1.tgz", - "integrity": "sha512-dXn3FZhPv0US+7dtJsIi2R+c7qWYiReoEh5zUntWCf4oSpMNib8FDhSoed6m3QyZdx5hK7iLFkYk3rNxwt8vTA==", - "dev": true, - "license": "MIT" - }, "node_modules/@layerstack/svelte-actions": { "version": "1.0.1-next.20", "resolved": "https://registry.npmjs.org/@layerstack/svelte-actions/-/svelte-actions-1.0.1-next.20.tgz", @@ -3053,6 +2808,700 @@ "url": "https://github.com/sponsors/oxc-project" } }, + "node_modules/@oxfmt/binding-android-arm-eabi": { + "version": "0.75.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-android-arm-eabi/-/binding-android-arm-eabi-0.75.0.tgz", + "integrity": "sha512-zHJ7LcTN46/5mtoLxsUu14pdF9ixFwDURtmxZ0CeNwqom5qB5NRVqU6o2GRZ7QPdNBW8G6j9UTJzQ+EDevMH0w==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-android-arm64": { + "version": "0.75.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-android-arm64/-/binding-android-arm64-0.75.0.tgz", + "integrity": "sha512-IdxsKZJvHZUvI7q6kLmzXdEFpFiBEDQw/WJtSp1QlzNXBw1JlLN3tY50WwWd4doPnq86XW4P+7BsQwu6meCW+w==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-darwin-arm64": { + "version": "0.75.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-darwin-arm64/-/binding-darwin-arm64-0.75.0.tgz", + "integrity": "sha512-vyiqZilO5jal/nXZ0143NyKcP6TkzjaQdVEWU/kwgyWqugAgIRgAbrnO3MOF+e6LkQu3CrtrkPoc3mrsZZY6cA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-darwin-x64": { + "version": "0.75.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-darwin-x64/-/binding-darwin-x64-0.75.0.tgz", + "integrity": "sha512-oua7eVqVe769mDam6ORcavygxTzG3ovo5QRQ1kJCPaEbnWXPYhtAiYDj8pajVmFjO7j8Elf3gInnWpTX0LLYtg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-freebsd-x64": { + "version": "0.75.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-freebsd-x64/-/binding-freebsd-x64-0.75.0.tgz", + "integrity": "sha512-NWkbezhg7mx2Ep94g/TysR3c1bsISsU4lQ6t5xI4841PAk0Kqcn1+UEe+BoFH2/UK2YegPXq+OF+0bUcSvUalA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-linux-arm-gnueabihf": { + "version": "0.75.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-0.75.0.tgz", + "integrity": "sha512-CAHX87kJplTq2E0OWP7opG8gEVlHc7CeLEi4nMJOyx3psuqBKf84HZ3UIkX2guWEJ5UljU2zJF0o46XylywVVA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-linux-arm-musleabihf": { + "version": "0.75.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm-musleabihf/-/binding-linux-arm-musleabihf-0.75.0.tgz", + "integrity": "sha512-jmxYOiQzx2fp+OwQb7717K1zI8AMKEykw04sfr95/mU8SIL/oKgQq8nXH42sEznEquBL2RU7nLY36eBnYFT+vg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-linux-arm64-gnu": { + "version": "0.75.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-0.75.0.tgz", + "integrity": "sha512-eimaiAhx08dbOg12Fj3PYhymXY8vRbaiJB505vDXMy6ohne3Y1qTS0e5KEwFMq3LmDjEO+16BX38c/oXFI/SAQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-linux-arm64-musl": { + "version": "0.75.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm64-musl/-/binding-linux-arm64-musl-0.75.0.tgz", + "integrity": "sha512-bjSONIG1ba2xugr9oHQau0E6oPFYOMjPaa5hK/wpVC/Q1pcgf2BZMKwbuA8/cWzhWX5QV/UdPzD+rw1kQHpikQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-linux-ppc64-gnu": { + "version": "0.75.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-0.75.0.tgz", + "integrity": "sha512-wDksWQXC/KZucISyqlhBtvpW+pyHh8z0Cjm6Qxiv22XlllM2Bx5gJGDnPYjV+H0lL+o1iqLlEli8jmBuRCLcjw==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-linux-riscv64-gnu": { + "version": "0.75.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-0.75.0.tgz", + "integrity": "sha512-5JkNwViqaVuk4I+9+zgVrEYiHOAPXFxgDgP6iDnpdOBjm7XAHAOjSvolHZZAokWPx7CGOw8tKteXmn4WPIInaQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-linux-riscv64-musl": { + "version": "0.75.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-0.75.0.tgz", + "integrity": "sha512-1EVqRIE0eZLB08j3ZCVN47Ors7LCXGmOI+3xJYgyoFUKUerD3Glxb+Q1Bp3lK8NeT5R3ZdS9uhX/wobNBYZ6jw==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-linux-s390x-gnu": { + "version": "0.75.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-0.75.0.tgz", + "integrity": "sha512-UJWRVNT6Yuw4ssLv2BwaBUWU1GWtByE+EnoHu8I+P1t8Kn+WozYU5WYOqb5aj8gbXJJ8gGZt+w40Hi/7L6iVLw==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-linux-x64-gnu": { + "version": "0.75.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-x64-gnu/-/binding-linux-x64-gnu-0.75.0.tgz", + "integrity": "sha512-FHdvHhyz8ChBctBUvVGti49kSEwANd1PZQwlXUEoF9Ed4plxXxk/wWc0mfZmrze2lRgmME7ytDmVIOixYauQhg==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-linux-x64-musl": { + "version": "0.75.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-x64-musl/-/binding-linux-x64-musl-0.75.0.tgz", + "integrity": "sha512-6MjtsF96s9mSBV0GEwUe4pOFPP2Mz7ahcHPAit0DSKL5fM6oMM7RG1zvYxwB7+SBkIxsWBRhhxuqmy7pibNwsA==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-openharmony-arm64": { + "version": "0.75.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-openharmony-arm64/-/binding-openharmony-arm64-0.75.0.tgz", + "integrity": "sha512-1D6T6aL1Pj+U5GLxqwV1fKjUJ5+FFm+bn7UrqNDMveZmWs0jo/3vc+dzzuV/jF/FdVo12gowODk3SnAO2YOwLg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-win32-arm64-msvc": { + "version": "0.75.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-0.75.0.tgz", + "integrity": "sha512-RX2eUmy7J/nM8+tnM3nzR8t1eqkwj1q8Kgo7beA+4DVgKYYHHyrEa3qEmthxw7Z+HqpCCEOWuoqa+jelo9/w2Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-win32-ia32-msvc": { + "version": "0.75.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-0.75.0.tgz", + "integrity": "sha512-UpKta0iSZmPLII0dYXYdbzdBTsGREUbSHLqgLdtKcqBvs40qjmUz+cgUcaU1smPx13DfbEG4XqnaSn5MoFN0og==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxfmt/binding-win32-x64-msvc": { + "version": "0.75.0", + "resolved": "https://registry.npmjs.org/@oxfmt/binding-win32-x64-msvc/-/binding-win32-x64-msvc-0.75.0.tgz", + "integrity": "sha512-pjiLiCk0QMCWxs0n5XiNU85YLAKA+wJxPjxlDVygmr4bP4glcfTU2nOpso5nR4Rdi2Pxv5YwakD4UE+eh7M0BQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-android-arm-eabi": { + "version": "1.90.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-android-arm-eabi/-/binding-android-arm-eabi-1.90.0.tgz", + "integrity": "sha512-sgfalb1HuxYjiAa4wESZ626z1FGusqNcXYHyB5oIOEprS2sbPg0UYEfo83uF1GNG70DIfZxHkXuE6KFrlSdn8Q==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-android-arm64": { + "version": "1.90.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-android-arm64/-/binding-android-arm64-1.90.0.tgz", + "integrity": "sha512-RcKhz1ETMq+fazE9TKS2+5NIRGwigm/nW8egqF0LI+A8Yw2iW5r0E/C3XAPRiwIm/vcPiutIRIa6IQCIKhZsTQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-darwin-arm64": { + "version": "1.90.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-darwin-arm64/-/binding-darwin-arm64-1.90.0.tgz", + "integrity": "sha512-PSrxMvP6mx+p1karZcUxLdy9lpaP+JWQPti4al9FgTaPhxE+pT/BjhGExloVVSWgZgIfOlLOjVyyq8BXlodhLQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-darwin-x64": { + "version": "1.90.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-darwin-x64/-/binding-darwin-x64-1.90.0.tgz", + "integrity": "sha512-OLbU9qsrV2Q8QxT2OEzOPdO8zCCpyI8qB+hDI8yr6RsYELtkf0FAZhJdfjM/RnLHKzt44HWwAPnk92vBtKofvw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-freebsd-x64": { + "version": "1.90.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-freebsd-x64/-/binding-freebsd-x64-1.90.0.tgz", + "integrity": "sha512-fBA4pWyVDARmNucQqpyFuPC49xYf1r+sX7dxPL5fNPQrSMLum39Sn56tZ9JPleWC7FzLPwSQ7plYYfirYBHF8A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-linux-arm-gnueabihf": { + "version": "1.90.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.90.0.tgz", + "integrity": "sha512-zhxH78eP2nR6/pGdhBc7MIfjhhcgATeu8fkmkFJbuzfk6Cj0FzBxyEhL85yDqrCybjx+G2YDzZGsxIO9kvO4Iw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-linux-arm-musleabihf": { + "version": "1.90.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm-musleabihf/-/binding-linux-arm-musleabihf-1.90.0.tgz", + "integrity": "sha512-MvYmpHyJqUJjEvkZbJHdwfdL45cGn8EVBkYmoXFiaYFW9suoD3dbJl5mBdpy0DVgdjlyddmldbRtk3cCgETadQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-linux-arm64-gnu": { + "version": "1.90.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.90.0.tgz", + "integrity": "sha512-L13Sy+Kg0nZhwTsToniqjUFPA2TuM6962qCZ5Wp5KeB517Tw7ApdLTTtlb+bF86fcZZa2EtvCVvAJxk4Dya/MQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-linux-arm64-musl": { + "version": "1.90.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.90.0.tgz", + "integrity": "sha512-wFDdZWGpzIPFdJFjSLWnKB0TGzFriTKUIrl04iMqMyM9BBIJTuerfCHYa0WpDSjr5x3lcW/CHLyacSt886WpGg==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-linux-ppc64-gnu": { + "version": "1.90.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.90.0.tgz", + "integrity": "sha512-FRywfn+MoKn8xpBSzgNwNVliSKRI2QXkxi/iF7o6FEQs8Bh8z2RpVTaFAcO3pchXjvB2eGNFIoLLQABIQ+u7VA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-linux-riscv64-gnu": { + "version": "1.90.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-1.90.0.tgz", + "integrity": "sha512-IS2PaUgpc/qeLADTyhUNmdx3x4ijs9pjJdPKBYHaT+mAE7k3FsjnHPTjhpsak1b++h6CIPhv6WX9Z+y7Pw0voQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-linux-riscv64-musl": { + "version": "1.90.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-1.90.0.tgz", + "integrity": "sha512-s7JFKRkGS8O7i2ZVODfuO++NC7sH6HDqpMn8lYxw91w0SXJOxnAVjQ8utvmDwLMMT0jaSkuOKuUYJDGDtu4sHQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-linux-s390x-gnu": { + "version": "1.90.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.90.0.tgz", + "integrity": "sha512-b0GxrOQr5VONCkd7KLSqmP6b6nqZuTpuS8QPQHzltmqdXP5bY0Jl0CZ0QmlCTrS3ExaLYbioFYOARzNbYvcApQ==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-linux-x64-gnu": { + "version": "1.90.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.90.0.tgz", + "integrity": "sha512-iaJeShJtgUp8rZbt9YUdTAGOpmX5KogCLba17Jp1tWdJ3F4M3D2g2TKUyI1FMTHxKH9NNHuQcuC2kZRg6IV7yQ==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-linux-x64-musl": { + "version": "1.90.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-linux-x64-musl/-/binding-linux-x64-musl-1.90.0.tgz", + "integrity": "sha512-/aZoXnL5WBLCXuzfHqvEFXcm4iwYmr/cYByHDTXzLFzJdE5DC7bm6phpWqHv6BeqpVgY9IpBAxGDv2WEkl5JCg==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-openharmony-arm64": { + "version": "1.90.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-openharmony-arm64/-/binding-openharmony-arm64-1.90.0.tgz", + "integrity": "sha512-SMhk7ozwoxYDKfYqGZCQEfULOKDneF9uhaoIf2neoDLWvNtjY9yVeL7YHmE5L9WdKvMpWNwwZxhenxBu6AgfOg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-win32-arm64-msvc": { + "version": "1.90.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.90.0.tgz", + "integrity": "sha512-KBvR3A9fO7fCi2vCP8ifWvlia7tGEQV9NaYh+IGwa/7Groy48Mt/UaYqMK9/zOtAWl20BUCf6RPqzJ32fRw33Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-win32-ia32-msvc": { + "version": "1.90.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-1.90.0.tgz", + "integrity": "sha512-+x42rDHQGbTCuT3EzpWAzhP3NoVPE/cJsG4gnrakOSg0olV+GCdMpPU23Nvrl3zZMnXxFZdTtDv4D3SuaA5ZeQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxlint/binding-win32-x64-msvc": { + "version": "1.90.0", + "resolved": "https://registry.npmjs.org/@oxlint/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.90.0.tgz", + "integrity": "sha512-30JiaFEBUB9peEOcvVM8ggo88SoN/IdSr9DW505JdBji/R6dM66gKEiG65hw6qcaF2f4mO0cEJ+RwRZprmun9g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, "node_modules/@parcel/watcher": { "version": "2.6.0", "resolved": "https://registry.npmjs.org/@parcel/watcher/-/watcher-2.6.0.tgz", @@ -4209,13 +4658,6 @@ "dev": true, "license": "MIT" }, - "node_modules/@types/esrecurse": { - "version": "4.3.1", - "resolved": "https://registry.npmjs.org/@types/esrecurse/-/esrecurse-4.3.1.tgz", - "integrity": "sha512-xJBAbDifo5hpffDBuHl0Y8ywswbiAp/Wi7Y/GtAgSlZyIABppyurxVueOPE8LUQOxdlgi6Zqce7uoEpqNTeiUw==", - "dev": true, - "license": "MIT" - }, "node_modules/@types/estree": { "version": "1.0.10", "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.10.tgz", @@ -4285,13 +4727,6 @@ "parse5": "^7.0.0" } }, - "node_modules/@types/json-schema": { - "version": "7.0.15", - "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", - "integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==", - "dev": true, - "license": "MIT" - }, "node_modules/@types/mime-types": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/@types/mime-types/-/mime-types-3.0.1.tgz", @@ -4370,236 +4805,6 @@ "dev": true, "license": "MIT" }, - "node_modules/@typescript-eslint/eslint-plugin": { - "version": "8.72.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.72.1.tgz", - "integrity": "sha512-5CokTWXpmbylfFabsbvHC0CAw3XLaGnoa+nFJX5FR592h/LoZsENUE6p/rg5xvkKrFEXz6pYmgI29AgXc2N3BQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@eslint-community/regexpp": "^4.12.2", - "@typescript-eslint/scope-manager": "8.72.1", - "@typescript-eslint/type-utils": "8.72.1", - "@typescript-eslint/utils": "8.72.1", - "@typescript-eslint/visitor-keys": "8.72.1", - "ignore": "^7.0.5", - "natural-compare": "^1.4.0", - "ts-api-utils": "^2.5.0" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "@typescript-eslint/parser": "^8.72.1", - "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", - "typescript": ">=4.8.4 <6.1.0" - } - }, - "node_modules/@typescript-eslint/eslint-plugin/node_modules/ignore": { - "version": "7.0.14", - "resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.14.tgz", - "integrity": "sha512-wCBiZ77u1tuWde6G/nfOtLaCTYcFDU5yCzARzK10y+rLhzYoL7a7yEemcopcc2Mzow7gZOIjnV2ym1NYmdiJOQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 4" - } - }, - "node_modules/@typescript-eslint/parser": { - "version": "8.72.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.72.1.tgz", - "integrity": "sha512-ZGwZP4OCfyA0AQTpEAMWz+rtX01DRhQWW5hB0ucKDEIX5U7jdmPSaMx94rQfaPAQzIYz2BimOgKOJtjfpRFQ9g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@typescript-eslint/scope-manager": "8.72.1", - "@typescript-eslint/types": "8.72.1", - "@typescript-eslint/typescript-estree": "8.72.1", - "@typescript-eslint/visitor-keys": "8.72.1", - "debug": "^4.4.3" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", - "typescript": ">=4.8.4 <6.1.0" - } - }, - "node_modules/@typescript-eslint/project-service": { - "version": "8.72.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.72.1.tgz", - "integrity": "sha512-fAuVMkwdO/huI8nyo/WKnNKf6Gag93S56Rh3Ts5mGcavwSdaN8tRg1gCeIGX8PF+nzp1BjGfO4gHhGzW1J6jTg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@typescript-eslint/tsconfig-utils": "^8.72.1", - "@typescript-eslint/types": "^8.72.1", - "debug": "^4.4.3" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "typescript": ">=4.8.4 <6.1.0" - } - }, - "node_modules/@typescript-eslint/scope-manager": { - "version": "8.72.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.72.1.tgz", - "integrity": "sha512-lC/t6eMCZZQAAKZEYGL6RDVSuFehpdmMT6h+nJIjIa6oylN/PwDgDVtEIbB7O9xFfZYtZAYLoLlDNWKJhtF+uQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@typescript-eslint/types": "8.72.1", - "@typescript-eslint/visitor-keys": "8.72.1" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - } - }, - "node_modules/@typescript-eslint/tsconfig-utils": { - "version": "8.72.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.72.1.tgz", - "integrity": "sha512-e4D5R5vpeAEPBxT2BAzsFQL3sbwyeeeo5+aczgNSRK1V734jE7pTqaGFU+fXapWEQwnZbpFaTn32+Z8DwS6OTg==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "typescript": ">=4.8.4 <6.1.0" - } - }, - "node_modules/@typescript-eslint/type-utils": { - "version": "8.72.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.72.1.tgz", - "integrity": "sha512-iY2wlmyrXJmx4yxUGP3aYCFF3cA/6ShddOKmLU2dx7LnEykbAM8WThlxZEfd1NddqceF6eJmZUayxx9oKIYNlg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@typescript-eslint/types": "8.72.1", - "@typescript-eslint/typescript-estree": "8.72.1", - "@typescript-eslint/utils": "8.72.1", - "debug": "^4.4.3", - "ts-api-utils": "^2.5.0" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", - "typescript": ">=4.8.4 <6.1.0" - } - }, - "node_modules/@typescript-eslint/types": { - "version": "8.72.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.72.1.tgz", - "integrity": "sha512-LmE5IhQet1BWOWEXqBrVtBPsMAOQ6Nzk35d+WLh3mk4EUF33sqlfxjio1MdYeSvKSG5skactKKuixBIKXhL4Rw==", - "devOptional": true, - "license": "MIT", - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - } - }, - "node_modules/@typescript-eslint/typescript-estree": { - "version": "8.72.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.72.1.tgz", - "integrity": "sha512-DAlUoUV93hIvrtIQLwCbmZQYVZwOMhiHJrOVUUIWicFZaIYjTRqlY3I/NZevfkLmSqkNHRu2qYDcq9lrn16oOQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@typescript-eslint/project-service": "8.72.1", - "@typescript-eslint/tsconfig-utils": "8.72.1", - "@typescript-eslint/types": "8.72.1", - "@typescript-eslint/visitor-keys": "8.72.1", - "debug": "^4.4.3", - "minimatch": "^10.2.2", - "semver": "^7.7.3", - "tinyglobby": "^0.2.15", - "ts-api-utils": "^2.5.0" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "typescript": ">=4.8.4 <6.1.0" - } - }, - "node_modules/@typescript-eslint/utils": { - "version": "8.72.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.72.1.tgz", - "integrity": "sha512-5v5liypurJBFHCBNqh/RjsymAD+VWcE0djuGY/BUqp5fC3Qn+luWDEksjuTtWjPn6i5zQlUtkZCRG/CYG0yCkA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@eslint-community/eslint-utils": "^4.9.1", - "@typescript-eslint/scope-manager": "8.72.1", - "@typescript-eslint/types": "8.72.1", - "@typescript-eslint/typescript-estree": "8.72.1" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", - "typescript": ">=4.8.4 <6.1.0" - } - }, - "node_modules/@typescript-eslint/visitor-keys": { - "version": "8.72.1", - "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.72.1.tgz", - "integrity": "sha512-SB8xqipSzZHUePCCLNeYxqnxq83X61/qzNhjQGbTfjxGZIeOEP7tBgWYX05Tcd6CgE02WdTJnh5b8kMZJ/+bnQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@typescript-eslint/types": "8.72.1", - "eslint-visitor-keys": "^5.0.0" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - } - }, "node_modules/@uiw/codemirror-extensions-color": { "version": "4.25.12", "resolved": "https://registry.npmjs.org/@uiw/codemirror-extensions-color/-/codemirror-extensions-color-4.25.12.tgz", @@ -5002,16 +5207,6 @@ "node": ">=0.4.0" } }, - "node_modules/acorn-jsx": { - "version": "5.3.2", - "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz", - "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==", - "dev": true, - "license": "MIT", - "peerDependencies": { - "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" - } - }, "node_modules/acorn-walk": { "version": "8.3.5", "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.3.5.tgz", @@ -5035,23 +5230,6 @@ "node": ">= 14" } }, - "node_modules/ajv": { - "version": "6.15.0", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.15.0.tgz", - "integrity": "sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw==", - "dev": true, - "license": "MIT", - "dependencies": { - "fast-deep-equal": "^3.1.1", - "fast-json-stable-stringify": "^2.0.0", - "json-schema-traverse": "^0.4.1", - "uri-js": "^4.2.2" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/epoberezkin" - } - }, "node_modules/ansi-escapes": { "version": "4.3.2", "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-4.3.2.tgz", @@ -5381,20 +5559,6 @@ "node": ">=20.19.0" } }, - "node_modules/cacheable": { - "version": "2.5.0", - "resolved": "https://registry.npmjs.org/cacheable/-/cacheable-2.5.0.tgz", - "integrity": "sha512-60cyAOytib/OzBw1JNSoSV/boK1AtHryDIjvVBk7XbN4ugfkM3+Sry7fEjNgPMGgOjuaZPAp8ruZ0Cxafwyq9g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@cacheable/memory": "^2.2.0", - "@cacheable/utils": "^2.5.0", - "hookified": "^1.15.0", - "keyv": "^5.6.0", - "qified": "^0.10.1" - } - }, "node_modules/callsites": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", @@ -6178,13 +6342,6 @@ } } }, - "node_modules/deep-is": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz", - "integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==", - "dev": true, - "license": "MIT" - }, "node_modules/deepmerge": { "version": "4.3.1", "resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.3.1.tgz", @@ -6565,121 +6722,12 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/eslint": { - "version": "10.14.0", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-10.14.0.tgz", - "integrity": "sha512-T0pNsxkb9IKmtQjhpK3d7nWOpFv+YHuMbTJnSVMoQblF0onvXfErrtp4V1jHtsQPan7dKaGVD0q1WCXnzMF31A==", - "dev": true, - "license": "MIT", - "workspaces": [ - "packages/*" - ], - "dependencies": { - "@eslint-community/eslint-utils": "^4.8.0", - "@eslint-community/regexpp": "^4.12.2", - "@eslint/config-array": "^0.23.5", - "@eslint/config-helpers": "^0.7.0", - "@eslint/core": "^1.2.1", - "@eslint/plugin-kit": "^0.7.3", - "@humanfs/node": "^0.16.8", - "@humanwhocodes/module-importer": "^1.0.1", - "@humanwhocodes/retry": "^0.4.2", - "@types/estree": "^1.0.6", - "ajv": "^6.14.0", - "cross-spawn": "^7.0.6", - "debug": "^4.3.2", - "escape-string-regexp": "^4.0.0", - "eslint-scope": "^9.1.2", - "eslint-visitor-keys": "^5.0.1", - "espree": "^11.2.0", - "esquery": "^1.7.0", - "esutils": "^2.0.2", - "fast-deep-equal": "^3.1.3", - "file-entry-cache": "11.1.5 || >11.1.6 <12", - "find-up": "^5.0.0", - "glob-parent": "^6.0.2", - "ignore": "^5.2.0", - "imurmurhash": "^0.1.4", - "is-glob": "^4.0.0", - "json-stable-stringify-without-jsonify": "^1.0.1", - "minimatch": "^10.2.6", - "natural-compare": "^1.4.0", - "optionator": "^0.9.3" - }, - "bin": { - "eslint": "bin/eslint.js" - }, - "engines": { - "node": "^20.19.0 || ^22.13.0 || >=24" - }, - "funding": { - "url": "https://eslint.org/donate" - }, - "peerDependencies": { - "jiti": "*" - }, - "peerDependenciesMeta": { - "jiti": { - "optional": true - } - } - }, - "node_modules/eslint-scope": { - "version": "9.1.2", - "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-9.1.2.tgz", - "integrity": "sha512-xS90H51cKw0jltxmvmHy2Iai1LIqrfbw57b79w/J7MfvDfkIkFZ+kj6zC3BjtUwh150HsSSdxXZcsuv72miDFQ==", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "@types/esrecurse": "^4.3.1", - "@types/estree": "^1.0.8", - "esrecurse": "^4.3.0", - "estraverse": "^5.2.0" - }, - "engines": { - "node": "^20.19.0 || ^22.13.0 || >=24" - }, - "funding": { - "url": "https://opencollective.com/eslint" - } - }, - "node_modules/eslint-visitor-keys": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-5.0.1.tgz", - "integrity": "sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": "^20.19.0 || ^22.13.0 || >=24" - }, - "funding": { - "url": "https://opencollective.com/eslint" - } - }, "node_modules/esm-env": { "version": "1.2.2", "resolved": "https://registry.npmjs.org/esm-env/-/esm-env-1.2.2.tgz", "integrity": "sha512-Epxrv+Nr/CaL4ZcFGPJIYLWFom+YeV1DqMLHJoEd9SYRxNbaFruBwfEX/kkHUJf55j2+TUbmDcmuilbP1TmXHA==", "license": "MIT" }, - "node_modules/espree": { - "version": "11.2.0", - "resolved": "https://registry.npmjs.org/espree/-/espree-11.2.0.tgz", - "integrity": "sha512-7p3DrVEIopW1B1avAGLuCSh1jubc01H2JHc8B4qqGblmg5gI9yumBgACjWo4JlIc04ufug4xJ3SQI8HkS/Rgzw==", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "acorn": "^8.16.0", - "acorn-jsx": "^5.3.2", - "eslint-visitor-keys": "^5.0.1" - }, - "engines": { - "node": "^20.19.0 || ^22.13.0 || >=24" - }, - "funding": { - "url": "https://opencollective.com/eslint" - } - }, "node_modules/esprima": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", @@ -6694,19 +6742,6 @@ "node": ">=4" } }, - "node_modules/esquery": { - "version": "1.7.0", - "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.7.0.tgz", - "integrity": "sha512-Ap6G0WQwcU/LHsvLwON1fAQX9Zp0A2Y6Y/cJBl9r/JbW90Zyg4/zbG6zzKa2OTALELarYHmKu0GhpM5EO+7T0g==", - "dev": true, - "license": "BSD-3-Clause", - "dependencies": { - "estraverse": "^5.1.0" - }, - "engines": { - "node": ">=0.10" - } - }, "node_modules/esrap": { "version": "2.4.0", "resolved": "https://registry.npmjs.org/esrap/-/esrap-2.4.0.tgz", @@ -6724,39 +6759,6 @@ } } }, - "node_modules/esrecurse": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz", - "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "estraverse": "^5.2.0" - }, - "engines": { - "node": ">=4.0" - } - }, - "node_modules/estraverse": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", - "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", - "dev": true, - "license": "BSD-2-Clause", - "engines": { - "node": ">=4.0" - } - }, - "node_modules/esutils": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", - "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", - "dev": true, - "license": "BSD-2-Clause", - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/execa": { "version": "5.1.1", "resolved": "https://registry.npmjs.org/execa/-/execa-5.1.1.tgz", @@ -6809,13 +6811,6 @@ "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, - "node_modules/fast-deep-equal": { - "version": "3.1.3", - "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", - "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", - "dev": true, - "license": "MIT" - }, "node_modules/fast-json-stable-stringify": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", @@ -6823,13 +6818,6 @@ "dev": true, "license": "MIT" }, - "node_modules/fast-levenshtein": { - "version": "2.0.6", - "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", - "integrity": "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==", - "dev": true, - "license": "MIT" - }, "node_modules/fastpriorityqueue": { "version": "0.7.5", "resolved": "https://registry.npmjs.org/fastpriorityqueue/-/fastpriorityqueue-0.7.5.tgz", @@ -6864,58 +6852,12 @@ } } }, - "node_modules/file-entry-cache": { - "version": "11.1.5", - "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-11.1.5.tgz", - "integrity": "sha512-+PFTHITI08JIGhnNpGNI8T8inUpgZfk3GNEqfT9R2zZV2iFXg3CvqzSl/uEhs7TSGujYRELEANyDvS8Fj7+S7Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "flat-cache": "^6.1.23" - } - }, - "node_modules/find-up": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", - "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==", - "dev": true, - "license": "MIT", - "dependencies": { - "locate-path": "^6.0.0", - "path-exists": "^4.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/flat-cache": { - "version": "6.1.23", - "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-6.1.23.tgz", - "integrity": "sha512-f++BY9pTk+983xK1FLzlLpmM0i0z+jHmx3QESGkURMXujQZz1k5wzwX6hjnQ8goaD0B+sYnDK1yZ6MTyZfUaqA==", - "dev": true, - "license": "MIT", - "dependencies": { - "cacheable": "^2.5.0", - "flatted": "^3.4.2", - "hookified": "^1.15.0" - } - }, "node_modules/flatbuffers": { "version": "25.9.23", "resolved": "https://registry.npmjs.org/flatbuffers/-/flatbuffers-25.9.23.tgz", "integrity": "sha512-MI1qs7Lo4Syw0EOzUl0xjs2lsoeqFku44KpngfIduHBYvzm8h2+7K8YMQh1JtVVVrUvhLpNwqVi4DERegUJhPQ==", "license": "Apache-2.0" }, - "node_modules/flatted": { - "version": "3.4.4", - "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.4.4.tgz", - "integrity": "sha512-5+ybhBZANEJxaH3X5evAFatUxLfEHSr7n6kYJ+1Qd0mUqr4eu9gIf6GDbWHf8RJijHrjjO8G+la14SlL2SeS1Q==", - "dev": true, - "license": "ISC" - }, "node_modules/fraction.js": { "version": "5.3.4", "resolved": "https://registry.npmjs.org/fraction.js/-/fraction.js-5.3.4.tgz", @@ -7059,19 +7001,6 @@ "url": "https://github.com/sponsors/isaacs" } }, - "node_modules/glob-parent": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", - "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==", - "dev": true, - "license": "ISC", - "dependencies": { - "is-glob": "^4.0.3" - }, - "engines": { - "node": ">=10.13.0" - } - }, "node_modules/glob/node_modules/minimatch": { "version": "11.0.4", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.4.tgz", @@ -7106,19 +7035,6 @@ "node": ">=10.0" } }, - "node_modules/globals": { - "version": "17.14.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-17.14.0.tgz", - "integrity": "sha512-UtdkTVyAJePQv0J2M9Xe4L0ruNSDV314XiIJsADI2Zf40bcdAonE/D/OhAU8AT99oij9mhLByb+NvA3QWZYgCg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/globalthis": { "version": "1.0.4", "resolved": "https://registry.npmjs.org/globalthis/-/globalthis-1.0.4.tgz", @@ -7204,19 +7120,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/hashery": { - "version": "1.5.1", - "resolved": "https://registry.npmjs.org/hashery/-/hashery-1.5.1.tgz", - "integrity": "sha512-iZyKG96/JwPz1N55vj2Ie2vXbhu440zfUfJvSwEqEbeLluk7NnapfGqa7LH0mOsnDxTF85Mx8/dyR6HfqcbmbQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "hookified": "^1.15.0" - }, - "engines": { - "node": ">=20" - } - }, "node_modules/he": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/he/-/he-1.2.0.tgz", @@ -7227,13 +7130,6 @@ "he": "bin/he" } }, - "node_modules/hookified": { - "version": "1.15.1", - "resolved": "https://registry.npmjs.org/hookified/-/hookified-1.15.1.tgz", - "integrity": "sha512-MvG/clsADq1GPM2KGo2nyfaWVyn9naPiXrqIe4jYjXNZQt238kWyOGrsyc/DmRAQ+Re6yeo6yX/yoNCG5KAEVg==", - "dev": true, - "license": "MIT" - }, "node_modules/hsl-matcher": { "version": "1.2.4", "resolved": "https://registry.npmjs.org/hsl-matcher/-/hsl-matcher-1.2.4.tgz", @@ -7316,16 +7212,6 @@ "node": ">=0.10.0" } }, - "node_modules/ignore": { - "version": "5.3.2", - "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", - "integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 4" - } - }, "node_modules/immediate": { "version": "3.0.6", "resolved": "https://registry.npmjs.org/immediate/-/immediate-3.0.6.tgz", @@ -8224,20 +8110,6 @@ "dev": true, "license": "MIT" }, - "node_modules/json-schema-traverse": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", - "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", - "dev": true, - "license": "MIT" - }, - "node_modules/json-stable-stringify-without-jsonify": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", - "integrity": "sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==", - "dev": true, - "license": "MIT" - }, "node_modules/json-stringify-safe": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz", @@ -8270,16 +8142,6 @@ "graceful-fs": "^4.1.6" } }, - "node_modules/keyv": { - "version": "5.6.0", - "resolved": "https://registry.npmjs.org/keyv/-/keyv-5.6.0.tgz", - "integrity": "sha512-CYDD3SOtsHtyXeEORYRx2qBtpDJFjRTGXUtmNEMGyzYOKj1TE3tycdlho7kA1Ufx9OYWZzg52QFBGALTirzDSw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@keyv/serialize": "^1.1.1" - } - }, "node_modules/layerchart": { "version": "2.9.2", "resolved": "https://registry.npmjs.org/layerchart/-/layerchart-2.9.2.tgz", @@ -8332,20 +8194,6 @@ "node": ">=6" } }, - "node_modules/levn": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz", - "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "prelude-ls": "^1.2.1", - "type-check": "~0.4.0" - }, - "engines": { - "node": ">= 0.8.0" - } - }, "node_modules/lie": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/lie/-/lie-3.1.1.tgz", @@ -8650,22 +8498,6 @@ "integrity": "sha512-SW13ws7BjaeJ6p7Q6CO2nchbYEc3X3J6WrmTTDto7yMPqVSZTUyY5Tjbid+Ab8gLnATtygYtiDIJGQRRn2ZOiA==", "license": "MIT" }, - "node_modules/locate-path": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", - "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==", - "dev": true, - "license": "MIT", - "dependencies": { - "p-locate": "^5.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/lodash.memoize": { "version": "4.1.2", "resolved": "https://registry.npmjs.org/lodash.memoize/-/lodash.memoize-4.1.2.tgz", @@ -9157,22 +8989,109 @@ "integrity": "sha512-vDJMkfCfb0b1A836rgHj+ORuZf4B4+cc2bASQtpeoJLueuFc5DuYwjIZUBrSvx/fO5IrLjLz+oTrB3pcGlhovQ==", "license": "MIT" }, - "node_modules/optionator": { - "version": "0.9.4", - "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz", - "integrity": "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==", + "node_modules/oxfmt": { + "version": "0.75.0", + "resolved": "https://registry.npmjs.org/oxfmt/-/oxfmt-0.75.0.tgz", + "integrity": "sha512-/ZKvY5asfsVi9hdkOmRIumqOPu6kxlTgiJSZf54uq29kKew+Gu1FFAnEkGePyvLVW+MAYu41D6XggnzoElQzPw==", "dev": true, "license": "MIT", "dependencies": { - "deep-is": "^0.1.3", - "fast-levenshtein": "^2.0.6", - "levn": "^0.4.1", - "prelude-ls": "^1.2.1", - "type-check": "^0.4.0", - "word-wrap": "^1.2.5" + "tinypool": "2.2.0" + }, + "bin": { + "oxfmt": "bin/oxfmt" }, "engines": { - "node": ">= 0.8.0" + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/sponsors/oxc-project" + }, + "optionalDependencies": { + "@oxfmt/binding-android-arm-eabi": "0.75.0", + "@oxfmt/binding-android-arm64": "0.75.0", + "@oxfmt/binding-darwin-arm64": "0.75.0", + "@oxfmt/binding-darwin-x64": "0.75.0", + "@oxfmt/binding-freebsd-x64": "0.75.0", + "@oxfmt/binding-linux-arm-gnueabihf": "0.75.0", + "@oxfmt/binding-linux-arm-musleabihf": "0.75.0", + "@oxfmt/binding-linux-arm64-gnu": "0.75.0", + "@oxfmt/binding-linux-arm64-musl": "0.75.0", + "@oxfmt/binding-linux-ppc64-gnu": "0.75.0", + "@oxfmt/binding-linux-riscv64-gnu": "0.75.0", + "@oxfmt/binding-linux-riscv64-musl": "0.75.0", + "@oxfmt/binding-linux-s390x-gnu": "0.75.0", + "@oxfmt/binding-linux-x64-gnu": "0.75.0", + "@oxfmt/binding-linux-x64-musl": "0.75.0", + "@oxfmt/binding-openharmony-arm64": "0.75.0", + "@oxfmt/binding-win32-arm64-msvc": "0.75.0", + "@oxfmt/binding-win32-ia32-msvc": "0.75.0", + "@oxfmt/binding-win32-x64-msvc": "0.75.0" + }, + "peerDependencies": { + "@astrojs/compiler-rs": "^0.5.0", + "svelte": "^5.0.0", + "vite-plus": "*" + }, + "peerDependenciesMeta": { + "@astrojs/compiler-rs": { + "optional": true + }, + "svelte": { + "optional": true + }, + "vite-plus": { + "optional": true + } + } + }, + "node_modules/oxlint": { + "version": "1.90.0", + "resolved": "https://registry.npmjs.org/oxlint/-/oxlint-1.90.0.tgz", + "integrity": "sha512-RkTN9EmgIUpLuhNoLhO3OliMGJlvb3Dk7XVjBZnfoMCHrVpuz5ESd97klfiyYeV7XfA2lNLnDCPMkUI+Qw5How==", + "dev": true, + "license": "MIT", + "bin": { + "oxlint": "bin/oxlint" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/sponsors/oxc-project" + }, + "optionalDependencies": { + "@oxlint/binding-android-arm-eabi": "1.90.0", + "@oxlint/binding-android-arm64": "1.90.0", + "@oxlint/binding-darwin-arm64": "1.90.0", + "@oxlint/binding-darwin-x64": "1.90.0", + "@oxlint/binding-freebsd-x64": "1.90.0", + "@oxlint/binding-linux-arm-gnueabihf": "1.90.0", + "@oxlint/binding-linux-arm-musleabihf": "1.90.0", + "@oxlint/binding-linux-arm64-gnu": "1.90.0", + "@oxlint/binding-linux-arm64-musl": "1.90.0", + "@oxlint/binding-linux-ppc64-gnu": "1.90.0", + "@oxlint/binding-linux-riscv64-gnu": "1.90.0", + "@oxlint/binding-linux-riscv64-musl": "1.90.0", + "@oxlint/binding-linux-s390x-gnu": "1.90.0", + "@oxlint/binding-linux-x64-gnu": "1.90.0", + "@oxlint/binding-linux-x64-musl": "1.90.0", + "@oxlint/binding-openharmony-arm64": "1.90.0", + "@oxlint/binding-win32-arm64-msvc": "1.90.0", + "@oxlint/binding-win32-ia32-msvc": "1.90.0", + "@oxlint/binding-win32-x64-msvc": "1.90.0" + }, + "peerDependencies": { + "oxlint-tsgolint": ">=7.0.2005", + "vite-plus": "*" + }, + "peerDependenciesMeta": { + "oxlint-tsgolint": { + "optional": true + }, + "vite-plus": { + "optional": true + } } }, "node_modules/p-limit": { @@ -9191,22 +9110,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/p-locate": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz", - "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==", - "dev": true, - "license": "MIT", - "dependencies": { - "p-limit": "^3.0.2" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/p-try": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", @@ -9469,32 +9372,6 @@ "node": "^10 || ^12 || >=14" } }, - "node_modules/prelude-ls": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", - "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.8.0" - } - }, - "node_modules/prettier": { - "version": "3.9.10", - "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.9.10.tgz", - "integrity": "sha512-skGHTH1Yb9QvaTC4hWnRTzEYtCpApF0UMBPz+t/0ZPzP8ihefo/btKd+QA7pUE0fEwA1SbS/NmhyEcstdXOIdA==", - "dev": true, - "license": "MIT", - "bin": { - "prettier": "bin/prettier.cjs" - }, - "engines": { - "node": ">=14" - }, - "funding": { - "url": "https://github.com/prettier/prettier?sponsor=1" - } - }, "node_modules/pretty-format": { "version": "30.5.1", "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-30.5.1.tgz", @@ -9592,26 +9469,6 @@ ], "license": "MIT" }, - "node_modules/qified": { - "version": "0.10.1", - "resolved": "https://registry.npmjs.org/qified/-/qified-0.10.1.tgz", - "integrity": "sha512-+Owyggi9IxT1ePKGafcI87ubSmxol6smwJ+RAHDQlx9+9cPwFWDiKFFCPuWhr9ignlGpZ9vDQLw67N4dcTVFEA==", - "dev": true, - "license": "MIT", - "dependencies": { - "hookified": "^2.1.1" - }, - "engines": { - "node": ">=20" - } - }, - "node_modules/qified/node_modules/hookified": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/hookified/-/hookified-2.2.0.tgz", - "integrity": "sha512-p/LgFzRN5FeoD3DLS6bkUapeye6E4SI6yJs6KetENd18S+FBthqYq2amJUWpt5z0EQwwHemidjY5OqJGEKm5uA==", - "dev": true, - "license": "MIT" - }, "node_modules/qrcode": { "version": "1.5.4", "resolved": "https://registry.npmjs.org/qrcode/-/qrcode-1.5.4.tgz", @@ -10470,6 +10327,16 @@ "url": "https://github.com/sponsors/SuperchupuDev" } }, + "node_modules/tinypool": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/tinypool/-/tinypool-2.2.0.tgz", + "integrity": "sha512-jBrmx4lYmaC9k/mgPbylxs7kBUxHtD8256up+HjLaDFfXScKJQyil+SWXSvhAtT7XHo+yTVlpB81PGmHP8oLSQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^20.0.0 || >=22.0.0" + } + }, "node_modules/tldts": { "version": "6.1.86", "resolved": "https://registry.npmjs.org/tldts/-/tldts-6.1.86.tgz", @@ -10516,19 +10383,6 @@ "node": ">=18" } }, - "node_modules/ts-api-utils": { - "version": "2.5.0", - "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.5.0.tgz", - "integrity": "sha512-OJ/ibxhPlqrMM0UiNHJ/0CKQkoKF243/AEmplt3qpRgkW8VG7IfOS41h7V8TjITqdByHzrjcS/2si+y4lIh8NA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18.12" - }, - "peerDependencies": { - "typescript": ">=4.8.4" - } - }, "node_modules/ts-jest": { "version": "29.4.15", "resolved": "https://registry.npmjs.org/ts-jest/-/ts-jest-29.4.15.tgz", @@ -10601,19 +10455,6 @@ "integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==", "license": "0BSD" }, - "node_modules/type-check": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", - "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==", - "dev": true, - "license": "MIT", - "dependencies": { - "prelude-ls": "^1.2.1" - }, - "engines": { - "node": ">= 0.8.0" - } - }, "node_modules/type-detect": { "version": "4.0.8", "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz", @@ -10660,30 +10501,6 @@ "node": ">=14.17" } }, - "node_modules/typescript-eslint": { - "version": "8.72.1", - "resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.72.1.tgz", - "integrity": "sha512-3Li9FfPmQp45nxEtFD1ZCrYFI3cYK5kpyNtmm1H7lMagm8u9sy6PTjy3ytwQZs7KNukOyKFHAZ6z6GjYFeaeXw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@typescript-eslint/eslint-plugin": "8.72.1", - "@typescript-eslint/parser": "8.72.1", - "@typescript-eslint/typescript-estree": "8.72.1", - "@typescript-eslint/utils": "8.72.1" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", - "typescript": ">=4.8.4 <6.1.0" - } - }, "node_modules/uglify-js": { "version": "3.19.3", "resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-3.19.3.tgz", @@ -10781,16 +10598,6 @@ "browserslist": ">= 4.21.0" } }, - "node_modules/uri-js": { - "version": "4.4.1", - "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", - "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "punycode": "^2.1.0" - } - }, "node_modules/v8-to-istanbul": { "version": "9.3.0", "resolved": "https://registry.npmjs.org/v8-to-istanbul/-/v8-to-istanbul-9.3.0.tgz", @@ -11266,16 +11073,6 @@ "integrity": "sha512-iBdZ57RDvnOR9AGBhML2vFZf7h8vmBjhoaZqODJBFWHVtKkDmKuHai3cx5PgVMrX5YDNp27AofYbAwctSS+vhQ==", "license": "ISC" }, - "node_modules/word-wrap": { - "version": "1.2.5", - "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz", - "integrity": "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/wordwrap": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-1.0.0.tgz", diff --git a/package.json b/package.json index 5a02ed75..0734e168 100644 --- a/package.json +++ b/package.json @@ -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, diff --git a/scripts/analyze-trace.mjs b/scripts/analyze-trace.mjs index 1c3bc00e..3c6c39ae 100644 --- a/scripts/analyze-trace.mjs +++ b/scripts/analyze-trace.mjs @@ -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,39 +138,57 @@ function top(map, n = 40, minCount = 1) { const traceDurationMs = ((maxTs - minTs) / 1000).toFixed(0); -console.log(JSON.stringify({ - summary: { - traceDurationMs, - eventCount: traceEvents.length, - layoutCount: layoutEvents.length, - layoutTotalMs: (layoutEvents.reduce((s, e) => s + e.dur, 0) / 1000).toFixed(1), - paintCount: paintEvents.length, - paintTotalMs: (paintEvents.reduce((s, e) => s + e.dur, 0) / 1000).toFixed(1), - longTaskCount: longTasks.length, - longTaskTotalMs: (longTasks.reduce((s, e) => s + e.dur, 0) / 1000).toFixed(1), - timerCount: timers.length, - timerTotalMs: (timers.reduce((s, e) => s + e.dur, 0) / 1000).toFixed(1), - observerCount: observers.length, - observerTotalMs: (observers.reduce((s, e) => s + e.dur, 0) / 1000).toFixed(1), - hitTestCount: hitTests.length, - hitTestTotalMs: (hitTests.reduce((s, e) => s + e.dur, 0) / 1000).toFixed(1), - gcCount: gcEvents.length, - gcTotalMs: (gcEvents.reduce((s, e) => s + e.dur, 0) / 1000).toFixed(1), - }, - topEventNames: top(byName, 50), - topCategories: top(byCat, 30), - topUrls: top(byUrl, 40), - topFunctions: top(byFunction, 40, 1), - topBetterseqta: top(betterseqtaHits, 50), - topLongTasks: longTasks.sort((a, b) => b.dur - a.dur).slice(0, 20).map(e => ({ - ms: (e.dur / 1000).toFixed(1), - cat: e.cat, - args: e.args, - })), - topLayout: layoutEvents.sort((a, b) => b.dur - a.dur).slice(0, 15).map(e => ({ - name: e.name, ms: (e.dur / 1000).toFixed(2), - })), - topObservers: observers.sort((a, b) => b.dur - a.dur).slice(0, 15).map(e => ({ - name: e.name, ms: (e.dur / 1000).toFixed(2), count: 1, - })), -}, null, 2)); +console.log( + JSON.stringify( + { + summary: { + traceDurationMs, + eventCount: traceEvents.length, + layoutCount: layoutEvents.length, + layoutTotalMs: (layoutEvents.reduce((s, e) => s + e.dur, 0) / 1000).toFixed(1), + paintCount: paintEvents.length, + paintTotalMs: (paintEvents.reduce((s, e) => s + e.dur, 0) / 1000).toFixed(1), + longTaskCount: longTasks.length, + longTaskTotalMs: (longTasks.reduce((s, e) => s + e.dur, 0) / 1000).toFixed(1), + timerCount: timers.length, + timerTotalMs: (timers.reduce((s, e) => s + e.dur, 0) / 1000).toFixed(1), + observerCount: observers.length, + observerTotalMs: (observers.reduce((s, e) => s + e.dur, 0) / 1000).toFixed(1), + hitTestCount: hitTests.length, + hitTestTotalMs: (hitTests.reduce((s, e) => s + e.dur, 0) / 1000).toFixed(1), + gcCount: gcEvents.length, + gcTotalMs: (gcEvents.reduce((s, e) => s + e.dur, 0) / 1000).toFixed(1), + }, + topEventNames: top(byName, 50), + topCategories: top(byCat, 30), + topUrls: top(byUrl, 40), + topFunctions: top(byFunction, 40, 1), + topBetterseqta: top(betterseqtaHits, 50), + topLongTasks: longTasks + .sort((a, b) => b.dur - a.dur) + .slice(0, 20) + .map((e) => ({ + ms: (e.dur / 1000).toFixed(1), + cat: e.cat, + args: e.args, + })), + topLayout: layoutEvents + .sort((a, b) => b.dur - a.dur) + .slice(0, 15) + .map((e) => ({ + name: e.name, + ms: (e.dur / 1000).toFixed(2), + })), + topObservers: observers + .sort((a, b) => b.dur - a.dur) + .slice(0, 15) + .map((e) => ({ + name: e.name, + ms: (e.dur / 1000).toFixed(2), + count: 1, + })), + }, + null, + 2, + ), +); diff --git a/scripts/compile-layerchart-vendor.mjs b/scripts/compile-layerchart-vendor.mjs index c3f84ea2..c35292cd 100644 --- a/scripts/compile-layerchart-vendor.mjs +++ b/scripts/compile-layerchart-vendor.mjs @@ -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")); diff --git a/scripts/smoke-test.mjs b/scripts/smoke-test.mjs index a19d3e16..de97815e 100644 --- a/scripts/smoke-test.mjs +++ b/scripts/smoke-test.mjs @@ -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)) { diff --git a/src/SEQTA.boot.test.ts b/src/SEQTA.boot.test.ts index fbeb84bf..1960d932 100644 --- a/src/SEQTA.boot.test.ts +++ b/src/SEQTA.boot.test.ts @@ -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"); }, ); diff --git a/src/SEQTA.ts b/src/SEQTA.ts index 8537ba6a..848cf5ed 100644 --- a/src/SEQTA.ts +++ b/src/SEQTA.ts @@ -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,13 +205,11 @@ async function bootErrorPage() { } function replaceIcons() { - document - .querySelectorAll('link[rel*="icon"]') - .forEach((link) => { - if (link.href !== icon48) { - link.href = icon48; - } - }); + document.querySelectorAll('link[rel*="icon"]').forEach((link) => { + if (link.href !== icon48) { + link.href = icon48; + } + }); } /** Vite/CRX HMR can leave modules with missing named exports until the graph is cleared. */ diff --git a/src/background/calendarBackground.ts b/src/background/calendarBackground.ts index 0ffcecf9..2ea1e267 100644 --- a/src/background/calendarBackground.ts +++ b/src/background/calendarBackground.ts @@ -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 { +async function getValidStoredAccessToken(provider: CalendarProviderBackend): Promise { 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 { - 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 { }; } -async function connectCalendar(provider: CalendarProviderBackend): Promise { +async function connectCalendar( + provider: CalendarProviderBackend, +): Promise { if (!provider.isConfigured()) { return { success: false, configured: false, error: provider.notConfiguredError }; } @@ -383,8 +390,7 @@ async function connectCalendar(provider: CalendarProviderBackend): Promise getValidStoredAccessToken(provider).then((accessToken) => ({ success: true, accessToken })), + () => + getValidStoredAccessToken(provider).then((accessToken) => ({ success: true, accessToken })), (err) => ({ success: false, error: errMsg(err, "Token refresh failed") }), ); } @@ -476,33 +483,45 @@ export function registerGoogleCalendarMessageHandlers( ): void { registerProviderHandlers(handlers, isTrustedSender, GOOGLE_BACKEND, getGoogleCalendarStatus); - registerTrustedAsyncHandler(handlers, isTrustedSender, "googleCalendarEnsureWeeklyAlarm", async () => { - await ensureWeeklySyncAlarm(); - return { success: true }; - }, (err) => ({ - success: false, - error: err instanceof Error ? err.message : "Could not schedule weekly sync", - })); + registerTrustedAsyncHandler( + handlers, + isTrustedSender, + "googleCalendarEnsureWeeklyAlarm", + async () => { + await ensureWeeklySyncAlarm(); + return { success: true }; + }, + (err) => ({ + success: false, + error: err instanceof Error ? err.message : "Could not schedule weekly sync", + }), + ); - registerTrustedAsyncHandler(handlers, isTrustedSender, "googleCalendarUpdateSyncSettings", async (request) => { - const body = request as { - syncWeeksAhead?: number; - autoSyncWeekly?: boolean; - syncAssessmentDueDates?: boolean; - }; - const patch: Record = {}; - if (body.syncWeeksAhead != null) patch.syncWeeksAhead = clampSyncWeeks(body.syncWeeksAhead); - if (body.autoSyncWeekly != null) patch.autoSyncWeekly = !!body.autoSyncWeekly; - if (body.syncAssessmentDueDates != null) { - patch.syncAssessmentDueDates = !!body.syncAssessmentDueDates; - } - if (Object.keys(patch).length > 0) await writeSharedCalendarSyncSettings(patch); - await ensureWeeklySyncAlarm(); - return { success: true, ...(await getGoogleCalendarStatus()) }; - }, (err) => ({ - success: false, - error: err instanceof Error ? err.message : "Could not update sync settings", - })); + registerTrustedAsyncHandler( + handlers, + isTrustedSender, + "googleCalendarUpdateSyncSettings", + async (request) => { + const body = request as { + syncWeeksAhead?: number; + autoSyncWeekly?: boolean; + syncAssessmentDueDates?: boolean; + }; + const patch: Record = {}; + if (body.syncWeeksAhead != null) patch.syncWeeksAhead = clampSyncWeeks(body.syncWeeksAhead); + if (body.autoSyncWeekly != null) patch.autoSyncWeekly = !!body.autoSyncWeekly; + if (body.syncAssessmentDueDates != null) { + patch.syncAssessmentDueDates = !!body.syncAssessmentDueDates; + } + if (Object.keys(patch).length > 0) await writeSharedCalendarSyncSettings(patch); + await ensureWeeklySyncAlarm(); + return { success: true, ...(await getGoogleCalendarStatus()) }; + }, + (err) => ({ + success: false, + error: err instanceof Error ? err.message : "Could not update sync settings", + }), + ); } export function registerOutlookCalendarMessageHandlers( diff --git a/src/background/cloudSettingsAutoSync.ts b/src/background/cloudSettingsAutoSync.ts index 4ba40d8d..6e3206fb 100644 --- a/src/background/cloudSettingsAutoSync.ts +++ b/src/background/cloudSettingsAutoSync.ts @@ -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 { +async function fetchCloudSummaryWithAuthRetry(token: string): Promise { let t = token; for (let attempt = 0; attempt < 2; attempt++) { const res = await fetchCloudSummaryOnce(t); @@ -355,9 +352,7 @@ async function runCloudSettingsPollInner(): Promise { 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(); } - diff --git a/src/background/customThemesHandlers.ts b/src/background/customThemesHandlers.ts index 47291d3d..71251537 100644 --- a/src/background/customThemesHandlers.ts +++ b/src/background/customThemesHandlers.ts @@ -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({ diff --git a/src/background/news.ts b/src/background/news.ts index f5c7a71d..18b8dac1 100644 --- a/src/background/news.ts +++ b/src/background/news.ts @@ -10,10 +10,7 @@ const rssFeedsByCountry: Record = { "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 = { "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", diff --git a/src/background/remoteConfig.ts b/src/background/remoteConfig.ts index 344b181d..86708518 100644 --- a/src/background/remoteConfig.ts +++ b/src/background/remoteConfig.ts @@ -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 { BS_STATUS_MANIFEST_URL.replace(/manifest\.json$/, "") || "https://raw.githubusercontent.com/BetterSEQTA/BS-Status/main/config/"; const files: Record = {}; - for (const [key, fileName] of Object.entries( - manifest.files as Record, - )) { + for (const [key, fileName] of Object.entries(manifest.files as Record)) { 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 { } } -async function registerInstall( - apiBase: string, - primaryOk: boolean, - force = false, -): Promise { +async function registerInstall(apiBase: string, primaryOk: boolean, force = false): Promise { 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 boolean> { function handleRefresh(_req: unknown, sendResponse: MessageSender): boolean { void refreshRemoteConfig(apiBase) .then((res) => sendResponse(res)) @@ -275,15 +265,11 @@ 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) => { - sendResponse({ - snapshot: normalizeRemoteConfigSnapshot( - stored[BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY], - ), - }); + void browser.storage.local.get(BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY).then((stored) => { + sendResponse({ + 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)) { diff --git a/src/background/searchThemeStockPhotos.ts b/src/background/searchThemeStockPhotos.ts index 08917489..7c4e2003 100644 --- a/src/background/searchThemeStockPhotos.ts +++ b/src/background/searchThemeStockPhotos.ts @@ -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 }; + query?: { + pages?: Record< + string, + { title?: string; imageinfo?: { thumburl?: string; url?: string }[] } + >; + }; }; const pages = json.query?.pages ?? {}; const results: StockPhotoResult[] = Object.values(pages) diff --git a/src/config/outlookCalendar.ts b/src/config/outlookCalendar.ts index 52d959aa..8e60755c 100644 --- a/src/config/outlookCalendar.ts +++ b/src/config/outlookCalendar.ts @@ -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"; diff --git a/src/css/injected.scss b/src/css/injected.scss index 58199a90..ebd39bf9 100644 --- a/src/css/injected.scss +++ b/src/css/injected.scss @@ -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: diff --git a/src/css/injected/sidebar-animation.scss b/src/css/injected/sidebar-animation.scss index 3d6e53ff..f3dc6cba 100644 --- a/src/css/injected/sidebar-animation.scss +++ b/src/css/injected/sidebar-animation.scss @@ -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; } diff --git a/src/interface/components/SidebarNav.svelte b/src/interface/components/SidebarNav.svelte index d4ff71fb..76a77c51 100644 --- a/src/interface/components/SidebarNav.svelte +++ b/src/interface/components/SidebarNav.svelte @@ -43,9 +43,9 @@ const scheduleIndicator = rafThrottle(updateIndicator); $effect(() => { - selectedId; - groups; - trackEl; + void selectedId; + void groups; + void trackEl; scheduleIndicator(); }); diff --git a/src/interface/components/colourPicker/colourValue.test.ts b/src/interface/components/colourPicker/colourValue.test.ts index 660d1f17..4b2036f9 100644 --- a/src/interface/components/colourPicker/colourValue.test.ts +++ b/src/interface/components/colourPicker/colourValue.test.ts @@ -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"); }); }); diff --git a/src/interface/components/colourPicker/colourValue.ts b/src/interface/components/colourPicker/colourValue.ts index df446b68..c50ee78a 100644 --- a/src/interface/components/colourPicker/colourValue.ts +++ b/src/interface/components/colourPicker/colourValue.ts @@ -23,7 +23,8 @@ const SIDE_ANGLES: Record = { "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)})`; } diff --git a/src/interface/components/fontPickerModal.css b/src/interface/components/fontPickerModal.css index 6633c924..a21525b3 100644 --- a/src/interface/components/fontPickerModal.css +++ b/src/interface/components/fontPickerModal.css @@ -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); } diff --git a/src/interface/components/themes/BackgroundSelector.svelte b/src/interface/components/themes/BackgroundSelector.svelte index 5f931d36..0fa4f3e2 100644 --- a/src/interface/components/themes/BackgroundSelector.svelte +++ b/src/interface/components/themes/BackgroundSelector.svelte @@ -128,7 +128,7 @@ $effect(() => { loadBackground(); - selectedBackground + void selectedBackground; }); onMount(() => { diff --git a/src/interface/hooks/BackgroundDataLoader.ts b/src/interface/hooks/BackgroundDataLoader.ts index ebb99155..7c069657 100644 --- a/src/interface/hooks/BackgroundDataLoader.ts +++ b/src/interface/hooks/BackgroundDataLoader.ts @@ -46,11 +46,7 @@ export async function readAllData(): Promise { return items; } -export async function writeData( - id: string, - type: string, - blob: Blob, -): Promise { +export async function writeData(id: string, type: string, blob: Blob): Promise { const record = { id, type, blob }; const db = await openDatabase(); const tx = db.transaction(STORE, "readwrite"); @@ -79,9 +75,7 @@ export async function clearAllData(): Promise { await txDone(tx); } -export async function getDataById( - id: string, -): Promise { +export async function getDataById(id: string): Promise { 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 { +export async function hasEnoughStorageSpace(requiredSpace: number): Promise { if (!("storage" in navigator) || !navigator.storage.estimate) return true; const { quota, usage } = await navigator.storage.estimate(); return quota == null || usage == null || quota - usage > requiredSpace; diff --git a/src/interface/hooks/communityThemesState.svelte.ts b/src/interface/hooks/communityThemesState.svelte.ts index 6aedd784..771ba533 100644 --- a/src/interface/hooks/communityThemesState.svelte.ts +++ b/src/interface/hooks/communityThemesState.svelte.ts @@ -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(); }); diff --git a/src/interface/index.ts b/src/interface/index.ts index 659da55d..84cfb56c 100644 --- a/src/interface/index.ts +++ b/src/interface/index.ts @@ -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(); diff --git a/src/interface/main.ts b/src/interface/main.ts index 8283e102..f7300e7f 100644 --- a/src/interface/main.ts +++ b/src/interface/main.ts @@ -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, { diff --git a/src/interface/pages/settings/pluginSettingsState.svelte.ts b/src/interface/pages/settings/pluginSettingsState.svelte.ts index 85499b6d..271a08ef 100644 --- a/src/interface/pages/settings/pluginSettingsState.svelte.ts +++ b/src/interface/pages/settings/pluginSettingsState.svelte.ts @@ -59,8 +59,7 @@ class PluginSettingsStore { private async load(): Promise { 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) { diff --git a/src/interface/pages/settings/shared.ts b/src/interface/pages/settings/shared.ts index bc6522f9..8da259b2 100644 --- a/src/interface/pages/settings/shared.ts +++ b/src/interface/pages/settings/shared.ts @@ -23,10 +23,7 @@ export type SettingsSectionSharedProps = { searchQuery?: string; }; -export function matchesSearch( - searchQuery: string, - ...parts: Array -): boolean { +export function matchesSearch(searchQuery: string, ...parts: Array): boolean { const q = searchQuery.trim().toLowerCase(); return !q || parts.some((part) => part?.toLowerCase().includes(q)); } diff --git a/src/interface/pages/store.svelte b/src/interface/pages/store.svelte index 6126d1d8..bc7bb588 100644 --- a/src/interface/pages/store.svelte +++ b/src/interface/pages/store.svelte @@ -243,7 +243,7 @@ $effect(() => { loadBackground(); - selectedBackground + void selectedBackground; }); $effect(() => { diff --git a/src/interface/utils/portal.ts b/src/interface/utils/portal.ts index 6124639e..fa9d038d 100644 --- a/src/interface/utils/portal.ts +++ b/src/interface/utils/portal.ts @@ -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 = ( - node, - target, -) => { +export const portal: Action = (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() { diff --git a/src/interface/utils/syncPageTheme.ts b/src/interface/utils/syncPageTheme.ts index 77612741..786c32a2 100644 --- a/src/interface/utils/syncPageTheme.ts +++ b/src/interface/utils/syncPageTheme.ts @@ -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")); } diff --git a/src/interface/utils/themeBuilderDraft.test.ts b/src/interface/utils/themeBuilderDraft.test.ts index fbec79e0..9fd5d344 100644 --- a/src/interface/utils/themeBuilderDraft.test.ts +++ b/src/interface/utils/themeBuilderDraft.test.ts @@ -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", + ); }); }); diff --git a/src/interface/utils/themeBuilderDraft.ts b/src/interface/utils/themeBuilderDraft.ts index 783f1a72..32538c28 100644 --- a/src/interface/utils/themeBuilderDraft.ts +++ b/src/interface/utils/themeBuilderDraft.ts @@ -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, diff --git a/src/interface/utils/themeImageHandlers.ts b/src/interface/utils/themeImageHandlers.ts index b67b131e..8338d395 100644 --- a/src/interface/utils/themeImageHandlers.ts +++ b/src/interface/utils/themeImageHandlers.ts @@ -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), diff --git a/src/interface/utils/themeListFilters.test.ts b/src/interface/utils/themeListFilters.test.ts index fb7b8fab..7ed6c450 100644 --- a/src/interface/utils/themeListFilters.test.ts +++ b/src/interface/utils/themeListFilters.test.ts @@ -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 & Pick): CustomTheme { +function makeCustomTheme( + overrides: Partial & Pick, +): 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 & Pick & Pick): Theme { +function makeStoreTheme(overrides: Partial & Pick): 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"); }); }); diff --git a/src/interface/utils/themeListFilters.ts b/src/interface/utils/themeListFilters.ts index 6b8ee359..a377c60a 100644 --- a/src/interface/utils/themeListFilters.ts +++ b/src/interface/utils/themeListFilters.ts @@ -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 | null, + existing: Pick | 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};`, diff --git a/src/interface/utils/themePlaceholderCover.test.ts b/src/interface/utils/themePlaceholderCover.test.ts index 85f6f318..12169313 100644 --- a/src/interface/utils/themePlaceholderCover.test.ts +++ b/src/interface/utils/themePlaceholderCover.test.ts @@ -1,7 +1,4 @@ -import { - createDefaultThemeCoverSvg, - defaultThemeCoverDataUrl, -} from "./themePlaceholderCover"; +import { createDefaultThemeCoverSvg, defaultThemeCoverDataUrl } from "./themePlaceholderCover"; describe("themePlaceholderCover", () => { it("builds an svg cover placeholder", () => { diff --git a/src/interface/utils/themeStoreFlavours.ts b/src/interface/utils/themeStoreFlavours.ts index 1dfa7767..2d3f6610 100644 --- a/src/interface/utils/themeStoreFlavours.ts +++ b/src/interface/utils/themeStoreFlavours.ts @@ -7,24 +7,22 @@ export function isHiddenStoreTheme(theme: Theme): boolean { /** Coerce API / fallback rows into the store `Theme` shape (camelCase images, safe strings). */ export function normalizeStoreTheme(raw: Record): Theme { const flavours = Array.isArray(raw.flavours) - ? (raw.flavours as Record[]).map( - (f): ThemeFlavour => ({ - id: String(f.id ?? ""), - name: String(f.name ?? ""), - accent_color: String(f.accent_color ?? f.accentColor ?? ""), - cover_image: String(f.cover_image ?? f.coverImage ?? ""), - marquee_image: - typeof (f.marquee_image ?? f.marqueeImage) === "string" - ? String(f.marquee_image ?? f.marqueeImage) + ? (raw.flavours as Record[]).map((f): ThemeFlavour => ({ + id: String(f.id ?? ""), + name: String(f.name ?? ""), + accent_color: String(f.accent_color ?? f.accentColor ?? ""), + cover_image: String(f.cover_image ?? f.coverImage ?? ""), + marquee_image: + typeof (f.marquee_image ?? f.marqueeImage) === "string" + ? String(f.marquee_image ?? f.marqueeImage) + : undefined, + download_count: + typeof f.download_count === "number" + ? f.download_count + : typeof f.downloadCount === "number" + ? f.downloadCount : undefined, - download_count: - typeof f.download_count === "number" - ? f.download_count - : typeof f.downloadCount === "number" - ? f.downloadCount - : undefined, - }), - ) + })) : undefined; return { diff --git a/src/lib/extensionAssetUrl.test.ts b/src/lib/extensionAssetUrl.test.ts index 910de7b1..98f2dbf4 100644 --- a/src/lib/extensionAssetUrl.test.ts +++ b/src/lib/extensionAssetUrl.test.ts @@ -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", ); diff --git a/src/lib/extensionAssetUrl.ts b/src/lib/extensionAssetUrl.ts index ebf0dbe1..c7a1a7a4 100644 --- a/src/lib/extensionAssetUrl.ts +++ b/src/lib/extensionAssetUrl.ts @@ -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(/^\/+/, "")); } - diff --git a/src/lib/icons/lucideMoon.ts b/src/lib/icons/lucideMoon.ts index c1040780..6303a4b8 100644 --- a/src/lib/icons/lucideMoon.ts +++ b/src/lib/icons/lucideMoon.ts @@ -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 = - ``; +export const LUCIDE_MOON_ICON_SVG = ``; diff --git a/src/lib/icons/lucideSun.ts b/src/lib/icons/lucideSun.ts index 543731e5..16542ccf 100644 --- a/src/lib/icons/lucideSun.ts +++ b/src/lib/icons/lucideSun.ts @@ -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 = - ``; +export const LUCIDE_SUN_ICON_SVG = ``; diff --git a/src/lib/transformersExtension.ts b/src/lib/transformersExtension.ts index f0a7945e..44d1847e 100644 --- a/src/lib/transformersExtension.ts +++ b/src/lib/transformersExtension.ts @@ -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 { +export async function ensureTransformersEnv(ortWasmBase?: string): Promise { 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 { +export async function configureTransformersEnvForBase(ortWasmBase: string): Promise { configured = false; await ensureTransformersEnv(ortWasmBase); } diff --git a/src/manifests/safari.ts b/src/manifests/safari.ts index 9d702f55..134b4b56 100644 --- a/src/manifests/safari.ts +++ b/src/manifests/safari.ts @@ -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["browser_specific_settings"]; +type BrowserSpecificSettings = Extract< + Manifest, + { manifest_version: number } +>["browser_specific_settings"]; const safariSettings = { safari: { diff --git a/src/pageState.js b/src/pageState.js index cdd8703d..2b158e8d 100644 --- a/src/pageState.js +++ b/src/pageState.js @@ -10,7 +10,7 @@ class ReactFiber { console.log("Selected Nodes:", this.nodes); console.log("🔍 Found Fibers:", this.fibers); console.log("🛠 Found Components:", this.components); - + this.fibers.forEach((fiber, index) => { if (fiber) { console.log(`Fiber ${index}:`, { @@ -19,7 +19,7 @@ class ReactFiber { elementType: fiber.elementType, stateNode: fiber.stateNode, hasState: !!fiber.stateNode?.state, - hasMemoizedState: !!fiber.memoizedState + hasMemoizedState: !!fiber.memoizedState, }); } }); @@ -32,25 +32,25 @@ class ReactFiber { getFiberNode(node) { if (!node) return null; - + // 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) { if (node[key]) return node[key]; } - + const fiberKey = Object.getOwnPropertyNames(node).find( (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,21 +80,21 @@ class ReactFiber { current.alternate.expirationTime = 1; } current.expirationTime = 1; - } + }, }; } } - + // Legacy fallback: check if stateNode has React component methods if ( current.stateNode && current.stateNode !== null && - typeof current.stateNode === 'object' && + typeof current.stateNode === "object" && (current.stateNode.setState || current.stateNode.forceUpdate) ) { return current.stateNode; } - + current = current.return; } return null; @@ -100,11 +102,11 @@ class ReactFiber { getState(key) { if (!this.components.length && !this.fibers.length) return null; - + const component = this.components[0]; const fiber = this.fibers[0]; let state = null; - + if (component?.state) { state = component.state; } @@ -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; } @@ -144,33 +146,34 @@ class ReactFiber { let mainStateFound = false; let currentHook = hookChain; let hookIndex = 0; - + if (this.debug) { console.log("🔍 Hook chain analysis:"); } - + 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, }); } - + // Try different approaches to extract state if (currentHook.memoizedState !== undefined && currentHook.memoizedState !== null) { const state = currentHook.memoizedState; - + // Priority 1: Check for useRef hooks with complex state in .current - if (!currentHook.queue && - typeof state === 'object' && - state !== null && - state.current !== undefined && - typeof state.current === 'object' && - state.current !== null) { - + if ( + !currentHook.queue && + typeof state === "object" && + state !== null && + state.current !== undefined && + 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,77 +201,78 @@ 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); } } - + currentHook = currentHook.next; hookIndex++; } - + if (this.debug) { console.log(`🎯 Extracted ${states.length} state values:`, states); } - + // 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) { // If we have multiple main state objects, find the most comprehensive one // or merge them if they seem complementary const largestState = mainStates.reduce((largest, current) => { const largestKeys = Object.keys(largest).length; const currentKeys = Object.keys(current).length; - + // Prefer the one with more properties if (currentKeys > largestKeys) return current; - + // If same number of properties, prefer the one with more complex data if (currentKeys === largestKeys) { const largestComplexity = this.calculateStateComplexity(largest); const currentComplexity = this.calculateStateComplexity(current); return currentComplexity > largestComplexity ? current : largest; } - + return largest; }); - + 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]; } - + return mainStates; } - + return states; } 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 } } - + return complexity; } @@ -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(); } @@ -335,11 +344,11 @@ function makeSerializable(obj, visited = new WeakSet(), depth = 0, maxDepth = 10 if (obj === null || obj === undefined) { return obj; } - + if (typeof obj === "function") { - return `[Function: ${obj.name || 'anonymous'}]`; + return `[Function: ${obj.name || "anonymous"}]`; } - + if (typeof obj !== "object") { if (typeof obj === "symbol") return obj.toString(); if (typeof obj === "bigint") return obj.toString() + "n"; @@ -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, }; } @@ -408,32 +422,54 @@ 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 { return false; } }); - + // Limit number of properties to avoid huge objects const maxKeys = 30; const processedKeys = ownKeys.slice(0, maxKeys); - + 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)) { serializableObj[key] = `[Skipped: ${key}]`; continue; @@ -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); } @@ -462,9 +497,9 @@ function makeSerializable(obj, visited = new WeakSet(), depth = 0, maxDepth = 10 serializableObj[key] = `[Error: ${error.message}]`; } } - + if (ownKeys.length > maxKeys) { - serializableObj['...'] = `[${ownKeys.length - maxKeys} more properties]`; + serializableObj["..."] = `[${ownKeys.length - maxKeys} more properties]`; } return serializableObj; @@ -480,14 +515,14 @@ function deepFunctionCheck(obj, path = "") { if (typeof obj === "function") { throw new Error(`Found function at path: ${path}`); } - + if (obj && typeof obj === "object") { if (Array.isArray(obj)) { obj.forEach((item, index) => { deepFunctionCheck(item, `${path}[${index}]`); }); } else { - Object.keys(obj).forEach(key => { + Object.keys(obj).forEach((key) => { deepFunctionCheck(obj[key], path ? `${path}.${key}` : key); }); } diff --git a/src/plugins/built-in/animatedBackground/index.ts b/src/plugins/built-in/animatedBackground/index.ts index 67ee6add..27e44966 100644 --- a/src/plugins/built-in/animatedBackground/index.ts +++ b/src/plugins/built-in/animatedBackground/index.ts @@ -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, diff --git a/src/plugins/built-in/appIcons/index.ts b/src/plugins/built-in/appIcons/index.ts index 28e4ef21..df1fdc65 100644 --- a/src/plugins/built-in/appIcons/index.ts +++ b/src/plugins/built-in/appIcons/index.ts @@ -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'; diff --git a/src/plugins/built-in/assessmentsAverage/engage.ts b/src/plugins/built-in/assessmentsAverage/engage.ts index cb06b22d..2cd41e20 100644 --- a/src/plugins/built-in/assessmentsAverage/engage.ts +++ b/src/plugins/built-in/assessmentsAverage/engage.ts @@ -9,25 +9,20 @@ export async function requestEngageAssessmentPdf(params: { }): Promise { const fileName = randomPdfFileName(); - const response = await fetch( - `${location.origin}/seqta/parent/print/assessment?${Date.now()}`, - { - method: "POST", - headers: { "Content-Type": "application/json; charset=utf-8" }, - credentials: "include", - body: JSON.stringify({ - id: params.assessmentID, - metaclass: params.metaclassID, - student: Number(params.studentID), - fileName, - }), - }, - ); + const response = await fetch(`${location.origin}/seqta/parent/print/assessment?${Date.now()}`, { + method: "POST", + headers: { "Content-Type": "application/json; charset=utf-8" }, + credentials: "include", + body: JSON.stringify({ + id: params.assessmentID, + metaclass: params.metaclassID, + 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 { diff --git a/src/plugins/built-in/assessmentsAverage/extractWeightFromCoversheetText.test.ts b/src/plugins/built-in/assessmentsAverage/extractWeightFromCoversheetText.test.ts index 0e0e6f23..4d63ae9b 100644 --- a/src/plugins/built-in/assessmentsAverage/extractWeightFromCoversheetText.test.ts +++ b/src/plugins/built-in/assessmentsAverage/extractWeightFromCoversheetText.test.ts @@ -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", () => { diff --git a/src/plugins/built-in/assessmentsAverage/index.ts b/src/plugins/built-in/assessmentsAverage/index.ts index 32af3ac5..3623432a 100644 --- a/src/plugins/built-in/assessmentsAverage/index.ts +++ b/src/plugins/built-in/assessmentsAverage/index.ts @@ -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 | null = null; @@ -25,61 +24,59 @@ const assessmentsAveragePlugin = { const { unregister: unregisterWrapperMount } = api.seqta.onMount( ".assessmentsWrapper", async () => { - await waitForElm( - "#main > .assessmentsWrapper .assessments [class*='AssessmentItem__AssessmentItem___']", - true, - 10, - 1000, - ); + await waitForElm( + "#main > .assessmentsWrapper .assessments [class*='AssessmentItem__AssessmentItem___']", + true, + 10, + 1000, + ); - // Wire listeners first so the very first re-render triggered by a - // background handleWeightings completion can find them. - overrideListenerController?.abort(); - overrideListenerController = new AbortController(); - document.addEventListener( - "betterseqta:overrideChanged", - () => renderSubjectAverage(api), - { signal: overrideListenerController.signal }, - ); - document.addEventListener( - "betterseqta:weightingsChanged", - () => renderSubjectAverage(api), - { signal: overrideListenerController.signal }, - ); - - // Render immediately with whatever is already cached. Fresh entries - // and stale-with-previous-value entries both contribute their numeric - // weights, so the subject average appears without waiting on any - // background PDF refetches. - await renderSubjectAverage(api); - - // Kick off indexing in the background. Each completion dispatches - // betterseqta:weightingsChanged, which triggers a fresh render. - void parseAssessments(api); - const wrapper = document.querySelector(".assessmentsWrapper"); - if (wrapper) { - wrapperColourObserver?.disconnect(); - if (wrapperColourObserverTimeout) { - clearTimeout(wrapperColourObserverTimeout); - } - wrapperColourObserver = new MutationObserver(() => { - applySubjectColourToOverallResult(); + // Wire listeners first so the very first re-render triggered by a + // background handleWeightings completion can find them. + overrideListenerController?.abort(); + overrideListenerController = new AbortController(); + document.addEventListener("betterseqta:overrideChanged", () => renderSubjectAverage(api), { + signal: overrideListenerController.signal, }); - wrapperColourObserver.observe(wrapper, { childList: true, subtree: true }); - wrapperColourObserverTimeout = setTimeout(() => { + document.addEventListener( + "betterseqta:weightingsChanged", + () => renderSubjectAverage(api), + { signal: overrideListenerController.signal }, + ); + + // Render immediately with whatever is already cached. Fresh entries + // and stale-with-previous-value entries both contribute their numeric + // weights, so the subject average appears without waiting on any + // background PDF refetches. + await renderSubjectAverage(api); + + // Kick off indexing in the background. Each completion dispatches + // betterseqta:weightingsChanged, which triggers a fresh render. + void parseAssessments(api); + const wrapper = document.querySelector(".assessmentsWrapper"); + if (wrapper) { wrapperColourObserver?.disconnect(); - wrapperColourObserver = null; - wrapperColourObserverTimeout = null; - }, 10000); - } - }, + if (wrapperColourObserverTimeout) { + clearTimeout(wrapperColourObserverTimeout); + } + wrapperColourObserver = new MutationObserver(() => { + applySubjectColourToOverallResult(); + }); + wrapperColourObserver.observe(wrapper, { childList: true, subtree: true }); + wrapperColourObserverTimeout = setTimeout(() => { + wrapperColourObserver?.disconnect(); + wrapperColourObserver = null; + wrapperColourObserverTimeout = null; + }, 10000); + } + }, ); const { unregister: unregisterSelectedMount } = api.seqta.onMount( "[class*='SelectedAssessment__']", () => { - injectWeightingsTab(api); - injectRubricCopyButtons(); - }, + injectWeightingsTab(api); + injectRubricCopyButtons(); + }, ); return () => { @@ -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( - `[class*='AssessmentItem__AssessmentItem___']`, - ), + assessmentsList.querySelectorAll(`[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,11 +220,11 @@ async function renderSubjectAverage(api: any) { } } function applySubjectColourToOverallResult() { - const selectedAssessmentItem = document.querySelector( - "[class*='AssessmentItem__AssessmentItem___'][class*='selected___']", - ) || document.querySelector( - "[class*='Collapsible__content___'] [class*='AssessmentItem__AssessmentItem___']", - ); + const selectedAssessmentItem = + document.querySelector("[class*='AssessmentItem__AssessmentItem___'][class*='selected___']") || + document.querySelector( + "[class*='Collapsible__content___'] [class*='AssessmentItem__AssessmentItem___']", + ); const assessmentThermoscore = selectedAssessmentItem?.querySelector( "[class*='Thermoscore__Thermoscore___']", ) as HTMLElement | null; @@ -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); diff --git a/src/plugins/built-in/assessmentsAverage/rubricCopy.ts b/src/plugins/built-in/assessmentsAverage/rubricCopy.ts index eb9b6c4d..614cf013 100644 --- a/src/plugins/built-in/assessmentsAverage/rubricCopy.ts +++ b/src/plugins/built-in/assessmentsAverage/rubricCopy.ts @@ -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) => - `${rubricPasteCellContent(heading)}`, - ) + .map((heading) => `${rubricPasteCellContent(heading)}`) .join(""); const bodyRows = table.rows @@ -258,7 +249,7 @@ function rubricToHtmlDocument(table: RubricTableData): string { return [ "", "", - "", + '', ``, rubricToHtmlTable(table), "", @@ -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); } diff --git a/src/plugins/built-in/assessmentsAverage/utils.ts b/src/plugins/built-in/assessmentsAverage/utils.ts index 1ce2ae53..85c8637d 100644 --- a/src/plugins/built-in/assessmentsAverage/utils.ts +++ b/src/plugins/built-in/assessmentsAverage/utils.ts @@ -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; } @@ -410,13 +383,13 @@ function createWeightLabel( const weightLabel = existingNativeLabel ? (existingNativeLabel.cloneNode(true) as HTMLElement) : (() => { - const labelClass = getClassByPattern(document, "Label__Label___"); - const innerTextClass = getClassByPattern(document, "Label__innerText___"); - const el = document.createElement("label"); - el.className = labelClass; - el.innerHTML = `
Weight
`; - return el; - })(); + const labelClass = getClassByPattern(document, "Label__Label___"); + const innerTextClass = getClassByPattern(document, "Label__innerText___"); + const el = document.createElement("label"); + el.className = labelClass; + el.innerHTML = `
Weight
`; + return el; + })(); weightLabel.classList.add("betterseqta-weight-label"); weightLabel.style.flex = "none"; @@ -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 { } 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 { export async function extractPDFText(url: string): Promise { 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 { 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 { } } - async function requestStudentAssessmentPdf(params: { assessmentID: string | number; metaclassID: string | number; @@ -687,25 +648,20 @@ async function requestStudentAssessmentPdf(params: { }): Promise { const fileName = randomPdfFileName(); - const printResponse = await fetch( - `${location.origin}/seqta/student/print/assessment`, - { - method: "POST", - headers: { "Content-Type": "application/json; charset=utf-8" }, - credentials: "include", - body: JSON.stringify({ - id: Number(params.assessmentID), - metaclass: Number(params.metaclassID), - student: Number(params.studentID), - fileName, - }), - }, - ); + const printResponse = await fetch(`${location.origin}/seqta/student/print/assessment`, { + method: "POST", + headers: { "Content-Type": "application/json; charset=utf-8" }, + credentials: "include", + body: JSON.stringify({ + id: Number(params.assessmentID), + metaclass: Number(params.metaclassID), + 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 { +async function extractPDFTextWithRetry(url: string, attempts = 3, delayMs = 1500): Promise { 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 { const resolved: Record = {}; // 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 { 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 @@ -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___"]; diff --git a/src/plugins/built-in/assessmentsOverview/AssessmentsOverview.svelte b/src/plugins/built-in/assessmentsOverview/AssessmentsOverview.svelte index 3c220632..30c0c8ae 100644 --- a/src/plugins/built-in/assessmentsOverview/AssessmentsOverview.svelte +++ b/src/plugins/built-in/assessmentsOverview/AssessmentsOverview.svelte @@ -70,7 +70,7 @@ ); function initSubjectFilters(): Record { - 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; diff --git a/src/plugins/built-in/assessmentsOverview/api.ts b/src/plugins/built-in/assessmentsOverview/api.ts index 0fe3187f..01653ffd 100644 --- a/src/plugins/built-in/assessmentsOverview/api.ts +++ b/src/plugins/built-in/assessmentsOverview/api.ts @@ -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", - { - assessment: assessment.id, - metaclass: assessment.metaclassID, - student, - }, - ); + 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; } diff --git a/src/plugins/built-in/assessmentsOverview/engageApi.ts b/src/plugins/built-in/assessmentsOverview/engageApi.ts index f085def9..0dc53357 100644 --- a/src/plugins/built-in/assessmentsOverview/engageApi.ts +++ b/src/plugins/built-in/assessmentsOverview/engageApi.ts @@ -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 { +async function loadEngageAssessmentsForStudent(child: EngageChildPayload): Promise { 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) => ({ - ...assessment, - studentId, - studentName, - })); + const assessments = filterAssessmentsForActiveSubjects(Object.values(map), subjects).map( + (assessment) => ({ + ...assessment, + studentId, + studentName, + }), + ); const submissions = await loadEngageSubmissions(studentId, assessments); assessments.forEach((assessment) => { diff --git a/src/plugins/built-in/assessmentsOverview/icons.ts b/src/plugins/built-in/assessmentsOverview/icons.ts index c8d0ba8e..e953ac92 100644 --- a/src/plugins/built-in/assessmentsOverview/icons.ts +++ b/src/plugins/built-in/assessmentsOverview/icons.ts @@ -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 = { "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 = { diff --git a/src/plugins/built-in/assessmentsOverview/index.ts b/src/plugins/built-in/assessmentsOverview/index.ts index 0daf28d8..8119008d 100644 --- a/src/plugins/built-in/assessmentsOverview/index.ts +++ b/src/plugins/built-in/assessmentsOverview/index.ts @@ -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 { 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) => { - item.classList.remove("active"); - }); + 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 = - '
'; - const container = document.getElementById( - "grid-view-container", - ) as HTMLElement; + main.innerHTML = '
'; + 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"); } } diff --git a/src/plugins/built-in/assessmentsOverview/styles.css b/src/plugins/built-in/assessmentsOverview/styles.css index b6c8398a..dd5dea16 100644 --- a/src/plugins/built-in/assessmentsOverview/styles.css +++ b/src/plugins/built-in/assessmentsOverview/styles.css @@ -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; @@ -995,17 +984,17 @@ .grid-view-title { font-size: 1.5rem !important; } - + .filter-select { padding: 0.5rem 0.75rem; font-size: 0.8rem; min-width: 120px; } - + .assessment-card { padding: 0.75rem; } - + .card-footer { flex-direction: column; gap: 0.5rem; @@ -1043,4 +1032,4 @@ .dark .column-cards::-webkit-scrollbar-thumb:hover { background: rgba(255, 255, 255, 0.3); -} \ No newline at end of file +} diff --git a/src/plugins/built-in/assessmentsOverview/ui.ts b/src/plugins/built-in/assessmentsOverview/ui.ts index c1d8484d..564220c3 100644 --- a/src/plugins/built-in/assessmentsOverview/ui.ts +++ b/src/plugins/built-in/assessmentsOverview/ui.ts @@ -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) { diff --git a/src/plugins/built-in/assessmentsOverview/utils.ts b/src/plugins/built-in/assessmentsOverview/utils.ts index 773d7c54..3431c01e 100644 --- a/src/plugins/built-in/assessmentsOverview/utils.ts +++ b/src/plugins/built-in/assessmentsOverview/utils.ts @@ -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, 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; } diff --git a/src/plugins/built-in/backgroundMusic/index.ts b/src/plugins/built-in/backgroundMusic/index.ts index 7e355d63..de1f398a 100644 --- a/src/plugins/built-in/backgroundMusic/index.ts +++ b/src/plugins/built-in/backgroundMusic/index.ts @@ -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 = { 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 = { }); 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 = { 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(); diff --git a/src/plugins/built-in/backgroundMusic/styles.css b/src/plugins/built-in/backgroundMusic/styles.css index cca0edc1..3a04b571 100644 --- a/src/plugins/built-in/backgroundMusic/styles.css +++ b/src/plugins/built-in/backgroundMusic/styles.css @@ -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); } diff --git a/src/plugins/built-in/enhancedNavigation/index.ts b/src/plugins/built-in/enhancedNavigation/index.ts index 4b7d85d0..d49e2b9b 100644 --- a/src/plugins/built-in/enhancedNavigation/index.ts +++ b/src/plugins/built-in/enhancedNavigation/index.ts @@ -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("li.cover"); if (cover) items.push(cover); - const lessons = Array.from( - navigator.querySelectorAll("li.lesson"), - ); + const lessons = Array.from(navigator.querySelectorAll("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(".course"); + const ref = document.getElementById("toolbar") ?? document.querySelector(".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( - 'button[data-en-action="prev"]', - ); - const next = container.querySelector( - 'button[data-en-action="next"]', - ); + const prev = container.querySelector('button[data-en-action="prev"]'); + const next = container.querySelector('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( - "button[data-en-action]", - ); + const btn = (e.target as Element).closest("button[data-en-action]"); if (!btn) return; const liveCourse = document.querySelector(".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, diff --git a/src/plugins/built-in/errorPageKitten/index.test.ts b/src/plugins/built-in/errorPageKitten/index.test.ts index 9e35ff52..10a0d232 100644 --- a/src/plugins/built-in/errorPageKitten/index.test.ts +++ b/src/plugins/built-in/errorPageKitten/index.test.ts @@ -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 = `
@@ -86,7 +83,9 @@ describe("errorPageKitten", () => { document.title = "SEQTA Learn"; document.body.innerHTML = '
'; - const cleanup = await errorPageKittenPlugin.run({} as Parameters[0]); + const cleanup = await errorPageKittenPlugin.run( + {} as Parameters[0], + ); expect(getCard()).toBeNull(); expect(cleanup).toBeDefined(); diff --git a/src/plugins/built-in/errorPageKitten/index.ts b/src/plugins/built-in/errorPageKitten/index.ts index 77ef3250..56f23dbb 100644 --- a/src/plugins/built-in/errorPageKitten/index.ts +++ b/src/plugins/built-in/errorPageKitten/index.ts @@ -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") ); } diff --git a/src/plugins/built-in/errorPageKitten/styles.css b/src/plugins/built-in/errorPageKitten/styles.css index 6434b443..89172e86 100644 --- a/src/plugins/built-in/errorPageKitten/styles.css +++ b/src/plugins/built-in/errorPageKitten/styles.css @@ -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, diff --git a/src/plugins/built-in/globalSearch/lazy.ts b/src/plugins/built-in/globalSearch/lazy.ts index b57b7ae4..aaf4ac0b 100644 --- a/src/plugins/built-in/globalSearch/lazy.ts +++ b/src/plugins/built-in/globalSearch/lazy.ts @@ -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: " + diff --git a/src/plugins/built-in/globalSearch/src/core/commands.ts b/src/plugins/built-in/globalSearch/src/core/commands.ts index 0ed26a3b..ba9cf7ec 100644 --- a/src/plugins/built-in/globalSearch/src/core/commands.ts +++ b/src/plugins/built-in/globalSearch/src/core/commands.ts @@ -20,7 +20,7 @@ export interface StaticCommandItem extends BaseCommandItem { async function getCurrentLesson() { const date = new Date(); const todayFormatted = formatDate(date); - + try { const response = await fetch(`${location.origin}/seqta/student/load/timetable?`, { method: "POST", @@ -31,35 +31,35 @@ async function getCurrentLesson() { until: todayFormatted, }), }); - + const timetableData = await response.json(); - + if (!timetableData.payload.items.length) { alert("No lessons today!"); return null; } - + const lessons = timetableData.payload.items.sort((a: any, b: any) => - a.from.localeCompare(b.from) + a.from.localeCompare(b.from), ); - + const currentTime = new Date(); - + for (const lesson of lessons) { const [startHour, startMinute] = lesson.from.split(":").map(Number); const [endHour, endMinute] = lesson.until.split(":").map(Number); - + const startDate = new Date(currentTime); startDate.setHours(startHour, startMinute, 0); - + const endDate = new Date(currentTime); endDate.setHours(endHour, endMinute, 0); - + if (startDate <= currentTime && endDate > currentTime) { return lesson; } } - + alert("There is no current lesson!"); return null; } catch (error) { @@ -72,33 +72,33 @@ async function getCurrentLesson() { async function navigateToSpecificLesson(lesson: any) { try { 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"); - + for (const week of weeks) { const lessons = week.querySelectorAll(".lesson"); - + for (const lessonElement of lessons) { const metaElement = lessonElement.querySelector(".meta"); if (!metaElement) continue; - + const dateElement = metaElement.querySelector(".date"); const periodElement = metaElement.querySelector(".period"); - + if (!dateElement || !periodElement) continue; - + const lessonDate = dateElement.textContent?.trim(); const lessonPeriod = periodElement.textContent?.trim().match(/\d+/)?.[0]; - + // extract the number from the period const normalizedLessonPeriod = lesson.period?.match(/\d+/)?.[0]; - + // Check if this lesson matches today's date and the current lesson's period if (lessonDate === todayDateString && lessonPeriod === normalizedLessonPeriod) { // Found the exact matching lesson, click it @@ -107,10 +107,11 @@ 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(); } @@ -171,7 +172,7 @@ const staticCommands: StaticCommandItem[] = [ const currentLesson = await getCurrentLesson(); if (currentLesson && currentLesson.programmeID !== 0) { window.location.hash = `?page=/courses/${currentLesson.programmeID}:${currentLesson.metaID}`; - + await navigateToSpecificLesson(currentLesson); } }, @@ -204,13 +205,16 @@ const staticCommands: StaticCommandItem[] = [ category: "action", text: "Compose Message", action: () => { - window.postMessage({ - type: "triggerKeyboardEvent", - key: 'm', - code: 'KeyM', - keyCode: 77, - altKey: true - }, location.origin); + window.postMessage( + { + type: "triggerKeyboardEvent", + key: "m", + code: "KeyM", + keyCode: 77, + altKey: true, + }, + location.origin, + ); }, keywords: ["compose", "message", "dm", "direct message", "new message"], priority: 3, diff --git a/src/plugins/built-in/globalSearch/src/core/index.ts b/src/plugins/built-in/globalSearch/src/core/index.ts index 61f8b3a5..4d6ab824 100644 --- a/src/plugins/built-in/globalSearch/src/core/index.ts +++ b/src/plugins/built-in/globalSearch/src/core/index.ts @@ -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, "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, "run"> = { } } - if ( - globalSearchIndexingEnabled(!!api.settings.runIndexingOnLoad) && - !isIndexingPaused() - ) { + if (globalSearchIndexingEnabled(!!api.settings.runIndexingOnLoad) && !isIndexingPaused()) { scheduleIdleIndexing(() => { if (!isIndexingPaused()) void runIndexing(); }); diff --git a/src/plugins/built-in/globalSearch/src/core/mountSearchBar.ts b/src/plugins/built-in/globalSearch/src/core/mountSearchBar.ts index 77faca0f..f3073252 100644 --- a/src/plugins/built-in/globalSearch/src/core/mountSearchBar.ts +++ b/src/plugins/built-in/globalSearch/src/core/mountSearchBar.ts @@ -18,12 +18,8 @@ type AppRef = { const SEARCH_SVG = ''; -async function resolveTriggerWrapper( - titleElement: Element, -): Promise { - const existing = titleElement.querySelector( - ".search-trigger-wrapper", - ) as HTMLElement | null; +async function resolveTriggerWrapper(titleElement: Element): Promise { + 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 = (sel: string) => - searchWrapper.querySelector(sel) as T; + const q = (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,19 +306,14 @@ 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"), + document.getElementById("bsplus-title-root"), ); if (searchWrapper) { diff --git a/src/plugins/built-in/globalSearch/src/core/styles.css b/src/plugins/built-in/globalSearch/src/core/styles.css index e442b4ab..952f94bd 100644 --- a/src/plugins/built-in/globalSearch/src/core/styles.css +++ b/src/plugins/built-in/globalSearch/src/core/styles.css @@ -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; diff --git a/src/plugins/built-in/globalSearch/src/indexing/__fixtures__/seqtaResponses.ts b/src/plugins/built-in/globalSearch/src/indexing/__fixtures__/seqtaResponses.ts index 850a5a6e..de352702 100644 --- a/src/plugins/built-in/globalSearch/src/indexing/__fixtures__/seqtaResponses.ts +++ b/src/plugins/built-in/globalSearch/src/indexing/__fixtures__/seqtaResponses.ts @@ -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|

Some reflection text.

]] Plain trailing text.', + contents: "[[embed:raw|

Some reflection text.

]] Plain trailing text.", created: "2026-04-14 10:32:34.264641+00", allow_comments: true, author: { year: "Year 10", name: "Jacob Johannesburg", id: 3111 }, diff --git a/src/plugins/built-in/globalSearch/src/indexing/actions.ts b/src/plugins/built-in/globalSearch/src/indexing/actions.ts index 605a9274..583fa306 100644 --- a/src/plugins/built-in/globalSearch/src/indexing/actions.ts +++ b/src/plugins/built-in/globalSearch/src/indexing/actions.ts @@ -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; @@ -73,14 +73,14 @@ export const actionMap: Record> = { ReactFiber.find('[class*="Viewer__Viewer___"] > div').setState({ selected: new Set([item.metadata.messageId]), }); - + // 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, }), }); @@ -98,13 +98,16 @@ export const actionMap: Record> = { // Firefox XrayWrapper prevents direct access to nested properties let itemClone: IndexItem & { metadata: AssessmentMetadata }; let metadata: AssessmentMetadata; - + try { // First try to clone the entire item 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,10 +115,10 @@ export const actionMap: Record> = { } 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); } } - + // Try to extract metadata values using multiple methods to handle XrayWrapper. // The metadata bag is intentionally typed loosely here because Firefox's // XrayWrapper occasionally surfaces extra/casing-variant keys we still @@ -152,51 +155,65 @@ export const actionMap: Record> = { return undefined; } }; - - 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}`; verboseLog("[Assessment Action] ✅ Navigating to:", url); @@ -226,15 +243,11 @@ export const actionMap: Record> = { }) as ActionHandler, subjectassessment: ((item: IndexItem) => { - navigateToHashRoute( - `/assessments/${item.metadata.programme}:${item.metadata.subjectId}`, - ); + navigateToHashRoute(`/assessments/${item.metadata.programme}:${item.metadata.subjectId}`); }) as ActionHandler, subjectcourse: ((item: IndexItem) => { - navigateToHashRoute( - `/courses/${item.metadata.programme}:${item.metadata.subjectId}`, - ); + navigateToHashRoute(`/courses/${item.metadata.programme}:${item.metadata.subjectId}`); }) as ActionHandler, forum: ((item: IndexItem) => { @@ -322,8 +335,7 @@ export const actionMap: Record> = { passive: ((item: IndexItem) => { const md = (item.metadata ?? {}) as Record; 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> = { }; 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) { diff --git a/src/plugins/built-in/globalSearch/src/indexing/api.ts b/src/plugins/built-in/globalSearch/src/indexing/api.ts index 81d58a84..16b95f46 100644 --- a/src/plugins/built-in/globalSearch/src/indexing/api.ts +++ b/src/plugins/built-in/globalSearch/src/indexing/api.ts @@ -302,10 +302,7 @@ export async function seqtaFetchPayload( const res = await seqtaFetchJson(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; } } diff --git a/src/plugins/built-in/globalSearch/src/indexing/db.ts b/src/plugins/built-in/globalSearch/src/indexing/db.ts index f447bac0..07a17ef2 100644 --- a/src/plugins/built-in/globalSearch/src/indexing/db.ts +++ b/src/plugins/built-in/globalSearch/src/indexing/db.ts @@ -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 { 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 { return deleteDatabaseWithRetries(DB_NAME); } -function deleteDatabaseWithRetries( - name: string, - maxAttempts = 6, -): Promise { +function deleteDatabaseWithRetries(name: string, maxAttempts = 6): Promise { return new Promise((resolve) => { const attemptDelete = (attempt: number) => { let req: IDBOpenDBRequest; @@ -146,9 +137,7 @@ async function openDBInternal(): Promise { 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 { 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( export async function getAll(store: string): Promise { 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 { export async function get(store: string, key: string): Promise { 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 { +export async function put(store: string, value: any, key?: string): Promise { try { await withObjectStore(store, "readwrite", async (s) => { await idbRequest(key ? s.put(value, key) : s.put(value)); diff --git a/src/plugins/built-in/globalSearch/src/indexing/extract.ts b/src/plugins/built-in/globalSearch/src/indexing/extract.ts index c91a9d07..349912c5 100644 --- a/src/plugins/built-in/globalSearch/src/indexing/extract.ts +++ b/src/plugins/built-in/globalSearch/src/indexing/extract.ts @@ -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 = { 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(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 = {}; diff --git a/src/plugins/built-in/globalSearch/src/indexing/indexer.ts b/src/plugins/built-in/globalSearch/src/indexing/indexer.ts index 137a9e00..a410cf90 100644 --- a/src/plugins/built-in/globalSearch/src/indexing/indexer.ts +++ b/src/plugins/built-in/globalSearch/src/indexing/indexer.ts @@ -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 { +async function diffAndStoreItems(targetStore: string, items: IndexItem[]): Promise { 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 }> = []; @@ -192,10 +187,10 @@ async function acquireLock(): Promise { function startHeartbeat() { const lockId = localStorage.getItem(LOCK_KEY); 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 { 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 { } 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; } @@ -315,177 +318,160 @@ export async function runIndexing(): Promise { verboseDebug("%c[Indexer] Starting indexing...", "color: green"); try { - const jobIds = Object.keys(jobs); - await ensureStoresExist([META_STORE, ...jobIds]); + const jobIds = Object.keys(jobs); + await ensureStoresExist([META_STORE, ...jobIds]); - let completedJobs = 0; - const totalSteps = jobIds.length + 1; - dispatchProgress(completedJobs, totalSteps, true, "Starting jobs"); + let completedJobs = 0; + const totalSteps = jobIds.length + 1; + dispatchProgress(completedJobs, totalSteps, true, "Starting jobs"); - 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", - ); - return; - } - - 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", - ); - completedJobs++; - dispatchProgress( - completedJobs, - totalSteps, - true, - `Skipped job: ${job.label}`, - ); - continue; - } - - const getStoredItems = async (storeId?: string) => - await getAll(storeId ?? jobId); - const setStoredItems = async (items: IndexItem[], storeId?: string) => { - const targetStore = storeId ?? jobId; - await diffAndStoreItems(targetStore, items); - }; - const addItem = async (item: IndexItem, storeId?: string) => { - const targetStore = storeId ?? jobId; - if (item && item.id) { - await put(targetStore, item, item.id); - } else { - console.warn( - `[Indexer Job ${jobId} -> Store ${targetStore}] Attempted to add invalid item:`, - item, - ); + 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"); + return; } - }; - const removeItem = async (id: string, storeId?: string) => { - const targetStore = storeId ?? jobId; - await remove(targetStore, id); - }; - const ctx: JobContext = { - getStoredItems, - setStoredItems, - addItem, - removeItem, - getProgress: () => loadProgress(jobId), - setProgress: (p) => saveProgress(jobId, p), - reportJobProgress: ({ processed, total, status }) => { - const stepProgress = total > 0 ? processed / total : 0; - dispatchProgress( - completedJobs + stepProgress, - totalSteps, - true, - status ?? `Running job: ${job.label}`, - ); - }, - }; + dispatchProgress(completedJobs, totalSteps, true, `Running job: ${jobs[jobId].label}`); + const job = jobs[jobId]; + const lastRun = await getLastRunMeta(jobId); - verboseDebug(`%c[Indexer] Running job "${jobId}"...`, "color: #4ea1ff"); + if (!shouldRun(job, lastRun)) { + verboseDebug(`%c[Indexer] Skipping job "${jobId}" (not due)`, "color: gray"); + completedJobs++; + dispatchProgress(completedJobs, totalSteps, true, `Skipped job: ${job.label}`); + continue; + } - try { - const newItemsRaw = await job.run(ctx); - const stored = await getStoredItems(); + const getStoredItems = async (storeId?: string) => await getAll(storeId ?? jobId); + const setStoredItems = async (items: IndexItem[], storeId?: string) => { + const targetStore = storeId ?? jobId; + await diffAndStoreItems(targetStore, items); + }; + const addItem = async (item: IndexItem, storeId?: string) => { + const targetStore = storeId ?? jobId; + if (item && item.id) { + await put(targetStore, item, item.id); + } else { + console.warn( + `[Indexer Job ${jobId} -> Store ${targetStore}] Attempted to add invalid item:`, + item, + ); + } + }; + const removeItem = async (id: string, storeId?: string) => { + const targetStore = storeId ?? jobId; + await remove(targetStore, id); + }; - let merged = mergeItems(stored, newItemsRaw); - if (job.purge) merged = job.purge(merged); - - await setStoredItems(merged); - await updateLastRunMeta(jobId); + const ctx: JobContext = { + getStoredItems, + setStoredItems, + addItem, + removeItem, + getProgress: () => loadProgress(jobId), + setProgress: (p) => saveProgress(jobId, p), + reportJobProgress: ({ processed, total, status }) => { + const stepProgress = total > 0 ? processed / total : 0; + dispatchProgress( + completedJobs + stepProgress, + totalSteps, + true, + status ?? `Running job: ${job.label}`, + ); + }, + }; - verboseDebug( - `%c[Indexer] ${job.label}: ${newItemsRaw.length} new items reported by run, ${merged.length} total items now in '${jobId}' store.`, - "color: #00c46f", - ); - } catch (err) { - verboseDebug(`%c[Indexer] Job ${job.label} failed:`, "color: red"); - console.error(err); - } - - completedJobs++; - dispatchProgress( - completedJobs, - totalSteps, - true, - `Finished job: ${job.label}`, - ); - } - - let allItemsInPrimaryStores = await loadAllStoredItems(); - - const liveItemIds = new Set(allItemsInPrimaryStores.map((item) => item.id)); - const prunedCount = await pruneOrphanVectorEmbeddings(liveItemIds); - if (prunedCount > 0) { - try { - const { refreshVectorCache } = await import("../search/vector/vectorSearch"); - await refreshVectorCache(); - } catch (e) { - console.warn("[Indexer] Failed to refresh vector cache after prune:", e); - } - } - - if (allItemsInPrimaryStores.length > 0) { - verboseDebug( - `%c[Indexer] Checking ${allItemsInPrimaryStores.length} items for vectorization...`, - "color: #4ea1ff", - ); - - // Pre-filter items to avoid initializing worker if nothing new - const vectorizedItemIds = await getVectorizedItemIds(); - const newItemsToVectorize = allItemsInPrimaryStores.filter(item => !vectorizedItemIds.has(item.id)); - - if (newItemsToVectorize.length > 0) { - verboseDebug( - `%c[Indexer] Sending ${newItemsToVectorize.length} new items to worker for vectorization (${allItemsInPrimaryStores.length - newItemsToVectorize.length} already vectorized)`, - "color: #4ea1ff", - ); - dispatchProgress(completedJobs, totalSteps, true, "Starting vectorization of new items"); + verboseDebug(`%c[Indexer] Running job "${jobId}"...`, "color: #4ea1ff"); try { - const workerManager = VectorWorkerManager.getInstance(); - await workerManager.processItems(newItemsToVectorize, (progress) => { - completedJobs = dispatchVectorProgress(progress, completedJobs, totalSteps); - }); - verboseDebug( - "%c[Indexer] Vectorization task for stored items sent to worker.", - "color: green", - ); - } catch (error) { - console.error( - `%c[Indexer] ❌ Failed to send items to vector worker:`, - "color: red", - error, - ); - dispatchProgress( - completedJobs, - totalSteps, - false, - "Vectorization failed", - String(error), - ); + const newItemsRaw = await job.run(ctx); + const stored = await getStoredItems(); + + let merged = mergeItems(stored, newItemsRaw); + if (job.purge) merged = job.purge(merged); + + await setStoredItems(merged); + await updateLastRunMeta(jobId); + + verboseDebug( + `%c[Indexer] ${job.label}: ${newItemsRaw.length} new items reported by run, ${merged.length} total items now in '${jobId}' store.`, + "color: #00c46f", + ); + } catch (err) { + verboseDebug(`%c[Indexer] Job ${job.label} failed:`, "color: red"); + console.error(err); + } + + completedJobs++; + dispatchProgress(completedJobs, totalSteps, true, `Finished job: ${job.label}`); } + + let allItemsInPrimaryStores = await loadAllStoredItems(); + + const liveItemIds = new Set(allItemsInPrimaryStores.map((item) => item.id)); + const prunedCount = await pruneOrphanVectorEmbeddings(liveItemIds); + if (prunedCount > 0) { + try { + const { refreshVectorCache } = await import("../search/vector/vectorSearch"); + await refreshVectorCache(); + } catch (e) { + console.warn("[Indexer] Failed to refresh vector cache after prune:", e); + } + } + + if (allItemsInPrimaryStores.length > 0) { + verboseDebug( + `%c[Indexer] Checking ${allItemsInPrimaryStores.length} items for vectorization...`, + "color: #4ea1ff", + ); + + // Pre-filter items to avoid initializing worker if nothing new + const vectorizedItemIds = await getVectorizedItemIds(); + const newItemsToVectorize = allItemsInPrimaryStores.filter( + (item) => !vectorizedItemIds.has(item.id), + ); + + if (newItemsToVectorize.length > 0) { + verboseDebug( + `%c[Indexer] Sending ${newItemsToVectorize.length} new items to worker for vectorization (${allItemsInPrimaryStores.length - newItemsToVectorize.length} already vectorized)`, + "color: #4ea1ff", + ); + dispatchProgress(completedJobs, totalSteps, true, "Starting vectorization of new items"); + + try { + const workerManager = VectorWorkerManager.getInstance(); + await workerManager.processItems(newItemsToVectorize, (progress) => { + completedJobs = dispatchVectorProgress(progress, completedJobs, totalSteps); + }); + verboseDebug( + "%c[Indexer] Vectorization task for stored items sent to worker.", + "color: green", + ); + } catch (error) { + console.error( + `%c[Indexer] ❌ Failed to send items to vector worker:`, + "color: red", + error, + ); + dispatchProgress(completedJobs, totalSteps, false, "Vectorization failed", String(error)); + } + } else { + verboseDebug( + `%c[Indexer] All ${allItemsInPrimaryStores.length} items are already vectorized, skipping worker initialization.`, + "color: gray", + ); + completedJobs++; + dispatchProgress( + completedJobs, + totalSteps, + false, + "Indexing finished (all items already vectorized)", + ); + } } else { verboseDebug( - `%c[Indexer] All ${allItemsInPrimaryStores.length} items are already vectorized, skipping worker initialization.`, + "%c[Indexer] No items found in primary stores to send for vectorization.", "color: gray", ); completedJobs++; @@ -493,31 +479,18 @@ export async function runIndexing(): Promise { completedJobs, totalSteps, false, - "Indexing finished (all items already vectorized)", + "Indexing finished (no items for vectorization)", ); } - } else { - verboseDebug( - "%c[Indexer] No items found in primary stores to send for vectorization.", - "color: gray", - ); - completedJobs++; - dispatchProgress( - completedJobs, - totalSteps, - false, - "Indexing finished (no items for vectorization)", - ); - } - allItemsInPrimaryStores = await loadAllStoredItems(); - const itemsWithComponents = decorateIndexItems(allItemsInPrimaryStores); - loadDynamicItems(itemsWithComponents); - window.dispatchEvent( - new CustomEvent("dynamic-items-updated", { - detail: { fullRebuild: true }, - }), - ); + allItemsInPrimaryStores = await loadAllStoredItems(); + const itemsWithComponents = decorateIndexItems(allItemsInPrimaryStores); + loadDynamicItems(itemsWithComponents); + window.dispatchEvent( + new CustomEvent("dynamic-items-updated", { + detail: { fullRebuild: true }, + }), + ); } finally { setIndexingActive(false); stopHeartbeat(); @@ -533,4 +506,4 @@ function mergeItems(existing: IndexItem[], incoming: IndexItem[]): IndexItem[] { if (item && item.id) map.set(item.id, item); } return Array.from(map.values()); -} \ No newline at end of file +} diff --git a/src/plugins/built-in/globalSearch/src/indexing/indexingState.test.ts b/src/plugins/built-in/globalSearch/src/indexing/indexingState.test.ts index 3ce9395f..0aaf3e3f 100644 --- a/src/plugins/built-in/globalSearch/src/indexing/indexingState.test.ts +++ b/src/plugins/built-in/globalSearch/src/indexing/indexingState.test.ts @@ -1,7 +1,4 @@ -import { - isIndexingActive, - setIndexingActive, -} from "./indexingState"; +import { isIndexingActive, setIndexingActive } from "./indexingState"; describe("indexingState", () => { afterEach(() => { diff --git a/src/plugins/built-in/globalSearch/src/indexing/jobs/assignments.ts b/src/plugins/built-in/globalSearch/src/indexing/jobs/assignments.ts index f5e9b1b2..bfc69f14 100644 --- a/src/plugins/built-in/globalSearch/src/indexing/jobs/assignments.ts +++ b/src/plugins/built-in/globalSearch/src/indexing/jobs/assignments.ts @@ -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); @@ -83,19 +84,19 @@ export const assignmentsJob: Job = { label: "Assignments", renderComponentId: "assessment", frequency: { type: "expiry", afterMs: 1000 * 60 * 60 * 24 }, // Daily - + boostCriteria: (item, searchTerm) => { if (searchTerm === "") { return -100; } let score = 0; - + if (item.metadata.dueDate) { const dueDate = new Date(item.metadata.dueDate).getTime(); const now = Date.now(); const daysUntilDue = (dueDate - now) / (1000 * 60 * 60 * 24); - + if (daysUntilDue >= 0 && daysUntilDue <= 7) { score += 0.05; // Boost assignments due within a week } @@ -103,11 +104,11 @@ export const assignmentsJob: Job = { score -= 0.1; // Penalty for overdue assignments } } - + if (item.metadata.submitted) { score += 0.02; } - + return score; }, @@ -118,33 +119,37 @@ 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); - + verboseDebug(`[Assignments job] Fetched ${past.length} past assessments`); - + const subjectLookup = new Map(); subjects.forEach((s: any) => { if (s.code && s.programme && s.metaclass) { subjectLookup.set(s.code, { programme: s.programme, metaclass: s.metaclass }); } }); - + const allAssessments = new Map(); - + upcoming.forEach((a: any) => { if (a && a.id) { let programme = a.programmeID || a.programme; let metaclass = a.metaclassID || a.metaclass; - + if ((!programme || !metaclass) && a.code) { const subjectInfo = subjectLookup.get(a.code); if (subjectInfo) { @@ -152,7 +157,7 @@ export const assignmentsJob: Job = { metaclass = metaclass || subjectInfo.metaclass; } } - + allAssessments.set(a.id, { ...a, programme, @@ -163,17 +168,17 @@ export const assignmentsJob: Job = { }); } }); - + past.forEach((a: any) => { if (a && a.id) { let programme = a.programmeID || a.programme; let metaclass = a.metaclassID || a.metaclass; - + const existing = allAssessments.get(a.id); if (existing) { programme = programme || existing.programme || existing.programmeID; metaclass = metaclass || existing.metaclass || existing.metaclassID; - + Object.assign(existing, { ...a, programme, @@ -182,13 +187,13 @@ export const assignmentsJob: Job = { metaclassID: metaclass, }); } else { - allAssessments.set(a.id, { - ...a, + allAssessments.set(a.id, { + ...a, programme, metaclass, programmeID: programme, metaclassID: metaclass, - isUpcoming: false + isUpcoming: false, }); } } @@ -198,79 +203,87 @@ export const assignmentsJob: Job = { const processedIds = new Set(); 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. - + for (let i = 0; i < assessmentArray.length; i += batchSize) { const batch = assessmentArray.slice(i, i + batchSize); - + const batchItems = await Promise.all( batch.map(async (assessment) => { const id = `assignment-${assessment.id}`; - + if (processedIds.has(id)) { return null; } - + processedIds.add(id); - const description = ""; const subjectName = assessment.subject || assessment.code || "Unknown Subject"; const dueDate = assessment.due ? new Date(assessment.due).getTime() : null; - + const programmeId = assessment.programmeID || assessment.programme; const metaclassId = assessment.metaclassID || assessment.metaclass; - + if (!programmeId || !metaclassId || !assessment.id) { - console.warn(`[Assignments job] Skipping assignment ${assessment.id} - missing required IDs:`, { - programmeId, - metaclassId, - assessmentId: assessment.id, - programmeID: assessment.programmeID, - metaclassID: assessment.metaclassID, - programme: assessment.programme, - metaclass: assessment.metaclass, - assessment, - }); + console.warn( + `[Assignments job] Skipping assignment ${assessment.id} - missing required IDs:`, + { + programmeId, + metaclassId, + assessmentId: assessment.id, + programmeID: assessment.programmeID, + metaclassID: assessment.metaclassID, + 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:`, { - programmeId: finalProgrammeId, - metaclassId: finalMetaclassId, - assessmentId: assessment.id, - rawProgrammeId: programmeId, - rawMetaclassId: metaclassId, - assessment, - }); + 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; } - + const item: IndexItem = { 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, @@ -290,7 +303,7 @@ export const assignmentsJob: Job = { actionId: "assessment", renderComponentId: "assessment", }; - + verboseDebug(`[Assignments job] ✅ Created item for assignment ${assessment.id}:`, { id: item.id, programmeId: item.metadata.programmeId, @@ -302,34 +315,37 @@ export const assignmentsJob: Job = { }); return item; - }) + }), ); - - batchItems.forEach(item => { + + batchItems.forEach((item) => { if (item) { items.push(item); } }); - + if (i + batchSize < assessmentArray.length) { await delay(50); } } - 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 && - i.metadata.assessmentId && - i.metadata.programmeId !== undefined && - i.metadata.metaclassId !== undefined; + return ( + i.metadata && + i.metadata.assessmentId && + i.metadata.programmeId !== undefined && + i.metadata.metaclassId !== undefined + ); }); }, }; - diff --git a/src/plugins/built-in/globalSearch/src/indexing/jobs/courses.ts b/src/plugins/built-in/globalSearch/src/indexing/jobs/courses.ts index 3e2e3e39..e5bb44f3 100644 --- a/src/plugins/built-in/globalSearch/src/indexing/jobs/courses.ts +++ b/src/plugins/built-in/globalSearch/src/indexing/jobs/courses.ts @@ -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 => { const payload = await seqtaFetchPayload( "/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( - "/seqta/student/load/courses", - { - programme: String(subject.programme), - metaclass: String(subject.metaclass), - }, - ); + const payload = await seqtaFetchPayload("/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) diff --git a/src/plugins/built-in/globalSearch/src/indexing/jobs/documents.ts b/src/plugins/built-in/globalSearch/src/indexing/jobs/documents.ts index b0c60b14..4284b814 100644 --- a/src/plugins/built-in/globalSearch/src/indexing/jobs/documents.ts +++ b/src/plugins/built-in/globalSearch/src/indexing/jobs/documents.ts @@ -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, diff --git a/src/plugins/built-in/globalSearch/src/indexing/jobs/folio.ts b/src/plugins/built-in/globalSearch/src/indexing/jobs/folio.ts index 54ac665f..f80d9993 100644 --- a/src/plugins/built-in/globalSearch/src/indexing/jobs/folio.ts +++ b/src/plugins/built-in/globalSearch/src/indexing/jobs/folio.ts @@ -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( - "/seqta/student/folio", - { mode: "list", page: 0, filters: {} }, - ); + const list = await seqtaFetchPayload("/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( - "/seqta/student/folio", - { mode: "load", id: entry.id }, - ); + const detail = await seqtaFetchPayload("/seqta/student/folio", { + mode: "load", + id: entry.id, + }); const rawContents = detail?.contents ?? ""; const flattened = stripEmbedRaw(rawContents); const content = flattened.slice(0, 4000); diff --git a/src/plugins/built-in/globalSearch/src/indexing/jobs/forums.ts b/src/plugins/built-in/globalSearch/src/indexing/jobs/forums.ts index 48fa8c53..26d3d848 100644 --- a/src/plugins/built-in/globalSearch/src/indexing/jobs/forums.ts +++ b/src/plugins/built-in/globalSearch/src/indexing/jobs/forums.ts @@ -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,9 +59,9 @@ 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); }, -}; \ No newline at end of file +}; diff --git a/src/plugins/built-in/globalSearch/src/indexing/jobs/goals.ts b/src/plugins/built-in/globalSearch/src/indexing/jobs/goals.ts index 4bcf2bf7..d122ec3b 100644 --- a/src/plugins/built-in/globalSearch/src/indexing/jobs/goals.ts +++ b/src/plugins/built-in/globalSearch/src/indexing/jobs/goals.ts @@ -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( - "/seqta/student/load/goals", - { mode: "list", year }, - ); + const yearGoals = await seqtaFetchPayload("/seqta/student/load/goals", { + mode: "list", + year, + }); if (!Array.isArray(yearGoals)) continue; for (const goal of yearGoals) { @@ -66,11 +66,11 @@ 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 - ? new Date(goal.updated ?? goal.created!).getTime() || Date.now() - : Date.now(); + 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(); items.push({ id, diff --git a/src/plugins/built-in/globalSearch/src/indexing/jobs/messages.ts b/src/plugins/built-in/globalSearch/src/indexing/jobs/messages.ts index 8a32e6c1..5074f041 100644 --- a/src/plugins/built-in/globalSearch/src/indexing/jobs/messages.ts +++ b/src/plugins/built-in/globalSearch/src/indexing/jobs/messages.ts @@ -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 { } } -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); } } diff --git a/src/plugins/built-in/globalSearch/src/indexing/jobs/notices.ts b/src/plugins/built-in/globalSearch/src/indexing/jobs/notices.ts index 9f6664d1..5017669a 100644 --- a/src/plugins/built-in/globalSearch/src/indexing/jobs/notices.ts +++ b/src/plugins/built-in/globalSearch/src/indexing/jobs/notices.ts @@ -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 daily notices from `/seqta/student/load/notices`. * @@ -61,9 +61,10 @@ const fetchNoticesForDate = async (date: string): Promise => { }; const fetchLabelLookup = async (): Promise> => { - const payload = await seqtaFetchPayload< - Array<{ id: number; title?: string }> - >("/seqta/student/load/notices", { mode: "labels" }); + const payload = await seqtaFetchPayload>( + "/seqta/student/load/notices", + { mode: "labels" }, + ); const map = new Map(); if (Array.isArray(payload)) { for (const entry of payload) { @@ -86,8 +87,7 @@ export const noticesJob: Job = { let score = 0; const ts = item.metadata?.timestamp; if (typeof ts === "string") { - const ageDays = - (Date.now() - new Date(ts).getTime()) / (1000 * 60 * 60 * 24); + const ageDays = (Date.now() - new Date(ts).getTime()) / (1000 * 60 * 60 * 24); if (ageDays >= 0 && ageDays <= 7) score += 0.05; } return score; @@ -108,19 +108,14 @@ export const noticesJob: Job = { // Sweep window: always the most recent SWEEP_DAYS, plus extend further // back the first time we run until we hit MAX_HISTORY_DAYS. - const earliestEverIso = formatYmd( - new Date(today.getTime() - MAX_HISTORY_DAYS * 86_400_000), - ); + const earliestEverIso = formatYmd(new Date(today.getTime() - MAX_HISTORY_DAYS * 86_400_000)); const dates: string[] = []; for (let offset = 0; offset < SWEEP_DAYS; offset++) { const day = new Date(today.getTime() - offset * 86_400_000); dates.push(formatYmd(day)); } - if ( - !progress.lastSweepBackTo || - progress.lastSweepBackTo > earliestEverIso - ) { + if (!progress.lastSweepBackTo || progress.lastSweepBackTo > earliestEverIso) { // Walk backwards in batches of ~30 days per run so we don't blow up // a single indexing pass. const startBack = parseYmd(progress.lastSweepBackTo) ?? today; @@ -151,13 +146,9 @@ export const noticesJob: Job = { const labelTitle = notice.label_title ?? - (typeof notice.label === "number" - ? labelLookup.get(notice.label) ?? null - : null); + (typeof notice.label === "number" ? (labelLookup.get(notice.label) ?? null) : null); - const bodyText = notice.contents - ? htmlToPlainText(notice.contents) - : ""; + const bodyText = notice.contents ? htmlToPlainText(notice.contents) : ""; items.push({ id, @@ -194,10 +185,7 @@ export const noticesJob: Job = { .filter((d): d is string => !!d); if (dateStrings.length > 0) { const earliest = dateStrings.sort()[0]; - if ( - !progress.earliestDate || - earliest < progress.earliestDate - ) { + if (!progress.earliestDate || earliest < progress.earliestDate) { progress.earliestDate = earliest; } } diff --git a/src/plugins/built-in/globalSearch/src/indexing/jobs/notifications.ts b/src/plugins/built-in/globalSearch/src/indexing/jobs/notifications.ts index e55c2b5f..fee5e802 100644 --- a/src/plugins/built-in/globalSearch/src/indexing/jobs/notifications.ts +++ b/src/plugins/built-in/globalSearch/src/indexing/jobs/notifications.ts @@ -6,7 +6,7 @@ import { VectorWorkerManager } from "../worker/vectorWorkerManager"; import { loadAllStoredItems } from "../indexer"; import { publishDynamicItemsUpdate } from "../renderComponents"; -import { verboseLog } from '@/utils/verboseLog'; +import { verboseLog } from "@/utils/verboseLog"; const NOTIFICATIONS_RATE_LIMIT = { baseDelay: 150, maxDelay: 3000, @@ -69,20 +69,14 @@ const fetchAssessmentName = async ( ): Promise => { const searchAssessment = (data: any): string | null => { for (const item of data.syllabus || []) { - const found = (item.assessments || []).find( - (a: any) => a.id === assessmentId, - ); + const found = (item.assessments || []).find((a: any) => a.id === assessmentId); if (found) return found.title; } - const foundPending = (data.pending || []).find( - (a: any) => a.id === assessmentId, - ); + const foundPending = (data.pending || []).find((a: any) => a.id === assessmentId); if (foundPending) return foundPending.title; - const foundTask = (data.tasks || []).find( - (a: any) => a.id === assessmentId, - ); + const foundTask = (data.tasks || []).find((a: any) => a.id === assessmentId); if (foundTask) return foundTask.title; return null; @@ -130,29 +124,18 @@ const fetchAssessmentName = async ( await delay(NOTIFICATIONS_RATE_LIMIT.baseDelay); - const upcomingPayload = await fetchAssessments( - "/seqta/student/assessment/list/upcoming", - ); - const foundUpcoming = (upcomingPayload || []).find( - (a: any) => a.id === assessmentId, - ); + const upcomingPayload = await fetchAssessments("/seqta/student/assessment/list/upcoming"); + const foundUpcoming = (upcomingPayload || []).find((a: any) => a.id === assessmentId); if (foundUpcoming) return foundUpcoming.title; - throw new Error( - `Assessment with ID ${assessmentId} not found in past or upcoming.`, - ); + throw new Error(`Assessment with ID ${assessmentId} not found in past or upcoming.`); } catch (error) { if (retryCount < NOTIFICATIONS_RATE_LIMIT.maxRetries) { const retryDelay = NOTIFICATIONS_RATE_LIMIT.baseDelay * Math.pow(NOTIFICATIONS_RATE_LIMIT.backoffMultiplier, retryCount); await delay(Math.min(retryDelay, NOTIFICATIONS_RATE_LIMIT.maxDelay)); - return fetchAssessmentName( - assessmentId, - metaclassId, - programmeId, - retryCount + 1, - ); + return fetchAssessmentName(assessmentId, metaclassId, programmeId, retryCount + 1); } console.error( @@ -213,29 +196,19 @@ export const notificationsJob: Job = { ); } } catch (error) { - console.warn( - "[Notifications job] Failed to start streaming session:", - error, - ); + console.warn("[Notifications job] Failed to start streaming session:", error); } } const notificationIsIndexed = async (id: string): Promise => { try { const [inAssessments, inMessages] = await Promise.all([ - ctx - .getStoredItems("notifications") - .then((items) => items.some((i) => i.id === id)), - ctx - .getStoredItems("messages") - .then((items) => items.some((i) => i.id === id)), + ctx.getStoredItems("notifications").then((items) => items.some((i) => i.id === id)), + ctx.getStoredItems("messages").then((items) => items.some((i) => i.id === id)), ]); return inAssessments || inMessages; } catch (error) { - console.warn( - `[Notifications job] Error checking if notification ${id} is indexed:`, - error, - ); + console.warn(`[Notifications job] Error checking if notification ${id} is indexed:`, error); return false; } }; @@ -254,27 +227,18 @@ export const notificationsJob: Job = { const retryBatch = progress.retryQueue.slice(0, 3); for (const notificationId of retryBatch) { - const notification = notifications.find( - (n) => n.notificationID === notificationId, - ); + const notification = notifications.find((n) => n.notificationID === notificationId); if (!notification) { - progress.retryQueue = progress.retryQueue.filter( - (id) => id !== notificationId, - ); + progress.retryQueue = progress.retryQueue.filter((id) => id !== notificationId); continue; } await delay(progress.currentDelay); try { - const { success, item } = await processNotification( - notification, - ctx, - ); + const { success, item } = await processNotification(notification, ctx); if (success) { - progress.retryQueue = progress.retryQueue.filter( - (id) => id !== notificationId, - ); + progress.retryQueue = progress.retryQueue.filter((id) => id !== notificationId); progress.failedRequests = Math.max(0, progress.failedRequests - 1); progress.currentDelay = Math.max( progress.currentDelay * 0.9, @@ -328,10 +292,7 @@ export const notificationsJob: Job = { } } } catch (error) { - console.error( - `[Notifications job] Failed to process notification ${id}:`, - error, - ); + console.error(`[Notifications job] Failed to process notification ${id}:`, error); if (progress.retryQueue.length < 10) { progress.retryQueue.push(notif.notificationID); @@ -357,10 +318,7 @@ export const notificationsJob: Job = { ); itemsToStream.length = 0; } catch (error) { - console.warn( - "[Notifications job] Failed to stream items to vector worker:", - error, - ); + console.warn("[Notifications job] Failed to stream items to vector worker:", error); } } @@ -371,11 +329,7 @@ export const notificationsJob: Job = { if (items.length > 0) { try { - publishDynamicItemsUpdate( - await loadAllStoredItems(), - "notifications", - items.length, - ); + publishDynamicItemsUpdate(await loadAllStoredItems(), "notifications", items.length); } catch (error) { console.warn( "[Notifications job] Failed to dispatch incremental search update:", @@ -394,10 +348,7 @@ export const notificationsJob: Job = { `[Notifications job] Streamed final ${itemsToStream.length} items to vector worker (total: ${itemsStreamedToVector})`, ); } catch (error) { - console.warn( - "[Notifications job] Failed to stream final items to vector worker:", - error, - ); + console.warn("[Notifications job] Failed to stream final items to vector worker:", error); } } @@ -409,18 +360,12 @@ export const notificationsJob: Job = { ); progress.streamingStarted = false; } catch (error) { - console.warn( - "[Notifications job] Failed to end streaming session:", - error, - ); + console.warn("[Notifications job] Failed to end streaming session:", error); } } if (items.length) { - const latest = Math.max( - ...items.map((i) => i.dateAdded), - progress.lastTs, - ); + const latest = Math.max(...items.map((i) => i.dateAdded), progress.lastTs); progress.lastTs = latest; } @@ -450,11 +395,7 @@ async function processNotification( if (notif.type === "coneqtassessments") { const a = notif.coneqtAssessments; - const content = await fetchAssessmentName( - a.assessmentID, - a.metaclassID, - a.programmeID, - ); + const content = await fetchAssessmentName(a.assessmentID, a.metaclassID, a.programmeID); const item: IndexItem = { id, @@ -502,10 +443,7 @@ async function processNotification( return { success: false }; } catch (error) { - console.error( - `[Notifications job] Error processing notification ${id}:`, - error, - ); + console.error(`[Notifications job] Error processing notification ${id}:`, error); return { success: false }; } } diff --git a/src/plugins/built-in/globalSearch/src/indexing/jobs/portals.ts b/src/plugins/built-in/globalSearch/src/indexing/jobs/portals.ts index 83350310..9fb351e6 100644 --- a/src/plugins/built-in/globalSearch/src/indexing/jobs/portals.ts +++ b/src/plugins/built-in/globalSearch/src/indexing/jobs/portals.ts @@ -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 the user's external portal entries from `/seqta/student/load/portals`. * diff --git a/src/plugins/built-in/globalSearch/src/indexing/jobs/reports.ts b/src/plugins/built-in/globalSearch/src/indexing/jobs/reports.ts index eb67b07d..c6c92b8e 100644 --- a/src/plugins/built-in/globalSearch/src/indexing/jobs/reports.ts +++ b/src/plugins/built-in/globalSearch/src/indexing/jobs/reports.ts @@ -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 report metadata from `/seqta/student/load/reports`. * diff --git a/src/plugins/built-in/globalSearch/src/indexing/jobs/subjects.ts b/src/plugins/built-in/globalSearch/src/indexing/jobs/subjects.ts index 2338b0c1..f642fac6 100755 --- a/src/plugins/built-in/globalSearch/src/indexing/jobs/subjects.ts +++ b/src/plugins/built-in/globalSearch/src/indexing/jobs/subjects.ts @@ -1,6 +1,6 @@ import type { IndexItem, Job } from "../types"; -import { verboseDebug } from '@/utils/verboseLog'; +import { verboseDebug } from "@/utils/verboseLog"; const fetchSubjects = async () => { const res = await fetch(`${location.origin}/seqta/student/load/subjects`, { method: "POST", @@ -32,14 +32,12 @@ export const subjectsJob: Job = { } else { score -= 50; // Penalty for inactive subjects } - + return score; }, run: async (ctx) => { - const existingIds = new Set( - (await ctx.getStoredItems("subjects")).map((i) => i.id), - ); + const existingIds = new Set((await ctx.getStoredItems("subjects")).map((i) => i.id)); let list; try { @@ -96,12 +94,12 @@ export const subjectsJob: Job = { semesterCode: semester.code, semesterDescription: semester.description, type: "assessments", - isActive + isActive, }, actionId: "subjectassessment", renderComponentId: "subject", }; - + const courseItem = { id: `${id}-course`, text: `${subject.title}`, @@ -116,16 +114,13 @@ export const subjectsJob: Job = { semesterCode: semester.code, semesterDescription: semester.description, type: "course", - isActive + isActive, }, actionId: "subjectcourse", renderComponentId: "subject", }; - items.push( - assessmentsItem, - courseItem - ); + items.push(assessmentsItem, courseItem); } } @@ -137,4 +132,4 @@ export const subjectsJob: Job = { // Keep all subjects as they are relatively static return items; }, -}; \ No newline at end of file +}; diff --git a/src/plugins/built-in/globalSearch/src/indexing/passiveObserver.ts b/src/plugins/built-in/globalSearch/src/indexing/passiveObserver.ts index fe3eef46..377088af 100644 --- a/src/plugins/built-in/globalSearch/src/indexing/passiveObserver.ts +++ b/src/plugins/built-in/globalSearch/src/indexing/passiveObserver.ts @@ -1,11 +1,6 @@ import type { IndexItem } from "./types"; import { getAll, put } from "./db"; -import { - buildIndexItem, - extractTextFromValue, - pickId, - pickTitle, -} from "./extract"; +import { buildIndexItem, extractTextFromValue, pickId, pickTitle } from "./extract"; import { verboseDebug } from "@/utils/verboseLog"; import { isSensitiveSeqtaPath, normalizeSeqtaPath } from "./api"; import { mergeDynamicItems } from "../utils/dynamicItems"; @@ -83,7 +78,10 @@ interface CapturedContext { function categoryFromRoute(route: string): string { // /seqta/student/load/courses -> courses // /seqta/student/load/message -> message - const tail = route.replace(/^\/seqta\/student\//, "").split("/").filter(Boolean); + const tail = route + .replace(/^\/seqta\/student\//, "") + .split("/") + .filter(Boolean); if (tail.length === 0) return "passive"; // message/people is a support endpoint that backs the messages compose UI. // We treat it as a low-priority `messages-support` record rather than a @@ -111,13 +109,7 @@ function isPeopleEntityWorthIndexing(entity: unknown): boolean { "given", "givenName", ]); - const last = stringField(obj, [ - "surname", - "lastname", - "lastName", - "last_name", - "familyName", - ]); + const last = stringField(obj, ["surname", "lastname", "lastName", "last_name", "familyName"]); const display = stringField(obj, ["displayName", "name", "fullName"]); return Boolean((first && last) || display); } @@ -158,12 +150,8 @@ function extractProgrammeMetaclass( src: Record | null, ): { programme: number; metaclass: number } | null => { if (!src) return null; - const programme = coerce( - src.programme ?? src.programmeId ?? src.programmeID, - ); - const metaclass = coerce( - src.metaclass ?? src.metaclassId ?? src.metaclassID ?? src.subjectId, - ); + const programme = coerce(src.programme ?? src.programmeId ?? src.programmeID); + const metaclass = coerce(src.metaclass ?? src.metaclassId ?? src.metaclassID ?? src.subjectId); if (programme !== undefined && metaclass !== undefined) { return { programme, metaclass }; } @@ -189,15 +177,7 @@ function entitiesFromPayload(payload: unknown): unknown[] { // `.items`, `.tasks`, etc. Pull the first array-shaped child as our // best guess; if none exists, fall back to the object itself so we // still index a single entry. - for (const key of [ - "list", - "items", - "messages", - "tasks", - "pending", - "forums", - "docs", - ]) { + for (const key of ["list", "items", "messages", "tasks", "pending", "forums", "docs"]) { const value = obj[key]; if (Array.isArray(value)) return value; } @@ -229,9 +209,7 @@ const DEEP_LINK_FIELDS = [ "messageId", ] as const; -function pickDeepLinkHints( - entity: unknown, -): Record { +function pickDeepLinkHints(entity: unknown): Record { if (!entity || typeof entity !== "object") return {}; const src = entity as Record; const out: Record = {}; @@ -246,10 +224,7 @@ function pickDeepLinkHints( return out; } -function stringField( - entity: Record, - keys: readonly string[], -): string | undefined { +function stringField(entity: Record, keys: readonly string[]): string | undefined { for (const key of keys) { const value = entity[key]; if (typeof value === "string" && value.trim()) return value.trim(); @@ -274,13 +249,7 @@ function titleFromEndpoint( "given", "givenName", ]); - const last = stringField(obj, [ - "surname", - "lastname", - "lastName", - "last_name", - "familyName", - ]); + const last = stringField(obj, ["surname", "lastname", "lastName", "last_name", "familyName"]); const full = [first, last].filter(Boolean).join(" ").trim(); if (full) return full.slice(0, 200); } @@ -354,9 +323,7 @@ function passiveEntityToIndexItem( sourcePage, ...(isPeopleSupport ? { supportRecord: true, priority: "low" } : {}), ...deepLinkHints, - ...(coursePm - ? { programme: coursePm.programme, metaclass: coursePm.metaclass } - : {}), + ...(coursePm ? { programme: coursePm.programme, metaclass: coursePm.metaclass } : {}), }, actionId: "passive", renderComponentId: "passive", @@ -364,10 +331,7 @@ function passiveEntityToIndexItem( }); } -function synthesizeItems( - ctx: CapturedContext, - payload: unknown, -): IndexItem[] { +function synthesizeItems(ctx: CapturedContext, payload: unknown): IndexItem[] { if (isAssessmentListRoute(ctx.route)) return []; const entities = entitiesFromPayload(payload); @@ -403,10 +367,7 @@ async function persistItems(items: IndexItem[]): Promise { await put(STORE_ID, item, item.id); pendingChangedItems.set(item.id, item); } catch (e) { - console.warn( - `[Passive Observer] Failed to persist item ${item.id}:`, - e, - ); + console.warn(`[Passive Observer] Failed to persist item ${item.id}:`, e); } } @@ -468,10 +429,7 @@ async function handleCapturedPayload( requestBody: unknown, payload: unknown, ): Promise { - const items = synthesizeItems( - { route, requestBody, observedAt: Date.now() }, - payload, - ); + const items = synthesizeItems({ route, requestBody, observedAt: Date.now() }, payload); if (items.length > 0) { await persistItems(items); } @@ -541,17 +499,10 @@ export function installPassiveObserver(): void { try { const url = - typeof input === "string" - ? input - : input instanceof URL - ? input.toString() - : input.url; + typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url; if (isSameOriginSeqtaUrl(url)) { const body = init?.body; - const parsed = - body && typeof body === "string" - ? tryParseJson(body) - : undefined; + const parsed = body && typeof body === "string" ? tryParseJson(body) : undefined; // Fire-and-forget: never block the host page on indexing work. void consumeResponse(response, url, parsed); } @@ -582,15 +533,11 @@ export function installPassiveObserver(): void { } return originalOpen.call(this, method, url, ...rest); }; - ProtoXhr.send = function patchedSend( - this: XMLHttpRequest, - body?: any, - ) { + ProtoXhr.send = function patchedSend(this: XMLHttpRequest, body?: any) { try { const url = (this as any).__bsplusUrl as string | undefined; if (url && isSameOriginSeqtaUrl(url)) { - const parsed = - typeof body === "string" ? tryParseJson(body) : undefined; + const parsed = typeof body === "string" ? tryParseJson(body) : undefined; this.addEventListener("load", () => { try { if (this.status < 200 || this.status >= 300) return; diff --git a/src/plugins/built-in/globalSearch/src/indexing/resetIndexes.ts b/src/plugins/built-in/globalSearch/src/indexing/resetIndexes.ts index 77937cf6..fd033874 100644 --- a/src/plugins/built-in/globalSearch/src/indexing/resetIndexes.ts +++ b/src/plugins/built-in/globalSearch/src/indexing/resetIndexes.ts @@ -47,9 +47,7 @@ const STRUCTURED_DB = "betterseqta-index"; const VECTOR_DB = "embeddiaDB"; const STRUCTURED_VERSION_KEY = "betterseqta-index-version"; -function tryDeleteDatabase( - name: string, -): Promise<"success" | "blocked" | "error"> { +function tryDeleteDatabase(name: string): Promise<"success" | "blocked" | "error"> { return new Promise((resolve) => { let req: IDBOpenDBRequest; try { @@ -91,15 +89,9 @@ async function deleteIndexedDb(name: string): Promise { export async function resetSearchIndexes(): Promise { try { if (typeof window !== "undefined") { - window.dispatchEvent( - new CustomEvent("betterseqta-clear-search-cache"), - ); - window.dispatchEvent( - new CustomEvent("betterseqta-clear-embedding-cache"), - ); - window.dispatchEvent( - new CustomEvent("betterseqta-reset-search-index"), - ); + window.dispatchEvent(new CustomEvent("betterseqta-clear-search-cache")); + window.dispatchEvent(new CustomEvent("betterseqta-clear-embedding-cache")); + window.dispatchEvent(new CustomEvent("betterseqta-reset-search-index")); } } catch { /* ignore */ @@ -107,10 +99,7 @@ export async function resetSearchIndexes(): Promise { await delay(300); - await Promise.allSettled([ - deleteIndexedDb(STRUCTURED_DB), - deleteIndexedDb(VECTOR_DB), - ]); + await Promise.allSettled([deleteIndexedDb(STRUCTURED_DB), deleteIndexedDb(VECTOR_DB)]); try { localStorage.removeItem(STRUCTURED_VERSION_KEY); diff --git a/src/plugins/built-in/globalSearch/src/indexing/routeFilters.test.ts b/src/plugins/built-in/globalSearch/src/indexing/routeFilters.test.ts index c1c7e069..dc2193ff 100644 --- a/src/plugins/built-in/globalSearch/src/indexing/routeFilters.test.ts +++ b/src/plugins/built-in/globalSearch/src/indexing/routeFilters.test.ts @@ -2,12 +2,8 @@ import { isAssessmentListRoute } from "./routeFilters"; describe("isAssessmentListRoute", () => { it("matches past and upcoming assessment list routes", () => { - expect(isAssessmentListRoute("/seqta/student/assessment/list/past?")).toBe( - true, - ); - expect( - isAssessmentListRoute("/seqta/student/assessment/list/upcoming?"), - ).toBe(true); + expect(isAssessmentListRoute("/seqta/student/assessment/list/past?")).toBe(true); + expect(isAssessmentListRoute("/seqta/student/assessment/list/upcoming?")).toBe(true); }); it("does not match unrelated routes", () => { diff --git a/src/plugins/built-in/globalSearch/src/indexing/routeFilters.ts b/src/plugins/built-in/globalSearch/src/indexing/routeFilters.ts index b5bd4ab8..ef741bb2 100644 --- a/src/plugins/built-in/globalSearch/src/indexing/routeFilters.ts +++ b/src/plugins/built-in/globalSearch/src/indexing/routeFilters.ts @@ -2,7 +2,6 @@ export function isAssessmentListRoute(route: string): boolean { const normalized = route.toLowerCase(); return ( - normalized.includes("/assessment/list/past") || - normalized.includes("/assessment/list/upcoming") + normalized.includes("/assessment/list/past") || normalized.includes("/assessment/list/upcoming") ); } diff --git a/src/plugins/built-in/globalSearch/src/indexing/selfTests.ts b/src/plugins/built-in/globalSearch/src/indexing/selfTests.ts index 053219e8..66b36d7b 100644 --- a/src/plugins/built-in/globalSearch/src/indexing/selfTests.ts +++ b/src/plugins/built-in/globalSearch/src/indexing/selfTests.ts @@ -53,17 +53,13 @@ function assertEqual(actual: T, expected: T, label: string) { function assertContains(haystack: string, needle: string, label: string) { if (!haystack.includes(needle)) { - throw new AssertionError( - `${label}: expected "${haystack}" to contain "${needle}"`, - ); + throw new AssertionError(`${label}: expected "${haystack}" to contain "${needle}"`); } } function assertNotContains(haystack: string, needle: string, label: string) { if (haystack.includes(needle)) { - throw new AssertionError( - `${label}: expected "${haystack}" NOT to contain "${needle}"`, - ); + throw new AssertionError(`${label}: expected "${haystack}" NOT to contain "${needle}"`); } } @@ -77,9 +73,7 @@ const cases: TestCase[] = [ "trailing token", ); assertEqual( - normalizeSeqtaPath( - "https://learn.example.com/seqta/student/load/courses?abc123", - ), + normalizeSeqtaPath("https://learn.example.com/seqta/student/load/courses?abc123"), "/seqta/student/load/courses", "absolute URL", ); @@ -88,34 +82,13 @@ const cases: TestCase[] = [ { name: "isSensitiveSeqtaPath catches credential routes", run: () => { - assert( - isSensitiveSeqtaPath("/seqta/student/login?xyz"), - "login is sensitive", - ); - assert( - isSensitiveSeqtaPath("/seqta/student/save/message"), - "save/* is sensitive", - ); - assert( - isSensitiveSeqtaPath("/seqta/student/load/settings"), - "settings is sensitive", - ); - assert( - isSensitiveSeqtaPath("/seqta/student/load/prefs?z=1"), - "prefs is sensitive", - ); - assert( - isSensitiveSeqtaPath("/seqta/ta/masquerade"), - "masquerade is sensitive", - ); - assert( - !isSensitiveSeqtaPath("/seqta/student/load/messages"), - "messages is NOT sensitive", - ); - assert( - !isSensitiveSeqtaPath("/seqta/student/load/courses"), - "courses is NOT sensitive", - ); + assert(isSensitiveSeqtaPath("/seqta/student/login?xyz"), "login is sensitive"); + assert(isSensitiveSeqtaPath("/seqta/student/save/message"), "save/* is sensitive"); + assert(isSensitiveSeqtaPath("/seqta/student/load/settings"), "settings is sensitive"); + assert(isSensitiveSeqtaPath("/seqta/student/load/prefs?z=1"), "prefs is sensitive"); + assert(isSensitiveSeqtaPath("/seqta/ta/masquerade"), "masquerade is sensitive"); + assert(!isSensitiveSeqtaPath("/seqta/student/load/messages"), "messages is NOT sensitive"); + assert(!isSensitiveSeqtaPath("/seqta/student/load/courses"), "courses is NOT sensitive"); }, }, { @@ -150,14 +123,8 @@ const cases: TestCase[] = [ looksLikeSecretValue("a".repeat(40) + "b".repeat(40)), "long base64-ish string looks secret", ); - assert( - !looksLikeSecretValue("Hello world"), - "short readable text is safe", - ); - assert( - !looksLikeSecretValue("https://example.com/foo/bar"), - "URLs are not secrets", - ); + assert(!looksLikeSecretValue("Hello world"), "short readable text is safe"); + assert(!looksLikeSecretValue("https://example.com/foo/bar"), "URLs are not secrets"); assert( !looksLikeSecretValue("3162189c-2052-4f83-ad83-a66c57460ea2"), "UUIDs are useful and not secret", @@ -191,16 +158,8 @@ const cases: TestCase[] = [ { name: "pickTitle / pickId prefer common SEQTA fields", run: () => { - assertEqual( - pickTitle({ title: "Hello", name: "Other" }), - "Hello", - "title wins over name", - ); - assertEqual( - pickTitle({ filename: "doc.pdf" }), - "doc.pdf", - "filename fallback", - ); + assertEqual(pickTitle({ title: "Hello", name: "Other" }), "Hello", "title wins over name"); + assertEqual(pickTitle({ filename: "doc.pdf" }), "doc.pdf", "filename fallback"); assertEqual(pickId({ id: 42 }), "42", "numeric id stringified"); assertEqual(pickId({ uuid: "abc" }), "abc", "uuid id"); }, @@ -224,10 +183,7 @@ const cases: TestCase[] = [ assertEqual(item.id, "x-1", "id propagated"); assertContains(item.content, "Hello", "html distilled"); assertNotContains(item.content, "should-be-stripped", "token stripped"); - assert( - !("apiKey" in (item.metadata as Record)), - "apiKey metadata stripped", - ); + assert(!("apiKey" in (item.metadata as Record)), "apiKey metadata stripped"); assertEqual(item.category, "passive", "category passes through"); }, }, @@ -246,8 +202,7 @@ const cases: TestCase[] = [ const subject = subjectsListPayload[0]?.subjects[0]; assert(subject, "fixture has at least one subject"); assert( - Number.isFinite(subject!.programme) && - Number.isFinite(subject!.metaclass), + Number.isFinite(subject!.programme) && Number.isFinite(subject!.metaclass), "programme & metaclass numeric", ); }, @@ -262,11 +217,7 @@ const cases: TestCase[] = [ { name: "notices fixture is HTML-bearing", run: () => { - assertContains( - noticesPayload[0]?.contents ?? "", - "

", - "notice html present", - ); + assertContains(noticesPayload[0]?.contents ?? "", "

", "notice html present"); }, }, { @@ -307,8 +258,7 @@ export async function runGlobalSearchSelfTests(): Promise { report.passed++; } catch (e) { report.failed++; - const error = - e instanceof Error ? `${e.name}: ${e.message}` : String(e); + const error = e instanceof Error ? `${e.name}: ${e.message}` : String(e); report.failures.push({ name: test.name, error }); } } diff --git a/src/plugins/built-in/globalSearch/src/indexing/types.ts b/src/plugins/built-in/globalSearch/src/indexing/types.ts index 22a84c5c..1cb18b3f 100644 --- a/src/plugins/built-in/globalSearch/src/indexing/types.ts +++ b/src/plugins/built-in/globalSearch/src/indexing/types.ts @@ -25,11 +25,7 @@ export interface JobContext { getProgress: () => Promise; setProgress: (progress: T) => Promise; /** Optional live status/progress while a long-running job is in flight. */ - reportJobProgress?: (detail: { - processed: number; - total: number; - status?: string; - }) => void; + reportJobProgress?: (detail: { processed: number; total: number; status?: string }) => void; } export interface Job { diff --git a/src/plugins/built-in/globalSearch/src/indexing/utils.ts b/src/plugins/built-in/globalSearch/src/indexing/utils.ts index f69ecdc0..d00e177e 100644 --- a/src/plugins/built-in/globalSearch/src/indexing/utils.ts +++ b/src/plugins/built-in/globalSearch/src/indexing/utils.ts @@ -19,9 +19,7 @@ export async function getVectorizedItemIds(): Promise> { } try { - const store = db - .transaction([EMBEDDIA_STORE], "readonly") - .objectStore(EMBEDDIA_STORE); + const store = db.transaction([EMBEDDIA_STORE], "readonly").objectStore(EMBEDDIA_STORE); const keys = await new Promise((resolve, reject) => { const req = store.getAllKeys(); req.onsuccess = () => resolve(req.result); @@ -70,16 +68,12 @@ export async function removeVectorEmbeddings(ids: string[]): Promise { } } -export async function pruneOrphanVectorEmbeddings( - liveItemIds: Set, -): Promise { +export async function pruneOrphanVectorEmbeddings(liveItemIds: Set): Promise { const vectorizedIds = await getVectorizedItemIds(); const orphanIds = [...vectorizedIds].filter((id) => !liveItemIds.has(id)); if (orphanIds.length > 0) { - console.debug( - `[Indexer] Pruning ${orphanIds.length} orphaned vector embedding(s)`, - ); + console.debug(`[Indexer] Pruning ${orphanIds.length} orphaned vector embedding(s)`); await removeVectorEmbeddings(orphanIds); } @@ -91,9 +85,7 @@ export function htmlToPlainText(rawHtml: string): string { const doc = parser.parseFromString(rawHtml, "text/html"); const { body } = doc; - body - .querySelectorAll("script,style,template,noscript,meta,link") - .forEach((el) => el.remove()); + body.querySelectorAll("script,style,template,noscript,meta,link").forEach((el) => el.remove()); body.querySelectorAll(".forward").forEach((el) => { let n: ChildNode | null = el; diff --git a/src/plugins/built-in/globalSearch/src/indexing/worker/vectorWorker.ts b/src/plugins/built-in/globalSearch/src/indexing/worker/vectorWorker.ts index c6cb3f5c..2e57a0a1 100644 --- a/src/plugins/built-in/globalSearch/src/indexing/worker/vectorWorker.ts +++ b/src/plugins/built-in/globalSearch/src/indexing/worker/vectorWorker.ts @@ -8,7 +8,8 @@ let ortWasmBase: string | null = null; async function configureOrtWasm(base: string): Promise { const { env } = await import("@huggingface/transformers"); - 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}/`; } let vectorIndex: EmbeddingIndex | null = null; let isInitialized = false; @@ -18,8 +19,9 @@ let loadedItemIds = new Set(); function isFirefoxWorker(): boolean { try { - return typeof navigator !== "undefined" && - navigator.userAgent.toLowerCase().includes("firefox"); + return ( + typeof navigator !== "undefined" && navigator.userAgent.toLowerCase().includes("firefox") + ); } catch { return false; } @@ -51,16 +53,18 @@ async function initWorker() { verboseDebug("Vector worker already initialized."); return; } - + // Skip initialization in Firefox if (isFirefoxWorker()) { - verboseDebug("[Vector Worker] Vector search not supported in Firefox - skipping initialization"); + verboseDebug( + "[Vector Worker] Vector search not supported in Firefox - skipping initialization", + ); isInitialized = true; initializationFailed = true; vectorIndex = null; return; } - + verboseDebug("Initializing vector worker..."); try { if (ortWasmBase) { @@ -82,16 +86,17 @@ async function initWorker() { } }); - verboseDebug( - `Vector index loaded ${loadedItemIds.size} unique items from IndexedDB.`, - ); + verboseDebug(`Vector index loaded ${loadedItemIds.size} unique items from IndexedDB.`); } else { verboseDebug("No existing vector index found in IndexedDB."); } isInitialized = true; verboseDebug("Vector worker initialized successfully."); } catch (e) { - console.warn("[Vector Worker] Failed to initialize vector worker (will use text search only):", e); + console.warn( + "[Vector Worker] Failed to initialize vector worker (will use text search only):", + e, + ); isInitialized = true; initializationFailed = true; vectorIndex = null; @@ -120,21 +125,14 @@ async function vectorizeItem( } } -async function startStreamingSession( - totalExpected: number, - batchSize: number = 5, -) { +async function startStreamingSession(totalExpected: number, batchSize: number = 5) { if (vectorUnavailable()) { - postVectorUnavailable( - "Vector search not available in Firefox - using text search only", - ); + postVectorUnavailable("Vector search not available in Firefox - using text search only"); return; } if (!vectorIndex) { - console.warn( - "Streaming requested but vector index not ready. Attempting init.", - ); + console.warn("Streaming requested but vector index not ready. Attempting init."); await initWorker(); if (!vectorIndex || initializationFailed) { postVectorUnavailable("Vector index not available - using text search only"); @@ -156,9 +154,7 @@ async function startStreamingSession( processingPromise: null, }; - verboseDebug( - `Started streaming session for ${totalExpected} items with batch size ${batchSize}`, - ); + verboseDebug(`Started streaming session for ${totalExpected} items with batch size ${batchSize}`); self.postMessage({ type: "streamingProgress", @@ -170,10 +166,7 @@ async function startStreamingSession( }); } -async function processStreamingBatch( - items: IndexItem[], - isLast: boolean = false, -) { +async function processStreamingBatch(items: IndexItem[], isLast: boolean = false) { if (!streamingSession?.isActive) { console.warn("Received streaming batch but no active session"); return; @@ -187,8 +180,7 @@ async function processStreamingBatch( ); const shouldProcess = - streamingSession.pendingItems.length >= streamingSession.batchSize || - isLast; + streamingSession.pendingItems.length >= streamingSession.batchSize || isLast; if (shouldProcess && !streamingSession.processingPromise) { streamingSession.processingPromise = processStreamingItems(); @@ -200,14 +192,8 @@ async function processStreamingItems() { return; } - while ( - streamingSession.pendingItems.length > 0 && - streamingSession.isActive - ) { - const batchToProcess = streamingSession.pendingItems.splice( - 0, - streamingSession.batchSize, - ); + while (streamingSession.pendingItems.length > 0 && streamingSession.isActive) { + const batchToProcess = streamingSession.pendingItems.splice(0, streamingSession.batchSize); const unprocessedItems = batchToProcess.filter((item) => { return item.id && !loadedItemIds.has(item.id); @@ -219,9 +205,7 @@ async function processStreamingItems() { continue; } - const vectorizationResults = await Promise.all( - unprocessedItems.map(vectorizeItem), - ); + const vectorizationResults = await Promise.all(unprocessedItems.map(vectorizeItem)); const successfullyVectorized = vectorizationResults.filter( (result) => result !== null, ) as (IndexItem & { embedding: number[] })[]; @@ -233,10 +217,7 @@ async function processStreamingItems() { loadedItemIds.add(item.id); }); - if ( - streamingSession.totalProcessed % 50 === 0 || - loadedItemIds.size % 200 === 0 - ) { + if (streamingSession.totalProcessed % 50 === 0 || loadedItemIds.size % 200 === 0) { await vectorIndex!.saveIndex("indexedDB"); verboseDebug( `Saved streaming index at ${streamingSession.totalProcessed} processed items (${loadedItemIds.size} total unique items)`, @@ -300,9 +281,7 @@ async function finalizeStreamingSession() { }, }); - verboseDebug( - `Streaming session completed: ${totalProcessed}/${totalExpected} items processed`, - ); + verboseDebug(`Streaming session completed: ${totalProcessed}/${totalExpected} items processed`); } async function endStreamingSession() { @@ -356,9 +335,7 @@ async function processItems(items: IndexItem[], signal: AbortSignal) { } if (!vectorIndex) { - console.warn( - "Processing requested but vector index not ready. Attempting init.", - ); + console.warn("Processing requested but vector index not ready. Attempting init."); await initWorker(); if (!vectorIndex || initializationFailed) { postVectorUnavailable("Vector index not available - using text search only"); @@ -384,9 +361,7 @@ async function processItems(items: IndexItem[], signal: AbortSignal) { } if (unprocessedItems.length === 0) { - verboseDebug( - `No new items to process. ${loadedItemIds.size} items already in index.`, - ); + verboseDebug(`No new items to process. ${loadedItemIds.size} items already in index.`); self.postMessage({ type: "progress", data: { @@ -469,10 +444,7 @@ async function processItems(items: IndexItem[], signal: AbortSignal) { return; } - if ( - (i / BATCH_SIZE + 1) % 3 === 0 || - i + BATCH_SIZE >= unprocessedItems.length - ) { + if ((i / BATCH_SIZE + 1) % 3 === 0 || i + BATCH_SIZE >= unprocessedItems.length) { try { await vectorIndex!.saveIndex("indexedDB"); verboseDebug( @@ -499,9 +471,7 @@ async function processItems(items: IndexItem[], signal: AbortSignal) { }); } - verboseDebug( - `Processing complete. Total unique items in index: ${loadedItemIds.size}`, - ); + verboseDebug(`Processing complete. Total unique items in index: ${loadedItemIds.size}`); self.postMessage({ type: "progress", data: { @@ -537,9 +507,7 @@ async function resetWorker() { await initWorker(); - verboseDebug( - `Vector worker reset complete. Loaded ${loadedItemIds.size} items.`, - ); + verboseDebug(`Vector worker reset complete. Loaded ${loadedItemIds.size} items.`); self.postMessage({ type: "progress", diff --git a/src/plugins/built-in/globalSearch/src/indexing/worker/vectorWorkerManager.ts b/src/plugins/built-in/globalSearch/src/indexing/worker/vectorWorkerManager.ts index d33d3551..212802e0 100644 --- a/src/plugins/built-in/globalSearch/src/indexing/worker/vectorWorkerManager.ts +++ b/src/plugins/built-in/globalSearch/src/indexing/worker/vectorWorkerManager.ts @@ -4,7 +4,7 @@ import { isVectorSearchSupported } from "../../utils/browserDetection"; import { getOrtWasmBaseUrl } from "@/lib/transformersExtension"; import vectorWorker from "./vectorWorker.ts?inlineWorker"; -import { verboseDebug, verboseLog } from '@/utils/verboseLog'; +import { verboseDebug, verboseLog } from "@/utils/verboseLog"; import { delay } from "@/seqta/utils/delay"; export type ProgressCallback = (data: { status: "started" | "processing" | "complete" | "error" | "cancelled"; @@ -46,10 +46,7 @@ export class VectorWorkerManager { VectorWorkerManager.instance = new VectorWorkerManager(); } - if ( - !VectorWorkerManager.resetListenerInstalled && - typeof window !== "undefined" - ) { + if (!VectorWorkerManager.resetListenerInstalled && typeof window !== "undefined") { VectorWorkerManager.resetListenerInstalled = true; window.addEventListener("betterseqta-reset-search-index", () => { VectorWorkerManager.getInstance().terminate(); @@ -62,7 +59,9 @@ export class VectorWorkerManager { private async initWorker(): Promise { // Skip initialization if vector search is not supported (e.g., Firefox) if (!isVectorSearchSupported()) { - verboseDebug("[VectorWorkerManager] Vector search not supported - skipping worker initialization"); + verboseDebug( + "[VectorWorkerManager] Vector search not supported - skipping worker initialization", + ); this.isInitialized = false; return Promise.resolve(); } @@ -109,10 +108,7 @@ export class VectorWorkerManager { break; case "progress": - if ( - data.status === "processing" || - data.status === "started" - ) { + if (data.status === "processing" || data.status === "started") { this.bumpActivityDuringVectorization(); } if (this.progressCallback) { @@ -136,7 +132,11 @@ export class VectorWorkerManager { ); } - if (data.status === "complete" || data.status === "cancelled" || data.status === "error") { + if ( + data.status === "complete" || + data.status === "cancelled" || + data.status === "error" + ) { this.scheduleUnload(); } } @@ -279,9 +279,7 @@ export class VectorWorkerManager { } if (!this.isInitialized || !this.worker) { - throw new Error( - "Vector Worker is not available after initialization attempt.", - ); + throw new Error("Vector Worker is not available after initialization attempt."); } } @@ -291,7 +289,7 @@ export class VectorWorkerManager { if (onProgress) { onProgress({ status: "complete", - message: "Vector search not available - using text search only" + message: "Vector search not available - using text search only", }); } return; @@ -302,7 +300,7 @@ export class VectorWorkerManager { if (onProgress) { onProgress({ status: "complete", - message: "No items to process" + message: "No items to process", }); } return; @@ -323,7 +321,7 @@ export class VectorWorkerManager { if (onProgress) { onProgress({ status: "complete", - message: "No unique items to process after deduplication" + message: "No unique items to process after deduplication", }); } return; @@ -356,9 +354,7 @@ export class VectorWorkerManager { onProgress?.(data); if ( !settled && - (data.status === "complete" || - data.status === "error" || - data.status === "cancelled") + (data.status === "complete" || data.status === "error" || data.status === "cancelled") ) { settled = true; resolve(); @@ -366,9 +362,7 @@ export class VectorWorkerManager { }; this.progressCallback = wrap; - verboseDebug( - `Sending ${uniqueItems.length} unique items to worker for processing.`, - ); + verboseDebug(`Sending ${uniqueItems.length} unique items to worker for processing.`); this.worker!.postMessage({ type: "process", @@ -377,10 +371,7 @@ export class VectorWorkerManager { }); } finally { this.vectorizationLockCount = Math.max(0, this.vectorizationLockCount - 1); - if ( - this.vectorizationLockCount === 0 && - !this.streamingSession?.isActive - ) { + if (this.vectorizationLockCount === 0 && !this.streamingSession?.isActive) { this.startIdleTimer(); } } @@ -468,9 +459,7 @@ export class VectorWorkerManager { } if (!this.streamingSession?.isActive) { - verboseDebug( - "[VectorWorker] streamItems skipped — no active streaming session", - ); + verboseDebug("[VectorWorker] streamItems skipped — no active streaming session"); return; } @@ -495,18 +484,13 @@ export class VectorWorkerManager { this.streamingSession.inactivityTimer = setTimeout(() => { if (this.streamingSession?.isActive) { - verboseDebug( - "[VectorWorker] Auto-ending streaming session due to inactivity", - ); + verboseDebug("[VectorWorker] Auto-ending streaming session due to inactivity"); this.endStreamingSession(); } }, 30000); } - if ( - this.streamingSession.batchBuffer.length >= - this.streamingSession.batchSize - ) { + if (this.streamingSession.batchBuffer.length >= this.streamingSession.batchSize) { await this.flushBatch(); } else { if (this.streamingSession.flushTimer) { @@ -520,10 +504,7 @@ export class VectorWorkerManager { } private async flushBatch(): Promise { - if ( - !this.streamingSession?.isActive || - this.streamingSession.batchBuffer.length === 0 - ) { + if (!this.streamingSession?.isActive || this.streamingSession.batchBuffer.length === 0) { return; } @@ -544,9 +525,7 @@ export class VectorWorkerManager { type: "streamBatch", data: { items: batch, - isLast: - this.streamingSession.totalSent >= - this.streamingSession.totalExpected, + isLast: this.streamingSession.totalSent >= this.streamingSession.totalExpected, }, }); } @@ -591,7 +570,6 @@ export class VectorWorkerManager { return this.streamItems([item]); } - isStreamingActive(): boolean { return this.streamingSession?.isActive ?? false; } diff --git a/src/plugins/built-in/globalSearch/src/search/dedupeIndexItems.ts b/src/plugins/built-in/globalSearch/src/search/dedupeIndexItems.ts index 1086bfb1..942c6260 100644 --- a/src/plugins/built-in/globalSearch/src/search/dedupeIndexItems.ts +++ b/src/plugins/built-in/globalSearch/src/search/dedupeIndexItems.ts @@ -19,26 +19,17 @@ function shouldDedupeAsSameCourseSPA(item: IndexItem): boolean { if (item.renderComponentId === "course") return true; if (item.actionId === "course") return true; if (item.actionId === "subjectcourse") return true; - if ( - item.actionId === "passive" && - item.metadata?.sourcePage === "/courses" - ) { + if (item.actionId === "passive" && item.metadata?.sourcePage === "/courses") { return true; } return false; } -function programmeMetaclassIds( - item: IndexItem, -): { programme?: number; metaclass?: number } { +function programmeMetaclassIds(item: IndexItem): { programme?: number; metaclass?: number } { const md = item.metadata ?? {}; return { - programme: toFiniteNumber( - md.programme ?? md.programmeId ?? md.programmeID, - ), - metaclass: toFiniteNumber( - md.metaclass ?? md.metaclassId ?? md.metaclassID ?? md.subjectId, - ), + programme: toFiniteNumber(md.programme ?? md.programmeId ?? md.programmeID), + metaclass: toFiniteNumber(md.metaclass ?? md.metaclassId ?? md.metaclassID ?? md.subjectId), }; } @@ -64,9 +55,7 @@ function shouldDedupeAsSameAssessmentSPA(item: IndexItem): boolean { export function assessmentDestinationKey(item: IndexItem): string | undefined { if (!shouldDedupeAsSameAssessmentSPA(item)) return undefined; const md = item.metadata ?? {}; - const assessmentId = toFiniteNumber( - md.assessmentId ?? md.assessmentID ?? md.entityId, - ); + const assessmentId = toFiniteNumber(md.assessmentId ?? md.assessmentID ?? md.entityId); if (assessmentId === undefined) return undefined; return `assessment:${assessmentId}`; } @@ -76,9 +65,7 @@ function searchDedupeKey(item: IndexItem): string | undefined { } function isPassiveLike(item: IndexItem): boolean { - return ( - item.actionId === "passive" || item.metadata?.source === "passive" - ); + return item.actionId === "passive" || item.metadata?.source === "passive"; } function hasProgrammeMetaclass(item: IndexItem): boolean { @@ -93,10 +80,8 @@ function pickBetterCourseNavDuplicate(a: IndexItem, b: IndexItem): IndexItem { if (!aP && bP) return a; if (a.category === "courses" && b.category !== "courses") return a; if (b.category === "courses" && a.category !== "courses") return b; - if (a.renderComponentId === "course" && b.renderComponentId !== "course") - return a; - if (b.renderComponentId === "course" && a.renderComponentId !== "course") - return b; + if (a.renderComponentId === "course" && b.renderComponentId !== "course") return a; + if (b.renderComponentId === "course" && a.renderComponentId !== "course") return b; const ad = typeof a.dateAdded === "number" ? a.dateAdded : 0; const bd = typeof b.dateAdded === "number" ? b.dateAdded : 0; return ad >= bd ? a : b; @@ -118,11 +103,7 @@ function pickBetterAssessmentDuplicate(a: IndexItem, b: IndexItem): IndexItem { return ad >= bd ? a : b; } -function pickBetterSearchDuplicate( - a: IndexItem, - b: IndexItem, - key: string, -): IndexItem { +function pickBetterSearchDuplicate(a: IndexItem, b: IndexItem, key: string): IndexItem { return key.startsWith("assessment:") ? pickBetterAssessmentDuplicate(a, b) : pickBetterCourseNavDuplicate(a, b); @@ -185,12 +166,6 @@ function mergeCombinedDuplicates( }; } -export function dedupeCombinedResultsByCourseNav( - results: CombinedResult[], -): CombinedResult[] { - return dedupeByCanonicalKey( - results, - dynamicSearchKey, - mergeCombinedDuplicates, - ); +export function dedupeCombinedResultsByCourseNav(results: CombinedResult[]): CombinedResult[] { + return dedupeByCanonicalKey(results, dynamicSearchKey, mergeCombinedDuplicates); } diff --git a/src/plugins/built-in/globalSearch/src/search/hybridSearch.ts b/src/plugins/built-in/globalSearch/src/search/hybridSearch.ts index 6496fc60..eb7f841e 100644 --- a/src/plugins/built-in/globalSearch/src/search/hybridSearch.ts +++ b/src/plugins/built-in/globalSearch/src/search/hybridSearch.ts @@ -23,15 +23,13 @@ function isIndexItem(item: CombinedResult["item"]): item is IndexItem { */ function isWeakSemanticQuery(trimmedQuery: string): boolean { if (trimmedQuery.length < 8) return true; - const meaningfulTokens = trimmedQuery - .split(/\s+/) - .filter((t) => t.length >= 3); + const meaningfulTokens = trimmedQuery.split(/\s+/).filter((t) => t.length >= 3); return meaningfulTokens.length < 2; } /** * Hybrid Search Implementation - * + * * Flow: * 1. BM25 (Fuse.js) gets top N results fast * 2. Vector search reranks by semantic similarity @@ -136,34 +134,33 @@ export async function hybridSearch( ): Promise { const opts = { ...DEFAULT_OPTIONS, ...options }; const trimmedQuery = query.trim().toLowerCase(); - + if (bm25Results.length === 0) { return []; } - + const topBm25Results = bm25Results.slice(0, opts.bm25TopK); if (trimmedQuery.length > 2) { try { const vectorTopK = opts.bm25TopK * 2; const vectorSearchResults = - precomputedVectorResults ?? - (await searchVectors(trimmedQuery, vectorTopK)); - + precomputedVectorResults ?? (await searchVectors(trimmedQuery, vectorTopK)); + // Create a map of item ID to vector similarity const vectorMap = new Map(); - vectorSearchResults.forEach(v => { + vectorSearchResults.forEach((v) => { // Use the highest similarity if item appears multiple times const existing = vectorMap.get(v.object.id); if (!existing || v.similarity > existing) { vectorMap.set(v.object.id, v.similarity); } }); - + // Now rerank BM25 results with vector scores const now = Date.now(); - - const rerankedResults: CombinedResult[] = topBm25Results.map(result => { + + const rerankedResults: CombinedResult[] = topBm25Results.map((result) => { const item = result.item; // Static command items don't have dateAdded/metadata/category to score @@ -190,7 +187,7 @@ export async function hybridSearch( const job = jobs[item.category]; let jobBoost = 0; - if (job && typeof job.boostCriteria === 'function') { + if (job && typeof job.boostCriteria === "function") { const boost = job.boostCriteria(item, trimmedQuery); if (boost) { jobBoost = boost / 100; @@ -206,8 +203,8 @@ export async function hybridSearch( else if (lexicalQuality >= 8) lexicalBonus += 0.14; const hybridScore = - (normalizedBm25Score * opts.bm25Weight) + - (vectorSimilarity * opts.vectorWeight) + + normalizedBm25Score * opts.bm25Weight + + vectorSimilarity * opts.vectorWeight + recencyBoost + popularityBoost + jobBoost + @@ -218,17 +215,16 @@ export async function hybridSearch( score: hybridScore * 100, }; }); - + rerankedResults.sort((a, b) => b.score - a.score); - + return rerankedResults.slice(0, opts.finalLimit); - } catch (e) { console.warn("[Hybrid Search] Vector reranking failed, using BM25 only:", e); return topBm25Results.slice(0, opts.finalLimit); } } - + // If query is too short for vector search, just return BM25 results return topBm25Results.slice(0, opts.finalLimit); } @@ -259,12 +255,7 @@ export async function hybridSearchWithExpansion( } // Rerank BM25 results using the single vector pass above - const rerankedBm25 = await hybridSearch( - bm25Results, - query, - options, - vectorResults, - ); + const rerankedBm25 = await hybridSearch(bm25Results, query, options, vectorResults); // For short / single-token queries vector expansion brings in too much // noise (and is the main reason results "flicker" between adjacent @@ -274,7 +265,7 @@ export async function hybridSearchWithExpansion( } // Find vector results that weren't in BM25 results - const bm25Ids = new Set(bm25Results.map(r => r.item.id)); + const bm25Ids = new Set(bm25Results.map((r) => r.item.id)); const vectorOnlyResults: CombinedResult[] = []; const now = Date.now(); @@ -292,11 +283,9 @@ export async function hybridSearchWithExpansion( } } // Vector-only results may sit at most at this score: - const vectorOnlyCeiling = strongLexicalFloor === -Infinity - ? Infinity - : strongLexicalFloor - 1; + const vectorOnlyCeiling = strongLexicalFloor === -Infinity ? Infinity : strongLexicalFloor - 1; - vectorResults.forEach(v => { + vectorResults.forEach((v) => { if (bm25Ids.has(v.object.id)) return; // Drop stale vector hits for items no longer in the live structured index. @@ -332,7 +321,7 @@ export async function hybridSearchWithExpansion( // Apply job-specific boost if available const job = jobs[item.category]; let jobBoost = 0; - if (job && typeof job.boostCriteria === 'function') { + if (job && typeof job.boostCriteria === "function") { const boost = job.boostCriteria(item, trimmedQuery); if (boost) { jobBoost = boost / 100; // Normalize boost @@ -358,4 +347,3 @@ export async function hybridSearchWithExpansion( return allResults.slice(0, opts.finalLimit); } - diff --git a/src/plugins/built-in/globalSearch/src/search/lexicalMatch.ts b/src/plugins/built-in/globalSearch/src/search/lexicalMatch.ts index 4da9e3e2..40ac04d2 100644 --- a/src/plugins/built-in/globalSearch/src/search/lexicalMatch.ts +++ b/src/plugins/built-in/globalSearch/src/search/lexicalMatch.ts @@ -97,12 +97,8 @@ export function getLexicalMatchQuality(item: IndexItem, query: string): number { } const md = (item.metadata ?? {}) as Record; - const subjectName = normalize( - typeof md.subjectName === "string" ? md.subjectName : "", - ); - const subjectCode = normalize( - typeof md.subjectCode === "string" ? md.subjectCode : "", - ); + const subjectName = normalize(typeof md.subjectName === "string" ? md.subjectName : ""); + const subjectCode = normalize(typeof md.subjectCode === "string" ? md.subjectCode : ""); if (subjectName && (subjectName === q || subjectName.startsWith(q))) return 5; if (subjectCode && (subjectCode === q || subjectCode.startsWith(q))) return 5; diff --git a/src/plugins/built-in/globalSearch/src/search/searchUtils.ts b/src/plugins/built-in/globalSearch/src/search/searchUtils.ts index d27054bb..dbc9f51b 100644 --- a/src/plugins/built-in/globalSearch/src/search/searchUtils.ts +++ b/src/plugins/built-in/globalSearch/src/search/searchUtils.ts @@ -133,9 +133,7 @@ export interface DynamicItemsUpdatedDetail { newItemCount?: number; } -export function createDynamicContentFuse( - items: IndexItem[], -): Fuse { +export function createDynamicContentFuse(items: IndexItem[]): Fuse { return new Fuse(dedupeIndexItemsForSearch(items), DYNAMIC_FUSE_OPTIONS); } @@ -275,14 +273,14 @@ export function searchDynamicItems( const now = Date.now(); const queryLower = query.toLowerCase(); const queryTrimmed = query.trim(); - + // For short queries (3 chars or less), use a more permissive approach const isShortQuery = queryTrimmed.length <= 3; const searchLimit = Math.min(limit * 3, 50); - + // First, try Fuse.js search const searchResults = dynamicContentFuse.search(query, { limit: searchLimit }); - + // For short queries, always do a simple substring match to supplement Fuse.js results // This ensures we catch partial word matches like "SAT" in "SAT 1: Differential Calculus" let additionalMatches: IndexItem[] = []; @@ -290,17 +288,19 @@ export function searchDynamicItems( // Always do substring search for short queries to catch partial word matches for (const item of dynamicIdToItemMap.values()) { const textLower = item.text.toLowerCase(); - const contentLower = (item.content || '').toLowerCase(); - const subjectNameLower = (item.metadata?.subjectName || '').toLowerCase(); - const subjectCodeLower = (item.metadata?.subjectCode || '').toLowerCase(); - + const contentLower = (item.content || "").toLowerCase(); + const subjectNameLower = (item.metadata?.subjectName || "").toLowerCase(); + const subjectCodeLower = (item.metadata?.subjectCode || "").toLowerCase(); + // Check if query appears anywhere in the text, content, or metadata - if (textLower.includes(queryLower) || - contentLower.includes(queryLower) || - subjectNameLower.includes(queryLower) || - subjectCodeLower.includes(queryLower)) { + if ( + textLower.includes(queryLower) || + contentLower.includes(queryLower) || + subjectNameLower.includes(queryLower) || + subjectCodeLower.includes(queryLower) + ) { // Only add if not already in Fuse.js results - if (!searchResults.find(r => r.item.id === item.id)) { + if (!searchResults.find((r) => r.item.id === item.id)) { additionalMatches.push(item); } } @@ -350,7 +350,7 @@ export function searchDynamicItems( // Add additional matches from simple substring search additionalMatches.forEach((item) => { - if (!results.find(r => r.id === item.id)) { + if (!results.find((r) => r.id === item.id)) { let score = 5; // Base score for substring matches const lexicalQuality = getLexicalMatchQuality(item, queryLower); @@ -374,7 +374,6 @@ export function searchDynamicItems( return results.sort((a, b) => b.score - a.score).slice(0, limit); } - export async function performSearch( query: string, commandsFuse: Fuse, @@ -384,7 +383,7 @@ export async function performSearch( sortByRecent: boolean = true, ): Promise { const trimmedQuery = query.trim().toLowerCase(); - + if (trimmedQuery.length > 2) { const cached = getCachedResults(trimmedQuery); if (cached) { @@ -393,11 +392,7 @@ export async function performSearch( } // Step 1: Get command results (these don't need hybrid search) - const commandResults = searchCommands( - commandsFuse, - trimmedQuery, - commandIdToItemMap, - ); + const commandResults = searchCommands(commandsFuse, trimmedQuery, commandIdToItemMap); // Step 2: Get BM25 results for dynamic items let dynamicResults: CombinedResult[] = []; @@ -443,19 +438,14 @@ export async function performSearch( if (trimmedQuery.length > 2 && bm25Results.length > 0) { try { // Apply hybrid search with expansion - dynamicResults = await hybridSearchWithExpansion( - bm25Results, - trimmedQuery, - allItems, - { - bm25TopK: 50, - finalLimit: 20, // Return top 20 after reranking - recencyBoost: sortByRecent, - bm25Weight: 0.4, // 40% BM25, 60% vector - vectorWeight: 0.6, - recencyWeight: 0.1, - }, - ); + dynamicResults = await hybridSearchWithExpansion(bm25Results, trimmedQuery, allItems, { + bm25TopK: 50, + finalLimit: 20, // Return top 20 after reranking + recencyBoost: sortByRecent, + bm25Weight: 0.4, // 40% BM25, 60% vector + vectorWeight: 0.6, + recencyWeight: 0.1, + }); } catch (e) { console.warn("[Search] Hybrid search failed, using BM25 only:", e); dynamicResults = bm25Results.slice(0, 20); @@ -469,14 +459,10 @@ export async function performSearch( // Step 4: Combine command and dynamic results const allResults = [...commandResults, ...dynamicResults]; - allResults.sort((a, b) => - compareCombinedSearchResults(a, b, trimmedQuery), - ); + allResults.sort((a, b) => compareCombinedSearchResults(a, b, trimmedQuery)); const dedupedResults = dedupeCombinedResultsByCourseNav(allResults); - dedupedResults.sort((a, b) => - compareCombinedSearchResults(a, b, trimmedQuery), - ); + dedupedResults.sort((a, b) => compareCombinedSearchResults(a, b, trimmedQuery)); // Cache results for queries longer than 2 chars if (trimmedQuery.length > 2) { diff --git a/src/plugins/built-in/globalSearch/src/search/vector/vectorSearch.ts b/src/plugins/built-in/globalSearch/src/search/vector/vectorSearch.ts index 8e3b97b9..1327daf0 100644 --- a/src/plugins/built-in/globalSearch/src/search/vector/vectorSearch.ts +++ b/src/plugins/built-in/globalSearch/src/search/vector/vectorSearch.ts @@ -19,7 +19,9 @@ export function warmUpVectorSearchOnInteraction(): void { export async function initVectorSearch() { if (initializationFailed || !isVectorSearchSupported()) { if (!isVectorSearchSupported()) { - verboseDebug("[Vector Search] Vector search not supported in Firefox - using text search only"); + verboseDebug( + "[Vector Search] Vector search not supported in Firefox - using text search only", + ); } return; } @@ -35,7 +37,10 @@ export async function initVectorSearch() { vectorIndex.preloadIndexedDB(); verboseDebug("[Vector Search] Initialized successfully"); } catch (e) { - console.warn("[Vector Search] Failed to initialize vector search (will use text search only):", e); + console.warn( + "[Vector Search] Failed to initialize vector search (will use text search only):", + e, + ); initializationFailed = true; vectorIndex = null; } @@ -97,7 +102,7 @@ export async function searchVectors( }); return results - .filter((r) => r.similarity > 0.80) + .filter((r) => r.similarity > 0.8) .sort((a, b) => b.similarity - a.similarity) .slice(0, topK) as VectorSearchResult[]; } catch (e) { diff --git a/src/plugins/built-in/globalSearch/src/utils/HighlightedText.svelte b/src/plugins/built-in/globalSearch/src/utils/HighlightedText.svelte index 24786355..f12a27e8 100644 --- a/src/plugins/built-in/globalSearch/src/utils/HighlightedText.svelte +++ b/src/plugins/built-in/globalSearch/src/utils/HighlightedText.svelte @@ -20,7 +20,7 @@ ); if (!fieldMatches?.indices?.length) return [{ text, highlight: false }]; - const highlightMap = new Array(text.length).fill(false); + const highlightMap = Array.from({ length: text.length }, () => false); for (const [start, end] of fieldMatches.indices) { if (fieldMatches.key === 'allContent') { const textPos = fieldMatches.value?.indexOf(text) ?? -1; diff --git a/src/plugins/built-in/globalSearch/src/utils/browserDetection.ts b/src/plugins/built-in/globalSearch/src/utils/browserDetection.ts index 753d08b9..85171090 100644 --- a/src/plugins/built-in/globalSearch/src/utils/browserDetection.ts +++ b/src/plugins/built-in/globalSearch/src/utils/browserDetection.ts @@ -27,4 +27,3 @@ export function isFirefox(): boolean { export function isVectorSearchSupported(): boolean { return !isFirefox(); } - diff --git a/src/plugins/built-in/globalSearch/src/utils/calculator.test.ts b/src/plugins/built-in/globalSearch/src/utils/calculator.test.ts index 033bb71b..6b892476 100644 --- a/src/plugins/built-in/globalSearch/src/utils/calculator.test.ts +++ b/src/plugins/built-in/globalSearch/src/utils/calculator.test.ts @@ -1,7 +1,4 @@ -import { - calculateExpression, - isLikelyMathExpression, -} from "./calculator"; +import { calculateExpression, isLikelyMathExpression } from "./calculator"; describe("calculator", () => { it("rejects non-math text without needing mathjs for validity", () => { diff --git a/src/plugins/built-in/globalSearch/src/utils/calculator.ts b/src/plugins/built-in/globalSearch/src/utils/calculator.ts index 45a6c15b..668fcc49 100644 --- a/src/plugins/built-in/globalSearch/src/utils/calculator.ts +++ b/src/plugins/built-in/globalSearch/src/utils/calculator.ts @@ -1,4 +1,4 @@ -import { unitFullNames } from './unitMap'; +import { unitFullNames } from "./unitMap"; export interface CalculatorResult { result: string | null; @@ -21,10 +21,22 @@ type CalculatorMath = { const FORMAT_OPTS = { precision: 14, lowerExp: -15, upperExp: 15 } as const; const emptyResult = (error?: string): CalculatorResult => ({ - result: null, isValid: false, isPartial: false, inputUnit: '', outputUnit: '', error, + result: null, + isValid: false, + isPartial: false, + inputUnit: "", + outputUnit: "", + error, }); -const BLOCKED_MATH_FUNCTIONS = ['import', 'createUnit', 'random', 'pickRandom', 'chain', 'help'] as const; +const BLOCKED_MATH_FUNCTIONS = [ + "import", + "createUnit", + "random", + "pickRandom", + "chain", + "help", +] as const; let calculatorMathPromise: Promise | null = null; @@ -55,7 +67,7 @@ async function getCalculatorMath(): Promise { unaryMinusDependencies, unaryPlusDependencies, unitDependencies, - } = await import('mathjs'); + } = await import("mathjs"); const config = Object.assign( {}, @@ -85,7 +97,7 @@ async function getCalculatorMath(): Promise { const sandbox = create(config) as CalculatorMath; const blockFn = () => { - throw new Error('Function not allowed'); + throw new Error("Function not allowed"); }; const blocked: Record never> = {}; for (const name of BLOCKED_MATH_FUNCTIONS) blocked[name] = blockFn; @@ -106,28 +118,42 @@ function detectUnit(math: CalculatorMath, expression: string): string { } catch { /* ignore */ } - return ''; + return ""; } /** Cheap pre-check so SearchBar/Calculator never load mathjs for plain text. */ export function isLikelyMathExpression(input: string): boolean { const trimmed = input.trim(); if (!/[\d+\-*/^()=.]/.test(trimmed)) return false; - const nonMathWords = ['abs', 'function', 'class', 'const', 'let', 'var', 'if', 'else', 'while', 'for', 'return', 'import', 'export']; + const nonMathWords = [ + "abs", + "function", + "class", + "const", + "let", + "var", + "if", + "else", + "while", + "for", + "return", + "import", + "export", + ]; const words = trimmed.toLowerCase().split(/\s+/); if (words.length === 1 && nonMathWords.includes(words[0]) && !/\d/.test(trimmed)) return false; - return /(\d+\.?\d*|\+|\-|\*|\/|\^|\(|\)|sin|cos|tan|log|sqrt|pi|e|=)/i.test(trimmed); + return /(\d+\.?\d*|\+|-|\*|\/|\^|\(|\)|sin|cos|tan|log|sqrt|pi|e|=)/i.test(trimmed); } function tryCompleteExpression(math: CalculatorMath, expression: string): string | null { const trimmed = expression.trim(); - for (const pattern of [/[\+\-\*\/\^]\s*$/, /\(\s*$/, /[\+\-\*\/\^]\s*\(/]) { + for (const pattern of [/[-+*/^]\s*$/, /\(\s*$/, /[-+*/^]\s*\(/]) { if (!pattern.test(trimmed)) continue; - const partial = trimmed.replace(/[\+\-\*\/\^]\s*$/, '').trim(); - if (!partial || partial.match(/[\+\-\*\/\^]\s*$/)) continue; + const partial = trimmed.replace(/[-+*/^]\s*$/, "").trim(); + if (!partial || partial.match(/[-+*/^]\s*$/)) continue; try { const result = math.evaluate(partial); - if (typeof result === 'number' && !isNaN(result)) { + if (typeof result === "number" && !isNaN(result)) { return math.format(result, FORMAT_OPTS); } } catch { @@ -148,24 +174,30 @@ export async function calculateExpression(input: string): Promise [item.id, item])); - const kept = dynamicItems.filter( - (item) => !removeSet.has(item.id) && !changeMap.has(item.id), - ); + const kept = dynamicItems.filter((item) => !removeSet.has(item.id) && !changeMap.has(item.id)); dynamicItems = [...kept, ...changedItems]; } diff --git a/src/plugins/built-in/globalSearch/src/utils/hotkeyUtils.ts b/src/plugins/built-in/globalSearch/src/utils/hotkeyUtils.ts index 5741eb09..16ec89f8 100644 --- a/src/plugins/built-in/globalSearch/src/utils/hotkeyUtils.ts +++ b/src/plugins/built-in/globalSearch/src/utils/hotkeyUtils.ts @@ -19,32 +19,36 @@ export function isAllowedHotkeyKey(key: string): boolean { } export function parseHotkey(hotkeyString: string): ParsedHotkey { - const parts = hotkeyString.toLowerCase().split('+').map(part => part.trim()).filter(part => part.length > 0); - + const parts = hotkeyString + .toLowerCase() + .split("+") + .map((part) => part.trim()) + .filter((part) => part.length > 0); + const parsed: ParsedHotkey = { ctrl: false, meta: false, alt: false, shift: false, - key: '' + key: "", }; for (const part of parts) { switch (part) { - case 'ctrl': - case 'control': + case "ctrl": + case "control": parsed.ctrl = true; break; - case 'cmd': - case 'meta': - case 'command': + case "cmd": + case "meta": + case "command": parsed.meta = true; break; - case 'alt': - case 'option': + case "alt": + case "option": parsed.alt = true; break; - case 'shift': + case "shift": parsed.shift = true; break; default: @@ -63,56 +67,56 @@ export function formatHotkeyForDisplay(hotkeyString: string): string { try { const parsed = parseHotkey(hotkeyString); const parts: string[] = []; - - const isMac = (navigator.platform.toUpperCase().indexOf('MAC') >= 0); - + + const isMac = navigator.platform.toUpperCase().indexOf("MAC") >= 0; + if (parsed.ctrl) { - parts.push('Ctrl'); + parts.push("Ctrl"); } if (parsed.meta) { - parts.push('⌘'); + parts.push("⌘"); } if (parsed.alt) { - parts.push(isMac ? '⌥' : 'Alt'); + parts.push(isMac ? "⌥" : "Alt"); } if (parsed.shift) { - parts.push(isMac ? '⇧' : 'Shift'); + parts.push(isMac ? "⇧" : "Shift"); } - + if (parsed.key && isAllowedHotkeyKey(parsed.key)) { parts.push(parsed.key.toUpperCase()); } - - return parts.join(isMac ? ' ' : '+'); + + return parts.join(isMac ? " " : "+"); } catch (error) { - console.warn('Invalid hotkey string:', hotkeyString); - return 'Ctrl+K'; + console.warn("Invalid hotkey string:", hotkeyString); + return "Ctrl+K"; } } export function matchesHotkey(event: KeyboardEvent, hotkeyString: string): boolean { try { const parsed = parseHotkey(hotkeyString); - + // If no key is specified, don't match anything if (!parsed.key || !isAllowedHotkeyKey(parsed.key)) { return false; } - + if (parsed.ctrl && !event.ctrlKey) return false; if (parsed.meta && !event.metaKey) return false; if (parsed.alt && !event.altKey) return false; if (parsed.shift && !event.shiftKey) return false; - + // Check if we have extra modifiers that shouldn't be there if (!parsed.ctrl && event.ctrlKey) return false; if (!parsed.meta && event.metaKey) return false; if (!parsed.alt && event.altKey) return false; if (!parsed.shift && event.shiftKey) return false; - + return event.key.toLowerCase() === parsed.key.toLowerCase(); } catch (error) { - console.warn('Error matching hotkey:', hotkeyString, error); + console.warn("Error matching hotkey:", hotkeyString, error); return false; } } diff --git a/src/plugins/built-in/globalSearch/src/utils/unitMap.ts b/src/plugins/built-in/globalSearch/src/utils/unitMap.ts index eb6a8229..2f2e8716 100644 --- a/src/plugins/built-in/globalSearch/src/utils/unitMap.ts +++ b/src/plugins/built-in/globalSearch/src/utils/unitMap.ts @@ -177,7 +177,7 @@ export const unitFullNames: Record = { // --- Currency --- USD: "US Dollars", - EUR: "Euros", + EUR: "Euros", GBP: "British Pounds", AUD: "Australian Dollars", CAD: "Canadian Dollars", @@ -193,7 +193,7 @@ export const unitFullNames: Record = { KRW: "South Korean Won", MXN: "Mexican Peso", BRL: "Brazilian Real", - RUB: "Russian Ruble", + RUB: "Russian Ruble", TRY: "Turkish Lira", ZAR: "South African Rand", PLN: "Polish Zloty", @@ -205,7 +205,7 @@ export const unitFullNames: Record = { PHP: "Philippine Peso", TWD: "Taiwan Dollar", MYR: "Malaysian Ringgit", - + // --- Cryptocurrencies --- BTC: "Bitcoin", ETH: "Ethereum", diff --git a/src/plugins/built-in/globalSearch/src/utils/versionCheck.ts b/src/plugins/built-in/globalSearch/src/utils/versionCheck.ts index 11160b77..a5fc792f 100644 --- a/src/plugins/built-in/globalSearch/src/utils/versionCheck.ts +++ b/src/plugins/built-in/globalSearch/src/utils/versionCheck.ts @@ -62,7 +62,9 @@ export async function checkAndHandleUpdate(): Promise { try { await resetSearchIndexes(); - verboseLog("[Version Check] Search index reset; next indexing pass will repopulate from scratch."); + verboseLog( + "[Version Check] Search index reset; next indexing pass will repopulate from scratch.", + ); } catch (e) { console.warn("[Version Check] resetSearchIndexes failed:", e); } @@ -89,7 +91,8 @@ export async function clearAllCaches(): Promise { const { clearEmbeddingCache } = await import("../search/vector/vectorSearch"); clearEmbeddingCache(); } catch (e) { - if (!isAssetLoadError(e)) verboseDebug("[Version Check] Could not clear embedding cache:", e); + if (!isAssetLoadError(e)) + verboseDebug("[Version Check] Could not clear embedding cache:", e); } }, 50); diff --git a/src/plugins/built-in/gradeAnalytics/AssessmentTable.svelte b/src/plugins/built-in/gradeAnalytics/AssessmentTable.svelte index c029ee9e..ffc8a7bd 100644 --- a/src/plugins/built-in/gradeAnalytics/AssessmentTable.svelte +++ b/src/plugins/built-in/gradeAnalytics/AssessmentTable.svelte @@ -36,8 +36,8 @@ ); $effect(() => { - sortedData.length; - itemsPerPage; + void sortedData.length; + void itemsPerPage; const maxPage = Math.max(0, pageCount - 1); if (currentPage > maxPage) { currentPage = maxPage; diff --git a/src/plugins/built-in/gradeAnalytics/GradeAnalyticsPage.svelte b/src/plugins/built-in/gradeAnalytics/GradeAnalyticsPage.svelte index 8bb8712b..477248f4 100644 --- a/src/plugins/built-in/gradeAnalytics/GradeAnalyticsPage.svelte +++ b/src/plugins/built-in/gradeAnalytics/GradeAnalyticsPage.svelte @@ -82,7 +82,7 @@ const totalCount = $derived(analyticsData?.length ?? 0); const formattedTimestamp = $derived.by(() => { - timestampRefresh; + void timestampRefresh; return lastUpdated ? formatLastUpdated(lastUpdated) : ""; }); diff --git a/src/plugins/built-in/gradeAnalytics/api.test.ts b/src/plugins/built-in/gradeAnalytics/api.test.ts index a704f652..aafc80f7 100644 --- a/src/plugins/built-in/gradeAnalytics/api.test.ts +++ b/src/plugins/built-in/gradeAnalytics/api.test.ts @@ -53,15 +53,9 @@ it("removes cached custom rubric percentages when inference is disabled", async gradeSource: "customBand", }); - await saveGradeInferenceSettings( - origin, - 12, - DEFAULT_ANALYTICS_GRADE_INFERENCE, - ); + await saveGradeInferenceSettings(origin, 12, DEFAULT_ANALYTICS_GRADE_INFERENCE); const refreshed = await syncGradeAnalytics(); expect(refreshed.assessments[0].finalGrade).toBeUndefined(); expect(refreshed.assessments[0].gradeSource).toBeUndefined(); - expect( - (await loadAnalyticsCache(origin, 12))?.assessments[0].finalGrade, - ).toBeUndefined(); + expect((await loadAnalyticsCache(origin, 12))?.assessments[0].finalGrade).toBeUndefined(); }); diff --git a/src/plugins/built-in/gradeAnalytics/api.ts b/src/plugins/built-in/gradeAnalytics/api.ts index 1525c994..1bb4aff6 100644 --- a/src/plugins/built-in/gradeAnalytics/api.ts +++ b/src/plugins/built-in/gradeAnalytics/api.ts @@ -6,11 +6,7 @@ import { extractLetterGradeStringFromPayload, resolveNumericGradeFromAssessmentPayload, } from "./letterGradeScale"; -import { - loadAnalyticsCache, - loadGradeInferenceSettings, - saveAnalyticsCache, -} from "./storage"; +import { loadAnalyticsCache, loadGradeInferenceSettings, saveAnalyticsCache } from "./storage"; import type { AnalyticsGradeInferenceSettings } from "./gradeInferenceSettings"; import type { Assessment, AssessmentStatus, AnalyticsClassOption } from "./types"; @@ -51,10 +47,7 @@ export function parseAssessment(data: unknown): Assessment | null { let finalGrade = resolveNumericGradeFromAssessmentPayload( raw as Parameters[0], ); - if ( - finalGrade !== undefined && - (typeof finalGrade !== "number" || isNaN(finalGrade)) - ) { + if (finalGrade !== undefined && (typeof finalGrade !== "number" || isNaN(finalGrade))) { finalGrade = undefined; } @@ -101,7 +94,6 @@ export function parseAssessment(data: unknown): Assessment | null { } } - function applyResolvedGrade( raw: Record, inference: AnalyticsGradeInferenceSettings, @@ -112,7 +104,6 @@ function applyResolvedGrade( if (resolved.source) raw.gradeSource = resolved.source; } - function classKey(programme: number, metaclass: number): string { return `${programme}-${metaclass}`; } @@ -279,10 +270,7 @@ async function loadAllPast( if (result.status === "fulfilled") { results.push(result.value); } else { - console.error( - "[BetterSEQTA+] Past assessments fetch failed:", - result.reason, - ); + console.error("[BetterSEQTA+] Past assessments fetch failed:", result.reason); } } } @@ -304,8 +292,7 @@ function mergeRawAssessments( if (!id) continue; applyResolvedGrade(raw, inference); - const finalGrade = - raw.finalGrade !== undefined ? Number(raw.finalGrade) : undefined; + const finalGrade = raw.finalGrade !== undefined ? Number(raw.finalGrade) : undefined; const existingItem = existingMap.get(id); if ( diff --git a/src/plugins/built-in/gradeAnalytics/chart/index.ts b/src/plugins/built-in/gradeAnalytics/chart/index.ts index 6e9af3af..e0a9cca3 100644 --- a/src/plugins/built-in/gradeAnalytics/chart/index.ts +++ b/src/plugins/built-in/gradeAnalytics/chart/index.ts @@ -2,9 +2,4 @@ import ChartContainer from "./chart-container.svelte"; import ChartTooltip from "./chart-tooltip.svelte"; export { type ChartConfig } from "./chart-utils"; -export { - ChartContainer, - ChartTooltip, - ChartContainer as Container, - ChartTooltip as Tooltip, -}; +export { ChartContainer, ChartTooltip, ChartContainer as Container, ChartTooltip as Tooltip }; diff --git a/src/plugins/built-in/gradeAnalytics/gradeDistribution.ts b/src/plugins/built-in/gradeAnalytics/gradeDistribution.ts index 391940bf..1d6a1f97 100644 --- a/src/plugins/built-in/gradeAnalytics/gradeDistribution.ts +++ b/src/plugins/built-in/gradeAnalytics/gradeDistribution.ts @@ -131,8 +131,7 @@ export function looksLikeLetterGrade(raw: string | undefined | null): boolean { function isGradedAssessment(a: Assessment): boolean { return ( - a.finalGrade !== undefined || - (a.letterGrade != null && looksLikeLetterGrade(a.letterGrade)) + a.finalGrade !== undefined || (a.letterGrade != null && looksLikeLetterGrade(a.letterGrade)) ); } @@ -162,14 +161,8 @@ function buildStandardLetterScale(): InferredLetterScale { for (let i = 0; i < bands.length; i++) { const above = bands[i - 1]; const below = bands[i + 1]; - bands[i].maxPercent = - above != null - ? (above.medianPercent + bands[i].medianPercent) / 2 - : 100; - bands[i].minPercent = - below != null - ? (below.medianPercent + bands[i].medianPercent) / 2 - : 0; + bands[i].maxPercent = above != null ? (above.medianPercent + bands[i].medianPercent) / 2 : 100; + bands[i].minPercent = below != null ? (below.medianPercent + bands[i].medianPercent) / 2 : 0; } return { @@ -183,9 +176,7 @@ function buildStandardLetterScale(): InferredLetterScale { /** * Learn letter bands from assessments that report both % and the letter SEQTA assigned. */ -export function inferLetterGradeScale( - assessments: Assessment[], -): InferredLetterScale | null { +export function inferLetterGradeScale(assessments: Assessment[]): InferredLetterScale | null { const pairMap = new Map(); const letterOnlyMap = new Map(); let pairedCount = 0; @@ -267,13 +258,8 @@ export function inferLetterGradeScale( const below = bands[i + 1]; if (bands[i].pairedSamples > 0 || above?.pairedSamples || below?.pairedSamples) { bands[i].maxPercent = - above != null - ? (above.medianPercent + bands[i].medianPercent) / 2 - : 100; - bands[i].minPercent = - below != null - ? (below.medianPercent + bands[i].medianPercent) / 2 - : 0; + above != null ? (above.medianPercent + bands[i].medianPercent) / 2 : 100; + bands[i].minPercent = below != null ? (below.medianPercent + bands[i].medianPercent) / 2 : 0; } } @@ -311,10 +297,7 @@ function resolveEffectiveMode( return letterCount / graded.length >= 0.35 ? "letter" : "percent"; } -function assignPercentToBand( - percent: number, - scale: InferredLetterScale, -): string | null { +function assignPercentToBand(percent: number, scale: InferredLetterScale): string | null { if (!scale.bands.length) return null; for (const band of scale.bands) { if (percent >= band.minPercent) return band.key; @@ -348,8 +331,7 @@ function buildPercentDistribution(graded: Assessment[]): GradeDistributionResult scaleSource: "percent", scaleLabel: "Percentage bands", gradedCount: graded.length, - averagePercent: - percentCount > 0 ? Math.round((percentSum / percentCount) * 10) / 10 : null, + averagePercent: percentCount > 0 ? Math.round((percentSum / percentCount) * 10) / 10 : null, letterGradeCoverage: 0, }; } @@ -406,10 +388,7 @@ function buildLetterDistribution( 0; scale.bands.push({ key, - label: - letterRaw && looksLikeLetterGrade(letterRaw) - ? letterRaw - : key.toUpperCase(), + label: letterRaw && looksLikeLetterGrade(letterRaw) ? letterRaw : key.toUpperCase(), medianPercent: approx, minPercent: 0, maxPercent: 100, @@ -442,8 +421,7 @@ function buildLetterDistribution( scaleSource, scaleLabel, gradedCount: graded.length, - averagePercent: - percentCount > 0 ? Math.round((percentSum / percentCount) * 10) / 10 : null, + averagePercent: percentCount > 0 ? Math.round((percentSum / percentCount) * 10) / 10 : null, letterGradeCoverage: graded.length ? withLetter / graded.length : 0, }; } diff --git a/src/plugins/built-in/gradeAnalytics/gradeResolution.test.ts b/src/plugins/built-in/gradeAnalytics/gradeResolution.test.ts index 42f21666..26f7eb80 100644 --- a/src/plugins/built-in/gradeAnalytics/gradeResolution.test.ts +++ b/src/plugins/built-in/gradeAnalytics/gradeResolution.test.ts @@ -1,9 +1,6 @@ import { describe, expect, it } from "@jest/globals"; import { DEFAULT_ANALYTICS_GRADE_INFERENCE } from "./gradeInferenceSettings"; -import { - resolveGradeFromAssessmentPayload, - rollupPercentFromCriteria, -} from "./gradeResolution"; +import { resolveGradeFromAssessmentPayload, rollupPercentFromCriteria } from "./gradeResolution"; describe("rollupPercentFromCriteria", () => { it("returns undefined when no criterion marks exist", () => { @@ -12,10 +9,7 @@ describe("rollupPercentFromCriteria", () => { it("averages criterion percentages when weights are missing", () => { const result = rollupPercentFromCriteria( - [ - { results: { percentage: 80 } }, - { results: { percentage: 60 } }, - ], + [{ results: { percentage: 80 } }, { results: { percentage: 60 } }], DEFAULT_ANALYTICS_GRADE_INFERENCE, ); expect(result).toBe(70); @@ -62,26 +56,18 @@ describe("resolveGradeFromAssessmentPayload", () => { it("does not rollup criteria unless the option is enabled", () => { const payload = { status: "MARKS_RELEASED", - criteria: [ - { results: { percentage: 70 } }, - { results: { percentage: 90 } }, - ], + criteria: [{ results: { percentage: 70 } }, { results: { percentage: 90 } }], }; expect( - resolveGradeFromAssessmentPayload(payload, DEFAULT_ANALYTICS_GRADE_INFERENCE) - .finalGrade, + resolveGradeFromAssessmentPayload(payload, DEFAULT_ANALYTICS_GRADE_INFERENCE).finalGrade, ).toBe(70); const withRollup = { ...DEFAULT_ANALYTICS_GRADE_INFERENCE, rollupCriteriaGrades: true, }; - expect( - resolveGradeFromAssessmentPayload(payload, withRollup).finalGrade, - ).toBe(80); - expect(resolveGradeFromAssessmentPayload(payload, withRollup).source).toBe( - "criteriaRollup", - ); + expect(resolveGradeFromAssessmentPayload(payload, withRollup).finalGrade).toBe(80); + expect(resolveGradeFromAssessmentPayload(payload, withRollup).source).toBe("criteriaRollup"); }); it("uses custom bands for letter-only marks", () => { diff --git a/src/plugins/built-in/gradeAnalytics/gradeResolution.ts b/src/plugins/built-in/gradeAnalytics/gradeResolution.ts index 1d90b88b..93ac026c 100644 --- a/src/plugins/built-in/gradeAnalytics/gradeResolution.ts +++ b/src/plugins/built-in/gradeAnalytics/gradeResolution.ts @@ -4,11 +4,7 @@ import { type AnalyticsGradeInferenceSettings, } from "./gradeInferenceSettings"; -export type GradeResolutionSource = - | "seqta" - | "criteriaRollup" - | "customBand" - | "defaultLetter"; +export type GradeResolutionSource = "seqta" | "criteriaRollup" | "customBand" | "defaultLetter"; export type GradeResolution = { finalGrade?: number; @@ -77,8 +73,7 @@ export function rollupPercentFromCriteria( } const letter = parseGradeString(row.results?.grade); const mapped = - customPercentFromGradeLabel(letter, settings) ?? - approximatePercentFromLetterGrade(letter); + customPercentFromGradeLabel(letter, settings) ?? approximatePercentFromLetterGrade(letter); if (mapped !== undefined) { parts.push({ percent: mapped, weight: criterionWeight(row) }); } @@ -90,10 +85,7 @@ export function rollupPercentFromCriteria( if (withWeights.length === parts.length) { const totalWeight = withWeights.reduce((sum, p) => sum + (p.weight ?? 0), 0); if (totalWeight > 0) { - const weighted = withWeights.reduce( - (sum, p) => sum + p.percent * (p.weight ?? 0), - 0, - ); + const weighted = withWeights.reduce((sum, p) => sum + p.percent * (p.weight ?? 0), 0); return Math.round((weighted / totalWeight) * 10) / 10; } } @@ -157,8 +149,7 @@ export function resolveGradeFromAssessmentPayload( const custom = settings.useCustomGradeBands ? customPercentFromGradeLabel(letter, settings) : undefined; - const finalGrade = - custom ?? approximatePercentFromLetterGrade(letter); + const finalGrade = custom ?? approximatePercentFromLetterGrade(letter); if (finalGrade !== undefined) { return { finalGrade, diff --git a/src/plugins/built-in/gradeAnalytics/injectAnalyticsMenuItem.ts b/src/plugins/built-in/gradeAnalytics/injectAnalyticsMenuItem.ts index 683763f6..778d36d9 100644 --- a/src/plugins/built-in/gradeAnalytics/injectAnalyticsMenuItem.ts +++ b/src/plugins/built-in/gradeAnalytics/injectAnalyticsMenuItem.ts @@ -35,9 +35,7 @@ export async function injectAnalyticsMenuItem(): Promise<() => void> { } document - .querySelectorAll( - `#menu .${ANALYTICS_MENU_CLASS}, #menu [data-key="${ANALYTICS_MENU_KEY}"]`, - ) + .querySelectorAll(`#menu .${ANALYTICS_MENU_CLASS}, #menu [data-key="${ANALYTICS_MENU_KEY}"]`) .forEach((node) => { node.remove(); }); diff --git a/src/plugins/built-in/gradeAnalytics/lazy.ts b/src/plugins/built-in/gradeAnalytics/lazy.ts index 86917ba5..2d5eb6b2 100644 --- a/src/plugins/built-in/gradeAnalytics/lazy.ts +++ b/src/plugins/built-in/gradeAnalytics/lazy.ts @@ -21,8 +21,7 @@ const settings = defineSettings({ const gradeAnalyticsPlugin: Plugin = { id: "grade-analytics", name: "Grade Analytics", - description: - "Grade trends, distribution charts, and assessment history synced from SEQTA", + description: "Grade trends, distribution charts, and assessment history synced from SEQTA", version: "1.0.0", settings, disableToggle: true, diff --git a/src/plugins/built-in/gradeAnalytics/letterGradeScale.ts b/src/plugins/built-in/gradeAnalytics/letterGradeScale.ts index 50a0079f..e9dd2751 100644 --- a/src/plugins/built-in/gradeAnalytics/letterGradeScale.ts +++ b/src/plugins/built-in/gradeAnalytics/letterGradeScale.ts @@ -43,12 +43,10 @@ export function approximatePercentFromLetterGrade( if (!isNaN(n) && n >= 0 && n <= 100) return n; } const key = normalizeLetterKey(t); - if (LETTER_TO_APPROX_PERCENT[key] !== undefined) - return LETTER_TO_APPROX_PERCENT[key]; + if (LETTER_TO_APPROX_PERCENT[key] !== undefined) return LETTER_TO_APPROX_PERCENT[key]; if (t.length === 1 && /^[a-f]$/i.test(t)) { const single = t.toLowerCase() as keyof typeof LETTER_TO_APPROX_PERCENT; - if (LETTER_TO_APPROX_PERCENT[single] !== undefined) - return LETTER_TO_APPROX_PERCENT[single]; + if (LETTER_TO_APPROX_PERCENT[single] !== undefined) return LETTER_TO_APPROX_PERCENT[single]; } return undefined; } @@ -66,9 +64,7 @@ export function extractLetterGradeStringFromPayload(data: { if (merged.letterGrade != null && String(merged.letterGrade).trim() !== "") { return String(merged.letterGrade).trim(); } - const criteria = merged.criteria as - | { results?: { grade?: unknown } }[] - | undefined; + const criteria = merged.criteria as { results?: { grade?: unknown } }[] | undefined; const c0 = criteria?.[0]?.results?.grade; if (c0 != null && String(c0).trim() !== "") return String(c0).trim(); const r = (merged.results as { grade?: unknown } | undefined)?.grade; @@ -101,9 +97,7 @@ export function resolveNumericGradeFromAssessmentPayload(data: { const n = Number(criteria[0].results!.percentage); if (!isNaN(n)) return n; } - const results = merged.results as - | { percentage?: unknown; grade?: unknown } - | undefined; + const results = merged.results as { percentage?: unknown; grade?: unknown } | undefined; if (results?.percentage !== undefined) { const n = Number(results.percentage); if (!isNaN(n)) return n; diff --git a/src/plugins/built-in/gradeAnalytics/loadAnalyticsPage.ts b/src/plugins/built-in/gradeAnalytics/loadAnalyticsPage.ts index c653d7cb..d0fa12b9 100644 --- a/src/plugins/built-in/gradeAnalytics/loadAnalyticsPage.ts +++ b/src/plugins/built-in/gradeAnalytics/loadAnalyticsPage.ts @@ -34,9 +34,7 @@ async function loadAnalyticsPageInner(): Promise { try { main = (await waitForElm("#main", true, 100, 60)) as HTMLElement; } catch { - console.warn( - "[BetterSEQTA+] Analytics: timed out waiting for #main (shell not ready).", - ); + console.warn("[BetterSEQTA+] Analytics: timed out waiting for #main (shell not ready)."); return; } diff --git a/src/plugins/built-in/gradeAnalytics/storage.ts b/src/plugins/built-in/gradeAnalytics/storage.ts index 2a0cc806..c6baae75 100644 --- a/src/plugins/built-in/gradeAnalytics/storage.ts +++ b/src/plugins/built-in/gradeAnalytics/storage.ts @@ -40,10 +40,7 @@ export async function saveAnalyticsCache( await browser.storage.local.set({ [key]: payload }); } -export function distributionModeStorageKey( - origin: string, - studentId: number, -): string { +export function distributionModeStorageKey(origin: string, studentId: number): string { return `${DISTRIBUTION_MODE_PREFIX}.${origin}.${studentId}`; } @@ -56,10 +53,7 @@ export async function loadDistributionMode( const key = distributionModeStorageKey(origin, studentId); const result = await browser.storage.local.get(key); const mode = result[key]; - if ( - typeof mode === "string" && - VALID_DISTRIBUTION_MODES.includes(mode as DistributionMode) - ) { + if (typeof mode === "string" && VALID_DISTRIBUTION_MODES.includes(mode as DistributionMode)) { return mode as DistributionMode; } return null; diff --git a/src/plugins/built-in/gradeAnalytics/styles.css b/src/plugins/built-in/gradeAnalytics/styles.css index 5d1f83b5..6e8f2ad9 100644 --- a/src/plugins/built-in/gradeAnalytics/styles.css +++ b/src/plugins/built-in/gradeAnalytics/styles.css @@ -21,11 +21,7 @@ --bsplus-analytics-surface: var(--theme-primary, var(--background-primary, #ffffff)); --bsplus-analytics-surface-2: var(--theme-secondary, var(--background-secondary, #f8fafc)); --bsplus-analytics-text: var(--text-primary, #1a1a1a); - --bsplus-analytics-muted: color-mix( - in srgb, - var(--bsplus-analytics-text) 65%, - transparent - ); + --bsplus-analytics-muted: color-mix(in srgb, var(--bsplus-analytics-text) 65%, transparent); --bsplus-analytics-border: color-mix( in srgb, var(--theme-offset-bg, var(--background-secondary, #e2e8f0)) 78%, @@ -170,10 +166,7 @@ .bsplus-analytics-btn-privacy:hover:not(:disabled) { transform: scale(1.02); - color: var( - --bsplus-theme-btn-privacy-hover-color, - var(--bsplus-analytics-accent) - ); + color: var(--bsplus-theme-btn-privacy-hover-color, var(--bsplus-analytics-accent)); box-shadow: var(--bsplus-theme-btn-privacy-hover-shadow, none); } @@ -250,22 +243,17 @@ } .bsplus-analytics-btn-primary { - background: var( - --bsplus-theme-btn-primary-bg, - var(--bsplus-analytics-accent) - ); + background: var(--bsplus-theme-btn-primary-bg, var(--bsplus-analytics-accent)); color: var(--bsplus-theme-btn-primary-color, var(--text-color)); box-shadow: var( --bsplus-theme-btn-primary-shadow, - 0 2px 8px - color-mix(in srgb, var(--bsplus-analytics-accent) 40%, transparent) + 0 2px 8px color-mix(in srgb, var(--bsplus-analytics-accent) 40%, transparent) ); } .bsplus-analytics-btn-primary:hover:not(:disabled) { 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-analytics-btn-primary:active:not(:disabled) { @@ -275,20 +263,13 @@ .bsplus-analytics-btn-ghost { background: var(--bsplus-theme-btn-ghost-bg, transparent); color: var(--bsplus-theme-btn-ghost-color, var(--bsplus-analytics-text)); - border: var( - --bsplus-theme-btn-ghost-border, - 2px solid var(--bsplus-analytics-border) - ); + border: var(--bsplus-theme-btn-ghost-border, 2px solid var(--bsplus-analytics-border)); box-shadow: var(--bsplus-theme-btn-ghost-shadow, none); } .bsplus-analytics-btn-ghost: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-analytics-btn:disabled { @@ -349,11 +330,7 @@ white-space: nowrap; text-decoration: underline; text-underline-offset: 0.15em; - text-decoration-color: color-mix( - in srgb, - var(--bsplus-analytics-accent) 45%, - transparent - ); + text-decoration-color: color-mix(in srgb, var(--bsplus-analytics-accent) 45%, transparent); } .bsplus-analytics-filters-clear:hover { @@ -409,8 +386,7 @@ padding-bottom: 0.4rem; background-color: var(--bsplus-analytics-control-bg-elevated); border-color: var(--bsplus-analytics-control-border-strong); - box-shadow: 0 1px 4px - color-mix(in srgb, var(--bsplus-analytics-text) 10%, transparent); + box-shadow: 0 1px 4px color-mix(in srgb, var(--bsplus-analytics-text) 10%, transparent); } .bsplus-analytics-filters .bsplus-analytics-input { @@ -423,8 +399,7 @@ padding-right: 0; background-color: var(--bsplus-analytics-control-bg-elevated); border-color: var(--bsplus-analytics-control-border-strong); - box-shadow: 0 1px 4px - color-mix(in srgb, var(--bsplus-analytics-text) 10%, transparent); + box-shadow: 0 1px 4px color-mix(in srgb, var(--bsplus-analytics-text) 10%, transparent); } .bsplus-analytics-filters .bsplus-grade-range-slider { @@ -434,8 +409,7 @@ .bsplus-analytics-filters .bsplus-analytics-range-value { background-color: var(--bsplus-analytics-control-bg-elevated); border-color: var(--bsplus-analytics-control-border-strong); - box-shadow: 0 1px 4px - color-mix(in srgb, var(--bsplus-analytics-text) 10%, transparent); + box-shadow: 0 1px 4px color-mix(in srgb, var(--bsplus-analytics-text) 10%, transparent); } @media (min-width: 900px) { @@ -559,15 +533,12 @@ box-sizing: content-box; width: 15px; height: 15px; - border: 3px solid - var(--item-colour, var(--better-main, var(--bsplus-analytics-accent))); + border: 3px solid var(--item-colour, var(--better-main, var(--bsplus-analytics-accent))); border-radius: 5px; color: var(--bsplus-analytics-text); } -.bsplus-analytics-checkbox:hover - input:not(:disabled) - ~ .bsplus-analytics-checkmark { +.bsplus-analytics-checkbox:hover input:not(:disabled) ~ .bsplus-analytics-checkmark { filter: brightness(0.8); } @@ -628,8 +599,7 @@ box-shadow 0.2s ease, background-color 0.2s ease, transform 0.2s var(--bsplus-analytics-ease); - box-shadow: 0 1px 3px - color-mix(in srgb, var(--bsplus-analytics-text) 8%, transparent); + box-shadow: 0 1px 3px color-mix(in srgb, var(--bsplus-analytics-text) 8%, transparent); } .bsplus-analytics-card .bsplus-analytics-select, @@ -794,8 +764,7 @@ border: 2px solid var(--bsplus-analytics-control-border); border-radius: var(--bsplus-analytics-radius-sm); cursor: pointer; - box-shadow: 0 1px 3px - color-mix(in srgb, var(--bsplus-analytics-text) 8%, transparent); + box-shadow: 0 1px 3px color-mix(in srgb, var(--bsplus-analytics-text) 8%, transparent); transition: border-color 0.2s ease, box-shadow 0.2s ease, @@ -903,19 +872,11 @@ } .bsplus-analytics-dropdown-item:hover { - background: color-mix( - in srgb, - var(--bsplus-analytics-surface-2) 90%, - transparent - ); + background: color-mix(in srgb, var(--bsplus-analytics-surface-2) 90%, transparent); } .bsplus-analytics-dropdown-item.is-selected { - background: color-mix( - in srgb, - var(--bsplus-analytics-accent) 12%, - transparent - ); + background: color-mix(in srgb, var(--bsplus-analytics-accent) 12%, transparent); color: var(--bsplus-analytics-text); font-weight: 600; } @@ -1272,15 +1233,9 @@ display: flex; flex-direction: column; height: 100%; - border-radius: var( - --bsplus-theme-card-radius, - var(--bsplus-analytics-radius) - ); + border-radius: var(--bsplus-theme-card-radius, var(--bsplus-analytics-radius)); background: var(--bsplus-theme-card-bg, var(--bsplus-analytics-surface)); - border: var( - --bsplus-theme-card-border, - 1px solid var(--bsplus-analytics-border) - ); + border: var(--bsplus-theme-card-border, 1px solid var(--bsplus-analytics-border)); box-shadow: var(--bsplus-theme-card-shadow, var(--bsplus-analytics-shadow)); backdrop-filter: var(--bsplus-theme-card-blur, none); overflow: hidden; @@ -1290,10 +1245,7 @@ } .bsplus-analytics-card:hover { - box-shadow: var( - --bsplus-theme-card-shadow-hover, - var(--bsplus-analytics-shadow-hover) - ); + box-shadow: var(--bsplus-theme-card-shadow-hover, var(--bsplus-analytics-shadow-hover)); } .bsplus-analytics-card-header { @@ -1473,17 +1425,9 @@ } /* Bar chart: show axis spines and tick marks (area chart hides these) */ -.bsplus-analytics-root - .bsplus-chart-surface-bar - .lc-rule-x-line:not(.lc-grid-x-rule), -.bsplus-analytics-root - .bsplus-chart-surface-bar - .lc-rule-y-line:not(.lc-grid-y-rule) { - stroke: color-mix( - in srgb, - var(--bsplus-analytics-muted) 45%, - transparent - ) !important; +.bsplus-analytics-root .bsplus-chart-surface-bar .lc-rule-x-line:not(.lc-grid-x-rule), +.bsplus-analytics-root .bsplus-chart-surface-bar .lc-rule-y-line:not(.lc-grid-y-rule) { + stroke: color-mix(in srgb, var(--bsplus-analytics-muted) 45%, transparent) !important; } .bsplus-analytics-root .bsplus-chart-surface-bar .lc-axis-tick { @@ -1535,9 +1479,7 @@ } .bsplus-analytics-root [data-slot="chart"] .lc-rule-x-line:not(.lc-grid-x-rule), -.bsplus-analytics-root - [data-slot="chart"] - .lc-rule-y-line:not(.lc-grid-y-rule) { +.bsplus-analytics-root [data-slot="chart"] .lc-rule-y-line:not(.lc-grid-y-rule) { stroke: transparent !important; } @@ -1588,15 +1530,9 @@ /* ─── Table ─── */ .bsplus-analytics-table-wrap { - border-radius: var( - --bsplus-theme-card-radius, - var(--bsplus-analytics-radius) - ); + border-radius: var(--bsplus-theme-card-radius, var(--bsplus-analytics-radius)); background: var(--bsplus-theme-card-bg, var(--bsplus-analytics-surface)); - border: var( - --bsplus-theme-card-border, - 1px solid var(--bsplus-analytics-border) - ); + border: var(--bsplus-theme-card-border, 1px solid var(--bsplus-analytics-border)); box-shadow: var(--bsplus-theme-card-shadow, var(--bsplus-analytics-shadow)); backdrop-filter: var(--bsplus-theme-card-blur, none); overflow: hidden; @@ -1624,11 +1560,7 @@ } .bsplus-analytics-table thead { - background: color-mix( - in srgb, - var(--bsplus-analytics-surface-2) 85%, - transparent - ); + background: color-mix(in srgb, var(--bsplus-analytics-surface-2) 85%, transparent); } .bsplus-analytics-table th { @@ -1665,11 +1597,7 @@ } .bsplus-analytics-table tbody tr:hover { - background: color-mix( - in srgb, - var(--bsplus-analytics-accent) 6%, - transparent - ); + background: color-mix(in srgb, var(--bsplus-analytics-accent) 6%, transparent); } .bsplus-analytics-table .cell-title { @@ -1763,15 +1691,9 @@ gap: 1rem; padding: 3rem 2rem; text-align: center; - border-radius: var( - --bsplus-theme-card-radius, - var(--bsplus-analytics-radius) - ); + border-radius: var(--bsplus-theme-card-radius, var(--bsplus-analytics-radius)); background: var(--bsplus-theme-card-bg, var(--bsplus-analytics-surface)); - border: var( - --bsplus-theme-card-border, - 1px solid var(--bsplus-analytics-border) - ); + border: var(--bsplus-theme-card-border, 1px solid var(--bsplus-analytics-border)); box-shadow: var(--bsplus-theme-card-shadow, var(--bsplus-analytics-shadow)); backdrop-filter: var(--bsplus-theme-card-blur, none); } diff --git a/src/plugins/built-in/gradeAnalytics/timeRange.test.ts b/src/plugins/built-in/gradeAnalytics/timeRange.test.ts index 65a82318..59fb628e 100644 --- a/src/plugins/built-in/gradeAnalytics/timeRange.test.ts +++ b/src/plugins/built-in/gradeAnalytics/timeRange.test.ts @@ -33,15 +33,10 @@ describe("timeRange", () => { assessment("2026-04-01"), ]; const filtered = filterAssessmentsByTimeRange(items, "custom", custom); - expect(filtered.map((a) => a.due)).toEqual([ - "2026-03-01", - "2026-03-31T23:59:00", - ]); + expect(filtered.map((a) => a.due)).toEqual(["2026-03-01", "2026-03-31T23:59:00"]); }); it("labels custom ranges", () => { - expect( - getTimeRangeLabel("custom", defaultCustomTimeRange(ref)), - ).toMatch(/2026/); + expect(getTimeRangeLabel("custom", defaultCustomTimeRange(ref))).toMatch(/2026/); }); }); diff --git a/src/plugins/built-in/gradeAnalytics/timeRange.ts b/src/plugins/built-in/gradeAnalytics/timeRange.ts index 92da5b78..89c8fa54 100644 --- a/src/plugins/built-in/gradeAnalytics/timeRange.ts +++ b/src/plugins/built-in/gradeAnalytics/timeRange.ts @@ -60,17 +60,11 @@ export function getTimeRangeBounds( return { start, end: null }; } -export function getTimeRangeCutoff( - timeRange: TimeRange, - custom?: CustomTimeRange, -): Date | null { +export function getTimeRangeCutoff(timeRange: TimeRange, custom?: CustomTimeRange): Date | null { return getTimeRangeBounds(timeRange, custom).start; } -export function getTimeRangeLabel( - timeRange: TimeRange, - custom?: CustomTimeRange, -): string { +export function getTimeRangeLabel(timeRange: TimeRange, custom?: CustomTimeRange): string { if (timeRange === "custom" && custom?.from && custom?.to) { const fmt = (iso: string) => parseDateOnly(iso).toLocaleDateString(undefined, { @@ -83,10 +77,7 @@ export function getTimeRangeLabel( return TIME_RANGE_OPTIONS.find((o) => o.value === timeRange)?.label ?? "All time"; } -function assessmentInRange( - due: string, - bounds: { start: Date | null; end: Date | null }, -): boolean { +function assessmentInRange(due: string, bounds: { start: Date | null; end: Date | null }): boolean { const date = new Date(due); if (bounds.start && date < bounds.start) return false; if (bounds.end && date > bounds.end) return false; @@ -103,10 +94,7 @@ export function filterAssessmentsByTimeRange( return assessments.filter((a) => assessmentInRange(a.due, bounds)); } -function usesMonthlyGrouping( - timeRange: TimeRange, - custom?: CustomTimeRange, -): boolean { +function usesMonthlyGrouping(timeRange: TimeRange, custom?: CustomTimeRange): boolean { if (timeRange === "365d" || timeRange === "all" || timeRange === "ytd") return true; if (timeRange !== "custom" || !custom?.from || !custom?.to) return false; const { start, end } = getTimeRangeBounds(timeRange, custom); @@ -148,10 +136,7 @@ export function subjectChartColor(index: number): string { return SUBJECT_CHART_COLORS[index % SUBJECT_CHART_COLORS.length]; } -function periodKeyForAssessment( - assessment: Assessment, - useMonthlyGrouping: boolean, -): string { +function periodKeyForAssessment(assessment: Assessment, useMonthlyGrouping: boolean): string { const date = new Date(assessment.due); if (useMonthlyGrouping) { return date.toISOString().slice(0, 7); @@ -199,12 +184,9 @@ export function buildGradeTrendChart( combinedLabel?: string; } = {}, ): { points: TrendPoint[]; series: TrendSeries[]; accentColor: string } { - const accentColor = - "var(--bsplus-analytics-accent, var(--better-main, #007bff))"; + const accentColor = "var(--bsplus-analytics-accent, var(--better-main, #007bff))"; - const graded = data.filter( - (a) => a.finalGrade !== undefined && a.finalGrade !== null, - ); + const graded = data.filter((a) => a.finalGrade !== undefined && a.finalGrade !== null); if (!graded.length) { return { points: [], series: [], accentColor }; } diff --git a/src/plugins/built-in/gradeAnalytics/utils/accentColor.ts b/src/plugins/built-in/gradeAnalytics/utils/accentColor.ts index 2858771a..59399d77 100644 --- a/src/plugins/built-in/gradeAnalytics/utils/accentColor.ts +++ b/src/plugins/built-in/gradeAnalytics/utils/accentColor.ts @@ -35,11 +35,7 @@ function adjustLightnessForContrast( return candidate; } const { l } = candidate.hsl().object(); - candidate = Color.hsl( - hue, - saturation, - isDark ? Math.min(l + 5, 82) : Math.max(l - 5, 18), - ); + candidate = Color.hsl(hue, saturation, isDark ? Math.min(l + 5, 82) : Math.max(l - 5, 18)); } return candidate; @@ -61,13 +57,7 @@ export function buildContrastAccentPalette( const saturation = Math.min(Math.max(s, 42), 88); const baseLightness = isDark ? 64 : 40; - const foreground = adjustLightnessForContrast( - h, - saturation, - baseLightness, - background, - isDark, - ); + const foreground = adjustLightnessForContrast(h, saturation, baseLightness, background, isDark); const accentHex = foreground.hex(); const subtleLightness = isDark ? 28 : 94; @@ -75,7 +65,10 @@ export function buildContrastAccentPalette( return { accent: accentHex, - accentSubtle: subtle.alpha(isDark ? 0.22 : 0.14).rgb().string(), + accentSubtle: subtle + .alpha(isDark ? 0.22 : 0.14) + .rgb() + .string(), onAccent: foreground.isLight() ? "#141414" : "#ffffff", }; } diff --git a/src/plugins/built-in/gradeAnalytics/utils/gradePrediction.ts b/src/plugins/built-in/gradeAnalytics/utils/gradePrediction.ts index 30dc43d2..a12991f0 100644 --- a/src/plugins/built-in/gradeAnalytics/utils/gradePrediction.ts +++ b/src/plugins/built-in/gradeAnalytics/utils/gradePrediction.ts @@ -97,8 +97,9 @@ function weightedLinearRegression(values: number[]): { } const rSquared = ssTot === 0 ? 1 : Math.max(0, 1 - ssRes / ssTot); - const forecasts = Array.from({ length: MAX_MONTHS }, (_, i) => - intercept + slope * (n - 1 + (i + 1)), + const forecasts = Array.from( + { length: MAX_MONTHS }, + (_, i) => intercept + slope * (n - 1 + (i + 1)), ); return { forecasts, slope, rSquared }; diff --git a/src/plugins/built-in/messageFolders/index.ts b/src/plugins/built-in/messageFolders/index.ts index 96de9b19..d0b91f27 100644 --- a/src/plugins/built-in/messageFolders/index.ts +++ b/src/plugins/built-in/messageFolders/index.ts @@ -10,30 +10,66 @@ interface Folder { } const FOLDER_COLORS = [ - "#3b82f6", "#ef4444", "#22c55e", "#f59e0b", - "#8b5cf6", "#ec4899", "#14b8a6", "#f97316", + "#3b82f6", + "#ef4444", + "#22c55e", + "#f59e0b", + "#8b5cf6", + "#ec4899", + "#14b8a6", + "#f97316", ]; const folderHeroicon = (inner: string) => `${inner}`; const FOLDER_HEROICONS = [ - folderHeroicon(''), - folderHeroicon(''), - folderHeroicon(''), - folderHeroicon(''), - folderHeroicon(''), - folderHeroicon(''), - folderHeroicon(''), - folderHeroicon(''), - folderHeroicon(''), - folderHeroicon(''), - folderHeroicon(''), + folderHeroicon( + '', + ), + folderHeroicon( + '', + ), + folderHeroicon( + '', + ), + folderHeroicon( + '', + ), + folderHeroicon( + '', + ), + folderHeroicon( + '', + ), + folderHeroicon( + '', + ), + folderHeroicon( + '', + ), + folderHeroicon( + '', + ), + folderHeroicon( + '', + ), + folderHeroicon( + '', + ), folderHeroicon(''), - folderHeroicon(''), - folderHeroicon(''), - folderHeroicon(''), - folderHeroicon(''), + folderHeroicon( + '', + ), + folderHeroicon( + '', + ), + folderHeroicon( + '', + ), + folderHeroicon( + '', + ), ]; const FOLDER_ICON_SVG = ``; @@ -45,7 +81,6 @@ const TRASH_SVG = ``; const DRAG_SVG = ``; - function isAllowedFolderColor(color: unknown): color is string { return typeof color === "string" && FOLDER_COLORS.includes(color); } @@ -84,8 +119,7 @@ function appendFolderBadgeContent(badge: HTMLElement, folder: Folder): void { badge.appendChild(document.createTextNode(folder.name)); } -const MESSAGE_LIST_ITEM_SELECTOR = - "[class*='MessageList__MessageList___'] ol > li[data-message]"; +const MESSAGE_LIST_ITEM_SELECTOR = "[class*='MessageList__MessageList___'] ol > li[data-message]"; function getMessageListItems(): NodeListOf { return document.querySelectorAll(MESSAGE_LIST_ITEM_SELECTOR); @@ -99,8 +133,7 @@ function clearMessageListBadges( const subject = li.querySelector("[class*='MessageList__subject___']"); if ( subject && - (subject.querySelector(".bsplus-msg-badges") || - subject.querySelector(".bsplus-subject-text")) + (subject.querySelector(".bsplus-msg-badges") || subject.querySelector(".bsplus-subject-text")) ) { restoreSubjectPlain(subject); } else { @@ -109,10 +142,7 @@ function clearMessageListBadges( } } -function getAssignedFolderIds( - msgId: string, - assignments: Record, -): string[] { +function getAssignedFolderIds(msgId: string, assignments: Record): string[] { return Object.entries(assignments) .filter(([, messageIds]) => messageIds.includes(msgId)) .map(([folderId]) => folderId); @@ -140,10 +170,7 @@ function ensureMessageBadgeContainer(li: Element): HTMLElement { return badgeContainer; } -function createFolderBadge( - folder: Folder, - onFilter: (folderId: string) => void, -): HTMLElement { +function createFolderBadge(folder: Folder, onFilter: (folderId: string) => void): HTMLElement { const badge = document.createElement("span"); badge.className = "bsplus-msg-badge"; badge.style.background = folder.color; @@ -368,17 +395,21 @@ const messageFoldersPlugin: Pick { e.stopPropagation(); - showConfirmModal("Delete folder", `Remove "${folder.name}"? Messages won't be deleted.`, () => { - const folders = getFolders().filter((f) => f.id !== folder.id); - saveFolders(folders); - const assignments = getAssignments(); - delete assignments[folder.id]; - saveAssignments(assignments); - if (activeFolderId === folder.id) activeFolderId = null; - applyFolderFilter(); - applyBadges(); - renderSidebarFolders(); - }); + showConfirmModal( + "Delete folder", + `Remove "${folder.name}"? Messages won't be deleted.`, + () => { + const folders = getFolders().filter((f) => f.id !== folder.id); + saveFolders(folders); + const assignments = getAssignments(); + delete assignments[folder.id]; + saveAssignments(assignments); + if (activeFolderId === folder.id) activeFolderId = null; + applyFolderFilter(); + applyBadges(); + renderSidebarFolders(); + }, + ); }); actions.appendChild(deleteBtn); @@ -407,7 +438,9 @@ const messageFoldersPlugin: Pick { item.classList.remove("bsplus-dragging"); - document.querySelectorAll(".bsplus-folder-item").forEach((el) => el.classList.remove("bsplus-drag-over")); + document + .querySelectorAll(".bsplus-folder-item") + .forEach((el) => el.classList.remove("bsplus-drag-over")); }); item.addEventListener("dragover", (e) => { e.preventDefault(); @@ -448,7 +481,9 @@ const messageFoldersPlugin: Pick { li.classList.remove("bsplus-msg-dragging"); - document.querySelectorAll(".bsplus-folder-item").forEach((el) => el.classList.remove("bsplus-drag-over")); + document + .querySelectorAll(".bsplus-folder-item") + .forEach((el) => el.classList.remove("bsplus-drag-over")); }); }); }; @@ -485,8 +522,10 @@ const messageFoldersPlugin: Pick { e.stopPropagation(); selectedColor = color; - colorRow.querySelectorAll(".bsplus-folder-color-opt").forEach((s) => - s.classList.toggle("bsplus-color-selected", (s as HTMLElement).style.background === color), - ); + colorRow + .querySelectorAll(".bsplus-folder-color-opt") + .forEach((s) => + s.classList.toggle( + "bsplus-color-selected", + (s as HTMLElement).style.background === color, + ), + ); }); colorRow.appendChild(swatch); } @@ -552,7 +596,12 @@ const messageFoldersPlugin: Pick { if (actionsObserver) return; - const target = document.querySelector("[class*='Viewer__Viewer___']") ?? document.querySelector("div.messages"); + const target = + document.querySelector("[class*='Viewer__Viewer___']") ?? + document.querySelector("div.messages"); if (!target) return; actionsObserver = new MutationObserver(() => { const actionsBar = document.querySelector("[class*='Message__actions___']"); @@ -945,11 +998,10 @@ const messageFoldersPlugin: Pick - el.classList.remove("bsplus-folder-hidden"), - ); + document + .querySelectorAll(".bsplus-folder-hidden") + .forEach((el) => el.classList.remove("bsplus-folder-hidden")); document.querySelectorAll(".bsplus-modal-overlay").forEach((el) => el.remove()); - }; }, }; diff --git a/src/plugins/built-in/messageFolders/styles.css b/src/plugins/built-in/messageFolders/styles.css index f764150c..a98d925c 100644 --- a/src/plugins/built-in/messageFolders/styles.css +++ b/src/plugins/built-in/messageFolders/styles.css @@ -3,7 +3,7 @@ border-top: 1px solid var(--background-secondary, rgba(128, 128, 128, 0.2)); margin-top: 4px; padding-top: 4px; - transition: opacity .2s; + transition: opacity 0.2s; } .bsplus-folders-section.bsplus-section-folded .bsplus-folder-item, @@ -46,7 +46,7 @@ border-radius: 4px !important; padding: 0 !important; margin: 0 !important; - transition: all .2s; + transition: all 0.2s; } .bsplus-folders-collapse:hover { @@ -87,7 +87,9 @@ align-items: center; padding: 6px 12px; cursor: pointer; - transition: background 0.15s ease, opacity 0.2s; + transition: + background 0.15s ease, + opacity 0.2s; position: relative; gap: 6px; user-select: none; @@ -125,7 +127,7 @@ display: flex; align-items: center; opacity: 0; - transition: opacity .15s; + transition: opacity 0.15s; margin-right: -4px; } @@ -226,7 +228,9 @@ background: var(--background-secondary, #f5f5f5); color: var(--text-primary, #333); outline: none; - transition: border-color 0.2s ease, box-shadow 0.2s ease; + transition: + border-color 0.2s ease, + box-shadow 0.2s ease; } .bsplus-folder-input input:focus { @@ -247,7 +251,7 @@ cursor: pointer; padding: 0 !important; margin: 0 !important; - transition: all .15s; + transition: all 0.15s; color: var(--text-primary, #333); } @@ -318,7 +322,7 @@ background: transparent !important; cursor: pointer; padding: 0 !important; - transition: all .15s; + transition: all 0.15s; color: var(--text-primary, #333); } @@ -349,9 +353,10 @@ border-radius: 50%; border: 2px solid transparent; cursor: pointer; - transition: transform 0.25s cubic-bezier(0.4, 0, 0.2, 1), - border-color 0.2s ease, - box-shadow 0.25s cubic-bezier(0.4, 0, 0.2, 1); + transition: + transform 0.25s cubic-bezier(0.4, 0, 0.2, 1), + border-color 0.2s ease, + box-shadow 0.25s cubic-bezier(0.4, 0, 0.2, 1); padding: 0; background: none; box-sizing: border-box; @@ -517,7 +522,7 @@ width: 100%; text-align: left !important; color: var(--text-primary, #333) !important; - transition: background .1s; + transition: background 0.1s; font-family: inherit; } @@ -561,18 +566,18 @@ opacity: 0.4; } -[class*='MessageList__MessageList___'] ol > li[data-message] { - transition: opacity .15s; +[class*="MessageList__MessageList___"] ol > li[data-message] { + transition: opacity 0.15s; } /* ── Layout fixes ── */ -[class*='MessageList__primary___'] { +[class*="MessageList__primary___"] { flex: 1 1 0% !important; min-width: 0 !important; overflow: hidden !important; } -[class*='MessageList__subject___'] { +[class*="MessageList__subject___"] { display: flex !important; align-items: center; gap: 6px; @@ -588,14 +593,14 @@ flex: 1 1 auto; } -[class*='MessageList__secondary___'] { +[class*="MessageList__secondary___"] { flex: 0 0 auto !important; width: auto !important; min-width: 0 !important; max-width: 200px !important; } -[class*='MessageList__flags___'] { +[class*="MessageList__flags___"] { width: 24px !important; min-width: 0 !important; flex-shrink: 0 !important; @@ -622,7 +627,9 @@ color: white; white-space: nowrap; cursor: pointer; - transition: opacity 0.2s ease, transform 0.2s cubic-bezier(0.4, 0, 0.2, 1); + transition: + opacity 0.2s ease, + transform 0.2s cubic-bezier(0.4, 0, 0.2, 1); } .bsplus-msg-badge:hover { @@ -637,8 +644,12 @@ /* ── Delete confirmation modal ── */ @keyframes bsplus-modal-overlay-in { - from { opacity: 0; } - to { opacity: 1; } + from { + opacity: 0; + } + to { + opacity: 1; + } } @keyframes bsplus-modal-in { @@ -728,5 +739,3 @@ transform: translateY(-1px); box-shadow: 0 4px 12px rgba(229, 62, 62, 0.35); } - - diff --git a/src/plugins/built-in/notificationCollector/archive.ts b/src/plugins/built-in/notificationCollector/archive.ts index b7fa0c9e..be0bd7c2 100644 --- a/src/plugins/built-in/notificationCollector/archive.ts +++ b/src/plugins/built-in/notificationCollector/archive.ts @@ -17,8 +17,7 @@ export async function resolveNotificationUserKey(): Promise { const info = await getUserInfo(); const id = info?.id ?? info?.personUUID ?? info?.username; if (id == null || id === "") return null; - const label = - info?.displayName ?? info?.name ?? info?.username ?? String(id); + const label = info?.displayName ?? info?.name ?? info?.username ?? String(id); return `${location.hostname}:${id}:${String(label).slice(0, 64)}`; } catch { return null; @@ -45,12 +44,8 @@ export async function fetchAllNotifications(): Promise { return Array.isArray(list) ? list : []; } -function archiveTimestamp( - item: ArchivedNotification & { timestamp?: string }, -): number { - const ms = new Date( - String(item.raw?.timestamp ?? item.timestamp ?? 0), - ).getTime(); +function archiveTimestamp(item: ArchivedNotification & { timestamp?: string }): number { + const ms = new Date(String(item.raw?.timestamp ?? item.timestamp ?? 0)).getTime(); return Number.isNaN(ms) ? 0 : ms; } @@ -77,16 +72,10 @@ export function mergeNotificationsIntoArchive( return { archive, changed }; } -export function listArchivedNotifications( - archive: ArchiveMap, -): ArchivedNotification[] { - return Object.values(archive).sort( - (a, b) => archiveTimestamp(b) - archiveTimestamp(a), - ); +export function listArchivedNotifications(archive: ArchiveMap): ArchivedNotification[] { + return Object.values(archive).sort((a, b) => archiveTimestamp(b) - archiveTimestamp(a)); } -export function archivedToApiNotification( - item: ArchivedNotification, -): RawNotification { +export function archivedToApiNotification(item: ArchivedNotification): RawNotification { return { ...item.raw, notificationID: item.notificationID }; } diff --git a/src/plugins/built-in/notificationCollector/index.ts b/src/plugins/built-in/notificationCollector/index.ts index b7db8a1b..72c55279 100644 --- a/src/plugins/built-in/notificationCollector/index.ts +++ b/src/plugins/built-in/notificationCollector/index.ts @@ -77,12 +77,9 @@ const notificationCollectorPlugin: Plugin< if (!userKey) return; const notifications = await fetchAllNotifications(); - const archivesByUser = { ...(api.storage.archivesByUser ?? {}) }; + const archivesByUser = { ...api.storage.archivesByUser }; const existing = archivesByUser[userKey] ?? {}; - const { archive: merged, changed } = mergeNotificationsIntoArchive( - existing, - notifications, - ); + const { archive: merged, changed } = mergeNotificationsIntoArchive(existing, notifications); if (changed) { archivesByUser[userKey] = merged; @@ -125,16 +122,12 @@ const notificationCollectorPlugin: Plugin< } } catch (error) { console.error("[BetterSEQTA+] Error fetching notifications:", error); - api.storage.consecutiveErrors = - (api.storage.consecutiveErrors || 0) + 1; + api.storage.consecutiveErrors = (api.storage.consecutiveErrors || 0) + 1; } }; const getNextInterval = () => { - const errorMultiplier = Math.min( - Math.pow(2, api.storage.consecutiveErrors || 0), - 10, - ); + const errorMultiplier = Math.min(Math.pow(2, api.storage.consecutiveErrors || 0), 10); return Math.min(baseInterval * errorMultiplier, maxInterval); }; @@ -184,10 +177,7 @@ const notificationCollectorPlugin: Plugin< } }); - const teardownInjection = mountArchivedNotificationInjection( - api, - resolveNotificationUserKey, - ); + const teardownInjection = mountArchivedNotificationInjection(api, resolveNotificationUserKey); const onBubbleMount = () => { startPolling(); diff --git a/src/plugins/built-in/notificationCollector/injectArchivedNotifications.ts b/src/plugins/built-in/notificationCollector/injectArchivedNotifications.ts index a61f741e..660f919f 100644 --- a/src/plugins/built-in/notificationCollector/injectArchivedNotifications.ts +++ b/src/plugins/built-in/notificationCollector/injectArchivedNotifications.ts @@ -48,8 +48,7 @@ async function tryInjectArchived(archive: ArchiveMap): Promise { const sameOrder = liveItems.length === merged.length && liveItems.every( - (item, index) => - Number(item.notificationID) === Number(merged[index]?.notificationID), + (item, index) => Number(item.notificationID) === Number(merged[index]?.notificationID), ); if (sameOrder) return true; diff --git a/src/plugins/built-in/profilePicture/index.ts b/src/plugins/built-in/profilePicture/index.ts index 3092b2f7..21735548 100644 --- a/src/plugins/built-in/profilePicture/index.ts +++ b/src/plugins/built-in/profilePicture/index.ts @@ -1,9 +1,5 @@ import type { Plugin } from "@/plugins/core/types"; -import { - booleanSetting, - componentSetting, - defineSettings, -} from "@/plugins/core/settingsHelpers"; +import { booleanSetting, componentSetting, defineSettings } from "@/plugins/core/settingsHelpers"; import ProfilePictureSetting from "./ProfilePictureSetting.svelte"; import { waitForElm } from "@/seqta/utils/waitForElm"; import browser from "@/lib/browser"; @@ -66,8 +62,7 @@ const profilePicturePlugin: Plugin = { const useCloud = api.settings.useCloudPfp; const userId = cloudAuth.state.user?.id; const pfpUrl = - cloudAuth.state.user?.pfpUrl ?? - (userId ? defaultAccountsPfpUrl(userId) : undefined); + cloudAuth.state.user?.pfpUrl ?? (userId ? defaultAccountsPfpUrl(userId) : undefined); if (useCloud && pfpUrl && userId) { const resolved = await resolveCloudPfp(userId, pfpUrl); diff --git a/src/plugins/built-in/themes/theme-manager.cloud.test.ts b/src/plugins/built-in/themes/theme-manager.cloud.test.ts index 2bbf2d41..8af9672b 100644 --- a/src/plugins/built-in/themes/theme-manager.cloud.test.ts +++ b/src/plugins/built-in/themes/theme-manager.cloud.test.ts @@ -7,9 +7,7 @@ jest.mock("localforage", () => { const records = new Map(); return { getItem: jest.fn(async (key: string) => records.get(key) ?? null), - setItem: jest.fn(async (key: string, value: unknown) => - records.set(key, value), - ), + setItem: jest.fn(async (key: string, value: unknown) => records.set(key, value)), clear: jest.fn(async () => records.clear()), }; }); @@ -47,60 +45,47 @@ describe("cloud theme restoration", () => { jest.restoreAllMocks(); }); - it.each(["themes", "custom-themes"])( - "installs a missing %s catalog theme", - async (catalog) => { - const jsonUrl = "https://betterseqta.org/storage/theme.json"; - (browser.runtime.sendMessage as jest.Mock).mockImplementation( - async ({ url }) => { - if ( - typeof url === "string" && - url.includes(`/api/${catalog}/catalog-id/download`) && - url.includes("extensionVersion=") - ) { - return { - data: { success: true, data: { theme_json_url: jsonUrl } }, - }; - } - if (url === jsonUrl) - return { - data: { - id: "catalog-id", - name: "Restored theme", - CustomCSS: "body { color: red; }", - }, - }; - return { error: "Not found" }; - }, - ); + it.each(["themes", "custom-themes"])("installs a missing %s catalog theme", async (catalog) => { + const jsonUrl = "https://betterseqta.org/storage/theme.json"; + (browser.runtime.sendMessage as jest.Mock).mockImplementation(async ({ url }) => { + if ( + typeof url === "string" && + url.includes(`/api/${catalog}/catalog-id/download`) && + url.includes("extensionVersion=") + ) { + return { + data: { success: true, data: { theme_json_url: jsonUrl } }, + }; + } + if (url === jsonUrl) + return { + data: { + id: "catalog-id", + name: "Restored theme", + CustomCSS: "body { color: red; }", + }, + }; + return { error: "Not found" }; + }); - await ThemeManager.getInstance().prepareThemeAfterCloudSync(); + await ThemeManager.getInstance().prepareThemeAfterCloudSync(); - expect(await localforage.getItem("catalog-id")).toMatchObject({ - name: "Restored theme", - installedFromStore: catalog === "themes", - ...(catalog === "custom-themes" - ? { installedFromCommunity: true } - : {}), - }); - expect( - await browser.storage.local.get( - BSPLUS_PENDING_THEME_ENSURE_AFTER_CLOUD_KEY, - ), - ).toEqual({}); - }, - ); + expect(await localforage.getItem("catalog-id")).toMatchObject({ + name: "Restored theme", + installedFromStore: catalog === "themes", + ...(catalog === "custom-themes" ? { installedFromCommunity: true } : {}), + }); + expect(await browser.storage.local.get(BSPLUS_PENDING_THEME_ENSURE_AFTER_CLOUD_KEY)).toEqual( + {}, + ); + }); it("keeps a failed download pending so a later page can retry", async () => { (browser.runtime.sendMessage as jest.Mock).mockResolvedValue({ error: "Offline", }); await ThemeManager.getInstance().prepareThemeAfterCloudSync(); - expect( - await browser.storage.local.get( - BSPLUS_PENDING_THEME_ENSURE_AFTER_CLOUD_KEY, - ), - ).toEqual({ + expect(await browser.storage.local.get(BSPLUS_PENDING_THEME_ENSURE_AFTER_CLOUD_KEY)).toEqual({ [BSPLUS_PENDING_THEME_ENSURE_AFTER_CLOUD_KEY]: "catalog-id", }); }); diff --git a/src/plugins/built-in/themes/theme-manager.ts b/src/plugins/built-in/themes/theme-manager.ts index 25c7c5da..555ca183 100644 --- a/src/plugins/built-in/themes/theme-manager.ts +++ b/src/plugins/built-in/themes/theme-manager.ts @@ -35,11 +35,7 @@ import { validateThemeDom, validateThemeScript, } from "./theme-runtime"; -import { - base64ToBlob, - blobToBase64Data, - stripBase64Prefix, -} from "@/seqta/utils/base64"; +import { base64ToBlob, blobToBase64Data, stripBase64Prefix } from "@/seqta/utils/base64"; type ThemeContent = { id: string; @@ -131,43 +127,37 @@ export class ThemeManager { */ private async applyViewTransition(callback: () => void): Promise { if ( - !document.startViewTransition || - !fullMotionEffectsEnabled() || + !document.startViewTransition || + !fullMotionEffectsEnabled() || window.matchMedia("(prefers-reduced-motion: reduce)").matches ) { // Just run the callback without animation if transitions not supported callback(); return; } - + // Use last known transition point or fallback to center const x = this.lastTransitionPoint.x || window.innerWidth / 2; const y = this.lastTransitionPoint.y || window.innerHeight / 2; const right = window.innerWidth - x; const bottom = window.innerHeight - y; - - const maxRadius = Math.hypot( - Math.max(x, right), - Math.max(y, bottom), - ); - + + const maxRadius = Math.hypot(Math.max(x, right), Math.max(y, bottom)); + await document.startViewTransition(() => { callback(); }).ready; - + try { document.documentElement.animate( { - clipPath: [ - `circle(0px at ${x}px ${y}px)`, - `circle(${maxRadius}px at ${x}px ${y}px)`, - ], + clipPath: [`circle(0px at ${x}px ${y}px)`, `circle(${maxRadius}px at ${x}px ${y}px)`], }, { duration: 400, - easing: 'ease-in-out', - pseudoElement: '::view-transition-new(root)', - } + easing: "ease-in-out", + pseudoElement: "::view-transition-new(root)", + }, ); } catch (error) { console.error("[ThemeManager] View Transition animation error:", error); @@ -234,22 +224,24 @@ export class ThemeManager { try { const neumorphicThemeId = "9a9786d1-b5fc-4a91-8c7a-f8bf7f7679ad"; const migrationCSS = "#title {\nbackground: transparent !important;\n}"; - + const theme = (await localforage.getItem(neumorphicThemeId)) as CustomTheme | null; - if (theme && theme.CustomCSS && !theme.CustomCSS.includes("#title {\nbackground: transparent !important;\n}")) { + if ( + theme && + theme.CustomCSS && + !theme.CustomCSS.includes("#title {\nbackground: transparent !important;\n}") + ) { theme.CustomCSS = theme.CustomCSS + "\n" + migrationCSS; await localforage.setItem(neumorphicThemeId, theme); } - const { readThemeCreatorSession } = await import( - "@/plugins/built-in/themes/themeCreatorPersistence" - ); + const { readThemeCreatorSession } = + await import("@/plugins/built-in/themes/themeCreatorPersistence"); const creatorSession = readThemeCreatorSession(); if (creatorSession.open) { verboseDebug("[ThemeManager] Restoring theme creator after navigation"); - const { OpenThemeCreator, isThemeCreatorOpen } = await import( - "@/plugins/built-in/themes/ThemeCreator" - ); + const { OpenThemeCreator, isThemeCreatorOpen } = + await import("@/plugins/built-in/themes/ThemeCreator"); if (!isThemeCreatorOpen()) { void OpenThemeCreator(creatorSession.editingThemeId); } @@ -366,24 +358,17 @@ export class ThemeManager { // Use the stored selected color if available, otherwise use the default if (theme.selectedColor) { - verboseDebug( - "[ThemeManager] Restoring saved color:", - theme.selectedColor, - ); + verboseDebug("[ThemeManager] Restoring saved color:", theme.selectedColor); settingsState.selectedColor = theme.selectedColor; } else if (theme.defaultColour) { - verboseDebug( - "[ThemeManager] Using default color:", - theme.defaultColour, - ); + verboseDebug("[ThemeManager] Using default color:", theme.defaultColour); settingsState.selectedColor = theme.defaultColour; } setCustomThemeAdaptiveCssVariables(theme.adaptiveCssVariables ?? []); - const { applyThemeCreatorMetaToSettings } = await import( - "@/interface/utils/themeCreatorMeta" - ); + const { applyThemeCreatorMetaToSettings } = + await import("@/interface/utils/themeCreatorMeta"); applyThemeCreatorMetaToSettings(theme.creatorMeta); injectThemeDom(theme.themeDom); @@ -395,10 +380,7 @@ export class ThemeManager { /** * Remove theme and restore original settings with view transition */ - private async removeTheme( - theme: CustomTheme, - clearSelectedTheme: boolean = true, - ): Promise { + private async removeTheme(theme: CustomTheme, clearSelectedTheme: boolean = true): Promise { verboseDebug("[ThemeManager] Removing theme with transition:", theme.name); try { await this.applyViewTransition(async () => { @@ -408,7 +390,7 @@ export class ThemeManager { console.error("[ThemeManager] Error removing theme with transition:", error); } } - + /** * Remove theme without applying view transition animation */ @@ -488,12 +470,8 @@ export class ThemeManager { return [...merged.values()]; } - private imageSyncKey( - images: Array<{ id: string; variableName: string; blob: Blob }>, - ): string { - return images - .map((image) => `${image.id}:${image.variableName}:${image.blob.size}`) - .join("|"); + private imageSyncKey(images: Array<{ id: string; variableName: string; blob: Blob }>): string { + return images.map((image) => `${image.id}:${image.variableName}:${image.blob.size}`).join("|"); } /** @@ -502,9 +480,7 @@ export class ThemeManager { public async getAvailableThemes(): Promise { verboseDebug("[ThemeManager] Getting available themes"); try { - const themeIds = (await localforage.getItem("customThemes")) as - | string[] - | null; + const themeIds = (await localforage.getItem("customThemes")) as string[] | null; if (!themeIds) { return []; } @@ -535,9 +511,7 @@ export class ThemeManager { } await localforage.setItem(toSave.id, toSave); - const themeIds = (await localforage.getItem("customThemes")) as - | string[] - | null; + const themeIds = (await localforage.getItem("customThemes")) as string[] | null; if (themeIds) { if (!themeIds.includes(toSave.id)) { @@ -565,9 +539,7 @@ export class ThemeManager { } await localforage.removeItem(themeId); - const themeIds = (await localforage.getItem("customThemes")) as - | string[] - | null; + const themeIds = (await localforage.getItem("customThemes")) as string[] | null; if (themeIds) { const updatedThemeIds = themeIds.filter((id) => id !== themeId); await localforage.setItem("customThemes", updatedThemeIds); @@ -582,14 +554,15 @@ export class ThemeManager { private get THEME_API_BASE(): string { return `${getApiBase()}/api`; } - private readonly GITHUB_THEMES_BASE = 'https://raw.githubusercontent.com/BetterSEQTA/BetterSEQTA-Themes/main/store/themes'; + private readonly GITHUB_THEMES_BASE = + "https://raw.githubusercontent.com/BetterSEQTA/BetterSEQTA-Themes/main/store/themes"; /** * Fetch JSON from a URL via background script (avoids CORS when running inside SEQTA page) */ private async fetchFromUrl(url: string, options?: { auth?: boolean }): Promise { const result = (await browser.runtime.sendMessage({ - type: 'fetchFromUrl', + type: "fetchFromUrl", url, auth: options?.auth === true, })) as { data?: unknown; error?: string }; @@ -751,9 +724,7 @@ export class ThemeManager { if (!isAllowedFetchUrl(themeJsonUrl)) { throw new Error("Theme download URL not allowed"); } - themeData = (await this.fetchFromUrl( - themeJsonUrl, - )) as ThemeContent; + themeData = (await this.fetchFromUrl(themeJsonUrl)) as ThemeContent; } catch (apiError) { console.warn("[ThemeManager] API failed, trying GitHub fallback:", apiError); const githubUrl = `${this.GITHUB_THEMES_BASE}/${themeContent.id}/theme.json`; @@ -769,10 +740,7 @@ export class ThemeManager { /** * Install a theme from theme data */ - public async installTheme( - themeData: ThemeContent, - meta?: InstallThemeMeta, - ): Promise { + public async installTheme(themeData: ThemeContent, meta?: InstallThemeMeta): Promise { verboseDebug("[ThemeManager] Installing theme:", themeData.name); try { if (!themeData.id || !themeData.name) { @@ -805,10 +773,7 @@ export class ThemeManager { let coverImageBlob = null; if (themeData.coverImage) { try { - coverImageBlob = base64ToBlob( - stripBase64Prefix(themeData.coverImage), - "image/png", - ); + coverImageBlob = base64ToBlob(stripBase64Prefix(themeData.coverImage), "image/png"); } catch (e) { console.warn("[ThemeManager] Failed to process cover image:", e); } @@ -851,10 +816,7 @@ export class ThemeManager { installedFromStore: fromStore, installedFromCommunity: fromCommunity || undefined, userEdited: fromStore ? false : undefined, - storeSyncedAtSec: - fromStore && serverUpdatedAtSec != null - ? serverUpdatedAtSec - : undefined, + storeSyncedAtSec: fromStore && serverUpdatedAtSec != null ? serverUpdatedAtSec : undefined, forceTheme: themeData.forceTheme !== undefined ? themeData.forceTheme @@ -900,18 +862,13 @@ export class ThemeManager { const serverById = new Map(); for (const t of res.data.themes) { - if ( - typeof t.id === "string" && - typeof t.updated_at === "number" - ) { + if (typeof t.id === "string" && typeof t.updated_at === "number") { serverById.set(t.id, t.updated_at); } } if (serverById.size === 0) return; - const themeIds = (await localforage.getItem("customThemes")) as - | string[] - | null; + const themeIds = (await localforage.getItem("customThemes")) as string[] | null; if (!themeIds?.length) return; for (const id of themeIds) { @@ -930,10 +887,7 @@ export class ThemeManager { continue; } - if ( - theme.installedFromStore === true && - theme.storeSyncedAtSec != null - ) { + if (theme.installedFromStore === true && theme.storeSyncedAtSec != null) { if (serverUpdated <= theme.storeSyncedAtSec) { continue; } @@ -951,10 +905,7 @@ export class ThemeManager { name: theme.name, updated_at: serverUpdated, }); - verboseInfo( - "[ThemeManager] Theme auto-updated from store:", - theme.name, - ); + verboseInfo("[ThemeManager] Theme auto-updated from store:", theme.name); if (wasSelected) { await this.setTheme(id, false); } @@ -1014,9 +965,7 @@ export class ThemeManager { })), ); - const coverImageBase64 = coverImage - ? await blobToBase64Data(coverImage) - : null; + const coverImageBase64 = coverImage ? await blobToBase64Data(coverImage) : null; // Create shareable theme data with only necessary fields const shareableTheme = { @@ -1043,10 +992,7 @@ export class ThemeManager { if (!theme.webURL) { if (this.originalPreviewColor === null) { this.originalPreviewColor = settingsState.selectedColor; - localStorage.setItem( - "originalPreviewColor", - settingsState.selectedColor, - ); + localStorage.setItem("originalPreviewColor", settingsState.selectedColor); } if (this.originalPreviewTheme === null) { this.originalPreviewTheme = settingsState.DarkMode; @@ -1103,9 +1049,7 @@ export class ThemeManager { if (previewImages.length > 0) { const imageKey = this.imageSyncKey(previewImages); const shouldSyncImages = - inCreatorSession || - imageKey !== this.lastSyncedImageKey || - theme.CustomCSS !== undefined; + inCreatorSession || imageKey !== this.lastSyncedImageKey || theme.CustomCSS !== undefined; if (shouldSyncImages) { syncInput.images = previewImages; this.lastSyncedImageKey = imageKey; @@ -1128,9 +1072,8 @@ export class ThemeManager { setCustomThemeAdaptiveCssVariables(theme.adaptiveCssVariables ?? []); - const { applyThemeCreatorMetaToSettings } = await import( - "@/interface/utils/themeCreatorMeta" - ); + const { applyThemeCreatorMetaToSettings } = + await import("@/interface/utils/themeCreatorMeta"); applyThemeCreatorMetaToSettings(theme.creatorMeta); void updateAllColors(); @@ -1139,12 +1082,9 @@ export class ThemeManager { } } - public updatePreviewDebounced = debounce( - (theme: Partial): void => { - this.updatePreview(theme); - }, - 2, - ); + public updatePreviewDebounced = debounce((theme: Partial): void => { + this.updatePreview(theme); + }, 2); /** * Start Theme Creator: keep the current theme on SEQTA; preview layers on top only. @@ -1199,25 +1139,16 @@ export class ThemeManager { settingsState.selectedColor = storedColor; localStorage.removeItem("originalPreviewColor"); } else if (this.originalPreviewColor !== null) { - verboseDebug( - "[ThemeManager] Restoring color from memory:", - this.originalPreviewColor, - ); + verboseDebug("[ThemeManager] Restoring color from memory:", this.originalPreviewColor); settingsState.selectedColor = this.originalPreviewColor; - verboseDebug( - "[ThemeManager] Color after restore:", - settingsState.selectedColor, - ); + verboseDebug("[ThemeManager] Color after restore:", settingsState.selectedColor); } else { verboseDebug("[ThemeManager] No color to restore found"); } this.originalPreviewColor = null; if (this.originalPreviewTheme !== null) { - verboseDebug( - "[ThemeManager] Restoring dark mode:", - this.originalPreviewTheme, - ); + verboseDebug("[ThemeManager] Restoring dark mode:", this.originalPreviewTheme); settingsState.DarkMode = this.originalPreviewTheme; this.originalPreviewTheme = null; } diff --git a/src/plugins/built-in/themes/theme-runtime.ts b/src/plugins/built-in/themes/theme-runtime.ts index 4c2c802f..def0f072 100644 --- a/src/plugins/built-in/themes/theme-runtime.ts +++ b/src/plugins/built-in/themes/theme-runtime.ts @@ -145,7 +145,6 @@ function getMinutesOfDay(now: Date = new Date()): number { return now.getHours() * 60 + now.getMinutes(); } - function clamp01(value: number): number { return Math.max(0, Math.min(1, value)); } @@ -177,10 +176,10 @@ function darknessForMinutes(minutes: number): number { * to anything. */ const LIT_OPACITIES: Record = { - night: [1.0, 1.0, 1.0], - dawn: [1.0, 0.0, 0.0], - day: [0.0, 0.0, 0.0], - dusk: [1.0, 0.6, 0.0], + night: [1.0, 1.0, 1.0], + dawn: [1.0, 0.0, 0.0], + day: [0.0, 0.0, 0.0], + dusk: [1.0, 0.6, 0.0], evening: [1.0, 1.0, 0.5], }; @@ -270,9 +269,7 @@ export function validateThemeScript(script: unknown): script is ThemeScriptSpec if (s.onInterval !== undefined && !isAllowedCall(s.onInterval)) return false; if ( s.interval !== undefined && - (typeof s.interval !== "number" || - !Number.isFinite(s.interval) || - s.interval < MIN_INTERVAL_MS) + (typeof s.interval !== "number" || !Number.isFinite(s.interval) || s.interval < MIN_INTERVAL_MS) ) { return false; } @@ -299,10 +296,7 @@ export function validateThemeDom(dom: unknown): dom is ThemeDomSpec { if (d.roadStrip !== undefined && typeof d.roadStrip !== "boolean") return false; if ( d.cars !== undefined && - (typeof d.cars !== "number" || - !Number.isInteger(d.cars) || - d.cars < 0 || - d.cars > MAX_CARS) + (typeof d.cars !== "number" || !Number.isInteger(d.cars) || d.cars < 0 || d.cars > MAX_CARS) ) { return false; } @@ -594,8 +588,7 @@ function mountDevTimePicker(): void { if (document.getElementById(DEV_PICKER_ID)) return; const initialOverride = readDevOverride(); - const startMinutes = - initialOverride ?? new Date().getHours() * 60 + new Date().getMinutes(); + const startMinutes = initialOverride ?? new Date().getHours() * 60 + new Date().getMinutes(); const useReal = initialOverride === null; const panel = document.createElement("div"); diff --git a/src/plugins/built-in/timetable/calendarSyncUi.ts b/src/plugins/built-in/timetable/calendarSyncUi.ts index 62efdf0b..ce063ac2 100644 --- a/src/plugins/built-in/timetable/calendarSyncUi.ts +++ b/src/plugins/built-in/timetable/calendarSyncUi.ts @@ -65,9 +65,7 @@ export function portalToBody(node: HTMLElement) { export function isCalendarSyncModalTarget(target: EventTarget | null): boolean { return ( target instanceof Element && - Boolean( - target.closest(".bsplus-cal-modal-backdrop, .bsplus-cal-disconnect-overlay"), - ) + Boolean(target.closest(".bsplus-cal-modal-backdrop, .bsplus-cal-disconnect-overlay")) ); } @@ -114,21 +112,17 @@ export function syncCalendarSyncTheme(target: HTMLElement): void { computed.getPropertyValue("--background-secondary").trim() || computed.getPropertyValue("--theme-offset-bg").trim(); - target.style.setProperty( - "--bsplus-cal-text", - textPrimary || (dark ? "#f4f4f5" : "#18181b"), - ); - target.style.setProperty( - "--bsplus-cal-surface", - bgPrimary || (dark ? "#27272a" : "#ffffff"), - ); + target.style.setProperty("--bsplus-cal-text", textPrimary || (dark ? "#f4f4f5" : "#18181b")); + target.style.setProperty("--bsplus-cal-surface", bgPrimary || (dark ? "#27272a" : "#ffffff")); target.style.setProperty( "--bsplus-cal-surface-muted", dark ? "#3f3f46" : "color-mix(in srgb, var(--bsplus-cal-text) 5%, var(--bsplus-cal-surface))", ); target.style.setProperty( "--bsplus-cal-border", - dark ? "color-mix(in srgb, #ffffff 14%, transparent)" : "color-mix(in srgb, var(--bsplus-cal-text) 12%, transparent)", + dark + ? "color-mix(in srgb, #ffffff 14%, transparent)" + : "color-mix(in srgb, var(--bsplus-cal-text) 12%, transparent)", ); } diff --git a/src/plugins/built-in/timetable/index.ts b/src/plugins/built-in/timetable/index.ts index b00a7972..5e6f083c 100644 --- a/src/plugins/built-in/timetable/index.ts +++ b/src/plugins/built-in/timetable/index.ts @@ -40,10 +40,7 @@ const timetablePlugin: Plugin<{}, {}> = { }; // Store event handlers globally for cleanup -const zoomHandlers = new WeakMap< - Element, - { zoomIn: () => void; zoomOut: () => void } ->(); +const zoomHandlers = new WeakMap void; zoomOut: () => void }>(); function resetTimetableStyles(): void { // Reset entry opacity (for assessment hide feature) @@ -59,9 +56,7 @@ function resetTimetableStyles(): void { const handlers = zoomHandlers.get(zoomControls); if (handlers) { const zoomIn = zoomControls.querySelector(".timetable-zoom:nth-child(2)"); - const zoomOut = zoomControls.querySelector( - ".timetable-zoom:nth-child(1)", - ); + const zoomOut = zoomControls.querySelector(".timetable-zoom:nth-child(1)"); if (zoomIn) zoomIn.removeEventListener("click", handlers.zoomIn); if (zoomOut) zoomOut.removeEventListener("click", handlers.zoomOut); zoomHandlers.delete(zoomControls); @@ -80,7 +75,9 @@ async function handleTimetable(): Promise { } if (settingsState.timeFormat == "12") { - const times = document.querySelectorAll(".timetablepage .times .time, .timetablepage .entry.new"); + const times = document.querySelectorAll( + ".timetablepage .times .time, .timetablepage .entry.new", + ); for (const time of times) { if (!time.textContent) continue; time.textContent = convertTo12HourFormat(time.textContent, true); @@ -117,14 +114,14 @@ function handleTimetableZoom(): void { toolbar?.appendChild(zoomControls); const zoomInHandler = () => { - const seqtaZoomIn = document.querySelector('.uiButton.zoom.in') as HTMLElement; + const seqtaZoomIn = document.querySelector(".uiButton.zoom.in") as HTMLElement; if (seqtaZoomIn) { seqtaZoomIn.click(); } }; const zoomOutHandler = () => { - const seqtaZoomOut = document.querySelector('.uiButton.zoom.out') as HTMLElement; + const seqtaZoomOut = document.querySelector(".uiButton.zoom.out") as HTMLElement; if (seqtaZoomOut) { seqtaZoomOut.click(); } diff --git a/src/plugins/built-in/timetableClassmates/accountsClient.ts b/src/plugins/built-in/timetableClassmates/accountsClient.ts index e1b3963b..18802db9 100644 --- a/src/plugins/built-in/timetableClassmates/accountsClient.ts +++ b/src/plugins/built-in/timetableClassmates/accountsClient.ts @@ -1,10 +1,7 @@ import browser from "@/lib/browser"; import { getInstanceHostname } from "@/seqta/utils/feedback/client"; import { ACCOUNTS_BASE } from "./constants"; -import type { - OptInBindingBody, - TimetableClassmatesBindingFields, -} from "./identityBinding"; +import type { OptInBindingBody, TimetableClassmatesBindingFields } from "./identityBinding"; export type PeersResponse = { self: { seqta_student_id: number; cloud_user_id?: string }; @@ -67,7 +64,7 @@ async function accountsFetch( headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, - ...(init?.headers ?? {}), + ...init?.headers, }, }); diff --git a/src/plugins/built-in/timetableClassmates/avatarStack.ts b/src/plugins/built-in/timetableClassmates/avatarStack.ts index 9066883b..cbbc4fb7 100644 --- a/src/plugins/built-in/timetableClassmates/avatarStack.ts +++ b/src/plugins/built-in/timetableClassmates/avatarStack.ts @@ -35,7 +35,12 @@ export function isClassmatesPluginMutation(record: MutationRecord): boolean { return false; } -function stackSignature(classKey: string, maxVisible: number, overflow: number, peerIds: number[]): string { +function stackSignature( + classKey: string, + maxVisible: number, + overflow: number, + peerIds: number[], +): string { return `${classKey}|${maxVisible}|${overflow}|${peerIds.join(",")}`; } @@ -127,7 +132,11 @@ async function hydrateAvatarFromCloud(wrap: HTMLElement, cloudUserId: string): P } } -function openRosterPopup(classTitle: string, allSorted: AvatarListInput[], peopleCache: PeopleCache): void { +function openRosterPopup( + classTitle: string, + allSorted: AvatarListInput[], + peopleCache: PeopleCache, +): void { openClassmatesRosterPopup( classTitle || "Classmates", allSorted.map((p) => { diff --git a/src/plugins/built-in/timetableClassmates/index.ts b/src/plugins/built-in/timetableClassmates/index.ts index a0f92746..e241605a 100644 --- a/src/plugins/built-in/timetableClassmates/index.ts +++ b/src/plugins/built-in/timetableClassmates/index.ts @@ -25,14 +25,8 @@ import { getStudentId } from "@/seqta/utils/userInfo"; import { peerCloudIdsForPaint } from "./accountsClient"; import { fetchSchoolYearEnrollmentSnapshot } from "./timetableYearSnapshot"; import { CLASSMATES_TIMETABLE_POLL_MS } from "./constants"; -import { - bindClassmatesOptInActivated, - scheduleClassmatesSyncIfNeeded, -} from "./syncOrchestrator"; -import { - mountClassmatesToolbarChip, - unmountClassmatesToolbarChip, -} from "./classmatesToolbarUi"; +import { bindClassmatesOptInActivated, scheduleClassmatesSyncIfNeeded } from "./syncOrchestrator"; +import { mountClassmatesToolbarChip, unmountClassmatesToolbarChip } from "./classmatesToolbarUi"; import { maybeResumeTimetableClassmatesOptInPopup } from "./openTimetableClassmatesPopup"; const timetableClassmatesPlugin: Plugin = { @@ -141,11 +135,15 @@ const timetableClassmatesPlugin: Plugin = { const title = quickbar.querySelector(".title")?.textContent?.trim() ?? ""; const host = (quickbar.querySelector(".meta") as HTMLElement | null) ?? (quickbar as HTMLElement); - paints.push(paintHost(host, classKeyFromCi(ciOf(findClassEntryByTitle(page, title)), ciMap))); + paints.push( + paintHost(host, classKeyFromCi(ciOf(findClassEntryByTitle(page, title)), ciMap)), + ); } } - const homeDays = document.querySelectorAll("#day-container .day[data-bsplus-meta-id]"); + const homeDays = document.querySelectorAll( + "#day-container .day[data-bsplus-meta-id]", + ); for (const day of homeDays) { paints.push(paintHost(day, classKeyForHomeDay(day))); } @@ -191,18 +189,17 @@ const timetableClassmatesPlugin: Plugin = { window.addEventListener(CLASSMATES_UPDATED_EVENT, onUpdated); const onRepaintClick = (e: Event) => { - if ( - (e.target as HTMLElement).closest?.( - ".timetablepage .entry.class, #day-container .day", - ) - ) { + if ((e.target as HTMLElement).closest?.(".timetablepage .entry.class, #day-container .day")) { schedulePaint(); } }; document.addEventListener("click", onRepaintClick, true); const { unregister: unregisterEnabled } = api.settings.onChange("enabled", schedulePaint); - const { unregister: unregisterTimetable } = api.seqta.onMount(".timetablepage", handleTimetablePage); + const { unregister: unregisterTimetable } = api.seqta.onMount( + ".timetablepage", + handleTimetablePage, + ); const { unregister: unregisterHome } = api.seqta.onMount("#home-container", handleHomePage); if ((await loadSession()).syncOptIn) { diff --git a/src/plugins/built-in/timetableClassmates/openTimetableClassmatesPopup.ts b/src/plugins/built-in/timetableClassmates/openTimetableClassmatesPopup.ts index 89569617..e49262fb 100644 --- a/src/plugins/built-in/timetableClassmates/openTimetableClassmatesPopup.ts +++ b/src/plugins/built-in/timetableClassmates/openTimetableClassmatesPopup.ts @@ -7,10 +7,7 @@ import TimetableClassmatesOptOutPopup from "./TimetableClassmatesOptOutPopup.sve import popupStyles from "./consentPopup.css?inline"; import { cloudAuth } from "@/seqta/utils/CloudAuth"; import { loadSession } from "./rosterStore"; -import { - clearResumeOptInAfterCloudLogin, - shouldResumeOptInAfterCloudLogin, -} from "./optInResume"; +import { clearResumeOptInAfterCloudLogin, shouldResumeOptInAfterCloudLogin } from "./optInResume"; const STYLE_ID = "bsplus-timetable-classmates-popup-styles"; const CLASSMATES_VIDEO_URL = diff --git a/src/plugins/built-in/timetableClassmates/relayClient.ts b/src/plugins/built-in/timetableClassmates/relayClient.ts index 1b15c3df..fd6c1b9f 100644 --- a/src/plugins/built-in/timetableClassmates/relayClient.ts +++ b/src/plugins/built-in/timetableClassmates/relayClient.ts @@ -53,7 +53,10 @@ export async function runRelayRoundTrip( const url = wsConnectUrl(session, instanceHost); const ws = new WebSocket(url); - const timer = setTimeout(() => finish({ ok: false, error: "Relay connection timed out" }), RELAY_TIMEOUT_MS); + const timer = setTimeout( + () => finish({ ok: false, error: "Relay connection timed out" }), + RELAY_TIMEOUT_MS, + ); ws.addEventListener("message", (event) => { void (async () => { diff --git a/src/plugins/built-in/timetableClassmates/relayCrypto.ts b/src/plugins/built-in/timetableClassmates/relayCrypto.ts index 32b0e3ce..b20b9fc5 100644 --- a/src/plugins/built-in/timetableClassmates/relayCrypto.ts +++ b/src/plugins/built-in/timetableClassmates/relayCrypto.ts @@ -21,7 +21,10 @@ async function sha256(data: Uint8Array): Promise, classKey: string): Promise { +async function classAesKey( + bundleKey: Uint8Array, + classKey: string, +): Promise { const prefix = new TextEncoder().encode(`tq-v1:${classKey}`); const material = new Uint8Array(bundleKey.length + 1 + prefix.length); material.set(bundleKey, 0); @@ -62,9 +65,7 @@ export async function encryptClassBundle( const key = await classAesKey(bundleKey, classKey); const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES)); const compressed = await compressUtf8(JSON.stringify(plaintext)); - const ct = new Uint8Array( - await crypto.subtle.encrypt({ name: "AES-GCM", iv }, key, compressed), - ); + const ct = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv }, key, compressed)); return { class_key: classKey, iv_b64: base64FromBytes(iv), @@ -80,9 +81,7 @@ export async function decryptClassBundle( const key = await classAesKey(bundleKey, bundle.class_key); const iv = Uint8Array.from(atob(bundle.iv_b64), (c) => c.charCodeAt(0)); const ct = Uint8Array.from(atob(bundle.ct_b64), (c) => c.charCodeAt(0)); - const plain = new Uint8Array( - await crypto.subtle.decrypt({ name: "AES-GCM", iv }, key, ct), - ); + const plain = new Uint8Array(await crypto.subtle.decrypt({ name: "AES-GCM", iv }, key, ct)); const json = await decompressUtf8(plain); return JSON.parse(json) as Record; } catch { diff --git a/src/plugins/built-in/timetableClassmates/rosterMerge.ts b/src/plugins/built-in/timetableClassmates/rosterMerge.ts index b70bd4ba..03f37c75 100644 --- a/src/plugins/built-in/timetableClassmates/rosterMerge.ts +++ b/src/plugins/built-in/timetableClassmates/rosterMerge.ts @@ -35,7 +35,7 @@ export function mergePayloadIntoRoster( for (const ref of refs) { const key = classRosterKey(ref); if (!key) continue; - const bucket = { ...(next[key] ?? {}) }; + const bucket = { ...next[key] }; bucket[String(senderId)] = member; next[key] = bucket; } @@ -62,20 +62,14 @@ export function removeMemberFromRoster( return next; } -export function archiveMember( - archived: ArchivedMembers, - seqtaStudentId: number, -): ArchivedMembers { +export function archiveMember(archived: ArchivedMembers, seqtaStudentId: number): ArchivedMembers { return { ...archived, [String(seqtaStudentId)]: { archivedAt: Date.now() }, }; } -export function isMemberArchived( - archived: ArchivedMembers, - seqtaStudentId: number, -): boolean { +export function isMemberArchived(archived: ArchivedMembers, seqtaStudentId: number): boolean { return Boolean(archived[String(seqtaStudentId)]); } @@ -86,7 +80,5 @@ export function rosterPeersForClass( ): RosterMember[] { const bucket = index[classKey]; if (!bucket) return []; - return Object.values(bucket).filter( - (m) => !isMemberArchived(archived, m.seqtaStudentId), - ); + return Object.values(bucket).filter((m) => !isMemberArchived(archived, m.seqtaStudentId)); } diff --git a/src/plugins/built-in/timetableClassmates/seqtaClient.ts b/src/plugins/built-in/timetableClassmates/seqtaClient.ts index 8b2edc52..8ddbc120 100644 --- a/src/plugins/built-in/timetableClassmates/seqtaClient.ts +++ b/src/plugins/built-in/timetableClassmates/seqtaClient.ts @@ -1,9 +1,6 @@ import { getStudentId, tryGetUserInfo } from "@/seqta/utils/userInfo"; -export async function postSeqtaJson( - path: string, - body: Record, -): Promise { +export async function postSeqtaJson(path: string, body: Record): Promise { const res = await fetch(`${location.origin}${path}`, { method: "POST", credentials: "include", diff --git a/src/plugins/built-in/timetableClassmates/settings.ts b/src/plugins/built-in/timetableClassmates/settings.ts index 12fbf4b9..2856fe8e 100644 --- a/src/plugins/built-in/timetableClassmates/settings.ts +++ b/src/plugins/built-in/timetableClassmates/settings.ts @@ -10,7 +10,8 @@ export const timetableClassmatesSettings = defineSettings({ }), showAvatars: componentSetting({ title: "Show classmate avatars", - description: "Display avatar stacks on lessons (saved per SEQTA site and student on this device)", + description: + "Display avatar stacks on lessons (saved per SEQTA site and student on this device)", component: TimetableClassmatesAvatarsSwitch, }), sharing: componentSetting({ diff --git a/src/plugins/built-in/timetableClassmates/syncOrchestrator.ts b/src/plugins/built-in/timetableClassmates/syncOrchestrator.ts index f0feb57a..af839480 100644 --- a/src/plugins/built-in/timetableClassmates/syncOrchestrator.ts +++ b/src/plugins/built-in/timetableClassmates/syncOrchestrator.ts @@ -9,11 +9,7 @@ import { putOptIn, rememberPeerCloudIds, } from "./accountsClient"; -import { - archiveMember, - mergePayloadIntoRoster, - removeMemberFromRoster, -} from "./rosterMerge"; +import { archiveMember, mergePayloadIntoRoster, removeMemberFromRoster } from "./rosterMerge"; import { loadArchivedMembers, loadRosterIndex, @@ -39,7 +35,11 @@ import { fingerprintEnrollment, type EnrollmentSnapshot, } from "./timetableYearSnapshot"; -import { buildEncryptedBundlesForClasses, decodeBundleKey, decryptClassBundle } from "./relayCrypto"; +import { + buildEncryptedBundlesForClasses, + decodeBundleKey, + decryptClassBundle, +} from "./relayCrypto"; import { buildSharePayload } from "./relayPayload"; import { runRelayRoundTrip, sendRelayRevoke, type RelaySnapshotShare } from "./relayClient"; import type { ClassRef } from "./classKeys"; @@ -59,9 +59,7 @@ export function bindClassmatesOptInActivated(fn: (() => void) | null): void { } export function scheduleClassmatesSyncIfNeeded(force = false): void { - syncChain = syncChain - .then(() => runClassmatesSyncIfNeeded(force)) - .catch(() => {}); + syncChain = syncChain.then(() => runClassmatesSyncIfNeeded(force)).catch(() => {}); } async function runClassmatesSyncIfNeeded(force = false): Promise { diff --git a/src/plugins/built-in/timetableClassmates/syncScopes.ts b/src/plugins/built-in/timetableClassmates/syncScopes.ts index 44f13e89..3aece4aa 100644 --- a/src/plugins/built-in/timetableClassmates/syncScopes.ts +++ b/src/plugins/built-in/timetableClassmates/syncScopes.ts @@ -5,7 +5,9 @@ const SYNC_SCOPES_KEY = "plugin.timetable-classmates.storage.syncScopes"; export async function setScopeSyncOptIn(scope: string, optedIn: boolean): Promise { const stored = await browser.storage.local.get(SYNC_SCOPES_KEY); const list = stored[SYNC_SCOPES_KEY]; - const scopes = new Set(Array.isArray(list) ? list.filter((s) => typeof s === "string") : []); + const scopes = new Set( + Array.isArray(list) ? list.filter((s) => typeof s === "string") : [], + ); if (optedIn) scopes.add(scope); else scopes.delete(scope); await browser.storage.local.set({ [SYNC_SCOPES_KEY]: [...scopes] }); diff --git a/src/plugins/built-in/timetableClassmates/timetableClassmates.test.ts b/src/plugins/built-in/timetableClassmates/timetableClassmates.test.ts index eda66977..175b8aa5 100644 --- a/src/plugins/built-in/timetableClassmates/timetableClassmates.test.ts +++ b/src/plugins/built-in/timetableClassmates/timetableClassmates.test.ts @@ -1,8 +1,4 @@ -import { - buildAvatarDisplayList, - classRefsFromTimetableItems, - classRosterKey, -} from "./classKeys"; +import { buildAvatarDisplayList, classRefsFromTimetableItems, classRosterKey } from "./classKeys"; import { buildSharePayload } from "./relayPayload"; import { buildIdentityBindingCanonical } from "./identityBinding"; import { @@ -43,9 +39,7 @@ describe("classRosterKey", () => { }); it("falls back to code and programmeID", () => { - expect(classRosterKey({ code: "AEMAA1", programmeID: 6865 })).toBe( - "cr:v1:AEMAA1:6865", - ); + expect(classRosterKey({ code: "AEMAA1", programmeID: 6865 })).toBe("cr:v1:AEMAA1:6865"); }); }); @@ -145,11 +139,7 @@ describe("buildAvatarDisplayList", () => { }); it("excludes self", () => { - const { visible } = buildAvatarDisplayList( - [{ seqtaStudentId: 3, updatedAt: 1 }], - 3, - 4, - ); + const { visible } = buildAvatarDisplayList([{ seqtaStudentId: 3, updatedAt: 1 }], 3, 4); expect(visible).toHaveLength(0); }); }); diff --git a/src/plugins/built-in/timetableClassmates/timetableYearSnapshot.ts b/src/plugins/built-in/timetableClassmates/timetableYearSnapshot.ts index 71f7ab83..3118032e 100644 --- a/src/plugins/built-in/timetableClassmates/timetableYearSnapshot.ts +++ b/src/plugins/built-in/timetableClassmates/timetableYearSnapshot.ts @@ -10,7 +10,9 @@ export type EnrollmentSnapshot = { }; /** Stable hash for “did my enrollments change?” checks. */ -export function fingerprintEnrollment(snapshot: Pick): string { +export function fingerprintEnrollment( + snapshot: Pick, +): string { const classKeys = snapshot.classes .map((c) => classRosterKey(c)) .filter((k): k is string => Boolean(k)) diff --git a/src/plugins/built-in/timetableEdit/index.ts b/src/plugins/built-in/timetableEdit/index.ts index 49f4fbef..9d5ce3f9 100644 --- a/src/plugins/built-in/timetableEdit/index.ts +++ b/src/plugins/built-in/timetableEdit/index.ts @@ -16,7 +16,6 @@ interface TimetableOverridesBySubject { [description: string]: { room?: string; staff?: string }; } - /** SEQTA timetable entries use .teacher and .room as direct children, and data-instance for ci */ function getRoomAndTeacherElements(entry: HTMLElement): { roomEl: HTMLElement | null; @@ -34,12 +33,7 @@ function showEditModal( item: TimetableEntryData, overrides: TimetableOverrides | undefined, overridesBySubject: TimetableOverridesBySubject | undefined, - onSave: ( - ci: number, - room: string, - staff: string, - applyToFuture: boolean, - ) => void, + onSave: (ci: number, room: string, staff: string, applyToFuture: boolean) => void, onClear: (ci: number) => void, ): void { const overlay = document.createElement("div"); @@ -48,8 +42,7 @@ function showEditModal( const modal = document.createElement("div"); modal.className = "timetable-edit-modal"; - const override = - overrides?.[String(item.ci)] ?? overridesBySubject?.[item.description]; + const override = overrides?.[String(item.ci)] ?? overridesBySubject?.[item.description]; const roomValue = override?.room ?? item.room ?? ""; const staffValue = override?.staff ?? item.staff ?? ""; @@ -94,31 +87,23 @@ function showEditModal( modal.addEventListener("mousedown", (e) => e.stopPropagation()); modal.addEventListener("mouseup", (e) => e.stopPropagation()); - const roomInput = modal.querySelector( - "#timetable-edit-room", - ) as HTMLInputElement; - const staffInput = modal.querySelector( - "#timetable-edit-staff", - ) as HTMLInputElement; + const roomInput = modal.querySelector("#timetable-edit-room") as HTMLInputElement; + const staffInput = modal.querySelector("#timetable-edit-staff") as HTMLInputElement; const applyFutureCheckbox = modal.querySelector( "#timetable-edit-apply-future", ) as HTMLInputElement; - modal - .querySelector(".timetable-edit-btn-save") - ?.addEventListener("click", () => { - onSave( - item.ci, - roomInput.value.trim(), - staffInput.value.trim(), - applyFutureCheckbox?.checked ?? false, - ); - removeModal(); - }); + modal.querySelector(".timetable-edit-btn-save")?.addEventListener("click", () => { + onSave( + item.ci, + roomInput.value.trim(), + staffInput.value.trim(), + applyFutureCheckbox?.checked ?? false, + ); + removeModal(); + }); - modal - .querySelector(".timetable-edit-btn-cancel") - ?.addEventListener("click", removeModal); + modal.querySelector(".timetable-edit-btn-cancel")?.addEventListener("click", removeModal); const clearBtn = modal.querySelector(".timetable-edit-btn-clear"); if (clearBtn) { @@ -148,8 +133,7 @@ const timetableEditPlugin = { } | null = null; let lastSyncedQuickbarCi: number | null = null; - const getOverrides = (): TimetableOverrides => - api.storage.timetableOverrides ?? {}; + const getOverrides = (): TimetableOverrides => api.storage.timetableOverrides ?? {}; const getOverridesBySubject = (): TimetableOverridesBySubject => api.storage.timetableOverridesBySubject ?? {}; @@ -159,10 +143,7 @@ const timetableEditPlugin = { ): { room?: string; staff?: string } | undefined => getOverrides()[String(ci)] ?? getOverridesBySubject()[description]; - const findClassEntry = ( - title: string, - calendarId?: string | null, - ): HTMLElement | null => { + const findClassEntry = (title: string, calendarId?: string | null): HTMLElement | null => { if (calendarId) { const byCalendar = document.querySelector( `.timetablepage .entry.class[data-calendarid="${calendarId}"]`, @@ -170,9 +151,7 @@ const timetableEditPlugin = { if (byCalendar) return byCalendar as HTMLElement; } - for (const entry of document.querySelectorAll( - ".timetablepage .entry.class", - )) { + for (const entry of document.querySelectorAll(".timetablepage .entry.class")) { const entryTitle = entry.querySelector(".title")?.textContent?.trim(); if (entryTitle === title) return entry as HTMLElement; } @@ -183,10 +162,8 @@ const timetableEditPlugin = { const title = quickbar.querySelector(".title")?.textContent?.trim() ?? ""; if (!title) return; - const quickbarRoom = - quickbar.querySelector(".meta .room")?.textContent?.trim() ?? ""; - const quickbarStaff = - quickbar.querySelector(".meta .teacher")?.textContent?.trim() ?? ""; + const quickbarRoom = quickbar.querySelector(".meta .room")?.textContent?.trim() ?? ""; + const quickbarStaff = quickbar.querySelector(".meta .teacher")?.textContent?.trim() ?? ""; const entry = findClassEntry(title); if (entry) { @@ -246,10 +223,8 @@ const timetableEditPlugin = { const override = getEffectiveOverride(ci, description); if (override) { - if (override.room !== undefined && roomEl) - roomEl.textContent = override.room; - if (override.staff !== undefined && teacherEl) - teacherEl.textContent = override.staff; + if (override.room !== undefined && roomEl) roomEl.textContent = override.room; + if (override.staff !== undefined && teacherEl) teacherEl.textContent = override.staff; } entry.addEventListener( @@ -265,19 +240,14 @@ const timetableEditPlugin = { }; const processAllEntries = () => { - document - .querySelectorAll(".timetablepage .entry.class") - .forEach((entry) => { - processEntry(entry as HTMLElement); - }); + document.querySelectorAll(".timetablepage .entry.class").forEach((entry) => { + processEntry(entry as HTMLElement); + }); }; const getVisibleClassQuickbar = (): HTMLElement | null => { - const quickbar = document.querySelector( - ".timetablepage .quickbar.visible", - ); - if (!quickbar || quickbar.getAttribute("data-type") !== "class") - return null; + const quickbar = document.querySelector(".timetablepage .quickbar.visible"); + if (!quickbar || quickbar.getAttribute("data-type") !== "class") return null; return quickbar as HTMLElement; }; @@ -304,18 +274,10 @@ const timetableEditPlugin = { if (override.room !== undefined && !roomEl) return; if (override.staff !== undefined && !teacherEl) return; - if ( - override.room !== undefined && - roomEl && - roomEl.textContent !== override.room - ) { + if (override.room !== undefined && roomEl && roomEl.textContent !== override.room) { roomEl.textContent = override.room; } - if ( - override.staff !== undefined && - teacherEl && - teacherEl.textContent !== override.staff - ) { + if (override.staff !== undefined && teacherEl && teacherEl.textContent !== override.staff) { teacherEl.textContent = override.staff; } @@ -328,8 +290,7 @@ const timetableEditPlugin = { const roomEl = quickbar.querySelector(".meta .room"); const teacherEl = quickbar.querySelector(".meta .teacher"); if (roomEl && roomEl.textContent !== room) roomEl.textContent = room; - if (teacherEl && teacherEl.textContent !== staff) - teacherEl.textContent = staff; + if (teacherEl && teacherEl.textContent !== staff) teacherEl.textContent = staff; if (lastClickedCi !== null) lastSyncedQuickbarCi = lastClickedCi; }; @@ -354,9 +315,7 @@ const timetableEditPlugin = { syncClassQuickbar(quickbar); - const hasButton = quickbar.querySelector( - ".timetable-edit-quickbar-btn", - ); + const hasButton = quickbar.querySelector(".timetable-edit-quickbar-btn"); const hasActions = quickbar.querySelector(".actions"); if ((!hasButton || !hasActions) && ++attempts < maxAttempts) { quickbarSyncTimer = setTimeout(trySync, 50); @@ -372,9 +331,7 @@ const timetableEditPlugin = { const actions = quickbar.querySelector(".actions"); if (!actions) return; - const colourBtn = actions.querySelector( - "[title='Choose a colour'], button.uiButton", - ); + const colourBtn = actions.querySelector("[title='Choose a colour'], button.uiButton"); const btn = document.createElement("button"); btn.type = "button"; btn.className = @@ -395,12 +352,9 @@ const timetableEditPlugin = { const entryData = lastClickedEntry; if (!entryData) return; - const quickbarRoom = - qb.querySelector(".meta .room")?.textContent?.trim() ?? ""; - const quickbarTeacher = - qb.querySelector(".meta .teacher")?.textContent?.trim() ?? ""; - const quickbarTitle = - qb.querySelector(".title")?.textContent?.trim() ?? ""; + const quickbarRoom = qb.querySelector(".meta .room")?.textContent?.trim() ?? ""; + const quickbarTeacher = qb.querySelector(".meta .teacher")?.textContent?.trim() ?? ""; + const quickbarTitle = qb.querySelector(".title")?.textContent?.trim() ?? ""; const ci = lastClickedCi ?? entryData.item.ci; const item: TimetableEntryData = { ci, @@ -446,8 +400,7 @@ const timetableEditPlugin = { delete bySubject[item.description]; api.storage.timetableOverridesBySubject = bySubject; if (entryData.roomEl) entryData.roomEl.textContent = item.room; - if (entryData.teacherEl) - entryData.teacherEl.textContent = item.staff; + if (entryData.teacherEl) entryData.teacherEl.textContent = item.staff; updateVisibleQuickbar(item.room, item.staff); processAllEntries(); }, @@ -472,19 +425,13 @@ const timetableEditPlugin = { if (!quickbar) return; const shouldSync = mutations.some((mutation) => { - if ( - mutation.type === "attributes" && - mutation.attributeName === "class" - ) { + if (mutation.type === "attributes" && mutation.attributeName === "class") { const target = mutation.target as HTMLElement; return target.classList.contains("quickbar"); } if (mutation.type === "childList") { const target = mutation.target as HTMLElement; - return ( - target.classList?.contains("quickbar") || - target.closest?.(".quickbar") - ); + return target.classList?.contains("quickbar") || target.closest?.(".quickbar"); } return false; }); @@ -524,13 +471,11 @@ const timetableEditPlugin = { const timetablePage = document.querySelector(".timetablepage"); if (timetablePage && !observer) { observer = new MutationObserver(() => { - document - .querySelectorAll(".timetablepage .entry.class") - .forEach((entry) => { - if (!entry.hasAttribute("data-timetable-edit-processed")) { - processEntry(entry as HTMLElement); - } - }); + document.querySelectorAll(".timetablepage .entry.class").forEach((entry) => { + if (!entry.hasAttribute("data-timetable-edit-processed")) { + processEntry(entry as HTMLElement); + } + }); }); observer.observe(timetablePage, { childList: true, subtree: true }); } @@ -544,14 +489,10 @@ const timetableEditPlugin = { observer?.disconnect(); quickbarObserver?.disconnect(); if (quickbarSyncTimer !== null) clearTimeout(quickbarSyncTimer); - document - .querySelectorAll("[data-timetable-edit-processed]") - .forEach((el) => { - el.removeAttribute("data-timetable-edit-processed"); - }); - document - .querySelectorAll(".timetable-edit-quickbar-btn") - .forEach((el) => el.remove()); + document.querySelectorAll("[data-timetable-edit-processed]").forEach((el) => { + el.removeAttribute("data-timetable-edit-processed"); + }); + document.querySelectorAll(".timetable-edit-quickbar-btn").forEach((el) => el.remove()); }; }, }; diff --git a/src/plugins/built-in/timetableEdit/styles.css b/src/plugins/built-in/timetableEdit/styles.css index fe77b549..683de31f 100644 --- a/src/plugins/built-in/timetableEdit/styles.css +++ b/src/plugins/built-in/timetableEdit/styles.css @@ -82,7 +82,10 @@ background: var(--background-secondary); color: var(--text-primary); box-sizing: border-box; - transition: border-color 0.2s ease, box-shadow 0.2s ease, transform 0.15s ease; + transition: + border-color 0.2s ease, + box-shadow 0.2s ease, + transform 0.15s ease; user-select: text; -webkit-user-select: text; } diff --git a/src/plugins/core/createAPI.ts b/src/plugins/core/createAPI.ts index a859ad4a..d5a6afb2 100644 --- a/src/plugins/core/createAPI.ts +++ b/src/plugins/core/createAPI.ts @@ -60,10 +60,7 @@ function createSettingsAPI( const listeners = new Map void>>(); const settingsWithMeta: any = { - onChange: ( - key: K, - callback: (value: SettingValue) => void, - ) => { + onChange: (key: K, callback: (value: SettingValue) => void) => { if (!listeners.has(key)) { listeners.set(key, new Set()); } @@ -74,17 +71,14 @@ function createSettingsAPI( }, }; }, - offChange: ( - key: K, - callback: (value: SettingValue) => void, - ) => { + offChange: (key: K, callback: (value: SettingValue) => void) => { listeners.get(key)?.delete(callback); }, loaded: Promise.resolve(), // will be replaced below }; for (const key in plugin.settings) { - if (plugin.settings[key].type !== 'component' && plugin.settings[key].type !== 'button') { + if (plugin.settings[key].type !== "component" && plugin.settings[key].type !== "button") { settingsWithMeta[key] = plugin.settings[key].default; } } @@ -98,17 +92,12 @@ function createSettingsAPI( for (const key in storedSettings) { if (key in settingsWithMeta) { settingsWithMeta[key] = storedSettings[key]; - listeners - .get(key as keyof T) - ?.forEach((cb) => cb(storedSettings[key])); + listeners.get(key as keyof T)?.forEach((cb) => cb(storedSettings[key])); } } } } catch (error) { - console.error( - `[BetterSEQTA+] Error loading settings for plugin ${plugin.id}:`, - error, - ); + console.error(`[BetterSEQTA+] Error loading settings for plugin ${plugin.id}:`, error); } })(); @@ -125,16 +114,10 @@ function createSettingsAPI( } }; - settingsState.register( - storageKey as keyof SettingsState, - handleSettingsChange, - ); + settingsState.register(storageKey as keyof SettingsState, handleSettingsChange); const dispose = () => { - settingsState.unregister( - storageKey as keyof SettingsState, - handleSettingsChange, - ); + settingsState.unregister(storageKey as keyof SettingsState, handleSettingsChange); }; const proxy = new Proxy(settingsWithMeta, { @@ -142,8 +125,7 @@ function createSettingsAPI( return target[prop]; }, set(target, prop, value) { - if (["onChange", "offChange", "loaded"].includes(prop as string)) - return false; + if (["onChange", "offChange", "loaded"].includes(prop as string)) return false; target[prop] = value; @@ -156,9 +138,7 @@ function createSettingsAPI( // Preserve enabled flag managed separately for disableToggle plugins if (plugin.disableToggle) { const allSettings = settingsState.getAll() as Record; - const existing = allSettings[storageKey] as - | { enabled?: boolean } - | undefined; + const existing = allSettings[storageKey] as { enabled?: boolean } | undefined; if (existing?.enabled !== undefined) { dataToStore.enabled = existing.enabled; } @@ -197,18 +177,11 @@ function createStorageAPI( } }); } catch (error) { - console.error( - `[BetterSEQTA+] Error loading storage for plugin ${pluginId}:`, - error, - ); + console.error(`[BetterSEQTA+] Error loading storage for plugin ${pluginId}:`, error); } })(); - const handleStorageChange = ( - newValue: unknown, - _oldValue: unknown, - key: string, - ) => { + const handleStorageChange = (newValue: unknown, _oldValue: unknown, key: string) => { if (!key.startsWith(prefix)) return; const shortKey = key.slice(prefix.length); diff --git a/src/plugins/core/dynamicLoader.ts b/src/plugins/core/dynamicLoader.ts index 5cc31402..2cb89ea7 100644 --- a/src/plugins/core/dynamicLoader.ts +++ b/src/plugins/core/dynamicLoader.ts @@ -41,7 +41,10 @@ export function createLazyPlugin( - plugin: Plugin, - ): void { + public registerPlugin(plugin: Plugin): void { if (this.plugins.has(plugin.id)) { throw new Error(`Plugin with id "${plugin.id}" is already registered`); } @@ -186,10 +184,7 @@ export class PluginManager { } catch (error) { this.removePluginStyles(pluginId); this.disposePluginAPI(pluginId); - console.error( - `[BetterSEQTA+] Failed to start plugin ${pluginId}:`, - error, - ); + console.error(`[BetterSEQTA+] Failed to start plugin ${pluginId}:`, error); throw error; } } @@ -201,10 +196,7 @@ export class PluginManager { if (!isRemotePluginStartAllowed(plugin.id)) { return false; } - if ( - isRemoteRouteEnhancementsStripped() && - !ROUTE_STRIP_KEEP_PLUGINS.has(plugin.id) - ) { + if (isRemoteRouteEnhancementsStripped() && !ROUTE_STRIP_KEEP_PLUGINS.has(plugin.id)) { return false; } if (!plugin.disableToggle) return true; @@ -314,7 +306,11 @@ export class PluginManager { id: string; options: Array<{ value: string; label: string }>; }) - | (Omit & { type: "button"; id: string; trigger?: () => void | Promise }) + | (Omit & { + type: "button"; + id: string; + trigger?: () => void | Promise; + }) | (Omit & { type: "hotkey"; id: string }) | (Omit & { type: "component"; id: string; component: any }); }; @@ -322,27 +318,23 @@ export class PluginManager { // Array<{ pluginId: string; name: string; description: string; beta?: boolean; settings: Record; disableToggle?: boolean; }> }> { return Array.from(this.plugins.entries()).map(([id, plugin]) => { - const settingsEntries = Object.entries(plugin.settings).map( - ([key, setting]) => { - const settingObj = setting as any; - let result: any; - if (settingObj.type === "button" || settingObj.type === "component") { - // For button or component, keep the functions - result = { ...settingObj }; - } else { - result = Object.fromEntries( - Object.entries(settingObj).filter( - ([_, value]) => typeof value !== "function", - ), - ); - } - result.id = key; - result.title = result.title || key; - result.description = result.description || ""; - result.defaultEnabled = plugin.defaultEnabled ?? true; - return [key, result]; - }, - ); + const settingsEntries = Object.entries(plugin.settings).map(([key, setting]) => { + const settingObj = setting as any; + let result: any; + if (settingObj.type === "button" || settingObj.type === "component") { + // For button or component, keep the functions + result = { ...settingObj }; + } else { + result = Object.fromEntries( + Object.entries(settingObj).filter(([_, value]) => typeof value !== "function"), + ); + } + result.id = key; + result.title = result.title || key; + result.description = result.description || ""; + result.defaultEnabled = plugin.defaultEnabled ?? true; + return [key, result]; + }); if (plugin.disableToggle) { settingsEntries.push([ @@ -392,10 +384,7 @@ export class PluginManager { } } - private async handlePluginStateChange( - pluginId: string, - enabled: boolean, - ): Promise { + private async handlePluginStateChange(pluginId: string, enabled: boolean): Promise { if (enabled) { await this.startPlugin(pluginId); } else { @@ -425,13 +414,9 @@ export class PluginManager { if (!plugin?.disableToggle) continue; const enabled = - (change.newValue as PluginSettingsStorage)?.enabled ?? - plugin.defaultEnabled ?? - true; + (change.newValue as PluginSettingsStorage)?.enabled ?? plugin.defaultEnabled ?? true; const wasEnabled = - (change.oldValue as PluginSettingsStorage)?.enabled ?? - plugin.defaultEnabled ?? - true; + (change.oldValue as PluginSettingsStorage)?.enabled ?? plugin.defaultEnabled ?? true; if (enabled !== wasEnabled) { this.handlePluginStateChange(pluginId, enabled); diff --git a/src/plugins/core/settingsHelpers.ts b/src/plugins/core/settingsHelpers.ts index b6c6df36..2255b3c7 100644 --- a/src/plugins/core/settingsHelpers.ts +++ b/src/plugins/core/settingsHelpers.ts @@ -8,27 +8,21 @@ import type { StringSetting, } from "./types"; -export function numberSetting( - options: Omit, -): NumberSetting { +export function numberSetting(options: Omit): NumberSetting { return { type: "number", ...options, }; } -export function booleanSetting( - options: Omit, -): BooleanSetting { +export function booleanSetting(options: Omit): BooleanSetting { return { type: "boolean", ...options, }; } -export function stringSetting( - options: Omit, -): StringSetting { +export function stringSetting(options: Omit): StringSetting { return { type: "string", ...options, @@ -44,35 +38,30 @@ export function selectSetting( }; } -export function buttonSetting( - options: Omit, -): ButtonSetting { +export function buttonSetting(options: Omit): ButtonSetting { return { type: "button", ...options, }; } - -export function componentSetting( - options: Omit, -): ComponentSetting { +export function componentSetting(options: Omit): ComponentSetting { return { type: "component", ...options, }; } -export function hotkeySetting( - options: Omit, -): HotkeySetting { +export function hotkeySetting(options: Omit): HotkeySetting { return { type: "hotkey", ...options, }; } -export function defineSettings>(settings: TSettings): TSettings { +export function defineSettings>( + settings: TSettings, +): TSettings { return settings; } diff --git a/src/plugins/core/types.ts b/src/plugins/core/types.ts index fb1b371e..35e79786 100644 --- a/src/plugins/core/types.ts +++ b/src/plugins/core/types.ts @@ -90,18 +90,12 @@ export type SettingsAPI = { key: K, callback: (value: SettingValue) => void, ) => { unregister: () => void }; - offChange: ( - key: K, - callback: (value: SettingValue) => void, - ) => void; + offChange: (key: K, callback: (value: SettingValue) => void) => void; loaded: Promise; }; export interface SEQTAAPI { - onMount: ( - selector: string, - callback: (element: Element) => void, - ) => { unregister: () => void }; + onMount: (selector: string, callback: (element: Element) => void) => { unregister: () => void }; getFiber: (selector: string) => ReactFiber; getCurrentPage: () => string; onPageChange: (callback: (page: string) => void) => { @@ -129,10 +123,7 @@ export type TypedStorageAPI = StorageAPI & { }; export interface EventsAPI { - on: ( - event: string, - callback: (...args: any[]) => void, - ) => { unregister: () => void }; + on: (event: string, callback: (...args: any[]) => void) => { unregister: () => void }; emit: (event: string, ...args: any[]) => void; } diff --git a/src/plugins/monofile.ts b/src/plugins/monofile.ts index cab444b2..0df3e50a 100644 --- a/src/plugins/monofile.ts +++ b/src/plugins/monofile.ts @@ -4,7 +4,12 @@ import { delay } from "@/seqta/utils/delay"; import stringToHTML from "@/seqta/utils/stringToHTML"; import { MessageHandler } from "@/seqta/utils/listeners/MessageListener"; import { settingsState } from "@/seqta/utils/listeners/SettingsState"; -import { animationsEnabled, fullMotionEffectsEnabled, isPerformanceMode, syncPerformanceModeEffects } from "@/seqta/utils/performanceMode"; +import { + animationsEnabled, + fullMotionEffectsEnabled, + isPerformanceMode, + syncPerformanceModeEffects, +} from "@/seqta/utils/performanceMode"; import { animatePopupOpen } from "@/seqta/utils/popupAnimation"; import { StorageChangeHandler } from "@/seqta/utils/listeners/StorageChanges"; import { eventManager } from "@/seqta/utils/listeners/EventManager"; @@ -79,9 +84,8 @@ export async function finishLoad() { try { // Keep the loading overlay up until the custom title bar is fully ready. if (!isSeqtaEngageExperience() && settingsState.onoff) { - const { waitForCustomTitleBarReady } = await import( - "@/seqta/ui/titlebar/mountCustomTitleBar" - ); + const { waitForCustomTitleBarReady } = + await import("@/seqta/ui/titlebar/mountCustomTitleBar"); await waitForCustomTitleBarReady(); } @@ -122,9 +126,7 @@ function removeThemeTagsFromNotices() { if (!doc?.body) continue; const body = doc.body; const bodyText = body.innerHTML; - body.innerHTML = bodyText - .replace(/\[\[[\w]+[:][\w]+[\]\]]+/g, "") - .replace(/ +/, " "); + body.innerHTML = bodyText.replace(/\[\[[\w]+[:][\w]+[\]\]]+/g, "").replace(/ +/, " "); } catch { // Cross-origin or otherwise inaccessible iframe (common during Engage load / filter frames) } @@ -141,8 +143,7 @@ async function updateIframesWithDarkMode(): Promise { "iframeAdded", { selector: "iframe", - customCheck: (element: Element) => - !element.classList.contains("iframecss"), + customCheck: (element: Element) => !element.classList.contains("iframecss"), }, (element) => { const iframe = element as HTMLIFrameElement; @@ -162,10 +163,7 @@ async function updateIframesWithDarkMode(): Promise { ); } -function applyDarkModeToIframe( - iframe: HTMLIFrameElement, - cssLink: HTMLStyleElement, -): void { +function applyDarkModeToIframe(iframe: HTMLIFrameElement, cssLink: HTMLStyleElement): void { const iframeDocument = iframe.contentDocument; if (!iframeDocument) return; @@ -183,17 +181,14 @@ function applyDarkModeToIframe( } } -function SortMessagePageItems(messagesParentElement: any) { +function SortMessagePageItems() { try { - let filterbutton = document.createElement("div"); + const filterbutton = document.createElement("div"); filterbutton.classList.add("messages-filterbutton"); filterbutton.innerText = "Filter"; - let header = document.querySelector( - "[class*='MessageList__MessageList___']", - ) as HTMLElement; + const header = document.querySelector("[class*='MessageList__MessageList___']") as HTMLElement; header.append(filterbutton); - messagesParentElement; } catch (error) { console.error("Error sorting message page items:", error); } @@ -226,14 +221,10 @@ async function LoadPageElements(): Promise { eventManager.register("reportsAdded", { selector: "div.reports" }, handleReports); - eventManager.register( - "timetableAdded", - { selector: "div.timetablepage" }, - async () => { - attachTimetableColorisRecovery(); - await updateTimetableTimes(); - }, - ); + eventManager.register("timetableAdded", { selector: "div.timetablepage" }, async () => { + attachTimetableColorisRecovery(); + await updateTimetableTimes(); + }); eventManager.register("noticesAdded", { selector: "div.notice" }, handleNotices); @@ -278,9 +269,7 @@ async function handleSublink(sublink: string | undefined): Promise { if (isSeqtaEngageExperience()) { switch (sublink) { case undefined: - window.location.replace( - `${location.origin}/#?page=/${settingsState.defaultPage}`, - ); + window.location.replace(`${location.origin}/#?page=/${settingsState.defaultPage}`); if (settingsState.defaultPage === "home") void loadEngageHomePage(); finishLoad(); break; @@ -304,16 +293,14 @@ async function handleSublink(sublink: string | undefined): Promise { case "analytics": verboseInfo("[BetterSEQTA+] Started Init (Analytics)"); if (settingsState.onoff) { - void import("@/plugins/built-in/gradeAnalytics/loadAnalyticsPage").then( - (m) => m.loadAnalyticsPage(), + void import("@/plugins/built-in/gradeAnalytics/loadAnalyticsPage").then((m) => + m.loadAnalyticsPage(), ); } finishLoad(); break; case undefined: - window.location.replace( - `${location.origin}/#?page=/${settingsState.defaultPage}`, - ); + window.location.replace(`${location.origin}/#?page=/${settingsState.defaultPage}`); if (settingsState.defaultPage === "home") loadHomePage(); if (settingsState.defaultPage === "documents") handleDocuments(document.querySelector(".documents")!); @@ -369,7 +356,7 @@ async function handleMessages(node: Element): Promise { if (legacy instanceof HTMLElement) legacy.innerText = titleText; } document.title = "Direct Messages ― SEQTA Learn"; - SortMessagePageItems(node); + SortMessagePageItems(); if (!animationsEnabled() || !fullMotionEffectsEnabled()) return; @@ -380,9 +367,7 @@ async function handleMessages(node: Element): Promise { document.head.append(style); await waitForElm("[data-message]", true, 10); - const messages = Array.from( - document.querySelectorAll("[data-message]"), - ).slice(0, 35); + const messages = Array.from(document.querySelectorAll("[data-message]")).slice(0, 35); const { animate, stagger } = await loadMotion(); animate( messages, @@ -492,8 +477,7 @@ const scanNotices = (el: Element) => { const scanAddedNotices = debounce((mutations: MutationRecord[]) => { for (const m of mutations) - for (const node of m.addedNodes) - if (node instanceof Element) scanNotices(node); + for (const node of m.addedNodes) if (node instanceof Element) scanNotices(node); }, 50); function CheckNoticeTextColour(notice: Element) { @@ -615,11 +599,7 @@ export function tryLoad() { }); updateIframesWithDarkMode(); - window.addEventListener( - "load", - () => removeThemeTagsFromNotices(), - { once: true }, - ); + window.addEventListener("load", () => removeThemeTagsFromNotices(), { once: true }); } export function showConflictPopup() { @@ -781,10 +761,13 @@ export function init() { }, 120); if (!settingsState.adaptiveThemeColour) return; if (hashColorTimer) clearTimeout(hashColorTimer); - hashColorTimer = setTimeout(() => { - hashColorTimer = null; - void updateAllColors(); - }, isPerformanceMode() ? 200 : 80); + hashColorTimer = setTimeout( + () => { + hashColorTimer = null; + void updateAllColors(); + }, + isPerformanceMode() ? 200 : 80, + ); }); if (!onLogin) { loading(); @@ -800,8 +783,7 @@ export function init() { { selector: ".uiSlidePane, .wispassessment", customCheck: (el) => - el.classList.contains("wispassessment") || - el.querySelector(".wispassessment") !== null, + el.classList.contains("wispassessment") || el.querySelector(".wispassessment") !== null, }, (element) => { const wispassessment = element.classList.contains("wispassessment") @@ -814,8 +796,7 @@ export function init() { const doc = iframe.contentDocument; const win = iframe.contentWindow; if (doc?.body && win) { - const editable = - doc.body.querySelector(".cke_editable") || doc.body; + const editable = doc.body.querySelector(".cke_editable") || doc.body; const el = editable as HTMLElement; el.focus(); const range = doc.createRange(); @@ -849,11 +830,7 @@ export function init() { const iframe = wispassessment.querySelector(".cke_wysiwyg_frame"); if (iframe instanceof HTMLIFrameElement) { - iframe.addEventListener( - "load", - () => focusEditableBody(iframe), - { once: true }, - ); + iframe.addEventListener("load", () => focusEditableBody(iframe), { once: true }); } let attempts = 0; @@ -868,9 +845,7 @@ export function init() { ); setTimeout(() => { - const legacyElement = document.querySelector( - ".outside-container .bottom-container", - ); + const legacyElement = document.querySelector(".outside-container .bottom-container"); if (legacyElement) { verboseLog("Legacy extension detected"); showConflictPopup(); diff --git a/src/plugins/syncablePluginDefaults.ts b/src/plugins/syncablePluginDefaults.ts index 6ee60469..6e2f3d76 100644 --- a/src/plugins/syncablePluginDefaults.ts +++ b/src/plugins/syncablePluginDefaults.ts @@ -12,10 +12,7 @@ function defaultSearchHotkey(): string { } /** `plugin..settings` defaults (component/button keys omitted). */ -export const SYNCABLE_PLUGIN_SETTING_DEFAULTS: Record< - string, - Record -> = { +export const SYNCABLE_PLUGIN_SETTING_DEFAULTS: Record> = { themes: {}, "animated-background": { speed: 1 }, "assessments-average": { lettergrade: false }, diff --git a/src/seqta/content/links.json b/src/seqta/content/links.json index b8e8b5a1..fc59326a 100644 --- a/src/seqta/content/links.json +++ b/src/seqta/content/links.json @@ -1,102 +1,102 @@ { "YouTube": { - "DisplayName":"Youtube", + "DisplayName": "Youtube", "link": "https://www.youtube.com/", "viewBox": "0 0 24 24", "icon": "M10,15L15.19,12L10,9V15M21.56,7.17C21.69,7.64 21.78,8.27 21.84,9.07C21.91,9.87 21.94,10.56 21.94,11.16L22,12C22,14.19 21.84,15.8 21.56,16.83C21.31,17.73 20.73,18.31 19.83,18.56C19.36,18.69 18.5,18.78 17.18,18.84C15.88,18.91 14.69,18.94 13.59,18.94L12,19C7.81,19 5.2,18.84 4.17,18.56C3.27,18.31 2.69,17.73 2.44,16.83C2.31,16.36 2.22,15.73 2.16,14.93C2.09,14.13 2.06,13.44 2.06,12.84L2,12C2,9.81 2.16,8.2 2.44,7.17C2.69,6.27 3.27,5.69 4.17,5.44C4.64,5.31 5.5,5.22 6.82,5.16C8.12,5.09 9.31,5.06 10.41,5.06L12,5C16.19,5 18.8,5.16 19.83,5.44C20.73,5.69 21.31,6.27 21.56,7.17Z" }, "Outlook": { - "DisplayName":"Outlook", + "DisplayName": "Outlook", "link": "https://outlook.office365.com/mail/inbox", "viewBox": "0 0 24 24", "icon": "M8.56 12.03Q8.56 12.41 8.5 12.76 8.39 13.1 8.2 13.38 8 13.65 7.71 13.81 7.41 13.97 7 13.97 6.58 13.97 6.29 13.8 6 13.63 5.81 13.35 5.62 13.07 5.54 12.72 5.45 12.37 5.45 12 5.45 11.64 5.54 11.28 5.62 10.93 5.81 10.65 6 10.37 6.31 10.2 6.61 10.03 7.03 10.03 7.46 10.03 7.75 10.2 8.05 10.38 8.23 10.66 8.41 10.95 8.5 11.3 8.56 11.66 8.56 12.03M22 12V19.81Q22 20.2 21.73 20.5 21.45 20.75 21.06 20.75H7.94Q7.55 20.75 7.27 20.5 7 20.2 7 19.81V17H2.83Q2.5 17 2.24 16.76 2 16.5 2 16.17V7.83Q2 7.5 2.24 7.24 2.5 7 2.83 7H8.25V4.13Q8.25 3.76 8.5 3.5 8.76 3.25 9.13 3.25H19.87Q20.24 3.25 20.5 3.5 20.75 3.76 20.75 4.13V11.04L21.79 11.64H21.8Q21.88 11.7 21.94 11.8 22 11.89 22 12M17 5.13V7.63H19.5V5.13M17 8.88V11.38H19.5V8.88M17 12.63V14.15L19.54 12.63M12.63 5.13V7.63H15.75V5.13M12.63 8.88V11.38H15.75V8.88M12.63 12.63V14.32L14.64 15.56L15.75 14.9V12.63M9.5 5.13V7H11.27Q11.33 7 11.38 7.04V5.12M7 15.32Q7.73 15.32 8.32 15.06 8.9 14.8 9.31 14.35 9.71 13.9 9.91 13.28 10.12 12.66 10.13 11.94 10.13 11.25 9.92 10.65 9.72 10.06 9.32 9.62 8.93 9.18 8.37 8.93 7.8 8.68 7.08 8.68 6.31 8.68 5.71 8.93 5.12 9.18 4.71 9.63 4.3 10.09 4.09 10.71 3.88 11.34 3.88 12.08 3.88 12.78 4.09 13.38 4.31 13.97 4.71 14.4 5.11 14.83 5.68 15.08 6.26 15.32 7 15.32M8.25 19.5H18.57L12 15.4V16.17Q12 16.5 11.76 16.76 11.5 17 11.17 17H8.25M20.75 19.39V13.36L15.83 16.31Z" }, "Office": { - "DisplayName":"Office365", + "DisplayName": "Office365", "link": "http://office.com", "viewBox": "0 0 24 24", "icon": "M19.94 5.59V18.39Q19.94 19.06 19.55 19.59 19.16 20.11 18.5 20.29L12.77 21.94Q12.65 21.97 12.5 22H12.28Q11.95 22 11.68 21.91 11.41 21.82 11.13 21.67L7.38 19.55Q7.17 19.43 7.05 19.24 6.93 19.05 6.93 18.81 6.93 18.45 7.19 18.2 7.44 17.95 7.8 17.95H12.66V6.14L9 7.44Q8.57 7.6 8.3 8 8.03 8.38 8.03 8.85V15.58Q8.03 16 7.82 16.34 7.62 16.68 7.25 16.88L5.53 17.82Q5.29 17.95 5.05 17.95 4.64 17.95 4.35 17.66 4.06 17.37 4.06 16.95V7.47Q4.06 6.95 4.33 6.5 4.61 6 5.06 5.74L11.22 2.24Q11.43 2.12 11.67 2.06 11.91 2 12.15 2 12.32 2 12.46 2.03 12.6 2.05 12.77 2.1L18.5 3.69Q18.83 3.78 19.09 3.96 19.35 4.14 19.54 4.39 19.74 4.65 19.84 4.95 19.94 5.26 19.94 5.59M18.62 18.39V5.59Q18.62 5.36 18.5 5.19 18.35 5 18.13 4.96L15.31 4.18Q15 4.09 14.65 4 14.32 3.89 14 3.81V20.21L18.13 19Q18.35 18.96 18.5 18.79 18.62 18.62 18.62 18.39Z" }, "Spotify": { - "DisplayName":"Spotify", + "DisplayName": "Spotify", "link": "https://accounts.spotify.com/en/login", "viewBox": "0 0 24 24", "icon": "M17.9,10.9C14.7,9 9.35,8.8 6.3,9.75C5.8,9.9 5.3,9.6 5.15,9.15C5,8.65 5.3,8.15 5.75,8C9.3,6.95 15.15,7.15 18.85,9.35C19.3,9.6 19.45,10.2 19.2,10.65C18.95,11 18.35,11.15 17.9,10.9M17.8,13.7C17.55,14.05 17.1,14.2 16.75,13.95C14.05,12.3 9.95,11.8 6.8,12.8C6.4,12.9 5.95,12.7 5.85,12.3C5.75,11.9 5.95,11.45 6.35,11.35C10,10.25 14.5,10.8 17.6,12.7C17.9,12.85 18.05,13.35 17.8,13.7M16.6,16.45C16.4,16.75 16.05,16.85 15.75,16.65C13.4,15.2 10.45,14.9 6.95,15.7C6.6,15.8 6.3,15.55 6.2,15.25C6.1,14.9 6.35,14.6 6.65,14.5C10.45,13.65 13.75,14 16.35,15.6C16.7,15.75 16.75,16.15 16.6,16.45M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10,10 0 0,0 12,2Z" }, "Google": { - "DisplayName":"Google", + "DisplayName": "Google", "link": "https://google.com", "viewBox": "0 0 24 24", "icon": "M12,20L15.46,14H15.45C15.79,13.4 16,12.73 16,12C16,10.8 15.46,9.73 14.62,9H19.41C19.79,9.93 20,10.94 20,12A8,8 0 0,1 12,20M4,12C4,10.54 4.39,9.18 5.07,8L8.54,14H8.55C9.24,15.19 10.5,16 12,16C12.45,16 12.88,15.91 13.29,15.77L10.89,19.91C7,19.37 4,16.04 4,12M15,12A3,3 0 0,1 12,15A3,3 0 0,1 9,12A3,3 0 0,1 12,9A3,3 0 0,1 15,12M12,4C14.96,4 17.54,5.61 18.92,8H12C10.06,8 8.45,9.38 8.08,11.21L5.7,7.08C7.16,5.21 9.44,4 12,4M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10,10 0 0,0 12,2Z" }, "DuckDuckGo": { - "DisplayName":"DuckDuckGo", + "DisplayName": "DuckDuckGo", "link": "https://duckduckgo.com/", "viewBox": "0 0 32 32", "icon": "M16 0c-8.839 0-16 7.161-16 16s7.161 16 16 16c8.839 0 16-7.161 16-16s-7.161-16-16-16zM16 30.667c-8.099 0-14.667-6.568-14.667-14.667s6.568-14.667 14.667-14.667c8.099 0 14.667 6.568 14.667 14.667s-6.568 14.667-14.667 14.667zM29.625 16c0 6.406-4.422 11.776-10.38 13.234-0.359-0.698-0.708-1.359-1-1.917 0.859 0.328 2.573 0.953 2.943 0.818 0.505-0.193 0.38-4.198-0.182-4.328-0.453-0.099-2.177 1.12-2.859 1.615l0.047 0.208c0.104 0.526 0.193 1.323 0.042 1.661 0 0.005-0.005 0.016-0.005 0.016-0.021 0.047-0.052 0.089-0.094 0.12-0.375 0.25-1.438 0.38-2 0.25-0.031-0.005-0.057-0.016-0.089-0.026-0.922 0.526-2.677 1.479-3 1.297-0.438-0.255-0.5-3.573-0.438-4.385 0.047-0.615 2.203 0.38 3.255 0.906 0.234-0.219 0.802-0.365 1.307-0.417-0.76-1.849-1.318-3.969-0.979-5.474 0 0.005 0.005 0.005 0.005 0.005 0.474 0.328 3.641 1.401 5.214 1.37s4.151-0.99 3.87-1.766c-0.281-0.771-2.849 0.682-5.521 0.432-1.984-0.182-2.333-1.073-1.896-1.719 0.552-0.818 1.557 0.151 3.214-0.344 1.661-0.495 3.984-1.38 4.844-1.859 1.995-1.115-0.833-1.573-1.5-1.266-0.63 0.297-2.828 0.849-3.849 1.094 0.568-2.021-0.807-5.531-2.344-7.068-0.5-0.5-1.271-0.813-2.141-0.979-0.333-0.458-0.87-0.896-1.63-1.302-1.474-0.771-3.156-1.047-4.797-0.781l-0.031 0.005-0.042 0.005 0.005 0.005c-0.198 0.036-0.318 0.104-0.479 0.13 0.198 0.021 0.943 0.37 1.411 0.557-0.234 0.089-0.552 0.146-0.797 0.245-0.094 0.016-0.182 0.036-0.271 0.073-0.229 0.109-0.406 0.5-0.401 0.688 1.12-0.115 2.776-0.031 3.99 0.328-0.859 0.12-1.646 0.344-2.214 0.646-0.021 0.010-0.042 0.021-0.068 0.036-0.068 0.026-0.141 0.057-0.198 0.089-1.823 0.958-2.63 3.203-2.151 5.896 0.432 2.432 2.219 10.786 3.052 14.755-5.297-1.87-9.094-6.917-9.094-12.854 0-7.526 6.099-13.625 13.625-13.625s13.625 6.099 13.625 13.625zM12.125 12.776c-0.557 0-1.010 0.453-1.010 1.010s0.453 1.010 1.010 1.010c1.349 0 1.349-2.021 0-2.021zM12.578 13.708c-0.146 0-0.26-0.115-0.26-0.26 0-0.141 0.115-0.26 0.26-0.26 0.349 0 0.349 0.521 0 0.521zM18.875 12.318c-0.49-0.016-0.901 0.375-0.901 0.87 0 0.49 0.411 0.885 0.901 0.865 1.156 0 1.156-1.734 0-1.734zM19.26 13.12c-0.12 0-0.224-0.099-0.224-0.224 0-0.12 0.104-0.224 0.224-0.224 0.302 0 0.302 0.448 0 0.448zM12.417 10.859c0 0-0.76-0.344-1.5 0.12-0.74 0.469-0.714 0.943-0.714 0.943s-0.391-0.875 0.656-1.307c1.047-0.427 1.557 0.245 1.557 0.245zM19.401 10.792c0 0-0.547-0.313-0.974-0.307-0.875 0.010-1.109 0.396-1.109 0.396s0.146-0.917 1.26-0.734c0.365 0.068 0.672 0.307 0.823 0.646z" }, "CoolMathGames": { - "DisplayName":"CoolMathGames", + "DisplayName": "CoolMathGames", "link": "https://coolmathgames.com/", "viewBox": "0 0 24 24", "icon": "M16.5,9L13.5,12L16.5,15H22V9M9,16.5V22H15V16.5L12,13.5M7.5,9H2V15H7.5L10.5,12M15,7.5V2H9V7.5L12,10.5L15,7.5Z" }, "SACE": { - "DisplayName":"SACE", + "DisplayName": "SACE", "link": "https://apps.sace.sa.edu.au/students-online/login.do", "viewBox": "0 0 125.2 125", "icon": "M103,40.1H84.8v-18C84.8,9.9,74.8,0,62.6,0C50.4,0,40.3,9.9,40.3,22.1c0,12.2,10,22.1,22.2,22.1h18.1v36H44.5v-18c0-12.2-10-22.1-22.2-22.1S0,50,0,62.2s10,22.1,22.2,22.1h18.1v18c0,12.2,10,22.1,22.2,22.1s22.2-9.9,22.2-22.1v-18h18.1c12.4,0,22.4-9.9,22.4-22.1S115.2,40.1,103,40.1z M40.3,80.2H22.2c-10,0-18.1-8.1-18.1-18s8.1-18,18.1-18s18.1,8.1,18.1,18V80.2zM80.7,102.3c0,9.9-8.1,18-18.1,18s-18.1-8.1-18.1-18v-18h36.2V102.3z M80.7,40.1H62.6c-10,0-18.1-8.1-18.1-18c0-9.9,8.1-18,18.1-18s18.1,8.1,18.1,18V40.1z M102.9,80.2H84.8v-36h18.1c10,0,18.1,8.1,18.1,18S112.9,80.2,102.9,80.2z" }, "GoogleScholar": { - "DisplayName":"Google Scholar", + "DisplayName": "Google Scholar", "link": "https://scholar.google.com", "viewBox": "0 0 24 24", "icon": "M21.35,11.1H12.18V13.83H18.69C18.36,17.64 15.19,19.27 12.19,19.27C8.36,19.27 5,16.25 5,12C5,7.9 8.2,4.73 12.2,4.73C15.29,4.73 17.1,6.7 17.1,6.7L19,4.72C19,4.72 16.56,2 12.1,2C6.42,2 2.03,6.8 2.03,12C2.03,17.05 6.16,22 12.25,22C17.6,22 21.5,18.33 21.5,12.91C21.5,11.76 21.35,11.1 21.35,11.1V11.1Z" }, "Gmail": { - "DisplayName":"Gmail", + "DisplayName": "Gmail", "link": "https://mail.google.com", "viewBox": "0 0 24 24", "icon": "M20,18H18V9.25L12,13L6,9.25V18H4V6H5.2L12,10.25L18.8,6H20M20,4H4C2.89,4 2,4.89 2,6V18A2,2 0 0,0 4,20H20A2,2 0 0,0 22,18V6C22,4.89 21.1,4 20,4Z" }, "Netflix": { - "DisplayName":"Netflix", + "DisplayName": "Netflix", "link": "https://netflix.com", "viewBox": "0 0 24 24", "icon": "M6.5,2H10.5L13.44,10.83L13.5,2H17.5V22C16.25,21.78 14.87,21.64 13.41,21.58L10.5,13L10.43,21.59C9.03,21.65 7.7,21.79 6.5,22V2Z" }, "EducationPerfect": { - "DisplayName":"Education perfect", + "DisplayName": "Education perfect", "link": "https://app.educationperfect.com/", "viewBox": "-14 -14 195 195", "icon": "m10.4416 135.353c1.4147 11.671 6.1052 21.415 16.9276 27.917 7.761 4.618 15.7359 5.355 24.0693 4.317 6.9762-.869 13.9511-1.749 20.9261-2.629 20.5955-2.599 41.1914-5.199 61.8194-7.505 22.622-2.529 35.971-17.699 33.53-40.246-3.163-29.2176-6.82-58.3877-10.734-87.5149-2.64-19.6412-20.094-31.93255-39.737-29.35091-27.95 3.67351-55.9352 7.10359-83.9427 10.31421-22.6545 2.597-35.69333 18.7386-32.934793 41.3362 2.016273 16.517 4.006133 33.0373 5.996003 49.5574 1.35724 11.268 2.71449 22.537 4.08009 33.804zm75.7961-30.85c-.0009-2.622-.0018-5.2439-.0028-7.8659 0-3.1641-.0134-6.2421-.0265-9.2569-.0357-8.2331-.0694-15.9944.1768-23.7469.071-2.2322 1.86-6.1171 3.2009-6.2723.5604-.0648 1.1565-.171 1.7693-.2802 3.3234-.592 7.1379-1.2715 8.4074 4.0816 7.7742-5.7078 16.1472-7.136 24.6472-2.5114 8.709 4.738 12.454 12.8252 12.025 22.4923-.234 5.2704-.822 10.8692-2.838 15.65-5.481 12.9927-20.052 16.8437-31.864 9.0597-.383-.252-.77-.499-1.322-.852-.315-.201-.6843-.437-1.1374-.728 0 2.04-.0179 4.011-.0354 5.936-.0395 4.354-.0768 8.463.1005 12.563.1785 4.125-1.7841 5.326-5.4159 5.12-.5296-.03-1.0763-.032-1.6227-.034-3.0313-.012-6.0503-.023-6.0538-4.816-.0045-6.18-.0066-12.359-.0086-18.539zm-51.331-9.007c-.1403-.2846-.2805-.5693-.4217-.8535-.0341-.1443-.0679-.2884-.1012-.4323-.116-.5004-.227-.9982-.3325-1.4932-1.9708-9.2421-2.0513-17.5563 2.7315-25.2978.0103-.0167.0206-.0333.0309-.05.1553-.2502.3157-.4998.4813-.7488 6.4799-9.7451 18.577-13.2695 29.5877-8.6224 9.6292 4.0641 16.8171 17.16 14.3021 27.1024-.3938 1.5569-3.7009 3.2931-5.7188 3.3672-7.0719.2595-14.1548.2219-21.2382.1842-2.5219-.0134-5.0439-.0268-7.5655-.0268.1004 8.0982 8.3794 11.52 17.4533 7.9322 2.9193-1.1544 6.148-1.6313 9.3298-2.0136.4545-.0546.908-.1073 1.3596-.1597l.1998-.0232c1.3215-.1536 3.7445.656 3.9712 1.4877.3914 1.436-.0396 3.6414-.9957 4.8156-9.4729 11.63-33.2723 14.035-42.1607-3.3382-.3104-.6068-.6117-1.2183-.9129-1.8298z" }, "Deezer": { - "DisplayName":"Deezer", + "DisplayName": "Deezer", "link": "https://www.deezer.com/", "viewBox": "-35 -35 510 510", "icon": "M429.821 187.348c1.892-.99 3.958-1.637 4.8-3.026 6.074-10.021 7.289-21.442 7.701-32.687.491-13.389.121-26.881-1.012-40.232-.634-7.472-3.22-14.866-5.665-22.043-.769-2.258-3.832-4.925-6.046-5.12-1.761-.155-3.856 3.141-5.735 4.974-.428.418-.63 1.103-.844 1.697-3.991 11.096-6.001 22.559-5.856 34.332.142 11.473.32 22.96 1.033 34.406.527 8.452 2.146 16.829 6.658 24.224.929 1.522 3.019 2.335 4.966 3.475ZM3.063 152.917c.326 3.005.372 5.621 1.029 8.073 2.044 7.636 3.655 15.491 6.714 22.719 2.434 5.75 7.383 5.268 10.304-.23 5.322-10.017 6.797-21.055 7.159-32.031.443-13.415.094-26.922-1.019-40.296-.61-7.339-3.149-14.608-5.557-21.656-.784-2.293-3.917-5.249-5.96-5.236-2.058.012-4.114 3.318-6.128 5.225-.326.308-.466.834-.635 1.28-4.072 10.756-5.659 21.97-5.872 33.385-.176 9.431-.036 18.869-.035 28.767ZM200 420c2.936 5.193 5.282 10.332 8.434 14.917 7.87 11.45 21.102 11.499 28.732-.137 4.266-6.506 8.136-13.506 10.783-20.792 7.107-19.564 11.491-39.844 13.946-60.533.41-3.46 1.256-6.867 1.637-8.895 3.949 10.845 7.467 22.831 12.659 34.042 4.326 9.342 11.965 11.217 17.708.856 4.343-7.836 7.997-16.519 9.702-25.265 4.738-24.301 8.3-48.831 12.176-72.361.348 1.259 1.027 3.795 1.75 6.319 3.6 12.569 6.45 25.402 15.036 35.948 5.731 7.04 12.531 8.265 17.966 1.248 4.907-6.334 9.469-13.664 11.591-21.278 4.572-16.394 7.496-33.25 11.049-49.926.69-3.237 1.177-6.517 1.798-10.006 2.624 5.449 4.622 10.51 7.396 15.101 2.738 4.531 8.735 4.479 11.826.211 1.385-1.913 2.48-4.096 3.383-6.289 4.901-11.906 7.723-24.334 8.844-37.138 1.67-19.055 4.323-38.105 4.562-57.182.27-21.61-1.298-43.274-2.789-64.864-.78-11.292-2.464-22.624-4.951-33.665-1.902-8.445-5.189-16.702-8.845-24.585-2.44-5.26-9.076-5.06-12.198-.18-1.873 2.93-3.513 6.116-4.636 9.398-2.132 6.232-3.817 12.617-5.982 19.933-2.231-9.352-3.63-17.898-6.366-25.991-3.253-9.63-7.17-19.11-11.696-28.2-4.394-8.83-15.305-9.71-20.69-2.17-2.406 3.37-4.983 6.75-6.629 10.5-7.099 16.19-10.992 33.279-13.582 50.703-.912 6.141-1.978 12.259-2.95 18.241-2.797-11.593-5.159-23.177-8.486-34.477-1.916-6.509-4.896-12.846-8.305-18.737-3.319-5.73-9.26-7.03-15.088-.32-1.34 1.55-2.295 3.48-3.188 5.35-7.888 16.501-10.88 34.357-13.568 52.159-2.583 17.109-3.954 34.402-5.843 51.481-.283-.719-.728-1.815-1.148-2.92-4.528-11.914-8.023-24.36-13.819-35.621-8.652-16.806-22.885-19.301-33.986-1.699-7.254 11.5-11.222 24.297-14.713 37.284-.239.889-.77 1.699-1.207 2.633-1.244-11.59-2.167-22.812-3.715-33.947-2.001-14.398-4.041-28.82-6.934-43.056-2.218-10.915-5.266-21.759-11.614-31.234-4.272-6.38-11.328-6.56-15.399-.18-2.388 3.75-4.746 7.749-5.959 11.968-4.016 13.972-7.505 28.095-10.778 40.566-1.753-10.101-3.517-22.099-5.974-33.954-2.983-14.39-6.718-28.58-14.467-41.36-6.34-10.47-17.549-11.57-23.695-.85-.875 1.53-1.972 2.93-2.776 4.49-8.296 16.1-11.371 33.755-14.625 48.825-3.101-8.161-6.449-18.434-10.921-28.195-2.707-5.91-9.291-5.82-12.417-.11-2.874 5.26-5.218 10.943-6.877 16.703-7.393 25.666-8.68 52.211-9.595 78.625-.66 19.038.607 38.185 1.833 57.231.894 13.892 2.35 27.848 5.015 41.491 1.897 9.71 5.65 19.199 9.668 28.305 2.639 5.98 9.081 5.748 12.476.07 2.647-4.428 4.61-9.265 6.901-13.97.256.517.778 1.171.907 1.895 2.647 14.769 4.798 29.645 8.008 44.289 2.424 11.057 6.115 21.85 12.553 31.42 4.334 6.444 9.908 8.987 15.263 6.801 5.596-2.284 8.795-7.239 10.781-12.283 4.99-12.671 9.116-25.683 13.589-38.559-.471 3.861.002 8.012.399 12.169.705 7.359.993 14.781 2.124 22.072 1.956 12.615 4.128 25.214 6.766 37.701 2.173 10.281 4.603 20.587 10.605 29.55 5.914 8.832 11.941 8.945 17.623-.044 6.995-11.069 9.16-23.856 12.583-36.394C185.588 369.161 189.939 395.091 200 420Z" }, - "GoogleClassroom":{ - "DisplayName":"Google Classroom", + "GoogleClassroom": { + "DisplayName": "Google Classroom", "link": "https://classroom.google.com/", "viewBox": "-31 -31 560 560", "icon": "M36 80 36 420C36 431 46 440 56 440L444 440C454 440 464 431 464 420L464 80C464 70 456 60 444 60L56 60C45 60 36 70 36 80ZM56.205 55.205 443.795 55.205C450.697 55.249 457.13 58.085 461.638 62.596 466.145 67.107 468.975 73.539 469.019 80.429L469.019 419.571C468.975 426.461 466.145 432.893 461.638 437.404 457.13 441.915 450.697 444.751 443.795 444.795L56.205 444.795C49.315 444.751 42.882 441.915 38.372 437.404 33.861 432.894 31.025 426.461 30.981 419.571L30.981 80.429C31.025 73.539 33.861 67.106 38.372 62.596 42.882 58.085 49.315 55.249 56.205 55.205ZM298.45 395.346 395.347 395.346 395.347 443.795 298.45 443.795 298.45 395.346ZM250 250C277.979 250 295.469 219.72 281.469 195.496 274.975 184.256 262.984 177.326 250 177.326 222.046 177.326 204.556 207.607 218.533 231.832 225.025 243.072 237.016 250 250 250ZM250 268.168C225.751 268.168 177.328 280.329 177.328 304.504L177.328 322.674 322.674 322.674 322.674 304.504C322.674 280.329 274.249 268.168 250 268.168ZM340.841 213.663C319.863 213.663 306.757 236.362 317.248 254.529 322.116 262.961 331.103 268.168 340.841 268.168 361.821 268.168 374.95 245.446 364.461 227.278 359.591 218.847 350.579 213.663 340.841 213.663ZM340.841 281.807C336.724 281.807 331.637 282.291 326.258 283.211 331.177 288.905 334.786 296.22 334.786 304.504L334.786 322.674 395.347 322.674 395.347 309.035C395.347 290.915 359.01 281.807 340.841 281.807ZM298.934 292.345C291.497 296.607 286.337 302.203 286.337 309.059L286.337 310.561 310.561 310.561 310.561 304.504C310.561 302.518 309.786 300.581 306.492 297.552 304.191 295.542 301.647 293.798 298.934 292.345ZM159.159 213.663C138.181 213.663 125.075 236.362 135.564 254.529 140.434 262.961 149.421 268.168 159.159 268.168 180.137 268.168 193.268 245.446 182.777 227.278 177.909 218.847 168.897 213.663 159.159 213.663ZM159.159 281.807C140.991 281.807 104.654 290.915 104.654 309.035L104.654 322.674 165.215 322.674 165.215 304.504C165.215 296.22 168.848 288.905 173.742 283.211 168.945 282.315 164.052 281.856 159.159 281.782L159.159 281.807ZM201.066 292.345C198.354 293.798 195.834 295.542 193.51 297.552 190.215 300.581 189.439 302.518 189.439 304.504L189.439 310.561 213.663 310.561 213.663 309.035C213.663 302.203 208.505 296.607 201.066 292.345Z" }, - "Reddit":{ - "DisplayName":"Reddit", + "Reddit": { + "DisplayName": "Reddit", "link": "https://www.reddit.com/", "viewBox": "-2 -2 24 24", "icon": "M13 12c-.762 0-1.401-.6258-1.401-1.3976 0-.7728.639-1.4189 1.401-1.4189.761 0 1.378.6461 1.378 1.4189C14.378 11.3742 13.762 12 13 12m.194 2.5822c-.673.6816-1.728 1.0132-3.224 1.0132-1.497 0-2.551-.3316-3.223-1.0132-.146-.1481-.146-.3874 0-.5365.145-.1481.382-.1481.528 0 .525.5325 1.406.7921 2.695.7921 1.288 0 2.17-.2596 2.696-.7921.145-.1481.382-.1481.528 0 .146.1491.146.3884 0 .5365M5.563 10.6024c0-.7718.638-1.4189 1.399-1.4189s1.378.6471 1.378 1.4189C8.34 11.3742 7.723 12 6.962 12s-1.399-.6258-1.399-1.3976M19.971 9.0659c0-1.2667-1.016-2.2972-2.265-2.2972-.576 0-1.119.218-1.535.6085-1.495-.9868-3.497-1.6247-5.714-1.712l1.223-3.786 3.212.7667c.001 1.0426.837 1.8894 1.865 1.8894s1.865-.8489 1.865-1.8915c0-1.0426-.837-1.8915-1.865-1.8915-.77 0-1.431.4747-1.716 1.1511-.692-.1653-3.166-.7566-3.858-.9219L9.673 5.6572c-2.301.0436-4.386.6785-5.937 1.6886-.411-.3702-.943-.5771-1.501-.5771-1.248 0-2.264 1.0304-2.264 2.2972 0 .8043.414 1.5416 1.076 1.9554-.603 3.6126 3.594 6.7312 8.882 6.7312 5.266 0 9.449-3.0913 8.891-6.6856.708-.4026 1.151-1.1572 1.151-2.001" }, - "HarvardReferencer":{ - "DisplayName":"Harvard Referencer", + "HarvardReferencer": { + "DisplayName": "Harvard Referencer", "link": "https://www.mybib.com/tools/harvard-referencing-generator", "viewBox": "-7 -7 78 78", "icon": "M52,63.999c-1.039,0-2.062-0.406-2.828-1.172L32,45.655L14.828,62.827 c-1.148,1.145-2.863,1.488-4.359,0.867C8.973,63.077,8,61.616,8,59.999v-56c0-2.211,1.789-4,4-4h40c2.211,0,4,1.789,4,4v56 c0,1.617-0.973,3.078-2.469,3.695C53.035,63.901,52.516,63.999,52,63.999z M32,35.999c1.023,0,2.047,0.391,2.828,1.172L48,50.343 V7.999H16v42.344l13.172-13.172C29.953,36.39,30.977,35.999,32,35.999z M32,35.999c1.023,0,2.047,0.391,2.828,1.172L48,50.343V7.999H16v42.344l13.172-13.172 C29.953,36.39,30.977,35.999,32,35.999z" }, - "ChatGPT":{ - "DisplayName":"ChatGPT", + "ChatGPT": { + "DisplayName": "ChatGPT", "link": "https://chatgpt.com", "viewBox": "0 0 41 41", "icon": "M37.532 16.87a9.96 9.96 0 0 0-.856-8.184 10.08 10.08 0 0 0-10.855-4.835A9.96 9.96 0 0 0 18.306.5a10.08 10.08 0 0 0-9.614 6.977 9.97 9.97 0 0 0-6.664 4.834 10.08 10.08 0 0 0 1.24 11.817 9.97 9.97 0 0 0 .856 8.185 10.08 10.08 0 0 0 10.855 4.835 9.97 9.97 0 0 0 7.516 3.35 10.08 10.08 0 0 0 9.617-6.981 9.97 9.97 0 0 0 6.663-4.834 10.08 10.08 0 0 0-1.243-11.813M22.498 37.886a7.47 7.47 0 0 1-4.799-1.735c.061-.033.168-.091.237-.134l7.964-4.6a1.3 1.3 0 0 0 .655-1.134V19.054l3.366 1.944a.12.12 0 0 1 .066.092v9.299a7.505 7.505 0 0 1-7.49 7.496zm-16.106-6.88a7.47 7.47 0 0 1-.894-5.023c.06.036.162.099.237.141l7.964 4.6a1.3 1.3 0 0 0 1.308 0l9.724-5.614v3.888a.12.12 0 0 1-.048.103l-8.051 4.649a7.504 7.504 0 0 1-10.24-2.744M4.297 13.62A7.47 7.47 0 0 1 8.2 10.333c0 .068-.004.19-.004.274v9.201a1.3 1.3 0 0 0 .654 1.132l9.723 5.614-3.366 1.944a.12.12 0 0 1-.114.01L7.04 23.856a7.504 7.504 0 0 1-2.743-10.237zm27.658 6.437-9.724-5.615 3.367-1.943a.12.12 0 0 1 .113-.01l8.052 4.648a7.498 7.498 0 0 1-1.158 13.528v-9.476a1.29 1.29 0 0 0-.65-1.132m3.35-5.043a7 7 0 0 0-.236-.141l-7.965-4.6a1.3 1.3 0 0 0-1.308 0l-9.723 5.614v-3.888a.12.12 0 0 1 .048-.103l8.05-4.645a7.497 7.497 0 0 1 11.135 7.763zm-21.063 6.929-3.367-1.944a.12.12 0 0 1-.065-.092v-9.299a7.497 7.497 0 0 1 12.293-5.756 7 7 0 0 0-.236.134l-7.965 4.6a1.3 1.3 0 0 0-.654 1.132zM16.071 18l4.33-2.501 4.332 2.5v5l-4.331 2.5-4.331-2.5z" diff --git a/src/seqta/main.ts b/src/seqta/main.ts index c7cdf811..bba9fc3f 100644 --- a/src/seqta/main.ts +++ b/src/seqta/main.ts @@ -6,26 +6,17 @@ import { extensionPageScriptUrl } from "@/lib/extensionPageScriptUrl"; import injectedCSS from "@/css/injected.scss?inline"; export async function main() { - return new Promise(async (resolve, reject) => { - try { - if (settingsState.onoff) { - injectPageState(); + if (!settingsState.onoff) return; + injectPageState(); - // CRXJS can't hot-reload ?inline CSS, so dev imports the stylesheet directly. - if (import.meta.env.MODE === "development") { - import("@/css/injected.scss"); - } else { - const injectedStyle = document.createElement("style"); - injectedStyle.textContent = injectedCSS; - document.head.appendChild(injectedStyle); - } - } - resolve(true); - } catch (error: any) { - console.error(error); - reject(error); - } - }); + // CRXJS can't hot-reload ?inline CSS, so dev imports the stylesheet directly. + if (import.meta.env.MODE === "development") { + void import("@/css/injected.scss"); + } else { + const injectedStyle = document.createElement("style"); + injectedStyle.textContent = injectedCSS; + document.head.appendChild(injectedStyle); + } } function injectPageState() { diff --git a/src/seqta/ui/AddBetterSEQTAElements.ts b/src/seqta/ui/AddBetterSEQTAElements.ts index b5f5c315..bdb4635a 100644 --- a/src/seqta/ui/AddBetterSEQTAElements.ts +++ b/src/seqta/ui/AddBetterSEQTAElements.ts @@ -21,7 +21,10 @@ import { } from "@/seqta/utils/openers/openThemeToggleSurprise"; import { LUCIDE_MOON_ICON_SVG } from "@/lib/icons/lucideMoon"; import { LUCIDE_SUN_ICON_SVG } from "@/lib/icons/lucideSun"; -import { ensureTitlebarFounderBadgeMounted, refreshTitlebarFounderBadge } from "@/seqta/ui/founderBadge/mountTitlebarFounderBadge"; +import { + ensureTitlebarFounderBadgeMounted, + refreshTitlebarFounderBadge, +} from "@/seqta/ui/founderBadge/mountTitlebarFounderBadge"; import { isPerformanceMode } from "@/seqta/utils/performanceMode"; import { checkRemoteFeature } from "@/seqta/utils/remoteConfig/runtime"; import { remoteChromeGateAllowed } from "@/seqta/utils/remoteConfig/routeGate"; @@ -126,10 +129,7 @@ async function handleUserInfoAndStudentData() { ensureTitlebarFounderBadgeMounted(); await updateStudentInfo((await studentResponse.json()).payload, userInfo); } catch (error) { - console.error( - "[BetterSEQTA+] Failed to handle user info and student data:", - error, - ); + console.error("[BetterSEQTA+] Failed to handle user info and student data:", error); } } @@ -197,9 +197,9 @@ async function updateStudentInfo(students: any, info: Awaited 300 ? "black" : "white"; + houseelement.style.color = colorresult && colorresult > 300 ? "black" : "white"; } catch { // Invalid color format, leave text color as default } @@ -247,10 +246,7 @@ function setupEventListeners() { const newsbutton = document.getElementById("newsbutton"); const activateMenuAction = (button: HTMLElement, action: () => void) => { - if ( - button.classList.contains("draggable") || - button.classList.contains("active") - ) { + if (button.classList.contains("draggable") || button.classList.contains("active")) { return; } @@ -268,9 +264,7 @@ function setupEventListeners() { menuCover?.addEventListener("click", () => { location.href = "../#?page=/home"; loadHomePage(); - ( - document.getElementById("menu")!.firstChild! as HTMLElement - ).classList.remove("noscroll"); + (document.getElementById("menu")!.firstChild! as HTMLElement).classList.remove("noscroll"); }); } @@ -306,10 +300,7 @@ async function injectEngageHomeButton() { document.getElementById("homebutton")?.addEventListener("click", () => { const btn = document.getElementById("homebutton") as HTMLElement; - if ( - btn.classList.contains("draggable") || - btn.classList.contains("active") - ) { + if (btn.classList.contains("draggable") || btn.classList.contains("active")) { return; } window.location.replace(`${location.origin}/#?page=/home`); @@ -337,7 +328,7 @@ async function getEngageUserInfo() { } async function addEngageUserInfo() { - const content = await waitForElm("#content") as HTMLElement; + const content = (await waitForElm("#content")) as HTMLElement; let info: Awaited>; try { @@ -439,11 +430,14 @@ async function setupEngageSettingsButton() { let engageRemountTimer: ReturnType | null = null; const debouncedTryMount = () => { if (engageRemountTimer) clearTimeout(engageRemountTimer); - engageRemountTimer = setTimeout(() => { - engageRemountTimer = null; - if (document.getElementById("AddedSettings")) return; - void tryMount(); - }, isPerformanceMode() ? 300 : 80); + engageRemountTimer = setTimeout( + () => { + engageRemountTimer = null; + if (document.getElementById("AddedSettings")) return; + void tryMount(); + }, + isPerformanceMode() ? 300 : 80, + ); }; const observer = new MutationObserver(debouncedTryMount); @@ -451,9 +445,7 @@ async function setupEngageSettingsButton() { } function GetLightDarkModeString() { - return settingsState.DarkMode - ? "Switch to light theme" - : "Switch to dark theme"; + return settingsState.DarkMode ? "Switch to light theme" : "Switch to dark theme"; } async function addDarkLightToggle(parent?: Element) { @@ -468,9 +460,7 @@ async function addDarkLightToggle(parent?: Element) { updateAllColors(); - const lightDarkModeButtonElement = document.getElementById( - "LightDarkModeButton", - )!; + const lightDarkModeButtonElement = document.getElementById("LightDarkModeButton")!; ensureThemeToggleSurprisePageScript(); @@ -483,10 +473,7 @@ async function addDarkLightToggle(parent?: Element) { return; } - if ( - settingsState.originalDarkMode !== undefined && - settingsState.selectedTheme - ) { + if (settingsState.originalDarkMode !== undefined && settingsState.selectedTheme) { return; } @@ -494,9 +481,7 @@ async function addDarkLightToggle(parent?: Element) { updateAllColors(); const svgElement = lightDarkModeButtonElement.querySelector("svg")!; - svgElement.innerHTML = settingsState.DarkMode - ? LUCIDE_SUN_ICON_SVG - : LUCIDE_MOON_ICON_SVG; + svgElement.innerHTML = settingsState.DarkMode ? LUCIDE_SUN_ICON_SVG : LUCIDE_MOON_ICON_SVG; lightDarkModeButtonElement.setAttribute("aria-label", GetLightDarkModeString()); }); } @@ -560,9 +545,7 @@ function handleSidebarKeyboardActivation(event: KeyboardEvent) { const target = event.target; if (!(target instanceof HTMLElement)) return; - const menuItem = target.closest("#menu li, #menu section") as - | HTMLElement - | null; + const menuItem = target.closest("#menu li, #menu section") as HTMLElement | null; if (!menuItem) return; if (event.key === "Tab") { @@ -602,9 +585,7 @@ function handleSidebarKeyboardActivation(event: KeyboardEvent) { event.preventDefault(); - const childSubmenu = menuItem.querySelector(":scope > .sub > ul") as - | HTMLElement - | null; + const childSubmenu = menuItem.querySelector(":scope > .sub > ul") as HTMLElement | null; menuItem.click(); scheduleSidebarAccessibilityUpdate(); @@ -615,10 +596,7 @@ function handleSidebarKeyboardActivation(event: KeyboardEvent) { } /** Folder rows on the path to the currently open sidebar list. */ -function getDrillFolderChain( - menu: HTMLElement, - visibleList: HTMLElement | null, -): Set { +function getDrillFolderChain(menu: HTMLElement, visibleList: HTMLElement | null): Set { const chain = new Set(); let list: HTMLElement | null = visibleList; @@ -636,10 +614,7 @@ function getDrillFolderChain( break; } chain.add(parentFolder); - list = - parentFolder.parentElement instanceof HTMLElement - ? parentFolder.parentElement - : null; + list = parentFolder.parentElement instanceof HTMLElement ? parentFolder.parentElement : null; } return chain; @@ -674,9 +649,7 @@ function updateSidebarAccessibility() { if (!menu) return; const visibleList = getVisibleSidebarList(menu); - const visibleEntries = new Set( - visibleList ? getDirectSidebarEntries(visibleList) : [], - ); + const visibleEntries = new Set(visibleList ? getDirectSidebarEntries(visibleList) : []); if (document.body?.classList.contains("icon-only-sidebar")) { const rootList = menu.querySelector(":scope > ul") as HTMLElement | null; if (rootList) getDirectSidebarEntries(rootList).forEach((entry) => visibleEntries.add(entry)); @@ -690,8 +663,7 @@ function updateSidebarAccessibility() { const label = entry.querySelector(":scope > label") as HTMLLabelElement | null; if (!label) continue; - const interactive = - visibleEntries.has(entry) || drillFolders.has(entry); + const interactive = visibleEntries.has(entry) || drillFolders.has(entry); if (!interactive) { // Keep rows in normal layout — offscreen position/opacity snaps cause a @@ -736,9 +708,7 @@ function getVisibleSidebarList(menu: HTMLElement) { return currentList; } - const nextList = activeSubmenuParent.querySelector( - ":scope > .sub > ul", - ) as HTMLElement | null; + const nextList = activeSubmenuParent.querySelector(":scope > .sub > ul") as HTMLElement | null; if (!nextList) { return currentList; @@ -769,9 +739,7 @@ function focusFirstSidebarSubmenuEntry(parentEntry: HTMLElement) { } const firstEntry = getDirectSidebarEntries(visibleList).find( - (entry) => - entry.offsetParent !== null && - window.getComputedStyle(entry).display !== "none", + (entry) => entry.offsetParent !== null && window.getComputedStyle(entry).display !== "none", ); firstEntry?.focus({ preventScroll: true }); diff --git a/src/seqta/ui/ImageBackgrounds.ts b/src/seqta/ui/ImageBackgrounds.ts index 7cbb51d1..790711b7 100644 --- a/src/seqta/ui/ImageBackgrounds.ts +++ b/src/seqta/ui/ImageBackgrounds.ts @@ -1,7 +1,4 @@ -import { - getDataById, - isIndexedDBSupported, -} from "@/interface/hooks/BackgroundDataLoader"; +import { getDataById, isIndexedDBSupported } from "@/interface/hooks/BackgroundDataLoader"; export async function appendBackgroundToUI() { const parent = document.getElementById("container"); @@ -84,9 +81,7 @@ export async function loadBackground() { } const mediaElement = - background.type === "video" - ? document.createElement("video") - : document.createElement("img"); + background.type === "video" ? document.createElement("video") : document.createElement("img"); const blobUrl = URL.createObjectURL(background.blob); lastBlobUrl = blobUrl; diff --git a/src/seqta/ui/Loading.ts b/src/seqta/ui/Loading.ts index 76c2a5ef..c40f7c7a 100644 --- a/src/seqta/ui/Loading.ts +++ b/src/seqta/ui/Loading.ts @@ -4,11 +4,7 @@ import { settingsState } from "@/seqta/utils/listeners/SettingsState"; import loadingSpinner from "./loading-spinner.html?raw"; import loadingOverlay from "./loading-overlay.html?raw"; import { startLoadingCanvas } from "./loadingCanvas"; -import { - pickLoadingVariant, - resolveLoadingTheme, - type LoadingVariant, -} from "./loadingVariants"; +import { pickLoadingVariant, resolveLoadingTheme, type LoadingVariant } from "./loadingVariants"; import { isPerformanceMode } from "@/seqta/utils/performanceMode"; let stopCanvas: (() => void) | null = null; @@ -208,7 +204,7 @@ const loadingStyles = /* css */ ` function overlayWithSpinner(): string { return loadingOverlay.replace( - "

", + '
', `
${loadingSpinner}
`, ); } @@ -230,11 +226,7 @@ function applyHostShell(host: HTMLElement) { } } -function applyVariantTheme( - host: HTMLElement, - shadow: ShadowRoot, - variant: LoadingVariant, -) { +function applyVariantTheme(host: HTMLElement, shadow: ShadowRoot, variant: LoadingVariant) { const darkMode = !!settingsState.DarkMode; const theme = resolveLoadingTheme(variant, darkMode); host.dataset.variant = variant.id; @@ -276,11 +268,7 @@ function bindLoadingThemeGuard() { }; } -function startCanvasForRoot( - host: HTMLElement, - shadow: ShadowRoot, - variant: LoadingVariant, -) { +function startCanvasForRoot(host: HTMLElement, shadow: ShadowRoot, variant: LoadingVariant) { stopCanvas?.(); const canvas = shadow.querySelector(".bkloading__canvas") as HTMLCanvasElement | null; stopCanvas = canvas ? startLoadingCanvas(canvas, host, variant) : null; diff --git a/src/seqta/ui/SettingsResizer.ts b/src/seqta/ui/SettingsResizer.ts index e6e6415f..9250bef7 100644 --- a/src/seqta/ui/SettingsResizer.ts +++ b/src/seqta/ui/SettingsResizer.ts @@ -6,10 +6,7 @@ import debounce from "@/seqta/utils/debounce"; export class SettingsResizer { constructor() { this.adjustPopupHeight(); - window.addEventListener( - "resize", - debounce(this.adjustPopupHeight, 250) as EventListener, - ); + window.addEventListener("resize", debounce(this.adjustPopupHeight, 250) as EventListener); document.addEventListener("DOMContentLoaded", this.adjustPopupHeight); } diff --git a/src/seqta/ui/colors/ColorLuminance.ts b/src/seqta/ui/colors/ColorLuminance.ts index 422a3024..4cc7d240 100644 --- a/src/seqta/ui/colors/ColorLuminance.ts +++ b/src/seqta/ui/colors/ColorLuminance.ts @@ -33,10 +33,7 @@ export default function ColorLuminance(color: any, lum = 0) { // Adjust luminance for each unique color stop for (let colorStop of uniqueColorSet) { const adjustedColor = adjustLuminance(colorStop, lum); - gradient = gradient.replace( - new RegExp(colorStop as string, "gi"), - adjustedColor, - ); + gradient = gradient.replace(new RegExp(colorStop as string, "gi"), adjustedColor); } return gradient; diff --git a/src/seqta/ui/colors/Manager.ts b/src/seqta/ui/colors/Manager.ts index 1c7cb170..e178f749 100644 --- a/src/seqta/ui/colors/Manager.ts +++ b/src/seqta/ui/colors/Manager.ts @@ -59,11 +59,7 @@ function parseRepresentativeHex(s: string): string | null { const rgbaMatch = trimmed.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/i); if (rgbaMatch) { try { - return Color.rgb( - Number(rgbaMatch[1]), - Number(rgbaMatch[2]), - Number(rgbaMatch[3]), - ).hex(); + return Color.rgb(Number(rgbaMatch[1]), Number(rgbaMatch[2]), Number(rgbaMatch[3])).hex(); } catch { // continue } @@ -161,10 +157,7 @@ function applyColorsWith(selectedColor: string) { const isBright = rgbThreshold > 210; const dynamicProps = { "--text-color": isBright ? "black" : "white", - "--better-light": - selectedColor === "#ffffff" - ? "#b7b7b7" - : ColorLuminance(selectedColor, 0.95), + "--better-light": selectedColor === "#ffffff" ? "#b7b7b7" : ColorLuminance(selectedColor, 0.95), }; applyProperties({ ...commonProps, ...modeProps, ...dynamicProps }); @@ -227,10 +220,7 @@ function toSoftGradient(hex: string): string { } export async function updateAllColors() { - let effectiveColor = - settingsState.selectedColor !== "" - ? settingsState.selectedColor - : "#007bff"; + let effectiveColor = settingsState.selectedColor !== "" ? settingsState.selectedColor : "#007bff"; let adaptiveHex: string | null = null; @@ -244,15 +234,11 @@ export async function updateAllColors() { } } - const baseSelected = - settingsState.selectedColor !== "" ? settingsState.selectedColor : "#007bff"; - const toHex = - adaptiveHex ?? parseRepresentativeHex(baseSelected); + const baseSelected = settingsState.selectedColor !== "" ? settingsState.selectedColor : "#007bff"; + const toHex = adaptiveHex ?? parseRepresentativeHex(baseSelected); const shouldAnimate = - settingsState.adaptiveThemeColour && - adaptiveThemeTransitionEnabled() && - !!toHex; + settingsState.adaptiveThemeColour && adaptiveThemeTransitionEnabled() && !!toHex; const applyImmediate = () => { cancelColorTransition(); @@ -272,8 +258,7 @@ export async function updateAllColors() { return; } - const useSoftGradientOnFrames = - !!adaptiveHex && !!settingsState.adaptiveThemeGradient; + const useSoftGradientOnFrames = !!adaptiveHex && !!settingsState.adaptiveThemeGradient; cancelColorTransition(); @@ -284,9 +269,7 @@ export async function updateAllColors() { const t = Math.min(1, elapsed / ADAPTIVE_THEME_TRANSITION_MS); const eased = easeInOutCubic(t); const interpolatedHex = Color(fromHex).mix(Color(toHex), eased).hex(); - const display = useSoftGradientOnFrames - ? toSoftGradient(interpolatedHex) - : interpolatedHex; + const display = useSoftGradientOnFrames ? toSoftGradient(interpolatedHex) : interpolatedHex; applyColorsWith(display); if (t < 1) { diff --git a/src/seqta/ui/colors/customThemeAdaptiveBindings.ts b/src/seqta/ui/colors/customThemeAdaptiveBindings.ts index cdd0c823..c7444faf 100644 --- a/src/seqta/ui/colors/customThemeAdaptiveBindings.ts +++ b/src/seqta/ui/colors/customThemeAdaptiveBindings.ts @@ -12,9 +12,7 @@ export type AdaptiveCssVariableBinding = { let boundBindings: AdaptiveCssVariableBinding[] = []; -function parseAdaptiveBinding( - rawBinding: string, -): AdaptiveCssVariableBinding | null { +function parseAdaptiveBinding(rawBinding: string): AdaptiveCssVariableBinding | null { const trimmed = rawBinding.trim(); if (!trimmed) return null; @@ -48,9 +46,7 @@ export function normalizeAdaptiveCssVariableBindings( return out; } -export function setCustomThemeAdaptiveCssVariables( - names: string[] | undefined, -): void { +export function setCustomThemeAdaptiveCssVariables(names: string[] | undefined): void { for (const binding of boundBindings) { document.documentElement.style.removeProperty(binding.cssVarName); } diff --git a/src/seqta/ui/colors/getThresholdColour.ts b/src/seqta/ui/colors/getThresholdColour.ts index 7f7b4c7e..da3601e0 100644 --- a/src/seqta/ui/colors/getThresholdColour.ts +++ b/src/seqta/ui/colors/getThresholdColour.ts @@ -16,16 +16,13 @@ export function GetThresholdOfColor(color: any) { const [r, g, b] = rgbaString.split(",").map((str) => str.trim()); // Compute the threshold using your existing algorithm - const threshold = Math.sqrt( - parseInt(r) ** 2 + parseInt(g) ** 2 + parseInt(b) ** 2, - ); + const threshold = Math.sqrt(parseInt(r) ** 2 + parseInt(g) ** 2 + parseInt(b) ** 2); gradientThresholds.push(threshold); } const averageThreshold = - gradientThresholds.reduce((acc, val) => acc + val, 0) / - gradientThresholds.length; + gradientThresholds.reduce((acc, val) => acc + val, 0) / gradientThresholds.length; return averageThreshold; } else { diff --git a/src/seqta/ui/colors/lightenAndPaleColor.ts b/src/seqta/ui/colors/lightenAndPaleColor.ts index 23da7584..2c899b9a 100644 --- a/src/seqta/ui/colors/lightenAndPaleColor.ts +++ b/src/seqta/ui/colors/lightenAndPaleColor.ts @@ -1,10 +1,6 @@ import Color from "color"; -export function lightenAndPaleColor( - inputColor: any, - lightenFactor = 0.75, - paleFactor = 0.55, -) { +export function lightenAndPaleColor(inputColor: any, lightenFactor = 0.75, paleFactor = 0.55) { if (!inputColor) return; if (inputColor.includes("gradient")) { @@ -41,11 +37,7 @@ function averageColors(colors: any) { avgG += color.green(); avgB += color.blue(); }); - return Color.rgb( - avgR / colors.length, - avgG / colors.length, - avgB / colors.length, - ); + return Color.rgb(avgR / colors.length, avgG / colors.length, avgB / colors.length); } // Main function to find a matching color for a CSS gradient function findMatchingColor(cssGradient: any) { @@ -56,9 +48,7 @@ function findMatchingColor(cssGradient: any) { const colorStops = cssGradient.match(regex); if (!colorStops) { - throw new Error( - "No valid color stops found in the provided CSS gradient.", - ); + throw new Error("No valid color stops found in the provided CSS gradient."); } // Normalize and trim the color stops diff --git a/src/seqta/ui/colors/parseCssColor.test.ts b/src/seqta/ui/colors/parseCssColor.test.ts index ae0dbc0b..eecedee8 100644 --- a/src/seqta/ui/colors/parseCssColor.test.ts +++ b/src/seqta/ui/colors/parseCssColor.test.ts @@ -1,30 +1,20 @@ -import { - extractSolidColor, - normalizeCssColorString, - parseCssColor, -} from "./parseCssColor"; +import { extractSolidColor, normalizeCssColorString, parseCssColor } from "./parseCssColor"; describe("normalizeCssColorString", () => { it("lowercases uppercase RGBA/RGB function names", () => { - expect(normalizeCssColorString("RGBA(3, 29, 11, 0.58)")).toBe( - "rgba(3, 29, 11, 0.58)", - ); + expect(normalizeCssColorString("RGBA(3, 29, 11, 0.58)")).toBe("rgba(3, 29, 11, 0.58)"); expect(normalizeCssColorString("RGB(10, 20, 30)")).toBe("rgb(10, 20, 30)"); }); }); describe("extractSolidColor", () => { it("extracts solid uppercase RGBA values", () => { - expect(extractSolidColor("RGBA(3, 29, 11, 0.58)")).toBe( - "rgba(3, 29, 11, 0.58)", - ); + expect(extractSolidColor("RGBA(3, 29, 11, 0.58)")).toBe("rgba(3, 29, 11, 0.58)"); }); it("extracts the first rgba stop from gradients with mixed casing", () => { expect( - extractSolidColor( - "linear-gradient(40deg, rgba(201,61,0,1) 0%, RGBA(170, 5, 58, 1) 100%)", - ), + extractSolidColor("linear-gradient(40deg, rgba(201,61,0,1) 0%, RGBA(170, 5, 58, 1) 100%)"), ).toBe("rgba(201,61,0,1)"); }); }); @@ -39,8 +29,6 @@ describe("parseCssColor", () => { }); it("falls back when the value is not a colour", () => { - expect(parseCssColor("not-a-color", "#007bff").hex().toLowerCase()).toBe( - "#007bff", - ); + expect(parseCssColor("not-a-color", "#007bff").hex().toLowerCase()).toBe("#007bff"); }); }); diff --git a/src/seqta/ui/colors/parseCssColor.ts b/src/seqta/ui/colors/parseCssColor.ts index d2835f94..c3077833 100644 --- a/src/seqta/ui/colors/parseCssColor.ts +++ b/src/seqta/ui/colors/parseCssColor.ts @@ -17,17 +17,11 @@ export function normalizeCssColorString(value: string): string { export function extractSolidColor(value: string): string | null { const trimmed = normalizeCssColorString(value); if (!trimmed || trimmed === "initial") return null; - if ( - trimmed.startsWith("#") || - /^rgba?\(/i.test(trimmed) || - /^hsla?\(/i.test(trimmed) - ) { + if (trimmed.startsWith("#") || /^rgba?\(/i.test(trimmed) || /^hsla?\(/i.test(trimmed)) { return trimmed; } if (trimmed.includes("gradient")) { - const match = trimmed.match( - /#[0-9A-Fa-f]{6}|#[0-9A-Fa-f]{3}|rgba?\([^)]+\)/gi, - ); + const match = trimmed.match(/#[0-9A-Fa-f]{6}|#[0-9A-Fa-f]{3}|rgba?\([^)]+\)/gi); return match?.[0] ? normalizeCssColorString(match[0]) : null; } return null; @@ -35,10 +29,9 @@ export function extractSolidColor(value: string): string | null { /** Parse a CSS colour for the `color` library; never throws. */ export function parseCssColor(value: string, fallback = "#007bff"): ColorInstance { - const candidates = [ - extractSolidColor(value), - normalizeCssColorString(value), - ].filter((candidate): candidate is string => Boolean(candidate)); + const candidates = [extractSolidColor(value), normalizeCssColorString(value)].filter( + (candidate): candidate is string => Boolean(candidate), + ); for (const candidate of candidates) { try { diff --git a/src/seqta/ui/dev/hideSensitiveContent.ts b/src/seqta/ui/dev/hideSensitiveContent.ts index 3fb2ebe7..82c9f9d9 100644 --- a/src/seqta/ui/dev/hideSensitiveContent.ts +++ b/src/seqta/ui/dev/hideSensitiveContent.ts @@ -45,9 +45,7 @@ function generateMockUserCode(): string { function getRandomDate(): Date { const start = new Date(); const end = new Date(start.getTime() + 60 * 24 * 60 * 60 * 1000); // 60 days from now - return new Date( - start.getTime() + Math.random() * (end.getTime() - start.getTime()), - ); + return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime())); } const contentConfig: ContentConfig = { @@ -155,8 +153,7 @@ const contentConfig: ContentConfig = { }, messageRecipients: { - selector: - '[class*="MessageList__recipients___"] [class*="MessageList__value___"]', + selector: '[class*="MessageList__recipients___"] [class*="MessageList__value___"]', action: (element) => { element.textContent = getRandomElement(mockData.messages.recipients); }, @@ -177,9 +174,7 @@ const contentConfig: ContentConfig = { action: (element) => { if (element instanceof HTMLElement) { element.style.removeProperty("background-image"); - element.firstChild!.firstChild!.textContent = getRandomElement( - mockData.names, - )[0]; + element.firstChild!.firstChild!.textContent = getRandomElement(mockData.names)[0]; } }, }, @@ -508,7 +503,7 @@ const mockData = { noticesData: [ { id: 1, - title: "Academic Lunch Support", + title: "Academic Lunch Support", contents: `The following table shows the names of the students who are required to attend at the beginning of lunchtime on the respective days.
  @@ -554,7 +549,7 @@ const mockData = { staff: "Mrs Jones", colour: "#9c27b0", label: 1, - label_title: "Middle & Senior School (5-12)" + label_title: "Middle & Senior School (5-12)", }, { id: 2, @@ -570,7 +565,7 @@ Students are expected to bring all necessary materials and maintain academic foc staff: "Mr. David Chen", colour: "#2196f3", label: 2, - label_title: "Year 12 Students" + label_title: "Year 12 Students", }, { id: 3, @@ -606,7 +601,7 @@ Students are expected to bring all necessary materials and maintain academic foc staff: "Dr. Sarah Mitchell", colour: "#4caf50", label: 3, - label_title: "Science Students" + label_title: "Science Students", }, { id: 4, @@ -626,7 +621,7 @@ For assistance with any digital resources, please contact the library staff duri staff: "Ms. Rebecca Torres", colour: "#ff9800", label: 4, - label_title: "All Students" + label_title: "All Students", }, { id: 5, @@ -665,26 +660,85 @@ Register through the PE department or see your house captains for more informati staff: "Coach Michael Park", colour: "#e91e63", label: 5, - label_title: "All Houses" - } - ] + label_title: "All Houses", + }, + ], }; /** Mock day schedule for home timetable: care 8:30–8:55, then 7 lessons 8:55–3:15 (45m each), 20m recess, lunch. */ function getMockDaySchedule(): string { const blocks: { title: string; teacher: string; room: string; from: string; until: string }[] = [ - { title: "Care Group", teacher: getRandomElement(mockData.teachers), room: getRandomElement(mockData.classrooms), from: "8:30am", until: "8:55am" }, - { title: getRandomElement(mockData.subjects), teacher: getRandomElement(mockData.teachers), room: getRandomElement(mockData.classrooms), from: "8:55am", until: "9:40am" }, - { title: getRandomElement(mockData.subjects), teacher: getRandomElement(mockData.teachers), room: getRandomElement(mockData.classrooms), from: "9:40am", until: "10:25am" }, + { + title: "Care Group", + teacher: getRandomElement(mockData.teachers), + room: getRandomElement(mockData.classrooms), + from: "8:30am", + until: "8:55am", + }, + { + title: getRandomElement(mockData.subjects), + teacher: getRandomElement(mockData.teachers), + room: getRandomElement(mockData.classrooms), + from: "8:55am", + until: "9:40am", + }, + { + title: getRandomElement(mockData.subjects), + teacher: getRandomElement(mockData.teachers), + room: getRandomElement(mockData.classrooms), + from: "9:40am", + until: "10:25am", + }, { title: "Recess", teacher: "—", room: "—", from: "10:25am", until: "10:45am" }, - { title: getRandomElement(mockData.subjects), teacher: getRandomElement(mockData.teachers), room: getRandomElement(mockData.classrooms), from: "10:45am", until: "11:30am" }, - { title: getRandomElement(mockData.subjects), teacher: getRandomElement(mockData.teachers), room: getRandomElement(mockData.classrooms), from: "11:30am", until: "12:15pm" }, + { + title: getRandomElement(mockData.subjects), + teacher: getRandomElement(mockData.teachers), + room: getRandomElement(mockData.classrooms), + from: "10:45am", + until: "11:30am", + }, + { + title: getRandomElement(mockData.subjects), + teacher: getRandomElement(mockData.teachers), + room: getRandomElement(mockData.classrooms), + from: "11:30am", + until: "12:15pm", + }, { title: "Lunch", teacher: "—", room: "—", from: "12:15pm", until: "1:00pm" }, - { title: getRandomElement(mockData.subjects), teacher: getRandomElement(mockData.teachers), room: getRandomElement(mockData.classrooms), from: "1:00pm", until: "1:45pm" }, - { title: getRandomElement(mockData.subjects), teacher: getRandomElement(mockData.teachers), room: getRandomElement(mockData.classrooms), from: "1:45pm", until: "2:30pm" }, - { title: getRandomElement(mockData.subjects), teacher: getRandomElement(mockData.teachers), room: getRandomElement(mockData.classrooms), from: "2:30pm", until: "3:15pm" }, + { + title: getRandomElement(mockData.subjects), + teacher: getRandomElement(mockData.teachers), + room: getRandomElement(mockData.classrooms), + from: "1:00pm", + until: "1:45pm", + }, + { + title: getRandomElement(mockData.subjects), + teacher: getRandomElement(mockData.teachers), + room: getRandomElement(mockData.classrooms), + from: "1:45pm", + until: "2:30pm", + }, + { + title: getRandomElement(mockData.subjects), + teacher: getRandomElement(mockData.teachers), + room: getRandomElement(mockData.classrooms), + from: "2:30pm", + until: "3:15pm", + }, + ]; + const colours = [ + "#8e8e8e", + "#4FBBFE", + "#59F675", + "#fa915d", + "#9c27b0", + "#2196f3", + "#4caf50", + "#ff9800", + "#e91e63", + "#673ab7", ]; - const colours = ["#8e8e8e", "#4FBBFE", "#59F675", "#fa915d", "#9c27b0", "#2196f3", "#4caf50", "#ff9800", "#e91e63", "#673ab7"]; return blocks .map( (b, i) => @@ -701,7 +755,7 @@ function getMockDaySchedule(): string { export function getMockNotices() { return { - payload: mockData.noticesData + payload: mockData.noticesData, }; } @@ -713,18 +767,16 @@ export function getMockGradeAnalyticsData() { return pct != null; }) .map( - ( - a: { - id: number; - title: string; - code: string; - due: string; - percentage?: number; - results?: { percentage?: number }; - programmeID: number; - metaclassID: number; - }, - ) => { + (a: { + id: number; + title: string; + code: string; + due: string; + percentage?: number; + results?: { percentage?: number }; + programmeID: number; + metaclassID: number; + }) => { const finalGrade = a.percentage ?? a.results?.percentage ?? 0; return { id: a.id, @@ -744,8 +796,7 @@ export function getMockGradeAnalyticsData() { reflectionsCompleted: false, availability: "", finalGrade, - letterGrade: - finalGrade >= 85 ? "A" : finalGrade >= 70 ? "B" : "C", + letterGrade: finalGrade >= 85 ? "A" : finalGrade >= 70 ? "B" : "C", }; }, ); @@ -766,25 +817,37 @@ export function getMockAssessmentsData() { const statusTemplates = [ // Marked with scores (70-90%) - goes to MARKS_RELEASED - { submitted: true, score: () => Math.floor(Math.random() * 21) + 70, dayOffset: () => Math.floor(Math.random() * -30) - 7 }, // Past due, marked with score - { submitted: true, score: () => Math.floor(Math.random() * 21) + 70, dayOffset: () => Math.floor(Math.random() * -14) - 1 }, // Recently marked with score - { submitted: true, score: () => Math.floor(Math.random() * 21) + 70, dayOffset: () => Math.floor(Math.random() * -7) }, // Very recently marked with score - + { + submitted: true, + score: () => Math.floor(Math.random() * 21) + 70, + dayOffset: () => Math.floor(Math.random() * -30) - 7, + }, // Past due, marked with score + { + submitted: true, + score: () => Math.floor(Math.random() * 21) + 70, + dayOffset: () => Math.floor(Math.random() * -14) - 1, + }, // Recently marked with score + { + submitted: true, + score: () => Math.floor(Math.random() * 21) + 70, + dayOffset: () => Math.floor(Math.random() * -7), + }, // Very recently marked with score + // Submitted but unmarked - goes to SUBMITTED { submitted: true, score: null, dayOffset: () => Math.floor(Math.random() * -5) - 1 }, // Recently submitted, awaiting marking { submitted: true, score: null, dayOffset: () => Math.floor(Math.random() * -3) }, // Very recently submitted, awaiting marking { submitted: true, score: null, dayOffset: () => Math.floor(Math.random() * -2) }, // Just submitted, awaiting marking - + // Due soon (not submitted) - only a couple { submitted: false, score: null, dayOffset: () => 0 }, // Due today { submitted: false, score: null, dayOffset: () => Math.floor(Math.random() * 3) + 2 }, // Due in next few days - + // Due later (not submitted) - most assessments { submitted: false, score: null, dayOffset: () => Math.floor(Math.random() * 7) + 8 }, // Due in 1-2 weeks { submitted: false, score: null, dayOffset: () => Math.floor(Math.random() * 14) + 14 }, // Due in 2-4 weeks { submitted: false, score: null, dayOffset: () => Math.floor(Math.random() * 21) + 21 }, // Due in 3-6 weeks { submitted: false, score: null, dayOffset: () => Math.floor(Math.random() * 14) + 35 }, // Due in 5-7 weeks - + // Few overdue (not submitted) - less common { submitted: false, score: null, dayOffset: () => Math.floor(Math.random() * -3) - 1 }, // Recently overdue ]; @@ -796,7 +859,7 @@ export function getMockAssessmentsData() { const due = new Date(); due.setDate(due.getDate() + template.dayOffset()); if (i >= 10) due.setFullYear(currentYear - 1); - + const types = ["Assignment", "Test", "Exam", "Project", "Presentation", "Report"]; const assessment: any = { id: i + 1, @@ -809,10 +872,10 @@ export function getMockAssessmentsData() { type: types[i % types.length], }; - if (template.score && typeof template.score === 'function') { + if (template.score && typeof template.score === "function") { assessment.percentage = template.score(); // This triggers MARKS_RELEASED assessment.results = { - percentage: template.score() // This displays the thermometer + percentage: template.score(), // This displays the thermometer }; } @@ -852,17 +915,20 @@ export default function hideSensitiveContent() { if (suppressMockMutations) return; let shouldProcess = false; - + mutations.forEach((mutation) => { // Check for both childList and subtree changes - if (mutation.type === 'childList') { + if (mutation.type === "childList") { if (mutation.addedNodes.length > 0) { mutation.addedNodes.forEach((node) => { if (node.nodeType === Node.ELEMENT_NODE) { const element = node as Element; // Check if the added element or its children match any of our selectors for (const config of Object.values(contentConfig)) { - if (element.matches?.(config.selector) || element.querySelector?.(config.selector)) { + if ( + element.matches?.(config.selector) || + element.querySelector?.(config.selector) + ) { shouldProcess = true; break; } @@ -870,7 +936,7 @@ export default function hideSensitiveContent() { } }); } - + // Large DOM replacements (e.g. page navigation). Skip only when #day-container gains many *mock* rows (our inject). if (mutation.addedNodes.length > 5 || mutation.removedNodes.length > 5) { const target = mutation.target as Element; @@ -878,10 +944,7 @@ export default function hideSensitiveContent() { for (const node of mutation.addedNodes) { if (node.nodeType === Node.ELEMENT_NODE) { const el = node as Element; - if ( - el.classList?.contains("day") && - !el.hasAttribute(MOCK_DAY_ATTR) - ) { + if (el.classList?.contains("day") && !el.hasAttribute(MOCK_DAY_ATTR)) { shouldProcess = true; break; } @@ -892,9 +955,9 @@ export default function hideSensitiveContent() { } } } - + // Check for attribute changes that might affect our selectors - if (mutation.type === 'attributes') { + if (mutation.type === "attributes") { const target = mutation.target as Element; for (const config of Object.values(contentConfig)) { if (target.matches?.(config.selector)) { @@ -915,7 +978,7 @@ export default function hideSensitiveContent() { childList: true, subtree: true, attributes: true, - attributeFilter: ['class', 'id'] // Watch for class/id changes that might affect our selectors + attributeFilter: ["class", "id"], // Watch for class/id changes that might affect our selectors }); } } diff --git a/src/seqta/ui/fonts/Manager.ts b/src/seqta/ui/fonts/Manager.ts index 48e17520..edd89f48 100644 --- a/src/seqta/ui/fonts/Manager.ts +++ b/src/seqta/ui/fonts/Manager.ts @@ -11,8 +11,7 @@ export const FONT_PICKER_ROOT_CLASS = "bsplus-font-picker-root"; function googleFamilyParam(preset: FontPreset): string | null { if (!preset.googleUrl) return null; - const name = - preset.stack.split(",")[0]?.trim().replace(/^"|"$/g, "") ?? ""; + const name = preset.stack.split(",")[0]?.trim().replace(/^"|"$/g, "") ?? ""; if (!name) return null; return `family=${encodeURIComponent(name)}:wght@400;500;600;700`; } diff --git a/src/seqta/ui/fonts/presets.ts b/src/seqta/ui/fonts/presets.ts index e03b68d1..2b06cc86 100644 --- a/src/seqta/ui/fonts/presets.ts +++ b/src/seqta/ui/fonts/presets.ts @@ -13,32 +13,28 @@ export const FONT_PRESETS: FontPreset[] = [ id: "rubik", name: "Rubik", stack: "Rubik, sans-serif", - googleUrl: - "https://fonts.googleapis.com/css2?family=Rubik:wght@400;500;600;700&display=swap", + googleUrl: "https://fonts.googleapis.com/css2?family=Rubik:wght@400;500;600;700&display=swap", sample: "Assessment due tomorrow at 3:30pm", }, { id: "inter", name: "Inter", stack: "Inter, sans-serif", - googleUrl: - "https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap", + googleUrl: "https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap", sample: "Assessment due tomorrow at 3:30pm", }, { id: "poppins", name: "Poppins", stack: "Poppins, sans-serif", - googleUrl: - "https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&display=swap", + googleUrl: "https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&display=swap", sample: "Assessment due tomorrow at 3:30pm", }, { id: "nunito", name: "Nunito", stack: "Nunito, sans-serif", - googleUrl: - "https://fonts.googleapis.com/css2?family=Nunito:wght@400;500;600;700&display=swap", + googleUrl: "https://fonts.googleapis.com/css2?family=Nunito:wght@400;500;600;700&display=swap", sample: "Assessment due tomorrow at 3:30pm", }, { @@ -61,8 +57,7 @@ export const FONT_PRESETS: FontPreset[] = [ id: "lato", name: "Lato", stack: "Lato, sans-serif", - googleUrl: - "https://fonts.googleapis.com/css2?family=Lato:wght@400;700&display=swap", + googleUrl: "https://fonts.googleapis.com/css2?family=Lato:wght@400;700&display=swap", sample: "Assessment due tomorrow at 3:30pm", }, { @@ -77,16 +72,14 @@ export const FONT_PRESETS: FontPreset[] = [ id: "raleway", name: "Raleway", stack: "Raleway, sans-serif", - googleUrl: - "https://fonts.googleapis.com/css2?family=Raleway:wght@400;500;600;700&display=swap", + googleUrl: "https://fonts.googleapis.com/css2?family=Raleway:wght@400;500;600;700&display=swap", sample: "Assessment due tomorrow at 3:30pm", }, { id: "dm-sans", name: "DM Sans", stack: '"DM Sans", sans-serif', - googleUrl: - "https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&display=swap", + googleUrl: "https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&display=swap", sample: "Assessment due tomorrow at 3:30pm", }, { @@ -101,16 +94,14 @@ export const FONT_PRESETS: FontPreset[] = [ id: "outfit", name: "Outfit", stack: "Outfit, sans-serif", - googleUrl: - "https://fonts.googleapis.com/css2?family=Outfit:wght@400;500;600;700&display=swap", + googleUrl: "https://fonts.googleapis.com/css2?family=Outfit:wght@400;500;600;700&display=swap", sample: "Assessment due tomorrow at 3:30pm", }, { id: "roboto", name: "Roboto", stack: "Roboto, sans-serif", - googleUrl: - "https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&display=swap", + googleUrl: "https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&display=swap", sample: "Assessment due tomorrow at 3:30pm", }, { @@ -125,40 +116,35 @@ export const FONT_PRESETS: FontPreset[] = [ id: "manrope", name: "Manrope", stack: "Manrope, sans-serif", - googleUrl: - "https://fonts.googleapis.com/css2?family=Manrope:wght@400;500;600;700&display=swap", + googleUrl: "https://fonts.googleapis.com/css2?family=Manrope:wght@400;500;600;700&display=swap", sample: "Assessment due tomorrow at 3:30pm", }, { id: "figtree", name: "Figtree", stack: "Figtree, sans-serif", - googleUrl: - "https://fonts.googleapis.com/css2?family=Figtree:wght@400;500;600;700&display=swap", + googleUrl: "https://fonts.googleapis.com/css2?family=Figtree:wght@400;500;600;700&display=swap", sample: "Assessment due tomorrow at 3:30pm", }, { id: "lexend", name: "Lexend", stack: "Lexend, sans-serif", - googleUrl: - "https://fonts.googleapis.com/css2?family=Lexend:wght@400;500;600;700&display=swap", + googleUrl: "https://fonts.googleapis.com/css2?family=Lexend:wght@400;500;600;700&display=swap", sample: "Assessment due tomorrow at 3:30pm", }, { id: "ubuntu", name: "Ubuntu", stack: "Ubuntu, sans-serif", - googleUrl: - "https://fonts.googleapis.com/css2?family=Ubuntu:wght@400;500;700&display=swap", + googleUrl: "https://fonts.googleapis.com/css2?family=Ubuntu:wght@400;500;700&display=swap", sample: "Assessment due tomorrow at 3:30pm", }, { id: "karla", name: "Karla", stack: "Karla, sans-serif", - googleUrl: - "https://fonts.googleapis.com/css2?family=Karla:wght@400;500;600;700&display=swap", + googleUrl: "https://fonts.googleapis.com/css2?family=Karla:wght@400;500;600;700&display=swap", sample: "Assessment due tomorrow at 3:30pm", }, { @@ -189,32 +175,28 @@ export const FONT_PRESETS: FontPreset[] = [ id: "mulish", name: "Mulish", stack: "Mulish, sans-serif", - googleUrl: - "https://fonts.googleapis.com/css2?family=Mulish:wght@400;500;600;700&display=swap", + googleUrl: "https://fonts.googleapis.com/css2?family=Mulish:wght@400;500;600;700&display=swap", sample: "Assessment due tomorrow at 3:30pm", }, { id: "cabin", name: "Cabin", stack: "Cabin, sans-serif", - googleUrl: - "https://fonts.googleapis.com/css2?family=Cabin:wght@400;500;600;700&display=swap", + googleUrl: "https://fonts.googleapis.com/css2?family=Cabin:wght@400;500;600;700&display=swap", sample: "Assessment due tomorrow at 3:30pm", }, { id: "oswald", name: "Oswald", stack: "Oswald, sans-serif", - googleUrl: - "https://fonts.googleapis.com/css2?family=Oswald:wght@400;500;600;700&display=swap", + googleUrl: "https://fonts.googleapis.com/css2?family=Oswald:wght@400;500;600;700&display=swap", sample: "Assessment due tomorrow at 3:30pm", }, { id: "merriweather", name: "Merriweather", stack: "Merriweather, serif", - googleUrl: - "https://fonts.googleapis.com/css2?family=Merriweather:wght@400;700&display=swap", + googleUrl: "https://fonts.googleapis.com/css2?family=Merriweather:wght@400;700&display=swap", sample: "Assessment due tomorrow at 3:30pm", }, { @@ -229,8 +211,7 @@ export const FONT_PRESETS: FontPreset[] = [ id: "lora", name: "Lora", stack: "Lora, serif", - googleUrl: - "https://fonts.googleapis.com/css2?family=Lora:wght@400;500;600;700&display=swap", + googleUrl: "https://fonts.googleapis.com/css2?family=Lora:wght@400;500;600;700&display=swap", sample: "Assessment due tomorrow at 3:30pm", }, { diff --git a/src/seqta/ui/founderBadge/mountTitlebarFounderBadge.ts b/src/seqta/ui/founderBadge/mountTitlebarFounderBadge.ts index b397dbbc..3d78ede3 100644 --- a/src/seqta/ui/founderBadge/mountTitlebarFounderBadge.ts +++ b/src/seqta/ui/founderBadge/mountTitlebarFounderBadge.ts @@ -23,7 +23,10 @@ function stopBadgeCarousel(slot: HTMLElement): void { carouselTimers.delete(slot); } -function createBadgeButton(badge: BadgeItem, signupNumber?: number | null): HTMLButtonElement | null { +function createBadgeButton( + badge: BadgeItem, + signupNumber?: number | null, +): HTMLButtonElement | null { const visual = badgeVisualForKey(badge.key, badge.label); if (!visual) return null; const button = document.createElement("button"); diff --git a/src/seqta/ui/founderBadge/openFounderBadgeModal.ts b/src/seqta/ui/founderBadge/openFounderBadgeModal.ts index 472037b5..750203f0 100644 --- a/src/seqta/ui/founderBadge/openFounderBadgeModal.ts +++ b/src/seqta/ui/founderBadge/openFounderBadgeModal.ts @@ -18,10 +18,7 @@ function esc(value: string): string { .replace(/"/g, """); } -export function openFounderBadgeModal( - badge: BadgeItem, - signupNumber?: number | null, -): void { +export function openFounderBadgeModal(badge: BadgeItem, signupNumber?: number | null): void { const visual = badgeVisualForKey(badge.key, badge.label); if (!visual) return; diff --git a/src/seqta/ui/loading-spinner.html b/src/seqta/ui/loading-spinner.html index 1fa413cb..cde34fca 100644 --- a/src/seqta/ui/loading-spinner.html +++ b/src/seqta/ui/loading-spinner.html @@ -1,4 +1,31 @@ - - - - + + + + + + + + + + diff --git a/src/seqta/ui/loadingCanvas.ts b/src/seqta/ui/loadingCanvas.ts index 8aa80741..85bad590 100644 --- a/src/seqta/ui/loadingCanvas.ts +++ b/src/seqta/ui/loadingCanvas.ts @@ -16,19 +16,106 @@ type SoftBlob = { }; const DIFFUSE: SoftBlob[] = [ - { cx: 0.26, cy: 1.14, rx: 0.4, ry: 0.34, rgb: "37, 99, 235", phase: 0, speed: 1, amp: 0.26, rot: 0.38 }, - { cx: 0.58, cy: 1.2, rx: 0.44, ry: 0.38, rgb: "59, 130, 246", phase: 2.2, speed: 0.82, amp: 0.3, rot: -0.32 }, - { cx: 0.46, cy: 1.1, rx: 0.36, ry: 0.28, rgb: "29, 78, 216", phase: 4.4, speed: 1.12, amp: 0.22, rot: 0.45 }, - { cx: 0.8, cy: 1.08, rx: 0.3, ry: 0.3, rgb: "96, 165, 250", phase: 1.5, speed: 0.74, amp: 0.24, rot: -0.4 }, - { cx: 0.12, cy: 1.12, rx: 0.32, ry: 0.32, rgb: "37, 99, 235", phase: 3.6, speed: 0.96, amp: 0.25, rot: 0.34 }, - { cx: 0.68, cy: 1.06, rx: 0.26, ry: 0.24, rgb: "14, 116, 244", phase: 5.1, speed: 0.88, amp: 0.18, rot: -0.28 }, + { + cx: 0.26, + cy: 1.14, + rx: 0.4, + ry: 0.34, + rgb: "37, 99, 235", + phase: 0, + speed: 1, + amp: 0.26, + rot: 0.38, + }, + { + cx: 0.58, + cy: 1.2, + rx: 0.44, + ry: 0.38, + rgb: "59, 130, 246", + phase: 2.2, + speed: 0.82, + amp: 0.3, + rot: -0.32, + }, + { + cx: 0.46, + cy: 1.1, + rx: 0.36, + ry: 0.28, + rgb: "29, 78, 216", + phase: 4.4, + speed: 1.12, + amp: 0.22, + rot: 0.45, + }, + { + cx: 0.8, + cy: 1.08, + rx: 0.3, + ry: 0.3, + rgb: "96, 165, 250", + phase: 1.5, + speed: 0.74, + amp: 0.24, + rot: -0.4, + }, + { + cx: 0.12, + cy: 1.12, + rx: 0.32, + ry: 0.32, + rgb: "37, 99, 235", + phase: 3.6, + speed: 0.96, + amp: 0.25, + rot: 0.34, + }, + { + cx: 0.68, + cy: 1.06, + rx: 0.26, + ry: 0.24, + rgb: "14, 116, 244", + phase: 5.1, + speed: 0.88, + amp: 0.18, + rot: -0.28, + }, ]; const TIDE: SoftBlob[] = [ { cx: 0.5, cy: 0.68, rx: 0.72, ry: 0.11, rgb: "37, 99, 235", phase: 0, speed: 0.42, drift: 0.08 }, - { cx: 0.32, cy: 0.8, rx: 0.58, ry: 0.09, rgb: "59, 130, 246", phase: 2.4, speed: 0.36, drift: 0.06 }, - { cx: 0.68, cy: 0.86, rx: 0.64, ry: 0.12, rgb: "29, 78, 216", phase: 4.6, speed: 0.4, drift: 0.07 }, - { cx: 0.5, cy: 0.96, rx: 0.78, ry: 0.1, rgb: "96, 165, 250", phase: 1.1, speed: 0.33, drift: 0.05 }, + { + cx: 0.32, + cy: 0.8, + rx: 0.58, + ry: 0.09, + rgb: "59, 130, 246", + phase: 2.4, + speed: 0.36, + drift: 0.06, + }, + { + cx: 0.68, + cy: 0.86, + rx: 0.64, + ry: 0.12, + rgb: "29, 78, 216", + phase: 4.6, + speed: 0.4, + drift: 0.07, + }, + { + cx: 0.5, + cy: 0.96, + rx: 0.78, + ry: 0.1, + rgb: "96, 165, 250", + phase: 1.1, + speed: 0.33, + drift: 0.05, + }, ]; const GLOBE_STAGGER_MS = 720; diff --git a/src/seqta/ui/loadingVariants.test.ts b/src/seqta/ui/loadingVariants.test.ts index 56de3876..be8de91c 100644 --- a/src/seqta/ui/loadingVariants.test.ts +++ b/src/seqta/ui/loadingVariants.test.ts @@ -1,7 +1,4 @@ -import { - listLoadingVariants, - resolveLoadingTheme, -} from "./loadingVariants"; +import { listLoadingVariants, resolveLoadingTheme } from "./loadingVariants"; describe("resolveLoadingTheme", () => { it("keeps the dark background in dark mode and swaps it for light mode", () => { diff --git a/src/seqta/ui/loadingVariants.ts b/src/seqta/ui/loadingVariants.ts index 8f28950b..5ebd7ca7 100644 --- a/src/seqta/ui/loadingVariants.ts +++ b/src/seqta/ui/loadingVariants.ts @@ -3,12 +3,7 @@ export type Line = { dur: number; dashed?: boolean; blue?: boolean; - stroke: ( - ctx: CanvasRenderingContext2D, - p: number, - w: number, - h: number, - ) => void; + stroke: (ctx: CanvasRenderingContext2D, p: number, w: number, h: number) => void; }; export type LoadingVariant = { @@ -60,8 +55,7 @@ const segment = (x1: number, y1: number, x2: number, y2: number): Line["stroke"] }; const BASE = "linear-gradient(180deg, #010101 0%, #040404 50%, #080808 100%)"; -const BASE_LIGHT = - "linear-gradient(180deg, #fafafa 0%, #f4f4f5 50%, #ececef 100%)"; +const BASE_LIGHT = "linear-gradient(180deg, #fafafa 0%, #f4f4f5 50%, #ececef 100%)"; const STAGE = "bkloading-stage-in"; function theme( diff --git a/src/seqta/ui/renderStore.ts b/src/seqta/ui/renderStore.ts index 09d6f04f..1741dd70 100644 --- a/src/seqta/ui/renderStore.ts +++ b/src/seqta/ui/renderStore.ts @@ -1,11 +1,8 @@ -async function openThemesDestination( - view: "store" | "community", -): Promise { - const [{ requestSettingsDestination }, { openSettingsPopup }] = - await Promise.all([ - import("@/seqta/utils/settingsNavigation"), - import("@/seqta/utils/setupSettingsButton"), - ]); +async function openThemesDestination(view: "store" | "community"): Promise { + const [{ requestSettingsDestination }, { openSettingsPopup }] = await Promise.all([ + import("@/seqta/utils/settingsNavigation"), + import("@/seqta/utils/setupSettingsButton"), + ]); requestSettingsDestination({ page: "themes", view }); await openSettingsPopup(); } diff --git a/src/seqta/ui/sidebar/applyNativeSidebar.ts b/src/seqta/ui/sidebar/applyNativeSidebar.ts index 32c59e2f..a05127ac 100644 --- a/src/seqta/ui/sidebar/applyNativeSidebar.ts +++ b/src/seqta/ui/sidebar/applyNativeSidebar.ts @@ -2,11 +2,7 @@ import type { SettingsState } from "@/types/storage"; import { settingsState } from "@/seqta/utils/listeners/SettingsState"; import { isSeqtaEngageExperience, isSeqtaLoginPage } from "@/seqta/utils/isSeqtaEngage"; import { waitForElm } from "@/seqta/utils/waitForElm"; -import { - applySidebarLook, - applySidebarStyleClass, - clearSidebarAppearance, -} from "./sidebarStyles"; +import { applySidebarLook, applySidebarStyleClass, clearSidebarAppearance } from "./sidebarStyles"; const MENU_CLASS = "bsplus-styled-sidebar"; @@ -48,9 +44,7 @@ function attachSettingsListeners() { settingsListenersAttached = true; clearSettingListeners(); - registerSetting("sidebarStyle", () => - applySidebarStyleClass(menuEl, settingsState.sidebarStyle), - ); + registerSetting("sidebarStyle", () => applySidebarStyleClass(menuEl, settingsState.sidebarStyle)); for (const key of [ "sidebarDensity", "sidebarCornerRadius", diff --git a/src/seqta/ui/sidebar/parseNativeMenu.ts b/src/seqta/ui/sidebar/parseNativeMenu.ts index 6bbae392..11a13179 100644 --- a/src/seqta/ui/sidebar/parseNativeMenu.ts +++ b/src/seqta/ui/sidebar/parseNativeMenu.ts @@ -44,25 +44,15 @@ function inferPath( return null; } -function parseEntry( - entry: HTMLElement, - parentPath: string | null = null, -): SidebarItem | null { +function parseEntry(entry: HTMLElement, parentPath: string | null = null): SidebarItem | null { if (!entry.matches("li.item, section.item, li, section")) return null; const label = entry.querySelector(":scope > label") as HTMLElement | null; const labelText = readLabelText(label); - let key = - entry.dataset.key ?? - entry.id ?? - labelText.toLowerCase().replace(/\s+/g, "-") ?? - ""; + let key = entry.dataset.key ?? entry.id ?? labelText.toLowerCase().replace(/\s+/g, "-") ?? ""; // Stable key for BS+ Overview injection (no data-key on the native node). - if ( - !entry.dataset.key && - entry.classList.contains("betterseqta-assessments-overview-item") - ) { + if (!entry.dataset.key && entry.classList.contains("betterseqta-assessments-overview-item")) { key = "assessments-overview"; } @@ -70,9 +60,7 @@ function parseEntry( const path = inferPath(entry.dataset.path, key || labelText, parentPath); - const childList = entry.querySelector( - ":scope > .sub > ul", - ) as HTMLElement | null; + const childList = entry.querySelector(":scope > .sub > ul") as HTMLElement | null; const children = childList ? [...childList.children] .filter((node): node is HTMLElement => node instanceof HTMLElement) @@ -98,9 +86,7 @@ export function folderNeedsNativePopulate(item: SidebarItem): boolean { if (item.key !== "assessments" && item.key !== "courses") return false; return !item.children.some( (child) => - !child.betterseqta && - child.key !== "upcoming" && - child.key !== "assessments-overview", + !child.betterseqta && child.key !== "upcoming" && child.key !== "assessments-overview", ); } @@ -123,9 +109,7 @@ export function findNativeMenuEntry( if (!list) return null; if (item.key === "assessments-overview") { - const overview = list.querySelector( - ".betterseqta-assessments-overview-item", - ); + const overview = list.querySelector(".betterseqta-assessments-overview-item"); if (overview instanceof HTMLElement) return overview; } @@ -162,24 +146,17 @@ export function findNativeMenuEntry( } } - const leaf = matches.find( - (node) => !node.classList.contains("hasChildren"), - ); + const leaf = matches.find((node) => !node.classList.contains("hasChildren")); if (leaf) return leaf; return matches[0]; } } if (item.label) { - const candidates = list.querySelectorAll( - "li.item, section.item", - ); + const candidates = list.querySelectorAll("li.item, section.item"); for (const candidate of candidates) { const label = candidate.querySelector(":scope > label"); - if ( - label instanceof HTMLElement && - readLabelText(label) === item.label - ) { + if (label instanceof HTMLElement && readLabelText(label) === item.label) { return candidate; } } diff --git a/src/seqta/ui/sidebar/sidebarDrillReturn.ts b/src/seqta/ui/sidebar/sidebarDrillReturn.ts index 71dcaced..0266a9d2 100644 --- a/src/seqta/ui/sidebar/sidebarDrillReturn.ts +++ b/src/seqta/ui/sidebar/sidebarDrillReturn.ts @@ -19,19 +19,14 @@ export function getSidebarDrillDepth( if (!activeFolder) break; depth += 1; - list = activeFolder.querySelector( - ":scope > .sub > ul", - ) as HTMLElement | null; + list = activeFolder.querySelector(":scope > .sub > ul") as HTMLElement | null; } return depth; } /** List that becomes visible after drilling back to `targetDepth`. */ -function getSidebarListAtDepth( - menu: HTMLElement, - targetDepth: number, -): HTMLElement | null { +function getSidebarListAtDepth(menu: HTMLElement, targetDepth: number): HTMLElement | null { if (targetDepth <= 0) { return menu.querySelector(":scope > ul") as HTMLElement | null; } @@ -44,9 +39,7 @@ function getSidebarListAtDepth( ":scope > li.hasChildren.active, :scope > section.hasChildren.active", ) as HTMLElement | null; if (!activeFolder) return list; - list = activeFolder.querySelector( - ":scope > .sub > ul", - ) as HTMLElement | null; + list = activeFolder.querySelector(":scope > .sub > ul") as HTMLElement | null; depth += 1; } @@ -54,17 +47,12 @@ function getSidebarListAtDepth( } function getReturnSlideNodes(list: HTMLElement): HTMLElement[] { - return [ - ...list.querySelectorAll(":scope > li, :scope > section"), - ]; + return [...list.querySelectorAll(":scope > li, :scope > section")]; } function prepareRowSlide(list: HTMLElement) { // The icons-only root rail remains visible next to the open panel. - if ( - document.body?.classList.contains("icon-only-sidebar") && - list.parentElement?.id === "menu" - ) + if (document.body?.classList.contains("icon-only-sidebar") && list.parentElement?.id === "menu") return; if (list.classList.contains(ROWS_CLASS)) return; const nodes = getReturnSlideNodes(list); @@ -96,9 +84,7 @@ let lastRootFolder: Element | null = null; let swapFrame: number | null = null; function rootFolder(menu: HTMLElement) { - return menu.querySelector( - ":scope > ul > .hasChildren:is(.active, .bsplus-active)", - ); + return menu.querySelector(":scope > ul > .hasChildren:is(.active, .bsplus-active)"); } function swapRootPanel(menu: HTMLElement) { @@ -151,8 +137,7 @@ export function runSidebarDrillReturn( function onDrillDepthChange(menu: HTMLElement) { const currentRoot = rootFolder(menu); - if (lastRootFolder && currentRoot && lastRootFolder !== currentRoot) - swapRootPanel(menu); + if (lastRootFolder && currentRoot && lastRootFolder !== currentRoot) swapRootPanel(menu); lastRootFolder = currentRoot; if (menu.classList.contains(MENU_RETURN_CLASS)) return; @@ -176,11 +161,7 @@ function onMenuClickCapture(event: MouseEvent) { if (!(target instanceof Element)) return; if (!target.closest(".sub .back")) { const folder = target.closest("li.hasChildren, section.hasChildren"); - if ( - folder && - !folder.classList.contains("active") && - folder.parentElement - ) { + if (folder && !folder.classList.contains("active") && folder.parentElement) { if ( folder.parentElement.parentElement === menu && rootFolder(menu) && @@ -244,9 +225,7 @@ export function uninstallSidebarDrillReturn() { menu.classList.remove("bsplus-icon-rail-switching"); clearReturnClasses(menu); clearRowSlide( - menu.querySelectorAll( - `ul.${ROWS_CLASS} > li, ul.${ROWS_CLASS} > section`, - ), + menu.querySelectorAll(`ul.${ROWS_CLASS} > li, ul.${ROWS_CLASS} > section`), ); if (backCaptureAttached) { menu.removeEventListener("click", onMenuClickCapture, true); diff --git a/src/seqta/ui/sidebar/sidebarStyles.test.ts b/src/seqta/ui/sidebar/sidebarStyles.test.ts index d386c230..a77143de 100644 --- a/src/seqta/ui/sidebar/sidebarStyles.test.ts +++ b/src/seqta/ui/sidebar/sidebarStyles.test.ts @@ -25,18 +25,21 @@ test("early sidebar preparation and cleanup work before body exists", () => { } }); -test.each([false, true])("applies unchanged settings to a newly available menu (replacement: %s)", (replacement) => { - const initialMenu = replacement ? document.createElement("div") : null; - applySidebarLook(initialMenu); - const menu = document.createElement("div"); - menu.id = "menu"; - document.body.append(menu); +test.each([false, true])( + "applies unchanged settings to a newly available menu (replacement: %s)", + (replacement) => { + const initialMenu = replacement ? document.createElement("div") : null; + applySidebarLook(initialMenu); + const menu = document.createElement("div"); + menu.id = "menu"; + document.body.append(menu); - applySidebarLook(menu); + applySidebarLook(menu); - expect(menu.classList.contains("bsplus-sidebar-density-compact")).toBe(true); - expect(menu.classList.contains("bsplus-sidebar-indicator-outline")).toBe(true); -}); + expect(menu.classList.contains("bsplus-sidebar-density-compact")).toBe(true); + expect(menu.classList.contains("bsplus-sidebar-indicator-outline")).toBe(true); + }, +); test("restores sidebar variables and classes after disable and re-enable", () => { const menu = document.createElement("div"); diff --git a/src/seqta/ui/sidebar/sidebarStyles.ts b/src/seqta/ui/sidebar/sidebarStyles.ts index 56c6d0da..91a2a8e3 100644 --- a/src/seqta/ui/sidebar/sidebarStyles.ts +++ b/src/seqta/ui/sidebar/sidebarStyles.ts @@ -1,14 +1,7 @@ import { settingsState } from "@/seqta/utils/listeners/SettingsState"; import { isPerformanceMode } from "@/seqta/utils/performanceMode"; -export type SidebarStyleId = - | "classic" - | "soft" - | "pill" - | "glass" - | "sharp" - | "strip" - | "neon"; +export type SidebarStyleId = "classic" | "soft" | "pill" | "glass" | "sharp" | "strip" | "neon"; export type SidebarDensity = "compact" | "comfortable" | "large"; export type SidebarActiveIndicator = "fill" | "bar" | "outline" | "underline"; @@ -64,18 +57,13 @@ function clampInt(value: unknown, min: number, max: number, fallback: number): n return Math.min(max, Math.max(min, Math.round(n))); } -export const normalizeSidebarStyleId = (v: unknown) => - oneOf(v, STYLE_IDS, DEFAULT_SIDEBAR_STYLE); +export const normalizeSidebarStyleId = (v: unknown) => oneOf(v, STYLE_IDS, DEFAULT_SIDEBAR_STYLE); export const normalizeSidebarDensity = (v: unknown) => oneOf(v, ["compact", "comfortable", "large"] as const, DEFAULT_SIDEBAR_DENSITY); export const normalizeSidebarIndicator = (v: unknown) => - oneOf( - v, - ["fill", "bar", "outline", "underline"] as const, - DEFAULT_SIDEBAR_INDICATOR, - ); + oneOf(v, ["fill", "bar", "outline", "underline"] as const, DEFAULT_SIDEBAR_INDICATOR); export const normalizeSidebarWidth = (v: unknown) => oneOf(v, ["narrow", "default", "wide"] as const, DEFAULT_SIDEBAR_WIDTH); @@ -83,11 +71,9 @@ export const normalizeSidebarWidth = (v: unknown) => export const normalizeSidebarPosition = (v: unknown) => oneOf(v, ["left", "right"] as const, DEFAULT_SIDEBAR_POSITION); -export const normalizeSidebarRadius = (v: unknown) => - clampInt(v, 0, 24, DEFAULT_SIDEBAR_RADIUS); +export const normalizeSidebarRadius = (v: unknown) => clampInt(v, 0, 24, DEFAULT_SIDEBAR_RADIUS); -export const normalizeSidebarBlur = (v: unknown) => - clampInt(v, 0, 80, DEFAULT_SIDEBAR_BLUR); +export const normalizeSidebarBlur = (v: unknown) => clampInt(v, 0, 80, DEFAULT_SIDEBAR_BLUR); export function getSidebarStyle(id: unknown): SidebarStyleDef { const normalized = normalizeSidebarStyleId(id); @@ -95,26 +81,18 @@ export function getSidebarStyle(id: unknown): SidebarStyleDef { } function clearPrefixed(el: HTMLElement, prefix: string) { - for (const cls of [...el.classList]) { + for (const cls of Array.from(el.classList)) { if (cls.startsWith(prefix)) el.classList.remove(cls); } } -function setExclusiveClass( - el: HTMLElement, - prefix: string, - value: string, - skipDefault?: string, -) { +function setExclusiveClass(el: HTMLElement, prefix: string, value: string, skipDefault?: string) { clearPrefixed(el, prefix); if (value !== skipDefault) el.classList.add(`${prefix}${value}`); } /** Apply style preset class on `#menu` (classic = no class). */ -export function applySidebarStyleClass( - menu: HTMLElement | null | undefined, - styleId: unknown, -) { +export function applySidebarStyleClass(menu: HTMLElement | null | undefined, styleId: unknown) { if (!menu) return; setExclusiveClass( menu, @@ -168,9 +146,7 @@ export function applySidebarLook( const indicator = normalizeSidebarIndicator(settingsState.sidebarActiveIndicator); const width = normalizeSidebarWidth(settingsState.sidebarWidth); const radius = normalizeSidebarRadius(settingsState.sidebarCornerRadius); - const blur = isPerformanceMode() - ? 0 - : normalizeSidebarBlur(settingsState.sidebarBlur); + const blur = isPerformanceMode() ? 0 : normalizeSidebarBlur(settingsState.sidebarBlur); applySidebarPosition(); @@ -187,12 +163,7 @@ export function applySidebarLook( lastSidebarLookMenu = menu; setExclusiveClass(menu, DENSITY_CLASS_PREFIX, density, DEFAULT_SIDEBAR_DENSITY); - setExclusiveClass( - menu, - INDICATOR_CLASS_PREFIX, - indicator, - DEFAULT_SIDEBAR_INDICATOR, - ); + setExclusiveClass(menu, INDICATOR_CLASS_PREFIX, indicator, DEFAULT_SIDEBAR_INDICATOR); } export function clearSidebarAppearance(menu: HTMLElement | null | undefined) { diff --git a/src/seqta/ui/titlebar/mountCustomTitleBar.ts b/src/seqta/ui/titlebar/mountCustomTitleBar.ts index 8b06b11b..900c3bf0 100644 --- a/src/seqta/ui/titlebar/mountCustomTitleBar.ts +++ b/src/seqta/ui/titlebar/mountCustomTitleBar.ts @@ -35,9 +35,7 @@ function syncPageTitle() { function needsSearchChip() { if (!isPluginAllowedInPerformanceMode("global-search")) return false; const all = settingsState.getAll() as unknown as Record; - const plugin = all["plugin.global-search.settings"] as - | { enabled?: boolean } - | undefined; + const plugin = all["plugin.global-search.settings"] as { enabled?: boolean } | undefined; return plugin?.enabled === true || titleBarState.showSearch; } @@ -75,12 +73,15 @@ function observeHost(host: HTMLElement) { hostObserver = new MutationObserver((mutations) => { if (!document.getElementById(ROOT_ID)) { if (remountTimer) clearTimeout(remountTimer); - remountTimer = setTimeout(() => { - remountTimer = null; - if (!settingsState.onoff || isSeqtaEngageExperience()) return; - app = null; - void mountCustomTitleBar(); - }, isPerformanceMode() ? 120 : 50); + remountTimer = setTimeout( + () => { + remountTimer = null; + if (!settingsState.onoff || isSeqtaEngageExperience()) return; + app = null; + void mountCustomTitleBar(); + }, + isPerformanceMode() ? 120 : 50, + ); return; } const titleChanged = mutations.some( @@ -104,7 +105,12 @@ function observeHost(host: HTMLElement) { } export function prepareCustomTitleBarEarly() { - if (isSeqtaEngageExperience() || isSeqtaLoginPage() || !settingsState.onoff || earlyPrepareStarted) { + if ( + isSeqtaEngageExperience() || + isSeqtaLoginPage() || + !settingsState.onoff || + earlyPrepareStarted + ) { return; } earlyPrepareStarted = true; diff --git a/src/seqta/utils/CloudAuth.ts b/src/seqta/utils/CloudAuth.ts index 3b8554d2..2e97eb19 100644 --- a/src/seqta/utils/CloudAuth.ts +++ b/src/seqta/utils/CloudAuth.ts @@ -81,10 +81,7 @@ class CloudAuthService { } private async loadFromStorage(): Promise { - const result = await browser.storage.local.get([ - STORAGE_KEYS.accessToken, - STORAGE_KEYS.user, - ]); + const result = await browser.storage.local.get([STORAGE_KEYS.accessToken, STORAGE_KEYS.user]); const token = result[STORAGE_KEYS.accessToken] as string | undefined; const user = result[STORAGE_KEYS.user] as CloudUser | undefined; this._state = { @@ -172,7 +169,7 @@ class CloudAuthService { public async login( login: string, - password: string + password: string, ): Promise<{ success: boolean; error?: string }> { try { const clientId = await this.getClientId(); diff --git a/src/seqta/utils/DevApiBase.ts b/src/seqta/utils/DevApiBase.ts index c214a7a0..f91f6775 100644 --- a/src/seqta/utils/DevApiBase.ts +++ b/src/seqta/utils/DevApiBase.ts @@ -43,9 +43,7 @@ export function setApiBase(url: string | null): void { } catch { // ignore } - void browser.runtime - .sendMessage({ type: "setDevApiBase", url: null }) - .catch(() => {}); + void browser.runtime.sendMessage({ type: "setDevApiBase", url: null }).catch(() => {}); return; } @@ -58,9 +56,7 @@ export function setApiBase(url: string | null): void { } catch { // ignore } - void browser.runtime - .sendMessage({ type: "setDevApiBase", url: url || null }) - .catch(() => {}); + void browser.runtime.sendMessage({ type: "setDevApiBase", url: url || null }).catch(() => {}); } /** Returns the override URL if one is currently active (production builds only). */ @@ -76,7 +72,5 @@ export function getStoredOverride(): string | null { */ export function syncApiBaseToBackground(): void { const override = import.meta.env.DEV ? null : readSessionOverride(); - void browser.runtime - .sendMessage({ type: "setDevApiBase", url: override }) - .catch(() => {}); + void browser.runtime.sendMessage({ type: "setDevApiBase", url: override }).catch(() => {}); } diff --git a/src/seqta/utils/FilterUpcomingAssessments.ts b/src/seqta/utils/FilterUpcomingAssessments.ts index 3a1f83f1..ad275865 100644 --- a/src/seqta/utils/FilterUpcomingAssessments.ts +++ b/src/seqta/utils/FilterUpcomingAssessments.ts @@ -28,14 +28,8 @@ export function FilterUpcomingAssessments(subjectoptions: any) { element.parentNode!.querySelectorAll(".hidden").length ) { if (element.parentNode!.querySelectorAll(".hidden").length > 0) { - if ( - !(element.parentNode!.parentNode! as HTMLElement).hasAttribute( - "data-day", - ) - ) { - (element.parentNode!.parentNode! as HTMLElement).classList.add( - "hidden", - ); + if (!(element.parentNode!.parentNode! as HTMLElement).hasAttribute("data-day")) { + (element.parentNode!.parentNode! as HTMLElement).classList.add("hidden"); } else { AddPlaceHolderToParent( element.parentNode!.parentNode, @@ -44,9 +38,7 @@ export function FilterUpcomingAssessments(subjectoptions: any) { } } } else { - (element.parentNode!.parentNode! as HTMLElement).classList.remove( - "hidden", - ); + (element.parentNode!.parentNode! as HTMLElement).classList.remove("hidden"); } } } diff --git a/src/seqta/utils/ReactFiber.ts b/src/seqta/utils/ReactFiber.ts index 33211fd5..c3864dad 100644 --- a/src/seqta/utils/ReactFiber.ts +++ b/src/seqta/utils/ReactFiber.ts @@ -27,9 +27,7 @@ class ReactFiber { } private isTrustedMessage(event: MessageEvent): boolean { - return ( - event.source === window && event.origin === this.getTargetOrigin() - ); + return event.source === window && event.origin === this.getTargetOrigin(); } private async sendMessage(action: string, payload: any = {}): Promise { @@ -70,9 +68,7 @@ class ReactFiber { async setState(update: Record): Promise { if (typeof update !== "object" || update === null || Array.isArray(update)) { - throw new TypeError( - "ReactFiber.setState only accepts plain JSON-serializable objects", - ); + throw new TypeError("ReactFiber.setState only accepts plain JSON-serializable objects"); } await this.sendMessage("setState", { updateObject: update }); diff --git a/src/seqta/utils/SendNewsPage.ts b/src/seqta/utils/SendNewsPage.ts index 9f86742b..98a1c414 100644 --- a/src/seqta/utils/SendNewsPage.ts +++ b/src/seqta/utils/SendNewsPage.ts @@ -33,15 +33,18 @@ export async function SendNewsPage() { const displayCountry = (() => { switch (settingsState.newsSource?.toLowerCase()) { - case "usa": return "the USA"; - case "uk": return "the UK"; - case "netherlands": return "the Netherlands"; + case "usa": + return "the USA"; + case "uk": + return "the UK"; + case "netherlands": + return "the Netherlands"; default: return settingsState.newsSource ? settingsState.newsSource - .split("_") - .map(word => word.charAt(0).toUpperCase() + word.slice(1)) - .join(" ") + .split("_") + .map((word) => word.charAt(0).toUpperCase() + word.slice(1)) + .join(" ") : "Australia"; } })(); @@ -117,9 +120,7 @@ export async function SendNewsPage() { const description = document.createElement("p"); const articleDescription = article.description || "No description available."; description.textContent = - articleDescription.length > 400 - ? `${articleDescription.slice(0, 400)}…` - : articleDescription; + articleDescription.length > 400 ? `${articleDescription.slice(0, 400)}…` : articleDescription; articletext.append(title, description); newsarticle.append(articleimage, articletext); diff --git a/src/seqta/utils/adaptiveThemeColour.ts b/src/seqta/utils/adaptiveThemeColour.ts index d0aa62d7..bc25c605 100644 --- a/src/seqta/utils/adaptiveThemeColour.ts +++ b/src/seqta/utils/adaptiveThemeColour.ts @@ -23,10 +23,7 @@ function parsePageContext(): { programme: number; metaclass: number } | null { /** * Fetches subjects and finds the subject matching programme:metaclass. */ -async function getSubjectCode( - programme: number, - metaclass: number -): Promise { +async function getSubjectCode(programme: number, metaclass: number): Promise { try { const res = await fetch(`${location.origin}/seqta/student/load/subjects?`, { method: "POST", @@ -42,10 +39,7 @@ async function getSubjectCode( const subjects = semester?.subjects; if (!Array.isArray(subjects)) continue; const subject = subjects.find( - (s: any) => - s && - Number(s.programme) === programme && - Number(s.metaclass) === metaclass + (s: any) => s && Number(s.programme) === programme && Number(s.metaclass) === metaclass, ); if (subject?.code) return subject.code; } @@ -59,10 +53,7 @@ async function getSubjectCode( /** * Fetches user prefs and returns the colour for the given subject code. */ -async function getSubjectColour( - subjectCode: string, - userId: number -): Promise { +async function getSubjectColour(subjectCode: string, userId: number): Promise { try { const res = await fetch(`${location.origin}/seqta/student/load/prefs?`, { method: "POST", @@ -79,8 +70,7 @@ async function getSubjectColour( if (!Array.isArray(payload)) return null; const pref = payload.find( - (p: { name: string; value: string }) => - p.name === `timetable.subject.colour.${subjectCode}` + (p: { name: string; value: string }) => p.name === `timetable.subject.colour.${subjectCode}`, ); return pref?.value ?? null; } catch (error) { diff --git a/src/seqta/utils/adders/AddShortcuts.ts b/src/seqta/utils/adders/AddShortcuts.ts index f3ae4146..86acce64 100644 --- a/src/seqta/utils/adders/AddShortcuts.ts +++ b/src/seqta/utils/adders/AddShortcuts.ts @@ -8,8 +8,7 @@ export function addShortcuts(shortcuts: any) { if (currentShortcut?.enabled) { const Itemname = (currentShortcut?.name ?? "").replace(/\s/g, ""); - const linkDetails = - ShortcutLinks?.[Itemname as keyof typeof ShortcutLinks]; + const linkDetails = ShortcutLinks?.[Itemname as keyof typeof ShortcutLinks]; if (linkDetails) { createNewShortcut( linkDetails.link, diff --git a/src/seqta/utils/allowedFetchUrl.ts b/src/seqta/utils/allowedFetchUrl.ts index f66d7684..333bbd3d 100644 --- a/src/seqta/utils/allowedFetchUrl.ts +++ b/src/seqta/utils/allowedFetchUrl.ts @@ -45,9 +45,7 @@ function isPrivateOrLocalHost(hostname: string): boolean { function isAllowedHost(hostname: string): boolean { const host = hostname.toLowerCase(); - return ALLOWED_HOST_SUFFIXES.some( - (suffix) => host === suffix || host.endsWith(`.${suffix}`), - ); + return ALLOWED_HOST_SUFFIXES.some((suffix) => host === suffix || host.endsWith(`.${suffix}`)); } /** HTTPS-only fetch allowlist for background `fetchFromUrl`. */ diff --git a/src/seqta/utils/bsplusDeviceName.ts b/src/seqta/utils/bsplusDeviceName.ts index 88690f3f..556583da 100644 --- a/src/seqta/utils/bsplusDeviceName.ts +++ b/src/seqta/utils/bsplusDeviceName.ts @@ -64,7 +64,6 @@ async function detectBrowserName(): Promise { */ export async function getBsplusDeviceName(): Promise { const browserName = await detectBrowserName(); - const osName = - typeof navigator !== "undefined" ? detectOsNameFromNavigator() : "Unknown OS"; + const osName = typeof navigator !== "undefined" ? detectOsNameFromNavigator() : "Unknown OS"; return `${browserName} on ${osName}`; } diff --git a/src/seqta/utils/calendarSync/eventMap.ts b/src/seqta/utils/calendarSync/eventMap.ts index 369bed79..808c632f 100644 --- a/src/seqta/utils/calendarSync/eventMap.ts +++ b/src/seqta/utils/calendarSync/eventMap.ts @@ -34,9 +34,7 @@ export function getStoredFingerprint( return normalizeEventMapEntry(value)?.fingerprint; } -export function getStoredEventId( - value: string | EventMapEntry | undefined, -): string | undefined { +export function getStoredEventId(value: string | EventMapEntry | undefined): string | undefined { return normalizeEventMapEntry(value)?.id; } diff --git a/src/seqta/utils/calendarSync/lessonSyncShared.test.ts b/src/seqta/utils/calendarSync/lessonSyncShared.test.ts index 91e8e104..39518169 100644 --- a/src/seqta/utils/calendarSync/lessonSyncShared.test.ts +++ b/src/seqta/utils/calendarSync/lessonSyncShared.test.ts @@ -51,9 +51,7 @@ describe("eventFingerprint", () => { timeZone: "Australia/Adelaide", }; expect(eventFingerprint(base)).toBe(eventFingerprint({ ...base })); - expect(eventFingerprint(base)).not.toBe( - eventFingerprint({ ...base, summary: "English" }), - ); + expect(eventFingerprint(base)).not.toBe(eventFingerprint({ ...base, summary: "English" })); }); }); diff --git a/src/seqta/utils/calendarSync/lessonSyncShared.ts b/src/seqta/utils/calendarSync/lessonSyncShared.ts index 4686a9b3..b2a15d63 100644 --- a/src/seqta/utils/calendarSync/lessonSyncShared.ts +++ b/src/seqta/utils/calendarSync/lessonSyncShared.ts @@ -218,10 +218,7 @@ export function formatLessonSyncResultMessage( return `${calendarLabel} updated (${parts.join(", ")}).`; } -export function buildDeleteSyncResult( - deleted: number, - failed: number, -): GoogleCalendarDeleteResult { +export function buildDeleteSyncResult(deleted: number, failed: number): GoogleCalendarDeleteResult { return { success: failed === 0, configured: true, diff --git a/src/seqta/utils/calendarSync/remoteEvents.test.ts b/src/seqta/utils/calendarSync/remoteEvents.test.ts index 6ca7409d..05d757cd 100644 --- a/src/seqta/utils/calendarSync/remoteEvents.test.ts +++ b/src/seqta/utils/calendarSync/remoteEvents.test.ts @@ -1,8 +1,5 @@ import { afterEach, expect, it, jest } from "@jest/globals"; -import { - listGoogleSyncedEvents, - listOutlookSyncedEvents, -} from "./remoteEvents"; +import { listGoogleSyncedEvents, listOutlookSyncedEvents } from "./remoteEvents"; afterEach(() => { jest.restoreAllMocks(); @@ -16,18 +13,15 @@ it.each([ body: JSON.stringify({ error: { message: "Invalid response" } }), }, { provider: "outlook", body: "{}" }, -])( - "rejects malformed successful $provider listings ($body)", - async ({ provider, body }) => { - jest.spyOn(globalThis, "fetch").mockResolvedValue(new Response(body)); - const range = { from: "2026-10-04", until: "2026-10-04" }; - const listing = - provider === "google" - ? listGoogleSyncedEvents("token", "calendar", range) - : listOutlookSyncedEvents("token", range); - await expect(listing).rejects.toThrow(); - }, -); +])("rejects malformed successful $provider listings ($body)", async ({ provider, body }) => { + jest.spyOn(globalThis, "fetch").mockResolvedValue(new Response(body)); + const range = { from: "2026-10-04", until: "2026-10-04" }; + const listing = + provider === "google" + ? listGoogleSyncedEvents("token", "calendar", range) + : listOutlookSyncedEvents("token", range); + await expect(listing).rejects.toThrow(); +}); it.each(["google", "outlook"])( "queries %s over complete local days across Sydney DST", @@ -49,18 +43,14 @@ it.each(["google", "outlook"])( return Response.json(provider === "google" ? {} : { value: [] }); }); const range = { from: "2026-10-04", until: "2026-10-04" }; - if (provider === "google") - await listGoogleSyncedEvents("token", "calendar", range); + if (provider === "google") await listGoogleSyncedEvents("token", "calendar", range); else await listOutlookSyncedEvents("token", range); if (expected) expect(requestedBounds).toEqual(expected); else { const [start, end] = requestedBounds.map((value) => new Date(value)); - expect([ - start.getDate(), - start.getHours(), - end.getDate(), - end.getHours(), - ]).toEqual([4, 0, 5, 0]); + expect([start.getDate(), start.getHours(), end.getDate(), end.getHours()]).toEqual([ + 4, 0, 5, 0, + ]); } }, ); @@ -68,14 +58,9 @@ it.each(["google", "outlook"])( it("rejects an incomplete paginated listing rather than authorizing reconciliation", async () => { jest .spyOn(globalThis, "fetch") + .mockResolvedValueOnce(Response.json({ items: [], nextPageToken: "second-page" })) .mockResolvedValueOnce( - Response.json({ items: [], nextPageToken: "second-page" }), - ) - .mockResolvedValueOnce( - Response.json( - { error: { message: "Page unavailable" } }, - { status: 400 }, - ), + Response.json({ error: { message: "Page unavailable" } }, { status: 400 }), ); await expect( listGoogleSyncedEvents("token", "calendar", { diff --git a/src/seqta/utils/calendarSync/remoteEvents.ts b/src/seqta/utils/calendarSync/remoteEvents.ts index b85e3746..569e5781 100644 --- a/src/seqta/utils/calendarSync/remoteEvents.ts +++ b/src/seqta/utils/calendarSync/remoteEvents.ts @@ -86,7 +86,10 @@ async function upsertRemoteEvent( { method: "POST", headers, body: JSON.stringify(body) }, refreshAccessToken, ); - const json = (await res.json().catch(() => ({}))) as { id?: string; error?: { message?: string } }; + const json = (await res.json().catch(() => ({}))) as { + id?: string; + error?: { message?: string }; + }; if (!res.ok || !json.id) { throw new Error(json?.error?.message ?? `${label} create failed (${res.status})`); } @@ -210,7 +213,8 @@ function googleItemToRemote( if (!item.id) return null; const seqtaKey = item.extendedProperties?.private?.[BSPLUS_GOOGLE_CALENDAR_EVENT_PROP] ?? ""; if (!seqtaKey && !includeUnkeyed) return null; - const startDateTime = item.start?.dateTime ?? (item.start?.date ? `${item.start.date}T00:00:00` : ""); + const startDateTime = + item.start?.dateTime ?? (item.start?.date ? `${item.start.date}T00:00:00` : ""); const endDateTime = item.end?.dateTime ?? (item.end?.date ? `${item.end.date}T00:00:00` : ""); const timeZone = item.start?.timeZone ?? item.end?.timeZone ?? "UTC"; return { @@ -247,8 +251,7 @@ export async function listGoogleSyncedEvents( maxResults: "2500", timeMin: toRfc3339Start(range.from), timeMax: toRfc3339EndExclusive(range.until), - fields: - "nextPageToken,items(id,summary,location,description,start,end,extendedProperties)", + fields: "nextPageToken,items(id,summary,location,description,start,end,extendedProperties)", }); if (pageToken) params.set("pageToken", pageToken); @@ -350,8 +353,7 @@ export async function listOutlookSyncedEvents( $select: "id,subject,body,location,start,end,categories", }); - let nextUrl: string | undefined = - `${OUTLOOK_GRAPH_API}/me/calendarView?${params.toString()}`; + let nextUrl: string | undefined = `${OUTLOOK_GRAPH_API}/me/calendarView?${params.toString()}`; while (nextUrl) { const res = await authorizedFetch( diff --git a/src/seqta/utils/calendarSync/settings.ts b/src/seqta/utils/calendarSync/settings.ts index 1b737f68..5253621d 100644 --- a/src/seqta/utils/calendarSync/settings.ts +++ b/src/seqta/utils/calendarSync/settings.ts @@ -126,12 +126,7 @@ export async function readResumableCalendarSync(): Promise { accessToken = await getAccessToken(); @@ -214,11 +214,7 @@ export async function syncLessonsToCalendar( const remoteIds = new Set(remoteEvents.map((event) => event.id)); for (const key of currentMapKeys) { const entry = normalizeEventMapEntry(eventMap[key]); - if ( - entry?.date && - isDateInRange(entry.date, reconcileRange) && - !remoteIds.has(entry.id) - ) { + if (entry?.date && isDateInRange(entry.date, reconcileRange) && !remoteIds.has(entry.id)) { delete eventMap[key]; } } @@ -335,7 +331,12 @@ export async function deleteSyncedEventsFromCalendar( const state = await provider.readState(); if (!state.refreshToken && !state.accessToken) { - return { success: false, configured: true, connected: false, error: provider.notConnectedError }; + return { + success: false, + configured: true, + connected: false, + error: provider.notConnectedError, + }; } reportSyncProgress(options.onProgress, { @@ -345,7 +346,7 @@ export async function deleteSyncedEventsFromCalendar( message: "Preparing removal…", }); - const eventMap = { ...(state.eventMap ?? {}) }; + const eventMap = { ...state.eventMap }; let accessToken = await getAccessToken(); const refreshAccessToken = async () => { accessToken = await getAccessToken(); diff --git a/src/seqta/utils/cloudPfpSync.ts b/src/seqta/utils/cloudPfpSync.ts index 33f5e8b8..394035c3 100644 --- a/src/seqta/utils/cloudPfpSync.ts +++ b/src/seqta/utils/cloudPfpSync.ts @@ -94,7 +94,7 @@ async function bsplusPfpRequest( ...init, headers: { Authorization: `Bearer ${token}`, - ...(init?.headers ?? {}), + ...init?.headers, }, }); const data = await parseJson(res); @@ -146,9 +146,7 @@ function mergeMeIntoUser(current: CloudUser, data: Record): Clo const pfpUrlRaw = raw.pfpUrl as string | null | undefined; const pfpHash = (raw.pfpHash as string | null | undefined) ?? null; const pfpUrl = - pfpUrlRaw == null || pfpUrlRaw === "" - ? undefined - : pfpUrlWithHash(pfpUrlRaw, pfpHash); + pfpUrlRaw == null || pfpUrlRaw === "" ? undefined : pfpUrlWithHash(pfpUrlRaw, pfpHash); return { ...current, @@ -180,7 +178,10 @@ export async function refreshCloudUserFromServer(): Promise<{ success: boolean; }); const data = await parseJson(res); if (!res.ok) { - return { success: false, error: (data.error as string) ?? `Could not refresh account (${res.status})` }; + return { + success: false, + error: (data.error as string) ?? `Could not refresh account (${res.status})`, + }; } let merged = mergeMeIntoUser(current, data); @@ -197,7 +198,10 @@ export async function refreshCloudUserFromServer(): Promise<{ success: boolean; } } -export async function pullCloudProfilePictureFromServer(): Promise<{ success: boolean; error?: string }> { +export async function pullCloudProfilePictureFromServer(): Promise<{ + success: boolean; + error?: string; +}> { const current = cloudAuth.state.user; if (!cloudAuth.state.isLoggedIn || !current?.id) { return { success: false, error: "Not signed in to BetterSEQTA Cloud" }; @@ -221,7 +225,9 @@ export async function onUseCloudPfpToggled(enabled: boolean): Promise { else await pullCloudProfilePictureFromServer(); } -export async function uploadCloudProfilePicture(source: Blob): Promise<{ success: boolean; error?: string }> { +export async function uploadCloudProfilePicture( + source: Blob, +): Promise<{ success: boolean; error?: string }> { if (!cloudAuth.state.isLoggedIn) { return { success: false, error: "Not signed in to BetterSEQTA Cloud" }; } @@ -241,7 +247,10 @@ export async function uploadCloudProfilePicture(source: Blob): Promise<{ success } } -export async function syncLocalProfilePictureToCloud(): Promise<{ success: boolean; error?: string }> { +export async function syncLocalProfilePictureToCloud(): Promise<{ + success: boolean; + error?: string; +}> { if (!(await isUseCloudPfpEnabled()) || !cloudAuth.state.isLoggedIn) return { success: true }; const blob = await profileStore.getItem("profile-picture"); if (!(blob instanceof Blob)) return { success: true }; @@ -257,7 +266,9 @@ export async function clearCloudProfilePicture(): Promise<{ success: boolean; er return { success: true }; } -export async function revertCloudProfilePicture(historyId: string): Promise<{ success: boolean; error?: string }> { +export async function revertCloudProfilePicture( + historyId: string, +): Promise<{ success: boolean; error?: string }> { if (!cloudAuth.state.isLoggedIn) { return { success: false, error: "Not signed in to BetterSEQTA Cloud" }; } diff --git a/src/seqta/utils/cloudSettingsSync.legacy.test.ts b/src/seqta/utils/cloudSettingsSync.legacy.test.ts index 6de7436e..e3eeb1c8 100644 --- a/src/seqta/utils/cloudSettingsSync.legacy.test.ts +++ b/src/seqta/utils/cloudSettingsSync.legacy.test.ts @@ -32,9 +32,7 @@ describe("isKeyIncludedInCloudUploadPayload", () => { expect(isKeyIncludedInCloudUploadPayload("bsplus_token")).toBe(false); expect(isKeyIncludedInCloudUploadPayload("bsplus_install_id")).toBe(false); expect(isKeyIncludedInCloudUploadPayload(BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY)).toBe(false); - expect(isKeyIncludedInCloudUploadPayload("plugin.global-search.storage.index")).toBe( - false, - ); + expect(isKeyIncludedInCloudUploadPayload("plugin.global-search.storage.index")).toBe(false); expect(isKeyIncludedInCloudUploadPayload("bsplus.analytics.v2.school.1")).toBe(false); }); diff --git a/src/seqta/utils/cloudSettingsSync.ts b/src/seqta/utils/cloudSettingsSync.ts index 288e1a5a..87f0f3a3 100644 --- a/src/seqta/utils/cloudSettingsSync.ts +++ b/src/seqta/utils/cloudSettingsSync.ts @@ -245,9 +245,7 @@ export async function getLastUploadedSnapshot(): Promise return snapshot as Record; } -export async function saveLastUploadedSnapshot( - snapshot: Record, -): Promise { +export async function saveLastUploadedSnapshot(snapshot: Record): Promise { await browser.storage.local.set({ [BSPLUS_CLOUD_LAST_UPLOADED_SNAPSHOT_KEY]: snapshot }); } @@ -266,9 +264,7 @@ export async function getSnapshotForUpload(): Promise).themeId, - ); + const top = normalizeThemeIdForSync((envelope as Record).themeId); if (top) return top; } @@ -304,7 +300,9 @@ export async function setKnownRemoteUpdatedAt(iso: string | undefined): Promise< * Only applies migrations for keys present in the data; does not overwrite * existing plugin settings if the legacy key is absent. */ -export function migrateLegacyToPluginSettings(data: Record): Record { +export function migrateLegacyToPluginSettings( + data: Record, +): Record { const result = { ...data }; function ensurePluginSettings(pluginId: string): Record { diff --git a/src/seqta/utils/convertTo12HourFormat.ts b/src/seqta/utils/convertTo12HourFormat.ts index 691bea0c..39a00eb5 100644 --- a/src/seqta/utils/convertTo12HourFormat.ts +++ b/src/seqta/utils/convertTo12HourFormat.ts @@ -1,7 +1,4 @@ -export function convertTo12HourFormat( - time: string, - noMinutes: boolean = false, -): string { +export function convertTo12HourFormat(time: string, noMinutes: boolean = false): string { let [hours, minutes] = time.split(":").map(Number); let period = "am"; diff --git a/src/seqta/utils/createEnable/CreateCustomShortcutDiv.ts b/src/seqta/utils/createEnable/CreateCustomShortcutDiv.ts index 85707f22..3359804c 100644 --- a/src/seqta/utils/createEnable/CreateCustomShortcutDiv.ts +++ b/src/seqta/utils/createEnable/CreateCustomShortcutDiv.ts @@ -36,8 +36,7 @@ export function CreateCustomShortcutDiv(element: any) { img.style.height = "39px"; image = img; } else { - image = stringToHTML( - /* html */` + image = stringToHTML(/* html */ ` - `, - ).firstChild; + `).firstChild; } (image as HTMLElement).classList.add("shortcuticondiv"); const text = document.createElement("p"); diff --git a/src/seqta/utils/customThemes/apiErrors.ts b/src/seqta/utils/customThemes/apiErrors.ts index 1114d423..faca908a 100644 --- a/src/seqta/utils/customThemes/apiErrors.ts +++ b/src/seqta/utils/customThemes/apiErrors.ts @@ -1,16 +1,21 @@ -import { CustomThemeApiError } from "./client"; -import { RATE_LIMIT_DAILY_MESSAGE, RATE_LIMIT_PENDING_MESSAGE } from "./constants"; - -export function formatCustomThemeApiError(err: unknown): string { - if (err instanceof CustomThemeApiError) { - if (err.status === 429) { - return err.message.includes("pending") ? RATE_LIMIT_PENDING_MESSAGE : RATE_LIMIT_DAILY_MESSAGE; - } - if (err.validationErrors.length > 0) { - return err.validationErrors.join("\n"); - } - return err.message; - } - return err instanceof Error ? err.message : "Something went wrong"; -} - \ No newline at end of file +import { CustomThemeApiError } from "./client"; + +import { RATE_LIMIT_DAILY_MESSAGE, RATE_LIMIT_PENDING_MESSAGE } from "./constants"; + +export function formatCustomThemeApiError(err: unknown): string { + if (err instanceof CustomThemeApiError) { + if (err.status === 429) { + return err.message.includes("pending") + ? RATE_LIMIT_PENDING_MESSAGE + : RATE_LIMIT_DAILY_MESSAGE; + } + + if (err.validationErrors.length > 0) { + return err.validationErrors.join("\n"); + } + + return err.message; + } + + return err instanceof Error ? err.message : "Something went wrong"; +} diff --git a/src/seqta/utils/customThemes/buildThemeUploadFormData.test.ts b/src/seqta/utils/customThemes/buildThemeUploadFormData.test.ts index 0a37af53..f51ea945 100644 --- a/src/seqta/utils/customThemes/buildThemeUploadFormData.test.ts +++ b/src/seqta/utils/customThemes/buildThemeUploadFormData.test.ts @@ -4,7 +4,14 @@ import { mergeUploadPayload } from "./buildThemeUploadFormData"; describe("buildThemeUploadFormData", () => { it("mergeUploadPayload attaches trimmed submission notes", () => { const merged = mergeUploadPayload( - { themeZip: { fieldName: "theme_zip", filename: "t.zip", mimeType: "application/zip", dataBase64: "abc" } }, + { + themeZip: { + fieldName: "theme_zip", + filename: "t.zip", + mimeType: "application/zip", + dataBase64: "abc", + }, + }, " Please review ", ); expect(merged.submissionNotes).toBe("Please review"); diff --git a/src/seqta/utils/customThemes/client.test.ts b/src/seqta/utils/customThemes/client.test.ts index 9f52b337..aa7d7df7 100644 --- a/src/seqta/utils/customThemes/client.test.ts +++ b/src/seqta/utils/customThemes/client.test.ts @@ -1,8 +1,4 @@ -import { - formatCustomThemeStatus, - statusBadgeClass, - canEditCustomTheme, -} from "./client"; +import { formatCustomThemeStatus, statusBadgeClass, canEditCustomTheme } from "./client"; import { formatEnvelopeErrorMessage, normalizeCustomThemeApiResponse, @@ -24,13 +20,39 @@ describe("customThemes client helpers", () => { }); it("allows edit only for pending and rejected themes", () => { - expect(canEditCustomTheme({ id: "1", name: "A", description: "", coverImage: "", status: "pending" })).toBe(true); - expect(canEditCustomTheme({ id: "1", name: "A", description: "", coverImage: "", status: "rejected" })).toBe(true); - expect(canEditCustomTheme({ id: "1", name: "A", description: "", coverImage: "", status: "approved" })).toBe(false); + expect( + canEditCustomTheme({ + id: "1", + name: "A", + description: "", + coverImage: "", + status: "pending", + }), + ).toBe(true); + expect( + canEditCustomTheme({ + id: "1", + name: "A", + description: "", + coverImage: "", + status: "rejected", + }), + ).toBe(true); + expect( + canEditCustomTheme({ + id: "1", + name: "A", + description: "", + coverImage: "", + status: "approved", + }), + ).toBe(false); }); it("parses API envelope errors and validation details", () => { - expect(parseApiError({ code: "INVALID_THEME_STRUCTURE", message: "Bad theme" })).toBe("Bad theme"); + expect(parseApiError({ code: "INVALID_THEME_STRUCTURE", message: "Bad theme" })).toBe( + "Bad theme", + ); expect(parseApiError(null, 500)).toBe("Request failed (HTTP 500)"); expect( parseValidationErrors({ diff --git a/src/seqta/utils/customThemes/client.ts b/src/seqta/utils/customThemes/client.ts index 4ae59efe..1b42174b 100644 --- a/src/seqta/utils/customThemes/client.ts +++ b/src/seqta/utils/customThemes/client.ts @@ -34,7 +34,11 @@ async function sendRuntimeMessage(message: object): Promise { return (await browser.runtime.sendMessage(message)) as T; } catch (err) { const msg = err instanceof Error ? err.message : String(err); - if (/disconnected port|context invalidated|receiving end does not exist|message port closed/i.test(msg)) { + if ( + /disconnected port|context invalidated|receiving end does not exist|message port closed/i.test( + msg, + ) + ) { throw new Error(EXTENSION_RELOAD_HINT, { cause: err }); } throw err; @@ -61,8 +65,7 @@ function sendMessageWithTimeout(message: object): Promise { function throwFromEnvelope( envelope: CustomThemeApiEnvelope & { httpStatus?: number }, ): never { - const errObj = - envelope.error && typeof envelope.error === "object" ? envelope.error : undefined; + const errObj = envelope.error && typeof envelope.error === "object" ? envelope.error : undefined; throw new CustomThemeApiError( formatEnvelopeErrorMessage(envelope), envelope.httpStatus ?? 0, @@ -102,7 +105,10 @@ export async function fetchCommunityThemes(options?: { search?: string; }): Promise { const res = await sendMessageWithTimeout< - CustomThemeApiEnvelope<{ themes?: unknown[]; pagination?: CustomThemeListResponse["pagination"] }> + CustomThemeApiEnvelope<{ + themes?: unknown[]; + pagination?: CustomThemeListResponse["pagination"]; + }> >({ type: "fetchCustomThemes", page: options?.page ?? 1, @@ -125,7 +131,10 @@ export async function fetchMyCustomThemes(options?: { status?: CustomThemeStatus; }): Promise { const res = await sendMessageWithTimeout< - CustomThemeApiEnvelope<{ themes?: unknown[]; pagination?: CustomThemeListResponse["pagination"] }> + CustomThemeApiEnvelope<{ + themes?: unknown[]; + pagination?: CustomThemeListResponse["pagination"]; + }> >({ type: "fetchMyCustomThemes", page: options?.page ?? 1, diff --git a/src/seqta/utils/defaultSettings.ts b/src/seqta/utils/defaultSettings.ts index df4337aa..cd3b1723 100644 --- a/src/seqta/utils/defaultSettings.ts +++ b/src/seqta/utils/defaultSettings.ts @@ -1,8 +1,7 @@ import type { SettingsState } from "@/types/storage"; function detectLowEndDevice(): boolean { - const lowCoreCount = - navigator.hardwareConcurrency && navigator.hardwareConcurrency < 4; + const lowCoreCount = navigator.hardwareConcurrency && navigator.hardwareConcurrency < 4; const lowMemory = (navigator as Navigator & { deviceMemory?: number }).deviceMemory != null && (navigator as Navigator & { deviceMemory?: number }).deviceMemory! <= 2; @@ -44,8 +43,7 @@ export function getDefaultSettingsState(): SettingsState { menuorder: [], subjectfilters: {}, selectedTheme: "", - selectedColor: - "linear-gradient(45deg, rgba(17,88,131,1) 0%, rgba(18,106,98,1) 100%)", + selectedColor: "linear-gradient(45deg, rgba(17,88,131,1) 0%, rgba(18,106,98,1) 100%)", originalSelectedColor: "", DarkMode: true, animations: !isLowEndDevice, diff --git a/src/seqta/utils/engageAssessmentStudent.ts b/src/seqta/utils/engageAssessmentStudent.ts index c5a60e5d..00d11971 100644 --- a/src/seqta/utils/engageAssessmentStudent.ts +++ b/src/seqta/utils/engageAssessmentStudent.ts @@ -1,5 +1,4 @@ -export const ENGAGE_STUDENT_STORAGE_KEY = () => - `bsplus.engageTimetable.student.${location.origin}`; +export const ENGAGE_STUDENT_STORAGE_KEY = () => `bsplus.engageTimetable.student.${location.origin}`; /** Engage assessments URLs: /#?page=/assessments/{studentId}/{programme}:{metaclass}:{studentId} */ export function getEngageAssessmentStudentId(): string | null { @@ -19,9 +18,7 @@ export function buildEngageAssessmentPagePath( return assessmentId != null ? `${base}&item=${assessmentId}` : base; } -export function buildEngageAssessmentOverviewPath( - studentId: string | number, -): string { +export function buildEngageAssessmentOverviewPath(studentId: string | number): string { return `#?page=/assessments/${studentId}/overview`; } diff --git a/src/seqta/utils/ensureSyncableStorageDefaults.ts b/src/seqta/utils/ensureSyncableStorageDefaults.ts index f872e4bc..a0b9ad91 100644 --- a/src/seqta/utils/ensureSyncableStorageDefaults.ts +++ b/src/seqta/utils/ensureSyncableStorageDefaults.ts @@ -60,9 +60,7 @@ export function getSyncableStorageDefaults(): Record { delete flat[key]; } - for (const [pluginId, settings] of Object.entries( - SYNCABLE_PLUGIN_SETTING_DEFAULTS, - )) { + for (const [pluginId, settings] of Object.entries(SYNCABLE_PLUGIN_SETTING_DEFAULTS)) { flat[`plugin.${pluginId}.settings`] = settings; } diff --git a/src/seqta/utils/feedback/client.ts b/src/seqta/utils/feedback/client.ts index 952aba38..0404d1c1 100644 --- a/src/seqta/utils/feedback/client.ts +++ b/src/seqta/utils/feedback/client.ts @@ -138,7 +138,11 @@ async function throwApiError(res: Response): Promise { body.code ?? "RATE_LIMITED", ); } - throw new FeedbackApiError(body.error || `Request failed (${res.status}).`, res.status, body.code); + throw new FeedbackApiError( + body.error || `Request failed (${res.status}).`, + res.status, + body.code, + ); } export async function submitFeedback(form: FeedbackFormInput): Promise<{ id: string }> { @@ -201,7 +205,8 @@ export async function submitFeedback(form: FeedbackFormInput): Promise<{ id: str }); if (res.status !== 201 && res.status !== 200) await throwApiError(res); const data = (await res.json()) as { id?: string }; - if (!data?.id) throw new FeedbackApiError("Unexpected response from the feedback server.", res.status); + if (!data?.id) + throw new FeedbackApiError("Unexpected response from the feedback server.", res.status); return { id: data.id }; } @@ -252,7 +257,9 @@ async function getPendingIds(): Promise { const stored = await browser.storage.local.get(BSPLUS_PENDING_FEEDBACK_IDS_KEY); const raw = stored[BSPLUS_PENDING_FEEDBACK_IDS_KEY]; if (!Array.isArray(raw)) return []; - return [...new Set(raw.filter((id): id is string => typeof id === "string" && id.startsWith("fb_")))]; + return [ + ...new Set(raw.filter((id): id is string => typeof id === "string" && id.startsWith("fb_"))), + ]; } export async function addPendingFeedbackId(id: string): Promise { diff --git a/src/seqta/utils/feedback/installId.ts b/src/seqta/utils/feedback/installId.ts index f4325092..b5d300c1 100644 --- a/src/seqta/utils/feedback/installId.ts +++ b/src/seqta/utils/feedback/installId.ts @@ -1,8 +1,7 @@ import browser from "@/lib/browser"; import { BSPLUS_INSTALL_ID_KEY } from "./constants"; -const UUID_RE = - /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; +const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; export function isValidInstallId(value: unknown): value is string { return typeof value === "string" && UUID_RE.test(value); diff --git a/src/seqta/utils/founderBadges.ts b/src/seqta/utils/founderBadges.ts index 10b6e4e8..5f0174f4 100644 --- a/src/seqta/utils/founderBadges.ts +++ b/src/seqta/utils/founderBadges.ts @@ -88,8 +88,7 @@ export const ACHIEVEMENT_BADGES = [ key: "theme_submitter", label: "Theme Submitter", rankLabel: "Community", - description: - "Submitted a custom theme that was accepted into the BetterSEQTA theme gallery.", + description: "Submitted a custom theme that was accepted into the BetterSEQTA theme gallery.", base: "#5b21b6", blobs: ["rgba(139,92,246,0.52)", "rgba(124,58,237,0.46)", "rgba(196,181,253,0.4)"], icon: "swatch", @@ -128,10 +127,7 @@ const UNKNOWN_ACHIEVEMENT_VISUAL = { icon: "sparkles", } as const; -function primaryFounderBadge( - badges: BadgeItem[], - signupNumber?: number | null, -): BadgeItem | null { +function primaryFounderBadge(badges: BadgeItem[], signupNumber?: number | null): BadgeItem | null { const fromApi = badges.find((b) => b.key.startsWith("founder_")); if (fromApi) return fromApi; @@ -154,10 +150,7 @@ function primaryFounderBadge( } /** Founder pill (at most one) then achievement pills — matches Accounts display rules. */ -export function badgesForTitlebar( - badges: BadgeItem[], - signupNumber?: number | null, -): BadgeItem[] { +export function badgesForTitlebar(badges: BadgeItem[], signupNumber?: number | null): BadgeItem[] { const founder = primaryFounderBadge(badges, signupNumber); const achievements = badges.filter((b) => !b.key.startsWith("founder_")); return founder ? [founder, ...achievements] : achievements; @@ -195,10 +188,7 @@ function badgeBlobStyle(visual: Pick): string { ].join(";"); } -export function founderBadgeChipHtml( - badge: BadgeItem, - options?: { hero?: boolean }, -): string { +export function founderBadgeChipHtml(badge: BadgeItem, options?: { hero?: boolean }): string { const visual = badgeVisualForKey(badge.key, badge.label); if (!visual) return ""; diff --git a/src/seqta/utils/googleCalendar/calendarProvisioning.test.ts b/src/seqta/utils/googleCalendar/calendarProvisioning.test.ts index d5816881..689743d0 100644 --- a/src/seqta/utils/googleCalendar/calendarProvisioning.test.ts +++ b/src/seqta/utils/googleCalendar/calendarProvisioning.test.ts @@ -25,7 +25,9 @@ describe("ensureGoogleAppCalendar", () => { }); it("reuses a stored calendar id when it still exists", async () => { - fetchMock.mockResolvedValueOnce(jsonResponse({ id: "stored-id", summary: "BetterSEQTA+ Timetable" })); + fetchMock.mockResolvedValueOnce( + jsonResponse({ id: "stored-id", summary: "BetterSEQTA+ Timetable" }), + ); await expect(ensureGoogleAppCalendar("token", "stored-id")).resolves.toBe("stored-id"); expect(fetchMock).toHaveBeenCalledTimes(1); @@ -41,7 +43,9 @@ describe("ensureGoogleAppCalendar", () => { await expect(ensureGoogleAppCalendar("token")).resolves.toBe("found-id"); expect(fetchMock).toHaveBeenCalledWith( "https://www.googleapis.com/calendar/v3/users/me/calendarList", - expect.objectContaining({ headers: expect.objectContaining({ Authorization: "Bearer token" }) }), + expect.objectContaining({ + headers: expect.objectContaining({ Authorization: "Bearer token" }), + }), ); }); diff --git a/src/seqta/utils/googleCalendar/calendarProvisioning.ts b/src/seqta/utils/googleCalendar/calendarProvisioning.ts index 6d0c25a8..21ee82a4 100644 --- a/src/seqta/utils/googleCalendar/calendarProvisioning.ts +++ b/src/seqta/utils/googleCalendar/calendarProvisioning.ts @@ -60,9 +60,7 @@ async function createAppCalendar(accessToken: string): Promise { ); if (!ok || !data.id) { - throw new Error( - data.error?.message ?? `Could not create BetterSEQTA+ calendar (${status}).`, - ); + throw new Error(data.error?.message ?? `Could not create BetterSEQTA+ calendar (${status}).`); } return data.id; } diff --git a/src/seqta/utils/googleCalendar/calendarSyncListener.ts b/src/seqta/utils/googleCalendar/calendarSyncListener.ts index d369f22b..2163c191 100644 --- a/src/seqta/utils/googleCalendar/calendarSyncListener.ts +++ b/src/seqta/utils/googleCalendar/calendarSyncListener.ts @@ -1,8 +1,5 @@ import browser from "@/lib/browser"; -import { - markWeeklySyncComplete, - shouldRunWeeklySync, -} from "@/seqta/utils/calendarSync/settings"; +import { markWeeklySyncComplete, shouldRunWeeklySync } from "@/seqta/utils/calendarSync/settings"; import { formatLessonSyncResultMessage } from "@/seqta/utils/calendarSync/lessonSyncShared"; import { resumeInterruptedCalendarSync, @@ -57,7 +54,10 @@ export function registerCalendarContentHandlers(): void { listenerRegistered = true; browser.runtime.onMessage.addListener((request, _sender, sendResponse) => { - if (request?.type === "calendarRunWeeklySync" || request?.type === "googleCalendarRunWeeklySync") { + if ( + request?.type === "calendarRunWeeklySync" || + request?.type === "googleCalendarRunWeeklySync" + ) { void runWeeklySyncForConnectedProviders() .then((results) => sendResponse({ success: true, results })) .catch((err: unknown) => { diff --git a/src/seqta/utils/googleCalendar/eventColor.ts b/src/seqta/utils/googleCalendar/eventColor.ts index 497ac9c8..1b252bcf 100644 --- a/src/seqta/utils/googleCalendar/eventColor.ts +++ b/src/seqta/utils/googleCalendar/eventColor.ts @@ -44,9 +44,7 @@ export function parseRgbColour(value: string): Rgb | null { }; } - const rgbMatch = trimmed.match( - /rgba?\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)/i, - ); + const rgbMatch = trimmed.match(/rgba?\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)/i); if (rgbMatch) { return { r: Math.round(Number(rgbMatch[1])), diff --git a/src/seqta/utils/googleCalendar/fetchTimetable.test.ts b/src/seqta/utils/googleCalendar/fetchTimetable.test.ts index 2e116874..801afea0 100644 --- a/src/seqta/utils/googleCalendar/fetchTimetable.test.ts +++ b/src/seqta/utils/googleCalendar/fetchTimetable.test.ts @@ -1,11 +1,4 @@ -import { - afterEach, - beforeEach, - describe, - expect, - it, - jest, -} from "@jest/globals"; +import { afterEach, beforeEach, describe, expect, it, jest } from "@jest/globals"; import { appointmentToLesson, fetchAppointments, @@ -65,17 +58,14 @@ describe("calendar source fetches", () => { const path = String(url); const body = JSON.parse(String(init?.body)); if (path.endsWith("/seqta/parent/load/timetable")) { - if (body.list) - return Response.json({ payload: [{ id: "42", name: "Child" }] }); + if (body.list) return Response.json({ payload: [{ id: "42", name: "Child" }] }); timetableStudents.push(body.student); return Response.json({ payload: { items: [] } }); } if (path.endsWith("/seqta/parent/assessment/list/upcoming?")) { assessmentStudents.push(body.student); return Response.json({ - payload: [ - { id: 1, title: "Essay", subject: "English", due: "2026-07-20" }, - ], + payload: [{ id: 1, title: "Essay", subject: "English", due: "2026-07-20" }], }); } if (path.includes("/seqta/student/")) @@ -83,9 +73,9 @@ describe("calendar source fetches", () => { return Response.json({ payload: [] }); }); await expect(fetchTimetableLessons(range)).resolves.toEqual([]); - await expect(fetchAssessmentsForCalendarSync(range)).resolves.toMatchObject( - [{ id: 1, title: "Essay" }], - ); + await expect(fetchAssessmentsForCalendarSync(range)).resolves.toMatchObject([ + { id: 1, title: "Essay" }, + ]); expect(timetableStudents).toEqual([42]); expect(assessmentStudents).toEqual([42]); }); @@ -94,8 +84,7 @@ describe("calendar source fetches", () => { "rejects failed $name fetches instead of reporting an empty source", async ({ path, load }) => { jest.spyOn(globalThis, "fetch").mockImplementation(async (url) => { - if (String(url).endsWith(path)) - return new Response("unavailable", { status: 503 }); + if (String(url).endsWith(path)) return new Response("unavailable", { status: 503 }); return Response.json({ payload: String(url).endsWith("/login") ? { id: 12 } : [], }); @@ -108,8 +97,7 @@ describe("calendar source fetches", () => { "rejects missing $name payloads that cannot authorize reconciliation", async ({ path, load }) => { jest.spyOn(globalThis, "fetch").mockImplementation(async (url) => { - if (String(url).endsWith(path)) - return Response.json({ error: "Session expired" }); + if (String(url).endsWith(path)) return Response.json({ error: "Session expired" }); return Response.json({ payload: String(url).endsWith("/login") ? { id: 12 } : [], }); diff --git a/src/seqta/utils/googleCalendar/fetchTimetable.ts b/src/seqta/utils/googleCalendar/fetchTimetable.ts index 3eeeefa9..df7aca62 100644 --- a/src/seqta/utils/googleCalendar/fetchTimetable.ts +++ b/src/seqta/utils/googleCalendar/fetchTimetable.ts @@ -72,7 +72,6 @@ function withSubjectColours( }); } - export async function resolveStudentId(): Promise { if (isEngageParentContext()) { const data = await postSeqtaJson<{ payload?: { id?: string | number }[] }>( @@ -113,7 +112,9 @@ type SeqtaAppointmentPayload = { }; /** Parse SEQTA datetimes like `2026-07-20 09:30:00.0` into lesson date/time fields. */ -export function parseSeqtaDateTime(value: string | undefined): { date: string; time: string } | null { +export function parseSeqtaDateTime( + value: string | undefined, +): { date: string; time: string } | null { if (!value) return null; const match = value.trim().match(/^(\d{4}-\d{2}-\d{2})[ T](\d{1,2}:\d{2})/); if (!match) return null; @@ -144,8 +145,7 @@ export async function fetchAppointments(range: SyncDateRange): Promise( @@ -170,9 +170,7 @@ export async function fetchAppointments(range: SyncDateRange): Promise { +export async function fetchTimetableLessons(range: SyncDateRange): Promise { const { from, until } = range; const coloursPromise = fetchSubjectColours(); @@ -236,8 +234,7 @@ export async function fetchAssessmentsForCalendarSync( range: SyncDateRange, ): Promise { const studentId = await resolveStudentId(); - if (studentId == null) - throw new Error("Could not resolve student for calendar sync."); + if (studentId == null) throw new Error("Could not resolve student for calendar sync."); const path = isEngageParentContext() ? "/seqta/parent/assessment/list/upcoming?" diff --git a/src/seqta/utils/googleCalendar/syncDateRange.test.ts b/src/seqta/utils/googleCalendar/syncDateRange.test.ts index d6b21839..d974f377 100644 --- a/src/seqta/utils/googleCalendar/syncDateRange.test.ts +++ b/src/seqta/utils/googleCalendar/syncDateRange.test.ts @@ -1,9 +1,5 @@ import { describe, expect, it } from "@jest/globals"; -import { - droppedWeekRange, - syncWindowRange, - trailingWeekRange, -} from "./syncDateRange"; +import { droppedWeekRange, syncWindowRange, trailingWeekRange } from "./syncDateRange"; describe("syncDateRange", () => { it("builds a 12-week rolling window from the current week", () => { diff --git a/src/seqta/utils/googleCalendar/syncEngine.test.ts b/src/seqta/utils/googleCalendar/syncEngine.test.ts index 7c6a5d4d..a1248d25 100644 --- a/src/seqta/utils/googleCalendar/syncEngine.test.ts +++ b/src/seqta/utils/googleCalendar/syncEngine.test.ts @@ -76,9 +76,11 @@ describe("syncLessonsToGoogleCalendar", () => { }); jest.mocked(upsertGoogleCalendarEvent).mockResolvedValue("google-existing"); jest.mocked(deleteGoogleCalendarEvent).mockResolvedValue(undefined); - jest.mocked(listGoogleSyncedEvents).mockResolvedValue([ - { seqtaKey: `${ORIGIN}:cal:12345`, id: "google-existing", date: syncDate, fingerprint: "" }, - ]); + jest + .mocked(listGoogleSyncedEvents) + .mockResolvedValue([ + { seqtaKey: `${ORIGIN}:cal:12345`, id: "google-existing", date: syncDate, fingerprint: "" }, + ]); }); it("updates existing events and removes stale tracked events on full sync", async () => { @@ -155,23 +157,47 @@ describe("syncLessonsToGoogleCalendar", () => { }); }); - it.each([false, true])("repairs missing remote events only after a complete listing (list failed: %s)", async (listFailed) => { - const mapped = lessonToGoogleEvent(ORIGIN, baseLesson, Intl.DateTimeFormat().resolvedOptions().timeZone)!; - jest.mocked(readGoogleCalendarState).mockResolvedValue({ - refreshToken: "refresh", calendarId: "app-calendar-id", - eventMap: { [`${ORIGIN}::${mapped.seqtaKey}`]: { id: "deleted-remotely", date: syncDate, fingerprint: eventFingerprint(mapped) } }, - }); - if (listFailed) jest.mocked(listGoogleSyncedEvents).mockRejectedValueOnce(new Error("Second page failed")); - else jest.mocked(listGoogleSyncedEvents).mockResolvedValueOnce([]); - const result = await syncLessonsToGoogleCalendar({ origin: ORIGIN, lessons: [baseLesson], mode: "full" }, getAccessToken); - if (listFailed) { - expect(upsertGoogleCalendarEvent).not.toHaveBeenCalled(); - expect(result.skipped).toBe(1); - } else { - expect(upsertGoogleCalendarEvent).toHaveBeenCalledWith("test-token", "app-calendar-id", undefined, expect.any(Object), expect.any(Function)); - expect(result.created).toBe(1); - } - }); + it.each([false, true])( + "repairs missing remote events only after a complete listing (list failed: %s)", + async (listFailed) => { + const mapped = lessonToGoogleEvent( + ORIGIN, + baseLesson, + Intl.DateTimeFormat().resolvedOptions().timeZone, + )!; + jest.mocked(readGoogleCalendarState).mockResolvedValue({ + refreshToken: "refresh", + calendarId: "app-calendar-id", + eventMap: { + [`${ORIGIN}::${mapped.seqtaKey}`]: { + id: "deleted-remotely", + date: syncDate, + fingerprint: eventFingerprint(mapped), + }, + }, + }); + if (listFailed) + jest.mocked(listGoogleSyncedEvents).mockRejectedValueOnce(new Error("Second page failed")); + else jest.mocked(listGoogleSyncedEvents).mockResolvedValueOnce([]); + const result = await syncLessonsToGoogleCalendar( + { origin: ORIGIN, lessons: [baseLesson], mode: "full" }, + getAccessToken, + ); + if (listFailed) { + expect(upsertGoogleCalendarEvent).not.toHaveBeenCalled(); + expect(result.skipped).toBe(1); + } else { + expect(upsertGoogleCalendarEvent).toHaveBeenCalledWith( + "test-token", + "app-calendar-id", + undefined, + expect.any(Object), + expect.any(Function), + ); + expect(result.created).toBe(1); + } + }, + ); it("deletes cancelled lessons that remain inside the sync window", async () => { jest.mocked(readGoogleCalendarState).mockResolvedValue({ diff --git a/src/seqta/utils/listeners/ClickListeners.ts b/src/seqta/utils/listeners/ClickListeners.ts index 9ca084cd..80333ac0 100644 --- a/src/seqta/utils/listeners/ClickListeners.ts +++ b/src/seqta/utils/listeners/ClickListeners.ts @@ -11,16 +11,13 @@ const handleNotificationClick = async (target: HTMLElement) => { const buttonType = notificationItem.getAttribute("data-type"); if (buttonType !== "message") return; - const notificationList = await ReactFiber.find( - '[class*="notifications__list___"]', - ).getState(); + const notificationList = await ReactFiber.find('[class*="notifications__list___"]').getState(); const buttonId = notificationItem.getAttribute("data-id"); if (!buttonId) return; - const matchingNotification = - notificationList.items.find( - (item: any) => item.notificationID === parseInt(buttonId), - ); + const matchingNotification = notificationList.items.find( + (item: any) => item.notificationID === parseInt(buttonId), + ); if (!matchingNotification?.message?.messageID) return; @@ -42,14 +39,14 @@ const handleNotificationClick = async (target: HTMLElement) => { if (button) { (button as HTMLElement).click(); } - + // 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: [matchingNotification.message.messageID], - mode: 'x-read', + mode: "x-read", read: true, }), }); diff --git a/src/seqta/utils/listeners/EventManager.ts b/src/seqta/utils/listeners/EventManager.ts index 8df11897..4baeb60b 100644 --- a/src/seqta/utils/listeners/EventManager.ts +++ b/src/seqta/utils/listeners/EventManager.ts @@ -16,7 +16,6 @@ interface EventListener { unregister: () => void; } - class EventManager { private static instance: EventManager; private listeners: Map = new Map(); @@ -74,10 +73,7 @@ class EventManager { return selector.trim() || null; } - private getElementsToCheck( - element: Element, - options: EventListenerOptions, - ): Element[] { + private getElementsToCheck(element: Element, options: EventListenerOptions): Element[] { const selector = this.buildSelector(options); if (!selector) return [element]; @@ -108,9 +104,7 @@ class EventManager { for (let i = 0; i < elements.length; i += this.chunkSize) { const chunk = elements.slice(i, i + this.chunkSize); - const filteredChunk = chunk.filter((element) => - this.matchesOptions(element, options), - ); + const filteredChunk = chunk.filter((element) => this.matchesOptions(element, options)); for (const element of filteredChunk) { callback(element); } @@ -213,19 +207,11 @@ class EventManager { } } - private matchesOptions( - element: Element, - options: EventListenerOptions, - ): boolean { - if ( - options.elementType && - element.tagName.toLowerCase() !== options.elementType.toLowerCase() - ) - return false; - if (options.textContent && element.textContent !== options.textContent) - return false; - if (options.className && !element.classList.contains(options.className)) + private matchesOptions(element: Element, options: EventListenerOptions): boolean { + if (options.elementType && element.tagName.toLowerCase() !== options.elementType.toLowerCase()) return false; + if (options.textContent && element.textContent !== options.textContent) return false; + if (options.className && !element.classList.contains(options.className)) return false; if (options.id && element.id !== options.id) return false; if (options.customCheck && !options.customCheck(element)) return false; return true; @@ -233,5 +219,4 @@ class EventManager { } export const eventManager = EventManager.getInstance(); -export const initializeEventManager = async () => - await EventManager.initialize(); +export const initializeEventManager = async () => await EventManager.initialize(); diff --git a/src/seqta/utils/listeners/MessageListener.ts b/src/seqta/utils/listeners/MessageListener.ts index c23c2e82..ff6aa18d 100644 --- a/src/seqta/utils/listeners/MessageListener.ts +++ b/src/seqta/utils/listeners/MessageListener.ts @@ -99,11 +99,9 @@ export class MessageHandler { case "OpenThemeCreator": { const themeID = request?.body?.themeID; - void import("@/plugins/built-in/themes/ThemeCreator").then( - ({ OpenThemeCreator }) => { - void OpenThemeCreator(themeID ? themeID : ""); - }, - ); + void import("@/plugins/built-in/themes/ThemeCreator").then(({ OpenThemeCreator }) => { + void OpenThemeCreator(themeID ? themeID : ""); + }); closeExtensionPopup(); sendResponse({ status: "success" }); break; @@ -118,17 +116,15 @@ export class MessageHandler { return true; case "CloseThemeCreator": - void import("@/plugins/built-in/themes/ThemeCreator").then( - ({ CloseThemeCreator }) => { - try { - CloseThemeCreator(); - sendResponse({ status: "success" }); - } catch (error) { - console.error("Error closing theme creator:", error); - sendResponse({ status: "error" }); - } - }, - ); + void import("@/plugins/built-in/themes/ThemeCreator").then(({ CloseThemeCreator }) => { + try { + CloseThemeCreator(); + sendResponse({ status: "success" }); + } catch (error) { + console.error("Error closing theme creator:", error); + sendResponse({ status: "error" }); + } + }); return true; case "HideSensitive": diff --git a/src/seqta/utils/listeners/SettingsState.master.test.ts b/src/seqta/utils/listeners/SettingsState.master.test.ts index 54574e5f..c9327aa9 100644 --- a/src/seqta/utils/listeners/SettingsState.master.test.ts +++ b/src/seqta/utils/listeners/SettingsState.master.test.ts @@ -5,37 +5,46 @@ describe("master extension setting", () => { jest.useRealTimers(); }); - it.each([false, true])("persists %s and queued preferences before reloading SEQTA tabs", async (enabled) => { - jest.useFakeTimers(); - let browser: any; - let settings: typeof import("./SettingsState"); - jest.isolateModules(() => { - browser = require("@/lib/browser").default; - settings = require("./SettingsState"); - }); - await browser.storage.local.set({ onoff: !enabled }); - await settings!.initializeSettingsState(); - browser.runtime.sendMessage.mockClear(); - const originalSet = browser.storage.local.set.getMockImplementation(); - let finishWrite: () => Promise = async () => {}; - browser.storage.local.set.mockImplementationOnce((patch: Record) => new Promise((resolve) => { - finishWrite = async () => { - await originalSet(patch); - resolve(); - }; - })); - browser.runtime.sendMessage.mockImplementation(async () => { - expect(await browser.storage.local.get(null)).toMatchObject({ onoff: enabled, selectedFont: "inter" }); - }); + it.each([false, true])( + "persists %s and queued preferences before reloading SEQTA tabs", + async (enabled) => { + jest.useFakeTimers(); + let browser: any; + let settings: typeof import("./SettingsState"); + jest.isolateModules(() => { + browser = require("@/lib/browser").default; + settings = require("./SettingsState"); + }); + await browser.storage.local.set({ onoff: !enabled }); + await settings!.initializeSettingsState(); + browser.runtime.sendMessage.mockClear(); + const originalSet = browser.storage.local.set.getMockImplementation(); + let finishWrite: () => Promise = async () => {}; + browser.storage.local.set.mockImplementationOnce( + (patch: Record) => + new Promise((resolve) => { + finishWrite = async () => { + await originalSet(patch); + resolve(); + }; + }), + ); + browser.runtime.sendMessage.mockImplementation(async () => { + expect(await browser.storage.local.get(null)).toMatchObject({ + onoff: enabled, + selectedFont: "inter", + }); + }); - settings!.settingsState.selectedFont = "inter"; - settings!.settingsState.onoff = enabled; - jest.advanceTimersByTime(300); - expect(browser.runtime.sendMessage).not.toHaveBeenCalled(); - await finishWrite(); - await Promise.resolve(); - await Promise.resolve(); + settings!.settingsState.selectedFont = "inter"; + settings!.settingsState.onoff = enabled; + jest.advanceTimersByTime(300); + expect(browser.runtime.sendMessage).not.toHaveBeenCalled(); + await finishWrite(); + await Promise.resolve(); + await Promise.resolve(); - expect(browser.runtime.sendMessage).toHaveBeenCalledWith({ type: "reloadTabs" }); - }); + expect(browser.runtime.sendMessage).toHaveBeenCalledWith({ type: "reloadTabs" }); + }, + ); }); diff --git a/src/seqta/utils/listeners/SettingsState.ts b/src/seqta/utils/listeners/SettingsState.ts index 5ab566ce..aea116a1 100644 --- a/src/seqta/utils/listeners/SettingsState.ts +++ b/src/seqta/utils/listeners/SettingsState.ts @@ -155,10 +155,7 @@ class StorageManager { try { await browser.runtime.sendMessage({ type: "ensureStorageDefaults" }); } catch (e) { - console.warn( - "[BetterSEQTA+] ensureStorageDefaults message failed:", - e, - ); + console.warn("[BetterSEQTA+] ensureStorageDefaults message failed:", e); } await instance.loadFromStorage(); instance.initialized = true; @@ -169,10 +166,7 @@ class StorageManager { return instance; } - public setKey( - key: K, - value: SettingsState[K], - ): void { + public setKey(key: K, value: SettingsState[K]): void { if (typeof key === "string" && isExcludedSettingsKey(key)) { void browser.storage.local.set({ [key]: value }); return; @@ -192,11 +186,7 @@ class StorageManager { } } - private notifySettingChange( - key: string, - newValue: unknown, - oldValue: unknown, - ): void { + private notifySettingChange(key: string, newValue: unknown, oldValue: unknown): void { if (this.bootstrapping) return; const listeners = this.listeners.get(key); if (listeners) { @@ -214,7 +204,7 @@ class StorageManager { Reflect.set(this.data, key, value); }); } - + public setSuppressWrites(suppress: boolean): void { this.suppressWrites = suppress; if (!suppress) { @@ -223,10 +213,7 @@ class StorageManager { } private queueStoragePatch(changedKeys?: string[]): void { - const keys = - changedKeys && changedKeys.length > 0 - ? changedKeys - : Object.keys(this.data); + const keys = changedKeys && changedKeys.length > 0 ? changedKeys : Object.keys(this.data); for (const key of keys) { if (isExcludedSettingsKey(key)) continue; @@ -300,11 +287,7 @@ class StorageManager { } } - if ( - !this.bootstrapping && - actualChanges.length > 0 && - this.globalListeners.size > 0 - ) { + if (!this.bootstrapping && actualChanges.length > 0 && this.globalListeners.size > 0) { for (const listener of this.globalListeners) { for (const key of actualChanges) { const { oldValue, newValue } = changes[key]; @@ -326,7 +309,7 @@ class StorageManager { } this.listeners.get(key)!.add(listener); } - + public unregister(prop: keyof SettingsState, listener: ChangeListener): void { this.listeners.get(prop as string)?.delete(listener); } @@ -334,7 +317,7 @@ class StorageManager { public registerGlobal(listener: GlobalChangeListener): void { this.globalListeners.add(listener); } - + public unregisterGlobal(listener: GlobalChangeListener): void { this.globalListeners.delete(listener); } @@ -365,8 +348,7 @@ class StorageManager { } export const settingsState = StorageManager.getInstance(); -export const initializeSettingsState = async () => - await StorageManager.initialize(); +export const initializeSettingsState = async () => await StorageManager.initialize(); export function setSettingsStateSuppressWrites(suppress: boolean): void { settingsState.setSuppressWrites(suppress); diff --git a/src/seqta/utils/listeners/StorageChanges.test.ts b/src/seqta/utils/listeners/StorageChanges.test.ts index 55da205c..0fad2bf2 100644 --- a/src/seqta/utils/listeners/StorageChanges.test.ts +++ b/src/seqta/utils/listeners/StorageChanges.test.ts @@ -26,12 +26,10 @@ test("changing the selected font updates the page without reloading", () => { new StorageChangeHandler(); settingsState.selectedFont = "inter"; - expect( - document.documentElement.style.getPropertyValue( - "--betterseqta-font-family", - ), - ).toBe("Inter"); - expect( - document.getElementById("betterseqta-font-override")?.textContent, - ).toContain("font-family: Inter"); + expect(document.documentElement.style.getPropertyValue("--betterseqta-font-family")).toBe( + "Inter", + ); + expect(document.getElementById("betterseqta-font-override")?.textContent).toContain( + "font-family: Inter", + ); }); diff --git a/src/seqta/utils/listeners/StorageChanges.ts b/src/seqta/utils/listeners/StorageChanges.ts index 836b4210..aed8077e 100644 --- a/src/seqta/utils/listeners/StorageChanges.ts +++ b/src/seqta/utils/listeners/StorageChanges.ts @@ -20,33 +20,17 @@ export class StorageChangeHandler { settingsState.register("selectedColor", () => void updateAllColors()); settingsState.register("adaptiveThemeColour", () => void updateAllColors()); settingsState.register("adaptiveThemeGradient", () => void updateAllColors()); - settingsState.register("adaptiveThemeColourTransition", () => - void updateAllColors(), - ); + settingsState.register("adaptiveThemeColourTransition", () => void updateAllColors()); settingsState.register("selectedTheme", () => void updateAllColors()); settingsState.register("DarkMode", this.handleDarkModeChange.bind(this)); settingsState.register("shortcuts", this.handleShortcutsChange.bind(this)); - settingsState.register( - "customshortcuts", - this.handleCustomShortcutsChange.bind(this), - ); - settingsState.register( - "transparencyEffects", - this.handleTransparencyEffectsChange.bind(this), - ); + settingsState.register("customshortcuts", this.handleCustomShortcutsChange.bind(this)); + settingsState.register("transparencyEffects", this.handleTransparencyEffectsChange.bind(this)); settingsState.register("performanceMode", () => syncPerformanceModeEffects()); - settingsState.register("performanceModePluginOverrides", () => - syncPerformanceModeEffects(), - ); - settingsState.register( - "subjectfilters", - FilterUpcomingAssessments.bind(this), - ); + settingsState.register("performanceModePluginOverrides", () => syncPerformanceModeEffects()); + settingsState.register("subjectfilters", FilterUpcomingAssessments.bind(this)); registerHomeUpcomingSettingsListeners(); - settingsState.register( - "iconOnlySidebar", - this.handleIconOnlySidebarChange.bind(this), - ); + settingsState.register("iconOnlySidebar", this.handleIconOnlySidebarChange.bind(this)); settingsState.register("selectedFont", () => applySelectedFont()); settingsState.register("menuitems", () => scheduleMenuItemVisibility()); settingsState.register("menuorder", (order) => { @@ -74,9 +58,7 @@ export class StorageChangeHandler { renderShortcuts(); } - private handleShortcutsChange( - newValue: { enabled: boolean; name: string }[] | undefined, - ) { + private handleShortcutsChange(newValue: { enabled: boolean; name: string }[] | undefined) { if (!Array.isArray(newValue)) return; renderShortcuts(); } diff --git a/src/seqta/utils/loaders/LoadEngageHomePage.ts b/src/seqta/utils/loaders/LoadEngageHomePage.ts index 84e873c3..faaade3f 100644 --- a/src/seqta/utils/loaders/LoadEngageHomePage.ts +++ b/src/seqta/utils/loaders/LoadEngageHomePage.ts @@ -31,8 +31,7 @@ export function updateEngageHomeMenuActive(isHome: boolean): void { } } -const STORAGE_KEY_STUDENT = () => - `bsplus.engageTimetable.student.${location.origin}`; +const STORAGE_KEY_STUDENT = () => `bsplus.engageTimetable.student.${location.origin}`; let engageViewDate = new Date(); let engageWeekFrom = ""; @@ -47,10 +46,7 @@ function setEngageTimetableSubtitle(): void { el.textContent = lessonsSubtitleForViewDate(engageViewDate); } -function makeEngageLessonDiv( - lesson: EngageParentTimetableItem, - index: number, -): HTMLElement { +function makeEngageLessonDiv(lesson: EngageParentTimetableItem, index: number): HTMLElement { let from = lesson.from?.substring(0, 5) ?? ""; let until = lesson.until?.substring(0, 5) ?? ""; if (settingsState.timeFormat === "12") { @@ -58,10 +54,7 @@ function makeEngageLessonDiv( until = convertTo12HourFormat(until); } - const title = - lesson.type === "class" - ? lesson.description - : lesson.type || "Lesson"; + const title = lesson.type === "class" ? lesson.description : lesson.type || "Lesson"; const div = document.createElement("div"); div.className = "day"; @@ -123,11 +116,7 @@ async function fetchWeekAndRender(): Promise { const { from, until } = weekRangeContaining(engageViewDate); try { - engageWeekItems = await fetchEngageParentTimetableWeek( - from, - until, - engageSelectedStudentId, - ); + engageWeekItems = await fetchEngageParentTimetableWeek(from, until, engageSelectedStudentId); engageWeekFrom = from; engageWeekUntil = until; } catch (e) { @@ -147,7 +136,7 @@ function shiftEngageDay(delta: number): void { const dayContainer = document.getElementById("engage-day-container"); dayContainer?.classList.add("loading"); - dayContainer && (dayContainer.innerHTML = ""); + if (dayContainer) dayContainer.innerHTML = ""; if ( engageWeekFrom && @@ -160,10 +149,7 @@ function shiftEngageDay(delta: number): void { } } -function populateChildSelector( - select: HTMLSelectElement, - children: EngageParentChild[], -): void { +function populateChildSelector(select: HTMLSelectElement, children: EngageParentChild[]): void { select.innerHTML = ""; for (const c of children) { const opt = document.createElement("option"); @@ -174,9 +160,7 @@ function populateChildSelector( const stored = localStorage.getItem(STORAGE_KEY_STUDENT()); const validStored = stored && children.some((c) => c.id === stored); - engageSelectedStudentId = validStored - ? stored! - : children[0]?.id ?? null; + engageSelectedStudentId = validStored ? stored! : (children[0]?.id ?? null); if (engageSelectedStudentId) { select.value = engageSelectedStudentId; @@ -190,9 +174,7 @@ function bindEngageTimetableUi(): void { const back = document.getElementById("engage-home-timetable-back"); const forward = document.getElementById("engage-home-timetable-forward"); - const select = document.getElementById( - "engage-child-selector", - ) as HTMLSelectElement | null; + const select = document.getElementById("engage-child-selector") as HTMLSelectElement | null; const onBack = () => shiftEngageDay(-1); const onForward = () => shiftEngageDay(1); @@ -211,9 +193,7 @@ function bindEngageTimetableUi(): void { void fetchWeekAndRender(); }; select?.addEventListener("change", onSelectChange); - cleanups.push(() => - select?.removeEventListener("change", onSelectChange), - ); + cleanups.push(() => select?.removeEventListener("change", onSelectChange)); engageListenersCleanup = () => { cleanups.forEach((fn) => fn()); @@ -297,9 +277,7 @@ export async function loadEngageHomePage(): Promise { /* Engage mounts `#main` after React hydrates; a single rAF often loses the race on cold load. */ main = (await waitForElm("#main", true, 100, 200)) as HTMLElement; } catch { - console.warn( - "[BetterSEQTA+] Engage home: timed out waiting for #main (shell not ready).", - ); + console.warn("[BetterSEQTA+] Engage home: timed out waiting for #main (shell not ready)."); return; } @@ -355,9 +333,7 @@ export async function loadEngageHomePage(): Promise { setEngageTimetableSubtitle(); renderShortcuts(); - const select = document.getElementById( - "engage-child-selector", - ) as HTMLSelectElement | null; + const select = document.getElementById("engage-child-selector") as HTMLSelectElement | null; const todayFormatted = toISODate(new Date()); diff --git a/src/seqta/utils/loaders/LoadHomePage.ts b/src/seqta/utils/loaders/LoadHomePage.ts index 805a2fc0..021ca67e 100644 --- a/src/seqta/utils/loaders/LoadHomePage.ts +++ b/src/seqta/utils/loaders/LoadHomePage.ts @@ -60,9 +60,7 @@ export async function loadHomePage() { if (!main) return; main.innerHTML = ""; - main.appendChild( - stringToHTML(`
`).firstChild!, - ); + main.appendChild(stringToHTML(`
`).firstChild!); const homeContainer = document.getElementById("home-root"); if (!homeContainer) return; @@ -146,10 +144,9 @@ export async function loadHomePage() { callHomeTimetable(TodayFormatted, true); const activeSubjects = activeSubjectsFromLearnPayload(classes); - const currentAssessments = filterAssessmentsForActiveSubjects( - assessments, - activeSubjects, - ).sort(comparedate); + const currentAssessments = filterAssessmentsForActiveSubjects(assessments, activeSubjects).sort( + comparedate, + ); const upcomingItems = document.getElementById("upcoming-items"); if (upcomingItems) { @@ -197,16 +194,12 @@ async function renderHomeUpcomingAssessments() { const filterContainer = document.getElementById("upcoming-filters"); if (filterContainer) filterContainer.innerHTML = ""; - const [assessments, classes] = await Promise.all([ - GetUpcomingAssessments(), - GetActiveClasses(), - ]); + const [assessments, classes] = await Promise.all([GetUpcomingAssessments(), GetActiveClasses()]); const activeSubjects = activeSubjectsFromLearnPayload(classes); - const currentAssessments = filterAssessmentsForActiveSubjects( - assessments, - activeSubjects, - ).sort(comparedate); + const currentAssessments = filterAssessmentsForActiveSubjects(assessments, activeSubjects).sort( + comparedate, + ); await CreateUpcomingSection(currentAssessments, activeSubjects); upcomingItems.classList.remove("loading"); @@ -286,14 +279,11 @@ function formatDate(date: Date): string { async function GetActiveClasses() { try { - const response = await fetch( - `${location.origin}/seqta/student/load/subjects?`, - { - method: "POST", - headers: { "Content-Type": "application/json; charset=utf-8" }, - body: JSON.stringify({}), - }, - ); + const response = await fetch(`${location.origin}/seqta/student/load/subjects?`, { + method: "POST", + headers: { "Content-Type": "application/json; charset=utf-8" }, + body: JSON.stringify({}), + }); return (await response.json()).payload; } catch (error) { console.error("[BetterSEQTA+] Failed to get active classes:", error); @@ -329,8 +319,8 @@ async function callHomeTimetable(date: string, change?: any) { if (serverResponse.payload.items.length > 0) { if (DayContainer.innerText || change) { - const lessonArray: Array = [...serverResponse.payload.items].sort( - (a, b) => a.from.localeCompare(b.from), + const lessonArray: Array = [...serverResponse.payload.items].sort((a, b) => + a.from.localeCompare(b.from), ); GetLessonColours().then((colours) => { @@ -339,9 +329,7 @@ async function callHomeTimetable(date: string, change?: any) { lessonArray[i].type == "tutorial" ? `timetable.tutor.${lessonArray[i].tutorID}` : `timetable.subject.colour.${lessonArray[i].code}`; - let subject = colours.find( - (element: any) => element.name === subjectname, - ); + let subject = colours.find((element: any) => element.name === subjectname); if (!subject) { lessonArray[i].colour = "--item-colour: #8e8e8e;"; @@ -357,14 +345,10 @@ async function callHomeTimetable(date: string, change?: any) { if (settingsState.timeFormat === "12") { lessonArray[i].from = convertTo12HourFormat(lessonArray[i].from); - lessonArray[i].until = convertTo12HourFormat( - lessonArray[i].until, - ); + lessonArray[i].until = convertTo12HourFormat(lessonArray[i].until); } - lessonArray[i].attendanceTitle = CheckUnmarkedAttendance( - lessonArray[i].attendance, - ); + lessonArray[i].attendanceTitle = CheckUnmarkedAttendance(lessonArray[i].attendance); } DayContainer.innerText = ""; @@ -411,14 +395,7 @@ function CheckCurrentLessonAll(lessons: any) { } async function CheckCurrentLesson(lesson: any, num: number) { - const { - from: startTime, - until: endTime, - code, - description, - room, - staff, - } = lesson; + const { from: startTime, until: endTime, code, description, room, staff } = lesson; const currentDate = new Date(); const [startHour, startMinute] = startTime.split(":").map(Number); @@ -441,8 +418,7 @@ async function CheckCurrentLesson(lesson: any, num: number) { } const isCurrentDate = - currentSelectedDate.toLocaleDateString("en-au") === - currentDate.toLocaleDateString("en-au"); + currentSelectedDate.toLocaleDateString("en-au") === currentDate.toLocaleDateString("en-au"); if (isCurrentDate) { if (isValidTime) { @@ -452,19 +428,11 @@ async function CheckCurrentLesson(lesson: any, num: number) { } } - const minutesUntilStart = Math.floor( - (startDate.getTime() - currentDate.getTime()) / 60000, - ); + const minutesUntilStart = Math.floor((startDate.getTime() - currentDate.getTime()) / 60000); - if ( - minutesUntilStart !== 5 || - settingsState.lessonalert || - !window.Notification - ) - return; + if (minutesUntilStart !== 5 || settingsState.lessonalert || !window.Notification) return; - if (Notification.permission !== "granted") - await Notification.requestPermission(); + if (Notification.permission !== "granted") await Notification.requestPermission(); try { new Notification("Next Lesson in 5 Minutes:", { @@ -571,19 +539,15 @@ function applyHomeUpcomingLimits(assessments: any[], activeSubjects: any[]) { } for (const items of bySubject.values()) { - items.sort( - (a, b) => new Date(a.due).getTime() - new Date(b.due).getTime(), - ); + items.sort((a, b) => new Date(a.due).getTime() - new Date(b.due).getTime()); } subjectOrder.sort( (a, b) => - new Date(bySubject.get(a)![0].due).getTime() - - new Date(bySubject.get(b)![0].due).getTime(), + new Date(bySubject.get(a)![0].due).getTime() - new Date(bySubject.get(b)![0].due).getTime(), ); - const subjectLimit = - maxSubjects > 0 ? maxSubjects : subjectOrder.length; + const subjectLimit = maxSubjects > 0 ? maxSubjects : subjectOrder.length; const allowedSubjects = subjectOrder.slice(0, subjectLimit); const limited: any[] = []; @@ -593,9 +557,7 @@ function applyHomeUpcomingLimits(assessments: any[], activeSubjects: any[]) { limited.push(...items.slice(0, perSubjectLimit)); } - limited.sort( - (a, b) => new Date(a.due).getTime() - new Date(b.due).getTime(), - ); + limited.sort((a, b) => new Date(a.due).getTime() - new Date(b.due).getTime()); assessments.splice(0, assessments.length, ...limited); } @@ -622,8 +584,7 @@ async function CreateUpcomingSection(assessments: any, activeSubjects: any) { for (let i = 0; i < assessments.length; i++) { const subject = colours.find( - (element: any) => - element.name === `timetable.subject.colour.${assessments[i].code}`, + (element: any) => element.name === `timetable.subject.colour.${assessments[i].code}`, ); if (!subject) { assessments[i].colour = "--item-colour: #8e8e8e;"; @@ -650,11 +611,9 @@ async function CreateUpcomingSection(assessments: any, activeSubjects: any) { div: CreateElement("div", "upcoming-date-container"), assessments: [], }; - (upcomingDates[element.due as keyof typeof upcomingDates] as any) = - dateObj; + (upcomingDates[element.due as keyof typeof upcomingDates] as any) = dateObj; } - const assessmentDateDiv = - upcomingDates[element.due as keyof typeof upcomingDates]; + const assessmentDateDiv = upcomingDates[element.due as keyof typeof upcomingDates]; if (assessmentDateDiv) { (assessmentDateDiv as any).assessments.push(element); } @@ -662,8 +621,7 @@ async function CreateUpcomingSection(assessments: any, activeSubjects: any) { for (const date in upcomingDates) { const assessmentdue = new Date( - (upcomingDates[date as keyof typeof upcomingDates] as any).assessments[0] - .due, + (upcomingDates[date as keyof typeof upcomingDates] as any).assessments[0].due, ); const specialcase = CheckSpecialDay(Today, assessmentdue); const assessmentDate = createAssessmentDateDiv( @@ -674,10 +632,7 @@ async function CreateUpcomingSection(assessments: any, activeSubjects: any) { ); if (specialcase === "Yesterday") { - upcomingitemcontainer!.insertBefore( - assessmentDate, - upcomingitemcontainer!.firstChild, - ); + upcomingitemcontainer!.insertBefore(assessmentDate, upcomingitemcontainer!.firstChild); } else { upcomingitemcontainer!.append(assessmentDate); } @@ -694,10 +649,10 @@ async function CreateUpcomingSection(assessments: any, activeSubjects: any) { } function createAssessmentDateDiv(date: string, value: any, student: number, datecase?: any) { - const options = { - weekday: "long" as "long", - month: "long" as "long", - day: "numeric" as "numeric", + const options: Intl.DateTimeFormatOptions = { + weekday: "long", + month: "long", + day: "numeric", }; const FormattedDate = new Date(date); const assessments = value.assessments; @@ -837,22 +792,14 @@ function CreateFilters(subjects: { code: string; colour: string }[]) { filteroptions[element.code] = true; } filterdiv!.append( - CreateSubjectFilter( - element.code, - element.colour, - filteroptions[element.code], - ), + CreateSubjectFilter(element.code, element.colour, filteroptions[element.code]), ); } settingsState.subjectfilters = filteroptions; } -function CreateSubjectFilter( - subjectcode: any, - itemcolour: string, - checked: any, -) { +function CreateSubjectFilter(subjectcode: any, itemcolour: string, checked: any) { const label = CreateElement("label", "upcoming-checkbox-container"); label.innerText = subjectcode; const input = CreateElement("input") as HTMLInputElement; diff --git a/src/seqta/utils/loaders/engageParentTimetable.ts b/src/seqta/utils/loaders/engageParentTimetable.ts index 4439e4d0..43ae7ccf 100644 --- a/src/seqta/utils/loaders/engageParentTimetable.ts +++ b/src/seqta/utils/loaders/engageParentTimetable.ts @@ -39,19 +39,11 @@ export function weekRangeContaining(date: Date): { from: string; until: string } return { from: toISODate(monday), until: toISODate(sunday) }; } -function isInWeekRange( - isoDay: string, - weekFrom: string, - weekUntil: string, -): boolean { +function isInWeekRange(isoDay: string, weekFrom: string, weekUntil: string): boolean { return isoDay >= weekFrom && isoDay <= weekUntil; } -export function isDateInCachedWeek( - date: Date, - weekFrom: string, - weekUntil: string, -): boolean { +export function isDateInCachedWeek(date: Date, weekFrom: string, weekUntil: string): boolean { return isInWeekRange(toISODate(date), weekFrom, weekUntil); } diff --git a/src/seqta/utils/loaders/timetableSubtitle.ts b/src/seqta/utils/loaders/timetableSubtitle.ts index 0dfd77c6..6d14e970 100644 --- a/src/seqta/utils/loaders/timetableSubtitle.ts +++ b/src/seqta/utils/loaders/timetableSubtitle.ts @@ -6,8 +6,7 @@ export function formatTimetableDayLabel(date: Date): string { export function lessonsSubtitleForViewDate(viewDate: Date): string { const today = new Date(); const isSameMonth = - today.getFullYear() === viewDate.getFullYear() && - today.getMonth() === viewDate.getMonth(); + today.getFullYear() === viewDate.getFullYear() && today.getMonth() === viewDate.getMonth(); if (isSameMonth) { const dayDiff = today.getDate() - viewDate.getDate(); diff --git a/src/seqta/utils/newsFeed.test.ts b/src/seqta/utils/newsFeed.test.ts index 26303c34..4e1da30c 100644 --- a/src/seqta/utils/newsFeed.test.ts +++ b/src/seqta/utils/newsFeed.test.ts @@ -90,13 +90,27 @@ describe("toNewsArticles", () => { expect( toNewsArticles({ articles: [ - { title: "Good", description: null, url: "https://abc.net.au/a", urlToImage: "https://abc.net.au/a.jpg" }, + { + title: "Good", + description: null, + url: "https://abc.net.au/a", + urlToImage: "https://abc.net.au/a.jpg", + }, { title: "Bad", url: "javascript:alert(1)" }, - { title: "No image", url: "https://abc.net.au/b", urlToImage: "data:image/png;base64,AAAA" }, + { + title: "No image", + url: "https://abc.net.au/b", + urlToImage: "data:image/png;base64,AAAA", + }, ], }), ).toEqual([ - { title: "Good", description: "", url: "https://abc.net.au/a", imageUrl: "https://abc.net.au/a.jpg" }, + { + title: "Good", + description: "", + url: "https://abc.net.au/a", + imageUrl: "https://abc.net.au/a.jpg", + }, { title: "No image", description: "", url: "https://abc.net.au/b", imageUrl: null }, ]); }); diff --git a/src/seqta/utils/newsFeed.ts b/src/seqta/utils/newsFeed.ts index 208f3f66..76613de6 100644 --- a/src/seqta/utils/newsFeed.ts +++ b/src/seqta/utils/newsFeed.ts @@ -32,7 +32,10 @@ function htmlToText(html: string): string { } function firstImageInHtml(html: string): string | null { - return new DOMParser().parseFromString(html, "text/html").querySelector("img")?.getAttribute("src") ?? null; + return ( + new DOMParser().parseFromString(html, "text/html").querySelector("img")?.getAttribute("src") ?? + null + ); } function children(el: Element, name: string): Element[] { @@ -50,16 +53,29 @@ function childText(el: Element, ...names: string[]): string { function itemLink(item: Element): string { const links = children(item, "link"); const alternate = links.find((link) => (link.getAttribute("rel") ?? "alternate") === "alternate"); - return alternate?.getAttribute("href") || alternate?.textContent?.trim() || childText(item, "guid", "id"); + return ( + alternate?.getAttribute("href") || + alternate?.textContent?.trim() || + childText(item, "guid", "id") + ); } function itemImage(item: Element, descriptionHtml: string): string | null { - const media = [...item.getElementsByTagNameNS("*", "thumbnail"), ...item.getElementsByTagNameNS("*", "content")] + const media = [ + ...item.getElementsByTagNameNS("*", "thumbnail"), + ...item.getElementsByTagNameNS("*", "content"), + ] .filter((el) => el.namespaceURI?.includes("mrss")) - .find((el) => el.getAttribute("url") && (!el.getAttribute("medium") || el.getAttribute("medium") === "image")); + .find( + (el) => + el.getAttribute("url") && + (!el.getAttribute("medium") || el.getAttribute("medium") === "image"), + ); if (media) return media.getAttribute("url"); - const enclosure = children(item, "enclosure").find((el) => el.getAttribute("type")?.startsWith("image/")); + const enclosure = children(item, "enclosure").find((el) => + el.getAttribute("type")?.startsWith("image/"), + ); if (enclosure) return enclosure.getAttribute("url"); return descriptionHtml ? firstImageInHtml(descriptionHtml) : null; diff --git a/src/seqta/utils/notices/noticeHomeUi.ts b/src/seqta/utils/notices/noticeHomeUi.ts index 5d471551..3ae256e9 100644 --- a/src/seqta/utils/notices/noticeHomeUi.ts +++ b/src/seqta/utils/notices/noticeHomeUi.ts @@ -170,12 +170,14 @@ export function openNoticeModal( sourceElement.style.opacity = "0"; sourceElement.style.transform = "scale(0.95)"; - const initialWidth = Math.round( - Math.min(Math.max(sourceWidth, 800), window.innerWidth - 40), - ); + const initialWidth = Math.round(Math.min(Math.max(sourceWidth, 800), window.innerWidth - 40)); const measuredHeight = measureNoticeHeight(notice, cleanContent, initialWidth); - let { width: targetWidth, height: targetHeight, left: targetLeft, top: targetTop } = - modalTargetSize(sourceWidth, measuredHeight); + let { + width: targetWidth, + height: targetHeight, + left: targetLeft, + top: targetTop, + } = modalTargetSize(sourceWidth, measuredHeight); const applyTargetLayout = () => { transitionContainer.style.left = `${Math.round(targetLeft + scrollX)}px`; @@ -206,12 +208,16 @@ export function openNoticeModal( animate(transitionContainer, { opacity: [1, 0] }, { duration: 0.2, delay: 0.3 }); showSourceElement(sourceElement); modal.style.pointerEvents = "none"; - animate(transitionContainer, { - left: [targetLeft + scrollX, sourceLeft + scrollX], - top: [targetTop, sourceTop + scrollY], - width: [targetWidth, sourceWidth], - height: [targetHeight, sourceHeight], - }, SPRING_CLOSE).finished.then(() => { + animate( + transitionContainer, + { + left: [targetLeft + scrollX, sourceLeft + scrollX], + top: [targetTop, sourceTop + scrollY], + width: [targetWidth, sourceWidth], + height: [targetHeight, sourceHeight], + }, + SPRING_CLOSE, + ).finished.then(() => { modal.remove(); sourceElement.removeAttribute("data-transitioning"); }); @@ -237,10 +243,7 @@ export function openNoticeModal( sourceLeft = rect.left - (sourceWidth - rect.width) / 2; sourceTop = rect.top - (sourceHeight - rect.height) / 2; - const next = modalTargetSize( - sourceWidth, - unifiedContent.getBoundingClientRect().height, - ); + const next = modalTargetSize(sourceWidth, unifiedContent.getBoundingClientRect().height); targetLeft = next.left; targetTop = next.top; targetWidth = next.width; @@ -253,12 +256,16 @@ export function openNoticeModal( unifiedContent.classList.replace("notice-card-state", "notice-modal-state"); if (settingsState.animations) { animate(modal, { opacity: [0, 1] }, { duration: 0.2 }); - animate(transitionContainer, { - left: [sourceLeft + scrollX, targetLeft + scrollX], - top: [sourceTop + scrollY, targetTop], - width: [sourceWidth, targetWidth], - height: [sourceHeight, targetHeight], - }, SPRING_OPEN); + animate( + transitionContainer, + { + left: [sourceLeft + scrollX, targetLeft + scrollX], + top: [sourceTop + scrollY, targetTop], + width: [sourceWidth, targetWidth], + height: [sourceHeight, targetHeight], + }, + SPRING_OPEN, + ); } else { modal.style.opacity = "1"; applyTargetLayout(); @@ -285,10 +292,7 @@ export function renderNoticesIntoContainer( const fragment = document.createDocumentFragment(); for (const notice of notices) { - if ( - settingsState.mockNotices || - noticeMatchesLabelFilter(notice, labelTokens) - ) { + if (settingsState.mockNotices || noticeMatchesLabelFilter(notice, labelTokens)) { fragment.appendChild(createNoticeElement(notice, processNoticeColor(notice.colour))); } } diff --git a/src/seqta/utils/notices/noticeLabelFilters.ts b/src/seqta/utils/notices/noticeLabelFilters.ts index 447a611f..be12195f 100644 --- a/src/seqta/utils/notices/noticeLabelFilters.ts +++ b/src/seqta/utils/notices/noticeLabelFilters.ts @@ -43,8 +43,7 @@ export async function resolveNoticeFilterTokens( export function normalizeNoticeLabelId(label: unknown): string | null { if (typeof label === "number" && !Number.isNaN(label)) return String(label); if (typeof label === "string" && label.trim()) return label.trim(); - const id = - label && typeof label === "object" ? (label as { id?: unknown }).id : undefined; + const id = label && typeof label === "object" ? (label as { id?: unknown }).id : undefined; if (typeof id === "number" && !Number.isNaN(id)) return String(id); if (typeof id === "string" && id.trim()) return id.trim(); return null; @@ -56,6 +55,8 @@ export function noticeMatchesLabelFilter( ): boolean { if (filterTokens.length === 0) return true; const id = normalizeNoticeLabelId(notice?.label); - return (id !== null && filterTokens.includes(id)) || - filterTokens.includes(JSON.stringify(notice?.label)); + return ( + (id !== null && filterTokens.includes(id)) || + filterTokens.includes(JSON.stringify(notice?.label)) + ); } diff --git a/src/seqta/utils/openThemeStoreWithHighlight.ts b/src/seqta/utils/openThemeStoreWithHighlight.ts index 00b343a4..d626eb14 100644 --- a/src/seqta/utils/openThemeStoreWithHighlight.ts +++ b/src/seqta/utils/openThemeStoreWithHighlight.ts @@ -13,7 +13,5 @@ export async function openThemeStoreWithHighlight(themeId: string): Promise { it("does not show again after the user has seen it", () => { expect( - shouldShowCoursesAssessmentsFixPopup( - { - onoff: false, - coursesAssessmentsFixPopupShown: true, - }, - ), + shouldShowCoursesAssessmentsFixPopup({ + onoff: false, + coursesAssessmentsFixPopupShown: true, + }), ).toBe(false); }); }); @@ -77,8 +75,6 @@ describe("reEnableBetterSeqtaFeatures", () => { coursesAssessmentsFixPopupShown: true, }); expect(reload).toHaveBeenCalledTimes(1); - expect(persist.mock.invocationCallOrder[0]).toBeLessThan( - reload.mock.invocationCallOrder[0], - ); + expect(persist.mock.invocationCallOrder[0]).toBeLessThan(reload.mock.invocationCallOrder[0]); }); }); diff --git a/src/seqta/utils/openers/OpenCoursesAssessmentsFixPopup.ts b/src/seqta/utils/openers/OpenCoursesAssessmentsFixPopup.ts index 55499045..aab6363f 100644 --- a/src/seqta/utils/openers/OpenCoursesAssessmentsFixPopup.ts +++ b/src/seqta/utils/openers/OpenCoursesAssessmentsFixPopup.ts @@ -35,9 +35,7 @@ export async function reEnableBetterSeqtaFeatures(options?: { reload?: () => void; }): Promise { const state = options?.state ?? settingsState; - const persist = - options?.persist ?? - ((patch) => browser.storage.local.set(patch)); + const persist = options?.persist ?? ((patch) => browser.storage.local.set(patch)); const reload = options?.reload ?? (() => location.reload()); markCoursesAssessmentsFixPopupSeen(state); @@ -223,20 +221,14 @@ function setPopupButtonsDisabled(disabled: boolean) { const reenable = document.getElementById( "bsplus-courses-fix-reenable", ) as HTMLButtonElement | null; - const later = document.getElementById( - "bsplus-courses-fix-later", - ) as HTMLButtonElement | null; - const dismiss = document.getElementById( - "bsplus-courses-fix-dismiss", - ) as HTMLButtonElement | null; + const later = document.getElementById("bsplus-courses-fix-later") as HTMLButtonElement | null; + const dismiss = document.getElementById("bsplus-courses-fix-dismiss") as HTMLButtonElement | null; if (reenable) reenable.disabled = disabled; if (later) later.disabled = disabled; if (dismiss) dismiss.disabled = disabled; } -export function OpenCoursesAssessmentsFixPopup( - onDismissed?: () => void, -) { +export function OpenCoursesAssessmentsFixPopup(onDismissed?: () => void) { if (document.getElementById("whatsnewbk")) { onDismissed?.(); return; @@ -250,8 +242,7 @@ export function OpenCoursesAssessmentsFixPopup( const offerReEnable = shouldOfferCoursesAssessmentsReEnable(); const isDark = - settingsState.DarkMode === true || - document.documentElement.classList.contains("dark"); + settingsState.DarkMode === true || document.documentElement.classList.contains("dark"); const header = stringToHTML(/* html */ `
diff --git a/src/seqta/utils/openers/OpenMenuOptions.ts b/src/seqta/utils/openers/OpenMenuOptions.ts index 088d4c9f..77125414 100644 --- a/src/seqta/utils/openers/OpenMenuOptions.ts +++ b/src/seqta/utils/openers/OpenMenuOptions.ts @@ -2,10 +2,7 @@ import type { SettingsState } from "@/types/storage"; import { settingsState } from "../listeners/SettingsState"; import { applyMenuItemVisibility } from "../menuItemVisibility"; import { ensureAnalyticsMenuOrder } from "@/seqta/utils/openers/analyticsMenuOrder"; -import { - isMenuOptionsOpen, - setMenuOptionsOpen, -} from "@/seqta/utils/openers/menuOptionsState"; +import { isMenuOptionsOpen, setMenuOptionsOpen } from "@/seqta/utils/openers/menuOptionsState"; import { ChangeMenuItemPositions } from "@/seqta/utils/openers/menuOrder"; import stringToHTML from "../stringToHTML"; import Sortable from "sortablejs"; @@ -42,9 +39,7 @@ function syncDefaultMenuOrder(menu: HTMLElement) { ensureAnalyticsMenuOrder(); } -function mergeMenuItemsFromDom( - menu: HTMLElement, -): Record { +function mergeMenuItemsFromDom(menu: HTMLElement): Record { const merged = { ...(settingsState.menuitems as Record), }; @@ -113,22 +108,15 @@ function prepareMenuItemsForEdit(menu: HTMLElement) { } function syncMenuItemSettings(menu: HTMLElement) { - settingsState.menuitems = mergeMenuItemsFromDom( - menu, - ) as SettingsState["menuitems"]; + settingsState.menuitems = mergeMenuItemsFromDom(menu) as SettingsState["menuitems"]; } function applySavedMenuToggleStates() { - const menuItems = settingsState.menuitems as Record< - string, - { toggle: boolean } - >; + const menuItems = settingsState.menuitems as Record; const buttons = document.getElementsByClassName("menuitem"); for (let i = 0; i < buttons.length; i++) { const id = buttons[i].id; - (buttons[i] as HTMLInputElement).checked = id - ? (menuItems[id]?.toggle ?? true) - : true; + (buttons[i] as HTMLInputElement).checked = id ? (menuItems[id]?.toggle ?? true) : true; } } @@ -173,10 +161,7 @@ function storeMenuSettings() { settingsState.menuitems = menuItems as SettingsState["menuitems"]; } -function restoreMenuItemsFromEditMode( - menu: HTMLElement, - listItems: NodeListOf, -) { +function restoreMenuItemsFromEditMode(menu: HTMLElement, listItems: NodeListOf) { for (let i = 0; i < listItems.length; i++) { const element = listItems[i] as HTMLElement; element.classList.remove("draggable"); @@ -205,8 +190,10 @@ export function OpenMenuOptions() { setMenuOptionsOpen(true); menu.classList.add("bsplus-sidebar-edit-mode"); - const { cover, menusettings, defaultbutton, savebutton } = - createMenuEditControls(menu, container); + const { cover, menusettings, defaultbutton, savebutton } = createMenuEditControls( + menu, + container, + ); const listItems = prepareMenuItemsForEdit(menu); syncMenuItemSettings(menu); applySavedMenuToggleStates(); diff --git a/src/seqta/utils/openers/OpenTermsOfServicePopup.test.ts b/src/seqta/utils/openers/OpenTermsOfServicePopup.test.ts index 604b4207..87d95546 100644 --- a/src/seqta/utils/openers/OpenTermsOfServicePopup.test.ts +++ b/src/seqta/utils/openers/OpenTermsOfServicePopup.test.ts @@ -13,7 +13,7 @@ import { const SAMPLE_TERMS = { last_updated: "2024-06-15T12:00:00Z", - whatsnew_html: "

Terms body

", + whatsnew_html: '

Terms body

', }; describe("shouldShowTermsOfServicePopup", () => { diff --git a/src/seqta/utils/openers/OpenTermsOfServicePopup.ts b/src/seqta/utils/openers/OpenTermsOfServicePopup.ts index a5bb5492..d48755b6 100644 --- a/src/seqta/utils/openers/OpenTermsOfServicePopup.ts +++ b/src/seqta/utils/openers/OpenTermsOfServicePopup.ts @@ -47,11 +47,7 @@ export async function fetchTermsOfService(): Promise { } } - -function termsVersionIsNewer( - remoteLastUpdated: string, - acceptedLastUpdated?: string, -): boolean { +function termsVersionIsNewer(remoteLastUpdated: string, acceptedLastUpdated?: string): boolean { if (!acceptedLastUpdated) return true; const remote = Date.parse(remoteLastUpdated); const accepted = Date.parse(acceptedLastUpdated); @@ -64,9 +60,7 @@ function termsVersionIsNewer( function resolvedTermsAcceptance( state: Pick< SettingsState, - | "termsOfServiceLastAccepted" - | "privacyStatementShown" - | "privacyStatementLastUpdated" + "termsOfServiceLastAccepted" | "privacyStatementShown" | "privacyStatementLastUpdated" >, ): string | undefined { if (state.termsOfServiceLastAccepted) return state.termsOfServiceLastAccepted; @@ -79,9 +73,7 @@ function resolvedTermsAcceptance( export function shouldShowTermsOfServicePopup( state: Pick< SettingsState, - | "termsOfServiceLastAccepted" - | "privacyStatementShown" - | "privacyStatementLastUpdated" + "termsOfServiceLastAccepted" | "privacyStatementShown" | "privacyStatementLastUpdated" >, terms: LegalDocumentPayload, ): boolean { diff --git a/src/seqta/utils/openers/OpenThemeOfTheMonthPopup.test.ts b/src/seqta/utils/openers/OpenThemeOfTheMonthPopup.test.ts index ea8e9883..f9dcf019 100644 --- a/src/seqta/utils/openers/OpenThemeOfTheMonthPopup.test.ts +++ b/src/seqta/utils/openers/OpenThemeOfTheMonthPopup.test.ts @@ -29,9 +29,7 @@ beforeEach(() => { }); afterEach(() => { - document - .querySelector(".themeOfTheMonthCardSecondary") - ?.click(); + document.querySelector(".themeOfTheMonthCardSecondary")?.click(); jest.runOnlyPendingTimers(); jest.useRealTimers(); }); @@ -41,10 +39,7 @@ it.each([false, true])( async (expanded) => { const onDismissed = jest.fn(); await OpenThemeOfTheMonthPopup(entry, onDismissed); - if (expanded) - document - .querySelector(".themeOfTheMonthCardPopout")! - .click(); + if (expanded) document.querySelector(".themeOfTheMonthCardPopout")!.click(); const outside = expanded ? document.getElementById("theme-of-the-month-backdrop")! : document.body; @@ -61,9 +56,7 @@ it.each([false, true])( it("keeps the card open while interacting with it and its fullscreen preview", async () => { await OpenThemeOfTheMonthPopup(entry); document.querySelector(".themeOfTheMonthCardBody")!.click(); - document - .querySelector(".themeOfTheMonthCardImage")! - .click(); + document.querySelector(".themeOfTheMonthCardImage")!.click(); const overlay = document.getElementById("bsplus-popup-media-overlay")!; expect(overlay).not.toBeNull(); overlay.querySelector("img")!.click(); @@ -80,10 +73,7 @@ it("ignores the opening click and cleans up an existing card when replaced", asy const opener = document.createElement("button"); document.body.append(opener); const oldDismissed = jest.fn(); - opener.addEventListener( - "click", - () => void OpenThemeOfTheMonthPopup(entry, oldDismissed), - ); + opener.addEventListener("click", () => void OpenThemeOfTheMonthPopup(entry, oldDismissed)); opener.click(); expect(document.getElementById("theme-of-the-month-card")).not.toBeNull(); const newDismissed = jest.fn(); diff --git a/src/seqta/utils/openers/OpenThemeOfTheMonthPopup.ts b/src/seqta/utils/openers/OpenThemeOfTheMonthPopup.ts index a55ce907..27daedf6 100644 --- a/src/seqta/utils/openers/OpenThemeOfTheMonthPopup.ts +++ b/src/seqta/utils/openers/OpenThemeOfTheMonthPopup.ts @@ -6,10 +6,7 @@ import { getApiBase } from "../DevApiBase"; import { withBsplusApiQuery } from "../bsplusClientContext"; import { openThemeStoreWithHighlight } from "../openThemeStoreWithHighlight"; import type { Theme } from "@/interface/types/Theme"; -import { - buildModalHeroSlides, - normalizeStoreTheme, -} from "@/interface/utils/themeStoreFlavours"; +import { buildModalHeroSlides, normalizeStoreTheme } from "@/interface/utils/themeStoreFlavours"; import { attachPopupMediaFullscreen } from "./attachPopupMediaFullscreen"; import { allowedPopupImageUrl } from "./allowedPopupImageUrl"; import { delay } from "@/seqta/utils/delay"; @@ -48,9 +45,7 @@ async function readCachedThemeOfTheMonth(): Promise } } -async function writeCachedThemeOfTheMonth( - entry: ThemeOfTheMonthEntry, -): Promise { +async function writeCachedThemeOfTheMonth(entry: ThemeOfTheMonthEntry): Promise { try { await browser.storage.local.set({ [TOTM_CACHE_KEY]: entry }); } catch { @@ -112,11 +107,11 @@ function heroUrlFromStoreTheme(theme: { } export async function fetchThemeStoreTheme(themeId: string): Promise { - try { - const res = (await browser.runtime.sendMessage({ - type: "fetchThemeDetails", - themeId, - })) as { success?: boolean; data?: { theme?: Record } }; + try { + const res = (await browser.runtime.sendMessage({ + type: "fetchThemeDetails", + themeId, + })) as { success?: boolean; data?: { theme?: Record } }; if (!res?.success || !res?.data?.theme) return null; return normalizeStoreTheme(res.data.theme); @@ -158,13 +153,10 @@ function renderHeroEmbossHtml(storeTheme: Theme, entry: ThemeOfTheMonthEntry): s const author = storeTheme.author?.trim() ?? ""; const storeDescription = storeTheme.description?.trim() ?? ""; const entryDesc = entry.description.trim(); - const showDescription = - storeDescription.length > 0 && storeDescription !== entryDesc; + const showDescription = storeDescription.length > 0 && storeDescription !== entryDesc; const flavourCount = storeTheme.flavours?.length ?? 0; const flavourLine = - flavourCount > 0 - ? `${flavourCount} colour variant${flavourCount === 1 ? "" : "s"}` - : ""; + flavourCount > 0 ? `${flavourCount} colour variant${flavourCount === 1 ? "" : "s"}` : ""; if (!name && !author && !showDescription && !flavourLine) return ""; @@ -302,10 +294,7 @@ function computeCardTranslate( ), ); const y = Math.round( - Math.max( - TOTM_MARGIN_PX, - window.innerHeight - cardHeight - TOTM_MARGIN_PX, - ), + Math.max(TOTM_MARGIN_PX, window.innerHeight - cardHeight - TOTM_MARGIN_PX), ); return { x, y }; } @@ -325,9 +314,7 @@ function applyThemeOfTheMonthCardPosition( animate: boolean, targetHeight?: number, ): void { - const width = expanded - ? themeOfTheMonthExpandedWidth() - : themeOfTheMonthCollapsedWidth(); + const width = expanded ? themeOfTheMonthExpandedWidth() : themeOfTheMonthCollapsedWidth(); card.style.width = `${width}px`; card.style.maxHeight = expanded ? `${themeOfTheMonthMaxCardHeight()}px` : ""; @@ -337,9 +324,7 @@ function applyThemeOfTheMonthCardPosition( const { x, y } = computeCardTranslate(width, h, expanded); const canAnimate = - animate && - settingsState.animations && - card.classList.contains("themeOfTheMonthCardMorphReady"); + animate && settingsState.animations && card.classList.contains("themeOfTheMonthCardMorphReady"); if (canAnimate) { card.style.transition = [ @@ -520,10 +505,7 @@ async function runThemeOfTheMonthCollapse( await delay(TOTM_LAYOUT_SWAP_MS); if (gen !== themeOfTheMonthAnimGen) return; - card.classList.remove( - "themeOfTheMonthCardExpanding", - "themeOfTheMonthCardCollapsing", - ); + card.classList.remove("themeOfTheMonthCardExpanding", "themeOfTheMonthCardCollapsing"); card.style.height = `${toH}px`; card.style.overflow = ""; card.style.transition = ""; @@ -690,8 +672,7 @@ export async function OpenThemeOfTheMonthPopup( const hasExpandableContent = gallerySlides.length > 0 || entry.description.trim().length > 0; const descriptionHtml = escapeHTML(entry.description).replace(/\n/g, "
"); - const heroEmbossHtml = - heroUrl && storeTheme ? renderHeroEmbossHtml(storeTheme, entry) : ""; + const heroEmbossHtml = heroUrl && storeTheme ? renderHeroEmbossHtml(storeTheme, entry) : ""; const backdrop = stringToHTML(/* html */ ` @@ -840,12 +821,16 @@ export async function OpenThemeOfTheMonthPopup( requestAnimationFrame(() => confirmEl.classList.add("themeOfTheMonthCardConfirmVisible")); }; - card.querySelector(".themeOfTheMonthCardDontShow")?.addEventListener("click", openDontShowConfirm); + card + .querySelector(".themeOfTheMonthCardDontShow") + ?.addEventListener("click", openDontShowConfirm); card.querySelector(".themeOfTheMonthCardConfirmCancel")?.addEventListener("click", () => { if (!confirmEl) return; confirmEl.classList.remove("themeOfTheMonthCardConfirmVisible"); - window.setTimeout(() => { confirmEl.hidden = true; }, 160); + window.setTimeout(() => { + confirmEl.hidden = true; + }, 160); }); card.querySelector(".themeOfTheMonthCardConfirmAccept")?.addEventListener("click", () => { diff --git a/src/seqta/utils/openers/OpenWhatsNewPopup.ts b/src/seqta/utils/openers/OpenWhatsNewPopup.ts index 35fea0db..77981857 100644 --- a/src/seqta/utils/openers/OpenWhatsNewPopup.ts +++ b/src/seqta/utils/openers/OpenWhatsNewPopup.ts @@ -28,11 +28,7 @@ export function OpenWhatsNewPopup(onDismissed?: () => void) { openPopup({ header, - content: [ - createPopupHeroVideo(UPDATE_VIDEO_URL, "BetterSEQTA+ update preview"), - text, - footer, - ], + content: [createPopupHeroVideo(UPDATE_VIDEO_URL, "BetterSEQTA+ update preview"), text, footer], afterClose: onDismissed, clearJustUpdated: true, }); diff --git a/src/seqta/utils/openers/PopupManager.ts b/src/seqta/utils/openers/PopupManager.ts index de41419f..21ca35f4 100644 --- a/src/seqta/utils/openers/PopupManager.ts +++ b/src/seqta/utils/openers/PopupManager.ts @@ -1,9 +1,6 @@ import { settingsState } from "../listeners/SettingsState"; import { fullMotionEffectsEnabled } from "@/seqta/utils/performanceMode"; -import { - animatePopupClose, - animatePopupOpen, -} from "@/seqta/utils/popupAnimation"; +import { animatePopupClose, animatePopupOpen } from "@/seqta/utils/popupAnimation"; import { animate as motionAnimate, stagger } from "motion"; type AnimationTarget = string | Element | Element[] | NodeList | null; @@ -49,9 +46,7 @@ export async function closePopup() { detachEscapeListener(); const background = document.getElementById("whatsnewbk"); - const popup = document.getElementsByClassName("whatsnewContainer")[0] as - | HTMLElement - | undefined; + const popup = document.getElementsByClassName("whatsnewContainer")[0] as HTMLElement | undefined; if (!background || !popup) { isClosing = false; diff --git a/src/seqta/utils/openers/allowedPopupImageUrl.ts b/src/seqta/utils/openers/allowedPopupImageUrl.ts index d11e6850..c29e9fba 100644 --- a/src/seqta/utils/openers/allowedPopupImageUrl.ts +++ b/src/seqta/utils/openers/allowedPopupImageUrl.ts @@ -10,14 +10,9 @@ export function allowedPopupImageUrl(url: string | null | undefined): string | n const parsed = new URL(trimmed); if (parsed.protocol === "https:") return parsed.href; - if ( - parsed.protocol === "chrome-extension:" || - parsed.protocol === "moz-extension:" - ) { + if (parsed.protocol === "chrome-extension:" || parsed.protocol === "moz-extension:") { const extId = - typeof chrome !== "undefined" && chrome.runtime?.id - ? chrome.runtime.id - : undefined; + typeof chrome !== "undefined" && chrome.runtime?.id ? chrome.runtime.id : undefined; if (extId && parsed.hostname === extId) return parsed.href; } diff --git a/src/seqta/utils/openers/analyticsMenuOrder.ts b/src/seqta/utils/openers/analyticsMenuOrder.ts index 8ce46f8e..f53c05b8 100644 --- a/src/seqta/utils/openers/analyticsMenuOrder.ts +++ b/src/seqta/utils/openers/analyticsMenuOrder.ts @@ -16,11 +16,7 @@ export function insertMenuItemAfterKey( } } -export function insertKeyAfterInOrder( - order: string[], - key: string, - afterKey: string, -): string[] { +export function insertKeyAfterInOrder(order: string[], key: string, afterKey: string): string[] { if (order.includes(key)) return order; const copy = [...order]; const afterIdx = copy.indexOf(afterKey); diff --git a/src/seqta/utils/openers/attachPopupMediaFullscreen.ts b/src/seqta/utils/openers/attachPopupMediaFullscreen.ts index c8a4080a..b5dac210 100644 --- a/src/seqta/utils/openers/attachPopupMediaFullscreen.ts +++ b/src/seqta/utils/openers/attachPopupMediaFullscreen.ts @@ -160,10 +160,7 @@ function openMediaOverlayViewer(source: HTMLImageElement | HTMLVideoElement) { }); } -export function attachPopupMediaFullscreenIfPresent( - root: ParentNode, - selector: string, -) { +export function attachPopupMediaFullscreenIfPresent(root: ParentNode, selector: string) { const el = root.querySelector(selector); if (el && isImageOrVideo(el)) { attachPopupMediaFullscreen(el); diff --git a/src/seqta/utils/openers/fetchThemeOfTheMonth.test.ts b/src/seqta/utils/openers/fetchThemeOfTheMonth.test.ts index fb0fbe3d..8259c29d 100644 --- a/src/seqta/utils/openers/fetchThemeOfTheMonth.test.ts +++ b/src/seqta/utils/openers/fetchThemeOfTheMonth.test.ts @@ -42,9 +42,7 @@ describe("fetchThemeOfTheMonth", () => { it("falls back to cache when fetch fails or times out", async () => { await browser.storage.local.set({ [CACHE_KEY]: sampleEntry }); - globalThis.fetch = jest - .fn() - .mockRejectedValue(new DOMException("Aborted", "AbortError")); + globalThis.fetch = jest.fn().mockRejectedValue(new DOMException("Aborted", "AbortError")); const entry = await fetchThemeOfTheMonth(); expect(entry?.id).toBe("totm-1"); diff --git a/src/seqta/utils/openers/openRemoteCampaignPopup.ts b/src/seqta/utils/openers/openRemoteCampaignPopup.ts index 141e4831..ce40c25a 100644 --- a/src/seqta/utils/openers/openRemoteCampaignPopup.ts +++ b/src/seqta/utils/openers/openRemoteCampaignPopup.ts @@ -6,10 +6,7 @@ import type { RemoteCampaign } from "@/seqta/utils/remoteConfig/types"; import { requestSettingsDestination } from "@/seqta/utils/settingsNavigation"; import { openSettingsPopup } from "@/seqta/utils/setupSettingsButton"; -export function openRemoteCampaignPopup( - campaign: RemoteCampaign, - onDismissed?: () => void, -): void { +export function openRemoteCampaignPopup(campaign: RemoteCampaign, onDismissed?: () => void): void { const title = campaign.header?.title ?? "BetterSEQTA+"; const subtitle = campaign.header?.subtitle ?? ""; let acknowledged = false; @@ -78,10 +75,7 @@ export function openRemoteCampaignPopup( animateSelector: ".whatsnewImgContainer, .whatsnewTextContainer *", actions, afterClose: () => { - void markCampaignSeen( - campaign.id, - campaign.requireAcknowledge ? acknowledged : undefined, - ); + void markCampaignSeen(campaign.id, campaign.requireAcknowledge ? acknowledged : undefined); onDismissed?.(); }, }); diff --git a/src/seqta/utils/openers/whatsNewChangelog.ts b/src/seqta/utils/openers/whatsNewChangelog.ts index 1ec3107d..c8931051 100644 --- a/src/seqta/utils/openers/whatsNewChangelog.ts +++ b/src/seqta/utils/openers/whatsNewChangelog.ts @@ -5,26 +5,28 @@ export type WhatsNewRelease = { export const WHATS_NEW_CHANGELOG: WhatsNewRelease[] = [ { - "title": "3.7.6 - Timetable Sharing Fixes, Better Update resilience & Community Theme Submitter Badges,", - "items": [ + title: + "3.7.6 - Timetable Sharing Fixes, Better Update resilience & Community Theme Submitter Badges,", + items: [ "Improved releiability of opening the connection for Timetable Sharing.", "Added a new submitter badge for community theme submitters.", "Added ability for Admin's to view unreleased community themes for QA.", "Added ability for BetterSEQTA+ features to be dynamically configured remotly to negate compatability issues.", "Added ability to set BetterSEQTA Cloud Profile Picture from Extension Settings.", - ] + ], }, { - "title": "3.7.5 - Timetable Sharing Fixes", - "items": [ + title: "3.7.5 - Timetable Sharing Fixes", + items: [ "Fixed the Sync with Friends button disappearing when classmate avatars fail to load.", "Sharing and sync controls now pause during BetterSEQTA Cloud outages and recover automatically.", - "Timetable sync failures now show an error." - ] + "Timetable sync failures now show an error.", + ], }, { - "title": "3.7.4 - Performance Mode, Timetable syncing with Friends and Calendars, Sidebar Customisation, new loading animations & Bugfix Bundle", - "items": [ + title: + "3.7.4 - Performance Mode, Timetable syncing with Friends and Calendars, Sidebar Customisation, new loading animations & Bugfix Bundle", + items: [ "Added Performance Mode in General settings dramatically improving performance with little sacrifice to looks.", "Added the ability to sync your timetable with your friends and calendars.", "Fixed custom background images and videos not uploading.", @@ -66,23 +68,24 @@ export const WHATS_NEW_CHANGELOG: WhatsNewRelease[] = [ "Added verbose logging toggle under Developer settings.", "Restored theme settings Edit/Done label and improved custom Select keyboard accessibility.", "Cloud sign-in now sends a device name for account management.", - "Added TOS popup" - ] + "Added TOS popup", + ], }, { - "title": "3.7.2 - Analytics Fixes", - "items": [ + title: "3.7.2 - Analytics Fixes", + items: [ "Fixed analytics page breaking on certain configurations.", "Added safer DOM handling for analytics to prevent crashes.", "Fixed hovering tooltip for forecast analytics chart.", "Improved grade analytics layout, controls, and forecast chart rendering.", - "Updated update image for new layout." - ] + "Updated update image for new layout.", + ], }, { - "title": "3.7.0 - Grade Analytics, Enhanced Navigation, fonts, Global Search & SEQTA Engage Improvements", - "items": [ - "Added Enhanced Navigation for courses: the navigator now auto-scrolls to the selected lesson (e.g. inside the \"Go to…\" popup) and prev/next arrows for jumping between lessons.", + title: + "3.7.0 - Grade Analytics, Enhanced Navigation, fonts, Global Search & SEQTA Engage Improvements", + items: [ + 'Added Enhanced Navigation for courses: the navigator now auto-scrolls to the selected lesson (e.g. inside the "Go to…" popup) and prev/next arrows for jumping between lessons.', "Added Grade Analytics, new sidebar page with grade trend charts synced from SEQTA.", "Added Grade distribution auto-detects your school’s letter scale from released marks for analytics page.", "Added documents, notices, portals, folios, goals, and more to Global Search.", @@ -98,39 +101,37 @@ export const WHATS_NEW_CHANGELOG: WhatsNewRelease[] = [ "Tweak Theme of the Month popup making it more clear about dismissals and respecting “Don’t show again”.", "Fixed duplicate-result fixes.", "Improved assessments overview with a better look.", - "Fixed assement overview showing old subjects." - ] + "Fixed assement overview showing old subjects.", + ], }, { - "title": "3.6.5 - Theme of the Month, custom message folders & assessment weighting overrides", - "items": [ + title: "3.6.5 - Theme of the Month, custom message folders & assessment weighting overrides", + items: [ "Added Theme of the Month — a monthly featured theme popup with a link to view it in the theme store.", "Added custom message folders for organising direct DM's with drag to reorder.", "Added the ability to override/add weightings to assessments (on assessment page).", "Fixed custom room and teacher names not showing in the timetable popup.", "Fixed assessment averages treating N/A weightings incorrectly in subject average calculations.", "Fixed the display of weightings that could not automatically be discovered.", - "Fixed the formatting of the weighting tag that was broken due to a SEQTA update." - ] + "Fixed the formatting of the weighting tag that was broken due to a SEQTA update.", + ], }, { - "title": "3.6.4 - Theme flavours and fixes, Upcoming Assements improvement", - "items": [ + title: "3.6.4 - Theme flavours and fixes, Upcoming Assements improvement", + items: [ "Added advanced colour adjustments variables for theme customisation.", "Improved logic for upcoming assements dashlet to improve compatibility.", "BS Cloud can now automatically download themes from other devices.", - "Added theme flavours for multiple colour variations of the same theme." - ] + "Added theme flavours for multiple colour variations of the same theme.", + ], }, { - "title": "3.6.3 - Assessment overview fix", - "items": [ - "Fixed assessments overview failing to load." - ] + title: "3.6.3 - Assessment overview fix", + items: ["Fixed assessments overview failing to load."], }, { - "title": "3.6.2 - Cloud backup, various fixes & SEQTA Engage support", - "items": [ + title: "3.6.2 - Cloud backup, various fixes & SEQTA Engage support", + items: [ "BetterSEQTA Cloud: back up and restore extension settings from your account (General settings).", "Optional automatic cloud sync if signed in (on by default).", "Option to use cloud profile photo as the local SEQTA profile picture", @@ -142,30 +143,26 @@ export const WHATS_NEW_CHANGELOG: WhatsNewRelease[] = [ "Reduced overlap between BetterSEQTA subject averages and SEQTA's built-in averages UI.", "Updated outdated in-app links and update some under the hood code (Vite 8).", "Added a notifications panel animation to work like settings.", - "Fix timetable edit plugin not working correctly." - ] + "Fix timetable edit plugin not working correctly.", + ], }, { - "title": "3.5.3 - Adaptive theme updates", - "items": [ - "Fixed adaptive theming on current-year course and assessment pages." - ] + title: "3.5.3 - Adaptive theme updates", + items: ["Fixed adaptive theming on current-year course and assessment pages."], }, { - "title": "3.5.2 - PDF & store compliance", - "items": [ - "Put PDF.js with the extension so assessment weighting stays compatible with Chrome Web Store rules" - ] + title: "3.5.2 - PDF & store compliance", + items: [ + "Put PDF.js with the extension so assessment weighting stays compatible with Chrome Web Store rules", + ], }, { - "title": "3.5.1 - QR & session link fix", - "items": [ - "Fixed DesQTA Connect Mobile App QR generation on Chrome" - ] + title: "3.5.1 - QR & session link fix", + items: ["Fixed DesQTA Connect Mobile App QR generation on Chrome"], }, { - "title": "3.5.0 - Adaptive Theme, Timetable Editor & More", - "items": [ + title: "3.5.0 - Adaptive Theme, Timetable Editor & More", + items: [ "Added adaptive theme colour", "Added optional soft gradient for adaptive theme when viewing a class", "Added timetable editor", @@ -180,89 +177,87 @@ export const WHATS_NEW_CHANGELOG: WhatsNewRelease[] = [ "Added new kanban categories to the assessments overview", "Added DesQTA QR code generation in settings for linking to the DesQTA (BetterSEQTA) mobile app", "New store with improved theme browsing and backgrounds", - "Other minor bug fixes and improvements" - ] + "Other minor bug fixes and improvements", + ], }, { - "title": "3.4.16 - Subject Averages Fixes", - "items": [ - "Fixed subject averages not showing correctly with letter grades and weighted marks" - ] + title: "3.4.16 - Subject Averages Fixes", + items: ["Fixed subject averages not showing correctly with letter grades and weighted marks"], }, { - "title": "3.4.15 - SEQTA New UI Patch", - "items": [ + title: "3.4.15 - SEQTA New UI Patch", + items: [ "Fixed compatibility issues caused by the new SEQTA UI update", "Adjusted styling to match updated SEQTA layout changes", - "Other minor bug fixes and stability improvements" - ] + "Other minor bug fixes and stability improvements", + ], }, { - "title": "3.4.14 - Search & Assessments Update", - "items": [ + title: "3.4.14 - Search & Assessments Update", + items: [ "Global Search improvements: indexing progress, more accurate results, and now includes past assessments/assignments", "Assessment Averages now parse weightings when possible for more accurate subject averages", "Added weight labels to assessment items (including proper handling of 0% and missing weights)", "Fixed homepage tutor lesson colours and assessments/courses visibility issues", "Fixed upcoming lessons tutorial room not displaying", "Fixed favicon not showing / race condition issues", - "Other minor styling and stability improvements" - ] + "Other minor styling and stability improvements", + ], }, { - "title": "3.4.13 - Bug Fixes & Styling Improvements", - "items": [ + title: "3.4.13 - Bug Fixes & Styling Improvements", + items: [ "Fixed house/year box hard failing when house_colour does not exist", "Fixed message of the day being unreadable in light mode", "Fixed global font styling issues due to SEQTA updates", "Fixed styling issues with title bar and other elements", - "Other minor bug fixes and improvements" - ] + "Other minor bug fixes and improvements", + ], }, { - "title": "3.4.12 - Privacy Updates & Bug Fixes", - "items": [ + title: "3.4.12 - Privacy Updates & Bug Fixes", + items: [ "Added privacy statement", "Added disclaimer modal to assessment averages switch", "Improved popup management system", - "Other minor bug fixes and improvements" - ] + "Other minor bug fixes and improvements", + ], }, { - "title": "3.4.11 - New Features & Bug Fixes", - "items": [ + title: "3.4.11 - New Features & Bug Fixes", + items: [ "Added Background Music plugin", "Added empty state for assessments on homepage", "Added Colour Picker hex/rgba controls", "Fixed custom shortcuts positioning (moved above regular shortcuts)", "Fixed Go to popup not scrolling properly", "Made theme edit mode more plain", - "Other minor bug fixes and improvements" - ] + "Other minor bug fixes and improvements", + ], }, { - "title": "3.4.10 - Minor bug fixes", - "items": [ + title: "3.4.10 - Minor bug fixes", + items: [ "Fixed UI file styling incorrectly applying to documents", "Fixed missing styles in global search", "Added icons for image files in file viewer", "Added rounded corners when dragging calendar events", "Improved performance of element scanning", - "Other minor improvements" - ] + "Other minor improvements", + ], }, { - "title": "3.4.9 - Bug Fixes and Performance Improvements", - "items": [ + title: "3.4.9 - Bug Fixes and Performance Improvements", + items: [ "Fixed performance issues with large notices on the homepage", "Improved performance when global search is disabled", "Improved performance of storage handling", - "Other bug fixes and improvements" - ] + "Other bug fixes and improvements", + ], }, { - "title": "3.4.8 - Improvements!", - "items": [ + title: "3.4.8 - Improvements!", + items: [ "Added new assessments kanban overview", "Added custom profile pictures", "Added custom shortcut icons", @@ -275,37 +270,35 @@ export const WHATS_NEW_CHANGELOG: WhatsNewRelease[] = [ "Fixed homepage lessons not properly changing days", "Performance improvements for global search", "Performance improvements across the extension", - "Other bug fixes and improvements" - ] + "Other bug fixes and improvements", + ], }, { - "title": "3.4.7 - Global Search", - "items": [ - "Added a new global search bar (enable in settings)\n beta\n ", + title: "3.4.7 - Global Search", + items: [ + 'Added a new global search bar (enable in settings)\n beta\n ', "Fixed news feed not loading", "Style changes and improvements", - "Other bug fixes" - ] + "Other bug fixes", + ], }, { - "title": "3.4.6.1 - Hot patch!", - "items": [ - "Fixed storage not updating and sometimes being replaced with default values" - ] + title: "3.4.6.1 - Hot patch!", + items: ["Fixed storage not updating and sometimes being replaced with default values"], }, { - "title": "3.4.6 - Massive internal reworks!", - "items": [ + title: "3.4.6 - Massive internal reworks!", + items: [ "Fix SEQTA classes not being applied correctly causing a totally broken experience", "Reworked internals to function as a plugin system (more on this soon)", "Rebuilt theme system that is significantly less buggy", "Performance improvements", - "Other minor bug fixes" - ] + "Other minor bug fixes", + ], }, { - "title": "3.4.5 - News, Bug Fixes, and improvements!", - "items": [ + title: "3.4.5 - News, Bug Fixes, and improvements!", + items: [ "Added alternative news sources", "Notifications now open direct messages", "Added Toggle for Letter/Percent Grades", @@ -314,12 +307,12 @@ export const WHATS_NEW_CHANGELOG: WhatsNewRelease[] = [ "Removed max width from theme creator", "Fixed discord icon colour in light mode", "Fixed subject averages not showing up with letter grades", - "Tweaked compose UI" - ] + "Tweaked compose UI", + ], }, { - "title": "3.4.4 - Bug Fixes and Improvements", - "items": [ + title: "3.4.4 - Bug Fixes and Improvements", + items: [ "Added vertical zoom to the timetable", "Fixed theme importing failing when images were included", "Removed broken gradients on the backgrounds of certain buttons", @@ -331,56 +324,51 @@ export const WHATS_NEW_CHANGELOG: WhatsNewRelease[] = [ "Added HEX colour input to the theme creator", "Fixed theme application in the creator", "Performance improvements", - "Other minor bug fixes" - ] + "Other minor bug fixes", + ], }, { - "title": "3.4.3 - Minor Bug Fixes", - "items": [ - "Fixed a bug where timetable colours couldn't be changed", - "Other minor bug fixes" - ] + title: "3.4.3 - Minor Bug Fixes", + items: ["Fixed a bug where timetable colours couldn't be changed", "Other minor bug fixes"], }, { - "title": "3.4.2 - Minor Bug Fixes", - "items": [ + title: "3.4.2 - Minor Bug Fixes", + items: [ "Fixed a bug where Assessment Average wasn't enabled by default", - "Fixed floating menus would sometimes be placed behind other elements" - ] + "Fixed floating menus would sometimes be placed behind other elements", + ], }, { - "title": "3.4.1 - Bug Fixes and Performance Improvements", - "items": [ - "Added a new \"Subject Average\" section to the assessments page", + title: "3.4.1 - Bug Fixes and Performance Improvements", + items: [ + 'Added a new "Subject Average" section to the assessments page', "Fixed a bug where animations wouldn't play correctly", "Added loading animations to the home page", "Under the hood performance improvements", "Improved animation performance", "Better Animations!", - "Minor style tweaks" - ] + "Minor style tweaks", + ], }, { - "title": "3.4.0 - Major Performance Update", - "items": [ + title: "3.4.0 - Major Performance Update", + items: [ "Completely rebuilt the extension popup using Svelte for dramatically improved performance", "Added a brand new background store with search functionality and downloadable backgrounds", "Significant code cleanup and optimization across the extension", "Improved overall responsiveness and load times", "Smoother animations and improved scrolling", "Fixed Firefox compatibility issues", - "Other minor bug fixes and under the hood improvements" - ] + "Other minor bug fixes and under the hood improvements", + ], }, { - "title": "3.3.1 - Hot Fix", - "items": [ - "Fixed assessments not loading when no notices are available" - ] + title: "3.3.1 - Hot Fix", + items: ["Fixed assessments not loading when no notices are available"], }, { - "title": "3.3.0 - Overhauled Theming System", - "items": [ + title: "3.3.0 - Overhauled Theming System", + items: [ "Added a theme store!", "Added the new theme creator!", "Fixed Notices not working on home page", @@ -392,158 +380,148 @@ export const WHATS_NEW_CHANGELOG: WhatsNewRelease[] = [ "Fixed loading of the tab icon", "Made animations toggle apply to settings", "Small styling improvements", - "Other minor bug fixes" - ] + "Other minor bug fixes", + ], }, { - "title": "3.2.7 - Minor Improvements", - "items": [ - "Improved performance!", - "Fixed a bug where the icon wasn't showing up" - ] + title: "3.2.7 - Minor Improvements", + items: ["Improved performance!", "Fixed a bug where the icon wasn't showing up"], }, { - "title": "3.2.6 - Bug fixes and performance improvements", - "items": [ + title: "3.2.6 - Bug fixes and performance improvements", + items: [ "Improved contrast for notifications", "Added 12-hour time format toggle", "Using external update video to ensure smaller package size", "Refactored underlying code to improve performance", - "Removed old theme system *revamp coming soon*", + 'Removed old theme system *revamp coming soon*', "Improved notices contrast", "Remove Telemetry completely - as we weren't using it too much", "Added Error handling to settings interface", "Fixed HTML message editor cursor becoming misaligned", "Enabled spellcheck inside of direct messages", "Fixed timetable dates being misaligned", - "Other minor bug fixes and under the hood improvements" - ] + "Other minor bug fixes and under the hood improvements", + ], }, { - "title": "3.2.5 - More Bug Fixes", - "items": [ + title: "3.2.5 - More Bug Fixes", + items: [ "New direct message scroll animations", "Added error message for brave browser shields breaking backgrounds", "Fixed homepage assessment tooltips being cut off", "Improved direct message styling", "Made settings panel auto size to height of screen", "Fixed timetable dates not visible", - "Other minor bug fixes" - ] + "Other minor bug fixes", + ], }, { - "title": "3.2.4 - Bug Fixes", - "items": [ + title: "3.2.4 - Bug Fixes", + items: [ "Added an open changelog button to settings", "Fixed a memory overflow bug with Education Perfect", "Fixed a bug where the background wouldn't change instantly", "Fixed news feed not loading", "Fixed home items duplicating", - "Fixed Upcoming assessments not showing" - ] + "Fixed Upcoming assessments not showing", + ], }, { - "title": "3.2.2 - Minor Improvements", - "items": [ - "Added Settings open-close animation", - "Minor Bug Fixes" - ] + title: "3.2.2 - Minor Improvements", + items: ["Added Settings open-close animation", "Minor Bug Fixes"], }, { - "title": "3.2.0 - Custom Themes", - "items": [ + title: "3.2.0 - Custom Themes", + items: [ "Added transparency (blur) effects", "Added custom themes", "Added colour picker history", - "Heaps of bug fixes" - ] + "Heaps of bug fixes", + ], }, { - "title": "3.1.3 - Custom Backgrounds", - "items": [ + title: "3.1.3 - Custom Backgrounds", + items: [ "Added custom backgrounds with support for images and videos", "Overhauled topbar", "New animated hamburger icon", - "Minor bug fixes" - ] + "Minor bug fixes", + ], }, { - "title": "3.1.2 - New settings menu!", - "items": [ + title: "3.1.2 - New settings menu!", + items: [ "Overhauled the settings menu", "Added custom gradients", "Added HEAPS of animations", "Fixed a bug where shortcuts don't show up", - "Other minor bugs fixed" - ] + "Other minor bugs fixed", + ], }, { - "title": "3.1.1 - Minor Bug fixes", - "items": [ + title: "3.1.1 - Minor Bug fixes", + items: [ "Fixed assessments overlapping", "Fixed houses not displaying if they aren't a specific color", - "Fixed Chrome Webstore Link" - ] + "Fixed Chrome Webstore Link", + ], }, { - "title": "3.1.0 - Design Improvements", - "items": [ + title: "3.1.0 - Design Improvements", + items: [ "Minor UI improvements", "Added Animation Speed Slider", "Animation now enables and disables without reloading SEQTA", - "Changed logo" - ] + "Changed logo", + ], }, { - "title": "3.0.0 - BetterSEQTA+ *Complete Overhaul*", - "items": [ + title: "3.0.0 - BetterSEQTA+ *Complete Overhaul*", + items: [ "Redesigned appearance", "Upgraded to manifest V3 (longer support)", "Fixed transitional glitches", "Under the hood improvements", - "Fixed News Feed" - ] + "Fixed News Feed", + ], }, { - "title": "2.0.7 - Added support to other domains + Minor bug fixes", - "items": [ + title: "2.0.7 - Added support to other domains + Minor bug fixes", + items: [ "Fixed BetterSEQTA+ not loading on some pages", "Fixed text colour of notices being unreadable", - "Fixed pages not reloading when saving changes" - ] + "Fixed pages not reloading when saving changes", + ], }, { - "title": "2.0.2 - Minor bug fixes", - "items": [ + title: "2.0.2 - Minor bug fixes", + items: [ "Fixed indicator for current lesson", "Fixed text colour for DM messages list in Light mode", - "Fixed user info text colour" - ] + "Fixed user info text colour", + ], }, { - "title": "Sleek New Layout", - "items": [ - "Updated with a new font and presentation, BetterSEQTA+ has never looked better." - ] + title: "Sleek New Layout", + items: ["Updated with a new font and presentation, BetterSEQTA+ has never looked better."], }, { - "title": "New Updated Sidebar", - "items": [ - "Condensed appearance with new updated icons." - ] + title: "New Updated Sidebar", + items: ["Condensed appearance with new updated icons."], }, { - "title": "Independent Light Mode and Dark Mode", - "items": [ - "Dark mode and Light mode are now available to pick alongside your chosen Theme Colour. Your Theme Colour will now become an accent colour for the page.\n Light/Dark mode can be toggled with the new button, found in the top-right of the menu bar." - ] + title: "Independent Light Mode and Dark Mode", + items: [ + "Dark mode and Light mode are now available to pick alongside your chosen Theme Colour. Your Theme Colour will now become an accent colour for the page.\n Light/Dark mode can be toggled with the new button, found in the top-right of the menu bar.", + ], }, { - "title": "Create Custom Shortcuts", - "items": [ - "Found in the BetterSEQTA+ Settings menu, custom shortcuts can now be created with a name and URL of your choice." - ] - } + title: "Create Custom Shortcuts", + items: [ + "Found in the BetterSEQTA+ Settings menu, custom shortcuts can now be created with a name and URL of your choice.", + ], + }, ]; export function renderWhatsNewChangelogHtml(): string { diff --git a/src/seqta/utils/outlookCalendar/upsertEvent.test.ts b/src/seqta/utils/outlookCalendar/upsertEvent.test.ts index a4e578a8..ec111861 100644 --- a/src/seqta/utils/outlookCalendar/upsertEvent.test.ts +++ b/src/seqta/utils/outlookCalendar/upsertEvent.test.ts @@ -18,9 +18,7 @@ describe("outlook calendar remote events", () => { }); it("creates a new event when none exists", async () => { - mockFetch.mockResolvedValueOnce( - new Response(JSON.stringify({ id: "evt-1" }), { status: 201 }), - ); + mockFetch.mockResolvedValueOnce(new Response(JSON.stringify({ id: "evt-1" }), { status: 201 })); const id = await upsertOutlookCalendarEvent("token", undefined, { subject: "Math" }); expect(id).toBe("evt-1"); @@ -102,7 +100,9 @@ describe("google calendar remote list", () => { start: { dateTime: "2026-07-13T09:00:00", timeZone: "UTC" }, end: { dateTime: "2026-07-13T10:00:00", timeZone: "UTC" }, extendedProperties: { - private: { [BSPLUS_GOOGLE_CALENDAR_EVENT_PROP]: "https://school.seqta.com.au:cal:1" }, + private: { + [BSPLUS_GOOGLE_CALENDAR_EVENT_PROP]: "https://school.seqta.com.au:cal:1", + }, }, }, { diff --git a/src/seqta/utils/patchSeqtaMenuUpdateColours.ts b/src/seqta/utils/patchSeqtaMenuUpdateColours.ts index 3b4142c0..24aa6874 100644 --- a/src/seqta/utils/patchSeqtaMenuUpdateColours.ts +++ b/src/seqta/utils/patchSeqtaMenuUpdateColours.ts @@ -112,10 +112,7 @@ export function attachTimetableColorisRecovery(): void { if (!pickerOpen) { const result = dismissTimetableUiBlockers(); if (result.slideRemoved > 0 || result.modalRemoved > 0) { - verboseInfo( - "[BetterSEQTA+] timetable colour: content-script cleanup", - result, - ); + verboseInfo("[BetterSEQTA+] timetable colour: content-script cleanup", result); } } }, diff --git a/src/seqta/utils/performanceMode.ts b/src/seqta/utils/performanceMode.ts index 903b08fc..cc340f09 100644 --- a/src/seqta/utils/performanceMode.ts +++ b/src/seqta/utils/performanceMode.ts @@ -16,10 +16,7 @@ export function isPerformanceMode(): boolean { } export function isSimpleAnalyticsUi(): boolean { - return ( - isPerformanceMode() && - !isPluginForceEnabledInPerformanceMode("grade-analytics") - ); + return isPerformanceMode() && !isPluginForceEnabledInPerformanceMode("grade-analytics"); } export function isPluginForceEnabledInPerformanceMode(pluginId: string): boolean { @@ -36,11 +33,8 @@ export function isPluginAllowedInPerformanceMode(pluginId: string): boolean { return !isPluginBlockedByPerformanceMode(pluginId); } -export function setPerformanceModePluginOverride( - pluginId: string, - forceEnable: boolean, -): void { - const current = { ...(settingsState.performanceModePluginOverrides ?? {}) }; +export function setPerformanceModePluginOverride(pluginId: string, forceEnable: boolean): void { + const current = { ...settingsState.performanceModePluginOverrides }; if (forceEnable) { current[pluginId] = true; } else { @@ -63,10 +57,7 @@ export function transparencyEnabled(): boolean { } export function adaptiveThemeTransitionEnabled(): boolean { - return ( - !isPerformanceMode() && - (settingsState.adaptiveThemeColourTransition ?? true) - ); + return !isPerformanceMode() && (settingsState.adaptiveThemeColourTransition ?? true); } export function globalSearchIndexingEnabled(settingEnabled: boolean): boolean { @@ -111,16 +102,13 @@ async function syncPerformanceModePlugins(): Promise { removeAnimatedBackgroundLayers(); window.dispatchEvent(new CustomEvent("betterseqta-background-music-stop")); } else { - const searchSettings = await browser.storage.local.get( - "plugin.global-search.settings", - ); + const searchSettings = await browser.storage.local.get("plugin.global-search.settings"); const gs = searchSettings["plugin.global-search.settings"] as | { runIndexingOnLoad?: boolean } | undefined; if (gs?.runIndexingOnLoad && isPluginAllowedInPerformanceMode("global-search")) { - const { runIndexing } = await import( - "@/plugins/built-in/globalSearch/src/indexing/indexer" - ); + const { runIndexing } = + await import("@/plugins/built-in/globalSearch/src/indexing/indexer"); if (typeof requestIdleCallback === "function") { requestIdleCallback(() => void runIndexing(), { timeout: 5000 }); } else { diff --git a/src/seqta/utils/performanceModeConfig.ts b/src/seqta/utils/performanceModeConfig.ts index 20721ca6..597c0cc0 100644 --- a/src/seqta/utils/performanceModeConfig.ts +++ b/src/seqta/utils/performanceModeConfig.ts @@ -53,6 +53,4 @@ export const PERFORMANCE_HEAVY_PLUGINS: readonly PerformanceHeavyPlugin[] = [ }, ] as const; -export const PERFORMANCE_HEAVY_PLUGIN_IDS = new Set( - PERFORMANCE_HEAVY_PLUGINS.map((p) => p.id), -); +export const PERFORMANCE_HEAVY_PLUGIN_IDS = new Set(PERFORMANCE_HEAVY_PLUGINS.map((p) => p.id)); diff --git a/src/seqta/utils/remoteConfig/apply.test.ts b/src/seqta/utils/remoteConfig/apply.test.ts index 041115c3..2c2d4b3a 100644 --- a/src/seqta/utils/remoteConfig/apply.test.ts +++ b/src/seqta/utils/remoteConfig/apply.test.ts @@ -1,8 +1,4 @@ -import { - computeEffectiveEnabled, - isRemoteFeatureAllowed, - resolveFeatureMode, -} from "./apply"; +import { computeEffectiveEnabled, isRemoteFeatureAllowed, resolveFeatureMode } from "./apply"; import { DEFAULT_REMOTE_CONFIG } from "./normalize"; import type { RemoteConfigSnapshot } from "./types"; @@ -21,9 +17,7 @@ describe("computeEffectiveEnabled", () => { }); it("allows when remote mode is on", () => { - expect(computeEffectiveEnabled(true, snapshot({ global: { mode: "on" } }), false)).toBe( - true, - ); + expect(computeEffectiveEnabled(true, snapshot({ global: { mode: "on" } }), false)).toBe(true); }); it("blocks when remote kill without local override", () => { @@ -113,7 +107,14 @@ describe("hydrateRemoteConfigFromStorage", () => { getManifest: () => ({ version: "3.7.6" }), sendMessage: jest.fn(async (msg: { type?: string }) => msg.type === "getRemoteConfigSnapshot" - ? { snapshot: { configVersion: "1", global: { mode: "on" }, features: {}, campaigns: [] } } + ? { + snapshot: { + configVersion: "1", + global: { mode: "on" }, + features: {}, + campaigns: [], + }, + } : {}, ), }, @@ -129,7 +130,8 @@ describe("hydrateRemoteConfigFromStorage", () => { dismissOptionalRemoteTheme: jest.fn(), resolveEffectiveRemoteTheme: jest.fn(), })); - const { hydrateRemoteConfigFromStorage, notifyRemoteConfigPageContext } = await import("./runtime"); + const { hydrateRemoteConfigFromStorage, notifyRemoteConfigPageContext } = + await import("./runtime"); await hydrateRemoteConfigFromStorage(); notifyRemoteConfigPageContext("learn.example.edu.au"); const browser = jest.requireMock("@/lib/browser"); diff --git a/src/seqta/utils/remoteConfig/apply.ts b/src/seqta/utils/remoteConfig/apply.ts index 28739df2..3773f40b 100644 --- a/src/seqta/utils/remoteConfig/apply.ts +++ b/src/seqta/utils/remoteConfig/apply.ts @@ -15,9 +15,7 @@ export function isHostnameAllowedByPolicy( if (!policy?.suffixes?.length) return true; const host = normalizeHostname(hostname); const suffixes = policy.suffixes.map((s) => normalizeHostname(s)); - const matches = suffixes.some( - (suffix) => host === suffix || host.endsWith(`.${suffix}`), - ); + const matches = suffixes.some((suffix) => host === suffix || host.endsWith(`.${suffix}`)); if (policy.mode === "denylist") return !matches; if (policy.mode === "allowlist") return matches; return true; @@ -64,7 +62,9 @@ export function getRemoteStatusMessage(snapshot: RemoteConfigSnapshot): string | const maint = snapshot.global.maintenance; if (maint?.body) return maint.body; if (maint?.title) return maint.title; - if (!isHostnameAllowedByPolicy(snapshot, typeof location !== "undefined" ? location.hostname : "")) { + if ( + !isHostnameAllowedByPolicy(snapshot, typeof location !== "undefined" ? location.hostname : "") + ) { return "BetterSEQTA+ is not enabled for this SEQTA site."; } return snapshot.global.mode === "off" diff --git a/src/seqta/utils/remoteConfig/normalize.ts b/src/seqta/utils/remoteConfig/normalize.ts index 6cc82683..fc880839 100644 --- a/src/seqta/utils/remoteConfig/normalize.ts +++ b/src/seqta/utils/remoteConfig/normalize.ts @@ -25,8 +25,7 @@ function normalizeGlobal(raw: unknown): RemoteGlobalConfig { g.maintenance && typeof g.maintenance === "object" ? (g.maintenance as RemoteGlobalConfig["maintenance"]) : null, - minExtensionVersion: - typeof g.minExtensionVersion === "string" ? g.minExtensionVersion : null, + minExtensionVersion: typeof g.minExtensionVersion === "string" ? g.minExtensionVersion : null, forceUpdateUrl: typeof g.forceUpdateUrl === "string" ? g.forceUpdateUrl : null, disableCloudSync: g.disableCloudSync === true, disableThemeStore: g.disableThemeStore === true, @@ -37,12 +36,12 @@ function normalizeGlobal(raw: unknown): RemoteGlobalConfig { mode: (g.hostnamePolicy as { mode?: string }).mode === "allowlist" || (g.hostnamePolicy as { mode?: string }).mode === "denylist" - ? ((g.hostnamePolicy as { mode: "allowlist" | "denylist" }).mode) + ? (g.hostnamePolicy as { mode: "allowlist" | "denylist" }).mode : undefined, suffixes: Array.isArray((g.hostnamePolicy as { suffixes?: unknown }).suffixes) - ? ((g.hostnamePolicy as { suffixes: string[] }).suffixes.filter( + ? (g.hostnamePolicy as { suffixes: string[] }).suffixes.filter( (s) => typeof s === "string", - )) + ) : undefined, } : null, @@ -72,15 +71,16 @@ function normalizeFeatures(raw: unknown): Record { message: msg && typeof msg === "object" && typeof (msg as { body?: string }).body === "string" ? { - title: typeof (msg as { title?: string }).title === "string" - ? (msg as { title: string }).title - : undefined, + title: + typeof (msg as { title?: string }).title === "string" + ? (msg as { title: string }).title + : undefined, body: (msg as { body: string }).body, severity: (msg as { severity?: string }).severity === "warning" || (msg as { severity?: string }).severity === "error" || (msg as { severity?: string }).severity === "info" - ? ((msg as { severity: "info" | "warning" | "error" }).severity) + ? (msg as { severity: "info" | "warning" | "error" }).severity : undefined, } : undefined, @@ -95,8 +95,7 @@ function normalizeRemoteTheme(raw: unknown): RemoteThemeDirective | null { const mode = r.mode; if (mode !== "off" && mode !== "optional" && mode !== "forced") return null; const packageId = typeof r.packageId === "string" ? r.packageId.trim() : ""; - const packageVersion = - typeof r.packageVersion === "string" ? r.packageVersion.trim() : ""; + const packageVersion = typeof r.packageVersion === "string" ? r.packageVersion.trim() : ""; if (!packageId || !packageVersion) return null; if (mode === "off") return null; const msg = r.message; @@ -111,12 +110,14 @@ function normalizeRemoteTheme(raw: unknown): RemoteThemeDirective | null { message: msg && typeof msg === "object" ? { - title: typeof (msg as { title?: string }).title === "string" - ? (msg as { title: string }).title - : undefined, - body: typeof (msg as { body?: string }).body === "string" - ? (msg as { body: string }).body - : undefined, + title: + typeof (msg as { title?: string }).title === "string" + ? (msg as { title: string }).title + : undefined, + body: + typeof (msg as { body?: string }).body === "string" + ? (msg as { body: string }).body + : undefined, } : undefined, }; @@ -125,11 +126,9 @@ function normalizeRemoteTheme(raw: unknown): RemoteThemeDirective | null { export function normalizeRemoteConfigSnapshot(raw: unknown): RemoteConfigSnapshot { if (!raw || typeof raw !== "object") return { ...DEFAULT_REMOTE_CONFIG }; const r = raw as Record; - const data = - r.data && typeof r.data === "object" ? (r.data as Record) : r; + const data = r.data && typeof r.data === "object" ? (r.data as Record) : r; return { - configVersion: - typeof data.configVersion === "string" ? data.configVersion : "0", + configVersion: typeof data.configVersion === "string" ? data.configVersion : "0", etag: typeof data.etag === "string" ? data.etag : undefined, source: data.source === "api" || @@ -140,7 +139,9 @@ export function normalizeRemoteConfigSnapshot(raw: unknown): RemoteConfigSnapsho : "cache", global: normalizeGlobal(data.global), features: normalizeFeatures(data.features), - campaigns: Array.isArray(data.campaigns) ? (data.campaigns as RemoteConfigSnapshot["campaigns"]) : [], + campaigns: Array.isArray(data.campaigns) + ? (data.campaigns as RemoteConfigSnapshot["campaigns"]) + : [], remoteTheme: normalizeRemoteTheme(data.remoteTheme), }; } diff --git a/src/seqta/utils/remoteConfig/remoteTheme.ts b/src/seqta/utils/remoteConfig/remoteTheme.ts index 8e90af69..9c3ffdfe 100644 --- a/src/seqta/utils/remoteConfig/remoteTheme.ts +++ b/src/seqta/utils/remoteConfig/remoteTheme.ts @@ -202,9 +202,10 @@ async function applyRemoteTheme( for (const layer of layers) { if (typeof layer.id === "string") layerIds.push(layer.id); if (typeof layer.CustomCSS === "string") css.push(layer.CustomCSS); - const stored = typeof layer.id === "string" - ? ((await localforage.getItem(layer.id)) as CustomTheme | null) - : null; + const stored = + typeof layer.id === "string" + ? ((await localforage.getItem(layer.id)) as CustomTheme | null) + : null; for (const img of stored?.CustomImages ?? []) { if (img.variableName && img.blob) images.set(img.variableName, img); } diff --git a/src/seqta/utils/remoteConfig/routeGate.ts b/src/seqta/utils/remoteConfig/routeGate.ts index 5dd5f45b..cd82b133 100644 --- a/src/seqta/utils/remoteConfig/routeGate.ts +++ b/src/seqta/utils/remoteConfig/routeGate.ts @@ -3,8 +3,7 @@ import { checkRemoteFeature } from "./runtime"; export const ROUTE_STRIP_KEEP_PLUGINS = new Set(["themes", "animated-background"]); export function parseSeqtaPageKeyFromHash(hash = location.hash): string | null { - const match = - hash.match(/[#?]page=\/([^/?&#]+)/i) ?? hash.match(/page=\/([^/?&#]+)/i); + const match = hash.match(/[#?]page=\/([^/?&#]+)/i) ?? hash.match(/page=\/([^/?&#]+)/i); if (!match?.[1]) return null; return match[1].trim().toLowerCase(); } diff --git a/src/seqta/utils/remoteConfig/runtime.ts b/src/seqta/utils/remoteConfig/runtime.ts index aa79a976..d2c08f50 100644 --- a/src/seqta/utils/remoteConfig/runtime.ts +++ b/src/seqta/utils/remoteConfig/runtime.ts @@ -25,10 +25,7 @@ import { } from "./apply"; import { scheduleReconcileRemoteTheme } from "./remoteTheme"; -export { - dismissOptionalRemoteTheme, - resolveEffectiveRemoteTheme, -} from "./remoteTheme"; +export { dismissOptionalRemoteTheme, resolveEffectiveRemoteTheme } from "./remoteTheme"; let snapshot: RemoteConfigSnapshot = normalizeRemoteConfigSnapshot(null); let localOverride = false; @@ -190,8 +187,7 @@ export function checkRemoteFeature(key: string) { } export function isRemoteSettingsSectionVisible(sectionId: string): boolean { - const key = - sectionId === "account" ? "settings.nav.cloud" : `settings.section.${sectionId}`; + const key = sectionId === "account" ? "settings.nav.cloud" : `settings.section.${sectionId}`; return !checkRemoteFeature(key).hide; } @@ -249,9 +245,7 @@ export async function ensureKilledModeSettingsAccess(): Promise { } const fallback = - document.getElementById("content") ?? - document.getElementById("container") ?? - document.body; + document.getElementById("content") ?? document.getElementById("container") ?? document.body; const mountParent = async (): Promise => { if (isSeqtaEngageExperience()) { diff --git a/src/seqta/utils/remoteConfig/storageKeys.ts b/src/seqta/utils/remoteConfig/storageKeys.ts index 0d69f658..c82cc6ae 100644 --- a/src/seqta/utils/remoteConfig/storageKeys.ts +++ b/src/seqta/utils/remoteConfig/storageKeys.ts @@ -2,8 +2,7 @@ export const BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY = "bsplus_remote_config_snapshot" export const BSPLUS_REMOTE_CONFIG_ETAG_KEY = "bsplus_remote_config_etag"; export const BSPLUS_CAMPAIGN_SEEN_KEY = "bsplus_campaign_seen"; export const BSPLUS_LOCAL_OVERRIDE_ONOFF_KEY = "bsplus_local_override_onoff"; -export const BSPLUS_FEATURES_HIDDEN_UNTIL_VERSION_KEY = - "bsplus_features_hidden_until_version"; +export const BSPLUS_FEATURES_HIDDEN_UNTIL_VERSION_KEY = "bsplus_features_hidden_until_version"; export const BSPLUS_INSTALL_REGISTERED_AT_KEY = "bsplus_install_registered_at"; export const BSPLUS_REMOTE_CONFIG_FETCHED_AT_KEY = "bsplus_remote_config_fetched_at"; export const BSPLUS_REMOTE_CONFIG_LAST_HOSTNAME_KEY = "bsplus_remote_config_last_hostname"; diff --git a/src/seqta/utils/remoteConfig/types.ts b/src/seqta/utils/remoteConfig/types.ts index 3275b1e0..b30a5e7b 100644 --- a/src/seqta/utils/remoteConfig/types.ts +++ b/src/seqta/utils/remoteConfig/types.ts @@ -1,10 +1,4 @@ -export type FeatureMode = - | "allow" - | "hide" - | "banner" - | "block" - | "greyout" - | "temp_hide"; +export type FeatureMode = "allow" | "hide" | "banner" | "block" | "greyout" | "temp_hide"; export type RemoteFeatureGate = { mode?: FeatureMode; @@ -73,7 +67,4 @@ export type RemoteConfigSnapshot = { remoteTheme?: RemoteThemeDirective | null; }; -export type CampaignSeenRecord = Record< - string, - { seenAt: string; ack?: boolean } ->; +export type CampaignSeenRecord = Record; diff --git a/src/seqta/utils/render/renderShortcuts.ts b/src/seqta/utils/render/renderShortcuts.ts index 7a2b5ea0..03ad3ff3 100644 --- a/src/seqta/utils/render/renderShortcuts.ts +++ b/src/seqta/utils/render/renderShortcuts.ts @@ -19,8 +19,11 @@ export function renderShortcuts() { try { CreateCustomShortcutDiv(element); } catch (err: any) { - console.error("[BetterSEQTA+] Error adding custom shortcut:", element?.name, err?.message || err); + console.error( + "[BetterSEQTA+] Error adding custom shortcut:", + element?.name, + err?.message || err, + ); } } } - diff --git a/src/seqta/utils/settingsNavigation.ts b/src/seqta/utils/settingsNavigation.ts index e34e2c60..686167c7 100644 --- a/src/seqta/utils/settingsNavigation.ts +++ b/src/seqta/utils/settingsNavigation.ts @@ -11,9 +11,7 @@ let pendingDestination: SettingsDestination | null = null; export function requestSettingsDestination(destination: SettingsDestination): void { pendingDestination = destination; - window.dispatchEvent( - new CustomEvent(SETTINGS_NAVIGATION_EVENT, { detail: destination }), - ); + window.dispatchEvent(new CustomEvent(SETTINGS_NAVIGATION_EVENT, { detail: destination })); } export function consumeSettingsDestination(): SettingsDestination | null { diff --git a/src/seqta/utils/settingsPopupAnimation.ts b/src/seqta/utils/settingsPopupAnimation.ts index 9630214b..7b1618c1 100644 --- a/src/seqta/utils/settingsPopupAnimation.ts +++ b/src/seqta/utils/settingsPopupAnimation.ts @@ -20,15 +20,21 @@ function settingsPanel(host: HTMLElement): HTMLElement | null { return host.shadowRoot?.querySelector("[data-settings-panel]") ?? null; } -const popupAnimations = new WeakMap; -}>(); +const popupAnimations = new WeakMap< + HTMLElement, + { + progress: number; + animation?: ReturnType; + } +>(); function animatePopup(host: HTMLElement, opening: boolean): void { const previous = popupAnimations.get(host); previous?.animation?.stop(); - const state = { progress: previous?.progress ?? 0, animation: undefined as ReturnType | undefined }; + const state = { + progress: previous?.progress ?? 0, + animation: undefined as ReturnType | undefined, + }; popupAnimations.set(host, state); if (opening) host.dispatchEvent(new Event("bsplus:settings-opening", { bubbles: true })); const panel = settingsPanel(host); diff --git a/src/seqta/utils/setupSettingsButton.ts b/src/seqta/utils/setupSettingsButton.ts index 9bb64d28..93c72cfb 100644 --- a/src/seqta/utils/setupSettingsButton.ts +++ b/src/seqta/utils/setupSettingsButton.ts @@ -1,5 +1,9 @@ import { closeExtensionPopup, getSettingsOpenGeneration } from "./closers/closeExtensionPopup"; -import { animateSettingsOpen, isExtensionSettingsOpen, prefetchSettingsShell } from "./settingsPopupAnimation"; +import { + animateSettingsOpen, + isExtensionSettingsOpen, + prefetchSettingsShell, +} from "./settingsPopupAnimation"; import { addExtensionSettings, renderSettingsIfNeeded } from "./adders/AddExtensionSettings"; export function setupSettingsButton() { diff --git a/src/seqta/utils/sidebarMenuIcons.ts b/src/seqta/utils/sidebarMenuIcons.ts index 257aba15..999019a2 100644 --- a/src/seqta/utils/sidebarMenuIcons.ts +++ b/src/seqta/utils/sidebarMenuIcons.ts @@ -33,11 +33,7 @@ export function isTopLevelSidebarItem(node: HTMLElement): boolean { function wrapMenuLabelText(label: HTMLElement) { const textNode = label.lastChild; - if ( - textNode?.nodeType === 3 && - textNode.parentNode && - textNode.parentNode.nodeName !== "SPAN" - ) { + if (textNode?.nodeType === 3 && textNode.parentNode && textNode.parentNode.nodeName !== "SPAN") { const span = document.createElement("span"); span.textContent = textNode.nodeValue; label.replaceChild(span, textNode); diff --git a/src/seqta/utils/stringToHTML.ts b/src/seqta/utils/stringToHTML.ts index e30179f2..73863588 100644 --- a/src/seqta/utils/stringToHTML.ts +++ b/src/seqta/utils/stringToHTML.ts @@ -6,7 +6,7 @@ export default function stringToHTML(str: string, styles = false) { str = DOMPurify.sanitize(str, { ADD_ATTR: ["onclick"], ALLOWED_URI_REGEXP: - /^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|chrome-extension):|\/|#|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i, + /^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|chrome-extension):|\/|#|[^a-z]|[a-z+.-]+(?:[^a-z+.\-:]|$))/i, }); const doc = parser.parseFromString(str, "text/html"); diff --git a/src/seqta/utils/themeImagePagePatch.js b/src/seqta/utils/themeImagePagePatch.js index f4319dc2..613a9768 100644 --- a/src/seqta/utils/themeImagePagePatch.js +++ b/src/seqta/utils/themeImagePagePatch.js @@ -41,7 +41,11 @@ function keepOverlayStylesLast() { function keepThemeStyleLast() { const themeStyle = document.getElementById(THEME_STYLE_ID); - if (themeStyle && document.head.contains(themeStyle) && document.head.lastElementChild !== themeStyle) { + if ( + themeStyle && + document.head.contains(themeStyle) && + document.head.lastElementChild !== themeStyle + ) { document.head.appendChild(themeStyle); } keepOverlayStylesLast(); @@ -131,7 +135,12 @@ function processPayload() { log("custom css applied"); } if (payload.overlayImages !== undefined) { - applyRootImages(payload.overlayImages, OVERLAY_IMAGES_STYLE_ID, overlayUrlCache, keepOverlayStylesLast); + applyRootImages( + payload.overlayImages, + OVERLAY_IMAGES_STYLE_ID, + overlayUrlCache, + keepOverlayStylesLast, + ); } if (payload.overlayCss !== undefined) { setStyleText(OVERLAY_STYLE_ID, payload.overlayCss || "", false); diff --git a/src/seqta/utils/updateTimetableTimes.ts b/src/seqta/utils/updateTimetableTimes.ts index 1b51be09..5b7afbce 100644 --- a/src/seqta/utils/updateTimetableTimes.ts +++ b/src/seqta/utils/updateTimetableTimes.ts @@ -19,9 +19,7 @@ function updateTimeElements(): void { const original = el.dataset.original; if (!original) return; - el.textContent = convertTo12HourFormat(original, true) - .toLowerCase() - .replace(" ", ""); + el.textContent = convertTo12HourFormat(original, true).toLowerCase().replace(" ", ""); }); const entryTimes = timetablePage.querySelectorAll(".entry .times"); @@ -38,14 +36,14 @@ function updateTimeElements(): void { el.textContent = `${start12}–${end12}`; }); - const quickbarTimes = document.querySelectorAll(".quickbar .meta .times"); + const quickbarTimes = document.querySelectorAll(".quickbar .meta .times"); quickbarTimes.forEach((el) => { if (!el.dataset.original) el.dataset.original = el.textContent || ""; const original = el.dataset.original || ""; if (!original.includes("–") && !original.includes("-")) return; const [start, end] = original.split(/[-–]/).map((p) => p.trim()); - + if (!start || !end) return; const start12 = convertTo12HourFormat(start).toLowerCase().replace(" ", ""); const end12 = convertTo12HourFormat(end).toLowerCase().replace(" ", ""); @@ -66,21 +64,23 @@ function startTimetableMonitoring(): void { // Create observer for timetable content changes timetableObserver = new MutationObserver((mutations) => { let shouldUpdate = false; - + mutations.forEach((mutation) => { if (mutation.type === "childList") { // Check if any time elements were added or modified const addedNodes = Array.from(mutation.addedNodes); - const hasTimeElements = addedNodes.some(node => { + const hasTimeElements = addedNodes.some((node) => { if (node.nodeType === Node.ELEMENT_NODE) { const element = node as Element; - return element.querySelector(".time, .times") || - element.classList.contains("time") || - element.classList.contains("times"); + return ( + element.querySelector(".time, .times") || + element.classList.contains("time") || + element.classList.contains("times") + ); } return false; }); - + if (hasTimeElements) { shouldUpdate = true; } @@ -107,10 +107,10 @@ function stopTimetableMonitoring(): void { function handleUrlChange(): void { const currentlyOnTimetable = checkIfOnTimetablePage(); - + if (currentlyOnTimetable !== isOnTimetablePage) { isOnTimetablePage = currentlyOnTimetable; - + if (isOnTimetablePage) { // Wait a bit for the page to load, then start monitoring setTimeout(() => { @@ -135,9 +135,9 @@ function startUrlMonitoring(): void { const signal = abortController.signal; // Listen for hash changes (more efficient than polling) - window.addEventListener('hashchange', handleUrlChange, { signal }); - window.addEventListener('popstate', handleUrlChange, { signal }); - + window.addEventListener("hashchange", handleUrlChange, { signal }); + window.addEventListener("popstate", handleUrlChange, { signal }); + handleUrlChange(); } @@ -149,7 +149,7 @@ function stopUrlMonitoring(): void { abortController.abort(); abortController = null; } - + stopTimetableMonitoring(); } @@ -172,7 +172,7 @@ export async function updateTimetableTimes(): Promise { } updateTimeElements(); - + // Start continuous monitoring when this function is called isOnTimetablePage = checkIfOnTimetablePage(); if (isOnTimetablePage) { diff --git a/src/seqta/utils/userInfo.ts b/src/seqta/utils/userInfo.ts index d9cea059..36b1a0b1 100644 --- a/src/seqta/utils/userInfo.ts +++ b/src/seqta/utils/userInfo.ts @@ -48,9 +48,7 @@ export async function getUserInfo(options?: { validateSession?: boolean }) { cachedUserInfo.id != null && payload.id !== cachedUserInfo.id ) { - console.warn( - "[BetterSEQTA+] Session user changed; invalidating cached user info", - ); + console.warn("[BetterSEQTA+] Session user changed; invalidating cached user info"); invalidateCachedUserInfo(); } diff --git a/src/seqta/utils/waitForEngageMenuList.ts b/src/seqta/utils/waitForEngageMenuList.ts index 0c9e6951..34c606b6 100644 --- a/src/seqta/utils/waitForEngageMenuList.ts +++ b/src/seqta/utils/waitForEngageMenuList.ts @@ -32,8 +32,6 @@ export async function waitForEngageMenuList(): Promise { } } - console.warn( - "[BetterSEQTA+] Engage: could not find a menu list to inject the home button", - ); + console.warn("[BetterSEQTA+] Engage: could not find a menu list to inject the home button"); return null; } diff --git a/src/seqta/utils/waitForSeqtaShell.test.ts b/src/seqta/utils/waitForSeqtaShell.test.ts index 27050c25..32d69dad 100644 --- a/src/seqta/utils/waitForSeqtaShell.test.ts +++ b/src/seqta/utils/waitForSeqtaShell.test.ts @@ -2,11 +2,7 @@ * @jest-environment jsdom */ import { waitForElm } from "@/seqta/utils/waitForElm"; -import { - resetSeqtaShellWaiters, - waitForSeqtaMenu, - waitForSeqtaTitle, -} from "./waitForSeqtaShell"; +import { resetSeqtaShellWaiters, waitForSeqtaMenu, waitForSeqtaTitle } from "./waitForSeqtaShell"; jest.mock("@/seqta/utils/waitForElm", () => ({ waitForElm: jest.fn(), diff --git a/src/seqta/utils/waitForSeqtaShell.ts b/src/seqta/utils/waitForSeqtaShell.ts index d8b5fe5f..b50c5c4a 100644 --- a/src/seqta/utils/waitForSeqtaShell.ts +++ b/src/seqta/utils/waitForSeqtaShell.ts @@ -30,20 +30,14 @@ function sharedWait( } /** Resolves once `#title` exists (shared across titlebar + global search). */ -export function waitForSeqtaTitle( - interval = 50, - maxIterations = 200, -): Promise { +export function waitForSeqtaTitle(interval = 50, maxIterations = 200): Promise { const immediate = document.querySelector("#title"); if (immediate) return Promise.resolve(immediate); return sharedWait("title", "#title", interval, maxIterations); } /** Resolves once `#menu` exists (shared across sidebar + background layers). */ -export function waitForSeqtaMenu( - interval = 50, - maxIterations = 200, -): Promise { +export function waitForSeqtaMenu(interval = 50, maxIterations = 200): Promise { const immediate = document.querySelector("#menu"); if (immediate) return Promise.resolve(immediate); return sharedWait("menu", "#menu", interval, maxIterations); diff --git a/src/types/canvas-confetti.d.ts b/src/types/canvas-confetti.d.ts index 16d21e0d..7893620f 100644 --- a/src/types/canvas-confetti.d.ts +++ b/src/types/canvas-confetti.d.ts @@ -1,4 +1,4 @@ -declare module 'canvas-confetti' { +declare module "canvas-confetti" { const confetti: any; export default confetti; -} \ No newline at end of file +} diff --git a/src/utils/githubReleaseUpdate.ts b/src/utils/githubReleaseUpdate.ts index e12a8b2b..68f2310b 100644 --- a/src/utils/githubReleaseUpdate.ts +++ b/src/utils/githubReleaseUpdate.ts @@ -15,8 +15,9 @@ export interface GhReleaseUpdateInfo { } function isUpdateCheckEnabled(): boolean { - return typeof __ENABLE_GH_RELEASE_UPDATE_CHECK__ !== "undefined" - && __ENABLE_GH_RELEASE_UPDATE_CHECK__; + return ( + typeof __ENABLE_GH_RELEASE_UPDATE_CHECK__ !== "undefined" && __ENABLE_GH_RELEASE_UPDATE_CHECK__ + ); } function getRepoSlug(): string { @@ -26,9 +27,7 @@ function getRepoSlug(): string { } function getUpdateChannel(): "stable" | "nightly" { - return typeof __UPDATE_CHANNEL__ !== "undefined" - ? __UPDATE_CHANNEL__ - : "stable"; + return typeof __UPDATE_CHANNEL__ !== "undefined" ? __UPDATE_CHANNEL__ : "stable"; } function getBuildLabel(): string { diff --git a/src/utils/verboseLog.ts b/src/utils/verboseLog.ts index 9d77f3f4..2937ea3c 100644 --- a/src/utils/verboseLog.ts +++ b/src/utils/verboseLog.ts @@ -8,10 +8,7 @@ export function isVerboseLoggingEnabled(): boolean { export function syncVerboseLogDomFlag(): void { if (typeof document === "undefined") return; - document.documentElement.toggleAttribute( - VERBOSE_LOG_ATTR, - isVerboseLoggingEnabled(), - ); + document.documentElement.toggleAttribute(VERBOSE_LOG_ATTR, isVerboseLoggingEnabled()); } let initialized = false; diff --git a/vite.config.ts b/vite.config.ts index 8b2c21f1..5a8eba4c 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -1,7 +1,6 @@ import { defaultClientConditions, defineConfig, loadEnv } from "vite"; import { join, resolve } from "node:path"; - import InlineWorkerPlugin from "./lib/inlineWorker.ts"; import { base64Loader } from "./lib/base64loader.ts"; import type { BuildTarget, Manifest } from "./lib/types.ts"; @@ -10,7 +9,6 @@ import stabilizeCrxDevHmr from "./lib/stabilizeCrxDevHmr.ts"; import { firefoxStripFunctionProbe } from "./lib/firefoxStripFunctionProbe.ts"; import { extensionChunkUrls } from "./lib/extensionChunkUrls.ts"; - import { svelte } from "@sveltejs/vite-plugin-svelte"; import { chrome } from "./src/manifests/chrome.ts"; @@ -42,10 +40,7 @@ function withDevManifestCsp(manifest: Manifest, command: string): Manifest { content_security_policy: { ...manifest.content_security_policy, extension_pages: extensionPages - .replace( - "script-src 'self'", - `script-src 'self' ${localhost} ${loopback}`, - ) + .replace("script-src 'self'", `script-src 'self' ${localhost} ${loopback}`) .replace( /connect-src ([^;]+)/, `connect-src $1 ${localhost} ${localhostWs} ${loopback} ${loopbackWs}`, @@ -62,112 +57,100 @@ export default defineConfig(({ command, mode: viteMode }) => { const env = loadEnv(viteMode, repoRoot, ""); return { - base: command === "build" ? "./" : "/", - define: { - __ENABLE_GH_RELEASE_UPDATE_CHECK__: JSON.stringify( - process.env.GH_RELEASE_UPDATE_CHECK === "true", - ), - __GH_RELEASE_REPO__: JSON.stringify( - process.env.GH_RELEASE_REPO ?? "BetterSEQTA/BetterSEQTA-Plus", - ), - __UPDATE_CHANNEL__: JSON.stringify(process.env.UPDATE_CHANNEL ?? "stable"), - __BUILD_LABEL__: JSON.stringify(process.env.BUILD_LABEL ?? ""), - __GOOGLE_OAUTH_CLIENT_ID__: JSON.stringify(env.GOOGLE_OAUTH_CLIENT_ID ?? ""), - __OUTLOOK_OAUTH_CLIENT_ID__: JSON.stringify(env.OUTLOOK_OAUTH_CLIENT_ID ?? ""), - }, - envDir: repoRoot, - plugins: [ - svelte({ - emitCss: false, - configFile: join(repoRoot, "src", "svelte.config.js"), - }), - extensionChunkUrls(), - base64Loader, - InlineWorkerPlugin(), - crx({ - manifest: withDevManifestCsp( - targets.find((t) => t.browser === mode.toLowerCase())?.manifest ?? - chrome.manifest, - command, + base: command === "build" ? "./" : "/", + define: { + __ENABLE_GH_RELEASE_UPDATE_CHECK__: JSON.stringify( + process.env.GH_RELEASE_UPDATE_CHECK === "true", ), - browser: mode.toLowerCase() === "firefox" ? "firefox" : "chrome", - }), - fixCrxWorkerLiveReload(), - stabilizeCrxDevHmr(), - ...(command === "build" ? [firefoxStripFunctionProbe()] : []), - ], - root: resolve(repoRoot, "./src"), - resolve: { - alias: { - "@": resolve(repoRoot, "./src"), + __GH_RELEASE_REPO__: JSON.stringify( + process.env.GH_RELEASE_REPO ?? "BetterSEQTA/BetterSEQTA-Plus", + ), + __UPDATE_CHANNEL__: JSON.stringify(process.env.UPDATE_CHANNEL ?? "stable"), + __BUILD_LABEL__: JSON.stringify(process.env.BUILD_LABEL ?? ""), + __GOOGLE_OAUTH_CLIENT_ID__: JSON.stringify(env.GOOGLE_OAUTH_CLIENT_ID ?? ""), + __OUTLOOK_OAUTH_CLIENT_ID__: JSON.stringify(env.OUTLOOK_OAUTH_CLIENT_ID ?? ""), }, - conditions: ["onnxruntime-web-use-extern-wasm", ...defaultClientConditions], - dedupe: [ - "@huggingface/transformers", - "onnxruntime-common", - "onnxruntime-web", + envDir: repoRoot, + plugins: [ + svelte({ + emitCss: false, + configFile: join(repoRoot, "src", "svelte.config.js"), + }), + extensionChunkUrls(), + base64Loader, + InlineWorkerPlugin(), + crx({ + manifest: withDevManifestCsp( + targets.find((t) => t.browser === mode.toLowerCase())?.manifest ?? chrome.manifest, + command, + ), + browser: mode.toLowerCase() === "firefox" ? "firefox" : "chrome", + }), + fixCrxWorkerLiveReload(), + stabilizeCrxDevHmr(), + ...(command === "build" ? [firefoxStripFunctionProbe()] : []), ], - }, - server: { - port: DEV_SERVER_PORT, - strictPort: true, - hmr: { - host: "localhost", - protocol: "ws", - port: DEV_SERVER_PORT, - }, - }, - css: { - preprocessorOptions: { - scss: {}, - }, - }, - optimizeDeps: { - include: [ - "layerchart", - "d3-scale", - "d3-shape", - "d3-array", - "d3-format", - "d3-time", - ], - }, - legacy: { - skipWebSocketTokenCheck: true, - }, - worker: { - format: "es", - }, - build: { - outDir: resolve(repoRoot, "dist", mode), - emptyOutDir: true, - minify: true, - chunkSizeWarningLimit: 4000, - rollupOptions: { - input: { - settings: join(repoRoot, "src", "interface", "index.html"), - pageState: join(repoRoot, "src", "pageState.js"), + root: resolve(repoRoot, "./src"), + resolve: { + alias: { + "@": resolve(repoRoot, "./src"), }, - output: { - assetFileNames: "assets/[name]-[hash][extname]", - manualChunks(id) { - const normalized = id.replace(/\\/g, "/"); - // Keep the Svelte mount helper out of the settings entry chunk so - // content-script `import("@/interface/main")` does not execute - // settings-page bootstrap (which requires #app). - if ( - normalized.endsWith("/interface/main.ts") || - normalized.endsWith("/interface/main.js") - ) { - return "interface-main"; - } + conditions: ["onnxruntime-web-use-extern-wasm", ...defaultClientConditions], + dedupe: ["@huggingface/transformers", "onnxruntime-common", "onnxruntime-web"], + }, + server: { + port: DEV_SERVER_PORT, + strictPort: true, + hmr: { + host: "localhost", + protocol: "ws", + port: DEV_SERVER_PORT, + }, + }, + css: { + preprocessorOptions: { + scss: {}, + }, + }, + optimizeDeps: { + include: ["layerchart", "d3-scale", "d3-shape", "d3-array", "d3-format", "d3-time"], + }, + legacy: { + skipWebSocketTokenCheck: true, + }, + worker: { + format: "es", + }, + build: { + outDir: resolve(repoRoot, "dist", mode), + emptyOutDir: true, + minify: true, + chunkSizeWarningLimit: 4000, + rollupOptions: { + input: { + settings: join(repoRoot, "src", "interface", "index.html"), + pageState: join(repoRoot, "src", "pageState.js"), + }, + output: { + assetFileNames: "assets/[name]-[hash][extname]", + manualChunks(id) { + const normalized = id.replace(/\\/g, "/"); + // Keep the Svelte mount helper out of the settings entry chunk so + // content-script `import("@/interface/main")` does not execute + // settings-page bootstrap (which requires #app). + if ( + normalized.endsWith("/interface/main.ts") || + normalized.endsWith("/interface/main.js") + ) { + return "interface-main"; + } + }, + }, + onwarn(warning, warn) { + if (warning.code === "FILE_NAME_CONFLICT") return; + warn(warning); }, }, - onwarn(warning, warn) { - if (warning.code === "FILE_NAME_CONFLICT") return; - warn(warning); - }, }, - }, -}; + }; });