drawnui-react 0.1.0-preview.8 → 1.0.1

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 (117) hide show
  1. package/README.md +229 -22
  2. package/SKIPPED.md +38 -29
  3. package/dist/controls/AnimatedFramesRenderer.d.ts +9 -0
  4. package/dist/controls/AnimatedFramesRenderer.js +18 -1
  5. package/dist/controls/DrawnGame.d.ts +44 -0
  6. package/dist/controls/DrawnGame.js +82 -0
  7. package/dist/controls/GridStructure.d.ts +25 -3
  8. package/dist/controls/GridStructure.js +81 -5
  9. package/dist/controls/SkiaBackdrop.d.ts +8 -2
  10. package/dist/controls/SkiaBackdrop.js +42 -14
  11. package/dist/controls/SkiaButton.d.ts +17 -3
  12. package/dist/controls/SkiaButton.js +26 -8
  13. package/dist/controls/SkiaCarousel.d.ts +22 -3
  14. package/dist/controls/SkiaCarousel.js +85 -9
  15. package/dist/controls/SkiaCheckbox.d.ts +0 -1
  16. package/dist/controls/SkiaCheckbox.js +2 -7
  17. package/dist/controls/SkiaDrawer.d.ts +15 -0
  18. package/dist/controls/SkiaDrawer.js +42 -7
  19. package/dist/controls/SkiaEditor.d.ts +51 -2
  20. package/dist/controls/SkiaEditor.js +292 -58
  21. package/dist/controls/SkiaGif.d.ts +7 -0
  22. package/dist/controls/SkiaGif.js +25 -4
  23. package/dist/controls/SkiaImage.d.ts +10 -0
  24. package/dist/controls/SkiaImage.js +80 -19
  25. package/dist/controls/SkiaLabel.d.ts +200 -11
  26. package/dist/controls/SkiaLabel.js +925 -93
  27. package/dist/controls/SkiaLabelFps.d.ts +12 -0
  28. package/dist/controls/SkiaLabelFps.js +35 -0
  29. package/dist/controls/SkiaLayout.d.ts +89 -9
  30. package/dist/controls/SkiaLayout.js +397 -23
  31. package/dist/controls/SkiaLottie.js +5 -3
  32. package/dist/controls/SkiaProgress.d.ts +2 -1
  33. package/dist/controls/SkiaProgress.js +8 -5
  34. package/dist/controls/SkiaRadioButton.d.ts +2 -0
  35. package/dist/controls/SkiaRadioButton.js +16 -4
  36. package/dist/controls/SkiaRichLabel.d.ts +1 -1
  37. package/dist/controls/SkiaRichLabel.js +11 -1
  38. package/dist/controls/SkiaScroll.d.ts +86 -7
  39. package/dist/controls/SkiaScroll.js +361 -40
  40. package/dist/controls/SkiaScrollBar.d.ts +27 -0
  41. package/dist/controls/SkiaScrollBar.js +51 -2
  42. package/dist/controls/SkiaShaderCarousel.d.ts +11 -1
  43. package/dist/controls/SkiaShaderCarousel.js +27 -5
  44. package/dist/controls/SkiaShape.d.ts +15 -2
  45. package/dist/controls/SkiaShape.js +57 -10
  46. package/dist/controls/SkiaShell.d.ts +282 -0
  47. package/dist/controls/SkiaShell.js +972 -0
  48. package/dist/controls/SkiaSlider.d.ts +20 -2
  49. package/dist/controls/SkiaSlider.js +61 -7
  50. package/dist/controls/SkiaSprite.d.ts +4 -0
  51. package/dist/controls/SkiaSprite.js +27 -11
  52. package/dist/controls/SkiaSvg.d.ts +4 -0
  53. package/dist/controls/SkiaSvg.js +28 -4
  54. package/dist/controls/SkiaSwitch.d.ts +0 -1
  55. package/dist/controls/SkiaSwitch.js +4 -8
  56. package/dist/controls/SkiaToggle.d.ts +25 -5
  57. package/dist/controls/SkiaToggle.js +58 -5
  58. package/dist/controls/SnappingLayout.d.ts +12 -1
  59. package/dist/controls/SnappingLayout.js +21 -2
  60. package/dist/controls/TooltipStyle.d.ts +52 -0
  61. package/dist/controls/TooltipStyle.js +88 -0
  62. package/dist/core/Accessibility.d.ts +162 -11
  63. package/dist/core/Accessibility.js +882 -22
  64. package/dist/core/Animators.d.ts +37 -1
  65. package/dist/core/Animators.js +102 -9
  66. package/dist/core/Canvas.d.ts +307 -8
  67. package/dist/core/Canvas.js +1202 -66
  68. package/dist/core/ControlStyle.d.ts +2 -0
  69. package/dist/core/ControlStyle.js +2 -0
  70. package/dist/core/DesignerActions.d.ts +32 -0
  71. package/dist/core/DesignerActions.js +68 -0
  72. package/dist/core/Easing.d.ts +12 -1
  73. package/dist/core/Easing.js +25 -1
  74. package/dist/core/Gestures.d.ts +86 -2
  75. package/dist/core/Gestures.js +184 -4
  76. package/dist/core/Hover.d.ts +51 -0
  77. package/dist/core/Hover.js +140 -0
  78. package/dist/core/ImageEffects.d.ts +2 -0
  79. package/dist/core/ImageEffects.js +2 -0
  80. package/dist/core/KeyboardManager.d.ts +40 -0
  81. package/dist/core/KeyboardManager.js +98 -8
  82. package/dist/core/PopupWindows.d.ts +94 -0
  83. package/dist/core/PopupWindows.js +207 -0
  84. package/dist/core/Props.d.ts +11 -0
  85. package/dist/core/Props.js +44 -0
  86. package/dist/core/ScrollAnimators.d.ts +6 -0
  87. package/dist/core/ScrollAnimators.js +16 -1
  88. package/dist/core/Shaping.d.ts +40 -0
  89. package/dist/core/Shaping.js +224 -0
  90. package/dist/core/SkiaControl.d.ts +306 -13
  91. package/dist/core/SkiaControl.js +681 -75
  92. package/dist/core/SkiaEffect.d.ts +29 -1
  93. package/dist/core/SkiaEffect.js +78 -16
  94. package/dist/core/SkiaImageManager.d.ts +101 -18
  95. package/dist/core/SkiaImageManager.js +318 -63
  96. package/dist/core/Styles.js +7 -1
  97. package/dist/core/Super.d.ts +33 -2
  98. package/dist/core/Super.js +58 -12
  99. package/dist/core/TextInputProxy.d.ts +31 -1
  100. package/dist/core/TextInputProxy.js +97 -15
  101. package/dist/core/Tooltips.d.ts +71 -0
  102. package/dist/core/Tooltips.js +205 -0
  103. package/dist/core/Types.d.ts +11 -1
  104. package/dist/core/Types.js +32 -1
  105. package/dist/core/ViewsAdapter.d.ts +7 -2
  106. package/dist/core/ViewsAdapter.js +10 -3
  107. package/dist/index.d.ts +8 -0
  108. package/dist/index.js +8 -0
  109. package/dist/react/SkiaShell.d.ts +8 -74
  110. package/dist/react/SkiaShell.js +163 -475
  111. package/dist/react/index.d.ts +48 -4
  112. package/dist/react/index.js +210 -43
  113. package/dist/react/reconciler.d.ts +32 -0
  114. package/dist/react/reconciler.js +71 -40
  115. package/dist/vite/index.d.ts +9 -0
  116. package/dist/vite/index.js +36 -3
  117. package/package.json +103 -5
@@ -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(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
  }
@@ -1,6 +1,6 @@
1
1
  import { Thickness } from "./Types";
2
2
  import { StylesCollection } from "./Styles";
3
- import type { CanvasKit, Font, Typeface } from "canvaskit-wasm";
3
+ import type { CanvasKit, Font, Typeface, TypefaceFontProvider } from "canvaskit-wasm";
4
4
  /** Mirrors DrawnUi.Net IFontCollection: fonts.AddFont(source, alias[, weight]), plus the Blazor-head AddSymbols/AddEmojis. */
5
5
  export declare class FontCollection {
6
6
  /** Where the shipped subset fonts are served from (the demo copies them to public/fonts). */
@@ -12,7 +12,7 @@ export declare class FontCollection {
12
12
  }[];
13
13
  /** Noto Sans Math + Symbols 2 subsets as "FontSymbols" / "FontSymbols2" (arrows, math, misc symbols) — DrawnUi.Blazor AddSymbols. */
14
14
  AddSymbols(): FontCollection;
15
- /** Noto Color Emoji subset (faces + hands) as "FontEmoji" — DrawnUi.Blazor AddEmojis. */
15
+ /** Noto Color Emoji subset (faces, hands, skin tones and a few objects) as "FontEmoji" — DrawnUi.Blazor AddEmojis. */
16
16
  AddEmojis(): FontCollection;
17
17
  /** Registers a face under an alias; weight 100..900 lets FontWeight / FontAttributes=Bold pick the right file. */
18
18
  AddFont(source: string, alias: string, weight?: number): FontCollection;
@@ -46,12 +46,43 @@ export declare class Super {
46
46
  static readonly Fonts: Map<string, Map<number, Typeface>>;
47
47
  /** First registered font, or CanvasKit's built-in one. */
48
48
  static DefaultTypeface?: Typeface;
49
+ /**
50
+ * App-wide opt-in (drawnui-cross 6ar): a control without a `Tooltip` shows its `AccessibilityHint` as tooltip, else its
51
+ * `AccessibilityLabel` when it shows no text of its own, so icon buttons get their screen-reader name as tooltip.
52
+ */
53
+ static TooltipsFromAccessibility: boolean;
54
+ /** Look and timing of the tooltips (a `TooltipStyle`), for every canvas without its own. Read when a tooltip is built. */
55
+ static TooltipStyle?: import("./Tooltips").TooltipStyleLike;
49
56
  /** CanvasKit's built-in face: what an empty FontFamily resolves to, like C# SKTypeface.CreateDefault(). */
50
57
  static SkiaDefaultTypeface?: Typeface;
51
58
  private static readonly fontCache;
59
+ /** Every face loaded from data, each under a family of its own: the paragraph module shapes text with them (`Shaping`). */
60
+ static ShapingFonts?: TypefaceFontProvider;
61
+ private static readonly shapingFamilyOfFace;
62
+ private static readonly shapingFamilyOfFont;
63
+ /**
64
+ * A face from font file data, also usable for shaping (complex scripts, emoji sequences, right to left). Register fonts
65
+ * by alias with `Super.Fonts` / ConfigureFonts; this only makes the face. Undefined when the data is no font.
66
+ */
67
+ static LoadFace(data: ArrayBuffer | Uint8Array): Typeface | undefined;
68
+ /** The shaping family of a font made by GetFont, undefined for faces without shaping data (CanvasKit's built-in face). */
69
+ static ShapingFamilyOf(font: Font): string | undefined;
70
+ /** Any shaping family (the bidirectional pass needs one, its font does not matter). */
71
+ static AnyShapingFamily(): string | undefined;
52
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;
53
77
  /** Master switch: false makes every control render uncached (DrawnUi Super.CacheEnabled). */
54
78
  static CacheEnabled: boolean;
79
+ /**
80
+ * Address every engine loader fetches a source from (images, sprites, fonts, SVG, GIF, Lottie, shaders); caches
81
+ * stay keyed by the source itself. Web-only, no C# counterpart. Default: a file listed in
82
+ * `globalThis.DrawnUiAssetStamps` (written into index.html by the `drawnUiAssetStamps()` Vite plugin) gets
83
+ * `?v=<content hash>`, so a browser never keeps an old copy of a changed file. Replace it to map sources elsewhere.
84
+ */
85
+ static ResolveAssetUrl: (source: string) => string;
55
86
  private static readonly colorCache;
56
87
  /**
57
88
  * Color string -> CanvasKit color. Hex follows the MAUI/DrawnUi convention: #RGB, #ARGB, #RRGGBB, #AARRGGBB
@@ -13,7 +13,7 @@ export class FontCollection {
13
13
  return this.AddFont(FontCollection.ContentRoot + "NotoSansMathSymbols-Subset.ttf", "FontSymbols")
14
14
  .AddFont(FontCollection.ContentRoot + "NotoSansSymbols2-Subset.ttf", "FontSymbols2");
15
15
  }
16
- /** Noto Color Emoji subset (faces + hands) as "FontEmoji" — DrawnUi.Blazor AddEmojis. */
16
+ /** Noto Color Emoji subset (faces, hands, skin tones and a few objects) as "FontEmoji" — DrawnUi.Blazor AddEmojis. */
17
17
  AddEmojis() {
18
18
  return this.AddFont(FontCollection.ContentRoot + "NotoColorEmoji-Subset.ttf", "FontEmoji");
19
19
  }
@@ -46,20 +46,11 @@ export class DrawnUiBuilder {
46
46
  for (const f of this.fonts.Fonts) {
47
47
  let face = loaded.get(f.Source);
48
48
  if (!face) {
49
- const data = await (await fetch(f.Source)).arrayBuffer();
50
- face = Super.CK.Typeface.MakeFreeTypeFaceFromData(data) ?? undefined;
49
+ const data = await (await fetch(Super.ResolveAssetUrl(f.Source))).arrayBuffer();
50
+ face = Super.LoadFace(data);
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) {
@@ -116,12 +107,62 @@ export class Super {
116
107
  static Fonts = new Map();
117
108
  /** First registered font, or CanvasKit's built-in one. */
118
109
  static DefaultTypeface;
110
+ /**
111
+ * App-wide opt-in (drawnui-cross 6ar): a control without a `Tooltip` shows its `AccessibilityHint` as tooltip, else its
112
+ * `AccessibilityLabel` when it shows no text of its own, so icon buttons get their screen-reader name as tooltip.
113
+ */
114
+ static TooltipsFromAccessibility = false;
115
+ /** Look and timing of the tooltips (a `TooltipStyle`), for every canvas without its own. Read when a tooltip is built. */
116
+ static TooltipStyle;
119
117
  /** CanvasKit's built-in face: what an empty FontFamily resolves to, like C# SKTypeface.CreateDefault(). */
120
118
  static SkiaDefaultTypeface;
121
119
  static fontCache = new Map();
120
+ /** Every face loaded from data, each under a family of its own: the paragraph module shapes text with them (`Shaping`). */
121
+ static ShapingFonts;
122
+ static shapingFamilyOfFace = new Map();
123
+ static shapingFamilyOfFont = new WeakMap();
124
+ /**
125
+ * A face from font file data, also usable for shaping (complex scripts, emoji sequences, right to left). Register fonts
126
+ * by alias with `Super.Fonts` / ConfigureFonts; this only makes the face. Undefined when the data is no font.
127
+ */
128
+ static LoadFace(data) {
129
+ const CK = Super.CK;
130
+ Super.ShapingFonts ??= CK.TypefaceFontProvider.Make();
131
+ const family = `drawnui-shaping-${Super.shapingFamilyOfFace.size}`;
132
+ Super.ShapingFonts.registerFont(data, family);
133
+ const face = Super.ShapingFonts.matchFamilyStyle(family, { weight: CK.FontWeight.Normal, width: CK.FontWidth.Normal, slant: CK.FontSlant.Upright });
134
+ if (face) {
135
+ Super.shapingFamilyOfFace.set(face, family);
136
+ return face;
137
+ }
138
+ return CK.Typeface.MakeFreeTypeFaceFromData(data instanceof Uint8Array ? data.slice().buffer : data) ?? undefined;
139
+ }
140
+ /** The shaping family of a font made by GetFont, undefined for faces without shaping data (CanvasKit's built-in face). */
141
+ static ShapingFamilyOf(font) { return Super.shapingFamilyOfFont.get(font); }
142
+ /** Any shaping family (the bidirectional pass needs one, its font does not matter). */
143
+ static AnyShapingFamily() { for (const f of Super.shapingFamilyOfFace.values())
144
+ return f; return undefined; }
122
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"); }
123
150
  /** Master switch: false makes every control render uncached (DrawnUi Super.CacheEnabled). */
124
151
  static CacheEnabled = true;
152
+ /**
153
+ * Address every engine loader fetches a source from (images, sprites, fonts, SVG, GIF, Lottie, shaders); caches
154
+ * stay keyed by the source itself. Web-only, no C# counterpart. Default: a file listed in
155
+ * `globalThis.DrawnUiAssetStamps` (written into index.html by the `drawnUiAssetStamps()` Vite plugin) gets
156
+ * `?v=<content hash>`, so a browser never keeps an old copy of a changed file. Replace it to map sources elsewhere.
157
+ */
158
+ static ResolveAssetUrl = (source) => {
159
+ const stamps = globalThis.DrawnUiAssetStamps;
160
+ if (!stamps)
161
+ return source;
162
+ const q = source.indexOf("?");
163
+ const v = stamps[(q < 0 ? source : source.slice(0, q)).replace(/^\.?\//, "")];
164
+ return v ? `${source}${q < 0 ? "?" : "&"}v=${v}` : source;
165
+ };
125
166
  static colorCache = new Map();
126
167
  /**
127
168
  * Color string -> CanvasKit color. Hex follows the MAUI/DrawnUi convention: #RGB, #ARGB, #RRGGBB, #AARRGGBB
@@ -183,11 +224,16 @@ export class Super {
183
224
  const resolved = Super.ResolveTypeface(alias, weight);
184
225
  font = new Super.CK.Font(resolved.Typeface, sizePx);
185
226
  font.setSubpixel(true);
227
+ // unhinted advances: the same text widths on every platform and engine (drawnui-cross 6f, DrawnUi.Rust fonts.rs)
228
+ font.setLinearMetrics(true);
186
229
  if (italic)
187
230
  font.setSkewX(-0.25);
188
231
  // no bold face registered: synthetic bold, like C# Font.Embolden = IsBold
189
232
  if (weight >= 600 && resolved.Weight < 600)
190
233
  font.setEmbolden(true);
234
+ const family = resolved.Typeface ? Super.shapingFamilyOfFace.get(resolved.Typeface) : undefined;
235
+ if (family)
236
+ Super.shapingFamilyOfFont.set(font, family);
191
237
  Super.fontCache.set(key, font);
192
238
  }
193
239
  return font;