domma-cms 1.26.0 → 1.26.2

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,13 @@
1
1
  # Changelog
2
2
 
3
+ ## [1.26.2] - 2026-10-31
4
+
5
+ - Documentation: the Form Follow-Up tutorial covers file fields (drop area, Several files and Most files, the size cap and accepted types) and copying forms between sites; Blocks covers Convert selection to Domma Block; Site Settings > Theme covers the searchable font pickers, separate site and admin fonts, and licensed Cera Pro and Euclid fonts.
6
+
7
+ ## [1.26.1] - 2026-10-31
8
+
9
+ - SEO: a redirect's "To" box (Add a redirect and the redirect panel) has a drop menu of the site's pages beside it, arranged as a tree by address - pick one, or keep typing any address. Typing filters it; arrow keys and Enter pick. The menu is `plugins/_lib/admin/ui/page-menu.js`, which SEO Pro 0.7.1 uses in its own redirect boxes too.
10
+
3
11
  ## [1.26.0] - 2026-10-31
4
12
 
5
13
  - Forms: fields that show and hide on conditions can now use fourteen more animations - Slide up, Slide down, Slide in from right or left, Zoom, Bubble pop, Bounce, Drop in, Elastic, Flip, Rotate, Swing, Unfold and Blur - beside None, Fade, Slide and Scale. A Preview button in the field's logic panel plays the chosen effect. Visitors who prefer reduced motion see an instant switch.
@@ -117,6 +117,30 @@ Subject Prefix: [Contact Form]</code></pre>
117
117
  <strong>Preview</strong> to play it on a sample. Visitors who ask their device to reduce motion see the
118
118
  field switch straight away.</p>
119
119
 
120
+ <h3>File uploads</h3>
121
+ <p>A <strong>File</strong> field is a drop area: visitors drop a file on it, browse for one or paste it, and
122
+ pictures show a preview. A file of the wrong type or size is refused as soon as it is added, with the
123
+ reason. Multi-step forms keep the file when the visitor goes back a step.</p>
124
+ <ul>
125
+ <li><strong>Several files</strong> lets one field take more than one file; <strong>Most files</strong> sets
126
+ how many (5 unless you change it, up to 20). Every file appears in the submission, the collection entry,
127
+ the email notification and the CSV export.</li>
128
+ <li>The page adds up a submission's files and warns before they pass the server's limit
129
+ (<code>uploads.maxSubmissionBytes</code>, at least 50 MB by default), so a visitor is not refused at the
130
+ end of a long form.</li>
131
+ <li>Forms accept pictures (not SVG), audio, video, PDFs, Office and OpenDocument files, text and CSV, and
132
+ archives. Web pages, SVG files and scripts are always refused. Files are only saved once the submission
133
+ has passed its spam and validation checks.</li>
134
+ </ul>
135
+
136
+ <h3>Copying a form to another site</h3>
137
+ <p>In <a href="#/forms">Data &gt; Forms</a>, choose <strong>Export JSON</strong> from a form's menu. On the
138
+ other site, use <strong>Import</strong> in the banner. The imported form gets its own new, private
139
+ submissions collection; existing forms and collections are never changed, and a form whose address is
140
+ already taken gets a new one. Surveys and Campaigns Pro import and export their definitions the same way,
141
+ without responses or recipients.</p>
142
+ <p>Every setting in the form editor has a <strong>(?)</strong> beside it. Click it for an explanation.</p>
143
+
120
144
  <hr>
121
145
  <p class="text-muted" style="font-size:.9rem;">
122
146
  <a href="#/tutorials">Back to all tutorials</a>
@@ -238,6 +238,13 @@
238
238
  and component. A block used elsewhere changes there too - you are asked the first time. Closing a tab, or
239
239
  leaving with unsaved changes, keeps your work as a draft for that block until you open it again.</p>
240
240
 
241
+ <h3>Making a block from part of a page</h3>
242
+ <p>In the page editor, select the markup you want to reuse, right-click and choose <strong>Convert selection
243
+ to Domma Block...</strong>. Give the block a name (lowercase letters, digits and hyphens). Once the block is
244
+ saved, the selection is replaced with <code>[block template="your-name" /]</code>. A name that is already
245
+ taken is refused rather than overwritten, and the page itself is left unsaved so you can check it before
246
+ you save.</p>
247
+
241
248
  <h3>Copying blocks between sites</h3>
242
249
  <p><strong>Export</strong> on a block's right-click menu downloads it as a <code>&lt;name&gt;.dmblock.json</code>
243
250
  file, with its HTML and CSS. On the other site, use <strong>Import</strong> in the Blocks banner. If a block
@@ -126,6 +126,15 @@
126
126
  Page Details. Picking an admin theme shows it at once so you can try them on - Save makes it
127
127
  everyone's, and leaving without saving puts the saved theme back.</p>
128
128
 
129
+ <p>Every font choice (the site font, the admin font, your editor lettering, Highlight text, Scribe
130
+ and a menu's font) is a searchable picker that shows each font's name and a sample in that
131
+ font. The site font and the admin font are set separately. Fonts such as Urbanist, Nunito
132
+ Sans and Mulish load from Google Fonts when chosen. <strong>Cera Pro</strong> and the
133
+ <strong>Euclid</strong> families are licensed fonts: put your own font files and a stylesheet
134
+ under <code>/public/fonts/</code>, enter the stylesheet in <strong>Licensed font
135
+ stylesheet</strong>, then pick them like any other font. They are never requested from Google
136
+ Fonts, updates leave them alone, and no commercial font files are bundled.</p>
137
+
129
138
  <h3>Dates and times</h3>
130
139
  <p>The admin shows dates as dd/mm/yyyy and times on a 24-hour clock (dd/mm/yyyy HH:mm), whatever
131
140
  the browser's language. Recent items may read "3 days ago" or "tomorrow at 09:00". Stored
@@ -186,6 +186,8 @@
186
186
  .sox-add { display: flex; gap: .4rem; flex-wrap: wrap; align-items: center; margin: 0; }
187
187
  .sox-add .form-input { width: auto; flex: 1 1 11rem; padding: .25rem .5rem; font-size: var(--dm-text-sm); }
188
188
  .sox-add .sox-code { flex: 0 1 11rem; }
189
+ .sox-add .dm-pm-wrap { flex: 1 1 11rem; }
190
+ .sox-add .dm-pm-wrap > .form-input { width: 100%; }
189
191
  .sox-code { font-family: var(--dm-font-mono, monospace); font-size: var(--dm-text-xs); background: color-mix(in srgb, var(--dm-text) 7%, transparent); padding: .5rem .65rem; border-radius: var(--dm-radius-sm); white-space: pre-wrap; margin: 0; max-height: 16rem; overflow: auto; }
190
192
  /* the page editor (slideover) */
191
193
  .sox-form { display: flex; flex-direction: column; gap: 1.1rem; padding-bottom: 1rem; }
@@ -1,18 +1,18 @@
1
- import{apiRequest as ys}from"../api.js";import{addBannerAction as xs}from"../lib/plugin-chrome.js";import{helpPopovers as ws}from"../lib/help-popover.js";import{onceClosed as ks,openMenuAt as Ms,viewLifetime as $s}from"../lib/tool-kit.js";import{snippet as Ss}from"../lib/seo-analyse.js";import{checkRule as xt,matchRedirect as Es}from"../lib/seo-redirects.js";import{checkSettings as Ts,mergeDefaults as wt,ORG_TYPES as Cs}from"../lib/seo-settings.js";import{pickMedia as ze}from"../lib/media-picker.js";import{checkSeoDefaults as Os,seoDefaults as Ls}from"../lib/seo-defaults.js";import{mountGoogleBusiness as Rs}from"../lib/google-business-panel.js";import{fmtDate as Is,fmtDateTime as Fe}from"../lib/dates.js";import{SHAPES as As,whileLoading as Ps}from"../lib/loading.js";import{countText as ve,draftAction as js,draftKey as Je,filterPages as Ds,fingerprint as J,pageCounts as Ns,restoreQuestion as Ye,usableDraft as kt}from"../lib/seo-arrange.js";const qs="/seo",Qe=/^#\/seo(\/[a-z0-9-]+)?\/?(\?.*)?$/,Mt=["overview","redirects","sitemap"],Us="#/seo",Bs={pass:"\u2713",warn:"!",fail:"\u2715",info:"i"},_s={301:"301 moved",302:"302 for now",307:"307 for now",308:"308 moved",410:"410 gone"},Hs={apiRequest:ys,addBannerAction:xs,helpPopovers:ws,onceClosed:ks,openMenuAt:Ms,viewLifetime:$s},Ws=async()=>Hs,L=i=>String(i??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;");function Ve(i){const d=document.createElement("template");return d.innerHTML=i.trim(),d.content.firstElementChild}async function ge(i,d){try{await navigator.clipboard.writeText(i),E.toast(`Copied ${d}.`,{type:"success"})}catch{E.toast(`Could not copy - ${i}`,{type:"warning",duration:6e3})}}const R={user(){try{return S.get("auth_user")?.id||""}catch{return""}},get(i){try{return i?S.get(i)??null:null}catch{return null}},set(i,d){try{i&&S.set(i,d)}catch{}},drop(i){try{i&&(S.remove?S.remove(i):S.set(i,null))}catch{}},keys(i){try{return(S.keys?.()||[]).filter(d=>d.startsWith(i))}catch{return[]}}},Ks=()=>new Promise(i=>setTimeout(i,0)),Xe=async(i,d)=>(await Ks(),E.confirm(L(i),d)),Ze=i=>Xe(i.text,{title:i.title,confirmText:i.confirmText,cancelText:i.cancelText});function $t(){try{window.dispatchEvent(new CustomEvent("dm:sidebar-count",{detail:{url:Us}}))}catch{}}const St=i=>typeof i!="number"?"":i>=85?"good":i>=60?"poor":"bad",Et=i=>i?Is(i):"",Tt=i=>{if(!i)return"";const d=Math.round((Date.now()-Date.parse(i))/6e4);if(d<1)return"just now";if(d<60)return`${d} min ago`;const U=Math.round(d/60);return U<48?`${U} hour${U===1?"":"s"} ago`:Et(i)};function Gs(i){const d=m=>{let n=String(m??"");return/^[=+\-@\t\r]/.test(n)&&(n=`'${n}`),/[",\n\r]/.test(n)?`"${n.replace(/"/g,'""')}"`:n},U=Object.keys(i[0]||{});return`\uFEFF${[U.join(","),...i.map(m=>U.map(n=>d(m[n])).join(","))].join(`\r
1
+ import{apiRequest as ks}from"../api.js";import{addBannerAction as Ms}from"../lib/plugin-chrome.js";import{helpPopovers as $s}from"../lib/help-popover.js";import{onceClosed as Ss,openMenuAt as Es,viewLifetime as Ts}from"../lib/tool-kit.js";import{snippet as Cs}from"../lib/seo-analyse.js";import{checkRule as wt,matchRedirect as Os}from"../lib/seo-redirects.js";import{checkSettings as Ls,mergeDefaults as kt,ORG_TYPES as Rs}from"../lib/seo-settings.js";import{pickMedia as ze}from"../lib/media-picker.js";import{checkSeoDefaults as Is,seoDefaults as As}from"../lib/seo-defaults.js";import{mountGoogleBusiness as Ps}from"../lib/google-business-panel.js";import{fmtDate as js,fmtDateTime as Fe}from"../lib/dates.js";import{SHAPES as Ds,whileLoading as Ns}from"../lib/loading.js";import{countText as ve,draftAction as qs,draftKey as Je,filterPages as Us,fingerprint as J,pageCounts as Bs,restoreQuestion as Ye,usableDraft as Mt}from"../lib/seo-arrange.js";const _s="/seo",Qe=/^#\/seo(\/[a-z0-9-]+)?\/?(\?.*)?$/,$t=["overview","redirects","sitemap"],Hs="#/seo",Ws={pass:"\u2713",warn:"!",fail:"\u2715",info:"i"},Ks={301:"301 moved",302:"302 for now",307:"307 for now",308:"308 moved",410:"410 gone"},Gs={apiRequest:ks,addBannerAction:Ms,helpPopovers:$s,onceClosed:Ss,openMenuAt:Es,viewLifetime:Ts},zs=async()=>Gs,R=i=>String(i??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;");function Ve(i){const c=document.createElement("template");return c.innerHTML=i.trim(),c.content.firstElementChild}async function ge(i,c){try{await navigator.clipboard.writeText(i),E.toast(`Copied ${c}.`,{type:"success"})}catch{E.toast(`Could not copy - ${i}`,{type:"warning",duration:6e3})}}const A={user(){try{return S.get("auth_user")?.id||""}catch{return""}},get(i){try{return i?S.get(i)??null:null}catch{return null}},set(i,c){try{i&&S.set(i,c)}catch{}},drop(i){try{i&&(S.remove?S.remove(i):S.set(i,null))}catch{}},keys(i){try{return(S.keys?.()||[]).filter(c=>c.startsWith(i))}catch{return[]}}},Fs=()=>new Promise(i=>setTimeout(i,0)),Xe=async(i,c)=>(await Fs(),E.confirm(R(i),c)),Ze=i=>Xe(i.text,{title:i.title,confirmText:i.confirmText,cancelText:i.cancelText});function St(){try{window.dispatchEvent(new CustomEvent("dm:sidebar-count",{detail:{url:Hs}}))}catch{}}const Et=i=>typeof i!="number"?"":i>=85?"good":i>=60?"poor":"bad",Tt=i=>i?js(i):"",Ct=i=>{if(!i)return"";const c=Math.round((Date.now()-Date.parse(i))/6e4);if(c<1)return"just now";if(c<60)return`${c} min ago`;const U=Math.round(c/60);return U<48?`${U} hour${U===1?"":"s"} ago`:Tt(i)};function Js(i){const c=m=>{let n=String(m??"");return/^[=+\-@\t\r]/.test(n)&&(n=`'${n}`),/[",\n\r]/.test(n)?`"${n.replace(/"/g,'""')}"`:n},U=Object.keys(i[0]||{});return`\uFEFF${[U.join(","),...i.map(m=>U.map(n=>c(m[n])).join(","))].join(`\r
2
2
  `)}\r
3
- `}function zs(i,d,U="text/csv;charset=utf-8"){const m=URL.createObjectURL(new Blob([d],{type:U})),n=Object.assign(document.createElement("a"),{href:m,download:i});document.body.appendChild(n),n.click(),n.remove(),setTimeout(()=>URL.revokeObjectURL(m),1e4)}const Fs=`
3
+ `}function Ys(i,c,U="text/csv;charset=utf-8"){const m=URL.createObjectURL(new Blob([c],{type:U})),n=Object.assign(document.createElement("a"),{href:m,download:i});document.body.appendChild(n),n.click(),n.remove(),setTimeout(()=>URL.revokeObjectURL(m),1e4)}const Qs=`
4
4
  <div class="sox-row" data-bind-data-row="id" tabindex="0" data-bind-title="path">
5
5
  <span class="sox-pill" data-bind-data-tone="tone" data-bind-text="scoreText"></span>
6
6
  <span class="sox-cell"><span data-bind-text="path"></span><small data-bind-text="sourceText"></small></span>
7
7
  <span class="sox-cell sox-hide-sm" data-bind-text="title" data-bind-title="title"></span>
8
8
  <span class="sox-cell sox-muted sox-hide-sm" data-bind-text="problems" data-bind-title="problems"></span>
9
9
  <button type="button" class="sox-kebab" aria-label="Actions" title="Actions">\u22EE</button>
10
- </div>`,Js=`
10
+ </div>`,Vs=`
11
11
  <div class="sox-row" data-bind-data-row="id" tabindex="0">
12
12
  <span class="sox-cell"><span data-bind-text="text" data-bind-title="text"></span><small data-bind-text="detail" data-bind-title="detail"></small></span>
13
13
  <span class="sox-pill" data-bind-data-tone="tone" data-bind-text="badge"></span>
14
14
  <button type="button" class="sox-kebab" aria-label="Actions" title="Actions">\u22EE</button>
15
- </div>`,Ys=`
15
+ </div>`,Xs=`
16
16
  <div class="sox-row" data-bind-data-row="id" tabindex="0" data-bind-title="note">
17
17
  <span class="sox-cell sox-mono" data-bind-text="from" data-bind-title="from"></span>
18
18
  <span class="sox-arrow" aria-hidden="true">\u2192</span>
@@ -20,42 +20,42 @@ import{apiRequest as ys}from"../api.js";import{addBannerAction as xs}from"../lib
20
20
  <span class="sox-pill sox-hide-sm" data-bind-data-tone="tone" data-bind-text="code"></span>
21
21
  <span class="sox-cell sox-muted sox-hide-sm" data-bind-text="hits" data-bind-title="lastHit"></span>
22
22
  <button type="button" class="sox-kebab" aria-label="Actions" title="Actions">\u22EE</button>
23
- </div>`,Qs=`
23
+ </div>`,Zs=`
24
24
  <div class="sox-row" data-bind-data-row="id" tabindex="0">
25
25
  <span class="sox-cell"><span data-bind-text="path" data-bind-title="path"></span><small data-bind-text="title"></small></span>
26
26
  <span class="sox-cell sox-muted sox-hide-sm" data-bind-text="source"></span>
27
27
  <span class="sox-cell sox-muted sox-hide-sm" data-bind-text="note" data-bind-title="note"></span>
28
28
  <button type="button" class="sox-kebab" aria-label="Actions" title="Actions">\u22EE</button>
29
- </div>`,Vs=`
29
+ </div>`,ea=`
30
30
  <div class="sox-row" data-bind-data-row="id" tabindex="0">
31
31
  <span class="sox-cell"><span data-bind-text="label"></span><small data-bind-text="detail"></small></span>
32
32
  <span class="sox-pill" data-bind-data-tone="tone" data-bind-text="state"></span>
33
33
  <button type="button" class="sox-kebab" aria-label="Actions" title="Actions">\u22EE</button>
34
- </div>`,Xs=`
34
+ </div>`,ta=`
35
35
  <div>
36
36
  <div class="sox-group" data-bind-hidden="!head" data-bind-text="head"></div>
37
37
  <div class="sox-check" data-bind-hidden="!title">
38
38
  <span class="sox-status" data-bind-data-status="status" data-bind-text="glyph"></span>
39
39
  <span class="sox-check-main"><strong data-bind-text="title"></strong><small data-bind-text="detail"></small><small data-bind-text="fix" data-bind-hidden="!fix"></small></span>
40
40
  </div>
41
- </div>`;export const seoView={templateUrl:"/admin/js/templates/seo.html",async onMount(i){const d=await Ws();if(!Qe.test(location.hash))return;const U=seoView._lifetime??(seoView._lifetime=d.viewLifetime(Qe));U.reset();const m=i.get(0).querySelector(".sox")||i.get(0),n=()=>Qe.test(location.hash)&&m.isConnected,A=e=>(U.add(e),e),g=(e,t)=>d.apiRequest(`${qs}${e}`,t),Ct=location.hash.match(/^#\/seo\/([a-z0-9-]+)/)?.[1]||"overview",Y=M.observable(Ct),Ce=M.observable(!0),Oe=M.observable(""),B=M.observable(!0),w=M.observable(null),ye=M.observable({results:[]}),te=M.observable("all"),xe=M.observable(""),Le=M.observable(""),N=M.observable({rules:[],chains:[],onRename:!0}),Re=M.observable(""),we=M.observable(""),ke=M.observable(""),et=M.observable("301"),W=M.observable({entries:[],left:[],sources:[],labels:{},robots:""}),de=M.observable("in"),Ie=M.observable(""),tt=M.observable([]),Ot=M.computed(()=>!Mt.includes(Y.value)),st=M.observable(!0),at=M.observable(!0),ot=M.observable(!0);let Q=null;const se=e=>W.value.labels?.[e]||(e==="pages"?"Pages":e),Lt=M.computed(()=>(w.value?.score??null)===null?"\u2014":`${w.value.score}%`),Rt=M.computed(()=>`${w.value?.score??0}%`),It=M.computed(()=>St(w.value?.score)),At=M.computed(()=>{const e=w.value;return e?{pages:String(e.pages),failing:String(e.failing),duplicates:String(e.duplicates),redirects:String(e.redirects)}:{pages:"\u2014",failing:"\u2014",duplicates:"\u2014",redirects:"\u2014"}}),Pt=M.computed(()=>w.value?.failing?String(w.value.failing):""),jt=M.computed(()=>{const e=w.value;return e?.running?`Checking\u2026 ${e.progress?.done||0} of ${e.progress?.total||"?"}`:e?.at?`Checked ${Tt(e.at)}`:"Not checked yet"}),nt=M.computed(()=>[...new Set((ye.value.results||[]).map(e=>e.source))]),it=M.observable([]);let Me=[];const Dt=M.computed(()=>{const e=Ns(ye.value.results,{source:xe.value});return{all:ve(e.all),problems:ve(e.problems),hidden:ve(e.hidden)}});A(M.effect(()=>{Me=Ds(ye.value.results,{show:te.value,source:xe.value,query:Le.value}),it.value=Me.slice(0,1e3).map((e,t)=>({id:`p${t}`,path:e.urlPath,sourceText:[se(e.source),e.noindex?"hidden from search engines":e.unlisted?"not in the sitemap":""].filter(Boolean).join(" \xB7 "),title:e.title||e.label||"",scoreText:e.error?"!":typeof e.score=="number"?String(e.score):"\u2014",tone:e.error?"bad":e.noindex?"info":St(e.score),problems:e.error||(e.problems?.length?e.problems.join(" \xB7 "):"Nothing to fix")}))}));const Nt=M.computed(()=>w.value?.at?Le.value.trim()?"No page matches.":te.value==="problems"?"Nothing needs attention.":"No pages.":w.value?.running?"Checking every page - this takes a moment\u2026":"Not checked yet. Check now with the button top right."),lt=M.observable([]);let G=[];A(M.effect(()=>{const e=w.value;if(G=[],e){const t=e.siteSeo||{};for(const s of e.issues?.duplicateTitles||[])G.push({kind:"dupe",text:`Title on ${s.paths.length} pages: "${s.text}"`,detail:s.paths.join(", "),paths:s.paths,tone:"poor",badge:"duplicate"});for(const s of e.issues?.duplicateDescriptions||[]){const a=t.defaultDescription&&s.text===t.defaultDescription;G.push({kind:"dupe",text:a?`${s.paths.length} pages use the site's default description`:`Description on ${s.paths.length} pages: "${s.text}"`,detail:s.paths.join(", "),paths:s.paths,tone:"poor",badge:a?"default":"duplicate"})}t.defaultImage||G.push({kind:"setting",text:"No default share image",detail:"Pages without their own image share with none. Set one in SEO settings.",link:"#/seo?settings=1",tone:"poor",badge:"setting"}),(!e.origin||/localhost|127\.0\.0\.1/.test(e.origin))&&G.push({kind:"setting",text:"The site address is not set",detail:"Canonical links and the sitemap use whatever address a visitor came in on. Set the site address in Settings.",link:"#/settings",tone:"poor",badge:"setting"}),e.chains&&G.push({kind:"chains",text:`${e.chains} redirect${e.chains===1?" leads":"s lead"} to another redirect`,detail:"Each hop is slower and loses a little standing. The Redirects tab shows which.",tone:"poor",badge:"redirects"})}lt.value=G.map((t,s)=>({id:`s${s}`,text:t.text,detail:t.detail||"",tone:t.tone,badge:t.badge}))}));const Ae=M.observable([]);let ue=[];A(M.effect(()=>{const e=Re.value.trim().toLowerCase(),t=new Set(N.value.chains.map(s=>s.id));ue=N.value.rules.filter(s=>!e||`${s.from} ${s.to} ${s.note}`.toLowerCase().includes(e)),Ae.value=ue.map((s,a)=>({id:`r${a}`,from:s.from,to:s.code===410?"(gone)":s.to,note:[s.auto?"Added when the page moved":s.note,t.has(s.id)?"leads to another redirect":""].filter(Boolean).join(" \xB7 "),code:String(s.code),tone:s.code===410?"bad":t.has(s.id)?"poor":s.code===301||s.code===308?"good":"info",hits:s.hits?`${s.hits.toLocaleString("en-GB")} use${s.hits===1?"":"s"}`:"unused",lastHit:s.lastHit?`Last used ${Tt(s.lastHit)}`:"Not used yet"}))}));const qt=M.computed(()=>N.value.rules.length?String(N.value.rules.length):""),Ut=M.computed(()=>`${ue.length+0*Ae.value.length} of ${N.value.rules.length}`),Bt=M.computed(()=>Re.value.trim()?"No redirect matches.":"No redirects yet."),_t=M.computed(()=>{const e=N.value.chains.length;return e?`${e} redirect${e===1?" leads":"s lead"} to another. Right-click one and choose "Go straight there" to make it one hop.`:""}),Ht=M.computed(()=>N.value.onRename?"When a page is renamed, a redirect from its old address is added for you.":"Redirects are not added when a page is renamed (see Settings)."),rt=M.observable([]);A(M.effect(()=>{rt.value=W.value.sources.map((e,t)=>({id:`x${t}`,label:se(e.id),detail:`${e.listed} of ${e.count} listed`,state:e.on?"on":"off",tone:e.on?"good":""}))}));const Pe=M.observable([]);let ae=[];A(M.effect(()=>{const e=Ie.value.trim().toLowerCase();ae=(de.value==="in"?W.value.entries:W.value.left).filter(s=>!e||`${s.urlPath} ${s.title}`.toLowerCase().includes(e)),Pe.value=ae.slice(0,2e3).map((s,a)=>({id:`e${a}`,path:s.urlPath,title:s.title||"",source:se(s.source),note:s.why||[s.lastmod?`Changed ${Et(s.lastmod)}`:"",s.changefreq||"",s.priority!==void 0?`priority ${s.priority}`:""].filter(Boolean).join(" \xB7 ")}))}));const Wt=M.computed(()=>W.value.robots||""),Kt=M.computed(()=>({in:ve((W.value.entries||[]).length),out:ve((W.value.left||[]).length)})),Gt=M.computed(()=>`${ae.length+0*Pe.value.length} address${ae.length===1?"":"es"}`),zt=M.computed(()=>W.value.hooks?Ie.value.trim()?"No address matches.":de.value==="in"?"The sitemap is empty.":"Nothing is left out.":"This version of Domma CMS lists only its own pages in the sitemap."),$e=e=>/403|forbidden/i.test(String(e?.message));async function oe(){try{const e=await g("/overview");if(!n()||!e)return;w.value=e,Oe.value="",e.running&&ct()}catch(e){n()&&(Oe.value=$e(e)?"You do not have access to SEO.":`Could not load SEO: ${e.message||e}`)}}const je=(e,t,s,a=As.rows)=>e.peek()?Ps(m.querySelector(t),s,a).finally(()=>{n()&&(e.value=!1)}):s;async function De(){try{const e=await je(st,".sox-pages-loading",g("/audit"));n()&&e&&(ye.value=e)}catch{}}async function pe(){try{const e=await je(at,".sox-rules-loading",g("/redirects"));if(!n()||!e)return;N.value=e,Vt(e.rules||[])}catch{}}async function Ne(){try{const e=await je(ot,".sox-entries-loading",g("/sitemap"));n()&&e&&(W.value=e)}catch(e){n()&&!$e(e)&&E.toast(`Could not load the sitemap: ${e.message||e}`,{type:"error"})}}async function qe(){Ce.value=!0,await Promise.all([oe(),De(),pe(),Ne()]),n()&&(Ce.value=!1)}function ct(){Q||(Q=setInterval(async()=>{if(!n()){clearInterval(Q),Q=null;return}await oe(),w.peek()?.running||(clearInterval(Q),Q=null,await De(),$t())},1500))}A(()=>{Q&&clearInterval(Q)});async function dt(){try{const e=await g("/audit",{method:"POST",body:JSON.stringify({})});n()&&(w.value={...w.peek(),...e,running:!0}),ct()}catch(e){n()&&E.toast(`Could not start the check: ${e.message||e}`,{type:"error"})}}async function Ue(e,t,s=pe){try{const a=await e();return n()&&(t&&E.toast(t,{type:"success"}),await Promise.all([s(),oe()])),a}catch(a){return n()&&($e(a)?(B.value=!1,E.toast("Only people who may manage SEO can change this.",{type:"warning"})):E.toast(`Not done: ${a.message||a}`,{type:"error"})),null}}const Ft=(e,t=`Redirect from ${e.from} added.`)=>Ue(()=>g("/redirects",{method:"POST",body:JSON.stringify(e)}),t),Jt=(e,t)=>Ue(()=>g(`/redirects/${encodeURIComponent(e.join(","))}`,{method:"DELETE"}),`${t} removed.`);async function Yt(e){try{const t=await g(`/redirects/test?path=${encodeURIComponent(e.replace(/\/\*$/,"/example"))}`);if(!n())return;const s=t.hops||[];E.toast(s.length?s.map(a=>`${a.from} \u2192 ${a.code===410?"gone":a.to} (${a.code})`).join(" \xB7 "):"No redirect applies.",{type:s.length>1?"warning":"info",duration:7e3})}catch(t){n()&&E.toast(`Could not test: ${t.message||t}`,{type:"error"})}}const ut=e=>({from:e.from||"",to:e.code===410?"":e.to||"",code:String(e.code||301),note:e.note||""});function Be(e,{asNew:t=!1,adopt:s=null}={}){const a=t?{from:"",to:"",code:"301",note:""}:ut(e),l={from:M.observable(a.from),to:M.observable(a.to),code:M.observable(a.code),note:M.observable(a.note)},o=t?"":J(ut(e));mt(t?"New redirect":`Redirect from ${e.from}`,l,`
41
+ </div>`;export const seoView={templateUrl:"/admin/js/templates/seo.html",async onMount(i){const c=await zs();if(!Qe.test(location.hash))return;const U=seoView._lifetime??(seoView._lifetime=c.viewLifetime(Qe));U.reset();const m=i.get(0).querySelector(".sox")||i.get(0),n=()=>Qe.test(location.hash)&&m.isConnected,O=e=>(U.add(e),e),v=(e,t)=>c.apiRequest(`${_s}${e}`,t);let Ot=null;const Lt=()=>Ot??(Ot=v("/audit").then(e=>(e?.results||[]).filter(t=>t.status===200)).catch(()=>[]).then(e=>e.length?e:c.apiRequest("/pages").then(t=>(Array.isArray(t)?t:[]).filter(s=>s.status==="published")).catch(()=>[])));async function et(e){if(!e)return null;try{const t=await import("/plugins/_lib/admin/ui/page-menu.js");return e.isConnected?t.attachPageMenu(e,{load:Lt}):null}catch{return null}}const Rt=location.hash.match(/^#\/seo\/([a-z0-9-]+)/)?.[1]||"overview",Y=M.observable(Rt),Ce=M.observable(!0),Oe=M.observable(""),B=M.observable(!0),w=M.observable(null),ye=M.observable({results:[]}),te=M.observable("all"),xe=M.observable(""),Le=M.observable(""),N=M.observable({rules:[],chains:[],onRename:!0}),Re=M.observable(""),we=M.observable(""),ke=M.observable(""),tt=M.observable("301"),W=M.observable({entries:[],left:[],sources:[],labels:{},robots:""}),de=M.observable("in"),Ie=M.observable(""),st=M.observable([]),It=M.computed(()=>!$t.includes(Y.value)),at=M.observable(!0),ot=M.observable(!0),nt=M.observable(!0);let Q=null;const se=e=>W.value.labels?.[e]||(e==="pages"?"Pages":e),At=M.computed(()=>(w.value?.score??null)===null?"\u2014":`${w.value.score}%`),Pt=M.computed(()=>`${w.value?.score??0}%`),jt=M.computed(()=>Et(w.value?.score)),Dt=M.computed(()=>{const e=w.value;return e?{pages:String(e.pages),failing:String(e.failing),duplicates:String(e.duplicates),redirects:String(e.redirects)}:{pages:"\u2014",failing:"\u2014",duplicates:"\u2014",redirects:"\u2014"}}),Nt=M.computed(()=>w.value?.failing?String(w.value.failing):""),qt=M.computed(()=>{const e=w.value;return e?.running?`Checking\u2026 ${e.progress?.done||0} of ${e.progress?.total||"?"}`:e?.at?`Checked ${Ct(e.at)}`:"Not checked yet"}),it=M.computed(()=>[...new Set((ye.value.results||[]).map(e=>e.source))]),lt=M.observable([]);let Me=[];const Ut=M.computed(()=>{const e=Bs(ye.value.results,{source:xe.value});return{all:ve(e.all),problems:ve(e.problems),hidden:ve(e.hidden)}});O(M.effect(()=>{Me=Us(ye.value.results,{show:te.value,source:xe.value,query:Le.value}),lt.value=Me.slice(0,1e3).map((e,t)=>({id:`p${t}`,path:e.urlPath,sourceText:[se(e.source),e.noindex?"hidden from search engines":e.unlisted?"not in the sitemap":""].filter(Boolean).join(" \xB7 "),title:e.title||e.label||"",scoreText:e.error?"!":typeof e.score=="number"?String(e.score):"\u2014",tone:e.error?"bad":e.noindex?"info":Et(e.score),problems:e.error||(e.problems?.length?e.problems.join(" \xB7 "):"Nothing to fix")}))}));const Bt=M.computed(()=>w.value?.at?Le.value.trim()?"No page matches.":te.value==="problems"?"Nothing needs attention.":"No pages.":w.value?.running?"Checking every page - this takes a moment\u2026":"Not checked yet. Check now with the button top right."),rt=M.observable([]);let G=[];O(M.effect(()=>{const e=w.value;if(G=[],e){const t=e.siteSeo||{};for(const s of e.issues?.duplicateTitles||[])G.push({kind:"dupe",text:`Title on ${s.paths.length} pages: "${s.text}"`,detail:s.paths.join(", "),paths:s.paths,tone:"poor",badge:"duplicate"});for(const s of e.issues?.duplicateDescriptions||[]){const a=t.defaultDescription&&s.text===t.defaultDescription;G.push({kind:"dupe",text:a?`${s.paths.length} pages use the site's default description`:`Description on ${s.paths.length} pages: "${s.text}"`,detail:s.paths.join(", "),paths:s.paths,tone:"poor",badge:a?"default":"duplicate"})}t.defaultImage||G.push({kind:"setting",text:"No default share image",detail:"Pages without their own image share with none. Set one in SEO settings.",link:"#/seo?settings=1",tone:"poor",badge:"setting"}),(!e.origin||/localhost|127\.0\.0\.1/.test(e.origin))&&G.push({kind:"setting",text:"The site address is not set",detail:"Canonical links and the sitemap use whatever address a visitor came in on. Set the site address in Settings.",link:"#/settings",tone:"poor",badge:"setting"}),e.chains&&G.push({kind:"chains",text:`${e.chains} redirect${e.chains===1?" leads":"s lead"} to another redirect`,detail:"Each hop is slower and loses a little standing. The Redirects tab shows which.",tone:"poor",badge:"redirects"})}rt.value=G.map((t,s)=>({id:`s${s}`,text:t.text,detail:t.detail||"",tone:t.tone,badge:t.badge}))}));const Ae=M.observable([]);let ue=[];O(M.effect(()=>{const e=Re.value.trim().toLowerCase(),t=new Set(N.value.chains.map(s=>s.id));ue=N.value.rules.filter(s=>!e||`${s.from} ${s.to} ${s.note}`.toLowerCase().includes(e)),Ae.value=ue.map((s,a)=>({id:`r${a}`,from:s.from,to:s.code===410?"(gone)":s.to,note:[s.auto?"Added when the page moved":s.note,t.has(s.id)?"leads to another redirect":""].filter(Boolean).join(" \xB7 "),code:String(s.code),tone:s.code===410?"bad":t.has(s.id)?"poor":s.code===301||s.code===308?"good":"info",hits:s.hits?`${s.hits.toLocaleString("en-GB")} use${s.hits===1?"":"s"}`:"unused",lastHit:s.lastHit?`Last used ${Ct(s.lastHit)}`:"Not used yet"}))}));const _t=M.computed(()=>N.value.rules.length?String(N.value.rules.length):""),Ht=M.computed(()=>`${ue.length+0*Ae.value.length} of ${N.value.rules.length}`),Wt=M.computed(()=>Re.value.trim()?"No redirect matches.":"No redirects yet."),Kt=M.computed(()=>{const e=N.value.chains.length;return e?`${e} redirect${e===1?" leads":"s lead"} to another. Right-click one and choose "Go straight there" to make it one hop.`:""}),Gt=M.computed(()=>N.value.onRename?"When a page is renamed, a redirect from its old address is added for you.":"Redirects are not added when a page is renamed (see Settings)."),ct=M.observable([]);O(M.effect(()=>{ct.value=W.value.sources.map((e,t)=>({id:`x${t}`,label:se(e.id),detail:`${e.listed} of ${e.count} listed`,state:e.on?"on":"off",tone:e.on?"good":""}))}));const Pe=M.observable([]);let ae=[];O(M.effect(()=>{const e=Ie.value.trim().toLowerCase();ae=(de.value==="in"?W.value.entries:W.value.left).filter(s=>!e||`${s.urlPath} ${s.title}`.toLowerCase().includes(e)),Pe.value=ae.slice(0,2e3).map((s,a)=>({id:`e${a}`,path:s.urlPath,title:s.title||"",source:se(s.source),note:s.why||[s.lastmod?`Changed ${Tt(s.lastmod)}`:"",s.changefreq||"",s.priority!==void 0?`priority ${s.priority}`:""].filter(Boolean).join(" \xB7 ")}))}));const zt=M.computed(()=>W.value.robots||""),Ft=M.computed(()=>({in:ve((W.value.entries||[]).length),out:ve((W.value.left||[]).length)})),Jt=M.computed(()=>`${ae.length+0*Pe.value.length} address${ae.length===1?"":"es"}`),Yt=M.computed(()=>W.value.hooks?Ie.value.trim()?"No address matches.":de.value==="in"?"The sitemap is empty.":"Nothing is left out.":"This version of Domma CMS lists only its own pages in the sitemap."),$e=e=>/403|forbidden/i.test(String(e?.message));async function oe(){try{const e=await v("/overview");if(!n()||!e)return;w.value=e,Oe.value="",e.running&&dt()}catch(e){n()&&(Oe.value=$e(e)?"You do not have access to SEO.":`Could not load SEO: ${e.message||e}`)}}const je=(e,t,s,a=Ds.rows)=>e.peek()?Ns(m.querySelector(t),s,a).finally(()=>{n()&&(e.value=!1)}):s;async function De(){try{const e=await je(at,".sox-pages-loading",v("/audit"));n()&&e&&(ye.value=e)}catch{}}async function pe(){try{const e=await je(ot,".sox-rules-loading",v("/redirects"));if(!n()||!e)return;N.value=e,es(e.rules||[])}catch{}}async function Ne(){try{const e=await je(nt,".sox-entries-loading",v("/sitemap"));n()&&e&&(W.value=e)}catch(e){n()&&!$e(e)&&E.toast(`Could not load the sitemap: ${e.message||e}`,{type:"error"})}}async function qe(){Ce.value=!0,await Promise.all([oe(),De(),pe(),Ne()]),n()&&(Ce.value=!1)}function dt(){Q||(Q=setInterval(async()=>{if(!n()){clearInterval(Q),Q=null;return}await oe(),w.peek()?.running||(clearInterval(Q),Q=null,await De(),St())},1500))}O(()=>{Q&&clearInterval(Q)});async function ut(){try{const e=await v("/audit",{method:"POST",body:JSON.stringify({})});n()&&(w.value={...w.peek(),...e,running:!0}),dt()}catch(e){n()&&E.toast(`Could not start the check: ${e.message||e}`,{type:"error"})}}async function Ue(e,t,s=pe){try{const a=await e();return n()&&(t&&E.toast(t,{type:"success"}),await Promise.all([s(),oe()])),a}catch(a){return n()&&($e(a)?(B.value=!1,E.toast("Only people who may manage SEO can change this.",{type:"warning"})):E.toast(`Not done: ${a.message||a}`,{type:"error"})),null}}const Qt=(e,t=`Redirect from ${e.from} added.`)=>Ue(()=>v("/redirects",{method:"POST",body:JSON.stringify(e)}),t),Vt=(e,t)=>Ue(()=>v(`/redirects/${encodeURIComponent(e.join(","))}`,{method:"DELETE"}),`${t} removed.`);async function Xt(e){try{const t=await v(`/redirects/test?path=${encodeURIComponent(e.replace(/\/\*$/,"/example"))}`);if(!n())return;const s=t.hops||[];E.toast(s.length?s.map(a=>`${a.from} \u2192 ${a.code===410?"gone":a.to} (${a.code})`).join(" \xB7 "):"No redirect applies.",{type:s.length>1?"warning":"info",duration:7e3})}catch(t){n()&&E.toast(`Could not test: ${t.message||t}`,{type:"error"})}}const pt=e=>({from:e.from||"",to:e.code===410?"":e.to||"",code:String(e.code||301),note:e.note||""});function Be(e,{asNew:t=!1,adopt:s=null}={}){const a=t?{from:"",to:"",code:"301",note:""}:pt(e),l={from:M.observable(a.from),to:M.observable(a.to),code:M.observable(a.code),note:M.observable(a.note)},o=t?"":J(pt(e));ht(t?"New redirect":`Redirect from ${e.from}`,l,`
42
42
  <div class="sox-form-grid">
43
43
  <div class="sox-wide"><label class="form-label" for="sox-r-from">From</label><input id="sox-r-from" class="form-input sox-mono" data-model="from.value"></div>
44
44
  <div class="sox-wide"><label class="form-label" for="sox-r-to">To</label><input id="sox-r-to" class="form-input sox-mono" data-model="to.value" data-bind-disabled="code.value === '410'"></div>
45
45
  <div><label class="form-label" for="sox-r-code">Kind</label><select id="sox-r-code" class="form-input" data-model="code.value">
46
- ${Object.entries(_s).map(([r,c])=>`<option value="${r}">${c}</option>`).join("")}</select></div>
46
+ ${Object.entries(Ks).map(([r,d])=>`<option value="${r}">${d}</option>`).join("")}</select></div>
47
47
  <div><label class="form-label" for="sox-r-note">Note</label><input id="sox-r-note" class="form-input" data-model="note.value"></div>
48
- </div>`,()=>{const r={from:l.from.value,to:l.to.value,code:Number(l.code.value),note:l.note.value},c=N.peek().rules.filter(y=>t||y.id!==e.id);return{body:r,errors:xt(r,c).errors}},async r=>{t?await g("/redirects",{method:"POST",body:JSON.stringify(r)}):await g(`/redirects/${encodeURIComponent(e.id)}`,{method:"PUT",body:JSON.stringify(r)}),n()&&(E.toast(t?`Redirect from ${r.from} added.`:"Redirect saved.",{type:"success"}),await Promise.all([pe(),oe()]))},t?"Add":"Save",{kind:"redirect",id:e.id,what:t?`the redirect from ${s?.from||e.from||"?"}`:`the redirect from ${e.from}`,was:o,adopt:s})}function Qt(){const e={csv:M.observable("")};mt("Import redirects",e,`
48
+ </div>`,()=>{const r={from:l.from.value,to:l.to.value,code:Number(l.code.value),note:l.note.value},d=N.peek().rules.filter(y=>t||y.id!==e.id);return{body:r,errors:wt(r,d).errors}},async r=>{t?await v("/redirects",{method:"POST",body:JSON.stringify(r)}):await v(`/redirects/${encodeURIComponent(e.id)}`,{method:"PUT",body:JSON.stringify(r)}),n()&&(E.toast(t?`Redirect from ${r.from} added.`:"Redirect saved.",{type:"success"}),await Promise.all([pe(),oe()]))},t?"Add":"Save",{kind:"redirect",id:e.id,what:t?`the redirect from ${s?.from||e.from||"?"}`:`the redirect from ${e.from}`,was:o,adopt:s}),et(document.getElementById("sox-r-to"))}function Zt(){const e={csv:M.observable("")};ht("Import redirects",e,`
49
49
  <p class="sox-note">One redirect per line: <span class="sox-mono">from, to</span>, and optionally the kind (301, 302, 307, 308, 410) and a note. A header line is skipped. Paste from a spreadsheet, or another CMS's export.</p>
50
- <textarea class="form-input sox-mono" rows="14" data-model="csv.value" placeholder="/old-page, /new-page&#10;/news/*, /blog/*, 301&#10;/retired, , 410"></textarea>`,()=>({body:{csv:e.csv.value},errors:e.csv.value.trim()?{}:{csv:"Paste some redirects first."}}),async t=>{const s=await g("/redirects/import",{method:"POST",body:JSON.stringify(t)});if(!n())return;const a=s.skipped||[];E.toast(`${s.added} added${a.length?`, ${a.length} skipped - line ${a[0].line}: ${a[0].why}`:"."}`,{type:a.length?"warning":"success",duration:a.length?9e3:4e3}),await Promise.all([pe(),oe()])},"Import",{kind:"import",what:"the redirects you were importing"})}let pt=!1;async function Vt(e){if(pt||!B.peek())return;pt=!0;const t=Je(R.user(),"redirect","");if(!t)return;const s=new Set(e.map(a=>String(a.id)));for(const a of R.keys(`${t}.`)){let l;try{l=decodeURIComponent(a.slice(t.length+1))}catch{continue}if(s.has(l))continue;const o=kt(R.get(a),{from:"",to:"",code:"301",note:""});if(!o){R.drop(a);continue}if(await Ze(Ye({what:`the redirect from ${o.values.from||"?"}`,when:o.at?Fe(o.at):"",gone:"Keep them to add it again as a new redirect."}))){R.drop(a);continue}n()&&Be({id:l},{asNew:!0,adopt:o.values});return}}function _e(e,{kind:t,id:s="",what:a,read:l,write:o,was:r=""}){const c=Je(R.user(),t,s);let y=J(l()),$=r,k=!0,O=!1,_=!1;const H=()=>J(l())!==y,f=()=>{const u=js({dirty:H(),owns:k});u==="write"?R.set(c,{values:l(),was:$,at:new Date().toISOString()}):u==="remove"&&R.drop(c)},T=u=>{O||(f(),H()&&(u.preventDefault(),u.returnValue=""))};window.addEventListener("beforeunload",T);const P=e.close.bind(e);let j=()=>{};const C=()=>{O=!0,window.removeEventListener("beforeunload",T),j()};return e.close=async u=>{if(O)return P(u);if(!(u!==!0&&!k)){if(u!==!0&&H()){if(_)return;_=!0;const h=await Xe("Throw away the changes you have not saved?",{title:"Unsaved changes",confirmText:"Throw away",cancelText:"Keep editing"});if(_=!1,!h||O)return;k&&R.drop(c)}else u!==!0&&f();return C(),P(u)}},j=U.add(()=>{if(!O){f(),C();try{P(!0)}catch{}}}),{saved(u,h=$){y=J(u),$=h,k=!0,f()},adopt(u,h=""){o(u),$=h,k=!0},async offer(u=r){const h=R.get(c),X=t==="settings"?Object.fromEntries(["defaultTitle","titleSeparator","defaultDescription","defaultImage"].map(b=>[b,l()[b]])):{},fe=h?.values?{...h,values:{...X,...h.values}}:h,q=kt(fe,l());return q?(k=!1,await Ze(Ye({what:a,when:q.at?Fe(q.at):"",stale:q.was!==u}))?(R.drop(c),k=!0,!1):O?!1:(k=!0,o(q.values),$=q.was,!0)):(h&&R.drop(c),!1)}}}let Se=!1;function mt(e,t,s,a,l,o="Save",r=null){if(Se)return;Se=!0;let c=null;try{const y=M.observable(!1),$=M.computed(()=>a()),k=M.computed(()=>Object.values($.value.errors).join(" ")),O={...t,saving:y,errText:k,cannot:M.computed(()=>y.value||!!k.value)},_=()=>Object.fromEntries(Object.entries(t).map(([u,h])=>[u,h.peek()])),H=u=>{for(const[h,X]of Object.entries(t))h in u&&(X.value=u[h])};c=E.slideover({title:e,size:"md",position:"right"});const f=Ve(`<div class="sox-form">${s}
50
+ <textarea class="form-input sox-mono" rows="14" data-model="csv.value" placeholder="/old-page, /new-page&#10;/news/*, /blog/*, 301&#10;/retired, , 410"></textarea>`,()=>({body:{csv:e.csv.value},errors:e.csv.value.trim()?{}:{csv:"Paste some redirects first."}}),async t=>{const s=await v("/redirects/import",{method:"POST",body:JSON.stringify(t)});if(!n())return;const a=s.skipped||[];E.toast(`${s.added} added${a.length?`, ${a.length} skipped - line ${a[0].line}: ${a[0].why}`:"."}`,{type:a.length?"warning":"success",duration:a.length?9e3:4e3}),await Promise.all([pe(),oe()])},"Import",{kind:"import",what:"the redirects you were importing"})}let mt=!1;async function es(e){if(mt||!B.peek())return;mt=!0;const t=Je(A.user(),"redirect","");if(!t)return;const s=new Set(e.map(a=>String(a.id)));for(const a of A.keys(`${t}.`)){let l;try{l=decodeURIComponent(a.slice(t.length+1))}catch{continue}if(s.has(l))continue;const o=Mt(A.get(a),{from:"",to:"",code:"301",note:""});if(!o){A.drop(a);continue}if(await Ze(Ye({what:`the redirect from ${o.values.from||"?"}`,when:o.at?Fe(o.at):"",gone:"Keep them to add it again as a new redirect."}))){A.drop(a);continue}n()&&Be({id:l},{asNew:!0,adopt:o.values});return}}function _e(e,{kind:t,id:s="",what:a,read:l,write:o,was:r=""}){const d=Je(A.user(),t,s);let y=J(l()),$=r,k=!0,L=!1,_=!1;const H=()=>J(l())!==y,f=()=>{const u=qs({dirty:H(),owns:k});u==="write"?A.set(d,{values:l(),was:$,at:new Date().toISOString()}):u==="remove"&&A.drop(d)},T=u=>{L||(f(),H()&&(u.preventDefault(),u.returnValue=""))};window.addEventListener("beforeunload",T);const P=e.close.bind(e);let j=()=>{};const C=()=>{L=!0,window.removeEventListener("beforeunload",T),j()};return e.close=async u=>{if(L)return P(u);if(!(u!==!0&&!k)){if(u!==!0&&H()){if(_)return;_=!0;const h=await Xe("Throw away the changes you have not saved?",{title:"Unsaved changes",confirmText:"Throw away",cancelText:"Keep editing"});if(_=!1,!h||L)return;k&&A.drop(d)}else u!==!0&&f();return C(),P(u)}},j=U.add(()=>{if(!L){f(),C();try{P(!0)}catch{}}}),{saved(u,h=$){y=J(u),$=h,k=!0,f()},adopt(u,h=""){o(u),$=h,k=!0},async offer(u=r){const h=A.get(d),X=t==="settings"?Object.fromEntries(["defaultTitle","titleSeparator","defaultDescription","defaultImage"].map(b=>[b,l()[b]])):{},fe=h?.values?{...h,values:{...X,...h.values}}:h,q=Mt(fe,l());return q?(k=!1,await Ze(Ye({what:a,when:q.at?Fe(q.at):"",stale:q.was!==u}))?(A.drop(d),k=!0,!1):L?!1:(k=!0,o(q.values),$=q.was,!0)):(h&&A.drop(d),!1)}}}let Se=!1;function ht(e,t,s,a,l,o="Save",r=null){if(Se)return;Se=!0;let d=null;try{const y=M.observable(!1),$=M.computed(()=>a()),k=M.computed(()=>Object.values($.value.errors).join(" ")),L={...t,saving:y,errText:k,cannot:M.computed(()=>y.value||!!k.value)},_=()=>Object.fromEntries(Object.entries(t).map(([u,h])=>[u,h.peek()])),H=u=>{for(const[h,X]of Object.entries(t))h in u&&(X.value=u[h])};d=E.slideover({title:e,size:"md",position:"right"});const f=Ve(`<div class="sox-form">${s}
51
51
  <p class="sox-err" data-bind-hidden="!errText.value" data-bind-text="errText.value"></p>
52
52
  <div class="sox-actions"><small class="sox-muted">Ctrl+Enter ${o.toLowerCase()}s.</small><span class="sox-spacer"></span>
53
53
  <button type="button" class="btn btn-sm btn-ghost" data-on-click="cancel">Cancel</button>
54
- <button type="button" class="btn btn-sm btn-primary" data-on-click="save" data-bind-disabled="cannot.value">${L(o)}</button></div></div>`);let T=null;async function P(){if(O.cannot.peek())return;y.value=!0;const u=_();f.inert=!0;try{await l($.peek().body),T?.saved(u,""),c.close(!0)}catch(h){f.inert=!1,n()&&E.toast(`Not saved: ${h.message||h}`,{type:"error"})}finally{y.value=!1}}c.element.appendChild(f);const j=d.helpPopovers(f),C=M.applyBindings(O,f,{methods:{save:P,cancel:()=>c.close()}});f.addEventListener("keydown",u=>{(u.ctrlKey||u.metaKey)&&u.key==="Enter"&&(u.preventDefault(),P())}),d.onceClosed(c,()=>{C.dispose(),j(),Se=!1}),r?(T=_e(c,{...r,read:_,write:H}),r.adopt?T.adopt(r.adopt,""):T.offer(r.was)):A(()=>{try{c.close(!0)}catch{}}),I.scan(f),c.open(),f.querySelector("input, textarea")?.focus()}catch(y){Se=!1;try{c?.close(!0)}catch{}E.toast(`Could not open ${e}: ${y.message||y}`,{type:"error"})}}let ne=!1;const Xt=e=>({title:String(e.title??"").trim().slice(0,200),description:String(e.description??"").trim().slice(0,400),image:String(e.image??"").trim().slice(0,500),noindex:e.noindex===!0,focus:String(e.focus??"").trim().slice(0,100)});async function ee(e){if(ne)return;ne=!0;let t;try{t=await g(`/item?path=${encodeURIComponent(e)}`)}catch(s){if(ne=!1,!n())return;const a=s?.status===404?Je(R.user(),"item",e):null,l=a?R.get(a):null;if(l?.values){await Ze(Ye({what:e,when:l.at?Fe(l.at):"",gone:"Keep them and they are offered again if the address is served again."}))&&R.drop(a);return}E.toast(`Could not open ${e}: ${s.message||s}`,{type:"error"});return}if(!n()){ne=!1;return}try{Zt(e,t)}catch(s){ne=!1,E.toast(`Could not open ${e}: ${s.message||s}`,{type:"error"})}}function Zt(e,t){const s={title:M.observable(t.fields.title),description:M.observable(t.fields.description),focus:M.observable(t.fields.focus),image:M.observable(t.fields.image),noindex:M.observable(t.fields.noindex)},a=t.limits||{},l=t.page?.title||t.live?.h1||"",o=t.kind==="page"?`${l}${t.defaults.separator}${t.defaults.siteTitle}`:t.live?.title||"",r=t.kind==="page"?t.defaults.description||"":t.live?.description||"",c=t.kind==="page"?t.defaults.image:t.live?.image||"",y=M.computed(()=>s.title.value.trim()||o),$=M.computed(()=>s.description.value.trim()||r),k=M.computed(()=>s.image.value.trim()||c),O=t.origin||location.origin,_=M.computed(()=>Ss({title:y.value,description:$.value,url:`${O}${e}`,limits:a})),H=(x,v,ce)=>{const Z=x.length;return{text:`${Z} / ${ce}`,width:`${Math.min(100,Z/ce*100)}%`,tone:Z?Z<v||Z>ce?"poor":"good":"bad"}},f=M.computed(()=>H(y.value,a.titleMin||30,a.titleMax||60)),T=M.computed(()=>H($.value,a.descMin||70,a.descMax||160)),P=(()=>{try{return new URL(O).host}catch{return location.host}})(),j=M.computed(()=>k.value?`url("${k.value.replace(/["\\\n\r]/g,"")}")`:"none"),C=M.observable([]),u=x=>{const v=[],ce=x?.checks||[],Z={fail:0,warn:1,pass:2,info:3};for(const Ke of[...new Set(ce.map(F=>F.group))]){v.push({id:`g-${Ke}`,head:Ke,title:"",detail:"",fix:"",status:"",glyph:""});for(const F of ce.filter(Ge=>Ge.group===Ke).sort((Ge,gs)=>Z[Ge.status]-Z[gs.status]))v.push({id:`c-${F.id}`,head:"",title:F.title,detail:F.detail,fix:F.status==="pass"?"":F.fix,status:F.status,glyph:Bs[F.status]||"?"})}C.value=v};u(t.analysis);const h=M.observable(t.analysis?`Score ${t.analysis.score}% \xB7 ${t.analysis.failing} failing, ${t.analysis.warnings} could be better`:t.status===200?"":`Not live (answers ${t.status||"nothing"}) - the checks run once it is published.`),X=()=>({title:s.title.peek(),description:s.description.peek(),focus:s.focus.peek(),image:s.image.peek(),noindex:s.noindex.peek()}),fe=x=>{for(const v of Object.keys(s))v in x&&(s[v].value=x[v])},q=M.observable(!1),p=M.computed(()=>s.image.value.trim()&&!/^(https?:\/\/|\/)/i.test(s.image.value.trim())?"The image: a path like /media/photo.jpg, or a full web address.":""),b={...s,saving:q,errText:p,checks:C,scoreLine:h,serp:_,titleMeter:f,descMeter:T,shareBg:j,effTitle:y,effDesc:$,host:P,hasImage:M.computed(()=>!!k.value),defTitle:o,defDesc:r,canManage:B,cannot:M.computed(()=>q.value||!!p.value||!B.value)},D=E.slideover({title:`SEO \xB7 ${e}`,size:"lg",position:"right"}),re=t.kind==="url"?'<p class="sox-note is-warn">A plugin serves this address (a blog post, a listing). What you set here takes the place of its own SEO fields.</p>':t.page?.status!=="published"?`<p class="sox-note is-warn">This page is a ${L(t.page?.status||"draft")} - not live yet.</p>`:"",be=t.redirect?`<p class="sox-note is-bad">A redirect sends visitors from here to ${L(t.redirect.to||"(gone)")} - they never see this page.</p>`:"",K=Ve(`
54
+ <button type="button" class="btn btn-sm btn-primary" data-on-click="save" data-bind-disabled="cannot.value">${R(o)}</button></div></div>`);let T=null;async function P(){if(L.cannot.peek())return;y.value=!0;const u=_();f.inert=!0;try{await l($.peek().body),T?.saved(u,""),d.close(!0)}catch(h){f.inert=!1,n()&&E.toast(`Not saved: ${h.message||h}`,{type:"error"})}finally{y.value=!1}}d.element.appendChild(f);const j=c.helpPopovers(f),C=M.applyBindings(L,f,{methods:{save:P,cancel:()=>d.close()}});f.addEventListener("keydown",u=>{(u.ctrlKey||u.metaKey)&&u.key==="Enter"&&(u.preventDefault(),P())}),c.onceClosed(d,()=>{C.dispose(),j(),Se=!1}),r?(T=_e(d,{...r,read:_,write:H}),r.adopt?T.adopt(r.adopt,""):T.offer(r.was)):O(()=>{try{d.close(!0)}catch{}}),I.scan(f),d.open(),f.querySelector("input, textarea")?.focus()}catch(y){Se=!1;try{d?.close(!0)}catch{}E.toast(`Could not open ${e}: ${y.message||y}`,{type:"error"})}}let ne=!1;const ts=e=>({title:String(e.title??"").trim().slice(0,200),description:String(e.description??"").trim().slice(0,400),image:String(e.image??"").trim().slice(0,500),noindex:e.noindex===!0,focus:String(e.focus??"").trim().slice(0,100)});async function ee(e){if(ne)return;ne=!0;let t;try{t=await v(`/item?path=${encodeURIComponent(e)}`)}catch(s){if(ne=!1,!n())return;const a=s?.status===404?Je(A.user(),"item",e):null,l=a?A.get(a):null;if(l?.values){await Ze(Ye({what:e,when:l.at?Fe(l.at):"",gone:"Keep them and they are offered again if the address is served again."}))&&A.drop(a);return}E.toast(`Could not open ${e}: ${s.message||s}`,{type:"error"});return}if(!n()){ne=!1;return}try{ss(e,t)}catch(s){ne=!1,E.toast(`Could not open ${e}: ${s.message||s}`,{type:"error"})}}function ss(e,t){const s={title:M.observable(t.fields.title),description:M.observable(t.fields.description),focus:M.observable(t.fields.focus),image:M.observable(t.fields.image),noindex:M.observable(t.fields.noindex)},a=t.limits||{},l=t.page?.title||t.live?.h1||"",o=t.kind==="page"?`${l}${t.defaults.separator}${t.defaults.siteTitle}`:t.live?.title||"",r=t.kind==="page"?t.defaults.description||"":t.live?.description||"",d=t.kind==="page"?t.defaults.image:t.live?.image||"",y=M.computed(()=>s.title.value.trim()||o),$=M.computed(()=>s.description.value.trim()||r),k=M.computed(()=>s.image.value.trim()||d),L=t.origin||location.origin,_=M.computed(()=>Cs({title:y.value,description:$.value,url:`${L}${e}`,limits:a})),H=(x,g,ce)=>{const Z=x.length;return{text:`${Z} / ${ce}`,width:`${Math.min(100,Z/ce*100)}%`,tone:Z?Z<g||Z>ce?"poor":"good":"bad"}},f=M.computed(()=>H(y.value,a.titleMin||30,a.titleMax||60)),T=M.computed(()=>H($.value,a.descMin||70,a.descMax||160)),P=(()=>{try{return new URL(L).host}catch{return location.host}})(),j=M.computed(()=>k.value?`url("${k.value.replace(/["\\\n\r]/g,"")}")`:"none"),C=M.observable([]),u=x=>{const g=[],ce=x?.checks||[],Z={fail:0,warn:1,pass:2,info:3};for(const Ke of[...new Set(ce.map(F=>F.group))]){g.push({id:`g-${Ke}`,head:Ke,title:"",detail:"",fix:"",status:"",glyph:""});for(const F of ce.filter(Ge=>Ge.group===Ke).sort((Ge,ws)=>Z[Ge.status]-Z[ws.status]))g.push({id:`c-${F.id}`,head:"",title:F.title,detail:F.detail,fix:F.status==="pass"?"":F.fix,status:F.status,glyph:Ws[F.status]||"?"})}C.value=g};u(t.analysis);const h=M.observable(t.analysis?`Score ${t.analysis.score}% \xB7 ${t.analysis.failing} failing, ${t.analysis.warnings} could be better`:t.status===200?"":`Not live (answers ${t.status||"nothing"}) - the checks run once it is published.`),X=()=>({title:s.title.peek(),description:s.description.peek(),focus:s.focus.peek(),image:s.image.peek(),noindex:s.noindex.peek()}),fe=x=>{for(const g of Object.keys(s))g in x&&(s[g].value=x[g])},q=M.observable(!1),p=M.computed(()=>s.image.value.trim()&&!/^(https?:\/\/|\/)/i.test(s.image.value.trim())?"The image: a path like /media/photo.jpg, or a full web address.":""),b={...s,saving:q,errText:p,checks:C,scoreLine:h,serp:_,titleMeter:f,descMeter:T,shareBg:j,effTitle:y,effDesc:$,host:P,hasImage:M.computed(()=>!!k.value),defTitle:o,defDesc:r,canManage:B,cannot:M.computed(()=>q.value||!!p.value||!B.value)},D=E.slideover({title:`SEO \xB7 ${e}`,size:"lg",position:"right"}),re=t.kind==="url"?'<p class="sox-note is-warn">A plugin serves this address (a blog post, a listing). What you set here takes the place of its own SEO fields.</p>':t.page?.status!=="published"?`<p class="sox-note is-warn">This page is a ${R(t.page?.status||"draft")} - not live yet.</p>`:"",be=t.redirect?`<p class="sox-note is-bad">A redirect sends visitors from here to ${R(t.redirect.to||"(gone)")} - they never see this page.</p>`:"",K=Ve(`
55
55
  <div class="sox-form">
56
56
  ${re}${be}
57
57
  <section><h4>As it will look <span data-help="The search result is drawn the way Google draws it, cut where it cuts (roughly - it measures pixels). The share card is what Facebook, LinkedIn, WhatsApp and others show when someone shares the link."></span>
58
- <span class="sox-spacer"></span><a class="btn btn-xs btn-ghost" href="${L(e)}" target="_blank" rel="noopener"><span data-icon="external-link" data-icon-size="12"></span> Open</a></h4>
58
+ <span class="sox-spacer"></span><a class="btn btn-xs btn-ghost" href="${R(e)}" target="_blank" rel="noopener"><span data-icon="external-link" data-icon-size="12"></span> Open</a></h4>
59
59
  <div class="sox-previews">
60
60
  <div class="sox-serp" aria-label="Search result preview">
61
61
  <div class="sox-serp-crumbs" data-bind-text="serp.value.crumbs"></div>
@@ -70,15 +70,15 @@ import{apiRequest as ys}from"../api.js";import{addBannerAction as xs}from"../lib
70
70
  </section>
71
71
  <section><h4>Search and sharing</h4><div class="sox-form-grid">
72
72
  <div class="sox-wide"><label class="form-label" for="sox-i-title">Title <span data-help="The blue link in search results and the headline of a share. Say what the page is about, words that matter first. Empty uses the page title and the site name."></span></label>
73
- <input id="sox-i-title" class="form-input" data-model="title.value" placeholder="${L(o)}" maxlength="200">
73
+ <input id="sox-i-title" class="form-input" data-model="title.value" placeholder="${R(o)}" maxlength="200">
74
74
  <div class="sox-meter" data-bind-data-tone="titleMeter.value.tone"><span class="sox-bar"><span data-bind-style-width="titleMeter.value.width"></span></span><span data-bind-text="titleMeter.value.text"></span></div></div>
75
75
  <div class="sox-wide"><label class="form-label" for="sox-i-desc">Description <span data-help="The grey text under the link. One or two sentences that make someone want to click. Empty uses the site's default - which every other such page shares."></span></label>
76
- <textarea id="sox-i-desc" rows="3" class="form-input" data-model="description.value" placeholder="${L(r)}" maxlength="400"></textarea>
76
+ <textarea id="sox-i-desc" rows="3" class="form-input" data-model="description.value" placeholder="${R(r)}" maxlength="400"></textarea>
77
77
  <div class="sox-meter" data-bind-data-tone="descMeter.value.tone"><span class="sox-bar"><span data-bind-style-width="descMeter.value.width"></span></span><span data-bind-text="descMeter.value.text"></span></div></div>
78
78
  <div><label class="form-label" for="sox-i-focus">Focus keyphrase <span data-help="The search this page should be found for - 'garden tools', 'plumber in Leeds'. The checks then look for it in the title, description, heading, address and opening. It is not shown anywhere."></span></label>
79
79
  <input id="sox-i-focus" class="form-input" data-model="focus.value" maxlength="100"></div>
80
80
  <div><label class="form-label" for="sox-i-image">Share image <span data-help="Shown when the page is shared. 1200 \xD7 630 pixels is ideal. Choose it from Media (or upload one), or type a full address. Empty uses the site's default image."></span></label>
81
- <div class="sox-pick"><input id="sox-i-image" class="form-input sox-mono" data-model="image.value" list="sox-media" placeholder="${L(c||"/media/\u2026")}">
81
+ <div class="sox-pick"><input id="sox-i-image" class="form-input sox-mono" data-model="image.value" list="sox-media" placeholder="${R(d||"/media/\u2026")}">
82
82
  <button type="button" class="btn btn-sm btn-ghost" data-on-click="pickImage"><span data-icon="image"></span> Choose\u2026</button></div></div>
83
83
  <label class="sox-wide" style="display:flex;align-items:center;gap:.5rem"><input type="checkbox" class="form-switch" data-model="noindex.value"> Hide from search engines
84
84
  <span data-help="Asks search engines not to list this page, and leaves it out of the sitemap. For thank-you pages, private landing pages and the like. It stays reachable by its address."></span></label>
@@ -92,10 +92,10 @@ import{apiRequest as ys}from"../api.js";import{addBannerAction as xs}from"../lib
92
92
  <button type="button" class="btn btn-sm btn-ghost" data-on-click="cancel">Close</button>
93
93
  <button type="button" class="btn btn-sm btn-primary" data-on-click="save" data-bind-disabled="cannot.value"><span data-icon="save" data-icon-size="13"></span> Save and check</button>
94
94
  </div>
95
- </div>`);K.querySelector(".sox-checks").innerHTML=Xs,es(K.querySelector("#sox-media"));let Te=null;async function gt(){if(b.cannot.peek())return;q.value=!0;const x=X();try{if(await g("/item",{method:"PUT",body:JSON.stringify({path:e,...x})}),Te?.saved(x,J(Xt(x))),!n())return;E.toast("Saved.",{type:"success"});const v=await g(`/item?path=${encodeURIComponent(e)}`).catch(()=>null);if(!n())return;v?.fields&&Te?.saved(x,J(v.fields)),v?.analysis&&(u(v.analysis),h.value=`Score ${v.analysis.score}% \xB7 ${v.analysis.failing} failing, ${v.analysis.warnings} could be better`),De(),oe(),$t()}catch(v){if(!n())return;$e(v)&&(B.value=!1),E.toast(`Not saved: ${v.message||v}`,{type:"error"})}finally{q.value=!1}}D.element.appendChild(K);const hs=d.helpPopovers(K),fs=M.applyBindings(b,K,{methods:{save:gt,cancel:()=>D.close(),pickImage:async()=>{const x=await ze({title:"Choose a share image",current:s.image.peek()});x&&(s.image.value=x)}}}),bs=K.querySelector(".sox-share-img"),vs=M.effect(()=>{bs.style.backgroundImage=j.value});K.addEventListener("keydown",x=>{(x.ctrlKey||x.metaKey)&&x.key==="Enter"&&(x.preventDefault(),gt())}),d.onceClosed(D,()=>{fs.dispose(),hs(),vs?.(),ne=!1});const yt=J(t.fields);Te=_e(D,{kind:"item",id:e,what:e,read:X,write:fe,was:yt}),I.scan(K),D.open(),Te.offer(yt)}let He=null;async function es(e){try{He??(He=await d.apiRequest("/media").then(t=>Array.isArray(t)?t:t?.files||t?.items||[]));for(const t of He){const s=t.url||t.path||(t.filename?`/media/${t.filename}`:"");s&&/\.(jpe?g|png|webp|gif|avif|svg)$/i.test(s)&&e.appendChild(Object.assign(document.createElement("option"),{value:s}))}}catch{He=[]}}let ie=!1;async function ht(){if(ie)return;ie=!0;let e,t,s;try{const a=await g("/settings");e=wt(a.settings),t=a.defaults||Ls(),s=J({settings:a.settings,defaults:t})}catch(a){ie=!1,n()&&E.toast(`Could not load the settings: ${a.message||a}`,{type:"error"});return}if(!n()){ie=!1;return}try{ts(e,s,t)}catch(a){ie=!1,E.toast(`Could not open the settings: ${a.message||a}`,{type:"error"})}}function ts(e,t,s){const a=e.organisation,l=w.peek()?.siteSeo?.defaultTitle||"The site's name",o={defaultTitle:M.observable(s.defaultTitle),titleSeparator:M.observable(s.titleSeparator),defaultDescription:M.observable(s.defaultDescription),defaultImage:M.observable(s.defaultImage),orgOn:M.observable(a.enabled),orgType:M.observable(a.type),orgName:M.observable(a.name),orgUrl:M.observable(a.url),orgLogo:M.observable(a.logo),orgEmail:M.observable(a.email),orgPhone:M.observable(a.phone),orgSame:M.observable(a.sameAs.join(`
95
+ </div>`);K.querySelector(".sox-checks").innerHTML=ta,as(K.querySelector("#sox-media"));let Te=null;async function yt(){if(b.cannot.peek())return;q.value=!0;const x=X();try{if(await v("/item",{method:"PUT",body:JSON.stringify({path:e,...x})}),Te?.saved(x,J(ts(x))),!n())return;E.toast("Saved.",{type:"success"});const g=await v(`/item?path=${encodeURIComponent(e)}`).catch(()=>null);if(!n())return;g?.fields&&Te?.saved(x,J(g.fields)),g?.analysis&&(u(g.analysis),h.value=`Score ${g.analysis.score}% \xB7 ${g.analysis.failing} failing, ${g.analysis.warnings} could be better`),De(),oe(),St()}catch(g){if(!n())return;$e(g)&&(B.value=!1),E.toast(`Not saved: ${g.message||g}`,{type:"error"})}finally{q.value=!1}}D.element.appendChild(K);const vs=c.helpPopovers(K),gs=M.applyBindings(b,K,{methods:{save:yt,cancel:()=>D.close(),pickImage:async()=>{const x=await ze({title:"Choose a share image",current:s.image.peek()});x&&(s.image.value=x)}}}),ys=K.querySelector(".sox-share-img"),xs=M.effect(()=>{ys.style.backgroundImage=j.value});K.addEventListener("keydown",x=>{(x.ctrlKey||x.metaKey)&&x.key==="Enter"&&(x.preventDefault(),yt())}),c.onceClosed(D,()=>{gs.dispose(),vs(),xs?.(),ne=!1});const xt=J(t.fields);Te=_e(D,{kind:"item",id:e,what:e,read:X,write:fe,was:xt}),I.scan(K),D.open(),Te.offer(xt)}let He=null;async function as(e){try{He??(He=await c.apiRequest("/media").then(t=>Array.isArray(t)?t:t?.files||t?.items||[]));for(const t of He){const s=t.url||t.path||(t.filename?`/media/${t.filename}`:"");s&&/\.(jpe?g|png|webp|gif|avif|svg)$/i.test(s)&&e.appendChild(Object.assign(document.createElement("option"),{value:s}))}}catch{He=[]}}let ie=!1;async function ft(){if(ie)return;ie=!0;let e,t,s;try{const a=await v("/settings");e=kt(a.settings),t=a.defaults||As(),s=J({settings:a.settings,defaults:t})}catch(a){ie=!1,n()&&E.toast(`Could not load the settings: ${a.message||a}`,{type:"error"});return}if(!n()){ie=!1;return}try{os(e,s,t)}catch(a){ie=!1,E.toast(`Could not open the settings: ${a.message||a}`,{type:"error"})}}function os(e,t,s){const a=e.organisation,l=w.peek()?.siteSeo?.defaultTitle||"The site's name",o={defaultTitle:M.observable(s.defaultTitle),titleSeparator:M.observable(s.titleSeparator),defaultDescription:M.observable(s.defaultDescription),defaultImage:M.observable(s.defaultImage),orgOn:M.observable(a.enabled),orgType:M.observable(a.type),orgName:M.observable(a.name),orgUrl:M.observable(a.url),orgLogo:M.observable(a.logo),orgEmail:M.observable(a.email),orgPhone:M.observable(a.phone),orgSame:M.observable(a.sameAs.join(`
96
96
  `)),street:M.observable(a.address.street),locality:M.observable(a.address.locality),region:M.observable(a.address.region),postcode:M.observable(a.address.postcode),country:M.observable(a.address.country),articles:M.observable(e.articles),exclude:M.observable(e.sitemap.exclude.join(`
97
- `)),blockAll:M.observable(e.robots.blockAll),llms:M.observable(e.llms.enabled),robotsExtra:M.observable(e.robots.extra),onRename:M.observable(e.redirects.onRename),every:M.observable(String(e.audit.everyHours)),tMin:M.observable(String(e.audit.titleMin)),tMax:M.observable(String(e.audit.titleMax)),dMin:M.observable(String(e.audit.descMin)),dMax:M.observable(String(e.audit.descMax)),words:M.observable(String(e.audit.minWords))},r=()=>({organisation:{enabled:o.orgOn.value,type:o.orgType.value,name:o.orgName.value,url:o.orgUrl.value,logo:o.orgLogo.value,email:o.orgEmail.value,phone:o.orgPhone.value,sameAs:o.orgSame.value,address:{street:o.street.value,locality:o.locality.value,region:o.region.value,postcode:o.postcode.value,country:o.country.value}},articles:o.articles.value,sitemap:{exclude:o.exclude.value,sources:e.sitemap.sources},robots:{blockAll:o.blockAll.value,extra:o.robotsExtra.value},llms:{enabled:o.llms.value},redirects:{onRename:o.onRename.value},audit:{everyHours:o.every.value,titleMin:o.tMin.value,titleMax:o.tMax.value,descMin:o.dMin.value,descMax:o.dMax.value,minWords:o.words.value}}),c=()=>Object.fromEntries(Object.entries(o).map(([p,b])=>[p,b.peek()])),y=p=>{for(const[b,D]of Object.entries(o))b in p&&(D.value=p[b])},$=M.observable(!1),k=M.computed(()=>Ts(r(),e)),O=M.computed(()=>Os(Object.fromEntries(Object.keys(s).map(p=>[p,o[p].value])))),_=M.computed(()=>[Object.values(k.value.errors).join(" "),O.value.error].filter(Boolean).join(" ")),H={...o,saving:$,errText:_,cannot:M.computed(()=>$.value||!!_.value),isPerson:M.computed(()=>o.orgType.value==="Person")},f=(p,b,D,re="",be="")=>`<div><label class="form-label" for="sox-s-${p}">${D}${re?` <span data-help="${L(re)}"></span>`:""}</label>
98
- <input id="sox-s-${p}" class="form-input" data-model="${b}.value" ${be}></div>`,T=(p,b,D,re,be,K="")=>f(p,b,D,K,`type="number" min="${re}" max="${be}"`),P=(p,b,D="")=>`<label class="sox-wide" style="display:flex;align-items:center;gap:.5rem"><input type="checkbox" class="form-switch" data-model="${p}.value"> ${b}${D?` <span data-help="${L(D)}"></span>`:""}</label>`,j=E.slideover({title:"SEO settings",size:"md",position:"right"}),C=Ve(`
97
+ `)),blockAll:M.observable(e.robots.blockAll),llms:M.observable(e.llms.enabled),robotsExtra:M.observable(e.robots.extra),onRename:M.observable(e.redirects.onRename),every:M.observable(String(e.audit.everyHours)),tMin:M.observable(String(e.audit.titleMin)),tMax:M.observable(String(e.audit.titleMax)),dMin:M.observable(String(e.audit.descMin)),dMax:M.observable(String(e.audit.descMax)),words:M.observable(String(e.audit.minWords))},r=()=>({organisation:{enabled:o.orgOn.value,type:o.orgType.value,name:o.orgName.value,url:o.orgUrl.value,logo:o.orgLogo.value,email:o.orgEmail.value,phone:o.orgPhone.value,sameAs:o.orgSame.value,address:{street:o.street.value,locality:o.locality.value,region:o.region.value,postcode:o.postcode.value,country:o.country.value}},articles:o.articles.value,sitemap:{exclude:o.exclude.value,sources:e.sitemap.sources},robots:{blockAll:o.blockAll.value,extra:o.robotsExtra.value},llms:{enabled:o.llms.value},redirects:{onRename:o.onRename.value},audit:{everyHours:o.every.value,titleMin:o.tMin.value,titleMax:o.tMax.value,descMin:o.dMin.value,descMax:o.dMax.value,minWords:o.words.value}}),d=()=>Object.fromEntries(Object.entries(o).map(([p,b])=>[p,b.peek()])),y=p=>{for(const[b,D]of Object.entries(o))b in p&&(D.value=p[b])},$=M.observable(!1),k=M.computed(()=>Ls(r(),e)),L=M.computed(()=>Is(Object.fromEntries(Object.keys(s).map(p=>[p,o[p].value])))),_=M.computed(()=>[Object.values(k.value.errors).join(" "),L.value.error].filter(Boolean).join(" ")),H={...o,saving:$,errText:_,cannot:M.computed(()=>$.value||!!_.value),isPerson:M.computed(()=>o.orgType.value==="Person")},f=(p,b,D,re="",be="")=>`<div><label class="form-label" for="sox-s-${p}">${D}${re?` <span data-help="${R(re)}"></span>`:""}</label>
98
+ <input id="sox-s-${p}" class="form-input" data-model="${b}.value" ${be}></div>`,T=(p,b,D,re,be,K="")=>f(p,b,D,K,`type="number" min="${re}" max="${be}"`),P=(p,b,D="")=>`<label class="sox-wide" style="display:flex;align-items:center;gap:.5rem"><input type="checkbox" class="form-switch" data-model="${p}.value"> ${b}${D?` <span data-help="${R(D)}"></span>`:""}</label>`,j=E.slideover({title:"SEO settings",size:"md",position:"right"}),C=Ve(`
99
99
  <div class="sox-form">
100
100
  <section><h4>Site defaults</h4><p class="sox-note">Used by pages without their own SEO values.</p><div class="sox-form-grid">
101
101
  ${f("default-title","defaultTitle","Default site title")}
@@ -109,8 +109,8 @@ import{apiRequest as ys}from"../api.js";import{addBannerAction as xs}from"../lib
109
109
  <section><h4>Who is behind the site <span data-help="Structured data on the home page, so search engines can show the name, logo and contact details - a knowledge panel, or a local business in maps."></span></h4><div class="sox-form-grid">
110
110
  ${P("orgOn","Tell search engines who runs the site")}
111
111
  <div><label class="form-label" for="sox-s-type">It is</label><select id="sox-s-type" class="form-input" data-model="orgType.value">
112
- ${Cs.map(p=>`<option value="${p}">${{Organization:"An organisation",LocalBusiness:"A local business",Person:"A person"}[p]}</option>`).join("")}</select></div>
113
- ${f("name","orgName","Name","Empty uses the site's name.",`placeholder="${L(l)}"`)}
112
+ ${Rs.map(p=>`<option value="${p}">${{Organization:"An organisation",LocalBusiness:"A local business",Person:"A person"}[p]}</option>`).join("")}</select></div>
113
+ ${f("name","orgName","Name","Empty uses the site's name.",`placeholder="${R(l)}"`)}
114
114
  ${f("url","orgUrl","Web address","Empty uses the site address.",'placeholder="https://\u2026"')}
115
115
  <div><label class="form-label" for="sox-s-logo">Logo (or photo) <span data-help="A square image works best. Choose it from Media (or upload one), or type a full address."></span></label>
116
116
  <div class="sox-pick"><input id="sox-s-logo" class="form-input sox-mono" data-model="orgLogo.value" placeholder="/media/logo.png">
@@ -150,7 +150,7 @@ import{apiRequest as ys}from"../api.js";import{addBannerAction as xs}from"../lib
150
150
  <button type="button" class="btn btn-sm btn-ghost" data-on-click="cancel">Cancel</button>
151
151
  <button type="button" class="btn btn-sm btn-primary" data-on-click="save" data-bind-disabled="cannot.value"><span data-icon="save" data-icon-size="13"></span> Save</button>
152
152
  </div>
153
- </div>`);let u=null;async function h(){if(H.cannot.peek())return;$.value=!0;const p=c();C.inert=!0;try{const b=await g("/settings",{method:"PUT",body:JSON.stringify({...k.peek().settings,siteDefaults:O.peek().defaults})});if(u?.saved(p,J({settings:b?.settings,defaults:b?.defaults})),j.close(!0),!n())return;E.toast("Settings saved.",{type:"success"}),qe()}catch(b){C.inert=!1,n()&&E.toast(`Not saved: ${b.message||b}`,{type:"error"})}finally{$.value=!1}}j.element.appendChild(C);const X=d.helpPopovers(C),fe=M.applyBindings(H,C,{methods:{save:h,cancel:()=>j.close(),pickDefaultImage:async()=>{const p=await ze({title:"Choose a default share image",current:o.defaultImage.peek()});p&&(o.defaultImage.value=p)},pickLogo:async()=>{const p=await ze({title:"Choose a logo",current:o.orgLogo.peek()});p&&(o.orgLogo.value=p)}}}),q=Rs(C.querySelector("[data-google-business]"),{read:c,apply:y});C.addEventListener("keydown",p=>{(p.ctrlKey||p.metaKey)&&p.key==="Enter"&&(p.preventDefault(),h())}),d.onceClosed(j,()=>{q(),fe.dispose(),X(),ie=!1}),u=_e(j,{kind:"settings",what:"the SEO settings",read:c,write:y,was:t}),I.scan(C),j.open(),u.offer(t)}async function ss(e,t){try{const s=await g("/settings"),a=wt(s.settings);if(a.sitemap.sources[e]=t,await g("/settings",{method:"PUT",body:JSON.stringify(a)}),!n())return;E.toast(`${se(e)} ${t?"back in":"left out of"} the sitemap.`,{type:"success"}),Ne()}catch(s){n()&&E.toast(`Not changed: ${s.message||s}`,{type:"error"})}}const z=e=>Number(String(e?.dataset?.row||"").slice(1));function as(e){const t=Me[z(e)];return t?[{header:t.urlPath},{label:"Title, description and checks\u2026",icon:"edit-3",action:()=>ee(t.urlPath)},{label:"Open the page",icon:"external-link",action:()=>window.open(t.urlPath,"_blank","noopener")},{label:"Redirect it elsewhere\u2026",icon:"corner-up-right",disabled:!B.peek(),action:()=>{V("redirects"),we.value=t.urlPath,ke.value=""}},{type:"divider"},{label:"Copy the address",icon:"copy",action:()=>ge(t.urlPath,"the address")},{label:"Copy the problems",icon:"clipboard",disabled:!t.problems?.length&&!t.error,action:()=>ge(`${t.urlPath}
153
+ </div>`);let u=null;async function h(){if(H.cannot.peek())return;$.value=!0;const p=d();C.inert=!0;try{const b=await v("/settings",{method:"PUT",body:JSON.stringify({...k.peek().settings,siteDefaults:L.peek().defaults})});if(u?.saved(p,J({settings:b?.settings,defaults:b?.defaults})),j.close(!0),!n())return;E.toast("Settings saved.",{type:"success"}),qe()}catch(b){C.inert=!1,n()&&E.toast(`Not saved: ${b.message||b}`,{type:"error"})}finally{$.value=!1}}j.element.appendChild(C);const X=c.helpPopovers(C),fe=M.applyBindings(H,C,{methods:{save:h,cancel:()=>j.close(),pickDefaultImage:async()=>{const p=await ze({title:"Choose a default share image",current:o.defaultImage.peek()});p&&(o.defaultImage.value=p)},pickLogo:async()=>{const p=await ze({title:"Choose a logo",current:o.orgLogo.peek()});p&&(o.orgLogo.value=p)}}}),q=Ps(C.querySelector("[data-google-business]"),{read:d,apply:y});C.addEventListener("keydown",p=>{(p.ctrlKey||p.metaKey)&&p.key==="Enter"&&(p.preventDefault(),h())}),c.onceClosed(j,()=>{q(),fe.dispose(),X(),ie=!1}),u=_e(j,{kind:"settings",what:"the SEO settings",read:d,write:y,was:t}),I.scan(C),j.open(),u.offer(t)}async function ns(e,t){try{const s=await v("/settings"),a=kt(s.settings);if(a.sitemap.sources[e]=t,await v("/settings",{method:"PUT",body:JSON.stringify(a)}),!n())return;E.toast(`${se(e)} ${t?"back in":"left out of"} the sitemap.`,{type:"success"}),Ne()}catch(s){n()&&E.toast(`Not changed: ${s.message||s}`,{type:"error"})}}const z=e=>Number(String(e?.dataset?.row||"").slice(1));function is(e){const t=Me[z(e)];return t?[{header:t.urlPath},{label:"Title, description and checks\u2026",icon:"edit-3",action:()=>ee(t.urlPath)},{label:"Open the page",icon:"external-link",action:()=>window.open(t.urlPath,"_blank","noopener")},{label:"Redirect it elsewhere\u2026",icon:"corner-up-right",disabled:!B.peek(),action:()=>{V("redirects"),we.value=t.urlPath,ke.value=""}},{type:"divider"},{label:"Copy the address",icon:"copy",action:()=>ge(t.urlPath,"the address")},{label:"Copy the problems",icon:"clipboard",disabled:!t.problems?.length&&!t.error,action:()=>ge(`${t.urlPath}
154
154
  ${t.error||t.problems.join(`
155
- `)}`,"the problems")}]:[]}function os(e){const t=G[z(e)];return t?t.kind==="dupe"?[{header:"Open one of them"},...t.paths.slice(0,12).map(s=>({label:s,icon:"edit-3",action:()=>ee(s)})),{type:"divider"},{label:"Copy the addresses",icon:"copy",action:()=>ge(t.paths.join(`
156
- `),"the addresses")}]:t.kind==="chains"?[{label:"Show the redirects",icon:"corner-up-right",action:()=>V("redirects")}]:[{label:"Go to Settings",icon:"settings",action:()=>{location.hash=t.link}}]:[]}function ns(e){const t=G[z(e)];t?.kind==="dupe"?ee(t.paths[0]):t?.kind==="chains"?V("redirects"):t?.link&&(location.hash=t.link)}function is(e){const t=ue[z(e)];if(!t)return[];const s=N.peek().rules,a=N.peek().chains.some(o=>o.id===t.id);let l=null;if(a){l=t.to;for(let o=0;o<10;o++){const r=Es(s,l);if(!r)break;if(r.code===410){l=null;break}if(l=r.location,/^https?:/i.test(l))break}}return[{header:`${t.from} \u2192 ${t.code===410?"gone":t.to}`},{label:"Edit\u2026",icon:"edit-3",disabled:!B.peek(),action:()=>Be(t)},{label:"Test it",icon:"play",action:()=>Yt(t.from)},{label:"Go straight there",icon:"fast-forward",disabled:!l||!B.peek(),action:()=>Ue(()=>g(`/redirects/${encodeURIComponent(t.id)}`,{method:"PUT",body:JSON.stringify({to:l})}),`${t.from} now goes straight to ${l}.`)},{label:"Open the old address",icon:"external-link",disabled:t.from.endsWith("/*"),action:()=>window.open(t.from,"_blank","noopener")},{type:"divider"},{label:"Copy",icon:"copy",action:()=>ge(`${t.from} ${t.to} ${t.code}`,"the redirect")},{label:"Remove",icon:"trash-2",danger:!0,disabled:!B.peek(),action:async()=>{await Xe(`Remove the redirect from ${t.from}? Visitors to it will get "not found".`)&&Jt([t.id],"Redirect")}}]}function ls(e){const t=ae[z(e)];return t?[{header:t.urlPath},{label:"Title, description and checks\u2026",icon:"edit-3",action:()=>ee(t.urlPath)},{label:"Open",icon:"external-link",action:()=>window.open(t.urlPath,"_blank","noopener")},{type:"divider"},{label:"Copy the address",icon:"copy",action:()=>ge(t.urlPath,"the address")}]:[]}function rs(e){const t=W.peek().sources[z(e)];return t?[{header:se(t.id)},{label:t.on?"Leave all of it out":"List it again",icon:t.on?"eye-off":"eye",disabled:!B.peek(),action:()=>ss(t.id,!t.on)}]:[]}function me(e,t,s){const a=E.contextMenu(e,{cursor:"glyph",match:"[data-row]",inherit:!1,density:"compact",items:r=>t(r)});A(()=>a?.destroy?.());const l=r=>{const c=r.target.closest("[data-row]");if(!(!c||r.target.closest("a"))){if(r.target.closest(".sox-kebab")){d.openMenuAt(c);return}s?.(c)}},o=r=>{const c=r.target.closest("[data-row]");c&&(r.key==="F10"&&r.shiftKey?(r.preventDefault(),d.openMenuAt(c)):r.key==="Enter"&&r.target===c&&(r.preventDefault(),r.stopPropagation(),setTimeout(()=>{n()&&c.isConnected&&s?.(c)},0)))};e.addEventListener("click",l),e.addEventListener("keydown",o),A(()=>{e.removeEventListener("click",l),e.removeEventListener("keydown",o)})}const cs=m.querySelector(".sox-ext"),We=m.querySelector(".sox-ext-tabs");let le=null,Ee="",he=0;const ft=()=>{const e=le;le=null;try{e?.dispose?.()}catch{}e?.box?.remove()};async function ds(){let e=[];try{e=(await g("/extensions"))?.tabs||[]}catch{}n()&&(tt.value=e,We.replaceChildren(...e.map(t=>{const s=document.createElement("button");return s.type="button",s.setAttribute("role","tab"),s.dataset.ext=t.key,s.innerHTML=`<span data-icon="${L(t.icon||"box")}" data-icon-size="14"></span> ${L(t.label)} <span class="sox-pro">PRO</span>`,t.help&&(s.title=t.help),s.addEventListener("click",()=>V(t.key)),s})),I.scan(We),bt())}async function bt(){if(!n())return;for(const l of We.querySelectorAll("button"))l.classList.toggle("is-on",l.dataset.ext===Y.peek());const e=tt.peek().find(l=>l.key===Y.peek());if(le&&le.key!==e?.key&&ft(),!e){Ee="",he++,Mt.includes(Y.peek())||V("overview");return}if(le?.key===e.key||Ee===e.key)return;const t=++he;Ee=e.key;const s=document.createElement("div");s.className="sox-panel sox-ext-body",cs.replaceChildren(s);const a=()=>t===he&&n()&&Y.peek()===e.key;try{const l=await import(e.module);if(!a())return;const o=await l.mount(s,{kit:d,api:d.apiRequest,scope:A,here:n,openItem:ee,reload:qe,E,M,I});if(!a()){try{o?.()}catch{}s.remove();return}le={key:e.key,dispose:o,box:s}}catch(l){a()&&(s.innerHTML=`<p class="sox-note is-bad">${L(e.label)} could not be shown: ${L(l.message||l)}</p>`)}finally{t===he&&(Ee="")}}A(()=>{he++,ft()}),m.querySelector(".sox-pages").innerHTML=Fs,m.querySelector(".sox-site").innerHTML=Js,m.querySelector(".sox-rules").innerHTML=Ys,m.querySelector(".sox-entries").innerHTML=Qs,m.querySelector(".sox-sources").innerHTML=Vs;const vt=m.querySelector(".sox-select");A(M.effect(()=>{const e=nt.value;vt.replaceChildren(new Option("Everything",""),...e.map(t=>new Option(se(t),t))),vt.value=xe.peek()}));function V(e){Y.peek()!==e&&(Y.value=e,history.replaceState(null,"",`#/seo${e==="overview"?"":`/${e}`}`),e==="redirects"&&pe(),e==="sitemap"&&Ne()),bt()}const us={tab:Y,busy:Ce,error:Oe,canManage:B,scoreText:Lt,scoreWidth:Rt,scoreTone:It,ov:At,attention:Pt,asOf:jt,sourceOptions:nt,source:xe,show:te,query:Le,pageRows:it,pagesEmpty:Nt,siteRows:lt,ruleRows:Ae,ruleCount:qt,ruleText:Ut,rulesEmpty:Bt,chainText:_t,renameText:Ht,ruleQuery:Re,newFrom:we,newTo:ke,newCode:et,sourceRows:rt,smRows:Pe,smShow:de,smQuery:Ie,smText:Gt,smEmpty:zt,robots:Wt,extOn:Ot,counts:Dt,smCounts:Kt,pagesLoading:st,rulesLoading:at,smLoading:ot},ps={tab_overview:()=>V("overview"),tab_redirects:()=>V("redirects"),tab_sitemap:()=>V("sitemap"),show_all:()=>{te.value="all"},show_problems:()=>{te.value="problems"},show_hidden:()=>{te.value="hidden"},sm_in:()=>{de.value="in"},sm_out:()=>{de.value="out"},importCsv:Qt,exportRules:()=>{const e=N.peek().rules;if(!e.length){E.toast("Nothing to export.",{type:"info"});return}zs(`redirects-${location.hostname}-${new Date().toISOString().slice(0,10)}.csv`,Gs(e.map(t=>({from:t.from,to:t.to,code:t.code,note:t.note||"",hits:t.hits||0,last_used:t.lastHit||""}))))},addRule:()=>{const e={from:we.peek(),to:ke.peek(),code:Number(et.peek())},{errors:t}=xt(e,N.peek().rules);return Object.keys(t).length?(E.toast(Object.values(t).join(" "),{type:"warning"}),!1):(Ft(e).then(s=>{s&&(we.value="",ke.value="")}),!1)}},ms=M.applyBindings(us,m,{methods:ps});A(()=>ms.dispose()),A(d.helpPopovers(m,{position:"bottom"})),me(m.querySelector(".sox-pages"),as,e=>{const t=Me[z(e)];t&&ee(t.urlPath)}),me(m.querySelector(".sox-site"),os,ns),me(m.querySelector(".sox-rules"),is,e=>{const t=ue[z(e)];t&&B.peek()&&Be(t)}),me(m.querySelector(".sox-entries"),ls,e=>{const t=ae[z(e)];t&&ee(t.urlPath)}),me(m.querySelector(".sox-sources"),rs),d.addBannerAction(i,{id:"seo-check",icon:"refresh-cw",title:"Check every page again",onClick:dt}),d.addBannerAction(i,{id:"seo-settings",icon:"settings",title:"SEO settings",onClick:ht}),I.scan(m),await Promise.all([qe(),ds()]),n()&&new URLSearchParams(location.hash.split("?")[1]||"").get("settings")==="1"&&ht(),n()&&I.scan(m),n()&&!w.peek()?.at&&!w.peek()?.running&&dt()}};
155
+ `)}`,"the problems")}]:[]}function ls(e){const t=G[z(e)];return t?t.kind==="dupe"?[{header:"Open one of them"},...t.paths.slice(0,12).map(s=>({label:s,icon:"edit-3",action:()=>ee(s)})),{type:"divider"},{label:"Copy the addresses",icon:"copy",action:()=>ge(t.paths.join(`
156
+ `),"the addresses")}]:t.kind==="chains"?[{label:"Show the redirects",icon:"corner-up-right",action:()=>V("redirects")}]:[{label:"Go to Settings",icon:"settings",action:()=>{location.hash=t.link}}]:[]}function rs(e){const t=G[z(e)];t?.kind==="dupe"?ee(t.paths[0]):t?.kind==="chains"?V("redirects"):t?.link&&(location.hash=t.link)}function cs(e){const t=ue[z(e)];if(!t)return[];const s=N.peek().rules,a=N.peek().chains.some(o=>o.id===t.id);let l=null;if(a){l=t.to;for(let o=0;o<10;o++){const r=Os(s,l);if(!r)break;if(r.code===410){l=null;break}if(l=r.location,/^https?:/i.test(l))break}}return[{header:`${t.from} \u2192 ${t.code===410?"gone":t.to}`},{label:"Edit\u2026",icon:"edit-3",disabled:!B.peek(),action:()=>Be(t)},{label:"Test it",icon:"play",action:()=>Xt(t.from)},{label:"Go straight there",icon:"fast-forward",disabled:!l||!B.peek(),action:()=>Ue(()=>v(`/redirects/${encodeURIComponent(t.id)}`,{method:"PUT",body:JSON.stringify({to:l})}),`${t.from} now goes straight to ${l}.`)},{label:"Open the old address",icon:"external-link",disabled:t.from.endsWith("/*"),action:()=>window.open(t.from,"_blank","noopener")},{type:"divider"},{label:"Copy",icon:"copy",action:()=>ge(`${t.from} ${t.to} ${t.code}`,"the redirect")},{label:"Remove",icon:"trash-2",danger:!0,disabled:!B.peek(),action:async()=>{await Xe(`Remove the redirect from ${t.from}? Visitors to it will get "not found".`)&&Vt([t.id],"Redirect")}}]}function ds(e){const t=ae[z(e)];return t?[{header:t.urlPath},{label:"Title, description and checks\u2026",icon:"edit-3",action:()=>ee(t.urlPath)},{label:"Open",icon:"external-link",action:()=>window.open(t.urlPath,"_blank","noopener")},{type:"divider"},{label:"Copy the address",icon:"copy",action:()=>ge(t.urlPath,"the address")}]:[]}function us(e){const t=W.peek().sources[z(e)];return t?[{header:se(t.id)},{label:t.on?"Leave all of it out":"List it again",icon:t.on?"eye-off":"eye",disabled:!B.peek(),action:()=>ns(t.id,!t.on)}]:[]}function me(e,t,s){const a=E.contextMenu(e,{cursor:"glyph",match:"[data-row]",inherit:!1,density:"compact",items:r=>t(r)});O(()=>a?.destroy?.());const l=r=>{const d=r.target.closest("[data-row]");if(!(!d||r.target.closest("a"))){if(r.target.closest(".sox-kebab")){c.openMenuAt(d);return}s?.(d)}},o=r=>{const d=r.target.closest("[data-row]");d&&(r.key==="F10"&&r.shiftKey?(r.preventDefault(),c.openMenuAt(d)):r.key==="Enter"&&r.target===d&&(r.preventDefault(),r.stopPropagation(),setTimeout(()=>{n()&&d.isConnected&&s?.(d)},0)))};e.addEventListener("click",l),e.addEventListener("keydown",o),O(()=>{e.removeEventListener("click",l),e.removeEventListener("keydown",o)})}const ps=m.querySelector(".sox-ext"),We=m.querySelector(".sox-ext-tabs");let le=null,Ee="",he=0;const bt=()=>{const e=le;le=null;try{e?.dispose?.()}catch{}e?.box?.remove()};async function ms(){let e=[];try{e=(await v("/extensions"))?.tabs||[]}catch{}n()&&(st.value=e,We.replaceChildren(...e.map(t=>{const s=document.createElement("button");return s.type="button",s.setAttribute("role","tab"),s.dataset.ext=t.key,s.innerHTML=`<span data-icon="${R(t.icon||"box")}" data-icon-size="14"></span> ${R(t.label)} <span class="sox-pro">PRO</span>`,t.help&&(s.title=t.help),s.addEventListener("click",()=>V(t.key)),s})),I.scan(We),vt())}async function vt(){if(!n())return;for(const l of We.querySelectorAll("button"))l.classList.toggle("is-on",l.dataset.ext===Y.peek());const e=st.peek().find(l=>l.key===Y.peek());if(le&&le.key!==e?.key&&bt(),!e){Ee="",he++,$t.includes(Y.peek())||V("overview");return}if(le?.key===e.key||Ee===e.key)return;const t=++he;Ee=e.key;const s=document.createElement("div");s.className="sox-panel sox-ext-body",ps.replaceChildren(s);const a=()=>t===he&&n()&&Y.peek()===e.key;try{const l=await import(e.module);if(!a())return;const o=await l.mount(s,{kit:c,api:c.apiRequest,scope:O,here:n,openItem:ee,reload:qe,E,M,I});if(!a()){try{o?.()}catch{}s.remove();return}le={key:e.key,dispose:o,box:s}}catch(l){a()&&(s.innerHTML=`<p class="sox-note is-bad">${R(e.label)} could not be shown: ${R(l.message||l)}</p>`)}finally{t===he&&(Ee="")}}O(()=>{he++,bt()}),m.querySelector(".sox-pages").innerHTML=Qs,m.querySelector(".sox-site").innerHTML=Vs,m.querySelector(".sox-rules").innerHTML=Xs,m.querySelector(".sox-entries").innerHTML=Zs,m.querySelector(".sox-sources").innerHTML=ea;const gt=m.querySelector(".sox-select");O(M.effect(()=>{const e=it.value;gt.replaceChildren(new Option("Everything",""),...e.map(t=>new Option(se(t),t))),gt.value=xe.peek()}));function V(e){Y.peek()!==e&&(Y.value=e,history.replaceState(null,"",`#/seo${e==="overview"?"":`/${e}`}`),e==="redirects"&&pe(),e==="sitemap"&&Ne()),vt()}const hs={tab:Y,busy:Ce,error:Oe,canManage:B,scoreText:At,scoreWidth:Pt,scoreTone:jt,ov:Dt,attention:Nt,asOf:qt,sourceOptions:it,source:xe,show:te,query:Le,pageRows:lt,pagesEmpty:Bt,siteRows:rt,ruleRows:Ae,ruleCount:_t,ruleText:Ht,rulesEmpty:Wt,chainText:Kt,renameText:Gt,ruleQuery:Re,newFrom:we,newTo:ke,newCode:tt,sourceRows:ct,smRows:Pe,smShow:de,smQuery:Ie,smText:Jt,smEmpty:Yt,robots:zt,extOn:It,counts:Ut,smCounts:Ft,pagesLoading:at,rulesLoading:ot,smLoading:nt},fs={tab_overview:()=>V("overview"),tab_redirects:()=>V("redirects"),tab_sitemap:()=>V("sitemap"),show_all:()=>{te.value="all"},show_problems:()=>{te.value="problems"},show_hidden:()=>{te.value="hidden"},sm_in:()=>{de.value="in"},sm_out:()=>{de.value="out"},importCsv:Zt,exportRules:()=>{const e=N.peek().rules;if(!e.length){E.toast("Nothing to export.",{type:"info"});return}Ys(`redirects-${location.hostname}-${new Date().toISOString().slice(0,10)}.csv`,Js(e.map(t=>({from:t.from,to:t.to,code:t.code,note:t.note||"",hits:t.hits||0,last_used:t.lastHit||""}))))},addRule:()=>{const e={from:we.peek(),to:ke.peek(),code:Number(tt.peek())},{errors:t}=wt(e,N.peek().rules);return Object.keys(t).length?(E.toast(Object.values(t).join(" "),{type:"warning"}),!1):(Qt(e).then(s=>{s&&(we.value="",ke.value="")}),!1)}},bs=M.applyBindings(hs,m,{methods:fs});et(m.querySelector('.sox-add input[aria-label="To"]')).then(e=>{e&&O(()=>e.dispose())}),O(()=>bs.dispose()),O(c.helpPopovers(m,{position:"bottom"})),me(m.querySelector(".sox-pages"),is,e=>{const t=Me[z(e)];t&&ee(t.urlPath)}),me(m.querySelector(".sox-site"),ls,rs),me(m.querySelector(".sox-rules"),cs,e=>{const t=ue[z(e)];t&&B.peek()&&Be(t)}),me(m.querySelector(".sox-entries"),ds,e=>{const t=ae[z(e)];t&&ee(t.urlPath)}),me(m.querySelector(".sox-sources"),us),c.addBannerAction(i,{id:"seo-check",icon:"refresh-cw",title:"Check every page again",onClick:ut}),c.addBannerAction(i,{id:"seo-settings",icon:"settings",title:"SEO settings",onClick:ft}),I.scan(m),await Promise.all([qe(),ms()]),n()&&new URLSearchParams(location.hash.split("?")[1]||"").get("settings")==="1"&&ft(),n()&&I.scan(m),n()&&!w.peek()?.at&&!w.peek()?.running&&ut()}};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "domma-cms",
3
- "version": "1.26.0",
3
+ "version": "1.26.2",
4
4
  "description": "File-based CMS powered by Domma and Fastify. Run npx domma-cms my-site to create a new project.",
5
5
  "type": "module",
6
6
  "main": "server/server.js",
@@ -0,0 +1,379 @@
1
+ /**
2
+ * Page menu - a drop menu of the site's pages, in their hierarchy, beside a
3
+ * text box that stays open for anything else.
4
+ *
5
+ * The typing always wins: picking a page fills the box in, it does not lock
6
+ * it. A redirect can go to an external site, a file or an address that is
7
+ * not a page yet, so a control that ONLY offered pages would be a downgrade.
8
+ *
9
+ * attachPageMenu(input, {load}) -> {open, close, dispose}
10
+ *
11
+ * `load()` resolves to `[{urlPath, title}]` (the SEO audit's results fit
12
+ * as they are). It is called once, on first focus or open; many inputs on
13
+ * one screen should share one memoised loader. The hierarchy comes from the addresses: /services/web sits
14
+ * under /services, and a level with no page of its own (/docs when only
15
+ * /docs/setup exists) is shown as a heading, not offered as a target.
16
+ *
17
+ * Typing filters the menu (a match keeps its parents, so it still reads as a
18
+ * tree); the arrow button shows everything. Arrow keys move, Enter picks,
19
+ * Escape closes the menu without closing a slideover around it.
20
+ *
21
+ * The panel lives on document.body with fixed positioning, so a scrolling
22
+ * list or a slideover cannot clip it. Focus never leaves the input, which is
23
+ * what keeps a slideover's focus trap happy. Theme tokens only (--dm-*).
24
+ *
25
+ * Imported over HTTP by plugins (`/plugins/_lib/admin/ui/page-menu.js`) and by
26
+ * core's SEO screen. `pageTree` / `filterTree` are pure and DOM-free.
27
+ */
28
+
29
+ /**
30
+ * The rows of the menu, in order: every page plus a heading for each level
31
+ * that has none, each with its depth.
32
+ *
33
+ * @param {Array<{urlPath: string, label?: string, title?: string}>} items - `label` (a page's own name, as the SEO audit gives it) is preferred to `title`
34
+ * @returns {Array<{path: string, label: string, depth: number, page: boolean, parent: string|null}>}
35
+ */
36
+ export function pageTree(items) {
37
+ const pages = new Map();
38
+ for (const it of Array.isArray(items) ? items : []) {
39
+ const raw = typeof it?.urlPath === 'string' ? it.urlPath.trim() : '';
40
+ if (!raw.startsWith('/') || raw.startsWith('//')) continue;
41
+ const path = raw.length > 1 ? raw.replace(/\/+$/, '') : '/';
42
+ if (pages.has(path)) continue;
43
+ const label = String(it.label || it.title || '').trim();
44
+ pages.set(path, label);
45
+ }
46
+ // A node per address and per level above it.
47
+ const nodes = new Map();
48
+ const node = (path) => {
49
+ if (!nodes.has(path)) nodes.set(path, {path, children: []});
50
+ return nodes.get(path);
51
+ };
52
+ const top = [];
53
+ for (const path of pages.keys()) {
54
+ if (path === '/') { node('/'); continue; }
55
+ const segs = path.slice(1).split('/');
56
+ for (let i = 1; i <= segs.length; i++) {
57
+ const p = `/${segs.slice(0, i).join('/')}`;
58
+ const fresh = !nodes.has(p);
59
+ const n = node(p);
60
+ if (!fresh) continue;
61
+ if (i === 1) top.push(n);
62
+ else node(`/${segs.slice(0, i - 1).join('/')}`).children.push(n);
63
+ }
64
+ }
65
+ const byPath = (a, b) => a.path.localeCompare(b.path, 'en', {sensitivity: 'base', numeric: true});
66
+ const out = [];
67
+ const walk = (n, depth, parent) => {
68
+ const page = pages.has(n.path);
69
+ const seg = n.path.split('/').pop() || '/';
70
+ out.push({path: n.path, label: page ? (pages.get(n.path) || seg) : seg, depth, page, parent});
71
+ n.children.sort(byPath).forEach(c => walk(c, depth + 1, n.path));
72
+ };
73
+ // The home page heads the list; everything else is a top level of its own.
74
+ if (pages.has('/')) out.push({path: '/', label: pages.get('/') || 'Home', depth: 0, page: true, parent: null});
75
+ top.sort(byPath).forEach(n => walk(n, 0, null));
76
+ return out;
77
+ }
78
+
79
+ /**
80
+ * The rows that match `query` (address or title, any case), each with the
81
+ * parents it needs so the tree still reads. An empty query keeps them all.
82
+ *
83
+ * @param {ReturnType<typeof pageTree>} rows
84
+ * @param {string} query
85
+ * @returns {ReturnType<typeof pageTree>}
86
+ */
87
+ export function filterTree(rows, query) {
88
+ const q = String(query ?? '').trim().toLowerCase();
89
+ if (!q) return rows;
90
+ const keep = new Set();
91
+ const parentOf = new Map(rows.map(r => [r.path, r.parent]));
92
+ for (const r of rows) {
93
+ if (!r.page) continue;
94
+ if (!r.path.toLowerCase().includes(q) && !r.label.toLowerCase().includes(q)) continue;
95
+ for (let p = r.path; p != null && !keep.has(p); p = parentOf.get(p)) keep.add(p);
96
+ }
97
+ return rows.filter(r => keep.has(r.path));
98
+ }
99
+
100
+ const STYLE_ID = 'dm-page-menu-styles';
101
+ const CSS = `
102
+ .dm-pm-wrap { display: flex; align-items: stretch; min-width: 0; }
103
+ .dm-pm-wrap > input { flex: 1 1 auto; min-width: 0; border-top-right-radius: 0; border-bottom-right-radius: 0; }
104
+ .dm-pm-btn { flex: 0 0 auto; display: inline-flex; align-items: center; justify-content: center; width: 2rem; padding: 0;
105
+ border: 1px solid var(--dm-border); border-left: 0; border-radius: 0 var(--dm-radius-md, 6px) var(--dm-radius-md, 6px) 0;
106
+ background: var(--dm-surface, var(--dm-bg)); color: var(--dm-text-muted); cursor: pointer; }
107
+ .dm-pm-btn:hover:not(:disabled), .dm-pm-btn[aria-expanded="true"] { color: var(--dm-text); background: color-mix(in srgb, var(--dm-text) 6%, var(--dm-surface, var(--dm-bg))); }
108
+ .dm-pm-btn:disabled { opacity: .5; cursor: default; }
109
+ .dm-pm-btn svg { width: 14px; height: 14px; }
110
+ .dm-pm-panel { position: fixed; z-index: 10060; max-height: 18rem; overflow-y: auto; padding: .25rem 0; margin: 0; list-style: none;
111
+ background: var(--dm-surface, var(--dm-bg)); color: var(--dm-text); border: 1px solid var(--dm-border);
112
+ border-radius: var(--dm-radius-md, 6px); box-shadow: 0 8px 24px color-mix(in srgb, #000 22%, transparent); font-size: var(--dm-text-sm, 13px); }
113
+ .dm-pm-row { display: flex; align-items: baseline; gap: .6rem; padding: .3rem .7rem; cursor: pointer; white-space: nowrap; }
114
+ .dm-pm-row.is-active { background: color-mix(in srgb, var(--dm-primary) 14%, transparent); }
115
+ .dm-pm-row.is-current .dm-pm-title { font-weight: 600; }
116
+ .dm-pm-row.is-head { cursor: default; color: var(--dm-text-muted); font-size: var(--dm-text-xs, 12px); text-transform: uppercase; letter-spacing: .03em; }
117
+ .dm-pm-title { overflow: hidden; text-overflow: ellipsis; }
118
+ .dm-pm-path { margin-left: auto; padding-left: .8rem; color: var(--dm-text-muted); font-family: var(--dm-font-mono, monospace); font-size: var(--dm-text-xs, 12px); overflow: hidden; text-overflow: ellipsis; }
119
+ .dm-pm-empty { padding: .45rem .7rem; color: var(--dm-text-muted); }
120
+ `;
121
+
122
+ function injectStyles() {
123
+ if (typeof document === 'undefined' || document.getElementById(STYLE_ID)) return;
124
+ const s = document.createElement('style');
125
+ s.id = STYLE_ID;
126
+ s.textContent = CSS;
127
+ document.head.appendChild(s);
128
+ }
129
+
130
+ const CARET = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="6 9 12 15 18 9"></polyline></svg>';
131
+ let seq = 0;
132
+
133
+ /**
134
+ * Put the drop menu beside `input`. Calling it twice on one input returns
135
+ * the first handle.
136
+ *
137
+ * @param {HTMLInputElement} input
138
+ * @param {{load: () => Promise<Array<{urlPath: string, title?: string}>>, onPick?: (path: string) => void}} opts
139
+ * @returns {{open: (all?: boolean) => void, close: () => void, dispose: () => void}}
140
+ */
141
+ export function attachPageMenu(input, {load, onPick} = {}) {
142
+ if (input.__dmPageMenu) return input.__dmPageMenu;
143
+ injectStyles();
144
+ const id = `dm-pm-${++seq}`;
145
+
146
+ const wrap = document.createElement('span');
147
+ wrap.className = 'dm-pm-wrap';
148
+ input.parentNode.insertBefore(wrap, input);
149
+ wrap.appendChild(input);
150
+ const btn = document.createElement('button');
151
+ btn.type = 'button';
152
+ btn.className = 'dm-pm-btn';
153
+ btn.title = 'Pick a page';
154
+ btn.setAttribute('aria-label', 'Pick a page');
155
+ btn.setAttribute('aria-haspopup', 'listbox');
156
+ btn.setAttribute('aria-expanded', 'false');
157
+ btn.tabIndex = -1;
158
+ btn.innerHTML = CARET;
159
+ wrap.appendChild(btn);
160
+
161
+ input.setAttribute('role', 'combobox');
162
+ input.setAttribute('aria-autocomplete', 'list');
163
+ input.setAttribute('aria-expanded', 'false');
164
+ input.setAttribute('aria-controls', id);
165
+ // The browser's own suggestions would sit on top of the menu.
166
+ input.setAttribute('autocomplete', 'off');
167
+ input.removeAttribute('list');
168
+
169
+ let tree = null;
170
+ let loading = null;
171
+ let panel = null;
172
+ let shown = [];
173
+ let active = -1;
174
+ let picking = false;
175
+
176
+ const ensureTree = () => {
177
+ if (tree) return Promise.resolve(tree);
178
+ loading ??= Promise.resolve().then(() => load?.()).then(
179
+ (items) => { tree = pageTree(items); return tree; },
180
+ () => { tree = []; return tree; });
181
+ return loading;
182
+ };
183
+ // The disabled state of the input (a 410 has no target) carries to the button.
184
+ const syncDisabled = () => { btn.disabled = input.disabled; if (input.disabled) close(); };
185
+ const watch = new MutationObserver(syncDisabled);
186
+ watch.observe(input, {attributes: true, attributeFilter: ['disabled']});
187
+ syncDisabled();
188
+
189
+ function place() {
190
+ if (!panel) return;
191
+ if (!input.isConnected) { close(); return; }
192
+ const r = wrap.getBoundingClientRect();
193
+ const below = window.innerHeight - r.bottom;
194
+ const want = Math.min(panel.scrollHeight, 288);
195
+ panel.style.left = `${Math.max(4, r.left)}px`;
196
+ panel.style.width = `${Math.max(r.width, 320)}px`;
197
+ panel.style.maxWidth = `${Math.max(240, window.innerWidth - Math.max(4, r.left) - 8)}px`;
198
+ if (below < want + 8 && r.top > below) {
199
+ panel.style.top = '';
200
+ panel.style.bottom = `${window.innerHeight - r.top + 2}px`;
201
+ } else {
202
+ panel.style.bottom = '';
203
+ panel.style.top = `${r.bottom + 2}px`;
204
+ }
205
+ }
206
+
207
+ function draw(query) {
208
+ if (!panel) return;
209
+ shown = filterTree(tree || [], query);
210
+ const current = input.value.trim().replace(/(.)\/+$/, '$1');
211
+ panel.replaceChildren();
212
+ if (!shown.some(r => r.page)) {
213
+ const li = document.createElement('li');
214
+ li.className = 'dm-pm-empty';
215
+ li.textContent = !tree ? 'Loading pages…' : tree.length ? 'No page matches - the address as typed is used.' : 'No pages to offer.';
216
+ panel.appendChild(li);
217
+ active = -1;
218
+ place();
219
+ return;
220
+ }
221
+ shown.forEach((r, i) => {
222
+ const li = document.createElement('li');
223
+ li.className = `dm-pm-row${r.page ? '' : ' is-head'}${r.page && r.path === current ? ' is-current' : ''}`;
224
+ li.style.paddingLeft = `${0.7 + r.depth * 1.1}rem`;
225
+ li.dataset.i = String(i);
226
+ if (r.page) {
227
+ li.id = `${id}-${i}`;
228
+ li.setAttribute('role', 'option');
229
+ li.setAttribute('aria-selected', r.path === current ? 'true' : 'false');
230
+ } else li.setAttribute('role', 'presentation');
231
+ const t = document.createElement('span');
232
+ t.className = 'dm-pm-title';
233
+ t.textContent = r.label;
234
+ li.appendChild(t);
235
+ if (r.page) {
236
+ const p = document.createElement('span');
237
+ p.className = 'dm-pm-path';
238
+ p.textContent = r.path;
239
+ li.appendChild(p);
240
+ }
241
+ panel.appendChild(li);
242
+ });
243
+ // Nothing is highlighted until an arrow key says so: Enter on a box that
244
+ // already holds a page's address is the form's (save), not a pick.
245
+ setActive(-1);
246
+ place();
247
+ }
248
+
249
+ function setActive(i) {
250
+ if (!panel) return;
251
+ panel.querySelector('.is-active')?.classList.remove('is-active');
252
+ active = i;
253
+ const li = i >= 0 ? panel.querySelector(`[data-i="${i}"]`) : null;
254
+ if (li) {
255
+ li.classList.add('is-active');
256
+ input.setAttribute('aria-activedescendant', li.id);
257
+ li.scrollIntoView({block: 'nearest'});
258
+ } else input.removeAttribute('aria-activedescendant');
259
+ }
260
+ function step(dir) {
261
+ if (!shown.length) return;
262
+ // The first arrow press starts from the page already in the box, if it is listed.
263
+ const current = input.value.trim().replace(/(.)\/+$/, '$1');
264
+ let i = active >= 0 ? active : shown.findIndex(r => r.page && r.path === current);
265
+ if (i >= 0 && active < 0) { setActive(i); return; }
266
+ for (let n = 0; n < shown.length; n++) {
267
+ i = i < 0 ? (dir > 0 ? 0 : shown.length - 1) : (i + dir + shown.length) % shown.length;
268
+ if (shown[i].page) { setActive(i); return; }
269
+ }
270
+ }
271
+ function pick(i) {
272
+ const r = shown[i];
273
+ if (!r?.page) return;
274
+ input.value = r.path;
275
+ // Whatever is bound to the field is listening for input, not for us.
276
+ picking = true;
277
+ try { input.dispatchEvent(new Event('input', {bubbles: true})); } finally { picking = false; }
278
+ close();
279
+ onPick?.(r.path);
280
+ }
281
+
282
+ const onDocDown = (e) => { if (!wrap.contains(e.target) && !panel?.contains(e.target)) close(); };
283
+ const onMove = () => place();
284
+
285
+ function open(all = true) {
286
+ if (input.disabled) return;
287
+ if (!panel) {
288
+ panel = document.createElement('ul');
289
+ panel.className = 'dm-pm-panel';
290
+ panel.id = id;
291
+ panel.setAttribute('role', 'listbox');
292
+ // Clicking the menu must not take focus from the input (or out of a focus trap).
293
+ panel.addEventListener('mousedown', (e) => e.preventDefault());
294
+ panel.addEventListener('click', (e) => {
295
+ const li = e.target.closest('[data-i]');
296
+ if (li) pick(Number(li.dataset.i));
297
+ });
298
+ document.body.appendChild(panel);
299
+ document.addEventListener('mousedown', onDocDown, true);
300
+ window.addEventListener('scroll', onMove, true);
301
+ window.addEventListener('resize', onMove);
302
+ btn.setAttribute('aria-expanded', 'true');
303
+ input.setAttribute('aria-expanded', 'true');
304
+ }
305
+ const query = all ? '' : input.value;
306
+ draw(query);
307
+ if (!tree) ensureTree().then(() => { if (panel) draw(all ? '' : input.value); });
308
+ }
309
+ function close() {
310
+ if (!panel) return;
311
+ panel.remove();
312
+ panel = null;
313
+ shown = [];
314
+ active = -1;
315
+ document.removeEventListener('mousedown', onDocDown, true);
316
+ window.removeEventListener('scroll', onMove, true);
317
+ window.removeEventListener('resize', onMove);
318
+ btn.setAttribute('aria-expanded', 'false');
319
+ input.setAttribute('aria-expanded', 'false');
320
+ input.removeAttribute('aria-activedescendant');
321
+ }
322
+
323
+ // Typed (not our own pick) - filter as they go.
324
+ const onInput = () => { if (!picking && document.activeElement === input) open(false); };
325
+ const onKey = (e) => {
326
+ if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
327
+ e.preventDefault();
328
+ if (!panel) { open(true); return; }
329
+ step(e.key === 'ArrowDown' ? 1 : -1);
330
+ } else if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) {
331
+ close();
332
+ } else if (e.key === 'Enter' && panel && active >= 0) {
333
+ // A highlighted page is the answer; with none, Enter is the form's.
334
+ e.preventDefault();
335
+ e.stopPropagation();
336
+ pick(active);
337
+ } else if (e.key === 'Escape' && panel) {
338
+ // Close the menu, not the slideover it is in.
339
+ e.preventDefault();
340
+ e.stopPropagation();
341
+ close();
342
+ } else if (e.key === 'Tab') close();
343
+ };
344
+ const onBlur = () => setTimeout(() => { if (document.activeElement !== input) close(); }, 0);
345
+ const onBtnDown = (e) => {
346
+ e.preventDefault();
347
+ if (btn.disabled) return;
348
+ if (panel) { close(); return; }
349
+ input.focus();
350
+ open(true);
351
+ };
352
+
353
+ input.addEventListener('input', onInput);
354
+ input.addEventListener('keydown', onKey);
355
+ input.addEventListener('blur', onBlur);
356
+ // Fetch the list on first focus, so the first open is rarely a loading line.
357
+ input.addEventListener('focus', ensureTree);
358
+ btn.addEventListener('mousedown', onBtnDown);
359
+ // The click after that mousedown is ours, not a row's (Bulk's rows toggle on a click).
360
+ const onBtnClick = (e) => e.stopPropagation();
361
+ btn.addEventListener('click', onBtnClick);
362
+
363
+ const handle = {
364
+ open, close,
365
+ dispose() {
366
+ close();
367
+ watch.disconnect();
368
+ input.removeEventListener('input', onInput);
369
+ input.removeEventListener('keydown', onKey);
370
+ input.removeEventListener('blur', onBlur);
371
+ input.removeEventListener('focus', ensureTree);
372
+ btn.removeEventListener('mousedown', onBtnDown);
373
+ btn.removeEventListener('click', onBtnClick);
374
+ delete input.__dmPageMenu;
375
+ }
376
+ };
377
+ input.__dmPageMenu = handle;
378
+ return handle;
379
+ }