- ClayJS
- Advanced
- Plugins
- Advanced source
Advanced source
Reading on-disk HTML bytes, mapping live elements to UTF-16 source offsets, and observing partial reprints.
For editing tools and plugins that map live DOM elements to source file offsets; for what source does by default and how to turn it off, see source.
Reading the file clay believes is on disk#
clay.source.stats(); // { paired, saves, reprints, lastReprint, ... }
document.addEventListener("clay:save-reprinted", (e) => console.warn(e.detail.reason));
clay.source.text(); // the bytes clay believes are on disk right now
clay.source.locate(el); // { from, to, line, column } for a live element, or null
clay.source.repairGeneration; // how many times this session rebuilt its map; 0 before it installs
The map installs on demand, so read await clay.source.ready before the first text() or locate(): until it installs, text() is null and locate() is null for every element. clay.source.ready is null in view. stats().installed and stats().refused say whether it installed, and clay.source.unpaired() lists what did not pair.
text() and locate() are what an editing tool needs: read the file as it will be written, point at an element in the live page, and express the change as a range in those bytes instead of as a DOM mutation. The offsets and column are UTF-16 code units into text(), not bytes, so slice the string text() hands you and the answer is exact. locate() returns null for an element that is not in the file, which includes one the page created after load.
Every save is reparsed and compared to the page before it is sent, and anything that does not match exactly is sent as the ordinary full serialization instead, so the worst case is the behaviour you already have. clay:save-reprinted fires when that happens and clay.source.stats() counts it. Edit mode only. It costs an HTML parser (about 48 KB compressed), loaded only when something needs it: the first save that changes something, or code that reads clay.source.ready. It starts from bytes the page already holds where it can, so a clean autosave, a reader and a page that never saves load nothing. exclude=source turns it off altogether.
repairGeneration is a getter, not a call. It counts the times this session’s map of the page to the file was rebuilt, and reads 0 before the session installs. A document over 300 KB prepares its save across several tasks; if repairGeneration moves while that save is being prepared, the preparation stops, because its bytes were laid out against a pairing that no longer describes the page.