Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore!: remove priority from store to reduce bundle size #30

Merged
merged 1 commit into from
Oct 31, 2023
Merged
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
32 changes: 5 additions & 27 deletions packages/store/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
export type AnyUpdater = (...args: any[]) => any

export type Listener = (opts: { priority: Priority }) => void

export type Priority = 'high' | 'low'
export type Listener = () => void

interface StoreOptions<
TState,
Expand All @@ -13,8 +11,7 @@ interface StoreOptions<
listener: Listener,
store: Store<TState, TUpdater>,
) => () => void
onUpdate?: (opts: { priority: Priority }) => void
defaultPriority?: Priority
onUpdate?: () => void
}

export class Store<
Expand All @@ -26,7 +23,6 @@ export class Store<
options?: StoreOptions<TState, TUpdater>
_batching = false
_flushing = 0
_nextPriority: null | Priority = null

constructor(initialState: TState, options?: StoreOptions<TState, TUpdater>) {
this.state = initialState
Expand All @@ -42,30 +38,14 @@ export class Store<
}
}

setState = (
updater: TUpdater,
opts?: {
priority: Priority
},
) => {
setState = (updater: TUpdater) => {
const previous = this.state
this.state = this.options?.updateFn
? this.options.updateFn(previous)(updater)
: (updater as any)(previous)

const priority = opts?.priority ?? this.options?.defaultPriority ?? 'high'
if (this._nextPriority === null) {
this._nextPriority = priority
} else if (this._nextPriority === 'high') {
this._nextPriority = priority
} else {
this._nextPriority = this.options?.defaultPriority ?? 'high'
}

// Always run onUpdate, regardless of batching
this.options?.onUpdate?.({
priority: this._nextPriority,
})
this.options?.onUpdate?.()

// Attempt to flush
this._flush()
Expand All @@ -76,9 +56,7 @@ export class Store<
const flushId = ++this._flushing
this.listeners.forEach((listener) => {
if (this._flushing !== flushId) return
listener({
priority: this._nextPriority ?? 'high',
})
listener()
})
}

Expand Down