nitropage
Version:
A free and open source, extensible visual page builder based on SolidStart.
61 lines (50 loc) • 1.45 kB
text/typescript
import { State } from "../../../../../types";
/**
* An element has different ids in different page revisions
* This tries to find the ids when switching from one revision to another one
*/
export const findNextElementIds = (
prevIds: (string | undefined)[],
prevState: State,
nextState: Partial<State>,
) => {
let resultLength = 0;
let result = {} as Record<string, string | null | undefined>;
const historyCandidates = [] as [string, string][];
const nextElements = nextState.elements!;
for (const prevId of prevIds) {
if (prevId == null) {
resultLength++;
continue;
}
if (nextElements[prevId] != null) {
result[prevId] = prevId;
resultLength++;
continue;
}
const historyId = prevState.elements[prevId].historyId;
if (!historyId) {
resultLength++;
continue;
}
historyCandidates.push([prevId, historyId]);
}
if (resultLength !== prevIds.length) {
for (const nextElement of Object.values(nextElements)) {
if (resultLength === prevIds.length) {
break;
}
for (const [prevId, historyId] of historyCandidates) {
if (result[prevId]) {
continue;
}
if (nextElement.historyId != historyId) {
continue;
}
result[prevId] = nextElement.id;
resultLength++;
}
}
}
return prevIds.map((prevId) => (prevId && result[prevId]) ?? undefined);
};