From c86e5ab7b19122826f1026338df2ab349d7ea645 Mon Sep 17 00:00:00 2001 From: Simon Hamp Date: Sun, 15 Nov 2026 15:10:29 +0000 Subject: [PATCH] Add native:lazy-stack, a lazily drawn vertical scroll A new element for long feeds that change often. On iOS it is a ScrollView with a LazyVStack, and each child is identified by its node id. native:list is a SwiftUI List, and a List gets slower with every row inserted into it. In the heimdall firehose (60 keyed inserts a second, capped at 1,000 rows) a List update cost about 10 ms after 100 inserts and 250 to 600 ms once full. The same rows in a lazy stack stayed at about 5.5 ms of main-thread time per update and 60 fps through 3,600 inserts on the simulator. It is deliberately small: children, gap-* spacing, the usual padding and background, a content-padding attribute that pads the scrolled content, and shows-indicators. No separators, swipe actions, pull-to-refresh, sections or row callbacks. native:list is unchanged. A child added above the screen doesn't move what the reader is looking at: scrollPosition keeps the top child in place. A reader at the very top is scrolled back to the top so new children show. Android has no renderer of its own yet. The manifest points it at the scroll view's renderer, which ignores content-padding. Co-Authored-By: Claude Opus 5.5 --- README.md | 18 ++++ nativephp.json | 8 ++ resources/ios/NativeUILazyStackRenderer.swift | 73 ++++++++++++++ src/Components/LazyStack.php | 13 +++ src/Elements/LazyStack.php | 96 +++++++++++++++++++ tests/LazyStackTest.php | 86 +++++++++++++++++ 6 files changed, 294 insertions(+) create mode 100644 resources/ios/NativeUILazyStackRenderer.swift create mode 100644 src/Components/LazyStack.php create mode 100644 src/Elements/LazyStack.php create mode 100644 tests/LazyStackTest.php diff --git a/README.md b/README.md index de5f10a..c6c94e0 100644 --- a/README.md +++ b/README.md @@ -158,6 +158,24 @@ use Native\Mobile\UI\Elements\StickyHeader; StickyHeader::make($newPostsButton); ``` +## Lazy stacks + +`native:lazy-stack` is a vertical scroll that only builds the children on screen and near it. Use it for long feeds that change often, such as a live log or a chat. A SwiftUI `List` gets slower with every row inserted into it, so a `native:list` taking 60 inserts a second fell well below 60 fps once it had a few hundred. A lazy stack held 60 fps through 3,600 inserts on the iOS simulator. + +```blade + + @foreach ($events as $event) + + @endforeach + +``` + +It has none of a list's extras: no separators, swipe actions, pull-to-refresh, sections or row callbacks. Each child draws itself. `gap-*` spaces the children, `p-*` pads the stack's frame and `content-padding` pads the scrolled content, taking one to four values like CSS `padding`. + +Give each child a stable `key`. A child added above the screen then doesn't move what the reader is looking at, and a reader at the very top sees new children come in. + +It's iOS only for now. On Android it falls back to the `native:scroll-view` renderer, which ignores `content-padding`. + ## Popovers `` floats its children in a small bubble beside the spot it diff --git a/nativephp.json b/nativephp.json index d494125..4e277dc 100644 --- a/nativephp.json +++ b/nativephp.json @@ -221,6 +221,14 @@ "ios_renderer": "NativeUIVirtualListRenderer", "self_closing": true }, + { + "type": "lazy_stack", + "element": "Native\\Mobile\\UI\\Elements\\LazyStack", + "blade": "Native\\Mobile\\UI\\Components\\LazyStack", + "android_renderer": "com.nativephp.plugins.native_ui.ui.ScrollViewRenderer", + "ios_renderer": "NativeUILazyStackRenderer", + "self_closing": false + }, { "type": "modal", "element": "Native\\Mobile\\UI\\Elements\\Modal", diff --git a/resources/ios/NativeUILazyStackRenderer.swift b/resources/ios/NativeUILazyStackRenderer.swift new file mode 100644 index 0000000..26f935a --- /dev/null +++ b/resources/ios/NativeUILazyStackRenderer.swift @@ -0,0 +1,73 @@ +import SwiftUI + +/// `native:lazy-stack`: a vertical scroll of children drawn lazily, in a +/// ScrollView with a LazyVStack, each child identified by its node id. +/// +/// It's for long feeds that change often. `native:list` is a SwiftUI `List`, +/// which got slower with every row inserted into it: at 60 inserts a second +/// an update cost about 10 ms after 100 inserts and 250 to 600 ms once the +/// list was full at 1,000 rows. The same rows here stayed at about 5 ms an +/// update through 3,600 inserts. +/// +/// It does less than a list on purpose: no separators, swipe actions, +/// pull-to-refresh, sections or row callbacks. Rows draw themselves. +/// +/// - Spacing between children is the node's `gap-*`. +/// - `p-*` pads the stack's frame, like any element. `content_padding_*` +/// pads the scrolled content instead, so the first and last child can sit +/// clear of the edges and still scroll under them. +/// - A child added above the screen doesn't move what's on it: the stack +/// keeps the top child on screen where it was. A reader at the very top +/// stays at the top and sees new children come in. +struct NativeUILazyStackRenderer: View { + let node: NativeUINode + + /// The child the stack keeps in place when children are added above it. + @State private var position = ScrollPosition(idType: Int.self) + + /// Whether the reader is at the very top, where children added above + /// should show rather than be kept off screen. + @State private var atTop = true + + var body: some View { + let children = node.children + let spacing = CGFloat(node.layout?.gap ?? 0) + let showsIndicators = node.props.getBool("shows_indicators", default: true) + let contentPadding = EdgeInsets( + top: CGFloat(node.props.getFloat("content_padding_top", default: 0)), + leading: CGFloat(node.props.getFloat("content_padding_left", default: 0)), + bottom: CGFloat(node.props.getFloat("content_padding_bottom", default: 0)), + trailing: CGFloat(node.props.getFloat("content_padding_right", default: 0)) + ) + + ScrollView(.vertical, showsIndicators: showsIndicators) { + LazyVStack(alignment: .leading, spacing: spacing) { + ForEach(children) { child in + NodeView(node: child) + .equatable() + .frame(maxWidth: .infinity, alignment: .leading) + } + } + // The children are what the scroll position is kept by. + .scrollTargetLayout() + .padding(contentPadding) + } + .scrollPosition($position, anchor: .top) + .onScrollGeometryChange(for: Bool.self, of: Self.isAtTop) { _, isAtTop in + atTop = isAtTop + } + .onChange(of: children.first?.id) { _, _ in + // The scroll position keeps the child that was at the top in + // place, which at the very top would hide what was just added. + guard atTop else { return } + position.scrollTo(edge: .top) + } + .scrollDismissesKeyboard(.interactively) + .modifier(ScrollViewBackgroundModifier(node: node)) + } + + /// Built from the geometry alone, so it captures nothing of the stack. + private static func isAtTop(_ geometry: ScrollGeometry) -> Bool { + geometry.contentOffset.y + geometry.contentInsets.top <= 1 + } +} diff --git a/src/Components/LazyStack.php b/src/Components/LazyStack.php new file mode 100644 index 0000000..4be8f10 --- /dev/null +++ b/src/Components/LazyStack.php @@ -0,0 +1,13 @@ + + * @foreach ($events as $event) + * + * @endforeach + * + * + * `gap-*` spaces the children. `p-*` pads the stack's frame, like any + * element; {@see contentPadding()} (the `content-padding` attribute, which + * a server screen sends as `contentPadding`) pads the scrolled content. + * + * iOS only for now. Android draws it with the scroll view's renderer, which + * ignores the content padding. + */ +class LazyStack extends Element +{ + protected string $type = 'lazy_stack'; + + protected array $stackProps = []; + + public static function make(Element ...$children): static + { + $el = new static; + $el->children = $children; + + return $el; + } + + public function applyAttributes(array $attrs): void + { + if (isset($attrs['showsIndicators']) || isset($attrs['shows-indicators'])) { + $this->showsIndicators((bool) ($attrs['showsIndicators'] ?? $attrs['shows-indicators'])); + } + + $padding = $attrs['content-padding'] ?? $attrs['contentPadding'] ?? null; + if ($padding !== null && $padding !== '') { + $values = is_array($padding) + ? array_values($padding) + : preg_split('/[\s,]+/', trim((string) $padding)); + $this->contentPadding(...array_map('floatval', array_slice($values, 0, 4))); + } + + $this->applyA11yAttributes($attrs); + } + + public function showsIndicators(bool $value = true): static + { + $this->stackProps['shows_indicators'] = $value; + + return $this; + } + + /** + * Pad the scrolled content, in points, the way CSS `padding` takes one to + * four values: all sides, vertical and horizontal, top, horizontal and + * bottom, or top, right, bottom and left. The first and last child sit + * this far from the ends and the content scrolls through the padding. + */ + public function contentPadding(float $top, ?float $right = null, ?float $bottom = null, ?float $left = null): static + { + $right ??= $top; + $bottom ??= $top; + $left ??= $right; + + $this->stackProps['content_padding_top'] = $top; + $this->stackProps['content_padding_right'] = $right; + $this->stackProps['content_padding_bottom'] = $bottom; + $this->stackProps['content_padding_left'] = $left; + + return $this; + } + + protected function resolveProps(CallbackRegistry $registry): array + { + return $this->stackProps; + } +} diff --git a/tests/LazyStackTest.php b/tests/LazyStackTest.php new file mode 100644 index 0000000..2c310a0 --- /dev/null +++ b/tests/LazyStackTest.php @@ -0,0 +1,86 @@ + 'w-full flex-1 gap-2 p-4 bg-white']); + NativeElementCollector::leaf('text', ['text' => 'One']); + NativeElementCollector::leaf('text', ['text' => 'Two']); + NativeElementCollector::close(); + + $tree = NativeElementCollector::collect()->toArray(new CallbackRegistry); + + expect($tree['type'])->toBe('lazy_stack') + ->and(array_column($tree['children'], 'type'))->toBe(['text', 'text']) + ->and($tree['layout'])->toMatchArray(['gap' => 8.0, 'padding' => 16.0]) + ->and($tree['style']['bg_color'])->toBe('#FFFFFF'); +}); + +it('takes content padding the way CSS padding takes values', function (mixed $value, array $expected) { + NativeElementCollector::open('lazy_stack', ['content-padding' => $value]); + NativeElementCollector::close(); + + $props = NativeElementCollector::collect()->toArray(new CallbackRegistry)['props']; + + expect([ + $props['content_padding_top'], $props['content_padding_right'], + $props['content_padding_bottom'], $props['content_padding_left'], + ])->toBe($expected); +})->with([ + 'one value' => [16, [16.0, 16.0, 16.0, 16.0]], + 'two values' => ['8 16', [8.0, 16.0, 8.0, 16.0]], + 'three values' => ['8 16 24', [8.0, 16.0, 24.0, 16.0]], + 'four values' => ['1 2 3 4', [1.0, 2.0, 3.0, 4.0]], +]); + +it('sends no props it was not given', function () { + $stack = LazyStack::make(Text::make('One'))->toArray(new CallbackRegistry); + + expect($stack['type'])->toBe('lazy_stack') + ->and($stack['children'])->toHaveCount(1) + ->and($stack['props'] ?? [])->not->toHaveKey('content_padding_top'); +}); + +it('hides the scroll indicator when asked', function () { + NativeElementCollector::open('lazy_stack', ['shows-indicators' => false]); + NativeElementCollector::close(); + + $props = NativeElementCollector::collect()->toArray(new CallbackRegistry)['props']; + + expect($props['shows_indicators'])->toBeFalse(); +}); + +it('registers a renderer for iOS and falls back to the scroll view on Android', function () { + $manifest = json_decode(file_get_contents(dirname(__DIR__).'/nativephp.json'), true); + $component = collect($manifest['components'])->firstWhere('type', 'lazy_stack'); + + expect($component)->toMatchArray([ + 'element' => LazyStack::class, + 'blade' => LazyStackComponent::class, + 'android_renderer' => 'com.nativephp.plugins.native_ui.ui.ScrollViewRenderer', + 'ios_renderer' => 'NativeUILazyStackRenderer', + 'self_closing' => false, + ]); +});