refactor: streamline snippet saving logic and button creation in UIManager

This commit is contained in:
2025-01-25 19:18:31 +02:00
parent c474f8cdc2
commit a04fd74b11
2 changed files with 40 additions and 37 deletions

View File

@@ -77,10 +77,10 @@ export class SnippetManager {
saveDraft() {
if (!this.currentSnippetId) return;
try {
const content = JSON.parse(this.editorManager.getValue());
const snippetIndex = this.snippets.findIndex(s => s.id === this.currentSnippetId);
const content = this.parseEditorContent();
if (!content) return;
const snippetIndex = this.snippets.findIndex(s => s.id === this.currentSnippetId);
if (snippetIndex !== -1) {
const currentSnippet = this.snippets[snippetIndex];
if (JSON.stringify(content) !== JSON.stringify(currentSnippet.content)) {
@@ -90,18 +90,15 @@ export class SnippetManager {
this.visualizationManager.updateVisualization(content);
}
}
} catch (e) {
console.error('Invalid JSON in editor');
}
}
saveCurrentSnippet() {
if (!this.currentSnippetId) return;
try {
const content = JSON.parse(this.editorManager.getValue());
const snippetIndex = this.snippets.findIndex(s => s.id === this.currentSnippetId);
const content = this.parseEditorContent();
if (!content) return;
const snippetIndex = this.snippets.findIndex(s => s.id === this.currentSnippetId);
if (snippetIndex !== -1) {
this.snippets[snippetIndex].content = content;
delete this.snippets[snippetIndex].draft;
@@ -109,8 +106,14 @@ export class SnippetManager {
this.isDraftVersion = false;
this.saveSnippetsAndUpdateUI();
}
}
parseEditorContent() {
try {
return JSON.parse(this.editorManager.getValue());
} catch (e) {
alert('Invalid JSON in editor');
console.error('Invalid JSON in editor');
return null;
}
}

View File

@@ -51,29 +51,29 @@ export class UIManager {
const buttonsDiv = document.createElement('div');
buttonsDiv.className = 'snippet-buttons';
const editButton = document.createElement('button');
editButton.className = 'edit-snippet';
editButton.innerHTML = '✏️';
editButton.onclick = (e) => {
buttonsDiv.appendChild(this.createButton('✏️', 'edit-snippet', (e) => {
e.stopPropagation();
this.snippetManager.renameSnippet(snippet.id);
};
buttonsDiv.appendChild(editButton);
}));
const deleteButton = document.createElement('button');
deleteButton.className = 'delete-snippet';
deleteButton.innerHTML = '❌';
deleteButton.onclick = (e) => {
buttonsDiv.appendChild(this.createButton('❌', 'delete-snippet', (e) => {
e.stopPropagation();
this.snippetManager.deleteSnippet(snippet.id);
};
buttonsDiv.appendChild(deleteButton);
}));
div.appendChild(buttonsDiv);
container.appendChild(div);
});
}
createButton(innerHTML, className, onClick) {
const button = document.createElement('button');
button.className = className;
button.innerHTML = innerHTML;
button.onclick = onClick;
return button;
}
updateSaveButton(hasUnsavedChanges) {
const saveButton = document.getElementById('save-snippet');
saveButton.disabled = !hasUnsavedChanges;