mirror of
https://github.com/BetterSEQTA/BetterSEQTA-Plus.git
synced 2026-12-06 19:56:45 +10:30
Merge branch 'main' into fix-external-video-loading
This commit is contained in:
259 files changed
+15048
-7311
No files matched your search
@@ -0,0 +1,3 @@
|
||||
# Optional OAuth client ID overrides (secrets live on accounts.betterseqta.org)
|
||||
# GOOGLE_OAUTH_CLIENT_ID=your-id.apps.googleusercontent.com
|
||||
# OUTLOOK_OAUTH_CLIENT_ID=your-azure-application-client-id
|
||||
@@ -33,14 +33,8 @@ outputs:
|
||||
runs:
|
||||
using: composite
|
||||
steps:
|
||||
- name: Use Node.js 20.x
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20.x
|
||||
|
||||
- name: Install dependencies
|
||||
shell: bash
|
||||
run: npm install --legacy-peer-deps
|
||||
- name: Setup Node and dependencies
|
||||
uses: ./.github/actions/setup-node-deps
|
||||
|
||||
- name: Read version
|
||||
id: version
|
||||
@@ -62,14 +56,4 @@ runs:
|
||||
env:
|
||||
UPDATE_CHANNEL: ${{ inputs.update_channel }}
|
||||
BUILD_LABEL: ${{ inputs.build_label }}
|
||||
run: |
|
||||
VERSION="${{ steps.version.outputs.version }}"
|
||||
if [ "$UPDATE_CHANNEL" = "nightly" ] && [ -n "$BUILD_LABEL" ]; then
|
||||
BASE="betterseqtaplus-nightly-${BUILD_LABEL}"
|
||||
else
|
||||
BASE="betterseqtaplus-${VERSION}"
|
||||
fi
|
||||
(cd dist/chrome && zip -r "../${BASE}-chrome.zip" .)
|
||||
(cd dist/firefox && zip -r "../${BASE}-firefox.zip" .)
|
||||
echo "chrome_zip=dist/${BASE}-chrome.zip" >> "$GITHUB_OUTPUT"
|
||||
echo "firefox_zip=dist/${BASE}-firefox.zip" >> "$GITHUB_OUTPUT"
|
||||
run: node scripts/package-extension-zips.mjs "${{ steps.version.outputs.version }}"
|
||||
@@ -0,0 +1,11 @@
|
||||
name: Run lint
|
||||
description: Run ESLint on src.
|
||||
|
||||
runs:
|
||||
using: composite
|
||||
steps:
|
||||
- name: Lint
|
||||
shell: bash
|
||||
run: npm run lint
|
||||
env:
|
||||
ESLINT_USE_FLAT_CONFIG: "false"
|
||||
@@ -0,0 +1,9 @@
|
||||
name: Run smoke tests
|
||||
description: Verify built extension dist output.
|
||||
|
||||
runs:
|
||||
using: composite
|
||||
steps:
|
||||
- name: Smoke tests
|
||||
shell: bash
|
||||
run: npm run test:smoke
|
||||
@@ -0,0 +1,9 @@
|
||||
name: Run unit tests
|
||||
description: Run Jest unit tests.
|
||||
|
||||
runs:
|
||||
using: composite
|
||||
steps:
|
||||
- name: Unit tests
|
||||
shell: bash
|
||||
run: npm run test:unit
|
||||
@@ -0,0 +1,14 @@
|
||||
name: Setup Node and dependencies
|
||||
description: Install Node.js 22.x and npm dependencies.
|
||||
|
||||
runs:
|
||||
using: composite
|
||||
steps:
|
||||
- name: Use Node.js 22.x
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 22.x
|
||||
|
||||
- name: Install dependencies
|
||||
shell: bash
|
||||
run: npm install --legacy-peer-deps
|
||||
@@ -1,36 +0,0 @@
|
||||
name: NodeJS Build
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: ["main"]
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
strategy:
|
||||
matrix:
|
||||
node-version: [20.x]
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Use Node.js ${{ matrix.node-version }}
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: ${{ matrix.node-version }}
|
||||
|
||||
- name: Build
|
||||
run: |
|
||||
npm install --legacy-peer-deps
|
||||
npm run build
|
||||
|
||||
- name: Zip dist folder
|
||||
run: |
|
||||
zip -r dist.zip dist
|
||||
|
||||
- name: Upload artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: dist-zip
|
||||
path: dist.zip
|
||||
@@ -1,11 +1,18 @@
|
||||
# Nightly release workflow — updates the same "nightly" release with fresh builds from main.
|
||||
# Runs only on BetterSEQTA/BetterSEQTA-Plus. Uses the default GITHUB_TOKEN.
|
||||
#
|
||||
# Scheduled at midnight Australia/Adelaide (ACST/ACDT). GitHub cron is UTC-only, so we
|
||||
# trigger at 13:30 and 14:30 UTC and only proceed when Adelaide local time is 00:00.
|
||||
# Builds on windows-latest (matches local dev; Linux nightly builds were failing on Vite/Svelte).
|
||||
|
||||
name: Nightly Release
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: "0 3 * * *"
|
||||
# 13:30 UTC = 00:00 Adelaide during daylight saving (ACDT, UTC+10:30)
|
||||
- cron: "30 13 * * *"
|
||||
# 14:30 UTC = 00:00 Adelaide during standard time (ACST, UTC+9:30)
|
||||
- cron: "30 14 * * *"
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
@@ -13,19 +20,41 @@ permissions:
|
||||
|
||||
env:
|
||||
NIGHTLY_TAG: nightly
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
|
||||
jobs:
|
||||
nightly:
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: windows-latest
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
steps:
|
||||
- name: Check Adelaide midnight
|
||||
id: time_check
|
||||
run: |
|
||||
if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
|
||||
echo "proceed=true" >> "$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
fi
|
||||
TZ=Australia/Adelaide
|
||||
if [ "$(date +%H%M)" = "0000" ]; then
|
||||
echo "proceed=true" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "proceed=false" >> "$GITHUB_OUTPUT"
|
||||
echo "Skipping: not midnight Australia/Adelaide ($(date +%Y-%m-%d %H:%M %Z))"
|
||||
fi
|
||||
|
||||
- uses: actions/checkout@v4
|
||||
if: steps.time_check.outputs.proceed == 'true'
|
||||
|
||||
- name: Set build date
|
||||
id: build_date
|
||||
run: echo "date=$(date -u +'%Y-%m-%d')" >> "$GITHUB_OUTPUT"
|
||||
if: steps.time_check.outputs.proceed == 'true'
|
||||
run: echo "date=$(TZ=Australia/Adelaide date +'%Y-%m-%d')" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Build extension
|
||||
id: build
|
||||
if: steps.time_check.outputs.proceed == 'true'
|
||||
uses: ./.github/actions/build-extension
|
||||
with:
|
||||
gh_release_update_check: "true"
|
||||
@@ -34,6 +63,7 @@ jobs:
|
||||
release_repo: ${{ github.repository }}
|
||||
|
||||
- name: Ensure nightly release exists
|
||||
if: steps.time_check.outputs.proceed == 'true'
|
||||
run: |
|
||||
TITLE="Nightly (${{ steps.build_date.outputs.date }})"
|
||||
if ! gh release view "${{ env.NIGHTLY_TAG }}" 2>/dev/null; then
|
||||
@@ -46,6 +76,7 @@ jobs:
|
||||
fi
|
||||
|
||||
- name: Upload nightly assets
|
||||
if: steps.time_check.outputs.proceed == 'true'
|
||||
run: |
|
||||
gh release upload "${{ env.NIGHTLY_TAG }}" \
|
||||
--clobber \
|
||||
|
||||
+45
-17
@@ -1,35 +1,63 @@
|
||||
name: PR CI
|
||||
name: CI
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches: ["main"]
|
||||
push:
|
||||
branches: ["main"]
|
||||
|
||||
jobs:
|
||||
ci:
|
||||
runs-on: ubuntu-latest
|
||||
lint:
|
||||
# windows-latest: Vite/Svelte build fails on Linux CI for layerchart vendor .svelte (see nightly.yml).
|
||||
runs-on: windows-latest
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Use Node.js 20.x
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20.x
|
||||
- name: Setup Node and dependencies
|
||||
uses: ./.github/actions/setup-node-deps
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm install --legacy-peer-deps
|
||||
- name: Run lint
|
||||
uses: ./.github/actions/run-lint
|
||||
|
||||
- name: Lint
|
||||
run: npm run lint
|
||||
env:
|
||||
ESLINT_USE_FLAT_CONFIG: "false"
|
||||
unit-tests:
|
||||
runs-on: windows-latest
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Unit tests
|
||||
run: npm test
|
||||
- name: Setup Node and dependencies
|
||||
uses: ./.github/actions/setup-node-deps
|
||||
|
||||
- name: Run unit tests
|
||||
uses: ./.github/actions/run-unit-tests
|
||||
|
||||
build-and-smoke:
|
||||
needs: [lint, unit-tests]
|
||||
runs-on: windows-latest
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Build extension
|
||||
id: build
|
||||
uses: ./.github/actions/build-extension
|
||||
with:
|
||||
gh_release_update_check: "false"
|
||||
|
||||
- name: Smoke tests
|
||||
run: npm run test:smoke
|
||||
- name: Upload extension zips
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: extension-zips
|
||||
path: |
|
||||
${{ steps.build.outputs.chrome_zip }}
|
||||
${{ steps.build.outputs.firefox_zip }}
|
||||
|
||||
- name: Run smoke tests
|
||||
uses: ./.github/actions/run-smoke-tests
|
||||
@@ -16,6 +16,9 @@ on:
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
|
||||
jobs:
|
||||
release:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
@@ -9,6 +9,9 @@ bun.lock
|
||||
# PDF.js extension assets (copied by postinstall from pdfjs-dist)
|
||||
src/public/resources/pdfjs/pdf.worker.min.mjs
|
||||
src/public/resources/pdfjs/pdf.legacy.min.mjs
|
||||
# ONNX Runtime WASM assets (copied by postinstall from @huggingface/transformers)
|
||||
src/public/resources/ort/ort-wasm-simd-threaded.jsep.mjs
|
||||
src/public/resources/ort/ort-wasm-simd-threaded.jsep.wasm
|
||||
|
||||
# Build
|
||||
extension.zip
|
||||
|
||||
@@ -3,11 +3,11 @@
|
||||
</a>
|
||||
|
||||
<p align="center">
|
||||
A beautiful 🤩 Chrome Extension that adds additional features and gives an overall better experience for <a href="https://educationhorizons.com/solutions/seqta/">SEQTA Learn.</a> <strong>Currently looking for contributors</strong> 🔥
|
||||
A beautiful 🤩 browser extension that transforms <a href="https://www.tes.com/en-au/for-schools/seqta">SEQTA</a> with modern themes, powerful customization, productivity tools, and an improved user experience. Contributions are always welcome!
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a target="_blank" href="https://chrome.google.com/webstore/detail/betterseqta%20/afdgaoaclhkhemfkkkonemoapeinchel"><img src="https://user-images.githubusercontent.com/95666457/149519713-159d7ef7-2c21-4034-a616-f037ff46d9a4.png" alt="ChromeDownload" width="250"></a>
|
||||
<a target="_blank" href="https://chromewebstore.google.com/detail/betterseqta+/afdgaoaclhkhemfkkkonemoapeinchel"><img src="https://user-images.githubusercontent.com/95666457/149519713-159d7ef7-2c21-4034-a616-f037ff46d9a4.png" alt="ChromeDownload" width="250"></a>
|
||||
<a target="_blank" href="https://discord.gg/YzmbnCDkat"><img src="https://github.com/BetterSEQTA/BetterSEQTA-Plus/assets/108050083/23055730-b16e-44c0-9bef-221d8545af92" width="240" style="border-radius:10%;" /></a>
|
||||
</p>
|
||||
|
||||
@@ -16,15 +16,16 @@
|
||||
<img src="https://img.shields.io/chrome-web-store/rating/afdgaoaclhkhemfkkkonemoapeinchel" />
|
||||
</div>
|
||||
|
||||
## 📚 Documentation
|
||||
All documentation has been moved to the [official docs site](https://docs.betterseqta.org):
|
||||
## Documentation
|
||||
|
||||
Everything you need to get started with BetterSEQTA+ can be found in the [official documentation](https://docs.betterseqta.org).
|
||||
|
||||
Includes:
|
||||
- Getting started
|
||||
- Development setup
|
||||
- Getting Started
|
||||
- Installation & Development
|
||||
- Architecture
|
||||
- Plugin system
|
||||
- Theme creation
|
||||
- Plugin System
|
||||
- Theme Creation
|
||||
|
||||
## Features
|
||||
|
||||
@@ -72,8 +73,7 @@ npm run dev
|
||||
Then load `dist` in `chrome://extensions` (Developer Mode → Load unpacked).
|
||||
|
||||
|
||||
Full setup guide:
|
||||
[https://betterseqta.github.io/BetterSEQTA-Docs/install/#for-developers-development-environment](https://betterseqta.github.io/BetterSEQTA-Docs/install/#for-developers-development-environment)
|
||||
Full development setup guide can be found [here](https://docs.betterseqta.org/install/#for-developers-development-environment).
|
||||
|
||||
## Contributors
|
||||
|
||||
@@ -85,10 +85,9 @@ Want to contribute? [Click Here!](https://docs.betterseqta.org/contributing/)
|
||||
|
||||
## Credits
|
||||
|
||||
This extension was initially developed by [Nulkem](https://github.com/Nulkem/betterseqta), was ported to manifest V3 by [MEGA-Dawg68](https://github.com/MEGA-Dawg68) and is currently under active development from lead developers [SethBurkart123](https://github.com/SethBurkart123) and [Crazypersonalph](https://github.com/Crazypersonalph) with help from other volunteers.
|
||||
Originally developed by [Nulkem](https://github.com/Nulkem/betterseqta)
|
||||
Ported to Manifest V3 by [MEGA-Dawg68](https://github.com/MEGA-Dawg68)
|
||||
Maintained by [SethBurkart123](https://github.com/SethBurkart123), [Crazypersonalph](https://github.com/Crazypersonalph) & the rest of the BetterSEQTA team!
|
||||
Originally developed by [Nulkem](https://github.com/Nulkem/betterseqta)
|
||||
Ported to Manifest V3 by [MEGA-Dawg68](https://github.com/MEGA-Dawg68)
|
||||
Maintained by [SethBurkart123](https://github.com/SethBurkart123), [Crazypersonalph](https://github.com/Crazypersonalph) & the rest of the BetterSEQTA team!
|
||||
|
||||
## Star History
|
||||
|
||||
|
||||
+6
-6
@@ -2,15 +2,15 @@
|
||||
|
||||
## Supported Versions
|
||||
|
||||
Below here is the supported versions of BetterSEQTA+. Anything older than this is not supported and contains bugs.
|
||||
The following versions of BetterSEQTA+ are currently supported.
|
||||
|
||||
| Version | Supported |
|
||||
| ------- | --------- |
|
||||
| 3.4.3 | ✅ |
|
||||
| < 3.4.3 | :x: |
|
||||
|
||||
`*` May not work on other devices.
|
||||
| 3.4.3 or later | ✅ |
|
||||
| Earlier than 3.4.3 | ❌ |
|
||||
|
||||
## Reporting a Vulnerability
|
||||
|
||||
If you find vulnerabilities, REPORT IT IMMEDIATELY. open the [advisories tab](https://github.com/BetterSEQTA/BetterSEQTA-Plus/security/advisories) on the left and click the green "report a vulnerability" button or use [this quick-link](https://github.com/BetterSEQTA/BetterSEQTA-Plus/security/advisories/new) to create a new report
|
||||
If you discover a security vulnerability, please report it responsibly through GitHub Security Advisories:
|
||||
|
||||
https://github.com/BetterSEQTA/BetterSEQTA-Plus/security/advisories/new
|
||||
@@ -8,11 +8,17 @@ export default {
|
||||
],
|
||||
transform: {
|
||||
'^.+\\.ts$': 'ts-jest',
|
||||
'^.+\\.js$': ['ts-jest', { tsconfig: { allowJs: true } }],
|
||||
},
|
||||
transformIgnorePatterns: [
|
||||
'/node_modules/(?!(color|color-string|color-convert|color-name)/)',
|
||||
],
|
||||
moduleNameMapper: {
|
||||
'^@/(.*)$': '<rootDir>/src/$1',
|
||||
'^color$': '<rootDir>/src/test/mocks/color.ts',
|
||||
'^webextension-polyfill$': '<rootDir>/src/test/mocks/webextension-polyfill.ts',
|
||||
},
|
||||
setupFilesAfterEnv: ['<rootDir>/src/test/jest.setup.ts'],
|
||||
moduleFileExtensions: ['ts', 'js', 'json'],
|
||||
collectCoverageFrom: [
|
||||
'src/**/*.ts',
|
||||
|
||||
+6
-44
@@ -1,58 +1,20 @@
|
||||
// ref: https://stackoverflow.com/a/76920975
|
||||
import type { Plugin } from "vite";
|
||||
|
||||
/**
|
||||
* Creates a Vite plugin designed to gracefully handle the conclusion of the build process.
|
||||
* This plugin utilizes the `buildEnd` and `closeBundle` hooks provided by Vite.
|
||||
* It checks for errors at the end of the build:
|
||||
* - If an error occurred during the build (`buildEnd` hook receives an error), it logs the error
|
||||
* and explicitly exits the Node.js process with a status code of 1 (indicating failure).
|
||||
* - If the build completes without errors and the bundle is successfully generated
|
||||
* (`closeBundle` hook is called), it logs a success message and exits the process
|
||||
* with a status code of 0 (indicating success).
|
||||
* This explicit process exiting can be useful in CI/CD environments or scripts that
|
||||
* rely on the process status code to determine the build outcome.
|
||||
* The core logic for using these hooks to exit the process is inspired by
|
||||
* a solution found on StackOverflow (https://stackoverflow.com/a/76920975).
|
||||
*
|
||||
* @returns {Plugin} A Vite plugin object configured with `name`, `buildEnd`, and `closeBundle` hooks.
|
||||
*/
|
||||
/** Exit with code 1 on build failure; do not exit on success (multi-target builds). */
|
||||
export default function ClosePlugin(): Plugin {
|
||||
return {
|
||||
/**
|
||||
* The unique name of this Vite plugin. This name is used by Vite for identification
|
||||
* purposes and will appear in warnings, errors, and logs related to this plugin.
|
||||
* @type {string}
|
||||
*/
|
||||
name: "ClosePlugin", // required, will show up in warnings and errors
|
||||
|
||||
/**
|
||||
* A Vite hook that is called when the build process has finished, regardless of
|
||||
* whether it was successful or encountered an error.
|
||||
*
|
||||
* @param {Error} [error] An optional error object. If the build failed, this parameter
|
||||
* will contain the error that occurred. If the build was successful,
|
||||
* this parameter will be undefined or null.
|
||||
*/
|
||||
name: "ClosePlugin",
|
||||
buildEnd(error) {
|
||||
if (error) {
|
||||
console.error("Error bundling");
|
||||
console.error(error);
|
||||
process.exit(1); // Exit with status 1 indicating an error
|
||||
console.error("Error bundling", error);
|
||||
process.exit(1);
|
||||
} else {
|
||||
console.log("Build ended"); // Log successful completion of the build phase
|
||||
console.log("Build ended");
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* A Vite hook that is called after the `buildEnd` hook, but only if the build
|
||||
* was successful (i.e., no errors were passed to `buildEnd`) and all output
|
||||
* files have been generated and written to disk. This signifies the successful
|
||||
* completion of the entire bundling process.
|
||||
*/
|
||||
closeBundle() {
|
||||
console.log("Bundle closed"); // Log successful closure of the bundle
|
||||
process.exit(0); // Exit with status 0 indicating a successful build
|
||||
console.log("Bundle closed");
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import type { Plugin } from "vite";
|
||||
|
||||
/** Relative chunk/CSS URLs via chrome.runtime.getURL for content-script dynamic imports. */
|
||||
export function extensionChunkUrls(): Plugin {
|
||||
return {
|
||||
name: "extension-chunk-urls",
|
||||
config() {
|
||||
return {
|
||||
base: "./",
|
||||
experimental: {
|
||||
renderBuiltUrl(filename, { hostType, type }) {
|
||||
const path = filename.replace(/^\//, "");
|
||||
if (type === "chunk" && hostType === "js") {
|
||||
return { runtime: `chrome.runtime.getURL(${JSON.stringify(path)})` };
|
||||
}
|
||||
// JS-triggered CSS preloads only — extension HTML pages need static hrefs.
|
||||
if (type === "asset" && hostType === "js" && path.endsWith(".css")) {
|
||||
return { runtime: `chrome.runtime.getURL(${JSON.stringify(path)})` };
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
+20
-58
@@ -1,70 +1,32 @@
|
||||
// vite-plugin-inline-worker-dev.ts
|
||||
// vite-plugin-inline-worker-dev.ts
|
||||
import { Plugin } from "vite";
|
||||
import fs from "fs/promises";
|
||||
import { build } from "esbuild";
|
||||
|
||||
/**
|
||||
* Creates a Vite plugin designed for bundling and inlining web worker scripts during development.
|
||||
* This plugin specifically targets module imports that include a `?inlineWorker` query parameter.
|
||||
* When such an import is encountered, the plugin bundles the worker script using `esbuild`
|
||||
* and then generates JavaScript code that inlines this bundled worker as a Blob,
|
||||
* creating the worker instance via `URL.createObjectURL()`.
|
||||
* The name "vite:inline-worker-dev" suggests it's primarily intended for development builds.
|
||||
*
|
||||
* @returns {Plugin} A Vite plugin object with `name` and `load` properties.
|
||||
*/
|
||||
/** Bundle worker entry points imported with `?inlineWorker` as Blob-backed Workers in dev. */
|
||||
export default function InlineWorkerDevPlugin(): Plugin {
|
||||
return {
|
||||
/**
|
||||
* The unique name of this Vite plugin.
|
||||
* @type {string}
|
||||
*/
|
||||
name: "vite:inline-worker-dev",
|
||||
/**
|
||||
* The Vite hook responsible for loading and transforming modules.
|
||||
* This function intercepts modules imported with `?inlineWorker`.
|
||||
* For such modules, it bundles the worker script and returns JavaScript code
|
||||
* that, when executed, will create an instance of this worker from an inlined Blob.
|
||||
*
|
||||
* @async
|
||||
* @param {string} id The path or ID of the module Vite is attempting to load,
|
||||
* potentially including query parameters (e.g., "/path/to/worker.ts?inlineWorker").
|
||||
* @returns {Promise<string | null>} A promise that resolves to:
|
||||
* - `null` if the module ID does not include `?inlineWorker`.
|
||||
* - A string of JavaScript code if the module is an inline worker.
|
||||
* This code will define a default export function (e.g., `InlineWorker`)
|
||||
* that, when called, creates and returns a new `Worker` instance
|
||||
* from the bundled and inlined worker script.
|
||||
*/
|
||||
async load(id) {
|
||||
if (id.includes("?inlineWorker")) {
|
||||
const [cleanPath] = id.split("?");
|
||||
// Note: Original code had `await fs.readFile(cleanPath, "utf-8");` but `code` wasn't used.
|
||||
// `esbuild` directly takes `cleanPath` as an entry point.
|
||||
const result = await build({
|
||||
entryPoints: [cleanPath], // esbuild uses the file path directly
|
||||
bundle: true,
|
||||
write: false, // We want the output in memory, not written to disk
|
||||
platform: "browser", // Target environment for the worker code
|
||||
format: "iife", // Immediately Invoked Function Expression, suitable for workers
|
||||
target: "esnext", // Transpile to modern JavaScript
|
||||
});
|
||||
if (!id.includes("?inlineWorker")) return null;
|
||||
|
||||
const workerCode = result.outputFiles[0].text;
|
||||
const [cleanPath] = id.split("?");
|
||||
const result = await build({
|
||||
entryPoints: [cleanPath],
|
||||
bundle: true,
|
||||
write: false,
|
||||
platform: "browser",
|
||||
format: "iife",
|
||||
target: "esnext",
|
||||
external: ["webextension-polyfill"],
|
||||
});
|
||||
|
||||
// Construct JavaScript code that will create the worker from a Blob.
|
||||
// This code is what gets returned to Vite and replaces the original import.
|
||||
const workerBlobCode = `
|
||||
const code = ${JSON.stringify(workerCode)};
|
||||
export default function InlineWorker() {
|
||||
const blob = new Blob([code], { type: 'application/javascript' });
|
||||
return new Worker(URL.createObjectURL(blob), { type: 'module' });
|
||||
}
|
||||
`;
|
||||
return workerBlobCode;
|
||||
}
|
||||
return null; // Let Vite handle other modules normally
|
||||
const workerCode = result.outputFiles[0].text;
|
||||
return `
|
||||
const code = ${JSON.stringify(workerCode)};
|
||||
export default function InlineWorker() {
|
||||
const blob = new Blob([code], { type: 'application/javascript' });
|
||||
return new Worker(URL.createObjectURL(blob), { type: 'module' });
|
||||
}
|
||||
`;
|
||||
},
|
||||
};
|
||||
}
|
||||
+2
-2
@@ -11,7 +11,7 @@
|
||||
* or `node lib/publish.js --b firefox`
|
||||
*/
|
||||
|
||||
const glob = require("glob");
|
||||
const { globSync } = require("glob");
|
||||
const semver = require("semver");
|
||||
const { execSync } = require("child_process");
|
||||
const path = require("path");
|
||||
@@ -98,7 +98,7 @@ function getLatestFiles(browser) {
|
||||
const pattern = `dist/betterseqtaplus@*-*${browser}.zip`;
|
||||
console.log("Glob pattern:", pattern);
|
||||
|
||||
const files = glob.sync(pattern);
|
||||
const files = globSync(pattern);
|
||||
console.log("Files found for browser", browser, ":", files);
|
||||
|
||||
if (files.length === 0) {
|
||||
|
||||
+35
-42
@@ -1,16 +1,17 @@
|
||||
{
|
||||
"name": "betterseqtaplus",
|
||||
"version": "3.7.2",
|
||||
"version": "3.7.3",
|
||||
"type": "module",
|
||||
"description": "Enhance SEQTA Learn's usability and aesthetics! A fork of BetterSEQTA to continue development and add heaps more features!",
|
||||
"browserslist": "> 0.5%, last 2 versions, not dead",
|
||||
"scripts": {
|
||||
"postinstall": "node scripts/copy-pdfjs-assets.mjs",
|
||||
"compile:layerchart": "node scripts/compile-layerchart-vendor.mjs",
|
||||
"postinstall": "node scripts/copy-pdfjs-assets.mjs && node scripts/copy-ort-wasm-assets.mjs && npm run compile:layerchart",
|
||||
"autoaudit": "npm audit && npm audit fix && npm run build",
|
||||
"dev": "cross-env MODE=chrome vite dev",
|
||||
"dev:firefox": "cross-env MODE=firefox vite build --watch",
|
||||
"compile": "npm i && npm run build",
|
||||
"build": "cross-env MODE=chrome vite build && cross-env MODE=firefox vite build",
|
||||
"build": "npm run compile:layerchart && cross-env MODE=chrome vite build && cross-env MODE=firefox vite build",
|
||||
"build:chrome": "cross-env MODE=chrome vite build",
|
||||
"build:firefox": "cross-env MODE=firefox vite build",
|
||||
"build:safari": "cross-env MODE=safari vite build",
|
||||
@@ -18,19 +19,14 @@
|
||||
"convert:safari": "xcrun safari-web-extension-converter dist/safari --project-location . --app-name $npm_package_name-safari",
|
||||
"dependency-graph": "depcruise src --include-only \"^src\" --output-type dot | dot -T svg > dependency-graph.svg",
|
||||
"lint": "cross-env ESLINT_USE_FLAT_CONFIG=false eslint \"src/**/*.{js,ts}\"",
|
||||
"test": "jest",
|
||||
"test": "npm run test:unit",
|
||||
"test:unit": "jest",
|
||||
"test:smoke": "node scripts/smoke-test.mjs",
|
||||
"test:ci": "npm run test:unit && npm run build && npm run test:smoke",
|
||||
"release": "gh release create $npm_package_version --repo BetterSEQTA/BetterSEQTA-Plus ./dist/*.zip --generate-notes",
|
||||
"publish": "bun lib/publish.js --b",
|
||||
"zip": "bedframe zip"
|
||||
},
|
||||
"targets": {
|
||||
"prod": {
|
||||
"sourceMap": {
|
||||
"inline": false
|
||||
}
|
||||
}
|
||||
},
|
||||
"keywords": [],
|
||||
"author": {
|
||||
"name": "SethBurkart123",
|
||||
@@ -39,34 +35,44 @@
|
||||
},
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"@babel/plugin-transform-runtime": "^7.26.9",
|
||||
"@babel/runtime": "^7.26.9",
|
||||
"@bedframe/cli": "^0.1.2",
|
||||
"@crxjs/vite-plugin": "^2.6.1",
|
||||
"@sveltejs/vite-plugin-svelte": "^5.0.3",
|
||||
"@tailwindcss/forms": "^0.5.10",
|
||||
"@tsconfig/svelte": "^5.0.4",
|
||||
"@types/chrome": "^0.1.4",
|
||||
"@types/color": "^4.2.0",
|
||||
"@types/d3-scale": "^4.0.9",
|
||||
"@types/d3-shape": "^3.1.8",
|
||||
"@types/jest": "^30.0.0",
|
||||
"@types/mime-types": "^3.0.1",
|
||||
"@types/react": "^19.0.10",
|
||||
"@types/react-dom": "^19.0.4",
|
||||
"@types/node": "^24.3.0",
|
||||
"@types/qrcode": "^1.5.6",
|
||||
"@types/react": "^17.0.0",
|
||||
"@types/react-dom": "^17.0.0",
|
||||
"@types/sortablejs": "^1.15.8",
|
||||
"@types/webextension-polyfill": "^0.12.3",
|
||||
"@typescript-eslint/eslint-plugin": "^8.60.1",
|
||||
"@typescript-eslint/parser": "^8.60.1",
|
||||
"autoprefixer": "^10.4.21",
|
||||
"cross-env": "^10.0.0",
|
||||
"dependency-cruiser": "^17.0.1",
|
||||
"esbuild": "^0.25.3",
|
||||
"eslint": "^9.33.0",
|
||||
"eslint-plugin-import": "^2.31.0",
|
||||
"glob": "^11.0.1",
|
||||
"glob": "^13.0.6",
|
||||
"jest": "^30.4.2",
|
||||
"jest-environment-jsdom": "^30.4.1",
|
||||
"mime-types": "^3.0.1",
|
||||
"postcss": "^8.5.3",
|
||||
"prettier": "^3.5.3",
|
||||
"process": "^0.11.10",
|
||||
"publish-browser-extension": "^4.0.4",
|
||||
"sass": "^1.85.1",
|
||||
"sass-loader": "^16.0.5",
|
||||
"semver": "^7.7.1",
|
||||
"tailwindcss": "3",
|
||||
"ts-jest": "^29.4.11",
|
||||
"url": "^0.11.4"
|
||||
"typescript": "^5.8.2",
|
||||
"vite": "^6.2.1"
|
||||
},
|
||||
"dependencies": {
|
||||
"@bedframe/core": "^0.1.0",
|
||||
@@ -77,22 +83,10 @@
|
||||
"@codemirror/search": "^6.5.10",
|
||||
"@codemirror/state": "^6.5.2",
|
||||
"@codemirror/view": "^6.36.4",
|
||||
"@sveltejs/vite-plugin-svelte": "^5.0.3",
|
||||
"@tailwindcss/forms": "^0.5.10",
|
||||
"@tsconfig/svelte": "^5.0.4",
|
||||
"@types/chrome": "^0.1.4",
|
||||
"@types/color": "^4.2.0",
|
||||
"@types/lodash": "^4.17.16",
|
||||
"@types/node": "^24.3.0",
|
||||
"@types/qrcode": "^1.5.6",
|
||||
"@types/sortablejs": "^1.15.8",
|
||||
"@types/uuid": "^10.0.0",
|
||||
"@types/webextension-polyfill": "^0.12.3",
|
||||
"@huggingface/transformers": "^3.8.1",
|
||||
"@uiw/codemirror-extensions-color": "^4.23.10",
|
||||
"@uiw/codemirror-theme-github": "^4.23.10",
|
||||
"autoprefixer": "^10.4.21",
|
||||
"canvas-confetti": "^1.9.3",
|
||||
"codemirror": "^6.0.1",
|
||||
"color": "^5.0.0",
|
||||
"d3-scale": "^4.0.2",
|
||||
"d3-shape": "^3.2.0",
|
||||
@@ -100,29 +94,28 @@
|
||||
"embeddia": "^1.3.0",
|
||||
"embla-carousel-autoplay": "^8.5.2",
|
||||
"embla-carousel-svelte": "^8.5.2",
|
||||
"esbuild": "^0.25.3",
|
||||
"events": "^3.3.0",
|
||||
"flexsearch": "^0.8.147",
|
||||
"fuse.js": "^7.1.0",
|
||||
"idb": "^8.0.2",
|
||||
"layerchart": "2.0.0-next.27",
|
||||
"localforage": "^1.10.0",
|
||||
"lodash": "^4.17.21",
|
||||
"mathjs": "^14.4.0",
|
||||
"million": "^3.1.11",
|
||||
"motion": "^12.4.12",
|
||||
"pdfjs-dist": "^5.4.530",
|
||||
"postcss": "^8.5.3",
|
||||
"qrcode": "^1.5.4",
|
||||
"react": "17",
|
||||
"react-best-gradient-color-picker": "3.0.11",
|
||||
"react-dom": "17",
|
||||
"rss-parser": "^3.13.0",
|
||||
"semver": "^7.7.1",
|
||||
"sortablejs": "^1.15.6",
|
||||
"svelte": "^5.46.4",
|
||||
"typescript": "^5.8.2",
|
||||
"uuid": "^11.1.0",
|
||||
"vite": "^6.2.1",
|
||||
"webextension-polyfill": "^0.12.0"
|
||||
},
|
||||
"overrides": {
|
||||
"glob": "^13.0.6"
|
||||
},
|
||||
"pnpm": {
|
||||
"overrides": {
|
||||
"glob": "^13.0.6"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
/**
|
||||
* Pre-compile layerchart `.svelte` sources to `.js` so Rollup/Vite CI builds succeed.
|
||||
*/
|
||||
import { compile } from "svelte/compiler";
|
||||
import { readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
|
||||
import { dirname, join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const root = join(dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const layerchartRoot = join(root, "node_modules", "layerchart");
|
||||
const layerchartDist = join(layerchartRoot, "dist");
|
||||
const stampPath = join(layerchartDist, ".bsplus-compiled");
|
||||
const COMPILE_ALGO_VERSION = "2";
|
||||
const importSuffixPattern = /\.svelte(?=['"])/g;
|
||||
|
||||
const exists = (path) => {
|
||||
try {
|
||||
statSync(path);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
if (!exists(layerchartDist)) {
|
||||
console.log("compile-layerchart-vendor: layerchart not installed, skipping");
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
const layerchartVersion = JSON.parse(
|
||||
readFileSync(join(layerchartRoot, "package.json"), "utf8"),
|
||||
).version;
|
||||
const stampContent = `${layerchartVersion}\n${COMPILE_ALGO_VERSION}`;
|
||||
|
||||
if (exists(stampPath) && readFileSync(stampPath, "utf8").trim() === stampContent) {
|
||||
console.log(`compile-layerchart-vendor: layerchart@${layerchartVersion} already compiled, skipping`);
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
const walkFiles = (dir, files = []) => {
|
||||
for (const name of readdirSync(dir)) {
|
||||
if (name === "node_modules") continue;
|
||||
const path = join(dir, name);
|
||||
if (statSync(path).isDirectory()) walkFiles(path, files);
|
||||
else files.push(path);
|
||||
}
|
||||
return files;
|
||||
};
|
||||
|
||||
const patchSvelteImports = (content) => content.replace(importSuffixPattern, ".js");
|
||||
const stripRollupBreakingSyntax = (code) =>
|
||||
code
|
||||
.replace(/(\w+)\?(?=\s*[,)\]])/g, "$1")
|
||||
.replace(/(\w+)\?(?=\s*:)/g, "$1");
|
||||
|
||||
const svelteFiles = walkFiles(layerchartDist).filter((f) => f.endsWith(".svelte"));
|
||||
|
||||
for (const sveltePath of svelteFiles) {
|
||||
const source = readFileSync(sveltePath, "utf8");
|
||||
if (!source.includes("<script")) continue;
|
||||
const compiled = compile(source, {
|
||||
filename: sveltePath,
|
||||
generate: "client",
|
||||
css: "injected",
|
||||
});
|
||||
writeFileSync(
|
||||
sveltePath.replace(/\.svelte$/, ".js"),
|
||||
stripRollupBreakingSyntax(patchSvelteImports(compiled.js.code)),
|
||||
);
|
||||
}
|
||||
|
||||
for (const filePath of walkFiles(layerchartDist).filter((f) => /\.(js|svelte|ts|mjs)$/.test(f))) {
|
||||
const content = readFileSync(filePath, "utf8");
|
||||
if (!content.includes(".svelte")) continue;
|
||||
const patched = patchSvelteImports(content);
|
||||
if (patched !== content) writeFileSync(filePath, patched);
|
||||
}
|
||||
|
||||
writeFileSync(stampPath, stampContent);
|
||||
console.log(`compile-layerchart-vendor: compiled ${svelteFiles.length} Svelte files`);
|
||||
@@ -0,0 +1,28 @@
|
||||
import { copyFileSync, existsSync, mkdirSync } from "node:fs";
|
||||
import { createRequire } from "node:module";
|
||||
import { dirname, join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const root = join(dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const require = createRequire(import.meta.url);
|
||||
|
||||
const transformersDist = dirname(require.resolve("@huggingface/transformers"));
|
||||
const outDir = join(root, "src", "public", "resources", "ort");
|
||||
|
||||
mkdirSync(outDir, { recursive: true });
|
||||
|
||||
const ortFiles = [
|
||||
"ort-wasm-simd-threaded.jsep.mjs",
|
||||
"ort-wasm-simd-threaded.jsep.wasm",
|
||||
];
|
||||
|
||||
for (const file of ortFiles) {
|
||||
const src = join(transformersDist, file);
|
||||
if (!existsSync(src)) {
|
||||
throw new Error(
|
||||
`Missing ONNX Runtime WASM asset: ${src}\n` +
|
||||
"Ensure @huggingface/transformers is installed (direct dependency).",
|
||||
);
|
||||
}
|
||||
copyFileSync(src, join(outDir, file));
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
/**
|
||||
* Package Chrome/Firefox build folders into Windows-friendly zip files.
|
||||
*/
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { appendFileSync, existsSync, mkdirSync, readFileSync, unlinkSync } from "node:fs";
|
||||
import { dirname, join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const root = join(dirname(fileURLToPath(import.meta.url)), "..");
|
||||
|
||||
function zipDirectory(sourceRel, outRel) {
|
||||
const sourceDir = join(root, sourceRel);
|
||||
const outZip = join(root, outRel);
|
||||
if (!existsSync(sourceDir)) throw new Error(`Missing build output: ${sourceRel}`);
|
||||
|
||||
mkdirSync(dirname(outZip), { recursive: true });
|
||||
if (existsSync(outZip)) unlinkSync(outZip);
|
||||
|
||||
if (process.platform === "win32") {
|
||||
const esc = (s) => s.replace(/'/g, "''");
|
||||
execFileSync(
|
||||
"powershell",
|
||||
[
|
||||
"-NoProfile",
|
||||
"-Command",
|
||||
[
|
||||
"Add-Type -AssemblyName System.IO.Compression.FileSystem",
|
||||
`[IO.Compression.ZipFile]::CreateFromDirectory('${esc(sourceDir)}', '${esc(outZip)}')`,
|
||||
].join("; "),
|
||||
],
|
||||
{ stdio: "inherit" },
|
||||
);
|
||||
} else {
|
||||
execFileSync("zip", ["-r", "-q", outZip, "."], { cwd: sourceDir, stdio: "inherit" });
|
||||
}
|
||||
}
|
||||
|
||||
const pkg = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
|
||||
const version = process.argv[2] || pkg.version;
|
||||
const updateChannel = process.env.UPDATE_CHANNEL || "stable";
|
||||
const buildLabel = process.env.BUILD_LABEL || "";
|
||||
const base =
|
||||
updateChannel === "nightly" && buildLabel
|
||||
? `betterseqtaplus-nightly-${buildLabel}`
|
||||
: `betterseqtaplus-${version}`;
|
||||
|
||||
const chromeZip = `dist/${base}-chrome.zip`;
|
||||
const firefoxZip = `dist/${base}-firefox.zip`;
|
||||
|
||||
zipDirectory("dist/chrome", chromeZip);
|
||||
zipDirectory("dist/firefox", firefoxZip);
|
||||
console.log(`Packaged ${chromeZip}\nPackaged ${firefoxZip}`);
|
||||
|
||||
if (process.env.GITHUB_OUTPUT) {
|
||||
appendFileSync(process.env.GITHUB_OUTPUT, `chrome_zip=${chromeZip}\nfirefox_zip=${firefoxZip}\n`);
|
||||
}
|
||||
+15
-9
@@ -6,10 +6,12 @@ import documentLoadCSS from "@/css/documentload.scss?inline";
|
||||
import icon48 from "@/resources/icons/icon-48.png?base64";
|
||||
import browser from "webextension-polyfill";
|
||||
|
||||
import * as plugins from "@/plugins";
|
||||
import { main } from "@/seqta/main";
|
||||
import { delay } from "./seqta/utils/delay";
|
||||
import { initializeHideSensitiveToggle } from "@/seqta/utils/hideSensitiveToggle";
|
||||
import { installSeqtaMenuColourPatch } from "@/seqta/utils/patchSeqtaMenuUpdateColours";
|
||||
import { installThemeImagePagePatch } from "@/seqta/utils/patchThemeImagesPageContext";
|
||||
import { initVerboseLogging, verboseInfo } from "@/utils/verboseLog";
|
||||
|
||||
function registerFetchSeqtaAppLinkListener() {
|
||||
browser.runtime.onMessage.addListener((request, _sender, sendResponse) => {
|
||||
@@ -46,6 +48,10 @@ if (document.childNodes[1]) {
|
||||
document.childNodes[1].textContent?.includes(
|
||||
"Copyright (c) SEQTA Software",
|
||||
) ?? false;
|
||||
if (hasSEQTAText) {
|
||||
installSeqtaMenuColourPatch();
|
||||
installThemeImagePagePatch();
|
||||
}
|
||||
init();
|
||||
}
|
||||
|
||||
@@ -57,11 +63,7 @@ async function init() {
|
||||
!IsSEQTAPage
|
||||
) {
|
||||
IsSEQTAPage = true;
|
||||
console.info("[BetterSEQTA+] Verified SEQTA Page");
|
||||
|
||||
if (typeof window !== "undefined" && window === window.top) {
|
||||
void browser.runtime.sendMessage({ type: "cloudSettingsPoll" }).catch(() => {});
|
||||
}
|
||||
verboseInfo("[BetterSEQTA+] Verified SEQTA Page");
|
||||
|
||||
registerFetchSeqtaAppLinkListener();
|
||||
|
||||
@@ -96,6 +98,7 @@ async function init() {
|
||||
|
||||
try {
|
||||
await initializeSettingsState();
|
||||
initVerboseLogging();
|
||||
|
||||
if (typeof settingsState.onoff === "undefined") {
|
||||
await browser.runtime.sendMessage({ type: "setDefaultStorage" });
|
||||
@@ -104,17 +107,20 @@ async function init() {
|
||||
}
|
||||
|
||||
await main();
|
||||
plugins.Monofile();
|
||||
|
||||
const { init: Monofile } = await import("@/plugins/monofile");
|
||||
Monofile();
|
||||
|
||||
if (settingsState.onoff) {
|
||||
await plugins.initializePlugins();
|
||||
const { initializePlugins } = await import("@/plugins/index");
|
||||
await initializePlugins();
|
||||
}
|
||||
|
||||
if (settingsState.devMode) {
|
||||
initializeHideSensitiveToggle();
|
||||
}
|
||||
|
||||
console.info(
|
||||
verboseInfo(
|
||||
"[BetterSEQTA+] Successfully initialised BetterSEQTA+, starting to load assets.",
|
||||
);
|
||||
} catch (error) {
|
||||
|
||||
+181
-80
@@ -10,7 +10,15 @@ import {
|
||||
performCloudSettingsUploadWithRetry,
|
||||
requestCloudSettingsDebouncedUpload,
|
||||
runCloudSettingsPoll,
|
||||
withSuppressedCloudAutoUpload,
|
||||
} from "./background/cloudSettingsAutoSync";
|
||||
import { getBsplusDeviceName } from "@/seqta/utils/bsplusDeviceName";
|
||||
import { isAllowedFetchUrl } from "@/seqta/utils/allowedFetchUrl";
|
||||
import { initCalendarBackground } from "./background/calendarBackground";
|
||||
import {
|
||||
registerGoogleCalendarMessageHandlers,
|
||||
registerOutlookCalendarMessageHandlers,
|
||||
} from "./background/calendarBackground";
|
||||
|
||||
/**
|
||||
* Session-only dev-mode override of the content API base.
|
||||
@@ -45,6 +53,11 @@ function reloadSeqtaPages() {
|
||||
/** Callback for sending a response back to the message sender */
|
||||
type MessageSender = { (response?: unknown): void };
|
||||
|
||||
async function getAccessTokenFromStorage(): Promise<string | null> {
|
||||
const { bsplus_token } = await browser.storage.local.get("bsplus_token");
|
||||
return typeof bsplus_token === "string" && bsplus_token.length > 0 ? bsplus_token : null;
|
||||
}
|
||||
|
||||
/** Accept API + GitHub fallback shapes; always return `{ success, data?: { themes } }`. */
|
||||
function normalizeFetchThemesResponse(json: unknown): {
|
||||
success: boolean;
|
||||
@@ -79,66 +92,101 @@ function normalizeFetchThemesResponse(json: unknown): {
|
||||
}
|
||||
|
||||
function handleFetchThemes(request: any, sendResponse: MessageSender): boolean {
|
||||
const { token } = request;
|
||||
const apiUrl = `${apiBase()}/api/themes?type=betterseqta&limit=100&nocache=${Date.now()}`;
|
||||
const githubUrl = `https://raw.githubusercontent.com/BetterSEQTA/BetterSEQTA-Themes/main/store/themes.json?nocache=${Date.now()}`;
|
||||
const headers: Record<string, string> = {};
|
||||
if (token) headers["Authorization"] = `Bearer ${token}`;
|
||||
fetch(apiUrl, { cache: "no-store", headers })
|
||||
.then(async (r) => {
|
||||
const json = await r.json();
|
||||
if (!r.ok) {
|
||||
throw new Error(
|
||||
(json && typeof json === "object" && "error" in json && typeof (json as { error?: string }).error === "string"
|
||||
? (json as { error: string }).error
|
||||
: null) ?? `Themes API HTTP ${r.status}`,
|
||||
);
|
||||
}
|
||||
return normalizeFetchThemesResponse(json);
|
||||
})
|
||||
.then(sendResponse)
|
||||
.catch((err) => {
|
||||
console.warn("[Background] fetchThemes API failed, trying GitHub fallback:", err?.message);
|
||||
fetch(githubUrl, { cache: "no-store" })
|
||||
.then(async (r) => {
|
||||
if (!r.ok) throw new Error(`GitHub fallback HTTP ${r.status}`);
|
||||
const data = await r.json();
|
||||
const themes = Array.isArray(data) ? data : (data?.themes ?? []);
|
||||
return normalizeFetchThemesResponse({ success: true, data: { themes } });
|
||||
})
|
||||
.then(sendResponse)
|
||||
.catch((fallbackErr) => {
|
||||
console.error("[Background] fetchThemes GitHub fallback error:", fallbackErr);
|
||||
sendResponse({ success: false, error: fallbackErr?.message });
|
||||
});
|
||||
});
|
||||
void (async () => {
|
||||
const token = await getAccessTokenFromStorage();
|
||||
const apiUrl = `${apiBase()}/api/themes?type=betterseqta&limit=100&nocache=${Date.now()}`;
|
||||
const githubUrl = `https://raw.githubusercontent.com/BetterSEQTA/BetterSEQTA-Themes/main/store/themes.json?nocache=${Date.now()}`;
|
||||
const headers: Record<string, string> = {};
|
||||
if (token) headers["Authorization"] = `Bearer ${token}`;
|
||||
fetch(apiUrl, { cache: "no-store", headers })
|
||||
.then(async (r) => {
|
||||
const json = await r.json();
|
||||
if (!r.ok) {
|
||||
throw new Error(
|
||||
(json && typeof json === "object" && "error" in json && typeof (json as { error?: string }).error === "string"
|
||||
? (json as { error: string }).error
|
||||
: null) ?? `Themes API HTTP ${r.status}`,
|
||||
);
|
||||
}
|
||||
return normalizeFetchThemesResponse(json);
|
||||
})
|
||||
.then(sendResponse)
|
||||
.catch((err) => {
|
||||
console.warn("[Background] fetchThemes API failed, trying GitHub fallback:", err?.message);
|
||||
fetch(githubUrl, { cache: "no-store" })
|
||||
.then(async (r) => {
|
||||
if (!r.ok) throw new Error(`GitHub fallback HTTP ${r.status}`);
|
||||
const data = await r.json();
|
||||
const themes = Array.isArray(data) ? data : (data?.themes ?? []);
|
||||
return normalizeFetchThemesResponse({ success: true, data: { themes } });
|
||||
})
|
||||
.then(sendResponse)
|
||||
.catch((fallbackErr) => {
|
||||
console.error("[Background] fetchThemes GitHub fallback error:", fallbackErr);
|
||||
sendResponse({ success: false, error: fallbackErr?.message });
|
||||
});
|
||||
});
|
||||
})();
|
||||
return true;
|
||||
}
|
||||
|
||||
function handleFetchThemeDetails(request: any, sendResponse: MessageSender): boolean {
|
||||
const { themeId, token } = request;
|
||||
const { themeId } = request;
|
||||
if (!themeId || typeof themeId !== "string") {
|
||||
sendResponse({ success: false, error: "Missing themeId" });
|
||||
return false;
|
||||
}
|
||||
const headers: Record<string, string> = {};
|
||||
if (token) headers["Authorization"] = `Bearer ${token}`;
|
||||
fetch(`${apiBase()}/api/themes/${themeId}`, { cache: "no-store", headers })
|
||||
.then((r) => r.json())
|
||||
.then(sendResponse)
|
||||
.catch((err) => {
|
||||
console.error("[Background] fetchThemeDetails error:", err);
|
||||
sendResponse({ success: false, error: err?.message });
|
||||
});
|
||||
void (async () => {
|
||||
const token = await getAccessTokenFromStorage();
|
||||
const headers: Record<string, string> = {};
|
||||
if (token) headers["Authorization"] = `Bearer ${token}`;
|
||||
fetch(`${apiBase()}/api/themes/${themeId}`, { cache: "no-store", headers })
|
||||
.then((r) => r.json())
|
||||
.then(sendResponse)
|
||||
.catch((err) => {
|
||||
console.error("[Background] fetchThemeDetails error:", err);
|
||||
sendResponse({ success: false, error: err?.message });
|
||||
});
|
||||
})();
|
||||
return true;
|
||||
}
|
||||
|
||||
function handleFetchFromUrl(request: any, sendResponse: MessageSender): boolean {
|
||||
function isTrustedSender(sender?: browser.Runtime.MessageSender): boolean {
|
||||
if (!sender) return false;
|
||||
if (sender.id && sender.id !== browser.runtime.id) return false;
|
||||
|
||||
const urls = [sender.url, sender.tab?.url].filter(Boolean) as string[];
|
||||
for (const pageUrl of urls) {
|
||||
if (/^chrome-extension:\/\//.test(pageUrl) || /^moz-extension:\/\//.test(pageUrl)) {
|
||||
return true;
|
||||
}
|
||||
try {
|
||||
if (isSeqtaOrigin(new URL(pageUrl).origin)) return true;
|
||||
} catch {
|
||||
// try next URL
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function handleFetchFromUrl(
|
||||
request: any,
|
||||
sendResponse: MessageSender,
|
||||
sender?: browser.Runtime.MessageSender,
|
||||
): boolean {
|
||||
if (!isTrustedSender(sender)) {
|
||||
sendResponse({ error: "Unauthorized sender" });
|
||||
return false;
|
||||
}
|
||||
const { url } = request;
|
||||
if (!url || typeof url !== "string") {
|
||||
sendResponse({ error: "Missing url" });
|
||||
return false;
|
||||
}
|
||||
if (!isAllowedFetchUrl(url)) {
|
||||
sendResponse({ error: "URL not allowed" });
|
||||
return false;
|
||||
}
|
||||
fetch(url, { cache: "no-store" })
|
||||
.then((r) => r.json())
|
||||
.then((data) => sendResponse({ data }))
|
||||
@@ -177,26 +225,42 @@ function handleCloudReserveClient(request: any, sendResponse: MessageSender): bo
|
||||
return true;
|
||||
}
|
||||
|
||||
function handleCloudLogin(request: any, sendResponse: MessageSender): boolean {
|
||||
const { client_id, redirect_uri, login, password } = request;
|
||||
function handleCloudLogin(
|
||||
request: any,
|
||||
sendResponse: MessageSender,
|
||||
sender?: browser.Runtime.MessageSender,
|
||||
): boolean {
|
||||
if (!isTrustedSender(sender)) {
|
||||
sendResponse({ error: "Unauthorized sender" });
|
||||
return false;
|
||||
}
|
||||
const { client_id, redirect_uri, login, password, device_name } = request;
|
||||
if (!client_id || !redirect_uri || !login || !password) {
|
||||
sendResponse({ error: "Missing client_id, redirect_uri, login, or password" });
|
||||
return false;
|
||||
}
|
||||
fetch("https://accounts.betterseqta.org/api/bsplus/login", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ client_id, redirect_uri, login, password }),
|
||||
})
|
||||
.then(async (r) => {
|
||||
void (async () => {
|
||||
const loginBody: Record<string, string> = {
|
||||
client_id,
|
||||
redirect_uri,
|
||||
login,
|
||||
password,
|
||||
device_name: device_name ?? await getBsplusDeviceName(),
|
||||
};
|
||||
try {
|
||||
const r = await fetch("https://accounts.betterseqta.org/api/bsplus/login", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(loginBody),
|
||||
});
|
||||
const data = await parseJsonResponse(r);
|
||||
if (!r.ok) sendResponse({ error: data?.error ?? "Login failed" });
|
||||
else sendResponse(data);
|
||||
})
|
||||
.catch((err) => {
|
||||
} catch (err) {
|
||||
console.error("[Background] cloudLogin error:", err);
|
||||
sendResponse({ error: err?.message ?? "Network error" });
|
||||
});
|
||||
sendResponse({ error: (err as Error)?.message ?? "Network error" });
|
||||
}
|
||||
})();
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -291,10 +355,18 @@ function handleCloudRefresh(request: any, sendResponse: MessageSender): boolean
|
||||
return true;
|
||||
}
|
||||
|
||||
function handleCloudSettingsUpload(request: any, sendResponse: MessageSender): boolean {
|
||||
function handleCloudSettingsUpload(
|
||||
request: any,
|
||||
sendResponse: MessageSender,
|
||||
sender?: browser.Runtime.MessageSender,
|
||||
): boolean {
|
||||
if (!isTrustedSender(sender)) {
|
||||
sendResponse({ success: false, error: "Unauthorized sender" });
|
||||
return false;
|
||||
}
|
||||
void (async () => {
|
||||
try {
|
||||
const token = request.token as string | undefined;
|
||||
const token = await getAccessTokenFromStorage();
|
||||
if (!token) {
|
||||
sendResponse({ success: false, error: "Not authenticated" });
|
||||
return;
|
||||
@@ -316,10 +388,18 @@ function handleCloudSettingsUpload(request: any, sendResponse: MessageSender): b
|
||||
return true;
|
||||
}
|
||||
|
||||
function handleCloudSettingsDownload(request: any, sendResponse: MessageSender): boolean {
|
||||
function handleCloudSettingsDownload(
|
||||
request: any,
|
||||
sendResponse: MessageSender,
|
||||
sender?: browser.Runtime.MessageSender,
|
||||
): boolean {
|
||||
if (!isTrustedSender(sender)) {
|
||||
sendResponse({ success: false, error: "Unauthorized sender" });
|
||||
return false;
|
||||
}
|
||||
void (async () => {
|
||||
try {
|
||||
const token = request.token as string | undefined;
|
||||
const token = await getAccessTokenFromStorage();
|
||||
if (!token) {
|
||||
sendResponse({ success: false, error: "Not authenticated" });
|
||||
return;
|
||||
@@ -343,22 +423,29 @@ function handleCloudSettingsDownload(request: any, sendResponse: MessageSender):
|
||||
}
|
||||
|
||||
function handleCloudFavorite(request: any, sendResponse: MessageSender): boolean {
|
||||
const { themeId, token, action } = request;
|
||||
if (!themeId || !token) {
|
||||
sendResponse({ success: false, error: "Theme ID and token required" });
|
||||
const { themeId, action } = request;
|
||||
if (!themeId) {
|
||||
sendResponse({ success: false, error: "Theme ID required" });
|
||||
return false;
|
||||
}
|
||||
const isFavorite = action === "favorite";
|
||||
fetch(`${apiBase()}/api/themes/${themeId}/favorite`, {
|
||||
method: isFavorite ? "POST" : "DELETE",
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
})
|
||||
.then((r) => r.json())
|
||||
.then(sendResponse)
|
||||
.catch((err) => {
|
||||
console.error("[Background] cloudFavorite error:", err);
|
||||
sendResponse({ success: false, error: err?.message });
|
||||
});
|
||||
void (async () => {
|
||||
const token = await getAccessTokenFromStorage();
|
||||
if (!token) {
|
||||
sendResponse({ success: false, error: "Not authenticated" });
|
||||
return;
|
||||
}
|
||||
const isFavorite = action === "favorite";
|
||||
fetch(`${apiBase()}/api/themes/${themeId}/favorite`, {
|
||||
method: isFavorite ? "POST" : "DELETE",
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
})
|
||||
.then((r) => r.json())
|
||||
.then(sendResponse)
|
||||
.catch((err) => {
|
||||
console.error("[Background] cloudFavorite error:", err);
|
||||
sendResponse({ success: false, error: err?.message });
|
||||
});
|
||||
})();
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -376,7 +463,12 @@ function isSeqtaOrigin(origin: string): boolean {
|
||||
}
|
||||
}
|
||||
|
||||
function handleSetDevApiBase(request: any): boolean {
|
||||
function handleSetDevApiBase(
|
||||
request: any,
|
||||
_sendResponse: MessageSender,
|
||||
sender?: browser.Runtime.MessageSender,
|
||||
): boolean {
|
||||
if (!isTrustedSender(sender)) return false;
|
||||
const url = typeof request?.url === "string" ? request.url.trim() : null;
|
||||
if (url && /^https?:\/\//.test(url)) {
|
||||
DEV_API_BASE = url.replace(/\/$/, "");
|
||||
@@ -415,7 +507,11 @@ const MESSAGE_HANDLERS: Record<string, MessageHandler> = {
|
||||
});
|
||||
return true;
|
||||
},
|
||||
sendNews: (req, sendResponse) => {
|
||||
sendNews: (req, sendResponse, sender) => {
|
||||
if (!isTrustedSender(sender)) {
|
||||
sendResponse({ error: "Unauthorized sender" });
|
||||
return false;
|
||||
}
|
||||
fetchNews(req.source ?? "australia", sendResponse);
|
||||
return true;
|
||||
},
|
||||
@@ -475,6 +571,10 @@ const MESSAGE_HANDLERS: Record<string, MessageHandler> = {
|
||||
},
|
||||
};
|
||||
|
||||
registerGoogleCalendarMessageHandlers(MESSAGE_HANDLERS, isTrustedSender);
|
||||
registerOutlookCalendarMessageHandlers(MESSAGE_HANDLERS, isTrustedSender);
|
||||
initCalendarBackground();
|
||||
|
||||
browser.runtime.onMessage.addListener(
|
||||
// @ts-ignore - OnMessageListener expects literal true for async, we return boolean
|
||||
(request: any, sender: browser.Runtime.MessageSender, sendResponse: MessageSender) => {
|
||||
@@ -492,10 +592,10 @@ function getDefaultValues(): SettingsState {
|
||||
return getDefaultSettingsState();
|
||||
}
|
||||
|
||||
function SetStorageValue(object: any) {
|
||||
for (var i in object) {
|
||||
browser.storage.local.set({ [i]: object[i] });
|
||||
}
|
||||
function SetStorageValue(object: SettingsState) {
|
||||
void withSuppressedCloudAutoUpload(() =>
|
||||
browser.storage.local.set(object as Record<string, unknown>),
|
||||
);
|
||||
}
|
||||
|
||||
/** One-time migration for 3.6.5: opt upgraders into Global Search + indexing + transparency defaults. */
|
||||
@@ -626,6 +726,7 @@ browser.runtime.onInstalled.addListener(function (event) {
|
||||
void migrateGlobalSearchDefaultsFor365Upgrade(event.previousVersion);
|
||||
void resetThemeOfTheMonthDisabledFor366Upgrade(event.previousVersion);
|
||||
void resetThemeOfTheMonthDismissalFor370Upgrade(event.previousVersion);
|
||||
reloadSeqtaPages();
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,544 @@
|
||||
import {
|
||||
GOOGLE_AUTH_URL,
|
||||
GOOGLE_CALENDAR_ACCOUNTS_NOT_READY_HINT,
|
||||
GOOGLE_CALENDAR_OAUTH_CALLBACK,
|
||||
GOOGLE_CALENDAR_REFRESH_URL,
|
||||
GOOGLE_CALENDAR_SCOPE,
|
||||
GOOGLE_CALENDAR_TOKEN_URL,
|
||||
GOOGLE_OAUTH_CLIENT_ID,
|
||||
googleOAuthRedirectUriHint,
|
||||
isGoogleCalendarConfigured,
|
||||
} from "@/config/googleCalendar";
|
||||
import {
|
||||
OUTLOOK_AUTH_URL,
|
||||
OUTLOOK_CALENDAR_ACCOUNTS_NOT_READY_HINT,
|
||||
OUTLOOK_CALENDAR_OAUTH_CALLBACK,
|
||||
OUTLOOK_CALENDAR_REFRESH_URL,
|
||||
OUTLOOK_CALENDAR_SCOPE,
|
||||
OUTLOOK_CALENDAR_TOKEN_URL,
|
||||
OUTLOOK_OAUTH_CLIENT_ID,
|
||||
isOutlookCalendarConfigured,
|
||||
outlookOAuthRedirectUriHint,
|
||||
} from "@/config/outlookCalendar";
|
||||
import {
|
||||
exchangeAccountsCode,
|
||||
refreshAccountsToken,
|
||||
type AccountsTokenPayload,
|
||||
} from "@/seqta/utils/calendarSync/accountsToken";
|
||||
import {
|
||||
CALENDAR_WEEKLY_ALARM,
|
||||
clampSyncWeeks,
|
||||
getAutoSyncWeekly,
|
||||
getSyncWeeksAhead,
|
||||
isAnyCalendarConnected,
|
||||
markWeeklySyncPending,
|
||||
readSharedCalendarSyncSettings,
|
||||
writeSharedCalendarSyncSettings,
|
||||
} from "@/seqta/utils/calendarSync/settings";
|
||||
import {
|
||||
clearGoogleCalendarState,
|
||||
readGoogleCalendarState,
|
||||
writeGoogleCalendarState,
|
||||
} from "@/seqta/utils/calendarSync/providerStorage";
|
||||
import { ensureGoogleAppCalendar } from "@/seqta/utils/googleCalendar/calendarProvisioning";
|
||||
import type {
|
||||
GoogleCalendarStatus,
|
||||
GoogleCalendarSyncResult,
|
||||
} from "@/seqta/utils/googleCalendar/types";
|
||||
import {
|
||||
clearOutlookCalendarState,
|
||||
readOutlookCalendarState,
|
||||
writeOutlookCalendarState,
|
||||
type OutlookCalendarStatus,
|
||||
} from "@/seqta/utils/calendarSync/providerStorage";
|
||||
import browser from "webextension-polyfill";
|
||||
|
||||
const WEEKLY_PERIOD_MINUTES = 7 * 24 * 60;
|
||||
|
||||
export type CalendarMessageHandler = (
|
||||
request: unknown,
|
||||
sendResponse: (response?: unknown) => void,
|
||||
sender?: browser.Runtime.MessageSender,
|
||||
) => boolean | void;
|
||||
|
||||
export type CalendarMessageHandlerMap = Record<string, CalendarMessageHandler>;
|
||||
|
||||
type StoredTokens = {
|
||||
accessToken?: string;
|
||||
refreshToken?: string;
|
||||
expiresAt?: number;
|
||||
lastSyncAt?: number;
|
||||
lastSyncOrigin?: string;
|
||||
};
|
||||
|
||||
type OAuthTabFlowOptions = {
|
||||
callbackPrefix: string;
|
||||
timeoutMessage: string;
|
||||
cancelledMessage: string;
|
||||
tabOpenErrorMessage: string;
|
||||
timeoutMs?: number;
|
||||
};
|
||||
|
||||
type CalendarProviderBackend = {
|
||||
label: string;
|
||||
isConfigured: () => boolean;
|
||||
redirectHint: () => string;
|
||||
mismatchRe: RegExp;
|
||||
authUrl: string;
|
||||
clientId: string;
|
||||
scope: string;
|
||||
callback: string;
|
||||
tabOpts: Omit<OAuthTabFlowOptions, "callbackPrefix">;
|
||||
notConfiguredError: string;
|
||||
notConnectedError: string;
|
||||
signInFailed: string;
|
||||
read: () => Promise<StoredTokens>;
|
||||
write: (patch: Partial<StoredTokens> & { connectedAt?: number }) => Promise<unknown>;
|
||||
clear: () => Promise<unknown>;
|
||||
exchange: (code: string, redirectUri: string, verifier: string) => Promise<AccountsTokenPayload>;
|
||||
refresh: (refreshToken: string) => Promise<AccountsTokenPayload>;
|
||||
applyAuthParams: (authUrl: URL) => void;
|
||||
messagePrefix: string;
|
||||
afterConnect?: (accessToken: string) => Promise<Partial<StoredTokens>>;
|
||||
};
|
||||
|
||||
function createProviderBackend(
|
||||
config: Omit<CalendarProviderBackend, "exchange" | "refresh"> & {
|
||||
tokenUrl: string;
|
||||
refreshUrl: string;
|
||||
notReadyHint: string;
|
||||
includeErrorDescription?: boolean;
|
||||
},
|
||||
): CalendarProviderBackend {
|
||||
const { tokenUrl, refreshUrl, notReadyHint, includeErrorDescription, ...backend } = config;
|
||||
return {
|
||||
...backend,
|
||||
exchange: (code, redirectUri, verifier) =>
|
||||
exchangeAccountsCode(tokenUrl, code, redirectUri, verifier, notReadyHint, includeErrorDescription),
|
||||
refresh: (refreshToken) =>
|
||||
refreshAccountsToken(refreshUrl, refreshToken, notReadyHint, includeErrorDescription),
|
||||
};
|
||||
}
|
||||
|
||||
const GOOGLE_BACKEND = createProviderBackend({
|
||||
label: "Google",
|
||||
isConfigured: isGoogleCalendarConfigured,
|
||||
redirectHint: googleOAuthRedirectUriHint,
|
||||
mismatchRe: /redirect_uri_mismatch|invalid_request/i,
|
||||
authUrl: GOOGLE_AUTH_URL,
|
||||
clientId: GOOGLE_OAUTH_CLIENT_ID,
|
||||
scope: GOOGLE_CALENDAR_SCOPE,
|
||||
callback: GOOGLE_CALENDAR_OAUTH_CALLBACK,
|
||||
tabOpts: {
|
||||
timeoutMessage: "Google sign-in timed out. Close the tab and try again.",
|
||||
cancelledMessage: "Google sign-in was cancelled.",
|
||||
tabOpenErrorMessage: "Could not open Google sign-in tab.",
|
||||
},
|
||||
notConfiguredError: "Google Calendar is not configured in this extension build.",
|
||||
notConnectedError: "Not connected to Google Calendar.",
|
||||
signInFailed: "Google sign-in failed",
|
||||
read: readGoogleCalendarState,
|
||||
write: writeGoogleCalendarState,
|
||||
clear: clearGoogleCalendarState,
|
||||
applyAuthParams(authUrl) {
|
||||
authUrl.searchParams.set("access_type", "offline");
|
||||
},
|
||||
messagePrefix: "googleCalendar",
|
||||
tokenUrl: GOOGLE_CALENDAR_TOKEN_URL,
|
||||
refreshUrl: GOOGLE_CALENDAR_REFRESH_URL,
|
||||
notReadyHint: GOOGLE_CALENDAR_ACCOUNTS_NOT_READY_HINT,
|
||||
async afterConnect(accessToken) {
|
||||
const state = await readGoogleCalendarState();
|
||||
const calendarId = await ensureGoogleAppCalendar(accessToken, state.calendarId);
|
||||
return { calendarId };
|
||||
},
|
||||
});
|
||||
|
||||
const OUTLOOK_BACKEND = createProviderBackend({
|
||||
label: "Microsoft",
|
||||
isConfigured: isOutlookCalendarConfigured,
|
||||
redirectHint: outlookOAuthRedirectUriHint,
|
||||
mismatchRe: /redirect_uri|invalid_request|AADSTS50011/i,
|
||||
authUrl: OUTLOOK_AUTH_URL,
|
||||
clientId: OUTLOOK_OAUTH_CLIENT_ID,
|
||||
scope: OUTLOOK_CALENDAR_SCOPE,
|
||||
callback: OUTLOOK_CALENDAR_OAUTH_CALLBACK,
|
||||
tabOpts: {
|
||||
timeoutMessage: "Microsoft sign-in timed out. Close the tab and try again.",
|
||||
cancelledMessage: "Microsoft sign-in was cancelled.",
|
||||
tabOpenErrorMessage: "Could not open Microsoft sign-in tab.",
|
||||
},
|
||||
notConfiguredError: "Outlook Calendar is not configured in this extension build.",
|
||||
notConnectedError: "Not connected to Outlook Calendar.",
|
||||
signInFailed: "Microsoft sign-in failed",
|
||||
read: readOutlookCalendarState,
|
||||
write: writeOutlookCalendarState,
|
||||
clear: clearOutlookCalendarState,
|
||||
applyAuthParams(authUrl) {
|
||||
authUrl.searchParams.set("response_mode", "query");
|
||||
},
|
||||
messagePrefix: "outlookCalendar",
|
||||
tokenUrl: OUTLOOK_CALENDAR_TOKEN_URL,
|
||||
refreshUrl: OUTLOOK_CALENDAR_REFRESH_URL,
|
||||
notReadyHint: OUTLOOK_CALENDAR_ACCOUNTS_NOT_READY_HINT,
|
||||
includeErrorDescription: true,
|
||||
});
|
||||
|
||||
function base64UrlEncode(buffer: ArrayBuffer): string {
|
||||
const bytes = new Uint8Array(buffer);
|
||||
let binary = "";
|
||||
for (const b of bytes) binary += String.fromCharCode(b);
|
||||
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
|
||||
}
|
||||
|
||||
function randomPkceVerifier(): string {
|
||||
const bytes = new Uint8Array(32);
|
||||
crypto.getRandomValues(bytes);
|
||||
return base64UrlEncode(bytes.buffer);
|
||||
}
|
||||
|
||||
async function pkceChallenge(verifier: string): Promise<string> {
|
||||
const data = new TextEncoder().encode(verifier);
|
||||
const digest = await crypto.subtle.digest("SHA-256", data);
|
||||
return base64UrlEncode(digest);
|
||||
}
|
||||
|
||||
function parseOAuthRedirectCode(responseUrl: string, providerLabel: string): string {
|
||||
const url = new URL(responseUrl);
|
||||
const err = url.searchParams.get("error");
|
||||
if (err) throw new Error(url.searchParams.get("error_description") ?? err);
|
||||
const code = url.searchParams.get("code");
|
||||
if (!code) throw new Error(`${providerLabel} sign-in did not return an authorization code.`);
|
||||
return code;
|
||||
}
|
||||
|
||||
function isOAuthCallbackUrl(url: string, callbackPrefix: string): boolean {
|
||||
if (!url.startsWith(callbackPrefix)) return false;
|
||||
const parsed = new URL(url);
|
||||
return parsed.searchParams.has("code") || parsed.searchParams.has("error");
|
||||
}
|
||||
|
||||
function waitForOAuthCallback(authTabId: number, opts: OAuthTabFlowOptions): Promise<string> {
|
||||
const timeoutMs = opts.timeoutMs ?? 10 * 60 * 1000;
|
||||
return new Promise((resolve, reject) => {
|
||||
const timeoutId = setTimeout(() => {
|
||||
cleanup();
|
||||
reject(new Error(opts.timeoutMessage));
|
||||
}, timeoutMs);
|
||||
|
||||
const cleanup = () => {
|
||||
clearTimeout(timeoutId);
|
||||
browser.tabs.onUpdated.removeListener(onUpdated);
|
||||
browser.tabs.onRemoved.removeListener(onRemoved);
|
||||
};
|
||||
|
||||
const finishFromUrl = (url: string, tabId: number) => {
|
||||
if (!isOAuthCallbackUrl(url, opts.callbackPrefix)) return false;
|
||||
cleanup();
|
||||
void browser.tabs.remove(tabId).catch(() => {});
|
||||
resolve(url);
|
||||
return true;
|
||||
};
|
||||
|
||||
const onRemoved = (tabId: number) => {
|
||||
if (tabId !== authTabId) return;
|
||||
cleanup();
|
||||
reject(new Error(opts.cancelledMessage));
|
||||
};
|
||||
|
||||
const onUpdated = (
|
||||
tabId: number,
|
||||
changeInfo: browser.Tabs.OnUpdatedChangeInfoType,
|
||||
tab: browser.Tabs.Tab,
|
||||
) => {
|
||||
if (tabId !== authTabId) return;
|
||||
const url =
|
||||
changeInfo.url ?? (changeInfo.status === "complete" ? tab.url : undefined);
|
||||
if (url) finishFromUrl(url, tabId);
|
||||
};
|
||||
|
||||
browser.tabs.onUpdated.addListener(onUpdated);
|
||||
browser.tabs.onRemoved.addListener(onRemoved);
|
||||
|
||||
void browser.tabs
|
||||
.get(authTabId)
|
||||
.then((tab) => {
|
||||
if (tab.url) finishFromUrl(tab.url, authTabId);
|
||||
})
|
||||
.catch(() => {});
|
||||
});
|
||||
}
|
||||
|
||||
async function openOAuthTab(authUrl: string, opts: OAuthTabFlowOptions): Promise<string> {
|
||||
const tab = await browser.tabs.create({ url: authUrl, active: true });
|
||||
if (tab.id === undefined) throw new Error(opts.tabOpenErrorMessage);
|
||||
return waitForOAuthCallback(tab.id, opts);
|
||||
}
|
||||
|
||||
function tokenExpiresAt(expiresIn?: number): number {
|
||||
return expiresIn ? Date.now() + expiresIn * 1000 : Date.now() + 3_600_000;
|
||||
}
|
||||
|
||||
async function getValidStoredAccessToken(
|
||||
provider: CalendarProviderBackend,
|
||||
): Promise<string> {
|
||||
const state = await provider.read();
|
||||
const now = Date.now();
|
||||
if (state.accessToken && state.expiresAt && state.expiresAt > now + 60_000) {
|
||||
return state.accessToken;
|
||||
}
|
||||
if (!state.refreshToken) throw new Error(provider.notConnectedError);
|
||||
const refreshed = await provider.refresh(state.refreshToken);
|
||||
await provider.write({
|
||||
accessToken: refreshed.access_token,
|
||||
refreshToken: refreshed.refresh_token ?? state.refreshToken,
|
||||
expiresAt: tokenExpiresAt(refreshed.expires_in),
|
||||
});
|
||||
return refreshed.access_token;
|
||||
}
|
||||
|
||||
export function registerTrustedAsyncHandler(
|
||||
handlers: CalendarMessageHandlerMap,
|
||||
isTrustedSender: (sender?: browser.Runtime.MessageSender) => boolean,
|
||||
key: string,
|
||||
fn: (request: unknown) => Promise<unknown>,
|
||||
onError?: (err: unknown) => unknown,
|
||||
): void {
|
||||
handlers[key] = (request, sendResponse, sender) => {
|
||||
if (!isTrustedSender(sender)) {
|
||||
sendResponse({ success: false, error: "Unauthorized sender" });
|
||||
return false;
|
||||
}
|
||||
void fn(request)
|
||||
.then(sendResponse)
|
||||
.catch((err) => {
|
||||
sendResponse(
|
||||
onError?.(err) ?? {
|
||||
success: false,
|
||||
error: err instanceof Error ? err.message : "Request failed",
|
||||
},
|
||||
);
|
||||
});
|
||||
return true;
|
||||
};
|
||||
}
|
||||
|
||||
async function getGoogleCalendarStatus(): Promise<GoogleCalendarStatus> {
|
||||
const [state, shared, syncWeeksAhead, autoSyncWeekly] = await Promise.all([
|
||||
readGoogleCalendarState(),
|
||||
readSharedCalendarSyncSettings(),
|
||||
getSyncWeeksAhead(),
|
||||
getAutoSyncWeekly(),
|
||||
]);
|
||||
return {
|
||||
configured: isGoogleCalendarConfigured(),
|
||||
connected: !!(state.refreshToken || state.accessToken),
|
||||
lastSyncAt: state.lastSyncAt,
|
||||
lastWeeklySyncAt: shared.lastWeeklySyncAt,
|
||||
lastSyncOrigin: state.lastSyncOrigin,
|
||||
syncWeeksAhead,
|
||||
autoSyncWeekly,
|
||||
};
|
||||
}
|
||||
|
||||
async function getOutlookCalendarStatus(): Promise<OutlookCalendarStatus> {
|
||||
const state = await readOutlookCalendarState();
|
||||
return {
|
||||
configured: isOutlookCalendarConfigured(),
|
||||
connected: !!(state.refreshToken || state.accessToken),
|
||||
lastSyncAt: state.lastSyncAt,
|
||||
lastSyncOrigin: state.lastSyncOrigin,
|
||||
};
|
||||
}
|
||||
|
||||
async function connectCalendar(provider: CalendarProviderBackend): Promise<GoogleCalendarSyncResult> {
|
||||
if (!provider.isConfigured()) {
|
||||
return { success: false, configured: false, error: provider.notConfiguredError };
|
||||
}
|
||||
|
||||
const redirectUri = provider.callback;
|
||||
const verifier = randomPkceVerifier();
|
||||
const challenge = await pkceChallenge(verifier);
|
||||
const authUrl = new URL(provider.authUrl);
|
||||
authUrl.searchParams.set("client_id", provider.clientId);
|
||||
authUrl.searchParams.set("response_type", "code");
|
||||
authUrl.searchParams.set("redirect_uri", redirectUri);
|
||||
authUrl.searchParams.set("scope", provider.scope);
|
||||
authUrl.searchParams.set("prompt", "consent");
|
||||
authUrl.searchParams.set("code_challenge", challenge);
|
||||
authUrl.searchParams.set("code_challenge_method", "S256");
|
||||
provider.applyAuthParams(authUrl);
|
||||
|
||||
let responseUrl: string;
|
||||
try {
|
||||
responseUrl = await openOAuthTab(authUrl.toString(), {
|
||||
callbackPrefix: provider.callback,
|
||||
...provider.tabOpts,
|
||||
});
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : provider.signInFailed;
|
||||
const mismatch =
|
||||
provider.mismatchRe.test(message) || provider.mismatchRe.test(String(err));
|
||||
return {
|
||||
success: false,
|
||||
configured: true,
|
||||
error: mismatch
|
||||
? `${provider.label} redirect URI mismatch. ${provider.redirectHint()}`
|
||||
: message.includes("cancel")
|
||||
? provider.tabOpts.cancelledMessage
|
||||
: message,
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const code = parseOAuthRedirectCode(responseUrl, provider.label);
|
||||
const tokens = await provider.exchange(code, redirectUri, verifier);
|
||||
const existing = await provider.read();
|
||||
await provider.write({
|
||||
accessToken: tokens.access_token,
|
||||
refreshToken: tokens.refresh_token ?? existing.refreshToken,
|
||||
expiresAt: tokenExpiresAt(tokens.expires_in),
|
||||
connectedAt: Date.now(),
|
||||
});
|
||||
if (provider.afterConnect) {
|
||||
const patch = await provider.afterConnect(tokens.access_token);
|
||||
if (patch && Object.keys(patch).length > 0) {
|
||||
await provider.write(patch);
|
||||
}
|
||||
}
|
||||
await ensureWeeklySyncAlarm();
|
||||
return { success: true, configured: true, connected: true };
|
||||
} catch (err) {
|
||||
return {
|
||||
success: false,
|
||||
configured: true,
|
||||
error: err instanceof Error ? err.message : provider.signInFailed,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function registerProviderHandlers(
|
||||
handlers: CalendarMessageHandlerMap,
|
||||
isTrustedSender: (sender?: browser.Runtime.MessageSender) => boolean,
|
||||
provider: CalendarProviderBackend,
|
||||
getStatus: () => Promise<unknown>,
|
||||
): void {
|
||||
const { messagePrefix, signInFailed } = provider;
|
||||
const errMsg = (err: unknown, fallback: string) =>
|
||||
err instanceof Error ? err.message : fallback;
|
||||
|
||||
registerTrustedAsyncHandler(
|
||||
handlers,
|
||||
isTrustedSender,
|
||||
`${messagePrefix}Connect`,
|
||||
() => connectCalendar(provider),
|
||||
(err) => ({ success: false, error: errMsg(err, signInFailed) }),
|
||||
);
|
||||
|
||||
registerTrustedAsyncHandler(
|
||||
handlers,
|
||||
isTrustedSender,
|
||||
`${messagePrefix}Disconnect`,
|
||||
async () => {
|
||||
await provider.clear();
|
||||
await ensureWeeklySyncAlarm();
|
||||
return { success: true };
|
||||
},
|
||||
(err) => ({ success: false, error: errMsg(err, "Disconnect failed") }),
|
||||
);
|
||||
|
||||
registerTrustedAsyncHandler(
|
||||
handlers,
|
||||
isTrustedSender,
|
||||
`${messagePrefix}Status`,
|
||||
getStatus,
|
||||
() => ({ configured: provider.isConfigured(), connected: false }),
|
||||
);
|
||||
|
||||
registerTrustedAsyncHandler(
|
||||
handlers,
|
||||
isTrustedSender,
|
||||
`${messagePrefix}GetAccessToken`,
|
||||
() => getValidStoredAccessToken(provider).then((accessToken) => ({ success: true, accessToken })),
|
||||
(err) => ({ success: false, error: errMsg(err, "Token refresh failed") }),
|
||||
);
|
||||
}
|
||||
|
||||
export function registerGoogleCalendarMessageHandlers(
|
||||
handlers: CalendarMessageHandlerMap,
|
||||
isTrustedSender: (sender?: browser.Runtime.MessageSender) => boolean,
|
||||
): void {
|
||||
registerProviderHandlers(handlers, isTrustedSender, GOOGLE_BACKEND, getGoogleCalendarStatus);
|
||||
|
||||
registerTrustedAsyncHandler(handlers, isTrustedSender, "googleCalendarEnsureWeeklyAlarm", async () => {
|
||||
await ensureWeeklySyncAlarm();
|
||||
return { success: true };
|
||||
}, (err) => ({
|
||||
success: false,
|
||||
error: err instanceof Error ? err.message : "Could not schedule weekly sync",
|
||||
}));
|
||||
|
||||
registerTrustedAsyncHandler(handlers, isTrustedSender, "googleCalendarUpdateSyncSettings", async (request) => {
|
||||
const body = request as { syncWeeksAhead?: number; autoSyncWeekly?: boolean };
|
||||
const patch: Record<string, unknown> = {};
|
||||
if (body.syncWeeksAhead != null) patch.syncWeeksAhead = clampSyncWeeks(body.syncWeeksAhead);
|
||||
if (body.autoSyncWeekly != null) patch.autoSyncWeekly = !!body.autoSyncWeekly;
|
||||
if (Object.keys(patch).length > 0) await writeSharedCalendarSyncSettings(patch);
|
||||
await ensureWeeklySyncAlarm();
|
||||
return { success: true, ...(await getGoogleCalendarStatus()) };
|
||||
}, (err) => ({
|
||||
success: false,
|
||||
error: err instanceof Error ? err.message : "Could not update sync settings",
|
||||
}));
|
||||
}
|
||||
|
||||
export function registerOutlookCalendarMessageHandlers(
|
||||
handlers: CalendarMessageHandlerMap,
|
||||
isTrustedSender: (sender?: browser.Runtime.MessageSender) => boolean,
|
||||
): void {
|
||||
registerProviderHandlers(handlers, isTrustedSender, OUTLOOK_BACKEND, getOutlookCalendarStatus);
|
||||
}
|
||||
|
||||
function isSeqtaTab(tab: browser.Tabs.Tab): boolean {
|
||||
const title = tab.title ?? "";
|
||||
return title.includes("SEQTA Learn") || title.includes("SEQTA Engage");
|
||||
}
|
||||
|
||||
export async function ensureWeeklySyncAlarm(): Promise<void> {
|
||||
const [connected, enabled] = await Promise.all([isAnyCalendarConnected(), getAutoSyncWeekly()]);
|
||||
if (!connected || !enabled) {
|
||||
await browser.alarms.clear(CALENDAR_WEEKLY_ALARM);
|
||||
return;
|
||||
}
|
||||
const existing = await browser.alarms.get(CALENDAR_WEEKLY_ALARM);
|
||||
if (!existing) {
|
||||
await browser.alarms.create(CALENDAR_WEEKLY_ALARM, { periodInMinutes: WEEKLY_PERIOD_MINUTES });
|
||||
}
|
||||
}
|
||||
|
||||
async function triggerWeeklySyncOnSeqtaTabs(): Promise<boolean> {
|
||||
const tabs = await browser.tabs.query({});
|
||||
let delivered = false;
|
||||
for (const tab of tabs) {
|
||||
if (tab.id == null || !isSeqtaTab(tab)) continue;
|
||||
try {
|
||||
await browser.tabs.sendMessage(tab.id, { type: "calendarRunWeeklySync" });
|
||||
delivered = true;
|
||||
} catch {
|
||||
// Tab may not have content script yet.
|
||||
}
|
||||
}
|
||||
return delivered;
|
||||
}
|
||||
|
||||
async function handleWeeklySyncAlarm(): Promise<void> {
|
||||
if (!(await isAnyCalendarConnected()) || !(await getAutoSyncWeekly())) return;
|
||||
if (!(await triggerWeeklySyncOnSeqtaTabs())) await markWeeklySyncPending();
|
||||
}
|
||||
|
||||
export function initCalendarBackground(): void {
|
||||
browser.alarms.onAlarm.addListener((alarm) => {
|
||||
if (alarm.name === CALENDAR_WEEKLY_ALARM) void handleWeeklySyncAlarm();
|
||||
});
|
||||
void ensureWeeklySyncAlarm();
|
||||
}
|
||||
@@ -25,6 +25,11 @@ const REFRESH_URL = `${ACCOUNTS_BASE}/api/bsplus/refresh`;
|
||||
const UPLOAD_DEBOUNCE_MS = 2000;
|
||||
const POLL_THROTTLE_MS = 24 * 60 * 60 * 1000;
|
||||
const POLL_THROTTLE_KEY = "bsplus_lastCloudPoll";
|
||||
const FETCH_TIMEOUT_MS = 30_000;
|
||||
|
||||
function fetchWithTimeout(url: string, init?: RequestInit): Promise<Response> {
|
||||
return fetch(url, { ...init, signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) });
|
||||
}
|
||||
|
||||
type CloudSummaryResponse = {
|
||||
desqta?: unknown;
|
||||
@@ -35,6 +40,7 @@ let reloadSeqtaPagesFn: (() => void) | null = null;
|
||||
let suppressAutoUploadDuringRestore = false;
|
||||
let debounceTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let pollInFlight: Promise<void> | null = null;
|
||||
let autoSyncInitialized = false;
|
||||
|
||||
function isAutoCloudSyncEnabled(all: Record<string, unknown>): boolean {
|
||||
return all.autoCloudSettingsSync !== false;
|
||||
@@ -65,7 +71,7 @@ async function tryRefreshTokens(): Promise<boolean> {
|
||||
if (!refresh_token || !client_id) return false;
|
||||
|
||||
try {
|
||||
const r = await fetch(REFRESH_URL, {
|
||||
const r = await fetchWithTimeout(REFRESH_URL, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ refresh_token, client_id }),
|
||||
@@ -100,7 +106,7 @@ async function fetchCloudSummaryOnce(
|
||||
| { ok: false; unauthorized: boolean; error?: string }
|
||||
> {
|
||||
try {
|
||||
const r = await fetch(CLOUD_SUMMARY_URL, {
|
||||
const r = await fetchWithTimeout(CLOUD_SUMMARY_URL, {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
cache: "no-store",
|
||||
});
|
||||
@@ -177,7 +183,7 @@ async function putSettingsOnce(token: string): Promise<PutResult> {
|
||||
return { ok: true, skipped: true };
|
||||
}
|
||||
|
||||
const r = await fetch(CLOUD_SETTINGS_SYNC_URL, {
|
||||
const r = await fetchWithTimeout(CLOUD_SETTINGS_SYNC_URL, {
|
||||
method: "PUT",
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
@@ -235,7 +241,7 @@ type GetResult =
|
||||
|
||||
async function getSettingsAndApplyOnce(token: string): Promise<GetResult> {
|
||||
try {
|
||||
const r = await fetch(CLOUD_SETTINGS_SYNC_URL, {
|
||||
const r = await fetchWithTimeout(CLOUD_SETTINGS_SYNC_URL, {
|
||||
method: "GET",
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
cache: "no-store",
|
||||
@@ -373,8 +379,8 @@ export function runCloudSettingsPoll(): Promise<void> {
|
||||
try {
|
||||
const { [POLL_THROTTLE_KEY]: last } = await browser.storage.local.get(POLL_THROTTLE_KEY);
|
||||
if (Date.now() - (Number(last) || 0) < POLL_THROTTLE_MS) return;
|
||||
await browser.storage.local.set({ [POLL_THROTTLE_KEY]: Date.now() });
|
||||
await runCloudSettingsPollInner();
|
||||
await browser.storage.local.set({ [POLL_THROTTLE_KEY]: Date.now() });
|
||||
} catch (e) {
|
||||
console.error("[BS+ cloud sync] Poll error:", e);
|
||||
} finally {
|
||||
@@ -451,8 +457,22 @@ function onStorageChanged(
|
||||
})();
|
||||
}
|
||||
|
||||
export async function withSuppressedCloudAutoUpload<T>(
|
||||
operation: () => T | Promise<T>,
|
||||
): Promise<T> {
|
||||
suppressAutoUploadDuringRestore = true;
|
||||
try {
|
||||
return await operation();
|
||||
} finally {
|
||||
suppressAutoUploadDuringRestore = false;
|
||||
}
|
||||
}
|
||||
|
||||
export function initCloudSettingsAutoSync(deps: { reloadSeqtaPages: () => void }): void {
|
||||
reloadSeqtaPagesFn = deps.reloadSeqtaPages;
|
||||
if (autoSyncInitialized) return;
|
||||
autoSyncInitialized = true;
|
||||
browser.storage.onChanged.addListener(onStorageChanged);
|
||||
void runCloudSettingsPoll();
|
||||
}
|
||||
|
||||
+20
-6
@@ -1,5 +1,7 @@
|
||||
import Parser from "rss-parser";
|
||||
|
||||
const MAX_RATE_LIMIT_RETRIES = 3;
|
||||
|
||||
/**
|
||||
* Fetches news articles specifically for Australia from the NewsAPI.
|
||||
*
|
||||
@@ -13,15 +15,23 @@ import Parser from "rss-parser";
|
||||
* to send the fetched news data back to the caller.
|
||||
* It's called with an object like `{ news: responseData }`.
|
||||
*/
|
||||
const fetchAustraliaNews = async (url: string, sendResponse: any) => {
|
||||
const fetchAustraliaNews = async (
|
||||
url: string,
|
||||
sendResponse: any,
|
||||
rateLimitRetryCount = 0,
|
||||
) => {
|
||||
fetch(url)
|
||||
.then((result) => result.json())
|
||||
.then((response) => {
|
||||
if (response.code == "rateLimited") {
|
||||
fetchAustraliaNews((url += "%00"), sendResponse);
|
||||
if (response.code == "rateLimited" && rateLimitRetryCount < MAX_RATE_LIMIT_RETRIES) {
|
||||
fetchAustraliaNews(`${url}%00`, sendResponse, rateLimitRetryCount + 1);
|
||||
} else {
|
||||
sendResponse({ news: response });
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error("[BetterSEQTA+] Failed to fetch Australia news", error);
|
||||
sendResponse({ news: { articles: [] } });
|
||||
});
|
||||
};
|
||||
|
||||
@@ -99,13 +109,14 @@ export async function fetchNews(source: string | undefined, sendResponse: any) {
|
||||
|
||||
if (normalizedSource === "australia") {
|
||||
const date = new Date();
|
||||
date.setDate(date.getDate() - 5);
|
||||
|
||||
const from =
|
||||
date.getFullYear() +
|
||||
"-" +
|
||||
(date.getMonth() + 1) +
|
||||
String(date.getMonth() + 1).padStart(2, "0") +
|
||||
"-" +
|
||||
(date.getDate() - 5);
|
||||
String(date.getDate()).padStart(2, "0");
|
||||
|
||||
const url = `https://newsapi.org/v2/everything?domains=abc.net.au&from=${from}&apiKey=17c0da766ba347c89d094449504e3080`;
|
||||
fetchAustraliaNews(url, sendResponse);
|
||||
@@ -115,7 +126,6 @@ export async function fetchNews(source: string | undefined, sendResponse: any) {
|
||||
|
||||
const parser = new Parser();
|
||||
let feeds: string[];
|
||||
console.log("fetchNews", normalizedSource);
|
||||
|
||||
if (rssFeedsByCountry[normalizedSource.toLowerCase()]) {
|
||||
feeds = rssFeedsByCountry[normalizedSource.toLowerCase()];
|
||||
@@ -129,6 +139,10 @@ export async function fetchNews(source: string | undefined, sendResponse: any) {
|
||||
const articlesPromises = feeds.map(async (feedUrl) => {
|
||||
try {
|
||||
const response = await fetch(feedUrl);
|
||||
if (!response.ok) {
|
||||
console.error(`Failed to fetch RSS feed: ${feedUrl} (${response.status})`);
|
||||
return [];
|
||||
}
|
||||
const feedString = await response.text();
|
||||
const feed = await parser.parseString(feedString);
|
||||
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
/** Google Calendar OAuth — public client config. Token exchange is on accounts.betterseqta.org. */
|
||||
|
||||
const HARDCODED_GOOGLE_OAUTH_CLIENT_ID =
|
||||
"270834969641-f6t7jtpu6j0cemse8updj3rkos7nl0hf.apps.googleusercontent.com";
|
||||
|
||||
const envClientId =
|
||||
typeof __GOOGLE_OAUTH_CLIENT_ID__ !== "undefined" ? __GOOGLE_OAUTH_CLIENT_ID__ : "";
|
||||
|
||||
export const GOOGLE_OAUTH_CLIENT_ID: string =
|
||||
envClientId.trim() || HARDCODED_GOOGLE_OAUTH_CLIENT_ID.trim();
|
||||
|
||||
export const ACCOUNTS_BASE = "https://accounts.betterseqta.org";
|
||||
|
||||
export const GOOGLE_CALENDAR_OAUTH_CALLBACK = `${ACCOUNTS_BASE}/auth/google/calendar/callback`;
|
||||
export const GOOGLE_CALENDAR_TOKEN_URL = `${ACCOUNTS_BASE}/api/bsplus/google/calendar/token`;
|
||||
export const GOOGLE_CALENDAR_REFRESH_URL = `${ACCOUNTS_BASE}/api/bsplus/google/calendar/refresh`;
|
||||
|
||||
/** App-owned secondary calendar only — cannot read or modify the user's other calendars. */
|
||||
export const GOOGLE_CALENDAR_SCOPE = "https://www.googleapis.com/auth/calendar.app.created";
|
||||
|
||||
export const GOOGLE_AUTH_URL = "https://accounts.google.com/o/oauth2/v2/auth";
|
||||
export const GOOGLE_CALENDAR_API = "https://www.googleapis.com/calendar/v3";
|
||||
|
||||
export const BSPLUS_GOOGLE_CALENDAR_NAME = "BetterSEQTA+ Timetable";
|
||||
export const BSPLUS_GOOGLE_CALENDAR_DESCRIPTION =
|
||||
"School timetable lessons synced by the BetterSEQTA+ extension.";
|
||||
|
||||
export const BSPLUS_GOOGLE_CALENDAR_EVENT_PROP = "bsplusSeqtaKey";
|
||||
|
||||
export const GOOGLE_CALENDAR_SYNC_WEEKS = 12;
|
||||
export const GOOGLE_CALENDAR_SYNC_WEEKS_MIN = 1;
|
||||
export const GOOGLE_CALENDAR_SYNC_WEEKS_MAX = 52;
|
||||
|
||||
export function isGoogleCalendarConfigured(): boolean {
|
||||
return GOOGLE_OAUTH_CLIENT_ID.length > 0;
|
||||
}
|
||||
|
||||
export const GOOGLE_CALENDAR_ACCOUNTS_NOT_READY_HINT =
|
||||
"Google Calendar connect requires accounts.betterseqta.org — see docs/GOOGLE_CALENDAR_ACCOUNTS_CALLBACK.md";
|
||||
|
||||
export function googleOAuthRedirectUriHint(): string {
|
||||
return `Authorized redirect URI in Google Cloud Console must be: ${GOOGLE_CALENDAR_OAUTH_CALLBACK}`;
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
/** Outlook Calendar OAuth — public client config. Token exchange is on accounts.betterseqta.org. */
|
||||
|
||||
import { ACCOUNTS_BASE } from "@/config/googleCalendar";
|
||||
|
||||
const HARDCODED_OUTLOOK_OAUTH_CLIENT_ID = "0b55168c-916c-4323-8f67-b3dd30af3c9e";
|
||||
|
||||
const envClientId =
|
||||
typeof __OUTLOOK_OAUTH_CLIENT_ID__ !== "undefined" ? __OUTLOOK_OAUTH_CLIENT_ID__ : "";
|
||||
|
||||
export const OUTLOOK_OAUTH_CLIENT_ID: string =
|
||||
envClientId.trim() || HARDCODED_OUTLOOK_OAUTH_CLIENT_ID.trim();
|
||||
|
||||
export const OUTLOOK_CALENDAR_OAUTH_CALLBACK = `${ACCOUNTS_BASE}/auth/microsoft/calendar/callback`;
|
||||
export const OUTLOOK_CALENDAR_TOKEN_URL = `${ACCOUNTS_BASE}/api/bsplus/microsoft/calendar/token`;
|
||||
export const OUTLOOK_CALENDAR_REFRESH_URL = `${ACCOUNTS_BASE}/api/bsplus/microsoft/calendar/refresh`;
|
||||
|
||||
export const OUTLOOK_CALENDAR_SCOPE = "offline_access Calendars.ReadWrite User.Read";
|
||||
|
||||
export const OUTLOOK_AUTH_URL =
|
||||
"https://login.microsoftonline.com/common/oauth2/v2.0/authorize";
|
||||
|
||||
export const OUTLOOK_GRAPH_API = "https://graph.microsoft.com/v1.0";
|
||||
|
||||
export const BSPLUS_OUTLOOK_CALENDAR_EVENT_CATEGORY = "BetterSEQTA+";
|
||||
|
||||
export function isOutlookCalendarConfigured(): boolean {
|
||||
return OUTLOOK_OAUTH_CLIENT_ID.length > 0;
|
||||
}
|
||||
|
||||
export const OUTLOOK_CALENDAR_ACCOUNTS_NOT_READY_HINT =
|
||||
"Outlook Calendar connect requires accounts.betterseqta.org — see docs/OUTLOOK_CALENDAR_ACCOUNTS_CALLBACK.md";
|
||||
|
||||
export function outlookOAuthRedirectUriHint(): string {
|
||||
return `Authorized redirect URI in Azure must be: ${OUTLOOK_CALENDAR_OAUTH_CALLBACK}`;
|
||||
}
|
||||
+125
-52
@@ -34,7 +34,8 @@
|
||||
display: none;
|
||||
}
|
||||
|
||||
button.uiButton.timetable-zoom.iconFamily,
|
||||
button.timetable-zoom.iconFamily,
|
||||
button.bsplus-timetable-control.iconFamily,
|
||||
.iconFamily {
|
||||
font-family: "IconFamily" !important;
|
||||
}
|
||||
@@ -63,9 +64,13 @@ body {
|
||||
|
||||
select {
|
||||
border-radius: 16px !important;
|
||||
border: 1px solid color-mix(in srgb, var(--theme-offset-bg, var(--background-secondary)) 78%, transparent) !important;
|
||||
background: color-mix(in srgb, var(--background-primary) 90%, transparent) !important;
|
||||
border: 1px solid var(--theme-offset-bg, var(--theme-secondary, var(--background-secondary))) !important;
|
||||
background: var(--theme-primary, var(--background-primary)) !important;
|
||||
color: var(--text-primary) !important;
|
||||
padding: 0.5rem 1rem !important;
|
||||
min-height: 2.5rem !important;
|
||||
font-size: 0.875rem !important;
|
||||
line-height: 1.25 !important;
|
||||
transition:
|
||||
background-color 180ms ease,
|
||||
border-color 180ms ease,
|
||||
@@ -73,14 +78,14 @@ select {
|
||||
}
|
||||
|
||||
select:hover {
|
||||
background: color-mix(in srgb, var(--background-primary) 94%, var(--background-secondary) 6%) !important;
|
||||
border-color: color-mix(in srgb, var(--theme-offset-bg, var(--background-secondary)) 92%, transparent) !important;
|
||||
background: var(--theme-secondary, var(--background-secondary)) !important;
|
||||
border-color: var(--theme-offset-bg, var(--theme-secondary, var(--background-secondary))) !important;
|
||||
}
|
||||
|
||||
select:focus {
|
||||
outline: none !important;
|
||||
background: color-mix(in srgb, var(--background-primary) 96%, var(--background-secondary) 4%) !important;
|
||||
border-color: color-mix(in srgb, var(--text-primary) 18%, var(--theme-offset-bg, var(--background-secondary)) 82%) !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;
|
||||
box-shadow: 0 0 0 1px color-mix(in srgb, var(--text-primary) 12%, transparent) !important;
|
||||
}
|
||||
|
||||
@@ -89,12 +94,12 @@ select[size="1"] {
|
||||
appearance: none;
|
||||
-webkit-appearance: none;
|
||||
-moz-appearance: none;
|
||||
color-scheme: light;
|
||||
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 20 20' fill='%23999'%3E%3Cpath fill-rule='evenodd' d='M5.23 7.21a.75.75 0 0 1 1.06.02L10 11.168l3.71-3.938a.75.75 0 1 1 1.08 1.04l-4.25 4.5a.75.75 0 0 1-1.08 0l-4.25-4.5a.75.75 0 0 1 .02-1.06Z' clip-rule='evenodd'/%3E%3C/svg%3E") !important;
|
||||
background-position: right 0.9rem center !important;
|
||||
background-repeat: no-repeat !important;
|
||||
background-size: 1rem !important;
|
||||
padding-right: 2.6rem !important;
|
||||
color-scheme: light;
|
||||
}
|
||||
|
||||
select::-ms-expand {
|
||||
@@ -102,19 +107,19 @@ select::-ms-expand {
|
||||
}
|
||||
|
||||
select option {
|
||||
background: var(--background-primary) !important;
|
||||
color: var(--text-primary) !important;
|
||||
background-color: #ffffff !important;
|
||||
color: #18181b !important;
|
||||
}
|
||||
|
||||
.dark select option {
|
||||
background-color: #1a1a1a !important;
|
||||
color: #ffffff !important;
|
||||
}
|
||||
|
||||
.dark select:not([multiple]):not([size]),
|
||||
.dark select[size="1"] {
|
||||
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 20 20' fill='%23c9c9c9'%3E%3Cpath fill-rule='evenodd' d='M5.23 7.21a.75.75 0 0 1 1.06.02L10 11.168l3.71-3.938a.75.75 0 1 1 1.08 1.04l-4.25 4.5a.75.75 0 0 1-1.08 0l-4.25-4.5a.75.75 0 0 1 .02-1.06Z' clip-rule='evenodd'/%3E%3C/svg%3E") !important;
|
||||
color-scheme: dark;
|
||||
}
|
||||
|
||||
.dark select option {
|
||||
background: var(--background-primary) !important;
|
||||
color: var(--text-primary) !important;
|
||||
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 20 20' fill='%23c9c9c9'%3E%3Cpath fill-rule='evenodd' d='M5.23 7.21a.75.75 0 0 1 1.06.02L10 11.168l3.71-3.938a.75.75 0 1 1 1.08 1.04l-4.25 4.5a.75.75 0 0 1-1.08 0l-4.25-4.5a.75.75 0 0 1 .02-1.06Z' clip-rule='evenodd'/%3E%3C/svg%3E") !important;
|
||||
}
|
||||
#container {
|
||||
background: var(--auto-background) !important;
|
||||
@@ -215,6 +220,13 @@ select option {
|
||||
pointer-events: none !important;
|
||||
}
|
||||
|
||||
/* Colour picker dialog teardown can leave an empty shell that blocks clicks */
|
||||
.modaliser-container:not(:has(.modaliser > *)) {
|
||||
display: none !important;
|
||||
visibility: hidden !important;
|
||||
pointer-events: none !important;
|
||||
}
|
||||
|
||||
.connectedNotificationsWrapper > div > button > svg > g {
|
||||
fill: var(--theme-primary) !important;
|
||||
}
|
||||
@@ -331,12 +343,18 @@ select option {
|
||||
}
|
||||
|
||||
.timetable-zoom,
|
||||
.timetable-hide {
|
||||
.timetable-hide,
|
||||
.bsplus-timetable-control {
|
||||
font-size: 14px !important;
|
||||
line-height: 1 !important;
|
||||
display: inline-flex !important;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: transparent;
|
||||
border: none;
|
||||
color: var(--text-primary);
|
||||
cursor: pointer;
|
||||
padding: 4px 8px;
|
||||
}
|
||||
|
||||
#main > .dashboard {
|
||||
@@ -421,6 +439,7 @@ ul.magicDelete > li.deleting {
|
||||
.addedButton svg {
|
||||
margin: 6px;
|
||||
fill: var(--theme-primary);
|
||||
color: var(--theme-primary);
|
||||
}
|
||||
#menu,
|
||||
.sub,
|
||||
@@ -508,6 +527,54 @@ ul.magicDelete > li.deleting {
|
||||
#menu:has(> ul > li.hasChildren.active) > ul > li:not(.hasChildren.active) {
|
||||
pointer-events: none !important;
|
||||
}
|
||||
|
||||
/* Edit Sidebar: every row + toggle must stay clickable (drill stack disables siblings). */
|
||||
#menu.bsplus-sidebar-edit-mode li.item,
|
||||
#menu.bsplus-sidebar-edit-mode section.item,
|
||||
#menu.bsplus-sidebar-edit-mode .bsplus-sidebar-offscreen,
|
||||
#menu.bsplus-sidebar-edit-mode .bsplus-sidebar-offscreen * {
|
||||
pointer-events: auto !important;
|
||||
user-select: auto !important;
|
||||
}
|
||||
|
||||
#menu.bsplus-sidebar-edit-mode:has(> ul > li.hasChildren.active)
|
||||
> ul
|
||||
> li:not(.hasChildren.active) {
|
||||
pointer-events: auto !important;
|
||||
}
|
||||
|
||||
#menu.bsplus-sidebar-edit-mode > ul > .bsplus-sidebar-offscreen:not(.hasChildren.active),
|
||||
#menu.bsplus-sidebar-edit-mode .sub .bsplus-sidebar-offscreen:not(.hasChildren.active) {
|
||||
position: relative !important;
|
||||
left: auto !important;
|
||||
width: auto !important;
|
||||
height: auto !important;
|
||||
margin: inherit !important;
|
||||
padding: inherit !important;
|
||||
overflow: visible !important;
|
||||
clip: auto !important;
|
||||
opacity: 1 !important;
|
||||
visibility: visible !important;
|
||||
}
|
||||
|
||||
#menu.bsplus-sidebar-edit-mode .item.draggable {
|
||||
display: flex !important;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
#menu.bsplus-sidebar-edit-mode .item.draggable > label {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
#menu.bsplus-sidebar-edit-mode .onoffswitch {
|
||||
pointer-events: auto !important;
|
||||
flex-shrink: 0;
|
||||
position: relative;
|
||||
z-index: 2;
|
||||
}
|
||||
|
||||
#menu section > label {
|
||||
align-items: center;
|
||||
box-sizing: border-box;
|
||||
@@ -796,6 +863,11 @@ ol:has([class*="MessageList__avatar___"] svg) {
|
||||
.quickbar .actions [title="Choose a colour"] > svg {
|
||||
scale: 0.9;
|
||||
}
|
||||
|
||||
.quickbar .actions .timetable-edit-quickbar-btn > svg {
|
||||
scale: 0.9;
|
||||
padding-top: 1px;
|
||||
}
|
||||
.quickbar[data-yiq="light"] .actions {
|
||||
color: white !important;
|
||||
}
|
||||
@@ -1026,7 +1098,13 @@ div > ol:has(.uiFileHandlerWrapper) {
|
||||
min-height: 128px !important;
|
||||
}
|
||||
body.student #menu > ul::before {
|
||||
content: "";
|
||||
display: block;
|
||||
width: 100%;
|
||||
background-image: var(--betterseqta-logo) !important;
|
||||
background-position: center;
|
||||
background-repeat: no-repeat;
|
||||
background-size: auto 48px;
|
||||
position: -webkit-sticky;
|
||||
position: sticky;
|
||||
top: 0;
|
||||
@@ -2660,11 +2738,24 @@ body {
|
||||
.days {
|
||||
width: 100%;
|
||||
}
|
||||
.modaliser {
|
||||
display: none;
|
||||
/* Do not hide .modaliser globally — SEQTA Modaliser relies on transitionend to
|
||||
dispose; display:none prevents that and leaves empty shells that block clicks. */
|
||||
.modaliser-container:not(.visible) {
|
||||
display: none !important;
|
||||
pointer-events: none !important;
|
||||
}
|
||||
|
||||
.modaliser-container.visible .modaliser {
|
||||
background: var(--better-main);
|
||||
}
|
||||
|
||||
/* ColourChooser teardown can leave a full-screen uiSlidePane that blocks entry clicks */
|
||||
.uiSlidePane:not(.shown):has(.pane.colourChooser) {
|
||||
display: none !important;
|
||||
pointer-events: none !important;
|
||||
visibility: hidden !important;
|
||||
}
|
||||
|
||||
[class*="MessageList__unread___"] {
|
||||
position: relative;
|
||||
background: var(--background-secondary, rgb(228 225 225));
|
||||
@@ -2742,39 +2833,9 @@ body {
|
||||
.defaultWelcomeWrapper {
|
||||
background: unset !important;
|
||||
}
|
||||
.clr-swatches button::after,
|
||||
.clr-dark .clr-preview::after,
|
||||
.clr-field button::after {
|
||||
opacity: unset;
|
||||
padding-top: unset;
|
||||
-webkit-transform: unset;
|
||||
transform: unset;
|
||||
-webkit-transform-origin: unset;
|
||||
transform-origin: unset;
|
||||
visibility: unset;
|
||||
-webkit-animation-name: unset !important;
|
||||
animation-name: unset !important;
|
||||
background-color: currentColor !important;
|
||||
}
|
||||
.clr-swatches button {
|
||||
align-items: unset;
|
||||
display: block;
|
||||
padding: unset;
|
||||
transition: none;
|
||||
}
|
||||
.clr-clear {
|
||||
display: none !important;
|
||||
}
|
||||
.clr-preview::before,
|
||||
.clr-preview::after {
|
||||
visibility: unset;
|
||||
-webkit-transform-origin: unset;
|
||||
transform-origin: unset;
|
||||
-webkit-transform: unset;
|
||||
transform: unset;
|
||||
padding-top: unset;
|
||||
opacity: unset;
|
||||
}
|
||||
|
||||
/* Coloris (timetable subject colours): cosmetic only — do not unset
|
||||
transforms/animations on ::after (breaks picker reopen). */
|
||||
#clr-color-preview {
|
||||
margin: 15px 0 20px 20px;
|
||||
border: 0;
|
||||
@@ -2783,6 +2844,18 @@ body {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.clr-swatches button {
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
/* Never let a closed Coloris picker intercept timetable clicks */
|
||||
body:not(.clr-open) .clr-picker,
|
||||
.clr-picker:not(.clr-open) {
|
||||
display: none !important;
|
||||
pointer-events: none !important;
|
||||
visibility: hidden !important;
|
||||
}
|
||||
|
||||
.dark
|
||||
[class*="MessageList__MessageList___"]
|
||||
> ol
|
||||
|
||||
Vendored
+16
@@ -10,6 +10,22 @@ declare module "*?inlineWorker" {
|
||||
export default value;
|
||||
}
|
||||
|
||||
/** CRXJS dynamic content / main-world script path (relative to extension root). */
|
||||
declare module "*?script" {
|
||||
const path: string;
|
||||
export default path;
|
||||
}
|
||||
|
||||
declare module "*?script&iife" {
|
||||
const path: string;
|
||||
export default path;
|
||||
}
|
||||
|
||||
declare module "*?script&module" {
|
||||
const path: string;
|
||||
export default path;
|
||||
}
|
||||
|
||||
declare module "*.png?base64" {
|
||||
const value: string;
|
||||
export default value;
|
||||
|
||||
Vendored
+2
@@ -2,3 +2,5 @@ declare const __ENABLE_GH_RELEASE_UPDATE_CHECK__: boolean;
|
||||
declare const __GH_RELEASE_REPO__: string;
|
||||
declare const __UPDATE_CHANNEL__: "stable" | "nightly";
|
||||
declare const __BUILD_LABEL__: string;
|
||||
declare const __GOOGLE_OAUTH_CLIENT_ID__: string;
|
||||
declare const __OUTLOOK_OAUTH_CLIENT_ID__: string;
|
||||
@@ -92,7 +92,7 @@
|
||||
bind:this={background}
|
||||
class="flex absolute top-0 left-0 z-50 justify-center items-center w-full h-full cursor-pointer bg-black/50"
|
||||
onclick={handleBackgroundClick}
|
||||
onkeydown={(e) => { if (e.key === "Enter") handleBackgroundClick; }}
|
||||
onkeydown={(e) => { if (e.key === "Enter") handleBackgroundClick(e as unknown as MouseEvent) }}
|
||||
>
|
||||
<div
|
||||
bind:this={content}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script lang="ts">
|
||||
import { resolveCloudPfp } from "@/seqta/utils/cloudPfpCache";
|
||||
import { resolveCloudPfp, defaultAccountsPfpUrl } from "@/seqta/utils/cloudPfpCache";
|
||||
import type { CloudUser } from "@/seqta/utils/CloudAuth";
|
||||
|
||||
const { user, class: className = "" } = $props<{
|
||||
@@ -18,10 +18,12 @@
|
||||
}
|
||||
avatarSrc = undefined;
|
||||
|
||||
if (!u?.pfpUrl || !u.id) return;
|
||||
if (!u?.id) return;
|
||||
|
||||
const pfpUrl = u.pfpUrl ?? defaultAccountsPfpUrl(u.id);
|
||||
|
||||
let cancelled = false;
|
||||
void resolveCloudPfp(u.id, u.pfpUrl).then((resolved) => {
|
||||
void resolveCloudPfp(u.id, pfpUrl).then((resolved) => {
|
||||
if (cancelled || !resolved) return;
|
||||
if (resolved.fromCache) {
|
||||
revokeUrl = resolved.src;
|
||||
|
||||
@@ -22,15 +22,13 @@
|
||||
});
|
||||
|
||||
async function upload() {
|
||||
const token = await cloudAuth.getStoredToken();
|
||||
if (!token) return;
|
||||
if (!cloudState.isLoggedIn) return;
|
||||
busy = true;
|
||||
statusError = null;
|
||||
statusMessage = null;
|
||||
try {
|
||||
const res = (await browser.runtime.sendMessage({
|
||||
type: "cloudSettingsUpload",
|
||||
token,
|
||||
})) as { success?: boolean; error?: string };
|
||||
if (res?.success) {
|
||||
statusMessage = "Settings uploaded.";
|
||||
@@ -49,15 +47,13 @@
|
||||
}
|
||||
|
||||
async function confirmDownload() {
|
||||
const token = await cloudAuth.getStoredToken();
|
||||
if (!token) return;
|
||||
if (!cloudState.isLoggedIn) return;
|
||||
busy = true;
|
||||
statusError = null;
|
||||
statusMessage = null;
|
||||
try {
|
||||
const res = (await browser.runtime.sendMessage({
|
||||
type: "cloudSettingsDownload",
|
||||
token,
|
||||
})) as { success?: boolean; error?: string; notFound?: boolean };
|
||||
if (res?.success) {
|
||||
statusMessage = "Settings restored.";
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
|
||||
let editor = $state<HTMLDivElement | null>(null)
|
||||
let view: EditorView | null = null;
|
||||
let unsubSettings: (() => void) | undefined;
|
||||
let editorTheme = new Compartment();
|
||||
let { value, onChange, className } = $props<{value: string, onChange: (value: string) => void, className?: string}>()
|
||||
|
||||
@@ -73,7 +74,7 @@
|
||||
view = createEditorView(state, editor as HTMLElement);
|
||||
}
|
||||
|
||||
settingsState.subscribe((settings) => {
|
||||
unsubSettings = settingsState.subscribe((settings) => {
|
||||
if (view) {
|
||||
view.dispatch({
|
||||
effects: editorTheme.reconfigure(
|
||||
@@ -85,6 +86,7 @@
|
||||
});
|
||||
|
||||
onDestroy(() => {
|
||||
unsubSettings?.();
|
||||
if (view) {
|
||||
view.destroy();
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from 'svelte'
|
||||
import ColourPicker from './ColourPicker.tsx';
|
||||
import ReactAdapter from './utils/ReactAdapter.svelte';
|
||||
import type { Component } from 'svelte'
|
||||
import { animate } from 'motion';
|
||||
import { delay } from '@/seqta/utils/delay.ts'
|
||||
|
||||
@@ -15,6 +14,19 @@
|
||||
|
||||
let background = $state<HTMLDivElement | null>(null);
|
||||
let content = $state<HTMLDivElement | null>(null);
|
||||
let ReactAdapter = $state<Component | null>(null);
|
||||
let ColourPickerEl = $state<unknown>(null);
|
||||
let pickerReady = $state(false);
|
||||
|
||||
const loadPicker = async () => {
|
||||
const [adapterMod, pickerMod] = await Promise.all([
|
||||
import('./utils/ReactAdapter.svelte'),
|
||||
import('./ColourPicker.tsx'),
|
||||
]);
|
||||
ReactAdapter = adapterMod.default;
|
||||
ColourPickerEl = pickerMod.default;
|
||||
pickerReady = true;
|
||||
};
|
||||
|
||||
const closePicker = async () => {
|
||||
if (standalone) return;
|
||||
@@ -37,28 +49,30 @@
|
||||
);
|
||||
|
||||
await delay(400);
|
||||
hidePicker();
|
||||
hidePicker?.();
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
if (standalone) return;
|
||||
if (!background || !content) return;
|
||||
void loadPicker().then(() => {
|
||||
if (standalone) return;
|
||||
if (!background || !content) return;
|
||||
|
||||
animate(
|
||||
background,
|
||||
{ opacity: [0, 1] },
|
||||
{ duration: 0.3, ease: [0.4, 0, 0.2, 1] }
|
||||
);
|
||||
animate(
|
||||
background,
|
||||
{ opacity: [0, 1] },
|
||||
{ duration: 0.3, ease: [0.4, 0, 0.2, 1] }
|
||||
);
|
||||
|
||||
animate(
|
||||
content,
|
||||
{ scale: [0.4, 1], opacity: [0, 1] },
|
||||
{
|
||||
type: 'spring',
|
||||
stiffness: 400,
|
||||
damping: 30
|
||||
}
|
||||
);
|
||||
animate(
|
||||
content,
|
||||
{ scale: [0.4, 1], opacity: [0, 1] },
|
||||
{
|
||||
type: 'spring',
|
||||
stiffness: 400,
|
||||
damping: 30
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
const handleEscapeKey = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape') {
|
||||
@@ -82,7 +96,9 @@
|
||||
|
||||
{#if standalone}
|
||||
<div class="h-auto overflow-clip rounded-xl">
|
||||
<ReactAdapter customOnChange={customOnChange} customState={customState} savePresets={savePresets} el={ColourPicker} />
|
||||
{#if pickerReady && ReactAdapter && ColourPickerEl}
|
||||
<ReactAdapter customOnChange={customOnChange} customState={customState} savePresets={savePresets} el={ColourPickerEl} />
|
||||
{/if}
|
||||
</div>
|
||||
{:else}
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
@@ -90,13 +106,15 @@
|
||||
bind:this={background}
|
||||
class="flex absolute top-0 left-0 z-50 justify-center items-center w-full h-full shadow-2xl cursor-pointer bg-black/20 border border-[#DDDDDD]/30 dark:border-[#38373D]/30"
|
||||
onclick={handleBackgroundClick}
|
||||
onkeydown={(e) => { e.key === 'Enter' && handleBackgroundClick }}
|
||||
onkeydown={(e) => { if (e.key === 'Enter') handleBackgroundClick(e as unknown as MouseEvent) }}
|
||||
>
|
||||
<div
|
||||
bind:this={content}
|
||||
class="p-4 h-auto bg-white rounded-xl border shadow-lg cursor-auto dark:bg-zinc-800 border-zinc-100 dark:border-zinc-700"
|
||||
>
|
||||
<ReactAdapter customOnChange={customOnChange} customState={customState} savePresets={savePresets} el={ColourPicker} />
|
||||
{#if pickerReady && ReactAdapter && ColourPickerEl}
|
||||
<ReactAdapter customOnChange={customOnChange} customState={customState} savePresets={savePresets} el={ColourPickerEl} />
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
@@ -78,7 +78,7 @@
|
||||
|
||||
const startRecording = () => {
|
||||
isRecording = true;
|
||||
recordedKeys.clear();
|
||||
recordedKeys = new Set();
|
||||
inputElement?.focus();
|
||||
};
|
||||
|
||||
@@ -87,7 +87,7 @@
|
||||
if (recordedKeys.has('esc')) {
|
||||
onChange('');
|
||||
isRecording = false;
|
||||
recordedKeys.clear();
|
||||
recordedKeys = new Set();
|
||||
inputElement?.blur();
|
||||
return;
|
||||
}
|
||||
@@ -113,10 +113,16 @@
|
||||
}
|
||||
|
||||
isRecording = false;
|
||||
recordedKeys.clear();
|
||||
recordedKeys = new Set();
|
||||
inputElement?.blur();
|
||||
};
|
||||
|
||||
const addRecordedKey = (key: string) => {
|
||||
const next = new Set(recordedKeys);
|
||||
next.add(key);
|
||||
recordedKeys = next;
|
||||
};
|
||||
|
||||
const handleKeyDown = (e: KeyboardEvent) => {
|
||||
if (!isRecording) return;
|
||||
|
||||
@@ -126,14 +132,14 @@
|
||||
const key = formatKeyForHotkey(e.key);
|
||||
|
||||
// Add modifiers
|
||||
if (e.ctrlKey) recordedKeys.add('ctrl');
|
||||
if (e.metaKey) recordedKeys.add('cmd');
|
||||
if (e.altKey) recordedKeys.add('alt');
|
||||
if (e.shiftKey) recordedKeys.add('shift');
|
||||
if (e.ctrlKey) addRecordedKey('ctrl');
|
||||
if (e.metaKey) addRecordedKey('cmd');
|
||||
if (e.altKey) addRecordedKey('alt');
|
||||
if (e.shiftKey) addRecordedKey('shift');
|
||||
|
||||
// Add the main key (ignore modifier keys themselves)
|
||||
if (!['ctrl', 'cmd', 'alt', 'shift'].includes(key)) {
|
||||
recordedKeys.add(key);
|
||||
addRecordedKey(key);
|
||||
}
|
||||
|
||||
// Auto-stop recording if we have a main key
|
||||
|
||||
@@ -1,82 +1,203 @@
|
||||
<script lang="ts">
|
||||
let { state, onChange, options } = $props<{
|
||||
state: string,
|
||||
onChange: (newState: string) => void,
|
||||
let { value, onChange, options } = $props<{
|
||||
value: string,
|
||||
onChange: (newValue: string) => void,
|
||||
options: Array<{ value: string, label: string }>
|
||||
}>();
|
||||
|
||||
let select: HTMLSelectElement;
|
||||
const listboxId = `select-listbox-${Math.random().toString(36).slice(2, 9)}`;
|
||||
|
||||
let isOpen = $state(false);
|
||||
let activeIndex = $state(0);
|
||||
let trigger = $state<HTMLButtonElement>();
|
||||
|
||||
function openMenu(preferredIndex?: number) {
|
||||
isOpen = true;
|
||||
const selectedIndex = options.findIndex((option) => option.value === value);
|
||||
activeIndex = preferredIndex ?? (selectedIndex >= 0 ? selectedIndex : 0);
|
||||
}
|
||||
|
||||
function closeMenu(returnFocus = true) {
|
||||
isOpen = false;
|
||||
if (returnFocus) trigger?.focus();
|
||||
}
|
||||
|
||||
function selectValue(nextValue: string) {
|
||||
onChange(nextValue);
|
||||
closeMenu();
|
||||
}
|
||||
|
||||
function onKeydown(event: KeyboardEvent, inListbox = false) {
|
||||
const { key } = event;
|
||||
|
||||
if (key === "ArrowDown" || key === "ArrowUp") {
|
||||
event.preventDefault();
|
||||
const count = options.length;
|
||||
if (!count) return;
|
||||
if (isOpen || inListbox) {
|
||||
activeIndex = (activeIndex + (key === "ArrowDown" ? 1 : -1) + count) % count;
|
||||
} else {
|
||||
openMenu();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (key === "Enter" || key === " ") {
|
||||
event.preventDefault();
|
||||
if (isOpen) {
|
||||
const option = options[activeIndex];
|
||||
if (option) selectValue(option.value);
|
||||
} else {
|
||||
openMenu();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (key === "Escape" && isOpen) {
|
||||
event.preventDefault();
|
||||
closeMenu();
|
||||
return;
|
||||
}
|
||||
|
||||
if (!inListbox) return;
|
||||
|
||||
if (key === "Home") {
|
||||
event.preventDefault();
|
||||
activeIndex = 0;
|
||||
} else if (key === "End") {
|
||||
event.preventDefault();
|
||||
activeIndex = Math.max(0, options.length - 1);
|
||||
} else if (key === "Tab") {
|
||||
closeMenu(false);
|
||||
}
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
if (!isOpen) return;
|
||||
|
||||
queueMicrotask(() => document.getElementById(listboxId)?.focus());
|
||||
|
||||
const wrapper = trigger?.parentElement;
|
||||
const onPointerDown = (event: PointerEvent) => {
|
||||
if (wrapper && event.composedPath().includes(wrapper)) return;
|
||||
closeMenu(false);
|
||||
};
|
||||
|
||||
document.addEventListener("pointerdown", onPointerDown, true);
|
||||
return () => document.removeEventListener("pointerdown", onPointerDown, true);
|
||||
});
|
||||
</script>
|
||||
|
||||
<div class="select-wrapper relative w-full overflow-hidden rounded-2xl border shadow-2xl">
|
||||
<select
|
||||
bind:this={select}
|
||||
value={state}
|
||||
onchange={() => onChange(select.value)}
|
||||
class="select-input w-full appearance-none border-none bg-transparent px-4 py-2.5 pr-10 text-[0.875rem] font-medium transition-colors"
|
||||
<div class="select relative w-full">
|
||||
<button
|
||||
bind:this={trigger}
|
||||
type="button"
|
||||
class="select-trigger flex w-full items-center justify-between gap-3 rounded-[18px] border px-4 py-2.5 text-sm font-medium leading-tight shadow-2xl transition-[background-color,border-color,box-shadow] duration-200 cursor-pointer"
|
||||
aria-haspopup="listbox"
|
||||
aria-expanded={isOpen}
|
||||
aria-controls={listboxId}
|
||||
onclick={() => (isOpen ? closeMenu() : openMenu())}
|
||||
onkeydown={onKeydown}
|
||||
>
|
||||
{#each options as option}
|
||||
<option value={option.value}>
|
||||
{option.label}
|
||||
</option>
|
||||
{/each}
|
||||
</select>
|
||||
<span class="select-icon pointer-events-none absolute inset-y-0 right-0 flex items-center pr-3" aria-hidden="true">
|
||||
<svg viewBox="0 0 20 20" fill="currentColor" class="h-4 w-4">
|
||||
<path fill-rule="evenodd" d="M5.23 7.21a.75.75 0 0 1 1.06.02L10 11.168l3.71-3.938a.75.75 0 1 1 1.08 1.04l-4.25 4.5a.75.75 0 0 1-1.08 0l-4.25-4.5a.75.75 0 0 1 .02-1.06Z" clip-rule="evenodd"></path>
|
||||
</svg>
|
||||
</span>
|
||||
<span class="truncate">
|
||||
{options.find((option) => option.value === value)?.label ?? value}
|
||||
</span>
|
||||
<span class="select-icon shrink-0" aria-hidden="true">
|
||||
<svg viewBox="0 0 20 20" fill="currentColor" class="h-4 w-4">
|
||||
<path
|
||||
fill-rule="evenodd"
|
||||
d="M5.23 7.21a.75.75 0 0 1 1.06.02L10 11.168l3.71-3.938a.75.75 0 1 1 1.08 1.04l-4.25 4.5a.75.75 0 0 1-1.08 0l-4.25-4.5a.75.75 0 0 1 .02-1.06Z"
|
||||
clip-rule="evenodd"
|
||||
/>
|
||||
</svg>
|
||||
</span>
|
||||
</button>
|
||||
|
||||
{#if isOpen}
|
||||
<div
|
||||
id={listboxId}
|
||||
class="select-menu absolute inset-x-0 top-[calc(100%+0.35rem)] z-50 flex max-h-72 flex-col gap-0.5 p-2"
|
||||
role="listbox"
|
||||
tabindex="-1"
|
||||
aria-activedescendant={options[activeIndex] ? `${listboxId}-opt-${activeIndex}` : undefined}
|
||||
onkeydown={(event) => onKeydown(event, true)}
|
||||
>
|
||||
{#each options as option, index (option.value)}
|
||||
<button
|
||||
type="button"
|
||||
id={`${listboxId}-opt-${index}`}
|
||||
role="option"
|
||||
aria-selected={option.value === value}
|
||||
class="select-option block w-full rounded-[10px] border-none px-3.5 py-2.5 text-left text-sm font-medium leading-snug transition-colors duration-150 cursor-pointer"
|
||||
class:is-selected={option.value === value}
|
||||
class:is-active={index === activeIndex}
|
||||
tabindex="-1"
|
||||
onclick={() => selectValue(option.value)}
|
||||
onmouseenter={() => (activeIndex = index)}
|
||||
>
|
||||
{option.label}
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.select-wrapper {
|
||||
background: color-mix(in srgb, var(--background-primary) 88%, transparent);
|
||||
border-color: color-mix(in srgb, var(--theme-offset-bg, var(--background-secondary)) 72%, transparent);
|
||||
border-radius: 18px;
|
||||
.select {
|
||||
--sel-border: var(--theme-offset-bg, var(--theme-secondary, #e5e7eb));
|
||||
--sel-bg: var(--theme-primary, #ffffff);
|
||||
--sel-surface: var(--theme-secondary, #e5e7eb);
|
||||
--sel-focus-border: color-mix(in srgb, var(--text-primary) 22%, var(--theme-secondary, #e5e7eb) 78%);
|
||||
--sel-ring: 0 0 0 1px color-mix(in srgb, var(--text-primary) 12%, transparent);
|
||||
--sel-menu-shadow:
|
||||
0 10px 25px -5px rgb(0 0 0 / 0.25),
|
||||
0 8px 10px -6px rgb(0 0 0 / 0.2);
|
||||
}
|
||||
|
||||
.select-trigger {
|
||||
border-color: var(--sel-border);
|
||||
background: var(--sel-bg);
|
||||
color: var(--text-primary);
|
||||
transition:
|
||||
background-color 180ms ease,
|
||||
border-color 180ms ease,
|
||||
box-shadow 180ms ease,
|
||||
transform 180ms ease;
|
||||
}
|
||||
|
||||
.select-wrapper:hover {
|
||||
background: color-mix(in srgb, var(--background-primary) 94%, var(--background-secondary) 6%);
|
||||
border-color: color-mix(in srgb, var(--theme-offset-bg, var(--background-secondary)) 88%, transparent);
|
||||
}
|
||||
|
||||
.select-wrapper:focus-within {
|
||||
background: color-mix(in srgb, var(--background-primary) 96%, var(--background-secondary) 4%);
|
||||
border-color: color-mix(in srgb, var(--text-primary) 22%, var(--theme-offset-bg, var(--background-secondary)) 78%);
|
||||
box-shadow: 0 0 0 1px color-mix(in srgb, var(--text-primary) 12%, transparent);
|
||||
}
|
||||
|
||||
.select-input {
|
||||
color: var(--text-primary);
|
||||
.select-trigger:hover,
|
||||
.select-trigger:focus-visible {
|
||||
outline: none;
|
||||
text-overflow: ellipsis;
|
||||
background: var(--sel-surface);
|
||||
border-color: var(--sel-border);
|
||||
}
|
||||
|
||||
.select-input:hover,
|
||||
.select-input:focus {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.select-input option {
|
||||
background: var(--background-primary);
|
||||
color: var(--text-primary);
|
||||
.select-trigger:focus-visible {
|
||||
border-color: var(--sel-focus-border);
|
||||
box-shadow: var(--sel-ring);
|
||||
}
|
||||
|
||||
.select-icon {
|
||||
color: color-mix(in srgb, var(--text-primary) 60%, transparent);
|
||||
}
|
||||
|
||||
.select-input {
|
||||
color-scheme: light;
|
||||
.select-menu {
|
||||
border: 1px solid var(--sel-border);
|
||||
border-radius: 14px;
|
||||
background: var(--sel-bg);
|
||||
box-shadow: var(--sel-menu-shadow);
|
||||
}
|
||||
|
||||
:global(.dark) .select-input {
|
||||
color-scheme: dark;
|
||||
.select-menu:focus-visible {
|
||||
outline: none;
|
||||
box-shadow: var(--sel-menu-shadow), var(--sel-ring);
|
||||
}
|
||||
|
||||
.select-option {
|
||||
background: transparent;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.select-option:hover,
|
||||
.select-option:focus-visible,
|
||||
.select-option.is-active,
|
||||
.select-option.is-selected {
|
||||
outline: none;
|
||||
background: var(--sel-surface);
|
||||
}
|
||||
</style>
|
||||
@@ -1,5 +1,5 @@
|
||||
<script lang="ts">
|
||||
let { state, onChange, min = 0, max = 100, step = 1 } = $props<{
|
||||
let { state = $bindable(), onChange, min = 0, max = 100, step = 1 } = $props<{
|
||||
state: number,
|
||||
onChange: (value: number) => void,
|
||||
min?: number,
|
||||
|
||||
@@ -38,8 +38,8 @@
|
||||
});
|
||||
</script>
|
||||
|
||||
<div class="flex flex-col h-full">
|
||||
<div class="top-0 z-10 text-[0.875rem] pb-0.5 mx-4 px-2 tab-width-container">
|
||||
<div class="flex flex-col h-full min-h-0">
|
||||
<div class="top-0 z-10 shrink-0 text-[0.875rem] pb-0.5 mx-4 px-2 tab-width-container" role="tablist">
|
||||
<div bind:this={containerRef} class="flex relative">
|
||||
<MotionDiv
|
||||
class="absolute top-0 left-0 z-0 h-full bg-gradient-to-tr dark:from-[#38373D]/80 dark:to-[#38373D] from-[#DDDDDD]/80 to-[#DDDDDD] rounded-full opacity-40 tab-width"
|
||||
@@ -48,6 +48,8 @@
|
||||
/>
|
||||
{#each tabs as { title }, index}
|
||||
<button
|
||||
role="tab"
|
||||
aria-selected={activeTab === index}
|
||||
class="relative z-10 flex-1 px-4 py-2 focus-visible:outline-none"
|
||||
onclick={() => activeTab = index}
|
||||
>
|
||||
@@ -56,21 +58,17 @@
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
<div class="overflow-hidden px-4 h-full">
|
||||
<MotionDiv
|
||||
class="h-full"
|
||||
animate={{ x: `${-activeTab * 100}%` }}
|
||||
transition={springTransition}
|
||||
>
|
||||
<div class="flex">
|
||||
{#each tabs as { Content, props }, index}
|
||||
<div class="absolute focus:outline-none w-full pt-2 transition-opacity duration-300 overflow-y-scroll no-scrollbar pb-2 h-full tab {activeTab === index ? 'opacity-100 active' : 'opacity-0'}"
|
||||
style="left: {index * 100}%;">
|
||||
<div style="left: {index * 100}%;" class="fixed top-0 w-full h-8 bg-gradient-to-b to-transparent pointer-events-none z-[100] from-white dark:from-zinc-800 dark:to-transparent"></div>
|
||||
<Content {...props} />
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
</MotionDiv>
|
||||
<div class="overflow-hidden px-4 flex-1 min-h-0">
|
||||
{#each tabs as { Content, props }, index (index)}
|
||||
{#if activeTab === index}
|
||||
<div
|
||||
role="tabpanel"
|
||||
class="focus:outline-none w-full h-full min-h-0 pt-2 overflow-y-auto no-scrollbar pb-6 tab active"
|
||||
>
|
||||
<div class="sticky top-0 w-full h-8 bg-gradient-to-b to-transparent pointer-events-none z-[100] from-white dark:from-zinc-800 dark:to-transparent"></div>
|
||||
<Content {...props} />
|
||||
</div>
|
||||
{/if}
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,15 @@
|
||||
<script lang="ts">
|
||||
import { LUCIDE_MOON_PATH } from "@/lib/icons/lucideMoon";
|
||||
|
||||
let { class: className = "w-5 h-5" }: { class?: string } = $props();
|
||||
</script>
|
||||
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 24 24"
|
||||
fill="currentColor"
|
||||
class={className}
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path d={LUCIDE_MOON_PATH} />
|
||||
</svg>
|
||||
@@ -0,0 +1,15 @@
|
||||
<script lang="ts">
|
||||
import { LUCIDE_SUN_PATH } from "@/lib/icons/lucideSun";
|
||||
|
||||
let { class: className = "w-5 h-5" }: { class?: string } = $props();
|
||||
</script>
|
||||
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 24 24"
|
||||
fill="currentColor"
|
||||
class={className}
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path d={LUCIDE_SUN_PATH} />
|
||||
</svg>
|
||||
@@ -2,7 +2,6 @@
|
||||
import { hasEnoughStorageSpace, isIndexedDBSupported, writeData, openDatabase, readAllData, deleteData } from '@/interface/hooks/BackgroundDataLoader';
|
||||
import Spinner from '../Spinner.svelte';
|
||||
import { settingsState } from '@/seqta/utils/listeners/SettingsState'
|
||||
import { Index } from 'flexsearch';
|
||||
import { backgroundUpdates } from '@/interface/hooks/BackgroundUpdates'
|
||||
import { ThemeManager } from '@/plugins/built-in/themes/theme-manager'
|
||||
|
||||
@@ -20,8 +19,6 @@
|
||||
let savedBackgrounds = $state<string[]>([]);
|
||||
let installingBackgrounds = $state<Set<string>>(new Set());
|
||||
let debugInfo = $state<string>('');
|
||||
let searchIndex = $state<Index | null>(null);
|
||||
|
||||
// New state variables
|
||||
let activeTab = $state<'all' | 'installed' | 'photos' | 'videos'>('all');
|
||||
let sortBy = $state<'newest' | 'popular' | 'name'>('newest');
|
||||
@@ -36,19 +33,6 @@
|
||||
}
|
||||
const data = await response.json();
|
||||
backgrounds = data.backgrounds;
|
||||
|
||||
// Initialize FlexSearch index
|
||||
const index = new Index({
|
||||
tokenize: "forward",
|
||||
preset: "score"
|
||||
});
|
||||
|
||||
// Add backgrounds to the index
|
||||
backgrounds.forEach((bg, i) => {
|
||||
index.add(i, bg.name + " " + bg.description);
|
||||
});
|
||||
|
||||
searchIndex = index;
|
||||
debugInfo = `Loaded ${backgrounds.length} backgrounds`;
|
||||
await loadSavedBackgrounds();
|
||||
} catch (e) {
|
||||
@@ -79,10 +63,11 @@
|
||||
let filteredBackgrounds = $derived((() => {
|
||||
let filtered = backgrounds;
|
||||
|
||||
// Use FlexSearch if there's a search term
|
||||
if (searchTerm.trim() && searchIndex) {
|
||||
const results = searchIndex.search(searchTerm) as number[];
|
||||
filtered = results.map(i => backgrounds[i]);
|
||||
if (searchTerm.trim()) {
|
||||
const q = searchTerm.trim().toLowerCase();
|
||||
filtered = backgrounds.filter((bg) =>
|
||||
`${bg.name} ${bg.description}`.toLowerCase().includes(q),
|
||||
);
|
||||
}
|
||||
|
||||
// Apply category filtering
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
<script lang="ts">
|
||||
import logo from '@/resources/icons/betterseqta-dark-full.png';
|
||||
import logoDark from '@/resources/icons/betterseqta-light-full.png';
|
||||
import { closeStore } from '@/seqta/ui/renderStore'
|
||||
import browser from 'webextension-polyfill';
|
||||
import CloudHeader from './CloudHeader.svelte';
|
||||
|
||||
const handleCloseStore = () => {
|
||||
void import('@/seqta/ui/renderStore').then((module) => module.closeStore());
|
||||
};
|
||||
|
||||
// Props
|
||||
let { searchTerm, setSearchTerm, darkMode, activeTab, setActiveTab } = $props<{
|
||||
searchTerm: string,
|
||||
@@ -64,7 +67,7 @@
|
||||
|
||||
<!-- Close Button -->
|
||||
<button
|
||||
onclick={closeStore}
|
||||
onclick={handleCloseStore}
|
||||
class="p-1 px-3"
|
||||
>
|
||||
<span class="text-2xl font-IconFamily"></span>
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -12,18 +12,18 @@
|
||||
|
||||
<div
|
||||
onclick={onClick}
|
||||
onkeydown={onClick}
|
||||
tabindex="-1"
|
||||
onkeydown={(e) => { if (e.key === 'Enter' || e.key === ' ') onClick() }}
|
||||
tabindex="0"
|
||||
role="button"
|
||||
class="relative w-16 h-16 cursor-pointer rounded-xl transition ring-3 dark:ring-zinc-500/50 ring-zinc-300 {isEditMode ? 'animate-shake' : ''} {isSelected ? 'dark:ring-4 ring-4' : 'ring-0'}"
|
||||
>
|
||||
{#if isEditMode}
|
||||
<div
|
||||
tabindex="-1"
|
||||
tabindex="0"
|
||||
role="button"
|
||||
class="absolute top-0 right-0 z-10 flex w-6 h-6 p-2 text-white translate-x-1/2 -translate-y-1/2 bg-red-600 rounded-full place-items-center"
|
||||
onclick={onDelete}
|
||||
onkeydown={onDelete}
|
||||
onclick={(e) => { e.stopPropagation(); onDelete() }}
|
||||
onkeydown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.stopPropagation(); onDelete() } }}
|
||||
>
|
||||
<div class="w-4 h-0.5 bg-white"></div>
|
||||
</div>
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
<script lang="ts">
|
||||
import { hasEnoughStorageSpace, isIndexedDBSupported, writeData, openDatabase, readAllData, deleteData } from '@/interface/hooks/BackgroundDataLoader'
|
||||
import { hasEnoughStorageSpace, isIndexedDBSupported, writeData, readAllData, deleteData } from '@/interface/hooks/BackgroundDataLoader'
|
||||
import BackgroundUploader from './BackgroundUploader.svelte';
|
||||
import BackgroundItem from './BackgroundItem.svelte'
|
||||
import { onMount, onDestroy } from 'svelte'
|
||||
import { loadBackground } from '@/seqta/ui/ImageBackgrounds'
|
||||
import { delay } from 'lodash'
|
||||
import { backgroundUpdates } from '@/interface/hooks/BackgroundUpdates'
|
||||
|
||||
let { isEditMode, selectNoBackground = $bindable(), selectedBackground = $bindable() } = $props<{ isEditMode: boolean, selectNoBackground: () => void, selectedBackground: string | null }>();
|
||||
@@ -14,10 +13,9 @@
|
||||
let imageBackgrounds = $derived(backgrounds.filter(bg => bg.type === 'image'));
|
||||
let videoBackgrounds = $derived(backgrounds.filter(bg => bg.type === 'video'));
|
||||
|
||||
let isVisible = $state(false);
|
||||
let element: HTMLElement;
|
||||
let observer: MutationObserver;
|
||||
let parentElement: HTMLElement | null = null;
|
||||
function setError(e: unknown) {
|
||||
error = e instanceof Error ? e.message : 'An unknown error occurred';
|
||||
}
|
||||
|
||||
async function getTheme() {
|
||||
return localStorage.getItem('selectedBackground');
|
||||
@@ -47,34 +45,7 @@
|
||||
await writeData(fileId, fileType, blob);
|
||||
backgrounds = [...backgrounds, { id: fileId, type: fileType, blob, url: URL.createObjectURL(blob) }];
|
||||
} catch (e) {
|
||||
if (e instanceof Error) {
|
||||
error = e.message;
|
||||
} else {
|
||||
error = 'An unknown error occurred';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function loadBackgroundMetadata(): Promise<void> {
|
||||
try {
|
||||
error = null;
|
||||
|
||||
if (!isIndexedDBSupported()) {
|
||||
throw new Error("Your browser doesn't support IndexedDB. Unable to load backgrounds.");
|
||||
}
|
||||
|
||||
await openDatabase();
|
||||
const data = await readAllData();
|
||||
selectedBackground = await getTheme();
|
||||
|
||||
// Only load metadata (id and type) for placeholders
|
||||
backgrounds = data.map(({ id, type }) => ({ id, type, blob: null }));
|
||||
} catch (e) {
|
||||
if (e instanceof Error) {
|
||||
error = e.message;
|
||||
} else {
|
||||
error = 'An unknown error occurred';
|
||||
}
|
||||
setError(e);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -86,8 +57,9 @@
|
||||
throw new Error("Your browser doesn't support IndexedDB. Unable to load backgrounds.");
|
||||
}
|
||||
|
||||
selectedBackground = await getTheme();
|
||||
const dbData = await readAllData();
|
||||
|
||||
|
||||
// Release existing object URLs to prevent memory leaks
|
||||
backgrounds.forEach(bg => {
|
||||
if (bg.url) URL.revokeObjectURL(bg.url);
|
||||
@@ -106,11 +78,7 @@
|
||||
selectNoBackground();
|
||||
}
|
||||
} catch (e) {
|
||||
if (e instanceof Error) {
|
||||
error = e.message;
|
||||
} else {
|
||||
error = 'An unknown error occurred';
|
||||
}
|
||||
setError(e);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -119,7 +87,7 @@
|
||||
selectNoBackground();
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
selectedBackground = fileId;
|
||||
setTheme(fileId);
|
||||
}
|
||||
@@ -133,11 +101,7 @@
|
||||
selectNoBackground();
|
||||
}
|
||||
} catch (e) {
|
||||
if (e instanceof Error) {
|
||||
error = `Failed to delete background: ${e.message}`;
|
||||
} else {
|
||||
error = 'An unknown error occurred';
|
||||
}
|
||||
error = e instanceof Error ? `Failed to delete background: ${e.message}` : 'An unknown error occurred';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -157,39 +121,23 @@
|
||||
}
|
||||
});
|
||||
|
||||
function checkActiveClass() {
|
||||
if (parentElement?.classList.contains('active')) {
|
||||
delay(() => {
|
||||
isVisible = true;
|
||||
syncBackgrounds();
|
||||
}, 600);
|
||||
}
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
loadBackgroundMetadata();
|
||||
syncBackgrounds();
|
||||
backgroundUpdates.addListener(syncBackgrounds);
|
||||
|
||||
parentElement = element.closest('.tab');
|
||||
if (parentElement) {
|
||||
observer = new MutationObserver(checkActiveClass);
|
||||
observer.observe(parentElement, { attributes: true, attributeFilter: ['class'] });
|
||||
|
||||
return () => {
|
||||
observer.disconnect();
|
||||
backgroundUpdates.removeListener(syncBackgrounds);
|
||||
};
|
||||
}
|
||||
return () => {
|
||||
backgroundUpdates.removeListener(syncBackgrounds);
|
||||
};
|
||||
});
|
||||
|
||||
onDestroy(() => {
|
||||
if (observer) {
|
||||
observer.disconnect();
|
||||
}
|
||||
backgrounds.forEach((bg) => {
|
||||
if (bg.url) URL.revokeObjectURL(bg.url);
|
||||
});
|
||||
});
|
||||
</script>
|
||||
|
||||
<div bind:this={element} class="relative px-1 { !( isEditMode && imageBackgrounds.length === 0 && videoBackgrounds.length === 0 ) && 'pt-2' }">
|
||||
<div class="relative px-1 { !( isEditMode && imageBackgrounds.length === 0 && videoBackgrounds.length === 0 ) && 'pt-2' }">
|
||||
{#if !(imageBackgrounds.length === 0 && isEditMode)}
|
||||
<h2 class="pb-2 text-lg font-bold">Background Images</h2>
|
||||
<div class="flex flex-wrap gap-4 mb-4">
|
||||
@@ -197,7 +145,7 @@
|
||||
<BackgroundUploader on:fileChange={e => handleFileChange(e.detail)} />
|
||||
{/if}
|
||||
{#each imageBackgrounds as bg (bg.id)}
|
||||
{#if isVisible && bg.blob}
|
||||
{#if bg.url}
|
||||
<BackgroundItem
|
||||
bg={bg}
|
||||
isSelected={selectedBackground === bg.id}
|
||||
@@ -218,7 +166,7 @@
|
||||
<BackgroundUploader on:fileChange={e => handleFileChange(e.detail)} />
|
||||
{/if}
|
||||
{#each videoBackgrounds as bg (bg.id)}
|
||||
{#if isVisible && bg.blob}
|
||||
{#if bg.url}
|
||||
<BackgroundItem
|
||||
bg={bg}
|
||||
isSelected={selectedBackground === bg.id}
|
||||
@@ -232,4 +180,4 @@
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,34 @@
|
||||
<script lang="ts">
|
||||
import { blobToDataUrl } from '@/plugins/built-in/themes/themeImageUrl'
|
||||
|
||||
let { source, alt = '', class: className = '' } = $props<{
|
||||
source: string | Blob | null | undefined
|
||||
alt?: string
|
||||
class?: string
|
||||
}>()
|
||||
|
||||
let src = $state('')
|
||||
|
||||
$effect(() => {
|
||||
const value = source
|
||||
if (!value) {
|
||||
src = ''
|
||||
return
|
||||
}
|
||||
if (typeof value === 'string') {
|
||||
src = value
|
||||
return
|
||||
}
|
||||
let cancelled = false
|
||||
void blobToDataUrl(value).then((url) => {
|
||||
if (!cancelled) src = url
|
||||
})
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
{#if src}
|
||||
<img {src} {alt} class={className} />
|
||||
{/if}
|
||||
@@ -2,13 +2,12 @@
|
||||
import type { CustomTheme, ThemeList } from '@/types/CustomThemes'
|
||||
import { onDestroy, onMount } from 'svelte'
|
||||
import browser from 'webextension-polyfill'
|
||||
import { OpenThemeCreator } from '@/plugins/built-in/themes/ThemeCreator'
|
||||
import { OpenStorePage } from '@/seqta/ui/renderStore'
|
||||
import { themeUpdates } from '@/interface/hooks/ThemeUpdates'
|
||||
import { closeExtensionPopup } from '@/seqta/utils/Closers/closeExtensionPopup'
|
||||
import { ThemeManager } from '@/plugins/built-in/themes/theme-manager'
|
||||
import { cloudAuth } from '@/seqta/utils/CloudAuth'
|
||||
import SignInToFavoriteModal from '@/interface/components/SignInToFavoriteModal.svelte'
|
||||
import ThemeBlobImage from '@/interface/components/themes/ThemeBlobImage.svelte'
|
||||
|
||||
const themeManager = ThemeManager.getInstance();
|
||||
|
||||
@@ -21,11 +20,14 @@
|
||||
let prevLoggedIn = $state(false);
|
||||
let showSignInModal = $state(false);
|
||||
|
||||
cloudAuth.subscribe((s) => {
|
||||
const now = s.isLoggedIn;
|
||||
if (now && !prevLoggedIn && themes) void fetchThemes();
|
||||
prevLoggedIn = now;
|
||||
cloudLoggedIn = now;
|
||||
$effect(() => {
|
||||
const unsub = cloudAuth.subscribe((s) => {
|
||||
const now = s.isLoggedIn;
|
||||
if (now && !prevLoggedIn && themes) void fetchThemes();
|
||||
prevLoggedIn = now;
|
||||
cloudLoggedIn = now;
|
||||
});
|
||||
return unsub;
|
||||
});
|
||||
|
||||
const handleThemeClick = async (theme: CustomTheme, e: MouseEvent) => {
|
||||
@@ -102,17 +104,14 @@
|
||||
selectedTheme: themeManager.getSelectedThemeId() || '',
|
||||
}
|
||||
if (themes && cloudLoggedIn) {
|
||||
const token = await cloudAuth.getStoredToken();
|
||||
if (token) {
|
||||
const status: Record<string, boolean> = {};
|
||||
await Promise.all(
|
||||
themes.themes.map(async (t) => {
|
||||
try {
|
||||
const res = (await browser.runtime.sendMessage({
|
||||
type: 'fetchThemeDetails',
|
||||
themeId: t.id,
|
||||
token,
|
||||
})) as { success?: boolean; data?: { theme?: { is_favorited?: boolean } } };
|
||||
const status: Record<string, boolean> = {};
|
||||
await Promise.all(
|
||||
themes.themes.map(async (t) => {
|
||||
try {
|
||||
const res = (await browser.runtime.sendMessage({
|
||||
type: 'fetchThemeDetails',
|
||||
themeId: t.id,
|
||||
})) as { success?: boolean; data?: { theme?: { is_favorited?: boolean } } };
|
||||
if (res?.success && res?.data?.theme) {
|
||||
status[t.id] = !!res.data.theme.is_favorited;
|
||||
}
|
||||
@@ -122,25 +121,32 @@
|
||||
})
|
||||
);
|
||||
favoriteStatus = status;
|
||||
}
|
||||
} else {
|
||||
favoriteStatus = {};
|
||||
}
|
||||
}
|
||||
|
||||
const openStorePage = async () => {
|
||||
const { OpenStorePage } = await import('@/seqta/ui/renderStore')
|
||||
OpenStorePage()
|
||||
}
|
||||
|
||||
const openThemeCreator = async (themeId?: string) => {
|
||||
const { OpenThemeCreator } = await import('@/plugins/built-in/themes/ThemeCreator')
|
||||
OpenThemeCreator(themeId)
|
||||
closeExtensionPopup()
|
||||
}
|
||||
|
||||
const handleToggleFavorite = async (theme: CustomTheme, e: MouseEvent) => {
|
||||
e.stopPropagation();
|
||||
if (!cloudLoggedIn) {
|
||||
showSignInModal = true;
|
||||
return;
|
||||
}
|
||||
const token = await cloudAuth.getStoredToken();
|
||||
if (!token) return;
|
||||
const isFavorite = !favoriteStatus[theme.id];
|
||||
const result = (await browser.runtime.sendMessage({
|
||||
type: 'cloudFavorite',
|
||||
themeId: theme.id,
|
||||
token,
|
||||
action: isFavorite ? 'favorite' : 'unfavorite',
|
||||
})) as { success?: boolean };
|
||||
if (result?.success) {
|
||||
@@ -216,8 +222,8 @@
|
||||
</div>
|
||||
<div
|
||||
class="absolute z-20 flex w-8 h-8 p-2 text-white transition-all rounded-full delay-[20ms] opacity-0 top-1/4 right-2 bg-black/50 place-items-center group-hover:opacity-100 group-hover:top-1/2 -translate-y-1/2"
|
||||
onclick={(event) => { event.stopPropagation(); OpenThemeCreator(theme.id); closeExtensionPopup() }}
|
||||
onkeydown={(event) => { if (event.key === 'Enter' || event.key === ' ') OpenThemeCreator(theme.id); closeExtensionPopup() }}
|
||||
onclick={(event) => { event.stopPropagation(); void openThemeCreator(theme.id) }}
|
||||
onkeydown={(event) => { if (event.key === 'Enter' || event.key === ' ') void openThemeCreator(theme.id) }}
|
||||
role="button"
|
||||
tabindex="-1"
|
||||
>
|
||||
@@ -237,8 +243,8 @@
|
||||
|
||||
<div class="relative top-0 z-10 flex justify-center w-full h-full overflow-hidden transition dark:text-white rounded-xl group place-items-center bg-zinc-100 dark:bg-zinc-900 { isEditMode ? 'animate-shake brightness-90' : ''}">
|
||||
{#if theme.coverImage}
|
||||
<img
|
||||
src={typeof theme.coverImage === 'string' ? theme.coverImage : URL.createObjectURL(theme.coverImage)}
|
||||
<ThemeBlobImage
|
||||
source={theme.coverImage}
|
||||
alt={theme.name}
|
||||
class="object-cover absolute inset-0 z-0 w-full h-full pointer-events-none"
|
||||
/>
|
||||
@@ -265,7 +271,7 @@
|
||||
{/if}
|
||||
|
||||
<button
|
||||
onclick={() => OpenStorePage()}
|
||||
onclick={() => void openStorePage()}
|
||||
class="flex justify-center items-center w-full rounded-xl transition aspect-theme bg-zinc-100 dark:bg-zinc-900 dark:text-white"
|
||||
>
|
||||
<span class="text-xl font-IconFamily"></span>
|
||||
@@ -273,7 +279,7 @@
|
||||
</button>
|
||||
|
||||
<button
|
||||
onclick={() => { OpenThemeCreator(); closeExtensionPopup() }}
|
||||
onclick={() => void openThemeCreator()}
|
||||
class="flex justify-center items-center w-full rounded-xl transition aspect-theme bg-zinc-100 dark:bg-zinc-900 dark:text-white"
|
||||
>
|
||||
<span class="text-xl font-IconFamily"></span>
|
||||
|
||||
@@ -1,21 +1,25 @@
|
||||
<script lang="ts">
|
||||
import React from "react";
|
||||
import ReactDOM from "react-dom";
|
||||
import { onDestroy, onMount } from "svelte";
|
||||
import { onDestroy } from "svelte";
|
||||
|
||||
const e = React.createElement;
|
||||
let container: HTMLDivElement;
|
||||
let adapterProps = $props();
|
||||
let container = $state<HTMLDivElement | null>(null);
|
||||
|
||||
onMount(() => {
|
||||
const { el, children, class: _, ...props } = $$props;
|
||||
$effect(() => {
|
||||
if (!container) return;
|
||||
|
||||
const { el, children, class: className, ...rest } = adapterProps;
|
||||
try {
|
||||
ReactDOM.render(e(el, props, children), container);
|
||||
ReactDOM.render(e(el, rest, children), container);
|
||||
} catch (err) {
|
||||
console.warn(`react-adapter failed to mount.`, { err });
|
||||
}
|
||||
});
|
||||
|
||||
onDestroy(() => {
|
||||
if (!container) return;
|
||||
try {
|
||||
ReactDOM.unmountComponentAtNode(container);
|
||||
} catch (err) {
|
||||
@@ -24,4 +28,4 @@
|
||||
});
|
||||
</script>
|
||||
|
||||
<div bind:this={container} class={$$props.class}></div>
|
||||
<div bind:this={container} class={adapterProps.class}></div>
|
||||
@@ -0,0 +1,21 @@
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
button {
|
||||
@apply cursor-pointer;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
|
||||
input {
|
||||
&:focus {
|
||||
box-shadow: unset !important;
|
||||
}
|
||||
}
|
||||
|
||||
.no-scrollbar {
|
||||
scrollbar-width: none !important;
|
||||
}
|
||||
@@ -1,149 +1,55 @@
|
||||
import { type DBSchema, type IDBPDatabase, openDB } from "idb";
|
||||
import localforage from "localforage";
|
||||
|
||||
/**
|
||||
* Defines the schema for the IndexedDB database used for storing background image data.
|
||||
*
|
||||
* @interface BackgroundDB
|
||||
* @extends {DBSchema}
|
||||
* @property {object} backgrounds - The object store for background images.
|
||||
* @property {string} backgrounds.key - The type of the key for the object store (in this case, it's `id` as defined in `keyPath`).
|
||||
* @property {object} backgrounds.value - The structure of the objects stored.
|
||||
* @property {string} backgrounds.value.id - The unique identifier for the background image record.
|
||||
* @property {string} backgrounds.value.type - The MIME type of the image (e.g., "image/png", "image/jpeg").
|
||||
* @property {Blob} backgrounds.value.blob - The binary large object (Blob) containing the image data.
|
||||
*/
|
||||
interface BackgroundDB extends DBSchema {
|
||||
backgrounds: {
|
||||
key: string; // Corresponds to the 'id' property due to keyPath: "id"
|
||||
value: {
|
||||
id: string;
|
||||
type: string;
|
||||
blob: Blob;
|
||||
};
|
||||
};
|
||||
type BackgroundRecord = { id: string; type: string; blob: Blob };
|
||||
|
||||
const store = localforage.createInstance({
|
||||
name: "BackgroundDB",
|
||||
storeName: "backgrounds",
|
||||
});
|
||||
|
||||
export async function openDatabase(): Promise<typeof store> {
|
||||
await store.ready();
|
||||
return store;
|
||||
}
|
||||
|
||||
let db: IDBPDatabase<BackgroundDB> | null = null;
|
||||
|
||||
/**
|
||||
* Initializes and opens an IndexedDB connection or returns an existing one.
|
||||
* If the database doesn't exist or needs an upgrade, the `upgrade` callback
|
||||
* creates the 'backgrounds' object store with 'id' as the keyPath.
|
||||
*
|
||||
* @async
|
||||
* @returns {Promise<IDBPDatabase<BackgroundDB>>} A promise that resolves with the database instance.
|
||||
*/
|
||||
export async function openDatabase(): Promise<IDBPDatabase<BackgroundDB>> {
|
||||
if (db) return db;
|
||||
|
||||
db = await openDB<BackgroundDB>("BackgroundDB", 1, {
|
||||
upgrade(db: IDBPDatabase<BackgroundDB>) {
|
||||
db.createObjectStore("backgrounds", { keyPath: "id" });
|
||||
},
|
||||
export async function readAllData(): Promise<BackgroundRecord[]> {
|
||||
await store.ready();
|
||||
const items: BackgroundRecord[] = [];
|
||||
await store.iterate<BackgroundRecord, void>((value) => {
|
||||
if (value?.id && value.blob) items.push(value);
|
||||
});
|
||||
|
||||
return db;
|
||||
return items;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves all background image records from the 'backgrounds' object store in IndexedDB.
|
||||
*
|
||||
* @async
|
||||
* @returns {Promise<Array<{id: string, type: string, blob: Blob}>>} A promise that resolves with an array of all background image records.
|
||||
*/
|
||||
export async function readAllData(): Promise<
|
||||
Array<{ id: string; type: string; blob: Blob }>
|
||||
> {
|
||||
const db = await openDatabase();
|
||||
return db.getAll("backgrounds");
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes or updates a background image record in the 'backgrounds' object store.
|
||||
* If a record with the given `id` already exists, it will be updated. Otherwise, a new record is created.
|
||||
*
|
||||
* @async
|
||||
* @param {string} id - The unique identifier for the background image record.
|
||||
* @param {string} type - The MIME type of the image (e.g., "image/png").
|
||||
* @param {Blob} blob - The Blob object containing the image data.
|
||||
* @returns {Promise<void>} A promise that resolves when the data has been successfully written.
|
||||
*/
|
||||
export async function writeData(
|
||||
id: string,
|
||||
type: string,
|
||||
blob: Blob,
|
||||
): Promise<void> {
|
||||
const db = await openDatabase();
|
||||
await db.put("backgrounds", { id, type, blob });
|
||||
await store.setItem(id, { id, type, blob });
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a background image record from the 'backgrounds' object store by its ID.
|
||||
*
|
||||
* @async
|
||||
* @param {string} id - The unique identifier of the background image record to delete.
|
||||
* @returns {Promise<void>} A promise that resolves when the data has been successfully deleted.
|
||||
*/
|
||||
export async function deleteData(id: string): Promise<void> {
|
||||
const db = await openDatabase();
|
||||
await db.delete("backgrounds", id);
|
||||
await store.removeItem(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears all records from the 'backgrounds' object store in IndexedDB.
|
||||
*
|
||||
* @async
|
||||
* @returns {Promise<void>} A promise that resolves when all data has been successfully cleared.
|
||||
*/
|
||||
export async function clearAllData(): Promise<void> {
|
||||
const db = await openDatabase();
|
||||
await db.clear("backgrounds");
|
||||
await store.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves a single background image record from the 'backgrounds' object store by its ID.
|
||||
*
|
||||
* @async
|
||||
* @param {string} id - The unique identifier of the background image record to retrieve.
|
||||
* @returns {Promise<{id: string, type: string, blob: Blob} | undefined>} A promise that resolves with the
|
||||
* background image record if found, or undefined otherwise.
|
||||
*/
|
||||
export async function getDataById(
|
||||
id: string,
|
||||
): Promise<{ id: string; type: string; blob: Blob } | undefined> {
|
||||
const db = await openDatabase();
|
||||
return db.get("backgrounds", id);
|
||||
): Promise<BackgroundRecord | undefined> {
|
||||
const item = await store.getItem<BackgroundRecord>(id);
|
||||
return item ?? undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes the active IndexedDB connection and nullifies the global `db` variable.
|
||||
* This is important to release resources and allow for proper database management.
|
||||
*/
|
||||
export function closeDatabase(): void {
|
||||
if (db) {
|
||||
db.close();
|
||||
db = null;
|
||||
}
|
||||
}
|
||||
export function closeDatabase(): void {}
|
||||
|
||||
/**
|
||||
* Checks if IndexedDB is supported by the current browser environment.
|
||||
*
|
||||
* @returns {boolean} True if IndexedDB is supported, false otherwise.
|
||||
*/
|
||||
export function isIndexedDBSupported(): boolean {
|
||||
return "indexedDB" in window;
|
||||
}
|
||||
|
||||
/**
|
||||
* Estimates available storage space and checks if it's sufficient for the specified `requiredSpace`.
|
||||
* Uses the `navigator.storage.estimate()` API if available.
|
||||
* If the API is not available or cannot determine space, it defaults to assuming enough space is available.
|
||||
*
|
||||
* @async
|
||||
* @param {number} requiredSpace - The amount of storage space required, in bytes.
|
||||
* @returns {Promise<boolean>} A promise that resolves with true if enough space is estimated to be available, false otherwise.
|
||||
*/
|
||||
export async function hasEnoughStorageSpace(
|
||||
requiredSpace: number,
|
||||
): Promise<boolean> {
|
||||
@@ -153,6 +59,5 @@ export async function hasEnoughStorageSpace(
|
||||
return quota - usage > requiredSpace;
|
||||
}
|
||||
}
|
||||
// If we can't determine, assume there's enough space
|
||||
return true;
|
||||
}
|
||||
@@ -1,53 +1 @@
|
||||
type SettingsPopupCallback = () => void;
|
||||
|
||||
/**
|
||||
* This is a singleton that triggers an update when the settings popup is closed.
|
||||
* This is used to close the colour picker.
|
||||
* Usage:
|
||||
* settingsPopup.addListener(() => {
|
||||
* console.log('Settings popup closed');
|
||||
* });
|
||||
*/
|
||||
class SettingsPopup {
|
||||
private static instance: SettingsPopup;
|
||||
private listeners: Set<SettingsPopupCallback> = new Set();
|
||||
|
||||
private constructor() {}
|
||||
|
||||
public static getInstance(): SettingsPopup {
|
||||
if (!SettingsPopup.instance) {
|
||||
SettingsPopup.instance = new SettingsPopup();
|
||||
}
|
||||
return SettingsPopup.instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a callback function to be invoked when the settings popup is closed.
|
||||
*
|
||||
* @param {SettingsPopupCallback} callback The function to call when the settings popup closes.
|
||||
* This callback takes no arguments and returns void.
|
||||
*/
|
||||
public addListener(callback: SettingsPopupCallback): void {
|
||||
this.listeners.add(callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Unregisters a previously added callback function.
|
||||
* After calling this method, the provided callback will no longer be invoked when the settings popup closes.
|
||||
*
|
||||
* @param {SettingsPopupCallback} callback The callback function to remove from the listeners.
|
||||
*/
|
||||
public removeListener(callback: SettingsPopupCallback): void {
|
||||
this.listeners.delete(callback);
|
||||
}
|
||||
|
||||
/**
|
||||
* Invokes all registered listener callbacks.
|
||||
* This method should be called when the settings popup is closed to notify all subscribed components or services.
|
||||
*/
|
||||
public triggerClose(): void {
|
||||
this.listeners.forEach((callback) => callback());
|
||||
}
|
||||
}
|
||||
|
||||
export const settingsPopup = SettingsPopup.getInstance();
|
||||
export { settingsPopup } from "@/seqta/utils/settingsPopup";
|
||||
@@ -2,18 +2,20 @@ import "./index.css";
|
||||
import Settings from "./pages/settings.svelte";
|
||||
import IconFamily from "@/resources/fonts/IconFamily.woff";
|
||||
import browser from "webextension-polyfill";
|
||||
import { resolveExtensionAssetUrl } from "@/lib/extensionAssetUrl";
|
||||
import renderSvelte from "./main";
|
||||
import { initializeSettingsState } from "@/seqta/utils/listeners/SettingsState";
|
||||
import { initVerboseLogging, verboseInfo } from "@/utils/verboseLog";
|
||||
|
||||
function InjectCustomIcons() {
|
||||
console.info("[BetterSEQTA+] Injecting Icons");
|
||||
verboseInfo("[BetterSEQTA+] Injecting Icons");
|
||||
|
||||
const style = document.createElement("style");
|
||||
style.setAttribute("type", "text/css");
|
||||
style.innerHTML = `
|
||||
@font-face {
|
||||
font-family: 'IconFamily';
|
||||
src: url('${browser.runtime.getURL(IconFamily)}') format('woff');
|
||||
src: url('${resolveExtensionAssetUrl(IconFamily)}') format('woff');
|
||||
font-weight: normal;
|
||||
font-style: normal;
|
||||
}`;
|
||||
@@ -30,5 +32,6 @@ InjectCustomIcons();
|
||||
|
||||
(async () => {
|
||||
await initializeSettingsState();
|
||||
initVerboseLogging();
|
||||
renderSvelte(Settings, mountPoint, { standalone: true });
|
||||
})();
|
||||
Vendored
-2
@@ -1,5 +1,3 @@
|
||||
import "./index.css";
|
||||
|
||||
declare module "*.png";
|
||||
declare module "*.svg";
|
||||
declare module "*.jpeg";
|
||||
|
||||
+11
-2
@@ -1,11 +1,20 @@
|
||||
import { mount } from "svelte";
|
||||
import type { SvelteComponent } from "svelte";
|
||||
import style from "./index.css?inline";
|
||||
import settingsStyle from "./index.css?inline";
|
||||
import contentShadowStyle from "./contentShadow.css?inline";
|
||||
|
||||
const shadowStyles = {
|
||||
settings: settingsStyle,
|
||||
content: contentShadowStyle,
|
||||
} as const;
|
||||
|
||||
export type ShadowStyleVariant = keyof typeof shadowStyles;
|
||||
|
||||
export default function renderSvelte(
|
||||
Component: SvelteComponent | any,
|
||||
mountPoint: ShadowRoot | HTMLElement,
|
||||
props: Record<string, any> = {},
|
||||
shadowStyle: ShadowStyleVariant = "settings",
|
||||
) {
|
||||
const app = mount(Component, {
|
||||
target: mountPoint,
|
||||
@@ -17,7 +26,7 @@ export default function renderSvelte(
|
||||
|
||||
if (mountPoint instanceof ShadowRoot) {
|
||||
const styleElement = document.createElement("style");
|
||||
styleElement.textContent = style;
|
||||
styleElement.textContent = shadowStyles[shadowStyle];
|
||||
mountPoint.appendChild(styleElement);
|
||||
}
|
||||
|
||||
|
||||
@@ -6,19 +6,18 @@
|
||||
import browser from "webextension-polyfill";
|
||||
|
||||
import { standalone as StandaloneStore } from "../utils/standalone.svelte";
|
||||
import { onMount } from "svelte";
|
||||
import { onMount, onDestroy } from "svelte";
|
||||
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
|
||||
|
||||
import { closeExtensionPopup } from "@/seqta/utils/Closers/closeExtensionPopup";
|
||||
import { OpenAboutPage } from "@/seqta/utils/Openers/OpenAboutPage";
|
||||
import { OpenWhatsNewPopup } from "@/seqta/utils/Openers/OpenWhatsNewPopup";
|
||||
//import { OpenMinecraftServerPopup } from "@/seqta/utils/Openers/OpenMinecraftServerPopup";
|
||||
|
||||
import ColourPicker from "../components/ColourPicker.svelte";
|
||||
import type { Component } from "svelte";
|
||||
import FontPickerModal from "../components/FontPickerModal.svelte";
|
||||
import CloudPanel from "../components/CloudPanel.svelte";
|
||||
import DisclaimerModal from "../components/DisclaimerModal.svelte";
|
||||
import { settingsPopup } from "../hooks/SettingsPopup";
|
||||
import { settingsPopup } from "@/seqta/utils/settingsPopup";
|
||||
import {
|
||||
checkGithubReleaseUpdate,
|
||||
dismissNightlyUpdate,
|
||||
@@ -64,7 +63,12 @@
|
||||
}, 10000);
|
||||
};
|
||||
|
||||
const openColourPicker = () => {
|
||||
let ColourPickerComponent = $state<Component | null>(null);
|
||||
|
||||
const openColourPicker = async () => {
|
||||
if (!ColourPickerComponent) {
|
||||
ColourPickerComponent = (await import("../components/ColourPicker.svelte")).default;
|
||||
}
|
||||
showColourPicker = true;
|
||||
};
|
||||
|
||||
@@ -82,11 +86,6 @@
|
||||
closeExtensionPopup();
|
||||
};
|
||||
|
||||
/* const openMinecraftServer = () => {
|
||||
OpenMinecraftServerPopup();
|
||||
closeExtensionPopup();
|
||||
}; */
|
||||
|
||||
const openPrivacyStatement = () => {
|
||||
window.open("https://betterseqta.org/privacy", "_blank");
|
||||
closeExtensionPopup();
|
||||
@@ -101,19 +100,26 @@
|
||||
showCloudPanel = true;
|
||||
};
|
||||
|
||||
const showDisclaimer = (onConfirm: () => void, onCancel: () => void, title?: string, message?: string) => {
|
||||
const showDisclaimer = (
|
||||
onConfirm: () => void,
|
||||
onCancel: () => void,
|
||||
title = "Confirm",
|
||||
message = "",
|
||||
) => {
|
||||
disclaimerCallbacks = { onConfirm, onCancel };
|
||||
disclaimerTitle = title ?? "Confirm";
|
||||
disclaimerMessage = message ?? "";
|
||||
disclaimerTitle = title;
|
||||
disclaimerMessage = message;
|
||||
showDisclaimerModal = true;
|
||||
};
|
||||
|
||||
const closePopupsOnSettingsClose = () => {
|
||||
showColourPicker = false;
|
||||
showFontPicker = false;
|
||||
showCloudPanel = false;
|
||||
};
|
||||
|
||||
onMount(() => {
|
||||
settingsPopup.addListener(() => {
|
||||
showColourPicker = false;
|
||||
showFontPicker = false;
|
||||
showCloudPanel = false;
|
||||
});
|
||||
settingsPopup.addListener(closePopupsOnSettingsClose);
|
||||
|
||||
if (standalone) {
|
||||
StandaloneStore.setStandalone(true);
|
||||
@@ -125,6 +131,10 @@
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
onDestroy(() => {
|
||||
settingsPopup.removeListener(closePopupsOnSettingsClose);
|
||||
});
|
||||
</script>
|
||||
|
||||
<div
|
||||
@@ -133,10 +143,10 @@
|
||||
: ''} {standalone ? 'h-[600px]' : 'h-full rounded-xl'} overflow-clip"
|
||||
>
|
||||
<div
|
||||
class="flex relative flex-col gap-2 h-full overflow-clip bg-white dark:bg-zinc-800 dark:text-white"
|
||||
class="flex relative flex-col gap-2 h-full min-h-0 overflow-hidden bg-white dark:bg-zinc-800 dark:text-white"
|
||||
>
|
||||
<div
|
||||
class="grid place-items-center border-b border-b-zinc-200/40 dark:border-b-zinc-700/40"
|
||||
class="grid shrink-0 place-items-center border-b border-b-zinc-200/40 dark:border-b-zinc-700/40"
|
||||
>
|
||||
<!-- svelte-ignore a11y_no_noninteractive_element_interactions -->
|
||||
<!-- svelte-ignore a11y_click_events_have_key_events -->
|
||||
@@ -205,160 +215,28 @@
|
||||
{"\uecba"}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- <button
|
||||
onclick={openMinecraftServer}
|
||||
class="flex justify-center items-center p-1 w-8 h-8 rounded-xl bg-zinc-100 dark:bg-zinc-700"
|
||||
aria-label="Open Minecraft Server"
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 64 70"
|
||||
fill="none"
|
||||
class="w-full h-full"
|
||||
>
|
||||
<path
|
||||
d="M0 0 C3.96 0 7.92 0 12 0 C12 3.96 12 7.92 12 12 C10.68 12 9.36 12 8 12 C8 10.68 8 9.36 8 8 C6.68 8 5.36 8 4 8 C4 6.68 4 5.36 4 4 C2.68 4 1.36 4 0 4 C0 2.68 0 1.36 0 0 Z "
|
||||
fill="currentColor"
|
||||
transform="translate(42,10)"
|
||||
/>
|
||||
<path
|
||||
d="M0 0 C1.32 0 2.64 0 4 0 C4 6.6 4 13.2 4 20 C2.68 20 1.36 20 0 20 C0 13.4 0 6.8 0 0 Z "
|
||||
fill="currentColor"
|
||||
transform="translate(54,22)"
|
||||
/>
|
||||
<path
|
||||
d="M0 0 C6.6 0 13.2 0 20 0 C20 1.32 20 2.64 20 4 C13.4 4 6.8 4 0 4 C0 2.68 0 1.36 0 0 Z "
|
||||
fill="currentColor"
|
||||
transform="translate(22,6)"
|
||||
/>
|
||||
<path
|
||||
d="M0 0 C1.32 0 2.64 0 4 0 C4 5.28 4 10.56 4 16 C2.68 16 1.36 16 0 16 C0 10.72 0 5.44 0 0 Z "
|
||||
fill="currentColor"
|
||||
transform="translate(46,26)"
|
||||
/>
|
||||
<path
|
||||
d="M0 0 C5.28 0 10.56 0 16 0 C16 1.32 16 2.64 16 4 C10.72 4 5.44 4 0 4 C0 2.68 0 1.36 0 0 Z "
|
||||
fill="currentColor"
|
||||
transform="translate(22,14)"
|
||||
/>
|
||||
<path
|
||||
d="M0 0 C1.32 0 2.64 0 4 0 C4 1.32 4 2.64 4 4 C5.32 4 6.64 4 8 4 C8 5.32 8 6.64 8 8 C5.36 8 2.72 8 0 8 C0 5.36 0 2.72 0 0 Z "
|
||||
fill="currentColor"
|
||||
transform="translate(6,50)"
|
||||
/>
|
||||
<path
|
||||
d="M0 0 C1.32 0 2.64 0 4 0 C4 1.32 4 2.64 4 4 C2.68 4 1.36 4 0 4 C0 2.68 0 1.36 0 0 Z "
|
||||
fill="currentColor"
|
||||
transform="translate(14,50)"
|
||||
/>
|
||||
<path
|
||||
d="M0 0 C1.32 0 2.64 0 4 0 C4 1.32 4 2.64 4 4 C2.68 4 1.36 4 0 4 C0 2.68 0 1.36 0 0 Z "
|
||||
fill="currentColor"
|
||||
transform="translate(18,46)"
|
||||
/>
|
||||
<path
|
||||
d="M0 0 C1.32 0 2.64 0 4 0 C4 1.32 4 2.64 4 4 C2.68 4 1.36 4 0 4 C0 2.68 0 1.36 0 0 Z "
|
||||
fill="currentColor"
|
||||
transform="translate(10,46)"
|
||||
/>
|
||||
<path
|
||||
d="M0 0 C1.32 0 2.64 0 4 0 C4 1.32 4 2.64 4 4 C2.68 4 1.36 4 0 4 C0 2.68 0 1.36 0 0 Z "
|
||||
fill="currentColor"
|
||||
transform="translate(50,42)"
|
||||
/>
|
||||
<path
|
||||
d="M0 0 C1.32 0 2.64 0 4 0 C4 1.32 4 2.64 4 4 C2.68 4 1.36 4 0 4 C0 2.68 0 1.36 0 0 Z "
|
||||
fill="currentColor"
|
||||
transform="translate(22,42)"
|
||||
/>
|
||||
<path
|
||||
d="M0 0 C1.32 0 2.64 0 4 0 C4 1.32 4 2.64 4 4 C2.68 4 1.36 4 0 4 C0 2.68 0 1.36 0 0 Z "
|
||||
fill="currentColor"
|
||||
transform="translate(14,42)"
|
||||
/>
|
||||
<path
|
||||
d="M0 0 C1.32 0 2.64 0 4 0 C4 1.32 4 2.64 4 4 C2.68 4 1.36 4 0 4 C0 2.68 0 1.36 0 0 Z "
|
||||
fill="currentColor"
|
||||
transform="translate(26,38)"
|
||||
/>
|
||||
<path
|
||||
d="M0 0 C1.32 0 2.64 0 4 0 C4 1.32 4 2.64 4 4 C2.68 4 1.36 4 0 4 C0 2.68 0 1.36 0 0 Z "
|
||||
fill="currentColor"
|
||||
transform="translate(18,38)"
|
||||
/>
|
||||
<path
|
||||
d="M0 0 C1.32 0 2.64 0 4 0 C4 1.32 4 2.64 4 4 C2.68 4 1.36 4 0 4 C0 2.68 0 1.36 0 0 Z "
|
||||
fill="currentColor"
|
||||
transform="translate(30,34)"
|
||||
/>
|
||||
<path
|
||||
d="M0 0 C1.32 0 2.64 0 4 0 C4 1.32 4 2.64 4 4 C2.68 4 1.36 4 0 4 C0 2.68 0 1.36 0 0 Z "
|
||||
fill="currentColor"
|
||||
transform="translate(22,34)"
|
||||
/>
|
||||
<path
|
||||
d="M0 0 C1.32 0 2.64 0 4 0 C4 1.32 4 2.64 4 4 C2.68 4 1.36 4 0 4 C0 2.68 0 1.36 0 0 Z "
|
||||
fill="currentColor"
|
||||
transform="translate(34,30)"
|
||||
/>
|
||||
<path
|
||||
d="M0 0 C1.32 0 2.64 0 4 0 C4 1.32 4 2.64 4 4 C2.68 4 1.36 4 0 4 C0 2.68 0 1.36 0 0 Z "
|
||||
fill="currentColor"
|
||||
transform="translate(26,30)"
|
||||
/>
|
||||
<path
|
||||
d="M0 0 C1.32 0 2.64 0 4 0 C4 1.32 4 2.64 4 4 C2.68 4 1.36 4 0 4 C0 2.68 0 1.36 0 0 Z "
|
||||
fill="currentColor"
|
||||
transform="translate(38,26)"
|
||||
/>
|
||||
<path
|
||||
d="M0 0 C1.32 0 2.64 0 4 0 C4 1.32 4 2.64 4 4 C2.68 4 1.36 4 0 4 C0 2.68 0 1.36 0 0 Z "
|
||||
fill="currentColor"
|
||||
transform="translate(30,26)"
|
||||
/>
|
||||
<path
|
||||
d="M0 0 C1.32 0 2.64 0 4 0 C4 1.32 4 2.64 4 4 C2.68 4 1.36 4 0 4 C0 2.68 0 1.36 0 0 Z "
|
||||
fill="currentColor"
|
||||
transform="translate(42,22)"
|
||||
/>
|
||||
<path
|
||||
d="M0 0 C1.32 0 2.64 0 4 0 C4 1.32 4 2.64 4 4 C2.68 4 1.36 4 0 4 C0 2.68 0 1.36 0 0 Z "
|
||||
fill="currentColor"
|
||||
transform="translate(34,22)"
|
||||
/>
|
||||
<path
|
||||
d="M0 0 C1.32 0 2.64 0 4 0 C4 1.32 4 2.64 4 4 C2.68 4 1.36 4 0 4 C0 2.68 0 1.36 0 0 Z "
|
||||
fill="currentColor"
|
||||
transform="translate(38,18)"
|
||||
/>
|
||||
<path
|
||||
d="M0 0 C1.32 0 2.64 0 4 0 C4 1.32 4 2.64 4 4 C2.68 4 1.36 4 0 4 C0 2.68 0 1.36 0 0 Z "
|
||||
fill="currentColor"
|
||||
transform="translate(18,10)"
|
||||
/>
|
||||
</svg>
|
||||
</button> -->
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<TabbedContainer
|
||||
bind:activeTab={settingsActiveTab}
|
||||
tabs={[
|
||||
{
|
||||
title: "Settings",
|
||||
Content: Settings,
|
||||
props: { showColourPicker: openColourPicker, showFontPicker: openFontPicker, showDisclaimer, showCloudPanel: openCloudPanel },
|
||||
},
|
||||
{ title: "Shortcuts", Content: Shortcuts },
|
||||
{ title: "Themes", Content: Theme },
|
||||
]}
|
||||
/>
|
||||
<div class="flex-1 min-h-0 overflow-hidden">
|
||||
<TabbedContainer
|
||||
bind:activeTab={settingsActiveTab}
|
||||
tabs={[
|
||||
{
|
||||
title: "Settings",
|
||||
Content: Settings,
|
||||
props: { showColourPicker: openColourPicker, showFontPicker: openFontPicker, showDisclaimer, showCloudPanel: openCloudPanel },
|
||||
},
|
||||
{ title: "Shortcuts", Content: Shortcuts },
|
||||
{ title: "Themes", Content: Theme },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{#if showColourPicker}
|
||||
<ColourPicker
|
||||
{#if showColourPicker && ColourPickerComponent}
|
||||
<ColourPickerComponent
|
||||
hidePicker={() => {
|
||||
showColourPicker = false;
|
||||
}}
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
import { closeExtensionPopup } from "@/seqta/utils/Closers/closeExtensionPopup"
|
||||
import { getSnapshotForUpload } from "@/seqta/utils/cloudSettingsSync"
|
||||
import { getStoredOverride, setApiBase } from "@/seqta/utils/DevApiBase"
|
||||
import { onMount } from "svelte"
|
||||
|
||||
let devApiBaseInput = $state<string>(getStoredOverride() ?? "")
|
||||
let devApiBaseActive = $state<string | null>(getStoredOverride())
|
||||
@@ -128,9 +129,9 @@
|
||||
await browser.storage.local.set({ [storageKey]: currentSettings });
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
loadPluginSettings();
|
||||
})
|
||||
onMount(() => {
|
||||
void loadPluginSettings();
|
||||
});
|
||||
|
||||
const { showColourPicker, showFontPicker, showDisclaimer, showCloudPanel } = $props<{
|
||||
showColourPicker: () => void;
|
||||
@@ -249,7 +250,7 @@
|
||||
id: 10,
|
||||
Component: Select,
|
||||
props: {
|
||||
state: $settingsState.defaultPage ?? "home",
|
||||
value: $settingsState.defaultPage ?? "home",
|
||||
onChange: (value: string) => (settingsState.defaultPage = value),
|
||||
options: [
|
||||
{ value: "home", label: "Home" },
|
||||
@@ -268,7 +269,7 @@
|
||||
id: 11,
|
||||
Component: Select,
|
||||
props: {
|
||||
state: $settingsState.newsSource,
|
||||
value: $settingsState.newsSource,
|
||||
onChange: (value: string) => settingsState.newsSource = value,
|
||||
options: [
|
||||
{ value: "australia", label: "Australia" },
|
||||
@@ -289,6 +290,65 @@
|
||||
{@render Setting(option)}
|
||||
{/each}
|
||||
|
||||
<div class="border-none">
|
||||
<div class="p-1 my-1 from-white to-zinc-100 bg-gradient-to-br rounded-xl border shadow-sm border-zinc-200/50 dark:border-zinc-700/40 dark:to-zinc-900/50 dark:from-zinc-900/40">
|
||||
<div class="flex justify-between items-center px-4 py-3">
|
||||
<div class="pr-4">
|
||||
<h2 class="text-sm font-bold">Home Page Assessments</h2>
|
||||
<p class="text-xs">Limit upcoming assessments shown on the home page by subject</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex justify-between items-center px-4 py-3 pl-6 border-t border-zinc-100 dark:border-zinc-700/50">
|
||||
<div class="pr-4">
|
||||
<h2 class="text-sm font-bold">Include Past Assessments</h2>
|
||||
<p class="text-xs">Show past-due assessments from the upcoming list, matching the Assessments page</p>
|
||||
</div>
|
||||
<div>
|
||||
<Switch
|
||||
state={$settingsState.homeUpcomingIncludePast ?? true}
|
||||
onChange={(isOn: boolean) => (settingsState.homeUpcomingIncludePast = isOn)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex justify-between items-center px-4 py-3 pl-6 border-t border-zinc-100 dark:border-zinc-700/50">
|
||||
<div class="pr-4">
|
||||
<h2 class="text-sm font-bold">Maximum Subjects</h2>
|
||||
<p class="text-xs">Number of subjects to include, ordered by soonest due date</p>
|
||||
</div>
|
||||
<Select
|
||||
value={String($settingsState.homeUpcomingSubjectsMax ?? 5)}
|
||||
onChange={(value: string) => (settingsState.homeUpcomingSubjectsMax = Number(value))}
|
||||
options={[
|
||||
{ value: "0", label: "All" },
|
||||
{ value: "3", label: "3" },
|
||||
{ value: "5", label: "5" },
|
||||
{ value: "7", label: "7" },
|
||||
{ value: "10", label: "10" },
|
||||
{ value: "15", label: "15" },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
<div class="flex justify-between items-center px-4 py-3 pl-6 border-t border-zinc-100 dark:border-zinc-700/50">
|
||||
<div class="pr-4">
|
||||
<h2 class="text-sm font-bold">Maximum Assessments per Subject</h2>
|
||||
<p class="text-xs">Assessments shown for each included subject</p>
|
||||
</div>
|
||||
<Select
|
||||
value={String($settingsState.homeUpcomingAssessmentsPerSubjectMax ?? 0)}
|
||||
onChange={(value: string) => (settingsState.homeUpcomingAssessmentsPerSubjectMax = Number(value))}
|
||||
options={[
|
||||
{ value: "0", label: "All" },
|
||||
{ value: "1", label: "1" },
|
||||
{ value: "2", label: "2" },
|
||||
{ value: "3", label: "3" },
|
||||
{ value: "5", label: "5" },
|
||||
{ value: "10", label: "10" },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="border-none">
|
||||
<div class="p-1 my-1 from-white to-zinc-100 bg-gradient-to-br rounded-xl border shadow-sm border-zinc-200/50 dark:border-zinc-700/40 dark:to-zinc-900/50 dark:from-zinc-900/40">
|
||||
<div class="flex justify-between items-center px-4 py-3">
|
||||
@@ -405,7 +465,7 @@
|
||||
/>
|
||||
{:else if setting.type === 'select'}
|
||||
<Select
|
||||
state={pluginSettingsValues[plugin.pluginId]?.[key] ?? setting.default}
|
||||
value={pluginSettingsValues[plugin.pluginId]?.[key] ?? setting.default}
|
||||
onChange={(value) => updatePluginSetting(plugin.pluginId, key, value)}
|
||||
options={(setting.options as string[]).map(opt => ({
|
||||
value: opt,
|
||||
@@ -492,6 +552,18 @@
|
||||
<Switch state={$settingsState.devMode} onChange={(isOn: boolean) => settingsState.devMode = isOn} />
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex justify-between items-center px-4 py-3">
|
||||
<div class="pr-4">
|
||||
<h2 class="text-sm font-bold">Verbose logging</h2>
|
||||
<p class="text-xs">Show diagnostic console output (indexer, theme manager, timetable colour patch, etc.)</p>
|
||||
</div>
|
||||
<div>
|
||||
<Switch
|
||||
state={$settingsState.verboseLogging ?? false}
|
||||
onChange={(isOn: boolean) => settingsState.verboseLogging = isOn}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex justify-between items-center px-4 py-3">
|
||||
<div class="pr-4">
|
||||
<h2 class="text-sm font-bold">Sensitive Hider</h2>
|
||||
|
||||
@@ -23,7 +23,10 @@
|
||||
const themeManager = ThemeManager.getInstance();
|
||||
let cloudLoggedIn = $state(cloudAuth.state.isLoggedIn);
|
||||
|
||||
cloudAuth.subscribe((s) => { cloudLoggedIn = s.isLoggedIn; });
|
||||
$effect(() => {
|
||||
const unsub = cloudAuth.subscribe((s) => { cloudLoggedIn = s.isLoggedIn; });
|
||||
return unsub;
|
||||
});
|
||||
|
||||
// State variables
|
||||
let searchTerm = $state('');
|
||||
@@ -86,13 +89,11 @@
|
||||
}
|
||||
|
||||
const toggleFavorite = async (theme: Theme) => {
|
||||
const token = await cloudAuth.getStoredToken();
|
||||
if (!token) return;
|
||||
if (!cloudLoggedIn) return;
|
||||
const isFavorite = !theme.is_favorited;
|
||||
const result = (await browser.runtime.sendMessage({
|
||||
type: 'cloudFavorite',
|
||||
themeId: theme.id,
|
||||
token,
|
||||
action: isFavorite ? 'favorite' : 'unfavorite',
|
||||
})) as { success?: boolean };
|
||||
if (result?.success) {
|
||||
@@ -119,14 +120,12 @@
|
||||
error = null;
|
||||
}
|
||||
try {
|
||||
const token = await cloudAuth.getStoredToken();
|
||||
const data = await sendMessageWithTimeout<{
|
||||
success?: boolean;
|
||||
data?: { themes: unknown[] };
|
||||
error?: string;
|
||||
}>({
|
||||
type: 'fetchThemes',
|
||||
token: token ?? undefined,
|
||||
});
|
||||
if (!data?.success || !Array.isArray(data?.data?.themes)) {
|
||||
throw new Error(data?.error || 'Failed to fetch themes');
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
<script lang="ts">
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
import { onMount } from 'svelte';
|
||||
import { slide } from 'svelte/transition';
|
||||
import { fade } from 'svelte/transition';
|
||||
@@ -27,12 +26,15 @@
|
||||
import { ThemeManager } from '@/plugins/built-in/themes/theme-manager'
|
||||
import { themeUpdates } from '../hooks/ThemeUpdates'
|
||||
import { CloseThemeCreator } from '@/plugins/built-in/themes/ThemeCreator'
|
||||
import ThemeBlobImage from '@/interface/components/themes/ThemeBlobImage.svelte'
|
||||
import LucideMoon from '@/interface/components/icons/LucideMoon.svelte'
|
||||
import LucideSun from '@/interface/components/icons/LucideSun.svelte'
|
||||
|
||||
const { themeID } = $props<{ themeID: string }>()
|
||||
const themeManager = ThemeManager.getInstance();
|
||||
|
||||
let theme = $state<LoadedCustomTheme>({
|
||||
id: uuidv4(),
|
||||
id: crypto.randomUUID(),
|
||||
name: '',
|
||||
description: '',
|
||||
defaultColour: 'blue',
|
||||
@@ -73,26 +75,17 @@
|
||||
await themeManager.disableTheme();
|
||||
|
||||
if (themeID) {
|
||||
const tempTheme = await themeManager.getTheme(themeID)
|
||||
|
||||
if (!tempTheme) return
|
||||
|
||||
// convert temptheme to LoadedCustomTheme
|
||||
const loadedTheme = {
|
||||
...tempTheme,
|
||||
CustomImages: tempTheme.CustomImages.map(image => ({
|
||||
...image
|
||||
}))
|
||||
}
|
||||
const tempTheme = await themeManager.getTheme(themeID);
|
||||
if (!tempTheme) return;
|
||||
|
||||
theme = {
|
||||
...loadedTheme,
|
||||
adaptiveCssVariables: loadedTheme.adaptiveCssVariables ?? [],
|
||||
...tempTheme,
|
||||
adaptiveCssVariables: tempTheme.adaptiveCssVariables ?? [],
|
||||
forceTheme:
|
||||
loadedTheme.forceTheme ??
|
||||
(loadedTheme.forceDark !== undefined ? true : undefined),
|
||||
}
|
||||
themeLoaded = true
|
||||
tempTheme.forceTheme ??
|
||||
(tempTheme.forceDark !== undefined ? true : undefined),
|
||||
};
|
||||
themeLoaded = true;
|
||||
} else {
|
||||
themeLoaded = true
|
||||
}
|
||||
@@ -230,7 +223,7 @@
|
||||
{#each theme.CustomImages as image (image.id)}
|
||||
<div class="flex gap-2 items-center px-2 py-2 mb-4 h-16 bg-white rounded-lg shadow-lg dark:bg-zinc-700">
|
||||
<div class="h-full">
|
||||
<img src={URL.createObjectURL(image.blob)} alt={image.variableName} class="object-contain h-full rounded" />
|
||||
<ThemeBlobImage source={image.blob} alt={image.variableName} class="object-contain h-full rounded" />
|
||||
</div>
|
||||
<input
|
||||
type="text"
|
||||
@@ -252,19 +245,23 @@
|
||||
</div>
|
||||
{:else if item.type === 'lightDarkToggle'}
|
||||
<button
|
||||
class="overflow-hidden relative px-4 py-1 text-xl font-medium rounded-lg transition bg-zinc-200 dark:bg-zinc-700 hover:bg-zinc-300 dark:hover:bg-zinc-600 font-IconFamily"
|
||||
class="overflow-hidden relative flex justify-center items-center px-4 py-1 text-xl font-medium rounded-lg transition bg-zinc-200 dark:bg-zinc-700 hover:bg-zinc-300 dark:hover:bg-zinc-600"
|
||||
onclick={() => (item.props as LightDarkToggleProps).onChange(!(item.props as LightDarkToggleProps).state)}
|
||||
>
|
||||
{#key (item.props as LightDarkToggleProps).state}
|
||||
<span
|
||||
class="absolute"
|
||||
class="absolute flex items-center justify-center"
|
||||
in:fade={{ duration: 150 }}
|
||||
out:fade={{ duration: 150 }}
|
||||
>
|
||||
{(item.props as LightDarkToggleProps).state ? '\uec12' : '\uecfe'}
|
||||
{#if (item.props as LightDarkToggleProps).state}
|
||||
<LucideMoon class="w-5 h-5" />
|
||||
{:else}
|
||||
<LucideSun class="w-5 h-5" />
|
||||
{/if}
|
||||
</span>
|
||||
{/key}
|
||||
<span class='opacity-0'>{'\uec12'}</span>
|
||||
<span class="opacity-0 inline-flex"><LucideMoon class="w-5 h-5" /></span>
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -330,7 +327,7 @@
|
||||
{/if}
|
||||
{#if theme.coverImage}
|
||||
<div class="absolute z-20 w-full h-full opacity-0 transition-opacity pointer-events-none group-hover:opacity-100 bg-black/20"></div>
|
||||
<img src="{typeof theme.coverImage === 'string' ? theme.coverImage : URL.createObjectURL(theme.coverImage)}" alt='Cover' class="object-cover absolute z-0 w-full h-full rounded" />
|
||||
<ThemeBlobImage source={theme.coverImage} alt="Cover" class="object-cover absolute z-0 w-full h-full rounded" />
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
|
||||
@@ -7,6 +7,8 @@ const THEME_CSS_VARS = [
|
||||
"--text-color",
|
||||
"--background-primary",
|
||||
"--background-secondary",
|
||||
"--theme-primary",
|
||||
"--theme-secondary",
|
||||
"--text-primary",
|
||||
"--theme-offset-bg",
|
||||
"--better-sub",
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import { describe, expect, it } from "@jest/globals";
|
||||
import { resolveExtensionAssetUrl } from "./extensionAssetUrl";
|
||||
|
||||
describe("resolveExtensionAssetUrl", () => {
|
||||
it("returns already-resolved extension URLs unchanged", () => {
|
||||
const url =
|
||||
"chrome-extension://abc/assets/IconFamily-B8lopphU.woff";
|
||||
expect(resolveExtensionAssetUrl(url)).toBe(url);
|
||||
});
|
||||
|
||||
it("repairs accidental double extension URL prefix", () => {
|
||||
const doubled =
|
||||
"chrome-extension://abc/chrome-extension://abc/assets/IconFamily-B8lopphU.woff";
|
||||
expect(resolveExtensionAssetUrl(doubled)).toBe(
|
||||
"chrome-extension://abc/assets/IconFamily-B8lopphU.woff",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,10 @@
|
||||
import browser from "webextension-polyfill";
|
||||
|
||||
/** Resolve Vite asset imports to a usable extension URL. */
|
||||
export function resolveExtensionAssetUrl(url: string): string {
|
||||
const doubled = url.match(/^((?:chrome|moz)-extension:\/\/[^/]+)\/\1\/(.+)$/);
|
||||
if (doubled) return `${doubled[1]}/${doubled[2]}`;
|
||||
if (/^(?:chrome|moz)-extension:\/\/|https?:|data:/.test(url)) return url;
|
||||
return browser.runtime.getURL(url.replace(/^\/+/, ""));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import { describe, expect, it, jest } from "@jest/globals";
|
||||
|
||||
jest.mock("webextension-polyfill", () => ({
|
||||
__esModule: true,
|
||||
default: {
|
||||
runtime: {
|
||||
getURL: (path: string) => `chrome-extension://testid/${path}`,
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
import { extensionPageScriptUrl } from "./extensionPageScriptUrl";
|
||||
|
||||
describe("extensionPageScriptUrl", () => {
|
||||
it("prefixes chrome.runtime.getURL and strips a leading slash", () => {
|
||||
expect(extensionPageScriptUrl("assets/pageState.js")).toBe(
|
||||
"chrome-extension://testid/assets/pageState.js",
|
||||
);
|
||||
expect(extensionPageScriptUrl("/assets/pageState.js")).toBe(
|
||||
"chrome-extension://testid/assets/pageState.js",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,10 @@
|
||||
import browser from "webextension-polyfill";
|
||||
|
||||
/**
|
||||
* Resolve a CRXJS `?script` / `?script&iife` import to a web-accessible
|
||||
* chrome-extension:// URL. Works in both `vite build` and `vite dev`
|
||||
* (plain `?url` imports 404 in CRXJS serve because they are not packaged).
|
||||
*/
|
||||
export function extensionPageScriptUrl(scriptPath: string): string {
|
||||
return browser.runtime.getURL(scriptPath.replace(/^\/+/, ""));
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
/** Material "dark_mode" moon icon — filled style to match SEQTA menu bar icons. */
|
||||
export const LUCIDE_MOON_PATH =
|
||||
"M12,3C7.03,3 3,7.03 3,12C3,16.97 7.03,21 12,21C16.97,21 21,16.97 21,12C21,11.54 20.96,11.08 20.9,10.64C19.92,12.01 18.32,12.9 16.5,12.9C13.52,12.9 11.1,10.48 11.1,7.5C11.1,5.68 11.99,4.08 13.36,3.1C12.92,3.04 12.46,3 12,3Z";
|
||||
|
||||
export const LUCIDE_MOON_ICON_SVG =
|
||||
`<path fill="currentColor" d="${LUCIDE_MOON_PATH}"/>`;
|
||||
@@ -0,0 +1,6 @@
|
||||
/** Material "light_mode" sun icon — filled style to match SEQTA menu bar icons. */
|
||||
export const LUCIDE_SUN_PATH =
|
||||
"M12,7C9.24,7 7,9.24 7,12C7,14.76 9.24,17 12,17C14.76,17 17,14.76 17,12C17,9.24 14.76,7 12,7M2,13H4C4.55,13 5,12.55 5,12C5,11.45 4.55,11 4,11H2C1.45,11 1,11.45 1,12C1,12.55 1.45,13 2,13M20,13H22C22.55,13 23,12.55 23,12C23,11.45 22.55,11 22,11H20C19.45,11 19,11.45 19,12C19,12.55 19.45,13 20,13M11,2V4C11,4.55 11.45,5 12,5C12.55,5 13,4.55 13,4V2C13,1.45 12.55,1 12,1C11.45,1 11,1.45 11,2M11,20V22C11,22.55 11.45,23 12,23C12.55,23 13,22.55 13,22V20C13,19.45 12.55,19 12,19C11.45,19 11,19.45 11,20M5.99,4.58C5.6,4.19 4.96,4.19 4.58,4.58C4.19,4.96 4.19,5.6 4.58,5.99L5.64,7.05C6.03,7.44 6.67,7.44 7.05,7.05C7.44,6.67 7.44,6.03 7.05,5.64L5.99,4.58M18.36,16.95C17.97,16.56 17.33,16.56 16.95,16.95C16.56,17.33 16.56,17.97 16.95,18.36L18.01,19.42C18.4,19.81 19.04,19.81 19.42,19.42C19.81,19.04 19.81,18.4 19.42,18.01L18.36,16.95M19.42,5.99C19.81,5.6 19.81,4.96 19.42,4.58C19.04,4.19 18.4,4.19 18.01,4.58L16.95,5.64C16.56,6.03 16.56,6.67 16.95,7.05C17.33,7.44 17.97,7.44 18.36,7.05L19.42,5.99M7.05,18.36C7.44,17.97 7.44,17.33 7.05,16.95C6.67,16.56 6.03,16.56 5.64,16.95L4.58,18.01C4.19,18.4 4.19,19.04 4.58,19.42C4.96,19.81 5.6,19.81 5.99,19.42L7.05,18.36Z";
|
||||
|
||||
export const LUCIDE_SUN_ICON_SVG =
|
||||
`<path fill="currentColor" d="${LUCIDE_SUN_PATH}"/>`;
|
||||
@@ -0,0 +1,43 @@
|
||||
import browser from "webextension-polyfill";
|
||||
|
||||
const ORT_RESOURCE_DIR = "resources/ort/";
|
||||
|
||||
let configured = false;
|
||||
|
||||
function extensionAssetUrl(relativePath: string): string {
|
||||
return browser.runtime.getURL(relativePath.replace(/^\/+/, ""));
|
||||
}
|
||||
|
||||
/**
|
||||
* Point HuggingFace transformers / onnxruntime at extension-local WASM files
|
||||
* instead of CDN (required on SEQTA pages where page CSP blocks jsdelivr).
|
||||
* Safe to call multiple times; must run before embeddia `initializeModel()`.
|
||||
*/
|
||||
export async function ensureTransformersEnv(
|
||||
ortWasmBase?: string,
|
||||
): Promise<void> {
|
||||
if (configured) return;
|
||||
|
||||
const { env } = await import("@huggingface/transformers");
|
||||
const base = ortWasmBase ?? extensionAssetUrl(ORT_RESOURCE_DIR);
|
||||
|
||||
env.backends.onnx.wasm = env.backends.onnx.wasm ?? {};
|
||||
env.backends.onnx.wasm.wasmPaths = base.endsWith("/") ? base : `${base}/`;
|
||||
|
||||
configured = true;
|
||||
}
|
||||
|
||||
export function getOrtWasmBaseUrl(): string {
|
||||
const base = extensionAssetUrl(ORT_RESOURCE_DIR);
|
||||
return base.endsWith("/") ? base : `${base}/`;
|
||||
}
|
||||
|
||||
/** For page-origin blob workers that cannot call `browser.runtime.getURL`. */
|
||||
export async function configureTransformersEnvForBase(
|
||||
ortWasmBase: string,
|
||||
): Promise<void> {
|
||||
configured = false;
|
||||
await ensureTransformersEnv(ortWasmBase);
|
||||
}
|
||||
|
||||
export { ORT_RESOURCE_DIR };
|
||||
@@ -15,17 +15,27 @@
|
||||
"64": "resources/icons/icon-64.png"
|
||||
}
|
||||
},
|
||||
"permissions": ["tabs", "notifications", "storage"],
|
||||
"host_permissions": ["https://newsapi.org/", "https://betterseqta.org/", "https://accounts.betterseqta.org/", "*://*/*"],
|
||||
"permissions": ["tabs", "notifications", "storage", "identity", "alarms"],
|
||||
"host_permissions": [
|
||||
"https://newsapi.org/",
|
||||
"https://betterseqta.org/",
|
||||
"https://accounts.betterseqta.org/",
|
||||
"https://www.googleapis.com/",
|
||||
"https://oauth2.googleapis.com/",
|
||||
"https://graph.microsoft.com/",
|
||||
"https://login.microsoftonline.com/",
|
||||
"*://*/*"
|
||||
],
|
||||
"background": {
|
||||
"service_worker": "background.ts"
|
||||
},
|
||||
"content_security_policy": {
|
||||
"extension_pages": "script-src 'self'; object-src 'self'; connect-src 'self' http: https: https://betterseqta.org https://accounts.betterseqta.org https://raw.githubusercontent.com https://newsapi.org"
|
||||
"extension_pages": "script-src 'self'; object-src 'self'; connect-src 'self' http: https: https://betterseqta.org https://accounts.betterseqta.org https://raw.githubusercontent.com https://newsapi.org https://www.googleapis.com https://oauth2.googleapis.com https://graph.microsoft.com https://login.microsoftonline.com"
|
||||
},
|
||||
"content_scripts": [
|
||||
{
|
||||
"matches": ["*://*/*"],
|
||||
"exclude_matches": ["*://accounts.betterseqta.org/*"],
|
||||
"js": ["SEQTA.ts"],
|
||||
"run_at": "document_start"
|
||||
}
|
||||
@@ -37,7 +47,10 @@
|
||||
"resources/update-image.webp",
|
||||
"resources/pdfjs/pdf.worker.min.mjs",
|
||||
"resources/pdfjs/pdf.legacy.min.mjs",
|
||||
"resources/themeToggleSurprisePage.js"
|
||||
"resources/themeToggleSurprisePage.js",
|
||||
"resources/ort/*",
|
||||
"assets/*.css",
|
||||
"assets/*"
|
||||
],
|
||||
"matches": ["*://*/*"]
|
||||
}
|
||||
|
||||
+99
-87
@@ -509,96 +509,108 @@ function deepFunctionCheck(obj, path = "") {
|
||||
}
|
||||
}
|
||||
|
||||
window.addEventListener("message", (event) => {
|
||||
if (event.data.type === "reactFiberRequest") {
|
||||
const { selector, action, payload, debug, messageId } = event.data;
|
||||
const fiberInstance = ReactFiber.find(selector, {
|
||||
debug,
|
||||
});
|
||||
function isTrustedMessage(event) {
|
||||
return event.source === window && event.origin === window.location.origin;
|
||||
}
|
||||
|
||||
let response;
|
||||
switch (action) {
|
||||
case "getState":
|
||||
response = fiberInstance.getState(payload.key);
|
||||
break;
|
||||
case "setState":
|
||||
// Handle both function and object updates
|
||||
if (payload.updateFn) {
|
||||
const updateFn = new Function('return ' + payload.updateFn)();
|
||||
fiberInstance.setState(updateFn);
|
||||
} else {
|
||||
fiberInstance.setState(payload.updateObject);
|
||||
}
|
||||
response = {};
|
||||
break;
|
||||
|
||||
case "getProp":
|
||||
response = fiberInstance.getProp(payload.propName);
|
||||
break;
|
||||
case "setProp":
|
||||
fiberInstance.setProp(payload.propName, payload.value);
|
||||
response = {};
|
||||
break;
|
||||
case "forceUpdate":
|
||||
fiberInstance.forceUpdate();
|
||||
response = {};
|
||||
break;
|
||||
default:
|
||||
console.warn(`[pageState] Unknown action: ${action}`);
|
||||
response = null;
|
||||
}
|
||||
|
||||
if (response !== null && typeof response === "object") {
|
||||
response = makeSerializable(response);
|
||||
}
|
||||
|
||||
// Final safety check before postMessage
|
||||
try {
|
||||
deepFunctionCheck(response);
|
||||
} catch (functionError) {
|
||||
console.warn("[pageState] Function detected in response, cleaning:", functionError.message);
|
||||
response = `[Cleaned Response - Function found at: ${functionError.message}]`;
|
||||
}
|
||||
|
||||
// Additional structured clone test
|
||||
try {
|
||||
// Test if the object can be cloned (same algorithm as postMessage)
|
||||
if (typeof structuredClone === 'function') {
|
||||
structuredClone(response);
|
||||
function executeReactFiberAction(fiberInstance, action, payload) {
|
||||
switch (action) {
|
||||
case "getState":
|
||||
return fiberInstance.getState(payload.key);
|
||||
case "setState":
|
||||
if (
|
||||
payload.updateObject &&
|
||||
typeof payload.updateObject === "object" &&
|
||||
!Array.isArray(payload.updateObject)
|
||||
) {
|
||||
fiberInstance.setState(payload.updateObject);
|
||||
} else {
|
||||
// Fallback for older browsers - try JSON round-trip
|
||||
JSON.parse(JSON.stringify(response));
|
||||
console.warn("[pageState] setState rejected: only plain objects are allowed");
|
||||
}
|
||||
} catch (cloneError) {
|
||||
console.warn("[pageState] Response not cloneable, fallback:", cloneError.message);
|
||||
response = `[Uncloneable Response: ${cloneError.message}]`;
|
||||
}
|
||||
return {};
|
||||
case "getProp":
|
||||
return fiberInstance.getProp(payload.propName);
|
||||
case "setProp":
|
||||
fiberInstance.setProp(payload.propName, payload.value);
|
||||
return {};
|
||||
case "forceUpdate":
|
||||
fiberInstance.forceUpdate();
|
||||
return {};
|
||||
default:
|
||||
console.warn(`[pageState] Unknown action: ${action}`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
window.postMessage(
|
||||
{
|
||||
type: "reactFiberResponse",
|
||||
response,
|
||||
messageId,
|
||||
},
|
||||
"*",
|
||||
);
|
||||
} else if (event.data.type === "triggerKeyboardEvent") {
|
||||
// Handle keyboard event triggering from content script
|
||||
const { key, code, altKey, ctrlKey, metaKey, shiftKey, keyCode } = event.data;
|
||||
|
||||
const keyboardEvent = new KeyboardEvent('keydown', {
|
||||
key,
|
||||
code,
|
||||
keyCode: keyCode || 0,
|
||||
which: keyCode || 0,
|
||||
altKey: altKey || false,
|
||||
ctrlKey: ctrlKey || false,
|
||||
metaKey: metaKey || false,
|
||||
shiftKey: shiftKey || false,
|
||||
bubbles: true,
|
||||
cancelable: true
|
||||
});
|
||||
|
||||
document.dispatchEvent(keyboardEvent);
|
||||
function sanitizeResponseForPostMessage(response) {
|
||||
if (response !== null && typeof response === "object") {
|
||||
response = makeSerializable(response);
|
||||
}
|
||||
|
||||
try {
|
||||
deepFunctionCheck(response);
|
||||
} catch (functionError) {
|
||||
console.warn("[pageState] Function detected in response, cleaning:", functionError.message);
|
||||
return `[Cleaned Response - Function found at: ${functionError.message}]`;
|
||||
}
|
||||
|
||||
try {
|
||||
if (typeof structuredClone === "function") {
|
||||
structuredClone(response);
|
||||
} else {
|
||||
JSON.parse(JSON.stringify(response));
|
||||
}
|
||||
} catch (cloneError) {
|
||||
console.warn("[pageState] Response not cloneable, fallback:", cloneError.message);
|
||||
return `[Uncloneable Response: ${cloneError.message}]`;
|
||||
}
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
function handleReactFiberRequest(data) {
|
||||
const { selector, action, payload, debug, messageId } = data;
|
||||
const fiberInstance = ReactFiber.find(selector, { debug });
|
||||
const response = sanitizeResponseForPostMessage(
|
||||
executeReactFiberAction(fiberInstance, action, payload),
|
||||
);
|
||||
|
||||
window.postMessage(
|
||||
{
|
||||
type: "reactFiberResponse",
|
||||
response,
|
||||
messageId,
|
||||
},
|
||||
window.location.origin,
|
||||
);
|
||||
}
|
||||
|
||||
function handleTriggerKeyboardEvent(data) {
|
||||
const { key, code, altKey, ctrlKey, metaKey, shiftKey, keyCode } = data;
|
||||
const keyboardEvent = new KeyboardEvent("keydown", {
|
||||
key,
|
||||
code,
|
||||
keyCode: keyCode || 0,
|
||||
which: keyCode || 0,
|
||||
altKey: altKey || false,
|
||||
ctrlKey: ctrlKey || false,
|
||||
metaKey: metaKey || false,
|
||||
shiftKey: shiftKey || false,
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
});
|
||||
document.dispatchEvent(keyboardEvent);
|
||||
}
|
||||
|
||||
window.addEventListener("message", (event) => {
|
||||
if (!isTrustedMessage(event)) return;
|
||||
|
||||
if (event.data.type === "reactFiberRequest") {
|
||||
handleReactFiberRequest(event.data);
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.data.type === "triggerKeyboardEvent") {
|
||||
handleTriggerKeyboardEvent(event.data);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,64 @@
|
||||
import type { PluginAPI } from "@/plugins/core/types";
|
||||
import { waitForElm } from "@/seqta/utils/waitForElm";
|
||||
|
||||
export const ANIMATED_BG_MARKER = "bsplus-animated-bg";
|
||||
|
||||
const LAYER_CLASSES = [
|
||||
["bg", ANIMATED_BG_MARKER],
|
||||
["bg", "bg2", ANIMATED_BG_MARKER],
|
||||
["bg", "bg3", ANIMATED_BG_MARKER],
|
||||
] as const;
|
||||
|
||||
const bgSel = `.bg.${ANIMATED_BG_MARKER}`;
|
||||
const scopeSel = `:scope > div${bgSel}`;
|
||||
const BASE_SPEEDS = [3, 4, 5] as const;
|
||||
|
||||
export function updateAnimationSpeed(speed: number) {
|
||||
document.querySelectorAll(bgSel).forEach((element, index) => {
|
||||
const base = BASE_SPEEDS[index] ?? BASE_SPEEDS[2];
|
||||
(element as HTMLElement).style.animationDuration = `${base / speed}s`;
|
||||
});
|
||||
}
|
||||
|
||||
export function ensureAnimatedBackgroundLayers(
|
||||
container: HTMLElement,
|
||||
menu: HTMLElement,
|
||||
speed: number,
|
||||
): void {
|
||||
if (container.querySelectorAll(scopeSel).length >= 3) {
|
||||
updateAnimationSpeed(speed);
|
||||
return;
|
||||
}
|
||||
|
||||
container.querySelectorAll(scopeSel).forEach((el) => el.remove());
|
||||
|
||||
for (const classes of LAYER_CLASSES) {
|
||||
const bk = document.createElement("div");
|
||||
classes.forEach((cls) => bk.classList.add(cls));
|
||||
container.insertBefore(bk, menu);
|
||||
}
|
||||
|
||||
updateAnimationSpeed(speed);
|
||||
}
|
||||
|
||||
export function removeAnimatedBackgroundLayers(): void {
|
||||
document.querySelectorAll(`div${bgSel}`).forEach((el) => el.remove());
|
||||
}
|
||||
|
||||
export async function syncAnimatedBackground(
|
||||
api: PluginAPI<{ speed: number }>,
|
||||
): Promise<void> {
|
||||
try {
|
||||
const [container, menu] = await Promise.all([
|
||||
waitForElm("#container", true),
|
||||
waitForElm("#menu", true),
|
||||
]);
|
||||
ensureAnimatedBackgroundLayers(
|
||||
container as HTMLElement,
|
||||
menu as HTMLElement,
|
||||
api.settings.speed,
|
||||
);
|
||||
} catch {
|
||||
// #container / #menu not ready yet
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,11 @@ import {
|
||||
Setting,
|
||||
} from "@/plugins/core/settingsHelpers";
|
||||
import styles from "./styles.css?inline";
|
||||
import { waitForElm } from "@/seqta/utils/waitForElm";
|
||||
import {
|
||||
removeAnimatedBackgroundLayers,
|
||||
syncAnimatedBackground,
|
||||
updateAnimationSpeed,
|
||||
} from "./backgroundLayers";
|
||||
|
||||
const settings = defineSettings({
|
||||
speed: numberSetting({
|
||||
@@ -36,48 +40,25 @@ const animatedBackgroundPlugin: Plugin<typeof settings> = {
|
||||
settings: instance.settings,
|
||||
|
||||
run: async (api) => {
|
||||
const [container, menu] = await Promise.all([
|
||||
waitForElm("#container", true),
|
||||
waitForElm("#menu", true),
|
||||
]);
|
||||
await syncAnimatedBackground(api);
|
||||
const resync = () => void syncAnimatedBackground(api);
|
||||
|
||||
const backgrounds = [
|
||||
{ classes: ["bg"] },
|
||||
{ classes: ["bg", "bg2"] },
|
||||
{ classes: ["bg", "bg3"] },
|
||||
];
|
||||
const speedUnregister = api.settings.onChange("speed", updateAnimationSpeed);
|
||||
const pageChangeUnregister = api.seqta.onPageChange(resync);
|
||||
window.addEventListener("pageshow", resync);
|
||||
|
||||
backgrounds.forEach(({ classes }) => {
|
||||
const bk = document.createElement("div");
|
||||
classes.forEach((cls) => bk.classList.add(cls));
|
||||
container.insertBefore(bk, menu);
|
||||
});
|
||||
const containerObserver = new MutationObserver(resync);
|
||||
const container = document.getElementById("container");
|
||||
if (container) containerObserver.observe(container, { childList: true });
|
||||
|
||||
// Set initial speed
|
||||
updateAnimationSpeed(api.settings.speed);
|
||||
|
||||
// Listen for speed changes
|
||||
const speedUnregister = api.settings.onChange(
|
||||
"speed",
|
||||
updateAnimationSpeed,
|
||||
);
|
||||
|
||||
// Return cleanup function
|
||||
return () => {
|
||||
speedUnregister.unregister();
|
||||
// Remove background elements
|
||||
const backgrounds = document.getElementsByClassName("bg");
|
||||
Array.from(backgrounds).forEach((element) => element.remove());
|
||||
pageChangeUnregister.unregister();
|
||||
window.removeEventListener("pageshow", resync);
|
||||
containerObserver.disconnect();
|
||||
removeAnimatedBackgroundLayers();
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
function updateAnimationSpeed(speed: number) {
|
||||
const bgElements = document.getElementsByClassName("bg");
|
||||
Array.from(bgElements).forEach((element, index) => {
|
||||
const baseSpeed = index === 0 ? 3 : index === 1 ? 4 : 5;
|
||||
(element as HTMLElement).style.animationDuration = `${baseSpeed / speed}s`;
|
||||
});
|
||||
}
|
||||
|
||||
export default animatedBackgroundPlugin;
|
||||
@@ -0,0 +1,31 @@
|
||||
import { extractWeightFromCoversheetText } from "./extractWeightFromCoversheetText";
|
||||
|
||||
describe("extractWeightFromCoversheetText", () => {
|
||||
it("matches Weight: N", () => {
|
||||
expect(extractWeightFromCoversheetText("Due date ... Weight: 20 Subject")).toBe(
|
||||
"20",
|
||||
);
|
||||
});
|
||||
|
||||
it("matches Weighting: N%", () => {
|
||||
expect(
|
||||
extractWeightFromCoversheetText("Assessment Weighting: 12.5% of semester"),
|
||||
).toBe("12.5");
|
||||
});
|
||||
|
||||
it("matches Assessment weight: N", () => {
|
||||
expect(
|
||||
extractWeightFromCoversheetText("Assessment weight: 15\nCriteria"),
|
||||
).toBe("15");
|
||||
});
|
||||
|
||||
it("matches Weight of N%", () => {
|
||||
expect(extractWeightFromCoversheetText("This task has a weight of 10%")).toBe(
|
||||
"10",
|
||||
);
|
||||
});
|
||||
|
||||
it("returns null when no weighting is present", () => {
|
||||
expect(extractWeightFromCoversheetText("No marks available yet")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
/** Pull a numeric weighting from coversheet / report PDF text. */
|
||||
export function extractWeightFromCoversheetText(text: string): string | null {
|
||||
const patterns = [
|
||||
/weightings?\s*:\s*(\d+(?:\.\d+)?)\s*%?/i,
|
||||
/weight\s*:\s*(\d+(?:\.\d+)?)\s*%?/i,
|
||||
/assessment\s+weight(?:ing)?\s*:\s*(\d+(?:\.\d+)?)\s*%?/i,
|
||||
/weight(?:ing)?\s+(?:of\s+)?(\d+(?:\.\d+)?)\s*%/i,
|
||||
];
|
||||
|
||||
for (const pattern of patterns) {
|
||||
const match = text.match(pattern);
|
||||
if (match?.[1]) return match[1];
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -1,9 +1,3 @@
|
||||
import { BasePlugin } from "@/plugins/core/settings";
|
||||
import {
|
||||
booleanSetting,
|
||||
defineSettings,
|
||||
Setting,
|
||||
} from "@/plugins/core/settingsHelpers";
|
||||
import { type Plugin } from "@/plugins/core/types";
|
||||
import stringToHTML from "@/seqta/utils/stringToHTML";
|
||||
import { waitForElm } from "@/seqta/utils/waitForElm";
|
||||
@@ -17,7 +11,7 @@ import {
|
||||
processAssessments,
|
||||
type WeightingEntry,
|
||||
} from "./utils.ts";
|
||||
import { injectRubricCopyButtons } from "./rubricCopy.ts";
|
||||
import { injectRubricCopyButtons, teardownRubricCopyButtons } from "./rubricCopy.ts";
|
||||
|
||||
interface weightingsStorage {
|
||||
weightings: Record<string, WeightingEntry>;
|
||||
@@ -25,36 +19,18 @@ interface weightingsStorage {
|
||||
weightingOverrides: Record<string, string>;
|
||||
}
|
||||
|
||||
const settings = defineSettings({
|
||||
lettergrade: booleanSetting({
|
||||
default: false,
|
||||
title: "Letter Grades",
|
||||
description: "Display the average as a letter instead of a percentage",
|
||||
}),
|
||||
});
|
||||
|
||||
class AssessmentsAveragePluginClass extends BasePlugin<typeof settings> {
|
||||
@Setting(settings.lettergrade)
|
||||
lettergrade!: boolean;
|
||||
}
|
||||
|
||||
const instance = new AssessmentsAveragePluginClass();
|
||||
|
||||
let overrideListenerController: AbortController | null = null;
|
||||
let wrapperColourObserver: MutationObserver | null = null;
|
||||
let wrapperColourObserverTimeout: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
const assessmentsAveragePlugin: Plugin<typeof settings, weightingsStorage> = {
|
||||
id: "assessments-average",
|
||||
name: "Assessment Averages",
|
||||
description: "Adds an average grade to the Assessments page",
|
||||
version: "1.0.0",
|
||||
disableToggle: true,
|
||||
settings: instance.settings,
|
||||
|
||||
run: async (api) => {
|
||||
const assessmentsAveragePlugin = {
|
||||
run: async (api: Parameters<NonNullable<Plugin["run"]>>[0]) => {
|
||||
await initStorage(api);
|
||||
clearStuck(api);
|
||||
|
||||
api.seqta.onMount(".assessmentsWrapper", async () => {
|
||||
const { unregister: unregisterWrapperMount } = api.seqta.onMount(
|
||||
".assessmentsWrapper",
|
||||
async () => {
|
||||
await waitForElm(
|
||||
"#main > .assessmentsWrapper .assessments [class*='AssessmentItem__AssessmentItem___']",
|
||||
true,
|
||||
@@ -88,17 +64,43 @@ const assessmentsAveragePlugin: Plugin<typeof settings, weightingsStorage> = {
|
||||
void parseAssessments(api);
|
||||
const wrapper = document.querySelector(".assessmentsWrapper");
|
||||
if (wrapper) {
|
||||
const observer = new MutationObserver(() => {
|
||||
wrapperColourObserver?.disconnect();
|
||||
if (wrapperColourObserverTimeout) {
|
||||
clearTimeout(wrapperColourObserverTimeout);
|
||||
}
|
||||
wrapperColourObserver = new MutationObserver(() => {
|
||||
applySubjectColourToOverallResult();
|
||||
});
|
||||
observer.observe(wrapper, { childList: true, subtree: true });
|
||||
setTimeout(() => observer.disconnect(), 10000);
|
||||
wrapperColourObserver.observe(wrapper, { childList: true, subtree: true });
|
||||
wrapperColourObserverTimeout = setTimeout(() => {
|
||||
wrapperColourObserver?.disconnect();
|
||||
wrapperColourObserver = null;
|
||||
wrapperColourObserverTimeout = null;
|
||||
}, 10000);
|
||||
}
|
||||
});
|
||||
api.seqta.onMount("[class*='SelectedAssessment__']", () => {
|
||||
},
|
||||
);
|
||||
const { unregister: unregisterSelectedMount } = api.seqta.onMount(
|
||||
"[class*='SelectedAssessment__']",
|
||||
() => {
|
||||
injectWeightingsTab(api);
|
||||
injectRubricCopyButtons();
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
return () => {
|
||||
overrideListenerController?.abort();
|
||||
overrideListenerController = null;
|
||||
wrapperColourObserver?.disconnect();
|
||||
wrapperColourObserver = null;
|
||||
if (wrapperColourObserverTimeout) {
|
||||
clearTimeout(wrapperColourObserverTimeout);
|
||||
wrapperColourObserverTimeout = null;
|
||||
}
|
||||
teardownRubricCopyButtons();
|
||||
unregisterWrapperMount();
|
||||
unregisterSelectedMount();
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import { defineLazyPlugin } from "../../core/dynamicLoader";
|
||||
import { booleanSetting, defineSettings } from "../../core/settingsHelpers";
|
||||
|
||||
const settings = defineSettings({
|
||||
lettergrade: booleanSetting({
|
||||
default: false,
|
||||
title: "Letter Grades",
|
||||
description: "Display the average as a letter instead of a percentage",
|
||||
}),
|
||||
});
|
||||
|
||||
export default defineLazyPlugin({
|
||||
id: "assessments-average",
|
||||
name: "Assessment Averages",
|
||||
description: "Adds an average grade to the Assessments page",
|
||||
version: "1.0.0",
|
||||
disableToggle: true,
|
||||
settings,
|
||||
loader: () => import("./index"),
|
||||
});
|
||||
@@ -1,3 +1,5 @@
|
||||
import debounce from "@/seqta/utils/debounce";
|
||||
|
||||
const RUBRIC_SELECTOR =
|
||||
"[class*='AssessableCriterion__rubric___'][class*='Rubric__Rubric___'], [class*='Rubric__Rubric___'][class*='AssessableCriterion__rubric___']";
|
||||
const ENHANCED_ATTR = "data-betterseqta-rubric-copy";
|
||||
@@ -365,13 +367,13 @@ function enhanceRubrics(root: ParentNode = document) {
|
||||
root.querySelectorAll<HTMLElement>(RUBRIC_SELECTOR).forEach(enhanceRubric);
|
||||
}
|
||||
|
||||
const debouncedEnhanceRubrics = debounce(enhanceRubrics, 50);
|
||||
|
||||
function watchRubrics(root: ParentNode) {
|
||||
observer?.disconnect();
|
||||
enhanceRubrics(root);
|
||||
|
||||
observer = new MutationObserver(() => {
|
||||
enhanceRubrics(root);
|
||||
});
|
||||
observer = new MutationObserver(() => debouncedEnhanceRubrics(root));
|
||||
|
||||
observer.observe(root, { childList: true, subtree: true });
|
||||
}
|
||||
|
||||
@@ -11,8 +11,9 @@ import {
|
||||
getPdfjsPageContextUrls,
|
||||
} from "@/lib/pdfjsExtension.ts";
|
||||
import * as pdfjs from "pdfjs-dist";
|
||||
import { extractWeightFromCoversheetText } from "./extractWeightFromCoversheetText";
|
||||
|
||||
ensurePdfjsWorker();
|
||||
export { extractWeightFromCoversheetText };
|
||||
|
||||
export const WEIGHTING_SCHEMA_VERSION = 1;
|
||||
|
||||
@@ -25,6 +26,91 @@ export interface WeightingEntry {
|
||||
|
||||
export type WeightingsMap = Record<string, WeightingEntry>;
|
||||
|
||||
/** Primary storage key for weightings / overrides. */
|
||||
export function assessmentIdKey(mark: { id: string | number }): string {
|
||||
return String(mark.id);
|
||||
}
|
||||
|
||||
/** Composite lookup key when the same title appears in multiple metaclasses. */
|
||||
export function assessmentTitleLookupKey(mark: {
|
||||
metaclassID?: string | number;
|
||||
title?: string;
|
||||
}): string | null {
|
||||
const title = mark.title?.trim();
|
||||
if (!title) return null;
|
||||
const metaclassID = mark.metaclassID;
|
||||
if (metaclassID != null && metaclassID !== "") {
|
||||
return `${metaclassID}:${title}`;
|
||||
}
|
||||
return title;
|
||||
}
|
||||
|
||||
function registerAssessmentLookup(api: any, mark: any) {
|
||||
const assessmentID = assessmentIdKey(mark);
|
||||
const next: Record<string, string> = {
|
||||
...api.storage.assessments,
|
||||
[assessmentID]: assessmentID,
|
||||
};
|
||||
const compositeKey = assessmentTitleLookupKey(mark);
|
||||
if (compositeKey) next[compositeKey] = assessmentID;
|
||||
api.storage.assessments = next;
|
||||
}
|
||||
|
||||
type MarkLike = {
|
||||
id: string | number;
|
||||
title?: string;
|
||||
metaclassID?: string | number;
|
||||
};
|
||||
|
||||
function collectMarksFromFiberState(state: Record<string, unknown>): MarkLike[] {
|
||||
return [
|
||||
...(Array.isArray(state.marks) ? state.marks : []),
|
||||
...(Array.isArray(state.upcoming) ? state.upcoming : []),
|
||||
...(Array.isArray(state.pending) ? state.pending : []),
|
||||
] as MarkLike[];
|
||||
}
|
||||
|
||||
async function resolveAssessmentId(
|
||||
api: any,
|
||||
title: string,
|
||||
marks?: MarkLike[],
|
||||
): Promise<string | undefined> {
|
||||
const assessments = (api.storage.assessments ?? {}) as Record<string, string>;
|
||||
let resolvedMarks = marks;
|
||||
|
||||
if (!resolvedMarks) {
|
||||
try {
|
||||
const state = await ReactFiber.find(
|
||||
"[class*='AssessmentList__items___']",
|
||||
).getState();
|
||||
resolvedMarks = collectMarksFromFiberState(state);
|
||||
} catch {
|
||||
resolvedMarks = [];
|
||||
}
|
||||
}
|
||||
|
||||
const matching = resolvedMarks.filter((mark) => mark.title?.trim() === title);
|
||||
if (matching.length === 1) {
|
||||
return assessmentIdKey(matching[0]);
|
||||
}
|
||||
|
||||
for (const mark of matching) {
|
||||
const compositeKey = assessmentTitleLookupKey(mark);
|
||||
if (compositeKey && assessments[compositeKey]) {
|
||||
return assessments[compositeKey];
|
||||
}
|
||||
}
|
||||
|
||||
if (assessments[title]) return assessments[title];
|
||||
|
||||
const suffix = `:${title}`;
|
||||
for (const [key, id] of Object.entries(assessments)) {
|
||||
if (key.endsWith(suffix)) return id;
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function computeFingerprint(mark: any): string {
|
||||
const score =
|
||||
mark?.results?.percentage ?? mark?.results?.score ?? null;
|
||||
@@ -264,6 +350,7 @@ function createWeightLabel(
|
||||
weighting: string | undefined,
|
||||
api: any,
|
||||
refreshing = false,
|
||||
assessmentID?: string,
|
||||
) {
|
||||
let statsContainer = assessmentItem.querySelector(
|
||||
`[class*='AssessmentItem__stats___'], .betterseqta-stats-container`,
|
||||
@@ -289,10 +376,8 @@ function createWeightLabel(
|
||||
? "space-between"
|
||||
: "flex-end";
|
||||
|
||||
const title = assessmentItem
|
||||
.querySelector(`[class*='AssessmentItem__title___']`)
|
||||
?.textContent?.trim();
|
||||
const assessmentID = title ? api.storage.assessments?.[title] : undefined;
|
||||
const resolvedAssessmentId =
|
||||
assessmentID ?? assessmentItem.dataset.betterseqtaAssessmentId;
|
||||
|
||||
const existingLabel = statsContainer.querySelector(
|
||||
".betterseqta-weight-label",
|
||||
@@ -302,7 +387,7 @@ function createWeightLabel(
|
||||
updateWeightLabelContent(
|
||||
existingLabel,
|
||||
weighting,
|
||||
assessmentID,
|
||||
resolvedAssessmentId,
|
||||
api,
|
||||
refreshing,
|
||||
);
|
||||
@@ -340,7 +425,7 @@ function createWeightLabel(
|
||||
updateWeightLabelContent(
|
||||
weightLabel,
|
||||
weighting,
|
||||
assessmentID,
|
||||
resolvedAssessmentId,
|
||||
api,
|
||||
refreshing,
|
||||
);
|
||||
@@ -352,14 +437,24 @@ export const isFirefox =
|
||||
!navigator.userAgent.toLowerCase().includes("seamonkey") &&
|
||||
!navigator.userAgent.toLowerCase().includes("waterfox");
|
||||
|
||||
function trustedPageOrigin(): string {
|
||||
return window.location.origin;
|
||||
}
|
||||
|
||||
function escJsSingleQuoted(value: string): string {
|
||||
return value.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
|
||||
}
|
||||
|
||||
async function fetchPDFAsArrayBuffer(url: string): Promise<ArrayBuffer> {
|
||||
const isBlobUrl = url.startsWith("blob:");
|
||||
const pageOrigin = trustedPageOrigin();
|
||||
|
||||
if (isBlobUrl || isFirefox) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const script = document.createElement("script");
|
||||
const requestId = `pdf-fetch-${Date.now()}-${Math.random()}`;
|
||||
const escapedUrl = url.replace(/'/g, "\\'");
|
||||
const escapedUrl = escJsSingleQuoted(url);
|
||||
const escapedOrigin = escJsSingleQuoted(pageOrigin);
|
||||
|
||||
script.textContent = `
|
||||
(function() {
|
||||
@@ -375,19 +470,20 @@ async function fetchPDFAsArrayBuffer(url: string): Promise<ArrayBuffer> {
|
||||
type: '${requestId}',
|
||||
success: true,
|
||||
data: Array.from(new Uint8Array(arrayBuffer))
|
||||
}, '*');
|
||||
}, '${escapedOrigin}');
|
||||
})
|
||||
.catch(error => {
|
||||
window.postMessage({
|
||||
type: '${requestId}',
|
||||
success: false,
|
||||
error: error.message || String(error)
|
||||
}, '*');
|
||||
}, '${escapedOrigin}');
|
||||
});
|
||||
})();
|
||||
`;
|
||||
|
||||
const messageHandler = (event: MessageEvent) => {
|
||||
if (event.origin !== pageOrigin || event.source !== window) return;
|
||||
if (event.data?.type === requestId) {
|
||||
window.removeEventListener("message", messageHandler);
|
||||
if (script.parentNode) {
|
||||
@@ -449,147 +545,79 @@ export async function extractPDFText(url: string): Promise<string> {
|
||||
if (isFirefox) {
|
||||
const { lib: pdfLibUrl, worker: pdfWorkerUrl } =
|
||||
getPdfjsPageContextUrls();
|
||||
const escJsSingleQuoted = (s: string) =>
|
||||
s.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
|
||||
const pdfLibInj = escJsSingleQuoted(pdfLibUrl);
|
||||
const pdfWorkerInj = escJsSingleQuoted(pdfWorkerUrl);
|
||||
|
||||
const pageOrigin = trustedPageOrigin();
|
||||
const escapedOrigin = escJsSingleQuoted(pageOrigin);
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const script = document.createElement("script");
|
||||
script.type = "module";
|
||||
const requestId = `pdf-extract-${Date.now()}-${Math.random()}`;
|
||||
|
||||
const escapedUrl = url
|
||||
.replace(/\\/g, "\\\\")
|
||||
.replace(/'/g, "\\'")
|
||||
.replace(/"/g, '\\"');
|
||||
const escapedUrl = escJsSingleQuoted(url);
|
||||
|
||||
// Import the legacy build in page context so it can set
|
||||
// globalThis.pdfjsLib, then parse the coversheet PDF.
|
||||
script.textContent = `
|
||||
(function() {
|
||||
const requestId = '${requestId}';
|
||||
const url = '${escapedUrl}';
|
||||
const pdfLibSrc = '${pdfLibInj}';
|
||||
const pdfWorkerSrc = '${pdfWorkerInj}';
|
||||
|
||||
if (window.pdfjsLib) {
|
||||
extractPDF();
|
||||
const requestId = '${requestId}';
|
||||
const pageOrigin = '${escapedOrigin}';
|
||||
const url = '${escapedUrl}';
|
||||
const pdfWorkerSrc = '${pdfWorkerInj}';
|
||||
|
||||
function postResult(payload) {
|
||||
window.postMessage({ type: requestId, ...payload }, pageOrigin);
|
||||
}
|
||||
|
||||
try {
|
||||
await import('${pdfLibInj}');
|
||||
const pdfjsLib = globalThis.pdfjsLib;
|
||||
if (!pdfjsLib?.getDocument) {
|
||||
postResult({ success: false, error: 'pdfjsLib missing after import' });
|
||||
} else {
|
||||
const pdfjsScript = document.createElement('script');
|
||||
pdfjsScript.src = pdfLibSrc;
|
||||
pdfjsScript.type = 'module';
|
||||
|
||||
pdfjsScript.onload = function() {
|
||||
extractPDF();
|
||||
};
|
||||
pdfjsScript.onerror = function() {
|
||||
window.postMessage({
|
||||
type: requestId,
|
||||
success: false,
|
||||
error: 'Failed to load pdfjs library'
|
||||
}, '*');
|
||||
};
|
||||
|
||||
document.head.appendChild(pdfjsScript);
|
||||
}
|
||||
|
||||
function extractPDF() {
|
||||
try {
|
||||
window.pdfjsLib.GlobalWorkerOptions.workerSrc = pdfWorkerSrc;
|
||||
|
||||
const xhr = new XMLHttpRequest();
|
||||
xhr.open('GET', url, true);
|
||||
xhr.responseType = 'arraybuffer';
|
||||
xhr.withCredentials = true;
|
||||
|
||||
xhr.onload = function() {
|
||||
if (xhr.status !== 200) {
|
||||
window.postMessage({
|
||||
type: requestId,
|
||||
success: false,
|
||||
error: 'HTTP ' + xhr.status + ': ' + xhr.statusText
|
||||
}, '*');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const arrayBuffer = xhr.response;
|
||||
if (!arrayBuffer || arrayBuffer.byteLength === 0) {
|
||||
throw new Error('PDF response is empty');
|
||||
}
|
||||
|
||||
window.pdfjsLib.getDocument({
|
||||
data: arrayBuffer,
|
||||
useSystemFonts: true,
|
||||
verbosity: 0,
|
||||
useWorkerFetch: false,
|
||||
isEvalSupported: false
|
||||
}).promise
|
||||
.then(pdf => {
|
||||
const pagePromises = [];
|
||||
for (let i = 1; i <= pdf.numPages; i++) {
|
||||
pagePromises.push(
|
||||
pdf.getPage(i).then(page => {
|
||||
return page.getTextContent().then(content => {
|
||||
return content.items.map(item => item.str).join(' ');
|
||||
});
|
||||
})
|
||||
);
|
||||
}
|
||||
return Promise.all(pagePromises);
|
||||
})
|
||||
.then(pages => {
|
||||
const text = pages.join('\\n');
|
||||
window.postMessage({
|
||||
type: requestId,
|
||||
success: true,
|
||||
text: text
|
||||
}, '*');
|
||||
})
|
||||
.catch(error => {
|
||||
window.postMessage({
|
||||
type: requestId,
|
||||
success: false,
|
||||
error: 'PDF parsing error: ' + (error.message || String(error))
|
||||
}, '*');
|
||||
});
|
||||
} catch (error) {
|
||||
window.postMessage({
|
||||
type: requestId,
|
||||
success: false,
|
||||
error: 'ArrayBuffer error: ' + (error.message || String(error))
|
||||
}, '*');
|
||||
}
|
||||
};
|
||||
|
||||
xhr.onerror = function() {
|
||||
window.postMessage({
|
||||
type: requestId,
|
||||
success: false,
|
||||
error: 'Network error fetching PDF'
|
||||
}, '*');
|
||||
};
|
||||
|
||||
xhr.ontimeout = function() {
|
||||
window.postMessage({
|
||||
type: requestId,
|
||||
success: false,
|
||||
error: 'Timeout fetching PDF'
|
||||
}, '*');
|
||||
};
|
||||
|
||||
xhr.timeout = 30000;
|
||||
xhr.send();
|
||||
} catch (error) {
|
||||
window.postMessage({
|
||||
type: requestId,
|
||||
success: false,
|
||||
error: 'Setup error: ' + (error.message || String(error))
|
||||
}, '*');
|
||||
pdfjsLib.GlobalWorkerOptions.workerSrc = pdfWorkerSrc;
|
||||
|
||||
const response = await fetch(url, {
|
||||
credentials: 'include',
|
||||
redirect: 'follow',
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error('HTTP ' + response.status + ': ' + response.statusText);
|
||||
}
|
||||
|
||||
const arrayBuffer = await response.arrayBuffer();
|
||||
if (!arrayBuffer || arrayBuffer.byteLength === 0) {
|
||||
throw new Error('PDF response is empty');
|
||||
}
|
||||
|
||||
const pdf = await pdfjsLib.getDocument({
|
||||
data: arrayBuffer,
|
||||
useSystemFonts: true,
|
||||
verbosity: 0,
|
||||
useWorkerFetch: false,
|
||||
isEvalSupported: false,
|
||||
}).promise;
|
||||
|
||||
const pages = [];
|
||||
for (let i = 1; i <= pdf.numPages; i++) {
|
||||
const page = await pdf.getPage(i);
|
||||
const content = await page.getTextContent();
|
||||
pages.push(content.items.map((item) => item.str).join(' '));
|
||||
}
|
||||
|
||||
postResult({ success: true, text: pages.join('\\n') });
|
||||
}
|
||||
})();
|
||||
} catch (error) {
|
||||
postResult({
|
||||
success: false,
|
||||
error: 'PDF extraction error: ' + (error?.message || String(error)),
|
||||
});
|
||||
}
|
||||
`;
|
||||
|
||||
const messageHandler = (event: MessageEvent) => {
|
||||
if (event.origin !== pageOrigin || event.source !== window) return;
|
||||
if (event.data?.type === requestId) {
|
||||
window.removeEventListener("message", messageHandler);
|
||||
if (script.parentNode) {
|
||||
@@ -625,9 +653,13 @@ export async function extractPDFText(url: string): Promise<string> {
|
||||
throw new Error("PDF response is empty");
|
||||
}
|
||||
|
||||
ensurePdfjsWorker();
|
||||
const pdf = await pdfjs.getDocument({
|
||||
data: arrayBuffer,
|
||||
useSystemFonts: true,
|
||||
verbosity: 0,
|
||||
useWorkerFetch: false,
|
||||
isEvalSupported: false,
|
||||
}).promise;
|
||||
|
||||
let text = "";
|
||||
@@ -645,23 +677,113 @@ export async function extractPDFText(url: string): Promise<string> {
|
||||
}
|
||||
}
|
||||
|
||||
function randomStudentPdfFileName(): string {
|
||||
// Matches SEQTA Learn coversheet tokens, e.g. "mrr158ct.pdf".
|
||||
return `${Math.random().toString(36).slice(2, 10)}.pdf`;
|
||||
}
|
||||
|
||||
async function requestStudentAssessmentPdf(params: {
|
||||
assessmentID: string | number;
|
||||
metaclassID: string | number;
|
||||
studentID: string | number;
|
||||
}): Promise<string> {
|
||||
const fileName = randomStudentPdfFileName();
|
||||
|
||||
const printResponse = await fetch(
|
||||
`${location.origin}/seqta/student/print/assessment`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json; charset=utf-8" },
|
||||
credentials: "include",
|
||||
body: JSON.stringify({
|
||||
id: Number(params.assessmentID),
|
||||
metaclass: Number(params.metaclassID),
|
||||
student: Number(params.studentID),
|
||||
fileName,
|
||||
}),
|
||||
},
|
||||
);
|
||||
|
||||
if (!printResponse.ok) {
|
||||
throw new Error(
|
||||
`Failed to generate PDF: ${printResponse.status} ${printResponse.statusText}`,
|
||||
);
|
||||
}
|
||||
|
||||
const data = (await printResponse.json()) as {
|
||||
payload?: { file?: string };
|
||||
status?: string | number;
|
||||
};
|
||||
|
||||
const resolved = data.payload?.file;
|
||||
if (!resolved) {
|
||||
throw new Error(
|
||||
`Print assessment response missing payload.file (status=${String(data.status)})`,
|
||||
);
|
||||
}
|
||||
|
||||
return resolved;
|
||||
}
|
||||
|
||||
function getStudentAssessmentReportUrl(fileName: string): string {
|
||||
const params = new URLSearchParams({
|
||||
type: "generated_report",
|
||||
file: fileName,
|
||||
});
|
||||
return `${location.origin}/seqta/student/load/file?${params.toString()}`;
|
||||
}
|
||||
|
||||
async function extractPDFTextWithRetry(
|
||||
url: string,
|
||||
attempts = 3,
|
||||
delayMs = 1500,
|
||||
): Promise<string> {
|
||||
let lastError: unknown;
|
||||
for (let attempt = 0; attempt < attempts; attempt++) {
|
||||
try {
|
||||
return await extractPDFText(url);
|
||||
} catch (error) {
|
||||
lastError = error;
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
const retryable =
|
||||
message.includes("404") ||
|
||||
message.includes("empty") ||
|
||||
message.includes("Failed to fetch PDF");
|
||||
if (!retryable || attempt === attempts - 1) throw error;
|
||||
await new Promise((resolve) => setTimeout(resolve, delayMs));
|
||||
}
|
||||
}
|
||||
throw lastError;
|
||||
}
|
||||
|
||||
async function handleWeightings(mark: any, api: any) {
|
||||
const assessmentID = mark.id;
|
||||
const assessmentID = assessmentIdKey(mark);
|
||||
const metaclassID = mark.metaclassID;
|
||||
const title = mark.title;
|
||||
|
||||
const fingerprint = computeFingerprint(mark);
|
||||
const existing = api.storage.weightings[assessmentID] as
|
||||
| WeightingEntry
|
||||
| undefined;
|
||||
|
||||
const isFresh =
|
||||
// Skip only when we already have a real numeric weight for this fingerprint.
|
||||
// "N/A" / "processing" / in-flight refreshing must not permanently block retries.
|
||||
const hasNumericWeight =
|
||||
existing &&
|
||||
existing.weight !== "processing" &&
|
||||
existing.fingerprint === fingerprint &&
|
||||
existing.pluginVersion === WEIGHTING_SCHEMA_VERSION;
|
||||
existing.weight !== "N/A" &&
|
||||
!Number.isNaN(parseFloat(existing.weight));
|
||||
|
||||
if (isFresh) return;
|
||||
const inFlightSameFingerprint =
|
||||
existing &&
|
||||
existing.fingerprint === fingerprint &&
|
||||
(existing.weight === "processing" || existing.refreshing);
|
||||
|
||||
const isFresh =
|
||||
Boolean(hasNumericWeight) &&
|
||||
existing?.fingerprint === fingerprint &&
|
||||
existing?.pluginVersion === WEIGHTING_SCHEMA_VERSION;
|
||||
|
||||
if (isFresh || inFlightSameFingerprint) return;
|
||||
|
||||
// If we have a previous usable value, keep showing it while we refetch
|
||||
// by marking the entry as refreshing instead of wiping it. We claim the
|
||||
@@ -669,7 +791,7 @@ async function handleWeightings(mark: any, api: any) {
|
||||
// pass (e.g. a fast re-mount of the wrapper) doesn't kick off a duplicate
|
||||
// refetch for the same id while this one is still in flight.
|
||||
const placeholder: WeightingEntry =
|
||||
existing && existing.weight !== "processing"
|
||||
existing && hasNumericWeight
|
||||
? {
|
||||
...existing,
|
||||
fingerprint,
|
||||
@@ -687,10 +809,7 @@ async function handleWeightings(mark: any, api: any) {
|
||||
[assessmentID]: placeholder,
|
||||
};
|
||||
|
||||
api.storage.assessments = {
|
||||
...api.storage.assessments,
|
||||
[title.trim()]: assessmentID,
|
||||
};
|
||||
registerAssessmentLookup(api, mark);
|
||||
|
||||
// Surface the refreshing indicator on the affected row immediately,
|
||||
// without waiting for the PDF fetch to finish.
|
||||
@@ -716,34 +835,13 @@ async function handleWeightings(mark: any, api: any) {
|
||||
const userInfo = await getUserInfo();
|
||||
const userID = userInfo.id;
|
||||
|
||||
const filename =
|
||||
"BetterSEQTA-" +
|
||||
String(Math.floor(Math.random() * 1e15)).padStart(15, "0");
|
||||
|
||||
const printResponse = await fetch(
|
||||
`${location.origin}/seqta/student/print/assessment`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json; charset=utf-8" },
|
||||
credentials: "include",
|
||||
body: JSON.stringify({
|
||||
fileName: filename,
|
||||
id: assessmentID,
|
||||
metaclass: metaclassID,
|
||||
student: userID,
|
||||
}),
|
||||
},
|
||||
);
|
||||
|
||||
if (!printResponse.ok) {
|
||||
throw new Error(
|
||||
`Failed to generate PDF: ${printResponse.status} ${printResponse.statusText}`,
|
||||
);
|
||||
}
|
||||
|
||||
const reportFile = await requestStudentAssessmentPdf({
|
||||
assessmentID,
|
||||
metaclassID,
|
||||
studentID: userID,
|
||||
});
|
||||
await new Promise((resolve) => setTimeout(resolve, 1000));
|
||||
|
||||
pdfUrl = `${location.origin}/seqta/student/report/get?file=${filename}`;
|
||||
pdfUrl = getStudentAssessmentReportUrl(reportFile);
|
||||
}
|
||||
|
||||
if (pdfUrl.startsWith("blob:")) {
|
||||
@@ -752,32 +850,37 @@ async function handleWeightings(mark: any, api: any) {
|
||||
|
||||
let text: string;
|
||||
try {
|
||||
text = await extractPDFText(pdfUrl);
|
||||
text = await extractPDFTextWithRetry(pdfUrl);
|
||||
} catch (error: any) {
|
||||
if (
|
||||
isFirefox &&
|
||||
(error?.message?.includes("blob") ||
|
||||
error?.message?.includes("Security") ||
|
||||
error?.message?.includes("CSP"))
|
||||
error?.message?.includes("CSP") ||
|
||||
error?.message?.includes("empty"))
|
||||
) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 2000));
|
||||
text = await extractPDFText(pdfUrl);
|
||||
text = await extractPDFTextWithRetry(pdfUrl, 2, 2000);
|
||||
} else {
|
||||
throw new Error(`PDF extraction failed: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
const match = text.match(/weight:\s*(\d+\.?\d*)/i);
|
||||
const weight = extractWeightFromCoversheetText(text);
|
||||
|
||||
api.storage.weightings = {
|
||||
...api.storage.weightings,
|
||||
[assessmentID]: {
|
||||
weight: match ? match[1] : "N/A",
|
||||
weight: weight ?? "N/A",
|
||||
fingerprint,
|
||||
pluginVersion: WEIGHTING_SCHEMA_VERSION,
|
||||
},
|
||||
};
|
||||
} catch (error: any) {
|
||||
console.error(
|
||||
`[BetterSEQTA+] Weighting fetch failed for assessment ${assessmentID}:`,
|
||||
error,
|
||||
);
|
||||
api.storage.weightings = {
|
||||
...api.storage.weightings,
|
||||
[assessmentID]: {
|
||||
@@ -813,6 +916,16 @@ export async function processAssessments(api: any, assessmentItems: Element[]) {
|
||||
let hasRefreshingWeighting = false;
|
||||
let count = 0;
|
||||
|
||||
let fiberMarks: MarkLike[] = [];
|
||||
try {
|
||||
const state = await ReactFiber.find(
|
||||
"[class*='AssessmentList__items___']",
|
||||
).getState();
|
||||
fiberMarks = collectMarksFromFiberState(state);
|
||||
} catch {
|
||||
fiberMarks = [];
|
||||
}
|
||||
|
||||
for (const assessmentItem of assessmentItems) {
|
||||
const titleEl = assessmentItem.querySelector(
|
||||
`[class*='AssessmentItem__title___']`,
|
||||
@@ -822,7 +935,11 @@ export async function processAssessments(api: any, assessmentItems: Element[]) {
|
||||
const title = titleEl.textContent?.trim();
|
||||
if (!title) continue;
|
||||
|
||||
const assessmentID = api.storage.assessments?.[title];
|
||||
const assessmentID = await resolveAssessmentId(api, title, fiberMarks);
|
||||
if (assessmentID) {
|
||||
(assessmentItem as HTMLElement).dataset.betterseqtaAssessmentId =
|
||||
assessmentID;
|
||||
}
|
||||
const entry = assessmentID
|
||||
? (api.storage.weightings?.[assessmentID] as WeightingEntry | undefined)
|
||||
: undefined;
|
||||
@@ -833,7 +950,7 @@ export async function processAssessments(api: any, assessmentItems: Element[]) {
|
||||
const weighting = override ?? autoWeighting;
|
||||
const refreshing = !override && Boolean(entry?.refreshing);
|
||||
|
||||
createWeightLabel(assessmentItem, weighting, api, refreshing);
|
||||
createWeightLabel(assessmentItem, weighting, api, refreshing, assessmentID);
|
||||
|
||||
const gradeElement = assessmentItem.querySelector(
|
||||
`[class*='Thermoscore__text___']`,
|
||||
@@ -935,25 +1052,35 @@ function resolveTabSetClasses(): Record<string, string> {
|
||||
return resolved;
|
||||
}
|
||||
|
||||
function buildWeightingsTabContent(api: any, sheet: HTMLElement) {
|
||||
const titleEl = document.querySelector(
|
||||
"[class*='AssessmentItem__AssessmentItem___'][class*='selected___'] [class*='AssessmentItem__title___']",
|
||||
interface WeightingTabContext {
|
||||
assessmentID?: string;
|
||||
autoWeight?: number;
|
||||
override?: number | string;
|
||||
weightingUnavailable: boolean;
|
||||
statusNote: string;
|
||||
}
|
||||
|
||||
async function resolveWeightingTabContext(api: any): Promise<WeightingTabContext> {
|
||||
const selectedItem = document.querySelector(
|
||||
"[class*='AssessmentItem__AssessmentItem___'][class*='selected___']",
|
||||
) as HTMLElement | null;
|
||||
const titleEl = selectedItem?.querySelector(
|
||||
"[class*='AssessmentItem__title___']",
|
||||
);
|
||||
const title = titleEl?.textContent?.trim();
|
||||
const assessmentID = title ? api.storage.assessments?.[title] : undefined;
|
||||
const assessmentID =
|
||||
selectedItem?.dataset.betterseqtaAssessmentId ??
|
||||
(title ? await resolveAssessmentId(api, title) : undefined);
|
||||
|
||||
const entry = assessmentID
|
||||
? (api.storage.weightings?.[assessmentID] as WeightingEntry | undefined)
|
||||
: undefined;
|
||||
const rawWeight = entry?.weight;
|
||||
|
||||
const weightingUnavailable = rawWeight === "N/A";
|
||||
|
||||
const autoWeight =
|
||||
rawWeight && rawWeight !== "processing" && rawWeight !== "N/A"
|
||||
? rawWeight
|
||||
: undefined;
|
||||
|
||||
const override = assessmentID
|
||||
? api.storage.weightingOverrides?.[assessmentID]
|
||||
: undefined;
|
||||
@@ -966,6 +1093,22 @@ function buildWeightingsTabContent(api: any, sheet: HTMLElement) {
|
||||
? "No weighting was found in the marksheet. Set one manually."
|
||||
: "Overrides the auto-detected value.";
|
||||
|
||||
return {
|
||||
assessmentID,
|
||||
autoWeight,
|
||||
override,
|
||||
weightingUnavailable,
|
||||
statusNote,
|
||||
};
|
||||
}
|
||||
|
||||
function renderWeightingTabHtml(
|
||||
sheet: HTMLElement,
|
||||
context: WeightingTabContext,
|
||||
) {
|
||||
const { assessmentID, autoWeight, override, weightingUnavailable, statusNote } =
|
||||
context;
|
||||
|
||||
sheet.innerHTML = `
|
||||
<style>
|
||||
#betterseqta-weight-override::placeholder {
|
||||
@@ -1010,9 +1153,13 @@ function buildWeightingsTabContent(api: any, sheet: HTMLElement) {
|
||||
${!assessmentID ? `<p style="font-size:12px;color:rgba(255,80,80,0.8);margin-top:8px">Assessment not yet indexed — try refreshing.</p>` : ""}
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
if (!assessmentID) return;
|
||||
|
||||
function attachWeightingInputHandlers(
|
||||
sheet: HTMLElement,
|
||||
api: any,
|
||||
assessmentID: string,
|
||||
) {
|
||||
const input = sheet.querySelector(
|
||||
"#betterseqta-weight-override",
|
||||
) as HTMLInputElement;
|
||||
@@ -1022,20 +1169,17 @@ function buildWeightingsTabContent(api: any, sheet: HTMLElement) {
|
||||
|
||||
const save = () => {
|
||||
const raw = input.value.trim();
|
||||
if (raw === "") {
|
||||
const result = saveWeightingOverride(api, assessmentID, "");
|
||||
if (!result.ok) return;
|
||||
input.style.borderColor = "rgba(128,128,128,0.3)";
|
||||
} else {
|
||||
const result = saveWeightingOverride(api, assessmentID, raw);
|
||||
if (!result.ok) {
|
||||
const result = saveWeightingOverride(api, assessmentID, raw);
|
||||
if (!result.ok) {
|
||||
if (raw !== "") {
|
||||
input.style.borderColor = "rgba(255,80,80,0.6)";
|
||||
statusEl.textContent = result.error ?? "Invalid. Must be 0 or greater";
|
||||
statusEl.style.color = "rgba(255,80,80,0.8)";
|
||||
return;
|
||||
}
|
||||
input.style.borderColor = "rgba(128,128,128,0.3)";
|
||||
return;
|
||||
}
|
||||
|
||||
input.style.borderColor = "rgba(128,128,128,0.3)";
|
||||
statusEl.textContent = "Saved";
|
||||
statusEl.style.color = "";
|
||||
setTimeout(() => (statusEl.textContent = ""), 2000);
|
||||
@@ -1055,6 +1199,13 @@ function buildWeightingsTabContent(api: any, sheet: HTMLElement) {
|
||||
});
|
||||
}
|
||||
|
||||
async function buildWeightingsTabContent(api: any, sheet: HTMLElement) {
|
||||
const context = await resolveWeightingTabContext(api);
|
||||
renderWeightingTabHtml(sheet, context);
|
||||
if (!context.assessmentID) return;
|
||||
attachWeightingInputHandlers(sheet, api, context.assessmentID);
|
||||
}
|
||||
|
||||
export function injectWeightingsTab(api: any) {
|
||||
const tabList = document.querySelector(
|
||||
'[class*="TabSet__tabs___"]',
|
||||
@@ -1093,7 +1244,7 @@ export function injectWeightingsTab(api: any) {
|
||||
container.appendChild(newSheet);
|
||||
|
||||
newTab.addEventListener("click", () => {
|
||||
buildWeightingsTabContent(api, newSheet);
|
||||
void buildWeightingsTabContent(api, newSheet);
|
||||
});
|
||||
|
||||
const allTabs = Array.from(tabList.querySelectorAll("li"));
|
||||
@@ -1107,20 +1258,22 @@ export function injectWeightingsTab(api: any) {
|
||||
t.className.includes("TabSet__selected___"),
|
||||
);
|
||||
if (i === currentIndex) return;
|
||||
const goingRight = i > currentIndex;
|
||||
const goingRight = currentIndex < 0 ? true : i > currentIndex;
|
||||
|
||||
allTabs.forEach((t) => {
|
||||
t.className = "";
|
||||
t.setAttribute("aria-selected", "false");
|
||||
});
|
||||
|
||||
allSheets[currentIndex].className = [
|
||||
cls["TabSet__tabsheet___"],
|
||||
cls["TabSet__hidden___"],
|
||||
goingRight
|
||||
? cls["TabSet__disappearToLeft___"]
|
||||
: cls["TabSet__disappearToRight___"],
|
||||
].join(" ");
|
||||
if (currentIndex >= 0) {
|
||||
allSheets[currentIndex].className = [
|
||||
cls["TabSet__tabsheet___"],
|
||||
cls["TabSet__hidden___"],
|
||||
goingRight
|
||||
? cls["TabSet__disappearToLeft___"]
|
||||
: cls["TabSet__disappearToRight___"],
|
||||
].join(" ");
|
||||
}
|
||||
|
||||
allSheets[i].className = [
|
||||
cls["TabSet__tabsheet___"],
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
<script lang="ts">
|
||||
import { determineStatus, formatDate, getGradeValue } from "./utils";
|
||||
import {
|
||||
assessmentHasGradeDisplay,
|
||||
determineStatus,
|
||||
formatDate,
|
||||
getDisplayGrade,
|
||||
getThermoscorePercent,
|
||||
} from "./utils";
|
||||
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
|
||||
import { isSeqtaEngageExperience } from "@/seqta/utils/isSeqtaEngage";
|
||||
import { buildEngageAssessmentPagePath } from "@/seqta/utils/engageAssessmentStudent";
|
||||
@@ -21,28 +27,12 @@
|
||||
|
||||
const HIDDEN_ASSESSMENTS_KEY = "betterseqta-hidden-assessments";
|
||||
|
||||
function percentageToLetter(percentage: number): string {
|
||||
const letterMap: Record<number, string> = {
|
||||
100: "A+",
|
||||
95: "A",
|
||||
90: "A-",
|
||||
85: "B+",
|
||||
80: "B",
|
||||
75: "B-",
|
||||
70: "C+",
|
||||
65: "C",
|
||||
60: "C-",
|
||||
55: "D+",
|
||||
50: "D",
|
||||
45: "D-",
|
||||
40: "E+",
|
||||
35: "E",
|
||||
30: "E-",
|
||||
0: "F",
|
||||
};
|
||||
|
||||
const rounded = Math.ceil(percentage / 5) * 5;
|
||||
return letterMap[rounded] || "F";
|
||||
function isLetterGradeMode(): boolean {
|
||||
const allSettings = settingsState.getAll() as unknown as Record<
|
||||
string,
|
||||
{ lettergrade?: boolean } | undefined
|
||||
>;
|
||||
return allSettings["plugin.assessments-average.settings"]?.lettergrade ?? false;
|
||||
}
|
||||
|
||||
let currentFilters: FilterOptions = {
|
||||
@@ -73,9 +63,7 @@
|
||||
}
|
||||
|
||||
function getAssessmentGrade(a: any): string {
|
||||
const val = getGradeValue(a);
|
||||
if (val === null) return "No grade";
|
||||
return percentageToLetter(val);
|
||||
return getDisplayGrade(a, isLetterGradeMode());
|
||||
}
|
||||
|
||||
function getGroupKey(assessment: any): string {
|
||||
@@ -522,7 +510,7 @@
|
||||
{#if assessment.submitted}
|
||||
<span class="card-label label-submitted" style="background: #10b981; color: white;">Submitted</span>
|
||||
{/if}
|
||||
{#if isCompleted && status === "MARKS_RELEASED" && !assessment.results}
|
||||
{#if isCompleted && status === "MARKS_RELEASED" && !assessmentHasGradeDisplay(assessment)}
|
||||
<span class="card-label label-completed" style="background: #059669; color: white;">Completed</span>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -559,7 +547,7 @@
|
||||
|
||||
<h3 class="assessment-title">{assessment.title}</h3>
|
||||
|
||||
{#if !assessment.results && !isCompleted}
|
||||
{#if !assessmentHasGradeDisplay(assessment) && !isCompleted}
|
||||
<div class="assessment-meta">
|
||||
<div class="due-date {dueDateClass}">
|
||||
<OverviewIcon name="calendar-days" size={14} />
|
||||
@@ -568,18 +556,14 @@
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if assessment.results}
|
||||
{#if assessmentHasGradeDisplay(assessment)}
|
||||
{@const gradeLabel = getDisplayGrade(assessment, isLetterGradeMode())}
|
||||
{@const barPercent = getThermoscorePercent(assessment) ?? 0}
|
||||
<div class="card-footer">
|
||||
<div class="Thermoscore__Thermoscore___WFpL3" style="--fill-colour: {color}">
|
||||
<div style="width: {assessment.results.percentage}%" class="Thermoscore__fill___ojxDI">
|
||||
<div title="{assessment.results.percentage}%" class="Thermoscore__text___XSR_M">
|
||||
{(() => {
|
||||
const allSettings = settingsState.getAll() as unknown as any;
|
||||
const letterGradeSetting = allSettings["plugin.assessments-average.settings"]?.lettergrade;
|
||||
return letterGradeSetting
|
||||
? percentageToLetter(assessment.results.percentage)
|
||||
: `${assessment.results.percentage}%`;
|
||||
})()}
|
||||
<div style="width: {barPercent}%" class="Thermoscore__fill___ojxDI">
|
||||
<div title={gradeLabel} class="Thermoscore__text___XSR_M">
|
||||
{gradeLabel}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -29,6 +29,9 @@ async function fetchJSON(url: string, body: any) {
|
||||
headers: { "Content-Type": "application/json; charset=utf-8" },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
if (!res.ok) {
|
||||
throw new Error(`HTTP ${res.status} for ${url}`);
|
||||
}
|
||||
return res.json();
|
||||
}
|
||||
|
||||
@@ -164,7 +167,7 @@ async function getLearnAssessmentsData(studentId: number) {
|
||||
}
|
||||
|
||||
export async function getAssessmentsData() {
|
||||
if (settingsState.mockNotices) {
|
||||
if (settingsState.hideSensitiveContent) {
|
||||
return getMockAssessmentsData();
|
||||
}
|
||||
|
||||
|
||||
@@ -38,6 +38,9 @@ async function fetchJSON(url: string, body: unknown) {
|
||||
headers: { "Content-Type": "application/json; charset=utf-8" },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
if (!res.ok) {
|
||||
throw new Error(`HTTP ${res.status} for ${url}`);
|
||||
}
|
||||
return res.json();
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { Plugin } from "../../core/types";
|
||||
import { waitForElm } from "@/seqta/utils/waitForElm";
|
||||
import { getAssessmentsData } from "./api";
|
||||
import { renderErrorState, renderGrid, renderSkeletonLoader } from "./ui";
|
||||
import { renderErrorState, renderGrid, renderSkeletonLoader, teardownOverviewUi } from "./ui";
|
||||
import styles from "./styles.css?inline";
|
||||
import { delay } from "@/seqta/utils/delay";
|
||||
import { isSeqtaEngageExperience } from "@/seqta/utils/isSeqtaEngage";
|
||||
@@ -53,7 +53,7 @@ const assessmentsOverviewPlugin: Plugin<{}> = {
|
||||
"Adds an overview option to the assessments page that organizes assessments by status",
|
||||
version: "1.0.0",
|
||||
settings: {},
|
||||
disableToggle: false,
|
||||
disableToggle: true,
|
||||
styles,
|
||||
|
||||
run: async () => {
|
||||
@@ -61,11 +61,14 @@ const assessmentsOverviewPlugin: Plugin<{}> = {
|
||||
const gridItem = document.createElement("li");
|
||||
gridItem.className = "item";
|
||||
gridItem.classList.add(OVERVIEW_MENU_CLASS);
|
||||
gridItem.dataset.betterseqta = "true";
|
||||
const label = document.createElement("label");
|
||||
label.textContent = "Overview";
|
||||
gridItem.appendChild(label);
|
||||
menu.insertBefore(gridItem, menu.firstChild);
|
||||
|
||||
let loadRequestId = 0;
|
||||
|
||||
const menuObserver = new MutationObserver(() => {
|
||||
ensureOverviewMenuPosition(menu, gridItem);
|
||||
});
|
||||
@@ -77,11 +80,24 @@ const assessmentsOverviewPlugin: Plugin<{}> = {
|
||||
|
||||
const clickHandler = (e: Event) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
e.stopImmediatePropagation();
|
||||
void loadGridView();
|
||||
};
|
||||
gridItem.addEventListener("click", clickHandler);
|
||||
gridItem.addEventListener("click", clickHandler, true);
|
||||
|
||||
const popstateHandler = () => {
|
||||
if (isOverviewRoute()) {
|
||||
void loadGridView();
|
||||
} else {
|
||||
loadRequestId += 1;
|
||||
teardownOverviewUi();
|
||||
}
|
||||
};
|
||||
window.addEventListener("popstate", popstateHandler);
|
||||
|
||||
async function loadGridView() {
|
||||
const requestId = ++loadRequestId;
|
||||
await delay(1);
|
||||
|
||||
if (isSeqtaEngageExperience()) {
|
||||
@@ -98,7 +114,7 @@ const assessmentsOverviewPlugin: Plugin<{}> = {
|
||||
}
|
||||
|
||||
const main = document.getElementById("main");
|
||||
if (!main) return;
|
||||
if (!main || requestId !== loadRequestId) return;
|
||||
|
||||
document
|
||||
.querySelectorAll('[data-key="assessments"] .item')
|
||||
@@ -110,17 +126,22 @@ const assessmentsOverviewPlugin: Plugin<{}> = {
|
||||
.querySelector('[data-key="assessments"]')
|
||||
?.classList.add("active");
|
||||
|
||||
main.innerHTML = '<div id="grid-view-container" class="bsplus-overview-host"></div>';
|
||||
main.innerHTML =
|
||||
'<div id="grid-view-container" class="bsplus-overview-host"></div>';
|
||||
const container = document.getElementById(
|
||||
"grid-view-container",
|
||||
) as HTMLElement;
|
||||
|
||||
if (requestId !== loadRequestId) return;
|
||||
|
||||
renderSkeletonLoader(container);
|
||||
|
||||
try {
|
||||
const data = await getAssessmentsData();
|
||||
if (requestId !== loadRequestId) return;
|
||||
renderGrid(container, data);
|
||||
} catch (err) {
|
||||
if (requestId !== loadRequestId) return;
|
||||
console.error("Failed to load assessments:", err);
|
||||
renderErrorState(
|
||||
container,
|
||||
@@ -130,8 +151,11 @@ const assessmentsOverviewPlugin: Plugin<{}> = {
|
||||
}
|
||||
|
||||
return () => {
|
||||
loadRequestId += 1;
|
||||
window.removeEventListener("popstate", popstateHandler);
|
||||
menuObserver.disconnect();
|
||||
gridItem.removeEventListener("click", clickHandler);
|
||||
gridItem.removeEventListener("click", clickHandler, true);
|
||||
teardownOverviewUi();
|
||||
gridItem.remove();
|
||||
};
|
||||
},
|
||||
|
||||
@@ -1,3 +1,8 @@
|
||||
import {
|
||||
approximatePercentFromLetterGrade,
|
||||
extractLetterGradeStringFromPayload,
|
||||
} from "../gradeAnalytics/letterGradeScale";
|
||||
|
||||
export interface OverviewSubject {
|
||||
code: string;
|
||||
programme: number;
|
||||
@@ -62,7 +67,7 @@ export function activeSubjectsFromEngageChild(child: {
|
||||
const seen = new Set<string>();
|
||||
|
||||
for (const term of child.terms ?? []) {
|
||||
if (term.active !== 1) continue;
|
||||
if (!isActiveTermFlag(term.active)) continue;
|
||||
for (const raw of term.subjects ?? []) {
|
||||
const subject = normalizeOverviewSubject(raw);
|
||||
if (!subject) continue;
|
||||
@@ -101,6 +106,34 @@ export function assessmentBelongsToActiveSubjects(
|
||||
return activeSubjects.some((subject) => subject.code === code);
|
||||
}
|
||||
|
||||
export function activeSubjectForAssessment(
|
||||
assessment: Record<string, unknown>,
|
||||
activeSubjects: OverviewSubject[],
|
||||
): OverviewSubject | undefined {
|
||||
const programme = Number(
|
||||
assessment.programmeID ?? assessment.programme,
|
||||
);
|
||||
const metaclass = Number(
|
||||
assessment.metaclassID ?? assessment.metaclass,
|
||||
);
|
||||
|
||||
if (
|
||||
programme &&
|
||||
metaclass &&
|
||||
!Number.isNaN(programme) &&
|
||||
!Number.isNaN(metaclass)
|
||||
) {
|
||||
const subject = activeSubjects.find(
|
||||
(s) => s.programme === programme && s.metaclass === metaclass,
|
||||
);
|
||||
if (subject) return subject;
|
||||
}
|
||||
|
||||
const code = String(assessment.code ?? assessment.subject ?? "").trim();
|
||||
if (!code) return undefined;
|
||||
return activeSubjects.find((s) => s.code === code);
|
||||
}
|
||||
|
||||
export function filterAssessmentsForActiveSubjects<T extends Record<string, unknown>>(
|
||||
assessments: T[],
|
||||
activeSubjects: OverviewSubject[],
|
||||
@@ -110,6 +143,24 @@ export function filterAssessmentsForActiveSubjects<T extends Record<string, unkn
|
||||
);
|
||||
}
|
||||
|
||||
/** Active subjects that have at least one assessment in the given list. */
|
||||
export function subjectsWithUpcomingAssessments(
|
||||
assessments: Record<string, unknown>[],
|
||||
activeSubjects: OverviewSubject[],
|
||||
): OverviewSubject[] {
|
||||
const result: OverviewSubject[] = [];
|
||||
const seen = new Set<string>();
|
||||
|
||||
for (const assessment of assessments) {
|
||||
const subject = activeSubjectForAssessment(assessment, activeSubjects);
|
||||
if (!subject || seen.has(subject.code)) continue;
|
||||
seen.add(subject.code);
|
||||
result.push(subject);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
export function formatDate(dateStr: string, submitted?: boolean): string {
|
||||
const d = new Date(dateStr);
|
||||
const now = new Date();
|
||||
@@ -151,7 +202,14 @@ export function determineStatus(item: any): string {
|
||||
}
|
||||
|
||||
const completedKey = "betterseqta-completed-assessments";
|
||||
const completed = JSON.parse(localStorage.getItem(completedKey) || "[]");
|
||||
let completed: unknown[] = [];
|
||||
try {
|
||||
const raw = localStorage.getItem(completedKey);
|
||||
const parsed = raw ? JSON.parse(raw) : [];
|
||||
completed = Array.isArray(parsed) ? parsed : [];
|
||||
} catch {
|
||||
completed = [];
|
||||
}
|
||||
if (completed.includes(item.id)) {
|
||||
return "MARKS_RELEASED";
|
||||
}
|
||||
@@ -211,3 +269,73 @@ export function getGradeValue(assessment: any): number | null {
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export function extractAssessmentLetterGrade(assessment: any): string | undefined {
|
||||
if (assessment?.grade != null && String(assessment.grade).trim() !== "") {
|
||||
return String(assessment.grade).trim();
|
||||
}
|
||||
return extractLetterGradeStringFromPayload(assessment);
|
||||
}
|
||||
|
||||
export function percentageToLetterGrade(percentage: number): string {
|
||||
const letterMap: Record<number, string> = {
|
||||
100: "A+",
|
||||
95: "A",
|
||||
90: "A-",
|
||||
85: "B+",
|
||||
80: "B",
|
||||
75: "B-",
|
||||
70: "C+",
|
||||
65: "C",
|
||||
60: "C-",
|
||||
55: "D+",
|
||||
50: "D",
|
||||
45: "D-",
|
||||
40: "E+",
|
||||
35: "E",
|
||||
30: "E-",
|
||||
0: "F",
|
||||
};
|
||||
|
||||
const rounded = Math.ceil(percentage / 5) * 5;
|
||||
return letterMap[rounded] || "F";
|
||||
}
|
||||
|
||||
export function getThermoscorePercent(assessment: any): number | null {
|
||||
const numeric = getGradeValue(assessment);
|
||||
if (numeric !== null) return numeric;
|
||||
|
||||
const letter = extractAssessmentLetterGrade(assessment);
|
||||
if (letter) {
|
||||
const approx = approximatePercentFromLetterGrade(letter);
|
||||
if (approx !== undefined) return approx;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export function getDisplayGrade(assessment: any, letterGradeMode: boolean): string {
|
||||
if (letterGradeMode) {
|
||||
const letter = extractAssessmentLetterGrade(assessment);
|
||||
if (letter) return letter;
|
||||
|
||||
const val = getGradeValue(assessment);
|
||||
if (val !== null) return percentageToLetterGrade(val);
|
||||
|
||||
return "No grade";
|
||||
}
|
||||
|
||||
const val = getGradeValue(assessment);
|
||||
if (val !== null) return `${val}%`;
|
||||
|
||||
const letter = extractAssessmentLetterGrade(assessment);
|
||||
if (letter) return letter;
|
||||
|
||||
return "No grade";
|
||||
}
|
||||
|
||||
export function assessmentHasGradeDisplay(assessment: any): boolean {
|
||||
if (extractAssessmentLetterGrade(assessment)) return true;
|
||||
if (getGradeValue(assessment) !== null) return true;
|
||||
return false;
|
||||
}
|
||||
@@ -1,5 +1,10 @@
|
||||
import type { Plugin } from "@/plugins/core/types";
|
||||
import { booleanSetting, componentSetting, defineSettings, numberSetting } from "@/plugins/core/settingsHelpers";
|
||||
import {
|
||||
booleanSetting,
|
||||
componentSetting,
|
||||
defineSettings,
|
||||
numberSetting,
|
||||
} from "@/plugins/core/settingsHelpers";
|
||||
import styles from "./styles.css?inline";
|
||||
import BackgroundMusicSetting from "./BackgroundMusicSetting.svelte";
|
||||
import localforage from "localforage";
|
||||
@@ -20,7 +25,8 @@ const settings = defineSettings({
|
||||
}),
|
||||
pauseOnHidden: booleanSetting({
|
||||
title: "Pause when tab hidden",
|
||||
description: "Pause music when switching to another tab or minimizing the browser",
|
||||
description:
|
||||
"Pause music when switching to another tab or minimizing the browser",
|
||||
default: true,
|
||||
}),
|
||||
});
|
||||
@@ -30,70 +36,144 @@ const store = localforage.createInstance({
|
||||
storeName: "music",
|
||||
});
|
||||
|
||||
let currentAudio: HTMLAudioElement | null = null;
|
||||
let currentObjectUrl: string | null = null;
|
||||
let cleanupRegistered = false;
|
||||
let pendingGestureCancel: (() => void) | null = null;
|
||||
let visibilityResumeTimeout: number | null = null;
|
||||
const GESTURE_EVENTS = ["pointerdown", "keydown", "touchstart"] as const;
|
||||
const gestureOpts: AddEventListenerOptions = { capture: true, passive: true };
|
||||
|
||||
async function loadAudioBlob(): Promise<Blob | null> {
|
||||
let audio: HTMLAudioElement | null = null;
|
||||
let objectUrl: string | null = null;
|
||||
let gestureCleanup: (() => void) | null = null;
|
||||
let resumeTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let hintEl: HTMLElement | null = null;
|
||||
let gesturePending = false;
|
||||
let ensureInFlight: Promise<void> | null = null;
|
||||
|
||||
const clamp = (v: number) => Math.max(0, Math.min(1, v));
|
||||
|
||||
async function waitForBody(): Promise<HTMLElement> {
|
||||
if (document.body) return document.body;
|
||||
await new Promise<void>((resolve) => {
|
||||
const observer = new MutationObserver(() => {
|
||||
if (document.body) {
|
||||
observer.disconnect();
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
observer.observe(document.documentElement, { childList: true });
|
||||
});
|
||||
return document.body!;
|
||||
}
|
||||
|
||||
function clearHint(): void {
|
||||
hintEl?.remove();
|
||||
hintEl = null;
|
||||
}
|
||||
|
||||
function disarmGesture(): void {
|
||||
gestureCleanup?.();
|
||||
gestureCleanup = null;
|
||||
gesturePending = false;
|
||||
}
|
||||
|
||||
function stopAudio(): void {
|
||||
audio?.pause();
|
||||
audio?.remove();
|
||||
audio = null;
|
||||
if (objectUrl) URL.revokeObjectURL(objectUrl);
|
||||
objectUrl = null;
|
||||
}
|
||||
|
||||
/** Prepare <audio> so play() can run synchronously inside a user-gesture handler. */
|
||||
async function prepareAudio(vol: number): Promise<boolean> {
|
||||
const blob = await store.getItem<Blob>("audio-blob");
|
||||
return blob && blob instanceof Blob ? blob : null;
|
||||
if (!(blob instanceof Blob)) {
|
||||
stopAudio();
|
||||
clearHint();
|
||||
return false;
|
||||
}
|
||||
|
||||
const body = await waitForBody();
|
||||
|
||||
if (!audio) {
|
||||
stopAudio();
|
||||
objectUrl = URL.createObjectURL(blob);
|
||||
audio = new Audio(objectUrl);
|
||||
audio.loop = true;
|
||||
audio.preload = "auto";
|
||||
audio.style.display = "none";
|
||||
body.append(audio);
|
||||
}
|
||||
audio.volume = clamp(vol);
|
||||
return true;
|
||||
}
|
||||
|
||||
function stopAndCleanupAudio(): void {
|
||||
if (currentAudio) {
|
||||
currentAudio.pause();
|
||||
currentAudio.src = "";
|
||||
currentAudio.remove();
|
||||
currentAudio = null;
|
||||
}
|
||||
if (currentObjectUrl) {
|
||||
URL.revokeObjectURL(currentObjectUrl);
|
||||
currentObjectUrl = null;
|
||||
}
|
||||
function attemptPlay(vol: number): Promise<boolean> {
|
||||
if (!audio) return Promise.resolve(false);
|
||||
audio.volume = clamp(vol);
|
||||
return audio
|
||||
.play()
|
||||
.then(() => {
|
||||
disarmGesture();
|
||||
clearHint();
|
||||
return true;
|
||||
})
|
||||
.catch(() => false);
|
||||
}
|
||||
|
||||
function ensureGestureStart(handler: () => void): () => void {
|
||||
const eventTypes = ["pointerdown", "keydown", "touchstart"]; // broad user gesture coverage
|
||||
const listener = () => {
|
||||
handler();
|
||||
for (const type of eventTypes) {
|
||||
window.removeEventListener(type, listener);
|
||||
/** Must stay synchronous — any await before play() drops user activation. */
|
||||
function playFromUserGesture(vol: number): void {
|
||||
if (!audio) {
|
||||
gesturePending = true;
|
||||
return;
|
||||
}
|
||||
audio.volume = clamp(vol);
|
||||
void audio.play().then(
|
||||
() => {
|
||||
disarmGesture();
|
||||
clearHint();
|
||||
},
|
||||
() => {
|
||||
// Keep listeners armed; show hint if somehow missing.
|
||||
if (!hintEl) showHint(() => playFromUserGesture(vol));
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
function showHint(onActivate: () => void): void {
|
||||
clearHint();
|
||||
if (!document.body) return;
|
||||
const hint = document.createElement("button");
|
||||
hint.id = "bsplus-bg-music-hint";
|
||||
hint.type = "button";
|
||||
hint.className = "bsplus-bg-music-hint";
|
||||
hint.textContent = "Tap to start background music";
|
||||
hint.addEventListener("pointerdown", (e) => {
|
||||
e.preventDefault();
|
||||
onActivate();
|
||||
});
|
||||
document.body.append(hint);
|
||||
hintEl = hint;
|
||||
}
|
||||
|
||||
function armGesture(onGesture: () => void): void {
|
||||
disarmGesture();
|
||||
const listener = (event: Event) => {
|
||||
if (event.type === "keydown") {
|
||||
const key = (event as KeyboardEvent).key;
|
||||
if (key !== "Enter" && key !== " ") return;
|
||||
}
|
||||
onGesture();
|
||||
};
|
||||
for (const type of GESTURE_EVENTS) {
|
||||
window.addEventListener(type, listener, gestureOpts);
|
||||
document.addEventListener(type, listener, gestureOpts);
|
||||
}
|
||||
gestureCleanup = () => {
|
||||
for (const type of GESTURE_EVENTS) {
|
||||
window.removeEventListener(type, listener, gestureOpts);
|
||||
document.removeEventListener(type, listener, gestureOpts);
|
||||
}
|
||||
};
|
||||
for (const type of eventTypes) {
|
||||
window.addEventListener(type, listener, { once: true, passive: true });
|
||||
}
|
||||
return () => {
|
||||
for (const type of eventTypes) {
|
||||
window.removeEventListener(type, listener);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
async function startPlayback(volume: number): Promise<void> {
|
||||
const blob = await loadAudioBlob();
|
||||
if (!blob) return;
|
||||
|
||||
stopAndCleanupAudio();
|
||||
|
||||
currentObjectUrl = URL.createObjectURL(blob);
|
||||
const audio = new Audio(currentObjectUrl);
|
||||
audio.loop = true;
|
||||
audio.volume = Math.max(0, Math.min(1, volume));
|
||||
audio.preload = "auto";
|
||||
audio.crossOrigin = "anonymous";
|
||||
audio.style.display = "none";
|
||||
document.body.appendChild(audio);
|
||||
currentAudio = audio;
|
||||
|
||||
try {
|
||||
// Attempt immediate play; may be blocked until gesture
|
||||
await audio.play();
|
||||
} catch {
|
||||
// Ignore; will be started after gesture if enabled
|
||||
}
|
||||
showHint(onGesture);
|
||||
}
|
||||
|
||||
const backgroundMusicPlugin: Plugin<typeof settings> = {
|
||||
@@ -109,74 +189,117 @@ const backgroundMusicPlugin: Plugin<typeof settings> = {
|
||||
run: async (api) => {
|
||||
await api.storage.loaded;
|
||||
|
||||
// react to specific setting changes
|
||||
api.settings.onChange("volume" as any, (value: any) => {
|
||||
const vol = (typeof value === "number" ? value : 0.5) as number;
|
||||
if (currentAudio) currentAudio.volume = Math.max(0, Math.min(1, vol));
|
||||
type BgSettings = { volume?: number; pauseOnHidden?: boolean };
|
||||
const vol = () => (api.settings as BgSettings).volume ?? 0.5;
|
||||
const pauseOnHidden = () =>
|
||||
(api.settings as BgSettings).pauseOnHidden ?? true;
|
||||
|
||||
const runEnsurePlayback = async () => {
|
||||
if (!(await prepareAudio(vol()))) return;
|
||||
|
||||
if (audio && !audio.paused) {
|
||||
disarmGesture();
|
||||
clearHint();
|
||||
return;
|
||||
}
|
||||
|
||||
// Arm unlock before autoplay so the next click/key can call play()
|
||||
// synchronously (async gaps drop user activation).
|
||||
if (!gestureCleanup) {
|
||||
armGesture(() => playFromUserGesture(vol()));
|
||||
}
|
||||
|
||||
if (gesturePending) {
|
||||
gesturePending = false;
|
||||
playFromUserGesture(vol());
|
||||
if (audio && !audio.paused) return;
|
||||
}
|
||||
|
||||
if (await attemptPlay(vol())) return;
|
||||
|
||||
// Retry after load — some browsers allow autoplay once the page settles
|
||||
// or Media Engagement Index applies from prior visits.
|
||||
for (const delayMs of [500, 1500, 3000]) {
|
||||
await new Promise((resolve) => setTimeout(resolve, delayMs));
|
||||
if (!audio || !audio.paused) return;
|
||||
if (await attemptPlay(vol())) return;
|
||||
}
|
||||
};
|
||||
|
||||
const ensurePlayback = () => {
|
||||
if (!ensureInFlight) {
|
||||
ensureInFlight = runEnsurePlayback().finally(() => {
|
||||
ensureInFlight = null;
|
||||
});
|
||||
}
|
||||
return ensureInFlight;
|
||||
};
|
||||
|
||||
api.settings.onChange("volume" as never, (value: unknown) => {
|
||||
if (typeof value === "number" && audio) audio.volume = clamp(value);
|
||||
});
|
||||
|
||||
api.settings.onChange("pauseOnHidden" as any, (value: any) => {
|
||||
const pauseOnHidden = (typeof value === "boolean" ? value : true) as boolean;
|
||||
// If the setting is disabled and audio is currently paused due to tab being hidden, resume it
|
||||
if (!pauseOnHidden && currentAudio && currentAudio.paused && document.visibilityState === "hidden") {
|
||||
currentAudio.play().catch(() => {});
|
||||
api.settings.onChange("pauseOnHidden" as never, (value: unknown) => {
|
||||
if (
|
||||
value === false &&
|
||||
audio?.paused &&
|
||||
document.visibilityState === "visible"
|
||||
) {
|
||||
void ensurePlayback();
|
||||
}
|
||||
});
|
||||
|
||||
// Note: Stop button/event removed by user; no stop handling needed
|
||||
|
||||
// Start if we have audio and autoplay is enabled
|
||||
const tryStart = async () => {
|
||||
const vol = (api.settings as any).volume ?? 0.5;
|
||||
await startPlayback(vol);
|
||||
};
|
||||
|
||||
// Always arm gesture start and attempt immediate start
|
||||
const cancel = ensureGestureStart(() => { tryStart(); });
|
||||
cleanupRegistered = true;
|
||||
(window as any).__betterseqta_bg_music_cancel__ = cancel;
|
||||
tryStart();
|
||||
|
||||
// Pause on tab hide, resume on show with a small delay (if enabled)
|
||||
const visHandler = () => {
|
||||
if (!currentAudio) return;
|
||||
const pauseOnHidden = (api.settings as any).pauseOnHidden ?? true;
|
||||
if (!pauseOnHidden) return;
|
||||
const onVisibility = () => {
|
||||
if (document.visibilityState === "hidden") {
|
||||
if (visibilityResumeTimeout !== null) {
|
||||
clearTimeout(visibilityResumeTimeout);
|
||||
visibilityResumeTimeout = null;
|
||||
}
|
||||
currentAudio.pause();
|
||||
} else if (document.visibilityState === "visible") {
|
||||
if (visibilityResumeTimeout !== null) {
|
||||
clearTimeout(visibilityResumeTimeout);
|
||||
}
|
||||
visibilityResumeTimeout = window.setTimeout(() => {
|
||||
visibilityResumeTimeout = null;
|
||||
currentAudio?.play().catch(() => {});
|
||||
}, 200);
|
||||
if (!pauseOnHidden() || !audio) return;
|
||||
if (resumeTimer) clearTimeout(resumeTimer);
|
||||
resumeTimer = null;
|
||||
audio.pause();
|
||||
return;
|
||||
}
|
||||
if (!audio) {
|
||||
void ensurePlayback();
|
||||
return;
|
||||
}
|
||||
if (!pauseOnHidden()) return;
|
||||
if (resumeTimer) clearTimeout(resumeTimer);
|
||||
resumeTimer = setTimeout(() => {
|
||||
resumeTimer = null;
|
||||
void ensurePlayback();
|
||||
}, 200);
|
||||
};
|
||||
document.addEventListener("visibilitychange", visHandler);
|
||||
|
||||
// Allow uploads to trigger refresh
|
||||
const uploadedHandler = () => {
|
||||
const vol = (api.settings as any).volume ?? 0.5;
|
||||
startPlayback(vol);
|
||||
const onUpdated = () => void ensurePlayback();
|
||||
const onStop = () => {
|
||||
disarmGesture();
|
||||
clearHint();
|
||||
stopAudio();
|
||||
};
|
||||
window.addEventListener("betterseqta-background-music-updated", uploadedHandler);
|
||||
|
||||
const pageChange = api.seqta.onPageChange(() => {
|
||||
void ensurePlayback();
|
||||
});
|
||||
|
||||
document.addEventListener("visibilitychange", onVisibility);
|
||||
window.addEventListener("pageshow", onUpdated);
|
||||
window.addEventListener("betterseqta-background-music-updated", onUpdated);
|
||||
window.addEventListener("betterseqta-background-music-stop", onStop);
|
||||
|
||||
void ensurePlayback();
|
||||
|
||||
return () => {
|
||||
document.removeEventListener("visibilitychange", visHandler);
|
||||
window.removeEventListener("betterseqta-background-music-updated", uploadedHandler);
|
||||
if (cleanupRegistered && (window as any).__betterseqta_bg_music_cancel__) {
|
||||
(window as any).__betterseqta_bg_music_cancel__();
|
||||
(window as any).__betterseqta_bg_music_cancel__ = undefined;
|
||||
}
|
||||
if (pendingGestureCancel) { pendingGestureCancel(); pendingGestureCancel = null; }
|
||||
if (visibilityResumeTimeout !== null) { clearTimeout(visibilityResumeTimeout); visibilityResumeTimeout = null; }
|
||||
stopAndCleanupAudio();
|
||||
pageChange.unregister();
|
||||
document.removeEventListener("visibilitychange", onVisibility);
|
||||
window.removeEventListener("pageshow", onUpdated);
|
||||
window.removeEventListener(
|
||||
"betterseqta-background-music-updated",
|
||||
onUpdated,
|
||||
);
|
||||
window.removeEventListener("betterseqta-background-music-stop", onStop);
|
||||
if (resumeTimer) clearTimeout(resumeTimer);
|
||||
disarmGesture();
|
||||
clearHint();
|
||||
stopAudio();
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
@@ -1,2 +1,14 @@
|
||||
.background-music-hidden{display:none}
|
||||
|
||||
.bsplus-bg-music-hint {
|
||||
position: fixed;
|
||||
bottom: 1rem;
|
||||
left: 1rem;
|
||||
z-index: 2147483000;
|
||||
padding: 0.5rem 0.875rem;
|
||||
border: 1px solid color-mix(in srgb, var(--better-main, #22c55e) 55%, transparent);
|
||||
border-radius: 999px;
|
||||
background: color-mix(in srgb, var(--theme-primary, #1a1a1a) 92%, black 8%);
|
||||
color: var(--text-primary, #fff);
|
||||
font: 600 0.8125rem/1.25 system-ui, sans-serif;
|
||||
cursor: pointer;
|
||||
box-shadow: 0 8px 24px rgb(0 0 0 / 0.35);
|
||||
}
|
||||
@@ -255,9 +255,9 @@ const watchNavigator = (navigator: Element, onChange: () => void) => {
|
||||
return observer;
|
||||
};
|
||||
|
||||
const handleSlidePane = (pane: Element) => {
|
||||
const handleSlidePane = (pane: Element): (() => void) => {
|
||||
const navigator = pane.querySelector(".navigator");
|
||||
if (!navigator) return;
|
||||
if (!navigator) return () => {};
|
||||
|
||||
requestAnimationFrame(() => scrollSelectedIntoView(navigator));
|
||||
setTimeout(() => scrollSelectedIntoView(navigator), 50);
|
||||
@@ -272,17 +272,22 @@ const handleSlidePane = (pane: Element) => {
|
||||
childList: true,
|
||||
});
|
||||
|
||||
const cleanup = new MutationObserver((muts) => {
|
||||
const paneCleanup = new MutationObserver((muts) => {
|
||||
muts.forEach((m) => {
|
||||
m.removedNodes.forEach((n) => {
|
||||
if (n === pane) {
|
||||
observer.disconnect();
|
||||
cleanup.disconnect();
|
||||
paneCleanup.disconnect();
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
cleanup.observe(document.body, { childList: true });
|
||||
paneCleanup.observe(document.body, { childList: true });
|
||||
|
||||
return () => {
|
||||
observer.disconnect();
|
||||
paneCleanup.disconnect();
|
||||
};
|
||||
};
|
||||
|
||||
const enhancedNavigationPlugin: Plugin<typeof settings> = {
|
||||
@@ -299,9 +304,12 @@ const enhancedNavigationPlugin: Plugin<typeof settings> = {
|
||||
injectStyles();
|
||||
|
||||
window.addEventListener("resize", positionArrows);
|
||||
window.addEventListener("scroll", positionArrows, true);
|
||||
|
||||
api.seqta.onMount(".course", async (element) => {
|
||||
const navObservers: MutationObserver[] = [];
|
||||
const courseObservers: MutationObserver[] = [];
|
||||
const slidePaneCleanups: Array<() => void> = [];
|
||||
|
||||
const courseMount = api.seqta.onMount(".course", async (element) => {
|
||||
const course = element as HTMLElement;
|
||||
let navObserver: MutationObserver | null = null;
|
||||
|
||||
@@ -318,6 +326,7 @@ const enhancedNavigationPlugin: Plugin<typeof settings> = {
|
||||
}
|
||||
ensureArrows(course);
|
||||
});
|
||||
navObservers.push(navObserver);
|
||||
return true;
|
||||
};
|
||||
|
||||
@@ -325,6 +334,7 @@ const enhancedNavigationPlugin: Plugin<typeof settings> = {
|
||||
const courseObserver = new MutationObserver(() => {
|
||||
if (setup()) courseObserver.disconnect();
|
||||
});
|
||||
courseObservers.push(courseObserver);
|
||||
courseObserver.observe(course, { childList: true, subtree: true });
|
||||
}
|
||||
});
|
||||
@@ -334,13 +344,20 @@ const enhancedNavigationPlugin: Plugin<typeof settings> = {
|
||||
m.addedNodes.forEach((n) => {
|
||||
if (n.nodeType !== 1) return;
|
||||
const el = n as Element;
|
||||
if (el.classList?.contains("uiSlidePane")) handleSlidePane(el);
|
||||
if (el.classList?.contains("uiSlidePane")) {
|
||||
slidePaneCleanups.push(handleSlidePane(el));
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
bodyObserver.observe(document.body, { childList: true });
|
||||
|
||||
return () => {
|
||||
window.removeEventListener("resize", positionArrows);
|
||||
courseMount.unregister();
|
||||
navObservers.forEach((observer) => observer.disconnect());
|
||||
courseObservers.forEach((observer) => observer.disconnect());
|
||||
slidePaneCleanups.forEach((cleanup) => cleanup());
|
||||
bodyObserver.disconnect();
|
||||
document.getElementById(ARROW_CONTAINER_ID)?.remove();
|
||||
document.getElementById(STYLE_ID)?.remove();
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import { defineLazyPlugin } from "../../core/dynamicLoader";
|
||||
import { booleanSetting, defineSettings } from "../../core/settingsHelpers";
|
||||
|
||||
const settings = defineSettings({
|
||||
autoScrollOnClick: booleanSetting({
|
||||
default: false,
|
||||
title: "Auto-scroll navigator on click",
|
||||
description:
|
||||
"When you click a lesson directly in the side panel, automatically scroll it to the centre. The prev/next arrows always centre the selected lesson regardless of this setting.",
|
||||
}),
|
||||
});
|
||||
|
||||
export default defineLazyPlugin({
|
||||
id: "enhanced-navigation",
|
||||
name: "Enhanced Navigation",
|
||||
description:
|
||||
"Keeps the course navigator focused on the current lesson and adds prev/next lesson arrows.",
|
||||
version: "1.0.0",
|
||||
disableToggle: true,
|
||||
settings,
|
||||
beta: false,
|
||||
loader: () => import("./index"),
|
||||
});
|
||||
@@ -7,17 +7,15 @@ import {
|
||||
} from "../../core/settingsHelpers";
|
||||
import { isSeqtaEngageExperience } from "@/seqta/utils/isSeqtaEngage";
|
||||
import styles from "./src/core/styles.css?inline";
|
||||
import { resetSearchIndexes } from "./src/indexing/resetIndexes";
|
||||
|
||||
// Platform-aware default hotkey
|
||||
const getDefaultHotkey = () => {
|
||||
const isMac = navigator.platform.toUpperCase().indexOf('MAC') >= 0;
|
||||
return isMac ? "cmd+k" : "ctrl+k";
|
||||
};
|
||||
import {
|
||||
resetSearchIndexes,
|
||||
notifyOpenTabsResetSearchIndex,
|
||||
} from "./src/indexing/resetIndexes";
|
||||
import { getDefaultSearchHotkey } from "./src/utils/hotkeyUtils";
|
||||
|
||||
const settings = defineSettings({
|
||||
searchHotkey: hotkeySetting({
|
||||
default: getDefaultHotkey(),
|
||||
default: getDefaultSearchHotkey(),
|
||||
title: "Search Hotkey",
|
||||
description: "Keyboard shortcut to open the search",
|
||||
}),
|
||||
@@ -52,9 +50,7 @@ const settings = defineSettings({
|
||||
if (!confirmed) return;
|
||||
|
||||
try {
|
||||
// `resetSearchIndexes` is a tiny statically-imported helper: no
|
||||
// dynamic chunks to chase, so the button keeps working even when
|
||||
// the settings page has been open across an extension update.
|
||||
await notifyOpenTabsResetSearchIndex();
|
||||
await resetSearchIndexes();
|
||||
alert(
|
||||
"Search index and storage were reset.\n\nReload this tab to regenerate the index.",
|
||||
|
||||
@@ -5,15 +5,16 @@
|
||||
import { circOut, quintOut } from 'svelte/easing';
|
||||
import { type StaticCommandItem } from '../core/commands';
|
||||
import type { CombinedResult } from '../core/types';
|
||||
import { createSearchIndexes, performSearch as doSearch } from '../search/searchUtils';
|
||||
import { createSearchIndexes, applyDynamicIndexDelta, performSearch as doSearch, type DynamicItemsUpdatedDetail } from '../search/searchUtils';
|
||||
import Fuse from 'fuse.js';
|
||||
import Calculator from './Calculator.svelte';
|
||||
import { actionMap } from '../indexing/actions';
|
||||
import type { IndexItem } from '../indexing/types';
|
||||
import debounce from 'lodash/debounce';
|
||||
import debounce from '@/seqta/utils/debounce';
|
||||
import { renderComponentMap } from '../indexing/renderComponents';
|
||||
import HighlightedText from '../utils/HighlightedText.svelte';
|
||||
import { matchesHotkey } from '../utils/hotkeyUtils';
|
||||
import { warmUpVectorSearchOnInteraction } from '../search/vector/vectorSearch';
|
||||
import browser from 'webextension-polyfill';
|
||||
|
||||
const {
|
||||
@@ -32,12 +33,6 @@
|
||||
const dynamicIdToItemMap = $state(new Map<string, IndexItem>());
|
||||
const commandIdToItemMap = $state(new Map<string, StaticCommandItem>());
|
||||
|
||||
let isIndexing = $state(false);
|
||||
let completedJobs = $state(0);
|
||||
let totalJobs = $state(0);
|
||||
let indexingStatus = $state<string | null>(null);
|
||||
let indexingDetail = $state<string | null>(null);
|
||||
|
||||
let commandPalleteOpen = $state(false);
|
||||
let searchTerm = $state('');
|
||||
let selectedIndex = $state(0);
|
||||
@@ -99,6 +94,7 @@
|
||||
keydownHandler = (e: KeyboardEvent) => {
|
||||
if (matchesHotkey(e, currentSearchHotkey)) {
|
||||
e.preventDefault();
|
||||
warmUpVectorSearchOnInteraction();
|
||||
commandPalleteOpen = true;
|
||||
tick().then(() => searchbar?.focus());
|
||||
}
|
||||
@@ -118,18 +114,31 @@
|
||||
});
|
||||
|
||||
onMount(() => {
|
||||
const progressHandler = (event: CustomEvent) => {
|
||||
const { completed, total, indexing, status, detail } = event.detail;
|
||||
completedJobs = completed;
|
||||
totalJobs = total;
|
||||
isIndexing = indexing;
|
||||
indexingStatus = status || null;
|
||||
indexingDetail = detail || null;
|
||||
};
|
||||
const itemsUpdatedHandler = (event: Event) => {
|
||||
const detail = (event as CustomEvent<DynamicItemsUpdatedDetail>).detail;
|
||||
|
||||
if (
|
||||
detail?.vectorUpdate &&
|
||||
!detail.changedItems?.length &&
|
||||
!detail.removedIds?.length
|
||||
) {
|
||||
performSearch();
|
||||
return;
|
||||
}
|
||||
|
||||
if (detail?.incremental && !detail.fullRebuild) {
|
||||
const updatedFuse = applyDynamicIndexDelta(
|
||||
dynamicContentFuse,
|
||||
dynamicIdToItemMap,
|
||||
detail,
|
||||
);
|
||||
if (updatedFuse) {
|
||||
dynamicContentFuse = updatedFuse;
|
||||
performSearch();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
window.addEventListener('indexing-progress', progressHandler as EventListener);
|
||||
|
||||
const itemsUpdatedHandler = () => {
|
||||
setupSearchIndexes();
|
||||
performSearch();
|
||||
};
|
||||
@@ -139,11 +148,11 @@
|
||||
|
||||
// @ts-ignore - Intentionally adding to window
|
||||
window.setCommandPalleteOpen = (open: boolean) => {
|
||||
if (open) warmUpVectorSearchOnInteraction();
|
||||
commandPalleteOpen = open;
|
||||
};
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('indexing-progress', progressHandler as EventListener);
|
||||
window.removeEventListener('dynamic-items-updated', itemsUpdatedHandler);
|
||||
};
|
||||
});
|
||||
@@ -159,8 +168,6 @@
|
||||
|
||||
dynamicItems.forEach(item => dynamicIdToItemMap.set(item.id, item));
|
||||
commands.forEach(item => commandIdToItemMap.set(item.id, item));
|
||||
|
||||
console.debug(`[Global Search] Indexed ${commands.length} command items and ${dynamicItems.length} dynamic items.`);
|
||||
}
|
||||
|
||||
const performSearch = async () => {
|
||||
@@ -175,29 +182,35 @@
|
||||
const term = searchTerm.trim().toLowerCase();
|
||||
const requestId = ++searchRequestId;
|
||||
|
||||
if (commandsFuse && dynamicContentFuse) {
|
||||
const results = await doSearch(
|
||||
term,
|
||||
commandsFuse,
|
||||
commandIdToItemMap,
|
||||
dynamicContentFuse,
|
||||
dynamicIdToItemMap,
|
||||
true, // sortByRecent
|
||||
);
|
||||
try {
|
||||
if (commandsFuse && dynamicContentFuse) {
|
||||
const results = await doSearch(
|
||||
term,
|
||||
commandsFuse,
|
||||
commandIdToItemMap,
|
||||
dynamicContentFuse,
|
||||
dynamicIdToItemMap,
|
||||
true, // sortByRecent
|
||||
);
|
||||
|
||||
// Drop the result if the user has typed since this search started, or
|
||||
// if the current term no longer matches what we searched for. This
|
||||
// keeps the visible list anchored to the latest query.
|
||||
if (requestId !== searchRequestId) return;
|
||||
if (searchTerm.trim().toLowerCase() !== term) return;
|
||||
// Drop the result if the user has typed since this search started, or
|
||||
// if the current term no longer matches what we searched for. This
|
||||
// keeps the visible list anchored to the latest query.
|
||||
if (requestId !== searchRequestId) return;
|
||||
if (searchTerm.trim().toLowerCase() !== term) return;
|
||||
|
||||
combinedResults = results;
|
||||
} else {
|
||||
if (requestId !== searchRequestId) return;
|
||||
combinedResults = [];
|
||||
combinedResults = results;
|
||||
} else {
|
||||
if (requestId !== searchRequestId) return;
|
||||
combinedResults = [];
|
||||
}
|
||||
} finally {
|
||||
// Only clear loading for the latest in-flight search — stale async
|
||||
// passes must not leave the spinner stuck after fast typing.
|
||||
if (requestId === searchRequestId) {
|
||||
isLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
isLoading = false;
|
||||
};
|
||||
|
||||
// Optimized debounce: shorter delay for better responsiveness
|
||||
|
||||
@@ -105,7 +105,6 @@ async function navigateToSpecificLesson(lesson: any) {
|
||||
if (lessonDate === todayDateString && lessonPeriod === normalizedLessonPeriod) {
|
||||
// Found the exact matching lesson, click it
|
||||
(lessonElement as HTMLElement).click();
|
||||
console.log(`Navigated to exact lesson: ${lessonDate} ${lessonPeriod}`);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -214,7 +213,7 @@ const staticCommands: StaticCommandItem[] = [
|
||||
code: 'KeyM',
|
||||
keyCode: 77,
|
||||
altKey: true
|
||||
}, "*");
|
||||
}, location.origin);
|
||||
},
|
||||
keywords: ["compose", "message", "dm", "direct message", "new message"],
|
||||
priority: 3,
|
||||
|
||||
@@ -1,202 +1,62 @@
|
||||
import type { Plugin } from "@/plugins/core/types";
|
||||
import { BasePlugin } from "@/plugins/core/settings";
|
||||
import {
|
||||
booleanSetting,
|
||||
buttonSetting,
|
||||
defineSettings,
|
||||
hotkeySetting,
|
||||
Setting,
|
||||
} from "@/plugins/core/settingsHelpers";
|
||||
import { verboseDebug, verboseLog } from "@/utils/verboseLog";
|
||||
import styles from "./styles.css?inline";
|
||||
import { waitForElm } from "@/seqta/utils/waitForElm";
|
||||
import { runIndexing } from "../indexing/indexer";
|
||||
import { initVectorSearch } from "../search/vector/vectorSearch";
|
||||
import { runIndexing, ensureSchemaCurrent } from "../indexing/indexer";
|
||||
import { installResetIndexMessageListener } from "../indexing/resetIndexes";
|
||||
import { isIndexingPaused } from "../indexing/indexingPause";
|
||||
import { cleanupSearchBar, mountSearchBar } from "./mountSearchBar";
|
||||
import { IndexedDbManager } from "embeddia";
|
||||
import { VectorWorkerManager } from "../indexing/worker/vectorWorkerManager";
|
||||
import { checkAndHandleUpdate } from "../utils/versionCheck";
|
||||
import {
|
||||
getStoredPassiveItems,
|
||||
installPassiveObserver,
|
||||
} from "../indexing/passiveObserver";
|
||||
|
||||
// Platform-aware default hotkey
|
||||
const getDefaultHotkey = () => {
|
||||
const isMac = navigator.platform.toUpperCase().indexOf('MAC') >= 0;
|
||||
return isMac ? "cmd+k" : "ctrl+k";
|
||||
};
|
||||
|
||||
const settings = defineSettings({
|
||||
searchHotkey: hotkeySetting({
|
||||
default: getDefaultHotkey(),
|
||||
title: "Search Hotkey",
|
||||
description: "Keyboard shortcut to open the search",
|
||||
}),
|
||||
showRecentFirst: booleanSetting({
|
||||
default: true,
|
||||
title: "Show Recent First",
|
||||
description: "Sort dynamic content by most recent first",
|
||||
}),
|
||||
transparencyEffects: booleanSetting({
|
||||
default: true,
|
||||
title: "Transparency Effects",
|
||||
description: "Enable transparency effects for the search bar",
|
||||
}),
|
||||
runIndexingOnLoad: booleanSetting({
|
||||
default: true,
|
||||
title: "Index on Page Load",
|
||||
description: "Run content indexing when SEQTA loads",
|
||||
}),
|
||||
passiveIndexing: booleanSetting({
|
||||
default: true,
|
||||
title: "Index Browsed Content",
|
||||
description:
|
||||
"Capture safe text from SEQTA pages you visit so they're searchable. Sensitive routes (settings, files, login) are always excluded.",
|
||||
}),
|
||||
resetIndex: buttonSetting({
|
||||
title: "Reset Index",
|
||||
description: "Reset the search index and storage",
|
||||
trigger: async () => {
|
||||
const confirmed = confirm(
|
||||
"Reset the search index and all stored Global Search data?\n\nAfter this, reload this SEQTA tab so indexing can run again and rebuild the index.",
|
||||
);
|
||||
|
||||
if (confirmed) {
|
||||
try {
|
||||
// Import resetDatabase function to properly close connections
|
||||
const { resetDatabase } = await import("../indexing/db");
|
||||
|
||||
// Reset the vector worker first
|
||||
try {
|
||||
const workerManager = VectorWorkerManager.getInstance();
|
||||
await workerManager.resetWorker();
|
||||
console.log("Vector worker reset successfully");
|
||||
} catch (e) {
|
||||
console.warn("Failed to reset vector worker:", e);
|
||||
}
|
||||
|
||||
// Close all database connections properly before deletion
|
||||
try {
|
||||
await resetDatabase();
|
||||
} catch (e) {
|
||||
console.warn("Failed to reset betterseqta-index database:", e);
|
||||
}
|
||||
|
||||
// Wait a bit for connections to fully close
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
|
||||
// Delete embeddiaDB (vector search database)
|
||||
const deleteDb = (dbName: string) => {
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
const req = indexedDB.deleteDatabase(dbName);
|
||||
req.onsuccess = () => {
|
||||
console.log(`Successfully deleted database: ${dbName}`);
|
||||
resolve();
|
||||
};
|
||||
req.onerror = () => {
|
||||
console.error(`Error deleting database ${dbName}:`, req.error);
|
||||
reject(req.error);
|
||||
};
|
||||
req.onblocked = () => {
|
||||
console.warn(`Database ${dbName} deletion blocked - connections still open`);
|
||||
// Wait and retry once
|
||||
setTimeout(() => {
|
||||
const retryReq = indexedDB.deleteDatabase(dbName);
|
||||
retryReq.onsuccess = () => {
|
||||
console.log(`Successfully deleted database on retry: ${dbName}`);
|
||||
resolve();
|
||||
};
|
||||
retryReq.onerror = () => reject(retryReq.error);
|
||||
retryReq.onblocked = () => {
|
||||
reject(new Error(`One database is open, failed to remove: ${dbName}. Please close other tabs and try again.`));
|
||||
};
|
||||
}, 500);
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
try {
|
||||
await deleteDb("embeddiaDB");
|
||||
await deleteDb("betterseqta-index");
|
||||
alert(
|
||||
"Search index and storage were reset.\n\nReload this tab to regenerate the index.",
|
||||
);
|
||||
} catch (e) {
|
||||
alert("Failed to reset one or more databases: " + String(e) + "\n\nTry closing other browser tabs and try again.");
|
||||
}
|
||||
} catch (e) {
|
||||
alert("Failed to reset index: " + String(e));
|
||||
}
|
||||
}
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
class GlobalSearchPlugin extends BasePlugin<typeof settings> {
|
||||
@Setting(settings.searchHotkey)
|
||||
searchHotkey!: string;
|
||||
|
||||
@Setting(settings.showRecentFirst)
|
||||
showRecentFirst!: boolean;
|
||||
|
||||
@Setting(settings.transparencyEffects)
|
||||
transparencyEffects!: boolean;
|
||||
|
||||
@Setting(settings.runIndexingOnLoad)
|
||||
runIndexingOnLoad!: boolean;
|
||||
|
||||
@Setting(settings.passiveIndexing)
|
||||
passiveIndexing!: boolean;
|
||||
|
||||
@Setting(settings.resetIndex)
|
||||
resetIndex!: () => void;
|
||||
}
|
||||
|
||||
const settingsInstance = new GlobalSearchPlugin();
|
||||
|
||||
const globalSearchPlugin: Plugin<typeof settings> = {
|
||||
const globalSearchPlugin: Plugin<{}> = {
|
||||
id: "global-search",
|
||||
name: "Global Search",
|
||||
description: "Quick search for everything in SEQTA",
|
||||
version: "1.0.0",
|
||||
settings: settingsInstance.settings,
|
||||
settings: {},
|
||||
disableToggle: true,
|
||||
defaultEnabled: false,
|
||||
styles: styles,
|
||||
styles,
|
||||
|
||||
run: async (api) => {
|
||||
const appRef = { current: null };
|
||||
|
||||
// Run the version check BEFORE we open any IndexedDB connections.
|
||||
// On a normal load (no version change) this is just a string compare
|
||||
// and a manifest read, so the cost is negligible. On a real update,
|
||||
// we want the database wipe to complete before `IndexedDbManager`
|
||||
// grabs a handle on `embeddiaDB`, otherwise the delete request comes
|
||||
// back blocked.
|
||||
installResetIndexMessageListener();
|
||||
|
||||
try {
|
||||
const wasUpdated = await checkAndHandleUpdate();
|
||||
if (wasUpdated) {
|
||||
console.log(
|
||||
verboseLog(
|
||||
"[Global Search] Extension updated — search index reset; the next indexing pass will repopulate.",
|
||||
);
|
||||
}
|
||||
} catch (error: any) {
|
||||
// Firefox sometimes refuses CSS preloads or asset reads; we never
|
||||
// want this path to take the whole plugin down.
|
||||
const msg = error?.message ?? "";
|
||||
if (
|
||||
error?.message?.includes("preload CSS") ||
|
||||
error?.message?.includes("MIME type") ||
|
||||
error?.message?.includes("NS_ERROR_CORRUPTED_CONTENT")
|
||||
msg.includes("preload CSS") ||
|
||||
msg.includes("MIME type") ||
|
||||
msg.includes("NS_ERROR_CORRUPTED_CONTENT")
|
||||
) {
|
||||
console.debug(
|
||||
verboseDebug(
|
||||
"[Global Search] Version check skipped due to asset loading restrictions:",
|
||||
error.message,
|
||||
msg,
|
||||
);
|
||||
} else {
|
||||
console.warn("[Global Search] Failed to check for updates:", error);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
await ensureSchemaCurrent();
|
||||
} catch (error) {
|
||||
console.warn("[Global Search] Schema check failed:", error);
|
||||
}
|
||||
|
||||
try {
|
||||
await IndexedDbManager.create("embeddiaDB", "embeddiaObjectStore", {
|
||||
primaryKey: "id",
|
||||
@@ -204,69 +64,15 @@ const globalSearchPlugin: Plugin<typeof settings> = {
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Failed to create IndexedDB:", error);
|
||||
// Continue execution - the search might still work without persistence
|
||||
}
|
||||
|
||||
initVectorSearch();
|
||||
|
||||
// Warm up vector worker in background to improve initial response time (skip in Firefox)
|
||||
setTimeout(async () => {
|
||||
try {
|
||||
// Only initialize worker if vector search is supported
|
||||
const { isVectorSearchSupported } = await import("../utils/browserDetection");
|
||||
if (isVectorSearchSupported()) {
|
||||
VectorWorkerManager.getInstance();
|
||||
} else {
|
||||
console.debug("[Global Search] Skipping vector worker warm-up (Firefox detected - using text search only)");
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn("[Global Search] Vector worker warm-up failed:", error);
|
||||
}
|
||||
}, 1000);
|
||||
|
||||
// Add debug helpers to window for troubleshooting
|
||||
// @ts-ignore
|
||||
window.globalSearchDebug = {
|
||||
resetWorker: async () => {
|
||||
const workerManager = VectorWorkerManager.getInstance();
|
||||
await workerManager.resetWorker();
|
||||
console.log("Vector worker reset via debug helper");
|
||||
},
|
||||
checkWorkerStatus: () => {
|
||||
const workerManager = VectorWorkerManager.getInstance();
|
||||
console.log("Streaming active:", workerManager.isStreamingActive());
|
||||
},
|
||||
passiveItems: async () => {
|
||||
const items = await getStoredPassiveItems();
|
||||
console.log(`Captured ${items.length} passive items`);
|
||||
return items;
|
||||
},
|
||||
runSelfTests: async () => {
|
||||
const { runGlobalSearchSelfTests } = await import(
|
||||
"../indexing/selfTests"
|
||||
);
|
||||
return runGlobalSearchSelfTests();
|
||||
},
|
||||
checkIndexedDBSize: async () => {
|
||||
try {
|
||||
const estimate = await navigator.storage.estimate();
|
||||
console.log("Storage estimate:", estimate);
|
||||
|
||||
// Check embeddiaDB size
|
||||
const dbRequest = indexedDB.open("embeddiaDB");
|
||||
dbRequest.onsuccess = () => {
|
||||
const db = dbRequest.result;
|
||||
const transaction = db.transaction(["embeddiaObjectStore"], "readonly");
|
||||
const store = transaction.objectStore("embeddiaObjectStore");
|
||||
const countRequest = store.count();
|
||||
countRequest.onsuccess = () => {
|
||||
console.log("embeddiaDB item count:", countRequest.result);
|
||||
};
|
||||
};
|
||||
} catch (e) {
|
||||
console.error("Error checking storage:", e);
|
||||
}
|
||||
}
|
||||
resetWorker: async () =>
|
||||
(await import("../indexing/worker/vectorWorkerManager")).VectorWorkerManager.getInstance().resetWorker(),
|
||||
passiveItems: getStoredPassiveItems,
|
||||
runSelfTests: async () =>
|
||||
(await import("../indexing/selfTests")).runGlobalSearchSelfTests(),
|
||||
};
|
||||
|
||||
if (api.settings.passiveIndexing) {
|
||||
@@ -277,24 +83,20 @@ const globalSearchPlugin: Plugin<typeof settings> = {
|
||||
}
|
||||
}
|
||||
|
||||
if (api.settings.runIndexingOnLoad) {
|
||||
if (api.settings.runIndexingOnLoad && !isIndexingPaused()) {
|
||||
setTimeout(async () => {
|
||||
await runIndexing();
|
||||
if (!isIndexingPaused()) await runIndexing();
|
||||
}, 2000);
|
||||
}
|
||||
|
||||
const title = document.querySelector("#title");
|
||||
|
||||
if (title) {
|
||||
mountSearchBar(title, api, appRef);
|
||||
void mountSearchBar(title, api, appRef);
|
||||
} else {
|
||||
const titleElement = await waitForElm("#title", true, 100, 60);
|
||||
mountSearchBar(titleElement, api, appRef);
|
||||
void mountSearchBar(await waitForElm("#title", true, 100, 60), api, appRef);
|
||||
}
|
||||
|
||||
return () => {
|
||||
cleanupSearchBar(appRef);
|
||||
};
|
||||
return () => cleanupSearchBar(appRef);
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
import renderSvelte from "@/interface/main";
|
||||
import SearchBar from "../components/SearchBar.svelte";
|
||||
import { unmount } from "svelte";
|
||||
import { VectorWorkerManager } from "../indexing/worker/vectorWorkerManager";
|
||||
import { warmUpVectorSearchOnInteraction } from "../search/vector/vectorSearch";
|
||||
import { formatHotkeyForDisplay, isValidHotkey } from "../utils/hotkeyUtils";
|
||||
import browser from "webextension-polyfill";
|
||||
|
||||
export function mountSearchBar(
|
||||
export async function mountSearchBar(
|
||||
titleElement: Element,
|
||||
api: any,
|
||||
appRef: {
|
||||
@@ -37,6 +36,21 @@ export function mountSearchBar(
|
||||
const searchButton = document.createElement("div");
|
||||
searchButton.className = "search-trigger";
|
||||
|
||||
const searchIcon = document.createElement("span");
|
||||
searchIcon.innerHTML =
|
||||
'<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>';
|
||||
|
||||
const searchLabel = document.createElement("p");
|
||||
searchLabel.textContent = "Quick search...";
|
||||
|
||||
const hotkeySpan = document.createElement("span");
|
||||
hotkeySpan.className = "search-trigger-hotkey";
|
||||
hotkeySpan.style.marginLeft = "auto";
|
||||
hotkeySpan.style.display = "flex";
|
||||
hotkeySpan.style.alignItems = "center";
|
||||
hotkeySpan.style.color = "#777";
|
||||
hotkeySpan.style.fontSize = "12px";
|
||||
|
||||
const progressBarWrapper = document.createElement("div");
|
||||
progressBarWrapper.className = "search-progress-bar-wrapper";
|
||||
|
||||
@@ -94,102 +108,9 @@ export function mountSearchBar(
|
||||
}
|
||||
};
|
||||
|
||||
const updateProgressDisplay = () => {
|
||||
const indexingStoppedThisTick = indexingJustStoppedFlag;
|
||||
indexingJustStoppedFlag = false;
|
||||
|
||||
const active = isIndexing && totalJobs > 0;
|
||||
|
||||
// Stray pulses (missing total, 0 completed, etc.) used to hit the idle
|
||||
// branch and call clearDoneFlashTimer(), killing the Done! hold/fade.
|
||||
if (doneFlashTimer !== null || doneFadeTimer !== null) {
|
||||
if (!active) {
|
||||
return;
|
||||
}
|
||||
clearDoneFlashTimer();
|
||||
}
|
||||
|
||||
const completionEligible =
|
||||
ranIndexingCycle &&
|
||||
!active &&
|
||||
totalJobs > 0 &&
|
||||
(completedJobs >= totalJobs || indexingStoppedThisTick);
|
||||
|
||||
if (active) {
|
||||
clearDoneFlashTimer();
|
||||
progressBarWrapper.classList.remove("is-rough-complete");
|
||||
progressText.classList.remove(
|
||||
"is-rough",
|
||||
"is-fading-done",
|
||||
"is-done-message",
|
||||
);
|
||||
const percentage = Math.round((completedJobs / totalJobs) * 100);
|
||||
progressBar.style.width = `${Math.max(2, percentage)}%`;
|
||||
progressBarWrapper.classList.add("is-active");
|
||||
searchAnchor.classList.add("is-indexing");
|
||||
searchButton.classList.add("is-indexing");
|
||||
|
||||
if (indexingStatus) {
|
||||
progressText.textContent = `${truncateStatus(indexingStatus)} · ${percentage}%`;
|
||||
} else {
|
||||
progressText.textContent = `Indexing ${completedJobs}/${totalJobs} (${percentage}%)`;
|
||||
}
|
||||
progressText.classList.add("is-active");
|
||||
return;
|
||||
}
|
||||
|
||||
if (completionEligible) {
|
||||
// Duplicate end-of-run ticks must not reschedule hold/fade timers
|
||||
if (doneFlashTimer !== null || doneFadeTimer !== null) {
|
||||
return;
|
||||
}
|
||||
|
||||
const rough =
|
||||
indexingStatus != null && statusLooksRough(indexingStatus);
|
||||
|
||||
progressBar.style.width = "0%";
|
||||
progressBarWrapper.classList.remove("is-active");
|
||||
searchAnchor.classList.remove("is-indexing");
|
||||
searchButton.classList.remove("is-indexing");
|
||||
progressText.classList.remove("is-fading-done");
|
||||
|
||||
progressText.textContent = rough ? truncateStatus(indexingStatus!, 52) : "Done!";
|
||||
if (rough) {
|
||||
progressText.classList.add("is-rough");
|
||||
progressBarWrapper.classList.add("is-rough-complete");
|
||||
} else {
|
||||
progressText.classList.remove("is-rough");
|
||||
progressBarWrapper.classList.remove("is-rough-complete");
|
||||
}
|
||||
progressText.classList.add("is-active", "is-done-message");
|
||||
|
||||
doneFlashTimer = setTimeout(() => {
|
||||
doneFlashTimer = null;
|
||||
progressText.classList.add("is-fading-done");
|
||||
doneFadeTimer = setTimeout(() => {
|
||||
doneFadeTimer = null;
|
||||
ranIndexingCycle = false;
|
||||
indexingStatus = null;
|
||||
progressBar.style.width = "0%";
|
||||
progressBarWrapper.classList.remove("is-active");
|
||||
progressBarWrapper.classList.remove("is-rough-complete");
|
||||
searchAnchor.classList.remove("is-indexing");
|
||||
searchButton.classList.remove("is-indexing");
|
||||
progressText.classList.remove(
|
||||
"is-active",
|
||||
"is-rough",
|
||||
"is-fading-done",
|
||||
"is-done-message",
|
||||
);
|
||||
progressText.textContent = "";
|
||||
}, DONE_FADE_MS);
|
||||
}, DONE_HOLD_MS);
|
||||
return;
|
||||
}
|
||||
|
||||
const resetIdleProgressUi = () => {
|
||||
clearDoneFlashTimer();
|
||||
progressBarWrapper.classList.remove("is-active");
|
||||
progressBarWrapper.classList.remove("is-rough-complete");
|
||||
progressBarWrapper.classList.remove("is-active", "is-rough-complete");
|
||||
searchAnchor.classList.remove("is-indexing");
|
||||
searchButton.classList.remove("is-indexing");
|
||||
progressText.classList.remove(
|
||||
@@ -204,6 +125,75 @@ export function mountSearchBar(
|
||||
indexingStatus = null;
|
||||
};
|
||||
|
||||
const showActiveIndexingUi = (percentage: number) => {
|
||||
clearDoneFlashTimer();
|
||||
progressBarWrapper.classList.remove("is-rough-complete");
|
||||
progressText.classList.remove("is-rough", "is-fading-done", "is-done-message");
|
||||
progressBar.style.width = `${Math.max(2, percentage)}%`;
|
||||
progressBarWrapper.classList.add("is-active");
|
||||
searchAnchor.classList.add("is-indexing");
|
||||
searchButton.classList.add("is-indexing");
|
||||
progressText.textContent = indexingStatus
|
||||
? `${truncateStatus(indexingStatus)} · ${percentage}%`
|
||||
: `Indexing ${completedJobs}/${totalJobs} (${percentage}%)`;
|
||||
progressText.classList.add("is-active");
|
||||
};
|
||||
|
||||
const scheduleCompletionFlash = (rough: boolean) => {
|
||||
progressBar.style.width = "0%";
|
||||
progressBarWrapper.classList.remove("is-active");
|
||||
searchAnchor.classList.remove("is-indexing");
|
||||
searchButton.classList.remove("is-indexing");
|
||||
progressText.classList.remove("is-fading-done");
|
||||
progressText.textContent = rough ? truncateStatus(indexingStatus!, 52) : "Done!";
|
||||
progressText.classList.toggle("is-rough", rough);
|
||||
progressBarWrapper.classList.toggle("is-rough-complete", rough);
|
||||
progressText.classList.add("is-active", "is-done-message");
|
||||
|
||||
doneFlashTimer = setTimeout(() => {
|
||||
doneFlashTimer = null;
|
||||
progressText.classList.add("is-fading-done");
|
||||
doneFadeTimer = setTimeout(() => {
|
||||
doneFadeTimer = null;
|
||||
resetIdleProgressUi();
|
||||
}, DONE_FADE_MS);
|
||||
}, DONE_HOLD_MS);
|
||||
};
|
||||
|
||||
const updateProgressDisplay = () => {
|
||||
const indexingStoppedThisTick = indexingJustStoppedFlag;
|
||||
indexingJustStoppedFlag = false;
|
||||
|
||||
const active = isIndexing && totalJobs > 0;
|
||||
|
||||
// Stray pulses (missing total, 0 completed, etc.) used to hit the idle
|
||||
// branch and call clearDoneFlashTimer(), killing the Done! hold/fade.
|
||||
if (doneFlashTimer !== null || doneFadeTimer !== null) {
|
||||
if (!active) return;
|
||||
clearDoneFlashTimer();
|
||||
}
|
||||
|
||||
const completionEligible =
|
||||
ranIndexingCycle &&
|
||||
!active &&
|
||||
totalJobs > 0 &&
|
||||
(completedJobs >= totalJobs || indexingStoppedThisTick);
|
||||
|
||||
if (active) {
|
||||
showActiveIndexingUi(Math.round((completedJobs / totalJobs) * 100));
|
||||
return;
|
||||
}
|
||||
|
||||
if (completionEligible) {
|
||||
if (doneFlashTimer !== null || doneFadeTimer !== null) return;
|
||||
const rough = indexingStatus != null && statusLooksRough(indexingStatus);
|
||||
scheduleCompletionFlash(rough);
|
||||
return;
|
||||
}
|
||||
|
||||
resetIdleProgressUi();
|
||||
};
|
||||
|
||||
// Listen for indexing progress events
|
||||
const progressHandler = (event: CustomEvent) => {
|
||||
const { completed, total, indexing, status } = event.detail as {
|
||||
@@ -234,14 +224,8 @@ export function mountSearchBar(
|
||||
appRef.clearDoneFlashTimer = clearDoneFlashTimer;
|
||||
|
||||
const updateSearchButtonDisplay = () => {
|
||||
searchButton.innerHTML = /* html */ `
|
||||
<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"></circle>
|
||||
<line x1="21" y1="21" x2="16.65" y2="16.65"></line>
|
||||
</svg>
|
||||
<p>Quick search...</p>
|
||||
<span style="margin-left: auto; display: flex; align-items: center; color: #777; font-size: 12px;">${hotkeyDisplay}</span>
|
||||
`;
|
||||
hotkeySpan.textContent = hotkeyDisplay;
|
||||
searchButton.replaceChildren(searchIcon, searchLabel, hotkeySpan);
|
||||
};
|
||||
|
||||
updateSearchButtonDisplay();
|
||||
@@ -269,16 +253,18 @@ export function mountSearchBar(
|
||||
const searchRootShadow = searchRoot.attachShadow({ mode: "open" });
|
||||
|
||||
searchButton.addEventListener("click", () => {
|
||||
warmUpVectorSearchOnInteraction();
|
||||
// @ts-ignore - Intentionally adding to window
|
||||
window.setCommandPalleteOpen(true);
|
||||
});
|
||||
|
||||
try {
|
||||
const { default: renderSvelte } = await import("@/interface/main");
|
||||
appRef.current = renderSvelte(SearchBar, searchRootShadow, {
|
||||
transparencyEffects: api.settings.transparencyEffects ? true : false,
|
||||
transparencyEffects: api.settings.transparencyEffects,
|
||||
showRecentFirst: api.settings.showRecentFirst,
|
||||
searchHotkey: currentHotkey,
|
||||
});
|
||||
}, "content");
|
||||
} catch (error) {
|
||||
console.error("Error rendering Svelte component:", error);
|
||||
}
|
||||
@@ -329,8 +315,10 @@ export function cleanupSearchBar(appRef: {
|
||||
searchRoot.remove();
|
||||
}
|
||||
|
||||
// Clean up vector worker
|
||||
VectorWorkerManager.getInstance().terminate();
|
||||
// Clean up vector worker when it was started (indexing or search interaction)
|
||||
void import("../indexing/worker/vectorWorkerManager").then(({ VectorWorkerManager }) => {
|
||||
VectorWorkerManager.getInstance().terminate();
|
||||
}).catch(() => {});
|
||||
|
||||
if (appRef.storageChangeHandler) {
|
||||
browser.storage.onChanged.removeListener(appRef.storageChangeHandler);
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { IndexItem } from "./types";
|
||||
import ReactFiber from "@/seqta/utils/ReactFiber";
|
||||
import { delay } from "@/seqta/utils/delay";
|
||||
|
||||
import { verboseLog } from '@/utils/verboseLog';
|
||||
interface MessageMetadata {
|
||||
messageId: number;
|
||||
author: string;
|
||||
@@ -171,7 +172,7 @@ export const actionMap: Record<string, ActionHandler<any>> = {
|
||||
if ((assessmentId === undefined || assessmentId === null) && itemClone.id && itemClone.id.startsWith('assignment-')) {
|
||||
const extractedId = itemClone.id.replace('assignment-', '');
|
||||
assessmentId = Number(extractedId) || extractedId;
|
||||
console.log("[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
|
||||
@@ -198,7 +199,7 @@ export const actionMap: Record<string, ActionHandler<any>> = {
|
||||
|
||||
if (hasProgrammeId && hasMetaclassId && hasAssessmentId) {
|
||||
const url = `#?page=/assessments/${programmeId}:${metaclassId}&item=${assessmentId}`;
|
||||
console.log("[Assessment Action] ✅ Navigating to:", url);
|
||||
verboseLog("[Assessment Action] ✅ Navigating to:", url);
|
||||
window.location.hash = url;
|
||||
} else {
|
||||
// Fallback: try to navigate to assessments page if metadata is incomplete
|
||||
@@ -352,9 +353,28 @@ export const actionMap: Record<string, ActionHandler<any>> = {
|
||||
const forumId = num("forumId") ?? num("forum");
|
||||
const year = num("year");
|
||||
const assessmentId =
|
||||
num("assessmentId") ?? num("assessmentID") ?? num("id");
|
||||
num("assessmentId") ??
|
||||
num("assessmentID") ??
|
||||
num("entityId") ??
|
||||
num("id");
|
||||
const messageId = num("messageId");
|
||||
|
||||
const navigateToAssessment = (): void => {
|
||||
if (programme !== undefined && metaclass !== undefined) {
|
||||
const itemSuffix =
|
||||
assessmentId !== undefined ? `&item=${assessmentId}` : "";
|
||||
navigateToHashRoute(
|
||||
`/assessments/${programme}:${metaclass}${itemSuffix}`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (assessmentId !== undefined) {
|
||||
navigateToHashRoute(`/assessments/upcoming&item=${assessmentId}`);
|
||||
return;
|
||||
}
|
||||
navigateToHashRoute("/assessments/upcoming");
|
||||
};
|
||||
|
||||
if (sourcePage === "/messages") {
|
||||
navigateInCurrentSeqtaApp("/messages");
|
||||
return;
|
||||
@@ -368,19 +388,8 @@ export const actionMap: Record<string, ActionHandler<any>> = {
|
||||
}
|
||||
break;
|
||||
case "assessments":
|
||||
if (programme !== undefined && metaclass !== undefined) {
|
||||
const itemSuffix =
|
||||
assessmentId !== undefined ? `&item=${assessmentId}` : "";
|
||||
navigateToHashRoute(
|
||||
`/assessments/${programme}:${metaclass}${itemSuffix}`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (assessmentId !== undefined) {
|
||||
navigateToHashRoute(`/assessments/upcoming&item=${assessmentId}`);
|
||||
return;
|
||||
}
|
||||
navigateToHashRoute("/assessments/upcoming");
|
||||
case "assessment":
|
||||
navigateToAssessment();
|
||||
return;
|
||||
case "forums":
|
||||
case "forum":
|
||||
|
||||
@@ -14,138 +14,214 @@ function updateVersion(version: number) {
|
||||
localStorage.setItem(VERSION_KEY, version.toString());
|
||||
}
|
||||
|
||||
function invalidateConnection(): void {
|
||||
if (cachedDb) {
|
||||
cachedDb.close();
|
||||
cachedDb = null;
|
||||
}
|
||||
dbPromise = null;
|
||||
}
|
||||
|
||||
function attachConnection(db: IDBDatabase): void {
|
||||
if (cachedDb && cachedDb !== db) {
|
||||
cachedDb.close();
|
||||
}
|
||||
cachedDb = db;
|
||||
cachedDb.onclose = () => {
|
||||
cachedDb = null;
|
||||
dbPromise = null;
|
||||
};
|
||||
updateVersion(db.version);
|
||||
}
|
||||
|
||||
function setupUpgradeHandler(
|
||||
request: IDBOpenDBRequest,
|
||||
extraStore?: string,
|
||||
): void {
|
||||
request.onupgradeneeded = (event) => {
|
||||
const db = request.result;
|
||||
|
||||
if (!Array.from(db.objectStoreNames).includes(META_STORE)) {
|
||||
db.createObjectStore(META_STORE);
|
||||
}
|
||||
|
||||
if (extraStore && !db.objectStoreNames.contains(extraStore)) {
|
||||
db.createObjectStore(extraStore);
|
||||
}
|
||||
|
||||
if (event.newVersion != null) {
|
||||
updateVersion(event.newVersion);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function openDatabase(version?: number, extraStore?: string): Promise<IDBDatabase> {
|
||||
return new Promise((resolve, reject) => {
|
||||
let request: IDBOpenDBRequest;
|
||||
try {
|
||||
request =
|
||||
version != null
|
||||
? indexedDB.open(DB_NAME, version)
|
||||
: indexedDB.open(DB_NAME);
|
||||
} catch (error) {
|
||||
reject(error);
|
||||
return;
|
||||
}
|
||||
|
||||
setupUpgradeHandler(request, extraStore);
|
||||
request.onsuccess = () => {
|
||||
attachConnection(request.result);
|
||||
resolve(request.result);
|
||||
};
|
||||
request.onerror = () => reject(request.error);
|
||||
});
|
||||
}
|
||||
|
||||
function wipeDatabase(): Promise<void> {
|
||||
invalidateConnection();
|
||||
localStorage.removeItem(VERSION_KEY);
|
||||
return deleteDatabaseWithRetries(DB_NAME);
|
||||
}
|
||||
|
||||
function deleteDatabaseWithRetries(
|
||||
name: string,
|
||||
maxAttempts = 6,
|
||||
): Promise<void> {
|
||||
return new Promise((resolve) => {
|
||||
const attemptDelete = (attempt: number) => {
|
||||
let req: IDBOpenDBRequest;
|
||||
try {
|
||||
req = indexedDB.deleteDatabase(name);
|
||||
} catch (error) {
|
||||
console.warn(`[DB] Could not start delete of ${name}:`, error);
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
|
||||
req.onsuccess = () => resolve();
|
||||
|
||||
req.onerror = () => {
|
||||
console.warn(`[DB] Error deleting ${name}:`, req.error);
|
||||
if (attempt + 1 < maxAttempts) {
|
||||
setTimeout(() => attemptDelete(attempt + 1), 150 * (attempt + 1));
|
||||
return;
|
||||
}
|
||||
resolve();
|
||||
};
|
||||
|
||||
req.onblocked = () => {
|
||||
console.warn(
|
||||
`[DB] Delete of ${name} blocked (attempt ${attempt + 1}/${maxAttempts}); waiting for connections to close`,
|
||||
);
|
||||
if (attempt + 1 < maxAttempts) {
|
||||
setTimeout(() => attemptDelete(attempt + 1), 200 * (attempt + 1));
|
||||
return;
|
||||
}
|
||||
resolve();
|
||||
};
|
||||
};
|
||||
|
||||
attemptDelete(0);
|
||||
});
|
||||
}
|
||||
|
||||
export function closeSearchDatabase(): void {
|
||||
invalidateConnection();
|
||||
}
|
||||
|
||||
if (typeof window !== "undefined") {
|
||||
window.addEventListener("betterseqta-reset-search-index", () => {
|
||||
closeSearchDatabase();
|
||||
});
|
||||
}
|
||||
|
||||
async function openDBInternal(): Promise<IDBDatabase> {
|
||||
const storedVersion = getCurrentVersion();
|
||||
|
||||
try {
|
||||
return await openDatabase(storedVersion);
|
||||
} catch (error) {
|
||||
const domError = error as DOMException | undefined;
|
||||
|
||||
if (domError?.name === "VersionError") {
|
||||
console.warn(
|
||||
"[DB] localStorage version out of sync with IndexedDB; opening current version",
|
||||
);
|
||||
invalidateConnection();
|
||||
try {
|
||||
return await openDatabase();
|
||||
} catch (fallbackError) {
|
||||
console.warn("[DB] Fallback open failed, recreating database:", fallbackError);
|
||||
}
|
||||
} else {
|
||||
console.error("Error opening database:", error);
|
||||
}
|
||||
|
||||
await wipeDatabase();
|
||||
return openDatabase(1);
|
||||
}
|
||||
}
|
||||
|
||||
function openDB(): Promise<IDBDatabase> {
|
||||
if (cachedDb && cachedDb.version >= getCurrentVersion()) {
|
||||
if (cachedDb) {
|
||||
return Promise.resolve(cachedDb);
|
||||
}
|
||||
|
||||
if (dbPromise) return dbPromise;
|
||||
|
||||
const currentVersion = getCurrentVersion();
|
||||
|
||||
dbPromise = new Promise((resolve, reject) => {
|
||||
let request: IDBOpenDBRequest;
|
||||
|
||||
try {
|
||||
request = indexedDB.open(DB_NAME, currentVersion);
|
||||
} catch (e) {
|
||||
console.warn("Database version conflict, recreating database...");
|
||||
if (cachedDb) {
|
||||
cachedDb.close();
|
||||
cachedDb = null;
|
||||
}
|
||||
indexedDB.deleteDatabase(DB_NAME);
|
||||
localStorage.removeItem(VERSION_KEY);
|
||||
request = indexedDB.open(DB_NAME, 1);
|
||||
updateVersion(1);
|
||||
}
|
||||
|
||||
request.onupgradeneeded = (event) => {
|
||||
const db = request.result;
|
||||
const existingStores = Array.from(db.objectStoreNames);
|
||||
|
||||
if (!existingStores.includes(META_STORE)) {
|
||||
db.createObjectStore(META_STORE);
|
||||
}
|
||||
|
||||
updateVersion(event.newVersion || 1);
|
||||
};
|
||||
|
||||
request.onsuccess = () => {
|
||||
if (cachedDb && cachedDb !== request.result) {
|
||||
cachedDb.close();
|
||||
}
|
||||
cachedDb = request.result;
|
||||
|
||||
cachedDb.onclose = () => {
|
||||
cachedDb = null;
|
||||
dbPromise = null;
|
||||
};
|
||||
|
||||
resolve(request.result);
|
||||
};
|
||||
|
||||
request.onerror = () => {
|
||||
console.error("Error opening database:", request.error);
|
||||
|
||||
if (cachedDb) {
|
||||
cachedDb.close();
|
||||
cachedDb = null;
|
||||
}
|
||||
indexedDB.deleteDatabase(DB_NAME);
|
||||
localStorage.removeItem(VERSION_KEY);
|
||||
dbPromise = null;
|
||||
reject(request.error);
|
||||
};
|
||||
});
|
||||
|
||||
dbPromise = openDBInternal();
|
||||
return dbPromise;
|
||||
}
|
||||
|
||||
async function getStore(store: string, mode: IDBTransactionMode = "readonly") {
|
||||
function idbRequest<T>(request: IDBRequest<T>): Promise<T> {
|
||||
return new Promise((resolve, reject) => {
|
||||
request.onsuccess = () => resolve(request.result);
|
||||
request.onerror = () => reject(request.error);
|
||||
});
|
||||
}
|
||||
|
||||
async function objectStore(
|
||||
store: string,
|
||||
mode: IDBTransactionMode = "readonly",
|
||||
): Promise<IDBObjectStore> {
|
||||
const db = await openDB();
|
||||
|
||||
if (!db.objectStoreNames.contains(store)) {
|
||||
await upgradeDB(store);
|
||||
|
||||
const upgradedDb = await openDB();
|
||||
const tx = upgradedDb.transaction(store, mode);
|
||||
return tx.objectStore(store);
|
||||
return upgradedDb.transaction(store, mode).objectStore(store);
|
||||
}
|
||||
|
||||
const tx = db.transaction(store, mode);
|
||||
return tx.objectStore(store);
|
||||
return db.transaction(store, mode).objectStore(store);
|
||||
}
|
||||
|
||||
function upgradeDB(newStore: string): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const currentVersion = getCurrentVersion();
|
||||
const newVersion = currentVersion + 1;
|
||||
async function upgradeDB(newStore: string): Promise<void> {
|
||||
invalidateConnection();
|
||||
|
||||
if (cachedDb) {
|
||||
cachedDb.close();
|
||||
cachedDb = null;
|
||||
}
|
||||
let baseVersion = 0;
|
||||
|
||||
try {
|
||||
const db = await openDatabase();
|
||||
baseVersion = db.version;
|
||||
db.close();
|
||||
cachedDb = null;
|
||||
dbPromise = null;
|
||||
} catch (error) {
|
||||
console.warn("[DB] Could not probe database version before upgrade:", error);
|
||||
}
|
||||
|
||||
const request = indexedDB.open(DB_NAME, newVersion);
|
||||
|
||||
request.onupgradeneeded = (event) => {
|
||||
const db = request.result;
|
||||
if (!db.objectStoreNames.contains(newStore)) {
|
||||
db.createObjectStore(newStore);
|
||||
}
|
||||
|
||||
updateVersion(event.newVersion || newVersion);
|
||||
};
|
||||
|
||||
request.onsuccess = () => {
|
||||
cachedDb = request.result;
|
||||
|
||||
cachedDb.onclose = () => {
|
||||
cachedDb = null;
|
||||
dbPromise = null;
|
||||
};
|
||||
|
||||
dbPromise = Promise.resolve(request.result);
|
||||
resolve();
|
||||
};
|
||||
|
||||
request.onerror = () => {
|
||||
console.error("Error upgrading database:", request.error);
|
||||
reject(request.error);
|
||||
};
|
||||
});
|
||||
try {
|
||||
await openDatabase(baseVersion + 1, newStore);
|
||||
} catch (error) {
|
||||
console.error("Error upgrading database:", error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export async function getAll(store: string): Promise<any[]> {
|
||||
try {
|
||||
const s = await getStore(store);
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = s.getAll();
|
||||
req.onsuccess = () => resolve(req.result);
|
||||
req.onerror = () => reject(req.error);
|
||||
});
|
||||
const s = await objectStore(store);
|
||||
return await idbRequest(s.getAll());
|
||||
} catch (error) {
|
||||
console.error(`Error in getAll for store ${store}:`, error);
|
||||
return [];
|
||||
@@ -154,12 +230,8 @@ export async function getAll(store: string): Promise<any[]> {
|
||||
|
||||
export async function get(store: string, key: string): Promise<any> {
|
||||
try {
|
||||
const s = await getStore(store);
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = s.get(key);
|
||||
req.onsuccess = () => resolve(req.result);
|
||||
req.onerror = () => reject(req.error);
|
||||
});
|
||||
const s = await objectStore(store);
|
||||
return await idbRequest(s.get(key));
|
||||
} catch (error) {
|
||||
console.error(`Error in get for store ${store}, key ${key}:`, error);
|
||||
return null;
|
||||
@@ -172,26 +244,61 @@ export async function put(
|
||||
key?: string,
|
||||
): Promise<void> {
|
||||
try {
|
||||
const s = await getStore(store, "readwrite");
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = key ? s.put(value, key) : s.put(value);
|
||||
req.onsuccess = () => resolve();
|
||||
req.onerror = () => reject(req.error);
|
||||
});
|
||||
const s = await objectStore(store, "readwrite");
|
||||
await idbRequest(key ? s.put(value, key) : s.put(value));
|
||||
} catch (error) {
|
||||
console.error(`Error in put for store ${store}:`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export async function applyStoreDiff(
|
||||
store: string,
|
||||
puts: Array<{ key: string; value: any }>,
|
||||
removeKeys: string[],
|
||||
): Promise<void> {
|
||||
if (puts.length === 0 && removeKeys.length === 0) return;
|
||||
|
||||
try {
|
||||
let db = await openDB();
|
||||
if (!db.objectStoreNames.contains(store)) {
|
||||
await upgradeDB(store);
|
||||
db = await openDB();
|
||||
}
|
||||
await runStoreDiffTransaction(db, store, puts, removeKeys);
|
||||
} catch (error) {
|
||||
console.error(`Error in applyStoreDiff for store ${store}:`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function runStoreDiffTransaction(
|
||||
db: IDBDatabase,
|
||||
store: string,
|
||||
puts: Array<{ key: string; value: any }>,
|
||||
removeKeys: string[],
|
||||
): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const tx = db.transaction(store, "readwrite");
|
||||
const objectStoreRef = tx.objectStore(store);
|
||||
|
||||
for (const key of removeKeys) {
|
||||
objectStoreRef.delete(key);
|
||||
}
|
||||
for (const { key, value } of puts) {
|
||||
objectStoreRef.put(value, key);
|
||||
}
|
||||
|
||||
tx.oncomplete = () => resolve();
|
||||
tx.onerror = () => reject(tx.error);
|
||||
tx.onabort = () => reject(tx.error);
|
||||
});
|
||||
}
|
||||
|
||||
export async function remove(store: string, key: string): Promise<void> {
|
||||
try {
|
||||
const s = await getStore(store, "readwrite");
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = s.delete(key);
|
||||
req.onsuccess = () => resolve();
|
||||
req.onerror = () => reject(req.error);
|
||||
});
|
||||
const s = await objectStore(store, "readwrite");
|
||||
await idbRequest(s.delete(key));
|
||||
} catch (error) {
|
||||
console.error(`Error in remove for store ${store}, key ${key}:`, error);
|
||||
throw error;
|
||||
@@ -200,12 +307,8 @@ export async function remove(store: string, key: string): Promise<void> {
|
||||
|
||||
export async function clear(store: string): Promise<void> {
|
||||
try {
|
||||
const s = await getStore(store, "readwrite");
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = s.clear();
|
||||
req.onsuccess = () => resolve();
|
||||
req.onerror = () => reject(req.error);
|
||||
});
|
||||
const s = await objectStore(store, "readwrite");
|
||||
await idbRequest(s.clear());
|
||||
} catch (error) {
|
||||
console.error(`Error in clear for store ${store}:`, error);
|
||||
throw error;
|
||||
@@ -213,54 +316,23 @@ export async function clear(store: string): Promise<void> {
|
||||
}
|
||||
|
||||
export async function resetDatabase(): Promise<void> {
|
||||
// Close cached database connection
|
||||
if (cachedDb) {
|
||||
try {
|
||||
cachedDb.close();
|
||||
} catch (e) {
|
||||
console.warn("[DB] Error closing cached database:", e);
|
||||
}
|
||||
cachedDb = null;
|
||||
}
|
||||
|
||||
// Close pending database promise
|
||||
if (dbPromise) {
|
||||
try {
|
||||
const db = await dbPromise;
|
||||
db.close();
|
||||
} catch (e) {
|
||||
// Database might not be open yet, that's okay
|
||||
} catch {
|
||||
// Database might not be open yet
|
||||
}
|
||||
dbPromise = null;
|
||||
}
|
||||
|
||||
// Wait a bit for connections to fully close
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
invalidateConnection();
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = indexedDB.deleteDatabase(DB_NAME);
|
||||
req.onsuccess = () => {
|
||||
localStorage.removeItem(VERSION_KEY);
|
||||
resolve();
|
||||
};
|
||||
req.onerror = () => {
|
||||
console.error("[DB] Error deleting database:", req.error);
|
||||
reject(req.error);
|
||||
};
|
||||
req.onblocked = () => {
|
||||
console.warn("[DB] Database deletion blocked - waiting for connections to close");
|
||||
// Wait a bit longer and try again
|
||||
setTimeout(() => {
|
||||
const retryReq = indexedDB.deleteDatabase(DB_NAME);
|
||||
retryReq.onsuccess = () => {
|
||||
localStorage.removeItem(VERSION_KEY);
|
||||
resolve();
|
||||
};
|
||||
retryReq.onerror = () => reject(retryReq.error);
|
||||
retryReq.onblocked = () => {
|
||||
reject(new Error(`Database is still open. Please close other tabs/windows and try again.`));
|
||||
};
|
||||
}, 500);
|
||||
};
|
||||
});
|
||||
if (typeof window !== "undefined") {
|
||||
window.dispatchEvent(new CustomEvent("betterseqta-reset-search-index"));
|
||||
}
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 200));
|
||||
|
||||
localStorage.removeItem(VERSION_KEY);
|
||||
await deleteDatabaseWithRetries(DB_NAME);
|
||||
}
|
||||
@@ -1,12 +1,15 @@
|
||||
import { clear, get, getAll, put, remove, resetDatabase } from "./db";
|
||||
import { applyStoreDiff, get, getAll, put, remove } from "./db";
|
||||
import { jobs } from "./jobs";
|
||||
import { renderComponentMap } from "./renderComponents";
|
||||
import { decorateIndexItems } from "./renderComponents";
|
||||
import type { IndexItem, Job, JobContext } from "./types";
|
||||
import { VectorWorkerManager } from "./worker/vectorWorkerManager";
|
||||
import { loadDynamicItems } from "../utils/dynamicItems";
|
||||
import { getVectorizedItemIds } from "./utils";
|
||||
import { getVectorizedItemIds, pruneOrphanVectorEmbeddings } from "./utils";
|
||||
import { INDEX_SCHEMA_VERSION, SCHEMA_VERSION_KEY } from "./schemaVersion";
|
||||
import { resetSearchIndexes } from "./resetIndexes";
|
||||
import { isIndexingPaused } from "./indexingPause";
|
||||
|
||||
import { verboseDebug } from '@/utils/verboseLog';
|
||||
const META_STORE = "meta";
|
||||
const LOCK_KEY = "bsq-indexer-lock";
|
||||
const HEARTBEAT_INTERVAL = 10000;
|
||||
@@ -32,20 +35,9 @@ async function ensureSchemaCurrent(): Promise<void> {
|
||||
);
|
||||
|
||||
try {
|
||||
await resetDatabase();
|
||||
await resetSearchIndexes();
|
||||
} catch (e) {
|
||||
console.warn("[Indexer] Failed to reset structured database:", e);
|
||||
}
|
||||
|
||||
try {
|
||||
await new Promise<void>((resolve) => {
|
||||
const req = indexedDB.deleteDatabase("embeddiaDB");
|
||||
req.onsuccess = () => resolve();
|
||||
req.onerror = () => resolve();
|
||||
req.onblocked = () => resolve();
|
||||
});
|
||||
} catch (e) {
|
||||
console.warn("[Indexer] Failed to reset embeddiaDB:", e);
|
||||
console.warn("[Indexer] Failed to reset search indexes:", e);
|
||||
}
|
||||
|
||||
try {
|
||||
@@ -57,7 +49,8 @@ async function ensureSchemaCurrent(): Promise<void> {
|
||||
return schemaCheckPromise;
|
||||
}
|
||||
|
||||
/* ─────────── Progress‑meta helpers ─────────── */
|
||||
export { ensureSchemaCurrent };
|
||||
|
||||
async function loadProgress<T = any>(jobId: string): Promise<T | undefined> {
|
||||
const rec = await get(META_STORE, `progress:${jobId}`);
|
||||
return rec?.progress as T | undefined;
|
||||
@@ -66,7 +59,6 @@ async function loadProgress<T = any>(jobId: string): Promise<T | undefined> {
|
||||
async function saveProgress<T = any>(jobId: string, progress: T): Promise<void> {
|
||||
await put(META_STORE, { progress }, `progress:${jobId}`);
|
||||
}
|
||||
/* ───────────────────────────────────────────── */
|
||||
|
||||
let heartbeatTimer: ReturnType<typeof setInterval> | null = null;
|
||||
let isIndexingActive = false;
|
||||
@@ -89,56 +81,108 @@ function shouldRun(job: Job, lastRun?: number): boolean {
|
||||
}
|
||||
|
||||
function getLastRunMeta(jobId: string): Promise<number | undefined> {
|
||||
return getAll(META_STORE).then((metaItems) => {
|
||||
const match = metaItems.find((m: any) => m.jobId === jobId);
|
||||
return match?.lastRun;
|
||||
return get(META_STORE, jobId).then((rec) => rec?.lastRun);
|
||||
}
|
||||
|
||||
function indexItemStorageKey(item: IndexItem): string {
|
||||
return JSON.stringify({
|
||||
id: item.id,
|
||||
text: item.text,
|
||||
category: item.category,
|
||||
content: item.content,
|
||||
dateAdded: item.dateAdded,
|
||||
metadata: item.metadata,
|
||||
actionId: item.actionId,
|
||||
renderComponentId: item.renderComponentId,
|
||||
});
|
||||
}
|
||||
|
||||
function indexItemsEqual(a: IndexItem, b: IndexItem): boolean {
|
||||
return indexItemStorageKey(a) === indexItemStorageKey(b);
|
||||
}
|
||||
|
||||
async function diffAndStoreItems(
|
||||
targetStore: string,
|
||||
items: IndexItem[],
|
||||
): Promise<void> {
|
||||
const validItems = items.filter((i) => i && i.id);
|
||||
if (validItems.length !== items.length) {
|
||||
console.warn(
|
||||
`[Indexer] Filtered out ${items.length - validItems.length} invalid items before storing in '${targetStore}'.`,
|
||||
);
|
||||
}
|
||||
|
||||
const existing = (await getAll(targetStore)) as IndexItem[];
|
||||
const existingMap = new Map(
|
||||
existing.filter((i) => i?.id).map((i) => [i.id, i]),
|
||||
);
|
||||
const newMap = new Map(validItems.map((i) => [i.id, i]));
|
||||
|
||||
const puts: Array<{ key: string; value: IndexItem }> = [];
|
||||
const removeKeys: string[] = [];
|
||||
|
||||
for (const [id, item] of newMap) {
|
||||
const prev = existingMap.get(id);
|
||||
if (!prev || !indexItemsEqual(prev, item)) {
|
||||
puts.push({ key: id, value: item });
|
||||
}
|
||||
}
|
||||
|
||||
for (const id of existingMap.keys()) {
|
||||
if (!newMap.has(id)) {
|
||||
removeKeys.push(id);
|
||||
}
|
||||
}
|
||||
|
||||
if (puts.length > 0 || removeKeys.length > 0) {
|
||||
await applyStoreDiff(targetStore, puts, removeKeys);
|
||||
}
|
||||
}
|
||||
|
||||
async function updateLastRunMeta(jobId: string): Promise<void> {
|
||||
await put(META_STORE, { jobId, lastRun: Date.now() }, jobId);
|
||||
}
|
||||
|
||||
async function tryClaimLock(lockId: string): Promise<boolean> {
|
||||
localStorage.setItem(LOCK_KEY, lockId);
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
if (localStorage.getItem(LOCK_KEY) === lockId) {
|
||||
isIndexingActive = true;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
async function acquireLock(): Promise<boolean> {
|
||||
if (isIndexingActive) {
|
||||
console.debug("[Indexer] Already indexing in this tab");
|
||||
verboseDebug("[Indexer] Already indexing in this tab");
|
||||
return false;
|
||||
}
|
||||
|
||||
const lockId = `${Date.now()}-${Math.random()}`;
|
||||
const startTime = Date.now();
|
||||
|
||||
|
||||
while (Date.now() - startTime < LOCK_ACQUIRE_TIMEOUT) {
|
||||
const currentLock = localStorage.getItem(LOCK_KEY);
|
||||
const currentTime = Date.now();
|
||||
|
||||
|
||||
if (!currentLock) {
|
||||
localStorage.setItem(LOCK_KEY, lockId);
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
if (localStorage.getItem(LOCK_KEY) === lockId) {
|
||||
isIndexingActive = true;
|
||||
return true;
|
||||
}
|
||||
if (await tryClaimLock(lockId)) return true;
|
||||
} else {
|
||||
try {
|
||||
const [timestamp] = currentLock.split('-');
|
||||
const [timestamp] = currentLock.split("-");
|
||||
const lockTime = parseInt(timestamp, 10);
|
||||
if (isNaN(lockTime) || currentTime - lockTime > LOCK_TIMEOUT) {
|
||||
localStorage.setItem(LOCK_KEY, lockId);
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
if (localStorage.getItem(LOCK_KEY) === lockId) {
|
||||
isIndexingActive = true;
|
||||
return true;
|
||||
}
|
||||
if (await tryClaimLock(lockId)) return true;
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn("[Indexer] Error parsing lock:", e);
|
||||
}
|
||||
}
|
||||
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
}
|
||||
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -200,17 +244,59 @@ export async function loadAllStoredItems(): Promise<IndexItem[]> {
|
||||
console.error(`Error loading items for job store ${jobId}:`, error);
|
||||
}
|
||||
}
|
||||
console.debug(
|
||||
verboseDebug(
|
||||
`[Indexer] Loaded ${all.length} items from all primary stores.`,
|
||||
);
|
||||
return all;
|
||||
}
|
||||
|
||||
function dispatchVectorProgress(
|
||||
progress: {
|
||||
status?: string;
|
||||
total?: number;
|
||||
processed?: number;
|
||||
message?: string;
|
||||
},
|
||||
completedJobs: number,
|
||||
totalSteps: number,
|
||||
): number {
|
||||
const { status, total, processed, message = "" } = progress;
|
||||
let detail = message;
|
||||
let completed = completedJobs;
|
||||
|
||||
if (status === "processing" && total != null && processed != null) {
|
||||
detail = `Vectorizing: ${processed} / ${total}`;
|
||||
} else if (status === "started") {
|
||||
detail = `Vectorization started for ${total} items`;
|
||||
} else if (status === "complete") {
|
||||
dispatchProgress(++completed, totalSteps, false, "Indexing finished", "Vectorization complete");
|
||||
return completed;
|
||||
} else if (status === "error") {
|
||||
dispatchProgress(completed, totalSteps, false, "Vectorization failed", `Vectorization error: ${message}`);
|
||||
return completed;
|
||||
} else if (status === "cancelled") {
|
||||
dispatchProgress(completed, totalSteps, false, "Vectorization cancelled", `Vectorization cancelled: ${message}`);
|
||||
return completed;
|
||||
} else {
|
||||
dispatchProgress(completed, totalSteps, true, "Vectorization in progress", detail);
|
||||
}
|
||||
|
||||
return completed;
|
||||
}
|
||||
|
||||
export async function runIndexing(): Promise<void> {
|
||||
if (isIndexingPaused()) {
|
||||
verboseDebug(
|
||||
"[Indexer] Skipping indexing — index was reset; reload the page to rebuild.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
await ensureSchemaCurrent();
|
||||
if (isIndexingPaused()) return;
|
||||
|
||||
if (!(await acquireLock())) {
|
||||
console.debug(
|
||||
verboseDebug(
|
||||
"%c[Indexer] Could not acquire lock - another tab is indexing or this tab is already indexing",
|
||||
"color: gray",
|
||||
);
|
||||
@@ -218,14 +304,28 @@ export async function runIndexing(): Promise<void> {
|
||||
}
|
||||
|
||||
startHeartbeat();
|
||||
console.debug("%c[Indexer] Starting indexing...", "color: green");
|
||||
verboseDebug("%c[Indexer] Starting indexing...", "color: green");
|
||||
|
||||
try {
|
||||
const jobIds = Object.keys(jobs);
|
||||
let completedJobs = 0;
|
||||
const totalSteps = jobIds.length + 1;
|
||||
dispatchProgress(completedJobs, totalSteps, true, "Starting jobs");
|
||||
|
||||
for (const jobId of jobIds) {
|
||||
if (isIndexingPaused()) {
|
||||
verboseDebug(
|
||||
"[Indexer] Indexing stopped — index was reset; reload the page to rebuild.",
|
||||
);
|
||||
dispatchProgress(
|
||||
completedJobs,
|
||||
totalSteps,
|
||||
false,
|
||||
"Indexing paused — reload to rebuild",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
dispatchProgress(
|
||||
completedJobs,
|
||||
totalSteps,
|
||||
@@ -236,7 +336,7 @@ export async function runIndexing(): Promise<void> {
|
||||
const lastRun = await getLastRunMeta(jobId);
|
||||
|
||||
if (!shouldRun(job, lastRun)) {
|
||||
console.debug(
|
||||
verboseDebug(
|
||||
`%c[Indexer] Skipping job "${jobId}" (not due)`,
|
||||
"color: gray",
|
||||
);
|
||||
@@ -254,14 +354,7 @@ export async function runIndexing(): Promise<void> {
|
||||
await getAll(storeId ?? jobId);
|
||||
const setStoredItems = async (items: IndexItem[], storeId?: string) => {
|
||||
const targetStore = storeId ?? jobId;
|
||||
await clear(targetStore);
|
||||
const validItems = items.filter((i) => i && i.id);
|
||||
if (validItems.length !== items.length) {
|
||||
console.warn(
|
||||
`[Indexer Job ${jobId} -> Store ${targetStore}] Filtered out ${items.length - validItems.length} invalid items before storing.`,
|
||||
);
|
||||
}
|
||||
await Promise.all(validItems.map((i) => put(targetStore, i, i.id)));
|
||||
await diffAndStoreItems(targetStore, items);
|
||||
};
|
||||
const addItem = async (item: IndexItem, storeId?: string) => {
|
||||
const targetStore = storeId ?? jobId;
|
||||
@@ -288,7 +381,7 @@ export async function runIndexing(): Promise<void> {
|
||||
setProgress: (p) => saveProgress(jobId, p),
|
||||
};
|
||||
|
||||
console.debug(`%c[Indexer] Running job "${jobId}"...`, "color: #4ea1ff");
|
||||
verboseDebug(`%c[Indexer] Running job "${jobId}"...`, "color: #4ea1ff");
|
||||
|
||||
try {
|
||||
const newItemsRaw = await job.run(ctx);
|
||||
@@ -300,12 +393,12 @@ export async function runIndexing(): Promise<void> {
|
||||
await setStoredItems(merged);
|
||||
await updateLastRunMeta(jobId);
|
||||
|
||||
console.debug(
|
||||
verboseDebug(
|
||||
`%c[Indexer] ${job.label}: ${newItemsRaw.length} new items reported by run, ${merged.length} total items now in '${jobId}' store.`,
|
||||
"color: #00c46f",
|
||||
);
|
||||
} catch (err) {
|
||||
console.debug(`%c[Indexer] Job ${job.label} failed:`, "color: red");
|
||||
verboseDebug(`%c[Indexer] Job ${job.label} failed:`, "color: red");
|
||||
console.error(err);
|
||||
}
|
||||
|
||||
@@ -320,8 +413,19 @@ export async function runIndexing(): Promise<void> {
|
||||
|
||||
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) {
|
||||
console.debug(
|
||||
verboseDebug(
|
||||
`%c[Indexer] Checking ${allItemsInPrimaryStores.length} items for vectorization...`,
|
||||
"color: #4ea1ff",
|
||||
);
|
||||
@@ -331,7 +435,7 @@ export async function runIndexing(): Promise<void> {
|
||||
const newItemsToVectorize = allItemsInPrimaryStores.filter(item => !vectorizedItemIds.has(item.id));
|
||||
|
||||
if (newItemsToVectorize.length > 0) {
|
||||
console.debug(
|
||||
verboseDebug(
|
||||
`%c[Indexer] Sending ${newItemsToVectorize.length} new items to worker for vectorization (${allItemsInPrimaryStores.length - newItemsToVectorize.length} already vectorized)`,
|
||||
"color: #4ea1ff",
|
||||
);
|
||||
@@ -340,56 +444,9 @@ export async function runIndexing(): Promise<void> {
|
||||
try {
|
||||
const workerManager = VectorWorkerManager.getInstance();
|
||||
await workerManager.processItems(newItemsToVectorize, (progress) => {
|
||||
let detailMessage = progress.message || "";
|
||||
if (
|
||||
progress.status === "processing" &&
|
||||
progress.total &&
|
||||
progress.processed !== undefined
|
||||
) {
|
||||
detailMessage = `Vectorizing: ${progress.processed} / ${progress.total}`;
|
||||
} else if (progress.status === "complete") {
|
||||
detailMessage = "Vectorization complete";
|
||||
completedJobs++;
|
||||
dispatchProgress(
|
||||
completedJobs,
|
||||
totalSteps,
|
||||
false,
|
||||
"Indexing finished",
|
||||
detailMessage
|
||||
);
|
||||
} else if (progress.status === "error") {
|
||||
detailMessage = `Vectorization error: ${progress.message}`;
|
||||
dispatchProgress(
|
||||
completedJobs,
|
||||
totalSteps,
|
||||
false,
|
||||
"Vectorization failed",
|
||||
detailMessage,
|
||||
);
|
||||
} else if (progress.status === "started") {
|
||||
detailMessage = `Vectorization started for ${progress.total} items`;
|
||||
} else if (progress.status === "cancelled") {
|
||||
detailMessage = `Vectorization cancelled: ${progress.message}`;
|
||||
dispatchProgress(
|
||||
completedJobs,
|
||||
totalSteps,
|
||||
false,
|
||||
"Vectorization cancelled",
|
||||
detailMessage,
|
||||
);
|
||||
}
|
||||
|
||||
if (progress.status !== "complete" && progress.status !== "error" && progress.status !== "cancelled") {
|
||||
dispatchProgress(
|
||||
completedJobs,
|
||||
totalSteps,
|
||||
true,
|
||||
"Vectorization in progress",
|
||||
detailMessage,
|
||||
);
|
||||
}
|
||||
});
|
||||
console.debug(
|
||||
completedJobs = dispatchVectorProgress(progress, completedJobs, totalSteps);
|
||||
});
|
||||
verboseDebug(
|
||||
"%c[Indexer] Vectorization task for stored items sent to worker.",
|
||||
"color: green",
|
||||
);
|
||||
@@ -408,7 +465,7 @@ export async function runIndexing(): Promise<void> {
|
||||
);
|
||||
}
|
||||
} else {
|
||||
console.debug(
|
||||
verboseDebug(
|
||||
`%c[Indexer] All ${allItemsInPrimaryStores.length} items are already vectorized, skipping worker initialization.`,
|
||||
"color: gray",
|
||||
);
|
||||
@@ -421,7 +478,7 @@ export async function runIndexing(): Promise<void> {
|
||||
);
|
||||
}
|
||||
} else {
|
||||
console.debug(
|
||||
verboseDebug(
|
||||
"%c[Indexer] No items found in primary stores to send for vectorization.",
|
||||
"color: gray",
|
||||
);
|
||||
@@ -434,38 +491,17 @@ export async function runIndexing(): Promise<void> {
|
||||
);
|
||||
}
|
||||
|
||||
stopHeartbeat();
|
||||
|
||||
allItemsInPrimaryStores = await loadAllStoredItems();
|
||||
// Create new objects to avoid XrayWrapper issues in Firefox
|
||||
const itemsWithComponents = allItemsInPrimaryStores.map(item => {
|
||||
try {
|
||||
const jobDef = jobs[item.category] || Object.values(jobs).find(j => j.id === item.category) || jobs[item.renderComponentId];
|
||||
let renderComponent = item.renderComponent;
|
||||
if (jobDef) {
|
||||
renderComponent = renderComponentMap[jobDef.renderComponentId] || renderComponent;
|
||||
} else if (renderComponentMap[item.renderComponentId]) {
|
||||
renderComponent = renderComponentMap[item.renderComponentId];
|
||||
}
|
||||
// Deep clone to avoid Firefox XrayWrapper issues with nested objects like metadata
|
||||
// Use JSON serialization to ensure all nested properties are accessible
|
||||
try {
|
||||
const cloned = JSON.parse(JSON.stringify(item));
|
||||
cloned.renderComponent = renderComponent;
|
||||
return cloned;
|
||||
} catch (e) {
|
||||
// Fallback to shallow copy if deep clone fails
|
||||
console.warn("[Indexer] Failed to deep clone item, using shallow copy:", e);
|
||||
return { ...item, renderComponent };
|
||||
}
|
||||
} catch (error) {
|
||||
// Fallback: return item as-is if modification fails (Firefox XrayWrapper)
|
||||
console.warn("[Indexer] Failed to add render component to item (Firefox XrayWrapper):", error);
|
||||
return item;
|
||||
}
|
||||
});
|
||||
const itemsWithComponents = decorateIndexItems(allItemsInPrimaryStores);
|
||||
loadDynamicItems(itemsWithComponents);
|
||||
window.dispatchEvent(new Event("dynamic-items-updated"));
|
||||
window.dispatchEvent(
|
||||
new CustomEvent("dynamic-items-updated", {
|
||||
detail: { fullRebuild: true },
|
||||
}),
|
||||
);
|
||||
} finally {
|
||||
stopHeartbeat();
|
||||
}
|
||||
}
|
||||
|
||||
function mergeItems(existing: IndexItem[], incoming: IndexItem[]): IndexItem[] {
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
/** In-memory gate: after a manual reset, skip indexing until the tab reloads. */
|
||||
let pausedUntilReload = false;
|
||||
|
||||
export function pauseIndexingUntilReload(): void {
|
||||
pausedUntilReload = true;
|
||||
}
|
||||
|
||||
export function isIndexingPaused(): boolean {
|
||||
return pausedUntilReload;
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { IndexItem, Job } from "../types";
|
||||
|
||||
import { verboseDebug } from '@/utils/verboseLog';
|
||||
const fetchJSON = async (url: string, body: any) => {
|
||||
const res = await fetch(`${location.origin}${url}`, {
|
||||
method: "POST",
|
||||
@@ -128,7 +129,7 @@ export const assignmentsJob: Job = {
|
||||
|
||||
const student = 69; // TODO: Get from context if available
|
||||
|
||||
console.debug("[Assignments job] Starting indexing - fetching all assessments (upcoming and past)...");
|
||||
verboseDebug("[Assignments job] Starting indexing - fetching all assessments (upcoming and past)...");
|
||||
|
||||
// Fetch data in parallel
|
||||
const [upcoming, subjects] = await Promise.all([
|
||||
@@ -136,12 +137,12 @@ export const assignmentsJob: Job = {
|
||||
fetchSubjects(),
|
||||
]);
|
||||
|
||||
console.debug(`[Assignments job] Fetched ${upcoming.length} upcoming assessments and ${subjects.length} subjects`);
|
||||
verboseDebug(`[Assignments job] Fetched ${upcoming.length} upcoming assessments and ${subjects.length} subjects`);
|
||||
|
||||
// Fetch past assessments for ALL subjects to ensure we get all historical assignments
|
||||
const past = await fetchPastAssessments(student, subjects);
|
||||
|
||||
console.debug(`[Assignments job] Fetched ${past.length} past assessments`);
|
||||
verboseDebug(`[Assignments job] Fetched ${past.length} past assessments`);
|
||||
|
||||
// Create a lookup map from subject code to programme/metaclass
|
||||
const subjectLookup = new Map<string, { programme: number; metaclass: number }>();
|
||||
@@ -220,7 +221,7 @@ export const assignmentsJob: Job = {
|
||||
const assessmentArray = Array.from(allAssessments.values());
|
||||
const pastCount = assessmentArray.filter(a => !a.isUpcoming).length;
|
||||
const upcomingCount = assessmentArray.filter(a => a.isUpcoming).length;
|
||||
console.debug(`[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; // Increased batch size for better performance
|
||||
|
||||
// Skip fetching assessment details - the API endpoint doesn't exist or returns 404
|
||||
@@ -321,7 +322,7 @@ export const assignmentsJob: Job = {
|
||||
renderComponentId: "assessment",
|
||||
};
|
||||
|
||||
console.debug(`[Assignments job] ✅ Created item for assignment ${assessment.id}:`, {
|
||||
verboseDebug(`[Assignments job] ✅ Created item for assignment ${assessment.id}:`, {
|
||||
id: item.id,
|
||||
programmeId: item.metadata.programmeId,
|
||||
programmeID: item.metadata.programmeID,
|
||||
@@ -350,7 +351,7 @@ export const assignmentsJob: Job = {
|
||||
|
||||
const newItemsCount = items.filter(item => !existingIds.has(item.id)).length;
|
||||
const updatedItemsCount = items.length - newItemsCount;
|
||||
console.debug(`[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;
|
||||
},
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ import { seqtaFetchPayload } from "../api";
|
||||
import { buildIndexItem } from "../extract";
|
||||
import { htmlToPlainText } from "../utils";
|
||||
|
||||
import { verboseDebug } from '@/utils/verboseLog';
|
||||
/**
|
||||
* Indexes per-subject course content from `/seqta/student/load/courses`.
|
||||
*
|
||||
@@ -106,7 +107,7 @@ export const coursesJob: Job = {
|
||||
run: async (_ctx) => {
|
||||
const subjects = await fetchActiveSubjects();
|
||||
if (subjects.length === 0) {
|
||||
console.debug("[Courses job] No active subjects discovered.");
|
||||
verboseDebug("[Courses job] No active subjects discovered.");
|
||||
return [];
|
||||
}
|
||||
|
||||
@@ -169,7 +170,7 @@ export const coursesJob: Job = {
|
||||
);
|
||||
}
|
||||
|
||||
console.debug(
|
||||
verboseDebug(
|
||||
`[Courses job] Indexed ${items.length} courses across ${subjects.length} subjects.`,
|
||||
);
|
||||
return items;
|
||||
|
||||
Loaded 100 of 259 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user