diff --git a/README.md b/README.md index 01469d9a..ce0bcc75 100644 --- a/README.md +++ b/README.md @@ -77,7 +77,7 @@ Those comparisons, and the kit's own build, which carries the documentation onto `npm test` runs every test past the others' failures: the nativeElement assertions check, the browser APIs check, the OnPush strategies check, the poll and test limits check, the part glyphs check, on Linux x64 only the Kit bundles, the Kit copies, the Kit manifest and Angular's newest, the kit's Node.js tests, `src/noldova.ui.components.angular/tests/node/*.test.ts`, with `node --test`, of the symbols entry, the stylesheets that load the symbol font and the browser APIs check, which no browser loads, and the kit's Angular specs, which must each report a result, with no test identity, the spec file and the titles of its suites and test, repeated, then, on Linux only, builds the docs site and tests it, as `npm run docs:build` and `npm run docs:test` do, as the static site it serves is the same on every platform. With `NOLDOVA_SEPARATE_TEST=docs`, as the CI targets' tests set it, `npm test` leaves the docs site out, and the CI run's "Separate test" job checks it once, with `npm run build` and `npm run test:docs`. -The kit's Angular specs run in two runs of Angular's test builder, each in a browser of its own: first every test but those in a `describe(LayoutTraceFixture.suite, ...)`, then, from the spec files that hold one, only those. A layout trace records every tab of its browser, so in the first browser, under the whole suite, one could take over 10 seconds to end and keep another spec's trace from starting ([#198](https://github.com/noldova-com/ui-components/issues/198)); in the second only the tracing tests run. Both runs use the Angular `part` configuration, and the script adds up their coverage as `npm run test:merge` does below, gating it on a whole run. The suite's title is in `src/noldova.ui.components.angular/tests/fixtures/layout-trace-suite.ts`, which the fixture and the script both read. After both runs, the script fails unless each test in either run's report passed or failed in exactly one of them, and the second run ran at least one test, so a traced test that both filters skip, or that both run, fails the run. Each run sets `DEBUG` to `vitest:browser:playwright,vitest:browser:api`, added to any `DEBUG` already set, so its log holds the Playwright provider's few lines on each browser session, the last of which means the page's loading began, and the browser API's on each session's orchestrator socket: its connects, its disconnects, a reconnect refused because its session closed, and pings it stopped answering; the script leaves the browser API's line on each command a test runs out of the log. When a session fails to connect within Vitest's connect timeout, on either output, the script names the browser's last stage, and each session's last provider stage and what its orchestrator did, from those lines ([#143](https://github.com/noldova-com/ui-components/issues/143)). +The kit's Angular specs run in two runs of Angular's test builder, each in a browser of its own: first every test but those in a `describe(LayoutTraceFixture.suite, ...)`, then, from the spec files that hold one, only those. A layout trace records every tab of its browser, so in the first browser, under the whole suite, one could take over 10 seconds to end and keep another spec's trace from starting ([#198](https://github.com/noldova-com/ui-components/issues/198)); in the second only the tracing tests run. The spec files that run alone, as [Tests that run alone](#tests-that-run-alone) lists, take a third run of their own, with the builder's `isolate` option on, and the first two leave them out. Every run uses the Angular `part` configuration, and the script adds up their coverage as `npm run test:merge` does below, gating it on a whole run. The suite's title is in `src/noldova.ui.components.angular/tests/fixtures/layout-trace-suite.ts`, which the fixture and the script both read. After the runs, the script fails unless each test in any run's report passed or failed in exactly one of them, and each run after the first ran at least one test, so a traced test that both filters skip, or that both run, fails the run. Each run sets `DEBUG` to `vitest:browser:playwright,vitest:browser:api`, added to any `DEBUG` already set, so its log holds the Playwright provider's few lines on each browser session, the last of which means the page's loading began, and the browser API's on each session's orchestrator socket: its connects, its disconnects, a reconnect refused because its session closed, and pings it stopped answering; the script leaves the browser API's line on each command a test runs out of the log. When a session fails to connect within Vitest's connect timeout, on either output, the script names the browser's last stage, and each session's last provider stage and what its orchestrator did, from those lines ([#143](https://github.com/noldova-com/ui-components/issues/143)). `npm test -- --shard=/`, with 2 to 8 parts, runs only every ``-th spec file of the kit's sorted list, from the ``-th, with the Angular `part` configuration, which keeps the coverage report in `_build/angular-coverage` without gating it, and runs the checks and the Node.js tests before the specs only in part 1. `npm run test:merge -- `, with Node.js alone, first checks itself on small reports in a temporary folder, then adds up the coverage of the parts, each in a subfolder of ``, by where each function, statement and branch sits in its file, from only the parts that loaded the file, since a part that never loaded it maps it from its source and can map it otherwise, and fails as `npm test` does below the requirement in [Coverage](#coverage), naming what no part reached; it also fails when fewer subfolders than `` came, or when one holds no report or one that isn't JSON. `npm test -- ...` runs only the spec files and Node.js tests whose path from the repository root holds a filter, without the coverage gates, the nativeElement assertions check, the browser APIs check, the OnPush strategies check, the poll and test limits check, the part glyphs check, the Kit bundles, the Kit copies, the Kit manifest, Angular's newest and the docs site, and fails when nothing matches. @@ -232,8 +232,8 @@ Every spec here, the kit's and the docs site's, is a component spec, since each `npm run test:timing` is the timing check, apart from `npm test` since its pass condition is a time. It runs the kit's specs three times without coverage, and on Linux the docs site's too, as their tests run only there. In the kit's folder, `npm run test:timing -- ...`, such as `npm run test:timing -- code-block-run.component.spec.ts`, times only the kit's spec files so named, in the same parts, and fails naming any name no spec file has or two spec files share, which a path from the kit's folder, such as `tests/styles/theme.spec.ts`, tells apart; from the repository's root the docs site's check refuses names and fails, since it times its whole suite; the test machines take only such runs of the specs a change touches, never the whole suite. -Each of the kit's runs is two runs of Angular's test builder, as `npm test`'s are, so the tests in a `describe(LayoutTraceFixture.suite, ...)` trace in a browser of their own; in one browser under the whole suite, a trace could hold it past the next trace's wait ([#198](https://github.com/noldova-com/ui-components/issues/198)). -A run fails, and the check times nothing, unless each test in the two reports passed or failed in exactly one of them and the second ran at least one test. +Each of the kit's runs is two runs of Angular's test builder, and a third for the spec files that run alone, as `npm test`'s are, so the tests in a `describe(LayoutTraceFixture.suite, ...)` trace in a browser of their own; in one browser under the whole suite, a trace could hold it past the next trace's wait ([#198](https://github.com/noldova-com/ui-components/issues/198)). +A run fails, and the check times nothing, unless each test in the reports passed or failed in exactly one of them and each report after the first ran at least one test. It takes each test's median over the runs, with `TestTimingCheck.median` from `@noldova/context.testing`, so one slow run decides nothing, and fails a spec file whose tests' median is over 100 ms plus a margin of 20%. It also prints each test whose median is over 1 second, which the list below holds. Its code is `src/noldova.ui.components.angular/scripts/angular/angular-test-timing.ts`, run by `scripts/angular/angular-timing-script.ts`, which each package's `scripts/test-timing.ts` or `scripts/test-docs-timing.ts` starts. @@ -536,10 +536,31 @@ Before each spec file, it also sets the emulated media to no reduced motion and `src/noldova.ui.components.angular/tests/typescript-grammar.setup.ts` keeps one property of its own on the page's `window`, `nolTypeScriptWarming`, the page's one TypeScript warming, which Time per file explains: a setup file and the modules it imports load again for each spec file, while the files on one page share its window. Specs emulate media only through `src/noldova.ui.components.angular/tests/fixtures/emulated-media.fixture.ts`, which the motion and forced-colors fixtures use: each emulation call replaces the whole emulated set, so the fixture sends every feature each time. A spy's own `mockRestore()` leaves its restore in Vitest's registry, where a later spec file's `vi.restoreAllMocks()` runs it again, so a test that spies on a faked timer global restores it with `vi.restoreAllMocks()`. -One spec fakes a timer global in the shared page, by the maintainer's decision: `src/noldova.ui.components.angular/tests/testing/services/kit-stylesheet-fixture.spec.ts` fakes `setTimeout` to reach `KitStylesheetFixture`'s 30 s load deadline and the 5 s limit on its diagnostic fetch of a font that failed. -No event can stand in for a load or an answer that never comes, and the fixture is a public helper with no injected time source; the spec restores the timers in its `afterEach`. -A spec that needs its own resize observers, to hold, count or call their callbacks, provides them through `ResizeTokens.observers` in `src/noldova.ui.components.angular/src/app/models/resize-tokens.ts`, whose default starts the browser's own, with one of the fake sources in `src/noldova.ui.components.angular/tests/fixtures`, such as `CountingResizeObserversFixture`; no spec replaces the global `ResizeObserver`, since the specs that run after it on the page would see the replacement. -No test needs a resource that the operating system can't isolate per process, so none runs alone. +By the maintainer's decision, `src/noldova.ui.components.angular/tests/testing/services/kit-stylesheet-fixture.spec.ts` fakes `setTimeout` to reach `KitStylesheetFixture`'s 30 s load deadline and the 5 s limit on its diagnostic fetch of a font that failed. +No event can stand in for a load or an answer that never comes, and the fixture is a public helper with no injected time source; the spec restores the timers in its `afterEach`, and it runs alone, as the table below says. +A spec that needs its own resize observers, to hold, count or call their callbacks, provides them through `ResizeTokens.observers` in `src/noldova.ui.components.angular/src/app/models/resize-tokens.ts`, whose default starts the browser's own, with one of the fake sources in `src/noldova.ui.components.angular/tests/fixtures`, such as `CountingResizeObserversFixture`. +A spec that reads media queries provides them through `MediaTokens.queries` in `src/noldova.ui.components.angular/src/app/models/media-tokens.ts`, whose default reads the browser's own. +A spec that waits on frames provides a time source through `ClockTokens.timeSource`, a spec of `SystemTimeSource` gives it idle callbacks of its own, and a spec under Vitest's fake timers counts the frames still waiting with `vi.getTimerCount()`. +A spec that checks a browser without the CSS Custom Highlight API calls `CodeHighlightsFixture.withoutHighlightApi()`, which provides `false` for `HighlightTokens.available` in `src/noldova.ui.components.angular/src/app/models/highlight-tokens.ts`, whose default finds the page's own API, so the page keeps its `Highlight` and `CSS.highlights`. + +No spec replaces a global in the shared page, a property of its window such as `ResizeObserver`, `matchMedia`, `Date.now` or `console`, since the specs that run after it on the page would see the replacement. +The one exception is Vitest's fake timers, which replace `setTimeout`, `requestAnimationFrame`, `Date` and the page's other timer globals while a test runs: seven spec files on the shared page use them, `api/index.spec.ts`, `app/components/markdown-view/markdown-view.component.spec.ts`, `app/components/message/message-run.component.spec.ts`, `app/models/markdown-reveal.spec.ts`, `app/models/text-reveal.spec.ts`, `testing/services/appearance-fixture.spec.ts` and `testing/services/markdown-fixture.spec.ts`, in `src/noldova.ui.components.angular/tests`. Each restores them with `vi.useRealTimers()` after each test, and the shared page's setup, above, fails a test that leaves one replaced. +A spec file that has to, to check how the kit behaves where a browser feature is missing or broken, or to read what reaches only the console, is listed in `src/noldova.ui.components.angular/tests/fixtures/isolated-specs.ts` and runs alone. +`npm test` leaves the listed files out of the shared page's run and runs them in a run of their own, with the Angular test builder's `isolate` option on, which loads each file in a page of its own, with its own window; it merges that run's coverage with the others' before the coverage gate, and fails when the list names a file that doesn't exist. + +| File, in `src/noldova.ui.components.angular/tests` | Why it runs alone | +|---|---| +| `app/components/code-block/code-block-server.component.spec.ts`, `app/components/site-card/site-card.component.spec.ts`, `app/components/site-hero/site-hero.component.spec.ts`, `app/components/site-theme-switch/site-theme-switch.component.spec.ts` | Each sets Angular's own `ngServerMode` global, which decides whether render hooks run, to render as a server does. | +| `app/models/link-reference-color.spec.ts` | Removes `CSS`, as when the package loads in Node.js. | +| `app/models/markdown-link.spec.ts` | Replaces `URL` with one that parses a drive path as Windows does, and `decodeURIComponent` with one that throws an error other than a broken encoding. | +| `app/models/mention-value.spec.ts` | Replaces `decodeURIComponent` with one that throws an error other than a broken encoding. | +| `app/services/code-highlighter-time-limit.spec.ts` | Replaces `Date.now` with a clock that jumps, to reach the time limit for a line, which Shiki's own tokenizer reads from `Date.now`, so no injected clock can stand in for it. | +| `app/services/overlay-bounds-server.service.spec.ts` | Spies on the window's `addEventListener` to check that the service listens for nothing outside a browser, where it measures nothing, so no listener's effect shows; the service's other specs share the page. | +| `testing/services/kit-stylesheet-fixture.spec.ts` | Replaces `fetch` to answer the fixture's diagnostic fetch of a font; `KitStylesheetFixture` is a public helper with no injected fetch. | +| `app/components/mention-field/mention-field-chips.spec.ts` | Spies on `console.warn` for the field's warning, in development, that its parent isn't positioned. | +| `app/components/message/message.component.spec.ts` | Spies on `console.warn` for Angular's warning of an output emitted after its component is destroyed. | +| `app/services/code-highlighter-lifetime.spec.ts` | Spies on `console.warn` for Shiki's warning that too many highlighters were made. | +| `fixtures/timer-globals.fixture.spec.ts` | Spies on the faked `setInterval` to check the shared page's own check of timer globals. | ### Newest context diff --git a/src/noldova.ui.components.angular/scripts/angular/angular-timing-script.ts b/src/noldova.ui.components.angular/scripts/angular/angular-timing-script.ts index c300c688..99f1cdf5 100644 --- a/src/noldova.ui.components.angular/scripts/angular/angular-timing-script.ts +++ b/src/noldova.ui.components.angular/scripts/angular/angular-timing-script.ts @@ -34,6 +34,8 @@ export abstract class AngularTimingScript extends Script { private static readonly ANGULAR_TEST_COMMAND: string = "test"; private static readonly ANGULAR_FILTER_OPTION: string = "--filter"; private static readonly ANGULAR_INCLUDE_OPTION: string = "--include"; + private static readonly ANGULAR_EXCLUDE_OPTION: string = "--exclude"; + private static readonly ANGULAR_ISOLATE_OPTION: string = "--isolate"; private static readonly TIMING_FOLDER: string = "../../_build/timing"; private static readonly DEPENDENCY_CACHE: string = "../../node_modules/.vite"; private static readonly WORKSPACE_FOLDER: string = "."; @@ -48,18 +50,21 @@ export abstract class AngularTimingScript extends Script { private static readonly SELF_CHECK_FAILED: string = "The timing check failed its own check, so it times nothing."; private static readonly SELECTION_CASE: string = "a workspace with a spec file that traces layout and one that doesn't runs every test outside the tracing suite first, then the suite from that file alone, " - + "and spec files named by their file names run only those files, in the same parts"; + + "and spec files named by their file names run only those files, in the same parts; a listed spec file runs alone, in a part of its own with isolate on, " + + "and the other parts leave it out"; private static readonly TRACED_SPEC: string = "tests/traced.spec.ts"; private static readonly UNTRACED_SPEC: string = "tests/untraced.spec.ts"; private static readonly SHARED_NAME_SPEC: string = "tests/other/untraced.spec.ts"; private readonly project: string; private readonly owner: string; + private readonly isolated: readonly string[]; - protected constructor(project: string, owner: string) { + protected constructor(project: string, owner: string, isolated: readonly string[] = []) { super(); this.project = project; this.owner = owner; + this.isolated = isolated; } // Spec files named by their file names, such as code-block-run.component.spec.ts, are the only ones timed; with none named, every spec file is. @@ -87,7 +92,7 @@ export abstract class AngularTimingScript extends Script { await fs.rm(AngularTimingScript.DEPENDENCY_CACHE, { recursive: true, force: true }); const timing = new AngularTestTiming(AngularTimingScript.WORKSPACE_FOLDER); const tests = new AngularTestReport(AngularTimingScript.WORKSPACE_FOLDER, this.project); - const parts = await AngularTimingScript.partsAsync(AngularTimingScript.WORKSPACE_FOLDER, tests, specs); + const parts = await AngularTimingScript.partsAsync(AngularTimingScript.WORKSPACE_FOLDER, tests, specs, this.isolated); for (let run = 1; run <= AngularTimingScript.RUNS; run++) { await this.writeLogAsync(`Timing run ${run} of ${AngularTimingScript.RUNS} of ${this.owner} specs...`); const reports: string[] = []; @@ -129,7 +134,7 @@ export abstract class AngularTimingScript extends Script { // The test builder's selections for one timing run: one for every spec, or, when spec files trace layout, first every test outside the tracing // suite, then only the suite's tests from the files that hold it, each in a browser of its own. - private static async partsAsync(folder: string, tests: AngularTestReport, specs: readonly string[] = []): Promise { + private static async partsAsync(folder: string, tests: AngularTestReport, specs: readonly string[], isolatedFiles: readonly string[]): Promise { const files = await tests.listSpecFilesAsync(); const matches = specs.map(t => [t, files.filter(u => u === t || path.posix.basename(u) === t)] as const); const unknown = matches.filter(([, t]) => t.length === 0).map(([t]) => t); @@ -141,17 +146,20 @@ export abstract class AngularTimingScript extends Script { throw new CommandFailedException(`${shared.map(([t, u]) => `${t} names ${u.join(" and ")}`).join("; ")}; name such a spec file by its path from the workspace's folder.`); const chosen = specs.length === 0 ? files : files.filter(t => matches.some(([, u]) => u.includes(t))); const include = (selected: readonly string[]): readonly string[] => selected.flatMap(t => [AngularTimingScript.ANGULAR_INCLUDE_OPTION, t]); + const isolated = chosen.filter(t => isolatedFiles.includes(t)); + const onPage = chosen.filter(t => !isolated.includes(t)); const traced: string[] = []; - for (const spec of chosen) + for (const spec of onPage) if ((await fs.readFile(path.resolve(folder, spec), AngularTimingScript.ENCODING)).includes(LayoutTraceSuite.mark)) traced.push(spec); - const named = specs.length === 0 ? [] : include(chosen); + const named = specs.length === 0 ? isolatedFiles.flatMap(t => [AngularTimingScript.ANGULAR_EXCLUDE_OPTION, t]) : include(onPage); + const untraced = `${AngularTimingScript.ANGULAR_FILTER_OPTION}=${LayoutTraceSuite.untracedFilter}`; + const alone = isolated.length === 0 ? [] : [[AngularTimingScript.ANGULAR_ISOLATE_OPTION, untraced, ...include(isolated)]]; + if (onPage.length === 0) + return alone; if (traced.length === 0) - return [named]; - return [ - [`${AngularTimingScript.ANGULAR_FILTER_OPTION}=${LayoutTraceSuite.untracedFilter}`, ...named], - [`${AngularTimingScript.ANGULAR_FILTER_OPTION}=${LayoutTraceSuite.title}`, ...include(traced)] - ]; + return [named, ...alone]; + return [[untraced, ...named], [`${AngularTimingScript.ANGULAR_FILTER_OPTION}=${LayoutTraceSuite.title}`, ...include(traced)], ...alone]; } private static async checkRanOnceAsync(tests: AngularTestReport, reports: readonly string[]): Promise { @@ -268,17 +276,23 @@ export abstract class AngularTimingScript extends Script { await fs.writeFile(path.join(folder, AngularTimingScript.SHARED_NAME_SPEC), "describe(\"Shared name\", () => {});\n", AngularTimingScript.ENCODING); const report = new AngularTestReport(folder, AngularTimingScript.SELF_CHECK_PROJECT); const tracedPart = [`${AngularTimingScript.ANGULAR_FILTER_OPTION}=${LayoutTraceSuite.title}`, AngularTimingScript.ANGULAR_INCLUDE_OPTION, AngularTimingScript.TRACED_SPEC]; + const untraced = `${AngularTimingScript.ANGULAR_FILTER_OPTION}=${LayoutTraceSuite.untracedFilter}`; + const isolated = [AngularTimingScript.SHARED_NAME_SPEC]; + const alonePart = [AngularTimingScript.ANGULAR_ISOLATE_OPTION, untraced, AngularTimingScript.ANGULAR_INCLUDE_OPTION, AngularTimingScript.SHARED_NAME_SPEC]; const selections = [ - [[], [[`${AngularTimingScript.ANGULAR_FILTER_OPTION}=${LayoutTraceSuite.untracedFilter}`], tracedPart]], - [[AngularTimingScript.UNTRACED_SPEC], [[AngularTimingScript.ANGULAR_INCLUDE_OPTION, AngularTimingScript.UNTRACED_SPEC]]], - [[path.posix.basename(AngularTimingScript.TRACED_SPEC)], - [[`${AngularTimingScript.ANGULAR_FILTER_OPTION}=${LayoutTraceSuite.untracedFilter}`, AngularTimingScript.ANGULAR_INCLUDE_OPTION, AngularTimingScript.TRACED_SPEC], tracedPart]] + [[], [], [[untraced], tracedPart]], + [[AngularTimingScript.UNTRACED_SPEC], [], [[AngularTimingScript.ANGULAR_INCLUDE_OPTION, AngularTimingScript.UNTRACED_SPEC]]], + [[path.posix.basename(AngularTimingScript.TRACED_SPEC)], [], [[untraced, AngularTimingScript.ANGULAR_INCLUDE_OPTION, AngularTimingScript.TRACED_SPEC], tracedPart]], + [[], isolated, [[untraced, AngularTimingScript.ANGULAR_EXCLUDE_OPTION, AngularTimingScript.SHARED_NAME_SPEC], tracedPart, alonePart]], + [[AngularTimingScript.UNTRACED_SPEC, AngularTimingScript.SHARED_NAME_SPEC], isolated, + [[AngularTimingScript.ANGULAR_INCLUDE_OPTION, AngularTimingScript.UNTRACED_SPEC], alonePart]], + [[AngularTimingScript.SHARED_NAME_SPEC], isolated, [alonePart]] ] as const; - for (const [specs, expected] of selections) - if (JSON.stringify(await AngularTimingScript.partsAsync(folder, report, specs)) !== JSON.stringify(expected)) + for (const [specs, isolatedFiles, expected] of selections) + if (JSON.stringify(await AngularTimingScript.partsAsync(folder, report, specs, isolatedFiles)) !== JSON.stringify(expected)) return false; for (const specs of [["missing.spec.ts"], [path.posix.basename(AngularTimingScript.UNTRACED_SPEC)]]) - if (await AngularTimingScript.partsAsync(folder, report, specs).then(() => true, (error: unknown) => !(error instanceof CommandFailedException))) + if (await AngularTimingScript.partsAsync(folder, report, specs, []).then(() => true, (error: unknown) => !(error instanceof CommandFailedException))) return false; return true; } diff --git a/src/noldova.ui.components.angular/scripts/test-timing.ts b/src/noldova.ui.components.angular/scripts/test-timing.ts index 334df7d8..dfd3a5ad 100644 --- a/src/noldova.ui.components.angular/scripts/test-timing.ts +++ b/src/noldova.ui.components.angular/scripts/test-timing.ts @@ -6,6 +6,7 @@ * LICENSE file in the root directory of this source tree. */ +import { IsolatedSpecs } from "../tests/fixtures/isolated-specs.ts"; import { AngularTimingScript } from "./angular/angular-timing-script.ts"; export class TestTiming extends AngularTimingScript { @@ -13,7 +14,7 @@ export class TestTiming extends AngularTimingScript { private static readonly OWNER: string = "the kit's"; public constructor() { - super(TestTiming.ANGULAR_PROJECT, TestTiming.OWNER); + super(TestTiming.ANGULAR_PROJECT, TestTiming.OWNER, IsolatedSpecs.files); } public override async runAsync(): Promise { diff --git a/src/noldova.ui.components.angular/scripts/test.ts b/src/noldova.ui.components.angular/scripts/test.ts index 62bdbe69..7e545a78 100644 --- a/src/noldova.ui.components.angular/scripts/test.ts +++ b/src/noldova.ui.components.angular/scripts/test.ts @@ -30,6 +30,7 @@ import { PollBoundCheck } from "./checks/poll-bound-check.ts"; import { ProductNamesCheck } from "./checks/product-names-check.ts"; import CommandFailedException from "./command-failed.exception.ts"; import Config from "./config.ts"; +import { IsolatedSpecs } from "../tests/fixtures/isolated-specs.ts"; import { LayoutTraceSuite } from "../tests/fixtures/layout-trace-suite.ts"; import { ProcessRunner } from "./processes/process-runner.ts"; import { TemporaryFolder } from "./processes/temporary-folder.ts"; @@ -74,11 +75,15 @@ export class Test extends Script { private static readonly ANGULAR_PART_OPTIONS: readonly string[] = ["--configuration=part"]; private static readonly ANGULAR_INCLUDE_OPTION: string = "--include"; private static readonly ANGULAR_FILTER_OPTION: string = "--filter"; + private static readonly ANGULAR_EXCLUDE_OPTION: string = "--exclude"; + private static readonly ANGULAR_ISOLATE_OPTION: string = "--isolate"; + private static readonly ISOLATED_SPECS: readonly string[] = IsolatedSpecs.files; private static readonly TRACED_SUITE: string = LayoutTraceSuite.title; private static readonly TRACED_MARK: string = LayoutTraceSuite.mark; private static readonly UNTRACED_FILTER: string = LayoutTraceSuite.untracedFilter; private static readonly TRACED_PART: string = "part-2"; private static readonly UNTRACED_PART: string = "part-1"; + private static readonly ISOLATED_PART: string = "part-3"; private static readonly PARTS_PREFIX: string = "kit-coverage-parts-"; private static readonly COVERAGE_PART_FILE: string = "coverage-final.json"; private static readonly DEPENDENCY_CACHE: string = "../../node_modules/.vite"; @@ -175,8 +180,15 @@ export class Test extends Script { if (selected.length === 0) return 0; + const unlisted = Test.ISOLATED_SPECS.filter(t => !specs.includes(t)); + if (unlisted.length > 0) { + await this.writeLogAsync(Test.isolatedSpecsMissing(unlisted)); + this.failed = true; + } + const isolated = selected.filter(t => Test.ISOLATED_SPECS.includes(t)); + const shared = selected.filter(t => !isolated.includes(t)); const traced: string[] = []; - for (const spec of selected) + for (const spec of shared) if ((await this.readFileAsync(path.resolve(Test.WORKSPACE_FOLDER, spec))).includes(Test.TRACED_MARK)) traced.push(spec); const isWhole = filters.length === 0 && Object.isNull(shard); @@ -185,15 +197,23 @@ export class Test extends Script { const parts = await new TemporaryFolder().createAsync(process.platform, Test.PARTS_PREFIX); try { await fs.rm(Test.DEPENDENCY_CACHE, { recursive: true, force: true }); - const runs = [await this.runAngularPartAsync(selected, isWhole ? [] : selected, options, Test.UNTRACED_FILTER, keepsCoverage ? path.join(parts, Test.UNTRACED_PART) : null)]; + const runs: ReadonlyMap[] = []; + if (shared.length > 0) { + const excluded = isWhole ? Test.ISOLATED_SPECS.flatMap(t => [Test.ANGULAR_EXCLUDE_OPTION, t]) : []; + runs.push(await this.runAngularPartAsync(shared, isWhole ? [] : shared, [...options, ...excluded], Test.UNTRACED_FILTER, + keepsCoverage ? path.join(parts, Test.UNTRACED_PART) : null)); + } if (traced.length > 0) runs.push(await this.runAngularPartAsync(traced, traced, options, Test.TRACED_SUITE, keepsCoverage ? path.join(parts, Test.TRACED_PART) : null)); + if (isolated.length > 0) + runs.push(await this.runAngularPartAsync(isolated, isolated, [...options, Test.ANGULAR_ISOLATE_OPTION], Test.UNTRACED_FILTER, + keepsCoverage ? path.join(parts, Test.ISOLATED_PART) : null)); for (const finding of AngularTestReport.checkRanOnce(runs)) { await this.writeLogAsync(finding); this.failed = true; } if (keepsCoverage) { - await new CoverageMerge(Test.ROOT, Test.KIT_FOLDER).mergeAsync(parts, traced.length > 0 ? 2 : 1, this.coverage.path); + await new CoverageMerge(Test.ROOT, Test.KIT_FOLDER).mergeAsync(parts, runs.length, this.coverage.path); if (Object.isNull(shard)) for (const line of await this.coverage.listUnhitAsync()) { await this.writeLogAsync(line); @@ -256,6 +276,10 @@ export class Test extends Script { return `The kit's run of the tests named by ${filter} wrote no coverage at ${file}.`; } + private static isolatedSpecsMissing(files: readonly string[]): string { + return `IsolatedSpecs names spec files the kit doesn't have, so they would run nowhere: ${files.join(", ")}.`; + } + private static partRun(part: number, parts: number, specs: number): string { return `Part ${part} of ${parts} ran ${specs} of the kit's spec files and kept their coverage, which npm run test:merge gates with the other parts'; the checks before the specs run in part 1 alone.`; } diff --git a/src/noldova.ui.components.angular/src/app/components/configuration-table/configuration-table.directive.ts b/src/noldova.ui.components.angular/src/app/components/configuration-table/configuration-table.directive.ts index 392c6c5d..f787f23e 100644 --- a/src/noldova.ui.components.angular/src/app/components/configuration-table/configuration-table.directive.ts +++ b/src/noldova.ui.components.angular/src/app/components/configuration-table/configuration-table.directive.ts @@ -10,6 +10,7 @@ import { DestroyRef, Directive, ElementRef, type Signal, afterNextRender, comput import "@noldova/context.core"; +import { ClockTokens } from "../../models/clock-tokens.js"; import { ConfigurationTableFillWidths } from "../../models/configuration-table-fill-widths.js"; import { ConfigurationTableShares } from "../../models/configuration-table-shares.js"; import { ConfigurationTableTokens } from "../../models/configuration-table-tokens.js"; @@ -45,9 +46,10 @@ export class ConfigurationTableDirective { }); public constructor() { - let fitAfterObservedFrame: number | null = null; - const sizes = new ResizeObserver(() => fitAfterObservedFrame ??= requestAnimationFrame(() => { - fitAfterObservedFrame = null; + const timeSource = inject(ClockTokens.timeSource); + let cancelFit: (() => void) | null = null; + const sizes = new ResizeObserver(() => cancelFit ??= timeSource.frame(() => { + cancelFit = null; this.fit(); })); afterNextRender(() => { @@ -55,8 +57,7 @@ export class ConfigurationTableDirective { sizes.observe(part); }); inject(DestroyRef).onDestroy(() => { - if (!Object.isNull(fitAfterObservedFrame)) - cancelAnimationFrame(fitAfterObservedFrame); + cancelFit?.(); sizes.disconnect(); }); } diff --git a/src/noldova.ui.components.angular/src/app/components/markdown-view/markdown-view.component.ts b/src/noldova.ui.components.angular/src/app/components/markdown-view/markdown-view.component.ts index 2deafdb3..a8e33c58 100644 --- a/src/noldova.ui.components.angular/src/app/components/markdown-view/markdown-view.component.ts +++ b/src/noldova.ui.components.angular/src/app/components/markdown-view/markdown-view.component.ts @@ -31,6 +31,7 @@ import { MarkdownMentions } from "../../models/markdown-mentions.js"; import { MarkdownReveal } from "../../models/markdown-reveal.js"; import { MarkdownShellRunner } from "../../models/markdown-shell-runner.js"; import { MarkdownViewTokens } from "../../models/markdown-view-tokens.js"; +import { MediaTokens } from "../../models/media-tokens.js"; import type { MentionCandidate } from "../../models/mention-candidate.js"; import type { ShellRun } from "../../models/shell-run.js"; import { ShellRunBlocks } from "../../models/shell-run-blocks.js"; @@ -66,7 +67,7 @@ export class MarkdownViewComponent { private readonly markdown: IMarkdownParser | null = inject(MarkdownViewTokens.parser); private readonly reader: MarkdownReader = new MarkdownReader(); private readonly host: HTMLElement = inject>(ElementRef).nativeElement; - private readonly reveal: MarkdownReveal | null = isPlatformBrowser(inject(PLATFORM_ID)) ? new MarkdownReveal(this.host) : null; + private readonly reveal: MarkdownReveal | null = isPlatformBrowser(inject(PLATFORM_ID)) ? new MarkdownReveal(this.host, inject(MediaTokens.queries)) : null; private readonly image: Signal = contentChild(MessageImageDirective, { descendants: false }); private readonly shellRunOutput: Signal = contentChild(ShellRunOutputDirective, { descendants: false }); private readonly outerImages: MarkdownImages = inject(MarkdownViewTokens.images, { skipSelf: true }); diff --git a/src/noldova.ui.components.angular/src/app/interfaces/i-highlight-scope.ts b/src/noldova.ui.components.angular/src/app/interfaces/i-highlight-scope.ts new file mode 100644 index 00000000..3fbcc123 --- /dev/null +++ b/src/noldova.ui.components.angular/src/app/interfaces/i-highlight-scope.ts @@ -0,0 +1,12 @@ +/** + * @license + * Copyright (c) Noldova. + * + * This source code is licensed under the license found in the + * LICENSE file in the root directory of this source tree. + */ + +export interface IHighlightScope { + readonly Highlight?: unknown; + readonly CSS?: { readonly highlights?: unknown }; +} diff --git a/src/noldova.ui.components.angular/src/app/interfaces/i-idle-callbacks.ts b/src/noldova.ui.components.angular/src/app/interfaces/i-idle-callbacks.ts new file mode 100644 index 00000000..efd11402 --- /dev/null +++ b/src/noldova.ui.components.angular/src/app/interfaces/i-idle-callbacks.ts @@ -0,0 +1,12 @@ +/** + * @license + * Copyright (c) Noldova. + * + * This source code is licensed under the license found in the + * LICENSE file in the root directory of this source tree. + */ + +export interface IIdleCallbacks { + readonly requestIdleCallback?: (callback: IdleRequestCallback) => number; + readonly cancelIdleCallback: (handle: number) => void; +} diff --git a/src/noldova.ui.components.angular/src/app/interfaces/i-media-queries.ts b/src/noldova.ui.components.angular/src/app/interfaces/i-media-queries.ts new file mode 100644 index 00000000..16726ae5 --- /dev/null +++ b/src/noldova.ui.components.angular/src/app/interfaces/i-media-queries.ts @@ -0,0 +1,11 @@ +/** + * @license + * Copyright (c) Noldova. + * + * This source code is licensed under the license found in the + * LICENSE file in the root directory of this source tree. + */ + +export interface IMediaQueries { + match(query: string): MediaQueryList; +} diff --git a/src/noldova.ui.components.angular/src/app/models/highlight-tokens.resources.ts b/src/noldova.ui.components.angular/src/app/models/highlight-tokens.resources.ts new file mode 100644 index 00000000..dddf8ca4 --- /dev/null +++ b/src/noldova.ui.components.angular/src/app/models/highlight-tokens.resources.ts @@ -0,0 +1,11 @@ +/** + * @license + * Copyright (c) Noldova. + * + * This source code is licensed under the license found in the + * LICENSE file in the root directory of this source tree. + */ + +export class HighlightTokensResources { + public static readonly highlightAvailableToken: string = "nol-highlight-available"; +} diff --git a/src/noldova.ui.components.angular/src/app/models/highlight-tokens.ts b/src/noldova.ui.components.angular/src/app/models/highlight-tokens.ts new file mode 100644 index 00000000..9069f7c4 --- /dev/null +++ b/src/noldova.ui.components.angular/src/app/models/highlight-tokens.ts @@ -0,0 +1,23 @@ +/** + * @license + * Copyright (c) Noldova. + * + * This source code is licensed under the license found in the + * LICENSE file in the root directory of this source tree. + */ + +import { InjectionToken } from "@angular/core"; + +import "@noldova/context.core"; + +import type { IHighlightScope } from "../interfaces/i-highlight-scope.js"; +import { HighlightTokensResources } from "./highlight-tokens.resources.js"; + +export class HighlightTokens { + public static readonly available: InjectionToken = + new InjectionToken(HighlightTokensResources.highlightAvailableToken, { providedIn: "root", factory: () => HighlightTokens.isAvailableIn(globalThis) }); + + public static isAvailableIn(scope: IHighlightScope): boolean { + return Object.isFunction(scope.Highlight) && !Object.isNullOrUndefined(scope.CSS?.highlights); + } +} diff --git a/src/noldova.ui.components.angular/src/app/models/markdown-reveal.ts b/src/noldova.ui.components.angular/src/app/models/markdown-reveal.ts index 99d15f35..6b932b94 100644 --- a/src/noldova.ui.components.angular/src/app/models/markdown-reveal.ts +++ b/src/noldova.ui.components.angular/src/app/models/markdown-reveal.ts @@ -8,6 +8,7 @@ import "@noldova/context.core"; +import type { IMediaQueries } from "../interfaces/i-media-queries.js"; import { MarkdownRevealResources } from "./markdown-reveal.resources.js"; import { RenderedText } from "./rendered-text.js"; import { TextReveal } from "./text-reveal.js"; @@ -16,7 +17,7 @@ import { Resources } from "../../resources.js"; export class MarkdownReveal { private readonly text: RenderedText; private readonly root: Node; - private readonly motion: MediaQueryList = matchMedia(Resources.reducedMotionQuery); + private readonly motion: MediaQueryList; private readonly observer: MutationObserver = new MutationObserver(t => this.rendered(t)); private readonly selected: () => void = () => this.selectionChanged(); private reveal: TextReveal | null = null; @@ -28,8 +29,9 @@ export class MarkdownReveal { private isDrawn: boolean = false; private burst: number = 0; - public constructor(root: Node) { + public constructor(root: Node, media: IMediaQueries) { this.root = root; + this.motion = media.match(Resources.reducedMotionQuery); this.text = new RenderedText(root); } diff --git a/src/noldova.ui.components.angular/src/app/models/media-tokens.resources.ts b/src/noldova.ui.components.angular/src/app/models/media-tokens.resources.ts new file mode 100644 index 00000000..f85869c0 --- /dev/null +++ b/src/noldova.ui.components.angular/src/app/models/media-tokens.resources.ts @@ -0,0 +1,11 @@ +/** + * @license + * Copyright (c) Noldova. + * + * This source code is licensed under the license found in the + * LICENSE file in the root directory of this source tree. + */ + +export class MediaTokensResources { + public static readonly mediaQueriesToken: string = "nol-media-queries"; +} diff --git a/src/noldova.ui.components.angular/src/app/models/media-tokens.ts b/src/noldova.ui.components.angular/src/app/models/media-tokens.ts new file mode 100644 index 00000000..c63fe109 --- /dev/null +++ b/src/noldova.ui.components.angular/src/app/models/media-tokens.ts @@ -0,0 +1,18 @@ +/** + * @license + * Copyright (c) Noldova. + * + * This source code is licensed under the license found in the + * LICENSE file in the root directory of this source tree. + */ + +import { InjectionToken } from "@angular/core"; + +import type { IMediaQueries } from "../interfaces/i-media-queries.js"; +import { BrowserMediaQueries } from "../services/browser-media-queries.js"; +import { MediaTokensResources } from "./media-tokens.resources.js"; + +export class MediaTokens { + public static readonly queries: InjectionToken = + new InjectionToken(MediaTokensResources.mediaQueriesToken, { providedIn: "root", factory: () => new BrowserMediaQueries() }); +} diff --git a/src/noldova.ui.components.angular/src/app/services/appearance.service.ts b/src/noldova.ui.components.angular/src/app/services/appearance.service.ts index b50fd5c6..3b301dd2 100644 --- a/src/noldova.ui.components.angular/src/app/services/appearance.service.ts +++ b/src/noldova.ui.components.angular/src/app/services/appearance.service.ts @@ -11,6 +11,7 @@ import { DestroyRef, Injectable, PLATFORM_ID, type Signal, type WritableSignal, import { ModePreference } from "../enums/mode-preference.js"; import { ThemeMode } from "../enums/theme-mode.js"; +import { MediaTokens } from "../models/media-tokens.js"; import type { Theme } from "../models/theme.js"; import { Typography } from "../models/typography.js"; import { DefaultTheme } from "../models/default-theme.js"; @@ -23,7 +24,7 @@ import { TypographyPainter } from "./typography-painter.js"; export class AppearanceService { private readonly root: HTMLElement = inject(DOCUMENT).documentElement; private readonly painter: ThemePainter = new ThemePainter(DefaultTheme.theme); - private readonly systemScheme: MediaQueryList | null = isPlatformBrowser(inject(PLATFORM_ID)) ? matchMedia(Resources.darkSchemeQuery) : null; + private readonly systemScheme: MediaQueryList | null = isPlatformBrowser(inject(PLATFORM_ID)) ? inject(MediaTokens.queries).match(Resources.darkSchemeQuery) : null; private readonly isSystemDark: WritableSignal = signal(this.systemScheme?.matches ?? false); private readonly themeState: WritableSignal = signal(DefaultTheme.theme); private readonly preferenceState: WritableSignal = signal(ModePreference.System); diff --git a/src/noldova.ui.components.angular/src/app/services/browser-media-queries.ts b/src/noldova.ui.components.angular/src/app/services/browser-media-queries.ts new file mode 100644 index 00000000..1e041f6b --- /dev/null +++ b/src/noldova.ui.components.angular/src/app/services/browser-media-queries.ts @@ -0,0 +1,15 @@ +/** + * @license + * Copyright (c) Noldova. + * + * This source code is licensed under the license found in the + * LICENSE file in the root directory of this source tree. + */ + +import type { IMediaQueries } from "../interfaces/i-media-queries.js"; + +export class BrowserMediaQueries implements IMediaQueries { + public match(query: string): MediaQueryList { + return matchMedia(query); + } +} diff --git a/src/noldova.ui.components.angular/src/app/services/code-highlights.ts b/src/noldova.ui.components.angular/src/app/services/code-highlights.ts index 6b196ac3..d014c7bb 100644 --- a/src/noldova.ui.components.angular/src/app/services/code-highlights.ts +++ b/src/noldova.ui.components.angular/src/app/services/code-highlights.ts @@ -13,12 +13,14 @@ import "@noldova/context.core"; import { CodeTokenKind } from "../enums/code-token-kind.js"; import type { CodeToken } from "../models/code-token.js"; +import { HighlightTokens } from "../models/highlight-tokens.js"; +import { MediaTokens } from "../models/media-tokens.js"; import { DomResources } from "../../dom-resources.js"; import { CodeHighlightsResources } from "./code-highlights.resources.js"; @Injectable({ providedIn: "root" }) export class CodeHighlights { - private readonly highlights: Readonly> | null = isPlatformBrowser(inject(PLATFORM_ID)) && CodeHighlights.canHighlight() + private readonly highlights: Readonly> | null = isPlatformBrowser(inject(PLATFORM_ID)) && inject(HighlightTokens.available) ? CodeHighlights.createHighlights() : null; public constructor() { @@ -26,7 +28,7 @@ export class CodeHighlights { return; const highlights = this.highlights; const kinds = Object.values(CodeTokenKind); - const forcedColors = matchMedia(DomResources.forcedColorsQuery); + const forcedColors = inject(MediaTokens.queries).match(DomResources.forcedColorsQuery); const register = (): void => { for (const kind of kinds) if (forcedColors.matches) @@ -63,10 +65,6 @@ export class CodeHighlights { return `${CodeHighlightsResources.codeHighlightPrefix}${kind.toLowerCase()}`; } - public static canHighlight(): boolean { - return Object.isFunction(globalThis.Highlight) && !Object.isNullOrUndefined(globalThis.CSS.highlights); - } - private static createHighlights(): Readonly> { return { [CodeTokenKind.Comment]: new Highlight(), diff --git a/src/noldova.ui.components.angular/src/app/services/diff-highlights.ts b/src/noldova.ui.components.angular/src/app/services/diff-highlights.ts index e4e3115c..cc0f76fa 100644 --- a/src/noldova.ui.components.angular/src/app/services/diff-highlights.ts +++ b/src/noldova.ui.components.angular/src/app/services/diff-highlights.ts @@ -12,12 +12,12 @@ import "@noldova/context.core"; import { DiffSide } from "../enums/diff-side.js"; import type { DiffChange } from "../models/diff-change.js"; -import { CodeHighlights } from "./code-highlights.js"; +import { HighlightTokens } from "../models/highlight-tokens.js"; import { DiffHighlightsResources } from "./diff-highlights.resources.js"; @Injectable({ providedIn: "root" }) export class DiffHighlights { - private readonly highlights: Readonly> | null = CodeHighlights.canHighlight() ? { + private readonly highlights: Readonly> | null = inject(HighlightTokens.available) ? { [DiffSide.Old]: new Highlight(), [DiffSide.New]: new Highlight() } : null; diff --git a/src/noldova.ui.components.angular/src/app/services/system-time-source.ts b/src/noldova.ui.components.angular/src/app/services/system-time-source.ts index 71a33d4b..e3000659 100644 --- a/src/noldova.ui.components.angular/src/app/services/system-time-source.ts +++ b/src/noldova.ui.components.angular/src/app/services/system-time-source.ts @@ -6,10 +6,17 @@ * LICENSE file in the root directory of this source tree. */ +import type { IIdleCallbacks } from "../interfaces/i-idle-callbacks.js"; import type { ITimeSource } from "../interfaces/i-time-source.js"; import { SystemTimeSourceResources } from "./system-time-source.resources.js"; export class SystemTimeSource implements ITimeSource { + private readonly idleCallbacks: IIdleCallbacks; + + public constructor(idleCallbacks: IIdleCallbacks = globalThis) { + this.idleCallbacks = idleCallbacks; + } + public now(): number { return Date.now(); } @@ -34,9 +41,10 @@ export class SystemTimeSource implements ITimeSource { } public idle(callback: () => void): () => void { - if (typeof globalThis.requestIdleCallback !== "function") + const callbacks = this.idleCallbacks; + if (typeof callbacks.requestIdleCallback !== "function") return this.after(callback, SystemTimeSourceResources.idleFallbackDelay); - const idle = requestIdleCallback(() => callback()); - return () => cancelIdleCallback(idle); + const idle = callbacks.requestIdleCallback(() => callback()); + return () => callbacks.cancelIdleCallback(idle); } } diff --git a/src/noldova.ui.components.angular/tests/app/components/code-block/code-block-spans.component.spec.ts b/src/noldova.ui.components.angular/tests/app/components/code-block/code-block-spans.component.spec.ts index 3422d795..5e89aba9 100644 --- a/src/noldova.ui.components.angular/tests/app/components/code-block/code-block-spans.component.spec.ts +++ b/src/noldova.ui.components.angular/tests/app/components/code-block/code-block-spans.component.spec.ts @@ -48,20 +48,19 @@ describe("CodeBlockComponent", () => { it("shows a streaming block's code, its ended lines as token spans and its growing line plain, settles that line into spans once it stops streaming, and throws nothing, in a browser without the CSS Highlight API", async () => { const code = "const a = 1;\nlet b = \"two\";"; const shown: unknown[] = []; + CodeHighlightsFixture.withoutHighlightApi(); - await CodeHighlightsFixture.withoutHighlightApiAsync(async () => { - controlTokens(t => [...t.matchAll(/const|let/gu)].map(m => new CodeToken(m.index, m[0], CodeTokenKind.Keyword))); - await renderAsync(); - await changeAsync(() => { - harness.host.streaming.set(true); - harness.host.code.set(code); - }); - shown.push([tokenSpans(), lines().map(isLine), body().querySelector("code")?.textContent]); - await changeAsync(() => harness.host.streaming.set(false)); - shown.push([tokenSpans(), lines().map(t => t.textContent), body().querySelector("code")?.textContent]); + controlTokens(t => [...t.matchAll(/const|let/gu)].map(m => new CodeToken(m.index, m[0], CodeTokenKind.Keyword))); + await renderAsync(); + await changeAsync(() => { + harness.host.streaming.set(true); + harness.host.code.set(code); }); + shown.push([tokenSpans(), lines().map(isLine), body().querySelector("code")?.textContent, allRanges(), CSS.highlights.has(CodeHighlights.nameOf(CodeTokenKind.Keyword))]); + await changeAsync(() => harness.host.streaming.set(false)); + shown.push([tokenSpans(), lines().map(t => t.textContent), body().querySelector("code")?.textContent]); - expect(shown).toEqual([[1, [false, true], code], [2, ["const a = 1;\n", "let b = \"two\";"], code]]); + expect(shown).toEqual([[1, [false, true], code, 0, false], [2, ["const a = 1;\n", "let b = \"two\";"], code]]); }); it("colors a streaming block's ended lines with token spans and its growing line with highlight ranges on its one text node, then settles that line into spans of the same colors and text once it stops streaming", async () => { diff --git a/src/noldova.ui.components.angular/tests/app/components/configuration-table/configuration-table.directive.spec.ts b/src/noldova.ui.components.angular/tests/app/components/configuration-table/configuration-table.directive.spec.ts index edff7ed5..ae79de53 100644 --- a/src/noldova.ui.components.angular/tests/app/components/configuration-table/configuration-table.directive.spec.ts +++ b/src/noldova.ui.components.angular/tests/app/components/configuration-table/configuration-table.directive.spec.ts @@ -14,7 +14,9 @@ import { ConfigurationTableFillDirective } from "../../../../src/app/components/ import { ConfigurationTableComponent } from "../../../../src/app/components/configuration-table/configuration-table.component"; import { ConfigurationTableDirective } from "../../../../src/app/components/configuration-table/configuration-table.directive"; import type { IScrollbarGutters } from "../../../../src/app/interfaces/i-scrollbar-gutters"; +import { ClockTokens } from "../../../../src/app/models/clock-tokens"; import { ConfigurationTableTokens } from "../../../../src/app/models/configuration-table-tokens"; +import { SystemTimeSource } from "../../../../src/app/services/system-time-source"; import { AppearanceFixture } from "../../../../src/testing/services/appearance-fixture"; import { ChangeSignalFixture } from "../../../fixtures/change-signal.fixture"; import { ConfigurationTableHostComponent } from "../../../fixtures/configuration-table-host.component"; @@ -22,6 +24,17 @@ import { DomChangeFixture } from "../../../fixtures/dom-change.fixture"; import { DomFixture } from "../../../fixtures/dom.fixture"; import { LayoutSettleFixture } from "../../../fixtures/layout-settle.fixture"; +class FrameRequestTimeSource extends SystemTimeSource { + public requested: (() => void) | null = null; + + public override frame(callback: () => void): () => void { + const requested = this.requested; + this.requested = null; + requested?.(); + return super.frame(callback); + } +} + @Component({ imports: [ButtonComponent, ConfigurationTableComponent, ConfigurationTableDirective, ConfigurationTableFillDirective], template: ` @@ -249,6 +262,8 @@ describe("ConfigurationTableDirective", () => { }); it("drops a fit still waiting for its frame once destroyed", async () => { + const frames = new FrameRequestTimeSource(); + TestBed.configureTestingModule({ providers: [{ provide: ClockTokens.timeSource, useValue: frames }] }); AppearanceFixture.apply(); await renderAsync(); await changeAsync(t => { @@ -264,20 +279,14 @@ describe("ConfigurationTableDirective", () => { fixture.componentInstance.width.set("40rem"); fixture.detectChanges(); - const request = window.requestAnimationFrame.bind(window); const requested = new ChangeSignalFixture(); let isRequested = false; - const requests = vi.spyOn(window, "requestAnimationFrame").mockImplementationOnce(callback => { + frames.requested = () => { isRequested = true; requested.fire(); queueMicrotask(() => fixture.destroy()); - return request(callback); - }); - try { - await requested.untilAsync(() => expect(isRequested, "a frame request").toBe(true)); - } finally { - requests.mockRestore(); - } + }; + await requested.untilAsync(() => expect(isRequested, "a frame request").toBe(true)); await frameAsync(); await frameAsync(); diff --git a/src/noldova.ui.components.angular/tests/app/components/diff-view/diff-view.component.spec.ts b/src/noldova.ui.components.angular/tests/app/components/diff-view/diff-view.component.spec.ts index 2dd2367b..c0a3fd65 100644 --- a/src/noldova.ui.components.angular/tests/app/components/diff-view/diff-view.component.spec.ts +++ b/src/noldova.ui.components.angular/tests/app/components/diff-view/diff-view.component.spec.ts @@ -224,18 +224,18 @@ describe("DiffViewComponent", () => { }); it("shows each line's sign and code, its changed lines marked, and throws nothing, in a browser without the CSS Highlight API", async () => { - const shown: unknown[] = []; + CodeHighlightsFixture.withoutHighlightApi(); - await CodeHighlightsFixture.withoutHighlightApiAsync(async () => { - await renderAsync(t => t.files.set([modified])); - const lines = cells(item(hunks(), 0)); - shown.push(lines.map(t => text(find(".nol-diff-sign", t))), lines.map(t => text(find(".nol-diff-text", t))), lines.map(t => t.classList.contains("nol-diff-cell-changed"))); - }); + await renderAsync(t => t.files.set([modified])); + const lines = cells(item(hunks(), 0)); + const shown = [lines.map(t => text(find(".nol-diff-sign", t))), lines.map(t => text(find(".nol-diff-text", t))), lines.map(t => t.classList.contains("nol-diff-cell-changed")), + ["nol-diff-removed-change", "nol-diff-added-change", "nol-code-keyword"].map(t => CSS.highlights.has(t))]; expect(shown).toEqual([ ["", "-", "+", "+", ""], ["Line 10 const a = 1;", "Removed line 11 const b = 1;", "Added line 11 const b = 2;", "Added line 12 const c = 3;", "Line 13 return a;"], - [false, true, true, true, false] + [false, true, true, true, false], + [false, false, false] ]); }); diff --git a/src/noldova.ui.components.angular/tests/app/components/markdown-view/markdown-view.component.spec.ts b/src/noldova.ui.components.angular/tests/app/components/markdown-view/markdown-view.component.spec.ts index 49249262..2ff5d7d5 100644 --- a/src/noldova.ui.components.angular/tests/app/components/markdown-view/markdown-view.component.spec.ts +++ b/src/noldova.ui.components.angular/tests/app/components/markdown-view/markdown-view.component.spec.ts @@ -13,6 +13,7 @@ import MarkdownIt, { type MarkdownIt as MarkdownItParser } from "markdown-it"; import { MarkdownViewComponent } from "../../../../src/app/components/markdown-view/markdown-view.component"; import { MessageImageDirective } from "../../../../src/app/components/message/message-image.directive"; import { LinkGesture } from "../../../../src/app/enums/link-gesture"; +import type { IMediaQueries } from "../../../../src/app/interfaces/i-media-queries"; import { ThemeMode } from "../../../../src/app/enums/theme-mode"; import { CodeHighlighterTokens } from "../../../../src/app/models/code-highlighter-tokens"; import { CodeLanguage } from "../../../../src/app/models/code-language"; @@ -21,6 +22,7 @@ import type { LinkMenuEvent } from "../../../../src/app/models/link-menu-event"; import type { LinkOpenEvent } from "../../../../src/app/models/link-open-event"; import { MarkdownLinkSchemes } from "../../../../src/app/models/markdown-link-schemes"; import { MarkdownViewTokens } from "../../../../src/app/models/markdown-view-tokens"; +import { MediaTokens } from "../../../../src/app/models/media-tokens"; import type { ShellRun } from "../../../../src/app/models/shell-run"; import { CodeHighlighter } from "../../../../src/app/services/code-highlighter"; import { MarkdownParser } from "../../../../src/app/services/markdown.parser"; @@ -127,8 +129,14 @@ describe("MarkdownViewComponent", () => { }; it("shows its streamed text whole and reads no media query when it starts outside a browser, as when a page is prerendered", async () => { - TestBed.configureTestingModule({ providers: [{ provide: PLATFORM_ID, useValue: "server" }] }); - const media = vi.spyOn(window, "matchMedia"); + const queries: string[] = []; + const media: IMediaQueries = { + match: query => { + queries.push(query); + return matchMedia(query); + } + }; + TestBed.configureTestingModule({ providers: [{ provide: PLATFORM_ID, useValue: "server" }, { provide: MediaTokens.queries, useValue: media }] }); fixture = TestBed.createComponent(MarkdownViewHostComponent); host = fixture.componentInstance; host.streaming.set(true); @@ -137,7 +145,7 @@ describe("MarkdownViewComponent", () => { const shown = view().innerText.trim(); fixture.destroy(); - expect([media.mock.calls.length, shown]).toEqual([0, `Start of a reply with ${"word ".repeat(40)}end`]); + expect([queries, shown]).toEqual([[], `Start of a reply with ${"word ".repeat(40)}end`]); }); it("renders each kind of block as its element", async () => { diff --git a/src/noldova.ui.components.angular/tests/app/models/highlight-tokens.spec.ts b/src/noldova.ui.components.angular/tests/app/models/highlight-tokens.spec.ts new file mode 100644 index 00000000..5c8ef8a1 --- /dev/null +++ b/src/noldova.ui.components.angular/tests/app/models/highlight-tokens.spec.ts @@ -0,0 +1,30 @@ +/** + * @license + * Copyright (c) Noldova. + * + * This source code is licensed under the license found in the + * LICENSE file in the root directory of this source tree. + */ + +import { TestBed } from "@angular/core/testing"; + +import { HighlightTokens } from "../../../src/app/models/highlight-tokens"; + +describe("HighlightTokens", () => { + it("finds the page's CSS Highlight API unless another answer is provided", () => { + expect(TestBed.inject(HighlightTokens.available)).toBe(true); + }); + + it("finds the CSS Highlight API only where a scope has both its Highlight constructor and its highlight registry", () => { + const registry = new Map(); + const highlight = (): void => undefined; + + expect([ + HighlightTokens.isAvailableIn({ Highlight: highlight, CSS: { highlights: registry } }), + HighlightTokens.isAvailableIn({ CSS: { highlights: registry } }), + HighlightTokens.isAvailableIn({ Highlight: highlight, CSS: {} }), + HighlightTokens.isAvailableIn({ Highlight: highlight }), + HighlightTokens.isAvailableIn({}) + ]).toEqual([true, false, false, false, false]); + }); +}); diff --git a/src/noldova.ui.components.angular/tests/app/models/markdown-reveal.spec.ts b/src/noldova.ui.components.angular/tests/app/models/markdown-reveal.spec.ts index a0d3d49a..31ebdf42 100644 --- a/src/noldova.ui.components.angular/tests/app/models/markdown-reveal.spec.ts +++ b/src/noldova.ui.components.angular/tests/app/models/markdown-reveal.spec.ts @@ -7,6 +7,7 @@ */ import { MarkdownReveal } from "../../../src/app/models/markdown-reveal"; +import { BrowserMediaQueries } from "../../../src/app/services/browser-media-queries"; import { ForcedColorsFixture } from "../../fixtures/forced-colors.fixture"; import { MotionFixture } from "../../fixtures/motion.fixture"; import { RevealedTextFixture } from "../../fixtures/revealed-text.fixture"; @@ -25,7 +26,7 @@ for (const isForced of [false, true]) root = document.body.appendChild(document.createElement("div")); paragraph = root.appendChild(document.createElement("p")); paragraph.append("Hello"); - reveal = new MarkdownReveal(root); + reveal = new MarkdownReveal(root, new BrowserMediaQueries()); }); afterEach(async () => { @@ -145,7 +146,7 @@ for (const isForced of [false, true]) paragraph.append(" seven"); await renderedAsync(); const reduced = shown(); - const other = new MarkdownReveal(root); + const other = new MarkdownReveal(root, new BrowserMediaQueries()); other.follow(true, false); paragraph.append(" eight"); await renderedAsync(); @@ -189,21 +190,19 @@ for (const isForced of [false, true]) }); it("lets go of what it hides when it is destroyed partway through a reveal, showing the whole text and asking for no more frames", async () => { - const frames = vi.spyOn(globalThis, "requestAnimationFrame"); reveal.follow(true, false); paragraph.append(" and a longer text that takes a while to reveal"); await renderedAsync(); const partway = framesOf(2).at(-1) ?? String.empty; reveal.destroy(); - const asked = frames.mock.calls.length; + const asked = vi.getTimerCount(); framesOf(20); - expect([partway.length < 40, shown(), frames.mock.calls.length]).toEqual([true, "Hello and a longer text that takes a while to reveal", asked]); + expect([partway.length < 40, shown(), asked, vi.getTimerCount()]).toEqual([true, "Hello and a longer text that takes a while to reveal", 0, 0]); }); it("never hides, cuts or counts an element marked to be skipped that a render puts past the reveal point, so the reveal ends with the text around it", async () => { const full = "Hello and a longer text that takes a while to reveal"; - const frames = vi.spyOn(globalThis, "requestAnimationFrame"); reveal.follow(true, false); paragraph.append(full.slice(5)); await renderedAsync(); @@ -219,10 +218,10 @@ for (const isForced of [false, true]) vi.advanceTimersByTime(16); seen.push([output.hidden !== false, output.textContent]); } - const asked = frames.mock.calls.length; + const asked = vi.getTimerCount(); framesOf(5); - expect([shown(), seen.every(([hidden, text]) => !hidden && text === "x".repeat(1000)), frames.mock.calls.length]).toEqual([full, true, asked]); + expect([shown(), seen.every(([hidden, text]) => !hidden && text === "x".repeat(1000)), asked, vi.getTimerCount()]).toEqual([full, true, 0, 0]); }); it("counts and walks only the block a render adds after those it shows, not the blocks before it, and reveals it", async () => { @@ -245,11 +244,10 @@ for (const isForced of [false, true]) }); it("asks for no frame when it isn't streaming, and none after it is disposed", async () => { - const frames = vi.spyOn(globalThis, "requestAnimationFrame"); reveal.follow(false, false); paragraph.append(" idle"); await renderedAsync(); - const idle = frames.mock.calls.length; + const idle = vi.getTimerCount(); reveal.follow(true, false); paragraph.append(" and a longer text that takes a while to reveal"); diff --git a/src/noldova.ui.components.angular/tests/app/models/media-tokens.spec.ts b/src/noldova.ui.components.angular/tests/app/models/media-tokens.spec.ts new file mode 100644 index 00000000..146e6e7a --- /dev/null +++ b/src/noldova.ui.components.angular/tests/app/models/media-tokens.spec.ts @@ -0,0 +1,18 @@ +/** + * @license + * Copyright (c) Noldova. + * + * This source code is licensed under the license found in the + * LICENSE file in the root directory of this source tree. + */ + +import { TestBed } from "@angular/core/testing"; + +import { MediaTokens } from "../../../src/app/models/media-tokens"; +import { BrowserMediaQueries } from "../../../src/app/services/browser-media-queries"; + +describe("MediaTokens", () => { + it("reads the browser's own media queries unless another source is provided", () => { + expect(TestBed.inject(MediaTokens.queries)).toBeInstanceOf(BrowserMediaQueries); + }); +}); diff --git a/src/noldova.ui.components.angular/tests/app/models/text-reveal.spec.ts b/src/noldova.ui.components.angular/tests/app/models/text-reveal.spec.ts index ab0b5e96..0d7f27ff 100644 --- a/src/noldova.ui.components.angular/tests/app/models/text-reveal.spec.ts +++ b/src/noldova.ui.components.angular/tests/app/models/text-reveal.spec.ts @@ -153,15 +153,14 @@ describe("TextReveal", () => { }); it("stops asking for frames when it has caught up and when it is disposed", () => { - const request = vi.spyOn(globalThis, "requestAnimationFrame"); const changed = vi.fn(); const reveal = new TextReveal(0, changed); reveal.follow(10, false, true); vi.advanceTimersByTime(1000); - const requests = request.mock.calls.length; + const requests = vi.getTimerCount(); vi.advanceTimersByTime(1000); - expect(request.mock.calls.length).toBe(requests); + expect([requests, vi.getTimerCount()]).toEqual([0, 0]); reveal.follow(1000, false, true); vi.advanceTimersByTime(40); @@ -171,7 +170,6 @@ describe("TextReveal", () => { expect(changed.mock.calls.length).toBe(seen); expect(reveal.count).toBeLessThan(1000); - request.mockRestore(); }); it("goes on a little each burst when told again after it was disposed, however long ago", () => { diff --git a/src/noldova.ui.components.angular/tests/app/services/anchored-overlay.spec.ts b/src/noldova.ui.components.angular/tests/app/services/anchored-overlay.spec.ts index 2949e9e9..81d766bc 100644 --- a/src/noldova.ui.components.angular/tests/app/services/anchored-overlay.spec.ts +++ b/src/noldova.ui.components.angular/tests/app/services/anchored-overlay.spec.ts @@ -413,13 +413,13 @@ describe("AnchoredOverlay", () => { it("does nothing when asked to reposition while closed and lets go of its listeners once closed", () => { overlay.reposition(); expect(overlay.placement).toBeNull(); - const added = vi.spyOn(window, "removeEventListener"); overlay.openComponent(new ComponentPortal(ContentComponent), anchor(), below()); overlay.close(); + const repositions = vi.spyOn(overlay, "reposition"); + window.dispatchEvent(new Event("resize")); - expect(overlay.isOpen).toBe(false); - expect(added).toHaveBeenCalledWith("resize", expect.any(Function)); + expect([overlay.isOpen, repositions.mock.calls.length]).toEqual([false, 0]); }); it("passes on its keyboard and outside pointer events and its detachments", () => { diff --git a/src/noldova.ui.components.angular/tests/app/services/appearance.service.spec.ts b/src/noldova.ui.components.angular/tests/app/services/appearance.service.spec.ts index a453d2b6..948eb671 100644 --- a/src/noldova.ui.components.angular/tests/app/services/appearance.service.spec.ts +++ b/src/noldova.ui.components.angular/tests/app/services/appearance.service.spec.ts @@ -10,8 +10,10 @@ import { EnvironmentInjector, PLATFORM_ID, createEnvironmentInjector, effect } f import { TestBed } from "@angular/core/testing"; import { FontChoice } from "../../../src/app/enums/font-choice"; +import type { IMediaQueries } from "../../../src/app/interfaces/i-media-queries"; import { ModePreference } from "../../../src/app/enums/mode-preference"; import { ThemeMode } from "../../../src/app/enums/theme-mode"; +import { MediaTokens } from "../../../src/app/models/media-tokens"; import { Typography } from "../../../src/app/models/typography"; import { AppearanceService } from "../../../src/app/services/appearance.service"; import { DefaultTheme } from "../../../src/app/models/default-theme"; @@ -51,10 +53,13 @@ describe("AppearanceService", () => { beforeEach(() => { queries = []; scheme = new SystemSchemeFixture(true, "(prefers-color-scheme: dark)"); - vi.spyOn(window, "matchMedia").mockImplementation(query => { - queries.push(query); - return scheme; - }); + const media: IMediaQueries = { + match: query => { + queries.push(query); + return scheme; + } + }; + TestBed.configureTestingModule({ providers: [{ provide: MediaTokens.queries, useValue: media }] }); }); afterEach(() => { diff --git a/src/noldova.ui.components.angular/tests/app/services/browser-media-queries.spec.ts b/src/noldova.ui.components.angular/tests/app/services/browser-media-queries.spec.ts new file mode 100644 index 00000000..7ff9e113 --- /dev/null +++ b/src/noldova.ui.components.angular/tests/app/services/browser-media-queries.spec.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright (c) Noldova. + * + * This source code is licensed under the license found in the + * LICENSE file in the root directory of this source tree. + */ + +import { BrowserMediaQueries } from "../../../src/app/services/browser-media-queries"; + +describe("BrowserMediaQueries", () => { + it("reads a browser media query, which matches as the page's own width says", () => { + const query = new BrowserMediaQueries().match(`(min-width: ${window.innerWidth}px)`); + + expect([query.media, query.matches]).toEqual([`(min-width: ${window.innerWidth}px)`, true]); + }); +}); diff --git a/src/noldova.ui.components.angular/tests/app/services/clipboard-writer.spec.ts b/src/noldova.ui.components.angular/tests/app/services/clipboard-writer.spec.ts index 2080e600..2c65a082 100644 --- a/src/noldova.ui.components.angular/tests/app/services/clipboard-writer.spec.ts +++ b/src/noldova.ui.components.angular/tests/app/services/clipboard-writer.spec.ts @@ -18,15 +18,11 @@ class TextOnlyClipboard extends ClipboardWriter { } describe("ClipboardWriter", () => { - afterEach(() => vi.restoreAllMocks()); - - it("says a writer that doesn't copy images refused an image, without touching the clipboard or its texts", async () => { + it("says a writer that doesn't copy images refused an image, writing nothing in its place", async () => { const clipboard = new TextOnlyClipboard(); - const writeAsync = vi.spyOn(navigator.clipboard, "write"); - const writeTextAsync = vi.spyOn(navigator.clipboard, "writeText"); const answer = await clipboard.writeImageAsync(new Uint8Array([0x89, 0x50, 0x4e, 0x47])); - expect([answer, writeAsync.mock.calls.length, writeTextAsync.mock.calls.length, clipboard.texts]).toEqual([false, 0, 0, []]); + expect([answer, clipboard.texts]).toEqual([false, []]); }); }); diff --git a/src/noldova.ui.components.angular/tests/app/services/code-highlighter-growing.spec.ts b/src/noldova.ui.components.angular/tests/app/services/code-highlighter-growing.spec.ts index bdcc066a..a194bd0a 100644 --- a/src/noldova.ui.components.angular/tests/app/services/code-highlighter-growing.spec.ts +++ b/src/noldova.ui.components.angular/tests/app/services/code-highlighter-growing.spec.ts @@ -84,24 +84,6 @@ describe("CodeHighlighter", () => { .toEqual([CodeTokenKind.Comment, CodeTokenKind.String, CodeTokenKind.Comment]); }); - it("keeps none of the complete lines the time limit may have cut short, so the next update tokenizes them again", async () => { - TestBed.overrideProvider(CodeHighlighterTokens.tokenizeTimeLimit, { useValue: 500 }); - const fresh = made(); - const streamed = made(); - const text = texts[0]?.[1] ?? String.empty; - const code = text.slice(0, text.lastIndexOf("\n") + 1); - await streamed.tokensAsync("let warm = 1;", typescript, signal); - let now = Date.now(); - const clock = vi.spyOn(Date, "now").mockImplementation(() => now += 1000); - const cut = await streamed.tokensAsync(code, typescript, signal); - clock.mockRestore(); - const kept = (await settledOfAsync(streamed)).length; - const grown = await streamed.tokensAsync(`${code}x`, typescript, signal); - - expect([shown(cut) === shown(await wholeAsync(fresh, code, typescript)), kept, shown(grown) === shown(await wholeAsync(fresh, `${code}x`, typescript))]) - .toEqual([false, 0, true]); - }); - it("tokenizes code with a carriage return whole, keeping none of its lines, with the tokens of the whole code at every length", async () => { const fresh = made(); const streamed = made(); diff --git a/src/noldova.ui.components.angular/tests/app/services/code-highlighter-kept.spec.ts b/src/noldova.ui.components.angular/tests/app/services/code-highlighter-kept.spec.ts index 91e128cc..4e422533 100644 --- a/src/noldova.ui.components.angular/tests/app/services/code-highlighter-kept.spec.ts +++ b/src/noldova.ui.components.angular/tests/app/services/code-highlighter-kept.spec.ts @@ -9,7 +9,6 @@ import { TestBed } from "@angular/core/testing"; import { CodeHighlighterTokens } from "../../../src/app/models/code-highlighter-tokens"; -import { CodeLanguage } from "../../../src/app/models/code-language"; import { CodeHighlighter } from "../../../src/app/services/code-highlighter"; import { Resources } from "../../../src/resources"; import { CodeHighlightingFixture } from "../../../src/testing/models/code-highlighting-fixture"; @@ -71,32 +70,3 @@ describe("CodeHighlighter", () => { expect(results).toEqual([["let", "a"], [], ["let", "a", "let", "b", "1", "let", "c"], ["let", "a", "let", "c"]]); }); }); - -describe("CodeHighlighter's time limit for a line", () => { - const signal = new AbortController().signal; - const typescript = CodeLanguage.named("ts") as CodeLanguage; - - let measured = 0; - - beforeEach(() => TestBed.configureTestingModule({ providers: [CodeHighlightingFixture.sharedShiki] })); - - const textsAfterAsync = async (elapsed: number): Promise => { - const highlighter = TestBed.inject(CodeHighlighter); - await highlighter.tokensAsync("let a;", typescript, signal); - const times = [0]; - const now = vi.spyOn(Date, "now").mockImplementation(() => times.shift() ?? elapsed); - const texts = (await highlighter.tokensAsync(`let a;${" ".repeat(++measured)}`, typescript, signal)).map(t => t.text); - now.mockRestore(); - return texts; - }; - - it("stops a line that has taken longer than 500 ms, leaving the rest of it plain, when no limit is provided", async () => { - expect([await textsAfterAsync(500), await textsAfterAsync(501)]).toEqual([["let", "a"], []]); - }); - - it("never stops a line when 0 is provided as its limit", async () => { - TestBed.configureTestingModule({ providers: [{ provide: CodeHighlighterTokens.tokenizeTimeLimit, useValue: 0 }] }); - - expect(await textsAfterAsync(Number.MAX_SAFE_INTEGER)).toEqual(["let", "a"]); - }); -}); diff --git a/src/noldova.ui.components.angular/tests/app/services/code-highlighter-time-limit.spec.ts b/src/noldova.ui.components.angular/tests/app/services/code-highlighter-time-limit.spec.ts new file mode 100644 index 00000000..746d750a --- /dev/null +++ b/src/noldova.ui.components.angular/tests/app/services/code-highlighter-time-limit.spec.ts @@ -0,0 +1,101 @@ +/** + * @license + * Copyright (c) Noldova. + * + * This source code is licensed under the license found in the + * LICENSE file in the root directory of this source tree. + */ + +import { TestBed } from "@angular/core/testing"; +import type { MockInstance } from "vitest"; + +import { CodeHighlighterTokens } from "../../../src/app/models/code-highlighter-tokens"; +import { CodeSettledLines } from "../../../src/app/models/code-settled-lines"; +import type { CodeToken } from "../../../src/app/models/code-token"; +import { CodeHighlighter } from "../../../src/app/services/code-highlighter"; +import { CodeHighlightingFixture } from "../../../src/testing/models/code-highlighting-fixture"; +import { CodeHighlighterFixture } from "../../fixtures/code-highlighter.fixture"; + +describe("CodeHighlighter's time limit for a line", () => { + const { signal, typescript } = CodeHighlighterFixture; + + let measured = 0; + + beforeEach(() => TestBed.configureTestingModule({ providers: [CodeHighlightingFixture.sharedShiki] })); + + afterEach(() => vi.restoreAllMocks()); + + const timedAsync = async (clock: () => number, work: () => Promise): Promise => { + const now = vi.spyOn(Date, "now").mockImplementation(clock); + try { + return await work(); + } + finally { + now.mockRestore(); + } + }; + + const textsAfterAsync = async (elapsed: number): Promise => { + const highlighter = TestBed.inject(CodeHighlighter); + await highlighter.tokensAsync("let a;", typescript, signal); + const times = [0]; + const tokens = await timedAsync(() => times.shift() ?? elapsed, () => highlighter.tokensAsync(`let a;${" ".repeat(++measured)}`, typescript, signal)); + return tokens.map(t => t.text); + }; + + it("stops a line that has taken longer than 500 ms, leaving the rest of it plain, when no limit is provided", async () => { + expect([await textsAfterAsync(500), await textsAfterAsync(501)]).toEqual([["let", "a"], []]); + }); + + it("never stops a line when 0 is provided as its limit", async () => { + TestBed.configureTestingModule({ providers: [{ provide: CodeHighlighterTokens.tokenizeTimeLimit, useValue: 0 }] }); + + expect(await textsAfterAsync(Number.MAX_SAFE_INTEGER)).toEqual(["let", "a"]); + }); + + describe("on code that grows", () => { + const text = "/**\n * A doc comment\n * over lines.\n */\nconst greeting = `Hello,\n${name}, a template\n across lines`;\n/* a block\n comment */ const b = \"string\"; // line\n" + + "function f(a: number): string {\n\n return /re\\/gex/.test(String(a)) ? 'x' : \"y\";\n}"; + const made = (): CodeHighlighter => TestBed.runInInjectionContext(() => new CodeHighlighter()); + const spyOnContinued = (): MockInstance => vi.spyOn(CodeSettledLines.prototype, "isContinuedBy"); + let continued: MockInstance; + let probes = 0; + const shown = (tokens: readonly CodeToken[]): string => tokens.map(t => `${t.start}:${t.kind}:${t.text}`).join("\n"); + + const settledOfAsync = async (highlighter: CodeHighlighter): Promise => { + continued.mockClear(); + await highlighter.tokensAsync(`probe${probes++}`, typescript, signal); + return continued.mock.contexts.filter(t => t instanceof CodeSettledLines).map(t => t.code); + }; + + const wholeAsync = async (fresh: CodeHighlighter, code: string): Promise => { + continued.mockReturnValue(false); + try { + return await fresh.tokensAsync(code, typescript, signal); + } + finally { + continued.mockRestore(); + continued = spyOnContinued(); + } + }; + + beforeEach(() => { + continued = spyOnContinued(); + }); + + it("keeps none of the complete lines the time limit may have cut short, so the next update tokenizes them again", async () => { + TestBed.overrideProvider(CodeHighlighterTokens.tokenizeTimeLimit, { useValue: 500 }); + const fresh = made(); + const streamed = made(); + const code = text.slice(0, text.lastIndexOf("\n") + 1); + await streamed.tokensAsync("let warm = 1;", typescript, signal); + let now = Date.now(); + const cut = await timedAsync(() => now += 1000, () => streamed.tokensAsync(code, typescript, signal)); + const kept = (await settledOfAsync(streamed)).length; + const grown = await streamed.tokensAsync(`${code}x`, typescript, signal); + + expect([shown(cut) === shown(await wholeAsync(fresh, code)), kept, shown(grown) === shown(await wholeAsync(fresh, `${code}x`))]) + .toEqual([false, 0, true]); + }); + }); +}); diff --git a/src/noldova.ui.components.angular/tests/app/services/code-highlights.spec.ts b/src/noldova.ui.components.angular/tests/app/services/code-highlights.spec.ts index ccd1eb5f..a6a73eb1 100644 --- a/src/noldova.ui.components.angular/tests/app/services/code-highlights.spec.ts +++ b/src/noldova.ui.components.angular/tests/app/services/code-highlights.spec.ts @@ -10,7 +10,9 @@ import { EnvironmentInjector, PLATFORM_ID, createEnvironmentInjector } from "@an import { TestBed } from "@angular/core/testing"; import { CodeTokenKind } from "../../../src/app/enums/code-token-kind"; +import type { IMediaQueries } from "../../../src/app/interfaces/i-media-queries"; import { CodeToken } from "../../../src/app/models/code-token"; +import { MediaTokens } from "../../../src/app/models/media-tokens"; import { CodeHighlights } from "../../../src/app/services/code-highlights"; import { ChangeSignalFixture } from "../../fixtures/change-signal.fixture"; import { CodeHighlightsFixture } from "../../fixtures/code-highlights.fixture"; @@ -28,6 +30,13 @@ describe("CodeHighlights", () => { return () => query.removeEventListener("change", recheck); }); + const recorded = (queries: string[], answer: (query: string) => MediaQueryList = t => matchMedia(t)): IMediaQueries => ({ + match: query => { + queries.push(query); + return answer(query); + } + }); + afterEach(async () => { vi.restoreAllMocks(); await ForcedColorsFixture.resetAsync(); @@ -44,8 +53,9 @@ describe("CodeHighlights", () => { }); it("reads no media query and registers and adds no highlight when it starts outside a browser, as when a page is prerendered", () => { - const media = vi.spyOn(window, "matchMedia"); - const scoped = createEnvironmentInjector([{ provide: PLATFORM_ID, useValue: "server" }, CodeHighlights], TestBed.inject(EnvironmentInjector)); + const queries: string[] = []; + const scoped = createEnvironmentInjector([{ provide: PLATFORM_ID, useValue: "server" }, { provide: MediaTokens.queries, useValue: recorded(queries) }, CodeHighlights], + TestBed.inject(EnvironmentInjector)); const highlights = scoped.get(CodeHighlights); const registered = shown(); @@ -54,18 +64,18 @@ describe("CodeHighlights", () => { remove(); scoped.destroy(); - expect([media.mock.calls.length, registered, added]).toEqual([0, [], []]); + expect([queries, registered, added]).toEqual([[], [], []]); }); - it("registers and adds no highlight, and throws nothing, in a browser without the CSS Highlight API", async () => { - await CodeHighlightsFixture.withoutHighlightApiAsync(() => { - const highlights = TestBed.inject(CodeHighlights); - const remove = highlights.add(document.createTextNode("return 1;"), [new CodeToken(0, "return", CodeTokenKind.Control)]); - remove(); - TestBed.resetTestingModule(); - }); + it("registers and adds no highlight, and throws nothing, in a browser without the CSS Highlight API", () => { + CodeHighlightsFixture.withoutHighlightApi(); + const highlights = TestBed.inject(CodeHighlights); + const remove = highlights.add(document.createTextNode("return 1;"), [new CodeToken(0, "return", CodeTokenKind.Control)]); + const added = [shown(), ranges()]; + remove(); + TestBed.resetTestingModule(); - expect([shown(), ranges()]).toEqual([[], []]); + expect(added).toEqual([[], []]); }); it("highlights each token's range of a text in its kind's highlight with a static range, and takes them back when asked", () => { @@ -117,7 +127,8 @@ describe("CodeHighlights", () => { it("listens for changes of forced colors while it lives, and stops when it goes", () => { const query = matchMedia("(forced-colors: active)"); - const media = vi.spyOn(window, "matchMedia").mockReturnValue(query); + const queries: string[] = []; + TestBed.configureTestingModule({ providers: [{ provide: MediaTokens.queries, useValue: recorded(queries, () => query) }] }); const listen = vi.spyOn(query, "addEventListener"); const stop = vi.spyOn(query, "removeEventListener"); TestBed.inject(CodeHighlights); @@ -126,7 +137,7 @@ describe("CodeHighlights", () => { TestBed.resetTestingModule(); - expect(media.mock.calls).toEqual([["(forced-colors: active)"]]); + expect(queries).toEqual(["(forced-colors: active)"]); expect(listened).toEqual([["change", expect.any(Function)]]); expect(stopped).toBe(0); expect(stop.mock.calls.map(t => [t[0], t[1]])).toEqual(listened); diff --git a/src/noldova.ui.components.angular/tests/app/services/diff-highlights.spec.ts b/src/noldova.ui.components.angular/tests/app/services/diff-highlights.spec.ts index 6c83dc4f..fa43a93e 100644 --- a/src/noldova.ui.components.angular/tests/app/services/diff-highlights.spec.ts +++ b/src/noldova.ui.components.angular/tests/app/services/diff-highlights.spec.ts @@ -17,15 +17,15 @@ describe("DiffHighlights", () => { const names = ["nol-diff-removed-change", "nol-diff-added-change"]; const ranges = (): readonly string[] => names.flatMap(name => [...CSS.highlights.get(name) ?? []].map(t => `${name} ${t.startContainer.textContent?.slice(t.startOffset, t.endOffset)}`)); - it("registers and adds no highlight, and throws nothing, in a browser without the CSS Highlight API", async () => { - await CodeHighlightsFixture.withoutHighlightApiAsync(() => { - const highlights = TestBed.inject(DiffHighlights); - const remove = highlights.add(document.createTextNode("let b = 2;"), [new DiffChange(4, 5, DiffSide.New)]); - remove(); - TestBed.resetTestingModule(); - }); - - expect([names.some(t => CSS.highlights.has(t)), ranges()]).toEqual([false, []]); + it("registers and adds no highlight, and throws nothing, in a browser without the CSS Highlight API", () => { + CodeHighlightsFixture.withoutHighlightApi(); + const highlights = TestBed.inject(DiffHighlights); + const remove = highlights.add(document.createTextNode("let b = 2;"), [new DiffChange(4, 5, DiffSide.New)]); + const added = [names.some(t => CSS.highlights.has(t)), ranges()]; + remove(); + TestBed.resetTestingModule(); + + expect(added).toEqual([false, []]); }); it("registers a highlight for each side's changes under the code's token colors, and removes them all when it goes", () => { diff --git a/src/noldova.ui.components.angular/tests/app/services/overlay-bounds-server.service.spec.ts b/src/noldova.ui.components.angular/tests/app/services/overlay-bounds-server.service.spec.ts new file mode 100644 index 00000000..f62228cd --- /dev/null +++ b/src/noldova.ui.components.angular/tests/app/services/overlay-bounds-server.service.spec.ts @@ -0,0 +1,30 @@ +/** + * @license + * Copyright (c) Noldova. + * + * This source code is licensed under the license found in the + * LICENSE file in the root directory of this source tree. + */ + +import { EnvironmentInjector, PLATFORM_ID, createEnvironmentInjector } from "@angular/core"; +import { TestBed } from "@angular/core/testing"; + +import { OverlayBoundsService } from "../../../src/app/services/overlay-bounds.service"; + +describe("OverlayBoundsService outside a browser", () => { + afterEach(() => vi.restoreAllMocks()); + + it("places nothing in the page and watches nothing when it starts outside a browser, as when a page is prerendered", () => { + const listen = vi.spyOn(window, "addEventListener"); + const scoped = createEnvironmentInjector([{ provide: PLATFORM_ID, useValue: "server" }, OverlayBoundsService], TestBed.inject(EnvironmentInjector)); + const before = document.body.innerHTML; + const service = scoped.get(OverlayBoundsService); + const after = document.body.innerHTML; + const listened = listen.mock.calls.map(t => t[0]); + scoped.destroy(); + + expect(service).toBeInstanceOf(OverlayBoundsService); + expect(after).toBe(before); + expect(listened).toEqual([]); + }); +}); diff --git a/src/noldova.ui.components.angular/tests/app/services/overlay-bounds.service.spec.ts b/src/noldova.ui.components.angular/tests/app/services/overlay-bounds.service.spec.ts index 324cd548..9ea0e682 100644 --- a/src/noldova.ui.components.angular/tests/app/services/overlay-bounds.service.spec.ts +++ b/src/noldova.ui.components.angular/tests/app/services/overlay-bounds.service.spec.ts @@ -6,7 +6,7 @@ * LICENSE file in the root directory of this source tree. */ -import { EnvironmentInjector, PLATFORM_ID, createEnvironmentInjector } from "@angular/core"; +import { EnvironmentInjector, createEnvironmentInjector } from "@angular/core"; import { TestBed } from "@angular/core/testing"; import { OverlayBoundsService } from "../../../src/app/services/overlay-bounds.service"; @@ -105,21 +105,6 @@ describe("OverlayBoundsService", () => { expect(holder?.isConnected).toBe(false); }); - it("places nothing in the page and watches nothing when it starts outside a browser, as when a page is prerendered", () => { - const listen = vi.spyOn(window, "addEventListener"); - const scoped = createEnvironmentInjector([{ provide: PLATFORM_ID, useValue: "server" }, OverlayBoundsService], TestBed.inject(EnvironmentInjector)); - const before = document.body.innerHTML; - const service = scoped.get(OverlayBoundsService); - const after = document.body.innerHTML; - const listened = listen.mock.calls.map(t => t[0]); - listen.mockRestore(); - scoped.destroy(); - - expect(service).toBeInstanceOf(OverlayBoundsService); - expect(after).toBe(before); - expect(listened).toEqual([]); - }); - it("measures its looks again once the root's or the body's attributes or the window's size change, and not for a style sheet added to the head", async () => { const service = TestBed.inject(OverlayBoundsService); const rem = parseFloat(getComputedStyle(document.documentElement).fontSize); diff --git a/src/noldova.ui.components.angular/tests/app/services/system-time-source.spec.ts b/src/noldova.ui.components.angular/tests/app/services/system-time-source.spec.ts index d82f14f7..76769af4 100644 --- a/src/noldova.ui.components.angular/tests/app/services/system-time-source.spec.ts +++ b/src/noldova.ui.components.angular/tests/app/services/system-time-source.spec.ts @@ -85,49 +85,43 @@ describe("SystemTimeSource", () => { it("calls back when the browser's idle callback comes, and not at all once cancelled", () => { const pending = new Map(); let requests = 0; - const request = vi.spyOn(globalThis, "requestIdleCallback").mockImplementation(callback => { - requests++; - pending.set(requests, callback); - return requests; + const cancelled: number[] = []; + const source = new SystemTimeSource({ + requestIdleCallback: callback => { + requests++; + pending.set(requests, callback); + return requests; + }, + cancelIdleCallback: id => { + cancelled.push(id); + pending.delete(id); + } }); - const cancel = vi.spyOn(globalThis, "cancelIdleCallback").mockImplementation(id => { - pending.delete(id); - }); - try { - const source = new SystemTimeSource(); - const calls: string[] = []; - source.idle(() => calls.push("cancelled"))(); - source.idle(() => calls.push("idle")); - const before = [...calls]; - for (const callback of pending.values()) - callback({ didTimeout: false, timeRemaining: () => 50 }); - - expect([before, calls, request.mock.calls.length, cancel.mock.calls]).toEqual([[], ["idle"], 2, [[1]]]); - } finally { - request.mockRestore(); - cancel.mockRestore(); - } + const calls: string[] = []; + source.idle(() => calls.push("cancelled"))(); + source.idle(() => calls.push("idle")); + const before = [...calls]; + for (const callback of pending.values()) + callback({ didTimeout: false, timeRemaining: () => 50 }); + + expect([before, calls, requests, cancelled]).toEqual([[], ["idle"], 2, [1]]); }); it("calls back after 100 milliseconds where the browser has no idle callback, and not at all once cancelled", async () => { - vi.stubGlobal("requestIdleCallback", undefined); - try { - const source = new SystemTimeSource(); - const after = vi.spyOn(source, "after"); - const calls: string[] = []; - const changes = new ChangeSignalFixture(); - const call = (name: string) => (): void => { - calls.push(name); - changes.fire(); - }; - source.idle(call("cancelled"))(); - source.idle(call("idle")); - - await changes.untilAsync(() => expect(calls).toContain("idle")); - - expect([calls, after.mock.calls.map(t => t[1])]).toEqual([["idle"], [SystemTimeSourceResources.idleFallbackDelay, SystemTimeSourceResources.idleFallbackDelay]]); - } finally { - vi.unstubAllGlobals(); - } + const cancelled: number[] = []; + const source = new SystemTimeSource({ cancelIdleCallback: id => cancelled.push(id) }); + const after = vi.spyOn(source, "after"); + const calls: string[] = []; + const changes = new ChangeSignalFixture(); + const call = (name: string) => (): void => { + calls.push(name); + changes.fire(); + }; + source.idle(call("cancelled"))(); + source.idle(call("idle")); + + await changes.untilAsync(() => expect(calls).toContain("idle")); + + expect([calls, after.mock.calls.map(t => t[1]), cancelled]).toEqual([["idle"], [SystemTimeSourceResources.idleFallbackDelay, SystemTimeSourceResources.idleFallbackDelay], []]); }); }); diff --git a/src/noldova.ui.components.angular/tests/fixtures/code-highlights.fixture.spec.ts b/src/noldova.ui.components.angular/tests/fixtures/code-highlights.fixture.spec.ts index 2b5f52c6..3d625664 100644 --- a/src/noldova.ui.components.angular/tests/fixtures/code-highlights.fixture.spec.ts +++ b/src/noldova.ui.components.angular/tests/fixtures/code-highlights.fixture.spec.ts @@ -10,6 +10,7 @@ import { TestBed } from "@angular/core/testing"; import { CodeTokenKind } from "../../src/app/enums/code-token-kind"; import { CodeToken } from "../../src/app/models/code-token"; +import { HighlightTokens } from "../../src/app/models/highlight-tokens"; import { CodeHighlights } from "../../src/app/services/code-highlights"; import { CodeHighlightsFixture } from "./code-highlights.fixture"; @@ -32,16 +33,11 @@ describe("CodeHighlightsFixture", () => { expect([heardInCall, heard]).toEqual([[], [1, 0]]); }); - it("takes the CSS Highlight API away while a check runs, and puts it back once the check has failed", async () => { + it("has the TestBed's services see no CSS Highlight API, and leaves the page's own as it is", () => { const [constructor, registry] = [globalThis.Highlight, CSS.highlights]; - const seen: unknown[] = []; - const failure = await CodeHighlightsFixture.withoutHighlightApiAsync(async () => { - await Promise.resolve(); - seen.push(globalThis.Highlight, CSS.highlights); - throw new Error("failed"); - }).catch((error: unknown) => error); + CodeHighlightsFixture.withoutHighlightApi(); - expect([seen, failure instanceof Error, globalThis.Highlight === constructor, CSS.highlights === registry]).toEqual([[undefined, undefined], true, true, true]); + expect([TestBed.inject(HighlightTokens.available), globalThis.Highlight === constructor, CSS.highlights === registry]).toEqual([false, true, true]); }); }); diff --git a/src/noldova.ui.components.angular/tests/fixtures/code-highlights.fixture.ts b/src/noldova.ui.components.angular/tests/fixtures/code-highlights.fixture.ts index d5c31bea..a7150c21 100644 --- a/src/noldova.ui.components.angular/tests/fixtures/code-highlights.fixture.ts +++ b/src/noldova.ui.components.angular/tests/fixtures/code-highlights.fixture.ts @@ -8,6 +8,7 @@ import { TestBed } from "@angular/core/testing"; +import { HighlightTokens } from "../../src/app/models/highlight-tokens"; import { CodeHighlights } from "../../src/app/services/code-highlights"; import { ChangeSignalFixture } from "./change-signal.fixture"; @@ -30,22 +31,9 @@ export class CodeHighlightsFixture { return changes; } - // Runs a check as in a browser without the CSS Highlight API, as Safari before 17.2 and Firefox before 140, and puts the API back once the check - // ends, failed or not. A check makes what reads the API, such as the TestBed's CodeHighlights, inside it. - public static async withoutHighlightApiAsync(check: () => void | Promise): Promise { - const constructor = Object.getOwnPropertyDescriptor(globalThis, "Highlight"); - const registry = Object.getOwnPropertyDescriptor(CSS, "highlights"); - Object.defineProperty(globalThis, "Highlight", { value: undefined, configurable: true, writable: true }); - Object.defineProperty(CSS, "highlights", { value: undefined, configurable: true }); - try { - await check(); - } - finally { - for (const [target, name, descriptor] of [[globalThis, "Highlight", constructor], [CSS, "highlights", registry]] as const) - if (descriptor === undefined) - Reflect.deleteProperty(target, name); - else - Object.defineProperty(target, name, descriptor); - } + // Has the TestBed's services see a browser without the CSS Highlight API, as Safari before 17.2 and Firefox before 140, through + // HighlightTokens.available, so the page's own API stays as it is. A spec calls it before anything injects CodeHighlights or DiffHighlights. + public static withoutHighlightApi(): void { + TestBed.overrideProvider(HighlightTokens.available, { useValue: false }); } } diff --git a/src/noldova.ui.components.angular/tests/fixtures/isolated-specs.ts b/src/noldova.ui.components.angular/tests/fixtures/isolated-specs.ts new file mode 100644 index 00000000..486e00ee --- /dev/null +++ b/src/noldova.ui.components.angular/tests/fixtures/isolated-specs.ts @@ -0,0 +1,26 @@ +/** + * @license + * Copyright (c) Noldova. + * + * This source code is licensed under the license found in the + * LICENSE file in the root directory of this source tree. + */ + +export class IsolatedSpecs { + public static readonly files: readonly string[] = [ + "tests/app/components/code-block/code-block-server.component.spec.ts", + "tests/app/components/mention-field/mention-field-chips.spec.ts", + "tests/app/components/message/message.component.spec.ts", + "tests/app/components/site-card/site-card.component.spec.ts", + "tests/app/components/site-hero/site-hero.component.spec.ts", + "tests/app/components/site-theme-switch/site-theme-switch.component.spec.ts", + "tests/app/models/link-reference-color.spec.ts", + "tests/app/models/markdown-link.spec.ts", + "tests/app/models/mention-value.spec.ts", + "tests/app/services/code-highlighter-lifetime.spec.ts", + "tests/app/services/code-highlighter-time-limit.spec.ts", + "tests/app/services/overlay-bounds-server.service.spec.ts", + "tests/fixtures/timer-globals.fixture.spec.ts", + "tests/testing/services/kit-stylesheet-fixture.spec.ts" + ]; +}