Skip to content

Commit

Permalink
adds support for save/restore (local browser storage) snippets (#270)
Browse files Browse the repository at this point in the history
  • Loading branch information
adrianoc committed Apr 2, 2024
1 parent 228f22a commit 3687d66
Show file tree
Hide file tree
Showing 6 changed files with 95 additions and 54 deletions.
2 changes: 1 addition & 1 deletion Cecilifier.Web/Pages/Index.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@
</script>

<script>
initializeSite("@Model.ErrorAccessingGist", "@fromGist", "@this.GetType().Assembly.GetName().Version");
initializeSite("@Model.ErrorAccessingGist", "@fromGist", "@Request.Path", "@Request.Query["remove"]", "@GetType().Assembly.GetName().Version");
</script>

<script>
Expand Down
1 change: 1 addition & 0 deletions Cecilifier.Web/Pages/Shared/_Layout.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
<script src="~/js/cecilifier.js"></script>
<script src="~/js/cecilifier.settings.js"></script>
<script src="~/js/cecilifier.hoverprovider.js"></script>
<script src="~/js/cecilifier.snippethandler.js"></script>
<script src="~/js/il.opcodes.js"></script>
<script src="~/js/release_notes.js"></script>

Expand Down
4 changes: 2 additions & 2 deletions Cecilifier.Web/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ public void ConfigureServices(IServiceCollection services)
options.MinimumSameSitePolicy = SameSiteMode.None;
});

services.AddRazorPages();
services.AddRazorPages(options => options.Conventions.AddPageRoute("/index", "/{snippet-name}"));
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
Expand Down Expand Up @@ -123,7 +123,7 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env)

app.Use(async (context, next) =>
{
if (context.Request.Path == "/ws")
if (context.Request.Path == "/connection/ws")
{
if (context.WebSockets.IsWebSocketRequest)
{
Expand Down
69 changes: 19 additions & 50 deletions Cecilifier.Web/wwwroot/js/cecilifier.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ let focusedEditor; // either csharpCode or cecilifiedCode
let blockMappings = null;
let csharpCodeEditorWidthMultiplier = 0.3;
let compilationErrorToast = null; // toast informing user about compilation errors. This reference is used to close the toast before cecilifying code.
let onCecilifiySuccessCallbacks = [];

const CecilifierResponseStatus = Object.freeze({
Success: 0,
Expand Down Expand Up @@ -126,19 +127,13 @@ function decreaseFocusedEditorFontSize() {
const newFontSize = options.fontSize - 1;
focusedEditor.updateOptions({ fontSize: newFontSize });
}
function initializeSite(errorAccessingGist, gist, version) {
function initializeSite(errorAccessingGist, gist, requestPath, removeStoredSnippet, version) {
require.config({ paths: { vs: 'lib/node_modules/monaco-editor/min/vs' } });

require(['vs/editor/editor.main'], function () {
csharpCode = monaco.editor.create(document.getElementById('csharpcode'), {
theme: "vs-dark",
value: [
`// Supported CSharp language version: ${document.getElementById('supportedCSharpVersion').innerText}\n// https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-${document.getElementById('supportedCSharpVersion').innerText}`,
'using System;',
'class Foo',
'{',
'\tvoid Bar() => Console.WriteLine("Hello World!");',
'}'].join('\n'),
value:"",
language: 'csharp',
minimap: { enabled: false },
fontSize: 14,
Expand Down Expand Up @@ -176,7 +171,13 @@ function initializeSite(errorAccessingGist, gist, version) {

initializeHoverProvider()

handleGist(gist, errorAccessingGist);
handleInitialSnippet(gist, errorAccessingGist, requestPath, removeStoredSnippet,
`// Supported CSharp language version: ${document.getElementById('supportedCSharpVersion').innerText}\n// https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-${document.getElementById('supportedCSharpVersion').innerText}
using System;
class Foo
{
void Bar() => Console.WriteLine("Hello World!");
};`);

csharpCode.focus();
focusedEditor = csharpCode;
Expand Down Expand Up @@ -310,7 +311,7 @@ function retrieveListOfFixedIssuesInStagingServer(callback) {
message: `Unable to retrieve list of fixed issues in staging server.`,
dismissible: true,
status: "Warning",
timeout: 120000,
timeout: 30000,
icon: "exclamation"
});

Expand Down Expand Up @@ -745,7 +746,7 @@ function setAlert(div_id, msg) {
function initializeWebSocket() {
const scheme = document.location.protocol === "https:" ? "wss" : "ws";
const port = document.location.port ? (":" + document.location.port) : "";
const connectionURL = scheme + "://" + document.location.hostname + port + "/ws";
const connectionURL = scheme + "://" + document.location.hostname + port + "/connection/ws";

let newSocket = new WebSocket(connectionURL);
newSocket.isRetryingToConnect = websocket === undefined ? 0 : websocket.isRetryingToConnect;
Expand Down Expand Up @@ -810,10 +811,15 @@ function initializeWebSocket() {
});
}
else {
cecilifiedCode.setValue(response.cecilifiedCode);
cecilifiedCode.setValue(response.cecilifiedCode);
// save the returned mappings used to map between code snippet <-> Cecilified Code.
blockMappings = response.mappings;
}

for(let i = 0; i < onCecilifiySuccessCallbacks.length; i++) {
onCecilifiySuccessCallbacks[i].callback(onCecilifiySuccessCallbacks[i].state);
}

} else if (response.status === CecilifierResponseStatus.ConnectionEstablished) {
let response = JSON.parse(event.data);
updateUsageStatisticsToolTip(response);
Expand All @@ -836,8 +842,7 @@ function initializeWebSocket() {
function: removeMarkersFromCSharpCode
}
]
});

});
} else if (response.status === CecilifierResponseStatus.InternalError) {
ShowErrorDialog("", response.error, "We've got an internal error.");
} else if (response.status === CecilifierResponseStatus.MissingAssemblies) {
Expand Down Expand Up @@ -961,42 +966,6 @@ function copyToClipboard(elementId) {
navigator.clipboard.writeText(cecilifiedCode.getValue("\r\n"));
}

function cecilifyFromGist(counter) {
if (websocket.readyState !== WebSocket.OPEN) {
if (counter < 4) {
setTimeout(cecilifyFromGist, 500, counter + 1);
}
}
else {
simulateClick("sendbutton");
}
}

function handleGist(gist, errorAccessingGist) {
if (errorAccessingGist.length === 0) {
setValueFromGist(gist);
} else {
setError(errorAccessingGist);
}
}

function setValueFromGist(snippet) {
if (snippet === null || snippet.length === 0)
return;

csharpCode.setValue(
snippet
.replace(/&quot;/g, '"')
.replace(/&gt;/g, '>')
.replace(/&lt;/g, '<')
.replace(/&#x27;/g, "'")
.replace(/&#x2B;/g, '+')
.replace(/&#x38;/g, '&')
.replace(/&amp;/g, '&'));

cecilifyFromGist(1);
}

function showSpinner() {
let spinnerDiv = document.getElementById("spinnerDiv");
spinnerDiv.style.visibility = "inherit";
Expand Down
71 changes: 71 additions & 0 deletions Cecilifier.Web/wwwroot/js/cecilifier.snippethandler.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
function handleInitialSnippet(gist, errorAccessingGist, requestPath, removeStoredSnippet, defaultSnippet) {
let snippet = gist;
let autoCecilify = false;

if (snippet !== null && snippet.length > 0) {
if (errorAccessingGist.length !== 0)
setError(errorAccessingGist);
autoCecilify = true;
}
else {
let snippetName = requestPath !== "/" ? requestPath.substring(1) : "default";
if (removeStoredSnippet) {
window.localStorage.removeItem(snippetName);
SnackBar({
message: `Snippet ${snippetName} deleted from local storage.`,
dismissible: true,
status: "Success",
timeout: 10000,
icon: "exclamation"
});
return;
}

snippet = window.localStorage.getItem(snippetName);

if (snippet === null || snippet.length === 0)
snippet = defaultSnippet;

onCecilifiySuccessCallbacks = onCecilifiySuccessCallbacks.concat(
[
{
state: snippetName,
callback: state => {
window.localStorage.setItem(state, csharpCode.getValue("\r\n"));
}
}
]);
}
setValueFromSnippet(snippet, autoCecilify);
}

function setValueFromSnippet(snippet, autoCecilify) {
if (snippet === null || snippet.length === 0)
return;

csharpCode.setValue(
snippet
.replace(/&quot;/g, '"')
.replace(/&gt;/g, '>')
.replace(/&lt;/g, '<')
.replace(/&#x27;/g, "'")
.replace(/&#x2B;/g, '+')
.replace(/&#x38;/g, '&')
.replace(/&amp;/g, '&'));

if (autoCecilify)
cecilifyFromSnippet(1);
}

function cecilifyFromSnippet(counter) {
if (websocket.readyState !== WebSocket.OPEN) {
if (counter < 4) {
setTimeout(cecilifyFromSnippet, 500, counter + 1);
}
else {
}
}
else {
simulateClick("sendbutton");
}
}
2 changes: 1 addition & 1 deletion Cecilifier.Web/wwwroot/js/release_notes.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ function showReleaseNotes() {
message: `Error retrieving release notes.`,
dismissible: true,
status: "Warning",
timeout: 120000,
timeout: 45000,
icon: "exclamation"
});

Expand Down

0 comments on commit 3687d66

Please sign in to comment.