Compare commits

..
3 Commits
Author SHA1 Message Date
SethBurkart123 51c265400c feat(app): improved input handling + better UI 2024-12-11 11:44:56 +11:00
SethBurkart123 6209b65afe feat(app): add icons to electron 2024-12-05 18:11:13 +11:00
SethBurkart123 bb388ab000 feat: electron building 2024-12-05 18:09:06 +11:00
660 changed files with 28996 additions and 91681 deletions

No files matched your search

-3
View File
@@ -1,3 +0,0 @@
# 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
+32
View File
@@ -0,0 +1,32 @@
{
"env": {
"browser": true,
"commonjs": true,
"es2021": true,
"node": true
},
"extends": "eslint:recommended",
"parserOptions": {
"ecmaVersion": "latest",
"sourceType": "module"
},
"rules": {
// allow importing ts extensions
"sort-imports": ["error", {
"ignoreCase": true,
"ignoreDeclarationSort": true,
"ignoreMemberSort": false,
"memberSyntaxSortOrder": ["none", "all", "multiple", "single"]
}],
"import/extensions": [
"error",
"ignorePackages",
{
"js": "never",
"ts": "never",
"tsx": "never"
}
]
},
"plugins": ["import"]
}
-1
View File
@@ -1 +0,0 @@
* text=auto eol=lf
+27
View File
@@ -0,0 +1,27 @@
---
name: Report A bug.
about: Create a report of a present bug.
title: "[BUG]"
labels: bug
assignees: ''
---
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Please indicate how did you make this happen.
**Expected behaviuor**
Please add a clear and concise description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Desktop (please complete the following information):**
- OS: [e.g. iOS]
- If using Windows, the build number. Find this by using ```winver``` and copying down the build id.
**Additional context**
Add any other context about the problem here.
-65
View File
@@ -1,65 +0,0 @@
name: Bug report
description: Something in BetterSEQTA+ is broken. For questions, ask in Discord instead.
labels: bug
title: "[BUG] "
type: "Bug"
body:
- type: markdown
attributes:
value: |
Please [search existing issues](https://github.com/BetterSEQTA/BetterSEQTA-Plus/issues?q=is%3Aissue) first, including closed ones. For general help you'll get a faster answer in [Discord](https://discord.gg/YzmbnCDkat).
- type: textarea
attributes:
label: What happened?
description: What went wrong, and what did you expect to happen instead?
validations:
required: true
- type: textarea
attributes:
label: Steps to reproduce
placeholder: |
1. Open the timetable
2. Click a class
3. ...
validations:
required: false
- type: input
attributes:
label: Extension version
description: Shown on your browser's extensions page (`chrome://extensions` or `about:addons`).
placeholder: "1.0.0"
validations:
required: true
- type: dropdown
attributes:
label: Browser
options:
- Chrome
- Microsoft Edge
- Brave
- Opera
- Other Chromium browser
- Firefox
- Safari
- Other
validations:
required: true
- type: checkboxes
attributes:
label: Confirm
options:
- label: I'm using an unmodified build from a store or GitHub release, without third-party plugins.
required: true
- type: textarea
attributes:
label: Screenshots and console output
description: Screenshots, a video, or errors from the browser console all help.
placeholder: Drag images or log files into this box to attach them.
validations:
required: false
-7
View File
@@ -1,7 +0,0 @@
contact_links:
- name: Discord
url: https://discord.gg/YzmbnCDkat
about: Questions, help and community chat.
- name: Documentation
url: https://docs.betterseqta.org
about: Guides for installing, making themes and writing plugins.
+20
View File
@@ -0,0 +1,20 @@
---
name: Feature request
about: Suggest an idea for this project
title: "[FR] "
labels: enhancement
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.
@@ -1,42 +0,0 @@
name: Feature request
description: Suggest something new for BetterSEQTA+ or a change to an existing feature.
labels: enhancement
title: "[FR] "
body:
- type: markdown
attributes:
value: |
Please [search existing issues](https://github.com/BetterSEQTA/BetterSEQTA-Plus/issues?q=is%3Aissue) first, including closed ones, in case it's already been suggested.
- type: textarea
attributes:
label: What would you like?
description: Describe the feature in as much detail as you can, and the problem it solves.
placeholder: It would be great if...
validations:
required: true
- type: dropdown
attributes:
label: Type
options:
- Visual / design
- Functionality
- Not sure
validations:
required: true
- type: input
attributes:
label: Related bug report
description: If this comes from a bug report, link it here.
placeholder: https://github.com/BetterSEQTA/BetterSEQTA-Plus/issues/...
validations:
required: false
- type: textarea
attributes:
label: Anything else
description: Mockups, reference images, or examples from other apps.
validations:
required: false
@@ -1,64 +0,0 @@
name: New contributor
description: First time contributing? Tell us what you'd like to work on and we'll help you get started.
labels: ["help wanted"]
title: "[NEW CONTRIBUTOR] "
body:
- type: markdown
attributes:
value: |
Welcome to BetterSEQTA+! Fill in what you can and a maintainer will point you in the right direction. For real-time help, join the [Discord](https://discord.gg/YzmbnCDkat).
- type: checkboxes
attributes:
label: About you
options:
- label: This is my first open source contribution
- label: I'm new to browser extensions
- label: I'm new to TypeScript or Svelte
- label: I've coded before but I'm new to this project
- type: checkboxes
attributes:
label: What would you like to work on?
options:
- label: Fixing a bug
- label: A new feature
- label: A plugin
- label: UI and design
- label: Tests
- label: Documentation
- label: Not sure yet, I'd like suggestions
- type: checkboxes
attributes:
label: Have you read the guides?
options:
- label: "[CONTRIBUTING.md](https://github.com/BetterSEQTA/BetterSEQTA-Plus/blob/main/CONTRIBUTING.md)"
required: true
- label: "The [architecture guide](https://docs.betterseqta.org/architecture/)"
- label: "The [plugin development guide](https://docs.betterseqta.org/plugin-development/), if you're writing a plugin"
- type: dropdown
attributes:
label: Is your dev environment working?
options:
- Yes, `npm run dev` works
- Partly, I'm running into issues
- Not set up yet
validations:
required: true
- type: textarea
attributes:
label: Errors
description: Paste any errors you've hit.
render: shell
validations:
required: false
- type: textarea
attributes:
label: Questions
description: What would you like help with? Is anything in the docs unclear?
validations:
required: false
+17
View File
@@ -0,0 +1,17 @@
---
name: Vulnerability
about: Report a vulnerability in this extension.
title: "[VUL] "
labels: ''
assignees: ''
---
**What is the vulnerability?**
Describe the vulnerability in concise language.
**Where is the vulnerability found?**
Describe where the vulnerability is found.
**What does this affect?**
Explain what it affects. E.G: It opens up my school email to the world. etc.
@@ -1,17 +0,0 @@
## What does this change?
<!-- A short summary, and why it's needed. -->
Fixes #
## Type of change
- [ ] Bug fix
- [ ] New feature
- [ ] Breaking change
- [ ] Docs or tooling only
## Checklist
- [ ] `npm run lint`, `npm test` and `npm run build` pass
- [ ] Tested on a SEQTA page
@@ -1,59 +0,0 @@
name: Build Extension
description: Install dependencies, build Chrome and Firefox extensions, and package zips.
inputs:
gh_release_update_check:
description: Enable GitHub release update checker in the built extension.
required: false
default: "false"
update_channel:
description: Update channel baked into the build (stable or nightly).
required: false
default: stable
build_label:
description: Optional build label for nightly display (e.g. UTC build date).
required: false
default: ""
release_repo:
description: GitHub repo slug for the update checker (owner/name).
required: false
default: BetterSEQTA/BetterSEQTA-Plus
outputs:
version:
description: Version from package.json
value: ${{ steps.version.outputs.version }}
chrome_zip:
description: Path to the Chrome extension zip
value: ${{ steps.zip.outputs.chrome_zip }}
firefox_zip:
description: Path to the Firefox extension zip
value: ${{ steps.zip.outputs.firefox_zip }}
runs:
using: composite
steps:
- name: Setup Node and dependencies
uses: ./.github/actions/setup-node-deps
- name: Read version
id: version
shell: bash
run: echo "version=$(node -p "require('./package.json').version")" >> "$GITHUB_OUTPUT"
- name: Build extension
shell: bash
env:
GH_RELEASE_UPDATE_CHECK: ${{ inputs.gh_release_update_check }}
UPDATE_CHANNEL: ${{ inputs.update_channel }}
GH_RELEASE_REPO: ${{ inputs.release_repo }}
BUILD_LABEL: ${{ inputs.build_label }}
run: npm run build
- name: Package zips
id: zip
shell: bash
env:
UPDATE_CHANNEL: ${{ inputs.update_channel }}
BUILD_LABEL: ${{ inputs.build_label }}
run: node scripts/package-extension-zips.mjs "${{ steps.version.outputs.version }}"
-17
View File
@@ -1,17 +0,0 @@
name: Run lint
description: Run oxlint, the format check and the type check.
runs:
using: composite
steps:
- name: Lint
shell: bash
run: npm run lint
- name: Format check
shell: bash
run: npm run format:check
- name: Type check
shell: bash
run: npm run typecheck
@@ -1,9 +0,0 @@
name: Run smoke tests
description: Verify built extension dist output.
runs:
using: composite
steps:
- name: Smoke tests
shell: bash
run: npm run test:smoke
@@ -1,9 +0,0 @@
name: Run unit tests
description: Run Jest unit tests.
runs:
using: composite
steps:
- name: Unit tests
shell: bash
run: npm run test:unit
@@ -1,15 +0,0 @@
name: Setup Node and dependencies
description: Install Node.js 26.x and npm dependencies.
runs:
using: composite
steps:
- name: Use Node.js 26.x
uses: actions/setup-node@v7
with:
node-version: 26.x
cache: npm
- name: Install dependencies
shell: bash
run: npm ci
-1
View File
@@ -1 +0,0 @@
Experimental nightly build from `main`. May break. **Do not upload to Chrome Web Store or Firefox Add-ons.** Download, replace your sideloaded copy, and reload the extension.
+38
View File
@@ -0,0 +1,38 @@
name: NodeJS Build
on:
push:
branches: [ "main" ]
pull_request:
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
-57
View File
@@ -1,57 +0,0 @@
# Rebuilds main every night and replaces the assets on the "nightly" prerelease.
# Runs on Windows because the layerchart Svelte build fails on Linux.
name: Nightly Release
on:
schedule:
# Midnight in Adelaide during daylight saving (UTC+10:30).
- cron: "30 13 * * *"
permissions:
contents: write
env:
NIGHTLY_TAG: nightly
GH_TOKEN: ${{ github.token }}
jobs:
nightly:
runs-on: windows-latest
defaults:
run:
shell: bash
steps:
- uses: actions/checkout@v7
- name: Set build date
id: build_date
run: echo "date=$(TZ=Australia/Adelaide date +'%Y-%m-%d')" >> "$GITHUB_OUTPUT"
- name: Build extension
id: build
uses: ./.github/actions/build-extension
with:
gh_release_update_check: "true"
update_channel: nightly
build_label: ${{ steps.build_date.outputs.date }}
release_repo: ${{ github.repository }}
- name: Ensure nightly release exists
run: |
TITLE="Nightly (${{ steps.build_date.outputs.date }})"
if ! gh release view "${{ env.NIGHTLY_TAG }}" 2>/dev/null; then
gh release create "${{ env.NIGHTLY_TAG }}" \
--prerelease \
--title "$TITLE" \
--notes-file .github/nightly-release-notes.md
else
gh release edit "${{ env.NIGHTLY_TAG }}" --title "$TITLE"
fi
- name: Upload nightly assets
run: |
gh release upload "${{ env.NIGHTLY_TAG }}" \
--clobber \
"${{ steps.build.outputs.chrome_zip }}" \
"${{ steps.build.outputs.firefox_zip }}"
-70
View File
@@ -1,70 +0,0 @@
name: CI
on:
pull_request:
branches: ["main"]
push:
branches: ["main"]
permissions:
contents: read
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
lint:
# The layerchart Svelte build fails on Linux, so CI runs on Windows.
runs-on: windows-latest
defaults:
run:
shell: bash
steps:
- uses: actions/checkout@v7
- name: Setup Node and dependencies
uses: ./.github/actions/setup-node-deps
- name: Run lint
uses: ./.github/actions/run-lint
unit-tests:
runs-on: windows-latest
defaults:
run:
shell: bash
steps:
- uses: actions/checkout@v7
- 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@v7
- name: Build extension
id: build
uses: ./.github/actions/build-extension
with:
gh_release_update_check: "false"
- name: Upload extension zips
uses: actions/upload-artifact@v7
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 -22
View File
@@ -1,29 +1,23 @@
# Dependencies
# npm
node_modules/
package-lock.json
bun.lockb
pnpm-lock.yaml
yarn.lock
# Build output
betterseqtaplus-safari/
coverage/
dist/
# Copied in by postinstall
src/public/resources/ort/ort-wasm-simd-threaded.jsep.mjs
src/public/resources/ort/ort-wasm-simd-threaded.jsep.wasm
src/public/resources/pdfjs/pdf.legacy.min.mjs
src/public/resources/pdfjs/pdf.worker.min.mjs
# Environment
.parcel-cache
.env
.env.submit
# Editors and OS
.claude/
.cursor/
.idea/
.vscode/
.DS_Store
Thumbs.db
# Build
extension.zip
dist/
betterseqtaplus-safari/
# Logs
*.log
.million/
.vscode/
**/.DS_Store
# Electron
electron-dist/
-4
View File
@@ -1,4 +0,0 @@
{
"$schema": "./node_modules/oxfmt/configuration_schema.json",
"ignorePatterns": ["package-lock.json", "src/public/"]
}
-16
View File
@@ -1,16 +0,0 @@
{
"$schema": "./node_modules/oxlint/configuration_schema.json",
"categories": {
"correctness": "error"
},
"rules": {
"no-unused-vars": [
"error",
{
"argsIgnorePattern": "^_",
"ignoreRestSiblings": true
}
]
},
"ignorePatterns": ["src/public/**"]
}
+5
View File
@@ -0,0 +1,5 @@
{
"transformers": {
"raw:*": ["@parcel/transformer-raw"]
}
}
+5
View File
@@ -0,0 +1,5 @@
{
"plugins": {
"tailwindcss": {}
}
}
+1
View File
@@ -0,0 +1 @@
build
+5
View File
@@ -0,0 +1,5 @@
{
"tabWidth": 2,
"useTabs": false,
"semi": false
}
+13 -14
View File
@@ -17,23 +17,23 @@ diverse, inclusive, and healthy community.
Examples of behavior that contributes to a positive environment for our
community include:
- Demonstrating empathy and kindness toward other people
- Being respectful of differing opinions, viewpoints, and experiences
- Giving and gracefully accepting constructive feedback
- Accepting responsibility and apologizing to those affected by our mistakes,
* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience
- Focusing on what is best not just for us as individuals, but for the
* Focusing on what is best not just for us as individuals, but for the
overall community
Examples of unacceptable behavior include:
- The use of sexualized language or imagery, and sexual attention or
* The use of sexualized language or imagery, and sexual attention or
advances of any kind
- Trolling, insulting or derogatory comments, and personal or political attacks
- Public or private harassment
- Publishing others' private information, such as a physical or email
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email
address, without their explicit permission
- Other conduct which could reasonably be considered inappropriate in a
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Enforcement Responsibilities
@@ -59,9 +59,8 @@ representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the community leaders responsible for enforcement by emailing
[betterseqta.plus@gmail.com](mailto:betterseqta.plus@gmail.com) or messaging a
moderator in the [Discord](https://discord.gg/YzmbnCDkat).
reported to the community leaders responsible for enforcement at
N/A (literally sorry guys).
All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the
@@ -107,7 +106,7 @@ Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behavior, harassment of an
standards, including sustained inappropriate behavior, harassment of an
individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within
+29 -55
View File
@@ -1,65 +1,39 @@
# Contributing to BetterSEQTA+
# Contributing
Thanks for helping out! For anything bigger than a small fix, open an issue or ask in [Discord](https://discord.gg/YzmbnCDkat) first so we can agree on the approach.
When contributing to this repository, please first discuss the change you wish to make via issue,
email, or any other method with the owners of this repository before making a change.
## Setup
## Pull Request Process
You need Node.js 26+, Git and a Chromium browser (Chrome, Edge or Brave).
1. It is recommended to start by opening an issue to discuss the change you wish to make. This will allow us to discuss the change and ensure it is a good fit for the project.
2. Fork the repo and create your branch from `master`.
3. When writing your pull request, make sure to use the pull request template.
```bash
git clone https://github.com/YOUR_USERNAME/BetterSEQTA-Plus
cd BetterSEQTA-Plus
npm install
npm run dev
### Pull Request Template
```
## Description
Please include a summary of the change and which issue is fixed. Please also include relevant motivation and context. List any dependencies that are required for this change.
Fixes # (issue)
## Type of change
Please delete options that are not relevant.
- [ ] Bug fix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected)
- [ ] This change requires a documentation update
```
Then load the extension:
### Issues
1. Open `chrome://extensions` and turn on Developer mode.
2. Click **Load unpacked** and pick the `dist/chrome` folder.
3. Open a SEQTA Learn page.
#### Create a new issue
For Firefox, run `npm run dev:firefox` and load `dist/firefox` from `about:debugging`.
If you spot a problem with the readme or code, [search if an issue already exists](https://github.com/BetterSEQTA/BetterSEQTA-Plus/issues). If a related issue doesn't exist, you can open a new issue using a relevant [issue form](https://github.com/BetterSEQTA/BetterSEQTA-Plus/issues/new).
## Project layout
#### Solve an issue
| Path | What's in it |
| -------------------------------------- | --------------------------------------------- |
| `src/SEQTA.ts` | Content script entry point |
| `src/background.ts`, `src/background/` | Service worker |
| `src/seqta/` | Everything injected into SEQTA pages |
| `src/interface/` | Settings popup and theme store (Svelte) |
| `src/plugins/` | Plugin system and built-in plugins |
| `src/css/` | Injected styles and the shared Tailwind setup |
| `lib/`, `scripts/` | Vite plugins and build scripts |
The [architecture guide](https://docs.betterseqta.org/architecture/) goes into more detail.
## Making changes
1. Branch from `main`, e.g. `git checkout -b fix/timetable-colours`.
2. Keep each PR to one change and match the style of the surrounding code.
3. Add tests for logic changes.
4. Before opening the PR, check everything passes:
```bash
npm run format
npm run lint
npm run typecheck
npm test
npm run build
```
5. Use short conventional commit messages: `feat:`, `fix:`, `chore:`, `docs:`.
6. Open the PR and fill in the template.
## Issues
Search [existing issues](https://github.com/BetterSEQTA/BetterSEQTA-Plus/issues) before opening a new one, and use the issue forms. [`good first issue`](https://github.com/BetterSEQTA/BetterSEQTA-Plus/labels/good%20first%20issue) and [`help wanted`](https://github.com/BetterSEQTA/BetterSEQTA-Plus/labels/help%20wanted) are good places to start. Issues aren't assigned, so just open a PR when you have a fix.
## More docs
- [Plugin development](https://docs.betterseqta.org/plugin-development/) and the [Plugin API](https://docs.betterseqta.org/plugin-api/)
- [Theme creation](https://docs.betterseqta.org/theme-creation/)
- [Troubleshooting](https://docs.betterseqta.org/troubleshooting/)
- [Releases and CI](docs/RELEASES.md)
Scan through our [existing issues](https://github.com/BetterSEQTA/BetterSEQTA-Plus/issues) to find one that interests you. You can narrow down the search using `labels` as filters. As a general rule, we don’t assign issues to anyone. If you find an issue to work on, you are welcome to open a PR with a fix.
+109 -33
View File
@@ -1,63 +1,139 @@
#
<a href="https://chromewebstore.google.com/detail/betterseqta+/afdgaoaclhkhemfkkkonemoapeinchel">
<img src="https://socialify.git.ci/betterseqta/betterseqta-plus/image?description=1&font=Inter&forks=1&issues=1&logo=data%3Aimage%2Fsvg%2Bxml%2C%253Csvg%20height%3D%27656pt%27%20fill%3D%27white%27%20preserveAspectRatio%3D%27xMidYMid%20meet%27%20viewBox%3D%270%200%20658%20656%27%20width%3D%27658pt%27%20xmlns%3D%27http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%27%253E%253Cg%20transform%3D%27matrix(.1%200%200%20-.1%200%20656)%27%253E%253Cpath%20d%3D%27m2960%206499c-918-100-1726-561-2278-1299-196-262-374-609-475-925-171-533-203-1109-91-1655%20228-1115%201030-2032%202104-2408%20356-124%20680-177%201080-176%20269%201%20403%2014%20650%2064%20790%20159%201503%20624%201980%201290%20714%20998%20799%202342%20217%203420-488%20902-1361%201515-2382%201671-113%2017-196%2022-430%2024-159%202-328-1-375-6zm566-1443c476-99%20885-385%201134-791%20190-309%20282-696%20250-1045-22-240-73-420-180-635-78-156-159-275-274-401l-77-84h445%20446v-235-236l-1162%204-1163%203-100%2023c-449%20101-812%20337-1071%20697-77%20107-193%20335-233%20459-115%20358-116%20726-1%201078%20209%20644%20766%201101%201446%201187%20128%2016%20405%204%20540-24z%27%2F%253E%253Cpath%20d%3D%27m3065%204604c-250-36-396-89-576-209-280-187-470-478-535-821-25-135-16-395%2019-525%2095-351%20331-644%20651-806%2098-49%20225-93%20331-114%2092-18%20368-18%20460%200%20481%2095%20853%20444%20982%20921%2035%20129%2044%20389%2019%20524-36%20191-121%20387-228%20531-186%20249-476%20428-783%20485-65%2012-291%2021-340%2014z%27%2F%253E%253C%2Fg%253E%253C%2Fsvg%253E&name=1&owner=1&pattern=Signal&stargazers=1&theme=Dark" />
</a>
<p align="center">
A browser extension that makes <a href="https://www.tes.com/en-au/for-schools/seqta">SEQTA</a> faster, nicer to look at and easier to use.
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> 🔥
</p>
<p align="center">
<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="Available in the Chrome Web Store" 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" alt="Join the Discord" width="240" style="border-radius:10%;" /></a>
<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://discord.gg/YzmbnCDkat"><img src="https://github.com/SethBurkart123/EvenBetterSEQTA/assets/108050083/23055730-b16e-44c0-9bef-221d8545af92" width="240" style="border-radius:10%;" /></a>
</p>
<p align="center">
<img src="https://img.shields.io/chrome-web-store/users/afdgaoaclhkhemfkkkonemoapeinchel" alt="Chrome Web Store users" />
<img src="https://img.shields.io/chrome-web-store/rating/afdgaoaclhkhemfkkkonemoapeinchel" alt="Chrome Web Store rating" />
</p>
<div>
<img src="https://img.shields.io/chrome-web-store/users/afdgaoaclhkhemfkkkonemoapeinchel" />
<img src="https://img.shields.io/chrome-web-store/rating/afdgaoaclhkhemfkkkonemoapeinchel" />
</div>
## Table of contents
- [Features](#features)
- [Creating Custom Themes](#creating-custom-themes)
- [Getting Started](#getting-started)
- [Running Development](#running-development)
- [Building for production](#building-for-production)
- [Folder Structure](#folder-structure)
- [Contributors](#contributors)
- [Credits](#credits)
- [Star History](#star-history)
## Features
- **Themes:** dark mode, custom colours and backgrounds, a community theme store and a theme creator.
- **Home page:** today's lessons, upcoming assessments, notices and your own shortcuts in one place.
- **Global search:** jump to assessments, messages, courses and notices from a keyboard shortcut.
- **Assessments:** an overview board grouped by status, averages and weightings on the assessments page, and grade analytics with trends and charts.
- **Timetable:** extra timetable tools, editable room and teacher names, calendar sync and opt-in classmates.
- **Messages and notifications:** custom message folders and a local archive of notifications that outlasts SEQTA's own history.
- **BetterSEQTA Cloud:** sign in to back up your settings and use your profile picture across devices.
- **Extras:** hide side menu items, animated backgrounds, background music and the classic kitten 404 page.
- Dark mode
- Custom Background/Themes
- Improved Styling/CSS
- Improved look for SEQTA Learn
- Custom Home Page including:
- Daily Lessons
- Shortcuts
- Easier Access Notices
- Assessments
- Options to remove certain items from the side menu
- Grades calculator
- Fully customisable themes and an offical theme store
- Notification for next lesson (sent 5 minutes before end of the lesson)
- Browser Support
- Chrome Supported
- Edge Supported
- Brave Supported
- Opera Supported
- Vivaldi Supported
- Chromium-based browsers are supported
- Firefox (Experimental - available [here](https://addons.mozilla.org/en-US/firefox/addon/betterseqta-plus/)
- Safari (Experimental - only available via compilation)
Works in Chrome, Edge, Brave, Opera and other Chromium browsers, and in [Firefox](https://addons.mozilla.org/en-US/firefox/addon/betterseqta-plus/). Safari support is experimental and needs a build from source.
## Creating Custom Themes
## Documentation
If you are looking to create custom themes, I would recommend you start at the official documentation [here](https://betterseqta.gitbook.io/betterseqta-docs). You can see some premade examples along with a compilation script that can be used to allow for CSS frameworks and libraries such as SCSS to be used [here](https://github.com/BetterSEQTA/BetterSEQTA-Theme-Generator).
Guides for installing, making themes and writing plugins are at **[docs.betterseqta.org](https://docs.betterseqta.org)**. If you get stuck, ask in the [Discord](https://discord.gg/YzmbnCDkat).
Don't worry- if you get stuck feel free to ask around in the discord. We're open and happy to help out! Happy creating :)
## Contributing
## Getting started
Contributions are welcome. Setup takes a few minutes:
1. Clone the repository
```bash
git clone https://github.com/YOUR_USERNAME/BetterSEQTA-Plus
cd BetterSEQTA-Plus
npm install
```
git clone https://github.com/BetterSEQTA/BetterSEQTA-Plus
```
### Running Development
1. Install dependencies
```
npm install # or your preferred package manager like pnpm or yarn
```
2. Run the dev script (it updates as you save files)
```
npm run dev
```
Then open `chrome://extensions`, turn on Developer mode, click **Load unpacked** and pick `dist/chrome`.
3. Load the extension into chrome
See [CONTRIBUTING.md](CONTRIBUTING.md) for the full guide.
- Go to `chrome://extensions`
- Enable developer mode
- Click `Load unpacked`
- Select the `dist` folder
<a href="https://github.com/BetterSEQTA/BetterSEQTA-Plus/graphs/contributors">
<img src="https://contrib.rocks/image?repo=betterseqta/betterseqta-plus" alt="Contributors" />
Just remember, in order to update changes to the extension, you need to click the refresh button on the extension in `chrome://extensions` whenever anything's changed.
### Building for production
1. Install dependencies
```
npm install # or your preferred package manager like pnpm or yarn
```
2. Run the build script
```
npm run build
```
3. Package it up (optional)
```
npm run zip # This requires 7-Zip to be installed in order to work
```
## Folder Structure
The folder structure is as follows:
- The `src` folder contains source files that are compiled to the build directory.
- The `src/interface` folder contains source React & Svelte files that are required for the Settings page.
- The `dist` folder is where the compiled code ends up, this is the folder what you need to load into chrome as an unpacked extension for development.
## Contributors
<a href="https://github.com/betterseqta/betterseqta-plus/graphs/contributors">
<img src="https://contrib.rocks/image?repo=betterseqta/betterseqta-plus" />
</a>
Want to contribute? [Click Here!](https://github.com/BetterSEQTA/BetterSEQTA-Plus/blob/main/CONTRIBUTING.md)
## Credits
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) and the rest of the BetterSEQTA team.
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 by [SethBurkart123](https://github.com/SethBurkart123) and [Crazypersonalph](https://github.com/Crazypersonalph)
## Star history
## Star History
[![Star History Chart](https://api.star-history.com/svg?repos=BetterSEQTA/BetterSEQTA-Plus&type=Date)](https://star-history.com/#BetterSEQTA/BetterSEQTA-Plus&Date)
[![Star History Chart](https://api.star-history.com/svg?repos=BetterSEQTA/BetterSEQTA-Plus&type=Date)](https://star-history.com/#sethburkart123/EvenBetterSEQTA&Date)
+12 -5
View File
@@ -1,9 +1,16 @@
# Security policy
# Security Policy
## Supported versions
## Supported Versions
Only the latest release gets security fixes. Store installs update automatically. If you sideload from GitHub, grab the newest [release](https://github.com/BetterSEQTA/BetterSEQTA-Plus/releases).
Below here is the supported versions of BetterSEQTA+. Anything older than this is not supported and contains bugs.
## Reporting a vulnerability
| Version | Supported |
| ------- | ------------------ |
| 3.4.0 | :white_check_mark: |
| <= 3.3 | :x: |
Please report vulnerabilities privately through [GitHub Security Advisories](https://github.com/BetterSEQTA/BetterSEQTA-Plus/security/advisories/new), not in a public issue.
`*` May not work on other devices.
## Reporting a Vulnerability
If you find vulnerabilities, REPORT IT IMMEDIATELY. Make an issue and use the template provided for vulnerabilities.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 6.6 KiB

File diff suppressed because it is too large. Load diff
-146
View File
@@ -1,146 +0,0 @@
# BetterSEQTA Cloud — settings sync (server specification)
This document describes the HTTP API the BetterSEQTA+ extension expects for **cloud backup of extension settings**. The client is implemented in the extension repo; the accounts service (`accounts.betterseqta.org`) must implement these endpoints.
## Purpose
- Store **one JSON document per authenticated BetterSEQTA Cloud user** representing a snapshot of the extension’s `chrome.storage.local` data (theme, layout, plugin settings, `plugin.*` keys, etc.).
- The extension **does not upload OAuth tokens** (`bsplus_token`, `bsplus_refresh_token`, `bsplus_client_id`, `bsplus_user`). Those remain only on the client.
- **Download** replaces local storage with the stored snapshot, then the client reapplies the current device’s session tokens so the user stays signed in.
## Base URL
All routes below are relative to:
`https://accounts.betterseqta.org`
## Authentication
Every request must include:
```http
Authorization: Bearer <access_token>
```
Use the same **access tokens** issued by the existing BetterSEQTA+ OAuth flows (`/api/bsplus/login`, `/api/bsplus/refresh`). Resolve the user from the token; the document is scoped to that user.
## Endpoints
### `PUT /api/bsplus/settings/sync`
Upserts the caller’s settings backup. The server **merges** `data` into the stored JSON document; keys omitted from the patch are **not** deleted.
**Request body (JSON):**
```json
{
"schemaVersion": 1,
"themeId": "uuid-string-or-empty",
"data": {
"DarkMode": true,
"selectedTheme": "uuid-or-empty-string"
}
}
```
The extension sends a **sparse patch**: only keys that changed since the last successful upload (or, on first upload, keys that differ from schema defaults). A full snapshot is not required.
- **`schemaVersion`**: integer. The extension currently sends `1`. The server may reject unknown major versions or store it for future migrations.
- **`themeId`**: optional but recommended duplicate of **`data.selectedTheme`**. Should be the UUID of the **installed** BetterSEQTA store theme (`selectedTheme`). This may be a normal theme id **or** a **flavour (slave) variant** id from themes with **`flavours[]`** — the extension uses it after restore to prefetch `theme.json` when missing locally (same **`GET …/themes/{id}/download`** as the store UI). Persist and return **`themeId`** in sync with **`data.selectedTheme`**.
- **`data`**: object whose keys are storage keys (strings) and values are JSON-serializable values (same types as stored in `chrome.storage.local`).
**Success response:** HTTP `200` (or `201` if you prefer create semantics). Example:
```json
{
"updated_at": "2026-04-07T12:00:00.000Z",
"patch": { "DarkMode": true }
}
```
`updated_at` should be an ISO 8601 timestamp of the save time. The extension displays success without requiring extra fields. Optional `patch` may echo the merged keys applied server-side.
**Error responses:** Standard JSON error body if applicable, e.g. `{ "error": "message" }`, with appropriate HTTP status (`401`, `413`, `422`, etc.).
---
### `GET /api/bsplus/settings/sync`
Returns the caller’s latest settings backup.
**Success response:** HTTP `200` with body:
```json
{
"schemaVersion": 1,
"themeId": "uuid-string-or-empty",
"data": {},
"updated_at": "2026-04-07T12:00:00.000Z"
}
```
- **`data`**: required for restore; must be the same shape as accepted in `PUT` (flat map of storage keys).
- **`themeId`**: optional; if present must match **`data.selectedTheme`** (see `PUT`).
- **`schemaVersion`**: optional but recommended; should match what was stored.
- **`updated_at`**: optional; included for UX if the client shows “last backup” time.
The extension resolves **`themeId`** (if non-empty), else **`data.selectedTheme`,** to [`resolveThemeIdForPostSyncDownload`](../src/seqta/utils/cloudSettingsSync.ts) after downloading the envelope — used only to reinstall theme assets from **`betterseqta.org`** when IndexedDB lacks that id (see **BetterSEQTA Cloud** flavour note in **[THEME_STORE_FLAVOURS_API](./THEME_STORE_FLAVOURS_API.md)** section “Cloud settings sync compatibility”).
**No backup yet:** HTTP **`404`**. The extension treats this as “nothing in the cloud” and shows an error to the user.
**Error responses:** `401` if the token is invalid, etc.
---
## Suggested database shape
Example relational layout:
| Column | Type | Notes |
| ------------ | ------------ | -------------------------------------------------------------------------------------- |
| `user_id` | FK → users | Unique per backup row (one row per user). |
| `payload` | JSON / JSONB | Store `{ "schemaVersion", "data" }` or only `data` + separate `schema_version` column. |
| `updated_at` | timestamptz | Set on each successful `PUT`. |
Unique constraint on `user_id`.
## Semantics
- **Merge on PUT:** each `PUT` deep-merges `data` into the stored backup for that user. Keys not present in the request body remain unchanged on the server.
- **Full document on GET:** restore and poll download still receive the complete hydrated settings object.
- **Optional later:** `If-Unmodified-Since` or a `revision` field for conflict detection (not required for v1).
## Security and privacy
- **Encryption at rest** for `payload` is recommended.
- Payload may contain **school-related UI preferences** and plugin data; treat as **user data** under your privacy policy.
- **Do not require or store** refresh/access tokens in the payload; the extension already strips them on upload.
### Never included in the sync payload (`chrome.storage.local` only)
The backup is a flat JSON map of **`chrome.storage.local`** keys. It does **not** include:
- **IndexedDB** — e.g. the Global Search index (`betterseqta-index` and related DBs) lives outside extension storage and is never serialized here.
- **OAuth / session keys** — `bsplus_token`, `bsplus_refresh_token`, `bsplus_client_id`, `bsplus_user`, plus legacy `cloudAccessToken` / `cloudUsername`.
- **Assessment Averages caches** — `plugin.assessments-average.storage.assessments`, `plugin.assessments-average.storage.weightings` (school assessment data).
- **Keys under** `plugin.global-search.storage.*` — reserved so any future plugin storage cache there is not synced.
- **Grade Analytics** — keys under `bsplus.analytics.*` (synced assessment cache and per-school chart preferences).
- **`bsplus_cloud_settings_last_uploaded_snapshot`** — client-only normalized map last acked by PUT; used to compute sparse upload patches (not part of the cloud backup blob).
- **`bsplus_cloud_settings_known_remote_updated_at`** — client-only watermark for auto-sync (not part of the cloud backup blob).
On restore, those keys are **not** taken from the server; the device keeps its current local values.
## Related endpoint: `GET /api/user/cloud-summary`
The extension may call **`GET /api/user/cloud-summary`** (same host, `Authorization: Bearer`) for a **small** JSON summary (e.g. whether DesQTA / BetterSEQTA+ cloud settings exist and **`bsplus.updated_at`** / **`schemaVersion`**). It does **not** return the large settings `data` blob.
- **Auto-sync flow:** compare `bsplus.updated_at` to a **client-only** watermark stored in extension storage as **`bsplus_cloud_settings_known_remote_updated_at`** (never uploaded, never applied from the server payload; preserved on restore).
- If the server timestamp is newer (and `schemaVersion` is not ahead of the client), the client then calls **`GET /api/bsplus/settings/sync`** and applies the full envelope as usual.
This uses standard **WebExtension** APIs (`browser.alarms`, `runtime` messages, `storage`) and works on **Chromium and Firefox** builds.
## Client reference (extension)
- Upload (sparse patch): `buildUploadPatch` / `putSettingsOnce` in `src/background/cloudSettingsAutoSync.ts`; baseline from `bsplus_cloud_settings_last_uploaded_snapshot` or schema defaults; dev full export via `getSnapshotForUpload` / `buildUploadPayload` in `src/seqta/utils/cloudSettingsSync.ts` (strips OAuth-related keys, sensitive device keys, client-only metadata — includes **`themeId`** aligned with **`selectedTheme`**).
- Download: resolve id via **`resolveThemeIdForPostSyncDownload`** → **`applyDownloadedEnvelope`** after `GET` → prefetch theme blobs in page context if needed (**`prepareThemeAfterCloudSync`** in **`ThemeManager`**) → reload SEQTA tabs; local auth keys, sensitive device keys, client-only watermark, and **`bsplus_pending_theme_ensure_after_cloud`** semantics preserved as documented above.
- Auto sync (summary, debounced upload, alarms): `src/background/cloudSettingsAutoSync.ts`; content script triggers a poll on each verified SEQTA Learn/Engage page load (top frame) via `cloudSettingsPoll`.
-19
View File
@@ -1,19 +0,0 @@
# Docs
The main documentation lives at **[docs.betterseqta.org](https://docs.betterseqta.org/)**, built from [BetterSEQTA-Docs](https://github.com/BetterSEQTA/BetterSEQTA-Docs). Send fixes for those pages there.
| Topic | Where |
| --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Installing | [docs.betterseqta.org/install](https://docs.betterseqta.org/install/) |
| Architecture | [docs.betterseqta.org/architecture](https://docs.betterseqta.org/architecture/) |
| Writing plugins | [Plugin development](https://docs.betterseqta.org/plugin-development/), [Plugin API](https://docs.betterseqta.org/plugin-api/), [Example plugin](https://docs.betterseqta.org/example-plugin/) |
| Making themes | [docs.betterseqta.org/theme-creation](https://docs.betterseqta.org/theme-creation/) |
| Troubleshooting | [docs.betterseqta.org/troubleshooting](https://docs.betterseqta.org/troubleshooting/) |
These pages only live in this repo because they track the code closely:
- [RELEASES.md](RELEASES.md): CI, stable and nightly releases, and the update badge.
- [CLOUD_SETTINGS_SYNC_SERVER.md](CLOUD_SETTINGS_SYNC_SERVER.md): the HTTP API the extension expects for cloud settings backup.
- [CLOUD_SETTINGS_SYNC_OPTIONS.md](CLOUD_SETTINGS_SYNC_OPTIONS.md): every value that goes into a cloud backup and how it is stored.
For contributing, see [CONTRIBUTING.md](../CONTRIBUTING.md).
-58
View File
@@ -1,58 +0,0 @@
# Releases, CI and the update badge
BetterSEQTA+ ships through the Chrome Web Store and Firefox Add-ons. GitHub also hosts sideload builds, and those builds can tell users when a newer one is out. This page covers how all of that is built.
## Workflows
| Workflow | Runs on | What it does |
| ------------------------------------------------- | ---------------------------------------------------------------- | ----------------------------------------------------------------------------- |
| [`pr-ci.yml`](../.github/workflows/pr-ci.yml) | Every pull request and push to `main` | Lint, unit tests, then build and smoke test. Uploads the zips as an artifact. |
| [`nightly.yml`](../.github/workflows/nightly.yml) | Daily at 13:30 UTC (midnight in Adelaide during daylight saving) | Builds `main` and replaces the assets on the `nightly` prerelease. |
Both build through the shared [`build-extension`](../.github/actions/build-extension/action.yml) action: install with `npm ci`, run `npm run build` for Chrome and Firefox, then zip `dist/chrome` and `dist/firefox`. Nightly publishes with the default `GITHUB_TOKEN`, so it needs no extra secrets.
## Publishing a stable release
Stable releases are published by hand:
1. Bump `version` in `package.json` on `main` and push it.
2. Build with the update checker, then zip:
```bash
GH_RELEASE_UPDATE_CHECK=true UPDATE_CHANNEL=stable npm run build
npm run zip
```
3. Run `npm run release`. It creates the release for that version with generated notes and uploads `betterseqtaplus@{version}-chrome.zip` and `-firefox.zip`.
## Nightly builds
The `nightly` tag always points at the latest build of `main`. Each run renames the release to `Nightly (YYYY-MM-DD)` and replaces its zips (`betterseqtaplus-nightly-{date}-chrome.zip` and `-firefox.zip`). The release text comes from [`nightly-release-notes.md`](../.github/nightly-release-notes.md) when the release is first created.
Get it from [releases/tag/nightly](https://github.com/BetterSEQTA/BetterSEQTA-Plus/releases/tag/nightly).
GitHub builds are for sideloading only. Never upload them to an extension store.
## Build-time flags
Release builds pass these into Vite, which bakes them in through `define` in [`vite.config.ts`](../vite.config.ts). Their types live in [`src/env.d.ts`](../src/env.d.ts).
| Variable | Stable | Nightly | PRs and local builds |
| ------------------------- | ------------------------------ | -------------- | -------------------- |
| `GH_RELEASE_UPDATE_CHECK` | `true` | `true` | unset |
| `UPDATE_CHANNEL` | `stable` | `nightly` | unset |
| `GH_RELEASE_REPO` | `BetterSEQTA/BetterSEQTA-Plus` | same | same |
| `BUILD_LABEL` | empty | UTC build date | empty |
Without `GH_RELEASE_UPDATE_CHECK=true`, the update checker is removed from the bundle entirely.
## Update badge
Release builds show an amber **Update — {version}** pill at the bottom of the settings sidebar when a newer build exists. Clicking it opens the releases page. The logic is in [`src/utils/githubReleaseUpdate.ts`](../src/utils/githubReleaseUpdate.ts):
- **Stable** compares the highest semver release tag (ignoring `nightly`) with the installed version.
- **Nightly** compares the `nightly` release's publish time with the last one seen, stored as `lastSeenNightlyPublishedAt`. The first check after install only records it.
Checks run at most every 6 hours (`localStorage` key `bsplus_lastGhReleaseCheck`).
To test the badge without publishing, turn on dev mode (click the settings logo and type `dev`), then set **GitHub latest version override** in the Advanced section to a higher version such as `9.9.9`.
+162
View File
@@ -0,0 +1,162 @@
<!DOCTYPE html>
<html>
<head>
<title>BetterSEQTA Settings</title>
<style>
:root {
--background-primary: #ffffff;
--background-secondary: #e5e7eb;
--text-primary: black;
--theme-primary: #4F46E5;
--theme-hover: #4338CA;
}
@media (prefers-color-scheme: dark) {
:root {
--background-primary: #232323;
--background-secondary: #1a1a1a;
--text-primary: white;
--theme-primary: #6366F1;
--theme-hover: #818CF8;
}
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}
body {
background: var(--background-primary);
color: var(--text-primary);
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
padding: 2rem;
}
.container {
width: 100%;
max-width: 100%;
display: flex;
flex-direction: column;
gap: 1rem;
}
h1 {
font-size: 1.75rem;
font-weight: 500;
margin-bottom: 0.25rem;
}
.subtitle {
color: #666;
font-size: 1rem;
margin-bottom: 1.5rem;
}
label {
display: block;
margin-bottom: 0.25rem;
font-weight: 500;
color: var(--text-primary);
}
input[type="url"] {
width: 100%;
padding: 0.75rem 1rem;
border: 1px solid var(--background-secondary);
border-radius: 8px;
font-size: 1rem;
background: var(--background-secondary);
color: var(--text-primary);
transition: all 0.2s;
}
input[type="url"]:focus {
outline: none;
border-color: var(--theme-primary);
box-shadow: 0 0 0 2px rgba(79, 70, 229, 0.1);
}
button {
margin-top: 1rem;
width: 100%;
padding: 0.75rem;
border: none;
border-radius: 8px;
background: var(--theme-primary);
color: white;
font-size: 1rem;
font-weight: 500;
cursor: pointer;
transition: all 0.2s;
}
button:hover {
background: var(--theme-hover);
}
#error-message {
color: #EF4444;
font-size: 0.875rem;
margin-top: 0.5rem;
display: none;
}
</style>
</head>
<body>
<div class="container">
<h1>BetterSEQTA Settings</h1>
<div class="subtitle">It's time to get started! To begin type in your school's SEQTA URL below.</div>
<label for="seqtaUrl">SEQTA Website URL</label>
<input type="url" id="seqtaUrl" placeholder="Enter your school's SEQTA URL (e.g https://seqta.school.edu.au)" required>
<div id="error-message"></div>
<button onclick="saveSettings()">Save Settings</button>
</div>
<script>
const electron = window.require('electron');
const { ipcRenderer } = electron;
const Store = window.require('electron-store');
const store = new Store();
// Load saved URL on page load
window.addEventListener('DOMContentLoaded', () => {
const savedUrl = store.get('seqtaUrl') || '';
document.getElementById('seqtaUrl').value = savedUrl;
});
// Handle error messages from main process
ipcRenderer.on('seqta-url-error', (event, message) => {
const errorElement = document.getElementById('error-message');
errorElement.textContent = message;
errorElement.style.display = 'block';
});
// Save settings
function saveSettings() {
const url = document.getElementById('seqtaUrl').value;
const errorElement = document.getElementById('error-message');
errorElement.style.display = 'none';
if (url) {
ipcRenderer.send('set-seqta-url', url);
} else {
errorElement.textContent = 'Please enter a URL';
errorElement.style.display = 'block';
}
}
// Handle enter key
document.getElementById('seqtaUrl').addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
saveSettings();
}
});
</script>
</body>
</html>
+333
View File
@@ -0,0 +1,333 @@
import { app, BrowserWindow, ipcMain, session, Menu } from 'electron';
import path from 'path';
import { fileURLToPath } from 'url';
import Store from 'electron-store';
// Fix for __dirname in ES modules
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const store = new Store();
let mainWindow = null;
let settingsWindow = null;
// CSS to inject
const customCSS = `
#alertBar {
display: none !important;
}
/* Match SEQTA's styling */
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif !important;
}
`;
// Create the application menu
function createAppMenu() {
const isMac = process.platform === 'darwin';
const template = [
...(isMac ? [{
label: app.name,
submenu: [
{ role: 'about' },
{ type: 'separator' },
{ role: 'services' },
{ type: 'separator' },
{ role: 'hide' },
{ role: 'hideOthers' },
{ role: 'unhide' },
{ type: 'separator' },
{ role: 'quit' }
]
}] : []),
{
label: 'Settings',
submenu: [
{
label: 'Configure SEQTA URL',
accelerator: isMac ? 'Cmd+,' : 'Ctrl+,',
click: () => {
createSettingsWindow();
}
}
]
},
{
label: 'View',
submenu: [
{ role: 'reload' },
{ role: 'forceReload' },
{ role: 'toggleDevTools' },
{ type: 'separator' },
{ role: 'resetZoom' },
{ role: 'zoomIn' },
{ role: 'zoomOut' },
{ type: 'separator' },
{ role: 'togglefullscreen' }
]
}
];
const menu = Menu.buildFromTemplate(template);
Menu.setApplicationMenu(menu);
}
// Validate SEQTA URL
function isValidSeqtaUrl(url) {
try {
const urlObj = new URL(url);
// Only ensure it's a valid HTTPS URL
return urlObj.protocol === 'https:';
} catch {
return false;
}
}
// Get the correct path for the extension based on whether we're in development or production
function getExtensionPath() {
if (app.isPackaged) {
// In production, the extension is in the resources directory
return path.join(process.resourcesPath, 'chrome-extension');
} else {
// In development, the extension is in the dist directory
return path.join(__dirname, '..', 'dist', 'chrome');
}
}
// Load the Chrome extension
async function loadExtension() {
try {
const extensionPath = getExtensionPath();
console.log('Loading extension from:', extensionPath);
await session.defaultSession.loadExtension(extensionPath, {
allowFileAccess: true
});
console.log('Extension loaded successfully!');
} catch (err) {
console.error('Failed to load extension:', err);
}
}
function createMainWindow() {
console.log('🚀 Creating main window...');
if (mainWindow) {
if (!mainWindow.isDestroyed()) {
console.log('✨ Existing window found, focusing it');
mainWindow.focus();
return mainWindow;
}
console.log('🔄 Old window was destroyed, creating new one');
}
console.log('📦 Initializing new BrowserWindow');
mainWindow = new BrowserWindow({
width: 1200,
height: 800,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
backgroundThrottling: false,
enableWebSQL: false,
webgl: false,
offscreen: false
},
show: false,
backgroundColor: '#ffffff'
});
const seqtaUrl = store.get('seqtaUrl');
console.log('📍 Stored SEQTA URL:', seqtaUrl);
// Register keyboard shortcut for settings
mainWindow.webContents.on('before-input-event', (event, input) => {
if ((input.meta || input.control) && input.key === ',') {
createSettingsWindow();
}
});
// Inject CSS when the page loads
mainWindow.webContents.on('did-finish-load', () => {
console.log('🎨 Page loaded, injecting CSS');
mainWindow.webContents.insertCSS(customCSS).catch(err => {
console.error('Failed to inject CSS:', err);
});
});
// Only show window when it's ready
mainWindow.once('ready-to-show', () => {
console.log('🎉 Window ready to show!');
mainWindow.show();
mainWindow.focus();
});
if (seqtaUrl) {
if (!isValidSeqtaUrl(seqtaUrl)) {
console.error('❌ Invalid SEQTA URL stored:', seqtaUrl);
createSettingsWindow();
return;
}
console.log('🌐 Loading SEQTA URL:', seqtaUrl);
mainWindow.loadURL(seqtaUrl)
.then(() => {
console.log('✅ Successfully loaded SEQTA URL');
mainWindow.show();
mainWindow.focus();
})
.catch(err => {
console.error('❌ Failed to load SEQTA URL:', err);
createSettingsWindow();
});
} else {
console.log('⚙️ No SEQTA URL found, opening settings');
createSettingsWindow();
}
return mainWindow;
}
function createSettingsWindow() {
if (settingsWindow) {
settingsWindow.focus();
return;
}
settingsWindow = new BrowserWindow({
width: 600,
height: 400,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
},
show: false,
backgroundColor: '#ffffff'
});
const settingsPath = path.join(__dirname, 'index.html');
settingsWindow.loadFile(settingsPath);
settingsWindow.once('ready-to-show', () => {
settingsWindow.show();
settingsWindow.focus();
});
// Only enable DevTools in development
if (process.env.NODE_ENV === 'development') {
settingsWindow.webContents.openDevTools();
}
settingsWindow.on('closed', () => {
settingsWindow = null;
});
}
// Performance optimization: Disable hardware acceleration if running on low-end device
if (process.platform !== 'darwin') { // Skip for macOS
app.disableHardwareAcceleration();
}
// Performance optimization: Disable smooth scrolling
app.commandLine.appendSwitch('disable-smooth-scrolling');
// Wait for app to be ready before creating windows
app.whenReady().then(async () => {
createAppMenu();
await loadExtension();
createMainWindow();
});
// Performance optimization: Quit immediately instead of gracefully
app.on('window-all-closed', () => {
app.quit();
});
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createMainWindow();
}
});
// Format and validate SEQTA URL
function formatAndValidateUrl(url) {
// Remove any whitespace
url = url.trim();
// If no protocol specified, add https://
if (!url.startsWith('http://') && !url.startsWith('https://')) {
url = 'https://' + url;
}
// If it's http://, upgrade to https://
if (url.startsWith('http://')) {
url = 'https://' + url.slice(7);
}
try {
const urlObj = new URL(url);
// Ensure it's https
if (urlObj.protocol !== 'https:') {
throw new Error('URL must use HTTPS');
}
return { isValid: true, url: url };
} catch (error) {
return { isValid: false, url: url, error: error.message };
}
}
// Handle setting the SEQTA URL
ipcMain.on('set-seqta-url', (event, url) => {
console.log('🔧 Received new SEQTA URL:', url);
const { isValid, url: formattedUrl, error } = formatAndValidateUrl(url);
if (!isValid) {
console.error('❌ Invalid URL format:', error);
event.reply('seqta-url-error', 'Please enter a valid URL');
return;
}
console.log('💾 Saving URL to store:', formattedUrl);
store.set('seqtaUrl', formattedUrl);
// Create main window if it doesn't exist
if (!mainWindow || mainWindow.isDestroyed()) {
console.log('🆕 Creating new main window');
createMainWindow();
} else {
console.log('🔄 Loading new URL in existing window:', formattedUrl);
mainWindow.loadURL(formattedUrl).then(() => {
console.log('✅ URL loaded successfully');
console.log('🎨 Injecting CSS and settings button');
mainWindow.webContents.insertCSS(customCSS).catch(err => {
console.error('Failed to inject CSS:', err);
});
mainWindow.webContents.executeJavaScript(`
if (!document.getElementById('bsp-settings-button')) {
document.body.insertAdjacentHTML('beforeend', ${JSON.stringify(settingsButtonHTML)});
document.getElementById('bsp-settings-button').addEventListener('click', () => {
window.postMessage('open-settings', '*');
});
}
`).catch(err => {
console.error('Failed to inject settings button:', err);
});
console.log('👀 Showing and focusing window');
mainWindow.show();
mainWindow.focus();
}).catch(err => {
console.error('❌ Failed to load SEQTA URL:', err);
event.reply('seqta-url-error', 'Failed to load SEQTA. Please check your connection and URL.');
});
}
// Close settings window if it exists
if (settingsWindow && !settingsWindow.isDestroyed()) {
console.log('🚪 Closing settings window');
settingsWindow.close();
}
});
-20
View File
@@ -1,20 +0,0 @@
export default {
preset: "ts-jest",
testEnvironment: "node",
roots: ["<rootDir>/src"],
testMatch: ["**/__tests__/**/*.ts", "**/?(*.)+(spec|test).ts"],
transform: {
"^.+\\.ts$": "ts-jest",
"^.+\\.js$": ["ts-jest", { tsconfig: { allowJs: true } }],
},
transformIgnorePatterns: ["/node_modules/(?!(color|color-string|color-convert|color-name)/)"],
moduleNameMapper: {
"^@/(.*)\\?script(?:&(?:iife|module))?$": "<rootDir>/src/test/mocks/crxjsScriptPath.ts",
"^@/lib/browser$": "<rootDir>/src/test/mocks/browser.ts",
"^@/(.*)$": "<rootDir>/src/$1",
"^color$": "<rootDir>/src/test/mocks/color.ts",
},
setupFilesAfterEnv: ["<rootDir>/src/test/jest.setup.ts"],
moduleFileExtensions: ["ts", "js", "json"],
collectCoverageFrom: ["src/**/*.ts", "!src/**/*.d.ts"],
};
+4 -5
View File
@@ -1,17 +1,16 @@
import fs from "node:fs";
import fs from "fs";
import mime from "mime-types";
export const base64Loader = {
name: "base64-loader",
transform(_sourceCode: string, id: string) {
void _sourceCode;
transform(_: any, id: string) {
const [filePath, query] = id.split("?");
if (query !== "base64") return null;
const data = fs.readFileSync(filePath, { encoding: "base64" });
const data = fs.readFileSync(filePath, { encoding: 'base64' });
const mimeType = mime.lookup(filePath);
const dataURL = `data:${mimeType};base64,${data}`;
return `export default '${dataURL}';`;
},
};
};
+32 -4
View File
@@ -1,5 +1,33 @@
import type { Browser, BuildTarget, Manifest } from "./types.ts";
export function createManifest(manifest: Manifest, browser: Browser): BuildTarget {
return { manifest, browser };
import type { Browser, BuildTarget, Manifest } from './types'
import type { AnyCase } from './utils'
/**
*
*
* @export
* @param {Manifest} manifest
* @param {AnyCase<Browser>} browser
* @return {*} {@link BuildTarget}
*/
export function createManifest(
manifest: Manifest,
browser: AnyCase<Browser>,
): BuildTarget {
return {
manifest,
browser,
}
}
/**
* create a base Manifest to inherit from
* type Manifest = chrome.runtime.ManifestV3
*
* use as shared base to extend inBrowser manifests
*
* @export
* @param {Manifest} manifest
* @return {*} {@link Manifest}
*/
export function createManifestBase(manifest: Manifest): Manifest {
return manifest
}
-25
View File
@@ -1,25 +0,0 @@
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)})` };
}
},
},
};
},
};
}
-43
View File
@@ -1,43 +0,0 @@
import type { Plugin } from "vite";
/**
* Firefox extension pages forbid eval / `Function` constructor. Some deps still emit:
* - `Function(\`return this\`)()` (lodash-style global)
* - `try { return Function(\`\`) / new Function("") … }` (feature probes, e.g. PDF.js / ORT)
*/
export function firefoxStripFunctionProbe(): Plugin {
return {
name: "firefox-strip-function-probe",
apply: "build",
enforce: "post",
generateBundle(_options, bundle) {
if ((process.env.MODE || "chrome").toLowerCase() !== "firefox") return;
const literalReplacements: [string, string][] = [
['try{return new Function(""),!0}catch{return!1}', "return!1"],
["try{return new Function(''),!0}catch{return!1}", "return!1"],
['try{return new Function(""),true}catch{return false}', "return false"],
["try{return new Function(''),true}catch{return false}", "return false"],
// Empty template literal probe (minifier output)
["try{return Function(``),!0}catch{return!1}", "return!1"],
];
for (const chunk of Object.values(bundle)) {
if (chunk.type !== "chunk" || typeof chunk.code !== "string") continue;
let { code } = chunk;
code = code.replace(/Function\(`return this`\)\(\)/g, "(globalThis)");
code = code.replace(/Function\("return this"\)\(\)/g, "(globalThis)");
code = code.replace(/Function\('return this'\)\(\)/g, "(globalThis)");
for (const [from, to] of literalReplacements) {
if (code.includes(from)) {
code = code.split(from).join(to);
}
}
chunk.code = code;
}
},
};
}
-19
View File
@@ -1,19 +0,0 @@
import type { Plugin } from "vite";
/**
* crxjs 2.6.x only replaces the first `__LIVE_RELOAD__` in `@crx/client-worker`,
* which crashes the service worker when the dev server reconnects.
*/
export default function fixCrxWorkerLiveReload(): Plugin {
return {
name: "fix-crx-worker-live-reload",
apply: "serve",
enforce: "post",
transform(code, id) {
if (!id.includes("@crx/client-worker") || !code.includes("__LIVE_RELOAD__")) {
return;
}
return code.replaceAll("__LIVE_RELOAD__", "true");
},
};
}
-40
View File
@@ -1,40 +0,0 @@
import { Plugin } from "vite";
import { build } from "esbuild";
import { resolve } from "node:path";
/** Bundle worker entry points imported with `?inlineWorker` as Blob-backed Workers in dev. */
export default function InlineWorkerDevPlugin(): Plugin {
return {
name: "vite:inline-worker-dev",
async load(id) {
if (!id.includes("?inlineWorker")) return null;
const [cleanPath] = id.split("?");
const result = await build({
entryPoints: [cleanPath],
bundle: true,
write: false,
platform: "browser",
format: "iife",
target: "esnext",
minify: true,
conditions: ["onnxruntime-web-use-extern-wasm"],
alias: {
"@huggingface/transformers": resolve(
"node_modules/@huggingface/transformers/dist/transformers.web.js",
),
},
external: ["@/lib/browser"],
});
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' });
}
`;
},
};
}
+65
View File
@@ -0,0 +1,65 @@
/*
TEMPORARY FIX FOR CHROME 130+ builds
*/
import path from 'node:path';
import fs from 'fs';
import { PluginOption } from 'vite';
import { ManifestV3Export } from '@crxjs/vite-plugin';
const manifestPath = path.resolve('dist/chrome/manifest.json');
export function updateManifestPlugin(): PluginOption {
return {
name: 'update-manifest-plugin',
enforce: 'post',
closeBundle() {
forceDisableUseDynamicUrl();
},
configureServer(server) {
server.httpServer?.once('listening', () => {
const updated = forceDisableUseDynamicUrl();
if (updated) {
server.ws.send({ type: 'full-reload' });
console.log('** updated **');
}
fs.watchFile(manifestPath, () => {
console.log('** watchFile ** ');
const manifestContents = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
if (manifestContents.web_accessible_resources.some((resource: any) => resource.use_dynamic_url)) {
const updated = forceDisableUseDynamicUrl();
if (updated) {
server.ws.send({ type: 'full-reload' });
console.log('** updated **');
}
}
});
});
},
writeBundle() {
console.log('### writeBundle ##');
forceDisableUseDynamicUrl();
},
};
}
function forceDisableUseDynamicUrl() {
if (!fs.existsSync(manifestPath)) {
return false;
}
const manifestContents = JSON.parse(fs.readFileSync(manifestPath, 'utf8')) as Awaited<ManifestV3Export>;
if (typeof manifestContents === 'function' || !manifestContents.web_accessible_resources) return false;
if (manifestContents.web_accessible_resources.every((resource) => !resource.use_dynamic_url)) return false;
manifestContents.web_accessible_resources.forEach((resource) => {
if (resource.use_dynamic_url) resource.use_dynamic_url = false;
});
fs.writeFileSync(manifestPath, JSON.stringify(manifestContents, null, 2));
return true;
}
+48 -116
View File
@@ -1,90 +1,31 @@
/**
* @fileoverview
* This script is a command-line utility for publishing the BetterSEQTA+ extension.
* It automates the process of finding the latest built extension ZIP files for specified
* browsers, zipping the project source code (for Firefox), and then invoking the
* `publish-extension` tool with the appropriate arguments.
*
* To use this script, invoke it with Node.js followed by browser arguments:
* e.g., `node lib/publish.js --b chrome firefox`
* or `node lib/publish.js --b chrome`
* or `node lib/publish.js --b firefox`
*/
import { globSync } from "node:fs";
import semver from "semver";
import { execSync } from "node:child_process";
const glob = require('glob');
const semver = require('semver');
const { execSync } = require('child_process');
const path = require('path');
function getLatestVersion(files) {
console.log("Files passed to getLatestVersion:", files);
console.log('Files passed to getLatestVersion:', files);
const versions = files.map(file => {
const match = file.match(/@(\d+\.\d+\.\d+)-/);
console.log('Matching file:', file, 'Version found:', match ? match[1] : 'None');
return match ? match[1] : null;
}).filter(Boolean);
const versions = files
.map((file) => {
const match = file.match(/@([\d.]+)-/);
console.log("Matching file:", file, "Version found:", match ? match[1] : "None");
if (!match) return null;
const fullVersion = match[1]; // Original version (e.g., 3.4.5.1)
// Trim to 3 parts for semver comparison, as semver typically handles X.Y.Z
const semverVersion = fullVersion.split(".").slice(0, 3).join(".");
return { fullVersion, semverVersion };
})
.filter(Boolean); // Remove null entries if any file didn't match
console.log(
"Extracted versions:",
versions.map((v) => v.semverVersion),
);
if (versions.length === 0) {
console.log("No versions extracted.");
return null;
}
// Find latest version using the trimmed semver format
const latestSemver = semver.maxSatisfying(
versions.map((v) => v.semverVersion),
"*", // Satisfy any version, effectively finding the max
);
console.log("Latest SemVer-compatible version:", latestSemver);
if (!latestSemver) {
console.log("Could not determine latest semver version.");
return null;
}
// Get the original full version string that matches the identified latest SemVer version
const latestVersionData = versions.find((v) => v.semverVersion === latestSemver);
const latestFullVersion = latestVersionData ? latestVersionData.fullVersion : null;
console.log("Final selected latest version:", latestFullVersion);
return latestFullVersion;
console.log('Extracted versions:', versions);
const latestVersion = semver.maxSatisfying(versions, '*');
console.log('Latest version:', latestVersion);
return latestVersion;
}
function getLatestFiles(browser) {
const pattern = `dist/betterseqtaplus@*-*${browser}.zip`;
console.log("Glob pattern:", pattern);
const files = globSync(pattern);
console.log("Files found for browser", browser, ":", files);
if (files.length === 0) {
console.log("No files found for browser", browser);
return undefined;
}
console.log('Glob pattern:', pattern);
const files = glob.sync(pattern);
console.log('Files found for browser', browser, ':', files);
const latestVersion = getLatestVersion(files);
if (!latestVersion) {
console.log("Could not determine latest version for browser", browser);
return undefined;
}
// Find the exact file by matching the original full version string
const latestFile = files.find((file) => file.includes(`@${latestVersion}-`));
console.log("Latest file for browser", browser, ":", latestFile);
const latestFile = files.find(file => file.includes(latestVersion));
console.log('Latest file for browser', browser, ':', latestFile);
return latestFile;
}
@@ -92,52 +33,44 @@ function zipSources() {
const zipFileName = `dist/betterseqtaplus@latest-sources.zip`;
const excludePatterns = [
"node_modules",
"dist",
".env*",
".git",
".github",
".vscode",
"LICENSE",
"package.json",
]
.map((pattern) => `-x!${pattern}`) // Format for 7z exclude syntax
.join(" ");
'node_modules',
'dist',
'.env*',
'.git',
'.github',
'.vscode',
'LICENSE',
'package.json'
].map(pattern => `-x!${pattern}`).join(' ');
// Command to zip the current directory's contents into zipFileName, applying exclude patterns
const zipCommand = `7zz a ${zipFileName} . ${excludePatterns}`;
const zipCommand = `7z a ${zipFileName} . ${excludePatterns}`;
console.log("Zipping project sources with command:", zipCommand);
execSync(zipCommand, { stdio: "inherit" }); // Execute synchronously and show output
console.log('Zipping project sources with command:', zipCommand);
execSync(zipCommand, { stdio: 'inherit' });
return zipFileName;
}
function runPublishCommand(browsers) {
const chromeZip = browsers.includes("chrome") ? getLatestFiles("chrome") : null;
const firefoxZip = browsers.includes("firefox") ? getLatestFiles("firefox") : null;
// Sources are typically only needed for Firefox submissions
const firefoxSourcesZip = browsers.includes("firefox") ? zipSources() : null;
const chromeZip = browsers.includes('chrome') ? getLatestFiles('chrome') : null;
const firefoxZip = browsers.includes('firefox') ? getLatestFiles('firefox') : null;
const firefoxSourcesZip = browsers.includes('firefox') ? zipSources() : null;
console.log("Chrome zip:", chromeZip);
console.log("Firefox zip:", firefoxZip);
console.log("Firefox sources zip:", firefoxSourcesZip);
console.log('Chrome zip:', chromeZip);
console.log('Firefox zip:', firefoxZip);
console.log('Firefox sources zip:', firefoxSourcesZip);
if (browsers.length === 0) {
console.log("No browsers specified. Exiting.");
process.exit(0); // Exit gracefully if no action is needed
console.log('No browsers specified. Exiting.');
process.exit(0);
}
// Check if required files are missing for the specified browsers
if (
(browsers.includes("chrome") && !chromeZip) ||
(browsers.includes("firefox") && (!firefoxZip || !firefoxSourcesZip))
) {
console.error("Could not find required zip files for specified browsers.");
process.exit(1); // Exit with error status
if ((browsers.includes('chrome') && !chromeZip) || (browsers.includes('firefox') && (!firefoxZip || !firefoxSourcesZip))) {
console.error('Could not find required zip files for specified browsers.');
process.exit(1);
}
let command = "publish-extension";
let command = 'publish-extension';
if (chromeZip) {
command += ` --chrome-zip ${chromeZip}`;
}
@@ -145,14 +78,13 @@ function runPublishCommand(browsers) {
command += ` --firefox-zip ${firefoxZip} --firefox-sources-zip ${firefoxSourcesZip}`;
}
console.log("Running command:", command);
execSync(command, { stdio: "inherit" }); // Execute and show output
console.log('Running command:', command);
execSync(command, { stdio: 'inherit' });
}
// Parse command-line arguments to determine which browsers to publish for
// Parse command-line arguments
const args = process.argv.slice(2);
const browserIndex = args.indexOf("--b"); // Find the --b flag
// If --b is found, take all subsequent arguments as browser names
const browserIndex = args.indexOf('--b');
const browsers = browserIndex !== -1 ? args.slice(browserIndex + 1) : [];
runPublishCommand(browsers);
runPublishCommand(browsers);
-53
View File
@@ -1,53 +0,0 @@
import type { Plugin, ViteDevServer } from "vite";
/**
* CRXJS + Vite 6 often corrupt content-script ESM bindings after HMR /
* `[crx] runtime reload` — modules load but named/`default` exports are missing
* until the dev server is restarted.
*
* Prefer invalidating the module graph + a full page reload over partial HMR.
*/
export default function stabilizeCrxDevHmr(): Plugin {
let reloadTimer: ReturnType<typeof setTimeout> | null = null;
const scheduleFullReload = (s: ViteDevServer) => {
if (reloadTimer) clearTimeout(reloadTimer);
// Debounce cascading invalidations (e.g. many files in one save).
reloadTimer = setTimeout(() => {
reloadTimer = null;
s.ws.send({ type: "full-reload", path: "*" });
}, 50);
};
return {
name: "stabilize-crx-dev-hmr",
apply: "serve",
enforce: "pre",
configureServer(s) {
s.ws.on("bsplus:reset-module-graph", () => {
s.moduleGraph.invalidateAll();
scheduleFullReload(s);
});
},
handleHotUpdate({ file, modules, server: viteServer }) {
if (!file.replace(/\\/g, "/").includes("/src/")) return;
if (file.includes("node_modules")) return;
const seen = new Set(modules);
const queue = [...modules];
while (queue.length) {
const mod = queue.pop()!;
viteServer.moduleGraph.invalidateModule(mod);
for (const importer of mod.importers) {
if (seen.has(importer)) continue;
seen.add(importer);
queue.push(importer);
}
}
scheduleFullReload(viteServer);
// Skip Vite's partial HMR for these modules — it is what leaves exports empty.
return [];
},
};
}
+100 -6
View File
@@ -1,10 +1,104 @@
import type { ManifestV3Export } from "@crxjs/vite-plugin";
import type { ManifestV3Export } from '@crxjs/vite-plugin'
import { type AnyCase, createEnum } from './utils'
export type Manifest = ManifestV3Export;
export const FrameworkEnum = {
React: 'React',
Vanilla: 'Vanilla',
Preact: 'Preact',
Lit: 'Lit',
Svelte: 'Svelte',
Vue: 'Vue',
} as const
export type Browser = "chrome" | "brave" | "edge" | "firefox" | "opera" | "safari";
export const BrowserEnum = {
Chrome: 'Chrome',
Brave: 'Brave',
Opera: 'Opera',
Edge: 'Edge',
Firefox: 'Firefox',
Safari: 'Safari',
} as const
const LanguageEnum = {
TypeScript: 'TypeScript',
JavaScript: 'JavaScript',
} as const
export const StyleEnum = {
Tailwind: 'Tailwind',
} as const
export const PackageManagerEnum = {
Bun: 'Bun',
PnPm: 'PnPm',
Npm: 'Npm',
Yarn: 'Yarn',
} as const
// see: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/firefox-webext-browser/index.d.ts
export type BrowserSpecificSettings = {
browser_specific_settings?: {
gecko?: {
id: string
strict_min_version?: string
strict_max_version?: string
}
}
}
export type Manifest = ManifestV3Export
export type ManifestIcons = chrome.runtime.ManifestIcons
export type ManifestBackground = chrome.runtime.ManifestV3['background']
export type ManifestContentScripts =
chrome.runtime.ManifestV3['content_scripts']
export type ManifestWebAccessibleResources =
chrome.runtime.ManifestV3['web_accessible_resources']
export type ManifestCommands = chrome.runtime.ManifestV3['commands']
export type ManifestAction = chrome.runtime.ManifestV3['action']
export type ManifestPermissions = chrome.runtime.ManifestV3['permissions']
export type ManifestOptionsUI = chrome.runtime.ManifestV3['options_ui']
export type ManifestURLOverrides =
chrome.runtime.ManifestV3['chrome_url_overrides']
export type BrowserName<T extends string> = Capitalize<T> | Lowercase<T>
export type BrowserEnumType<T extends string> = {
[browser in BrowserName<T>]: BrowserName<T>
}
export type BuildMode = AnyCase<Browser>
export type BuildTarget = {
manifest: Manifest;
browser: Browser;
};
manifest: Manifest
browser: AnyCase<Browser>
}
export type BuildConfig = {
command?: 'build' | 'serve'
mode?: AnyCase<Browser> | string | undefined
}
export interface Repository {
type: string
url?: string
bugs?: Bugs
}
export interface Bugs {
url?: string
email?: string
}
export type Browser = (typeof BrowserEnum)[keyof typeof BrowserEnum]
export const Browser: AnyCase<Browser> = createEnum(BrowserEnum)
export type PackageManager =
(typeof PackageManagerEnum)[keyof typeof PackageManagerEnum]
export const PackageManager: AnyCase<PackageManager> =
createEnum(PackageManagerEnum)
export type Framework = (typeof FrameworkEnum)[keyof typeof FrameworkEnum]
export const Framework: AnyCase<Framework> = createEnum(FrameworkEnum)
export type Style = (typeof StyleEnum)[keyof typeof StyleEnum]
export const Style: AnyCase<Style> = createEnum(StyleEnum)
export type Language = (typeof LanguageEnum)[keyof typeof LanguageEnum]
export const Language: AnyCase<Language> = createEnum(LanguageEnum)
+21
View File
@@ -0,0 +1,21 @@
export type ObjectValues<T> = T[keyof T]
export function createEnum<T extends Record<string, string>>(enumObj: T) {
return Object.values(enumObj) as unknown as ObjectValues<T>
}
export type AnyCase<T extends string> =
| Uppercase<T>
| Lowercase<T>
| Capitalize<T>
| Uncapitalize<T>
export type AnyCaseLanguage<T extends string, K extends string> =
| Uppercase<T | K>
| Lowercase<T | K>
| Capitalize<T | K>
| Uncapitalize<T | K>
export type OptionalKeys<T> = {
[K in keyof T as undefined extends T[K] ? K : never]: T[K]
}
-10936
View File
File diff suppressed because it is too large. Load diff
+134 -98
View File
@@ -1,114 +1,150 @@
{
"name": "betterseqtaplus",
"version": "3.7.7",
"description": "Enhance SEQTA Learn's usability and aesthetics! A fork of BetterSEQTA to continue development and add heaps more features!",
"keywords": [],
"license": "MIT",
"author": {
"name": "SethBurkart123",
"email": "betterseqta.plus@gmail.com",
"url": "https://github.com/BetterSEQTA/BetterSEQTA-Plus"
},
"version": "3.4.2",
"type": "module",
"description": "Enhance SEQTA Learn's usability and aesthetics! A fork of BetterSEQTA to continue development, while incorporating a plethora of new and improved features!",
"main": "electron/main.js",
"browserslist": "> 0.5%, last 2 versions, not dead",
"scripts": {
"compile:layerchart": "node scripts/compile-layerchart-vendor.mjs",
"postinstall": "node scripts/copy-runtime-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": "npm run compile:layerchart && cross-env MODE=chrome vite build && cross-env MODE=firefox vite build",
"build": "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",
"build:dev": "cross-env MODE=chrome SOURCEMAP=true vite build && cross-env MODE=firefox SOURCEMAP=true vite build",
"convert:safari": "xcrun safari-web-extension-converter dist/safari --project-location . --app-name $npm_package_name-safari",
"lint": "oxlint --deny-warnings",
"format": "oxfmt",
"format:check": "oxfmt --check",
"typecheck": "svelte-check --tsconfig ./tsconfig.json --fail-on-warnings",
"test": "npm run test:unit",
"test:unit": "cross-env NODE_OPTIONS=--no-experimental-webstorage jest",
"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": "node lib/publish.js --b",
"zip": "node scripts/package-extension-zips.mjs"
"release": "gh release create $npm_package_name@$npm_package_version ./dist/*.zip --generate-notes",
"publish": "bun lib/publish.js --b",
"zip": "bedframe zip",
"electron-dev": "electron .",
"electron-build": "electron-builder",
"electron-pack": "npm run build:chrome && electron-builder --dir",
"electron-dist": "npm run build:chrome && electron-builder"
},
"targets": {
"prod": {
"sourceMap": {
"inline": false
}
}
},
"keywords": [],
"author": {
"name": "SethBurkart123",
"email": "betterseqta@betterseqta.com",
"url": "https://github.com/BetterSEQTA/BetterSEQTA-plus"
},
"license": "MIT",
"devDependencies": {
"@babel/plugin-transform-runtime": "^7.25.9",
"@babel/runtime": "^7.26.0",
"@crxjs/vite-plugin": "2.0.0-beta.25",
"@types/mime-types": "^2.1.4",
"@vitejs/plugin-react-swc": "^3.7.0",
"cross-env": "^7.0.3",
"electron": "^33.2.1",
"electron-builder": "^25.1.8",
"eslint": "^8.57.0",
"glob": "^11.0.0",
"mime-types": "^2.1.35",
"prettier": "^3.3.3",
"process": "^0.11.10",
"sass": "^1.78.0",
"sass-loader": "^13.3.3",
"semver": "^7.6.3",
"url": "^0.11.4"
},
"dependencies": {
"@codemirror/autocomplete": "^6.20.4",
"@codemirror/commands": "^6.11.1",
"@codemirror/lang-css": "^6.3.1",
"@codemirror/language": "^6.13.1",
"@codemirror/search": "^6.7.2",
"@codemirror/state": "^6.7.6",
"@codemirror/view": "^6.43.15",
"@huggingface/transformers": "^3.8.1",
"@uiw/codemirror-extensions-color": "^4.25.12",
"@uiw/codemirror-theme-github": "^4.25.12",
"canvas-confetti": "^1.9.4",
"color": "^5.0.3",
"d3-scale": "^4.0.2",
"d3-shape": "^3.2.0",
"dompurify": "^3.4.17",
"embeddia": "^1.3.0",
"embla-carousel-autoplay": "^8.6.0",
"embla-carousel-svelte": "^8.6.0",
"fuse.js": "^7.5.0",
"layerchart": "^2.9.2",
"@bedframe/cli": "^0.0.85",
"@codemirror/lang-css": "^6.3.0",
"@codemirror/lang-less": "^6.0.2",
"@codemirror/theme-one-dark": "^6.1.2",
"@sveltejs/vite-plugin-svelte": "^4.0.0",
"@tailwindcss/forms": "^0.5.9",
"@tsconfig/svelte": "^5.0.4",
"@types/chrome": "^0.0.270",
"@types/color": "^3.0.6",
"@types/dompurify": "^3.0.5",
"@types/lodash": "^4.17.7",
"@types/node": "^20.16.5",
"@types/react": "17",
"@types/react-dom": "17",
"@types/sortablejs": "^1.15.8",
"@types/uuid": "^9.0.8",
"@types/webextension-polyfill": "^0.10.7",
"@uiw/codemirror-extensions-color": "^4.23.3",
"@uiw/codemirror-theme-github": "^4.23.3",
"@vitejs/plugin-react": "^4.3.1",
"autoprefixer": "^10.4.20",
"caniuse-lite": "^1.0.30001684",
"classnames": "^2.5.1",
"codemirror": "^6.0.1",
"color": "^4.2.3",
"dompurify": "^3.1.6",
"electron-store": "^10.0.0",
"embla-carousel-autoplay": "^8.3.1",
"embla-carousel-svelte": "^8.3.1",
"fuse.js": "^7.0.0",
"idb": "^8.0.0",
"kolorist": "^1.8.0",
"localforage": "^1.10.0",
"mathjs": "^15.2.0",
"motion": "^14.9.0",
"pdfjs-dist": "^6.5.438",
"qrcode": "^1.5.4",
"semver": "^7.7.1",
"sortablejs": "^1.15.7",
"svelte": "^5.57.3"
"lodash": "^4.17.21",
"million": "^3.1.11",
"motion": "^11.12.0",
"postcss": "^8.4.45",
"publish-browser-extension": "^2.2.1",
"react": "17",
"react-best-gradient-color-picker": "^3.0.10",
"react-dom": "17",
"sortablejs": "^1.15.3",
"svelte": "^5.1.9",
"tailwindcss": "^3.4.11",
"typescript": "^5.6.2",
"uuid": "^9.0.1",
"vite": "^5.4.4",
"webextension-polyfill": "^0.10.0"
},
"devDependencies": {
"@crxjs/vite-plugin": "^3.0.0",
"@jest/globals": "^30.5.2",
"@sveltejs/vite-plugin-svelte": "^7.3.1",
"@tailwindcss/forms": "^0.5.11",
"@tailwindcss/postcss": "^4.3.3",
"@tsconfig/svelte": "^5.0.8",
"@types/canvas-confetti": "^1.9.0",
"@types/chrome": "^0.3.7",
"@types/d3-scale": "^4.0.9",
"@types/d3-shape": "^3.2.0",
"@types/jest": "^30.0.0",
"@types/mime-types": "^3.0.1",
"@types/node": "^26.6.6",
"@types/qrcode": "^1.5.6",
"@types/semver": "^7.8.0",
"@types/sortablejs": "^1.15.9",
"cross-env": "^10.1.0",
"esbuild": "^0.28.2",
"jest": "^30.5.2",
"jest-environment-jsdom": "^30.5.2",
"mime-types": "^3.0.2",
"oxfmt": "^0.75.0",
"oxlint": "^1.90.0",
"publish-browser-extension": "^6.2.0",
"sass": "^1.107.1",
"svelte-check": "^4.7.8",
"tailwindcss": "^4.3.3",
"ts-jest": "^29.4.15",
"typescript": "~6.0.3",
"vite": "^8.3.5"
},
"overrides": {
"glob": "^14.0.3"
},
"browserslist": "> 0.5%, last 2 versions, not dead",
"engines": {
"node": ">=26"
},
"allowScripts": {
"@parcel/watcher": false,
"esbuild": false,
"onnxruntime-node": false,
"protobufjs": false,
"sharp": false
"build": {
"appId": "com.betterseqta.app",
"productName": "BetterSEQTA",
"directories": {
"output": "electron-dist",
"buildResources": "build"
},
"files": [
"dist/**/*",
"electron/**/*",
"!**/node_modules/*/{CHANGELOG.md,README.md,README,readme.md,readme}",
"!**/node_modules/*/{test,__tests__,tests,powered-test,example,examples}",
"!**/node_modules/*.d.ts",
"!**/node_modules/.bin",
"!**/*.{iml,o,hprof,orig,pyc,pyo,rbc,swp,csproj,sln,xproj}",
"!.editorconfig",
"!**/._*",
"!**/{.DS_Store,.git,.hg,.svn,CVS,RCS,SCCS,.gitignore,.gitattributes}",
"!**/{__pycache__,thumbs.db,.flowconfig,.idea,.vs,.nyc_output}",
"!**/{appveyor.yml,.travis.yml,circle.yml}",
"!**/{npm-debug.log,yarn.lock,.yarn-integrity,.yarn-metadata.json}"
],
"extraResources": [
{
"from": "dist/chrome",
"to": "chrome-extension",
"filter": ["**/*"]
}
],
"mac": {
"category": "public.app-category.education",
"target": ["dmg", "zip"],
"icon": "build/icon.icns"
},
"win": {
"target": "nsis",
"icon": "build/icon.ico"
},
"linux": {
"target": "AppImage",
"icon": "build/icon.png"
}
}
}
+6
View File
@@ -0,0 +1,6 @@
export default {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
-194
View File
@@ -1,194 +0,0 @@
/**
* Chrome trace analyzer — aggregates hotspots for BetterSEQTA+ optimization.
* Usage: node scripts/analyze-trace.mjs <path-to-trace.json>
*/
import fs from "node:fs";
const path = process.argv[2];
if (!path) {
console.error("Usage: node scripts/analyze-trace.mjs <trace.json>");
process.exit(1);
}
const raw = fs.readFileSync(path, "utf8");
const { traceEvents } = JSON.parse(raw);
const openStacks = new Map(); // key -> { name, cat, args, ts }
const byName = new Map();
const byCat = new Map();
const byUrl = new Map();
const byFunction = new Map();
const layoutEvents = [];
const paintEvents = [];
const longTasks = [];
const timers = [];
const observers = [];
const hitTests = [];
const betterseqtaHits = new Map();
const ipcMessages = new Map();
const gcEvents = [];
let minTs = Infinity;
let maxTs = -Infinity;
function add(map, key, dur, count = 1) {
const e = map.get(key) ?? { dur: 0, count: 0 };
e.dur += dur;
e.count += count;
map.set(key, e);
}
for (const ev of traceEvents) {
if (ev.ts != null) {
minTs = Math.min(minTs, ev.ts);
maxTs = Math.max(maxTs, ev.ts);
}
const ph = ev.ph;
const name = ev.name ?? "";
const cat = ev.cat ?? "";
const args = ev.args ?? {};
if (ph === "b") {
openStacks.set(`${ev.pid}:${ev.tid}:${ev.id ?? name}`, ev);
continue;
}
let dur = ev.dur ?? 0;
if (ph === "e" && ev.id != null) {
const start = openStacks.get(`${ev.pid}:${ev.tid}:${ev.id}`);
if (start) dur = ev.ts - start.ts;
}
if (dur <= 0 && ph !== "X") continue;
add(byName, name, dur);
const catParts = cat.split(",").filter(Boolean);
for (const c of catParts.length ? catParts : [cat || "(none)"]) {
add(byCat, c, dur);
}
const url =
args.data?.url ?? args.url ?? args.fileName ?? args.data?.scriptName ?? args.data?.frame ?? "";
if (url && typeof url === "string" && dur > 0) {
add(byUrl, url.slice(0, 200), dur);
}
const fn =
(args.data?.functionName ?? args.functionName ?? args.data?.columnNumber != null)
? `${args.data?.functionName ?? name}@${args.data?.url ?? ""}:${args.data?.lineNumber ?? "?"}`
: "";
if (fn && dur > 100) {
add(byFunction, String(fn).slice(0, 250), dur);
}
if (/Layout|UpdateLayoutTree|InvalidateLayout|LocalFrameView::performLayout/i.test(name)) {
layoutEvents.push({ name, dur, ts: ev.ts, cat });
}
if (/Paint|Raster|DrawFrame|CompositeLayers|UpdateLayer/i.test(name)) {
paintEvents.push({ name, dur, ts: ev.ts });
}
if (name === "RunTask" && dur > 50000) {
longTasks.push({ dur, ts: ev.ts, cat, args: JSON.stringify(args).slice(0, 300) });
}
if (
/Timer|setTimeout|setInterval|FireIdleCallback|requestAnimationFrame|RequestAnimationFrame/i.test(
name,
)
) {
timers.push({ name, dur, ts: ev.ts });
}
if (
/MutationObserver|ResizeObserver|IntersectionObserver|DeliverObservations|NotifyMutation/i.test(
name,
)
) {
observers.push({ name, dur, ts: ev.ts });
}
if (/HitTest|FindElement|ElementAt/i.test(name)) {
hitTests.push({ name, dur, ts: ev.ts });
}
if (/V8\.GC|GC_|MajorGC|MinorGC|IncrementalMarking/i.test(name)) {
gcEvents.push({ name, dur, ts: ev.ts });
}
if (/IPC|MessagePort|postMessage/i.test(name)) {
add(ipcMessages, name, dur);
}
const blob = JSON.stringify(args);
if (/betterseqta|BetterSEQTA|bsplus|SEQTA\.ts|monofile|AddBetterSEQTA/i.test(blob + name + url)) {
const key = `${name} | ${(url || blob).slice(0, 120)}`;
add(betterseqtaHits, key, dur);
}
}
function top(map, n = 40, minCount = 1) {
return [...map.entries()]
.filter(([, v]) => v.count >= minCount)
.sort((a, b) => b[1].dur - a[1].dur)
.slice(0, n)
.map(([k, v]) => ({
key: k,
totalMs: (v.dur / 1000).toFixed(1),
count: v.count,
avgMs: (v.dur / v.count / 1000).toFixed(2),
}));
}
const traceDurationMs = ((maxTs - minTs) / 1000).toFixed(0);
console.log(
JSON.stringify(
{
summary: {
traceDurationMs,
eventCount: traceEvents.length,
layoutCount: layoutEvents.length,
layoutTotalMs: (layoutEvents.reduce((s, e) => s + e.dur, 0) / 1000).toFixed(1),
paintCount: paintEvents.length,
paintTotalMs: (paintEvents.reduce((s, e) => s + e.dur, 0) / 1000).toFixed(1),
longTaskCount: longTasks.length,
longTaskTotalMs: (longTasks.reduce((s, e) => s + e.dur, 0) / 1000).toFixed(1),
timerCount: timers.length,
timerTotalMs: (timers.reduce((s, e) => s + e.dur, 0) / 1000).toFixed(1),
observerCount: observers.length,
observerTotalMs: (observers.reduce((s, e) => s + e.dur, 0) / 1000).toFixed(1),
hitTestCount: hitTests.length,
hitTestTotalMs: (hitTests.reduce((s, e) => s + e.dur, 0) / 1000).toFixed(1),
gcCount: gcEvents.length,
gcTotalMs: (gcEvents.reduce((s, e) => s + e.dur, 0) / 1000).toFixed(1),
},
topEventNames: top(byName, 50),
topCategories: top(byCat, 30),
topUrls: top(byUrl, 40),
topFunctions: top(byFunction, 40, 1),
topBetterseqta: top(betterseqtaHits, 50),
topLongTasks: longTasks
.sort((a, b) => b.dur - a.dur)
.slice(0, 20)
.map((e) => ({
ms: (e.dur / 1000).toFixed(1),
cat: e.cat,
args: e.args,
})),
topLayout: layoutEvents
.sort((a, b) => b.dur - a.dur)
.slice(0, 15)
.map((e) => ({
name: e.name,
ms: (e.dur / 1000).toFixed(2),
})),
topObservers: observers
.sort((a, b) => b.dur - a.dur)
.slice(0, 15)
.map((e) => ({
name: e.name,
ms: (e.dur / 1000).toFixed(2),
count: 1,
})),
},
null,
2,
),
);
-80
View File
@@ -1,80 +0,0 @@
/**
* 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`);
-24
View File
@@ -1,24 +0,0 @@
import { copyFileSync, mkdirSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
const root = join(dirname(fileURLToPath(import.meta.url)), "..");
const resources = join(root, "src", "public", "resources");
const files = [
["pdfjs-dist/build/pdf.worker.min.mjs", "pdfjs/pdf.worker.min.mjs"],
["pdfjs-dist/legacy/build/pdf.min.mjs", "pdfjs/pdf.legacy.min.mjs"],
[
"@huggingface/transformers/dist/ort-wasm-simd-threaded.jsep.mjs",
"ort/ort-wasm-simd-threaded.jsep.mjs",
],
[
"@huggingface/transformers/dist/ort-wasm-simd-threaded.jsep.wasm",
"ort/ort-wasm-simd-threaded.jsep.wasm",
],
];
for (const [source, target] of files) {
const output = join(resources, target);
mkdirSync(dirname(output), { recursive: true });
copyFileSync(join(root, "node_modules", source), output);
}
-56
View File
@@ -1,56 +0,0 @@
/**
* 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}`
: `${pkg.name}@${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`);
}
-46
View File
@@ -1,46 +0,0 @@
import fs from "node:fs";
import path from "node:path";
const root = process.cwd();
function fail(message) {
console.error(`[smoke-test] ${message}`);
process.exit(1);
}
function assertManifest(browserDir) {
const manifestPath = path.join(root, "dist", browserDir, "manifest.json");
if (!fs.existsSync(manifestPath)) {
fail(`Missing ${manifestPath} — run npm run build first`);
}
const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8"));
if (!manifest.manifest_version) fail(`${browserDir} manifest missing manifest_version`);
if (!manifest.name) fail(`${browserDir} manifest missing name`);
if (!manifest.version) fail(`${browserDir} manifest missing version`);
const sw = manifest.background?.service_worker ?? manifest.background?.scripts?.[0] ?? null;
if (sw) {
const swPath = path.join(root, "dist", browserDir, sw);
if (!fs.existsSync(swPath)) {
fail(`${browserDir} service worker not found on disk: ${sw}`);
}
}
}
function assertAssets(browserDir) {
const assetsDir = path.join(root, "dist", browserDir, "assets");
if (!fs.existsSync(assetsDir)) {
fail(`Missing assets directory: dist/${browserDir}/assets`);
}
const jsFiles = fs.readdirSync(assetsDir).filter((f) => f.endsWith(".js"));
if (jsFiles.length === 0) {
fail(`No JS assets in dist/${browserDir}/assets`);
}
}
for (const browser of ["chrome", "firefox"]) {
assertManifest(browser);
assertAssets(browser);
}
console.log("[smoke-test] dist/chrome and dist/firefox look OK");
-66
View File
@@ -1,66 +0,0 @@
/** @jest-environment jsdom */
import { execFileSync } from "node:child_process";
import { runInNewContext } from "node:vm";
// Compile the actual Vite entry and the 404 boot it loads in Node (esbuild
// cannot run in jsdom's realm).
const [bootScript, errorPageScript]: string[] = JSON.parse(
execFileSync(
process.execPath,
[
"--input-type=module",
"-e",
`
import { readFileSync } from "node:fs";
import { transformSync } from "esbuild";
const compile = (file) => transformSync(readFileSync(file, "utf8"), {
loader: "ts", format: "cjs",
supported: { "dynamic-import": false },
define: { "import.meta.env.DEV": "false", "import.meta.hot": "undefined" },
}).code;
process.stdout.write(JSON.stringify(["src/SEQTA.ts", "src/seqta/bootErrorPage.ts"].map(compile)));
`,
],
{ encoding: "utf8" },
),
);
test.each([{ onoff: false }, { "plugin.error-page-kitten.settings": { enabled: false } }])(
"disabled 404 customization preserves the native error message: %j",
async (stored) => {
document.head.innerHTML = "";
document.body.innerHTML = '<div class="message">Page not found</div>';
const mount = jest.fn();
const requireMock = (module: string): unknown => {
if (module === "@/seqta/bootErrorPage") {
const loaded = { exports: {} };
runInNewContext(errorPageScript, {
document,
window,
console,
module: loaded,
exports: loaded.exports,
require: requireMock,
});
return loaded.exports;
}
if (module === "@/lib/browser") {
return { storage: { local: { get: async () => stored } } };
}
if (module.includes("errorPageKitten")) {
return { isSeqta404Page: () => true, mountErrorPageKitten: mount };
}
return {};
};
runInNewContext(bootScript, {
document,
window,
console,
require: requireMock,
});
for (let i = 0; i < 10; i++) await Promise.resolve();
expect(mount).not.toHaveBeenCalled();
expect(window.getComputedStyle(document.querySelector(".message")!).display).not.toBe("none");
},
);
+2788 -19
View File
File diff suppressed because it is too large. Load diff
+252 -688
View File
@@ -1,717 +1,281 @@
import browser from "@/lib/browser";
import browser from 'webextension-polyfill'
import type { SettingsState } from "@/types/storage";
import { getDefaultSettingsState } from "@/seqta/utils/defaultSettings";
import { ensureSyncableStorageDefaults } from "@/seqta/utils/ensureSyncableStorageDefaults";
import { fetchNews } from "./background/news";
import {
initCloudSettingsAutoSync,
performCloudSettingsDownloadWithRetry,
performCloudSettingsUploadWithRetry,
requestCloudSettingsDebouncedUpload,
runCloudSettingsPoll,
withSuppressedCloudAutoUpload,
} from "./background/cloudSettingsAutoSync";
import { getBsplusDeviceName } from "@/seqta/utils/bsplusDeviceName";
import { isAllowedFetchUrl } from "@/seqta/utils/allowedFetchUrl";
import {
initCalendarBackground,
registerGoogleCalendarMessageHandlers,
registerOutlookCalendarMessageHandlers,
type CalendarMessageHandlerMap,
} from "./background/calendarBackground";
import { createCustomThemesHandlers } from "./background/customThemesHandlers";
import { DEFAULT_BACKGROUND_PENDING_KEY } from "@/seqta/ui/defaultBackgroundKey";
import { handleSearchThemeStockPhotos } from "./background/searchThemeStockPhotos";
import { initTimetableClassmatesBackgroundSync } from "./background/timetableClassmatesSync";
import { runStorageMigrations } from "./background/storageMigrations";
/**
* Session-only dev-mode override of the content API base.
*
* Stored in a module-level variable (not `chrome.storage`) so it is wiped
* automatically when the browser/service-worker process restarts. Content
* scripts re-sync this on every page load via `setDevApiBase` so the value
* survives transient service-worker terminations within the same browser
* session.
*/
const DEFAULT_API_BASE = "https://betterseqta.org";
let DEV_API_BASE: string | null = null;
function apiBase(): string {
// Extension dev builds always hit production (see DevApiBase.ts).
if (import.meta.env.DEV) return DEFAULT_API_BASE;
return DEV_API_BASE ?? DEFAULT_API_BASE;
}
export const openDB = () => {
return new Promise((resolve, reject) => {
const request = indexedDB.open('MyDatabase', 1);
request.onupgradeneeded = (event: any) => {
const db = event.target.result;
db.createObjectStore('backgrounds', { keyPath: 'id' });
};
request.onsuccess = () => {
resolve(request.result);
};
request.onerror = (event: any) => {
reject('Error opening database: ' + event.target.errorCode);
};
});
};
export const writeData = async (type: any, data: any) => {
const db: any = await openDB();
const tx = db.transaction('backgrounds', 'readwrite');
const store = tx.objectStore('backgrounds');
const request = await store.put({ id: 'customBackground', type, data });
return request.result;
};
export const readData = () => {
return new Promise((resolve, reject) => {
openDB()
.then((db: any) => {
const tx = db.transaction('backgrounds', 'readonly');
const store = tx.objectStore('backgrounds');
// Retrieve the custom background
const getRequest = store.get('customBackground');
// Attach success and error event handlers
getRequest.onsuccess = function(event: any) {
resolve(event.target.result);
};
getRequest.onerror = function(event: any) {
console.error('An error occurred:', event);
reject(event);
};
})
.catch(error => {
console.error('An error occurred:', error);
reject(error);
});
});
};
function reloadSeqtaPages() {
const result = browser.tabs.query({});
function open(tabs: chrome.tabs.Tab[]) {
for (const tab of tabs) {
if (tab.title?.includes("SEQTA Learn") || tab.title?.includes("SEQTA Engage")) {
const result = browser.tabs.query({})
function open (tabs: any) {
for (let tab of tabs) {
if (tab.title.includes('SEQTA Learn')) {
browser.tabs.reload(tab.id);
}
}
}
result.then(open, console.error);
result.then(open, console.error)
}
/** Callback for sending a response back to the message sender */
type MessageSender = { (response?: unknown): void };
/** Runtime message payloads from extension pages / content scripts */
type BackgroundRequest = Record<string, unknown>;
function reqString(req: BackgroundRequest, key: string): string | undefined {
const value = req[key];
return typeof value === "string" ? value : undefined;
}
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;
data?: { themes: unknown[] };
error?: string;
} {
if (!json || typeof json !== "object") {
return { success: false, error: "Invalid themes response" };
}
const body = json as Record<string, unknown>;
if (body.success === false) {
return {
success: false,
error: typeof body.error === "string" ? body.error : "Failed to fetch themes",
};
}
const data = body.data;
let themes: unknown[] | null = null;
if (data && typeof data === "object" && !Array.isArray(data)) {
const nested = (data as Record<string, unknown>).themes;
if (Array.isArray(nested)) themes = nested;
} else if (Array.isArray(data)) {
themes = data;
}
if (!themes && Array.isArray(body.themes)) {
themes = body.themes;
}
if (!themes) {
return { success: false, error: "Themes list missing from response" };
}
return { success: true, data: { themes } };
}
function handleFetchThemes(_request: unknown, sendResponse: MessageSender): boolean {
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}`,
);
// Main message listener
browser.runtime.onMessage.addListener((request: any, _sender: any, sendResponse: any) => {
switch (request.type) {
case 'reloadTabs':
reloadSeqtaPages();
break;
case 'extensionPages':
browser.tabs.query({}).then(function (tabs) {
for (let tab of tabs) {
if (tab.url?.includes('chrome-extension://')) {
browser.tabs.sendMessage(tab.id!, request);
}
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: BackgroundRequest, sendResponse: MessageSender): boolean {
const { themeId } = request;
if (!themeId || typeof themeId !== "string") {
sendResponse({ success: false, error: "Missing themeId" });
return false;
}
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 isTrustedSender(sender?: chrome.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 (pageUrl.startsWith("chrome-extension://") || pageUrl.startsWith("moz-extension://")) {
return true;
}
try {
if (isSeqtaOrigin(new URL(pageUrl).origin)) return true;
} catch {}
}
return false;
}
function handleFetchFromUrl(
request: BackgroundRequest,
sendResponse: MessageSender,
sender?: chrome.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;
}
void (async () => {
try {
const headers: Record<string, string> = { Accept: "application/json" };
if (request.auth === true) {
const token = await getAccessTokenFromStorage();
if (!token) {
sendResponse({ error: "Not authenticated" });
return;
}
headers.Authorization = `Bearer ${token}`;
}
const r = await fetch(url, { cache: "no-store", headers });
const text = await r.text();
if (!r.ok) {
sendResponse({
error: text?.slice(0, 200) || `HTTP ${r.status}`,
httpStatus: r.status,
});
return;
}
try {
sendResponse({ data: text ? JSON.parse(text) : {} });
} catch {
sendResponse({ error: "Invalid JSON response" });
}
} catch (err) {
console.error("[Background] fetchFromUrl error:", err);
sendResponse({ error: (err as Error)?.message });
}
})();
return true;
}
async function parseJsonResponse(r: Response): Promise<unknown> {
const text = await r.text();
try {
return text ? JSON.parse(text) : {};
} catch {
return {};
}
}
function handleCloudReserveClient(
request: BackgroundRequest,
sendResponse: MessageSender,
): boolean {
const redirect_uri =
request.redirect_uri ?? "https://accounts.betterseqta.org/auth/bsplus/callback";
fetch("https://accounts.betterseqta.org/api/bsplus/client/reserve", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ redirect_uri }),
})
.then(async (r) => {
const data = await parseJsonResponse(r);
const errorText =
data && typeof data === "object" && "error" in data
? String((data as { error?: unknown }).error)
: undefined;
if (!r.ok) sendResponse({ error: errorText ?? `Reserve failed (${r.status})` });
else sendResponse(data);
})
.catch((err) => {
console.error("[Background] cloudReserveClient error:", err);
sendResponse({ error: err?.message ?? "Network error" });
});
return true;
}
function handleCloudLogin(
request: BackgroundRequest,
sendResponse: MessageSender,
sender?: chrome.runtime.MessageSender,
): boolean {
if (!isTrustedSender(sender)) {
sendResponse({ error: "Unauthorized sender" });
return false;
}
const client_id = reqString(request, "client_id");
const redirect_uri = reqString(request, "redirect_uri");
const login = reqString(request, "login");
const password = reqString(request, "password");
const device_name = reqString(request, "device_name");
if (!client_id || !redirect_uri || !login || !password) {
sendResponse({ error: "Missing client_id, redirect_uri, login, or password" });
return false;
}
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),
break;
case 'currentTab':
browser.tabs.query({ active: true, currentWindow: true }).then(function (tabs) {
browser.tabs.sendMessage(tabs[0].id!, request).then(function (response) {
sendResponse(response);
});
const data = await parseJsonResponse(r);
const errorText =
data && typeof data === "object" && "error" in data
? String((data as { error?: unknown }).error)
: undefined;
if (!r.ok) sendResponse({ error: errorText ?? "Login failed" });
else sendResponse(data);
} catch (err) {
console.error("[Background] cloudLogin error:", err);
sendResponse({ error: (err as Error)?.message ?? "Network error" });
}
})();
return true;
}
function handleCloudStartLogin(request: BackgroundRequest, sendResponse: MessageSender): boolean {
const client_id = reqString(request, "client_id");
const redirect_uri = reqString(request, "redirect_uri");
if (!client_id || !redirect_uri) {
sendResponse({ error: "Missing client_id or redirect_uri" });
});
return true;
case 'githubTab':
browser.tabs.create({ url: 'github.com/BetterSEQTA/BetterSEQTA-Plus' });
break;
case 'setDefaultStorage':
SetStorageValue(DefaultValues);
break;
case 'sendNews':
const date = new Date();
const from =
date.getFullYear() +
'-' +
(date.getMonth() + 1) +
'-' +
(date.getDate() - 5);
const url = `https://newsapi.org/v2/everything?domains=abc.net.au&from=${from}&apiKey=17c0da766ba347c89d094449504e3080`;
GetNews(sendResponse, url);
return true;
default:
console.log('Unknown request type');
}
const authorizeUrl = `https://accounts.betterseqta.org/login?redirect=${encodeURIComponent(`/oauth/authorize?client_id=${client_id}&redirect_uri=${encodeURIComponent(redirect_uri)}`)}`;
browser.tabs
.create({ url: authorizeUrl })
.then(() => {
sendResponse({ success: true });
})
.catch((err) => {
console.error("[Background] cloudStartLogin error:", err);
sendResponse({ error: err?.message ?? "Failed to open login page" });
});
return true;
}
const CALLBACK_URL_PREFIX = "https://accounts.betterseqta.org/auth/bsplus/callback";
function initCloudLoginCallbackListener() {
browser.tabs.onUpdated.addListener((tabId, changeInfo) => {
if (changeInfo.url && changeInfo.url.startsWith(CALLBACK_URL_PREFIX)) {
try {
const url = new URL(changeInfo.url);
const token = url.searchParams.get("token");
const refreshToken = url.searchParams.get("refresh_token");
const userId = url.searchParams.get("user_id");
if (token && refreshToken) {
void (async () => {
try {
await browser.storage.local.set({
bsplus_token: token,
bsplus_refresh_token: refreshToken,
});
const userRes = await fetch("https://accounts.betterseqta.org/api/auth/me", {
headers: { Authorization: `Bearer ${token}` },
});
if (userRes.ok) {
const user = await userRes.json();
await browser.storage.local.set({ bsplus_user: user });
} else if (userId) {
await browser.storage.local.set({ bsplus_user: { id: userId } });
}
void performCloudSettingsDownloadWithRetry(token).catch((err) => {
console.warn("[Background] Cloud settings download after login:", err);
});
} catch (err) {
console.error("[Background] Failed to process login callback:", err);
}
})();
void browser.tabs.remove(tabId);
}
} catch (err) {
console.error("[Background] Error parsing callback URL:", err);
}
}
});
}
initCloudLoginCallbackListener();
function handleCloudRefresh(request: BackgroundRequest, sendResponse: MessageSender): boolean {
const { refresh_token, client_id } = request;
if (!refresh_token || !client_id) {
sendResponse({ error: "Missing refresh_token or client_id" });
return false;
}
fetch("https://accounts.betterseqta.org/api/bsplus/refresh", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ refresh_token, client_id }),
})
.then(async (r) => {
const data = await parseJsonResponse(r);
const errorText =
data && typeof data === "object" && "error" in data
? String((data as { error?: unknown }).error)
: undefined;
if (!r.ok) sendResponse({ error: errorText ?? "Refresh failed" });
else sendResponse(data);
})
.catch((err) => {
console.error("[Background] cloudRefresh error:", err);
sendResponse({ error: err?.message ?? "Network error" });
});
return true;
}
function handleCloudSettingsUpload(
_request: unknown,
sendResponse: MessageSender,
sender?: chrome.runtime.MessageSender,
): boolean {
if (!isTrustedSender(sender)) {
sendResponse({ success: false, error: "Unauthorized sender" });
return false;
}
void (async () => {
try {
const token = await getAccessTokenFromStorage();
if (!token) {
sendResponse({ success: false, error: "Not authenticated" });
return;
}
const res = await performCloudSettingsUploadWithRetry(token);
sendResponse({
success: res.success,
error: res.error,
updated_at: res.updated_at,
});
} catch (err) {
console.error("[Background] cloudSettingsUpload error:", err);
sendResponse({
success: false,
error: err instanceof Error ? err.message : "Upload failed",
});
}
})();
return true;
}
function handleCloudSettingsDownload(
_request: unknown,
sendResponse: MessageSender,
sender?: chrome.runtime.MessageSender,
): boolean {
if (!isTrustedSender(sender)) {
sendResponse({ success: false, error: "Unauthorized sender" });
return false;
}
void (async () => {
try {
const token = await getAccessTokenFromStorage();
if (!token) {
sendResponse({ success: false, error: "Not authenticated" });
return;
}
const res = await performCloudSettingsDownloadWithRetry(token);
sendResponse({
success: res.success,
notFound: res.notFound,
error: res.error,
updated_at: res.updated_at,
});
} catch (err) {
console.error("[Background] cloudSettingsDownload error:", err);
sendResponse({
success: false,
error: err instanceof Error ? err.message : "Download failed",
});
}
})();
return true;
}
function handleCloudFavorite(request: BackgroundRequest, sendResponse: MessageSender): boolean {
const { themeId, action } = request;
if (!themeId) {
sendResponse({ success: false, error: "Theme ID required" });
return false;
}
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;
}
/** Handler for a message type; receives request, sendResponse, and optional sender (for tab routing) */
type MessageHandler = {
(
request: BackgroundRequest,
sendResponse: MessageSender,
sender?: chrome.runtime.MessageSender,
): boolean | void;
};
function isSeqtaOrigin(origin: string): boolean {
try {
const u = new URL(origin);
return u.hostname.includes("seqta") || u.hostname.endsWith(".edu.au");
} catch {
return false;
}
}
function handleSetDevApiBase(
request: BackgroundRequest,
_sendResponse: MessageSender,
sender?: chrome.runtime.MessageSender,
): boolean {
if (!isTrustedSender(sender)) return false;
if (import.meta.env.DEV) {
DEV_API_BASE = null;
return false;
}
const url = typeof request?.url === "string" ? request.url.trim() : null;
if (url && /^https?:\/\//.test(url)) {
DEV_API_BASE = url.replace(/\/$/, "");
} else {
DEV_API_BASE = null;
}
return false;
}
const customThemesHandlers = createCustomThemesHandlers({
apiBase,
getAccessTokenFromStorage,
});
const MESSAGE_HANDLERS: Record<string, MessageHandler> = {
...customThemesHandlers,
searchThemeStockPhotos: handleSearchThemeStockPhotos,
reloadTabs: () => reloadSeqtaPages(),
setDevApiBase: handleSetDevApiBase,
extensionPages: (req) => {
browser.tabs.query({}).then((tabs) => {
for (const tab of tabs) {
if (tab.url?.includes("chrome-extension://")) browser.tabs.sendMessage(tab.id!, req);
function GetNews(sendResponse: any, url: string) {
fetch(url)
.then((result) => result.json())
.then((response) => {
if (response.code == 'rateLimited') {
GetNews(sendResponse, url += '%00');
} else {
sendResponse({ news: response });
}
});
},
currentTab: (req, sendResponse) => {
browser.tabs.query({ active: true, currentWindow: true }).then((tabs) => {
browser.tabs.sendMessage(tabs[0].id!, req).then(sendResponse);
});
return true;
},
githubTab: () => {
void browser.tabs.create({ url: "github.com/BetterSEQTA/BetterSEQTA-Plus" });
},
setDefaultStorage: () => SetStorageValue(getDefaultValues()),
ensureStorageDefaults: (_req, sendResponse) => {
void ensureSyncableStorageDefaults()
.then(() => sendResponse({ ok: true }))
.catch((e) => {
console.warn("[BetterSEQTA+] ensureStorageDefaults failed:", e);
sendResponse({ ok: false });
});
return true;
},
sendNews: (req, sendResponse, sender) => {
if (!isTrustedSender(sender)) {
sendResponse({ error: "Unauthorized sender" });
return false;
}
const source = typeof req.source === "string" ? req.source : undefined;
void fetchNews(source).then((news) => sendResponse({ news }));
return true;
},
fetchThemes: handleFetchThemes,
fetchThemeDetails: handleFetchThemeDetails,
fetchFromUrl: handleFetchFromUrl,
cloudReserveClient: handleCloudReserveClient,
cloudLogin: handleCloudLogin,
cloudStartLogin: handleCloudStartLogin,
cloudRefresh: handleCloudRefresh,
cloudFavorite: handleCloudFavorite,
cloudSettingsUpload: handleCloudSettingsUpload,
cloudSettingsDownload: handleCloudSettingsDownload,
cloudSettingsPoll: () => {
void runCloudSettingsPoll();
return false;
},
cloudSettingsRequestDebouncedUpload: () => {
requestCloudSettingsDebouncedUpload();
return false;
},
getSeqtaSession: (
req: { baseUrl?: string },
sendResponse: MessageSender,
sender?: chrome.runtime.MessageSender,
) => {
(async () => {
try {
let tabId = sender?.tab?.id;
let originForCheck: string | undefined = req.baseUrl;
if (tabId == null) {
const tabs = await browser.tabs.query({ active: true, lastFocusedWindow: true });
const tab = tabs[0];
if (!tab?.id || !tab.url) {
sendResponse({ appLink: null });
return;
}
tabId = tab.id;
if (!originForCheck) originForCheck = new URL(tab.url).origin;
} else if (!originForCheck && sender?.tab?.url) {
originForCheck = new URL(sender.tab.url).origin;
}
if (!originForCheck || !isSeqtaOrigin(originForCheck)) {
sendResponse({ appLink: null });
return;
}
const reply = (await browser.tabs.sendMessage(tabId, { type: "fetchSeqtaAppLink" })) as
| { appLink?: string | null }
| undefined;
const appLink =
typeof reply?.appLink === "string" && reply.appLink.length > 0 ? reply.appLink : null;
sendResponse({ appLink });
} catch (err) {
console.error("[Background] getSeqtaSession error:", err);
sendResponse({ appLink: null });
}
})();
return true;
},
};
registerGoogleCalendarMessageHandlers(
MESSAGE_HANDLERS as CalendarMessageHandlerMap,
isTrustedSender,
);
registerOutlookCalendarMessageHandlers(
MESSAGE_HANDLERS as CalendarMessageHandlerMap,
isTrustedSender,
);
initCalendarBackground();
browser.runtime.onMessage.addListener(
(
request: BackgroundRequest,
sender: chrome.runtime.MessageSender,
sendResponse: MessageSender,
) => {
const handler = MESSAGE_HANDLERS[request.type as string];
if (!handler) return false;
if (handler(request, sendResponse, sender) === true) return true;
sendResponse();
return false;
},
);
function getDefaultValues(): SettingsState {
return getDefaultSettingsState();
}
function SetStorageValue(object: SettingsState) {
void withSuppressedCloudAutoUpload(() =>
browser.storage.local.set(object as Record<string, unknown>),
);
const DefaultValues: SettingsState = {
onoff: true,
animatedbk: true,
bksliderinput: "50",
transparencyEffects: false,
lessonalert: true,
notificationcollector: true,
defaultmenuorder: [],
menuitems: {
assessments: { toggle: true },
courses: { toggle: true },
dashboard: { toggle: true },
documents: { toggle: true },
forums: { toggle: true },
goals: { toggle: true },
home: { toggle: true },
messages: { toggle: true },
myed: { toggle: true },
news: { toggle: true },
notices: { toggle: true },
portals: { toggle: true },
reports: { toggle: true },
settings: { toggle: true },
timetable: { toggle: true },
welcome: { toggle: true },
},
menuorder: [],
subjectfilters: {},
selectedTheme: '',
selectedColor: 'linear-gradient(40deg, rgba(201,61,0,1) 0%, RGBA(170, 5, 58, 1) 100%)',
originalSelectedColor: '',
DarkMode: true,
animations: true,
assessmentsAverage: true,
defaultPage: 'home',
shortcuts: [
{
name: 'YouTube',
enabled: false,
},
{
name: 'Outlook',
enabled: true,
},
{
name: 'Office',
enabled: true,
},
{
name: 'Spotify',
enabled: false,
},
{
name: 'Google',
enabled: true,
},
{
name: 'DuckDuckGo',
enabled: false,
},
{
name: 'Cool Math Games',
enabled: false,
},
{
name: 'SACE',
enabled: false,
},
{
name: 'Google Scholar',
enabled: false,
},
{
name: 'Gmail',
enabled: false,
},
{
name: 'Netflix',
enabled: false,
},
{
name: 'Education Perfect',
enabled: false,
},
],
customshortcuts: [],
};
function SetStorageValue(object: any) {
for (var i in object) {
browser.storage.local.set({ [i]: object[i] });
}
}
async function UpdateCurrentValues() {
try {
const items = await browser.storage.local.get();
const CurrentValues = items;
const NewValue = Object.assign({}, DefaultValues, CurrentValues);
function CheckInnerElement(element: any) {
for (let i in element) {
if (typeof element[i] === 'object') {
// @ts-expect-error
if (!Array.isArray(DefaultValues[i])) {
// @ts-expect-error
NewValue[i] = Object.assign({}, DefaultValues[i], CurrentValues[i]);
} else {
// @ts-expect-error
const length = DefaultValues[i].length;
// @ts-expect-error
NewValue[i] = Object.assign({}, DefaultValues[i], CurrentValues[i]);
let NewArray = [];
for (let j = 0; j < length; j++) {
NewArray.push(NewValue[i][j]);
}
NewValue[i] = NewArray;
}
}
}
}
CheckInnerElement(DefaultValues);
if (items['customshortcuts']) {
NewValue['customshortcuts'] = items['customshortcuts'];
}
SetStorageValue(NewValue);
console.log('[BetterSEQTA+] Values updated successfully');
} catch (error) {
console.error('[BetterSEQTA+] Error updating values:', error);
}
}
browser.runtime.onInstalled.addListener(function (event) {
browser.storage.local.remove(["justupdated", "data"]);
browser.storage.local.remove(['justupdated']);
browser.storage.local.remove(['data']);
const defaultsReady = ensureSyncableStorageDefaults();
if (event.reason == "install" || event.reason == "update") {
UpdateCurrentValues();
if ( event.reason == 'install', event.reason == 'update' ) {
browser.storage.local.set({ justupdated: true });
}
if (event.reason === "update" && event.previousVersion) {
void runStorageMigrations(event.previousVersion);
reloadSeqtaPages();
}
if (event.reason === "install") {
void browser.storage.local.set({ [DEFAULT_BACKGROUND_PENDING_KEY]: true });
void defaultsReady
.catch(() => undefined)
.then(async () => {
const key = "plugin.animated-background.settings";
const { [key]: settings } = await browser.storage.local.get(key);
await browser.storage.local.set({ [key]: { ...(settings as object), enabled: false } });
});
}
});
browser.runtime.onStartup.addListener(() => {
void ensureSyncableStorageDefaults();
});
initCloudSettingsAutoSync({ reloadSeqtaPages });
initTimetableClassmatesBackgroundSync();
void ensureSyncableStorageDefaults();
-571
View File
@@ -1,571 +0,0 @@
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,
getSyncAssessmentDueDates,
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 "@/lib/browser";
import { isSeqtaTab } from "@/seqta/utils/seqtaTabMatch";
const WEEKLY_PERIOD_MINUTES = 7 * 24 * 60;
export type CalendarMessageHandler = (
request: unknown,
sendResponse: (response?: unknown) => void,
sender?: chrome.runtime.MessageSender,
) => boolean | void;
export type CalendarMessageHandlerMap = Record<string, CalendarMessageHandler>;
type StoredTokens = {
accessToken?: string;
refreshToken?: string;
expiresAt?: number;
lastSyncAt?: number;
lastSyncOrigin?: string;
calendarId?: 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: chrome.tabs.OnUpdatedInfo,
tab: chrome.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?: chrome.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, syncAssessmentDueDates] = await Promise.all(
[
readGoogleCalendarState(),
readSharedCalendarSyncSettings(),
getSyncWeeksAhead(),
getAutoSyncWeekly(),
getSyncAssessmentDueDates(),
],
);
return {
configured: isGoogleCalendarConfigured(),
connected: !!(state.refreshToken || state.accessToken),
lastSyncAt: state.lastSyncAt,
lastWeeklySyncAt: shared.lastWeeklySyncAt,
lastSyncOrigin: state.lastSyncOrigin,
syncWeeksAhead,
autoSyncWeekly,
syncAssessmentDueDates,
};
}
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?: chrome.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?: chrome.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;
syncAssessmentDueDates?: boolean;
};
const patch: Record<string, unknown> = {};
if (body.syncWeeksAhead != null) patch.syncWeeksAhead = clampSyncWeeks(body.syncWeeksAhead);
if (body.autoSyncWeekly != null) patch.autoSyncWeekly = !!body.autoSyncWeekly;
if (body.syncAssessmentDueDates != null) {
patch.syncAssessmentDueDates = !!body.syncAssessmentDueDates;
}
if (Object.keys(patch).length > 0) await writeSharedCalendarSyncSettings(patch);
await ensureWeeklySyncAlarm();
return { success: true, ...(await getGoogleCalendarStatus()) };
},
(err) => ({
success: false,
error: err instanceof Error ? err.message : "Could not update sync settings",
}),
);
}
export function registerOutlookCalendarMessageHandlers(
handlers: CalendarMessageHandlerMap,
isTrustedSender: (sender?: chrome.runtime.MessageSender) => boolean,
): void {
registerProviderHandlers(handlers, isTrustedSender, OUTLOOK_BACKEND, getOutlookCalendarStatus);
}
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();
}
-497
View File
@@ -1,497 +0,0 @@
import browser from "@/lib/browser";
import {
ensureSyncableStorageDefaults,
getSyncableStorageDefaults,
} from "@/seqta/utils/ensureSyncableStorageDefaults";
import {
applyDownloadedEnvelope,
BSPLUS_CLOUD_KNOWN_REMOTE_UPDATED_AT_KEY,
BSPLUS_PENDING_THEME_ENSURE_AFTER_CLOUD_KEY,
buildUploadPatch,
CLOUD_SETTINGS_SYNC_SCHEMA_VERSION,
isKeyIncludedInCloudUploadPayload,
normalizeStorageForSync,
resolveThemeIdForPostSyncDownload,
saveLastUploadedSnapshot,
getLastUploadedSnapshot,
setKnownRemoteUpdatedAt,
} from "@/seqta/utils/cloudSettingsSync";
import { readRemoteStatus } from "@/seqta/utils/remoteStatus";
async function isCloudSyncDisabled(): Promise<boolean> {
return (await readRemoteStatus()).disabledFeatures.includes("cloud.sync");
}
const ACCOUNTS_BASE = "https://accounts.betterseqta.org";
export const CLOUD_SUMMARY_URL = `${ACCOUNTS_BASE}/api/user/cloud-summary`;
const CLOUD_SETTINGS_SYNC_URL = `${ACCOUNTS_BASE}/api/bsplus/settings/sync`;
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;
bsplus?: { updated_at: string; schemaVersion: number } | null;
};
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;
}
type CloudJsonBody = {
access_token?: string;
refresh_token?: string;
user?: unknown;
error?: string;
updated_at?: string;
};
function asCloudJsonBody(data: unknown): CloudJsonBody {
return data && typeof data === "object" ? (data as CloudJsonBody) : {};
}
async function parseJsonResponse(r: Response): Promise<unknown> {
const text = await r.text();
try {
return text ? JSON.parse(text) : {};
} catch {
return {};
}
}
async function getAccessToken(): 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;
}
async function tryRefreshTokens(): Promise<boolean> {
const result = await browser.storage.local.get([
"bsplus_refresh_token",
"bsplus_client_id",
"bsplus_user",
]);
const refresh_token = result.bsplus_refresh_token as string | undefined;
const client_id = result.bsplus_client_id as string | undefined;
if (!refresh_token || !client_id) return false;
try {
const r = await fetchWithTimeout(REFRESH_URL, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ refresh_token, client_id }),
});
const data = asCloudJsonBody(await parseJsonResponse(r));
if (!r.ok || !data.access_token || !data.refresh_token) return false;
await browser.storage.local.set({
bsplus_token: data.access_token,
bsplus_refresh_token: data.refresh_token,
bsplus_user: data.user ?? result.bsplus_user,
});
return true;
} catch {
return false;
}
}
function isServerTimestampNewer(serverIso: string, localIso: string | undefined): boolean {
const a = Date.parse(serverIso);
if (Number.isNaN(a)) return false;
if (localIso === undefined || localIso === "") return true;
const b = Date.parse(localIso);
if (Number.isNaN(b)) return true;
return a > b;
}
async function fetchCloudSummaryOnce(
token: string,
): Promise<
{ ok: true; data: CloudSummaryResponse } | { ok: false; unauthorized: boolean; error?: string }
> {
try {
const r = await fetchWithTimeout(CLOUD_SUMMARY_URL, {
headers: { Authorization: `Bearer ${token}` },
cache: "no-store",
});
const data = (await parseJsonResponse(r)) as CloudSummaryResponse;
if (r.status === 401) return { ok: false, unauthorized: true };
if (!r.ok) {
return {
ok: false,
unauthorized: false,
error: (data as { error?: string })?.error ?? `Summary failed (${r.status})`,
};
}
return { ok: true, data };
} catch (e) {
return {
ok: false,
unauthorized: false,
error: e instanceof Error ? e.message : "Network error",
};
}
}
async function fetchCloudSummaryWithAuthRetry(token: string): Promise<CloudSummaryResponse | null> {
let t = token;
for (let attempt = 0; attempt < 2; attempt++) {
const res = await fetchCloudSummaryOnce(t);
if (res.ok) return res.data;
if (res.unauthorized && attempt === 0) {
const refreshed = await tryRefreshTokens();
if (!refreshed) break;
const next = await getAccessToken();
if (!next) break;
t = next;
continue;
}
if (res.error) console.warn("[BS+ cloud sync] cloud-summary:", res.error);
break;
}
return null;
}
type PutResult =
| { ok: true; updated_at?: string; skipped?: boolean }
| { ok: false; unauthorized: boolean; error?: string };
async function resolveUploadBaseline(
normalized: Record<string, unknown>,
watermark: string | undefined,
): Promise<Record<string, unknown>> {
const lastSnapshot = await getLastUploadedSnapshot();
if (lastSnapshot) return lastSnapshot;
if (watermark) {
await saveLastUploadedSnapshot(normalized);
return normalized;
}
return getSyncableStorageDefaults();
}
async function putSettingsOnce(token: string): Promise<PutResult> {
try {
await ensureSyncableStorageDefaults();
const all = (await browser.storage.local.get()) as Record<string, unknown>;
const normalized = normalizeStorageForSync(all);
const watermark = all[BSPLUS_CLOUD_KNOWN_REMOTE_UPDATED_AT_KEY] as string | undefined;
const baseline = await resolveUploadBaseline(normalized, watermark);
const payload = buildUploadPatch(all, baseline);
if (!payload) {
return { ok: true, skipped: true };
}
const r = await fetchWithTimeout(CLOUD_SETTINGS_SYNC_URL, {
method: "PUT",
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
body: JSON.stringify(payload),
});
const data = asCloudJsonBody(await parseJsonResponse(r));
if (r.status === 401) return { ok: false, unauthorized: true };
if (!r.ok) {
return {
ok: false,
unauthorized: false,
error: data.error ?? `Upload failed (${r.status})`,
};
}
const updated_at = data.updated_at;
await saveLastUploadedSnapshot(normalized);
await setKnownRemoteUpdatedAt(updated_at);
return { ok: true, updated_at };
} catch (e) {
return {
ok: false,
unauthorized: false,
error: e instanceof Error ? e.message : "Upload failed",
};
}
}
export async function performCloudSettingsUploadWithRetry(
token: string,
): Promise<{ success: boolean; error?: string; updated_at?: string; skipped?: boolean }> {
if (await isCloudSyncDisabled()) {
return { success: false, error: "Cloud sync is temporarily disabled", skipped: true };
}
let t = token;
for (let attempt = 0; attempt < 2; attempt++) {
const res = await putSettingsOnce(t);
if (res.ok) {
return { success: true, updated_at: res.updated_at, skipped: res.skipped };
}
if (res.unauthorized && attempt === 0) {
const refreshed = await tryRefreshTokens();
if (!refreshed) return { success: false, error: "Not authenticated" };
const next = await getAccessToken();
if (!next) return { success: false, error: "Not authenticated" };
t = next;
continue;
}
return { success: false, error: res.error ?? "Upload failed" };
}
return { success: false, error: "Upload failed" };
}
type GetResult =
| { ok: true; updated_at?: string }
| { ok: false; notFound?: boolean; unauthorized: boolean; error?: string };
async function getSettingsAndApplyOnce(token: string): Promise<GetResult> {
try {
const r = await fetchWithTimeout(CLOUD_SETTINGS_SYNC_URL, {
method: "GET",
headers: { Authorization: `Bearer ${token}` },
cache: "no-store",
});
const data = asCloudJsonBody(await parseJsonResponse(r));
if (r.status === 401) return { ok: false, unauthorized: true };
if (r.status === 404) {
return {
ok: false,
notFound: true,
unauthorized: false,
error: "No settings backup found in the cloud",
};
}
if (!r.ok) {
return {
ok: false,
unauthorized: false,
error: data.error ?? `Download failed (${r.status})`,
};
}
const themeIdToEnsure = resolveThemeIdForPostSyncDownload(data);
await applyDownloadedEnvelope(data);
if (themeIdToEnsure) {
await browser.storage.local.set({
[BSPLUS_PENDING_THEME_ENSURE_AFTER_CLOUD_KEY]: themeIdToEnsure,
});
} else {
await browser.storage.local.remove(BSPLUS_PENDING_THEME_ENSURE_AFTER_CLOUD_KEY);
}
reloadSeqtaPagesFn?.();
const updated_at = data?.updated_at as string | undefined;
await setKnownRemoteUpdatedAt(updated_at);
await saveLastUploadedSnapshot(
normalizeStorageForSync((await browser.storage.local.get()) as Record<string, unknown>),
);
return { ok: true, updated_at };
} catch (e) {
return {
ok: false,
unauthorized: false,
error: e instanceof Error ? e.message : "Download failed",
};
}
}
export async function performCloudSettingsDownloadWithRetry(
token: string,
): Promise<{ success: boolean; notFound?: boolean; error?: string; updated_at?: string }> {
suppressAutoUploadDuringRestore = true;
try {
let t = token;
for (let attempt = 0; attempt < 2; attempt++) {
const res = await getSettingsAndApplyOnce(t);
if (res.ok) return { success: true, updated_at: res.updated_at };
if (res.unauthorized && attempt === 0) {
const refreshed = await tryRefreshTokens();
if (!refreshed) return { success: false, error: "Not authenticated" };
const next = await getAccessToken();
if (!next) return { success: false, error: "Not authenticated" };
t = next;
continue;
}
return {
success: false,
notFound: res.notFound,
error: res.error ?? "Download failed",
};
}
return { success: false, error: "Download failed" };
} finally {
suppressAutoUploadDuringRestore = false;
}
}
async function maybeUploadBaseline(token: string): Promise<void> {
const res = await performCloudSettingsUploadWithRetry(token);
if (!res.success) {
console.warn("[BS+ cloud sync] Baseline upload failed:", res.error);
}
}
async function downloadIfNeeded(token: string): Promise<void> {
const res = await performCloudSettingsDownloadWithRetry(token);
if (!res.success && !res.notFound) {
console.warn("[BS+ cloud sync] Auto-download failed:", res.error);
}
}
async function runCloudSettingsPollInner(): Promise<void> {
if (await isCloudSyncDisabled()) return;
const all = (await browser.storage.local.get()) as Record<string, unknown>;
if (!isAutoCloudSyncEnabled(all)) return;
let token = await getAccessToken();
if (!token) return;
const summary = await fetchCloudSummaryWithAuthRetry(token);
if (!summary) return;
const bsplus = summary.bsplus;
const watermark = all[BSPLUS_CLOUD_KNOWN_REMOTE_UPDATED_AT_KEY] as string | undefined;
if (
bsplus &&
typeof bsplus.schemaVersion === "number" &&
bsplus.schemaVersion > CLOUD_SETTINGS_SYNC_SCHEMA_VERSION
) {
console.warn("[BS+ cloud sync] Server schemaVersion newer than client; skip auto-download");
return;
}
token = (await getAccessToken()) ?? token;
if (!watermark) {
if (!bsplus?.updated_at) {
await maybeUploadBaseline(token);
return;
}
await downloadIfNeeded(token);
return;
}
if (!bsplus?.updated_at) return;
if (isServerTimestampNewer(bsplus.updated_at, watermark)) {
await downloadIfNeeded(token);
}
}
export function runCloudSettingsPoll(): Promise<void> {
if (pollInFlight) return pollInFlight;
pollInFlight = (async () => {
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 runCloudSettingsPollInner();
await browser.storage.local.set({ [POLL_THROTTLE_KEY]: Date.now() });
} catch (e) {
console.error("[BS+ cloud sync] Poll error:", e);
} finally {
pollInFlight = null;
}
})();
return pollInFlight;
}
function clearUploadDebounce(): void {
if (debounceTimer) {
clearTimeout(debounceTimer);
debounceTimer = null;
}
}
function scheduleDebouncedUpload(): void {
if (suppressAutoUploadDuringRestore) return;
clearUploadDebounce();
debounceTimer = setTimeout(() => {
debounceTimer = null;
void runDebouncedUploadJob();
}, UPLOAD_DEBOUNCE_MS);
}
/** Call after store theme install (and similar) so cloud upload runs even if storage events are flaky. */
export function requestCloudSettingsDebouncedUpload(): void {
void (async () => {
if (await isCloudSyncDisabled()) return;
const all = (await browser.storage.local.get()) as Record<string, unknown>;
if (!isAutoCloudSyncEnabled(all)) return;
if (suppressAutoUploadDuringRestore) return;
if (!(await getAccessToken())) return;
scheduleDebouncedUpload();
})();
}
async function runDebouncedUploadJob(): Promise<void> {
if (await isCloudSyncDisabled()) return;
const all = (await browser.storage.local.get()) as Record<string, unknown>;
if (!isAutoCloudSyncEnabled(all)) return;
const token = await getAccessToken();
if (!token) return;
const res = await performCloudSettingsUploadWithRetry(token);
if (!res.success) {
console.warn("[BS+ cloud sync] Auto-upload failed:", res.error);
}
}
async function syncAutoUploadWithStorage(): Promise<void> {
const all = (await browser.storage.local.get()) as Record<string, unknown>;
if (!isAutoCloudSyncEnabled(all)) {
clearUploadDebounce();
}
}
function onStorageChanged(
changes: Record<string, chrome.storage.StorageChange>,
area: string,
): void {
if (area !== "local") return;
if (Object.hasOwn(changes, "autoCloudSettingsSync")) {
void syncAutoUploadWithStorage();
}
const keys = Object.keys(changes);
if (!keys.some((k) => isKeyIncludedInCloudUploadPayload(k))) return;
void (async () => {
if (await isCloudSyncDisabled()) return;
const all = (await browser.storage.local.get()) as Record<string, unknown>;
if (!isAutoCloudSyncEnabled(all)) return;
if (suppressAutoUploadDuringRestore) return;
if (!(await getAccessToken())) return;
scheduleDebouncedUpload();
})();
}
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();
}
-347
View File
@@ -1,347 +0,0 @@
import { normalizeCustomThemeApiResponse } from "@/seqta/utils/customThemes/parseApiEnvelope";
import { base64ToBlob } from "@/seqta/utils/base64";
type MessageSender = { (response?: unknown): void };
type UploadFilePart = {
fieldName: string;
filename: string;
mimeType: string;
dataBase64: string;
};
type UploadPayload = {
themeZip?: UploadFilePart;
looseFiles?: UploadFilePart[];
submissionNotes?: string;
};
function buildFormDataFromPayload(payload: UploadPayload): FormData {
const form = new FormData();
if (payload.themeZip) {
const part = payload.themeZip;
form.append(part.fieldName, base64ToBlob(part.dataBase64, part.mimeType), part.filename);
}
for (const part of payload.looseFiles ?? []) {
form.append(part.fieldName, base64ToBlob(part.dataBase64, part.mimeType), part.filename);
}
if (payload.submissionNotes?.trim()) {
form.append("submission_notes", payload.submissionNotes.trim());
}
return form;
}
export function createCustomThemesHandlers(deps: {
apiBase: () => string;
getAccessTokenFromStorage: () => Promise<string | null>;
}): Record<string, (request: Record<string, unknown>, sendResponse: MessageSender) => boolean> {
async function readCustomThemesResponse(r: Response): Promise<Record<string, unknown>> {
const text = await r.text();
let body: unknown;
try {
body = text ? JSON.parse(text) : {};
} catch {
body = null;
}
const normalized = normalizeCustomThemeApiResponse(body, r.status, text);
if (!r.ok || normalized.success === false) {
console.error("[BetterSEQTA+ CustomThemes]", r.status, r.url, normalized);
}
return normalized;
}
async function customThemesJsonFetch(
path: string,
init: RequestInit = {},
requireAuth = false,
): Promise<Record<string, unknown>> {
const headers: Record<string, string> = {
Accept: "application/json",
...(init.headers as Record<string, string> | undefined),
};
if (requireAuth) {
const token = await deps.getAccessTokenFromStorage();
if (!token) {
return { success: false, error: "Not authenticated", httpStatus: 401 };
}
headers.Authorization = `Bearer ${token}`;
}
const url = `${deps.apiBase()}${path}`;
const r = await fetch(url, {
...init,
headers,
cache: "no-store",
});
return await readCustomThemesResponse(r);
}
async function customThemesMultipartPost(
path: string,
payload: UploadPayload,
): Promise<Record<string, unknown>> {
const token = await deps.getAccessTokenFromStorage();
if (!token) {
return { success: false, error: "Not authenticated", httpStatus: 401 };
}
const form = buildFormDataFromPayload(payload);
const url = `${deps.apiBase()}${path}`;
const r = await fetch(url, {
method: "POST",
headers: { Authorization: `Bearer ${token}` },
body: form,
cache: "no-store",
});
return await readCustomThemesResponse(r);
}
function handleFetchCustomThemes(
request: Record<string, unknown>,
sendResponse: MessageSender,
): boolean {
void (async () => {
try {
const params = new URLSearchParams();
params.set("type", "betterseqta");
params.set("page", String(request.page ?? 1));
params.set("limit", String(request.limit ?? 20));
if (request.sort) params.set("sort", String(request.sort));
const searchRaw = request.search;
const search = typeof searchRaw === "string" ? searchRaw.trim() : "";
const path = search
? `/api/custom-themes/search?${params}&q=${encodeURIComponent(search)}`
: `/api/custom-themes?${params}`;
sendResponse(await customThemesJsonFetch(path));
} catch (err) {
console.error("[Background] fetchCustomThemes error:", err);
sendResponse({
success: false,
error: err instanceof Error ? err.message : "Fetch failed",
});
}
})();
return true;
}
function handleFetchMyCustomThemes(
request: Record<string, unknown>,
sendResponse: MessageSender,
): boolean {
void (async () => {
try {
const params = new URLSearchParams();
params.set("page", String(request.page ?? 1));
params.set("limit", String(request.limit ?? 20));
params.set("type", "betterseqta");
if (request.status) params.set("status", String(request.status));
sendResponse(await customThemesJsonFetch(`/api/custom-themes/mine?${params}`, {}, true));
} catch (err) {
console.error("[Background] fetchMyCustomThemes error:", err);
sendResponse({
success: false,
error: err instanceof Error ? err.message : "Fetch failed",
});
}
})();
return true;
}
function handleFetchMyCustomThemeDetail(
request: Record<string, unknown>,
sendResponse: MessageSender,
): boolean {
const { themeId } = request;
if (!themeId || typeof themeId !== "string") {
sendResponse({ success: false, error: "Missing themeId" });
return false;
}
void (async () => {
try {
sendResponse(
await customThemesJsonFetch(
`/api/custom-themes/mine/${encodeURIComponent(themeId)}`,
{},
true,
),
);
} catch (err) {
console.error("[Background] fetchMyCustomThemeDetail error:", err);
sendResponse({
success: false,
error: err instanceof Error ? err.message : "Fetch failed",
});
}
})();
return true;
}
function handleSubmitCustomTheme(
request: Record<string, unknown>,
sendResponse: MessageSender,
): boolean {
const payload = request.payload as UploadPayload | undefined;
if (!payload?.themeZip && (!payload?.looseFiles || payload.looseFiles.length === 0)) {
sendResponse({ success: false, error: "Missing upload files" });
return false;
}
void (async () => {
try {
sendResponse(await customThemesMultipartPost("/api/custom-themes/mine", payload!));
} catch (err) {
console.error("[Background] submitCustomTheme error:", err);
sendResponse({
success: false,
error: { message: err instanceof Error ? err.message : "Upload failed" },
httpStatus: 0,
});
}
})();
return true;
}
function handleReplaceCustomThemeFiles(
request: Record<string, unknown>,
sendResponse: MessageSender,
): boolean {
const { themeId, payload: payloadRaw } = request;
if (!themeId || typeof themeId !== "string") {
sendResponse({ success: false, error: "Missing themeId" });
return false;
}
const payload =
payloadRaw && typeof payloadRaw === "object" ? (payloadRaw as UploadPayload) : undefined;
if (!payload?.themeZip && (!payload?.looseFiles || payload.looseFiles.length === 0)) {
sendResponse({ success: false, error: "Missing upload files" });
return false;
}
void (async () => {
try {
sendResponse(
await customThemesMultipartPost(
`/api/custom-themes/mine/${encodeURIComponent(themeId)}/files`,
payload as UploadPayload,
),
);
} catch (err) {
console.error("[Background] replaceCustomThemeFiles error:", err);
sendResponse({
success: false,
error: err instanceof Error ? err.message : "Upload failed",
});
}
})();
return true;
}
function handleUpdateCustomThemeMetadata(
request: Record<string, unknown>,
sendResponse: MessageSender,
): boolean {
const { themeId, body } = request;
if (!themeId || typeof themeId !== "string") {
sendResponse({ success: false, error: "Missing themeId" });
return false;
}
void (async () => {
try {
sendResponse(
await customThemesJsonFetch(
`/api/custom-themes/mine/${encodeURIComponent(themeId)}`,
{
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body ?? {}),
},
true,
),
);
} catch (err) {
console.error("[Background] updateCustomThemeMetadata error:", err);
sendResponse({
success: false,
error: err instanceof Error ? err.message : "Update failed",
});
}
})();
return true;
}
function handleDeleteCustomTheme(
request: Record<string, unknown>,
sendResponse: MessageSender,
): boolean {
const { themeId } = request;
if (!themeId || typeof themeId !== "string") {
sendResponse({ success: false, error: "Missing themeId" });
return false;
}
void (async () => {
try {
sendResponse(
await customThemesJsonFetch(
`/api/custom-themes/mine/${encodeURIComponent(themeId)}`,
{ method: "DELETE" },
true,
),
);
} catch (err) {
console.error("[Background] deleteCustomTheme error:", err);
sendResponse({
success: false,
error: err instanceof Error ? err.message : "Delete failed",
});
}
})();
return true;
}
function handleFetchBsplusAdminMe(_request: unknown, sendResponse: MessageSender): boolean {
void (async () => {
try {
sendResponse(await customThemesJsonFetch("/api/bsplus/admin/me", {}, true));
} catch (err) {
sendResponse({
success: false,
error: err instanceof Error ? err.message : "Fetch failed",
});
}
})();
return true;
}
function handleFetchBsplusAdminThemes(
request: Record<string, unknown>,
sendResponse: MessageSender,
): boolean {
void (async () => {
try {
const params = new URLSearchParams();
params.set("page", String(request.page ?? 1));
params.set("limit", String(Math.min(Number(request.limit ?? 20) || 20, 100)));
if (request.status) params.set("status", String(request.status));
if (request.source) params.set("source", String(request.source));
const searchRaw = request.search;
const search = typeof searchRaw === "string" ? searchRaw.trim() : "";
if (search) params.set("search", search);
sendResponse(await customThemesJsonFetch(`/api/bsplus/admin/themes?${params}`, {}, true));
} catch (err) {
sendResponse({
success: false,
error: err instanceof Error ? err.message : "Fetch failed",
});
}
})();
return true;
}
return {
fetchCustomThemes: handleFetchCustomThemes,
fetchMyCustomThemes: handleFetchMyCustomThemes,
fetchMyCustomThemeDetail: handleFetchMyCustomThemeDetail,
submitCustomTheme: handleSubmitCustomTheme,
replaceCustomThemeFiles: handleReplaceCustomThemeFiles,
updateCustomThemeMetadata: handleUpdateCustomThemeMetadata,
deleteCustomTheme: handleDeleteCustomTheme,
fetchBsplusAdminMe: handleFetchBsplusAdminMe,
fetchBsplusAdminThemes: handleFetchBsplusAdminThemes,
};
}
-86
View File
@@ -1,86 +0,0 @@
import type { NewsFeed, NewsPayload } from "@/seqta/utils/newsFeed";
const NEWS_API_KEY = "17c0da766ba347c89d094449504e3080";
const MAX_RATE_LIMIT_RETRIES = 3;
const REQUEST_TIMEOUT_MS = 10_000;
const DAY_MS = 86_400_000;
const rssFeedsByCountry: Record<string, string[]> = {
usa: [
"https://rss.nytimes.com/services/xml/rss/nyt/HomePage.xml",
"https://feeds.npr.org/1001/rss.xml",
],
taiwan: ["https://news.ltn.com.tw/rss/all.xml", "https://www.taipeitimes.com/xml/index.rss"],
hong_kong: [
"https://rthk9.rthk.hk/rthk/news/rss/e_expressnews_elocal.xml",
"https://www.scmp.com/rss/91/feed",
],
panama: [
"https://critica.com.pa/rss.xml",
"https://www.panamaamerica.com.pa/rss.xml",
"https://noticiassin.com/feed/",
],
canada: [
"https://www.cbc.ca/cmlink/rss-topstories",
"https://calgaryherald.com/feed",
"https://ottawacitizen.com/feed",
],
singapore: [
"https://www.straitstimes.com/news/singapore/rss.xml",
"https://www.channelnewsasia.com/rssfeeds/8395986",
],
uk: ["https://feeds.bbci.co.uk/news/rss.xml", "https://www.theguardian.com/uk/rss"],
japan: [
"https://www3.nhk.or.jp/rss/news/cat0.xml",
"https://news.livedoor.com/topics/rss/int.xml",
],
netherlands: ["https://www.dutchnews.nl/feed/", "https://www.nrc.nl/rss/"],
};
async function fetchAustraliaNews(): Promise<NewsPayload> {
const from = new Date(Date.now() - 5 * DAY_MS).toISOString().slice(0, 10);
let url = `https://newsapi.org/v2/everything?domains=abc.net.au&from=${from}&apiKey=${NEWS_API_KEY}`;
try {
for (let attempt = 0; attempt <= MAX_RATE_LIMIT_RETRIES; attempt++) {
const response = await fetch(url, { signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) });
const data = await response.json();
if (data.code !== "rateLimited") return { articles: data.articles ?? [] };
url += "%00";
}
} catch (error) {
console.error("[BetterSEQTA+] Failed to fetch Australia news", error);
}
return { articles: [] };
}
async function fetchFeed(url: string): Promise<NewsFeed> {
const response = await fetch(url, { signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) });
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return { url: response.url || url, xml: await response.text() };
}
function feedsForSource(source: string): string[] | null {
const preset = rssFeedsByCountry[source.toLowerCase()];
if (preset) return preset;
return /^https?:\/\//i.test(source) ? [source] : null;
}
export async function fetchNews(source?: string): Promise<NewsPayload> {
const normalizedSource = source?.trim() || "australia";
if (normalizedSource === "australia") return fetchAustraliaNews();
const feedUrls = feedsForSource(normalizedSource);
if (!feedUrls) {
console.warn("[BetterSEQTA+] Invalid news source, falling back to Australia", normalizedSource);
return fetchAustraliaNews();
}
const results = await Promise.allSettled(feedUrls.map(fetchFeed));
const feeds = results.flatMap((result, i) => {
if (result.status === "fulfilled") return [result.value];
console.error("[BetterSEQTA+] Failed to fetch RSS feed:", feedUrls[i], result.reason);
return [];
});
return { feeds };
}
-62
View File
@@ -1,62 +0,0 @@
type MessageSender = { (response?: unknown): void };
type StockPhotoResult = { title: string; thumbUrl: string; imageUrl: string };
export function handleSearchThemeStockPhotos(
request: { query?: string; limit?: number },
sendResponse: MessageSender,
): boolean {
const query = request.query?.trim();
if (!query) {
sendResponse({ success: false, error: "Missing query" });
return false;
}
const limit = Math.min(Math.max(request.limit ?? 8, 1), 12);
void (async () => {
try {
const params = new URLSearchParams({
action: "query",
origin: "*",
format: "json",
generator: "search",
gsrsearch: query,
gsrnamespace: "6",
gsrlimit: String(limit),
prop: "imageinfo",
iiprop: "url",
iiurlwidth: "1400",
});
const res = await fetch(`https://commons.wikimedia.org/w/api.php?${params}`);
const json = (await res.json()) as {
query?: {
pages?: Record<
string,
{ title?: string; imageinfo?: { thumburl?: string; url?: string }[] }
>;
};
};
const pages = json.query?.pages ?? {};
const results: StockPhotoResult[] = Object.values(pages)
.map((page) => {
const info = page.imageinfo?.[0];
if (!info?.url) return null;
return {
title: page.title?.replace(/^File:/, "") ?? "Photo",
thumbUrl: info.thumburl ?? info.url,
imageUrl: info.url,
};
})
.filter((row): row is StockPhotoResult => row != null);
sendResponse({ success: true, results });
} catch (err) {
sendResponse({
success: false,
error: err instanceof Error ? err.message : "Search failed",
});
}
})();
return true;
}
-71
View File
@@ -1,71 +0,0 @@
import semver from "semver";
import browser from "@/lib/browser";
function crossedUpgrade(previousVersion: string, boundary: string): boolean {
const prev = semver.coerce(previousVersion);
const curr = semver.coerce(browser.runtime.getManifest().version);
return prev != null && curr != null && !semver.lt(curr, boundary) && semver.lt(prev, boundary);
}
/** One-time storage patches when crossing 3.6.5 / 3.6.6 / 3.7.0 / 3.7.7 (see git history on main). */
export async function runStorageMigrations(previousVersion: string): Promise<void> {
if (crossedUpgrade(previousVersion, "3.6.5")) {
try {
const key = "plugin.global-search.settings";
const got = await browser.storage.local.get(key);
const existing = (got[key] ?? {}) as Record<string, unknown>;
await browser.storage.local.set({
[key]: {
...existing,
enabled: true,
transparencyEffects: true,
runIndexingOnLoad: true,
passiveIndexing: true,
},
});
} catch (e) {
console.warn("[BetterSEQTA+] Global Search 3.6.5 settings migration failed:", e);
}
}
if (crossedUpgrade(previousVersion, "3.6.6")) {
try {
await browser.storage.local.set({ themeOfTheMonthDisabled: false });
await browser.storage.local.remove("themeOfTheMonthLastSeenId");
} catch (e) {
console.warn("[BetterSEQTA+] Theme of the Month 3.6.6 reset migration failed:", e);
}
}
if (crossedUpgrade(previousVersion, "3.7.0")) {
try {
await browser.storage.local.remove([
"themeOfTheMonthLastSeenId",
"themeOfTheMonthDismissedMonth",
]);
} catch (e) {
console.warn("[BetterSEQTA+] Theme of the Month 3.7.0 dismissal migration failed:", e);
}
}
if (crossedUpgrade(previousVersion, "3.7.7")) {
try {
await browser.storage.local.remove([
"bsplus_remote_config_snapshot",
"bsplus_remote_config_etag",
"bsplus_remote_config_fetched_at",
"bsplus_remote_config_last_hostname",
"bsplus_remote_last_primary_ok",
"bsplus_campaign_seen",
"bsplus_local_override_onoff",
"bsplus_features_hidden_until_version",
"bsplus_install_registered_at",
"bsplus_remote_theme_before_v1",
"bsplus_remote_theme_state_v1",
"bsplus_remote_theme_user_off",
]);
} catch (e) {
console.warn("[BetterSEQTA+] 3.7.7 storage cleanup migration failed:", e);
}
}
}
-36
View File
@@ -1,36 +0,0 @@
import browser from "@/lib/browser";
import { hasAnySyncOptInScope } from "@/plugins/built-in/timetableClassmates/syncScopes";
import { isSeqtaTab } from "@/seqta/utils/seqtaTabMatch";
const ALARM_NAME = "timetable-classmates-sync";
const ALARM_PERIOD_MINUTES = 8 * 60;
let initialized = false;
async function pingSeqtaTabs(): Promise<void> {
const tabs = await browser.tabs.query({});
for (const tab of tabs) {
if (!isSeqtaTab(tab) || tab.id == null) continue;
try {
await browser.tabs.sendMessage(tab.id, { type: "timetableClassmatesSync" });
} catch {
/* content script not ready */
}
}
}
async function pingIfOptedIn(): Promise<void> {
if (!(await hasAnySyncOptInScope())) return;
await pingSeqtaTabs();
}
export function initTimetableClassmatesBackgroundSync(): void {
if (initialized) return;
initialized = true;
void browser.alarms.create(ALARM_NAME, { periodInMinutes: ALARM_PERIOD_MINUTES });
browser.alarms.onAlarm.addListener((alarm) => {
if (alarm.name === ALARM_NAME) void pingIfOptedIn();
});
}
-43
View File
@@ -1,43 +0,0 @@
/** 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}`;
}
-34
View File
@@ -1,34 +0,0 @@
/** 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}`;
}
+3 -90
View File
@@ -15,45 +15,12 @@
* along with EvenBetterSEQTA. If not, see <https://www.gnu.org/licenses/>.
*/
@use "injected/popup.scss";
@font-face {
font-family: "Roboto";
src: url("https://fonts.gstatic.com/s/roboto/v50/KFO7CnqEu92Fr1ME7kSn66aGLdTylUAMa3yUBA.woff2")
format("woff2");
font-weight: 700;
font-style: normal;
font-display: swap;
}
@font-face {
font-family: "IconFamily";
src: url("@/resources/fonts/IconFamily.woff") format("woff");
font-weight: normal;
font-style: normal;
font-display: block;
}
@layer base, override;
@layer override {
.legacy-root,
.legacy-root *:not(.iconFamily) {
font-family: var(--betterseqta-font-family, Rubik), sans-serif !important;
}
.iconFamily,
.iconFamily *,
[class~="iconFamily"],
[class~="iconFamily"] * {
font-family: "IconFamily" !important;
}
}
@use 'injected/popup.scss';
html {
background: #161616 !important;
background-color: #161616;
font-family: Roboto, system-ui, -apple-system, sans-serif !important;
font-family: Rubik, Roboto !important;
}
.tooltip svg {
@@ -124,58 +91,4 @@ body:has(.outside-container:not(.hide)) #AddedSettings.tooltip:hover > .tooltipt
top: 115% !important;
background: var(--text-primary) !important;
color: var(--theme-primary) !important;
}
.fixed-tooltip {
display: inline-block;
z-index: 5 !important;
width: 28px;
background: none;
box-shadow: none;
padding: 2px;
position: absolute;
}
.fixed-tooltip svg {
fill: var(--theme-primary);
}
.tooltiptext-fixed {
width: 120px;
transform: scale(0);
transition: transform 0.2s;
transform-origin: top;
background: var(--background-primary);
color: var(--text-primary);
text-align: center;
border-radius: 6px;
padding: 2px;
position: fixed;
z-index: 1000;
top: 0;
left: 0;
margin-left: -62px;
}
.tooltiptext-fixed::after {
content: "";
position: absolute;
bottom: 100%;
left: 50%;
margin-left: -5px;
border-width: 5px;
border-style: solid;
border-color: transparent transparent var(--text-primary) transparent;
}
.tooltiptext-fixed.show {
transform: scale(1);
transform-origin: top;
transition: transform 0.2s;
}
.tooltiptext-fixed p:hover {
cursor: pointer;
background: rgba(0, 0, 0, 0.3) !important;
transition: 200ms;
}
.tooltiptext-fixed p {
border-radius: 8px !important;
padding-top: 2px;
padding-bottom: 2px;
margin: 2px;
}
}
+1 -1
View File
@@ -1 +1 @@
import "./documentload.scss";
import './documentload.scss';
+3 -11
View File
@@ -15,7 +15,7 @@
* along with EvenBetterSEQTA. If not, see <https://www.gnu.org/licenses/>.
*/
body {
body {
background: transparent;
}
@@ -25,9 +25,7 @@ body {
span,
body {
color: white !important;
text-shadow:
1px 1px 2px #161616,
0 0 1em #161616;
text-shadow: 1px 1px 2px #161616, 0 0 1em #161616;
}
body {
@@ -113,10 +111,4 @@ body {
text-decoration: underline;
transition: text-shadow 0.5s;
}
}
.cke_panel_listItem > a {
&:hover {
background: #3d3d3e !important;
}
}
}
+609 -3407
View File
File diff suppressed because it is too large. Load diff
-51
View File
@@ -1,51 +0,0 @@
html.performanceMode {
--bs-settings-ease: 0.2s cubic-bezier(0.22, 1, 0.36, 1);
--bs-motion-duration: 0.2s;
--bs-motion-ease: cubic-bezier(0.22, 1, 0.36, 1);
backdrop-filter: none !important;
-webkit-backdrop-filter: none !important;
filter: none !important;
/* Inline page loaders only — boot overlay lives in #loading shadow DOM. */
.bkloading-inline .big-circle,
.bkloading-inline .small-circle,
.bkloading-inline .outer-circle {
animation: none !important;
}
/* Custom title: cheaper hit-testing during mouse moves (trace showed many HitTests). */
.bsplus-custom-title,
#title.bsplus-custom-title {
contain: layout style paint;
}
/* Settings backdrop — skip expensive blur in performance mode. */
#ExtensionPopup ~ *,
.outside-container.hide {
backdrop-filter: none !important;
}
}
html.performanceModeSimpleUi {
.bsplus-analytics-charts,
.bsplus-analytics-chart-cell {
display: none !important;
}
}
/* Boot loading spinner uses shadow DOM; custom properties inherit from the host. */
#loading.bkloading {
--bk-stage-duration: 0.85s !important;
--bk-spin-outer: 1s !important;
--bk-spin-inner: 3s !important;
--bk-spin-small: 3s !important;
}
html.performanceMode.transparencyEffects,
html.performanceMode .backdrop-blur-xl,
html.performanceMode .backdrop-blur-sm,
html.performanceMode [class*="backdrop-blur"] {
backdrop-filter: none !important;
-webkit-backdrop-filter: none !important;
}
+12 -26
View File
@@ -14,12 +14,11 @@
.outside-container {
margin: 0;
overflow: hidden;
position: fixed;
inset: 0;
width: 100%;
height: 100%;
/* Above Engage React chrome / MUI layers; below rare fullscreen media overlays */
z-index: 200000;
position: absolute;
right: 10px;
top: 80px;
height: 590px;
z-index: 20;
transition-duration: 100ms;
}
@@ -32,23 +31,10 @@
}
#ExtensionPopup {
border-radius: 0;
filter: none;
transform-origin: center center;
opacity: 0;
transition: opacity var(--bs-motion-duration, 0.2s) cubic-bezier(0.22, 1, 0.36, 1);
}
#ExtensionPopup.bsplus-settings-host--open {
opacity: 1;
}
#ExtensionPopup.bsplus-settings-host--closing {
opacity: 0;
pointer-events: none;
}
/* Feedback modal scrollport — host overflow:hidden otherwise clips fixed overlays. */
#ExtensionPopup.bsplus-feedback-open {
overflow: auto !important;
}
border-radius: 1rem;
filter: drop-shadow(0px 0px 20px rgba(0, 0, 0, 0.6));
transform-origin: 70% 0;
will-change: opacity, transform;
transform: translateZ(0); // promotes GPU rendering
transition: opacity 0.05s, transform 0.05s;
}
+22 -59
View File
@@ -1,68 +1,22 @@
#menu
ul:has(li.hasChildren:is(.active, .bsplus-active))
li.hasChildren:is(.active, .bsplus-active) {
#menu ul:has(li.hasChildren.active) li.hasChildren.active {
box-shadow: inset 0px 0 var(--item-colour, transparent) !important;
background: transparent !important;
}
#menu ul:not(:has(> li.hasChildren:is(.active, .bsplus-active))) {
#menu ul:not(:has(li.hasChildren.active)) {
overflow-y: scroll !important;
}
/* Move the complete row, including hover fill, arrow and subject stripe.
A transform on the folder itself would also move its absolute `.sub` panel.
Resting margins are measured before drilling so auto margins interpolate. */
#menu#menu ul.bsplus-drill-rows > :is(li, section) {
margin-left: var(--bsplus-row-margin-left) !important;
transition:
margin-left 0.3s ease,
background-color 0.2s ease,
box-shadow 0.2s ease !important;
animation: none !important;
> label,
> svg,
&::before,
&::after {
transform: none !important;
animation: none !important;
}
#menu > ul:has(li.hasChildren.active) > li::before,
#menu > ul ul:has(li.hasChildren.active) > li::before,
#menu > ul:has(li.hasChildren.active) > li > label,
#menu > ul:has(li.hasChildren.active) > li > svg,
#menu > ul ul:has(li.hasChildren.active) > li > label,
#menu > ul ul:has(li.hasChildren.active) > li > svg {
transform: translateX(-320px);
}
#menu#menu ul.bsplus-drill-rows:has(> .hasChildren:is(.active, .bsplus-active)) > :is(li, section) {
margin-left: calc(var(--bsplus-row-margin-left) + var(--bsplus-slide-off, -320px)) !important;
}
/* Incoming rows travel only with their native panel. */
#menu .sub > ul:not(.bsplus-drill-rows) > li {
&,
> label,
> svg,
&::before,
&::after {
animation: none !important;
transform: none !important;
}
}
#menu .sub {
transition:
transform 0.3s ease,
left 0.4s cubic-bezier(0.4, 0, 0.2, 1);
}
#menu
.sub
ul:has(> li.hasChildren:is(.active, .bsplus-active))
> li:not(:is(.active, .bsplus-active)) {
pointer-events: none !important;
}
#menu > ul:has(li.hasChildren:is(.active, .bsplus-active)) > li:is(.active, .bsplus-active) {
background: transparent !important;
}
#menu li.hasChildren:not(:is(.active, .bsplus-active)) li .sub {
#menu li.hasChildren:not(.active) li .sub {
display: none; // improves performance
}
@@ -71,10 +25,19 @@
padding-top: 2px;
}
.sub:has(ul > li.hasChildren:is(.active, .bsplus-active)) > .nav > .back {
.sub:has(ul>li.hasChildren.active) > .nav > .back {
display: none !important;
}
#menu {
--bsplus-slide-off: -320px;
#menu ul > li > label,
#menu ul > li > svg {
transition: transform 0.3s ease;
}
#menu .sub {
transition: transform 0.3s ease;
}
#menu > ul:has(li.hasChildren.active) > li.active {
background: transparent !important;
}
-263
View File
@@ -1,263 +0,0 @@
/* Native sidebar style presets + Look (density / radius / indicator). */
$sidebar-motion: 0.4s cubic-bezier(0.4, 0, 0.2, 1);
@mixin accent-bar($shadow: 0.55) {
content: "" !important;
position: absolute !important;
left: 0 !important;
top: 10px !important;
bottom: 10px !important;
width: 4px !important;
border-radius: 2px !important;
background: #fff !important;
box-shadow: 0 0 10px rgba(255, 255, 255, $shadow) !important;
pointer-events: none !important;
z-index: 3 !important;
opacity: 1 !important;
display: block !important;
}
#menu.bsplus-styled-sidebar {
$rootItem: "> ul > li.item";
$subItem: ".sub li.item";
$item: "#{$rootItem}, #{$subItem}";
$rootLabel: "> ul > li.item > label:not(.toggle)";
$subLabel: ".sub li.item > label:not(.toggle)";
$label: "#{$rootLabel}, #{$subLabel}";
$active: "> ul > li.item.active:not(.hasChildren), .sub li.item.active:not(.hasChildren)";
/* Look: base radius — layout transitions only on root rows (settings tweaks).
Submenu rows must not animate margin/padding during folder drill slides. */
#{$rootItem} {
border-radius: var(--bsplus-sidebar-radius, 12px) !important;
transition:
padding $sidebar-motion,
margin $sidebar-motion,
border-radius $sidebar-motion,
background-color 0.2s ease,
box-shadow 0.2s ease;
}
#{$subItem} {
border-radius: var(--bsplus-sidebar-radius, 12px) !important;
transition:
background-color 0.2s ease,
box-shadow 0.2s ease;
}
#{$rootLabel} {
min-height: 28px !important;
transition:
font-size $sidebar-motion,
line-height $sidebar-motion,
padding $sidebar-motion,
margin $sidebar-motion;
> svg {
transition:
width $sidebar-motion,
height $sidebar-motion,
margin $sidebar-motion;
}
}
#{$subLabel} {
min-height: 28px !important;
transition: none;
}
/* —— Style presets —— */
&.bsplus-sidebar-style-soft {
#{$item} {
margin: 0 8px 10px !important;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.12);
}
#{$active} {
box-shadow: 0 6px 18px rgba(0, 0, 0, 0.22);
background: rgba(0, 0, 0, 0.38) !important;
}
}
&.bsplus-sidebar-style-pill {
#{$item} {
margin: 0 10px 8px !important;
border-radius: 999px !important;
}
#{$active} {
background: rgba(0, 0, 0, 0.4) !important;
}
}
&.bsplus-sidebar-style-glass {
/* Never put backdrop-filter on a folder — it becomes a clip
containing-block and hides `.sub` labels on Chromium/Edge. Lean rows
blur; closed folders keep the translated glass surface without blur;
open folders drop the fill entirely so `.sub` stays clip-safe. */
#{$item} {
&:not(:has(> .sub)) {
margin: 4px 8px 4px !important;
background: rgba(255, 255, 255, 0.1) !important;
backdrop-filter: blur(10px);
-webkit-backdrop-filter: blur(10px);
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.14);
}
&:is(li, section).hasChildren:not(:is(.active, .bsplus-active)) {
margin: 4px 8px 4px !important;
background: rgba(255, 255, 255, 0.1) !important;
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.14);
}
&:has(> .sub):is(.active, .bsplus-active) {
background: transparent !important;
backdrop-filter: none !important;
-webkit-backdrop-filter: none !important;
box-shadow: none !important;
overflow: visible !important;
contain: none !important;
}
}
#{$active} {
background: rgba(255, 255, 255, 0.2) !important;
box-shadow:
inset 0 0 0 1px rgba(255, 255, 255, 0.28),
0 8px 20px rgba(0, 0, 0, 0.2);
}
}
&.bsplus-sidebar-style-sharp {
#{$item},
#{$active} {
border-radius: 4px !important;
}
#{$item} {
margin: 0 4px 4px !important;
}
#{$active} {
background: rgba(0, 0, 0, 0.42) !important;
}
}
&.bsplus-sidebar-style-strip {
#{$item} {
margin: 0 0 2px !important;
border-radius: 0 !important;
background: transparent !important;
box-shadow: none !important;
}
#{$active} {
position: relative !important;
background: rgba(255, 255, 255, 0.12) !important;
box-shadow: none !important;
&::after {
@include accent-bar(0.55);
}
}
}
&.bsplus-sidebar-style-neon {
#{$active} {
background: rgba(255, 255, 255, 0.1) !important;
box-shadow:
0 0 0 1px rgba(255, 255, 255, 0.55),
0 0 14px rgba(255, 255, 255, 0.4),
0 0 28px rgba(255, 255, 255, 0.22) !important;
}
#{$item} {
margin: 0 8px 8px !important;
}
}
/* —— Density (comfortable = no class / no overrides) —— */
&.bsplus-sidebar-density-compact {
#{$item},
#{$active} {
padding: 6px 8px !important;
min-height: 0 !important;
}
#{$item} {
margin: 0 6px 4px !important;
height: auto !important;
}
#{$label} {
padding: 0 !important;
margin: 0 !important;
font-size: 13px !important;
line-height: 1.2 !important;
min-height: 20px !important;
height: auto !important;
white-space: nowrap !important;
> svg {
width: 20px !important;
height: 20px !important;
margin: 0 8px 0 2px !important;
flex-shrink: 0 !important;
}
}
}
&.bsplus-sidebar-density-large {
#{$item} {
margin: 0 8px 10px !important;
padding: 14px 12px !important;
}
#{$label} {
padding: 0 !important;
font-size: 17px !important;
line-height: 1.25 !important;
min-height: 30px !important;
> svg {
width: 30px !important;
height: 30px !important;
margin: 0 10px 0 4px !important;
}
}
}
/* —— Active indicator (fill = default, no class) —— */
&.bsplus-sidebar-indicator-bar:not(.bsplus-sidebar-style-strip) {
#{$active} {
position: relative !important;
background: rgba(255, 255, 255, 0.1) !important;
box-shadow: none !important;
&::after {
@include accent-bar(0.45);
}
}
}
&.bsplus-sidebar-indicator-outline {
#{$active} {
background: transparent !important;
box-shadow:
inset 0 0 0 2px rgba(255, 255, 255, 0.55),
0 0 0 1px rgba(255, 255, 255, 0.12) !important;
}
}
&.bsplus-sidebar-indicator-underline:not(.bsplus-sidebar-style-strip) {
#{$active} {
position: relative !important;
background: transparent !important;
box-shadow: none !important;
&::after {
content: "" !important;
position: absolute !important;
left: 14px !important;
right: 14px !important;
bottom: 6px !important;
top: auto !important;
width: auto !important;
height: 3px !important;
border-radius: 999px !important;
background: #fff !important;
box-shadow: 0 0 8px rgba(255, 255, 255, 0.4) !important;
pointer-events: none !important;
z-index: 3 !important;
opacity: 1 !important;
display: block !important;
}
}
}
}
+1 -1
View File
@@ -12,4 +12,4 @@ html:not(.dark) {
--theme-primary: #ffffff;
--theme-secondary: #e5e7eb;
--text-primary: black;
}
}
+21 -19
View File
@@ -8,9 +8,10 @@ html.transparencyEffects:not(.dark) {
--background-secondary: rgba(229, 231, 235, 0.6);
}
html.transparencyEffects {
/* Background Fixes */
[class*="notifications__item___"],
.notifications__item___2ErJN,
#shortcuts {
backdrop-filter: unset !important;
}
@@ -21,52 +22,53 @@ html.transparencyEffects {
}
/* Blurs */
.search,
.document,
.bsplus-rounded,
.draggable,
.notice,
[class*="BasicPanel__BasicPanel___"],
.BasicPanel__BasicPanel___1GP6s,
.message.addMessage,
.singleSelect,
.uiFileHandlerPanel,
[class*="Module__wrapper___"],
[class*="notifications__list___"],
.Module__wrapper___2sbOo,
.notifications__list___rp2L2,
.thread,
.calendar,
.navigator,
#title,
[class*="LabelList__selected___"],
.LabelList__selected___3Egk7,
.buttonChecklist,
.pane,
[class*="MessageList__MessageList___"] {
.legacy-root button, .legacy-root a,
.MessageList__MessageList___3DxoC {
backdrop-filter: blur(80px);
}
.filter-select,
.uiShortText.search,
.report {
backdrop-filter: blur(10px) !important;
}
#menu {
backdrop-filter: blur(var(--bsplus-sidebar-blur, 50px));
.whatsnewContainer,
.Message__Message___3oJaU {
backdrop-filter: blur(50px);
}
.kanban-column,
.whatsnewContainer,
[class*="Message__Message___"] {
backdrop-filter: blur(50px);
#menu {
backdrop-filter: blur(20px);
}
.title > a {
backdrop-filter: blur(0px) !important;
}
.search,
.document,
.border {
backdrop-filter: blur(80px);
}
#main > .dashboard {
section,
.dashlet {
backdrop-filter: blur(8px);
}
}
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 273 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 141 KiB

-48
View File
@@ -1,48 +0,0 @@
@import "tailwindcss" source("../");
@plugin "@tailwindcss/forms";
@custom-variant dark (&:is(.dark *));
@theme {
--text-*: initial;
--text-xs: 0.65rem;
--text-sm: 0.775rem;
--text-base: 0.65rem;
--text-md: 0.65rem;
--text-lg: 1rem;
--text-xl: 1.25rem;
--text-2xl: 1.5rem;
--text-3xl: 1.875rem;
--text-4xl: 2.25rem;
--text-5xl: 3rem;
--text-6xl: 4rem;
--text-7xl: 5rem;
--text-8xl: 6rem;
--text-9xl: 8rem;
--text-10xl: 10rem;
--text-11xl: 12rem;
--text-12xl: 14rem;
--text-13xl: 16rem;
--text-14xl: 18rem;
--font-IconFamily: IconFamily;
--animate-spin-fast: spin 0.4s linear infinite;
--aspect-theme: 5 / 1;
}
@layer base {
*,
::after,
::before,
::backdrop,
::file-selector-button {
border-color: var(--color-gray-200, currentcolor);
}
button {
cursor: pointer;
}
}
+6 -30
View File
@@ -1,32 +1,8 @@
declare module "*.mp4";
declare module "*.webm";
declare module "*.woff";
declare module "*.scss";
declare module "*.png";
declare module "*.webp";
declare module "*.html";
declare module "*.svelte";
declare module "*?inlineWorker" {
const value: () => Worker;
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 '*.mp4';
declare module '*.woff';
declare module '*.scss';
declare module '*.png';
declare module '*.html';
declare module "*.png?base64" {
const value: string;
@@ -51,4 +27,4 @@ declare module "*.gif?base64" {
declare module "*.svg?base64" {
const value: string;
export default value;
}
}
-6
View File
@@ -1,6 +0,0 @@
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;
-4
View File
@@ -1,4 +0,0 @@
{
"last_updated": "2026-10-29T00:00:00.000Z",
"whatsnew_html": "<div class=\"whatsnewTextContainer\"><h3>1. Agreement</h3><p>By installing or using BetterSEQTA+, you agree to these Terms of Service. If you do not agree, do not use the extension.</p><h3>2. The extension</h3><p>BetterSEQTA+ is a browser extension that enhances SEQTA Learn and SEQTA Engage on your device. Features may change over time.</p><h3>3. Your school account</h3><p>You must comply with your school’s policies when using SEQTA. BetterSEQTA+ does not replace your school’s terms.</p><h3>4. Acceptable use</h3><p>Do not use the extension to harm others, bypass security, or violate applicable law.</p><h3>5. Privacy</h3><p>Our Privacy Policy explains what data we process. See <a href=\"https://betterseqta.org/privacy\" target=\"_blank\" rel=\"noopener noreferrer\">betterseqta.org/privacy</a>.</p><h3>6. Changes</h3><p>We may update these terms. Material changes may require you to accept again in the extension.</p></div>"
}
+3 -29
View File
@@ -1,33 +1,7 @@
<script lang="ts">
let {
onClick,
text,
disabled = false,
variant = "secondary",
icon,
class: className = "",
}: {
onClick: () => void;
text: string;
disabled?: boolean;
variant?: "primary" | "secondary" | "ghost";
icon?: string;
class?: string;
} = $props();
const variants = {
primary: "bg-zinc-100 text-zinc-900 border-transparent enabled:hover:bg-white",
secondary: "dark:bg-[#38373D]/50 bg-[#DDDDDD]/50 border-[#DDDDDD]/30 dark:border-[#38373D]/30 dark:text-white enabled:hover:brightness-125",
ghost: "bg-transparent border-transparent dark:text-white enabled:hover:bg-zinc-200/60 dark:enabled:hover:bg-zinc-700/50",
};
let { onClick, text } = $props<{ onClick: () => void, text: string, [key: string]: any }>();
</script>
<button
type="button"
onclick={onClick}
disabled={disabled}
class="inline-flex items-center justify-center gap-1.5 px-5 py-1.5 text-[0.75rem] shadow-2xl border rounded-lg transition enabled:active:scale-[0.96] focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-zinc-400 disabled:cursor-not-allowed disabled:opacity-50 {variants[variant]} {className}"
>
{#if icon}<span class="font-IconFamily text-base" aria-hidden="true">{icon}</span>{/if}
<button onclick={onClick} class='px-4 py-1 text-[0.75rem] dark:bg-[#38373D] bg-[#DDDDDD] dark:text-white rounded-md'>
{text}
</button>
</button>
-154
View File
@@ -1,154 +0,0 @@
<script lang="ts">
import { onMount } from "svelte";
import { animate } from "motion";
import { delay } from "@/seqta/utils/delay.ts";
import { cloudAuth } from "@/seqta/utils/CloudAuth";
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
import CloudPfpAvatar from "@/interface/components/CloudPfpAvatar.svelte";
import Button from "./Button.svelte";
const { hidePanel }: {
hidePanel: () => void;
} = $props();
let cloudState = $state(cloudAuth.state);
let background = $state<HTMLDivElement | null>(null);
let content = $state<HTMLDivElement | null>(null);
let loginError = $state<string | null>(null);
onMount(() => {
const unsub = cloudAuth.subscribe((s) => {
cloudState = s;
});
if (background && content) {
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 }
);
}
const handleEscapeKey = (e: KeyboardEvent) => {
if (e.key === "Escape") closePanel();
};
document.addEventListener("keydown", handleEscapeKey);
return () => {
unsub();
document.removeEventListener("keydown", handleEscapeKey);
};
});
async function closePanel() {
if (!background || !content) return;
animate(
content,
{ scale: [1, 0.4], opacity: [1, 0] },
{ type: "spring", stiffness: 400, damping: 30 }
);
animate(
background,
{ opacity: [1, 0] },
{ ease: [0.4, 0, 0.2, 1] }
);
await delay(400);
hidePanel();
}
function handleBackgroundClick(event: MouseEvent) {
if (event.target === background) closePanel();
}
async function handleSignIn() {
loginError = null;
const result = await cloudAuth.startLogin();
if (result.success) {
closePanel();
} else {
loginError = result.error ?? "Failed to open login page";
}
}
async function handleLogout() {
await cloudAuth.logout();
}
function getInitials(): string {
const u = cloudState.user;
if (!u) return "?";
if (u.displayName) return u.displayName.slice(0, 2).toUpperCase();
if (u.username) return u.username.slice(0, 2).toUpperCase();
if (u.email) return u.email.slice(0, 2).toUpperCase();
return "?";
}
</script>
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
bind:this={background}
class="flex absolute top-0 left-0 z-50 justify-center items-center w-full h-full cursor-pointer bg-black/50 {$settingsState.DarkMode ? 'dark' : ''}"
onclick={handleBackgroundClick}
onkeydown={(e) => { if (e.key === "Enter") handleBackgroundClick(e as unknown as MouseEvent) }}
>
<div
bind:this={content}
class="p-5 w-[320px] bg-white rounded-xl border shadow-lg cursor-auto dark:bg-zinc-800 border-zinc-100 dark:border-zinc-700"
>
<h3 class="text-lg font-bold text-zinc-900 dark:text-white">BetterSEQTA Cloud</h3>
<p class="mt-0.5 text-sm text-zinc-500 dark:text-zinc-400">Account & sync</p>
<div class="mt-4">
{#if cloudState.isLoggedIn}
<div class="flex flex-col gap-4">
<div class="flex items-center gap-3">
{#if cloudState.user?.pfpUrl}
<CloudPfpAvatar
user={cloudState.user}
class="w-12 h-12 rounded-full object-cover ring-2 ring-zinc-200 dark:ring-zinc-600"
/>
{/if}
{#if !cloudState.user?.pfpUrl}
<div class="flex items-center justify-center w-12 h-12 rounded-full bg-zinc-300 dark:bg-zinc-600 text-zinc-700 dark:text-zinc-200 font-semibold text-base">
{getInitials()}
</div>
{/if}
<div class="min-w-0 flex-1">
<p class="text-sm font-medium text-zinc-900 dark:text-white truncate">
{cloudState.user?.displayName || cloudState.user?.username || cloudState.user?.email || "User"}
</p>
{#if cloudState.user?.email && cloudState.user?.email !== (cloudState.user?.displayName || cloudState.user?.username)}
<p class="text-xs text-zinc-500 dark:text-zinc-400 truncate">{cloudState.user.email}</p>
{/if}
</div>
</div>
<button
type="button"
onclick={handleLogout}
class="w-full px-4 py-2.5 text-sm font-medium rounded-lg bg-zinc-200 dark:bg-zinc-700 text-zinc-900 dark:text-white hover:bg-zinc-300 dark:hover:bg-zinc-600 transition-colors duration-200"
>
Sign out
</button>
</div>
{:else}
<div class="flex flex-col gap-3">
<p class="text-sm text-zinc-600 dark:text-zinc-400">
Sign in to sync settings across devices, use your cloud profile picture, and more.
</p>
<Button class="w-full" icon={""} text="Sign in with BetterSEQTA Cloud" onClick={handleSignIn} />
{#if loginError}
<p class="text-xs text-red-600 dark:text-red-400">{loginError}</p>
{/if}
<p class="text-xs text-center text-zinc-400 dark:text-zinc-500">
Opens accounts.betterseqta.org in a new tab
</p>
</div>
{/if}
</div>
</div>
</div>
@@ -1,46 +0,0 @@
<script lang="ts">
import { resolveCloudPfp, defaultAccountsPfpUrl } from "@/seqta/utils/cloudPfpCache";
import type { CloudUser } from "@/seqta/utils/CloudAuth";
const { user, class: className = "" }: {
user: CloudUser | null | undefined;
class?: string;
} = $props();
let avatarSrc = $state<string | undefined>(undefined);
let revokeUrl: string | undefined;
$effect(() => {
const u = user;
if (revokeUrl) {
URL.revokeObjectURL(revokeUrl);
revokeUrl = undefined;
}
avatarSrc = undefined;
if (!u?.id) return;
const pfpUrl = u.pfpUrl ?? defaultAccountsPfpUrl(u.id);
let cancelled = false;
void resolveCloudPfp(u.id, pfpUrl).then((resolved) => {
if (cancelled || !resolved) return;
if (resolved.fromCache) {
revokeUrl = resolved.src;
}
avatarSrc = resolved.src;
});
return () => {
cancelled = true;
if (revokeUrl) {
URL.revokeObjectURL(revokeUrl);
revokeUrl = undefined;
}
};
});
</script>
{#if avatarSrc}
<img src={avatarSrc} alt="" class={className} />
{/if}
@@ -1,116 +0,0 @@
<script lang="ts">
import browser from "@/lib/browser";
import { cloudAuth } from "@/seqta/utils/CloudAuth";
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
import Button from "./Button.svelte";
import Switch from "./Switch.svelte";
let { showDisclaimer }: {
showDisclaimer: (onConfirm: () => void, onCancel: () => void) => void;
} = $props();
let cloudState = $state(cloudAuth.state);
let busy = $state(false);
let statusMessage = $state<string | null>(null);
let statusError = $state<string | null>(null);
$effect(() => {
const unsub = cloudAuth.subscribe((s) => {
cloudState = s;
});
return unsub;
});
async function upload() {
if (!cloudState.isLoggedIn) return;
busy = true;
statusError = null;
statusMessage = null;
try {
const res = (await browser.runtime.sendMessage({
type: "cloudSettingsUpload",
})) as { success?: boolean; error?: string };
if (res?.success) {
statusMessage = "Settings uploaded.";
} else {
statusError = res?.error ?? "Upload failed";
}
} catch (e) {
statusError = e instanceof Error ? e.message : "Upload failed";
} finally {
busy = false;
}
}
function promptDownload() {
showDisclaimer(confirmDownload, () => {});
}
async function confirmDownload() {
if (!cloudState.isLoggedIn) return;
busy = true;
statusError = null;
statusMessage = null;
try {
const res = (await browser.runtime.sendMessage({
type: "cloudSettingsDownload",
})) as { success?: boolean; error?: string; notFound?: boolean };
if (res?.success) {
statusMessage = "Settings restored.";
} else {
statusError = res?.error ?? "Download failed";
}
} catch (e) {
statusError = e instanceof Error ? e.message : "Download failed";
} finally {
busy = false;
}
}
</script>
{#if cloudState.isLoggedIn}
<div class="flex flex-col gap-2.5">
<div class="flex items-center justify-between gap-3">
<div>
<p class="text-[11px] font-semibold text-zinc-800 dark:text-zinc-100">Automatic sync</p>
<p class="text-[10px] text-zinc-500 dark:text-zinc-400">Syncs settings when SEQTA loads and when you make changes</p>
</div>
<div class="shrink-0">
<Switch
state={$settingsState.autoCloudSettingsSync !== false}
onChange={(isOn: boolean) => (settingsState.autoCloudSettingsSync = isOn)}
/>
</div>
</div>
<div class="flex flex-wrap gap-2">
<Button
text={busy ? "Please wait\u2026" : "Upload"}
onClick={upload}
disabled={busy}
/>
<Button
text={busy ? "Please wait\u2026" : "Download"}
onClick={promptDownload}
disabled={busy}
/>
</div>
{#if statusMessage}
<p class="text-[11px] text-emerald-600 dark:text-emerald-400">{statusMessage}</p>
{/if}
{#if statusError}
<p class="text-[11px] text-red-600 dark:text-red-400">{statusError}</p>
{/if}
<p class="text-[10px] text-zinc-400 dark:text-zinc-500">
Passwords and tokens are never synced.
<a
href="https://betterseqta.org/privacy"
target="_blank"
rel="noopener noreferrer"
class="font-medium text-emerald-600 underline decoration-emerald-600/50 underline-offset-2 hover:text-emerald-700 dark:text-emerald-400 dark:hover:text-emerald-300 rounded-xs"
>Privacy policy</a>
</p>
</div>
{/if}
+7 -7
View File
@@ -7,19 +7,20 @@
import { indentWithTab, history, defaultKeymap, historyKeymap } from '@codemirror/commands';
import { indentOnInput, indentUnit, bracketMatching, foldKeymap, syntaxHighlighting, defaultHighlightStyle } from '@codemirror/language';
import { closeBrackets, autocompletion, closeBracketsKeymap, completionKeymap } from '@codemirror/autocomplete';
import { highlightSpecialChars, drawSelection, rectangularSelection, crosshairCursor, highlightActiveLine, keymap, EditorView, dropCursor, type KeyBinding } from '@codemirror/view';
import { highlightSpecialChars, drawSelection, rectangularSelection, crosshairCursor, highlightActiveLine, keymap, EditorView, dropCursor } from '@codemirror/view';
import { color } from '@uiw/codemirror-extensions-color'
import { Compartment } from '@codemirror/state';
// Theme
import { githubLight, githubDark } from '@uiw/codemirror-theme-github';
// Language
import { css } from "@codemirror/lang-css";
let editor = $state<HTMLDivElement | null>(null)
let view: EditorView | null = null;
let unsubSettings: (() => void) | undefined;
let editorTheme = new Compartment();
let { value, onChange, className }: {value: string, onChange: (value: string) => void, className?: string} = $props()
let { value, onChange } = $props<{value: string, onChange: (value: string) => void}>()
function createEditorState(initialContents: string) {
let extensions = [
@@ -45,7 +46,7 @@
...historyKeymap,
...foldKeymap,
...completionKeymap,
] as KeyBinding[]),
]),
EditorView.updateListener.of((update) => {
if (update.docChanged) {
onChange(update.state.doc.toString())
@@ -72,7 +73,7 @@
view = createEditorView(state, editor as HTMLElement);
}
unsubSettings = settingsState.subscribe((settings) => {
settingsState.subscribe((settings) => {
if (view) {
view.dispatch({
effects: editorTheme.reconfigure(
@@ -84,11 +85,10 @@
});
onDestroy(() => {
unsubSettings?.();
if (view) {
view.destroy();
}
})
</script>
<div class={`rounded-lg text-[13px] overflow-clip w-full bg-white dark:bg-zinc-900 ${className}`} bind:this={editor}></div>
<div class="rounded-lg text-[13px] overflow-clip w-full bg-white dark:bg-zinc-900" bind:this={editor}></div>
+86
View File
@@ -0,0 +1,86 @@
div:has(> #rbgcp-wrapper) {
background: transparent !important;
}
.dark {
#rbgcp-wrapper {
div[style="padding-top: 11px; position: relative;"] div {
color: white !important;
}
div:has(> #rbgcp-solid-btn),
div:has(> #rbgcp-advanced-btn),
#rbgcp-color-model-btn > div,
#rbgcp-gradient-controls-wrap {
background-color: #37373b !important;
color: white !important;
svg {
circle {
fill: white !important;
}
polyline,
line,
g,
path {
stroke: white !important;
}
}
#rbgcp-radial-btn,
#rbgcp-linear-btn {
&[style*="background: white;"] {
background-color: #28282b !important;
}
svg {
path,
g,
polyline,
circle {
stroke: white !important;
fill: transparent !important;
}
}
}
div:has(> #rbgcp-stop-input) svg {
path {
stroke: unset !important;
fill: white !important;
}
}
#rbgcp-comparibles-btn svg path {
fill: white !important;
}
> div {
color: white !important;
&[style*="background: white;"] {
background: #28282b !important;
}
}
}
div:has(> #rbgcp-degree-input) {
width: 70px !important;
}
#rbgcp-degree-input {
width: 50px !important;
}
#rbgcp-degree-input,
#rbgcp-stop-input {
color: white !important;
}
#rbgcp-gradient-controls-wrap > div,
#rbgcp-gradient-controls-wrap > div > div:not([role="button"]) {
background-color: #37373b !important;
}
}
}
+60 -85
View File
@@ -1,127 +1,102 @@
<script lang="ts">
import { onMount } from 'svelte'
import ColourPicker from './ColourPicker.tsx';
import ReactAdapter from './utils/ReactAdapter.svelte';
import { animate } from 'motion';
import { delay } from '@/seqta/utils/delay'
import { settingsState } from '@/seqta/utils/listeners/SettingsState'
import GradientPicker from './colourPicker/GradientPicker.svelte'
import { delay } from '@/seqta/utils/delay.ts'
const PRESETS_KEY = 'colorPickerPresets';
const MAX_PRESETS = 18;
const DEFAULT_PRESETS = [
"linear-gradient(30deg, rgba(229,209,218,1) 0%, RGBA(235,169,202,1) 46%, rgba(214,155,162,1) 100%)",
"linear-gradient(40deg, rgba(201,61,0,1) 0%, RGBA(170, 5, 58, 1) 100%)",
"linear-gradient(40deg, rgba(0, 141, 201, 0.76) 0%, rgba(8, 5, 170, 0.66) 100%)",
"linear-gradient(40deg, rgba(0, 201, 20, 0.76) 0%, rgba(4, 160, 105, 0.66) 100%)",
"linear-gradient(40deg, rgba(199, 20, 55, 0.76) 0%, rgba(95, 11, 160, 0.66) 100%)",
"linear-gradient(40deg, rgba(24, 20, 199, 0.76) 0%, rgba(23, 173, 65, 0.66) 100%)",
"radial-gradient(circle, rgba(20, 199, 178, 0.76) 32%, rgba(3, 120, 57, 0.66) 100%)",
"radial-gradient(circle, rgba(13, 15, 145, 0.76) 12%, rgba(103, 3, 120, 0.66) 100%)",
"linear-gradient(20deg, rgb(230, 21, 21) 0%, rgb(230, 109, 21) 12%, rgb(230, 34, 21) 26%, rgb(230, 21, 21) 39%, rgb(230, 84, 21) 48%, rgb(230, 34, 21) 58%, rgb(230, 96, 21) 69%, rgb(230, 34, 21) 80%, rgb(230, 71, 21) 89%, rgb(230, 21, 21) 100%)",
"rgba(114, 1, 170, 0.89)",
"rgba(93, 135, 63, 0.89)",
"rgba(4, 4, 138, 0.77)",
"rgba(21, 20, 20, 0.89)",
"linear-gradient(340deg, rgb(205, 74, 82) 18%, rgba(132, 8, 8, 0.89) 46%, rgb(204, 78, 85) 72%)",
"radial-gradient(circle, rgb(74, 205, 158) 0%, rgba(8, 72, 132, 0.89) 99%)",
"rgba(17, 94, 89, 1)",
"rgba(30, 64, 175, 0.89)",
"rgba(134, 25, 143, 1)",
"rgba(14, 165, 233, 0.9)",
];
const {
hidePicker,
standalone = false,
savePresets = true,
customOnChange = null,
customState = null,
}: {
hidePicker?: () => void;
standalone?: boolean;
savePresets?: boolean;
customOnChange?: ((color: string) => void) | null;
customState?: string | null;
} = $props();
const { hidePicker, standalone = false, savePresets = true, customOnChange = null, customState = null } = $props<{
hidePicker?: () => void,
standalone?: boolean,
savePresets?: boolean,
customOnChange?: (color: string) => void,
customState?: string
}>();
let background = $state<HTMLDivElement | null>(null);
let content = $state<HTMLDivElement | null>(null);
let presets = $state<string[]>(loadPresets());
let current = $state(initialColour());
function initialColour(): string {
return customState ?? settingsState.selectedColor ?? '';
}
function loadPresets(): string[] {
try {
const saved = JSON.parse(localStorage.getItem(PRESETS_KEY) ?? 'null');
return Array.isArray(saved) ? saved : DEFAULT_PRESETS;
} catch {
return DEFAULT_PRESETS;
}
}
function rememberPreset(colour: string) {
if (!colour || presets[0] === colour) return;
const updated = [colour, ...presets.filter((preset) => preset !== colour)].slice(0, MAX_PRESETS);
localStorage.setItem(PRESETS_KEY, JSON.stringify(updated));
}
function handleChange(colour: string) {
current = colour;
if (customOnChange) customOnChange(colour);
else settingsState.selectedColor = colour;
}
const closePicker = async () => {
if (standalone || !background || !content) return;
if (standalone) return;
if (!background || !content) return;
animate(content, { scale: [1, 0.4], opacity: [1, 0] }, { type: 'spring', stiffness: 400, damping: 30 });
animate(background, { opacity: [1, 0] }, { ease: [0.4, 0, 0.2, 1] });
animate(
content,
{ scale: [1, 0.4], opacity: [1, 0] },
{
type: 'spring',
stiffness: 400,
damping: 30
}
);
animate(
background,
{ opacity: [1, 0] },
{ ease: [0.4, 0, 0.2, 1] }
);
await delay(400);
hidePicker?.();
hidePicker();
}
onMount(() => {
if (!standalone && background && content) {
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 });
}
if (standalone) return;
if (!background || !content) return;
const handleEscapeKey = (event: KeyboardEvent) => {
if (event.key === 'Escape') closePicker();
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
}
);
const handleEscapeKey = (e: KeyboardEvent) => {
if (e.key === 'Escape') {
closePicker();
}
};
document.addEventListener('keydown', handleEscapeKey);
return () => {
document.removeEventListener('keydown', handleEscapeKey);
if (savePresets && !customOnChange) rememberPreset(current);
};
});
function handleBackgroundClick(event: MouseEvent) {
if (event.target === background) closePicker();
if (event.target === background) {
closePicker();
}
}
</script>
{#if standalone}
<div class="h-auto {$settingsState.DarkMode ? 'dark' : ''}">
<GradientPicker value={customState ?? current} onchange={handleChange} {presets} />
<div class="h-auto rounded-xl overflow-clip">
<ReactAdapter customOnChange={customOnChange} customState={customState} savePresets={savePresets} el={ColourPicker} />
</div>
{:else}
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
bind:this={background}
class="flex absolute top-0 left-0 z-50 justify-center items-center w-full h-full shadow-2xl cursor-pointer bg-black/20 border border-[#DDDDDD]/30 dark:border-[#38373D]/30 {$settingsState.DarkMode ? 'dark' : ''}"
class="absolute top-0 left-0 z-50 flex items-center justify-center w-full h-full cursor-pointer bg-black/20"
onclick={handleBackgroundClick}
onkeydown={(event) => { if (event.key === 'Enter') handleBackgroundClick(event as unknown as MouseEvent) }}
onkeydown={(e) => { e.key === 'Enter' && handleBackgroundClick }}
>
<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"
class="h-auto p-4 bg-white border shadow-lg cursor-auto rounded-xl dark:bg-zinc-800 border-zinc-100 dark:border-zinc-700"
>
<GradientPicker value={current} onchange={handleChange} {presets} />
<ReactAdapter customOnChange={customOnChange} customState={customState} savePresets={savePresets} el={ColourPicker} />
</div>
</div>
{/if}
+108
View File
@@ -0,0 +1,108 @@
import ColorPicker from "react-best-gradient-color-picker"
import { useEffect, useRef, useState } from "react"
import { settingsState } from "@/seqta/utils/listeners/SettingsState.ts"
const defaultPresets = [
"linear-gradient(30deg, rgba(229,209,218,1) 0%, RGBA(235,169,202,1) 46%, rgba(214,155,162,1) 100%)",
"linear-gradient(40deg, rgba(201,61,0,1) 0%, RGBA(170, 5, 58, 1) 100%)",
"linear-gradient(40deg, rgba(0, 141, 201, 0.76) 0%, rgba(8, 5, 170, 0.66) 100%)",
"linear-gradient(40deg, rgba(0, 201, 20, 0.76) 0%, rgba(4, 160, 105, 0.66) 100%)",
"linear-gradient(40deg, rgba(199, 20, 55, 0.76) 0%, rgba(95, 11, 160, 0.66) 100%)",
"linear-gradient(40deg, rgba(24, 20, 199, 0.76) 0%, rgba(23, 173, 65, 0.66) 100%)",
"radial-gradient(circle, rgba(20, 199, 178, 0.76) 32%, rgba(3, 120, 57, 0.66) 100%)",
"radial-gradient(circle, rgba(13, 15, 145, 0.76) 12%, rgba(103, 3, 120, 0.66) 100%)",
"linear-gradient(20deg, rgb(230, 21, 21) 0%, rgb(230, 109, 21) 12%, rgb(230, 34, 21) 26%, rgb(230, 21, 21) 39%, rgb(230, 84, 21) 48%, rgb(230, 34, 21) 58%, rgb(230, 96, 21) 69%, rgb(230, 34, 21) 80%, rgb(230, 71, 21) 89%, rgb(230, 21, 21) 100%)",
"rgba(114, 1, 170, 0.89)",
"rgba(93, 135, 63, 0.89)",
"rgba(4, 4, 138, 0.77)",
"rgba(21, 20, 20, 0.89)",
"linear-gradient(340deg, rgb(205, 74, 82) 18%, rgba(132, 8, 8, 0.89) 46%, rgb(204, 78, 85) 72%)",
"radial-gradient(circle, rgb(74, 205, 158) 0%, rgba(8, 72, 132, 0.89) 99%)",
"rgba(17, 94, 89, 1)",
"rgba(30, 64, 175, 0.89)",
"rgba(134, 25, 143, 1)",
"rgba(14, 165, 233, 0.9)",
]
interface PickerProps {
customOnChange?: (color: string) => void
customState?: string
savePresets?: boolean
}
export default function Picker({
customOnChange,
customState,
savePresets = true,
}: PickerProps) {
const [customThemeColor, setCustomThemeColor] = useState<string | null>()
const [presets, setPresets] = useState<string[]>()
const latestValuesRef = useRef({ customThemeColor, customOnChange, savePresets, presets });
useEffect(() => {
if (customState !== undefined && customState !== null) {
setCustomThemeColor(customState)
} else {
setCustomThemeColor(settingsState.selectedColor ?? null)
}
if (presets === undefined) {
const savedPresets = localStorage.getItem("colorPickerPresets")
setPresets(savedPresets ? JSON.parse(savedPresets) : defaultPresets)
}
}, [])
useEffect(() => {
latestValuesRef.current = { customThemeColor, customOnChange, savePresets, presets };
}, [customThemeColor, customOnChange, savePresets, presets]);
useEffect(() => {
return () => {
const { customThemeColor, customOnChange, savePresets, presets } = latestValuesRef.current;
if (!(customThemeColor && !customOnChange && savePresets && presets)) return;
// Only proceed if presets are different (avoid unnecessary updates)
const existingIndex = presets.indexOf(customThemeColor);
let updatedPresets;
if (existingIndex === 0) {
// No need to update if the selected color is already the first element
return;
} else if (existingIndex > -1) {
updatedPresets = [
customThemeColor,
...presets.slice(0, existingIndex),
...presets.slice(existingIndex + 1),
];
} else {
updatedPresets = [customThemeColor, ...presets].slice(0, 18);
}
localStorage.setItem("colorPickerPresets", JSON.stringify(updatedPresets));
}
}, [])
useEffect(() => {
if (customThemeColor && !customOnChange) {
settingsState.selectedColor = customThemeColor
}
}, [customThemeColor, customOnChange])
return (
<ColorPicker
disableDarkMode={true}
presets={presets}
hideInputs={true}
value={customThemeColor ?? ""}
onChange={(color: string) => {
if (customOnChange) {
customOnChange(color)
setCustomThemeColor(color)
} else {
setCustomThemeColor(color)
}
}}
/>
)
}
@@ -1,168 +0,0 @@
<script lang="ts">
import { fade } from "svelte/transition";
import browser from "@/lib/browser";
import QRCode from "qrcode";
import Button from "./Button.svelte";
import { portal } from "../utils/portal";
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
let showQrModal = $state(false);
let qrDataUrl = $state<string | null>(null);
let appLink = $state<string | null>(null);
let errorMessage = $state<string | null>(null);
let isLoading = $state(false);
let isStandalone = $state(false);
function isExtensionPage(): boolean {
return (
window.location.protocol === "chrome-extension:" ||
window.location.protocol === "moz-extension:"
);
}
function isSeqtaUrl(url: string): boolean {
try {
const u = new URL(url);
return u.hostname.includes("seqta") || u.hostname.endsWith(".edu.au");
} catch {
return false;
}
}
function normalizeBaseUrl(url: string): string {
try {
const u = new URL(url);
return u.origin;
} catch {
return url;
}
}
async function getAppLink(): Promise<string | null> {
let baseUrl: string | undefined;
if (isExtensionPage()) {
baseUrl = undefined;
} else {
baseUrl = normalizeBaseUrl(window.location.href);
if (!isSeqtaUrl(baseUrl)) return null;
}
const { appLink: link } = (await browser.runtime.sendMessage({
type: "getSeqtaSession",
baseUrl,
})) as { appLink: string | null };
return link ?? null;
}
async function generateQrCode() {
errorMessage = null;
qrDataUrl = null;
isLoading = true;
try {
isStandalone = isExtensionPage();
const link = await getAppLink();
if (!link) {
if (isStandalone) {
errorMessage =
"Open SEQTA Learn in a tab and log in, then open settings from that tab to generate a QR code.";
} else {
errorMessage = "Please log in to SEQTA Learn first.";
}
return;
}
const dataUrl = await QRCode.toDataURL(link, { width: 256, margin: 2 });
appLink = link;
qrDataUrl = dataUrl;
showQrModal = true;
} catch (err) {
console.error("[ConnectMobileApp] Failed to generate QR:", err);
errorMessage = "Failed to generate QR code. Please try again.";
} finally {
isLoading = false;
}
}
function closeModal() {
showQrModal = false;
qrDataUrl = null;
appLink = null;
errorMessage = null;
}
function openAppLink() {
if (appLink) window.location.href = appLink;
}
function downloadQrImage() {
if (!qrDataUrl) return;
const link = document.createElement("a");
link.href = qrDataUrl;
link.download = "desqta-login-qr.png";
link.click();
}
</script>
<div class="flex flex-col gap-1 items-end">
<Button onClick={generateQrCode} disabled={isLoading} text={isLoading ? "Generating..." : "Generate QR"} />
{#if errorMessage}
<p class="text-xs text-right text-amber-600 dark:text-amber-400">{errorMessage}</p>
{/if}
</div>
{#if showQrModal && qrDataUrl}
<div
use:portal
class="fixed cursor-auto inset-0 z-10000 flex justify-center items-center bg-black/50 {isStandalone ? 'backdrop-blur-xs' : ''} {$settingsState.DarkMode ? 'dark' : ''}"
role="button"
tabindex="-1"
onclick={(e) => {
if (e.target === e.currentTarget) closeModal();
}}
onkeydown={(e) => {
if (e.key === "Escape") closeModal();
}}
transition:fade={{ duration: 150 }}>
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
class="p-6 mx-4 w-full max-w-sm bg-white rounded-2xl shadow-2xl dark:bg-zinc-800"
onclick={(e) => e.stopPropagation()}
onkeydown={(e) => e.stopPropagation()}>
<div class="flex justify-between items-center mb-4">
<h2 class="text-lg font-bold text-zinc-900 dark:text-white">Scan with DesQTA</h2>
<button
type="button"
onclick={closeModal}
class="p-2 rounded-lg transition-colors text-zinc-500 hover:text-zinc-700 hover:bg-zinc-100 dark:hover:text-zinc-400 dark:hover:bg-zinc-700"
aria-label="Close">
<svg xmlns="http://www.w3.org/2000/svg" class="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</div>
<div class="flex justify-center p-4 bg-white rounded-xl dark:bg-zinc-900">
<img src={qrDataUrl} alt="SEQTA Learn app link QR code" class="w-64 h-64" />
</div>
<div class="flex flex-col gap-2 mt-4">
<button
type="button"
onclick={openAppLink}
class="px-4 py-2.5 w-full text-sm font-medium text-white bg-indigo-600 rounded-lg transition-colors dark:bg-indigo-500 hover:bg-indigo-700 dark:hover:bg-indigo-600">
Sign into DesQTA Desktop
</button>
<button
type="button"
onclick={downloadQrImage}
class="px-4 py-2 w-full text-xs font-medium rounded-lg border transition-colors text-zinc-500 dark:text-zinc-400 border-zinc-200 dark:border-zinc-600 hover:bg-zinc-50 dark:hover:bg-zinc-800/50">
Download QR as image
</button>
</div>
<p class="mt-2 text-sm text-center text-zinc-600 dark:text-zinc-400">
Or scan this QR code with DesQTA on your phone.
</p>
</div>
</div>
{/if}
@@ -1,74 +0,0 @@
<script lang="ts">
import { fade } from 'svelte/transition';
import { animate } from 'motion';
import { settingsState } from '@/seqta/utils/listeners/SettingsState';
let { onConfirm, onCancel, title, message }: {
onConfirm: () => void;
onCancel: () => void;
title: string;
message: string;
} = $props();
let modalElement: HTMLElement;
$effect(() => {
if (modalElement) {
animate(
modalElement,
{ scale: [0.9, 1], opacity: [0, 1] },
{
type: 'spring',
stiffness: 300,
damping: 25
}
);
}
});
</script>
<div
class="flex fixed inset-0 z-10000 justify-center items-center bg-black/50 {$settingsState.DarkMode ? 'dark' : ''}"
style="position: fixed; top: 0; left: 0; right: 0; bottom: 0;"
onclick={(e) => {
if (e.target === e.currentTarget) onCancel();
}}
onkeydown={(e) => {
if (e.key === 'Escape') onCancel();
}}
role="button"
tabindex="-1"
transition:fade={{ duration: 150 }}
>
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
bind:this={modalElement}
class="p-4 mx-4 w-full max-w-md bg-white rounded-2xl shadow-2xl dark:bg-zinc-800"
onclick={(e) => e.stopPropagation()}
onkeydown={(e) => e.stopPropagation()}
>
<h2 class="mb-3 text-xl font-bold text-gray-900 dark:text-white">
{title}
</h2>
<div class="mb-6 text-lg text-gray-700 whitespace-pre-line dark:text-gray-300">
{message}
</div>
<div class="flex gap-3 justify-end">
<button
onclick={onCancel}
class="px-4 py-2 text-sm font-medium text-gray-700 bg-gray-100 rounded-lg transition-colors hover:bg-gray-200 dark:bg-zinc-700 dark:text-gray-200 dark:hover:bg-zinc-600"
>
Cancel
</button>
<button
onclick={onConfirm}
class="px-4 py-2 text-sm font-medium text-white bg-green-600 rounded-lg shadow-inner transition-colors hover:bg-green-700 dark:bg-green-500 dark:hover:bg-green-600"
>
Enable
</button>
</div>
</div>
</div>
@@ -1,574 +0,0 @@
<script lang="ts">
import { fade, scale } from "svelte/transition";
import { onMount } from "svelte";
import Switch from "./Switch.svelte";
import {
FEEDBACK_CATEGORIES,
FEEDBACK_MESSAGE_MAX,
FEEDBACK_MESSAGE_MIN,
type FeedbackCategory,
} from "@/seqta/utils/feedback/constants";
import {
FeedbackApiError,
addPendingFeedbackId,
categoryLabel,
fetchFeedbackStatusItem,
fetchFeedbackStatusList,
formatStatus,
getInstanceHostname,
hasReply,
removePendingFeedbackIds,
submitFeedback,
validateFeedbackForm,
type FeedbackStatusItem,
} from "@/seqta/utils/feedback/client";
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
import Spinner from "./Spinner.svelte";
let { onClose, initialFeedbackId = null }: {
onClose: () => void;
initialFeedbackId?: string | null;
} = $props();
let tab = $derived<"send" | "status">(
typeof initialFeedbackId === "string" && initialFeedbackId ? "status" : "send",
);
let category = $state<FeedbackCategory>("bug");
let subject = $state("");
let message = $state("");
let includeContact = $state(false);
let contactName = $state("");
let contactEmail = $state("");
let includeInstance = $state(false);
let submitting = $state(false);
let errorMessage = $state<string | null>(null);
let successId = $state<string | null>(null);
let statusLoading = $state(false);
let statusError = $state<string | null>(null);
let statusItems = $state<FeedbackStatusItem[]>([]);
let selectedItem = $state<FeedbackStatusItem | null>(null);
const instanceHostname = getInstanceHostname();
const isDark = $derived(!!$settingsState.DarkMode);
const busy = $derived(submitting || statusLoading);
const fieldStyle = $derived(
isDark
? "background-color:#18181b;color:#fafafa;border-color:#52525b;color-scheme:dark"
: "background-color:#fff;color:#18181b;border-color:#e4e4e7;color-scheme:light",
);
const field =
"feedback-field w-full px-3 py-2.5 text-[18px] rounded-lg border focus:outline-hidden focus:ring-2 focus:ring-zinc-400";
const btn =
"px-4 py-2 text-[18px] font-medium rounded-lg transition-all duration-200 hover:scale-105 active:scale-95 focus:outline-hidden focus:ring-2 focus:ring-zinc-400 disabled:opacity-50";
const btnMuted = $derived(
`${btn} ${isDark ? "bg-zinc-700 text-zinc-200" : "bg-zinc-200 text-zinc-700"}`,
);
const btnPrimary = $derived(
`${btn} ${isDark ? "bg-zinc-200 text-zinc-900" : "bg-zinc-800 text-white"}`,
);
function isStatusDetailKey(key: string): boolean {
return key.startsWith("status-") && key !== "status-list";
}
const panelKey = $derived(
tab === "send"
? successId
? "send-success"
: "send-form"
: selectedItem
? `status-${selectedItem.id}`
: "status-list",
);
function errText(e: unknown): string {
if (e instanceof FeedbackApiError) return e.message;
return e instanceof Error ? e.message : "Something went wrong.";
}
async function loadStatusList() {
statusLoading = true;
statusError = null;
selectedItem = null;
try {
statusItems = await fetchFeedbackStatusList(10);
} catch (e) {
statusItems = [];
statusError = errText(e);
} finally {
statusLoading = false;
}
}
async function openStatusItem(id: string) {
statusLoading = true;
statusError = null;
try {
selectedItem = await fetchFeedbackStatusItem(id);
tab = "status";
successId = null;
if (selectedItem && hasReply(selectedItem)) {
void removePendingFeedbackIds([selectedItem.id]);
}
} catch (e) {
statusError = errText(e);
} finally {
statusLoading = false;
}
}
function selectTab(next: "send" | "status") {
tab = next;
errorMessage = null;
statusError = null;
successId = null;
selectedItem = null;
if (next === "status") void loadStatusList();
}
onMount(() => {
const host = document.getElementById("ExtensionPopup");
host?.classList.add("bsplus-feedback-open");
// Remove leaked global styles from earlier builds that portaled to body.
document.getElementById("betterseqta-feedback-modal-styles")?.remove();
const handleEscapeKey = (e: KeyboardEvent) => {
if (e.key === "Escape" && !busy) onClose();
};
document.addEventListener("keydown", handleEscapeKey);
if (typeof initialFeedbackId === "string" && initialFeedbackId) {
void openStatusItem(initialFeedbackId);
}
return () => {
host?.classList.remove("bsplus-feedback-open");
document.removeEventListener("keydown", handleEscapeKey);
};
});
async function handleSubmit() {
const form = {
category,
subject,
message,
includeContact,
contactName,
contactEmail,
includeInstance,
};
errorMessage = validateFeedbackForm(form);
if (errorMessage) return;
submitting = true;
try {
const result = await submitFeedback(form);
successId = result.id;
void addPendingFeedbackId(result.id);
} catch (e) {
errorMessage = errText(e);
} finally {
submitting = false;
}
}
</script>
<!-- Backdrop click target — separate from dialog so inner clicks never bubble to a "close" handler. -->
<div
class="feedback-overlay fixed inset-0 z-99999 overflow-y-auto overscroll-contain {isDark
? 'dark'
: ''}"
transition:fade={{ duration: $settingsState.animations ? 200 : 0 }}
>
<button
type="button"
class="feedback-overlay__backdrop fixed inset-0 bg-black/50 backdrop-blur-xs border-0 p-0 cursor-default"
aria-label="Close feedback"
disabled={busy}
onclick={() => {
if (!busy) onClose();
}}
></button>
<div
class="feedback-overlay__center relative z-1 flex min-h-full items-center justify-center p-4 sm:p-6 pointer-events-none"
>
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
class="feedback-dialog pointer-events-auto w-full max-w-lg max-h-[min(90dvh,100%)] rounded-2xl shadow-2xl border text-[18px] {isDark
? 'bg-zinc-800 text-white border-zinc-700'
: 'bg-white text-zinc-900 border-zinc-200'}"
onclick={(e) => e.stopPropagation()}
onkeydown={(e) => e.stopPropagation()}
role="dialog"
aria-modal="true"
aria-labelledby="feedback-modal-title"
tabindex="-1"
in:scale={{
duration: $settingsState.animations ? 280 : 0,
start: 0.92,
opacity: 0,
easing: (t) => 1 - Math.pow(1 - t, 3),
}}
>
<div
class="feedback-tabs shrink-0 flex gap-1 p-1 m-5 mb-0 rounded-full {isDark
? 'bg-zinc-900'
: 'bg-zinc-100'}"
role="tablist"
aria-label="Feedback views"
>
<button
type="button"
role="tab"
aria-selected={tab === "send"}
onclick={() => selectTab("send")}
class="feedback-tab flex-1 px-3 py-2.5 rounded-full text-[18px] font-medium transition-all duration-200 {tab ===
'send'
? isDark
? 'bg-zinc-700 text-white font-semibold shadow-xs'
: 'bg-white text-zinc-900 font-semibold shadow-xs'
: isDark
? 'bg-transparent text-zinc-400 hover:text-zinc-200'
: 'bg-transparent text-zinc-500 hover:text-zinc-800'}"
>
Send
</button>
<button
type="button"
role="tab"
aria-selected={tab === "status"}
onclick={() => selectTab("status")}
class="feedback-tab flex-1 px-3 py-2.5 rounded-full text-[18px] font-medium transition-all duration-200 {tab ===
'status'
? isDark
? 'bg-zinc-700 text-white font-semibold shadow-xs'
: 'bg-white text-zinc-900 font-semibold shadow-xs'
: isDark
? 'bg-transparent text-zinc-400 hover:text-zinc-200'
: 'bg-transparent text-zinc-500 hover:text-zinc-800'}"
>
My feedback
</button>
</div>
<div class="feedback-panel__body overflow-y-auto overscroll-contain px-5 pb-5 pt-4">
{#if panelKey === "send-success" && successId}
<h2 id="feedback-modal-title" class="mb-3 text-xl font-bold">Thanks for the feedback</h2>
<p class="mb-2 text-zinc-600 dark:text-zinc-300">Reference ID:</p>
<p
class="mb-4 px-3 py-2 font-mono text-base rounded-lg {isDark
? 'bg-zinc-900'
: 'bg-zinc-100'} break-all"
>
{successId}
</p>
<div class="flex gap-3 justify-end">
<button
type="button"
class={btnMuted}
onclick={() => successId && openStatusItem(successId)}>Check status</button
>
<button type="button" class={btnPrimary} onclick={onClose}>Done</button>
</div>
{:else if panelKey === "send-form"}
<h2 id="feedback-modal-title" class="mb-1 text-xl font-bold">Send feedback</h2>
<p class="mb-4 text-zinc-600 dark:text-zinc-400">
Anonymous by default. Contact and school details are optional.
</p>
<div class="flex flex-col gap-4">
<label class="flex flex-col gap-1.5 font-medium">
Category
<select id="feedback-category" bind:value={category} class={field} style={fieldStyle}>
{#each FEEDBACK_CATEGORIES as value (value)}
<option {value} style={fieldStyle}>{categoryLabel(value)}</option>
{/each}
</select>
</label>
<label class="flex flex-col gap-1.5 font-medium">
Subject <span class="font-normal text-zinc-500">(optional)</span>
<input
type="text"
maxlength={120}
bind:value={subject}
placeholder="Short summary"
class={field}
style={fieldStyle}
/>
</label>
<label class="flex flex-col gap-1.5 font-medium">
Message
<textarea
rows={5}
maxlength={FEEDBACK_MESSAGE_MAX}
bind:value={message}
placeholder="What happened, or what would you like to see?"
class="{field} resize-y min-h-[120px]"
style={fieldStyle}
></textarea>
<span class="text-base font-normal text-zinc-500"
>{message.trim().length}/{FEEDBACK_MESSAGE_MAX} (min {FEEDBACK_MESSAGE_MIN})</span
>
</label>
<div class="flex justify-between items-center gap-3">
<div>
<p class="font-medium">Include contact details</p>
<p class="text-base text-zinc-500">Name and email so we can reply</p>
</div>
<Switch state={includeContact} onChange={(v) => (includeContact = v)} />
</div>
{#if includeContact}
<input
type="text"
maxlength={80}
bind:value={contactName}
placeholder="Name"
class={field}
style={fieldStyle}
/>
<input
type="email"
maxlength={254}
bind:value={contactEmail}
placeholder="Email"
class={field}
style={fieldStyle}
/>
{/if}
<div class="flex justify-between items-center gap-3">
<div>
<p class="font-medium">Include SEQTA instance</p>
<p class="text-base text-zinc-500">
{#if instanceHostname}
Hostname only: <span class="font-mono">{instanceHostname}</span>
{:else}
Open SEQTA first to detect hostname
{/if}
</p>
</div>
<Switch
state={includeInstance && !!instanceHostname}
onChange={(v) => {
if (instanceHostname) includeInstance = v;
}}
/>
</div>
{#if errorMessage}
<p class="text-red-600 dark:text-red-400" role="alert">{errorMessage}</p>
{/if}
<p class="text-base text-zinc-500">
Sent to betterseqta.org.
<a
href="https://betterseqta.org/privacy"
target="_blank"
rel="noopener noreferrer"
class="underline">Privacy</a
>
</p>
<div class="flex gap-3 justify-end">
<button type="button" class={btnMuted} onclick={onClose} disabled={submitting}
>Cancel</button
>
<button type="button" class={btnPrimary} onclick={handleSubmit} disabled={submitting}>
{submitting ? "Sending…" : "Send feedback"}
</button>
</div>
</div>
{:else if isStatusDetailKey(panelKey) && selectedItem}
<div class="flex items-start justify-between gap-3 mb-3">
<h2 id="feedback-modal-title" class="text-xl font-bold">Feedback status</h2>
<button
type="button"
class="{btnMuted} text-base! px-3! py-1.5!"
onclick={() => {
selectedItem = null;
void loadStatusList();
}}>Back</button
>
</div>
<p class="mb-1 font-medium">
{selectedItem.subject || "Untitled"} · {formatStatus(selectedItem.status)}
</p>
<p class="mb-4 font-mono text-base text-zinc-500 break-all">{selectedItem.id}</p>
{#if hasReply(selectedItem)}
<div
class="p-3 mb-4 rounded-lg border {isDark
? 'border-zinc-700 bg-zinc-900/50'
: 'border-zinc-200 bg-zinc-50'}"
>
<p class="mb-1 text-base font-semibold uppercase tracking-wide text-zinc-500">
Response
</p>
<p class="whitespace-pre-wrap">{selectedItem.response}</p>
</div>
{:else}
<p class="mb-4 text-zinc-500">No response yet.</p>
{/if}
{#if statusError}<p class="mb-3 text-red-600 dark:text-red-400" role="alert">{statusError}</p
>{/if}
<div class="flex gap-3 justify-end">
<button
type="button"
class={btnMuted}
onclick={() => openStatusItem(selectedItem!.id)}
disabled={statusLoading}
>
{statusLoading ? "Refreshing…" : "Refresh"}
</button>
<button type="button" class={btnPrimary} onclick={onClose}>Close</button>
</div>
{:else}
<div class="flex items-start justify-between gap-3 mb-3">
<h2 id="feedback-modal-title" class="text-xl font-bold">My feedback</h2>
<button
type="button"
class="{btnMuted} text-base! px-3! py-1.5!"
onclick={() => void loadStatusList()}
disabled={statusLoading}
>
{statusLoading ? "…" : "Refresh"}
</button>
</div>
{#if statusError}<p class="mb-3 text-red-600 dark:text-red-400" role="alert">{statusError}</p
>{/if}
{#if statusLoading && !statusItems.length}
<div class="feedback-loading" aria-busy="true" aria-live="polite">
<Spinner size="md" />
<p class="text-zinc-500">Checking your feedback…</p>
<div class="feedback-loading__skeleton" aria-hidden="true">
<span></span>
<span></span>
<span></span>
</div>
</div>
{:else if !statusItems.length}
<p class="mb-4 text-zinc-500">No feedback yet.</p>
<button type="button" class={btnPrimary} onclick={() => selectTab("send")}
>Send feedback</button
>
{:else}
<ul class="flex flex-col gap-2 mb-4">
{#each statusItems as item (item.id)}
<li>
<button
type="button"
onclick={() => openStatusItem(item.id)}
class="w-full p-3 text-left rounded-lg border transition-all duration-200 hover:scale-[1.01] focus:outline-hidden focus:ring-2 focus:ring-zinc-400 {isDark
? 'border-zinc-700 bg-zinc-900/40'
: 'border-zinc-200 bg-white'}"
>
<p class="text-base text-zinc-500 mb-0.5">
{formatStatus(item.status)}{#if hasReply(item)} · Reply{/if} · {categoryLabel(
item.category,
)}
</p>
<p class="font-medium truncate">{item.subject || "Untitled"}</p>
</button>
</li>
{/each}
</ul>
{/if}
<div class="flex justify-end">
<button type="button" class={btnMuted} onclick={onClose}>Close</button>
</div>
{/if}
</div>
</div>
</div>
</div>
<style>
.feedback-overlay {
-webkit-overflow-scrolling: touch;
}
.feedback-overlay__backdrop:disabled {
cursor: default;
}
.feedback-dialog {
display: flex;
flex-direction: column;
min-height: 0;
overflow: hidden;
}
.feedback-panel__body {
flex: 1 1 auto;
min-height: 0;
-webkit-overflow-scrolling: touch;
}
.feedback-tabs {
flex-shrink: 0;
}
.feedback-tab {
border: none;
cursor: pointer;
line-height: 1.2;
}
.feedback-loading {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 0.75rem;
min-height: 14rem;
padding: 1rem 0 1.5rem;
}
.feedback-loading__skeleton {
display: flex;
flex-direction: column;
gap: 0.5rem;
width: 100%;
margin-top: 0.5rem;
}
.feedback-loading__skeleton span {
display: block;
height: 3.5rem;
border-radius: 0.5rem;
background: color-mix(in srgb, currentColor 8%, transparent);
animation: feedback-skeleton-pulse 1.2s ease-in-out infinite;
}
.feedback-loading__skeleton span:nth-child(2) {
animation-delay: 0.15s;
}
.feedback-loading__skeleton span:nth-child(3) {
animation-delay: 0.3s;
}
@keyframes feedback-skeleton-pulse {
0%,
100% {
opacity: 0.45;
}
50% {
opacity: 0.9;
}
}
:global(.feedback-field),
:global(.feedback-field option) {
-webkit-text-fill-color: currentColor !important;
caret-color: currentColor !important;
}
:global(.feedback-field::placeholder) {
-webkit-text-fill-color: #a1a1aa !important;
color: #a1a1aa !important;
opacity: 1;
}
</style>
@@ -1,147 +0,0 @@
<script lang="ts">
import { fade } from "svelte/transition";
import { onMount } from "svelte";
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
import { FONT_PRESETS, DEFAULT_FONT_ID, getFontPreset } from "@/seqta/ui/fonts/presets";
import {
applySelectedFont,
buildFontPreviewCss,
ensureFontPickerFontsLoaded,
} from "@/seqta/ui/fonts/Manager";
import { portal } from "@/interface/utils/portal";
import { syncPageThemeToElement } from "@/interface/utils/syncPageTheme";
import fontPickerStyles from "./fontPickerModal.css?inline";
let { hidePicker }: { hidePicker: () => void } = $props();
let rootEl = $state<HTMLElement | null>(null);
let selectedId = $state(getFontPreset($settingsState.selectedFont).id);
let styleEl: HTMLStyleElement | null = null;
function selectFont(id: string) {
selectedId = id;
settingsState.selectedFont = id;
applySelectedFont(id);
}
function resetToDefault() {
selectFont(DEFAULT_FONT_ID);
}
function handleBackdropClick(event: MouseEvent) {
if (event.target === event.currentTarget) hidePicker();
}
function syncTheme() {
if (rootEl) syncPageThemeToElement(rootEl);
}
onMount(() => {
void ensureFontPickerFontsLoaded();
styleEl = document.getElementById(
"betterseqta-font-picker-styles",
) as HTMLStyleElement | null;
if (!styleEl) {
styleEl = document.createElement("style");
styleEl.id = "betterseqta-font-picker-styles";
document.head.appendChild(styleEl);
}
styleEl.textContent = `${fontPickerStyles}\n${buildFontPreviewCss()}`;
syncTheme();
const themeObserver = new MutationObserver(() => syncTheme());
themeObserver.observe(document.documentElement, {
attributes: true,
attributeFilter: ["style", "class"],
});
const handleEscapeKey = (event: KeyboardEvent) => {
if (event.key === "Escape") hidePicker();
};
document.addEventListener("keydown", handleEscapeKey);
return () => {
themeObserver.disconnect();
document.removeEventListener("keydown", handleEscapeKey);
};
});
</script>
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
bind:this={rootEl}
use:portal={document.body}
class="bsplus-font-picker-overlay bsplus-font-picker-root"
onclick={handleBackdropClick}
onkeydown={(event) => {
if (event.key === "Enter" || event.key === " ") handleBackdropClick(event as unknown as MouseEvent);
}}
role="presentation"
transition:fade={{ duration: 200 }}
>
<div
class="bsplus-font-picker-dialog"
onclick={(event) => event.stopPropagation()}
onkeydown={(event) => event.stopPropagation()}
role="dialog"
tabindex="-1"
aria-modal="true"
aria-labelledby="font-picker-title"
>
<header class="bsplus-font-picker-header">
<div class="bsplus-font-picker-header-actions">
<button
type="button"
onclick={resetToDefault}
disabled={selectedId === DEFAULT_FONT_ID}
class="bsplus-font-picker-reset"
aria-label="Reset font to default"
>
Reset to default
</button>
<button
type="button"
onclick={hidePicker}
class="bsplus-font-picker-done"
aria-label="Close font picker"
>
Done
</button>
</div>
<div class="bsplus-font-picker-header-text">
<h2 id="font-picker-title" class="bsplus-font-picker-title">
Choose a font
</h2>
<p class="bsplus-font-picker-desc">
Choose a typeface for SEQTA Learn.
</p>
</div>
</header>
<div class="bsplus-font-picker-list">
{#each FONT_PRESETS as preset (preset.id)}
<button
type="button"
onclick={() => selectFont(preset.id)}
class="bsplus-font-picker-option {selectedId === preset.id ? 'is-selected' : ''}"
data-font-id={preset.id}
>
<div class="bsplus-font-picker-option-head">
<span
class="bsplus-font-picker-option-name"
style="font-family: {preset.stack} !important;"
>
{preset.name}
</span>
{#if selectedId === preset.id}
<span class="bsplus-font-picker-badge">Selected</span>
{/if}
</div>
</button>
{/each}
</div>
</div>
</div>
Loaded 100 of 660 files, more files were not shown because too many files have changed in this diff. Show more