mirror of
https://github.com/BetterSEQTA/BetterSEQTA-Plus.git
synced 2026-12-06 19:56:45 +10:30
chore: switch to oxlint and oxfmt and tidy ci
This commit is contained in:
306 files changed
+4927
-6687
No files matched your search
@@ -1,5 +1,5 @@
|
|||||||
name: Run lint
|
name: Run lint
|
||||||
description: Run ESLint on src.
|
description: Run oxlint, the format check and the type check.
|
||||||
|
|
||||||
runs:
|
runs:
|
||||||
using: composite
|
using: composite
|
||||||
@@ -7,3 +7,11 @@ runs:
|
|||||||
- name: Lint
|
- name: Lint
|
||||||
shell: bash
|
shell: bash
|
||||||
run: npm run lint
|
run: npm run lint
|
||||||
|
|
||||||
|
- name: Format check
|
||||||
|
shell: bash
|
||||||
|
run: npm run format:check
|
||||||
|
|
||||||
|
- name: Type check
|
||||||
|
shell: bash
|
||||||
|
run: npm run typecheck
|
||||||
@@ -8,6 +8,7 @@ runs:
|
|||||||
uses: actions/setup-node@v7
|
uses: actions/setup-node@v7
|
||||||
with:
|
with:
|
||||||
node-version: 26.x
|
node-version: 26.x
|
||||||
|
cache: npm
|
||||||
|
|
||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
shell: bash
|
shell: bash
|
||||||
|
|||||||
@@ -22,7 +22,6 @@ jobs:
|
|||||||
run:
|
run:
|
||||||
shell: bash
|
shell: bash
|
||||||
steps:
|
steps:
|
||||||
|
|
||||||
- uses: actions/checkout@v7
|
- uses: actions/checkout@v7
|
||||||
|
|
||||||
- name: Set build date
|
- name: Set build date
|
||||||
|
|||||||
@@ -6,6 +6,13 @@ on:
|
|||||||
push:
|
push:
|
||||||
branches: ["main"]
|
branches: ["main"]
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: ${{ github.workflow }}-${{ github.ref }}
|
||||||
|
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
lint:
|
lint:
|
||||||
# The layerchart Svelte build fails on Linux, so CI runs on Windows.
|
# The layerchart Svelte build fails on Linux, so CI runs on Windows.
|
||||||
@@ -22,9 +29,6 @@ jobs:
|
|||||||
- name: Run lint
|
- name: Run lint
|
||||||
uses: ./.github/actions/run-lint
|
uses: ./.github/actions/run-lint
|
||||||
|
|
||||||
- name: Type check
|
|
||||||
run: npm run typecheck
|
|
||||||
|
|
||||||
unit-tests:
|
unit-tests:
|
||||||
runs-on: windows-latest
|
runs-on: windows-latest
|
||||||
defaults:
|
defaults:
|
||||||
|
|||||||
@@ -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 }}"
|
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
{
|
||||||
|
"$schema": "./node_modules/oxfmt/configuration_schema.json",
|
||||||
|
"ignorePatterns": [
|
||||||
|
"betterseqtaplus-safari/",
|
||||||
|
"coverage/",
|
||||||
|
"dist/",
|
||||||
|
"package-lock.json",
|
||||||
|
"src/public/"
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
{
|
||||||
|
"$schema": "./node_modules/oxlint/configuration_schema.json",
|
||||||
|
"plugins": ["typescript", "unicorn", "oxc", "import"],
|
||||||
|
"categories": {
|
||||||
|
"correctness": "error"
|
||||||
|
},
|
||||||
|
"env": {
|
||||||
|
"builtin": true,
|
||||||
|
"browser": true,
|
||||||
|
"node": true
|
||||||
|
},
|
||||||
|
"globals": {
|
||||||
|
"__ENABLE_GH_RELEASE_UPDATE_CHECK__": "readonly",
|
||||||
|
"__GH_RELEASE_REPO__": "readonly",
|
||||||
|
"__UPDATE_CHANNEL__": "readonly",
|
||||||
|
"__BUILD_LABEL__": "readonly",
|
||||||
|
"__GOOGLE_OAUTH_CLIENT_ID__": "readonly",
|
||||||
|
"__OUTLOOK_OAUTH_CLIENT_ID__": "readonly"
|
||||||
|
},
|
||||||
|
"rules": {
|
||||||
|
"no-unused-vars": [
|
||||||
|
"error",
|
||||||
|
{
|
||||||
|
"ignoreRestSiblings": true,
|
||||||
|
"argsIgnorePattern": "^_",
|
||||||
|
"varsIgnorePattern": "^_",
|
||||||
|
"caughtErrors": "none"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"import/default": "off"
|
||||||
|
},
|
||||||
|
"ignorePatterns": ["src/public/**"]
|
||||||
|
}
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
betterseqtaplus-safari/
|
|
||||||
coverage/
|
|
||||||
dist/
|
|
||||||
package-lock.json
|
|
||||||
src/public/
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
{
|
|
||||||
"tabWidth": 2,
|
|
||||||
"useTabs": false,
|
|
||||||
"semi": true
|
|
||||||
}
|
|
||||||
+10
-9
@@ -23,15 +23,15 @@ For Firefox, run `npm run dev:firefox` and load `dist/firefox` from `about:debug
|
|||||||
|
|
||||||
## Project layout
|
## Project layout
|
||||||
|
|
||||||
| Path | What's in it |
|
| Path | What's in it |
|
||||||
|------|--------------|
|
| -------------------------------------- | --------------------------------------------- |
|
||||||
| `src/SEQTA.ts` | Content script entry point |
|
| `src/SEQTA.ts` | Content script entry point |
|
||||||
| `src/background.ts`, `src/background/` | Service worker |
|
| `src/background.ts`, `src/background/` | Service worker |
|
||||||
| `src/seqta/` | Everything injected into SEQTA pages |
|
| `src/seqta/` | Everything injected into SEQTA pages |
|
||||||
| `src/interface/` | Settings popup and theme store (Svelte) |
|
| `src/interface/` | Settings popup and theme store (Svelte) |
|
||||||
| `src/plugins/` | Plugin system and built-in plugins |
|
| `src/plugins/` | Plugin system and built-in plugins |
|
||||||
| `src/css/` | Injected styles and the shared Tailwind setup |
|
| `src/css/` | Injected styles and the shared Tailwind setup |
|
||||||
| `lib/`, `scripts/` | Vite plugins and build scripts |
|
| `lib/`, `scripts/` | Vite plugins and build scripts |
|
||||||
|
|
||||||
The [architecture guide](https://docs.betterseqta.org/architecture/) goes into more detail.
|
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:
|
4. Before opening the PR, check everything passes:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
|
npm run format
|
||||||
npm run lint
|
npm run lint
|
||||||
npm run typecheck
|
npm run typecheck
|
||||||
npm test
|
npm test
|
||||||
|
|||||||
+423
-423
File diff suppressed because it is too large.
Load diff
@@ -74,7 +74,7 @@ Returns the caller’s latest settings backup.
|
|||||||
{
|
{
|
||||||
"schemaVersion": 1,
|
"schemaVersion": 1,
|
||||||
"themeId": "uuid-string-or-empty",
|
"themeId": "uuid-string-or-empty",
|
||||||
"data": { },
|
"data": {},
|
||||||
"updated_at": "2026-04-07T12:00:00.000Z"
|
"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:
|
Example relational layout:
|
||||||
|
|
||||||
| Column | Type | Notes |
|
| Column | Type | Notes |
|
||||||
|---------------|-------------|--------|
|
| ------------ | ------------ | -------------------------------------------------------------------------------------- |
|
||||||
| `user_id` | FK → users | Unique per backup row (one row per user). |
|
| `user_id` | FK → users | Unique per backup row (one row per user). |
|
||||||
| `payload` | JSON / JSONB| Store `{ "schemaVersion", "data" }` or only `data` + separate `schema_version` column. |
|
| `payload` | JSON / JSONB | Store `{ "schemaVersion", "data" }` or only `data` + separate `schema_version` column. |
|
||||||
| `updated_at` | timestamptz | Set on each successful `PUT`. |
|
| `updated_at` | timestamptz | Set on each successful `PUT`. |
|
||||||
|
|
||||||
Unique constraint on `user_id`.
|
Unique constraint on `user_id`.
|
||||||
|
|
||||||
|
|||||||
+6
-6
@@ -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.
|
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 |
|
| Topic | Where |
|
||||||
|-------|-------|
|
| --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||||
| Installing | [docs.betterseqta.org/install](https://docs.betterseqta.org/install/) |
|
| Installing | [docs.betterseqta.org/install](https://docs.betterseqta.org/install/) |
|
||||||
| Architecture | [docs.betterseqta.org/architecture](https://docs.betterseqta.org/architecture/) |
|
| 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/) |
|
| 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/) |
|
| Making themes | [docs.betterseqta.org/theme-creation](https://docs.betterseqta.org/theme-creation/) |
|
||||||
| Troubleshooting | [docs.betterseqta.org/troubleshooting](https://docs.betterseqta.org/troubleshooting/) |
|
| Troubleshooting | [docs.betterseqta.org/troubleshooting](https://docs.betterseqta.org/troubleshooting/) |
|
||||||
|
|
||||||
These pages only live in this repo because they track the code closely:
|
These pages only live in this repo because they track the code closely:
|
||||||
|
|
||||||
|
|||||||
+23
-22
@@ -4,21 +4,26 @@ BetterSEQTA+ ships through the Chrome Web Store and Firefox Add-ons. GitHub also
|
|||||||
|
|
||||||
## Workflows
|
## Workflows
|
||||||
|
|
||||||
| Workflow | Runs on | What it does |
|
| 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. |
|
| [`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. |
|
| [`nightly.yml`](../.github/workflows/nightly.yml) | Daily at 13:30 UTC (midnight in Adelaide during daylight saving) | Builds `main` and replaces the assets on the `nightly` prerelease. |
|
||||||
| [`release.yml`](../.github/workflows/release.yml) | Manually only | Builds the version in `package.json` and publishes it as a release with that tag. |
|
|
||||||
|
|
||||||
Every build goes through the shared [`build-extension`](../.github/actions/build-extension/action.yml) action: install with `npm ci`, run `npm run build` for Chrome and Firefox, then zip `dist/chrome` and `dist/firefox`. The release workflows publish with the default `GITHUB_TOKEN`, so they need no extra secrets.
|
Both build through the shared [`build-extension`](../.github/actions/build-extension/action.yml) action: install with `npm ci`, run `npm run build` for Chrome and Firefox, then zip `dist/chrome` and `dist/firefox`. Nightly publishes with the default `GITHUB_TOKEN`, so it needs no extra secrets.
|
||||||
|
|
||||||
## Publishing a stable release
|
## Publishing a stable release
|
||||||
|
|
||||||
1. Bump `version` in `package.json` on `main` and push it.
|
Stable releases are published by hand:
|
||||||
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.
|
|
||||||
|
|
||||||
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
|
## Nightly builds
|
||||||
|
|
||||||
@@ -30,20 +35,16 @@ GitHub builds are for sideloading only. Never upload them to an extension store.
|
|||||||
|
|
||||||
## Build-time flags
|
## 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 |
|
| Variable | Stable | Nightly | PRs and local builds |
|
||||||
|----------|--------|---------|----------------------|
|
| ------------------------- | ------------------------------ | -------------- | -------------------- |
|
||||||
| `GH_RELEASE_UPDATE_CHECK` | `true` | `true` | unset |
|
| `GH_RELEASE_UPDATE_CHECK` | `true` | `true` | unset |
|
||||||
| `UPDATE_CHANNEL` | `stable` | `nightly` | unset |
|
| `UPDATE_CHANNEL` | `stable` | `nightly` | unset |
|
||||||
| `GH_RELEASE_REPO` | `BetterSEQTA/BetterSEQTA-Plus` | same | same |
|
| `GH_RELEASE_REPO` | `BetterSEQTA/BetterSEQTA-Plus` | same | same |
|
||||||
| `BUILD_LABEL` | empty | UTC build date | empty |
|
| `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:
|
Without `GH_RELEASE_UPDATE_CHECK=true`, the update checker is removed from the bundle entirely.
|
||||||
|
|
||||||
```bash
|
|
||||||
GH_RELEASE_UPDATE_CHECK=true UPDATE_CHANNEL=stable npm run build
|
|
||||||
```
|
|
||||||
|
|
||||||
## Update badge
|
## Update badge
|
||||||
|
|
||||||
|
|||||||
@@ -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",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
];
|
|
||||||
+15
-24
@@ -1,29 +1,20 @@
|
|||||||
export default {
|
export default {
|
||||||
preset: 'ts-jest',
|
preset: "ts-jest",
|
||||||
testEnvironment: 'node',
|
testEnvironment: "node",
|
||||||
roots: ['<rootDir>/src'],
|
roots: ["<rootDir>/src"],
|
||||||
testMatch: [
|
testMatch: ["**/__tests__/**/*.ts", "**/?(*.)+(spec|test).ts"],
|
||||||
'**/__tests__/**/*.ts',
|
|
||||||
'**/?(*.)+(spec|test).ts'
|
|
||||||
],
|
|
||||||
transform: {
|
transform: {
|
||||||
'^.+\\.ts$': 'ts-jest',
|
"^.+\\.ts$": "ts-jest",
|
||||||
'^.+\\.js$': ['ts-jest', { tsconfig: { allowJs: true } }],
|
"^.+\\.js$": ["ts-jest", { tsconfig: { allowJs: true } }],
|
||||||
},
|
},
|
||||||
transformIgnorePatterns: [
|
transformIgnorePatterns: ["/node_modules/(?!(color|color-string|color-convert|color-name)/)"],
|
||||||
'/node_modules/(?!(color|color-string|color-convert|color-name)/)',
|
|
||||||
],
|
|
||||||
moduleNameMapper: {
|
moduleNameMapper: {
|
||||||
'^@/(.*)\\?script(?:&(?:iife|module))?$':
|
"^@/(.*)\\?script(?:&(?:iife|module))?$": "<rootDir>/src/test/mocks/crxjsScriptPath.ts",
|
||||||
'<rootDir>/src/test/mocks/crxjsScriptPath.ts',
|
"^@/lib/browser$": "<rootDir>/src/test/mocks/browser.ts",
|
||||||
'^@/lib/browser$': '<rootDir>/src/test/mocks/browser.ts',
|
"^@/(.*)$": "<rootDir>/src/$1",
|
||||||
'^@/(.*)$': '<rootDir>/src/$1',
|
"^color$": "<rootDir>/src/test/mocks/color.ts",
|
||||||
'^color$': '<rootDir>/src/test/mocks/color.ts',
|
|
||||||
},
|
},
|
||||||
setupFilesAfterEnv: ['<rootDir>/src/test/jest.setup.ts'],
|
setupFilesAfterEnv: ["<rootDir>/src/test/jest.setup.ts"],
|
||||||
moduleFileExtensions: ['ts', 'js', 'json'],
|
moduleFileExtensions: ["ts", "js", "json"],
|
||||||
collectCoverageFrom: [
|
collectCoverageFrom: ["src/**/*.ts", "!src/**/*.d.ts"],
|
||||||
'src/**/*.ts',
|
};
|
||||||
'!src/**/*.d.ts',
|
|
||||||
],
|
|
||||||
};
|
|
||||||
Generated
+804
-1007
File diff suppressed because it is too large.
Load diff
+45
-46
@@ -1,12 +1,15 @@
|
|||||||
{
|
{
|
||||||
"name": "betterseqtaplus",
|
"name": "betterseqtaplus",
|
||||||
"version": "3.7.6",
|
"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!",
|
"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",
|
"keywords": [],
|
||||||
"engines": {
|
"license": "MIT",
|
||||||
"node": ">=26"
|
"author": {
|
||||||
|
"name": "SethBurkart123",
|
||||||
|
"email": "betterseqta.plus@gmail.com",
|
||||||
|
"url": "https://github.com/BetterSEQTA/BetterSEQTA-Plus"
|
||||||
},
|
},
|
||||||
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"compile:layerchart": "node scripts/compile-layerchart-vendor.mjs",
|
"compile:layerchart": "node scripts/compile-layerchart-vendor.mjs",
|
||||||
"postinstall": "node scripts/copy-runtime-assets.mjs && npm run compile:layerchart",
|
"postinstall": "node scripts/copy-runtime-assets.mjs && npm run compile:layerchart",
|
||||||
@@ -20,7 +23,9 @@
|
|||||||
"build:safari": "cross-env MODE=safari vite build",
|
"build:safari": "cross-env MODE=safari vite build",
|
||||||
"build:dev": "cross-env MODE=chrome SOURCEMAP=true vite build && cross-env MODE=firefox SOURCEMAP=true vite build",
|
"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",
|
"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",
|
"typecheck": "svelte-check --tsconfig ./tsconfig.json --fail-on-warnings",
|
||||||
"test": "npm run test:unit",
|
"test": "npm run test:unit",
|
||||||
"test:unit": "cross-env NODE_OPTIONS=--no-experimental-webstorage jest",
|
"test:unit": "cross-env NODE_OPTIONS=--no-experimental-webstorage jest",
|
||||||
@@ -30,47 +35,6 @@
|
|||||||
"publish": "node lib/publish.js --b",
|
"publish": "node lib/publish.js --b",
|
||||||
"zip": "node scripts/package-extension-zips.mjs"
|
"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": {
|
"dependencies": {
|
||||||
"@codemirror/autocomplete": "^6.20.4",
|
"@codemirror/autocomplete": "^6.20.4",
|
||||||
"@codemirror/commands": "^6.11.1",
|
"@codemirror/commands": "^6.11.1",
|
||||||
@@ -101,9 +65,44 @@
|
|||||||
"sortablejs": "^1.15.7",
|
"sortablejs": "^1.15.7",
|
||||||
"svelte": "^5.57.3"
|
"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": {
|
"overrides": {
|
||||||
"glob": "^14.0.3"
|
"glob": "^14.0.3"
|
||||||
},
|
},
|
||||||
|
"browserslist": "> 0.5%, last 2 versions, not dead",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=26"
|
||||||
|
},
|
||||||
"allowScripts": {
|
"allowScripts": {
|
||||||
"@parcel/watcher": false,
|
"@parcel/watcher": false,
|
||||||
"esbuild": false,
|
"esbuild": false,
|
||||||
|
|||||||
+66
-52
@@ -13,7 +13,6 @@ if (!path) {
|
|||||||
const raw = fs.readFileSync(path, "utf8");
|
const raw = fs.readFileSync(path, "utf8");
|
||||||
const { traceEvents } = JSON.parse(raw);
|
const { traceEvents } = JSON.parse(raw);
|
||||||
|
|
||||||
const DURATION_PHASES = new Set(["X", "b", "e"]);
|
|
||||||
const openStacks = new Map(); // key -> { name, cat, args, ts }
|
const openStacks = new Map(); // key -> { name, cat, args, ts }
|
||||||
|
|
||||||
const byName = new Map();
|
const byName = new Map();
|
||||||
@@ -40,10 +39,6 @@ function add(map, key, dur, count = 1) {
|
|||||||
map.set(key, e);
|
map.set(key, e);
|
||||||
}
|
}
|
||||||
|
|
||||||
function stackKey(ev) {
|
|
||||||
return `${ev.pid}:${ev.tid}:${ev.name}:${ev.ts}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const ev of traceEvents) {
|
for (const ev of traceEvents) {
|
||||||
if (ev.ts != null) {
|
if (ev.ts != null) {
|
||||||
minTs = Math.min(minTs, ev.ts);
|
minTs = Math.min(minTs, ev.ts);
|
||||||
@@ -75,20 +70,13 @@ for (const ev of traceEvents) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const url =
|
const url =
|
||||||
args.data?.url ??
|
args.data?.url ?? args.url ?? args.fileName ?? args.data?.scriptName ?? args.data?.frame ?? "";
|
||||||
args.url ??
|
|
||||||
args.fileName ??
|
|
||||||
args.data?.scriptName ??
|
|
||||||
args.data?.frame ??
|
|
||||||
"";
|
|
||||||
if (url && typeof url === "string" && dur > 0) {
|
if (url && typeof url === "string" && dur > 0) {
|
||||||
add(byUrl, url.slice(0, 200), dur);
|
add(byUrl, url.slice(0, 200), dur);
|
||||||
}
|
}
|
||||||
|
|
||||||
const fn =
|
const fn =
|
||||||
args.data?.functionName ??
|
(args.data?.functionName ?? args.functionName ?? args.data?.columnNumber != null)
|
||||||
args.functionName ??
|
|
||||||
args.data?.columnNumber != null
|
|
||||||
? `${args.data?.functionName ?? name}@${args.data?.url ?? ""}:${args.data?.lineNumber ?? "?"}`
|
? `${args.data?.functionName ?? name}@${args.data?.url ?? ""}:${args.data?.lineNumber ?? "?"}`
|
||||||
: "";
|
: "";
|
||||||
if (fn && dur > 100) {
|
if (fn && dur > 100) {
|
||||||
@@ -104,10 +92,18 @@ for (const ev of traceEvents) {
|
|||||||
if (name === "RunTask" && dur > 50000) {
|
if (name === "RunTask" && dur > 50000) {
|
||||||
longTasks.push({ dur, ts: ev.ts, cat, args: JSON.stringify(args).slice(0, 300) });
|
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 });
|
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 });
|
observers.push({ name, dur, ts: ev.ts });
|
||||||
}
|
}
|
||||||
if (/HitTest|FindElement|ElementAt/i.test(name)) {
|
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);
|
const traceDurationMs = ((maxTs - minTs) / 1000).toFixed(0);
|
||||||
|
|
||||||
console.log(JSON.stringify({
|
console.log(
|
||||||
summary: {
|
JSON.stringify(
|
||||||
traceDurationMs,
|
{
|
||||||
eventCount: traceEvents.length,
|
summary: {
|
||||||
layoutCount: layoutEvents.length,
|
traceDurationMs,
|
||||||
layoutTotalMs: (layoutEvents.reduce((s, e) => s + e.dur, 0) / 1000).toFixed(1),
|
eventCount: traceEvents.length,
|
||||||
paintCount: paintEvents.length,
|
layoutCount: layoutEvents.length,
|
||||||
paintTotalMs: (paintEvents.reduce((s, e) => s + e.dur, 0) / 1000).toFixed(1),
|
layoutTotalMs: (layoutEvents.reduce((s, e) => s + e.dur, 0) / 1000).toFixed(1),
|
||||||
longTaskCount: longTasks.length,
|
paintCount: paintEvents.length,
|
||||||
longTaskTotalMs: (longTasks.reduce((s, e) => s + e.dur, 0) / 1000).toFixed(1),
|
paintTotalMs: (paintEvents.reduce((s, e) => s + e.dur, 0) / 1000).toFixed(1),
|
||||||
timerCount: timers.length,
|
longTaskCount: longTasks.length,
|
||||||
timerTotalMs: (timers.reduce((s, e) => s + e.dur, 0) / 1000).toFixed(1),
|
longTaskTotalMs: (longTasks.reduce((s, e) => s + e.dur, 0) / 1000).toFixed(1),
|
||||||
observerCount: observers.length,
|
timerCount: timers.length,
|
||||||
observerTotalMs: (observers.reduce((s, e) => s + e.dur, 0) / 1000).toFixed(1),
|
timerTotalMs: (timers.reduce((s, e) => s + e.dur, 0) / 1000).toFixed(1),
|
||||||
hitTestCount: hitTests.length,
|
observerCount: observers.length,
|
||||||
hitTestTotalMs: (hitTests.reduce((s, e) => s + e.dur, 0) / 1000).toFixed(1),
|
observerTotalMs: (observers.reduce((s, e) => s + e.dur, 0) / 1000).toFixed(1),
|
||||||
gcCount: gcEvents.length,
|
hitTestCount: hitTests.length,
|
||||||
gcTotalMs: (gcEvents.reduce((s, e) => s + e.dur, 0) / 1000).toFixed(1),
|
hitTestTotalMs: (hitTests.reduce((s, e) => s + e.dur, 0) / 1000).toFixed(1),
|
||||||
},
|
gcCount: gcEvents.length,
|
||||||
topEventNames: top(byName, 50),
|
gcTotalMs: (gcEvents.reduce((s, e) => s + e.dur, 0) / 1000).toFixed(1),
|
||||||
topCategories: top(byCat, 30),
|
},
|
||||||
topUrls: top(byUrl, 40),
|
topEventNames: top(byName, 50),
|
||||||
topFunctions: top(byFunction, 40, 1),
|
topCategories: top(byCat, 30),
|
||||||
topBetterseqta: top(betterseqtaHits, 50),
|
topUrls: top(byUrl, 40),
|
||||||
topLongTasks: longTasks.sort((a, b) => b.dur - a.dur).slice(0, 20).map(e => ({
|
topFunctions: top(byFunction, 40, 1),
|
||||||
ms: (e.dur / 1000).toFixed(1),
|
topBetterseqta: top(betterseqtaHits, 50),
|
||||||
cat: e.cat,
|
topLongTasks: longTasks
|
||||||
args: e.args,
|
.sort((a, b) => b.dur - a.dur)
|
||||||
})),
|
.slice(0, 20)
|
||||||
topLayout: layoutEvents.sort((a, b) => b.dur - a.dur).slice(0, 15).map(e => ({
|
.map((e) => ({
|
||||||
name: e.name, ms: (e.dur / 1000).toFixed(2),
|
ms: (e.dur / 1000).toFixed(1),
|
||||||
})),
|
cat: e.cat,
|
||||||
topObservers: observers.sort((a, b) => b.dur - a.dur).slice(0, 15).map(e => ({
|
args: e.args,
|
||||||
name: e.name, ms: (e.dur / 1000).toFixed(2), count: 1,
|
})),
|
||||||
})),
|
topLayout: layoutEvents
|
||||||
}, null, 2));
|
.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,
|
||||||
|
),
|
||||||
|
);
|
||||||
@@ -33,7 +33,9 @@ const layerchartVersion = JSON.parse(
|
|||||||
const stampContent = `${layerchartVersion}\n${COMPILE_ALGO_VERSION}`;
|
const stampContent = `${layerchartVersion}\n${COMPILE_ALGO_VERSION}`;
|
||||||
|
|
||||||
if (exists(stampPath) && readFileSync(stampPath, "utf8").trim() === stampContent) {
|
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);
|
process.exit(0);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -49,9 +51,7 @@ const walkFiles = (dir, files = []) => {
|
|||||||
|
|
||||||
const patchSvelteImports = (content) => content.replace(importSuffixPattern, ".js");
|
const patchSvelteImports = (content) => content.replace(importSuffixPattern, ".js");
|
||||||
const stripRollupBreakingSyntax = (code) =>
|
const stripRollupBreakingSyntax = (code) =>
|
||||||
code
|
code.replace(/(\w+)\?(?=\s*[,)\]])/g, "$1").replace(/(\w+)\?(?=\s*:)/g, "$1");
|
||||||
.replace(/(\w+)\?(?=\s*[,)\]])/g, "$1")
|
|
||||||
.replace(/(\w+)\?(?=\s*:)/g, "$1");
|
|
||||||
|
|
||||||
const svelteFiles = walkFiles(layerchartDist).filter((f) => f.endsWith(".svelte"));
|
const svelteFiles = walkFiles(layerchartDist).filter((f) => f.endsWith(".svelte"));
|
||||||
|
|
||||||
|
|||||||
@@ -18,10 +18,7 @@ function assertManifest(browserDir) {
|
|||||||
if (!manifest.name) fail(`${browserDir} manifest missing name`);
|
if (!manifest.name) fail(`${browserDir} manifest missing name`);
|
||||||
if (!manifest.version) fail(`${browserDir} manifest missing version`);
|
if (!manifest.version) fail(`${browserDir} manifest missing version`);
|
||||||
|
|
||||||
const sw =
|
const sw = manifest.background?.service_worker ?? manifest.background?.scripts?.[0] ?? null;
|
||||||
manifest.background?.service_worker ??
|
|
||||||
manifest.background?.scripts?.[0] ??
|
|
||||||
null;
|
|
||||||
if (sw) {
|
if (sw) {
|
||||||
const swPath = path.join(root, "dist", browserDir, sw);
|
const swPath = path.join(root, "dist", browserDir, sw);
|
||||||
if (!fs.existsSync(swPath)) {
|
if (!fs.existsSync(swPath)) {
|
||||||
|
|||||||
@@ -21,10 +21,7 @@ const bootScript = execFileSync(
|
|||||||
{ encoding: "utf8" },
|
{ encoding: "utf8" },
|
||||||
);
|
);
|
||||||
|
|
||||||
test.each([
|
test.each([{ onoff: false }, { "plugin.error-page-kitten.settings": { enabled: false } }])(
|
||||||
{ onoff: false },
|
|
||||||
{ "plugin.error-page-kitten.settings": { enabled: false } },
|
|
||||||
])(
|
|
||||||
"disabled 404 customization preserves the native error message: %j",
|
"disabled 404 customization preserves the native error message: %j",
|
||||||
async (stored) => {
|
async (stored) => {
|
||||||
document.head.innerHTML = "";
|
document.head.innerHTML = "";
|
||||||
@@ -47,8 +44,6 @@ test.each([
|
|||||||
for (let i = 0; i < 10; i++) await Promise.resolve();
|
for (let i = 0; i < 10; i++) await Promise.resolve();
|
||||||
|
|
||||||
expect(mount).not.toHaveBeenCalled();
|
expect(mount).not.toHaveBeenCalled();
|
||||||
expect(
|
expect(window.getComputedStyle(document.querySelector(".message")!).display).not.toBe("none");
|
||||||
window.getComputedStyle(document.querySelector(".message")!).display,
|
|
||||||
).not.toBe("none");
|
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
+13
-31
@@ -1,7 +1,4 @@
|
|||||||
import {
|
import { initializeSettingsState, settingsState } from "@/seqta/utils/listeners/SettingsState";
|
||||||
initializeSettingsState,
|
|
||||||
settingsState,
|
|
||||||
} from "@/seqta/utils/listeners/SettingsState";
|
|
||||||
import documentLoadCSS from "@/css/documentload.scss?inline";
|
import documentLoadCSS from "@/css/documentload.scss?inline";
|
||||||
import icon48 from "@/resources/icons/icon-48.png?base64";
|
import icon48 from "@/resources/icons/icon-48.png?base64";
|
||||||
import browser from "@/lib/browser";
|
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)
|
// 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]) {
|
if (document.childNodes[1]) {
|
||||||
hasSEQTAText =
|
hasSEQTAText =
|
||||||
document.childNodes[1].textContent?.includes(
|
document.childNodes[1].textContent?.includes("Copyright (c) SEQTA Software") ?? false;
|
||||||
"Copyright (c) SEQTA Software",
|
|
||||||
) ?? false;
|
|
||||||
if (hasSEQTAText) {
|
if (hasSEQTAText) {
|
||||||
installSeqtaMenuColourPatch();
|
installSeqtaMenuColourPatch();
|
||||||
installThemeImagePagePatch();
|
installThemeImagePagePatch();
|
||||||
@@ -73,8 +68,7 @@ if (import.meta.env.DEV) {
|
|||||||
async function init() {
|
async function init() {
|
||||||
if (
|
if (
|
||||||
hasSEQTAText &&
|
hasSEQTAText &&
|
||||||
(document.title.includes("SEQTA Learn") ||
|
(document.title.includes("SEQTA Learn") || document.title.includes("SEQTA Engage")) &&
|
||||||
document.title.includes("SEQTA Engage")) &&
|
|
||||||
!IsSEQTAPage
|
!IsSEQTAPage
|
||||||
) {
|
) {
|
||||||
IsSEQTAPage = true;
|
IsSEQTAPage = true;
|
||||||
@@ -90,7 +84,6 @@ async function init() {
|
|||||||
|
|
||||||
const observer = new MutationObserver((mutations) => {
|
const observer = new MutationObserver((mutations) => {
|
||||||
for (const mutation of mutations) {
|
for (const mutation of mutations) {
|
||||||
|
|
||||||
if (
|
if (
|
||||||
mutation.type === "attributes" &&
|
mutation.type === "attributes" &&
|
||||||
mutation.target instanceof HTMLLinkElement &&
|
mutation.target instanceof HTMLLinkElement &&
|
||||||
@@ -109,8 +102,6 @@ async function init() {
|
|||||||
attributeFilter: ["href"],
|
attributeFilter: ["href"],
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await initializeSettingsState();
|
await initializeSettingsState();
|
||||||
initVerboseLogging();
|
initVerboseLogging();
|
||||||
@@ -152,9 +143,7 @@ async function init() {
|
|||||||
sessionStorage.removeItem("bsplus-dev-export-recovery");
|
sessionStorage.removeItem("bsplus-dev-export-recovery");
|
||||||
}
|
}
|
||||||
|
|
||||||
verboseInfo(
|
verboseInfo("[BetterSEQTA+] Successfully initialised BetterSEQTA+, starting to load assets.");
|
||||||
"[BetterSEQTA+] Successfully initialised BetterSEQTA+, starting to load assets.",
|
|
||||||
);
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(error);
|
console.error(error);
|
||||||
recoverFromStaleDevModuleGraph(error);
|
recoverFromStaleDevModuleGraph(error);
|
||||||
@@ -167,22 +156,17 @@ function inject404FlashHide(): void {
|
|||||||
if (document.getElementById("bsplus-404-flash-hide")) return;
|
if (document.getElementById("bsplus-404-flash-hide")) return;
|
||||||
const style = document.createElement("style");
|
const style = document.createElement("style");
|
||||||
style.id = "bsplus-404-flash-hide";
|
style.id = "bsplus-404-flash-hide";
|
||||||
style.textContent =
|
style.textContent = "html,body{background:#333!important}.message{display:none!important}";
|
||||||
"html,body{background:#333!important}.message{display:none!important}";
|
|
||||||
(document.head ?? document.documentElement).appendChild(style);
|
(document.head ?? document.documentElement).appendChild(style);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function bootErrorPage() {
|
async function bootErrorPage() {
|
||||||
if (IsSEQTAPage) return;
|
if (IsSEQTAPage) return;
|
||||||
|
|
||||||
const { isSeqta404Page, mountErrorPageKitten } = await import(
|
const { isSeqta404Page, mountErrorPageKitten } =
|
||||||
"@/plugins/built-in/errorPageKitten"
|
await import("@/plugins/built-in/errorPageKitten");
|
||||||
);
|
|
||||||
|
|
||||||
const storagePromise = browser.storage.local.get([
|
const storagePromise = browser.storage.local.get(["onoff", "plugin.error-page-kitten.settings"]);
|
||||||
"onoff",
|
|
||||||
"plugin.error-page-kitten.settings",
|
|
||||||
]);
|
|
||||||
|
|
||||||
const watchTitle = () => {
|
const watchTitle = () => {
|
||||||
if (isSeqta404Page()) inject404FlashHide();
|
if (isSeqta404Page()) inject404FlashHide();
|
||||||
@@ -221,13 +205,11 @@ async function bootErrorPage() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function replaceIcons() {
|
function replaceIcons() {
|
||||||
document
|
document.querySelectorAll<HTMLLinkElement>('link[rel*="icon"]').forEach((link) => {
|
||||||
.querySelectorAll<HTMLLinkElement>('link[rel*="icon"]')
|
if (link.href !== icon48) {
|
||||||
.forEach((link) => {
|
link.href = icon48;
|
||||||
if (link.href !== icon48) {
|
}
|
||||||
link.href = icon48;
|
});
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Vite/CRX HMR can leave modules with missing named exports until the graph is cleared. */
|
/** Vite/CRX HMR can leave modules with missing named exports until the graph is cleared. */
|
||||||
|
|||||||
@@ -117,7 +117,14 @@ function createProviderBackend(
|
|||||||
return {
|
return {
|
||||||
...backend,
|
...backend,
|
||||||
exchange: (code, redirectUri, verifier) =>
|
exchange: (code, redirectUri, verifier) =>
|
||||||
exchangeAccountsCode(tokenUrl, code, redirectUri, verifier, notReadyHint, includeErrorDescription),
|
exchangeAccountsCode(
|
||||||
|
tokenUrl,
|
||||||
|
code,
|
||||||
|
redirectUri,
|
||||||
|
verifier,
|
||||||
|
notReadyHint,
|
||||||
|
includeErrorDescription,
|
||||||
|
),
|
||||||
refresh: (refreshToken) =>
|
refresh: (refreshToken) =>
|
||||||
refreshAccountsToken(refreshUrl, refreshToken, notReadyHint, includeErrorDescription),
|
refreshAccountsToken(refreshUrl, refreshToken, notReadyHint, includeErrorDescription),
|
||||||
};
|
};
|
||||||
@@ -255,8 +262,7 @@ function waitForOAuthCallback(authTabId: number, opts: OAuthTabFlowOptions): Pro
|
|||||||
tab: chrome.tabs.Tab,
|
tab: chrome.tabs.Tab,
|
||||||
) => {
|
) => {
|
||||||
if (tabId !== authTabId) return;
|
if (tabId !== authTabId) return;
|
||||||
const url =
|
const url = changeInfo.url ?? (changeInfo.status === "complete" ? tab.url : undefined);
|
||||||
changeInfo.url ?? (changeInfo.status === "complete" ? tab.url : undefined);
|
|
||||||
if (url) finishFromUrl(url, tabId);
|
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;
|
return expiresIn ? Date.now() + expiresIn * 1000 : Date.now() + 3_600_000;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function getValidStoredAccessToken(
|
async function getValidStoredAccessToken(provider: CalendarProviderBackend): Promise<string> {
|
||||||
provider: CalendarProviderBackend,
|
|
||||||
): Promise<string> {
|
|
||||||
const state = await provider.read();
|
const state = await provider.read();
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
if (state.accessToken && state.expiresAt && state.expiresAt > now + 60_000) {
|
if (state.accessToken && state.expiresAt && state.expiresAt > now + 60_000) {
|
||||||
@@ -327,14 +331,15 @@ export function registerTrustedAsyncHandler(
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function getGoogleCalendarStatus(): Promise<GoogleCalendarStatus> {
|
async function getGoogleCalendarStatus(): Promise<GoogleCalendarStatus> {
|
||||||
const [state, shared, syncWeeksAhead, autoSyncWeekly, syncAssessmentDueDates] =
|
const [state, shared, syncWeeksAhead, autoSyncWeekly, syncAssessmentDueDates] = await Promise.all(
|
||||||
await Promise.all([
|
[
|
||||||
readGoogleCalendarState(),
|
readGoogleCalendarState(),
|
||||||
readSharedCalendarSyncSettings(),
|
readSharedCalendarSyncSettings(),
|
||||||
getSyncWeeksAhead(),
|
getSyncWeeksAhead(),
|
||||||
getAutoSyncWeekly(),
|
getAutoSyncWeekly(),
|
||||||
getSyncAssessmentDueDates(),
|
getSyncAssessmentDueDates(),
|
||||||
]);
|
],
|
||||||
|
);
|
||||||
return {
|
return {
|
||||||
configured: isGoogleCalendarConfigured(),
|
configured: isGoogleCalendarConfigured(),
|
||||||
connected: !!(state.refreshToken || state.accessToken),
|
connected: !!(state.refreshToken || state.accessToken),
|
||||||
@@ -357,7 +362,9 @@ async function getOutlookCalendarStatus(): Promise<OutlookCalendarStatus> {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async function connectCalendar(provider: CalendarProviderBackend): Promise<GoogleCalendarSyncResult> {
|
async function connectCalendar(
|
||||||
|
provider: CalendarProviderBackend,
|
||||||
|
): Promise<GoogleCalendarSyncResult> {
|
||||||
if (!provider.isConfigured()) {
|
if (!provider.isConfigured()) {
|
||||||
return { success: false, configured: false, error: provider.notConfiguredError };
|
return { success: false, configured: false, error: provider.notConfiguredError };
|
||||||
}
|
}
|
||||||
@@ -383,8 +390,7 @@ async function connectCalendar(provider: CalendarProviderBackend): Promise<Googl
|
|||||||
});
|
});
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
const message = err instanceof Error ? err.message : provider.signInFailed;
|
const message = err instanceof Error ? err.message : provider.signInFailed;
|
||||||
const mismatch =
|
const mismatch = provider.mismatchRe.test(message) || provider.mismatchRe.test(String(err));
|
||||||
provider.mismatchRe.test(message) || provider.mismatchRe.test(String(err));
|
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
configured: true,
|
configured: true,
|
||||||
@@ -465,7 +471,8 @@ function registerProviderHandlers(
|
|||||||
handlers,
|
handlers,
|
||||||
isTrustedSender,
|
isTrustedSender,
|
||||||
`${messagePrefix}GetAccessToken`,
|
`${messagePrefix}GetAccessToken`,
|
||||||
() => getValidStoredAccessToken(provider).then((accessToken) => ({ success: true, accessToken })),
|
() =>
|
||||||
|
getValidStoredAccessToken(provider).then((accessToken) => ({ success: true, accessToken })),
|
||||||
(err) => ({ success: false, error: errMsg(err, "Token refresh failed") }),
|
(err) => ({ success: false, error: errMsg(err, "Token refresh failed") }),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -476,33 +483,45 @@ export function registerGoogleCalendarMessageHandlers(
|
|||||||
): void {
|
): void {
|
||||||
registerProviderHandlers(handlers, isTrustedSender, GOOGLE_BACKEND, getGoogleCalendarStatus);
|
registerProviderHandlers(handlers, isTrustedSender, GOOGLE_BACKEND, getGoogleCalendarStatus);
|
||||||
|
|
||||||
registerTrustedAsyncHandler(handlers, isTrustedSender, "googleCalendarEnsureWeeklyAlarm", async () => {
|
registerTrustedAsyncHandler(
|
||||||
await ensureWeeklySyncAlarm();
|
handlers,
|
||||||
return { success: true };
|
isTrustedSender,
|
||||||
}, (err) => ({
|
"googleCalendarEnsureWeeklyAlarm",
|
||||||
success: false,
|
async () => {
|
||||||
error: err instanceof Error ? err.message : "Could not schedule weekly sync",
|
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) => {
|
registerTrustedAsyncHandler(
|
||||||
const body = request as {
|
handlers,
|
||||||
syncWeeksAhead?: number;
|
isTrustedSender,
|
||||||
autoSyncWeekly?: boolean;
|
"googleCalendarUpdateSyncSettings",
|
||||||
syncAssessmentDueDates?: boolean;
|
async (request) => {
|
||||||
};
|
const body = request as {
|
||||||
const patch: Record<string, unknown> = {};
|
syncWeeksAhead?: number;
|
||||||
if (body.syncWeeksAhead != null) patch.syncWeeksAhead = clampSyncWeeks(body.syncWeeksAhead);
|
autoSyncWeekly?: boolean;
|
||||||
if (body.autoSyncWeekly != null) patch.autoSyncWeekly = !!body.autoSyncWeekly;
|
syncAssessmentDueDates?: boolean;
|
||||||
if (body.syncAssessmentDueDates != null) {
|
};
|
||||||
patch.syncAssessmentDueDates = !!body.syncAssessmentDueDates;
|
const patch: Record<string, unknown> = {};
|
||||||
}
|
if (body.syncWeeksAhead != null) patch.syncWeeksAhead = clampSyncWeeks(body.syncWeeksAhead);
|
||||||
if (Object.keys(patch).length > 0) await writeSharedCalendarSyncSettings(patch);
|
if (body.autoSyncWeekly != null) patch.autoSyncWeekly = !!body.autoSyncWeekly;
|
||||||
await ensureWeeklySyncAlarm();
|
if (body.syncAssessmentDueDates != null) {
|
||||||
return { success: true, ...(await getGoogleCalendarStatus()) };
|
patch.syncAssessmentDueDates = !!body.syncAssessmentDueDates;
|
||||||
}, (err) => ({
|
}
|
||||||
success: false,
|
if (Object.keys(patch).length > 0) await writeSharedCalendarSyncSettings(patch);
|
||||||
error: err instanceof Error ? err.message : "Could not update sync settings",
|
await ensureWeeklySyncAlarm();
|
||||||
}));
|
return { success: true, ...(await getGoogleCalendarStatus()) };
|
||||||
|
},
|
||||||
|
(err) => ({
|
||||||
|
success: false,
|
||||||
|
error: err instanceof Error ? err.message : "Could not update sync settings",
|
||||||
|
}),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function registerOutlookCalendarMessageHandlers(
|
export function registerOutlookCalendarMessageHandlers(
|
||||||
|
|||||||
@@ -103,8 +103,7 @@ function isServerTimestampNewer(serverIso: string, localIso: string | undefined)
|
|||||||
async function fetchCloudSummaryOnce(
|
async function fetchCloudSummaryOnce(
|
||||||
token: string,
|
token: string,
|
||||||
): Promise<
|
): Promise<
|
||||||
| { ok: true; data: CloudSummaryResponse }
|
{ ok: true; data: CloudSummaryResponse } | { ok: false; unauthorized: boolean; error?: string }
|
||||||
| { ok: false; unauthorized: boolean; error?: string }
|
|
||||||
> {
|
> {
|
||||||
try {
|
try {
|
||||||
const r = await fetchWithTimeout(CLOUD_SUMMARY_URL, {
|
const r = await fetchWithTimeout(CLOUD_SUMMARY_URL, {
|
||||||
@@ -130,9 +129,7 @@ async function fetchCloudSummaryOnce(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function fetchCloudSummaryWithAuthRetry(
|
async function fetchCloudSummaryWithAuthRetry(token: string): Promise<CloudSummaryResponse | null> {
|
||||||
token: string,
|
|
||||||
): Promise<CloudSummaryResponse | null> {
|
|
||||||
let t = token;
|
let t = token;
|
||||||
for (let attempt = 0; attempt < 2; attempt++) {
|
for (let attempt = 0; attempt < 2; attempt++) {
|
||||||
const res = await fetchCloudSummaryOnce(t);
|
const res = await fetchCloudSummaryOnce(t);
|
||||||
@@ -355,9 +352,7 @@ async function runCloudSettingsPollInner(): Promise<void> {
|
|||||||
typeof bsplus.schemaVersion === "number" &&
|
typeof bsplus.schemaVersion === "number" &&
|
||||||
bsplus.schemaVersion > CLOUD_SETTINGS_SYNC_SCHEMA_VERSION
|
bsplus.schemaVersion > CLOUD_SETTINGS_SYNC_SCHEMA_VERSION
|
||||||
) {
|
) {
|
||||||
console.warn(
|
console.warn("[BS+ cloud sync] Server schemaVersion newer than client; skip auto-download");
|
||||||
"[BS+ cloud sync] Server schemaVersion newer than client; skip auto-download",
|
|
||||||
);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -484,4 +479,3 @@ export function initCloudSettingsAutoSync(deps: { reloadSeqtaPages: () => void }
|
|||||||
browser.storage.onChanged.addListener(onStorageChanged);
|
browser.storage.onChanged.addListener(onStorageChanged);
|
||||||
void runCloudSettingsPoll();
|
void runCloudSettingsPoll();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -21,18 +21,10 @@ function buildFormDataFromPayload(payload: UploadPayload): FormData {
|
|||||||
const form = new FormData();
|
const form = new FormData();
|
||||||
if (payload.themeZip) {
|
if (payload.themeZip) {
|
||||||
const part = payload.themeZip;
|
const part = payload.themeZip;
|
||||||
form.append(
|
form.append(part.fieldName, base64ToBlob(part.dataBase64, part.mimeType), part.filename);
|
||||||
part.fieldName,
|
|
||||||
base64ToBlob(part.dataBase64, part.mimeType),
|
|
||||||
part.filename,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
for (const part of payload.looseFiles ?? []) {
|
for (const part of payload.looseFiles ?? []) {
|
||||||
form.append(
|
form.append(part.fieldName, base64ToBlob(part.dataBase64, part.mimeType), part.filename);
|
||||||
part.fieldName,
|
|
||||||
base64ToBlob(part.dataBase64, part.mimeType),
|
|
||||||
part.filename,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
if (payload.submissionNotes?.trim()) {
|
if (payload.submissionNotes?.trim()) {
|
||||||
form.append("submission_notes", payload.submissionNotes.trim());
|
form.append("submission_notes", payload.submissionNotes.trim());
|
||||||
@@ -137,9 +129,7 @@ export function createCustomThemesHandlers(deps: {
|
|||||||
params.set("type", "betterseqta");
|
params.set("type", "betterseqta");
|
||||||
(await bsplusApiQueryParams()).forEach((value, key) => params.set(key, value));
|
(await bsplusApiQueryParams()).forEach((value, key) => params.set(key, value));
|
||||||
if (request.status) params.set("status", String(request.status));
|
if (request.status) params.set("status", String(request.status));
|
||||||
sendResponse(
|
sendResponse(await customThemesJsonFetch(`/api/custom-themes/mine?${params}`, {}, true));
|
||||||
await customThemesJsonFetch(`/api/custom-themes/mine?${params}`, {}, true),
|
|
||||||
);
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error("[Background] fetchMyCustomThemes error:", err);
|
console.error("[Background] fetchMyCustomThemes error:", err);
|
||||||
sendResponse({
|
sendResponse({
|
||||||
|
|||||||
@@ -10,10 +10,7 @@ const rssFeedsByCountry: Record<string, string[]> = {
|
|||||||
"https://rss.nytimes.com/services/xml/rss/nyt/HomePage.xml",
|
"https://rss.nytimes.com/services/xml/rss/nyt/HomePage.xml",
|
||||||
"https://feeds.npr.org/1001/rss.xml",
|
"https://feeds.npr.org/1001/rss.xml",
|
||||||
],
|
],
|
||||||
taiwan: [
|
taiwan: ["https://news.ltn.com.tw/rss/all.xml", "https://www.taipeitimes.com/xml/index.rss"],
|
||||||
"https://news.ltn.com.tw/rss/all.xml",
|
|
||||||
"https://www.taipeitimes.com/xml/index.rss",
|
|
||||||
],
|
|
||||||
hong_kong: [
|
hong_kong: [
|
||||||
"https://rthk9.rthk.hk/rthk/news/rss/e_expressnews_elocal.xml",
|
"https://rthk9.rthk.hk/rthk/news/rss/e_expressnews_elocal.xml",
|
||||||
"https://www.scmp.com/rss/91/feed",
|
"https://www.scmp.com/rss/91/feed",
|
||||||
@@ -32,10 +29,7 @@ const rssFeedsByCountry: Record<string, string[]> = {
|
|||||||
"https://www.straitstimes.com/news/singapore/rss.xml",
|
"https://www.straitstimes.com/news/singapore/rss.xml",
|
||||||
"https://www.channelnewsasia.com/rssfeeds/8395986",
|
"https://www.channelnewsasia.com/rssfeeds/8395986",
|
||||||
],
|
],
|
||||||
uk: [
|
uk: ["https://feeds.bbci.co.uk/news/rss.xml", "https://www.theguardian.com/uk/rss"],
|
||||||
"https://feeds.bbci.co.uk/news/rss.xml",
|
|
||||||
"https://www.theguardian.com/uk/rss",
|
|
||||||
],
|
|
||||||
japan: [
|
japan: [
|
||||||
"https://www3.nhk.or.jp/rss/news/cat0.xml",
|
"https://www3.nhk.or.jp/rss/news/cat0.xml",
|
||||||
"https://news.livedoor.com/topics/rss/int.xml",
|
"https://news.livedoor.com/topics/rss/int.xml",
|
||||||
|
|||||||
@@ -1,9 +1,6 @@
|
|||||||
import browser from "@/lib/browser";
|
import browser from "@/lib/browser";
|
||||||
import { getBsplusDeviceName } from "@/seqta/utils/bsplusDeviceName";
|
import { getBsplusDeviceName } from "@/seqta/utils/bsplusDeviceName";
|
||||||
import {
|
import { bsplusApiQueryParams, bsplusExtensionPayload } from "@/seqta/utils/bsplusClientContext";
|
||||||
bsplusApiQueryParams,
|
|
||||||
bsplusExtensionPayload,
|
|
||||||
} from "@/seqta/utils/bsplusClientContext";
|
|
||||||
import { getOrCreateInstallId } from "@/seqta/utils/feedback/installId";
|
import { getOrCreateInstallId } from "@/seqta/utils/feedback/installId";
|
||||||
import { isAllowedFetchUrl } from "@/seqta/utils/allowedFetchUrl";
|
import { isAllowedFetchUrl } from "@/seqta/utils/allowedFetchUrl";
|
||||||
import {
|
import {
|
||||||
@@ -78,9 +75,7 @@ async function fetchGithubSnapshot(): Promise<RemoteConfigSnapshot | null> {
|
|||||||
BS_STATUS_MANIFEST_URL.replace(/manifest\.json$/, "") ||
|
BS_STATUS_MANIFEST_URL.replace(/manifest\.json$/, "") ||
|
||||||
"https://raw.githubusercontent.com/BetterSEQTA/BS-Status/main/config/";
|
"https://raw.githubusercontent.com/BetterSEQTA/BS-Status/main/config/";
|
||||||
const files: Record<string, unknown> = {};
|
const files: Record<string, unknown> = {};
|
||||||
for (const [key, fileName] of Object.entries(
|
for (const [key, fileName] of Object.entries(manifest.files as Record<string, string>)) {
|
||||||
manifest.files as Record<string, string>,
|
|
||||||
)) {
|
|
||||||
if (typeof fileName !== "string") continue;
|
if (typeof fileName !== "string") continue;
|
||||||
const url = fileName.startsWith("http") ? fileName : `${base}${fileName}`;
|
const url = fileName.startsWith("http") ? fileName : `${base}${fileName}`;
|
||||||
if (!isAllowedFetchUrl(url)) continue;
|
if (!isAllowedFetchUrl(url)) continue;
|
||||||
@@ -95,11 +90,7 @@ async function fetchGithubSnapshot(): Promise<RemoteConfigSnapshot | null> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function registerInstall(
|
async function registerInstall(apiBase: string, primaryOk: boolean, force = false): Promise<void> {
|
||||||
apiBase: string,
|
|
||||||
primaryOk: boolean,
|
|
||||||
force = false,
|
|
||||||
): Promise<void> {
|
|
||||||
if (!primaryOk) return;
|
if (!primaryOk) return;
|
||||||
const stored = await browser.storage.local.get(BSPLUS_INSTALL_REGISTERED_AT_KEY);
|
const stored = await browser.storage.local.get(BSPLUS_INSTALL_REGISTERED_AT_KEY);
|
||||||
const last = Number(stored[BSPLUS_INSTALL_REGISTERED_AT_KEY] ?? 0);
|
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<
|
export function createRemoteConfigHandlers(
|
||||||
string,
|
apiBase: () => string,
|
||||||
(request: unknown, sendResponse: MessageSender) => boolean
|
): Record<string, (request: unknown, sendResponse: MessageSender) => boolean> {
|
||||||
> {
|
|
||||||
function handleRefresh(_req: unknown, sendResponse: MessageSender): boolean {
|
function handleRefresh(_req: unknown, sendResponse: MessageSender): boolean {
|
||||||
void refreshRemoteConfig(apiBase)
|
void refreshRemoteConfig(apiBase)
|
||||||
.then((res) => sendResponse(res))
|
.then((res) => sendResponse(res))
|
||||||
@@ -275,15 +265,11 @@ export function createRemoteConfigHandlers(apiBase: () => string): Record<
|
|||||||
}
|
}
|
||||||
|
|
||||||
function handleGetSnapshot(_req: unknown, sendResponse: MessageSender): boolean {
|
function handleGetSnapshot(_req: unknown, sendResponse: MessageSender): boolean {
|
||||||
void browser.storage.local
|
void browser.storage.local.get(BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY).then((stored) => {
|
||||||
.get(BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY)
|
sendResponse({
|
||||||
.then((stored) => {
|
snapshot: normalizeRemoteConfigSnapshot(stored[BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY]),
|
||||||
sendResponse({
|
|
||||||
snapshot: normalizeRemoteConfigSnapshot(
|
|
||||||
stored[BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY],
|
|
||||||
),
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
});
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -300,10 +286,7 @@ export function createRemoteConfigHandlers(apiBase: () => string): Record<
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
function handleFetchRemoteThemePackage(
|
function handleFetchRemoteThemePackage(req: unknown, sendResponse: MessageSender): boolean {
|
||||||
req: unknown,
|
|
||||||
sendResponse: MessageSender,
|
|
||||||
): boolean {
|
|
||||||
const { packageId: rawPackageId } = req as { packageId?: unknown };
|
const { packageId: rawPackageId } = req as { packageId?: unknown };
|
||||||
const packageId = typeof rawPackageId === "string" ? rawPackageId.trim() : "";
|
const packageId = typeof rawPackageId === "string" ? rawPackageId.trim() : "";
|
||||||
if (!packageId) {
|
if (!packageId) {
|
||||||
@@ -341,10 +324,7 @@ export function createRemoteConfigHandlers(apiBase: () => string): Record<
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
function handleFetchRemoteThemePackageUrl(
|
function handleFetchRemoteThemePackageUrl(req: unknown, sendResponse: MessageSender): boolean {
|
||||||
req: unknown,
|
|
||||||
sendResponse: MessageSender,
|
|
||||||
): boolean {
|
|
||||||
const { url: rawUrl } = req as { url?: unknown };
|
const { url: rawUrl } = req as { url?: unknown };
|
||||||
const url = typeof rawUrl === "string" ? rawUrl.trim() : "";
|
const url = typeof rawUrl === "string" ? rawUrl.trim() : "";
|
||||||
if (!url || !isAllowedFetchUrl(url)) {
|
if (!url || !isAllowedFetchUrl(url)) {
|
||||||
|
|||||||
@@ -29,7 +29,12 @@ export function handleSearchThemeStockPhotos(
|
|||||||
});
|
});
|
||||||
const res = await fetch(`https://commons.wikimedia.org/w/api.php?${params}`);
|
const res = await fetch(`https://commons.wikimedia.org/w/api.php?${params}`);
|
||||||
const json = (await res.json()) as {
|
const json = (await res.json()) as {
|
||||||
query?: { pages?: Record<string, { title?: string; imageinfo?: { thumburl?: string; url?: string }[] }> };
|
query?: {
|
||||||
|
pages?: Record<
|
||||||
|
string,
|
||||||
|
{ title?: string; imageinfo?: { thumburl?: string; url?: string }[] }
|
||||||
|
>;
|
||||||
|
};
|
||||||
};
|
};
|
||||||
const pages = json.query?.pages ?? {};
|
const pages = json.query?.pages ?? {};
|
||||||
const results: StockPhotoResult[] = Object.values(pages)
|
const results: StockPhotoResult[] = Object.values(pages)
|
||||||
|
|||||||
@@ -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_CALENDAR_SCOPE = "offline_access Calendars.ReadWrite User.Read";
|
||||||
|
|
||||||
export const OUTLOOK_AUTH_URL =
|
export const OUTLOOK_AUTH_URL = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize";
|
||||||
"https://login.microsoftonline.com/common/oauth2/v2.0/authorize";
|
|
||||||
|
|
||||||
export const OUTLOOK_GRAPH_API = "https://graph.microsoft.com/v1.0";
|
export const OUTLOOK_GRAPH_API = "https://graph.microsoft.com/v1.0";
|
||||||
|
|
||||||
|
|||||||
+87
-98
@@ -1,4 +1,3 @@
|
|||||||
|
|
||||||
@use "sass:meta";
|
@use "sass:meta";
|
||||||
@import url("https://fonts.googleapis.com/css?family=Rubik:300,400,500,600,700");
|
@import url("https://fonts.googleapis.com/css?family=Rubik:300,400,500,600,700");
|
||||||
|
|
||||||
@@ -81,13 +80,20 @@ select {
|
|||||||
|
|
||||||
select:hover {
|
select:hover {
|
||||||
background: var(--theme-secondary, var(--background-secondary)) !important;
|
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 {
|
select:focus {
|
||||||
outline: none !important;
|
outline: none !important;
|
||||||
background: var(--theme-secondary, var(--background-secondary)) !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;
|
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;
|
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;
|
pointer-events: none !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -743,8 +751,7 @@ body.icon-only-sidebar {
|
|||||||
width: 92.5% !important;
|
width: 92.5% !important;
|
||||||
margin-left: 7.5% !important;
|
margin-left: 7.5% !important;
|
||||||
margin-right: 0 !important;
|
margin-right: 0 !important;
|
||||||
border-radius: var(--bsplus-sidebar-radius, 12px) 0 0
|
border-radius: var(--bsplus-sidebar-radius, 12px) 0 0 var(--bsplus-sidebar-radius, 12px) !important;
|
||||||
var(--bsplus-sidebar-radius, 12px) !important;
|
|
||||||
background: var(--background-primary) !important;
|
background: var(--background-primary) !important;
|
||||||
transition: none !important;
|
transition: none !important;
|
||||||
color: var(--text-primary) !important;
|
color: var(--text-primary) !important;
|
||||||
@@ -778,9 +785,8 @@ body.icon-only-sidebar {
|
|||||||
var(--background-primary) var(--bsplus-sidebar-radius, 12px)
|
var(--background-primary) var(--bsplus-sidebar-radius, 12px)
|
||||||
)
|
)
|
||||||
bottom / 100% var(--bsplus-sidebar-radius, 12px) no-repeat,
|
bottom / 100% var(--bsplus-sidebar-radius, 12px) no-repeat,
|
||||||
linear-gradient(var(--background-primary), var(--background-primary))
|
linear-gradient(var(--background-primary), var(--background-primary)) center / 100%
|
||||||
center / 100% calc(100% - 2 * var(--bsplus-sidebar-radius, 12px))
|
calc(100% - 2 * var(--bsplus-sidebar-radius, 12px)) no-repeat;
|
||||||
no-repeat;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#menu > ul > .hasChildren > .sub {
|
#menu > ul > .hasChildren > .sub {
|
||||||
@@ -788,10 +794,7 @@ body.icon-only-sidebar {
|
|||||||
right: auto !important;
|
right: auto !important;
|
||||||
top: 71px !important;
|
top: 71px !important;
|
||||||
margin-top: 0 !important;
|
margin-top: 0 !important;
|
||||||
width: min(
|
width: min(var(--bsplus-sidebar-width, 270px), calc(100vw - 70px)) !important;
|
||||||
var(--bsplus-sidebar-width, 270px),
|
|
||||||
calc(100vw - 70px)
|
|
||||||
) !important;
|
|
||||||
background: var(--background-primary) !important;
|
background: var(--background-primary) !important;
|
||||||
color: var(--text-primary) !important;
|
color: var(--text-primary) !important;
|
||||||
border-right: 1px solid var(--border-color, rgba(128, 128, 128, 0.3)) !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;
|
fill: currentColor !important;
|
||||||
}
|
}
|
||||||
:is(li, section):hover {
|
:is(li, section):hover {
|
||||||
background: color-mix(
|
background: color-mix(in srgb, var(--text-primary) 8%, transparent) !important;
|
||||||
in srgb,
|
|
||||||
var(--text-primary) 8%,
|
|
||||||
transparent
|
|
||||||
) !important;
|
|
||||||
}
|
}
|
||||||
:is(li, section):is(.active, .bsplus-active):not(.hasChildren) {
|
:is(li, section):is(.active, .bsplus-active):not(.hasChildren) {
|
||||||
background: color-mix(
|
background: color-mix(in srgb, var(--text-primary) 14%, transparent) !important;
|
||||||
in srgb,
|
|
||||||
var(--text-primary) 14%,
|
|
||||||
transparent
|
|
||||||
) !important;
|
|
||||||
&::after {
|
&::after {
|
||||||
background: var(--text-primary) !important;
|
background: var(--text-primary) !important;
|
||||||
box-shadow: 0 0 10px
|
box-shadow: 0 0 10px color-mix(in srgb, var(--text-primary) 45%, transparent) !important;
|
||||||
color-mix(in srgb, var(--text-primary) 45%, transparent) !important;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.sub {
|
.sub {
|
||||||
@@ -903,14 +897,15 @@ body.icon-only-sidebar {
|
|||||||
box-sizing: border-box !important;
|
box-sizing: border-box !important;
|
||||||
margin-inline: 0 !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;
|
width: calc(100% + 1px) !important;
|
||||||
box-sizing: border-box !important;
|
box-sizing: border-box !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
body.icon-only-sidebar:has(
|
body.icon-only-sidebar:has(#menu > ul > .hasChildren:is(.active, .bsplus-active)) {
|
||||||
#menu > ul > .hasChildren:is(.active, .bsplus-active)
|
|
||||||
) {
|
|
||||||
--bsplus-icon-rail-space: calc(
|
--bsplus-icon-rail-space: calc(
|
||||||
70px + min(var(--bsplus-sidebar-width, 270px), calc(100vw - 70px))
|
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;
|
border-bottom: none !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
html.transparencyEffects
|
html.transparencyEffects [class*="BasicPanel__BasicPanel___q92_U"] > ol > li + li {
|
||||||
[class*="BasicPanel__BasicPanel___q92_U"]
|
|
||||||
> ol
|
|
||||||
> li
|
|
||||||
+ li {
|
|
||||||
border-top: 1px solid var(--theme-offset-bg);
|
border-top: 1px solid var(--theme-offset-bg);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1383,7 +1374,9 @@ html.transparencyEffects
|
|||||||
}
|
}
|
||||||
|
|
||||||
#content {
|
#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);
|
left: var(--bsplus-sidebar-width, 270px);
|
||||||
background: unset;
|
background: unset;
|
||||||
}
|
}
|
||||||
@@ -1432,7 +1425,9 @@ html.transparencyEffects
|
|||||||
-webkit-transform: translatex(-70px);
|
-webkit-transform: translatex(-70px);
|
||||||
transform: translatex(-70px);
|
transform: translatex(-70px);
|
||||||
}
|
}
|
||||||
#content { left: 0 !important; }
|
#content {
|
||||||
|
left: 0 !important;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
body.icon-only-sidebar.menuShown #content {
|
body.icon-only-sidebar.menuShown #content {
|
||||||
-webkit-transform: translatex(var(--bsplus-icon-rail-space)) !important;
|
-webkit-transform: translatex(var(--bsplus-icon-rail-space)) !important;
|
||||||
@@ -2008,13 +2003,10 @@ html.transparencyEffects
|
|||||||
margin: 20px auto 0px;
|
margin: 20px auto 0px;
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
}
|
}
|
||||||
.dark
|
.dark [class*="notifications__detailsBody___"] > [class*="notifications__subtitle___"] {
|
||||||
[class*="notifications__detailsBody___"]
|
|
||||||
> [class*="notifications__subtitle___"] {
|
|
||||||
color: #c1bcbc;
|
color: #c1bcbc;
|
||||||
}
|
}
|
||||||
[class*="notifications__detailsBody___"]
|
[class*="notifications__detailsBody___"] > [class*="notifications__subtitle___"] {
|
||||||
> [class*="notifications__subtitle___"] {
|
|
||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
}
|
}
|
||||||
[class*="notifications__notifications___"] > button {
|
[class*="notifications__notifications___"] > button {
|
||||||
@@ -2028,9 +2020,7 @@ html.transparencyEffects
|
|||||||
height: 25px;
|
height: 25px;
|
||||||
width: 24px;
|
width: 24px;
|
||||||
}
|
}
|
||||||
[class*="notifications__notifications___"]
|
[class*="notifications__notifications___"] > button > [class*="notifications__bubble___"] {
|
||||||
> button
|
|
||||||
> [class*="notifications__bubble___"] {
|
|
||||||
background: var(--better-alert-highlight);
|
background: var(--better-alert-highlight);
|
||||||
width: 25px;
|
width: 25px;
|
||||||
height: 25px;
|
height: 25px;
|
||||||
@@ -2258,20 +2248,32 @@ iframe.userHTML {
|
|||||||
background-color: var(--auto-background);
|
background-color: var(--auto-background);
|
||||||
}
|
}
|
||||||
[class*="OverallResult__OverallResult___"] {
|
[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__Thermoscore___"],
|
||||||
[class*="OverallResult__OverallResult___"] [class*="Thermoscore__fill___"],
|
[class*="OverallResult__OverallResult___"] [class*="Thermoscore__fill___"],
|
||||||
[class*="OverallResult__OverallResult___"] > div > div {
|
[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___"] {
|
[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__Thermoscore___"],
|
||||||
[class*="AssessableCriterion__header___"] [class*="Thermoscore__fill___"],
|
[class*="AssessableCriterion__header___"] [class*="Thermoscore__fill___"],
|
||||||
[class*="AssessableCriterion__header___"] > div > div > div {
|
[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___"] {
|
.dark [class*="Thermoscore__Thermoscore___"] {
|
||||||
border: 2px solid rgba(255, 255, 255, 0.3);
|
border: 2px solid rgba(255, 255, 255, 0.3);
|
||||||
@@ -2468,13 +2470,10 @@ div:has(> [class*="AssessmentDetails__AssessmentDetails___"]) {
|
|||||||
> [class*="SelectedAssessment__clearBtn___"] {
|
> [class*="SelectedAssessment__clearBtn___"] {
|
||||||
background: var(--better-main);
|
background: var(--better-main);
|
||||||
}
|
}
|
||||||
[class*="SelectedAssessment__SelectedAssessment___"]
|
[class*="SelectedAssessment__SelectedAssessment___"] > [class*="SelectedAssessment__meta___"] {
|
||||||
> [class*="SelectedAssessment__meta___"] {
|
|
||||||
border-bottom: 1px solid var(--better-main);
|
border-bottom: 1px solid var(--better-main);
|
||||||
}
|
}
|
||||||
[class*="TabSet__TabSet___"]
|
[class*="TabSet__TabSet___"] > ol[class*="TabSet__tabs___"] > li[class*="TabSet__selected___"] {
|
||||||
> ol[class*="TabSet__tabs___"]
|
|
||||||
> li[class*="TabSet__selected___"] {
|
|
||||||
border-bottom-color: var(--better-main);
|
border-bottom-color: var(--better-main);
|
||||||
}
|
}
|
||||||
[class*="TabSet__TabSet___"] > ol[class*="TabSet__tabs___"] {
|
[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%"] {
|
div.entry.class[style*="width: 46.5%"] {
|
||||||
width: 50% !important;
|
width: 50% !important;
|
||||||
}
|
}
|
||||||
.timetablepage
|
.timetablepage .dailycal > .content > .wrapper > .days > tbody > tr > td > .entriesWrapper {
|
||||||
.dailycal
|
|
||||||
> .content
|
|
||||||
> .wrapper
|
|
||||||
> .days
|
|
||||||
> tbody
|
|
||||||
> tr
|
|
||||||
> td
|
|
||||||
> .entriesWrapper {
|
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
width: auto !important;
|
width: auto !important;
|
||||||
}
|
}
|
||||||
@@ -2996,15 +2987,7 @@ body {
|
|||||||
.forumView .assessment {
|
.forumView .assessment {
|
||||||
background: var(--better-main);
|
background: var(--better-main);
|
||||||
}
|
}
|
||||||
.dailycal
|
.dailycal > .content > .wrapper > .days > tbody > tr > td > .entriesWrapper > .entry {
|
||||||
> .content
|
|
||||||
> .wrapper
|
|
||||||
> .days
|
|
||||||
> tbody
|
|
||||||
> tr
|
|
||||||
> td
|
|
||||||
> .entriesWrapper
|
|
||||||
> .entry {
|
|
||||||
padding: 3px;
|
padding: 3px;
|
||||||
transition: opacity 0.2s ease-in-out;
|
transition: opacity 0.2s ease-in-out;
|
||||||
}
|
}
|
||||||
@@ -3080,9 +3063,7 @@ body {
|
|||||||
box-shadow: none;
|
box-shadow: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
[class*="MessageList__MessageList___"]
|
[class*="MessageList__MessageList___"] > ol > li[class*="MessageList__unread___"]::before,
|
||||||
> ol
|
|
||||||
> li[class*="MessageList__unread___"]::before,
|
|
||||||
[class*="MessageList__MessageList___"] > ol > li::before {
|
[class*="MessageList__MessageList___"] > ol > li::before {
|
||||||
content: "";
|
content: "";
|
||||||
position: absolute;
|
position: absolute;
|
||||||
@@ -3094,9 +3075,7 @@ body {
|
|||||||
transition: width 0.1s;
|
transition: width 0.1s;
|
||||||
}
|
}
|
||||||
|
|
||||||
[class*="MessageList__MessageList___"]
|
[class*="MessageList__MessageList___"] > ol > li[class*="MessageList__unread___"]::before {
|
||||||
> ol
|
|
||||||
> li[class*="MessageList__unread___"]::before {
|
|
||||||
width: 3px;
|
width: 3px;
|
||||||
}
|
}
|
||||||
.connectedNotificationsWrapper > div > button {
|
.connectedNotificationsWrapper > div > button {
|
||||||
@@ -3152,16 +3131,11 @@ body:not(.clr-open) .clr-picker,
|
|||||||
visibility: hidden !important;
|
visibility: hidden !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
.dark
|
.dark [class*="MessageList__MessageList___"] > ol > li[class*="MessageList__selected___"] {
|
||||||
[class*="MessageList__MessageList___"]
|
|
||||||
> ol
|
|
||||||
> li[class*="MessageList__selected___"] {
|
|
||||||
background: var(--background-secondary);
|
background: var(--background-secondary);
|
||||||
}
|
}
|
||||||
|
|
||||||
[class*="MessageList__MessageList___"]
|
[class*="MessageList__MessageList___"] > ol > li[class*="MessageList__selected___"] {
|
||||||
> ol
|
|
||||||
> li[class*="MessageList__selected___"] {
|
|
||||||
background: var(--background-secondary, rgb(228 225 225));
|
background: var(--background-secondary, rgb(228 225 225));
|
||||||
color: var(--text-primary);
|
color: var(--text-primary);
|
||||||
box-shadow: none !important;
|
box-shadow: none !important;
|
||||||
@@ -3793,12 +3767,16 @@ div.day-empty {
|
|||||||
max-width: 16rem;
|
max-width: 16rem;
|
||||||
min-width: 10rem;
|
min-width: 10rem;
|
||||||
padding: 0.35rem 0.6rem;
|
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 {
|
.engage-child-select:focus {
|
||||||
outline: none;
|
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) {
|
#engage-day-container:has(> .day-empty) {
|
||||||
@@ -4321,14 +4299,16 @@ div.day-empty {
|
|||||||
/* Lightweight popup motion (performance mode) — fade + scale, no blur springs. */
|
/* Lightweight popup motion (performance mode) — fade + scale, no blur springs. */
|
||||||
.whatsnewBackground.bsplus-popup-css-animate {
|
.whatsnewBackground.bsplus-popup-css-animate {
|
||||||
opacity: 0;
|
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 {
|
.whatsnewContainer {
|
||||||
opacity: 0;
|
opacity: 0;
|
||||||
transform: scale(0.94);
|
transform: scale(0.94);
|
||||||
transition:
|
transition:
|
||||||
opacity var(--bs-motion-duration, 0.2s) var(--bs-motion-ease, cubic-bezier(0.22, 1, 0.36, 1)),
|
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 {
|
&.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);
|
inset 0 0 0 1px color-mix(in srgb, var(--text-primary) 14%, transparent);
|
||||||
backdrop-filter: blur(8px);
|
backdrop-filter: blur(8px);
|
||||||
-webkit-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 {
|
.themeOfTheMonthCardPopoutIcon {
|
||||||
display: inline-flex;
|
display: inline-flex;
|
||||||
@@ -4961,7 +4943,9 @@ div.day-empty {
|
|||||||
border-radius: 9999px;
|
border-radius: 9999px;
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
background: color-mix(in srgb, var(--text-primary) 28%, transparent);
|
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 {
|
.themeOfTheMonthCardGalleryDotActive {
|
||||||
background: var(--better-pri, #6366f1);
|
background: var(--better-pri, #6366f1);
|
||||||
@@ -5039,7 +5023,10 @@ div.day-empty {
|
|||||||
padding: 0.5rem 0.85rem;
|
padding: 0.5rem 0.85rem;
|
||||||
font-size: 0.84rem;
|
font-size: 0.84rem;
|
||||||
font-weight: 700;
|
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 {
|
.themeOfTheMonthCardConfirmCancel {
|
||||||
background: color-mix(in srgb, var(--text-primary) 10%, transparent);
|
background: color-mix(in srgb, var(--text-primary) 10%, transparent);
|
||||||
@@ -5151,7 +5138,9 @@ div.day-empty {
|
|||||||
padding: 0.58rem 0.9rem;
|
padding: 0.58rem 0.9rem;
|
||||||
font-size: 0.86rem;
|
font-size: 0.86rem;
|
||||||
font-weight: 700;
|
font-weight: 700;
|
||||||
transition: background 0.15s ease, color 0.15s ease;
|
transition:
|
||||||
|
background 0.15s ease,
|
||||||
|
color 0.15s ease;
|
||||||
}
|
}
|
||||||
.themeOfTheMonthCardPrimary {
|
.themeOfTheMonthCardPrimary {
|
||||||
background: var(--better-pri, #6366f1);
|
background: var(--better-pri, #6366f1);
|
||||||
@@ -5223,7 +5212,8 @@ div.day-empty {
|
|||||||
animation: bsplusThemeHighlightPulse 1.4s ease-in-out 2;
|
animation: bsplusThemeHighlightPulse 1.4s ease-in-out 2;
|
||||||
}
|
}
|
||||||
@keyframes bsplusThemeHighlightPulse {
|
@keyframes bsplusThemeHighlightPulse {
|
||||||
0%, 100% {
|
0%,
|
||||||
|
100% {
|
||||||
box-shadow: 0 0 0 0 color-mix(in srgb, var(--better-pri, #6366f1) 0%, transparent);
|
box-shadow: 0 0 0 0 color-mix(in srgb, var(--better-pri, #6366f1) 0%, transparent);
|
||||||
}
|
}
|
||||||
50% {
|
50% {
|
||||||
@@ -5233,7 +5223,9 @@ div.day-empty {
|
|||||||
|
|
||||||
.popup-media-fullscreenable {
|
.popup-media-fullscreenable {
|
||||||
cursor: pointer;
|
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 {
|
.popup-media-fullscreenable:hover {
|
||||||
opacity: 0.95;
|
opacity: 0.95;
|
||||||
@@ -5448,10 +5440,7 @@ div.day-empty {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
&:not(:hover)
|
&:not(:hover) .cke_button:not(.cke_button_on):not(.cke_button__seqta-align-left:first-child) {
|
||||||
.cke_button:not(.cke_button_on):not(
|
|
||||||
.cke_button__seqta-align-left:first-child
|
|
||||||
) {
|
|
||||||
transform: translateY(0);
|
transform: translateY(0);
|
||||||
visibility: hidden;
|
visibility: hidden;
|
||||||
transition:
|
transition:
|
||||||
|
|||||||
@@ -29,12 +29,8 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#menu#menu
|
#menu#menu ul.bsplus-drill-rows:has(> .hasChildren:is(.active, .bsplus-active)) > :is(li, section) {
|
||||||
ul.bsplus-drill-rows:has(> .hasChildren:is(.active, .bsplus-active))
|
margin-left: calc(var(--bsplus-row-margin-left) + var(--bsplus-slide-off, -320px)) !important;
|
||||||
> :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. */
|
/* Incoming rows travel only with their native panel. */
|
||||||
@@ -62,9 +58,7 @@
|
|||||||
pointer-events: none !important;
|
pointer-events: none !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
#menu
|
#menu > ul:has(li.hasChildren:is(.active, .bsplus-active)) > li:is(.active, .bsplus-active) {
|
||||||
> ul:has(li.hasChildren:is(.active, .bsplus-active))
|
|
||||||
> li:is(.active, .bsplus-active) {
|
|
||||||
background: transparent !important;
|
background: transparent !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -43,9 +43,9 @@
|
|||||||
const scheduleIndicator = rafThrottle(updateIndicator);
|
const scheduleIndicator = rafThrottle(updateIndicator);
|
||||||
|
|
||||||
$effect(() => {
|
$effect(() => {
|
||||||
selectedId;
|
void selectedId;
|
||||||
groups;
|
void groups;
|
||||||
trackEl;
|
void trackEl;
|
||||||
scheduleIndicator();
|
scheduleIndicator();
|
||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|||||||
@@ -30,7 +30,9 @@ describe("parseColour", () => {
|
|||||||
|
|
||||||
describe("parseValue", () => {
|
describe("parseValue", () => {
|
||||||
it("parses the default gradient", () => {
|
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",
|
kind: "linear",
|
||||||
angle: 45,
|
angle: 45,
|
||||||
stops: [
|
stops: [
|
||||||
@@ -41,7 +43,9 @@ describe("parseValue", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("parses radial gradients and skips the shape", () => {
|
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).toBe("radial");
|
||||||
expect(value.kind !== "solid" && value.stops.map((stop) => stop.position)).toEqual([32, 100]);
|
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", () => {
|
it("maps side keywords and fills missing stop positions", () => {
|
||||||
const value = parseValue("linear-gradient(to right, #000, #888, #fff)");
|
const value = parseValue("linear-gradient(to right, #000, #888, #fff)");
|
||||||
expect(value).toMatchObject({ kind: "linear", angle: 90 });
|
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", () => {
|
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");
|
expect(parseValue("not a colour").kind).toBe("solid");
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -23,7 +23,8 @@ const SIDE_ANGLES: Record<string, number> = {
|
|||||||
"to left top": 315,
|
"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 round = (value: number, digits = 0) => {
|
||||||
const factor = 10 ** digits;
|
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 {
|
function hslToRgba(h: number, s: number, l: number, a: number): Rgba {
|
||||||
const k = (n: number) => (n + h / 30) % 12;
|
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 };
|
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")) {
|
if (fn[1].startsWith("rgb")) {
|
||||||
const [r, g, b] = parts
|
const [r, g, b] = parts
|
||||||
.slice(0, 3)
|
.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 };
|
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];
|
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 {
|
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 {
|
export function formatValue(value: ColourValue): string {
|
||||||
if (value.kind === "solid") return formatColour(value.colour);
|
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)})`;
|
return `radial-gradient(circle, ${formatStops(value.stops)})`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -21,11 +21,7 @@
|
|||||||
--bsplus-analytics-surface: var(--background-primary, #ffffff);
|
--bsplus-analytics-surface: var(--background-primary, #ffffff);
|
||||||
--bsplus-analytics-surface-2: var(--background-secondary, #f8fafc);
|
--bsplus-analytics-surface-2: var(--background-secondary, #f8fafc);
|
||||||
--bsplus-analytics-text: var(--text-primary, #1a1a1a);
|
--bsplus-analytics-text: var(--text-primary, #1a1a1a);
|
||||||
--bsplus-analytics-muted: color-mix(
|
--bsplus-analytics-muted: color-mix(in srgb, var(--bsplus-analytics-text) 55%, transparent);
|
||||||
in srgb,
|
|
||||||
var(--bsplus-analytics-text) 55%,
|
|
||||||
transparent
|
|
||||||
);
|
|
||||||
--bsplus-analytics-border: color-mix(
|
--bsplus-analytics-border: color-mix(
|
||||||
in srgb,
|
in srgb,
|
||||||
var(--theme-offset-bg, var(--background-secondary, #e2e8f0)) 78%,
|
var(--theme-offset-bg, var(--background-secondary, #e2e8f0)) 78%,
|
||||||
@@ -142,11 +138,7 @@
|
|||||||
|
|
||||||
.bsplus-font-picker-reset:hover:not(:disabled) {
|
.bsplus-font-picker-reset:hover:not(:disabled) {
|
||||||
transform: scale(1.02);
|
transform: scale(1.02);
|
||||||
background: color-mix(
|
background: color-mix(in srgb, var(--bsplus-analytics-surface-2) 80%, transparent);
|
||||||
in srgb,
|
|
||||||
var(--bsplus-analytics-surface-2) 80%,
|
|
||||||
transparent
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.bsplus-font-picker-reset:active:not(:disabled) {
|
.bsplus-font-picker-reset:active:not(:disabled) {
|
||||||
@@ -155,8 +147,7 @@
|
|||||||
|
|
||||||
.bsplus-font-picker-reset:focus-visible {
|
.bsplus-font-picker-reset:focus-visible {
|
||||||
outline: none;
|
outline: none;
|
||||||
box-shadow: 0 0 0 3px
|
box-shadow: 0 0 0 3px color-mix(in srgb, var(--bsplus-analytics-accent) 35%, transparent);
|
||||||
color-mix(in srgb, var(--bsplus-analytics-accent) 35%, transparent);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.bsplus-font-picker-reset:disabled {
|
.bsplus-font-picker-reset:disabled {
|
||||||
@@ -180,8 +171,7 @@
|
|||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
background: var(--bsplus-analytics-accent);
|
background: var(--bsplus-analytics-accent);
|
||||||
color: var(--text-color, #ffffff);
|
color: var(--text-color, #ffffff);
|
||||||
box-shadow: 0 2px 8px
|
box-shadow: 0 2px 8px color-mix(in srgb, var(--bsplus-analytics-accent) 40%, transparent);
|
||||||
color-mix(in srgb, var(--bsplus-analytics-accent) 40%, transparent);
|
|
||||||
transition:
|
transition:
|
||||||
transform 0.2s var(--bsplus-analytics-ease),
|
transform 0.2s var(--bsplus-analytics-ease),
|
||||||
box-shadow 0.2s var(--bsplus-analytics-ease);
|
box-shadow 0.2s var(--bsplus-analytics-ease);
|
||||||
@@ -189,8 +179,7 @@
|
|||||||
|
|
||||||
.bsplus-font-picker-done:hover {
|
.bsplus-font-picker-done:hover {
|
||||||
transform: scale(1.03);
|
transform: scale(1.03);
|
||||||
box-shadow: 0 4px 14px
|
box-shadow: 0 4px 14px color-mix(in srgb, var(--bsplus-analytics-accent) 45%, transparent);
|
||||||
color-mix(in srgb, var(--bsplus-analytics-accent) 45%, transparent);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.bsplus-font-picker-done:active {
|
.bsplus-font-picker-done:active {
|
||||||
@@ -199,8 +188,7 @@
|
|||||||
|
|
||||||
.bsplus-font-picker-done:focus-visible {
|
.bsplus-font-picker-done:focus-visible {
|
||||||
outline: none;
|
outline: none;
|
||||||
box-shadow: 0 0 0 3px
|
box-shadow: 0 0 0 3px color-mix(in srgb, var(--bsplus-analytics-accent) 35%, transparent);
|
||||||
color-mix(in srgb, var(--bsplus-analytics-accent) 35%, transparent);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.bsplus-font-picker-list {
|
.bsplus-font-picker-list {
|
||||||
@@ -213,8 +201,7 @@
|
|||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
gap: 0.65rem;
|
gap: 0.65rem;
|
||||||
scrollbar-width: thin;
|
scrollbar-width: thin;
|
||||||
scrollbar-color: color-mix(in srgb, var(--bsplus-analytics-accent) 35%, transparent)
|
scrollbar-color: color-mix(in srgb, var(--bsplus-analytics-accent) 35%, transparent) transparent;
|
||||||
transparent;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.bsplus-font-picker-list::-webkit-scrollbar {
|
.bsplus-font-picker-list::-webkit-scrollbar {
|
||||||
@@ -272,8 +259,7 @@
|
|||||||
var(--bsplus-analytics-accent) 10%,
|
var(--bsplus-analytics-accent) 10%,
|
||||||
var(--bsplus-analytics-surface)
|
var(--bsplus-analytics-surface)
|
||||||
);
|
);
|
||||||
box-shadow: 0 4px 16px
|
box-shadow: 0 4px 16px color-mix(in srgb, var(--bsplus-analytics-accent) 22%, transparent);
|
||||||
color-mix(in srgb, var(--bsplus-analytics-accent) 22%, transparent);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.bsplus-font-picker-option-head {
|
.bsplus-font-picker-option-head {
|
||||||
@@ -302,10 +288,6 @@
|
|||||||
border-radius: 999px;
|
border-radius: 999px;
|
||||||
font-size: 0.7rem;
|
font-size: 0.7rem;
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
background: color-mix(
|
background: color-mix(in srgb, var(--bsplus-analytics-accent) 18%, transparent);
|
||||||
in srgb,
|
|
||||||
var(--bsplus-analytics-accent) 18%,
|
|
||||||
transparent
|
|
||||||
);
|
|
||||||
color: var(--bsplus-analytics-accent);
|
color: var(--bsplus-analytics-accent);
|
||||||
}
|
}
|
||||||
@@ -128,7 +128,7 @@
|
|||||||
|
|
||||||
$effect(() => {
|
$effect(() => {
|
||||||
loadBackground();
|
loadBackground();
|
||||||
selectedBackground
|
void selectedBackground;
|
||||||
});
|
});
|
||||||
|
|
||||||
onMount(() => {
|
onMount(() => {
|
||||||
|
|||||||
@@ -46,11 +46,7 @@ export async function readAllData(): Promise<BackgroundRecord[]> {
|
|||||||
return items;
|
return items;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function writeData(
|
export async function writeData(id: string, type: string, blob: Blob): Promise<void> {
|
||||||
id: string,
|
|
||||||
type: string,
|
|
||||||
blob: Blob,
|
|
||||||
): Promise<void> {
|
|
||||||
const record = { id, type, blob };
|
const record = { id, type, blob };
|
||||||
const db = await openDatabase();
|
const db = await openDatabase();
|
||||||
const tx = db.transaction(STORE, "readwrite");
|
const tx = db.transaction(STORE, "readwrite");
|
||||||
@@ -79,9 +75,7 @@ export async function clearAllData(): Promise<void> {
|
|||||||
await txDone(tx);
|
await txDone(tx);
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getDataById(
|
export async function getDataById(id: string): Promise<BackgroundRecord | undefined> {
|
||||||
id: string,
|
|
||||||
): Promise<BackgroundRecord | undefined> {
|
|
||||||
const db = await openDatabase();
|
const db = await openDatabase();
|
||||||
const tx = db.transaction(STORE, "readonly");
|
const tx = db.transaction(STORE, "readonly");
|
||||||
const item = await req(tx.objectStore(STORE).get(id));
|
const item = await req(tx.objectStore(STORE).get(id));
|
||||||
@@ -100,9 +94,7 @@ export function isIndexedDBSupported(): boolean {
|
|||||||
return "indexedDB" in window;
|
return "indexedDB" in window;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function hasEnoughStorageSpace(
|
export async function hasEnoughStorageSpace(requiredSpace: number): Promise<boolean> {
|
||||||
requiredSpace: number,
|
|
||||||
): Promise<boolean> {
|
|
||||||
if (!("storage" in navigator) || !navigator.storage.estimate) return true;
|
if (!("storage" in navigator) || !navigator.storage.estimate) return true;
|
||||||
const { quota, usage } = await navigator.storage.estimate();
|
const { quota, usage } = await navigator.storage.estimate();
|
||||||
return quota == null || usage == null || quota - usage > requiredSpace;
|
return quota == null || usage == null || quota - usage > requiredSpace;
|
||||||
|
|||||||
@@ -1,6 +1,9 @@
|
|||||||
import browser from "@/lib/browser";
|
import browser from "@/lib/browser";
|
||||||
import type { Theme } from "@/interface/types/Theme";
|
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 { normalizeStoreTheme } from "@/interface/utils/themeStoreFlavours";
|
||||||
import { themeUpdates } from "@/interface/hooks/ThemeUpdates";
|
import { themeUpdates } from "@/interface/hooks/ThemeUpdates";
|
||||||
import { ThemeManager } from "@/plugins/built-in/themes/theme-manager";
|
import { ThemeManager } from "@/plugins/built-in/themes/theme-manager";
|
||||||
@@ -125,9 +128,7 @@ export class CommunityThemesState {
|
|||||||
limit: 50,
|
limit: 50,
|
||||||
})) as { success?: boolean; data?: { themes?: unknown[] }; error?: unknown };
|
})) as { success?: boolean; data?: { themes?: unknown[] }; error?: unknown };
|
||||||
if (!res?.success || !Array.isArray(res.data?.themes)) {
|
if (!res?.success || !Array.isArray(res.data?.themes)) {
|
||||||
throw new Error(
|
throw new Error(typeof res?.error === "string" ? res.error : "Could not load admin themes");
|
||||||
typeof res?.error === "string" ? res.error : "Could not load admin themes",
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
this.reviewThemes = res.data.themes
|
this.reviewThemes = res.data.themes
|
||||||
.map((row) => {
|
.map((row) => {
|
||||||
@@ -161,7 +162,9 @@ export class CommunityThemesState {
|
|||||||
themeUpdates.triggerUpdate();
|
themeUpdates.triggerUpdate();
|
||||||
await this.refreshInstalledThemes();
|
await this.refreshInstalledThemes();
|
||||||
this.selectedThemeId = installedId;
|
this.selectedThemeId = installedId;
|
||||||
void browser.runtime.sendMessage({ type: "cloudSettingsRequestDebouncedUpload" }).catch(() => {});
|
void browser.runtime
|
||||||
|
.sendMessage({ type: "cloudSettingsRequestDebouncedUpload" })
|
||||||
|
.catch(() => {});
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
this.reviewPreviewError = err instanceof Error ? err.message : "Preview failed";
|
this.reviewPreviewError = err instanceof Error ? err.message : "Preview failed";
|
||||||
}
|
}
|
||||||
@@ -242,7 +245,9 @@ export class CommunityThemesState {
|
|||||||
await this.themeManager.setTheme(installedId);
|
await this.themeManager.setTheme(installedId);
|
||||||
themeUpdates.triggerUpdate();
|
themeUpdates.triggerUpdate();
|
||||||
await this.refreshInstalledThemes();
|
await this.refreshInstalledThemes();
|
||||||
void browser.runtime.sendMessage({ type: "cloudSettingsRequestDebouncedUpload" }).catch(() => {});
|
void browser.runtime
|
||||||
|
.sendMessage({ type: "cloudSettingsRequestDebouncedUpload" })
|
||||||
|
.catch(() => {});
|
||||||
}
|
}
|
||||||
|
|
||||||
async removeInstalledTheme(themeId: string) {
|
async removeInstalledTheme(themeId: string) {
|
||||||
@@ -255,7 +260,9 @@ export class CommunityThemesState {
|
|||||||
await this.themeManager.setTheme(themeId);
|
await this.themeManager.setTheme(themeId);
|
||||||
this.selectedThemeId = themeId;
|
this.selectedThemeId = themeId;
|
||||||
themeUpdates.triggerUpdate();
|
themeUpdates.triggerUpdate();
|
||||||
void browser.runtime.sendMessage({ type: "cloudSettingsRequestDebouncedUpload" }).catch(() => {});
|
void browser.runtime
|
||||||
|
.sendMessage({ type: "cloudSettingsRequestDebouncedUpload" })
|
||||||
|
.catch(() => {});
|
||||||
}
|
}
|
||||||
|
|
||||||
async saveMetadata() {
|
async saveMetadata() {
|
||||||
@@ -338,13 +345,13 @@ export class CommunityThemesState {
|
|||||||
});
|
});
|
||||||
|
|
||||||
$effect(() => {
|
$effect(() => {
|
||||||
this.statusFilter;
|
void this.statusFilter;
|
||||||
if (this.innerTab === "mine" && this.cloudLoggedIn) void this.loadMyThemes();
|
if (this.innerTab === "mine" && this.cloudLoggedIn) void this.loadMyThemes();
|
||||||
});
|
});
|
||||||
|
|
||||||
$effect(() => {
|
$effect(() => {
|
||||||
this.reviewStatusFilter;
|
void this.reviewStatusFilter;
|
||||||
this.reviewSourceFilter;
|
void this.reviewSourceFilter;
|
||||||
this.getSearchTerm();
|
this.getSearchTerm();
|
||||||
if (this.innerTab === "review" && this.isAdmin) void this.loadReviewThemes();
|
if (this.innerTab === "review" && this.isAdmin) void this.loadReviewThemes();
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -25,9 +25,7 @@ if (!mountPoint) {
|
|||||||
// In production, Rollup may put this entry in a shared chunk that content
|
// In production, Rollup may put this entry in a shared chunk that content
|
||||||
// scripts load via `import("@/interface/main")`. Only the settings page
|
// scripts load via `import("@/interface/main")`. Only the settings page
|
||||||
// has `#app` — never throw on SEQTA tabs.
|
// has `#app` — never throw on SEQTA tabs.
|
||||||
verboseInfo(
|
verboseInfo("[BetterSEQTA+] Settings bootstrap skipped (no #app — not the settings page)");
|
||||||
"[BetterSEQTA+] Settings bootstrap skipped (no #app — not the settings page)",
|
|
||||||
);
|
|
||||||
} else {
|
} else {
|
||||||
InjectCustomIcons();
|
InjectCustomIcons();
|
||||||
|
|
||||||
|
|||||||
@@ -19,9 +19,7 @@ export default function renderSvelte(
|
|||||||
if (mountPoint instanceof ShadowRoot || props.standalone === true) {
|
if (mountPoint instanceof ShadowRoot || props.standalone === true) {
|
||||||
const styleElement = document.createElement("style");
|
const styleElement = document.createElement("style");
|
||||||
styleElement.textContent = shadowStyles[shadowStyle];
|
styleElement.textContent = shadowStyles[shadowStyle];
|
||||||
(mountPoint instanceof ShadowRoot ? mountPoint : document.head).appendChild(
|
(mountPoint instanceof ShadowRoot ? mountPoint : document.head).appendChild(styleElement);
|
||||||
styleElement,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const app = mount(Component, {
|
const app = mount(Component, {
|
||||||
|
|||||||
@@ -59,8 +59,7 @@ class PluginSettingsStore {
|
|||||||
private async load(): Promise<void> {
|
private async load(): Promise<void> {
|
||||||
const { getAllPluginSettings } = await import("@/plugins");
|
const { getAllPluginSettings } = await import("@/plugins");
|
||||||
this.plugins = getAllPluginSettings().filter(
|
this.plugins = getAllPluginSettings().filter(
|
||||||
(plugin) =>
|
(plugin) => !(isSeqtaEngageExperience() && plugin.pluginId === "global-search"),
|
||||||
!(isSeqtaEngageExperience() && plugin.pluginId === "global-search"),
|
|
||||||
) as PluginSettingsEntry[];
|
) as PluginSettingsEntry[];
|
||||||
|
|
||||||
for (const plugin of this.plugins) {
|
for (const plugin of this.plugins) {
|
||||||
|
|||||||
@@ -23,10 +23,7 @@ export type SettingsSectionSharedProps = {
|
|||||||
searchQuery?: string;
|
searchQuery?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
export function matchesSearch(
|
export function matchesSearch(searchQuery: string, ...parts: Array<string | undefined>): boolean {
|
||||||
searchQuery: string,
|
|
||||||
...parts: Array<string | undefined>
|
|
||||||
): boolean {
|
|
||||||
const q = searchQuery.trim().toLowerCase();
|
const q = searchQuery.trim().toLowerCase();
|
||||||
return !q || parts.some((part) => part?.toLowerCase().includes(q));
|
return !q || parts.some((part) => part?.toLowerCase().includes(q));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -243,7 +243,7 @@
|
|||||||
|
|
||||||
$effect(() => {
|
$effect(() => {
|
||||||
loadBackground();
|
loadBackground();
|
||||||
selectedBackground
|
void selectedBackground;
|
||||||
});
|
});
|
||||||
|
|
||||||
$effect(() => {
|
$effect(() => {
|
||||||
|
|||||||
@@ -6,18 +6,14 @@ import type { Action } from "svelte/action";
|
|||||||
* is rendered inside a shadow DOM. Falls back to document.body otherwise.
|
* is rendered inside a shadow DOM. Falls back to document.body otherwise.
|
||||||
* Pass `document.body` to escape transformed/contained settings popups entirely.
|
* Pass `document.body` to escape transformed/contained settings popups entirely.
|
||||||
*/
|
*/
|
||||||
export const portal: Action<HTMLElement, HTMLElement | ShadowRoot | undefined> = (
|
export const portal: Action<HTMLElement, HTMLElement | ShadowRoot | undefined> = (node, target) => {
|
||||||
node,
|
|
||||||
target,
|
|
||||||
) => {
|
|
||||||
const root = node.getRootNode();
|
const root = node.getRootNode();
|
||||||
const dest = target ?? (root instanceof ShadowRoot ? root : document.body);
|
const dest = target ?? (root instanceof ShadowRoot ? root : document.body);
|
||||||
dest.appendChild(node);
|
dest.appendChild(node);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
update(newTarget) {
|
update(newTarget) {
|
||||||
const nextDest =
|
const nextDest = newTarget ?? (root instanceof ShadowRoot ? root : document.body);
|
||||||
newTarget ?? (root instanceof ShadowRoot ? root : document.body);
|
|
||||||
nextDest.appendChild(node);
|
nextDest.appendChild(node);
|
||||||
},
|
},
|
||||||
destroy() {
|
destroy() {
|
||||||
|
|||||||
@@ -24,17 +24,11 @@ const ACCENT_CSS_VARS = [
|
|||||||
function extractSolidColor(value: string): string | null {
|
function extractSolidColor(value: string): string | null {
|
||||||
const trimmed = value.trim();
|
const trimmed = value.trim();
|
||||||
if (!trimmed || trimmed === "initial") return null;
|
if (!trimmed || trimmed === "initial") return null;
|
||||||
if (
|
if (trimmed.startsWith("#") || trimmed.startsWith("rgb") || trimmed.startsWith("hsl")) {
|
||||||
trimmed.startsWith("#") ||
|
|
||||||
trimmed.startsWith("rgb") ||
|
|
||||||
trimmed.startsWith("hsl")
|
|
||||||
) {
|
|
||||||
return trimmed;
|
return trimmed;
|
||||||
}
|
}
|
||||||
if (trimmed.includes("gradient")) {
|
if (trimmed.includes("gradient")) {
|
||||||
const match = trimmed.match(
|
const match = trimmed.match(/#[0-9A-Fa-f]{6}|#[0-9A-Fa-f]{3}|rgba?\([^)]+\)/i);
|
||||||
/#[0-9A-Fa-f]{6}|#[0-9A-Fa-f]{3}|rgba?\([^)]+\)/i,
|
|
||||||
);
|
|
||||||
return match?.[0] ?? null;
|
return match?.[0] ?? null;
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
@@ -69,8 +63,5 @@ export function syncPageThemeToElement(target: HTMLElement): void {
|
|||||||
target.style.setProperty("--bsplus-analytics-accent", accent);
|
target.style.setProperty("--bsplus-analytics-accent", accent);
|
||||||
target.style.setProperty("--better-main", accent);
|
target.style.setProperty("--better-main", accent);
|
||||||
|
|
||||||
target.classList.toggle(
|
target.classList.toggle("dark", document.documentElement.classList.contains("dark"));
|
||||||
"dark",
|
|
||||||
document.documentElement.classList.contains("dark"),
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
@@ -3,21 +3,20 @@ import { getFontPreset } from "@/seqta/ui/fonts/presets";
|
|||||||
|
|
||||||
describe("themeBuilderDraft", () => {
|
describe("themeBuilderDraft", () => {
|
||||||
it("paints the tint above an opaque photo when blur is disabled", () => {
|
it("paints the tint above an opaque photo when blur is disabled", () => {
|
||||||
const css = buildThemeBuilderCss(
|
const css = buildThemeBuilderCss(getFontPreset("inter"), ["theme-bg-0"], {
|
||||||
getFontPreset("inter"),
|
accentColor: "#00f",
|
||||||
["theme-bg-0"],
|
overlayOpacity: 0.5,
|
||||||
{ accentColor: "#00f", overlayOpacity: 0.5, backgroundBlurPx: 0 },
|
backgroundBlurPx: 0,
|
||||||
);
|
});
|
||||||
const backgroundLayers = css.match(/background-image: (.*) !important;/)?.[1];
|
const backgroundLayers = css.match(/background-image: (.*) !important;/)?.[1];
|
||||||
expect(backgroundLayers).toMatch(/^linear-gradient\(.*\), var\(--theme-bg-0\)$/);
|
expect(backgroundLayers).toMatch(/^linear-gradient\(.*\), var\(--theme-bg-0\)$/);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("builds CSS with font import and image variables", () => {
|
it("builds CSS with font import and image variables", () => {
|
||||||
const css = buildThemeBuilderCss(
|
const css = buildThemeBuilderCss(getFontPreset("inter"), ["theme-bg-0"], {
|
||||||
getFontPreset("inter"),
|
accentColor: "#00f",
|
||||||
["theme-bg-0"],
|
gradientEnd: "#f0f",
|
||||||
{ accentColor: "#00f", gradientEnd: "#f0f" },
|
});
|
||||||
);
|
|
||||||
expect(css).toContain("Inter");
|
expect(css).toContain("Inter");
|
||||||
expect(css).toContain("var(--theme-bg-0)");
|
expect(css).toContain("var(--theme-bg-0)");
|
||||||
expect(css).toContain("#title");
|
expect(css).toContain("#title");
|
||||||
@@ -39,8 +38,8 @@ describe("themeBuilderDraft", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("requires a name", () => {
|
it("requires a name", () => {
|
||||||
expect(() =>
|
expect(() => buildThemeFromDraft({ name: " ", accentColor: "#000", photoBlobs: [] })).toThrow(
|
||||||
buildThemeFromDraft({ name: " ", accentColor: "#000", photoBlobs: [] }),
|
"Theme name is required",
|
||||||
).toThrow("Theme name is required");
|
);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -29,7 +29,12 @@ export function buildThemeBuilderCss(
|
|||||||
imageVariables: string[],
|
imageVariables: string[],
|
||||||
draft: Pick<
|
draft: Pick<
|
||||||
ThemeBuilderDraft,
|
ThemeBuilderDraft,
|
||||||
"accentColor" | "gradientEnd" | "gradientAngle" | "backgroundBlurPx" | "overlayOpacity" | "customCssExtra"
|
| "accentColor"
|
||||||
|
| "gradientEnd"
|
||||||
|
| "gradientAngle"
|
||||||
|
| "backgroundBlurPx"
|
||||||
|
| "overlayOpacity"
|
||||||
|
| "customCssExtra"
|
||||||
>,
|
>,
|
||||||
): string {
|
): string {
|
||||||
const importLine = font.googleUrl ? `@import url("${font.googleUrl}");\n` : "";
|
const importLine = font.googleUrl ? `@import url("${font.googleUrl}");\n` : "";
|
||||||
@@ -45,9 +50,7 @@ export function buildThemeBuilderCss(
|
|||||||
];
|
];
|
||||||
|
|
||||||
const imageLayer =
|
const imageLayer =
|
||||||
imageVariables.length > 0
|
imageVariables.length > 0 ? imageVariables.map((name) => `var(--${name})`).join(", ") : "";
|
||||||
? 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))`;
|
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 {
|
rules.push(`#container {
|
||||||
@@ -126,7 +129,11 @@ export function buildThemeFromDraft(draft: ThemeBuilderDraft): LoadedCustomTheme
|
|||||||
defaultColour: draft.accentColor.trim() || "rgba(0, 123, 255, 1)",
|
defaultColour: draft.accentColor.trim() || "rgba(0, 123, 255, 1)",
|
||||||
CanChangeColour: true,
|
CanChangeColour: true,
|
||||||
allowBackgrounds: true,
|
allowBackgrounds: true,
|
||||||
CustomCSS: buildThemeBuilderCss(font, CustomImages.map((i) => i.variableName), draft),
|
CustomCSS: buildThemeBuilderCss(
|
||||||
|
font,
|
||||||
|
CustomImages.map((i) => i.variableName),
|
||||||
|
draft,
|
||||||
|
),
|
||||||
CustomImages,
|
CustomImages,
|
||||||
coverImage: photoBlobs[0] ?? null,
|
coverImage: photoBlobs[0] ?? null,
|
||||||
isEditable: true,
|
isEditable: true,
|
||||||
|
|||||||
@@ -1,9 +1,6 @@
|
|||||||
import type { LoadedCustomTheme } from "@/types/CustomThemes";
|
import type { LoadedCustomTheme } from "@/types/CustomThemes";
|
||||||
|
|
||||||
export function handleImageUpload(
|
export function handleImageUpload(event: Event, theme: LoadedCustomTheme): LoadedCustomTheme {
|
||||||
event: Event,
|
|
||||||
theme: LoadedCustomTheme,
|
|
||||||
): LoadedCustomTheme {
|
|
||||||
const input = event.target as HTMLInputElement;
|
const input = event.target as HTMLInputElement;
|
||||||
const file = input.files?.[0];
|
const file = input.files?.[0];
|
||||||
input.value = "";
|
input.value = "";
|
||||||
@@ -22,10 +19,7 @@ export function handleImageUpload(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export function handleRemoveImage(
|
export function handleRemoveImage(imageId: string, theme: LoadedCustomTheme): LoadedCustomTheme {
|
||||||
imageId: string,
|
|
||||||
theme: LoadedCustomTheme,
|
|
||||||
): LoadedCustomTheme {
|
|
||||||
return {
|
return {
|
||||||
...theme,
|
...theme,
|
||||||
CustomImages: theme.CustomImages.filter((image) => image.id !== imageId),
|
CustomImages: theme.CustomImages.filter((image) => image.id !== imageId),
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import type { CustomTheme } from '@/types/CustomThemes';
|
import type { CustomTheme } from "@/types/CustomThemes";
|
||||||
import type { Theme } from '@/interface/types/Theme';
|
import type { Theme } from "@/interface/types/Theme";
|
||||||
import {
|
import {
|
||||||
getThemeApplyButtonStyles,
|
getThemeApplyButtonStyles,
|
||||||
getCommunityInstalledThemeIds,
|
getCommunityInstalledThemeIds,
|
||||||
@@ -7,15 +7,17 @@ import {
|
|||||||
isStoreThemeInstalled,
|
isStoreThemeInstalled,
|
||||||
resolveLocalThemeInstallId,
|
resolveLocalThemeInstallId,
|
||||||
resolveStoreVariantAccentColor,
|
resolveStoreVariantAccentColor,
|
||||||
} from './themeListFilters';
|
} from "./themeListFilters";
|
||||||
|
|
||||||
function makeCustomTheme(overrides: Partial<CustomTheme> & Pick<CustomTheme, 'id' | 'name'>): CustomTheme {
|
function makeCustomTheme(
|
||||||
|
overrides: Partial<CustomTheme> & Pick<CustomTheme, "id" | "name">,
|
||||||
|
): CustomTheme {
|
||||||
return {
|
return {
|
||||||
description: '',
|
description: "",
|
||||||
defaultColour: '#000000',
|
defaultColour: "#000000",
|
||||||
CanChangeColour: true,
|
CanChangeColour: true,
|
||||||
allowBackgrounds: true,
|
allowBackgrounds: true,
|
||||||
CustomCSS: '',
|
CustomCSS: "",
|
||||||
CustomImages: [],
|
CustomImages: [],
|
||||||
coverImage: null,
|
coverImage: null,
|
||||||
isEditable: false,
|
isEditable: false,
|
||||||
@@ -24,78 +26,78 @@ function makeCustomTheme(overrides: Partial<CustomTheme> & Pick<CustomTheme, 'id
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function makeStoreTheme(overrides: Partial<Theme> & Pick<Theme, 'id' | 'name'>): Theme {
|
function makeStoreTheme(overrides: Partial<Theme> & Pick<Theme, "id" | "name">): Theme {
|
||||||
return {
|
return {
|
||||||
description: '',
|
description: "",
|
||||||
coverImage: '',
|
coverImage: "",
|
||||||
...overrides,
|
...overrides,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
describe('resolveLocalThemeInstallId', () => {
|
describe("resolveLocalThemeInstallId", () => {
|
||||||
it('keeps store ids and forks local imports that collide with store copies', () => {
|
it("keeps store ids and forks local imports that collide with store copies", () => {
|
||||||
expect(resolveLocalThemeInstallId('theme-1', null, true, false)).toBe('theme-1');
|
expect(resolveLocalThemeInstallId("theme-1", null, true, false)).toBe("theme-1");
|
||||||
const forked = resolveLocalThemeInstallId(
|
const forked = resolveLocalThemeInstallId(
|
||||||
'theme-1',
|
"theme-1",
|
||||||
makeCustomTheme({ id: 'theme-1', name: 'Store', installedFromStore: true }),
|
makeCustomTheme({ id: "theme-1", name: "Store", installedFromStore: true }),
|
||||||
false,
|
false,
|
||||||
false,
|
false,
|
||||||
);
|
);
|
||||||
expect(forked).not.toBe('theme-1');
|
expect(forked).not.toBe("theme-1");
|
||||||
expect(
|
expect(
|
||||||
resolveLocalThemeInstallId(
|
resolveLocalThemeInstallId(
|
||||||
'theme-1',
|
"theme-1",
|
||||||
makeCustomTheme({ id: 'theme-1', name: 'Local' }),
|
makeCustomTheme({ id: "theme-1", name: "Local" }),
|
||||||
false,
|
false,
|
||||||
false,
|
false,
|
||||||
),
|
),
|
||||||
).toBe('theme-1');
|
).toBe("theme-1");
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('installed theme id helpers', () => {
|
describe("installed theme id helpers", () => {
|
||||||
it('returns store-only and community-only ids', () => {
|
it("returns store-only and community-only ids", () => {
|
||||||
const themes = [
|
const themes = [
|
||||||
makeCustomTheme({ id: 'store-1', name: 'Store', installedFromStore: true }),
|
makeCustomTheme({ id: "store-1", name: "Store", installedFromStore: true }),
|
||||||
makeCustomTheme({ id: 'community-1', name: 'Community', installedFromCommunity: true }),
|
makeCustomTheme({ id: "community-1", name: "Community", installedFromCommunity: true }),
|
||||||
makeCustomTheme({ id: 'local-1', name: 'Local' }),
|
makeCustomTheme({ id: "local-1", name: "Local" }),
|
||||||
];
|
];
|
||||||
expect(getStoreInstalledThemeIds(themes)).toEqual(['store-1']);
|
expect(getStoreInstalledThemeIds(themes)).toEqual(["store-1"]);
|
||||||
expect(getCommunityInstalledThemeIds(themes)).toEqual(['community-1']);
|
expect(getCommunityInstalledThemeIds(themes)).toEqual(["community-1"]);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('isStoreThemeInstalled', () => {
|
describe("isStoreThemeInstalled", () => {
|
||||||
it('matches master or flavour ids', () => {
|
it("matches master or flavour ids", () => {
|
||||||
const theme = makeStoreTheme({
|
const theme = makeStoreTheme({
|
||||||
id: 'master-1',
|
id: "master-1",
|
||||||
name: 'Master',
|
name: "Master",
|
||||||
flavours: [{ id: 'flavour-1', name: 'Dark', accent_color: '#000', cover_image: '' }],
|
flavours: [{ id: "flavour-1", name: "Dark", accent_color: "#000", cover_image: "" }],
|
||||||
});
|
});
|
||||||
expect(isStoreThemeInstalled(theme, ['master-1'])).toBe(true);
|
expect(isStoreThemeInstalled(theme, ["master-1"])).toBe(true);
|
||||||
expect(isStoreThemeInstalled(theme, ['flavour-1'])).toBe(true);
|
expect(isStoreThemeInstalled(theme, ["flavour-1"])).toBe(true);
|
||||||
expect(isStoreThemeInstalled(theme, ['other'])).toBe(false);
|
expect(isStoreThemeInstalled(theme, ["other"])).toBe(false);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('resolveStoreVariantAccentColor', () => {
|
describe("resolveStoreVariantAccentColor", () => {
|
||||||
it('prefers installed colours then flavour accents', () => {
|
it("prefers installed colours then flavour accents", () => {
|
||||||
const theme = makeStoreTheme({
|
const theme = makeStoreTheme({
|
||||||
id: 'master-1',
|
id: "master-1",
|
||||||
name: 'Master',
|
name: "Master",
|
||||||
flavours: [{ id: 'flavour-1', name: 'Dark', accent_color: '#112233', cover_image: '' }],
|
flavours: [{ id: "flavour-1", name: "Dark", accent_color: "#112233", cover_image: "" }],
|
||||||
});
|
});
|
||||||
expect(resolveStoreVariantAccentColor(theme, 'flavour-1', { 'flavour-1': '#ff0000' })).toBe(
|
expect(resolveStoreVariantAccentColor(theme, "flavour-1", { "flavour-1": "#ff0000" })).toBe(
|
||||||
'#ff0000',
|
"#ff0000",
|
||||||
);
|
);
|
||||||
expect(resolveStoreVariantAccentColor(theme, 'flavour-1')).toBe('#112233');
|
expect(resolveStoreVariantAccentColor(theme, "flavour-1")).toBe("#112233");
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('getThemeApplyButtonStyles', () => {
|
describe("getThemeApplyButtonStyles", () => {
|
||||||
it('derives apply and applied styles from the accent colour', () => {
|
it("derives apply and applied styles from the accent colour", () => {
|
||||||
const styles = getThemeApplyButtonStyles('#ff0000');
|
const styles = getThemeApplyButtonStyles("#ff0000");
|
||||||
expect(styles.apply).toContain('background-color: #FF0000');
|
expect(styles.apply).toContain("background-color: #FF0000");
|
||||||
expect(styles.applied).toContain('color: #FF0000');
|
expect(styles.applied).toContain("color: #FF0000");
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
import type { CustomTheme } from '@/types/CustomThemes';
|
import type { CustomTheme } from "@/types/CustomThemes";
|
||||||
import type { Theme } from '@/interface/types/Theme';
|
import type { Theme } from "@/interface/types/Theme";
|
||||||
import { parseCssColor } from '@/seqta/ui/colors/parseCssColor';
|
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). */
|
/** Local themes: created in the editor or imported from a file (not store/community). */
|
||||||
export function isLocalCustomTheme(theme: CustomTheme): boolean {
|
export function isLocalCustomTheme(theme: CustomTheme): boolean {
|
||||||
@@ -15,7 +15,7 @@ export function isLocalCustomTheme(theme: CustomTheme): boolean {
|
|||||||
*/
|
*/
|
||||||
export function resolveLocalThemeInstallId(
|
export function resolveLocalThemeInstallId(
|
||||||
themeId: string,
|
themeId: string,
|
||||||
existing: Pick<CustomTheme, 'installedFromStore' | 'installedFromCommunity'> | null,
|
existing: Pick<CustomTheme, "installedFromStore" | "installedFromCommunity"> | null,
|
||||||
fromStore: boolean,
|
fromStore: boolean,
|
||||||
fromCommunity: boolean,
|
fromCommunity: boolean,
|
||||||
): string {
|
): string {
|
||||||
@@ -36,9 +36,7 @@ export function getStoreInstalledThemeIds(themes: CustomTheme[]): string[] {
|
|||||||
|
|
||||||
/** Installed theme ids from the community API only (excludes file imports / custom copies). */
|
/** Installed theme ids from the community API only (excludes file imports / custom copies). */
|
||||||
export function getCommunityInstalledThemeIds(themes: CustomTheme[]): string[] {
|
export function getCommunityInstalledThemeIds(themes: CustomTheme[]): string[] {
|
||||||
return themes
|
return themes.filter((theme) => theme.installedFromCommunity === true).map((theme) => theme.id);
|
||||||
.filter((theme) => theme.installedFromCommunity === true)
|
|
||||||
.map((theme) => theme.id);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function isStoreThemeInstalled(theme: Theme, installedIds: string[]): boolean {
|
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 (flavour?.accent_color?.trim()) return flavour.accent_color.trim();
|
||||||
|
|
||||||
if (variantId === theme.id) {
|
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;
|
if (firstFlavourAccent) return firstFlavourAccent;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -73,7 +73,7 @@ export type ThemeApplyButtonStyles = {
|
|||||||
|
|
||||||
export function getThemeApplyButtonStyles(accentColor: string | undefined): ThemeApplyButtonStyles {
|
export function getThemeApplyButtonStyles(accentColor: string | undefined): ThemeApplyButtonStyles {
|
||||||
const parsed = parseCssColor(accentColor?.trim() || DEFAULT_THEME_ACCENT, DEFAULT_THEME_ACCENT);
|
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 {
|
return {
|
||||||
apply: `background-color: ${parsed.hex()}; color: ${onAccent};`,
|
apply: `background-color: ${parsed.hex()}; color: ${onAccent};`,
|
||||||
|
|||||||
@@ -1,7 +1,4 @@
|
|||||||
import {
|
import { createDefaultThemeCoverSvg, defaultThemeCoverDataUrl } from "./themePlaceholderCover";
|
||||||
createDefaultThemeCoverSvg,
|
|
||||||
defaultThemeCoverDataUrl,
|
|
||||||
} from "./themePlaceholderCover";
|
|
||||||
|
|
||||||
describe("themePlaceholderCover", () => {
|
describe("themePlaceholderCover", () => {
|
||||||
it("builds an svg cover placeholder", () => {
|
it("builds an svg cover placeholder", () => {
|
||||||
|
|||||||
@@ -7,24 +7,22 @@ export function isHiddenStoreTheme(theme: Theme): boolean {
|
|||||||
/** Coerce API / fallback rows into the store `Theme` shape (camelCase images, safe strings). */
|
/** Coerce API / fallback rows into the store `Theme` shape (camelCase images, safe strings). */
|
||||||
export function normalizeStoreTheme(raw: Record<string, unknown>): Theme {
|
export function normalizeStoreTheme(raw: Record<string, unknown>): Theme {
|
||||||
const flavours = Array.isArray(raw.flavours)
|
const flavours = Array.isArray(raw.flavours)
|
||||||
? (raw.flavours as Record<string, unknown>[]).map(
|
? (raw.flavours as Record<string, unknown>[]).map((f): ThemeFlavour => ({
|
||||||
(f): ThemeFlavour => ({
|
id: String(f.id ?? ""),
|
||||||
id: String(f.id ?? ""),
|
name: String(f.name ?? ""),
|
||||||
name: String(f.name ?? ""),
|
accent_color: String(f.accent_color ?? f.accentColor ?? ""),
|
||||||
accent_color: String(f.accent_color ?? f.accentColor ?? ""),
|
cover_image: String(f.cover_image ?? f.coverImage ?? ""),
|
||||||
cover_image: String(f.cover_image ?? f.coverImage ?? ""),
|
marquee_image:
|
||||||
marquee_image:
|
typeof (f.marquee_image ?? f.marqueeImage) === "string"
|
||||||
typeof (f.marquee_image ?? f.marqueeImage) === "string"
|
? String(f.marquee_image ?? f.marqueeImage)
|
||||||
? String(f.marquee_image ?? f.marqueeImage)
|
: undefined,
|
||||||
|
download_count:
|
||||||
|
typeof f.download_count === "number"
|
||||||
|
? f.download_count
|
||||||
|
: typeof f.downloadCount === "number"
|
||||||
|
? f.downloadCount
|
||||||
: undefined,
|
: undefined,
|
||||||
download_count:
|
}))
|
||||||
typeof f.download_count === "number"
|
|
||||||
? f.download_count
|
|
||||||
: typeof f.downloadCount === "number"
|
|
||||||
? f.downloadCount
|
|
||||||
: undefined,
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
: undefined;
|
: undefined;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -3,14 +3,12 @@ import { resolveExtensionAssetUrl } from "./extensionAssetUrl";
|
|||||||
|
|
||||||
describe("resolveExtensionAssetUrl", () => {
|
describe("resolveExtensionAssetUrl", () => {
|
||||||
it("returns already-resolved extension URLs unchanged", () => {
|
it("returns already-resolved extension URLs unchanged", () => {
|
||||||
const url =
|
const url = "chrome-extension://abc/assets/IconFamily-B8lopphU.woff";
|
||||||
"chrome-extension://abc/assets/IconFamily-B8lopphU.woff";
|
|
||||||
expect(resolveExtensionAssetUrl(url)).toBe(url);
|
expect(resolveExtensionAssetUrl(url)).toBe(url);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("repairs accidental double extension URL prefix", () => {
|
it("repairs accidental double extension URL prefix", () => {
|
||||||
const doubled =
|
const doubled = "chrome-extension://abc/chrome-extension://abc/assets/IconFamily-B8lopphU.woff";
|
||||||
"chrome-extension://abc/chrome-extension://abc/assets/IconFamily-B8lopphU.woff";
|
|
||||||
expect(resolveExtensionAssetUrl(doubled)).toBe(
|
expect(resolveExtensionAssetUrl(doubled)).toBe(
|
||||||
"chrome-extension://abc/assets/IconFamily-B8lopphU.woff",
|
"chrome-extension://abc/assets/IconFamily-B8lopphU.woff",
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -7,4 +7,3 @@ export function resolveExtensionAssetUrl(url: string): string {
|
|||||||
if (/^(?:chrome|moz)-extension:\/\/|https?:|data:/.test(url)) return url;
|
if (/^(?:chrome|moz)-extension:\/\/|https?:|data:/.test(url)) return url;
|
||||||
return browser.runtime.getURL(url.replace(/^\/+/, ""));
|
return browser.runtime.getURL(url.replace(/^\/+/, ""));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2,5 +2,4 @@
|
|||||||
export const LUCIDE_MOON_PATH =
|
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";
|
"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 = `<path fill="currentColor" d="${LUCIDE_MOON_PATH}"/>`;
|
||||||
`<path fill="currentColor" d="${LUCIDE_MOON_PATH}"/>`;
|
|
||||||
@@ -2,5 +2,4 @@
|
|||||||
export const LUCIDE_SUN_PATH =
|
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";
|
"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 = `<path fill="currentColor" d="${LUCIDE_SUN_PATH}"/>`;
|
||||||
`<path fill="currentColor" d="${LUCIDE_SUN_PATH}"/>`;
|
|
||||||
@@ -13,15 +13,14 @@ function extensionAssetUrl(relativePath: string): string {
|
|||||||
* instead of CDN (required on SEQTA pages where page CSP blocks jsdelivr).
|
* instead of CDN (required on SEQTA pages where page CSP blocks jsdelivr).
|
||||||
* Safe to call multiple times; must run before embeddia `initializeModel()`.
|
* Safe to call multiple times; must run before embeddia `initializeModel()`.
|
||||||
*/
|
*/
|
||||||
export async function ensureTransformersEnv(
|
export async function ensureTransformersEnv(ortWasmBase?: string): Promise<void> {
|
||||||
ortWasmBase?: string,
|
|
||||||
): Promise<void> {
|
|
||||||
if (configured) return;
|
if (configured) return;
|
||||||
|
|
||||||
const { env } = await import("@huggingface/transformers");
|
const { env } = await import("@huggingface/transformers");
|
||||||
const base = ortWasmBase ?? extensionAssetUrl(ORT_RESOURCE_DIR);
|
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;
|
configured = true;
|
||||||
}
|
}
|
||||||
@@ -32,9 +31,7 @@ export function getOrtWasmBaseUrl(): string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** For page-origin blob workers that cannot call `browser.runtime.getURL`. */
|
/** For page-origin blob workers that cannot call `browser.runtime.getURL`. */
|
||||||
export async function configureTransformersEnvForBase(
|
export async function configureTransformersEnvForBase(ortWasmBase: string): Promise<void> {
|
||||||
ortWasmBase: string,
|
|
||||||
): Promise<void> {
|
|
||||||
configured = false;
|
configured = false;
|
||||||
await ensureTransformersEnv(ortWasmBase);
|
await ensureTransformersEnv(ortWasmBase);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,10 @@ import type { Manifest } from "../../lib/types.ts";
|
|||||||
import baseManifest from "./manifest.json" with { type: "json" };
|
import baseManifest from "./manifest.json" with { type: "json" };
|
||||||
import pkg from "../../package.json" with { type: "json" };
|
import pkg from "../../package.json" with { type: "json" };
|
||||||
|
|
||||||
type BrowserSpecificSettings = Extract<Manifest, { manifest_version: number }>["browser_specific_settings"];
|
type BrowserSpecificSettings = Extract<
|
||||||
|
Manifest,
|
||||||
|
{ manifest_version: number }
|
||||||
|
>["browser_specific_settings"];
|
||||||
|
|
||||||
const safariSettings = {
|
const safariSettings = {
|
||||||
safari: {
|
safari: {
|
||||||
|
|||||||
+129
-94
@@ -10,7 +10,7 @@ class ReactFiber {
|
|||||||
console.log("Selected Nodes:", this.nodes);
|
console.log("Selected Nodes:", this.nodes);
|
||||||
console.log("🔍 Found Fibers:", this.fibers);
|
console.log("🔍 Found Fibers:", this.fibers);
|
||||||
console.log("🛠 Found Components:", this.components);
|
console.log("🛠 Found Components:", this.components);
|
||||||
|
|
||||||
this.fibers.forEach((fiber, index) => {
|
this.fibers.forEach((fiber, index) => {
|
||||||
if (fiber) {
|
if (fiber) {
|
||||||
console.log(`Fiber ${index}:`, {
|
console.log(`Fiber ${index}:`, {
|
||||||
@@ -19,7 +19,7 @@ class ReactFiber {
|
|||||||
elementType: fiber.elementType,
|
elementType: fiber.elementType,
|
||||||
stateNode: fiber.stateNode,
|
stateNode: fiber.stateNode,
|
||||||
hasState: !!fiber.stateNode?.state,
|
hasState: !!fiber.stateNode?.state,
|
||||||
hasMemoizedState: !!fiber.memoizedState
|
hasMemoizedState: !!fiber.memoizedState,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -32,25 +32,25 @@ class ReactFiber {
|
|||||||
|
|
||||||
getFiberNode(node) {
|
getFiberNode(node) {
|
||||||
if (!node) return null;
|
if (!node) return null;
|
||||||
|
|
||||||
// Try multiple property name patterns for different React versions
|
// Try multiple property name patterns for different React versions
|
||||||
const possibleKeys = [
|
const possibleKeys = [
|
||||||
'__reactFiber$', // React 16+
|
"__reactFiber$", // React 16+
|
||||||
'__reactInternalFiber$', // React 15
|
"__reactInternalFiber$", // React 15
|
||||||
'__reactInternalInstance$', // Older versions
|
"__reactInternalInstance$", // Older versions
|
||||||
'__reactFiber',
|
"__reactFiber",
|
||||||
'__reactInternalInstance'
|
"__reactInternalInstance",
|
||||||
];
|
];
|
||||||
|
|
||||||
for (const key of possibleKeys) {
|
for (const key of possibleKeys) {
|
||||||
if (node[key]) return node[key];
|
if (node[key]) return node[key];
|
||||||
}
|
}
|
||||||
|
|
||||||
const fiberKey = Object.getOwnPropertyNames(node).find(
|
const fiberKey = Object.getOwnPropertyNames(node).find(
|
||||||
(name) =>
|
(name) =>
|
||||||
name.startsWith("__reactFiber") ||
|
name.startsWith("__reactFiber") ||
|
||||||
name.startsWith("__reactInternalInstance") ||
|
name.startsWith("__reactInternalInstance") ||
|
||||||
name.startsWith("__reactInternalFiber")
|
name.startsWith("__reactInternalFiber"),
|
||||||
);
|
);
|
||||||
return fiberKey ? node[fiberKey] : null;
|
return fiberKey ? node[fiberKey] : null;
|
||||||
}
|
}
|
||||||
@@ -60,16 +60,18 @@ class ReactFiber {
|
|||||||
while (current) {
|
while (current) {
|
||||||
// Use React's internal tag system to identify component types
|
// Use React's internal tag system to identify component types
|
||||||
// Based on React's WorkTags: ClassComponent = 1, FunctionComponent = 0
|
// 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
|
return current.stateNode; // For class components, stateNode is the component instance
|
||||||
}
|
}
|
||||||
|
|
||||||
// For function components, look for hooks in memoizedState
|
// 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
|
// Function components don't have setState, but we can still track them
|
||||||
if (current.memoizedState && current.type) {
|
if (current.memoizedState && current.type) {
|
||||||
return {
|
return {
|
||||||
type: 'function',
|
type: "function",
|
||||||
hooks: current.memoizedState,
|
hooks: current.memoizedState,
|
||||||
fiber: current,
|
fiber: current,
|
||||||
forceUpdate: () => {
|
forceUpdate: () => {
|
||||||
@@ -78,21 +80,21 @@ class ReactFiber {
|
|||||||
current.alternate.expirationTime = 1;
|
current.alternate.expirationTime = 1;
|
||||||
}
|
}
|
||||||
current.expirationTime = 1;
|
current.expirationTime = 1;
|
||||||
}
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Legacy fallback: check if stateNode has React component methods
|
// Legacy fallback: check if stateNode has React component methods
|
||||||
if (
|
if (
|
||||||
current.stateNode &&
|
current.stateNode &&
|
||||||
current.stateNode !== null &&
|
current.stateNode !== null &&
|
||||||
typeof current.stateNode === 'object' &&
|
typeof current.stateNode === "object" &&
|
||||||
(current.stateNode.setState || current.stateNode.forceUpdate)
|
(current.stateNode.setState || current.stateNode.forceUpdate)
|
||||||
) {
|
) {
|
||||||
return current.stateNode;
|
return current.stateNode;
|
||||||
}
|
}
|
||||||
|
|
||||||
current = current.return;
|
current = current.return;
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
@@ -100,11 +102,11 @@ class ReactFiber {
|
|||||||
|
|
||||||
getState(key) {
|
getState(key) {
|
||||||
if (!this.components.length && !this.fibers.length) return null;
|
if (!this.components.length && !this.fibers.length) return null;
|
||||||
|
|
||||||
const component = this.components[0];
|
const component = this.components[0];
|
||||||
const fiber = this.fibers[0];
|
const fiber = this.fibers[0];
|
||||||
let state = null;
|
let state = null;
|
||||||
|
|
||||||
if (component?.state) {
|
if (component?.state) {
|
||||||
state = component.state;
|
state = component.state;
|
||||||
}
|
}
|
||||||
@@ -118,7 +120,7 @@ class ReactFiber {
|
|||||||
state = states.length === 1 ? states[0] : states;
|
state = states.length === 1 ? states[0] : states;
|
||||||
}
|
}
|
||||||
// Fallback: try component hooks if available
|
// 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);
|
const states = this.extractStateFromHooks(component.hooks);
|
||||||
state = states.length === 1 ? states[0] : states;
|
state = states.length === 1 ? states[0] : states;
|
||||||
}
|
}
|
||||||
@@ -144,33 +146,34 @@ class ReactFiber {
|
|||||||
let mainStateFound = false;
|
let mainStateFound = false;
|
||||||
let currentHook = hookChain;
|
let currentHook = hookChain;
|
||||||
let hookIndex = 0;
|
let hookIndex = 0;
|
||||||
|
|
||||||
if (this.debug) {
|
if (this.debug) {
|
||||||
console.log("🔍 Hook chain analysis:");
|
console.log("🔍 Hook chain analysis:");
|
||||||
}
|
}
|
||||||
|
|
||||||
while (currentHook) {
|
while (currentHook) {
|
||||||
if (this.debug) {
|
if (this.debug) {
|
||||||
console.log(`Hook ${hookIndex}:`, {
|
console.log(`Hook ${hookIndex}:`, {
|
||||||
type: currentHook.tag || 'unknown',
|
type: currentHook.tag || "unknown",
|
||||||
memoizedState: currentHook.memoizedState,
|
memoizedState: currentHook.memoizedState,
|
||||||
queue: currentHook.queue,
|
queue: currentHook.queue,
|
||||||
next: !!currentHook.next
|
next: !!currentHook.next,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// Try different approaches to extract state
|
// Try different approaches to extract state
|
||||||
if (currentHook.memoizedState !== undefined && currentHook.memoizedState !== null) {
|
if (currentHook.memoizedState !== undefined && currentHook.memoizedState !== null) {
|
||||||
const state = currentHook.memoizedState;
|
const state = currentHook.memoizedState;
|
||||||
|
|
||||||
// Priority 1: Check for useRef hooks with complex state in .current
|
// Priority 1: Check for useRef hooks with complex state in .current
|
||||||
if (!currentHook.queue &&
|
if (
|
||||||
typeof state === 'object' &&
|
!currentHook.queue &&
|
||||||
state !== null &&
|
typeof state === "object" &&
|
||||||
state.current !== undefined &&
|
state !== null &&
|
||||||
typeof state.current === 'object' &&
|
state.current !== undefined &&
|
||||||
state.current !== null) {
|
typeof state.current === "object" &&
|
||||||
|
state.current !== null
|
||||||
|
) {
|
||||||
// Check if this looks like a substantial state object (has multiple properties)
|
// Check if this looks like a substantial state object (has multiple properties)
|
||||||
const currentKeys = Object.keys(state.current);
|
const currentKeys = Object.keys(state.current);
|
||||||
if (currentKeys.length > 2) {
|
if (currentKeys.length > 2) {
|
||||||
@@ -180,12 +183,17 @@ class ReactFiber {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Priority 2: useState hooks with queue
|
// Priority 2: useState hooks with queue
|
||||||
else if (currentHook.queue && typeof state !== 'function') {
|
else if (currentHook.queue && typeof state !== "function") {
|
||||||
states.push(state);
|
states.push(state);
|
||||||
if (this.debug) console.log(` ✅ Found useState state:`, state);
|
if (this.debug) console.log(` ✅ Found useState state:`, state);
|
||||||
}
|
}
|
||||||
// Priority 3: Other potential state objects (only if we haven't found main 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)
|
// Skip useEffect hooks (they have tag 36)
|
||||||
if (!(state.tag === 36 && state.create)) {
|
if (!(state.tag === 36 && state.create)) {
|
||||||
states.push(state);
|
states.push(state);
|
||||||
@@ -193,77 +201,78 @@ class ReactFiber {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Priority 4: Simple primitive state
|
// Priority 4: Simple primitive state
|
||||||
else if (typeof state !== 'function' && typeof state !== 'object') {
|
else if (typeof state !== "function" && typeof state !== "object") {
|
||||||
states.push(state);
|
states.push(state);
|
||||||
if (this.debug) console.log(` 🔹 Found primitive state:`, state);
|
if (this.debug) console.log(` 🔹 Found primitive state:`, state);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
currentHook = currentHook.next;
|
currentHook = currentHook.next;
|
||||||
hookIndex++;
|
hookIndex++;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.debug) {
|
if (this.debug) {
|
||||||
console.log(`🎯 Extracted ${states.length} state values:`, states);
|
console.log(`🎯 Extracted ${states.length} state values:`, states);
|
||||||
}
|
}
|
||||||
|
|
||||||
// If we found main state objects, prioritize and deduplicate them
|
// If we found main state objects, prioritize and deduplicate them
|
||||||
if (mainStateFound && states.length > 1) {
|
if (mainStateFound && states.length > 1) {
|
||||||
const mainStates = states.filter(state =>
|
const mainStates = states.filter(
|
||||||
typeof state === 'object' &&
|
(state) => typeof state === "object" && state !== null && Object.keys(state).length > 2,
|
||||||
state !== null &&
|
|
||||||
Object.keys(state).length > 2
|
|
||||||
);
|
);
|
||||||
|
|
||||||
if (mainStates.length > 1) {
|
if (mainStates.length > 1) {
|
||||||
// If we have multiple main state objects, find the most comprehensive one
|
// If we have multiple main state objects, find the most comprehensive one
|
||||||
// or merge them if they seem complementary
|
// or merge them if they seem complementary
|
||||||
const largestState = mainStates.reduce((largest, current) => {
|
const largestState = mainStates.reduce((largest, current) => {
|
||||||
const largestKeys = Object.keys(largest).length;
|
const largestKeys = Object.keys(largest).length;
|
||||||
const currentKeys = Object.keys(current).length;
|
const currentKeys = Object.keys(current).length;
|
||||||
|
|
||||||
// Prefer the one with more properties
|
// Prefer the one with more properties
|
||||||
if (currentKeys > largestKeys) return current;
|
if (currentKeys > largestKeys) return current;
|
||||||
|
|
||||||
// If same number of properties, prefer the one with more complex data
|
// If same number of properties, prefer the one with more complex data
|
||||||
if (currentKeys === largestKeys) {
|
if (currentKeys === largestKeys) {
|
||||||
const largestComplexity = this.calculateStateComplexity(largest);
|
const largestComplexity = this.calculateStateComplexity(largest);
|
||||||
const currentComplexity = this.calculateStateComplexity(current);
|
const currentComplexity = this.calculateStateComplexity(current);
|
||||||
return currentComplexity > largestComplexity ? current : largest;
|
return currentComplexity > largestComplexity ? current : largest;
|
||||||
}
|
}
|
||||||
|
|
||||||
return largest;
|
return largest;
|
||||||
});
|
});
|
||||||
|
|
||||||
if (this.debug) {
|
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 [largestState];
|
||||||
}
|
}
|
||||||
|
|
||||||
return mainStates;
|
return mainStates;
|
||||||
}
|
}
|
||||||
|
|
||||||
return states;
|
return states;
|
||||||
}
|
}
|
||||||
|
|
||||||
calculateStateComplexity(state) {
|
calculateStateComplexity(state) {
|
||||||
if (!state || typeof state !== 'object') return 0;
|
if (!state || typeof state !== "object") return 0;
|
||||||
|
|
||||||
let complexity = 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
|
complexity += 1; // Base point for each property
|
||||||
|
|
||||||
if (Array.isArray(value)) {
|
if (Array.isArray(value)) {
|
||||||
complexity += value.length * 0.1; // Arrays get points based on length
|
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
|
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
|
complexity += 2; // Functions are valuable
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return complexity;
|
return complexity;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -273,8 +282,7 @@ class ReactFiber {
|
|||||||
if (typeof update === "function") {
|
if (typeof update === "function") {
|
||||||
component.setState((prevState) => {
|
component.setState((prevState) => {
|
||||||
const newState = update(prevState);
|
const newState = update(prevState);
|
||||||
if (this.debug)
|
if (this.debug) console.log("✅ Updated State (Functional):", newState);
|
||||||
console.log("✅ Updated State (Functional):", newState);
|
|
||||||
return newState;
|
return newState;
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
@@ -284,16 +292,17 @@ class ReactFiber {
|
|||||||
...prevState,
|
...prevState,
|
||||||
...update,
|
...update,
|
||||||
};
|
};
|
||||||
if (this.debug)
|
if (this.debug) console.log("✅ Updated State (Object Merge):", newState);
|
||||||
console.log("✅ Updated State (Object Merge):", newState);
|
|
||||||
return newState;
|
return newState;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Handle function components - force re-render since we can't directly update hooks
|
// 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) {
|
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();
|
component.forceUpdate();
|
||||||
}
|
}
|
||||||
@@ -335,11 +344,11 @@ function makeSerializable(obj, visited = new WeakSet(), depth = 0, maxDepth = 10
|
|||||||
if (obj === null || obj === undefined) {
|
if (obj === null || obj === undefined) {
|
||||||
return obj;
|
return obj;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (typeof obj === "function") {
|
if (typeof obj === "function") {
|
||||||
return `[Function: ${obj.name || 'anonymous'}]`;
|
return `[Function: ${obj.name || "anonymous"}]`;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (typeof obj !== "object") {
|
if (typeof obj !== "object") {
|
||||||
if (typeof obj === "symbol") return obj.toString();
|
if (typeof obj === "symbol") return obj.toString();
|
||||||
if (typeof obj === "bigint") return obj.toString() + "n";
|
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,
|
tagName: obj.tagName,
|
||||||
id: obj.id || null,
|
id: obj.id || null,
|
||||||
className: obj.className || 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 {
|
return {
|
||||||
type: "Event",
|
type: "Event",
|
||||||
eventType: obj.type,
|
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 {
|
return {
|
||||||
type: "ReactFiber",
|
type: "ReactFiber",
|
||||||
tag: obj.tag,
|
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,
|
key: obj.key,
|
||||||
hasState: !!obj.stateNode?.state,
|
hasState: !!obj.stateNode?.state,
|
||||||
hasMemoizedState: !!obj.memoizedState,
|
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 = {};
|
const serializableObj = {};
|
||||||
|
|
||||||
// Get own enumerable properties only to avoid prototype pollution
|
// Get own enumerable properties only to avoid prototype pollution
|
||||||
const ownKeys = Object.getOwnPropertyNames(obj).filter(key => {
|
const ownKeys = Object.getOwnPropertyNames(obj).filter((key) => {
|
||||||
try {
|
try {
|
||||||
return obj.propertyIsEnumerable(key);
|
return obj.propertyIsEnumerable(key);
|
||||||
} catch {
|
} catch {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// Limit number of properties to avoid huge objects
|
// Limit number of properties to avoid huge objects
|
||||||
const maxKeys = 30;
|
const maxKeys = 30;
|
||||||
const processedKeys = ownKeys.slice(0, maxKeys);
|
const processedKeys = ownKeys.slice(0, maxKeys);
|
||||||
|
|
||||||
for (const key of processedKeys) {
|
for (const key of processedKeys) {
|
||||||
try {
|
try {
|
||||||
const dangerousKeys = [
|
const dangerousKeys = [
|
||||||
'parentNode', 'parentElement', 'ownerDocument', 'children', 'childNodes',
|
"parentNode",
|
||||||
'return', 'child', 'sibling', 'alternate', 'ref', // React Fiber circular refs
|
"parentElement",
|
||||||
'_owner', '_source', '_self', '_debugOwner', '_debugSource', // React internals
|
"ownerDocument",
|
||||||
'window', 'document', 'global', 'self', 'top', 'parent', // Global objects
|
"children",
|
||||||
'constructor', 'prototype', '__proto__', // Constructor/prototype chains
|
"childNodes",
|
||||||
'addEventListener', 'removeEventListener', // Event handlers
|
"return",
|
||||||
'setState', 'forceUpdate', 'render' // React methods that might be functions
|
"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)) {
|
if (dangerousKeys.includes(key)) {
|
||||||
serializableObj[key] = `[Skipped: ${key}]`;
|
serializableObj[key] = `[Skipped: ${key}]`;
|
||||||
continue;
|
continue;
|
||||||
@@ -449,10 +485,9 @@ function makeSerializable(obj, visited = new WeakSet(), depth = 0, maxDepth = 10
|
|||||||
|
|
||||||
// Handle symbols specifically (React context symbols)
|
// Handle symbols specifically (React context symbols)
|
||||||
if (typeof value === "symbol") {
|
if (typeof value === "symbol") {
|
||||||
value = `[Symbol: ${value.description || 'anonymous'}]`;
|
value = `[Symbol: ${value.description || "anonymous"}]`;
|
||||||
}
|
} else if (typeof value === "function") {
|
||||||
else if (typeof value === "function") {
|
value = `[Function: ${value.name || "anonymous"}]`;
|
||||||
value = `[Function: ${value.name || 'anonymous'}]`;
|
|
||||||
} else if (value && typeof value === "object") {
|
} else if (value && typeof value === "object") {
|
||||||
value = makeSerializable(value, visited, depth + 1, maxDepth);
|
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}]`;
|
serializableObj[key] = `[Error: ${error.message}]`;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (ownKeys.length > maxKeys) {
|
if (ownKeys.length > maxKeys) {
|
||||||
serializableObj['...'] = `[${ownKeys.length - maxKeys} more properties]`;
|
serializableObj["..."] = `[${ownKeys.length - maxKeys} more properties]`;
|
||||||
}
|
}
|
||||||
|
|
||||||
return serializableObj;
|
return serializableObj;
|
||||||
@@ -480,14 +515,14 @@ function deepFunctionCheck(obj, path = "") {
|
|||||||
if (typeof obj === "function") {
|
if (typeof obj === "function") {
|
||||||
throw new Error(`Found function at path: ${path}`);
|
throw new Error(`Found function at path: ${path}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (obj && typeof obj === "object") {
|
if (obj && typeof obj === "object") {
|
||||||
if (Array.isArray(obj)) {
|
if (Array.isArray(obj)) {
|
||||||
obj.forEach((item, index) => {
|
obj.forEach((item, index) => {
|
||||||
deepFunctionCheck(item, `${path}[${index}]`);
|
deepFunctionCheck(item, `${path}[${index}]`);
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
Object.keys(obj).forEach(key => {
|
Object.keys(obj).forEach((key) => {
|
||||||
deepFunctionCheck(obj[key], path ? `${path}.${key}` : key);
|
deepFunctionCheck(obj[key], path ? `${path}.${key}` : key);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,6 @@
|
|||||||
import { BasePlugin } from "../../core/settings";
|
import { BasePlugin } from "../../core/settings";
|
||||||
import { type Plugin } from "@/plugins/core/types";
|
import { type Plugin } from "@/plugins/core/types";
|
||||||
import {
|
import { defineSettings, numberSetting, Setting } from "@/plugins/core/settingsHelpers";
|
||||||
defineSettings,
|
|
||||||
numberSetting,
|
|
||||||
Setting,
|
|
||||||
} from "@/plugins/core/settingsHelpers";
|
|
||||||
import styles from "./styles.css?inline";
|
import styles from "./styles.css?inline";
|
||||||
import {
|
import {
|
||||||
removeAnimatedBackgroundLayers,
|
removeAnimatedBackgroundLayers,
|
||||||
|
|||||||
@@ -5,8 +5,7 @@ import appstorelight from "@/resources/icons/dlappstore-light.svg";
|
|||||||
import gplayicon from "@/resources/icons/googleplay.svg";
|
import gplayicon from "@/resources/icons/googleplay.svg";
|
||||||
import styles from "./styles.css?inline";
|
import styles from "./styles.css?inline";
|
||||||
|
|
||||||
const APPSTORE =
|
const APPSTORE = 'a[href="https://itunes.apple.com/au/app/seqta-learn/id1143069793"]>img';
|
||||||
'a[href="https://itunes.apple.com/au/app/seqta-learn/id1143069793"]>img';
|
|
||||||
const GOOGLEPLAY =
|
const GOOGLEPLAY =
|
||||||
'a[href="https://play.google.com/store/apps/details?id=com.seqta.android.learn"]>img';
|
'a[href="https://play.google.com/store/apps/details?id=com.seqta.android.learn"]>img';
|
||||||
|
|
||||||
|
|||||||
@@ -9,25 +9,20 @@ export async function requestEngageAssessmentPdf(params: {
|
|||||||
}): Promise<string> {
|
}): Promise<string> {
|
||||||
const fileName = randomPdfFileName();
|
const fileName = randomPdfFileName();
|
||||||
|
|
||||||
const response = await fetch(
|
const response = await fetch(`${location.origin}/seqta/parent/print/assessment?${Date.now()}`, {
|
||||||
`${location.origin}/seqta/parent/print/assessment?${Date.now()}`,
|
method: "POST",
|
||||||
{
|
headers: { "Content-Type": "application/json; charset=utf-8" },
|
||||||
method: "POST",
|
credentials: "include",
|
||||||
headers: { "Content-Type": "application/json; charset=utf-8" },
|
body: JSON.stringify({
|
||||||
credentials: "include",
|
id: params.assessmentID,
|
||||||
body: JSON.stringify({
|
metaclass: params.metaclassID,
|
||||||
id: params.assessmentID,
|
student: Number(params.studentID),
|
||||||
metaclass: params.metaclassID,
|
fileName,
|
||||||
student: Number(params.studentID),
|
}),
|
||||||
fileName,
|
});
|
||||||
}),
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
throw new Error(
|
throw new Error(`Failed to generate PDF: ${response.status} ${response.statusText}`);
|
||||||
`Failed to generate PDF: ${response.status} ${response.statusText}`,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const data = (await response.json()) as {
|
const data = (await response.json()) as {
|
||||||
|
|||||||
@@ -2,27 +2,19 @@ import { extractWeightFromCoversheetText } from "./extractWeightFromCoversheetTe
|
|||||||
|
|
||||||
describe("extractWeightFromCoversheetText", () => {
|
describe("extractWeightFromCoversheetText", () => {
|
||||||
it("matches Weight: N", () => {
|
it("matches Weight: N", () => {
|
||||||
expect(extractWeightFromCoversheetText("Due date ... Weight: 20 Subject")).toBe(
|
expect(extractWeightFromCoversheetText("Due date ... Weight: 20 Subject")).toBe("20");
|
||||||
"20",
|
|
||||||
);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it("matches Weighting: N%", () => {
|
it("matches Weighting: N%", () => {
|
||||||
expect(
|
expect(extractWeightFromCoversheetText("Assessment Weighting: 12.5% of semester")).toBe("12.5");
|
||||||
extractWeightFromCoversheetText("Assessment Weighting: 12.5% of semester"),
|
|
||||||
).toBe("12.5");
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it("matches Assessment weight: N", () => {
|
it("matches Assessment weight: N", () => {
|
||||||
expect(
|
expect(extractWeightFromCoversheetText("Assessment weight: 15\nCriteria")).toBe("15");
|
||||||
extractWeightFromCoversheetText("Assessment weight: 15\nCriteria"),
|
|
||||||
).toBe("15");
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it("matches Weight of N%", () => {
|
it("matches Weight of N%", () => {
|
||||||
expect(extractWeightFromCoversheetText("This task has a weight of 10%")).toBe(
|
expect(extractWeightFromCoversheetText("This task has a weight of 10%")).toBe("10");
|
||||||
"10",
|
|
||||||
);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it("returns null when no weighting is present", () => {
|
it("returns null when no weighting is present", () => {
|
||||||
|
|||||||
@@ -12,7 +12,6 @@ import {
|
|||||||
} from "./utils.ts";
|
} from "./utils.ts";
|
||||||
import { injectRubricCopyButtons, teardownRubricCopyButtons } from "./rubricCopy.ts";
|
import { injectRubricCopyButtons, teardownRubricCopyButtons } from "./rubricCopy.ts";
|
||||||
|
|
||||||
|
|
||||||
let overrideListenerController: AbortController | null = null;
|
let overrideListenerController: AbortController | null = null;
|
||||||
let wrapperColourObserver: MutationObserver | null = null;
|
let wrapperColourObserver: MutationObserver | null = null;
|
||||||
let wrapperColourObserverTimeout: ReturnType<typeof setTimeout> | null = null;
|
let wrapperColourObserverTimeout: ReturnType<typeof setTimeout> | null = null;
|
||||||
@@ -25,61 +24,59 @@ const assessmentsAveragePlugin = {
|
|||||||
const { unregister: unregisterWrapperMount } = api.seqta.onMount(
|
const { unregister: unregisterWrapperMount } = api.seqta.onMount(
|
||||||
".assessmentsWrapper",
|
".assessmentsWrapper",
|
||||||
async () => {
|
async () => {
|
||||||
await waitForElm(
|
await waitForElm(
|
||||||
"#main > .assessmentsWrapper .assessments [class*='AssessmentItem__AssessmentItem___']",
|
"#main > .assessmentsWrapper .assessments [class*='AssessmentItem__AssessmentItem___']",
|
||||||
true,
|
true,
|
||||||
10,
|
10,
|
||||||
1000,
|
1000,
|
||||||
);
|
);
|
||||||
|
|
||||||
// Wire listeners first so the very first re-render triggered by a
|
// Wire listeners first so the very first re-render triggered by a
|
||||||
// background handleWeightings completion can find them.
|
// background handleWeightings completion can find them.
|
||||||
overrideListenerController?.abort();
|
overrideListenerController?.abort();
|
||||||
overrideListenerController = new AbortController();
|
overrideListenerController = new AbortController();
|
||||||
document.addEventListener(
|
document.addEventListener("betterseqta:overrideChanged", () => renderSubjectAverage(api), {
|
||||||
"betterseqta:overrideChanged",
|
signal: overrideListenerController.signal,
|
||||||
() => 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();
|
|
||||||
});
|
});
|
||||||
wrapperColourObserver.observe(wrapper, { childList: true, subtree: true });
|
document.addEventListener(
|
||||||
wrapperColourObserverTimeout = setTimeout(() => {
|
"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?.disconnect();
|
||||||
wrapperColourObserver = null;
|
if (wrapperColourObserverTimeout) {
|
||||||
wrapperColourObserverTimeout = null;
|
clearTimeout(wrapperColourObserverTimeout);
|
||||||
}, 10000);
|
}
|
||||||
}
|
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(
|
const { unregister: unregisterSelectedMount } = api.seqta.onMount(
|
||||||
"[class*='SelectedAssessment__']",
|
"[class*='SelectedAssessment__']",
|
||||||
() => {
|
() => {
|
||||||
injectWeightingsTab(api);
|
injectWeightingsTab(api);
|
||||||
injectRubricCopyButtons();
|
injectRubricCopyButtons();
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
@@ -117,9 +114,7 @@ async function renderSubjectAverage(api: any) {
|
|||||||
if (!assessmentsList) return;
|
if (!assessmentsList) return;
|
||||||
|
|
||||||
// Remove existing subject average before re-rendering
|
// Remove existing subject average before re-rendering
|
||||||
Array.from(
|
Array.from(assessmentsList.querySelectorAll(`[class*='AssessmentItem__title___']`))
|
||||||
assessmentsList.querySelectorAll(`[class*='AssessmentItem__title___']`),
|
|
||||||
)
|
|
||||||
.find((el) => el.textContent === "Subject Average")
|
.find((el) => el.textContent === "Subject Average")
|
||||||
?.closest("[class*='AssessmentItem__AssessmentItem___']")
|
?.closest("[class*='AssessmentItem__AssessmentItem___']")
|
||||||
?.remove();
|
?.remove();
|
||||||
@@ -136,23 +131,15 @@ async function renderSubjectAverage(api: any) {
|
|||||||
sampleAssessmentItem,
|
sampleAssessmentItem,
|
||||||
"AssessmentItem__metaContainer___",
|
"AssessmentItem__metaContainer___",
|
||||||
);
|
);
|
||||||
const metaClass = getClassByPattern(
|
const metaClass = getClassByPattern(sampleAssessmentItem, "AssessmentItem__meta___");
|
||||||
sampleAssessmentItem,
|
|
||||||
"AssessmentItem__meta___",
|
|
||||||
);
|
|
||||||
const simpleResultClass = getClassByPattern(
|
const simpleResultClass = getClassByPattern(
|
||||||
sampleAssessmentItem,
|
sampleAssessmentItem,
|
||||||
"AssessmentItem__simpleResult___",
|
"AssessmentItem__simpleResult___",
|
||||||
);
|
);
|
||||||
const titleClass = getClassByPattern(
|
const titleClass = getClassByPattern(sampleAssessmentItem, "AssessmentItem__title___");
|
||||||
sampleAssessmentItem,
|
|
||||||
"AssessmentItem__title___",
|
|
||||||
);
|
|
||||||
|
|
||||||
const assessmentItems = Array.from(
|
const assessmentItems = Array.from(
|
||||||
assessmentsList.querySelectorAll<HTMLElement>(
|
assessmentsList.querySelectorAll<HTMLElement>(`[class*='AssessmentItem__AssessmentItem___']`),
|
||||||
`[class*='AssessmentItem__AssessmentItem___']`,
|
|
||||||
),
|
|
||||||
).filter(
|
).filter(
|
||||||
(item) =>
|
(item) =>
|
||||||
!item
|
!item
|
||||||
@@ -160,31 +147,18 @@ async function renderSubjectAverage(api: any) {
|
|||||||
?.textContent?.includes("Subject Average"),
|
?.textContent?.includes("Subject Average"),
|
||||||
);
|
);
|
||||||
|
|
||||||
const {
|
const { weightedTotal, totalWeight, hasInaccurateWeighting, hasRefreshingWeighting, count } =
|
||||||
weightedTotal,
|
await processAssessments(api, assessmentItems);
|
||||||
totalWeight,
|
|
||||||
hasInaccurateWeighting,
|
|
||||||
hasRefreshingWeighting,
|
|
||||||
count,
|
|
||||||
} = await processAssessments(api, assessmentItems);
|
|
||||||
if (!count || totalWeight === 0) return;
|
if (!count || totalWeight === 0) return;
|
||||||
|
|
||||||
const thermoscoreElement = document.querySelector(
|
const thermoscoreElement = document.querySelector("[class*='Thermoscore__Thermoscore___']");
|
||||||
"[class*='Thermoscore__Thermoscore___']",
|
|
||||||
);
|
|
||||||
if (!thermoscoreElement) return;
|
if (!thermoscoreElement) return;
|
||||||
const thermoscoreClass =
|
const thermoscoreClass =
|
||||||
Array.from(thermoscoreElement.classList).find((c) =>
|
Array.from(thermoscoreElement.classList).find((c) =>
|
||||||
c.startsWith("Thermoscore__Thermoscore___"),
|
c.startsWith("Thermoscore__Thermoscore___"),
|
||||||
) || "";
|
) || "";
|
||||||
const fillClass = getClassByPattern(
|
const fillClass = getClassByPattern(thermoscoreElement, "Thermoscore__fill___");
|
||||||
thermoscoreElement,
|
const textClass = getClassByPattern(thermoscoreElement, "Thermoscore__text___");
|
||||||
"Thermoscore__fill___",
|
|
||||||
);
|
|
||||||
const textClass = getClassByPattern(
|
|
||||||
thermoscoreElement,
|
|
||||||
"Thermoscore__text___",
|
|
||||||
);
|
|
||||||
|
|
||||||
const avg = weightedTotal / totalWeight;
|
const avg = weightedTotal / totalWeight;
|
||||||
const rounded = Math.ceil(avg / 5) * 5;
|
const rounded = Math.ceil(avg / 5) * 5;
|
||||||
@@ -246,11 +220,11 @@ async function renderSubjectAverage(api: any) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
function applySubjectColourToOverallResult() {
|
function applySubjectColourToOverallResult() {
|
||||||
const selectedAssessmentItem = document.querySelector(
|
const selectedAssessmentItem =
|
||||||
"[class*='AssessmentItem__AssessmentItem___'][class*='selected___']",
|
document.querySelector("[class*='AssessmentItem__AssessmentItem___'][class*='selected___']") ||
|
||||||
) || document.querySelector(
|
document.querySelector(
|
||||||
"[class*='Collapsible__content___'] [class*='AssessmentItem__AssessmentItem___']",
|
"[class*='Collapsible__content___'] [class*='AssessmentItem__AssessmentItem___']",
|
||||||
);
|
);
|
||||||
const assessmentThermoscore = selectedAssessmentItem?.querySelector(
|
const assessmentThermoscore = selectedAssessmentItem?.querySelector(
|
||||||
"[class*='Thermoscore__Thermoscore___']",
|
"[class*='Thermoscore__Thermoscore___']",
|
||||||
) as HTMLElement | null;
|
) as HTMLElement | null;
|
||||||
@@ -263,10 +237,22 @@ function applySubjectColourToOverallResult() {
|
|||||||
|
|
||||||
if (assessmentThermoscore && (overallResult || assessableCriterionHeaders.length > 0)) {
|
if (assessmentThermoscore && (overallResult || assessableCriterionHeaders.length > 0)) {
|
||||||
const accentColour =
|
const accentColour =
|
||||||
getComputedStyle(assessmentThermoscore).getPropertyValue("--assessment-accent-colour").trim() ||
|
getComputedStyle(assessmentThermoscore)
|
||||||
|
.getPropertyValue("--assessment-accent-colour")
|
||||||
|
.trim() ||
|
||||||
getComputedStyle(assessmentThermoscore).getPropertyValue("--fill-colour").trim() ||
|
getComputedStyle(assessmentThermoscore).getPropertyValue("--fill-colour").trim() ||
|
||||||
getComputedStyle(assessmentThermoscore.closest("[class*='Collapsible__Collapsible___']") || assessmentThermoscore).getPropertyValue("--assessment-accent-colour").trim() ||
|
getComputedStyle(
|
||||||
getComputedStyle(assessmentThermoscore.closest("[class*='Collapsible__Collapsible___']") || assessmentThermoscore).getPropertyValue("--item-colour").trim();
|
assessmentThermoscore.closest("[class*='Collapsible__Collapsible___']") ||
|
||||||
|
assessmentThermoscore,
|
||||||
|
)
|
||||||
|
.getPropertyValue("--assessment-accent-colour")
|
||||||
|
.trim() ||
|
||||||
|
getComputedStyle(
|
||||||
|
assessmentThermoscore.closest("[class*='Collapsible__Collapsible___']") ||
|
||||||
|
assessmentThermoscore,
|
||||||
|
)
|
||||||
|
.getPropertyValue("--item-colour")
|
||||||
|
.trim();
|
||||||
if (accentColour) {
|
if (accentColour) {
|
||||||
overallResult?.style.setProperty("--assessment-accent-colour", accentColour);
|
overallResult?.style.setProperty("--assessment-accent-colour", accentColour);
|
||||||
overallResult?.style.setProperty("--fill-colour", accentColour);
|
overallResult?.style.setProperty("--fill-colour", accentColour);
|
||||||
|
|||||||
@@ -152,9 +152,7 @@ function parseRubricTable(rubric: Element): RubricTableData | null {
|
|||||||
lines.forEach((line) => {
|
lines.forEach((line) => {
|
||||||
const meta = line.querySelector("[class*='Rubric__meta___']");
|
const meta = line.querySelector("[class*='Rubric__meta___']");
|
||||||
const label = cellText(meta?.querySelector("[class*='Rubric__label___']"));
|
const label = cellText(meta?.querySelector("[class*='Rubric__label___']"));
|
||||||
const criterion = cellText(
|
const criterion = cellText(meta?.querySelector("[class*='Rubric__description___']"));
|
||||||
meta?.querySelector("[class*='Rubric__description___']"),
|
|
||||||
);
|
|
||||||
|
|
||||||
const row: RubricCell[] = [
|
const row: RubricCell[] = [
|
||||||
{ text: label, selected: false },
|
{ text: label, selected: false },
|
||||||
@@ -162,9 +160,7 @@ function parseRubricTable(rubric: Element): RubricTableData | null {
|
|||||||
];
|
];
|
||||||
|
|
||||||
line.querySelectorAll("[class*='Rubric__descriptor___']").forEach((descriptor) => {
|
line.querySelectorAll("[class*='Rubric__descriptor___']").forEach((descriptor) => {
|
||||||
const text = cellText(
|
const text = cellText(descriptor.querySelector("[class*='Rubric__description___']"));
|
||||||
descriptor.querySelector("[class*='Rubric__description___']"),
|
|
||||||
);
|
|
||||||
const selected = Array.from(descriptor.classList).some((cls) =>
|
const selected = Array.from(descriptor.classList).some((cls) =>
|
||||||
cls.startsWith("Rubric__selected___"),
|
cls.startsWith("Rubric__selected___"),
|
||||||
);
|
);
|
||||||
@@ -198,10 +194,9 @@ function rubricToPlainText(table: RubricTableData): string {
|
|||||||
const formatCell = (cell: RubricCell) =>
|
const formatCell = (cell: RubricCell) =>
|
||||||
cell.selected && cell.text ? `${cell.text} (selected)` : cell.text;
|
cell.selected && cell.text ? `${cell.text} (selected)` : cell.text;
|
||||||
|
|
||||||
return [
|
return [table.header.join("\t"), ...table.rows.map((row) => row.map(formatCell).join("\t"))].join(
|
||||||
table.header.join("\t"),
|
"\n",
|
||||||
...table.rows.map((row) => row.map(formatCell).join("\t")),
|
);
|
||||||
].join("\n");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const RUBRIC_PASTE_FONT_PT = 7;
|
const RUBRIC_PASTE_FONT_PT = 7;
|
||||||
@@ -222,16 +217,12 @@ function rubricPasteCellContent(text: string): string {
|
|||||||
|
|
||||||
function rubricToHtmlTable(table: RubricTableData): string {
|
function rubricToHtmlTable(table: RubricTableData): string {
|
||||||
const baseFont = rubricPasteFontStyle();
|
const baseFont = rubricPasteFontStyle();
|
||||||
const cellStyle =
|
const cellStyle = `border:1px solid #000000;border-collapse:collapse;padding:4px;vertical-align:top;${baseFont}`;
|
||||||
`border:1px solid #000000;border-collapse:collapse;padding:4px;vertical-align:top;${baseFont}`;
|
|
||||||
const headerStyle = `${cellStyle}background:#f3f4f6;font-weight:700;`;
|
const headerStyle = `${cellStyle}background:#f3f4f6;font-weight:700;`;
|
||||||
const selectedStyle = `${cellStyle}background:#dbeafe;font-weight:600;`;
|
const selectedStyle = `${cellStyle}background:#dbeafe;font-weight:600;`;
|
||||||
|
|
||||||
const headerRow = table.header
|
const headerRow = table.header
|
||||||
.map(
|
.map((heading) => `<th style="${headerStyle}">${rubricPasteCellContent(heading)}</th>`)
|
||||||
(heading) =>
|
|
||||||
`<th style="${headerStyle}">${rubricPasteCellContent(heading)}</th>`,
|
|
||||||
)
|
|
||||||
.join("");
|
.join("");
|
||||||
|
|
||||||
const bodyRows = table.rows
|
const bodyRows = table.rows
|
||||||
@@ -258,7 +249,7 @@ function rubricToHtmlDocument(table: RubricTableData): string {
|
|||||||
return [
|
return [
|
||||||
"<!DOCTYPE html>",
|
"<!DOCTYPE html>",
|
||||||
"<html>",
|
"<html>",
|
||||||
"<head><meta charset=\"utf-8\"></head>",
|
'<head><meta charset="utf-8"></head>',
|
||||||
`<body style="${rubricPasteFontStyle()}">`,
|
`<body style="${rubricPasteFontStyle()}">`,
|
||||||
rubricToHtmlTable(table),
|
rubricToHtmlTable(table),
|
||||||
"</body>",
|
"</body>",
|
||||||
@@ -348,8 +339,7 @@ function watchRubrics(root: ParentNode) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function injectRubricCopyButtons() {
|
export function injectRubricCopyButtons() {
|
||||||
const root =
|
const root = document.querySelector("[class*='SelectedAssessment__']") ?? document;
|
||||||
document.querySelector("[class*='SelectedAssessment__']") ?? document;
|
|
||||||
watchRubrics(root);
|
watchRubrics(root);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -7,10 +7,7 @@ import {
|
|||||||
randomPdfFileName,
|
randomPdfFileName,
|
||||||
requestEngageAssessmentPdf,
|
requestEngageAssessmentPdf,
|
||||||
} from "./engage.ts";
|
} from "./engage.ts";
|
||||||
import {
|
import { ensurePdfjsWorker, getPdfjsPageContextUrls } from "@/lib/pdfjsExtension.ts";
|
||||||
ensurePdfjsWorker,
|
|
||||||
getPdfjsPageContextUrls,
|
|
||||||
} from "@/lib/pdfjsExtension.ts";
|
|
||||||
import * as pdfjs from "pdfjs-dist";
|
import * as pdfjs from "pdfjs-dist";
|
||||||
import { extractWeightFromCoversheetText } from "./extractWeightFromCoversheetText";
|
import { extractWeightFromCoversheetText } from "./extractWeightFromCoversheetText";
|
||||||
import { delay } from "@/seqta/utils/delay";
|
import { delay } from "@/seqta/utils/delay";
|
||||||
@@ -83,9 +80,7 @@ async function resolveAssessmentId(
|
|||||||
|
|
||||||
if (!resolvedMarks) {
|
if (!resolvedMarks) {
|
||||||
try {
|
try {
|
||||||
const state = await ReactFiber.find(
|
const state = await ReactFiber.find("[class*='AssessmentList__items___']").getState();
|
||||||
"[class*='AssessmentList__items___']",
|
|
||||||
).getState();
|
|
||||||
resolvedMarks = collectMarksFromFiberState(state);
|
resolvedMarks = collectMarksFromFiberState(state);
|
||||||
} catch {
|
} catch {
|
||||||
resolvedMarks = [];
|
resolvedMarks = [];
|
||||||
@@ -115,8 +110,7 @@ async function resolveAssessmentId(
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function computeFingerprint(mark: any): string {
|
export function computeFingerprint(mark: any): string {
|
||||||
const score =
|
const score = mark?.results?.percentage ?? mark?.results?.score ?? null;
|
||||||
mark?.results?.percentage ?? mark?.results?.score ?? null;
|
|
||||||
return JSON.stringify([
|
return JSON.stringify([
|
||||||
mark?.status ?? "",
|
mark?.status ?? "",
|
||||||
Boolean(mark?.graded),
|
Boolean(mark?.graded),
|
||||||
@@ -199,10 +193,7 @@ export function clearStuck(api: any) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Helper function to find actual class names by their base pattern
|
// Helper function to find actual class names by their base pattern
|
||||||
export const getClassByPattern = (
|
export const getClassByPattern = (element: Element | Document, basePattern: string): string => {
|
||||||
element: Element | Document,
|
|
||||||
basePattern: string,
|
|
||||||
): string => {
|
|
||||||
const classes = Array.from(element.querySelectorAll("*"))
|
const classes = Array.from(element.querySelectorAll("*"))
|
||||||
.flatMap((el) => Array.from(el.classList))
|
.flatMap((el) => Array.from(el.classList))
|
||||||
.filter((className) => className.startsWith(basePattern));
|
.filter((className) => className.startsWith(basePattern));
|
||||||
@@ -271,16 +262,10 @@ function saveWeightingOverride(
|
|||||||
return { ok: true };
|
return { ok: true };
|
||||||
}
|
}
|
||||||
|
|
||||||
function attachWeightInputListeners(
|
function attachWeightInputListeners(input: HTMLInputElement, api: any, assessmentID: string) {
|
||||||
input: HTMLInputElement,
|
|
||||||
api: any,
|
|
||||||
assessmentID: string,
|
|
||||||
) {
|
|
||||||
const save = () => {
|
const save = () => {
|
||||||
const result = saveWeightingOverride(api, assessmentID, input.value);
|
const result = saveWeightingOverride(api, assessmentID, input.value);
|
||||||
input.style.borderColor = result.ok
|
input.style.borderColor = result.ok ? "rgba(128,128,128,0.35)" : "rgba(255,80,80,0.6)";
|
||||||
? "rgba(128,128,128,0.35)"
|
|
||||||
: "rgba(255,80,80,0.6)";
|
|
||||||
};
|
};
|
||||||
|
|
||||||
input.addEventListener("blur", save);
|
input.addEventListener("blur", save);
|
||||||
@@ -336,10 +321,7 @@ function updateWeightLabelContent(
|
|||||||
|
|
||||||
const span = document.createElement("span");
|
const span = document.createElement("span");
|
||||||
span.className = "betterseqta-weight-value";
|
span.className = "betterseqta-weight-value";
|
||||||
const baseText =
|
const baseText = weighting && weighting !== "N/A" ? formatWeightDisplay(weighting) : "N/A";
|
||||||
weighting && weighting !== "N/A"
|
|
||||||
? formatWeightDisplay(weighting)
|
|
||||||
: "N/A";
|
|
||||||
span.textContent = refreshing ? `${baseText} ↻` : baseText;
|
span.textContent = refreshing ? `${baseText} ↻` : baseText;
|
||||||
if (refreshing) {
|
if (refreshing) {
|
||||||
span.style.opacity = "0.7";
|
span.style.opacity = "0.7";
|
||||||
@@ -375,25 +357,16 @@ function createWeightLabel(
|
|||||||
const hasNativeLabel = !!statsContainer.querySelector(
|
const hasNativeLabel = !!statsContainer.querySelector(
|
||||||
`[class*='Label__Label___']:not(.betterseqta-weight-label)`,
|
`[class*='Label__Label___']:not(.betterseqta-weight-label)`,
|
||||||
);
|
);
|
||||||
statsContainer.style.justifyContent = hasNativeLabel
|
statsContainer.style.justifyContent = hasNativeLabel ? "space-between" : "flex-end";
|
||||||
? "space-between"
|
|
||||||
: "flex-end";
|
|
||||||
|
|
||||||
const resolvedAssessmentId =
|
const resolvedAssessmentId = assessmentID ?? assessmentItem.dataset.betterseqtaAssessmentId;
|
||||||
assessmentID ?? assessmentItem.dataset.betterseqtaAssessmentId;
|
|
||||||
|
|
||||||
const existingLabel = statsContainer.querySelector(
|
const existingLabel = statsContainer.querySelector(
|
||||||
".betterseqta-weight-label",
|
".betterseqta-weight-label",
|
||||||
) as HTMLElement | null;
|
) as HTMLElement | null;
|
||||||
|
|
||||||
if (existingLabel) {
|
if (existingLabel) {
|
||||||
updateWeightLabelContent(
|
updateWeightLabelContent(existingLabel, weighting, resolvedAssessmentId, api, refreshing);
|
||||||
existingLabel,
|
|
||||||
weighting,
|
|
||||||
resolvedAssessmentId,
|
|
||||||
api,
|
|
||||||
refreshing,
|
|
||||||
);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -410,13 +383,13 @@ function createWeightLabel(
|
|||||||
const weightLabel = existingNativeLabel
|
const weightLabel = existingNativeLabel
|
||||||
? (existingNativeLabel.cloneNode(true) as HTMLElement)
|
? (existingNativeLabel.cloneNode(true) as HTMLElement)
|
||||||
: (() => {
|
: (() => {
|
||||||
const labelClass = getClassByPattern(document, "Label__Label___");
|
const labelClass = getClassByPattern(document, "Label__Label___");
|
||||||
const innerTextClass = getClassByPattern(document, "Label__innerText___");
|
const innerTextClass = getClassByPattern(document, "Label__innerText___");
|
||||||
const el = document.createElement("label");
|
const el = document.createElement("label");
|
||||||
el.className = labelClass;
|
el.className = labelClass;
|
||||||
el.innerHTML = `<div class="${innerTextClass}">Weight</div>`;
|
el.innerHTML = `<div class="${innerTextClass}">Weight</div>`;
|
||||||
return el;
|
return el;
|
||||||
})();
|
})();
|
||||||
|
|
||||||
weightLabel.classList.add("betterseqta-weight-label");
|
weightLabel.classList.add("betterseqta-weight-label");
|
||||||
weightLabel.style.flex = "none";
|
weightLabel.style.flex = "none";
|
||||||
@@ -425,13 +398,7 @@ function createWeightLabel(
|
|||||||
const innerTextDiv = weightLabel.querySelector(`[class*='Label__innerText___']`);
|
const innerTextDiv = weightLabel.querySelector(`[class*='Label__innerText___']`);
|
||||||
if (innerTextDiv) innerTextDiv.textContent = "Weight";
|
if (innerTextDiv) innerTextDiv.textContent = "Weight";
|
||||||
|
|
||||||
updateWeightLabelContent(
|
updateWeightLabelContent(weightLabel, weighting, resolvedAssessmentId, api, refreshing);
|
||||||
weightLabel,
|
|
||||||
weighting,
|
|
||||||
resolvedAssessmentId,
|
|
||||||
api,
|
|
||||||
refreshing,
|
|
||||||
);
|
|
||||||
statsContainer.appendChild(weightLabel);
|
statsContainer.appendChild(weightLabel);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -525,9 +492,7 @@ async function fetchPDFAsArrayBuffer(url: string): Promise<ArrayBuffer> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
throw new Error(
|
throw new Error(`Failed to fetch PDF: ${response.status} ${response.statusText}`);
|
||||||
`Failed to fetch PDF: ${response.status} ${response.statusText}`,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return await response.arrayBuffer();
|
return await response.arrayBuffer();
|
||||||
@@ -546,8 +511,7 @@ async function fetchPDFAsArrayBuffer(url: string): Promise<ArrayBuffer> {
|
|||||||
export async function extractPDFText(url: string): Promise<string> {
|
export async function extractPDFText(url: string): Promise<string> {
|
||||||
try {
|
try {
|
||||||
if (isFirefox) {
|
if (isFirefox) {
|
||||||
const { lib: pdfLibUrl, worker: pdfWorkerUrl } =
|
const { lib: pdfLibUrl, worker: pdfWorkerUrl } = getPdfjsPageContextUrls();
|
||||||
getPdfjsPageContextUrls();
|
|
||||||
const pdfLibInj = escJsSingleQuoted(pdfLibUrl);
|
const pdfLibInj = escJsSingleQuoted(pdfLibUrl);
|
||||||
const pdfWorkerInj = escJsSingleQuoted(pdfWorkerUrl);
|
const pdfWorkerInj = escJsSingleQuoted(pdfWorkerUrl);
|
||||||
|
|
||||||
@@ -630,9 +594,7 @@ export async function extractPDFText(url: string): Promise<string> {
|
|||||||
if (event.data.success) {
|
if (event.data.success) {
|
||||||
resolve(event.data.text);
|
resolve(event.data.text);
|
||||||
} else {
|
} else {
|
||||||
reject(
|
reject(new Error(event.data.error || "Failed to extract PDF text"));
|
||||||
new Error(event.data.error || "Failed to extract PDF text"),
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -679,7 +641,6 @@ export async function extractPDFText(url: string): Promise<string> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
async function requestStudentAssessmentPdf(params: {
|
async function requestStudentAssessmentPdf(params: {
|
||||||
assessmentID: string | number;
|
assessmentID: string | number;
|
||||||
metaclassID: string | number;
|
metaclassID: string | number;
|
||||||
@@ -687,25 +648,20 @@ async function requestStudentAssessmentPdf(params: {
|
|||||||
}): Promise<string> {
|
}): Promise<string> {
|
||||||
const fileName = randomPdfFileName();
|
const fileName = randomPdfFileName();
|
||||||
|
|
||||||
const printResponse = await fetch(
|
const printResponse = await fetch(`${location.origin}/seqta/student/print/assessment`, {
|
||||||
`${location.origin}/seqta/student/print/assessment`,
|
method: "POST",
|
||||||
{
|
headers: { "Content-Type": "application/json; charset=utf-8" },
|
||||||
method: "POST",
|
credentials: "include",
|
||||||
headers: { "Content-Type": "application/json; charset=utf-8" },
|
body: JSON.stringify({
|
||||||
credentials: "include",
|
id: Number(params.assessmentID),
|
||||||
body: JSON.stringify({
|
metaclass: Number(params.metaclassID),
|
||||||
id: Number(params.assessmentID),
|
student: Number(params.studentID),
|
||||||
metaclass: Number(params.metaclassID),
|
fileName,
|
||||||
student: Number(params.studentID),
|
}),
|
||||||
fileName,
|
});
|
||||||
}),
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
if (!printResponse.ok) {
|
if (!printResponse.ok) {
|
||||||
throw new Error(
|
throw new Error(`Failed to generate PDF: ${printResponse.status} ${printResponse.statusText}`);
|
||||||
`Failed to generate PDF: ${printResponse.status} ${printResponse.statusText}`,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const data = (await printResponse.json()) as {
|
const data = (await printResponse.json()) as {
|
||||||
@@ -731,11 +687,7 @@ function getStudentAssessmentReportUrl(fileName: string): string {
|
|||||||
return `${location.origin}/seqta/student/load/file?${params.toString()}`;
|
return `${location.origin}/seqta/student/load/file?${params.toString()}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function extractPDFTextWithRetry(
|
async function extractPDFTextWithRetry(url: string, attempts = 3, delayMs = 1500): Promise<string> {
|
||||||
url: string,
|
|
||||||
attempts = 3,
|
|
||||||
delayMs = 1500,
|
|
||||||
): Promise<string> {
|
|
||||||
let lastError: unknown;
|
let lastError: unknown;
|
||||||
for (let attempt = 0; attempt < attempts; attempt++) {
|
for (let attempt = 0; attempt < attempts; attempt++) {
|
||||||
try {
|
try {
|
||||||
@@ -759,9 +711,7 @@ async function handleWeightings(mark: any, api: any) {
|
|||||||
const metaclassID = mark.metaclassID;
|
const metaclassID = mark.metaclassID;
|
||||||
|
|
||||||
const fingerprint = computeFingerprint(mark);
|
const fingerprint = computeFingerprint(mark);
|
||||||
const existing = api.storage.weightings[assessmentID] as
|
const existing = api.storage.weightings[assessmentID] as WeightingEntry | undefined;
|
||||||
| WeightingEntry
|
|
||||||
| undefined;
|
|
||||||
|
|
||||||
// Skip only when we already have a real numeric weight for this fingerprint.
|
// Skip only when we already have a real numeric weight for this fingerprint.
|
||||||
// "N/A" / "processing" / in-flight refreshing must not permanently block retries.
|
// "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) {
|
} catch (error: any) {
|
||||||
console.error(
|
console.error(`[BetterSEQTA+] Weighting fetch failed for assessment ${assessmentID}:`, error);
|
||||||
`[BetterSEQTA+] Weighting fetch failed for assessment ${assessmentID}:`,
|
|
||||||
error,
|
|
||||||
);
|
|
||||||
api.storage.weightings = {
|
api.storage.weightings = {
|
||||||
...api.storage.weightings,
|
...api.storage.weightings,
|
||||||
[assessmentID]: {
|
[assessmentID]: {
|
||||||
@@ -893,9 +840,7 @@ async function handleWeightings(mark: any, api: any) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function parseAssessments(api: any) {
|
export async function parseAssessments(api: any) {
|
||||||
const state = await ReactFiber.find(
|
const state = await ReactFiber.find("[class*='AssessmentList__items___']").getState();
|
||||||
"[class*='AssessmentList__items___']",
|
|
||||||
).getState();
|
|
||||||
|
|
||||||
const marks = [
|
const marks = [
|
||||||
...(state["marks"] ?? []),
|
...(state["marks"] ?? []),
|
||||||
@@ -917,18 +862,14 @@ export async function processAssessments(api: any, assessmentItems: HTMLElement[
|
|||||||
|
|
||||||
let fiberMarks: MarkLike[];
|
let fiberMarks: MarkLike[];
|
||||||
try {
|
try {
|
||||||
const state = await ReactFiber.find(
|
const state = await ReactFiber.find("[class*='AssessmentList__items___']").getState();
|
||||||
"[class*='AssessmentList__items___']",
|
|
||||||
).getState();
|
|
||||||
fiberMarks = collectMarksFromFiberState(state);
|
fiberMarks = collectMarksFromFiberState(state);
|
||||||
} catch {
|
} catch {
|
||||||
fiberMarks = [];
|
fiberMarks = [];
|
||||||
}
|
}
|
||||||
|
|
||||||
for (const assessmentItem of assessmentItems) {
|
for (const assessmentItem of assessmentItems) {
|
||||||
const titleEl = assessmentItem.querySelector(
|
const titleEl = assessmentItem.querySelector(`[class*='AssessmentItem__title___']`);
|
||||||
`[class*='AssessmentItem__title___']`,
|
|
||||||
);
|
|
||||||
if (!titleEl) continue;
|
if (!titleEl) continue;
|
||||||
|
|
||||||
const title = titleEl.textContent?.trim();
|
const title = titleEl.textContent?.trim();
|
||||||
@@ -942,17 +883,13 @@ export async function processAssessments(api: any, assessmentItems: HTMLElement[
|
|||||||
? (api.storage.weightings?.[assessmentID] as WeightingEntry | undefined)
|
? (api.storage.weightings?.[assessmentID] as WeightingEntry | undefined)
|
||||||
: undefined;
|
: undefined;
|
||||||
const autoWeighting = entry?.weight;
|
const autoWeighting = entry?.weight;
|
||||||
const override = assessmentID
|
const override = assessmentID ? api.storage.weightingOverrides?.[assessmentID] : undefined;
|
||||||
? api.storage.weightingOverrides?.[assessmentID]
|
|
||||||
: undefined;
|
|
||||||
const weighting = override ?? autoWeighting;
|
const weighting = override ?? autoWeighting;
|
||||||
const refreshing = !override && Boolean(entry?.refreshing);
|
const refreshing = !override && Boolean(entry?.refreshing);
|
||||||
|
|
||||||
createWeightLabel(assessmentItem, weighting, api, refreshing, assessmentID);
|
createWeightLabel(assessmentItem, weighting, api, refreshing, assessmentID);
|
||||||
|
|
||||||
const gradeElement = assessmentItem.querySelector(
|
const gradeElement = assessmentItem.querySelector(`[class*='Thermoscore__text___']`);
|
||||||
`[class*='Thermoscore__text___']`,
|
|
||||||
);
|
|
||||||
if (!gradeElement) continue;
|
if (!gradeElement) continue;
|
||||||
const grade = parseGrade(gradeElement.textContent || "");
|
const grade = parseGrade(gradeElement.textContent || "");
|
||||||
if (grade <= 0) continue;
|
if (grade <= 0) continue;
|
||||||
@@ -964,7 +901,7 @@ export async function processAssessments(api: any, assessmentItems: HTMLElement[
|
|||||||
weighting === "processing"
|
weighting === "processing"
|
||||||
) {
|
) {
|
||||||
hasInaccurateWeighting = true;
|
hasInaccurateWeighting = true;
|
||||||
continue
|
continue;
|
||||||
} else {
|
} else {
|
||||||
const weight = parseFloat(weighting);
|
const weight = parseFloat(weighting);
|
||||||
|
|
||||||
@@ -1004,9 +941,9 @@ function resolveTabSetClasses(): Record<string, string> {
|
|||||||
const resolved: Record<string, string> = {};
|
const resolved: Record<string, string> = {};
|
||||||
|
|
||||||
// First pass: scan live DOM elements (fast, covers currently-applied classes)
|
// First pass: scan live DOM elements (fast, covers currently-applied classes)
|
||||||
const allClasses = Array.from(
|
const allClasses = Array.from(document.querySelectorAll('[class*="TabSet__"]')).flatMap((el) =>
|
||||||
document.querySelectorAll('[class*="TabSet__"]'),
|
Array.from(el.classList),
|
||||||
).flatMap((el) => Array.from(el.classList));
|
);
|
||||||
|
|
||||||
for (const pattern of patterns) {
|
for (const pattern of patterns) {
|
||||||
const found = allClasses.find((c) => c.startsWith(pattern));
|
const found = allClasses.find((c) => c.startsWith(pattern));
|
||||||
@@ -1023,13 +960,10 @@ function resolveTabSetClasses(): Record<string, string> {
|
|||||||
try {
|
try {
|
||||||
for (const rule of Array.from(sheet.cssRules ?? [])) {
|
for (const rule of Array.from(sheet.cssRules ?? [])) {
|
||||||
if (!(rule instanceof CSSStyleRule)) continue;
|
if (!(rule instanceof CSSStyleRule)) continue;
|
||||||
const selectorClasses =
|
const selectorClasses = rule.selectorText.match(/\.([\w-]+)/g) ?? [];
|
||||||
rule.selectorText.match(/\.([\w-]+)/g) ?? [];
|
|
||||||
for (const pattern of missing) {
|
for (const pattern of missing) {
|
||||||
if (!resolved[pattern]) {
|
if (!resolved[pattern]) {
|
||||||
const match = selectorClasses.find((c) =>
|
const match = selectorClasses.find((c) => c.slice(1).startsWith(pattern));
|
||||||
c.slice(1).startsWith(pattern),
|
|
||||||
);
|
|
||||||
if (match) resolved[pattern] = match.slice(1);
|
if (match) resolved[pattern] = match.slice(1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1062,9 +996,7 @@ async function resolveWeightingTabContext(api: any): Promise<WeightingTabContext
|
|||||||
const selectedItem = document.querySelector(
|
const selectedItem = document.querySelector(
|
||||||
"[class*='AssessmentItem__AssessmentItem___'][class*='selected___']",
|
"[class*='AssessmentItem__AssessmentItem___'][class*='selected___']",
|
||||||
) as HTMLElement | null;
|
) as HTMLElement | null;
|
||||||
const titleEl = selectedItem?.querySelector(
|
const titleEl = selectedItem?.querySelector("[class*='AssessmentItem__title___']");
|
||||||
"[class*='AssessmentItem__title___']",
|
|
||||||
);
|
|
||||||
const title = titleEl?.textContent?.trim();
|
const title = titleEl?.textContent?.trim();
|
||||||
const assessmentID =
|
const assessmentID =
|
||||||
selectedItem?.dataset.betterseqtaAssessmentId ??
|
selectedItem?.dataset.betterseqtaAssessmentId ??
|
||||||
@@ -1076,12 +1008,8 @@ async function resolveWeightingTabContext(api: any): Promise<WeightingTabContext
|
|||||||
const rawWeight = entry?.weight;
|
const rawWeight = entry?.weight;
|
||||||
const weightingUnavailable = rawWeight === "N/A";
|
const weightingUnavailable = rawWeight === "N/A";
|
||||||
const autoWeight =
|
const autoWeight =
|
||||||
rawWeight && rawWeight !== "processing" && rawWeight !== "N/A"
|
rawWeight && rawWeight !== "processing" && rawWeight !== "N/A" ? rawWeight : undefined;
|
||||||
? rawWeight
|
const override = assessmentID ? api.storage.weightingOverrides?.[assessmentID] : undefined;
|
||||||
: undefined;
|
|
||||||
const override = assessmentID
|
|
||||||
? api.storage.weightingOverrides?.[assessmentID]
|
|
||||||
: undefined;
|
|
||||||
|
|
||||||
const statusNote = !assessmentID
|
const statusNote = !assessmentID
|
||||||
? ""
|
? ""
|
||||||
@@ -1100,12 +1028,8 @@ async function resolveWeightingTabContext(api: any): Promise<WeightingTabContext
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function renderWeightingTabHtml(
|
function renderWeightingTabHtml(sheet: HTMLElement, context: WeightingTabContext) {
|
||||||
sheet: HTMLElement,
|
const { assessmentID, autoWeight, override, weightingUnavailable, statusNote } = context;
|
||||||
context: WeightingTabContext,
|
|
||||||
) {
|
|
||||||
const { assessmentID, autoWeight, override, weightingUnavailable, statusNote } =
|
|
||||||
context;
|
|
||||||
|
|
||||||
sheet.innerHTML = `
|
sheet.innerHTML = `
|
||||||
<style>
|
<style>
|
||||||
@@ -1130,7 +1054,7 @@ function renderWeightingTabHtml(
|
|||||||
type="number"
|
type="number"
|
||||||
min="0"
|
min="0"
|
||||||
step="5"
|
step="5"
|
||||||
placeholder="${weightingUnavailable ? "Enter weight" : autoWeight ?? ""}"
|
placeholder="${weightingUnavailable ? "Enter weight" : (autoWeight ?? "")}"
|
||||||
value="${override ?? ""}"
|
value="${override ?? ""}"
|
||||||
${!assessmentID ? "disabled" : ""}
|
${!assessmentID ? "disabled" : ""}
|
||||||
style="
|
style="
|
||||||
@@ -1153,17 +1077,9 @@ function renderWeightingTabHtml(
|
|||||||
`;
|
`;
|
||||||
}
|
}
|
||||||
|
|
||||||
function attachWeightingInputHandlers(
|
function attachWeightingInputHandlers(sheet: HTMLElement, api: any, assessmentID: string) {
|
||||||
sheet: HTMLElement,
|
const input = sheet.querySelector("#betterseqta-weight-override") as HTMLInputElement;
|
||||||
api: any,
|
const statusEl = sheet.querySelector(".betterseqta-save-status") as HTMLElement;
|
||||||
assessmentID: string,
|
|
||||||
) {
|
|
||||||
const input = sheet.querySelector(
|
|
||||||
"#betterseqta-weight-override",
|
|
||||||
) as HTMLInputElement;
|
|
||||||
const statusEl = sheet.querySelector(
|
|
||||||
".betterseqta-save-status",
|
|
||||||
) as HTMLElement;
|
|
||||||
|
|
||||||
const save = () => {
|
const save = () => {
|
||||||
const raw = input.value.trim();
|
const raw = input.value.trim();
|
||||||
@@ -1192,8 +1108,7 @@ function attachWeightingInputHandlers(
|
|||||||
});
|
});
|
||||||
input.addEventListener("input", () => {
|
input.addEventListener("input", () => {
|
||||||
input.style.borderColor = "rgba(128,128,128,0.3)";
|
input.style.borderColor = "rgba(128,128,128,0.3)";
|
||||||
if (statusEl.textContent === "Invalid. Must be 0 or greater.")
|
if (statusEl.textContent === "Invalid. Must be 0 or greater.") statusEl.textContent = "";
|
||||||
statusEl.textContent = "";
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1205,21 +1120,14 @@ async function buildWeightingsTabContent(api: any, sheet: HTMLElement) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function injectWeightingsTab(api: any) {
|
export function injectWeightingsTab(api: any) {
|
||||||
const tabList = document.querySelector(
|
const tabList = document.querySelector('[class*="TabSet__tabs___"]') as HTMLElement;
|
||||||
'[class*="TabSet__tabs___"]',
|
const container = document.querySelector('[class*="TabSet__tabContainer___"]') as HTMLElement;
|
||||||
) as HTMLElement;
|
|
||||||
const container = document.querySelector(
|
|
||||||
'[class*="TabSet__tabContainer___"]',
|
|
||||||
) as HTMLElement;
|
|
||||||
if (!tabList || !container) return;
|
if (!tabList || !container) return;
|
||||||
if (tabList.querySelector(".betterseqta-weightings-tab")) return;
|
if (tabList.querySelector(".betterseqta-weightings-tab")) return;
|
||||||
|
|
||||||
const cls = resolveTabSetClasses();
|
const cls = resolveTabSetClasses();
|
||||||
|
|
||||||
const prefix = (tabList.querySelector("li") as HTMLElement).id.replace(
|
const prefix = (tabList.querySelector("li") as HTMLElement).id.replace(/-tab-\d+$/, "");
|
||||||
/-tab-\d+$/,
|
|
||||||
"",
|
|
||||||
);
|
|
||||||
const newIndex = tabList.querySelectorAll("li").length;
|
const newIndex = tabList.querySelectorAll("li").length;
|
||||||
|
|
||||||
const newTab = document.createElement("li");
|
const newTab = document.createElement("li");
|
||||||
@@ -1246,15 +1154,11 @@ export function injectWeightingsTab(api: any) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const allTabs = Array.from(tabList.querySelectorAll("li"));
|
const allTabs = Array.from(tabList.querySelectorAll("li"));
|
||||||
const allSheets = Array.from(
|
const allSheets = Array.from(container.querySelectorAll('[class*="tabsheet"]'));
|
||||||
container.querySelectorAll('[class*="tabsheet"]'),
|
|
||||||
);
|
|
||||||
|
|
||||||
allTabs.forEach((tab, i) => {
|
allTabs.forEach((tab, i) => {
|
||||||
tab.addEventListener("click", () => {
|
tab.addEventListener("click", () => {
|
||||||
const currentIndex = allTabs.findIndex((t) =>
|
const currentIndex = allTabs.findIndex((t) => t.className.includes("TabSet__selected___"));
|
||||||
t.className.includes("TabSet__selected___"),
|
|
||||||
);
|
|
||||||
if (i === currentIndex) return;
|
if (i === currentIndex) return;
|
||||||
const goingRight = currentIndex < 0 ? true : i > currentIndex;
|
const goingRight = currentIndex < 0 ? true : i > currentIndex;
|
||||||
|
|
||||||
@@ -1267,18 +1171,14 @@ export function injectWeightingsTab(api: any) {
|
|||||||
allSheets[currentIndex].className = [
|
allSheets[currentIndex].className = [
|
||||||
cls["TabSet__tabsheet___"],
|
cls["TabSet__tabsheet___"],
|
||||||
cls["TabSet__hidden___"],
|
cls["TabSet__hidden___"],
|
||||||
goingRight
|
goingRight ? cls["TabSet__disappearToLeft___"] : cls["TabSet__disappearToRight___"],
|
||||||
? cls["TabSet__disappearToLeft___"]
|
|
||||||
: cls["TabSet__disappearToRight___"],
|
|
||||||
].join(" ");
|
].join(" ");
|
||||||
}
|
}
|
||||||
|
|
||||||
allSheets[i].className = [
|
allSheets[i].className = [
|
||||||
cls["TabSet__tabsheet___"],
|
cls["TabSet__tabsheet___"],
|
||||||
cls["TabSet__selected___"],
|
cls["TabSet__selected___"],
|
||||||
goingRight
|
goingRight ? cls["TabSet__appearFromRight___"] : cls["TabSet__appearFromLeft___"],
|
||||||
? cls["TabSet__appearFromRight___"]
|
|
||||||
: cls["TabSet__appearFromLeft___"],
|
|
||||||
].join(" ");
|
].join(" ");
|
||||||
|
|
||||||
tab.className = cls["TabSet__selected___"];
|
tab.className = cls["TabSet__selected___"];
|
||||||
|
|||||||
@@ -70,7 +70,7 @@
|
|||||||
);
|
);
|
||||||
|
|
||||||
function initSubjectFilters(): Record<string, boolean> {
|
function initSubjectFilters(): Record<string, boolean> {
|
||||||
const filters = { ...(settingsState.subjectfilters || {}) };
|
const filters = { ...settingsState.subjectfilters };
|
||||||
const missing = (data?.subjects ?? []).filter((s: any) => !Object.hasOwn(filters, s.code));
|
const missing = (data?.subjects ?? []).filter((s: any) => !Object.hasOwn(filters, s.code));
|
||||||
if (missing.length) {
|
if (missing.length) {
|
||||||
for (const s of missing) filters[s.code] = true;
|
for (const s of missing) filters[s.code] = true;
|
||||||
|
|||||||
@@ -14,12 +14,9 @@ import { getUserInfo } from "@/seqta/utils/userInfo";
|
|||||||
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
|
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
|
||||||
import { getMockAssessmentsData } from "@/seqta/ui/dev/hideSensitiveContent";
|
import { getMockAssessmentsData } from "@/seqta/ui/dev/hideSensitiveContent";
|
||||||
import { isSeqtaEngageExperience } from "@/seqta/utils/isSeqtaEngage";
|
import { isSeqtaEngageExperience } from "@/seqta/utils/isSeqtaEngage";
|
||||||
import {
|
import { getEngageAssessmentsData } from "./engageApi";
|
||||||
getEngageAssessmentsData,
|
|
||||||
} from "./engageApi";
|
|
||||||
|
|
||||||
let cache: { time: number; engageAll?: boolean; studentId: number; data: any } | null =
|
let cache: { time: number; engageAll?: boolean; studentId: number; data: any } | null = null;
|
||||||
null;
|
|
||||||
const CACHE_MS = 10 * 60 * 1000;
|
const CACHE_MS = 10 * 60 * 1000;
|
||||||
|
|
||||||
async function fetchJSON(url: string, body: any) {
|
async function fetchJSON(url: string, body: any) {
|
||||||
@@ -111,21 +108,15 @@ async function loadSubmissions(student: number, assessments: any[]) {
|
|||||||
await Promise.all(
|
await Promise.all(
|
||||||
assessments.map(async (assessment) => {
|
assessments.map(async (assessment) => {
|
||||||
try {
|
try {
|
||||||
const res = await fetchJSON(
|
const res = await fetchJSON("/seqta/student/assessment/submissions/get", {
|
||||||
"/seqta/student/assessment/submissions/get",
|
assessment: assessment.id,
|
||||||
{
|
metaclass: assessment.metaclassID,
|
||||||
assessment: assessment.id,
|
student,
|
||||||
metaclass: assessment.metaclassID,
|
});
|
||||||
student,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
submissionMap[assessment.id] = res.payload && res.payload.length > 0;
|
submissionMap[assessment.id] = res.payload && res.payload.length > 0;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.warn(
|
console.warn(`Failed to fetch submission for assessment ${assessment.id}:`, error);
|
||||||
`Failed to fetch submission for assessment ${assessment.id}:`,
|
|
||||||
error,
|
|
||||||
);
|
|
||||||
submissionMap[assessment.id] = false;
|
submissionMap[assessment.id] = false;
|
||||||
}
|
}
|
||||||
}),
|
}),
|
||||||
@@ -153,10 +144,7 @@ async function getLearnAssessmentsData(studentId: number) {
|
|||||||
else map[t.id] = t;
|
else map[t.id] = t;
|
||||||
});
|
});
|
||||||
|
|
||||||
const allAssessments = filterAssessmentsForActiveSubjects(
|
const allAssessments = filterAssessmentsForActiveSubjects(Object.values(map), subjects);
|
||||||
Object.values(map),
|
|
||||||
subjects,
|
|
||||||
);
|
|
||||||
const submissions = await loadSubmissions(studentId, allAssessments);
|
const submissions = await loadSubmissions(studentId, allAssessments);
|
||||||
|
|
||||||
allAssessments.forEach((assessment: any) => {
|
allAssessments.forEach((assessment: any) => {
|
||||||
@@ -183,11 +171,7 @@ export async function getAssessmentsData() {
|
|||||||
|
|
||||||
const studentId = (await getUserInfo()).id;
|
const studentId = (await getUserInfo()).id;
|
||||||
|
|
||||||
if (
|
if (cache && Date.now() - cache.time < CACHE_MS && cache.studentId === studentId) {
|
||||||
cache &&
|
|
||||||
Date.now() - cache.time < CACHE_MS &&
|
|
||||||
cache.studentId === studentId
|
|
||||||
) {
|
|
||||||
return cache.data;
|
return cache.data;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -144,8 +144,7 @@ async function loadEngageSubmissions(studentId: number, assessments: any[]) {
|
|||||||
metaclass: assessment.metaclassID,
|
metaclass: assessment.metaclassID,
|
||||||
student: studentId,
|
student: studentId,
|
||||||
});
|
});
|
||||||
submissionMap[assessment.id] =
|
submissionMap[assessment.id] = Array.isArray(res.payload) && res.payload.length > 0;
|
||||||
Array.isArray(res.payload) && res.payload.length > 0;
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.warn(
|
console.warn(
|
||||||
`[BetterSEQTA+] Failed to fetch Engage submission for assessment ${assessment.id}:`,
|
`[BetterSEQTA+] Failed to fetch Engage submission for assessment ${assessment.id}:`,
|
||||||
@@ -159,9 +158,7 @@ async function loadEngageSubmissions(studentId: number, assessments: any[]) {
|
|||||||
return submissionMap;
|
return submissionMap;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function loadEngageAssessmentsForStudent(
|
async function loadEngageAssessmentsForStudent(child: EngageChildPayload): Promise<any[]> {
|
||||||
child: EngageChildPayload,
|
|
||||||
): Promise<any[]> {
|
|
||||||
const studentId = Number(child.id);
|
const studentId = Number(child.id);
|
||||||
const studentName = child.name ?? "Student";
|
const studentName = child.name ?? "Student";
|
||||||
const subjects = subjectsFromChild(child);
|
const subjects = subjectsFromChild(child);
|
||||||
@@ -182,14 +179,13 @@ async function loadEngageAssessmentsForStudent(
|
|||||||
else map[task.id] = task;
|
else map[task.id] = task;
|
||||||
});
|
});
|
||||||
|
|
||||||
const assessments = filterAssessmentsForActiveSubjects(
|
const assessments = filterAssessmentsForActiveSubjects(Object.values(map), subjects).map(
|
||||||
Object.values(map),
|
(assessment) => ({
|
||||||
subjects,
|
...assessment,
|
||||||
).map((assessment) => ({
|
studentId,
|
||||||
...assessment,
|
studentName,
|
||||||
studentId,
|
}),
|
||||||
studentName,
|
);
|
||||||
}));
|
|
||||||
|
|
||||||
const submissions = await loadEngageSubmissions(studentId, assessments);
|
const submissions = await loadEngageSubmissions(studentId, assessments);
|
||||||
assessments.forEach((assessment) => {
|
assessments.forEach((assessment) => {
|
||||||
|
|||||||
@@ -14,10 +14,7 @@ export type OverviewIconName =
|
|||||||
| "ellipsis-vertical"
|
| "ellipsis-vertical"
|
||||||
| "exclamation-circle";
|
| "exclamation-circle";
|
||||||
|
|
||||||
export const OVERVIEW_ICON_PATHS: Record<
|
export const OVERVIEW_ICON_PATHS: Record<OverviewIconName, string | string[]> = {
|
||||||
OverviewIconName,
|
|
||||||
string | string[]
|
|
||||||
> = {
|
|
||||||
"calendar-days":
|
"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",
|
"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",
|
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",
|
"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":
|
"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",
|
"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":
|
"check-circle": "M9 12.75L11.25 15 15 9.75M21 12a9 9 0 11-18 0 9 9 0 0118 0z",
|
||||||
"M9 12.75L11.25 15 15 9.75M21 12a9 9 0 11-18 0 9 9 0 0118 0z",
|
|
||||||
"book-open":
|
"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",
|
"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:
|
calendar:
|
||||||
@@ -45,8 +41,7 @@ export const OVERVIEW_ICON_PATHS: Record<
|
|||||||
],
|
],
|
||||||
"ellipsis-vertical":
|
"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",
|
"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":
|
"exclamation-circle": "M12 9v3.75m9-.75a9 9 0 11-18 0 9 9 0 0118 0zm-9 3.75h.008v.008H12v-.008z",
|
||||||
"M12 9v3.75m9-.75a9 9 0 11-18 0 9 9 0 0118 0zm-9 3.75h.008v.008H12v-.008z",
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export const STATUS_COLUMN_ICONS: Record<string, OverviewIconName> = {
|
export const STATUS_COLUMN_ICONS: Record<string, OverviewIconName> = {
|
||||||
|
|||||||
@@ -5,17 +5,12 @@ import { renderErrorState, renderGrid, renderSkeletonLoader, teardownOverviewUi
|
|||||||
import styles from "./styles.css?inline";
|
import styles from "./styles.css?inline";
|
||||||
import { delay } from "@/seqta/utils/delay";
|
import { delay } from "@/seqta/utils/delay";
|
||||||
import { isSeqtaEngageExperience } from "@/seqta/utils/isSeqtaEngage";
|
import { isSeqtaEngageExperience } from "@/seqta/utils/isSeqtaEngage";
|
||||||
import {
|
import { isEngageAssessmentOverviewRoute } from "@/seqta/utils/engageAssessmentStudent";
|
||||||
isEngageAssessmentOverviewRoute,
|
|
||||||
} from "@/seqta/utils/engageAssessmentStudent";
|
|
||||||
import { resolveEngageStudentId } from "./engageApi";
|
import { resolveEngageStudentId } from "./engageApi";
|
||||||
|
|
||||||
const OVERVIEW_MENU_CLASS = "betterseqta-assessments-overview-item";
|
const OVERVIEW_MENU_CLASS = "betterseqta-assessments-overview-item";
|
||||||
|
|
||||||
function ensureOverviewMenuPosition(
|
function ensureOverviewMenuPosition(menu: HTMLElement, gridItem: HTMLElement) {
|
||||||
menu: HTMLElement,
|
|
||||||
gridItem: HTMLElement,
|
|
||||||
) {
|
|
||||||
if (menu.firstElementChild !== gridItem) {
|
if (menu.firstElementChild !== gridItem) {
|
||||||
menu.insertBefore(gridItem, menu.firstChild);
|
menu.insertBefore(gridItem, menu.firstChild);
|
||||||
}
|
}
|
||||||
@@ -30,12 +25,7 @@ function isOverviewRoute() {
|
|||||||
|
|
||||||
async function waitForAssessmentsSubmenu(): Promise<HTMLElement> {
|
async function waitForAssessmentsSubmenu(): Promise<HTMLElement> {
|
||||||
if (!isSeqtaEngageExperience()) {
|
if (!isSeqtaEngageExperience()) {
|
||||||
return (await waitForElm(
|
return (await waitForElm('[data-key="assessments"] > .sub > ul', true, 100, 60)) as HTMLElement;
|
||||||
'[data-key="assessments"] > .sub > ul',
|
|
||||||
true,
|
|
||||||
100,
|
|
||||||
60,
|
|
||||||
)) as HTMLElement;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return (await waitForElm(
|
return (await waitForElm(
|
||||||
@@ -107,11 +97,7 @@ const assessmentsOverviewPlugin: Plugin<{}> = {
|
|||||||
|
|
||||||
if (isSeqtaEngageExperience()) {
|
if (isSeqtaEngageExperience()) {
|
||||||
const studentId = await resolveEngageStudentId();
|
const studentId = await resolveEngageStudentId();
|
||||||
window.history.pushState(
|
window.history.pushState({}, "", `/#?page=/assessments/${studentId}/overview`);
|
||||||
{},
|
|
||||||
"",
|
|
||||||
`/#?page=/assessments/${studentId}/overview`,
|
|
||||||
);
|
|
||||||
document.title = "Overview ― SEQTA Engage";
|
document.title = "Overview ― SEQTA Engage";
|
||||||
} else {
|
} else {
|
||||||
window.history.pushState({}, "", "/#?page=/assessments/overview");
|
window.history.pushState({}, "", "/#?page=/assessments/overview");
|
||||||
@@ -121,21 +107,14 @@ const assessmentsOverviewPlugin: Plugin<{}> = {
|
|||||||
const main = document.getElementById("main");
|
const main = document.getElementById("main");
|
||||||
if (!main || requestId !== loadRequestId) return;
|
if (!main || requestId !== loadRequestId) return;
|
||||||
|
|
||||||
document
|
document.querySelectorAll('[data-key="assessments"] .item').forEach((item) => {
|
||||||
.querySelectorAll('[data-key="assessments"] .item')
|
item.classList.remove("active");
|
||||||
.forEach((item) => {
|
});
|
||||||
item.classList.remove("active");
|
|
||||||
});
|
|
||||||
gridItem.classList.add("active");
|
gridItem.classList.add("active");
|
||||||
document
|
document.querySelector('[data-key="assessments"]')?.classList.add("active");
|
||||||
.querySelector('[data-key="assessments"]')
|
|
||||||
?.classList.add("active");
|
|
||||||
|
|
||||||
main.innerHTML =
|
main.innerHTML = '<div id="grid-view-container" class="bsplus-overview-host"></div>';
|
||||||
'<div id="grid-view-container" class="bsplus-overview-host"></div>';
|
const container = document.getElementById("grid-view-container") as HTMLElement;
|
||||||
const container = document.getElementById(
|
|
||||||
"grid-view-container",
|
|
||||||
) as HTMLElement;
|
|
||||||
|
|
||||||
if (requestId !== loadRequestId) return;
|
if (requestId !== loadRequestId) return;
|
||||||
|
|
||||||
@@ -148,10 +127,7 @@ const assessmentsOverviewPlugin: Plugin<{}> = {
|
|||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (requestId !== loadRequestId) return;
|
if (requestId !== loadRequestId) return;
|
||||||
console.error("Failed to load assessments:", err);
|
console.error("Failed to load assessments:", err);
|
||||||
renderErrorState(
|
renderErrorState(container, err instanceof Error ? err.message : "Unknown error");
|
||||||
container,
|
|
||||||
err instanceof Error ? err.message : "Unknown error",
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -8,11 +8,7 @@
|
|||||||
--bsplus-overview-surface: var(--background-primary, #ffffff);
|
--bsplus-overview-surface: var(--background-primary, #ffffff);
|
||||||
--bsplus-overview-surface-2: var(--background-secondary, #f8fafc);
|
--bsplus-overview-surface-2: var(--background-secondary, #f8fafc);
|
||||||
--bsplus-overview-text: var(--text-primary, #1a1a1a);
|
--bsplus-overview-text: var(--text-primary, #1a1a1a);
|
||||||
--bsplus-overview-muted: color-mix(
|
--bsplus-overview-muted: color-mix(in srgb, var(--bsplus-overview-text) 55%, transparent);
|
||||||
in srgb,
|
|
||||||
var(--bsplus-overview-text) 55%,
|
|
||||||
transparent
|
|
||||||
);
|
|
||||||
--bsplus-overview-border: color-mix(
|
--bsplus-overview-border: color-mix(
|
||||||
in srgb,
|
in srgb,
|
||||||
var(--theme-offset-bg, var(--background-secondary, #e2e8f0)) 78%,
|
var(--theme-offset-bg, var(--background-secondary, #e2e8f0)) 78%,
|
||||||
@@ -157,8 +153,7 @@
|
|||||||
.filter-select:focus {
|
.filter-select:focus {
|
||||||
outline: none;
|
outline: none;
|
||||||
border-color: var(--bsplus-overview-accent);
|
border-color: var(--bsplus-overview-accent);
|
||||||
box-shadow: 0 0 0 3px
|
box-shadow: 0 0 0 3px color-mix(in srgb, var(--bsplus-overview-accent) 22%, transparent);
|
||||||
color-mix(in srgb, var(--bsplus-overview-accent) 22%, transparent);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.filter-select:hover {
|
.filter-select:hover {
|
||||||
@@ -317,7 +312,11 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.label-subject {
|
.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 {
|
.label-student {
|
||||||
@@ -360,18 +359,13 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.menu-button:hover {
|
.menu-button:hover {
|
||||||
background: color-mix(
|
background: color-mix(in srgb, var(--bsplus-overview-surface-2) 90%, transparent) !important;
|
||||||
in srgb,
|
|
||||||
var(--bsplus-overview-surface-2) 90%,
|
|
||||||
transparent
|
|
||||||
) !important;
|
|
||||||
color: var(--bsplus-overview-text);
|
color: var(--bsplus-overview-text);
|
||||||
transform: scale(1.05) !important;
|
transform: scale(1.05) !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
.menu-button:focus-visible {
|
.menu-button:focus-visible {
|
||||||
box-shadow: 0 0 0 2px
|
box-shadow: 0 0 0 2px color-mix(in srgb, var(--bsplus-overview-accent) 35%, transparent) !important;
|
||||||
color-mix(in srgb, var(--bsplus-overview-accent) 35%, transparent) !important;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.menu-dropdown {
|
.menu-dropdown {
|
||||||
@@ -404,11 +398,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.menu-item:hover {
|
.menu-item:hover {
|
||||||
background: color-mix(
|
background: color-mix(in srgb, var(--bsplus-overview-surface-2) 90%, transparent);
|
||||||
in srgb,
|
|
||||||
var(--bsplus-overview-surface-2) 90%,
|
|
||||||
transparent
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.menu-item.mark-completed {
|
.menu-item.mark-completed {
|
||||||
@@ -879,8 +869,12 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
@keyframes spin {
|
@keyframes spin {
|
||||||
0% { transform: rotate(0deg); }
|
0% {
|
||||||
100% { transform: rotate(360deg); }
|
transform: rotate(0deg);
|
||||||
|
}
|
||||||
|
100% {
|
||||||
|
transform: rotate(360deg);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@keyframes shimmer {
|
@keyframes shimmer {
|
||||||
@@ -893,12 +887,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.skeleton-element {
|
.skeleton-element {
|
||||||
background: linear-gradient(
|
background: linear-gradient(90deg, #f1f5f9 0%, #e2e8f0 50%, #f1f5f9 100%);
|
||||||
90deg,
|
|
||||||
#f1f5f9 0%,
|
|
||||||
#e2e8f0 50%,
|
|
||||||
#f1f5f9 100%
|
|
||||||
);
|
|
||||||
background-size: 1000px 100%;
|
background-size: 1000px 100%;
|
||||||
animation: shimmer 2s infinite linear;
|
animation: shimmer 2s infinite linear;
|
||||||
border-radius: 4px;
|
border-radius: 4px;
|
||||||
@@ -995,17 +984,17 @@
|
|||||||
.grid-view-title {
|
.grid-view-title {
|
||||||
font-size: 1.5rem !important;
|
font-size: 1.5rem !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
.filter-select {
|
.filter-select {
|
||||||
padding: 0.5rem 0.75rem;
|
padding: 0.5rem 0.75rem;
|
||||||
font-size: 0.8rem;
|
font-size: 0.8rem;
|
||||||
min-width: 120px;
|
min-width: 120px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.assessment-card {
|
.assessment-card {
|
||||||
padding: 0.75rem;
|
padding: 0.75rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
.card-footer {
|
.card-footer {
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
gap: 0.5rem;
|
gap: 0.5rem;
|
||||||
@@ -1043,4 +1032,4 @@
|
|||||||
|
|
||||||
.dark .column-cards::-webkit-scrollbar-thumb:hover {
|
.dark .column-cards::-webkit-scrollbar-thumb:hover {
|
||||||
background: rgba(255, 255, 255, 0.3);
|
background: rgba(255, 255, 255, 0.3);
|
||||||
}
|
}
|
||||||
@@ -38,17 +38,11 @@ const ACCENT_CSS_VARS = [
|
|||||||
function extractSolidColor(value: string): string | null {
|
function extractSolidColor(value: string): string | null {
|
||||||
const trimmed = value.trim();
|
const trimmed = value.trim();
|
||||||
if (!trimmed || trimmed === "initial") return null;
|
if (!trimmed || trimmed === "initial") return null;
|
||||||
if (
|
if (trimmed.startsWith("#") || trimmed.startsWith("rgb") || trimmed.startsWith("hsl")) {
|
||||||
trimmed.startsWith("#") ||
|
|
||||||
trimmed.startsWith("rgb") ||
|
|
||||||
trimmed.startsWith("hsl")
|
|
||||||
) {
|
|
||||||
return trimmed;
|
return trimmed;
|
||||||
}
|
}
|
||||||
if (trimmed.includes("gradient")) {
|
if (trimmed.includes("gradient")) {
|
||||||
const match = trimmed.match(
|
const match = trimmed.match(/#[0-9A-Fa-f]{6}|#[0-9A-Fa-f]{3}|rgba?\([^)]+\)/i);
|
||||||
/#[0-9A-Fa-f]{6}|#[0-9A-Fa-f]{3}|rgba?\([^)]+\)/i,
|
|
||||||
);
|
|
||||||
return match?.[0] ?? null;
|
return match?.[0] ?? null;
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
@@ -71,18 +65,16 @@ function resolvePageAccentColor(): string {
|
|||||||
function syncOverviewTheme(target: HTMLElement) {
|
function syncOverviewTheme(target: HTMLElement) {
|
||||||
const computed = getComputedStyle(document.documentElement);
|
const computed = getComputedStyle(document.documentElement);
|
||||||
for (const name of THEME_CSS_VARS) {
|
for (const name of THEME_CSS_VARS) {
|
||||||
const value = document.documentElement.style.getPropertyValue(name).trim()
|
const value =
|
||||||
|| computed.getPropertyValue(name).trim();
|
document.documentElement.style.getPropertyValue(name).trim() ||
|
||||||
|
computed.getPropertyValue(name).trim();
|
||||||
if (value) target.style.setProperty(name, value);
|
if (value) target.style.setProperty(name, value);
|
||||||
}
|
}
|
||||||
|
|
||||||
const accent = resolvePageAccentColor();
|
const accent = resolvePageAccentColor();
|
||||||
target.style.setProperty("--bsplus-overview-accent", accent);
|
target.style.setProperty("--bsplus-overview-accent", accent);
|
||||||
target.style.setProperty("--better-main", accent);
|
target.style.setProperty("--better-main", accent);
|
||||||
target.classList.toggle(
|
target.classList.toggle("dark", document.documentElement.classList.contains("dark"));
|
||||||
"dark",
|
|
||||||
document.documentElement.classList.contains("dark"),
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function watchOverviewTheme(root: HTMLElement) {
|
function watchOverviewTheme(root: HTMLElement) {
|
||||||
|
|||||||
@@ -87,17 +87,12 @@ export function assessmentBelongsToActiveSubjects(
|
|||||||
): boolean {
|
): boolean {
|
||||||
if (!activeSubjects.length) return false;
|
if (!activeSubjects.length) return false;
|
||||||
|
|
||||||
const programme = Number(
|
const programme = Number(assessment.programmeID ?? assessment.programme);
|
||||||
assessment.programmeID ?? assessment.programme,
|
const metaclass = Number(assessment.metaclassID ?? assessment.metaclass);
|
||||||
);
|
|
||||||
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)) {
|
||||||
return activeSubjects.some(
|
return activeSubjects.some(
|
||||||
(subject) =>
|
(subject) => subject.programme === programme && subject.metaclass === metaclass,
|
||||||
subject.programme === programme && subject.metaclass === metaclass,
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -110,19 +105,10 @@ export function activeSubjectForAssessment(
|
|||||||
assessment: Record<string, unknown>,
|
assessment: Record<string, unknown>,
|
||||||
activeSubjects: OverviewSubject[],
|
activeSubjects: OverviewSubject[],
|
||||||
): OverviewSubject | undefined {
|
): OverviewSubject | undefined {
|
||||||
const programme = Number(
|
const programme = Number(assessment.programmeID ?? assessment.programme);
|
||||||
assessment.programmeID ?? assessment.programme,
|
const metaclass = Number(assessment.metaclassID ?? assessment.metaclass);
|
||||||
);
|
|
||||||
const metaclass = Number(
|
|
||||||
assessment.metaclassID ?? assessment.metaclass,
|
|
||||||
);
|
|
||||||
|
|
||||||
if (
|
if (programme && metaclass && !Number.isNaN(programme) && !Number.isNaN(metaclass)) {
|
||||||
programme &&
|
|
||||||
metaclass &&
|
|
||||||
!Number.isNaN(programme) &&
|
|
||||||
!Number.isNaN(metaclass)
|
|
||||||
) {
|
|
||||||
const subject = activeSubjects.find(
|
const subject = activeSubjects.find(
|
||||||
(s) => s.programme === programme && s.metaclass === metaclass,
|
(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 {
|
export function getGradeValue(assessment: any): number | null {
|
||||||
if (
|
if (assessment.results?.percentage !== undefined && assessment.results.percentage !== null) {
|
||||||
assessment.results?.percentage !== undefined &&
|
|
||||||
assessment.results.percentage !== null
|
|
||||||
) {
|
|
||||||
return assessment.results.percentage;
|
return assessment.results.percentage;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -27,8 +27,7 @@ const settings = defineSettings({
|
|||||||
}),
|
}),
|
||||||
pauseOnHidden: booleanSetting({
|
pauseOnHidden: booleanSetting({
|
||||||
title: "Pause when tab hidden",
|
title: "Pause when tab hidden",
|
||||||
description:
|
description: "Pause music when switching to another tab or minimizing the browser",
|
||||||
"Pause music when switching to another tab or minimizing the browser",
|
|
||||||
default: true,
|
default: true,
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
@@ -197,8 +196,7 @@ const backgroundMusicPlugin: Plugin<typeof settings> = {
|
|||||||
|
|
||||||
type BgSettings = { volume?: number; pauseOnHidden?: boolean };
|
type BgSettings = { volume?: number; pauseOnHidden?: boolean };
|
||||||
const vol = () => (api.settings as BgSettings).volume ?? 0.5;
|
const vol = () => (api.settings as BgSettings).volume ?? 0.5;
|
||||||
const pauseOnHidden = () =>
|
const pauseOnHidden = () => (api.settings as BgSettings).pauseOnHidden ?? true;
|
||||||
(api.settings as BgSettings).pauseOnHidden ?? true;
|
|
||||||
|
|
||||||
const runEnsurePlayback = async () => {
|
const runEnsurePlayback = async () => {
|
||||||
if (!(await prepareAudio(vol()))) return;
|
if (!(await prepareAudio(vol()))) return;
|
||||||
@@ -246,11 +244,7 @@ const backgroundMusicPlugin: Plugin<typeof settings> = {
|
|||||||
});
|
});
|
||||||
|
|
||||||
api.settings.onChange("pauseOnHidden" as never, (value: unknown) => {
|
api.settings.onChange("pauseOnHidden" as never, (value: unknown) => {
|
||||||
if (
|
if (value === false && audio?.paused && document.visibilityState === "visible") {
|
||||||
value === false &&
|
|
||||||
audio?.paused &&
|
|
||||||
document.visibilityState === "visible"
|
|
||||||
) {
|
|
||||||
void ensurePlayback();
|
void ensurePlayback();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -297,10 +291,7 @@ const backgroundMusicPlugin: Plugin<typeof settings> = {
|
|||||||
pageChange.unregister();
|
pageChange.unregister();
|
||||||
document.removeEventListener("visibilitychange", onVisibility);
|
document.removeEventListener("visibilitychange", onVisibility);
|
||||||
window.removeEventListener("pageshow", onUpdated);
|
window.removeEventListener("pageshow", onUpdated);
|
||||||
window.removeEventListener(
|
window.removeEventListener("betterseqta-background-music-updated", onUpdated);
|
||||||
"betterseqta-background-music-updated",
|
|
||||||
onUpdated,
|
|
||||||
);
|
|
||||||
window.removeEventListener("betterseqta-background-music-stop", onStop);
|
window.removeEventListener("betterseqta-background-music-stop", onStop);
|
||||||
if (resumeTimer) clearTimeout(resumeTimer);
|
if (resumeTimer) clearTimeout(resumeTimer);
|
||||||
disarmGesture();
|
disarmGesture();
|
||||||
|
|||||||
@@ -8,7 +8,9 @@
|
|||||||
border-radius: 999px;
|
border-radius: 999px;
|
||||||
background: color-mix(in srgb, var(--theme-primary, #1a1a1a) 92%, black 8%);
|
background: color-mix(in srgb, var(--theme-primary, #1a1a1a) 92%, black 8%);
|
||||||
color: var(--text-primary, #fff);
|
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;
|
cursor: pointer;
|
||||||
box-shadow: 0 8px 24px rgb(0 0 0 / 0.35);
|
box-shadow: 0 8px 24px rgb(0 0 0 / 0.35);
|
||||||
}
|
}
|
||||||
@@ -1,10 +1,6 @@
|
|||||||
import type { Plugin } from "@/plugins/core/types";
|
import type { Plugin } from "@/plugins/core/types";
|
||||||
import { BasePlugin } from "@/plugins/core/settings";
|
import { BasePlugin } from "@/plugins/core/settings";
|
||||||
import {
|
import { booleanSetting, defineSettings, Setting } from "@/plugins/core/settingsHelpers";
|
||||||
booleanSetting,
|
|
||||||
defineSettings,
|
|
||||||
Setting,
|
|
||||||
} from "@/plugins/core/settingsHelpers";
|
|
||||||
|
|
||||||
const settings = defineSettings({
|
const settings = defineSettings({
|
||||||
autoScrollOnClick: booleanSetting({
|
autoScrollOnClick: booleanSetting({
|
||||||
@@ -94,9 +90,7 @@ const getOrderedItems = (navigator: Element): HTMLElement[] => {
|
|||||||
const items: HTMLElement[] = [];
|
const items: HTMLElement[] = [];
|
||||||
const cover = navigator.querySelector<HTMLElement>("li.cover");
|
const cover = navigator.querySelector<HTMLElement>("li.cover");
|
||||||
if (cover) items.push(cover);
|
if (cover) items.push(cover);
|
||||||
const lessons = Array.from(
|
const lessons = Array.from(navigator.querySelectorAll<HTMLElement>("li.lesson"));
|
||||||
navigator.querySelectorAll<HTMLElement>("li.lesson"),
|
|
||||||
);
|
|
||||||
lessons.sort((a, b) => {
|
lessons.sort((a, b) => {
|
||||||
const wa = parseInt(a.dataset.week ?? "0", 10);
|
const wa = parseInt(a.dataset.week ?? "0", 10);
|
||||||
const wb = parseInt(b.dataset.week ?? "0", 10);
|
const wb = parseInt(b.dataset.week ?? "0", 10);
|
||||||
@@ -132,33 +126,24 @@ const scrollSelectedIntoView = (navigator: Element) => {
|
|||||||
const selected = getSelected(navigator);
|
const selected = getSelected(navigator);
|
||||||
if (!selected) return;
|
if (!selected) return;
|
||||||
|
|
||||||
const scroller =
|
const scroller = findScrollableAncestor(selected) ?? (navigator as HTMLElement);
|
||||||
findScrollableAncestor(selected) ?? (navigator as HTMLElement);
|
|
||||||
if (!scroller) return;
|
if (!scroller) return;
|
||||||
|
|
||||||
const scrollerRect = scroller.getBoundingClientRect();
|
const scrollerRect = scroller.getBoundingClientRect();
|
||||||
const selectedRect = selected.getBoundingClientRect();
|
const selectedRect = selected.getBoundingClientRect();
|
||||||
const offset =
|
const offset =
|
||||||
selectedRect.top -
|
selectedRect.top - scrollerRect.top - scroller.clientHeight / 2 + selectedRect.height / 2;
|
||||||
scrollerRect.top -
|
|
||||||
scroller.clientHeight / 2 +
|
|
||||||
selectedRect.height / 2;
|
|
||||||
|
|
||||||
scroller.scrollTop = Math.max(
|
scroller.scrollTop = Math.max(
|
||||||
0,
|
0,
|
||||||
Math.min(
|
Math.min(scroller.scrollTop + offset, scroller.scrollHeight - scroller.clientHeight),
|
||||||
scroller.scrollTop + offset,
|
|
||||||
scroller.scrollHeight - scroller.clientHeight,
|
|
||||||
),
|
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
const positionArrows = () => {
|
const positionArrows = () => {
|
||||||
const container = document.getElementById(ARROW_CONTAINER_ID);
|
const container = document.getElementById(ARROW_CONTAINER_ID);
|
||||||
if (!container) return;
|
if (!container) return;
|
||||||
const ref =
|
const ref = document.getElementById("toolbar") ?? document.querySelector<HTMLElement>(".course");
|
||||||
document.getElementById("toolbar") ??
|
|
||||||
document.querySelector<HTMLElement>(".course");
|
|
||||||
if (!ref) return;
|
if (!ref) return;
|
||||||
const rect = ref.getBoundingClientRect();
|
const rect = ref.getBoundingClientRect();
|
||||||
const arrowH = container.offsetHeight || 32;
|
const arrowH = container.offsetHeight || 32;
|
||||||
@@ -189,12 +174,8 @@ const updateArrowState = (course: HTMLElement) => {
|
|||||||
const selected = getSelected(nav);
|
const selected = getSelected(nav);
|
||||||
const idx = selected ? items.indexOf(selected) : -1;
|
const idx = selected ? items.indexOf(selected) : -1;
|
||||||
|
|
||||||
const prev = container.querySelector<HTMLButtonElement>(
|
const prev = container.querySelector<HTMLButtonElement>('button[data-en-action="prev"]');
|
||||||
'button[data-en-action="prev"]',
|
const next = container.querySelector<HTMLButtonElement>('button[data-en-action="next"]');
|
||||||
);
|
|
||||||
const next = container.querySelector<HTMLButtonElement>(
|
|
||||||
'button[data-en-action="next"]',
|
|
||||||
);
|
|
||||||
if (prev) prev.disabled = idx <= 0;
|
if (prev) prev.disabled = idx <= 0;
|
||||||
if (next) next.disabled = idx === -1 || idx >= items.length - 1;
|
if (next) next.disabled = idx === -1 || idx >= items.length - 1;
|
||||||
};
|
};
|
||||||
@@ -223,13 +204,10 @@ const ensureArrows = (course: HTMLElement) => {
|
|||||||
container.addEventListener("click", (e) => {
|
container.addEventListener("click", (e) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
const btn = (e.target as Element).closest<HTMLButtonElement>(
|
const btn = (e.target as Element).closest<HTMLButtonElement>("button[data-en-action]");
|
||||||
"button[data-en-action]",
|
|
||||||
);
|
|
||||||
if (!btn) return;
|
if (!btn) return;
|
||||||
const liveCourse = document.querySelector<HTMLElement>(".course");
|
const liveCourse = document.querySelector<HTMLElement>(".course");
|
||||||
if (liveCourse)
|
if (liveCourse) navigate(liveCourse, btn.dataset.enAction as "prev" | "next");
|
||||||
navigate(liveCourse, btn.dataset.enAction as "prev" | "next");
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -242,9 +220,7 @@ const watchNavigator = (navigator: Element, onChange: () => void) => {
|
|||||||
const observer = new MutationObserver((muts) => {
|
const observer = new MutationObserver((muts) => {
|
||||||
if (
|
if (
|
||||||
muts.some(
|
muts.some(
|
||||||
(m) =>
|
(m) => (m.type === "attributes" && m.attributeName === "class") || m.type === "childList",
|
||||||
(m.type === "attributes" && m.attributeName === "class") ||
|
|
||||||
m.type === "childList",
|
|
||||||
)
|
)
|
||||||
) {
|
) {
|
||||||
onChange();
|
onChange();
|
||||||
@@ -266,9 +242,7 @@ const handleSlidePane = (pane: Element): (() => void) => {
|
|||||||
requestAnimationFrame(() => scrollSelectedIntoView(navigator));
|
requestAnimationFrame(() => scrollSelectedIntoView(navigator));
|
||||||
setTimeout(() => scrollSelectedIntoView(navigator), 50);
|
setTimeout(() => scrollSelectedIntoView(navigator), 50);
|
||||||
|
|
||||||
const observer = new MutationObserver(() =>
|
const observer = new MutationObserver(() => scrollSelectedIntoView(navigator));
|
||||||
scrollSelectedIntoView(navigator),
|
|
||||||
);
|
|
||||||
observer.observe(navigator, {
|
observer.observe(navigator, {
|
||||||
subtree: true,
|
subtree: true,
|
||||||
attributes: true,
|
attributes: true,
|
||||||
|
|||||||
@@ -15,10 +15,7 @@ jest.mock("./styles.css?inline", () => ({
|
|||||||
default: "/* test */",
|
default: "/* test */",
|
||||||
}));
|
}));
|
||||||
|
|
||||||
import errorPageKittenPlugin, {
|
import errorPageKittenPlugin, { isSeqta404Page, mountErrorPageKitten } from "./index";
|
||||||
isSeqta404Page,
|
|
||||||
mountErrorPageKitten,
|
|
||||||
} from "./index";
|
|
||||||
|
|
||||||
const REBRANDED_404_BODY = `
|
const REBRANDED_404_BODY = `
|
||||||
<div class="message">
|
<div class="message">
|
||||||
@@ -86,7 +83,9 @@ describe("errorPageKitten", () => {
|
|||||||
document.title = "SEQTA Learn";
|
document.title = "SEQTA Learn";
|
||||||
document.body.innerHTML = '<div id="container"></div>';
|
document.body.innerHTML = '<div id="container"></div>';
|
||||||
|
|
||||||
const cleanup = await errorPageKittenPlugin.run({} as Parameters<typeof errorPageKittenPlugin.run>[0]);
|
const cleanup = await errorPageKittenPlugin.run(
|
||||||
|
{} as Parameters<typeof errorPageKittenPlugin.run>[0],
|
||||||
|
);
|
||||||
|
|
||||||
expect(getCard()).toBeNull();
|
expect(getCard()).toBeNull();
|
||||||
expect(cleanup).toBeDefined();
|
expect(cleanup).toBeDefined();
|
||||||
|
|||||||
@@ -33,9 +33,7 @@ function isSeqtaRebranded404Message(message: Element): boolean {
|
|||||||
const body = normalizePageText(message.textContent ?? "");
|
const body = normalizePageText(message.textContent ?? "");
|
||||||
return (
|
return (
|
||||||
body.includes("We can't find the page you're looking for") &&
|
body.includes("We can't find the page you're looking for") &&
|
||||||
body.includes(
|
body.includes("It may have been moved, deleted or the link might be out of date.") &&
|
||||||
"It may have been moved, deleted or the link might be out of date.",
|
|
||||||
) &&
|
|
||||||
body.includes("Ref: 404")
|
body.includes("Ref: 404")
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ html.bsplus-kitten-404 {
|
|||||||
}
|
}
|
||||||
html.bsplus-kitten-404 body {
|
html.bsplus-kitten-404 body {
|
||||||
background: #333;
|
background: #333;
|
||||||
font-family: 'Trebuchet MS', sans-serif;
|
font-family: "Trebuchet MS", sans-serif;
|
||||||
font-size: 12pt;
|
font-size: 12pt;
|
||||||
color: #aaa;
|
color: #aaa;
|
||||||
margin: 8px;
|
margin: 8px;
|
||||||
@@ -24,7 +24,8 @@ html.bsplus-kitten-404 .bsplus-kitten-404 {
|
|||||||
margin: 64px auto;
|
margin: 64px auto;
|
||||||
background: #222;
|
background: #222;
|
||||||
border-radius: 4px;
|
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);
|
1px 1px rgba(255, 255, 255, 0.2);
|
||||||
padding: 0 0 8px;
|
padding: 0 0 8px;
|
||||||
text-align: center;
|
text-align: center;
|
||||||
@@ -32,7 +33,8 @@ html.bsplus-kitten-404 .bsplus-kitten-404 {
|
|||||||
|
|
||||||
html.bsplus-kitten-404 .bsplus-kitten-404 > h1 {
|
html.bsplus-kitten-404 .bsplus-kitten-404 > h1 {
|
||||||
background: #612;
|
background: #612;
|
||||||
background-image: repeating-linear-gradient(
|
background-image:
|
||||||
|
repeating-linear-gradient(
|
||||||
135deg,
|
135deg,
|
||||||
rgba(0, 0, 0, 0),
|
rgba(0, 0, 0, 0),
|
||||||
rgba(0, 0, 0, 0) 8px,
|
rgba(0, 0, 0, 0) 8px,
|
||||||
|
|||||||
@@ -7,10 +7,7 @@ import {
|
|||||||
} from "../../core/settingsHelpers";
|
} from "../../core/settingsHelpers";
|
||||||
import { isSeqtaEngageExperience, isSeqtaLoginPage } from "@/seqta/utils/isSeqtaEngage";
|
import { isSeqtaEngageExperience, isSeqtaLoginPage } from "@/seqta/utils/isSeqtaEngage";
|
||||||
import styles from "./src/core/styles.css?inline";
|
import styles from "./src/core/styles.css?inline";
|
||||||
import {
|
import { resetSearchIndexes, notifyOpenTabsResetSearchIndex } from "./src/indexing/resetIndexes";
|
||||||
resetSearchIndexes,
|
|
||||||
notifyOpenTabsResetSearchIndex,
|
|
||||||
} from "./src/indexing/resetIndexes";
|
|
||||||
import {
|
import {
|
||||||
formatHotkeyForDisplay,
|
formatHotkeyForDisplay,
|
||||||
getDefaultSearchHotkey,
|
getDefaultSearchHotkey,
|
||||||
@@ -58,9 +55,7 @@ const settings = defineSettings({
|
|||||||
try {
|
try {
|
||||||
await notifyOpenTabsResetSearchIndex();
|
await notifyOpenTabsResetSearchIndex();
|
||||||
await resetSearchIndexes();
|
await resetSearchIndexes();
|
||||||
alert(
|
alert("Search index and storage were reset.\n\nReload this tab to regenerate the index.");
|
||||||
"Search index and storage were reset.\n\nReload this tab to regenerate the index.",
|
|
||||||
);
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
alert(
|
alert(
|
||||||
"Failed to reset index: " +
|
"Failed to reset index: " +
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ export interface StaticCommandItem extends BaseCommandItem {
|
|||||||
async function getCurrentLesson() {
|
async function getCurrentLesson() {
|
||||||
const date = new Date();
|
const date = new Date();
|
||||||
const todayFormatted = formatDate(date);
|
const todayFormatted = formatDate(date);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await fetch(`${location.origin}/seqta/student/load/timetable?`, {
|
const response = await fetch(`${location.origin}/seqta/student/load/timetable?`, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
@@ -31,35 +31,35 @@ async function getCurrentLesson() {
|
|||||||
until: todayFormatted,
|
until: todayFormatted,
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
const timetableData = await response.json();
|
const timetableData = await response.json();
|
||||||
|
|
||||||
if (!timetableData.payload.items.length) {
|
if (!timetableData.payload.items.length) {
|
||||||
alert("No lessons today!");
|
alert("No lessons today!");
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
const lessons = timetableData.payload.items.sort((a: any, b: any) =>
|
const lessons = timetableData.payload.items.sort((a: any, b: any) =>
|
||||||
a.from.localeCompare(b.from)
|
a.from.localeCompare(b.from),
|
||||||
);
|
);
|
||||||
|
|
||||||
const currentTime = new Date();
|
const currentTime = new Date();
|
||||||
|
|
||||||
for (const lesson of lessons) {
|
for (const lesson of lessons) {
|
||||||
const [startHour, startMinute] = lesson.from.split(":").map(Number);
|
const [startHour, startMinute] = lesson.from.split(":").map(Number);
|
||||||
const [endHour, endMinute] = lesson.until.split(":").map(Number);
|
const [endHour, endMinute] = lesson.until.split(":").map(Number);
|
||||||
|
|
||||||
const startDate = new Date(currentTime);
|
const startDate = new Date(currentTime);
|
||||||
startDate.setHours(startHour, startMinute, 0);
|
startDate.setHours(startHour, startMinute, 0);
|
||||||
|
|
||||||
const endDate = new Date(currentTime);
|
const endDate = new Date(currentTime);
|
||||||
endDate.setHours(endHour, endMinute, 0);
|
endDate.setHours(endHour, endMinute, 0);
|
||||||
|
|
||||||
if (startDate <= currentTime && endDate > currentTime) {
|
if (startDate <= currentTime && endDate > currentTime) {
|
||||||
return lesson;
|
return lesson;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
alert("There is no current lesson!");
|
alert("There is no current lesson!");
|
||||||
return null;
|
return null;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -72,33 +72,33 @@ async function getCurrentLesson() {
|
|||||||
async function navigateToSpecificLesson(lesson: any) {
|
async function navigateToSpecificLesson(lesson: any) {
|
||||||
try {
|
try {
|
||||||
await waitForElm(".course .navigator", true, 100, 100);
|
await waitForElm(".course .navigator", true, 100, 100);
|
||||||
|
|
||||||
const today = new Date();
|
const today = new Date();
|
||||||
const todayDateString = today.toLocaleDateString('en-GB', {
|
const todayDateString = today.toLocaleDateString("en-GB", {
|
||||||
day: 'numeric',
|
day: "numeric",
|
||||||
month: 'short'
|
month: "short",
|
||||||
});
|
});
|
||||||
|
|
||||||
const weeks = document.querySelectorAll(".course .navigator .week");
|
const weeks = document.querySelectorAll(".course .navigator .week");
|
||||||
|
|
||||||
for (const week of weeks) {
|
for (const week of weeks) {
|
||||||
const lessons = week.querySelectorAll(".lesson");
|
const lessons = week.querySelectorAll(".lesson");
|
||||||
|
|
||||||
for (const lessonElement of lessons) {
|
for (const lessonElement of lessons) {
|
||||||
const metaElement = lessonElement.querySelector(".meta");
|
const metaElement = lessonElement.querySelector(".meta");
|
||||||
if (!metaElement) continue;
|
if (!metaElement) continue;
|
||||||
|
|
||||||
const dateElement = metaElement.querySelector(".date");
|
const dateElement = metaElement.querySelector(".date");
|
||||||
const periodElement = metaElement.querySelector(".period");
|
const periodElement = metaElement.querySelector(".period");
|
||||||
|
|
||||||
if (!dateElement || !periodElement) continue;
|
if (!dateElement || !periodElement) continue;
|
||||||
|
|
||||||
const lessonDate = dateElement.textContent?.trim();
|
const lessonDate = dateElement.textContent?.trim();
|
||||||
const lessonPeriod = periodElement.textContent?.trim().match(/\d+/)?.[0];
|
const lessonPeriod = periodElement.textContent?.trim().match(/\d+/)?.[0];
|
||||||
|
|
||||||
// extract the number from the period
|
// extract the number from the period
|
||||||
const normalizedLessonPeriod = lesson.period?.match(/\d+/)?.[0];
|
const normalizedLessonPeriod = lesson.period?.match(/\d+/)?.[0];
|
||||||
|
|
||||||
// Check if this lesson matches today's date and the current lesson's period
|
// Check if this lesson matches today's date and the current lesson's period
|
||||||
if (lessonDate === todayDateString && lessonPeriod === normalizedLessonPeriod) {
|
if (lessonDate === todayDateString && lessonPeriod === normalizedLessonPeriod) {
|
||||||
// Found the exact matching lesson, click it
|
// Found the exact matching lesson, click it
|
||||||
@@ -107,10 +107,11 @@ async function navigateToSpecificLesson(lesson: any) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const todayButton = Array.from(document.querySelectorAll('#toolbar .uiButton'))
|
const todayButton = Array.from(document.querySelectorAll("#toolbar .uiButton")).find(
|
||||||
.find(button => button.textContent?.trim() === 'Today') as HTMLElement;
|
(button) => button.textContent?.trim() === "Today",
|
||||||
|
) as HTMLElement;
|
||||||
|
|
||||||
if (todayButton) {
|
if (todayButton) {
|
||||||
todayButton.click();
|
todayButton.click();
|
||||||
}
|
}
|
||||||
@@ -171,7 +172,7 @@ const staticCommands: StaticCommandItem[] = [
|
|||||||
const currentLesson = await getCurrentLesson();
|
const currentLesson = await getCurrentLesson();
|
||||||
if (currentLesson && currentLesson.programmeID !== 0) {
|
if (currentLesson && currentLesson.programmeID !== 0) {
|
||||||
window.location.hash = `?page=/courses/${currentLesson.programmeID}:${currentLesson.metaID}`;
|
window.location.hash = `?page=/courses/${currentLesson.programmeID}:${currentLesson.metaID}`;
|
||||||
|
|
||||||
await navigateToSpecificLesson(currentLesson);
|
await navigateToSpecificLesson(currentLesson);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -204,13 +205,16 @@ const staticCommands: StaticCommandItem[] = [
|
|||||||
category: "action",
|
category: "action",
|
||||||
text: "Compose Message",
|
text: "Compose Message",
|
||||||
action: () => {
|
action: () => {
|
||||||
window.postMessage({
|
window.postMessage(
|
||||||
type: "triggerKeyboardEvent",
|
{
|
||||||
key: 'm',
|
type: "triggerKeyboardEvent",
|
||||||
code: 'KeyM',
|
key: "m",
|
||||||
keyCode: 77,
|
code: "KeyM",
|
||||||
altKey: true
|
keyCode: 77,
|
||||||
}, location.origin);
|
altKey: true,
|
||||||
|
},
|
||||||
|
location.origin,
|
||||||
|
);
|
||||||
},
|
},
|
||||||
keywords: ["compose", "message", "dm", "direct message", "new message"],
|
keywords: ["compose", "message", "dm", "direct message", "new message"],
|
||||||
priority: 3,
|
priority: 3,
|
||||||
|
|||||||
@@ -8,10 +8,7 @@ import { isIndexingPaused } from "../indexing/indexingPause";
|
|||||||
import { cleanupSearchBar, mountSearchBar } from "./mountSearchBar";
|
import { cleanupSearchBar, mountSearchBar } from "./mountSearchBar";
|
||||||
import { IndexedDbManager } from "embeddia";
|
import { IndexedDbManager } from "embeddia";
|
||||||
import { checkAndHandleUpdate } from "../utils/versionCheck";
|
import { checkAndHandleUpdate } from "../utils/versionCheck";
|
||||||
import {
|
import { getStoredPassiveItems, installPassiveObserver } from "../indexing/passiveObserver";
|
||||||
getStoredPassiveItems,
|
|
||||||
installPassiveObserver,
|
|
||||||
} from "../indexing/passiveObserver";
|
|
||||||
import { globalSearchIndexingEnabled } from "@/seqta/utils/performanceMode";
|
import { globalSearchIndexingEnabled } from "@/seqta/utils/performanceMode";
|
||||||
|
|
||||||
function scheduleIdleIndexing(run: () => void): void {
|
function scheduleIdleIndexing(run: () => void): void {
|
||||||
@@ -69,10 +66,11 @@ const globalSearchPlugin: Pick<Plugin<GlobalSearchSettings>, "run"> = {
|
|||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
window.globalSearchDebug = {
|
window.globalSearchDebug = {
|
||||||
resetWorker: async () =>
|
resetWorker: async () =>
|
||||||
(await import("../indexing/worker/vectorWorkerManager")).VectorWorkerManager.getInstance().resetWorker(),
|
(
|
||||||
|
await import("../indexing/worker/vectorWorkerManager")
|
||||||
|
).VectorWorkerManager.getInstance().resetWorker(),
|
||||||
passiveItems: getStoredPassiveItems,
|
passiveItems: getStoredPassiveItems,
|
||||||
runSelfTests: async () =>
|
runSelfTests: async () => (await import("../indexing/selfTests")).runGlobalSearchSelfTests(),
|
||||||
(await import("../indexing/selfTests")).runGlobalSearchSelfTests(),
|
|
||||||
};
|
};
|
||||||
|
|
||||||
if (globalSearchIndexingEnabled(!!api.settings.passiveIndexing)) {
|
if (globalSearchIndexingEnabled(!!api.settings.passiveIndexing)) {
|
||||||
@@ -83,10 +81,7 @@ const globalSearchPlugin: Pick<Plugin<GlobalSearchSettings>, "run"> = {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (
|
if (globalSearchIndexingEnabled(!!api.settings.runIndexingOnLoad) && !isIndexingPaused()) {
|
||||||
globalSearchIndexingEnabled(!!api.settings.runIndexingOnLoad) &&
|
|
||||||
!isIndexingPaused()
|
|
||||||
) {
|
|
||||||
scheduleIdleIndexing(() => {
|
scheduleIdleIndexing(() => {
|
||||||
if (!isIndexingPaused()) void runIndexing();
|
if (!isIndexingPaused()) void runIndexing();
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -18,12 +18,8 @@ type AppRef = {
|
|||||||
const SEARCH_SVG =
|
const SEARCH_SVG =
|
||||||
'<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>';
|
'<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>';
|
||||||
|
|
||||||
async function resolveTriggerWrapper(
|
async function resolveTriggerWrapper(titleElement: Element): Promise<HTMLElement | null> {
|
||||||
titleElement: Element,
|
const existing = titleElement.querySelector(".search-trigger-wrapper") as HTMLElement | null;
|
||||||
): Promise<HTMLElement | null> {
|
|
||||||
const existing = titleElement.querySelector(
|
|
||||||
".search-trigger-wrapper",
|
|
||||||
) as HTMLElement | null;
|
|
||||||
if (existing) return existing;
|
if (existing) return existing;
|
||||||
|
|
||||||
const custom =
|
const custom =
|
||||||
@@ -65,8 +61,7 @@ function buildTriggerWrapper() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function triggerParts(searchWrapper: HTMLElement) {
|
function triggerParts(searchWrapper: HTMLElement) {
|
||||||
const q = <T extends HTMLElement>(sel: string) =>
|
const q = <T extends HTMLElement>(sel: string) => searchWrapper.querySelector(sel) as T;
|
||||||
searchWrapper.querySelector(sel) as T;
|
|
||||||
return {
|
return {
|
||||||
searchWrapper,
|
searchWrapper,
|
||||||
searchAnchor: q(".search-trigger-anchor"),
|
searchAnchor: q(".search-trigger-anchor"),
|
||||||
@@ -80,11 +75,7 @@ function triggerParts(searchWrapper: HTMLElement) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function mountSearchBar(
|
export async function mountSearchBar(titleElement: Element, api: any, appRef: AppRef) {
|
||||||
titleElement: Element,
|
|
||||||
api: any,
|
|
||||||
appRef: AppRef,
|
|
||||||
) {
|
|
||||||
const preRendered = await resolveTriggerWrapper(titleElement);
|
const preRendered = await resolveTriggerWrapper(titleElement);
|
||||||
if (preRendered?.dataset.bsplusSearchWired === "1") return;
|
if (preRendered?.dataset.bsplusSearchWired === "1") return;
|
||||||
|
|
||||||
@@ -132,8 +123,7 @@ export async function mountSearchBar(
|
|||||||
const DONE_HOLD_MS = 5000;
|
const DONE_HOLD_MS = 5000;
|
||||||
const DONE_FADE_MS = 550;
|
const DONE_FADE_MS = 550;
|
||||||
const statusLooksRough = (s: string) => /\b(fail|error|cancel)\b/i.test(s);
|
const statusLooksRough = (s: string) => /\b(fail|error|cancel)\b/i.test(s);
|
||||||
const truncateStatus = (s: string, max = 44) =>
|
const truncateStatus = (s: string, max = 44) => (s.length > max ? s.slice(0, max - 1) + "…" : s);
|
||||||
s.length > max ? s.slice(0, max - 1) + "…" : s;
|
|
||||||
|
|
||||||
const clearDoneFlashTimer = () => {
|
const clearDoneFlashTimer = () => {
|
||||||
if (doneFlashTimer) clearTimeout(doneFlashTimer);
|
if (doneFlashTimer) clearTimeout(doneFlashTimer);
|
||||||
@@ -147,12 +137,7 @@ export async function mountSearchBar(
|
|||||||
progressBarWrapper.classList.remove("is-active", "is-rough-complete");
|
progressBarWrapper.classList.remove("is-active", "is-rough-complete");
|
||||||
searchAnchor.classList.remove("is-indexing");
|
searchAnchor.classList.remove("is-indexing");
|
||||||
searchButton.classList.remove("is-indexing");
|
searchButton.classList.remove("is-indexing");
|
||||||
progressText.classList.remove(
|
progressText.classList.remove("is-active", "is-rough", "is-fading-done", "is-done-message");
|
||||||
"is-active",
|
|
||||||
"is-rough",
|
|
||||||
"is-fading-done",
|
|
||||||
"is-done-message",
|
|
||||||
);
|
|
||||||
progressBar.style.width = "0%";
|
progressBar.style.width = "0%";
|
||||||
progressText.textContent = "";
|
progressText.textContent = "";
|
||||||
ranIndexingCycle = false;
|
ranIndexingCycle = false;
|
||||||
@@ -179,9 +164,7 @@ export async function mountSearchBar(
|
|||||||
searchAnchor.classList.remove("is-indexing");
|
searchAnchor.classList.remove("is-indexing");
|
||||||
searchButton.classList.remove("is-indexing");
|
searchButton.classList.remove("is-indexing");
|
||||||
progressText.classList.remove("is-fading-done");
|
progressText.classList.remove("is-fading-done");
|
||||||
progressText.textContent = rough
|
progressText.textContent = rough ? truncateStatus(indexingStatus!, 52) : "Done!";
|
||||||
? truncateStatus(indexingStatus!, 52)
|
|
||||||
: "Done!";
|
|
||||||
progressText.classList.toggle("is-rough", rough);
|
progressText.classList.toggle("is-rough", rough);
|
||||||
progressBarWrapper.classList.toggle("is-rough-complete", rough);
|
progressBarWrapper.classList.toggle("is-rough-complete", rough);
|
||||||
progressText.classList.add("is-active", "is-done-message");
|
progressText.classList.add("is-active", "is-done-message");
|
||||||
@@ -219,9 +202,7 @@ export async function mountSearchBar(
|
|||||||
|
|
||||||
if (completionEligible) {
|
if (completionEligible) {
|
||||||
if (doneFlashTimer !== null || doneFadeTimer !== null) return;
|
if (doneFlashTimer !== null || doneFadeTimer !== null) return;
|
||||||
scheduleCompletionFlash(
|
scheduleCompletionFlash(indexingStatus != null && statusLooksRough(indexingStatus));
|
||||||
indexingStatus != null && statusLooksRough(indexingStatus),
|
|
||||||
);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -325,19 +306,14 @@ export function cleanupSearchBar(appRef: AppRef) {
|
|||||||
appRef.clearDoneFlashTimer = undefined;
|
appRef.clearDoneFlashTimer = undefined;
|
||||||
|
|
||||||
if (appRef.progressHandler) {
|
if (appRef.progressHandler) {
|
||||||
window.removeEventListener(
|
window.removeEventListener("indexing-progress", appRef.progressHandler as EventListener);
|
||||||
"indexing-progress",
|
|
||||||
appRef.progressHandler as EventListener,
|
|
||||||
);
|
|
||||||
appRef.progressHandler = null;
|
appRef.progressHandler = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
const searchWrapper = document.querySelector(
|
const searchWrapper = document.querySelector(".search-trigger-wrapper") as HTMLElement | null;
|
||||||
".search-trigger-wrapper",
|
|
||||||
) as HTMLElement | null;
|
|
||||||
const customOwns = Boolean(
|
const customOwns = Boolean(
|
||||||
document.querySelector("#title.bsplus-custom-title") ||
|
document.querySelector("#title.bsplus-custom-title") ||
|
||||||
document.getElementById("bsplus-title-root"),
|
document.getElementById("bsplus-title-root"),
|
||||||
);
|
);
|
||||||
|
|
||||||
if (searchWrapper) {
|
if (searchWrapper) {
|
||||||
|
|||||||
@@ -212,15 +212,10 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.search-progress-bar::after {
|
.search-progress-bar::after {
|
||||||
content: '';
|
content: "";
|
||||||
position: absolute;
|
position: absolute;
|
||||||
inset: 0;
|
inset: 0;
|
||||||
background: linear-gradient(
|
background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.28), transparent);
|
||||||
90deg,
|
|
||||||
transparent,
|
|
||||||
rgba(255, 255, 255, 0.28),
|
|
||||||
transparent
|
|
||||||
);
|
|
||||||
animation: shimmer 2s infinite;
|
animation: shimmer 2s infinite;
|
||||||
}
|
}
|
||||||
/*
|
/*
|
||||||
@@ -236,7 +231,10 @@
|
|||||||
font-weight: 500;
|
font-weight: 500;
|
||||||
opacity: 0;
|
opacity: 0;
|
||||||
transform: translateX(-4px);
|
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;
|
pointer-events: none;
|
||||||
max-width: 240px;
|
max-width: 240px;
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
|
|||||||
@@ -43,8 +43,7 @@ export const coursesPayload = {
|
|||||||
t: "English GEN 1",
|
t: "English GEN 1",
|
||||||
i: 3830,
|
i: 3830,
|
||||||
m: 29611,
|
m: 29611,
|
||||||
document:
|
document: '{"document":{"modules":[{"uuid":"1641cf87-ae08-4bcb-832d-d5709d84d0c5"}]}}',
|
||||||
'{"document":{"modules":[{"uuid":"1641cf87-ae08-4bcb-832d-d5709d84d0c5"}]}}',
|
|
||||||
w: [
|
w: [
|
||||||
[
|
[
|
||||||
{ t: "", h: "", i: 248293, l: "", n: 0, o: "" },
|
{ t: "", h: "", i: 248293, l: "", n: 0, o: "" },
|
||||||
@@ -86,8 +85,7 @@ export const documentsPayload = [
|
|||||||
filename: "School Glossary.docx",
|
filename: "School Glossary.docx",
|
||||||
size: "14931",
|
size: "14931",
|
||||||
context_uuid: "3162189c-2052-4f83-ad83-a66c57460ea2",
|
context_uuid: "3162189c-2052-4f83-ad83-a66c57460ea2",
|
||||||
mimetype:
|
mimetype: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||||||
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
|
||||||
created_date: "2021-08-04 12:55:55.102653+00",
|
created_date: "2021-08-04 12:55:55.102653+00",
|
||||||
title: "School Glossary",
|
title: "School Glossary",
|
||||||
uuid: "3162189c-2052-4f83-ad83-a66c57460ea2",
|
uuid: "3162189c-2052-4f83-ad83-a66c57460ea2",
|
||||||
@@ -139,8 +137,7 @@ export const folioListPayload = {
|
|||||||
|
|
||||||
export const folioEntryPayload = {
|
export const folioEntryPayload = {
|
||||||
forum: 478,
|
forum: 478,
|
||||||
contents:
|
contents: "[[embed:raw|<p>Some <strong>reflection</strong> text.</p>]] Plain trailing text.",
|
||||||
'[[embed:raw|<p>Some <strong>reflection</strong> text.</p>]] Plain trailing text.',
|
|
||||||
created: "2026-04-14 10:32:34.264641+00",
|
created: "2026-04-14 10:32:34.264641+00",
|
||||||
allow_comments: true,
|
allow_comments: true,
|
||||||
author: { year: "Year 10", name: "Jacob Johannesburg", id: 3111 },
|
author: { year: "Year 10", name: "Jacob Johannesburg", id: 3111 },
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import type { IndexItem } from "./types";
|
|||||||
import ReactFiber from "@/seqta/utils/ReactFiber";
|
import ReactFiber from "@/seqta/utils/ReactFiber";
|
||||||
import { delay } from "@/seqta/utils/delay";
|
import { delay } from "@/seqta/utils/delay";
|
||||||
|
|
||||||
import { verboseLog } from '@/utils/verboseLog';
|
import { verboseLog } from "@/utils/verboseLog";
|
||||||
interface MessageMetadata {
|
interface MessageMetadata {
|
||||||
messageId: number;
|
messageId: number;
|
||||||
author: string;
|
author: string;
|
||||||
@@ -73,14 +73,14 @@ export const actionMap: Record<string, ActionHandler<any>> = {
|
|||||||
ReactFiber.find('[class*="Viewer__Viewer___"] > div').setState({
|
ReactFiber.find('[class*="Viewer__Viewer___"] > div').setState({
|
||||||
selected: new Set([item.metadata.messageId]),
|
selected: new Set([item.metadata.messageId]),
|
||||||
});
|
});
|
||||||
|
|
||||||
// send a network request to mark as read
|
// send a network request to mark as read
|
||||||
fetch('/seqta/student/save/message', {
|
fetch("/seqta/student/save/message", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
credentials: "include",
|
credentials: "include",
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
items: [item.metadata.messageId],
|
items: [item.metadata.messageId],
|
||||||
mode: 'x-read',
|
mode: "x-read",
|
||||||
read: true,
|
read: true,
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
@@ -98,13 +98,16 @@ export const actionMap: Record<string, ActionHandler<any>> = {
|
|||||||
// Firefox XrayWrapper prevents direct access to nested properties
|
// Firefox XrayWrapper prevents direct access to nested properties
|
||||||
let itemClone: IndexItem & { metadata: AssessmentMetadata };
|
let itemClone: IndexItem & { metadata: AssessmentMetadata };
|
||||||
let metadata: AssessmentMetadata;
|
let metadata: AssessmentMetadata;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// First try to clone the entire item
|
// First try to clone the entire item
|
||||||
itemClone = JSON.parse(JSON.stringify(item));
|
itemClone = JSON.parse(JSON.stringify(item));
|
||||||
metadata = itemClone.metadata || {};
|
metadata = itemClone.metadata || {};
|
||||||
} catch (e) {
|
} 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 {
|
try {
|
||||||
// If full clone fails, try cloning just metadata
|
// If full clone fails, try cloning just metadata
|
||||||
metadata = JSON.parse(JSON.stringify(item.metadata || {}));
|
metadata = JSON.parse(JSON.stringify(item.metadata || {}));
|
||||||
@@ -112,10 +115,10 @@ export const actionMap: Record<string, ActionHandler<any>> = {
|
|||||||
} catch (e2) {
|
} catch (e2) {
|
||||||
console.warn("[Assessment Action] Failed to clone metadata, using direct access:", e2);
|
console.warn("[Assessment Action] Failed to clone metadata, using direct access:", e2);
|
||||||
itemClone = item;
|
itemClone = item;
|
||||||
metadata = item.metadata || {} as AssessmentMetadata;
|
metadata = item.metadata || ({} as AssessmentMetadata);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Try to extract metadata values using multiple methods to handle XrayWrapper.
|
// Try to extract metadata values using multiple methods to handle XrayWrapper.
|
||||||
// The metadata bag is intentionally typed loosely here because Firefox's
|
// The metadata bag is intentionally typed loosely here because Firefox's
|
||||||
// XrayWrapper occasionally surfaces extra/casing-variant keys we still
|
// XrayWrapper occasionally surfaces extra/casing-variant keys we still
|
||||||
@@ -152,51 +155,65 @@ export const actionMap: Record<string, ActionHandler<any>> = {
|
|||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
if (getMetadataValue('isMessageBased')) {
|
if (getMetadataValue("isMessageBased")) {
|
||||||
window.location.hash = `#?page=/messages`;
|
window.location.hash = `#?page=/messages`;
|
||||||
|
|
||||||
await waitForElm('[class*="Viewer__Viewer___"] > div', true, 20);
|
await waitForElm('[class*="Viewer__Viewer___"] > div', true, 20);
|
||||||
|
|
||||||
// Select the specific direct message
|
// Select the specific direct message
|
||||||
ReactFiber.find('[class*="Viewer__Viewer___"] > div').setState({
|
ReactFiber.find('[class*="Viewer__Viewer___"] > div').setState({
|
||||||
selected: new Set([getMetadataValue('messageId')]),
|
selected: new Set([getMetadataValue("messageId")]),
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
// Extract values - check both camelCase and PascalCase, and try multiple access methods
|
// Extract values - check both camelCase and PascalCase, and try multiple access methods
|
||||||
let programmeId = getMetadataValue('programmeId', 'programmeID');
|
let programmeId = getMetadataValue("programmeId", "programmeID");
|
||||||
let metaclassId = getMetadataValue('metaclassId', 'metaclassID');
|
let metaclassId = getMetadataValue("metaclassId", "metaclassID");
|
||||||
let assessmentId = getMetadataValue('assessmentId', 'assessmentID');
|
let assessmentId = getMetadataValue("assessmentId", "assessmentID");
|
||||||
|
|
||||||
// Fallback: try to extract assessmentId from item ID if metadata is missing
|
// Fallback: try to extract assessmentId from item ID if metadata is missing
|
||||||
if ((assessmentId === undefined || assessmentId === null) && itemClone.id && itemClone.id.startsWith('assignment-')) {
|
if (
|
||||||
const extractedId = itemClone.id.replace('assignment-', '');
|
(assessmentId === undefined || assessmentId === null) &&
|
||||||
|
itemClone.id &&
|
||||||
|
itemClone.id.startsWith("assignment-")
|
||||||
|
) {
|
||||||
|
const extractedId = itemClone.id.replace("assignment-", "");
|
||||||
assessmentId = Number(extractedId) || extractedId;
|
assessmentId = Number(extractedId) || extractedId;
|
||||||
verboseLog("[Assessment Action] Extracted assessmentId from item ID:", assessmentId);
|
verboseLog("[Assessment Action] Extracted assessmentId from item ID:", assessmentId);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Convert to numbers, but preserve 0 as valid
|
// Convert to numbers, but preserve 0 as valid
|
||||||
if (programmeId !== undefined && programmeId !== null && programmeId !== '') {
|
if (programmeId !== undefined && programmeId !== null && programmeId !== "") {
|
||||||
const num = Number(programmeId);
|
const num = Number(programmeId);
|
||||||
programmeId = isNaN(num) ? programmeId : num;
|
programmeId = isNaN(num) ? programmeId : num;
|
||||||
}
|
}
|
||||||
if (metaclassId !== undefined && metaclassId !== null && metaclassId !== '') {
|
if (metaclassId !== undefined && metaclassId !== null && metaclassId !== "") {
|
||||||
const num = Number(metaclassId);
|
const num = Number(metaclassId);
|
||||||
metaclassId = isNaN(num) ? metaclassId : num;
|
metaclassId = isNaN(num) ? metaclassId : num;
|
||||||
}
|
}
|
||||||
if (assessmentId !== undefined && assessmentId !== null && assessmentId !== '') {
|
if (assessmentId !== undefined && assessmentId !== null && assessmentId !== "") {
|
||||||
const num = Number(assessmentId);
|
const num = Number(assessmentId);
|
||||||
assessmentId = isNaN(num) ? assessmentId : num;
|
assessmentId = isNaN(num) ? assessmentId : num;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check if values exist (including 0, which is a valid ID)
|
// Check if values exist (including 0, which is a valid ID)
|
||||||
// Use typeof check to properly handle 0
|
// Use typeof check to properly handle 0
|
||||||
const hasProgrammeId = programmeId !== undefined && programmeId !== null && programmeId !== '' && typeof programmeId === 'number';
|
const hasProgrammeId =
|
||||||
const hasMetaclassId = metaclassId !== undefined && metaclassId !== null && metaclassId !== '' && typeof metaclassId === 'number';
|
programmeId !== undefined &&
|
||||||
const hasAssessmentId = assessmentId !== undefined && assessmentId !== null && assessmentId !== '' && typeof assessmentId === 'number';
|
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) {
|
if (hasProgrammeId && hasMetaclassId && hasAssessmentId) {
|
||||||
const url = `#?page=/assessments/${programmeId}:${metaclassId}&item=${assessmentId}`;
|
const url = `#?page=/assessments/${programmeId}:${metaclassId}&item=${assessmentId}`;
|
||||||
verboseLog("[Assessment Action] ✅ Navigating to:", url);
|
verboseLog("[Assessment Action] ✅ Navigating to:", url);
|
||||||
@@ -226,15 +243,11 @@ export const actionMap: Record<string, ActionHandler<any>> = {
|
|||||||
}) as ActionHandler<any>,
|
}) as ActionHandler<any>,
|
||||||
|
|
||||||
subjectassessment: ((item: IndexItem) => {
|
subjectassessment: ((item: IndexItem) => {
|
||||||
navigateToHashRoute(
|
navigateToHashRoute(`/assessments/${item.metadata.programme}:${item.metadata.subjectId}`);
|
||||||
`/assessments/${item.metadata.programme}:${item.metadata.subjectId}`,
|
|
||||||
);
|
|
||||||
}) as ActionHandler<any>,
|
}) as ActionHandler<any>,
|
||||||
|
|
||||||
subjectcourse: ((item: IndexItem) => {
|
subjectcourse: ((item: IndexItem) => {
|
||||||
navigateToHashRoute(
|
navigateToHashRoute(`/courses/${item.metadata.programme}:${item.metadata.subjectId}`);
|
||||||
`/courses/${item.metadata.programme}:${item.metadata.subjectId}`,
|
|
||||||
);
|
|
||||||
}) as ActionHandler<any>,
|
}) as ActionHandler<any>,
|
||||||
|
|
||||||
forum: ((item: IndexItem) => {
|
forum: ((item: IndexItem) => {
|
||||||
@@ -322,8 +335,7 @@ export const actionMap: Record<string, ActionHandler<any>> = {
|
|||||||
passive: ((item: IndexItem) => {
|
passive: ((item: IndexItem) => {
|
||||||
const md = (item.metadata ?? {}) as Record<string, unknown>;
|
const md = (item.metadata ?? {}) as Record<string, unknown>;
|
||||||
const route = typeof md.route === "string" ? (md.route as string) : "";
|
const route = typeof md.route === "string" ? (md.route as string) : "";
|
||||||
const sourcePage =
|
const sourcePage = typeof md.sourcePage === "string" ? (md.sourcePage as string) : "";
|
||||||
typeof md.sourcePage === "string" ? (md.sourcePage as string) : "";
|
|
||||||
const routeParts = route
|
const routeParts = route
|
||||||
.replace(/^\/seqta\/student\/?/, "")
|
.replace(/^\/seqta\/student\/?/, "")
|
||||||
.replace(/^load\//, "")
|
.replace(/^load\//, "")
|
||||||
@@ -347,24 +359,16 @@ export const actionMap: Record<string, ActionHandler<any>> = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const programme = num("programme") ?? num("programmeId") ?? num("programmeID");
|
const programme = num("programme") ?? num("programmeId") ?? num("programmeID");
|
||||||
const metaclass =
|
const metaclass = num("metaclass") ?? num("metaclassId") ?? num("metaclassID");
|
||||||
num("metaclass") ?? num("metaclassId") ?? num("metaclassID");
|
|
||||||
const portalUuid = str("portalUuid") ?? str("uuid");
|
const portalUuid = str("portalUuid") ?? str("uuid");
|
||||||
const forumId = num("forumId") ?? num("forum");
|
const forumId = num("forumId") ?? num("forum");
|
||||||
const year = num("year");
|
const year = num("year");
|
||||||
const assessmentId =
|
const assessmentId = num("assessmentId") ?? num("assessmentID") ?? num("entityId") ?? num("id");
|
||||||
num("assessmentId") ??
|
|
||||||
num("assessmentID") ??
|
|
||||||
num("entityId") ??
|
|
||||||
num("id");
|
|
||||||
|
|
||||||
const navigateToAssessment = (): void => {
|
const navigateToAssessment = (): void => {
|
||||||
if (programme !== undefined && metaclass !== undefined) {
|
if (programme !== undefined && metaclass !== undefined) {
|
||||||
const itemSuffix =
|
const itemSuffix = assessmentId !== undefined ? `&item=${assessmentId}` : "";
|
||||||
assessmentId !== undefined ? `&item=${assessmentId}` : "";
|
navigateToHashRoute(`/assessments/${programme}:${metaclass}${itemSuffix}`);
|
||||||
navigateToHashRoute(
|
|
||||||
`/assessments/${programme}:${metaclass}${itemSuffix}`,
|
|
||||||
);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (assessmentId !== undefined) {
|
if (assessmentId !== undefined) {
|
||||||
|
|||||||
@@ -302,10 +302,7 @@ export async function seqtaFetchPayload<T = any>(
|
|||||||
const res = await seqtaFetchJson<T>(path, body, options);
|
const res = await seqtaFetchJson<T>(path, body, options);
|
||||||
return res.payload ?? null;
|
return res.payload ?? null;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.warn(
|
console.warn(`[Global Search API] Request to ${normalizeSeqtaPath(path)} failed:`, e);
|
||||||
`[Global Search API] Request to ${normalizeSeqtaPath(path)} failed:`,
|
|
||||||
e,
|
|
||||||
);
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -36,10 +36,7 @@ function attachConnection(db: IDBDatabase): void {
|
|||||||
updateVersion(db.version);
|
updateVersion(db.version);
|
||||||
}
|
}
|
||||||
|
|
||||||
function setupUpgradeHandler(
|
function setupUpgradeHandler(request: IDBOpenDBRequest, extraStore?: string): void {
|
||||||
request: IDBOpenDBRequest,
|
|
||||||
extraStore?: string,
|
|
||||||
): void {
|
|
||||||
request.onupgradeneeded = (event) => {
|
request.onupgradeneeded = (event) => {
|
||||||
const db = request.result;
|
const db = request.result;
|
||||||
|
|
||||||
@@ -61,10 +58,7 @@ function openDatabase(version?: number, extraStore?: string): Promise<IDBDatabas
|
|||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
let request: IDBOpenDBRequest;
|
let request: IDBOpenDBRequest;
|
||||||
try {
|
try {
|
||||||
request =
|
request = version != null ? indexedDB.open(DB_NAME, version) : indexedDB.open(DB_NAME);
|
||||||
version != null
|
|
||||||
? indexedDB.open(DB_NAME, version)
|
|
||||||
: indexedDB.open(DB_NAME);
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
reject(error);
|
reject(error);
|
||||||
return;
|
return;
|
||||||
@@ -85,10 +79,7 @@ function wipeDatabase(): Promise<void> {
|
|||||||
return deleteDatabaseWithRetries(DB_NAME);
|
return deleteDatabaseWithRetries(DB_NAME);
|
||||||
}
|
}
|
||||||
|
|
||||||
function deleteDatabaseWithRetries(
|
function deleteDatabaseWithRetries(name: string, maxAttempts = 6): Promise<void> {
|
||||||
name: string,
|
|
||||||
maxAttempts = 6,
|
|
||||||
): Promise<void> {
|
|
||||||
return new Promise((resolve) => {
|
return new Promise((resolve) => {
|
||||||
const attemptDelete = (attempt: number) => {
|
const attemptDelete = (attempt: number) => {
|
||||||
let req: IDBOpenDBRequest;
|
let req: IDBOpenDBRequest;
|
||||||
@@ -146,9 +137,7 @@ async function openDBInternal(): Promise<IDBDatabase> {
|
|||||||
const domError = error as DOMException | undefined;
|
const domError = error as DOMException | undefined;
|
||||||
|
|
||||||
if (domError?.name === "VersionError") {
|
if (domError?.name === "VersionError") {
|
||||||
console.warn(
|
console.warn("[DB] localStorage version out of sync with IndexedDB; opening current version");
|
||||||
"[DB] localStorage version out of sync with IndexedDB; opening current version",
|
|
||||||
);
|
|
||||||
invalidateConnection();
|
invalidateConnection();
|
||||||
try {
|
try {
|
||||||
return await openDatabase();
|
return await openDatabase();
|
||||||
@@ -293,9 +282,7 @@ export async function ensureStoresExist(stores: string[]): Promise<void> {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const missing = uniqueStores.filter(
|
const missing = uniqueStores.filter((store) => !db.objectStoreNames.contains(store));
|
||||||
(store) => !db.objectStoreNames.contains(store),
|
|
||||||
);
|
|
||||||
if (missing.length === 0) return;
|
if (missing.length === 0) return;
|
||||||
|
|
||||||
invalidateConnection();
|
invalidateConnection();
|
||||||
@@ -334,9 +321,7 @@ async function withObjectStore<T>(
|
|||||||
|
|
||||||
export async function getAll(store: string): Promise<any[]> {
|
export async function getAll(store: string): Promise<any[]> {
|
||||||
try {
|
try {
|
||||||
return await withObjectStore(store, "readonly", async (s) =>
|
return await withObjectStore(store, "readonly", async (s) => idbRequest(s.getAll()));
|
||||||
idbRequest(s.getAll()),
|
|
||||||
);
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(`Error in getAll for store ${store}:`, error);
|
console.error(`Error in getAll for store ${store}:`, error);
|
||||||
return [];
|
return [];
|
||||||
@@ -345,20 +330,14 @@ export async function getAll(store: string): Promise<any[]> {
|
|||||||
|
|
||||||
export async function get(store: string, key: string): Promise<any> {
|
export async function get(store: string, key: string): Promise<any> {
|
||||||
try {
|
try {
|
||||||
return await withObjectStore(store, "readonly", async (s) =>
|
return await withObjectStore(store, "readonly", async (s) => idbRequest(s.get(key)));
|
||||||
idbRequest(s.get(key)),
|
|
||||||
);
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(`Error in get for store ${store}, key ${key}:`, error);
|
console.error(`Error in get for store ${store}, key ${key}:`, error);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function put(
|
export async function put(store: string, value: any, key?: string): Promise<void> {
|
||||||
store: string,
|
|
||||||
value: any,
|
|
||||||
key?: string,
|
|
||||||
): Promise<void> {
|
|
||||||
try {
|
try {
|
||||||
await withObjectStore(store, "readwrite", async (s) => {
|
await withObjectStore(store, "readwrite", async (s) => {
|
||||||
await idbRequest(key ? s.put(value, key) : s.put(value));
|
await idbRequest(key ? s.put(value, key) : s.put(value));
|
||||||
|
|||||||
@@ -70,11 +70,7 @@ export function looksLikeSecretValue(value: unknown): boolean {
|
|||||||
if (/^[A-Za-z0-9+/=._-]{32,}$/.test(trimmed) && !/[.,!?]/.test(trimmed)) {
|
if (/^[A-Za-z0-9+/=._-]{32,}$/.test(trimmed) && !/[.,!?]/.test(trimmed)) {
|
||||||
// Reject obvious URLs and UUIDs (they're useful and not secret).
|
// Reject obvious URLs and UUIDs (they're useful and not secret).
|
||||||
if (/^https?:\/\//i.test(trimmed)) return false;
|
if (/^https?:\/\//i.test(trimmed)) return false;
|
||||||
if (
|
if (/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(trimmed)) {
|
||||||
/^[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 false;
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
@@ -119,10 +115,7 @@ const DEFAULT_EXTRACT_OPTIONS: Required<ExtractTextOptions> = {
|
|||||||
maxStringLength: 8000,
|
maxStringLength: 8000,
|
||||||
};
|
};
|
||||||
|
|
||||||
export function extractTextFromValue(
|
export function extractTextFromValue(value: unknown, options: ExtractTextOptions = {}): string {
|
||||||
value: unknown,
|
|
||||||
options: ExtractTextOptions = {},
|
|
||||||
): string {
|
|
||||||
const opts = { ...DEFAULT_EXTRACT_OPTIONS, ...options };
|
const opts = { ...DEFAULT_EXTRACT_OPTIONS, ...options };
|
||||||
const parts: string[] = [];
|
const parts: string[] = [];
|
||||||
let remaining = opts.maxChars;
|
let remaining = opts.maxChars;
|
||||||
@@ -197,9 +190,7 @@ export function redactSensitive<T>(value: T, depth = 0): T {
|
|||||||
if (depth >= 8) return value;
|
if (depth >= 8) return value;
|
||||||
|
|
||||||
if (Array.isArray(value)) {
|
if (Array.isArray(value)) {
|
||||||
return value
|
return value.slice(0, 200).map((v) => redactSensitive(v, depth + 1)) as unknown as T;
|
||||||
.slice(0, 200)
|
|
||||||
.map((v) => redactSensitive(v, depth + 1)) as unknown as T;
|
|
||||||
}
|
}
|
||||||
if (typeof value === "object") {
|
if (typeof value === "object") {
|
||||||
const out: Record<string, unknown> = {};
|
const out: Record<string, unknown> = {};
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ import { isIndexingPaused } from "./indexingPause";
|
|||||||
import { setIndexingActive } from "./indexingState";
|
import { setIndexingActive } from "./indexingState";
|
||||||
import { isPluginBlockedByPerformanceMode } from "@/seqta/utils/performanceMode";
|
import { isPluginBlockedByPerformanceMode } from "@/seqta/utils/performanceMode";
|
||||||
|
|
||||||
import { verboseDebug } from '@/utils/verboseLog';
|
import { verboseDebug } from "@/utils/verboseLog";
|
||||||
import { delay } from "@/seqta/utils/delay";
|
import { delay } from "@/seqta/utils/delay";
|
||||||
const META_STORE = "meta";
|
const META_STORE = "meta";
|
||||||
const LOCK_KEY = "bsq-indexer-lock";
|
const LOCK_KEY = "bsq-indexer-lock";
|
||||||
@@ -104,10 +104,7 @@ function indexItemsEqual(a: IndexItem, b: IndexItem): boolean {
|
|||||||
return indexItemStorageKey(a) === indexItemStorageKey(b);
|
return indexItemStorageKey(a) === indexItemStorageKey(b);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function diffAndStoreItems(
|
async function diffAndStoreItems(targetStore: string, items: IndexItem[]): Promise<void> {
|
||||||
targetStore: string,
|
|
||||||
items: IndexItem[],
|
|
||||||
): Promise<void> {
|
|
||||||
const validItems = items.filter((i) => i && i.id);
|
const validItems = items.filter((i) => i && i.id);
|
||||||
if (validItems.length !== items.length) {
|
if (validItems.length !== items.length) {
|
||||||
console.warn(
|
console.warn(
|
||||||
@@ -116,9 +113,7 @@ async function diffAndStoreItems(
|
|||||||
}
|
}
|
||||||
|
|
||||||
const existing = (await getAll(targetStore)) as IndexItem[];
|
const existing = (await getAll(targetStore)) as IndexItem[];
|
||||||
const existingMap = new Map(
|
const existingMap = new Map(existing.filter((i) => i?.id).map((i) => [i.id, i]));
|
||||||
existing.filter((i) => i?.id).map((i) => [i.id, i]),
|
|
||||||
);
|
|
||||||
const newMap = new Map(validItems.map((i) => [i.id, i]));
|
const newMap = new Map(validItems.map((i) => [i.id, i]));
|
||||||
|
|
||||||
const puts: Array<{ key: string; value: IndexItem }> = [];
|
const puts: Array<{ key: string; value: IndexItem }> = [];
|
||||||
@@ -192,10 +187,10 @@ async function acquireLock(): Promise<boolean> {
|
|||||||
function startHeartbeat() {
|
function startHeartbeat() {
|
||||||
const lockId = localStorage.getItem(LOCK_KEY);
|
const lockId = localStorage.getItem(LOCK_KEY);
|
||||||
if (!lockId) return;
|
if (!lockId) return;
|
||||||
|
|
||||||
heartbeatTimer = setInterval(() => {
|
heartbeatTimer = setInterval(() => {
|
||||||
if (localStorage.getItem(LOCK_KEY)?.endsWith(lockId.split('-')[1])) {
|
if (localStorage.getItem(LOCK_KEY)?.endsWith(lockId.split("-")[1])) {
|
||||||
const newLockId = `${Date.now()}-${lockId.split('-')[1]}`;
|
const newLockId = `${Date.now()}-${lockId.split("-")[1]}`;
|
||||||
localStorage.setItem(LOCK_KEY, newLockId);
|
localStorage.setItem(LOCK_KEY, newLockId);
|
||||||
}
|
}
|
||||||
}, HEARTBEAT_INTERVAL);
|
}, HEARTBEAT_INTERVAL);
|
||||||
@@ -247,9 +242,7 @@ export async function loadAllStoredItems(): Promise<IndexItem[]> {
|
|||||||
console.error(`Error loading items for job store ${jobId}:`, error);
|
console.error(`Error loading items for job store ${jobId}:`, error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
verboseDebug(
|
verboseDebug(`[Indexer] Loaded ${all.length} items from all primary stores.`);
|
||||||
`[Indexer] Loaded ${all.length} items from all primary stores.`,
|
|
||||||
);
|
|
||||||
return all;
|
return all;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -275,10 +268,22 @@ function dispatchVectorProgress(
|
|||||||
dispatchProgress(++completed, totalSteps, false, "Indexing finished", "Vectorization complete");
|
dispatchProgress(++completed, totalSteps, false, "Indexing finished", "Vectorization complete");
|
||||||
return completed;
|
return completed;
|
||||||
} else if (status === "error") {
|
} else if (status === "error") {
|
||||||
dispatchProgress(completed, totalSteps, false, "Vectorization failed", `Vectorization error: ${message}`);
|
dispatchProgress(
|
||||||
|
completed,
|
||||||
|
totalSteps,
|
||||||
|
false,
|
||||||
|
"Vectorization failed",
|
||||||
|
`Vectorization error: ${message}`,
|
||||||
|
);
|
||||||
return completed;
|
return completed;
|
||||||
} else if (status === "cancelled") {
|
} else if (status === "cancelled") {
|
||||||
dispatchProgress(completed, totalSteps, false, "Vectorization cancelled", `Vectorization cancelled: ${message}`);
|
dispatchProgress(
|
||||||
|
completed,
|
||||||
|
totalSteps,
|
||||||
|
false,
|
||||||
|
"Vectorization cancelled",
|
||||||
|
`Vectorization cancelled: ${message}`,
|
||||||
|
);
|
||||||
return completed;
|
return completed;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -293,9 +298,7 @@ export async function runIndexing(): Promise<void> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (isIndexingPaused()) {
|
if (isIndexingPaused()) {
|
||||||
verboseDebug(
|
verboseDebug("[Indexer] Skipping indexing — index was reset; reload the page to rebuild.");
|
||||||
"[Indexer] Skipping indexing — index was reset; reload the page to rebuild.",
|
|
||||||
);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -315,177 +318,160 @@ export async function runIndexing(): Promise<void> {
|
|||||||
verboseDebug("%c[Indexer] Starting indexing...", "color: green");
|
verboseDebug("%c[Indexer] Starting indexing...", "color: green");
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const jobIds = Object.keys(jobs);
|
const jobIds = Object.keys(jobs);
|
||||||
await ensureStoresExist([META_STORE, ...jobIds]);
|
await ensureStoresExist([META_STORE, ...jobIds]);
|
||||||
|
|
||||||
let completedJobs = 0;
|
let completedJobs = 0;
|
||||||
const totalSteps = jobIds.length + 1;
|
const totalSteps = jobIds.length + 1;
|
||||||
dispatchProgress(completedJobs, totalSteps, true, "Starting jobs");
|
dispatchProgress(completedJobs, totalSteps, true, "Starting jobs");
|
||||||
|
|
||||||
for (const jobId of jobIds) {
|
for (const jobId of jobIds) {
|
||||||
if (isIndexingPaused()) {
|
if (isIndexingPaused()) {
|
||||||
verboseDebug(
|
verboseDebug("[Indexer] Indexing stopped — index was reset; reload the page to rebuild.");
|
||||||
"[Indexer] Indexing stopped — index was reset; reload the page to rebuild.",
|
dispatchProgress(completedJobs, totalSteps, false, "Indexing paused — reload to rebuild");
|
||||||
);
|
return;
|
||||||
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,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
};
|
|
||||||
const removeItem = async (id: string, storeId?: string) => {
|
|
||||||
const targetStore = storeId ?? jobId;
|
|
||||||
await remove(targetStore, id);
|
|
||||||
};
|
|
||||||
|
|
||||||
const ctx: JobContext = {
|
dispatchProgress(completedJobs, totalSteps, true, `Running job: ${jobs[jobId].label}`);
|
||||||
getStoredItems,
|
const job = jobs[jobId];
|
||||||
setStoredItems,
|
const lastRun = await getLastRunMeta(jobId);
|
||||||
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] 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 getStoredItems = async (storeId?: string) => await getAll(storeId ?? jobId);
|
||||||
const newItemsRaw = await job.run(ctx);
|
const setStoredItems = async (items: IndexItem[], storeId?: string) => {
|
||||||
const stored = await getStoredItems();
|
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);
|
const ctx: JobContext = {
|
||||||
if (job.purge) merged = job.purge(merged);
|
getStoredItems,
|
||||||
|
setStoredItems,
|
||||||
await setStoredItems(merged);
|
addItem,
|
||||||
await updateLastRunMeta(jobId);
|
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(
|
verboseDebug(`%c[Indexer] Running job "${jobId}"...`, "color: #4ea1ff");
|
||||||
`%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 {
|
try {
|
||||||
const workerManager = VectorWorkerManager.getInstance();
|
const newItemsRaw = await job.run(ctx);
|
||||||
await workerManager.processItems(newItemsToVectorize, (progress) => {
|
const stored = await getStoredItems();
|
||||||
completedJobs = dispatchVectorProgress(progress, completedJobs, totalSteps);
|
|
||||||
});
|
let merged = mergeItems(stored, newItemsRaw);
|
||||||
verboseDebug(
|
if (job.purge) merged = job.purge(merged);
|
||||||
"%c[Indexer] Vectorization task for stored items sent to worker.",
|
|
||||||
"color: green",
|
await setStoredItems(merged);
|
||||||
);
|
await updateLastRunMeta(jobId);
|
||||||
} catch (error) {
|
|
||||||
console.error(
|
verboseDebug(
|
||||||
`%c[Indexer] ❌ Failed to send items to vector worker:`,
|
`%c[Indexer] ${job.label}: ${newItemsRaw.length} new items reported by run, ${merged.length} total items now in '${jobId}' store.`,
|
||||||
"color: red",
|
"color: #00c46f",
|
||||||
error,
|
);
|
||||||
);
|
} catch (err) {
|
||||||
dispatchProgress(
|
verboseDebug(`%c[Indexer] Job ${job.label} failed:`, "color: red");
|
||||||
completedJobs,
|
console.error(err);
|
||||||
totalSteps,
|
}
|
||||||
false,
|
|
||||||
"Vectorization failed",
|
completedJobs++;
|
||||||
String(error),
|
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 {
|
} else {
|
||||||
verboseDebug(
|
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",
|
"color: gray",
|
||||||
);
|
);
|
||||||
completedJobs++;
|
completedJobs++;
|
||||||
@@ -493,31 +479,18 @@ export async function runIndexing(): Promise<void> {
|
|||||||
completedJobs,
|
completedJobs,
|
||||||
totalSteps,
|
totalSteps,
|
||||||
false,
|
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();
|
allItemsInPrimaryStores = await loadAllStoredItems();
|
||||||
const itemsWithComponents = decorateIndexItems(allItemsInPrimaryStores);
|
const itemsWithComponents = decorateIndexItems(allItemsInPrimaryStores);
|
||||||
loadDynamicItems(itemsWithComponents);
|
loadDynamicItems(itemsWithComponents);
|
||||||
window.dispatchEvent(
|
window.dispatchEvent(
|
||||||
new CustomEvent("dynamic-items-updated", {
|
new CustomEvent("dynamic-items-updated", {
|
||||||
detail: { fullRebuild: true },
|
detail: { fullRebuild: true },
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
} finally {
|
} finally {
|
||||||
setIndexingActive(false);
|
setIndexingActive(false);
|
||||||
stopHeartbeat();
|
stopHeartbeat();
|
||||||
@@ -533,4 +506,4 @@ function mergeItems(existing: IndexItem[], incoming: IndexItem[]): IndexItem[] {
|
|||||||
if (item && item.id) map.set(item.id, item);
|
if (item && item.id) map.set(item.id, item);
|
||||||
}
|
}
|
||||||
return Array.from(map.values());
|
return Array.from(map.values());
|
||||||
}
|
}
|
||||||
@@ -1,7 +1,4 @@
|
|||||||
import {
|
import { isIndexingActive, setIndexingActive } from "./indexingState";
|
||||||
isIndexingActive,
|
|
||||||
setIndexingActive,
|
|
||||||
} from "./indexingState";
|
|
||||||
|
|
||||||
describe("indexingState", () => {
|
describe("indexingState", () => {
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import type { IndexItem, Job } from "../types";
|
import type { IndexItem, Job } from "../types";
|
||||||
|
|
||||||
import { verboseDebug } from '@/utils/verboseLog';
|
import { verboseDebug } from "@/utils/verboseLog";
|
||||||
import { delay } from "@/seqta/utils/delay";
|
import { delay } from "@/seqta/utils/delay";
|
||||||
import { getUserInfo } from "@/seqta/utils/userInfo";
|
import { getUserInfo } from "@/seqta/utils/userInfo";
|
||||||
const fetchJSON = async (url: string, body: any) => {
|
const fetchJSON = async (url: string, body: any) => {
|
||||||
@@ -28,9 +28,7 @@ const fetchUpcomingAssessments = async (student: number) => {
|
|||||||
const fetchSubjects = async () => {
|
const fetchSubjects = async () => {
|
||||||
try {
|
try {
|
||||||
const res = await fetchJSON("/seqta/student/load/subjects?", {});
|
const res = await fetchJSON("/seqta/student/load/subjects?", {});
|
||||||
return res.payload
|
return res.payload?.filter((s: any) => s.active === 1)?.flatMap((s: any) => s.subjects) || [];
|
||||||
?.filter((s: any) => s.active === 1)
|
|
||||||
?.flatMap((s: any) => s.subjects) || [];
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error("[Assignments job] Failed to fetch subjects:", e);
|
console.error("[Assignments job] Failed to fetch subjects:", e);
|
||||||
return [];
|
return [];
|
||||||
@@ -70,9 +68,12 @@ const fetchPastAssessments = async (student: number, subjects: any[]) => {
|
|||||||
res.payload.tasks.forEach(processAssessment);
|
res.payload.tasks.forEach(processAssessment);
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} 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);
|
return Object.values(map);
|
||||||
@@ -83,19 +84,19 @@ export const assignmentsJob: Job = {
|
|||||||
label: "Assignments",
|
label: "Assignments",
|
||||||
renderComponentId: "assessment",
|
renderComponentId: "assessment",
|
||||||
frequency: { type: "expiry", afterMs: 1000 * 60 * 60 * 24 }, // Daily
|
frequency: { type: "expiry", afterMs: 1000 * 60 * 60 * 24 }, // Daily
|
||||||
|
|
||||||
boostCriteria: (item, searchTerm) => {
|
boostCriteria: (item, searchTerm) => {
|
||||||
if (searchTerm === "") {
|
if (searchTerm === "") {
|
||||||
return -100;
|
return -100;
|
||||||
}
|
}
|
||||||
|
|
||||||
let score = 0;
|
let score = 0;
|
||||||
|
|
||||||
if (item.metadata.dueDate) {
|
if (item.metadata.dueDate) {
|
||||||
const dueDate = new Date(item.metadata.dueDate).getTime();
|
const dueDate = new Date(item.metadata.dueDate).getTime();
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
const daysUntilDue = (dueDate - now) / (1000 * 60 * 60 * 24);
|
const daysUntilDue = (dueDate - now) / (1000 * 60 * 60 * 24);
|
||||||
|
|
||||||
if (daysUntilDue >= 0 && daysUntilDue <= 7) {
|
if (daysUntilDue >= 0 && daysUntilDue <= 7) {
|
||||||
score += 0.05; // Boost assignments due within a week
|
score += 0.05; // Boost assignments due within a week
|
||||||
}
|
}
|
||||||
@@ -103,11 +104,11 @@ export const assignmentsJob: Job = {
|
|||||||
score -= 0.1; // Penalty for overdue assignments
|
score -= 0.1; // Penalty for overdue assignments
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (item.metadata.submitted) {
|
if (item.metadata.submitted) {
|
||||||
score += 0.02;
|
score += 0.02;
|
||||||
}
|
}
|
||||||
|
|
||||||
return score;
|
return score;
|
||||||
},
|
},
|
||||||
|
|
||||||
@@ -118,33 +119,37 @@ export const assignmentsJob: Job = {
|
|||||||
|
|
||||||
const { id: student } = await getUserInfo();
|
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([
|
const [upcoming, subjects] = await Promise.all([
|
||||||
fetchUpcomingAssessments(student),
|
fetchUpcomingAssessments(student),
|
||||||
fetchSubjects(),
|
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);
|
const past = await fetchPastAssessments(student, subjects);
|
||||||
|
|
||||||
verboseDebug(`[Assignments job] Fetched ${past.length} past assessments`);
|
verboseDebug(`[Assignments job] Fetched ${past.length} past assessments`);
|
||||||
|
|
||||||
const subjectLookup = new Map<string, { programme: number; metaclass: number }>();
|
const subjectLookup = new Map<string, { programme: number; metaclass: number }>();
|
||||||
subjects.forEach((s: any) => {
|
subjects.forEach((s: any) => {
|
||||||
if (s.code && s.programme && s.metaclass) {
|
if (s.code && s.programme && s.metaclass) {
|
||||||
subjectLookup.set(s.code, { programme: s.programme, metaclass: s.metaclass });
|
subjectLookup.set(s.code, { programme: s.programme, metaclass: s.metaclass });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
const allAssessments = new Map<number, any>();
|
const allAssessments = new Map<number, any>();
|
||||||
|
|
||||||
upcoming.forEach((a: any) => {
|
upcoming.forEach((a: any) => {
|
||||||
if (a && a.id) {
|
if (a && a.id) {
|
||||||
let programme = a.programmeID || a.programme;
|
let programme = a.programmeID || a.programme;
|
||||||
let metaclass = a.metaclassID || a.metaclass;
|
let metaclass = a.metaclassID || a.metaclass;
|
||||||
|
|
||||||
if ((!programme || !metaclass) && a.code) {
|
if ((!programme || !metaclass) && a.code) {
|
||||||
const subjectInfo = subjectLookup.get(a.code);
|
const subjectInfo = subjectLookup.get(a.code);
|
||||||
if (subjectInfo) {
|
if (subjectInfo) {
|
||||||
@@ -152,7 +157,7 @@ export const assignmentsJob: Job = {
|
|||||||
metaclass = metaclass || subjectInfo.metaclass;
|
metaclass = metaclass || subjectInfo.metaclass;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
allAssessments.set(a.id, {
|
allAssessments.set(a.id, {
|
||||||
...a,
|
...a,
|
||||||
programme,
|
programme,
|
||||||
@@ -163,17 +168,17 @@ export const assignmentsJob: Job = {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
past.forEach((a: any) => {
|
past.forEach((a: any) => {
|
||||||
if (a && a.id) {
|
if (a && a.id) {
|
||||||
let programme = a.programmeID || a.programme;
|
let programme = a.programmeID || a.programme;
|
||||||
let metaclass = a.metaclassID || a.metaclass;
|
let metaclass = a.metaclassID || a.metaclass;
|
||||||
|
|
||||||
const existing = allAssessments.get(a.id);
|
const existing = allAssessments.get(a.id);
|
||||||
if (existing) {
|
if (existing) {
|
||||||
programme = programme || existing.programme || existing.programmeID;
|
programme = programme || existing.programme || existing.programmeID;
|
||||||
metaclass = metaclass || existing.metaclass || existing.metaclassID;
|
metaclass = metaclass || existing.metaclass || existing.metaclassID;
|
||||||
|
|
||||||
Object.assign(existing, {
|
Object.assign(existing, {
|
||||||
...a,
|
...a,
|
||||||
programme,
|
programme,
|
||||||
@@ -182,13 +187,13 @@ export const assignmentsJob: Job = {
|
|||||||
metaclassID: metaclass,
|
metaclassID: metaclass,
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
allAssessments.set(a.id, {
|
allAssessments.set(a.id, {
|
||||||
...a,
|
...a,
|
||||||
programme,
|
programme,
|
||||||
metaclass,
|
metaclass,
|
||||||
programmeID: programme,
|
programmeID: programme,
|
||||||
metaclassID: metaclass,
|
metaclassID: metaclass,
|
||||||
isUpcoming: false
|
isUpcoming: false,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -198,79 +203,87 @@ export const assignmentsJob: Job = {
|
|||||||
const processedIds = new Set<string>();
|
const processedIds = new Set<string>();
|
||||||
|
|
||||||
const assessmentArray = Array.from(allAssessments.values());
|
const assessmentArray = Array.from(allAssessments.values());
|
||||||
const pastCount = assessmentArray.filter(a => !a.isUpcoming).length;
|
const pastCount = assessmentArray.filter((a) => !a.isUpcoming).length;
|
||||||
const upcomingCount = 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)`);
|
verboseDebug(
|
||||||
|
`[Assignments job] Processing ${assessmentArray.length} total assessments (${upcomingCount} upcoming, ${pastCount} past)`,
|
||||||
|
);
|
||||||
const batchSize = 15;
|
const batchSize = 15;
|
||||||
|
|
||||||
// The assessment details endpoint 404s, so details aren't fetched.
|
// The assessment details endpoint 404s, so details aren't fetched.
|
||||||
|
|
||||||
for (let i = 0; i < assessmentArray.length; i += batchSize) {
|
for (let i = 0; i < assessmentArray.length; i += batchSize) {
|
||||||
const batch = assessmentArray.slice(i, i + batchSize);
|
const batch = assessmentArray.slice(i, i + batchSize);
|
||||||
|
|
||||||
const batchItems = await Promise.all(
|
const batchItems = await Promise.all(
|
||||||
batch.map(async (assessment) => {
|
batch.map(async (assessment) => {
|
||||||
const id = `assignment-${assessment.id}`;
|
const id = `assignment-${assessment.id}`;
|
||||||
|
|
||||||
if (processedIds.has(id)) {
|
if (processedIds.has(id)) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
processedIds.add(id);
|
processedIds.add(id);
|
||||||
|
|
||||||
|
|
||||||
const description = "";
|
const description = "";
|
||||||
|
|
||||||
const subjectName = assessment.subject || assessment.code || "Unknown Subject";
|
const subjectName = assessment.subject || assessment.code || "Unknown Subject";
|
||||||
const dueDate = assessment.due ? new Date(assessment.due).getTime() : null;
|
const dueDate = assessment.due ? new Date(assessment.due).getTime() : null;
|
||||||
|
|
||||||
const programmeId = assessment.programmeID || assessment.programme;
|
const programmeId = assessment.programmeID || assessment.programme;
|
||||||
const metaclassId = assessment.metaclassID || assessment.metaclass;
|
const metaclassId = assessment.metaclassID || assessment.metaclass;
|
||||||
|
|
||||||
if (!programmeId || !metaclassId || !assessment.id) {
|
if (!programmeId || !metaclassId || !assessment.id) {
|
||||||
console.warn(`[Assignments job] Skipping assignment ${assessment.id} - missing required IDs:`, {
|
console.warn(
|
||||||
programmeId,
|
`[Assignments job] Skipping assignment ${assessment.id} - missing required IDs:`,
|
||||||
metaclassId,
|
{
|
||||||
assessmentId: assessment.id,
|
programmeId,
|
||||||
programmeID: assessment.programmeID,
|
metaclassId,
|
||||||
metaclassID: assessment.metaclassID,
|
assessmentId: assessment.id,
|
||||||
programme: assessment.programme,
|
programmeID: assessment.programmeID,
|
||||||
metaclass: assessment.metaclass,
|
metaclassID: assessment.metaclassID,
|
||||||
assessment,
|
programme: assessment.programme,
|
||||||
});
|
metaclass: assessment.metaclass,
|
||||||
|
assessment,
|
||||||
|
},
|
||||||
|
);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
let finalProgrammeId: number | undefined;
|
let finalProgrammeId: number | undefined;
|
||||||
let finalMetaclassId: number | undefined;
|
let finalMetaclassId: number | undefined;
|
||||||
|
|
||||||
if (programmeId !== undefined && programmeId !== null && programmeId !== '') {
|
if (programmeId !== undefined && programmeId !== null && programmeId !== "") {
|
||||||
const num = Number(programmeId);
|
const num = Number(programmeId);
|
||||||
finalProgrammeId = isNaN(num) ? undefined : num;
|
finalProgrammeId = isNaN(num) ? undefined : num;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (metaclassId !== undefined && metaclassId !== null && metaclassId !== '') {
|
if (metaclassId !== undefined && metaclassId !== null && metaclassId !== "") {
|
||||||
const num = Number(metaclassId);
|
const num = Number(metaclassId);
|
||||||
finalMetaclassId = isNaN(num) ? undefined : num;
|
finalMetaclassId = isNaN(num) ? undefined : num;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (finalProgrammeId === undefined || finalMetaclassId === undefined || !assessment.id) {
|
if (finalProgrammeId === undefined || finalMetaclassId === undefined || !assessment.id) {
|
||||||
console.error(`[Assignments job] ❌ Skipping assignment ${assessment.id} - invalid IDs after conversion:`, {
|
console.error(
|
||||||
programmeId: finalProgrammeId,
|
`[Assignments job] ❌ Skipping assignment ${assessment.id} - invalid IDs after conversion:`,
|
||||||
metaclassId: finalMetaclassId,
|
{
|
||||||
assessmentId: assessment.id,
|
programmeId: finalProgrammeId,
|
||||||
rawProgrammeId: programmeId,
|
metaclassId: finalMetaclassId,
|
||||||
rawMetaclassId: metaclassId,
|
assessmentId: assessment.id,
|
||||||
assessment,
|
rawProgrammeId: programmeId,
|
||||||
});
|
rawMetaclassId: metaclassId,
|
||||||
|
assessment,
|
||||||
|
},
|
||||||
|
);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
const item: IndexItem = {
|
const item: IndexItem = {
|
||||||
id,
|
id,
|
||||||
text: assessment.title || assessment.name || "Untitled Assignment",
|
text: assessment.title || assessment.name || "Untitled Assignment",
|
||||||
category: "assignments",
|
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(),
|
dateAdded: dueDate || Date.now(),
|
||||||
metadata: {
|
metadata: {
|
||||||
assessmentId: assessment.id,
|
assessmentId: assessment.id,
|
||||||
@@ -290,7 +303,7 @@ export const assignmentsJob: Job = {
|
|||||||
actionId: "assessment",
|
actionId: "assessment",
|
||||||
renderComponentId: "assessment",
|
renderComponentId: "assessment",
|
||||||
};
|
};
|
||||||
|
|
||||||
verboseDebug(`[Assignments job] ✅ Created item for assignment ${assessment.id}:`, {
|
verboseDebug(`[Assignments job] ✅ Created item for assignment ${assessment.id}:`, {
|
||||||
id: item.id,
|
id: item.id,
|
||||||
programmeId: item.metadata.programmeId,
|
programmeId: item.metadata.programmeId,
|
||||||
@@ -302,34 +315,37 @@ export const assignmentsJob: Job = {
|
|||||||
});
|
});
|
||||||
|
|
||||||
return item;
|
return item;
|
||||||
})
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
batchItems.forEach(item => {
|
batchItems.forEach((item) => {
|
||||||
if (item) {
|
if (item) {
|
||||||
items.push(item);
|
items.push(item);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
if (i + batchSize < assessmentArray.length) {
|
if (i + batchSize < assessmentArray.length) {
|
||||||
await delay(50);
|
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;
|
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;
|
return items;
|
||||||
},
|
},
|
||||||
|
|
||||||
purge: (items) => {
|
purge: (items) => {
|
||||||
// Old assignments stay searchable; only items missing required metadata are dropped.
|
// Old assignments stay searchable; only items missing required metadata are dropped.
|
||||||
return items.filter((i) => {
|
return items.filter((i) => {
|
||||||
return i.metadata &&
|
return (
|
||||||
i.metadata.assessmentId &&
|
i.metadata &&
|
||||||
i.metadata.programmeId !== undefined &&
|
i.metadata.assessmentId &&
|
||||||
i.metadata.metaclassId !== undefined;
|
i.metadata.programmeId !== undefined &&
|
||||||
|
i.metadata.metaclassId !== undefined
|
||||||
|
);
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -3,7 +3,7 @@ import { seqtaFetchPayload } from "../api";
|
|||||||
import { buildIndexItem } from "../extract";
|
import { buildIndexItem } from "../extract";
|
||||||
import { htmlToPlainText } from "../utils";
|
import { htmlToPlainText } from "../utils";
|
||||||
|
|
||||||
import { verboseDebug } from '@/utils/verboseLog';
|
import { verboseDebug } from "@/utils/verboseLog";
|
||||||
/**
|
/**
|
||||||
* Indexes per-subject course content from `/seqta/student/load/courses`.
|
* Indexes per-subject course content from `/seqta/student/load/courses`.
|
||||||
*
|
*
|
||||||
@@ -36,9 +36,7 @@ interface CoursePayload {
|
|||||||
document?: string;
|
document?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
const fetchActiveSubjects = async (): Promise<
|
const fetchActiveSubjects = async (): Promise<SubjectsListPayload["subjects"]> => {
|
||||||
SubjectsListPayload["subjects"]
|
|
||||||
> => {
|
|
||||||
const payload = await seqtaFetchPayload<SubjectsListPayload[]>(
|
const payload = await seqtaFetchPayload<SubjectsListPayload[]>(
|
||||||
"/seqta/student/load/subjects",
|
"/seqta/student/load/subjects",
|
||||||
{},
|
{},
|
||||||
@@ -50,11 +48,7 @@ const fetchActiveSubjects = async (): Promise<
|
|||||||
if (!semester || !Array.isArray(semester.subjects)) continue;
|
if (!semester || !Array.isArray(semester.subjects)) continue;
|
||||||
if (semester.active !== 1) continue;
|
if (semester.active !== 1) continue;
|
||||||
for (const subject of semester.subjects) {
|
for (const subject of semester.subjects) {
|
||||||
if (
|
if (subject && Number.isFinite(subject.programme) && Number.isFinite(subject.metaclass)) {
|
||||||
subject &&
|
|
||||||
Number.isFinite(subject.programme) &&
|
|
||||||
Number.isFinite(subject.metaclass)
|
|
||||||
) {
|
|
||||||
out.push(subject);
|
out.push(subject);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -129,13 +123,10 @@ export const coursesJob: Job = {
|
|||||||
status: `Running job: Courses (${processedSubjects + 1}/${totalSubjects})`,
|
status: `Running job: Courses (${processedSubjects + 1}/${totalSubjects})`,
|
||||||
});
|
});
|
||||||
|
|
||||||
const payload = await seqtaFetchPayload<CoursePayload>(
|
const payload = await seqtaFetchPayload<CoursePayload>("/seqta/student/load/courses", {
|
||||||
"/seqta/student/load/courses",
|
programme: String(subject.programme),
|
||||||
{
|
metaclass: String(subject.metaclass),
|
||||||
programme: String(subject.programme),
|
});
|
||||||
metaclass: String(subject.metaclass),
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
if (!payload) {
|
if (!payload) {
|
||||||
processedSubjects++;
|
processedSubjects++;
|
||||||
@@ -150,8 +141,7 @@ export const coursesJob: Job = {
|
|||||||
"Course";
|
"Course";
|
||||||
|
|
||||||
const lessonText = flattenLessonHtml(payload);
|
const lessonText = flattenLessonHtml(payload);
|
||||||
const courseCode =
|
const courseCode = (typeof payload.c === "string" && payload.c.trim()) || subject.code;
|
||||||
(typeof payload.c === "string" && payload.c.trim()) || subject.code;
|
|
||||||
|
|
||||||
const summary = [courseCode, lessonText]
|
const summary = [courseCode, lessonText]
|
||||||
.filter((s) => s && s.length > 0)
|
.filter((s) => s && s.length > 0)
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import type { IndexItem, Job } from "../types";
|
import type { IndexItem, Job } from "../types";
|
||||||
import { seqtaFetchPayload } from "../api";
|
import { seqtaFetchPayload } from "../api";
|
||||||
|
|
||||||
import { verboseDebug } from '@/utils/verboseLog';
|
import { verboseDebug } from "@/utils/verboseLog";
|
||||||
/**
|
/**
|
||||||
* Indexes file metadata from `/seqta/student/load/documents`.
|
* Indexes file metadata from `/seqta/student/load/documents`.
|
||||||
*
|
*
|
||||||
@@ -87,10 +87,7 @@ export const documentsJob: Job = {
|
|||||||
if (seen.has(id)) continue;
|
if (seen.has(id)) continue;
|
||||||
seen.add(id);
|
seen.add(id);
|
||||||
|
|
||||||
const title =
|
const title = doc.title?.trim() || doc.filename?.trim() || `Document ${doc.file ?? uuid}`;
|
||||||
doc.title?.trim() ||
|
|
||||||
doc.filename?.trim() ||
|
|
||||||
`Document ${doc.file ?? uuid}`;
|
|
||||||
|
|
||||||
const sizeText = prettySize(doc.size);
|
const sizeText = prettySize(doc.size);
|
||||||
const mimeLabel = describeMime(doc.mimetype);
|
const mimeLabel = describeMime(doc.mimetype);
|
||||||
@@ -117,8 +114,7 @@ export const documentsJob: Job = {
|
|||||||
fileId: doc.file,
|
fileId: doc.file,
|
||||||
filename: doc.filename,
|
filename: doc.filename,
|
||||||
mimetype: doc.mimetype,
|
mimetype: doc.mimetype,
|
||||||
sizeBytes:
|
sizeBytes: typeof doc.size === "string" ? parseInt(doc.size, 10) : doc.size,
|
||||||
typeof doc.size === "string" ? parseInt(doc.size, 10) : doc.size,
|
|
||||||
categoryId: category.id,
|
categoryId: category.id,
|
||||||
categoryName: category.category,
|
categoryName: category.category,
|
||||||
createdDate: doc.created_date,
|
createdDate: doc.created_date,
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import { seqtaFetchPayload } from "../api";
|
|||||||
import { htmlToPlainText } from "../utils";
|
import { htmlToPlainText } from "../utils";
|
||||||
import { delay } from "@/seqta/utils/delay";
|
import { delay } from "@/seqta/utils/delay";
|
||||||
|
|
||||||
import { verboseDebug } from '@/utils/verboseLog';
|
import { verboseDebug } from "@/utils/verboseLog";
|
||||||
/**
|
/**
|
||||||
* Indexes student folio entries from `/seqta/student/folio`.
|
* Indexes student folio entries from `/seqta/student/folio`.
|
||||||
*
|
*
|
||||||
@@ -61,10 +61,11 @@ export const folioJob: Job = {
|
|||||||
const stored = await ctx.getStoredItems("folio");
|
const stored = await ctx.getStoredItems("folio");
|
||||||
const existing = new Map(stored.map((i) => [i.id, i]));
|
const existing = new Map(stored.map((i) => [i.id, i]));
|
||||||
|
|
||||||
const list = await seqtaFetchPayload<FolioListPayload | null>(
|
const list = await seqtaFetchPayload<FolioListPayload | null>("/seqta/student/folio", {
|
||||||
"/seqta/student/folio",
|
mode: "list",
|
||||||
{ mode: "list", page: 0, filters: {} },
|
page: 0,
|
||||||
);
|
filters: {},
|
||||||
|
});
|
||||||
if (!list || !Array.isArray(list.list)) return [];
|
if (!list || !Array.isArray(list.list)) return [];
|
||||||
|
|
||||||
const items: IndexItem[] = [];
|
const items: IndexItem[] = [];
|
||||||
@@ -88,10 +89,10 @@ export const folioJob: Job = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const detail = await seqtaFetchPayload<FolioEntryPayload | null>(
|
const detail = await seqtaFetchPayload<FolioEntryPayload | null>("/seqta/student/folio", {
|
||||||
"/seqta/student/folio",
|
mode: "load",
|
||||||
{ mode: "load", id: entry.id },
|
id: entry.id,
|
||||||
);
|
});
|
||||||
const rawContents = detail?.contents ?? "";
|
const rawContents = detail?.contents ?? "";
|
||||||
const flattened = stripEmbedRaw(rawContents);
|
const flattened = stripEmbedRaw(rawContents);
|
||||||
const content = flattened.slice(0, 4000);
|
const content = flattened.slice(0, 4000);
|
||||||
|
|||||||
@@ -21,9 +21,7 @@ export const forumsJob: Job = {
|
|||||||
frequency: { type: "expiry", afterMs: 30 * 24 * 60 * 60 * 1000 }, // 30 days
|
frequency: { type: "expiry", afterMs: 30 * 24 * 60 * 60 * 1000 }, // 30 days
|
||||||
|
|
||||||
run: async (ctx) => {
|
run: async (ctx) => {
|
||||||
const existingIds = new Set(
|
const existingIds = new Set((await ctx.getStoredItems("forums")).map((i) => i.id));
|
||||||
(await ctx.getStoredItems("forums")).map((i) => i.id),
|
|
||||||
);
|
|
||||||
|
|
||||||
let list;
|
let list;
|
||||||
try {
|
try {
|
||||||
@@ -61,9 +59,9 @@ export const forumsJob: Job = {
|
|||||||
return items;
|
return items;
|
||||||
},
|
},
|
||||||
|
|
||||||
/** Keep only forums from the last year. */
|
/** Keep only forums from the last year. */
|
||||||
purge: (items) => {
|
purge: (items) => {
|
||||||
const oneYearAgo = Date.now() - 365 * 24 * 60 * 60 * 1000;
|
const oneYearAgo = Date.now() - 365 * 24 * 60 * 60 * 1000;
|
||||||
return items.filter((i) => i.dateAdded >= oneYearAgo);
|
return items.filter((i) => i.dateAdded >= oneYearAgo);
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
@@ -3,7 +3,7 @@ import { seqtaFetchPayload } from "../api";
|
|||||||
import { extractTextFromValue } from "../extract";
|
import { extractTextFromValue } from "../extract";
|
||||||
import { delay } from "@/seqta/utils/delay";
|
import { delay } from "@/seqta/utils/delay";
|
||||||
|
|
||||||
import { verboseDebug } from '@/utils/verboseLog';
|
import { verboseDebug } from "@/utils/verboseLog";
|
||||||
/**
|
/**
|
||||||
* Indexes student goals from `/seqta/student/load/goals`.
|
* Indexes student goals from `/seqta/student/load/goals`.
|
||||||
*
|
*
|
||||||
@@ -52,10 +52,10 @@ export const goalsJob: Job = {
|
|||||||
|
|
||||||
for (const year of years) {
|
for (const year of years) {
|
||||||
try {
|
try {
|
||||||
const yearGoals = await seqtaFetchPayload<GoalEntry[] | null>(
|
const yearGoals = await seqtaFetchPayload<GoalEntry[] | null>("/seqta/student/load/goals", {
|
||||||
"/seqta/student/load/goals",
|
mode: "list",
|
||||||
{ mode: "list", year },
|
year,
|
||||||
);
|
});
|
||||||
if (!Array.isArray(yearGoals)) continue;
|
if (!Array.isArray(yearGoals)) continue;
|
||||||
|
|
||||||
for (const goal of yearGoals) {
|
for (const goal of yearGoals) {
|
||||||
@@ -66,11 +66,11 @@ export const goalsJob: Job = {
|
|||||||
if (seen.has(id)) continue;
|
if (seen.has(id)) continue;
|
||||||
seen.add(id);
|
seen.add(id);
|
||||||
|
|
||||||
const title =
|
const title = goal.title?.trim() || goal.description?.slice(0, 80) || `Goal ${stableId}`;
|
||||||
goal.title?.trim() || goal.description?.slice(0, 80) || `Goal ${stableId}`;
|
const dateAdded =
|
||||||
const dateAdded = goal.updated || goal.created
|
goal.updated || goal.created
|
||||||
? new Date(goal.updated ?? goal.created!).getTime() || Date.now()
|
? new Date(goal.updated ?? goal.created!).getTime() || Date.now()
|
||||||
: Date.now();
|
: Date.now();
|
||||||
|
|
||||||
items.push({
|
items.push({
|
||||||
id,
|
id,
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import { VectorWorkerManager } from "../worker/vectorWorkerManager";
|
|||||||
import { loadAllStoredItems } from "../indexer";
|
import { loadAllStoredItems } from "../indexer";
|
||||||
import { publishDynamicItemsUpdate } from "../renderComponents";
|
import { publishDynamicItemsUpdate } from "../renderComponents";
|
||||||
|
|
||||||
import { verboseInfo, verboseLog } from '@/utils/verboseLog';
|
import { verboseInfo, verboseLog } from "@/utils/verboseLog";
|
||||||
const RATE_LIMIT_CONFIG = {
|
const RATE_LIMIT_CONFIG = {
|
||||||
minDelay: 30,
|
minDelay: 30,
|
||||||
maxDelay: 3000,
|
maxDelay: 3000,
|
||||||
@@ -89,8 +89,7 @@ export const fetchMessageContent = async (
|
|||||||
|
|
||||||
if (retryCount < RATE_LIMIT_CONFIG.maxRetries) {
|
if (retryCount < RATE_LIMIT_CONFIG.maxRetries) {
|
||||||
const retryDelay =
|
const retryDelay =
|
||||||
RATE_LIMIT_CONFIG.baseDelay *
|
RATE_LIMIT_CONFIG.baseDelay * Math.pow(RATE_LIMIT_CONFIG.backoffMultiplier, retryCount);
|
||||||
Math.pow(RATE_LIMIT_CONFIG.backoffMultiplier, retryCount);
|
|
||||||
await delay(Math.min(retryDelay, RATE_LIMIT_CONFIG.maxDelay));
|
await delay(Math.min(retryDelay, RATE_LIMIT_CONFIG.maxDelay));
|
||||||
return fetchMessageContent(id, retryCount + 1);
|
return fetchMessageContent(id, retryCount + 1);
|
||||||
}
|
}
|
||||||
@@ -99,17 +98,9 @@ export const fetchMessageContent = async (
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
function calculateAdaptiveDelay(
|
function calculateAdaptiveDelay(progress: MessagesProgress, responseTime: number): number {
|
||||||
progress: MessagesProgress,
|
const { currentDelay, failedRequests, lastSuccessTime, circuitBreakerOpen, consecutiveFailures } =
|
||||||
responseTime: number,
|
progress;
|
||||||
): number {
|
|
||||||
const {
|
|
||||||
currentDelay,
|
|
||||||
failedRequests,
|
|
||||||
lastSuccessTime,
|
|
||||||
circuitBreakerOpen,
|
|
||||||
consecutiveFailures,
|
|
||||||
} = progress;
|
|
||||||
const timeSinceLastSuccess = Date.now() - lastSuccessTime;
|
const timeSinceLastSuccess = Date.now() - lastSuccessTime;
|
||||||
|
|
||||||
if (circuitBreakerOpen) {
|
if (circuitBreakerOpen) {
|
||||||
@@ -118,17 +109,12 @@ function calculateAdaptiveDelay(
|
|||||||
|
|
||||||
if (consecutiveFailures > 2 || failedRequests > 3 || responseTime > 3000) {
|
if (consecutiveFailures > 2 || failedRequests > 3 || responseTime > 3000) {
|
||||||
return Math.min(
|
return Math.min(
|
||||||
currentDelay *
|
currentDelay * (RATE_LIMIT_CONFIG.backoffMultiplier + consecutiveFailures * 0.2),
|
||||||
(RATE_LIMIT_CONFIG.backoffMultiplier + consecutiveFailures * 0.2),
|
|
||||||
RATE_LIMIT_CONFIG.maxDelay,
|
RATE_LIMIT_CONFIG.maxDelay,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (
|
if (responseTime < 300 && timeSinceLastSuccess > 5000 && consecutiveFailures === 0) {
|
||||||
responseTime < 300 &&
|
|
||||||
timeSinceLastSuccess > 5000 &&
|
|
||||||
consecutiveFailures === 0
|
|
||||||
) {
|
|
||||||
return Math.max(currentDelay * 0.7, RATE_LIMIT_CONFIG.minDelay);
|
return Math.max(currentDelay * 0.7, RATE_LIMIT_CONFIG.minDelay);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -149,37 +135,23 @@ async function estimateMessageCount(): Promise<number> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function calculateAdaptiveBatchSize(
|
function calculateAdaptiveBatchSize(progress: MessagesProgress, responseTime: number): number {
|
||||||
progress: MessagesProgress,
|
|
||||||
responseTime: number,
|
|
||||||
): number {
|
|
||||||
if (!RATE_LIMIT_CONFIG.adaptiveBatchSize) {
|
if (!RATE_LIMIT_CONFIG.adaptiveBatchSize) {
|
||||||
return progress.currentBatchSize;
|
return progress.currentBatchSize;
|
||||||
}
|
}
|
||||||
|
|
||||||
const {
|
const { currentBatchSize, failedRequests, circuitBreakerOpen, consecutiveFailures } = progress;
|
||||||
currentBatchSize,
|
|
||||||
failedRequests,
|
|
||||||
circuitBreakerOpen,
|
|
||||||
consecutiveFailures,
|
|
||||||
} = progress;
|
|
||||||
|
|
||||||
if (circuitBreakerOpen) {
|
if (circuitBreakerOpen) {
|
||||||
return RATE_LIMIT_CONFIG.minBatchSize;
|
return RATE_LIMIT_CONFIG.minBatchSize;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (consecutiveFailures > 1 || failedRequests > 2 || responseTime > 2500) {
|
if (consecutiveFailures > 1 || failedRequests > 2 || responseTime > 2500) {
|
||||||
return Math.max(
|
return Math.max(Math.floor(currentBatchSize * 0.6), RATE_LIMIT_CONFIG.minBatchSize);
|
||||||
Math.floor(currentBatchSize * 0.6),
|
|
||||||
RATE_LIMIT_CONFIG.minBatchSize,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (failedRequests === 0 && responseTime < 800 && consecutiveFailures === 0) {
|
if (failedRequests === 0 && responseTime < 800 && consecutiveFailures === 0) {
|
||||||
return Math.min(
|
return Math.min(Math.floor(currentBatchSize * 1.4), RATE_LIMIT_CONFIG.maxBatchSize);
|
||||||
Math.floor(currentBatchSize * 1.4),
|
|
||||||
RATE_LIMIT_CONFIG.maxBatchSize,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return currentBatchSize;
|
return currentBatchSize;
|
||||||
@@ -202,8 +174,7 @@ function checkCircuitBreaker(progress: MessagesProgress): boolean {
|
|||||||
|
|
||||||
if (
|
if (
|
||||||
progress.circuitBreakerOpen &&
|
progress.circuitBreakerOpen &&
|
||||||
now - progress.circuitBreakerOpenTime >
|
now - progress.circuitBreakerOpenTime > RATE_LIMIT_CONFIG.circuitBreakerResetTime
|
||||||
RATE_LIMIT_CONFIG.circuitBreakerResetTime
|
|
||||||
) {
|
) {
|
||||||
progress.circuitBreakerOpen = false;
|
progress.circuitBreakerOpen = false;
|
||||||
progress.consecutiveFailures = 0;
|
progress.consecutiveFailures = 0;
|
||||||
@@ -257,20 +228,11 @@ async function processMessagesInParallel(
|
|||||||
return { processedItems, consecutiveExisting, updatedProgress, shouldStop };
|
return { processedItems, consecutiveExisting, updatedProgress, shouldStop };
|
||||||
}
|
}
|
||||||
|
|
||||||
for (
|
for (let i = 0; i < messagesToProcess.length; i += RATE_LIMIT_CONFIG.parallelRequests) {
|
||||||
let i = 0;
|
const batch = messagesToProcess.slice(i, i + RATE_LIMIT_CONFIG.parallelRequests);
|
||||||
i < messagesToProcess.length;
|
|
||||||
i += RATE_LIMIT_CONFIG.parallelRequests
|
|
||||||
) {
|
|
||||||
const batch = messagesToProcess.slice(
|
|
||||||
i,
|
|
||||||
i + RATE_LIMIT_CONFIG.parallelRequests,
|
|
||||||
);
|
|
||||||
|
|
||||||
if (i > 0) {
|
if (i > 0) {
|
||||||
await delay(
|
await delay(Math.max(updatedProgress.currentDelay, RATE_LIMIT_CONFIG.parallelDelay));
|
||||||
Math.max(updatedProgress.currentDelay, RATE_LIMIT_CONFIG.parallelDelay),
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const batchStartTime = Date.now();
|
const batchStartTime = Date.now();
|
||||||
@@ -336,20 +298,14 @@ async function processMessagesInParallel(
|
|||||||
|
|
||||||
if (batchSuccesses > 0) {
|
if (batchSuccesses > 0) {
|
||||||
updatedProgress.lastSuccessTime = Date.now();
|
updatedProgress.lastSuccessTime = Date.now();
|
||||||
updatedProgress.failedRequests = Math.max(
|
updatedProgress.failedRequests = Math.max(0, updatedProgress.failedRequests - batchSuccesses);
|
||||||
0,
|
|
||||||
updatedProgress.failedRequests - batchSuccesses,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (batchFailures > 0) {
|
if (batchFailures > 0) {
|
||||||
updatedProgress.failedRequests += batchFailures;
|
updatedProgress.failedRequests += batchFailures;
|
||||||
}
|
}
|
||||||
|
|
||||||
updatedProgress.currentDelay = calculateAdaptiveDelay(
|
updatedProgress.currentDelay = calculateAdaptiveDelay(updatedProgress, batchResponseTime);
|
||||||
updatedProgress,
|
|
||||||
batchResponseTime,
|
|
||||||
);
|
|
||||||
|
|
||||||
verboseLog(
|
verboseLog(
|
||||||
`[Messages job] Processed parallel batch: ${batchSuccesses} successes, ${batchFailures} failures, ${batchResponseTime}ms total time`,
|
`[Messages job] Processed parallel batch: ${batchSuccesses} successes, ${batchFailures} failures, ${batchResponseTime}ms total time`,
|
||||||
@@ -409,10 +365,7 @@ export const messagesJob: Job = {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.warn(
|
console.warn("[Messages job] Failed to start streaming session:", error);
|
||||||
"[Messages job] Failed to start streaming session:",
|
|
||||||
error,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -427,14 +380,8 @@ export const messagesJob: Job = {
|
|||||||
const retryBatch = progress.retryQueue.slice(0, 10);
|
const retryBatch = progress.retryQueue.slice(0, 10);
|
||||||
const retryBatches = [];
|
const retryBatches = [];
|
||||||
|
|
||||||
for (
|
for (let i = 0; i < retryBatch.length; i += RATE_LIMIT_CONFIG.parallelRequests) {
|
||||||
let i = 0;
|
retryBatches.push(retryBatch.slice(i, i + RATE_LIMIT_CONFIG.parallelRequests));
|
||||||
i < retryBatch.length;
|
|
||||||
i += RATE_LIMIT_CONFIG.parallelRequests
|
|
||||||
) {
|
|
||||||
retryBatches.push(
|
|
||||||
retryBatch.slice(i, i + RATE_LIMIT_CONFIG.parallelRequests),
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
for (const batch of retryBatches) {
|
for (const batch of retryBatches) {
|
||||||
@@ -458,10 +405,7 @@ export const messagesJob: Job = {
|
|||||||
return { success: false, messageId, responseTime };
|
return { success: false, messageId, responseTime };
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(
|
console.error(`[Messages job] Retry failed for message ${messageId}:`, error);
|
||||||
`[Messages job] Retry failed for message ${messageId}:`,
|
|
||||||
error,
|
|
||||||
);
|
|
||||||
return { success: false, messageId, error };
|
return { success: false, messageId, error };
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -478,9 +422,7 @@ export const messagesJob: Job = {
|
|||||||
processedIdsSet.add(result.messageId.toString());
|
processedIdsSet.add(result.messageId.toString());
|
||||||
retrySuccesses++;
|
retrySuccesses++;
|
||||||
}
|
}
|
||||||
progress.retryQueue = progress.retryQueue.filter(
|
progress.retryQueue = progress.retryQueue.filter((mid) => mid !== result.messageId);
|
||||||
(mid) => mid !== result.messageId,
|
|
||||||
);
|
|
||||||
} else {
|
} else {
|
||||||
retryFailures++;
|
retryFailures++;
|
||||||
}
|
}
|
||||||
@@ -488,20 +430,14 @@ export const messagesJob: Job = {
|
|||||||
|
|
||||||
if (retrySuccesses > 0) {
|
if (retrySuccesses > 0) {
|
||||||
progress.lastSuccessTime = Date.now();
|
progress.lastSuccessTime = Date.now();
|
||||||
progress.failedRequests = Math.max(
|
progress.failedRequests = Math.max(0, progress.failedRequests - retrySuccesses);
|
||||||
0,
|
|
||||||
progress.failedRequests - retrySuccesses,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (retryFailures > 0) {
|
if (retryFailures > 0) {
|
||||||
progress.failedRequests += retryFailures;
|
progress.failedRequests += retryFailures;
|
||||||
}
|
}
|
||||||
|
|
||||||
progress.currentDelay = calculateAdaptiveDelay(
|
progress.currentDelay = calculateAdaptiveDelay(progress, batchResponseTime);
|
||||||
progress,
|
|
||||||
batchResponseTime,
|
|
||||||
);
|
|
||||||
|
|
||||||
verboseLog(
|
verboseLog(
|
||||||
`[Messages job] Processed retry batch: ${retrySuccesses} successes, ${retryFailures} failures`,
|
`[Messages job] Processed retry batch: ${retrySuccesses} successes, ${retryFailures} failures`,
|
||||||
@@ -511,9 +447,7 @@ export const messagesJob: Job = {
|
|||||||
|
|
||||||
while (!progress.done) {
|
while (!progress.done) {
|
||||||
if (checkCircuitBreaker(progress)) {
|
if (checkCircuitBreaker(progress)) {
|
||||||
console.warn(
|
console.warn("[Messages job] Circuit breaker is open, skipping processing");
|
||||||
"[Messages job] Circuit breaker is open, skipping processing",
|
|
||||||
);
|
|
||||||
await delay(RATE_LIMIT_CONFIG.maxDelay);
|
await delay(RATE_LIMIT_CONFIG.maxDelay);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -529,10 +463,7 @@ export const messagesJob: Job = {
|
|||||||
progress.consecutiveFailures = 0;
|
progress.consecutiveFailures = 0;
|
||||||
|
|
||||||
progress.currentDelay = calculateAdaptiveDelay(progress, responseTime);
|
progress.currentDelay = calculateAdaptiveDelay(progress, responseTime);
|
||||||
progress.currentBatchSize = calculateAdaptiveBatchSize(
|
progress.currentBatchSize = calculateAdaptiveBatchSize(progress, responseTime);
|
||||||
progress,
|
|
||||||
responseTime,
|
|
||||||
);
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error("[Messages job] list fetch failed:", e);
|
console.error("[Messages job] list fetch failed:", e);
|
||||||
progress.failedRequests++;
|
progress.failedRequests++;
|
||||||
@@ -591,25 +522,15 @@ export const messagesJob: Job = {
|
|||||||
`[Messages job] Streamed ${itemsToStream.length} items to vector worker (total: ${itemsStreamedToVector})`,
|
`[Messages job] Streamed ${itemsToStream.length} items to vector worker (total: ${itemsStreamedToVector})`,
|
||||||
);
|
);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.warn(
|
console.warn("[Messages job] Failed to stream items to vector worker:", error);
|
||||||
"[Messages job] Failed to stream items to vector worker:",
|
|
||||||
error,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (processedItems.length > 0) {
|
if (processedItems.length > 0) {
|
||||||
try {
|
try {
|
||||||
publishDynamicItemsUpdate(
|
publishDynamicItemsUpdate(await loadAllStoredItems(), "messages", processedItems.length);
|
||||||
await loadAllStoredItems(),
|
|
||||||
"messages",
|
|
||||||
processedItems.length,
|
|
||||||
);
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.warn(
|
console.warn("[Messages job] Failed to dispatch incremental search update:", error);
|
||||||
"[Messages job] Failed to dispatch incremental search update:",
|
|
||||||
error,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Loaded 100 of 306 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user