tensaku 0.1.0 → 0.2.1
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 +161 -2
- data/README.md +15 -11
- data/app/assets/tensaku.js +187 -331
- data/exe/tensaku +5 -0
- data/lib/generators/tensaku/install_generator.rb +98 -46
- data/lib/tensaku/agents.rb +143 -0
- data/lib/tensaku/build.rb +32 -0
- data/lib/tensaku/cli.rb +155 -0
- data/lib/tensaku/doorbell.rb +91 -0
- data/lib/tensaku/edits.rb +30 -0
- data/lib/tensaku/endpoints.rb +95 -18
- data/lib/tensaku/file_write.rb +14 -3
- data/lib/tensaku/guard.rb +1 -2
- data/lib/tensaku/mcp.rb +112 -127
- data/lib/tensaku/middleware.rb +1 -1
- data/lib/tensaku/notes/markdown.rb +86 -0
- data/lib/tensaku/notes/target.rb +59 -0
- data/lib/tensaku/notes.rb +255 -254
- data/lib/tensaku/presence.rb +60 -0
- data/lib/tensaku/project.rb +98 -0
- data/lib/tensaku/railtie.rb +16 -1
- data/lib/tensaku/repo.rb +57 -0
- data/lib/tensaku/session/tools.rb +171 -0
- data/lib/tensaku/session.rb +278 -0
- data/lib/tensaku/source/locale.rb +1 -1
- data/lib/tensaku/source/markdown.rb +3 -2
- data/lib/tensaku/source/template.rb +3 -2
- data/lib/tensaku/store.rb +196 -0
- data/lib/tensaku/version.rb +1 -1
- data/lib/tensaku.rb +37 -12
- data/skills/tensaku/SKILL.md +62 -15
- metadata +33 -5
data/app/assets/tensaku.js
CHANGED
|
@@ -1,5 +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",shortcut:tag?.dataset.tensakuShortcut??"alt+shift+KeyT"}}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();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}var Idiomorph=function(){let noOp=()=>{},defaults={morphStyle:"outerHTML",callbacks:{beforeNodeAdded:noOp,afterNodeAdded:noOp,beforeNodeMorphed:noOp,afterNodeMorphed:noOp,beforeNodeRemoved:noOp,afterNodeRemoved:noOp,beforeAttributeUpdated:noOp},head:{style:"merge",shouldPreserve:(elt)=>elt.getAttribute("im-preserve")==="true",shouldReAppend:(elt)=>elt.getAttribute("im-re-append")==="true",shouldRemove:noOp,afterHeadMorphed:noOp},restoreFocus:!0};function morph(oldNode,newContent,config={}){oldNode=normalizeElement(oldNode);let newNode=normalizeParent(newContent),ctx=createMorphContext(oldNode,newNode,config),morphedNodes=saveAndRestoreFocus(ctx,()=>{return withHeadBlocking(ctx,oldNode,newNode,(ctx2)=>{if(ctx2.morphStyle==="innerHTML")return morphChildren(ctx2,oldNode,newNode),Array.from(oldNode.childNodes);else return morphOuterHTML(ctx2,oldNode,newNode)})});return ctx.pantry.remove(),morphedNodes}function morphOuterHTML(ctx,oldNode,newNode){let oldParent=normalizeParent(oldNode);return morphChildren(ctx,oldParent,newNode,oldNode,oldNode.nextSibling),Array.from(oldParent.childNodes)}function saveAndRestoreFocus(ctx,fn){if(!ctx.config.restoreFocus)return fn();let activeElement=document.activeElement;if(!(activeElement instanceof HTMLInputElement||activeElement instanceof HTMLTextAreaElement))return fn();let{id:activeElementId,selectionStart,selectionEnd}=activeElement,results=fn();if(activeElementId&&activeElementId!==document.activeElement?.getAttribute("id"))activeElement=ctx.target.querySelector(`[id="${activeElementId}"]`),activeElement?.focus();if(activeElement&&!activeElement.selectionEnd&&selectionEnd)activeElement.setSelectionRange(selectionStart,selectionEnd);return results}let morphChildren=function(){function morphChildren2(ctx,oldParent,newParent,insertionPoint=null,endPoint=null){if(oldParent instanceof HTMLTemplateElement&&newParent instanceof HTMLTemplateElement)oldParent=oldParent.content,newParent=newParent.content;insertionPoint||=oldParent.firstChild;for(let newChild of newParent.childNodes){if(insertionPoint&&insertionPoint!=endPoint){let bestMatch=findBestMatch(ctx,newChild,insertionPoint,endPoint);if(bestMatch){if(bestMatch!==insertionPoint)removeNodesBetween(ctx,insertionPoint,bestMatch);morphNode(bestMatch,newChild,ctx),insertionPoint=bestMatch.nextSibling;continue}}if(newChild instanceof Element){let newChildId=newChild.getAttribute("id");if(ctx.persistentIds.has(newChildId)){let movedChild=moveBeforeById(oldParent,newChildId,insertionPoint,ctx);morphNode(movedChild,newChild,ctx),insertionPoint=movedChild.nextSibling;continue}}let insertedNode=createNode(oldParent,newChild,insertionPoint,ctx);if(insertedNode)insertionPoint=insertedNode.nextSibling}while(insertionPoint&&insertionPoint!=endPoint){let tempNode=insertionPoint;insertionPoint=insertionPoint.nextSibling,removeNode(ctx,tempNode)}}function createNode(oldParent,newChild,insertionPoint,ctx){if(ctx.callbacks.beforeNodeAdded(newChild)===!1)return null;if(ctx.idMap.has(newChild)){let newEmptyChild=document.createElement(newChild.tagName);return oldParent.insertBefore(newEmptyChild,insertionPoint),morphNode(newEmptyChild,newChild,ctx),ctx.callbacks.afterNodeAdded(newEmptyChild),newEmptyChild}else{let newClonedChild=document.importNode(newChild,!0);return oldParent.insertBefore(newClonedChild,insertionPoint),ctx.callbacks.afterNodeAdded(newClonedChild),newClonedChild}}let findBestMatch=function(){function findBestMatch2(ctx,node,startPoint,endPoint){let softMatch=null,nextSibling=node.nextSibling,siblingSoftMatchCount=0,cursor=startPoint;while(cursor&&cursor!=endPoint){if(isSoftMatch(cursor,node)){if(isIdSetMatch(ctx,cursor,node))return cursor;if(softMatch===null){if(!ctx.idMap.has(cursor))softMatch=cursor}}if(softMatch===null&&nextSibling&&isSoftMatch(cursor,nextSibling)){if(siblingSoftMatchCount++,nextSibling=nextSibling.nextSibling,siblingSoftMatchCount>=2)softMatch=void 0}if(ctx.activeElementAndParents.includes(cursor))break;cursor=cursor.nextSibling}return softMatch||null}function isIdSetMatch(ctx,oldNode,newNode){let oldSet=ctx.idMap.get(oldNode),newSet=ctx.idMap.get(newNode);if(!newSet||!oldSet)return!1;for(let id of oldSet)if(newSet.has(id))return!0;return!1}function isSoftMatch(oldNode,newNode){let oldElt=oldNode,newElt=newNode;return oldElt.nodeType===newElt.nodeType&&oldElt.tagName===newElt.tagName&&(!oldElt.getAttribute?.("id")||oldElt.getAttribute?.("id")===newElt.getAttribute?.("id"))}return findBestMatch2}();function removeNode(ctx,node){if(ctx.idMap.has(node))moveBefore(ctx.pantry,node,null);else{if(ctx.callbacks.beforeNodeRemoved(node)===!1)return;node.parentNode?.removeChild(node),ctx.callbacks.afterNodeRemoved(node)}}function removeNodesBetween(ctx,startInclusive,endExclusive){let cursor=startInclusive;while(cursor&&cursor!==endExclusive){let tempNode=cursor;cursor=cursor.nextSibling,removeNode(ctx,tempNode)}return cursor}function moveBeforeById(parentNode,id,after,ctx){let target=ctx.target.getAttribute?.("id")===id&&ctx.target||ctx.target.querySelector(`[id="${id}"]`)||ctx.pantry.querySelector(`[id="${id}"]`);return removeElementFromAncestorsIdMaps(target,ctx),moveBefore(parentNode,target,after),target}function removeElementFromAncestorsIdMaps(element,ctx){let id=element.getAttribute("id");while(element=element.parentNode){let idSet=ctx.idMap.get(element);if(idSet){if(idSet.delete(id),!idSet.size)ctx.idMap.delete(element)}}}function moveBefore(parentNode,element,after){if(parentNode.moveBefore)try{parentNode.moveBefore(element,after)}catch(e){parentNode.insertBefore(element,after)}else parentNode.insertBefore(element,after)}return morphChildren2}(),morphNode=function(){function morphNode2(oldNode,newContent,ctx){if(ctx.ignoreActive&&oldNode===document.activeElement)return null;if(ctx.callbacks.beforeNodeMorphed(oldNode,newContent)===!1)return oldNode;if(oldNode instanceof HTMLHeadElement&&ctx.head.ignore);else if(oldNode instanceof HTMLHeadElement&&ctx.head.style!=="morph")handleHeadElement(oldNode,newContent,ctx);else if(morphAttributes(oldNode,newContent,ctx),!ignoreValueOfActiveElement(oldNode,ctx))morphChildren(ctx,oldNode,newContent);return ctx.callbacks.afterNodeMorphed(oldNode,newContent),oldNode}function morphAttributes(oldNode,newNode,ctx){let type=newNode.nodeType;if(type===1){let oldElt=oldNode,newElt=newNode,oldAttributes=oldElt.attributes,newAttributes=newElt.attributes;for(let newAttribute of newAttributes){if(ignoreAttribute(newAttribute.name,oldElt,"update",ctx))continue;if(oldElt.getAttribute(newAttribute.name)!==newAttribute.value)oldElt.setAttribute(newAttribute.name,newAttribute.value)}for(let i=oldAttributes.length-1;0<=i;i--){let oldAttribute=oldAttributes[i];if(!oldAttribute)continue;if(!newElt.hasAttribute(oldAttribute.name)){if(ignoreAttribute(oldAttribute.name,oldElt,"remove",ctx))continue;oldElt.removeAttribute(oldAttribute.name)}}if(!ignoreValueOfActiveElement(oldElt,ctx))syncInputValue(oldElt,newElt,ctx)}if(type===8||type===3){if(oldNode.nodeValue!==newNode.nodeValue)oldNode.nodeValue=newNode.nodeValue}}function syncInputValue(oldElement,newElement,ctx){if(oldElement instanceof HTMLInputElement&&newElement instanceof HTMLInputElement&&newElement.type!=="file"){let newValue=newElement.value,oldValue=oldElement.value;if(syncBooleanAttribute(oldElement,newElement,"checked",ctx),syncBooleanAttribute(oldElement,newElement,"disabled",ctx),!newElement.hasAttribute("value")){if(!ignoreAttribute("value",oldElement,"remove",ctx))oldElement.value="",oldElement.removeAttribute("value")}else if(oldValue!==newValue){if(!ignoreAttribute("value",oldElement,"update",ctx))oldElement.setAttribute("value",newValue),oldElement.value=newValue}}else if(oldElement instanceof HTMLOptionElement&&newElement instanceof HTMLOptionElement)syncBooleanAttribute(oldElement,newElement,"selected",ctx);else if(oldElement instanceof HTMLTextAreaElement&&newElement instanceof HTMLTextAreaElement){let newValue=newElement.value,oldValue=oldElement.value;if(ignoreAttribute("value",oldElement,"update",ctx))return;if(newValue!==oldValue)oldElement.value=newValue;if(oldElement.firstChild&&oldElement.firstChild.nodeValue!==newValue)oldElement.firstChild.nodeValue=newValue}}function syncBooleanAttribute(oldElement,newElement,attributeName,ctx){let newLiveValue=newElement[attributeName],oldLiveValue=oldElement[attributeName];if(newLiveValue!==oldLiveValue){let ignoreUpdate=ignoreAttribute(attributeName,oldElement,"update",ctx);if(!ignoreUpdate)oldElement[attributeName]=newElement[attributeName];if(newLiveValue){if(!ignoreUpdate)oldElement.setAttribute(attributeName,"")}else if(!ignoreAttribute(attributeName,oldElement,"remove",ctx))oldElement.removeAttribute(attributeName)}}function ignoreAttribute(attr,element,updateType,ctx){if(attr==="value"&&ctx.ignoreActiveValue&&element===document.activeElement)return!0;return ctx.callbacks.beforeAttributeUpdated(attr,element,updateType)===!1}function ignoreValueOfActiveElement(possibleActiveElement,ctx){return!!ctx.ignoreActiveValue&&possibleActiveElement===document.activeElement&&possibleActiveElement!==document.body}return morphNode2}();function withHeadBlocking(ctx,oldNode,newNode,callback){if(ctx.head.block){let oldHead=oldNode.querySelector("head"),newHead=newNode.querySelector("head");if(oldHead&&newHead){let promises=handleHeadElement(oldHead,newHead,ctx);return Promise.all(promises).then(()=>{let newCtx=Object.assign(ctx,{head:{block:!1,ignore:!0}});return callback(newCtx)})}}return callback(ctx)}function handleHeadElement(oldHead,newHead,ctx){let added=[],removed=[],preserved=[],nodesToAppend=[],srcToNewHeadNodes=new Map;for(let newHeadChild of newHead.children)srcToNewHeadNodes.set(newHeadChild.outerHTML,newHeadChild);for(let currentHeadElt of oldHead.children){let inNewContent=srcToNewHeadNodes.has(currentHeadElt.outerHTML),isReAppended=ctx.head.shouldReAppend(currentHeadElt),isPreserved=ctx.head.shouldPreserve(currentHeadElt);if(inNewContent||isPreserved)if(isReAppended)removed.push(currentHeadElt);else srcToNewHeadNodes.delete(currentHeadElt.outerHTML),preserved.push(currentHeadElt);else if(ctx.head.style==="append"){if(isReAppended)removed.push(currentHeadElt),nodesToAppend.push(currentHeadElt)}else if(ctx.head.shouldRemove(currentHeadElt)!==!1)removed.push(currentHeadElt)}nodesToAppend.push(...srcToNewHeadNodes.values());let promises=[];for(let newNode of nodesToAppend){let newElt=document.createRange().createContextualFragment(newNode.outerHTML).firstChild;if(ctx.callbacks.beforeNodeAdded(newElt)!==!1){if("href"in newElt&&newElt.href||"src"in newElt&&newElt.src){let resolve,promise=new Promise(function(_resolve){resolve=_resolve});newElt.addEventListener("load",function(){resolve()}),promises.push(promise)}oldHead.appendChild(newElt),ctx.callbacks.afterNodeAdded(newElt),added.push(newElt)}}for(let removedElement of removed)if(ctx.callbacks.beforeNodeRemoved(removedElement)!==!1)oldHead.removeChild(removedElement),ctx.callbacks.afterNodeRemoved(removedElement);return ctx.head.afterHeadMorphed(oldHead,{added,kept:preserved,removed}),promises}let createMorphContext=function(){function createMorphContext2(oldNode,newContent,config){let{persistentIds,idMap}=createIdMaps(oldNode,newContent),mergedConfig=mergeDefaults(config),morphStyle=mergedConfig.morphStyle||"outerHTML";if(!["innerHTML","outerHTML"].includes(morphStyle))throw`Do not understand how to morph style ${morphStyle}`;return{target:oldNode,newContent,config:mergedConfig,morphStyle,ignoreActive:mergedConfig.ignoreActive,ignoreActiveValue:mergedConfig.ignoreActiveValue,restoreFocus:mergedConfig.restoreFocus,idMap,persistentIds,pantry:createPantry(),activeElementAndParents:createActiveElementAndParents(oldNode),callbacks:mergedConfig.callbacks,head:mergedConfig.head}}function mergeDefaults(config){let finalConfig=Object.assign({},defaults);return Object.assign(finalConfig,config),finalConfig.callbacks=Object.assign({},defaults.callbacks,config.callbacks),finalConfig.head=Object.assign({},defaults.head,config.head),finalConfig}function createPantry(){let pantry=document.createElement("div");return pantry.hidden=!0,document.body.insertAdjacentElement("afterend",pantry),pantry}function createActiveElementAndParents(oldNode){let activeElementAndParents=[],elt=document.activeElement;if(elt?.tagName!=="BODY"&&oldNode.contains(elt))while(elt){if(activeElementAndParents.push(elt),elt===oldNode)break;elt=elt.parentElement}return activeElementAndParents}function findIdElements(root){let elements=Array.from(root.querySelectorAll("[id]"));if(root.getAttribute?.("id"))elements.push(root);return elements}function populateIdMapWithTree(idMap,persistentIds,root,elements){for(let elt of elements){let id=elt.getAttribute("id");if(persistentIds.has(id)){let current=elt;while(current){let idSet=idMap.get(current);if(idSet==null)idSet=new Set,idMap.set(current,idSet);if(idSet.add(id),current===root)break;current=current.parentElement}}}}function createIdMaps(oldContent,newContent){let oldIdElements=findIdElements(oldContent),newIdElements=findIdElements(newContent),persistentIds=createPersistentIds(oldIdElements,newIdElements),idMap=new Map;populateIdMapWithTree(idMap,persistentIds,oldContent,oldIdElements);let newRoot=newContent.__idiomorphRoot||newContent;return populateIdMapWithTree(idMap,persistentIds,newRoot,newIdElements),{persistentIds,idMap}}function createPersistentIds(oldIdElements,newIdElements){let duplicateIds=new Set,oldIdTagNameMap=new Map;for(let{id,tagName}of oldIdElements)if(oldIdTagNameMap.has(id))duplicateIds.add(id);else oldIdTagNameMap.set(id,tagName);let persistentIds=new Set;for(let{id,tagName}of newIdElements)if(persistentIds.has(id))duplicateIds.add(id);else if(oldIdTagNameMap.get(id)===tagName)persistentIds.add(id);for(let id of duplicateIds)persistentIds.delete(id);return persistentIds}return createMorphContext2}(),{normalizeElement,normalizeParent}=function(){let generatedByIdiomorph=new WeakSet;function normalizeElement2(content){if(content instanceof Document)return content.documentElement;else return content}function normalizeParent2(newContent){if(newContent==null)return document.createElement("div");else if(typeof newContent==="string")return normalizeParent2(parseContent(newContent));else if(generatedByIdiomorph.has(newContent))return newContent;else if(newContent instanceof Node)if(newContent.parentNode)return new SlicedParentNode(newContent);else{let dummyParent=document.createElement("div");return dummyParent.append(newContent),dummyParent}else{let dummyParent=document.createElement("div");for(let elt of[...newContent])dummyParent.append(elt);return dummyParent}}class SlicedParentNode{constructor(node){this.originalNode=node,this.realParentNode=node.parentNode,this.previousSibling=node.previousSibling,this.nextSibling=node.nextSibling}get childNodes(){let nodes=[],cursor=this.previousSibling?this.previousSibling.nextSibling:this.realParentNode.firstChild;while(cursor&&cursor!=this.nextSibling)nodes.push(cursor),cursor=cursor.nextSibling;return nodes}querySelectorAll(selector){return this.childNodes.reduce((results,node)=>{if(node instanceof Element){if(node.matches(selector))results.push(node);let nodeList=node.querySelectorAll(selector);for(let i=0;i<nodeList.length;i++)results.push(nodeList[i])}return results},[])}insertBefore(node,referenceNode){return this.realParentNode.insertBefore(node,referenceNode)}moveBefore(node,referenceNode){return this.realParentNode.moveBefore(node,referenceNode)}get __idiomorphRoot(){return this.originalNode}}function parseContent(newContent){let parser=new DOMParser,contentWithSvgsRemoved=newContent.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(contentWithSvgsRemoved.match(/<\/html>/)||contentWithSvgsRemoved.match(/<\/head>/)||contentWithSvgsRemoved.match(/<\/body>/)){let content=parser.parseFromString(newContent,"text/html");if(contentWithSvgsRemoved.match(/<\/html>/))return generatedByIdiomorph.add(content),content;else{let htmlElement=content.firstChild;if(htmlElement)generatedByIdiomorph.add(htmlElement);return htmlElement}}else{let content=parser.parseFromString("<body><template>"+newContent+"</template></body>","text/html").body.querySelector("template").content;return generatedByIdiomorph.add(content),content}}return{normalizeElement:normalizeElement2,normalizeParent:normalizeParent2}}();return{morph,defaults}}();var host=document.createElement("tensaku-overlay");host.id="tensaku-overlay";host.setAttribute("data-tensaku-ui","");host.setAttribute("data-turbo-permanent","");var shadow=host.attachShadow({mode:"open"});if("adoptedStyleSheets"in shadow&&typeof CSSStyleSheet<"u"&&"replaceSync"in CSSStyleSheet.prototype){let sheet=new CSSStyleSheet;sheet.replaceSync(`
|
|
2
|
-
: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,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; }
|
|
3
2
|
* { box-sizing: border-box; }
|
|
4
3
|
[hidden] { display: none !important; }
|
|
5
4
|
|
|
@@ -58,42 +57,66 @@ kbd { font: 10.5px/1 var(--mono); padding: 2px 4px; border-radius: 4px; backgrou
|
|
|
58
57
|
|
|
59
58
|
/* Post-it paper: the note form, note cards and the notes panel's cards. The folded corner sits at the
|
|
60
59
|
bottom right; text and fields stay aligned to the square edges. */
|
|
61
|
-
.postit {
|
|
62
|
-
.postit::after { content: ""; position: absolute; right: -1px; bottom: -1px; width: 18px; height: 18px;
|
|
63
|
-
.postit.question {
|
|
64
|
-
.postit.resolved {
|
|
60
|
+
.postit { --paper: var(--postit); --edge: var(--postit-edge); position: relative; border: 1px solid transparent; border-radius: 3px 3px 0 3px; background: linear-gradient(315deg, transparent 12.7px, var(--paper) 12.7px) border-box; filter: drop-shadow(0 0 .6px var(--edge)); color: var(--ink); }
|
|
61
|
+
.postit::after { content: ""; position: absolute; right: -1px; bottom: -1px; width: 18px; height: 18px; background: linear-gradient(135deg, color-mix(in srgb, var(--paper), #000 18%) 50%, transparent 50%); pointer-events: none; }
|
|
62
|
+
.postit.question { --paper: var(--postit-question); --edge: var(--postit-question-edge); }
|
|
63
|
+
.postit.resolved { --paper: var(--postit-resolved); --edge: var(--postit-resolved-edge); }
|
|
65
64
|
.postit textarea { background: rgba(255, 255, 255, .6); border-color: var(--postit-edge); }
|
|
66
65
|
.postit button:not(.primary):not(.icon-button) { border-color: rgba(0, 0, 0, .16); background: rgba(255, 255, 255, .45); }
|
|
67
66
|
.postit button:not(.primary):not(.icon-button):hover { background: rgba(255, 255, 255, .8); border-color: rgba(0, 0, 0, .35); }
|
|
68
67
|
|
|
69
|
-
.note-form { width: 320px; max-width: calc(100vw - 16px); padding: 10px 12px 12px;
|
|
68
|
+
.note-form { width: 320px; max-width: calc(100vw - 16px); padding: 10px 12px 12px; filter: drop-shadow(0 0 .6px var(--edge)) drop-shadow(0 12px 16px rgba(0, 0, 0, .3)); animation: settle .22s var(--spring); }
|
|
69
|
+
/* The form is a fresh sheet: square corners, no fold. */
|
|
70
|
+
.note-form { border-radius: 3px; background: var(--paper) border-box; }
|
|
71
|
+
.note-form::after { content: none; }
|
|
70
72
|
.note-form .head { display: flex; gap: 6px; align-items: center; margin-bottom: 8px; }
|
|
71
73
|
.note-form .head .what { flex: 1; min-width: 0; }
|
|
72
74
|
.note-form .head .title { font-weight: 600; font-size: 12px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
|
73
75
|
.note-form .head .where { font: 11px/1.3 var(--mono); color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
|
74
76
|
.note-form .head .tools { display: flex; gap: 1px; }
|
|
75
77
|
.note-form .foot { display: flex; gap: 6px; align-items: center; margin-top: 8px; }
|
|
78
|
+
.note-form .options { display: flex; gap: 10px; align-items: center; margin-top: 6px; font-size: 11px; color: var(--muted); }
|
|
79
|
+
.note-form .options label, .note-form .options .to { display: flex; gap: 4px; align-items: center; min-width: 0; }
|
|
80
|
+
.note-form .options .to { flex: 1; justify-content: flex-end; }
|
|
81
|
+
.note-form .options .to select { flex: 1; }
|
|
82
|
+
/* WebKit shrinks a checkbox in a flex row to nothing without a fixed size. */
|
|
83
|
+
.note-form .options input[type=checkbox] { flex: none; width: 13px; height: 13px; margin: 0; }
|
|
84
|
+
.note-form select, .note-card select { min-width: 0; max-width: 100%; font: 11px var(--sans); color: var(--ink); background: var(--paper); border: 1px solid var(--edge); border-radius: 3px; padding: 1px 2px; }
|
|
85
|
+
.popover .agent .outdated { margin-top: 2px; font-size: 11px; color: var(--akaji); }
|
|
86
|
+
.note-card .assign { display: flex; gap: 6px; align-items: center; margin-top: 6px; font-size: 11px; color: var(--muted); }
|
|
87
|
+
.note-card .assign .to { display: flex; gap: 4px; align-items: center; flex: 1; min-width: 0; }
|
|
88
|
+
.note-card .assign select { flex: 1; }
|
|
89
|
+
.note-card .assign button:not(.link), .note-form .foot button.primary { display: inline-flex; gap: 5px; align-items: center; }
|
|
90
|
+
.note-card .assign button:not(.link) { padding: 2px 10px; font-size: 11px; }
|
|
91
|
+
.note-card .assign button:disabled { opacity: .55; cursor: default; }
|
|
92
|
+
.note-card .tools .reopen { padding: 2px 9px; font-size: 11px; }
|
|
93
|
+
.note-form .options .to .link, .note-card .assign .link { font-size: 11px; }
|
|
94
|
+
.note-card .screenshot { display: block; margin: 6px 0 2px; padding: 0; border: 1px solid var(--edge); border-radius: 3px; background: none; cursor: zoom-in; max-width: 100%; }
|
|
95
|
+
.note-card .screenshot img { display: block; max-width: 100%; max-height: 140px; width: auto; height: auto; object-fit: contain; }
|
|
76
96
|
.note-form .foot .hint { flex: 1; font-size: 11px; color: var(--muted); }
|
|
77
97
|
|
|
78
98
|
.note-pop { padding: 0; background: none; border: none; box-shadow: none; min-width: 280px; }
|
|
79
|
-
.note-pop .note-card {
|
|
99
|
+
.note-pop .note-card { filter: drop-shadow(0 0 .6px var(--edge)) drop-shadow(0 12px 16px rgba(0, 0, 0, .3)); animation: settle .2s var(--spring); }
|
|
80
100
|
.note-card { padding: 12px 14px 14px; }
|
|
81
|
-
.note-card .
|
|
82
|
-
.note-card .
|
|
83
|
-
.note-card .
|
|
101
|
+
.note-card .head { display: flex; align-items: center; justify-content: space-between; gap: 8px; margin: -5px -7px 0 0; min-height: 28px; }
|
|
102
|
+
.note-card .tools { display: flex; gap: 1px; flex: none; }
|
|
103
|
+
.note-card .icon-button.resolve:hover { color: var(--resolved); }
|
|
104
|
+
.note-card .icon-button.delete:hover { color: var(--akaji); }
|
|
105
|
+
.note-card .comment { white-space: pre-wrap; margin-top: 4px; overflow-wrap: anywhere; }
|
|
84
106
|
.note-card .row { display: flex; gap: 6px; align-items: center; flex-wrap: wrap; margin-top: 10px; }
|
|
85
|
-
.note-card .row:
|
|
86
|
-
.note-card .
|
|
107
|
+
.note-card .row.end { justify-content: flex-end; margin-top: 6px; }
|
|
108
|
+
.note-card .source { margin-top: 10px; padding-right: 12px; font: 11px/1.4 var(--mono); color: var(--muted); overflow-wrap: anywhere; }
|
|
87
109
|
.note-card textarea { margin-top: 8px; }
|
|
88
|
-
.status { display: inline-flex; align-items: center; gap: 4px; font:
|
|
110
|
+
.status { display: inline-flex; align-items: center; gap: 4px; min-width: 0; font: 600 12px/1.2 var(--sans); color: var(--muted); }
|
|
89
111
|
.status.question { color: var(--question); }
|
|
90
|
-
.status.resolved { color:
|
|
91
|
-
.status
|
|
112
|
+
.status.resolved { color: #1f7f54; }
|
|
113
|
+
.status.declined { color: var(--muted); }
|
|
114
|
+
.status .icon { width: 15px; height: 15px; stroke-width: 2.4; }
|
|
92
115
|
|
|
93
116
|
.panel.menu { background: var(--tray); color: var(--tray-ink); border-color: var(--tray-line); padding: 6px; min-width: 240px; animation: settle .16s var(--spring); }
|
|
94
117
|
.menu { display: flex; flex-direction: column; gap: 1px; }
|
|
95
118
|
.menu h3 { display: flex; flex-direction: column; gap: 2px; margin: 2px 6px 6px; color: var(--tray-ink); font-size: 12px; }
|
|
96
|
-
.menu h3 .where { font: 400 11px/1.3 var(--mono); color: var(--tray-muted);
|
|
119
|
+
.menu h3 .where { font: 400 11px/1.3 var(--mono); color: var(--tray-muted); overflow-wrap: anywhere; }
|
|
97
120
|
.menu button { display: flex; gap: 10px; align-items: center; width: 100%; text-align: left; border: none; border-radius: 7px; padding: 7px 8px; color: var(--tray-ink); }
|
|
98
121
|
.menu button span { flex: 1; }
|
|
99
122
|
.menu button .icon { width: 17px; height: 17px; color: var(--tray-muted); }
|
|
@@ -114,7 +137,11 @@ kbd { font: 10.5px/1 var(--mono); padding: 2px 4px; border-radius: 4px; backgrou
|
|
|
114
137
|
.editable { outline: none; text-decoration: underline dotted color-mix(in srgb, var(--akaji) 70%, transparent); text-decoration-thickness: 1.5px; text-underline-offset: .22em; min-width: .5em; display: inline; }
|
|
115
138
|
.editable { text-decoration-color: color-mix(in srgb, var(--akaji) 45%, transparent); }
|
|
116
139
|
.editable:focus { text-decoration-color: color-mix(in srgb, var(--akaji) 80%, transparent); }
|
|
117
|
-
.chip { display: inline-block; font:
|
|
140
|
+
.chip { display: inline-block; max-width: min(100%, 24em); overflow: hidden; text-overflow: ellipsis; font: 12px/1.6 var(--mono); letter-spacing: normal; color: var(--muted); background: color-mix(in srgb, currentColor 7%, transparent); border: 1px solid var(--line); border-radius: 5px; padding: 0 5px; margin: 0 2px; vertical-align: middle; user-select: none; cursor: default; white-space: nowrap; }
|
|
141
|
+
.chip.mark { width: 10px; height: 10px; padding: 0; background: none; border-style: dashed; }
|
|
142
|
+
.nested { opacity: .6; user-select: none; cursor: default; }
|
|
143
|
+
.nested.link { cursor: pointer; }
|
|
144
|
+
.nested.link:hover { opacity: .9; text-decoration: underline dotted; text-underline-offset: .22em; }
|
|
118
145
|
.locale { display: grid; grid-template-columns: 32px 1fr; gap: 4px 6px; align-items: start; padding: 6px 10px; border-top: 1px solid var(--line); font: 13px/1.4 var(--sans); }
|
|
119
146
|
.locale .code { font: 11px var(--mono); color: var(--muted); padding-top: 2px; }
|
|
120
147
|
.attr { display: grid; grid-template-columns: 90px 1fr; gap: 6px; align-items: baseline; margin-top: 6px; }
|
|
@@ -127,49 +154,111 @@ kbd { font: 10.5px/1 var(--mono); padding: 2px 4px; border-radius: 4px; backgrou
|
|
|
127
154
|
.pin.fresh { animation: pin-drop .32s var(--spring); }
|
|
128
155
|
.pin.question { background: var(--question); }
|
|
129
156
|
.pin.resolved { background: var(--resolved); }
|
|
157
|
+
.pin.declined { background: var(--muted); }
|
|
130
158
|
.pin .icon { width: 16px; height: 16px; stroke-width: 2.6; }
|
|
131
159
|
.pin.fresh .stroke { stroke-dasharray: 24; stroke-dashoffset: 24; animation: draw .42s .12s ease-out forwards; }
|
|
132
160
|
|
|
133
161
|
/* The tray. The corner button opens it; the selected tool rises and shows its ink. */
|
|
134
|
-
.dock { position: fixed; display: flex; align-items: center;
|
|
135
|
-
.corner { width: 40px; height: 40px; border-radius: 50%; border:
|
|
136
|
-
.corner
|
|
137
|
-
.corner
|
|
162
|
+
.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
|
+
.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; }
|
|
164
|
+
.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
|
+
.corner:hover { background: var(--tray-raised); }
|
|
166
|
+
.corner:hover .logo { rotate: -8deg; }
|
|
167
|
+
.corner:focus-visible { outline: 2px solid var(--marker); outline-offset: 1px; }
|
|
168
|
+
.dock.open .corner .logo { transform: rotate(360deg); }
|
|
169
|
+
.corner.active, .corner.active:hover { background: var(--akaji); color: #fff; }
|
|
138
170
|
.corner .count { position: absolute; top: -5px; right: -5px; min-width: 18px; height: 18px; border-radius: 9px; background: var(--marker); color: var(--ink); font: 700 10px/18px var(--sans); padding: 0 5px; box-shadow: 0 1px 3px rgba(0, 0, 0, .3); }
|
|
139
|
-
|
|
171
|
+
/* The tools stay pinned next to the corner button while the toolbar's width reveals them, right to left. */
|
|
172
|
+
.toolbar { display: flex; justify-content: flex-end; width: 0; overflow: hidden; opacity: 0; visibility: hidden; transition: width .28s cubic-bezier(.22, 1, .36, 1), opacity .18s, visibility 0s .28s; }
|
|
173
|
+
.dock.open .toolbar { width: var(--tools-width); opacity: 1; visibility: visible; transition: width .28s cubic-bezier(.22, 1, .36, 1), opacity .18s, visibility 0s; }
|
|
174
|
+
.dock.settled .toolbar { overflow: visible; }
|
|
175
|
+
.tools { display: flex; align-items: center; gap: 2px; flex: none; }
|
|
176
|
+
.tools > * { flex: none; }
|
|
177
|
+
.tools > :last-child { margin-right: 2px; }
|
|
140
178
|
.toolbar .sep { width: 1px; height: 20px; background: var(--tray-line); margin: 0 4px; }
|
|
141
|
-
.tool { position: relative; display: grid; place-items: center; width:
|
|
142
|
-
.tool:hover { background: var(--tray-raised);
|
|
143
|
-
.tool[aria-pressed="true"] { background: var(--
|
|
144
|
-
|
|
145
|
-
.tool .icon { width: 22px; height: 22px; }
|
|
179
|
+
.tool { position: relative; display: grid; place-items: center; width: 40px; height: 40px; padding: 0; border: none; border-radius: 50%; color: var(--tray-ink); }
|
|
180
|
+
.tool:hover, .tool[aria-pressed="true"] { background: var(--tray-raised); }
|
|
181
|
+
.tool[aria-pressed="true"]::after { content: ""; position: absolute; bottom: 5px; left: 50%; width: 14px; height: 3px; margin-left: -7px; border-radius: 2px; background: var(--ink-color, var(--tray-ink)); }
|
|
182
|
+
/* The circle stays on the bar's center line; only the drawing moves. */
|
|
183
|
+
.tool .icon { width: 22px; height: 22px; transition: transform .16s var(--spring); }
|
|
184
|
+
.tool:hover .icon { transform: translateY(-1px) rotate(-6deg); }
|
|
185
|
+
.tool[aria-pressed="true"] .icon { transform: translateY(-3px); }
|
|
146
186
|
.tool .badge { position: absolute; top: 2px; right: 1px; min-width: 16px; height: 16px; border-radius: 8px; background: var(--akaji); color: #fff; font: 700 9.5px/16px var(--sans); padding: 0 4px; }
|
|
147
|
-
.tool .tip { position: absolute; bottom: calc(100% +
|
|
187
|
+
.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; }
|
|
148
188
|
.tool:hover .tip, .tool:focus-visible .tip { opacity: 1; transform: translateX(-50%); }
|
|
149
189
|
.tool:focus-visible { outline: 2px solid var(--marker); outline-offset: 1px; }
|
|
190
|
+
/* On a phone the tools are smaller, and on a screen narrower than the open toolbar its tools scroll
|
|
191
|
+
sideways. The dock sits 16px from the right edge and the corner button takes 50px of it. */
|
|
192
|
+
@media (max-width: 420px) {
|
|
193
|
+
.tool { width: 32px; height: 32px; }
|
|
194
|
+
.tool .icon { width: 20px; height: 20px; }
|
|
195
|
+
.tool[aria-pressed="true"]::after { bottom: 2px; }
|
|
196
|
+
.toolbar .sep { margin: 0 2px; }
|
|
197
|
+
.toolbar { justify-content: safe flex-end; }
|
|
198
|
+
.dock.open .toolbar { width: min(var(--tools-width), calc(100vw - 76px)); }
|
|
199
|
+
.dock.settled .toolbar { overflow-x: auto; scrollbar-width: none; }
|
|
200
|
+
}
|
|
150
201
|
|
|
151
202
|
/* The notes panel: the tray's material, holding the page's Post-its. */
|
|
152
|
-
.sidebar { position: fixed; top: 12px; right: 12px; bottom: 70px; 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); }
|
|
203
|
+
.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); }
|
|
153
204
|
.sidebar header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px; }
|
|
154
205
|
.sidebar header strong { font-size: 14px; }
|
|
155
206
|
.sidebar header .icon-button { color: var(--tray-muted); }
|
|
156
207
|
.sidebar header .icon-button:hover { background: var(--tray-raised); color: var(--tray-ink); }
|
|
157
|
-
|
|
158
|
-
.sidebar >
|
|
159
|
-
.sidebar
|
|
208
|
+
/* Pinned to the panel's bottom edge, however few notes there are and while they scroll. */
|
|
209
|
+
.sidebar > * { flex: none; }
|
|
210
|
+
.sidebar .copy-bar { position: sticky; bottom: -14px; display: flex; flex-direction: column; gap: 10px; margin: auto -14px -14px; padding: 10px 14px 12px; background: var(--tray); }
|
|
211
|
+
.sidebar .copy-bar .actions { display: flex; justify-content: flex-end; gap: 6px; }
|
|
212
|
+
.sidebar .copy-bar .actions button { border-color: var(--tray-line); color: var(--tray-ink); font-size: 12px; }
|
|
213
|
+
.sidebar .copy-bar .actions button:hover { border-color: var(--tray-muted); background: var(--tray-raised); }
|
|
214
|
+
.sidebar .listener { display: flex; align-items: center; gap: 7px; margin: 0 -14px; padding: 10px 14px 0; border-top: 1px solid var(--tray-line); font-size: 12px; color: var(--tray-muted); }
|
|
215
|
+
.sidebar .listener .dot { width: 8px; height: 8px; border-radius: 50%; background: var(--tray-line); box-shadow: inset 0 0 0 1px var(--tray-muted); }
|
|
216
|
+
.sidebar .listener.on { color: var(--tray-ink); }
|
|
217
|
+
.sidebar .listener.on .dot { background: var(--resolved); box-shadow: 0 0 0 3px rgba(47, 168, 114, .25); }
|
|
218
|
+
.sidebar .listener button.link { margin-left: auto; color: var(--tray-ink); font-size: 12px; }
|
|
160
219
|
.sidebar .note-card { margin-bottom: 10px; }
|
|
161
220
|
.sidebar .empty { color: var(--tray-muted); padding: 12px 2px; line-height: 1.5; }
|
|
162
221
|
|
|
163
222
|
.toasts { position: fixed; left: 50%; bottom: 18px; transform: translateX(-50%); display: flex; flex-direction: column; gap: 6px; align-items: center; }
|
|
164
223
|
.toast { background: var(--tray); color: var(--tray-ink); border: 1px solid var(--tray-line); border-radius: 999px; padding: 8px 14px; box-shadow: 0 10px 26px -8px rgba(0, 0, 0, .45); display: flex; gap: 10px; align-items: center; max-width: 560px; animation: settle .2s var(--spring); }
|
|
224
|
+
@media (max-width: 640px) { .toasts { bottom: 76px; } }
|
|
225
|
+
.toast.detailed { flex-wrap: wrap; justify-content: space-between; width: min(36rem, calc(100vw - 24px)); border-radius: 12px; }
|
|
226
|
+
.diff { flex-basis: 100%; min-width: 0; font: 12px/1.6 var(--mono); }
|
|
227
|
+
.diff-row { padding: 0 6px; white-space: pre-wrap; overflow-wrap: anywhere; }
|
|
228
|
+
.diff-row:first-child { border-radius: 4px 4px 0 0; }
|
|
229
|
+
.diff-row:last-child { border-radius: 0 0 4px 4px; }
|
|
230
|
+
.diff-row mark { color: inherit; border-radius: 2px; }
|
|
231
|
+
.diff-row.removed { background: rgba(224, 52, 79, .16); }
|
|
232
|
+
.diff-row.removed mark { background: rgba(224, 52, 79, .55); }
|
|
233
|
+
.diff-row.added { background: rgba(47, 168, 114, .18); }
|
|
234
|
+
.diff-row.added mark { background: rgba(47, 168, 114, .55); }
|
|
235
|
+
.diff-sign { display: inline-block; width: 1.25em; user-select: none; }
|
|
236
|
+
.diff-more { padding: 2px 6px 0; color: var(--tray-muted); }
|
|
165
237
|
.toast.error { background: var(--akaji); border-color: var(--akaji); color: #fff; border-radius: 12px; }
|
|
166
238
|
.toast button { color: inherit; border-color: currentColor; padding: 1px 9px; font-size: 12px; border-radius: 999px; }
|
|
167
239
|
|
|
168
|
-
/*
|
|
169
|
-
.
|
|
170
|
-
.
|
|
171
|
-
.agent
|
|
172
|
-
.
|
|
240
|
+
/* The Agents button: a grey plane with no agent, in ink while one is connected, flying in green while one listens. */
|
|
241
|
+
.tool.agents:not(.connected) .icon { opacity: .45; }
|
|
242
|
+
.popover .agent { display: flex; flex-direction: column; gap: 3px; padding: 8px 6px; border-top: 1px solid var(--tray-line); }
|
|
243
|
+
.popover .agent .who { display: flex; gap: 8px; align-items: baseline; justify-content: space-between; }
|
|
244
|
+
.popover .agent .who strong { display: flex; gap: 6px; align-items: center; min-width: 0; }
|
|
245
|
+
.popover .agent .who .client, .popover .agent .who .icon { flex: none; width: 14px; height: 14px; }
|
|
246
|
+
.popover .agent .who .client { fill: currentColor; }
|
|
247
|
+
/* The first row sits right under the heading, without a line. */
|
|
248
|
+
.popover h3 + .agent, .popover h3 + .idle-toggle { border-top: none; }
|
|
249
|
+
.popover .agent .doing { font-size: 12px; color: var(--tray-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
250
|
+
.popover .agent.listening .doing { color: var(--resolved); }
|
|
251
|
+
.popover .idle-toggle { all: unset; box-sizing: border-box; width: 100%; cursor: pointer; display: block; padding: 8px 6px; border-top: 1px solid var(--tray-line); font-size: 12px; color: var(--tray-muted); }
|
|
252
|
+
.popover .idle-toggle::before { content: "▸ "; }
|
|
253
|
+
.popover .idle-toggle[aria-expanded="true"]::before { content: "▾ "; }
|
|
254
|
+
.popover .idle-toggle:hover, .popover .idle-toggle:focus-visible { color: var(--tray-ink); }
|
|
255
|
+
.popover .agent a.doing { color: var(--tray-ink); text-decoration: underline; text-decoration-color: var(--tray-line); }
|
|
256
|
+
.popover .connect { display: flex; flex-direction: column; gap: 4px; margin-top: 8px; padding: 10px; border: 1px solid var(--tray-line); border-radius: 10px; background: var(--tray-raised); font-size: 12px; line-height: 1.45; }
|
|
257
|
+
.popover .connect p { margin: 0 0 2px; }
|
|
258
|
+
.popover .connect .command { display: flex; justify-content: space-between; align-items: center; gap: 6px; }
|
|
259
|
+
.popover .connect code { font: 11px/1.3 var(--mono); overflow-wrap: anywhere; }
|
|
260
|
+
.popover .connect .icon-button { border: none; color: var(--tray-muted); }
|
|
261
|
+
.popover .connect .icon-button:hover { color: var(--tray-ink); background: var(--tray); }
|
|
173
262
|
.tool.confirm { background: var(--akaji); color: #fff; }
|
|
174
263
|
.tool.confirm .tip { background: var(--akaji); border-color: var(--akaji); color: #fff; }
|
|
175
264
|
|
|
@@ -177,30 +266,13 @@ kbd { font: 10.5px/1 var(--mono); padding: 2px 4px; border-radius: 4px; backgrou
|
|
|
177
266
|
.note-card .editing textarea { margin-top: 8px; }
|
|
178
267
|
.note-card .editing .row { justify-content: flex-end; }
|
|
179
268
|
.pin.working { background: var(--tray); box-shadow: 0 0 0 3px rgba(255, 225, 77, .55), 0 3px 8px rgba(0, 0, 0, .3); animation: breathe 2.4s ease-in-out infinite; }
|
|
180
|
-
.status.working { color: #
|
|
181
|
-
@keyframes breathe { 50% { box-shadow: 0 0 0 6px rgba(47, 168, 114, 0); } }
|
|
182
|
-
.pin.working { animation-name: breathe-ink; }
|
|
183
|
-
@keyframes breathe-ink { 50% { box-shadow: 0 0 0 7px rgba(255, 225, 77, 0), 0 3px 8px rgba(0, 0, 0, .3); } }
|
|
184
|
-
|
|
185
|
-
/* An agent connected over MCP: a green light at the start of the tray and on the corner button. */
|
|
186
|
-
.agent-light { position: relative; width: 10px; height: 10px; margin: 0 6px 0 8px; border-radius: 50%; background: var(--resolved); box-shadow: 0 0 0 3px rgba(47, 168, 114, .25); animation: breathe 2.4s ease-in-out infinite; }
|
|
187
|
-
.agent-light .tip { bottom: calc(100% + 18px); }
|
|
188
|
-
.agent-light:hover .tip { opacity: 1; transform: translateX(-50%); }
|
|
189
|
-
.corner.agent::before { content: ""; position: absolute; left: -2px; bottom: -2px; width: 11px; height: 11px; border-radius: 50%; background: var(--resolved); border: 2px solid var(--tray); }
|
|
190
|
-
.tool.confirm { background: var(--akaji); color: #fff; }
|
|
191
|
-
.tool.confirm .tip { background: var(--akaji); border-color: var(--akaji); color: #fff; }
|
|
192
|
-
|
|
193
|
-
.panel.pick { min-width: 220px; }
|
|
194
|
-
.note-card .editing textarea { margin-top: 8px; }
|
|
195
|
-
.note-card .editing .row { justify-content: flex-end; }
|
|
196
|
-
.pin.working { background: var(--tray); box-shadow: 0 0 0 3px rgba(255, 225, 77, .55), 0 3px 8px rgba(0, 0, 0, .3); animation: breathe 2.4s ease-in-out infinite; }
|
|
197
|
-
.status.working { color: #8a6a00; background: rgba(255, 225, 77, .55); }
|
|
269
|
+
.status.working { color: #7a5e00; }
|
|
198
270
|
@keyframes breathe { 50% { box-shadow: 0 0 0 6px rgba(47, 168, 114, 0); } }
|
|
199
271
|
.pin.working { animation-name: breathe-ink; }
|
|
200
272
|
@keyframes breathe-ink { 50% { box-shadow: 0 0 0 7px rgba(255, 225, 77, 0), 0 3px 8px rgba(0, 0, 0, .3); } }
|
|
201
273
|
|
|
202
274
|
/* Popovers above the toolbar: history and settings, in the tray's material. */
|
|
203
|
-
.popover { position:
|
|
275
|
+
.popover { position: fixed; width: 340px; max-width: calc(100vw - 24px); max-height: 60vh; overflow: auto; background: var(--tray); color: var(--tray-ink); border: 1px solid var(--tray-line); border-radius: 14px; padding: 10px; box-shadow: 0 18px 40px -12px rgba(0, 0, 0, .5); animation: settle .18s var(--spring); }
|
|
204
276
|
.popover h3 { display: flex; flex-direction: column; gap: 3px; margin: 2px 4px 10px; font-size: 13px; }
|
|
205
277
|
.popover .where { font: 400 11px/1.35 var(--sans); color: var(--tray-muted); }
|
|
206
278
|
.popover button { border-color: var(--tray-line); color: var(--tray-ink); font-size: 12px; }
|
|
@@ -210,20 +282,40 @@ kbd { font: 10.5px/1 var(--mono); padding: 2px 4px; border-radius: 4px; backgrou
|
|
|
210
282
|
.popover .entry .what { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 2px; }
|
|
211
283
|
.popover .entry .what .where { font-family: var(--mono); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
212
284
|
.popover .entry.undone .what > span:first-child { text-decoration: line-through; color: var(--tray-muted); }
|
|
213
|
-
|
|
214
|
-
.
|
|
215
|
-
.
|
|
285
|
+
/* The settings panel: sections apart by one rule, rows on an 8px rhythm without rules of their own. */
|
|
286
|
+
.settings header { margin-bottom: 0; }
|
|
287
|
+
.settings section { display: flex; flex-direction: column; gap: 4px; padding: 16px 0; }
|
|
288
|
+
.settings section + section { border-top: 1px solid var(--tray-line); }
|
|
289
|
+
.settings section:last-child { padding-bottom: 0; }
|
|
290
|
+
.settings h4 { display: flex; justify-content: space-between; align-items: baseline; margin: 0 0 4px; color: var(--tray-muted); font-size: 11px; font-weight: 700; letter-spacing: .06em; text-transform: uppercase; }
|
|
291
|
+
.settings h4 button.link { color: var(--tray-muted); font-size: 12px; font-weight: 400; letter-spacing: normal; text-transform: none; }
|
|
292
|
+
.settings h4 button.link:hover { color: var(--tray-ink); }
|
|
293
|
+
.settings h5 { margin: 12px 0 0; color: var(--tray-muted); font-size: 12px; font-weight: 600; }
|
|
294
|
+
.settings .where { margin: 0; font: 400 12px/1.4 var(--sans); color: var(--tray-muted); }
|
|
295
|
+
.settings section > .where { margin-bottom: 4px; }
|
|
296
|
+
.settings .setting { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; min-height: 32px; }
|
|
297
|
+
.settings .setting > span:first-child { flex: 1; }
|
|
298
|
+
.settings .setting > button { border-color: var(--tray-line); color: var(--tray-ink); font-size: 12px; }
|
|
299
|
+
.settings .setting > button:hover { border-color: var(--tray-muted); background: var(--tray-raised); }
|
|
300
|
+
.settings .check { display: flex; gap: 8px; align-items: flex-start; padding: 4px 0; cursor: pointer; }
|
|
301
|
+
.settings .check input { width: auto; margin: 2px 0 0; accent-color: var(--akaji); }
|
|
302
|
+
.settings .check > span { display: flex; flex-direction: column; gap: 2px; }
|
|
216
303
|
.segmented { display: inline-flex; border: 1px solid var(--tray-line); border-radius: 999px; padding: 2px; }
|
|
217
|
-
.segmented button { border: none; border-radius: 999px; padding: 3px 10px; }
|
|
304
|
+
.segmented button { border: none; border-radius: 999px; padding: 3px 10px; font-size: 12px; }
|
|
218
305
|
.segmented button[aria-pressed="true"] { background: var(--tray-ink); color: var(--tray); }
|
|
219
|
-
.
|
|
220
|
-
.
|
|
221
|
-
.
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
.
|
|
225
|
-
.
|
|
226
|
-
.
|
|
306
|
+
.settings .shortcut { display: flex; align-items: center; gap: 4px; min-height: 32px; font-size: 13px; }
|
|
307
|
+
.settings .shortcut > span:first-child { flex: 1; min-width: 0; }
|
|
308
|
+
.settings .shortcut.changed > span:first-child::after { content: " •"; color: var(--marker); }
|
|
309
|
+
.settings .shortcut .keys { min-width: 88px; padding: 3px 8px; border: 1px dashed transparent; border-radius: 7px; text-align: right; font-size: 12px; }
|
|
310
|
+
.settings .shortcut .keys:hover { border-color: var(--tray-line); background: var(--tray-raised); }
|
|
311
|
+
.settings .shortcut .keys.recording { border-color: var(--marker); color: var(--marker); text-align: center; }
|
|
312
|
+
.settings .shortcut .keys .none { color: var(--tray-muted); }
|
|
313
|
+
.settings .shortcut .icon-button { width: 24px; height: 24px; color: var(--tray-muted); }
|
|
314
|
+
.settings .shortcut .icon-button:hover { background: var(--tray-raised); color: var(--tray-ink); }
|
|
315
|
+
.settings .shortcut .icon-button .icon { width: 14px; height: 14px; }
|
|
316
|
+
.settings .shortcut:not(:has(.icon-button)) .keys { margin-right: 28px; }
|
|
317
|
+
.settings .shortcut.always { min-height: 28px; color: var(--tray-muted); }
|
|
318
|
+
.settings .shortcut.always kbd { margin-right: 37px; }
|
|
227
319
|
|
|
228
320
|
/* Notes on selected text: the phrase stays marked with the highlighter. */
|
|
229
321
|
.phrase { position: absolute; pointer-events: none; background: var(--marker-soft); box-shadow: inset 0 -2px 0 var(--marker-edge); border-radius: 2px; }
|
|
@@ -231,11 +323,15 @@ kbd { font: 10.5px/1 var(--mono); padding: 2px 4px; border-radius: 4px; backgrou
|
|
|
231
323
|
.ink-muted { color: var(--muted); }
|
|
232
324
|
.phrase.resolved { background: rgba(47, 168, 114, .16); box-shadow: inset 0 -2px 0 var(--resolved); }
|
|
233
325
|
|
|
234
|
-
|
|
235
|
-
.note-card .
|
|
236
|
-
.note-card .message
|
|
237
|
-
.note-card .message .who { display: block; font:
|
|
326
|
+
/* The agent's replies read as more writing on the same paper, under a ruled line. */
|
|
327
|
+
.note-card .thread { display: flex; flex-direction: column; gap: 8px; margin-top: 10px; padding-top: 9px; border-top: 1px dashed rgba(0, 0, 0, .2); }
|
|
328
|
+
.note-card .message { white-space: pre-wrap; overflow-wrap: anywhere; }
|
|
329
|
+
.note-card .message .who { display: block; font: 600 12px/1.4 var(--sans); color: var(--muted); }
|
|
238
330
|
.note-card .missing { margin-top: 8px; font-size: 12px; color: var(--akaji); }
|
|
331
|
+
.note-card .missing button.link { color: inherit; font-weight: 600; }
|
|
332
|
+
.sidebar .section { display: flex; justify-content: space-between; align-items: center; gap: 8px; margin: 16px 2px 10px; color: var(--tray-muted); font-size: 12px; font-weight: 600; }
|
|
333
|
+
.sidebar .section button { border-color: var(--tray-line); color: var(--tray-ink); font-size: 12px; font-weight: 400; }
|
|
334
|
+
.sidebar .section button:hover { border-color: var(--tray-muted); background: var(--tray-raised); }
|
|
239
335
|
.sidebar .tabs { display: flex; gap: 2px; margin-bottom: 10px; border: 1px solid var(--tray-line); border-radius: 999px; padding: 2px; width: fit-content; }
|
|
240
336
|
.sidebar .tabs button { border: none; border-radius: 999px; padding: 3px 12px; color: var(--tray-muted); font-size: 12px; }
|
|
241
337
|
.sidebar .tabs button[aria-selected="true"] { background: var(--tray-ink); color: var(--tray); }
|
|
@@ -252,265 +348,25 @@ kbd { font: 10.5px/1 var(--mono); padding: 2px 4px; border-radius: 4px; backgrou
|
|
|
252
348
|
@media (prefers-reduced-motion: reduce) {
|
|
253
349
|
*, *::before, *::after { animation: none !important; transition: none !important; }
|
|
254
350
|
.pin.fresh .stroke { stroke-dashoffset: 0; }
|
|
255
|
-
.tool:hover, .tool[aria-pressed="true"], .corner:hover { transform: none; }
|
|
351
|
+
.tool:hover .icon, .tool[aria-pressed="true"] .icon, .corner:hover .logo { transform: none; rotate: none; }
|
|
256
352
|
}
|
|
257
|
-
`),shadow.adoptedStyleSheets=[sheet]}else{let style=document.createElement("style");style.textContent=`
|
|
258
|
-
:host { all: initial; }
|
|
259
|
-
* { box-sizing: border-box; }
|
|
260
|
-
[hidden] { display: none !important; }
|
|
353
|
+
`;var host=document.createElement("tensaku-overlay");host.id="tensaku-overlay";host.setAttribute("data-tensaku-ui","");host.setAttribute("data-turbo-permanent","");var shadow=host.attachShadow({mode:"open"});if("adoptedStyleSheets"in shadow&&typeof CSSStyleSheet<"u"&&"replaceSync"in CSSStyleSheet.prototype){let sheet=new CSSStyleSheet;sheet.replaceSync(overlay_default),shadow.adoptedStyleSheets=[sheet]}else{let style=document.createElement("style");style.textContent=overlay_default,shadow.append(style)}var layer=div("layer"),fixed=div("fixed"),toasts=div("toasts");shadow.append(layer,fixed);fixed.append(toasts);function mount(){if(!host.isConnected)document.documentElement.append(host)}function h(tag,attributes={},...children){let element=document.createElement(tag);for(let[name,value]of Object.entries(attributes)){if(value===void 0||value===null||value===!1)continue;if(name.startsWith("on")&&typeof value==="function")element.addEventListener(name.slice(2),value);else if(name==="className")element.className=value;else element.setAttribute(name,value===!0?"":String(value))}for(let child of children)if(child)element.append(child);return element}function div(className,...children){return h("div",{className},...children)}function toast(message,options={}){let element=div("toast"+(options.error?" error":"")+(options.detail?" detailed":""),h("span",{},message));element.setAttribute("role",options.error?"alert":"status");for(let[label,action]of Object.entries(options.actions??{}))element.append(h("button",{onclick:()=>{element.remove(),action()}},label));if(options.detail)element.append(options.detail);if(toasts.append(element),options.timeout!==0)setTimeout(()=>element.remove(),options.timeout??(options.error?8000:5000));return element}function panel(anchor,className,...children){let element=div("panel "+className,...children);return layer.append(element),place(element,anchor),element}function place(element,anchor,over=!1){let width=element.offsetWidth,left=Math.max(scrollX+8,Math.min(anchor.left,scrollX+innerWidth-width-8)),top=over?anchor.top:anchor.bottom+6;if(!over&&top+element.offsetHeight>scrollY+innerHeight-8&&anchor.top-element.offsetHeight-6>scrollY)top=anchor.top-element.offsetHeight-6;element.style.left=`${left}px`,element.style.top=`${top}px`}function box(rect,className,label){let element=div("box "+className);if(Object.assign(element.style,{left:`${rect.left}px`,top:`${rect.top}px`,width:`${rect.width}px`,height:`${rect.height}px`}),layer.append(element),!label)return[element];let tag=div("label");if(tag.append(label[0]),label[1])tag.append(h("span",{className:"where"},label[1]));return Object.assign(tag.style,{left:`${rect.left}px`,top:`${rect.top}px`}),layer.append(tag),[element,tag]}async function copy(text){try{await navigator.clipboard.writeText(text)}catch{let area=h("textarea",{},text);shadow.append(area),area.select(),document.execCommand("copy"),area.remove()}}function storage(key,fallback){try{let value=localStorage.getItem(`tensaku:${key}`);return value?JSON.parse(value):fallback}catch{return fallback}}function store(key,value){try{localStorage.setItem(`tensaku:${key}`,JSON.stringify(value))}catch{}}function activeInShadow(){return shadow.activeElement}var DEFAULTS={copyFormat:"detailed",notify:!1,shortcuts:{}},current={...DEFAULTS,...storage("settings",{})},listeners=[],settings=()=>current,onSettings=(listener)=>{listeners.push(listener),listener(current)};function changeSettings(change){current={...current,...change},store("settings",current),listeners.forEach((listener)=>listener(current))}var Idiomorph=function(){let noOp=()=>{},defaults={morphStyle:"outerHTML",callbacks:{beforeNodeAdded:noOp,afterNodeAdded:noOp,beforeNodeMorphed:noOp,afterNodeMorphed:noOp,beforeNodeRemoved:noOp,afterNodeRemoved:noOp,beforeAttributeUpdated:noOp},head:{style:"merge",shouldPreserve:(elt)=>elt.getAttribute("im-preserve")==="true",shouldReAppend:(elt)=>elt.getAttribute("im-re-append")==="true",shouldRemove:noOp,afterHeadMorphed:noOp},restoreFocus:!0};function morph(oldNode,newContent,config={}){oldNode=normalizeElement(oldNode);let newNode=normalizeParent(newContent),ctx=createMorphContext(oldNode,newNode,config),morphedNodes=saveAndRestoreFocus(ctx,()=>{return withHeadBlocking(ctx,oldNode,newNode,(ctx2)=>{if(ctx2.morphStyle==="innerHTML")return morphChildren(ctx2,oldNode,newNode),Array.from(oldNode.childNodes);else return morphOuterHTML(ctx2,oldNode,newNode)})});return ctx.pantry.remove(),morphedNodes}function morphOuterHTML(ctx,oldNode,newNode){let oldParent=normalizeParent(oldNode);return morphChildren(ctx,oldParent,newNode,oldNode,oldNode.nextSibling),Array.from(oldParent.childNodes)}function saveAndRestoreFocus(ctx,fn){if(!ctx.config.restoreFocus)return fn();let activeElement=document.activeElement;if(!(activeElement instanceof HTMLInputElement||activeElement instanceof HTMLTextAreaElement))return fn();let{id:activeElementId,selectionStart,selectionEnd}=activeElement,results=fn();if(activeElementId&&activeElementId!==document.activeElement?.getAttribute("id"))activeElement=ctx.target.querySelector(`[id="${activeElementId}"]`),activeElement?.focus();if(activeElement&&!activeElement.selectionEnd&&selectionEnd)activeElement.setSelectionRange(selectionStart,selectionEnd);return results}let morphChildren=function(){function morphChildren2(ctx,oldParent,newParent,insertionPoint=null,endPoint=null){if(oldParent instanceof HTMLTemplateElement&&newParent instanceof HTMLTemplateElement)oldParent=oldParent.content,newParent=newParent.content;insertionPoint||=oldParent.firstChild;for(let newChild of newParent.childNodes){if(insertionPoint&&insertionPoint!=endPoint){let bestMatch=findBestMatch(ctx,newChild,insertionPoint,endPoint);if(bestMatch){if(bestMatch!==insertionPoint)removeNodesBetween(ctx,insertionPoint,bestMatch);morphNode(bestMatch,newChild,ctx),insertionPoint=bestMatch.nextSibling;continue}}if(newChild instanceof Element){let newChildId=newChild.getAttribute("id");if(ctx.persistentIds.has(newChildId)){let movedChild=moveBeforeById(oldParent,newChildId,insertionPoint,ctx);morphNode(movedChild,newChild,ctx),insertionPoint=movedChild.nextSibling;continue}}let insertedNode=createNode(oldParent,newChild,insertionPoint,ctx);if(insertedNode)insertionPoint=insertedNode.nextSibling}while(insertionPoint&&insertionPoint!=endPoint){let tempNode=insertionPoint;insertionPoint=insertionPoint.nextSibling,removeNode(ctx,tempNode)}}function createNode(oldParent,newChild,insertionPoint,ctx){if(ctx.callbacks.beforeNodeAdded(newChild)===!1)return null;if(ctx.idMap.has(newChild)){let newEmptyChild=document.createElement(newChild.tagName);return oldParent.insertBefore(newEmptyChild,insertionPoint),morphNode(newEmptyChild,newChild,ctx),ctx.callbacks.afterNodeAdded(newEmptyChild),newEmptyChild}else{let newClonedChild=document.importNode(newChild,!0);return oldParent.insertBefore(newClonedChild,insertionPoint),ctx.callbacks.afterNodeAdded(newClonedChild),newClonedChild}}let findBestMatch=function(){function findBestMatch2(ctx,node,startPoint,endPoint){let softMatch=null,nextSibling=node.nextSibling,siblingSoftMatchCount=0,cursor2=startPoint;while(cursor2&&cursor2!=endPoint){if(isSoftMatch(cursor2,node)){if(isIdSetMatch(ctx,cursor2,node))return cursor2;if(softMatch===null){if(!ctx.idMap.has(cursor2))softMatch=cursor2}}if(softMatch===null&&nextSibling&&isSoftMatch(cursor2,nextSibling)){if(siblingSoftMatchCount++,nextSibling=nextSibling.nextSibling,siblingSoftMatchCount>=2)softMatch=void 0}if(ctx.activeElementAndParents.includes(cursor2))break;cursor2=cursor2.nextSibling}return softMatch||null}function isIdSetMatch(ctx,oldNode,newNode){let oldSet=ctx.idMap.get(oldNode),newSet=ctx.idMap.get(newNode);if(!newSet||!oldSet)return!1;for(let id of oldSet)if(newSet.has(id))return!0;return!1}function isSoftMatch(oldNode,newNode){let oldElt=oldNode,newElt=newNode;return oldElt.nodeType===newElt.nodeType&&oldElt.tagName===newElt.tagName&&(!oldElt.getAttribute?.("id")||oldElt.getAttribute?.("id")===newElt.getAttribute?.("id"))}return findBestMatch2}();function removeNode(ctx,node){if(ctx.idMap.has(node))moveBefore(ctx.pantry,node,null);else{if(ctx.callbacks.beforeNodeRemoved(node)===!1)return;node.parentNode?.removeChild(node),ctx.callbacks.afterNodeRemoved(node)}}function removeNodesBetween(ctx,startInclusive,endExclusive){let cursor2=startInclusive;while(cursor2&&cursor2!==endExclusive){let tempNode=cursor2;cursor2=cursor2.nextSibling,removeNode(ctx,tempNode)}return cursor2}function moveBeforeById(parentNode,id,after,ctx){let target=ctx.target.getAttribute?.("id")===id&&ctx.target||ctx.target.querySelector(`[id="${id}"]`)||ctx.pantry.querySelector(`[id="${id}"]`);return removeElementFromAncestorsIdMaps(target,ctx),moveBefore(parentNode,target,after),target}function removeElementFromAncestorsIdMaps(element,ctx){let id=element.getAttribute("id");while(element=element.parentNode){let idSet=ctx.idMap.get(element);if(idSet){if(idSet.delete(id),!idSet.size)ctx.idMap.delete(element)}}}function moveBefore(parentNode,element,after){if(parentNode.moveBefore)try{parentNode.moveBefore(element,after)}catch(e){parentNode.insertBefore(element,after)}else parentNode.insertBefore(element,after)}return morphChildren2}(),morphNode=function(){function morphNode2(oldNode,newContent,ctx){if(ctx.ignoreActive&&oldNode===document.activeElement)return null;if(ctx.callbacks.beforeNodeMorphed(oldNode,newContent)===!1)return oldNode;if(oldNode instanceof HTMLHeadElement&&ctx.head.ignore);else if(oldNode instanceof HTMLHeadElement&&ctx.head.style!=="morph")handleHeadElement(oldNode,newContent,ctx);else if(morphAttributes(oldNode,newContent,ctx),!ignoreValueOfActiveElement(oldNode,ctx))morphChildren(ctx,oldNode,newContent);return ctx.callbacks.afterNodeMorphed(oldNode,newContent),oldNode}function morphAttributes(oldNode,newNode,ctx){let type=newNode.nodeType;if(type===1){let oldElt=oldNode,newElt=newNode,oldAttributes=oldElt.attributes,newAttributes=newElt.attributes;for(let newAttribute of newAttributes){if(ignoreAttribute(newAttribute.name,oldElt,"update",ctx))continue;if(oldElt.getAttribute(newAttribute.name)!==newAttribute.value)oldElt.setAttribute(newAttribute.name,newAttribute.value)}for(let i=oldAttributes.length-1;0<=i;i--){let oldAttribute=oldAttributes[i];if(!oldAttribute)continue;if(!newElt.hasAttribute(oldAttribute.name)){if(ignoreAttribute(oldAttribute.name,oldElt,"remove",ctx))continue;oldElt.removeAttribute(oldAttribute.name)}}if(!ignoreValueOfActiveElement(oldElt,ctx))syncInputValue(oldElt,newElt,ctx)}if(type===8||type===3){if(oldNode.nodeValue!==newNode.nodeValue)oldNode.nodeValue=newNode.nodeValue}}function syncInputValue(oldElement,newElement,ctx){if(oldElement instanceof HTMLInputElement&&newElement instanceof HTMLInputElement&&newElement.type!=="file"){let newValue=newElement.value,oldValue=oldElement.value;if(syncBooleanAttribute(oldElement,newElement,"checked",ctx),syncBooleanAttribute(oldElement,newElement,"disabled",ctx),!newElement.hasAttribute("value")){if(!ignoreAttribute("value",oldElement,"remove",ctx))oldElement.value="",oldElement.removeAttribute("value")}else if(oldValue!==newValue){if(!ignoreAttribute("value",oldElement,"update",ctx))oldElement.setAttribute("value",newValue),oldElement.value=newValue}}else if(oldElement instanceof HTMLOptionElement&&newElement instanceof HTMLOptionElement)syncBooleanAttribute(oldElement,newElement,"selected",ctx);else if(oldElement instanceof HTMLTextAreaElement&&newElement instanceof HTMLTextAreaElement){let newValue=newElement.value,oldValue=oldElement.value;if(ignoreAttribute("value",oldElement,"update",ctx))return;if(newValue!==oldValue)oldElement.value=newValue;if(oldElement.firstChild&&oldElement.firstChild.nodeValue!==newValue)oldElement.firstChild.nodeValue=newValue}}function syncBooleanAttribute(oldElement,newElement,attributeName,ctx){let newLiveValue=newElement[attributeName],oldLiveValue=oldElement[attributeName];if(newLiveValue!==oldLiveValue){let ignoreUpdate=ignoreAttribute(attributeName,oldElement,"update",ctx);if(!ignoreUpdate)oldElement[attributeName]=newElement[attributeName];if(newLiveValue){if(!ignoreUpdate)oldElement.setAttribute(attributeName,"")}else if(!ignoreAttribute(attributeName,oldElement,"remove",ctx))oldElement.removeAttribute(attributeName)}}function ignoreAttribute(attr,element,updateType,ctx){if(attr==="value"&&ctx.ignoreActiveValue&&element===document.activeElement)return!0;return ctx.callbacks.beforeAttributeUpdated(attr,element,updateType)===!1}function ignoreValueOfActiveElement(possibleActiveElement,ctx){return!!ctx.ignoreActiveValue&&possibleActiveElement===document.activeElement&&possibleActiveElement!==document.body}return morphNode2}();function withHeadBlocking(ctx,oldNode,newNode,callback){if(ctx.head.block){let oldHead=oldNode.querySelector("head"),newHead=newNode.querySelector("head");if(oldHead&&newHead){let promises=handleHeadElement(oldHead,newHead,ctx);return Promise.all(promises).then(()=>{let newCtx=Object.assign(ctx,{head:{block:!1,ignore:!0}});return callback(newCtx)})}}return callback(ctx)}function handleHeadElement(oldHead,newHead,ctx){let added=[],removed=[],preserved=[],nodesToAppend=[],srcToNewHeadNodes=new Map;for(let newHeadChild of newHead.children)srcToNewHeadNodes.set(newHeadChild.outerHTML,newHeadChild);for(let currentHeadElt of oldHead.children){let inNewContent=srcToNewHeadNodes.has(currentHeadElt.outerHTML),isReAppended=ctx.head.shouldReAppend(currentHeadElt),isPreserved=ctx.head.shouldPreserve(currentHeadElt);if(inNewContent||isPreserved)if(isReAppended)removed.push(currentHeadElt);else srcToNewHeadNodes.delete(currentHeadElt.outerHTML),preserved.push(currentHeadElt);else if(ctx.head.style==="append"){if(isReAppended)removed.push(currentHeadElt),nodesToAppend.push(currentHeadElt)}else if(ctx.head.shouldRemove(currentHeadElt)!==!1)removed.push(currentHeadElt)}nodesToAppend.push(...srcToNewHeadNodes.values());let promises=[];for(let newNode of nodesToAppend){let newElt=document.createRange().createContextualFragment(newNode.outerHTML).firstChild;if(ctx.callbacks.beforeNodeAdded(newElt)!==!1){if("href"in newElt&&newElt.href||"src"in newElt&&newElt.src){let resolve,promise=new Promise(function(_resolve){resolve=_resolve});newElt.addEventListener("load",function(){resolve()}),promises.push(promise)}oldHead.appendChild(newElt),ctx.callbacks.afterNodeAdded(newElt),added.push(newElt)}}for(let removedElement of removed)if(ctx.callbacks.beforeNodeRemoved(removedElement)!==!1)oldHead.removeChild(removedElement),ctx.callbacks.afterNodeRemoved(removedElement);return ctx.head.afterHeadMorphed(oldHead,{added,kept:preserved,removed}),promises}let createMorphContext=function(){function createMorphContext2(oldNode,newContent,config){let{persistentIds,idMap}=createIdMaps(oldNode,newContent),mergedConfig=mergeDefaults(config),morphStyle=mergedConfig.morphStyle||"outerHTML";if(!["innerHTML","outerHTML"].includes(morphStyle))throw`Do not understand how to morph style ${morphStyle}`;return{target:oldNode,newContent,config:mergedConfig,morphStyle,ignoreActive:mergedConfig.ignoreActive,ignoreActiveValue:mergedConfig.ignoreActiveValue,restoreFocus:mergedConfig.restoreFocus,idMap,persistentIds,pantry:createPantry(),activeElementAndParents:createActiveElementAndParents(oldNode),callbacks:mergedConfig.callbacks,head:mergedConfig.head}}function mergeDefaults(config){let finalConfig=Object.assign({},defaults);return Object.assign(finalConfig,config),finalConfig.callbacks=Object.assign({},defaults.callbacks,config.callbacks),finalConfig.head=Object.assign({},defaults.head,config.head),finalConfig}function createPantry(){let pantry=document.createElement("div");return pantry.hidden=!0,document.body.insertAdjacentElement("afterend",pantry),pantry}function createActiveElementAndParents(oldNode){let activeElementAndParents=[],elt=document.activeElement;if(elt?.tagName!=="BODY"&&oldNode.contains(elt))while(elt){if(activeElementAndParents.push(elt),elt===oldNode)break;elt=elt.parentElement}return activeElementAndParents}function findIdElements(root){let elements=Array.from(root.querySelectorAll("[id]"));if(root.getAttribute?.("id"))elements.push(root);return elements}function populateIdMapWithTree(idMap,persistentIds,root,elements){for(let elt of elements){let id=elt.getAttribute("id");if(persistentIds.has(id)){let current2=elt;while(current2){let idSet=idMap.get(current2);if(idSet==null)idSet=new Set,idMap.set(current2,idSet);if(idSet.add(id),current2===root)break;current2=current2.parentElement}}}}function createIdMaps(oldContent,newContent){let oldIdElements=findIdElements(oldContent),newIdElements=findIdElements(newContent),persistentIds=createPersistentIds(oldIdElements,newIdElements),idMap=new Map;populateIdMapWithTree(idMap,persistentIds,oldContent,oldIdElements);let newRoot=newContent.__idiomorphRoot||newContent;return populateIdMapWithTree(idMap,persistentIds,newRoot,newIdElements),{persistentIds,idMap}}function createPersistentIds(oldIdElements,newIdElements){let duplicateIds=new Set,oldIdTagNameMap=new Map;for(let{id,tagName}of oldIdElements)if(oldIdTagNameMap.has(id))duplicateIds.add(id);else oldIdTagNameMap.set(id,tagName);let persistentIds=new Set;for(let{id,tagName}of newIdElements)if(persistentIds.has(id))duplicateIds.add(id);else if(oldIdTagNameMap.get(id)===tagName)persistentIds.add(id);for(let id of duplicateIds)persistentIds.delete(id);return persistentIds}return createMorphContext2}(),{normalizeElement,normalizeParent}=function(){let generatedByIdiomorph=new WeakSet;function normalizeElement2(content){if(content instanceof Document)return content.documentElement;else return content}function normalizeParent2(newContent){if(newContent==null)return document.createElement("div");else if(typeof newContent==="string")return normalizeParent2(parseContent(newContent));else if(generatedByIdiomorph.has(newContent))return newContent;else if(newContent instanceof Node)if(newContent.parentNode)return new SlicedParentNode(newContent);else{let dummyParent=document.createElement("div");return dummyParent.append(newContent),dummyParent}else{let dummyParent=document.createElement("div");for(let elt of[...newContent])dummyParent.append(elt);return dummyParent}}class SlicedParentNode{constructor(node){this.originalNode=node,this.realParentNode=node.parentNode,this.previousSibling=node.previousSibling,this.nextSibling=node.nextSibling}get childNodes(){let nodes=[],cursor2=this.previousSibling?this.previousSibling.nextSibling:this.realParentNode.firstChild;while(cursor2&&cursor2!=this.nextSibling)nodes.push(cursor2),cursor2=cursor2.nextSibling;return nodes}querySelectorAll(selector){return this.childNodes.reduce((results,node)=>{if(node instanceof Element){if(node.matches(selector))results.push(node);let nodeList=node.querySelectorAll(selector);for(let i=0;i<nodeList.length;i++)results.push(nodeList[i])}return results},[])}insertBefore(node,referenceNode){return this.realParentNode.insertBefore(node,referenceNode)}moveBefore(node,referenceNode){return this.realParentNode.moveBefore(node,referenceNode)}get __idiomorphRoot(){return this.originalNode}}function parseContent(newContent){let parser=new DOMParser,contentWithSvgsRemoved=newContent.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(contentWithSvgsRemoved.match(/<\/html>/)||contentWithSvgsRemoved.match(/<\/head>/)||contentWithSvgsRemoved.match(/<\/body>/)){let content=parser.parseFromString(newContent,"text/html");if(contentWithSvgsRemoved.match(/<\/html>/))return generatedByIdiomorph.add(content),content;else{let htmlElement=content.firstChild;if(htmlElement)generatedByIdiomorph.add(htmlElement);return htmlElement}}else{let content=parser.parseFromString("<body><template>"+newContent+"</template></body>","text/html").body.querySelector("template").content;return generatedByIdiomorph.add(content),content}}return{normalizeElement:normalizeElement2,normalizeParent:normalizeParent2}}();return{morph,defaults}}();var listeners2=[];function onRefresh(listener){listeners2.push(listener)}function permanent(node){return node instanceof Element&&(node.hasAttribute("data-turbo-permanent")||node.hasAttribute("data-tensaku-permanent")||node.hasAttribute("data-tensaku-ui"))}function herbDevServer(){return Boolean(document.querySelector('meta[name="herb-dev-server-port"]'))}function replaceText(nodes,from,to){let normal=(text)=>text.replace(/\s+/g," ").trim(),target=normal(from);if(!target)return;for(let node of nodes)if(normal(node.data)===target){let lead=node.data.match(/^\s*/)[0],trail=node.data.match(/\s*$/)[0];node.data=lead+to.trim()+trail}else if(node.data.includes(from)&&from.trim())node.data=node.data.replace(from,to)}async function refresh(kind){if(meta().method!=="GET"){toast("Saved. This page came from a form submission, so reload to check it.",{timeout:7000});return}if(kind==="template"&&herbDevServer())return;try{let response=await fetch(location.href,{headers:{Accept:"text/html","X-Tensaku-Refresh":"1"},credentials:"same-origin"});if(!response.ok)throw Error(`HTTP ${response.status}`);let html=await response.text(),next=new DOMParser().parseFromString(html,"text/html");morph(next)}catch(error){toast(`Saved, but refreshing the page failed (${error.message}). Reload to check.`,{error:!0})}}var agentFetch=0;async function refreshAfterAgent(){if(meta().method!=="GET")return;let sequence=++agentFetch;try{let response=await fetch(location.href,{headers:{Accept:"text/html","X-Tensaku-Refresh":"1"},credentials:"same-origin"});if(!response.ok)return;let html=await response.text();if(sequence!==agentFetch)return;let next=new DOMParser().parseFromString(html,"text/html");swapStylesheets(next),morph(next)}catch{}}function swapStylesheets(next){let wanted=new Set(((doc)=>Array.from(doc.querySelectorAll('head link[rel="stylesheet"]')).map((link)=>link.getAttribute("href")))(next)),current2=Array.from(document.querySelectorAll('head link[rel="stylesheet"]')),have=new Set(current2.map((link)=>link.getAttribute("href"))),added=Array.from(next.querySelectorAll('head link[rel="stylesheet"]')).filter((link)=>!have.has(link.getAttribute("href")));if(!added.length)return;let stale=current2.filter((link)=>!wanted.has(link.getAttribute("href"))),waiting=added.length;for(let link of added){let copy2=document.importNode(link,!0),done=()=>{if(--waiting===0)stale.forEach((old)=>old.remove())};copy2.addEventListener("load",done),copy2.addEventListener("error",done),document.head.append(copy2)}}function changedByUser(element){if(element instanceof HTMLInputElement){if(element.type==="checkbox"||element.type==="radio")return element.checked!==element.defaultChecked;return element.type!=="file"&&element.value!==element.defaultValue}if(element instanceof HTMLTextAreaElement)return element.value!==element.defaultValue;if(element instanceof HTMLOptionElement)return element.selected!==element.defaultSelected;if(element instanceof HTMLSelectElement)return Array.from(element.options).some((option)=>option.selected!==option.defaultSelected);return!1}var FORM_STATE=new Set(["value","checked","selected"]);function morph(next){let lazyFrames=Array.from(document.querySelectorAll("turbo-frame[src]"));if(Idiomorph.morph(document.body,next.body,{morphStyle:"outerHTML",ignoreActiveValue:!0,restoreFocus:!0,callbacks:{beforeNodeMorphed:(oldNode)=>!permanent(oldNode)&&!(oldNode instanceof HTMLTextAreaElement&&changedByUser(oldNode)),beforeAttributeUpdated:(name,element)=>!(FORM_STATE.has(name)&&changedByUser(element)),beforeNodeRemoved:(node)=>!permanent(node)}}),next.title)document.title=next.title;for(let frame of lazyFrames)if(frame.isConnected&&typeof frame.reload==="function"&&!frame.hasAttribute("complete"))frame.reload();listeners2.forEach((listener)=>listener())}var notes=[],scoped=[],scope=null,openCount=0,agents=[],currentNotes=()=>notes,scopedNotes=()=>scoped,currentAgents=()=>agents,openNotes=()=>openCount,agentLabel=(agent)=>agent.handle?`${agent.name} · ${agent.handle}`:agent.name,listeners3=()=>agents.filter((agent)=>agent.listening).map(agentLabel),closed=(note)=>note.status==="resolved"||note.status==="declined",renderListeners=[],countListeners=[],agentListeners=[],changeListeners=[],onRender=(listener)=>renderListeners.push(listener),onCount=(listener)=>countListeners.push(listener),onAgents=(listener)=>agentListeners.push(listener),onChanges=(listener)=>changeListeners.push(listener),normalized=(list)=>list.map((note)=>({...note,targets:note.targets??[]})),lastSignature="",loadSequence=0,tokenWarned=!1,restartWarned=!1,agentChangedAt,primed=!1;async function load({force=!1}={}){let sequence=++loadSequence,first=!1;try{let data=await api("GET","/notes"+query({url:location.pathname}));if(sequence!==loadSequence)return;if(tokenWarned=!1,primed&&data.changed_at&&data.changed_at!==agentChangedAt)refreshAfterAgent();if(agentChangedAt=data.changed_at,data.restart&&!restartWarned)restartWarned=!0,toast("Tensaku's code changed since this dev server started, so the page runs a newer overlay than the server. Restart the dev server.",{error:!0,timeout:20000});data.notes=data.notes.filter((note)=>!pendingDeletes.has(note.id)),agents=data.agents??[],agentListeners.forEach((listener)=>listener(agents));let signature=location.pathname+JSON.stringify([data.notes,data.open,listeners3()]);if(!force&&signature===lastSignature)return;lastSignature=signature;let after=normalized(data.notes);if(primed&&data.notes.length&¬es.length)changeListeners.forEach((listener)=>listener(notes,after));if(first=!primed,primed=!0,notes=after,openCount=data.open,scope&&scope!=="page"){let all=await scopeNotes(scope);if(sequence!==loadSequence)return;scoped=all}}catch(error){if(sequence!==loadSequence)return;if(error instanceof ApiError&&error.status===403&&!tokenWarned)tokenWarned=!0,toast(`${error.message} Notes can't be loaded until then.`,{error:!0,timeout:15000,actions:{Reload:()=>location.reload()}});return}countListeners.forEach((listener)=>listener(openCount)),render({force,first})}function render(what){renderListeners.forEach((listener)=>listener(what))}var scopeNotes=async(which)=>normalized((await api("GET","/notes"+(which==="archived"?query({archived:"1"}):""))).notes).filter((note)=>!pendingDeletes.has(note.id));async function setScope(which){if(scope=which,which&&which!=="page")scoped=await scopeNotes(which)}var streaming=!1;function poll(){let pending=0,changed=()=>{clearTimeout(pending),pending=window.setTimeout(()=>load(),30)},editedPending=0,edited=()=>{clearTimeout(editedPending),editedPending=window.setTimeout(refreshAfterAgent,150)},connect=async()=>{let retry=5000;try{let{token,root}=meta(),response=await fetch(root+"/events",{headers:{"X-Tensaku-Token":token,Accept:"text/event-stream"},credentials:"same-origin"});if(response.status===501)return;if(!response.ok||!response.body)throw Error(`events ${response.status}`);streaming=!0;let reader=response.body.pipeThrough(new TextDecoderStream).getReader(),buffer="";for(;;){let{value,done}=await reader.read();if(done)break;buffer+=value;let events=buffer.split(`
|
|
261
354
|
|
|
262
|
-
/* The pencil case (ART_STYLE.md). Tensaku keeps one look on every host page: a dark tray for the
|
|
263
|
-
|
|
264
|
-
:
|
|
265
|
-
|
|
266
|
-
--paper: #fffdf6; --ink: #24201b; --muted: #6f675a; --line: #e4ddcd;
|
|
267
|
-
--akaji: #e0344f; --akaji-soft: rgba(224, 52, 79, .12);
|
|
268
|
-
--marker: #ffe14d; --marker-edge: #d9a900; --marker-soft: rgba(255, 225, 77, .26);
|
|
269
|
-
--question: #4c7df0; --resolved: #2fa872;
|
|
270
|
-
--postit: #fff1a1; --postit-edge: #ecd66a; --postit-question: #ffdbe3; --postit-question-edge: #f1b3c2; --postit-resolved: #d3f1df; --postit-resolved-edge: #9fd8b8;
|
|
271
|
-
--sans: ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;
|
|
272
|
-
--mono: ui-monospace, SFMono-Regular, Menlo, monospace;
|
|
273
|
-
--spring: cubic-bezier(.34, 1.56, .64, 1);
|
|
355
|
+
`);if(buffer=events.pop()??"",events.includes("data: changed"))changed();if(events.includes("data: edited"))edited()}}catch{retry=15000}streaming=!1,setTimeout(connect,retry)},tick=async()=>{if(!streaming&&(document.visibilityState==="visible"||settings().notify))await load();setTimeout(tick,document.visibilityState==="visible"?4000:16000)};connect(),setTimeout(tick,4000)}var localChanges=new Set,changedHere=(id)=>localChanges.delete(id);function replace(note,removed=!1){let swap=(list)=>removed?list.filter((other)=>other.id!==note.id):list.map((other)=>other.id===note.id?note:other);notes=swap(notes),scoped=swap(scoped),lastSignature="",render({force:!0,changed:removed?void 0:note})}function predicted(note,change){let next={...note,thread:[...note.thread??[]]};if(change.comment)next.comment=change.comment;if(change.message)next.thread.push({from:"you",text:change.message,at:new Date().toISOString()});if(change.status)next.status=change.status;if(change.to!==void 0){let chosen=agents.find((agent)=>agent.handle===change.to);Object.assign(next,{status:"open",agent:chosen?agentLabel(chosen):void 0,delivered_at:void 0,delivered_to:void 0,stopped:void 0})}if(next.status==="open"&&(change.comment||change.message||change.to!==void 0))next.sent_at=new Date().toISOString();return next}async function updateNote(note,change,onChange=()=>{}){let after=predicted(note,change);localChanges.add(note.id),replace(after),onChange(after);try{return await api("PATCH",`/notes/${note.id}`,change),load({force:!0}),!0}catch(error){return localChanges.delete(note.id),replace(note),onChange(note),toast(error.message,{error:!0}),!1}}var pendingDeletes=new Map;addEventListener("pagehide",()=>pendingDeletes.forEach((commit)=>commit()));function deleteLater(note){replace(note,!0);let done=!1,commit=()=>{if(done)return;done=!0,pendingDeletes.delete(note.id),api("DELETE",`/notes/${note.id}`).catch((error)=>toast(error.message,{error:!0})).finally(()=>load({force:!0}))};pendingDeletes.set(note.id,commit);let timer=setTimeout(commit,6000);toast("Note deleted",{timeout:6000,actions:{Undo:()=>{done=!0,clearTimeout(timer),pendingDeletes.delete(note.id),load({force:!0})}}})}async function deleteNotes(list){try{for(let note of list)await api("DELETE",`/notes/${note.id}`)}finally{await load({force:!0})}}var PREFIX="[modern-screenshot]",IN_BROWSER=typeof window<"u",SUPPORT_WEB_WORKER=IN_BROWSER&&"Worker"in window,SUPPORT_ATOB=IN_BROWSER&&"atob"in window,SUPPORT_BTOA=IN_BROWSER&&"btoa"in window,USER_AGENT=IN_BROWSER?window.navigator?.userAgent:"",IN_CHROME=USER_AGENT.includes("Chrome"),IN_SAFARI=USER_AGENT.includes("AppleWebKit")&&!IN_CHROME,IN_FIREFOX=USER_AGENT.includes("Firefox"),isContext=(value)=>value&&("__CONTEXT__"in value),isCssFontFaceRule=(rule)=>rule.constructor.name==="CSSFontFaceRule",isCSSImportRule=(rule)=>rule.constructor.name==="CSSImportRule",isLayerBlockRule=(rule)=>rule.constructor.name==="CSSLayerBlockRule",isElementNode=(node)=>node.nodeType===1,isSVGElementNode=(node)=>typeof node.className==="object",isSVGImageElementNode=(node)=>node.tagName==="image",isSVGUseElementNode=(node)=>node.tagName==="use",isHTMLElementNode=(node)=>isElementNode(node)&&typeof node.style<"u"&&!isSVGElementNode(node),isCommentNode=(node)=>node.nodeType===8,isTextNode=(node)=>node.nodeType===3,isImageElement=(node)=>node.tagName==="IMG",isVideoElement=(node)=>node.tagName==="VIDEO",isCanvasElement=(node)=>node.tagName==="CANVAS",isTextareaElement=(node)=>node.tagName==="TEXTAREA",isInputElement=(node)=>node.tagName==="INPUT",isStyleElement=(node)=>node.tagName==="STYLE",isScriptElement=(node)=>node.tagName==="SCRIPT",isSelectElement=(node)=>node.tagName==="SELECT",isSlotElement=(node)=>node.tagName==="SLOT",isIFrameElement=(node)=>node.tagName==="IFRAME",consoleWarn=(...args)=>console.warn(PREFIX,...args);function supportWebp(ownerDocument){let canvas=ownerDocument?.createElement?.("canvas");if(canvas)canvas.height=canvas.width=1;return Boolean(canvas)&&"toDataURL"in canvas&&Boolean(canvas.toDataURL("image/webp").includes("image/webp"))}var isDataUrl=(url)=>url.startsWith("data:");function resolveUrl(url,baseUrl){if(url.match(/^[a-z]+:\/\//i))return url;if(IN_BROWSER&&url.match(/^\/\//))return window.location.protocol+url;if(url.match(/^[a-z]+:/i))return url;if(!IN_BROWSER)return url;let doc=getDocument().implementation.createHTMLDocument(),base=doc.createElement("base"),a=doc.createElement("a");if(doc.head.appendChild(base),doc.body.appendChild(a),baseUrl)base.href=baseUrl;return a.href=url,a.href}function getDocument(target){return(target&&isElementNode(target)?target?.ownerDocument:target)??window.document}var XMLNS="http://www.w3.org/2000/svg";function createSvg(width,height,ownerDocument){let svg=getDocument(ownerDocument).createElementNS(XMLNS,"svg");return svg.setAttributeNS(null,"width",width.toString()),svg.setAttributeNS(null,"height",height.toString()),svg.setAttributeNS(null,"viewBox",`0 0 ${width} ${height}`),svg}function svgToDataUrl(svg,removeControlCharacter){let xhtml=new XMLSerializer().serializeToString(svg);if(removeControlCharacter)xhtml=xhtml.replace(/[\u0000-\u0008\v\f\u000E-\u001F\uD800-\uDFFF\uFFFE\uFFFF]/gu,"");return`data:image/svg+xml;charset=utf-8,${encodeURIComponent(xhtml)}`}function readBlob(blob,type){return new Promise((resolve,reject)=>{let reader=new FileReader;if(reader.onload=()=>resolve(reader.result),reader.onerror=()=>reject(reader.error),reader.onabort=()=>reject(Error(`Failed read blob to ${type}`)),type==="dataUrl")reader.readAsDataURL(blob);else if(type==="arrayBuffer")reader.readAsArrayBuffer(blob)})}var blobToDataUrl=(blob)=>readBlob(blob,"dataUrl");function createImage(url,ownerDocument){let img=getDocument(ownerDocument).createElement("img");return img.decoding="sync",img.loading="eager",img.src=url,img}function loadMedia(media,options){return new Promise((resolve)=>{let{timeout,ownerDocument,onError:userOnError,onWarn}=options??{},node=typeof media==="string"?createImage(media,getDocument(ownerDocument)):media,timer=null,removeEventListeners=null;function onResolve(){resolve(node),timer&&clearTimeout(timer),removeEventListeners?.()}if(timeout)timer=setTimeout(onResolve,timeout);if(isVideoElement(node)){let currentSrc=node.currentSrc||node.src;if(!currentSrc){if(node.poster)return loadMedia(node.poster,options).then(resolve);return onResolve()}if(node.readyState>=2)return onResolve();let onLoadeddata=onResolve,onError=(error)=>{onWarn?.("Failed video load",currentSrc,error),userOnError?.(error),onResolve()};removeEventListeners=()=>{node.removeEventListener("loadeddata",onLoadeddata),node.removeEventListener("error",onError)},node.addEventListener("loadeddata",onLoadeddata,{once:!0}),node.addEventListener("error",onError,{once:!0})}else{let currentSrc=isSVGImageElementNode(node)?node.href.baseVal:node.currentSrc||node.src;if(!currentSrc)return onResolve();let onLoad=async()=>{if(isImageElement(node)&&"decode"in node)try{await node.decode()}catch(error){onWarn?.("Failed to decode image, trying to render anyway",node.dataset.originalSrc||currentSrc,error)}onResolve()},onError=(error)=>{onWarn?.("Failed image load",node.dataset.originalSrc||currentSrc,error),onResolve()};if(isImageElement(node)&&node.complete)return onLoad();removeEventListeners=()=>{node.removeEventListener("load",onLoad),node.removeEventListener("error",onError)},node.addEventListener("load",onLoad,{once:!0}),node.addEventListener("error",onError,{once:!0})}})}async function waitUntilLoad(node,options){if(isHTMLElementNode(node))if(isImageElement(node)||isVideoElement(node))await loadMedia(node,options);else await Promise.all(["img","video"].flatMap((selectors)=>{return Array.from(node.querySelectorAll(selectors)).map((el)=>loadMedia(el,options))}))}var uuid=function(){let counter=0,random=()=>`0000${(Math.random()*1679616<<0).toString(36)}`.slice(-4);return()=>{return counter+=1,`u${random()}${counter}`}}();function splitFontFamily(fontFamily){return fontFamily?.split(",").map((val)=>val.trim().replace(/"|'/g,"").toLowerCase()).filter(Boolean)}var uid=0;function createLogger(debug){let prefix=`${PREFIX}[#${uid}]`;return uid++,{time:(label)=>debug&&console.time(`${prefix} ${label}`),timeEnd:(label)=>debug&&console.timeEnd(`${prefix} ${label}`),warn:(...args)=>debug&&consoleWarn(...args)}}function getDefaultRequestInit(bypassingCache){return{cache:bypassingCache?"no-cache":"force-cache"}}async function orCreateContext(node,options){return isContext(node)?node:createContext(node,{...options,autoDestruct:!0})}async function createContext(node,options){let{scale=1,workerUrl,workerNumber=1}=options||{},debug=Boolean(options?.debug),features=options?.features??!0,ownerDocument=node.ownerDocument??(IN_BROWSER?window.document:void 0),ownerWindow=node.ownerDocument?.defaultView??(IN_BROWSER?window:void 0),requests=new Map,context={width:0,height:0,quality:1,type:"image/png",scale,backgroundColor:null,style:null,filter:null,maximumCanvasSize:0,timeout:30000,progress:null,debug,fetch:{requestInit:getDefaultRequestInit(options?.fetch?.bypassingCache),placeholderImage:"data:image/png;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7",bypassingCache:!1,...options?.fetch},fetchFn:null,font:{},drawImageInterval:100,workerUrl:null,workerNumber,onCloneEachNode:null,onCloneNode:null,onEmbedNode:null,onCreateForeignObjectSvg:null,includeStyleProperties:null,autoDestruct:!1,...options,__CONTEXT__:!0,log:createLogger(debug),node,ownerDocument,ownerWindow,dpi:scale===1?null:96*scale,svgStyleElement:createStyleElement(ownerDocument),svgDefsElement:ownerDocument?.createElementNS(XMLNS,"defs"),svgStyles:new Map,defaultComputedStyles:new Map,workers:[...Array.from({length:SUPPORT_WEB_WORKER&&workerUrl&&workerNumber?workerNumber:0})].map(()=>{try{let worker=new Worker(workerUrl);return worker.onmessage=async(event)=>{let{url,result}=event.data;if(result)requests.get(url)?.resolve?.(result);else requests.get(url)?.reject?.(Error(`Error receiving message from worker: ${url}`))},worker.onmessageerror=(event)=>{let{url}=event.data;requests.get(url)?.reject?.(Error(`Error receiving message from worker: ${url}`))},worker}catch(error){return context.log.warn("Failed to new Worker",error),null}}).filter(Boolean),fontFamilies:new Map,fontCssTexts:new Map,acceptOfImage:`${[supportWebp(ownerDocument)&&"image/webp","image/svg+xml","image/*","*/*"].filter(Boolean).join(",")};q=0.8`,requests,drawImageCount:0,tasks:[],features,isEnable:(key)=>{if(key==="restoreScrollPosition")return typeof features==="boolean"?!1:features[key]??!1;if(typeof features==="boolean")return features;return features[key]??!0},shadowRoots:[]};context.log.time("wait until load"),await waitUntilLoad(node,{timeout:context.timeout,onWarn:context.log.warn}),context.log.timeEnd("wait until load");let{width,height}=resolveBoundingBox(node,context);return context.width=width,context.height=height,context}function createStyleElement(ownerDocument){if(!ownerDocument)return;let style=ownerDocument.createElement("style"),cssText=style.ownerDocument.createTextNode(`
|
|
356
|
+
.______background-clip--text {
|
|
357
|
+
background-clip: text;
|
|
358
|
+
-webkit-background-clip: text;
|
|
274
359
|
}
|
|
275
|
-
.
|
|
276
|
-
.fixed { position: fixed; inset: 0; pointer-events: none; z-index: 2147483001; font: 13px/1.45 var(--sans); color: var(--ink); }
|
|
277
|
-
.
|
|
278
|
-
|
|
279
|
-
.
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
button { font: inherit; color: inherit; background: none; border: 1px solid var(--line); border-radius: 8px; padding: 4px 10px; cursor: pointer; transition: background-color .12s, border-color .12s, transform .16s var(--spring); }
|
|
284
|
-
button:hover { border-color: var(--ink); }
|
|
285
|
-
button:focus-visible { outline: 2px solid var(--question); outline-offset: 2px; }
|
|
286
|
-
button.primary { background: var(--tray); color: var(--tray-ink); border-color: var(--tray); font-weight: 600; }
|
|
287
|
-
button.primary:hover { background: #000; }
|
|
288
|
-
button.primary:disabled { opacity: .4; cursor: default; }
|
|
289
|
-
button.link { border: none; padding: 0; text-decoration: underline; color: var(--muted); }
|
|
290
|
-
button.quiet { border-color: transparent; color: var(--muted); }
|
|
291
|
-
button.quiet:hover { color: var(--ink); border-color: transparent; background: rgba(0, 0, 0, .06); }
|
|
292
|
-
button.icon-button { display: inline-grid; place-items: center; width: 28px; height: 28px; padding: 0; border: none; border-radius: 7px; color: var(--muted); }
|
|
293
|
-
button.icon-button:hover { background: rgba(0, 0, 0, .08); color: var(--ink); }
|
|
294
|
-
button.icon-button .icon { width: 17px; height: 17px; }
|
|
295
|
-
textarea, input { font: inherit; color: var(--ink); background: var(--paper); border: 1px solid var(--line); border-radius: 8px; padding: 7px 9px; width: 100%; resize: vertical; }
|
|
296
|
-
textarea:focus, input:focus { outline: 2px solid var(--question); outline-offset: -1px; }
|
|
297
|
-
kbd { font: 10.5px/1 var(--mono); padding: 2px 4px; border-radius: 4px; background: rgba(255, 255, 255, .12); color: inherit; opacity: .8; }
|
|
298
|
-
|
|
299
|
-
/* Marks on the page: highlighter for annotating, red pen for editing. */
|
|
300
|
-
.box { position: absolute; pointer-events: none; border: 1.5px solid var(--marker-edge); background: var(--marker-soft); border-radius: 4px; }
|
|
301
|
-
.box.edit { border: 1.5px dashed var(--akaji); background: transparent; }
|
|
302
|
-
.box.hover-edit { border: 1.5px solid var(--akaji); background: var(--akaji-soft); }
|
|
303
|
-
.box.selected { border-width: 2px; }
|
|
304
|
-
.label { position: absolute; transform: translateY(calc(-100% - 4px)); display: flex; gap: 6px; align-items: baseline; background: var(--tray); color: var(--tray-ink); font: 600 11px/1.3 var(--sans); padding: 3px 8px; border-radius: 6px; white-space: nowrap; pointer-events: none; max-width: 560px; overflow: hidden; text-overflow: ellipsis; box-shadow: 0 4px 12px rgba(0, 0, 0, .25); }
|
|
305
|
-
.label .where { font: 400 11px/1.3 var(--mono); color: var(--tray-muted); }
|
|
306
|
-
.area { position: absolute; border: 2px dashed var(--marker-edge); background: var(--marker-soft); border-radius: 4px; pointer-events: none; }
|
|
307
|
-
|
|
308
|
-
.panel { position: absolute; background: var(--paper); border: 1px solid var(--line); border-radius: 12px; box-shadow: 0 18px 40px -12px rgba(0, 0, 0, .35), 0 2px 6px rgba(0, 0, 0, .1); padding: 10px; min-width: 260px; max-width: 460px; }
|
|
309
|
-
.panel h3 { margin: 0 0 6px; font-size: 12px; font-weight: 600; color: var(--muted); }
|
|
310
|
-
.panel .row { display: flex; gap: 6px; align-items: center; flex-wrap: wrap; margin-top: 8px; }
|
|
311
|
-
.panel .row.end { justify-content: flex-end; }
|
|
312
|
-
.panel .meta { font: 11px/1.4 var(--mono); color: var(--muted); word-break: break-all; }
|
|
313
|
-
.panel .warn { font-size: 12px; color: var(--akaji); margin-top: 6px; }
|
|
314
|
-
|
|
315
|
-
/* Post-it paper: the note form, note cards and the notes panel's cards. The folded corner sits at the
|
|
316
|
-
bottom right; text and fields stay aligned to the square edges. */
|
|
317
|
-
.postit { position: relative; background: var(--postit); border: 1px solid var(--postit-edge); border-radius: 3px 3px 16px 3px; color: var(--ink); }
|
|
318
|
-
.postit::after { content: ""; position: absolute; right: -1px; bottom: -1px; width: 18px; height: 18px; border-radius: 0 0 16px 0; background: linear-gradient(135deg, rgba(0, 0, 0, .12) 0 50%, transparent 50%); pointer-events: none; }
|
|
319
|
-
.postit.question { background: var(--postit-question); border-color: var(--postit-question-edge); }
|
|
320
|
-
.postit.resolved { background: var(--postit-resolved); border-color: var(--postit-resolved-edge); }
|
|
321
|
-
.postit textarea { background: rgba(255, 255, 255, .6); border-color: var(--postit-edge); }
|
|
322
|
-
.postit button:not(.primary):not(.icon-button) { border-color: rgba(0, 0, 0, .16); background: rgba(255, 255, 255, .45); }
|
|
323
|
-
.postit button:not(.primary):not(.icon-button):hover { background: rgba(255, 255, 255, .8); border-color: rgba(0, 0, 0, .35); }
|
|
324
|
-
|
|
325
|
-
.note-form { width: 320px; max-width: calc(100vw - 16px); padding: 10px 12px 12px; box-shadow: 0 18px 40px -14px rgba(0, 0, 0, .45), 0 2px 6px rgba(0, 0, 0, .12); animation: settle .22s var(--spring); }
|
|
326
|
-
.note-form .head { display: flex; gap: 6px; align-items: center; margin-bottom: 8px; }
|
|
327
|
-
.note-form .head .what { flex: 1; min-width: 0; }
|
|
328
|
-
.note-form .head .title { font-weight: 600; font-size: 12px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
|
329
|
-
.note-form .head .where { font: 11px/1.3 var(--mono); color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
|
330
|
-
.note-form .head .tools { display: flex; gap: 1px; }
|
|
331
|
-
.note-form .foot { display: flex; gap: 6px; align-items: center; margin-top: 8px; }
|
|
332
|
-
.note-form .foot .hint { flex: 1; font-size: 11px; color: var(--muted); }
|
|
333
|
-
|
|
334
|
-
.note-pop { padding: 0; background: none; border: none; box-shadow: none; min-width: 280px; }
|
|
335
|
-
.note-pop .note-card { box-shadow: 0 18px 40px -14px rgba(0, 0, 0, .45); animation: settle .2s var(--spring); }
|
|
336
|
-
.note-card { padding: 12px 14px 14px; }
|
|
337
|
-
.note-card .comment { white-space: pre-wrap; margin-top: 6px; }
|
|
338
|
-
.note-card .reply { margin-top: 8px; padding: 6px 9px; border-left: 3px solid var(--resolved); background: rgba(255, 255, 255, .55); border-radius: 0 6px 6px 0; white-space: pre-wrap; }
|
|
339
|
-
.note-card .reply.question { border-color: var(--question); }
|
|
340
|
-
.note-card .row { display: flex; gap: 6px; align-items: center; flex-wrap: wrap; margin-top: 10px; }
|
|
341
|
-
.note-card .row:first-child { margin-top: 0; }
|
|
342
|
-
.note-card .meta { font: 11px/1.4 var(--mono); color: var(--muted); word-break: break-all; }
|
|
343
|
-
.note-card textarea { margin-top: 8px; }
|
|
344
|
-
.status { display: inline-flex; align-items: center; gap: 4px; font: 700 10px/1 var(--sans); text-transform: uppercase; letter-spacing: .05em; padding: 3px 6px; border-radius: 999px; background: rgba(0, 0, 0, .08); color: var(--ink); }
|
|
345
|
-
.status.question { color: var(--question); }
|
|
346
|
-
.status.resolved { color: var(--resolved); }
|
|
347
|
-
.status .icon { width: 13px; height: 13px; stroke-width: 2.4; }
|
|
348
|
-
|
|
349
|
-
.panel.menu { background: var(--tray); color: var(--tray-ink); border-color: var(--tray-line); padding: 6px; min-width: 240px; animation: settle .16s var(--spring); }
|
|
350
|
-
.menu { display: flex; flex-direction: column; gap: 1px; }
|
|
351
|
-
.menu h3 { display: flex; flex-direction: column; gap: 2px; margin: 2px 6px 6px; color: var(--tray-ink); font-size: 12px; }
|
|
352
|
-
.menu h3 .where { font: 400 11px/1.3 var(--mono); color: var(--tray-muted); word-break: break-all; }
|
|
353
|
-
.menu button { display: flex; gap: 10px; align-items: center; width: 100%; text-align: left; border: none; border-radius: 7px; padding: 7px 8px; color: var(--tray-ink); }
|
|
354
|
-
.menu button span { flex: 1; }
|
|
355
|
-
.menu button .icon { width: 17px; height: 17px; color: var(--tray-muted); }
|
|
356
|
-
.menu button:hover, .menu button:focus-visible { background: var(--tray-raised); outline: none; }
|
|
357
|
-
.menu button:hover .icon, .menu button:focus-visible .icon { color: var(--tray-ink); }
|
|
358
|
-
|
|
359
|
-
/* The inline editor: the page's own background, colour and type, outlined by the red pen. Lines and
|
|
360
|
-
muted text derive from the page's text colour, so it reads on light and dark pages. */
|
|
361
|
-
.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); }
|
|
362
|
-
.editor .surface { padding: 8px 10px; white-space: pre-wrap; outline: none; min-height: 1.4em; max-height: 60vh; overflow: auto; caret-color: var(--akaji); }
|
|
363
|
-
.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); }
|
|
364
|
-
.editor .bar .actions { display: flex; gap: 4px; }
|
|
365
|
-
.editor .bar button { font: 600 12px/1.2 var(--sans); padding: 5px 12px; border-radius: 999px; border-color: transparent; color: var(--tray-ink); }
|
|
366
|
-
.editor .bar button:hover { background: var(--tray-raised); border-color: transparent; }
|
|
367
|
-
.editor .bar button.primary { background: var(--akaji); border-color: var(--akaji); color: #fff; }
|
|
368
|
-
.editor .bar button.primary:hover { background: #c41e3a; }
|
|
369
|
-
.editor .bar kbd { background: rgba(255, 255, 255, .1); }
|
|
370
|
-
.editable { outline: none; text-decoration: underline dotted color-mix(in srgb, var(--akaji) 70%, transparent); text-decoration-thickness: 1.5px; text-underline-offset: .22em; min-width: .5em; display: inline; }
|
|
371
|
-
.editable { text-decoration-color: color-mix(in srgb, var(--akaji) 45%, transparent); }
|
|
372
|
-
.editable:focus { text-decoration-color: color-mix(in srgb, var(--akaji) 80%, transparent); }
|
|
373
|
-
.chip { display: inline-block; font: .78em/1.5 var(--mono); color: var(--muted); background: color-mix(in srgb, currentColor 7%, transparent); border: 1px solid var(--line); border-radius: 5px; padding: 0 5px; margin: 0 1px; vertical-align: baseline; user-select: none; cursor: default; white-space: nowrap; }
|
|
374
|
-
.locale { display: grid; grid-template-columns: 32px 1fr; gap: 4px 6px; align-items: start; padding: 6px 10px; border-top: 1px solid var(--line); font: 13px/1.4 var(--sans); }
|
|
375
|
-
.locale .code { font: 11px var(--mono); color: var(--muted); padding-top: 2px; }
|
|
376
|
-
.attr { display: grid; grid-template-columns: 90px 1fr; gap: 6px; align-items: baseline; margin-top: 6px; }
|
|
377
|
-
.attr .name { font: 11px var(--mono); color: var(--muted); }
|
|
378
|
-
.attr .value { border: 1px solid var(--line); border-radius: 6px; padding: 4px 6px; white-space: pre-wrap; }
|
|
379
|
-
|
|
380
|
-
/* Pins: dropped where a note points, red while open, green with a drawn check once resolved. */
|
|
381
|
-
.pin { position: absolute; display: grid; place-items: center; width: 24px; height: 24px; padding: 0; border-radius: 50%; border: 2px solid #fff; background: var(--akaji); color: #fff; font: 700 11px/1 var(--sans); cursor: pointer; box-shadow: 0 3px 8px rgba(0, 0, 0, .3); transform: translate(-50%, -50%); }
|
|
382
|
-
.pin:hover { transform: translate(-50%, -50%) scale(1.12); border-color: #fff; }
|
|
383
|
-
.pin.fresh { animation: pin-drop .32s var(--spring); }
|
|
384
|
-
.pin.question { background: var(--question); }
|
|
385
|
-
.pin.resolved { background: var(--resolved); }
|
|
386
|
-
.pin .icon { width: 16px; height: 16px; stroke-width: 2.6; }
|
|
387
|
-
.pin.fresh .stroke { stroke-dasharray: 24; stroke-dashoffset: 24; animation: draw .42s .12s ease-out forwards; }
|
|
388
|
-
|
|
389
|
-
/* The tray. The corner button opens it; the selected tool rises and shows its ink. */
|
|
390
|
-
.dock { position: fixed; display: flex; align-items: center; gap: 8px; user-select: none; }
|
|
391
|
-
.corner { width: 40px; height: 40px; border-radius: 50%; border: 1px solid var(--tray-line); background: var(--tray); color: var(--akaji); font: 600 19px/38px "Hiragino Mincho ProN", "Yu Mincho", serif; text-align: center; cursor: grab; box-shadow: 0 8px 22px rgba(0, 0, 0, .3); position: relative; padding: 0; }
|
|
392
|
-
.corner:hover { border-color: var(--tray-muted); transform: rotate(-8deg); }
|
|
393
|
-
.corner.active { background: var(--akaji); color: #fff; border-color: var(--akaji); }
|
|
394
|
-
.corner .count { position: absolute; top: -5px; right: -5px; min-width: 18px; height: 18px; border-radius: 9px; background: var(--marker); color: var(--ink); font: 700 10px/18px var(--sans); padding: 0 5px; box-shadow: 0 1px 3px rgba(0, 0, 0, .3); }
|
|
395
|
-
.toolbar { display: flex; align-items: center; gap: 2px; background: var(--tray); border: 1px solid var(--tray-line); border-radius: 999px; padding: 5px; box-shadow: 0 12px 30px -8px rgba(0, 0, 0, .45); animation: settle .2s var(--spring); }
|
|
396
|
-
.toolbar .sep { width: 1px; height: 20px; background: var(--tray-line); margin: 0 4px; }
|
|
397
|
-
.tool { position: relative; display: grid; place-items: center; width: 38px; height: 38px; padding: 0; border: none; border-radius: 50%; color: var(--tray-ink); }
|
|
398
|
-
.tool:hover { background: var(--tray-raised); transform: translateY(-2px) rotate(-6deg); }
|
|
399
|
-
.tool[aria-pressed="true"] { background: var(--tray-raised); transform: translateY(-4px); }
|
|
400
|
-
.tool[aria-pressed="true"]::after { content: ""; position: absolute; bottom: 3px; left: 50%; width: 14px; height: 3px; margin-left: -7px; border-radius: 2px; background: var(--ink-color, var(--tray-ink)); }
|
|
401
|
-
.tool .icon { width: 22px; height: 22px; }
|
|
402
|
-
.tool .badge { position: absolute; top: 2px; right: 1px; min-width: 16px; height: 16px; border-radius: 8px; background: var(--akaji); color: #fff; font: 700 9.5px/16px var(--sans); padding: 0 4px; }
|
|
403
|
-
.tool .tip { position: absolute; bottom: calc(100% + 10px); 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; }
|
|
404
|
-
.tool:hover .tip, .tool:focus-visible .tip { opacity: 1; transform: translateX(-50%); }
|
|
405
|
-
.tool:focus-visible { outline: 2px solid var(--marker); outline-offset: 1px; }
|
|
406
|
-
|
|
407
|
-
/* The notes panel: the tray's material, holding the page's Post-its. */
|
|
408
|
-
.sidebar { position: fixed; top: 12px; right: 12px; bottom: 70px; 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); }
|
|
409
|
-
.sidebar header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px; }
|
|
410
|
-
.sidebar header strong { font-size: 14px; }
|
|
411
|
-
.sidebar header .icon-button { color: var(--tray-muted); }
|
|
412
|
-
.sidebar header .icon-button:hover { background: var(--tray-raised); color: var(--tray-ink); }
|
|
413
|
-
.sidebar > .row { display: flex; gap: 6px; flex-wrap: wrap; margin-bottom: 12px; }
|
|
414
|
-
.sidebar > .row button { border-color: var(--tray-line); color: var(--tray-ink); font-size: 12px; }
|
|
415
|
-
.sidebar > .row button:hover { border-color: var(--tray-muted); background: var(--tray-raised); }
|
|
416
|
-
.sidebar .note-card { margin-bottom: 10px; }
|
|
417
|
-
.sidebar .empty { color: var(--tray-muted); padding: 12px 2px; line-height: 1.5; }
|
|
418
|
-
|
|
419
|
-
.toasts { position: fixed; left: 50%; bottom: 18px; transform: translateX(-50%); display: flex; flex-direction: column; gap: 6px; align-items: center; }
|
|
420
|
-
.toast { background: var(--tray); color: var(--tray-ink); border: 1px solid var(--tray-line); border-radius: 999px; padding: 8px 14px; box-shadow: 0 10px 26px -8px rgba(0, 0, 0, .45); display: flex; gap: 10px; align-items: center; max-width: 560px; animation: settle .2s var(--spring); }
|
|
421
|
-
.toast.error { background: var(--akaji); border-color: var(--akaji); color: #fff; border-radius: 12px; }
|
|
422
|
-
.toast button { color: inherit; border-color: currentColor; padding: 1px 9px; font-size: 12px; border-radius: 999px; }
|
|
423
|
-
|
|
424
|
-
/* An agent connected over MCP: a green light at the start of the tray and on the corner button. */
|
|
425
|
-
.agent-light { position: relative; width: 10px; height: 10px; margin: 0 6px 0 8px; border-radius: 50%; background: var(--resolved); box-shadow: 0 0 0 3px rgba(47, 168, 114, .25); animation: breathe 2.4s ease-in-out infinite; }
|
|
426
|
-
.agent-light .tip { bottom: calc(100% + 18px); }
|
|
427
|
-
.agent-light:hover .tip { opacity: 1; transform: translateX(-50%); }
|
|
428
|
-
.corner.agent::before { content: ""; position: absolute; left: -2px; bottom: -2px; width: 11px; height: 11px; border-radius: 50%; background: var(--resolved); border: 2px solid var(--tray); }
|
|
429
|
-
.tool.confirm { background: var(--akaji); color: #fff; }
|
|
430
|
-
.tool.confirm .tip { background: var(--akaji); border-color: var(--akaji); color: #fff; }
|
|
431
|
-
|
|
432
|
-
.panel.pick { min-width: 220px; }
|
|
433
|
-
.note-card .editing textarea { margin-top: 8px; }
|
|
434
|
-
.note-card .editing .row { justify-content: flex-end; }
|
|
435
|
-
.pin.working { background: var(--tray); box-shadow: 0 0 0 3px rgba(255, 225, 77, .55), 0 3px 8px rgba(0, 0, 0, .3); animation: breathe 2.4s ease-in-out infinite; }
|
|
436
|
-
.status.working { color: #8a6a00; background: rgba(255, 225, 77, .55); }
|
|
437
|
-
@keyframes breathe { 50% { box-shadow: 0 0 0 6px rgba(47, 168, 114, 0); } }
|
|
438
|
-
.pin.working { animation-name: breathe-ink; }
|
|
439
|
-
@keyframes breathe-ink { 50% { box-shadow: 0 0 0 7px rgba(255, 225, 77, 0), 0 3px 8px rgba(0, 0, 0, .3); } }
|
|
440
|
-
|
|
441
|
-
/* An agent connected over MCP: a green light at the start of the tray and on the corner button. */
|
|
442
|
-
.agent-light { position: relative; width: 10px; height: 10px; margin: 0 6px 0 8px; border-radius: 50%; background: var(--resolved); box-shadow: 0 0 0 3px rgba(47, 168, 114, .25); animation: breathe 2.4s ease-in-out infinite; }
|
|
443
|
-
.agent-light .tip { bottom: calc(100% + 18px); }
|
|
444
|
-
.agent-light:hover .tip { opacity: 1; transform: translateX(-50%); }
|
|
445
|
-
.corner.agent::before { content: ""; position: absolute; left: -2px; bottom: -2px; width: 11px; height: 11px; border-radius: 50%; background: var(--resolved); border: 2px solid var(--tray); }
|
|
446
|
-
.tool.confirm { background: var(--akaji); color: #fff; }
|
|
447
|
-
.tool.confirm .tip { background: var(--akaji); border-color: var(--akaji); color: #fff; }
|
|
448
|
-
|
|
449
|
-
.panel.pick { min-width: 220px; }
|
|
450
|
-
.note-card .editing textarea { margin-top: 8px; }
|
|
451
|
-
.note-card .editing .row { justify-content: flex-end; }
|
|
452
|
-
.pin.working { background: var(--tray); box-shadow: 0 0 0 3px rgba(255, 225, 77, .55), 0 3px 8px rgba(0, 0, 0, .3); animation: breathe 2.4s ease-in-out infinite; }
|
|
453
|
-
.status.working { color: #8a6a00; background: rgba(255, 225, 77, .55); }
|
|
454
|
-
@keyframes breathe { 50% { box-shadow: 0 0 0 6px rgba(47, 168, 114, 0); } }
|
|
455
|
-
.pin.working { animation-name: breathe-ink; }
|
|
456
|
-
@keyframes breathe-ink { 50% { box-shadow: 0 0 0 7px rgba(255, 225, 77, 0), 0 3px 8px rgba(0, 0, 0, .3); } }
|
|
457
|
-
|
|
458
|
-
/* Popovers above the toolbar: history and settings, in the tray's material. */
|
|
459
|
-
.popover { position: absolute; right: 0; bottom: calc(100% + 12px); width: 340px; max-width: calc(100vw - 24px); max-height: 60vh; overflow: auto; background: var(--tray); color: var(--tray-ink); border: 1px solid var(--tray-line); border-radius: 14px; padding: 10px; box-shadow: 0 18px 40px -12px rgba(0, 0, 0, .5); animation: settle .18s var(--spring); }
|
|
460
|
-
.popover h3 { display: flex; flex-direction: column; gap: 3px; margin: 2px 4px 10px; font-size: 13px; }
|
|
461
|
-
.popover .where { font: 400 11px/1.35 var(--sans); color: var(--tray-muted); }
|
|
462
|
-
.popover button { border-color: var(--tray-line); color: var(--tray-ink); font-size: 12px; }
|
|
463
|
-
.popover button:hover { background: var(--tray-raised); border-color: var(--tray-muted); }
|
|
464
|
-
.popover .empty { color: var(--tray-muted); padding: 4px; }
|
|
465
|
-
.popover .entry { display: flex; gap: 8px; align-items: center; padding: 7px 6px; border-top: 1px solid var(--tray-line); }
|
|
466
|
-
.popover .entry .what { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 2px; }
|
|
467
|
-
.popover .entry .what .where { font-family: var(--mono); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
468
|
-
.popover .entry.undone .what > span:first-child { text-decoration: line-through; color: var(--tray-muted); }
|
|
469
|
-
.popover .setting { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; padding: 8px 4px; border-top: 1px solid var(--tray-line); }
|
|
470
|
-
.popover .setting > span:first-child { flex: 1; }
|
|
471
|
-
.popover .setting .where { flex-basis: 100%; }
|
|
472
|
-
.segmented { display: inline-flex; border: 1px solid var(--tray-line); border-radius: 999px; padding: 2px; }
|
|
473
|
-
.segmented button { border: none; border-radius: 999px; padding: 3px 10px; }
|
|
474
|
-
.segmented button[aria-pressed="true"] { background: var(--tray-ink); color: var(--tray); }
|
|
475
|
-
.popover .check { display: flex; gap: 10px; align-items: flex-start; padding: 8px 4px; border-top: 1px solid var(--tray-line); cursor: pointer; }
|
|
476
|
-
.popover .check input { width: auto; margin-top: 2px; accent-color: var(--akaji); }
|
|
477
|
-
.popover .check > span { display: flex; flex-direction: column; gap: 2px; }
|
|
478
|
-
|
|
479
|
-
/* The corner button, compact: a small tab that grows when pointed at. */
|
|
480
|
-
.corner.compact:not(.active):not([aria-expanded="true"]) { width: 18px; height: 18px; font-size: 0; opacity: .7; }
|
|
481
|
-
.corner.compact:not(.active):not([aria-expanded="true"]) .count { display: none; }
|
|
482
|
-
.dock:hover .corner.compact { width: 40px; height: 40px; font-size: 19px; opacity: 1; }
|
|
483
|
-
|
|
484
|
-
/* Notes on selected text: the phrase stays marked with the highlighter. */
|
|
485
|
-
.phrase { position: absolute; pointer-events: none; background: var(--marker-soft); box-shadow: inset 0 -2px 0 var(--marker-edge); border-radius: 2px; }
|
|
486
|
-
.ink-warning { color: var(--akaji); }
|
|
487
|
-
.ink-muted { color: var(--muted); }
|
|
488
|
-
.phrase.resolved { background: rgba(47, 168, 114, .16); box-shadow: inset 0 -2px 0 var(--resolved); }
|
|
489
|
-
|
|
490
|
-
.note-card .thread { display: flex; flex-direction: column; gap: 6px; margin-top: 8px; }
|
|
491
|
-
.note-card .message { padding: 6px 9px; border-radius: 0 6px 6px 0; background: rgba(255, 255, 255, .55); border-left: 3px solid var(--resolved); white-space: pre-wrap; }
|
|
492
|
-
.note-card .message.you { border-left-color: var(--ink); background: rgba(255, 255, 255, .3); }
|
|
493
|
-
.note-card .message .who { display: block; font: 700 10px/1.4 var(--sans); text-transform: uppercase; letter-spacing: .05em; color: var(--muted); }
|
|
494
|
-
.note-card .missing { margin-top: 8px; font-size: 12px; color: var(--akaji); }
|
|
495
|
-
.sidebar .tabs { display: flex; gap: 2px; margin-bottom: 10px; border: 1px solid var(--tray-line); border-radius: 999px; padding: 2px; width: fit-content; }
|
|
496
|
-
.sidebar .tabs button { border: none; border-radius: 999px; padding: 3px 12px; color: var(--tray-muted); font-size: 12px; }
|
|
497
|
-
.sidebar .tabs button[aria-selected="true"] { background: var(--tray-ink); color: var(--tray); }
|
|
498
|
-
.sidebar a.page { display: flex; justify-content: space-between; margin: 14px 2px 8px; color: var(--tray-ink); font: 600 12px/1.3 var(--mono); text-decoration: none; }
|
|
499
|
-
.sidebar a.page:hover { text-decoration: underline; }
|
|
500
|
-
.sidebar a.page.current { color: var(--marker); }
|
|
501
|
-
.sidebar a.page span { color: var(--tray-muted); }
|
|
502
|
-
|
|
503
|
-
@keyframes settle { from { opacity: 0; transform: translateY(6px) rotate(-1.2deg); } to { opacity: 1; transform: none; } }
|
|
504
|
-
@keyframes slide-in { from { opacity: 0; transform: translateX(16px); } to { opacity: 1; transform: none; } }
|
|
505
|
-
@keyframes pin-drop { from { opacity: 0; transform: translate(-50%, -140%) scale(.6); } to { opacity: 1; transform: translate(-50%, -50%); } }
|
|
506
|
-
@keyframes draw { to { stroke-dashoffset: 0; } }
|
|
507
|
-
|
|
508
|
-
@media (prefers-reduced-motion: reduce) {
|
|
509
|
-
*, *::before, *::after { animation: none !important; transition: none !important; }
|
|
510
|
-
.pin.fresh .stroke { stroke-dashoffset: 0; }
|
|
511
|
-
.tool:hover, .tool[aria-pressed="true"], .corner:hover { transform: none; }
|
|
360
|
+
`);return style.appendChild(cssText),style}function resolveBoundingBox(node,context){let{width,height}=context;if(isElementNode(node)&&(!width||!height)){let box2=node.getBoundingClientRect();width=width||box2.width||Number(node.getAttribute("width"))||0,height=height||box2.height||Number(node.getAttribute("height"))||0}return{width,height}}async function imageToCanvas(image,context){let{log,timeout,drawImageCount,drawImageInterval}=context;log.time("image to canvas");let loaded=await loadMedia(image,{timeout,onWarn:context.log.warn}),{canvas,context2d}=createCanvas(image.ownerDocument,context),drawImage=()=>{try{context2d?.drawImage(loaded,0,0,canvas.width,canvas.height)}catch(error){context.log.warn("Failed to drawImage",error)}};if(drawImage(),context.isEnable("fixSvgXmlDecode"))for(let i=0;i<drawImageCount;i++)await new Promise((resolve)=>{setTimeout(()=>{context2d?.clearRect(0,0,canvas.width,canvas.height),drawImage(),resolve()},i+drawImageInterval)});return context.drawImageCount=0,log.timeEnd("image to canvas"),canvas}function createCanvas(ownerDocument,context){let{width,height,scale,backgroundColor,maximumCanvasSize:max}=context,canvas=ownerDocument.createElement("canvas");if(canvas.width=Math.floor(width*scale),canvas.height=Math.floor(height*scale),canvas.style.width=`${width}px`,canvas.style.height=`${height}px`,max){if(canvas.width>max||canvas.height>max)if(canvas.width>max&&canvas.height>max)if(canvas.width>canvas.height)canvas.height*=max/canvas.width,canvas.width=max;else canvas.width*=max/canvas.height,canvas.height=max;else if(canvas.width>max)canvas.height*=max/canvas.width,canvas.width=max;else canvas.width*=max/canvas.height,canvas.height=max}let context2d=canvas.getContext("2d");if(context2d&&backgroundColor)context2d.fillStyle=backgroundColor,context2d.fillRect(0,0,canvas.width,canvas.height);return{canvas,context2d}}function cloneCanvas(canvas,context){if(canvas.ownerDocument)try{let dataURL=canvas.toDataURL();if(dataURL!=="data:,")return createImage(dataURL,canvas.ownerDocument)}catch(error){context.log.warn("Failed to clone canvas",error)}let cloned=canvas.cloneNode(!1),ctx=canvas.getContext("2d"),clonedCtx=cloned.getContext("2d");try{if(ctx&&clonedCtx)clonedCtx.putImageData(ctx.getImageData(0,0,canvas.width,canvas.height),0,0);return cloned}catch(error){context.log.warn("Failed to clone canvas",error)}return cloned}function cloneIframe(iframe,context){try{if(iframe?.contentDocument?.documentElement)return cloneNode(iframe.contentDocument.documentElement,context)}catch(error){context.log.warn("Failed to clone iframe",error)}return iframe.cloneNode(!1)}function cloneImage(image){let cloned=image.cloneNode(!1);if(image.currentSrc&&image.currentSrc!==image.src)cloned.src=image.currentSrc,cloned.srcset="";if(cloned.loading==="lazy")cloned.loading="eager";return cloned}async function cloneVideo(video,context){if(video.ownerDocument&&!video.currentSrc&&video.poster)return createImage(video.poster,video.ownerDocument);let cloned=video.cloneNode(!1);if(cloned.crossOrigin="anonymous",video.currentSrc&&video.currentSrc!==video.src)cloned.src=video.currentSrc;let ownerDocument=cloned.ownerDocument;if(ownerDocument){let canPlay=!0;if(await loadMedia(cloned,{onError:()=>canPlay=!1,onWarn:context.log.warn}),!canPlay){if(video.poster)return createImage(video.poster,video.ownerDocument);return cloned}cloned.currentTime=video.currentTime,await new Promise((resolve)=>{cloned.addEventListener("seeked",resolve,{once:!0})});let canvas=ownerDocument.createElement("canvas");canvas.width=video.offsetWidth,canvas.height=video.offsetHeight;try{let ctx=canvas.getContext("2d");if(ctx)ctx.drawImage(cloned,0,0,canvas.width,canvas.height)}catch(error){if(context.log.warn("Failed to clone video",error),video.poster)return createImage(video.poster,video.ownerDocument);return cloned}return cloneCanvas(canvas,context)}return cloned}function cloneElement(node,context){if(isCanvasElement(node))return cloneCanvas(node,context);if(isIFrameElement(node))return cloneIframe(node,context);if(isImageElement(node))return cloneImage(node);if(isVideoElement(node))return cloneVideo(node,context);return node.cloneNode(!1)}function getSandBox(context){let sandbox=context.sandbox;if(!sandbox){let{ownerDocument}=context;try{if(ownerDocument)sandbox=ownerDocument.createElement("iframe"),sandbox.id=`__SANDBOX__${uuid()}`,sandbox.width="0",sandbox.height="0",sandbox.style.visibility="hidden",sandbox.style.position="fixed",ownerDocument.body.appendChild(sandbox),sandbox.srcdoc='<!DOCTYPE html><meta charset="UTF-8"><title></title><body>',context.sandbox=sandbox}catch(error){context.log.warn("Failed to getSandBox",error)}}return sandbox}var ignoredStyles=["width","height","-webkit-text-fill-color"],includedAttributes=["stroke","fill"];function getDefaultStyle(node,pseudoElement,context){let{defaultComputedStyles}=context,nodeName=node.nodeName.toLowerCase(),isSvgNode=isSVGElementNode(node)&&nodeName!=="svg",attributes=isSvgNode?includedAttributes.map((name)=>[name,node.getAttribute(name)]).filter(([,value])=>value!==null):[],key=[isSvgNode&&"svg",nodeName,attributes.map((name,value)=>`${name}=${value}`).join(","),pseudoElement].filter(Boolean).join(":");if(defaultComputedStyles.has(key))return defaultComputedStyles.get(key);let sandboxWindow=getSandBox(context)?.contentWindow;if(!sandboxWindow)return new Map;let sandboxDocument=sandboxWindow?.document,root,el;if(isSvgNode)root=sandboxDocument.createElementNS(XMLNS,"svg"),el=root.ownerDocument.createElementNS(root.namespaceURI,nodeName),attributes.forEach(([name,value])=>{el.setAttributeNS(null,name,value)}),root.appendChild(el);else root=el=sandboxDocument.createElement(nodeName);el.textContent=" ",sandboxDocument.body.appendChild(root);let computedStyle=sandboxWindow.getComputedStyle(el,pseudoElement),styles=new Map;for(let len=computedStyle.length,i=0;i<len;i++){let name=computedStyle.item(i);if(ignoredStyles.includes(name))continue;styles.set(name,computedStyle.getPropertyValue(name))}return sandboxDocument.body.removeChild(root),defaultComputedStyles.set(key,styles),styles}function getDiffStyle(style,defaultStyle,includeStyleProperties){let diffStyle=new Map,prefixs=[],prefixTree=new Map;if(includeStyleProperties)for(let name of includeStyleProperties)applyTo(name);else for(let len=style.length,i=0;i<len;i++){let name=style.item(i);applyTo(name)}for(let len=prefixs.length,i=0;i<len;i++)prefixTree.get(prefixs[i])?.forEach((value,name)=>diffStyle.set(name,value));function applyTo(name){let value=style.getPropertyValue(name),priority=style.getPropertyPriority(name),subIndex=name.lastIndexOf("-"),prefix=subIndex>-1?name.substring(0,subIndex):void 0;if(prefix){let map=prefixTree.get(prefix);if(!map)map=new Map,prefixTree.set(prefix,map);map.set(name,[value,priority])}if(defaultStyle.get(name)===value&&!priority)return;if(prefix)prefixs.push(prefix);else diffStyle.set(name,[value,priority])}return diffStyle}function copyCssStyles(node,cloned,isRoot,context){let{ownerWindow,includeStyleProperties,currentParentNodeStyle}=context,clonedStyle=cloned.style,computedStyle=ownerWindow.getComputedStyle(node),defaultStyle=getDefaultStyle(node,null,context);currentParentNodeStyle?.forEach((_,key)=>{defaultStyle.delete(key)});let style=getDiffStyle(computedStyle,defaultStyle,includeStyleProperties);if(style.delete("transition-property"),style.delete("all"),style.delete("d"),style.delete("content"),isRoot)style.delete("position"),style.delete("margin-top"),style.delete("margin-right"),style.delete("margin-bottom"),style.delete("margin-left"),style.delete("margin-block-start"),style.delete("margin-block-end"),style.delete("margin-inline-start"),style.delete("margin-inline-end"),style.set("box-sizing",["border-box",""]);if(style.get("background-clip")?.[0]==="text")cloned.classList.add("______background-clip--text");if(IN_CHROME){if(!style.has("font-kerning"))style.set("font-kerning",["normal",""]);if((style.get("overflow-x")?.[0]==="hidden"||style.get("overflow-y")?.[0]==="hidden")&&style.get("text-overflow")?.[0]==="ellipsis"&&node.scrollWidth===node.clientWidth)style.set("text-overflow",["clip",""])}for(let len=clonedStyle.length,i=0;i<len;i++)clonedStyle.removeProperty(clonedStyle.item(i));return style.forEach(([value,priority],name)=>{clonedStyle.setProperty(name,value,priority)}),style}function copyInputValue(node,cloned){if(isTextareaElement(node)||isInputElement(node)||isSelectElement(node))cloned.setAttribute("value",node.value)}var pseudoClasses=["::before","::after"],scrollbarPseudoClasses=["::-webkit-scrollbar","::-webkit-scrollbar-button","::-webkit-scrollbar-thumb","::-webkit-scrollbar-track","::-webkit-scrollbar-track-piece","::-webkit-scrollbar-corner","::-webkit-resizer"];function copyPseudoClass(node,cloned,copyScrollbar,context,addWordToFontFamilies){let{ownerWindow,svgStyleElement,svgStyles,currentNodeStyle}=context;if(!svgStyleElement||!ownerWindow)return;function copyBy(pseudoClass){let computedStyle=ownerWindow.getComputedStyle(node,pseudoClass),content=computedStyle.getPropertyValue("content");if(!content||content==="none")return;addWordToFontFamilies?.(content),content=content.replace(/(')|(")|(counter\(.+\))/g,"");let klasses=[uuid()],defaultStyle=getDefaultStyle(node,pseudoClass,context);currentNodeStyle?.forEach((_,key)=>{defaultStyle.delete(key)});let style=getDiffStyle(computedStyle,defaultStyle,context.includeStyleProperties);if(style.delete("content"),style.delete("-webkit-locale"),style.get("background-clip")?.[0]==="text")cloned.classList.add("______background-clip--text");let cloneStyle=[`content: '${content}';`];if(style.forEach(([value,priority],name)=>{cloneStyle.push(`${name}: ${value}${priority?" !important":""};`)}),cloneStyle.length===1)return;try{cloned.className=[cloned.className,...klasses].join(" ")}catch(err){context.log.warn("Failed to copyPseudoClass",err);return}let cssText=cloneStyle.join(`
|
|
361
|
+
`),allClasses=svgStyles.get(cssText);if(!allClasses)allClasses=[],svgStyles.set(cssText,allClasses);allClasses.push(`.${klasses[0]}${pseudoClass}`)}if(pseudoClasses.forEach(copyBy),copyScrollbar)scrollbarPseudoClasses.forEach(copyBy)}var excludeParentNodes=new Set(["symbol"]);async function appendChildNode(node,cloned,child,context,addWordToFontFamilies){if(isElementNode(child)&&(isStyleElement(child)||isScriptElement(child)))return;if(context.filter&&!context.filter(child))return;if(excludeParentNodes.has(cloned.nodeName)||excludeParentNodes.has(child.nodeName))context.currentParentNodeStyle=void 0;else context.currentParentNodeStyle=context.currentNodeStyle;let childCloned=await cloneNode(child,context,!1,addWordToFontFamilies);if(context.isEnable("restoreScrollPosition"))restoreScrollPosition(node,childCloned);cloned.appendChild(childCloned)}async function cloneChildNodes(node,cloned,context,addWordToFontFamilies){let firstChild=node.firstChild;if(isElementNode(node)){if(node.shadowRoot)firstChild=node.shadowRoot?.firstChild,context.shadowRoots.push(node.shadowRoot)}for(let child=firstChild;child;child=child.nextSibling){if(isCommentNode(child))continue;if(isElementNode(child)&&isSlotElement(child)&&typeof child.assignedNodes==="function"){let nodes=child.assignedNodes();for(let i=0;i<nodes.length;i++)await appendChildNode(node,cloned,nodes[i],context,addWordToFontFamilies)}else await appendChildNode(node,cloned,child,context,addWordToFontFamilies)}}function restoreScrollPosition(node,chlidCloned){if(!isHTMLElementNode(node)||!isHTMLElementNode(chlidCloned))return;let{scrollTop,scrollLeft}=node;if(!scrollTop&&!scrollLeft)return;let{transform}=chlidCloned.style,matrix=new DOMMatrix(transform),{a,b,c,d}=matrix;matrix.a=1,matrix.b=0,matrix.c=0,matrix.d=1,matrix.translateSelf(-scrollLeft,-scrollTop),matrix.a=a,matrix.b=b,matrix.c=c,matrix.d=d,chlidCloned.style.transform=matrix.toString()}function applyCssStyleWithOptions(cloned,context){let{backgroundColor,width,height,style:styles}=context,clonedStyle=cloned.style;if(backgroundColor)clonedStyle.setProperty("background-color",backgroundColor,"important");if(width)clonedStyle.setProperty("width",`${width}px`,"important");if(height)clonedStyle.setProperty("height",`${height}px`,"important");if(styles)for(let name in styles)clonedStyle[name]=styles[name]}var NORMAL_ATTRIBUTE_RE=/^[\w-:]+$/;async function cloneNode(node,context,isRoot=!1,addWordToFontFamilies){let{ownerDocument,ownerWindow,fontFamilies,onCloneEachNode}=context;if(ownerDocument&&isTextNode(node)){if(addWordToFontFamilies&&/\S/.test(node.data))addWordToFontFamilies(node.data);return ownerDocument.createTextNode(node.data)}if(ownerDocument&&ownerWindow&&isElementNode(node)&&(isHTMLElementNode(node)||isSVGElementNode(node))){let cloned2=await cloneElement(node,context);if(context.isEnable("removeAbnormalAttributes")){let names=cloned2.getAttributeNames();for(let len=names.length,i=0;i<len;i++){let name=names[i];if(!NORMAL_ATTRIBUTE_RE.test(name))cloned2.removeAttribute(name)}}let style=context.currentNodeStyle=copyCssStyles(node,cloned2,isRoot,context);if(isRoot)applyCssStyleWithOptions(cloned2,context);let copyScrollbar=!1;if(context.isEnable("copyScrollbar")){let overflow=[style.get("overflow-x")?.[0],style.get("overflow-y")?.[0]];copyScrollbar=overflow.includes("scroll")||(overflow.includes("auto")||overflow.includes("overlay"))&&(node.scrollHeight>node.clientHeight||node.scrollWidth>node.clientWidth)}let textTransform=style.get("text-transform")?.[0],families=splitFontFamily(style.get("font-family")?.[0]),addWordToFontFamilies2=families?(word)=>{if(textTransform==="uppercase")word=word.toUpperCase();else if(textTransform==="lowercase")word=word.toLowerCase();else if(textTransform==="capitalize")word=word[0].toUpperCase()+word.substring(1);families.forEach((family)=>{let fontFamily=fontFamilies.get(family);if(!fontFamily)fontFamilies.set(family,fontFamily=new Set);word.split("").forEach((text)=>fontFamily.add(text))})}:void 0;if(copyPseudoClass(node,cloned2,copyScrollbar,context,addWordToFontFamilies2),copyInputValue(node,cloned2),!isVideoElement(node))await cloneChildNodes(node,cloned2,context,addWordToFontFamilies2);return await onCloneEachNode?.(cloned2),cloned2}let cloned=node.cloneNode(!1);return await cloneChildNodes(node,cloned,context),await onCloneEachNode?.(cloned),cloned}function destroyContext(context){if(context.ownerDocument=void 0,context.ownerWindow=void 0,context.svgStyleElement=void 0,context.svgDefsElement=void 0,context.svgStyles.clear(),context.defaultComputedStyles.clear(),context.sandbox){try{context.sandbox.remove()}catch(err){context.log.warn("Failed to destroyContext",err)}context.sandbox=void 0}context.workers=[],context.fontFamilies.clear(),context.fontCssTexts.clear(),context.requests.clear(),context.tasks=[],context.shadowRoots=[]}function baseFetch(options){let{url,timeout,responseType,...requestInit}=options,controller=new AbortController,timer=timeout?setTimeout(()=>controller.abort(),timeout):void 0;return fetch(url,{signal:controller.signal,...requestInit}).then((response)=>{if(!response.ok)throw Error("Failed fetch, not 2xx response",{cause:response});switch(responseType){case"arrayBuffer":return response.arrayBuffer();case"dataUrl":return response.blob().then(blobToDataUrl);case"text":default:return response.text()}}).finally(()=>clearTimeout(timer))}function contextFetch(context,options){let{url:rawUrl,requestType="text",responseType="text",imageDom}=options,url=rawUrl,{timeout,acceptOfImage,requests,fetchFn,fetch:{requestInit,bypassingCache,placeholderImage},font,workers,fontFamilies}=context;if(requestType==="image"&&(IN_SAFARI||IN_FIREFOX))context.drawImageCount++;let request=requests.get(rawUrl);if(!request){if(bypassingCache){if(bypassingCache instanceof RegExp&&bypassingCache.test(url))url+=(/\?/.test(url)?"&":"?")+new Date().getTime()}let canFontMinify=requestType.startsWith("font")&&font&&font.minify,fontTexts=new Set;if(canFontMinify)requestType.split(";")[1].split(",").forEach((family)=>{if(!fontFamilies.has(family))return;fontFamilies.get(family).forEach((text)=>fontTexts.add(text))});let needFontMinify=canFontMinify&&fontTexts.size,baseFetchOptions={url,timeout,responseType:needFontMinify?"arrayBuffer":responseType,headers:requestType==="image"?{accept:acceptOfImage}:void 0,...requestInit};request={type:requestType,resolve:void 0,reject:void 0,response:null},request.response=(async()=>{if(fetchFn&&requestType==="image"){let result=await fetchFn(rawUrl);if(result)return result}if(!IN_SAFARI&&rawUrl.startsWith("http")&&workers.length)return new Promise((resolve,reject)=>{workers[requests.size&workers.length-1].postMessage({rawUrl,...baseFetchOptions}),request.resolve=resolve,request.reject=reject});return baseFetch(baseFetchOptions)})().catch((error)=>{if(requests.delete(rawUrl),requestType==="image"&&placeholderImage)return context.log.warn("Failed to fetch image base64, trying to use placeholder image",url),typeof placeholderImage==="string"?placeholderImage:placeholderImage(imageDom);throw error}),requests.set(rawUrl,request)}return request.response}async function replaceCssUrlToDataUrl(cssText,baseUrl,context,isImage){if(!hasCssUrl(cssText))return cssText;for(let[rawUrl,url]of parseCssUrls(cssText,baseUrl))try{let dataUrl=await contextFetch(context,{url,requestType:isImage?"image":"text",responseType:"dataUrl"});cssText=cssText.replace(toRE(rawUrl),`$1${dataUrl}$3`)}catch(error){context.log.warn("Failed to fetch css data url",rawUrl,error)}return cssText}function hasCssUrl(cssText){return/url\((['"]?)([^'"]+?)\1\)/.test(cssText)}var URL_RE=/url\((['"]?)([^'"]+?)\1\)/g;function parseCssUrls(cssText,baseUrl){let result=[];return cssText.replace(URL_RE,(raw,quotation,url)=>{return result.push([url,resolveUrl(url,baseUrl)]),raw}),result.filter(([url])=>!isDataUrl(url))}function toRE(url){let escaped=url.replace(/([.*+?^${}()|\[\]\/\\])/g,"\\$1");return new RegExp(`(url\\(['"]?)(${escaped})(['"]?\\))`,"g")}var properties=["background-image","border-image-source","-webkit-border-image","-webkit-mask-image","list-style-image"];function embedCssStyleImage(style,context){return properties.map((property)=>{let value=style.getPropertyValue(property);if(!value||value==="none")return null;if(IN_SAFARI||IN_FIREFOX)context.drawImageCount++;return replaceCssUrlToDataUrl(value,null,context,!0).then((newValue)=>{if(!newValue||value===newValue)return;style.setProperty(property,newValue,style.getPropertyPriority(property))})}).filter(Boolean)}function embedImageElement(cloned,context){if(isImageElement(cloned)){let originalSrc=cloned.currentSrc||cloned.src;if(!isDataUrl(originalSrc))return[contextFetch(context,{url:originalSrc,imageDom:cloned,requestType:"image",responseType:"dataUrl"}).then((url)=>{if(!url)return;cloned.srcset="",cloned.dataset.originalSrc=originalSrc,cloned.src=url||""})];if(IN_SAFARI||IN_FIREFOX)context.drawImageCount++}else if(isSVGElementNode(cloned)&&!isDataUrl(cloned.href.baseVal)){let originalSrc=cloned.href.baseVal;return[contextFetch(context,{url:originalSrc,imageDom:cloned,requestType:"image",responseType:"dataUrl"}).then((url)=>{if(!url)return;cloned.dataset.originalSrc=originalSrc,cloned.href.baseVal=url||""})]}return[]}function embedSvgUse(cloned,context){let{ownerDocument,svgDefsElement}=context,href=cloned.getAttribute("href")??cloned.getAttribute("xlink:href");if(!href)return[];let[svgUrl,id]=href.split("#");if(id){let query2=`#${id}`,definition=context.shadowRoots.reduce((res,root)=>{return res??root.querySelector(`svg ${query2}`)},ownerDocument?.querySelector(`svg ${query2}`));if(svgUrl)cloned.setAttribute("href",query2);if(svgDefsElement?.querySelector(query2))return[];if(definition)return svgDefsElement?.appendChild(definition.cloneNode(!0)),[];else if(svgUrl)return[contextFetch(context,{url:svgUrl,responseType:"text"}).then((svgData)=>{svgDefsElement?.insertAdjacentHTML("beforeend",svgData)})]}return[]}function embedNode(cloned,context){let{tasks}=context;if(isElementNode(cloned)){if(isImageElement(cloned)||isSVGImageElementNode(cloned))tasks.push(...embedImageElement(cloned,context));if(isSVGUseElementNode(cloned))tasks.push(...embedSvgUse(cloned,context))}if(isHTMLElementNode(cloned))tasks.push(...embedCssStyleImage(cloned.style,context));cloned.childNodes.forEach((child)=>{embedNode(child,context)})}async function embedWebFont(clone,context){let{ownerDocument,svgStyleElement,fontFamilies,fontCssTexts,tasks,font}=context;if(!ownerDocument||!svgStyleElement||!fontFamilies.size)return;if(font&&font.cssText){let cssText=filterPreferredFormat(font.cssText,context);svgStyleElement.appendChild(ownerDocument.createTextNode(`${cssText}
|
|
362
|
+
`))}else{let styleSheets=Array.from(ownerDocument.styleSheets).filter((styleSheet)=>{try{return"cssRules"in styleSheet&&Boolean(styleSheet.cssRules.length)}catch(error){return context.log.warn(`Error while reading CSS rules from ${styleSheet.href}`,error),!1}}),tempDoc=ownerDocument.implementation.createHTMLDocument(""),tempStyleEl=tempDoc.createElement("style");tempDoc.head.appendChild(tempStyleEl);let tempStyleSheet=tempStyleEl.sheet;if(await Promise.all(styleSheets.flatMap((styleSheet)=>{return Array.from(styleSheet.cssRules).map(async(cssRule)=>{if(isCSSImportRule(cssRule)){let baseUrl=cssRule.href,cssText="";try{cssText=await contextFetch(context,{url:baseUrl,requestType:"text",responseType:"text"})}catch(error){context.log.warn(`Error fetch remote css import from ${baseUrl}`,error)}let replacedCssText=cssText.replace(URL_RE,(raw,quotation,url)=>raw.replace(url,resolveUrl(url,baseUrl)));for(let rule of parseCss(replacedCssText))try{tempStyleSheet.insertRule(rule,tempStyleSheet.cssRules.length)}catch(error){context.log.warn("Error inserting rule from remote css import",{rule,error})}}})})),tempStyleSheet.cssRules.length)styleSheets.push(tempStyleSheet);let cssRules=[];styleSheets.forEach((sheet)=>{unwrapCssLayers(sheet.cssRules,cssRules)}),cssRules.filter((cssRule)=>isCssFontFaceRule(cssRule)&&hasCssUrl(cssRule.style.getPropertyValue("src"))&&splitFontFamily(cssRule.style.getPropertyValue("font-family"))?.some((val)=>fontFamilies.has(val))).forEach((value)=>{let rule=value,cssText=fontCssTexts.get(rule.cssText);if(cssText)svgStyleElement.appendChild(ownerDocument.createTextNode(`${cssText}
|
|
363
|
+
`));else tasks.push(replaceCssUrlToDataUrl(rule.cssText,rule.parentStyleSheet?rule.parentStyleSheet.href:null,context).then((cssText2)=>{cssText2=filterPreferredFormat(cssText2,context),fontCssTexts.set(rule.cssText,cssText2),svgStyleElement.appendChild(ownerDocument.createTextNode(`${cssText2}
|
|
364
|
+
`))}))})}}var COMMENTS_RE=/(\/\*[\s\S]*?\*\/)/g,KEYFRAMES_RE=/((@.*?keyframes [\s\S]*?){([\s\S]*?}\s*?)})/gi;function parseCss(source){if(source==null)return[];let result=[],cssText=source.replace(COMMENTS_RE,"");while(!0){let matches=KEYFRAMES_RE.exec(cssText);if(!matches)break;result.push(matches[0])}cssText=cssText.replace(KEYFRAMES_RE,"");let IMPORT_RE=/@import[\s\S]*?url\([^)]*\)[\s\S]*?;/gi,UNIFIED_RE=new RegExp("((\\s*?(?:\\/\\*[\\s\\S]*?\\*\\/)?\\s*?@media[\\s\\S]*?){([\\s\\S]*?)}\\s*?})|(([\\s\\S]*?){([\\s\\S]*?)})","gi");while(!0){let matches=IMPORT_RE.exec(cssText);if(!matches)if(matches=UNIFIED_RE.exec(cssText),!matches)break;else IMPORT_RE.lastIndex=UNIFIED_RE.lastIndex;else UNIFIED_RE.lastIndex=IMPORT_RE.lastIndex;result.push(matches[0])}return result}var URL_WITH_FORMAT_RE=/url\([^)]+\)\s*format\((["']?)([^"']+)\1\)/g,FONT_SRC_RE=/src:\s*(?:url\([^)]+\)\s*format\([^)]+\)[,;]\s*)+/g;function filterPreferredFormat(str,context){let{font}=context,preferredFormat=font?font?.preferredFormat:void 0;return preferredFormat?str.replace(FONT_SRC_RE,(match)=>{while(!0){let[src,,format]=URL_WITH_FORMAT_RE.exec(match)||[];if(!format)return"";if(format===preferredFormat)return`src: ${src};`}}):str}function unwrapCssLayers(rules,out=[]){for(let rule of Array.from(rules))if(isLayerBlockRule(rule))out.push(...unwrapCssLayers(rule.cssRules));else if("cssRules"in rule)unwrapCssLayers(rule.cssRules,out);else out.push(rule);return out}var SVG_EXTERNAL_RESOURCE_REGEX=/\bx?link:?href\s*=\s*["'](?!data:)[^"']+["']/i;function svgHasExternalResources(svg){return SVG_EXTERNAL_RESOURCE_REGEX.test(svg.innerHTML)}async function domToForeignObjectSvg(node,options){let context=await orCreateContext(node,options);if(isElementNode(context.node)&&isSVGElementNode(context.node)&&!svgHasExternalResources(context.node))return context.node;let{ownerDocument,log,tasks,svgStyleElement,svgDefsElement,svgStyles,font,progress,autoDestruct,onCloneNode,onEmbedNode,onCreateForeignObjectSvg}=context;log.time("clone node");let clone=await cloneNode(context.node,context,!0);if(svgStyleElement&&ownerDocument){let allCssText="";svgStyles.forEach((klasses,cssText)=>{allCssText+=`${klasses.join(`,
|
|
365
|
+
`)} {
|
|
366
|
+
${cssText}
|
|
512
367
|
}
|
|
513
|
-
`,shadow.append(style)}var layer=div("layer"),fixed=div("fixed"),toasts=div("toasts");shadow.append(layer,fixed);fixed.append(toasts);function mount(){if(!host.isConnected)document.documentElement.append(host)}function h(tag,attributes={},...children){let element=document.createElement(tag);for(let[name,value]of Object.entries(attributes)){if(value===void 0||value===null||value===!1)continue;if(name.startsWith("on")&&typeof value==="function")element.addEventListener(name.slice(2),value);else if(name==="className")element.className=value;else element.setAttribute(name,value===!0?"":String(value))}for(let child of children)if(child)element.append(child);return element}function div(className,...children){return h("div",{className},...children)}function toast(message,options={}){let element=div("toast"+(options.error?" error":""),h("span",{},message));element.setAttribute("role",options.error?"alert":"status");for(let[label,action]of Object.entries(options.actions??{}))element.append(h("button",{onclick:()=>{element.remove(),action()}},label));return toasts.append(element),setTimeout(()=>element.remove(),options.timeout??(options.error?8000:5000)),element}function panel(anchor,className,...children){let element=div("panel "+className,...children);return layer.append(element),place(element,anchor),element}function place(element,anchor,over=!1){let width=element.offsetWidth,left=Math.max(scrollX+8,Math.min(anchor.left,scrollX+innerWidth-width-8)),top=over?anchor.top:anchor.bottom+6;if(!over&&top+element.offsetHeight>scrollY+innerHeight-8&&anchor.top-element.offsetHeight-6>scrollY)top=anchor.top-element.offsetHeight-6;element.style.left=`${left}px`,element.style.top=`${top}px`}function box(rect,className,label){let element=div("box "+className);if(Object.assign(element.style,{left:`${rect.left}px`,top:`${rect.top}px`,width:`${rect.width}px`,height:`${rect.height}px`}),layer.append(element),!label)return[element];let tag=div("label");if(tag.append(label[0]),label[1])tag.append(h("span",{className:"where"},label[1]));return Object.assign(tag.style,{left:`${rect.left}px`,top:`${rect.top}px`}),layer.append(tag),[element,tag]}async function copy(text){try{await navigator.clipboard.writeText(text)}catch{let area=h("textarea",{},text);shadow.append(area),area.select(),document.execCommand("copy"),area.remove()}}function storage(key,fallback){try{let value=localStorage.getItem(`tensaku:${key}`);return value?JSON.parse(value):fallback}catch{return fallback}}function store(key,value){try{localStorage.setItem(`tensaku:${key}`,JSON.stringify(value))}catch{}}function activeInShadow(){return shadow.activeElement}var listeners=[];function onRefresh(listener){listeners.push(listener)}function permanent(node){return node instanceof Element&&(node.hasAttribute("data-turbo-permanent")||node.hasAttribute("data-tensaku-permanent")||node.hasAttribute("data-tensaku-ui"))}function herbDevServer(){return Boolean(document.querySelector('meta[name="herb-dev-server-port"]'))}function replaceText(nodes,from,to){let normal=(text)=>text.replace(/\s+/g," ").trim(),target=normal(from);if(!target)return;for(let node of nodes)if(normal(node.data)===target){let lead=node.data.match(/^\s*/)[0],trail=node.data.match(/\s*$/)[0];node.data=lead+to.trim()+trail}else if(node.data.includes(from)&&from.trim())node.data=node.data.replace(from,to)}async function refresh(kind){if(meta().method!=="GET"){toast("Saved. This page came from a form submission, so reload to check it.",{timeout:7000});return}if(kind==="template"&&herbDevServer())return;try{let response=await fetch(location.href,{headers:{Accept:"text/html","X-Tensaku-Refresh":"1"},credentials:"same-origin"});if(!response.ok)throw Error(`HTTP ${response.status}`);let html=await response.text(),next=new DOMParser().parseFromString(html,"text/html");morph(next)}catch(error){toast(`Saved, but refreshing the page failed (${error.message}). Reload to check.`,{error:!0})}}function changedByUser(element){if(element instanceof HTMLInputElement){if(element.type==="checkbox"||element.type==="radio")return element.checked!==element.defaultChecked;return element.type!=="file"&&element.value!==element.defaultValue}if(element instanceof HTMLTextAreaElement)return element.value!==element.defaultValue;if(element instanceof HTMLOptionElement)return element.selected!==element.defaultSelected;if(element instanceof HTMLSelectElement)return Array.from(element.options).some((option)=>option.selected!==option.defaultSelected);return!1}var FORM_STATE=new Set(["value","checked","selected"]);function morph(next){let lazyFrames=Array.from(document.querySelectorAll("turbo-frame[src]"));if(Idiomorph.morph(document.body,next.body,{morphStyle:"outerHTML",ignoreActiveValue:!0,restoreFocus:!0,callbacks:{beforeNodeMorphed:(oldNode)=>!permanent(oldNode)&&!(oldNode instanceof HTMLTextAreaElement&&changedByUser(oldNode)),beforeAttributeUpdated:(name,element)=>!(FORM_STATE.has(name)&&changedByUser(element)),beforeNodeRemoved:(node)=>!permanent(node)}}),next.title)document.title=next.title;for(let frame of lazyFrames)if(frame.isConnected&&typeof frame.reload==="function"&&!frame.hasAttribute("complete"))frame.reload();listeners.forEach((listener)=>listener())}var undos=new Map,history=[],HISTORY_LIMIT=20;function editHistory(){return history.slice().reverse().map((entry)=>({label:entry.label,at:entry.at,file:entry.file,undone:entry.undone,canUndo:!entry.undone&&undos.get(entry.key)===entry.undo,run:()=>entry.undo.run().catch(report)}))}var open=null;function undoFor(element){let key=undoKey(element);return key?undos.get(key):void 0}function undoKey(element){let translation=translationOf(element);return element.getAttribute(STAMP)??element.getAttribute(MARKDOWN)??(translation?`${translation.locale}.${translation.key}`:null)}var anonymousUndos=0,composing=(event)=>event.isComposing||event.keyCode===229;function isEditing(){return open!==null}function closeEditor(){open?.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)}}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})}var normal=(text)=>text.replace(/\s+/g," ").trim();function assertRendered(element,texts){let rendered=normal(element.textContent??""),from=0;for(let text of texts.map(normal).filter(Boolean)){let at=rendered.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(),open=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)}),open={element:container,save:saveAndClose,close},container.querySelector(".editable")?.focus(),container}function pieceSurface(pieces){let surface=div(""),fields=[];for(let piece of pieces)if(piece.kind==="text"){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")surface.append(chip(`<${piece.tag}>${piece.label?" "+piece.label:""}`,"Edit this element on its own"));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),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,isUndo=!1){let result=await api("POST","/text",{stamp,edits:changes.map(({piece,text})=>({start:piece.start,end:piece.end,original:piece.raw,text}))}),nodes=Array.from(document.querySelectorAll(`[${STAMP}="${CSS.escape(stamp)}"]`)).flatMap((el)=>Array.from(el.childNodes).filter((node)=>node.nodeType===Node.TEXT_NODE));changes.forEach(({piece,text})=>replaceText(nodes,piece.text,text));let undo;if(!isUndo)undo=remember(element,`Undo edit in ${stamp}`,async()=>{let texts=(await api("GET","/source"+query({stamp}))).pieces.filter((p)=>p.kind==="text"),reverse=changes.map(({piece,text})=>{let now=texts[piece.index??-1];if(!now||now.text!==text)throw new ApiError("The text changed since the edit, so it can't be undone here.",409,!0);return{piece:{...now,index:piece.index},text:piece.text}});await saveTemplate(element,stamp,reverse,!0)});done(result,"template",undo)}async function editAttributes(element){let stamp=stampOf(element),description=stamp?await api("GET","/source"+query({stamp:stamp.value})):null,names=editableAttributes(element),rows=[],savers=[],templateFields=[];for(let name of names){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 saveTranslation(element,key,entry.value,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 current=el.getAttribute(name);if(current!==null)el.setAttribute(name,current.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 undo=remember(element,`Undo ${Array.from(new Set(saved.map((s)=>s.name))).join(", ")}`,async()=>{for(let{name,index,from,to}of saved){let now=(await api("GET","/source"+query({stamp}))).attributes.find((a)=>a.name===name)?.pieces.filter((p)=>p.kind==="text")[index];if(!now||now.text!==to)throw new ApiError("The attribute changed since the edit, so it can't be undone here.",409,!0);await api("POST","/attribute",{stamp,name,start:now.start,end:now.end,original:now.raw,text:from})}done({changed:!0},"template")});done({...last,changed:!0},"template",undo)}}}var INTERPOLATION=/(%\{[^}]+\})/;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 text=main.read();if(text!==entry.value)await saveTranslation(element,key,entry.value,text),entry.value=text;for(let other of otherReaders){let value=other.read();if(value===other.entry.value)continue;await api("POST","/translation",{locale:other.locale,key:key.key,original:other.entry.value,text:value}),other.entry.value=value}},extra)}async function saveTranslation(element,key,original,text,isUndo=!1){let result=await api("POST","/translation",{locale:key.locale,key:key.key,original,text});if(!INTERPOLATION.test(original))replaceText(nodesForKey(key),original,text),elementsWithAttributeKey(key).forEach(({element:el,name})=>{if(el.getAttribute(name)===original)el.setAttribute(name,text)});let undo=isUndo?void 0:remember(element,`Undo ${key.key}`,()=>saveTranslation(element,key,text,original,!0));done(result,"translation",undo)}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(`
|
|
514
|
-
`).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,!1,tag)})}async function saveMarkdown(element,range,original,prefix,text,previous,isUndo=!1,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 undo;if(!isUndo)undo=remember(element,"Undo Markdown edit",async()=>{let[,path,startLine,startColumn]=range.match(/^(.+):(\d+):(\d+)-/),source=prefix+text,lines=source.split(`
|
|
515
|
-
`),endLine=Number(startLine)+lines.length-1,endColumn=(lines.length===1?Number(startColumn)-1:0)+utf8Length(lines[lines.length-1]);await saveMarkdown(element,`${path}:${startLine}:${startColumn}-${endLine}:${endColumn}`,source,prefix,previous,text,!0,tag)});done(result,"markdown",undo)}function remember(element,label,run){let key=undoKey(element)??`anonymous:${++anonymousUndos}`,entry={key,label:label.replace(/^Undo /,""),at:new Date,undone:!1,undo:{label,run:async()=>{}}};if(entry.undo={label,run:async()=>{undos.delete(key),entry.undone=!0,await run()}},undos.set(key,entry.undo),history.push(entry),history.length>HISTORY_LIMIT)history.shift();return entry.undo}function done(result,kind,undo){if(!result.changed)return;let entry=undo?history.find((item)=>item.undo===undo):void 0;if(entry&&!entry.file)entry.file=result.file;if(toast(`Saved ${result.file??""}`.trim(),{actions:undo?{Undo:()=>{if(Array.from(undos.values()).includes(undo))undo.run().catch(report);else toast("That edit was changed again, so it can't be undone from here.")}}:void 0}),result.warning)toast(result.warning,{timeout:8000});refresh(kind)}function undo(element){undoFor(element)?.run().catch(report)}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}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"/>',gear:'<circle cx="12" cy="12" r="3"/><path d="M12 2.8v2.4M12 18.8v2.4M2.8 12h2.4M18.8 12h2.4M5.5 5.5l1.7 1.7M16.8 16.8l1.7 1.7M5.5 18.5l1.7-1.7M16.8 7.2l1.7-1.7"/>',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 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 DEFAULTS={copyFormat:"detailed",notify:!1,compact:!1},current={...DEFAULTS,...storage("settings",{})},listeners2=[],settings=()=>current,onSettings=(listener)=>{listeners2.push(listener),listener(current)};function changeSettings(change){current={...current,...change},store("settings",current),listeners2.forEach((listener)=>listener(current))}var notes=[],openCount=0,agent={connected:!1,seen_at:null},pinLayer=div("pins");layer.append(pinLayer);var countListeners=[],agentListeners=[],onCount=(listener)=>countListeners.push(listener),onAgent=(listener)=>agentListeners.push(listener);function setPinsHidden(hidden){pinLayer.hidden=hidden}async function deleteAll(){let ids=notes.map((note)=>note.id);for(let id of ids)await api("DELETE",`/notes/${id}`);return await load({force:!0}),ids.length}function poll(){let ticks=0;setInterval(()=>{if(ticks++,document.visibilityState==="visible"||settings().notify&&ticks%4===0)load()},4000)}var moveHandler=null,setMoveHandler=(handler)=>{moveHandler=handler};async function moveNote(note,element){localChanges.add(note.id),await api("PATCH",`/notes/${note.id}`,{targets:targetsFor(element)}),toast("Note moved"),await load({force:!0})}var localChanges=new Set;function announce(note,what){let who=note.agent??note.thread?.filter((entry)=>entry.from==="agent").pop()?.agent??"The agent",about=`"${note.comment.length>48?note.comment.slice(0,48)+"…":note.comment}"`,text={resolved:`${who} resolved ${about}`,question:`${who} has a question on ${about}`,working:`${who} started on ${about}`,message:`${who} replied on ${about}`}[what];if(toast(text,{actions:{Show:()=>{let rect=anchorFor(note);if(rect)scrollTo({top:Math.max(0,rect.top-120),behavior:"smooth"}),showNote(note,rect)}}}),document.visibilityState!=="visible"&&settings().notify&&"Notification"in window&&Notification.permission==="granted")new Notification("Tensaku",{body:text,tag:`tensaku-${note.id}`})}function announceChanges(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(localChanges.delete(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")announce(note,note.status)}}var currentNotes=()=>notes;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),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 box2=contentRect(element);if(!box2.width||!box2.height)return!1;return Math.max(0,Math.min(box2.right,rect.right)-Math.max(box2.left,rect.left))*Math.max(0,Math.min(box2.bottom,rect.bottom)-Math.max(box2.top,rect.top))/(box2.width*box2.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 noteForm(anchor,targets,extra={},onDone,heading){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?.()},save=async()=>{let comment=textarea.value.trim();if(!comment)return textarea.focus();try{await api("POST","/notes",{url:location.pathname,comment,targets,viewport:`${innerWidth}x${innerHeight}`,...extra}),close(),toast("Note saved"),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(anchor,"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("foot",h("span",{className:"hint"},"⌘↵ saves"),h("button",{type:"button",className:"quiet",onclick:close},"Cancel"),h("button",{type:"button",className:"primary",onclick:save},"Save note")));return textarea.focus(),element}var normalized=(list)=>list.map((note)=>({...note,targets:note.targets??[]})),lastSignature="",loadSequence=0,tokenWarned=!1;async function load({force=!1}={}){let sequence=++loadSequence;try{let data=await api("GET","/notes"+query({url:location.pathname}));if(sequence!==loadSequence)return;tokenWarned=!1,agent=data.agent??{connected:!1,seen_at:null},agentListeners.forEach((listener)=>listener(agent));let signature=location.pathname+JSON.stringify([data.notes,data.open]);if(signature===lastSignature)return;if(lastSignature=signature,!primed)data.notes.forEach((note)=>drawn.set(note.id,note.status));else if(data.notes.length&¬es.length)announceChanges(notes,normalized(data.notes));if(primed=!0,notes=normalized(data.notes),openCount=data.open,sidebarScope==="all"&&sidebar?.isConnected){let all=normalized((await api("GET","/notes")).notes);if(sequence!==loadSequence)return;allNotes=all}}catch(error){if(sequence!==loadSequence)return;if(error instanceof ApiError&&error.status===403&&!tokenWarned)tokenWarned=!0,toast(`${error.message} Notes can't be loaded until then.`,{error:!0,timeout:15000,actions:{Reload:()=>location.reload()}});return}if(countListeners.forEach((listener)=>listener(openCount)),drawPins(),sidebar?.isConnected&&(force||!sidebar.contains(activeInShadow())))renderSidebar()}function phraseRects(note){let target=note.targets.find((t)=>t.kind==="text"&&t.text&&t.stamp),element=target&&Array.from(document.querySelectorAll(`[${STAMP}="${CSS.escape(target.stamp)}"]`)).find((el)=>el.textContent?.includes(target.text));if(!target||!element)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 targetElement(target){let selector=target.stamp?`[${STAMP}="${CSS.escape(target.stamp)}"]`:target.md?`[${MARKDOWN}="${CSS.escape(target.md)}"]`:null;if(!selector)return null;let elements=Array.from(document.querySelectorAll(selector));if(elements.length<2||!target.text)return elements[0]??null;let text=target.text.replace(/…$/,"");return elements.find((element)=>visibleText(element,300)===target.text)??elements.find((element)=>visibleText(element,300).startsWith(text))??elements.find((element)=>target.kind==="text"&&element.textContent?.includes(text))??elements[0]}var drawn=new Map,primed=!1;function drawPins(){pinLayer.replaceChildren(),notes.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 rect=phrase.length?phrase[phrase.length-1]: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"):String(index+1));Object.assign(pin.style,{left:`${rect.right}px`,top:`${rect.top}px`}),pin.addEventListener("click",(event)=>{event.stopPropagation(),showNote(note,rect)}),pinLayer.append(pin)})}function noteCard(note,onChange){let actions=div("row"),attempt=async(run)=>{try{return await run(),!0}catch(error){return localChanges.delete(note.id),toast(error.message,{error:!0}),!1}},update=(body)=>attempt(async()=>{localChanges.add(note.id),await api("PATCH",`/notes/${note.id}`,body),await load({force:!0}),onChange()}),remove=()=>attempt(async()=>{await api("DELETE",`/notes/${note.id}`),await load({force:!0}),onChange()}),copyNote=()=>attempt(async()=>{await copy(await api("GET","/notes.md"+query({id:note.id,format:settings().copyFormat==="short"?"short":void 0}))),toast("Copied note as Markdown")});actions.append(h("button",{type:"button",onclick:copyNote},"Copy"));let comment=h("div",{className:"comment"},note.comment),startEditing=()=>{let field2=h("textarea",{rows:3,"aria-label":"Edit note"},note.comment),saveEdit=async()=>{let value=field2.value.trim();if(!value)return field2.focus();if(value===note.comment)return stopEditing();if(await update({comment:value,status:"open",reply:""}))toast("Note updated")},stopEditing=()=>{editing.replaceWith(comment),actions.hidden=!1};field2.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",field2,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,field2.focus(),field2.setSelectionRange(field2.value.length,field2.value.length)};actions.append(h("button",{type:"button",onclick:startEditing},"Edit"));let here=note.url===location.pathname;if(here&&moveHandler)actions.append(h("button",{type:"button",onclick:()=>{onChange(),moveHandler(note)}},"Move"));if(note.status==="resolved")actions.append(h("button",{type:"button",onclick:remove},"Dismiss"),h("button",{type:"button",onclick:()=>update({status:"open"})},"Reopen"));else actions.append(h("button",{type:"button",onclick:()=>update({status:"resolved"})},"Resolve"),h("button",{type:"button",onclick:remove},"Delete"));let answer=note.status!=="resolved"?h("textarea",{rows:2,placeholder:note.status==="question"?"Answer the question":"Add a message for the agent","aria-label":"Message"}):null;if(answer)answer.addEventListener("keydown",(event)=>event.stopPropagation()),actions.append(h("button",{type:"button",className:"primary",onclick:()=>answer.value.trim()&&update({message:answer.value.trim(),status:note.status==="question"?"open":void 0})},note.status==="question"?"Answer":"Send"));let thread=note.thread?.length?div("thread",...note.thread.map((entry)=>div(`message ${entry.from}`,h("span",{className:"who"},entry.from==="you"?"You":entry.agent??"Agent"),h("span",{},entry.text)))):note.reply?h("div",{className:`reply ${note.status}`},note.reply):null,missing=here&&!anchorFor(note)?div("missing","Not found on this page any more. Move it to the element it's about."):null,files=note.targets.filter((t)=>t.file).map((t)=>`${t.file}${t.range?":"+t.range.split("-")[0]:""}`);return div(`postit note-card ${note.status}`,div("row",h("span",{className:`status ${note.status}`},note.status==="resolved"?icon("check"):null,note.status==="working"?`${note.agent??"agent"} working`:note.status),h("span",{className:"meta"},Array.from(new Set(files)).join(", "))),comment,thread,missing,answer,actions)}var shown=null;function showNote(note,rect){shown?.remove(),shown=panel(rect,"note-pop",noteCard(note,()=>shown?.remove()));let close=(event)=>{if(!event.composedPath().includes(shown))shown?.remove(),document.removeEventListener("pointerdown",close,!0)};setTimeout(()=>document.addEventListener("pointerdown",close,!0))}var sidebar=null;function toggleSidebar(force){if(!(force??!sidebar?.isConnected)){sidebar?.remove();return}sidebar??=div("sidebar"),sidebar.setAttribute("role","complementary"),sidebar.setAttribute("aria-label","Tensaku notes"),fixed.append(sidebar),renderSidebar()}var sidebarOpen=()=>Boolean(sidebar?.isConnected),sidebarScope="page",allNotes=[];async function showScope(scope){if(sidebarScope=scope,scope==="all")allNotes=normalized((await api("GET","/notes")).notes);renderSidebar()}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=(scope,text)=>h("button",{type:"button",role:"tab","aria-selected":String(sidebarScope===scope),onclick:()=>showScope(scope)},text),body;if(sidebarScope==="page")body=notes.length?notes.map((note)=>noteCard(note,()=>{})):[div("empty","No notes on this page. Select an element or drag over an area to add one.")];else{let pages=Array.from(new Set(allNotes.map((note)=>note.url)));body=pages.length?pages.flatMap((url)=>[h("a",{className:`page${url===location.pathname?" current":""}`,href:url},url,h("span",{},String(allNotes.filter((note)=>note.url===url).length))),...allNotes.filter((note)=>note.url===url).map((note)=>noteCard(note,()=>{}))]):[div("empty","No notes yet.")]}sidebar.replaceChildren(h("header",{},h("strong",{},sidebarScope==="page"?`Notes on ${location.pathname}`:"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")),div("row",h("button",{type:"button",onclick:()=>copyAll(!1)},"Copy page notes"),h("button",{type:"button",onclick:()=>copyAll(!0)},`Copy all open (${openCount})`)),...body)}var pending=[];function onDocument(type,listener,options){pending.push(()=>document.addEventListener(type,listener,options))}function onWindow(type,listener){pending.push(()=>addEventListener(type,listener))}var mode="off",hoverBoxes=[],editBoxes=[],menu=null,drag=null,suppressClick=!1,count=h("span",{className:"count",hidden:!0}),corner=h("button",{className:"corner",type:"button",title:"Tensaku","aria-label":"Tensaku","aria-expanded":"false"},"添",count),INK={highlighter:"#ffe14d",pen:"#e0344f",pad:"#fff1a1"};function tool(name,ink,text,shortcut){let tip=h("span",{className:"tip","aria-hidden":"true"},text,shortcut?h("kbd",{},shortcut):null),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}var shortcutLabel=()=>meta().shortcut.replace(/Key(\w)/,"$1").replace(/Alt/i,"⌥").replace(/Shift/i,"⇧").replace(/Ctrl/i,"⌃").replace(/Meta|Cmd/i,"⌘").replace(/\+/g,""),buttons={inspect:tool("highlighter",INK.highlighter,"Select",shortcutLabel()),edit:tool("pen",INK.pen,"Edit"),notes:tool("pad",INK.pad,"Notes")},notesBadge=h("span",{className:"badge",hidden:!0});buttons.notes.append(notesBadge);function action(name,text,shortcut){return h("button",{type:"button",className:"tool","aria-label":text},icon(name),h("span",{className:"tip","aria-hidden":"true"},text,shortcut?h("kbd",{},shortcut):null))}var setTip=(button,text)=>{button.setAttribute("aria-label",text),button.querySelector(".tip").firstChild.textContent=text},pinsTool=action("eye","Hide pins"),clearTool=action("trash","Delete this page's notes"),historyTool=action("history","Edit history"),settingsTool=action("gear","Settings"),closeTool=action("close","Close","Esc");closeTool.setAttribute("aria-label","Close Tensaku");var agentLight=h("span",{className:"agent-light",role:"status",hidden:!0},h("span",{className:"tip"},"Agent connected")),toolbar=div("toolbar",agentLight,buttons.inspect,buttons.edit,buttons.notes,div("sep"),pinsTool,clearTool,historyTool,settingsTool,div("sep"),closeTool);toolbar.hidden=!0;var dock=div("dock",toolbar,corner);fixed.append(dock);function placeDock(){let position=storage("dock",{right:16,bottom:16});dock.style.right=`${Math.min(Math.max(position.right,4),innerWidth-44)}px`,dock.style.bottom=`${Math.min(Math.max(position.bottom,4),innerHeight-44)}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(toolbar.hidden=!toolbar.hidden,corner.setAttribute("aria-expanded",String(!toolbar.hidden)),toolbar.hidden)setMode("off")});buttons.inspect.addEventListener("click",()=>setMode(mode==="inspect"?"off":"inspect"));buttons.edit.addEventListener("click",()=>setMode(mode==="edit"?"off":"edit"));buttons.notes.addEventListener("click",()=>{toggleSidebar(),syncButtons()});var pinsHidden=storage("pinsHidden",!1);function syncPins(){setPinsHidden(pinsHidden),pinsTool.setAttribute("aria-pressed",String(pinsHidden)),pinsTool.replaceChild(icon(pinsHidden?"eye-off":"eye"),pinsTool.querySelector("svg")),setTip(pinsTool,pinsHidden?"Show pins":"Hide pins")}pinsTool.addEventListener("click",()=>{pinsHidden=!pinsHidden,store("pinsHidden",pinsHidden),syncPins()});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{let deleted=await deleteAll();toast(`Deleted ${deleted} ${deleted===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")}onAgent((agent2)=>{agentLight.hidden=!agent2.connected,corner.classList.toggle("agent",agent2.connected);let names=agent2.names??[];agentLight.firstChild.textContent=names.length?`${names.join(", ")} connected`:"Agent connected"});var popover=null,popoverTool=null;function closePopover(){popover?.remove(),popover=null,popoverTool?.setAttribute("aria-pressed","false"),popoverTool=null}function openPopover(tool2,render){let same=popoverTool===tool2;if(closePopover(),same)return;popover=div("popover",...render()),popover.addEventListener("keydown",(event)=>event.stopPropagation()),dock.append(popover),popoverTool=tool2,tool2.setAttribute("aria-pressed","true")}onDocument("pointerdown",(event)=>{if(popover&&!event.composedPath().some((node)=>node===popover||node===popoverTool))closePopover()},!0);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`};function renderHistory(){let entries=editHistory();return[h("h3",{},"Edit history",h("span",{className:"where"},"Saves since this page loaded. Each element can undo its latest edit.")),...entries.length?entries.map((entry)=>div(`entry${entry.undone?" undone":""}`,div("what",h("span",{},entry.label),h("span",{className:"where"},`${entry.file??""} · ${ago(entry.at)}`)),entry.canUndo?h("button",{type:"button",onclick:async()=>{await entry.run(),closePopover()}},"Undo"):h("span",{className:"where"},entry.undone?"undone":"edited again"))):[div("empty","No edits yet.")]]}historyTool.addEventListener("click",()=>openPopover(historyTool,renderHistory));function renderSettings(){let prefs=settings(),choice=(value,text)=>h("button",{type:"button","aria-pressed":String(prefs.copyFormat===value),onclick:()=>{changeSettings({copyFormat:value}),refreshPopover()}},text),check=(checked,text,hint,change)=>{let input=h("input",{type:"checkbox",checked});return input.addEventListener("change",()=>change(input.checked)),h("label",{className:"check"},input,h("span",{},text,h("span",{className:"where"},hint)))};return[h("h3",{},"Settings",h("span",{className:"where"},"Kept in this browser.")),div("setting",h("span",{},"Copy notes as"),div("segmented",choice("detailed","Detailed"),choice("short","One line each"))),check(prefs.notify,"Notify me","When an agent answers while this tab is in the background.",async(on)=>{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}),refreshPopover()}),check(prefs.compact,"Compact button","The corner button stays small until you point at it.",(on)=>changeSettings({compact:on})),div("setting",h("span",{},"Shortcut"),h("kbd",{},shortcutLabel()),h("span",{className:"where"},"config.shortcut in the initializer")),div("setting",h("button",{type:"button",onclick:()=>{store("dock",{right:16,bottom:16}),placeDock()}},"Move the toolbar back to the corner"))]}function refreshPopover(){if(popover&&popoverTool===settingsTool)popover.replaceChildren(...renderSettings())}settingsTool.addEventListener("click",()=>openPopover(settingsTool,renderSettings));onSettings((prefs)=>corner.classList.toggle("compact",prefs.compact));closeTool.addEventListener("click",()=>{toggleSidebar(!1),setMode("off"),toolbar.hidden=!0,corner.setAttribute("aria-expanded","false")});onCount((n)=>{count.hidden=n===0,count.textContent=String(n),notesBadge.hidden=n===0,notesBadge.textContent=String(n),buttons.notes.setAttribute("aria-label",n?`Notes (${n})`:"Notes"),buttons.notes.querySelector(".tip").firstChild.textContent=n?`Notes (${n})`:"Notes"});function syncButtons(){buttons.inspect.setAttribute("aria-pressed",String(mode==="inspect")),buttons.edit.setAttribute("aria-pressed",String(mode==="edit")),buttons.notes.setAttribute("aria-pressed",String(sidebarOpen())),corner.classList.toggle("active",mode!=="off")}function setMode(next){if(mode=next,next!=="inspect"&&picked.length)clearPicked();if(next!=="off")toolbar.hidden=!1,corner.setAttribute("aria-expanded","true");clearHover(),closeMenu(),drawEditBoxes(),document.documentElement.style.cursor=next==="inspect"?cursor("highlighter",INK.highlighter):next==="edit"?cursor("pen",INK.pen):"",syncButtons()}function clearHover(){current2=null,hoverBoxes.forEach((b)=>b.remove()),hoverBoxes=[]}function label(element){let stamp=stampOf(element)??nearestStamp(element),md=element.getAttribute(MARKDOWN),key=translationOf(element),where=key?`${key.locale}.${key.key}`:md?md.split(/:(?=\d+:\d+-)/)[0]+":"+md.split(/:(?=\d+:\d+-)/)[1].split(":")[0]:stamp?`${stamp.file}:${stamp.line}`:"";return[tagLabel(element),where]}var current2=null;function highlight(element){clearHover(),current2=element,hoverBoxes=box(documentRect(element),mode==="edit"?"hover-edit":"",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 typingInPage(){let active=document.activeElement;return active instanceof HTMLElement&&!isUi(active)&&(active.matches("input, textarea, select")||active.isContentEditable)}function keyboardSelect(event){if(mode!=="inspect"||!current2||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(current2,event.key);if(event.preventDefault(),!next)return!0;return highlight(next),next.scrollIntoView({block:"nearest"}),!0}if(event.key==="Enter")return event.preventDefault(),openMenu(current2),!0;if(event.key.toLowerCase()==="c"&&(event.metaKey||event.ctrlKey)&&!getSelection()?.toString())return event.preventDefault(),copy(reference(current2)).then(()=>toast("Copied reference")),!0;return!1}var moving=null;setMoveHandler((note)=>{moving=note,toggleSidebar(!1),setMode("inspect"),syncButtons(),toast("Click the element this note is about. Esc cancels.",{timeout:8000})});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)}var asking=!1,EDITABLE_BATCH=5000;function drawEditBoxes(){if(editBoxes.forEach((b)=>b.remove()),editBoxes=[],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,drawEditBoxes()});return}for(let element of elements)editBoxes.push(...box(documentRect(element),"edit"))}var picked=[],pickedBoxes=[],pickBar=null;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 closeMenu(){menu?.remove(),menu=null}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(`
|
|
516
|
-
`)
|
|
368
|
+
`}),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
|
+
`)},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(`
|
|
371
|
+
`).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
|
+
`)}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();})();
|