Public
Edited
Jun 25, 2024
Importers
3 stars
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function TextScroller(t, options = {}) {
const {
comma = false,
wheel = true,
keydown = true,
highlight = true,
step = 1,
formatting = (n) => {
return n;
},
constraints = (n) => {
return true;
}
} = options;

let action = (e) => {
// only recognize up/down arrow and mousewheel
if (e.which != 38 && e.which != 40 && e.type != "wheel") return;

// compatability for Observable Inputs and html`` inputs
if (!t.input)
t.input = t.querySelector("input") || t.querySelector("textarea");
if (!t.input) t.input = t;

// only works when focused
if (t.input != document.activeElement) return;

e.preventDefault();

// amount to change the value, hold alt/ctrl/shift to increase the delta
// holding the shift key while scrolling makes deltaY -0 regardless of scroll direction
let delta = e.which == 40 || e.deltaY < 0 ? -step : step;
let deltaScale = 10;
if (e.altKey) delta *= deltaScale;
if (e.ctrlKey) delta *= deltaScale;
if (e.shiftKey) delta *= deltaScale;

let newValue = "";
let selection = { start: 0, end: 0 };

// sequentially reconstruct the value string to handle number width changes
parseNumbers(
t.input.value,
t.input.selectionStart,
t.input.selectionEnd,
delta,
options
).forEach((n, i, a) => {
if (i == 0) selection.start = n.start;

newValue +=
t.input.value.substring(i == 0 ? 0 : a[i - 1].end, n.start) +
n.newNumber;

if (i == a.length - 1) {
selection.end = newValue.length;
newValue += t.input.value.substring(n.end, t.input.value.length);
}
});

// noop if there are no changes
if (newValue == "") return;

t.input.value = newValue;

// update cells that reference this view
t.input.dispatchEvent(new CustomEvent("input"));
t.dispatchEvent(new CustomEvent("input"));

// snap the cursor to the number(s) selection
if (highlight || selection.start != selection.end) {
t.input.setSelectionRange(selection.start, selection.end);
}
};

if (wheel) t.addEventListener("wheel", action);
if (keydown) t.addEventListener("keydown", action);

return t;
}
Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more