Skip to content

Instantly share code, notes, and snippets.

@franklindyer
Created March 12, 2024 05:53
Show Gist options
  • Save franklindyer/2e2303b4bf4ae0caaae0ebf4d33b90bc to your computer and use it in GitHub Desktop.
Save franklindyer/2e2303b4bf4ae0caaae0ebf4d33b90bc to your computer and use it in GitHub Desktop.
Code annotation proof of concept
<head>
<style>
#main-container {
margin: auto;
width: 80%;
}
div.annotated-code {
font-family: Courier;
background-color: #dddddd;
color: black;
padding-left: 8px;
padding-right: 8px;
padding-top: 2px;
padding-bottom: 2px;
border: 2px gray dashed;
overflow-wrap: break-word;
white-space: pre-wrap;
}
</style>
</head>
<body>
<div id="main-container">
<div id="an-code-0" class="annotated-code">
ɑfibo :: Int -> Intβ
ɑfibo 0 = 0
fibo 1 = 1β
ɑfibo n = fibo (n-1) + fibo (n-2)β
</div>
<div id="an-code-0-info"></div>
</div>
<script>
const annotations = {
"an-code-0-0": "This function takes an integer as input, and returns an integer.",
"an-code-0-1": "The first two Fibonacci numbers are F₀ = 0 and F₁ = 1.",
"an-code-0-2": "This is the Fibonacci recurrence: each Fibonacci number is the sum of the previous two."
}
function annotateText(content) {
let replacer = (match, p1, offset, str) => `<span class='annotated-snippet'>${p1}</span>`;
let annotated = content.replace(/ɑ([^β]+)β/g, replacer);
return annotated;
}
function annotateElement(id) {
let elt = document.getElementById(id);
elt.innerHTML = annotateText(elt.innerHTML);
let snips = elt.getElementsByClassName("annotated-snippet");
let infoBox = document.getElementById(`${id}-info`);
Array.from(snips).forEach((snip, i) => {
snip.id = `${id}-${i}`;
snip.onmouseover = () => {
snip.style.backgroundColor = "rgba(255,255,0,0.3)";
infoBox.textContent = annotations[snip.id];
};
snip.onmouseleave = () => {
snip.style.backgroundColor = "rgba(0,0,0,0)";
infoBox.textContent = "";
}
});
}
annotateElement("an-code-0")
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment