tensaku 0.2.1 → 0.2.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/CHANGELOG.md +30 -0
- data/README.md +1 -1
- data/app/assets/tensaku.js +17 -8
- data/lib/tensaku/i18n.rb +58 -9
- data/lib/tensaku/railtie.rb +5 -0
- data/lib/tensaku/version.rb +1 -1
- metadata +2 -2
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 9a473b72e27ddfc1b18e8848593d73387037f3390ac3212d13b265c38fb48254
|
|
4
|
+
data.tar.gz: 9eda493e2c5077d05163fbd25018b633b1085b1cd6f0f0b435ae06503a14c937
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: c716be67a15686686d732025fc874ba31982c252a7ad5573af5f8e65f7cd191938c0ea7c5bd696909ed315a27c188cfb19f217f2ef324fc9d5de38c4cdc80b99
|
|
7
|
+
data.tar.gz: 8e17e3cb4f815efe6c8d923ed54ef47885a99a817a496262529c89503ffe9111665d5e3ae1f882f66fca5a89a5e2cf4dd151082450f586754f16ad5f96f1e58f
|
data/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,35 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.2.3 (2026-11-14)
|
|
4
|
+
|
|
5
|
+
### Translations
|
|
6
|
+
|
|
7
|
+
- Translation markers are only added while a template renders. Text translated in a controller
|
|
8
|
+
action, such as a flash message, is plain text again: it can't be traced back to its key from the
|
|
9
|
+
page, but code that measures, compares or stores it no longer sees a marker.
|
|
10
|
+
|
|
11
|
+
- A translation that names an asset, such as `image_tag t("hero.image")` with a screenshot per
|
|
12
|
+
locale, resolves again. Its marker made the asset lookup fail with `Propshaft::MissingAssetError`.
|
|
13
|
+
- A page no longer freezes when the app cuts a translated string short, such as a title truncated
|
|
14
|
+
for `og:title`. The cut marker could not be stripped, the overlay wrote the same value back, and
|
|
15
|
+
its observer saw that write as a new change, forever. Cut markers are now stripped, and an
|
|
16
|
+
unchanged value is never written.
|
|
17
|
+
- Markers no longer reach your data. A translated string assigned to a model attribute, such as a
|
|
18
|
+
default category name made in a callback, loses its marker, so it is validated and saved as plain
|
|
19
|
+
text. Before, a length validation could fail, or the marker was stored in the database.
|
|
20
|
+
- A blank translation gets no marker, so `t("step.subtitle").present?` stays false and the page
|
|
21
|
+
doesn't render an empty element that only exists in development.
|
|
22
|
+
|
|
23
|
+
## 0.2.2 (2026-11-14)
|
|
24
|
+
|
|
25
|
+
### Overlay
|
|
26
|
+
|
|
27
|
+
- Phones: the open toolbar fits on screens up to 520px wide (it used to stop at 420px, so on a 430px
|
|
28
|
+
phone the first tools were off the left edge), and also when the dock was dragged away from the
|
|
29
|
+
corner. The text editor's bar shortens the file name so Cancel and Save stay on screen. Dragging the
|
|
30
|
+
corner button moves the dock instead of scrolling the page. Touch screens no longer show keyboard
|
|
31
|
+
shortcuts in the element menu and note form, or leave a tool's tip up after a tap.
|
|
32
|
+
|
|
3
33
|
## 0.2.1 (2026-11-14)
|
|
4
34
|
|
|
5
35
|
### Agents
|
data/README.md
CHANGED
data/app/assets/tensaku.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
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;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; }
|
|
2
2
|
* { box-sizing: border-box; }
|
|
3
3
|
[hidden] { display: none !important; }
|
|
4
4
|
|
|
@@ -128,7 +128,9 @@ kbd { font: 10.5px/1 var(--mono); padding: 2px 4px; border-radius: 4px; backgrou
|
|
|
128
128
|
.editor { --line: color-mix(in srgb, currentColor 18%, transparent); --muted: color-mix(in srgb, currentColor 62%, transparent); padding: 0; min-width: 0; max-width: none; border: 1.5px solid var(--akaji); border-radius: 8px; box-shadow: 0 0 0 4px var(--akaji-soft), 0 14px 32px -12px rgba(0, 0, 0, .45); animation: settle .16s var(--spring); }
|
|
129
129
|
.editor .surface { padding: 8px 10px; white-space: pre-wrap; outline: none; min-height: 1.4em; max-height: 60vh; overflow: auto; caret-color: var(--akaji); }
|
|
130
130
|
.editor .bar { position: absolute; left: -1.5px; top: calc(100% + 8px); display: flex; gap: 10px; align-items: center; background: var(--tray); color: var(--tray-muted); border: 1px solid var(--tray-line); border-radius: 999px; padding: 4px 4px 4px 12px; font: 11px/1.3 var(--mono); white-space: nowrap; box-shadow: 0 10px 26px -8px rgba(0, 0, 0, .45); }
|
|
131
|
-
|
|
131
|
+
/* editor.ts limits the bar to the screen; then the file name shortens, so Cancel and Save stay on it. */
|
|
132
|
+
.editor .bar > span { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
|
|
133
|
+
.editor .bar .actions { display: flex; gap: 4px; flex: none; }
|
|
132
134
|
.editor .bar button { font: 600 12px/1.2 var(--sans); padding: 5px 12px; border-radius: 999px; border-color: transparent; color: var(--tray-ink); }
|
|
133
135
|
.editor .bar button:hover { background: var(--tray-raised); border-color: transparent; }
|
|
134
136
|
.editor .bar button.primary { background: var(--akaji); border-color: var(--akaji); color: #fff; }
|
|
@@ -160,7 +162,8 @@ kbd { font: 10.5px/1 var(--mono); padding: 2px 4px; border-radius: 4px; backgrou
|
|
|
160
162
|
|
|
161
163
|
/* The tray. The corner button opens it; the selected tool rises and shows its ink. */
|
|
162
164
|
.dock { position: fixed; display: flex; align-items: center; padding: 4px; border-radius: 999px; background: var(--tray); border: 1px solid var(--tray-line); box-shadow: 0 12px 30px -8px rgba(0, 0, 0, .45); user-select: none; }
|
|
163
|
-
|
|
165
|
+
/* touch-action: dragging the button on a touch screen moves the dock instead of scrolling the page. */
|
|
166
|
+
.corner { width: 40px; height: 40px; border-radius: 50%; border: none; background: none; color: var(--akaji); display: grid; place-items: center; cursor: pointer; position: relative; padding: 0; flex: none; touch-action: none; }
|
|
164
167
|
.corner .logo { width: 25px; height: 25px; fill: none; stroke: currentColor; stroke-width: 10; stroke-linecap: round; stroke-linejoin: round; transition: transform .5s cubic-bezier(.22, 1, .36, 1), rotate .16s var(--spring); }
|
|
165
168
|
.corner:hover { background: var(--tray-raised); }
|
|
166
169
|
.corner:hover .logo { rotate: -8deg; }
|
|
@@ -187,17 +190,23 @@ kbd { font: 10.5px/1 var(--mono); padding: 2px 4px; border-radius: 4px; backgrou
|
|
|
187
190
|
.tool .tip { position: absolute; bottom: calc(100% + 12px); left: 50%; transform: translateX(-50%) translateY(4px); display: flex; gap: 6px; align-items: center; background: var(--tray); color: var(--tray-ink); border: 1px solid var(--tray-line); font: 600 12px/1 var(--sans); padding: 6px 8px; border-radius: 7px; white-space: nowrap; pointer-events: none; opacity: 0; transition: opacity .12s, transform .12s; }
|
|
188
191
|
.tool:hover .tip, .tool:focus-visible .tip { opacity: 1; transform: translateX(-50%); }
|
|
189
192
|
.tool:focus-visible { outline: 2px solid var(--marker); outline-offset: 1px; }
|
|
190
|
-
/* On a phone the tools are smaller, and
|
|
191
|
-
sideways.
|
|
192
|
-
|
|
193
|
+
/* On a phone the tools are smaller, and when the open toolbar is wider than the room left of the
|
|
194
|
+
dock its tools scroll sideways. --dock-right is the dock's distance from the right edge; the corner
|
|
195
|
+
button and the dock's padding take 60px more. */
|
|
196
|
+
@media (max-width: 520px) {
|
|
193
197
|
.tool { width: 32px; height: 32px; }
|
|
194
198
|
.tool .icon { width: 20px; height: 20px; }
|
|
195
199
|
.tool[aria-pressed="true"]::after { bottom: 2px; }
|
|
196
200
|
.toolbar .sep { margin: 0 2px; }
|
|
197
201
|
.toolbar { justify-content: safe flex-end; }
|
|
198
|
-
.dock.open .toolbar { width: min(var(--tools-width), calc(100vw -
|
|
202
|
+
.dock.open .toolbar { width: min(var(--tools-width), calc(100vw - var(--dock-right, 16px) - 60px)); }
|
|
199
203
|
.dock.settled .toolbar { overflow-x: auto; scrollbar-width: none; }
|
|
200
204
|
}
|
|
205
|
+
/* A touch screen has no keyboard shortcuts to show, and a tap leaves :hover on the tapped tool, which
|
|
206
|
+
kept its tip up. */
|
|
207
|
+
@media (hover: none) {
|
|
208
|
+
.tool .tip, .menu kbd, .note-form .hint { display: none; }
|
|
209
|
+
}
|
|
201
210
|
|
|
202
211
|
/* The notes panel: the tray's material, holding the page's Post-its. */
|
|
203
212
|
.sidebar { position: fixed; top: 12px; right: 12px; bottom: 70px; display: flex; flex-direction: column; width: 360px; max-width: calc(100vw - 24px); overflow: auto; background: var(--tray); color: var(--tray-ink); border: 1px solid var(--tray-line); border-radius: 16px; box-shadow: 0 24px 50px -16px rgba(0, 0, 0, .55); padding: 14px; animation: slide-in .22s var(--spring); }
|
|
@@ -367,6 +376,6 @@ kbd { font: 10.5px/1 var(--mono); padding: 2px 4px; border-radius: 4px; backgrou
|
|
|
367
376
|
}
|
|
368
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(`
|
|
369
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)&¬e.thread[messages-1].from==="agent"&¬e.status===previous.status)announce(note,"message");else if(note.status!==previous.status&¬e.status!=="open"&¬e.status!=="working")announce(note,note.status)}});var siClaude={title:"Claude",slug:"claude",get svg(){return'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Claude</title><path d="'+this.path+'"/></svg>'},path:"m4.7144 15.9555 4.7174-2.6471.079-.2307-.079-.1275h-.2307l-.7893-.0486-2.6956-.0729-2.3375-.0971-2.2646-.1214-.5707-.1215-.5343-.7042.0546-.3522.4797-.3218.686.0608 1.5179.1032 2.2767.1578 1.6514.0972 2.4468.255h.3886l.0546-.1579-.1336-.0971-.1032-.0972L6.973 9.8356l-2.55-1.6879-1.3356-.9714-.7225-.4918-.3643-.4614-.1578-1.0078.6557-.7225.8803.0607.2246.0607.8925.686 1.9064 1.4754 2.4893 1.8336.3643.3035.1457-.1032.0182-.0728-.164-.2733-1.3539-2.4467-1.445-2.4893-.6435-1.032-.17-.6194c-.0607-.255-.1032-.4674-.1032-.7285L6.287.1335 6.6997 0l.9957.1336.419.3642.6192 1.4147 1.0018 2.2282 1.5543 3.0296.4553.8985.2429.8318.091.255h.1579v-.1457l.1275-1.706.2368-2.0947.2307-2.6957.0789-.7589.3764-.9107.7468-.4918.5828.2793.4797.686-.0668.4433-.2853 1.8517-.5586 2.9021-.3643 1.9429h.2125l.2429-.2429.9835-1.3053 1.6514-2.0643.7286-.8196.85-.9046.5464-.4311h1.0321l.759 1.1293-.34 1.1657-1.0625 1.3478-.8804 1.1414-1.2628 1.7-.7893 1.36.0729.1093.1882-.0183 2.8535-.607 1.5421-.2794 1.8396-.3157.8318.3886.091.3946-.3278.8075-1.967.4857-2.3072.4614-3.4364.8136-.0425.0304.0486.0607 1.5482.1457.6618.0364h1.621l3.0175.2247.7892.522.4736.6376-.079.4857-1.2142.6193-1.6393-.3886-3.825-.9107-1.3113-.3279h-.1822v.1093l1.0929 1.0686 2.0035 1.8092 2.5075 2.3314.1275.5768-.3218.4554-.34-.0486-2.2039-1.6575-.85-.7468-1.9246-1.621h-.1275v.17l.4432.6496 2.3436 3.5214.1214 1.0807-.17.3521-.6071.2125-.6679-.1214-1.3721-1.9246L14.38 17.959l-1.1414-1.9428-.1397.079-.674 7.2552-.3156.3703-.7286.2793-.6071-.4614-.3218-.7468.3218-1.4753.3886-1.9246.3157-1.53.2853-1.9004.17-.6314-.0121-.0425-.1397.0182-1.4328 1.9672-2.1796 2.9446-1.7243 1.8456-.4128.164-.7164-.3704.0667-.6618.4008-.5889 2.386-3.0357 1.4389-1.882.929-1.0868-.0062-.1579h-.0546l-6.3385 4.1164-1.1293.1457-.4857-.4554.0608-.7467.2307-.2429 1.9064-1.3114Z",source:"https://claude.ai",hex:"D97757"};var siCline={title:"Cline",slug:"cline",get svg(){return'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Cline</title><path d="'+this.path+'"/></svg>'},path:"m23.365 13.556-1.442-2.895V8.994c0-2.764-2.218-5.002-4.954-5.002h-2.464c.178-.367.276-.779.276-1.213A2.77 2.77 0 0 0 12.018 0a2.77 2.77 0 0 0-2.763 2.779c0 .434.098.846.276 1.213H7.067c-2.736 0-4.954 2.238-4.954 5.002v1.667L.64 13.549c-.149.29-.149.636 0 .927l1.472 2.855v1.667C2.113 21.762 4.33 24 7.067 24h9.902c2.736 0 4.954-2.238 4.954-5.002V17.33l1.44-2.865c.143-.286.143-.622.002-.91m-12.854 2.36a2.27 2.27 0 0 1-2.261 2.273 2.27 2.27 0 0 1-2.261-2.273v-4.042A2.27 2.27 0 0 1 8.249 9.6a2.267 2.267 0 0 1 2.262 2.274zm7.285 0a2.27 2.27 0 0 1-2.26 2.273 2.27 2.27 0 0 1-2.262-2.273v-4.042A2.267 2.267 0 0 1 15.535 9.6a2.267 2.267 0 0 1 2.261 2.274z",source:"https://cline.bot/assets/branding/logos/cline-wordmark-black.svg",hex:"18181B"};var siCursor={title:"Cursor",slug:"cursor",get svg(){return'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Cursor</title><path d="'+this.path+'"/></svg>'},path:"M11.503.131 1.891 5.678a.84.84 0 0 0-.42.726v11.188c0 .3.162.575.42.724l9.609 5.55a1 1 0 0 0 .998 0l9.61-5.55a.84.84 0 0 0 .42-.724V6.404a.84.84 0 0 0-.42-.726L12.497.131a1.01 1.01 0 0 0-.996 0M2.657 6.338h18.55c.263 0 .43.287.297.515L12.23 22.918c-.062.107-.229.064-.229-.06V12.335a.59.59 0 0 0-.295-.51l-9.11-5.257c-.109-.063-.064-.23.061-.23",source:"https://cursor.com/brand",hex:"000000"};var siGithubcopilot={title:"GitHub Copilot",slug:"githubcopilot",get svg(){return'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>GitHub Copilot</title><path d="'+this.path+'"/></svg>'},path:"M23.922 16.997C23.061 18.492 18.063 22.02 12 22.02 5.937 22.02.939 18.492.078 16.997A.641.641 0 0 1 0 16.741v-2.869a.883.883 0 0 1 .053-.22c.372-.935 1.347-2.292 2.605-2.656.167-.429.414-1.055.644-1.517a10.098 10.098 0 0 1-.052-1.086c0-1.331.282-2.499 1.132-3.368.397-.406.89-.717 1.474-.952C7.255 2.937 9.248 1.98 11.978 1.98c2.731 0 4.767.957 6.166 2.093.584.235 1.077.546 1.474.952.85.869 1.132 2.037 1.132 3.368 0 .368-.014.733-.052 1.086.23.462.477 1.088.644 1.517 1.258.364 2.233 1.721 2.605 2.656a.841.841 0 0 1 .053.22v2.869a.641.641 0 0 1-.078.256Zm-11.75-5.992h-.344a4.359 4.359 0 0 1-.355.508c-.77.947-1.918 1.492-3.508 1.492-1.725 0-2.989-.359-3.782-1.259a2.137 2.137 0 0 1-.085-.104L4 11.746v6.585c1.435.779 4.514 2.179 8 2.179 3.486 0 6.565-1.4 8-2.179v-6.585l-.098-.104s-.033.045-.085.104c-.793.9-2.057 1.259-3.782 1.259-1.59 0-2.738-.545-3.508-1.492a4.359 4.359 0 0 1-.355-.508Zm2.328 3.25c.549 0 1 .451 1 1v2c0 .549-.451 1-1 1-.549 0-1-.451-1-1v-2c0-.549.451-1 1-1Zm-5 0c.549 0 1 .451 1 1v2c0 .549-.451 1-1 1-.549 0-1-.451-1-1v-2c0-.549.451-1 1-1Zm3.313-6.185c.136 1.057.403 1.913.878 2.497.442.544 1.134.938 2.344.938 1.573 0 2.292-.337 2.657-.751.384-.435.558-1.15.558-2.361 0-1.14-.243-1.847-.705-2.319-.477-.488-1.319-.862-2.824-1.025-1.487-.161-2.192.138-2.533.529-.269.307-.437.808-.438 1.578v.021c0 .265.021.562.063.893Zm-1.626 0c.042-.331.063-.628.063-.894v-.02c-.001-.77-.169-1.271-.438-1.578-.341-.391-1.046-.69-2.533-.529-1.505.163-2.347.537-2.824 1.025-.462.472-.705 1.179-.705 2.319 0 1.211.175 1.926.558 2.361.365.414 1.084.751 2.657.751 1.21 0 1.902-.394 2.344-.938.475-.584.742-1.44.878-2.497Z",source:"https://primer.style/foundations/icons/copilot-24",hex:"000000",license:{type:"MIT",url:"https://spdx.org/licenses/MIT"}};var siGooglegemini={title:"Google Gemini",slug:"googlegemini",get svg(){return'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Google Gemini</title><path d="'+this.path+'"/></svg>'},path:"M11.04 19.32Q12 21.51 12 24q0-2.49.93-4.68.96-2.19 2.58-3.81t3.81-2.55Q21.51 12 24 12q-2.49 0-4.68-.93a12.3 12.3 0 0 1-3.81-2.58 12.3 12.3 0 0 1-2.58-3.81Q12 2.49 12 0q0 2.49-.96 4.68-.93 2.19-2.55 3.81a12.3 12.3 0 0 1-3.81 2.58Q2.49 12 0 12q2.49 0 4.68.96 2.19.93 3.81 2.55t2.55 3.81",source:"https://gemini.google.com",hex:"8E75B2"};var siOpencode={title:"OpenCode",slug:"opencode",get svg(){return'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>OpenCode</title><path d="'+this.path+'"/></svg>'},path:"M22 24H2V0h20zM17 4.8H7v14.4h10z",source:"https://github.com/anomalyco/opencode/blob/1251a870cb384543c150c4a72fb101b55eec971b/packages/identity/mark.svg",hex:"000000"};var siWindsurf={title:"Windsurf",slug:"windsurf",get svg(){return'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Windsurf</title><path d="'+this.path+'"/></svg>'},path:"M23.55 5.067c-1.2038-.002-2.1806.973-2.1806 2.1765v4.8676c0 .972-.8035 1.7594-1.7597 1.7594-.568 0-1.1352-.286-1.4718-.7659l-4.9713-7.1003c-.4125-.5896-1.0837-.941-1.8103-.941-1.1334 0-2.1533.9635-2.1533 2.153v4.8957c0 .972-.7969 1.7594-1.7596 1.7594-.57 0-1.1363-.286-1.4728-.7658L.4076 5.1598C.2822 4.9798 0 5.0688 0 5.2882v4.2452c0 .2147.0656.4228.1884.599l5.4748 7.8183c.3234.462.8006.8052 1.3509.9298 1.3771.313 2.6446-.747 2.6446-2.0977v-4.893c0-.972.7875-1.7593 1.7596-1.7593h.003a1.798 1.798 0 0 1 1.4718.7658l4.9723 7.0994c.4135.5905 1.05.941 1.8093.941 1.1587 0 2.1515-.9645 2.1515-2.153v-4.8948c0-.972.7875-1.7594 1.7596-1.7594h.194a.22.22 0 0 0 .2204-.2202v-4.622a.22.22 0 0 0-.2203-.2203Z",source:"https://windsurf.com/brand",hex:"0B100F",guidelines:"https://windsurf.com/brand"};var siZedindustries={title:"Zed Industries",slug:"zedindustries",get svg(){return'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Zed Industries</title><path d="'+this.path+'"/></svg>'},path:"M2.25 1.5a.75.75 0 0 0-.75.75v16.5H0V2.25A2.25 2.25 0 0 1 2.25 0h20.095c1.002 0 1.504 1.212.795 1.92L10.764 14.298h3.486V12.75h1.5v1.922a1.125 1.125 0 0 1-1.125 1.125H9.264l-2.578 2.578h11.689V9h1.5v9.375a1.5 1.5 0 0 1-1.5 1.5H5.185L2.562 22.5H21.75a.75.75 0 0 0 .75-.75V5.25H24v16.5A2.25 2.25 0 0 1 21.75 24H1.655C.653 24 .151 22.788.86 22.08L13.19 9.75H9.75v1.5h-1.5V9.375A1.125 1.125 0 0 1 9.375 8.25h5.314l2.625-2.625H5.625V15h-1.5V5.625a1.5 1.5 0 0 1 1.5-1.5h13.19L21.438 1.5z",source:"https://github.com/zed-industries/zed/blob/ccc939124fa2f366b3029926447fd0a0c46a85c7/assets/icons/logo_96.svg",hex:"084CCF"};var CLIENTS=[[/claude/i,siClaude],[/cursor/i,siCursor],[/gemini/i,siGooglegemini],[/opencode/i,siOpencode],[/copilot/i,siGithubcopilot],[/windsurf/i,siWindsurf],[/\bzed\b/i,siZedindustries],[/cline/i,siCline]];function readable(hex){let[r,g,b]=[0,2,4].map((i)=>parseInt(hex.slice(i,i+2),16));return 0.2126*r+0.7152*g+0.0722*b>90}function clientIcon(name){let brand=CLIENTS.find(([pattern])=>pattern.test(name))?.[1];if(!brand)return icon("plane");let svg=document.createElementNS("http://www.w3.org/2000/svg","svg");svg.setAttribute("class","client"),svg.setAttribute("viewBox","0 0 24 24"),svg.setAttribute("aria-hidden","true"),svg.setAttribute("focusable","false");let path=document.createElementNS("http://www.w3.org/2000/svg","path");if(path.setAttribute("d",brand.path),svg.append(path),readable(brand.hex))svg.style.color=`#${brand.hex}`;return svg}var popover=null,popoverTool=null,rendered=()=>[],popoverOpen=(tool)=>tool?popoverTool===tool:Boolean(popover);function closePopover(){popover?.remove(),popover=null,popoverTool?.setAttribute("aria-pressed","false"),popoverTool=null}function togglePopover(tool,dock,render2){let same=popoverTool===tool;if(closePopover(),same)return;rendered=render2,popover=div("popover",...render2()),popover.addEventListener("keydown",(event)=>event.stopPropagation());let rect=dock.getBoundingClientRect();popover.style.right=`${Math.max(12,innerWidth-rect.right)}px`,popover.style.bottom=`${innerHeight-rect.top+12}px`,fixed.append(popover),popoverTool=tool,tool.setAttribute("aria-pressed","true")}function redrawPopover(tool){if(popover&&(!tool||popoverTool===tool))popover.replaceChildren(...rendered())}function closeOutside(event){if(popover&&!event.composedPath().some((node)=>node===popover||node===popoverTool))closePopover()}var ago=(date)=>{let seconds=Math.round((Date.now()-date.getTime())/1000);return seconds<60?"just now":seconds<3600?`${Math.round(seconds/60)} min ago`:`${Math.round(seconds/3600)} h ago`};var PROMPTS={watch:"Watch my Tensaku notes",once:"Do my Tensaku notes",install:"bin/rails generate tensaku:install",channel:"claude --dangerously-load-development-channels server:tensaku"};function copyRow(text,done){return div("command",h("code",{},text),h("button",{type:"button",className:"icon-button",title:"Copy","aria-label":`Copy ${text}`,onclick:async()=>{await copy(text),toast(done)}},icon("copy")))}var DID={start_note:"started",resolve_note:"resolved",decline_note:"declined",ask_question:"asked on",reply_to_note:"replied on",get_note:"read",list_notes:"listed the notes",watch_notes:"checked for notes",current_selection:"read the selection"};function lastAction(agent){if(agent.working.length)return agent.working.map((note)=>h("a",{className:"doing",href:note.url,title:`“${note.comment}”`},`Working on ${note.id}: “${note.comment}”`));let last=agent.last,did=last?`${DID[last.tool]??last.tool}${last.note?` ${last.note}`:""} ${ago(new Date(last.at))}`:null,waiting2=agent.channel?"Live: notes reach its chat as you save them":"Waiting for your notes",text=agent.listening?`${waiting2}${did?` · ${did}`:""}`:did?`Last ${did}`:"No calls yet";return[h("span",{className:"doing"},text)]}function agentRow(agent){return div(`agent${agent.listening?" listening":""}${agent.channel?" live":""}${agent.working.length?" working":""}`,div("who",h("strong",{},clientIcon(agent.name),agentLabel(agent)),h("span",{className:"where"},agent.folder??"")),agent.outdated?div("outdated","Runs older Tensaku code. Reconnect it (/mcp in Claude Code) or restart it."):null,...lastAction(agent))}var idleOpen=!1;function renderAgents(){let agents2=currentAgents(),listening=agents2.filter((agent)=>agent.listening),idle=agents2.filter((agent)=>!agent.listening),ask=(lead)=>[h("p",{},lead),copyRow(PROMPTS.watch,"Copied. Paste it into your agent's chat."),h("p",{className:"where"},"It waits for notes and takes each one as you save it."),copyRow(PROMPTS.once,"Copied. Paste it into your agent's chat."),h("p",{className:"where"},"It works through the open notes, then stops."),h("p",{},h("strong",{},"Claude Code, without asking: "),"start it with Tensaku as a channel, and each note you save starts it working. Experimental, and it asks you to confirm at start:"),copyRow(PROMPTS.channel,"Copied. Run it in the app's folder.")],rest=listening.length&&idle.length?[h("button",{type:"button",className:"idle-toggle","aria-expanded":String(idleOpen),onclick:()=>{idleOpen=!idleOpen,redrawPopover()}},`${idle.length} more connected, not listening`),...idleOpen?idle.map(agentRow):[]]:idle.map(agentRow);return[h("h3",{},"Agents"),...agents2.length?[...listening.map(agentRow),...rest,...listening.length?[]:[div("connect",...ask("None is listening. Agents read notes when you ask them to, so say this in your agent's chat:"))]]:[div("empty","No agent connected."),div("connect",h("p",{},h("strong",{},"Set up once per project. "),"Run this in the app, then restart your agent. It adds Tensaku to Claude Code, Codex, Cursor, Gemini CLI and OpenCode:"),copyRow(PROMPTS.install,"Copied. Run it in the app, then restart your agent."),h("p",{className:"where"},"Already set up? Start your agent in this project and it shows here. In Claude Code, /mcp reconnects it."),...ask("Then say this in your agent's chat:"))]]}var CONTEXT=26,MAX_LINES=3;function sharedEnds(before,after){let prefix=0;while(prefix<before.length&&before[prefix]===after[prefix])prefix++;let suffix=0;while(suffix<before.length-prefix&&suffix<after.length-prefix&&before[before.length-1-suffix]===after[after.length-1-suffix])suffix++;while(prefix>0&&/\w/.test(before[prefix-1]))prefix--;while(suffix>0&&/\w/.test(before[before.length-suffix]))suffix--;return{prefix,suffix}}function row(sign,line,{prefix,suffix}){let end=line.length-suffix,head=prefix>CONTEXT?`…${line.slice(prefix-CONTEXT,prefix).replace(/^\S*\s/,"")}`:line.slice(0,prefix).trimStart(),tail=suffix>CONTEXT?`${line.slice(end,end+CONTEXT).replace(/\s\S*$/,"")}…`:line.slice(end);return div(`diff-row ${sign==="-"?"removed":"added"}`,h("span",{className:"diff-sign"},sign),head,h("mark",{},line.slice(prefix,end)),tail)}function diffRows({removed,added}){let count=Math.max(removed.length,added.length),rows=[];for(let index=0;index<Math.min(count,MAX_LINES);index++){let ends=sharedEnds(removed[index]??"",added[index]??"");if(removed[index]!==void 0)rows.push(row("-",removed[index],ends));if(added[index]!==void 0)rows.push(row("+",added[index],ends))}if(count>MAX_LINES)rows.push(div("diff-more",`${count-MAX_LINES} more ${count-MAX_LINES===1?"line":"lines"} changed`));return div("diff",...rows)}var INTERPOLATION=/(%\{[^}]+\})/;function finish(result,kind,verb,actions){if(!result.changed)return;let where=result.diff?`${result.file}:${result.diff.line}`:result.file??"";if(toast(`${verb} ${where}`.trim(),{timeout:result.diff?8000:void 0,detail:result.diff?diffRows(result.diff):void 0,actions}),result.warning)toast(result.warning,{timeout:8000});refresh(kind)}function report(error){let message=error instanceof Error?error.message:String(error);toast(message,{error:!0,actions:error instanceof ApiError&&error.stale?{Reload:()=>location.reload()}:void 0})}function rangeAfter(range,text){let[,path,startLine,startColumn]=range.match(/^(.+):(\d+):(\d+)-/),lines=text.split(`
|
|
370
|
-
`),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 placeDock(){let position=storage("dock",{right:16,bottom:16});dock.style.right=`${Math.min(Math.max(position.right,4),innerWidth-52)}px`,dock.style.bottom=`${Math.min(Math.max(position.bottom,4),innerHeight-52)}px`}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",dock.style.right=`${start.right-dx}px`,dock.style.bottom=`${start.bottom-dy}px`},up=()=>{if(corner.removeEventListener("pointermove",move),corner.removeEventListener("pointerup",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("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)}},container=div("panel editor",surface,...extra,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.setAttribute("role","dialog"),container.setAttribute("aria-label","Tensaku editor"),container.style.background=backgroundOf(element),container.style.color=computed.color,container.style.minWidth=`${Math.max(rect.width+INSET.x*2,240)}px`,container.style.maxWidth=`${Math.max(rect.width+INSET.x*2,480)}px`,layer.append(container),place(container,new DOMRect(rect.left-INSET.x,rect.top-INSET.y,rect.width+INSET.x*2,rect.height),!0);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(`
|
|
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(`
|
|
371
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(`
|
|
372
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();})();
|
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
|
|
10
|
-
# `time.*` and similar keys, never to a value that came from a `default:` instead of the key,
|
|
11
|
-
#
|
|
12
|
-
#
|
|
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
|
-
#
|
|
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 :
|
|
125
|
+
prepend_around_action :tensaku_i18n_page
|
|
86
126
|
end
|
|
87
127
|
|
|
88
128
|
private
|
|
89
129
|
|
|
90
|
-
def
|
|
130
|
+
def tensaku_i18n_page(&)
|
|
91
131
|
return yield unless request.format&.html?
|
|
92
132
|
|
|
93
|
-
I18nMarkers.
|
|
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
|
data/lib/tensaku/railtie.rb
CHANGED
|
@@ -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}")
|
data/lib/tensaku/version.rb
CHANGED
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.
|
|
4
|
+
version: 0.2.3
|
|
5
5
|
platform: ruby
|
|
6
6
|
authors:
|
|
7
7
|
- David Afonso
|
|
@@ -162,5 +162,5 @@ required_rubygems_version: !ruby/object:Gem::Requirement
|
|
|
162
162
|
requirements: []
|
|
163
163
|
rubygems_version: 4.0.20
|
|
164
164
|
specification_version: 4
|
|
165
|
-
summary: Fix your Rails app
|
|
165
|
+
summary: Fix your Rails app in the browser.
|
|
166
166
|
test_files: []
|