| 1 |
import type { ViewUpdate } from "@codemirror/view"; |
| 2 |
import { ViewPlugin } from "@codemirror/view"; |
| 3 |
|
| 4 |
/** |
| 5 |
* This CodeMirror view plugin creates a ruler at (before) the given column. |
| 6 |
*/ |
| 7 |
export const rulerPlugin = ( |
| 8 |
column: number, |
| 9 |
): ViewPlugin<{ |
| 10 |
update(update: ViewUpdate): void; |
| 11 |
destroy(): void; |
| 12 |
}> => |
| 13 |
ViewPlugin.define((view) => { |
| 14 |
const ruler = view.dom.appendChild(document.createElement("div")); |
| 15 |
ruler.style.position = "absolute"; |
| 16 |
ruler.style.borderRight = "1px dotted black"; |
| 17 |
ruler.style.height = "100%"; |
| 18 |
ruler.style.opacity = "0.5"; |
| 19 |
ruler.style.pointerEvents = "none"; |
| 20 |
|
| 21 |
const updatePosition = () => { |
| 22 |
const firstLine = view.contentDOM.querySelector(".cm-line"); |
| 23 |
if (firstLine) { |
| 24 |
const { paddingLeft } = getComputedStyle(firstLine); |
| 25 |
const domRect = view.dom.getBoundingClientRect(); |
| 26 |
const contentDOMRect = view.contentDOM.getBoundingClientRect(); |
| 27 |
// We need to add the width of the gutter (line numbers etc.) since |
| 28 |
// our ruler is positioned absolutely within the whole editor. |
| 29 |
const gutterWidth = contentDOMRect.x - domRect.x; |
| 30 |
const offset = column * view.defaultCharacterWidth + gutterWidth; |
| 31 |
ruler.style.width = paddingLeft; |
| 32 |
ruler.style.left = `${offset.toString()}px`; |
| 33 |
} |
| 34 |
}; |
| 35 |
|
| 36 |
view.requestMeasure({ read: updatePosition }); |
| 37 |
|
| 38 |
return { |
| 39 |
update(update) { |
| 40 |
if (update.viewportChanged || update.geometryChanged) { |
| 41 |
view.requestMeasure({ read: updatePosition }); |
| 42 |
} |
| 43 |
}, |
| 44 |
|
| 45 |
destroy() { |
| 46 |
ruler.remove(); |
| 47 |
}, |
| 48 |
}; |
| 49 |
}); |