diff --git a/android/src/main/cpp/AndroidStoreListener.h b/android/src/main/cpp/AndroidStoreListener.h index d69167a..24e50fc 100644 --- a/android/src/main/cpp/AndroidStoreListener.h +++ b/android/src/main/cpp/AndroidStoreListener.h @@ -39,8 +39,9 @@ struct JFlumeStoreListener : jni::JavaClass { javaClassStatic() ->getMethod("onListChanged"); + // A separator neighbor rebinds in place like a changed row. method(self(), ops.reset, rangeArray(ops.removed).get(), rangeArray(ops.inserted).get(), pairArray(ops.moved).get(), - intArray(ops.changed).get(), count, intArray(ops.sticky).get()); + intArray(rebound(ops)).get(), count, intArray(ops.sticky).get()); } }; 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/adapter/BatchUpdates.cpp b/cpp/adapter/BatchUpdates.cpp index 4b11ce7..f76bb93 100644 --- a/cpp/adapter/BatchUpdates.cpp +++ b/cpp/adapter/BatchUpdates.cpp @@ -41,7 +41,7 @@ BatchUpdates toBatchUpdates(const ListOps& ops, int previousCount) { } } std::sort(batch.deletes.begin(), batch.deletes.end()); - batch.reconfigures = ops.changed; + batch.reconfigures = rebound(ops); return batch; } diff --git a/cpp/adapter/ListRows.cpp b/cpp/adapter/ListRows.cpp index 1e241ed..0d59a1a 100644 --- a/cpp/adapter/ListRows.cpp +++ b/cpp/adapter/ListRows.cpp @@ -31,6 +31,7 @@ ListOps ListRows::positions(const ListOps& dataOps) const { to += shift; } for (int& index : ops.changed) index += shift; + for (int& index : ops.neighbors) index += shift; return ops; } diff --git a/cpp/bindings/Engine.cpp b/cpp/bindings/Engine.cpp index 9a42543..8528297 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,14 @@ 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->list.setSeparators(separatorCell != nullptr); + 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 +220,7 @@ void Engine::releaseOnRuntime(int storeId) { store = it->second; } store->slot.renderCellFn.reset(); + store->slot.separatorCellFn.reset(); store->slot.items.clear(); } @@ -236,6 +246,13 @@ void Engine::detach(int storeId) { store->list.setAttached(false); } +void Engine::setRowShape(int storeId, RowShape shape) { + auto store = find(storeId); + if (store == nullptr) return; + store->shape = shape; + store->list.setLanes(shape.horizontal ? 1 : shape.lanes); +} + int Engine::count(int storeId) { auto store = find(storeId); return store == nullptr ? 0 : store->list.count(); @@ -350,6 +367,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/KeyDiff.cpp b/cpp/core/KeyDiff.cpp index 26169d9..8537172 100644 --- a/cpp/core/KeyDiff.cpp +++ b/cpp/core/KeyDiff.cpp @@ -101,4 +101,16 @@ ListOps diffKeys(const Keys& previous, const Keys& next, const std::vector& return ops; } +std::vector rebound(const ListOps& ops) { + std::vector rows = ops.changed; + rows.insert(rows.end(), ops.neighbors.begin(), ops.neighbors.end()); + std::sort(rows.begin(), rows.end()); + rows.erase(std::unique(rows.begin(), rows.end()), rows.end()); + return rows; +} + +bool isNeighbor(const ListOps& ops, int index) { + return std::binary_search(ops.neighbors.begin(), ops.neighbors.end(), index); +} + } // namespace flume diff --git a/cpp/core/KeyDiff.h b/cpp/core/KeyDiff.h index d45d236..d9d5c3d 100644 --- a/cpp/core/KeyDiff.h +++ b/cpp/core/KeyDiff.h @@ -18,9 +18,16 @@ struct ListOps { std::vector inserted; // next positions, ascending std::vector> moved; // from, to; sequential on the order left by removes then inserts std::vector changed; // next positions of changed items that already existed + std::vector neighbors; // next positions of worklet rows whose separator changed, none of them changed std::vector sticky; // the sticky header indices of the data these ops lead to }; +// The rows a platform rebinds in place: the changed rows and the neighbors, ascending. +std::vector rebound(const ListOps& ops); + +// Whether a next position gained or lost its separator, so a measured length no longer holds. +bool isNeighbor(const ListOps& ops, int index); + // Past this many moves the platform reloads: per-row move animations stop meaning anything, and the work stays bounded. inline constexpr int kMaxMoves = 100; diff --git a/cpp/core/ListStore.cpp b/cpp/core/ListStore.cpp index 6864f6b..7318640 100644 --- a/cpp/core/ListStore.cpp +++ b/cpp/core/ListStore.cpp @@ -2,6 +2,8 @@ #include +#include "core/SeparatorRule.h" + namespace flume { void ListStore::setPending(std::vector keys, std::vector types, @@ -51,6 +53,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; } @@ -71,6 +74,11 @@ void ListStore::setKinds(bool reactByDefault, std::vector reactType pendingKinds_ = Kinds{reactByDefault, {reactTypes.begin(), reactTypes.end()}}; } +void ListStore::setSeparators(bool on) { + std::lock_guard lock(mutex_); + separators_ = on; +} + void ListStore::resolveKinds() { reactByTypeId_.assign(typeRegistry_.size(), false); for (const auto& [name, id] : typeRegistry_) { @@ -82,11 +90,13 @@ std::optional ListStore::applyPending() { std::optional pending; std::optional kinds; std::optional> sticky; + bool separators = false; { std::lock_guard lock(mutex_); pending.swap(pending_); kinds.swap(pendingKinds_); sticky.swap(pendingSticky_); + separators = separators_; } if (kinds) { kinds_ = std::move(*kinds); @@ -110,6 +120,9 @@ std::optional ListStore::applyPending() { std::vector typeIds(size); std::vector itemIds(size); std::vector changed = pending->changedIndices; + // Each row's index in the previous data, -1 for a new key, kept only for the separator neighbors. + std::vector oldOf(separators ? size : 0, -1); + const int oldStart = lastRowStart(static_cast(keys_.size()), lanes_, sticky_); size_t carried = 0; for (size_t i = 0; i < size; i++) { typeIds[i] = typeRegistry_.try_emplace(pending->types[i], static_cast(typeRegistry_.size())).first->second; @@ -117,6 +130,7 @@ std::optional ListStore::applyPending() { idRegistry_.try_emplace(pending->keys[i], static_cast(idRegistry_.size()) + 1).first->second; auto it = previous.find(pending->keys[i]); if (it == previous.end()) continue; + if (separators) oldOf[i] = static_cast(it->second); items[i] = std::move(items_[it->second]); versions[i] = versions_[it->second]; carried++; @@ -142,7 +156,28 @@ std::optional ListStore::applyPending() { versions_ = std::move(versions); typeIds_ = std::move(typeIds); itemIds_ = std::move(itemIds); + if (separators && !ops.reset) ops.neighbors = separatorNeighbors(ops, oldOf, oldStart); return ops; } +// A worklet row rebinds when its separator came or went, or when the row after it is another key or changed. +std::vector ListStore::separatorNeighbors(const ListOps& ops, const std::vector& oldOf, int oldStart) const { + const int size = count(); + std::vector fresh(size, false); + for (int index : ops.changed) fresh[index] = true; + for (const auto& range : ops.inserted) { + for (int i = range.index; i < range.index + range.count; i++) fresh[i] = true; + } + const int newStart = lastRowStart(size, lanes_, sticky_); + std::vector neighbors; + for (int i = 0; i < size; i++) { + const int was = oldOf[i]; + if (was < 0 || fresh[i] || isReactAt(i)) continue; + const bool had = was < oldStart; + const bool has = i < newStart; + if (had != has || (has && (fresh[i + 1] || oldOf[i + 1] != was + 1))) neighbors.push_back(i); + } + return neighbors; +} + } // namespace flume diff --git a/cpp/core/ListStore.h b/cpp/core/ListStore.h index f087999..1fd25c5 100644 --- a/cpp/core/ListStore.h +++ b/cpp/core/ListStore.h @@ -26,6 +26,11 @@ class ListStore { // JS thread; the next applyPending applies it, also when no data is pending. void setKinds(bool reactByDefault, std::vector reactTypes); + // JS thread: with worklet separators on, applyPending lists the rows whose separator changed. + void setSeparators(bool on); + // UI thread: the lanes a grid row holds, which decide its last row. + void setLanes(int lanes) { lanes_ = lanes; } + // UI thread, before the attach applies the pending data, so a snapshot that saw the store detached is still applied. void setAttached(bool attached); // Any thread; a detached store needs no UI wake, its attach applies what is pending. @@ -61,6 +66,7 @@ class ListStore { }; void resolveKinds(); + std::vector separatorNeighbors(const ListOps& ops, const std::vector& oldOf, int oldStart) const; mutable std::mutex mutex_; bool attached_ = false; @@ -80,6 +86,8 @@ class ListStore { std::unordered_map idRegistry_; uint64_t nextVersion_ = 1; uint64_t keysGeneration_ = 0; + bool separators_ = false; // under mutex_ + int lanes_ = 1; }; } // namespace flume 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..fd96653 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(); @@ -316,7 +320,12 @@ void Reconciler::emitRootLabel(Holder& holder, OpBatch& out) { void Reconciler::emitPressableLabels(Mounted& node, OpBatch& out) { if (node.viewId != 0 && node.type == NodeType::Pressable && node.accessibilityLabel.empty()) { std::string joined; - appendTexts(node, joined); + // A separator root is left out of its row's label, not out of its own. + if (node.separator) { + for (const auto& child : node.children) appendTexts(*child, joined); + } else { + appendTexts(node, joined); + } if (joined != node.derivedLabel) { node.derivedLabel = joined; out.accessibility(node.viewId, joined, node.testID, 1, node.accessible); 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/batch_updates_test.cpp b/cpp/tests/batch_updates_test.cpp index 1b58e81..6219399 100644 --- a/cpp/tests/batch_updates_test.cpp +++ b/cpp/tests/batch_updates_test.cpp @@ -88,3 +88,10 @@ TEST_CASE("a reset reloads") { ops.reset = true; CHECK(toBatchUpdates(ops, 3).reload); } + +TEST_CASE("separator neighbors are reconfigured with the changed items") { + ListOps ops = diffKeys({"a", "b", "c"}, {"a", "b", "c", "d"}, {}, true); + ops.neighbors = {2}; + BatchUpdates batch = toBatchUpdates(ops, 3); + CHECK(batch.reconfigures == std::vector{2}); +} diff --git a/cpp/tests/jsi/engine_separator_test.cpp b/cpp/tests/jsi/engine_separator_test.cpp new file mode 100644 index 0000000..d359244 --- /dev/null +++ b/cpp/tests/jsi/engine_separator_test.cpp @@ -0,0 +1,152 @@ +#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()); +} + +namespace { + +struct RecordingListener : flume::StoreListener { + std::vector calls; + void onListChanged(const flume::ListOps& ops, int) override { calls.push_back(ops); } +}; + +} // namespace + +TEST_CASE("with a separator worklet an append lists the old last row as a neighbor") { + ReactSide side; + RecordingListener listener; + int id = separatedStore(side, listener, 3, "0, 0, 0"); + listener.calls.clear(); + side.rig.eval( + "__flume.setData(id, ['0', '1', '2', '3'], ['row', 'react'], new Int32Array([0, 0, 0, 0]), [3], [{n: 3}]," + " true, false);"); + REQUIRE(listener.calls.size() == 1); + CHECK(listener.calls.back().inserted == std::vector{{3, 1}}); + CHECK(listener.calls.back().neighbors == std::vector{2}); +} diff --git a/cpp/tests/list_rows_test.cpp b/cpp/tests/list_rows_test.cpp index b3a0f49..0f83bd8 100644 --- a/cpp/tests/list_rows_test.cpp +++ b/cpp/tests/list_rows_test.cpp @@ -42,3 +42,10 @@ TEST_CASE("full span takes the header, sticky rows, the empty row and the footer ListRows rows{.header = true, .dataCount = 5, .footer = true}; CHECK(rows.fullSpanPositions({2, 4, 9}) == std::vector{0, 3, 5, 6}); } + +TEST_CASE("positions shift the separator neighbors past the header") { + ListRows rows{.header = true, .dataCount = 3, .footer = false}; + ListOps ops; + ops.neighbors = {0, 2}; + CHECK(rows.positions(ops).neighbors == std::vector{1, 3}); +} diff --git a/cpp/tests/list_store_test.cpp b/cpp/tests/list_store_test.cpp index a23018a..e2722fe 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}); @@ -167,3 +174,116 @@ TEST_CASE("data set while detached waits for the attach to apply it") { CHECK(ops->inserted == std::vector{{0, 2}}); CHECK(store.count() == 2); } + +namespace { + +std::vector keysUpTo(int count) { + std::vector keys; + for (int i = 0; i < count; i++) keys.push_back("k" + std::to_string(i)); + return keys; +} + +// Applies keys of one worklet type, with the items at changed given new values. +std::optional applyKeys(flume::ListStore& store, std::vector keys, + std::vector changed = {}, std::vector types = {}) { + if (types.empty()) types.assign(keys.size(), "t"); + std::vector items; + for (int index : changed) items.push_back(V(index)); + store.setPending(std::move(keys), std::move(types), std::move(changed), std::move(items), true); + return store.applyPending(); +} + +// A store holding k0..k(count-1) with worklet separators on. +void separated(flume::ListStore& store, int count, int lanes = 1) { + store.setSeparators(true); + store.setLanes(lanes); + std::vector all; + for (int i = 0; i < count; i++) all.push_back(i); + applyKeys(store, keysUpTo(count), all); +} + +} // namespace + +TEST_CASE("an append rebinds the old last row for its separator") { + flume::ListStore store; + separated(store, 5); + auto ops = applyKeys(store, keysUpTo(6), {5}); + REQUIRE(ops); + CHECK(ops->neighbors == std::vector{4}); +} + +TEST_CASE("deleting the last row rebinds the new last row") { + flume::ListStore store; + separated(store, 5); + auto ops = applyKeys(store, keysUpTo(4)); + REQUIRE(ops); + CHECK(ops->neighbors == std::vector{3}); +} + +TEST_CASE("an insert rebinds the row before it, whose next item changed") { + flume::ListStore store; + separated(store, 5); + auto ops = applyKeys(store, {"k0", "k1", "new", "k2", "k3", "k4"}, {2}); + REQUIRE(ops); + CHECK(ops->neighbors == std::vector{1}); +} + +TEST_CASE("a move rebinds the rows before both ends and the moved row") { + flume::ListStore store; + separated(store, 5); + auto ops = applyKeys(store, {"k0", "k2", "k3", "k1", "k4"}); + REQUIRE(ops); + CHECK(ops->neighbors == std::vector{0, 2, 3}); +} + +TEST_CASE("a changed item rebinds the row before it, and neighbors leave out changed rows") { + flume::ListStore store; + separated(store, 5); + auto one = applyKeys(store, keysUpTo(5), {3}); + REQUIRE(one); + CHECK(one->neighbors == std::vector{2}); + auto two = applyKeys(store, keysUpTo(5), {3, 4}); + REQUIRE(two); + CHECK(two->neighbors == std::vector{2}); +} + +TEST_CASE("an append to a full last grid row rebinds that whole row") { + flume::ListStore store; + separated(store, 9, 3); + auto ops = applyKeys(store, keysUpTo(10), {9}); + REQUIRE(ops); + CHECK(ops->neighbors == std::vector{6, 7, 8}); +} + +TEST_CASE("without separators no neighbor rebinds") { + flume::ListStore store; + separated(store, 5); + store.setSeparators(false); + auto ops = applyKeys(store, keysUpTo(6), {5}); + REQUIRE(ops); + CHECK(ops->neighbors.empty()); +} + +TEST_CASE("a key that turns into a React row rebinds the worklet row before it") { + flume::ListStore store; + store.setKinds(false, {"react"}); + separated(store, 4); + auto ops = applyKeys(store, keysUpTo(4), {}, {"t", "t", "react", "t"}); + REQUIRE(ops); + CHECK(ops->changed == std::vector{2}); + CHECK(ops->neighbors == std::vector{1}); +} + +TEST_CASE("the rows to rebind in place are the changed rows and the neighbors, ascending") { + flume::ListOps ops; + ops.changed = {5, 2}; + ops.neighbors = {1, 4}; + CHECK(flume::rebound(ops) == std::vector{1, 2, 4, 5}); +} + +TEST_CASE("a neighbor position is found among the neighbors only") { + flume::ListOps ops; + ops.neighbors = {1, 4}; + CHECK(flume::isNeighbor(ops, 4)); + CHECK_FALSE(flume::isNeighbor(ops, 2)); +} diff --git a/cpp/tests/separator_rule_test.cpp b/cpp/tests/separator_rule_test.cpp new file mode 100644 index 0000000..dc110b1 --- /dev/null +++ b/cpp/tests/separator_rule_test.cpp @@ -0,0 +1,170 @@ +#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("a pressable separator reads as its own texts, outside the row's label") { + auto pressable = obj({{"type", V("pressable")}, + {"id", V("more")}, + {"children", arr({obj({{"type", V("text")}, {"text", V("Show more")}})})}}); + Bound composed; + composed.bind(flume::composeRow(parsed(row()), parsed(pressable), false, false)); + // The row is view 1 with its texts 2 and 3, the separator pressable view 4. + auto separatorAccess = accessOf(composed.batch, 4); + REQUIRE(separatorAccess); + CHECK(separatorAccess->label == "Show more"); + auto rootAccess = accessOf(composed.batch, 0); + REQUIRE(rootAccess); + CHECK(rootAccess->label.find("Show more") == std::string::npos); +} + +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() {