diff --git a/src/index.ts b/src/index.ts index bea8e03..ccd81da 100644 --- a/src/index.ts +++ b/src/index.ts @@ -250,9 +250,11 @@ export class Lrud { if (parentNode.activeChild && parentNode.activeChild === nodeId) { delete parentNode.activeChild const top = this.climbUp(parentNode, '*') - const prev = this.getPrevChild(top) - const child = this.digDown(prev) - this.assignFocus(child.id) + if (top) { + const prev = this.getPrevChild(top) + const child = this.digDown(prev) + this.assignFocus(child.id) + } } // ...we need to recalculate the indexes of all the parents children diff --git a/src/unregister.test.js b/src/unregister.test.js index ef7ca76..6f45234 100644 --- a/src/unregister.test.js +++ b/src/unregister.test.js @@ -294,4 +294,42 @@ describe('unregisterNode()', () => { expect(navigation.tree).toMatchObject({}) expect(navigation.overrides).toMatchObject({}) }) + + test('unregistering the focused node when there is nothing else that can be focused on', () => { + const nav = new Lrud() + + nav.registerNode('root', { orientation: 'vertical' }) + nav.registerNode('row1', { orientation: 'horizontal', parent: 'root' }) + nav.registerNode('item1', { isFocusable: true, parent: 'row1' }) + + // nothing else to focus on, but we shouldn't throw an exception + expect(() => { + nav.unregisterNode('item1') + }).not.toThrow() + + // root should still have an activeChild of row 1 + expect(nav.getNode('root').activeChild).toEqual('row1') + expect(nav.getNode('row1').activeChild).toEqual(undefined) + }) + + test('unregistering the focused node when there is nothing else that can be focused on - more nesting', () => { + const nav = new Lrud() + + nav.registerNode('root', { orientation: 'vertical' }) + nav.registerNode('boxa', { orientation: 'horizontal', parent: 'root' }) + nav.registerNode('boxb', { orientation: 'horizontal', parent: 'boxa' }) + nav.registerNode('boxc', { orientation: 'horizontal', parent: 'boxb' }) + nav.registerNode('item1', { isFocusable: true, parent: 'boxc' }) + + // nothing else to focus on, but we shouldn't throw an exception + expect(() => { + nav.unregisterNode('item1') + }).not.toThrow() + + // root should still have an activeChild of row 1 + expect(nav.getNode('root').activeChild).toEqual('boxa') + expect(nav.getNode('boxa').activeChild).toEqual('boxb') + expect(nav.getNode('boxb').activeChild).toEqual('boxc') + expect(nav.getNode('boxc').activeChild).toEqual(undefined) + }) })