Skip to content

Commit

Permalink
Editor save is disabled when content is not changed
Browse files Browse the repository at this point in the history
Fixed editor content updating
  • Loading branch information
james-pre committed Oct 14, 2024
1 parent 43616a6 commit 988d558
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 3 deletions.
38 changes: 36 additions & 2 deletions src/editor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,23 +6,48 @@ export const content = $<HTMLTextAreaElement>('#editor .content');

export let file: string | void;

let savedContent: string | undefined;

function updateButtons() {
if (!file) {
$('#editor button.save').removeAttr('disabled');
return;
}

if (content.val() == savedContent) {
$('#editor button.save').attr('disabled', 1);
} else {
$('#editor button.save').removeAttr('disabled');
}
}

export async function open(path?: string | void) {
path ??= await prompt('Open file');
if (!path) {
return;
}
file = path;
content.text(fs.readFileSync(file, 'utf-8'));
const data = fs.readFileSync(file, 'utf-8');
content.val(data);
savedContent = data;
content[0].focus();
}

export async function save() {
file ||= await prompt('Save to path');
if (!file) return;
fs.writeFileSync(file, content.val()!);
savedContent = content.val();
updateButtons();
}

content.on('keydown', e => {
export function reload() {
if (!file) return;
content.val(fs.readFileSync(file, 'utf-8'));
updateButtons();
}

function handleKeydown(e: JQuery.KeyDownEvent<HTMLTextAreaElement, unknown, HTMLTextAreaElement, HTMLTextAreaElement>) {
if (e.key == 'Tab') {
e.preventDefault();
const start = e.target.selectionStart;
Expand All @@ -38,11 +63,20 @@ content.on('keydown', e => {
// Key combos
switch (e.key) {
case 'o':
e.preventDefault();
void open();
break;
case 's':
e.preventDefault();
void save();
break;
}
}

content.on('keydown', e => {
handleKeydown(e);
setTimeout(updateButtons, 0);
});

$('#editor button.save').on('click', () => void save());
$('#editor button.reload').on('click', () => void reload());
2 changes: 1 addition & 1 deletion src/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@
<div class="top">
<p><strong>Editor</strong></p>
<button class="save">Save</button>
<button class="reset">Reset</button>
<button class="reload">Reload</button>
</div>

<textarea class="content"></textarea>
Expand Down

0 comments on commit 988d558

Please sign in to comment.