Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Support out of bound indices on proxied arrays #3559

Merged
merged 11 commits into from
Nov 1, 2022
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/grumpy-dots-wink.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"mobx": minor
---

Proxied observable arrays can now safely read/write out of bound indices. See https://github.com/mobxjs/mobx/discussions/3537
64 changes: 47 additions & 17 deletions packages/mobx/__tests__/v5/base/array.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ const mobx = require("../../../src/mobx.ts")
const { observable, when, _getAdministration, reaction, computed, makeObservable, autorun } = mobx
const iterall = require("iterall")

let consoleWarnMock
let consoleWarnSpy
afterEach(() => {
consoleWarnMock?.mockRestore()
consoleWarnSpy?.mockRestore()
})

test("test1", function () {
Expand Down Expand Up @@ -402,8 +402,8 @@ test("array exposes correct keys", () => {
expect(keys).toEqual(["0", "1"])
})

test("accessing out of bound values throws", () => {
const a = mobx.observable([])
test("legacy array: accessing out of bound values throws", () => {
const a = mobx.observable([], { proxy: false })

let warns = 0
const baseWarn = console.warn
Expand Down Expand Up @@ -666,25 +666,41 @@ test("very long arrays can be safely passed to nativeArray.concat #2379", () =>
const nativeArray = ["a", "b"]
const longNativeArray = [...Array(10000).keys()] // MAX_SPLICE_SIZE seems to be the threshold
const longObservableArray = observable(longNativeArray)
const longLegacyArray = observable(longNativeArray, { proxy: false })
expect(longObservableArray.length).toBe(10000)
expect(longLegacyArray.length).toBe(10000)

expect(longObservableArray).toEqual(longNativeArray)
expect(longObservableArray[9000]).toBe(longNativeArray[9000])
expect(longObservableArray[9999]).toBe(longNativeArray[9999])
consoleWarnMock = jest.spyOn(console, "warn").mockImplementation(() => {})
expect(longObservableArray[10000]).toBe(longNativeArray[10000])
expect(consoleWarnMock).toMatchSnapshot()
expect(longLegacyArray).toEqual(longNativeArray)

const expectedArray = nativeArray.concat(longNativeArray)
const actualArray = nativeArray.concat(longObservableArray)
expect(longObservableArray[9000]).toBe(longNativeArray[9000])
expect(longLegacyArray[9000]).toBe(longNativeArray[9000])

expect(actualArray).toEqual(expectedArray)
expect(longObservableArray[9999]).toBe(longNativeArray[9999])
expect(longLegacyArray[9999]).toBe(longNativeArray[9999])

const anotherArray = [0, 1, 2, 3, 4, 5]
const observableArray = observable(anotherArray)
const r1 = anotherArray.splice(2, 2, ...longNativeArray)
const r2 = observableArray.splice(2, 2, ...longNativeArray)
expect(longObservableArray[10000]).toBe(longNativeArray[10000])
consoleWarnSpy = jest.spyOn(console, "warn").mockImplementation(() => {}) // Out of bound warn
expect(longLegacyArray[10000]).toBe(longNativeArray[10000])
expect(consoleWarnSpy).toMatchSnapshot()

const expectedNativeArray = nativeArray.concat(longNativeArray)
const actualObservableArray = nativeArray.concat(longObservableArray)
const actualLegacyArray = nativeArray.concat(longLegacyArray.slice()) // .slice because legacy isn't concat spreadable

expect(actualObservableArray).toEqual(expectedNativeArray)
expect(actualLegacyArray).toEqual(expectedNativeArray)

const anotherNativeArray = [0, 1, 2, 3, 4, 5]
const anotherObservableArray = observable(anotherNativeArray)
const anotherLegacyArray = observable(anotherNativeArray)
const r1 = anotherNativeArray.splice(2, 2, ...longNativeArray)
const r2 = anotherObservableArray.splice(2, 2, ...longNativeArray)
const r3 = anotherLegacyArray.splice(2, 2, ...longNativeArray)
expect(r2).toEqual(r1)
expect(observableArray).toEqual(anotherArray)
expect(r3).toEqual(r1)
expect(anotherObservableArray).toEqual(anotherNativeArray)
expect(anotherLegacyArray).toEqual(anotherNativeArray)
})

describe("dehances", () => {
Expand Down Expand Up @@ -867,3 +883,17 @@ test("reduce without initial value #2432", () => {
expect(observableArraySum).toEqual(arraySum)
expect(arrayReducerArgs).toEqual(observableArrayReducerArgs)
})

test("proxied arrays can access out-bound indices", () => {
consoleWarnSpy = jest.spyOn(console, "warn").mockImplementation(() => {
throw new Error(`Unexpected console.warn call`)
})

const array = observable([])

array[1]
array[2]
array[1001] = "foo"
expect(array.length).toBe(1002)
expect(array[1001]).toBe("foo")
})
37 changes: 23 additions & 14 deletions packages/mobx/src/types/observablearray.ts
Original file line number Diff line number Diff line change
Expand Up @@ -345,19 +345,24 @@ export class ObservableArrayAdministration
}

get_(index: number): any | undefined {
if (index < this.values_.length) {
this.atom_.reportObserved()
return this.dehanceValue_(this.values_[index])
}
console.warn(
__DEV__
? `[mobx] Out of bounds read: ${index}`
: `[mobx.array] Attempt to read an array index (${index}) that is out of bounds (${this.values_.length}). Please check length first. Out of bound indices will not be tracked by MobX`
)
if (this.legacyMode_ && index >= this.values_.length) {
console.warn(
__DEV__
? `[mobx] Out of bounds read: ${index}`
urugator marked this conversation as resolved.
Show resolved Hide resolved
: `[mobx.array] Attempt to read an array index (${index}) that is out of bounds (${this.values_.length}). Please check length first. Out of bound indices will not be tracked by MobX`
)
return undefined
}
this.atom_.reportObserved()
return this.dehanceValue_(this.values_[index])
}

set_(index: number, newValue: any) {
const values = this.values_
if (this.legacyMode_ && index > values.length) {
// out of bounds
die(17, index, values.length)
}
if (index < values.length) {
// update at index in range
checkIfStateModificationsAreAllowed(this.atom_)
Expand All @@ -380,12 +385,16 @@ export class ObservableArrayAdministration
values[index] = newValue
this.notifyArrayChildUpdate_(index, newValue, oldValue)
}
} else if (index === values.length) {
// add a new item
this.spliceWithArray_(index, 0, [newValue])
} else {
// out of bounds
die(17, index, values.length)
// For out of bound index, we don't create an actual sparse array,
// but rather fill the holes with undefined (same as setArrayLength_).
// This could be considered a bug.
const newItems = new Array(index + 1 - values.length)
for (let i = 0; i < newItems.length - 1; i++) {
newItems[i] = undefined
} // No Array.fill everywhere...
newItems[newItems.length - 1] = newValue
this.spliceWithArray_(values.length, 0, newItems)
}
}
}
Expand Down