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
3 changes: 2 additions & 1 deletion android/src/main/cpp/AndroidStoreListener.h
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,9 @@ struct JFlumeStoreListener : jni::JavaClass<JFlumeStoreListener> {
javaClassStatic()
->getMethod<void(jboolean, jni::JArrayInt::javaobject, jni::JArrayInt::javaobject, jni::JArrayInt::javaobject,
jni::JArrayInt::javaobject, jint, jni::JArrayInt::javaobject)>("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());
}
};

Expand Down
5 changes: 5 additions & 0 deletions android/src/main/cpp/FlumeJni.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,10 @@ struct JFlumeJni : jni::JavaClass<JFlumeJni> {
return flume::Engine::instance().applyNow(storeId) ? JNI_TRUE : JNI_FALSE;
}

static void setRowShape(jni::alias_ref<jclass>, 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<jclass>, jboolean enabled) {
flume::Engine::instance().setStatsEnabled(enabled);
}
Expand All @@ -123,6 +127,7 @@ struct JFlumeJni : jni::JavaClass<JFlumeJni> {
makeNativeMethod("invalidateMeasures", JFlumeJni::invalidateMeasures),
makeNativeMethod("refresh", JFlumeJni::refresh),
makeNativeMethod("applyNow", JFlumeJni::applyNow),
makeNativeMethod("setRowShape", JFlumeJni::setRowShape),
makeNativeMethod("setStatsEnabled", JFlumeJni::setStatsEnabled),
});
}
Expand Down
12 changes: 11 additions & 1 deletion android/src/main/java/me/sectiontn/flume/FlumeAdapter.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Comment thread
SectionTN marked this conversation as resolved.
Resolved
Comment thread
SectionTN marked this conversation as resolved.
Resolved
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() {
Expand All @@ -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
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 @@ -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)
}
2 changes: 2 additions & 0 deletions android/src/main/java/me/sectiontn/flume/FlumeView.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion cpp/adapter/BatchUpdates.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand Down
1 change: 1 addition & 0 deletions cpp/adapter/ListRows.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand Down
64 changes: 64 additions & 0 deletions cpp/bindings/Engine.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
#include <cstdio>

#include "bindings/JsiConverter.h"
#include "core/SeparatorRule.h"
#include "core/TreeParser.h"

#ifdef __ANDROID__
Expand Down Expand Up @@ -118,6 +119,14 @@ void Engine::setCell(int storeId, std::shared_ptr<worklets::Serializable> render
scheduleRefresh(store, true);
}

void Engine::setSeparatorCell(int storeId, std::shared_ptr<worklets::Serializable> 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<std::string> reactTypes) {
auto store = find(storeId);
if (store == nullptr) return;
Expand Down Expand Up @@ -211,6 +220,7 @@ void Engine::releaseOnRuntime(int storeId) {
store = it->second;
}
store->slot.renderCellFn.reset();
store->slot.separatorCellFn.reset();
store->slot.items.clear();
}

Expand All @@ -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();
Expand Down Expand Up @@ -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<Node> 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<std::string> 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) {
Expand Down
3 changes: 3 additions & 0 deletions cpp/bindings/Engine.h
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ class Engine {
// A sticky-only change: it joins pending data, or applies alone.
void setStickyHeaderIndices(int storeId, std::vector<int> sticky);
void setCell(int storeId, std::shared_ptr<worklets::Serializable> renderCell);
void setSeparatorCell(int storeId, std::shared_ptr<worklets::Serializable> separatorCell); // null clears it
void setCellKinds(int storeId, bool reactByDefault, std::vector<std::string> 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
Expand All @@ -52,6 +53,7 @@ class Engine {
// UI thread (platform bridge)
int attach(int storeId, StoreListener* listener, std::unique_ptr<TextMeasurer> 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
Expand Down Expand Up @@ -89,6 +91,7 @@ class Engine {
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 composeOnRuntime(facebook::jsi::Runtime& rt, Store& store, int index);
void releaseOnRuntime(int storeId);
void logLine(const std::string& message);

Expand Down
16 changes: 15 additions & 1 deletion cpp/bindings/FlumeHost.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<std::string> stringsOf(jsi::Runtime& rt, const jsi::Value& value) {
std::vector<std::string> out;
Expand Down Expand Up @@ -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<worklets::Serializable> 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<int>(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) {
Expand Down
11 changes: 11 additions & 0 deletions cpp/bindings/Store.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,15 @@ uint64_t Store::renderCellVersion() const {
return renderCellVersion_;
}

void Store::setSeparatorCell(std::shared_ptr<worklets::Serializable> separatorCell) {
std::lock_guard<std::mutex> lock(mutex_);
separatorCell_ = std::move(separatorCell);
separatorCellVersion_++;
}

std::pair<std::shared_ptr<worklets::Serializable>, uint64_t> Store::separatorCell() const {
std::lock_guard<std::mutex> lock(mutex_);
return {separatorCell_, separatorCellVersion_};
}

} // namespace flume
17 changes: 17 additions & 0 deletions cpp/bindings/Store.h
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
#include <optional>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>

#include "bindings/ItemCache.h"
Expand Down Expand Up @@ -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<Store> {
public:
Expand All @@ -49,10 +58,14 @@ class Store : public std::enable_shared_from_this<Store> {

// JS thread
void setRenderCell(std::shared_ptr<worklets::Serializable> renderCell);
void setSeparatorCell(std::shared_ptr<worklets::Serializable> separatorCell); // null clears it

// UI thread
std::shared_ptr<worklets::Serializable> 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<std::shared_ptr<worklets::Serializable>, uint64_t> separatorCell() const;
RowShape shape; // set by the platform view before it binds with a new shape

std::unordered_map<int, std::unique_ptr<Holder>> holders;
StoreListener* listener = nullptr;
Expand All @@ -65,6 +78,8 @@ class Store : public std::enable_shared_from_this<Store> {
std::shared_ptr<const FlumeRuntime> flume; // the runtime of the values below, declared first so it dies last
std::optional<facebook::jsi::Function> renderCellFn;
uint64_t renderCellVersion = 0;
std::optional<facebook::jsi::Function> separatorCellFn;
uint64_t separatorCellVersion = 0;
ItemCache items;
uint64_t retainedGeneration = 0;
} slot;
Expand All @@ -73,6 +88,8 @@ class Store : public std::enable_shared_from_this<Store> {
mutable std::mutex mutex_;
std::shared_ptr<worklets::Serializable> renderCell_;
uint64_t renderCellVersion_ = 0;
std::shared_ptr<worklets::Serializable> separatorCell_;
uint64_t separatorCellVersion_ = 0;
};

} // namespace flume
12 changes: 12 additions & 0 deletions cpp/core/KeyDiff.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -101,4 +101,16 @@ ListOps diffKeys(const Keys& previous, const Keys& next, const std::vector<int>&
return ops;
}

std::vector<int> rebound(const ListOps& ops) {
std::vector<int> 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
7 changes: 7 additions & 0 deletions cpp/core/KeyDiff.h
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,16 @@ struct ListOps {
std::vector<Range> inserted; // next positions, ascending
std::vector<std::pair<int, int>> moved; // from, to; sequential on the order left by removes then inserts
std::vector<int> changed; // next positions of changed items that already existed
std::vector<int> neighbors; // next positions of worklet rows whose separator changed, none of them changed
std::vector<int> 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<int> 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;

Expand Down
Loading
Loading