refactor: rename reactivity package name and APIs
This commit is contained in:
3
packages/reactivity/.npmignore
Normal file
3
packages/reactivity/.npmignore
Normal file
@@ -0,0 +1,3 @@
|
||||
__tests__/
|
||||
__mocks__/
|
||||
dist/packages
|
||||
18
packages/reactivity/README.md
Normal file
18
packages/reactivity/README.md
Normal file
@@ -0,0 +1,18 @@
|
||||
# @vue/observer
|
||||
|
||||
## Usage Note
|
||||
|
||||
This package is inlined into Global & Browser ESM builds of user-facing renderers (e.g. `@vue/runtime-dom`), but also published as a package that can be used standalone. The standalone build should not be used alongside a pre-bundled build of a user-facing renderer, as they will have different internal storage for reactivity connections. A user-facing renderer should re-export all APIs from this package.
|
||||
|
||||
## Credits
|
||||
|
||||
The implementation of this module is inspired by the following prior art in the JavaScript ecosystem:
|
||||
|
||||
- [Meteor Tracker](https://docs.meteor.com/api/tracker.html)
|
||||
- [nx-js/observer-util](https://github.com/nx-js/observer-util)
|
||||
- [salesforce/observable-membrane](https://github.com/salesforce/observable-membrane)
|
||||
|
||||
|
||||
## Caveats
|
||||
|
||||
- Built-in objects are not observed except for `Map`, `WeakMap`, `Set` and `WeakSet`.
|
||||
305
packages/reactivity/__tests__/collections/Map.spec.ts
Normal file
305
packages/reactivity/__tests__/collections/Map.spec.ts
Normal file
@@ -0,0 +1,305 @@
|
||||
import { state, effect, toRaw, isState } from '../../src'
|
||||
|
||||
describe('observer/collections', () => {
|
||||
describe('Map', () => {
|
||||
test('instanceof', () => {
|
||||
const original = new Map()
|
||||
const observed = state(original)
|
||||
expect(isState(observed)).toBe(true)
|
||||
expect(original instanceof Map).toBe(true)
|
||||
expect(observed instanceof Map).toBe(true)
|
||||
})
|
||||
|
||||
it('should observe mutations', () => {
|
||||
let dummy
|
||||
const map = state(new Map())
|
||||
effect(() => {
|
||||
dummy = map.get('key')
|
||||
})
|
||||
|
||||
expect(dummy).toBe(undefined)
|
||||
map.set('key', 'value')
|
||||
expect(dummy).toBe('value')
|
||||
map.set('key', 'value2')
|
||||
expect(dummy).toBe('value2')
|
||||
map.delete('key')
|
||||
expect(dummy).toBe(undefined)
|
||||
})
|
||||
|
||||
it('should observe size mutations', () => {
|
||||
let dummy
|
||||
const map = state(new Map())
|
||||
effect(() => (dummy = map.size))
|
||||
|
||||
expect(dummy).toBe(0)
|
||||
map.set('key1', 'value')
|
||||
map.set('key2', 'value2')
|
||||
expect(dummy).toBe(2)
|
||||
map.delete('key1')
|
||||
expect(dummy).toBe(1)
|
||||
map.clear()
|
||||
expect(dummy).toBe(0)
|
||||
})
|
||||
|
||||
it('should observe for of iteration', () => {
|
||||
let dummy
|
||||
const map = state(new Map())
|
||||
effect(() => {
|
||||
dummy = 0
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
for (let [key, num] of map) {
|
||||
key
|
||||
dummy += num
|
||||
}
|
||||
})
|
||||
|
||||
expect(dummy).toBe(0)
|
||||
map.set('key1', 3)
|
||||
expect(dummy).toBe(3)
|
||||
map.set('key2', 2)
|
||||
expect(dummy).toBe(5)
|
||||
map.delete('key1')
|
||||
expect(dummy).toBe(2)
|
||||
map.clear()
|
||||
expect(dummy).toBe(0)
|
||||
})
|
||||
|
||||
it('should observe forEach iteration', () => {
|
||||
let dummy: any
|
||||
const map = state(new Map())
|
||||
effect(() => {
|
||||
dummy = 0
|
||||
map.forEach((num: any) => (dummy += num))
|
||||
})
|
||||
|
||||
expect(dummy).toBe(0)
|
||||
map.set('key1', 3)
|
||||
expect(dummy).toBe(3)
|
||||
map.set('key2', 2)
|
||||
expect(dummy).toBe(5)
|
||||
map.delete('key1')
|
||||
expect(dummy).toBe(2)
|
||||
map.clear()
|
||||
expect(dummy).toBe(0)
|
||||
})
|
||||
|
||||
it('should observe keys iteration', () => {
|
||||
let dummy
|
||||
const map = state(new Map())
|
||||
effect(() => {
|
||||
dummy = 0
|
||||
for (let key of map.keys()) {
|
||||
dummy += key
|
||||
}
|
||||
})
|
||||
|
||||
expect(dummy).toBe(0)
|
||||
map.set(3, 3)
|
||||
expect(dummy).toBe(3)
|
||||
map.set(2, 2)
|
||||
expect(dummy).toBe(5)
|
||||
map.delete(3)
|
||||
expect(dummy).toBe(2)
|
||||
map.clear()
|
||||
expect(dummy).toBe(0)
|
||||
})
|
||||
|
||||
it('should observe values iteration', () => {
|
||||
let dummy
|
||||
const map = state(new Map())
|
||||
effect(() => {
|
||||
dummy = 0
|
||||
for (let num of map.values()) {
|
||||
dummy += num
|
||||
}
|
||||
})
|
||||
|
||||
expect(dummy).toBe(0)
|
||||
map.set('key1', 3)
|
||||
expect(dummy).toBe(3)
|
||||
map.set('key2', 2)
|
||||
expect(dummy).toBe(5)
|
||||
map.delete('key1')
|
||||
expect(dummy).toBe(2)
|
||||
map.clear()
|
||||
expect(dummy).toBe(0)
|
||||
})
|
||||
|
||||
it('should observe entries iteration', () => {
|
||||
let dummy
|
||||
const map = state(new Map())
|
||||
effect(() => {
|
||||
dummy = 0
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
for (let [key, num] of map.entries()) {
|
||||
key
|
||||
dummy += num
|
||||
}
|
||||
})
|
||||
|
||||
expect(dummy).toBe(0)
|
||||
map.set('key1', 3)
|
||||
expect(dummy).toBe(3)
|
||||
map.set('key2', 2)
|
||||
expect(dummy).toBe(5)
|
||||
map.delete('key1')
|
||||
expect(dummy).toBe(2)
|
||||
map.clear()
|
||||
expect(dummy).toBe(0)
|
||||
})
|
||||
|
||||
it('should be triggered by clearing', () => {
|
||||
let dummy
|
||||
const map = state(new Map())
|
||||
effect(() => (dummy = map.get('key')))
|
||||
|
||||
expect(dummy).toBe(undefined)
|
||||
map.set('key', 3)
|
||||
expect(dummy).toBe(3)
|
||||
map.clear()
|
||||
expect(dummy).toBe(undefined)
|
||||
})
|
||||
|
||||
it('should not observe custom property mutations', () => {
|
||||
let dummy
|
||||
const map: any = state(new Map())
|
||||
effect(() => (dummy = map.customProp))
|
||||
|
||||
expect(dummy).toBe(undefined)
|
||||
map.customProp = 'Hello World'
|
||||
expect(dummy).toBe(undefined)
|
||||
})
|
||||
|
||||
it('should not observe non value changing mutations', () => {
|
||||
let dummy
|
||||
const map = state(new Map())
|
||||
const mapSpy = jest.fn(() => (dummy = map.get('key')))
|
||||
effect(mapSpy)
|
||||
|
||||
expect(dummy).toBe(undefined)
|
||||
expect(mapSpy).toHaveBeenCalledTimes(1)
|
||||
map.set('key', 'value')
|
||||
expect(dummy).toBe('value')
|
||||
expect(mapSpy).toHaveBeenCalledTimes(2)
|
||||
map.set('key', 'value')
|
||||
expect(dummy).toBe('value')
|
||||
expect(mapSpy).toHaveBeenCalledTimes(2)
|
||||
map.delete('key')
|
||||
expect(dummy).toBe(undefined)
|
||||
expect(mapSpy).toHaveBeenCalledTimes(3)
|
||||
map.delete('key')
|
||||
expect(dummy).toBe(undefined)
|
||||
expect(mapSpy).toHaveBeenCalledTimes(3)
|
||||
map.clear()
|
||||
expect(dummy).toBe(undefined)
|
||||
expect(mapSpy).toHaveBeenCalledTimes(3)
|
||||
})
|
||||
|
||||
it('should not observe raw data', () => {
|
||||
let dummy
|
||||
const map = state(new Map())
|
||||
effect(() => (dummy = toRaw(map).get('key')))
|
||||
|
||||
expect(dummy).toBe(undefined)
|
||||
map.set('key', 'Hello')
|
||||
expect(dummy).toBe(undefined)
|
||||
map.delete('key')
|
||||
expect(dummy).toBe(undefined)
|
||||
})
|
||||
|
||||
it('should not pollute original Map with Proxies', () => {
|
||||
const map = new Map()
|
||||
const observed = state(map)
|
||||
const value = state({})
|
||||
observed.set('key', value)
|
||||
expect(map.get('key')).not.toBe(value)
|
||||
expect(map.get('key')).toBe(toRaw(value))
|
||||
})
|
||||
|
||||
it('should return observable versions of contained values', () => {
|
||||
const observed = state(new Map())
|
||||
const value = {}
|
||||
observed.set('key', value)
|
||||
const wrapped = observed.get('key')
|
||||
expect(isState(wrapped)).toBe(true)
|
||||
expect(toRaw(wrapped)).toBe(value)
|
||||
})
|
||||
|
||||
it('should observed nested data', () => {
|
||||
const observed = state(new Map())
|
||||
observed.set('key', { a: 1 })
|
||||
let dummy
|
||||
effect(() => {
|
||||
dummy = observed.get('key').a
|
||||
})
|
||||
observed.get('key').a = 2
|
||||
expect(dummy).toBe(2)
|
||||
})
|
||||
|
||||
it('should observe nested values in iterations (forEach)', () => {
|
||||
const map = state(new Map([[1, { foo: 1 }]]))
|
||||
let dummy: any
|
||||
effect(() => {
|
||||
dummy = 0
|
||||
map.forEach(value => {
|
||||
expect(isState(value)).toBe(true)
|
||||
dummy += value.foo
|
||||
})
|
||||
})
|
||||
expect(dummy).toBe(1)
|
||||
;(map.get(1) as any).foo++
|
||||
expect(dummy).toBe(2)
|
||||
})
|
||||
|
||||
it('should observe nested values in iterations (values)', () => {
|
||||
const map = state(new Map([[1, { foo: 1 }]]))
|
||||
let dummy: any
|
||||
effect(() => {
|
||||
dummy = 0
|
||||
for (const value of map.values()) {
|
||||
expect(isState(value)).toBe(true)
|
||||
dummy += value.foo
|
||||
}
|
||||
})
|
||||
expect(dummy).toBe(1)
|
||||
;(map.get(1) as any).foo++
|
||||
expect(dummy).toBe(2)
|
||||
})
|
||||
|
||||
it('should observe nested values in iterations (entries)', () => {
|
||||
const key = {}
|
||||
const map = state(new Map([[key, { foo: 1 }]]))
|
||||
let dummy: any
|
||||
effect(() => {
|
||||
dummy = 0
|
||||
for (const [key, value] of map.entries()) {
|
||||
key
|
||||
expect(isState(key)).toBe(true)
|
||||
expect(isState(value)).toBe(true)
|
||||
dummy += value.foo
|
||||
}
|
||||
})
|
||||
expect(dummy).toBe(1)
|
||||
;(map.get(key) as any).foo++
|
||||
expect(dummy).toBe(2)
|
||||
})
|
||||
|
||||
it('should observe nested values in iterations (for...of)', () => {
|
||||
const key = {}
|
||||
const map = state(new Map([[key, { foo: 1 }]]))
|
||||
let dummy: any
|
||||
effect(() => {
|
||||
dummy = 0
|
||||
for (const [key, value] of map) {
|
||||
key
|
||||
expect(isState(key)).toBe(true)
|
||||
expect(isState(value)).toBe(true)
|
||||
dummy += value.foo
|
||||
}
|
||||
})
|
||||
expect(dummy).toBe(1)
|
||||
;(map.get(key) as any).foo++
|
||||
expect(dummy).toBe(2)
|
||||
})
|
||||
})
|
||||
})
|
||||
359
packages/reactivity/__tests__/collections/Set.spec.ts
Normal file
359
packages/reactivity/__tests__/collections/Set.spec.ts
Normal file
@@ -0,0 +1,359 @@
|
||||
import { state, effect, isState, toRaw } from '../../src'
|
||||
|
||||
describe('observer/collections', () => {
|
||||
describe('Set', () => {
|
||||
it('instanceof', () => {
|
||||
const original = new Set()
|
||||
const observed = state(original)
|
||||
expect(isState(observed)).toBe(true)
|
||||
expect(original instanceof Set).toBe(true)
|
||||
expect(observed instanceof Set).toBe(true)
|
||||
})
|
||||
|
||||
it('should observe mutations', () => {
|
||||
let dummy
|
||||
const set = state(new Set())
|
||||
effect(() => (dummy = set.has('value')))
|
||||
|
||||
expect(dummy).toBe(false)
|
||||
set.add('value')
|
||||
expect(dummy).toBe(true)
|
||||
set.delete('value')
|
||||
expect(dummy).toBe(false)
|
||||
})
|
||||
|
||||
it('should observe for of iteration', () => {
|
||||
let dummy
|
||||
const set = state(new Set() as Set<number>)
|
||||
effect(() => {
|
||||
dummy = 0
|
||||
for (let num of set) {
|
||||
dummy += num
|
||||
}
|
||||
})
|
||||
|
||||
expect(dummy).toBe(0)
|
||||
set.add(2)
|
||||
set.add(1)
|
||||
expect(dummy).toBe(3)
|
||||
set.delete(2)
|
||||
expect(dummy).toBe(1)
|
||||
set.clear()
|
||||
expect(dummy).toBe(0)
|
||||
})
|
||||
|
||||
it('should observe forEach iteration', () => {
|
||||
let dummy: any
|
||||
const set = state(new Set())
|
||||
effect(() => {
|
||||
dummy = 0
|
||||
set.forEach(num => (dummy += num))
|
||||
})
|
||||
|
||||
expect(dummy).toBe(0)
|
||||
set.add(2)
|
||||
set.add(1)
|
||||
expect(dummy).toBe(3)
|
||||
set.delete(2)
|
||||
expect(dummy).toBe(1)
|
||||
set.clear()
|
||||
expect(dummy).toBe(0)
|
||||
})
|
||||
|
||||
it('should observe values iteration', () => {
|
||||
let dummy
|
||||
const set = state(new Set() as Set<number>)
|
||||
effect(() => {
|
||||
dummy = 0
|
||||
for (let num of set.values()) {
|
||||
dummy += num
|
||||
}
|
||||
})
|
||||
|
||||
expect(dummy).toBe(0)
|
||||
set.add(2)
|
||||
set.add(1)
|
||||
expect(dummy).toBe(3)
|
||||
set.delete(2)
|
||||
expect(dummy).toBe(1)
|
||||
set.clear()
|
||||
expect(dummy).toBe(0)
|
||||
})
|
||||
|
||||
it('should observe keys iteration', () => {
|
||||
let dummy
|
||||
const set = state(new Set() as Set<number>)
|
||||
effect(() => {
|
||||
dummy = 0
|
||||
for (let num of set.keys()) {
|
||||
dummy += num
|
||||
}
|
||||
})
|
||||
|
||||
expect(dummy).toBe(0)
|
||||
set.add(2)
|
||||
set.add(1)
|
||||
expect(dummy).toBe(3)
|
||||
set.delete(2)
|
||||
expect(dummy).toBe(1)
|
||||
set.clear()
|
||||
expect(dummy).toBe(0)
|
||||
})
|
||||
|
||||
it('should observe entries iteration', () => {
|
||||
let dummy
|
||||
const set = state(new Set() as Set<number>)
|
||||
effect(() => {
|
||||
dummy = 0
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
for (let [key, num] of set.entries()) {
|
||||
key
|
||||
dummy += num
|
||||
}
|
||||
})
|
||||
|
||||
expect(dummy).toBe(0)
|
||||
set.add(2)
|
||||
set.add(1)
|
||||
expect(dummy).toBe(3)
|
||||
set.delete(2)
|
||||
expect(dummy).toBe(1)
|
||||
set.clear()
|
||||
expect(dummy).toBe(0)
|
||||
})
|
||||
|
||||
it('should be triggered by clearing', () => {
|
||||
let dummy
|
||||
const set = state(new Set())
|
||||
effect(() => (dummy = set.has('key')))
|
||||
|
||||
expect(dummy).toBe(false)
|
||||
set.add('key')
|
||||
expect(dummy).toBe(true)
|
||||
set.clear()
|
||||
expect(dummy).toBe(false)
|
||||
})
|
||||
|
||||
it('should not observe custom property mutations', () => {
|
||||
let dummy
|
||||
const set: any = state(new Set())
|
||||
effect(() => (dummy = set.customProp))
|
||||
|
||||
expect(dummy).toBe(undefined)
|
||||
set.customProp = 'Hello World'
|
||||
expect(dummy).toBe(undefined)
|
||||
})
|
||||
|
||||
it('should observe size mutations', () => {
|
||||
let dummy
|
||||
const set = state(new Set())
|
||||
effect(() => (dummy = set.size))
|
||||
|
||||
expect(dummy).toBe(0)
|
||||
set.add('value')
|
||||
set.add('value2')
|
||||
expect(dummy).toBe(2)
|
||||
set.delete('value')
|
||||
expect(dummy).toBe(1)
|
||||
set.clear()
|
||||
expect(dummy).toBe(0)
|
||||
})
|
||||
|
||||
it('should not observe non value changing mutations', () => {
|
||||
let dummy
|
||||
const set = state(new Set())
|
||||
const setSpy = jest.fn(() => (dummy = set.has('value')))
|
||||
effect(setSpy)
|
||||
|
||||
expect(dummy).toBe(false)
|
||||
expect(setSpy).toHaveBeenCalledTimes(1)
|
||||
set.add('value')
|
||||
expect(dummy).toBe(true)
|
||||
expect(setSpy).toHaveBeenCalledTimes(2)
|
||||
set.add('value')
|
||||
expect(dummy).toBe(true)
|
||||
expect(setSpy).toHaveBeenCalledTimes(2)
|
||||
set.delete('value')
|
||||
expect(dummy).toBe(false)
|
||||
expect(setSpy).toHaveBeenCalledTimes(3)
|
||||
set.delete('value')
|
||||
expect(dummy).toBe(false)
|
||||
expect(setSpy).toHaveBeenCalledTimes(3)
|
||||
set.clear()
|
||||
expect(dummy).toBe(false)
|
||||
expect(setSpy).toHaveBeenCalledTimes(3)
|
||||
})
|
||||
|
||||
it('should not observe raw data', () => {
|
||||
let dummy
|
||||
const set = state(new Set())
|
||||
effect(() => (dummy = toRaw(set).has('value')))
|
||||
|
||||
expect(dummy).toBe(false)
|
||||
set.add('value')
|
||||
expect(dummy).toBe(false)
|
||||
})
|
||||
|
||||
it('should not observe raw iterations', () => {
|
||||
let dummy = 0
|
||||
const set = state(new Set() as Set<number>)
|
||||
effect(() => {
|
||||
dummy = 0
|
||||
for (let [num] of toRaw(set).entries()) {
|
||||
dummy += num
|
||||
}
|
||||
for (let num of toRaw(set).keys()) {
|
||||
dummy += num
|
||||
}
|
||||
for (let num of toRaw(set).values()) {
|
||||
dummy += num
|
||||
}
|
||||
toRaw(set).forEach(num => {
|
||||
dummy += num
|
||||
})
|
||||
for (let num of toRaw(set)) {
|
||||
dummy += num
|
||||
}
|
||||
})
|
||||
|
||||
expect(dummy).toBe(0)
|
||||
set.add(2)
|
||||
set.add(3)
|
||||
expect(dummy).toBe(0)
|
||||
set.delete(2)
|
||||
expect(dummy).toBe(0)
|
||||
})
|
||||
|
||||
it('should not be triggered by raw mutations', () => {
|
||||
let dummy
|
||||
const set = state(new Set())
|
||||
effect(() => (dummy = set.has('value')))
|
||||
|
||||
expect(dummy).toBe(false)
|
||||
toRaw(set).add('value')
|
||||
expect(dummy).toBe(false)
|
||||
dummy = true
|
||||
toRaw(set).delete('value')
|
||||
expect(dummy).toBe(true)
|
||||
toRaw(set).clear()
|
||||
expect(dummy).toBe(true)
|
||||
})
|
||||
|
||||
it('should not observe raw size mutations', () => {
|
||||
let dummy
|
||||
const set = state(new Set())
|
||||
effect(() => (dummy = toRaw(set).size))
|
||||
|
||||
expect(dummy).toBe(0)
|
||||
set.add('value')
|
||||
expect(dummy).toBe(0)
|
||||
})
|
||||
|
||||
it('should not be triggered by raw size mutations', () => {
|
||||
let dummy
|
||||
const set = state(new Set())
|
||||
effect(() => (dummy = set.size))
|
||||
|
||||
expect(dummy).toBe(0)
|
||||
toRaw(set).add('value')
|
||||
expect(dummy).toBe(0)
|
||||
})
|
||||
|
||||
it('should support objects as key', () => {
|
||||
let dummy
|
||||
const key = {}
|
||||
const set = state(new Set())
|
||||
const setSpy = jest.fn(() => (dummy = set.has(key)))
|
||||
effect(setSpy)
|
||||
|
||||
expect(dummy).toBe(false)
|
||||
expect(setSpy).toHaveBeenCalledTimes(1)
|
||||
|
||||
set.add({})
|
||||
expect(dummy).toBe(false)
|
||||
expect(setSpy).toHaveBeenCalledTimes(1)
|
||||
|
||||
set.add(key)
|
||||
expect(dummy).toBe(true)
|
||||
expect(setSpy).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('should not pollute original Set with Proxies', () => {
|
||||
const set = new Set()
|
||||
const observed = state(set)
|
||||
const value = state({})
|
||||
observed.add(value)
|
||||
expect(observed.has(value)).toBe(true)
|
||||
expect(set.has(value)).toBe(false)
|
||||
})
|
||||
|
||||
it('should observe nested values in iterations (forEach)', () => {
|
||||
const set = state(new Set([{ foo: 1 }]))
|
||||
let dummy: any
|
||||
effect(() => {
|
||||
dummy = 0
|
||||
set.forEach(value => {
|
||||
expect(isState(value)).toBe(true)
|
||||
dummy += value.foo
|
||||
})
|
||||
})
|
||||
expect(dummy).toBe(1)
|
||||
set.forEach(value => {
|
||||
value.foo++
|
||||
})
|
||||
expect(dummy).toBe(2)
|
||||
})
|
||||
|
||||
it('should observe nested values in iterations (values)', () => {
|
||||
const set = state(new Set([{ foo: 1 }]))
|
||||
let dummy: any
|
||||
effect(() => {
|
||||
dummy = 0
|
||||
for (const value of set.values()) {
|
||||
expect(isState(value)).toBe(true)
|
||||
dummy += value.foo
|
||||
}
|
||||
})
|
||||
expect(dummy).toBe(1)
|
||||
set.forEach(value => {
|
||||
value.foo++
|
||||
})
|
||||
expect(dummy).toBe(2)
|
||||
})
|
||||
|
||||
it('should observe nested values in iterations (entries)', () => {
|
||||
const set = state(new Set([{ foo: 1 }]))
|
||||
let dummy: any
|
||||
effect(() => {
|
||||
dummy = 0
|
||||
for (const [key, value] of set.entries()) {
|
||||
expect(isState(key)).toBe(true)
|
||||
expect(isState(value)).toBe(true)
|
||||
dummy += value.foo
|
||||
}
|
||||
})
|
||||
expect(dummy).toBe(1)
|
||||
set.forEach(value => {
|
||||
value.foo++
|
||||
})
|
||||
expect(dummy).toBe(2)
|
||||
})
|
||||
|
||||
it('should observe nested values in iterations (for...of)', () => {
|
||||
const set = state(new Set([{ foo: 1 }]))
|
||||
let dummy: any
|
||||
effect(() => {
|
||||
dummy = 0
|
||||
for (const value of set) {
|
||||
expect(isState(value)).toBe(true)
|
||||
dummy += value.foo
|
||||
}
|
||||
})
|
||||
expect(dummy).toBe(1)
|
||||
set.forEach(value => {
|
||||
value.foo++
|
||||
})
|
||||
expect(dummy).toBe(2)
|
||||
})
|
||||
})
|
||||
})
|
||||
108
packages/reactivity/__tests__/collections/WeakMap.spec.ts
Normal file
108
packages/reactivity/__tests__/collections/WeakMap.spec.ts
Normal file
@@ -0,0 +1,108 @@
|
||||
import { state, effect, toRaw, isState } from '../../src'
|
||||
|
||||
describe('observer/collections', () => {
|
||||
describe('WeakMap', () => {
|
||||
test('instanceof', () => {
|
||||
const original = new WeakMap()
|
||||
const observed = state(original)
|
||||
expect(isState(observed)).toBe(true)
|
||||
expect(original instanceof WeakMap).toBe(true)
|
||||
expect(observed instanceof WeakMap).toBe(true)
|
||||
})
|
||||
|
||||
it('should observe mutations', () => {
|
||||
let dummy
|
||||
const key = {}
|
||||
const map = state(new WeakMap())
|
||||
effect(() => {
|
||||
dummy = map.get(key)
|
||||
})
|
||||
|
||||
expect(dummy).toBe(undefined)
|
||||
map.set(key, 'value')
|
||||
expect(dummy).toBe('value')
|
||||
map.set(key, 'value2')
|
||||
expect(dummy).toBe('value2')
|
||||
map.delete(key)
|
||||
expect(dummy).toBe(undefined)
|
||||
})
|
||||
|
||||
it('should not observe custom property mutations', () => {
|
||||
let dummy
|
||||
const map: any = state(new WeakMap())
|
||||
effect(() => (dummy = map.customProp))
|
||||
|
||||
expect(dummy).toBe(undefined)
|
||||
map.customProp = 'Hello World'
|
||||
expect(dummy).toBe(undefined)
|
||||
})
|
||||
|
||||
it('should not observe non value changing mutations', () => {
|
||||
let dummy
|
||||
const key = {}
|
||||
const map = state(new WeakMap())
|
||||
const mapSpy = jest.fn(() => (dummy = map.get(key)))
|
||||
effect(mapSpy)
|
||||
|
||||
expect(dummy).toBe(undefined)
|
||||
expect(mapSpy).toHaveBeenCalledTimes(1)
|
||||
map.set(key, 'value')
|
||||
expect(dummy).toBe('value')
|
||||
expect(mapSpy).toHaveBeenCalledTimes(2)
|
||||
map.set(key, 'value')
|
||||
expect(dummy).toBe('value')
|
||||
expect(mapSpy).toHaveBeenCalledTimes(2)
|
||||
map.delete(key)
|
||||
expect(dummy).toBe(undefined)
|
||||
expect(mapSpy).toHaveBeenCalledTimes(3)
|
||||
map.delete(key)
|
||||
expect(dummy).toBe(undefined)
|
||||
expect(mapSpy).toHaveBeenCalledTimes(3)
|
||||
})
|
||||
|
||||
it('should not observe raw data', () => {
|
||||
let dummy
|
||||
const key = {}
|
||||
const map = state(new WeakMap())
|
||||
effect(() => (dummy = toRaw(map).get(key)))
|
||||
|
||||
expect(dummy).toBe(undefined)
|
||||
map.set(key, 'Hello')
|
||||
expect(dummy).toBe(undefined)
|
||||
map.delete(key)
|
||||
expect(dummy).toBe(undefined)
|
||||
})
|
||||
|
||||
it('should not pollute original Map with Proxies', () => {
|
||||
const map = new WeakMap()
|
||||
const observed = state(map)
|
||||
const key = {}
|
||||
const value = state({})
|
||||
observed.set(key, value)
|
||||
expect(map.get(key)).not.toBe(value)
|
||||
expect(map.get(key)).toBe(toRaw(value))
|
||||
})
|
||||
|
||||
it('should return observable versions of contained values', () => {
|
||||
const observed = state(new WeakMap())
|
||||
const key = {}
|
||||
const value = {}
|
||||
observed.set(key, value)
|
||||
const wrapped = observed.get(key)
|
||||
expect(isState(wrapped)).toBe(true)
|
||||
expect(toRaw(wrapped)).toBe(value)
|
||||
})
|
||||
|
||||
it('should observed nested data', () => {
|
||||
const observed = state(new Map())
|
||||
const key = {}
|
||||
observed.set(key, { a: 1 })
|
||||
let dummy
|
||||
effect(() => {
|
||||
dummy = observed.get(key).a
|
||||
})
|
||||
observed.get(key).a = 2
|
||||
expect(dummy).toBe(2)
|
||||
})
|
||||
})
|
||||
})
|
||||
90
packages/reactivity/__tests__/collections/WeakSet.spec.ts
Normal file
90
packages/reactivity/__tests__/collections/WeakSet.spec.ts
Normal file
@@ -0,0 +1,90 @@
|
||||
import { state, isState, effect, toRaw } from '../../src'
|
||||
|
||||
describe('observer/collections', () => {
|
||||
describe('WeakSet', () => {
|
||||
it('instanceof', () => {
|
||||
const original = new Set()
|
||||
const observed = state(original)
|
||||
expect(isState(observed)).toBe(true)
|
||||
expect(original instanceof Set).toBe(true)
|
||||
expect(observed instanceof Set).toBe(true)
|
||||
})
|
||||
|
||||
it('should observe mutations', () => {
|
||||
let dummy
|
||||
const value = {}
|
||||
const set = state(new WeakSet())
|
||||
effect(() => (dummy = set.has(value)))
|
||||
|
||||
expect(dummy).toBe(false)
|
||||
set.add(value)
|
||||
expect(dummy).toBe(true)
|
||||
set.delete(value)
|
||||
expect(dummy).toBe(false)
|
||||
})
|
||||
|
||||
it('should not observe custom property mutations', () => {
|
||||
let dummy
|
||||
const set: any = state(new WeakSet())
|
||||
effect(() => (dummy = set.customProp))
|
||||
|
||||
expect(dummy).toBe(undefined)
|
||||
set.customProp = 'Hello World'
|
||||
expect(dummy).toBe(undefined)
|
||||
})
|
||||
|
||||
it('should not observe non value changing mutations', () => {
|
||||
let dummy
|
||||
const value = {}
|
||||
const set = state(new WeakSet())
|
||||
const setSpy = jest.fn(() => (dummy = set.has(value)))
|
||||
effect(setSpy)
|
||||
|
||||
expect(dummy).toBe(false)
|
||||
expect(setSpy).toHaveBeenCalledTimes(1)
|
||||
set.add(value)
|
||||
expect(dummy).toBe(true)
|
||||
expect(setSpy).toHaveBeenCalledTimes(2)
|
||||
set.add(value)
|
||||
expect(dummy).toBe(true)
|
||||
expect(setSpy).toHaveBeenCalledTimes(2)
|
||||
set.delete(value)
|
||||
expect(dummy).toBe(false)
|
||||
expect(setSpy).toHaveBeenCalledTimes(3)
|
||||
set.delete(value)
|
||||
expect(dummy).toBe(false)
|
||||
expect(setSpy).toHaveBeenCalledTimes(3)
|
||||
})
|
||||
|
||||
it('should not observe raw data', () => {
|
||||
const value = {}
|
||||
let dummy
|
||||
const set = state(new WeakSet())
|
||||
effect(() => (dummy = toRaw(set).has(value)))
|
||||
|
||||
expect(dummy).toBe(false)
|
||||
set.add(value)
|
||||
expect(dummy).toBe(false)
|
||||
})
|
||||
|
||||
it('should not be triggered by raw mutations', () => {
|
||||
const value = {}
|
||||
let dummy
|
||||
const set = state(new WeakSet())
|
||||
effect(() => (dummy = set.has(value)))
|
||||
|
||||
expect(dummy).toBe(false)
|
||||
toRaw(set).add(value)
|
||||
expect(dummy).toBe(false)
|
||||
})
|
||||
|
||||
it('should not pollute original Set with Proxies', () => {
|
||||
const set = new WeakSet()
|
||||
const observed = state(set)
|
||||
const value = state({})
|
||||
observed.add(value)
|
||||
expect(observed.has(value)).toBe(true)
|
||||
expect(set.has(value)).toBe(false)
|
||||
})
|
||||
})
|
||||
})
|
||||
128
packages/reactivity/__tests__/computed.spec.ts
Normal file
128
packages/reactivity/__tests__/computed.spec.ts
Normal file
@@ -0,0 +1,128 @@
|
||||
import { computed, state, effect, stop } from '../src'
|
||||
|
||||
describe('observer/computed', () => {
|
||||
it('should return updated value', () => {
|
||||
const value: any = state({})
|
||||
const cValue = computed(() => value.foo)
|
||||
expect(cValue.value).toBe(undefined)
|
||||
value.foo = 1
|
||||
expect(cValue.value).toBe(1)
|
||||
})
|
||||
|
||||
it('should compute lazily', () => {
|
||||
const value: any = state({})
|
||||
const getter = jest.fn(() => value.foo)
|
||||
const cValue = computed(getter)
|
||||
|
||||
// lazy
|
||||
expect(getter).not.toHaveBeenCalled()
|
||||
|
||||
expect(cValue.value).toBe(undefined)
|
||||
expect(getter).toHaveBeenCalledTimes(1)
|
||||
|
||||
// should not compute again
|
||||
cValue.value
|
||||
expect(getter).toHaveBeenCalledTimes(1)
|
||||
|
||||
// should not compute until needed
|
||||
value.foo = 1
|
||||
expect(getter).toHaveBeenCalledTimes(1)
|
||||
|
||||
// now it should compute
|
||||
expect(cValue.value).toBe(1)
|
||||
expect(getter).toHaveBeenCalledTimes(2)
|
||||
|
||||
// should not compute again
|
||||
cValue.value
|
||||
expect(getter).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('should trigger effect', () => {
|
||||
const value: any = state({})
|
||||
const cValue = computed(() => value.foo)
|
||||
let dummy
|
||||
effect(() => {
|
||||
dummy = cValue.value
|
||||
})
|
||||
expect(dummy).toBe(undefined)
|
||||
value.foo = 1
|
||||
expect(dummy).toBe(1)
|
||||
})
|
||||
|
||||
it('should work when chained', () => {
|
||||
const value: any = state({ foo: 0 })
|
||||
const c1 = computed(() => value.foo)
|
||||
const c2 = computed(() => c1.value + 1)
|
||||
expect(c2.value).toBe(1)
|
||||
expect(c1.value).toBe(0)
|
||||
value.foo++
|
||||
expect(c2.value).toBe(2)
|
||||
expect(c1.value).toBe(1)
|
||||
})
|
||||
|
||||
it('should trigger effect when chained', () => {
|
||||
const value: any = state({ foo: 0 })
|
||||
const getter1 = jest.fn(() => value.foo)
|
||||
const getter2 = jest.fn(() => {
|
||||
return c1.value + 1
|
||||
})
|
||||
const c1 = computed(getter1)
|
||||
const c2 = computed(getter2)
|
||||
|
||||
let dummy
|
||||
effect(() => {
|
||||
dummy = c2.value
|
||||
})
|
||||
expect(dummy).toBe(1)
|
||||
expect(getter1).toHaveBeenCalledTimes(1)
|
||||
expect(getter2).toHaveBeenCalledTimes(1)
|
||||
value.foo++
|
||||
expect(dummy).toBe(2)
|
||||
// should not result in duplicate calls
|
||||
expect(getter1).toHaveBeenCalledTimes(2)
|
||||
expect(getter2).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('should trigger effect when chained (mixed invocations)', () => {
|
||||
const value: any = state({ foo: 0 })
|
||||
const getter1 = jest.fn(() => value.foo)
|
||||
const getter2 = jest.fn(() => {
|
||||
return c1.value + 1
|
||||
})
|
||||
const c1 = computed(getter1)
|
||||
const c2 = computed(getter2)
|
||||
|
||||
let dummy
|
||||
effect(() => {
|
||||
dummy = c1.value + c2.value
|
||||
})
|
||||
expect(dummy).toBe(1)
|
||||
|
||||
expect(getter1).toHaveBeenCalledTimes(1)
|
||||
expect(getter2).toHaveBeenCalledTimes(1)
|
||||
value.foo++
|
||||
expect(dummy).toBe(3)
|
||||
// should not result in duplicate calls
|
||||
expect(getter1).toHaveBeenCalledTimes(2)
|
||||
expect(getter2).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('should no longer update when stopped', () => {
|
||||
const value: any = state({})
|
||||
const cValue = computed(() => value.foo)
|
||||
let dummy
|
||||
effect(() => {
|
||||
dummy = cValue.value
|
||||
})
|
||||
expect(dummy).toBe(undefined)
|
||||
value.foo = 1
|
||||
expect(dummy).toBe(1)
|
||||
stop(cValue.effect)
|
||||
value.foo = 2
|
||||
expect(dummy).toBe(1)
|
||||
})
|
||||
|
||||
it('should support setter', () => {
|
||||
// TODO
|
||||
})
|
||||
})
|
||||
643
packages/reactivity/__tests__/effect.spec.ts
Normal file
643
packages/reactivity/__tests__/effect.spec.ts
Normal file
@@ -0,0 +1,643 @@
|
||||
import {
|
||||
state,
|
||||
effect,
|
||||
stop,
|
||||
toRaw,
|
||||
OperationTypes,
|
||||
DebuggerEvent,
|
||||
markNonReactive
|
||||
} from '../src/index'
|
||||
import { ITERATE_KEY } from '../src/effect'
|
||||
|
||||
describe('observer/effect', () => {
|
||||
it('should run the passed function once (wrapped by a effect)', () => {
|
||||
const fnSpy = jest.fn(() => {})
|
||||
effect(fnSpy)
|
||||
expect(fnSpy).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('should observe basic properties', () => {
|
||||
let dummy
|
||||
const counter = state({ num: 0 })
|
||||
effect(() => (dummy = counter.num))
|
||||
|
||||
expect(dummy).toBe(0)
|
||||
counter.num = 7
|
||||
expect(dummy).toBe(7)
|
||||
})
|
||||
|
||||
it('should observe multiple properties', () => {
|
||||
let dummy
|
||||
const counter = state({ num1: 0, num2: 0 })
|
||||
effect(() => (dummy = counter.num1 + counter.num1 + counter.num2))
|
||||
|
||||
expect(dummy).toBe(0)
|
||||
counter.num1 = counter.num2 = 7
|
||||
expect(dummy).toBe(21)
|
||||
})
|
||||
|
||||
it('should handle multiple effects', () => {
|
||||
let dummy1, dummy2
|
||||
const counter = state({ num: 0 })
|
||||
effect(() => (dummy1 = counter.num))
|
||||
effect(() => (dummy2 = counter.num))
|
||||
|
||||
expect(dummy1).toBe(0)
|
||||
expect(dummy2).toBe(0)
|
||||
counter.num++
|
||||
expect(dummy1).toBe(1)
|
||||
expect(dummy2).toBe(1)
|
||||
})
|
||||
|
||||
it('should observe nested properties', () => {
|
||||
let dummy
|
||||
const counter = state({ nested: { num: 0 } })
|
||||
effect(() => (dummy = counter.nested.num))
|
||||
|
||||
expect(dummy).toBe(0)
|
||||
counter.nested.num = 8
|
||||
expect(dummy).toBe(8)
|
||||
})
|
||||
|
||||
it('should observe delete operations', () => {
|
||||
let dummy
|
||||
const obj = state({ prop: 'value' })
|
||||
effect(() => (dummy = obj.prop))
|
||||
|
||||
expect(dummy).toBe('value')
|
||||
delete obj.prop
|
||||
expect(dummy).toBe(undefined)
|
||||
})
|
||||
|
||||
it('should observe has operations', () => {
|
||||
let dummy
|
||||
const obj: any = state({ prop: 'value' })
|
||||
effect(() => (dummy = 'prop' in obj))
|
||||
|
||||
expect(dummy).toBe(true)
|
||||
delete obj.prop
|
||||
expect(dummy).toBe(false)
|
||||
obj.prop = 12
|
||||
expect(dummy).toBe(true)
|
||||
})
|
||||
|
||||
it('should observe properties on the prototype chain', () => {
|
||||
let dummy
|
||||
const counter = state({ num: 0 })
|
||||
const parentCounter = state({ num: 2 })
|
||||
Object.setPrototypeOf(counter, parentCounter)
|
||||
effect(() => (dummy = counter.num))
|
||||
|
||||
expect(dummy).toBe(0)
|
||||
delete counter.num
|
||||
expect(dummy).toBe(2)
|
||||
parentCounter.num = 4
|
||||
expect(dummy).toBe(4)
|
||||
counter.num = 3
|
||||
expect(dummy).toBe(3)
|
||||
})
|
||||
|
||||
it('should observe has operations on the prototype chain', () => {
|
||||
let dummy
|
||||
const counter = state({ num: 0 })
|
||||
const parentCounter = state({ num: 2 })
|
||||
Object.setPrototypeOf(counter, parentCounter)
|
||||
effect(() => (dummy = 'num' in counter))
|
||||
|
||||
expect(dummy).toBe(true)
|
||||
delete counter.num
|
||||
expect(dummy).toBe(true)
|
||||
delete parentCounter.num
|
||||
expect(dummy).toBe(false)
|
||||
counter.num = 3
|
||||
expect(dummy).toBe(true)
|
||||
})
|
||||
|
||||
it('should observe inherited property accessors', () => {
|
||||
let dummy, parentDummy, hiddenValue: any
|
||||
const obj: any = state({})
|
||||
const parent = state({
|
||||
set prop(value) {
|
||||
hiddenValue = value
|
||||
},
|
||||
get prop() {
|
||||
return hiddenValue
|
||||
}
|
||||
})
|
||||
Object.setPrototypeOf(obj, parent)
|
||||
effect(() => (dummy = obj.prop))
|
||||
effect(() => (parentDummy = parent.prop))
|
||||
|
||||
expect(dummy).toBe(undefined)
|
||||
expect(parentDummy).toBe(undefined)
|
||||
obj.prop = 4
|
||||
expect(dummy).toBe(4)
|
||||
// this doesn't work, should it?
|
||||
// expect(parentDummy).toBe(4)
|
||||
parent.prop = 2
|
||||
expect(dummy).toBe(2)
|
||||
expect(parentDummy).toBe(2)
|
||||
})
|
||||
|
||||
it('should observe function call chains', () => {
|
||||
let dummy
|
||||
const counter = state({ num: 0 })
|
||||
effect(() => (dummy = getNum()))
|
||||
|
||||
function getNum() {
|
||||
return counter.num
|
||||
}
|
||||
|
||||
expect(dummy).toBe(0)
|
||||
counter.num = 2
|
||||
expect(dummy).toBe(2)
|
||||
})
|
||||
|
||||
it('should observe iteration', () => {
|
||||
let dummy
|
||||
const list = state(['Hello'])
|
||||
effect(() => (dummy = list.join(' ')))
|
||||
|
||||
expect(dummy).toBe('Hello')
|
||||
list.push('World!')
|
||||
expect(dummy).toBe('Hello World!')
|
||||
list.shift()
|
||||
expect(dummy).toBe('World!')
|
||||
})
|
||||
|
||||
it('should observe implicit array length changes', () => {
|
||||
let dummy
|
||||
const list = state(['Hello'])
|
||||
effect(() => (dummy = list.join(' ')))
|
||||
|
||||
expect(dummy).toBe('Hello')
|
||||
list[1] = 'World!'
|
||||
expect(dummy).toBe('Hello World!')
|
||||
list[3] = 'Hello!'
|
||||
expect(dummy).toBe('Hello World! Hello!')
|
||||
})
|
||||
|
||||
it('should observe sparse array mutations', () => {
|
||||
let dummy
|
||||
const list: any[] = state([])
|
||||
list[1] = 'World!'
|
||||
effect(() => (dummy = list.join(' ')))
|
||||
|
||||
expect(dummy).toBe(' World!')
|
||||
list[0] = 'Hello'
|
||||
expect(dummy).toBe('Hello World!')
|
||||
list.pop()
|
||||
expect(dummy).toBe('Hello')
|
||||
})
|
||||
|
||||
it('should observe enumeration', () => {
|
||||
let dummy = 0
|
||||
const numbers: any = state({ num1: 3 })
|
||||
effect(() => {
|
||||
dummy = 0
|
||||
for (let key in numbers) {
|
||||
dummy += numbers[key]
|
||||
}
|
||||
})
|
||||
|
||||
expect(dummy).toBe(3)
|
||||
numbers.num2 = 4
|
||||
expect(dummy).toBe(7)
|
||||
delete numbers.num1
|
||||
expect(dummy).toBe(4)
|
||||
})
|
||||
|
||||
it('should observe symbol keyed properties', () => {
|
||||
const key = Symbol('symbol keyed prop')
|
||||
let dummy, hasDummy
|
||||
const obj = state({ [key]: 'value' })
|
||||
effect(() => (dummy = obj[key]))
|
||||
effect(() => (hasDummy = key in obj))
|
||||
|
||||
expect(dummy).toBe('value')
|
||||
expect(hasDummy).toBe(true)
|
||||
obj[key] = 'newValue'
|
||||
expect(dummy).toBe('newValue')
|
||||
delete obj[key]
|
||||
expect(dummy).toBe(undefined)
|
||||
expect(hasDummy).toBe(false)
|
||||
})
|
||||
|
||||
it('should not observe well-known symbol keyed properties', () => {
|
||||
const key = Symbol.isConcatSpreadable
|
||||
let dummy
|
||||
const array: any = state([])
|
||||
effect(() => (dummy = array[key]))
|
||||
|
||||
expect(array[key]).toBe(undefined)
|
||||
expect(dummy).toBe(undefined)
|
||||
array[key] = true
|
||||
expect(array[key]).toBe(true)
|
||||
expect(dummy).toBe(undefined)
|
||||
})
|
||||
|
||||
it('should observe function valued properties', () => {
|
||||
const oldFunc = () => {}
|
||||
const newFunc = () => {}
|
||||
|
||||
let dummy
|
||||
const obj = state({ func: oldFunc })
|
||||
effect(() => (dummy = obj.func))
|
||||
|
||||
expect(dummy).toBe(oldFunc)
|
||||
obj.func = newFunc
|
||||
expect(dummy).toBe(newFunc)
|
||||
})
|
||||
|
||||
it('should not observe set operations without a value change', () => {
|
||||
let hasDummy, getDummy
|
||||
const obj = state({ prop: 'value' })
|
||||
|
||||
const getSpy = jest.fn(() => (getDummy = obj.prop))
|
||||
const hasSpy = jest.fn(() => (hasDummy = 'prop' in obj))
|
||||
effect(getSpy)
|
||||
effect(hasSpy)
|
||||
|
||||
expect(getDummy).toBe('value')
|
||||
expect(hasDummy).toBe(true)
|
||||
obj.prop = 'value'
|
||||
expect(getSpy).toHaveBeenCalledTimes(1)
|
||||
expect(hasSpy).toHaveBeenCalledTimes(1)
|
||||
expect(getDummy).toBe('value')
|
||||
expect(hasDummy).toBe(true)
|
||||
})
|
||||
|
||||
it('should not observe raw mutations', () => {
|
||||
let dummy
|
||||
const obj: any = state()
|
||||
effect(() => (dummy = toRaw(obj).prop))
|
||||
|
||||
expect(dummy).toBe(undefined)
|
||||
obj.prop = 'value'
|
||||
expect(dummy).toBe(undefined)
|
||||
})
|
||||
|
||||
it('should not be triggered by raw mutations', () => {
|
||||
let dummy
|
||||
const obj: any = state()
|
||||
effect(() => (dummy = obj.prop))
|
||||
|
||||
expect(dummy).toBe(undefined)
|
||||
toRaw(obj).prop = 'value'
|
||||
expect(dummy).toBe(undefined)
|
||||
})
|
||||
|
||||
it('should not be triggered by inherited raw setters', () => {
|
||||
let dummy, parentDummy, hiddenValue: any
|
||||
const obj: any = state({})
|
||||
const parent = state({
|
||||
set prop(value) {
|
||||
hiddenValue = value
|
||||
},
|
||||
get prop() {
|
||||
return hiddenValue
|
||||
}
|
||||
})
|
||||
Object.setPrototypeOf(obj, parent)
|
||||
effect(() => (dummy = obj.prop))
|
||||
effect(() => (parentDummy = parent.prop))
|
||||
|
||||
expect(dummy).toBe(undefined)
|
||||
expect(parentDummy).toBe(undefined)
|
||||
toRaw(obj).prop = 4
|
||||
expect(dummy).toBe(undefined)
|
||||
expect(parentDummy).toBe(undefined)
|
||||
})
|
||||
|
||||
it('should avoid implicit infinite recursive loops with itself', () => {
|
||||
const counter = state({ num: 0 })
|
||||
|
||||
const counterSpy = jest.fn(() => counter.num++)
|
||||
effect(counterSpy)
|
||||
expect(counter.num).toBe(1)
|
||||
expect(counterSpy).toHaveBeenCalledTimes(1)
|
||||
counter.num = 4
|
||||
expect(counter.num).toBe(5)
|
||||
expect(counterSpy).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('should allow explicitly recursive raw function loops', () => {
|
||||
const counter = state({ num: 0 })
|
||||
const numSpy = jest.fn(() => {
|
||||
counter.num++
|
||||
if (counter.num < 10) {
|
||||
numSpy()
|
||||
}
|
||||
})
|
||||
effect(numSpy)
|
||||
expect(counter.num).toEqual(10)
|
||||
expect(numSpy).toHaveBeenCalledTimes(10)
|
||||
})
|
||||
|
||||
it('should avoid infinite loops with other effects', () => {
|
||||
const nums = state({ num1: 0, num2: 1 })
|
||||
|
||||
const spy1 = jest.fn(() => (nums.num1 = nums.num2))
|
||||
const spy2 = jest.fn(() => (nums.num2 = nums.num1))
|
||||
effect(spy1)
|
||||
effect(spy2)
|
||||
expect(nums.num1).toBe(1)
|
||||
expect(nums.num2).toBe(1)
|
||||
expect(spy1).toHaveBeenCalledTimes(1)
|
||||
expect(spy2).toHaveBeenCalledTimes(1)
|
||||
nums.num2 = 4
|
||||
expect(nums.num1).toBe(4)
|
||||
expect(nums.num2).toBe(4)
|
||||
expect(spy1).toHaveBeenCalledTimes(2)
|
||||
expect(spy2).toHaveBeenCalledTimes(2)
|
||||
nums.num1 = 10
|
||||
expect(nums.num1).toBe(10)
|
||||
expect(nums.num2).toBe(10)
|
||||
expect(spy1).toHaveBeenCalledTimes(3)
|
||||
expect(spy2).toHaveBeenCalledTimes(3)
|
||||
})
|
||||
|
||||
it('should return a new reactive version of the function', () => {
|
||||
function greet() {
|
||||
return 'Hello World'
|
||||
}
|
||||
const effect1 = effect(greet)
|
||||
const effect2 = effect(greet)
|
||||
expect(typeof effect1).toBe('function')
|
||||
expect(typeof effect2).toBe('function')
|
||||
expect(effect1).not.toBe(greet)
|
||||
expect(effect1).not.toBe(effect2)
|
||||
})
|
||||
|
||||
it('should discover new branches while running automatically', () => {
|
||||
let dummy
|
||||
const obj = state({ prop: 'value', run: false })
|
||||
|
||||
const conditionalSpy = jest.fn(() => {
|
||||
dummy = obj.run ? obj.prop : 'other'
|
||||
})
|
||||
effect(conditionalSpy)
|
||||
|
||||
expect(dummy).toBe('other')
|
||||
expect(conditionalSpy).toHaveBeenCalledTimes(1)
|
||||
obj.prop = 'Hi'
|
||||
expect(dummy).toBe('other')
|
||||
expect(conditionalSpy).toHaveBeenCalledTimes(1)
|
||||
obj.run = true
|
||||
expect(dummy).toBe('Hi')
|
||||
expect(conditionalSpy).toHaveBeenCalledTimes(2)
|
||||
obj.prop = 'World'
|
||||
expect(dummy).toBe('World')
|
||||
expect(conditionalSpy).toHaveBeenCalledTimes(3)
|
||||
})
|
||||
|
||||
it('should discover new branches when running manually', () => {
|
||||
let dummy
|
||||
let run = false
|
||||
const obj = state({ prop: 'value' })
|
||||
const runner = effect(() => {
|
||||
dummy = run ? obj.prop : 'other'
|
||||
})
|
||||
|
||||
expect(dummy).toBe('other')
|
||||
runner()
|
||||
expect(dummy).toBe('other')
|
||||
run = true
|
||||
runner()
|
||||
expect(dummy).toBe('value')
|
||||
obj.prop = 'World'
|
||||
expect(dummy).toBe('World')
|
||||
})
|
||||
|
||||
it('should not be triggered by mutating a property, which is used in an inactive branch', () => {
|
||||
let dummy
|
||||
const obj = state({ prop: 'value', run: true })
|
||||
|
||||
const conditionalSpy = jest.fn(() => {
|
||||
dummy = obj.run ? obj.prop : 'other'
|
||||
})
|
||||
effect(conditionalSpy)
|
||||
|
||||
expect(dummy).toBe('value')
|
||||
expect(conditionalSpy).toHaveBeenCalledTimes(1)
|
||||
obj.run = false
|
||||
expect(dummy).toBe('other')
|
||||
expect(conditionalSpy).toHaveBeenCalledTimes(2)
|
||||
obj.prop = 'value2'
|
||||
expect(dummy).toBe('other')
|
||||
expect(conditionalSpy).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('should not double wrap if the passed function is a effect', () => {
|
||||
const runner = effect(() => {})
|
||||
const otherRunner = effect(runner)
|
||||
expect(runner).not.toBe(otherRunner)
|
||||
expect(runner.raw).toBe(otherRunner.raw)
|
||||
})
|
||||
|
||||
it('should not run multiple times for a single mutation', () => {
|
||||
let dummy
|
||||
const obj: any = state()
|
||||
const fnSpy = jest.fn(() => {
|
||||
for (const key in obj) {
|
||||
dummy = obj[key]
|
||||
}
|
||||
dummy = obj.prop
|
||||
})
|
||||
effect(fnSpy)
|
||||
|
||||
expect(fnSpy).toHaveBeenCalledTimes(1)
|
||||
obj.prop = 16
|
||||
expect(dummy).toBe(16)
|
||||
expect(fnSpy).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('should allow nested effects', () => {
|
||||
const nums = state({ num1: 0, num2: 1, num3: 2 })
|
||||
const dummy: any = {}
|
||||
|
||||
const childSpy = jest.fn(() => (dummy.num1 = nums.num1))
|
||||
const childeffect = effect(childSpy)
|
||||
const parentSpy = jest.fn(() => {
|
||||
dummy.num2 = nums.num2
|
||||
childeffect()
|
||||
dummy.num3 = nums.num3
|
||||
})
|
||||
effect(parentSpy)
|
||||
|
||||
expect(dummy).toEqual({ num1: 0, num2: 1, num3: 2 })
|
||||
expect(parentSpy).toHaveBeenCalledTimes(1)
|
||||
expect(childSpy).toHaveBeenCalledTimes(2)
|
||||
// this should only call the childeffect
|
||||
nums.num1 = 4
|
||||
expect(dummy).toEqual({ num1: 4, num2: 1, num3: 2 })
|
||||
expect(parentSpy).toHaveBeenCalledTimes(1)
|
||||
expect(childSpy).toHaveBeenCalledTimes(3)
|
||||
// this calls the parenteffect, which calls the childeffect once
|
||||
nums.num2 = 10
|
||||
expect(dummy).toEqual({ num1: 4, num2: 10, num3: 2 })
|
||||
expect(parentSpy).toHaveBeenCalledTimes(2)
|
||||
expect(childSpy).toHaveBeenCalledTimes(4)
|
||||
// this calls the parenteffect, which calls the childeffect once
|
||||
nums.num3 = 7
|
||||
expect(dummy).toEqual({ num1: 4, num2: 10, num3: 7 })
|
||||
expect(parentSpy).toHaveBeenCalledTimes(3)
|
||||
expect(childSpy).toHaveBeenCalledTimes(5)
|
||||
})
|
||||
|
||||
it('should observe class method invocations', () => {
|
||||
class Model {
|
||||
count: number
|
||||
constructor() {
|
||||
this.count = 0
|
||||
}
|
||||
inc() {
|
||||
this.count++
|
||||
}
|
||||
}
|
||||
const model = state(new Model())
|
||||
let dummy
|
||||
effect(() => {
|
||||
dummy = model.count
|
||||
})
|
||||
expect(dummy).toBe(0)
|
||||
model.inc()
|
||||
expect(dummy).toBe(1)
|
||||
})
|
||||
|
||||
it('scheduler', () => {
|
||||
let runner: any, dummy
|
||||
const scheduler = jest.fn(_runner => {
|
||||
runner = _runner
|
||||
})
|
||||
const obj = state({ foo: 1 })
|
||||
effect(
|
||||
() => {
|
||||
dummy = obj.foo
|
||||
},
|
||||
{ scheduler }
|
||||
)
|
||||
expect(scheduler).not.toHaveBeenCalled()
|
||||
expect(dummy).toBe(1)
|
||||
// should be called on first trigger
|
||||
obj.foo++
|
||||
expect(scheduler).toHaveBeenCalledTimes(1)
|
||||
// should not run yet
|
||||
expect(dummy).toBe(1)
|
||||
// manually run
|
||||
runner()
|
||||
// should have run
|
||||
expect(dummy).toBe(2)
|
||||
})
|
||||
|
||||
it('events: onTrack', () => {
|
||||
let events: any[] = []
|
||||
let dummy
|
||||
const onTrack = jest.fn((e: DebuggerEvent) => {
|
||||
events.push(e)
|
||||
})
|
||||
const obj = state({ foo: 1, bar: 2 })
|
||||
const runner = effect(
|
||||
() => {
|
||||
dummy = obj.foo
|
||||
dummy = 'bar' in obj
|
||||
dummy = Object.keys(obj)
|
||||
},
|
||||
{ onTrack }
|
||||
)
|
||||
expect(dummy).toEqual(['foo', 'bar'])
|
||||
expect(onTrack).toHaveBeenCalledTimes(3)
|
||||
expect(events).toEqual([
|
||||
{
|
||||
effect: runner,
|
||||
target: toRaw(obj),
|
||||
type: OperationTypes.GET,
|
||||
key: 'foo'
|
||||
},
|
||||
{
|
||||
effect: runner,
|
||||
target: toRaw(obj),
|
||||
type: OperationTypes.HAS,
|
||||
key: 'bar'
|
||||
},
|
||||
{
|
||||
effect: runner,
|
||||
target: toRaw(obj),
|
||||
type: OperationTypes.ITERATE,
|
||||
key: ITERATE_KEY
|
||||
}
|
||||
])
|
||||
})
|
||||
|
||||
it('events: onTrigger', () => {
|
||||
let events: any[] = []
|
||||
let dummy
|
||||
const onTrigger = jest.fn((e: DebuggerEvent) => {
|
||||
events.push(e)
|
||||
})
|
||||
const obj = state({ foo: 1 })
|
||||
const runner = effect(
|
||||
() => {
|
||||
dummy = obj.foo
|
||||
},
|
||||
{ onTrigger }
|
||||
)
|
||||
|
||||
obj.foo++
|
||||
expect(dummy).toBe(2)
|
||||
expect(onTrigger).toHaveBeenCalledTimes(1)
|
||||
expect(events[0]).toEqual({
|
||||
effect: runner,
|
||||
target: toRaw(obj),
|
||||
type: OperationTypes.SET,
|
||||
key: 'foo',
|
||||
oldValue: 1,
|
||||
newValue: 2
|
||||
})
|
||||
|
||||
delete obj.foo
|
||||
expect(dummy).toBeUndefined()
|
||||
expect(onTrigger).toHaveBeenCalledTimes(2)
|
||||
expect(events[1]).toEqual({
|
||||
effect: runner,
|
||||
target: toRaw(obj),
|
||||
type: OperationTypes.DELETE,
|
||||
key: 'foo',
|
||||
oldValue: 2
|
||||
})
|
||||
})
|
||||
|
||||
it('stop', () => {
|
||||
let dummy
|
||||
const obj = state({ prop: 1 })
|
||||
const runner = effect(() => {
|
||||
dummy = obj.prop
|
||||
})
|
||||
obj.prop = 2
|
||||
expect(dummy).toBe(2)
|
||||
stop(runner)
|
||||
obj.prop = 3
|
||||
expect(dummy).toBe(2)
|
||||
|
||||
// stopped effect should still be manually callable
|
||||
runner()
|
||||
expect(dummy).toBe(3)
|
||||
})
|
||||
|
||||
it('markNonReactive', () => {
|
||||
const obj = state({
|
||||
foo: markNonReactive({
|
||||
prop: 0
|
||||
})
|
||||
})
|
||||
let dummy
|
||||
effect(() => {
|
||||
dummy = obj.foo.prop
|
||||
})
|
||||
expect(dummy).toBe(0)
|
||||
obj.foo.prop++
|
||||
expect(dummy).toBe(0)
|
||||
obj.foo = { prop: 1 }
|
||||
expect(dummy).toBe(1)
|
||||
})
|
||||
})
|
||||
393
packages/reactivity/__tests__/immutableState.spec.ts
Normal file
393
packages/reactivity/__tests__/immutableState.spec.ts
Normal file
@@ -0,0 +1,393 @@
|
||||
import {
|
||||
state,
|
||||
immutableState,
|
||||
toRaw,
|
||||
isState,
|
||||
isImmutableState,
|
||||
markNonReactive,
|
||||
markImmutable,
|
||||
lock,
|
||||
unlock,
|
||||
effect
|
||||
} from '../src'
|
||||
|
||||
describe('observer/immutable', () => {
|
||||
let warn: any
|
||||
|
||||
beforeEach(() => {
|
||||
warn = jest.spyOn(console, 'warn')
|
||||
warn.mockImplementation(() => {})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
warn.mockRestore()
|
||||
})
|
||||
|
||||
describe('Object', () => {
|
||||
it('should make nested values immutable', () => {
|
||||
const original = { foo: 1, bar: { baz: 2 } }
|
||||
const observed = immutableState(original)
|
||||
expect(observed).not.toBe(original)
|
||||
expect(isState(observed)).toBe(true)
|
||||
expect(isImmutableState(observed)).toBe(true)
|
||||
expect(isState(original)).toBe(false)
|
||||
expect(isImmutableState(original)).toBe(false)
|
||||
expect(isState(observed.bar)).toBe(true)
|
||||
expect(isImmutableState(observed.bar)).toBe(true)
|
||||
expect(isState(original.bar)).toBe(false)
|
||||
expect(isImmutableState(original.bar)).toBe(false)
|
||||
// get
|
||||
expect(observed.foo).toBe(1)
|
||||
// has
|
||||
expect('foo' in observed).toBe(true)
|
||||
// ownKeys
|
||||
expect(Object.keys(observed)).toEqual(['foo', 'bar'])
|
||||
})
|
||||
|
||||
it('should not allow mutation', () => {
|
||||
const observed = immutableState({ foo: 1, bar: { baz: 2 } })
|
||||
observed.foo = 2
|
||||
expect(observed.foo).toBe(1)
|
||||
expect(warn).toHaveBeenCalledTimes(1)
|
||||
observed.bar.baz = 3
|
||||
expect(observed.bar.baz).toBe(2)
|
||||
expect(warn).toHaveBeenCalledTimes(2)
|
||||
delete observed.foo
|
||||
expect(observed.foo).toBe(1)
|
||||
expect(warn).toHaveBeenCalledTimes(3)
|
||||
delete observed.bar.baz
|
||||
expect(observed.bar.baz).toBe(2)
|
||||
expect(warn).toHaveBeenCalledTimes(4)
|
||||
})
|
||||
|
||||
it('should allow mutation when unlocked', () => {
|
||||
const observed: any = immutableState({ foo: 1, bar: { baz: 2 } })
|
||||
unlock()
|
||||
observed.prop = 2
|
||||
observed.bar.qux = 3
|
||||
delete observed.bar.baz
|
||||
delete observed.foo
|
||||
lock()
|
||||
expect(observed.prop).toBe(2)
|
||||
expect(observed.foo).toBeUndefined()
|
||||
expect(observed.bar.qux).toBe(3)
|
||||
expect('baz' in observed.bar).toBe(false)
|
||||
expect(warn).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should not trigger effects when locked', () => {
|
||||
const observed = immutableState({ a: 1 })
|
||||
let dummy
|
||||
effect(() => {
|
||||
dummy = observed.a
|
||||
})
|
||||
expect(dummy).toBe(1)
|
||||
observed.a = 2
|
||||
expect(observed.a).toBe(1)
|
||||
expect(dummy).toBe(1)
|
||||
})
|
||||
|
||||
it('should trigger effects when unlocked', () => {
|
||||
const observed = immutableState({ a: 1 })
|
||||
let dummy
|
||||
effect(() => {
|
||||
dummy = observed.a
|
||||
})
|
||||
expect(dummy).toBe(1)
|
||||
unlock()
|
||||
observed.a = 2
|
||||
lock()
|
||||
expect(observed.a).toBe(2)
|
||||
expect(dummy).toBe(2)
|
||||
})
|
||||
})
|
||||
|
||||
describe('Array', () => {
|
||||
it('should make nested values immutable', () => {
|
||||
const original: any[] = [{ foo: 1 }]
|
||||
const observed = immutableState(original)
|
||||
expect(observed).not.toBe(original)
|
||||
expect(isState(observed)).toBe(true)
|
||||
expect(isImmutableState(observed)).toBe(true)
|
||||
expect(isState(original)).toBe(false)
|
||||
expect(isImmutableState(original)).toBe(false)
|
||||
expect(isState(observed[0])).toBe(true)
|
||||
expect(isImmutableState(observed[0])).toBe(true)
|
||||
expect(isState(original[0])).toBe(false)
|
||||
expect(isImmutableState(original[0])).toBe(false)
|
||||
// get
|
||||
expect(observed[0].foo).toBe(1)
|
||||
// has
|
||||
expect(0 in observed).toBe(true)
|
||||
// ownKeys
|
||||
expect(Object.keys(observed)).toEqual(['0'])
|
||||
})
|
||||
|
||||
it('should not allow mutation', () => {
|
||||
const observed: any = immutableState([{ foo: 1 }])
|
||||
observed[0] = 1
|
||||
expect(observed[0]).not.toBe(1)
|
||||
expect(warn).toHaveBeenCalledTimes(1)
|
||||
observed[0].foo = 2
|
||||
expect(observed[0].foo).toBe(1)
|
||||
expect(warn).toHaveBeenCalledTimes(2)
|
||||
|
||||
// should block length mutation
|
||||
observed.length = 0
|
||||
expect(observed.length).toBe(1)
|
||||
expect(observed[0].foo).toBe(1)
|
||||
expect(warn).toHaveBeenCalledTimes(3)
|
||||
|
||||
// mutation methods invoke set/length internally and thus are blocked as well
|
||||
observed.push(2)
|
||||
expect(observed.length).toBe(1)
|
||||
// push triggers two warnings on [1] and .length
|
||||
expect(warn).toHaveBeenCalledTimes(5)
|
||||
})
|
||||
|
||||
it('should allow mutation when unlocked', () => {
|
||||
const observed: any[] = immutableState([{ foo: 1, bar: { baz: 2 } }])
|
||||
unlock()
|
||||
observed[1] = 2
|
||||
observed.push(3)
|
||||
observed[0].foo = 2
|
||||
observed[0].bar.baz = 3
|
||||
lock()
|
||||
expect(observed.length).toBe(3)
|
||||
expect(observed[1]).toBe(2)
|
||||
expect(observed[2]).toBe(3)
|
||||
expect(observed[0].foo).toBe(2)
|
||||
expect(observed[0].bar.baz).toBe(3)
|
||||
expect(warn).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should not trigger effects when locked', () => {
|
||||
const observed = immutableState([{ a: 1 }])
|
||||
let dummy
|
||||
effect(() => {
|
||||
dummy = observed[0].a
|
||||
})
|
||||
expect(dummy).toBe(1)
|
||||
observed[0].a = 2
|
||||
expect(observed[0].a).toBe(1)
|
||||
expect(dummy).toBe(1)
|
||||
observed[0] = { a: 2 }
|
||||
expect(observed[0].a).toBe(1)
|
||||
expect(dummy).toBe(1)
|
||||
})
|
||||
|
||||
it('should trigger effects when unlocked', () => {
|
||||
const observed = immutableState([{ a: 1 }])
|
||||
let dummy
|
||||
effect(() => {
|
||||
dummy = observed[0].a
|
||||
})
|
||||
expect(dummy).toBe(1)
|
||||
|
||||
unlock()
|
||||
|
||||
observed[0].a = 2
|
||||
expect(observed[0].a).toBe(2)
|
||||
expect(dummy).toBe(2)
|
||||
|
||||
observed[0] = { a: 3 }
|
||||
expect(observed[0].a).toBe(3)
|
||||
expect(dummy).toBe(3)
|
||||
|
||||
observed.unshift({ a: 4 })
|
||||
expect(observed[0].a).toBe(4)
|
||||
expect(dummy).toBe(4)
|
||||
lock()
|
||||
})
|
||||
})
|
||||
|
||||
const maps = [Map, WeakMap]
|
||||
maps.forEach((Collection: any) => {
|
||||
describe(Collection.name, () => {
|
||||
test('should make nested values immutable', () => {
|
||||
const key1 = {}
|
||||
const key2 = {}
|
||||
const original = new Collection([[key1, {}], [key2, {}]])
|
||||
const observed = immutableState(original)
|
||||
expect(observed).not.toBe(original)
|
||||
expect(isState(observed)).toBe(true)
|
||||
expect(isImmutableState(observed)).toBe(true)
|
||||
expect(isState(original)).toBe(false)
|
||||
expect(isImmutableState(original)).toBe(false)
|
||||
expect(isState(observed.get(key1))).toBe(true)
|
||||
expect(isImmutableState(observed.get(key1))).toBe(true)
|
||||
expect(isState(original.get(key1))).toBe(false)
|
||||
expect(isImmutableState(original.get(key1))).toBe(false)
|
||||
})
|
||||
|
||||
test('should not allow mutation & not trigger effect', () => {
|
||||
const map = immutableState(new Collection())
|
||||
const key = {}
|
||||
let dummy
|
||||
effect(() => {
|
||||
dummy = map.get(key)
|
||||
})
|
||||
expect(dummy).toBeUndefined()
|
||||
map.set(key, 1)
|
||||
expect(dummy).toBeUndefined()
|
||||
expect(map.has(key)).toBe(false)
|
||||
expect(warn).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
test('should allow mutation & trigger effect when unlocked', () => {
|
||||
const map = immutableState(new Collection())
|
||||
const isWeak = Collection === WeakMap
|
||||
const key = {}
|
||||
let dummy
|
||||
effect(() => {
|
||||
dummy = map.get(key) + (isWeak ? 0 : map.size)
|
||||
})
|
||||
expect(dummy).toBeNaN()
|
||||
unlock()
|
||||
map.set(key, 1)
|
||||
lock()
|
||||
expect(dummy).toBe(isWeak ? 1 : 2)
|
||||
expect(map.get(key)).toBe(1)
|
||||
expect(warn).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
if (Collection === Map) {
|
||||
test('should retrive immutable values on iteration', () => {
|
||||
const key1 = {}
|
||||
const key2 = {}
|
||||
const original = new Collection([[key1, {}], [key2, {}]])
|
||||
const observed = immutableState(original)
|
||||
for (const [key, value] of observed) {
|
||||
expect(isImmutableState(key)).toBe(true)
|
||||
expect(isImmutableState(value)).toBe(true)
|
||||
}
|
||||
observed.forEach((value: any) => {
|
||||
expect(isImmutableState(value)).toBe(true)
|
||||
})
|
||||
for (const value of observed.values()) {
|
||||
expect(isImmutableState(value)).toBe(true)
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
const sets = [Set, WeakSet]
|
||||
sets.forEach((Collection: any) => {
|
||||
describe(Collection.name, () => {
|
||||
test('should make nested values immutable', () => {
|
||||
const key1 = {}
|
||||
const key2 = {}
|
||||
const original = new Collection([key1, key2])
|
||||
const observed = immutableState(original)
|
||||
expect(observed).not.toBe(original)
|
||||
expect(isState(observed)).toBe(true)
|
||||
expect(isImmutableState(observed)).toBe(true)
|
||||
expect(isState(original)).toBe(false)
|
||||
expect(isImmutableState(original)).toBe(false)
|
||||
expect(observed.has(state(key1))).toBe(true)
|
||||
expect(original.has(state(key1))).toBe(false)
|
||||
})
|
||||
|
||||
test('should not allow mutation & not trigger effect', () => {
|
||||
const set = immutableState(new Collection())
|
||||
const key = {}
|
||||
let dummy
|
||||
effect(() => {
|
||||
dummy = set.has(key)
|
||||
})
|
||||
expect(dummy).toBe(false)
|
||||
set.add(key)
|
||||
expect(dummy).toBe(false)
|
||||
expect(set.has(key)).toBe(false)
|
||||
expect(warn).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
test('should allow mutation & trigger effect when unlocked', () => {
|
||||
const set = immutableState(new Collection())
|
||||
const key = {}
|
||||
let dummy
|
||||
effect(() => {
|
||||
dummy = set.has(key)
|
||||
})
|
||||
expect(dummy).toBe(false)
|
||||
unlock()
|
||||
set.add(key)
|
||||
lock()
|
||||
expect(dummy).toBe(true)
|
||||
expect(set.has(key)).toBe(true)
|
||||
expect(warn).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
if (Collection === Set) {
|
||||
test('should retrive immutable values on iteration', () => {
|
||||
const original = new Collection([{}, {}])
|
||||
const observed = immutableState(original)
|
||||
for (const value of observed) {
|
||||
expect(isImmutableState(value)).toBe(true)
|
||||
}
|
||||
observed.forEach((value: any) => {
|
||||
expect(isImmutableState(value)).toBe(true)
|
||||
})
|
||||
for (const value of observed.values()) {
|
||||
expect(isImmutableState(value)).toBe(true)
|
||||
}
|
||||
for (const [v1, v2] of observed.entries()) {
|
||||
expect(isImmutableState(v1)).toBe(true)
|
||||
expect(isImmutableState(v2)).toBe(true)
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
test('calling observable on an immutable should return immutable', () => {
|
||||
const a = immutableState()
|
||||
const b = state(a)
|
||||
expect(isImmutableState(b)).toBe(true)
|
||||
// should point to same original
|
||||
expect(toRaw(a)).toBe(toRaw(b))
|
||||
})
|
||||
|
||||
test('calling immutable on an observable should return immutable', () => {
|
||||
const a = state()
|
||||
const b = immutableState(a)
|
||||
expect(isImmutableState(b)).toBe(true)
|
||||
// should point to same original
|
||||
expect(toRaw(a)).toBe(toRaw(b))
|
||||
})
|
||||
|
||||
test('observing already observed value should return same Proxy', () => {
|
||||
const original = { foo: 1 }
|
||||
const observed = immutableState(original)
|
||||
const observed2 = immutableState(observed)
|
||||
expect(observed2).toBe(observed)
|
||||
})
|
||||
|
||||
test('observing the same value multiple times should return same Proxy', () => {
|
||||
const original = { foo: 1 }
|
||||
const observed = immutableState(original)
|
||||
const observed2 = immutableState(original)
|
||||
expect(observed2).toBe(observed)
|
||||
})
|
||||
|
||||
test('markNonReactive', () => {
|
||||
const obj = immutableState({
|
||||
foo: { a: 1 },
|
||||
bar: markNonReactive({ b: 2 })
|
||||
})
|
||||
expect(isState(obj.foo)).toBe(true)
|
||||
expect(isState(obj.bar)).toBe(false)
|
||||
})
|
||||
|
||||
test('markImmutable', () => {
|
||||
const obj = state({
|
||||
foo: { a: 1 },
|
||||
bar: markImmutable({ b: 2 })
|
||||
})
|
||||
expect(isState(obj.foo)).toBe(true)
|
||||
expect(isState(obj.bar)).toBe(true)
|
||||
expect(isImmutableState(obj.foo)).toBe(false)
|
||||
expect(isImmutableState(obj.bar)).toBe(true)
|
||||
})
|
||||
})
|
||||
174
packages/reactivity/__tests__/state.spec.ts
Normal file
174
packages/reactivity/__tests__/state.spec.ts
Normal file
@@ -0,0 +1,174 @@
|
||||
import { state, isState, toRaw, markNonReactive } from '../src/index'
|
||||
|
||||
describe('observer/observable', () => {
|
||||
test('Object', () => {
|
||||
const original = { foo: 1 }
|
||||
const observed = state(original)
|
||||
expect(observed).not.toBe(original)
|
||||
expect(isState(observed)).toBe(true)
|
||||
expect(isState(original)).toBe(false)
|
||||
// get
|
||||
expect(observed.foo).toBe(1)
|
||||
// has
|
||||
expect('foo' in observed).toBe(true)
|
||||
// ownKeys
|
||||
expect(Object.keys(observed)).toEqual(['foo'])
|
||||
})
|
||||
|
||||
test('Array', () => {
|
||||
const original: any[] = [{ foo: 1 }]
|
||||
const observed = state(original)
|
||||
expect(observed).not.toBe(original)
|
||||
expect(isState(observed)).toBe(true)
|
||||
expect(isState(original)).toBe(false)
|
||||
expect(isState(observed[0])).toBe(true)
|
||||
// get
|
||||
expect(observed[0].foo).toBe(1)
|
||||
// has
|
||||
expect(0 in observed).toBe(true)
|
||||
// ownKeys
|
||||
expect(Object.keys(observed)).toEqual(['0'])
|
||||
})
|
||||
|
||||
test('cloned observable Array should point to observed values', () => {
|
||||
const original = [{ foo: 1 }]
|
||||
const observed = state(original)
|
||||
const clone = observed.slice()
|
||||
expect(isState(clone[0])).toBe(true)
|
||||
expect(clone[0]).not.toBe(original[0])
|
||||
expect(clone[0]).toBe(observed[0])
|
||||
})
|
||||
|
||||
test('nested observables', () => {
|
||||
const original = {
|
||||
nested: {
|
||||
foo: 1
|
||||
},
|
||||
array: [{ bar: 2 }]
|
||||
}
|
||||
const observed = state(original)
|
||||
expect(isState(observed.nested)).toBe(true)
|
||||
expect(isState(observed.array)).toBe(true)
|
||||
expect(isState(observed.array[0])).toBe(true)
|
||||
})
|
||||
|
||||
test('observed value should proxy mutations to original (Object)', () => {
|
||||
const original: any = { foo: 1 }
|
||||
const observed = state(original)
|
||||
// set
|
||||
observed.bar = 1
|
||||
expect(observed.bar).toBe(1)
|
||||
expect(original.bar).toBe(1)
|
||||
// delete
|
||||
delete observed.foo
|
||||
expect('foo' in observed).toBe(false)
|
||||
expect('foo' in original).toBe(false)
|
||||
})
|
||||
|
||||
test('observed value should proxy mutations to original (Array)', () => {
|
||||
const original: any[] = [{ foo: 1 }, { bar: 2 }]
|
||||
const observed = state(original)
|
||||
// set
|
||||
const value = { baz: 3 }
|
||||
const observableValue = state(value)
|
||||
observed[0] = value
|
||||
expect(observed[0]).toBe(observableValue)
|
||||
expect(original[0]).toBe(value)
|
||||
// delete
|
||||
delete observed[0]
|
||||
expect(observed[0]).toBeUndefined()
|
||||
expect(original[0]).toBeUndefined()
|
||||
// mutating methods
|
||||
observed.push(value)
|
||||
expect(observed[2]).toBe(observableValue)
|
||||
expect(original[2]).toBe(value)
|
||||
})
|
||||
|
||||
test('setting a property with an unobserved value should wrap with observable', () => {
|
||||
const observed: any = state({})
|
||||
const raw = {}
|
||||
observed.foo = raw
|
||||
expect(observed.foo).not.toBe(raw)
|
||||
expect(isState(observed.foo)).toBe(true)
|
||||
})
|
||||
|
||||
test('observing already observed value should return same Proxy', () => {
|
||||
const original = { foo: 1 }
|
||||
const observed = state(original)
|
||||
const observed2 = state(observed)
|
||||
expect(observed2).toBe(observed)
|
||||
})
|
||||
|
||||
test('observing the same value multiple times should return same Proxy', () => {
|
||||
const original = { foo: 1 }
|
||||
const observed = state(original)
|
||||
const observed2 = state(original)
|
||||
expect(observed2).toBe(observed)
|
||||
})
|
||||
|
||||
test('should not pollute original object with Proxies', () => {
|
||||
const original: any = { foo: 1 }
|
||||
const original2 = { bar: 2 }
|
||||
const observed = state(original)
|
||||
const observed2 = state(original2)
|
||||
observed.bar = observed2
|
||||
expect(observed.bar).toBe(observed2)
|
||||
expect(original.bar).toBe(original2)
|
||||
})
|
||||
|
||||
test('unwrap', () => {
|
||||
const original = { foo: 1 }
|
||||
const observed = state(original)
|
||||
expect(toRaw(observed)).toBe(original)
|
||||
expect(toRaw(original)).toBe(original)
|
||||
})
|
||||
|
||||
test('unobservable values', () => {
|
||||
const warn = jest.spyOn(console, 'warn')
|
||||
let lastMsg: string
|
||||
warn.mockImplementation(msg => {
|
||||
lastMsg = msg
|
||||
})
|
||||
|
||||
const getMsg = (value: any) => `value is not observable: ${String(value)}`
|
||||
const assertValue = (value: any) => {
|
||||
state(value)
|
||||
expect(lastMsg).toMatch(getMsg(value))
|
||||
}
|
||||
|
||||
// number
|
||||
assertValue(1)
|
||||
// string
|
||||
assertValue('foo')
|
||||
// boolean
|
||||
assertValue(false)
|
||||
// null
|
||||
assertValue(null)
|
||||
// undefined should work because it returns empty object observable
|
||||
lastMsg = ''
|
||||
state(undefined)
|
||||
expect(lastMsg).toBe('')
|
||||
// symbol
|
||||
const s = Symbol()
|
||||
assertValue(s)
|
||||
|
||||
warn.mockRestore()
|
||||
|
||||
// built-ins should work and return same value
|
||||
const p = Promise.resolve()
|
||||
expect(state(p)).toBe(p)
|
||||
const r = new RegExp('')
|
||||
expect(state(r)).toBe(r)
|
||||
const d = new Date()
|
||||
expect(state(d)).toBe(d)
|
||||
})
|
||||
|
||||
test('markNonReactive', () => {
|
||||
const obj = state({
|
||||
foo: { a: 1 },
|
||||
bar: markNonReactive({ b: 2 })
|
||||
})
|
||||
expect(isState(obj.foo)).toBe(true)
|
||||
expect(isState(obj.bar)).toBe(false)
|
||||
})
|
||||
})
|
||||
65
packages/reactivity/__tests__/value.spec.ts
Normal file
65
packages/reactivity/__tests__/value.spec.ts
Normal file
@@ -0,0 +1,65 @@
|
||||
import { value } from '../src/value'
|
||||
import { effect, state } from '../src/index'
|
||||
|
||||
describe('observer/value', () => {
|
||||
it('should hold a value', () => {
|
||||
const a = value(1)
|
||||
expect(a.value).toBe(1)
|
||||
a.value = 2
|
||||
expect(a.value).toBe(2)
|
||||
})
|
||||
|
||||
it('should be reactive', () => {
|
||||
const a = value(1)
|
||||
let dummy
|
||||
effect(() => {
|
||||
dummy = a.value
|
||||
})
|
||||
expect(dummy).toBe(1)
|
||||
a.value = 2
|
||||
expect(dummy).toBe(2)
|
||||
})
|
||||
|
||||
it('should make nested properties reactive', () => {
|
||||
const a = value({
|
||||
count: 1
|
||||
})
|
||||
let dummy
|
||||
effect(() => {
|
||||
dummy = a.value.count
|
||||
})
|
||||
expect(dummy).toBe(1)
|
||||
a.value.count = 2
|
||||
expect(dummy).toBe(2)
|
||||
})
|
||||
|
||||
it('should work like a normal property when nested in an observable', () => {
|
||||
const a = value(1)
|
||||
const obj = state({
|
||||
a,
|
||||
b: {
|
||||
c: a,
|
||||
d: [a]
|
||||
}
|
||||
})
|
||||
let dummy1
|
||||
let dummy2
|
||||
let dummy3
|
||||
effect(() => {
|
||||
dummy1 = obj.a
|
||||
dummy2 = obj.b.c
|
||||
dummy3 = obj.b.d[0]
|
||||
})
|
||||
expect(dummy1).toBe(1)
|
||||
expect(dummy2).toBe(1)
|
||||
expect(dummy3).toBe(1)
|
||||
a.value++
|
||||
expect(dummy1).toBe(2)
|
||||
expect(dummy2).toBe(2)
|
||||
expect(dummy3).toBe(2)
|
||||
obj.a++
|
||||
expect(dummy1).toBe(3)
|
||||
expect(dummy2).toBe(3)
|
||||
expect(dummy3).toBe(3)
|
||||
})
|
||||
})
|
||||
7
packages/reactivity/index.js
Normal file
7
packages/reactivity/index.js
Normal file
@@ -0,0 +1,7 @@
|
||||
'use strict'
|
||||
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
module.exports = require('./dist/reactivity.cjs.prod.js.js')
|
||||
} else {
|
||||
module.exports = require('./dist/reactivity.cjs.js.js')
|
||||
}
|
||||
27
packages/reactivity/package.json
Normal file
27
packages/reactivity/package.json
Normal file
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"name": "@vue/reactivity",
|
||||
"version": "3.0.0-alpha.1",
|
||||
"description": "@vue/reactivity",
|
||||
"main": "index.js",
|
||||
"module": "dist/reactivity.esm-bundler.js",
|
||||
"types": "dist/index.d.ts",
|
||||
"unpkg": "dist/reactivity.global.js",
|
||||
"sideEffects": false,
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/vuejs/vue.git"
|
||||
},
|
||||
"buildOptions": {
|
||||
"name": "VueObserver",
|
||||
"formats": ["esm", "cjs", "global", "esm-browser"]
|
||||
},
|
||||
"keywords": [
|
||||
"vue"
|
||||
],
|
||||
"author": "Evan You",
|
||||
"license": "MIT",
|
||||
"bugs": {
|
||||
"url": "https://github.com/vuejs/vue/issues"
|
||||
},
|
||||
"homepage": "https://github.com/vuejs/vue/tree/dev/packages/reactivity#readme"
|
||||
}
|
||||
138
packages/reactivity/src/baseHandlers.ts
Normal file
138
packages/reactivity/src/baseHandlers.ts
Normal file
@@ -0,0 +1,138 @@
|
||||
import { state, immutableState, toRaw } from './index'
|
||||
import { OperationTypes } from './operations'
|
||||
import { track, trigger } from './effect'
|
||||
import { LOCKED } from './lock'
|
||||
import { isObject } from '@vue/shared'
|
||||
import { isValue } from './value'
|
||||
|
||||
const hasOwnProperty = Object.prototype.hasOwnProperty
|
||||
|
||||
const builtInSymbols = new Set(
|
||||
Object.getOwnPropertyNames(Symbol)
|
||||
.map(key => (Symbol as any)[key])
|
||||
.filter(value => typeof value === 'symbol')
|
||||
)
|
||||
|
||||
function createGetter(isImmutable: boolean) {
|
||||
return function get(target: any, key: string | symbol, receiver: any) {
|
||||
const res = Reflect.get(target, key, receiver)
|
||||
if (typeof key === 'symbol' && builtInSymbols.has(key)) {
|
||||
return res
|
||||
}
|
||||
if (isValue(res)) {
|
||||
return res.value
|
||||
}
|
||||
track(target, OperationTypes.GET, key)
|
||||
return isObject(res)
|
||||
? isImmutable
|
||||
? // need to lazy access immutable and observable here to avoid
|
||||
// circular dependency
|
||||
immutableState(res)
|
||||
: state(res)
|
||||
: res
|
||||
}
|
||||
}
|
||||
|
||||
function set(
|
||||
target: any,
|
||||
key: string | symbol,
|
||||
value: any,
|
||||
receiver: any
|
||||
): boolean {
|
||||
value = toRaw(value)
|
||||
const hadKey = hasOwnProperty.call(target, key)
|
||||
const oldValue = target[key]
|
||||
if (isValue(oldValue)) {
|
||||
oldValue.value = value
|
||||
return true
|
||||
}
|
||||
const result = Reflect.set(target, key, value, receiver)
|
||||
// don't trigger if target is something up in the prototype chain of original
|
||||
if (target === toRaw(receiver)) {
|
||||
/* istanbul ignore else */
|
||||
if (__DEV__) {
|
||||
const extraInfo = { oldValue, newValue: value }
|
||||
if (!hadKey) {
|
||||
trigger(target, OperationTypes.ADD, key, extraInfo)
|
||||
} else if (value !== oldValue) {
|
||||
trigger(target, OperationTypes.SET, key, extraInfo)
|
||||
}
|
||||
} else {
|
||||
if (!hadKey) {
|
||||
trigger(target, OperationTypes.ADD, key)
|
||||
} else if (value !== oldValue) {
|
||||
trigger(target, OperationTypes.SET, key)
|
||||
}
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
function deleteProperty(target: any, key: string | symbol): boolean {
|
||||
const hadKey = hasOwnProperty.call(target, key)
|
||||
const oldValue = target[key]
|
||||
const result = Reflect.deleteProperty(target, key)
|
||||
if (hadKey) {
|
||||
/* istanbul ignore else */
|
||||
if (__DEV__) {
|
||||
trigger(target, OperationTypes.DELETE, key, { oldValue })
|
||||
} else {
|
||||
trigger(target, OperationTypes.DELETE, key)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
function has(target: any, key: string | symbol): boolean {
|
||||
const result = Reflect.has(target, key)
|
||||
track(target, OperationTypes.HAS, key)
|
||||
return result
|
||||
}
|
||||
|
||||
function ownKeys(target: any): (string | number | symbol)[] {
|
||||
track(target, OperationTypes.ITERATE)
|
||||
return Reflect.ownKeys(target)
|
||||
}
|
||||
|
||||
export const mutableHandlers: ProxyHandler<any> = {
|
||||
get: createGetter(false),
|
||||
set,
|
||||
deleteProperty,
|
||||
has,
|
||||
ownKeys
|
||||
}
|
||||
|
||||
export const immutableHandlers: ProxyHandler<any> = {
|
||||
get: createGetter(true),
|
||||
|
||||
set(target: any, key: string | symbol, value: any, receiver: any): boolean {
|
||||
if (LOCKED) {
|
||||
if (__DEV__) {
|
||||
console.warn(
|
||||
`Set operation on key "${key as any}" failed: target is immutable.`,
|
||||
target
|
||||
)
|
||||
}
|
||||
return true
|
||||
} else {
|
||||
return set(target, key, value, receiver)
|
||||
}
|
||||
},
|
||||
|
||||
deleteProperty(target: any, key: string | symbol): boolean {
|
||||
if (LOCKED) {
|
||||
if (__DEV__) {
|
||||
console.warn(
|
||||
`Delete operation on key "${key as any}" failed: target is immutable.`,
|
||||
target
|
||||
)
|
||||
}
|
||||
return true
|
||||
} else {
|
||||
return deleteProperty(target, key)
|
||||
}
|
||||
},
|
||||
|
||||
has,
|
||||
ownKeys
|
||||
}
|
||||
239
packages/reactivity/src/collectionHandlers.ts
Normal file
239
packages/reactivity/src/collectionHandlers.ts
Normal file
@@ -0,0 +1,239 @@
|
||||
import { toRaw, state, immutableState } from './index'
|
||||
import { track, trigger } from './effect'
|
||||
import { OperationTypes } from './operations'
|
||||
import { LOCKED } from './lock'
|
||||
import { isObject } from '@vue/shared'
|
||||
|
||||
const toObservable = (value: any) => (isObject(value) ? state(value) : value)
|
||||
const toImmutable = (value: any) =>
|
||||
isObject(value) ? immutableState(value) : value
|
||||
|
||||
function get(target: any, key: any, wrap: (t: any) => any): any {
|
||||
target = toRaw(target)
|
||||
key = toRaw(key)
|
||||
const proto: any = Reflect.getPrototypeOf(target)
|
||||
track(target, OperationTypes.GET, key)
|
||||
const res = proto.get.call(target, key)
|
||||
return wrap(res)
|
||||
}
|
||||
|
||||
function has(key: any): boolean {
|
||||
const target = toRaw(this)
|
||||
key = toRaw(key)
|
||||
const proto: any = Reflect.getPrototypeOf(target)
|
||||
track(target, OperationTypes.HAS, key)
|
||||
return proto.has.call(target, key)
|
||||
}
|
||||
|
||||
function size(target: any) {
|
||||
target = toRaw(target)
|
||||
const proto = Reflect.getPrototypeOf(target)
|
||||
track(target, OperationTypes.ITERATE)
|
||||
return Reflect.get(proto, 'size', target)
|
||||
}
|
||||
|
||||
function add(value: any) {
|
||||
value = toRaw(value)
|
||||
const target = toRaw(this)
|
||||
const proto: any = Reflect.getPrototypeOf(this)
|
||||
const hadKey = proto.has.call(target, value)
|
||||
const result = proto.add.call(target, value)
|
||||
if (!hadKey) {
|
||||
/* istanbul ignore else */
|
||||
if (__DEV__) {
|
||||
trigger(target, OperationTypes.ADD, value, { value })
|
||||
} else {
|
||||
trigger(target, OperationTypes.ADD, value)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
function set(key: any, value: any) {
|
||||
value = toRaw(value)
|
||||
const target = toRaw(this)
|
||||
const proto: any = Reflect.getPrototypeOf(this)
|
||||
const hadKey = proto.has.call(target, key)
|
||||
const oldValue = proto.get.call(target, key)
|
||||
const result = proto.set.call(target, key, value)
|
||||
if (value !== oldValue) {
|
||||
/* istanbul ignore else */
|
||||
if (__DEV__) {
|
||||
const extraInfo = { oldValue, newValue: value }
|
||||
if (!hadKey) {
|
||||
trigger(target, OperationTypes.ADD, key, extraInfo)
|
||||
} else {
|
||||
trigger(target, OperationTypes.SET, key, extraInfo)
|
||||
}
|
||||
} else {
|
||||
if (!hadKey) {
|
||||
trigger(target, OperationTypes.ADD, key)
|
||||
} else {
|
||||
trigger(target, OperationTypes.SET, key)
|
||||
}
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
function deleteEntry(key: any) {
|
||||
const target = toRaw(this)
|
||||
const proto: any = Reflect.getPrototypeOf(this)
|
||||
const hadKey = proto.has.call(target, key)
|
||||
const oldValue = proto.get ? proto.get.call(target, key) : undefined
|
||||
// forward the operation before queueing reactions
|
||||
const result = proto.delete.call(target, key)
|
||||
if (hadKey) {
|
||||
/* istanbul ignore else */
|
||||
if (__DEV__) {
|
||||
trigger(target, OperationTypes.DELETE, key, { oldValue })
|
||||
} else {
|
||||
trigger(target, OperationTypes.DELETE, key)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
function clear() {
|
||||
const target = toRaw(this)
|
||||
const proto: any = Reflect.getPrototypeOf(this)
|
||||
const hadItems = target.size !== 0
|
||||
const oldTarget = target instanceof Map ? new Map(target) : new Set(target)
|
||||
// forward the operation before queueing reactions
|
||||
const result = proto.clear.call(target)
|
||||
if (hadItems) {
|
||||
/* istanbul ignore else */
|
||||
if (__DEV__) {
|
||||
trigger(target, OperationTypes.CLEAR, void 0, { oldTarget })
|
||||
} else {
|
||||
trigger(target, OperationTypes.CLEAR)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
function createForEach(isImmutable: boolean) {
|
||||
return function forEach(callback: Function, thisArg?: any) {
|
||||
const observed = this
|
||||
const target = toRaw(observed)
|
||||
const proto: any = Reflect.getPrototypeOf(target)
|
||||
const wrap = isImmutable ? toImmutable : toObservable
|
||||
track(target, OperationTypes.ITERATE)
|
||||
// important: create sure the callback is
|
||||
// 1. invoked with the observable map as `this` and 3rd arg
|
||||
// 2. the value received should be a corresponding observable/immutable.
|
||||
function wrappedCallback(value: any, key: any) {
|
||||
return callback.call(observed, wrap(value), wrap(key), observed)
|
||||
}
|
||||
return proto.forEach.call(target, wrappedCallback, thisArg)
|
||||
}
|
||||
}
|
||||
|
||||
function createIterableMethod(method: string | symbol, isImmutable: boolean) {
|
||||
return function(...args: any[]) {
|
||||
const target = toRaw(this)
|
||||
const proto: any = Reflect.getPrototypeOf(target)
|
||||
const isPair =
|
||||
method === 'entries' ||
|
||||
(method === Symbol.iterator && target instanceof Map)
|
||||
const innerIterator = proto[method].apply(target, args)
|
||||
const wrap = isImmutable ? toImmutable : toObservable
|
||||
track(target, OperationTypes.ITERATE)
|
||||
// return a wrapped iterator which returns observed versions of the
|
||||
// values emitted from the real iterator
|
||||
return {
|
||||
// iterator protocol
|
||||
next() {
|
||||
const { value, done } = innerIterator.next()
|
||||
return done
|
||||
? { value, done }
|
||||
: {
|
||||
value: isPair ? [wrap(value[0]), wrap(value[1])] : wrap(value),
|
||||
done
|
||||
}
|
||||
},
|
||||
// iterable protocol
|
||||
[Symbol.iterator]() {
|
||||
return this
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function createImmutableMethod(
|
||||
method: Function,
|
||||
type: OperationTypes
|
||||
): Function {
|
||||
return function(...args: any[]) {
|
||||
if (LOCKED) {
|
||||
if (__DEV__) {
|
||||
const key = args[0] ? `on key "${args[0]}"` : ``
|
||||
console.warn(
|
||||
`${type} operation ${key}failed: target is immutable.`,
|
||||
toRaw(this)
|
||||
)
|
||||
}
|
||||
return type === OperationTypes.DELETE ? false : this
|
||||
} else {
|
||||
return method.apply(this, args)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const mutableInstrumentations: any = {
|
||||
get(key: any) {
|
||||
return get(this, key, toObservable)
|
||||
},
|
||||
get size() {
|
||||
return size(this)
|
||||
},
|
||||
has,
|
||||
add,
|
||||
set,
|
||||
delete: deleteEntry,
|
||||
clear,
|
||||
forEach: createForEach(false)
|
||||
}
|
||||
|
||||
const immutableInstrumentations: any = {
|
||||
get(key: any) {
|
||||
return get(this, key, toImmutable)
|
||||
},
|
||||
get size() {
|
||||
return size(this)
|
||||
},
|
||||
has,
|
||||
add: createImmutableMethod(add, OperationTypes.ADD),
|
||||
set: createImmutableMethod(set, OperationTypes.SET),
|
||||
delete: createImmutableMethod(deleteEntry, OperationTypes.DELETE),
|
||||
clear: createImmutableMethod(clear, OperationTypes.CLEAR),
|
||||
forEach: createForEach(true)
|
||||
}
|
||||
|
||||
const iteratorMethods = ['keys', 'values', 'entries', Symbol.iterator]
|
||||
iteratorMethods.forEach(method => {
|
||||
mutableInstrumentations[method] = createIterableMethod(method, false)
|
||||
immutableInstrumentations[method] = createIterableMethod(method, true)
|
||||
})
|
||||
|
||||
function createInstrumentationGetter(instrumentations: any) {
|
||||
return function getInstrumented(
|
||||
target: any,
|
||||
key: string | symbol,
|
||||
receiver: any
|
||||
) {
|
||||
target =
|
||||
instrumentations.hasOwnProperty(key) && key in target
|
||||
? instrumentations
|
||||
: target
|
||||
return Reflect.get(target, key, receiver)
|
||||
}
|
||||
}
|
||||
|
||||
export const mutableCollectionHandlers: ProxyHandler<any> = {
|
||||
get: createInstrumentationGetter(mutableInstrumentations)
|
||||
}
|
||||
|
||||
export const immutableCollectionHandlers: ProxyHandler<any> = {
|
||||
get: createInstrumentationGetter(immutableInstrumentations)
|
||||
}
|
||||
62
packages/reactivity/src/computed.ts
Normal file
62
packages/reactivity/src/computed.ts
Normal file
@@ -0,0 +1,62 @@
|
||||
import { effect } from './index'
|
||||
import { ReactiveEffect, activeReactiveEffectStack } from './effect'
|
||||
import { knownValues } from './value'
|
||||
|
||||
export interface ComputedValue<T> {
|
||||
readonly value: T
|
||||
readonly effect: ReactiveEffect
|
||||
}
|
||||
|
||||
export function computed<T>(
|
||||
getter: () => T,
|
||||
setter?: (v: T) => void
|
||||
): ComputedValue<T> {
|
||||
let dirty: boolean = true
|
||||
let value: any = undefined
|
||||
const runner = effect(getter, {
|
||||
lazy: true,
|
||||
// mark effect as computed so that it gets priority during trigger
|
||||
computed: true,
|
||||
scheduler: () => {
|
||||
dirty = true
|
||||
}
|
||||
})
|
||||
const computedValue = {
|
||||
// expose effect so computed can be stopped
|
||||
effect: runner,
|
||||
get value() {
|
||||
if (dirty) {
|
||||
value = runner()
|
||||
dirty = false
|
||||
}
|
||||
// When computed effects are accessed in a parent effect, the parent
|
||||
// should track all the dependencies the computed property has tracked.
|
||||
// This should also apply for chained computed properties.
|
||||
trackChildRun(runner)
|
||||
return value
|
||||
},
|
||||
set value(newValue) {
|
||||
if (setter) {
|
||||
setter(newValue)
|
||||
} else {
|
||||
// TODO warn attempting to mutate readonly computed value
|
||||
}
|
||||
}
|
||||
}
|
||||
knownValues.add(computedValue)
|
||||
return computedValue
|
||||
}
|
||||
|
||||
function trackChildRun(childRunner: ReactiveEffect) {
|
||||
const parentRunner =
|
||||
activeReactiveEffectStack[activeReactiveEffectStack.length - 1]
|
||||
if (parentRunner) {
|
||||
for (let i = 0; i < childRunner.deps.length; i++) {
|
||||
const dep = childRunner.deps[i]
|
||||
if (!dep.has(parentRunner)) {
|
||||
dep.add(parentRunner)
|
||||
parentRunner.deps.push(dep)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
197
packages/reactivity/src/effect.ts
Normal file
197
packages/reactivity/src/effect.ts
Normal file
@@ -0,0 +1,197 @@
|
||||
import { OperationTypes } from './operations'
|
||||
import { Dep, targetMap } from './state'
|
||||
|
||||
export interface ReactiveEffect {
|
||||
(): any
|
||||
isEffect: true
|
||||
active: boolean
|
||||
raw: Function
|
||||
deps: Array<Dep>
|
||||
computed?: boolean
|
||||
scheduler?: Scheduler
|
||||
onTrack?: Debugger
|
||||
onTrigger?: Debugger
|
||||
onStop?: () => void
|
||||
}
|
||||
|
||||
export interface ReactiveEffectOptions {
|
||||
lazy?: boolean
|
||||
computed?: boolean
|
||||
scheduler?: Scheduler
|
||||
onTrack?: Debugger
|
||||
onTrigger?: Debugger
|
||||
onStop?: () => void
|
||||
}
|
||||
|
||||
export type Scheduler = (run: () => any) => void
|
||||
|
||||
export interface DebuggerEvent {
|
||||
effect: ReactiveEffect
|
||||
target: any
|
||||
type: OperationTypes
|
||||
key: string | symbol | undefined
|
||||
}
|
||||
|
||||
export type Debugger = (event: DebuggerEvent) => void
|
||||
|
||||
export const activeReactiveEffectStack: ReactiveEffect[] = []
|
||||
|
||||
export const ITERATE_KEY = Symbol('iterate')
|
||||
|
||||
export function createReactiveEffect(
|
||||
fn: Function,
|
||||
options: ReactiveEffectOptions
|
||||
): ReactiveEffect {
|
||||
const effect = function effect(...args): any {
|
||||
return run(effect as ReactiveEffect, fn, args)
|
||||
} as ReactiveEffect
|
||||
effect.isEffect = true
|
||||
effect.active = true
|
||||
effect.raw = fn
|
||||
effect.scheduler = options.scheduler
|
||||
effect.onTrack = options.onTrack
|
||||
effect.onTrigger = options.onTrigger
|
||||
effect.onStop = options.onStop
|
||||
effect.computed = options.computed
|
||||
effect.deps = []
|
||||
return effect
|
||||
}
|
||||
|
||||
function run(effect: ReactiveEffect, fn: Function, args: any[]): any {
|
||||
if (!effect.active) {
|
||||
return fn(...args)
|
||||
}
|
||||
if (activeReactiveEffectStack.indexOf(effect) === -1) {
|
||||
cleanup(effect)
|
||||
try {
|
||||
activeReactiveEffectStack.push(effect)
|
||||
return fn(...args)
|
||||
} finally {
|
||||
activeReactiveEffectStack.pop()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function cleanup(effect: ReactiveEffect) {
|
||||
const { deps } = effect
|
||||
if (deps.length) {
|
||||
for (let i = 0; i < deps.length; i++) {
|
||||
deps[i].delete(effect)
|
||||
}
|
||||
deps.length = 0
|
||||
}
|
||||
}
|
||||
|
||||
export function track(
|
||||
target: any,
|
||||
type: OperationTypes,
|
||||
key?: string | symbol
|
||||
) {
|
||||
const effect = activeReactiveEffectStack[activeReactiveEffectStack.length - 1]
|
||||
if (effect) {
|
||||
if (type === OperationTypes.ITERATE) {
|
||||
key = ITERATE_KEY
|
||||
}
|
||||
let depsMap = targetMap.get(target)
|
||||
if (depsMap === void 0) {
|
||||
targetMap.set(target, (depsMap = new Map()))
|
||||
}
|
||||
let dep = depsMap.get(key as string | symbol)
|
||||
if (!dep) {
|
||||
depsMap.set(key as string | symbol, (dep = new Set()))
|
||||
}
|
||||
if (!dep.has(effect)) {
|
||||
dep.add(effect)
|
||||
effect.deps.push(dep)
|
||||
if (__DEV__ && effect.onTrack) {
|
||||
effect.onTrack({
|
||||
effect,
|
||||
target,
|
||||
type,
|
||||
key
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function trigger(
|
||||
target: any,
|
||||
type: OperationTypes,
|
||||
key?: string | symbol,
|
||||
extraInfo?: any
|
||||
) {
|
||||
const depsMap = targetMap.get(target)
|
||||
if (depsMap === void 0) {
|
||||
// never been tracked
|
||||
return
|
||||
}
|
||||
const effects: Set<ReactiveEffect> = new Set()
|
||||
const computedRunners: Set<ReactiveEffect> = new Set()
|
||||
if (type === OperationTypes.CLEAR) {
|
||||
// collection being cleared, trigger all effects for target
|
||||
depsMap.forEach(dep => {
|
||||
addRunners(effects, computedRunners, dep)
|
||||
})
|
||||
} else {
|
||||
// schedule runs for SET | ADD | DELETE
|
||||
if (key !== void 0) {
|
||||
addRunners(effects, computedRunners, depsMap.get(key as string | symbol))
|
||||
}
|
||||
// also run for iteration key on ADD | DELETE
|
||||
if (type === OperationTypes.ADD || type === OperationTypes.DELETE) {
|
||||
const iterationKey = Array.isArray(target) ? 'length' : ITERATE_KEY
|
||||
addRunners(effects, computedRunners, depsMap.get(iterationKey))
|
||||
}
|
||||
}
|
||||
const run = (effect: ReactiveEffect) => {
|
||||
scheduleRun(effect, target, type, key, extraInfo)
|
||||
}
|
||||
// Important: computed effects must be run first so that computed getters
|
||||
// can be invalidated before any normal effects that depend on them are run.
|
||||
computedRunners.forEach(run)
|
||||
effects.forEach(run)
|
||||
}
|
||||
|
||||
function addRunners(
|
||||
effects: Set<ReactiveEffect>,
|
||||
computedRunners: Set<ReactiveEffect>,
|
||||
effectsToAdd: Set<ReactiveEffect> | undefined
|
||||
) {
|
||||
if (effectsToAdd !== void 0) {
|
||||
effectsToAdd.forEach(effect => {
|
||||
if (effect.computed) {
|
||||
computedRunners.add(effect)
|
||||
} else {
|
||||
effects.add(effect)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
function scheduleRun(
|
||||
effect: ReactiveEffect,
|
||||
target: any,
|
||||
type: OperationTypes,
|
||||
key: string | symbol | undefined,
|
||||
extraInfo: any
|
||||
) {
|
||||
if (__DEV__ && effect.onTrigger) {
|
||||
effect.onTrigger(
|
||||
Object.assign(
|
||||
{
|
||||
effect,
|
||||
target,
|
||||
key,
|
||||
type
|
||||
},
|
||||
extraInfo
|
||||
)
|
||||
)
|
||||
}
|
||||
if (effect.scheduler !== void 0) {
|
||||
effect.scheduler(effect)
|
||||
} else {
|
||||
effect()
|
||||
}
|
||||
}
|
||||
164
packages/reactivity/src/index.ts
Normal file
164
packages/reactivity/src/index.ts
Normal file
@@ -0,0 +1,164 @@
|
||||
import { isObject, EMPTY_OBJ } from '@vue/shared'
|
||||
import { mutableHandlers, immutableHandlers } from './baseHandlers'
|
||||
|
||||
import {
|
||||
mutableCollectionHandlers,
|
||||
immutableCollectionHandlers
|
||||
} from './collectionHandlers'
|
||||
|
||||
import {
|
||||
targetMap,
|
||||
observedToRaw,
|
||||
rawToObserved,
|
||||
immutableToRaw,
|
||||
rawToImmutable,
|
||||
immutableValues,
|
||||
nonReactiveValues
|
||||
} from './state'
|
||||
|
||||
import {
|
||||
createReactiveEffect,
|
||||
cleanup,
|
||||
ReactiveEffect,
|
||||
ReactiveEffectOptions,
|
||||
DebuggerEvent
|
||||
} from './effect'
|
||||
|
||||
import { UnwrapValue } from './value'
|
||||
|
||||
export { ReactiveEffect, ReactiveEffectOptions, DebuggerEvent }
|
||||
export { OperationTypes } from './operations'
|
||||
export { computed, ComputedValue } from './computed'
|
||||
export { lock, unlock } from './lock'
|
||||
export { value, isValue, Value, UnwrapValue } from './value'
|
||||
|
||||
const collectionTypes: Set<any> = new Set([Set, Map, WeakMap, WeakSet])
|
||||
const observableValueRE = /^\[object (?:Object|Array|Map|Set|WeakMap|WeakSet)\]$/
|
||||
|
||||
const canObserve = (value: any): boolean => {
|
||||
return (
|
||||
!value._isVue &&
|
||||
!value._isVNode &&
|
||||
observableValueRE.test(Object.prototype.toString.call(value)) &&
|
||||
!nonReactiveValues.has(value)
|
||||
)
|
||||
}
|
||||
|
||||
type ObservableFactory = <T>(target?: T) => UnwrapValue<T>
|
||||
|
||||
export const state = ((target: any = {}): any => {
|
||||
// if trying to observe an immutable proxy, return the immutable version.
|
||||
if (immutableToRaw.has(target)) {
|
||||
return target
|
||||
}
|
||||
// target is explicitly marked as immutable by user
|
||||
if (immutableValues.has(target)) {
|
||||
return immutableState(target)
|
||||
}
|
||||
return createObservable(
|
||||
target,
|
||||
rawToObserved,
|
||||
observedToRaw,
|
||||
mutableHandlers,
|
||||
mutableCollectionHandlers
|
||||
)
|
||||
}) as ObservableFactory
|
||||
|
||||
export const immutableState = ((target: any = {}): any => {
|
||||
// value is a mutable observable, retrive its original and return
|
||||
// a readonly version.
|
||||
if (observedToRaw.has(target)) {
|
||||
target = observedToRaw.get(target)
|
||||
}
|
||||
return createObservable(
|
||||
target,
|
||||
rawToImmutable,
|
||||
immutableToRaw,
|
||||
immutableHandlers,
|
||||
immutableCollectionHandlers
|
||||
)
|
||||
}) as ObservableFactory
|
||||
|
||||
function createObservable(
|
||||
target: any,
|
||||
toProxy: WeakMap<any, any>,
|
||||
toRaw: WeakMap<any, any>,
|
||||
baseHandlers: ProxyHandler<any>,
|
||||
collectionHandlers: ProxyHandler<any>
|
||||
) {
|
||||
if (!isObject(target)) {
|
||||
if (__DEV__) {
|
||||
console.warn(`value is not observable: ${String(target)}`)
|
||||
}
|
||||
return target
|
||||
}
|
||||
// target already has corresponding Proxy
|
||||
let observed = toProxy.get(target)
|
||||
if (observed !== void 0) {
|
||||
return observed
|
||||
}
|
||||
// target is already a Proxy
|
||||
if (toRaw.has(target)) {
|
||||
return target
|
||||
}
|
||||
// only a whitelist of value types can be observed.
|
||||
if (!canObserve(target)) {
|
||||
return target
|
||||
}
|
||||
const handlers = collectionTypes.has(target.constructor)
|
||||
? collectionHandlers
|
||||
: baseHandlers
|
||||
observed = new Proxy(target, handlers)
|
||||
toProxy.set(target, observed)
|
||||
toRaw.set(observed, target)
|
||||
if (!targetMap.has(target)) {
|
||||
targetMap.set(target, new Map())
|
||||
}
|
||||
return observed
|
||||
}
|
||||
|
||||
export function effect(
|
||||
fn: Function,
|
||||
options: ReactiveEffectOptions = EMPTY_OBJ
|
||||
): ReactiveEffect {
|
||||
if ((fn as ReactiveEffect).isEffect) {
|
||||
fn = (fn as ReactiveEffect).raw
|
||||
}
|
||||
const effect = createReactiveEffect(fn, options)
|
||||
if (!options.lazy) {
|
||||
effect()
|
||||
}
|
||||
return effect
|
||||
}
|
||||
|
||||
export function stop(effect: ReactiveEffect) {
|
||||
if (effect.active) {
|
||||
cleanup(effect)
|
||||
if (effect.onStop) {
|
||||
effect.onStop()
|
||||
}
|
||||
effect.active = false
|
||||
}
|
||||
}
|
||||
|
||||
export function isState(value: any): boolean {
|
||||
return observedToRaw.has(value) || immutableToRaw.has(value)
|
||||
}
|
||||
|
||||
export function isImmutableState(value: any): boolean {
|
||||
return immutableToRaw.has(value)
|
||||
}
|
||||
|
||||
export function toRaw<T>(observed: T): T {
|
||||
return observedToRaw.get(observed) || immutableToRaw.get(observed) || observed
|
||||
}
|
||||
|
||||
export function markImmutable<T>(value: T): T {
|
||||
immutableValues.add(value)
|
||||
return value
|
||||
}
|
||||
|
||||
export function markNonReactive<T>(value: T): T {
|
||||
nonReactiveValues.add(value)
|
||||
return value
|
||||
}
|
||||
10
packages/reactivity/src/lock.ts
Normal file
10
packages/reactivity/src/lock.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
// global immutability lock
|
||||
export let LOCKED = true
|
||||
|
||||
export function lock() {
|
||||
LOCKED = true
|
||||
}
|
||||
|
||||
export function unlock() {
|
||||
LOCKED = false
|
||||
}
|
||||
11
packages/reactivity/src/operations.ts
Normal file
11
packages/reactivity/src/operations.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
export const enum OperationTypes {
|
||||
// using literal strings instead of numbers so that it's easier to inspect
|
||||
// debugger events
|
||||
SET = 'set',
|
||||
ADD = 'add',
|
||||
DELETE = 'delete',
|
||||
CLEAR = 'clear',
|
||||
GET = 'get',
|
||||
HAS = 'has',
|
||||
ITERATE = 'iterate'
|
||||
}
|
||||
20
packages/reactivity/src/state.ts
Normal file
20
packages/reactivity/src/state.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
import { ReactiveEffect } from './effect'
|
||||
|
||||
// The main WeakMap that stores {target -> key -> dep} connections.
|
||||
// Conceptually, it's easier to think of a dependency as a Dep class
|
||||
// which maintains a Set of subscribers, but we simply store them as
|
||||
// raw Sets to reduce memory overhead.
|
||||
export type Dep = Set<ReactiveEffect>
|
||||
export type KeyToDepMap = Map<string | symbol, Dep>
|
||||
export const targetMap: WeakMap<any, KeyToDepMap> = new WeakMap()
|
||||
|
||||
// WeakMaps that store {raw <-> observed} pairs.
|
||||
export const rawToObserved: WeakMap<any, any> = new WeakMap()
|
||||
export const observedToRaw: WeakMap<any, any> = new WeakMap()
|
||||
export const rawToImmutable: WeakMap<any, any> = new WeakMap()
|
||||
export const immutableToRaw: WeakMap<any, any> = new WeakMap()
|
||||
|
||||
// WeakSets for values that are marked immutable or non-reactive during
|
||||
// observable creation.
|
||||
export const immutableValues: WeakSet<any> = new WeakSet()
|
||||
export const nonReactiveValues: WeakSet<any> = new WeakSet()
|
||||
118
packages/reactivity/src/value.ts
Normal file
118
packages/reactivity/src/value.ts
Normal file
@@ -0,0 +1,118 @@
|
||||
import { track, trigger } from './effect'
|
||||
import { OperationTypes } from './operations'
|
||||
import { isObject } from '@vue/shared'
|
||||
import { state } from './index'
|
||||
|
||||
export const knownValues = new WeakSet()
|
||||
|
||||
export interface Value<T> {
|
||||
value: T
|
||||
}
|
||||
|
||||
const convert = (val: any): any => (isObject(val) ? state(val) : val)
|
||||
|
||||
export function value<T>(raw: T): Value<T> {
|
||||
raw = convert(raw)
|
||||
const v = {
|
||||
get value() {
|
||||
track(v, OperationTypes.GET, '')
|
||||
return raw
|
||||
},
|
||||
set value(newVal) {
|
||||
raw = convert(newVal)
|
||||
trigger(v, OperationTypes.SET, '')
|
||||
}
|
||||
}
|
||||
knownValues.add(v)
|
||||
return v
|
||||
}
|
||||
|
||||
export function isValue(v: any): v is Value<any> {
|
||||
return knownValues.has(v)
|
||||
}
|
||||
|
||||
type BailTypes =
|
||||
| Function
|
||||
| Map<any, any>
|
||||
| Set<any>
|
||||
| WeakMap<any, any>
|
||||
| WeakSet<any>
|
||||
|
||||
// Recursively unwraps nested value bindings.
|
||||
// Unfortunately TS cannot do recursive types, but this should be enough for
|
||||
// practical use cases...
|
||||
export type UnwrapValue<T> = T extends Value<infer V>
|
||||
? UnwrapValue2<V>
|
||||
: T extends Array<infer V>
|
||||
? Array<UnwrapValue2<V>>
|
||||
: T extends BailTypes
|
||||
? T // bail out on types that shouldn't be unwrapped
|
||||
: T extends object ? { [K in keyof T]: UnwrapValue2<T[K]> } : T
|
||||
|
||||
type UnwrapValue2<T> = T extends Value<infer V>
|
||||
? UnwrapValue3<V>
|
||||
: T extends Array<infer V>
|
||||
? Array<UnwrapValue3<V>>
|
||||
: T extends BailTypes
|
||||
? T
|
||||
: T extends object ? { [K in keyof T]: UnwrapValue3<T[K]> } : T
|
||||
|
||||
type UnwrapValue3<T> = T extends Value<infer V>
|
||||
? UnwrapValue4<V>
|
||||
: T extends Array<infer V>
|
||||
? Array<UnwrapValue4<V>>
|
||||
: T extends BailTypes
|
||||
? T
|
||||
: T extends object ? { [K in keyof T]: UnwrapValue4<T[K]> } : T
|
||||
|
||||
type UnwrapValue4<T> = T extends Value<infer V>
|
||||
? UnwrapValue5<V>
|
||||
: T extends Array<infer V>
|
||||
? Array<UnwrapValue5<V>>
|
||||
: T extends BailTypes
|
||||
? T
|
||||
: T extends object ? { [K in keyof T]: UnwrapValue5<T[K]> } : T
|
||||
|
||||
type UnwrapValue5<T> = T extends Value<infer V>
|
||||
? UnwrapValue6<V>
|
||||
: T extends Array<infer V>
|
||||
? Array<UnwrapValue6<V>>
|
||||
: T extends BailTypes
|
||||
? T
|
||||
: T extends object ? { [K in keyof T]: UnwrapValue6<T[K]> } : T
|
||||
|
||||
type UnwrapValue6<T> = T extends Value<infer V>
|
||||
? UnwrapValue7<V>
|
||||
: T extends Array<infer V>
|
||||
? Array<UnwrapValue7<V>>
|
||||
: T extends BailTypes
|
||||
? T
|
||||
: T extends object ? { [K in keyof T]: UnwrapValue7<T[K]> } : T
|
||||
|
||||
type UnwrapValue7<T> = T extends Value<infer V>
|
||||
? UnwrapValue8<V>
|
||||
: T extends Array<infer V>
|
||||
? Array<UnwrapValue8<V>>
|
||||
: T extends BailTypes
|
||||
? T
|
||||
: T extends object ? { [K in keyof T]: UnwrapValue8<T[K]> } : T
|
||||
|
||||
type UnwrapValue8<T> = T extends Value<infer V>
|
||||
? UnwrapValue9<V>
|
||||
: T extends Array<infer V>
|
||||
? Array<UnwrapValue9<V>>
|
||||
: T extends BailTypes
|
||||
? T
|
||||
: T extends object ? { [K in keyof T]: UnwrapValue9<T[K]> } : T
|
||||
|
||||
type UnwrapValue9<T> = T extends Value<infer V>
|
||||
? UnwrapValue10<V>
|
||||
: T extends Array<infer V>
|
||||
? Array<UnwrapValue10<V>>
|
||||
: T extends BailTypes
|
||||
? T
|
||||
: T extends object ? { [K in keyof T]: UnwrapValue10<T[K]> } : T
|
||||
|
||||
type UnwrapValue10<T> = T extends Value<infer V>
|
||||
? V // stop recursion
|
||||
: T
|
||||
Reference in New Issue
Block a user