From 918fd1bf2377385ac9a49f4ddd679c2529ccfb04 Mon Sep 17 00:00:00 2001 From: Rayen Sbai Date: Sat, 21 Nov 2026 23:27:00 +0100 Subject: [PATCH 1/3] feat: draw worklet separators with renderSeparatorCell ItemSeparatorComponent draws only inside React rows, so worklet rows had no item separator. renderSeparatorCell is a worklet that gets leadingItem and trailingItem and returns a cell tree, which the engine lays out under the row in the row's own cell (above it when inverted), except in the last grid row. The cell keeps the row root's press, label, testID and role, and a cell root's margins no longer shrink its layout, as they never moved its paint. --- android/src/main/cpp/FlumeJni.cpp | 5 + .../java/me/sectiontn/flume/FlumeAdapter.kt | 12 +- .../main/java/me/sectiontn/flume/FlumeJni.kt | 3 + .../main/java/me/sectiontn/flume/FlumeView.kt | 2 + cpp/bindings/Engine.cpp | 61 +++++++ cpp/bindings/Engine.h | 3 + cpp/bindings/FlumeHost.cpp | 16 +- cpp/bindings/Store.cpp | 11 ++ cpp/bindings/Store.h | 17 ++ cpp/core/ListStore.cpp | 1 + cpp/core/Mounted.h | 3 +- cpp/core/Node.h | 1 + cpp/core/Reconciler.cpp | 4 + cpp/core/SeparatorRule.cpp | 51 ++++++ cpp/core/SeparatorRule.h | 17 ++ cpp/core/Style.cpp | 15 ++ cpp/core/Style.h | 3 + cpp/tests/jsi/engine_separator_test.cpp | 130 +++++++++++++++ cpp/tests/list_store_test.cpp | 7 + cpp/tests/separator_rule_test.cpp | 155 ++++++++++++++++++ example/src/chat.ts | 12 +- example/src/screens/ChatScreen.tsx | 19 ++- ios/FLMView.mm | 12 ++ src/Flume.tsx | 18 ++ src/__tests__/Flume.test.tsx | 91 ++++++++++ src/foreign.ts | 1 + src/index.ts | 4 + src/props.ts | 1 + src/store.ts | 6 + src/types.ts | 8 + 30 files changed, 683 insertions(+), 6 deletions(-) create mode 100644 cpp/core/SeparatorRule.cpp create mode 100644 cpp/core/SeparatorRule.h create mode 100644 cpp/tests/jsi/engine_separator_test.cpp create mode 100644 cpp/tests/separator_rule_test.cpp diff --git a/android/src/main/cpp/FlumeJni.cpp b/android/src/main/cpp/FlumeJni.cpp index 4b66512..63ed947 100644 --- a/android/src/main/cpp/FlumeJni.cpp +++ b/android/src/main/cpp/FlumeJni.cpp @@ -99,6 +99,10 @@ struct JFlumeJni : jni::JavaClass { return flume::Engine::instance().applyNow(storeId) ? JNI_TRUE : JNI_FALSE; } + static void setRowShape(jni::alias_ref, jint storeId, jboolean horizontal, jboolean inverted, jint lanes) { + flume::Engine::instance().setRowShape(storeId, {horizontal == JNI_TRUE, inverted == JNI_TRUE, lanes}); + } + static void setStatsEnabled(jni::alias_ref, jboolean enabled) { flume::Engine::instance().setStatsEnabled(enabled); } @@ -123,6 +127,7 @@ struct JFlumeJni : jni::JavaClass { makeNativeMethod("invalidateMeasures", JFlumeJni::invalidateMeasures), makeNativeMethod("refresh", JFlumeJni::refresh), makeNativeMethod("applyNow", JFlumeJni::applyNow), + makeNativeMethod("setRowShape", JFlumeJni::setRowShape), makeNativeMethod("setStatsEnabled", JFlumeJni::setStatsEnabled), }); } diff --git a/android/src/main/java/me/sectiontn/flume/FlumeAdapter.kt b/android/src/main/java/me/sectiontn/flume/FlumeAdapter.kt index 80a7234..90419db 100644 --- a/android/src/main/java/me/sectiontn/flume/FlumeAdapter.kt +++ b/android/src/main/java/me/sectiontn/flume/FlumeAdapter.kt @@ -48,7 +48,16 @@ class FlumeAdapter( // Orientation, columns and padding come from the host; a change of the cell size rebinds every row. fun configure(horizontal: Boolean, numColumns: Int, inverted: Boolean, paddingPx: IntArray) { - if (geometry.configure(horizontal, numColumns, inverted, paddingPx)) rebindAll() + if (!geometry.configure(horizontal, numColumns, inverted, paddingPx)) return + sendRowShape() + rebindAll() + } + + // The engine composes worklet separators with the shape the rows are laid out with. + private fun sendRowShape() { + if (storeId == 0) return + val lanes = if (geometry.horizontal) 1 else geometry.numColumns + FlumeJni.setRowShape(storeId, geometry.horizontal, geometry.inverted, lanes) } private fun rebindAll() { @@ -72,6 +81,7 @@ class FlumeAdapter( if (this.storeId != 0 && this.storeId != storeId) detach() val reload = attached.onAttach(storeId) val attachedCount = FlumeJni.attach(storeId, this, measurer, density) + sendRowShape() val sticky = FlumeJni.stickyIndices(storeId) val stickyChanged = !sticky.contentEquals(stickyIndices) stickyIndices = sticky diff --git a/android/src/main/java/me/sectiontn/flume/FlumeJni.kt b/android/src/main/java/me/sectiontn/flume/FlumeJni.kt index 604d26d..df2d172 100644 --- a/android/src/main/java/me/sectiontn/flume/FlumeJni.kt +++ b/android/src/main/java/me/sectiontn/flume/FlumeJni.kt @@ -44,6 +44,9 @@ object FlumeJni { // 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 + // UI thread: the shape the rows are laid out with, before any bind that uses it. + @JvmStatic external fun setRowShape(storeId: Int, horizontal: Boolean, inverted: Boolean, lanes: Int) + // Binds read the clock and return stats only while this is on. @JvmStatic external fun setStatsEnabled(enabled: Boolean) } diff --git a/android/src/main/java/me/sectiontn/flume/FlumeView.kt b/android/src/main/java/me/sectiontn/flume/FlumeView.kt index 67ea2bb..a3b8f14 100644 --- a/android/src/main/java/me/sectiontn/flume/FlumeView.kt +++ b/android/src/main/java/me/sectiontn/flume/FlumeView.kt @@ -195,6 +195,8 @@ class FlumeView(context: Context) : FrameLayout(context) { recycler.adapter = adapter recycler.itemAnimator = animator recycler.clipToPadding = false + // A row composed with its separator draws its shadow from a child view, which a clipping cell would cut. + recycler.clipChildren = false adapter.onPress = { position, pressId, long -> val index = rows.dataIndex(position) if (index >= 0) emitPress(index, FlumeJni.keyAt(storeId, index), pressId, long) diff --git a/cpp/bindings/Engine.cpp b/cpp/bindings/Engine.cpp index 9a42543..386c39a 100644 --- a/cpp/bindings/Engine.cpp +++ b/cpp/bindings/Engine.cpp @@ -4,6 +4,7 @@ #include #include "bindings/JsiConverter.h" +#include "core/SeparatorRule.h" #include "core/TreeParser.h" #ifdef __ANDROID__ @@ -118,6 +119,13 @@ void Engine::setCell(int storeId, std::shared_ptr render scheduleRefresh(store, true); } +void Engine::setSeparatorCell(int storeId, std::shared_ptr separatorCell) { + auto store = find(storeId); + if (store == nullptr) return; + store->setSeparatorCell(std::move(separatorCell)); + scheduleRefresh(store, true); +} + void Engine::setCellKinds(int storeId, bool reactByDefault, std::vector reactTypes) { auto store = find(storeId); if (store == nullptr) return; @@ -211,6 +219,7 @@ void Engine::releaseOnRuntime(int storeId) { store = it->second; } store->slot.renderCellFn.reset(); + store->slot.separatorCellFn.reset(); store->slot.items.clear(); } @@ -236,6 +245,11 @@ void Engine::detach(int storeId) { store->list.setAttached(false); } +void Engine::setRowShape(int storeId, RowShape shape) { + auto store = find(storeId); + if (store != nullptr) store->shape = shape; +} + int Engine::count(int storeId) { auto store = find(storeId); return store == nullptr ? 0 : store->list.count(); @@ -350,6 +364,53 @@ void Engine::bindOnRuntime(jsi::Runtime& rt, int index) { } catch (const std::exception& e) { current_.error = std::string("renderCell failed: ") + e.what(); } + if (current_.fresh != nullptr) composeOnRuntime(rt, *store, index); +} + +// With a separator worklet every row binds composed, and rows before the last grid row get its tree. +void Engine::composeOnRuntime(jsi::Runtime& rt, Store& store, int index) { + Store::RuntimeSlot& slot = store.slot; + auto [separatorCell, version] = store.separatorCell(); + if (separatorCell == nullptr) { + slot.separatorCellFn.reset(); + return; + } + const RowShape& shape = store.shape; + std::unique_ptr separator; + try { + if (!slot.separatorCellFn || slot.separatorCellVersion != version) { + slot.separatorCellFn = separatorCell->toJSValue(rt).asObject(rt).asFunction(rt); + slot.separatorCellVersion = version; + } + int count = store.list.count(); + if (index < lastRowStart(count, shape.horizontal ? 1 : shape.lanes, store.list.sticky())) { + const ListStore& list = store.list; + jsi::Object info(rt); + info.setProperty(rt, "leadingItem", + jsi::Value(rt, slot.items.materialize(rt, list.keyAt(index), list.itemVersion(index), + list.itemAt(index)))); + int next = index + 1; + // A React row's item lives in JS only, so its separator gets no trailing item. + if (next < count && !list.isReactAt(next)) { + info.setProperty(rt, "trailingItem", + jsi::Value(rt, slot.items.materialize(rt, list.keyAt(next), list.itemVersion(next), + list.itemAt(next)))); + } + jsi::Value result = slot.separatorCellFn->call(rt, {jsi::Value(rt, info)}); + if (!result.isNull() && !result.isUndefined()) { + std::vector unknownKeys; + ParseResult parsed = parseTree(toValue(rt, result), &unknownKeys); + for (const std::string& key : unknownKeys) report(1, "unknown style key: " + key); + if (parsed.root == nullptr) report(2, "renderSeparatorCell returned an invalid tree: " + parsed.error); + separator = std::move(parsed.root); + } + } + } catch (const jsi::JSError& e) { + report(2, "renderSeparatorCell threw: " + e.getMessage()); + } catch (const std::exception& e) { + report(2, std::string("renderSeparatorCell failed: ") + e.what()); + } + current_.fresh = composeRow(std::move(current_.fresh), std::move(separator), shape.horizontal, shape.inverted); } int Engine::viewType(int storeId, int position) { diff --git a/cpp/bindings/Engine.h b/cpp/bindings/Engine.h index 4ef7931..0d60600 100644 --- a/cpp/bindings/Engine.h +++ b/cpp/bindings/Engine.h @@ -41,6 +41,7 @@ class Engine { // A sticky-only change: it joins pending data, or applies alone. void setStickyHeaderIndices(int storeId, std::vector sticky); void setCell(int storeId, std::shared_ptr renderCell); + void setSeparatorCell(int storeId, std::shared_ptr separatorCell); // null clears it void setCellKinds(int storeId, bool reactByDefault, std::vector reactTypes); void setReporter(int session, facebook::jsi::Function reporter); // a function on the React runtime, development only void report(int level, const std::string& message); // once per message: the reporter when set, else logcat @@ -52,6 +53,7 @@ class Engine { // UI thread (platform bridge) int attach(int storeId, StoreListener* listener, std::unique_ptr measurer, float pointScale); void detach(int storeId); + void setRowShape(int storeId, RowShape shape); // before any bind laid out with the new shape int count(int storeId); int viewType(int storeId, int position); // type id * 2, plus 1 for React; 0 for an unknown position bool hasReactKinds(int storeId); // some item type renders as a React row @@ -89,6 +91,7 @@ class Engine { void scheduleRefresh(const std::shared_ptr& store, bool always); static bool applyPending(Store& store, bool always); void bindOnRuntime(facebook::jsi::Runtime& rt, int index); + void composeOnRuntime(facebook::jsi::Runtime& rt, Store& store, int index); void releaseOnRuntime(int storeId); void logLine(const std::string& message); diff --git a/cpp/bindings/FlumeHost.cpp b/cpp/bindings/FlumeHost.cpp index d6f7f30..8365635 100644 --- a/cpp/bindings/FlumeHost.cpp +++ b/cpp/bindings/FlumeHost.cpp @@ -15,7 +15,8 @@ namespace jsi = facebook::jsi; namespace { const char* const kNames[] = {"install", "setScheduler", "createStore", "releaseStore", "setData", - "setCell", "setCellKinds", "setStickyHeaderIndices", "setReporter"}; + "setCell", "setSeparatorCell", "setCellKinds", "setStickyHeaderIndices", + "setReporter"}; std::vector stringsOf(jsi::Runtime& rt, const jsi::Value& value) { std::vector out; @@ -157,6 +158,19 @@ jsi::Value FlumeHost::get(jsi::Runtime& rt, const jsi::PropNameID& nameId) { return jsi::Value::undefined(); }); } + if (name == "setSeparatorCell") { + return hostFunction(rt, "setSeparatorCell", 2, + [&engine](jsi::Runtime& rt, const jsi::Value&, const jsi::Value* args, size_t count) { + if (count < 1) throw jsi::JSError(rt, "setSeparatorCell needs a store id"); + std::shared_ptr worklet; + if (count > 1 && !args[1].isNull() && !args[1].isUndefined()) { + worklet = worklets::extractSerializable( + rt, args[1], "react-native-flume: renderSeparatorCell must be a worklet"); + } + engine.setSeparatorCell(static_cast(args[0].asNumber()), std::move(worklet)); + return jsi::Value::undefined(); + }); + } if (name == "setCellKinds") { return hostFunction(rt, "setCellKinds", 3, [&engine](jsi::Runtime& rt, const jsi::Value&, const jsi::Value* args, size_t count) { diff --git a/cpp/bindings/Store.cpp b/cpp/bindings/Store.cpp index 4f0e361..7c0c061 100644 --- a/cpp/bindings/Store.cpp +++ b/cpp/bindings/Store.cpp @@ -28,4 +28,15 @@ uint64_t Store::renderCellVersion() const { return renderCellVersion_; } +void Store::setSeparatorCell(std::shared_ptr separatorCell) { + std::lock_guard lock(mutex_); + separatorCell_ = std::move(separatorCell); + separatorCellVersion_++; +} + +std::pair, uint64_t> Store::separatorCell() const { + std::lock_guard lock(mutex_); + return {separatorCell_, separatorCellVersion_}; +} + } // namespace flume diff --git a/cpp/bindings/Store.h b/cpp/bindings/Store.h index 464cc94..23f26d6 100644 --- a/cpp/bindings/Store.h +++ b/cpp/bindings/Store.h @@ -9,6 +9,7 @@ #include #include #include +#include #include #include "bindings/ItemCache.h" @@ -37,6 +38,14 @@ struct FlumeRuntime { const facebook::jsi::Function release; }; +// How the platform lays rows out, which decides where a separator goes and which rows draw one. +struct RowShape { + bool horizontal = false; + bool inverted = false; + int lanes = 1; + bool operator==(const RowShape&) const = default; +}; + // One list: its order and items, the cell worklet, its holders and its runtime handles. class Store : public std::enable_shared_from_this { public: @@ -49,10 +58,14 @@ class Store : public std::enable_shared_from_this { // JS thread void setRenderCell(std::shared_ptr renderCell); + void setSeparatorCell(std::shared_ptr separatorCell); // null clears it // UI thread std::shared_ptr renderCell() const; uint64_t renderCellVersion() const; + // The separator worklet with its version, read together so a set between two reads cannot pair them wrong. + std::pair, uint64_t> separatorCell() const; + RowShape shape; // set by the platform view before it binds with a new shape std::unordered_map> holders; StoreListener* listener = nullptr; @@ -65,6 +78,8 @@ class Store : public std::enable_shared_from_this { std::shared_ptr flume; // the runtime of the values below, declared first so it dies last std::optional renderCellFn; uint64_t renderCellVersion = 0; + std::optional separatorCellFn; + uint64_t separatorCellVersion = 0; ItemCache items; uint64_t retainedGeneration = 0; } slot; @@ -73,6 +88,8 @@ class Store : public std::enable_shared_from_this { mutable std::mutex mutex_; std::shared_ptr renderCell_; uint64_t renderCellVersion_ = 0; + std::shared_ptr separatorCell_; + uint64_t separatorCellVersion_ = 0; }; } // namespace flume diff --git a/cpp/core/ListStore.cpp b/cpp/core/ListStore.cpp index 6864f6b..e5b320f 100644 --- a/cpp/core/ListStore.cpp +++ b/cpp/core/ListStore.cpp @@ -51,6 +51,7 @@ std::vector stickyWithin(const std::vector& sticky, size_t count) { for (int index : sticky) { if (index >= 0 && static_cast(index) < count) out.push_back(index); } + std::sort(out.begin(), out.end()); return out; } diff --git a/cpp/core/Mounted.h b/cpp/core/Mounted.h index db80f26..af9e02d 100644 --- a/cpp/core/Mounted.h +++ b/cpp/core/Mounted.h @@ -32,7 +32,8 @@ struct Mounted { std::string testID; std::string accessibilityLabel; std::optional accessible; - std::string derivedLabel; // the label last sent from the texts inside a pressable without its own + bool separator = false; // the separator half of a composed row, left out of the row's label + std::string derivedLabel; // the label last sent from the texts inside a pressable without its own int viewId = 0; // 0 is the holder's own view YGNodeRef yoga = nullptr; Layout* layout = nullptr; diff --git a/cpp/core/Node.h b/cpp/core/Node.h index 9900d2a..4a5220a 100644 --- a/cpp/core/Node.h +++ b/cpp/core/Node.h @@ -28,6 +28,7 @@ struct Node { std::string testID; std::string accessibilityLabel; std::optional accessible; + bool separator = false; // the separator half of a composed row, left out of the row's label std::vector> children; // view and pressable only }; diff --git a/cpp/core/Reconciler.cpp b/cpp/core/Reconciler.cpp index 1e59b83..7e63a55 100644 --- a/cpp/core/Reconciler.cpp +++ b/cpp/core/Reconciler.cpp @@ -81,9 +81,11 @@ void copyProps(Mounted& mounted, Node& fresh) { mounted.testID = std::move(fresh.testID); mounted.accessibilityLabel = std::move(fresh.accessibilityLabel); mounted.accessible = fresh.accessible; + mounted.separator = fresh.separator; } void appendTexts(const Mounted& node, std::string& out) { + if (node.separator) return; if (node.type == NodeType::Text && !node.text.empty()) { if (!out.empty()) out += ' '; out += node.text; @@ -101,6 +103,8 @@ void Reconciler::reconcile(Holder& holder, std::unique_ptr fresh, OpBatch& } return; } + // The cell view is the root's box, so a root margin would only shrink the layout under an unchanged paint. + clearParentLayout(fresh->style); if (holder.root != nullptr && holder.root->type != fresh->type) { unmount(*holder.root, out); holder.root.reset(); diff --git a/cpp/core/SeparatorRule.cpp b/cpp/core/SeparatorRule.cpp new file mode 100644 index 0000000..de813ec --- /dev/null +++ b/cpp/core/SeparatorRule.cpp @@ -0,0 +1,51 @@ +#include "core/SeparatorRule.h" + +#include +#include + +namespace flume { + +int lastRowStart(int count, int lanes, const std::vector& sortedFullSpans) { + if (count <= 0) return 0; + int last = count - 1; + lanes = std::max(lanes, 1); + // Only the last full span at or before the last index decides where the last run of lanes starts. + auto after = std::upper_bound(sortedFullSpans.begin(), sortedFullSpans.end(), last); + int runStart = 0; + if (after != sortedFullSpans.begin()) { + int span = *(after - 1); + if (span == last) return last; + runStart = span + 1; + } + return runStart + (last - runStart) / lanes * lanes; +} + +std::unique_ptr composeRow(std::unique_ptr row, std::unique_ptr separator, bool horizontal, + bool inverted) { + auto root = std::make_unique(); + root->style.flexDirection = horizontal ? YGFlexDirectionRow : YGFlexDirectionColumn; + if (row->type == NodeType::Pressable) { + root->type = NodeType::Pressable; + row->type = NodeType::View; + } + root->pressId = std::move(row->pressId); + root->pressedOpacity = row->pressedOpacity; + root->testID = std::move(row->testID); + root->accessibilityLabel = std::move(row->accessibilityLabel); + root->accessible = row->accessible; + row->pressId.clear(); + row->testID.clear(); + row->accessibilityLabel.clear(); + row->accessible.reset(); + clearParentLayout(row->style); + row->key = "r"; + root->children.push_back(std::move(row)); + if (separator != nullptr) { + separator->key = "s"; + separator->separator = true; + root->children.insert(inverted ? root->children.begin() : root->children.end(), std::move(separator)); + } + return root; +} + +} // namespace flume diff --git a/cpp/core/SeparatorRule.h b/cpp/core/SeparatorRule.h new file mode 100644 index 0000000..2cb5901 --- /dev/null +++ b/cpp/core/SeparatorRule.h @@ -0,0 +1,17 @@ +#pragma once + +#include +#include + +#include "core/Node.h" + +namespace flume { + +// The first index of the last grid row, whose rows draw no separator. A full-span index ends a run of lanes. +int lastRowStart(int count, int lanes, const std::vector& sortedFullSpans); + +// The row and its separator (first when inverted) under a root that takes the row root's press, label, id and role. +std::unique_ptr composeRow(std::unique_ptr row, std::unique_ptr separator, bool horizontal, + bool inverted); + +} // namespace flume diff --git a/cpp/core/Style.cpp b/cpp/core/Style.cpp index 880b701..aafd611 100644 --- a/cpp/core/Style.cpp +++ b/cpp/core/Style.cpp @@ -290,3 +290,18 @@ Style Style::fromValue(const Value& object, std::vector* unknownKey } } // namespace flume + +namespace flume { + +void clearParentLayout(Style& style) { + style.margin.fill(Dimension{}); + style.position.fill(Dimension{}); + style.positionType.reset(); + style.alignSelf.reset(); + style.flex.reset(); + style.flexGrow.reset(); + style.flexShrink.reset(); + style.flexBasis = Dimension{}; +} + +} // namespace flume diff --git a/cpp/core/Style.h b/cpp/core/Style.h index 3004928..dcac85f 100644 --- a/cpp/core/Style.h +++ b/cpp/core/Style.h @@ -60,4 +60,7 @@ struct Style { bool operator==(const Style&) const = default; }; +// Drops what only a parent reads (margins, insets, position type, alignSelf and flex), as a cell root never has one. +void clearParentLayout(Style& style); + } // namespace flume diff --git a/cpp/tests/jsi/engine_separator_test.cpp b/cpp/tests/jsi/engine_separator_test.cpp new file mode 100644 index 0000000..2c12f5c --- /dev/null +++ b/cpp/tests/jsi/engine_separator_test.cpp @@ -0,0 +1,130 @@ +#include +#include +#include +#include + +#include "batch.h" +#include "bindings/Engine.h" +#include "bindings/FlumeHost.h" +#include "doctest.h" +#include "fake_measurer.h" +#include "fake_worklets.h" +#include "hermes_rig.h" + +namespace { + +// A React runtime with __flume and a flume runtime installed, so rows bind. +struct ReactSide { + HermesRig rig; + std::shared_ptr invoker = std::make_shared(); + ReactSide() { + flume::FlumeHost::install(rig.rt(), invoker); + installFlumeRuntime(rig.rt()); + } +}; + +struct NullListener : flume::StoreListener { + void onListChanged(const flume::ListOps&, int) override {} +}; + +// Rows 10 pt tall, typed by typeIds, and a separator 1 pt tall whose text names its leading and trailing items. +int separatedStore(ReactSide& side, flume::StoreListener& listener, int count, const std::string& typeIds, + const std::string& reactTypes = "[]") { + std::string keys, items; + for (int i = 0; i < count; i++) { + keys += (i ? ", '" : "'") + std::to_string(i) + "'"; + items += (i ? ", {n: " : "{n: ") + std::to_string(i) + "}"; + } + std::string indices; + for (int i = 0; i < count; i++) indices += (i ? ", " : "") + std::to_string(i); + int id = static_cast( + side.rig + .eval("__flume.setScheduler({});" + "var id = __flume.createStore();" + "__flume.setCellKinds(id, false, " + + reactTypes + + ");" + "__flume.setData(id, [" + + keys + "], ['row', 'react'], new Int32Array([" + typeIds + "]), [" + indices + "], [" + items + + "], true, false);" + "__flume.setCell(id, function (item, index) {" + " 'show source';" + " return {type: 'view', style: {height: 10}};" + "});" + "__flume.setSeparatorCell(id, function (info) {" + " 'show source';" + " var trailing = info.trailingItem === undefined ? 'none' : String(info.trailingItem.n);" + " return {type: 'text', text: info.leadingItem.n + '-' + trailing, style: {height: 1}};" + "});" + "id") + .asNumber()); + REQUIRE(flume::Engine::instance().attach(id, &listener, std::make_unique(), 1) == count); + return id; +} + +flume::OpBatch bound(int id, int index) { + flume::OpBatch out; + REQUIRE(flume::Engine::instance().bind(id, index, index, 300, NAN, out)); + return out; +} + +bool says(const flume::OpBatch& batch, const std::string& text) { + return std::find(batch.strings.begin(), batch.strings.end(), text) != batch.strings.end(); +} + +} // namespace + +TEST_CASE("a separator worklet draws under every row but the last, with the next item") { + ReactSide side; + NullListener listener; + int id = separatedStore(side, listener, 3, "0, 0, 0"); + auto first = bound(id, 0); + CHECK(says(first, "0-1")); + CHECK(first.rootHeight == 11); + auto last = bound(id, 2); + CHECK_FALSE(says(last, "2-none")); + CHECK(last.rootHeight == 10); + // The last row keeps the composed root, so it never switches shape. + CHECK(frameOf(last, 1).has_value()); +} + +TEST_CASE("a separator before a React row has no trailing item") { + ReactSide side; + NullListener listener; + int id = separatedStore(side, listener, 3, "0, 0, 1", "['react']"); + CHECK(says(bound(id, 1), "1-none")); +} + +TEST_CASE("an inverted row shape puts the separator before the row") { + ReactSide side; + NullListener listener; + int id = separatedStore(side, listener, 3, "0, 0, 0"); + flume::Engine::instance().setRowShape(id, {false, true, 1}); + auto out = bound(id, 0); + // The separator is created first: view 1 at the top, the row view 2 under it. + auto divider = frameOf(out, 1); + auto row = frameOf(out, 2); + REQUIRE(divider); + REQUIRE(row); + CHECK((*divider)[1] == 0); + CHECK((*row)[1] == 1); +} + +TEST_CASE("three lanes leave the last grid row without a separator") { + ReactSide side; + NullListener listener; + int id = separatedStore(side, listener, 10, "0, 0, 0, 0, 0, 0, 0, 0, 0, 0"); + flume::Engine::instance().setRowShape(id, {false, false, 3}); + CHECK(says(bound(id, 8), "8-9")); + CHECK(bound(id, 9).rootHeight == 10); +} + +TEST_CASE("clearing the separator worklet binds plain rows again") { + ReactSide side; + NullListener listener; + int id = separatedStore(side, listener, 3, "0, 0, 0"); + side.rig.eval("__flume.setSeparatorCell(id, null)"); + auto out = bound(id, 0); + CHECK(out.rootHeight == 10); + CHECK_FALSE(frameOf(out, 1).has_value()); +} diff --git a/cpp/tests/list_store_test.cpp b/cpp/tests/list_store_test.cpp index a23018a..65d1be3 100644 --- a/cpp/tests/list_store_test.cpp +++ b/cpp/tests/list_store_test.cpp @@ -18,6 +18,13 @@ TEST_CASE("a first snapshot inserts everything") { CHECK(store.keyAt(2) == "c"); } +TEST_CASE("sticky indices apply sorted, so the last full span is found by a search") { + flume::ListStore store; + store.setPending({"a", "b", "c", "d"}, {"t", "t", "t", "t"}, {0, 1, 2, 3}, {V(1), V(2), V(3), V(4)}, true, {3, 0, 2}); + store.applyPending(); + CHECK(store.sticky() == std::vector{0, 2, 3}); +} + TEST_CASE("a reset carries the sticky indices of its own data") { flume::ListStore store; store.setPending({"a", "b", "c"}, {"t", "t", "t"}, {0, 1, 2}, {V(1), V(2), V(3)}, true, {0}); diff --git a/cpp/tests/separator_rule_test.cpp b/cpp/tests/separator_rule_test.cpp new file mode 100644 index 0000000..038e890 --- /dev/null +++ b/cpp/tests/separator_rule_test.cpp @@ -0,0 +1,155 @@ +#include "doctest.h" + +#include +#include +#include +#include + +#include "batch.h" +#include "core/Layout.h" +#include "core/Reconciler.h" +#include "core/SeparatorRule.h" +#include "core/TreeParser.h" +#include "fake_measurer.h" +#include "values.h" + +namespace { + +// The same table as src/__tests__/separators.test.ts. +struct Case { + int count, columns; + std::vector spans; + int start; +}; + +struct Bound { + FakeMeasurer fake; + flume::Layout layout{fake, 1}; + flume::Reconciler rec{layout}; + flume::Holder holder; + flume::OpBatch batch; + + void bind(std::unique_ptr root, float width = 360) { + batch.clear(); + rec.reconcile(holder, std::move(root), batch); + layout.layout(*holder.root, width, NAN); + layout.readFrames(*holder.root, batch); + rec.emitAfterLayout(holder, batch); + } +}; + +std::unique_ptr parsed(const flume::Value& tree) { + auto result = flume::parseTree(tree); + REQUIRE(result.root); + return std::move(result.root); +} + +flume::Value row(const char* label = nullptr) { + flume::Value::Object row{ + {"type", V("pressable")}, + {"id", V("open")}, + {"testID", V("row-a")}, + {"style", obj({{"margin", V(10)}, {"padding", V(12)}, {"backgroundColor", V("#ffffff")}, + {"shadowOpacity", V(0.3)}, {"shadowRadius", V(4)}})}, + {"children", arr({obj({{"type", V("text")}, {"text", V("hello")}}), + obj({{"type", V("text")}, {"text", V("9:41")}})})}}; + if (label != nullptr) row.emplace_back("accessibilityLabel", V(label)); + return flume::Value(std::move(row)); +} + +flume::Value separator() { + return obj({{"type", V("view")}, + {"style", obj({{"height", V(1)}, {"backgroundColor", V("#cccccc")}})}, + {"children", arr({obj({{"type", V("text")}, {"text", V("divider")}})})}}); +} + +// The last accessibility op of a view: label, testID, role. +struct Access { + std::string label, testID; + int role; +}; +std::optional accessOf(const flume::OpBatch& batch, int id) { + std::optional found; + for (const auto& op : decode(batch)) { + if (op.op != 8 || op.id != id) continue; + auto text = [&](int index) { return index < 0 ? std::string() : batch.strings[index]; }; + found = Access{text(op.ints[0]), text(op.ints[1]), op.ints[2]}; + } + return found; +} + +} // namespace + +TEST_CASE("the last grid row starts where the table says") { + const std::vector cases{{0, 1, {}, 0}, {5, 1, {}, 4}, {9, 3, {}, 6}, {10, 3, {}, 9}, + {10, 3, {4}, 8}, {10, 3, {9}, 9}, {6, 2, {0, 3}, 4}}; + for (const Case& c : cases) { + CAPTURE(c.count); + CAPTURE(c.columns); + CHECK(flume::lastRowStart(c.count, c.columns, c.spans) == c.start); + } +} + +TEST_CASE("a composed row draws like the plain row") { + Bound plain; + plain.bind(parsed(row())); + Bound composed; + composed.bind(flume::composeRow(parsed(row()), parsed(separator()), false, false)); + // Plain: the root is view 0 and its texts views 1 and 2. Composed: the row is view 1, its texts 2 and 3. + auto plainRoot = frameOf(plain.batch, 0); + auto composedRow = frameOf(composed.batch, 1); + REQUIRE(plainRoot); + REQUIRE(composedRow); + // A root margin is ignored, so the row spans the bind width in both. + CHECK((*plainRoot)[2] == 360); + CHECK((*composedRow)[0] == 0); + CHECK((*composedRow)[1] == 0); + CHECK((*composedRow)[2] == (*plainRoot)[2]); + CHECK((*composedRow)[3] == (*plainRoot)[3]); + CHECK(frameOf(composed.batch, 2) == frameOf(plain.batch, 1)); + CHECK(frameOf(composed.batch, 3) == frameOf(plain.batch, 2)); + // The separator is view 4, under the row and as wide as the bind width. + auto divider = frameOf(composed.batch, 4); + REQUIRE(divider); + CHECK((*divider)[0] == 0); + CHECK((*divider)[1] == (*plainRoot)[3]); + CHECK((*divider)[2] == 360); + CHECK((*divider)[3] == 1); + auto plainAccess = accessOf(plain.batch, 0); + auto composedAccess = accessOf(composed.batch, 0); + REQUIRE(plainAccess); + REQUIRE(composedAccess); + CHECK(composedAccess->label == plainAccess->label); + CHECK(composedAccess->label.find("divider") == std::string::npos); + CHECK(composedAccess->testID == "row-a"); + CHECK(composedAccess->role == 1); + CHECK_FALSE(accessOf(composed.batch, 1).has_value()); + CHECK(firstOp(composed.batch, 7, 0).id == 0); +} + +TEST_CASE("a composed row keeps the row's own label on the cell") { + Bound composed; + composed.bind(flume::composeRow(parsed(row("Open chat")), parsed(separator()), false, false)); + auto access = accessOf(composed.batch, 0); + REQUIRE(access); + CHECK(access->label == "Open chat"); + CHECK(access->testID == "row-a"); + CHECK_FALSE(accessOf(composed.batch, 1).has_value()); +} + +TEST_CASE("an inverted composed row puts the separator first") { + Bound composed; + composed.bind(flume::composeRow(parsed(row()), parsed(separator()), false, true)); + // The separator is created first, so it is view 1 and the row view 3. + auto divider = frameOf(composed.batch, 1); + REQUIRE(divider); + CHECK((*divider)[1] == 0); + CHECK((*divider)[3] == 1); +} + +TEST_CASE("a composed row without a separator keeps the row alone") { + Bound composed; + composed.bind(flume::composeRow(parsed(row()), nullptr, false, false)); + CHECK(frameOf(composed.batch, 1).has_value()); + CHECK_FALSE(frameOf(composed.batch, 4).has_value()); +} diff --git a/example/src/chat.ts b/example/src/chat.ts index 61354a2..36b29b0 100644 --- a/example/src/chat.ts +++ b/example/src/chat.ts @@ -1,4 +1,4 @@ -import { type CellNode, cell } from 'react-native-flume'; +import { type CellNode, cell, type SeparatorCellInfo } from 'react-native-flume'; export type Chat = { id: string; @@ -68,6 +68,16 @@ export function dayIndices(chats: readonly Chat[]): number[] { export const accentColor = (dark: boolean) => (dark ? '#6ea8ff' : '#0066ff'); +// A hairline under each message, inset past the avatar, and full width next to a day chip. +export function makeRenderSeparatorCell(dark: boolean) { + const line = dark ? '#3a3a3a' : '#dddddd'; + return ({ leadingItem, trailingItem }: SeparatorCellInfo): CellNode => { + 'worklet'; + const nextToDay = leadingItem.kind === 'day' || trailingItem?.kind === 'day'; + return cell.view({ height: 1, marginLeft: nextToDay ? 0 : 64, backgroundColor: line }); + }; +} + export function makeRenderCell(dark: boolean) { const textColor = dark ? '#eeeeee' : '#111111'; const timeColor = dark ? '#aaaaaa' : '#666666'; diff --git a/example/src/screens/ChatScreen.tsx b/example/src/screens/ChatScreen.tsx index 9519aeb..c9a8c9c 100644 --- a/example/src/screens/ChatScreen.tsx +++ b/example/src/screens/ChatScreen.tsx @@ -1,7 +1,14 @@ import { useMemo, useRef, useState } from 'react'; import { Button, Platform, ToastAndroid, View } from 'react-native'; import { Flume, type FlumeRef, type PressInfo } from 'react-native-flume'; -import { accentColor, type Chat, dayIndices, makeChats, makeRenderCell } from '../chat'; +import { + accentColor, + type Chat, + dayIndices, + makeChats, + makeRenderCell, + makeRenderSeparatorCell, +} from '../chat'; function blockJs(ms: number) { const end = Date.now() + ms; @@ -53,6 +60,9 @@ export default function ChatScreen() { older: 0, })); const renderCell = useMemo(() => makeRenderCell(dark), [dark]); + // Native hairlines from the separator prop, or a worklet that draws each one next to its rows. + const [workletSeparators, setWorkletSeparators] = useState(false); + const renderSeparatorCell = useMemo(() => makeRenderSeparatorCell(dark), [dark]); const sticky = useMemo(() => dayIndices(list.chats), [list.chats]); const onPress = ({ item, id }: PressInfo) => toast(id === 'like' ? `like ${item.id}` : `open ${item.id}`); @@ -107,6 +117,10 @@ export default function ChatScreen() {