blitz-pdf 0.1.4 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/README.md +67 -3
  2. package/THIRD_PARTY_NOTICES.md +2 -0
  3. package/dist/api.d.ts +9 -1
  4. package/dist/api.d.ts.map +1 -1
  5. package/dist/api.js +25 -27
  6. package/dist/api.js.map +1 -1
  7. package/dist/browser.d.ts +1 -1
  8. package/dist/browser.d.ts.map +1 -1
  9. package/dist/browser.js +13 -1
  10. package/dist/browser.js.map +1 -1
  11. package/dist/node-worker.d.ts +2 -0
  12. package/dist/node-worker.d.ts.map +1 -0
  13. package/dist/node-worker.js +10 -0
  14. package/dist/node-worker.js.map +1 -0
  15. package/dist/node.d.ts +1 -1
  16. package/dist/node.d.ts.map +1 -1
  17. package/dist/node.js +18 -6
  18. package/dist/node.js.map +1 -1
  19. package/dist/render.d.ts +8 -0
  20. package/dist/render.d.ts.map +1 -0
  21. package/dist/render.js +28 -0
  22. package/dist/render.js.map +1 -0
  23. package/dist/wasm.d.ts +3 -0
  24. package/dist/wasm.d.ts.map +1 -0
  25. package/dist/wasm.js +18 -0
  26. package/dist/wasm.js.map +1 -0
  27. package/dist/worker-host.d.ts +16 -0
  28. package/dist/worker-host.d.ts.map +1 -0
  29. package/dist/worker-host.js +31 -0
  30. package/dist/worker-host.js.map +1 -0
  31. package/dist/worker-protocol.d.ts +22 -0
  32. package/dist/worker-protocol.d.ts.map +1 -0
  33. package/dist/worker-protocol.js +2 -0
  34. package/dist/worker-protocol.js.map +1 -0
  35. package/dist/worker-runtime.d.ts +8 -0
  36. package/dist/worker-runtime.d.ts.map +1 -0
  37. package/dist/worker-runtime.js +34 -0
  38. package/dist/worker-runtime.js.map +1 -0
  39. package/dist/worker.d.ts +2 -0
  40. package/dist/worker.d.ts.map +1 -0
  41. package/dist/worker.js +7 -0
  42. package/dist/worker.js.map +1 -0
  43. package/package.json +5 -2
  44. package/src/api.ts +33 -22
  45. package/src/browser.ts +13 -3
  46. package/src/node-worker.ts +9 -0
  47. package/src/node.ts +13 -4
  48. package/src/render.ts +28 -0
  49. package/src/wasm.ts +17 -0
  50. package/src/worker-host.ts +45 -0
  51. package/src/worker-protocol.ts +10 -0
  52. package/src/worker-runtime.ts +35 -0
  53. package/src/worker.ts +12 -0
  54. package/vendor/README.md +24 -0
  55. package/vendor/blitz-paint/Cargo.toml +50 -0
  56. package/vendor/blitz-paint/LICENSE-APACHE +176 -0
  57. package/vendor/blitz-paint/LICENSE-MIT +23 -0
  58. package/vendor/blitz-paint/src/color.rs +66 -0
  59. package/vendor/blitz-paint/src/debug_overlay.rs +168 -0
  60. package/vendor/blitz-paint/src/filters.rs +40 -0
  61. package/vendor/blitz-paint/src/gradient.rs +536 -0
  62. package/vendor/blitz-paint/src/kurbo_css/css_box.rs +847 -0
  63. package/vendor/blitz-paint/src/kurbo_css/mod.rs +77 -0
  64. package/vendor/blitz-paint/src/kurbo_css/non_uniform_radii.rs +60 -0
  65. package/vendor/blitz-paint/src/layers.rs +95 -0
  66. package/vendor/blitz-paint/src/lib.rs +190 -0
  67. package/vendor/blitz-paint/src/render/background.rs +968 -0
  68. package/vendor/blitz-paint/src/render/border.rs +631 -0
  69. package/vendor/blitz-paint/src/render/box_shadow.rs +157 -0
  70. package/vendor/blitz-paint/src/render/clip_path.rs +492 -0
  71. package/vendor/blitz-paint/src/render/form_controls.rs +103 -0
  72. package/vendor/blitz-paint/src/render/mask.rs +144 -0
  73. package/vendor/blitz-paint/src/render.rs +1351 -0
  74. package/vendor/blitz-paint/src/sizing.rs +63 -0
  75. package/vendor/blitz-paint/src/text.rs +747 -0
  76. package/wasm/blitz_pdf_bg.wasm +0 -0
package/src/api.ts CHANGED
@@ -1,44 +1,55 @@
1
- import loadWasm, { render_pdf, engine_version, RenderJob } from "../wasm/blitz_pdf.js";
1
+ import loadWasm, { engine_version } from "../wasm/blitz_pdf.js";
2
2
  import { createAssetLoader } from "./assets.js";
3
3
  import { normalizeOptions } from "./options.js";
4
+ import { render, validateHtml } from "./render.js";
5
+ import { compileWasm } from "./wasm.js";
6
+ import { renderInWorker, type SpawnWorker } from "./worker-host.js";
4
7
  import type { InitOptions, PdfOptions, WasmSource } from "./types.js";
5
8
 
6
- export function createApi(defaultSource: () => Promise<WasmSource> | WasmSource,
7
- prepare: (source: WasmSource) => Promise<WasmSource> = async source => source) {
9
+ export interface ApiConfig {
10
+ defaultSource: () => Promise<WasmSource> | WasmSource;
11
+ prepare?: (source: WasmSource) => Promise<WasmSource>;
12
+ spawnWorker: SpawnWorker;
13
+ }
14
+
15
+ export function createApi({ defaultSource, prepare = async source => source, spawnWorker }: ApiConfig) {
16
+ let compiled: Promise<WebAssembly.Module> | undefined;
8
17
  let ready: Promise<void> | undefined;
9
18
 
19
+ function compile(source?: WasmSource): Promise<WebAssembly.Module> {
20
+ if (compiled) return compiled;
21
+ compiled = (async () => compileWasm(await prepare(source ?? await defaultSource())))()
22
+ .catch((error: unknown) => { compiled = undefined; throw error; });
23
+ return compiled;
24
+ }
25
+
10
26
  /** Initialize once. Concurrent callers share initialization; failed loads can be retried. */
11
27
  function init(options: InitOptions = {}): Promise<void> {
12
28
  if (ready) return ready;
13
29
  ready = (async () => {
14
- const source = await prepare(options.wasm ?? await defaultSource());
15
- await loadWasm({ module_or_path: source });
30
+ await loadWasm({ module_or_path: await compile(options.wasm) });
16
31
  })().catch((error: unknown) => { ready = undefined; throw error; });
17
32
  return ready;
18
33
  }
19
34
 
35
+ /** The compiled WASM module, compiled once and shared with every worker. It can be posted to your own workers. */
36
+ function getWasmModule(): Promise<WebAssembly.Module> { return compile(); }
37
+
20
38
  /** Render HTML/CSS to a vector PDF/A-3u with embedded fonts and selectable text. */
21
39
  async function renderPdf(html: string, options: PdfOptions = {}): Promise<Uint8Array> {
22
- if (typeof html !== "string") throw new TypeError("html must be a string");
23
- if (new TextEncoder().encode(html).byteLength > 16 * 1024 * 1024) throw new RangeError("HTML exceeds the 16 MiB limit");
40
+ validateHtml(html);
24
41
  const { assetResolver, ...normalized } = normalizeOptions(options);
25
42
  await init();
26
- if (!assetResolver) return render_pdf(html, normalized);
27
- const load = createAssetLoader(assetResolver);
28
- const job = new RenderJob(html, normalized);
29
- try {
30
- for (;;) {
31
- const urls = job.pending_assets();
32
- if (urls.length === 0) return job.finish();
33
- const data = await load(urls);
34
- for (let i = 0; i < urls.length; i++) job.provide_asset(urls[i]!, data[i]!);
35
- }
36
- } finally {
37
- // In-flight JS loaders never access this job, including after a sibling rejects.
38
- job.free();
39
- }
43
+ return render(html, normalized, assetResolver && createAssetLoader(assetResolver));
44
+ }
45
+
46
+ /** Like `renderPdf`, but layout and serialization run in a new worker. An `assets` function still runs on the calling thread. */
47
+ async function renderPdfInWorker(html: string, options: PdfOptions = {}): Promise<Uint8Array> {
48
+ validateHtml(html);
49
+ const { assetResolver, ...normalized } = normalizeOptions(options);
50
+ return renderInWorker(spawnWorker, await compile(), html, normalized, assetResolver);
40
51
  }
41
52
 
42
53
  async function getEngineVersion(): Promise<string> { await init(); return engine_version(); }
43
- return { init, renderPdf, getEngineVersion };
54
+ return { init, renderPdf, renderPdfInWorker, getWasmModule, getEngineVersion };
44
55
  }
package/src/browser.ts CHANGED
@@ -1,6 +1,16 @@
1
1
  import { createApi } from "./api.js";
2
2
 
3
3
  export type { AssetData, AssetMap, AssetResolver, AttachmentRelationship, BinaryData, InitOptions, Length, PageFormat, PageNumberOptions, PdfAttachment, PdfDate, PdfMetadata, PdfOptions, PdfXmpProperty, PdfXmpSchema, WasmSource } from "./types.js";
4
- export const { init, renderPdf, getEngineVersion } = createApi(
5
- () => new URL("../wasm/blitz_pdf_bg.wasm", import.meta.url),
6
- );
4
+ export const { init, renderPdf, renderPdfInWorker, getWasmModule, getEngineVersion } = createApi({
5
+ defaultSource: () => new URL("../wasm/blitz_pdf_bg.wasm", import.meta.url),
6
+ spawnWorker: events => {
7
+ const worker = new Worker(new URL("./worker.js", import.meta.url), { type: "module" });
8
+ worker.onmessage = event => events.message(event.data);
9
+ worker.onerror = event => {
10
+ event.preventDefault();
11
+ events.error(new Error(`Render worker failed: ${event.message || "unknown error"}`));
12
+ };
13
+ worker.onmessageerror = () => events.error(new Error("Render worker sent a message that could not be deserialized"));
14
+ return { post: (message, transfer) => worker.postMessage(message, transfer), terminate: () => worker.terminate() };
15
+ },
16
+ });
@@ -0,0 +1,9 @@
1
+ import { parentPort } from "node:worker_threads";
2
+ import { serve } from "./worker-runtime.js";
3
+
4
+ const port = parentPort;
5
+ if (!port) throw new Error("blitz-pdf node-worker must run in a worker thread");
6
+ serve({
7
+ post: (message, transfer) => port.postMessage(message, transfer),
8
+ onMessage: handler => { port.on("message", handler); },
9
+ });
package/src/node.ts CHANGED
@@ -1,12 +1,21 @@
1
1
  import { readFile } from "node:fs/promises";
2
+ import { Worker } from "node:worker_threads";
2
3
  import { createApi } from "./api.js";
3
4
 
4
5
  export type { AssetData, AssetMap, AssetResolver, AttachmentRelationship, BinaryData, InitOptions, Length, PageFormat, PageNumberOptions, PdfAttachment, PdfDate, PdfMetadata, PdfOptions, PdfXmpProperty, PdfXmpSchema, WasmSource } from "./types.js";
5
- export const { init, renderPdf, getEngineVersion } = createApi(
6
- () => readFile(new URL("../wasm/blitz_pdf_bg.wasm", import.meta.url)),
7
- async source => {
6
+ export const { init, renderPdf, renderPdfInWorker, getWasmModule, getEngineVersion } = createApi({
7
+ defaultSource: () => readFile(new URL("../wasm/blitz_pdf_bg.wasm", import.meta.url)),
8
+ prepare: async source => {
8
9
  if (source instanceof URL && source.protocol === "file:") return readFile(source);
9
10
  if (typeof source === "string" && source.startsWith("file:")) return readFile(new URL(source));
10
11
  return source;
11
12
  },
12
- );
13
+ spawnWorker: events => {
14
+ const worker = new Worker(new URL("./node-worker.js", import.meta.url));
15
+ worker.on("message", events.message);
16
+ worker.on("error", events.error);
17
+ worker.on("messageerror", events.error);
18
+ worker.on("exit", code => events.error(new Error(`Render worker exited with code ${code}`)));
19
+ return { post: (message, transfer) => worker.postMessage(message, transfer), terminate: () => void worker.terminate() };
20
+ },
21
+ });
package/src/render.ts ADDED
@@ -0,0 +1,28 @@
1
+ import { render_pdf, RenderJob } from "../wasm/blitz_pdf.js";
2
+ import type { normalizeOptions } from "./options.js";
3
+
4
+ /** Normalized options without the resolver function, so they can be posted to a worker. */
5
+ export type RenderOptions = Omit<ReturnType<typeof normalizeOptions>, "assetResolver">;
6
+ export type LoadAssets = (urls: string[]) => Promise<Uint8Array[]>;
7
+
8
+ export function validateHtml(html: unknown): asserts html is string {
9
+ if (typeof html !== "string") throw new TypeError("html must be a string");
10
+ if (new TextEncoder().encode(html).byteLength > 16 * 1024 * 1024) throw new RangeError("HTML exceeds the 16 MiB limit");
11
+ }
12
+
13
+ /** Requires an initialized WASM instance in the current thread. */
14
+ export async function render(html: string, options: RenderOptions, load?: LoadAssets): Promise<Uint8Array> {
15
+ if (!load) return render_pdf(html, options);
16
+ const job = new RenderJob(html, options);
17
+ try {
18
+ for (;;) {
19
+ const urls = job.pending_assets();
20
+ if (urls.length === 0) return job.finish();
21
+ const data = await load(urls);
22
+ for (let i = 0; i < urls.length; i++) job.provide_asset(urls[i]!, data[i]!);
23
+ }
24
+ } finally {
25
+ // In-flight JS loaders never access this job, including after a sibling rejects.
26
+ job.free();
27
+ }
28
+ }
package/src/wasm.ts ADDED
@@ -0,0 +1,17 @@
1
+ import type { WasmSource } from "./types.js";
2
+
3
+ export async function compileWasm(source: WasmSource): Promise<WebAssembly.Module> {
4
+ if (source instanceof WebAssembly.Module) return source;
5
+ if (typeof source === "string" || source instanceof URL || (typeof Request === "function" && source instanceof Request)) {
6
+ source = await fetch(source);
7
+ }
8
+ if (typeof Response === "function" && source instanceof Response) {
9
+ if (!source.ok) throw new Error(`Failed to fetch WASM: ${source.status} ${source.statusText} fetching '${source.url}'`);
10
+ // Streaming compilation rejects other MIME types, so fall back to buffering instead.
11
+ if (typeof WebAssembly.compileStreaming === "function" && source.headers.get("Content-Type") === "application/wasm") {
12
+ return WebAssembly.compileStreaming(source);
13
+ }
14
+ return WebAssembly.compile(await source.arrayBuffer());
15
+ }
16
+ return WebAssembly.compile(source as BufferSource);
17
+ }
@@ -0,0 +1,45 @@
1
+ import { createAssetLoader } from "./assets.js";
2
+ import type { RenderOptions } from "./render.js";
3
+ import type { AssetResolver } from "./types.js";
4
+ import type { HostMessage, WorkerMessage } from "./worker-protocol.js";
5
+
6
+ export interface WorkerEvents {
7
+ message(message: WorkerMessage): void;
8
+ /** Crashes, unreadable messages, or an exit before the render settled. */
9
+ error(error: unknown): void;
10
+ }
11
+
12
+ export interface WorkerHandle {
13
+ post(message: HostMessage, transfer: ArrayBuffer[]): void;
14
+ terminate(): void;
15
+ }
16
+
17
+ export type SpawnWorker = (events: WorkerEvents) => WorkerHandle;
18
+
19
+ /** Renders in a fresh worker that instantiates the precompiled module, then terminates it. */
20
+ export function renderInWorker(spawn: SpawnWorker, module: WebAssembly.Module, html: string,
21
+ options: RenderOptions, resolver: AssetResolver | undefined): Promise<Uint8Array> {
22
+ return new Promise<Uint8Array>((resolve, reject) => {
23
+ const load = resolver && createAssetLoader(resolver);
24
+ let settled = false;
25
+ const settle = (callback: () => void) => {
26
+ if (settled) return;
27
+ settled = true;
28
+ worker.terminate();
29
+ callback();
30
+ };
31
+ const worker: WorkerHandle = spawn({
32
+ message(message) {
33
+ if (message.type === "done") settle(() => resolve(message.pdf));
34
+ else if (message.type === "error") settle(() => reject(message.error));
35
+ else if (!load) settle(() => reject(new Error("Render worker requested assets without a resolver")));
36
+ else load(message.urls).then(
37
+ data => { if (!settled) worker.post({ type: "assets", data }, data.map(bytes => bytes.buffer as ArrayBuffer)); },
38
+ (error: unknown) => settle(() => reject(error)),
39
+ );
40
+ },
41
+ error(error) { settle(() => reject(error)); },
42
+ });
43
+ worker.post({ type: "render", module, html, options, external: load !== undefined }, []);
44
+ });
45
+ }
@@ -0,0 +1,10 @@
1
+ import type { RenderOptions } from "./render.js";
2
+
3
+ export type HostMessage =
4
+ | { type: "render"; module: WebAssembly.Module; html: string; options: RenderOptions; external: boolean }
5
+ | { type: "assets"; data: Uint8Array[] };
6
+
7
+ export type WorkerMessage =
8
+ | { type: "assets"; urls: string[] }
9
+ | { type: "done"; pdf: Uint8Array }
10
+ | { type: "error"; error: unknown };
@@ -0,0 +1,35 @@
1
+ import { initSync } from "../wasm/blitz_pdf.js";
2
+ import { render } from "./render.js";
3
+ import type { HostMessage, WorkerMessage } from "./worker-protocol.js";
4
+
5
+ export interface WorkerEndpoint {
6
+ post(message: WorkerMessage, transfer: ArrayBuffer[]): void;
7
+ onMessage(handler: (message: HostMessage) => void): void;
8
+ }
9
+
10
+ /** Worker side of `renderPdfInWorker`: one render per worker; asset bytes come from the host. */
11
+ export function serve(endpoint: WorkerEndpoint): void {
12
+ let receiveAssets: ((data: Uint8Array[]) => void) | undefined;
13
+ endpoint.onMessage(async message => {
14
+ if (message.type === "assets") {
15
+ const receive = receiveAssets;
16
+ receiveAssets = undefined;
17
+ receive?.(message.data);
18
+ return;
19
+ }
20
+ try {
21
+ initSync({ module: message.module });
22
+ const load = message.external
23
+ ? (urls: string[]) => new Promise<Uint8Array[]>(resolve => {
24
+ receiveAssets = resolve;
25
+ endpoint.post({ type: "assets", urls }, []);
26
+ })
27
+ : undefined;
28
+ const pdf = await render(message.html, message.options, load);
29
+ endpoint.post({ type: "done", pdf }, [pdf.buffer as ArrayBuffer]);
30
+ } catch (error) {
31
+ try { endpoint.post({ type: "error", error }, []); }
32
+ catch { endpoint.post({ type: "error", error: new Error(String(error)) }, []); }
33
+ }
34
+ });
35
+ }
package/src/worker.ts ADDED
@@ -0,0 +1,12 @@
1
+ import { serve } from "./worker-runtime.js";
2
+
3
+ interface DedicatedWorkerScope {
4
+ postMessage(message: unknown, transfer: Transferable[]): void;
5
+ onmessage: ((event: MessageEvent) => void) | null;
6
+ }
7
+
8
+ const scope = globalThis as unknown as DedicatedWorkerScope;
9
+ serve({
10
+ post: (message, transfer) => scope.postMessage(message, transfer),
11
+ onMessage: handler => { scope.onmessage = event => handler(event.data); },
12
+ });
package/vendor/README.md CHANGED
@@ -75,3 +75,27 @@ against rebuilt WASM. Layout tests check physical margins, fractional viewport
75
75
  widths, header/footer geometry, table line spacing, descendant alignment, empty
76
76
  paragraphs, explicit empty-box dimensions, exact page-boundary fits, constrained
77
77
  table columns, anonymous cells, and inheritance after CSS page-size changes.
78
+
79
+ # Blitz Unicode paint notifications
80
+
81
+ `blitz-paint/` contains `packages/blitz-paint` from Blitz revision
82
+ `e72650a6e67941852fddf025295cfee30c39ea32`, with its MIT/Apache-2.0 licenses.
83
+ Its standalone manifest expands the upstream workspace dependencies and pins
84
+ sibling crates to the same revision.
85
+
86
+ - `src/lib.rs`: add the opt-in `TextObserver` and `paint_scene_with_text` API.
87
+ The original `paint_scene` entry point keeps its existing behavior.
88
+ - `src/render.rs`: notify the observer immediately before painting inline text,
89
+ input/textarea text, and outside list markers; forward it to subdocuments.
90
+ The notifications supply the exact Parley layout and source string in paint
91
+ order, including visibility and stacking order decisions.
92
+
93
+ The PDF renderer associates the observed runs with individual scene commands
94
+ and checks that their glyphs match. It retains this immutable association when
95
+ replaying pages or repeated table fragments. It no longer uses glyph shapes as
96
+ document-wide source-text identities: `fi` and `fi`, for example, legitimately
97
+ share a shape while requiring different Unicode mappings.
98
+
99
+ When upgrading Blitz, retain these notifications at all text-paint boundaries
100
+ and run `tests/unicode.test.ts` (requires Poppler), the existing rendering,
101
+ pagination, and template suites, and `npm run test:pdfa` on the rebuilt WASM.
@@ -0,0 +1,50 @@
1
+ [package]
2
+ name = "blitz-paint"
3
+ description = "Paint a Blitz Document using anyrender"
4
+ documentation = "https://docs.rs/blitz-paint"
5
+ version = "0.3.0-beta.3"
6
+ license = "MIT OR Apache-2.0"
7
+ homepage = "https://github.com/dioxuslabs/blitz"
8
+ repository = "https://github.com/dioxuslabs/blitz"
9
+ categories = ["gui"]
10
+ edition = "2024"
11
+ rust-version = "1.91.0"
12
+
13
+ [features]
14
+ default = ["svg"]
15
+ tracing = ["dep:tracing"]
16
+ svg = ["dep:anyrender_svg", "dep:usvg", "blitz-dom/svg"]
17
+ custom-widget = ["blitz-dom/custom-widget"]
18
+ font-embolden = []
19
+ apple-font-embolden = []
20
+ # Paint overlay scrollbar thumbs on scroll containers, and enable their
21
+ # drag/hover interaction in blitz-dom (off by default while the feature
22
+ # matures).
23
+ scrollbars = ["blitz-dom/scrollbars"]
24
+
25
+ [dependencies]
26
+ # Blitz dependencies
27
+ anyrender = { version = "0.14.0" }
28
+ anyrender_svg = { version = "0.15.0", optional = true }
29
+ blitz-traits = { version = "=0.3.0-beta.3", default-features = false, git = "https://github.com/DioxusLabs/blitz", rev = "e72650a6e67941852fddf025295cfee30c39ea32" }
30
+ blitz-dom = { version = "=0.3.0-beta.3", default-features = false, git = "https://github.com/DioxusLabs/blitz", rev = "e72650a6e67941852fddf025295cfee30c39ea32" }
31
+
32
+ # Servo dependencies
33
+ style = { version = "0.22.0", package = "stylo" }
34
+ euclid = { version = "0.22" }
35
+
36
+ # DioxusLabs dependencies
37
+ taffy = { git = "https://github.com/DioxusLabs/taffy", rev = "6c2106e3df79493d304f954dc2cd4a4a382981d3", default-features = false, features = ["std", "flexbox", "flexbox_balance", "grid", "block_layout", "content_size", "calc", "detailed_layout_info"] }
38
+
39
+ # Linebender + WGPU dependencies
40
+ parley = { version = "0.12", default-features = false, features = ["std", "bytemuck"] }
41
+ skrifa = { version = "0.44", default-features = false, features = ["std"] }
42
+ color = { version = "0.3" }
43
+ peniko = { version = "0.6.0" }
44
+ kurbo = { version = "0.13.1" }
45
+ usvg = { version = "0.48.1", optional = true }
46
+
47
+ # Other dependencies
48
+ bytemuck = { version = "1" }
49
+ smallvec = { version = "1" }
50
+ tracing = { version = "0.1.40", optional = true }
@@ -0,0 +1,176 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
@@ -0,0 +1,23 @@
1
+ Permission is hereby granted, free of charge, to any
2
+ person obtaining a copy of this software and associated
3
+ documentation files (the "Software"), to deal in the
4
+ Software without restriction, including without
5
+ limitation the rights to use, copy, modify, merge,
6
+ publish, distribute, sublicense, and/or sell copies of
7
+ the Software, and to permit persons to whom the Software
8
+ is furnished to do so, subject to the following
9
+ conditions:
10
+
11
+ The above copyright notice and this permission notice
12
+ shall be included in all copies or substantial portions
13
+ of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
16
+ ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
17
+ TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
18
+ PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
19
+ SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20
+ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
22
+ IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
23
+ DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,66 @@
1
+ use color::{AlphaColor, DynamicColor, Srgb};
2
+ use style::color::AbsoluteColor;
3
+
4
+ pub type Color = AlphaColor<Srgb>;
5
+
6
+ pub trait ToColorColor {
7
+ /// Converts a color into the `AlphaColor<Srgb>` type from the `color` crate
8
+ fn as_srgb_color(&self) -> Color;
9
+
10
+ /// Converts a color into the `DynamicColor` type from the `color` crate
11
+ fn as_dynamic_color(&self) -> DynamicColor;
12
+ }
13
+ impl ToColorColor for AbsoluteColor {
14
+ fn as_srgb_color(&self) -> Color {
15
+ Color::new(
16
+ *self
17
+ .to_color_space(style::color::ColorSpace::Srgb)
18
+ .raw_components(),
19
+ )
20
+ }
21
+
22
+ fn as_dynamic_color(&self) -> DynamicColor {
23
+ DynamicColor::from_alpha_color(self.as_srgb_color())
24
+ }
25
+ }
26
+
27
+ /// The WCAG contrast ratio (>= 1) between two colours, matching Chrome's
28
+ /// `color_utils::GetContrastRatio`.
29
+ pub(crate) fn contrast_ratio(a: Color, b: Color) -> f32 {
30
+ // `relative_luminance` is defined on `OpaqueColor`; discard the alpha (which
31
+ // it ignores anyway) with `split`.
32
+ let la = a.split().0.relative_luminance() + 0.05;
33
+ let lb = b.split().0.relative_luminance() + 0.05;
34
+ if la > lb { la / lb } else { lb / la }
35
+ }
36
+
37
+ /// Blend `color` towards black or white (whichever has contrast headroom)
38
+ /// just far enough to reach `target` contrast with the original, so the
39
+ /// result is visibly distinct for any input. Transparent colours pass
40
+ /// through unchanged; alpha is preserved.
41
+ #[cfg(feature = "scrollbars")]
42
+ pub(crate) fn blend_for_contrast(color: Color, target: f32) -> Color {
43
+ let alpha = color.components[3];
44
+ if alpha == 0.0 {
45
+ return color;
46
+ }
47
+ let white = Color::new([1.0, 1.0, 1.0, alpha]);
48
+ let black = Color::new([0.0, 0.0, 0.0, alpha]);
49
+ let pole = if contrast_ratio(color, white) >= contrast_ratio(color, black) {
50
+ white
51
+ } else {
52
+ black
53
+ };
54
+ // Contrast grows monotonically towards the pole: bisect the blend
55
+ // fraction to land just past the target ratio.
56
+ let (mut lo, mut hi) = (0.0_f32, 1.0_f32);
57
+ for _ in 0..8 {
58
+ let mid = (lo + hi) / 2.0;
59
+ if contrast_ratio(color, color.lerp_rect(pole, mid)) < target {
60
+ lo = mid;
61
+ } else {
62
+ hi = mid;
63
+ }
64
+ }
65
+ color.lerp_rect(pole, hi)
66
+ }