Reputation: 1
I'm building a calculator web application where users type ASCIIMath expressions, which are then rendered into LaTeX using ASCIIMathML. One challenge I'm facing is ensuring that when users type or move the cursor in the input field, the scroll position aligns correctly with the corresponding position in the rendered LaTeX output.
The main issue is that the relationship between the length of the ASCIIMath input and the width of the rendered LaTeX is non-linear and unpredictable. For example:
Currently, my implementation uses simple arithmetic to estimate the cursor position in the LaTeX render, but this is inconsistent because:
Here is my current code snippet for handling scrolling:
const cursorPosition = keyinputs.selectionStart;
const isTypingAtEnd = cursorPosition === input.length;
const simplebarContentWrapper = document.querySelector('.simplebar-content-wrapper'); // latex is stored in here
if (isTypingAtEnd) {
simplebarContentWrapper.scrollLeft = simplebarContentWrapper.scrollWidth;
showScrollbarTemporarily();
} else {
const currentScrollPosition = simplebarContentWrapper.scrollLeft;
const contentWidth = simplebarContentWrapper.scrollWidth;
const displayWidth = simplebarContentWrapper.clientWidth;
if (contentWidth > displayWidth) {
const threshold = displayWidth * 0.05;
const estimatedCursorPosition = (cursorPosition / input.length) * contentWidth;
const cursorViewPosition = estimatedCursorPosition - currentScrollPosition;
if (cursorViewPosition < threshold) {
const targetScrollPosition = Math.max(0, estimatedCursorPosition - threshold);
simplebarContentWrapper.scrollTo({
left: targetScrollPosition,
behavior: 'auto'
});
} else if (cursorViewPosition > displayWidth - threshold) {
const targetScrollPosition = Math.min(contentWidth - displayWidth, estimatedCursorPosition + threshold);
simplebarContentWrapper.scrollTo({
left: targetScrollPosition,
behavior: 'auto'
});
}
}
}
This works in some cases, but it doesn't guarantee accuracy when:
I want to improve this algorithm to ensure scrolling always aligns the input cursor with the correct position in the rendered LaTeX. I've thought about tokenizing the ASCIIMath input or precomputing mappings between input positions and LaTeX positions, but I'm unsure how to implement these efficiently.
Upvotes: 0
Views: 19