tensaku 0.2.2 → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 147e87281f8421a4cf77646bcbfe8152a230f1ea4b1e313bb290769cf49fc0e6
4
- data.tar.gz: 58bf0b7360dbe7570042955a26a3602edc59631ee0de28cee2e56f64c46bf12d
3
+ metadata.gz: 9a473b72e27ddfc1b18e8848593d73387037f3390ac3212d13b265c38fb48254
4
+ data.tar.gz: 9eda493e2c5077d05163fbd25018b633b1085b1cd6f0f0b435ae06503a14c937
5
5
  SHA512:
6
- metadata.gz: 5578d740e98b26eccdb059529559f8adcd76909b8f3722eef6efc491ec0ea9fa05573c290535575dd609d2eb9988e2e93ae5666c9773ba162094dc34122b6a3b
7
- data.tar.gz: f4b24cada858233e727833563c9fe1210bf0793c21569bbd6f9bb5bf542c8d5168119860f5707b22ab129600455a71281759b48f6d81f4e8bd8e677f0975485e
6
+ metadata.gz: c716be67a15686686d732025fc874ba31982c252a7ad5573af5f8e65f7cd191938c0ea7c5bd696909ed315a27c188cfb19f217f2ef324fc9d5de38c4cdc80b99
7
+ data.tar.gz: 8e17e3cb4f815efe6c8d923ed54ef47885a99a817a496262529c89503ffe9111665d5e3ae1f882f66fca5a89a5e2cf4dd151082450f586754f16ad5f96f1e58f
data/CHANGELOG.md CHANGED
@@ -1,5 +1,25 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.3 (2026-11-14)
4
+
5
+ ### Translations
6
+
7
+ - Translation markers are only added while a template renders. Text translated in a controller
8
+ action, such as a flash message, is plain text again: it can't be traced back to its key from the
9
+ page, but code that measures, compares or stores it no longer sees a marker.
10
+
11
+ - A translation that names an asset, such as `image_tag t("hero.image")` with a screenshot per
12
+ locale, resolves again. Its marker made the asset lookup fail with `Propshaft::MissingAssetError`.
13
+ - A page no longer freezes when the app cuts a translated string short, such as a title truncated
14
+ for `og:title`. The cut marker could not be stripped, the overlay wrote the same value back, and
15
+ its observer saw that write as a new change, forever. Cut markers are now stripped, and an
16
+ unchanged value is never written.
17
+ - Markers no longer reach your data. A translated string assigned to a model attribute, such as a
18
+ default category name made in a callback, loses its marker, so it is validated and saved as plain
19
+ text. Before, a length validation could fail, or the marker was stored in the database.
20
+ - A blank translation gets no marker, so `t("step.subtitle").present?` stays false and the page
21
+ doesn't render an empty element that only exists in development.
22
+
3
23
  ## 0.2.2 (2026-11-14)
4
24
 
5
25
  ### Overlay
@@ -1,4 +1,4 @@
1
- (()=>{function meta(){let tag=document.querySelector('meta[name="tensaku"]');return{token:tag?.dataset.tensakuToken??"",root:tag?.dataset.tensakuRoot??"/__tensaku",method:tag?.dataset.tensakuRequest??"GET"}}class ApiError extends Error{status;stale;constructor(message,status,stale){super(message);this.status=status;this.stale=stale}}async function api(method,path,body){let{token,root}=meta(),response=await fetch(root+path,{method,headers:{"Content-Type":"application/json","X-Tensaku-Token":token,Accept:"application/json"},body:body===void 0?void 0:JSON.stringify(body),credentials:"same-origin"}),data=(response.headers.get("content-type")??"").includes("json")?await response.json():await response.text();if(!response.ok){let message=typeof data==="object"&&data?.error?data.error:`Tensaku request failed (${response.status})`;throw new ApiError(message,response.status,Boolean(data?.stale))}return data}var query=(params)=>"?"+new URLSearchParams(Object.entries(params).filter((entry)=>entry[1]!==void 0)).toString(),isApple=/mac|iphone|ipad|ipod/i.test(navigator.platform||navigator.userAgent);var PATHS={highlighter:'<path d="M13.2 4.3l6.5 6.5-8.6 8.6-6.5-6.5z"/><path d="M11 6.6l6.4 6.4"/><path class="ink" d="M4.6 12.9l6.5 6.5-3.4 1.5-4.6-4.6z"/><path class="ink" d="M2.6 22h6.2" stroke-width="2.4"/>',pen:'<path d="M16.6 3.4l4 4-10.8 10.8-4-4z"/><path d="M14.4 5.6l4 4"/><path class="ink" d="M5.8 14.2l4 4-5.6 1.6z"/>',pad:'<path class="ink" d="M4.5 4.5h15v9.8l-5.2 5.2H4.5z"/><path d="M19.5 14.3h-5.2v5.2"/><path d="M8 9h8M8 12h4.5"/>',copy:'<rect x="8.5" y="8.5" width="11" height="11" rx="2.2"/><path d="M15.5 8.5V6.2a1.7 1.7 0 0 0-1.7-1.7H6.2a1.7 1.7 0 0 0-1.7 1.7v7.6a1.7 1.7 0 0 0 1.7 1.7h2.3"/>',close:'<path d="M6.5 6.5l11 11M17.5 6.5l-11 11"/>',code:'<path d="M8.5 7.5L4 12l4.5 4.5M15.5 7.5L20 12l-4.5 4.5"/>',undo:'<path d="M9 14.5L4.5 10 9 5.5"/><path d="M4.5 10h9.2a5.8 5.8 0 0 1 0 11.6H11"/>',tag:'<path d="M3.8 12.6V4.5a.7.7 0 0 1 .7-.7h8.1l7.6 7.6-8.8 8.8z"/><circle cx="8.3" cy="8.3" r="1.4"/>',eye:'<path d="M2.5 12S6 5.5 12 5.5 21.5 12 21.5 12 18 18.5 12 18.5 2.5 12 2.5 12z"/><circle cx="12" cy="12" r="2.8"/>',"eye-off":'<path d="M2.5 12S6 5.5 12 5.5c1.9 0 3.6.7 5 1.6M21.5 12s-3.5 6.5-9.5 6.5c-1.9 0-3.6-.7-5-1.6"/><path d="M4 20L20 4"/>',trash:'<path d="M4.5 7h15M9.5 7V4.8h5V7M6.5 7l.9 12.2a1.6 1.6 0 0 0 1.6 1.3h6a1.6 1.6 0 0 0 1.6-1.3L17.5 7"/><path d="M10 10.5v6M14 10.5v6"/>',history:'<path d="M4 12a8 8 0 1 0 2.4-5.7"/><path d="M4 4.5v3.8h3.8"/><path d="M12 8v4.3l2.8 1.8"/>',sliders:'<path d="M4 8h9M17 8h3M4 16h3M11 16h9"/><circle cx="15" cy="8" r="2.2"/><circle cx="9" cy="16" r="2.2"/>',pause:'<path d="M9 5.5v13M15 5.5v13"/>',play:'<path d="M8 5.5l10 6.5-10 6.5z"/>',plane:'<path d="M20.5 3.5L3.5 10.4l6.6 3 3 6.6z"/><path d="M10.1 13.4l10.4-9.9"/>',"plane-flying":'<path class="ink" d="M20.5 3.5L3.5 10.4l6.6 3 3 6.6z"/><path d="M10.1 13.4l10.4-9.9"/><path d="M3 16.5l3-1.2M4.5 20l3.4-1.6" stroke-width="1.6"/>',check:'<path class="stroke" d="M5 12.8c1.6 1.2 2.9 2.7 3.9 4.6C11 12.3 14.6 8 19.5 5"/>'};function icon(name,ink){let template=document.createElement("template");template.innerHTML=`<svg class="icon icon-${name}" viewBox="0 0 24 24" aria-hidden="true" focusable="false">${PATHS[name]}</svg>`;let svg=template.content.firstElementChild;if(ink)svg.style.setProperty("--ink-color",ink);return svg}function logo(){let template=document.createElement("template");return template.innerHTML='<svg class="logo" viewBox="0 3.65 100 100" aria-hidden="true" focusable="false"><path d="M48.2 48.6L48.9 47.2L49.7 46.4L51.1 45.6L52.5 45.3L54.1 45.3L56.9 46.3L58.5 47.6L60.2 49.9L60.5 50.6L61.3 53.8L61.1 57.4L59.7 61L59.1 61.9L57.8 63.6L56.3 65.1L54.4 66.4L51.2 67.9L48.8 68.5L44.9 68.7L42.3 68.4L39.6 67.7L37 66.5L34.5 65L32.2 63L30.1 60.7L27.6 56.6L26.4 53.5L26 51.8L25.5 48.4L25.4 44.9L25.9 41.3L26.4 39.5L28.5 34.2L30.6 30.9L33.2 27.9L36.3 25.2L38 24L39.8 22.9L43.7 21.2L47.8 19.9L50 19.5L50.7 16.8L51.5 15.6L53.2 13.8L55 12.6L57.8 11.4L59.8 10.8L61.7 10.5L64.7 10.4L69.5 11.2L74 13L75.7 14L78 15.8L80.7 18.6L82.4 21L83.3 22.7L84.1 24.5L85.1 28.4L85.3 30.3L85.1 33.4L84.7 35.4L83.9 37.5L82.3 39.8L80.3 41.2L83.6 42.5L85.4 43.6L86.9 45L88.7 47.2L90.4 50.6L91 52.4L91.7 56.9L91.7 58.8L90.9 63.4L90 66L89.2 67.7L86.6 71.5L83.9 74L82.4 75.1L79 76.8L77.2 77.4L74.2 77.8L73.2 77.8L70.9 77.4L70.6 78.2L68.8 77L69.9 79.8L70 81.2L69.3 84.7L68.4 86.7L67.3 88.4L64.6 91.5L62.2 93.3L58.7 95.2L56.8 95.9L53.9 96.6L48.9 96.9L44 96.1L40.3 94.7L37.7 93.2L35.3 91.4L33.9 89.9L32.1 87.5L31.1 85.6L30.1 82.3L30 81L31 77L28.5 78L25.1 78.3L22.1 77.9L18.5 76.5L15.3 74.4L13.2 72.5L11.4 70.3L9.9 67.9L9.1 66.2L8.2 63.5L7.5 59.8L7.5 56L8.2 52.3L9.6 48.7L12.4 44.7L15.8 42.2L17 41.7L17.4 41.1L19.3 40.9L17.9 39.7L17 38.6L15.6 35.4L15.1 32.4L15.3 28.4L16.3 24.7L18 21.2L20.3 18.1L23.9 14.9L27.2 12.9L29.9 11.8L31.8 11.3L35.6 10.8L39.5 11.1L42.4 11.8L45.2 13.1L46.1 13.7L47.8 15.1L49.4 17L50.1 18.6L50.9 16.6L51.7 15.4L53.4 13.7L55.2 12.5L58.9 11"/></svg>',template.content.firstElementChild}function cursor(name,ink){let svg=`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#1d1b19" stroke-width="1.6" stroke-linejoin="round" stroke-linecap="round"><g fill="#fffdf6">${PATHS[name].replace(/class="ink"/g,`fill="${ink}"`)}</g></svg>`;return`url("data:image/svg+xml,${encodeURIComponent(svg)}") 3 21, crosshair`}var DIGITS=["​","‌","‍","⁠"],PATTERN=/⁣[​‌‍⁠]+⁣/g,nodeKeys=new WeakMap,attributeKeys=new WeakMap;var textNodesOf=(element)=>Array.from(element.childNodes).filter((node)=>node.nodeType===Node.TEXT_NODE);function recordText(node){let parent=node.parentElement;if(!parent)return;let entries=[];textNodesOf(parent).forEach((text,index)=>nodeKeys.get(text)?.forEach((key)=>entries.push([index,key.locale,key.key]))),writeRecord(parent,"data-tensaku-t",entries)}function recordAttributes(element){let entries=Array.from(attributeKeys.get(element)??[]).map(([name,key])=>[name,key.locale,key.key]);writeRecord(element,"data-tensaku-a",entries)}function writeRecord(element,name,entries){let value=JSON.stringify(entries);if(entries.length&&element.getAttribute(name)!==value)element.setAttribute(name,value)}function readRecord(element,name){try{let value=JSON.parse(element.getAttribute(name)??"[]");return Array.isArray(value)?value:[]}catch{return[]}}function restore(root=document){root.querySelectorAll("[data-tensaku-t]").forEach((element)=>{let texts=textNodesOf(element);for(let[index,locale,key]of readRecord(element,"data-tensaku-t")){let node=texts[index];if(!node||nodeKeys.get(node)?.some((k)=>k.key===key&&k.locale===locale))continue;nodeKeys.set(node,[...nodeKeys.get(node)??[],{locale,key}])}}),root.querySelectorAll("[data-tensaku-a]").forEach((element)=>{let map=attributeKeys.get(element)??new Map;for(let[name,locale,key]of readRecord(element,"data-tensaku-a"))if(!map.has(name))map.set(name,{locale,key});if(map.size)attributeKeys.set(element,map)})}function decode(marker){let digits=[...marker.slice(1,-1)].map((char)=>DIGITS.indexOf(char));if(digits.length%4!==0||digits.includes(-1))return null;let bytes=new Uint8Array(digits.length/4);for(let i=0;i<bytes.length;i++){let[a,b,c,d]=digits.slice(i*4,i*4+4);bytes[i]=a<<6|b<<4|c<<2|d}let text=new TextDecoder().decode(bytes),colon=text.indexOf(":");return colon>0?{locale:text.slice(0,colon),key:text.slice(colon+1)}:null}function extract(text){let keys=[];return{text:text.replace(PATTERN,(marker)=>{let key=decode(marker);if(key)keys.push(key);return""}),keys}}function stripText(node){if(!node.data.includes("⁣"))return;let{text,keys}=extract(node.data);if(node.data=text,keys.length){let known=nodeKeys.get(node)??[];nodeKeys.set(node,[...known,...keys.filter((key)=>!known.some((k)=>k.key===key.key&&k.locale===key.locale))]),recordText(node)}}function stripAttributes(element){for(let attribute of Array.from(element.attributes)){if(!attribute.value.includes("⁣"))continue;let{text,keys}=extract(attribute.value);if(element.setAttribute(attribute.name,text),keys.length){let map=attributeKeys.get(element)??new Map;map.set(attribute.name,keys[keys.length-1]),attributeKeys.set(element,map),recordAttributes(element)}}if(element instanceof HTMLTextAreaElement&&element.value.includes("⁣"))element.value=extract(element.value).text}function strip(root){if(root.nodeType===Node.TEXT_NODE)return stripText(root);if(!(root instanceof Element||root instanceof Document||root instanceof DocumentFragment))return;if(root instanceof Element)stripAttributes(root);let walker=document.createTreeWalker(root,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_TEXT);for(let node=walker.nextNode();node;node=walker.nextNode())if(node.nodeType===Node.TEXT_NODE)stripText(node);else stripAttributes(node)}function watch(){if(strip(document.documentElement),document.title.includes("⁣"))document.title=extract(document.title).text;document.addEventListener("turbo:render",()=>restore()),document.addEventListener("turbo:frame-render",()=>restore()),new MutationObserver((records)=>{for(let record of records)if(record.type==="characterData")stripText(record.target);else if(record.type==="attributes")stripAttributes(record.target);else record.addedNodes.forEach((node)=>strip(node))}).observe(document.documentElement,{subtree:!0,childList:!0,characterData:!0,attributes:!0})}function textKeys(element){let found=[],walker=document.createTreeWalker(element,NodeFilter.SHOW_TEXT);for(let node=walker.nextNode();node;node=walker.nextNode()){let keys=nodeKeys.get(node);if(!keys)continue;let owner=node.parentElement?.closest("[data-herb-source], [data-md-source]");if(owner&&owner!==element&&element.contains(owner))continue;keys.forEach((key)=>found.push({node,key}))}return found}function attributeKey(element,name){return attributeKeys.get(element)?.get(name)}function attributeKeyNames(element){return Array.from(attributeKeys.get(element)?.keys()??[])}function nodesForKey(key){let nodes=[],walker=document.createTreeWalker(document.body,NodeFilter.SHOW_TEXT);for(let node=walker.nextNode();node;node=walker.nextNode())if(nodeKeys.get(node)?.some((k)=>k.key===key.key&&k.locale===key.locale))nodes.push(node);return nodes}function elementsWithAttributeKey(key){let found=[];return document.querySelectorAll("*").forEach((element)=>{attributeKeys.get(element)?.forEach((k,name)=>{if(k.key===key.key&&k.locale===key.locale)found.push({element,name})})}),found}var STAMP="data-herb-source",MARKDOWN="data-md-source",SOURCE_SELECTOR=`[${STAMP}], [${MARKDOWN}]`;function parseStamp(value){let match=value?.match(/^(.+):(\d+):(\d+)$/);return match?{file:match[1],line:Number(match[2]),column:Number(match[3]),value}:null}function isUi(node){return node instanceof Element&&Boolean(node.closest("[data-tensaku-ui]"))}function sourceElement(node){let start=node instanceof Element?node:node?.parentElement;if(!start||isUi(start))return null;let group=start.closest("[data-tensaku-group]");if(group)return group;return start.closest(SOURCE_SELECTOR)}function stampOf(element){return parseStamp(element.getAttribute(STAMP))}function nearestStamp(element){return parseStamp(element.closest(`[${STAMP}]`)?.getAttribute(STAMP))}function copiesOf(element){let value=element.getAttribute(STAMP);return value?document.querySelectorAll(`[${STAMP}="${CSS.escape(value)}"]`).length:1}function partialChain(element){let files=[];for(let node=element;node;node=node.parentElement){let stamp=parseStamp(node.getAttribute(STAMP));if(stamp&&files[files.length-1]!==stamp.file)files.push(stamp.file)}return files.filter((file,index)=>files.indexOf(file)===index)}function contextOf(element){return{partials:partialChain(element),controller:element.closest("[data-controller]")?.getAttribute("data-controller")??void 0,frame:element.closest("turbo-frame")?.id??void 0}}function tagLabel(element){let tag=element.tagName.toLowerCase();if(element.id)return`${tag}#${element.id}`;let first=Array.from(element.classList).find((name)=>!name.startsWith("tensaku"));return first?`${tag}.${first}`:tag}function visibleText(element,limit=120){let text=(element instanceof HTMLElement?element.innerText:element.textContent??"").replace(/\s+/g," ").trim();return text.length>limit?text.slice(0,limit-1)+"…":text}function hasOwnText(element){for(let node of Array.from(element.childNodes))if(node.nodeType===Node.TEXT_NODE&&node.textContent.trim())return!0;return!1}var MARKDOWN_EDITABLE=new Set(["p","h1","h2","h3","h4","h5","h6","li","blockquote"]),ATTRIBUTES=["alt","title","placeholder","aria-label","value"],templateText=new Map;function editKind(element){if(translationOf(element))return"translation";if(element.hasAttribute(MARKDOWN)&&MARKDOWN_EDITABLE.has(element.tagName.toLowerCase()))return"markdown";if(element.hasAttribute(STAMP)&&hasOwnText(element)&&templateText.get(element.getAttribute(STAMP))!==!1)return"template";if(editableAttributes(element).length)return"attributes";return null}function translationOf(element){let keys=textKeys(element);if(!keys.length)return null;let own=keys[0].node.data.trim(),all=(element.textContent??"").replace(/\s+/g," ").trim();return own&&all.length<=own.length*2+20?keys[0].key:null}function editableAttributes(element){let names=ATTRIBUTES.filter((name)=>element.hasAttribute(name)).filter((name)=>name!=="value"||element.matches("button, input[type=submit], input[type=button], input[type=reset]")),fromStamp=element.hasAttribute(STAMP)?names:[];return Array.from(new Set([...fromStamp,...attributeKeyNames(element).filter((name)=>ATTRIBUTES.includes(name))]))}function documentRect(element){let rect=element.getBoundingClientRect();return new DOMRect(rect.left+scrollX,rect.top+scrollY,rect.width,rect.height)}function contentRect(element){let outer=documentRect(element),range=document.createRange();range.selectNodeContents(element);let inner=range.getBoundingClientRect();if(!inner.width||!inner.height)return outer;let left=Math.max(outer.left,inner.left+scrollX),top=Math.max(outer.top,inner.top+scrollY);return new DOMRect(left,top,Math.min(outer.right,inner.right+scrollX)-left,Math.min(outer.bottom,inner.bottom+scrollY)-top)}function utf8Length(text){return new TextEncoder().encode(text).length}function typingInPage(){let active=document.activeElement;return active instanceof HTMLElement&&!isUi(active)&&(active.matches("input, textarea, select")||active.isContentEditable)}var classesOf=(element)=>Array.from(element.classList).filter((name)=>!name.startsWith("tensaku")).slice(0,12);function targetsFor(element,selectedText){let block=element.closest(`[${MARKDOWN}]`),stamped=element.closest(`[${STAMP}]`);if(block&&(!stamped||stamped.contains(block)))return[{kind:"markdown",md:block.getAttribute(MARKDOWN)??void 0,text:selectedText||visibleText(element,300),tag:tagLabel(element),context:contextOf(element)}];let stamp=nearestStamp(element),targets=[{kind:selectedText?"text":"element",stamp:stamp?.value,text:selectedText||visibleText(element,300),tag:tagLabel(element),classes:classesOf(element),context:contextOf(element)}],key=translationOf(element)??textKeys(element)[0]?.key;if(key)targets.push({kind:"translation",key:key.key,locale:key.locale,text:visibleText(element,300)});let md=element.closest(`[${MARKDOWN}]`)?.getAttribute(MARKDOWN);if(md)targets.push({kind:"markdown",md,text:visibleText(element,300),tag:tagLabel(element)});return targets}function elementsInArea(rect){let candidates=Array.from(document.querySelectorAll(`[${STAMP}], [${MARKDOWN}]`)).filter((element)=>{if(element===document.body||element.closest("[data-tensaku-ui]"))return!1;let box=contentRect(element);if(!box.width||!box.height)return!1;return Math.max(0,Math.min(box.right,rect.right)-Math.max(box.left,rect.left))*Math.max(0,Math.min(box.bottom,rect.bottom)-Math.max(box.top,rect.top))/(box.width*box.height)>=0.5}),outermost=candidates.filter((element)=>!candidates.some((other)=>other!==element&&other.contains(element)));if(outermost.length)return outermost.slice(0,20);let fallback=document.elementFromPoint(rect.left+rect.width/2-scrollX,rect.top+rect.height/2-scrollY)?.closest(`[${STAMP}], [${MARKDOWN}]`);return fallback?[fallback]:[]}function phraseRects(note){let target=note.targets.find((t)=>t.kind==="text"&&t.text&&t.stamp),element=target&&targetElement(target);if(!target||!element?.textContent?.includes(target.text))return[];let nodes=[],starts=[],all="",walker=document.createTreeWalker(element,NodeFilter.SHOW_TEXT);while(walker.nextNode()){let node=walker.currentNode;starts.push(all.length),nodes.push(node),all+=node.data}let at=all.indexOf(target.text);if(at<0)return[];let end=at+target.text.length,lastIndex=(test)=>{for(let i=starts.length-1;i>=0;i--)if(test(starts[i]))return i;return 0},first=lastIndex((start)=>start<=at),last=lastIndex((start)=>start<end),range=document.createRange();return range.setStart(nodes[first],at-starts[first]),range.setEnd(nodes[last],end-starts[last]),Array.from(range.getClientRects()).filter((r)=>r.width>0).map((r)=>new DOMRect(r.left+scrollX,r.top+scrollY,r.width,r.height))}function anchorFor(note){if(note.rect)return new DOMRect(note.rect.x,note.rect.y,note.rect.width,note.rect.height);for(let target of note.targets){let element=targetElement(target);if(element)return contentRect(element)}return null}function pointFor(note){let target=note.targets.find((t)=>t.point),element=target&&targetElement(target);if(!target?.point||!element)return null;let rect=documentRect(element);return new DOMRect(rect.x+target.point[0]*rect.width,rect.y+target.point[1]*rect.height,0,0)}function targetElement(target){let attribute=target.stamp?STAMP:target.md?MARKDOWN:null,value=target.stamp??target.md;if(!attribute||!value)return null;let elements=Array.from(document.querySelectorAll(`[${attribute}="${CSS.escape(value)}"]`));if(!target.text)return elements[0]??null;let text=target.text.replace(/…$/,""),written=(candidates)=>candidates.find((element)=>visibleText(element,300)===target.text)??candidates.find((element)=>visibleText(element,300).startsWith(text))??candidates.find((element)=>target.kind==="text"&&element.textContent?.includes(text)),here=written(elements);if(here)return here;let tag=target.tag?.split(/[.#]/)[0],sameTag=(element)=>!tag||element.tagName.toLowerCase()===tag,file=value.match(/^(.+?):\d+/)?.[1],inFile=file?Array.from(document.querySelectorAll(`[${attribute}^="${CSS.escape(file)}:"]`)).filter(sameTag):[];return written(inFile)??elements.find(sameTag)??null}var overlay_default=`:host { all: initial; }
1
+ (()=>{function meta(){let tag=document.querySelector('meta[name="tensaku"]');return{token:tag?.dataset.tensakuToken??"",root:tag?.dataset.tensakuRoot??"/__tensaku",method:tag?.dataset.tensakuRequest??"GET"}}class ApiError extends Error{status;stale;constructor(message,status,stale){super(message);this.status=status;this.stale=stale}}async function api(method,path,body){let{token,root}=meta(),response=await fetch(root+path,{method,headers:{"Content-Type":"application/json","X-Tensaku-Token":token,Accept:"application/json"},body:body===void 0?void 0:JSON.stringify(body),credentials:"same-origin"}),data=(response.headers.get("content-type")??"").includes("json")?await response.json():await response.text();if(!response.ok){let message=typeof data==="object"&&data?.error?data.error:`Tensaku request failed (${response.status})`;throw new ApiError(message,response.status,Boolean(data?.stale))}return data}var query=(params)=>"?"+new URLSearchParams(Object.entries(params).filter((entry)=>entry[1]!==void 0)).toString(),isApple=/mac|iphone|ipad|ipod/i.test(navigator.platform||navigator.userAgent);var PATHS={highlighter:'<path d="M13.2 4.3l6.5 6.5-8.6 8.6-6.5-6.5z"/><path d="M11 6.6l6.4 6.4"/><path class="ink" d="M4.6 12.9l6.5 6.5-3.4 1.5-4.6-4.6z"/><path class="ink" d="M2.6 22h6.2" stroke-width="2.4"/>',pen:'<path d="M16.6 3.4l4 4-10.8 10.8-4-4z"/><path d="M14.4 5.6l4 4"/><path class="ink" d="M5.8 14.2l4 4-5.6 1.6z"/>',pad:'<path class="ink" d="M4.5 4.5h15v9.8l-5.2 5.2H4.5z"/><path d="M19.5 14.3h-5.2v5.2"/><path d="M8 9h8M8 12h4.5"/>',copy:'<rect x="8.5" y="8.5" width="11" height="11" rx="2.2"/><path d="M15.5 8.5V6.2a1.7 1.7 0 0 0-1.7-1.7H6.2a1.7 1.7 0 0 0-1.7 1.7v7.6a1.7 1.7 0 0 0 1.7 1.7h2.3"/>',close:'<path d="M6.5 6.5l11 11M17.5 6.5l-11 11"/>',code:'<path d="M8.5 7.5L4 12l4.5 4.5M15.5 7.5L20 12l-4.5 4.5"/>',undo:'<path d="M9 14.5L4.5 10 9 5.5"/><path d="M4.5 10h9.2a5.8 5.8 0 0 1 0 11.6H11"/>',tag:'<path d="M3.8 12.6V4.5a.7.7 0 0 1 .7-.7h8.1l7.6 7.6-8.8 8.8z"/><circle cx="8.3" cy="8.3" r="1.4"/>',eye:'<path d="M2.5 12S6 5.5 12 5.5 21.5 12 21.5 12 18 18.5 12 18.5 2.5 12 2.5 12z"/><circle cx="12" cy="12" r="2.8"/>',"eye-off":'<path d="M2.5 12S6 5.5 12 5.5c1.9 0 3.6.7 5 1.6M21.5 12s-3.5 6.5-9.5 6.5c-1.9 0-3.6-.7-5-1.6"/><path d="M4 20L20 4"/>',trash:'<path d="M4.5 7h15M9.5 7V4.8h5V7M6.5 7l.9 12.2a1.6 1.6 0 0 0 1.6 1.3h6a1.6 1.6 0 0 0 1.6-1.3L17.5 7"/><path d="M10 10.5v6M14 10.5v6"/>',history:'<path d="M4 12a8 8 0 1 0 2.4-5.7"/><path d="M4 4.5v3.8h3.8"/><path d="M12 8v4.3l2.8 1.8"/>',sliders:'<path d="M4 8h9M17 8h3M4 16h3M11 16h9"/><circle cx="15" cy="8" r="2.2"/><circle cx="9" cy="16" r="2.2"/>',pause:'<path d="M9 5.5v13M15 5.5v13"/>',play:'<path d="M8 5.5l10 6.5-10 6.5z"/>',plane:'<path d="M20.5 3.5L3.5 10.4l6.6 3 3 6.6z"/><path d="M10.1 13.4l10.4-9.9"/>',"plane-flying":'<path class="ink" d="M20.5 3.5L3.5 10.4l6.6 3 3 6.6z"/><path d="M10.1 13.4l10.4-9.9"/><path d="M3 16.5l3-1.2M4.5 20l3.4-1.6" stroke-width="1.6"/>',check:'<path class="stroke" d="M5 12.8c1.6 1.2 2.9 2.7 3.9 4.6C11 12.3 14.6 8 19.5 5"/>'};function icon(name,ink){let template=document.createElement("template");template.innerHTML=`<svg class="icon icon-${name}" viewBox="0 0 24 24" aria-hidden="true" focusable="false">${PATHS[name]}</svg>`;let svg=template.content.firstElementChild;if(ink)svg.style.setProperty("--ink-color",ink);return svg}function logo(){let template=document.createElement("template");return template.innerHTML='<svg class="logo" viewBox="0 3.65 100 100" aria-hidden="true" focusable="false"><path d="M48.2 48.6L48.9 47.2L49.7 46.4L51.1 45.6L52.5 45.3L54.1 45.3L56.9 46.3L58.5 47.6L60.2 49.9L60.5 50.6L61.3 53.8L61.1 57.4L59.7 61L59.1 61.9L57.8 63.6L56.3 65.1L54.4 66.4L51.2 67.9L48.8 68.5L44.9 68.7L42.3 68.4L39.6 67.7L37 66.5L34.5 65L32.2 63L30.1 60.7L27.6 56.6L26.4 53.5L26 51.8L25.5 48.4L25.4 44.9L25.9 41.3L26.4 39.5L28.5 34.2L30.6 30.9L33.2 27.9L36.3 25.2L38 24L39.8 22.9L43.7 21.2L47.8 19.9L50 19.5L50.7 16.8L51.5 15.6L53.2 13.8L55 12.6L57.8 11.4L59.8 10.8L61.7 10.5L64.7 10.4L69.5 11.2L74 13L75.7 14L78 15.8L80.7 18.6L82.4 21L83.3 22.7L84.1 24.5L85.1 28.4L85.3 30.3L85.1 33.4L84.7 35.4L83.9 37.5L82.3 39.8L80.3 41.2L83.6 42.5L85.4 43.6L86.9 45L88.7 47.2L90.4 50.6L91 52.4L91.7 56.9L91.7 58.8L90.9 63.4L90 66L89.2 67.7L86.6 71.5L83.9 74L82.4 75.1L79 76.8L77.2 77.4L74.2 77.8L73.2 77.8L70.9 77.4L70.6 78.2L68.8 77L69.9 79.8L70 81.2L69.3 84.7L68.4 86.7L67.3 88.4L64.6 91.5L62.2 93.3L58.7 95.2L56.8 95.9L53.9 96.6L48.9 96.9L44 96.1L40.3 94.7L37.7 93.2L35.3 91.4L33.9 89.9L32.1 87.5L31.1 85.6L30.1 82.3L30 81L31 77L28.5 78L25.1 78.3L22.1 77.9L18.5 76.5L15.3 74.4L13.2 72.5L11.4 70.3L9.9 67.9L9.1 66.2L8.2 63.5L7.5 59.8L7.5 56L8.2 52.3L9.6 48.7L12.4 44.7L15.8 42.2L17 41.7L17.4 41.1L19.3 40.9L17.9 39.7L17 38.6L15.6 35.4L15.1 32.4L15.3 28.4L16.3 24.7L18 21.2L20.3 18.1L23.9 14.9L27.2 12.9L29.9 11.8L31.8 11.3L35.6 10.8L39.5 11.1L42.4 11.8L45.2 13.1L46.1 13.7L47.8 15.1L49.4 17L50.1 18.6L50.9 16.6L51.7 15.4L53.4 13.7L55.2 12.5L58.9 11"/></svg>',template.content.firstElementChild}function cursor(name,ink){let svg=`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#1d1b19" stroke-width="1.6" stroke-linejoin="round" stroke-linecap="round"><g fill="#fffdf6">${PATHS[name].replace(/class="ink"/g,`fill="${ink}"`)}</g></svg>`;return`url("data:image/svg+xml,${encodeURIComponent(svg)}") 3 21, crosshair`}var DIGITS=["​","‌","‍","⁠"],PATTERN=/⁣[​‌‍⁠]+⁣/g,CUT=/⁣[​‌‍⁠]*/g,nodeKeys=new WeakMap,attributeKeys=new WeakMap;var textNodesOf=(element)=>Array.from(element.childNodes).filter((node)=>node.nodeType===Node.TEXT_NODE);function recordText(node){let parent=node.parentElement;if(!parent)return;let entries=[];textNodesOf(parent).forEach((text,index)=>nodeKeys.get(text)?.forEach((key)=>entries.push([index,key.locale,key.key]))),writeRecord(parent,"data-tensaku-t",entries)}function recordAttributes(element){let entries=Array.from(attributeKeys.get(element)??[]).map(([name,key])=>[name,key.locale,key.key]);writeRecord(element,"data-tensaku-a",entries)}function writeRecord(element,name,entries){let value=JSON.stringify(entries);if(entries.length&&element.getAttribute(name)!==value)element.setAttribute(name,value)}function readRecord(element,name){try{let value=JSON.parse(element.getAttribute(name)??"[]");return Array.isArray(value)?value:[]}catch{return[]}}function restore(root=document){root.querySelectorAll("[data-tensaku-t]").forEach((element)=>{let texts=textNodesOf(element);for(let[index,locale,key]of readRecord(element,"data-tensaku-t")){let node=texts[index];if(!node||nodeKeys.get(node)?.some((k)=>k.key===key&&k.locale===locale))continue;nodeKeys.set(node,[...nodeKeys.get(node)??[],{locale,key}])}}),root.querySelectorAll("[data-tensaku-a]").forEach((element)=>{let map=attributeKeys.get(element)??new Map;for(let[name,locale,key]of readRecord(element,"data-tensaku-a"))if(!map.has(name))map.set(name,{locale,key});if(map.size)attributeKeys.set(element,map)})}function decode(marker){let digits=[...marker.slice(1,-1)].map((char)=>DIGITS.indexOf(char));if(digits.length%4!==0||digits.includes(-1))return null;let bytes=new Uint8Array(digits.length/4);for(let i=0;i<bytes.length;i++){let[a,b,c,d]=digits.slice(i*4,i*4+4);bytes[i]=a<<6|b<<4|c<<2|d}let text=new TextDecoder().decode(bytes),colon=text.indexOf(":");return colon>0?{locale:text.slice(0,colon),key:text.slice(colon+1)}:null}function extract(text){let keys=[];return{text:text.replace(PATTERN,(marker)=>{let key=decode(marker);if(key)keys.push(key);return""}).replace(CUT,""),keys}}function stripText(node){if(!node.data.includes("⁣"))return;let{text,keys}=extract(node.data);if(text!==node.data)node.data=text;if(keys.length){let known=nodeKeys.get(node)??[];nodeKeys.set(node,[...known,...keys.filter((key)=>!known.some((k)=>k.key===key.key&&k.locale===key.locale))]),recordText(node)}}function stripAttributes(element){for(let attribute of Array.from(element.attributes)){if(!attribute.value.includes("⁣"))continue;let{text,keys}=extract(attribute.value);if(text!==attribute.value)element.setAttribute(attribute.name,text);if(keys.length){let map=attributeKeys.get(element)??new Map;map.set(attribute.name,keys[keys.length-1]),attributeKeys.set(element,map),recordAttributes(element)}}if(element instanceof HTMLTextAreaElement&&element.value.includes("⁣"))element.value=extract(element.value).text}function strip(root){if(root.nodeType===Node.TEXT_NODE)return stripText(root);if(!(root instanceof Element||root instanceof Document||root instanceof DocumentFragment))return;if(root instanceof Element)stripAttributes(root);let walker=document.createTreeWalker(root,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_TEXT);for(let node=walker.nextNode();node;node=walker.nextNode())if(node.nodeType===Node.TEXT_NODE)stripText(node);else stripAttributes(node)}function watch(){if(strip(document.documentElement),document.title.includes("⁣"))document.title=extract(document.title).text;document.addEventListener("turbo:render",()=>restore()),document.addEventListener("turbo:frame-render",()=>restore()),new MutationObserver((records)=>{for(let record of records)if(record.type==="characterData")stripText(record.target);else if(record.type==="attributes")stripAttributes(record.target);else record.addedNodes.forEach((node)=>strip(node))}).observe(document.documentElement,{subtree:!0,childList:!0,characterData:!0,attributes:!0})}function textKeys(element){let found=[],walker=document.createTreeWalker(element,NodeFilter.SHOW_TEXT);for(let node=walker.nextNode();node;node=walker.nextNode()){let keys=nodeKeys.get(node);if(!keys)continue;let owner=node.parentElement?.closest("[data-herb-source], [data-md-source]");if(owner&&owner!==element&&element.contains(owner))continue;keys.forEach((key)=>found.push({node,key}))}return found}function attributeKey(element,name){return attributeKeys.get(element)?.get(name)}function attributeKeyNames(element){return Array.from(attributeKeys.get(element)?.keys()??[])}function nodesForKey(key){let nodes=[],walker=document.createTreeWalker(document.body,NodeFilter.SHOW_TEXT);for(let node=walker.nextNode();node;node=walker.nextNode())if(nodeKeys.get(node)?.some((k)=>k.key===key.key&&k.locale===key.locale))nodes.push(node);return nodes}function elementsWithAttributeKey(key){let found=[];return document.querySelectorAll("*").forEach((element)=>{attributeKeys.get(element)?.forEach((k,name)=>{if(k.key===key.key&&k.locale===key.locale)found.push({element,name})})}),found}var STAMP="data-herb-source",MARKDOWN="data-md-source",SOURCE_SELECTOR=`[${STAMP}], [${MARKDOWN}]`;function parseStamp(value){let match=value?.match(/^(.+):(\d+):(\d+)$/);return match?{file:match[1],line:Number(match[2]),column:Number(match[3]),value}:null}function isUi(node){return node instanceof Element&&Boolean(node.closest("[data-tensaku-ui]"))}function sourceElement(node){let start=node instanceof Element?node:node?.parentElement;if(!start||isUi(start))return null;let group=start.closest("[data-tensaku-group]");if(group)return group;return start.closest(SOURCE_SELECTOR)}function stampOf(element){return parseStamp(element.getAttribute(STAMP))}function nearestStamp(element){return parseStamp(element.closest(`[${STAMP}]`)?.getAttribute(STAMP))}function copiesOf(element){let value=element.getAttribute(STAMP);return value?document.querySelectorAll(`[${STAMP}="${CSS.escape(value)}"]`).length:1}function partialChain(element){let files=[];for(let node=element;node;node=node.parentElement){let stamp=parseStamp(node.getAttribute(STAMP));if(stamp&&files[files.length-1]!==stamp.file)files.push(stamp.file)}return files.filter((file,index)=>files.indexOf(file)===index)}function contextOf(element){return{partials:partialChain(element),controller:element.closest("[data-controller]")?.getAttribute("data-controller")??void 0,frame:element.closest("turbo-frame")?.id??void 0}}function tagLabel(element){let tag=element.tagName.toLowerCase();if(element.id)return`${tag}#${element.id}`;let first=Array.from(element.classList).find((name)=>!name.startsWith("tensaku"));return first?`${tag}.${first}`:tag}function visibleText(element,limit=120){let text=(element instanceof HTMLElement?element.innerText:element.textContent??"").replace(/\s+/g," ").trim();return text.length>limit?text.slice(0,limit-1)+"…":text}function hasOwnText(element){for(let node of Array.from(element.childNodes))if(node.nodeType===Node.TEXT_NODE&&node.textContent.trim())return!0;return!1}var MARKDOWN_EDITABLE=new Set(["p","h1","h2","h3","h4","h5","h6","li","blockquote"]),ATTRIBUTES=["alt","title","placeholder","aria-label","value"],templateText=new Map;function editKind(element){if(translationOf(element))return"translation";if(element.hasAttribute(MARKDOWN)&&MARKDOWN_EDITABLE.has(element.tagName.toLowerCase()))return"markdown";if(element.hasAttribute(STAMP)&&hasOwnText(element)&&templateText.get(element.getAttribute(STAMP))!==!1)return"template";if(editableAttributes(element).length)return"attributes";return null}function translationOf(element){let keys=textKeys(element);if(!keys.length)return null;let own=keys[0].node.data.trim(),all=(element.textContent??"").replace(/\s+/g," ").trim();return own&&all.length<=own.length*2+20?keys[0].key:null}function editableAttributes(element){let names=ATTRIBUTES.filter((name)=>element.hasAttribute(name)).filter((name)=>name!=="value"||element.matches("button, input[type=submit], input[type=button], input[type=reset]")),fromStamp=element.hasAttribute(STAMP)?names:[];return Array.from(new Set([...fromStamp,...attributeKeyNames(element).filter((name)=>ATTRIBUTES.includes(name))]))}function documentRect(element){let rect=element.getBoundingClientRect();return new DOMRect(rect.left+scrollX,rect.top+scrollY,rect.width,rect.height)}function contentRect(element){let outer=documentRect(element),range=document.createRange();range.selectNodeContents(element);let inner=range.getBoundingClientRect();if(!inner.width||!inner.height)return outer;let left=Math.max(outer.left,inner.left+scrollX),top=Math.max(outer.top,inner.top+scrollY);return new DOMRect(left,top,Math.min(outer.right,inner.right+scrollX)-left,Math.min(outer.bottom,inner.bottom+scrollY)-top)}function utf8Length(text){return new TextEncoder().encode(text).length}function typingInPage(){let active=document.activeElement;return active instanceof HTMLElement&&!isUi(active)&&(active.matches("input, textarea, select")||active.isContentEditable)}var classesOf=(element)=>Array.from(element.classList).filter((name)=>!name.startsWith("tensaku")).slice(0,12);function targetsFor(element,selectedText){let block=element.closest(`[${MARKDOWN}]`),stamped=element.closest(`[${STAMP}]`);if(block&&(!stamped||stamped.contains(block)))return[{kind:"markdown",md:block.getAttribute(MARKDOWN)??void 0,text:selectedText||visibleText(element,300),tag:tagLabel(element),context:contextOf(element)}];let stamp=nearestStamp(element),targets=[{kind:selectedText?"text":"element",stamp:stamp?.value,text:selectedText||visibleText(element,300),tag:tagLabel(element),classes:classesOf(element),context:contextOf(element)}],key=translationOf(element)??textKeys(element)[0]?.key;if(key)targets.push({kind:"translation",key:key.key,locale:key.locale,text:visibleText(element,300)});let md=element.closest(`[${MARKDOWN}]`)?.getAttribute(MARKDOWN);if(md)targets.push({kind:"markdown",md,text:visibleText(element,300),tag:tagLabel(element)});return targets}function elementsInArea(rect){let candidates=Array.from(document.querySelectorAll(`[${STAMP}], [${MARKDOWN}]`)).filter((element)=>{if(element===document.body||element.closest("[data-tensaku-ui]"))return!1;let box=contentRect(element);if(!box.width||!box.height)return!1;return Math.max(0,Math.min(box.right,rect.right)-Math.max(box.left,rect.left))*Math.max(0,Math.min(box.bottom,rect.bottom)-Math.max(box.top,rect.top))/(box.width*box.height)>=0.5}),outermost=candidates.filter((element)=>!candidates.some((other)=>other!==element&&other.contains(element)));if(outermost.length)return outermost.slice(0,20);let fallback=document.elementFromPoint(rect.left+rect.width/2-scrollX,rect.top+rect.height/2-scrollY)?.closest(`[${STAMP}], [${MARKDOWN}]`);return fallback?[fallback]:[]}function phraseRects(note){let target=note.targets.find((t)=>t.kind==="text"&&t.text&&t.stamp),element=target&&targetElement(target);if(!target||!element?.textContent?.includes(target.text))return[];let nodes=[],starts=[],all="",walker=document.createTreeWalker(element,NodeFilter.SHOW_TEXT);while(walker.nextNode()){let node=walker.currentNode;starts.push(all.length),nodes.push(node),all+=node.data}let at=all.indexOf(target.text);if(at<0)return[];let end=at+target.text.length,lastIndex=(test)=>{for(let i=starts.length-1;i>=0;i--)if(test(starts[i]))return i;return 0},first=lastIndex((start)=>start<=at),last=lastIndex((start)=>start<end),range=document.createRange();return range.setStart(nodes[first],at-starts[first]),range.setEnd(nodes[last],end-starts[last]),Array.from(range.getClientRects()).filter((r)=>r.width>0).map((r)=>new DOMRect(r.left+scrollX,r.top+scrollY,r.width,r.height))}function anchorFor(note){if(note.rect)return new DOMRect(note.rect.x,note.rect.y,note.rect.width,note.rect.height);for(let target of note.targets){let element=targetElement(target);if(element)return contentRect(element)}return null}function pointFor(note){let target=note.targets.find((t)=>t.point),element=target&&targetElement(target);if(!target?.point||!element)return null;let rect=documentRect(element);return new DOMRect(rect.x+target.point[0]*rect.width,rect.y+target.point[1]*rect.height,0,0)}function targetElement(target){let attribute=target.stamp?STAMP:target.md?MARKDOWN:null,value=target.stamp??target.md;if(!attribute||!value)return null;let elements=Array.from(document.querySelectorAll(`[${attribute}="${CSS.escape(value)}"]`));if(!target.text)return elements[0]??null;let text=target.text.replace(/…$/,""),written=(candidates)=>candidates.find((element)=>visibleText(element,300)===target.text)??candidates.find((element)=>visibleText(element,300).startsWith(text))??candidates.find((element)=>target.kind==="text"&&element.textContent?.includes(text)),here=written(elements);if(here)return here;let tag=target.tag?.split(/[.#]/)[0],sameTag=(element)=>!tag||element.tagName.toLowerCase()===tag,file=value.match(/^(.+?):\d+/)?.[1],inFile=file?Array.from(document.querySelectorAll(`[${attribute}^="${CSS.escape(file)}:"]`)).filter(sameTag):[];return written(inFile)??elements.find(sameTag)??null}var overlay_default=`:host { all: initial; }
2
2
  * { box-sizing: border-box; }
3
3
  [hidden] { display: none !important; }
4
4
 
data/lib/tensaku/i18n.rb CHANGED
@@ -6,14 +6,17 @@ module Tensaku
6
6
  # A marker is U+2063 (invisible separator), then "locale:key" as UTF-8 bytes written in base 4 with
7
7
  # four zero-width characters, then U+2063 again. Nothing shows if the overlay never runs.
8
8
  #
9
- # Markers are only added while a controller handles an HTML request, never to `number.*`, `date.*`,
10
- # `time.*` and similar keys, never to a value that came from a `default:` instead of the key, and
11
- # never to pluralized lookups. A Ruby comparison against a translated string sees the marker, which
12
- # is the known cost of this technique (development only).
9
+ # Markers are only added while a template of an HTML page renders, never to `number.*`, `date.*`,
10
+ # `time.*` and similar keys, never to a value that came from a `default:` instead of the key, never
11
+ # to pluralized lookups, and never to a blank value: it has no text to edit, and `t(...).present?`
12
+ # must stay false. A Ruby comparison against a translated string sees the marker, which is the
13
+ # known cost of this technique (development only).
13
14
  module I18nMarkers
14
15
  FENCE = "⁣"
15
16
  DIGITS = [ "​", "‌", "‍", "⁠" ].freeze
16
17
  PATTERN = /#{FENCE}[#{DIGITS.join}]+#{FENCE}/o
18
+ # What is left of a marker that the app cut short, such as a title truncated for a meta tag.
19
+ CUT = /#{FENCE}[#{DIGITS.join}]*/o
17
20
  SKIP = /\A(?:number|date|time|datetime|support|i18n|helpers\.submit|errors\.format)(?:\.|\z)/
18
21
 
19
22
  module_function
@@ -41,7 +44,7 @@ module Tensaku
41
44
  end
42
45
 
43
46
  def strip(text)
44
- text.include?(FENCE) ? text.gsub(PATTERN, "") : text
47
+ text.include?(FENCE) ? text.gsub(PATTERN, "").gsub(CUT, "") : text
45
48
  end
46
49
 
47
50
  # The raw value stored for the key, to tell a translation apart from a `default:` or a pluralized
@@ -67,6 +70,7 @@ module Tensaku
67
70
  def translate(locale, key, options = ::I18n::EMPTY_HASH)
68
71
  result = super
69
72
  return result unless I18nMarkers.active? && result.is_a?(String) && !key.nil?
73
+ return result if result.blank?
70
74
 
71
75
  full = ::I18n.normalize_keys(nil, key, options[:scope], options[:separator]).join(".")
72
76
  return result if full.match?(SKIP)
@@ -77,20 +81,65 @@ module Tensaku
77
81
  end
78
82
  end
79
83
 
80
- # Wraps controller actions for HTML requests.
84
+ # A translated file name, such as a screenshot per locale, names an asset rather than text the
85
+ # overlay can edit, so it resolves without its marker. Otherwise the asset lookup misses.
86
+ # Both names, because Rails aliases one to the other and image_path calls the alias.
87
+ module AssetPaths
88
+ %i[asset_path path_to_asset].each do |name|
89
+ define_method(name) do |source, options = {}|
90
+ super(source.is_a?(String) ? I18nMarkers.strip(source) : source, options)
91
+ end
92
+ end
93
+ end
94
+
95
+ # A marker belongs to the page, never to data: a translated string assigned to a model attribute,
96
+ # such as a default category name, loses its marker, so validations, saves and comparisons on the
97
+ # model see the text alone. Both string types, because String has its own cast_value.
98
+ module ModelStrings
99
+ private
100
+
101
+ def cast_value(value)
102
+ super(value.is_a?(String) ? I18nMarkers.strip(value) : value)
103
+ end
104
+ end
105
+
106
+ def page?
107
+ Thread.current[:tensaku_i18n_page] == true
108
+ end
109
+
110
+ def on_page
111
+ previous = Thread.current[:tensaku_i18n_page]
112
+ Thread.current[:tensaku_i18n_page] = true
113
+ yield
114
+ ensure
115
+ Thread.current[:tensaku_i18n_page] = previous
116
+ end
117
+
118
+ # Wraps controller actions for HTML requests. The action itself translates without markers, so
119
+ # a flash message, a model default or anything else it measures, compares or stores stays plain
120
+ # text; Templates turns them on while the page renders.
81
121
  module Controller
82
122
  extend ActiveSupport::Concern
83
123
 
84
124
  included do
85
- prepend_around_action :tensaku_i18n_markers
125
+ prepend_around_action :tensaku_i18n_page
86
126
  end
87
127
 
88
128
  private
89
129
 
90
- def tensaku_i18n_markers(&)
130
+ def tensaku_i18n_page(&)
91
131
  return yield unless request.format&.html?
92
132
 
93
- I18nMarkers.with_markers(&)
133
+ I18nMarkers.on_page(&)
134
+ end
135
+ end
136
+
137
+ # Prepended to ActionView::Template: markers while a template of an HTML page renders.
138
+ module Templates
139
+ def render(view, locals, buffer = nil, **options, &block)
140
+ return super unless I18nMarkers.page? && !I18nMarkers.active?
141
+
142
+ I18nMarkers.with_markers { super(view, locals, buffer, **options, &block) }
94
143
  end
95
144
  end
96
145
  end
@@ -37,10 +37,15 @@ module Tensaku
37
37
  ActiveSupport.on_load(:action_controller_base) do
38
38
  include Tensaku::I18nMarkers::Controller
39
39
  end
40
+ ActiveSupport.on_load(:action_view) do
41
+ prepend Tensaku::I18nMarkers::AssetPaths
42
+ ActionView::Template.prepend(Tensaku::I18nMarkers::Templates)
43
+ end
40
44
  end
41
45
 
42
46
  config.after_initialize do
43
47
  I18n.backend.extend(Tensaku::I18nMarkers::Backend) unless I18n.backend.is_a?(Tensaku::I18nMarkers::Backend)
48
+ [ ActiveModel::Type::ImmutableString, ActiveModel::Type::String ].each { it.prepend(Tensaku::I18nMarkers::ModelStrings) }
44
49
 
45
50
  if (warning = Tensaku::Caches.fragment_cache_warning)
46
51
  Rails.logger.warn("[Tensaku] #{warning}")
@@ -1,3 +1,3 @@
1
1
  module Tensaku
2
- VERSION = "0.2.2"
2
+ VERSION = "0.2.3"
3
3
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: tensaku
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.2.2
4
+ version: 0.2.3
5
5
  platform: ruby
6
6
  authors:
7
7
  - David Afonso