Skip to content

fix(reactivity): process subtypes of collections properly #1799

New issue

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

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

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions packages/reactivity/__tests__/reactive.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,24 @@ describe('reactivity/reactive', () => {
expect(isReactive(observed.array[0])).toBe(true)
})

test('process subtypes of collections properly', () => {
class CustomMap extends Map {
count = 0

set(key: any, value: any): this {
super.set(key, value)
this.count++
return this
}
}

const testMap = new CustomMap()
const observed = reactive(testMap)
expect(observed.count).toBe(0)
observed.set('test', 'value')
expect(observed.count).toBe(1)
})

test('observed value should proxy mutations to original (Object)', () => {
const original: any = { foo: 1 }
const observed = reactive(original)
Expand Down
15 changes: 12 additions & 3 deletions packages/reactivity/src/reactive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@ export const enum ReactiveFlags {
IS_READONLY = '__v_isReadonly',
RAW = '__v_raw',
REACTIVE = '__v_reactive',
READONLY = '__v_readonly'
READONLY = '__v_readonly',

IS_COLLECTION = '__v_isCollection'
}

interface Target {
Expand All @@ -28,9 +30,15 @@ interface Target {
[ReactiveFlags.RAW]?: any
[ReactiveFlags.REACTIVE]?: any
[ReactiveFlags.READONLY]?: any

[ReactiveFlags.IS_COLLECTION]?: boolean
}

const collectionTypes = new Set<Function>([Set, Map, WeakMap, WeakSet])
;([Set, Map, WeakMap, WeakSet] as Array<Function>).forEach(
collectionType =>
(collectionType.prototype[ReactiveFlags.IS_COLLECTION] = true)
)

const isObservableType = /*#__PURE__*/ makeMap(
'Object,Array,Map,Set,WeakMap,WeakSet'
)
Expand Down Expand Up @@ -151,9 +159,10 @@ function createReactiveObject(
if (!canObserve(target)) {
return target
}

const observed = new Proxy(
target,
collectionTypes.has(target.constructor) ? collectionHandlers : baseHandlers
target[ReactiveFlags.IS_COLLECTION] ? collectionHandlers : baseHandlers
)
def(target, reactiveFlag, observed)
return observed
Expand Down