indentfold
code:script.js
function*u(e){let t=[],n=-1;for(let i of e){n++;let a=y(i.text);for(lets,oof...t){if(o<a)break;yield{id:es.id,indent:o,children:e.slice(s+1,n).map(({id:d})=>d)},t.shift()}t.unshift(n,a)}let l=[];for(leti,aof t){let s=ei.id;yield{id:s,indent:a,children:...l},l.unshift(s)}}var y=e=>e.match(/^(\s*)/)?.1?.length??0;var E=()=>{r(),scrapbox.addListener("layout:changed",r);let e,t=()=>{clearTimeout(e),e=setTimeout(r,500)};return scrapbox.addListener("lines:changed",t),{cleanup:()=>{v(),x("folding-lines"),scrapbox.removeListener("layout:changed",r),scrapbox.removeListener("lines:changed",t)}}};function r(){if(scrapbox.Layout!=="page")return;let e=[],t,n=l=>{e=l(e),cancelAnimationFrame(t),t=requestAnimationFrame(()=>{h("folding-lines",div:is(${e.map(i=>#${i}).join(", ")}) { display: none; })})};for(let{id:l,indent:i,children:a}of u(scrapbox.Page.lines)){let s=document.getElementById(L${l});b(s,i,a.map(o=>L${o}),n)}}function h(e,t){let n=document.querySelector(head style[data-style-name="${e}"]);n||(n=document.createElement("style"),n.dataset.styleName=e,document.head.append(n)),n.textContent=t}function x(e){document.querySelector(head style[data-style-name="${e}"])?.remove?.()}function b(e,t,n,l){let i=e.getElementsByClassName("button folding")0,a=i?.classList?.contains?.("open")??!0;if(i?.remove?.(),n.length===0)return;let s=document.createElement("i");s.className=fas fa-caret-${a?"down":"right"},s.style.minWidth="0.5em";let o=document.createElement("a");o.type="button",o.classList.add("button","folding","open"),o.style.position="absolute";let d=e.getElementsByClassName("indent")0??e.getElementsByClassName("char-index")0,f=e.getBoundingClientRect().left,p=t===0?f:d.getBoundingClientRect().left;o.style.left=calc(${Math.round(p-f)}px - ${e.getElementsByClassName("code-body").length>0?2:1}em),o.style.fontSize="20px",o.style.zIndex="1000",o.append(s),o.addEventListener("click",m=>{m.preventDefault(),m.stopPropagation(),a?(l(c=>(c.push(...n),c)),s.className="fas fa-caret-right",e.style.textDecoration="solid underline var(--folding-line-color, orange) 2px",a=!1):(l(c=>c.filter(g=>!n.includes(g))),s.className="fas fa-caret-down",e.style.textDecoration="",a=!0)}),e.insertAdjacentElement("afterbegin",o)}function v(){for(let e of Array.from(document.querySelectorAll("div.line > .button.folding"))){let t=e.closest("div.line");t&&(t.style.textDecoration=""),e.remove()}}export{E as setup};