mirror of
https://github.com/zoldar/jenot.git
synced 2026-01-03 14:32:54 +00:00
Optimize notes rendering reducing DOM updates
This commit is contained in:
parent
8774683919
commit
8e8c37b1c5
1 changed files with 81 additions and 34 deletions
|
|
@ -113,17 +113,65 @@ editNote.addEventListener("deleteNote", async (e) => {
|
|||
Notes.saveStorage();
|
||||
});
|
||||
|
||||
// All notes are currently re-rendered on each storage
|
||||
// update. The routine will be optimized to replace only
|
||||
// nodes that actually changed - most likely based on unique
|
||||
// note IDs associated with block elements.
|
||||
// The notes rendering routine is optimized to replace only
|
||||
// nodes that actually changed.
|
||||
|
||||
let currentNotes = {};
|
||||
|
||||
function notesEqual(note1, note2) {
|
||||
return note1.id === note2.id && note1.updated === note2.updated;
|
||||
}
|
||||
|
||||
async function render() {
|
||||
const notes = await Notes.all();
|
||||
const notesContainer = document.querySelector("#notes");
|
||||
notesContainer.replaceChildren();
|
||||
|
||||
let previousId = null;
|
||||
let notePrecedence = {};
|
||||
const ids = [];
|
||||
|
||||
notes.forEach((n) => {
|
||||
notePrecedence[n.id] = previousId;
|
||||
ids.push(n.id);
|
||||
previousId = n.id;
|
||||
});
|
||||
|
||||
Object.keys(currentNotes)
|
||||
.filter((id) => !ids.includes(id))
|
||||
.forEach((id) => {
|
||||
delete currentNotes[id];
|
||||
document.getElementById(id).remove();
|
||||
});
|
||||
|
||||
notes.forEach((note) => {
|
||||
const existingNote = currentNotes[note.id];
|
||||
|
||||
if (!existingNote) {
|
||||
const noteElement = renderNote(note);
|
||||
const beforeId = notePrecedence[note.id];
|
||||
|
||||
if (!beforeId) {
|
||||
notesContainer.prepend(noteElement);
|
||||
} else {
|
||||
const before = document.getElementById(beforeId);
|
||||
if (before) {
|
||||
before.after(noteElement);
|
||||
} else {
|
||||
notesContainer.prepend(noteElement);
|
||||
}
|
||||
}
|
||||
} else if (!notesEqual(existingNote, note)) {
|
||||
const noteElement = renderNote(note);
|
||||
const existing = document.getElementById(note.id);
|
||||
existing.replaceWith(noteElement);
|
||||
}
|
||||
});
|
||||
|
||||
currentNotes = {};
|
||||
notes.forEach((n) => (currentNotes[n.id] = n));
|
||||
}
|
||||
|
||||
function renderNote(note) {
|
||||
const container = document.createElement("div");
|
||||
container.id = note.id;
|
||||
container.classList.add("note");
|
||||
|
|
@ -148,13 +196,12 @@ async function render() {
|
|||
container.appendChild(list);
|
||||
}
|
||||
|
||||
notesContainer.appendChild(container);
|
||||
|
||||
container.addEventListener("click", async (e) => {
|
||||
newNote.classList.add("hidden");
|
||||
editNote.classList.remove("hidden");
|
||||
const note = await Notes.get(container.id);
|
||||
editNote.load(note);
|
||||
});
|
||||
});
|
||||
|
||||
return container;
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue