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

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/README.md CHANGED
@@ -24,6 +24,9 @@ await Super.UseDrawnUi()
24
24
  </Canvas>
25
25
  ```
26
26
 
27
+ ## MIT, everywhere
28
+ DrawnUI is MIT licensed in every language and on every platform: desktop, mobile, web and embedded devices. Ship it in commercial products with no attribution badge, no about screen and no per-device royalty.
29
+
27
30
  ## Install
28
31
 
29
32
  ```
package/SKIPPED.md CHANGED
@@ -19,7 +19,7 @@ DrawnUi name and semantics; nothing here is a redesign, only an omission.
19
19
  | Disposal (`Dispose` / `OnDisposing`) | ported | The React renderer calls `Dispose()` when an element leaves the tree (`detachDeletedInstance`): caches, gradient shaders, running `*ToAsync` animations, overlay effects, the accessibility node, then the children (static and templated pool); `SkiaScroll`/`SnappingLayout` stop their animators, `SkiaSvg` drops its raster, `SkiaLottie`/`SkiaGif` free the Skottie animation / frames; `Canvas.Dispose` disposes the content. Not ported: `IsDisposing` staged disposal, `Disposing` event, `OnWillDisposeWithChildren`. |
20
20
  | Hover: `ReceivesHover` (opt-in; on by default in SkiaButton, SkiaSlider, the toggles, SkiaRadioButton, SkiaCarousel, SkiaDrawer), `IsHovered`, `HoverChanged` (turns `ReceivesHover` on, as C# `OnHovered`) | ported | drawnui-cross 6m: every opted-in control under the mouse is hovered; nothing changes while a scroll, carousel or drawer moves its content, one check at the last pointer position when it stops and after an add / remove, a rebind, a hidden hovered control or an instant scroll jump; pointerleave clears at once; touch never hovers (`Canvas.Hover`, a `HoverManager`). Not ported: C# `SetHover`, `CheckHovered` / `OnHover` / `IsPointerOver` (no Pointer gestures are routed), SkiaSpinner / wheel picker (no such controls). |
21
21
  | `KeyboardManager` | ported | Window-level keydown / keyup capture listeners like `drawnui-keyboard.js`: `KeyDown` / `KeyUp` with the DOM `event.code` ("KeyA", "ArrowLeft"; C# maps the same codes to `InputKey`), `KeyChar` for printable keys without Ctrl / Alt / Meta, `IsShiftPressed` / `IsControlPressed` / `IsAltPressed`, `AttachToKeyboard` (idempotent, pointerdown pulls window focus inside iframes), `BlurExternalTextInput`, `IsOwnedByElement` / `IsInputMethodKey` (React additions: a handler acting on keys skips keys a focused DOM element or the input method owns, C# 845b26e9); `Subscribe` / `Unsubscribe` instead of C# events. Not ported: `InputKey` enum (codes are strings). |
22
- | `SkiaEditor` | partial | SkiaShape host with padding, content `SkiaLabel` (single-line: `HorizontalTextAlignment` Center / End get the field as the label's minimum width, so short text centers and long text still scrolls), placeholder label, caret (blinking 1 s, `CursorColor`, `CanShowCursor`) and selection overlay (`SelectionColor`) painted by the editor, single line (`MaxLines` 1, scrolls horizontally to the caret) / multiline (`MaxLines` != 1, `AutoHeight`) with own scroll offsets instead of the C# inner `SkiaScroll`; `Text` (line breaks normalized, spaces for single line), `PlaceholderText/Color/HorizontalAlignment`, `FontSize` (12) / `FontFamily` / `FontWeight` / `TextColor` / `TextGradient` / `LineHeight` / `Horizontal|VerticalTextAlignment`, `IsPassword` (bullets), `ReturnType` (Send submits multiline), `KeyboardType` / `IsSpellCheckEnabled` / `UseMarkdown` / `UseUnicode` accepted, `CursorPosition`, `SelectionLength`, `IsFocused` (one focused editor at a time), `ControlStyle` (C# `ApplyControlStyleVisuals` palettes over unset values), events `TextChanged` / `FocusChanged` / `CursorMoved` / `TextSubmitted`, `Submit` / `SelectAll` / `SetSelection` / `SelectWord` / `GetSelectedText` / `DeleteSelection` / `InsertAtCursor` / `CutSelection` / `CopySelection` / `PasteFromClipboard` (navigator.clipboard), the Blazor head stubs `StubTypeText` / `StubPressEnter` / `StubBackspace` / `StubDelete` (grapheme clusters via Intl.Segmenter) / `StubMoveCursor` / `StubSelectRange` / `StubSelectAll` / `HandleVerticalArrow`, Ctrl+A / C / X / V, Home / End, Escape blurs, tap places the caret, drag selects, long press selects a word, shift + tap extends. Keys come from `KeyboardManager` like the Blazor / Wasm heads; on top of that (not in DrawnUi.Blazor) a focused editor is mirrored by a hidden DOM textarea (`TextInputProxy`, `inputmode` from `KeyboardType`, `enterkeyhint` from `ReturnType`) so IME composition, the mobile soft keyboard, autocorrect and native paste / cut / undo reach the editor: every input event is diffed against the editor text and replayed through `StubSelectRange` + `StubTypeText` / `StubBackspace` / `StubPressEnter`; while the proxy holds DOM focus, Backspace / Delete / Enter / Ctrl+C / X / V key events are left to it. iOS may need a second tap for the keyboard (focus() runs on the next frame, outside the touch handler). Not ported: `SkiaCursor` control + `CursorGradient`, `SkiaEditorSelection` handles, `Superview.FocusedChild`, `CommandOn*`, `SkiaEditorDocument` (rich formatting), single-line Enter clearing focus (Blazor keeps it). |
22
+ | `SkiaEditor` | partial | SkiaShape host with padding, content `SkiaLabel` (single-line: `HorizontalTextAlignment` Center / End get the field as the label's minimum width, so short text centers and long text still scrolls), placeholder label, caret (blinking 1 s, `CursorColor`, `CanShowCursor`) and selection overlay (`SelectionColor`) painted by the editor, single line (`MaxLines` 1, scrolls horizontally to the caret) / multiline (`MaxLines` != 1, `AutoHeight`) with own scroll offsets instead of the C# inner `SkiaScroll`; `Text` (line breaks normalized, spaces for single line), `PlaceholderText/Color/HorizontalAlignment`, `FontSize` (12) / `FontFamily` / `FontWeight` / `TextColor` / `TextGradient` / `LineHeight` / `Horizontal|VerticalTextAlignment`, `IsPassword` (bullets), `ReturnType` (Send submits multiline), `KeyboardType` / `IsSpellCheckEnabled` / `UseMarkdown` / `UseUnicode` accepted, `CursorPosition`, `SelectionLength`, `IsFocused` (one focused editor at a time), `ControlStyle` (C# `ApplyControlStyleVisuals` palettes over unset values), events `TextChanged` / `FocusChanged` / `CursorMoved` / `TextSubmitted`, `Submit` / `SelectAll` / `SetSelection` / `SelectWord` / `GetSelectedText` / `DeleteSelection` / `InsertAtCursor` / `CutSelection` / `CopySelection` / `PasteFromClipboard` (navigator.clipboard), the Blazor head stubs `StubTypeText` / `StubPressEnter` / `StubBackspace` / `StubDelete` (grapheme clusters via Intl.Segmenter) / `StubMoveCursor` / `StubSelectRange` / `StubSelectAll` / `HandleVerticalArrow`, Ctrl+A / C / X / V, Home / End, Escape blurs, tap places the caret, drag selects, long press selects a word, shift + tap extends. Keys come from `KeyboardManager` like the Blazor / Wasm heads; on top of that (not in DrawnUi.Blazor) a focused editor is mirrored by a hidden DOM textarea (`TextInputProxy`, `inputmode` from `KeyboardType`, `enterkeyhint` from `ReturnType`) so IME composition, the mobile soft keyboard, autocorrect and native paste / cut / undo reach the editor: every input event is diffed against the editor text and replayed through `StubSelectRange` + `StubTypeText` / `StubBackspace` / `StubPressEnter`; while the proxy holds DOM focus, Backspace / Delete / Enter / Ctrl+C / X / V key events are left to it. iOS may need a second tap for the keyboard (focus() runs on the next frame, outside the touch handler). Not ported: `SkiaCursor` control + `CursorGradient`, `SkiaEditorSelection` handles, `Superview.FocusedChild`, `CommandOn*`, `SkiaEditorDocument` (rich formatting), single-line Enter clearing focus (Blazor keeps it). Right-to-left and mixed text: the caret, taps, Left / Right (visual moves) and the selection follow the screen, stops at grapheme boundaries (drawnui-cross 6ak, same rules as DrawnUi.Rust). |
23
23
  | `SkiaSprite` / `SkiaSpriteSet` | ported | Sprite: `Source` (sheets cached per source, `CachedSpriteSheets`), `Columns` / `Rows` / `MaxFrames`, `FramesPerSecond` (24), `FrameSequence` / `AnimationName` + `CreateAnimationSequence` / `RegisteredAnimations`, `CurrentFrame`, `TotalFrames` / `DurationMs` / `FrameDurationMs` / `FrameWidth` / `FrameHeight`, `ApplyPlacementConfig` (units-per-pixel, size, anchor, offset = C# SpriteFrameImage ResolveFrameMetrics), transparent frame borders trimmed per frame (pixels read once), nearest sampling, AspectFit of the frame, `DisplayRect`, `Success` / `Error`, the AnimatedFramesRenderer playback. Set: `State`, `Define(state, source, columns, rows, fps, repeat, autoPlay, placement)`, `CurrentSprite`, `OnChangeState` hook, hit box from the drawn frame. Not ported: `Display` as a separate SkiaImage child (`SpriteFrameImage`) and the standalone `SkiaSprite(display)` ctor, `RescalingQuality` other than None, `InflateAmount`, `ClearCache` / `RemoveFromCache` (SkiaImageManager owns the images), `SkiaSpriteSet.InvalidateInternal`. Code-behind subclasses (FastRepro `WarriorSprite`) mount through a ref + `AddSubView` and are disposed by the mounting effect. |
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. |
@@ -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 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). |
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, right-to-left alignment by paragraph direction (alignment stays Start / Center / End, as C#). |
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. |
@@ -73,6 +73,12 @@ export declare class SkiaEditor extends SkiaShape {
73
73
  private styleApplied;
74
74
  private layoutVersion;
75
75
  private boxes;
76
+ /** The glyph box starting at a text index, and the one ending at it. */
77
+ private readonly boxAt;
78
+ private readonly boxEnd;
79
+ /** Grapheme boundaries of the text, the places a caret may stand. */
80
+ private stops;
81
+ private stopsText;
76
82
  constructor();
77
83
  get Text(): string;
78
84
  set Text(v: string);
@@ -127,10 +133,23 @@ export declare class SkiaEditor extends SkiaShape {
127
133
  /** Keeps the caret inside the padded box by scrolling the label (C#: SkiaScroll under the label). */
128
134
  private ScrollToCaret;
129
135
  private Boxes;
136
+ private Stops;
137
+ /** The laid-out line a caret index belongs to: the line holding the character before it, else the one starting at it. */
138
+ private static LineOf;
139
+ /** Where the caret before character `index` stands (label pixels): its x, the direction of the text there, its line box. */
140
+ private CaretPlace;
130
141
  /** Rect of the caret before character `index` (label pixels), or undefined before the first layout. */
131
142
  private CaretRectLabelPx;
143
+ /** The grapheme boundary of a line whose caret x is nearest to `x` (a tie: the smaller index). */
144
+ private NearestStop;
132
145
  /** C# GetCursorPosition: the text index nearest to a point in label pixels. */
133
146
  private HitTestIndex;
147
+ /**
148
+ * Left / Right from a caret index: the grapheme boundary on its line whose caret x is nearest that way (equal x: the
149
+ * one logically nearest); at the visual edge of the line one grapheme logically, forward for Right in a
150
+ * left-to-right paragraph and backward in a right-to-left one (Left the other way round).
151
+ */
152
+ private VisualTarget;
134
153
  private LabelPoint;
135
154
  protected Paint(ctx: DrawingContext): void;
136
155
  ProcessGestures(args: SkiaGesturesParameters, apply: GestureEventProcessingInfo): SkiaControl | null;
@@ -164,6 +183,11 @@ export declare class SkiaEditor extends SkiaShape {
164
183
  StubDelete(count?: number): void;
165
184
  /** Arrow / Home / End: the anchor stays, the moving edge follows (shift), or the selection collapses in the move direction. */
166
185
  StubMoveCursor(delta: number, extendSelection?: boolean): void;
186
+ /**
187
+ * Arrow Left (-1) / Right (1): visual moves, as native text fields (see VisualTarget). Without Shift a selection
188
+ * collapses to its visually left (Left) or right (Right) edge; with Shift its moving edge moves.
189
+ */
190
+ MoveVisual(dir: -1 | 1, extendSelection?: boolean): void;
167
191
  StubSelectRange(start: number, length: number): void;
168
192
  StubSelectAll(): void;
169
193
  /** Up / Down keep the caret x on the neighbouring line (C# HandleVerticalArrow). */
@@ -86,6 +86,12 @@ export class SkiaEditor extends SkiaShape {
86
86
  styleApplied = {};
87
87
  layoutVersion = -1;
88
88
  boxes = [];
89
+ /** The glyph box starting at a text index, and the one ending at it. */
90
+ boxAt = new Map();
91
+ boxEnd = new Map();
92
+ /** Grapheme boundaries of the text, the places a caret may stand. */
93
+ stops = [0];
94
+ stopsText = "";
89
95
  constructor() {
90
96
  super();
91
97
  this.Type = "Rectangle";
@@ -382,34 +388,89 @@ export class SkiaEditor extends SkiaShape {
382
388
  this.OnLayoutChanged();
383
389
  }
384
390
  // ---- caret / selection geometry (pixels relative to the label's DrawingRect) ----
391
+ // Rules shared with DrawnUi.Rust (drawnui-cross 6ak): boxes are visual, the caret at index i is the trailing edge of
392
+ // character i - 1 on its line (the leading edge of the first character at a line start), taps and Left / Right go to
393
+ // the grapheme boundary whose caret x is nearest.
385
394
  Boxes() {
386
395
  if (this.layoutVersion !== this.Label.LayoutVersion) {
387
396
  this.boxes = this.Label.GetGlyphBoxes();
388
397
  this.layoutVersion = this.Label.LayoutVersion;
398
+ this.boxAt.clear();
399
+ this.boxEnd.clear();
400
+ for (const b of this.boxes) {
401
+ this.boxAt.set(b.Index, b);
402
+ this.boxEnd.set(b.Index + b.Length, b);
403
+ }
389
404
  }
390
405
  return this.boxes;
391
406
  }
392
- /** Rect of the caret before character `index` (label pixels), or undefined before the first layout. */
393
- CaretRectLabelPx(index = this.cursorPosition + this.selectionLength) {
394
- const boxes = this.Boxes();
407
+ Stops() {
408
+ if (this.stopsText !== this.text) {
409
+ this.stopsText = this.text;
410
+ this.stops = SkiaEditor.Graphemes(this.text).map((g) => g.index);
411
+ this.stops.push(this.text.length);
412
+ }
413
+ return this.stops;
414
+ }
415
+ /** The laid-out line a caret index belongs to: the line holding the character before it, else the one starting at it. */
416
+ static LineOf(index, lines) {
417
+ for (const l of lines)
418
+ if (index > l.Start && index <= l.End)
419
+ return l;
420
+ for (const l of lines)
421
+ if (index === l.Start)
422
+ return l;
423
+ let line = lines[0];
424
+ for (const l of lines)
425
+ if (l.Start <= index)
426
+ line = l; // in a space wrapped away: the line before it
427
+ return line;
428
+ }
429
+ /** Where the caret before character `index` stands (label pixels): its x, the direction of the text there, its line box. */
430
+ CaretPlace(index) {
395
431
  const lines = this.Label.GetLineBoxes();
396
432
  if (lines.length === 0)
397
433
  return undefined;
434
+ const boxes = this.Boxes();
435
+ const line = SkiaEditor.LineOf(index, lines);
436
+ const trailing = (b) => ({ X: b.Rtl ? b.Left : b.Left + b.Width, Rtl: !!b.Rtl, Top: b.Top, Height: b.Height });
437
+ if (index > line.Start) {
438
+ let prev = this.boxEnd.get(index);
439
+ if (!prev || prev.Line !== line.Line) {
440
+ prev = undefined;
441
+ for (const b of boxes)
442
+ if (b.Line === line.Line && b.Index < index)
443
+ prev = b;
444
+ }
445
+ if (prev)
446
+ return trailing(prev);
447
+ }
448
+ const cur = this.boxAt.get(index);
449
+ if (cur && cur.Line === line.Line)
450
+ return { X: cur.Rtl ? cur.Left + cur.Width : cur.Left, Rtl: !!cur.Rtl, Top: cur.Top, Height: cur.Height };
451
+ return { X: line.Left, Rtl: false, Top: line.Top, Height: line.Height };
452
+ }
453
+ /** Rect of the caret before character `index` (label pixels), or undefined before the first layout. */
454
+ CaretRectLabelPx(index = this.cursorPosition + this.selectionLength) {
455
+ const place = this.CaretPlace(index);
456
+ if (!place)
457
+ return undefined;
398
458
  const caretW = 2 * this.RenderingScale;
399
- const at = boxes.find((b) => b.Index === index);
400
- if (at)
401
- return SKRect.Create(at.Left, at.Top, caretW, at.Height);
402
- let prev;
403
- for (const b of boxes) {
404
- if (b.Index < index)
405
- prev = b;
406
- else
407
- break;
459
+ return SKRect.Create(place.Rtl ? place.X - caretW : place.X, place.Top, caretW, place.Height);
460
+ }
461
+ /** The grapheme boundary of a line whose caret x is nearest to `x` (a tie: the smaller index). */
462
+ NearestStop(line, x) {
463
+ let best = -1, bestD = Infinity;
464
+ for (const i of this.Stops()) {
465
+ if (i < line.Start || i > line.End)
466
+ continue;
467
+ const d = Math.abs((this.CaretPlace(i)?.X ?? 0) - x);
468
+ if (d < bestD - 0.01) {
469
+ best = i;
470
+ bestD = d;
471
+ }
408
472
  }
409
- if (prev)
410
- return SKRect.Create(prev.Left + prev.Width, prev.Top, caretW, prev.Height);
411
- const first = lines[0];
412
- return SKRect.Create(first.Left, first.Top, caretW, first.Height);
473
+ return best >= 0 ? best : Math.min(line.Start, this.text.length);
413
474
  }
414
475
  /** C# GetCursorPosition: the text index nearest to a point in label pixels. */
415
476
  HitTestIndex(x, y) {
@@ -422,16 +483,54 @@ export class SkiaEditor extends SkiaShape {
422
483
  line = l;
423
484
  break;
424
485
  }
425
- const boxes = this.Boxes().filter((b) => b.Line === line.Line);
426
- if (boxes.length === 0)
427
- return Math.min(line.Start, this.text.length);
428
- if (x <= boxes[0].Left)
429
- return boxes[0].Index;
430
- for (const b of boxes)
431
- if (x < b.Left + b.Width)
432
- return x < b.Left + b.Width / 2 ? b.Index : b.Index + b.Length;
433
- const last = boxes[boxes.length - 1];
434
- return Math.min(last.Index + last.Length, this.text.length);
486
+ return this.NearestStop(line, x);
487
+ }
488
+ /**
489
+ * Left / Right from a caret index: the grapheme boundary on its line whose caret x is nearest that way (equal x: the
490
+ * one logically nearest); at the visual edge of the line one grapheme logically, forward for Right in a
491
+ * left-to-right paragraph and backward in a right-to-left one (Left the other way round).
492
+ */
493
+ VisualTarget(from, dir) {
494
+ const lines = this.Label.GetLineBoxes();
495
+ const stops = this.Stops();
496
+ let line;
497
+ if (lines.length > 0) {
498
+ line = SkiaEditor.LineOf(from, lines);
499
+ const x0 = this.CaretPlace(from)?.X ?? 0;
500
+ let best = -1, bestX = 0;
501
+ for (const i of stops) {
502
+ if (i < line.Start || i > line.End || i === from)
503
+ continue;
504
+ const x = this.CaretPlace(i)?.X ?? 0;
505
+ if ((x - x0) * dir <= 0.01)
506
+ continue;
507
+ if (best < 0 || (x - bestX) * dir < -0.01 || (Math.abs(x - bestX) <= 0.01 && Math.abs(i - from) < Math.abs(best - from))) {
508
+ best = i;
509
+ bestX = x;
510
+ }
511
+ }
512
+ if (best >= 0)
513
+ return best;
514
+ }
515
+ const start = Math.max(this.text.lastIndexOf(ParagraphBreak, from - 1) + 1, 0);
516
+ const end = this.text.indexOf(ParagraphBreak, from);
517
+ const step = SkiaLabel.FirstStrongIsRtl(this.text.slice(start, end < 0 ? undefined : end)) ? -dir : dir;
518
+ let to = from;
519
+ if (step > 0) {
520
+ for (const i of stops)
521
+ if (i > from) {
522
+ to = i;
523
+ break;
524
+ }
525
+ }
526
+ else
527
+ for (let k = stops.length - 1; k >= 0; k--)
528
+ if (stops[k] < from) {
529
+ to = stops[k];
530
+ break;
531
+ }
532
+ // the step only crosses to the next or previous line: inside a mixed line the visual end stays put
533
+ return line && lines.length > 0 && SkiaEditor.LineOf(to, lines) === line ? from : to;
435
534
  }
436
535
  LabelPoint(args, apply, starting = false) {
437
536
  const loc = starting ? args.Event.StartingLocation : apply.MappedLocation;
@@ -451,9 +550,10 @@ export class SkiaEditor extends SkiaShape {
451
550
  const paint = new CK.Paint();
452
551
  paint.setColor(Super.ParseColor(this.SelectionColor));
453
552
  const end = this.cursorPosition + this.selectionLength;
553
+ // every selected character's own visual box: across a direction boundary the highlight can be two blocks
454
554
  for (const b of this.Boxes())
455
- if (b.Index >= this.cursorPosition && b.Index < end)
456
- canvas.drawRect(CK.LTRBRect(lr.Left + b.Left, lr.Top + b.Top, lr.Left + b.Left + Math.max(b.Width, 2), lr.Top + b.Top + b.Height), paint);
555
+ if (b.Index >= this.cursorPosition && b.Index < end && b.Width > 0)
556
+ canvas.drawRect(CK.LTRBRect(lr.Left + b.Left, lr.Top + b.Top, lr.Left + b.Left + b.Width, lr.Top + b.Top + b.Height), paint);
457
557
  paint.delete();
458
558
  canvas.restoreToCount(saved);
459
559
  }
@@ -641,11 +741,11 @@ export class SkiaEditor extends SkiaShape {
641
741
  break;
642
742
  case "ArrowLeft":
643
743
  handled();
644
- this.StubMoveCursor(-1, shift);
744
+ this.MoveVisual(-1, shift);
645
745
  break;
646
746
  case "ArrowRight":
647
747
  handled();
648
- this.StubMoveCursor(1, shift);
748
+ this.MoveVisual(1, shift);
649
749
  break;
650
750
  case "ArrowUp":
651
751
  if (this.IsMultiline) {
@@ -767,6 +867,39 @@ export class SkiaEditor extends SkiaShape {
767
867
  this.selectionMovingEdge = -1;
768
868
  this.OnCursorMoved();
769
869
  }
870
+ /**
871
+ * Arrow Left (-1) / Right (1): visual moves, as native text fields (see VisualTarget). Without Shift a selection
872
+ * collapses to its visually left (Left) or right (Right) edge; with Shift its moving edge moves.
873
+ */
874
+ MoveVisual(dir, extendSelection = false) {
875
+ if (!extendSelection && this.HasSelection) {
876
+ const a = this.cursorPosition, b = this.cursorPosition + this.selectionLength;
877
+ const xa = this.CaretPlace(a)?.X ?? 0, xb = this.CaretPlace(b)?.X ?? 0;
878
+ const to = dir < 0 ? (xa <= xb ? a : b) : (xa >= xb ? a : b);
879
+ this.cursorPosition = to;
880
+ this.selectionLength = 0;
881
+ this.stubSelectionStop = -1;
882
+ this.selectionMovingEdge = -1;
883
+ this.OnCursorMoved();
884
+ return;
885
+ }
886
+ // a selection made by dragging has no moving edge yet: its end moves
887
+ if (extendSelection && this.HasSelection && this.selectionMovingEdge < 0) {
888
+ this.stubSelectionStop = this.cursorPosition;
889
+ this.selectionMovingEdge = this.cursorPosition + this.selectionLength;
890
+ }
891
+ const from = extendSelection && this.HasSelection ? this.selectionMovingEdge : this.cursorPosition;
892
+ if (extendSelection && !this.HasSelection) {
893
+ this.stubSelectionStop = this.cursorPosition;
894
+ this.selectionMovingEdge = this.cursorPosition;
895
+ }
896
+ const to = this.VisualTarget(from, dir);
897
+ if (extendSelection) {
898
+ this.StubMoveCursor(to - this.selectionMovingEdge, true);
899
+ return;
900
+ }
901
+ this.StubMoveCursor(to - this.cursorPosition, false);
902
+ }
770
903
  StubSelectRange(start, length) {
771
904
  const len = this.text.length;
772
905
  const s = Math.max(0, Math.min(len, start)), l = Math.max(0, Math.min(len - s, length));
@@ -10,7 +10,8 @@ export interface GlyphBox {
10
10
  Left: number;
11
11
  Top: number;
12
12
  Width: number;
13
- Height: number;
13
+ Height: number; /** The code point runs right to left (its box is in visual place). */
14
+ Rtl?: boolean;
14
15
  }
15
16
  /** A laid-out line: first text index, box in pixels relative to DrawingRect. */
16
17
  export interface LineBox {
@@ -171,19 +172,19 @@ export declare class SkiaLabel extends SkiaControl {
171
172
  */
172
173
  private LayoutLines;
173
174
  /** 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;
175
+ static FirstStrongIsRtl(text: string): boolean;
176
+ /** The runs of a line cut where its visual run changes; `map` per UTF-16 index of the line text. */
177
+ private SplitByRuns;
177
178
  /**
178
179
  * 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
+ * right-to-left text every run is cut where its bidirectional run changes (Unicode bidirectional algorithm, ICU, the
180
181
  * 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
+ * runs are placed in visual order. Lines without such text are left as they are (plain path).
182
183
  */
183
184
  private ShapeLines;
184
185
  /**
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).
186
+ * Where each run of a line with right-to-left text goes: visual runs left to right; inside a run, pieces (spans, fonts)
187
+ * in logical order, reversed in a right-to-left run.
187
188
  */
188
189
  private static PlaceRuns;
189
190
  private LineHeightPx;
@@ -3,7 +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
+ import { BidiRuns, HasCodePoint, IsRtl, JoinsPrevious, NeedsShaping, Shape } from "../core/Shaping";
7
7
  /**
8
8
  * Mirrors DrawnUi SkiaLabel: multi-line text with word wrapping, MaxLines + tail ellipsis, horizontal /
9
9
  * vertical alignment, LineSpacing / LineHeight, weights and attributes resolved through the font registry,
@@ -505,36 +505,34 @@ export class SkiaLabel extends SkiaControl {
505
505
  }
506
506
  return false;
507
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) {
508
+ /** The runs of a line cut where its visual run changes; `map` per UTF-16 index of the line text. */
509
+ SplitByRuns(runs, map) {
510
510
  const out = [];
511
511
  let at = 0;
512
512
  for (const r of runs) {
513
- const piece = (from, to, level) => {
513
+ const piece = (from, to) => {
514
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 });
515
+ out.push({ ...r, Text: text, Width: from === 0 && to === r.Text.length ? r.Width : this.Advance(r.Font, text), Level: map.Rtl[at + from] ? 1 : 0, Rank: map.Rank[at + from], At: at + from, Shaped: undefined, X: undefined });
516
516
  };
517
- let from = 0, level = levels[at] ?? 0;
517
+ let from = 0;
518
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);
519
+ if (i > 0 && map.Rank[at + i] !== map.Rank[at + from]) {
520
+ piece(from, i);
522
521
  from = i;
523
- level = next;
524
522
  }
525
523
  i += r.Text.codePointAt(i) > 0xFFFF ? 2 : 1;
526
524
  }
527
525
  if (r.Text.length > 0)
528
- piece(from, r.Text.length, level);
526
+ piece(from, r.Text.length);
529
527
  at += r.Text.length;
530
528
  }
531
529
  return out;
532
530
  }
533
531
  /**
534
532
  * 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
533
+ * right-to-left text every run is cut where its bidirectional run changes (Unicode bidirectional algorithm, ICU, the
536
534
  * 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).
535
+ * runs are placed in visual order. Lines without such text are left as they are (plain path).
538
536
  */
539
537
  ShapeLines(lines) {
540
538
  const sp = this.glyphSpacing;
@@ -551,9 +549,9 @@ export class SkiaLabel extends SkiaControl {
551
549
  end++;
552
550
  rtlParagraph = SkiaLabel.FirstStrongIsRtl(lines.slice(li, end).map(lineText).join(""));
553
551
  }
554
- const levels = BidiLevels(lineText(line), rtlParagraph);
555
- if (levels) {
556
- line.Runs = this.SplitByLevel(line.Runs, levels);
552
+ const map = BidiRuns(lineText(line), rtlParagraph);
553
+ if (map) {
554
+ line.Runs = this.SplitByRuns(line.Runs, map);
557
555
  bidi = line.Runs.some((r) => (r.Level ?? 0) > 0);
558
556
  }
559
557
  }
@@ -580,28 +578,16 @@ export class SkiaLabel extends SkiaControl {
580
578
  }
581
579
  }
582
580
  /**
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).
581
+ * Where each run of a line with right-to-left text goes: visual runs left to right; inside a run, pieces (spans, fonts)
582
+ * in logical order, reversed in a right-to-left run.
585
583
  */
586
584
  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
- }
585
+ const order = runs.map((_, i) => i).sort((a, b) => {
586
+ const ra = runs[a], rb = runs[b];
587
+ if ((ra.Rank ?? 0) !== (rb.Rank ?? 0))
588
+ return (ra.Rank ?? 0) - (rb.Rank ?? 0);
589
+ return ((ra.Level ?? 0) % 2 === 1 ? -1 : 1) * ((ra.At ?? 0) - (rb.At ?? 0));
590
+ });
605
591
  let x = 0;
606
592
  for (const k of order) {
607
593
  runs[k].X = x;
@@ -706,19 +692,30 @@ export class SkiaLabel extends SkiaControl {
706
692
  let start = g.text.length ? this.text.indexOf(g.text, cursor) : cursor;
707
693
  if (start < 0)
708
694
  start = cursor;
709
- // right-to-left runs are boxed left to right in logical order (the caret is not placed visually there)
695
+ // boxes in logical order, each at its visual place: a right-to-left run fills from its right edge
710
696
  let x = g.x, index = start;
697
+ const sp = this.glyphSpacing;
711
698
  for (const run of line.Runs) {
712
699
  if (run.X !== undefined)
713
700
  x = g.x + run.X;
714
701
  const cps = Array.from(run.Text);
715
- const widths = run.Shaped ? run.Shaped.Advances.map((a) => a - this.glyphSpacing) : run.Font.getGlyphWidths(run.Font.getGlyphIDs(run.Text, cps.length));
702
+ const widths = run.Shaped ? run.Shaped.Advances.map((a) => a - sp) : run.Font.getGlyphWidths(run.Font.getGlyphIDs(run.Text, cps.length));
703
+ const rtl = (run.Level ?? 0) % 2 === 1;
704
+ let right = x + run.Width - sp;
716
705
  cps.forEach((cp, k) => {
717
706
  const w = widths[k] ?? 0;
718
- out.push({ Index: index, Length: cp.length, Line: li, Left: x, Top: g.y, Width: w, Height: g.h });
719
- x += w + this.glyphSpacing;
707
+ if (rtl) {
708
+ out.push({ Index: index, Length: cp.length, Line: li, Left: right - w, Top: g.y, Width: w, Height: g.h, Rtl: true });
709
+ right -= w + sp;
710
+ }
711
+ else {
712
+ out.push({ Index: index, Length: cp.length, Line: li, Left: x, Top: g.y, Width: w, Height: g.h });
713
+ x += w + sp;
714
+ }
720
715
  index += cp.length;
721
716
  });
717
+ if (rtl)
718
+ x += run.Width;
722
719
  }
723
720
  cursor = start + g.text.length;
724
721
  });
@@ -27,9 +27,14 @@ export interface Shaped {
27
27
  * data): the caller keeps its plain glyphs.
28
28
  */
29
29
  export declare function Shape(font: Font, text: string, rtl: boolean, spacing: number): Shaped | undefined;
30
+ /** The visual runs of a line: for every UTF-16 index, the rank of its run from the left and whether it runs right to left. */
31
+ export interface BidiMap {
32
+ Rank: Int32Array;
33
+ Rtl: Uint8Array;
34
+ }
30
35
  /**
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.
36
+ * Bidirectional runs of a line (Unicode bidirectional algorithm, ICU in CanvasKit), read from the visual order of a
37
+ * paragraph of that line: digits after Arabic in a left-to-right paragraph stay with the Arabic run (level 2), as the
38
+ * algorithm orders them. Undefined when no font was registered for shaping.
34
39
  */
35
- export declare function BidiLevels(text: string, rtlParagraph: boolean): Uint8Array | undefined;
40
+ export declare function BidiRuns(text: string, rtlParagraph: boolean): BidiMap | undefined;
@@ -90,13 +90,15 @@ function ShapeNow(font, family, size, text, rtl, spacing) {
90
90
  if (lines.length === 0)
91
91
  return undefined;
92
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;
93
+ const cpOfByte = [], u16OfCp = [];
94
+ let cps = 0, u16 = 0;
95
95
  for (const ch of text) {
96
96
  const c = ch.codePointAt(0), bytes = c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
97
97
  for (let b = 0; b < bytes; b++)
98
98
  cpOfByte.push(cps);
99
+ u16OfCp.push(u16);
99
100
  cps++;
101
+ u16 += ch.length;
100
102
  }
101
103
  const cpOf = (byte) => cpOfByte[Math.min(byte, cpOfByte.length - 1)] ?? 0;
102
104
  let count = 0;
@@ -119,16 +121,28 @@ function ShapeNow(font, family, size, text, rtl, spacing) {
119
121
  }
120
122
  }
121
123
  }
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
+ // the advance of every grapheme on its first code point (caret boxes): the paragraph's own grapheme bounds, which
125
+ // follow the shaped pen advances (DrawnUi.Rust: HarfBuzz x_advance per cluster)
124
126
  let sum = 0;
125
- for (let g = 0; g < count; g++) {
126
- advances[clusters[g]] += glyphWidths[g];
127
- sum += glyphWidths[g];
127
+ for (let i = 0; i < cps; i++) {
128
+ const info = paragraph.getGlyphInfoAt(u16OfCp[i]);
129
+ if (!info || info.graphemeClusterTextRange.start !== u16OfCp[i])
130
+ continue;
131
+ const b = info.graphemeLayoutBounds;
132
+ advances[i] = b[2] - b[0];
133
+ sum += advances[i];
134
+ }
135
+ if (sum <= 0) {
136
+ // no grapheme bounds: the glyphs' own widths, scaled to the shaped width
137
+ const glyphWidths = font.getGlyphWidths(glyphs);
138
+ for (let g = 0; g < count; g++) {
139
+ advances[clusters[g]] += glyphWidths[g];
140
+ sum += glyphWidths[g];
141
+ }
142
+ if (sum > 0)
143
+ for (let i = 0; i < advances.length; i++)
144
+ advances[i] *= shapedWidth / sum;
128
145
  }
129
- if (sum > 0)
130
- for (let i = 0; i < advances.length; i++)
131
- advances[i] *= shapedWidth / sum;
132
146
  if (spacing !== 0) {
133
147
  // visual order: the spacing of the code points between two clusters goes between them
134
148
  let extra = 0, last = -1;
@@ -149,31 +163,60 @@ function ShapeNow(font, family, size, text, rtl, spacing) {
149
163
  }
150
164
  }
151
165
  /**
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.
166
+ * Bidirectional runs of a line (Unicode bidirectional algorithm, ICU in CanvasKit), read from the visual order of a
167
+ * paragraph of that line: digits after Arabic in a left-to-right paragraph stay with the Arabic run (level 2), as the
168
+ * algorithm orders them. Undefined when no font was registered for shaping.
155
169
  */
156
- export function BidiLevels(text, rtlParagraph) {
170
+ export function BidiRuns(text, rtlParagraph) {
157
171
  const family = Super.AnyShapingFamily();
158
- if (!family)
172
+ if (!family || !text)
159
173
  return undefined;
160
174
  const CK = Super.CK;
161
175
  const paragraph = Paragraph(family, 12, text, rtlParagraph);
162
176
  try {
163
- const levels = new Uint8Array(text.length);
164
- let level = rtlParagraph ? 1 : 0;
177
+ // UTF-16 index of every UTF-8 byte offset (the shaped runs report clusters in UTF-8)
178
+ const u16OfByte = [];
179
+ let u = 0;
180
+ for (const ch of text) {
181
+ const c = ch.codePointAt(0), bytes = c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
182
+ for (let k = 0; k < bytes; k++)
183
+ u16OfByte.push(u);
184
+ u += ch.length;
185
+ }
186
+ u16OfByte.push(u);
187
+ // every cluster start with the rank of its run; runs come left to right
188
+ const starts = [];
189
+ const firstOfRank = [];
190
+ let rank = 0;
191
+ for (const l of paragraph.getShapedLines()) {
192
+ for (const r of l.runs) {
193
+ let first = Infinity;
194
+ for (let g = 0; g < r.glyphs.length; g++) {
195
+ const at = u16OfByte[Math.min(r.offsets[g], u16OfByte.length - 1)];
196
+ starts.push({ At: at, Rank: rank });
197
+ first = Math.min(first, at);
198
+ }
199
+ firstOfRank.push(first);
200
+ rank++;
201
+ }
202
+ }
203
+ if (starts.length === 0)
204
+ return undefined;
205
+ starts.sort((x, y) => x.At - y.At);
206
+ const map = { Rank: new Int32Array(text.length), Rtl: new Uint8Array(text.length) };
207
+ let k = 0, current = starts[0].Rank;
165
208
  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;
209
+ while (k < starts.length && starts[k].At <= i)
210
+ current = starts[k++].Rank;
211
+ map.Rank[i] = current;
175
212
  }
176
- return levels;
213
+ const rtlOfRank = firstOfRank.map((at) => {
214
+ const info = Number.isFinite(at) ? paragraph.getGlyphInfoAt(at) : null;
215
+ return info ? info.dir.value === CK.TextDirection.RTL.value : rtlParagraph;
216
+ });
217
+ for (let i = 0; i < text.length; i++)
218
+ map.Rtl[i] = rtlOfRank[map.Rank[i]] ? 1 : 0;
219
+ return map;
177
220
  }
178
221
  finally {
179
222
  paragraph.delete();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "drawnui-react",
3
- "version": "0.1.0-preview.28",
3
+ "version": "0.1.0-preview.29",
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)",
@@ -86,6 +86,7 @@
86
86
  "check:carousel-swipe": "node dev/check.mjs dev/check-carousel-swipe.ts",
87
87
  "check:editor-focus": "node dev/check.mjs dev/check-editor-focus.ts",
88
88
  "check:shaping": "node dev/check.mjs dev/check-shaping.ts",
89
+ "check:editor-rtl": "node dev/check.mjs dev/check-editor-rtl.ts",
89
90
  "site:extras": "node dev/site-extras.mjs dist/demo",
90
91
  "build:lib": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\" && tsc -p tsconfig.build.json",
91
92
  "prepublishOnly": "npm run build:lib",