Skip to content
Merged
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
5 changes: 5 additions & 0 deletions android/src/main/cpp/FlumeJni.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,10 @@ struct JFlumeJni : jni::JavaClass<JFlumeJni> {

static void refresh(jni::alias_ref<jclass>, jint storeId) { flume::Engine::instance().refresh(storeId); }

static jboolean applyNow(jni::alias_ref<jclass>, jint storeId) {
return flume::Engine::instance().applyNow(storeId) ? JNI_TRUE : JNI_FALSE;
}

static void setStatsEnabled(jni::alias_ref<jclass>, jboolean enabled) {
flume::Engine::instance().setStatsEnabled(enabled);
}
Expand All @@ -118,6 +122,7 @@ struct JFlumeJni : jni::JavaClass<JFlumeJni> {
makeNativeMethod("releaseHolder", JFlumeJni::releaseHolder),
makeNativeMethod("invalidateMeasures", JFlumeJni::invalidateMeasures),
makeNativeMethod("refresh", JFlumeJni::refresh),
makeNativeMethod("applyNow", JFlumeJni::applyNow),
makeNativeMethod("setStatsEnabled", JFlumeJni::setStatsEnabled),
});
}
Expand Down
3 changes: 3 additions & 0 deletions android/src/main/java/me/sectiontn/flume/FlumeJni.kt
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,9 @@ object FlumeJni {
// Applies data JS deferred until its pre-rendered cells mounted.
@JvmStatic external fun refresh(storeId: Int)

// UI thread: applies deferred data now, in the frame of the mount that brought its cells. False when none was pending.
@JvmStatic external fun applyNow(storeId: Int): Boolean

// Binds read the clock and return stats only while this is on.
@JvmStatic external fun setStatsEnabled(enabled: Boolean)
}
33 changes: 32 additions & 1 deletion android/src/main/java/me/sectiontn/flume/FlumeView.kt
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,14 @@ import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.facebook.react.bridge.ReactContext
import com.facebook.react.bridge.UIManager
import com.facebook.react.bridge.UIManagerListener
import com.facebook.react.common.annotations.UnstableReactNativeAPI
import com.facebook.react.uimanager.StateWrapper
import com.facebook.react.uimanager.UIManagerHelper
import com.facebook.react.uimanager.events.Event
import com.facebook.react.uimanager.events.NativeGestureUtil
import com.facebook.react.uimanager.common.UIManagerType
import kotlin.math.roundToInt

class FlumeView(context: Context) : FrameLayout(context) {
Expand Down Expand Up @@ -792,6 +796,7 @@ class FlumeView(context: Context) : FrameLayout(context) {
}

override fun onDetachedFromWindow() {
dropMountListener()
adapter.detach()
super.onDetachedFromWindow()
}
Expand All @@ -805,11 +810,37 @@ class FlumeView(context: Context) : FrameLayout(context) {
}

private val dataRefresh = Runnable { if (storeId != 0) FlumeJni.refresh(storeId) }
Comment thread
SectionTN marked this conversation as resolved.
Resolved
@OptIn(UnstableReactNativeAPI::class) private var mountListener: UIManagerListener? = null

// Data JS deferred for its pre-rendered cells applies after the mount batch that registers them, once they measured.
// Data JS deferred for its pre-rendered cells applies right after the mount batch that registers them, in the frame
// that shows the rows it re-rendered with them. The post only covers a batch Fabric never reports.
@OptIn(UnstableReactNativeAPI::class)
fun refreshData() {
removeCallbacks(dataRefresh)
post(dataRefresh)
if (mountListener != null) return
val uiManager = UIManagerHelper.getUIManager(context as ReactContext, UIManagerType.FABRIC) ?: return
val listener = object : UIManagerListener {
override fun willDispatchViewUpdates(uiManager: UIManager) = Unit
override fun willMountItems(uiManager: UIManager) = Unit
override fun didDispatchMountItems(uiManager: UIManager) = Unit
override fun didScheduleMountItems(uiManager: UIManager) = Unit
// A batch that lands before the deferred data keeps the listener and the posted fallback.
override fun didMountItems(uiManager: UIManager) {
if (storeId == 0 || !FlumeJni.applyNow(storeId)) return
dropMountListener()
removeCallbacks(dataRefresh)
}
}
mountListener = listener
uiManager.addUIManagerEventListener(listener)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

@OptIn(UnstableReactNativeAPI::class)
fun dropMountListener() {
val listener = mountListener ?: return
mountListener = null
UIManagerHelper.getUIManager(context as ReactContext, UIManagerType.FABRIC)?.removeUIManagerEventListener(listener)
}

fun setEstimatedItemSize(dp: Double) {
Expand Down
2 changes: 2 additions & 0 deletions android/src/main/java/me/sectiontn/flume/FlumeViewManager.kt
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ class FlumeViewManager : ViewGroupManager<FlumeView>(), FlumeViewManagerInterfac
}

override fun onDropViewInstance(view: FlumeView) {
// A view dropped while detached registered its mount listener after its own detach cleanup.
view.dropMountListener()
view.setStateWrapper(null)
super.onDropViewInstance(view)
}
Expand Down
24 changes: 16 additions & 8 deletions cpp/bindings/Engine.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -133,17 +133,25 @@ void Engine::scheduleRefresh(const std::shared_ptr<Store>& store, bool always) {
if (scheduler == nullptr) return;
std::weak_ptr<Store> weak = store;
worklets::scheduleOnUI(scheduler, [weak, always] {
auto s = weak.lock();
if (s == nullptr) return;
std::optional<ListOps> ops = s->list.applyPending();
if (s->listener == nullptr || (!ops && !always)) return;
ListOps reset;
reset.reset = true;
reset.sticky = s->list.sticky();
s->listener->onListChanged(always ? reset : *ops, s->list.count());
if (auto s = weak.lock()) applyPending(*s, always);
});
}

bool Engine::applyPending(Store& store, bool always) {
std::optional<ListOps> ops = store.list.applyPending();
if (store.listener == nullptr || (!ops && !always)) return ops.has_value();
ListOps reset;
reset.reset = true;
reset.sticky = store.list.sticky();
store.listener->onListChanged(always ? reset : *ops, store.list.count());
return ops.has_value();
}

bool Engine::applyNow(int storeId) {
auto store = find(storeId);
return store != nullptr && store->list.attached() && applyPending(*store, false);
}

// The JS thread only unregisters. The UI job releases runtime handles under the runtime lock, ~Store the native parts.
void Engine::releaseStore(int storeId) {
std::shared_ptr<worklets::UIScheduler> scheduler;
Expand Down
3 changes: 3 additions & 0 deletions cpp/bindings/Engine.h
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,8 @@ class Engine {
void releaseHolder(int storeId, int holderId);
void invalidateMeasures(int storeId); // clears the text measure cache
void refresh(int storeId); // applies deferred data
// UI thread: applies deferred data now, in the frame of the mount that brought its cells. False when none was pending.
bool applyNow(int storeId);
void setStatsEnabled(bool enabled) { statsEnabled_ = enabled; } // any thread; binds read the clock only while on

private:
Expand All @@ -85,6 +87,7 @@ class Engine {
std::shared_ptr<worklets::UIScheduler> schedulerOf(int session);
std::shared_ptr<const FlumeRuntime> flumeOf(int session);
void scheduleRefresh(const std::shared_ptr<Store>& store, bool always);
static bool applyPending(Store& store, bool always);
void bindOnRuntime(facebook::jsi::Runtime& rt, int index);
void releaseOnRuntime(int storeId);
void logLine(const std::string& message);
Expand Down
27 changes: 27 additions & 0 deletions cpp/tests/jsi/engine_session_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -181,3 +181,30 @@ TEST_CASE("a sticky-only change reaches the listener as empty ops") {
CHECK(listener.calls.back().sticky == std::vector<int>{0, 2});
CHECK(flume::Engine::instance().stickyIndices(id) == std::vector<int>{0, 2});
}

TEST_CASE("deferred data waits for its cells and applyNow applies it at once") {
ReactSide side;
RecordingListener listener;
int id = stickyStore(side, listener);
listener.calls.clear();
side.rig.eval(
"__flume.setData(id, ['a', 'b', 'c', 'd'], ['row'], new Int32Array([0, 0, 0, 0]), [], [], true, true, [1]);");
CHECK(listener.calls.empty());
CHECK(flume::Engine::instance().applyNow(id));
REQUIRE(listener.calls.size() == 1);
CHECK(listener.calls.back().inserted == std::vector<flume::ListOps::Range>{{3, 1}});
CHECK_FALSE(flume::Engine::instance().applyNow(id));
CHECK(listener.calls.size() == 1);
}

TEST_CASE("applyNow before the deferred data arrives reports nothing applied") {
ReactSide side;
RecordingListener listener;
int id = stickyStore(side, listener);
listener.calls.clear();
CHECK_FALSE(flume::Engine::instance().applyNow(id));
side.rig.eval(
"__flume.setData(id, ['a', 'b', 'c', 'd'], ['row'], new Int32Array([0, 0, 0, 0]), [], [], true, true, [1]);");
CHECK(flume::Engine::instance().applyNow(id));
CHECK(listener.calls.size() == 1);
}
15 changes: 15 additions & 0 deletions example/src/screens/ReactScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,9 @@ const Empty = () => (
</View>
);

const Divider = () => <View style={styles.divider} />;
const ChipDivider = () => <View style={styles.chipDivider} />;

export default function ReactScreen() {
const all = useMemo(() => makeReactRows(), []);
const [rows, setRows] = useState(all);
Expand All @@ -140,6 +143,7 @@ export default function ReactScreen() {
const [taps, setTaps] = useState<Taps>('never');
const [refreshing, setRefreshing] = useState(false);
const [pressed, setPressed] = useState('none');
const [separators, setSeparators] = useState(false);
useEffect(() => {
showPressed = setPressed;
return () => {
Expand All @@ -156,6 +160,11 @@ export default function ReactScreen() {
const n = -++prepended.current;
setRows((current) => [{ id: `p${n}`, kind: 'row', title: `Row ${n}`, n }, ...current]);
};
const appended = useRef(0);
const append = () => {
const n = ++appended.current;
setRows((current) => [...current, { id: `a${n}`, kind: 'row', title: `Appended ${n}`, n }]);
};
const refresh = () => {
setRefreshing(true);
setTimeout(() => setRefreshing(false), 1000);
Expand All @@ -172,6 +181,8 @@ export default function ReactScreen() {
[`Mode ${mode}`, () => setMode((value) => (value === 'react' ? 'mixed' : 'react'))],
['Block JS 3 s', () => blockJs(3000)],
['Prepend', prepend],
['Append', append],
[`Separators ${separators ? 'off' : 'on'}`, () => setSeparators((on) => !on)],
['Replace all', () => setRows(makeReactRows(500, `v${++version.current}`))],
['Clear', () => setRows([])],
['Refill', () => setRows(all)],
Expand Down Expand Up @@ -199,6 +210,7 @@ export default function ReactScreen() {
<Flume
data={CHIPS}
renderItem={renderChip}
ItemSeparatorComponent={separators ? ChipDivider : undefined}
horizontal
showsHorizontalScrollIndicator={false}
style={styles.chips}
Expand All @@ -217,6 +229,7 @@ export default function ReactScreen() {
estimatedItemSize={56}
numColumns={columns}
inverted={inverted}
ItemSeparatorComponent={separators ? Divider : undefined}
ListHeaderComponent={Header}
ListFooterComponent={footer}
ListEmptyComponent={Empty}
Expand Down Expand Up @@ -257,6 +270,8 @@ const styles = StyleSheet.create({
section: { height: 48, backgroundColor: '#dde6fb' },
sectionTitle: { flex: 1, fontSize: 15, fontWeight: '700', color: '#1b2a4a' },
chips: { height: 64 },
divider: { height: 1, backgroundColor: '#d0d0d8' },
chipDivider: { width: 1, marginVertical: 20, backgroundColor: '#b0b0b8' },
chip: {
marginVertical: 12,
marginHorizontal: 4,
Expand Down
53 changes: 46 additions & 7 deletions src/Flume.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,14 @@ import {
useRef,
useState,
} from 'react';
import { type StyleProp, View, type ViewStyle } from 'react-native';
import { createSerializable } from 'react-native-worklets';
import { cellKinds, type ResolvedCell, resolveCell } from './cells';
import { type DataState, diffData, itemOf, type NativeItems, typeOf } from './data';
import { FlumeSlot } from './FlumeSlot';
import { hostProps } from './foreign';
import { contentPadding, nativeProps, refreshOf, settleProps, stickyIndicesOf } from './props';
import { lastRowStart } from './separators';
import {
applySnapshot,
gridCellWidth,
Expand All @@ -39,14 +41,24 @@ import FlumeViewNativeComponent, {
} from './specs/FlumeViewNativeComponent';
import { logSetData, statsEnabled } from './stats';
import { getHost, isDev } from './store';
import type { FlumeProps, FlumeRef, PressInfo, ReactCell, ViewToken } from './types';
import type {
FlumeProps,
FlumeRef,
PressInfo,
ReactCell,
SeparatorProps,
ViewToken,
} from './types';

// FlatList's rule for the list components: an element renders as given, a component through createElement.
// A given style wraps it in a View, as FlatList and FlashList do.
function componentElement(
component: ComponentType<object> | ReactElement | null | undefined,
style: StyleProp<ViewStyle> | null | undefined,
): ReactElement | null {
if (component == null) return null;
return isValidElement(component) ? component : createElement(component);
const element = isValidElement(component) ? component : createElement(component);
return style == null ? element : createElement(View, { style }, element);
}

function FlumeInner<T>(given: FlumeProps<T>, ref: Ref<FlumeRef>): ReactElement {
Expand All @@ -66,6 +78,11 @@ function FlumeInner<T>(given: FlumeProps<T>, ref: Ref<FlumeRef>): ReactElement {
ListHeaderComponent,
ListFooterComponent,
ListEmptyComponent,
ListHeaderComponentStyle,
ListFooterComponentStyle,
ListEmptyComponentStyle,
ItemSeparatorComponent,
inverted,
itemAnimations = true,
onPress,
onLongPress,
Expand Down Expand Up @@ -263,9 +280,18 @@ function FlumeInner<T>(given: FlumeProps<T>, ref: Ref<FlumeRef>): ReactElement {
[horizontal, numColumns, padding.top, padding.left, padding.bottom, padding.right, cellWidth],
);
const sticky = useMemo(() => new Set(stickyHeaderIndices), [stickyHeaderIndices]);
const header = useMemo(() => componentElement(ListHeaderComponent), [ListHeaderComponent]);
const footer = useMemo(() => componentElement(ListFooterComponent), [ListFooterComponent]);
const empty = useMemo(() => componentElement(ListEmptyComponent), [ListEmptyComponent]);
const header = useMemo(
() => componentElement(ListHeaderComponent, ListHeaderComponentStyle),
[ListHeaderComponent, ListHeaderComponentStyle],
);
const footer = useMemo(
() => componentElement(ListFooterComponent, ListFooterComponentStyle),
[ListFooterComponent, ListFooterComponentStyle],
);
const empty = useMemo(
() => componentElement(ListEmptyComponent, ListEmptyComponentStyle),
[ListEmptyComponent, ListEmptyComponentStyle],
);
const elementFor = (kind: number) =>
kind === SlotKind.header
? header
Expand Down Expand Up @@ -316,18 +342,31 @@ function FlumeInner<T>(given: FlumeProps<T>, ref: Ref<FlumeRef>): ReactElement {
return [...bySlot.values()].sort((a, b) => a.slot - b.slot);
}, [fresh, table]);
const { next } = commit.diff;
const lastStart = lastRowStart(next.keys.length, horizontal ? 1 : numColumns, stickyIndices);
const separator = (ItemSeparatorComponent ?? null) as
| ComponentType<SeparatorProps<unknown>>
| ReactElement
| null;
const cells = entries.map((entry) => {
const type = typeOf(next, entry.key);
const resolved = type === undefined ? undefined : resolveCell(type, latest.current);
const row = entry.kind === SlotKind.row || entry.kind === SlotKind.sticky;
// By key from the data, since native's table can lag it; a row that left keeps native's index.
const dataIndex = row ? next.index.get(entry.key) : undefined;
const index = dataIndex ?? entry.index;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
return (
<FlumeSlot
key={entry.slot}
slot={entry.slot}
kind={entry.kind}
itemKey={entry.key}
index={entry.index}
index={index}
minMain={entry.minMain}
fullSpan={entry.kind !== SlotKind.row || sticky.has(entry.index)}
fullSpan={entry.kind !== SlotKind.row || sticky.has(index)}
separator={row ? separator : null}
last={dataIndex === undefined || dataIndex >= lastStart}
trailingItem={dataIndex === undefined ? undefined : next.items[dataIndex + 1]}
inverted={inverted === true}
layout={layout}
item={itemOf(next, entry.key)}
render={resolved?.kind === 'react' ? (resolved.render as ReactCell<unknown>) : undefined}
Expand Down
Loading
Loading