Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
<native:lazy-stack class="w-full flex-1 gap-2" content-padding="16 0">
@foreach ($events as $event)
<native:list-item :key="$event->id" :headline="$event->title" />
@endforeach
</native:lazy-stack>
```

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

`<native:popover>` floats its children in a small bubble beside the spot it
Expand Down
8 changes: 8 additions & 0 deletions nativephp.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
73 changes: 73 additions & 0 deletions resources/ios/NativeUILazyStackRenderer.swift
Original file line number Diff line number Diff line change
@@ -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
}
}
13 changes: 13 additions & 0 deletions src/Components/LazyStack.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

namespace Native\Mobile\UI\Components;

use Native\Mobile\Edge\Components\Native\NativeBladeComponent;

class LazyStack extends NativeBladeComponent
{
protected function elementType(): string
{
return 'lazy_stack';
}
}
96 changes: 96 additions & 0 deletions src/Elements/LazyStack.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
<?php

namespace Native\Mobile\UI\Elements;

use Native\Mobile\Edge\CallbackRegistry;
use Native\Mobile\Edge\Element;

/**
* A vertical scroll of children drawn lazily, for long feeds that change
* often (a live log, a chat, a firehose of events). Only the children on
* screen and near it are built.
*
* Unlike {@see NativeList}, it has no separators, swipe actions,
* pull-to-refresh, sections or row callbacks: each child draws itself. In
* return a stack that has taken thousands of inserts updates as fast as a
* fresh one, where a list gets slower with every insert.
*
* Give each child a stable `key`. A child added above the screen then
* doesn't move what's on it, and a reader at the very top sees it come in.
*
* <native:lazy-stack class="w-full flex-1 gap-2" :content-padding="16">
* @foreach ($events as $event)
* <native:list-item :key="$event->id" :headline="$event->title" />
* @endforeach
* </native:lazy-stack>
*
* `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;
}
}
86 changes: 86 additions & 0 deletions tests/LazyStackTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
<?php

use Native\Mobile\Edge\CallbackRegistry;
use Native\Mobile\Edge\ElementRegistry;
use Native\Mobile\Edge\Elements\Text;
use Native\Mobile\Edge\NativeElementCollector;
use Native\Mobile\Edge\TailwindParser;
use Native\Mobile\UI\Components\LazyStack as LazyStackComponent;
use Native\Mobile\UI\Elements\LazyStack;

/**
* `native:lazy-stack`: a vertical scroll of keyed children drawn lazily.
*/
beforeEach(function () {
NativeElementCollector::reset();
TailwindParser::clearCache();
ElementRegistry::reset();
ElementRegistry::register('text', Text::class);
ElementRegistry::register('lazy_stack', LazyStack::class);
});

afterEach(function () {
NativeElementCollector::reset();
ElementRegistry::reset();
});

it('collects its children in order, with gap and padding from classes', function () {
NativeElementCollector::open('lazy_stack', ['class' => '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,
]);
});
Loading