Skip to content

Commit

Permalink
Fix for arrays not being properly updated in writable stores
Browse files Browse the repository at this point in the history
  • Loading branch information
acurrieclark committed Feb 7, 2024
1 parent 51c1eb7 commit 289a06e
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
17 changes: 15 additions & 2 deletions src/automerge-writable-store.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { type Updater, type Writable } from "svelte/store";
import type { AutomergeSvelteStoreInterface } from "./automerge-svelte-store.type";
import { diffArrays } from "diff";

export class AutomergeWritableStore<T>
implements Writable<T>, AutomergeSvelteStoreInterface<T>
Expand All @@ -8,7 +9,7 @@ export class AutomergeWritableStore<T>

constructor(rootStore: AutomergeSvelteStoreInterface<T>) {
this.#rootStore = rootStore;
if (typeof rootStore.get() !== "object") {
if (typeof rootStore.get() === "string") {
throw new Error(
"We cannot currently create writable store from string value",
);
Expand Down Expand Up @@ -37,7 +38,19 @@ export class AutomergeWritableStore<T>

set(value: T) {
this.#rootStore.change((doc) => {
if (
if (Array.isArray(doc) && Array.isArray(value)) {
const diffs = diffArrays(doc, value);
diffs.forEach((diff) => {
if (diff.added) {
doc.push(...diff.value);
} else if (diff.removed) {
const index = doc.indexOf(diff.value[0]);
if (index > -1) {
doc.splice(index, 1);
}
}
});
} else if (
doc !== null &&
typeof doc === "object" &&
typeof value === "object"
Expand Down
6 changes: 6 additions & 0 deletions tests/writable-store.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,12 @@ describe("writable store", () => {
"world",
"hello there world",
]);

writableStore.update((doc) => {
return doc.filter((item) => item !== "world");
});

expect(get(writableStore)).toEqual(["hello", "hello there world"]);
});

test("writable non object stores throw an error", () => {
Expand Down

0 comments on commit 289a06e

Please sign in to comment.