stack3 with paste
by Julian
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Word Index Tracker</title>
</head>
<body>
<form id="indexer">
<button id="toggle" class="off" type="button"></button>
<fieldset id="source">
Paste text here
</fieldset>
<output id="selected">
<ol></ol>
</output>
</form>
</body>
</html>
CSS
:root {
font: 2ch/1.5 "Segoe UI"
}
#toggle {
margin-bottom: 1rem;
padding: 5px 10px;
border-radius: 8px;
font: inherit;
cursor: pointer;
background:
radial-gradient(
ellipse at center,
rgba(197,222,234,1) 0%,
rgba(138,187,215,1) 31%,
rgba(6,109,171,1) 100%);
}
#toggle::before {
content: "Edit Mode"
}
#toggle::after {
content: " ON";
}
#toggle.off {
color: #fff;
background:
radial-gradient(
ellipse at center,
rgba(125, 126, 125, 1) 0%,
rgba(14, 14, 14, 1) 100%);
}
JavaScript
// Reference <form>
const form = document.forms.indexer;
/**
* Reference all form controls of <form>
* In this layout it is:
* - <button>
* - <fieldset>
* - <output>
*/
const io = form.elements;
// Reference <button>
const btn = io.toggle;
// Reference <fieldset>
const src = io.source;
// Reference <output>
const sel = io.selected;
// Declaration for two arrays (not made yet).
let marked;
let indices;
/**
* Index each word by extracting the string,
* converting the string into an array of
* substrings, and wrapping each word with
* a <mark> element. Each <mark> is then
* assigned a [data-idx] attribute with the
* corresponding index number.
*/
const indexText = () => {
const text = src.innerText;
let marks = text.split(" ");
marks[0] = `<mark>${marks[0]}`;
marks[marks.length - 1] = `${marks[marks.length - 1]}</mark>`;
src.innerHTML = marks.join(`</mark> <mark>`).trim();
marked = [...document.querySelectorAll("mark")];
marked.forEach((mrk, idx) => mrk.dataset.idx = idx);
};
/**
* Handle "click" event when the user clicks
* button#toggle. Basically an on/off switch
* for whether fieldset#source can be edited
* and when the text can be indexed.
* @param {object} e - Event object
*/
const editText = (e) => {
e.target.classList.toggle("off");
src.toggleAttribute("contenteditable");
indexText();
};
/**
* Handle "click" event when user clicks
* a word. Each word is inside a <mark> and
* it's background color will change, and
* it's text and index number will be listed
* in output#selected > ol.
* @param {object} e - Event object
*/
const highLight = (e) => {
const clk = e.target;
if (clk.matches("mark")) {
clk.classList.toggle("highlight");
}
indices = [...document.querySelectorAll(".highlight")]
.map(h => {
let txt = h.innerText;
txt = txt.replace(/[^A-Z0-9]$/i, "");
return `
<li>${txt}
${h.dataset.idx}</li>
`;
});
sel.firstElementChild.innerHTML =...