Skip to content
Merged
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
37 changes: 36 additions & 1 deletion packages/reactivity/__tests__/collections/Set.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
import { effect, isReactive, reactive, toRaw } from '../../src'
import {
effect,
isReactive,
reactive,
readonly,
shallowReactive,
toRaw,
} from '../../src'

describe('reactivity/collections', () => {
function coverCollectionFn(collection: Set<any>, fnName: string) {
Expand Down Expand Up @@ -403,6 +410,34 @@ describe('reactivity/collections', () => {
expect(dummy).toBe(false)
})

it('should not add readonly versions of existing raw values', () => {
const rawValue = {}
const wrappedValue = readonly(rawValue)
const set = reactive(new Set([rawValue]))

expect(set.has(wrappedValue)).toBe(true)

set.add(wrappedValue)

expect(set.size).toBe(1)
expect(toRaw(set).has(rawValue)).toBe(true)
expect(toRaw(set).has(wrappedValue)).toBe(false)
})

it('should not add proxy versions of existing raw values to shallow sets', () => {
const rawValue = {}
const wrappedValue = reactive(rawValue)
const set = shallowReactive(new Set([rawValue]))

expect(set.has(wrappedValue)).toBe(true)

set.add(wrappedValue)

expect(set.size).toBe(1)
expect(toRaw(set).has(rawValue)).toBe(true)
expect(toRaw(set).has(wrappedValue)).toBe(false)
})

it('should warn when set contains both raw and reactive versions of the same object', () => {
const raw = new Set()
const rawKey = {}
Expand Down
8 changes: 6 additions & 2 deletions packages/reactivity/src/collectionHandlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -169,13 +169,17 @@ function createInstrumentations(
add(this: SetTypes, value: unknown) {
const target = toRaw(this)
const proto = getProto(target)
const rawValue = toRaw(value)
const valueToAdd =
!shallow && !isShallow(value) && !isReadonly(value)
? toRaw(value)
? rawValue
: value
const hadKey =
proto.has.call(target, valueToAdd) ||
(value !== valueToAdd && proto.has.call(target, value))
(hasChanged(value, valueToAdd) &&
proto.has.call(target, value)) ||
(hasChanged(rawValue, valueToAdd) &&
proto.has.call(target, rawValue))
if (!hadKey) {
target.add(valueToAdd)
trigger(target, TriggerOpTypes.ADD, valueToAdd, valueToAdd)
Expand Down
Loading