Skip to content

Commit

Permalink
feat(autosave): save the editor content to local browser storage and …
Browse files Browse the repository at this point in the history
…use a debounce to keep it fast
  • Loading branch information
st-vi committed Nov 22, 2023
1 parent 1f17782 commit 4d3d63b
Show file tree
Hide file tree
Showing 5 changed files with 44 additions and 24 deletions.
1 change: 0 additions & 1 deletion WebSocketClient/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ <h1>UVL Playground</h1>
</div>
<div class="flex-container">
<div class="container">
<button id="rerender">Trigger rerender</button>
<div id="container" class="editor"></div>
</div>
<div class="graph"></div>
Expand Down
6 changes: 6 additions & 0 deletions WebSocketClient/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions WebSocketClient/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
"@codingame/monaco-vscode-theme-service-override": "~1.83.2",
"@viz-js/viz": "^3.2.3",
"dotenv": "^16.3.1",
"lodash": "^4.17.21",
"monaco-editor": "^0.44.0",
"monaco-editor-workers": "~0.44.0",
"monaco-languageclient": "^6.6.0",
Expand Down
41 changes: 27 additions & 14 deletions WebSocketClient/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,15 @@ import config from './config.js';
import { instance } from "@viz-js/viz";
import { Message } from 'vscode-jsonrpc';
import { v4 as uuidv4 } from 'uuid';
import lodash from 'lodash';

import { buildWorkerDefinition } from 'monaco-editor-workers';
buildWorkerDefinition('./node_modules/monaco-editor-workers/dist/workers', new URL('', window.location.href).href, false);

const languageId = 'uvls';
let languageClient: MonacoLanguageClient;
let fileID;
let model;

const createUrl = (hostname: string, port: number, path: string, searchParams: Record<string, any> = {}, secure: boolean): string => {
const protocol = secure ? 'wss' : 'ws';
Expand Down Expand Up @@ -138,11 +140,6 @@ function createDiagramFromDot(res: string): void {
});
}

function generateDiagram(): void {
vscode.commands.executeCommand("uvls/generate_diagram", `file:///workspace/${fileID}.uvl`)
.then((res) => createDiagramFromDot(res as string));
}

export const startPythonClient = async () => {
// init vscode-api
const useDebugLogging = config.debug ? LogLevel.Debug : LogLevel.Off;
Expand Down Expand Up @@ -182,14 +179,6 @@ export const startPythonClient = async () => {
};
registerExtension(extension, ExtensionHostKind.LocalProcess);

const button = document.getElementById("rerender");
if(button){
button.onclick = () => generateDiagram();
}
else{
console.log("I cannot find the button")
}

updateUserConfiguration(`{
"editor.fontSize": 14,
"workbench.colorTheme": "Default Dark Modern",
Expand All @@ -198,7 +187,7 @@ export const startPythonClient = async () => {

const fileSystemProvider = new RegisteredFileSystemProvider(false);
fileID = uuidv4();
fileSystemProvider.registerFile(new RegisteredMemoryFile(vscode.Uri.file(`/workspace/${fileID}.uvl`), 'features\n\tfeature1\n\t\tor\n\t\t\tfeature2\n\t\t\tfeature3\n\nconstraints\n\tfeature1'));
fileSystemProvider.registerFile(new RegisteredMemoryFile(vscode.Uri.file(`/workspace/${fileID}.uvl`), getInitialFm()));
registerFileSystemOverlay(1, fileSystemProvider);

// create the web socket and configure to start the language client on open, can add extra parameters to the url if needed.
Expand All @@ -212,6 +201,14 @@ export const startPythonClient = async () => {

// use the file create before
const modelRef = await createModelReference(monaco.Uri.file(`/workspace/${fileID}.uvl`));
model = modelRef.object;

const debouncedSave = lodash.debounce(saveFm, 1000);
modelRef.object.onDidChangeContent(() => {
debouncedSave();
});


modelRef.object.setLanguageId(languageId);

// create monaco editor
Expand All @@ -220,3 +217,19 @@ export const startPythonClient = async () => {
automaticLayout: true
});
};

function getInitialFm(){
let initialFm = "features\n\tfeature1\n\t\tor\n\t\t\tfeature2\n\t\t\tfeature3\n\nconstraints\n\tfeature1";
const storedFm = window.localStorage.getItem("fm");
if(storedFm !== null){
initialFm = storedFm;
}
return initialFm;
}

function saveFm(){
if(model !== undefined){
const content = model.textEditorModel?.getValue();
window.localStorage.setItem("fm", content);
}
}
19 changes: 10 additions & 9 deletions WebSocketLanguageServer/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,10 @@ const initUVLS = () => {
if (typedMessage.method === "client/registerCapability") {
initMessage2 = newMessage;
} else if (typedMessage.method === "workspace/executeCommand") {
console.log(typedMessage);
const fileUri = typedMessage.params?.["arguments"][0]?.["uri"].split("create/").pop();
if(fileUri !== undefined){
socketConnection = uriToConnectionMap.get(fileUri);
}
}

} else if (Message.isResponse(message)) {
Expand All @@ -111,12 +114,12 @@ const initUVLS = () => {
} else if (Message.isNotification(message)) {
const typedMessage = message as NotificationMessage;
const uri: string | undefined = typedMessage.params?.["uri"];
if (uri !== undefined) {
socketConnection = uriToConnectionMap.get(uri);
if (uri !== undefined && uri.split("///").length === 2) {
socketConnection = uriToConnectionMap.get(uri.split("///")[1]);

}
}
if (socketConnection) {
console.log(newMessage);
socketConnection.writer.write(newMessage);
} else {
console.log(`Could not resolve destination of server message to right client\nMessage: ${JSON.stringify(message)}`)
Expand All @@ -139,7 +142,6 @@ function multiplexHandler(socket: IWebSocket) {
socketConnection.writer.write(initMessage1);
return;
} else if (typedMessage.method === "workspace/executeCommand") {
console.log(typedMessage);
const serverScopeId = getServerScopeIdFromClientScopeId(Number(typedMessage.id), clientId);
newMessage["id"] = serverScopeId;
} else {
Expand All @@ -160,18 +162,17 @@ function multiplexHandler(socket: IWebSocket) {
return;
} else if (typedMessage.method === "textDocument/didOpen") {
const uri: string | undefined = typedMessage.params?.["textDocument"]?.["uri"];
if (uri !== undefined) {
uriToConnectionMap.set(uri, socketConnection);
if (uri !== undefined && uri.split("///").length === 2) {
uriToConnectionMap.set(uri.split("///")[1], socketConnection);
}

} else if (typedMessage.method === "$/cancelRequest") {
console.log(JSON.stringify(newMessage));
newMessage["params"]["id"] = getServerScopeIdFromClientScopeId(newMessage["params"]["id"], clientId);
} else if (typedMessage.method === "initialized" && initMessage2 !== undefined) {
socketConnection.writer.write(initMessage2);
return;
} else {
console.log(JSON.stringify(newMessage));
// other messages are just forwarded to the uvls
}

}
Expand Down

0 comments on commit 4d3d63b

Please sign in to comment.