refactor: modernise old code, fix svelte warnings and redo title bar badge

This commit is contained in:
Jones Jankovic committed 2026-11-02 17:29:12 +10:30
1 parent 941597f197
commit e2b1b6b81f
68 files changed
+785 -2152

No files matched your search

+1 -34
View File
@@ -1,41 +1,8 @@
import fs from "fs";
import fs from "node:fs";
import mime from "mime-types";
/**
* A Vite plugin designed to load files as base64 encoded data URLs.
* This plugin intercepts module imports that have a `?base64` query parameter
* appended to the file path. It then reads the targeted file, converts its content
* to a base64 string, and constructs a data URL which is then exported as the
* default export of a new JavaScript module.
*
* @example
* // To use this loader, import a file with ?base64 query:
* // import myImageBase64 from './path/to/myimage.png?base64';
* // myImageBase64 will then be a string like "data:image/png;base64,..."
*/
export const base64Loader = {
/**
* The name of the Vite plugin.
* @type {string}
*/
name: "base64-loader",
/**
* The core transformation function of the Vite plugin.
* It is called by Vite for modules that might need transformation. This function
* checks if the module ID includes the `?base64` query. If so, it reads the
* specified file, converts it to a base64 data URL, and returns a new
* JavaScript module that default exports this data URL.
*
* @param {any} _ The original code of the file. This parameter is unused by this loader.
* @param {string} id The ID of the module being transformed. This string typically
* contains the absolute file path and any query parameters
* (e.g., "/path/to/file.png?base64").
* @returns {string | null} If the module ID does not contain `?base64` query,
* it returns `null` to indicate no transformation.
* Otherwise, it returns a string of JavaScript code
* that default exports the base64 data URL of the file.
* For example: `export default 'data:image/png;base64,xxxx';`
*/
transform(_: any, id: string) {
const [filePath, query] = id.split("?");
if (query !== "base64") return null;
+2 -43
View File
@@ -1,46 +1,5 @@
import type { Browser, BuildTarget, Manifest } from "./types.ts";
import type { AnyCase } from "./utils.ts";
/**
* Packages a given manifest object with a specific target browser identifier.
* This function is typically used in multi-browser extension build processes
* to create a configuration object that pairs the manifest data with the browser
* it's intended for. The `AnyCase<Browser>` type for the browser parameter
* implies that browser names like 'chrome', 'firefox', etc., can be provided
* in various casings.
*
* @export
* @param {Manifest} manifest The core manifest data for the extension,
* compatible with `chrome.runtime.ManifestV3` as defined by the {@link Manifest} type.
* @param {AnyCase<Browser>} browser The target browser identifier (e.g., 'chrome', 'firefox', 'CHROME').
* Refers to the {@link Browser} type, allowing for flexible casing.
* @returns {BuildTarget} An object that pairs the `manifest` with its target `browser`.
* The structure is `{ manifest: Manifest; browser: AnyCase<Browser>; }`
* as defined by the {@link BuildTarget} type.
*/
export function createManifest(
manifest: Manifest,
browser: AnyCase<Browser>,
): BuildTarget {
return {
manifest,
browser,
};
}
/**
* Defines a base manifest object.
* This function is typically used to establish a common, shared foundation for an extension's manifest
* (compatible with `chrome.runtime.ManifestV3` as per the {@link Manifest} type).
* This base can then be extended or modified for different browsers or specific build configurations.
* For example, you might define core permissions and properties here, and then add
* browser-specific keys in subsequent steps.
*
* @export
* @param {Manifest} manifest The core manifest data to be used as a base.
* This should conform to the {@link Manifest} type structure.
* @returns {Manifest} The provided manifest object, intended to serve as a reusable base.
*/
export function createManifestBase(manifest: Manifest): Manifest {
return manifest;
export function createManifest(manifest: Manifest, browser: Browser): BuildTarget {
return { manifest, browser };
}
-44
View File
@@ -15,18 +15,6 @@ import { globSync } from "glob";
import semver from "semver";
import { execSync } from "node:child_process";
/**
* Determines the latest version string from a list of filenames that include version numbers.
* Filenames are expected to follow a pattern like `betterseqtaplus@3.4.5.1-chrome.zip`.
* This function handles potential 4-part versions (e.g., `3.4.5.1`) by trimming them
* to 3 parts (e.g., `3.4.5`) for comparison using the `semver` library. After identifying
* the latest semver-compatible version, it returns the original full version string
* (e.g., "3.4.5.1") that corresponds to this latest version.
*
* @param {string[]} files An array of filenames.
* @returns {string | null} The latest version string (e.g., "3.4.5.1") found among the files,
* or `null` if no valid version numbers are found or no files are provided.
*/
function getLatestVersion(files) {
console.log("Files passed to getLatestVersion:", files);
@@ -82,17 +70,6 @@ function getLatestVersion(files) {
return latestFullVersion;
}
/**
* Finds the path to the latest built ZIP file for a specific browser.
* It constructs a glob pattern based on the browser name (e.g., `dist/betterseqtaplus@*-*chrome.zip`),
* finds all matching files, and then uses `getLatestVersion` to identify the version string
* of the most recent file. Finally, it returns the full path to that specific file.
*
* @param {string} browser A string indicating the target browser (e.g., "chrome", "firefox").
* @returns {string | undefined} The filepath string to the latest ZIP file for the specified browser,
* or `undefined` if no matching file is found or if the latest version
* cannot be determined.
*/
function getLatestFiles(browser) {
const pattern = `dist/betterseqtaplus@*-*${browser}.zip`;
console.log("Glob pattern:", pattern);
@@ -118,14 +95,6 @@ function getLatestFiles(browser) {
return latestFile;
}
/**
* Creates a ZIP file of the project's source code, excluding specified development-related
* files and directories such as `node_modules`, `dist`, `.git`, etc.
* It uses the `7z` command-line tool to perform the archiving.
* The output filename is fixed as `dist/betterseqtaplus@latest-sources.zip`.
*
* @returns {string} The filename of the created ZIP file (e.g., `dist/betterseqtaplus@latest-sources.zip`).
*/
function zipSources() {
const zipFileName = `dist/betterseqtaplus@latest-sources.zip`;
@@ -151,19 +120,6 @@ function zipSources() {
return zipFileName;
}
/**
* Orchestrates the extension publishing process for the specified browsers.
* This function performs the following steps:
* 1. Calls `getLatestFiles` to find the latest built ZIP for Chrome if "chrome" is in `browsers`.
* 2. Calls `getLatestFiles` to find the latest built ZIP for Firefox if "firefox" is in `browsers`.
* 3. Calls `zipSources` to create a source code ZIP if "firefox" is in `browsers` (required for Mozilla Add-ons).
* 4. Validates that all required files were found and that at least one browser was specified. Exits if not.
* 5. Constructs the `publish-extension` command-line string with the appropriate arguments
* based on the found ZIP files for the specified browsers.
* 6. Executes the constructed `publish-extension` command.
*
* @param {string[]} browsers An array of browser strings (e.g., ["chrome", "firefox"]) for which to publish the extension.
*/
function runPublishCommand(browsers) {
const chromeZip = browsers.includes("chrome")
? getLatestFiles("chrome")
+2 -232
View File
@@ -1,240 +1,10 @@
import type { ManifestV3Export } from "@crxjs/vite-plugin";
import { type AnyCase, createEnum, ObjectValues } from "./utils.ts";
/**
* Enumerates supported JavaScript frameworks for project generation or configuration.
*/
export const FrameworkEnum = {
React: "React",
Vanilla: "Vanilla",
Preact: "Preact",
Lit: "Lit",
Svelte: "Svelte",
Vue: "Vue",
} as const;
/**
* Enumerates supported web browsers, typically for targeting builds or configurations.
*/
export const BrowserEnum = {
Chrome: "Chrome",
Brave: "Brave",
Opera: "Opera",
Edge: "Edge",
Firefox: "Firefox",
Safari: "Safari",
} as const;
/**
* @private
* Enumerates supported programming languages for project setup.
* This enum is not exported, suggesting it's for internal use within this module or related modules.
*/
const LanguageEnum = {
TypeScript: "TypeScript",
JavaScript: "JavaScript",
} as const;
/**
* Enumerates supported styling options or libraries.
*/
export const StyleEnum = {
Tailwind: "Tailwind",
} as const;
/**
* Enumerates supported package managers.
*/
export const PackageManagerEnum = {
Bun: "Bun",
PnPm: "PnPm",
Npm: "Npm",
Yarn: "Yarn",
} as const;
/**
* Defines the structure for browser-specific settings within a web extension manifest.
* This is particularly used for Firefox (gecko) extensions to specify properties like
* an extension ID, and minimum/maximum supported browser versions.
* The structure is based on common manifest extensions for Firefox.
* See: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/browser_specific_settings
* The link in the original code (// see: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/firefox-webext-browser/index.d.ts)
* also points to type definitions that include this structure.
*
* @property {object} [browser_specific_settings] - Container for browser-specific settings.
* @property {object} [browser_specific_settings.gecko] - Settings specific to Gecko-based browsers (e.g., Firefox).
* @property {string} [browser_specific_settings.gecko.id] - The unique identifier for the extension in Firefox.
* @property {string} [browser_specific_settings.gecko.strict_min_version] - The minimum version of Firefox the extension is compatible with.
* @property {string} [browser_specific_settings.gecko.strict_max_version] - The maximum version of Firefox the extension is compatible with.
*/
export type BrowserSpecificSettings = {
browser_specific_settings?: {
gecko?: {
id: string;
strict_min_version?: string;
strict_max_version?: string;
};
};
};
/**
* Represents the structure of a Chrome Manifest V3 file.
* This type is an alias for `ManifestV3Export` from the `@crxjs/vite-plugin`,
* which provides a comprehensive definition for Chrome extension manifests.
*/
export type Manifest = ManifestV3Export;
/** Alias for the `icons` property within a Chrome Manifest V3. */
export type ManifestIcons = chrome.runtime.ManifestIcons;
/** Alias for the `background` property within a Chrome Manifest V3. */
export type ManifestBackground = chrome.runtime.ManifestV3["background"];
/** Alias for the `content_scripts` property within a Chrome Manifest V3. */
export type ManifestContentScripts =
chrome.runtime.ManifestV3["content_scripts"];
/** Alias for the `web_accessible_resources` property within a Chrome Manifest V3. */
export type ManifestWebAccessibleResources =
chrome.runtime.ManifestV3["web_accessible_resources"];
/** Alias for the `commands` property within a Chrome Manifest V3. */
export type ManifestCommands = chrome.runtime.ManifestV3["commands"];
/** Alias for the `action` property (or `browser_action`/`page_action`) within a Chrome Manifest V3. */
export type ManifestAction = chrome.runtime.ManifestV3["action"];
/** Alias for the `permissions` property within a Chrome Manifest V3. */
export type ManifestPermissions = chrome.runtime.ManifestV3["permissions"];
/** Alias for the `options_ui` property within a Chrome Manifest V3. */
export type ManifestOptionsUI = chrome.runtime.ManifestV3["options_ui"];
/** Alias for the `chrome_url_overrides` property within a Chrome Manifest V3. */
export type ManifestURLOverrides =
chrome.runtime.ManifestV3["chrome_url_overrides"];
export type Browser = "chrome" | "brave" | "edge" | "firefox" | "opera" | "safari";
/**
* Creates a type that accepts a string literal `T` in either its capitalized or lowercase form.
* Useful for defining types that should be case-insensitive for specific known strings.
* @template T - A string literal type.
*/
export type BrowserName<T extends string> = Capitalize<T> | Lowercase<T>;
/**
* Creates a record type where both keys and values are derived from a string literal `T`,
* specifically using `BrowserName<T>` which allows for capitalized or lowercase forms.
* This could be used to define an object where, for example, keys are 'Chrome' or 'chrome'
* and values are also 'Chrome' or 'chrome'.
* @template T - A string literal type, typically representing a browser name.
*/
export type BrowserEnumType<T extends string> = {
[browser in BrowserName<T>]: BrowserName<T>;
};
/**
* Represents the target browser for a build, allowing for various casings of browser names
* (e.g., "chrome", "Chrome", "CHROME") through the `AnyCase<Browser>` utility type.
* `Browser` itself is a union of specific browser name strings (e.g., "Chrome" | "Firefox").
*/
export type BuildMode = AnyCase<Browser>;
/**
* Defines an object structure that pairs a web extension `Manifest`
* with its target `browser` (represented as `AnyCase<Browser>`).
* This is commonly used in build processes to manage configurations for different browsers.
*/
export type BuildTarget = {
manifest: Manifest;
browser: AnyCase<Browser>;
browser: Browser;
};
/**
* Defines the configuration options for a build process.
* @property {"build" | "serve"} [command] - The type of build command (e.g., 'build' for production, 'serve' for development).
* @property {AnyCase<Browser> | string | undefined} [mode] - The target build mode, typically a browser name (allowing various casings)
* or potentially other custom mode strings.
*/
export type BuildConfig = {
command?: "build" | "serve";
mode?: AnyCase<Browser> | string | undefined;
};
/**
* Defines the structure for repository information, commonly found in `package.json`.
* @property {string} type - The type of the repository (e.g., "git").
* @property {string} [url] - The URL of the repository.
* @property {Bugs} [bugs] - An object containing information about where to report bugs.
*/
export interface Repository {
type: string;
url?: string;
bugs?: Bugs;
}
/**
* Defines the structure for bug reporting information, often part of the `Repository` interface.
* @property {string} [url] - The URL of the issue tracker.
* @property {string} [email] - The email address for reporting bugs.
*/
export interface Bugs {
url?: string;
email?: string;
}
/**
* A string literal union type representing supported browser names, derived from the values of `BrowserEnum`.
* e.g., "Chrome" | "Firefox" | ...
*/
export type Browser = ObjectValues<typeof BrowserEnum>;
/**
* A constant intended to provide access to browser names, potentially in various casings.
* Its type `AnyCase<Browser>` suggests it can be used where case-insensitivity for browser names is needed.
* The `createEnum(BrowserEnum)` call aims to produce a representation of browser names from `BrowserEnum`.
* Note: `createEnum` from `lib/utils.ts` has a declared return type of `ObjectValues<T>` (a union of values),
* while its implementation uses `Object.values()` which returns an array. This constant will hold the
* runtime array value, but its JSDoc type refers to the more restrictive `AnyCase<Browser>` union type.
*/
export const Browser: AnyCase<Browser> = createEnum(BrowserEnum);
/**
* A string literal union type representing supported package managers, derived from the values of `PackageManagerEnum`.
* e.g., "Bun" | "PnPm" | "Npm" | "Yarn"
*/
export type PackageManager = ObjectValues<typeof PackageManagerEnum>;
/**
* A constant intended to provide access to package manager names, potentially in various casings.
* Its type `AnyCase<PackageManager>` suggests it can be used where case-insensitivity for package manager names is needed.
* Utilizes `createEnum(PackageManagerEnum)`. Refer to notes on `Browser` constant regarding `createEnum` behavior.
*/
export const PackageManager: AnyCase<PackageManager> =
createEnum(PackageManagerEnum);
/**
* A string literal union type representing supported JavaScript frameworks, derived from the values of `FrameworkEnum`.
* e.g., "React" | "Vanilla" | ...
*/
export type Framework = ObjectValues<typeof FrameworkEnum>;
/**
* A constant intended to provide access to framework names, potentially in various casings.
* Its type `AnyCase<Framework>` suggests it can be used where case-insensitivity for framework names is needed.
* Utilizes `createEnum(FrameworkEnum)`. Refer to notes on `Browser` constant regarding `createEnum` behavior.
*/
export const Framework: AnyCase<Framework> = createEnum(FrameworkEnum);
/**
* A string literal union type representing supported styling options, derived from the values of `StyleEnum`.
* e.g., "Tailwind"
*/
export type Style = ObjectValues<typeof StyleEnum>;
/**
* A constant intended to provide access to style option names, potentially in various casings.
* Its type `AnyCase<Style>` suggests it can be used where case-insensitivity for style names is needed.
* Utilizes `createEnum(StyleEnum)`. Refer to notes on `Browser` constant regarding `createEnum` behavior.
*/
export const Style: AnyCase<Style> = createEnum(StyleEnum);
/**
* A string literal union type representing supported programming languages, derived from the values of `LanguageEnum`.
* e.g., "TypeScript" | "JavaScript"
*/
export type Language = ObjectValues<typeof LanguageEnum>;
/**
* A constant intended to provide access to programming language names, potentially in various casings.
* Its type `AnyCase<Language>` suggests it can be used where case-insensitivity for language names is needed.
* Utilizes `createEnum(LanguageEnum)`. Refer to notes on `Browser` constant regarding `createEnum` behavior.
*/
export const Language: AnyCase<Language> = createEnum(LanguageEnum);
-84
View File
@@ -1,84 +0,0 @@
/**
* Extracts a union type of all values from the properties of an object type `T`.
*
* @template T - An object type (typically a Record or an enum-like object).
* @example
* type MyObject = { a: "foo", b: "bar", c: 123 };
* type MyObjectValues = ObjectValues<MyObject>; // "foo" | "bar" | 123
*/
export type ObjectValues<T> = T[keyof T];
/**
* Creates a union of an object's string values, often used to represent the set of possible values for an enum-like object.
* Note: The implementation `Object.values(enumObj) as unknown as ObjectValues<T>` returns an array at runtime,
* but the declared return type `ObjectValues<T>` is a union of the object's property values.
* This type signature suggests it's intended to represent the set of possible string values from `enumObj`.
*
* @template T - An object type where keys are strings and values are strings (e.g., `const MyEnum = { VAL_A: "A", VAL_B: "B" }`).
* @param {T} enumObj - The object from which to extract values.
* @returns {ObjectValues<T>} A union type representing all possible string values of the `enumObj`.
* For example, if `enumObj` is `{ A: "valA", B: "valB" }`, the return type is `"valA" | "valB"`.
* (Runtime behavior of `Object.values()` is to return an array like `["valA", "valB"]`).
*/
export function createEnum<T extends Record<string, string>>(enumObj: T) {
return Object.values(enumObj) as unknown as ObjectValues<T>;
}
/**
* Creates a union type that includes various case formats (uppercase, lowercase, capitalized, uncapitalized)
* of a given string literal type `T`.
*
* @template T - A string literal type.
* @example
* type MyString = "example";
* type MyStringAnyCase = AnyCase<MyString>; // "EXAMPLE" | "example" | "Example" | "example" (Uncapitalize<"Example"> is "example")
*/
export type AnyCase<T extends string> =
| Uppercase<T>
| Lowercase<T>
| Capitalize<T>
| Uncapitalize<T>;
/**
* Creates a union type that includes various case formats (uppercase, lowercase, capitalized, uncapitalized)
* of the union of two given string literal types `T` and `K`.
* This is useful for representing a combined set of related string constants where case variations are permitted for each.
*
* @template T - A string literal type.
* @template K - Another string literal type.
* @example
* type Lang1 = "english";
* type Lang2 = "french";
* type CombinedLangsAnyCase = AnyCaseLanguage<Lang1, Lang2>;
* // Result includes: "ENGLISH" | "english" | "English" | "FRENCH" | "french" | "French" etc.
* // for all case variations of "english" and "french".
*/
export type AnyCaseLanguage<T extends string, K extends string> =
| Uppercase<T | K>
| Lowercase<T | K>
| Capitalize<T | K>
| Uncapitalize<T | K>;
/**
* Extracts a new object type containing only the keys of `T` whose properties are optional
* (i.e., their type includes `undefined`). The values associated with these keys retain their original types.
*
* @template T - An object type.
* @example
* type MyObject = {
* requiredProp: string;
* optionalProp?: number;
* anotherOptional?: boolean | undefined;
* nullProp: string | null;
* };
* type MyOptionalProps = OptionalKeys<MyObject>;
* // MyOptionalProps would be conceptually equivalent to:
* // {
* // optionalProp?: number;
* // anotherOptional?: boolean | undefined;
* // }
* // The actual resulting type is an object type with only these optional keys.
*/
export type OptionalKeys<T> = {
[K in keyof T as undefined extends T[K] ? K : never]: T[K];
};
+1 -1
View File
@@ -45,7 +45,7 @@ function registerFetchSeqtaAppLinkListener() {
});
}
var IsSEQTAPage = false;
let IsSEQTAPage = false;
let hasSEQTAText = false;
// This check is placed outside of the document load event due to issues with EP (https://github.com/BetterSEQTA/BetterSEQTA-Plus/issues/84)
+1 -1
View File
@@ -449,7 +449,7 @@ function onStorageChanged(
): void {
if (area !== "local") return;
if (Object.prototype.hasOwnProperty.call(changes, "autoCloudSettingsSync")) {
if (Object.hasOwn(changes, "autoCloudSettingsSync")) {
void syncAutoUploadWithStorage();
}
-38
View File
@@ -2,19 +2,6 @@ import Parser from "rss-parser";
const MAX_RATE_LIMIT_RETRIES = 3;
/**
* Fetches news articles specifically for Australia from the NewsAPI.
*
* This function handles a specific case for fetching Australian news. It includes a
* mechanism to retry the fetch operation by appending "%00" to the URL if a
* rate limit error (`response.code == "rateLimited"`) is encountered. This is
* likely a workaround for cache-busting or bypassing certain rate-limiting measures.
*
* @param {string} url The NewsAPI URL to fetch Australian news from.
* @param {any} sendResponse A callback function (likely from a browser extension message listener)
* to send the fetched news data back to the caller.
* It's called with an object like `{ news: responseData }`.
*/
const fetchAustraliaNews = async (
url: string,
sendResponse: any,
@@ -35,12 +22,6 @@ const fetchAustraliaNews = async (
});
};
/**
* A record mapping lowercase country codes (e.g., "usa", "canada") to an array
* of RSS feed URLs for news sources in that country.
*
* @type {Record<string, string[]>}
*/
const rssFeedsByCountry: Record<string, string[]> = {
usa: [
"https://rss.nytimes.com/services/xml/rss/nyt/HomePage.xml",
@@ -83,25 +64,6 @@ const rssFeedsByCountry: Record<string, string[]> = {
netherlands: ["https://www.dutchnews.nl/feed/", "https://www.nrc.nl/rss/"],
};
/**
* Fetches news articles based on a specified source.
*
* The source can be:
* 1. The string "australia": Fetches news from Australian sources via NewsAPI,
* handled by the `fetchAustraliaNews` function.
* 2. A lowercase country code (e.g., "usa", "canada"): Fetches news from a predefined
* list of RSS feeds for that country, as specified in `rssFeedsByCountry`.
* 3. A direct RSS feed URL (starting with "http"): Fetches news directly from this URL.
*
* The fetched articles are then sent back to the caller using the `sendResponse` callback.
*
* @param {string} source The news source identifier. This can be "australia", a
* lowercase country code, or a direct RSS feed URL.
* @param {any} sendResponse A callback function (typically from a browser extension
* message listener, like `chrome.runtime.onMessage`)
* used to send the fetched news data back to the caller.
* It's called with an object like `{ news: { articles: [...] } }`.
*/
export async function fetchNews(source: string | undefined, sendResponse: any) {
const normalizedSource = typeof source === "string" && source.trim()
? source.trim()
-5
View File
@@ -110,11 +110,6 @@ html {
transform-origin: top;
transition: transform 0.2s;
}
body:has(.outside-container:not(.hide))
#AddedSettings.tooltip:hover
> .tooltiptext {
transform: scale(0);
}
.assessmenttooltip svg {
fill: var(--text-primary);
}
+46 -96
View File
@@ -251,6 +251,8 @@ html:not(.dark) .legacy-root {
color: var(--theme-primary) !important;
height: 35px;
width: 35px !important;
padding: 0;
box-shadow: none;
}
/* Engage toolbar: keep settings/theme buttons above React chrome */
@@ -3870,130 +3872,78 @@ div.day-empty {
display: grid;
grid-template-areas:
"house name"
"badge code";
". code";
align-items: center;
justify-items: end;
column-gap: 10px;
row-gap: 2px;
}
.userInfoHouseWrap,
.userInfoDetails {
display: contents;
}
.userInfoDetails > .userInfoCode {
grid-area: code;
}
.userInfoNameRow .userInfohouse {
.userInfoHouseWrap,
.userInfoNameRow > .bsplus-founder-badge-slot {
grid-area: house;
justify-self: stretch;
display: flex;
align-items: center;
gap: 6px;
}
.userInfoNameRow .bsplus-founder-badge-slot {
grid-area: badge;
justify-self: stretch;
box-sizing: border-box;
}
.bsplus-founder-badge-carousel {
.bsplus-founder-badge-slot {
display: grid;
width: 100%;
max-width: 100%;
box-sizing: border-box;
justify-items: end;
order: -1;
}
.bsplus-founder-badge-carousel > .bsplus-founder-badge {
.bsplus-founder-badge-slot[hidden] {
display: none !important;
}
.titlebar .bsplus-titlebar-badge {
grid-area: 1 / 1;
width: 100%;
min-width: 0;
height: auto;
min-height: 0;
margin: 0;
padding: 2px 8px;
border: none;
border-radius: 6px;
box-shadow: none;
background:
radial-gradient(ellipse 72% 68% at 18% 42%, var(--badge-blob-a), transparent 72%),
radial-gradient(ellipse 68% 62% at 82% 58%, var(--badge-blob-b), transparent 70%),
radial-gradient(ellipse 64% 56% at 50% 88%, var(--badge-blob-c), transparent 68%),
var(--badge-base);
color: #fff;
font-family: inherit;
font-size: 14px;
font-weight: 600;
line-height: 1.3;
text-align: center;
white-space: nowrap;
cursor: pointer;
transition:
opacity 0.45s ease,
visibility 0s;
}
.titlebar .bsplus-titlebar-badge[aria-hidden="true"] {
opacity: 0;
visibility: hidden;
transform: translateY(5px);
transition:
opacity 0.45s ease,
transform 0.45s ease,
visibility 0s linear 0.45s;
pointer-events: none;
}
.bsplus-founder-badge-carousel > .bsplus-founder-badge--active {
opacity: 1;
visibility: visible;
transform: translateY(0);
transition:
opacity 0.45s ease,
transform 0.45s ease,
visibility 0s;
pointer-events: auto;
z-index: 1;
.titlebar .bsplus-titlebar-badge:focus-visible {
outline: 2px solid var(--theme-primary);
outline-offset: 2px;
}
.bsplus-founder-badge-carousel--static > .bsplus-founder-badge {
transition: none;
transform: none;
visibility: hidden;
}
.bsplus-founder-badge-carousel--static > .bsplus-founder-badge--active {
visibility: visible;
.bsplus-founder-badge-slot--static .bsplus-titlebar-badge {
transition: none !important;
}
@media (prefers-reduced-motion: reduce) {
.bsplus-founder-badge-carousel > .bsplus-founder-badge {
.titlebar .bsplus-titlebar-badge {
transition: none;
transform: none;
}
}
.userInfoHouseWrap .bsplus-founder-badge-slot[hidden],
.bsplus-founder-badge-slot[hidden] {
display: none;
}
.bsplus-founder-badge--titlebar {
display: block;
width: 100%;
border-radius: 5px;
overflow: hidden;
}
.bsplus-founder-badge--titlebar .bsplus-founder-badge__glass {
display: flex;
width: 100%;
border-radius: 5px;
box-sizing: border-box;
box-shadow:
inset 0 0 0 1px rgba(255, 255, 255, 0.22),
inset 0 1px 0 rgba(255, 255, 255, 0.12);
}
.bsplus-founder-badge--titlebar .bsplus-founder-badge__content {
display: flex;
flex: 1 1 auto;
width: 100%;
justify-content: center;
padding: 0 6px;
gap: 0;
min-height: 0;
min-width: 0;
height: auto;
font-size: 15px;
line-height: normal;
border-radius: 5px;
box-sizing: border-box;
backdrop-filter: none;
-webkit-backdrop-filter: none;
background: rgba(255, 255, 255, 0.1);
box-shadow: none;
}
.bsplus-founder-badge--titlebar .bsplus-founder-badge__label {
display: block;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
text-align: center;
}
.bsplus-founder-badge--titlebar:hover {
transform: none;
}
.bsplus-founder-badge--titlebar:focus-visible {
outline: none;
}
.bsplus-founder-badge--titlebar:focus-visible .bsplus-founder-badge__glass {
box-shadow:
inset 0 0 0 1px rgba(255, 255, 255, 0.22),
inset 0 1px 0 rgba(255, 255, 255, 0.12),
0 0 0 2px var(--theme-primary, #f97316),
0 0 0 4px rgba(249, 115, 22, 0.35);
}
.legacy-root .bsplus-founder-badge,
.legacy-root .bsplus-founder-badge-actions .bsplus-cal-btn {
background: transparent !important;
@@ -30,7 +30,7 @@
initialFeedbackId?: string | null;
}>();
let tab = $state<"send" | "status">(
let tab = $derived<"send" | "status">(
typeof initialFeedbackId === "string" && initialFeedbackId ? "status" : "send",
);
let category = $state<FeedbackCategory>("bug");
@@ -87,6 +87,7 @@
onclick={(event) => event.stopPropagation()}
onkeydown={(event) => event.stopPropagation()}
role="dialog"
tabindex="-1"
aria-modal="true"
aria-labelledby="font-picker-title"
>
+1 -1
View File
@@ -5,7 +5,7 @@
options: Array<{ value: string, label: string }>
}>();
const listboxId = `select-listbox-${Math.random().toString(36).slice(2, 9)}`;
const listboxId = $props.id();
let isOpen = $state(false);
let activeIndex = $state(0);
@@ -1,57 +0,0 @@
<script lang="ts">
import { createEventDispatcher } from 'svelte';
let dispatch = createEventDispatcher();
let filters = $state({
type: [] as string[],
color: [] as string[],
resolution: [] as string[],
orientation: [] as string[]
});
$effect(() => {
dispatch('filter', filters);
});
function toggleFilter(category: keyof typeof filters, value: string) {
if (filters[category].includes(value)) {
filters[category] = filters[category].filter(v => v !== value);
} else {
filters[category] = [...filters[category], value];
}
}
function clearFilters() {
filters = {
type: [],
color: [],
resolution: [],
orientation: []
};
}
</script>
<div class="p-4 bg-white rounded-lg shadow-sm dark:bg-gray-800">
<h2 class="mb-4 text-xl font-semibold">Filters</h2>
<div class="mb-4">
<h3 class="mb-2 font-medium">Type</h3>
<div class="space-y-2">
<label class="flex items-center">
<input type="checkbox" checked={filters.type.includes('image')} onchange={() => toggleFilter('type', 'image')}>
<span class="ml-2">Image</span>
</label>
<label class="flex items-center">
<input type="checkbox" checked={filters.type.includes('video')} onchange={() => toggleFilter('type', 'video')}>
<span class="ml-2">Video</span>
</label>
</div>
</div>
<button
class="px-4 py-2 mt-4 text-white bg-red-500 rounded-sm hover:bg-red-600"
onclick={clearFilters}
>
Clear Filters
</button>
</div>
-16
View File
@@ -12,10 +12,6 @@ class BackgroundUpdates {
private constructor() {}
/**
* Gets the singleton instance of the BackgroundUpdates class.
* @returns {BackgroundUpdates} The singleton instance.
*/
public static getInstance(): BackgroundUpdates {
if (!BackgroundUpdates.instance) {
BackgroundUpdates.instance = new BackgroundUpdates();
@@ -23,22 +19,10 @@ class BackgroundUpdates {
return BackgroundUpdates.instance;
}
/**
* Registers a callback function to be invoked when a background update is triggered.
*
* @param {BackgroundUpdateCallback} callback The function to call when a background update occurs.
* This callback takes no arguments and returns void.
*/
public addListener(callback: BackgroundUpdateCallback): void {
this.listeners.add(callback);
}
/**
* Unregisters a previously added callback function.
* After calling this method, the provided callback will no longer be invoked when a background update is triggered.
*
* @param {BackgroundUpdateCallback} callback The callback function to remove from the listeners.
*/
public removeListener(callback: BackgroundUpdateCallback): void {
this.listeners.delete(callback);
}
-16
View File
@@ -12,10 +12,6 @@ class ThemeUpdates {
private constructor() {}
/**
* Gets the singleton instance of the ThemeUpdates class.
* @returns {ThemeUpdates} The singleton instance.
*/
public static getInstance(): ThemeUpdates {
if (!ThemeUpdates.instance) {
ThemeUpdates.instance = new ThemeUpdates();
@@ -23,22 +19,10 @@ class ThemeUpdates {
return ThemeUpdates.instance;
}
/**
* Registers a callback function to be invoked when a theme update is triggered.
*
* @param {ThemeUpdateCallback} callback The function to call when a theme update occurs.
* This callback takes no arguments and returns void.
*/
public addListener(callback: ThemeUpdateCallback): void {
this.listeners.add(callback);
}
/**
* Unregisters a previously added callback function.
* After calling this method, the provided callback will no longer be invoked when a theme update is triggered.
*
* @param {ThemeUpdateCallback} callback The callback function to remove from the listeners.
*/
public removeListener(callback: ThemeUpdateCallback): void {
this.listeners.delete(callback);
}
+2 -3
View File
@@ -1,5 +1,4 @@
import { mount } from "svelte";
import type { SvelteComponent } from "svelte";
import { mount, type Component } from "svelte";
import settingsStyle from "./index.css?inline";
import contentShadowStyle from "./contentShadow.css?inline";
@@ -12,7 +11,7 @@ const shadowStyles = {
export type ShadowStyleVariant = keyof typeof shadowStyles;
export default function renderSvelte(
Component: SvelteComponent | any,
Component: Component<any>,
mountPoint: ShadowRoot | HTMLElement,
props: Record<string, any> = {},
shadowStyle: ShadowStyleVariant = "settings",
@@ -1,4 +1,5 @@
<script lang="ts">
import { delay } from "@/seqta/utils/delay";
import Switch from "@/interface/components/Switch.svelte";
import Button from "@/interface/components/Button.svelte";
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
@@ -151,7 +152,7 @@
settingsState.privacyStatementShown = false;
settingsState.privacyStatementLastUpdated = undefined;
closeExtensionPopup();
await new Promise((resolve) => setTimeout(resolve, 100));
await delay(100);
await openTermsOfServicePopup(undefined, { force: true });
}}
text="Show Now"
@@ -169,7 +170,7 @@
<Button
onClick={async () => {
closeExtensionPopup();
await new Promise((resolve) => setTimeout(resolve, 100));
await delay(100);
await showThemeOfTheMonthPopupNow();
}}
text="Show Now"
+4 -10
View File
@@ -152,13 +152,7 @@
}
async function prepareThemeClone() {
const themeClone = JSON.parse(JSON.stringify(theme)) as LoadedCustomTheme;
themeClone.CustomImages = theme.CustomImages.map((image) => ({
...image,
blob: image.blob,
}));
themeClone.coverImage = theme.coverImage;
const themeClone = $state.snapshot(theme) as LoadedCustomTheme;
themeClone.userEdited = true;
if (shouldForceThemeAppearance(themeClone)) {
@@ -223,10 +217,10 @@
};
});
async function onImageUpload(event: Event) {
const updated = await handleImageUpload(event, theme);
function onImageUpload(event: Event) {
const updated = handleImageUpload(event, theme);
if (updated === theme) return;
theme = updated as LoadedCustomTheme;
theme = updated;
if (!creatorMeta.pageBackgroundImageId && theme.CustomImages.length === 1) {
creatorMeta = { ...creatorMeta, pageBackgroundImageId: theme.CustomImages[0].id };
}
+1 -2
View File
@@ -1,4 +1,3 @@
import { generateImageId } from "@/interface/utils/themeImageHandlers";
import { DEFAULT_FONT_ID, getFontPreset, type FontPreset } from "@/seqta/ui/fonts/presets";
import type { LoadedCustomTheme } from "@/types/CustomThemes";
@@ -115,7 +114,7 @@ export function buildThemeFromDraft(draft: ThemeBuilderDraft): LoadedCustomTheme
const font = getFontPreset(draft.fontId ?? DEFAULT_FONT_ID);
const photoBlobs = draft.photoBlobs.filter((blob) => blob.size > 0);
const CustomImages = photoBlobs.map((blob, index) => ({
id: generateImageId(),
id: crypto.randomUUID(),
blob,
variableName: `theme-bg-${index}`,
}));
+16 -80
View File
@@ -1,60 +1,27 @@
import type { LoadedCustomTheme } from "@/types/CustomThemes";
/**
* Generates a random 9-character alphanumeric string to be used as a unique ID for images.
* This helps in identifying and managing custom images within a theme.
*
* @returns {string} A randomly generated unique ID string.
*/
export function generateImageId(): string {
return Math.random().toString(36).substr(2, 9);
}
/**
* Handles the upload of a new custom image from a file input event.
* If a file is selected, it generates a unique ID and a default variable name for it, and then adds this new image
* to the `CustomImages` array within the provided `theme` object.
*
* @param {Event} event The file input change event, typically from an `<input type="file">` element.
* @param {LoadedCustomTheme} theme The current theme object to which the new image will be added.
* @returns {Promise<LoadedCustomTheme> | LoadedCustomTheme} A Promise that resolves with the updated theme object
* containing the new image if a file was processed.
* Returns the original theme object synchronously if no file was selected.
*/
export function handleImageUpload(
event: Event,
theme: LoadedCustomTheme,
): Promise<LoadedCustomTheme> | LoadedCustomTheme {
): LoadedCustomTheme {
const input = event.target as HTMLInputElement;
const file = input.files?.[0];
input.value = "";
if (file) {
return Promise.resolve({
...theme,
CustomImages: [
...theme.CustomImages,
{
id: generateImageId(),
blob: file,
variableName: `custom-image-${theme.CustomImages.length}`,
url: null,
},
],
});
}
return theme;
if (!file) return theme;
return {
...theme,
CustomImages: [
...theme.CustomImages,
{
id: crypto.randomUUID(),
blob: file,
variableName: `custom-image-${theme.CustomImages.length}`,
url: null,
},
],
};
}
/**
* Removes a custom image from the theme based on its ID.
* It filters out the image with the specified `imageId` from the `CustomImages` array
* in the `theme` object.
*
* @param {string} imageId The unique ID of the custom image to be removed.
* @param {LoadedCustomTheme} theme The current theme object from which the image will be removed.
* @returns {LoadedCustomTheme} A new theme object with the specified image removed from its `CustomImages` array.
* This function is synchronous.
*/
export function handleRemoveImage(
imageId: string,
theme: LoadedCustomTheme,
@@ -62,20 +29,9 @@ export function handleRemoveImage(
return {
...theme,
CustomImages: theme.CustomImages.filter((image) => image.id !== imageId),
} as LoadedCustomTheme;
};
}
/**
* Updates the CSS variable name associated with a specific custom image in the theme.
* It finds the image by `imageId` in the `CustomImages` array of the `theme` object
* and updates its `variableName` property.
*
* @param {string} imageId The unique ID of the custom image whose variable name is to be updated.
* @param {string} variableName The new CSS variable name to assign to the image.
* @param {LoadedCustomTheme} theme The current theme object containing the image to be updated.
* @returns {LoadedCustomTheme} A new theme object with the updated image variable name.
* This function is synchronous.
*/
export function handleImageVariableChange(
imageId: string,
variableName: string,
@@ -86,25 +42,5 @@ export function handleImageVariableChange(
CustomImages: theme.CustomImages.map((image) =>
image.id === imageId ? { ...image, variableName } : image,
),
} as LoadedCustomTheme;
}
/**
* Handles the upload of a cover image for the theme from a file input event.
* If a file is selected, it updates the `coverImage` property of the provided `theme` object with the file.
*
* @param {Event} event The file input change event, typically from an `<input type="file">` element.
* @param {LoadedCustomTheme} theme The current theme object whose cover image will be updated.
* @returns {Promise<LoadedCustomTheme>} A Promise that resolves with the updated theme object
* containing the new cover image if a file was processed.
* Returns a Promise resolving with the original theme object if no file was selected.
*/
export function handleCoverImageUpload(
event: Event,
theme: LoadedCustomTheme,
): Promise<LoadedCustomTheme> {
const input = event.target as HTMLInputElement;
const file = input.files?.[0];
input.value = "";
return Promise.resolve(file ? { ...theme, coverImage: file } : theme);
};
}
+1 -5
View File
@@ -555,11 +555,7 @@ function sanitizeResponseForPostMessage(response) {
}
try {
if (typeof structuredClone === "function") {
structuredClone(response);
} else {
JSON.parse(JSON.stringify(response));
}
structuredClone(response);
} catch (cloneError) {
console.warn("[pageState] Response not cloneable, fallback:", cloneError.message);
return `[Uncloneable Response: ${cloneError.message}]`;
@@ -271,48 +271,17 @@ async function copyRubricTable(rubric: Element, button: HTMLButtonElement) {
if (!table) return;
const plain = rubricToPlainText(table);
const htmlTable = rubricToHtmlTable(table);
const htmlDocument = rubricToHtmlDocument(table);
let copied = false;
if (navigator.clipboard?.write && typeof ClipboardItem !== "undefined") {
try {
await navigator.clipboard.write([
new ClipboardItem({
"text/plain": new Blob([plain], { type: "text/plain" }),
"text/html": new Blob([htmlDocument], { type: "text/html" }),
}),
]);
copied = true;
} catch {
// Fall through to legacy rich-text copy.
}
}
if (!copied) {
const host = document.createElement("div");
host.contentEditable = "true";
host.innerHTML = htmlTable;
host.style.position = "fixed";
host.style.left = "-9999px";
host.style.top = "0";
document.body.appendChild(host);
const selection = window.getSelection();
const range = document.createRange();
range.selectNodeContents(host);
selection?.removeAllRanges();
selection?.addRange(range);
copied = document.execCommand("copy");
selection?.removeAllRanges();
host.remove();
if (!copied) {
await navigator.clipboard.writeText(plain);
}
try {
await navigator.clipboard.write([
new ClipboardItem({
"text/plain": new Blob([plain], { type: "text/plain" }),
"text/html": new Blob([htmlDocument], { type: "text/html" }),
}),
]);
} catch {
await navigator.clipboard.writeText(plain);
}
const label = button.querySelector(".betterseqta-rubric-copy-label");
@@ -12,6 +12,7 @@ import {
} from "@/lib/pdfjsExtension.ts";
import * as pdfjs from "pdfjs-dist";
import { extractWeightFromCoversheetText } from "./extractWeightFromCoversheetText";
import { delay } from "@/seqta/utils/delay";
export { extractWeightFromCoversheetText };
@@ -434,7 +435,7 @@ function createWeightLabel(
}
export const isFirefox =
navigator.userAgent.toLowerCase().indexOf("firefox") > -1 &&
navigator.userAgent.toLowerCase().includes("firefox") &&
!navigator.userAgent.toLowerCase().includes("seamonkey") &&
!navigator.userAgent.toLowerCase().includes("waterfox");
@@ -751,7 +752,7 @@ async function extractPDFTextWithRetry(
message.includes("empty") ||
message.includes("Failed to fetch PDF");
if (!retryable || attempt === attempts - 1) throw error;
await new Promise((resolve) => setTimeout(resolve, delayMs));
await delay(delayMs);
}
}
throw lastError;
@@ -830,7 +831,7 @@ async function handleWeightings(mark: any, api: any) {
metaclassID,
studentID,
});
await new Promise((resolve) => setTimeout(resolve, 1000));
await delay(1000);
pdfUrl = getEngageAssessmentReportUrl(reportFile);
} else {
const userInfo = await getUserInfo();
@@ -841,7 +842,7 @@ async function handleWeightings(mark: any, api: any) {
metaclassID,
studentID: userID,
});
await new Promise((resolve) => setTimeout(resolve, 1000));
await delay(1000);
pdfUrl = getStudentAssessmentReportUrl(reportFile);
}
@@ -860,7 +861,7 @@ async function handleWeightings(mark: any, api: any) {
error?.message?.includes("CSP") ||
error?.message?.includes("empty"))
) {
await new Promise((resolve) => setTimeout(resolve, 2000));
await delay(2000);
text = await extractPDFTextWithRetry(pdfUrl, 2, 2000);
} else {
throw new Error(`PDF extraction failed: ${error.message}`, { cause: error });
@@ -5,6 +5,7 @@
formatDate,
getDisplayGrade,
getThermoscorePercent,
readStoredList,
} from "./utils";
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
import { isSeqtaEngageExperience } from "@/seqta/utils/isSeqtaEngage";
@@ -17,7 +18,7 @@
} from "./icons";
import confetti from "canvas-confetti";
export let data: any;
let { data }: { data: any } = $props();
interface FilterOptions {
subject: string;
@@ -25,7 +26,73 @@
sortBy: "due" | "grade" | "subject" | "title" | "year";
}
type Column = {
key: string;
title: string;
className: string;
icon: OverviewIconName;
};
const HIDDEN_ASSESSMENTS_KEY = "betterseqta-hidden-assessments";
const COMPLETED_ASSESSMENTS_KEY = "betterseqta-completed-assessments";
const STATUS_COLUMNS: Column[] = [
{ key: "UPCOMING", title: "Upcoming", className: "column-upcoming", icon: "calendar-days" },
{ key: "DUE_SOON", title: "Due Soon", className: "column-due-soon", icon: "clock" },
{ key: "OVERDUE", title: "Overdue", className: "column-overdue", icon: "exclamation-triangle" },
{ key: "SUBMITTED", title: "Submitted", className: "column-submitted", icon: "document-check" },
{ key: "MARKS_RELEASED", title: "Marked", className: "column-marked", icon: "check-circle" },
];
const isEngage = isSeqtaEngageExperience();
let currentFilters = $state<FilterOptions>({
subject: "all",
student: "all",
sortBy: "due",
});
let subjectFilters = $state<Record<string, boolean>>(initSubjectFilters());
let hiddenIds = $state(readStoredList(HIDDEN_ASSESSMENTS_KEY).map(String));
let completedIds = $state(readStoredList(COMPLETED_ASSESSMENTS_KEY));
let openMenuId = $state<string | null>(null);
let showVisibilityPanel = $state(false);
const showStudentFilter = $derived(isEngage && (data?.students?.length ?? 0) > 1);
const board = $derived(buildGroupsAndColumns());
const hiddenSubjects = $derived(
data?.subjects?.filter((s: any) => subjectFilters[s.code] === false) ?? [],
);
const hiddenAssessmentsWithInfo = $derived(
data?.assessments?.filter((a: any) => hiddenIds.includes(String(a.id))) ?? [],
);
const hasHiddenItems = $derived(
hiddenSubjects.length > 0 || hiddenAssessmentsWithInfo.length > 0,
);
function initSubjectFilters(): Record<string, boolean> {
const filters = { ...(settingsState.subjectfilters || {}) };
const missing = (data?.subjects ?? []).filter((s: any) => !Object.hasOwn(filters, s.code));
if (missing.length) {
for (const s of missing) filters[s.code] = true;
settingsState.subjectfilters = filters;
}
return filters;
}
function setSubjectVisible(subjectCode: string, visible: boolean) {
subjectFilters[subjectCode] = visible;
settingsState.subjectfilters = $state.snapshot(subjectFilters);
}
function saveHiddenIds(ids: string[]) {
hiddenIds = ids;
localStorage.setItem(HIDDEN_ASSESSMENTS_KEY, JSON.stringify(ids));
}
function saveCompletedIds(ids: unknown[]) {
completedIds = ids;
localStorage.setItem(COMPLETED_ASSESSMENTS_KEY, JSON.stringify(ids));
}
function isLetterGradeMode(): boolean {
const allSettings = settingsState.getAll() as unknown as Record<
@@ -35,52 +102,29 @@
return allSettings["plugin.assessments-average.settings"]?.lettergrade ?? false;
}
let currentFilters: FilterOptions = {
subject: "all",
student: "all",
sortBy: "due",
};
const isEngage = isSeqtaEngageExperience();
$: showStudentFilter = isEngage && (data?.students?.length ?? 0) > 1;
let filteredAssessments: any[] = [];
let statusGroups: Record<string, any[]> = {};
let columns: {
key: string;
title: string;
className: string;
icon: OverviewIconName;
}[] = [];
function statusOf(assessment: any): string {
return determineStatus(assessment, completedIds);
}
function getAssessmentYear(a: any): number {
const dateStr = a.due || a.date || a.dueDate || a.created;
return dateStr ? new Date(dateStr).getFullYear() : 0;
}
function getAssessmentType(a: any): string {
return (a.type || a.assessmentType || a.taskType || "Other").toString();
}
function getAssessmentGrade(a: any): string {
return getDisplayGrade(a, isLetterGradeMode());
}
function getGroupKey(assessment: any): string {
switch (currentFilters.sortBy) {
case "due":
return determineStatus(assessment);
case "year":
return String(getAssessmentYear(assessment) || "Unknown");
case "subject":
return assessment.code || "Unknown";
case "grade":
return getAssessmentGrade(assessment);
case "title":
return getDisplayGrade(assessment, isLetterGradeMode());
case "title": {
const first = (assessment.title || "?")[0].toUpperCase();
return /[A-Z0-9]/.test(first) ? first : "#";
}
default:
return determineStatus(assessment);
return statusOf(assessment);
}
}
@@ -88,94 +132,49 @@
return new Date(a.due || a.date || 0).getTime() - new Date(b.due || b.date || 0).getTime();
}
const STATUS_COLUMNS: {
key: string;
title: string;
className: string;
icon: OverviewIconName;
}[] = [
{ key: "UPCOMING", title: "Upcoming", className: "column-upcoming", icon: "calendar-days" },
{ key: "DUE_SOON", title: "Due Soon", className: "column-due-soon", icon: "clock" },
{ key: "OVERDUE", title: "Overdue", className: "column-overdue", icon: "exclamation-triangle" },
{ key: "SUBMITTED", title: "Submitted", className: "column-submitted", icon: "document-check" },
{ key: "MARKS_RELEASED", title: "Marked", className: "column-marked", icon: "check-circle" },
];
function groupSortIcon(): OverviewIconName {
return GROUP_SORT_ICONS[currentFilters.sortBy] ?? "queue-list";
}
function buildGroupsAndColumns() {
function buildGroupsAndColumns(): {
filteredAssessments: any[];
statusGroups: Record<string, any[]>;
columns: Column[];
} {
if (!data?.assessments) return { filteredAssessments: [], statusGroups: {}, columns: [] };
const subjectFilters = settingsState.subjectfilters || {};
const hiddenAssessmentIds = new Set(
(JSON.parse(localStorage.getItem(HIDDEN_ASSESSMENTS_KEY) || "[]")).map(String)
);
const filtered = data.assessments.filter((a: any) => {
if (hiddenAssessmentIds.has(String(a.id))) return false;
const filtered: any[] = data.assessments.filter((a: any) => {
if (hiddenIds.includes(String(a.id))) return false;
if (subjectFilters[a.code] === false) return false;
if (currentFilters.subject !== "all" && a.code !== currentFilters.subject) {
return false;
}
if (
isEngage &&
currentFilters.student !== "all" &&
String(a.studentId) !== currentFilters.student
) {
if (currentFilters.subject !== "all" && a.code !== currentFilters.subject) return false;
if (isEngage && currentFilters.student !== "all" && String(a.studentId) !== currentFilters.student) {
return false;
}
return true;
});
const groups: Record<string, any[]> = {};
filtered.forEach((assessment) => {
const key = getGroupKey(assessment);
if (!groups[key]) groups[key] = [];
groups[key].push(assessment);
});
const groups = Object.groupBy(filtered, getGroupKey) as Record<string, any[]>;
for (const group of Object.values(groups)) group.sort(sortCompare);
Object.keys(groups).forEach((key) => {
groups[key].sort(sortCompare);
});
let cols: { key: string; title: string; className: string; icon: OverviewIconName }[];
if (currentFilters.sortBy === "due") {
cols = STATUS_COLUMNS;
} else {
const keys = Object.keys(groups).filter((k) => groups[k]?.length > 0);
const sortIcon = groupSortIcon();
if (currentFilters.sortBy === "year") {
cols = keys.sort((a, b) => Number(b) - Number(a)).map((k) => ({ key: k, title: k, className: "column-custom", icon: sortIcon }));
} else if (currentFilters.sortBy === "subject") {
const subjectTitles = new Map(data?.subjects?.map((s: any) => [s.code, `${s.code} - ${s.title}`]) || []);
cols = keys.sort().map((k) => ({ key: k, title: subjectTitles.get(k) || k, className: "column-custom", icon: sortIcon }));
} else {
cols = keys.sort().map((k) => ({ key: k, title: k, className: "column-custom", icon: sortIcon }));
}
return { filteredAssessments: filtered, statusGroups: groups, columns: STATUS_COLUMNS };
}
return { filteredAssessments: filtered, statusGroups: groups, columns: cols };
}
const icon = GROUP_SORT_ICONS[currentFilters.sortBy] ?? "queue-list";
const keys = Object.keys(groups);
const subjectTitles = new Map<string, string>(
data?.subjects?.map((s: any) => [s.code, `${s.code} - ${s.title}`]) ?? [],
);
const sorted =
currentFilters.sortBy === "year" ? keys.sort((a, b) => Number(b) - Number(a)) : keys.sort();
const columns = sorted.map((key) => ({
key,
title: currentFilters.sortBy === "subject" ? (subjectTitles.get(key) ?? key) : key,
className: "column-custom",
icon,
}));
$: if (data) {
const _ = currentFilters.sortBy && currentFilters.subject;
const result = buildGroupsAndColumns();
filteredAssessments = result.filteredAssessments;
statusGroups = result.statusGroups;
columns = result.columns;
}
function updateAssessments() {
const result = buildGroupsAndColumns();
filteredAssessments = result.filteredAssessments;
statusGroups = result.statusGroups;
columns = result.columns;
return { filteredAssessments: filtered, statusGroups: groups, columns };
}
function getDueDateClass(assessment: any): string {
const status = determineStatus(assessment);
switch (status) {
switch (statusOf(assessment)) {
case "OVERDUE":
return "overdue";
case "DUE_SOON":
@@ -188,155 +187,65 @@
}
function markAssessmentCompleted(assessment: any) {
const completedKey = "betterseqta-completed-assessments";
const completed = JSON.parse(localStorage.getItem(completedKey) || "[]");
if (!completed.includes(assessment.id)) {
completed.push(assessment.id);
localStorage.setItem(completedKey, JSON.stringify(completed));
updateAssessments();
checkForCelebration();
}
if (completedIds.includes(assessment.id)) return;
saveCompletedIds([...completedIds, assessment.id]);
checkForCelebration();
}
function unmarkAssessmentCompleted(assessment: any) {
const completedKey = "betterseqta-completed-assessments";
const completed = JSON.parse(localStorage.getItem(completedKey) || "[]");
const index = completed.indexOf(assessment.id);
if (index > -1) {
completed.splice(index, 1);
localStorage.setItem(completedKey, JSON.stringify(completed));
updateAssessments();
}
saveCompletedIds(completedIds.filter((id) => id !== assessment.id));
}
function hideAssessment(assessment: any) {
const hidden = JSON.parse(localStorage.getItem(HIDDEN_ASSESSMENTS_KEY) || "[]");
const id = String(assessment.id);
if (!hidden.includes(id)) {
hidden.push(id);
localStorage.setItem(HIDDEN_ASSESSMENTS_KEY, JSON.stringify(hidden));
visibilityRefresh++;
closeAllMenus();
updateAssessments();
}
}
function hideSubject(subjectCode: string) {
const filters = { ...(settingsState.subjectfilters || {}) };
filters[subjectCode] = false;
settingsState.subjectfilters = filters;
if (hiddenIds.includes(id)) return;
saveHiddenIds([...hiddenIds, id]);
closeAllMenus();
updateAssessments();
}
function unhideSubject(subjectCode: string) {
const filters = { ...(settingsState.subjectfilters || {}) };
filters[subjectCode] = true;
settingsState.subjectfilters = filters;
updateAssessments();
}
function unhideAssessment(assessmentId: string) {
const hidden = JSON.parse(localStorage.getItem(HIDDEN_ASSESSMENTS_KEY) || "[]");
const idStr = String(assessmentId);
const filtered = hidden.filter((id: string) => id !== idStr);
localStorage.setItem(HIDDEN_ASSESSMENTS_KEY, JSON.stringify(filtered));
visibilityRefresh++;
updateAssessments();
saveHiddenIds(hiddenIds.filter((id) => id !== String(assessmentId)));
}
function initSubjectFilters() {
const filters = settingsState.subjectfilters || {};
let updated = false;
data.subjects.forEach((s: any) => {
if (!Object.prototype.hasOwnProperty.call(filters, s.code)) {
filters[s.code] = true;
updated = true;
}
});
if (updated) {
settingsState.subjectfilters = filters;
function hideSubject(subjectCode: string) {
setSubjectVisible(subjectCode, false);
closeAllMenus();
}
function fireConfetti(options: confetti.Options) {
try {
confetti({ disableForReducedMotion: true, ...options });
} catch (e) {
console.log("Confetti celebration failed:", e);
}
}
function checkForCelebration() {
const overdueCount = statusGroups.OVERDUE?.length || 0;
const dueSoonCount = statusGroups.DUE_SOON?.length || 0;
const overdueCount = board.statusGroups.OVERDUE?.length || 0;
const dueSoonCount = board.statusGroups.DUE_SOON?.length || 0;
if (overdueCount === 0 && dueSoonCount === 0) {
setTimeout(() => {
try {
const duration = 100;
const end = Date.now() + duration;
(function frame() {
confetti({
particleCount: 17,
angle: 60,
spread: 65,
drift: 0.8,
startVelocity: 40,
scalar: 2,
gravity: 2,
decay: 0.97,
ticks: 300,
origin: { x: 0, y: 1 },
disableForReducedMotion: true,
});
confetti({
particleCount: 17,
angle: 120,
spread: 65,
drift: -0.8,
startVelocity: 40,
scalar: 2,
decay: 0.97,
ticks: 300,
gravity: 2,
origin: { x: 1, y: 1 },
disableForReducedMotion: true,
});
if (Date.now() < end) {
requestAnimationFrame(frame);
}
}());
} catch (e) {
console.log("Confetti celebration failed:", e);
}
const end = Date.now() + 100;
const side = { particleCount: 17, spread: 65, startVelocity: 40, scalar: 2, gravity: 2, decay: 0.97, ticks: 300 };
const frame = () => {
fireConfetti({ ...side, angle: 60, drift: 0.8, origin: { x: 0, y: 1 } });
fireConfetti({ ...side, angle: 120, drift: -0.8, origin: { x: 1, y: 1 } });
if (Date.now() < end) requestAnimationFrame(frame);
};
frame();
}, 500);
} else if (overdueCount === 0 || dueSoonCount === 0) {
setTimeout(() => {
try {
confetti({
particleCount: 100,
spread: 70,
origin: { y: 0.6 },
scalar: 0.9,
disableForReducedMotion: true,
});
} catch (e) {
console.log("Confetti celebration failed:", e);
}
fireConfetti({ particleCount: 100, spread: 70, origin: { y: 0.6 }, scalar: 0.9 });
}, 500);
}
}
function isManuallyCompleted(assessmentId: string): boolean {
const completedKey = "betterseqta-completed-assessments";
const completed = JSON.parse(localStorage.getItem(completedKey) || "[]");
return completed.includes(assessmentId);
}
function handleCardClick(assessment: any, event: Event) {
if ((event.target as HTMLElement).closest(".card-menu")) {
return;
}
if ((event.target as HTMLElement).closest(".card-menu")) return;
if (isSeqtaEngageExperience()) {
if (isEngage) {
const studentId = assessment.studentId ?? data?.studentId;
if (!studentId) return;
window.location.hash = buildEngageAssessmentPagePath(
@@ -351,22 +260,6 @@
window.location.hash = `#?page=/assessments/${assessment.programmeID}:${assessment.metaclassID}&item=${assessment.id}`;
}
let openMenuId: string | null = null;
let showVisibilityPanel = false;
let visibilityRefresh = 0;
$: hiddenSubjects = data?.subjects?.filter(
(s: any) => (settingsState.subjectfilters || {})[s.code] === false
) || [];
$: hiddenAssessmentIds = (() => {
visibilityRefresh; // Dependency for reactivity
return new Set((JSON.parse(localStorage.getItem(HIDDEN_ASSESSMENTS_KEY) || "[]")).map(String));
})();
$: hiddenAssessmentsWithInfo = data?.assessments?.filter(
(a: any) => hiddenAssessmentIds.has(String(a.id))
) || [];
$: hasHiddenItems = hiddenSubjects.length > 0 || hiddenAssessmentsWithInfo.length > 0;
function toggleMenu(assessmentId: string, event: Event) {
event.stopPropagation();
openMenuId = openMenuId === assessmentId ? null : assessmentId;
@@ -375,18 +268,9 @@
function closeAllMenus() {
openMenuId = null;
}
$: if (data) {
initSubjectFilters();
updateAssessments();
void currentFilters.sortBy;
void currentFilters.subject;
void currentFilters.student;
}
</script>
<svelte:window on:click={closeAllMenus} />
<svelte:window onclick={closeAllMenus} />
<div class="bsplus-overview-page">
<header class="grid-view-header bsplus-overview-animate">
@@ -420,7 +304,7 @@
<button
class="visibility-toggle"
class:active={showVisibilityPanel}
on:click={() => (showVisibilityPanel = !showVisibilityPanel)}
onclick={() => (showVisibilityPanel = !showVisibilityPanel)}
title="Manage hidden subjects and assessments"
>
<OverviewIcon name="eye" size={18} />
@@ -440,7 +324,7 @@
{#each hiddenSubjects as subject}
<span class="visibility-chip">
{subject.code}
<button class="visibility-unhide" on:click={() => unhideSubject(subject.code)}>Show</button>
<button class="visibility-unhide" onclick={() => setSubjectVisible(subject.code, true)}>Show</button>
</span>
{/each}
</div>
@@ -453,7 +337,7 @@
{#each hiddenAssessmentsWithInfo as assessment}
<span class="visibility-chip">
{assessment.title}
<button class="visibility-unhide" on:click={() => unhideAssessment(assessment.id)}>Show</button>
<button class="visibility-unhide" onclick={() => unhideAssessment(assessment.id)}>Show</button>
</span>
{/each}
</div>
@@ -463,15 +347,15 @@
{/if}
<div id="main-grid-content" class="bsplus-overview-animate bsplus-overview-delay-1">
{#if filteredAssessments.length === 0}
{#if board.filteredAssessments.length === 0}
<div class="empty-state">
<OverviewIcon name="clipboard-document-list" size={40} class="empty-icon" />
<p>No assessments found matching your filters</p>
</div>
{:else}
<div class="kanban-board">
{#each columns as column}
{#if statusGroups[column.key]?.length > 0}
{#each board.columns as column}
{#if board.statusGroups[column.key]?.length > 0}
<div class="kanban-column-parent">
<div class="kanban-column {column.className}">
<div class="column-header">
@@ -483,24 +367,24 @@
/>
{column.title}
</span>
<span class="column-count">{statusGroups[column.key].length}</span>
<span class="column-count">{board.statusGroups[column.key].length}</span>
</div>
</div>
<div class="column-cards" id="{column.key.toLowerCase()}-cards">
{#each statusGroups[column.key] as assessment}
{@const status = determineStatus(assessment)}
{#each board.statusGroups[column.key] as assessment}
{@const status = statusOf(assessment)}
{@const dueDateClass = getDueDateClass(assessment)}
{@const isCompleted = isManuallyCompleted(assessment.id)}
{@const isCompleted = completedIds.includes(assessment.id)}
{@const color = data.colors[assessment.code] || "#6366f1"}
<div
class="assessment-card"
data-subject={assessment.code}
data-status={status}
style="--subject-color: {color}"
on:click={(e) => handleCardClick(assessment, e)}
onclick={(e) => handleCardClick(assessment, e)}
role="button"
tabindex="0"
on:keydown={(e) => e.key === 'Enter' && handleCardClick(assessment, e)}
onkeydown={(e) => e.key === 'Enter' && handleCardClick(assessment, e)}
>
<div class="card-labels">
{#if isEngage && assessment.studentName}
@@ -520,25 +404,25 @@
<button
class="menu-button"
data-assessment-id={assessment.id}
on:click={(e) => toggleMenu(assessment.id, e)}
onclick={(e) => toggleMenu(assessment.id, e)}
aria-label="Open menu"
>
<OverviewIcon name="ellipsis-vertical" size={16} />
</button>
<div class="menu-dropdown" style="display: {openMenuId === assessment.id ? 'block' : 'none'};">
{#if status !== "MARKS_RELEASED"}
<button class="menu-item mark-completed" on:click={() => markAssessmentCompleted(assessment)}>
<button class="menu-item mark-completed" onclick={() => markAssessmentCompleted(assessment)}>
Mark as Completed
</button>
{:else if isCompleted}
<button class="menu-item mark-not-completed" on:click={() => unmarkAssessmentCompleted(assessment)}>
<button class="menu-item mark-not-completed" onclick={() => unmarkAssessmentCompleted(assessment)}>
Mark as Not Complete
</button>
{/if}
<button class="menu-item menu-item-hide" on:click={() => hideAssessment(assessment)}>
<button class="menu-item menu-item-hide" onclick={() => hideAssessment(assessment)}>
Hide assessment
</button>
<button class="menu-item menu-item-hide" on:click={() => hideSubject(assessment.code)}>
<button class="menu-item menu-item-hide" onclick={() => hideSubject(assessment.code)}>
Hide subject ({assessment.code})
</button>
</div>
@@ -1,7 +1,7 @@
<script lang="ts">
import OverviewIcon from "./OverviewIcon.svelte";
export let error: string;
let { error }: { error: string } = $props();
</script>
<div class="error-container bsplus-overview-animate">
@@ -191,7 +191,16 @@ export function formatDate(dateStr: string, submitted?: boolean): string {
});
}
export function determineStatus(item: any): string {
export function readStoredList(key: string): unknown[] {
try {
const parsed = JSON.parse(localStorage.getItem(key) || "[]");
return Array.isArray(parsed) ? parsed : [];
} catch {
return [];
}
}
export function determineStatus(item: any, completed: readonly unknown[]): string {
if (
item.status === "MARKS_RELEASED" ||
item.grade ||
@@ -201,15 +210,6 @@ export function determineStatus(item: any): string {
return "MARKS_RELEASED";
}
const completedKey = "betterseqta-completed-assessments";
let completed: unknown[];
try {
const raw = localStorage.getItem(completedKey);
const parsed = raw ? JSON.parse(raw) : [];
completed = Array.isArray(parsed) ? parsed : [];
} catch {
completed = [];
}
if (completed.includes(item.id)) {
return "MARKS_RELEASED";
}
@@ -9,6 +9,7 @@ import styles from "./styles.css?inline";
import BackgroundMusicSetting from "./BackgroundMusicSetting.svelte";
import localforage from "localforage";
import { isPerformanceMode } from "@/seqta/utils/performanceMode";
import { delay } from "@/seqta/utils/delay";
const settings = defineSettings({
uploader: componentSetting({
@@ -225,7 +226,7 @@ const backgroundMusicPlugin: Plugin<typeof settings> = {
// Retry after load — some browsers allow autoplay once the page settles
// or Media Engagement Index applies from prior visits.
for (const delayMs of [500, 1500, 3000]) {
await new Promise((resolve) => setTimeout(resolve, delayMs));
await delay(delayMs);
if (!audio || !audio.paused) return;
if (await attemptPlay(vol())) return;
}
@@ -1,13 +1,17 @@
<script lang="ts">
import { createEventDispatcher, onDestroy } from 'svelte';
import { onDestroy } from 'svelte';
import { calculateExpression } from '../utils/calculator';
let { searchTerm = '', isSelected = false } = $props<{ searchTerm: string, isSelected: boolean }>();
const dispatch = createEventDispatcher<{
hasResult: string | null;
}>();
let {
searchTerm = '',
isSelected = false,
onresult,
}: {
searchTerm: string;
isSelected: boolean;
onresult: (result: string | null) => void;
} = $props();
let result = $state<string | null>(null);
let isCalculating = $state(false);
let inputUnit = $state<string>('');
@@ -29,13 +33,13 @@
inputUnit = calcResult.inputUnit;
outputUnit = calcResult.outputUnit;
isPartial = calcResult.isPartial;
dispatch('hasResult', calcResult.result);
onresult(calcResult.result);
} else {
result = null;
inputUnit = '';
outputUnit = '';
isPartial = false;
dispatch('hasResult', null);
onresult(null);
}
} catch {
if (gen !== calcGen) return;
@@ -43,7 +47,7 @@
inputUnit = '';
outputUnit = '';
isPartial = false;
dispatch('hasResult', null);
onresult(null);
} finally {
if (gen === calcGen) isCalculating = false;
}
@@ -54,7 +58,7 @@
});
onDestroy(() => {
dispatch('hasResult', null);
onresult(null);
});
</script>
@@ -25,7 +25,7 @@
searchHotkey: string
}>();
let currentSearchHotkey = $state(initialSearchHotkey);
let currentSearchHotkey = $derived(initialSearchHotkey);
let commandsFuse = $state<Fuse<StaticCommandItem>>();
let dynamicContentFuse = $state<Fuse<IndexItem>>();
@@ -50,9 +50,6 @@
// the `world w` pass and clobbers the more relevant matches.
let searchRequestId = 0;
const updateCalculatorState = (hasResult: string | null) => {
calculatorResult = hasResult;
};
let keydownHandler: ((e: KeyboardEvent) => void) | null = null;
@@ -364,7 +361,7 @@
<Calculator
searchTerm={searchTerm}
isSelected={selectedIndex === 0}
on:hasResult={(e) => updateCalculatorState(e.detail)}
onresult={(result) => (calculatorResult = result)}
/>
{#if combinedResults.length > 0}
@@ -1,15 +1,21 @@
<script lang="ts">
import HighlightedText from '../../utils/HighlightedText.svelte';
import type { IndexItem } from '../../indexing/types';
import type { IndexItem } from '../../indexing/types';
import type { FuseResultMatch } from '../../core/types';
export let item: IndexItem;
export let isSelected: boolean;
export let searchTerm: string;
export let matches: readonly FuseResultMatch[] | undefined;
export let onclick: (() => void) | undefined;
let {
item,
isSelected,
searchTerm,
matches,
onclick,
}: {
item: IndexItem;
isSelected: boolean;
searchTerm: string;
matches: readonly FuseResultMatch[] | undefined;
onclick: (() => void) | undefined;
} = $props();
</script>
<button
@@ -1,3 +1,4 @@
import { delay } from "@/seqta/utils/delay";
const DB_NAME = "betterseqta-index";
const META_STORE = "meta";
const VERSION_KEY = "betterseqta-index-version";
@@ -449,7 +450,7 @@ export async function resetDatabase(): Promise<void> {
window.dispatchEvent(new CustomEvent("betterseqta-reset-search-index"));
}
await new Promise((resolve) => setTimeout(resolve, 200));
await delay(200);
localStorage.removeItem(VERSION_KEY);
await deleteDatabaseWithRetries(DB_NAME);
@@ -12,6 +12,7 @@ import { setIndexingActive } from "./indexingState";
import { isPluginBlockedByPerformanceMode } from "@/seqta/utils/performanceMode";
import { verboseDebug } from '@/utils/verboseLog';
import { delay } from "@/seqta/utils/delay";
const META_STORE = "meta";
const LOCK_KEY = "bsq-indexer-lock";
const HEARTBEAT_INTERVAL = 10000;
@@ -147,7 +148,7 @@ async function updateLastRunMeta(jobId: string): Promise<void> {
async function tryClaimLock(lockId: string): Promise<boolean> {
localStorage.setItem(LOCK_KEY, lockId);
await new Promise((resolve) => setTimeout(resolve, 50));
await delay(50);
if (localStorage.getItem(LOCK_KEY) === lockId) {
isIndexingActive = true;
return true;
@@ -182,7 +183,7 @@ async function acquireLock(): Promise<boolean> {
}
}
await new Promise((resolve) => setTimeout(resolve, 100));
await delay(100);
}
return false;
@@ -1,6 +1,7 @@
import type { IndexItem, Job } from "../types";
import { verboseDebug } from '@/utils/verboseLog';
import { delay } from "@/seqta/utils/delay";
const fetchJSON = async (url: string, body: any) => {
const res = await fetch(`${location.origin}${url}`, {
method: "POST",
@@ -345,7 +346,7 @@ export const assignmentsJob: Job = {
// Small delay between batches to avoid rate limiting
if (i + batchSize < assessmentArray.length) {
await new Promise(resolve => setTimeout(resolve, 50)); // Reduced delay
await delay(50); // Reduced delay
}
}
@@ -1,4 +1,4 @@
import type { SvelteComponent } from "svelte";
import type { Component } from "svelte";
import AssessmentItem from "../components/items/AssessmentItem.svelte";
import ForumItem from "../components/items/ForumItem.svelte";
import SubjectItem from "../components/items/SubjectItem.svelte";
@@ -7,26 +7,26 @@ import type { IndexItem } from "./types";
import { jobs } from "./jobs";
import { loadDynamicItems } from "../utils/dynamicItems";
export const renderComponentMap: Record<string, typeof SvelteComponent> = {
assessment: AssessmentItem as unknown as typeof SvelteComponent,
message: AssessmentItem as unknown as typeof SvelteComponent,
forum: ForumItem as unknown as typeof SvelteComponent,
subject: SubjectItem as unknown as typeof SvelteComponent,
export const renderComponentMap: Record<string, Component<any>> = {
assessment: AssessmentItem,
message: AssessmentItem,
forum: ForumItem,
subject: SubjectItem,
// New categories share a generic, category-aware row component to keep
// the palette consistent without bespoke layouts for every job. The
// component reads `item.metadata.icon` and the `category` to pick a
// sensible default visual treatment.
course: GenericItem as unknown as typeof SvelteComponent,
notice: GenericItem as unknown as typeof SvelteComponent,
document: GenericItem as unknown as typeof SvelteComponent,
folio: GenericItem as unknown as typeof SvelteComponent,
portal: GenericItem as unknown as typeof SvelteComponent,
report: GenericItem as unknown as typeof SvelteComponent,
goal: GenericItem as unknown as typeof SvelteComponent,
passive: GenericItem as unknown as typeof SvelteComponent,
course: GenericItem,
notice: GenericItem,
document: GenericItem,
folio: GenericItem,
portal: GenericItem,
report: GenericItem,
goal: GenericItem,
passive: GenericItem,
};
function resolveRenderComponent(item: IndexItem): typeof SvelteComponent | undefined {
function resolveRenderComponent(item: IndexItem): Component<any> | undefined {
const jobDef =
jobs[item.category] ||
Object.values(jobs).find((j) => j.id === item.category) ||
@@ -2,6 +2,7 @@ import { SCHEMA_VERSION_KEY } from "./schemaVersion";
import { pauseIndexingUntilReload } from "./indexingPause";
import { pausePassiveObserver } from "./passiveObserver";
import browser from "webextension-polyfill";
import { delay } from "@/seqta/utils/delay";
export const RESET_INDEX_MESSAGE = "global-search-reset-index";
@@ -46,10 +47,6 @@ const STRUCTURED_DB = "betterseqta-index";
const VECTOR_DB = "embeddiaDB";
const STRUCTURED_VERSION_KEY = "betterseqta-index-version";
function delay(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function tryDeleteDatabase(
name: string,
): Promise<"success" | "blocked" | "error"> {
@@ -1,4 +1,4 @@
import type { SvelteComponent } from "svelte";
import type { Component } from "svelte";
export interface IndexItem {
id: string;
@@ -9,7 +9,7 @@ export interface IndexItem {
metadata: Record<string, any>;
actionId: string;
renderComponentId: string;
renderComponent?: typeof SvelteComponent;
renderComponent?: Component<any>;
}
export type Frequency =
@@ -2,6 +2,7 @@ import { EmbeddingIndex, getEmbedding, initializeModel } from "embeddia";
import type { IndexItem } from "../types";
import { verboseDebug } from "./workerVerboseLog";
import { delay } from "@/seqta/utils/delay";
let ortWasmBase: string | null = null;
@@ -258,7 +259,7 @@ async function processStreamingItems() {
},
});
await new Promise((resolve) => setTimeout(resolve, 10));
await delay(10);
}
streamingSession.processingPromise = null;
@@ -5,6 +5,7 @@ import { getOrtWasmBaseUrl } from "@/lib/transformersExtension";
import vectorWorker from "./vectorWorker.ts?inlineWorker";
import { verboseDebug, verboseLog } from '@/utils/verboseLog';
import { delay } from "@/seqta/utils/delay";
export type ProgressCallback = (data: {
status: "started" | "processing" | "complete" | "error" | "cancelled";
total?: number;
@@ -242,7 +243,7 @@ export class VectorWorkerManager {
private async ensureReady() {
if (this.initializationMutex) {
while (this.initializationMutex) {
await new Promise((resolve) => setTimeout(resolve, 50));
await delay(50);
}
if (this.isInitialized && this.worker) {
@@ -420,7 +421,7 @@ export class VectorWorkerManager {
);
await this.endStreamingSession();
await new Promise((resolve) => setTimeout(resolve, 100));
await delay(100);
} else {
verboseDebug(`Streaming session for job ${jobId} already active`);
return true;
@@ -1,4 +1,4 @@
import type { SvelteComponent } from "svelte";
import type { Component } from "svelte";
import type { IndexItem } from "../indexing/types";
export interface DynamicContentItem {
@@ -10,7 +10,7 @@ export interface DynamicContentItem {
metadata: Record<string, any>;
actionId: string;
renderComponentId: string;
renderComponent?: typeof SvelteComponent;
renderComponent?: Component<any>;
}
let dynamicItems: IndexItem[] = [];
@@ -35,7 +35,7 @@
let showPrediction = $state(false);
let predictionMonths = $state(3);
const chartUid = `area-${Math.random().toString(36).slice(2, 9)}`;
const chartUid = $props.id();
const chartResult = $derived.by(() =>
buildGradeTrendChart(data, timeRange, {
@@ -173,7 +173,6 @@
aria-modal="true"
aria-labelledby="bsplus-class-group-modal-title"
transition:scale={{ duration: fadeDuration, start: 0.96 }}
onclick={(e) => e.stopPropagation()}
>
<header class="bsplus-analytics-class-groups-dialog-head">
<div>
+2 -5
View File
@@ -44,9 +44,6 @@ const TRASH_SVG = `<svg style="width:12px;height:12px;flex-shrink:0" viewBox="0
const CHEVRON_SVG = `<svg style="width:12px;height:12px;flex-shrink:0;transition:transform .2s" viewBox="0 0 24 24"><path fill="#888" d="M7.41 8.59L12 13.17l4.59-4.58L18 10l-6 6-6-6 1.41-1.41z"/></svg>`;
const DRAG_SVG = `<svg style="width:14px;height:14px;flex-shrink:0;cursor:grab" viewBox="0 0 24 24"><path fill="#888" d="M6.5 12.5a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3zm5.5 0a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3zm5.5 0a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3z"/></svg>`;
function generateId(): string {
return Date.now().toString(36) + Math.random().toString(36).slice(2, 7);
}
function isAllowedFolderColor(color: unknown): color is string {
return typeof color === "string" && FOLDER_COLORS.includes(color);
@@ -58,7 +55,7 @@ function isAllowedFolderIcon(icon: unknown): icon is string {
function normalizeFolder(folder: Folder): Folder {
return {
id: typeof folder.id === "string" && folder.id ? folder.id : generateId(),
id: typeof folder.id === "string" && folder.id ? folder.id : crypto.randomUUID(),
name: typeof folder.name === "string" ? folder.name.trim().slice(0, 30) : "Folder",
color: isAllowedFolderColor(folder.color) ? folder.color : FOLDER_COLORS[0],
emoji: isAllowedFolderIcon(folder.emoji) ? folder.emoji : FOLDER_HEROICONS[0],
@@ -549,7 +546,7 @@ const messageFoldersPlugin = {
);
saveFolders(folders);
} else {
const folder: Folder = { id: generateId(), name, color: selectedColor, emoji: selectedIcon };
const folder: Folder = { id: crypto.randomUUID(), name, color: selectedColor, emoji: selectedIcon };
saveFolders([...getFolders(), folder]);
}
applyBadges();
@@ -1151,10 +1151,6 @@ export class ThemeManager {
}
}
/**
* Update the preview of a theme (debounced)
* @param theme - The theme to update the preview of
*/
public updatePreviewDebounced = debounce(
(theme: Partial<LoadedCustomTheme>): void => {
this.updatePreview(theme);
-60
View File
@@ -51,40 +51,6 @@ function createSEQTAAPI(): SEQTAAPI {
};
}
/**
* Creates a reactive and persistent settings store for a given plugin.
* This store is a Svelte-like store, providing reactivity, persistence
* via `browser.storage.local`, and default value handling.
*
* @template T - Represents the structure of the plugin's settings, extending `PluginSettings`.
* @param {Plugin<T, any>} plugin The plugin instance for which the settings store is being created.
* `plugin.id` is used for namespacing the settings in storage,
* and `plugin.settings` provides the definitions and default values for each setting.
* @returns {SettingsAPI<T> & { loaded: Promise<void> }} An object that functions as a Svelte store,
* enhanced with specific methods for settings management.
* The object includes:
* - Reactivity: Changes to settings can be subscribed to using Svelte's store subscription pattern
* (though not explicitly a Svelte store, it behaves similarly for direct property access and updates).
* The `onChange` method provides a more direct way to listen for specific key changes.
* - Persistence: Settings are automatically loaded from `browser.storage.local` when the store is created
* and saved back whenever a setting is changed via the proxy's setter.
* - Default Values: Uses default values from the `plugin.settings` definition if no stored value exists for a setting.
* - `loaded`: A Promise that resolves when the settings have been successfully loaded from storage,
* allowing operations to be deferred until settings are ready.
* - Direct property access for getting values (e.g., `settingsStore.mySettingKey`).
* - Direct property assignment for setting values (e.g., `settingsStore.mySettingKey = newValue`), which also persists the change.
* - `onChange(key, callback)`: Method to listen for changes to a specific setting. (Note: The prompt mentioned `listen`, this is `onChange`).
* Returns an object with an `unregister` method.
* - `offChange(key, callback)`: Method to stop listening for changes to a specific setting.
* The following methods are not explicitly present on the returned proxy from `createSettingsAPI` but are typically
* expected in a full "Svelte store" settings manager. The current implementation relies on direct property
* manipulation for get/set, and re-initialization for reset-like behavior or would require external implementation
* of reset logic if needed:
* - `get(key)`: (Achieved by direct property access: `settingsStore.key`)
* - `set(key, value)`: (Achieved by direct property assignment: `settingsStore.key = value`)
* - `reset(key)`: (Would require manual re-application of `plugin.settings[key].default` and then setting it)
* - `resetAll()`: (Would require iterating through all `plugin.settings` and applying defaults, then setting them)
*/
function createSettingsAPI<T extends PluginSettings>(
plugin: Plugin<T>,
): {
@@ -344,32 +310,6 @@ function createEventsAPI(pluginId: string): EventsAPI {
};
}
/**
* Creates and returns a tailored API object for a specific plugin.
* This API object provides the plugin with various functionalities such as
* managing settings, accessing namespaced storage, interacting with SEQTA-specific features,
* and handling plugin-specific events.
*
* @template T - The type of the plugin's settings, extending `PluginSettings`.
* @template S - The type of the data the plugin will store in its namespaced storage.
* @param {Plugin<T, S>} plugin The plugin instance for which the API is being created.
* The plugin's `id` and `name` are used internally by the API
* for namespacing and identification but are accessed from the `plugin` object directly.
* @returns {PluginAPI<T, S>} An API object containing the following key properties:
* - `seqta`: An API for interacting with SEQTA-specific functionalities, created by `createSEQTAAPI()`.
* This includes methods like `onMount` for DOM element appearance, `getFiber` for React component inspection,
* `getCurrentPage` for getting the current SEQTA page, and `onPageChange` for listening to page navigations.
* - `settings`: An API for managing plugin-specific settings, created by `createSettingsAPI(plugin)`.
* It allows getting, setting, and listening to changes in the plugin's settings,
* which are stored persistently and namespaced to the plugin. Includes a `loaded` promise.
* - `storage`: An API for providing namespaced storage for the plugin, created by `createStorageAPI<S>(plugin.id)`.
* It allows the plugin to store and retrieve arbitrary data, namespaced to prevent conflicts
* with other plugins or parts of the extension. Includes a `loaded` promise and `onChange` listeners.
* - `events`: An API for allowing the plugin to dispatch and listen for custom events within its own scope,
* created by `createEventsAPI(plugin.id)`. It provides `on(event, callback)` to listen for
* plugin-specific events and `emit(event, ...args)` to dispatch them. These events are namespaced
* to the plugin.
*/
export function createPluginAPI<T extends PluginSettings, S = any>(
plugin: Plugin<T, S>,
): PluginAPI<T, S> {
-125
View File
@@ -79,10 +79,6 @@ export class PluginManager {
this.setupPluginStateListener();
}
/**
* Gets the singleton instance of the PluginManager.
* @returns {PluginManager} The singleton instance.
*/
public static getInstance(): PluginManager {
if (!PluginManager.instance) {
PluginManager.instance = new PluginManager();
@@ -90,15 +86,6 @@ export class PluginManager {
return PluginManager.instance;
}
/**
* Dispatches an event to a specific plugin.
* If the plugin is currently running, the event is dispatched immediately via a DOM CustomEvent.
* If the plugin is not running, the event is added to a backlog to be processed when the plugin starts.
*
* @param {string} pluginId The ID of the target plugin.
* @param {string} event The name of the event to dispatch (e.g., "update").
* @param {any} [args] Optional arguments to pass with the event.
*/
public dispatchPluginEvent(pluginId: string, event: string, args?: any) {
const fullEventName = `plugin.${pluginId}.${event}`;
@@ -114,14 +101,6 @@ export class PluginManager {
}
}
/**
* Processes and dispatches any events that were backlogged for a plugin.
* This is typically called after a plugin has successfully started.
*
* @private
* @param {string} pluginId The ID of the plugin for which to process backlogged events.
* @returns {Promise<void>}
*/
private async processBackloggedEvents(pluginId: string) {
for (const [key, argsList] of this.eventBacklog.entries()) {
const [eventPluginId, event] = key.split(":");
@@ -134,15 +113,6 @@ export class PluginManager {
}
}
/**
* Registers a plugin with the manager.
* Plugins must have a unique ID.
*
* @template T - The type of settings the plugin uses.
* @template S - The type of storage the plugin uses.
* @param {Plugin<T, S>} plugin The plugin object to register.
* @throws {Error} If a plugin with the same ID is already registered.
*/
public registerPlugin<T extends PluginSettings, S>(
plugin: Plugin<T, S>,
): void {
@@ -152,22 +122,6 @@ export class PluginManager {
this.plugins.set(plugin.id, plugin);
}
/**
* Starts a specific plugin by its ID.
* This involves:
* - Checking if the plugin exists and isn't already running.
* - Creating and providing the plugin API (settings, storage, etc.).
* - Checking if the plugin is enabled (if `disableToggle` is true), respecting its `defaultEnabled` status.
* - Injecting any CSS styles defined by the plugin into the document head.
* - Waiting for the plugin's settings and storage to be loaded.
* - Executing the plugin's `run` method.
* - Storing any cleanup function returned by `run` for later use in `stopPlugin`.
* - Marking the plugin as running and processing any backlogged events for it.
*
* @param {string} pluginId The ID of the plugin to start.
* @returns {Promise<void>} A promise that resolves when the plugin has started or is determined not to start (e.g., disabled).
* @throws {Error} If the plugin is not found, or if an error occurs during plugin initialization or execution.
*/
public async startPlugin(pluginId: string): Promise<void> {
const plugin = this.plugins.get(pluginId);
if (plugin && !this.shouldStartPlugin(plugin)) return;
@@ -291,13 +245,6 @@ export class PluginManager {
await Promise.allSettled(startPromises);
}
/**
* Attempts to start all registered plugins in phased order.
* Errors during the start of individual plugins are caught and logged,
* allowing other plugins to attempt to start.
*
* @returns {Promise<void>} A promise that resolves when all plugins have attempted to start.
*/
public async startAllPlugins(): Promise<void> {
for (const phase of PLUGIN_START_PHASES) {
await this.startPluginPhase(phase);
@@ -312,17 +259,6 @@ export class PluginManager {
}
}
/**
* Stops a specific plugin by its ID.
* This involves:
* - Removing any CSS styles injected by the plugin.
* - Executing the cleanup function that was returned by the plugin's `run` method (if any).
* - Marking the plugin as not running.
* - Emitting a "plugin.stopped" event with the pluginId.
*
* @param {string} pluginId The ID of the plugin to stop.
* @returns {Promise<void>} A promise that resolves when the plugin has been stopped.
*/
public async stopPlugin(pluginId: string): Promise<void> {
const stopRequest = Symbol();
this.pendingStops.set(pluginId, stopRequest);
@@ -357,39 +293,14 @@ export class PluginManager {
await Promise.allSettled(stops);
}
/**
* Retrieves a registered plugin by its ID.
*
* @param {string} pluginId The ID of the plugin to retrieve.
* @returns {Plugin | undefined} The plugin object if found, otherwise undefined.
*/
public getPlugin(pluginId: string): Plugin | undefined {
return this.plugins.get(pluginId);
}
/**
* Retrieves an array of all registered plugin objects.
*
* @returns {Plugin[]} An array containing all registered plugin objects.
*/
public getAllPlugins(): Plugin[] {
return Array.from(this.plugins.values());
}
/**
* Retrieves a structured list of settings for all registered plugins.
* This is primarily used for building user interfaces for plugin configuration.
* It processes each plugin's defined settings, adding IDs, titles, descriptions,
* and default enabled states. For plugins with `disableToggle`, an "enabled"
* boolean setting is automatically included.
*
* @returns {Array<object>} An array of objects, where each object represents a plugin
* and contains its ID, name, description, beta status,
* and a processed `settings` object. The `settings` object
* maps setting keys to their detailed configuration (type, title, etc.).
* The specific structure of each setting object within `settings`
* depends on its type (boolean, string, number, select, button, hotkey).
*/
public getAllPluginSettings(): Array<{
pluginId: string;
name: string;
@@ -459,24 +370,10 @@ export class PluginManager {
});
}
/**
* Checks if a specific plugin is currently running.
*
* @param {string} pluginId The ID of the plugin to check.
* @returns {boolean} True if the plugin is running, false otherwise.
*/
public isPluginRunning(pluginId: string): boolean {
return this.runningPlugins.get(pluginId) || false;
}
/**
* Emits an event to all registered listeners for that event.
* This is an internal event bus for the PluginManager itself.
*
* @private
* @param {string} event The name of the event to emit.
* @param {any[]} args Arguments to pass to the event listeners.
*/
private emit(event: string, ...args: any[]): void {
const listeners = this.listeners.get(event);
if (listeners) {
@@ -484,12 +381,6 @@ export class PluginManager {
}
}
/**
* Registers an event listener for PluginManager's internal events.
*
* @param {string} event The name of the event to listen for (e.g., "plugin.stopped").
* @param {(...args: any[]) => void} callback The function to call when the event is emitted.
*/
public on(event: string, callback: (...args: any[]) => void): void {
if (!this.listeners.has(event)) {
this.listeners.set(event, new Set());
@@ -497,12 +388,6 @@ export class PluginManager {
this.listeners.get(event)!.add(callback);
}
/**
* Unregisters an event listener for PluginManager's internal events.
*
* @param {string} event The name of the event.
* @param {(...args: any[]) => void} callback The callback function to remove.
*/
public off(event: string, callback: (...args: any[]) => void): void {
const listeners = this.listeners.get(event);
if (listeners) {
@@ -510,16 +395,6 @@ export class PluginManager {
}
}
/**
* Handles the change in a plugin's enabled state.
* Starts or stops the plugin based on the new `enabled` value.
* This is typically called by `setupPluginStateListener` when a relevant storage change is detected.
*
* @private
* @param {string} pluginId The ID of the plugin whose state has changed.
* @param {boolean} enabled The new enabled state of the plugin.
* @returns {Promise<void>}
*/
private async handlePluginStateChange(
pluginId: string,
enabled: boolean,
+3 -32
View File
@@ -1,39 +1,10 @@
import type { PluginSettings } from "./types";
export function Setting(settingDef: any): PropertyDecorator {
return (target, propertyKey) => {
const proto = target.constructor.prototype;
if (!proto.hasOwnProperty("settings")) {
Object.defineProperty(proto, "settings", {
value: {},
writable: true,
configurable: true,
enumerable: true,
});
}
proto.settings[propertyKey] = settingDef;
};
}
// Base plugin class that handles settings
export abstract class BasePlugin<T extends PluginSettings = PluginSettings> {
// The settings property will be populated by decorators
// Keep the instance property and constructor logic as is,
// as changing it would require changing animated-background/index.ts
settings!: T; // Use definite assignment assertion
settings: T;
constructor() {
// Copy settings from the prototype to the instance
// This ensures that each instance has its own settings object
// IMPORTANT: Ensure the prototype actually HAS settings before copying
if (this.constructor.prototype.hasOwnProperty("settings")) {
// Deep clone might be safer if settings objects become complex,
// but a shallow clone is usually fine for this structure.
this.settings = { ...this.constructor.prototype.settings } as T;
} else {
// Fallback if decorators somehow didn't run or add the property
this.settings = {} as T;
}
const proto = this.constructor.prototype;
this.settings = { ...(Object.hasOwn(proto, "settings") ? proto.settings : {}) } as T;
}
}
+1 -94
View File
@@ -9,16 +9,6 @@ import type {
StringSetting,
} from "./types";
/**
* Creates a complete `NumberSetting` object from its options.
* This helper function ensures the `type` property is correctly set to "number".
* It's used for defining a numeric setting for a plugin.
* This function itself does not handle storage or persistence; it defines the setting's structure.
*
* @param {Omit<NumberSetting, "type">} options The configuration options for the number setting,
* excluding the `type` property (e.g., `title`, `default`, `min`, `max`).
* @returns {NumberSetting} A complete number setting object with `type: "number"`.
*/
export function numberSetting(
options: Omit<NumberSetting, "type">,
): NumberSetting {
@@ -28,16 +18,6 @@ export function numberSetting(
};
}
/**
* Creates a complete `BooleanSetting` object from its options.
* This helper function ensures the `type` property is correctly set to "boolean".
* It's used for defining a boolean (true/false) setting for a plugin.
* This function itself does not handle storage or persistence; it defines the setting's structure.
*
* @param {Omit<BooleanSetting, "type">} options The configuration options for the boolean setting,
* excluding the `type` property (e.g., `title`, `default`).
* @returns {BooleanSetting} A complete boolean setting object with `type: "boolean"`.
*/
export function booleanSetting(
options: Omit<BooleanSetting, "type">,
): BooleanSetting {
@@ -47,16 +27,6 @@ export function booleanSetting(
};
}
/**
* Creates a complete `StringSetting` object from its options.
* This helper function ensures the `type` property is correctly set to "string".
* It's used for defining a text-based setting for a plugin.
* This function itself does not handle storage or persistence; it defines the setting's structure.
*
* @param {Omit<StringSetting, "type">} options The configuration options for the string setting,
* excluding the `type` property (e.g., `title`, `default`, `placeholder`).
* @returns {StringSetting} A complete string setting object with `type: "string"`.
*/
export function stringSetting(
options: Omit<StringSetting, "type">,
): StringSetting {
@@ -66,17 +36,6 @@ export function stringSetting(
};
}
/**
* Creates a complete `SelectSetting` object from its options.
* This helper function ensures the `type` property is correctly set to "select".
* It's used for defining a setting where the user can choose from a predefined list of options.
* This function itself does not handle storage or persistence; it defines the setting's structure.
*
* @template TValue - The type of the value for each option in the select list (extends string).
* @param {Omit<SelectSetting<TValue>, "type">} options The configuration options for the select setting,
* excluding the `type` property (e.g., `title`, `default`, `options` array).
* @returns {SelectSetting<TValue>} A complete select setting object with `type: "select"`.
*/
export function selectSetting<TValue extends string>(
options: Omit<SelectSetting<TValue>, "type">,
): SelectSetting<TValue> {
@@ -86,16 +45,6 @@ export function selectSetting<TValue extends string>(
};
}
/**
* Creates a complete `ButtonSetting` object from its options.
* This helper function ensures the `type` property is correctly set to "button".
* It's used for defining a button in the plugin's settings UI, which can trigger an action.
* This function itself does not handle storage or persistence; it defines the button's structure and action.
*
* @param {Omit<ButtonSetting, "type">} options The configuration options for the button setting,
* excluding the `type` property (e.g., `title`, `label`, `trigger` function).
* @returns {ButtonSetting} A complete button setting object with `type: "button"`.
*/
export function buttonSetting(
options: Omit<ButtonSetting, "type">,
): ButtonSetting {
@@ -105,16 +54,6 @@ export function buttonSetting(
};
}
/**
* Creates a complete `HotkeySetting` object from its options.
* This helper function ensures the `type` property is correctly set to "hotkey".
* It's used for defining a setting where the user can configure a keyboard shortcut.
* This function itself does not handle storage or persistence; it defines the hotkey setting's structure.
*
* @param {Omit<HotkeySetting, "type">} options The configuration options for the hotkey setting,
* excluding the `type` property (e.g., `title`, `default` hotkey string).
* @returns {HotkeySetting} A complete hotkey setting object with `type: "hotkey"`.
*/
export function componentSetting(
options: Omit<ComponentSetting, "type">,
@@ -134,46 +73,14 @@ export function hotkeySetting(
};
}
/**
* Defines a collection of settings for a plugin.
* This function currently acts as an identity function, returning the settings object as is.
* Its primary purpose is to provide type inference and a structured way to define
* the entire settings configuration for a plugin, ensuring it conforms to the expected type.
* This function itself does not handle storage or persistence; it's for structural definition.
*
* @template TSettings - A record type where keys are setting names and values are setting definition objects
* (e.g., `NumberSetting`, `BooleanSetting`).
* @param {TSettings} settings The complete settings configuration object for the plugin.
* @returns {TSettings} The same settings configuration object, primarily for type checking/inference.
*/
export function defineSettings<TSettings extends Record<string, any>>(settings: TSettings): TSettings {
return settings;
}
/**
* A property decorator for declaratively defining a plugin setting on a class property.
* When a class property is decorated with `@Setting({...})`, this decorator adds the
* provided setting definition (`settingDef`) to a static `settings` object on the
* class's prototype. This allows settings to be defined alongside their related class logic.
* This decorator itself does not handle runtime storage or persistence of setting *values*;
* it is for defining the *structure* and *metadata* of a setting.
*
* Example:
* ```typescript
* class MyPlugin extends BasePlugin {
* @Setting(numberSetting({ title: "My Number", default: 10 }))
* myNumberSetting: number; // Type annotation for the setting's value
* }
* ```
*
* @param {any} settingDef The setting definition object, typically created by one of the
* helper functions like `numberSetting(...)`, `booleanSetting(...)`, etc.
* @returns {PropertyDecorator} A property decorator function.
*/
export function Setting(settingDef: any): PropertyDecorator {
return (target, propertyKey) => {
const proto = target.constructor.prototype;
if (!proto.hasOwnProperty("settings")) {
if (!Object.hasOwn(proto, "settings")) {
Object.defineProperty(proto, "settings", {
value: {},
writable: true,
+10 -22
View File
@@ -14,7 +14,6 @@ import { applyDefaultBackgroundOnce } from "./defaultBackground";
import stringToHTML from "@/seqta/utils/stringToHTML";
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
import { updateAllColors } from "./colors/Manager";
import { delay } from "@/seqta/utils/delay";
import {
ensureThemeToggleSurprisePageScript,
openThemeToggleSurprise,
@@ -341,19 +340,15 @@ function setupEventListeners() {
action();
};
homebutton?.addEventListener("click", function () {
activateMenuAction(homebutton, () => {
loadHomePage();
});
homebutton?.addEventListener("click", () => {
activateMenuAction(homebutton, loadHomePage);
});
newsbutton?.addEventListener("click", function () {
activateMenuAction(newsbutton, () => {
SendNewsPage();
});
newsbutton?.addEventListener("click", () => {
activateMenuAction(newsbutton, SendNewsPage);
});
menuCover?.addEventListener("click", function () {
menuCover?.addEventListener("click", () => {
location.href = "../#?page=/home";
loadHomePage();
(
@@ -372,11 +367,10 @@ async function createSettingsButton(parent?: Element) {
document.body;
target.append(
stringToHTML(/* html */ `
<button class="addedButton tooltip" id="AddedSettings">
<button class="addedButton" id="AddedSettings" type="button" aria-label="BetterSEQTA+ settings">
<svg width="24" height="24" viewBox="0 0 24 24">
<g><g><path d="M23.182,6.923c-.29,0-3.662,2.122-4.142,2.4l-2.8-1.555V4.511l4.257-2.456a.518.518,0,0,0,.233-.408.479.479,0,0,0-.233-.407,6.511,6.511,0,1,0-3.327,12.107,6.582,6.582,0,0,0,6.148-4.374,5.228,5.228,0,0,0,.333-1.542A.461.461,0,0,0,23.182,6.923Z"></path><path d="M9.73,10.418,7.376,12.883c-.01.01-.021.016-.03.025L1.158,19.1a2.682,2.682,0,1,0,3.793,3.793l4.583-4.582,0,0,4.1-4.005-.037-.037A9.094,9.094,0,0,1,9.73,10.418ZM3.053,21.888A.894.894,0,1,1,3.946,21,.893.893,0,0,1,3.053,21.888Z"></path></g></g>
</svg>
${settingsState.onoff ? '<div class="tooltiptext topmenutooltip">BetterSEQTA+ Settings</div>' : ""}
</button>
`).firstChild!,
);
@@ -549,9 +543,8 @@ async function addDarkLightToggle(parent?: Element) {
const toggleTarget = parent ?? document.getElementById("content")!;
toggleTarget.append(
stringToHTML(/* html */ `
<button class="addedButton DarkLightButton tooltip" id="LightDarkModeButton">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">${settingsState.DarkMode ? LUCIDE_SUN_ICON_SVG : LUCIDE_MOON_ICON_SVG}</svg>
<div class="tooltiptext topmenutooltip" id="darklighttooliptext">${GetLightDarkModeString()}</div>
<button class="addedButton DarkLightButton" id="LightDarkModeButton" type="button" aria-label="${GetLightDarkModeString()}">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" aria-hidden="true">${settingsState.DarkMode ? LUCIDE_SUN_ICON_SVG : LUCIDE_MOON_ICON_SVG}</svg>
</button>
`).firstChild!,
);
@@ -564,9 +557,7 @@ async function addDarkLightToggle(parent?: Element) {
ensureThemeToggleSurprisePageScript();
lightDarkModeButtonElement.addEventListener("click", async () => {
const darklightText = document.getElementById("darklighttooliptext");
lightDarkModeButtonElement.addEventListener("click", () => {
lightDarkToggleStreak += 1;
if (lightDarkToggleStreak >= THEME_TOGGLE_SURPRISE_TRIGGER_AT) {
@@ -579,9 +570,6 @@ async function addDarkLightToggle(parent?: Element) {
settingsState.originalDarkMode !== undefined &&
settingsState.selectedTheme
) {
darklightText!.innerText = "Locked by current theme";
await delay(1000);
darklightText!.innerText = GetLightDarkModeString();
return;
}
@@ -592,7 +580,7 @@ async function addDarkLightToggle(parent?: Element) {
svgElement.innerHTML = settingsState.DarkMode
? LUCIDE_SUN_ICON_SVG
: LUCIDE_MOON_ICON_SVG;
darklightText!.innerText = GetLightDarkModeString();
lightDarkModeButtonElement.setAttribute("aria-label", GetLightDarkModeString());
});
}
@@ -3,8 +3,9 @@ import { refreshCloudUserFromServer } from "@/seqta/utils/cloudPfpSync";
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
import { fullMotionEffectsEnabled } from "@/seqta/utils/performanceMode";
import {
badgeBlobStyle,
badgesForTitlebar,
founderBadgeChipHtml,
badgeVisualForKey,
type BadgeItem,
} from "@/seqta/utils/founderBadges";
import { openFounderBadgeModal } from "@/seqta/ui/founderBadge/openFounderBadgeModal";
@@ -18,58 +19,30 @@ const BADGE_CYCLE_MS = 4500;
const carouselTimers = new WeakMap<HTMLElement, ReturnType<typeof setInterval>>();
function stopBadgeCarousel(slot: HTMLElement): void {
const timer = carouselTimers.get(slot);
if (timer != null) {
clearInterval(timer);
carouselTimers.delete(slot);
}
clearInterval(carouselTimers.get(slot));
carouselTimers.delete(slot);
}
function wireBadgeChip(
chip: HTMLButtonElement,
badge: BadgeItem,
signupNumber?: number | null,
): void {
chip.setAttribute("aria-label", `${badge.label}, click for details`);
chip.addEventListener("click", () => openFounderBadgeModal(badge, signupNumber));
function createBadgeButton(badge: BadgeItem, signupNumber?: number | null): HTMLButtonElement | null {
const visual = badgeVisualForKey(badge.key, badge.label);
if (!visual) return null;
const button = document.createElement("button");
button.type = "button";
button.className = "bsplus-titlebar-badge";
button.style.cssText = badgeBlobStyle(visual);
button.textContent = badge.label || visual.label;
button.addEventListener("click", () => openFounderBadgeModal(badge, signupNumber));
return button;
}
function setActiveBadgeChip(chips: HTMLButtonElement[], index: number): void {
chips.forEach((chip, i) => {
function showBadge(buttons: HTMLButtonElement[], index: number): void {
buttons.forEach((button, i) => {
const active = i === index;
chip.classList.toggle("bsplus-founder-badge--active", active);
chip.setAttribute("aria-hidden", active ? "false" : "true");
chip.tabIndex = active ? 0 : -1;
button.toggleAttribute("inert", !active);
button.setAttribute("aria-hidden", String(!active));
});
}
function startBadgeCarousel(
slot: HTMLElement,
chips: HTMLButtonElement[],
badges: BadgeItem[],
signupNumber?: number | null,
): void {
stopBadgeCarousel(slot);
if (chips.length <= 1) return;
let index = 0;
setActiveBadgeChip(chips, index);
slot.setAttribute(
"aria-label",
`${badges[index]?.label ?? "Cloud badge"}. Cycles through ${badges.length} badges.`,
);
carouselTimers.set(
slot,
setInterval(() => {
index = (index + 1) % chips.length;
setActiveBadgeChip(chips, index);
const label = badges[index]?.label;
if (label) slot.setAttribute("aria-label", `${label}. Badge ${index + 1} of ${badges.length}.`);
}, BADGE_CYCLE_MS),
);
}
function renderTitlebarBadges(
slot: HTMLElement,
badges: BadgeItem[],
@@ -77,52 +50,21 @@ function renderTitlebarBadges(
): void {
stopBadgeCarousel(slot);
const house = slot
.closest(".userInfoHouseWrap")
?.querySelector<HTMLElement>(".userInfohouse");
if (house?.style.display === "none") {
slot.replaceChildren();
slot.hidden = true;
return;
}
const buttons = badges.flatMap((badge) => createBadgeButton(badge, signupNumber) ?? []);
const rendered = badges
.map((b) => ({ badge: b, html: founderBadgeChipHtml(b, { titlebar: true }) }))
.filter((entry) => entry.html.length > 0);
slot.replaceChildren(...buttons);
slot.hidden = buttons.length === 0;
slot.classList.toggle("bsplus-founder-badge-slot--static", !fullMotionEffectsEnabled());
if (buttons.length <= 1) return;
if (rendered.length === 0) {
slot.replaceChildren();
slot.hidden = true;
return;
}
slot.hidden = false;
slot.removeAttribute("aria-label");
if (rendered.length === 1) {
slot.innerHTML = rendered[0].html;
const chip = slot.querySelector<HTMLButtonElement>(".bsplus-founder-badge");
if (chip) wireBadgeChip(chip, rendered[0].badge, signupNumber);
return;
}
const motionClass = fullMotionEffectsEnabled()
? "bsplus-founder-badge-carousel"
: "bsplus-founder-badge-carousel bsplus-founder-badge-carousel--static";
slot.innerHTML = `<div class="${motionClass}">${rendered.map((r) => r.html).join("")}</div>`;
const chips = [...slot.querySelectorAll<HTMLButtonElement>(".bsplus-founder-badge")];
chips.forEach((chip, i) => {
const entry = rendered[i];
if (!entry) return;
wireBadgeChip(chip, entry.badge, signupNumber);
});
startBadgeCarousel(
let index = 0;
showBadge(buttons, index);
carouselTimers.set(
slot,
chips,
rendered.map((r) => r.badge),
signupNumber,
setInterval(() => {
index = (index + 1) % buttons.length;
showBadge(buttons, index);
}, BADGE_CYCLE_MS),
);
}
+1 -1
View File
@@ -1,7 +1,7 @@
import { CreateElement } from "@/seqta/utils/createEnable/CreateElement";
export function FilterUpcomingAssessments(subjectoptions: any) {
for (var item in subjectoptions) {
for (const item in subjectoptions) {
let subjectdivs = document.querySelectorAll(`[data-subject="${item}"]`);
for (let i = 0; i < subjectdivs.length; i++) {
+2 -5
View File
@@ -8,6 +8,7 @@ import {
parseOutlookSeqtaKey,
} from "@/seqta/utils/calendarSync/eventFingerprint";
import type { SyncDateRange } from "@/seqta/utils/googleCalendar/syncDateRange";
import { delay } from "@/seqta/utils/delay";
export type RemoteSyncedEvent = {
seqtaKey: string;
@@ -23,10 +24,6 @@ export type ListSyncedEventsOptions = {
const MAX_RETRIES = 4;
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function isRetryableStatus(status: number): boolean {
return status === 429 || status === 500 || status === 502 || status === 503 || status === 403;
}
@@ -48,7 +45,7 @@ async function authorizedFetch(
continue;
}
if (isRetryableStatus(res.status) && attempt < MAX_RETRIES - 1) {
await sleep(250 * 2 ** attempt + Math.floor(Math.random() * 100));
await delay(250 * 2 ** attempt + Math.floor(Math.random() * 100));
continue;
}
return res;
@@ -11,11 +11,10 @@ function isSafeShortcutHref(url: string): boolean {
}
export function CreateCustomShortcutDiv(element: any) {
// Creates the stucture and element information for each seperate shortcut
const container = document.getElementById("shortcuts");
if (!container) return;
var shortcut = document.createElement("a");
const shortcut = document.createElement("a");
if (isSafeShortcutHref(element.url)) {
shortcut.setAttribute("href", element.url);
shortcut.setAttribute("target", "_blank");
@@ -23,9 +22,8 @@ export function CreateCustomShortcutDiv(element: any) {
shortcut.setAttribute("href", "#");
shortcut.setAttribute("aria-disabled", "true");
}
var shortcutdiv = document.createElement("div");
shortcutdiv.classList.add("shortcut");
shortcutdiv.classList.add("customshortcut");
const shortcutdiv = document.createElement("div");
shortcutdiv.classList.add("shortcut", "customshortcut");
let image: ChildNode | null;
@@ -57,10 +55,9 @@ export function CreateCustomShortcutDiv(element: any) {
).firstChild;
}
(image as HTMLElement).classList.add("shortcuticondiv");
var text = document.createElement("p");
const text = document.createElement("p");
text.textContent = element.name;
shortcutdiv.append(image!);
shortcutdiv.append(text);
shortcutdiv.append(image!, text);
shortcut.append(shortcutdiv);
container.append(shortcut);
+1 -10
View File
@@ -1,12 +1,3 @@
/**
* Pauses execution for a specified number of milliseconds.
*
* This function returns a Promise that resolves after the given delay,
* allowing it to be used with `async/await` to pause asynchronous operations.
*
* @param {number} ms The number of milliseconds to delay.
* @returns {Promise<void>} A Promise that resolves after the specified delay.
*/
export function delay(ms: number) {
export function delay(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
@@ -95,7 +95,7 @@ export async function ensureSyncableStorageDefaults(): Promise<void> {
const patch: Record<string, unknown> = {};
for (const [key, value] of Object.entries(defaults)) {
if (!isKeyIncludedInCloudUploadPayload(key)) continue;
if (Object.prototype.hasOwnProperty.call(existing, key)) continue;
if (Object.hasOwn(existing, key)) continue;
if (key.startsWith("plugin.") && key.endsWith(".settings")) {
patch[key] = mergePluginSettingsDefaults(
+3 -4
View File
@@ -189,15 +189,14 @@ function badgeBlobStyle(visual: Pick<BadgeVisual, "base" | "blobs">): string {
export function founderBadgeChipHtml(
badge: BadgeItem,
options?: { hero?: boolean; titlebar?: boolean },
options?: { hero?: boolean },
): string {
const visual = badgeVisualForKey(badge.key, badge.label);
if (!visual) return "";
const hero = options?.hero ?? false;
const titlebar = options?.titlebar ?? false;
const mods = `${hero ? " bsplus-founder-badge--hero" : ""}${titlebar ? " bsplus-founder-badge--titlebar" : ""}`;
const icon = titlebar ? "" : badgeIconSvg(visual.icon, hero ? 20 : 15);
const mods = hero ? " bsplus-founder-badge--hero" : "";
const icon = badgeIconSvg(visual.icon, hero ? 20 : 15);
return `<button type="button" class="bsplus-founder-badge${mods}" data-tier="${badge.key}" style="${badgeBlobStyle(visual)}"><span class="bsplus-founder-badge__glass"><span class="bsplus-founder-badge__blobs" aria-hidden="true"></span><span class="bsplus-founder-badge__content">${icon}<span class="bsplus-founder-badge__label">${badge.label || visual.label}</span></span></span></button>`;
}
+1 -5
View File
@@ -46,7 +46,7 @@ class EventManager {
options: EventListenerOptions,
callback: (element: Element) => void,
): { unregister: () => void } {
const id = this.generateUniqueId();
const id = crypto.randomUUID();
if (!this.listeners.has(event)) {
this.listeners.set(event, []);
}
@@ -230,10 +230,6 @@ class EventManager {
if (options.customCheck && !options.customCheck(element)) return false;
return true;
}
private generateUniqueId(): string {
return "_" + Math.random().toString(36).substr(2, 9);
}
}
export const eventManager = EventManager.getInstance();
@@ -319,11 +319,6 @@ class StorageManager {
});
}
/**
* Register a listener for a setting.
* @param prop The setting to listen to.
* @param listener The listener to call when the setting changes -> takes two arguments, (newValue, oldValue)
*/
public register(prop: keyof SettingsState, listener: ChangeListener): void {
const key = prop as string;
if (!this.listeners.has(key)) {
@@ -332,35 +327,18 @@ class StorageManager {
this.listeners.get(key)!.add(listener);
}
/**
* Unregister a listener for a setting.
* @param prop The setting to stop listening to.
* @param listener The listener to remove.
*/
public unregister(prop: keyof SettingsState, listener: ChangeListener): void {
this.listeners.get(prop as string)?.delete(listener);
}
/**
* Register a listener for any setting.
* @param listener The listener to call when any setting changes -> takes three arguments, (newValue, oldValue, key)
*/
public registerGlobal(listener: GlobalChangeListener): void {
this.globalListeners.add(listener);
}
/**
* Unregister a global listener.
* @param listener The listener to remove.
*/
public unregisterGlobal(listener: GlobalChangeListener): void {
this.globalListeners.delete(listener);
}
/**
* Get all settings.
* @returns All settings.
*/
public getAll(): SettingsState {
return this.data;
}
+79 -95
View File
@@ -312,109 +312,93 @@ function startOfDay(date: Date): Date {
return new Date(date.getFullYear(), date.getMonth(), date.getDate());
}
function callHomeTimetable(date: string, change?: any) {
var xhr = new XMLHttpRequest();
xhr.open("POST", `${location.origin}/seqta/student/load/timetable?`, true);
async function callHomeTimetable(date: string, change?: any) {
const response = await fetch(`${location.origin}/seqta/student/load/timetable?`, {
method: "POST",
headers: { "Content-Type": "application/json; charset=utf-8" },
body: JSON.stringify({ from: date, until: date, student: 69 }),
});
const serverResponse = await response.json();
xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
if (loadingTimeout) {
clearTimeout(loadingTimeout);
loadingTimeout = null;
}
xhr.onreadystatechange = function () {
if (xhr.readyState !== 4) return;
const DayContainer = document.getElementById("day-container")!;
if (loadingTimeout) {
clearTimeout(loadingTimeout);
loadingTimeout = null;
}
if (serverResponse.payload.items.length > 0) {
if (DayContainer.innerText || change) {
const lessonArray: Array<any> = [...serverResponse.payload.items].sort(
(a, b) => a.from.localeCompare(b.from),
);
const DayContainer = document.getElementById("day-container")!;
GetLessonColours().then((colours) => {
for (let i = 0; i < lessonArray.length; i++) {
let subjectname =
lessonArray[i].type == "tutorial"
? `timetable.tutor.${lessonArray[i].tutorID}`
: `timetable.subject.colour.${lessonArray[i].code}`;
let subject = colours.find(
(element: any) => element.name === subjectname,
);
var serverResponse = JSON.parse(xhr.response);
let lessonArray: Array<any> = [];
if (!subject) {
lessonArray[i].colour = "--item-colour: #8e8e8e;";
} else {
lessonArray[i].colour = `--item-colour: ${subject.value};`;
if (GetThresholdOfColor(subject.value) > 300) {
lessonArray[i].invert = true;
}
}
if (serverResponse.payload.items.length > 0) {
if (DayContainer.innerText || change) {
for (let i = 0; i < serverResponse.payload.items.length; i++) {
lessonArray.push(serverResponse.payload.items[i]);
lessonArray[i].from = lessonArray[i].from.substring(0, 5);
lessonArray[i].until = lessonArray[i].until.substring(0, 5);
if (settingsState.timeFormat === "12") {
lessonArray[i].from = convertTo12HourFormat(lessonArray[i].from);
lessonArray[i].until = convertTo12HourFormat(
lessonArray[i].until,
);
}
lessonArray[i].attendanceTitle = CheckUnmarkedAttendance(
lessonArray[i].attendance,
);
}
lessonArray.sort(function (a, b) {
return a.from.localeCompare(b.from);
});
GetLessonColours().then((colours) => {
DayContainer.innerText = "";
for (let i = 0; i < lessonArray.length; i++) {
const div = makeLessonDiv(lessonArray[i], i + 1);
if (lessonArray[i].invert) {
(div.firstChild! as HTMLElement).classList.add("day-inverted");
}
DayContainer.append(div.firstChild as HTMLElement);
}
DayContainer.classList.remove("loading");
const today = new Date();
if (currentSelectedDate.getDate() == today.getDate()) {
for (let i = 0; i < lessonArray.length; i++) {
let subjectname =
lessonArray[i].type == "tutorial"
? `timetable.tutor.${lessonArray[i].tutorID}`
: `timetable.subject.colour.${lessonArray[i].code}`;
let subject = colours.find(
(element: any) => element.name === subjectname,
);
if (!subject) {
lessonArray[i].colour = "--item-colour: #8e8e8e;";
} else {
lessonArray[i].colour = `--item-colour: ${subject.value};`;
if (GetThresholdOfColor(subject.value) > 300) {
lessonArray[i].invert = true;
}
}
lessonArray[i].from = lessonArray[i].from.substring(0, 5);
lessonArray[i].until = lessonArray[i].until.substring(0, 5);
if (settingsState.timeFormat === "12") {
lessonArray[i].from = convertTo12HourFormat(lessonArray[i].from);
lessonArray[i].until = convertTo12HourFormat(
lessonArray[i].until,
);
}
lessonArray[i].attendanceTitle = CheckUnmarkedAttendance(
lessonArray[i].attendance,
);
CheckCurrentLesson(lessonArray[i], i + 1);
}
DayContainer.innerText = "";
for (let i = 0; i < lessonArray.length; i++) {
const div = makeLessonDiv(lessonArray[i], i + 1);
if (lessonArray[i].invert) {
(div.firstChild! as HTMLElement).classList.add("day-inverted");
}
DayContainer.append(div.firstChild as HTMLElement);
}
DayContainer.classList.remove("loading");
const today = new Date();
if (currentSelectedDate.getDate() == today.getDate()) {
for (let i = 0; i < lessonArray.length; i++) {
CheckCurrentLesson(lessonArray[i], i + 1);
}
CheckCurrentLessonAll(lessonArray);
}
});
}
} else {
DayContainer.innerHTML = "";
const dummyDay = document.createElement("div");
dummyDay.classList.add("day-empty");
const img = document.createElement("img");
img.src = resolveExtensionAssetUrl(LogoLight);
const text = document.createElement("p");
text.innerText = "No lessons available.";
dummyDay.append(img, text);
DayContainer.append(dummyDay);
DayContainer.classList.remove("loading");
CheckCurrentLessonAll(lessonArray);
}
});
}
};
xhr.send(
JSON.stringify({
from: date,
until: date,
student: 69,
}),
);
} else {
DayContainer.innerHTML = "";
const dummyDay = document.createElement("div");
dummyDay.classList.add("day-empty");
const img = document.createElement("img");
img.src = resolveExtensionAssetUrl(LogoLight);
const text = document.createElement("p");
text.innerText = "No lessons available.";
dummyDay.append(img, text);
DayContainer.append(dummyDay);
DayContainer.classList.remove("loading");
}
}
function CheckCurrentLessonAll(lessons: any) {
@@ -686,7 +670,7 @@ async function CreateUpcomingSection(assessments: any, activeSubjects: any) {
}
}
for (var date in upcomingDates) {
for (const date in upcomingDates) {
const assessmentdue = new Date(
(upcomingDates[date as keyof typeof upcomingDates] as any).assessments[0]
.due,
@@ -770,7 +754,7 @@ function createAssessmentDateDiv(date: string, value: any, datecase?: any) {
const subject = document.createElement("p");
subject.innerText = element.title;
subject.classList.add("upcoming-assessment-title");
subject.onclick = function () {
subject.onclick = () => {
location.href = `../#?page=/assessments/${element.programmeID}:${element.metaclassID}&item=${element.id}`;
};
detailsdiv.append(detailstitle, subject);
@@ -858,7 +842,7 @@ function CreateFilters(subjects: { code: string }[]) {
for (let i = 0; i < subjects.length; i++) {
const element = subjects[i];
if (!Object.prototype.hasOwnProperty.call(filteroptions, element.code)) {
if (!Object.hasOwn(filteroptions, element.code)) {
filteroptions[element.code] = true;
}
filterdiv!.append(
+2 -3
View File
@@ -35,7 +35,7 @@ function syncDefaultMenuOrder(menu: HTMLElement) {
for (let i = 0; i < childnodes.length; i++) {
const key = (childnodes[i] as HTMLElement).dataset.key;
if (key && settingsState.defaultmenuorder.indexOf(key) === -1) {
if (key && !settingsState.defaultmenuorder.includes(key)) {
settingsState.defaultmenuorder = [...settingsState.defaultmenuorder, key];
}
}
@@ -264,8 +264,7 @@ export function OpenMenuOptions() {
}
function saveNewOrder(sortable: Sortable) {
var order = sortable.toArray();
settingsState.menuorder = order;
settingsState.menuorder = sortable.toArray();
}
function cloneAttributes(target: any, source: any) {
@@ -12,6 +12,7 @@ import {
} from "@/interface/utils/themeStoreFlavours";
import { attachPopupMediaFullscreen } from "./attachPopupMediaFullscreen";
import { allowedPopupImageUrl } from "./allowedPopupImageUrl";
import { delay } from "@/seqta/utils/delay";
export interface ThemeOfTheMonthEntry {
id: string;
@@ -252,10 +253,6 @@ function themeOfTheMonthExpandedShellHeight(): number {
return Math.min(TOTM_EXPANDED_SHELL_MAX_PX, themeOfTheMonthMaxCardHeight());
}
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => window.setTimeout(resolve, ms));
}
// ---------------------------------------------------------------------------
// Pure-transform positioning
//
@@ -476,12 +473,12 @@ async function runThemeOfTheMonthExpand(
applyThemeOfTheMonthCardPosition(card, true, true, toH);
await sleep(TOTM_LAYOUT_SWAP_MS);
await delay(TOTM_LAYOUT_SWAP_MS);
if (gen !== themeOfTheMonthAnimGen) return;
applyExpandedLayout(card, descriptionHtml);
applyExpandedCardShell(card);
await sleep(TOTM_LAYOUT_SWAP_MS);
await delay(TOTM_LAYOUT_SWAP_MS);
if (gen !== themeOfTheMonthAnimGen) return;
card.classList.remove("themeOfTheMonthCardExpanding");
@@ -516,11 +513,11 @@ async function runThemeOfTheMonthCollapse(
applyThemeOfTheMonthCardPosition(card, false, true, toH);
await sleep(TOTM_LAYOUT_SWAP_MS);
await delay(TOTM_LAYOUT_SWAP_MS);
if (gen !== themeOfTheMonthAnimGen) return;
applyCollapsedLayout(card, descriptionHtml);
await sleep(TOTM_LAYOUT_SWAP_MS);
await delay(TOTM_LAYOUT_SWAP_MS);
if (gen !== themeOfTheMonthAnimGen) return;
card.classList.remove(
@@ -894,7 +891,7 @@ export async function showThemeOfTheMonthPopupNow(): Promise<void> {
if (document.getElementById("whatsnewbk")) {
await closePopup();
await new Promise((resolve) => setTimeout(resolve, 150));
await delay(150);
}
await OpenThemeOfTheMonthPopup(entry);
+2 -1
View File
@@ -1,5 +1,6 @@
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
import { fullMotionEffectsEnabled } from "@/seqta/utils/performanceMode";
import { delay } from "@/seqta/utils/delay";
const BACKDROP_CLASS = "bsplus-popup-css-animate";
const OPEN_CLASS = "bsplus-popup-css-animate--open";
@@ -31,5 +32,5 @@ export function animatePopupOpen(background: HTMLElement): void {
export function animatePopupClose(background: HTMLElement): Promise<void> {
if (!useCssPopupAnimation()) return Promise.resolve();
background.classList.remove(OPEN_CLASS);
return new Promise((resolve) => window.setTimeout(resolve, CLOSE_FALLBACK_MS));
return delay(CLOSE_FALLBACK_MS);
}
+1 -2
View File
@@ -283,12 +283,11 @@ export async function ensureKilledModeSettingsAccess(): Promise<void> {
if (document.getElementById("AddedSettings")) return;
parent.append(
stringToHTML(/* html */ `
<button class="addedButton tooltip" id="AddedSettings" type="button" aria-label="BetterSEQTA+ settings">
<button class="addedButton" id="AddedSettings" type="button" aria-label="BetterSEQTA+ settings">
<svg width="24" height="24" viewBox="0 0 24 24" aria-hidden="true">
<path d="M23.182,6.923c-.29,0-3.662,2.122-4.142,2.4l-2.8-1.555V4.511l4.257-2.456a.518.518,0,0,0,.233-.408.479.479,0,0,0-.233-.407,6.511,6.511,0,1,0-3.327,12.107,6.582,6.582,0,0,0,6.148-4.374,5.228,5.228,0,0,0,.333-1.542A.461.461,0,0,0,23.182,6.923Z"></path>
<path d="M9.73,10.418,7.376,12.883c-.01.01-.021.016-.03.025L1.158,19.1a2.682,2.682,0,1,0,3.793,3.793l4.583-4.582,0,0,4.1-4.005-.037-.037A9.094,9.094,0,0,1,9.73,10.418ZM3.053,21.888A.894.894,0,1,1,3.946,21,.893.893,0,0,1,3.053,21.888Z"></path>
</svg>
<div class="tooltiptext topmenutooltip">BetterSEQTA+ Settings</div>
</button>
`).firstChild!,
);
+155 -199
View File
@@ -1,217 +1,173 @@
/**
* PAGE context — patches broken menu.update.colours and removes stuck colour-dialog layers.
*/
(function () {
if (window.__bsplusMenuColoursPatched) return;
const MENU_UPDATE_COLOURS = "menu.update.colours";
const SUBJECT_PREFIX = "timetable.subject.colour.";
const TUTOR_PREFIX = "timetable.tutor.";
const CLEANUP_FOLLOWUP_MS = 300;
let cleanupFollowup = null;
var MENU_UPDATE_COLOURS = "menu.update.colours";
var SUBJECT_PREFIX = "timetable.subject.colour.";
var TUTOR_PREFIX = "timetable.tutor.";
var CLEANUP_FOLLOWUP_MS = 300;
var cleanupFollowup = null;
function isTesStyling() {
return document.getElementById("logo-style")?.textContent.includes("tesSeqta") ?? false;
}
function isTesStyling() {
var el = document.getElementById("logo-style");
return el && el.textContent.indexOf("tesSeqta") !== -1;
function dismissStaleDialogs(forceColour) {
for (const pane of document.querySelectorAll(".uiSlidePane")) {
if (pane.querySelector(".pane.colourChooser")) {
pane.remove();
continue;
}
if (!forceColour && pane.classList.contains("shown")) continue;
if (!pane.classList.contains("shown")) pane.remove();
}
function dismissStaleDialogs(forceColour) {
var slide = 0;
var panes = document.querySelectorAll(".uiSlidePane");
for (var i = 0; i < panes.length; i++) {
var p = panes[i];
if (p.querySelector(".pane.colourChooser")) {
p.remove();
slide++;
continue;
}
if (!forceColour && p.classList.contains("shown")) continue;
if (!p.classList.contains("shown")) {
p.remove();
slide++;
}
for (const container of document.querySelectorAll(".modaliser-container")) {
const modal = container.querySelector(".modaliser");
if (!modal?.childElementCount || !container.classList.contains("visible")) {
container.remove();
}
var modal = 0;
var containers = document.querySelectorAll(".modaliser-container");
for (var j = 0; j < containers.length; j++) {
var c = containers[j];
var m = c.querySelector(".modaliser");
if (!m || !m.childElementCount || !c.classList.contains("visible")) {
c.remove();
modal++;
}
}
document.body.classList.remove("clr-open");
document.documentElement.classList.remove("clr-open");
return { slideRemoved: slide, modalRemoved: modal };
}
function scheduleCleanup() {
document.body.classList.remove("clr-open");
document.documentElement.classList.remove("clr-open");
}
function scheduleCleanup() {
dismissStaleDialogs(true);
clearTimeout(cleanupFollowup);
cleanupFollowup = setTimeout(() => {
cleanupFollowup = null;
dismissStaleDialogs(true);
if (cleanupFollowup) clearTimeout(cleanupFollowup);
cleanupFollowup = setTimeout(function () {
cleanupFollowup = null;
dismissStaleDialogs(true);
}, CLEANUP_FOLLOWUP_MS);
}
}, CLEANUP_FOLLOWUP_MS);
}
function applyMenuColours() {
if (!window.user) return;
var def = isTesStyling() ? "#2b3547" : "#dddddd";
var items = document.querySelectorAll("#menu li[data-colour]");
for (var i = 0; i < items.length; i++) {
var item = items[i];
var prefName = item.getAttribute("data-colour");
if (!prefName) continue;
var pref = window.user.getPreference(prefName);
item.style.setProperty("--item-colour", (pref && pref.value) || def);
function applyMenuColours() {
if (!window.user) return;
const fallback = isTesStyling() ? "#2b3547" : "#dddddd";
for (const item of document.querySelectorAll("#menu li[data-colour]")) {
const prefName = item.getAttribute("data-colour");
if (!prefName) continue;
const pref = window.user.getPreference(prefName);
item.style.setProperty("--item-colour", pref?.value || fallback);
}
}
function reconcileQuickbars() {
let fixed = 0;
for (const quickbar of document.querySelectorAll(".timetablepage .quickbar.visible")) {
if (!quickbar.querySelector(".wrapper")?.childElementCount) {
quickbar.classList.remove("visible");
fixed++;
}
}
function reconcileQuickbars() {
var fixed = 0;
var quickbars = document.querySelectorAll(".timetablepage .quickbar.visible");
for (var i = 0; i < quickbars.length; i++) {
var qb = quickbars[i];
var w = qb.querySelector(".wrapper");
if (!w || !w.childElementCount) {
qb.classList.remove("visible");
fixed++;
}
}
if (fixed) {
try {
window.msg.send("calendar.quickbar.hide");
} catch (err) {
/* ignore */
}
}
return fixed;
}
function findEntry(calendarId, code) {
if (calendarId) {
var byId = document.querySelector(
".timetablepage .entry[data-calendarid=\"" + calendarId + "\"]",
);
if (byId) return byId;
}
if (!code) return null;
var entries = document.querySelectorAll(".timetablepage .entry.class");
for (var i = 0; i < entries.length; i++) {
var entry = entries[i];
var titleEl = entry.querySelector(".title");
var title =
titleEl && titleEl.textContent ? titleEl.textContent.trim() : "";
if (title && title.indexOf(code) !== -1) return entry;
}
return null;
}
function normalizeQuickbarContext(contents) {
if (!contents) return contents;
reconcileQuickbars();
var element = contents.element;
var calendarId =
(element && element.getAttribute && element.getAttribute("data-calendarid")) ||
(contents.data && contents.data.calendarid);
var code = contents.data && contents.data.code;
var connected =
element &&
element.isConnected &&
typeof document.contains === "function" &&
document.contains(element);
if (!connected) {
var replacement = findEntry(calendarId, code);
if (replacement) contents.element = replacement;
}
return contents;
}
function isColourPref(handle) {
return (
typeof handle === "string" &&
(handle.indexOf(SUBJECT_PREFIX) === 0 || handle.indexOf(TUTOR_PREFIX) === 0)
);
}
function onMenuColourUpdate() {
if (fixed) {
try {
applyMenuColours();
} catch (err) {
console.error("[BetterSEQTA+] menu.update.colours failed:", err);
window.msg.send("calendar.quickbar.hide");
} catch {}
}
}
function findEntry(calendarId, code) {
if (calendarId) {
const byId = document.querySelector(
`.timetablepage .entry[data-calendarid="${CSS.escape(calendarId)}"]`,
);
if (byId) return byId;
}
if (!code) return null;
for (const entry of document.querySelectorAll(".timetablepage .entry.class")) {
const title = entry.querySelector(".title")?.textContent?.trim() ?? "";
if (title.includes(code)) return entry;
}
return null;
}
function normalizeQuickbarContext(contents) {
if (!contents) return contents;
reconcileQuickbars();
const { element } = contents;
if (!element?.isConnected) {
const calendarId = element?.getAttribute?.("data-calendarid") || contents.data?.calendarid;
const replacement = findEntry(calendarId, contents.data?.code);
if (replacement) contents.element = replacement;
}
return contents;
}
function isColourPref(handle) {
return (
typeof handle === "string" &&
(handle.startsWith(SUBJECT_PREFIX) || handle.startsWith(TUTOR_PREFIX))
);
}
function onMenuColourUpdate() {
try {
applyMenuColours();
} catch (err) {
console.error("[BetterSEQTA+] menu.update.colours failed:", err);
}
scheduleCleanup();
reconcileQuickbars();
}
function neutralizeBrokenListeners(msg) {
for (const listener of msg.listeners?.[MENU_UPDATE_COLOURS] ?? []) {
if (listener) listener.fn = onMenuColourUpdate;
}
}
function patchMsg(msg) {
if (!msg || msg.__bsplusPatched) return;
const send = msg.send.bind(msg);
const register = msg.register.bind(msg);
msg.send = (handle, contents, suppressLogs, noRecord) => {
if (handle === MENU_UPDATE_COLOURS) {
onMenuColourUpdate();
return;
}
scheduleCleanup();
reconcileQuickbars();
}
function neutralizeBrokenListeners(msg) {
var listeners = msg.listeners && msg.listeners[MENU_UPDATE_COLOURS];
if (!listeners) return;
for (var i = 0; i < listeners.length; i++) {
if (listeners[i]) listeners[i].fn = onMenuColourUpdate;
if (isColourPref(handle)) {
const result = send(handle, contents, suppressLogs, noRecord);
scheduleCleanup();
reconcileQuickbars();
return result;
}
}
if (handle === "calendar.quickbar.class") {
return send(handle, normalizeQuickbarContext(contents), suppressLogs, noRecord);
}
return send(handle, contents, suppressLogs, noRecord);
};
function patchMsg(msg) {
if (!msg || msg.__bsplusPatched) return;
msg.register = (handle, callback, clear, ignoreHistory) =>
register(
handle,
handle === MENU_UPDATE_COLOURS ? onMenuColourUpdate : callback,
clear,
ignoreHistory,
);
var send = msg.send.bind(msg);
var register = msg.register.bind(msg);
neutralizeBrokenListeners(msg);
msg.__bsplusPatched = true;
}
msg.send = function (handle, contents, suppressLogs, noRecord) {
if (handle === MENU_UPDATE_COLOURS) {
onMenuColourUpdate();
return;
}
if (isColourPref(handle)) {
var result = send(handle, contents, suppressLogs, noRecord);
scheduleCleanup();
reconcileQuickbars();
return result;
}
if (handle === "calendar.quickbar.class") {
return send(
handle,
normalizeQuickbarContext(contents),
suppressLogs,
noRecord,
);
}
return send(handle, contents, suppressLogs, noRecord);
};
function tryPatch() {
if (window.__bsplusMenuColoursPatched) return true;
if (!window.msg?.send) return false;
patchMsg(window.msg);
window.__bsplusMenuColoursPatched = true;
return true;
}
msg.register = function (handle, callback, clear, ignoreHistory) {
if (handle === MENU_UPDATE_COLOURS) {
return register(handle, onMenuColourUpdate, clear, ignoreHistory);
}
return register(handle, callback, clear, ignoreHistory);
};
neutralizeBrokenListeners(msg);
msg.__bsplusPatched = true;
}
function tryPatch() {
if (window.__bsplusMenuColoursPatched) return true;
if (!window.msg || !window.msg.send) return false;
patchMsg(window.msg);
window.__bsplusMenuColoursPatched = true;
return true;
}
if (!tryPatch()) {
var delay = 25, waited = 0;
(function poll() {
if (tryPatch() || (waited += delay) >= 120000) return;
if (window.msg) neutralizeBrokenListeners(window.msg);
setTimeout(poll, delay = Math.min(delay * 2, 2000));
})();
}
})();
if (!tryPatch()) {
let interval = 25;
let waited = 0;
const poll = () => {
if (tryPatch() || (waited += interval) >= 120000) return;
if (window.msg) neutralizeBrokenListeners(window.msg);
interval = Math.min(interval * 2, 2000);
setTimeout(poll, interval);
};
poll();
}
-12
View File
@@ -1,17 +1,5 @@
import DOMPurify from "dompurify";
/**
* Converts an HTML string into a DOM element, with sanitization and optional styling.
*
* This function first sanitizes the input HTML string using DOMPurify to prevent XSS attacks.
* The sanitization process allows only safe URI schemes in links and media.
* Then, it parses the sanitized string into an HTML document and returns its body.
* Optionally, it can apply predefined CSS styles to the body element.
*
* @param {string} str The HTML string to convert.
* @param {boolean} [styles=false] Whether to apply predefined styles to the document body.
* @returns {HTMLElement} The body element of the parsed and sanitized HTML document.
*/
export default function stringToHTML(str: string, styles = false) {
const parser = new DOMParser();
+153 -179
View File
@@ -1,205 +1,179 @@
/**
* PAGE context only — theme CustomCSS and decorative image variables must live
* in page-origin stylesheets. Extension-injected #custom-theme cannot load
* page blob: URLs referenced via var() on Firefox.
*/
(function () {
if (window.__bsplusThemePagePatched) return;
window.__bsplusThemePagePatched = true;
import { base64ToBlob } from "./base64.ts";
var LOG = "[BetterSEQTA+] theme page:";
var BRIDGE_ID = "bsplus-theme-image-bridge";
var PAYLOAD_ID = "bsplus-theme-image-payload";
var IMAGES_STYLE_ID = "bsplus-theme-images";
var THEME_STYLE_ID = "custom-theme";
var PREVIEW_STYLE_ID = "custom-theme-preview";
var OVERLAY_STYLE_ID = "bsplus-remote-theme-overlay";
var OVERLAY_IMAGES_STYLE_ID = "bsplus-remote-theme-overlay-images";
var urlCache = {};
var overlayUrlCache = {};
var headObserver = null;
const LOG = "[BetterSEQTA+] theme page:";
const BRIDGE_ID = "bsplus-theme-image-bridge";
const PAYLOAD_ID = "bsplus-theme-image-payload";
const IMAGES_STYLE_ID = "bsplus-theme-images";
const THEME_STYLE_ID = "custom-theme";
const PREVIEW_STYLE_ID = "custom-theme-preview";
const OVERLAY_STYLE_ID = "bsplus-remote-theme-overlay";
const OVERLAY_IMAGES_STYLE_ID = "bsplus-remote-theme-overlay-images";
const urlCache = new Set();
const overlayUrlCache = new Set();
let headObserver = null;
function log(event, detail) {
if (!document.documentElement.hasAttribute("data-bsplus-verbose-log")) return;
console.info(LOG, event, detail);
function log(event, detail) {
if (!document.documentElement.hasAttribute("data-bsplus-verbose-log")) return;
console.info(LOG, event, detail);
}
function releaseCache(cache) {
for (const url of cache) URL.revokeObjectURL(url);
cache.clear();
}
function styleEl(id) {
let el = document.getElementById(id);
if (!el) {
el = document.createElement("style");
el.id = id;
document.head.appendChild(el);
}
return el;
}
function base64ToBlob(base64, mime) {
var bytes = atob(base64);
var ab = new ArrayBuffer(bytes.length);
var view = new Uint8Array(ab);
for (var i = 0; i < bytes.length; i++) view[i] = bytes.charCodeAt(i);
return new Blob([ab], { type: mime || "image/png" });
function keepOverlayStylesLast() {
for (const id of [OVERLAY_IMAGES_STYLE_ID, OVERLAY_STYLE_ID]) {
const el = document.getElementById(id);
if (el && document.head.contains(el)) document.head.appendChild(el);
}
}
function releaseCache(cache) {
for (var key in cache) {
if (!Object.prototype.hasOwnProperty.call(cache, key)) continue;
try {
URL.revokeObjectURL(cache[key]);
} catch (e) {}
}
for (key in cache) {
if (Object.prototype.hasOwnProperty.call(cache, key)) delete cache[key];
function keepThemeStyleLast() {
const themeStyle = document.getElementById(THEME_STYLE_ID);
if (themeStyle && document.head.contains(themeStyle) && document.head.lastElementChild !== themeStyle) {
document.head.appendChild(themeStyle);
}
keepOverlayStylesLast();
}
function watchHead() {
if (headObserver) return;
headObserver = new MutationObserver(keepThemeStyleLast);
headObserver.observe(document.head, { childList: true });
}
function setStyleText(id, text, watchThemeOrder) {
if (!text) {
document.getElementById(id)?.remove();
return;
}
styleEl(id).textContent = text;
if (watchThemeOrder) {
watchHead();
keepThemeStyleLast();
}
}
function applyRootImages(images, styleId, cache, afterApply) {
releaseCache(cache);
if (!images?.length) {
document.getElementById(styleId)?.remove();
return;
}
const lines = [":root {"];
for (const img of images) {
if (!img?.variableName || !img.data) continue;
try {
const url = URL.createObjectURL(base64ToBlob(img.data, img.mime || "image/png"));
cache.add(url);
lines.push(` --${img.variableName}: url("${url}");`);
} catch (e) {
console.warn(LOG, "skip image", img.variableName, e);
}
}
lines.push("}");
styleEl(styleId).textContent = lines.join("\n");
afterApply?.();
log("images applied", { styleId, count: images.length });
}
function styleEl(id) {
var el = document.getElementById(id);
if (!el) {
el = document.createElement("style");
el.id = id;
document.head.appendChild(el);
}
return el;
function clearOverlayOnly() {
releaseCache(overlayUrlCache);
document.getElementById(OVERLAY_STYLE_ID)?.remove();
document.getElementById(OVERLAY_IMAGES_STYLE_ID)?.remove();
log("overlay cleared");
}
function clearAll() {
releaseCache(urlCache);
setStyleText(IMAGES_STYLE_ID, "");
document.getElementById(THEME_STYLE_ID)?.remove();
document.getElementById(PREVIEW_STYLE_ID)?.remove();
headObserver?.disconnect();
headObserver = null;
log("cleared");
}
function processPayload() {
const raw = document.getElementById(PAYLOAD_ID)?.value;
if (!raw) {
clearAll();
return;
}
function keepOverlayStylesLast() {
var overlayImages = document.getElementById(OVERLAY_IMAGES_STYLE_ID);
var overlayCss = document.getElementById(OVERLAY_STYLE_ID);
if (overlayImages && document.head.contains(overlayImages)) {
document.head.appendChild(overlayImages);
}
if (overlayCss && document.head.contains(overlayCss)) {
document.head.appendChild(overlayCss);
}
}
function keepThemeStyleLast() {
var themeStyle = document.getElementById(THEME_STYLE_ID);
if (themeStyle && document.head.contains(themeStyle) && document.head.lastElementChild !== themeStyle) {
document.head.appendChild(themeStyle);
}
keepOverlayStylesLast();
}
function watchHead() {
if (headObserver) return;
headObserver = new MutationObserver(keepThemeStyleLast);
headObserver.observe(document.head, { childList: true });
}
function setStyleText(id, text, watchThemeOrder) {
if (!text) {
document.getElementById(id)?.remove();
return;
}
styleEl(id).textContent = text;
if (watchThemeOrder) {
watchHead();
keepThemeStyleLast();
}
}
function applyRootImages(images, styleId, cache, afterApply) {
releaseCache(cache);
if (!images?.length) {
document.getElementById(styleId)?.remove();
return;
}
var lines = [":root {"];
for (var i = 0; i < images.length; i++) {
var img = images[i];
if (!img?.variableName || !img.data) continue;
try {
var url = URL.createObjectURL(base64ToBlob(img.data, img.mime));
cache[img.variableName] = url;
lines.push(' --' + img.variableName + ': url("' + url + '");');
} catch (e) {
console.warn(LOG, "skip image", img.variableName, e);
}
}
lines.push("}");
styleEl(styleId).textContent = lines.join("\n");
if (afterApply) afterApply();
log("images applied", { styleId: styleId, count: images.length });
}
function clearOverlayOnly() {
releaseCache(overlayUrlCache);
document.getElementById(OVERLAY_STYLE_ID)?.remove();
document.getElementById(OVERLAY_IMAGES_STYLE_ID)?.remove();
log("overlay cleared");
}
function clearAll() {
releaseCache(urlCache);
setStyleText(IMAGES_STYLE_ID, "");
document.getElementById(THEME_STYLE_ID)?.remove();
document.getElementById(PREVIEW_STYLE_ID)?.remove();
headObserver?.disconnect();
headObserver = null;
log("cleared");
}
function processPayload() {
var raw = document.getElementById(PAYLOAD_ID)?.value;
if (!raw) {
try {
const payload = JSON.parse(raw);
if (!payload || payload.clear) {
clearAll();
return;
}
try {
var payload = JSON.parse(raw);
if (!payload || payload.clear) {
clearAll();
return;
}
if (payload.clearOverlay) {
clearOverlayOnly();
return;
}
if (payload.images !== undefined) {
applyRootImages(payload.images, IMAGES_STYLE_ID, urlCache);
}
if (payload.customCss !== undefined) {
setStyleText(THEME_STYLE_ID, payload.customCss || "", true);
log("custom css applied");
}
if (payload.overlayImages !== undefined) {
applyRootImages(payload.overlayImages, OVERLAY_IMAGES_STYLE_ID, overlayUrlCache, keepOverlayStylesLast);
}
if (payload.overlayCss !== undefined) {
setStyleText(OVERLAY_STYLE_ID, payload.overlayCss || "", false);
keepOverlayStylesLast();
log("overlay css applied");
}
if (payload.previewCss !== undefined) {
setStyleText(PREVIEW_STYLE_ID, payload.previewCss || "");
var previewStyle = document.getElementById(PREVIEW_STYLE_ID);
if (previewStyle) document.head.appendChild(previewStyle);
}
if (payload.clearPreview) setStyleText(PREVIEW_STYLE_ID, "");
} catch (e) {
console.warn(LOG, "invalid payload", e);
if (payload.clearOverlay) {
clearOverlayOnly();
return;
}
if (payload.images !== undefined) {
applyRootImages(payload.images, IMAGES_STYLE_ID, urlCache);
}
if (payload.customCss !== undefined) {
setStyleText(THEME_STYLE_ID, payload.customCss || "", true);
log("custom css applied");
}
if (payload.overlayImages !== undefined) {
applyRootImages(payload.overlayImages, OVERLAY_IMAGES_STYLE_ID, overlayUrlCache, keepOverlayStylesLast);
}
if (payload.overlayCss !== undefined) {
setStyleText(OVERLAY_STYLE_ID, payload.overlayCss || "", false);
keepOverlayStylesLast();
log("overlay css applied");
}
if (payload.previewCss !== undefined) {
setStyleText(PREVIEW_STYLE_ID, payload.previewCss || "");
const previewStyle = document.getElementById(PREVIEW_STYLE_ID);
if (previewStyle) document.head.appendChild(previewStyle);
}
if (payload.clearPreview) setStyleText(PREVIEW_STYLE_ID, "");
} catch (e) {
console.warn(LOG, "invalid payload", e);
}
}
function ensureBridge() {
if (!document.getElementById(PAYLOAD_ID)) {
var payload = document.createElement("textarea");
payload.id = PAYLOAD_ID;
payload.hidden = true;
payload.setAttribute("aria-hidden", "true");
payload.tabIndex = -1;
document.documentElement.appendChild(payload);
}
if (!document.getElementById(BRIDGE_ID)) {
var bridge = document.createElement("div");
bridge.id = BRIDGE_ID;
bridge.hidden = true;
bridge.setAttribute("aria-hidden", "true");
document.documentElement.appendChild(bridge);
}
function ensureBridge() {
if (!document.getElementById(PAYLOAD_ID)) {
const payload = document.createElement("textarea");
payload.id = PAYLOAD_ID;
payload.hidden = true;
payload.setAttribute("aria-hidden", "true");
payload.tabIndex = -1;
document.documentElement.appendChild(payload);
}
if (!document.getElementById(BRIDGE_ID)) {
const bridge = document.createElement("div");
bridge.id = BRIDGE_ID;
bridge.hidden = true;
bridge.setAttribute("aria-hidden", "true");
document.documentElement.appendChild(bridge);
}
}
if (!window.__bsplusThemePagePatched) {
window.__bsplusThemePagePatched = true;
ensureBridge();
new MutationObserver(processPayload).observe(document.getElementById(BRIDGE_ID), {
attributes: true,
attributeFilter: ["data-rev"],
});
processPayload();
log("patch active");
})();
}
-14
View File
@@ -1,17 +1,3 @@
/**
* Asynchronously waits for an element to be present in the DOM.
*
* By default uses direct `querySelector` plus a targeted `MutationObserver`
* on `document.documentElement`. Polling via `setTimeout` is available as a
* fallback when `usePolling` is true.
*
* @param {string} selector The CSS selector for the target element.
* @param {boolean} [usePolling=false] If true, forces the use of `setTimeout` for polling.
* @param {number} [interval=100] The polling interval in milliseconds (only applicable if `usePolling` is true).
* @param {number} [maxIterations] Optional. The maximum number of polling attempts before rejecting (only applicable if `usePolling` is true).
* @returns {Promise<Element>} A Promise that resolves with the found DOM Element.
* If `usePolling` is true and `maxIterations` is reached, the Promise rejects with an Error.
*/
export async function waitForElm(
selector: string,
usePolling: boolean = false,
+1 -1
View File
@@ -1,5 +1,5 @@
import { defineConfig, loadEnv } from "vite";
import { join, resolve } from "path";
import { join, resolve } from "node:path";
import touchGlobalCSSPlugin from "./lib/touchGlobalCSS.ts";
import InlineWorkerPlugin from "./lib/inlineWorker.ts";