Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
9 changes: 5 additions & 4 deletions src/draft.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,17 +29,16 @@ import {
finalizeSetValue,
markFinalization,
finalizePatches,
isDraft,
} from './utils';
import { checkReadable } from './unsafe';
import { generatePatches } from './patch';

const draftsCache = new WeakSet<object>();

const proxyHandler: ProxyHandler<ProxyDraft> = {
get(target: ProxyDraft, key: string | number | symbol, receiver: any) {
const copy = target.copy?.[key];
// Improve draft reading performance by caching the draft copy.
if (copy && draftsCache.has(copy)) {
if (copy && target.finalities.draftsCache.has(copy)) {
return copy;
}
if (key === PROXY_DRAFT) return target;
Expand Down Expand Up @@ -118,6 +117,9 @@ const proxyHandler: ProxyHandler<ProxyDraft> = {
}
return target.copy![key];
}
if (isDraft(value)) {
target.finalities.draftsCache.add(value);
}
return value;
},
set(target: ProxyDraft, key: string | number | symbol, value: any) {
Expand Down Expand Up @@ -252,7 +254,6 @@ export function createDraft<T extends object>(createDraftOptions: {
proxyHandler
);
finalities.revoke.push(revoke);
draftsCache.add(proxy);
proxyDraft.proxy = proxy;
if (parentDraft) {
const target = parentDraft;
Expand Down
1 change: 1 addition & 0 deletions src/draftify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ export function draftify<
draft: [],
revoke: [],
handledSet: new WeakSet<any>(),
draftsCache: new WeakSet<object>(),
};
let patches: Patches | undefined;
let inversePatches: Patches | undefined;
Expand Down
1 change: 1 addition & 0 deletions src/interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ export interface Finalities {
draft: ((patches?: Patches, inversePatches?: Patches) => void)[];
revoke: (() => void)[];
handledSet: WeakSet<any>;
draftsCache: WeakSet<object>;
}

export interface ProxyDraft<T = any> {
Expand Down