Skip to content

Commit 891b259

Browse files
committed
feat(json-crdt): 🎸 add File.apply() method
1 parent 404f9cb commit 891b259

File tree

2 files changed

+14
-4
lines changed

2 files changed

+14
-4
lines changed

src/json-crdt/file/File.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import {CborEncoder} from '../../json-pack/cbor/CborEncoder';
1212
import {JsonEncoder} from '../../json-pack/json/JsonEncoder';
1313
import {printTree} from '../../util/print/printTree';
1414
import {decodeModel, decodeNdjsonComponents, decodePatch, decodeSeqCborComponents} from './util';
15+
import {Patch} from '../../json-crdt-patch';
1516
import type * as types from './types';
1617
import type {Printable} from '../../util/print/types';
1718

@@ -68,6 +69,13 @@ export class File implements Printable {
6869

6970
constructor(public readonly model: Model, public readonly log: PatchLog) {}
7071

72+
public apply(patch: Patch): void {
73+
const id = patch.getId();
74+
if (!id) return;
75+
this.model.applyPatch(patch);
76+
this.log.push(patch);
77+
}
78+
7179
public serialize(params: types.FileSerializeParams = {}): types.FileWriteSequence {
7280
if (params.noView && params.model === 'sidecar') throw new Error('SIDECAR_MODEL_WITHOUT_VIEW');
7381
const metadata: types.FileMetadata = [{}, FileModelEncoding.Auto];

src/json-crdt/file/__tests__/PatchLog.spec.ts

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,18 +9,20 @@ const setup = (view: unknown) => {
99
};
1010

1111
test('can replay to specific patch', () => {
12-
const {model, file} = setup({foo: 'bar'});
12+
const {file} = setup({foo: 'bar'});
13+
const model = file.model.clone();
1314
model.api.obj([]).set({x: 1});
1415
const patch1 = model.api.flush();
1516
model.api.obj([]).set({y: 2});
1617
const patch2 = model.api.flush();
17-
file.log.push(patch1);
18-
file.log.push(patch2);
18+
file.apply(patch1);
19+
file.apply(patch2);
1920
const model2 = file.log.replayToEnd();
2021
const model3 = file.log.replayTo(patch1.getId()!);
2122
const model4 = file.log.replayTo(patch2.getId()!);
2223
expect(model.view()).toEqual({foo: 'bar', x: 1, y: 2});
23-
expect(file.log.start.view()).toEqual({foo: 'bar'});
24+
expect(file.model.view()).toEqual({foo: 'bar', x: 1, y: 2});
25+
expect(file.log.start.view()).toEqual(undefined);
2426
expect(model2.view()).toEqual({foo: 'bar', x: 1, y: 2});
2527
expect(model3.view()).toEqual({foo: 'bar', x: 1});
2628
expect(model4.view()).toEqual({foo: 'bar', x: 1, y: 2});

0 commit comments

Comments
 (0)