drawnui-react 0.1.0-preview.41 → 0.1.0-preview.43

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 (51) hide show
  1. package/README.md +89 -7
  2. package/SKIPPED.md +7 -7
  3. package/dist/controls/GridStructure.d.ts +9 -1
  4. package/dist/controls/GridStructure.js +41 -1
  5. package/dist/controls/SkiaEditor.d.ts +4 -1
  6. package/dist/controls/SkiaEditor.js +25 -6
  7. package/dist/controls/SkiaImage.d.ts +5 -0
  8. package/dist/controls/SkiaImage.js +32 -5
  9. package/dist/controls/SkiaLabel.d.ts +85 -4
  10. package/dist/controls/SkiaLabel.js +406 -20
  11. package/dist/controls/SkiaLabelFps.d.ts +0 -3
  12. package/dist/controls/SkiaLabelFps.js +1 -11
  13. package/dist/controls/SkiaLayout.js +33 -2
  14. package/dist/controls/SkiaScroll.d.ts +51 -2
  15. package/dist/controls/SkiaScroll.js +150 -9
  16. package/dist/controls/SkiaShape.d.ts +2 -0
  17. package/dist/controls/SkiaShape.js +7 -0
  18. package/dist/controls/SkiaShell.d.ts +282 -0
  19. package/dist/controls/SkiaShell.js +972 -0
  20. package/dist/controls/SkiaSprite.js +5 -1
  21. package/dist/core/Accessibility.d.ts +30 -13
  22. package/dist/core/Accessibility.js +237 -43
  23. package/dist/core/Canvas.d.ts +122 -14
  24. package/dist/core/Canvas.js +585 -47
  25. package/dist/core/Gestures.d.ts +11 -1
  26. package/dist/core/Gestures.js +12 -1
  27. package/dist/core/PopupWindows.js +2 -0
  28. package/dist/core/Props.d.ts +11 -0
  29. package/dist/core/Props.js +44 -0
  30. package/dist/core/ScrollAnimators.d.ts +6 -0
  31. package/dist/core/ScrollAnimators.js +7 -1
  32. package/dist/core/SkiaControl.d.ts +24 -4
  33. package/dist/core/SkiaControl.js +59 -13
  34. package/dist/core/SkiaEffect.d.ts +12 -1
  35. package/dist/core/SkiaEffect.js +35 -8
  36. package/dist/core/SkiaImageManager.d.ts +101 -18
  37. package/dist/core/SkiaImageManager.js +318 -63
  38. package/dist/core/Styles.js +7 -1
  39. package/dist/core/Super.d.ts +4 -0
  40. package/dist/core/Super.js +4 -9
  41. package/dist/core/TextInputProxy.d.ts +31 -1
  42. package/dist/core/TextInputProxy.js +97 -15
  43. package/dist/index.d.ts +1 -0
  44. package/dist/index.js +1 -0
  45. package/dist/react/SkiaShell.d.ts +8 -74
  46. package/dist/react/SkiaShell.js +163 -514
  47. package/dist/react/index.d.ts +6 -1
  48. package/dist/react/index.js +51 -40
  49. package/dist/react/reconciler.d.ts +12 -0
  50. package/dist/react/reconciler.js +22 -46
  51. package/package.json +37 -4
@@ -2,42 +2,125 @@ import type { Image } from "canvaskit-wasm";
2
2
  /** C# LoadPriority: order of the managed load queue. */
3
3
  export type LoadPriority = "Low" | "Normal" | "High";
4
4
  /**
5
- * Mirrors DrawnUi SkiaImageManager: loads + decodes image sources once and shares the decoded CanvasKit Image
6
- * between all SkiaImage instances using the same source (`ReuseBitmaps`). `LoadImageManagedAsync` goes through the
7
- * priority queue (High > Normal > Low, at most `MaxParallelLoads` fetches in flight, C# semaphore of 5; the same
8
- * source requested twice is fetched once), `LoadImageAsync` loads directly. `PreloadImages` warms the cache,
9
- * `CancelAll` drops what is still queued. Sources are URLs (absolute, or relative to the page like "images/photo.jpg").
5
+ * Mirrors DrawnUi SkiaImageManager (DrawnUi.Net): loads and decodes image sources, keeps the decoded images in a cache
6
+ * by source for `CacheLongevitySecs`, and shares one decoded image between every control on the same source
7
+ * (`ReuseBitmaps`; off, each caller gets a copy of its own of the one cached copy). `LoadImageManagedAsync` caches and
8
+ * goes through the priority queue (High > Normal > Low, at most `MaxParallelLoads` fetches in flight; the same source
9
+ * requested twice is fetched once); `LoadImageAsync` is a direct load that does not touch the cache. The cache keeps
10
+ * at most `CacheBudgetMb` megabytes of decoded pixels: over it, images no control holds go, the one held longest ago first
11
+ * (as DrawnUI for Rust's image cache); images a control holds never go. Keys are case-insensitive and local paths
12
+ * normalized (backslashes, a leading slash). Sources are URLs (absolute, or relative to the page like
13
+ * "images/photo.jpg").
14
+ *
15
+ * Ownership: CanvasKit images must be deleted by hand. The manager deletes an image it made once no holder draws it
16
+ * and the cache no longer keeps it; a control holds the image it shows (`Hold`) and lets it go (`Free`). Removing an
17
+ * entry from the cache (`RemoveFromCache`, `ClearCache`, expiry, the budget) never deletes an image a control holds.
10
18
  */
11
19
  export declare class SkiaImageManager {
12
20
  static readonly Instance: SkiaImageManager;
13
- /** Keep decoded images for reuse across controls (DrawnUi ReuseBitmaps). */
21
+ /** Share one decoded image between every control on the same source (DrawnUi ReuseBitmaps, on by default). */
14
22
  static ReuseBitmaps: boolean;
23
+ /** Use the cache at all (DrawnUi UseCache): off, every load fetches and decodes again. */
24
+ static UseCache: boolean;
25
+ /** Seconds a cached image is kept before the next load fetches it again (DrawnUi, 30 minutes). */
26
+ static CacheLongevitySecs: number;
27
+ /**
28
+ * Most megabytes of decoded pixels the cache keeps (DrawnUi CacheBudgetMb, 128 as DrawnUI for Rust; 0 or less = no
29
+ * limit). Images a control holds never go for it.
30
+ */
31
+ static CacheBudgetMb: number;
15
32
  /** Fetches in flight at once through the managed queue (C# CreateSemaphoreForLocalFiles: 5). */
16
33
  static MaxParallelLoads: number;
17
- /** C# CanReload: raised when a queued load failed so the caller may retry later. */
18
- CanReload?: (source: string, error: Error) => void;
34
+ /** Retry a failed load (DrawnUi EnableHttpRetry): up to HttpRetryMaxAttempts more times, 100, 200, 400 ms apart. */
35
+ static EnableHttpRetry: boolean;
36
+ static HttpRetryMaxAttempts: number;
37
+ /** Base address of relative sources (DrawnUi HttpBaseAddress); unset, they resolve against the page. */
38
+ static HttpBaseAddress?: string;
39
+ /** C# CanReload: raised when `IsLoadingLocked` is turned off, so what waited or failed meanwhile may load again. */
40
+ CanReload?: () => void;
19
41
  private readonly cache;
20
- private readonly pending;
42
+ /** Every image the manager made and still tracks: cached ones and the copies it handed out. */
43
+ private readonly owned;
44
+ private readonly inflight;
21
45
  private readonly queue;
22
46
  private readonly waiting;
47
+ private readonly registered;
23
48
  private running;
49
+ private used;
50
+ private tick;
51
+ private locked;
52
+ private unlocked;
53
+ private unlock?;
24
54
  /** Queue diagnostics. */
25
55
  get QueuedCount(): number;
26
56
  get RunningCount(): number;
27
- /** Cached decoded image, if loaded already (C# GetFromCache). */
28
- GetFromCache(source: string): Image | undefined;
29
- /** Direct load without the queue (C# LoadImageAsync); cached and de-duplicated. Rejects on network/decode failure. */
30
- LoadImageAsync(source: string, signal?: AbortSignal): Promise<Image>;
57
+ /** Megabytes of decoded pixels the cache holds now (DrawnUi CacheMemoryMb). */
58
+ get CacheMemoryMb(): number;
59
+ /** The browser says it has no network. */
60
+ get IsOffline(): boolean;
61
+ /** While true, managed loads wait (DrawnUi IsLoadingLocked); turning it off lets them go and raises CanReload. */
62
+ get IsLoadingLocked(): boolean;
63
+ set IsLoadingLocked(value: boolean);
64
+ /** Registers a source under a name of its own (DrawnUi RegisterImage): loading `alias` loads `source`. */
65
+ RegisterImage(alias: string, source?: string): void;
66
+ /** Cache key: case-insensitive, a local path with forward slashes and no leading slash (DrawnUi GetCacheKey). */
67
+ static Key(source: string): string;
68
+ /** A holder (a control) draws this image now: it is not deleted until let go. Images the manager did not make are ignored. */
69
+ Hold(image: Image | undefined): void;
70
+ /** The holder no longer draws it: an image no holder draws and the cache does not keep is deleted. */
71
+ Free(image: Image | undefined): void;
72
+ /** Deletes an image nobody keeps any more. */
73
+ private Forget;
74
+ private Track;
75
+ /** A copy of an image of its own (ReuseBitmaps off), tracked so its holder frees it. */
76
+ private Copy;
77
+ /** What a caller gets of a cached image: the shared one, or a copy of its own (ReuseBitmaps off). */
78
+ private HandOut;
79
+ /** Puts an image in the cache for `cacheLongevitySecs` (DrawnUi AddToCache); false when cached already or caching is off. */
80
+ AddToCache(uri: string, image: Image, cacheLongevitySecs?: number): boolean;
81
+ /** Replaces the cached image of a source (DrawnUi UpdateInCache, minutes as .NET). */
82
+ UpdateInCache(uri: string, image: Image, cacheLongevityMinutes: number): void;
83
+ /** Drops the image from the cache, so the next load reads it again (DrawnUi RemoveFromCache); false when it was not cached. */
84
+ RemoveFromCache(uri: string): boolean;
85
+ /** Drops every cached image; images controls still show stay until they let them go. */
86
+ ClearCache(): void;
87
+ /** RemoveFromCache(source) or ClearCache(). */
88
+ Clear(source?: string): void;
89
+ private Drop;
90
+ private CleanupExpired;
91
+ /** Over the budget: the cached images no holder draws go, the one held longest ago first (DrawnUI for Rust trim). */
92
+ Trim(): void;
93
+ /** The cached image of a source, or undefined (DrawnUi GetFromCache): the shared one, or a copy (ReuseBitmaps off). */
94
+ GetFromCache(url: string): Image | undefined;
95
+ /** The cached image itself, whatever ReuseBitmaps says (DrawnUi GetFromCacheInternal). */
96
+ GetFromCacheInternal(url: string): Image | undefined;
97
+ /** The address a source is fetched from: its registered file, against HttpBaseAddress, stamped (Super.ResolveAssetUrl). */
98
+ private Address;
99
+ /** Fetches and decodes a source, retried when it fails (EnableHttpRetry); undefined when it could not be loaded. */
31
100
  private Fetch;
32
- /** Queued load (C# LoadImageManagedAsync): cached images resolve at once, the rest wait their turn by priority. */
33
- LoadImageManagedAsync(source: string, signal?: AbortSignal, priority?: LoadPriority): Promise<Image>;
101
+ /**
102
+ * Direct load without the queue and the cache (C# LoadImageAsync): a new image the caller owns (delete it, or hand it
103
+ * to a control that holds it); undefined when it could not be loaded.
104
+ */
105
+ LoadImageAsync(source: string, signal?: AbortSignal): Promise<Image | undefined>;
106
+ /**
107
+ * Queued, cached load (C# LoadImageManagedAsync): a cached image resolves at once, the rest wait their turn by priority;
108
+ * one fetch serves every request of the same source. Resolves to the shared image (ReuseBitmaps) or a copy of its own,
109
+ * undefined when it could not be loaded. As the DrawnUi.Net Blazor head: when the caller's signal aborts a cached load,
110
+ * or a load waiting for IsLoadingLocked, the promise rejects with the abort (an AbortError, C# OperationCanceledException);
111
+ * with UseCache off a cancelled load resolves to undefined.
112
+ */
113
+ LoadImageManagedAsync(source: string, signal?: AbortSignal, priority?: LoadPriority): Promise<Image | undefined>;
114
+ /** C# Task.WaitAsync(token): rejects with the abort when the signal aborts; the load itself goes on for the others. */
115
+ private static WithCancel;
116
+ private Enqueue;
117
+ /** A fresh image goes into the cache; the cached one (an equal source loaded meanwhile) wins. */
118
+ private Cached;
34
119
  private Pump;
35
120
  /** C# PreloadImage: warms the cache for one source; failures are ignored. */
36
121
  PreloadImage(source: string, priority?: LoadPriority): Promise<void>;
37
122
  /** Warms the cache so first paint of these images is instant (DrawnUi PreloadImages). Failures are ignored. */
38
123
  PreloadImages(sources: string[], priority?: LoadPriority): Promise<void>;
39
- /** Drops everything still waiting in the queue (C# CancelAll); loads already in flight finish. */
124
+ /** Drops everything still waiting in the queue (C# CancelAll): those loads resolve to nothing; loads in flight finish. */
40
125
  CancelAll(): void;
41
- /** Drops a cached image (or everything) — decoded images hold GPU/WASM memory. */
42
- Clear(source?: string): void;
43
126
  }
@@ -1,70 +1,318 @@
1
1
  import { Super } from "./Super";
2
2
  const PRIORITY_RANK = { High: 0, Normal: 1, Low: 2 };
3
3
  /**
4
- * Mirrors DrawnUi SkiaImageManager: loads + decodes image sources once and shares the decoded CanvasKit Image
5
- * between all SkiaImage instances using the same source (`ReuseBitmaps`). `LoadImageManagedAsync` goes through the
6
- * priority queue (High > Normal > Low, at most `MaxParallelLoads` fetches in flight, C# semaphore of 5; the same
7
- * source requested twice is fetched once), `LoadImageAsync` loads directly. `PreloadImages` warms the cache,
8
- * `CancelAll` drops what is still queued. Sources are URLs (absolute, or relative to the page like "images/photo.jpg").
4
+ * Mirrors DrawnUi SkiaImageManager (DrawnUi.Net): loads and decodes image sources, keeps the decoded images in a cache
5
+ * by source for `CacheLongevitySecs`, and shares one decoded image between every control on the same source
6
+ * (`ReuseBitmaps`; off, each caller gets a copy of its own of the one cached copy). `LoadImageManagedAsync` caches and
7
+ * goes through the priority queue (High > Normal > Low, at most `MaxParallelLoads` fetches in flight; the same source
8
+ * requested twice is fetched once); `LoadImageAsync` is a direct load that does not touch the cache. The cache keeps
9
+ * at most `CacheBudgetMb` megabytes of decoded pixels: over it, images no control holds go, the one held longest ago first
10
+ * (as DrawnUI for Rust's image cache); images a control holds never go. Keys are case-insensitive and local paths
11
+ * normalized (backslashes, a leading slash). Sources are URLs (absolute, or relative to the page like
12
+ * "images/photo.jpg").
13
+ *
14
+ * Ownership: CanvasKit images must be deleted by hand. The manager deletes an image it made once no holder draws it
15
+ * and the cache no longer keeps it; a control holds the image it shows (`Hold`) and lets it go (`Free`). Removing an
16
+ * entry from the cache (`RemoveFromCache`, `ClearCache`, expiry, the budget) never deletes an image a control holds.
9
17
  */
10
18
  export class SkiaImageManager {
11
19
  static Instance = new SkiaImageManager();
12
- /** Keep decoded images for reuse across controls (DrawnUi ReuseBitmaps). */
20
+ /** Share one decoded image between every control on the same source (DrawnUi ReuseBitmaps, on by default). */
13
21
  static ReuseBitmaps = true;
22
+ /** Use the cache at all (DrawnUi UseCache): off, every load fetches and decodes again. */
23
+ static UseCache = true;
24
+ /** Seconds a cached image is kept before the next load fetches it again (DrawnUi, 30 minutes). */
25
+ static CacheLongevitySecs = 1800;
26
+ /**
27
+ * Most megabytes of decoded pixels the cache keeps (DrawnUi CacheBudgetMb, 128 as DrawnUI for Rust; 0 or less = no
28
+ * limit). Images a control holds never go for it.
29
+ */
30
+ static CacheBudgetMb = 128;
14
31
  /** Fetches in flight at once through the managed queue (C# CreateSemaphoreForLocalFiles: 5). */
15
32
  static MaxParallelLoads = 5;
16
- /** C# CanReload: raised when a queued load failed so the caller may retry later. */
33
+ /** Retry a failed load (DrawnUi EnableHttpRetry): up to HttpRetryMaxAttempts more times, 100, 200, 400 ms apart. */
34
+ static EnableHttpRetry = true;
35
+ static HttpRetryMaxAttempts = 3;
36
+ /** Base address of relative sources (DrawnUi HttpBaseAddress); unset, they resolve against the page. */
37
+ static HttpBaseAddress;
38
+ /** C# CanReload: raised when `IsLoadingLocked` is turned off, so what waited or failed meanwhile may load again. */
17
39
  CanReload;
18
40
  cache = new Map();
19
- pending = new Map();
41
+ /** Every image the manager made and still tracks: cached ones and the copies it handed out. */
42
+ owned = new Map();
43
+ inflight = new Map();
20
44
  queue = [];
21
45
  waiting = new Map();
46
+ registered = new Map();
22
47
  running = 0;
48
+ used = 0;
49
+ tick = 0;
50
+ locked = false;
51
+ unlocked = Promise.resolve();
52
+ unlock;
23
53
  /** Queue diagnostics. */
24
54
  get QueuedCount() { return this.queue.length; }
25
55
  get RunningCount() { return this.running; }
26
- /** Cached decoded image, if loaded already (C# GetFromCache). */
27
- GetFromCache(source) { return this.cache.get(source); }
28
- /** Direct load without the queue (C# LoadImageAsync); cached and de-duplicated. Rejects on network/decode failure. */
29
- LoadImageAsync(source, signal) {
30
- const cached = this.cache.get(source);
31
- if (cached)
32
- return Promise.resolve(cached);
33
- let inflight = this.pending.get(source);
34
- if (inflight)
35
- return inflight;
36
- inflight = this.Fetch(source, signal);
37
- this.pending.set(source, inflight);
38
- inflight.finally(() => this.pending.delete(source)).catch(() => undefined);
39
- return inflight;
56
+ /** Megabytes of decoded pixels the cache holds now (DrawnUi CacheMemoryMb). */
57
+ get CacheMemoryMb() { return this.used / (1 << 20); }
58
+ /** The browser says it has no network. */
59
+ get IsOffline() { return typeof navigator !== "undefined" && navigator.onLine === false; }
60
+ /** While true, managed loads wait (DrawnUi IsLoadingLocked); turning it off lets them go and raises CanReload. */
61
+ get IsLoadingLocked() { return this.locked; }
62
+ set IsLoadingLocked(value) {
63
+ if (this.locked === value)
64
+ return;
65
+ this.locked = value;
66
+ if (value)
67
+ this.unlocked = new Promise((r) => { this.unlock = r; });
68
+ else {
69
+ this.unlock?.();
70
+ this.unlock = undefined;
71
+ this.CanReload?.();
72
+ }
40
73
  }
41
- async Fetch(source, signal) {
42
- const response = await fetch(Super.ResolveAssetUrl(source), signal ? { signal } : undefined);
43
- if (!response.ok)
44
- throw new Error(`DrawnUi: ${response.status} loading image '${source}'`);
45
- const image = Super.CK.MakeImageFromEncoded(await response.arrayBuffer());
74
+ /** Registers a source under a name of its own (DrawnUi RegisterImage): loading `alias` loads `source`. */
75
+ RegisterImage(alias, source) {
76
+ if (!alias)
77
+ throw new Error("Image source URL cannot be empty.");
78
+ this.registered.set(SkiaImageManager.Key(alias), source ?? alias);
79
+ }
80
+ /** Cache key: case-insensitive, a local path with forward slashes and no leading slash (DrawnUi GetCacheKey). */
81
+ static Key(source) {
82
+ if (!source || source.includes("://"))
83
+ return source.toLowerCase();
84
+ let key = source.replace(/\\/g, "/");
85
+ if (key.startsWith("/") && !key.startsWith("//"))
86
+ key = key.replace(/^\/+/, "");
87
+ return key.toLowerCase();
88
+ }
89
+ // ---- holders ----
90
+ /** A holder (a control) draws this image now: it is not deleted until let go. Images the manager did not make are ignored. */
91
+ Hold(image) {
92
+ const entry = image && this.owned.get(image);
93
+ if (entry) {
94
+ entry.Holders++;
95
+ entry.Shown = ++this.tick;
96
+ }
97
+ }
98
+ /** The holder no longer draws it: an image no holder draws and the cache does not keep is deleted. */
99
+ Free(image) {
100
+ const entry = image && this.owned.get(image);
101
+ if (!entry)
102
+ return;
103
+ entry.Holders = Math.max(0, entry.Holders - 1);
104
+ entry.Shown = ++this.tick;
105
+ this.Forget(entry);
106
+ }
107
+ /** Deletes an image nobody keeps any more. */
108
+ Forget(entry) {
109
+ if (entry.Holders > 0 || entry.Cached)
110
+ return;
111
+ this.owned.delete(entry.Image);
112
+ if (!entry.Image.isDeleted())
113
+ entry.Image.delete();
114
+ }
115
+ Track(image, key) {
116
+ let entry = this.owned.get(image);
117
+ if (!entry) {
118
+ entry = { Image: image, Key: key, Bytes: image.width() * image.height() * 4, Cached: false, Expires: 0, Shown: ++this.tick, Holders: 0 };
119
+ this.owned.set(image, entry);
120
+ }
121
+ return entry;
122
+ }
123
+ /** A copy of an image of its own (ReuseBitmaps off), tracked so its holder frees it. */
124
+ Copy(image, key) {
125
+ const CK = Super.CK;
126
+ const info = { width: image.width(), height: image.height(), colorType: CK.ColorType.RGBA_8888, alphaType: CK.AlphaType.Premul, colorSpace: CK.ColorSpace.SRGB };
127
+ const pixels = image.readPixels(0, 0, info);
128
+ const copy = pixels instanceof Uint8Array ? CK.MakeImage(info, pixels, info.width * 4) : null;
129
+ if (!copy)
130
+ return undefined;
131
+ this.Track(copy, key);
132
+ return copy;
133
+ }
134
+ /** What a caller gets of a cached image: the shared one, or a copy of its own (ReuseBitmaps off). */
135
+ HandOut(image, key) {
46
136
  if (!image)
47
- throw new Error(`DrawnUi: cannot decode image '${source}'`);
48
- if (SkiaImageManager.ReuseBitmaps)
49
- this.cache.set(source, image);
137
+ return undefined;
138
+ return SkiaImageManager.ReuseBitmaps ? image : this.Copy(image, key);
139
+ }
140
+ // ---- the cache ----
141
+ /** Puts an image in the cache for `cacheLongevitySecs` (DrawnUi AddToCache); false when cached already or caching is off. */
142
+ AddToCache(uri, image, cacheLongevitySecs = SkiaImageManager.CacheLongevitySecs) {
143
+ if (!SkiaImageManager.UseCache || !uri || !image)
144
+ return false;
145
+ const key = SkiaImageManager.Key(uri);
146
+ this.CleanupExpired(key);
147
+ if (this.cache.has(key))
148
+ return false;
149
+ const entry = this.Track(image, key);
150
+ entry.Cached = true;
151
+ entry.Expires = performance.now() + cacheLongevitySecs * 1000;
152
+ entry.Shown = ++this.tick;
153
+ this.cache.set(key, entry);
154
+ this.used += entry.Bytes;
155
+ this.Trim();
156
+ return true;
157
+ }
158
+ /** Replaces the cached image of a source (DrawnUi UpdateInCache, minutes as .NET). */
159
+ UpdateInCache(uri, image, cacheLongevityMinutes) {
160
+ this.RemoveFromCache(uri);
161
+ this.AddToCache(uri, image, cacheLongevityMinutes * 60);
162
+ }
163
+ /** Drops the image from the cache, so the next load reads it again (DrawnUi RemoveFromCache); false when it was not cached. */
164
+ RemoveFromCache(uri) {
165
+ if (!uri)
166
+ return false;
167
+ const entry = this.cache.get(SkiaImageManager.Key(uri));
168
+ if (!entry)
169
+ return false;
170
+ this.Drop(entry);
171
+ return true;
172
+ }
173
+ /** Drops every cached image; images controls still show stay until they let them go. */
174
+ ClearCache() { for (const entry of [...this.cache.values()])
175
+ this.Drop(entry); }
176
+ /** RemoveFromCache(source) or ClearCache(). */
177
+ Clear(source) { if (source)
178
+ this.RemoveFromCache(source);
179
+ else
180
+ this.ClearCache(); }
181
+ Drop(entry) {
182
+ if (!entry.Cached)
183
+ return;
184
+ this.cache.delete(entry.Key);
185
+ this.used -= entry.Bytes;
186
+ entry.Cached = false;
187
+ this.Forget(entry);
188
+ }
189
+ CleanupExpired(key) {
190
+ const entry = this.cache.get(key);
191
+ if (entry && entry.Expires <= performance.now())
192
+ this.Drop(entry);
193
+ }
194
+ /** Over the budget: the cached images no holder draws go, the one held longest ago first (DrawnUI for Rust trim). */
195
+ Trim() {
196
+ const budget = SkiaImageManager.CacheBudgetMb * (1 << 20);
197
+ if (SkiaImageManager.CacheBudgetMb <= 0 || this.used <= budget)
198
+ return;
199
+ const idle = [...this.cache.values()].filter((e) => e.Holders === 0).sort((a, b) => a.Shown - b.Shown);
200
+ for (const entry of idle) {
201
+ if (this.used <= budget)
202
+ break;
203
+ this.Drop(entry);
204
+ }
205
+ }
206
+ /** The cached image of a source, or undefined (DrawnUi GetFromCache): the shared one, or a copy (ReuseBitmaps off). */
207
+ GetFromCache(url) {
208
+ return this.HandOut(this.GetFromCacheInternal(url), SkiaImageManager.Key(url));
209
+ }
210
+ /** The cached image itself, whatever ReuseBitmaps says (DrawnUi GetFromCacheInternal). */
211
+ GetFromCacheInternal(url) {
212
+ if (!SkiaImageManager.UseCache || !url)
213
+ return undefined;
214
+ const key = SkiaImageManager.Key(url);
215
+ this.CleanupExpired(key);
216
+ const entry = this.cache.get(key);
217
+ if (!entry)
218
+ return undefined;
219
+ entry.Shown = ++this.tick;
220
+ return entry.Image;
221
+ }
222
+ // ---- loading ----
223
+ /** The address a source is fetched from: its registered file, against HttpBaseAddress, stamped (Super.ResolveAssetUrl). */
224
+ Address(source) {
225
+ const file = this.registered.get(SkiaImageManager.Key(source)) ?? source;
226
+ const base = SkiaImageManager.HttpBaseAddress;
227
+ return Super.ResolveAssetUrl(base && !file.includes("://") ? new URL(file, base).href : file);
228
+ }
229
+ /** Fetches and decodes a source, retried when it fails (EnableHttpRetry); undefined when it could not be loaded. */
230
+ async Fetch(source, signal) {
231
+ const attempts = SkiaImageManager.EnableHttpRetry ? SkiaImageManager.HttpRetryMaxAttempts : 0;
232
+ let error;
233
+ for (let attempt = 0; attempt <= attempts; attempt++) {
234
+ if (signal?.aborted)
235
+ return { Error: new Error("DrawnUi: image load cancelled") };
236
+ try {
237
+ const response = await fetch(this.Address(source), signal ? { signal } : undefined);
238
+ if (!response.ok)
239
+ error = new Error(`DrawnUi: ${response.status} loading image '${source}'`);
240
+ else {
241
+ const image = Super.CK.MakeImageFromEncoded(await response.arrayBuffer());
242
+ if (image)
243
+ return { Image: image };
244
+ error = new Error(`DrawnUi: cannot decode image '${source}'`);
245
+ }
246
+ }
247
+ catch (e) {
248
+ if (signal?.aborted)
249
+ return { Error: new Error("DrawnUi: image load cancelled") };
250
+ error = e instanceof Error ? e : new Error(String(e));
251
+ }
252
+ if (attempt < attempts)
253
+ await new Promise((r) => setTimeout(r, 2 ** attempt * 100));
254
+ }
255
+ return { Error: error };
256
+ }
257
+ /**
258
+ * Direct load without the queue and the cache (C# LoadImageAsync): a new image the caller owns (delete it, or hand it
259
+ * to a control that holds it); undefined when it could not be loaded.
260
+ */
261
+ async LoadImageAsync(source, signal) {
262
+ const { Image: image } = await this.Fetch(source, signal);
263
+ if (image)
264
+ this.Track(image, SkiaImageManager.Key(source));
50
265
  return image;
51
266
  }
52
- /** Queued load (C# LoadImageManagedAsync): cached images resolve at once, the rest wait their turn by priority. */
53
- LoadImageManagedAsync(source, signal, priority = "Normal") {
54
- const cached = this.cache.get(source);
267
+ /**
268
+ * Queued, cached load (C# LoadImageManagedAsync): a cached image resolves at once, the rest wait their turn by priority;
269
+ * one fetch serves every request of the same source. Resolves to the shared image (ReuseBitmaps) or a copy of its own,
270
+ * undefined when it could not be loaded. As the DrawnUi.Net Blazor head: when the caller's signal aborts a cached load,
271
+ * or a load waiting for IsLoadingLocked, the promise rejects with the abort (an AbortError, C# OperationCanceledException);
272
+ * with UseCache off a cancelled load resolves to undefined.
273
+ */
274
+ async LoadImageManagedAsync(source, signal, priority = "Normal") {
275
+ if (!source)
276
+ return undefined;
277
+ while (this.locked)
278
+ await SkiaImageManager.WithCancel(this.unlocked, signal);
279
+ const key = SkiaImageManager.Key(source);
280
+ if (!SkiaImageManager.UseCache)
281
+ return this.Enqueue(key, source, priority, signal, false);
282
+ const cached = this.GetFromCacheInternal(key);
55
283
  if (cached)
56
- return Promise.resolve(cached);
57
- const inflight = this.pending.get(source);
58
- if (inflight)
59
- return inflight;
284
+ return this.HandOut(cached, key);
285
+ let task = this.inflight.get(key);
286
+ if (!task) {
287
+ task = this.Enqueue(key, source, priority, signal, true);
288
+ this.inflight.set(key, task);
289
+ void task.finally(() => this.inflight.delete(key));
290
+ }
291
+ return this.HandOut(await SkiaImageManager.WithCancel(task, signal), key);
292
+ }
293
+ /** C# Task.WaitAsync(token): rejects with the abort when the signal aborts; the load itself goes on for the others. */
294
+ static WithCancel(task, signal) {
295
+ if (!signal)
296
+ return task;
297
+ const reason = () => signal.reason ?? new DOMException("image load cancelled", "AbortError");
298
+ if (signal.aborted)
299
+ return Promise.reject(reason());
60
300
  return new Promise((resolve, reject) => {
61
- const item = { source, priority, signal, resolve, reject };
62
- const same = this.waiting.get(source);
301
+ const abort = () => reject(reason());
302
+ signal.addEventListener("abort", abort, { once: true });
303
+ task.then((v) => { signal.removeEventListener("abort", abort); resolve(v); }, (e) => { signal.removeEventListener("abort", abort); reject(e); });
304
+ });
305
+ }
306
+ Enqueue(key, source, priority, signal, cache) {
307
+ return new Promise((resolve) => {
308
+ const item = { key, source, priority, signal, resolve: cache ? (image) => resolve(image && this.Cached(key, image)) : resolve };
309
+ const same = cache ? this.waiting.get(key) : undefined;
63
310
  if (same) {
64
311
  same.push(item);
65
312
  return;
66
313
  } // already queued: one fetch serves every requester
67
- this.waiting.set(source, [item]);
314
+ if (cache)
315
+ this.waiting.set(key, [item]);
68
316
  const rank = PRIORITY_RANK[priority];
69
317
  let at = this.queue.length;
70
318
  while (at > 0 && PRIORITY_RANK[this.queue[at - 1].priority] > rank)
@@ -73,50 +321,57 @@ export class SkiaImageManager {
73
321
  this.Pump();
74
322
  });
75
323
  }
324
+ /** A fresh image goes into the cache; the cached one (an equal source loaded meanwhile) wins. */
325
+ Cached(key, image) {
326
+ if (this.AddToCache(key, image))
327
+ return image;
328
+ const existing = this.GetFromCacheInternal(key);
329
+ if (existing && existing !== image) {
330
+ this.Forget(this.Track(image, key));
331
+ return existing;
332
+ }
333
+ return image;
334
+ }
76
335
  Pump() {
77
336
  while (this.running < SkiaImageManager.MaxParallelLoads && this.queue.length > 0) {
78
337
  const item = this.queue.shift();
79
- const requesters = this.waiting.get(item.source) ?? [item];
80
- this.waiting.delete(item.source);
338
+ const requesters = this.waiting.get(item.key) ?? [item];
339
+ if (this.waiting.get(item.key)?.includes(item))
340
+ this.waiting.delete(item.key);
81
341
  if (item.signal?.aborted) {
82
342
  for (const r of requesters)
83
- r.reject(new Error("DrawnUi: image load cancelled"));
343
+ r.resolve(undefined);
84
344
  continue;
85
345
  }
86
346
  this.running++;
87
- const task = this.LoadImageAsync(item.source, item.signal);
88
- task.then((image) => { for (const r of requesters)
89
- r.resolve(image); }, (error) => { this.CanReload?.(item.source, error); for (const r of requesters)
90
- r.reject(error); }).finally(() => { this.running--; this.Pump(); });
347
+ void this.Fetch(item.source, item.signal).then(({ Image: image }) => {
348
+ if (image)
349
+ this.Track(image, item.key);
350
+ // the first requester caches it; the others get what is cached
351
+ for (const r of requesters)
352
+ r.resolve(image);
353
+ }).finally(() => { this.running--; this.Pump(); });
91
354
  }
92
355
  }
93
356
  /** C# PreloadImage: warms the cache for one source; failures are ignored. */
94
357
  async PreloadImage(source, priority = "Normal") {
95
- await this.LoadImageManagedAsync(source, undefined, priority).catch(() => undefined);
358
+ const image = await this.LoadImageManagedAsync(source, undefined, priority);
359
+ // a copy of its own (ReuseBitmaps off, or no cache) nobody will draw
360
+ if (image && this.owned.get(image)?.Cached !== true)
361
+ this.Forget(this.owned.get(image));
96
362
  }
97
363
  /** Warms the cache so first paint of these images is instant (DrawnUi PreloadImages). Failures are ignored. */
98
364
  async PreloadImages(sources, priority = "Normal") {
99
365
  await Promise.all(sources.map((s) => this.PreloadImage(s, priority)));
100
366
  }
101
- /** Drops everything still waiting in the queue (C# CancelAll); loads already in flight finish. */
367
+ /** Drops everything still waiting in the queue (C# CancelAll): those loads resolve to nothing; loads in flight finish. */
102
368
  CancelAll() {
103
369
  const items = this.queue.splice(0);
104
370
  for (const item of items) {
105
- const requesters = this.waiting.get(item.source) ?? [item];
106
- this.waiting.delete(item.source);
371
+ const requesters = this.waiting.get(item.key) ?? [item];
372
+ this.waiting.delete(item.key);
107
373
  for (const r of requesters)
108
- r.reject(new Error("DrawnUi: image load cancelled"));
109
- }
110
- }
111
- /** Drops a cached image (or everything) — decoded images hold GPU/WASM memory. */
112
- Clear(source) {
113
- if (source) {
114
- this.cache.get(source)?.delete();
115
- this.cache.delete(source);
116
- return;
374
+ r.resolve(undefined);
117
375
  }
118
- for (const img of this.cache.values())
119
- img.delete();
120
- this.cache.clear();
121
376
  }
122
377
  }
@@ -82,9 +82,15 @@ export class SkiaStyles {
82
82
  const target = control;
83
83
  if (atConstruction)
84
84
  SkiaStyles.SnapshotDefaults(type, control, keys);
85
+ else if (!SkiaStyles.defaults.has(type)) {
86
+ // a control built in code before any of its class went through the reconciler: the class defaults come from a
87
+ // fresh instance (once per class), so what the code already set still wins
88
+ const fresh = new type();
89
+ SkiaStyles.SnapshotDefaults(type, fresh, keys);
90
+ fresh.Dispose();
91
+ }
85
92
  const defaults = atConstruction ? undefined : SkiaStyles.defaults.get(type);
86
93
  for (const key of keys) {
87
- // no snapshot for this class (nothing of it ever went through the reconciler): apply as a plain default
88
94
  if (!defaults || Object.is(target[key], defaults[key]))
89
95
  target[key] = resolved.Setters[key];
90
96
  }
@@ -70,6 +70,10 @@ export declare class Super {
70
70
  /** Any shaping family (the bidirectional pass needs one, its font does not matter). */
71
71
  static AnyShapingFamily(): string | undefined;
72
72
  static UseDrawnUi(): DrawnUiBuilder;
73
+ /** C# Super.SetClipboardText: puts text on the clipboard (selection copies go through it; replace it to observe or redirect them). */
74
+ static SetClipboardText: (text: string) => void;
75
+ /** C# Super.OpenLink: opens an address in a new browser tab (noopener: the opened page gets no handle on this one). */
76
+ static OpenLink(url: string): void;
73
77
  /** Master switch: false makes every control render uncached (DrawnUi Super.CacheEnabled). */
74
78
  static CacheEnabled: boolean;
75
79
  /**
@@ -51,15 +51,6 @@ export class DrawnUiBuilder {
51
51
  if (!face)
52
52
  throw new Error(`DrawnUi: cannot load font '${f.Source}'`);
53
53
  loaded.set(f.Source, face);
54
- // the same face as a CSS font under the alias: the accessibility overlay's selectable text lines up with the drawn glyphs
55
- if (typeof FontFace !== "undefined" && typeof document !== "undefined") {
56
- try {
57
- const css = new FontFace(f.Alias, data, { weight: String(f.Weight) });
58
- await css.load();
59
- document.fonts.add(css);
60
- }
61
- catch { /* selection text falls back to a system font */ }
62
- }
63
54
  }
64
55
  let weights = Super.Fonts.get(f.Alias);
65
56
  if (!weights) {
@@ -152,6 +143,10 @@ export class Super {
152
143
  static AnyShapingFamily() { for (const f of Super.shapingFamilyOfFace.values())
153
144
  return f; return undefined; }
154
145
  static UseDrawnUi() { return new DrawnUiBuilder(); }
146
+ /** C# Super.SetClipboardText: puts text on the clipboard (selection copies go through it; replace it to observe or redirect them). */
147
+ static SetClipboardText = (text) => { void navigator.clipboard?.writeText(text).catch(() => { }); };
148
+ /** C# Super.OpenLink: opens an address in a new browser tab (noopener: the opened page gets no handle on this one). */
149
+ static OpenLink(url) { window.open(url, "_blank", "noopener"); }
155
150
  /** Master switch: false makes every control render uncached (DrawnUi Super.CacheEnabled). */
156
151
  static CacheEnabled = true;
157
152
  /**