dequoter/frontend/src/services.js
Leon Mika f96b8a8266
All checks were successful
Build / build (push) Successful in 1m0s
Added a store
2026-01-26 09:31:14 +11:00

85 lines
2.3 KiB
JavaScript

import {
ProcessText,
LoadCurrentBuffer,
SaveCurrentBuffer,
} from "../wailsjs/go/main/App";
class TextProcessor {
constructor() {
this._lastAutoSave = undefined;
}
setCodeMirrorEditor(editor) {
this._editor = editor;
window.runtime.EventsOn("process-text-response", (data) => {
const changes = data.output.map(span => {
if (span.append) {
return {
from: span.pos + span.len,
to: span.pos + span.len,
insert: span.text,
};
} else {
return {
from: span.pos,
to: span.pos + span.len,
insert: span.text,
};
}
});
this._editor.dispatch({ changes: changes });
});
}
async runTextCommand(command) {
if (this._editor === undefined) {
return;
}
let ranges = this._editor.state.selection.ranges;
let shouldBeAll = ranges.reduce((a, r) => a && r.from === r.to, true);
let inputs = [];
if (shouldBeAll) {
inputs.push({
text: this._editor.state.doc.toString(),
pos: 0,
len: this._editor.state.doc.length,
});
} else {
inputs = ranges.map(r => ({
text: this._editor.state.doc.slice(r.from, r.to).toString(),
pos: r.from,
len: r.to - r.from,
}))
}
await ProcessText({
action: command,
input: inputs,
});
await this.saveBuffer();
}
async loadCurrentBuffer() {
let buffer = await LoadCurrentBuffer();
this._editor.dispatch({ changes: { from: 0, to: this._editor.state.doc.length, insert: buffer } });
this._lastAutoSave = buffer;
}
startAutoSaver() {
setInterval(() => {
this.saveBuffer();
}, 1000);
}
async saveBuffer(force) {
let buffer = this._editor.state.doc.toString();
if (force || (buffer !== this._lastAutoSave)) {
this._lastAutoSave = buffer;
await SaveCurrentBuffer(buffer);
}
}
}
export const textProcessor = new TextProcessor();