fix: add focus nodes on nested artboards to main focus tree when added to main artboard (#12788) 90140f105b * fix: add focus nodes on nested artboards to main focus tree when added to main artboard * reconcile changes with artboard lists work * fix test * fix some dead reference cases on the focus tree management * prevent unnecessary blur on focus tree rebuild * clean up comments * fix clang issues * clarify js doc on hasFocusNodes Co-authored-by: Zachary Plata <zach@rive.app>
diff --git a/.rive_head b/.rive_head index 07ac448..ec53e13 100644 --- a/.rive_head +++ b/.rive_head
@@ -1 +1 @@ -476a0f6f85fff4bd0126576b9d7f4ca9404f4a15 +90140f105b84682dd5e6021cace4e64b95250e14
diff --git a/include/rive/input/focus_manager.hpp b/include/rive/input/focus_manager.hpp index 41f9962..42b8573 100644 --- a/include/rive/input/focus_manager.hpp +++ b/include/rive/input/focus_manager.hpp
@@ -143,10 +143,19 @@ } #endif + /// True if any node in the tree is backed by focusable data or can take + /// focus — even while currently ineligible for traversal. Structural + /// scopes (unbacked, canFocus=false) don't count on their own. Gates + /// one-time keyboard setup in high-level runtimes via + /// StateMachineInstance::hasFocusNodes(). + bool hasFocusableContent() const; + private: rcp<FocusNode> m_primaryFocus; std::vector<rcp<FocusNode>> m_rootNodes; void removeManager(rcp<FocusNode>); + // Erase a node from m_rootNodes if present (no-op otherwise). + void eraseRoot(const rcp<FocusNode>& node); #ifdef WITH_RIVE_TOOLS FocusChangedCallback m_focusChangedCallback = nullptr; ScrollIntoViewCallback m_scrollIntoViewCallback = nullptr;
diff --git a/include/rive/input/focus_node.hpp b/include/rive/input/focus_node.hpp index 3b771c3..1456a1f 100644 --- a/include/rive/input/focus_node.hpp +++ b/include/rive/input/focus_node.hpp
@@ -29,6 +29,21 @@ { public: FocusNode(Focusable* focusable = nullptr) : m_focusable(focusable) {} + ~FocusNode(); + + // Transparent structural scope: unbacked (no Focusable) and never a focus + // target itself. Traversal descends through it to reach focusable + // descendants (see focusNodeTraversable); empty scopes contribute no + // focus stops. Used by data-bound nested-artboard hosts and component + // lists. + static rcp<FocusNode> makeStructuralScope() + { + auto node = make_rcp<FocusNode>(); + node->canFocus(false); + node->canTraverse(false); + node->canTouch(false); + return node; + } // === Focusable ===
diff --git a/include/rive/nested_artboard.hpp b/include/rive/nested_artboard.hpp index 81f2fd2..8c03410 100644 --- a/include/rive/nested_artboard.hpp +++ b/include/rive/nested_artboard.hpp
@@ -14,6 +14,8 @@ #include "rive/advancing_component.hpp" #include "rive/resetting_component.hpp" #include "rive/viewmodel/viewmodel_instance_artboard.hpp" +#include "rive/input/focus_node.hpp" +#include "rive/nested_artboard_host_flags.hpp" #include "rive/refcnt.hpp" #include "rive/file.hpp" #include <stdio.h> @@ -22,6 +24,7 @@ { class ArtboardInstance; +class FocusManager; class NestedAnimation; class NestedArtboardOrigin; class NestedInput; @@ -52,16 +55,18 @@ // construction ref; this list holds an extra ref (see ref_rcp in // onAddedClean) so it stays valid regardless of teardown ordering. std::vector<rcp<ViewModelInstance>> m_globalViewModelInstances; + /// Structural scope for data-bound hosts only + rcp<FocusNode> m_focusScope; -protected: private: void clearNestedAnimations(); float m_cumulatedSeconds = 0; // True if m_activeViewModelInstance is a dynamically-created bound VMI // that must be unref'd by this NestedArtboard. bool m_ownsActiveVmi = false; - bool m_hasPendingStatefulBinding = false; + NestedArtboardHostFlags m_hostFlags = NestedArtboardHostFlags::none; void nest(Artboard* artboard); + void detectArtboardDataBinding(); bool tryScheduleBindStateful(); void bindStateful(); // Walks children() for the first ViewModelInstance child (the stateful @@ -69,8 +74,42 @@ ViewModelInstance* findStatefulChildVmi() const; // Releases the current active VMI if owned, then assigns the new one. void setActiveViewModelInstance(ViewModelInstance* vmi, bool owns); + /// Create/attach this host's persistent focus scope (data-bound hosts + /// only). With `place` true (full build pass) the scope is re-appended + /// under `parentNode` so append order matches the hierarchy walk; with + /// `place` false an already-registered scope is never moved. + void registerFocusScope(FocusManager* focusManager, + rcp<FocusNode> parentNode, + bool place); public: + /// True when this host can receive runtime artboard swaps and therefore + /// owns (or will own) a persistent focus scope. + bool isArtboardDataBound() const + { + return enums::is_flag_set(m_hostFlags, + NestedArtboardHostFlags::artboardDataBound); + } + + /// Register this host's focus scope (if data-bound) and rebuild the nested + /// instance focus tree under the parent FocusManager. Called from the + /// hierarchical focus-tree build (Artboard::buildFocusTree) and from the + /// data-bound artboard swap path. + /// @param fallbackParent Parent used when the host has no closest ancestor + /// FocusNode. + /// @param placeScope True only from the full build pass, which is the + /// ordering authority: the scope is re-appended at the walk's + /// current position. All other callers leave placement untouched. + /// @param forceRebuild When true (the default), always tear down and + /// rebuild the nested instance's focus subtree. When false, skip the + /// rebuild if the subtree already shares this manager, preserving + /// focus resting inside an untouched instance. The full build pass + /// passes false unless it just re-wired the manager (which rebuilds + /// at the root and requires re-homing). + void syncNestedFocusTree(rcp<FocusNode> fallbackParent, + bool placeScope = false, + bool forceRebuild = true); + NestedArtboard(); ~NestedArtboard() override; StatusCode onAddedClean(CoreContext* context) override;
diff --git a/include/rive/nested_artboard_host_flags.hpp b/include/rive/nested_artboard_host_flags.hpp new file mode 100644 index 0000000..944f5f5 --- /dev/null +++ b/include/rive/nested_artboard_host_flags.hpp
@@ -0,0 +1,23 @@ +#ifndef _RIVE_NESTED_ARTBOARD_HOST_FLAGS_HPP_ +#define _RIVE_NESTED_ARTBOARD_HOST_FLAGS_HPP_ + +#include "rive/enums.hpp" +#include <cstdint> + +namespace rive +{ + +/// Runtime-only flags stored in NestedArtboard::m_hostFlags (not serialized). +enum class NestedArtboardHostFlags : uint8_t +{ + none = 0, + /// Stateful VM binding is scheduled and should run on next advance. + pendingStatefulBinding = 1 << 0, + /// artboardId is data-bound (VM artboard property); host needs a focus + /// scope for runtime-swappable nested artboards. + artboardDataBound = 1 << 1, +}; + +} // namespace rive + +#endif
diff --git a/src/animation/nested_state_machine.cpp b/src/animation/nested_state_machine.cpp index 31e4d8e..f8557cc 100644 --- a/src/animation/nested_state_machine.cpp +++ b/src/animation/nested_state_machine.cpp
@@ -40,12 +40,8 @@ auto* parentFM = parentArtboard->focusManager(); m_StateMachineInstance->setExternalFocusManager(parentFM); - // Find closest focus node (handles artboard boundaries) - auto parentNode = - FocusData::findClosestFocusNode(nestedArtboard); - - // Build nested artboard's focus tree under parent - artboard->buildFocusTree(parentFM, parentNode); + nestedArtboard->syncNestedFocusTree( + FocusData::findClosestFocusNode(nestedArtboard)); } } }
diff --git a/src/animation/state_machine_instance.cpp b/src/animation/state_machine_instance.cpp index 48b5f9f..9afa31e 100644 --- a/src/animation/state_machine_instance.cpp +++ b/src/animation/state_machine_instance.cpp
@@ -3217,7 +3217,7 @@ { auto* fm = focusManager(); assert(fm != nullptr); - return !fm->rootNodes().empty(); + return fm->hasFocusableContent(); } bool StateMachineInstance::focusNext()
diff --git a/src/artboard.cpp b/src/artboard.cpp index 4a561e1..08db63b 100644 --- a/src/artboard.cpp +++ b/src/artboard.cpp
@@ -1926,13 +1926,13 @@ if (component->is<NestedArtboard>()) { auto* nestedHost = component->as<NestedArtboard>(); - auto* nestedArtboard = nestedHost->artboardInstance(0); - if (nestedArtboard != nullptr && - nestedArtboard->focusManager() != focusManager) - { - nestedArtboard->cleanupFocusTree(); - nestedArtboard->buildFocusTree(focusManager, focusNode); - } + // Wire the nested state machines to this manager before placing the + // scope: setExternalFocusManager rebuilds the nested focus tree at the + // manager root, so it must run first. Track whether any was actually + // re-wired — a re-wire leaves the tree at the root and requires + // re-homing under the scope (forceRebuild); an already-wired tree is + // left in place. + bool rewired = false; for (auto* animation : nestedHost->nestedAnimations()) { if (animation->is<NestedStateMachine>()) @@ -1942,9 +1942,19 @@ if (smi != nullptr && smi->focusManager() != focusManager) { smi->setExternalFocusManager(focusManager); + rewired = true; } } } + // Scope placement must be the final write so it overrides the root + // rebuild above. For data-bound hosts this parents the nested focus + // tree under the host's persistent structural scope; static hosts + // build directly under focusNode. placeScope=true: the build pass is + // the ordering authority — the scope is re-appended at the walk's + // position. + nestedHost->syncNestedFocusTree(focusNode, + /*placeScope=*/true, + /*forceRebuild=*/rewired); } else if (component->is<ArtboardComponentList>()) { @@ -2043,11 +2053,18 @@ if (obj != nullptr && obj->is<FocusData>()) { auto* fd = obj->as<FocusData>(); - // Only remove if the FocusNode was created (lazy initialization) - // and is still registered with THIS manager (defensive check for - // cases where auto-cleanup via FocusData destructor already ran) auto node = fd->focusNode(); - if (node != nullptr && node->manager() == m_activeFocusManager) + if (node == nullptr) + { + // FocusNode never lazily created — nothing to remove. + continue; + } + // Remove the node when it belongs to this manager, or when its + // manager was nulled by an ancestor removal while it is still + // attached (removeChild clears m_manager across a removed subtree). + // Nodes owned by a DIFFERENT live manager are left untouched. + if (node->manager() == m_activeFocusManager || + (node->manager() == nullptr && node->parent() != nullptr)) { m_activeFocusManager->removeChild(node); }
diff --git a/src/artboard_component_list.cpp b/src/artboard_component_list.cpp index 7e52579..efe62ac 100644 --- a/src/artboard_component_list.cpp +++ b/src/artboard_component_list.cpp
@@ -385,21 +385,12 @@ } if (m_listScopeFocusNode == nullptr) { - m_listScopeFocusNode = rcp<FocusNode>(new FocusNode(nullptr)); - m_listScopeFocusNode->canFocus(true); - m_listScopeFocusNode->canTraverse(true); + m_listScopeFocusNode = FocusNode::makeStructuralScope(); m_listScopeFocusNode->name("ArtboardComponentListScope"); } - if (m_listScopeFocusNode->manager() == focusManager) - { - if (m_listScopeFocusNode->parent() == hostParent.get() || - (m_listScopeFocusNode->parent() == nullptr && - hostParent == nullptr)) - { - syncListRowNodesWithList(focusManager); - return; - } - } + // Only called from the full build pass (buildFocusTreeVisit), which is + // the ordering authority: always re-append so the scope sits at the + // walk's current position focusManager->addChild(std::move(hostParent), m_listScopeFocusNode); syncListRowNodesWithList(focusManager); } @@ -433,9 +424,10 @@ rcp<FocusNode> ArtboardComponentList::makeListRowFocusNode() const { - auto node = rcp<FocusNode>(new FocusNode(nullptr)); - node->canFocus(true); - node->canTraverse(true); + // Structural rows: rows with focusable content are descended through; + // rows for items with no focusables are skipped entirely instead of + // becoming invisible focus stops. + auto node = FocusNode::makeStructuralScope(); node->name("ArtboardComponentListRow"); return node; } @@ -469,6 +461,57 @@ } } +namespace +{ +// True if the artboard contains any focus content at any depth: authored +// FocusData, or a data-bound nested artboard host (whose persistent scope +// counts as focus content even while its current artboard has no focusables — +// a later swap can materialize focus nodes under it). Recurses through both +// host kinds — single nested artboards and component lists +bool artboardHasFocusContent(Artboard* artboard) +{ + if (artboard == nullptr) + { + return false; + } + if (artboard->rootFocusDataCount() > 0) + { + return true; + } + for (auto* host : artboard->nestedArtboards()) + { + if (host == nullptr) + { + continue; + } + if (host->isArtboardDataBound()) + { + return true; + } + if (artboardHasFocusContent(host->artboardInstance(0))) + { + return true; + } + } + for (auto* list : artboard->artboardComponentLists()) + { + if (list == nullptr) + { + continue; + } + // A component list is bound to a VM list property and always owns a + // structural scope (ensureListScopeFocusNode); its items — and their + // focusables — can populate at runtime, exactly like a data-bound + // nested-artboard host swap. Count the list itself as latent focus + // content (symmetric with the isArtboardDataBound() host check above) + // so the enclosing item is rebuilt under its row while the inner list + // is still empty, keeping tab order correct once it fills. + return true; + } + return false; +} +} // namespace + bool ArtboardComponentList::listItemNeedsBuildUnderRow(FocusManager* parentFM, ArtboardInstance* inst, rcp<FocusNode> row) const @@ -481,9 +524,12 @@ { return true; } - // If the artboard has focusables but the row is empty, focus is still - // attached under the list scope (legacy) and must be rebuilt on the row. - if (row->children().empty() && inst->rootFocusDataCount() > 0) + // If the artboard has focus content but the row is empty, that content is + // attached outside the row (setExternalFocusManager builds at the manager + // root) and must be rebuilt under the row. Focus content includes + // data-bound host scopes at any depth, not just authored FocusData, so a + // later swap materializes focus nodes at the row's position. + if (row->children().empty() && artboardHasFocusContent(inst)) { return true; } @@ -592,6 +638,15 @@ { continue; } + // Wire the item's state machine to the shared manager first: + // setExternalFocusManager rebuilds the item's focus tree at the manager + // root, so it must run before building under the row. Same "wire first, + // place last" ordering as buildFocusTreeVisit and updateArtboard. + auto* smi = stateMachineInstance(i); + if (smi != nullptr && smi->focusManager() != fm) + { + smi->setExternalFocusManager(fm); + } if (listItemNeedsBuildUnderRow(fm, inst, row)) { if (inst->focusManager() != nullptr) @@ -600,11 +655,6 @@ } inst->buildFocusTree(fm, row); } - auto* smi = stateMachineInstance(i); - if (smi != nullptr && smi->focusManager() != fm) - { - smi->setExternalFocusManager(fm); - } } }
diff --git a/src/input/focus_manager.cpp b/src/input/focus_manager.cpp index 3a5cd47..68859c0 100644 --- a/src/input/focus_manager.cpp +++ b/src/input/focus_manager.cpp
@@ -179,33 +179,8 @@ return; } - // Remove from old location first - if (child->parent()) - { - child->removeFromParent(); - } - else - { - // Remove from root nodes if it was a root - auto it = std::find(m_rootNodes.begin(), m_rootNodes.end(), child); - if (it != m_rootNodes.end()) - { - m_rootNodes.erase(it); - } - } - - // Set the manager reference on the child - child->m_manager = this; - - if (parent) - { - parent->addChild(std::move(child)); - } - else - { - // Add to root nodes - m_rootNodes.push_back(std::move(child)); - } + size_t index = parent ? parent->children().size() : m_rootNodes.size(); + addChild(std::move(parent), std::move(child), index); } void FocusManager::addChild(rcp<FocusNode> parent, @@ -220,13 +195,17 @@ { child->removeFromParent(); } + else if (child->m_manager != nullptr && child->m_manager != this) + { + // The child is a root of a DIFFERENT manager (e.g. a scope migrating + // from a nested state machine's internal manager to the parent). Erase + // it from that manager's root list so it belongs to exactly one + // manager. + child->m_manager->eraseRoot(child); + } else { - auto it = std::find(m_rootNodes.begin(), m_rootNodes.end(), child); - if (it != m_rootNodes.end()) - { - m_rootNodes.erase(it); - } + eraseRoot(child); } child->m_manager = this; if (parent) @@ -257,8 +236,11 @@ clearFocus(); } - // Clear the manager reference - child->m_manager = nullptr; + // Removing a node takes its whole subtree out of the manager, so clear + // m_manager on every descendant too: a descendant held elsewhere (e.g. a + // persistent NestedArtboard scope) must not retain a pointer to a manager + // it no longer belongs to. + removeManager(child); if (child->parent()) { @@ -266,12 +248,16 @@ } else { - // Remove from root nodes - auto it = std::find(m_rootNodes.begin(), m_rootNodes.end(), child); - if (it != m_rootNodes.end()) - { - m_rootNodes.erase(it); - } + eraseRoot(child); + } +} + +void FocusManager::eraseRoot(const rcp<FocusNode>& node) +{ + auto it = std::find(m_rootNodes.begin(), m_rootNodes.end(), node); + if (it != m_rootNodes.end()) + { + m_rootNodes.erase(it); } } @@ -331,12 +317,17 @@ return false; } -// Helper to check if a node is a leaf (no traversable children) +static bool focusNodeTraversable(FocusNode* node); + +// Helper to check if a node is a leaf (no traversable children). Uses the same +// predicate as Tab traversal so directional navigation and Tab agree on what +// counts as a scope: a child that is a transparent structural scope (canFocus +// false) still makes this node a non-leaf when a focusable lives beneath it. static bool isLeaf(FocusNode* node) { for (const auto& child : node->children()) { - if (child->canFocus() && child->canTraverse()) + if (focusNodeTraversable(child.get())) { return false; } @@ -362,6 +353,34 @@ } } +static bool subtreeHasFocusableContent(const std::vector<rcp<FocusNode>>& nodes) +{ + for (const auto& node : nodes) + { + // A node backed by focusable data counts even while it is currently + // ineligible for traversal: eligibility (collapse, hidden ancestors) + // and canFocus/canTraverse are runtime state that can change on any + // frame, while this signal gates one-time setup in high-level + // runtimes (e.g. attaching tab/shift+tab listeners in JS). Unbacked + // nodes with canFocus=false are structural scopes and don't count on + // their own. + if (node->focusable() != nullptr || node->canFocus()) + { + return true; + } + if (subtreeHasFocusableContent(node->children())) + { + return true; + } + } + return false; +} + +bool FocusManager::hasFocusableContent() const +{ + return subtreeHasFocusableContent(m_rootNodes); +} + // Calculate overlap on the orthogonal axis (perpendicular to navigation) // Returns the length of overlap, or 0 if no overlap static float calculateOverlap(float aMin, float aMax, float bMin, float bMax) @@ -799,6 +818,31 @@ #endif } +static bool hasEligibleTraversableChildInFocusTree(FocusNode* node); + +// True if this node is a focusable traversal target itself, or the transparent +// scope of a data-bound nested artboard that we descend through to reach its +// focusable descendants. +static bool focusNodeTraversable(FocusNode* node) +{ + if (node == nullptr) + { + return false; + } + if (focusNodeEligibleForTraversal(node)) + { + return true; + } + // The data-bound nested-artboard scope is the only runtime FocusNode with + // no Focusable: descend through such an unbacked node. Authored + // canFocus=false nodes keep their Focusable and stay non-traversable + if (node->focusable() != nullptr) + { + return false; + } + return hasEligibleTraversableChildInFocusTree(node); +} + std::vector<FocusNode*> FocusManager::getTraversableNodes( FocusNode* scope) const { @@ -810,7 +854,7 @@ for (const auto& child : *childList) { - if (focusNodeEligibleForTraversal(child.get())) + if (focusNodeTraversable(child.get())) { result.push_back(child.get()); } @@ -830,7 +874,7 @@ { for (const auto& ch : node->children()) { - if (focusNodeEligibleForTraversal(ch.get())) + if (focusNodeTraversable(ch.get())) { return true; }
diff --git a/src/input/focus_node.cpp b/src/input/focus_node.cpp index a97eb85..430ac37 100644 --- a/src/input/focus_node.cpp +++ b/src/input/focus_node.cpp
@@ -9,18 +9,20 @@ namespace rive { +FocusNode::~FocusNode() +{ + // A child held elsewhere via rcp (a NestedArtboard's persistent focus + // scope, an ArtboardComponentList row) can outlive this node, so clear its + // back-pointer to keep m_parent from dangling. + for (const auto& child : m_children) + { + child->m_parent = nullptr; + } +} + void FocusNode::addChild(rcp<FocusNode> child) { - if (!child) - { - return; - } - - // Remove from old parent if exists - child->removeFromParent(); - - child->m_parent = this; - m_children.push_back(std::move(child)); + insertChild(m_children.size(), std::move(child)); } void FocusNode::insertChild(size_t index, rcp<FocusNode> child)
diff --git a/src/nested_artboard.cpp b/src/nested_artboard.cpp index 01a8ec5..58be9b2 100644 --- a/src/nested_artboard.cpp +++ b/src/nested_artboard.cpp
@@ -5,6 +5,10 @@ #include "rive/file.hpp" #include "rive/importers/import_stack.hpp" #include "rive/importers/backboard_importer.hpp" +#include "rive/data_bind/data_bind.hpp" +#include "rive/data_bind/data_values/data_type.hpp" +#include "rive/focus_data.hpp" +#include "rive/input/focus_manager.hpp" #include "rive/input/focusable.hpp" #include "rive/nested_animation.hpp" #include "rive/animation/nested_state_machine.hpp" @@ -68,10 +72,17 @@ } m_activeViewModelInstance = nullptr; m_ownsActiveVmi = false; - m_hasPendingStatefulBinding = false; // Release our extra refs on the global VMI children (the artboard's // m_Objects still holds its own ref for each). m_globalViewModelInstances.clear(); + + // Scope outlives nested instance swaps; remove from parent FocusManager + // when the host component is destroyed. + if (m_focusScope != nullptr && m_focusScope->manager() != nullptr) + { + m_focusScope->manager()->removeChild(m_focusScope); + } + m_focusScope = nullptr; } Core* NestedArtboard::clone() const @@ -79,6 +90,14 @@ NestedArtboard* nestedArtboard = static_cast<NestedArtboard*>(NestedArtboardBase::clone()); nestedArtboard->file(file()); + // Carry the swap-slot flag to clones. It is detected on the SOURCE + // artboard's host (import populates the source's data binds before + // onAddedClean) + if (isArtboardDataBound()) + { + nestedArtboard->m_hostFlags |= + NestedArtboardHostFlags::artboardDataBound; + } if (m_referencedArtboard == nullptr) { return nestedArtboard; @@ -139,7 +158,7 @@ if (m_activeViewModelInstance != nullptr && artboardInstance()) { - m_hasPendingStatefulBinding = true; + m_hostFlags |= NestedArtboardHostFlags::pendingStatefulBinding; return true; } return false; @@ -147,7 +166,7 @@ void NestedArtboard::bindStateful() { - m_hasPendingStatefulBinding = false; + m_hostFlags &= ~NestedArtboardHostFlags::pendingStatefulBinding; if (artboardInstance() == nullptr) { return; @@ -209,15 +228,42 @@ void NestedArtboard::updateArtboard( ViewModelInstanceArtboard* viewModelInstanceArtboard) { + // A VM artboard swap means this host is data-bound. + m_hostFlags |= NestedArtboardHostFlags::artboardDataBound; + + // Resolve the swap target BEFORE tearing anything down. asset == nullptr + // and propertyValue == -1 is the user explicitly clearing the artboard (a + // real "set to null"); any OTHER unresolvable id must leave the currently + // displayed artboard — and its focus tree — untouched, rather than blanking + // focus for content that stays on screen. findArtboard has no side effects, + // so resolving it early is safe. + bool explicitNull = viewModelInstanceArtboard != nullptr && + viewModelInstanceArtboard->asset() == nullptr && + viewModelInstanceArtboard->propertyValue() == -1; + Artboard* artboard = + explicitNull + ? nullptr + : findArtboard(viewModelInstanceArtboard, parentArtboard(), m_file); + if (!explicitNull && artboard == nullptr) + { + // Unresolved target — keep the outgoing instance and its focus intact. + return; + } + + // Detach the outgoing instance's focus tree BEFORE teardown, while every + // component is still alive: clearing focus runs blur callbacks + // (FocusData::blurred walks parents/siblings), which must act on live + // components rather than partially-destroyed ones. + auto* outgoing = artboardInstance(0); + if (outgoing != nullptr) + { + outgoing->cleanupFocusTree(); + } clearDataContext(); clearNestedAnimations(); m_boundNestedStateMachine = nullptr; - // If asset == nullptr and propertyValue == -1, it means that the user - // explicitly set the asset to null, so only in that case we clear the - // artboard - if (viewModelInstanceArtboard != nullptr && - viewModelInstanceArtboard->asset() == nullptr && - viewModelInstanceArtboard->propertyValue() == -1) + + if (explicitNull) { if (m_referencedArtboard) { @@ -229,8 +275,6 @@ return; } - Artboard* artboard = - findArtboard(viewModelInstanceArtboard, parentArtboard(), m_file); if (artboard != nullptr) { auto artboardInstance = artboard->instance(); @@ -304,9 +348,140 @@ } // TODO: @hernan review what dirt to add addDirt(ComponentDirt::Filthy); + + // Share the parent's focus manager with the swapped-in artboard's + // state machine BEFORE the focus sync: its listener groups (pointer + // focus, key/text input) must act on the same focus state Tab + // traversal uses. The wiring in + // NestedStateMachine::initializeAnimation is skipped here because the + // runtime-created bound state machine is unparented. + auto* parentAb = parentArtboard(); + auto* parentFM = + parentAb != nullptr ? parentAb->focusManager() : nullptr; + if (parentFM != nullptr && m_boundNestedStateMachine != nullptr) + { + auto* smi = m_boundNestedStateMachine->stateMachineInstance(); + if (smi != nullptr && smi->focusManager() != parentFM) + { + smi->setExternalFocusManager(parentFM); + } + } + // Re-home the nested instance's focus tree under the host's scope. + // setExternalFocusManager above rebuilds the nested tree at the + // manager root, so scope placement must be the final write. + syncNestedFocusTree(FocusData::findClosestFocusNode(this)); } } +// Focus tree integration for data-bound nested artboards. +// +// When artboardId is bound to a VM artboard property the nested instance can be +// swapped at runtime (e.g. Plain -> Focusable), so its FocusData leaves must +// live in the *parent* StateMachine's FocusManager for Tab order to work across +// the main artboard and nested content. Each data-bound host owns one +// structural m_focusScope (see registerFocusScope) that persists across swaps; +// static nested artboards get no scope and zero extra FocusNode cost. + +void NestedArtboard::detectArtboardDataBinding() +{ + // Marks hosts that can receive runtime + // artboard swaps so a focus scope is allocated later at tree-build time. + // Only a direct bind of this host's artboardId counts. Match on the + // bind's target property key: it is static file data, available at + // import time on the source artboard + if (isArtboardDataBound()) + { + return; + } + auto* parent = artboard(); + if (parent != nullptr) + { + for (auto* dataBind : parent->dataBinds()) + { + if (dataBind->target() == this && + dataBind->propertyKey() == + NestedArtboardBase::artboardIdPropertyKey) + { + m_hostFlags |= NestedArtboardHostFlags::artboardDataBound; + return; + } + } + } +} + +void NestedArtboard::registerFocusScope(FocusManager* focusManager, + rcp<FocusNode> parentNode, + bool place) +{ + // No-op for static hosts; data-bound hosts lazily get one persistent scope. + if (focusManager == nullptr || !isArtboardDataBound()) + { + return; + } + + if (m_focusScope == nullptr) + { + m_focusScope = FocusNode::makeStructuralScope(); + } + + if (!place && m_focusScope->manager() == focusManager) + { + // Ensure-only callers (state machine init, artboard swap) must never + // move an already-registered scope: the full build pass is the only + // ordering authority. + return; + } + + // Build pass placement, or first registration. During the depth-first + // build pass every sibling that should precede this scope has already been + // re-appended by the same walk, so appending yields hierarchy order. A + // first registration outside a pass is best-effort (appended under the + // caller's fallback parent) and is normalized by the next build pass. + focusManager->addChild(std::move(parentNode), m_focusScope); +} + +void NestedArtboard::syncNestedFocusTree(rcp<FocusNode> fallbackParent, + bool placeScope, + bool forceRebuild) +{ + auto* parentAb = artboard(); + auto* parentFM = parentAb != nullptr ? parentAb->focusManager() : nullptr; + if (parentFM == nullptr) + { + return; + } + + // Place the structural scope first — even with no nested instance yet — so + // a data-bound host whose artboard starts null still has its scope at the + // authored tab position for a later swap to build under. Placement is a + // non-destructive move (addChild), so it never clears focus. + registerFocusScope(parentFM, fallbackParent, placeScope); + + auto* nestedInstance = artboardInstance(0); + if (nestedInstance == nullptr) + { + return; + } + + // Skip the destructive teardown+rebuild when the subtree already shares + // this manager and was not just re-wired (forceRebuild): rebuilding an + // untouched nested instance clears focus resting inside it, while the scope + // placement above already keeps tab order correct. forceRebuild is set + // after setExternalFocusManager (which rebuilds at the manager root) or on + // a swap. + if (!forceRebuild && nestedInstance->focusManager() == parentFM) + { + return; + } + + nestedInstance->cleanupFocusTree(); + // Under the scope when data-bound, else under fallbackParent (the caller's + // resolved closest ancestor). + nestedInstance->buildFocusTree(parentFM, + m_focusScope != nullptr ? m_focusScope + : fallbackParent); +} + static Mat2D makeTranslate(const Artboard* artboard) { return Mat2D::fromTranslate(-artboard->originX() * artboard->width(), @@ -443,6 +618,7 @@ } } tryScheduleBindStateful(); + detectArtboardDataBinding(); return Super::onAddedClean(context); } @@ -792,7 +968,8 @@ { return false; } - if (m_hasPendingStatefulBinding) + if (enums::is_flag_set(m_hostFlags, + NestedArtboardHostFlags::pendingStatefulBinding)) { bindStateful(); }
diff --git a/tests/unit_tests/assets/bindable_focus_tree_swap.riv b/tests/unit_tests/assets/bindable_focus_tree_swap.riv new file mode 100644 index 0000000..f7e0286 --- /dev/null +++ b/tests/unit_tests/assets/bindable_focus_tree_swap.riv Binary files differ
diff --git a/tests/unit_tests/assets/swappable_artboards_focus.riv b/tests/unit_tests/assets/swappable_artboards_focus.riv new file mode 100644 index 0000000..134c5a0 --- /dev/null +++ b/tests/unit_tests/assets/swappable_artboards_focus.riv Binary files differ
diff --git a/tests/unit_tests/runtime/focus_test.cpp b/tests/unit_tests/runtime/focus_test.cpp index c3d6ed9..392e03c 100644 --- a/tests/unit_tests/runtime/focus_test.cpp +++ b/tests/unit_tests/runtime/focus_test.cpp
@@ -5,6 +5,7 @@ #include "rive/animation/transition_focus_condition.hpp" #include "rive/animation/transition_property_component_comparator.hpp" #include "rive/animation/listener_invocation.hpp" +#include "rive/animation/nested_state_machine.hpp" #include "rive/animation/state_machine.hpp" #include "rive/animation/state_machine_instance.hpp" #include "rive/artboard.hpp" @@ -16,6 +17,8 @@ #include "utils/no_op_factory.hpp" #include "utils/serializing_factory.hpp" #include "rive_file_reader.hpp" +#include "rive/nested_artboard.hpp" +#include "rive/viewmodel/viewmodel_instance_artboard.hpp" #include "rive/viewmodel/viewmodel_instance_boolean.hpp" #include "rive/viewmodel/viewmodel_instance_number.hpp" #include "rive/animation/listener_invocation.hpp" @@ -64,6 +67,9 @@ void focused() override { focusedCount++; } void blurred() override { blurredCount++; } + + bool eligible = true; + bool isEligibleForFocusTraversal() const override { return eligible; } }; // ============================================================================= @@ -634,6 +640,74 @@ CHECK(node->manager() == nullptr); } +TEST_CASE("Freeing a FocusNode clears the parent pointer of a child that " + "outlives it", + "[FocusManager]") +{ + FocusManager manager; + auto scope = make_rcp<FocusNode>(); // persistent host scope, held here + { + auto row = make_rcp<FocusNode>(); // transient list row + manager.addChild(nullptr, row); + manager.addChild(row, scope); + CHECK(scope->parent() == row.get()); + // The list re-sync removes the row from the manager, then drops it. + manager.removeChild(row); + } // row FocusNode destroyed here; scope survives via the outer rcp + + REQUIRE(scope->parent() == nullptr); + + // Re-homing the survivor is now safe — no dereference of the freed row. + auto newParent = make_rcp<FocusNode>(); + manager.addChild(nullptr, newParent); + manager.addChild(newParent, scope); + CHECK(scope->parent() == newParent.get()); + CHECK(newParent->children().size() == 1); +} + +TEST_CASE("FocusManager::addChild removes a migrating root from its previous " + "manager", + "[FocusManager]") +{ + FocusManager internalManager; + FocusManager parentManager; + auto scope = make_rcp<FocusNode>(); + + internalManager.addChild(nullptr, scope); + CHECK(scope->manager() == &internalManager); + CHECK(internalManager.rootNodes().size() == 1); + + // Migrate the scope to the parent manager (no FocusNode parent -> root). + parentManager.addChild(nullptr, scope); + CHECK(scope->manager() == &parentManager); + CHECK(parentManager.rootNodes().size() == 1); + + // The internal manager must no longer reference the migrated scope. + CHECK(internalManager.rootNodes().empty()); +} + +TEST_CASE("A migrated focus scope survives destruction of its previous manager", + "[FocusManager]") +{ + FocusManager parentManager; + auto scope = make_rcp<FocusNode>(); + { + FocusManager internalManager; + internalManager.addChild(nullptr, scope); + parentManager.addChild(nullptr, scope); // migrate to parent + CHECK(scope->manager() == &parentManager); + } // internalManager destroyed here + + // The scope still belongs to parentManager, not the destroyed one. + CHECK(scope->manager() == &parentManager); + + if (scope->manager() != nullptr) + { + scope->manager()->removeChild(scope); + } + CHECK(parentManager.rootNodes().empty()); +} + TEST_CASE("FocusManager traversal backward from first leaf exits scope", "[FocusManager]") { @@ -698,6 +772,182 @@ CHECK(manager.primaryFocus() == node1); } +TEST_CASE("StateMachineInstance hasFocusNodes ignores non-traversable scopes", + "[FocusManager]") +{ + NoOpFactory factory; + Artboard artboard(&factory); + auto instance = artboard.instance(); + StateMachine machine; + StateMachineInstance smi(&machine, instance.get()); + + auto scope = make_rcp<FocusNode>(); + scope->canFocus(false); + scope->canTraverse(false); + smi.focusManager()->addChild(nullptr, scope); + CHECK(smi.hasFocusNodes() == false); +} + +TEST_CASE("StateMachineInstance hasFocusNodes sees leaves under a " + "transparent scope", + "[FocusManager]") +{ + NoOpFactory factory; + Artboard artboard(&factory); + auto instance = artboard.instance(); + StateMachine machine; + StateMachineInstance smi(&machine, instance.get()); + + // Transparent structural scope as registered for a data-bound nested + // artboard host: unbacked (no focusable), canFocus/canTraverse/canTouch + // false. Traversal descends through it because it has no focusable. + auto scope = make_rcp<FocusNode>(); + scope->canFocus(false); + scope->canTraverse(false); + scope->canTouch(false); + smi.focusManager()->addChild(nullptr, scope); + + // Empty scope contributes no focus targets (e.g. a bindable artboard with + // no focus nodes). + CHECK(smi.hasFocusNodes() == false); + + // Swapping in an artboard that has a focusable leaf must make the state + // machine report focus nodes, even though the leaf lives under the scope. + auto leaf = make_rcp<FocusNode>(); + smi.focusManager()->addChild(scope, leaf); + CHECK(smi.hasFocusNodes() == true); +} + +TEST_CASE("StateMachineInstance hasFocusNodes counts focus data that is " + "currently ineligible for traversal", + "[FocusManager]") +{ + NoOpFactory factory; + Artboard artboard(&factory); + auto instance = artboard.instance(); + StateMachine machine; + StateMachineInstance smi(&machine, instance.get()); + + // hasFocusNodes gates one-time setup in high-level runtimes (attaching + // tab/shift+tab listeners in JS), so authored focus data must count even + // while it can't currently be focused: canFocus/canTraverse are + // data-bindable and collapse/visibility can change on any frame. + FocusData focusData; + // canFocus/canTraverse are now bits in the focusFlags bitmask; clear both + // (leave the rest) to make the node ineligible for traversal. + focusData.focusFlags( + focusData.focusFlags() & + ~(FocusData::canFocusBitmask | FocusData::canTraverseBitmask)); + smi.focusManager()->addChild(nullptr, focusData.focusNode()); + CHECK(smi.hasFocusNodes() == true); +} + +TEST_CASE("FocusManager traversal descends through a transparent scope " + "and keeps sibling order", + "[FocusManager]") +{ + FocusManager manager; + auto leafA = make_rcp<FocusNode>(); + auto scope = make_rcp<FocusNode>(); + auto leafC = make_rcp<FocusNode>(); + + // scope mirrors a data-bound nested artboard host slot sitting between two + // sibling focus nodes: unbacked (no focusable) and not a focus target + // itself, but Tab descends through it to whatever artboard is swapped in. + scope->canFocus(false); + scope->canTraverse(false); + scope->canTouch(false); + + manager.addChild(nullptr, leafA); + manager.addChild(nullptr, scope); + manager.addChild(nullptr, leafC); + + // Empty scope is skipped: A -> C. + manager.focusNext(); + CHECK(manager.primaryFocus() == leafA); + manager.focusNext(); + CHECK(manager.primaryFocus() == leafC); + + // Populate the scope (artboard swapped in). Its leaf occupies the scope's + // sibling slot, so traversal order becomes A -> B -> C. + manager.clearFocus(); + auto leafB = make_rcp<FocusNode>(); + manager.addChild(scope, leafB); + + manager.focusNext(); + CHECK(manager.primaryFocus() == leafA); + manager.focusNext(); + CHECK(manager.primaryFocus() == leafB); + manager.focusNext(); + CHECK(manager.primaryFocus() == leafC); +} + +TEST_CASE("FocusManager drops focus when a leaf under a transparent scope " + "becomes hidden", + "[FocusManager]") +{ + FocusManager manager; + // Unbacked scope: the shape of a data-bound nested artboard's scope node. + auto scope = make_rcp<FocusNode>(); + scope->canFocus(false); + scope->canTraverse(false); + scope->canTouch(false); + // A focusable leaf inside it, like a swapped-in nested artboard's element. + MockFocusable leafFocusable; + auto leaf = make_rcp<FocusNode>(&leafFocusable); + manager.addChild(nullptr, scope); + manager.addChild(scope, leaf); + + // Tab descends through the scope onto the nested leaf. + manager.focusNext(); + REQUIRE(manager.primaryFocus() == leaf); + + // Hide the nested content (its focusable reports ineligible). Focus must be + // dropped, not left stranded behind the scope. + leafFocusable.eligible = false; + manager.dropFocusIfFocusTargetHidden(); + CHECK(manager.primaryFocus() == nullptr); +} + +TEST_CASE("FocusManager rebuilding one scope's subtree preserves focus in a " + "sibling scope", + "[FocusManager]") +{ + FocusManager manager; + // Two sibling transparent scopes, like two data-bound nested artboard + // hosts. + auto scopeA = make_rcp<FocusNode>(); + scopeA->canFocus(false); + scopeA->canTraverse(false); + scopeA->canTouch(false); + auto scopeB = make_rcp<FocusNode>(); + scopeB->canFocus(false); + scopeB->canTraverse(false); + scopeB->canTouch(false); + + MockFocusable leafAFocusable, leafBFocusable; + auto leafA = make_rcp<FocusNode>(&leafAFocusable); + auto leafB = make_rcp<FocusNode>(&leafBFocusable); + manager.addChild(nullptr, scopeA); + manager.addChild(scopeA, leafA); + manager.addChild(nullptr, scopeB); + manager.addChild(scopeB, leafB); + + // Focus the leaf inside scope A. + manager.setFocus(leafA); + REQUIRE(manager.primaryFocus() == leafA); + + // Simulate swapping the artboard in sibling scope B: tear down B's current + // content and rebuild it with a new focusable leaf under the same scope. + // Focus held in the unrelated scope A must be untouched. + manager.removeChild(leafB); + MockFocusable leafB2Focusable; + auto leafB2 = make_rcp<FocusNode>(&leafB2Focusable); + manager.addChild(scopeB, leafB2); + + CHECK(manager.primaryFocus() == leafA); +} + TEST_CASE("FocusActionTraversal perform advances focus with traversalKind next", "[FocusActionTraversal]") { @@ -1193,6 +1443,115 @@ } // namespace rive +TEST_CASE("Swapping bindable artboard registers nested focus nodes for Tab", + "[silver]") +{ + rive::SerializingFactory silver; + auto file = ReadRiveFile("assets/bindable_focus_tree_swap.riv", &silver); + + auto artboard = file->artboardDefault(); + REQUIRE(artboard != nullptr); + silver.frameSize(artboard->width(), artboard->height()); + + auto stateMachine = artboard->stateMachineAt(0); + REQUIRE(stateMachine != nullptr); + + auto vmi = file->createDefaultViewModelInstance(artboard.get()); + REQUIRE(vmi != nullptr); + + stateMachine->bindViewModelInstance(vmi); + stateMachine->advanceAndApply(0.016f); + + auto* focusManager = stateMachine->focusManager(); + REQUIRE(focusManager != nullptr); + REQUIRE(stateMachine->hasFocusNodes() == true); + + focusManager->focusNext(); + stateMachine->advanceAndApply(0.016f); + REQUIRE(focusManager->primaryFocus() != nullptr); + + CHECK(stateMachine->focusNext() == false); + // There's only one focus node in the main artboard, go back to that last + // node + stateMachine->focusPrevious(); + + auto* artboardProp = vmi->propertyValue("bindedArt"); + REQUIRE(artboardProp != nullptr); + REQUIRE(artboardProp->is<rive::ViewModelInstanceArtboard>()); + auto* vmiArtboard = artboardProp->as<rive::ViewModelInstanceArtboard>(); + + // Has other focus nodes in this artboard + auto focusableSource = file->bindableArtboardNamed("Focusable"); + REQUIRE(focusableSource != nullptr); + + vmiArtboard->asset(focusableSource); + stateMachine->advanceAndApply(0.016f); + + rive::NestedArtboard* focusableHost = nullptr; + for (auto* nestedHost : artboard->nestedArtboards()) + { + auto* source = nestedHost->sourceArtboard(); + if (source != nullptr && source->name() == "Focusable") + { + focusableHost = nestedHost; + break; + } + } + REQUIRE(focusableHost != nullptr); + auto* focusableInstance = focusableHost->artboardInstance(0); + REQUIRE(focusableInstance != nullptr); + + CHECK(stateMachine->focusNext() == true); + CHECK(focusManager->primaryFocus() != nullptr); + CHECK(focusManager->primaryFocusImmediateArtboard() == focusableInstance); +} + +TEST_CASE("Swapping a bindable nested artboard preserves focus held elsewhere", + "[silver]") +{ + rive::SerializingFactory silver; + auto file = ReadRiveFile("assets/bindable_focus_tree_swap.riv", &silver); + + auto artboard = file->artboardDefault(); + REQUIRE(artboard != nullptr); + silver.frameSize(artboard->width(), artboard->height()); + + auto stateMachine = artboard->stateMachineAt(0); + REQUIRE(stateMachine != nullptr); + + auto vmi = file->createDefaultViewModelInstance(artboard.get()); + REQUIRE(vmi != nullptr); + + stateMachine->bindViewModelInstance(vmi); + stateMachine->advanceAndApply(0.016f); + + auto* focusManager = stateMachine->focusManager(); + REQUIRE(focusManager != nullptr); + + // Focus the main artboard's own focus node. Before the swap the bindable + // host is "Plain" (no focus nodes), so the main node is the only focusable. + focusManager->focusNext(); + auto focused = focusManager->primaryFocus(); + REQUIRE(focused != nullptr); + REQUIRE(focusManager->primaryFocusImmediateArtboard() == artboard.get()); + + // Swap the (unrelated) bindable nested artboard to one that HAS focus + // nodes. + auto* artboardProp = vmi->propertyValue("bindedArt"); + REQUIRE(artboardProp != nullptr); + REQUIRE(artboardProp->is<rive::ViewModelInstanceArtboard>()); + auto* vmiArtboard = artboardProp->as<rive::ViewModelInstanceArtboard>(); + auto focusableSource = file->bindableArtboardNamed("Focusable"); + REQUIRE(focusableSource != nullptr); + vmiArtboard->asset(focusableSource); + stateMachine->advanceAndApply(0.016f); + + // Focus held on the main artboard must survive the unrelated nested swap: + // the swap only re-syncs the swapped host's subtree, not the whole tree. + CHECK(focusManager->primaryFocus() == focused); + CHECK(focusManager->primaryFocusImmediateArtboard() == artboard.get()); +} + TEST_CASE("FocusManager skips collapsed nodes and fully transparent nodes", "[FocusManager]") { @@ -1219,14 +1578,25 @@ silver.addFrame(); focusManager->focusNext(); - focusManager->focusNext(); - // Focus on an element + // The first focusable is now inside a data-bound nested artboard REQUIRE(focusManager->primaryFocus() != nullptr); + REQUIRE(focusManager->primaryFocusImmediateArtboard() != nullptr); + REQUIRE(focusManager->primaryFocusImmediateArtboard() != artboard.get()); stateMachine->advanceAndApply(0.016f); artboard->draw(renderer.get()); // ===> Frame 2 silver.addFrame(); - // Hide the element, ensure the focus has been dropped + + // Tab next into the main artboard's own element — the one `opacity` + // controls. + focusManager->focusNext(); + REQUIRE(focusManager->primaryFocus() != nullptr); + REQUIRE(focusManager->primaryFocusImmediateArtboard() == artboard.get()); + stateMachine->advanceAndApply(0.016f); + artboard->draw(renderer.get()); + silver.addFrame(); + + // Hide that focused element; focus must be dropped. opacityProp->propertyValue(0); // First advance sets the opacity to 0 stateMachine->advanceAndApply(0.016f); @@ -1702,8 +2072,10 @@ REQUIRE(scope != nullptr); CHECK(scope->manager() == fm); CHECK(scope->name() == "ArtboardComponentListScope"); - CHECK(scope->canFocus() == true); - CHECK(scope->canTraverse() == true); + // Transparent structural scope: not a focus target itself; traversal + // descends through it (focusNodeTraversable) to reach item focusables. + CHECK(scope->canFocus() == false); + CHECK(scope->canTraverse() == false); CHECK(scope->focusable() == nullptr); } @@ -1860,3 +2232,425 @@ CHECK(silver.matches("focus_test")); } +TEST_CASE("List item focus tree stays under its row when the item's state " + "machine is (re)wired during the focus sync", + "[FocusManager][list]") +{ + // Regression for the syncListRowNodesWithList ordering bug: each list + // item's state machine must be wired to the shared FocusManager BEFORE the + // item's focus tree is (re)built under its row. setExternalFocusManager + // rebuilds the item's focus tree at the manager ROOT as a side effect, so + // if it runs after the build-under-row it clobbers the row placement and + // the item's focus nodes end up detached from the list scope (at the + // manager root). + // + // The natural build path happens to wire the manager first (via + // linkStateMachineToArtboard, whose setExternalFocusManager runs before the + // row sync), so the in-loop call is normally skipped by the + // `smi->focusManager() != fm` guard. Force the mismatch to exercise the + // ordering directly. + auto file = ReadRiveFile("assets/list_focus_order.riv"); + auto artboard = file->artboardDefault(); + REQUIRE(artboard != nullptr); + auto stateMachine = artboard->stateMachineAt(0); + REQUIRE(stateMachine != nullptr); + auto* fm = stateMachine->focusManager(); + REQUIRE(fm != nullptr); + + auto vmi = file->createDefaultViewModelInstance(artboard.get()); + REQUIRE(vmi != nullptr); + stateMachine->bindViewModelInstance(vmi); + stateMachine->advanceAndApply(0.016f); + + REQUIRE(artboard->artboardComponentLists().size() == 1); + auto* list = artboard->artboardComponentLists()[0]; + REQUIRE(list != nullptr); + const int itemCount = static_cast<int>(list->artboardCount()); + REQUIRE(itemCount > 0); + + // A row node with children means the item's focus subtree is parented under + // it (inside the list scope) — the invariant the bug breaks. + auto rowForItem = [&](int i) -> rive::FocusNode* { + auto scope = list->listScopeFocusNode(); + if (scope == nullptr || i >= static_cast<int>(scope->children().size())) + { + return nullptr; + } + return scope->children()[static_cast<size_t>(i)].get(); + }; + + // Pick a list item that (after the normal build) has focus content placed + // under its row AND owns a state machine — the only case where the in-loop + // setExternalFocusManager fires. + int targetIndex = -1; + for (int i = 0; i < itemCount; i++) + { + rive::FocusNode* row = rowForItem(i); + if (row != nullptr && !row->children().empty() && + list->stateMachineInstance(i) != nullptr) + { + targetIndex = i; + break; + } + } + REQUIRE(targetIndex != -1); + + // Force the mismatch: drop the item's shared-manager wiring so the next + // focus sync must call setExternalFocusManager(fm) again — the exact call + // whose manager-root rebuild would clobber the row placement if it ran + // after the build-under-row. + list->stateMachineInstance(targetIndex)->setExternalFocusManager(nullptr); + CHECK(list->stateMachineInstance(targetIndex)->focusManager() != fm); + + // Re-run the parent focus build; this recreates the list scope/rows and + // re-syncs each item under its row. + artboard->cleanupFocusTree(); + artboard->buildFocusTree(fm, nullptr); + + // With the fix (wire first, place last) the item's focus subtree is + // parented under its row inside the list scope. With the bug it was rebuilt + // at the manager root, leaving the row empty. + rive::FocusNode* targetRow = rowForItem(targetIndex); + REQUIRE(targetRow != nullptr); + CHECK(targetRow->manager() == fm); + CHECK_FALSE(targetRow->children().empty()); + CHECK(list->stateMachineInstance(targetIndex)->focusManager() == fm); +} + +TEST_CASE("Swappable artboard slot keeps its place in tab order", + "[FocusManager]") +{ + // File: https://editor.uat.rive.app/file/untitled/36028 + auto file = ReadRiveFile("assets/swappable_artboards_focus.riv"); + auto artboard = file->artboardNamed("Main"); + REQUIRE(artboard != nullptr); + + auto stateMachine = artboard->stateMachineAt(0); + REQUIRE(stateMachine != nullptr); + auto* focusManager = stateMachine->focusManager(); + REQUIRE(focusManager != nullptr); + + auto vmi = file->createDefaultViewModelInstance(artboard.get()); + REQUIRE(vmi != nullptr); + stateMachine->bindViewModelInstance(vmi); + stateMachine->advanceAndApply(0.016f); + stateMachine->advanceAndApply(0.016f); + + // Only the data-bound slot is flagged as swappable; static nested + // artboards get no placeholder scope regardless of whether their artboard + // contains focusables. + rive::NestedArtboard* slotHost = nullptr; + for (auto* host : artboard->nestedArtboards()) + { + auto* source = host->sourceArtboard(); + REQUIRE(source != nullptr); + if (source->name() == "Swappable1" || source->name() == "Swappable2") + { + CHECK(host->isArtboardDataBound() == true); + slotHost = host; + } + else + { + CHECK(host->isArtboardDataBound() == false); + } + } + REQUIRE(slotHost != nullptr); + + CHECK(stateMachine->hasFocusNodes() == true); + + // The artboard owning the currently focused element. + auto focusedArtboardName = [&]() -> std::string { + auto* ab = focusManager->primaryFocusImmediateArtboard(); + return ab != nullptr ? ab->name() : "<none>"; + }; + + // Initial tab order follows the Main hierarchy: Rectangle (Main) -> slot + // (Swappable1) -> StaticNestWithFocusable. StaticNestWithoutFocusable + // contributes nothing. + CHECK(stateMachine->focusNext() == true); + CHECK(focusedArtboardName() == "Main"); + CHECK(stateMachine->focusNext() == true); + CHECK(focusedArtboardName() == "Swappable1"); + CHECK(stateMachine->focusNext() == true); + CHECK(focusedArtboardName() == "StaticNestWithFocusable"); + // Edge of the root scope clears focus. + CHECK(stateMachine->focusNext() == false); + CHECK(focusManager->primaryFocus() == nullptr); + + // Swap the slot to an artboard with no focusables: the slot contributes + // no focus stop and the rest of the order is untouched. + auto* artboardProp = vmi->propertyValue("artboardProp"); + REQUIRE(artboardProp != nullptr); + REQUIRE(artboardProp->is<rive::ViewModelInstanceArtboard>()); + auto* vmiArtboard = artboardProp->as<rive::ViewModelInstanceArtboard>(); + auto swappable2 = file->bindableArtboardNamed("Swappable2"); + REQUIRE(swappable2 != nullptr); + vmiArtboard->asset(swappable2); + stateMachine->advanceAndApply(0.016f); + + CHECK(stateMachine->focusNext() == true); + CHECK(focusedArtboardName() == "Main"); + CHECK(stateMachine->focusNext() == true); + CHECK(focusedArtboardName() == "StaticNestWithFocusable"); + CHECK(stateMachine->focusNext() == false); + + // Focus the Main rectangle, then swap back to the focusable artboard: + // focus held elsewhere survives the (unrelated) swap... + CHECK(stateMachine->focusNext() == true); + CHECK(focusedArtboardName() == "Main"); + auto heldFocus = focusManager->primaryFocus(); + auto swappable1 = file->bindableArtboardNamed("Swappable1"); + REQUIRE(swappable1 != nullptr); + vmiArtboard->asset(swappable1); + stateMachine->advanceAndApply(0.016f); + CHECK(focusManager->primaryFocus() == heldFocus); + CHECK(focusedArtboardName() == "Main"); + + // ...and the swapped-in focusable takes the slot's place in the middle of + // the tab order (its hierarchy position), not the end. + CHECK(stateMachine->focusNext() == true); + CHECK(focusedArtboardName() == "Swappable1"); + CHECK(stateMachine->focusNext() == true); + CHECK(focusedArtboardName() == "StaticNestWithFocusable"); + CHECK(stateMachine->focusNext() == false); +} + +TEST_CASE("Repeat focus-tree build keeps focus inside an untouched nested " + "artboard", + "[FocusManager]") +{ + // #4 regression: a second full buildFocusTree pass over an already-wired + // tree (same manager) must not tear down and rebuild nested artboards that + // did not change — doing so blurs focus resting inside them. Only the + // non-destructive scope placement should run on the repeat pass. + auto file = ReadRiveFile("assets/swappable_artboards_focus.riv"); + auto artboard = file->artboardNamed("Main"); + REQUIRE(artboard != nullptr); + + auto stateMachine = artboard->stateMachineAt(0); + REQUIRE(stateMachine != nullptr); + auto* focusManager = stateMachine->focusManager(); + REQUIRE(focusManager != nullptr); + + auto vmi = file->createDefaultViewModelInstance(artboard.get()); + REQUIRE(vmi != nullptr); + stateMachine->bindViewModelInstance(vmi); + stateMachine->advanceAndApply(0.016f); + stateMachine->advanceAndApply(0.016f); + + auto focusedArtboardName = [&]() -> std::string { + auto* ab = focusManager->primaryFocusImmediateArtboard(); + return ab != nullptr ? ab->name() : "<none>"; + }; + + // Tab into the focusable that lives inside the STATIC nested artboard. + // Order (established by the sibling test): Main -> Swappable1 -> + // StaticNestWithFocusable. + CHECK(stateMachine->focusNext() == true); + CHECK(stateMachine->focusNext() == true); + CHECK(stateMachine->focusNext() == true); + REQUIRE(focusedArtboardName() == "StaticNestWithFocusable"); + auto heldFocus = focusManager->primaryFocus(); + REQUIRE(heldFocus != nullptr); + + // Repeat the full build pass with the SAME manager (mirrors the host's + // documented two-phase build, or any later focus-tree re-wire). Nothing + // about the static nested artboard changed, so the focus resting inside it + // must survive rather than being blurred by a needless rebuild. + artboard->buildFocusTree(focusManager, nullptr); + + CHECK(focusManager->primaryFocus() == heldFocus); + CHECK(focusedArtboardName() == "StaticNestWithFocusable"); +} + +TEST_CASE("Cross-file swaps keep slot order and share the focus manager", + "[FocusManager]") +{ + // The slot's host, bind, and scope all live in the main file; the + // swapped-in artboard may come from a different .riv. Loading the asset + // twice yields two independent Files, so pulling bindable artboards from + // the second File exercises the cross-file path. + auto file = ReadRiveFile("assets/swappable_artboards_focus.riv"); + auto otherFile = ReadRiveFile("assets/swappable_artboards_focus.riv"); + + auto artboard = file->artboardNamed("Main"); + REQUIRE(artboard != nullptr); + auto stateMachine = artboard->stateMachineAt(0); + REQUIRE(stateMachine != nullptr); + auto* focusManager = stateMachine->focusManager(); + REQUIRE(focusManager != nullptr); + + auto vmi = file->createDefaultViewModelInstance(artboard.get()); + REQUIRE(vmi != nullptr); + stateMachine->bindViewModelInstance(vmi); + stateMachine->advanceAndApply(0.016f); + + auto focusedArtboard = [&]() -> rive::Artboard* { + return focusManager->primaryFocusImmediateArtboard(); + }; + auto focusedArtboardName = [&]() -> std::string { + auto* ab = focusedArtboard(); + return ab != nullptr ? ab->name() : "<none>"; + }; + // The slot host's bound state machine (created by the latest swap). + auto slotBoundStateMachine = [&]() -> rive::StateMachineInstance* { + for (auto* host : artboard->nestedArtboards()) + { + if (!host->isArtboardDataBound()) + { + continue; + } + for (auto* animation : host->nestedAnimations()) + { + if (animation->is<rive::NestedStateMachine>()) + { + return animation->as<rive::NestedStateMachine>() + ->stateMachineInstance(); + } + } + } + return nullptr; + }; + + auto* artboardProp = vmi->propertyValue("artboardProp"); + REQUIRE(artboardProp != nullptr); + REQUIRE(artboardProp->is<rive::ViewModelInstanceArtboard>()); + auto* vmiArtboard = artboardProp->as<rive::ViewModelInstanceArtboard>(); + + // Swap in a LEAF artboard (one focusable, no nested hosts) from the + // other file. + auto foreignSwappable = otherFile->bindableArtboardNamed("Swappable1"); + REQUIRE(foreignSwappable != nullptr); + vmiArtboard->asset(foreignSwappable); + stateMachine->advanceAndApply(0.016f); + + // The foreign artboard's focus node sits at the slot's hierarchy + // position, exactly like a same-file swap. + CHECK(stateMachine->focusNext() == true); + CHECK(focusedArtboardName() == "Main"); + CHECK(stateMachine->focusNext() == true); + CHECK(focusedArtboardName() == "Swappable1"); + CHECK(stateMachine->focusNext() == true); + CHECK(focusedArtboardName() == "StaticNestWithFocusable"); + CHECK(stateMachine->focusNext() == false); + + // The swapped-in artboard's own state machine must share the parent + // FocusManager, so its focus/keyboard listener groups act on the same + // focus state that Tab traversal uses. + auto* leafSmi = slotBoundStateMachine(); + REQUIRE(leafSmi != nullptr); + CHECK(leafSmi->focusManager() == focusManager); +} + +TEST_CASE("Unresolvable artboard swap leaves focus and tab order untouched", + "[FocusManager]") +{ + auto file = ReadRiveFile("assets/swappable_artboards_focus.riv"); + auto artboard = file->artboardNamed("Main"); + REQUIRE(artboard != nullptr); + + auto stateMachine = artboard->stateMachineAt(0); + REQUIRE(stateMachine != nullptr); + auto* focusManager = stateMachine->focusManager(); + REQUIRE(focusManager != nullptr); + + auto vmi = file->createDefaultViewModelInstance(artboard.get()); + REQUIRE(vmi != nullptr); + stateMachine->bindViewModelInstance(vmi); + stateMachine->advanceAndApply(0.016f); + stateMachine->advanceAndApply(0.016f); + + auto focusedArtboardName = [&]() -> std::string { + auto* ab = focusManager->primaryFocusImmediateArtboard(); + return ab != nullptr ? ab->name() : "<none>"; + }; + + // Default order (per the sibling test): Main -> Swappable1 -> + // StaticNestWithFocusable. Rest focus on Main's Rectangle and hold the rcp. + CHECK(stateMachine->focusNext() == true); + REQUIRE(focusedArtboardName() == "Main"); + auto heldFocus = focusManager->primaryFocus(); + REQUIRE(heldFocus != nullptr); + + // Drive the slot's VM artboard property into the UNRESOLVABLE state: no + // bindable asset and a bogus (non -1) id that matches no artboard. This is + // distinct from an explicit clear (asset null AND propertyValue == -1), so + // updateArtboard must return early and leave the on-screen slot alone. + auto* artboardProp = vmi->propertyValue("artboardProp"); + REQUIRE(artboardProp != nullptr); + REQUIRE(artboardProp->is<rive::ViewModelInstanceArtboard>()); + auto* vmiArtboard = artboardProp->as<rive::ViewModelInstanceArtboard>(); + vmiArtboard->propertyValue(9999u); + REQUIRE(vmiArtboard->asset() == nullptr); + REQUIRE(vmiArtboard->propertyValue() != static_cast<uint32_t>(-1)); + stateMachine->advanceAndApply(0.016f); + + // Focus held on Main survives the failed swap... + CHECK(focusManager->primaryFocus() == heldFocus); + CHECK(focusedArtboardName() == "Main"); + + // ...and the outgoing Swappable1 kept its focus nodes, so the full tab + // order is unchanged: Main -> Swappable1 -> StaticNestWithFocusable. + CHECK(stateMachine->focusNext() == true); + CHECK(focusedArtboardName() == "Swappable1"); + CHECK(stateMachine->focusNext() == true); + CHECK(focusedArtboardName() == "StaticNestWithFocusable"); + CHECK(stateMachine->focusNext() == false); +} + +TEST_CASE("Initially-empty bindable slot keeps its authored tab position on " + "first swap", + "[FocusManager]") +{ + auto file = ReadRiveFile("assets/swappable_artboards_focus.riv"); + auto artboard = file->artboardNamed("Main"); + REQUIRE(artboard != nullptr); + + auto stateMachine = artboard->stateMachineAt(0); + REQUIRE(stateMachine != nullptr); + auto* focusManager = stateMachine->focusManager(); + REQUIRE(focusManager != nullptr); + + auto vmi = file->createDefaultViewModelInstance(artboard.get()); + REQUIRE(vmi != nullptr); + + // Clear the slot to explicit null (asset null, propertyValue -1) BEFORE the + // first advance, so the slot is empty when the focus tree is first built. + auto* artboardProp = vmi->propertyValue("artboardProp"); + REQUIRE(artboardProp != nullptr); + REQUIRE(artboardProp->is<rive::ViewModelInstanceArtboard>()); + auto* vmiArtboard = artboardProp->as<rive::ViewModelInstanceArtboard>(); + vmiArtboard->asset(nullptr); + + stateMachine->bindViewModelInstance(vmi); + stateMachine->advanceAndApply(0.016f); + stateMachine->advanceAndApply(0.016f); + + auto focusedArtboardName = [&]() -> std::string { + auto* ab = focusManager->primaryFocusImmediateArtboard(); + return ab != nullptr ? ab->name() : "<none>"; + }; + + // The empty slot's scope holds its place but offers no focus stop, so the + // order skips it: Main -> StaticNestWithFocusable. + CHECK(stateMachine->focusNext() == true); + CHECK(focusedArtboardName() == "Main"); + CHECK(stateMachine->focusNext() == true); + CHECK(focusedArtboardName() == "StaticNestWithFocusable"); + CHECK(stateMachine->focusNext() == false); + + // Swap Swappable1 in for the first time: it must build under the scope the + // empty-slot build pass already placed, entering the MIDDLE of the tab + // order (Main -> Swappable1 -> StaticNestWithFocusable), not the end. + auto swappable1 = file->bindableArtboardNamed("Swappable1"); + REQUIRE(swappable1 != nullptr); + vmiArtboard->asset(swappable1); + stateMachine->advanceAndApply(0.016f); + CHECK(stateMachine->focusNext() == true); + CHECK(focusedArtboardName() == "Main"); + CHECK(stateMachine->focusNext() == true); + CHECK(focusedArtboardName() == "Swappable1"); + CHECK(stateMachine->focusNext() == true); + CHECK(focusedArtboardName() == "StaticNestWithFocusable"); + CHECK(stateMachine->focusNext() == false); +}
diff --git a/tests/unit_tests/silvers/focus_collapsing.sriv b/tests/unit_tests/silvers/focus_collapsing.sriv index 04e33a7..9f27e87 100644 --- a/tests/unit_tests/silvers/focus_collapsing.sriv +++ b/tests/unit_tests/silvers/focus_collapsing.sriv Binary files differ