drawnui-react 0.1.0-preview.26 → 0.1.0-preview.28

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.
package/SKIPPED.md CHANGED
@@ -24,7 +24,7 @@ DrawnUi name and semantics; nothing here is a redesign, only an omission.
24
24
  | `IsClippedToBounds`, `ClipEffects` | ported | Clip to `DrawingRect` around content, children and post-animators; `ClipEffects=false` grows the clip by the aggregated effects margin so a child's shadow/glow can escape. Layouts aggregate their children's effects margins (C# `AggregatedEffectsMarginPixels`), cached per control and reset by `InvalidateMeasure`. Not ported: `Clipping` callback, `ClipWith`, `ClipFrom`, platform clips; C# currently ignores `ClipEffects` in its render path (always expands). |
25
25
  | `Padding` on base `SkiaControl` | skipped | Only `SkiaLayout.Padding` exists. |
26
26
  | `SkiaRichLabel` (markdown) | ported | Own lightweight parser (C# uses CommonMark.NET): `#`–`###+` headings (+9/+4/+2 pt, bold, `HeadingTextColor`), paragraphs (soft breaks kept as "
27
- "), bullet / numbered lists (`PrefixBullet`, `PrefixNumbered`), fenced code blocks (`CodeTextColor`, `CodeBlockBackgroundColor` as span background — C# paints it as `ParagraphColor` full-width), inline code, `**bold**`/`__bold__`, `*italic*`/`_italic_`, `~~strike~~` (`StrikeoutColor`), `[text](url)` (`LinkColor`, `UnderlineLink`, `UnderlineWidth`, `LinkTapped`, `OnLinkTapped`), backslash escapes, `MarkdownEnabled=false` = literal. Not ported, with the path to do it later (all inside `SkiaRichLabel.ts` / `SkiaLabel.ts`, no architecture change): **block quotes, nested lists, setext headings** = parser only (indent levels, `>` prefix, spans with prefix/left margin); **tables** = parser + render as a generated `SkiaGrid` of labels (a label cannot do columns; same limit as C#); **images `![alt](src)`** = a span kind that reserves a box and draws a `SkiaImage`, the run layout already carries per-run widths (C# has no images either); **inline HTML** = out, C# neither; **`CommandLinkTapped`** = MAUI ICommand, `LinkTapped` is the React shape, nothing to port; **per-run typeface detection (`BuildSpanData`)** = run segmentation already exists (`FontFamilyFallback` chain per codepoint), only the automatic system-font `MatchCharacter` is impossible in CanvasKit — fallbacks stay explicit; **code-block full-width background** = add `ParagraphColor` to `TextSpan` and paint a line-wide rect in `SkiaLabel.Paint`; **parser edge cases** = swap `RenderDocument` for `markdown-it`/`micromark` on demand, spans unchanged. |
27
+ "), bullet / numbered lists (`PrefixBullet`, `PrefixNumbered`), fenced code blocks (`CodeTextColor`, `CodeBlockBackgroundColor` as span background — C# paints it as `ParagraphColor` full-width), inline code, `***bold italic***`/`___bold italic___`, `**bold**`/`__bold__`, `*italic*`/`_italic_`, `~~strike~~` (`StrikeoutColor`), `[text](url)` (`LinkColor`, `UnderlineLink`, `UnderlineWidth`, `LinkTapped`, `OnLinkTapped`), backslash escapes, `MarkdownEnabled=false` = literal. Not ported, with the path to do it later (all inside `SkiaRichLabel.ts` / `SkiaLabel.ts`, no architecture change): **block quotes, nested lists, setext headings** = parser only (indent levels, `>` prefix, spans with prefix/left margin); **tables** = parser + render as a generated `SkiaGrid` of labels (a label cannot do columns; same limit as C#); **images `![alt](src)`** = a span kind that reserves a box and draws a `SkiaImage`, the run layout already carries per-run widths (C# has no images either); **inline HTML** = out, C# neither; **`CommandLinkTapped`** = MAUI ICommand, `LinkTapped` is the React shape, nothing to port; **per-run typeface detection (`BuildSpanData`)** = run segmentation already exists (`FontFamilyFallback` chain per codepoint), only the automatic system-font `MatchCharacter` is impossible in CanvasKit — fallbacks stay explicit; **code-block full-width background** = add `ParagraphColor` to `TextSpan` and paint a line-wide rect in `SkiaLabel.Paint`; **parser edge cases** = swap `RenderDocument` for `markdown-it`/`micromark` on demand, spans unchanged. |
28
28
  | `MinimumWidthRequest`/`MaximumWidthRequest` (+Height) | ported | Same semantics as C#: `-1` = unset; `WidthRequest` wins over `MaximumWidthRequest`; the maximum caps both the measured size and the arranged Fill box, alignment still uses the parent's full box (a centered `Fill` child with `MaximumWidthRequest` stays centered). |
29
29
  | `LockRatio` | ported | Same as C#: a single set `WidthRequest`/`HeightRequest` drives both sides (`CalculateSizeRequest`), otherwise the constraints are locked with `SmartMax`/`SmartMin` × \|ratio\| (sign decides larger/smaller side, infinite side loses). |
30
30
  | `HorizontalFillRatio`/`VerticalFillRatio` | ported | Applied at arrange like C# `DefineAvailableSize` (the Fill box is scaled, alignment stays inside the full box); measure is not affected (C# passes `useModifiers=false` there too). |
@@ -72,7 +72,7 @@ DrawnUi name and semantics; nothing here is a redesign, only an omission.
72
72
  | `SkiaLayout` Wrap (static children) + `SkiaWrap` alias | ported | Left-to-right flow, `Spacing` between items and rows, row height = tallest item. Not ported: `Split`, main-axis `Fill` children sharing a row (1.9.7.4 flex-fill), `UseDynamicColumns`, RTL. |
73
73
  | `SkiaLayout` Masonry + `SkiaMasonry` alias (Split 2, horizontal fill) | ported | C# `MeasureMasonry` / `BuildMasonryLayout`: `Split` columns of width round((width - (Split - 1) * Spacing) / Split), every visible item measured unbounded at that width and placed at the bottom of the shortest column (the first on a tie), `Spacing` between columns and items. Children or `ItemsSource` + `ItemTemplate` (recycled slots, taps, `ScrollToIndex` from the slot rect, `LoadMore`); a templated slot keeps its item's size, so an appended page or a changed item is the only one measured and every item is placed again. No items window. Content = used columns wide, tallest column high. `npm run check:masonry` (C# MasonryLayoutTests) |
74
74
  | `SkiaLayout` Grid (static children) + `SkiaGrid` alias | ported | Port of `SkiaGridStructure` (MAUI grid manager): `ColumnDefinitions`/`RowDefinitions` as `"*, 2*, Auto, 100"` or arrays, `DefaultColumnDefinition`/`DefaultRowDefinition` (Auto, like C#), `ColumnSpacing`/`RowSpacing`, child `Column`/`Row`/`ColumnSpan`/`RowSpan` (plain props instead of attached properties), implicit tracks, unknown/known measure passes, span resolution, star compression, Fill-child minimums, last-track stretch when the grid fills, remeasure at final cells. Not ported: `Split`/`Invert` (templated grids), `UseDynamicColumns`, `SkiaDecoratedGrid`, `GetOrderedSubviews` ZIndex ordering. |
75
- | `SkiaLabel` | partial | Word wrap (+ character break for long words), `MaxLines` with tail ellipsis, `LineBreakMode` (NoWrap / wraps / Tail; Head/Middle behave as Tail), `HorizontalTextAlignment` Start/Center/End (Fill* accepted, align Start), `VerticalTextAlignment`, `LineSpacing`, `LineHeight`, `FontWeight` + `FontAttributes` via faces registered per weight (`AddFont(src, alias, weight)`, nearest weight wins, synthetic bold (`setEmbolden`) when the nearest face is lighter than 600 — C# `Font.Embolden`; italic = synthetic skew when no italic face; empty `FontFamily` = the first registered family, weights included), `TextTransform`, `Padding`, `LinesCount`; defaults as C# (`FontSize` 12, `TextColor` GreenYellow). `FontFamilyFallback` ported and extended: comma-separated chain (`"FontSymbols,FontSymbols2"`), per-codepoint run segmentation, spaces always stay on the main font; `fonts.AddSymbols()` (`FontSymbols` = Noto Sans Math subset, `FontSymbols2` = Noto Sans Symbols 2 subset) and `fonts.AddEmojis()` (`FontEmoji` = Noto Color Emoji faces+hands subset) ship the same subsets as DrawnUi.Blazor. `Spans` ported as `<TextSpan>` children: `Text`, `TextColor`/`FontSize`/`FontFamily` (unset = inherit from the label, like C# HasSetColor/HasSetSize/HasSetFont), `FontWeight`, `IsBold`, `IsItalic`, `Underline`/`UnderlineWidth`, `Strikeout`/`StrikeoutWidth`/`StrikeoutColor` (Red default), `BackgroundColor`, `Tapped` + `ForceCaptureInput` (hit-tested through per-fragment `Rects`, ripple on the label, `OnSpanTapped` overridable), mixed sizes on one line share a baseline. TextSpan not ported: `ParagraphColor`, `CommandTapped`, per-span `LineSpacing`/`LineHeight`, `AutoFindFont`, `DrawingOffset`, `Shape`/glyph shaping. `CharacterSpacing` (C#: (value - 1) points after every glyph, measured, wrapped and cut at the drawn width), Chinese / Japanese line breaks between characters with kinsoku (C# FitAtBreak, `CanBreakInsideWord`). Not ported: `AutoFont`, `AutoSize`/`AutoSizeText`, `DropShadow*`, text `StrokeColor`/`StrokeWidth`/`StrokeGradient`, `GradientByLines`, `MonoForDigits`, `KeepSpacesOnLineBreaks`, `Format`, RTL/bidi, hyphenation, `SkiaRichLabel`/markdown. |
75
+ | `SkiaLabel` | partial | Word wrap (+ character break for long words), `MaxLines` with tail ellipsis, `LineBreakMode` (NoWrap / wraps / Tail; Head/Middle behave as Tail), `HorizontalTextAlignment` Start/Center/End (Fill* accepted, align Start), `VerticalTextAlignment`, `LineSpacing`, `LineHeight`, `FontWeight` + `FontAttributes` via faces registered per weight (`AddFont(src, alias, weight)`, nearest weight wins, synthetic bold (`setEmbolden`) when the nearest face is lighter than 600 — C# `Font.Embolden`; italic = synthetic skew when no italic face; empty `FontFamily` = the first registered family, weights included), `TextTransform`, `Padding`, `LinesCount`; defaults as C# (`FontSize` 12, `TextColor` GreenYellow). `FontFamilyFallback` ported and extended: comma-separated chain (`"FontSymbols,FontSymbols2"`), per-codepoint run segmentation, spaces always stay on the main font; `fonts.AddSymbols()` (`FontSymbols` = Noto Sans Math subset, `FontSymbols2` = Noto Sans Symbols 2 subset) and `fonts.AddEmojis()` (`FontEmoji` = Noto Color Emoji subset: faces, hands, skin tones and the demo emoji) ship the same subsets as DrawnUi.Blazor. A joiner, variation selector, skin tone, keycap or tag keeps the font of the glyph before it (C# JoinsPreviousGlyph). Text shaping where the text needs it (C# `UnicodeNeedsShaping` ranges plus Hebrew, Arabic supplements and emoji sequence characters): Arabic joins, Indic conjuncts and marks, emoji sequences as one glyph, through the CanvasKit paragraph module already in the build (HarfBuzz + ICU, no extra wasm); other text keeps the plain glyph-by-glyph path. Right-to-left lines: runs cut where the bidirectional level changes (ICU levels; the paragraph direction from its first strong letter, explicit embeddings reported as their direction only) and placed in visual order (rule L2). A space keeps the style of the span it was written in; where two spans meet with a space each, both stay (C#). `Spans` ported as `<TextSpan>` children: `Text`, `TextColor`/`FontSize`/`FontFamily` (unset = inherit from the label, like C# HasSetColor/HasSetSize/HasSetFont), `FontWeight`, `IsBold`, `IsItalic`, `Underline`/`UnderlineWidth`, `Strikeout`/`StrikeoutWidth`/`StrikeoutColor` (Red default), `BackgroundColor`, `Tapped` + `ForceCaptureInput` (hit-tested through per-fragment `Rects`, ripple on the label, `OnSpanTapped` overridable), mixed sizes on one line share a baseline. TextSpan not ported: `ParagraphColor`, `CommandTapped`, per-span `LineSpacing`/`LineHeight`, `AutoFindFont`, `DrawingOffset`. `CharacterSpacing` (C#: (value - 1) points after every glyph, measured, wrapped and cut at the drawn width), Chinese / Japanese line breaks between characters with kinsoku (C# FitAtBreak, `CanBreakInsideWord`). Text `StrokeColor`/`StrokeWidth`/`StrokeGradient`, `DropShadow*` and `GradientByLines` ported (C# DrawText order). Not ported: `AutoFont`, `AutoSize`/`AutoSizeText`, `MonoForDigits`, `KeepSpacesOnLineBreaks` (accepted, no effect), `Format`, hyphenation, the editor caret placed visually in right-to-left text (boxes stay in logical order; DrawnUi.Rust has the same gap). |
76
76
  | `SkiaHotspot` | ported | Fill/Fill, `Tapped`, `Down`, `Up`, `LockPanning`, `TouchDown`; consumes only Tapped like the C# one. No `AnimationTapped`/ripple/shimmer. |
77
77
  | `SkiaButton` | partial | Default look only: rounded frame radius 8 (hardcoded like the C# default content), centered label, `Text`/`TextColor`/`FontSize`/`FontFamily`/`BackgroundColor`/`IsPressed`/`RespondsToGestures` (`IsDisabled` = its obsolete opposite)/`LockPanning`, `Tapped`/`Down`/`Up`. `RespondsToGestures = false`: no press, no `Tapped`/`Down`/`Up`, a press or tap on it stops there, keyboard skips it, reported disabled (drawnui-cross 6w). `IsPressed` is tracked but has no visual; press feedback = `ApplyEffect="Ripple"`. No `ButtonStyle` platform looks, icons, `TextCase`, elevation, shimmer, `BtnText`/`BtnShape` templating. |
78
78
  | `SkiaImage` | partial | Effects ported: `AddEffect` (BlackAndWhite/Grayscale, Pastel, Sepia, InvertColors, Tint + `ColorTint`/`EffectBlendMode`, Darken, Lighten, Contrast, Saturation, Brightness, TSL, Gamma ≈ linear fit — CanvasKit has no table color filter), `Blur` (image filter, mirror tile), `ZoomX/ZoomY`, `HorizontalOffset/VerticalOffset`; C# color matrices use 0..255 translations, CanvasKit 0..1 — converted. `HSL` (hue from `Gamma`, `Saturation`, `Brightness`, tint blend), `Custom` = your own `PaintColorFilter` (C# public fields `PaintColorFilter` / `PaintImageFilter`, the latter replaces `Blur`), `ImageBitmap` (decoded image shared, not owned), `LoadPriority` of the queued `Source` load. Not ported: `UseGradient`/`StartColor`/`EndColor`, sprites, `InflateAmount`, `EraseChangedContent`, `RescaleSource`/`RescalingQuality`. `Source` (URL), `Aspect` (all `TransformAspect` values; `Tile` is a no-op like C#, tiling is `SkiaImageTiles`, same `RescaleAspect` math), `HorizontalAlignment`/`VerticalAlignment`, `Success`/`Error`, `IsLoading`, `LoadedSource`, `DisplayRect`, `AspectScale`; overflow clipped to the box. Not ported: `LoadSourceOnFirstDraw`, `PreviewBase64`, `ImageBitmap`/`LoadedImageSource`, `RescaleSource`/`CacheRescaledSource`/`RescalingQuality`, all adjustments (`Brightness`…`Blur`, `ColorTint`, gradient, `Zoom*`, offsets), sprites, `DrawWhenEmpty`, `EraseChangedContent`, `UseAssembly`. Measure: bounded box taken as is, unbounded axis from source aspect; no `NeedAutoWidth/Height` from Start alignment. |
@@ -103,8 +103,19 @@ export declare class SkiaCarousel extends SnappingLayout {
103
103
  protected FindNearestAnchorInternal(current: SKPoint, velocity: SKPoint): SKPoint;
104
104
  /** C# SkiaCarousel.ScrollToNearestAnchor: velocity below SnapVelocityThreshold counts as none; looped snaps around virtual anchors. */
105
105
  ScrollToNearestAnchor(location: SKPoint, velocity: SKPoint): void;
106
- /** C# SkiaCarousel.SelectNextAnchor: base choice, plus a wrap to the virtual anchor at the strip borders when looped. */
106
+ /** C# SkiaCarousel.SelectNextAnchor: the choice below, at most one slide from where a finger gesture started. */
107
107
  SelectNextAnchor(origin: SKPoint, velocity: SKPoint): SKPoint;
108
+ /**
109
+ * A finger release moves at most one slide from the slide its gesture started on, as iOS paging and the Android
110
+ * ViewPager do (C# 1070e0db): a drag past the middle makes the next slide the nearest one, and the flick then went one
111
+ * further. Code moves (ScrollTo, SelectedIndex) are not limited: releaseHome is set only while a release snaps.
112
+ */
113
+ private LimitToNeighbours;
114
+ /** The slide a finger gesture started on (the target when it caught a snap in flight), see LimitToNeighbours. */
115
+ private gestureHome?;
116
+ private releaseHome?;
117
+ /** Base choice, plus a wrap to the virtual anchor at the strip borders when looped. */
118
+ private SelectNextAnchorInternal;
108
119
  /** C# FixIndex: a virtual anchor becomes the real one, the position keeps its offset (visually identical, looped drawing wraps). */
109
120
  private FixIndex;
110
121
  private FixPosition;
@@ -247,8 +247,30 @@ export class SkiaCarousel extends SnappingLayout {
247
247
  }
248
248
  super.ScrollToNearestAnchor(location, velocity);
249
249
  }
250
- /** C# SkiaCarousel.SelectNextAnchor: base choice, plus a wrap to the virtual anchor at the strip borders when looped. */
250
+ /** C# SkiaCarousel.SelectNextAnchor: the choice below, at most one slide from where a finger gesture started. */
251
251
  SelectNextAnchor(origin, velocity) {
252
+ return this.LimitToNeighbours(this.SelectNextAnchorInternal(origin, velocity));
253
+ }
254
+ /**
255
+ * A finger release moves at most one slide from the slide its gesture started on, as iOS paging and the Android
256
+ * ViewPager do (C# 1070e0db): a drag past the middle makes the next slide the nearest one, and the flick then went one
257
+ * further. Code moves (ScrollTo, SelectedIndex) are not limited: releaseHome is set only while a release snaps.
258
+ */
259
+ LimitToNeighbours(target) {
260
+ const home = this.releaseHome;
261
+ if (!home)
262
+ return target;
263
+ const at = (p) => this.SnapPoints.findIndex((s) => Math.abs(s.X - p.X) <= 1 && Math.abs(s.Y - p.Y) <= 1);
264
+ const from = at(home), to = at(target);
265
+ if (from < 0 || to < 0 || Math.abs(to - from) <= 1)
266
+ return target; // a looped wrap goes to a virtual point next to the edge: one slide already
267
+ return this.SnapPoints[from + Math.sign(to - from)];
268
+ }
269
+ /** The slide a finger gesture started on (the target when it caught a snap in flight), see LimitToNeighbours. */
270
+ gestureHome;
271
+ releaseHome;
272
+ /** Base choice, plus a wrap to the virtual anchor at the strip borders when looped. */
273
+ SelectNextAnchorInternal(origin, velocity) {
252
274
  if (!this.ApplyLoopedLogic)
253
275
  return super.SelectNextAnchor(origin, velocity);
254
276
  const baseTarget = super.SelectNextAnchor(origin, velocity);
@@ -551,6 +573,9 @@ export class SkiaCarousel extends SnappingLayout {
551
573
  this.FixPosition();
552
574
  this.panningOffset = this.CurrentPosition;
553
575
  this.panningStart = this.CurrentPosition;
576
+ // a swipe that catches a snap in flight starts from the slide that snap was going to
577
+ const going = this.snapIfNoPanOnUp ? this.SnapPoints.find((s) => Math.abs(s.X - this.CurrentSnap.X) <= 1 && Math.abs(s.Y - this.CurrentSnap.Y) <= 1) : undefined;
578
+ this.gestureHome = going ?? (this.SnapPoints.length > 0 ? this.FindNearestAnchor(this.CurrentPosition) : undefined);
554
579
  };
555
580
  switch (args.Type) {
556
581
  case "Down":
@@ -591,7 +616,13 @@ export class SkiaCarousel extends SnappingLayout {
591
616
  consumed = this;
592
617
  const final = this.velocityAccumulator.CalculateFinalVelocity(500);
593
618
  this.CurrentSnap = this.CurrentPosition;
594
- this.ScrollToNearestAnchor(this.CurrentSnap, new SKPoint(final.X, final.Y));
619
+ this.releaseHome = this.gestureHome;
620
+ try {
621
+ this.ScrollToNearestAnchor(this.CurrentSnap, new SKPoint(final.X, final.Y));
622
+ }
623
+ finally {
624
+ this.releaseHome = undefined;
625
+ }
595
626
  this.IsUserPanning = false;
596
627
  this.IsUserFocused = false;
597
628
  this.snapIfNoPanOnUp = false;
@@ -51,6 +51,8 @@ export declare class SkiaEditor extends SkiaShape {
51
51
  CanShowCursor: boolean;
52
52
  SelectionColor: Color;
53
53
  private cursorPosition;
54
+ /** A caret position was given (by the app, a tap, a selection): focusing keeps it; otherwise focusing puts the caret at the end. */
55
+ private cursorPlaced;
54
56
  private selectionLength;
55
57
  private isFocused;
56
58
  private controlStyle;
@@ -58,6 +58,8 @@ export class SkiaEditor extends SkiaShape {
58
58
  CanShowCursor = true;
59
59
  SelectionColor = "#5590CFFE";
60
60
  cursorPosition = 0;
61
+ /** A caret position was given (by the app, a tap, a selection): focusing keeps it; otherwise focusing puts the caret at the end. */
62
+ cursorPlaced = false;
61
63
  selectionLength = 0;
62
64
  isFocused = false;
63
65
  controlStyle = "Unset";
@@ -174,6 +176,7 @@ export class SkiaEditor extends SkiaShape {
174
176
  /** Caret index (UTF-16 units) = the left edge of the selection when one exists. */
175
177
  get CursorPosition() { return this.cursorPosition; }
176
178
  set CursorPosition(v) {
179
+ this.cursorPlaced = true;
177
180
  const p = Math.max(0, Math.min(this.text.length, v | 0));
178
181
  if (p === this.cursorPosition)
179
182
  return;
@@ -218,6 +221,14 @@ export class SkiaEditor extends SkiaShape {
218
221
  if (SkiaEditor.Focused && SkiaEditor.Focused !== this)
219
222
  SkiaEditor.Focused.IsFocused = false;
220
223
  SkiaEditor.Focused = this;
224
+ // focused with no caret placed (from code, by the keyboard): the caret goes to the end of the text, as a tap after
225
+ // the text does, and the native field takes that position when it attaches (C# 2285b422: typing appends)
226
+ if (!this.cursorPlaced) {
227
+ this.cursorPlaced = true;
228
+ this.cursorPosition = this.text.length;
229
+ this.selectionLength = 0;
230
+ this.ScrollToCaret();
231
+ }
221
232
  this.SetFocusNative(true);
222
233
  this.StartBlink();
223
234
  }
@@ -484,6 +495,7 @@ export class SkiaEditor extends SkiaShape {
484
495
  this.stubSelectionStop = -1;
485
496
  this.selectionMovingEdge = -1;
486
497
  }
498
+ this.cursorPlaced = true;
487
499
  if (!this.isFocused)
488
500
  this.IsFocused = true;
489
501
  this.OnCursorMoved();
@@ -505,6 +517,7 @@ export class SkiaEditor extends SkiaShape {
505
517
  this.SelectWord(this.HitTestIndex(p.X, p.Y));
506
518
  this.dragSelecting = true;
507
519
  this.selectionAnchor = this.cursorPosition;
520
+ this.cursorPlaced = true;
508
521
  if (!this.isFocused)
509
522
  this.IsFocused = true;
510
523
  return this;
@@ -541,6 +554,7 @@ export class SkiaEditor extends SkiaShape {
541
554
  }
542
555
  SelectAll() { this.SetSelection(0, this.text.length); }
543
556
  SetSelection(start, end) {
557
+ this.cursorPlaced = true;
544
558
  const s = Math.max(0, Math.min(this.text.length, Math.min(start, end))), e = Math.max(0, Math.min(this.text.length, Math.max(start, end)));
545
559
  this.cursorPosition = s;
546
560
  this.selectionLength = e - s;
@@ -119,6 +119,8 @@ export declare class SkiaLabel extends SkiaControl {
119
119
  /** The label's own style, and the base every span inherits from. */
120
120
  private ResolveMainFonts;
121
121
  private ResolveSpanFonts;
122
+ private static NeedsShapingOrRtl;
123
+ /** Width of a text in one font: the shaped glyphs where the text needs shaping (Arabic joins, emoji sequences), else glyph by glyph. */
122
124
  private Advance;
123
125
  private static readonly Ignorable;
124
126
  /**
@@ -129,7 +131,8 @@ export declare class SkiaLabel extends SkiaControl {
129
131
  private static DropIgnorables;
130
132
  /**
131
133
  * Splits text into runs by glyph availability: the main font, or the first fallback that has a glyph where the
132
- * main font has glyph 0. Spaces always stay on the main font (fallback faces often carry very wide spaces).
134
+ * main font has glyph 0. Spaces always stay on the main font (fallback faces often carry very wide spaces). A joiner,
135
+ * a variation selector, a skin tone or a tag keeps the font of the glyph before it: an emoji sequence is one run.
133
136
  */
134
137
  private Segment;
135
138
  private Width;
@@ -167,6 +170,22 @@ export declare class SkiaLabel extends SkiaControl {
167
170
  * text cuts it, not only MaxLines).
168
171
  */
169
172
  private LayoutLines;
173
+ /** A paragraph is right to left when its first strong letter is (DrawnUi.Rust split_bidi). */
174
+ private static FirstStrongIsRtl;
175
+ /** The runs of a line cut where the bidirectional level changes; `levels` per UTF-16 index of the line text. */
176
+ private SplitByLevel;
177
+ /**
178
+ * After the layout, lines whose text needs shaping or runs right to left (DrawnUi.Rust build_blobs): with
179
+ * right-to-left text every run is cut where the bidirectional level changes (Unicode bidirectional algorithm, the
180
+ * paragraph direction from its first strong letter); runs that are right to left or need shaping get shaped glyphs;
181
+ * runs are placed in visual order (rule L2). Lines without such text are left as they are (plain path).
182
+ */
183
+ private ShapeLines;
184
+ /**
185
+ * Where each run of a line with right-to-left text goes, in visual order (Unicode rule L2: from the highest level down
186
+ * to the lowest odd one, every sequence of runs at that level or higher is reversed).
187
+ */
188
+ private static PlaceRuns;
170
189
  private LineHeightPx;
171
190
  /** ParagraphSpacing above a line that starts a paragraph (after the first): that many of its lines, with their spacing. */
172
191
  private ParagraphSpace;
@@ -3,6 +3,7 @@ import { ControlTappedEventArgs } from "../core/Gestures";
3
3
  import { Super } from "../core/Super";
4
4
  import { Colors, ScaledSize, SKRect, Thickness, } from "../core/Types";
5
5
  import { TextSpan } from "./TextSpan";
6
+ import { BidiLevels, HasCodePoint, IsRtl, JoinsPrevious, NeedsShaping, Shape } from "../core/Shaping";
6
7
  /**
7
8
  * Mirrors DrawnUi SkiaLabel: multi-line text with word wrapping, MaxLines + tail ellipsis, horizontal /
8
9
  * vertical alignment, LineSpacing / LineHeight, weights and attributes resolved through the font registry,
@@ -158,7 +159,14 @@ export class SkiaLabel extends SkiaControl {
158
159
  const weight = span.FontWeight > 0 ? span.FontWeight : span.IsBold ? 700 : this.fontWeight > 0 ? this.fontWeight : bold ? 700 : 0;
159
160
  return this.ResolveFonts(span.FontFamily ?? this.fontFamily, weight, italic, (span.FontSize ?? this.fontSize) * scale);
160
161
  }
162
+ static NeedsShapingOrRtl(cp) { return NeedsShaping(cp) || IsRtl(cp); }
163
+ /** Width of a text in one font: the shaped glyphs where the text needs shaping (Arabic joins, emoji sequences), else glyph by glyph. */
161
164
  Advance(font, text) {
165
+ if (HasCodePoint(text, SkiaLabel.NeedsShapingOrRtl)) {
166
+ const shaped = Shape(font, text, HasCodePoint(text, IsRtl), this.glyphSpacing);
167
+ if (shaped)
168
+ return shaped.Width;
169
+ }
162
170
  let w = 0;
163
171
  for (const adv of font.getGlyphWidths(font.getGlyphIDs(text)))
164
172
  w += adv + this.glyphSpacing;
@@ -178,7 +186,8 @@ export class SkiaLabel extends SkiaControl {
178
186
  }
179
187
  /**
180
188
  * Splits text into runs by glyph availability: the main font, or the first fallback that has a glyph where the
181
- * main font has glyph 0. Spaces always stay on the main font (fallback faces often carry very wide spaces).
189
+ * main font has glyph 0. Spaces always stay on the main font (fallback faces often carry very wide spaces). A joiner,
190
+ * a variation selector, a skin tone or a tag keeps the font of the glyph before it: an emoji sequence is one run.
182
191
  */
183
192
  Segment(text, fonts, span) {
184
193
  if (text.length === 0)
@@ -211,7 +220,7 @@ export class SkiaLabel extends SkiaControl {
211
220
  };
212
221
  let start = 0, current = fontFor(0);
213
222
  for (let i = 1; i < cps.length; i++) {
214
- const f = fontFor(i);
223
+ const f = JoinsPrevious(cps[i].codePointAt(0)) ? current : fontFor(i);
215
224
  if (f !== current) {
216
225
  const t = cps.slice(start, i).join("");
217
226
  cached.push({ Text: t, Font: current, Width: this.Advance(current, t), Fonts: fonts });
@@ -342,11 +351,11 @@ export class SkiaLabel extends SkiaControl {
342
351
  else if (this.text) {
343
352
  add(this.text, this.mainFonts);
344
353
  }
345
- // a fragment ending with a space puts the space before the NEXT token
354
+ // a fragment ending with a space puts that space, in its own style, before the NEXT token
346
355
  for (const para of paragraphs) {
347
356
  for (let i = 0; i < para.length; i++) {
348
357
  if (para[i].TrailingSpace && i + 1 < para.length)
349
- para[i + 1].SpaceBefore = true;
358
+ para[i + 1].Carried = { Fonts: para[i].Fonts, Span: para[i].Span };
350
359
  }
351
360
  }
352
361
  return paragraphs;
@@ -389,12 +398,16 @@ export class SkiaLabel extends SkiaControl {
389
398
  lastFonts = tok.Fonts;
390
399
  // glued fragments (no space between spans) wrap as one word
391
400
  let word = this.Segment(tok.Text, tok.Fonts, tok.Span);
392
- while (i + 1 < para.length && !para[i + 1].SpaceBefore) {
401
+ while (i + 1 < para.length && !para[i + 1].SpaceBefore && !para[i + 1].Carried) {
393
402
  i++;
394
403
  word = word.concat(this.Segment(para[i].Text, para[i].Fonts, para[i].Span));
395
404
  }
396
405
  for (;;) {
397
- const space = tok.SpaceBefore && line.Runs.length > 0 ? this.Segment(" ", tok.Fonts, tok.Span) : [];
406
+ // the space the fragment before ends with, then the word's own one, each in its style
407
+ const space = line.Runs.length === 0 ? [] : [
408
+ ...(tok.Carried ? this.Segment(" ", tok.Carried.Fonts, tok.Carried.Span) : []),
409
+ ...(tok.SpaceBefore ? this.Segment(" ", tok.Fonts, tok.Span) : []),
410
+ ];
398
411
  const spaceW = this.Width(space), wordW = this.Width(word);
399
412
  if (!wrap || line.Width + spaceW + wordW - sp <= maxWidth || (line.Runs.length === 0 && wordW - sp <= maxWidth)) {
400
413
  this.Append(line, space);
@@ -481,6 +494,120 @@ export class SkiaLabel extends SkiaControl {
481
494
  l.Width -= sp;
482
495
  return out;
483
496
  }
497
+ /** A paragraph is right to left when its first strong letter is (DrawnUi.Rust split_bidi). */
498
+ static FirstStrongIsRtl(text) {
499
+ for (const ch of text) {
500
+ const cp = ch.codePointAt(0);
501
+ if (IsRtl(cp))
502
+ return true;
503
+ if (/\p{L}/u.test(ch))
504
+ return false;
505
+ }
506
+ return false;
507
+ }
508
+ /** The runs of a line cut where the bidirectional level changes; `levels` per UTF-16 index of the line text. */
509
+ SplitByLevel(runs, levels) {
510
+ const out = [];
511
+ let at = 0;
512
+ for (const r of runs) {
513
+ const piece = (from, to, level) => {
514
+ const text = r.Text.slice(from, to);
515
+ out.push({ ...r, Text: text, Width: from === 0 && to === r.Text.length ? r.Width : this.Advance(r.Font, text), Level: level, Shaped: undefined, X: undefined });
516
+ };
517
+ let from = 0, level = levels[at] ?? 0;
518
+ for (let i = 0; i < r.Text.length;) {
519
+ const next = levels[at + i] ?? level;
520
+ if (i > 0 && next !== level) {
521
+ piece(from, i, level);
522
+ from = i;
523
+ level = next;
524
+ }
525
+ i += r.Text.codePointAt(i) > 0xFFFF ? 2 : 1;
526
+ }
527
+ if (r.Text.length > 0)
528
+ piece(from, r.Text.length, level);
529
+ at += r.Text.length;
530
+ }
531
+ return out;
532
+ }
533
+ /**
534
+ * After the layout, lines whose text needs shaping or runs right to left (DrawnUi.Rust build_blobs): with
535
+ * right-to-left text every run is cut where the bidirectional level changes (Unicode bidirectional algorithm, the
536
+ * paragraph direction from its first strong letter); runs that are right to left or need shaping get shaped glyphs;
537
+ * runs are placed in visual order (rule L2). Lines without such text are left as they are (plain path).
538
+ */
539
+ ShapeLines(lines) {
540
+ const sp = this.glyphSpacing;
541
+ const lineText = (l) => l.Runs.map((r) => r.Text).join("");
542
+ const anyRtl = lines.some((l) => l.Runs.some((r) => HasCodePoint(r.Text, IsRtl)));
543
+ let rtlParagraph = false;
544
+ for (let li = 0; li < lines.length; li++) {
545
+ const line = lines[li];
546
+ let bidi = false;
547
+ if (anyRtl) {
548
+ if (li === 0 || line.Para) {
549
+ let end = li + 1;
550
+ while (end < lines.length && !lines[end].Para)
551
+ end++;
552
+ rtlParagraph = SkiaLabel.FirstStrongIsRtl(lines.slice(li, end).map(lineText).join(""));
553
+ }
554
+ const levels = BidiLevels(lineText(line), rtlParagraph);
555
+ if (levels) {
556
+ line.Runs = this.SplitByLevel(line.Runs, levels);
557
+ bidi = line.Runs.some((r) => (r.Level ?? 0) > 0);
558
+ }
559
+ }
560
+ let shaped = false;
561
+ for (const run of line.Runs) {
562
+ const rtl = (run.Level ?? 0) % 2 === 1;
563
+ if (!rtl && !HasCodePoint(run.Text, NeedsShaping))
564
+ continue;
565
+ const s = Shape(run.Font, run.Text, rtl, sp);
566
+ if (s) {
567
+ run.Shaped = s;
568
+ run.Width = s.Width;
569
+ shaped = true;
570
+ }
571
+ }
572
+ if (!shaped && !bidi)
573
+ continue;
574
+ let width = 0;
575
+ for (const run of line.Runs)
576
+ width += run.Width;
577
+ line.Width = line.Runs.length > 0 ? width - sp : 0;
578
+ if (bidi)
579
+ SkiaLabel.PlaceRuns(line.Runs);
580
+ }
581
+ }
582
+ /**
583
+ * Where each run of a line with right-to-left text goes, in visual order (Unicode rule L2: from the highest level down
584
+ * to the lowest odd one, every sequence of runs at that level or higher is reversed).
585
+ */
586
+ static PlaceRuns(runs) {
587
+ const order = runs.map((_, i) => i);
588
+ const levelOf = (i) => runs[i].Level ?? 0;
589
+ const highest = Math.max(0, ...runs.map((r) => r.Level ?? 0));
590
+ const odd = runs.map((r) => r.Level ?? 0).filter((l) => l % 2 === 1);
591
+ const lowestOdd = odd.length ? Math.min(...odd) : highest + 1;
592
+ for (let level = highest; level >= lowestOdd && level > 0; level--) {
593
+ for (let i = 0; i < order.length;) {
594
+ if (levelOf(order[i]) < level) {
595
+ i++;
596
+ continue;
597
+ }
598
+ const start = i;
599
+ while (i < order.length && levelOf(order[i]) >= level)
600
+ i++;
601
+ const reversed = order.slice(start, i).reverse();
602
+ order.splice(start, reversed.length, ...reversed);
603
+ }
604
+ }
605
+ let x = 0;
606
+ for (const k of order) {
607
+ runs[k].X = x;
608
+ x += runs[k].Width;
609
+ }
610
+ }
484
611
  LineHeightPx(line) { return (line.Ascent + line.Descent) * this.lineHeight; }
485
612
  /** ParagraphSpacing above a line that starts a paragraph (after the first): that many of its lines, with their spacing. */
486
613
  ParagraphSpace(line) { return line.Para && this.paragraphSpacing ? this.LineHeightPx(line) * this.lineSpacing * this.paragraphSpacing : 0; }
@@ -502,6 +629,7 @@ export class SkiaLabel extends SkiaControl {
502
629
  const px = this.padding.HorizontalThickness * scale, py = this.padding.VerticalThickness * scale;
503
630
  const extraH = this.EffectsExtra(scale).H;
504
631
  this.lines = this.text || this.Spans.length > 0 ? this.LayoutLines(widthConstraint - px, scale, heightConstraint - py - extraH) : [];
632
+ this.ShapeLines(this.lines);
505
633
  let width = 0;
506
634
  for (const l of this.lines)
507
635
  width = Math.max(width, l.Width);
@@ -578,10 +706,13 @@ export class SkiaLabel extends SkiaControl {
578
706
  let start = g.text.length ? this.text.indexOf(g.text, cursor) : cursor;
579
707
  if (start < 0)
580
708
  start = cursor;
709
+ // right-to-left runs are boxed left to right in logical order (the caret is not placed visually there)
581
710
  let x = g.x, index = start;
582
711
  for (const run of line.Runs) {
712
+ if (run.X !== undefined)
713
+ x = g.x + run.X;
583
714
  const cps = Array.from(run.Text);
584
- const widths = run.Font.getGlyphWidths(run.Font.getGlyphIDs(run.Text, cps.length));
715
+ const widths = run.Shaped ? run.Shaped.Advances.map((a) => a - this.glyphSpacing) : run.Font.getGlyphWidths(run.Font.getGlyphIDs(run.Text, cps.length));
585
716
  cps.forEach((cp, k) => {
586
717
  const w = widths[k] ?? 0;
587
718
  out.push({ Index: index, Length: cp.length, Line: li, Left: x, Top: g.y, Width: w, Height: g.h });
@@ -670,6 +801,10 @@ export class SkiaLabel extends SkiaControl {
670
801
  const sp = this.glyphSpacing;
671
802
  // spaced text: every glyph placed with the gap after it (C# MeasureLineGlyphs positions)
672
803
  const drawRun = (run, rx, ry, paint) => {
804
+ if (run.Shaped) {
805
+ canvas.drawGlyphs(run.Shaped.Glyphs, run.Shaped.Positions, rx, ry, run.Font, paint);
806
+ return;
807
+ }
673
808
  if (sp === 0) {
674
809
  canvas.drawText(run.Text, rx, ry, paint, run.Font);
675
810
  return;
@@ -699,7 +834,11 @@ export class SkiaLabel extends SkiaControl {
699
834
  const gradientRect = gradient ? (this.GradientByLines ? new SKRect(x, y, x + line.Width, y + lh) : textRect) : undefined;
700
835
  if (strokePaint && this.StrokeGradient)
701
836
  this.SetupGradient(strokePaint, this.StrokeGradient, gradientRect ?? new SKRect(x, y, x + line.Width, y + lh));
837
+ const lineX = x;
702
838
  for (const run of line.Runs) {
839
+ // a line with right-to-left text places its runs in visual order
840
+ if (run.X !== undefined)
841
+ x = lineX + run.X;
703
842
  const span = run.Span;
704
843
  const drawnW = run.Width - sp; // the gap after the run's last glyph is not part of it
705
844
  if (span) {
@@ -72,6 +72,6 @@ export declare class SkiaRichLabel extends SkiaLabel {
72
72
  private RenderDocument;
73
73
  /** Blocks are separated by one line break once something was emitted (C# hadParagraph). */
74
74
  private BeginBlock;
75
- /** Inline markdown: `code`, **bold**, __bold__, *italic*, _italic_, ~~strike~~, [text](url), backslash escapes. */
75
+ /** Inline markdown: `code`, ***bold italic***, ___bold italic___, **bold**, __bold__, *italic*, _italic_, ~~strike~~, [text](url), backslash escapes. */
76
76
  private RenderInlines;
77
77
  }
@@ -206,7 +206,7 @@ export class SkiaRichLabel extends SkiaLabel {
206
206
  this.LineBreak();
207
207
  this.hadParagraph = true;
208
208
  }
209
- /** Inline markdown: `code`, **bold**, __bold__, *italic*, _italic_, ~~strike~~, [text](url), backslash escapes. */
209
+ /** Inline markdown: `code`, ***bold italic***, ___bold italic___, **bold**, __bold__, *italic*, _italic_, ~~strike~~, [text](url), backslash escapes. */
210
210
  RenderInlines(text, state) {
211
211
  let literal = "";
212
212
  const flush = () => { if (literal) {
@@ -246,6 +246,16 @@ export class SkiaRichLabel extends SkiaLabel {
246
246
  continue;
247
247
  }
248
248
  }
249
+ const three = text.slice(i, i + 3);
250
+ if (three === "***" || three === "___") {
251
+ const end = closes(three, i + 3);
252
+ if (end > i + 3) {
253
+ flush();
254
+ this.RenderInlines(text.slice(i + 3, end), { ...state, bold: true, italic: true });
255
+ i = end + 3;
256
+ continue;
257
+ }
258
+ }
249
259
  const two = text.slice(i, i + 2);
250
260
  if (two === "**" || two === "__" || two === "~~") {
251
261
  const end = closes(two, i + 2);
@@ -0,0 +1,35 @@
1
+ import type { Font } from "canvaskit-wasm";
2
+ /**
3
+ * Text shaping (C# SkiaLabel DrawShapedText, HarfBuzzSharp there; DrawnUi.Rust shaping.rs, harfrust) for the text that
4
+ * needs it: complex scripts whose letters join or reorder (Arabic, Hebrew marks, Indic, Thai...) and emoji sequences
5
+ * (ZWJ families, skin tones, flags, keycaps). Everything else keeps the plain path: one glyph per character.
6
+ * HarfBuzz and ICU come with the CanvasKit paragraph module, already in the build (no extra wasm): a run is laid out as a
7
+ * one-font paragraph and its shaped glyphs are read back; the label keeps its own line breaking and font fallback.
8
+ */
9
+ /** C# SkiaLabel.UnicodeNeedsShaping, plus the characters that make emoji sequences and the right-to-left scripts C# leaves out. */
10
+ export declare function NeedsShaping(cp: number): boolean;
11
+ /** Characters that belong to the glyph before them (an emoji sequence or a mark): they keep its font (C# JoinsPreviousGlyph). */
12
+ export declare function JoinsPrevious(cp: number): boolean;
13
+ /** Right-to-left letters: a paragraph with one of them gets the bidirectional pass. */
14
+ export declare function IsRtl(cp: number): boolean;
15
+ /** Whether a text has a character `test` accepts. */
16
+ export declare function HasCodePoint(text: string, test: (cp: number) => boolean): boolean;
17
+ /** One shaped run: glyphs from x = 0 on the baseline, in visual order, and the advance of every code point in logical order (a cluster's advance on its first code point). */
18
+ export interface Shaped {
19
+ Glyphs: Uint16Array;
20
+ Positions: Float32Array;
21
+ Advances: number[];
22
+ Width: number;
23
+ }
24
+ /**
25
+ * Shapes `text` with `font` in one direction (the caller splits runs by font and by bidirectional level), `spacing`
26
+ * pixels after every code point. Undefined when the font was not registered through the font registry (no shaping
27
+ * data): the caller keeps its plain glyphs.
28
+ */
29
+ export declare function Shape(font: Font, text: string, rtl: boolean, spacing: number): Shaped | undefined;
30
+ /**
31
+ * Bidirectional level of every UTF-16 index of a line (Unicode bidirectional algorithm, ICU in CanvasKit): 0 left to
32
+ * right in a left-to-right paragraph, 1 right to left, 2 left to right inside a right-to-left paragraph. Explicit
33
+ * embeddings (U+202A..202E, U+2066..2069) are resolved by ICU but reported as their direction only.
34
+ */
35
+ export declare function BidiLevels(text: string, rtlParagraph: boolean): Uint8Array | undefined;
@@ -0,0 +1,181 @@
1
+ import { Super } from "./Super";
2
+ /**
3
+ * Text shaping (C# SkiaLabel DrawShapedText, HarfBuzzSharp there; DrawnUi.Rust shaping.rs, harfrust) for the text that
4
+ * needs it: complex scripts whose letters join or reorder (Arabic, Hebrew marks, Indic, Thai...) and emoji sequences
5
+ * (ZWJ families, skin tones, flags, keycaps). Everything else keeps the plain path: one glyph per character.
6
+ * HarfBuzz and ICU come with the CanvasKit paragraph module, already in the build (no extra wasm): a run is laid out as a
7
+ * one-font paragraph and its shaped glyphs are read back; the label keeps its own line breaking and font fallback.
8
+ */
9
+ /** C# SkiaLabel.UnicodeNeedsShaping, plus the characters that make emoji sequences and the right-to-left scripts C# leaves out. */
10
+ export function NeedsShaping(cp) {
11
+ return (cp >= 0x0590 && cp <= 0x08FF) // Hebrew, Arabic, Syriac, Arabic Supplement, Thaana, NKo, Samaritan, Mandaic, Arabic Extended
12
+ || (cp >= 0x0900 && cp <= 0x0DFF) // Devanagari .. Sinhala
13
+ || (cp >= 0x0E00 && cp <= 0x0FFF) // Thai, Lao, Tibetan
14
+ || (cp >= 0x1000 && cp <= 0x109F) // Myanmar
15
+ || (cp >= 0x10A0 && cp <= 0x10FF) // Georgian
16
+ || (cp >= 0x1100 && cp <= 0x11FF) // Hangul Jamo
17
+ || (cp >= 0x1200 && cp <= 0x137F) // Ethiopic
18
+ || (cp >= 0x1780 && cp <= 0x18AF) // Khmer, Mongolian
19
+ || cp === 0x200C || cp === 0x200D // ZWNJ, ZWJ
20
+ || cp === 0x20E3 // keycap
21
+ || (cp >= 0x2600 && cp <= 0x27BF) // symbols that have emoji forms
22
+ || (cp >= 0xFB1D && cp <= 0xFDFF) // Hebrew and Arabic presentation forms A
23
+ || (cp >= 0xFE00 && cp <= 0xFE0F) // variation selectors (VS15 / VS16)
24
+ || (cp >= 0xFE70 && cp <= 0xFEFF) // Arabic presentation forms B
25
+ || (cp >= 0x1F000 && cp <= 0x1FAFF) // emoji, regional indicators (flags), skin tones
26
+ || (cp >= 0xE0020 && cp <= 0xE007F); // tag sequences (subdivision flags)
27
+ }
28
+ /** Characters that belong to the glyph before them (an emoji sequence or a mark): they keep its font (C# JoinsPreviousGlyph). */
29
+ export function JoinsPrevious(cp) {
30
+ return cp === 0x200D || cp === 0x20E3 || (cp >= 0xFE00 && cp <= 0xFE0F) || (cp >= 0x1F3FB && cp <= 0x1F3FF) || (cp >= 0xE0020 && cp <= 0xE007F);
31
+ }
32
+ /** Right-to-left letters: a paragraph with one of them gets the bidirectional pass. */
33
+ export function IsRtl(cp) {
34
+ return (cp >= 0x0590 && cp <= 0x08FF) || (cp >= 0xFB1D && cp <= 0xFDFF) || (cp >= 0xFE70 && cp <= 0xFEFF) || (cp >= 0x10800 && cp <= 0x10FFF) || (cp >= 0x1E800 && cp <= 0x1EFFF);
35
+ }
36
+ /** Whether a text has a character `test` accepts. */
37
+ export function HasCodePoint(text, test) {
38
+ for (let i = 0; i < text.length; i++) {
39
+ const c = text.charCodeAt(i);
40
+ // below U+0590 nothing needs shaping or is right to left
41
+ if (c < 0x0590)
42
+ continue;
43
+ const cp = text.codePointAt(i);
44
+ if (test(cp))
45
+ return true;
46
+ if (cp > 0xFFFF)
47
+ i++;
48
+ }
49
+ return false;
50
+ }
51
+ const cache = new Map();
52
+ /** Bounds the shaping cache; a label re-measured with new text shapes again. */
53
+ const CacheLimit = 4000;
54
+ /**
55
+ * Shapes `text` with `font` in one direction (the caller splits runs by font and by bidirectional level), `spacing`
56
+ * pixels after every code point. Undefined when the font was not registered through the font registry (no shaping
57
+ * data): the caller keeps its plain glyphs.
58
+ */
59
+ export function Shape(font, text, rtl, spacing) {
60
+ const family = Super.ShapingFamilyOf(font);
61
+ if (!family || !text)
62
+ return undefined;
63
+ const size = font.getSize();
64
+ const key = `${family}|${size}|${rtl ? 1 : 0}|${spacing}|${text}`;
65
+ const hit = cache.get(key);
66
+ if (hit !== undefined)
67
+ return hit ?? undefined;
68
+ const shaped = ShapeNow(font, family, size, text, rtl, spacing);
69
+ if (cache.size >= CacheLimit)
70
+ cache.clear();
71
+ cache.set(key, shaped ?? null);
72
+ return shaped;
73
+ }
74
+ /** Width a run is laid out in: one line, never wrapped; a right-to-left run ends at its right edge. */
75
+ const LayoutWidth = 1e6;
76
+ function Paragraph(family, size, text, rtl) {
77
+ const CK = Super.CK;
78
+ const style = new CK.ParagraphStyle({ textStyle: { fontFamilies: [family], fontSize: size }, textDirection: rtl ? CK.TextDirection.RTL : CK.TextDirection.LTR });
79
+ const builder = CK.ParagraphBuilder.MakeFromFontProvider(style, Super.ShapingFonts);
80
+ builder.addText(text);
81
+ const paragraph = builder.build();
82
+ builder.delete();
83
+ paragraph.layout(LayoutWidth);
84
+ return paragraph;
85
+ }
86
+ function ShapeNow(font, family, size, text, rtl, spacing) {
87
+ const paragraph = Paragraph(family, size, text, rtl);
88
+ try {
89
+ const lines = paragraph.getShapedLines();
90
+ if (lines.length === 0)
91
+ return undefined;
92
+ // the code point of every UTF-8 byte offset (the shaped runs report clusters in UTF-8)
93
+ const cpOfByte = [];
94
+ let cps = 0;
95
+ for (const ch of text) {
96
+ const c = ch.codePointAt(0), bytes = c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
97
+ for (let b = 0; b < bytes; b++)
98
+ cpOfByte.push(cps);
99
+ cps++;
100
+ }
101
+ const cpOf = (byte) => cpOfByte[Math.min(byte, cpOfByte.length - 1)] ?? 0;
102
+ let count = 0;
103
+ for (const l of lines)
104
+ for (const r of l.runs)
105
+ count += r.glyphs.length;
106
+ const glyphs = new Uint16Array(count), positions = new Float32Array(count * 2), advances = new Array(cps).fill(0), clusters = new Array(count);
107
+ // one line (no width limit, no line breaks in a run); runs come in visual order. Glyph positions include their
108
+ // offsets (a mark sits off its pen position), so the run's left edge and width come from the paragraph itself.
109
+ const shapedWidth = paragraph.getMaxIntrinsicWidth();
110
+ const left = rtl ? LayoutWidth - shapedWidth : 0;
111
+ let k = 0;
112
+ for (const l of lines) {
113
+ for (const r of l.runs) {
114
+ for (let g = 0; g < r.glyphs.length; g++, k++) {
115
+ glyphs[k] = r.glyphs[g];
116
+ positions[k * 2] = r.positions[g * 2] - left;
117
+ positions[k * 2 + 1] = r.positions[g * 2 + 1] - l.baseline;
118
+ clusters[k] = cpOf(r.offsets[g]);
119
+ }
120
+ }
121
+ }
122
+ // the advance of every cluster (caret boxes): its glyphs' advances, scaled to the shaped width (kerning, joins)
123
+ const glyphWidths = font.getGlyphWidths(glyphs);
124
+ let sum = 0;
125
+ for (let g = 0; g < count; g++) {
126
+ advances[clusters[g]] += glyphWidths[g];
127
+ sum += glyphWidths[g];
128
+ }
129
+ if (sum > 0)
130
+ for (let i = 0; i < advances.length; i++)
131
+ advances[i] *= shapedWidth / sum;
132
+ if (spacing !== 0) {
133
+ // visual order: the spacing of the code points between two clusters goes between them
134
+ let extra = 0, last = -1;
135
+ for (let g = 0; g < count; g++) {
136
+ if (last >= 0 && last !== clusters[g])
137
+ extra += spacing * Math.abs(last - clusters[g]);
138
+ last = clusters[g];
139
+ positions[g * 2] += extra;
140
+ }
141
+ for (let i = 0; i < advances.length; i++)
142
+ advances[i] += spacing;
143
+ }
144
+ const width = shapedWidth + spacing * cps;
145
+ return { Glyphs: glyphs, Positions: positions, Advances: advances, Width: width };
146
+ }
147
+ finally {
148
+ paragraph.delete();
149
+ }
150
+ }
151
+ /**
152
+ * Bidirectional level of every UTF-16 index of a line (Unicode bidirectional algorithm, ICU in CanvasKit): 0 left to
153
+ * right in a left-to-right paragraph, 1 right to left, 2 left to right inside a right-to-left paragraph. Explicit
154
+ * embeddings (U+202A..202E, U+2066..2069) are resolved by ICU but reported as their direction only.
155
+ */
156
+ export function BidiLevels(text, rtlParagraph) {
157
+ const family = Super.AnyShapingFamily();
158
+ if (!family)
159
+ return undefined;
160
+ const CK = Super.CK;
161
+ const paragraph = Paragraph(family, 12, text, rtlParagraph);
162
+ try {
163
+ const levels = new Uint8Array(text.length);
164
+ let level = rtlParagraph ? 1 : 0;
165
+ for (let i = 0; i < text.length; i++) {
166
+ const c = text.charCodeAt(i);
167
+ if (c >= 0xDC00 && c <= 0xDFFF) {
168
+ levels[i] = level;
169
+ continue;
170
+ } // low surrogate: as its pair
171
+ const info = paragraph.getGlyphInfoAt(i);
172
+ if (info)
173
+ level = info.dir.value === CK.TextDirection.RTL.value ? 1 : rtlParagraph ? 2 : 0;
174
+ levels[i] = level;
175
+ }
176
+ return levels;
177
+ }
178
+ finally {
179
+ paragraph.delete();
180
+ }
181
+ }
@@ -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;
@@ -49,6 +49,19 @@ export declare class Super {
49
49
  /** CanvasKit's built-in face: what an empty FontFamily resolves to, like C# SKTypeface.CreateDefault(). */
50
50
  static SkiaDefaultTypeface?: Typeface;
51
51
  private static readonly fontCache;
52
+ /** Every face loaded from data, each under a family of its own: the paragraph module shapes text with them (`Shaping`). */
53
+ static ShapingFonts?: TypefaceFontProvider;
54
+ private static readonly shapingFamilyOfFace;
55
+ private static readonly shapingFamilyOfFont;
56
+ /**
57
+ * A face from font file data, also usable for shaping (complex scripts, emoji sequences, right to left). Register fonts
58
+ * by alias with `Super.Fonts` / ConfigureFonts; this only makes the face. Undefined when the data is no font.
59
+ */
60
+ static LoadFace(data: ArrayBuffer | Uint8Array): Typeface | undefined;
61
+ /** The shaping family of a font made by GetFont, undefined for faces without shaping data (CanvasKit's built-in face). */
62
+ static ShapingFamilyOf(font: Font): string | undefined;
63
+ /** Any shaping family (the bidirectional pass needs one, its font does not matter). */
64
+ static AnyShapingFamily(): string | undefined;
52
65
  static UseDrawnUi(): DrawnUiBuilder;
53
66
  /** Master switch: false makes every control render uncached (DrawnUi Super.CacheEnabled). */
54
67
  static CacheEnabled: boolean;
@@ -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
  }
@@ -47,7 +47,7 @@ export class DrawnUiBuilder {
47
47
  let face = loaded.get(f.Source);
48
48
  if (!face) {
49
49
  const data = await (await fetch(Super.ResolveAssetUrl(f.Source))).arrayBuffer();
50
- face = Super.CK.Typeface.MakeFreeTypeFaceFromData(data) ?? undefined;
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);
@@ -119,6 +119,31 @@ export class Super {
119
119
  /** CanvasKit's built-in face: what an empty FontFamily resolves to, like C# SKTypeface.CreateDefault(). */
120
120
  static SkiaDefaultTypeface;
121
121
  static fontCache = new Map();
122
+ /** Every face loaded from data, each under a family of its own: the paragraph module shapes text with them (`Shaping`). */
123
+ static ShapingFonts;
124
+ static shapingFamilyOfFace = new Map();
125
+ static shapingFamilyOfFont = new WeakMap();
126
+ /**
127
+ * A face from font file data, also usable for shaping (complex scripts, emoji sequences, right to left). Register fonts
128
+ * by alias with `Super.Fonts` / ConfigureFonts; this only makes the face. Undefined when the data is no font.
129
+ */
130
+ static LoadFace(data) {
131
+ const CK = Super.CK;
132
+ Super.ShapingFonts ??= CK.TypefaceFontProvider.Make();
133
+ const family = `drawnui-shaping-${Super.shapingFamilyOfFace.size}`;
134
+ Super.ShapingFonts.registerFont(data, family);
135
+ const face = Super.ShapingFonts.matchFamilyStyle(family, { weight: CK.FontWeight.Normal, width: CK.FontWidth.Normal, slant: CK.FontSlant.Upright });
136
+ if (face) {
137
+ Super.shapingFamilyOfFace.set(face, family);
138
+ return face;
139
+ }
140
+ return CK.Typeface.MakeFreeTypeFaceFromData(data instanceof Uint8Array ? data.slice().buffer : data) ?? undefined;
141
+ }
142
+ /** The shaping family of a font made by GetFont, undefined for faces without shaping data (CanvasKit's built-in face). */
143
+ static ShapingFamilyOf(font) { return Super.shapingFamilyOfFont.get(font); }
144
+ /** Any shaping family (the bidirectional pass needs one, its font does not matter). */
145
+ static AnyShapingFamily() { for (const f of Super.shapingFamilyOfFace.values())
146
+ return f; return undefined; }
122
147
  static UseDrawnUi() { return new DrawnUiBuilder(); }
123
148
  /** Master switch: false makes every control render uncached (DrawnUi Super.CacheEnabled). */
124
149
  static CacheEnabled = true;
@@ -202,6 +227,9 @@ export class Super {
202
227
  // no bold face registered: synthetic bold, like C# Font.Embolden = IsBold
203
228
  if (weight >= 600 && resolved.Weight < 600)
204
229
  font.setEmbolden(true);
230
+ const family = resolved.Typeface ? Super.shapingFamilyOfFace.get(resolved.Typeface) : undefined;
231
+ if (family)
232
+ Super.shapingFamilyOfFont.set(font, family);
205
233
  Super.fontCache.set(key, font);
206
234
  }
207
235
  return font;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "drawnui-react",
3
- "version": "0.1.0-preview.26",
3
+ "version": "0.1.0-preview.28",
4
4
  "description": "DrawnUi for React: the DrawnUi (.NET) drawn-UI engine in TypeScript on CanvasKit (Skia WASM). Same controls, same PascalCase API as DrawnUi.Net.",
5
5
  "license": "MIT",
6
6
  "author": "Nick Kovalsky (AppoMobi)",
@@ -83,6 +83,9 @@
83
83
  "check:thickness": "node dev/check.mjs dev/check-thickness.ts",
84
84
  "check:scroll-recycled": "node dev/check.mjs dev/check-scroll-recycled.ts",
85
85
  "check:masonry-keys": "node dev/check.mjs dev/check-masonry-keys.ts",
86
+ "check:carousel-swipe": "node dev/check.mjs dev/check-carousel-swipe.ts",
87
+ "check:editor-focus": "node dev/check.mjs dev/check-editor-focus.ts",
88
+ "check:shaping": "node dev/check.mjs dev/check-shaping.ts",
86
89
  "site:extras": "node dev/site-extras.mjs dist/demo",
87
90
  "build:lib": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\" && tsc -p tsconfig.build.json",
88
91
  "prepublishOnly": "npm run build:lib",