Shrinking an array with `length =` and growing it back loses the patches for the truncated indices
Mantenedores costumam responder em até 4 dias
Avaliação
- Dificuldade
- 2/5
- Tempo estimado
- 1-3 horas
- Facilidade para iniciantes
- 75/100
- Tipo de issue
- Bug
- Clareza
- Claramente especificada
- Status de atividade
- Ativa
- Stack de tecnologia
- javascript
- Domínio
- backend
Direção de pesquisa
Comece em src/plugins/patches.ts, especialmente em generateArrayPatches_, e acompanhe como reduzir um array draft altera copy_ e assigned_. Adicione o teste de regressão fornecido para reduzir e aumentar length novamente e execute os testes relacionados a patches. O trabalho estará concluído quando os patches diretos reproduzirem o resultado da receita e os patches inversos restaurarem a base.
Escrita pelo modelo de indexação a partir do texto da issue.
Descrição
🐛 Bug Report
With enablePatches(), if a recipe shrinks a draft array by assigning .length and then grows it back to at least its original length, no replace patch (and no inverse patch) is produced for the truncated indices. Replaying the patches on the base gives a different state than the recipe, and the inverse patches do not restore the base. The same recipe written with splice(0) produces correct patches.
Link to repro
Not applicable: no CodeSandbox account; the script below and the unit test at the end reproduce it.
To Reproduce
npm i [email protected], save as t.mjs, run node t.mjs:
import { produceWithPatches, applyPatches, enablePatches } from "immer";
enablePatches();
const base = [1];
const [result, patches, inverse] = produceWithPatches(base, d => {
d.length = 0; // truncate index 0
d[1] = 2; // grow again
});
console.log(result);
console.log(patches);
console.log(inverse);
console.log(applyPatches(base, patches));
console.log(applyPatches(result, inverse));
const [r2, p2, i2] = produceWithPatches([1, 2], d => { d.length = 0; d.length = 2; });
console.log(r2, p2, i2);
Observed behavior
[ <1 empty item>, 2 ]
[ { op: 'add', path: [ 1 ], value: 2 } ]
[ { op: 'remove', path: [ 1 ] } ]
[ 1, 2 ]
[ <1 empty item> ]
[ <2 empty items> ] [] []
applyPatches(base, patches) keeps the stale 1 at index 0, and applyPatches(result, inverse) does not bring it back. The second recipe changes both elements but produces no patches at all.
Expected behavior
The same patches as for d.splice(0); d[1] = 2, which immer already gets right:
[
{ op: 'replace', path: [ 0 ], value: undefined },
{ op: 'add', path: [ 1 ], value: 2 }
] [
{ op: 'replace', path: [ 0 ], value: 1 },
{ op: 'remove', path: [ 1 ] }
]
so that applyPatches(base, patches) gives [ undefined, 2 ] and applyPatches(result, inverse) gives [ 1 ].
generateArrayPatches_ in src/plugins/patches.ts only emits a replace for an index below base.length when assigned_.get(i) is set (or allIndicesReassigned_). Assigning a smaller length truncates copy_ without marking the dropped indices as assigned, so they are skipped once the array is long again.
Unit test:
test("length shrink then grow produces replace patches", () => {
const base = [1]
const [result, patches, inverse] = produceWithPatches(base, d => {
d.length = 0
d[1] = 2
})
expect(applyPatches(base, patches)).toEqual(result)
expect(applyPatches(result, inverse)).toEqual(base)
})
Environment
We only accept bug reports against the latest Immer version.
- Immer version: 11.2.9 (also main 75a290e, built from source), Node.js v26.13.0
- I filed this report against the latest version of Immer
- Occurs with
setUseProxies(true) - Occurs with
setUseProxies(false)(ES5 only)
Credit: https://ucsbplse.github.io/
- Linguagem predominante
- JavaScript
- Estrelas
- 29k
- Forks
- 905
- Merge médio
- 3d 16h
- PRs com merge (30d)
- 22
Preparar o ambiente
Este projeto não oferece contêiner de desenvolvimento, Dockerfile nem guia de contribuição, então a configuração fica por sua conta: comece pelo README e veja nosso guia da primeira contribuição para os passos gerais.
Primeiros passos
- Leia a issue inteira e depois o guia de contribuição do projeto.
- Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
- Faça um fork do repositório e trabalhe em uma branch.
- Abra um pull request que referencie o número da issue.
Mais de immerjs/immer
-
Dificuldade 3/5 1-2 dias Facilidade para iniciantes 35/100
Mantenedores costumam responder em até 4 dias
-
Docs: Chinese (zh-CN) website translation is outdated vs English docsTalvez livre de novo @lijiayou0728 assumiu há 92 dias e não há nenhum pull request aberto. Aberta
Dificuldade 4/5 3-5 dias Facilidade para iniciantes 55/100
immerjs/immer#1242 · 5 comentários ·
Mantenedores costumam responder em até 4 dias
-
question
Dificuldade 5/5 Mais de uma semana Facilidade para iniciantes 35/100
Mantenedores costumam responder em até 4 dias
-
Dificuldade 5/5 Mais de uma semana Facilidade para iniciantes 35/100
immerjs/immer#1217 · 1 comentário ·
Mantenedores costumam responder em até 4 dias
-
[Feature Request] Support for "Splice" patches in arrays for CRDT/Y.js integration (and others)Abertaproposal
Dificuldade 5/5 Mais de uma semana Facilidade para iniciantes 25/100
immerjs/immer#1202 · 2 comentários · 1 reação ·
Mantenedores costumam responder em até 4 dias
Todas as issues de immerjs/immer
Issues semelhantes
-
xsd:integer cast from a string rejects negative numbers, a leading + and surrounding whitespaceAbertabug 🐛
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 78/100
comunica/comunica#1960 · 1 comentário ·
Mantenedores costumam responder em até 1 dia
-
Waiting for: Product Owner
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 76/100
getsentry/sentry-javascript#26203 · 1 comentário ·
Mantenedores costumam responder em até 1 dia
-
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 70/100
Mantenedores costumam responder em até 1 dia
-
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 75/100
Mantenedores costumam responder em até 1 dia
-
bug
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 76/100
bytedance/flowgram.ai#1235 ·
Mantenedores costumam responder em até 1 dia