dequoter/frontend/src/services.js

85 lines
2.3 KiB
JavaScript
Raw Normal View History

2026-01-25 22:31:14 +00:00
import {
ProcessText,
LoadCurrentBuffer,
SaveCurrentBuffer,
} from "../wailsjs/go/main/App";
2025-09-06 01:26:54 +00:00
class TextProcessor {
2026-01-25 22:31:14 +00:00
constructor() {
this._lastAutoSave = undefined;
}
2025-09-06 01:26:54 +00:00
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,
};
}
});
2025-09-06 01:26:54 +00:00
this._editor.dispatch({ changes: changes });
});
}
2026-01-25 22:31:14 +00:00
async runTextCommand(command) {
2025-09-06 01:26:54 +00:00
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,
}))
}
2026-01-25 22:31:14 +00:00
await ProcessText({
2025-09-06 01:26:54 +00:00
action: command,
input: inputs,
2025-09-06 01:26:54 +00:00
});
2026-01-25 22:31:14 +00:00
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;
2025-09-06 01:26:54 +00:00
}
2026-01-25 22:31:14 +00:00
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);
}
}
}
2025-09-06 01:26:54 +00:00
export const textProcessor = new TextProcessor();