tensaku 0.2.2 → 0.3.0

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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 147e87281f8421a4cf77646bcbfe8152a230f1ea4b1e313bb290769cf49fc0e6
4
- data.tar.gz: 58bf0b7360dbe7570042955a26a3602edc59631ee0de28cee2e56f64c46bf12d
3
+ metadata.gz: e8c394724c7f5587635c17b0c4c6e3ff7c02351ac3d432554836ee35255179fe
4
+ data.tar.gz: 3dcdeeb2b5cfc2fd56ed28e00dd399c9529ea04edd335ba5ce220f74459e6ca2
5
5
  SHA512:
6
- metadata.gz: 5578d740e98b26eccdb059529559f8adcd76909b8f3722eef6efc491ec0ea9fa05573c290535575dd609d2eb9988e2e93ae5666c9773ba162094dc34122b6a3b
7
- data.tar.gz: f4b24cada858233e727833563c9fe1210bf0793c21569bbd6f9bb5bf542c8d5168119860f5707b22ab129600455a71281759b48f6d81f4e8bd8e677f0975485e
6
+ metadata.gz: 71966e3cb764655f9a128df10bf084327692668c80f5bfc6708e43d5ab41e8a4db7743b1ebe033a1df369242e9b2ff156c2718c90cd5951bc420586f527c38ea
7
+ data.tar.gz: ebe3540b54a22d691b0a3fa9b9197f3ec76066fa078d80515078697871af8575835c4043b8345983ebd575e7218d783ffc28f30589ca289132bceebc0eae39f1
data/CHANGELOG.md CHANGED
@@ -1,5 +1,52 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.0 (2026-11-15)
4
+
5
+ ### Notes
6
+
7
+ - A pin that finds its element only by the old position, because the element's text changed, is
8
+ drawn as a guess. The note's card asks whether it is still the right element: **Keep here** or
9
+ **Pick again**, which takes the next click on the page. The note then points at that element and an
10
+ open note is sent again. A card whose element is gone also offers **Pick again**.
11
+ - While its pin is a guess and the element's source changed since the note was written, an open note
12
+ is held: agents don't get it from `watch_notes`, `start_note` refuses it, and `list_notes` marks it
13
+ held. Notes now record a digest of their element's source for this check. The database gets a
14
+ `held_at` column.
15
+
16
+ ### Overlay
17
+
18
+ - Tensaku works over native dialogs and popovers. The overlay drew under a `<dialog>` opened with
19
+ `showModal()`, and the dialog made it inert, so its menu and note form could not be clicked or typed
20
+ in. While a modal dialog or a popover is open, the overlay now moves inside the topmost one and shows
21
+ itself as a popover. Area notes leave out what a dialog or an app's CSS modal covers, and select
22
+ mode's arrow keys, edit mode's outlines and the pins stay inside an open modal dialog.
23
+ - Escape that closes Tensaku's menu, note, popover or panel no longer also closes the app's dialog.
24
+ - Clicks and keys on the overlay no longer reach the app's event handlers, so they don't close the
25
+ app's dialogs or dropdowns or trigger its keyboard shortcuts.
26
+ - The Archive and All pages tabs refresh after a change made from the panel. A note reopened from the
27
+ archive could stay listed there when the dev server's change event arrived before the page had
28
+ fetched the archive again.
29
+
30
+ ## 0.2.3 (2026-11-14)
31
+
32
+ ### Translations
33
+
34
+ - Translation markers are only added while a template renders. Text translated in a controller
35
+ action, such as a flash message, is plain text again: it can't be traced back to its key from the
36
+ page, but code that measures, compares or stores it no longer sees a marker.
37
+
38
+ - A translation that names an asset, such as `image_tag t("hero.image")` with a screenshot per
39
+ locale, resolves again. Its marker made the asset lookup fail with `Propshaft::MissingAssetError`.
40
+ - A page no longer freezes when the app cuts a translated string short, such as a title truncated
41
+ for `og:title`. The cut marker could not be stripped, the overlay wrote the same value back, and
42
+ its observer saw that write as a new change, forever. Cut markers are now stripped, and an
43
+ unchanged value is never written.
44
+ - Markers no longer reach your data. A translated string assigned to a model attribute, such as a
45
+ default category name made in a callback, loses its marker, so it is validated and saved as plain
46
+ text. Before, a length validation could fail, or the marker was stored in the database.
47
+ - A blank translation gets no marker, so `t("step.subtitle").present?` stays false and the page
48
+ doesn't render an empty element that only exists in development.
49
+
3
50
  ## 0.2.2 (2026-11-14)
4
51
 
5
52
  ### Overlay
@@ -1,8 +1,12 @@
1
- (()=>{function meta(){let tag=document.querySelector('meta[name="tensaku"]');return{token:tag?.dataset.tensakuToken??"",root:tag?.dataset.tensakuRoot??"/__tensaku",method:tag?.dataset.tensakuRequest??"GET"}}class ApiError extends Error{status;stale;constructor(message,status,stale){super(message);this.status=status;this.stale=stale}}async function api(method,path,body){let{token,root}=meta(),response=await fetch(root+path,{method,headers:{"Content-Type":"application/json","X-Tensaku-Token":token,Accept:"application/json"},body:body===void 0?void 0:JSON.stringify(body),credentials:"same-origin"}),data=(response.headers.get("content-type")??"").includes("json")?await response.json():await response.text();if(!response.ok){let message=typeof data==="object"&&data?.error?data.error:`Tensaku request failed (${response.status})`;throw new ApiError(message,response.status,Boolean(data?.stale))}return data}var query=(params)=>"?"+new URLSearchParams(Object.entries(params).filter((entry)=>entry[1]!==void 0)).toString(),isApple=/mac|iphone|ipad|ipod/i.test(navigator.platform||navigator.userAgent);var PATHS={highlighter:'<path d="M13.2 4.3l6.5 6.5-8.6 8.6-6.5-6.5z"/><path d="M11 6.6l6.4 6.4"/><path class="ink" d="M4.6 12.9l6.5 6.5-3.4 1.5-4.6-4.6z"/><path class="ink" d="M2.6 22h6.2" stroke-width="2.4"/>',pen:'<path d="M16.6 3.4l4 4-10.8 10.8-4-4z"/><path d="M14.4 5.6l4 4"/><path class="ink" d="M5.8 14.2l4 4-5.6 1.6z"/>',pad:'<path class="ink" d="M4.5 4.5h15v9.8l-5.2 5.2H4.5z"/><path d="M19.5 14.3h-5.2v5.2"/><path d="M8 9h8M8 12h4.5"/>',copy:'<rect x="8.5" y="8.5" width="11" height="11" rx="2.2"/><path d="M15.5 8.5V6.2a1.7 1.7 0 0 0-1.7-1.7H6.2a1.7 1.7 0 0 0-1.7 1.7v7.6a1.7 1.7 0 0 0 1.7 1.7h2.3"/>',close:'<path d="M6.5 6.5l11 11M17.5 6.5l-11 11"/>',code:'<path d="M8.5 7.5L4 12l4.5 4.5M15.5 7.5L20 12l-4.5 4.5"/>',undo:'<path d="M9 14.5L4.5 10 9 5.5"/><path d="M4.5 10h9.2a5.8 5.8 0 0 1 0 11.6H11"/>',tag:'<path d="M3.8 12.6V4.5a.7.7 0 0 1 .7-.7h8.1l7.6 7.6-8.8 8.8z"/><circle cx="8.3" cy="8.3" r="1.4"/>',eye:'<path d="M2.5 12S6 5.5 12 5.5 21.5 12 21.5 12 18 18.5 12 18.5 2.5 12 2.5 12z"/><circle cx="12" cy="12" r="2.8"/>',"eye-off":'<path d="M2.5 12S6 5.5 12 5.5c1.9 0 3.6.7 5 1.6M21.5 12s-3.5 6.5-9.5 6.5c-1.9 0-3.6-.7-5-1.6"/><path d="M4 20L20 4"/>',trash:'<path d="M4.5 7h15M9.5 7V4.8h5V7M6.5 7l.9 12.2a1.6 1.6 0 0 0 1.6 1.3h6a1.6 1.6 0 0 0 1.6-1.3L17.5 7"/><path d="M10 10.5v6M14 10.5v6"/>',history:'<path d="M4 12a8 8 0 1 0 2.4-5.7"/><path d="M4 4.5v3.8h3.8"/><path d="M12 8v4.3l2.8 1.8"/>',sliders:'<path d="M4 8h9M17 8h3M4 16h3M11 16h9"/><circle cx="15" cy="8" r="2.2"/><circle cx="9" cy="16" r="2.2"/>',pause:'<path d="M9 5.5v13M15 5.5v13"/>',play:'<path d="M8 5.5l10 6.5-10 6.5z"/>',plane:'<path d="M20.5 3.5L3.5 10.4l6.6 3 3 6.6z"/><path d="M10.1 13.4l10.4-9.9"/>',"plane-flying":'<path class="ink" d="M20.5 3.5L3.5 10.4l6.6 3 3 6.6z"/><path d="M10.1 13.4l10.4-9.9"/><path d="M3 16.5l3-1.2M4.5 20l3.4-1.6" stroke-width="1.6"/>',check:'<path class="stroke" d="M5 12.8c1.6 1.2 2.9 2.7 3.9 4.6C11 12.3 14.6 8 19.5 5"/>'};function icon(name,ink){let template=document.createElement("template");template.innerHTML=`<svg class="icon icon-${name}" viewBox="0 0 24 24" aria-hidden="true" focusable="false">${PATHS[name]}</svg>`;let svg=template.content.firstElementChild;if(ink)svg.style.setProperty("--ink-color",ink);return svg}function logo(){let template=document.createElement("template");return template.innerHTML='<svg class="logo" viewBox="0 3.65 100 100" aria-hidden="true" focusable="false"><path d="M48.2 48.6L48.9 47.2L49.7 46.4L51.1 45.6L52.5 45.3L54.1 45.3L56.9 46.3L58.5 47.6L60.2 49.9L60.5 50.6L61.3 53.8L61.1 57.4L59.7 61L59.1 61.9L57.8 63.6L56.3 65.1L54.4 66.4L51.2 67.9L48.8 68.5L44.9 68.7L42.3 68.4L39.6 67.7L37 66.5L34.5 65L32.2 63L30.1 60.7L27.6 56.6L26.4 53.5L26 51.8L25.5 48.4L25.4 44.9L25.9 41.3L26.4 39.5L28.5 34.2L30.6 30.9L33.2 27.9L36.3 25.2L38 24L39.8 22.9L43.7 21.2L47.8 19.9L50 19.5L50.7 16.8L51.5 15.6L53.2 13.8L55 12.6L57.8 11.4L59.8 10.8L61.7 10.5L64.7 10.4L69.5 11.2L74 13L75.7 14L78 15.8L80.7 18.6L82.4 21L83.3 22.7L84.1 24.5L85.1 28.4L85.3 30.3L85.1 33.4L84.7 35.4L83.9 37.5L82.3 39.8L80.3 41.2L83.6 42.5L85.4 43.6L86.9 45L88.7 47.2L90.4 50.6L91 52.4L91.7 56.9L91.7 58.8L90.9 63.4L90 66L89.2 67.7L86.6 71.5L83.9 74L82.4 75.1L79 76.8L77.2 77.4L74.2 77.8L73.2 77.8L70.9 77.4L70.6 78.2L68.8 77L69.9 79.8L70 81.2L69.3 84.7L68.4 86.7L67.3 88.4L64.6 91.5L62.2 93.3L58.7 95.2L56.8 95.9L53.9 96.6L48.9 96.9L44 96.1L40.3 94.7L37.7 93.2L35.3 91.4L33.9 89.9L32.1 87.5L31.1 85.6L30.1 82.3L30 81L31 77L28.5 78L25.1 78.3L22.1 77.9L18.5 76.5L15.3 74.4L13.2 72.5L11.4 70.3L9.9 67.9L9.1 66.2L8.2 63.5L7.5 59.8L7.5 56L8.2 52.3L9.6 48.7L12.4 44.7L15.8 42.2L17 41.7L17.4 41.1L19.3 40.9L17.9 39.7L17 38.6L15.6 35.4L15.1 32.4L15.3 28.4L16.3 24.7L18 21.2L20.3 18.1L23.9 14.9L27.2 12.9L29.9 11.8L31.8 11.3L35.6 10.8L39.5 11.1L42.4 11.8L45.2 13.1L46.1 13.7L47.8 15.1L49.4 17L50.1 18.6L50.9 16.6L51.7 15.4L53.4 13.7L55.2 12.5L58.9 11"/></svg>',template.content.firstElementChild}function cursor(name,ink){let svg=`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#1d1b19" stroke-width="1.6" stroke-linejoin="round" stroke-linecap="round"><g fill="#fffdf6">${PATHS[name].replace(/class="ink"/g,`fill="${ink}"`)}</g></svg>`;return`url("data:image/svg+xml,${encodeURIComponent(svg)}") 3 21, crosshair`}var DIGITS=["​","‌","‍","⁠"],PATTERN=/⁣[​‌‍⁠]+⁣/g,nodeKeys=new WeakMap,attributeKeys=new WeakMap;var textNodesOf=(element)=>Array.from(element.childNodes).filter((node)=>node.nodeType===Node.TEXT_NODE);function recordText(node){let parent=node.parentElement;if(!parent)return;let entries=[];textNodesOf(parent).forEach((text,index)=>nodeKeys.get(text)?.forEach((key)=>entries.push([index,key.locale,key.key]))),writeRecord(parent,"data-tensaku-t",entries)}function recordAttributes(element){let entries=Array.from(attributeKeys.get(element)??[]).map(([name,key])=>[name,key.locale,key.key]);writeRecord(element,"data-tensaku-a",entries)}function writeRecord(element,name,entries){let value=JSON.stringify(entries);if(entries.length&&element.getAttribute(name)!==value)element.setAttribute(name,value)}function readRecord(element,name){try{let value=JSON.parse(element.getAttribute(name)??"[]");return Array.isArray(value)?value:[]}catch{return[]}}function restore(root=document){root.querySelectorAll("[data-tensaku-t]").forEach((element)=>{let texts=textNodesOf(element);for(let[index,locale,key]of readRecord(element,"data-tensaku-t")){let node=texts[index];if(!node||nodeKeys.get(node)?.some((k)=>k.key===key&&k.locale===locale))continue;nodeKeys.set(node,[...nodeKeys.get(node)??[],{locale,key}])}}),root.querySelectorAll("[data-tensaku-a]").forEach((element)=>{let map=attributeKeys.get(element)??new Map;for(let[name,locale,key]of readRecord(element,"data-tensaku-a"))if(!map.has(name))map.set(name,{locale,key});if(map.size)attributeKeys.set(element,map)})}function decode(marker){let digits=[...marker.slice(1,-1)].map((char)=>DIGITS.indexOf(char));if(digits.length%4!==0||digits.includes(-1))return null;let bytes=new Uint8Array(digits.length/4);for(let i=0;i<bytes.length;i++){let[a,b,c,d]=digits.slice(i*4,i*4+4);bytes[i]=a<<6|b<<4|c<<2|d}let text=new TextDecoder().decode(bytes),colon=text.indexOf(":");return colon>0?{locale:text.slice(0,colon),key:text.slice(colon+1)}:null}function extract(text){let keys=[];return{text:text.replace(PATTERN,(marker)=>{let key=decode(marker);if(key)keys.push(key);return""}),keys}}function stripText(node){if(!node.data.includes("⁣"))return;let{text,keys}=extract(node.data);if(node.data=text,keys.length){let known=nodeKeys.get(node)??[];nodeKeys.set(node,[...known,...keys.filter((key)=>!known.some((k)=>k.key===key.key&&k.locale===key.locale))]),recordText(node)}}function stripAttributes(element){for(let attribute of Array.from(element.attributes)){if(!attribute.value.includes("⁣"))continue;let{text,keys}=extract(attribute.value);if(element.setAttribute(attribute.name,text),keys.length){let map=attributeKeys.get(element)??new Map;map.set(attribute.name,keys[keys.length-1]),attributeKeys.set(element,map),recordAttributes(element)}}if(element instanceof HTMLTextAreaElement&&element.value.includes("⁣"))element.value=extract(element.value).text}function strip(root){if(root.nodeType===Node.TEXT_NODE)return stripText(root);if(!(root instanceof Element||root instanceof Document||root instanceof DocumentFragment))return;if(root instanceof Element)stripAttributes(root);let walker=document.createTreeWalker(root,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_TEXT);for(let node=walker.nextNode();node;node=walker.nextNode())if(node.nodeType===Node.TEXT_NODE)stripText(node);else stripAttributes(node)}function watch(){if(strip(document.documentElement),document.title.includes("⁣"))document.title=extract(document.title).text;document.addEventListener("turbo:render",()=>restore()),document.addEventListener("turbo:frame-render",()=>restore()),new MutationObserver((records)=>{for(let record of records)if(record.type==="characterData")stripText(record.target);else if(record.type==="attributes")stripAttributes(record.target);else record.addedNodes.forEach((node)=>strip(node))}).observe(document.documentElement,{subtree:!0,childList:!0,characterData:!0,attributes:!0})}function textKeys(element){let found=[],walker=document.createTreeWalker(element,NodeFilter.SHOW_TEXT);for(let node=walker.nextNode();node;node=walker.nextNode()){let keys=nodeKeys.get(node);if(!keys)continue;let owner=node.parentElement?.closest("[data-herb-source], [data-md-source]");if(owner&&owner!==element&&element.contains(owner))continue;keys.forEach((key)=>found.push({node,key}))}return found}function attributeKey(element,name){return attributeKeys.get(element)?.get(name)}function attributeKeyNames(element){return Array.from(attributeKeys.get(element)?.keys()??[])}function nodesForKey(key){let nodes=[],walker=document.createTreeWalker(document.body,NodeFilter.SHOW_TEXT);for(let node=walker.nextNode();node;node=walker.nextNode())if(nodeKeys.get(node)?.some((k)=>k.key===key.key&&k.locale===key.locale))nodes.push(node);return nodes}function elementsWithAttributeKey(key){let found=[];return document.querySelectorAll("*").forEach((element)=>{attributeKeys.get(element)?.forEach((k,name)=>{if(k.key===key.key&&k.locale===key.locale)found.push({element,name})})}),found}var STAMP="data-herb-source",MARKDOWN="data-md-source",SOURCE_SELECTOR=`[${STAMP}], [${MARKDOWN}]`;function parseStamp(value){let match=value?.match(/^(.+):(\d+):(\d+)$/);return match?{file:match[1],line:Number(match[2]),column:Number(match[3]),value}:null}function isUi(node){return node instanceof Element&&Boolean(node.closest("[data-tensaku-ui]"))}function sourceElement(node){let start=node instanceof Element?node:node?.parentElement;if(!start||isUi(start))return null;let group=start.closest("[data-tensaku-group]");if(group)return group;return start.closest(SOURCE_SELECTOR)}function stampOf(element){return parseStamp(element.getAttribute(STAMP))}function nearestStamp(element){return parseStamp(element.closest(`[${STAMP}]`)?.getAttribute(STAMP))}function copiesOf(element){let value=element.getAttribute(STAMP);return value?document.querySelectorAll(`[${STAMP}="${CSS.escape(value)}"]`).length:1}function partialChain(element){let files=[];for(let node=element;node;node=node.parentElement){let stamp=parseStamp(node.getAttribute(STAMP));if(stamp&&files[files.length-1]!==stamp.file)files.push(stamp.file)}return files.filter((file,index)=>files.indexOf(file)===index)}function contextOf(element){return{partials:partialChain(element),controller:element.closest("[data-controller]")?.getAttribute("data-controller")??void 0,frame:element.closest("turbo-frame")?.id??void 0}}function tagLabel(element){let tag=element.tagName.toLowerCase();if(element.id)return`${tag}#${element.id}`;let first=Array.from(element.classList).find((name)=>!name.startsWith("tensaku"));return first?`${tag}.${first}`:tag}function visibleText(element,limit=120){let text=(element instanceof HTMLElement?element.innerText:element.textContent??"").replace(/\s+/g," ").trim();return text.length>limit?text.slice(0,limit-1)+"…":text}function hasOwnText(element){for(let node of Array.from(element.childNodes))if(node.nodeType===Node.TEXT_NODE&&node.textContent.trim())return!0;return!1}var MARKDOWN_EDITABLE=new Set(["p","h1","h2","h3","h4","h5","h6","li","blockquote"]),ATTRIBUTES=["alt","title","placeholder","aria-label","value"],templateText=new Map;function editKind(element){if(translationOf(element))return"translation";if(element.hasAttribute(MARKDOWN)&&MARKDOWN_EDITABLE.has(element.tagName.toLowerCase()))return"markdown";if(element.hasAttribute(STAMP)&&hasOwnText(element)&&templateText.get(element.getAttribute(STAMP))!==!1)return"template";if(editableAttributes(element).length)return"attributes";return null}function translationOf(element){let keys=textKeys(element);if(!keys.length)return null;let own=keys[0].node.data.trim(),all=(element.textContent??"").replace(/\s+/g," ").trim();return own&&all.length<=own.length*2+20?keys[0].key:null}function editableAttributes(element){let names=ATTRIBUTES.filter((name)=>element.hasAttribute(name)).filter((name)=>name!=="value"||element.matches("button, input[type=submit], input[type=button], input[type=reset]")),fromStamp=element.hasAttribute(STAMP)?names:[];return Array.from(new Set([...fromStamp,...attributeKeyNames(element).filter((name)=>ATTRIBUTES.includes(name))]))}function documentRect(element){let rect=element.getBoundingClientRect();return new DOMRect(rect.left+scrollX,rect.top+scrollY,rect.width,rect.height)}function contentRect(element){let outer=documentRect(element),range=document.createRange();range.selectNodeContents(element);let inner=range.getBoundingClientRect();if(!inner.width||!inner.height)return outer;let left=Math.max(outer.left,inner.left+scrollX),top=Math.max(outer.top,inner.top+scrollY);return new DOMRect(left,top,Math.min(outer.right,inner.right+scrollX)-left,Math.min(outer.bottom,inner.bottom+scrollY)-top)}function utf8Length(text){return new TextEncoder().encode(text).length}function typingInPage(){let active=document.activeElement;return active instanceof HTMLElement&&!isUi(active)&&(active.matches("input, textarea, select")||active.isContentEditable)}var classesOf=(element)=>Array.from(element.classList).filter((name)=>!name.startsWith("tensaku")).slice(0,12);function targetsFor(element,selectedText){let block=element.closest(`[${MARKDOWN}]`),stamped=element.closest(`[${STAMP}]`);if(block&&(!stamped||stamped.contains(block)))return[{kind:"markdown",md:block.getAttribute(MARKDOWN)??void 0,text:selectedText||visibleText(element,300),tag:tagLabel(element),context:contextOf(element)}];let stamp=nearestStamp(element),targets=[{kind:selectedText?"text":"element",stamp:stamp?.value,text:selectedText||visibleText(element,300),tag:tagLabel(element),classes:classesOf(element),context:contextOf(element)}],key=translationOf(element)??textKeys(element)[0]?.key;if(key)targets.push({kind:"translation",key:key.key,locale:key.locale,text:visibleText(element,300)});let md=element.closest(`[${MARKDOWN}]`)?.getAttribute(MARKDOWN);if(md)targets.push({kind:"markdown",md,text:visibleText(element,300),tag:tagLabel(element)});return targets}function elementsInArea(rect){let candidates=Array.from(document.querySelectorAll(`[${STAMP}], [${MARKDOWN}]`)).filter((element)=>{if(element===document.body||element.closest("[data-tensaku-ui]"))return!1;let box=contentRect(element);if(!box.width||!box.height)return!1;return Math.max(0,Math.min(box.right,rect.right)-Math.max(box.left,rect.left))*Math.max(0,Math.min(box.bottom,rect.bottom)-Math.max(box.top,rect.top))/(box.width*box.height)>=0.5}),outermost=candidates.filter((element)=>!candidates.some((other)=>other!==element&&other.contains(element)));if(outermost.length)return outermost.slice(0,20);let fallback=document.elementFromPoint(rect.left+rect.width/2-scrollX,rect.top+rect.height/2-scrollY)?.closest(`[${STAMP}], [${MARKDOWN}]`);return fallback?[fallback]:[]}function phraseRects(note){let target=note.targets.find((t)=>t.kind==="text"&&t.text&&t.stamp),element=target&&targetElement(target);if(!target||!element?.textContent?.includes(target.text))return[];let nodes=[],starts=[],all="",walker=document.createTreeWalker(element,NodeFilter.SHOW_TEXT);while(walker.nextNode()){let node=walker.currentNode;starts.push(all.length),nodes.push(node),all+=node.data}let at=all.indexOf(target.text);if(at<0)return[];let end=at+target.text.length,lastIndex=(test)=>{for(let i=starts.length-1;i>=0;i--)if(test(starts[i]))return i;return 0},first=lastIndex((start)=>start<=at),last=lastIndex((start)=>start<end),range=document.createRange();return range.setStart(nodes[first],at-starts[first]),range.setEnd(nodes[last],end-starts[last]),Array.from(range.getClientRects()).filter((r)=>r.width>0).map((r)=>new DOMRect(r.left+scrollX,r.top+scrollY,r.width,r.height))}function anchorFor(note){if(note.rect)return new DOMRect(note.rect.x,note.rect.y,note.rect.width,note.rect.height);for(let target of note.targets){let element=targetElement(target);if(element)return contentRect(element)}return null}function pointFor(note){let target=note.targets.find((t)=>t.point),element=target&&targetElement(target);if(!target?.point||!element)return null;let rect=documentRect(element);return new DOMRect(rect.x+target.point[0]*rect.width,rect.y+target.point[1]*rect.height,0,0)}function targetElement(target){let attribute=target.stamp?STAMP:target.md?MARKDOWN:null,value=target.stamp??target.md;if(!attribute||!value)return null;let elements=Array.from(document.querySelectorAll(`[${attribute}="${CSS.escape(value)}"]`));if(!target.text)return elements[0]??null;let text=target.text.replace(/…$/,""),written=(candidates)=>candidates.find((element)=>visibleText(element,300)===target.text)??candidates.find((element)=>visibleText(element,300).startsWith(text))??candidates.find((element)=>target.kind==="text"&&element.textContent?.includes(text)),here=written(elements);if(here)return here;let tag=target.tag?.split(/[.#]/)[0],sameTag=(element)=>!tag||element.tagName.toLowerCase()===tag,file=value.match(/^(.+?):\d+/)?.[1],inFile=file?Array.from(document.querySelectorAll(`[${attribute}^="${CSS.escape(file)}:"]`)).filter(sameTag):[];return written(inFile)??elements.find(sameTag)??null}var overlay_default=`:host { all: initial; }
1
+ (()=>{function meta(){let tag=document.querySelector('meta[name="tensaku"]');return{token:tag?.dataset.tensakuToken??"",root:tag?.dataset.tensakuRoot??"/__tensaku",method:tag?.dataset.tensakuRequest??"GET"}}class ApiError extends Error{status;stale;constructor(message,status,stale){super(message);this.status=status;this.stale=stale}}async function api(method,path,body){let{token,root}=meta(),response=await fetch(root+path,{method,headers:{"Content-Type":"application/json","X-Tensaku-Token":token,Accept:"application/json"},body:body===void 0?void 0:JSON.stringify(body),credentials:"same-origin"}),data=(response.headers.get("content-type")??"").includes("json")?await response.json():await response.text();if(!response.ok){let message=typeof data==="object"&&data?.error?data.error:`Tensaku request failed (${response.status})`;throw new ApiError(message,response.status,Boolean(data?.stale))}return data}var query=(params)=>"?"+new URLSearchParams(Object.entries(params).filter((entry)=>entry[1]!==void 0)).toString(),isApple=/mac|iphone|ipad|ipod/i.test(navigator.platform||navigator.userAgent);var PATHS={highlighter:'<path d="M13.2 4.3l6.5 6.5-8.6 8.6-6.5-6.5z"/><path d="M11 6.6l6.4 6.4"/><path class="ink" d="M4.6 12.9l6.5 6.5-3.4 1.5-4.6-4.6z"/><path class="ink" d="M2.6 22h6.2" stroke-width="2.4"/>',pen:'<path d="M16.6 3.4l4 4-10.8 10.8-4-4z"/><path d="M14.4 5.6l4 4"/><path class="ink" d="M5.8 14.2l4 4-5.6 1.6z"/>',pad:'<path class="ink" d="M4.5 4.5h15v9.8l-5.2 5.2H4.5z"/><path d="M19.5 14.3h-5.2v5.2"/><path d="M8 9h8M8 12h4.5"/>',copy:'<rect x="8.5" y="8.5" width="11" height="11" rx="2.2"/><path d="M15.5 8.5V6.2a1.7 1.7 0 0 0-1.7-1.7H6.2a1.7 1.7 0 0 0-1.7 1.7v7.6a1.7 1.7 0 0 0 1.7 1.7h2.3"/>',close:'<path d="M6.5 6.5l11 11M17.5 6.5l-11 11"/>',code:'<path d="M8.5 7.5L4 12l4.5 4.5M15.5 7.5L20 12l-4.5 4.5"/>',undo:'<path d="M9 14.5L4.5 10 9 5.5"/><path d="M4.5 10h9.2a5.8 5.8 0 0 1 0 11.6H11"/>',tag:'<path d="M3.8 12.6V4.5a.7.7 0 0 1 .7-.7h8.1l7.6 7.6-8.8 8.8z"/><circle cx="8.3" cy="8.3" r="1.4"/>',eye:'<path d="M2.5 12S6 5.5 12 5.5 21.5 12 21.5 12 18 18.5 12 18.5 2.5 12 2.5 12z"/><circle cx="12" cy="12" r="2.8"/>',"eye-off":'<path d="M2.5 12S6 5.5 12 5.5c1.9 0 3.6.7 5 1.6M21.5 12s-3.5 6.5-9.5 6.5c-1.9 0-3.6-.7-5-1.6"/><path d="M4 20L20 4"/>',trash:'<path d="M4.5 7h15M9.5 7V4.8h5V7M6.5 7l.9 12.2a1.6 1.6 0 0 0 1.6 1.3h6a1.6 1.6 0 0 0 1.6-1.3L17.5 7"/><path d="M10 10.5v6M14 10.5v6"/>',history:'<path d="M4 12a8 8 0 1 0 2.4-5.7"/><path d="M4 4.5v3.8h3.8"/><path d="M12 8v4.3l2.8 1.8"/>',sliders:'<path d="M4 8h9M17 8h3M4 16h3M11 16h9"/><circle cx="15" cy="8" r="2.2"/><circle cx="9" cy="16" r="2.2"/>',pause:'<path d="M9 5.5v13M15 5.5v13"/>',play:'<path d="M8 5.5l10 6.5-10 6.5z"/>',plane:'<path d="M20.5 3.5L3.5 10.4l6.6 3 3 6.6z"/><path d="M10.1 13.4l10.4-9.9"/>',"plane-flying":'<path class="ink" d="M20.5 3.5L3.5 10.4l6.6 3 3 6.6z"/><path d="M10.1 13.4l10.4-9.9"/><path d="M3 16.5l3-1.2M4.5 20l3.4-1.6" stroke-width="1.6"/>',check:'<path class="stroke" d="M5 12.8c1.6 1.2 2.9 2.7 3.9 4.6C11 12.3 14.6 8 19.5 5"/>'};function icon(name,ink){let template=document.createElement("template");template.innerHTML=`<svg class="icon icon-${name}" viewBox="0 0 24 24" aria-hidden="true" focusable="false">${PATHS[name]}</svg>`;let svg=template.content.firstElementChild;if(ink)svg.style.setProperty("--ink-color",ink);return svg}function logo(){let template=document.createElement("template");return template.innerHTML='<svg class="logo" viewBox="0 3.65 100 100" aria-hidden="true" focusable="false"><path d="M48.2 48.6L48.9 47.2L49.7 46.4L51.1 45.6L52.5 45.3L54.1 45.3L56.9 46.3L58.5 47.6L60.2 49.9L60.5 50.6L61.3 53.8L61.1 57.4L59.7 61L59.1 61.9L57.8 63.6L56.3 65.1L54.4 66.4L51.2 67.9L48.8 68.5L44.9 68.7L42.3 68.4L39.6 67.7L37 66.5L34.5 65L32.2 63L30.1 60.7L27.6 56.6L26.4 53.5L26 51.8L25.5 48.4L25.4 44.9L25.9 41.3L26.4 39.5L28.5 34.2L30.6 30.9L33.2 27.9L36.3 25.2L38 24L39.8 22.9L43.7 21.2L47.8 19.9L50 19.5L50.7 16.8L51.5 15.6L53.2 13.8L55 12.6L57.8 11.4L59.8 10.8L61.7 10.5L64.7 10.4L69.5 11.2L74 13L75.7 14L78 15.8L80.7 18.6L82.4 21L83.3 22.7L84.1 24.5L85.1 28.4L85.3 30.3L85.1 33.4L84.7 35.4L83.9 37.5L82.3 39.8L80.3 41.2L83.6 42.5L85.4 43.6L86.9 45L88.7 47.2L90.4 50.6L91 52.4L91.7 56.9L91.7 58.8L90.9 63.4L90 66L89.2 67.7L86.6 71.5L83.9 74L82.4 75.1L79 76.8L77.2 77.4L74.2 77.8L73.2 77.8L70.9 77.4L70.6 78.2L68.8 77L69.9 79.8L70 81.2L69.3 84.7L68.4 86.7L67.3 88.4L64.6 91.5L62.2 93.3L58.7 95.2L56.8 95.9L53.9 96.6L48.9 96.9L44 96.1L40.3 94.7L37.7 93.2L35.3 91.4L33.9 89.9L32.1 87.5L31.1 85.6L30.1 82.3L30 81L31 77L28.5 78L25.1 78.3L22.1 77.9L18.5 76.5L15.3 74.4L13.2 72.5L11.4 70.3L9.9 67.9L9.1 66.2L8.2 63.5L7.5 59.8L7.5 56L8.2 52.3L9.6 48.7L12.4 44.7L15.8 42.2L17 41.7L17.4 41.1L19.3 40.9L17.9 39.7L17 38.6L15.6 35.4L15.1 32.4L15.3 28.4L16.3 24.7L18 21.2L20.3 18.1L23.9 14.9L27.2 12.9L29.9 11.8L31.8 11.3L35.6 10.8L39.5 11.1L42.4 11.8L45.2 13.1L46.1 13.7L47.8 15.1L49.4 17L50.1 18.6L50.9 16.6L51.7 15.4L53.4 13.7L55.2 12.5L58.9 11"/></svg>',template.content.firstElementChild}function cursor(name,ink){let svg=`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#1d1b19" stroke-width="1.6" stroke-linejoin="round" stroke-linecap="round"><g fill="#fffdf6">${PATHS[name].replace(/class="ink"/g,`fill="${ink}"`)}</g></svg>`;return`url("data:image/svg+xml,${encodeURIComponent(svg)}") 3 21, crosshair`}var DIGITS=["​","‌","‍","⁠"],PATTERN=/⁣[​‌‍⁠]+⁣/g,CUT=/⁣[​‌‍⁠]*/g,nodeKeys=new WeakMap,attributeKeys=new WeakMap;var textNodesOf=(element)=>Array.from(element.childNodes).filter((node)=>node.nodeType===Node.TEXT_NODE);function recordText(node){let parent=node.parentElement;if(!parent)return;let entries=[];textNodesOf(parent).forEach((text,index)=>nodeKeys.get(text)?.forEach((key)=>entries.push([index,key.locale,key.key]))),writeRecord(parent,"data-tensaku-t",entries)}function recordAttributes(element){let entries=Array.from(attributeKeys.get(element)??[]).map(([name,key])=>[name,key.locale,key.key]);writeRecord(element,"data-tensaku-a",entries)}function writeRecord(element,name,entries){let value=JSON.stringify(entries);if(entries.length&&element.getAttribute(name)!==value)element.setAttribute(name,value)}function readRecord(element,name){try{let value=JSON.parse(element.getAttribute(name)??"[]");return Array.isArray(value)?value:[]}catch{return[]}}function restore(root=document){root.querySelectorAll("[data-tensaku-t]").forEach((element)=>{let texts=textNodesOf(element);for(let[index,locale,key]of readRecord(element,"data-tensaku-t")){let node=texts[index];if(!node||nodeKeys.get(node)?.some((k)=>k.key===key&&k.locale===locale))continue;nodeKeys.set(node,[...nodeKeys.get(node)??[],{locale,key}])}}),root.querySelectorAll("[data-tensaku-a]").forEach((element)=>{let map=attributeKeys.get(element)??new Map;for(let[name,locale,key]of readRecord(element,"data-tensaku-a"))if(!map.has(name))map.set(name,{locale,key});if(map.size)attributeKeys.set(element,map)})}function decode(marker){let digits=[...marker.slice(1,-1)].map((char)=>DIGITS.indexOf(char));if(digits.length%4!==0||digits.includes(-1))return null;let bytes=new Uint8Array(digits.length/4);for(let i=0;i<bytes.length;i++){let[a,b,c,d]=digits.slice(i*4,i*4+4);bytes[i]=a<<6|b<<4|c<<2|d}let text=new TextDecoder().decode(bytes),colon=text.indexOf(":");return colon>0?{locale:text.slice(0,colon),key:text.slice(colon+1)}:null}function extract(text){let keys=[];return{text:text.replace(PATTERN,(marker)=>{let key=decode(marker);if(key)keys.push(key);return""}).replace(CUT,""),keys}}function stripText(node){if(!node.data.includes("⁣"))return;let{text,keys}=extract(node.data);if(text!==node.data)node.data=text;if(keys.length){let known=nodeKeys.get(node)??[];nodeKeys.set(node,[...known,...keys.filter((key)=>!known.some((k)=>k.key===key.key&&k.locale===key.locale))]),recordText(node)}}function stripAttributes(element){for(let attribute of Array.from(element.attributes)){if(!attribute.value.includes("⁣"))continue;let{text,keys}=extract(attribute.value);if(text!==attribute.value)element.setAttribute(attribute.name,text);if(keys.length){let map=attributeKeys.get(element)??new Map;map.set(attribute.name,keys[keys.length-1]),attributeKeys.set(element,map),recordAttributes(element)}}if(element instanceof HTMLTextAreaElement&&element.value.includes("⁣"))element.value=extract(element.value).text}function strip(root){if(root.nodeType===Node.TEXT_NODE)return stripText(root);if(!(root instanceof Element||root instanceof Document||root instanceof DocumentFragment))return;if(root instanceof Element)stripAttributes(root);let walker=document.createTreeWalker(root,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_TEXT);for(let node=walker.nextNode();node;node=walker.nextNode())if(node.nodeType===Node.TEXT_NODE)stripText(node);else stripAttributes(node)}function watch(){if(strip(document.documentElement),document.title.includes("⁣"))document.title=extract(document.title).text;document.addEventListener("turbo:render",()=>restore()),document.addEventListener("turbo:frame-render",()=>restore()),new MutationObserver((records)=>{for(let record of records)if(record.type==="characterData")stripText(record.target);else if(record.type==="attributes")stripAttributes(record.target);else record.addedNodes.forEach((node)=>strip(node))}).observe(document.documentElement,{subtree:!0,childList:!0,characterData:!0,attributes:!0})}function textKeys(element){let found=[],walker=document.createTreeWalker(element,NodeFilter.SHOW_TEXT);for(let node=walker.nextNode();node;node=walker.nextNode()){let keys=nodeKeys.get(node);if(!keys)continue;let owner=node.parentElement?.closest("[data-herb-source], [data-md-source]");if(owner&&owner!==element&&element.contains(owner))continue;keys.forEach((key)=>found.push({node,key}))}return found}function attributeKey(element,name){return attributeKeys.get(element)?.get(name)}function attributeKeyNames(element){return Array.from(attributeKeys.get(element)?.keys()??[])}function nodesForKey(key){let nodes=[],walker=document.createTreeWalker(document.body,NodeFilter.SHOW_TEXT);for(let node=walker.nextNode();node;node=walker.nextNode())if(nodeKeys.get(node)?.some((k)=>k.key===key.key&&k.locale===key.locale))nodes.push(node);return nodes}function elementsWithAttributeKey(key){let found=[];return document.querySelectorAll("*").forEach((element)=>{attributeKeys.get(element)?.forEach((k,name)=>{if(k.key===key.key&&k.locale===key.locale)found.push({element,name})})}),found}var STAMP="data-herb-source",MARKDOWN="data-md-source",SOURCE_SELECTOR=`[${STAMP}], [${MARKDOWN}]`;function parseStamp(value){let match=value?.match(/^(.+):(\d+):(\d+)$/);return match?{file:match[1],line:Number(match[2]),column:Number(match[3]),value}:null}function isUi(node){return node instanceof Element&&Boolean(node.closest("[data-tensaku-ui]"))}function sourceElement(node){let start=node instanceof Element?node:node?.parentElement;if(!start||isUi(start))return null;let group=start.closest("[data-tensaku-group]");if(group)return group;return start.closest(SOURCE_SELECTOR)}function stampOf(element){return parseStamp(element.getAttribute(STAMP))}function nearestStamp(element){return parseStamp(element.closest(`[${STAMP}]`)?.getAttribute(STAMP))}function copiesOf(element){let value=element.getAttribute(STAMP);return value?document.querySelectorAll(`[${STAMP}="${CSS.escape(value)}"]`).length:1}function partialChain(element){let files=[];for(let node=element;node;node=node.parentElement){let stamp=parseStamp(node.getAttribute(STAMP));if(stamp&&files[files.length-1]!==stamp.file)files.push(stamp.file)}return files.filter((file,index)=>files.indexOf(file)===index)}function contextOf(element){return{partials:partialChain(element),controller:element.closest("[data-controller]")?.getAttribute("data-controller")??void 0,frame:element.closest("turbo-frame")?.id??void 0}}function tagLabel(element){let tag=element.tagName.toLowerCase();if(element.id)return`${tag}#${element.id}`;let first=Array.from(element.classList).find((name)=>!name.startsWith("tensaku"));return first?`${tag}.${first}`:tag}function visibleText(element,limit=120){let text=(element instanceof HTMLElement?element.innerText:element.textContent??"").replace(/\s+/g," ").trim();return text.length>limit?text.slice(0,limit-1)+"…":text}function hasOwnText(element){for(let node of Array.from(element.childNodes))if(node.nodeType===Node.TEXT_NODE&&node.textContent.trim())return!0;return!1}var MARKDOWN_EDITABLE=new Set(["p","h1","h2","h3","h4","h5","h6","li","blockquote"]),ATTRIBUTES=["alt","title","placeholder","aria-label","value"],templateText=new Map;function editKind(element){if(translationOf(element))return"translation";if(element.hasAttribute(MARKDOWN)&&MARKDOWN_EDITABLE.has(element.tagName.toLowerCase()))return"markdown";if(element.hasAttribute(STAMP)&&hasOwnText(element)&&templateText.get(element.getAttribute(STAMP))!==!1)return"template";if(editableAttributes(element).length)return"attributes";return null}function translationOf(element){let keys=textKeys(element);if(!keys.length)return null;let own=keys[0].node.data.trim(),all=(element.textContent??"").replace(/\s+/g," ").trim();return own&&all.length<=own.length*2+20?keys[0].key:null}function editableAttributes(element){let names=ATTRIBUTES.filter((name)=>element.hasAttribute(name)).filter((name)=>name!=="value"||element.matches("button, input[type=submit], input[type=button], input[type=reset]")),fromStamp=element.hasAttribute(STAMP)?names:[];return Array.from(new Set([...fromStamp,...attributeKeyNames(element).filter((name)=>ATTRIBUTES.includes(name))]))}function documentRect(element){let rect=element.getBoundingClientRect();return new DOMRect(rect.left+scrollX,rect.top+scrollY,rect.width,rect.height)}function contentRect(element){let outer=documentRect(element),range=document.createRange();range.selectNodeContents(element);let inner=range.getBoundingClientRect();if(!inner.width||!inner.height)return outer;let left=Math.max(outer.left,inner.left+scrollX),top=Math.max(outer.top,inner.top+scrollY);return new DOMRect(left,top,Math.min(outer.right,inner.right+scrollX)-left,Math.min(outer.bottom,inner.bottom+scrollY)-top)}function utf8Length(text){return new TextEncoder().encode(text).length}function typingInPage(){let active=document.activeElement;return active instanceof HTMLElement&&!isUi(active)&&(active.matches("input, textarea, select")||active.isContentEditable)}var classesOf=(element)=>Array.from(element.classList).filter((name)=>!name.startsWith("tensaku")).slice(0,12);function targetsFor(element,selectedText){let block=element.closest(`[${MARKDOWN}]`),stamped=element.closest(`[${STAMP}]`);if(block&&(!stamped||stamped.contains(block)))return[{kind:"markdown",md:block.getAttribute(MARKDOWN)??void 0,text:selectedText||visibleText(element,300),tag:tagLabel(element),context:contextOf(element)}];let stamp=nearestStamp(element),targets=[{kind:selectedText?"text":"element",stamp:stamp?.value,text:selectedText||visibleText(element,300),tag:tagLabel(element),classes:classesOf(element),context:contextOf(element)}],key=translationOf(element)??textKeys(element)[0]?.key;if(key)targets.push({kind:"translation",key:key.key,locale:key.locale,text:visibleText(element,300)});let md=element.closest(`[${MARKDOWN}]`)?.getAttribute(MARKDOWN);if(md)targets.push({kind:"markdown",md,text:visibleText(element,300),tag:tagLabel(element)});return targets}function elementsInArea(rect){let candidates=Array.from(document.querySelectorAll(`[${STAMP}], [${MARKDOWN}]`)).filter((element)=>{if(element===document.body||element.closest("[data-tensaku-ui]"))return!1;let box=contentRect(element);if(!box.width||!box.height)return!1;let left=Math.max(box.left,rect.left),right=Math.min(box.right,rect.right),top=Math.max(box.top,rect.top),bottom=Math.min(box.bottom,rect.bottom);return Math.max(0,right-left)*Math.max(0,bottom-top)/(box.width*box.height)>=0.5&&onTop(element,new DOMRect(left,top,right-left,bottom-top))}),outermost=candidates.filter((element)=>!candidates.some((other)=>other!==element&&other.contains(element)));if(outermost.length)return outermost.slice(0,20);let fallback=document.elementsFromPoint(rect.left+rect.width/2-scrollX,rect.top+rect.height/2-scrollY).find((found)=>!isUi(found))?.closest(`[${STAMP}], [${MARKDOWN}]`);return fallback?[fallback]:[]}function onTop(element,part){return[[0.5,0.5],[0.2,0.2],[0.8,0.2],[0.2,0.8],[0.8,0.8]].some(([x,y])=>{let px=part.left+part.width*x-scrollX,py=part.top+part.height*y-scrollY;if(px<0||py<0||px>=innerWidth||py>=innerHeight)return!0;let hit=document.elementsFromPoint(px,py).find((found)=>!isUi(found));return Boolean(hit&&(element.contains(hit)||hit.contains(element)))})}function phraseRects(note){let target=note.targets.find((t)=>t.kind==="text"&&t.text&&t.stamp),element=target&&targetElement(target);if(!target||!element?.textContent?.includes(target.text))return[];let nodes=[],starts=[],all="",walker=document.createTreeWalker(element,NodeFilter.SHOW_TEXT);while(walker.nextNode()){let node=walker.currentNode;starts.push(all.length),nodes.push(node),all+=node.data}let at=all.indexOf(target.text);if(at<0)return[];let end=at+target.text.length,lastIndex=(test)=>{for(let i=starts.length-1;i>=0;i--)if(test(starts[i]))return i;return 0},first=lastIndex((start)=>start<=at),last=lastIndex((start)=>start<end),range=document.createRange();return range.setStart(nodes[first],at-starts[first]),range.setEnd(nodes[last],end-starts[last]),Array.from(range.getClientRects()).filter((r)=>r.width>0).map((r)=>new DOMRect(r.left+scrollX,r.top+scrollY,r.width,r.height))}function anchorFor(note){if(note.rect)return new DOMRect(note.rect.x,note.rect.y,note.rect.width,note.rect.height);for(let target of note.targets){let element=targetElement(target);if(element)return contentRect(element)}return null}function pointFor(note){let target=note.targets.find((t)=>t.point),element=target&&targetElement(target);if(!target?.point||!element)return null;let rect=documentRect(element);return new DOMRect(rect.x+target.point[0]*rect.width,rect.y+target.point[1]*rect.height,0,0)}function guessedElement(note){for(let target of note.targets){let match=targetMatch(target);if(match?.guessed)return match.element}return null}function noteElement(note){for(let target of note.targets){let element=targetElement(target);if(element)return element}return null}function targetElement(target){return targetMatch(target)?.element??null}function targetMatch(target){let attribute=target.stamp?STAMP:target.md?MARKDOWN:null,value=target.stamp??target.md;if(!attribute||!value)return null;let elements=Array.from(document.querySelectorAll(`[${attribute}="${CSS.escape(value)}"]`)),sure=(element)=>element?{element,guessed:!1}:null;if(!target.text)return sure(elements[0]);let text=target.text.replace(/…$/,""),written=(candidates)=>candidates.find((element)=>visibleText(element,300)===target.text)??candidates.find((element)=>visibleText(element,300).startsWith(text))??candidates.find((element)=>target.kind==="text"&&element.textContent?.includes(text)),here=written(elements);if(here)return sure(here);let tag=target.tag?.split(/[.#]/)[0],sameTag=(element)=>!tag||element.tagName.toLowerCase()===tag,file=value.match(/^(.+?):\d+/)?.[1],inFile=file?Array.from(document.querySelectorAll(`[${attribute}^="${CSS.escape(file)}:"]`)).filter(sameTag):[],guess=elements.find(sameTag);return sure(written(inFile))??(guess?{element:guess,guessed:!0}:null)}var overlay_default=`:host { all: initial; }
2
+ /* Shown as a popover over a dialog or popover (top-layer.ts): placed at the document's origin, as on
3
+ <html>, so the overlay's page coordinates stay the same. Important, so the page's [popover] styles
4
+ don't move it. */
5
+ :host(:popover-open) { position: absolute !important; inset: 0 auto auto 0 !important; width: 0 !important; height: 0 !important; margin: 0 !important; padding: 0 !important; border: 0 !important; overflow: visible !important; background: none !important; }
2
6
  * { box-sizing: border-box; }
3
7
  [hidden] { display: none !important; }
4
8
 
5
- /* The pencil case (ART_STYLE.md). Tensaku keeps one look on every host page: a dark tray for the
9
+ /* The pencil case. Tensaku keeps one look on every host page: a dark tray for the
6
10
  tools, Post-it paper for notes, and a few inks. */
7
11
  :host {
8
12
  --tray: #1d1b19; --tray-raised: #2b2825; --tray-line: #3b3732; --tray-ink: #efe9dd; --tray-muted: #a69e90;
@@ -157,6 +161,9 @@ kbd { font: 10.5px/1 var(--mono); padding: 2px 4px; border-radius: 4px; backgrou
157
161
  .pin.question { background: var(--question); }
158
162
  .pin.resolved { background: var(--resolved); }
159
163
  .pin.declined { background: var(--muted); }
164
+ /* Found only by its old position: the note's card asks you to confirm or pick the element again. */
165
+ .pin.unsure { border-style: dashed; border-color: var(--akaji); background: var(--paper); color: var(--akaji); }
166
+ .pin.unsure:hover { border-color: var(--akaji); }
160
167
  .pin .icon { width: 16px; height: 16px; stroke-width: 2.6; }
161
168
  .pin.fresh .stroke { stroke-dasharray: 24; stroke-dashoffset: 24; animation: draw .42s .12s ease-out forwards; }
162
169
 
@@ -359,9 +366,9 @@ kbd { font: 10.5px/1 var(--mono); padding: 2px 4px; border-radius: 4px; backgrou
359
366
  .pin.fresh .stroke { stroke-dashoffset: 0; }
360
367
  .tool:hover .icon, .tool[aria-pressed="true"] .icon, .corner:hover .logo { transform: none; rotate: none; }
361
368
  }
362
- `;var host=document.createElement("tensaku-overlay");host.id="tensaku-overlay";host.setAttribute("data-tensaku-ui","");host.setAttribute("data-turbo-permanent","");var shadow=host.attachShadow({mode:"open"});if("adoptedStyleSheets"in shadow&&typeof CSSStyleSheet<"u"&&"replaceSync"in CSSStyleSheet.prototype){let sheet=new CSSStyleSheet;sheet.replaceSync(overlay_default),shadow.adoptedStyleSheets=[sheet]}else{let style=document.createElement("style");style.textContent=overlay_default,shadow.append(style)}var layer=div("layer"),fixed=div("fixed"),toasts=div("toasts");shadow.append(layer,fixed);fixed.append(toasts);function mount(){if(!host.isConnected)document.documentElement.append(host)}function h(tag,attributes={},...children){let element=document.createElement(tag);for(let[name,value]of Object.entries(attributes)){if(value===void 0||value===null||value===!1)continue;if(name.startsWith("on")&&typeof value==="function")element.addEventListener(name.slice(2),value);else if(name==="className")element.className=value;else element.setAttribute(name,value===!0?"":String(value))}for(let child of children)if(child)element.append(child);return element}function div(className,...children){return h("div",{className},...children)}function toast(message,options={}){let element=div("toast"+(options.error?" error":"")+(options.detail?" detailed":""),h("span",{},message));element.setAttribute("role",options.error?"alert":"status");for(let[label,action]of Object.entries(options.actions??{}))element.append(h("button",{onclick:()=>{element.remove(),action()}},label));if(options.detail)element.append(options.detail);if(toasts.append(element),options.timeout!==0)setTimeout(()=>element.remove(),options.timeout??(options.error?8000:5000));return element}function panel(anchor,className,...children){let element=div("panel "+className,...children);return layer.append(element),place(element,anchor),element}function place(element,anchor,over=!1){let width=element.offsetWidth,left=Math.max(scrollX+8,Math.min(anchor.left,scrollX+innerWidth-width-8)),top=over?anchor.top:anchor.bottom+6;if(!over&&top+element.offsetHeight>scrollY+innerHeight-8&&anchor.top-element.offsetHeight-6>scrollY)top=anchor.top-element.offsetHeight-6;element.style.left=`${left}px`,element.style.top=`${top}px`}function box(rect,className,label){let element=div("box "+className);if(Object.assign(element.style,{left:`${rect.left}px`,top:`${rect.top}px`,width:`${rect.width}px`,height:`${rect.height}px`}),layer.append(element),!label)return[element];let tag=div("label");if(tag.append(label[0]),label[1])tag.append(h("span",{className:"where"},label[1]));return Object.assign(tag.style,{left:`${rect.left}px`,top:`${rect.top}px`}),layer.append(tag),[element,tag]}async function copy(text){try{await navigator.clipboard.writeText(text)}catch{let area=h("textarea",{},text);shadow.append(area),area.select(),document.execCommand("copy"),area.remove()}}function storage(key,fallback){try{let value=localStorage.getItem(`tensaku:${key}`);return value?JSON.parse(value):fallback}catch{return fallback}}function store(key,value){try{localStorage.setItem(`tensaku:${key}`,JSON.stringify(value))}catch{}}function activeInShadow(){return shadow.activeElement}var DEFAULTS={copyFormat:"detailed",notify:!1,shortcuts:{}},current={...DEFAULTS,...storage("settings",{})},listeners=[],settings=()=>current,onSettings=(listener)=>{listeners.push(listener),listener(current)};function changeSettings(change){current={...current,...change},store("settings",current),listeners.forEach((listener)=>listener(current))}var Idiomorph=function(){let noOp=()=>{},defaults={morphStyle:"outerHTML",callbacks:{beforeNodeAdded:noOp,afterNodeAdded:noOp,beforeNodeMorphed:noOp,afterNodeMorphed:noOp,beforeNodeRemoved:noOp,afterNodeRemoved:noOp,beforeAttributeUpdated:noOp},head:{style:"merge",shouldPreserve:(elt)=>elt.getAttribute("im-preserve")==="true",shouldReAppend:(elt)=>elt.getAttribute("im-re-append")==="true",shouldRemove:noOp,afterHeadMorphed:noOp},restoreFocus:!0};function morph(oldNode,newContent,config={}){oldNode=normalizeElement(oldNode);let newNode=normalizeParent(newContent),ctx=createMorphContext(oldNode,newNode,config),morphedNodes=saveAndRestoreFocus(ctx,()=>{return withHeadBlocking(ctx,oldNode,newNode,(ctx2)=>{if(ctx2.morphStyle==="innerHTML")return morphChildren(ctx2,oldNode,newNode),Array.from(oldNode.childNodes);else return morphOuterHTML(ctx2,oldNode,newNode)})});return ctx.pantry.remove(),morphedNodes}function morphOuterHTML(ctx,oldNode,newNode){let oldParent=normalizeParent(oldNode);return morphChildren(ctx,oldParent,newNode,oldNode,oldNode.nextSibling),Array.from(oldParent.childNodes)}function saveAndRestoreFocus(ctx,fn){if(!ctx.config.restoreFocus)return fn();let activeElement=document.activeElement;if(!(activeElement instanceof HTMLInputElement||activeElement instanceof HTMLTextAreaElement))return fn();let{id:activeElementId,selectionStart,selectionEnd}=activeElement,results=fn();if(activeElementId&&activeElementId!==document.activeElement?.getAttribute("id"))activeElement=ctx.target.querySelector(`[id="${activeElementId}"]`),activeElement?.focus();if(activeElement&&!activeElement.selectionEnd&&selectionEnd)activeElement.setSelectionRange(selectionStart,selectionEnd);return results}let morphChildren=function(){function morphChildren2(ctx,oldParent,newParent,insertionPoint=null,endPoint=null){if(oldParent instanceof HTMLTemplateElement&&newParent instanceof HTMLTemplateElement)oldParent=oldParent.content,newParent=newParent.content;insertionPoint||=oldParent.firstChild;for(let newChild of newParent.childNodes){if(insertionPoint&&insertionPoint!=endPoint){let bestMatch=findBestMatch(ctx,newChild,insertionPoint,endPoint);if(bestMatch){if(bestMatch!==insertionPoint)removeNodesBetween(ctx,insertionPoint,bestMatch);morphNode(bestMatch,newChild,ctx),insertionPoint=bestMatch.nextSibling;continue}}if(newChild instanceof Element){let newChildId=newChild.getAttribute("id");if(ctx.persistentIds.has(newChildId)){let movedChild=moveBeforeById(oldParent,newChildId,insertionPoint,ctx);morphNode(movedChild,newChild,ctx),insertionPoint=movedChild.nextSibling;continue}}let insertedNode=createNode(oldParent,newChild,insertionPoint,ctx);if(insertedNode)insertionPoint=insertedNode.nextSibling}while(insertionPoint&&insertionPoint!=endPoint){let tempNode=insertionPoint;insertionPoint=insertionPoint.nextSibling,removeNode(ctx,tempNode)}}function createNode(oldParent,newChild,insertionPoint,ctx){if(ctx.callbacks.beforeNodeAdded(newChild)===!1)return null;if(ctx.idMap.has(newChild)){let newEmptyChild=document.createElement(newChild.tagName);return oldParent.insertBefore(newEmptyChild,insertionPoint),morphNode(newEmptyChild,newChild,ctx),ctx.callbacks.afterNodeAdded(newEmptyChild),newEmptyChild}else{let newClonedChild=document.importNode(newChild,!0);return oldParent.insertBefore(newClonedChild,insertionPoint),ctx.callbacks.afterNodeAdded(newClonedChild),newClonedChild}}let findBestMatch=function(){function findBestMatch2(ctx,node,startPoint,endPoint){let softMatch=null,nextSibling=node.nextSibling,siblingSoftMatchCount=0,cursor2=startPoint;while(cursor2&&cursor2!=endPoint){if(isSoftMatch(cursor2,node)){if(isIdSetMatch(ctx,cursor2,node))return cursor2;if(softMatch===null){if(!ctx.idMap.has(cursor2))softMatch=cursor2}}if(softMatch===null&&nextSibling&&isSoftMatch(cursor2,nextSibling)){if(siblingSoftMatchCount++,nextSibling=nextSibling.nextSibling,siblingSoftMatchCount>=2)softMatch=void 0}if(ctx.activeElementAndParents.includes(cursor2))break;cursor2=cursor2.nextSibling}return softMatch||null}function isIdSetMatch(ctx,oldNode,newNode){let oldSet=ctx.idMap.get(oldNode),newSet=ctx.idMap.get(newNode);if(!newSet||!oldSet)return!1;for(let id of oldSet)if(newSet.has(id))return!0;return!1}function isSoftMatch(oldNode,newNode){let oldElt=oldNode,newElt=newNode;return oldElt.nodeType===newElt.nodeType&&oldElt.tagName===newElt.tagName&&(!oldElt.getAttribute?.("id")||oldElt.getAttribute?.("id")===newElt.getAttribute?.("id"))}return findBestMatch2}();function removeNode(ctx,node){if(ctx.idMap.has(node))moveBefore(ctx.pantry,node,null);else{if(ctx.callbacks.beforeNodeRemoved(node)===!1)return;node.parentNode?.removeChild(node),ctx.callbacks.afterNodeRemoved(node)}}function removeNodesBetween(ctx,startInclusive,endExclusive){let cursor2=startInclusive;while(cursor2&&cursor2!==endExclusive){let tempNode=cursor2;cursor2=cursor2.nextSibling,removeNode(ctx,tempNode)}return cursor2}function moveBeforeById(parentNode,id,after,ctx){let target=ctx.target.getAttribute?.("id")===id&&ctx.target||ctx.target.querySelector(`[id="${id}"]`)||ctx.pantry.querySelector(`[id="${id}"]`);return removeElementFromAncestorsIdMaps(target,ctx),moveBefore(parentNode,target,after),target}function removeElementFromAncestorsIdMaps(element,ctx){let id=element.getAttribute("id");while(element=element.parentNode){let idSet=ctx.idMap.get(element);if(idSet){if(idSet.delete(id),!idSet.size)ctx.idMap.delete(element)}}}function moveBefore(parentNode,element,after){if(parentNode.moveBefore)try{parentNode.moveBefore(element,after)}catch(e){parentNode.insertBefore(element,after)}else parentNode.insertBefore(element,after)}return morphChildren2}(),morphNode=function(){function morphNode2(oldNode,newContent,ctx){if(ctx.ignoreActive&&oldNode===document.activeElement)return null;if(ctx.callbacks.beforeNodeMorphed(oldNode,newContent)===!1)return oldNode;if(oldNode instanceof HTMLHeadElement&&ctx.head.ignore);else if(oldNode instanceof HTMLHeadElement&&ctx.head.style!=="morph")handleHeadElement(oldNode,newContent,ctx);else if(morphAttributes(oldNode,newContent,ctx),!ignoreValueOfActiveElement(oldNode,ctx))morphChildren(ctx,oldNode,newContent);return ctx.callbacks.afterNodeMorphed(oldNode,newContent),oldNode}function morphAttributes(oldNode,newNode,ctx){let type=newNode.nodeType;if(type===1){let oldElt=oldNode,newElt=newNode,oldAttributes=oldElt.attributes,newAttributes=newElt.attributes;for(let newAttribute of newAttributes){if(ignoreAttribute(newAttribute.name,oldElt,"update",ctx))continue;if(oldElt.getAttribute(newAttribute.name)!==newAttribute.value)oldElt.setAttribute(newAttribute.name,newAttribute.value)}for(let i=oldAttributes.length-1;0<=i;i--){let oldAttribute=oldAttributes[i];if(!oldAttribute)continue;if(!newElt.hasAttribute(oldAttribute.name)){if(ignoreAttribute(oldAttribute.name,oldElt,"remove",ctx))continue;oldElt.removeAttribute(oldAttribute.name)}}if(!ignoreValueOfActiveElement(oldElt,ctx))syncInputValue(oldElt,newElt,ctx)}if(type===8||type===3){if(oldNode.nodeValue!==newNode.nodeValue)oldNode.nodeValue=newNode.nodeValue}}function syncInputValue(oldElement,newElement,ctx){if(oldElement instanceof HTMLInputElement&&newElement instanceof HTMLInputElement&&newElement.type!=="file"){let newValue=newElement.value,oldValue=oldElement.value;if(syncBooleanAttribute(oldElement,newElement,"checked",ctx),syncBooleanAttribute(oldElement,newElement,"disabled",ctx),!newElement.hasAttribute("value")){if(!ignoreAttribute("value",oldElement,"remove",ctx))oldElement.value="",oldElement.removeAttribute("value")}else if(oldValue!==newValue){if(!ignoreAttribute("value",oldElement,"update",ctx))oldElement.setAttribute("value",newValue),oldElement.value=newValue}}else if(oldElement instanceof HTMLOptionElement&&newElement instanceof HTMLOptionElement)syncBooleanAttribute(oldElement,newElement,"selected",ctx);else if(oldElement instanceof HTMLTextAreaElement&&newElement instanceof HTMLTextAreaElement){let newValue=newElement.value,oldValue=oldElement.value;if(ignoreAttribute("value",oldElement,"update",ctx))return;if(newValue!==oldValue)oldElement.value=newValue;if(oldElement.firstChild&&oldElement.firstChild.nodeValue!==newValue)oldElement.firstChild.nodeValue=newValue}}function syncBooleanAttribute(oldElement,newElement,attributeName,ctx){let newLiveValue=newElement[attributeName],oldLiveValue=oldElement[attributeName];if(newLiveValue!==oldLiveValue){let ignoreUpdate=ignoreAttribute(attributeName,oldElement,"update",ctx);if(!ignoreUpdate)oldElement[attributeName]=newElement[attributeName];if(newLiveValue){if(!ignoreUpdate)oldElement.setAttribute(attributeName,"")}else if(!ignoreAttribute(attributeName,oldElement,"remove",ctx))oldElement.removeAttribute(attributeName)}}function ignoreAttribute(attr,element,updateType,ctx){if(attr==="value"&&ctx.ignoreActiveValue&&element===document.activeElement)return!0;return ctx.callbacks.beforeAttributeUpdated(attr,element,updateType)===!1}function ignoreValueOfActiveElement(possibleActiveElement,ctx){return!!ctx.ignoreActiveValue&&possibleActiveElement===document.activeElement&&possibleActiveElement!==document.body}return morphNode2}();function withHeadBlocking(ctx,oldNode,newNode,callback){if(ctx.head.block){let oldHead=oldNode.querySelector("head"),newHead=newNode.querySelector("head");if(oldHead&&newHead){let promises=handleHeadElement(oldHead,newHead,ctx);return Promise.all(promises).then(()=>{let newCtx=Object.assign(ctx,{head:{block:!1,ignore:!0}});return callback(newCtx)})}}return callback(ctx)}function handleHeadElement(oldHead,newHead,ctx){let added=[],removed=[],preserved=[],nodesToAppend=[],srcToNewHeadNodes=new Map;for(let newHeadChild of newHead.children)srcToNewHeadNodes.set(newHeadChild.outerHTML,newHeadChild);for(let currentHeadElt of oldHead.children){let inNewContent=srcToNewHeadNodes.has(currentHeadElt.outerHTML),isReAppended=ctx.head.shouldReAppend(currentHeadElt),isPreserved=ctx.head.shouldPreserve(currentHeadElt);if(inNewContent||isPreserved)if(isReAppended)removed.push(currentHeadElt);else srcToNewHeadNodes.delete(currentHeadElt.outerHTML),preserved.push(currentHeadElt);else if(ctx.head.style==="append"){if(isReAppended)removed.push(currentHeadElt),nodesToAppend.push(currentHeadElt)}else if(ctx.head.shouldRemove(currentHeadElt)!==!1)removed.push(currentHeadElt)}nodesToAppend.push(...srcToNewHeadNodes.values());let promises=[];for(let newNode of nodesToAppend){let newElt=document.createRange().createContextualFragment(newNode.outerHTML).firstChild;if(ctx.callbacks.beforeNodeAdded(newElt)!==!1){if("href"in newElt&&newElt.href||"src"in newElt&&newElt.src){let resolve,promise=new Promise(function(_resolve){resolve=_resolve});newElt.addEventListener("load",function(){resolve()}),promises.push(promise)}oldHead.appendChild(newElt),ctx.callbacks.afterNodeAdded(newElt),added.push(newElt)}}for(let removedElement of removed)if(ctx.callbacks.beforeNodeRemoved(removedElement)!==!1)oldHead.removeChild(removedElement),ctx.callbacks.afterNodeRemoved(removedElement);return ctx.head.afterHeadMorphed(oldHead,{added,kept:preserved,removed}),promises}let createMorphContext=function(){function createMorphContext2(oldNode,newContent,config){let{persistentIds,idMap}=createIdMaps(oldNode,newContent),mergedConfig=mergeDefaults(config),morphStyle=mergedConfig.morphStyle||"outerHTML";if(!["innerHTML","outerHTML"].includes(morphStyle))throw`Do not understand how to morph style ${morphStyle}`;return{target:oldNode,newContent,config:mergedConfig,morphStyle,ignoreActive:mergedConfig.ignoreActive,ignoreActiveValue:mergedConfig.ignoreActiveValue,restoreFocus:mergedConfig.restoreFocus,idMap,persistentIds,pantry:createPantry(),activeElementAndParents:createActiveElementAndParents(oldNode),callbacks:mergedConfig.callbacks,head:mergedConfig.head}}function mergeDefaults(config){let finalConfig=Object.assign({},defaults);return Object.assign(finalConfig,config),finalConfig.callbacks=Object.assign({},defaults.callbacks,config.callbacks),finalConfig.head=Object.assign({},defaults.head,config.head),finalConfig}function createPantry(){let pantry=document.createElement("div");return pantry.hidden=!0,document.body.insertAdjacentElement("afterend",pantry),pantry}function createActiveElementAndParents(oldNode){let activeElementAndParents=[],elt=document.activeElement;if(elt?.tagName!=="BODY"&&oldNode.contains(elt))while(elt){if(activeElementAndParents.push(elt),elt===oldNode)break;elt=elt.parentElement}return activeElementAndParents}function findIdElements(root){let elements=Array.from(root.querySelectorAll("[id]"));if(root.getAttribute?.("id"))elements.push(root);return elements}function populateIdMapWithTree(idMap,persistentIds,root,elements){for(let elt of elements){let id=elt.getAttribute("id");if(persistentIds.has(id)){let current2=elt;while(current2){let idSet=idMap.get(current2);if(idSet==null)idSet=new Set,idMap.set(current2,idSet);if(idSet.add(id),current2===root)break;current2=current2.parentElement}}}}function createIdMaps(oldContent,newContent){let oldIdElements=findIdElements(oldContent),newIdElements=findIdElements(newContent),persistentIds=createPersistentIds(oldIdElements,newIdElements),idMap=new Map;populateIdMapWithTree(idMap,persistentIds,oldContent,oldIdElements);let newRoot=newContent.__idiomorphRoot||newContent;return populateIdMapWithTree(idMap,persistentIds,newRoot,newIdElements),{persistentIds,idMap}}function createPersistentIds(oldIdElements,newIdElements){let duplicateIds=new Set,oldIdTagNameMap=new Map;for(let{id,tagName}of oldIdElements)if(oldIdTagNameMap.has(id))duplicateIds.add(id);else oldIdTagNameMap.set(id,tagName);let persistentIds=new Set;for(let{id,tagName}of newIdElements)if(persistentIds.has(id))duplicateIds.add(id);else if(oldIdTagNameMap.get(id)===tagName)persistentIds.add(id);for(let id of duplicateIds)persistentIds.delete(id);return persistentIds}return createMorphContext2}(),{normalizeElement,normalizeParent}=function(){let generatedByIdiomorph=new WeakSet;function normalizeElement2(content){if(content instanceof Document)return content.documentElement;else return content}function normalizeParent2(newContent){if(newContent==null)return document.createElement("div");else if(typeof newContent==="string")return normalizeParent2(parseContent(newContent));else if(generatedByIdiomorph.has(newContent))return newContent;else if(newContent instanceof Node)if(newContent.parentNode)return new SlicedParentNode(newContent);else{let dummyParent=document.createElement("div");return dummyParent.append(newContent),dummyParent}else{let dummyParent=document.createElement("div");for(let elt of[...newContent])dummyParent.append(elt);return dummyParent}}class SlicedParentNode{constructor(node){this.originalNode=node,this.realParentNode=node.parentNode,this.previousSibling=node.previousSibling,this.nextSibling=node.nextSibling}get childNodes(){let nodes=[],cursor2=this.previousSibling?this.previousSibling.nextSibling:this.realParentNode.firstChild;while(cursor2&&cursor2!=this.nextSibling)nodes.push(cursor2),cursor2=cursor2.nextSibling;return nodes}querySelectorAll(selector){return this.childNodes.reduce((results,node)=>{if(node instanceof Element){if(node.matches(selector))results.push(node);let nodeList=node.querySelectorAll(selector);for(let i=0;i<nodeList.length;i++)results.push(nodeList[i])}return results},[])}insertBefore(node,referenceNode){return this.realParentNode.insertBefore(node,referenceNode)}moveBefore(node,referenceNode){return this.realParentNode.moveBefore(node,referenceNode)}get __idiomorphRoot(){return this.originalNode}}function parseContent(newContent){let parser=new DOMParser,contentWithSvgsRemoved=newContent.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(contentWithSvgsRemoved.match(/<\/html>/)||contentWithSvgsRemoved.match(/<\/head>/)||contentWithSvgsRemoved.match(/<\/body>/)){let content=parser.parseFromString(newContent,"text/html");if(contentWithSvgsRemoved.match(/<\/html>/))return generatedByIdiomorph.add(content),content;else{let htmlElement=content.firstChild;if(htmlElement)generatedByIdiomorph.add(htmlElement);return htmlElement}}else{let content=parser.parseFromString("<body><template>"+newContent+"</template></body>","text/html").body.querySelector("template").content;return generatedByIdiomorph.add(content),content}}return{normalizeElement:normalizeElement2,normalizeParent:normalizeParent2}}();return{morph,defaults}}();var listeners2=[];function onRefresh(listener){listeners2.push(listener)}function permanent(node){return node instanceof Element&&(node.hasAttribute("data-turbo-permanent")||node.hasAttribute("data-tensaku-permanent")||node.hasAttribute("data-tensaku-ui"))}function herbDevServer(){return Boolean(document.querySelector('meta[name="herb-dev-server-port"]'))}function replaceText(nodes,from,to){let normal=(text)=>text.replace(/\s+/g," ").trim(),target=normal(from);if(!target)return;for(let node of nodes)if(normal(node.data)===target){let lead=node.data.match(/^\s*/)[0],trail=node.data.match(/\s*$/)[0];node.data=lead+to.trim()+trail}else if(node.data.includes(from)&&from.trim())node.data=node.data.replace(from,to)}async function refresh(kind){if(meta().method!=="GET"){toast("Saved. This page came from a form submission, so reload to check it.",{timeout:7000});return}if(kind==="template"&&herbDevServer())return;try{let response=await fetch(location.href,{headers:{Accept:"text/html","X-Tensaku-Refresh":"1"},credentials:"same-origin"});if(!response.ok)throw Error(`HTTP ${response.status}`);let html=await response.text(),next=new DOMParser().parseFromString(html,"text/html");morph(next)}catch(error){toast(`Saved, but refreshing the page failed (${error.message}). Reload to check.`,{error:!0})}}var agentFetch=0;async function refreshAfterAgent(){if(meta().method!=="GET")return;let sequence=++agentFetch;try{let response=await fetch(location.href,{headers:{Accept:"text/html","X-Tensaku-Refresh":"1"},credentials:"same-origin"});if(!response.ok)return;let html=await response.text();if(sequence!==agentFetch)return;let next=new DOMParser().parseFromString(html,"text/html");swapStylesheets(next),morph(next)}catch{}}function swapStylesheets(next){let wanted=new Set(((doc)=>Array.from(doc.querySelectorAll('head link[rel="stylesheet"]')).map((link)=>link.getAttribute("href")))(next)),current2=Array.from(document.querySelectorAll('head link[rel="stylesheet"]')),have=new Set(current2.map((link)=>link.getAttribute("href"))),added=Array.from(next.querySelectorAll('head link[rel="stylesheet"]')).filter((link)=>!have.has(link.getAttribute("href")));if(!added.length)return;let stale=current2.filter((link)=>!wanted.has(link.getAttribute("href"))),waiting=added.length;for(let link of added){let copy2=document.importNode(link,!0),done=()=>{if(--waiting===0)stale.forEach((old)=>old.remove())};copy2.addEventListener("load",done),copy2.addEventListener("error",done),document.head.append(copy2)}}function changedByUser(element){if(element instanceof HTMLInputElement){if(element.type==="checkbox"||element.type==="radio")return element.checked!==element.defaultChecked;return element.type!=="file"&&element.value!==element.defaultValue}if(element instanceof HTMLTextAreaElement)return element.value!==element.defaultValue;if(element instanceof HTMLOptionElement)return element.selected!==element.defaultSelected;if(element instanceof HTMLSelectElement)return Array.from(element.options).some((option)=>option.selected!==option.defaultSelected);return!1}var FORM_STATE=new Set(["value","checked","selected"]);function morph(next){let lazyFrames=Array.from(document.querySelectorAll("turbo-frame[src]"));if(Idiomorph.morph(document.body,next.body,{morphStyle:"outerHTML",ignoreActiveValue:!0,restoreFocus:!0,callbacks:{beforeNodeMorphed:(oldNode)=>!permanent(oldNode)&&!(oldNode instanceof HTMLTextAreaElement&&changedByUser(oldNode)),beforeAttributeUpdated:(name,element)=>!(FORM_STATE.has(name)&&changedByUser(element)),beforeNodeRemoved:(node)=>!permanent(node)}}),next.title)document.title=next.title;for(let frame of lazyFrames)if(frame.isConnected&&typeof frame.reload==="function"&&!frame.hasAttribute("complete"))frame.reload();listeners2.forEach((listener)=>listener())}var notes=[],scoped=[],scope=null,openCount=0,agents=[],currentNotes=()=>notes,scopedNotes=()=>scoped,currentAgents=()=>agents,openNotes=()=>openCount,agentLabel=(agent)=>agent.handle?`${agent.name} · ${agent.handle}`:agent.name,listeners3=()=>agents.filter((agent)=>agent.listening).map(agentLabel),closed=(note)=>note.status==="resolved"||note.status==="declined",renderListeners=[],countListeners=[],agentListeners=[],changeListeners=[],onRender=(listener)=>renderListeners.push(listener),onCount=(listener)=>countListeners.push(listener),onAgents=(listener)=>agentListeners.push(listener),onChanges=(listener)=>changeListeners.push(listener),normalized=(list)=>list.map((note)=>({...note,targets:note.targets??[]})),lastSignature="",loadSequence=0,tokenWarned=!1,restartWarned=!1,agentChangedAt,primed=!1;async function load({force=!1}={}){let sequence=++loadSequence,first=!1;try{let data=await api("GET","/notes"+query({url:location.pathname}));if(sequence!==loadSequence)return;if(tokenWarned=!1,primed&&data.changed_at&&data.changed_at!==agentChangedAt)refreshAfterAgent();if(agentChangedAt=data.changed_at,data.restart&&!restartWarned)restartWarned=!0,toast("Tensaku's code changed since this dev server started, so the page runs a newer overlay than the server. Restart the dev server.",{error:!0,timeout:20000});data.notes=data.notes.filter((note)=>!pendingDeletes.has(note.id)),agents=data.agents??[],agentListeners.forEach((listener)=>listener(agents));let signature=location.pathname+JSON.stringify([data.notes,data.open,listeners3()]);if(!force&&signature===lastSignature)return;lastSignature=signature;let after=normalized(data.notes);if(primed&&data.notes.length&&notes.length)changeListeners.forEach((listener)=>listener(notes,after));if(first=!primed,primed=!0,notes=after,openCount=data.open,scope&&scope!=="page"){let all=await scopeNotes(scope);if(sequence!==loadSequence)return;scoped=all}}catch(error){if(sequence!==loadSequence)return;if(error instanceof ApiError&&error.status===403&&!tokenWarned)tokenWarned=!0,toast(`${error.message} Notes can't be loaded until then.`,{error:!0,timeout:15000,actions:{Reload:()=>location.reload()}});return}countListeners.forEach((listener)=>listener(openCount)),render({force,first})}function render(what){renderListeners.forEach((listener)=>listener(what))}var scopeNotes=async(which)=>normalized((await api("GET","/notes"+(which==="archived"?query({archived:"1"}):""))).notes).filter((note)=>!pendingDeletes.has(note.id));async function setScope(which){if(scope=which,which&&which!=="page")scoped=await scopeNotes(which)}var streaming=!1;function poll(){let pending=0,changed=()=>{clearTimeout(pending),pending=window.setTimeout(()=>load(),30)},editedPending=0,edited=()=>{clearTimeout(editedPending),editedPending=window.setTimeout(refreshAfterAgent,150)},connect=async()=>{let retry=5000;try{let{token,root}=meta(),response=await fetch(root+"/events",{headers:{"X-Tensaku-Token":token,Accept:"text/event-stream"},credentials:"same-origin"});if(response.status===501)return;if(!response.ok||!response.body)throw Error(`events ${response.status}`);streaming=!0;let reader=response.body.pipeThrough(new TextDecoderStream).getReader(),buffer="";for(;;){let{value,done}=await reader.read();if(done)break;buffer+=value;let events=buffer.split(`
369
+ `;var host=document.createElement("tensaku-overlay");host.id="tensaku-overlay";host.setAttribute("data-tensaku-ui","");host.setAttribute("data-turbo-permanent","");var shadow=host.attachShadow({mode:"open"});for(let type of["pointerdown","pointerup","mousedown","mouseup","click","dblclick","contextmenu","keydown","keyup","keypress"])host.addEventListener(type,(event)=>event.stopPropagation());if("adoptedStyleSheets"in shadow&&typeof CSSStyleSheet<"u"&&"replaceSync"in CSSStyleSheet.prototype){let sheet=new CSSStyleSheet;sheet.replaceSync(overlay_default),shadow.adoptedStyleSheets=[sheet]}else{let style=document.createElement("style");style.textContent=overlay_default,shadow.append(style)}var layer=div("layer"),fixed=div("fixed"),toasts=div("toasts");shadow.append(layer,fixed);fixed.append(toasts);function h(tag,attributes={},...children){let element=document.createElement(tag);for(let[name,value]of Object.entries(attributes)){if(value===void 0||value===null||value===!1)continue;if(name.startsWith("on")&&typeof value==="function")element.addEventListener(name.slice(2),value);else if(name==="className")element.className=value;else element.setAttribute(name,value===!0?"":String(value))}for(let child of children)if(child)element.append(child);return element}function div(className,...children){return h("div",{className},...children)}function toast(message,options={}){let element=div("toast"+(options.error?" error":"")+(options.detail?" detailed":""),h("span",{},message));element.setAttribute("role",options.error?"alert":"status");for(let[label,action]of Object.entries(options.actions??{}))element.append(h("button",{onclick:()=>{element.remove(),action()}},label));if(options.detail)element.append(options.detail);if(toasts.append(element),options.timeout!==0)setTimeout(()=>element.remove(),options.timeout??(options.error?8000:5000));return element}function panel(anchor,className,...children){let element=div("panel "+className,...children);return layer.append(element),place(element,anchor),element}function place(element,anchor,over=!1){let width=element.offsetWidth,left=Math.max(scrollX+8,Math.min(anchor.left,scrollX+innerWidth-width-8)),top=over?anchor.top:anchor.bottom+6;if(!over&&top+element.offsetHeight>scrollY+innerHeight-8&&anchor.top-element.offsetHeight-6>scrollY)top=anchor.top-element.offsetHeight-6;element.style.left=`${left}px`,element.style.top=`${top}px`}function box(rect,className,label){let element=div("box "+className);if(Object.assign(element.style,{left:`${rect.left}px`,top:`${rect.top}px`,width:`${rect.width}px`,height:`${rect.height}px`}),layer.append(element),!label)return[element];let tag=div("label");if(tag.append(label[0]),label[1])tag.append(h("span",{className:"where"},label[1]));return Object.assign(tag.style,{left:`${rect.left}px`,top:`${rect.top}px`}),layer.append(tag),[element,tag]}async function copy(text){try{await navigator.clipboard.writeText(text)}catch{let area=h("textarea",{},text);shadow.append(area),area.select(),document.execCommand("copy"),area.remove()}}function storage(key,fallback){try{let value=localStorage.getItem(`tensaku:${key}`);return value?JSON.parse(value):fallback}catch{return fallback}}function store(key,value){try{localStorage.setItem(`tensaku:${key}`,JSON.stringify(value))}catch{}}function activeInShadow(){return shadow.activeElement}var picking=null,hint=null,listeners=[],isPicking=()=>picking!==null,onPick=(listener)=>{listeners.push(listener)};function startPick(done){stop(),picking=done,hint=toast("Click the element this note is about. Esc cancels.",{timeout:0}),listeners.forEach((listener)=>listener())}function pick(element,at){let done=picking;stop(),done?.(element,at)}function cancelPick(){if(!picking)return!1;return stop(),!0}function stop(){picking=null,hint?.remove(),hint=null,listeners.forEach((listener)=>listener())}var DEFAULTS={copyFormat:"detailed",notify:!1,shortcuts:{}},current={...DEFAULTS,...storage("settings",{})},listeners2=[],settings=()=>current,onSettings=(listener)=>{listeners2.push(listener),listener(current)};function changeSettings(change){current={...current,...change},store("settings",current),listeners2.forEach((listener)=>listener(current))}var Idiomorph=function(){let noOp=()=>{},defaults={morphStyle:"outerHTML",callbacks:{beforeNodeAdded:noOp,afterNodeAdded:noOp,beforeNodeMorphed:noOp,afterNodeMorphed:noOp,beforeNodeRemoved:noOp,afterNodeRemoved:noOp,beforeAttributeUpdated:noOp},head:{style:"merge",shouldPreserve:(elt)=>elt.getAttribute("im-preserve")==="true",shouldReAppend:(elt)=>elt.getAttribute("im-re-append")==="true",shouldRemove:noOp,afterHeadMorphed:noOp},restoreFocus:!0};function morph(oldNode,newContent,config={}){oldNode=normalizeElement(oldNode);let newNode=normalizeParent(newContent),ctx=createMorphContext(oldNode,newNode,config),morphedNodes=saveAndRestoreFocus(ctx,()=>{return withHeadBlocking(ctx,oldNode,newNode,(ctx2)=>{if(ctx2.morphStyle==="innerHTML")return morphChildren(ctx2,oldNode,newNode),Array.from(oldNode.childNodes);else return morphOuterHTML(ctx2,oldNode,newNode)})});return ctx.pantry.remove(),morphedNodes}function morphOuterHTML(ctx,oldNode,newNode){let oldParent=normalizeParent(oldNode);return morphChildren(ctx,oldParent,newNode,oldNode,oldNode.nextSibling),Array.from(oldParent.childNodes)}function saveAndRestoreFocus(ctx,fn){if(!ctx.config.restoreFocus)return fn();let activeElement=document.activeElement;if(!(activeElement instanceof HTMLInputElement||activeElement instanceof HTMLTextAreaElement))return fn();let{id:activeElementId,selectionStart,selectionEnd}=activeElement,results=fn();if(activeElementId&&activeElementId!==document.activeElement?.getAttribute("id"))activeElement=ctx.target.querySelector(`[id="${activeElementId}"]`),activeElement?.focus();if(activeElement&&!activeElement.selectionEnd&&selectionEnd)activeElement.setSelectionRange(selectionStart,selectionEnd);return results}let morphChildren=function(){function morphChildren2(ctx,oldParent,newParent,insertionPoint=null,endPoint=null){if(oldParent instanceof HTMLTemplateElement&&newParent instanceof HTMLTemplateElement)oldParent=oldParent.content,newParent=newParent.content;insertionPoint||=oldParent.firstChild;for(let newChild of newParent.childNodes){if(insertionPoint&&insertionPoint!=endPoint){let bestMatch=findBestMatch(ctx,newChild,insertionPoint,endPoint);if(bestMatch){if(bestMatch!==insertionPoint)removeNodesBetween(ctx,insertionPoint,bestMatch);morphNode(bestMatch,newChild,ctx),insertionPoint=bestMatch.nextSibling;continue}}if(newChild instanceof Element){let newChildId=newChild.getAttribute("id");if(ctx.persistentIds.has(newChildId)){let movedChild=moveBeforeById(oldParent,newChildId,insertionPoint,ctx);morphNode(movedChild,newChild,ctx),insertionPoint=movedChild.nextSibling;continue}}let insertedNode=createNode(oldParent,newChild,insertionPoint,ctx);if(insertedNode)insertionPoint=insertedNode.nextSibling}while(insertionPoint&&insertionPoint!=endPoint){let tempNode=insertionPoint;insertionPoint=insertionPoint.nextSibling,removeNode(ctx,tempNode)}}function createNode(oldParent,newChild,insertionPoint,ctx){if(ctx.callbacks.beforeNodeAdded(newChild)===!1)return null;if(ctx.idMap.has(newChild)){let newEmptyChild=document.createElement(newChild.tagName);return oldParent.insertBefore(newEmptyChild,insertionPoint),morphNode(newEmptyChild,newChild,ctx),ctx.callbacks.afterNodeAdded(newEmptyChild),newEmptyChild}else{let newClonedChild=document.importNode(newChild,!0);return oldParent.insertBefore(newClonedChild,insertionPoint),ctx.callbacks.afterNodeAdded(newClonedChild),newClonedChild}}let findBestMatch=function(){function findBestMatch2(ctx,node,startPoint,endPoint){let softMatch=null,nextSibling=node.nextSibling,siblingSoftMatchCount=0,cursor2=startPoint;while(cursor2&&cursor2!=endPoint){if(isSoftMatch(cursor2,node)){if(isIdSetMatch(ctx,cursor2,node))return cursor2;if(softMatch===null){if(!ctx.idMap.has(cursor2))softMatch=cursor2}}if(softMatch===null&&nextSibling&&isSoftMatch(cursor2,nextSibling)){if(siblingSoftMatchCount++,nextSibling=nextSibling.nextSibling,siblingSoftMatchCount>=2)softMatch=void 0}if(ctx.activeElementAndParents.includes(cursor2))break;cursor2=cursor2.nextSibling}return softMatch||null}function isIdSetMatch(ctx,oldNode,newNode){let oldSet=ctx.idMap.get(oldNode),newSet=ctx.idMap.get(newNode);if(!newSet||!oldSet)return!1;for(let id of oldSet)if(newSet.has(id))return!0;return!1}function isSoftMatch(oldNode,newNode){let oldElt=oldNode,newElt=newNode;return oldElt.nodeType===newElt.nodeType&&oldElt.tagName===newElt.tagName&&(!oldElt.getAttribute?.("id")||oldElt.getAttribute?.("id")===newElt.getAttribute?.("id"))}return findBestMatch2}();function removeNode(ctx,node){if(ctx.idMap.has(node))moveBefore(ctx.pantry,node,null);else{if(ctx.callbacks.beforeNodeRemoved(node)===!1)return;node.parentNode?.removeChild(node),ctx.callbacks.afterNodeRemoved(node)}}function removeNodesBetween(ctx,startInclusive,endExclusive){let cursor2=startInclusive;while(cursor2&&cursor2!==endExclusive){let tempNode=cursor2;cursor2=cursor2.nextSibling,removeNode(ctx,tempNode)}return cursor2}function moveBeforeById(parentNode,id,after,ctx){let target=ctx.target.getAttribute?.("id")===id&&ctx.target||ctx.target.querySelector(`[id="${id}"]`)||ctx.pantry.querySelector(`[id="${id}"]`);return removeElementFromAncestorsIdMaps(target,ctx),moveBefore(parentNode,target,after),target}function removeElementFromAncestorsIdMaps(element,ctx){let id=element.getAttribute("id");while(element=element.parentNode){let idSet=ctx.idMap.get(element);if(idSet){if(idSet.delete(id),!idSet.size)ctx.idMap.delete(element)}}}function moveBefore(parentNode,element,after){if(parentNode.moveBefore)try{parentNode.moveBefore(element,after)}catch(e){parentNode.insertBefore(element,after)}else parentNode.insertBefore(element,after)}return morphChildren2}(),morphNode=function(){function morphNode2(oldNode,newContent,ctx){if(ctx.ignoreActive&&oldNode===document.activeElement)return null;if(ctx.callbacks.beforeNodeMorphed(oldNode,newContent)===!1)return oldNode;if(oldNode instanceof HTMLHeadElement&&ctx.head.ignore);else if(oldNode instanceof HTMLHeadElement&&ctx.head.style!=="morph")handleHeadElement(oldNode,newContent,ctx);else if(morphAttributes(oldNode,newContent,ctx),!ignoreValueOfActiveElement(oldNode,ctx))morphChildren(ctx,oldNode,newContent);return ctx.callbacks.afterNodeMorphed(oldNode,newContent),oldNode}function morphAttributes(oldNode,newNode,ctx){let type=newNode.nodeType;if(type===1){let oldElt=oldNode,newElt=newNode,oldAttributes=oldElt.attributes,newAttributes=newElt.attributes;for(let newAttribute of newAttributes){if(ignoreAttribute(newAttribute.name,oldElt,"update",ctx))continue;if(oldElt.getAttribute(newAttribute.name)!==newAttribute.value)oldElt.setAttribute(newAttribute.name,newAttribute.value)}for(let i=oldAttributes.length-1;0<=i;i--){let oldAttribute=oldAttributes[i];if(!oldAttribute)continue;if(!newElt.hasAttribute(oldAttribute.name)){if(ignoreAttribute(oldAttribute.name,oldElt,"remove",ctx))continue;oldElt.removeAttribute(oldAttribute.name)}}if(!ignoreValueOfActiveElement(oldElt,ctx))syncInputValue(oldElt,newElt,ctx)}if(type===8||type===3){if(oldNode.nodeValue!==newNode.nodeValue)oldNode.nodeValue=newNode.nodeValue}}function syncInputValue(oldElement,newElement,ctx){if(oldElement instanceof HTMLInputElement&&newElement instanceof HTMLInputElement&&newElement.type!=="file"){let newValue=newElement.value,oldValue=oldElement.value;if(syncBooleanAttribute(oldElement,newElement,"checked",ctx),syncBooleanAttribute(oldElement,newElement,"disabled",ctx),!newElement.hasAttribute("value")){if(!ignoreAttribute("value",oldElement,"remove",ctx))oldElement.value="",oldElement.removeAttribute("value")}else if(oldValue!==newValue){if(!ignoreAttribute("value",oldElement,"update",ctx))oldElement.setAttribute("value",newValue),oldElement.value=newValue}}else if(oldElement instanceof HTMLOptionElement&&newElement instanceof HTMLOptionElement)syncBooleanAttribute(oldElement,newElement,"selected",ctx);else if(oldElement instanceof HTMLTextAreaElement&&newElement instanceof HTMLTextAreaElement){let newValue=newElement.value,oldValue=oldElement.value;if(ignoreAttribute("value",oldElement,"update",ctx))return;if(newValue!==oldValue)oldElement.value=newValue;if(oldElement.firstChild&&oldElement.firstChild.nodeValue!==newValue)oldElement.firstChild.nodeValue=newValue}}function syncBooleanAttribute(oldElement,newElement,attributeName,ctx){let newLiveValue=newElement[attributeName],oldLiveValue=oldElement[attributeName];if(newLiveValue!==oldLiveValue){let ignoreUpdate=ignoreAttribute(attributeName,oldElement,"update",ctx);if(!ignoreUpdate)oldElement[attributeName]=newElement[attributeName];if(newLiveValue){if(!ignoreUpdate)oldElement.setAttribute(attributeName,"")}else if(!ignoreAttribute(attributeName,oldElement,"remove",ctx))oldElement.removeAttribute(attributeName)}}function ignoreAttribute(attr,element,updateType,ctx){if(attr==="value"&&ctx.ignoreActiveValue&&element===document.activeElement)return!0;return ctx.callbacks.beforeAttributeUpdated(attr,element,updateType)===!1}function ignoreValueOfActiveElement(possibleActiveElement,ctx){return!!ctx.ignoreActiveValue&&possibleActiveElement===document.activeElement&&possibleActiveElement!==document.body}return morphNode2}();function withHeadBlocking(ctx,oldNode,newNode,callback){if(ctx.head.block){let oldHead=oldNode.querySelector("head"),newHead=newNode.querySelector("head");if(oldHead&&newHead){let promises=handleHeadElement(oldHead,newHead,ctx);return Promise.all(promises).then(()=>{let newCtx=Object.assign(ctx,{head:{block:!1,ignore:!0}});return callback(newCtx)})}}return callback(ctx)}function handleHeadElement(oldHead,newHead,ctx){let added=[],removed=[],preserved=[],nodesToAppend=[],srcToNewHeadNodes=new Map;for(let newHeadChild of newHead.children)srcToNewHeadNodes.set(newHeadChild.outerHTML,newHeadChild);for(let currentHeadElt of oldHead.children){let inNewContent=srcToNewHeadNodes.has(currentHeadElt.outerHTML),isReAppended=ctx.head.shouldReAppend(currentHeadElt),isPreserved=ctx.head.shouldPreserve(currentHeadElt);if(inNewContent||isPreserved)if(isReAppended)removed.push(currentHeadElt);else srcToNewHeadNodes.delete(currentHeadElt.outerHTML),preserved.push(currentHeadElt);else if(ctx.head.style==="append"){if(isReAppended)removed.push(currentHeadElt),nodesToAppend.push(currentHeadElt)}else if(ctx.head.shouldRemove(currentHeadElt)!==!1)removed.push(currentHeadElt)}nodesToAppend.push(...srcToNewHeadNodes.values());let promises=[];for(let newNode of nodesToAppend){let newElt=document.createRange().createContextualFragment(newNode.outerHTML).firstChild;if(ctx.callbacks.beforeNodeAdded(newElt)!==!1){if("href"in newElt&&newElt.href||"src"in newElt&&newElt.src){let resolve,promise=new Promise(function(_resolve){resolve=_resolve});newElt.addEventListener("load",function(){resolve()}),promises.push(promise)}oldHead.appendChild(newElt),ctx.callbacks.afterNodeAdded(newElt),added.push(newElt)}}for(let removedElement of removed)if(ctx.callbacks.beforeNodeRemoved(removedElement)!==!1)oldHead.removeChild(removedElement),ctx.callbacks.afterNodeRemoved(removedElement);return ctx.head.afterHeadMorphed(oldHead,{added,kept:preserved,removed}),promises}let createMorphContext=function(){function createMorphContext2(oldNode,newContent,config){let{persistentIds,idMap}=createIdMaps(oldNode,newContent),mergedConfig=mergeDefaults(config),morphStyle=mergedConfig.morphStyle||"outerHTML";if(!["innerHTML","outerHTML"].includes(morphStyle))throw`Do not understand how to morph style ${morphStyle}`;return{target:oldNode,newContent,config:mergedConfig,morphStyle,ignoreActive:mergedConfig.ignoreActive,ignoreActiveValue:mergedConfig.ignoreActiveValue,restoreFocus:mergedConfig.restoreFocus,idMap,persistentIds,pantry:createPantry(),activeElementAndParents:createActiveElementAndParents(oldNode),callbacks:mergedConfig.callbacks,head:mergedConfig.head}}function mergeDefaults(config){let finalConfig=Object.assign({},defaults);return Object.assign(finalConfig,config),finalConfig.callbacks=Object.assign({},defaults.callbacks,config.callbacks),finalConfig.head=Object.assign({},defaults.head,config.head),finalConfig}function createPantry(){let pantry=document.createElement("div");return pantry.hidden=!0,document.body.insertAdjacentElement("afterend",pantry),pantry}function createActiveElementAndParents(oldNode){let activeElementAndParents=[],elt=document.activeElement;if(elt?.tagName!=="BODY"&&oldNode.contains(elt))while(elt){if(activeElementAndParents.push(elt),elt===oldNode)break;elt=elt.parentElement}return activeElementAndParents}function findIdElements(root){let elements=Array.from(root.querySelectorAll("[id]"));if(root.getAttribute?.("id"))elements.push(root);return elements}function populateIdMapWithTree(idMap,persistentIds,root,elements){for(let elt of elements){let id=elt.getAttribute("id");if(persistentIds.has(id)){let current2=elt;while(current2){let idSet=idMap.get(current2);if(idSet==null)idSet=new Set,idMap.set(current2,idSet);if(idSet.add(id),current2===root)break;current2=current2.parentElement}}}}function createIdMaps(oldContent,newContent){let oldIdElements=findIdElements(oldContent),newIdElements=findIdElements(newContent),persistentIds=createPersistentIds(oldIdElements,newIdElements),idMap=new Map;populateIdMapWithTree(idMap,persistentIds,oldContent,oldIdElements);let newRoot=newContent.__idiomorphRoot||newContent;return populateIdMapWithTree(idMap,persistentIds,newRoot,newIdElements),{persistentIds,idMap}}function createPersistentIds(oldIdElements,newIdElements){let duplicateIds=new Set,oldIdTagNameMap=new Map;for(let{id,tagName}of oldIdElements)if(oldIdTagNameMap.has(id))duplicateIds.add(id);else oldIdTagNameMap.set(id,tagName);let persistentIds=new Set;for(let{id,tagName}of newIdElements)if(persistentIds.has(id))duplicateIds.add(id);else if(oldIdTagNameMap.get(id)===tagName)persistentIds.add(id);for(let id of duplicateIds)persistentIds.delete(id);return persistentIds}return createMorphContext2}(),{normalizeElement,normalizeParent}=function(){let generatedByIdiomorph=new WeakSet;function normalizeElement2(content){if(content instanceof Document)return content.documentElement;else return content}function normalizeParent2(newContent){if(newContent==null)return document.createElement("div");else if(typeof newContent==="string")return normalizeParent2(parseContent(newContent));else if(generatedByIdiomorph.has(newContent))return newContent;else if(newContent instanceof Node)if(newContent.parentNode)return new SlicedParentNode(newContent);else{let dummyParent=document.createElement("div");return dummyParent.append(newContent),dummyParent}else{let dummyParent=document.createElement("div");for(let elt of[...newContent])dummyParent.append(elt);return dummyParent}}class SlicedParentNode{constructor(node){this.originalNode=node,this.realParentNode=node.parentNode,this.previousSibling=node.previousSibling,this.nextSibling=node.nextSibling}get childNodes(){let nodes=[],cursor2=this.previousSibling?this.previousSibling.nextSibling:this.realParentNode.firstChild;while(cursor2&&cursor2!=this.nextSibling)nodes.push(cursor2),cursor2=cursor2.nextSibling;return nodes}querySelectorAll(selector){return this.childNodes.reduce((results,node)=>{if(node instanceof Element){if(node.matches(selector))results.push(node);let nodeList=node.querySelectorAll(selector);for(let i=0;i<nodeList.length;i++)results.push(nodeList[i])}return results},[])}insertBefore(node,referenceNode){return this.realParentNode.insertBefore(node,referenceNode)}moveBefore(node,referenceNode){return this.realParentNode.moveBefore(node,referenceNode)}get __idiomorphRoot(){return this.originalNode}}function parseContent(newContent){let parser=new DOMParser,contentWithSvgsRemoved=newContent.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(contentWithSvgsRemoved.match(/<\/html>/)||contentWithSvgsRemoved.match(/<\/head>/)||contentWithSvgsRemoved.match(/<\/body>/)){let content=parser.parseFromString(newContent,"text/html");if(contentWithSvgsRemoved.match(/<\/html>/))return generatedByIdiomorph.add(content),content;else{let htmlElement=content.firstChild;if(htmlElement)generatedByIdiomorph.add(htmlElement);return htmlElement}}else{let content=parser.parseFromString("<body><template>"+newContent+"</template></body>","text/html").body.querySelector("template").content;return generatedByIdiomorph.add(content),content}}return{normalizeElement:normalizeElement2,normalizeParent:normalizeParent2}}();return{morph,defaults}}();var listeners3=[];function onRefresh(listener){listeners3.push(listener)}function permanent(node){return node instanceof Element&&(node.hasAttribute("data-turbo-permanent")||node.hasAttribute("data-tensaku-permanent")||node.hasAttribute("data-tensaku-ui"))}function herbDevServer(){return Boolean(document.querySelector('meta[name="herb-dev-server-port"]'))}function replaceText(nodes,from,to){let normal=(text)=>text.replace(/\s+/g," ").trim(),target=normal(from);if(!target)return;for(let node of nodes)if(normal(node.data)===target){let lead=node.data.match(/^\s*/)[0],trail=node.data.match(/\s*$/)[0];node.data=lead+to.trim()+trail}else if(node.data.includes(from)&&from.trim())node.data=node.data.replace(from,to)}async function refresh(kind){if(meta().method!=="GET"){toast("Saved. This page came from a form submission, so reload to check it.",{timeout:7000});return}if(kind==="template"&&herbDevServer())return;try{let response=await fetch(location.href,{headers:{Accept:"text/html","X-Tensaku-Refresh":"1"},credentials:"same-origin"});if(!response.ok)throw Error(`HTTP ${response.status}`);let html=await response.text(),next=new DOMParser().parseFromString(html,"text/html");morph(next)}catch(error){toast(`Saved, but refreshing the page failed (${error.message}). Reload to check.`,{error:!0})}}var agentFetch=0;async function refreshAfterAgent(){if(meta().method!=="GET")return;let sequence=++agentFetch;try{let response=await fetch(location.href,{headers:{Accept:"text/html","X-Tensaku-Refresh":"1"},credentials:"same-origin"});if(!response.ok)return;let html=await response.text();if(sequence!==agentFetch)return;let next=new DOMParser().parseFromString(html,"text/html");swapStylesheets(next),morph(next)}catch{}}function swapStylesheets(next){let wanted=new Set(((doc)=>Array.from(doc.querySelectorAll('head link[rel="stylesheet"]')).map((link)=>link.getAttribute("href")))(next)),current2=Array.from(document.querySelectorAll('head link[rel="stylesheet"]')),have=new Set(current2.map((link)=>link.getAttribute("href"))),added=Array.from(next.querySelectorAll('head link[rel="stylesheet"]')).filter((link)=>!have.has(link.getAttribute("href")));if(!added.length)return;let stale=current2.filter((link)=>!wanted.has(link.getAttribute("href"))),waiting=added.length;for(let link of added){let copy2=document.importNode(link,!0),done=()=>{if(--waiting===0)stale.forEach((old)=>old.remove())};copy2.addEventListener("load",done),copy2.addEventListener("error",done),document.head.append(copy2)}}function changedByUser(element){if(element instanceof HTMLInputElement){if(element.type==="checkbox"||element.type==="radio")return element.checked!==element.defaultChecked;return element.type!=="file"&&element.value!==element.defaultValue}if(element instanceof HTMLTextAreaElement)return element.value!==element.defaultValue;if(element instanceof HTMLOptionElement)return element.selected!==element.defaultSelected;if(element instanceof HTMLSelectElement)return Array.from(element.options).some((option)=>option.selected!==option.defaultSelected);return!1}var FORM_STATE=new Set(["value","checked","selected"]);function morph(next){let lazyFrames=Array.from(document.querySelectorAll("turbo-frame[src]"));if(Idiomorph.morph(document.body,next.body,{morphStyle:"outerHTML",ignoreActiveValue:!0,restoreFocus:!0,callbacks:{beforeNodeMorphed:(oldNode)=>!permanent(oldNode)&&!(oldNode instanceof HTMLTextAreaElement&&changedByUser(oldNode)),beforeAttributeUpdated:(name,element)=>!(FORM_STATE.has(name)&&changedByUser(element)),beforeNodeRemoved:(node)=>!permanent(node)}}),next.title)document.title=next.title;for(let frame of lazyFrames)if(frame.isConnected&&typeof frame.reload==="function"&&!frame.hasAttribute("complete"))frame.reload();listeners3.forEach((listener)=>listener())}var notes=[],scoped=[],scope=null,openCount=0,agents=[],currentNotes=()=>notes,scopedNotes=()=>scoped,currentAgents=()=>agents,openNotes=()=>openCount,agentLabel=(agent)=>agent.handle?`${agent.name} · ${agent.handle}`:agent.name,listeners4=()=>agents.filter((agent)=>agent.listening).map(agentLabel),closed=(note)=>note.status==="resolved"||note.status==="declined",renderListeners=[],countListeners=[],agentListeners=[],changeListeners=[],onRender=(listener)=>renderListeners.push(listener),onCount=(listener)=>countListeners.push(listener),onAgents=(listener)=>agentListeners.push(listener),onChanges=(listener)=>changeListeners.push(listener),normalized=(list)=>list.map((note)=>({...note,targets:note.targets??[]})),lastSignature="",loadSequence=0,tokenWarned=!1,restartWarned=!1,agentChangedAt,primed=!1;async function load({force=!1}={}){let sequence=++loadSequence,first=!1;try{let data=await api("GET","/notes"+query({url:location.pathname}));if(sequence!==loadSequence)return;if(tokenWarned=!1,primed&&data.changed_at&&data.changed_at!==agentChangedAt)refreshAfterAgent();if(agentChangedAt=data.changed_at,data.restart&&!restartWarned)restartWarned=!0,toast("Tensaku's code changed since this dev server started, so the page runs a newer overlay than the server. Restart the dev server.",{error:!0,timeout:20000});data.notes=data.notes.filter((note)=>!pendingDeletes.has(note.id)),agents=data.agents??[],agentListeners.forEach((listener)=>listener(agents));let signature=location.pathname+JSON.stringify([data.notes,data.open,listeners4()]);if(!force&&signature===lastSignature)return;let which=scope,all=which&&which!=="page"?await scopeNotes(which):null;if(sequence!==loadSequence)return;lastSignature=signature;let after=normalized(data.notes);if(primed&&data.notes.length&&notes.length)changeListeners.forEach((listener)=>listener(notes,after));if(first=!primed,primed=!0,notes=after,openCount=data.open,all&&scope===which)scoped=all}catch(error){if(sequence!==loadSequence)return;if(error instanceof ApiError&&error.status===403&&!tokenWarned)tokenWarned=!0,toast(`${error.message} Notes can't be loaded until then.`,{error:!0,timeout:15000,actions:{Reload:()=>location.reload()}});return}countListeners.forEach((listener)=>listener(openCount)),render({force,first})}function render(what){renderListeners.forEach((listener)=>listener(what))}var scopeNotes=async(which)=>normalized((await api("GET","/notes"+(which==="archived"?query({archived:"1"}):""))).notes).filter((note)=>!pendingDeletes.has(note.id));async function setScope(which){if(scope=which,which&&which!=="page")scoped=await scopeNotes(which)}var streaming=!1;function poll(){let pending=0,changed=()=>{clearTimeout(pending),pending=window.setTimeout(()=>load(),30)},editedPending=0,edited=()=>{clearTimeout(editedPending),editedPending=window.setTimeout(refreshAfterAgent,150)},connect=async()=>{let retry=5000;try{let{token,root}=meta(),response=await fetch(root+"/events",{headers:{"X-Tensaku-Token":token,Accept:"text/event-stream"},credentials:"same-origin"});if(response.status===501)return;if(!response.ok||!response.body)throw Error(`events ${response.status}`);streaming=!0;let reader=response.body.pipeThrough(new TextDecoderStream).getReader(),buffer="";for(;;){let{value,done}=await reader.read();if(done)break;buffer+=value;let events=buffer.split(`
363
370
 
364
- `);if(buffer=events.pop()??"",events.includes("data: changed"))changed();if(events.includes("data: edited"))edited()}}catch{retry=15000}streaming=!1,setTimeout(connect,retry)},tick=async()=>{if(!streaming&&(document.visibilityState==="visible"||settings().notify))await load();setTimeout(tick,document.visibilityState==="visible"?4000:16000)};connect(),setTimeout(tick,4000)}var localChanges=new Set,changedHere=(id)=>localChanges.delete(id);function replace(note,removed=!1){let swap=(list)=>removed?list.filter((other)=>other.id!==note.id):list.map((other)=>other.id===note.id?note:other);notes=swap(notes),scoped=swap(scoped),lastSignature="",render({force:!0,changed:removed?void 0:note})}function predicted(note,change){let next={...note,thread:[...note.thread??[]]};if(change.comment)next.comment=change.comment;if(change.message)next.thread.push({from:"you",text:change.message,at:new Date().toISOString()});if(change.status)next.status=change.status;if(change.to!==void 0){let chosen=agents.find((agent)=>agent.handle===change.to);Object.assign(next,{status:"open",agent:chosen?agentLabel(chosen):void 0,delivered_at:void 0,delivered_to:void 0,stopped:void 0})}if(next.status==="open"&&(change.comment||change.message||change.to!==void 0))next.sent_at=new Date().toISOString();return next}async function updateNote(note,change,onChange=()=>{}){let after=predicted(note,change);localChanges.add(note.id),replace(after),onChange(after);try{return await api("PATCH",`/notes/${note.id}`,change),load({force:!0}),!0}catch(error){return localChanges.delete(note.id),replace(note),onChange(note),toast(error.message,{error:!0}),!1}}var pendingDeletes=new Map;addEventListener("pagehide",()=>pendingDeletes.forEach((commit)=>commit()));function deleteLater(note){replace(note,!0);let done=!1,commit=()=>{if(done)return;done=!0,pendingDeletes.delete(note.id),api("DELETE",`/notes/${note.id}`).catch((error)=>toast(error.message,{error:!0})).finally(()=>load({force:!0}))};pendingDeletes.set(note.id,commit);let timer=setTimeout(commit,6000);toast("Note deleted",{timeout:6000,actions:{Undo:()=>{done=!0,clearTimeout(timer),pendingDeletes.delete(note.id),load({force:!0})}}})}async function deleteNotes(list){try{for(let note of list)await api("DELETE",`/notes/${note.id}`)}finally{await load({force:!0})}}var PREFIX="[modern-screenshot]",IN_BROWSER=typeof window<"u",SUPPORT_WEB_WORKER=IN_BROWSER&&"Worker"in window,SUPPORT_ATOB=IN_BROWSER&&"atob"in window,SUPPORT_BTOA=IN_BROWSER&&"btoa"in window,USER_AGENT=IN_BROWSER?window.navigator?.userAgent:"",IN_CHROME=USER_AGENT.includes("Chrome"),IN_SAFARI=USER_AGENT.includes("AppleWebKit")&&!IN_CHROME,IN_FIREFOX=USER_AGENT.includes("Firefox"),isContext=(value)=>value&&("__CONTEXT__"in value),isCssFontFaceRule=(rule)=>rule.constructor.name==="CSSFontFaceRule",isCSSImportRule=(rule)=>rule.constructor.name==="CSSImportRule",isLayerBlockRule=(rule)=>rule.constructor.name==="CSSLayerBlockRule",isElementNode=(node)=>node.nodeType===1,isSVGElementNode=(node)=>typeof node.className==="object",isSVGImageElementNode=(node)=>node.tagName==="image",isSVGUseElementNode=(node)=>node.tagName==="use",isHTMLElementNode=(node)=>isElementNode(node)&&typeof node.style<"u"&&!isSVGElementNode(node),isCommentNode=(node)=>node.nodeType===8,isTextNode=(node)=>node.nodeType===3,isImageElement=(node)=>node.tagName==="IMG",isVideoElement=(node)=>node.tagName==="VIDEO",isCanvasElement=(node)=>node.tagName==="CANVAS",isTextareaElement=(node)=>node.tagName==="TEXTAREA",isInputElement=(node)=>node.tagName==="INPUT",isStyleElement=(node)=>node.tagName==="STYLE",isScriptElement=(node)=>node.tagName==="SCRIPT",isSelectElement=(node)=>node.tagName==="SELECT",isSlotElement=(node)=>node.tagName==="SLOT",isIFrameElement=(node)=>node.tagName==="IFRAME",consoleWarn=(...args)=>console.warn(PREFIX,...args);function supportWebp(ownerDocument){let canvas=ownerDocument?.createElement?.("canvas");if(canvas)canvas.height=canvas.width=1;return Boolean(canvas)&&"toDataURL"in canvas&&Boolean(canvas.toDataURL("image/webp").includes("image/webp"))}var isDataUrl=(url)=>url.startsWith("data:");function resolveUrl(url,baseUrl){if(url.match(/^[a-z]+:\/\//i))return url;if(IN_BROWSER&&url.match(/^\/\//))return window.location.protocol+url;if(url.match(/^[a-z]+:/i))return url;if(!IN_BROWSER)return url;let doc=getDocument().implementation.createHTMLDocument(),base=doc.createElement("base"),a=doc.createElement("a");if(doc.head.appendChild(base),doc.body.appendChild(a),baseUrl)base.href=baseUrl;return a.href=url,a.href}function getDocument(target){return(target&&isElementNode(target)?target?.ownerDocument:target)??window.document}var XMLNS="http://www.w3.org/2000/svg";function createSvg(width,height,ownerDocument){let svg=getDocument(ownerDocument).createElementNS(XMLNS,"svg");return svg.setAttributeNS(null,"width",width.toString()),svg.setAttributeNS(null,"height",height.toString()),svg.setAttributeNS(null,"viewBox",`0 0 ${width} ${height}`),svg}function svgToDataUrl(svg,removeControlCharacter){let xhtml=new XMLSerializer().serializeToString(svg);if(removeControlCharacter)xhtml=xhtml.replace(/[\u0000-\u0008\v\f\u000E-\u001F\uD800-\uDFFF\uFFFE\uFFFF]/gu,"");return`data:image/svg+xml;charset=utf-8,${encodeURIComponent(xhtml)}`}function readBlob(blob,type){return new Promise((resolve,reject)=>{let reader=new FileReader;if(reader.onload=()=>resolve(reader.result),reader.onerror=()=>reject(reader.error),reader.onabort=()=>reject(Error(`Failed read blob to ${type}`)),type==="dataUrl")reader.readAsDataURL(blob);else if(type==="arrayBuffer")reader.readAsArrayBuffer(blob)})}var blobToDataUrl=(blob)=>readBlob(blob,"dataUrl");function createImage(url,ownerDocument){let img=getDocument(ownerDocument).createElement("img");return img.decoding="sync",img.loading="eager",img.src=url,img}function loadMedia(media,options){return new Promise((resolve)=>{let{timeout,ownerDocument,onError:userOnError,onWarn}=options??{},node=typeof media==="string"?createImage(media,getDocument(ownerDocument)):media,timer=null,removeEventListeners=null;function onResolve(){resolve(node),timer&&clearTimeout(timer),removeEventListeners?.()}if(timeout)timer=setTimeout(onResolve,timeout);if(isVideoElement(node)){let currentSrc=node.currentSrc||node.src;if(!currentSrc){if(node.poster)return loadMedia(node.poster,options).then(resolve);return onResolve()}if(node.readyState>=2)return onResolve();let onLoadeddata=onResolve,onError=(error)=>{onWarn?.("Failed video load",currentSrc,error),userOnError?.(error),onResolve()};removeEventListeners=()=>{node.removeEventListener("loadeddata",onLoadeddata),node.removeEventListener("error",onError)},node.addEventListener("loadeddata",onLoadeddata,{once:!0}),node.addEventListener("error",onError,{once:!0})}else{let currentSrc=isSVGImageElementNode(node)?node.href.baseVal:node.currentSrc||node.src;if(!currentSrc)return onResolve();let onLoad=async()=>{if(isImageElement(node)&&"decode"in node)try{await node.decode()}catch(error){onWarn?.("Failed to decode image, trying to render anyway",node.dataset.originalSrc||currentSrc,error)}onResolve()},onError=(error)=>{onWarn?.("Failed image load",node.dataset.originalSrc||currentSrc,error),onResolve()};if(isImageElement(node)&&node.complete)return onLoad();removeEventListeners=()=>{node.removeEventListener("load",onLoad),node.removeEventListener("error",onError)},node.addEventListener("load",onLoad,{once:!0}),node.addEventListener("error",onError,{once:!0})}})}async function waitUntilLoad(node,options){if(isHTMLElementNode(node))if(isImageElement(node)||isVideoElement(node))await loadMedia(node,options);else await Promise.all(["img","video"].flatMap((selectors)=>{return Array.from(node.querySelectorAll(selectors)).map((el)=>loadMedia(el,options))}))}var uuid=function(){let counter=0,random=()=>`0000${(Math.random()*1679616<<0).toString(36)}`.slice(-4);return()=>{return counter+=1,`u${random()}${counter}`}}();function splitFontFamily(fontFamily){return fontFamily?.split(",").map((val)=>val.trim().replace(/"|'/g,"").toLowerCase()).filter(Boolean)}var uid=0;function createLogger(debug){let prefix=`${PREFIX}[#${uid}]`;return uid++,{time:(label)=>debug&&console.time(`${prefix} ${label}`),timeEnd:(label)=>debug&&console.timeEnd(`${prefix} ${label}`),warn:(...args)=>debug&&consoleWarn(...args)}}function getDefaultRequestInit(bypassingCache){return{cache:bypassingCache?"no-cache":"force-cache"}}async function orCreateContext(node,options){return isContext(node)?node:createContext(node,{...options,autoDestruct:!0})}async function createContext(node,options){let{scale=1,workerUrl,workerNumber=1}=options||{},debug=Boolean(options?.debug),features=options?.features??!0,ownerDocument=node.ownerDocument??(IN_BROWSER?window.document:void 0),ownerWindow=node.ownerDocument?.defaultView??(IN_BROWSER?window:void 0),requests=new Map,context={width:0,height:0,quality:1,type:"image/png",scale,backgroundColor:null,style:null,filter:null,maximumCanvasSize:0,timeout:30000,progress:null,debug,fetch:{requestInit:getDefaultRequestInit(options?.fetch?.bypassingCache),placeholderImage:"data:image/png;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7",bypassingCache:!1,...options?.fetch},fetchFn:null,font:{},drawImageInterval:100,workerUrl:null,workerNumber,onCloneEachNode:null,onCloneNode:null,onEmbedNode:null,onCreateForeignObjectSvg:null,includeStyleProperties:null,autoDestruct:!1,...options,__CONTEXT__:!0,log:createLogger(debug),node,ownerDocument,ownerWindow,dpi:scale===1?null:96*scale,svgStyleElement:createStyleElement(ownerDocument),svgDefsElement:ownerDocument?.createElementNS(XMLNS,"defs"),svgStyles:new Map,defaultComputedStyles:new Map,workers:[...Array.from({length:SUPPORT_WEB_WORKER&&workerUrl&&workerNumber?workerNumber:0})].map(()=>{try{let worker=new Worker(workerUrl);return worker.onmessage=async(event)=>{let{url,result}=event.data;if(result)requests.get(url)?.resolve?.(result);else requests.get(url)?.reject?.(Error(`Error receiving message from worker: ${url}`))},worker.onmessageerror=(event)=>{let{url}=event.data;requests.get(url)?.reject?.(Error(`Error receiving message from worker: ${url}`))},worker}catch(error){return context.log.warn("Failed to new Worker",error),null}}).filter(Boolean),fontFamilies:new Map,fontCssTexts:new Map,acceptOfImage:`${[supportWebp(ownerDocument)&&"image/webp","image/svg+xml","image/*","*/*"].filter(Boolean).join(",")};q=0.8`,requests,drawImageCount:0,tasks:[],features,isEnable:(key)=>{if(key==="restoreScrollPosition")return typeof features==="boolean"?!1:features[key]??!1;if(typeof features==="boolean")return features;return features[key]??!0},shadowRoots:[]};context.log.time("wait until load"),await waitUntilLoad(node,{timeout:context.timeout,onWarn:context.log.warn}),context.log.timeEnd("wait until load");let{width,height}=resolveBoundingBox(node,context);return context.width=width,context.height=height,context}function createStyleElement(ownerDocument){if(!ownerDocument)return;let style=ownerDocument.createElement("style"),cssText=style.ownerDocument.createTextNode(`
371
+ `);if(buffer=events.pop()??"",events.includes("data: changed"))changed();if(events.includes("data: edited"))edited()}}catch{retry=15000}streaming=!1,setTimeout(connect,retry)},tick=async()=>{if(!streaming&&(document.visibilityState==="visible"||settings().notify))await load();setTimeout(tick,document.visibilityState==="visible"?4000:16000)};connect(),setTimeout(tick,4000)}var localChanges=new Set,changedHere=(id)=>localChanges.delete(id);function replace(note,removed=!1){let swap=(list)=>removed?list.filter((other)=>other.id!==note.id):list.map((other)=>other.id===note.id?note:other);notes=swap(notes),scoped=swap(scoped),lastSignature="",render({force:!0,changed:removed?void 0:note})}function predicted(note,change){let next={...note,thread:[...note.thread??[]]};if(change.comment)next.comment=change.comment;if(change.message)next.thread.push({from:"you",text:change.message,at:new Date().toISOString()});if(change.status)next.status=change.status;if(change.targets)Object.assign(next,{targets:change.targets,held_at:void 0});if(change.to!==void 0){let chosen=agents.find((agent)=>agent.handle===change.to);Object.assign(next,{status:"open",agent:chosen?agentLabel(chosen):void 0,delivered_at:void 0,delivered_to:void 0,stopped:void 0})}if(next.status==="open"&&(change.comment||change.message||change.targets||change.to!==void 0))next.sent_at=new Date().toISOString();return next}async function updateNote(note,change,onChange=()=>{}){let after=predicted(note,change);localChanges.add(note.id),replace(after),onChange(after);try{return await api("PATCH",`/notes/${note.id}`,change),load({force:!0}),!0}catch(error){return localChanges.delete(note.id),replace(note),onChange(note),toast(error.message,{error:!0}),!1}}var pendingDeletes=new Map;addEventListener("pagehide",()=>pendingDeletes.forEach((commit)=>commit()));function deleteLater(note){replace(note,!0);let done=!1,commit=()=>{if(done)return;done=!0,pendingDeletes.delete(note.id),api("DELETE",`/notes/${note.id}`).catch((error)=>toast(error.message,{error:!0})).finally(()=>load({force:!0}))};pendingDeletes.set(note.id,commit);let timer=setTimeout(commit,6000);toast("Note deleted",{timeout:6000,actions:{Undo:()=>{done=!0,clearTimeout(timer),pendingDeletes.delete(note.id),load({force:!0})}}})}async function deleteNotes(list){try{for(let note of list)await api("DELETE",`/notes/${note.id}`)}finally{await load({force:!0})}}var PREFIX="[modern-screenshot]",IN_BROWSER=typeof window<"u",SUPPORT_WEB_WORKER=IN_BROWSER&&"Worker"in window,SUPPORT_ATOB=IN_BROWSER&&"atob"in window,SUPPORT_BTOA=IN_BROWSER&&"btoa"in window,USER_AGENT=IN_BROWSER?window.navigator?.userAgent:"",IN_CHROME=USER_AGENT.includes("Chrome"),IN_SAFARI=USER_AGENT.includes("AppleWebKit")&&!IN_CHROME,IN_FIREFOX=USER_AGENT.includes("Firefox"),isContext=(value)=>value&&("__CONTEXT__"in value),isCssFontFaceRule=(rule)=>rule.constructor.name==="CSSFontFaceRule",isCSSImportRule=(rule)=>rule.constructor.name==="CSSImportRule",isLayerBlockRule=(rule)=>rule.constructor.name==="CSSLayerBlockRule",isElementNode=(node)=>node.nodeType===1,isSVGElementNode=(node)=>typeof node.className==="object",isSVGImageElementNode=(node)=>node.tagName==="image",isSVGUseElementNode=(node)=>node.tagName==="use",isHTMLElementNode=(node)=>isElementNode(node)&&typeof node.style<"u"&&!isSVGElementNode(node),isCommentNode=(node)=>node.nodeType===8,isTextNode=(node)=>node.nodeType===3,isImageElement=(node)=>node.tagName==="IMG",isVideoElement=(node)=>node.tagName==="VIDEO",isCanvasElement=(node)=>node.tagName==="CANVAS",isTextareaElement=(node)=>node.tagName==="TEXTAREA",isInputElement=(node)=>node.tagName==="INPUT",isStyleElement=(node)=>node.tagName==="STYLE",isScriptElement=(node)=>node.tagName==="SCRIPT",isSelectElement=(node)=>node.tagName==="SELECT",isSlotElement=(node)=>node.tagName==="SLOT",isIFrameElement=(node)=>node.tagName==="IFRAME",consoleWarn=(...args)=>console.warn(PREFIX,...args);function supportWebp(ownerDocument){let canvas=ownerDocument?.createElement?.("canvas");if(canvas)canvas.height=canvas.width=1;return Boolean(canvas)&&"toDataURL"in canvas&&Boolean(canvas.toDataURL("image/webp").includes("image/webp"))}var isDataUrl=(url)=>url.startsWith("data:");function resolveUrl(url,baseUrl){if(url.match(/^[a-z]+:\/\//i))return url;if(IN_BROWSER&&url.match(/^\/\//))return window.location.protocol+url;if(url.match(/^[a-z]+:/i))return url;if(!IN_BROWSER)return url;let doc=getDocument().implementation.createHTMLDocument(),base=doc.createElement("base"),a=doc.createElement("a");if(doc.head.appendChild(base),doc.body.appendChild(a),baseUrl)base.href=baseUrl;return a.href=url,a.href}function getDocument(target){return(target&&isElementNode(target)?target?.ownerDocument:target)??window.document}var XMLNS="http://www.w3.org/2000/svg";function createSvg(width,height,ownerDocument){let svg=getDocument(ownerDocument).createElementNS(XMLNS,"svg");return svg.setAttributeNS(null,"width",width.toString()),svg.setAttributeNS(null,"height",height.toString()),svg.setAttributeNS(null,"viewBox",`0 0 ${width} ${height}`),svg}function svgToDataUrl(svg,removeControlCharacter){let xhtml=new XMLSerializer().serializeToString(svg);if(removeControlCharacter)xhtml=xhtml.replace(/[\u0000-\u0008\v\f\u000E-\u001F\uD800-\uDFFF\uFFFE\uFFFF]/gu,"");return`data:image/svg+xml;charset=utf-8,${encodeURIComponent(xhtml)}`}function readBlob(blob,type){return new Promise((resolve,reject)=>{let reader=new FileReader;if(reader.onload=()=>resolve(reader.result),reader.onerror=()=>reject(reader.error),reader.onabort=()=>reject(Error(`Failed read blob to ${type}`)),type==="dataUrl")reader.readAsDataURL(blob);else if(type==="arrayBuffer")reader.readAsArrayBuffer(blob)})}var blobToDataUrl=(blob)=>readBlob(blob,"dataUrl");function createImage(url,ownerDocument){let img=getDocument(ownerDocument).createElement("img");return img.decoding="sync",img.loading="eager",img.src=url,img}function loadMedia(media,options){return new Promise((resolve)=>{let{timeout,ownerDocument,onError:userOnError,onWarn}=options??{},node=typeof media==="string"?createImage(media,getDocument(ownerDocument)):media,timer=null,removeEventListeners=null;function onResolve(){resolve(node),timer&&clearTimeout(timer),removeEventListeners?.()}if(timeout)timer=setTimeout(onResolve,timeout);if(isVideoElement(node)){let currentSrc=node.currentSrc||node.src;if(!currentSrc){if(node.poster)return loadMedia(node.poster,options).then(resolve);return onResolve()}if(node.readyState>=2)return onResolve();let onLoadeddata=onResolve,onError=(error)=>{onWarn?.("Failed video load",currentSrc,error),userOnError?.(error),onResolve()};removeEventListeners=()=>{node.removeEventListener("loadeddata",onLoadeddata),node.removeEventListener("error",onError)},node.addEventListener("loadeddata",onLoadeddata,{once:!0}),node.addEventListener("error",onError,{once:!0})}else{let currentSrc=isSVGImageElementNode(node)?node.href.baseVal:node.currentSrc||node.src;if(!currentSrc)return onResolve();let onLoad=async()=>{if(isImageElement(node)&&"decode"in node)try{await node.decode()}catch(error){onWarn?.("Failed to decode image, trying to render anyway",node.dataset.originalSrc||currentSrc,error)}onResolve()},onError=(error)=>{onWarn?.("Failed image load",node.dataset.originalSrc||currentSrc,error),onResolve()};if(isImageElement(node)&&node.complete)return onLoad();removeEventListeners=()=>{node.removeEventListener("load",onLoad),node.removeEventListener("error",onError)},node.addEventListener("load",onLoad,{once:!0}),node.addEventListener("error",onError,{once:!0})}})}async function waitUntilLoad(node,options){if(isHTMLElementNode(node))if(isImageElement(node)||isVideoElement(node))await loadMedia(node,options);else await Promise.all(["img","video"].flatMap((selectors)=>{return Array.from(node.querySelectorAll(selectors)).map((el)=>loadMedia(el,options))}))}var uuid=function(){let counter=0,random=()=>`0000${(Math.random()*1679616<<0).toString(36)}`.slice(-4);return()=>{return counter+=1,`u${random()}${counter}`}}();function splitFontFamily(fontFamily){return fontFamily?.split(",").map((val)=>val.trim().replace(/"|'/g,"").toLowerCase()).filter(Boolean)}var uid=0;function createLogger(debug){let prefix=`${PREFIX}[#${uid}]`;return uid++,{time:(label)=>debug&&console.time(`${prefix} ${label}`),timeEnd:(label)=>debug&&console.timeEnd(`${prefix} ${label}`),warn:(...args)=>debug&&consoleWarn(...args)}}function getDefaultRequestInit(bypassingCache){return{cache:bypassingCache?"no-cache":"force-cache"}}async function orCreateContext(node,options){return isContext(node)?node:createContext(node,{...options,autoDestruct:!0})}async function createContext(node,options){let{scale=1,workerUrl,workerNumber=1}=options||{},debug=Boolean(options?.debug),features=options?.features??!0,ownerDocument=node.ownerDocument??(IN_BROWSER?window.document:void 0),ownerWindow=node.ownerDocument?.defaultView??(IN_BROWSER?window:void 0),requests=new Map,context={width:0,height:0,quality:1,type:"image/png",scale,backgroundColor:null,style:null,filter:null,maximumCanvasSize:0,timeout:30000,progress:null,debug,fetch:{requestInit:getDefaultRequestInit(options?.fetch?.bypassingCache),placeholderImage:"data:image/png;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7",bypassingCache:!1,...options?.fetch},fetchFn:null,font:{},drawImageInterval:100,workerUrl:null,workerNumber,onCloneEachNode:null,onCloneNode:null,onEmbedNode:null,onCreateForeignObjectSvg:null,includeStyleProperties:null,autoDestruct:!1,...options,__CONTEXT__:!0,log:createLogger(debug),node,ownerDocument,ownerWindow,dpi:scale===1?null:96*scale,svgStyleElement:createStyleElement(ownerDocument),svgDefsElement:ownerDocument?.createElementNS(XMLNS,"defs"),svgStyles:new Map,defaultComputedStyles:new Map,workers:[...Array.from({length:SUPPORT_WEB_WORKER&&workerUrl&&workerNumber?workerNumber:0})].map(()=>{try{let worker=new Worker(workerUrl);return worker.onmessage=async(event)=>{let{url,result}=event.data;if(result)requests.get(url)?.resolve?.(result);else requests.get(url)?.reject?.(Error(`Error receiving message from worker: ${url}`))},worker.onmessageerror=(event)=>{let{url}=event.data;requests.get(url)?.reject?.(Error(`Error receiving message from worker: ${url}`))},worker}catch(error){return context.log.warn("Failed to new Worker",error),null}}).filter(Boolean),fontFamilies:new Map,fontCssTexts:new Map,acceptOfImage:`${[supportWebp(ownerDocument)&&"image/webp","image/svg+xml","image/*","*/*"].filter(Boolean).join(",")};q=0.8`,requests,drawImageCount:0,tasks:[],features,isEnable:(key)=>{if(key==="restoreScrollPosition")return typeof features==="boolean"?!1:features[key]??!1;if(typeof features==="boolean")return features;return features[key]??!0},shadowRoots:[]};context.log.time("wait until load"),await waitUntilLoad(node,{timeout:context.timeout,onWarn:context.log.warn}),context.log.timeEnd("wait until load");let{width,height}=resolveBoundingBox(node,context);return context.width=width,context.height=height,context}function createStyleElement(ownerDocument){if(!ownerDocument)return;let style=ownerDocument.createElement("style"),cssText=style.ownerDocument.createTextNode(`
365
372
  .______background-clip--text {
366
373
  background-clip: text;
367
374
  -webkit-background-clip: text;
@@ -374,8 +381,8 @@ kbd { font: 10.5px/1 var(--mono); padding: 2px 4px; border-radius: 4px; backgrou
374
381
  `)} {
375
382
  ${cssText}
376
383
  }
377
- `}),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){let fraction=(value)=>Math.round(Math.min(Math.max(value,0),1)*1000)/1000;targets=[{...targets[0],point:[fraction((at.x-anchor.x)/anchor.width),fraction((at.y-anchor.y)/anchor.height)]}]}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 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(`
378
- `)},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),missing=!done&&here&&!anchorFor(note)?div("missing","Not found on this page any more."):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=listeners3(),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)&&note.thread[messages-1].from==="agent"&&note.status===previous.status)announce(note,"message");else if(note.status!==previous.status&&note.status!=="open"&&note.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(`
379
- `),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",listeners4=[],mode=()=>current2,onMode=(listener)=>listeners4.push(listener);function setMode(next){current2=next,listeners4.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 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()});function drawPins(){pinLayer.replaceChildren(),currentNotes().forEach((note,index)=>{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":""}`,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=[],last={};try{for(let{name,piece,text}of changed){last=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},last.file);afterSave({...last,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(`
380
- `).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&&(element.hasAttribute(STAMP)||element.hasAttribute(MARKDOWN)));function step(element,key){if(key==="ArrowUp"){for(let node=element.parentElement;node&&node!==document.body;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 parent=step(element,"ArrowUp")??document.body,siblings=Array.from(parent.querySelectorAll(`[${STAMP}], [${MARKDOWN}]`)).filter((node)=>stamped(node)&&step(node,"ArrowUp")===(parent===document.body?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 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(`
381
- `)}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)||!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||mode()==="inspect"?cursor("highlighter",INK.highlighter):mode()==="edit"?cursor("pen",INK.pen):""}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||menuOpen()||isEditing())return;let element=pageTarget(event);if(!element)return clearHover();let editing=mode()==="edit"&&!altHeld;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())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),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()},!0);function escape(){if(isEditing()||typingInPage())return;let field2=activeInShadow();if(field2?.matches("textarea, input, [contenteditable]")){field2.blur();return}if(popoverOpen())closePopover();else if(menuOpen())closeMenu();else if(closeNote()||closeSidePanel())return;else if(mode()!=="off")setMode("off");else closeToolbar()}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()});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(),mount(),placeDock(),load(),poll(),syncPins(),new MutationObserver(()=>mount()).observe(document.documentElement,{childList:!0})}boot();})();
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
+ `)},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)&&note.thread[messages-1].from==="agent"&&note.status===previous.status)announce(note,"message");else if(note.status!==previous.status&&note.status!=="open"&&note.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(`
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();})();
@@ -104,6 +104,10 @@ module Tensaku
104
104
  in [ "GET", %r{\A/notes/[a-z0-9]+/screenshot\z} ]
105
105
  shot = Notes.screenshot(note_id) or raise Notes::NotFound, "That note has no screenshot"
106
106
  [ 200, { "content-type" => "image/png", "cache-control" => "no-store" }, [ shot["png"] ] ]
107
+ in [ "PATCH", %r{\A/notes/[a-z0-9]+\z} ] if params.key?("targets")
108
+ json(Notes.retarget(note_id, params["targets"]))
109
+ in [ "PATCH", %r{\A/notes/[a-z0-9]+\z} ] if params.key?("held")
110
+ json(Notes.hold(note_id, params["held"] == true))
107
111
  in [ "PATCH", %r{\A/notes/[a-z0-9]+\z} ]
108
112
  # An edit or a message is for the agent: the note is sent again. A status change alone (done,
109
113
  # reopened, or undoing either) isn't.
data/lib/tensaku/i18n.rb CHANGED
@@ -6,14 +6,17 @@ module Tensaku
6
6
  # A marker is U+2063 (invisible separator), then "locale:key" as UTF-8 bytes written in base 4 with
7
7
  # four zero-width characters, then U+2063 again. Nothing shows if the overlay never runs.
8
8
  #
9
- # Markers are only added while a controller handles an HTML request, never to `number.*`, `date.*`,
10
- # `time.*` and similar keys, never to a value that came from a `default:` instead of the key, and
11
- # never to pluralized lookups. A Ruby comparison against a translated string sees the marker, which
12
- # is the known cost of this technique (development only).
9
+ # Markers are only added while a template of an HTML page renders, never to `number.*`, `date.*`,
10
+ # `time.*` and similar keys, never to a value that came from a `default:` instead of the key, never
11
+ # to pluralized lookups, and never to a blank value: it has no text to edit, and `t(...).present?`
12
+ # must stay false. A Ruby comparison against a translated string sees the marker, which is the
13
+ # known cost of this technique (development only).
13
14
  module I18nMarkers
14
15
  FENCE = "⁣"
15
16
  DIGITS = [ "​", "‌", "‍", "⁠" ].freeze
16
17
  PATTERN = /#{FENCE}[#{DIGITS.join}]+#{FENCE}/o
18
+ # What is left of a marker that the app cut short, such as a title truncated for a meta tag.
19
+ CUT = /#{FENCE}[#{DIGITS.join}]*/o
17
20
  SKIP = /\A(?:number|date|time|datetime|support|i18n|helpers\.submit|errors\.format)(?:\.|\z)/
18
21
 
19
22
  module_function
@@ -41,7 +44,7 @@ module Tensaku
41
44
  end
42
45
 
43
46
  def strip(text)
44
- text.include?(FENCE) ? text.gsub(PATTERN, "") : text
47
+ text.include?(FENCE) ? text.gsub(PATTERN, "").gsub(CUT, "") : text
45
48
  end
46
49
 
47
50
  # The raw value stored for the key, to tell a translation apart from a `default:` or a pluralized
@@ -67,6 +70,7 @@ module Tensaku
67
70
  def translate(locale, key, options = ::I18n::EMPTY_HASH)
68
71
  result = super
69
72
  return result unless I18nMarkers.active? && result.is_a?(String) && !key.nil?
73
+ return result if result.blank?
70
74
 
71
75
  full = ::I18n.normalize_keys(nil, key, options[:scope], options[:separator]).join(".")
72
76
  return result if full.match?(SKIP)
@@ -77,20 +81,65 @@ module Tensaku
77
81
  end
78
82
  end
79
83
 
80
- # Wraps controller actions for HTML requests.
84
+ # A translated file name, such as a screenshot per locale, names an asset rather than text the
85
+ # overlay can edit, so it resolves without its marker. Otherwise the asset lookup misses.
86
+ # Both names, because Rails aliases one to the other and image_path calls the alias.
87
+ module AssetPaths
88
+ %i[asset_path path_to_asset].each do |name|
89
+ define_method(name) do |source, options = {}|
90
+ super(source.is_a?(String) ? I18nMarkers.strip(source) : source, options)
91
+ end
92
+ end
93
+ end
94
+
95
+ # A marker belongs to the page, never to data: a translated string assigned to a model attribute,
96
+ # such as a default category name, loses its marker, so validations, saves and comparisons on the
97
+ # model see the text alone. Both string types, because String has its own cast_value.
98
+ module ModelStrings
99
+ private
100
+
101
+ def cast_value(value)
102
+ super(value.is_a?(String) ? I18nMarkers.strip(value) : value)
103
+ end
104
+ end
105
+
106
+ def page?
107
+ Thread.current[:tensaku_i18n_page] == true
108
+ end
109
+
110
+ def on_page
111
+ previous = Thread.current[:tensaku_i18n_page]
112
+ Thread.current[:tensaku_i18n_page] = true
113
+ yield
114
+ ensure
115
+ Thread.current[:tensaku_i18n_page] = previous
116
+ end
117
+
118
+ # Wraps controller actions for HTML requests. The action itself translates without markers, so
119
+ # a flash message, a model default or anything else it measures, compares or stores stays plain
120
+ # text; Templates turns them on while the page renders.
81
121
  module Controller
82
122
  extend ActiveSupport::Concern
83
123
 
84
124
  included do
85
- prepend_around_action :tensaku_i18n_markers
125
+ prepend_around_action :tensaku_i18n_page
86
126
  end
87
127
 
88
128
  private
89
129
 
90
- def tensaku_i18n_markers(&)
130
+ def tensaku_i18n_page(&)
91
131
  return yield unless request.format&.html?
92
132
 
93
- I18nMarkers.with_markers(&)
133
+ I18nMarkers.on_page(&)
134
+ end
135
+ end
136
+
137
+ # Prepended to ActionView::Template: markers while a template of an HTML page renders.
138
+ module Templates
139
+ def render(view, locals, buffer = nil, **options, &block)
140
+ return super unless I18nMarkers.page? && !I18nMarkers.active?
141
+
142
+ I18nMarkers.with_markers { super(view, locals, buffer, **options, &block) }
94
143
  end
95
144
  end
96
145
  end
@@ -23,14 +23,16 @@ module Tensaku
23
23
 
24
24
  notes.map do |note|
25
25
  where = Array(note["targets"]).filter_map { [ it["file"], it["range"]&.split("-")&.first ].compact.join(":").presence }.uniq.first(3)
26
- "- `#{note["id"]}` (#{note["status"]}) #{note["comment"].squish.truncate(160)}#{" at #{where.map { "`#{it}`" }.join(", ")}" if where.any?}"
26
+ "- `#{note["id"]}` (#{note["status"]}#{", held" if note["held_at"]}) #{note["comment"].squish.truncate(160)}#{" at #{where.map { "`#{it}`" }.join(", ")}" if where.any?}"
27
27
  end.join("\n")
28
28
  end
29
29
 
30
30
  def note(note, base: Project.base_url, app: nil, latest: false, session: nil, absolute: false)
31
31
  page = base && note["url"].to_s.start_with?("/") ? "#{base.chomp("/")}#{note["url"]}" : note["url"]
32
32
  lines = [ "## Tensaku note #{note["id"]} (#{note["status"]}) on #{page}#{" in #{app}" if app}", "" ]
33
- if session && ACTIVE.include?(note["status"])
33
+ if note["held_at"]
34
+ lines << "*Held: the source where it pointed changed, and the person picks its element again on the page. Leave it until then.*" << ""
35
+ elsif session && ACTIVE.include?(note["status"])
34
36
  lines << if note["session"] == session && note["status"] == "working" then "*Yours, and started: make the change, then resolve it.*"
35
37
  elsif note["session"] == session then "*Yours. Call start_note before you change anything.*"
36
38
  elsif note["stopped"] then "*Its session stopped while working on it, so it is nobody's now. Part of the change may already be made: check the file before you redo it. Call start_note to take it.*"
data/lib/tensaku/notes.rb CHANGED
@@ -14,6 +14,9 @@ module Tensaku
14
14
  #
15
15
  # `sent_at` says when the note was last sent to an agent: when you saved it, or last edited, answered
16
16
  # or reopened it.
17
+ #
18
+ # `held_at` says the page found an open note's element only by its old position, and the source there
19
+ # changed since the note was written: agents leave the note until you pick its element again.
17
20
  module Notes
18
21
  autoload :Markdown, "tensaku/notes/markdown"
19
22
  autoload :Target, "tensaku/notes/target"
@@ -175,6 +178,8 @@ module Tensaku
175
178
  Project.write do |db, app|
176
179
  note = find(id)
177
180
  check_owner!(note, session)
181
+ raise Error, "Note #{note["id"]} waits for the person to pick its element again: the source where it pointed changed. Leave it, and take the next one." if note["held_at"]
182
+
178
183
  note["session"] = session if session
179
184
  apply(db, app, note, status: "working", agent:)
180
185
  end
@@ -188,6 +193,48 @@ module Tensaku
188
193
  owner.nil? || session.nil? || owner == session || !Agents.connected?(owner)
189
194
  end
190
195
 
196
+ # The page found the note's element only at its old position, with other text. held: true holds an
197
+ # open note back from agents when the source at a target changed since the note was written, since
198
+ # another element may sit there now. An element whose text changes on its own (Ruby data, a clock)
199
+ # has the same source, and is not held. held: false sends a held note again.
200
+ def hold(id, held)
201
+ Project.write do |db, app|
202
+ note = find(id)
203
+ if held && note["status"] == "open" && !note["held_at"] && source_changed?(note)
204
+ save(db, app, note.merge("held_at" => Project.timestamp))
205
+ elsif !held && note["held_at"]
206
+ apply(db, app, note.except("held_at"), send: note["status"] == "open")
207
+ else
208
+ note
209
+ end
210
+ end
211
+ end
212
+
213
+ # You picked the note's element again on the page: its targets are replaced, a hold ends, and an
214
+ # open note is sent again.
215
+ def retarget(id, targets)
216
+ targets = Array(targets).map { Target.from(it) }
217
+ raise Error, "A note needs a target to point at" if targets.empty?
218
+
219
+ Project.write do |db, app|
220
+ note = find(id)
221
+ apply(db, app, note.except("held_at").merge("targets" => targets), send: note["status"] == "open")
222
+ end
223
+ end
224
+
225
+ # Whether the source at one of the note's stamped targets differs from when the note was written.
226
+ # A target without a digest (an older note) or whose file can't be read counts as changed.
227
+ def source_changed?(note)
228
+ Array(note["targets"]).any? do |target|
229
+ next false unless target["stamp"]
230
+
231
+ path, line, column = Source::Template.parse_stamp(target["stamp"])
232
+ target["digest"].nil? || Source::Template.new(path).element_range(line, column)[:digest] != target["digest"]
233
+ rescue Error
234
+ true
235
+ end
236
+ end
237
+
191
238
  def check_owner!(note, session)
192
239
  return if available_to?(note, session)
193
240
 
@@ -251,7 +298,7 @@ module Tensaku
251
298
  # passes it as the next since sees every note exactly once.
252
299
  def sent_between(since, upto, session: nil)
253
300
  Project.write do
254
- list(status: "open", session:).select { it["sent_at"] && it["sent_at"] > Project.timestamp(since) && it["sent_at"] <= Project.timestamp(upto) }
301
+ list(status: "open", session:).select { !it["held_at"] && it["sent_at"] && it["sent_at"] > Project.timestamp(since) && it["sent_at"] <= Project.timestamp(upto) }
255
302
  end
256
303
  end
257
304
 
@@ -297,7 +344,7 @@ module Tensaku
297
344
  end
298
345
  end
299
346
 
300
- COLUMNS = %w[id url comment status targets rect viewport commit session agent sent_at delivered_at delivered_to archived_at created_at updated_at].freeze
347
+ COLUMNS = %w[id url comment status targets rect viewport commit session agent sent_at delivered_at delivered_to held_at archived_at created_at updated_at].freeze
301
348
 
302
349
  # Writes the whole note, thread included, and logs the change. Returns the note.
303
350
  def save(db, app, note)
@@ -37,10 +37,15 @@ module Tensaku
37
37
  ActiveSupport.on_load(:action_controller_base) do
38
38
  include Tensaku::I18nMarkers::Controller
39
39
  end
40
+ ActiveSupport.on_load(:action_view) do
41
+ prepend Tensaku::I18nMarkers::AssetPaths
42
+ ActionView::Template.prepend(Tensaku::I18nMarkers::Templates)
43
+ end
40
44
  end
41
45
 
42
46
  config.after_initialize do
43
47
  I18n.backend.extend(Tensaku::I18nMarkers::Backend) unless I18n.backend.is_a?(Tensaku::I18nMarkers::Backend)
48
+ [ ActiveModel::Type::ImmutableString, ActiveModel::Type::String ].each { it.prepend(Tensaku::I18nMarkers::ModelStrings) }
44
49
 
45
50
  if (warning = Tensaku::Caches.fragment_cache_warning)
46
51
  Rails.logger.warn("[Tensaku] #{warning}")
@@ -38,7 +38,7 @@ module Tensaku
38
38
  },
39
39
  {
40
40
  name: "start_note",
41
- description: "Mark a note you found with list_notes as being worked on before you make the change. The pin on the page shows that an agent has picked it up, and the note becomes this session's. Notes handed to you (by watch_notes, a channel event or another tool's answer) are already started, so skip this for them. Fails when the note belongs to another running agent session: then leave it. Call resolve_note as soon as the change is made.",
41
+ description: "Mark a note you found with list_notes as being worked on before you make the change. The pin on the page shows that an agent has picked it up, and the note becomes this session's. Notes handed to you (by watch_notes, a channel event or another tool's answer) are already started, so skip this for them. Fails when the note belongs to another running agent session, or is held while the person picks its element again: then leave it. Call resolve_note as soon as the change is made.",
42
42
  inputSchema: BY_ID
43
43
  },
44
44
  {
@@ -1,3 +1,4 @@
1
+ require "digest"
1
2
  require "herb"
2
3
  require "tensaku/source/html_text"
3
4
 
@@ -77,10 +78,12 @@ module Tensaku
77
78
  }
78
79
  end
79
80
 
80
- # The file range of the element, for notes: "line:col-line:col".
81
+ # The file range of the element, for notes: "line:col-line:col", and a digest of its source, which
82
+ # tells later whether the element at that position changed in the file.
81
83
  def element_range(line, column)
82
84
  element = element_at!(line, column)
83
- { range: range_label(element.location), tag: tag_label(element) }
85
+ start, finish = byte_range(element.location)
86
+ { range: range_label(element.location), tag: tag_label(element), digest: Digest::SHA256.hexdigest(source.byteslice(start...finish))[0, 16] }
84
87
  end
85
88
 
86
89
  # edits: [{ start:, end:, original:, text: }], byte ranges of text pieces with the source they had
data/lib/tensaku/store.rb CHANGED
@@ -95,7 +95,10 @@ module Tensaku
95
95
 
96
96
  # Each change to the schema after BASE, in order, applied once: MIGRATIONS[0] takes a database from
97
97
  # BASE to BASE + 1. Add to the end; never change a step that may have run.
98
- MIGRATIONS = [].freeze
98
+ MIGRATIONS = [
99
+ # held_at: the page found the note's element only at its old position, and the source there changed.
100
+ "ALTER TABLE notes ADD COLUMN held_at TEXT;"
101
+ ].freeze
99
102
  VERSION = BASE + MIGRATIONS.size
100
103
 
101
104
  LOCK = Monitor.new
@@ -1,3 +1,3 @@
1
1
  module Tensaku
2
- VERSION = "0.2.2"
2
+ VERSION = "0.3.0"
3
3
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: tensaku
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.2.2
4
+ version: 0.3.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - David Afonso