Skip to content
Open
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
5 changes: 5 additions & 0 deletions .changeset/lit-selector-host-sync.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@tanstack/lit-store': patch
---

Keep `TanStackStoreSelector` and `TanStackStoreAtom` in sync with their host. The selector runs again on each host update, so selectors that read host properties stay current, and the subscription follows the host when it is moved in the DOM or removed.
37 changes: 25 additions & 12 deletions packages/lit-store/src/tan-stack-store-selector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ export class TanStackStoreSelector<
#subscribedStore?: SelectionSource<TSource>
#hasSelected = false
#lastSelected?: TSelected
#connected = false

constructor(
host: ReactiveControllerHost,
Expand All @@ -86,9 +87,19 @@ export class TanStackStoreSelector<
return this.#lastSelected
}

hostConnected() {
this.#connected = true
this.#host.requestUpdate()
}

hostUpdate() {
// An update can still run after the host is removed; do not subscribe then.
if (!this.#connected) return
const store = this.#getStore()
if (store === this.#subscribedStore) return
if (store && store === this.#subscribedStore) {
this.#select(store.get())
return
}
this.#unsubscribe?.()
this.#subscribedStore = store
if (!store) {
Expand All @@ -97,24 +108,26 @@ export class TanStackStoreSelector<
this.#lastSelected = undefined
return
}
this.#lastSelected = this.#selector(store.get())
this.#hasSelected = true
this.#select(store.get())
this.#unsubscribe = store.subscribe((value) => {
const next = this.#selector(value)
if (this.#hasSelected && this.#compare(this.#lastSelected!, next)) {
return
}
this.#lastSelected = next
this.#hasSelected = true
this.#host.requestUpdate()
if (this.#select(value)) this.#host.requestUpdate()
}).unsubscribe
}

hostDisconnected() {
this.#connected = false
this.#unsubscribe?.()
this.#unsubscribe = undefined
this.#subscribedStore = undefined
this.#hasSelected = false
this.#lastSelected = undefined
}

#select(value: TSource) {
const next = this.#selector(value)
if (this.#hasSelected && this.#compare(this.#lastSelected!, next)) {
return false
}
this.#lastSelected = next
this.#hasSelected = true
return true
}
}
94 changes: 93 additions & 1 deletion packages/lit-store/tests/selector.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { describe, expect, it } from 'vitest'
import '@testing-library/jest-dom/vitest'
import { userEvent } from '@testing-library/user-event'
import { LitElement, html } from 'lit'
import { createStore } from '@tanstack/store'
import { createStore, shallow } from '@tanstack/store'
import { TanStackStoreSelector } from '../src'
import { defineOnce, mount } from './utils'

Expand Down Expand Up @@ -123,4 +123,96 @@ describe('Lit Store Tests', () => {
expect(getBtn()).toHaveTextContent('1')
expect(getIgnore()).toHaveTextContent('1')
})

it('should select again when a host property read by the selector changes', async () => {
const store = createStore({ dogs: 3, cats: 7 })

class TestForm extends LitElement {
static properties = { animal: {} }
animal: 'dogs' | 'cats' = 'dogs'

#count = new TanStackStoreSelector(
this,
() => store,
(state) => state[this.animal],
)

render() {
return html`<p id="count">${this.#count.value}</p>`
}
}

const tag = defineOnce('test-form', TestForm)

const element = await mount<TestForm>(tag)

const getCount = () => element.shadowRoot!.querySelector('#count')

expect(getCount()).toHaveTextContent('3')

element.animal = 'cats'
await element.updateComplete
expect(getCount()).toHaveTextContent('7')
})

it('should keep updating after the element is moved', async () => {
const counter = createStore({ count: 0 })

class TestForm extends LitElement {
selection = new TanStackStoreSelector(
this,
() => counter,
(state) => ({ count: state.count }),
{ compare: shallow },
)

render() {
return html`<p id="count">${this.selection.value?.count}</p>`
}
}

const tag = defineOnce('test-form', TestForm)

const element = await mount<TestForm>(tag)

const getCount = () => element.shadowRoot!.querySelector('#count')

expect(getCount()).toHaveTextContent('0')

const selected = element.selection.value
document.body.appendChild(element)
await element.updateComplete
expect(element.selection.value).toBe(selected)

counter.setState(() => ({ count: 1 }))
await element.updateComplete
expect(getCount()).toHaveTextContent('1')
})

it('should stop updating after the element is removed', async () => {
const counter = createStore(0)
let renders = 0

class TestForm extends LitElement {
#count = new TanStackStoreSelector(this, () => counter)

render() {
renders++
return html`<p id="count">${this.#count.value}</p>`
}
}

const tag = defineOnce('test-form', TestForm)

const element = await mount<TestForm>(tag)

counter.setState(() => 1)
element.remove()
await element.updateComplete
const rendersAfterRemove = renders

counter.setState(() => 2)
await element.updateComplete
expect(renders).toBe(rendersAfterRemove)
})
})