tensaku 0.3.3 → 0.3.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/CHANGELOG.md +7 -0
- data/app/assets/tensaku.js +2 -2
- data/lib/tensaku/version.rb +1 -1
- metadata +1 -1
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: fac97d550dbf849762ea442a38deaec1ddb6324036d4c245a1d1dbcd98cacc3a
|
|
4
|
+
data.tar.gz: 59e5805ae504654e9bb165f9ef6a9aa4f2c26fa3a49f55c54b5dd3a79337baed
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: f7e341cb18501e7cc3375d8d69610e8fd97f614325361aacc0ae63ac6c6857984545d9236b7ea610532d98025be015b9c34304de318e0f34798fbdd678de880d
|
|
7
|
+
data.tar.gz: ca53738a6b54633b98e0ca1611fd1632cf36fc41e515ffb60a0eb2aacc8111af59c11f8570e95663db63a982085a7e0ae5a711b2595385b6fc8f2d3a5abb5366
|
data/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,12 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.3.4 (2026-11-23)
|
|
4
|
+
|
|
5
|
+
- A translation with markup (an `_html` key, or one a view marks `html_safe`) opens its editor. It
|
|
6
|
+
was refused with "The file changed since the page was rendered" on every try, because the stale
|
|
7
|
+
check looked for the tags and entities in the page's text. It now compares the text the page
|
|
8
|
+
shows, so a real change to the locale file is still refused.
|
|
9
|
+
|
|
3
10
|
## 0.3.3 (2026-11-15)
|
|
4
11
|
|
|
5
12
|
- With [meta-tags](https://github.com/kpumuk/meta-tags), pages keep their own title in development.
|
data/app/assets/tensaku.js
CHANGED
|
@@ -383,6 +383,6 @@ kbd { font: 10.5px/1 var(--mono); padding: 2px 4px; border-radius: 4px; backgrou
|
|
|
383
383
|
}
|
|
384
384
|
`}),svgStyleElement.appendChild(ownerDocument.createTextNode(allCssText))}if(log.timeEnd("clone node"),await onCloneNode?.(clone),font!==!1&&isElementNode(clone))log.time("embed web font"),await embedWebFont(clone,context),log.timeEnd("embed web font");log.time("embed node"),embedNode(clone,context);let count=tasks.length,current2=0,runTask=async()=>{while(!0){let task=tasks.pop();if(!task)break;try{await task}catch(error){context.log.warn("Failed to run task",error)}progress?.(++current2,count)}};progress?.(current2,count),await Promise.all([...Array.from({length:4})].map(runTask)),log.timeEnd("embed node"),await onEmbedNode?.(clone);let svg=createForeignObjectSvg(clone,context);return svgDefsElement&&svg.insertBefore(svgDefsElement,svg.children[0]),svgStyleElement&&svg.insertBefore(svgStyleElement,svg.children[0]),autoDestruct&&destroyContext(context),await onCreateForeignObjectSvg?.(svg),svg}function createForeignObjectSvg(clone,context){let{width,height}=context,svg=createSvg(width,height,clone.ownerDocument),foreignObject=svg.ownerDocument.createElementNS(svg.namespaceURI,"foreignObject");return foreignObject.setAttributeNS(null,"x","0%"),foreignObject.setAttributeNS(null,"y","0%"),foreignObject.setAttributeNS(null,"width","100%"),foreignObject.setAttributeNS(null,"height","100%"),foreignObject.append(clone),svg.appendChild(foreignObject),svg}async function domToCanvas(node,options){let context=await orCreateContext(node,options),svg=await domToForeignObjectSvg(context),dataUrl=svgToDataUrl(svg,context.isEnable("removeControlCharacter"));if(!context.autoDestruct)context.svgStyleElement=createStyleElement(context.ownerDocument),context.svgDefsElement=context.ownerDocument?.createElementNS(XMLNS,"defs"),context.svgStyles.clear();let image=createImage(dataUrl,svg.ownerDocument);return await imageToCanvas(image,context)}var MARGIN=40,MAX_SIDE=16000,MAX_AREA=40000000,MAX_OUTPUT=1600,isOverlay=(node)=>node instanceof Element&&node.hasAttribute("data-tensaku-ui"),MAX_NODES=2000;function containerOf(rect){let x=Math.min(Math.max(rect.left+rect.width/2,0),innerWidth-1),y=Math.min(Math.max(rect.top+rect.height/2,0),innerHeight-1),contains=(box2,margin)=>box2.left<=rect.left-margin&&box2.top<=rect.top-margin&&box2.right>=rect.right+margin&&box2.bottom>=rect.bottom+margin,node=document.elementsFromPoint(x,y).find((el)=>!el.closest("[data-tensaku-ui]"))??document.body,tight=null;while(node&&node!==document.documentElement){let box2=node.getBoundingClientRect();if(tight??=contains(box2,-0.5)?node:null,tight&&node.getElementsByTagName("*").length>MAX_NODES)return tight;if(contains(box2,MARGIN))return node;node=node.parentElement}return tight??document.body}async function capture(area){try{let rect=new DOMRect(area.x-scrollX,area.y-scrollY,area.width,area.height),node=containerOf(rect),box2=node.getBoundingClientRect(),scale=Math.min(devicePixelRatio||1,2,MAX_SIDE/Math.max(box2.width,box2.height,1),Math.sqrt(MAX_AREA/Math.max(box2.width*box2.height,1))),canvas=await domToCanvas(node,{scale,filter:(n)=>!isOverlay(n),timeout:3000,backgroundColor:getComputedStyle(document.body).backgroundColor||"#fff"}),left=Math.max(rect.left-MARGIN,box2.left),top=Math.max(rect.top-MARGIN,box2.top),width=Math.min(rect.right+MARGIN,box2.right)-left,height=Math.min(rect.bottom+MARGIN,box2.bottom)-top;if(width<1||height<1)return null;let shrink=Math.min(1,MAX_OUTPUT/(Math.max(width,height)*scale)),out=document.createElement("canvas");return out.width=Math.round(width*scale*shrink),out.height=Math.round(height*scale*shrink),out.getContext("2d").drawImage(canvas,(left-box2.left)*scale,(top-box2.top)*scale,width*scale,height*scale,0,0,out.width,out.height),out.toDataURL("image/png")}catch{return null}}var showAgents=()=>{},setAgentsHandler=(handler)=>{showAgents=handler},openAgents=()=>showAgents();function noteForm(anchor,targets,extra={},onDone,heading,at=anchor){let shot=capture(anchor);if(at!==anchor&&!extra.rect&&targets.length===1&&anchor.width&&anchor.height)targets=[{...targets[0],point:pointIn(anchor,at)}];let textarea=h("textarea",{rows:3,placeholder:"What should change?","aria-label":"Note"}),where=targets.filter((t)=>t.kind!=="translation"&&t.kind!=="markdown").map((t)=>t.stamp??t.tag).filter(Boolean),close=()=>{element.remove(),onDone?.()},picker=agentPicker(storage("assign-to","")),withShot=h("input",{type:"checkbox",checked:storage("screenshots",!0),"aria-label":"Attach a screenshot",onchange:()=>store("screenshots",withShot.checked)}),button=h("button",{type:"button",className:"primary",onclick:()=>save()},"Save note");picker?.addEventListener("change",()=>store("assign-to",picker.value));let save=async()=>{let comment=textarea.value.trim();if(!comment)return textarea.focus();try{let to=picker?.value||void 0,note=await api("POST","/notes",{url:location.pathname,comment,targets,viewport:`${innerWidth}x${innerHeight}`,to,...extra});close();let chosen=currentAgents().find((agent)=>agent.handle===to);toast(chosen?`Note saved and assigned to ${agentLabel(chosen)}`:"Note saved");let png=withShot.checked?await shot:null;if(png)await api("PUT",`/notes/${note.id}/screenshot`,{png}).catch((error)=>toast(`The screenshot wasn't saved: ${error.message}`,{error:!0}));await load()}catch(error){toast(error.message,{error:!0})}};textarea.addEventListener("keydown",(event)=>{if(event.key==="Enter"&&(event.metaKey||event.ctrlKey))event.preventDefault(),save();if(event.key==="Escape")event.preventDefault(),event.stopPropagation(),close()});let title=heading?heading:extra.rect?`Area, ${targets.length} ${targets.length===1?"element":"elements"}`:targets[0]?.tag??"Note",quoted=!heading&&!extra.rect&&targets[0]?.text?`${title} · "${targets[0].text.slice(0,48)}${targets[0].text.length>48?"…":""}"`:title,element=panel(at,"postit note-form",div("head",div("what",div("title",quoted),div("where",where.slice(0,3).join(", ")+(where.length>3?` and ${where.length-3} more`:""))),h("button",{type:"button",className:"icon-button",onclick:close,"aria-label":"Cancel"},icon("close"))),textarea,div("options",h("label",{className:"shot"},withShot,"Screenshot"),picker?h("label",{className:"to"},"Assign to",picker):noAgent()),div("foot",h("span",{className:"hint"},`${isApple?"⌘↵":"Ctrl+Enter"} saves`),h("button",{type:"button",className:"quiet",onclick:close},"Cancel"),button));return textarea.focus(),element}function pointIn(rect,at){let fraction=(value)=>Math.round(Math.min(Math.max(value,0),1)*1000)/1000;return[fraction((at.x-rect.x)/rect.width),fraction((at.y-rect.y)/rect.height)]}function noAgent(){return h("span",{className:"to"},"Assign to",h("button",{type:"button",className:"link",onclick:openAgents},"no agent connected, connect one"))}function agentPicker(selected){let named=currentAgents().filter((agent)=>agent.handle);if(!named.length)return null;let ordered=[...named.filter((agent)=>agent.listening),...named.filter((agent)=>!agent.listening)],select=h("select",{"aria-label":"Assign to"},h("option",{value:""},"Anyone"),...ordered.map((agent)=>h("option",{value:agent.handle},`${agentLabel(agent)}${agent.listening?"":" (not listening)"}`)));return select.value=ordered.some((agent)=>agent.handle===selected)?selected:"",select}function sourceLines(note){let lines=new Map;for(let target of note.targets){if(!target.file)continue;if(!lines.has(target.file))lines.set(target.file,new Set);if(target.range)lines.get(target.file).add(target.range.split(/[:-]/)[0])}let files=Array.from(lines.keys());if(!files.length)return null;let shortened=files.slice(0,3).map((file)=>{let numbers=Array.from(lines.get(file)).join(", ");return file.split("/").pop()+(numbers?`:${numbers}`:"")});if(files.length>3)shortened.push(`${files.length-3} more`);return h("div",{className:"source",title:files.join(`
|
|
385
385
|
`)},shortened.join(" · "))}var STATUS_LABELS={open:"Open",question:"Question",resolved:"Resolved",declined:"Declined"};function noteCard(note,onChange=()=>{}){let update=(change)=>updateNote(note,change,onChange),remove=()=>{deleteLater(note),onChange()},setStatus=async(status2,said)=>{let before=note.status;if(await update({status:status2}))toast(said,{actions:{Undo:()=>update({status:before})}})},tool=(name,label,onclick,className="")=>h("button",{type:"button",className:`icon-button ${className}`,title:label,"aria-label":label,onclick},icon(name)),comment=h("div",{className:"comment"},note.comment),startEditing=()=>{let field=h("textarea",{rows:3,"aria-label":"Edit note"},note.comment),saveEdit=async()=>{let value=field.value.trim();if(!value)return field.focus();if(value===note.comment)return stopEditing();if(await update({comment:value,status:"open"}))toast("Note updated")},stopEditing=()=>{editing.replaceWith(comment),actions.hidden=!1};field.addEventListener("keydown",(event)=>{if(event.stopPropagation(),event.key==="Enter"&&(event.metaKey||event.ctrlKey))event.preventDefault(),saveEdit();if(event.key==="Escape")event.preventDefault(),stopEditing()});let editing=div("editing",field,div("row",h("button",{type:"button",className:"quiet",onclick:stopEditing},"Cancel"),h("button",{type:"button",className:"primary",onclick:saveEdit},"Save")));comment.replaceWith(editing),actions.hidden=!0,field.focus(),field.setSelectionRange(field.value.length,field.value.length)},here=note.url===location.pathname,done=closed(note),actions=div("tools",done?h("button",{type:"button",className:"reopen",title:"Reopen: back to open, without sending it to an agent","aria-label":"Reopen",onclick:()=>setStatus("open","Note reopened")},"Reopen"):tool("check","Mark as done",()=>setStatus("resolved","Marked as done"),"resolve"),tool("pen","Edit",startEditing),tool("trash","Delete",remove,"delete")),answer=null;if(note.status==="question"||note.thread?.at(-1)?.from==="agent"){let asked=note.status==="question",label=asked?"Answer":"Ask for changes",field=h("textarea",{rows:2,placeholder:asked?"Answer the question":"What should change?","aria-label":label}),send=()=>field.value.trim()&&update({message:field.value.trim(),status:"open"});field.addEventListener("keydown",(event)=>{if(event.stopPropagation(),event.key==="Enter"&&(event.metaKey||event.ctrlKey))event.preventDefault(),send()}),answer=div("answer",field,div("row end",h("button",{type:"button",className:"primary",onclick:send},label)))}let thread=threadView(note),pointAt=(element,at)=>{let rect=documentRect(element),point=at&&rect.width&&rect.height?pointIn(rect,at):note.targets.find((t)=>t.point)?.point,[first,...rest]=targetsFor(element);update({targets:[{...first,point},...rest]}).then((saved)=>saved&&toast("The note points at this element now"))},pickAgain=h("button",{type:"button",className:"link",onclick:()=>{closeNote(),startPick(pointAt)}},"Pick again"),guessed=!done&&here?guessedElement(note):null,missing=done?null:guessed||note.held_at?div("missing",note.held_at?"The source here changed since you wrote this note, so agents wait until you choose its element. ":"The text here changed since you wrote this note. ",here?"Is this still the right element? ":"Open its page to choose. ",guessed?h("button",{type:"button",className:"link",onclick:()=>pointAt(guessed)},"Keep here"):null,guessed?" · ":null,here?pickAgain:null):here&&!anchorFor(note)?div("missing","Not found on this page any more. ",pickAgain):null,status=note.status==="working"?note.stopped?`${note.agent??"Agent"} stopped. Anyone can take it`:`${note.agent??"Agent"} is working`:note.status==="open"?note.agent?`Assigned to ${note.agent}`:"Unassigned":STATUS_LABELS[note.status],owner=currentAgents().find((agent)=>agent.handle&&agentLabel(agent)===note.agent),assignable=note.status==="open"||note.status==="working",picker=assignable?agentPicker(note.status==="open"?owner?.handle??"":""):null,current2=note.status==="open"?owner?.handle??"":null,assignButton=h("button",{type:"button",onclick:async()=>{let chosen=currentAgents().find((agent)=>agent.handle===picker.value),undo=current2===null?void 0:{Undo:()=>update({to:current2})};if(await update({to:picker.value}))toast(chosen?`Note assigned to ${agentLabel(chosen)}`:"Note unassigned: the first session that checks takes it",{actions:undo})}}),syncAssign=()=>{let same=picker?.value===current2;assignButton.disabled=same,assignButton.textContent=same?"Assigned":note.status==="working"?"Reassign":"Assign"};picker?.addEventListener("change",syncAssign),syncAssign();let assignRow=!assignable?null:picker?div("assign",h("label",{className:"to"},"Assign to",picker),assignButton):div("assign",noAgent()),statusLabel=h("span",{},status);return div(`postit note-card ${note.status}`,div("head",h("span",{className:`status ${note.status}`},note.status==="resolved"?icon("check"):null,statusLabel),actions),comment,screenshotView(note),thread,missing,assignRow,answer,sourceLines(note))}function screenshotView(note){if(!note.screenshot)return null;let image=h("img",{alt:"Screenshot",width:note.screenshot.width,height:note.screenshot.height}),url="";return fetch(`${meta().root}/notes/${note.id}/screenshot`,{headers:{"X-Tensaku-Token":meta().token},credentials:"same-origin"}).then((response)=>response.ok?response.blob():null).then((blob)=>{if(blob)image.src=url=URL.createObjectURL(blob)}).catch(()=>{}),h("button",{type:"button",className:"screenshot",title:"Open the screenshot","aria-label":"Open the screenshot",onclick:()=>url&&open(url,"_blank")},image)}var openThreads=new Set;function threadView(note){let entries=note.thread??[];if(!entries.length)return null;let lastAgent=entries.map((entry)=>entry.from).lastIndexOf("agent"),start=openThreads.has(note.id)?0:lastAgent>=0?lastAgent:Math.max(0,entries.length-2),message=(entry)=>div(`message ${entry.from}`,h("span",{className:"who"},entry.from==="you"?"You":entry.agent??"Agent"),h("span",{},entry.text)),view=div("thread"),earlier=start>0?h("button",{type:"button",className:"link earlier",onclick:()=>{openThreads.add(note.id),view.replaceWith(threadView(note))}},`Show ${start} earlier ${start===1?"message":"messages"}`):null;if(earlier)view.append(earlier);return view.append(...entries.slice(start).map(message)),view}var shown=null,shownNote=null;function showNote(note,rect){let onChange=(next)=>{if(!next)shown?.remove()};if(!rect){if(!shown?.isConnected)return;shownNote=note,shown.replaceChildren(noteCard(note,onChange));return}shown?.remove(),shownNote=note,shown=panel(rect,"note-pop",noteCard(note,onChange));let close=(event)=>{if(!event.composedPath().includes(shown))shown?.remove(),document.removeEventListener("pointerdown",close,!0)};setTimeout(()=>document.addEventListener("pointerdown",close,!0))}function closeNote(){if(!shown?.isConnected)return!1;return shown.remove(),!0}onRender(({changed})=>{if(changed){if(shownNote?.id===changed.id)showNote(changed);return}if(!shown?.isConnected||!shownNote)return;let latest=currentNotes().find((note)=>note.id===shownNote.id);if(!latest||JSON.stringify(latest)===JSON.stringify(shownNote))return;let typing=activeInShadow();if(typing?.matches("textarea, input")&&shown.contains(typing)&&typing.value)return;showNote(latest)});var sidebar=null,scope2="page";function toggleSidebar(force){if(!(force??!sidebar?.isConnected)){sidebar?.remove(),setScope(null);return}sidebar??=div("sidebar"),sidebar.setAttribute("role","complementary"),sidebar.setAttribute("aria-label","Tensaku notes"),fixed.append(sidebar),setScope(scope2),renderSidebar()}var sidebarOpen=()=>Boolean(sidebar?.isConnected);onRender(({force})=>{if(!sidebar?.isConnected)return;let typing=activeInShadow();if(force||!(typing?.matches("textarea, input")&&sidebar.contains(typing)))renderSidebar()});async function showScope(next){scope2=next,await setScope(next),renderSidebar()}async function clearDone(done){try{await api("POST","/notes/archive",{ids:done.map((note)=>note.id)}),await load({force:!0}),toast(`Archived ${done.length} done ${done.length===1?"note":"notes"}`)}catch(error){toast(error.message,{error:!0})}}function renderSidebar(){if(!sidebar)return;let format=settings().copyFormat==="short"?"short":void 0,copyAll=async(all)=>{let markdown=await api("GET","/notes.md"+query(all?{format}:{url:location.pathname,format}));await copy(markdown),toast(all?"Copied all open notes":"Copied this page's open notes")},tab=(which,text)=>h("button",{type:"button",role:"tab","aria-selected":String(scope2===which),onclick:()=>showScope(which)},text),card=(note)=>noteCard(note),listed=scope2==="page"?currentNotes():scopedNotes(),grouped=(list)=>scope2==="page"?list.map(card):Array.from(new Set(list.map((note)=>note.url))).flatMap((url)=>[h("a",{className:`page${url===location.pathname?" current":""}`,href:url},url,h("span",{},String(list.filter((note)=>note.url===url).length))),...list.filter((note)=>note.url===url).map(card)]),archive=scope2==="archived",done=archive?[]:listed.filter(closed),body=grouped(archive?listed.slice().reverse():listed.filter((note)=>!closed(note)));if(archive){if(!listed.length)body.push(div("empty","Nothing archived. Archive done moves resolved and declined notes here."))}else if(done.length)body.push(div("section",h("span",{},`Done (${done.length})`),h("button",{type:"button",onclick:()=>clearDone(done)},"Archive done")),...grouped(done));else if(!listed.length)body.push(div("empty",scope2==="page"?"No notes on this page. Select an element or drag over an area to add one.":"No notes yet."));sidebar.replaceChildren(h("header",{},h("strong",{},scope2==="page"?`Notes on ${location.pathname}`:archive?"Archived notes":"Notes on every page"),h("button",{type:"button",className:"icon-button",onclick:()=>toggleSidebar(!1),"aria-label":"Close notes"},icon("close"))),div("tabs",tab("page","This page"),tab("all","All pages"),tab("archived","Archive")),...body,...openNotes()?[sendBar(copyAll)]:[])}function sendBar(copyAll){let names=listeners4(),status=names.length?div("listener on",h("span",{className:"dot"}),names.length===1?`${names[0]} is checking for notes`:`${names.length} agents are checking for notes`):div("listener",h("span",{className:"dot"}),"No agent listening",h("button",{type:"button",className:"link",onclick:openAgents},"Connect one"));return div("copy-bar",div("actions",h("button",{type:"button",onclick:()=>copyAll(!1)},"Copy page"),h("button",{type:"button",onclick:()=>copyAll(!0)},`Copy all (${openNotes()})`)),status)}var SHOWN_AT_ONCE=3,PACE=1200,waiting=[],shownToasts=[],paceTimer=0,whoChanged=(note)=>note.agent??note.thread?.filter((entry)=>entry.from==="agent").pop()?.agent??"The agent";function notify(text,tag){if(document.visibilityState!=="visible"&&settings().notify&&"Notification"in window&&Notification.permission==="granted")new Notification("Tensaku",{body:text,tag})}function announceOne(note,what){let who=whoChanged(note),about=`"${note.comment.length>48?note.comment.slice(0,48)+"…":note.comment}"`,text={resolved:`${who} resolved ${about}`,declined:`${who} declined ${about}`,question:`${who} has a question on ${about}`,message:`${who} replied on ${about}`}[what];return notify(text,`tensaku-${note.id}`),toast(text,{actions:{Show:()=>{let rect=anchorFor(note);if(rect)scrollTo({top:Math.max(0,rect.top-120),behavior:"smooth"}),showNote(note,rect)}}})}function announceSummary(changes){let names=new Set(changes.map((change)=>whoChanged(change.note))),who=names.size===1?Array.from(names)[0]:"Agents",count=(what)=>changes.filter((change)=>change.what===what).length,plural=(n,word)=>`${n} ${word}${n===1?"":"s"}`,parts=[count("resolved")&&`resolved ${plural(count("resolved"),"note")}`,count("declined")&&`declined ${plural(count("declined"),"note")}`,count("question")&&`asked ${plural(count("question"),"question")}`,count("message")&&`replied on ${plural(count("message"),"note")}`].filter(Boolean),text=`${who} ${parts.slice(0,-1).join(", ")}${parts.length>1?" and ":""}${parts[parts.length-1]}`;return notify(text,"tensaku-summary"),toast(text,{timeout:8000,actions:{Show:()=>toggleSidebar(!0)}})}function nextAnnouncement(){if(paceTimer=0,!waiting.length)return;if(shownToasts=shownToasts.filter((element)=>element.isConnected),shownToasts.length<SHOWN_AT_ONCE)if(waiting.length>SHOWN_AT_ONCE)shownToasts.push(announceSummary(waiting.splice(0)));else{let change=waiting.shift();shownToasts.push(announceOne(change.note,change.what))}if(waiting.length)paceTimer=window.setTimeout(nextAnnouncement,PACE)}function announce(note,what){let queued=waiting.findIndex((change)=>change.note.id===note.id);if(queued>=0)waiting.splice(queued,1);if(waiting.push({note,what}),!paceTimer)paceTimer=window.setTimeout(nextAnnouncement)}onChanges((before,after)=>{let old=new Map(before.map((note)=>[note.id,note]));for(let note of after){let previous=old.get(note.id);if(!previous)continue;if(changedHere(note.id))continue;let messages=note.thread?.length??0;if(messages>(previous.thread?.length??0)&¬e.thread[messages-1].from==="agent"&¬e.status===previous.status)announce(note,"message");else if(note.status!==previous.status&¬e.status!=="open"&¬e.status!=="working")announce(note,note.status)}});var siClaude={title:"Claude",slug:"claude",get svg(){return'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Claude</title><path d="'+this.path+'"/></svg>'},path:"m4.7144 15.9555 4.7174-2.6471.079-.2307-.079-.1275h-.2307l-.7893-.0486-2.6956-.0729-2.3375-.0971-2.2646-.1214-.5707-.1215-.5343-.7042.0546-.3522.4797-.3218.686.0608 1.5179.1032 2.2767.1578 1.6514.0972 2.4468.255h.3886l.0546-.1579-.1336-.0971-.1032-.0972L6.973 9.8356l-2.55-1.6879-1.3356-.9714-.7225-.4918-.3643-.4614-.1578-1.0078.6557-.7225.8803.0607.2246.0607.8925.686 1.9064 1.4754 2.4893 1.8336.3643.3035.1457-.1032.0182-.0728-.164-.2733-1.3539-2.4467-1.445-2.4893-.6435-1.032-.17-.6194c-.0607-.255-.1032-.4674-.1032-.7285L6.287.1335 6.6997 0l.9957.1336.419.3642.6192 1.4147 1.0018 2.2282 1.5543 3.0296.4553.8985.2429.8318.091.255h.1579v-.1457l.1275-1.706.2368-2.0947.2307-2.6957.0789-.7589.3764-.9107.7468-.4918.5828.2793.4797.686-.0668.4433-.2853 1.8517-.5586 2.9021-.3643 1.9429h.2125l.2429-.2429.9835-1.3053 1.6514-2.0643.7286-.8196.85-.9046.5464-.4311h1.0321l.759 1.1293-.34 1.1657-1.0625 1.3478-.8804 1.1414-1.2628 1.7-.7893 1.36.0729.1093.1882-.0183 2.8535-.607 1.5421-.2794 1.8396-.3157.8318.3886.091.3946-.3278.8075-1.967.4857-2.3072.4614-3.4364.8136-.0425.0304.0486.0607 1.5482.1457.6618.0364h1.621l3.0175.2247.7892.522.4736.6376-.079.4857-1.2142.6193-1.6393-.3886-3.825-.9107-1.3113-.3279h-.1822v.1093l1.0929 1.0686 2.0035 1.8092 2.5075 2.3314.1275.5768-.3218.4554-.34-.0486-2.2039-1.6575-.85-.7468-1.9246-1.621h-.1275v.17l.4432.6496 2.3436 3.5214.1214 1.0807-.17.3521-.6071.2125-.6679-.1214-1.3721-1.9246L14.38 17.959l-1.1414-1.9428-.1397.079-.674 7.2552-.3156.3703-.7286.2793-.6071-.4614-.3218-.7468.3218-1.4753.3886-1.9246.3157-1.53.2853-1.9004.17-.6314-.0121-.0425-.1397.0182-1.4328 1.9672-2.1796 2.9446-1.7243 1.8456-.4128.164-.7164-.3704.0667-.6618.4008-.5889 2.386-3.0357 1.4389-1.882.929-1.0868-.0062-.1579h-.0546l-6.3385 4.1164-1.1293.1457-.4857-.4554.0608-.7467.2307-.2429 1.9064-1.3114Z",source:"https://claude.ai",hex:"D97757"};var siCline={title:"Cline",slug:"cline",get svg(){return'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Cline</title><path d="'+this.path+'"/></svg>'},path:"m23.365 13.556-1.442-2.895V8.994c0-2.764-2.218-5.002-4.954-5.002h-2.464c.178-.367.276-.779.276-1.213A2.77 2.77 0 0 0 12.018 0a2.77 2.77 0 0 0-2.763 2.779c0 .434.098.846.276 1.213H7.067c-2.736 0-4.954 2.238-4.954 5.002v1.667L.64 13.549c-.149.29-.149.636 0 .927l1.472 2.855v1.667C2.113 21.762 4.33 24 7.067 24h9.902c2.736 0 4.954-2.238 4.954-5.002V17.33l1.44-2.865c.143-.286.143-.622.002-.91m-12.854 2.36a2.27 2.27 0 0 1-2.261 2.273 2.27 2.27 0 0 1-2.261-2.273v-4.042A2.27 2.27 0 0 1 8.249 9.6a2.267 2.267 0 0 1 2.262 2.274zm7.285 0a2.27 2.27 0 0 1-2.26 2.273 2.27 2.27 0 0 1-2.262-2.273v-4.042A2.267 2.267 0 0 1 15.535 9.6a2.267 2.267 0 0 1 2.261 2.274z",source:"https://cline.bot/assets/branding/logos/cline-wordmark-black.svg",hex:"18181B"};var siCursor={title:"Cursor",slug:"cursor",get svg(){return'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Cursor</title><path d="'+this.path+'"/></svg>'},path:"M11.503.131 1.891 5.678a.84.84 0 0 0-.42.726v11.188c0 .3.162.575.42.724l9.609 5.55a1 1 0 0 0 .998 0l9.61-5.55a.84.84 0 0 0 .42-.724V6.404a.84.84 0 0 0-.42-.726L12.497.131a1.01 1.01 0 0 0-.996 0M2.657 6.338h18.55c.263 0 .43.287.297.515L12.23 22.918c-.062.107-.229.064-.229-.06V12.335a.59.59 0 0 0-.295-.51l-9.11-5.257c-.109-.063-.064-.23.061-.23",source:"https://cursor.com/brand",hex:"000000"};var siGithubcopilot={title:"GitHub Copilot",slug:"githubcopilot",get svg(){return'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>GitHub Copilot</title><path d="'+this.path+'"/></svg>'},path:"M23.922 16.997C23.061 18.492 18.063 22.02 12 22.02 5.937 22.02.939 18.492.078 16.997A.641.641 0 0 1 0 16.741v-2.869a.883.883 0 0 1 .053-.22c.372-.935 1.347-2.292 2.605-2.656.167-.429.414-1.055.644-1.517a10.098 10.098 0 0 1-.052-1.086c0-1.331.282-2.499 1.132-3.368.397-.406.89-.717 1.474-.952C7.255 2.937 9.248 1.98 11.978 1.98c2.731 0 4.767.957 6.166 2.093.584.235 1.077.546 1.474.952.85.869 1.132 2.037 1.132 3.368 0 .368-.014.733-.052 1.086.23.462.477 1.088.644 1.517 1.258.364 2.233 1.721 2.605 2.656a.841.841 0 0 1 .053.22v2.869a.641.641 0 0 1-.078.256Zm-11.75-5.992h-.344a4.359 4.359 0 0 1-.355.508c-.77.947-1.918 1.492-3.508 1.492-1.725 0-2.989-.359-3.782-1.259a2.137 2.137 0 0 1-.085-.104L4 11.746v6.585c1.435.779 4.514 2.179 8 2.179 3.486 0 6.565-1.4 8-2.179v-6.585l-.098-.104s-.033.045-.085.104c-.793.9-2.057 1.259-3.782 1.259-1.59 0-2.738-.545-3.508-1.492a4.359 4.359 0 0 1-.355-.508Zm2.328 3.25c.549 0 1 .451 1 1v2c0 .549-.451 1-1 1-.549 0-1-.451-1-1v-2c0-.549.451-1 1-1Zm-5 0c.549 0 1 .451 1 1v2c0 .549-.451 1-1 1-.549 0-1-.451-1-1v-2c0-.549.451-1 1-1Zm3.313-6.185c.136 1.057.403 1.913.878 2.497.442.544 1.134.938 2.344.938 1.573 0 2.292-.337 2.657-.751.384-.435.558-1.15.558-2.361 0-1.14-.243-1.847-.705-2.319-.477-.488-1.319-.862-2.824-1.025-1.487-.161-2.192.138-2.533.529-.269.307-.437.808-.438 1.578v.021c0 .265.021.562.063.893Zm-1.626 0c.042-.331.063-.628.063-.894v-.02c-.001-.77-.169-1.271-.438-1.578-.341-.391-1.046-.69-2.533-.529-1.505.163-2.347.537-2.824 1.025-.462.472-.705 1.179-.705 2.319 0 1.211.175 1.926.558 2.361.365.414 1.084.751 2.657.751 1.21 0 1.902-.394 2.344-.938.475-.584.742-1.44.878-2.497Z",source:"https://primer.style/foundations/icons/copilot-24",hex:"000000",license:{type:"MIT",url:"https://spdx.org/licenses/MIT"}};var siGooglegemini={title:"Google Gemini",slug:"googlegemini",get svg(){return'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Google Gemini</title><path d="'+this.path+'"/></svg>'},path:"M11.04 19.32Q12 21.51 12 24q0-2.49.93-4.68.96-2.19 2.58-3.81t3.81-2.55Q21.51 12 24 12q-2.49 0-4.68-.93a12.3 12.3 0 0 1-3.81-2.58 12.3 12.3 0 0 1-2.58-3.81Q12 2.49 12 0q0 2.49-.96 4.68-.93 2.19-2.55 3.81a12.3 12.3 0 0 1-3.81 2.58Q2.49 12 0 12q2.49 0 4.68.96 2.19.93 3.81 2.55t2.55 3.81",source:"https://gemini.google.com",hex:"8E75B2"};var siOpencode={title:"OpenCode",slug:"opencode",get svg(){return'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>OpenCode</title><path d="'+this.path+'"/></svg>'},path:"M22 24H2V0h20zM17 4.8H7v14.4h10z",source:"https://github.com/anomalyco/opencode/blob/1251a870cb384543c150c4a72fb101b55eec971b/packages/identity/mark.svg",hex:"000000"};var siWindsurf={title:"Windsurf",slug:"windsurf",get svg(){return'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Windsurf</title><path d="'+this.path+'"/></svg>'},path:"M23.55 5.067c-1.2038-.002-2.1806.973-2.1806 2.1765v4.8676c0 .972-.8035 1.7594-1.7597 1.7594-.568 0-1.1352-.286-1.4718-.7659l-4.9713-7.1003c-.4125-.5896-1.0837-.941-1.8103-.941-1.1334 0-2.1533.9635-2.1533 2.153v4.8957c0 .972-.7969 1.7594-1.7596 1.7594-.57 0-1.1363-.286-1.4728-.7658L.4076 5.1598C.2822 4.9798 0 5.0688 0 5.2882v4.2452c0 .2147.0656.4228.1884.599l5.4748 7.8183c.3234.462.8006.8052 1.3509.9298 1.3771.313 2.6446-.747 2.6446-2.0977v-4.893c0-.972.7875-1.7593 1.7596-1.7593h.003a1.798 1.798 0 0 1 1.4718.7658l4.9723 7.0994c.4135.5905 1.05.941 1.8093.941 1.1587 0 2.1515-.9645 2.1515-2.153v-4.8948c0-.972.7875-1.7594 1.7596-1.7594h.194a.22.22 0 0 0 .2204-.2202v-4.622a.22.22 0 0 0-.2203-.2203Z",source:"https://windsurf.com/brand",hex:"0B100F",guidelines:"https://windsurf.com/brand"};var siZedindustries={title:"Zed Industries",slug:"zedindustries",get svg(){return'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Zed Industries</title><path d="'+this.path+'"/></svg>'},path:"M2.25 1.5a.75.75 0 0 0-.75.75v16.5H0V2.25A2.25 2.25 0 0 1 2.25 0h20.095c1.002 0 1.504 1.212.795 1.92L10.764 14.298h3.486V12.75h1.5v1.922a1.125 1.125 0 0 1-1.125 1.125H9.264l-2.578 2.578h11.689V9h1.5v9.375a1.5 1.5 0 0 1-1.5 1.5H5.185L2.562 22.5H21.75a.75.75 0 0 0 .75-.75V5.25H24v16.5A2.25 2.25 0 0 1 21.75 24H1.655C.653 24 .151 22.788.86 22.08L13.19 9.75H9.75v1.5h-1.5V9.375A1.125 1.125 0 0 1 9.375 8.25h5.314l2.625-2.625H5.625V15h-1.5V5.625a1.5 1.5 0 0 1 1.5-1.5h13.19L21.438 1.5z",source:"https://github.com/zed-industries/zed/blob/ccc939124fa2f366b3029926447fd0a0c46a85c7/assets/icons/logo_96.svg",hex:"084CCF"};var CLIENTS=[[/claude/i,siClaude],[/cursor/i,siCursor],[/gemini/i,siGooglegemini],[/opencode/i,siOpencode],[/copilot/i,siGithubcopilot],[/windsurf/i,siWindsurf],[/\bzed\b/i,siZedindustries],[/cline/i,siCline]];function readable(hex){let[r,g,b]=[0,2,4].map((i)=>parseInt(hex.slice(i,i+2),16));return 0.2126*r+0.7152*g+0.0722*b>90}function clientIcon(name){let brand=CLIENTS.find(([pattern])=>pattern.test(name))?.[1];if(!brand)return icon("plane");let svg=document.createElementNS("http://www.w3.org/2000/svg","svg");svg.setAttribute("class","client"),svg.setAttribute("viewBox","0 0 24 24"),svg.setAttribute("aria-hidden","true"),svg.setAttribute("focusable","false");let path=document.createElementNS("http://www.w3.org/2000/svg","path");if(path.setAttribute("d",brand.path),svg.append(path),readable(brand.hex))svg.style.color=`#${brand.hex}`;return svg}var popover=null,popoverTool=null,rendered=()=>[],popoverOpen=(tool)=>tool?popoverTool===tool:Boolean(popover);function closePopover(){popover?.remove(),popover=null,popoverTool?.setAttribute("aria-pressed","false"),popoverTool=null}function togglePopover(tool,dock,render2){let same=popoverTool===tool;if(closePopover(),same)return;rendered=render2,popover=div("popover",...render2()),popover.addEventListener("keydown",(event)=>event.stopPropagation());let rect=dock.getBoundingClientRect();popover.style.right=`${Math.max(12,innerWidth-rect.right)}px`,popover.style.bottom=`${innerHeight-rect.top+12}px`,fixed.append(popover),popoverTool=tool,tool.setAttribute("aria-pressed","true")}function redrawPopover(tool){if(popover&&(!tool||popoverTool===tool))popover.replaceChildren(...rendered())}function closeOutside(event){if(popover&&!event.composedPath().some((node)=>node===popover||node===popoverTool))closePopover()}var ago=(date)=>{let seconds=Math.round((Date.now()-date.getTime())/1000);return seconds<60?"just now":seconds<3600?`${Math.round(seconds/60)} min ago`:`${Math.round(seconds/3600)} h ago`};var PROMPTS={watch:"Watch my Tensaku notes",once:"Do my Tensaku notes",install:"bin/rails generate tensaku:install",channel:"claude --dangerously-load-development-channels server:tensaku"};function copyRow(text,done){return div("command",h("code",{},text),h("button",{type:"button",className:"icon-button",title:"Copy","aria-label":`Copy ${text}`,onclick:async()=>{await copy(text),toast(done)}},icon("copy")))}var DID={start_note:"started",resolve_note:"resolved",decline_note:"declined",ask_question:"asked on",reply_to_note:"replied on",get_note:"read",list_notes:"listed the notes",watch_notes:"checked for notes",current_selection:"read the selection"};function lastAction(agent){if(agent.working.length)return agent.working.map((note)=>h("a",{className:"doing",href:note.url,title:`“${note.comment}”`},`Working on ${note.id}: “${note.comment}”`));let last=agent.last,did=last?`${DID[last.tool]??last.tool}${last.note?` ${last.note}`:""} ${ago(new Date(last.at))}`:null,waiting2=agent.channel?"Live: notes reach its chat as you save them":"Waiting for your notes",text=agent.listening?`${waiting2}${did?` · ${did}`:""}`:did?`Last ${did}`:"No calls yet";return[h("span",{className:"doing"},text)]}function agentRow(agent){return div(`agent${agent.listening?" listening":""}${agent.channel?" live":""}${agent.working.length?" working":""}`,div("who",h("strong",{},clientIcon(agent.name),agentLabel(agent)),h("span",{className:"where"},agent.folder??"")),agent.outdated?div("outdated","Runs older Tensaku code. Reconnect it (/mcp in Claude Code) or restart it."):null,...lastAction(agent))}var idleOpen=!1;function renderAgents(){let agents2=currentAgents(),listening=agents2.filter((agent)=>agent.listening),idle=agents2.filter((agent)=>!agent.listening),ask=(lead)=>[h("p",{},lead),copyRow(PROMPTS.watch,"Copied. Paste it into your agent's chat."),h("p",{className:"where"},"It waits for notes and takes each one as you save it."),copyRow(PROMPTS.once,"Copied. Paste it into your agent's chat."),h("p",{className:"where"},"It works through the open notes, then stops."),h("p",{},h("strong",{},"Claude Code, without asking: "),"start it with Tensaku as a channel, and each note you save starts it working. Experimental, and it asks you to confirm at start:"),copyRow(PROMPTS.channel,"Copied. Run it in the app's folder.")],rest=listening.length&&idle.length?[h("button",{type:"button",className:"idle-toggle","aria-expanded":String(idleOpen),onclick:()=>{idleOpen=!idleOpen,redrawPopover()}},`${idle.length} more connected, not listening`),...idleOpen?idle.map(agentRow):[]]:idle.map(agentRow);return[h("h3",{},"Agents"),...agents2.length?[...listening.map(agentRow),...rest,...listening.length?[]:[div("connect",...ask("None is listening. Agents read notes when you ask them to, so say this in your agent's chat:"))]]:[div("empty","No agent connected."),div("connect",h("p",{},h("strong",{},"Set up once per project. "),"Run this in the app, then restart your agent. It adds Tensaku to Claude Code, Codex, Cursor, Gemini CLI and OpenCode:"),copyRow(PROMPTS.install,"Copied. Run it in the app, then restart your agent."),h("p",{className:"where"},"Already set up? Start your agent in this project and it shows here. In Claude Code, /mcp reconnects it."),...ask("Then say this in your agent's chat:"))]]}var CONTEXT=26,MAX_LINES=3;function sharedEnds(before,after){let prefix=0;while(prefix<before.length&&before[prefix]===after[prefix])prefix++;let suffix=0;while(suffix<before.length-prefix&&suffix<after.length-prefix&&before[before.length-1-suffix]===after[after.length-1-suffix])suffix++;while(prefix>0&&/\w/.test(before[prefix-1]))prefix--;while(suffix>0&&/\w/.test(before[before.length-suffix]))suffix--;return{prefix,suffix}}function row(sign,line,{prefix,suffix}){let end=line.length-suffix,head=prefix>CONTEXT?`…${line.slice(prefix-CONTEXT,prefix).replace(/^\S*\s/,"")}`:line.slice(0,prefix).trimStart(),tail=suffix>CONTEXT?`${line.slice(end,end+CONTEXT).replace(/\s\S*$/,"")}…`:line.slice(end);return div(`diff-row ${sign==="-"?"removed":"added"}`,h("span",{className:"diff-sign"},sign),head,h("mark",{},line.slice(prefix,end)),tail)}function diffRows({removed,added}){let count=Math.max(removed.length,added.length),rows=[];for(let index=0;index<Math.min(count,MAX_LINES);index++){let ends=sharedEnds(removed[index]??"",added[index]??"");if(removed[index]!==void 0)rows.push(row("-",removed[index],ends));if(added[index]!==void 0)rows.push(row("+",added[index],ends))}if(count>MAX_LINES)rows.push(div("diff-more",`${count-MAX_LINES} more ${count-MAX_LINES===1?"line":"lines"} changed`));return div("diff",...rows)}var INTERPOLATION=/(%\{[^}]+\})/;function finish(result,kind,verb,actions){if(!result.changed)return;let where=result.diff?`${result.file}:${result.diff.line}`:result.file??"";if(toast(`${verb} ${where}`.trim(),{timeout:result.diff?8000:void 0,detail:result.diff?diffRows(result.diff):void 0,actions}),result.warning)toast(result.warning,{timeout:8000});refresh(kind)}function report(error){let message=error instanceof Error?error.message:String(error);toast(message,{error:!0,actions:error instanceof ApiError&&error.stale?{Reload:()=>location.reload()}:void 0})}function rangeAfter(range,text){let[,path,startLine,startColumn]=range.match(/^(.+):(\d+):(\d+)-/),lines=text.split(`
|
|
386
|
-
`),endLine=Number(startLine)+lines.length-1,endColumn=(lines.length===1?Number(startColumn)-1:0)+utf8Length(lines[lines.length-1]);return`${path}:${startLine}:${startColumn}-${endLine}:${endColumn}`}var textNodesOf2=(stamp)=>Array.from(document.querySelectorAll(`[${STAMP}="${CSS.escape(stamp)}"]`)).flatMap((el)=>Array.from(el.childNodes).filter((node)=>node.nodeType===Node.TEXT_NODE));function showTranslation(key,from,to){if(INTERPOLATION.test(from))return;replaceText(nodesForKey(key),from,to),elementsWithAttributeKey(key).forEach(({element:el,name})=>{if(el.getAttribute(name)===from)el.setAttribute(name,to)})}var HISTORY_LIMIT=50,HISTORY_KEY="tensaku:history",done=[],undone=[];try{let saved=JSON.parse(sessionStorage.getItem(HISTORY_KEY)??"null");if(saved&&Array.isArray(saved.done)&&Array.isArray(saved.undone))({done,undone}=saved)}catch{}function persist(){try{sessionStorage.setItem(HISTORY_KEY,JSON.stringify({done,undone}))}catch{}}var nextId=()=>Math.max(0,...done.map((entry)=>entry.id),...undone.map((entry)=>entry.id))+1;function record(element,label,op,file){let entry={id:nextId(),label,key:element?undoKey(element):null,file,at:new Date().toISOString(),op};if(done.push(entry),done.length>HISTORY_LIMIT)done.shift();return undone=[],persist(),entry}function editHistory(){return{done:done.slice().reverse(),undone:undone.slice().reverse()}}var canUndo=()=>done.length>0,canRedo=()=>undone.length>0;async function undo(entry=done[done.length-1]){if(!entry||!done.includes(entry))return toast("That edit was undone already.");try{let result=await apply(entry.op,!0);done=done.filter((item)=>item!==entry),undone.push(entry),persist(),finish(result,sourceKind(entry.op),`Undid ${entry.label}`,{Redo:()=>redo(entry)})}catch(error){report(error)}}async function redo(entry=undone[undone.length-1]){if(!entry||undone[undone.length-1]!==entry)return toast("Only the latest undone edit can be redone.");try{let result=await apply(entry.op,!1);undone.pop(),done.push(entry),persist(),finish(result,sourceKind(entry.op),`Redid ${entry.label}`,{Undo:()=>undo(entry)})}catch(error){report(error)}}var sourceKind=(op)=>op.kind==="attribute"?"template":op.kind;function undoFor(element){let key=undoKey(element);return key?done.slice().reverse().find((entry)=>entry.key===key):void 0}async function apply(op,reverse){let verb=reverse?"undone":"redone",stale=(what)=>new ApiError(`The ${what} changed since the edit, so it can't be ${verb} here.`,409,!0);if(op.kind==="template"){let texts=(await api("GET","/source"+query({stamp:op.stamp}))).pieces.filter((p)=>p.kind==="text"),edits=op.changes.map(({index,from,to})=>{let[current3,target2]=reverse?[to,from]:[from,to],now=texts[index];if(!now||now.text!==current3)throw stale("text");return{piece:now,current:current3,target:target2}}),result2=await api("POST","/text",{stamp:op.stamp,edits:edits.map(({piece,target:target2})=>({start:piece.start,end:piece.end,original:piece.raw,text:target2}))}),nodes=textNodesOf2(op.stamp);return edits.forEach(({current:current3,target:target2})=>replaceText(nodes,current3,target2)),result2}if(op.kind==="attribute"){let result2={};for(let{name,index,from,to}of op.changes){let[current3,target2]=reverse?[to,from]:[from,to],now=(await api("GET","/source"+query({stamp:op.stamp}))).attributes.find((a)=>a.name===name)?.pieces.filter((p)=>p.kind==="text")[index];if(!now||now.text!==current3)throw stale("attribute");result2=await api("POST","/attribute",{stamp:op.stamp,name,start:now.start,end:now.end,original:now.raw,text:target2}),document.querySelectorAll(`[${STAMP}="${CSS.escape(op.stamp)}"]`).forEach((el)=>{let value=el.getAttribute(name);if(value!==null)el.setAttribute(name,value.replace(current3,target2))})}return{...result2,changed:!0}}if(op.kind==="translation"){let result2={};for(let{locale,from,to}of op.changes){let[current3,target2]=reverse?[to,from]:[from,to],saved=await api("POST","/translation",{locale,key:op.key,original:current3,text:target2});result2={...saved,file:result2.file??saved.file,changed:!0},showTranslation({locale,key:op.key},current3,target2)}return result2}let[current2,target]=reverse?[op.to,op.from]:[op.from,op.to],result=await api("POST","/markdown",{range:op.range,original:op.prefix+current2,text:target,tag:op.tag});return op.range=rangeAfter(op.range,op.prefix+target),result}function undoKey(element){let translation=translationOf(element);return element.getAttribute(STAMP)??element.getAttribute(MARKDOWN)??(translation?`${translation.locale}.${translation.key}`:null)}var UNDO_KEYS=isApple?"⌘Z and ⇧⌘Z":"Ctrl+Z and Ctrl+Y";function renderHistory(){let{done:done2,undone:undone2}=editHistory(),row2=(entry,action)=>div(`entry${undone2.includes(entry)?" undone":""}`,div("what",h("span",{},entry.label),h("span",{className:"where"},`${entry.file??""} · ${ago(new Date(entry.at))}`)),action),button=(text,run)=>h("button",{type:"button",onclick:async()=>{await run(),closePopover()}},text);return[h("h3",{},"Edit history",h("span",{className:"where"},`Saves in this tab. ${UNDO_KEYS} undo and redo.`)),...done2.length||undone2.length?[...done2.map((entry)=>row2(entry,button("Undo",()=>undo(entry)))),...undone2.map((entry,i)=>row2(entry,i===0?button("Redo",()=>redo(entry)):h("span",{className:"where"},"undone")))]:[div("empty","No edits yet.")]]}var current2="off",listeners5=[],mode=()=>current2,onMode=(listener)=>listeners5.push(listener);function setMode(next){current2=next,listeners5.forEach((listener)=>listener(next))}var paused=null;function togglePause(){if(paused)return paused.style.remove(),paused.animations.forEach((animation)=>{try{animation.play()}catch{}}),paused.media.forEach((media2)=>media2.play().catch(()=>{})),paused=null,!1;let animations=document.getAnimations().filter((animation)=>{let target=animation.effect?.target;return animation.playState==="running"&&!(target&&isUi(target))});animations.forEach((animation)=>animation.pause());let media=Array.from(document.querySelectorAll("video, audio")).filter((element)=>!element.paused);media.forEach((element)=>element.pause());let style=document.createElement("style");return style.setAttribute("data-tensaku-pause",""),style.textContent="*, *::before, *::after { animation-play-state: paused !important; transition: none !important; }",document.head.append(style),paused={animations,media,style},!0}var supported=typeof host.showPopover==="function";if(supported)host.popover="manual";var opened=[],raisedOver=null,scope3=null,listeners6=[],modalScope=()=>scope3,outsideScope=(element)=>Boolean(scope3&&!scope3.contains(element)),onScopeChange=(listener)=>{listeners6.push(listener)};function openNow(){try{return Array.from(document.querySelectorAll("dialog:modal, :popover-open")).filter((element)=>element!==host)}catch{return[]}}var last=(elements,test)=>[...elements].reverse().find(test),holdsHost=(element)=>element.matches("dialog:modal")||["auto","hint"].includes(element.popover??"");function sync(closing){if(!supported){if(!host.isConnected)document.documentElement.append(host);return}let now=openNow().filter((element)=>element!==closing);opened=[...opened.filter((element)=>now.includes(element)),...now.filter((element)=>!opened.includes(element))];let container=last(opened,holdsHost)??document.documentElement;if(host.parentNode!==container)container.append(host);let top=opened.at(-1)??null,raised=host.matches(":popover-open");if(!top){if(raised)host.hidePopover()}else if(!raised||top!==raisedOver){if(raised)host.hidePopover();host.showPopover()}raisedOver=top;let modal=last(opened,(element)=>element.matches("dialog:modal"))??null;if(modal!==scope3)scope3=modal,listeners6.forEach((listener)=>listener())}function watchTopLayer(){sync(),new MutationObserver((records)=>{if(records.some((record2)=>record2.type==="attributes")||!host.isConnected||opened.some((element)=>!element.isConnected))sync()}).observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["open"]}),document.addEventListener("toggle",(event)=>{if(event.target!==host)sync()},!0),document.addEventListener("beforetoggle",(event)=>{let target=event.target;if(target!==host&&event.newState==="closed"&&target.contains(host))sync(target)},!0)}var pinLayer=div("pins");layer.append(pinLayer);function setPinsHidden(hidden){pinLayer.hidden=hidden}var drawn=new Map;onRender(({first})=>{if(first)currentNotes().forEach((note)=>drawn.set(note.id,note.status));drawPins()});var asked=new Map;onRefresh(()=>asked.clear());function syncHold(note,guessed){if(note.status!=="open"||note.url!==location.pathname)return;if(Boolean(note.held_at)===guessed||asked.get(note.id)===guessed)return;asked.set(note.id,guessed),api("PATCH",`/notes/${note.id}`,{held:guessed}).then(()=>load({force:!0})).catch(()=>{})}function drawPins(){pinLayer.replaceChildren();let scope4=modalScope();currentNotes().forEach((note,index)=>{if(scope4&&!scope4.contains(noteElement(note)))return;let guessed=!closed(note)&&Boolean(guessedElement(note));syncHold(note,guessed);let phrase=phraseRects(note);for(let r of phrase){let mark=div(`phrase ${note.status}`);Object.assign(mark.style,{left:`${r.left}px`,top:`${r.top}px`,width:`${r.width}px`,height:`${r.height}px`}),pinLayer.append(mark)}let point=phrase.length?null:pointFor(note),rect=phrase.length?phrase[phrase.length-1]:point??anchorFor(note);if(!rect)return;let fresh=drawn.get(note.id)!==note.status;drawn.set(note.id,note.status);let pin=h("button",{className:`pin ${note.status}${fresh?" fresh":""}${guessed||note.held_at&&!closed(note)?" unsure":""}`,title:note.comment,"aria-label":`Note ${index+1}: ${note.comment}`,"data-note":note.id},note.status==="resolved"?icon("check"):note.status==="declined"?icon("close"):String(index+1));Object.assign(pin.style,{left:`${point?point.x:rect.right}px`,top:`${rect.top}px`}),pin.addEventListener("click",(event)=>{event.stopPropagation(),showNote(note,rect)}),pinLayer.append(pin)})}var SHORTCUT_TOOLS={select:"Select",edit:"Edit",notes:"Notes",agents:"Agents",pins:"Hide or show pins",clear:"Delete this page's notes",pause:"Pause animations",history:"Edit history",settings:"Settings"},DEFAULTS2={select:"alt+shift+KeyT",edit:"alt+shift+KeyE",notes:"alt+shift+KeyN"};function shortcutFor(tool){let own=settings().shortcuts;return tool in own?own[tool]:DEFAULTS2[tool]??null}var isDefault=(tool)=>!(tool in settings().shortcuts);function setShortcut(tool,keys){let shortcuts={...settings().shortcuts},taken=keys?toolFor(keys):null;if(taken&&taken!==tool)shortcuts[taken]=null;if(keys===(DEFAULTS2[tool]??null))delete shortcuts[tool];else shortcuts[tool]=keys;return changeSettings({shortcuts}),taken&&taken!==tool?taken:null}var resetShortcuts=()=>changeSettings({shortcuts:{}});function toolFor(keys){return Object.keys(SHORTCUT_TOOLS).find((tool)=>shortcutFor(tool)===keys)??null}function toolForEvent(event){return event.code?toolFor(keysOf(event)):null}function keysOf(event){return[...[event.ctrlKey&&"ctrl",event.altKey&&"alt",event.shiftKey&&"shift",event.metaKey&&"meta"].filter(Boolean),event.code].join("+")}var isModifierKey=(event)=>["Alt","Shift","Control","Meta"].includes(event.key),hasCommandModifier=(event)=>event.altKey||event.ctrlKey||event.metaKey,APPLE_KEYS={alt:"⌥",shift:"⇧",ctrl:"⌃",meta:"⌘"},OTHER_KEYS={alt:"Alt",shift:"Shift",ctrl:"Ctrl",meta:"Meta"};function keysLabel(keys){let parts=keys.split("+"),key=parts.pop().replace(/^(Key|Digit)/,""),names=isApple?APPLE_KEYS:OTHER_KEYS;return[...parts.map((part)=>names[part]??part),key].join(isApple?"":"+")}var panel2=null,recording=null,hooks={toggled:()=>{},moveDockHome:()=>{}},setSettingsHooks=(given)=>{hooks=given},settingsOpen=()=>Boolean(panel2?.isConnected);function toggleSettings(force){let show=force??!settingsOpen();if(stopRecording(),!show){panel2?.remove(),hooks.toggled();return}panel2??=div("sidebar settings"),panel2.setAttribute("role","complementary"),panel2.setAttribute("aria-label","Tensaku settings"),fixed.append(panel2),render2(),hooks.toggled()}function render2(){if(!panel2)return;let prefs=settings(),choice=(value,text)=>h("button",{type:"button","aria-pressed":String(prefs.copyFormat===value),onclick:()=>{changeSettings({copyFormat:value}),render2()}},text),notify2=h("input",{type:"checkbox",checked:prefs.notify});notify2.addEventListener("change",async()=>{let on=notify2.checked;if(on&&"Notification"in window&&Notification.permission==="default")await Notification.requestPermission();let allowed="Notification"in window&&Notification.permission==="granted";if(on&&!allowed)toast("The browser blocked notifications for this site.",{error:!0});changeSettings({notify:on&&allowed}),render2()});let customized=Object.keys(SHORTCUT_TOOLS).some((tool)=>!isDefault(tool));panel2.replaceChildren(h("header",{},h("strong",{},"Settings"),h("button",{type:"button",className:"icon-button",onclick:()=>toggleSettings(!1),"aria-label":"Close settings"},icon("close"))),h("section",{},h("h4",{},"Notes"),div("setting",h("span",{},"Copy notes as"),div("segmented",choice("detailed","Detailed"),choice("short","One line each"))),h("label",{className:"check"},notify2,h("span",{},"Notify me",h("span",{className:"where"},"When an agent answers while this tab is in the background.")))),h("section",{},h("h4",{},"Keyboard shortcuts",customized?h("button",{type:"button",className:"link",onclick:()=>{resetShortcuts(),render2()}},"Reset all"):null),h("p",{className:"where"},"Click a shortcut and press the new keys, with Alt, Ctrl or Cmd. Escape cancels."),...Object.entries(SHORTCUT_TOOLS).map(([tool,name])=>shortcutRow(tool,name)),h("h5",{},"Always on"),...fixedShortcuts().map(([keys,what])=>div("shortcut always",h("span",{},what),h("kbd",{},keys)))),h("section",{},h("h4",{},"Toolbar"),div("setting",h("button",{type:"button",onclick:()=>hooks.moveDockHome()},"Move the toolbar back to the corner"))))}function shortcutRow(tool,name){let keys=shortcutFor(tool),waiting2=recording===tool,record2=h("button",{type:"button",className:`keys${waiting2?" recording":""}`,"aria-label":`Change the shortcut for ${name}`,onclick:()=>startRecording(tool)},waiting2?"Press keys…":keys?h("kbd",{},keysLabel(keys)):h("span",{className:"none"},"None")),clear=keys&&!waiting2?h("button",{type:"button",className:"icon-button","aria-label":`Remove the shortcut for ${name}`,onclick:()=>{setShortcut(tool,null),render2()}},icon("close")):null;return div(`shortcut${isDefault(tool)?"":" changed"}`,h("span",{},name),record2,clear)}function startRecording(tool){stopRecording(),recording=tool,addEventListener("keydown",onRecordKey,!0),render2()}function stopRecording(){recording=null,removeEventListener("keydown",onRecordKey,!0)}function onRecordKey(event){if(!recording||!settingsOpen()){stopRecording();return}if(isModifierKey(event))return;event.preventDefault(),event.stopImmediatePropagation();let tool=recording;if(stopRecording(),event.key==="Escape"){render2();return}if(!hasCommandModifier(event)){toast("Use Alt, Ctrl or Cmd with the key, so typing never triggers it.",{error:!0}),render2();return}let keys=keysOf(event),moved=setShortcut(tool,keys);if(moved)toast(`${keysLabel(keys)} no longer does ${SHORTCUT_TOOLS[moved]}.`);render2()}function fixedShortcuts(){let click=(keys)=>isApple?`${keys} click`:`${keys}+click`,alt=isApple?"⌥":"Alt",shift=isApple?"⇧":"Shift";return[[click(alt),"Menu for an element"],[click(isApple?alt+shift:`${alt}+${shift}`),"Note on an element"],[click(shift),"Pick several elements, in select mode"],["N","Note the picked elements"],["Esc","Close a menu or panel, or leave the mode"]]}var INK={highlighter:"#ffe14d",pen:"#e0344f",pad:"#fff1a1"},count=h("span",{className:"count",hidden:!0}),corner=h("button",{className:"corner",type:"button",title:"Tensaku","aria-label":"Tensaku","aria-expanded":"false"},logo(),count);function tool(name,ink,text){let tip=h("span",{className:"tip","aria-hidden":"true"},text),button=h("button",{type:"button",className:"tool","aria-pressed":"false","aria-label":text},icon(name,ink),tip);return button.style.setProperty("--ink-color",ink),button}function action(name,text){return h("button",{type:"button",className:"tool","aria-label":text},icon(name),h("span",{className:"tip","aria-hidden":"true"},text))}function setTip(button,text){button.setAttribute("aria-label",text),button.querySelector(".tip").firstChild.textContent=text}var setIcon=(button,name,ink)=>button.replaceChild(icon(name,ink),button.querySelector("svg")),selectTool=tool("highlighter",INK.highlighter,"Select"),editTool=tool("pen",INK.pen,"Edit"),notesTool=tool("pad",INK.pad,"Notes"),notesBadge=h("span",{className:"badge",hidden:!0});notesTool.append(notesBadge);var pinsTool=action("eye","Hide pins"),pauseTool=action("pause","Pause animations"),clearTool=action("trash","Delete this page's notes"),historyTool=action("history","Edit history"),settingsTool=action("sliders","Settings"),agentsTool=action("plane","No agent connected");agentsTool.classList.add("agents");var agentsBadge=h("span",{className:"badge",hidden:!0});agentsTool.append(agentsBadge);var tools=div("tools",selectTool,editTool,div("sep"),notesTool,agentsTool,pinsTool,clearTool,div("sep"),pauseTool,historyTool,settingsTool),toolbar=div("toolbar",tools);new ResizeObserver(()=>toolbar.style.setProperty("--tools-width",`${tools.offsetWidth}px`)).observe(tools);var dock=div("dock",toolbar,corner);fixed.append(dock);var shortcutButtons={select:selectTool,edit:editTool,notes:notesTool,agents:agentsTool,pins:pinsTool,clear:clearTool,pause:pauseTool,history:historyTool,settings:settingsTool};onSettings(()=>{for(let[name,button]of Object.entries(shortcutButtons)){let keys=shortcutFor(name),tip=button.querySelector(".tip");if(tip.querySelector("kbd")?.remove(),keys)tip.append(h("kbd",{},keysLabel(keys)))}});function pressShortcut(name){setToolbar(!0),shortcutButtons[name].click()}var toolbarOpen=()=>dock.classList.contains("open"),settling=0;function setToolbar(open2){if(open2===toolbarOpen())return;if(dock.classList.toggle("open",open2),corner.setAttribute("aria-expanded",String(open2)),clearTimeout(settling),dock.classList.remove("settled"),open2)settling=window.setTimeout(()=>dock.classList.add("settled"),280)}function moveDock(right,bottom){dock.style.right=`${right}px`,dock.style.bottom=`${bottom}px`,dock.style.setProperty("--dock-right",`${right}px`)}function placeDock(){let position=storage("dock",{right:16,bottom:16});moveDock(Math.min(Math.max(position.right,4),innerWidth-52),Math.min(Math.max(position.bottom,4),innerHeight-52))}var dragged=!1;corner.addEventListener("pointerdown",(event)=>{let start={x:event.clientX,y:event.clientY,right:parseFloat(dock.style.right),bottom:parseFloat(dock.style.bottom)};dragged=!1,corner.setPointerCapture(event.pointerId);let move=(e)=>{let dx=e.clientX-start.x,dy=e.clientY-start.y;if(!dragged&&Math.hypot(dx,dy)<4)return;dragged=!0,corner.style.cursor="grabbing",moveDock(start.right-dx,start.bottom-dy)},up=()=>{if(corner.removeEventListener("pointermove",move),corner.removeEventListener("pointerup",up),corner.removeEventListener("pointercancel",up),corner.style.cursor="",dragged)store("dock",{right:parseFloat(dock.style.right),bottom:parseFloat(dock.style.bottom)})};corner.addEventListener("pointermove",move),corner.addEventListener("pointerup",up),corner.addEventListener("pointercancel",up)});corner.addEventListener("click",()=>{if(dragged)return;if(setToolbar(!toolbarOpen()),toolbarOpen())return;toggleSidebar(!1),toggleSettings(!1),setMode("off")});function closeToolbar(){if(!toolbarOpen())return!1;return setToolbar(!1),!0}function syncButtons(){selectTool.setAttribute("aria-pressed",String(mode()==="inspect")),editTool.setAttribute("aria-pressed",String(mode()==="edit")),notesTool.setAttribute("aria-pressed",String(sidebarOpen())),settingsTool.setAttribute("aria-pressed",String(settingsOpen())),corner.classList.toggle("active",mode()!=="off")}onMode((next)=>{if(next!=="off")setToolbar(!0);syncButtons()});function closeSidePanel(){if(settingsOpen())return toggleSettings(!1),!0;if(!sidebarOpen())return!1;return toggleSidebar(!1),syncButtons(),!0}selectTool.addEventListener("click",()=>setMode(mode()==="inspect"?"off":"inspect"));editTool.addEventListener("click",()=>setMode(mode()==="edit"?"off":"edit"));notesTool.addEventListener("click",()=>{toggleSettings(!1),toggleSidebar(),syncButtons()});onCount((n)=>{count.hidden=n===0,count.textContent=String(n),notesBadge.hidden=n===0,notesBadge.textContent=String(n),setTip(notesTool,n?`Notes (${n})`:"Notes")});setSettingsHooks({toggled:syncButtons,moveDockHome:()=>{store("dock",{right:16,bottom:16}),placeDock()}});settingsTool.addEventListener("click",()=>{if(closePopover(),!settingsOpen())toggleSidebar(!1);toggleSettings()});historyTool.addEventListener("click",()=>togglePopover(historyTool,dock,renderHistory));var pinsHidden=storage("pinsHidden",!1);function syncPins(){setPinsHidden(pinsHidden),pinsTool.setAttribute("aria-pressed",String(pinsHidden)),setIcon(pinsTool,pinsHidden?"eye-off":"eye"),setTip(pinsTool,pinsHidden?"Show pins":"Hide pins")}pinsTool.addEventListener("click",()=>{pinsHidden=!pinsHidden,store("pinsHidden",pinsHidden),syncPins()});pauseTool.addEventListener("click",()=>{let paused2=togglePause();pauseTool.setAttribute("aria-pressed",String(paused2)),setIcon(pauseTool,paused2?"play":"pause"),setTip(pauseTool,paused2?"Resume animations":"Pause animations")});var confirmClear=0;clearTool.addEventListener("click",async()=>{let total=currentNotes().length;if(!total){toast("No notes on this page");return}if(!confirmClear){clearTool.classList.add("confirm"),setTip(clearTool,`Delete ${total} ${total===1?"note":"notes"}? Click again`),confirmClear=window.setTimeout(resetClear,3000);return}resetClear();try{await deleteNotes(currentNotes()),toast(`Deleted ${total} ${total===1?"note":"notes"}`)}catch(error){toast(error.message,{error:!0})}});function resetClear(){clearTimeout(confirmClear),confirmClear=0,clearTool.classList.remove("confirm"),setTip(clearTool,"Delete this page's notes")}var names=(list)=>list.map(agentLabel).join(", "),agentsSignature="[]";onAgents((agents2)=>{let signature=JSON.stringify(agents2);if(signature===agentsSignature)return;agentsSignature=signature;let listening=agents2.filter((agent)=>agent.listening);agentsTool.classList.toggle("connected",agents2.length>0),agentsTool.classList.toggle("listening",listening.length>0),setIcon(agentsTool,listening.length?"plane-flying":"plane",listening.length?"#2fa872":void 0),agentsBadge.hidden=agents2.length<2,agentsBadge.textContent=String(agents2.length),setTip(agentsTool,listening.length?`${names(listening)} listening`:agents2.length?`${names(agents2)} connected`:"No agent connected"),redrawPopover(agentsTool)});agentsTool.addEventListener("click",()=>togglePopover(agentsTool,dock,renderAgents));setAgentsHandler(()=>{if(setToolbar(!0),!popoverOpen(agentsTool))togglePopover(agentsTool,dock,renderAgents)});var open2=null,composing=(event)=>event.isComposing||event.keyCode===229;function isEditing(){return open2!==null}function closeEditor(){open2?.close()}async function edit(element,kind=editKind(element)){closeEditor();try{if(kind==="translation")await editTranslation(element,translationOf(element));else if(kind==="markdown")await editMarkdown(element);else if(kind==="template")await editTemplate(element);else if(kind==="attributes")await editAttributes(element);else toast("This text comes from Ruby, so it can't be edited here. Leave a note instead.")}catch(error){report(error)}}var normal=(text)=>text.replace(/\s+/g," ").trim();function assertRendered(element,texts){let rendered2=normal(element.textContent??""),from=0;for(let text of texts.map(normal).filter(Boolean)){let at=rendered2.indexOf(text,from);if(at<0)throw new ApiError("The file changed since the page was rendered. Reload the page and try again.",409,!0);from=at+text.length}}function field(text,multiline=!1){let span=h("span",{className:"editable",spellcheck:"true"},text);if(span.contentEditable="plaintext-only",span.contentEditable!=="plaintext-only")span.contentEditable="true";if(span.dataset.original=text,span.addEventListener("paste",(event)=>{event.preventDefault(),document.execCommand("insertText",!1,event.clipboardData?.getData("text/plain")??"")}),!multiline)span.addEventListener("keydown",(event)=>{if(event.key==="Enter"&&event.shiftKey&&!composing(event))event.preventDefault()});return span}var valueOf=(span)=>(span.innerText??span.textContent??"").replace(/ /g," ").replace(/\n$/,"");function chip(label,title){return h("span",{className:"chip",title,contenteditable:"false"},label)}function backgroundOf(element){for(let node=element;node;node=node.parentElement){let color=getComputedStyle(node).backgroundColor,alpha=color.match(/rgba?\([^)]*,\s*([\d.]+)\)/)?.[1];if(color!=="transparent"&&(alpha===void 0||Number(alpha)>0.6))return color}return"#fff"}var INSET={x:11.5,y:9.5};function frame(element,surface,info,save,extra=[],warning){let rect=contentRect(element),computed=getComputedStyle(element);Object.assign(surface.style,{fontFamily:computed.fontFamily,fontSize:computed.fontSize,fontWeight:computed.fontWeight,lineHeight:computed.lineHeight,letterSpacing:computed.letterSpacing,textAlign:computed.textAlign,color:computed.color}),surface.classList.add("surface");let status=h("span",{},info),close=()=>{container.remove(),open2=null,document.removeEventListener("keydown",keys,!0)},saveAndClose=async()=>{if(container.dataset.saving)return;container.dataset.saving="1",status.textContent="Saving…";try{await save(),close()}catch(error){delete container.dataset.saving,status.textContent=info,report(error)}},bar=div("bar",h("span",{},status,warning?h("strong",{className:"ink-warning"},` · ${warning}`):null),div("actions",h("button",{onclick:close,type:"button"},"Cancel"),h("button",{className:"primary",onclick:saveAndClose,type:"button"},"Save"))),container=div("panel editor",surface,...extra,bar);container.setAttribute("role","dialog"),container.setAttribute("aria-label","Tensaku editor"),container.style.background=backgroundOf(element),container.style.color=computed.color;let room=innerWidth-16;container.style.minWidth=`${Math.min(Math.max(rect.width+INSET.x*2,240),room)}px`,container.style.maxWidth=`${Math.min(Math.max(rect.width+INSET.x*2,480),room)}px`,layer.append(container),place(container,new DOMRect(rect.left-INSET.x,rect.top-INSET.y,rect.width+INSET.x*2,rect.height),!0),bar.style.maxWidth=`${innerWidth-8-container.getBoundingClientRect().left}px`;let keys=(event)=>{if(!container.isConnected)return;if(event.key==="Escape")event.preventDefault(),event.stopPropagation(),close();if(event.key!=="Enter"||composing(event)||!activeInShadow()?.classList.contains("editable"))return;if(surface.dataset.newlines!==void 0?event.metaKey||event.ctrlKey:!event.shiftKey)event.preventDefault(),saveAndClose()};return document.addEventListener("keydown",keys,!0),container.addEventListener("focusout",()=>{setTimeout(()=>{let active=activeInShadow();if(container.isConnected&&!container.dataset.saving&&!(active&&container.contains(active)))saveAndClose()},150)}),open2={element:container,save:saveAndClose,close},container.querySelector(".editable")?.focus(),container}var NESTED_STYLES=["fontFamily","fontSize","fontStyle","fontWeight","letterSpacing","textTransform","color"];function nestedElement(piece,host2,unchanged){if(piece.tag==="br"||piece.tag.startsWith("br.")||piece.tag.startsWith("br#"))return document.createElement("br");let child=piece.stamp?host2?.querySelector(`[${STAMP}="${CSS.escape(piece.stamp)}"]`):null,computed=child?getComputedStyle(child):null;if(computed&&(computed.display==="none"||computed.position==="absolute"||computed.position==="fixed"))return null;let text=child?visibleText(child,80):piece.label;if(!text)return h("span",{className:"chip mark",title:`<${piece.tag}>`,contenteditable:"false"});let span=h("span",{className:"nested",contenteditable:"false"},text);if(computed){if(NESTED_STYLES.forEach((name)=>{span.style[name]=computed[name]}),!computed.display.startsWith("inline"))span.style.display="block"}if(child&&editKind(child))span.classList.add("link"),span.title="Edit this element on its own",span.addEventListener("click",()=>{if(unchanged())edit(child)});return span}function pieceSurface(pieces,host2){let surface=div(""),fields=[],unchanged=()=>fields.every(({span,piece})=>valueOf(span)===piece.text);for(let piece of pieces)if(piece.kind==="text"){if(!piece.text.trim()){if(surface.lastChild&&surface.lastChild.nodeName!=="BR")surface.append(" ");continue}let span=field(piece.text);fields.push({span,piece}),surface.append(span)}else if(piece.kind==="ruby")surface.append(chip(piece.code.length>30?piece.code.slice(0,29)+"…":piece.code,piece.code));else if(piece.kind==="element"){let node=nestedElement(piece,host2,unchanged);if(node)surface.append(node)}return{surface,fields}}async function editTemplate(element){let stamp=stampOf(element),info=await api("GET","/source"+query({stamp:stamp.value}));if(indexPieces(info.pieces),!info.editable){if(editableAttributes(element).length)return editAttributes(element);throw Error(info.helper?"This element comes from a helper, so its text can't be edited here.":"This element has no static text to edit.")}assertRendered(element,info.pieces.filter((p)=>p.kind==="text").map((p)=>p.text));let{surface,fields}=pieceSurface(info.pieces,element),copies=copiesOf(element);frame(element,surface,`${info.file}:${stamp.line}`,async()=>{let changed=fields.filter(({span,piece})=>valueOf(span)!==piece.text);if(!changed.length)return;await saveTemplate(element,stamp.value,changed.map(({span,piece})=>({piece,text:valueOf(span)})))},[],copies>1?`this edits all ${copies} copies`:void 0)}async function saveTemplate(element,stamp,changes){let result=await api("POST","/text",{stamp,edits:changes.map(({piece,text})=>({start:piece.start,end:piece.end,original:piece.raw,text}))}),nodes=textNodesOf2(stamp);changes.forEach(({piece,text})=>replaceText(nodes,piece.text,text));let entry=result.changed?record(element,`edit in ${stamp}`,{kind:"template",stamp,changes:changes.map(({piece,text})=>({index:piece.index??-1,from:piece.text,to:text}))},result.file):void 0;afterSave(result,"template",entry)}async function editAttributes(element){let stamp=stampOf(element),description=stamp?await api("GET","/source"+query({stamp:stamp.value})):null,names2=editableAttributes(element),rows=[],savers=[],templateFields=[];for(let name of names2){let key=attributeKey(element,name);if(key){let entry=(await api("GET","/translation"+query({key:key.key}))).locales[key.locale];if(!entry?.editable||entry.value===null)continue;assertRendered(attributeNode(element,name),staticParts(entry.value));let{surface:surface3,read}=interpolationSurface(entry.value);rows.push(div("attr",h("span",{className:"name",title:`${key.locale}.${key.key}`},`${name} (t)`),div("value",surface3))),savers.push(async()=>{let text=read();if(text===entry.value)return;await saveTranslations(element,key,[{locale:key.locale,from:entry.value,to:text}]),entry.value=text});continue}let attribute=description?.attributes.find((a)=>a.name===name);if(!attribute||!attribute.pieces.some((p)=>p.kind==="text"))continue;assertRendered(attributeNode(element,name),attribute.pieces.filter((p)=>p.kind==="text").map((p)=>p.text));let{surface:surface2,fields}=pieceSurface(attribute.pieces);rows.push(div("attr",h("span",{className:"name"},name),div("value",surface2))),fields.forEach(({span,piece})=>templateFields.push({name,span,piece}))}if(templateFields.length)savers.push(()=>saveAttributePieces(element,stamp.value,templateFields));if(!rows.length)throw Error("Nothing here can be edited. Leave a note instead.");let surface=div("");surface.append(...rows),frame(element,surface,description?`${description.file}:${stamp.line} attributes`:"attributes",async()=>{for(let save of savers)await save()})}async function saveAttributePieces(element,stamp,fields){let changed=fields.map(({name,span,piece})=>({name,piece,text:valueOf(span)})).filter(({piece,text})=>text!==piece.text).sort((a,b)=>b.piece.start-a.piece.start);if(!changed.length)return;let saved=[],last2={};try{for(let{name,piece,text}of changed){last2=await api("POST","/attribute",{stamp,name,start:piece.start,end:piece.end,original:piece.raw,text}),document.querySelectorAll(`[${STAMP}="${CSS.escape(stamp)}"]`).forEach((el)=>{let current3=el.getAttribute(name);if(current3!==null)el.setAttribute(name,current3.replace(piece.text,text))});let index=fields.filter((field2)=>field2.name===name).findIndex((field2)=>field2.piece===piece);saved.push({name,index,from:piece.text,to:text}),piece.text=text}}finally{if(saved.length){let names2=Array.from(new Set(saved.map((change)=>change.name))).join(", "),entry=record(element,names2,{kind:"attribute",stamp,changes:saved},last2.file);afterSave({...last2,changed:!0},"template",entry)}}}function interpolationSurface(value){let surface=div("");for(let part of value.split(INTERPOLATION)){if(!part)continue;surface.append(INTERPOLATION.test(part)?chip(part):field(part,!0))}if(!surface.querySelector(".editable"))surface.prepend(field("",!0));return{surface,read:()=>Array.from(surface.childNodes).map((node)=>node.classList?.contains("chip")?node.textContent:valueOf(node)).join("")}}async function editTranslation(element,key){let{locales}=await api("GET","/translation"+query({key:key.key})),entry=locales[key.locale];if(!entry?.editable||entry.value===null)throw Error(`${key.locale}.${key.key} isn't in a writable locale file (it may come from a gem).`);assertRendered(element,staticParts(entry.value));let main=interpolationSurface(entry.value),others=Object.entries(locales).filter(([locale])=>locale!==key.locale),otherRows=div("");otherRows.hidden=!0;let otherReaders=[];for(let[locale,other]of others)if(other.editable&&other.value!==null){let surface=interpolationSurface(other.value);otherReaders.push({locale,entry:other,read:surface.read}),otherRows.append(div("locale",h("span",{className:"code"},locale),surface.surface))}else otherRows.append(div("locale",h("span",{className:"code"},locale),h("em",{className:"ink-muted"},other.value===null?"missing":`${other.value} (not writable)`)));let toggle=others.length?h("button",{className:"link",type:"button",onclick:()=>{otherRows.hidden=!otherRows.hidden,toggle.textContent=otherRows.hidden?`Other locales (${others.length})`:"Hide other locales"}},`Other locales (${others.length})`):null,extra=toggle?[div("locale",h("span",{className:"code"},""),toggle),otherRows]:[];frame(element,main.surface,`${key.locale}.${key.key} · ${entry.file}:${entry.line}`,async()=>{let changes=[{locale:key.locale,entry,read:main.read},...otherReaders].flatMap(({locale,entry:entry2,read})=>{let to=read();return to===entry2.value?[]:[{locale,from:entry2.value,to,entry:entry2}]});await saveTranslations(element,key,changes,(change)=>{change.entry.value=change.to})},extra)}async function saveTranslations(element,key,changes,onSaved=()=>{}){let saved=[],result={};try{for(let change of changes){let reply=await api("POST","/translation",{locale:change.locale,key:key.key,original:change.from,text:change.to});if(showTranslation({locale:change.locale,key:key.key},change.from,change.to),onSaved(change),reply.changed)saved.push({locale:change.locale,from:change.from,to:change.to});result={...reply,file:result.file??reply.file,changed:result.changed||reply.changed}}}finally{let label=saved.length>1?`${key.key} in ${saved.length} locales`:key.key,entry=saved.length?record(element,label,{kind:"translation",key:key.key,changes:saved},result.file):void 0;if(saved.length)afterSave(result,"translation",entry)}}async function editMarkdown(element){let range=element.getAttribute(MARKDOWN),tag=element.tagName.toLowerCase(),info=await api("GET","/markdown"+query({range,tag}));if(!info.editable)throw Error("This Markdown block can only get notes.");let words=info.text.replace(/^\s*(?:[-*+]|\d{1,9}[.)])\s+(?:\[[ xX]\]\s+)?/gm,"").replace(/\]\([^)]*\)/g,"").replace(/[*_`#>\[\]]/g,"");assertRendered(element,words.split(`
|
|
387
|
-
`).map((line)=>line.trim().split(/\s+/).slice(0,6).join(" ")).slice(0,8));let surface=div("");if(tag==="ul"||tag==="ol")surface.dataset.newlines="";if(info.prefix.trim())surface.append(chip(info.prefix.trim())," ");let text=field(info.text,!0);surface.append(text),frame(element,surface,`${info.file}:${info.range.split(":")[0]} (Markdown)`,async()=>{let value=valueOf(text);if(value===info.text)return;await saveMarkdown(element,range,info.original,info.prefix,value,info.text,tag)})}async function saveMarkdown(element,range,original,prefix,text,previous,tag){let result=await api("POST","/markdown",{range,original,text,tag});if(!tag?.match(/^[uo]l$/)&&!/[*_`\[\]<>#]/.test(previous+text))replaceText(Array.from(element.childNodes).filter((n)=>n.nodeType===Node.TEXT_NODE),previous,text);let entry=result.changed?record(element,"Markdown edit",{kind:"markdown",range:rangeAfter(range,prefix+text),prefix,from:previous,to:text,tag},result.file):void 0;afterSave(result,"markdown",entry)}function indexPieces(pieces){let index=0;for(let piece of pieces)if(piece.kind==="text")piece.index=index++}var staticParts=(value)=>value.split(INTERPOLATION).filter((part)=>part&&!INTERPOLATION.test(part));function attributeNode(element,name){let node=document.createElement("span");return node.textContent=element.getAttribute(name)??"",node}function afterSave(result,kind,entry){finish(result,kind,"Saved",entry?{Undo:()=>undo(entry)}:void 0)}var TAB=(()=>{try{let id=sessionStorage.getItem("tensaku-tab")??Math.random().toString(36).slice(2,10);return sessionStorage.setItem("tensaku-tab",id),id}catch{return Math.random().toString(36).slice(2,10)}})();function sendSelection(targets,text){api("POST","/selection",{url:location.pathname,tab:TAB,targets,text}).catch(()=>{})}var hoverBoxes=[],current3=null;function clearHover(){current3=null,hoverBoxes.forEach((b)=>b.remove()),hoverBoxes=[]}function label(element){let stamp=stampOf(element)??nearestStamp(element),md=element.getAttribute(MARKDOWN)?.match(/^(.+):(\d+):\d+-/),key=translationOf(element),where=key?`${key.locale}.${key.key}`:md?`${md[1]}:${md[2]}`:stamp?`${stamp.file}:${stamp.line}`:"";return[tagLabel(element),where]}function highlight(element,className=""){clearHover(),current3=element,hoverBoxes=box(documentRect(element),className,label(element))}var stamped=(element)=>Boolean(element&&!isUi(element)&&element!==document.body&&!outsideScope(element)&&(element.hasAttribute(STAMP)||element.hasAttribute(MARKDOWN)));function step(element,key){if(key==="ArrowUp"){for(let node=element.parentElement;node&&node!==document.body&&!outsideScope(node);node=node.parentElement)if(stamped(node))return node;return null}if(key==="ArrowDown")return Array.from(element.querySelectorAll(`[${STAMP}], [${MARKDOWN}]`)).find((child)=>stamped(child)&&child.offsetParent!==null)??null;let base=modalScope()??document.body,parent=step(element,"ArrowUp")??base,siblings=Array.from(parent.querySelectorAll(`[${STAMP}], [${MARKDOWN}]`)).filter((node)=>stamped(node)&&step(node,"ArrowUp")===(parent===base?null:parent)),index=siblings.indexOf(element);return siblings[index+(key==="ArrowRight"?1:-1)]??null}function selectKey(event){if(mode()!=="inspect"||!current3||menu||isEditing()||activeInShadow()?.matches("textarea, input, [contenteditable]")||typingInPage())return!1;if(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(event.key)&&!event.altKey&&!event.metaKey&&!event.ctrlKey){let next=step(current3,event.key);if(event.preventDefault(),!next)return!0;return highlight(next),next.scrollIntoView({block:"nearest"}),!0}if(event.key==="Enter")return event.preventDefault(),openMenu(current3),!0;if(event.key.toLowerCase()==="c"&&(event.metaKey||event.ctrlKey)&&!getSelection()?.toString())return event.preventDefault(),copy(reference(current3)).then(()=>toast("Copied reference")),!0;return!1}var picked=[],pickedBoxes=[],pickBar=null,hasPicked=()=>picked.length>0;function clearPicked(){picked=[],drawPicked()}function togglePicked(element){clearHover();let index=picked.indexOf(element);if(index>=0)picked.splice(index,1);else picked.push(element);drawPicked()}function pickedRect(){let rects=picked.map(documentRect),left=Math.min(...rects.map((r)=>r.left)),top=Math.min(...rects.map((r)=>r.top));return new DOMRect(left,top,Math.max(...rects.map((r)=>r.right))-left,Math.max(...rects.map((r)=>r.bottom))-top)}function notePicked(){if(!picked.length)return;let elements=picked,targets=elements.flatMap((element)=>targetsFor(element).slice(0,1));pickBar?.remove(),pickBar=null,noteForm(pickedRect(),targets,{},clearPicked,`${elements.length} ${elements.length===1?"element":"elements"}`)}function drawPicked(){if(pickedBoxes.forEach((b)=>b.remove()),pickBar?.remove(),pickBar=null,pickedBoxes=picked.flatMap((element,index)=>box(documentRect(element),"selected",[`${index+1} ${tagLabel(element)}`,""])),!picked.length)return;pickBar=panel(documentRect(picked[picked.length-1]),"menu pick",h("h3",{},`${picked.length} selected`,h("span",{className:"where"},"Shift-click to add or remove")),h("button",{type:"button",onclick:notePicked},icon("pad"),h("span",{},"Add note"),h("kbd",{},"N")),h("button",{type:"button",onclick:clearPicked},icon("close"),h("span",{},"Clear"),h("kbd",{},"Esc"))),pickBar.dataset.tensakuMenu=""}function pickKey(event){if(!pickBar||isEditing()||activeInShadow()?.matches("textarea"))return!1;if(event.key.toLowerCase()==="n"&&!event.metaKey&&!event.ctrlKey&&!event.altKey)return event.preventDefault(),notePicked(),!0;if(event.key==="Escape")return event.preventDefault(),clearPicked(),!0;return!1}var menu=null,menuOpen=()=>menu!==null;function closeMenu(){if(menu?.remove(),menu=null,mode()==="off")clearHover()}function reference(element){let stamp=nearestStamp(element),lines=[`${meta().method} ${location.pathname}${location.search} → ${stamp?`${stamp.file}:${stamp.line}:${stamp.column}`:"(no source stamp)"}`],text=visibleText(element,200);lines.push(`<${tagLabel(element)}>${text?` "${text}"`:""}`);let key=translationOf(element);if(key)lines.push(`Translation: ${key.locale}.${key.key}`);let md=element.closest(`[${MARKDOWN}]`)?.getAttribute(MARKDOWN);if(md)lines.push(`Markdown: ${md}`);let context=contextOf(element);if(context.partials.length>1)lines.push(`Partials: ${context.partials.join(" < ")}`);if(context.controller)lines.push(`Stimulus: ${context.controller}`);if(context.frame)lines.push(`Turbo Frame: #${context.frame}`);let copies=copiesOf(element);if(copies>1)lines.push(`Rendered ${copies} times on this page (loop or repeated partial)`);return lines.join(`
|
|
386
|
+
`),endLine=Number(startLine)+lines.length-1,endColumn=(lines.length===1?Number(startColumn)-1:0)+utf8Length(lines[lines.length-1]);return`${path}:${startLine}:${startColumn}-${endLine}:${endColumn}`}var textNodesOf2=(stamp)=>Array.from(document.querySelectorAll(`[${STAMP}="${CSS.escape(stamp)}"]`)).flatMap((el)=>Array.from(el.childNodes).filter((node)=>node.nodeType===Node.TEXT_NODE));function showTranslation(key,from,to){if(INTERPOLATION.test(from))return;replaceText(nodesForKey(key),from,to),elementsWithAttributeKey(key).forEach(({element:el,name})=>{if(el.getAttribute(name)===from)el.setAttribute(name,to)})}var HISTORY_LIMIT=50,HISTORY_KEY="tensaku:history",done=[],undone=[];try{let saved=JSON.parse(sessionStorage.getItem(HISTORY_KEY)??"null");if(saved&&Array.isArray(saved.done)&&Array.isArray(saved.undone))({done,undone}=saved)}catch{}function persist(){try{sessionStorage.setItem(HISTORY_KEY,JSON.stringify({done,undone}))}catch{}}var nextId=()=>Math.max(0,...done.map((entry)=>entry.id),...undone.map((entry)=>entry.id))+1;function record(element,label,op,file){let entry={id:nextId(),label,key:element?undoKey(element):null,file,at:new Date().toISOString(),op};if(done.push(entry),done.length>HISTORY_LIMIT)done.shift();return undone=[],persist(),entry}function editHistory(){return{done:done.slice().reverse(),undone:undone.slice().reverse()}}var canUndo=()=>done.length>0,canRedo=()=>undone.length>0;async function undo(entry=done[done.length-1]){if(!entry||!done.includes(entry))return toast("That edit was undone already.");try{let result=await apply(entry.op,!0);done=done.filter((item)=>item!==entry),undone.push(entry),persist(),finish(result,sourceKind(entry.op),`Undid ${entry.label}`,{Redo:()=>redo(entry)})}catch(error){report(error)}}async function redo(entry=undone[undone.length-1]){if(!entry||undone[undone.length-1]!==entry)return toast("Only the latest undone edit can be redone.");try{let result=await apply(entry.op,!1);undone.pop(),done.push(entry),persist(),finish(result,sourceKind(entry.op),`Redid ${entry.label}`,{Undo:()=>undo(entry)})}catch(error){report(error)}}var sourceKind=(op)=>op.kind==="attribute"?"template":op.kind;function undoFor(element){let key=undoKey(element);return key?done.slice().reverse().find((entry)=>entry.key===key):void 0}async function apply(op,reverse){let verb=reverse?"undone":"redone",stale=(what)=>new ApiError(`The ${what} changed since the edit, so it can't be ${verb} here.`,409,!0);if(op.kind==="template"){let texts=(await api("GET","/source"+query({stamp:op.stamp}))).pieces.filter((p)=>p.kind==="text"),edits=op.changes.map(({index,from,to})=>{let[current3,target2]=reverse?[to,from]:[from,to],now=texts[index];if(!now||now.text!==current3)throw stale("text");return{piece:now,current:current3,target:target2}}),result2=await api("POST","/text",{stamp:op.stamp,edits:edits.map(({piece,target:target2})=>({start:piece.start,end:piece.end,original:piece.raw,text:target2}))}),nodes=textNodesOf2(op.stamp);return edits.forEach(({current:current3,target:target2})=>replaceText(nodes,current3,target2)),result2}if(op.kind==="attribute"){let result2={};for(let{name,index,from,to}of op.changes){let[current3,target2]=reverse?[to,from]:[from,to],now=(await api("GET","/source"+query({stamp:op.stamp}))).attributes.find((a)=>a.name===name)?.pieces.filter((p)=>p.kind==="text")[index];if(!now||now.text!==current3)throw stale("attribute");result2=await api("POST","/attribute",{stamp:op.stamp,name,start:now.start,end:now.end,original:now.raw,text:target2}),document.querySelectorAll(`[${STAMP}="${CSS.escape(op.stamp)}"]`).forEach((el)=>{let value=el.getAttribute(name);if(value!==null)el.setAttribute(name,value.replace(current3,target2))})}return{...result2,changed:!0}}if(op.kind==="translation"){let result2={};for(let{locale,from,to}of op.changes){let[current3,target2]=reverse?[to,from]:[from,to],saved=await api("POST","/translation",{locale,key:op.key,original:current3,text:target2});result2={...saved,file:result2.file??saved.file,changed:!0},showTranslation({locale,key:op.key},current3,target2)}return result2}let[current2,target]=reverse?[op.to,op.from]:[op.from,op.to],result=await api("POST","/markdown",{range:op.range,original:op.prefix+current2,text:target,tag:op.tag});return op.range=rangeAfter(op.range,op.prefix+target),result}function undoKey(element){let translation=translationOf(element);return element.getAttribute(STAMP)??element.getAttribute(MARKDOWN)??(translation?`${translation.locale}.${translation.key}`:null)}var UNDO_KEYS=isApple?"⌘Z and ⇧⌘Z":"Ctrl+Z and Ctrl+Y";function renderHistory(){let{done:done2,undone:undone2}=editHistory(),row2=(entry,action)=>div(`entry${undone2.includes(entry)?" undone":""}`,div("what",h("span",{},entry.label),h("span",{className:"where"},`${entry.file??""} · ${ago(new Date(entry.at))}`)),action),button=(text,run)=>h("button",{type:"button",onclick:async()=>{await run(),closePopover()}},text);return[h("h3",{},"Edit history",h("span",{className:"where"},`Saves in this tab. ${UNDO_KEYS} undo and redo.`)),...done2.length||undone2.length?[...done2.map((entry)=>row2(entry,button("Undo",()=>undo(entry)))),...undone2.map((entry,i)=>row2(entry,i===0?button("Redo",()=>redo(entry)):h("span",{className:"where"},"undone")))]:[div("empty","No edits yet.")]]}var current2="off",listeners5=[],mode=()=>current2,onMode=(listener)=>listeners5.push(listener);function setMode(next){current2=next,listeners5.forEach((listener)=>listener(next))}var paused=null;function togglePause(){if(paused)return paused.style.remove(),paused.animations.forEach((animation)=>{try{animation.play()}catch{}}),paused.media.forEach((media2)=>media2.play().catch(()=>{})),paused=null,!1;let animations=document.getAnimations().filter((animation)=>{let target=animation.effect?.target;return animation.playState==="running"&&!(target&&isUi(target))});animations.forEach((animation)=>animation.pause());let media=Array.from(document.querySelectorAll("video, audio")).filter((element)=>!element.paused);media.forEach((element)=>element.pause());let style=document.createElement("style");return style.setAttribute("data-tensaku-pause",""),style.textContent="*, *::before, *::after { animation-play-state: paused !important; transition: none !important; }",document.head.append(style),paused={animations,media,style},!0}var supported=typeof host.showPopover==="function";if(supported)host.popover="manual";var opened=[],raisedOver=null,scope3=null,listeners6=[],modalScope=()=>scope3,outsideScope=(element)=>Boolean(scope3&&!scope3.contains(element)),onScopeChange=(listener)=>{listeners6.push(listener)};function openNow(){try{return Array.from(document.querySelectorAll("dialog:modal, :popover-open")).filter((element)=>element!==host)}catch{return[]}}var last=(elements,test)=>[...elements].reverse().find(test),holdsHost=(element)=>element.matches("dialog:modal")||["auto","hint"].includes(element.popover??"");function sync(closing){if(!supported){if(!host.isConnected)document.documentElement.append(host);return}let now=openNow().filter((element)=>element!==closing);opened=[...opened.filter((element)=>now.includes(element)),...now.filter((element)=>!opened.includes(element))];let container=last(opened,holdsHost)??document.documentElement;if(host.parentNode!==container)container.append(host);let top=opened.at(-1)??null,raised=host.matches(":popover-open");if(!top){if(raised)host.hidePopover()}else if(!raised||top!==raisedOver){if(raised)host.hidePopover();host.showPopover()}raisedOver=top;let modal=last(opened,(element)=>element.matches("dialog:modal"))??null;if(modal!==scope3)scope3=modal,listeners6.forEach((listener)=>listener())}function watchTopLayer(){sync(),new MutationObserver((records)=>{if(records.some((record2)=>record2.type==="attributes")||!host.isConnected||opened.some((element)=>!element.isConnected))sync()}).observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["open"]}),document.addEventListener("toggle",(event)=>{if(event.target!==host)sync()},!0),document.addEventListener("beforetoggle",(event)=>{let target=event.target;if(target!==host&&event.newState==="closed"&&target.contains(host))sync(target)},!0)}var pinLayer=div("pins");layer.append(pinLayer);function setPinsHidden(hidden){pinLayer.hidden=hidden}var drawn=new Map;onRender(({first})=>{if(first)currentNotes().forEach((note)=>drawn.set(note.id,note.status));drawPins()});var asked=new Map;onRefresh(()=>asked.clear());function syncHold(note,guessed){if(note.status!=="open"||note.url!==location.pathname)return;if(Boolean(note.held_at)===guessed||asked.get(note.id)===guessed)return;asked.set(note.id,guessed),api("PATCH",`/notes/${note.id}`,{held:guessed}).then(()=>load({force:!0})).catch(()=>{})}function drawPins(){pinLayer.replaceChildren();let scope4=modalScope();currentNotes().forEach((note,index)=>{if(scope4&&!scope4.contains(noteElement(note)))return;let guessed=!closed(note)&&Boolean(guessedElement(note));syncHold(note,guessed);let phrase=phraseRects(note);for(let r of phrase){let mark=div(`phrase ${note.status}`);Object.assign(mark.style,{left:`${r.left}px`,top:`${r.top}px`,width:`${r.width}px`,height:`${r.height}px`}),pinLayer.append(mark)}let point=phrase.length?null:pointFor(note),rect=phrase.length?phrase[phrase.length-1]:point??anchorFor(note);if(!rect)return;let fresh=drawn.get(note.id)!==note.status;drawn.set(note.id,note.status);let pin=h("button",{className:`pin ${note.status}${fresh?" fresh":""}${guessed||note.held_at&&!closed(note)?" unsure":""}`,title:note.comment,"aria-label":`Note ${index+1}: ${note.comment}`,"data-note":note.id},note.status==="resolved"?icon("check"):note.status==="declined"?icon("close"):String(index+1));Object.assign(pin.style,{left:`${point?point.x:rect.right}px`,top:`${rect.top}px`}),pin.addEventListener("click",(event)=>{event.stopPropagation(),showNote(note,rect)}),pinLayer.append(pin)})}var SHORTCUT_TOOLS={select:"Select",edit:"Edit",notes:"Notes",agents:"Agents",pins:"Hide or show pins",clear:"Delete this page's notes",pause:"Pause animations",history:"Edit history",settings:"Settings"},DEFAULTS2={select:"alt+shift+KeyT",edit:"alt+shift+KeyE",notes:"alt+shift+KeyN"};function shortcutFor(tool){let own=settings().shortcuts;return tool in own?own[tool]:DEFAULTS2[tool]??null}var isDefault=(tool)=>!(tool in settings().shortcuts);function setShortcut(tool,keys){let shortcuts={...settings().shortcuts},taken=keys?toolFor(keys):null;if(taken&&taken!==tool)shortcuts[taken]=null;if(keys===(DEFAULTS2[tool]??null))delete shortcuts[tool];else shortcuts[tool]=keys;return changeSettings({shortcuts}),taken&&taken!==tool?taken:null}var resetShortcuts=()=>changeSettings({shortcuts:{}});function toolFor(keys){return Object.keys(SHORTCUT_TOOLS).find((tool)=>shortcutFor(tool)===keys)??null}function toolForEvent(event){return event.code?toolFor(keysOf(event)):null}function keysOf(event){return[...[event.ctrlKey&&"ctrl",event.altKey&&"alt",event.shiftKey&&"shift",event.metaKey&&"meta"].filter(Boolean),event.code].join("+")}var isModifierKey=(event)=>["Alt","Shift","Control","Meta"].includes(event.key),hasCommandModifier=(event)=>event.altKey||event.ctrlKey||event.metaKey,APPLE_KEYS={alt:"⌥",shift:"⇧",ctrl:"⌃",meta:"⌘"},OTHER_KEYS={alt:"Alt",shift:"Shift",ctrl:"Ctrl",meta:"Meta"};function keysLabel(keys){let parts=keys.split("+"),key=parts.pop().replace(/^(Key|Digit)/,""),names=isApple?APPLE_KEYS:OTHER_KEYS;return[...parts.map((part)=>names[part]??part),key].join(isApple?"":"+")}var panel2=null,recording=null,hooks={toggled:()=>{},moveDockHome:()=>{}},setSettingsHooks=(given)=>{hooks=given},settingsOpen=()=>Boolean(panel2?.isConnected);function toggleSettings(force){let show=force??!settingsOpen();if(stopRecording(),!show){panel2?.remove(),hooks.toggled();return}panel2??=div("sidebar settings"),panel2.setAttribute("role","complementary"),panel2.setAttribute("aria-label","Tensaku settings"),fixed.append(panel2),render2(),hooks.toggled()}function render2(){if(!panel2)return;let prefs=settings(),choice=(value,text)=>h("button",{type:"button","aria-pressed":String(prefs.copyFormat===value),onclick:()=>{changeSettings({copyFormat:value}),render2()}},text),notify2=h("input",{type:"checkbox",checked:prefs.notify});notify2.addEventListener("change",async()=>{let on=notify2.checked;if(on&&"Notification"in window&&Notification.permission==="default")await Notification.requestPermission();let allowed="Notification"in window&&Notification.permission==="granted";if(on&&!allowed)toast("The browser blocked notifications for this site.",{error:!0});changeSettings({notify:on&&allowed}),render2()});let customized=Object.keys(SHORTCUT_TOOLS).some((tool)=>!isDefault(tool));panel2.replaceChildren(h("header",{},h("strong",{},"Settings"),h("button",{type:"button",className:"icon-button",onclick:()=>toggleSettings(!1),"aria-label":"Close settings"},icon("close"))),h("section",{},h("h4",{},"Notes"),div("setting",h("span",{},"Copy notes as"),div("segmented",choice("detailed","Detailed"),choice("short","One line each"))),h("label",{className:"check"},notify2,h("span",{},"Notify me",h("span",{className:"where"},"When an agent answers while this tab is in the background.")))),h("section",{},h("h4",{},"Keyboard shortcuts",customized?h("button",{type:"button",className:"link",onclick:()=>{resetShortcuts(),render2()}},"Reset all"):null),h("p",{className:"where"},"Click a shortcut and press the new keys, with Alt, Ctrl or Cmd. Escape cancels."),...Object.entries(SHORTCUT_TOOLS).map(([tool,name])=>shortcutRow(tool,name)),h("h5",{},"Always on"),...fixedShortcuts().map(([keys,what])=>div("shortcut always",h("span",{},what),h("kbd",{},keys)))),h("section",{},h("h4",{},"Toolbar"),div("setting",h("button",{type:"button",onclick:()=>hooks.moveDockHome()},"Move the toolbar back to the corner"))))}function shortcutRow(tool,name){let keys=shortcutFor(tool),waiting2=recording===tool,record2=h("button",{type:"button",className:`keys${waiting2?" recording":""}`,"aria-label":`Change the shortcut for ${name}`,onclick:()=>startRecording(tool)},waiting2?"Press keys…":keys?h("kbd",{},keysLabel(keys)):h("span",{className:"none"},"None")),clear=keys&&!waiting2?h("button",{type:"button",className:"icon-button","aria-label":`Remove the shortcut for ${name}`,onclick:()=>{setShortcut(tool,null),render2()}},icon("close")):null;return div(`shortcut${isDefault(tool)?"":" changed"}`,h("span",{},name),record2,clear)}function startRecording(tool){stopRecording(),recording=tool,addEventListener("keydown",onRecordKey,!0),render2()}function stopRecording(){recording=null,removeEventListener("keydown",onRecordKey,!0)}function onRecordKey(event){if(!recording||!settingsOpen()){stopRecording();return}if(isModifierKey(event))return;event.preventDefault(),event.stopImmediatePropagation();let tool=recording;if(stopRecording(),event.key==="Escape"){render2();return}if(!hasCommandModifier(event)){toast("Use Alt, Ctrl or Cmd with the key, so typing never triggers it.",{error:!0}),render2();return}let keys=keysOf(event),moved=setShortcut(tool,keys);if(moved)toast(`${keysLabel(keys)} no longer does ${SHORTCUT_TOOLS[moved]}.`);render2()}function fixedShortcuts(){let click=(keys)=>isApple?`${keys} click`:`${keys}+click`,alt=isApple?"⌥":"Alt",shift=isApple?"⇧":"Shift";return[[click(alt),"Menu for an element"],[click(isApple?alt+shift:`${alt}+${shift}`),"Note on an element"],[click(shift),"Pick several elements, in select mode"],["N","Note the picked elements"],["Esc","Close a menu or panel, or leave the mode"]]}var INK={highlighter:"#ffe14d",pen:"#e0344f",pad:"#fff1a1"},count=h("span",{className:"count",hidden:!0}),corner=h("button",{className:"corner",type:"button",title:"Tensaku","aria-label":"Tensaku","aria-expanded":"false"},logo(),count);function tool(name,ink,text){let tip=h("span",{className:"tip","aria-hidden":"true"},text),button=h("button",{type:"button",className:"tool","aria-pressed":"false","aria-label":text},icon(name,ink),tip);return button.style.setProperty("--ink-color",ink),button}function action(name,text){return h("button",{type:"button",className:"tool","aria-label":text},icon(name),h("span",{className:"tip","aria-hidden":"true"},text))}function setTip(button,text){button.setAttribute("aria-label",text),button.querySelector(".tip").firstChild.textContent=text}var setIcon=(button,name,ink)=>button.replaceChild(icon(name,ink),button.querySelector("svg")),selectTool=tool("highlighter",INK.highlighter,"Select"),editTool=tool("pen",INK.pen,"Edit"),notesTool=tool("pad",INK.pad,"Notes"),notesBadge=h("span",{className:"badge",hidden:!0});notesTool.append(notesBadge);var pinsTool=action("eye","Hide pins"),pauseTool=action("pause","Pause animations"),clearTool=action("trash","Delete this page's notes"),historyTool=action("history","Edit history"),settingsTool=action("sliders","Settings"),agentsTool=action("plane","No agent connected");agentsTool.classList.add("agents");var agentsBadge=h("span",{className:"badge",hidden:!0});agentsTool.append(agentsBadge);var tools=div("tools",selectTool,editTool,div("sep"),notesTool,agentsTool,pinsTool,clearTool,div("sep"),pauseTool,historyTool,settingsTool),toolbar=div("toolbar",tools);new ResizeObserver(()=>toolbar.style.setProperty("--tools-width",`${tools.offsetWidth}px`)).observe(tools);var dock=div("dock",toolbar,corner);fixed.append(dock);var shortcutButtons={select:selectTool,edit:editTool,notes:notesTool,agents:agentsTool,pins:pinsTool,clear:clearTool,pause:pauseTool,history:historyTool,settings:settingsTool};onSettings(()=>{for(let[name,button]of Object.entries(shortcutButtons)){let keys=shortcutFor(name),tip=button.querySelector(".tip");if(tip.querySelector("kbd")?.remove(),keys)tip.append(h("kbd",{},keysLabel(keys)))}});function pressShortcut(name){setToolbar(!0),shortcutButtons[name].click()}var toolbarOpen=()=>dock.classList.contains("open"),settling=0;function setToolbar(open2){if(open2===toolbarOpen())return;if(dock.classList.toggle("open",open2),corner.setAttribute("aria-expanded",String(open2)),clearTimeout(settling),dock.classList.remove("settled"),open2)settling=window.setTimeout(()=>dock.classList.add("settled"),280)}function moveDock(right,bottom){dock.style.right=`${right}px`,dock.style.bottom=`${bottom}px`,dock.style.setProperty("--dock-right",`${right}px`)}function placeDock(){let position=storage("dock",{right:16,bottom:16});moveDock(Math.min(Math.max(position.right,4),innerWidth-52),Math.min(Math.max(position.bottom,4),innerHeight-52))}var dragged=!1;corner.addEventListener("pointerdown",(event)=>{let start={x:event.clientX,y:event.clientY,right:parseFloat(dock.style.right),bottom:parseFloat(dock.style.bottom)};dragged=!1,corner.setPointerCapture(event.pointerId);let move=(e)=>{let dx=e.clientX-start.x,dy=e.clientY-start.y;if(!dragged&&Math.hypot(dx,dy)<4)return;dragged=!0,corner.style.cursor="grabbing",moveDock(start.right-dx,start.bottom-dy)},up=()=>{if(corner.removeEventListener("pointermove",move),corner.removeEventListener("pointerup",up),corner.removeEventListener("pointercancel",up),corner.style.cursor="",dragged)store("dock",{right:parseFloat(dock.style.right),bottom:parseFloat(dock.style.bottom)})};corner.addEventListener("pointermove",move),corner.addEventListener("pointerup",up),corner.addEventListener("pointercancel",up)});corner.addEventListener("click",()=>{if(dragged)return;if(setToolbar(!toolbarOpen()),toolbarOpen())return;toggleSidebar(!1),toggleSettings(!1),setMode("off")});function closeToolbar(){if(!toolbarOpen())return!1;return setToolbar(!1),!0}function syncButtons(){selectTool.setAttribute("aria-pressed",String(mode()==="inspect")),editTool.setAttribute("aria-pressed",String(mode()==="edit")),notesTool.setAttribute("aria-pressed",String(sidebarOpen())),settingsTool.setAttribute("aria-pressed",String(settingsOpen())),corner.classList.toggle("active",mode()!=="off")}onMode((next)=>{if(next!=="off")setToolbar(!0);syncButtons()});function closeSidePanel(){if(settingsOpen())return toggleSettings(!1),!0;if(!sidebarOpen())return!1;return toggleSidebar(!1),syncButtons(),!0}selectTool.addEventListener("click",()=>setMode(mode()==="inspect"?"off":"inspect"));editTool.addEventListener("click",()=>setMode(mode()==="edit"?"off":"edit"));notesTool.addEventListener("click",()=>{toggleSettings(!1),toggleSidebar(),syncButtons()});onCount((n)=>{count.hidden=n===0,count.textContent=String(n),notesBadge.hidden=n===0,notesBadge.textContent=String(n),setTip(notesTool,n?`Notes (${n})`:"Notes")});setSettingsHooks({toggled:syncButtons,moveDockHome:()=>{store("dock",{right:16,bottom:16}),placeDock()}});settingsTool.addEventListener("click",()=>{if(closePopover(),!settingsOpen())toggleSidebar(!1);toggleSettings()});historyTool.addEventListener("click",()=>togglePopover(historyTool,dock,renderHistory));var pinsHidden=storage("pinsHidden",!1);function syncPins(){setPinsHidden(pinsHidden),pinsTool.setAttribute("aria-pressed",String(pinsHidden)),setIcon(pinsTool,pinsHidden?"eye-off":"eye"),setTip(pinsTool,pinsHidden?"Show pins":"Hide pins")}pinsTool.addEventListener("click",()=>{pinsHidden=!pinsHidden,store("pinsHidden",pinsHidden),syncPins()});pauseTool.addEventListener("click",()=>{let paused2=togglePause();pauseTool.setAttribute("aria-pressed",String(paused2)),setIcon(pauseTool,paused2?"play":"pause"),setTip(pauseTool,paused2?"Resume animations":"Pause animations")});var confirmClear=0;clearTool.addEventListener("click",async()=>{let total=currentNotes().length;if(!total){toast("No notes on this page");return}if(!confirmClear){clearTool.classList.add("confirm"),setTip(clearTool,`Delete ${total} ${total===1?"note":"notes"}? Click again`),confirmClear=window.setTimeout(resetClear,3000);return}resetClear();try{await deleteNotes(currentNotes()),toast(`Deleted ${total} ${total===1?"note":"notes"}`)}catch(error){toast(error.message,{error:!0})}});function resetClear(){clearTimeout(confirmClear),confirmClear=0,clearTool.classList.remove("confirm"),setTip(clearTool,"Delete this page's notes")}var names=(list)=>list.map(agentLabel).join(", "),agentsSignature="[]";onAgents((agents2)=>{let signature=JSON.stringify(agents2);if(signature===agentsSignature)return;agentsSignature=signature;let listening=agents2.filter((agent)=>agent.listening);agentsTool.classList.toggle("connected",agents2.length>0),agentsTool.classList.toggle("listening",listening.length>0),setIcon(agentsTool,listening.length?"plane-flying":"plane",listening.length?"#2fa872":void 0),agentsBadge.hidden=agents2.length<2,agentsBadge.textContent=String(agents2.length),setTip(agentsTool,listening.length?`${names(listening)} listening`:agents2.length?`${names(agents2)} connected`:"No agent connected"),redrawPopover(agentsTool)});agentsTool.addEventListener("click",()=>togglePopover(agentsTool,dock,renderAgents));setAgentsHandler(()=>{if(setToolbar(!0),!popoverOpen(agentsTool))togglePopover(agentsTool,dock,renderAgents)});var open2=null,composing=(event)=>event.isComposing||event.keyCode===229;function isEditing(){return open2!==null}function closeEditor(){open2?.close()}async function edit(element,kind=editKind(element)){closeEditor();try{if(kind==="translation")await editTranslation(element,translationOf(element));else if(kind==="markdown")await editMarkdown(element);else if(kind==="template")await editTemplate(element);else if(kind==="attributes")await editAttributes(element);else toast("This text comes from Ruby, so it can't be edited here. Leave a note instead.")}catch(error){report(error)}}var normal=(text)=>text.replace(/\s+/g," ").trim();function assertRendered(element,texts){let rendered2=normal(element.textContent??""),from=0;for(let text of texts.map(normal).filter(Boolean)){let at=rendered2.indexOf(text,from);if(at<0)throw new ApiError("The file changed since the page was rendered. Reload the page and try again.",409,!0);from=at+text.length}}function field(text,multiline=!1){let span=h("span",{className:"editable",spellcheck:"true"},text);if(span.contentEditable="plaintext-only",span.contentEditable!=="plaintext-only")span.contentEditable="true";if(span.dataset.original=text,span.addEventListener("paste",(event)=>{event.preventDefault(),document.execCommand("insertText",!1,event.clipboardData?.getData("text/plain")??"")}),!multiline)span.addEventListener("keydown",(event)=>{if(event.key==="Enter"&&event.shiftKey&&!composing(event))event.preventDefault()});return span}var valueOf=(span)=>(span.innerText??span.textContent??"").replace(/ /g," ").replace(/\n$/,"");function chip(label,title){return h("span",{className:"chip",title,contenteditable:"false"},label)}function backgroundOf(element){for(let node=element;node;node=node.parentElement){let color=getComputedStyle(node).backgroundColor,alpha=color.match(/rgba?\([^)]*,\s*([\d.]+)\)/)?.[1];if(color!=="transparent"&&(alpha===void 0||Number(alpha)>0.6))return color}return"#fff"}var INSET={x:11.5,y:9.5};function frame(element,surface,info,save,extra=[],warning){let rect=contentRect(element),computed=getComputedStyle(element);Object.assign(surface.style,{fontFamily:computed.fontFamily,fontSize:computed.fontSize,fontWeight:computed.fontWeight,lineHeight:computed.lineHeight,letterSpacing:computed.letterSpacing,textAlign:computed.textAlign,color:computed.color}),surface.classList.add("surface");let status=h("span",{},info),close=()=>{container.remove(),open2=null,document.removeEventListener("keydown",keys,!0)},saveAndClose=async()=>{if(container.dataset.saving)return;container.dataset.saving="1",status.textContent="Saving…";try{await save(),close()}catch(error){delete container.dataset.saving,status.textContent=info,report(error)}},bar=div("bar",h("span",{},status,warning?h("strong",{className:"ink-warning"},` · ${warning}`):null),div("actions",h("button",{onclick:close,type:"button"},"Cancel"),h("button",{className:"primary",onclick:saveAndClose,type:"button"},"Save"))),container=div("panel editor",surface,...extra,bar);container.setAttribute("role","dialog"),container.setAttribute("aria-label","Tensaku editor"),container.style.background=backgroundOf(element),container.style.color=computed.color;let room=innerWidth-16;container.style.minWidth=`${Math.min(Math.max(rect.width+INSET.x*2,240),room)}px`,container.style.maxWidth=`${Math.min(Math.max(rect.width+INSET.x*2,480),room)}px`,layer.append(container),place(container,new DOMRect(rect.left-INSET.x,rect.top-INSET.y,rect.width+INSET.x*2,rect.height),!0),bar.style.maxWidth=`${innerWidth-8-container.getBoundingClientRect().left}px`;let keys=(event)=>{if(!container.isConnected)return;if(event.key==="Escape")event.preventDefault(),event.stopPropagation(),close();if(event.key!=="Enter"||composing(event)||!activeInShadow()?.classList.contains("editable"))return;if(surface.dataset.newlines!==void 0?event.metaKey||event.ctrlKey:!event.shiftKey)event.preventDefault(),saveAndClose()};return document.addEventListener("keydown",keys,!0),container.addEventListener("focusout",()=>{setTimeout(()=>{let active=activeInShadow();if(container.isConnected&&!container.dataset.saving&&!(active&&container.contains(active)))saveAndClose()},150)}),open2={element:container,save:saveAndClose,close},container.querySelector(".editable")?.focus(),container}var NESTED_STYLES=["fontFamily","fontSize","fontStyle","fontWeight","letterSpacing","textTransform","color"];function nestedElement(piece,host2,unchanged){if(piece.tag==="br"||piece.tag.startsWith("br.")||piece.tag.startsWith("br#"))return document.createElement("br");let child=piece.stamp?host2?.querySelector(`[${STAMP}="${CSS.escape(piece.stamp)}"]`):null,computed=child?getComputedStyle(child):null;if(computed&&(computed.display==="none"||computed.position==="absolute"||computed.position==="fixed"))return null;let text=child?visibleText(child,80):piece.label;if(!text)return h("span",{className:"chip mark",title:`<${piece.tag}>`,contenteditable:"false"});let span=h("span",{className:"nested",contenteditable:"false"},text);if(computed){if(NESTED_STYLES.forEach((name)=>{span.style[name]=computed[name]}),!computed.display.startsWith("inline"))span.style.display="block"}if(child&&editKind(child))span.classList.add("link"),span.title="Edit this element on its own",span.addEventListener("click",()=>{if(unchanged())edit(child)});return span}function pieceSurface(pieces,host2){let surface=div(""),fields=[],unchanged=()=>fields.every(({span,piece})=>valueOf(span)===piece.text);for(let piece of pieces)if(piece.kind==="text"){if(!piece.text.trim()){if(surface.lastChild&&surface.lastChild.nodeName!=="BR")surface.append(" ");continue}let span=field(piece.text);fields.push({span,piece}),surface.append(span)}else if(piece.kind==="ruby")surface.append(chip(piece.code.length>30?piece.code.slice(0,29)+"…":piece.code,piece.code));else if(piece.kind==="element"){let node=nestedElement(piece,host2,unchanged);if(node)surface.append(node)}return{surface,fields}}async function editTemplate(element){let stamp=stampOf(element),info=await api("GET","/source"+query({stamp:stamp.value}));if(indexPieces(info.pieces),!info.editable){if(editableAttributes(element).length)return editAttributes(element);throw Error(info.helper?"This element comes from a helper, so its text can't be edited here.":"This element has no static text to edit.")}assertRendered(element,info.pieces.filter((p)=>p.kind==="text").map((p)=>p.text));let{surface,fields}=pieceSurface(info.pieces,element),copies=copiesOf(element);frame(element,surface,`${info.file}:${stamp.line}`,async()=>{let changed=fields.filter(({span,piece})=>valueOf(span)!==piece.text);if(!changed.length)return;await saveTemplate(element,stamp.value,changed.map(({span,piece})=>({piece,text:valueOf(span)})))},[],copies>1?`this edits all ${copies} copies`:void 0)}async function saveTemplate(element,stamp,changes){let result=await api("POST","/text",{stamp,edits:changes.map(({piece,text})=>({start:piece.start,end:piece.end,original:piece.raw,text}))}),nodes=textNodesOf2(stamp);changes.forEach(({piece,text})=>replaceText(nodes,piece.text,text));let entry=result.changed?record(element,`edit in ${stamp}`,{kind:"template",stamp,changes:changes.map(({piece,text})=>({index:piece.index??-1,from:piece.text,to:text}))},result.file):void 0;afterSave(result,"template",entry)}async function editAttributes(element){let stamp=stampOf(element),description=stamp?await api("GET","/source"+query({stamp:stamp.value})):null,names2=editableAttributes(element),rows=[],savers=[],templateFields=[];for(let name of names2){let key=attributeKey(element,name);if(key){let entry=(await api("GET","/translation"+query({key:key.key}))).locales[key.locale];if(!entry?.editable||entry.value===null)continue;assertRendered(attributeNode(element,name),staticParts(entry.value));let{surface:surface3,read}=interpolationSurface(entry.value);rows.push(div("attr",h("span",{className:"name",title:`${key.locale}.${key.key}`},`${name} (t)`),div("value",surface3))),savers.push(async()=>{let text=read();if(text===entry.value)return;await saveTranslations(element,key,[{locale:key.locale,from:entry.value,to:text}]),entry.value=text});continue}let attribute=description?.attributes.find((a)=>a.name===name);if(!attribute||!attribute.pieces.some((p)=>p.kind==="text"))continue;assertRendered(attributeNode(element,name),attribute.pieces.filter((p)=>p.kind==="text").map((p)=>p.text));let{surface:surface2,fields}=pieceSurface(attribute.pieces);rows.push(div("attr",h("span",{className:"name"},name),div("value",surface2))),fields.forEach(({span,piece})=>templateFields.push({name,span,piece}))}if(templateFields.length)savers.push(()=>saveAttributePieces(element,stamp.value,templateFields));if(!rows.length)throw Error("Nothing here can be edited. Leave a note instead.");let surface=div("");surface.append(...rows),frame(element,surface,description?`${description.file}:${stamp.line} attributes`:"attributes",async()=>{for(let save of savers)await save()})}async function saveAttributePieces(element,stamp,fields){let changed=fields.map(({name,span,piece})=>({name,piece,text:valueOf(span)})).filter(({piece,text})=>text!==piece.text).sort((a,b)=>b.piece.start-a.piece.start);if(!changed.length)return;let saved=[],last2={};try{for(let{name,piece,text}of changed){last2=await api("POST","/attribute",{stamp,name,start:piece.start,end:piece.end,original:piece.raw,text}),document.querySelectorAll(`[${STAMP}="${CSS.escape(stamp)}"]`).forEach((el)=>{let current3=el.getAttribute(name);if(current3!==null)el.setAttribute(name,current3.replace(piece.text,text))});let index=fields.filter((field2)=>field2.name===name).findIndex((field2)=>field2.piece===piece);saved.push({name,index,from:piece.text,to:text}),piece.text=text}}finally{if(saved.length){let names2=Array.from(new Set(saved.map((change)=>change.name))).join(", "),entry=record(element,names2,{kind:"attribute",stamp,changes:saved},last2.file);afterSave({...last2,changed:!0},"template",entry)}}}function interpolationSurface(value){let surface=div("");for(let part of value.split(INTERPOLATION)){if(!part)continue;surface.append(INTERPOLATION.test(part)?chip(part):field(part,!0))}if(!surface.querySelector(".editable"))surface.prepend(field("",!0));return{surface,read:()=>Array.from(surface.childNodes).map((node)=>node.classList?.contains("chip")?node.textContent:valueOf(node)).join("")}}async function editTranslation(element,key){let{locales}=await api("GET","/translation"+query({key:key.key})),entry=locales[key.locale];if(!entry?.editable||entry.value===null)throw Error(`${key.locale}.${key.key} isn't in a writable locale file (it may come from a gem).`);assertRendered(element,staticParts(entry.value).map(renderedText));let main=interpolationSurface(entry.value),others=Object.entries(locales).filter(([locale])=>locale!==key.locale),otherRows=div("");otherRows.hidden=!0;let otherReaders=[];for(let[locale,other]of others)if(other.editable&&other.value!==null){let surface=interpolationSurface(other.value);otherReaders.push({locale,entry:other,read:surface.read}),otherRows.append(div("locale",h("span",{className:"code"},locale),surface.surface))}else otherRows.append(div("locale",h("span",{className:"code"},locale),h("em",{className:"ink-muted"},other.value===null?"missing":`${other.value} (not writable)`)));let toggle=others.length?h("button",{className:"link",type:"button",onclick:()=>{otherRows.hidden=!otherRows.hidden,toggle.textContent=otherRows.hidden?`Other locales (${others.length})`:"Hide other locales"}},`Other locales (${others.length})`):null,extra=toggle?[div("locale",h("span",{className:"code"},""),toggle),otherRows]:[];frame(element,main.surface,`${key.locale}.${key.key} · ${entry.file}:${entry.line}`,async()=>{let changes=[{locale:key.locale,entry,read:main.read},...otherReaders].flatMap(({locale,entry:entry2,read})=>{let to=read();return to===entry2.value?[]:[{locale,from:entry2.value,to,entry:entry2}]});await saveTranslations(element,key,changes,(change)=>{change.entry.value=change.to})},extra)}async function saveTranslations(element,key,changes,onSaved=()=>{}){let saved=[],result={};try{for(let change of changes){let reply=await api("POST","/translation",{locale:change.locale,key:key.key,original:change.from,text:change.to});if(showTranslation({locale:change.locale,key:key.key},change.from,change.to),onSaved(change),reply.changed)saved.push({locale:change.locale,from:change.from,to:change.to});result={...reply,file:result.file??reply.file,changed:result.changed||reply.changed}}}finally{let label=saved.length>1?`${key.key} in ${saved.length} locales`:key.key,entry=saved.length?record(element,label,{kind:"translation",key:key.key,changes:saved},result.file):void 0;if(saved.length)afterSave(result,"translation",entry)}}async function editMarkdown(element){let range=element.getAttribute(MARKDOWN),tag=element.tagName.toLowerCase(),info=await api("GET","/markdown"+query({range,tag}));if(!info.editable)throw Error("This Markdown block can only get notes.");let words=info.text.replace(/^\s*(?:[-*+]|\d{1,9}[.)])\s+(?:\[[ xX]\]\s+)?/gm,"").replace(/\]\([^)]*\)/g,"").replace(/[*_`#>\[\]]/g,"");assertRendered(element,words.split(`
|
|
387
|
+
`).map((line)=>line.trim().split(/\s+/).slice(0,6).join(" ")).slice(0,8));let surface=div("");if(tag==="ul"||tag==="ol")surface.dataset.newlines="";if(info.prefix.trim())surface.append(chip(info.prefix.trim())," ");let text=field(info.text,!0);surface.append(text),frame(element,surface,`${info.file}:${info.range.split(":")[0]} (Markdown)`,async()=>{let value=valueOf(text);if(value===info.text)return;await saveMarkdown(element,range,info.original,info.prefix,value,info.text,tag)})}async function saveMarkdown(element,range,original,prefix,text,previous,tag){let result=await api("POST","/markdown",{range,original,text,tag});if(!tag?.match(/^[uo]l$/)&&!/[*_`\[\]<>#]/.test(previous+text))replaceText(Array.from(element.childNodes).filter((n)=>n.nodeType===Node.TEXT_NODE),previous,text);let entry=result.changed?record(element,"Markdown edit",{kind:"markdown",range:rangeAfter(range,prefix+text),prefix,from:previous,to:text,tag},result.file):void 0;afterSave(result,"markdown",entry)}function indexPieces(pieces){let index=0;for(let piece of pieces)if(piece.kind==="text")piece.index=index++}function renderedText(html){let template=document.createElement("template");return template.innerHTML=html,template.content.textContent??""}var staticParts=(value)=>value.split(INTERPOLATION).filter((part)=>part&&!INTERPOLATION.test(part));function attributeNode(element,name){let node=document.createElement("span");return node.textContent=element.getAttribute(name)??"",node}function afterSave(result,kind,entry){finish(result,kind,"Saved",entry?{Undo:()=>undo(entry)}:void 0)}var TAB=(()=>{try{let id=sessionStorage.getItem("tensaku-tab")??Math.random().toString(36).slice(2,10);return sessionStorage.setItem("tensaku-tab",id),id}catch{return Math.random().toString(36).slice(2,10)}})();function sendSelection(targets,text){api("POST","/selection",{url:location.pathname,tab:TAB,targets,text}).catch(()=>{})}var hoverBoxes=[],current3=null;function clearHover(){current3=null,hoverBoxes.forEach((b)=>b.remove()),hoverBoxes=[]}function label(element){let stamp=stampOf(element)??nearestStamp(element),md=element.getAttribute(MARKDOWN)?.match(/^(.+):(\d+):\d+-/),key=translationOf(element),where=key?`${key.locale}.${key.key}`:md?`${md[1]}:${md[2]}`:stamp?`${stamp.file}:${stamp.line}`:"";return[tagLabel(element),where]}function highlight(element,className=""){clearHover(),current3=element,hoverBoxes=box(documentRect(element),className,label(element))}var stamped=(element)=>Boolean(element&&!isUi(element)&&element!==document.body&&!outsideScope(element)&&(element.hasAttribute(STAMP)||element.hasAttribute(MARKDOWN)));function step(element,key){if(key==="ArrowUp"){for(let node=element.parentElement;node&&node!==document.body&&!outsideScope(node);node=node.parentElement)if(stamped(node))return node;return null}if(key==="ArrowDown")return Array.from(element.querySelectorAll(`[${STAMP}], [${MARKDOWN}]`)).find((child)=>stamped(child)&&child.offsetParent!==null)??null;let base=modalScope()??document.body,parent=step(element,"ArrowUp")??base,siblings=Array.from(parent.querySelectorAll(`[${STAMP}], [${MARKDOWN}]`)).filter((node)=>stamped(node)&&step(node,"ArrowUp")===(parent===base?null:parent)),index=siblings.indexOf(element);return siblings[index+(key==="ArrowRight"?1:-1)]??null}function selectKey(event){if(mode()!=="inspect"||!current3||menu||isEditing()||activeInShadow()?.matches("textarea, input, [contenteditable]")||typingInPage())return!1;if(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(event.key)&&!event.altKey&&!event.metaKey&&!event.ctrlKey){let next=step(current3,event.key);if(event.preventDefault(),!next)return!0;return highlight(next),next.scrollIntoView({block:"nearest"}),!0}if(event.key==="Enter")return event.preventDefault(),openMenu(current3),!0;if(event.key.toLowerCase()==="c"&&(event.metaKey||event.ctrlKey)&&!getSelection()?.toString())return event.preventDefault(),copy(reference(current3)).then(()=>toast("Copied reference")),!0;return!1}var picked=[],pickedBoxes=[],pickBar=null,hasPicked=()=>picked.length>0;function clearPicked(){picked=[],drawPicked()}function togglePicked(element){clearHover();let index=picked.indexOf(element);if(index>=0)picked.splice(index,1);else picked.push(element);drawPicked()}function pickedRect(){let rects=picked.map(documentRect),left=Math.min(...rects.map((r)=>r.left)),top=Math.min(...rects.map((r)=>r.top));return new DOMRect(left,top,Math.max(...rects.map((r)=>r.right))-left,Math.max(...rects.map((r)=>r.bottom))-top)}function notePicked(){if(!picked.length)return;let elements=picked,targets=elements.flatMap((element)=>targetsFor(element).slice(0,1));pickBar?.remove(),pickBar=null,noteForm(pickedRect(),targets,{},clearPicked,`${elements.length} ${elements.length===1?"element":"elements"}`)}function drawPicked(){if(pickedBoxes.forEach((b)=>b.remove()),pickBar?.remove(),pickBar=null,pickedBoxes=picked.flatMap((element,index)=>box(documentRect(element),"selected",[`${index+1} ${tagLabel(element)}`,""])),!picked.length)return;pickBar=panel(documentRect(picked[picked.length-1]),"menu pick",h("h3",{},`${picked.length} selected`,h("span",{className:"where"},"Shift-click to add or remove")),h("button",{type:"button",onclick:notePicked},icon("pad"),h("span",{},"Add note"),h("kbd",{},"N")),h("button",{type:"button",onclick:clearPicked},icon("close"),h("span",{},"Clear"),h("kbd",{},"Esc"))),pickBar.dataset.tensakuMenu=""}function pickKey(event){if(!pickBar||isEditing()||activeInShadow()?.matches("textarea"))return!1;if(event.key.toLowerCase()==="n"&&!event.metaKey&&!event.ctrlKey&&!event.altKey)return event.preventDefault(),notePicked(),!0;if(event.key==="Escape")return event.preventDefault(),clearPicked(),!0;return!1}var menu=null,menuOpen=()=>menu!==null;function closeMenu(){if(menu?.remove(),menu=null,mode()==="off")clearHover()}function reference(element){let stamp=nearestStamp(element),lines=[`${meta().method} ${location.pathname}${location.search} → ${stamp?`${stamp.file}:${stamp.line}:${stamp.column}`:"(no source stamp)"}`],text=visibleText(element,200);lines.push(`<${tagLabel(element)}>${text?` "${text}"`:""}`);let key=translationOf(element);if(key)lines.push(`Translation: ${key.locale}.${key.key}`);let md=element.closest(`[${MARKDOWN}]`)?.getAttribute(MARKDOWN);if(md)lines.push(`Markdown: ${md}`);let context=contextOf(element);if(context.partials.length>1)lines.push(`Partials: ${context.partials.join(" < ")}`);if(context.controller)lines.push(`Stimulus: ${context.controller}`);if(context.frame)lines.push(`Turbo Frame: #${context.frame}`);let copies=copiesOf(element);if(copies>1)lines.push(`Rendered ${copies} times on this page (loop or repeated partial)`);return lines.join(`
|
|
388
388
|
`)}var hasAttributes=(element)=>["alt","title","placeholder","aria-label"].some((name)=>element.hasAttribute(name));function openMenu(element,selectedText,at){closeMenu();let rect=documentRect(element),spot=at??rect,kind=editKind(element),item=(name,text,action2,shortcut)=>h("button",{type:"button",onclick:()=>{closeMenu(),action2()}},icon(name),h("span",{},text),shortcut?h("kbd",{},shortcut):null),undoable=undoFor(element),list=element.closest(`ul[${MARKDOWN}], ol[${MARKDOWN}]`),[tag,where]=label(element);menu=panel(spot,"menu",h("h3",{},tag,h("span",{className:"where"},where)),kind?item(kind==="attributes"?"tag":"pen",kind==="attributes"?"Edit attributes":"Edit text",()=>edit(element,kind),"E"):null,kind&&kind!=="attributes"&&hasAttributes(element)?item("tag","Edit attributes",()=>edit(element,"attributes")):null,list&&list!==element?item("pen","Edit the whole list",()=>edit(list,"markdown"),"L"):null,item("pad",selectedText?"Note on selected text":"Add note",()=>noteForm(rect,targetsFor(element,selectedText),{},void 0,void 0,spot),"N"),item("copy","Copy reference",async()=>{await copy(reference(element)),toast("Copied reference")},"C"),undoable?item("undo",`Undo ${undoable.label}`,()=>undo(undoable),"U"):null,item("code","Open in editor",()=>openInEditor(element),"O")),menu.dataset.tensakuMenu="",menu.addEventListener("keydown",(event)=>event.stopPropagation()),menu.querySelector("button")?.focus(),sendSelection(targetsFor(element,selectedText),visibleText(element,300))}function menuKey(event){if(!menu||event.key.length!==1||!"cneluo".includes(event.key.toLowerCase())||event.metaKey||event.ctrlKey||event.altKey)return;let match=Array.from(menu.querySelectorAll("button")).find((button)=>button.querySelector("kbd")?.textContent===event.key.toUpperCase());if(match)event.preventDefault(),match.click()}async function openInEditor(element){let md=element.closest(`[${MARKDOWN}]`)?.getAttribute(MARKDOWN)?.match(/^(.+):(\d+):\d+-/),stamp=nearestStamp(element),[file,line]=md&&(!stamp||element.closest(`[${STAMP}]`)?.contains(element.closest(`[${MARKDOWN}]`)))?[md[1],md[2]]:stamp?[stamp.file,String(stamp.line)]:[];if(!file)return toast("This element has no source position.",{error:!0});try{let{url}=await api("GET","/editor"+query({file,line}));if(url)location.href=url;else toast(`Set RAILS_EDITOR (vscode, cursor, zed, …) to open files from here. ${file}:${line}`,{timeout:8000})}catch(error){toast(error.message,{error:!0})}}var EDITABLE_BATCH=5000,outlines=[],asking=!1;function editableElements(){let elements=new Set;return document.body.querySelectorAll(`[${STAMP}], [${MARKDOWN}], *`).forEach((element)=>{if(isUi(element)||outsideScope(element)||!element.offsetParent&&getComputedStyle(element).position!=="fixed")return;if(editKind(element))elements.add(element)}),Array.from(elements)}function drawOutlines(){if(outlines.forEach((b)=>b.remove()),outlines=[],mode()!=="edit")return;let elements=editableElements(),unknown=Array.from(new Set(elements.filter((element)=>element.hasAttribute(STAMP)&&hasOwnText(element)).map((element)=>element.getAttribute(STAMP)).filter((stamp)=>!templateText.has(stamp)))).slice(0,EDITABLE_BATCH);if(unknown.length){if(asking)return;asking=!0,api("POST","/editable",{stamps:unknown}).then(({editable})=>unknown.forEach((stamp)=>templateText.set(stamp,editable[stamp]??!1))).catch(()=>unknown.forEach((stamp)=>templateText.set(stamp,!0))).finally(()=>{asking=!1,drawOutlines()});return}for(let element of elements)outlines.push(...box(documentRect(element),"edit"))}var pending=[];function onDocument(type,listener,options){pending.push(()=>document.addEventListener(type,listener,options))}function onWindow(type,listener){pending.push(()=>addEventListener(type,listener))}onMode((next)=>{if(next!=="inspect"&&hasPicked())clearPicked();clearHover(),closeMenu(),drawOutlines(),syncCursor()});function syncCursor(){document.documentElement.style.cursor=altHeld||isPicking()||mode()==="inspect"?cursor("highlighter",INK.highlighter):mode()==="edit"?cursor("pen",INK.pen):""}onPick(()=>{clearHover(),syncCursor()});var altHeld=!1,pointer=null,altPreviews=(event)=>event.altKey&&!event.metaKey&&!event.ctrlKey&&!isEditing()&&!typingInPage()&&!activeInShadow()?.matches("textarea, input");function setAltHeld(held){if(held===altHeld)return;if(altHeld=held,syncCursor(),!held){if(mode()!=="inspect")clearHover();return}let under=pointer&&!menuOpen()?document.elementFromPoint(pointer.x,pointer.y):null,element=under&&!isUi(under)?sourceElement(under):null;if(element)highlight(element)}var drag=null,suppressClick=!1;function pageTarget(event){let target=event.composedPath()[0];if(isUi(target)||target instanceof Node&&isUi(target.parentElement))return null;return sourceElement(target)}onDocument("mousemove",(event)=>{if(drag)return updateDrag(event);if(pointer={x:event.clientX,y:event.clientY},setAltHeld(altPreviews(event)),mode()==="off"&&!altHeld&&!isPicking()||menuOpen()||isEditing())return;let element=pageTarget(event);if(!element)return clearHover();let editing=mode()==="edit"&&!altHeld&&!isPicking();if(editing&&!editKind(element))return clearHover();highlight(element,editing?"hover-edit":"")},!0);onDocument("mousedown",(event)=>{if(event.button!==0||isUi(event.target))return;let altDrag=event.altKey;if(altDrag)event.preventDefault();if(mode()!=="inspect"&&!altDrag||menuOpen()||isEditing()||isPicking())return;if(event.shiftKey){event.preventDefault();return}drag={x:event.pageX,y:event.pageY,area:null}},!0);function updateDrag(event){if(!drag)return;let width=Math.abs(event.pageX-drag.x),height=Math.abs(event.pageY-drag.y);if(!drag.area&&Math.hypot(width,height)<8)return;if(!drag.area)clearHover(),drag.area=div("area"),layer.append(drag.area);Object.assign(drag.area.style,{left:`${Math.min(event.pageX,drag.x)}px`,top:`${Math.min(event.pageY,drag.y)}px`,width:`${width}px`,height:`${height}px`}),event.preventDefault()}onDocument("mouseup",(event)=>{if(!drag)return;let area=drag.area,start=drag;if(drag=null,!area)return;suppressClick=!0;let rect=new DOMRect(Math.min(event.pageX,start.x),Math.min(event.pageY,start.y),Math.abs(event.pageX-start.x),Math.abs(event.pageY-start.y)),elements=elementsInArea(rect),highlights=elements.flatMap((element)=>box(documentRect(element),"selected")),targets=elements.flatMap((element)=>targetsFor(element).slice(0,1));noteForm(rect,targets,{rect:{x:Math.round(rect.x),y:Math.round(rect.y),width:Math.round(rect.width),height:Math.round(rect.height)}},()=>{area.remove(),highlights.forEach((b)=>b.remove())},void 0,new DOMRect(event.pageX,event.pageY,0,0)),sendSelection(targets,"")},!0);onDocument("click",(event)=>{if(suppressClick){suppressClick=!1,event.preventDefault(),event.stopPropagation();return}if(isUi(event.target))return;let element=pageTarget(event),at=new DOMRect(event.pageX,event.pageY,0,0);if(isPicking()){if(event.preventDefault(),event.stopImmediatePropagation(),element)pick(element,at);return}let selectedIn=(within)=>{let selection=getSelection()?.toString().trim();return selection&&within.contains(getSelection().anchorNode)?selection:void 0};if(event.altKey&&element){if(event.preventDefault(),event.stopImmediatePropagation(),closeMenu(),event.shiftKey)noteForm(documentRect(element),targetsFor(element,selectedIn(element)),{},void 0,void 0,at);else openMenu(element,selectedIn(element),at);return}if(mode()==="off"&&!menuOpen())return;if(event.preventDefault(),event.stopImmediatePropagation(),menuOpen()||isEditing()){closeMenu();return}if(!element)return;if(mode()==="edit"){let kind=editKind(element);if(kind)edit(element,kind);return}if(event.shiftKey){togglePicked(element);return}if(hasPicked())clearPicked();openMenu(element,selectedIn(element),at)},!0);onDocument("pointerdown",closeOutside,!0);function undoKeys(event){if(!(isApple?event.metaKey:event.ctrlKey)||event.altKey||isEditing()||typingInPage()||activeInShadow()?.matches("textarea, input, [contenteditable]"))return!1;let key=event.key.toLowerCase(),wantsRedo=key==="z"&&event.shiftKey||!isApple&&key==="y";if(key==="z"&&!event.shiftKey&&canUndo())return event.preventDefault(),undo(),!0;if(wantsRedo&&canRedo())return event.preventDefault(),redo(),!0;return!1}onDocument("keydown",(event)=>{if(event.key==="Alt")setAltHeld(altPreviews(event));let shortcut=hasCommandModifier(event)?toolForEvent(event):null;if(shortcut){event.preventDefault(),pressShortcut(shortcut);return}if(undoKeys(event))return;if(menuKey(event),selectKey(event))return;if(pickKey(event))return;if(event.key==="Escape"&&escape())event.preventDefault()},!0);function escape(){if(isEditing()||typingInPage())return!1;if(cancelPick())return!0;let field2=activeInShadow();if(field2?.matches("textarea, input, [contenteditable]"))return field2.blur(),!0;if(popoverOpen())closePopover();else if(menuOpen())closeMenu();else if(closeNote()||closeSidePanel())return!0;else if(mode()!=="off")return setMode("off"),!1;else return closeToolbar(),!1;return!0}onDocument("keyup",(event)=>{if(event.key==="Alt")setAltHeld(!1)},!0);onWindow("blur",()=>setAltHeld(!1));var redraw=0;function scheduleRedraw(){cancelAnimationFrame(redraw),redraw=requestAnimationFrame(()=>{if(drawPins(),drawOutlines(),hasPicked())drawPicked()})}onWindow("resize",()=>{placeDock(),scheduleRedraw()});onScopeChange(()=>{clearHover(),scheduleRedraw()});var path=location.pathname;function pageChanged(){path=location.pathname,closeMenu(),clearPicked(),closeEditor(),clearHover(),load(),scheduleRedraw()}onDocument("turbo:load",pageChanged);onDocument("turbo:frame-load",scheduleRedraw);onWindow("popstate",pageChanged);pending.push(()=>onRefresh(()=>{templateText.clear(),scheduleRedraw(),load()}));pending.push(()=>setInterval(()=>{if(location.pathname!==path)pageChanged();else drawPins()},1000));onDocument("scroll",(event)=>{if(event.target!==document&&!isUi(event.target))scheduleRedraw()},{capture:!0,passive:!0});function boot(){if(window.__tensaku)return;window.__tensaku=!0,pending.forEach((add)=>add()),watch(),watchTopLayer(),placeDock(),load(),poll(),syncPins()}boot();})();
|
data/lib/tensaku/version.rb
CHANGED