drawnui-react 0.1.0-preview.27 → 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 +3 -0
- package/SKIPPED.md +3 -3
- package/dist/controls/SkiaEditor.d.ts +24 -0
- package/dist/controls/SkiaEditor.js +163 -30
- package/dist/controls/SkiaLabel.d.ts +22 -2
- package/dist/controls/SkiaLabel.js +145 -9
- package/dist/controls/SkiaRichLabel.d.ts +1 -1
- package/dist/controls/SkiaRichLabel.js +11 -1
- package/dist/core/Shaping.d.ts +40 -0
- package/dist/core/Shaping.js +224 -0
- package/dist/core/Super.d.ts +15 -2
- package/dist/core/Super.js +30 -2
- package/package.json +3 -1
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,12 +19,12 @@ 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. |
|
|
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 ``** = 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 ``** = 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
|
|
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
|
-
|
|
393
|
-
|
|
394
|
-
|
|
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
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
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
|
-
|
|
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
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
const
|
|
434
|
-
|
|
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 +
|
|
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.
|
|
744
|
+
this.MoveVisual(-1, shift);
|
|
645
745
|
break;
|
|
646
746
|
case "ArrowRight":
|
|
647
747
|
handled();
|
|
648
|
-
this.
|
|
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 {
|
|
@@ -119,6 +120,8 @@ export declare class SkiaLabel extends SkiaControl {
|
|
|
119
120
|
/** The label's own style, and the base every span inherits from. */
|
|
120
121
|
private ResolveMainFonts;
|
|
121
122
|
private ResolveSpanFonts;
|
|
123
|
+
private static NeedsShapingOrRtl;
|
|
124
|
+
/** Width of a text in one font: the shaped glyphs where the text needs shaping (Arabic joins, emoji sequences), else glyph by glyph. */
|
|
122
125
|
private Advance;
|
|
123
126
|
private static readonly Ignorable;
|
|
124
127
|
/**
|
|
@@ -129,7 +132,8 @@ export declare class SkiaLabel extends SkiaControl {
|
|
|
129
132
|
private static DropIgnorables;
|
|
130
133
|
/**
|
|
131
134
|
* 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).
|
|
135
|
+
* main font has glyph 0. Spaces always stay on the main font (fallback faces often carry very wide spaces). A joiner,
|
|
136
|
+
* a variation selector, a skin tone or a tag keeps the font of the glyph before it: an emoji sequence is one run.
|
|
133
137
|
*/
|
|
134
138
|
private Segment;
|
|
135
139
|
private Width;
|
|
@@ -167,6 +171,22 @@ export declare class SkiaLabel extends SkiaControl {
|
|
|
167
171
|
* text cuts it, not only MaxLines).
|
|
168
172
|
*/
|
|
169
173
|
private LayoutLines;
|
|
174
|
+
/** A paragraph is right to left when its first strong letter is (DrawnUi.Rust split_bidi). */
|
|
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;
|
|
178
|
+
/**
|
|
179
|
+
* After the layout, lines whose text needs shaping or runs right to left (DrawnUi.Rust build_blobs): with
|
|
180
|
+
* right-to-left text every run is cut where its bidirectional run changes (Unicode bidirectional algorithm, ICU, the
|
|
181
|
+
* paragraph direction from its first strong letter); runs that are right to left or need shaping get shaped glyphs;
|
|
182
|
+
* runs are placed in visual order. Lines without such text are left as they are (plain path).
|
|
183
|
+
*/
|
|
184
|
+
private ShapeLines;
|
|
185
|
+
/**
|
|
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.
|
|
188
|
+
*/
|
|
189
|
+
private static PlaceRuns;
|
|
170
190
|
private LineHeightPx;
|
|
171
191
|
/** ParagraphSpacing above a line that starts a paragraph (after the first): that many of its lines, with their spacing. */
|
|
172
192
|
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 { BidiRuns, 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
|
|
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].
|
|
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
|
-
|
|
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,106 @@ 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 its visual run changes; `map` per UTF-16 index of the line text. */
|
|
509
|
+
SplitByRuns(runs, map) {
|
|
510
|
+
const out = [];
|
|
511
|
+
let at = 0;
|
|
512
|
+
for (const r of runs) {
|
|
513
|
+
const piece = (from, to) => {
|
|
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: map.Rtl[at + from] ? 1 : 0, Rank: map.Rank[at + from], At: at + from, Shaped: undefined, X: undefined });
|
|
516
|
+
};
|
|
517
|
+
let from = 0;
|
|
518
|
+
for (let i = 0; i < r.Text.length;) {
|
|
519
|
+
if (i > 0 && map.Rank[at + i] !== map.Rank[at + from]) {
|
|
520
|
+
piece(from, i);
|
|
521
|
+
from = i;
|
|
522
|
+
}
|
|
523
|
+
i += r.Text.codePointAt(i) > 0xFFFF ? 2 : 1;
|
|
524
|
+
}
|
|
525
|
+
if (r.Text.length > 0)
|
|
526
|
+
piece(from, r.Text.length);
|
|
527
|
+
at += r.Text.length;
|
|
528
|
+
}
|
|
529
|
+
return out;
|
|
530
|
+
}
|
|
531
|
+
/**
|
|
532
|
+
* After the layout, lines whose text needs shaping or runs right to left (DrawnUi.Rust build_blobs): with
|
|
533
|
+
* right-to-left text every run is cut where its bidirectional run changes (Unicode bidirectional algorithm, ICU, the
|
|
534
|
+
* paragraph direction from its first strong letter); runs that are right to left or need shaping get shaped glyphs;
|
|
535
|
+
* runs are placed in visual order. Lines without such text are left as they are (plain path).
|
|
536
|
+
*/
|
|
537
|
+
ShapeLines(lines) {
|
|
538
|
+
const sp = this.glyphSpacing;
|
|
539
|
+
const lineText = (l) => l.Runs.map((r) => r.Text).join("");
|
|
540
|
+
const anyRtl = lines.some((l) => l.Runs.some((r) => HasCodePoint(r.Text, IsRtl)));
|
|
541
|
+
let rtlParagraph = false;
|
|
542
|
+
for (let li = 0; li < lines.length; li++) {
|
|
543
|
+
const line = lines[li];
|
|
544
|
+
let bidi = false;
|
|
545
|
+
if (anyRtl) {
|
|
546
|
+
if (li === 0 || line.Para) {
|
|
547
|
+
let end = li + 1;
|
|
548
|
+
while (end < lines.length && !lines[end].Para)
|
|
549
|
+
end++;
|
|
550
|
+
rtlParagraph = SkiaLabel.FirstStrongIsRtl(lines.slice(li, end).map(lineText).join(""));
|
|
551
|
+
}
|
|
552
|
+
const map = BidiRuns(lineText(line), rtlParagraph);
|
|
553
|
+
if (map) {
|
|
554
|
+
line.Runs = this.SplitByRuns(line.Runs, map);
|
|
555
|
+
bidi = line.Runs.some((r) => (r.Level ?? 0) > 0);
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
let shaped = false;
|
|
559
|
+
for (const run of line.Runs) {
|
|
560
|
+
const rtl = (run.Level ?? 0) % 2 === 1;
|
|
561
|
+
if (!rtl && !HasCodePoint(run.Text, NeedsShaping))
|
|
562
|
+
continue;
|
|
563
|
+
const s = Shape(run.Font, run.Text, rtl, sp);
|
|
564
|
+
if (s) {
|
|
565
|
+
run.Shaped = s;
|
|
566
|
+
run.Width = s.Width;
|
|
567
|
+
shaped = true;
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
if (!shaped && !bidi)
|
|
571
|
+
continue;
|
|
572
|
+
let width = 0;
|
|
573
|
+
for (const run of line.Runs)
|
|
574
|
+
width += run.Width;
|
|
575
|
+
line.Width = line.Runs.length > 0 ? width - sp : 0;
|
|
576
|
+
if (bidi)
|
|
577
|
+
SkiaLabel.PlaceRuns(line.Runs);
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
/**
|
|
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.
|
|
583
|
+
*/
|
|
584
|
+
static PlaceRuns(runs) {
|
|
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
|
+
});
|
|
591
|
+
let x = 0;
|
|
592
|
+
for (const k of order) {
|
|
593
|
+
runs[k].X = x;
|
|
594
|
+
x += runs[k].Width;
|
|
595
|
+
}
|
|
596
|
+
}
|
|
484
597
|
LineHeightPx(line) { return (line.Ascent + line.Descent) * this.lineHeight; }
|
|
485
598
|
/** ParagraphSpacing above a line that starts a paragraph (after the first): that many of its lines, with their spacing. */
|
|
486
599
|
ParagraphSpace(line) { return line.Para && this.paragraphSpacing ? this.LineHeightPx(line) * this.lineSpacing * this.paragraphSpacing : 0; }
|
|
@@ -502,6 +615,7 @@ export class SkiaLabel extends SkiaControl {
|
|
|
502
615
|
const px = this.padding.HorizontalThickness * scale, py = this.padding.VerticalThickness * scale;
|
|
503
616
|
const extraH = this.EffectsExtra(scale).H;
|
|
504
617
|
this.lines = this.text || this.Spans.length > 0 ? this.LayoutLines(widthConstraint - px, scale, heightConstraint - py - extraH) : [];
|
|
618
|
+
this.ShapeLines(this.lines);
|
|
505
619
|
let width = 0;
|
|
506
620
|
for (const l of this.lines)
|
|
507
621
|
width = Math.max(width, l.Width);
|
|
@@ -578,16 +692,30 @@ export class SkiaLabel extends SkiaControl {
|
|
|
578
692
|
let start = g.text.length ? this.text.indexOf(g.text, cursor) : cursor;
|
|
579
693
|
if (start < 0)
|
|
580
694
|
start = cursor;
|
|
695
|
+
// boxes in logical order, each at its visual place: a right-to-left run fills from its right edge
|
|
581
696
|
let x = g.x, index = start;
|
|
697
|
+
const sp = this.glyphSpacing;
|
|
582
698
|
for (const run of line.Runs) {
|
|
699
|
+
if (run.X !== undefined)
|
|
700
|
+
x = g.x + run.X;
|
|
583
701
|
const cps = Array.from(run.Text);
|
|
584
|
-
const widths = 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;
|
|
585
705
|
cps.forEach((cp, k) => {
|
|
586
706
|
const w = widths[k] ?? 0;
|
|
587
|
-
|
|
588
|
-
|
|
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
|
+
}
|
|
589
715
|
index += cp.length;
|
|
590
716
|
});
|
|
717
|
+
if (rtl)
|
|
718
|
+
x += run.Width;
|
|
591
719
|
}
|
|
592
720
|
cursor = start + g.text.length;
|
|
593
721
|
});
|
|
@@ -670,6 +798,10 @@ export class SkiaLabel extends SkiaControl {
|
|
|
670
798
|
const sp = this.glyphSpacing;
|
|
671
799
|
// spaced text: every glyph placed with the gap after it (C# MeasureLineGlyphs positions)
|
|
672
800
|
const drawRun = (run, rx, ry, paint) => {
|
|
801
|
+
if (run.Shaped) {
|
|
802
|
+
canvas.drawGlyphs(run.Shaped.Glyphs, run.Shaped.Positions, rx, ry, run.Font, paint);
|
|
803
|
+
return;
|
|
804
|
+
}
|
|
673
805
|
if (sp === 0) {
|
|
674
806
|
canvas.drawText(run.Text, rx, ry, paint, run.Font);
|
|
675
807
|
return;
|
|
@@ -699,7 +831,11 @@ export class SkiaLabel extends SkiaControl {
|
|
|
699
831
|
const gradientRect = gradient ? (this.GradientByLines ? new SKRect(x, y, x + line.Width, y + lh) : textRect) : undefined;
|
|
700
832
|
if (strokePaint && this.StrokeGradient)
|
|
701
833
|
this.SetupGradient(strokePaint, this.StrokeGradient, gradientRect ?? new SKRect(x, y, x + line.Width, y + lh));
|
|
834
|
+
const lineX = x;
|
|
702
835
|
for (const run of line.Runs) {
|
|
836
|
+
// a line with right-to-left text places its runs in visual order
|
|
837
|
+
if (run.X !== undefined)
|
|
838
|
+
x = lineX + run.X;
|
|
703
839
|
const span = run.Span;
|
|
704
840
|
const drawnW = run.Width - sp; // the gap after the run's last glyph is not part of it
|
|
705
841
|
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,40 @@
|
|
|
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
|
+
/** 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
|
+
}
|
|
35
|
+
/**
|
|
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.
|
|
39
|
+
*/
|
|
40
|
+
export declare function BidiRuns(text: string, rtlParagraph: boolean): BidiMap | undefined;
|
|
@@ -0,0 +1,224 @@
|
|
|
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 = [], u16OfCp = [];
|
|
94
|
+
let cps = 0, u16 = 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
|
+
u16OfCp.push(u16);
|
|
100
|
+
cps++;
|
|
101
|
+
u16 += ch.length;
|
|
102
|
+
}
|
|
103
|
+
const cpOf = (byte) => cpOfByte[Math.min(byte, cpOfByte.length - 1)] ?? 0;
|
|
104
|
+
let count = 0;
|
|
105
|
+
for (const l of lines)
|
|
106
|
+
for (const r of l.runs)
|
|
107
|
+
count += r.glyphs.length;
|
|
108
|
+
const glyphs = new Uint16Array(count), positions = new Float32Array(count * 2), advances = new Array(cps).fill(0), clusters = new Array(count);
|
|
109
|
+
// one line (no width limit, no line breaks in a run); runs come in visual order. Glyph positions include their
|
|
110
|
+
// offsets (a mark sits off its pen position), so the run's left edge and width come from the paragraph itself.
|
|
111
|
+
const shapedWidth = paragraph.getMaxIntrinsicWidth();
|
|
112
|
+
const left = rtl ? LayoutWidth - shapedWidth : 0;
|
|
113
|
+
let k = 0;
|
|
114
|
+
for (const l of lines) {
|
|
115
|
+
for (const r of l.runs) {
|
|
116
|
+
for (let g = 0; g < r.glyphs.length; g++, k++) {
|
|
117
|
+
glyphs[k] = r.glyphs[g];
|
|
118
|
+
positions[k * 2] = r.positions[g * 2] - left;
|
|
119
|
+
positions[k * 2 + 1] = r.positions[g * 2 + 1] - l.baseline;
|
|
120
|
+
clusters[k] = cpOf(r.offsets[g]);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
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)
|
|
126
|
+
let sum = 0;
|
|
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;
|
|
145
|
+
}
|
|
146
|
+
if (spacing !== 0) {
|
|
147
|
+
// visual order: the spacing of the code points between two clusters goes between them
|
|
148
|
+
let extra = 0, last = -1;
|
|
149
|
+
for (let g = 0; g < count; g++) {
|
|
150
|
+
if (last >= 0 && last !== clusters[g])
|
|
151
|
+
extra += spacing * Math.abs(last - clusters[g]);
|
|
152
|
+
last = clusters[g];
|
|
153
|
+
positions[g * 2] += extra;
|
|
154
|
+
}
|
|
155
|
+
for (let i = 0; i < advances.length; i++)
|
|
156
|
+
advances[i] += spacing;
|
|
157
|
+
}
|
|
158
|
+
const width = shapedWidth + spacing * cps;
|
|
159
|
+
return { Glyphs: glyphs, Positions: positions, Advances: advances, Width: width };
|
|
160
|
+
}
|
|
161
|
+
finally {
|
|
162
|
+
paragraph.delete();
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
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.
|
|
169
|
+
*/
|
|
170
|
+
export function BidiRuns(text, rtlParagraph) {
|
|
171
|
+
const family = Super.AnyShapingFamily();
|
|
172
|
+
if (!family || !text)
|
|
173
|
+
return undefined;
|
|
174
|
+
const CK = Super.CK;
|
|
175
|
+
const paragraph = Paragraph(family, 12, text, rtlParagraph);
|
|
176
|
+
try {
|
|
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;
|
|
208
|
+
for (let i = 0; i < text.length; i++) {
|
|
209
|
+
while (k < starts.length && starts[k].At <= i)
|
|
210
|
+
current = starts[k++].Rank;
|
|
211
|
+
map.Rank[i] = current;
|
|
212
|
+
}
|
|
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;
|
|
220
|
+
}
|
|
221
|
+
finally {
|
|
222
|
+
paragraph.delete();
|
|
223
|
+
}
|
|
224
|
+
}
|
package/dist/core/Super.d.ts
CHANGED
|
@@ -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
|
|
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;
|
package/dist/core/Super.js
CHANGED
|
@@ -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
|
|
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.
|
|
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.
|
|
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)",
|
|
@@ -85,6 +85,8 @@
|
|
|
85
85
|
"check:masonry-keys": "node dev/check.mjs dev/check-masonry-keys.ts",
|
|
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
|
+
"check:shaping": "node dev/check.mjs dev/check-shaping.ts",
|
|
89
|
+
"check:editor-rtl": "node dev/check.mjs dev/check-editor-rtl.ts",
|
|
88
90
|
"site:extras": "node dev/site-extras.mjs dist/demo",
|
|
89
91
|
"build:lib": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\" && tsc -p tsconfig.build.json",
|
|
90
92
|
"prepublishOnly": "npm run build:lib",
|