Skip to content

Commit 4fad44b

Browse files
committed
feat(sync): Add checks when containerId is provided
I run into an issue providing a container ID of an detached container. With the implementation before I got an `Uncaught TypeError` since there is no type check whether `getContainerId()` returns a container so that `map.get()` cannot be called. I took me a while to find the issue. Thus I suggest to add some type checks when `containerId` is provided with appropriate error message. This should result in a better developer experience.
1 parent b2bcee5 commit 4fad44b

1 file changed

Lines changed: 22 additions & 3 deletions

File tree

src/lib.ts

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -75,9 +75,7 @@ export function updateLoroToPmState(
7575
containerId?: ContainerID,
7676
) {
7777
const node = editorState.doc;
78-
const map = containerId
79-
? (doc.getContainerById(containerId) as LoroMap<LoroNodeContainerType>)
80-
: doc.getMap(ROOT_DOC_KEY);
78+
const map = getContainer(doc, containerId);
8179

8280
let isInit = false;
8381
if (map.get("nodeName") == null) {
@@ -94,6 +92,27 @@ export function updateLoroToPmState(
9492
}
9593
}
9694

95+
function getContainer(
96+
doc: LoroDocType,
97+
containerId?: ContainerID,
98+
): LoroMap<LoroNodeContainerType> {
99+
if (containerId == null) return doc.getMap(ROOT_DOC_KEY);
100+
101+
const container = doc.getContainerById(containerId);
102+
103+
if (container == null) {
104+
throw new Error(
105+
`Container with ID ${containerId} not found. Maybe the container is not attached to the document yet.`,
106+
);
107+
}
108+
109+
if (!(container instanceof LoroMap)) {
110+
throw new Error(`Container with ID ${containerId} is not a LoroMap`);
111+
}
112+
113+
return container as LoroMap<LoroNodeContainerType>;
114+
}
115+
97116
export function createNodeFromLoroObj(
98117
schema: Schema,
99118
obj: LoroNode,

0 commit comments

Comments
 (0)