domma-cms 1.66.9 → 1.67.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +15 -0
- package/admin/css/admin.css +1 -1
- package/admin/js/lib/actions-arrange.js +1 -1
- package/admin/js/lib/collections-arrange.js +1 -1
- package/admin/js/lib/forms-arrange.js +1 -1
- package/admin/js/lib/menus-arrange.js +1 -1
- package/admin/js/lib/page-editor-reference.js +1 -1
- package/admin/js/lib/projects-arrange.js +1 -1
- package/admin/js/lib/rich-field.js +9 -0
- package/admin/js/lib/views-arrange.js +1 -1
- package/admin/js/templates/docs/usage-shortcodes-components.html +4 -4
- package/admin/js/templates/docs/usage-shortcodes-content.html +1 -1
- package/admin/js/templates/docs/usage-shortcodes-effects.html +23 -6
- package/admin/js/templates/docs/usage-shortcodes-layout.html +3 -3
- package/admin/js/templates/effects.html +1 -1
- package/admin/js/templates/project-detail.html +1 -1
- package/admin/js/templates/view-preview.html +1 -1
- package/admin/js/views/action-editor.js +2 -2
- package/admin/js/views/collection-editor.js +4 -4
- package/admin/js/views/collection-entries.js +4 -4
- package/admin/js/views/form-editor.js +5 -5
- package/admin/js/views/menu-editor.js +5 -5
- package/admin/js/views/project-detail.js +2 -2
- package/admin/js/views/project-settings.js +1 -1
- package/admin/js/views/projects.js +3 -3
- package/admin/js/views/view-editor.js +1 -1
- package/admin/js/views/view-preview.js +1 -1
- package/docs/DommaFeatures.md +8 -0
- package/docs/markdown-shortcodes.md +15 -10
- package/docs/plugin-development.md +27 -0
- package/package.json +1 -1
- package/public/css/site.css +1 -1
- package/public/js/effects.js +1 -1
- package/public/js/rich-text.mjs +9 -0
- package/server/routes/api/forms.js +3 -1
- package/server/services/actions.js +3 -1
- package/server/services/collections.js +6 -1
- package/server/services/forms.js +2 -1
- package/server/services/markdown.js +107 -35
- package/server/services/menus.js +3 -2
- package/server/services/projects.js +3 -2
- package/server/services/richText.js +98 -0
- package/server/services/views.js +3 -1
- package/server/templates/page.html +2 -2
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import{isRichText as m,plainToRichHtml as v,richTextToPlain as d,richTextSummary as D}from"../../../public/js/rich-text.mjs";export{m as isRichText,d as richTextToPlain,D as richTextSummary};const L=[["bold","italic","underline"],["ul","ol"],["link"],["undo","redo"]],O={ALLOWED_TAGS:["p","br","strong","b","em","i","u","s","ul","ol","li","a","h2","h3","h4","blockquote","code"],ALLOWED_ATTR:["href","target","rel"],ALLOW_DATA_ATTR:!1},y="rich-description-css",_=`
|
|
2
|
+
.rich-description{display:none}
|
|
3
|
+
.rich-description-editor .dm-editor-body,.rich-description-editor .dm-editor-content{min-height:var(--rich-description-min,6rem)}
|
|
4
|
+
.rich-description-editor .dm-editor-content{padding:.6rem .75rem}
|
|
5
|
+
.rich-text>:first-child{margin-top:0}
|
|
6
|
+
.rich-text>:last-child{margin-bottom:0}
|
|
7
|
+
.rich-text p,.rich-text ul,.rich-text ol,.rich-text blockquote{margin:0 0 .5em}
|
|
8
|
+
.rich-text ul,.rich-text ol{padding-left:1.25em}
|
|
9
|
+
`;function x(){if(document.getElementById(y))return;const t=document.createElement("style");t.id=y,t.textContent=_,document.head.appendChild(t)}const n=Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,"value"),T=t=>m(t)?t:v(t),w=t=>!!d(T(t)).replace(/^- ?$/gm,"").trim();export function richDescription(t,{minHeight:s=88,placeholder:o}={}){const e=typeof t=="string"?document.querySelector(t):t?.get?.(0)??t,a={rich:!1,get:()=>e?.value??"",getText:()=>d(e?.value??""),set:r=>{e&&(e.value=r??"")},focus:()=>e?.focus(),destroy:()=>{}};if(!(e instanceof HTMLTextAreaElement)||e._richDescription||typeof globalThis.E?.editor!="function")return e?._richDescription??a;const i=document.createElement("div");i.className="rich-description",e.after(i);let h,u=!1,p=null;const S=r=>{n.get.call(e)!==r&&(n.set.call(e,r),e.dispatchEvent(new Event("input",{bubbles:!0})),e.dispatchEvent(new Event("change",{bubbles:!0})))},f=r=>{const c=T(r);if(c!==p){u=!0;try{h.setValue(c)}finally{u=!1}p=c}};try{h=globalThis.E.editor(i,{mode:"rich",minHeight:s,imagePaste:!1,toolbar:L,placeholder:o??e.getAttribute("placeholder")??"",onChange:r=>{if(u)return;const c=typeof r=="string"?r:h.getValue();p=c,S(w(c)?c:"")}})}catch{return i.remove(),a}const l=i.nextElementSibling?.querySelector("[contenteditable]")?i.nextElementSibling:i;x(),l.classList.add("rich-description-editor"),l.style.minHeight="",l.style.setProperty("--rich-description-min",`${s}px`);const g=l.querySelector("[contenteditable]"),A=e.id?document.querySelector(`label[for="${CSS.escape(e.id)}"]`):e.closest("label"),E=e.getAttribute("aria-label")||A?.childNodes[0]?.textContent?.trim()||"Description";g?.setAttribute("aria-label",E),e.removeAttribute("maxlength"),e.hidden=!0,f(n.get.call(e)),Object.defineProperty(e,"value",{configurable:!0,get:()=>n.get.call(e),set:r=>{n.set.call(e,r??""),f(n.get.call(e))}});const b={rich:!0,get:()=>n.get.call(e),getText:()=>d(n.get.call(e)),set:r=>{e.value=r??""},focus:()=>g?.focus(),destroy:()=>{delete e.value,delete e._richDescription;try{h.destroy?.()}catch{}l!==i&&l.remove(),i.remove(),e.hidden=!1}};return e._richDescription=b,b}export function showRichText(t,s){const o=t?.get?.(0)??t;if(!o)return;const e=typeof s=="string"?s:"";if(!m(e)||!globalThis.DOMPurify){o.textContent=d(e),o.style.whiteSpace="pre-line";return}o.style.whiteSpace="",x();const a=new DOMParser().parseFromString(globalThis.DOMPurify.sanitize(e,O),"text/html");for(const i of a.body.querySelectorAll("a"))i.setAttribute("rel","noopener noreferrer");o.classList.add("rich-text"),o.replaceChildren(...a.body.childNodes)}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export const FILTERS=["all","public","restricted","broken"];const
|
|
1
|
+
import{richTextToPlain as l,richTextSummary as u}from"../../../public/js/rich-text.mjs";export const FILTERS=["all","public","restricted","broken"];const a={table:"Table",cards:"Cards",list:"List",block:"Block",accordion:"Accordion",timeline:"Timeline",carousel:"Carousel",listgroup:"List group"},p=(e,r,s=`${r}s`)=>`${e} ${e===1?r:s}`;export function projectScope(e=""){const r=String(e).split("?")[0].match(/^#\/projects\/([^/]+)\/views\/?$/);if(!r)return null;try{return decodeURIComponent(r[1])}catch{return r[1]}}export const projectOf=e=>e?.meta?.project||"core",newViewHref=e=>e?`#/views/new?project=${encodeURIComponent(e)}`:"#/views/new",shortcodeFor=e=>`[view slug="${e}" /]`,isBroken=e=>e?.sourceInfo?.exists===!1;export function arrangeViews(e,{filter:r="all",query:s="",project:o=null}={}){const i=String(s).trim().toLowerCase(),n={all:()=>!0,public:t=>t.access?.public===!0,restricted:t=>t.access?.public!==!0,broken:isBroken}[r]||(()=>!0);return[...e||[]].filter(t=>!o||projectOf(t)===o).filter(n).filter(t=>!i||[t.title,t.slug,l(t.description),t.pipeline?.source,t.sourceInfo?.title].some(c=>String(c||"").toLowerCase().includes(i))).sort((t,c)=>Number(isBroken(c))-Number(isBroken(t))||String(t.title||t.slug).localeCompare(String(c.title||c.slug)))}export function countViews(e,{project:r=null}={}){const s=(e||[]).filter(o=>!r||projectOf(o)===r);return{all:s.length,public:s.filter(o=>o.access?.public===!0).length,restricted:s.filter(o=>o.access?.public!==!0).length,broken:s.filter(isBroken).length}}export function viewRow(e){const r=Array.isArray(e.pipeline?.stages)?e.pipeline.stages.length:0,s=e.pipeline?.source||"-",o=e.sourceInfo,i=isBroken(e),n=!o||i?"":o.adapter==="mongodb"?"MongoDB aggregation":"JS pipeline",t=Array.isArray(e.access?.roles)?e.access.roles:[];return{slug:e.slug,title:e.title||e.slug,meta:[e.slug,`from ${o?.title&&!i?o.title:s}`,p(r,"stage"),a[e.display?.mode]||e.display?.mode||"Table"].join(" \xB7 "),description:u(e.description,200),access:e.access?.public?"Public":t.length?t.join(", "):"Admins",accessCls:e.access?.public?"is-ok":"",engine:n,project:e.meta?.project&&e.meta.project!=="core"?e.meta.project:"",broken:i,brokenText:i?`Source "${s}" is gone`:"",rowCls:i?"is-broken":""}}
|
|
@@ -28,12 +28,12 @@
|
|
|
28
28
|
<tbody><tr>
|
|
29
29
|
<td><code>[tabs]</code></td>
|
|
30
30
|
<td><code>style</code></td>
|
|
31
|
-
<td><code>pills</code> for rounded buttons. Without it, tabs are underlined</td>
|
|
31
|
+
<td><code>pills</code> for rounded buttons, or <code>bordered</code> to put the tabs and their panel in one box. Without it, tabs are underlined</td>
|
|
32
32
|
</tr>
|
|
33
33
|
<tr>
|
|
34
34
|
<td><code>[tabs]</code></td>
|
|
35
35
|
<td><code>align</code></td>
|
|
36
|
-
<td><code>center</code> centres the tabs</td>
|
|
36
|
+
<td><code>center</code> centres the tabs, <code>right</code> puts them at the right</td>
|
|
37
37
|
</tr>
|
|
38
38
|
<tr>
|
|
39
39
|
<td><code>[tabs]</code></td>
|
|
@@ -327,9 +327,9 @@ The site will be read-only on **Sunday** from 8am.
|
|
|
327
327
|
</tbody></table>
|
|
328
328
|
<p>Good to know:</p>
|
|
329
329
|
<ul>
|
|
330
|
-
<li>A banner
|
|
330
|
+
<li>A banner can go inside a card, box, column, tab or accordion item.</li>
|
|
331
331
|
<li>To show a banner only until a date, add <code>expires-at</code> - see "Showing a shortcode for a limited time" in <a href="#/docs/usage/shortcodes">Shortcodes</a>.</li>
|
|
332
|
-
<li>A banner takes the effects <code>reveal</code>, <code>pulse</code> and <code>
|
|
332
|
+
<li>A banner takes the effects <code>reveal</code>, <code>pulse</code>, <code>shake</code>, <code>animate</code> and <code>ambient</code> as switches.</li>
|
|
333
333
|
</ul>
|
|
334
334
|
<h3 id="sc-countdown"><code>countdown</code> - a countdown clock</h3>
|
|
335
335
|
<p>A clock counting down to a date, or for a number of seconds.</p>
|
|
@@ -296,7 +296,7 @@
|
|
|
296
296
|
<td>Your own CSS class or id</td>
|
|
297
297
|
</tr>
|
|
298
298
|
</tbody></table>
|
|
299
|
-
<p>A button takes the effects <code>breathe</code>, <code>pulse</code>, <code>shake</code> and <code>
|
|
299
|
+
<p>A button takes the effects <code>breathe</code>, <code>pulse</code>, <code>shake</code>, <code>ripple</code> and <code>animate</code> as switches: <code>[button href="/contact" pulse]Get in touch[/button]</code>.</p>
|
|
300
300
|
<p>To make a button that runs an Action rather than opening a page, use <code>[cta]</code> - see <a href="#/docs/usage/shortcodes-data">Data shortcodes</a>.</p>
|
|
301
301
|
<h3 id="sc-link"><code>link</code> - a link with extras</h3>
|
|
302
302
|
<p>A text link with extras: an icon, a new tab, your own class. For an ordinary link, plain Markdown - <code>[words](/address)</code> - is simpler.</p>
|
|
@@ -262,6 +262,7 @@ Build smoother experiences, one letter at a time.
|
|
|
262
262
|
<h3 id="sc-scramble"><code>scramble</code> - text out of random characters</h3>
|
|
263
263
|
<p>Text that appears through a flurry of random characters, settling into the real words.</p>
|
|
264
264
|
<pre><code>[scramble speed="50"]Access granted[/scramble]
|
|
265
|
+
[scramble loop loop-delay="3000"]Now hiring[/scramble]
|
|
265
266
|
</code></pre>
|
|
266
267
|
<table class="table table-sm">
|
|
267
268
|
<thead>
|
|
@@ -274,6 +275,14 @@ Build smoother experiences, one letter at a time.
|
|
|
274
275
|
<td><code>speed</code></td>
|
|
275
276
|
<td>Milliseconds per character (default 50)</td>
|
|
276
277
|
</tr>
|
|
278
|
+
<tr>
|
|
279
|
+
<td><code>loop</code></td>
|
|
280
|
+
<td>Switch: play again and again. Without it, the text scrambles once</td>
|
|
281
|
+
</tr>
|
|
282
|
+
<tr>
|
|
283
|
+
<td><code>loop-delay</code></td>
|
|
284
|
+
<td>With <code>loop</code>: how long the words stay still between plays, in milliseconds (default 2000)</td>
|
|
285
|
+
</tr>
|
|
277
286
|
</tbody></table>
|
|
278
287
|
<h3 id="sc-counter"><code>counter</code> - a number that counts up</h3>
|
|
279
288
|
<p>A number that counts up (or down) to its target.</p>
|
|
@@ -333,6 +342,10 @@ Build smoother experiences, one letter at a time.
|
|
|
333
342
|
<td><code>duration</code></td>
|
|
334
343
|
<td>How long it lasts, in milliseconds (default 600)</td>
|
|
335
344
|
</tr>
|
|
345
|
+
<tr>
|
|
346
|
+
<td><code>opacity</code></td>
|
|
347
|
+
<td>How strong the ripple starts, from 0 (invisible) to 1 (solid, the default). Use it with a solid colour: <code>colour="#7c6af7" opacity="0.3"</code></td>
|
|
348
|
+
</tr>
|
|
336
349
|
</tbody></table>
|
|
337
350
|
<h3 id="sc-twinkle"><code>twinkle</code> - sparkles</h3>
|
|
338
351
|
<p>Sparkling particles over what is inside.</p>
|
|
@@ -844,6 +857,10 @@ Fast, file-based and friendly.
|
|
|
844
857
|
[/card]
|
|
845
858
|
|
|
846
859
|
[button href="/contact" pulse]Get in touch[/button]
|
|
860
|
+
|
|
861
|
+
[card title="New" animate animate-type="zoom-in" ambient ambient-type="aurora"]
|
|
862
|
+
A card that zooms in, on a moving background.
|
|
863
|
+
[/card]
|
|
847
864
|
</code></pre>
|
|
848
865
|
<table class="table table-sm">
|
|
849
866
|
<thead>
|
|
@@ -854,26 +871,26 @@ Fast, file-based and friendly.
|
|
|
854
871
|
</thead>
|
|
855
872
|
<tbody><tr>
|
|
856
873
|
<td><code>[card]</code>, <code>[box]</code></td>
|
|
857
|
-
<td><code>reveal</code>, <code>breathe</code>, <code>pulse</code>, <code>shake</code>, <code>twinkle</code>, <code>ripple</code></td>
|
|
874
|
+
<td><code>reveal</code>, <code>breathe</code>, <code>pulse</code>, <code>shake</code>, <code>twinkle</code>, <code>ripple</code>, <code>animate</code>, <code>ambient</code></td>
|
|
858
875
|
</tr>
|
|
859
876
|
<tr>
|
|
860
877
|
<td><code>[hero]</code></td>
|
|
861
|
-
<td><code>reveal</code>, <code>breathe</code>, <code>pulse</code>, <code>twinkle</code>, <code>ticker-tape</code>, <code>butterflies</code>, <code>strobe</code></td>
|
|
878
|
+
<td><code>reveal</code>, <code>breathe</code>, <code>pulse</code>, <code>twinkle</code>, <code>ticker-tape</code>, <code>butterflies</code>, <code>strobe</code>, <code>animate</code>, <code>ambient</code></td>
|
|
862
879
|
</tr>
|
|
863
880
|
<tr>
|
|
864
881
|
<td><code>[banner]</code></td>
|
|
865
|
-
<td><code>reveal</code>, <code>pulse</code>, <code>shake</code></td>
|
|
882
|
+
<td><code>reveal</code>, <code>pulse</code>, <code>shake</code>, <code>animate</code>, <code>ambient</code></td>
|
|
866
883
|
</tr>
|
|
867
884
|
<tr>
|
|
868
885
|
<td><code>[col]</code></td>
|
|
869
|
-
<td><code>reveal</code>, <code>breathe</code>, <code>ripple</code></td>
|
|
886
|
+
<td><code>reveal</code>, <code>breathe</code>, <code>ripple</code>, <code>animate</code></td>
|
|
870
887
|
</tr>
|
|
871
888
|
<tr>
|
|
872
889
|
<td><code>[button]</code></td>
|
|
873
|
-
<td><code>breathe</code>, <code>pulse</code>, <code>shake</code>, <code>ripple</code></td>
|
|
890
|
+
<td><code>breathe</code>, <code>pulse</code>, <code>shake</code>, <code>ripple</code>, <code>animate</code></td>
|
|
874
891
|
</tr>
|
|
875
892
|
</tbody></table>
|
|
876
|
-
<p><code>
|
|
893
|
+
<p><code>animate</code> and <code>ambient</code> take the same settings as their tags: <code>animate-type</code>, <code>animate-duration</code>, <code>animate-delay</code>, <code>animate-repeat</code>, and <code>ambient-type</code>, <code>ambient-speed</code>, <code>ambient-intensity</code>. Written with no type, <code>animate</code> fades the tag in and <code>ambient</code> gives it the <code>aurora</code> background.</p>
|
|
877
894
|
|
|
878
895
|
</div>
|
|
879
896
|
</div>
|
|
@@ -222,7 +222,7 @@
|
|
|
222
222
|
<td>Your own id on the column</td>
|
|
223
223
|
</tr>
|
|
224
224
|
</tbody></table>
|
|
225
|
-
<p>A column also takes the effects <code>reveal</code>, <code>breathe</code> and <code>
|
|
225
|
+
<p>A column also takes the effects <code>reveal</code>, <code>breathe</code>, <code>ripple</code> and <code>animate</code> as switches - see <a href="#/docs/usage/shortcodes-effects">Effects</a>.</p>
|
|
226
226
|
<h3 id="sc-center"><code>center</code> - centred content</h3>
|
|
227
227
|
<p>Centres whatever is inside it.</p>
|
|
228
228
|
<pre><code>[center]
|
|
@@ -414,7 +414,7 @@ The body, as usual.
|
|
|
414
414
|
<p>Good to know:</p>
|
|
415
415
|
<ul>
|
|
416
416
|
<li>The full list of layouts, variants and gradients, with pictures, is in <a href="#/docs/usage/shortcodes">Shortcodes</a> under Cards. The editor's Card builder offers all of them.</li>
|
|
417
|
-
<li>A card takes the effects <code>reveal</code>, <code>breathe</code>, <code>pulse</code>, <code>shake</code>, <code>twinkle</code> and <code>
|
|
417
|
+
<li>A card takes the effects <code>reveal</code>, <code>breathe</code>, <code>pulse</code>, <code>shake</code>, <code>twinkle</code>, <code>ripple</code>, <code>animate</code> and <code>ambient</code> as switches: <code>[card title="Why us" reveal reveal-animation="zoom"]</code>.</li>
|
|
418
418
|
<li>Cards can go inside grids, boxes, slideovers and other cards.</li>
|
|
419
419
|
</ul>
|
|
420
420
|
<h3 id="sc-box"><code>box</code> - a plain container</h3>
|
|
@@ -555,7 +555,7 @@ Optional text underneath, with **Markdown**.
|
|
|
555
555
|
<td>Your own CSS class or id</td>
|
|
556
556
|
</tr>
|
|
557
557
|
</tbody></table>
|
|
558
|
-
<p>A hero takes the effects <code>reveal</code>, <code>breathe</code>, <code>pulse</code>, <code>twinkle</code>, <code>ticker-tape</code>, <code>butterflies</code> and <code>
|
|
558
|
+
<p>A hero takes the effects <code>reveal</code>, <code>breathe</code>, <code>pulse</code>, <code>twinkle</code>, <code>ticker-tape</code>, <code>butterflies</code>, <code>strobe</code>, <code>animate</code> and <code>ambient</code> as switches.</p>
|
|
559
559
|
<h3 id="sc-slideover"><code>slideover</code> - a panel that slides in</h3>
|
|
560
560
|
<p>A button that opens a panel sliding in from the side. What you write between the tags is what the panel shows.</p>
|
|
561
561
|
<pre><code>[slideover title="Delivery details" trigger="Read more" size="lg"]
|
|
@@ -386,7 +386,7 @@ Your text appears letter by letter.
|
|
|
386
386
|
<h3 class="mb-2">Scramble</h3>
|
|
387
387
|
<p class="text-muted mb-2">Reveals text through a character-scramble animation. Great for tech/data
|
|
388
388
|
aesthetics.</p>
|
|
389
|
-
<pre class="code-block mb-3">[scramble speed="50" loop="
|
|
389
|
+
<pre class="code-block mb-3">[scramble speed="50" loop loop-delay="2000"]
|
|
390
390
|
Scrambled reveal text.
|
|
391
391
|
[/scramble]</pre>
|
|
392
392
|
|
|
@@ -22,7 +22,7 @@
|
|
|
22
22
|
<div class="pdx-hero-icon" aria-hidden="true"><span data-icon="folder" data-icon-size="32"></span></div>
|
|
23
23
|
<div class="pdx-hero-main">
|
|
24
24
|
<strong class="pdx-name" data-bind-text="name.value"></strong>
|
|
25
|
-
<
|
|
25
|
+
<div class="pdx-desc" data-bind-hidden="!description.value"></div>
|
|
26
26
|
<div class="pdx-chips">
|
|
27
27
|
<span class="pdx-chip is-warn" data-bind-hidden="!off.value">Disabled</span>
|
|
28
28
|
<span class="pdx-chip is-ok" data-bind-hidden="off.value || loading.value">Enabled</span>
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
<div class="vpx-card-title">What runs
|
|
6
6
|
<span data-help-title="Preview" data-help="The saved view, run as you (an admin) would see it: every row the pipeline gives, a page at a time. Row-level access narrows the results for other users, not here. To change what it shows, Edit it - the editor's Results tab runs unsaved changes too."></span></div>
|
|
7
7
|
<div class="vpx-chips" data-each="chips.value key=text"></div>
|
|
8
|
-
<
|
|
8
|
+
<div class="vpx-note" data-bind-hidden="!description.value"></div>
|
|
9
9
|
</div>
|
|
10
10
|
|
|
11
11
|
<div class="vpx-card">
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{apiRequest as L}from"../api.js";import{addBannerAction as ge}from"../lib/plugin-chrome.js";import{helpPopovers as Ke}from"../lib/help-popover.js";import{openMenuAt as Ve,sidebarCount as Se}from"../lib/tool-kit.js";import{isMongoMissing as We}from"../lib/actions-arrange.js";import{STEP_TYPES as Ye,checkAction as gt,draftKey as St,draftOf as Ee,duplicateStep as Et,formFromAction as X,makeStep as xt,moveStep as ze,payloadFromForm as kt,problemsText as Je,removeStep as wt,restoreDraft as Ct,rolePicker as Mt,slugify as Ge,snapshot as N,stepSummary as Qe}from"../lib/action-editor-arrange.js";const
|
|
1
|
+
import{apiRequest as L}from"../api.js";import{addBannerAction as ge}from"../lib/plugin-chrome.js";import{helpPopovers as Ke}from"../lib/help-popover.js";import{openMenuAt as Ve,sidebarCount as Se}from"../lib/tool-kit.js";import{isMongoMissing as We}from"../lib/actions-arrange.js";import{STEP_TYPES as Ye,checkAction as gt,draftKey as St,draftOf as Ee,duplicateStep as Et,formFromAction as X,makeStep as xt,moveStep as ze,payloadFromForm as kt,problemsText as Je,removeStep as wt,restoreDraft as Ct,rolePicker as Mt,slugify as Ge,snapshot as N,stepSummary as Qe}from"../lib/action-editor-arrange.js";import{richDescription as _t}from"../lib/rich-field.js";const $t=/^\/actions\/(new|edit\/[^/?#]+)\/?(\?.*)?$/,re=h=>String(h||"").split("?")[0].replace(/\/$/,""),xe="#/actions",Lt=`
|
|
2
2
|
<label class="aex-role" data-role="{{name}}">
|
|
3
3
|
<input type="checkbox" class="aex-role-cb" data-bind-checked="on">
|
|
4
4
|
<span class="aex-step-main"><strong>{{label}}</strong><small>{{name}}</small></span>
|
|
5
5
|
<span class="aex-chip" data-bind-hidden="!levelText">{{levelText}}</span>
|
|
6
6
|
<span class="aex-chip is-warn" data-bind-hidden="!missing" title="The action names it, but System \u203A Roles has no such role">No longer exists</span>
|
|
7
|
-
</label>`,Lt=[[["entry.data.fieldName"],"Any field of the entry"],[["entry.id"],"The entry's id"],[["now"],"The current time (ISO)"],[["user.id","user.name","user.email"],"Who ran it"],[["env.CMS_PUBLIC_*"],"Public environment variables"]],Nt=h=>String(h??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""");function ke(h,y){const l=h.querySelector(".dm-plugin-banner-name");if(!l)return;const T=l.querySelector(".dm-plugin-banner-sep");if(T){for(;T.nextSibling;)T.nextSibling.remove();T.after(document.createTextNode(y))}}let A=null,Xe=!1;function At(){Xe||!window.R?.use||(Xe=!0,R.use((h,y,l)=>{if(!(_t.test(y?.path||"")&&re(h?.path)!==re(y?.path))||!A?.dirty())return l();const m=`#${y.path}`;return E.confirm("This action has unsaved changes. Leave anyway? They are kept as a draft for your next visit.").then(Z=>{Z?l():history.replaceState(null,"",m)})}),M.subscribe("router:afterChange",({to:h}={})=>{if(A&&re(h?.path)!==A.key){const y=A;A=null,y.dispose()}}))}export const actionEditorView={templateUrl:"/admin/js/templates/action-editor.html",async onMount(h){if(At(),A){const e=A;A=null,e.dispose()}const y=h.get(0),l=y.querySelector(".aex")||y,T=[],m=e=>(T.push(e),e);let Z=!1;const C=()=>!Z&&l.isConnected,ie=location.hash.replace(/^#/,""),we=ie.match(/^\/actions\/edit\/([^/?#]+)/),x=we?decodeURIComponent(we[1]):null,_=!!x,ue=new URLSearchParams(ie.split("?")[1]||"").get("project")||"",Ze=re(ie),w=St(x),F=M.observable(!0),H=M.observable(!1),ee=M.observable(!1),j=M.observable(!1),K=X(null,{project:ue}),i={};for(const[e,t]of Object.entries(K))e!=="steps"&&e!=="roles"&&(i[e]=M.observable(t));const U=M.observable([...K.roles]);let v=K.steps;const te=M.observable(0),de=()=>{te.value=te.peek()+1},Ce=M.observable("updateField");let ne={},p=null;const Me=()=>p?X(p):K,_e=()=>{te.value;const e={steps:v,roles:U.value};for(const t of Object.keys(i))e[t]=i[t].value;return e},O=()=>{const e={steps:v,roles:U.peek()};for(const t of Object.keys(i))e[t]=i[t].peek();return e},V=M.observable(N(K)),oe=M.computed(()=>!F.value&&!H.value&&N(_e())!==V.value),ae=M.computed(()=>gt(_e())),et=M.computed(()=>{const e=ae.value;if(j.value)return e;const t={};return i.title.value&&e.title&&(t.title=e.title),e.slug&&(t.slug=e.slug),e.roles&&(t.roles=e.roles),t}),tt=M.computed(()=>j.value?Je(ae.value):""),nt=M.computed(()=>(te.value,v.length)),b=l.querySelector("#action-steps-list"),pe=M.computed(()=>ae.value.steps||{});let me=null,$e=!1;const P=l.querySelector("#action-collection"),z=l.querySelector("#action-project"),se=l.querySelector("#action-transition-field"),ot=l.querySelector("#action-collection-fields"),at=l.querySelector("#action-transition-values"),f=(e,t)=>{const n=document.createElement("option");return n.value=e,n.textContent=t,n},Le=M.observable([]),Ne=M.observable([]);m(M.effect(()=>{Ne.value=Mt(Le.value,U.value)}));const fe=new Map,J=M.observable([]);let Ae=0;async function st(e){const t=++Ae;if(!e){J.value=[];return}fe.has(e)||fe.set(e,L(`/collections/${encodeURIComponent(e)}`).then(o=>o?.fields||[]).catch(()=>[]));const n=await fe.get(e);t===Ae&&C()&&(J.value=n)}m(M.effect(()=>{st(i.collection.value)})),m(M.effect(()=>{const e=J.value,t=i.transitionField.peek();se.replaceChildren(f("",e.length?"- choose a field -":"- no fields -"));for(const n of e)se.appendChild(f(n.name,`${n.label||n.name} (${n.name})`));t&&!e.some(n=>n.name===t)&&se.appendChild(f(t,`${t} (not in the collection)`)),se.value=t,ot.replaceChildren(...e.map(n=>f(n.name,n.label||n.name))),$e&&he()}));const ve=M.computed(()=>{const e=J.value.find(t=>t.name===i.transitionField.value);return e?.type==="select"?(e.options||[]).map(t=>typeof t=="string"?t:t?.value).filter(Boolean):[]});m(M.effect(()=>{at.replaceChildren(...ve.value.map(e=>f(e,e)))}));function lt(e,t,n){const o=document.createElement("div"),r=document.createElement("label");r.className="form-label",r.textContent=t.label,o.appendChild(r);const a=document.createElement(t.multiline?"textarea":"input");return t.multiline?a.rows=3:a.type="text",a.className=`form-input step-field-${t.name}`,a.placeholder=t.placeholder||"",a.value=e.config[t.name]??"",a.addEventListener("input",()=>{e.config[t.name]=a.value,n()}),o.appendChild(a),o}function ct(e,t,n){const o=J.peek(),r=document.createElement("div"),a=document.createElement("label");a.className="form-label",a.textContent="Field",r.appendChild(a);const s=document.createElement("select");s.className="form-input step-field-field",s.appendChild(f("",o.length?"- choose a field -":"- no fields - enter one below -"));for(const g of o)s.appendChild(f(g.name,`${g.label||g.name} (${g.name})`));s.appendChild(f("__custom__","- enter a field name -"));const d=document.createElement("input");d.type="text",d.className="form-input step-field-field-custom",d.placeholder="Field name, e.g. status",o.some(g=>g.name===e.config.field)?s.value=e.config.field:e.config.field&&(s.value="__custom__",d.value=e.config.field),d.hidden=s.value!=="__custom__",r.append(s,d);const q=document.createElement("div"),W=document.createElement("label");W.className="form-label",W.textContent="New value",q.appendChild(W);const k=document.createElement("div");q.appendChild(k);const $=()=>{k.replaceChildren();const g=o.find(c=>c.name===e.config.field),Y=g?.type==="select"?(g.options||[]).map(c=>typeof c=="string"?{value:c,label:c}:{value:c?.value,label:c?.label||c?.value}).filter(c=>c.value):[],u=document.createElement("input");if(u.type="text",u.className="form-input step-field-value",u.placeholder="e.g. approved or {{now}}",Y.length){const c=document.createElement("select");c.className="form-input",c.appendChild(f("","- choose a value -"));for(const ce of Y)c.appendChild(f(ce.value,ce.label));c.appendChild(f("__custom__","- enter a value -"));const He=Y.some(ce=>ce.value===e.config.value);c.value=He?e.config.value:e.config.value?"__custom__":"",u.value=He?"":e.config.value,u.hidden=c.value!=="__custom__",c.addEventListener("change",()=>{u.hidden=c.value!=="__custom__",e.config.value=c.value==="__custom__"?u.value:c.value,n()}),u.addEventListener("input",()=>{e.config.value=u.value,n()}),k.append(c,u)}else u.value=e.config.value,u.addEventListener("input",()=>{e.config.value=u.value,n()}),k.append(u)};s.addEventListener("change",()=>{d.hidden=s.value!=="__custom__",e.config.field=s.value==="__custom__"?d.value.trim():s.value,e.config.value="",$(),n()}),d.addEventListener("input",()=>{e.config.field=d.value.trim(),n()}),$(),t.append(r,q)}function he(){if(!b)return;const e=pe.peek();b.replaceChildren(),v.forEach((t,n)=>{const o=Ye[t.type],r=document.createElement("div");r.className=`aex-step${j.peek()&&e[n]?" is-bad":""}`,r.dataset.index=String(n);const a=document.createElement("div");a.className="aex-step-head",a.tabIndex=0;const s=document.createElement("span");s.className="aex-step-n",s.textContent=String(n+1);const d=document.createElement("span");d.className="aex-step-main";const be=document.createElement("strong");be.textContent=o?.label||t.type;const q=document.createElement("small");q.className="aex-step-summary",q.textContent=Qe(t),d.append(be,q);const W=document.createElement("span");W.setAttribute("data-help",o?.help||"A step type this editor does not know - it is kept exactly as stored.");const k=document.createElement("button");k.type="button",k.className="aex-kebab",k.textContent="\u22EE",k.title="Actions",k.setAttribute("aria-label",`Actions for step ${n+1}`),a.append(s,d,W,k);const $=document.createElement("div");$.className="aex-step-body";const g=document.createElement("small");g.className="aex-err";const Y=()=>{q.textContent=Qe(t),de()};if(t.type==="updateField")ct(t,$,Y);else if(o&&o.fields.length)o.fields.forEach(u=>$.appendChild(lt(t,u,Y)));else{const u=document.createElement("p");u.className="aex-note",u.textContent=t.type==="deleteEntry"?"Deletes the entry. Nothing to set.":"Nothing to set.",$.appendChild(u)}$.appendChild(g),r.append(a,$),b.appendChild(r)}),I.scan(b),me?.(),me=Ke(b,{position:"bottom"}),Re()}m(()=>me?.());function Re(){const e=pe.peek();for(const t of b?.querySelectorAll(".aex-step")||[]){const n=Number(t.dataset.index),o=j.peek()&&e[n]||"";t.classList.toggle("is-bad",!!o);const r=t.querySelector(":scope > .aex-step-body > .aex-err");r&&(r.textContent=o,r.hidden=!o)}}m(M.effect(()=>{pe.value,j.value,Re()}));const G=e=>{v=e,he(),de()};function rt(e){const t=v[e];return t?[{header:`Step ${e+1} - ${Ye[t.type]?.label||t.type}`},{label:"Move up",icon:"arrow-up",disabled:e===0,action:()=>{G(ze(v,e,-1)),Q(e-1)}},{label:"Move down",icon:"arrow-down",disabled:e===v.length-1,action:()=>{G(ze(v,e,1)),Q(e+1)}},{label:"Duplicate",icon:"copy",action:()=>{G(Et(v,e)),Q(e+1)}},{type:"divider"},{label:"Remove",icon:"trash",danger:!0,action:()=>{G(wt(v,e)),Q(Math.min(e,v.length-1))}}]:[]}const Q=e=>requestAnimationFrame(()=>b?.querySelector(`.aex-step[data-index="${e}"] .aex-step-head`)?.focus()),it=E.contextMenu(b,{cursor:"glyph",match:".aex-step",inherit:!1,density:"compact",items:e=>rt(Number(e.dataset.index))});m(()=>it?.destroy?.());const Te=e=>{const t=e.target.closest(".aex-kebab");t&&Ve(t)},je=e=>{const t=e.target.closest(".aex-step-head");!t||e.target!==t||(e.key==="F10"&&e.shiftKey||e.key==="ContextMenu"?(e.preventDefault(),Ve(t)):e.key==="Enter"&&(e.preventDefault(),t.parentElement.querySelector(".aex-step-body input, .aex-step-body select, .aex-step-body textarea")?.focus()))};b.addEventListener("click",Te),b.addEventListener("keydown",je),m(()=>{b.removeEventListener("click",Te),b.removeEventListener("keydown",je)});function le(e){$e=!0;for(const[t,n]of Object.entries(e))t!=="steps"&&(t==="roles"?U.value=[...n]:i[t]&&(i[t].value=n));v=e.steps.map(t=>({type:t.type,config:{...t.config}})),he(),de()}async function ye(){if(ee.peek()||F.peek()||H.peek())return;j.value=!0;const e=ae.peek();if(Object.keys(e).length){E.toast(Je(e),{type:"warning",duration:6e3});return}ee.value=!0;const t=kt(O(),{meta:ne,editing:_});try{if(_){const n=await L(`/actions/${encodeURIComponent(x)}`,{method:"PUT",body:JSON.stringify(t)});if(!C())return;p=n||{...p,...t},ne=p.meta||ne,V.value=N(O()),j.value=!1;try{S.remove?S.remove(w):S.set(w,null)}catch{}ke(y,p.title||x),Se(xe),E.toast("Action saved.",{type:"success"})}else{const n=await L("/actions",{method:"POST",body:JSON.stringify(t)});V.value=N(O());try{S.remove?S.remove(w):S.set(w,null)}catch{}Se(xe),E.toast(`Action "${n.title||t.title}" created.`,{type:"success"}),C()&&(location.hash=`#/actions/edit/${encodeURIComponent(n.slug)}`)}}catch(n){if(We(n)){H.value=!0;return}E.toast(`Not saved: ${n.message||n}`,{type:"error"})}finally{ee.value=!1}}async function ut(){if(!_)return;const e=p?.title||x;if(await E.confirm(`Delete the action "${Nt(e)}"? Its button disappears from every entry. This cannot be undone.`))try{await L(`/actions/${encodeURIComponent(x)}`,{method:"DELETE"}),V.value=N(O());try{S.remove?S.remove(w):S.set(w,null)}catch{}Se(xe),E.toast(`Deleted "${e}".`,{type:"success"}),location.hash="#/actions"}catch(t){E.toast(`Not deleted: ${t.message||t}`,{type:"error"})}}function dt(){E.confirm("Discard the changes you have not saved?").then(e=>{!e||!C()||(le(X(p,{project:ue})),j.value=!1)})}l.querySelector(".aex-roles").innerHTML=$t;const pt={...i,roles:U,loading:F,needsMongo:H,saving:ee,dirty:oe,err:et,problems:tt,stepCount:nt,addType:Ce,roleRows:Ne,editing:_,dirtyText:M.computed(()=>"Unsaved changes - Save (Ctrl+S) to keep them. Leave and they are kept as a draft for next time."),slugHint:M.computed(()=>_?"":Ge(i.title.value)?`Made from the title: ${Ge(i.title.value)}`:"Made from the title"),buttonText:M.computed(()=>String(i.triggerLabel.value||"").trim()||"Run"),stateValuesText:M.computed(()=>ve.value.length?`This field's values: ${ve.value.join(", ")}`:"")},mt=E.tabs(l.querySelector(".aex-tabs"),{tabSelector:".tab-item",panelSelector:".tab-panel"}),ft=M.applyBindings(pt,l,{methods:{save:()=>ye(),discard:()=>dt(),addStep:()=>{G([...v,xt(Ce.peek())]),Q(v.length-1)}}});m(()=>ft.dispose()),m(Ke(l,{position:"bottom"}));const vt=l.querySelector(".aex-vars");for(const[e,t]of Lt){const n=document.createElement("tr"),o=document.createElement("td");e.forEach((a,s)=>{s&&o.append(", ");const d=document.createElement("code");d.textContent=`{{${a}}}`,o.appendChild(d)});const r=document.createElement("td");r.textContent=t,n.append(o,r),vt.appendChild(n)}const qe=l.querySelector(".aex-roles"),Ie=e=>{if(!e.target.matches(".aex-role-cb"))return;const t=e.target.closest("[data-role]")?.dataset.role;if(!t)return;const n=U.peek();U.value=e.target.checked?[...new Set([...n,t])]:n.filter(o=>o!==t)};qe.addEventListener("change",Ie),m(()=>qe.removeEventListener("change",Ie));const De=l.querySelector(".aex-preview-icon");m(M.effect(()=>{const e=String(i.triggerIcon.value||"").trim()||"zap",t=document.createElement("span");t.setAttribute("data-icon",e),t.setAttribute("data-icon-size","14"),De.replaceChildren(t),I.scan(De)})),ge(h,{id:"action-editor-back",icon:"arrow-left",title:"All actions",onClick:()=>{location.hash="#/actions"}});const ht=()=>{_&&ge(h,{id:"action-editor-delete",icon:"trash",title:"Delete this action",onClick:()=>ut()}),ge(h,{id:"action-editor-save",icon:"save",title:"Save (Ctrl+S)",onClick:()=>ye()})};ke(y,_?x:"New action");const Fe=e=>{!(e.ctrlKey||e.metaKey)||e.key!=="s"||(e.preventDefault(),e.stopImmediatePropagation(),ye())};document.addEventListener("keydown",Fe,!0),m(()=>document.removeEventListener("keydown",Fe,!0));const Ue=()=>{if(!oe.peek())return;const e=Me();try{S.set(w,{form:Ee(O(),e),base:N(Ee(e,e)),at:new Date().toISOString()})}catch{}},Oe=e=>{oe.peek()&&(Ue(),e.preventDefault(),e.returnValue="")};window.addEventListener("beforeunload",Oe),m(()=>window.removeEventListener("beforeunload",Oe)),A={key:Ze,dirty:()=>oe.peek(),dispose(){Z=!0,Ue(),T.splice(0).reverse().forEach(e=>{try{e()}catch{}})}},I.scan(l);const yt=await L("/actions/_count").catch(()=>null);if(!C())return;if(yt?.available===!1){H.value=!0,F.value=!1,I.scan(l);return}ht();const[Pe,Be,bt]=await Promise.all([L("/collections").catch(()=>[]),L("/projects").catch(()=>[]),L("/collections/roles/entries?limit=1000").catch(()=>({entries:[]}))]);if(!C())return;for(const e of Array.isArray(Pe)?Pe:[])P.appendChild(f(e.slug,`${e.title||e.slug} (${e.slug})`));for(const e of Array.isArray(Be)?Be:[])z.appendChild(f(e.slug,e.name||e.slug));if(Le.value=(bt?.entries||[]).map(e=>e.data||{}).filter(e=>e.name),P.value=i.collection.peek(),z.value=i.project.peek(),_){try{p=await L(`/actions/${encodeURIComponent(x)}`)}catch(t){if(!C())return;if(We(t)){H.value=!0,F.value=!1;return}E.toast(t.status===404||/not found/i.test(t.message||"")?`There is no action "${x}".`:`Could not load the action: ${t.message||t}`,{type:"error"}),F.value=!1,location.hash="#/actions";return}if(!C())return;if(!p){E.toast(`There is no action "${x}".`,{type:"error"}),location.hash="#/actions";return}ne=p.meta||{},p.collection&&![...P.options].some(t=>t.value===p.collection)&&P.appendChild(f(p.collection,`${p.collection} (not found)`));const e=X(p);e.project&&![...z.options].some(t=>t.value===e.project)&&z.appendChild(f(e.project,e.project)),le(e),P.value=i.collection.peek(),z.value=i.project.peek(),V.value=N(O()),ke(y,p.title||x)}else le(K),V.value=N(O());F.value=!1,I.scan(l);let B=null;try{B=S.get(w)}catch{}if(B?.form){try{S.remove?S.remove(w):S.set(w,null)}catch{}const e=Me(),t=B.base&&B.base!==N(Ee(e,e)),n=B.at?` (${D(B.at).format("D MMM HH:mm")})`:"",o=_?"this action":"a new action",r=t?`You left unsaved changes to ${o}${n}, but it has been saved since. Restore your version anyway?`:`You left unsaved changes to ${o}${n}. Restore them?`;if(await E.confirm(r)&&C()){const{form:a,lost:s}=Ct(B.form,X(p,{project:ue}));s&&E.toast(`${s===1?"A webhook URL":`${s} webhook URLs`} typed before you left ${s===1?"was":"were"} not kept in the draft - enter ${s===1?"it":"them"} again.`,{type:"warning",duration:8e3}),a.collection&&![...P.options].some(d=>d.value===a.collection)&&P.appendChild(f(a.collection,a.collection)),le(a)}}}};
|
|
7
|
+
</label>`,Nt=[[["entry.data.fieldName"],"Any field of the entry"],[["entry.id"],"The entry's id"],[["now"],"The current time (ISO)"],[["user.id","user.name","user.email"],"Who ran it"],[["env.CMS_PUBLIC_*"],"Public environment variables"]],At=h=>String(h??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""");function ke(h,y){const l=h.querySelector(".dm-plugin-banner-name");if(!l)return;const T=l.querySelector(".dm-plugin-banner-sep");if(T){for(;T.nextSibling;)T.nextSibling.remove();T.after(document.createTextNode(y))}}let A=null,Xe=!1;function Rt(){Xe||!window.R?.use||(Xe=!0,R.use((h,y,l)=>{if(!($t.test(y?.path||"")&&re(h?.path)!==re(y?.path))||!A?.dirty())return l();const m=`#${y.path}`;return E.confirm("This action has unsaved changes. Leave anyway? They are kept as a draft for your next visit.").then(Z=>{Z?l():history.replaceState(null,"",m)})}),M.subscribe("router:afterChange",({to:h}={})=>{if(A&&re(h?.path)!==A.key){const y=A;A=null,y.dispose()}}))}export const actionEditorView={templateUrl:"/admin/js/templates/action-editor.html",async onMount(h){if(Rt(),A){const e=A;A=null,e.dispose()}const y=h.get(0),l=y.querySelector(".aex")||y,T=[],m=e=>(T.push(e),e);let Z=!1;const C=()=>!Z&&l.isConnected,ie=location.hash.replace(/^#/,""),we=ie.match(/^\/actions\/edit\/([^/?#]+)/),x=we?decodeURIComponent(we[1]):null,_=!!x,ue=new URLSearchParams(ie.split("?")[1]||"").get("project")||"",Ze=re(ie),w=St(x),F=M.observable(!0),H=M.observable(!1),ee=M.observable(!1),j=M.observable(!1),K=X(null,{project:ue}),i={};for(const[e,t]of Object.entries(K))e!=="steps"&&e!=="roles"&&(i[e]=M.observable(t));const U=M.observable([...K.roles]);let v=K.steps;const te=M.observable(0),de=()=>{te.value=te.peek()+1},Ce=M.observable("updateField");let ne={},p=null;const Me=()=>p?X(p):K,_e=()=>{te.value;const e={steps:v,roles:U.value};for(const t of Object.keys(i))e[t]=i[t].value;return e},O=()=>{const e={steps:v,roles:U.peek()};for(const t of Object.keys(i))e[t]=i[t].peek();return e},V=M.observable(N(K)),oe=M.computed(()=>!F.value&&!H.value&&N(_e())!==V.value),ae=M.computed(()=>gt(_e())),et=M.computed(()=>{const e=ae.value;if(j.value)return e;const t={};return i.title.value&&e.title&&(t.title=e.title),e.slug&&(t.slug=e.slug),e.roles&&(t.roles=e.roles),t}),tt=M.computed(()=>j.value?Je(ae.value):""),nt=M.computed(()=>(te.value,v.length)),b=l.querySelector("#action-steps-list"),pe=M.computed(()=>ae.value.steps||{});let me=null,$e=!1;const P=l.querySelector("#action-collection"),z=l.querySelector("#action-project"),se=l.querySelector("#action-transition-field"),ot=l.querySelector("#action-collection-fields"),at=l.querySelector("#action-transition-values"),f=(e,t)=>{const n=document.createElement("option");return n.value=e,n.textContent=t,n},Le=M.observable([]),Ne=M.observable([]);m(M.effect(()=>{Ne.value=Mt(Le.value,U.value)}));const fe=new Map,J=M.observable([]);let Ae=0;async function st(e){const t=++Ae;if(!e){J.value=[];return}fe.has(e)||fe.set(e,L(`/collections/${encodeURIComponent(e)}`).then(o=>o?.fields||[]).catch(()=>[]));const n=await fe.get(e);t===Ae&&C()&&(J.value=n)}m(M.effect(()=>{st(i.collection.value)})),m(M.effect(()=>{const e=J.value,t=i.transitionField.peek();se.replaceChildren(f("",e.length?"- choose a field -":"- no fields -"));for(const n of e)se.appendChild(f(n.name,`${n.label||n.name} (${n.name})`));t&&!e.some(n=>n.name===t)&&se.appendChild(f(t,`${t} (not in the collection)`)),se.value=t,ot.replaceChildren(...e.map(n=>f(n.name,n.label||n.name))),$e&&he()}));const ve=M.computed(()=>{const e=J.value.find(t=>t.name===i.transitionField.value);return e?.type==="select"?(e.options||[]).map(t=>typeof t=="string"?t:t?.value).filter(Boolean):[]});m(M.effect(()=>{at.replaceChildren(...ve.value.map(e=>f(e,e)))}));function lt(e,t,n){const o=document.createElement("div"),r=document.createElement("label");r.className="form-label",r.textContent=t.label,o.appendChild(r);const a=document.createElement(t.multiline?"textarea":"input");return t.multiline?a.rows=3:a.type="text",a.className=`form-input step-field-${t.name}`,a.placeholder=t.placeholder||"",a.value=e.config[t.name]??"",a.addEventListener("input",()=>{e.config[t.name]=a.value,n()}),o.appendChild(a),o}function ct(e,t,n){const o=J.peek(),r=document.createElement("div"),a=document.createElement("label");a.className="form-label",a.textContent="Field",r.appendChild(a);const s=document.createElement("select");s.className="form-input step-field-field",s.appendChild(f("",o.length?"- choose a field -":"- no fields - enter one below -"));for(const g of o)s.appendChild(f(g.name,`${g.label||g.name} (${g.name})`));s.appendChild(f("__custom__","- enter a field name -"));const d=document.createElement("input");d.type="text",d.className="form-input step-field-field-custom",d.placeholder="Field name, e.g. status",o.some(g=>g.name===e.config.field)?s.value=e.config.field:e.config.field&&(s.value="__custom__",d.value=e.config.field),d.hidden=s.value!=="__custom__",r.append(s,d);const q=document.createElement("div"),W=document.createElement("label");W.className="form-label",W.textContent="New value",q.appendChild(W);const k=document.createElement("div");q.appendChild(k);const $=()=>{k.replaceChildren();const g=o.find(c=>c.name===e.config.field),Y=g?.type==="select"?(g.options||[]).map(c=>typeof c=="string"?{value:c,label:c}:{value:c?.value,label:c?.label||c?.value}).filter(c=>c.value):[],u=document.createElement("input");if(u.type="text",u.className="form-input step-field-value",u.placeholder="e.g. approved or {{now}}",Y.length){const c=document.createElement("select");c.className="form-input",c.appendChild(f("","- choose a value -"));for(const ce of Y)c.appendChild(f(ce.value,ce.label));c.appendChild(f("__custom__","- enter a value -"));const He=Y.some(ce=>ce.value===e.config.value);c.value=He?e.config.value:e.config.value?"__custom__":"",u.value=He?"":e.config.value,u.hidden=c.value!=="__custom__",c.addEventListener("change",()=>{u.hidden=c.value!=="__custom__",e.config.value=c.value==="__custom__"?u.value:c.value,n()}),u.addEventListener("input",()=>{e.config.value=u.value,n()}),k.append(c,u)}else u.value=e.config.value,u.addEventListener("input",()=>{e.config.value=u.value,n()}),k.append(u)};s.addEventListener("change",()=>{d.hidden=s.value!=="__custom__",e.config.field=s.value==="__custom__"?d.value.trim():s.value,e.config.value="",$(),n()}),d.addEventListener("input",()=>{e.config.field=d.value.trim(),n()}),$(),t.append(r,q)}function he(){if(!b)return;const e=pe.peek();b.replaceChildren(),v.forEach((t,n)=>{const o=Ye[t.type],r=document.createElement("div");r.className=`aex-step${j.peek()&&e[n]?" is-bad":""}`,r.dataset.index=String(n);const a=document.createElement("div");a.className="aex-step-head",a.tabIndex=0;const s=document.createElement("span");s.className="aex-step-n",s.textContent=String(n+1);const d=document.createElement("span");d.className="aex-step-main";const be=document.createElement("strong");be.textContent=o?.label||t.type;const q=document.createElement("small");q.className="aex-step-summary",q.textContent=Qe(t),d.append(be,q);const W=document.createElement("span");W.setAttribute("data-help",o?.help||"A step type this editor does not know - it is kept exactly as stored.");const k=document.createElement("button");k.type="button",k.className="aex-kebab",k.textContent="\u22EE",k.title="Actions",k.setAttribute("aria-label",`Actions for step ${n+1}`),a.append(s,d,W,k);const $=document.createElement("div");$.className="aex-step-body";const g=document.createElement("small");g.className="aex-err";const Y=()=>{q.textContent=Qe(t),de()};if(t.type==="updateField")ct(t,$,Y);else if(o&&o.fields.length)o.fields.forEach(u=>$.appendChild(lt(t,u,Y)));else{const u=document.createElement("p");u.className="aex-note",u.textContent=t.type==="deleteEntry"?"Deletes the entry. Nothing to set.":"Nothing to set.",$.appendChild(u)}$.appendChild(g),r.append(a,$),b.appendChild(r)}),I.scan(b),me?.(),me=Ke(b,{position:"bottom"}),Re()}m(()=>me?.());function Re(){const e=pe.peek();for(const t of b?.querySelectorAll(".aex-step")||[]){const n=Number(t.dataset.index),o=j.peek()&&e[n]||"";t.classList.toggle("is-bad",!!o);const r=t.querySelector(":scope > .aex-step-body > .aex-err");r&&(r.textContent=o,r.hidden=!o)}}m(M.effect(()=>{pe.value,j.value,Re()}));const G=e=>{v=e,he(),de()};function rt(e){const t=v[e];return t?[{header:`Step ${e+1} - ${Ye[t.type]?.label||t.type}`},{label:"Move up",icon:"arrow-up",disabled:e===0,action:()=>{G(ze(v,e,-1)),Q(e-1)}},{label:"Move down",icon:"arrow-down",disabled:e===v.length-1,action:()=>{G(ze(v,e,1)),Q(e+1)}},{label:"Duplicate",icon:"copy",action:()=>{G(Et(v,e)),Q(e+1)}},{type:"divider"},{label:"Remove",icon:"trash",danger:!0,action:()=>{G(wt(v,e)),Q(Math.min(e,v.length-1))}}]:[]}const Q=e=>requestAnimationFrame(()=>b?.querySelector(`.aex-step[data-index="${e}"] .aex-step-head`)?.focus()),it=E.contextMenu(b,{cursor:"glyph",match:".aex-step",inherit:!1,density:"compact",items:e=>rt(Number(e.dataset.index))});m(()=>it?.destroy?.());const Te=e=>{const t=e.target.closest(".aex-kebab");t&&Ve(t)},je=e=>{const t=e.target.closest(".aex-step-head");!t||e.target!==t||(e.key==="F10"&&e.shiftKey||e.key==="ContextMenu"?(e.preventDefault(),Ve(t)):e.key==="Enter"&&(e.preventDefault(),t.parentElement.querySelector(".aex-step-body input, .aex-step-body select, .aex-step-body textarea")?.focus()))};b.addEventListener("click",Te),b.addEventListener("keydown",je),m(()=>{b.removeEventListener("click",Te),b.removeEventListener("keydown",je)});function le(e){$e=!0;for(const[t,n]of Object.entries(e))t!=="steps"&&(t==="roles"?U.value=[...n]:i[t]&&(i[t].value=n));v=e.steps.map(t=>({type:t.type,config:{...t.config}})),he(),de()}async function ye(){if(ee.peek()||F.peek()||H.peek())return;j.value=!0;const e=ae.peek();if(Object.keys(e).length){E.toast(Je(e),{type:"warning",duration:6e3});return}ee.value=!0;const t=kt(O(),{meta:ne,editing:_});try{if(_){const n=await L(`/actions/${encodeURIComponent(x)}`,{method:"PUT",body:JSON.stringify(t)});if(!C())return;p=n||{...p,...t},ne=p.meta||ne,V.value=N(O()),j.value=!1;try{S.remove?S.remove(w):S.set(w,null)}catch{}ke(y,p.title||x),Se(xe),E.toast("Action saved.",{type:"success"})}else{const n=await L("/actions",{method:"POST",body:JSON.stringify(t)});V.value=N(O());try{S.remove?S.remove(w):S.set(w,null)}catch{}Se(xe),E.toast(`Action "${n.title||t.title}" created.`,{type:"success"}),C()&&(location.hash=`#/actions/edit/${encodeURIComponent(n.slug)}`)}}catch(n){if(We(n)){H.value=!0;return}E.toast(`Not saved: ${n.message||n}`,{type:"error"})}finally{ee.value=!1}}async function ut(){if(!_)return;const e=p?.title||x;if(await E.confirm(`Delete the action "${At(e)}"? Its button disappears from every entry. This cannot be undone.`))try{await L(`/actions/${encodeURIComponent(x)}`,{method:"DELETE"}),V.value=N(O());try{S.remove?S.remove(w):S.set(w,null)}catch{}Se(xe),E.toast(`Deleted "${e}".`,{type:"success"}),location.hash="#/actions"}catch(t){E.toast(`Not deleted: ${t.message||t}`,{type:"error"})}}function dt(){E.confirm("Discard the changes you have not saved?").then(e=>{!e||!C()||(le(X(p,{project:ue})),j.value=!1)})}l.querySelector(".aex-roles").innerHTML=Lt;const pt={...i,roles:U,loading:F,needsMongo:H,saving:ee,dirty:oe,err:et,problems:tt,stepCount:nt,addType:Ce,roleRows:Ne,editing:_,dirtyText:M.computed(()=>"Unsaved changes - Save (Ctrl+S) to keep them. Leave and they are kept as a draft for next time."),slugHint:M.computed(()=>_?"":Ge(i.title.value)?`Made from the title: ${Ge(i.title.value)}`:"Made from the title"),buttonText:M.computed(()=>String(i.triggerLabel.value||"").trim()||"Run"),stateValuesText:M.computed(()=>ve.value.length?`This field's values: ${ve.value.join(", ")}`:"")},mt=E.tabs(l.querySelector(".aex-tabs"),{tabSelector:".tab-item",panelSelector:".tab-panel"});_t("#action-description");const ft=M.applyBindings(pt,l,{methods:{save:()=>ye(),discard:()=>dt(),addStep:()=>{G([...v,xt(Ce.peek())]),Q(v.length-1)}}});m(()=>ft.dispose()),m(Ke(l,{position:"bottom"}));const vt=l.querySelector(".aex-vars");for(const[e,t]of Nt){const n=document.createElement("tr"),o=document.createElement("td");e.forEach((a,s)=>{s&&o.append(", ");const d=document.createElement("code");d.textContent=`{{${a}}}`,o.appendChild(d)});const r=document.createElement("td");r.textContent=t,n.append(o,r),vt.appendChild(n)}const qe=l.querySelector(".aex-roles"),Ie=e=>{if(!e.target.matches(".aex-role-cb"))return;const t=e.target.closest("[data-role]")?.dataset.role;if(!t)return;const n=U.peek();U.value=e.target.checked?[...new Set([...n,t])]:n.filter(o=>o!==t)};qe.addEventListener("change",Ie),m(()=>qe.removeEventListener("change",Ie));const De=l.querySelector(".aex-preview-icon");m(M.effect(()=>{const e=String(i.triggerIcon.value||"").trim()||"zap",t=document.createElement("span");t.setAttribute("data-icon",e),t.setAttribute("data-icon-size","14"),De.replaceChildren(t),I.scan(De)})),ge(h,{id:"action-editor-back",icon:"arrow-left",title:"All actions",onClick:()=>{location.hash="#/actions"}});const ht=()=>{_&&ge(h,{id:"action-editor-delete",icon:"trash",title:"Delete this action",onClick:()=>ut()}),ge(h,{id:"action-editor-save",icon:"save",title:"Save (Ctrl+S)",onClick:()=>ye()})};ke(y,_?x:"New action");const Fe=e=>{!(e.ctrlKey||e.metaKey)||e.key!=="s"||(e.preventDefault(),e.stopImmediatePropagation(),ye())};document.addEventListener("keydown",Fe,!0),m(()=>document.removeEventListener("keydown",Fe,!0));const Ue=()=>{if(!oe.peek())return;const e=Me();try{S.set(w,{form:Ee(O(),e),base:N(Ee(e,e)),at:new Date().toISOString()})}catch{}},Oe=e=>{oe.peek()&&(Ue(),e.preventDefault(),e.returnValue="")};window.addEventListener("beforeunload",Oe),m(()=>window.removeEventListener("beforeunload",Oe)),A={key:Ze,dirty:()=>oe.peek(),dispose(){Z=!0,Ue(),T.splice(0).reverse().forEach(e=>{try{e()}catch{}})}},I.scan(l);const yt=await L("/actions/_count").catch(()=>null);if(!C())return;if(yt?.available===!1){H.value=!0,F.value=!1,I.scan(l);return}ht();const[Pe,Be,bt]=await Promise.all([L("/collections").catch(()=>[]),L("/projects").catch(()=>[]),L("/collections/roles/entries?limit=1000").catch(()=>({entries:[]}))]);if(!C())return;for(const e of Array.isArray(Pe)?Pe:[])P.appendChild(f(e.slug,`${e.title||e.slug} (${e.slug})`));for(const e of Array.isArray(Be)?Be:[])z.appendChild(f(e.slug,e.name||e.slug));if(Le.value=(bt?.entries||[]).map(e=>e.data||{}).filter(e=>e.name),P.value=i.collection.peek(),z.value=i.project.peek(),_){try{p=await L(`/actions/${encodeURIComponent(x)}`)}catch(t){if(!C())return;if(We(t)){H.value=!0,F.value=!1;return}E.toast(t.status===404||/not found/i.test(t.message||"")?`There is no action "${x}".`:`Could not load the action: ${t.message||t}`,{type:"error"}),F.value=!1,location.hash="#/actions";return}if(!C())return;if(!p){E.toast(`There is no action "${x}".`,{type:"error"}),location.hash="#/actions";return}ne=p.meta||{},p.collection&&![...P.options].some(t=>t.value===p.collection)&&P.appendChild(f(p.collection,`${p.collection} (not found)`));const e=X(p);e.project&&![...z.options].some(t=>t.value===e.project)&&z.appendChild(f(e.project,e.project)),le(e),P.value=i.collection.peek(),z.value=i.project.peek(),V.value=N(O()),ke(y,p.title||x)}else le(K),V.value=N(O());F.value=!1,I.scan(l);let B=null;try{B=S.get(w)}catch{}if(B?.form){try{S.remove?S.remove(w):S.set(w,null)}catch{}const e=Me(),t=B.base&&B.base!==N(Ee(e,e)),n=B.at?` (${D(B.at).format("D MMM HH:mm")})`:"",o=_?"this action":"a new action",r=t?`You left unsaved changes to ${o}${n}, but it has been saved since. Restore your version anyway?`:`You left unsaved changes to ${o}${n}. Restore them?`;if(await E.confirm(r)&&C()){const{form:a,lost:s}=Ct(B.form,X(p,{project:ue}));s&&E.toast(`${s===1?"A webhook URL":`${s} webhook URLs`} typed before you left ${s===1?"was":"were"} not kept in the draft - enter ${s===1?"it":"them"} again.`,{type:"warning",duration:8e3}),a.collection&&![...P.options].some(d=>d.value===a.collection)&&P.appendChild(f(a.collection,a.collection)),le(a)}}}};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{api as y}from"../api.js";import{addBannerAction as de}from"../lib/plugin-chrome.js";import{helpPopovers as Te}from"../lib/help-popover.js";import{onceClosed as it,openMenuAt as Re}from"../lib/tool-kit.js";import{ADDON_TYPES as
|
|
1
|
+
import{api as y}from"../api.js";import{addBannerAction as de}from"../lib/plugin-chrome.js";import{helpPopovers as Te}from"../lib/help-popover.js";import{onceClosed as it,openMenuAt as Re}from"../lib/tool-kit.js";import{ADDON_TYPES as rt,EXTRA_TYPES as pe,FIELD_TYPES as ct,OPERATIONS as dt,OPTION_TYPES as pt,accessOptions as ut,checkForm as ft,draftOf as mt,duplicateField as ht,errorCount as q,fieldFromPanel as Pe,fieldProblem as vt,fieldRow as bt,formFromCollection as De,formFromDraft as yt,moveField as Fe,nameFromLabel as gt,newField as xt,panelForm as wt,payloadFromForm as kt,roleLadder as Et,slugify as Q,snapshot as _,storageChange as Ne}from"../lib/collection-editor-arrange.js";import{fmtDateTime as St}from"../lib/dates.js";import{rowPlaceKeeper as Mt}from"../lib/menu-drag.js";import{openIconPicker as Be}from"../lib/card-builder.js";import{richDescription as Ct}from"../lib/rich-field.js";const $t=/^\/collections\/(new|edit\/[^/?#]+)\/?(\?.*)?$/,At=i=>`collection-editor.draft.${i||"new"}`,Ot=`
|
|
2
2
|
<div class="cex-row" data-key="{{key}}" tabindex="0" data-bind-class="rowCls">
|
|
3
3
|
<span class="cex-grip" title="Drag to reorder" aria-hidden="true"></span>
|
|
4
4
|
<span class="cex-main"><strong data-bind-text="label"></strong><small data-bind-text="meta"></small><small class="cex-problem" data-bind-hidden="!problem" data-bind-text="problem"></small></span>
|
|
@@ -6,7 +6,7 @@ import{api as y}from"../api.js";import{addBannerAction as de}from"../lib/plugin-
|
|
|
6
6
|
<span class="cex-chip" data-bind-hidden="!hidden">Hidden</span>
|
|
7
7
|
<span class="cex-chip" data-bind-hidden="!notInLists">Not in lists</span>
|
|
8
8
|
<button type="button" class="cex-kebab" aria-label="Actions for this field" title="Actions">\u22EE</button>
|
|
9
|
-
</div>`,Z=i=>String(i??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""");function
|
|
9
|
+
</div>`,Z=i=>String(i??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""");function jt(i){const p=document.createElement("template");return p.innerHTML=i.trim(),p.content.firstElementChild}function Le(i,p){const r=i.querySelector(".dm-plugin-banner-name");if(!r)return;const $=document.createElement("span");$.className="dm-plugin-banner-parent",$.textContent="Collections";const x=document.createElement("span");x.className="dm-plugin-banner-sep",x.setAttribute("aria-hidden","true"),x.textContent="\u203A",r.replaceChildren($,x,document.createTextNode(p))}let g=null,qe=!1;const ee=i=>String(i||"").split("?")[0];function It(){qe||!window.R?.use||(qe=!0,R.use((i,p,r)=>{if(!(g&&$t.test(p?.path||"")&&ee(i?.path)!==ee(p?.path))||!g.dirty())return r();const x=`#${p.path}`;return E.confirm("This collection has unsaved changes. Leave anyway? They are kept as a draft for your next visit.").then(d=>{d?r():history.replaceState(null,"",x)})}),M.subscribe("router:afterChange",({to:i}={})=>{if(g&&ee(i?.path)!==g.path){const p=g;g=null,p.dispose()}}))}export const collectionEditorView={templateUrl:"/admin/js/templates/collection-editor.html",async onMount(i){if(It(),g){const e=g;g=null,e.dispose()}const p=i.get(0),r=p.querySelector(".cex")||p,$=ee(location.hash.replace(/^#/,""))||"/collections/new",x=$.match(/^\/collections\/edit\/([^/?#]+)/),d=x?decodeURIComponent(x[1]):null,D=!d,ue=[],v=e=>(ue.push(e),e);let fe=!1;const te=()=>!fe&&r.isConnected,me=E.loader(p,{type:"dots"});let A=null,ae=[],F=null,he=[],u=0,N=[];try{[A,ae,F,he,N]=await Promise.all([d?y.collections.get(d):Promise.resolve(null),y.projects.list().catch(()=>[]),y.collections.proStatus().catch(()=>null),D?y.collections.list().then(e=>(e||[]).map(t=>t.slug)).catch(()=>[]):Promise.resolve([]),y.collections.listEntries("roles",{limit:1e3}).then(Et).catch(()=>[])]),d&&(u=(await y.collections.listEntries(d,{limit:1}).catch(()=>null))?.total??0)}catch(e){me.destroy(),E.toast(e?.status===404?"Collection not found.":`Could not load the collection: ${e.message||e}`,{type:"error"}),R.navigate("/collections");return}if(me.destroy(),!r.isConnected)return;if(d&&!A){E.toast("Collection not found.",{type:"error"}),R.navigate("/collections");return}const ve=new URLSearchParams(location.hash.split("?")[1]||"").get("project")||"",m=De(A,{project:ve,defaultRole:N.at(-1)?.name||""}),w=Object.fromEntries(m.fields.map(e=>[e._key,e.name])),_e=A?.meta||{};let K=m.storageAdapter;const Ke=new Set(["public","token",...N.map(e=>e.name)]),be=(e,t)=>{if(!N.length)return"";const n=[...new Set(e.filter(l=>l&&!Ke.has(l)))];return n.length?`Not a role on this site: ${n.join(", ")}. Until you pick another, ${t}.`:""},a={};for(const[e,t]of Object.entries(m))a[e]=M.observable(t);const k=M.observable(D),U=M.observable(!1),H=()=>Object.fromEntries(Object.keys(a).map(e=>[e,a[e].peek()])),ye=()=>Object.fromEntries(Object.keys(a).map(e=>[e,a[e].value])),P=M.observable(_(m)),B=M.computed(()=>_(ye())!==P.value);let Y=!D;v(M.effect(()=>{const e=a.title.value;Y||(a.slug.value=Q(e))}));const h=M.computed(()=>ft(ye(),{isNew:k.value,taken:he,original:w})),ge=M.observable([]);v(M.effect(()=>{const e=h.value.fields||{},t=a.layout.value==="grid";ge.value=a.fields.value.map(n=>bt(n,e,{grid:t}))}));const Ue=M.computed(()=>new Set(a.fields.value.map(e=>e.name))),He={...a,isNew:k,saving:U,dirty:B,rows:ge,errTitle:M.computed(()=>h.value.title||""),errSlug:M.computed(()=>h.value.slug||""),errColumns:M.computed(()=>h.value.columns||""),errExport:M.computed(()=>h.value.export||""),problemCount:M.computed(()=>q(h.value)),problemText:M.computed(()=>{const e=q(h.value);return e?`${e} thing${e===1?"":"s"} to fix before it can be saved`:""}),settingsBad:M.computed(()=>!!(h.value.title||h.value.slug||h.value.columns)),fieldsBad:M.computed(()=>!!h.value.fields),exportBad:M.computed(()=>!!h.value.export),fieldCount:M.computed(()=>a.fields.value.length),slugHint:M.computed(()=>k.value?`Will be created as "${Q(a.slug.value||a.title.value)||"\u2026"}".`:"Cannot be changed once the collection exists."),apiPath:M.computed(()=>`/api/collections/${Q(a.slug.value||a.title.value)||"<slug>"}/public`),unknownReadFields:M.computed(()=>{const e=String(a.readFields.value||"").split(",").map(t=>t.trim()).filter(t=>t&&!Ue.value.has(t));return e.length?`Not a field of this collection: ${e.join(", ")}`:""}),missingApiRoles:M.computed(()=>be(dt.filter(e=>a[`${e}Enabled`].value).map(e=>a[`${e}Access`].value),"only the level-0 role passes")),missingExportRole:M.computed(()=>be(a.exportEnabled.value?[a.exportAccess.value]:[],"only the level-0 role is offered export")),showStorage:M.observable(!!F?.pro&&d!=="roles"),storageNote:M.computed(()=>{const e=Ne(K,a.storageAdapter.value);return!e||k.value?"":u?`Switching ${e}: Save asks whether to move the ${u} existing ${u===1?"entry":"entries"} across. Export them first if they matter.`:`Switching ${e}. There are no entries to move.`})},xe=r.querySelector("#collection-project");for(const e of ae){const t=document.createElement("option");t.value=e.slug,t.textContent=e.name||e.slug,xe.appendChild(t)}if(m.project&&!ae.some(e=>e.slug===m.project)){const e=document.createElement("option");e.value=m.project,e.textContent=`${m.project} (not found)`,xe.appendChild(e)}const Ye=[...r.querySelectorAll('.cex-op select[data-model$="Access.value"]')],we=e=>{for(const t of Ye){const n=t.getAttribute("data-model").split(".")[0],l=e[n];t.replaceChildren(...ut(N,l,{token:t.id!=="export-access"}).map(c=>new Option(c.label,c.value))),t.value=l}};we(m);const We=r.querySelector("#storage-connection"),ze=Array.isArray(F?.connections)&&F.connections.length?F.connections:["default"];for(const e of new Set([...ze,m.storageConnection])){const t=document.createElement("option");t.value=e,t.textContent=e,We.appendChild(t)}const W=e=>a.fields.peek().findIndex(t=>t._key===e),O=e=>{a.fields.value=e};function z(e,t){const n=W(e);n<0||(O(Fe(a.fields.peek(),n,n+t)),requestAnimationFrame(()=>r.querySelector(`.cex-row[data-key="${e}"]`)?.focus()))}async function ne(e){const t=W(e);if(t<0)return;const n=a.fields.peek()[t];!k.peek()&&u&&w[e]&&!await E.confirm(`Remove the field "${Z(n.label||n.name)}"? The ${u} existing ${u===1?"entry keeps its":"entries keep their"} value for it, but it is no longer shown or edited. Nothing is lost until you Save - Discard puts it back.`)||O(a.fields.peek().filter(l=>l._key!==e))}function G(e,{isAdded:t=!1}={}){const n=W(e);if(n<0)return;const l=a.fields.peek()[n],c=wt(l),s={};for(const[o,C]of Object.entries(c))s[o]=M.observable(C);const f=JSON.stringify(c),V=()=>Object.fromEntries(Object.keys(s).map(o=>[o,s[o].peek()])),$e=()=>JSON.stringify(V())!==f;let Ae=!!l.name;const et=M.effect(()=>{const o=s.label.value;Ae||(s.name.value=gt(o))}),tt=new Set(a.fields.peek().filter(o=>o._key!==e).map(o=>o.name)),Oe=M.computed(()=>{const o=Pe(l,Object.fromEntries(Object.keys(s).map(C=>[C,s[C].value])));return o.name&&tt.has(o.name)?`"${o.name}" is used by another field.`:vt(o,w[e])}),at=M.computed(()=>!k.peek()&&u&&w[e]&&s.name.value.trim()!==w[e]?`Entries keep their value under "${w[e]}" - renaming the field does not move it.`:""),nt={...s,problem:Oe,renamed:at,isOptions:M.computed(()=>pt.has(s.type.value)),canAddon:M.computed(()=>rt.has(s.type.value)),canClear:M.computed(()=>pe.clear.has(s.type.value)),canStepper:M.computed(()=>pe.stepper.has(s.type.value)),canCounter:M.computed(()=>pe.counter.has(s.type.value)),isGrid:M.computed(()=>a.layout.value==="grid")},b=E.slideover({title:t?"New field":`Field: ${Z(l.label||l.name||"Untitled")}`,size:"md",position:"right"}),T=jt(`
|
|
10
10
|
<div class="cex-panel">
|
|
11
11
|
<div class="cex-grid">
|
|
12
12
|
<div>
|
|
@@ -21,7 +21,7 @@ import{api as y}from"../api.js";import{addBannerAction as de}from"../lib/plugin-
|
|
|
21
21
|
<div>
|
|
22
22
|
<label class="form-label" for="cex-f-type">Type</label>
|
|
23
23
|
<select id="cex-f-type" class="form-input" data-model="type.value">
|
|
24
|
-
${
|
|
24
|
+
${ct.map(o=>`<option value="${o.value}">${o.label}</option>`).join("")}
|
|
25
25
|
</select>
|
|
26
26
|
</div>
|
|
27
27
|
<div class="cex-setting">
|
|
@@ -98,4 +98,4 @@ import{api as y}from"../api.js";import{addBannerAction as de}from"../lib/plugin-
|
|
|
98
98
|
<button type="button" class="btn btn-sm btn-ghost" data-on-click="cancel">Cancel</button>
|
|
99
99
|
<button type="button" class="btn btn-sm btn-primary" data-on-click="done" data-bind-disabled="problem.value"><span data-icon="check" data-icon-size="13"></span> Done</button>
|
|
100
100
|
</div>
|
|
101
|
-
</div>`);let X=!1,
|
|
101
|
+
</div>`);let X=!1,re=!1;const ot=b.close.bind(b);function je(){if(Oe.peek())return;const o=Pe(l,V());O(a.fields.peek().map(C=>C._key===e?o:C)),X=!0,b.close()}b.element.appendChild(T);const lt=Te(T),st=M.applyBindings(nt,T,{methods:{done:je,cancel:()=>b.close(),pickPrefix:()=>Be(o=>{s.prefixIcon.value=o,s.prefixText.value=""}),pickSuffix:()=>Be(o=>{s.suffixIcon.value=o,s.suffixText.value=""}),remove:async()=>{X=!0,b.close(),await ne(e)}}}),Ie=T.querySelector("#cex-f-name");Ie.addEventListener("input",()=>{Ae=!!Ie.value}),T.addEventListener("keydown",o=>{(o.ctrlKey||o.metaKey)&&o.key==="Enter"&&(o.preventDefault(),je())}),it(b,()=>{et(),st.dispose(),lt(),se.delete(b)}),b.close=async o=>{if(!X&&o!==!0&&$e()){if(re)return;re=!0;const ce=await E.confirm("Discard the changes to this field?");if(re=!1,!ce)return}X=!0;const C=ot();return t&&!$e()&&!l.name&&O(a.fields.peek().filter(ce=>ce._key!==e)),C},se.add(b),I.scan(T),b.open(),T.querySelector("#cex-f-label")?.focus()}function Ge(){const e=xt();O([...a.fields.peek(),e]),Xe.activate?.(1),G(e._key,{isAdded:!0})}function Je(e){const t=W(e);if(t<0)return[];const n=a.fields.peek()[t],l=a.fields.peek().length;return[{header:n.label||n.name||"Field"},{label:"Edit\u2026",icon:"edit",action:()=>G(e)},{label:"Move up",icon:"arrow-up",disabled:t===0,action:()=>z(e,-1)},{label:"Move down",icon:"arrow-down",disabled:t===l-1,action:()=>z(e,1)},{label:"Duplicate",icon:"copy",action:()=>O(ht(a.fields.peek(),t))},{type:"divider"},{label:"Remove\u2026",icon:"trash",danger:!0,action:()=>ne(e)}]}async function oe(){if(U.peek())return;const e=h.peek();if(q(e)){E.toast(`Not saved - ${q(e)} thing${q(e)===1?"":"s"} to fix first (marked on the tabs).`,{type:"warning"});return}const t=kt(H(),{isNew:k.peek(),meta:_e});U.value=!0;try{if(k.peek()){const l=await y.collections.create(t);P.value=_(H()),ie(),E.toast(`Created "${t.title}".`,{type:"success"}),R.navigate(`/collections/edit/${encodeURIComponent(l.slug)}`);return}const n=Ne(K,t.storage.adapter);if(n&&u){if(await E.confirm(`You changed the storage (${n}). Move the ${u} existing ${u===1?"entry":"entries"} to the new storage?`)){const c=await y.collections.migrateStorage(d,t.storage);E.toast(`Moved ${c.migrated} of ${c.total} entries.`,{type:"success"})}else if(!await E.confirm(`Switch without moving them? The ${u} ${u===1?"entry stays":"entries stay"} in ${Z(K)} storage and this collection will show none until they are moved.`))return}if(await y.collections.update(d,t),!te())return;K=t.storage.adapter,n&&(u=(await y.collections.listEntries(d,{limit:1}).catch(()=>null))?.total??u);for(const l of a.fields.peek())w[l._key]=l.name;P.value=_(H()),ie(),Le(p,t.title),E.toast("Collection saved.",{type:"success"})}catch(n){E.toast(`Not saved: ${n.message||n}`,{type:"error"})}finally{U.value=!1}}async function Ve(){if(!B.peek()||!await E.confirm("Discard the changes you have not saved?"))return;const e=De(A,{project:ve});for(const t of e.fields)w[t._key]=t.name;for(const[t,n]of Object.entries(e))a[t].value=n;P.value=_(e),Y=!k.peek()}const L=r.querySelector(".cex-list");L.innerHTML=Ot;const Xe=E.tabs(r.querySelector(".cex-tabs"),{tabSelector:".tab-item",panelSelector:".tab-panel"});Ct("#field-description");const Qe=M.applyBindings(He,r,{methods:{save:()=>oe(),discard:()=>Ve(),addField:()=>Ge()}});v(()=>Qe.dispose()),v(Te(r,{position:"bottom"}));const le=r.querySelector("#field-slug"),ke=()=>{Y=!!le.value};le.addEventListener("input",ke),v(()=>le.removeEventListener("input",ke));const se=new Set;v(()=>[...se].forEach(e=>{try{e.close(!0)}catch{}}));const Ze=E.contextMenu(L,{cursor:"glyph",match:".cex-row",inherit:!1,density:"compact",items:e=>Je(e.dataset.key)});v(()=>Ze?.destroy?.());const Ee={click:e=>{const t=e.target.closest(".cex-row");if(!t)return;const n=e.target.closest(".cex-kebab");if(n){Re(n);return}G(t.dataset.key)},keydown:e=>{const t=e.target.closest(".cex-row");!t||e.target!==t||(e.key==="F10"&&e.shiftKey?(e.preventDefault(),Re(t)):e.key==="Enter"?G(t.dataset.key):e.altKey&&e.key==="ArrowUp"?(e.preventDefault(),z(t.dataset.key,-1)):e.altKey&&e.key==="ArrowDown"?(e.preventDefault(),z(t.dataset.key,1)):e.key==="Delete"&&(e.preventDefault(),ne(t.dataset.key)))}};for(const[e,t]of Object.entries(Ee))L.addEventListener(e,t);if(v(()=>{for(const[e,t]of Object.entries(Ee))L.removeEventListener(e,t)}),typeof E.sortable=="function"){const e=Mt(),t=E.sortable(L,{items:".cex-row",key:"data-key",keyboard:!1,onStart:e.start,onEnd:({item:n})=>e.restore(n),onSort:({item:n,from:l,to:c})=>{e.restore(n),O(Fe(a.fields.peek(),l,c))}});v(()=>t.destroy())}Le(p,A?.title||"New collection"),de(i,{id:"collection-editor-back",icon:"arrow-left",title:"All collections",onClick:()=>R.navigate("/collections")}),d&&de(i,{id:"collection-editor-entries",icon:"list",title:"Open entries",onClick:()=>R.navigate(`/collections/${encodeURIComponent(d)}/entries`)}),de(i,{id:"collection-editor-save",icon:"save",title:"Save (Ctrl+S)",onClick:()=>oe()});const Se=e=>{!(e.ctrlKey||e.metaKey)||e.key!=="s"||!te()||(e.preventDefault(),e.stopImmediatePropagation(),oe())};document.addEventListener("keydown",Se,!0),v(()=>document.removeEventListener("keydown",Se,!0));const J=At(d);function ie(){try{S.remove?S.remove(J):S.set(J,null)}catch{}}const Me=()=>{if(B.peek())try{S.set(J,{form:mt(H()),base:P.peek(),at:new Date().toISOString()})}catch{}},Ce=e=>{B.peek()&&(Me(),e.preventDefault(),e.returnValue="")};window.addEventListener("beforeunload",Ce),v(()=>window.removeEventListener("beforeunload",Ce)),g={path:$,dirty:()=>B.peek(),dispose(){fe=!0,Me(),ue.splice(0).reverse().forEach(e=>{try{e()}catch{}})}},I.scan(r);let j=null;try{j=S.get(J)}catch{}if(j?.form){ie();const e=j.base&&j.base!==P.peek(),t=j.at?` (${St(j.at)})`:"",n=d?`changes to "${Z(A?.title||d)}"`:"a new collection",l=e?`You left unsaved ${n}${t}, but the saved collection has changed since. Restore your version anyway?`:`You left unsaved ${n}${t}. Restore them?`;if(await E.confirm(l)&&te()){const c=yt(j.form,m);D||(c.slug=m.slug);const s=Object.fromEntries(m.fields.filter(f=>f.id).map(f=>[f.id,f.name]));for(const f of c.fields)f.id&&s[f.id]!==void 0&&(w[f._key]=s[f.id]);we(c);for(const[f,V]of Object.entries(c))a[f]&&(a[f].value=V);D&&(Y=!!c.slug&&c.slug!==Q(c.title))}}}};
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import{wirePrivateLink as ft}from"/admin/js/lib/private-files.js";import{api as k,apiRequest as mt}from"../api.js";import{addBannerAction as j}from"../lib/plugin-chrome.js";import{SHAPES as ht,showLoading as yt}from"../lib/loading.js";import{helpPopovers as ze}from"../lib/help-popover.js";import{onceClosed as vt,openMenuAt as je,sidebarCount as P,viewLifetime as bt}from"../lib/tool-kit.js";import{PAGE_SIZE as ce,SHOW_STEP as X,arrangeEntries as gt,listColumns as Et,canClear as kt,cellText as Pe,countText as xt,draftable as wt,fileRefsOf as St,filterChoices as Ct,filterText as $t,hasForm as At,isFileValue as ve,safeFileHref as Mt,shownValue as be,snapshot as _e,typedValue as Lt,valueText as ge}from"../lib/collection-entries-arrange.js";import{fmtDate as qt,fmtDateTime as _}from"../lib/dates.js";const Be=/^#\/collections\/[^/?#]+\/entries\/?(\?.*)?$/,B=p=>`collection-entries.draft.${p}`,U=p=>String(p??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""");function le(p){const m=document.createElement("template");return m.innerHTML=p.trim(),m.content.firstElementChild}const
|
|
1
|
+
import{wirePrivateLink as ft}from"/admin/js/lib/private-files.js";import{api as k,apiRequest as mt}from"../api.js";import{addBannerAction as j}from"../lib/plugin-chrome.js";import{SHAPES as ht,showLoading as yt}from"../lib/loading.js";import{helpPopovers as ze}from"../lib/help-popover.js";import{onceClosed as vt,openMenuAt as je,sidebarCount as P,viewLifetime as bt}from"../lib/tool-kit.js";import{PAGE_SIZE as ce,SHOW_STEP as X,arrangeEntries as gt,listColumns as Et,canClear as kt,cellText as Pe,countText as xt,draftable as wt,fileRefsOf as St,filterChoices as Ct,filterText as $t,hasForm as At,isFileValue as ve,safeFileHref as Mt,shownValue as be,snapshot as _e,typedValue as Lt,valueText as ge}from"../lib/collection-entries-arrange.js";import{fmtDate as qt,fmtDateTime as _}from"../lib/dates.js";import{richTextSummary as Tt}from"../lib/rich-field.js";const Be=/^#\/collections\/[^/?#]+\/entries\/?(\?.*)?$/,B=p=>`collection-entries.draft.${p}`,U=p=>String(p??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""");function le(p){const m=document.createElement("template");return m.innerHTML=p.trim(),m.content.firstElementChild}const Nt='<span class="cex-chip">{{text}}<button type="button" data-idx="{{idx}}" title="Remove this filter" aria-label="Remove filter {{text}}">\xD7</button></span>';function It(p){return`
|
|
2
2
|
<tr class="cex-row" data-id="{{id}}" tabindex="0" data-bind-class="rowCls">
|
|
3
3
|
<td class="cex-check"><input type="checkbox" class="cex-sel" aria-label="Select this entry" data-bind-checked="sel"></td>
|
|
4
4
|
${Array.from({length:p},(v,a)=>`<td data-col="${a}" title="{{t${a}}}">{{c${a}}}</td>`).join("")}
|
|
5
5
|
<td class="cex-when" title="{{whenFull}}">{{when}}</td>
|
|
6
6
|
<td class="cex-tools"><button type="button" class="cex-run" data-bind-hidden="!runs" title="Run one of this collection's actions">\u26A1 {{runs}}</button><button type="button" class="cex-kebab" aria-label="Actions for this entry" title="Actions">\u22EE</button></td>
|
|
7
|
-
</tr>`}const
|
|
7
|
+
</tr>`}const Dt=(p,m)=>p?.type==="file"||ve(m?.[p?.name]);function He(p){const m=document.createElement("ul");m.className="cex-files";for(const v of St(p)){const a=document.createElement("li"),l=Mt(v.url),c=document.createElement(l?"a":"span");l&&(c.href=l,c.target="_blank",c.rel="noopener",ft(c,v)),c.textContent=ge(v),a.appendChild(c),m.appendChild(a)}return m}function Ot(p,m){const v={};return p.forEach(a=>{const l={};a.fullWidth?l.span=m:a.span>1&&(l.span=a.span),a.placeholder&&(l.placeholder=a.placeholder),a.helper&&(l.hint=a.helper),a.prefix&&(l.prefix=a.prefix),a.suffix&&(l.suffix=a.suffix);for(const u of["clear","stepper","counter"])a[u]===!0&&(l[u]=!0);const c=a.type==="checkbox"?"boolean":a.type==="date"?"string":a.type;v[a.name]={type:c,label:a.label,required:a.required,options:a.options,...Object.keys(l).length?{formConfig:l}:{}}}),v}function Ve(p,m){const v=CSS.escape(m);return[...p.querySelectorAll(`[name="${v}"], [name="${v}[]"]`)]}function ie(p,m){const v={};for(const a of m){const l=Ve(p,a.name);if(!l.length)continue;const c=l[0];c.type==="radio"?v[a.name]=l.find(u=>u.checked)?.value??"":c.type==="checkbox"&&(l.length>1||c.name.endsWith("[]"))?v[a.name]=l.filter(u=>u.checked).map(u=>u.value):c.type==="checkbox"?v[a.name]=c.checked:c.tagName==="SELECT"&&c.multiple?v[a.name]=[...c.selectedOptions].map(u=>u.value):v[a.name]=Lt(a,c.value)}return v}function Je(p,m,v){for(const a of m){if(!(a.name in v))continue;const l=v[a.name],c=Ve(p,a.name);if(!c.length)continue;const u=c[0];u.type==="radio"?c.forEach(r=>{r.checked=r.value===String(l)}):u.type==="checkbox"&&(c.length>1||u.name.endsWith("[]"))?c.forEach(r=>{r.checked=Array.isArray(l)&&l.includes(r.value)}):u.type==="checkbox"?u.checked=l===!0:u.tagName==="SELECT"&&u.multiple?[...u.options].forEach(r=>{r.selected=Array.isArray(l)&&l.includes(r.value)}):u.value=l??"",c.forEach(r=>r.dispatchEvent(new Event("input",{bubbles:!0})))}}const Ke=bt(Be);export const collectionEntriesView={templateUrl:"/admin/js/templates/collection-entries.html",async onMount(p){Ke.reset();const m=p.get(0).querySelector(".cex")||p.get(0),v=location.hash.match(/^#\/collections\/([^/?#]+)\/entries/),a=v?decodeURIComponent(v[1]):null,l=()=>Be.test(location.hash)&&m.isConnected&&location.hash.includes(`/collections/${encodeURIComponent(a)}/entries`),c=e=>(Ke.add(e),e);if(!a){E.toast("No collection selected.",{type:"error"});return}const u=M.observable(null),r=M.observable([]),x=M.observable(0),Y=M.observable(!0),H=M.observable(""),We=M.computed(()=>u.value!==null),re=M.observable(""),w=M.observable([]),Z=M.observable({key:"created",dir:"desc"}),g=M.observable([]),N=M.observable(X),V=M.observable([]),Q=M.observable({}),L=M.observable(!1);let ee=1;const te=()=>u.peek()?.fields||[],de=M.computed(()=>Et(u.value?.fields)),J=e=>r.peek().find(t=>t.id===e),Ee=e=>V.peek().filter(t=>{const n=Q.peek()[t.slug];return n==null||n.has(e)}),D=M.observable([]),ke=M.observable([]);c(M.effect(()=>{const e=gt(r.value,{filters:w.value,query:re.value,sort:Z.value});D.value=e})),c(M.effect(()=>{const e=de.value,t=new Set(g.value);Q.value,V.value,ke.value=D.value.slice(0,N.value).map(n=>{const o={id:n.id,sel:t.has(n.id),rowCls:t.has(n.id)?"is-selected":""};e.forEach((i,h)=>{const d=be(i,n.data?.[i.name]);o[`c${h}`]=Pe(d),o[`t${h}`]=ge(d)});const s=n.meta?.createdAt;o.when=s?qt(s):"",o.whenFull=s?`Created ${_(s)}${n.meta?.updatedAt?` \xB7 changed ${_(n.meta.updatedAt)}`:""}`:"";const f=Ee(n.id).length;return o.runs=f?String(f):"",o})}));const Ge=M.computed(()=>w.value.map((e,t)=>({key:`${t}:${e.field}:${e.op}:${e.value}`,idx:t,text:$t(e)}))),Xe=M.computed(()=>g.value.length),Ye={schema:u,loaded:r,loading:Y,loadError:H,ready:We,query:re,rows:ke,chips:Ge,busy:L,selectedCount:Xe,countLine:M.computed(()=>xt(D.value.length,r.value.length,x.value)),selectedText:M.computed(()=>`${g.value.length} selected`),canClear:M.computed(()=>kt(a)),introText:M.computed(()=>{const e=u.value;return e?`${e.description?`${Tt(e.description,200)} - `:""}${(e.fields||[]).length} field${(e.fields||[]).length===1?"":"s"}${e.storage?.adapter==="mongodb"?", on MongoDB":""}.`:""}),emptyText:M.computed(()=>r.value.length?"No entries match the search or filters.":"No entries yet - Add entry in the banner makes one, or Import brings many."),moreText:M.computed(()=>{const e=D.value.length-N.value;if(e>0)return`Show ${Math.min(X,e)} more (${e} not shown)`;const t=x.value-r.value.length;return t>0?`Load the next ${Math.min(ce,t)} from the server`:""})};async function K({reset:e=!0,pending:t=null}={}){Y.value=!0;try{const n=e?Math.max(ce,r.peek().length):ce;e&&(ee=1);const o=await k.collections.listEntries(a,{limit:n,page:ee});if(t&&await t.done(),!l())return;const s=o?.entries||(Array.isArray(o)?o:[]);r.value=e?s:[...r.peek(),...s.filter(i=>!J(i.id))],x.value=Number(o?.total)||r.peek().length,e&&(ee=Math.max(1,Math.ceil(r.peek().length/ce)));const f=new Set(r.peek().map(i=>i.id));g.value=g.peek().filter(i=>f.has(i)),H.value="",await et()}catch(n){H.value=`Could not load the entries: ${n.message||n}`}finally{t&&await t.done(),Y.value=!1}}async function Ze(){ee+=1,await K({reset:!1})}async function Qe(){try{if((await mt("/actions/_count",{method:"GET"}).catch(()=>null))?.available===!1)return;const t=await k.actions.forCollection(a);V.value=Array.isArray(t)?t.filter(n=>n.canRun!==!1):[]}catch{V.value=[]}}async function et(){const e=V.peek().filter(o=>o.access?.rowLevel);if(!e.length||!r.peek().length)return;const t=r.peek().map(o=>o.id),n={...Q.peek()};await Promise.all(e.map(async o=>{try{n[o.slug]=new Set((await k.actions.checkAccess(o.slug,t)).allowed)}catch{n[o.slug]=null}})),Q.value=n}const W=e=>{const t=te()[0];return(t?Pe(be(t,e?.data?.[t.name]),40):"")||`Entry ${String(e?.id||"").slice(0,8)}`};async function xe(e){if(await E.confirm(`Delete \u201C${U(W(e))}\u201D? This cannot be undone.`))try{await k.collections.deleteEntry(a,e.id),r.value=r.peek().filter(t=>t.id!==e.id),x.value=Math.max(0,x.peek()-1),g.value=g.peek().filter(t=>t!==e.id),P("#/collections"),E.toast("Entry deleted.",{type:"success"})}catch(t){E.toast(`Not deleted: ${t.message||t}`,{type:"error"})}}async function tt(){const e=[...g.peek()];if(!e.length||!await E.confirm(`Delete ${e.length} entr${e.length===1?"y":"ies"}? This cannot be undone.`))return;L.value=!0;let t=0;const n=[];for(const o of e)try{await k.collections.deleteEntry(a,o),t++}catch(s){n.push(s.message||String(s))}L.value=!1,g.value=[],P("#/collections"),E.toast(n.length?`Deleted ${t}; ${n.length} refused (${n[0]}).`:`Deleted ${t} entr${t===1?"y":"ies"}.`,{type:n.length?"warning":"success",duration:n.length?7e3:4e3}),l()&&await K()}async function nt(){const e=u.peek();if(await E.confirm(`Delete ALL ${x.peek()} entries in \u201C${U(e?.title||a)}\u201D? This cannot be undone.`)){L.value=!0;try{await k.collections.clearEntries(a),r.value=[],x.value=0,g.value=[],P("#/collections"),E.toast("All entries deleted.",{type:"success"})}catch(t){E.toast(`Not cleared: ${t.message||t}`,{type:"error"})}finally{L.value=!1}}}async function at(e){try{const t=await k.collections.createEntry(a,{...e.data||{}});r.value=[t,...r.peek()],x.value=x.peek()+1,P("#/collections"),E.toast("Duplicated - the copy is at the top.",{type:"success"})}catch(t){E.toast(`Not duplicated: ${t.message||t}`,{type:"error"})}}async function st(e,t){const n=e.trigger?.confirmMessage;if(!(n&&!await E.confirm(U(n)))){L.value=!0;try{const o=await k.actions.execute(e.slug,t.id);if(o?.success){const s=o.stepsCompleted??0;E.toast(`${e.trigger?.label||e.title||"Action"} done (${s} step${s===1?"":"s"}).`,{type:"success"}),l()&&await K()}else E.toast(o?.results?.find(s=>!s.success)?.error||"The action failed.",{type:"error"})}catch(o){E.toast(o.message||"The action failed.",{type:"error"})}finally{L.value=!1}}}async function we(e){try{await navigator.clipboard.writeText(e),E.toast("Copied.",{type:"success",duration:1500})}catch{E.toast("Copy failed - your browser refused the clipboard.",{type:"error"})}}function ue(e){const t=g.peek();g.value=t.includes(e)?t.filter(n=>n!==e):[...t,e]}function Se(e,t,n){w.value=[...w.peek(),{field:e.name,label:e.label||e.name,op:t,value:n}],N.value=X}const pe=new Set;let O=null,Ce=!1;function $e(e,t,n){const o=e.close.bind(e);let s=!1,f=!1;e.close=async i=>{if(!s&&i!==!0&&!Ce&&t()){if(f)return;f=!0;const h=await E.confirm(n);if(f=!1,!h)return}return s=!0,o()}}function ne(e,t=()=>{}){pe.add(e),vt(e,()=>{pe.delete(e),t()})}function z(e,t=null){const n=u.peek(),o=te().filter(y=>Dt(y,e?.data)),s=te().filter(y=>!o.includes(y)),f=Object.fromEntries(o.filter(y=>e?.data&&y.name in e.data).map(y=>[y.name,e.data[y.name]])),i=!!e,h=E.slideover({title:i?`Edit ${U(W(e))}`:"New entry",size:"md",position:"right"}),d=le(`
|
|
8
8
|
<div class="cex-form">
|
|
9
9
|
<div class="cex-fields"></div>
|
|
10
10
|
<small class="cex-hint cex-when-line"></small>
|
|
@@ -15,7 +15,7 @@ import{wirePrivateLink as ft}from"/admin/js/lib/private-files.js";import{api as
|
|
|
15
15
|
<button type="button" class="btn btn-sm btn-ghost" data-act="cancel">Cancel</button>
|
|
16
16
|
<button type="button" class="btn btn-sm btn-primary" data-act="save"><span data-icon="check" data-icon-size="13"></span> <span class="cex-save-text"></span></button>
|
|
17
17
|
</div>
|
|
18
|
-
</div>`);d.querySelector(".cex-save-text").textContent=i?"Save":"Add entry";const b=d.querySelector(".cex-fields");for(const y of o){if(!ve(f[y.name]))continue;const $=document.createElement("div");$.className="cex-files-field";const T=document.createElement("span");T.textContent=y.label||y.name,$.append(T,He(f[y.name])),b.before($)}F.create(
|
|
18
|
+
</div>`);d.querySelector(".cex-save-text").textContent=i?"Save":"Add entry";const b=d.querySelector(".cex-fields");for(const y of o){if(!ve(f[y.name]))continue;const $=document.createElement("div");$.className="cex-files-field";const T=document.createElement("span");T.textContent=y.label||y.name,$.append(T,He(f[y.name])),b.before($)}F.create(Ot(s,n?.columns||2),e?.data||{},{layout:n?.layout||"stacked",columns:n?.columns||2,showSubmitButton:!1}).renderTo(b),s.forEach(y=>{if(y.type!=="date"||!y.name)return;const $=b.querySelector(`[name="${CSS.escape(y.name)}"]`);$&&$.type!=="date"&&($.type="date")}),e?.data&&Je(b,s,e.data),i&&e.meta?.createdAt&&(d.querySelector(".cex-when-line").textContent=`Created ${_(e.meta.createdAt)}${e.meta.updatedAt?`, last changed ${_(e.meta.updatedAt)}`:""}${e.meta.source?` \xB7 via ${e.meta.source}`:""}.`),h.element.appendChild(d);const ut=_e(ie(b,s));t&&Je(b,s,t);const me=()=>_e(ie(b,s))!==ut,pt=d.querySelector(".cex-dirty"),he=()=>{pt.hidden=!me()};b.addEventListener("input",he),b.addEventListener("change",he),he();let ye=!1;async function Re(){if(ye)return;document.activeElement?.dispatchEvent?.(new Event("change",{bubbles:!0}));const y={...i?e.data:{},...ie(b,s),...f};ye=!0;const $=d.querySelector('[data-act="save"]');$.disabled=!0;try{if(i){const T=await k.collections.updateEntry(a,e.id,y);r.value=r.peek().map(Ue=>Ue.id===e.id?T:Ue),E.toast("Entry saved.",{type:"success"})}else{const T=await k.collections.createEntry(a,y);r.value=[T,...r.peek()],x.value=x.peek()+1,P("#/collections"),E.toast("Entry added.",{type:"success"})}try{S.remove?S.remove(B(a)):S.set(B(a),null)}catch{}h.close(!0)}catch(T){E.toast(T.message||"Not saved.",{type:"error"})}finally{ye=!1,$.disabled=!1}}d.querySelector('[data-act="save"]').addEventListener("click",Re),d.querySelector('[data-act="cancel"]').addEventListener("click",()=>h.close()),d.addEventListener("keydown",y=>{(y.ctrlKey||y.metaKey)&&(y.key==="Enter"||y.key==="s")&&(y.preventDefault(),Re())});const Fe={id:e?.id??null,dirty:me,values:()=>wt(ie(b,s),s)};O=Fe,ne(h,()=>{O===Fe&&(O=null)}),$e(h,me,"Discard the changes you have not saved?"),I.scan(d),h.open(),b.querySelector("input, select, textarea")?.focus()}function ot(e){const t=E.slideover({title:U(W(e)),size:"md",position:"right"}),n=le(`
|
|
19
19
|
<div class="cex-form">
|
|
20
20
|
<dl class="cex-detail"></dl>
|
|
21
21
|
<div class="cex-meta"></div>
|
|
@@ -47,4 +47,4 @@ import{wirePrivateLink as ft}from"/admin/js/lib/private-files.js";import{api as
|
|
|
47
47
|
<button type="button" class="btn btn-ghost" data-fmt="json"><span data-icon="download" data-icon-size="14"></span> Export as JSON</button>
|
|
48
48
|
<button type="button" class="btn btn-ghost" data-fmt="csv"><span data-icon="download" data-icon-size="14"></span> Export as CSV</button>
|
|
49
49
|
</div>
|
|
50
|
-
</div>`);t.querySelectorAll("[data-fmt]").forEach(n=>n.addEventListener("click",async()=>{const o=n.dataset.fmt;try{const s=await fetch(`/api/collections/${encodeURIComponent(a)}/export?format=${o}`,{headers:{Authorization:`Bearer ${S.get("auth_token")||""}`}});if(!s.ok)throw new Error(`${s.status}`);const f=await s.blob(),i=document.createElement("a");i.href=URL.createObjectURL(f),i.download=`${a}-entries.${o}`,document.body.appendChild(i),i.click(),i.remove(),setTimeout(()=>URL.revokeObjectURL(i.href),1e3),e.close(!0)}catch(s){E.toast(`Export failed (${s.message}).`,{type:"error"})}})),e.element.appendChild(t),ne(e),I.scan(t),e.open()}function it(e,t){const n=J(e.dataset.id);if(!n)return[];const o=t?.event?.target?.closest?.("td[data-col]"),s=o?de.peek()[Number(o.dataset.col)]:null,f=Ee(n.id),i=g.peek().includes(n.id),h=s?Ct(s,n.data?.[s.name]):[];return[{header:W(n)},{label:"Edit\u2026",icon:"edit",action:()=>z(n)},{label:"See all of it\u2026",icon:"eye",action:()=>ot(n)},{label:"Duplicate",icon:"copy",action:()=>at(n)},{label:"Copy id",icon:"hash",action:()=>we(n.id)},{label:i?"Deselect":"Select",icon:"check",action:()=>ue(n.id)},...f.length?[{type:"divider"},...f.map(d=>({label:`${d.trigger?.label||d.title||d.slug}\u2026`,icon:d.trigger?.icon||"zap",disabled:L.peek(),action:()=>st(d,n)}))]:[],...s?[{type:"divider"},{label:`Filter by ${s.label||s.name}`,icon:"filter",submenu:[...h.map(d=>({label:d.label,action:()=>Se(s,d.op,d.value)})),{label:`${s.label||s.name} contains\u2026`,action:async()=>{const d=await E.prompt(`Show entries whose ${U(s.label||s.name)} contains`,{inputPlaceholder:"text"});d&&String(d).trim()&&Se(s,"contains",String(d).trim())}}]}]:[],...w.peek().length?[{label:`Clear filters (${w.peek().length})`,icon:"x",action:()=>{w.value=[]}}]:[],{type:"divider"},{label:"Delete\u2026",icon:"trash",danger:!0,action:()=>xe(n)}]}const q=m.querySelector(".cex-rows"),G=m.querySelector(".cex-head"),fe=m.querySelector(".cex-chips-list");fe.innerHTML=
|
|
50
|
+
</div>`);t.querySelectorAll("[data-fmt]").forEach(n=>n.addEventListener("click",async()=>{const o=n.dataset.fmt;try{const s=await fetch(`/api/collections/${encodeURIComponent(a)}/export?format=${o}`,{headers:{Authorization:`Bearer ${S.get("auth_token")||""}`}});if(!s.ok)throw new Error(`${s.status}`);const f=await s.blob(),i=document.createElement("a");i.href=URL.createObjectURL(f),i.download=`${a}-entries.${o}`,document.body.appendChild(i),i.click(),i.remove(),setTimeout(()=>URL.revokeObjectURL(i.href),1e3),e.close(!0)}catch(s){E.toast(`Export failed (${s.message}).`,{type:"error"})}})),e.element.appendChild(t),ne(e),I.scan(t),e.open()}function it(e,t){const n=J(e.dataset.id);if(!n)return[];const o=t?.event?.target?.closest?.("td[data-col]"),s=o?de.peek()[Number(o.dataset.col)]:null,f=Ee(n.id),i=g.peek().includes(n.id),h=s?Ct(s,n.data?.[s.name]):[];return[{header:W(n)},{label:"Edit\u2026",icon:"edit",action:()=>z(n)},{label:"See all of it\u2026",icon:"eye",action:()=>ot(n)},{label:"Duplicate",icon:"copy",action:()=>at(n)},{label:"Copy id",icon:"hash",action:()=>we(n.id)},{label:i?"Deselect":"Select",icon:"check",action:()=>ue(n.id)},...f.length?[{type:"divider"},...f.map(d=>({label:`${d.trigger?.label||d.title||d.slug}\u2026`,icon:d.trigger?.icon||"zap",disabled:L.peek(),action:()=>st(d,n)}))]:[],...s?[{type:"divider"},{label:`Filter by ${s.label||s.name}`,icon:"filter",submenu:[...h.map(d=>({label:d.label,action:()=>Se(s,d.op,d.value)})),{label:`${s.label||s.name} contains\u2026`,action:async()=>{const d=await E.prompt(`Show entries whose ${U(s.label||s.name)} contains`,{inputPlaceholder:"text"});d&&String(d).trim()&&Se(s,"contains",String(d).trim())}}]}]:[],...w.peek().length?[{label:`Clear filters (${w.peek().length})`,icon:"x",action:()=>{w.value=[]}}]:[],{type:"divider"},{label:"Delete\u2026",icon:"trash",danger:!0,action:()=>xe(n)}]}const q=m.querySelector(".cex-rows"),G=m.querySelector(".cex-head"),fe=m.querySelector(".cex-chips-list");fe.innerHTML=Nt;const ae=yt(m.querySelector(".dm-loading-slot"),ht.table);try{u.value=await k.collections.get(a)}catch(e){H.value=`Could not load the collection: ${e.message||e}`}if(!l()){ae.done();return}if(!u.peek()&&(await ae.done(),!H.peek())){E.toast("Collection not found.",{type:"error"}),R.navigate("/collections");return}const Ae=de.peek();q.innerHTML=It(Ae.length),G.replaceChildren();const se=(e,t)=>{const n=document.createElement("th");return e&&(n.className=e),t&&n.append(t),G.appendChild(n),n},A=document.createElement("input");A.type="checkbox",A.title="Select every entry shown",A.setAttribute("aria-label","Select every entry shown"),se("cex-check",A);const Me=(e,t)=>{const n=document.createElement("button");return n.type="button",n.dataset.sort=e,n.append(document.createTextNode(t),Object.assign(document.createElement("span"),{className:"cex-sort"})),n};Ae.forEach(e=>se("",Me(e.name,e.label||e.name))),se("cex-when",Me("created","Created")),se("cex-tools"),c(M.effect(()=>{const e=Z.value;G.querySelectorAll("[data-sort]").forEach(t=>{t.querySelector(".cex-sort").textContent=t.dataset.sort===e.key?e.dir==="asc"?"\u25B2":"\u25BC":"",t.parentElement.setAttribute("aria-sort",t.dataset.sort===e.key?e.dir==="asc"?"ascending":"descending":"none")})})),c(M.effect(()=>{const e=D.value.map(n=>n.id),t=new Set(g.value);A.checked=e.length>0&&e.every(n=>t.has(n)),A.indeterminate=!A.checked&&e.some(n=>t.has(n))}));const Le=e=>{const t=e.target.closest("[data-sort]");if(!t)return;const n=Z.peek();Z.value={key:t.dataset.sort,dir:n.key===t.dataset.sort&&n.dir==="asc"?"desc":"asc"}};G.addEventListener("click",Le),A.addEventListener("change",()=>{const e=D.peek().map(t=>t.id);g.value=A.checked?[...new Set([...g.peek(),...e])]:g.peek().filter(t=>!e.includes(t))}),c(()=>G.removeEventListener("click",Le));const rt=M.applyBindings(Ye,m,{methods:{clearSelection:()=>{g.value=[]},deleteSelected:()=>tt(),clearAll:()=>nt(),clearFilters:()=>{w.value=[]},showMore:()=>{D.peek().length>N.peek()?N.value=N.peek()+X:Ze()}}});c(()=>rt.dispose()),c(ze(m,{position:"bottom"})),c(M.effect(()=>{re.value,w.value,N.value=X}));const qe=e=>{const t=e.target.closest("button[data-idx]");if(!t)return;const n=Number(t.dataset.idx);w.value=w.peek().filter((o,s)=>s!==n)};fe.addEventListener("click",qe),c(()=>fe.removeEventListener("click",qe));const dt=E.contextMenu(q,{cursor:"glyph",match:".cex-row",inherit:!1,density:"compact",items:(e,t)=>it(e,t)});c(()=>dt?.destroy?.());const Te=e=>{const t=e.target.closest(".cex-row");if(!t)return;if(e.target.closest(".cex-kebab, .cex-run")){je(e.target.closest(".cex-kebab, .cex-run"));return}if(e.target.closest(".cex-check"))return;const n=J(t.dataset.id);n&&z(n)},Ne=e=>{if(!e.target.matches(".cex-sel"))return;const t=e.target.closest(".cex-row");t&&ue(t.dataset.id)},Ie=e=>{const t=e.target.closest(".cex-row");if(!t||e.target!==t)return;const n=J(t.dataset.id);n&&(e.key==="F10"&&e.shiftKey?(e.preventDefault(),je(t)):e.key==="Enter"?(e.preventDefault(),z(n)):e.key===" "?(e.preventDefault(),ue(n.id)):e.key==="Delete"&&(e.preventDefault(),xe(n)))};q.addEventListener("click",Te),q.addEventListener("change",Ne),q.addEventListener("keydown",Ie),c(()=>{q.removeEventListener("click",Te),q.removeEventListener("change",Ne),q.removeEventListener("keydown",Ie)});const De=u.peek(),oe=p.get(0).querySelector(".dm-plugin-banner-name")?.querySelector(".dm-plugin-banner-sep");if(oe&&De?.title){for(;oe.nextSibling;)oe.nextSibling.remove();oe.after(document.createTextNode(De.title))}j(p,{id:"entries-back",icon:"arrow-left",title:"All collections",onClick:()=>{location.hash="#/collections"}}),j(p,{id:"entries-fields",icon:"edit-3",title:"Edit its fields and settings",onClick:()=>{location.hash=`#/collections/edit/${encodeURIComponent(a)}`}}),At(a)&&j(p,{id:"entries-form",icon:"layout",title:"Open its form",onClick:()=>{location.hash=`#/forms/edit/${encodeURIComponent(a)}`}}),j(p,{id:"entries-export",icon:"download",title:"Export",onClick:()=>lt()}),j(p,{id:"entries-import",icon:"upload",title:"Import",onClick:()=>ct()}),j(p,{id:"entries-add",icon:"plus",title:"Add entry",onClick:()=>z(null)});const Oe=e=>{O?.dirty()&&(e.preventDefault(),e.returnValue="")};if(window.addEventListener("beforeunload",Oe),c(()=>window.removeEventListener("beforeunload",Oe)),c(()=>{if(O?.dirty())try{S.set(B(a),{id:O.id,values:O.values(),at:new Date().toISOString()})}catch{}Ce=!0,[...pe].forEach(e=>{try{e.close(!0)}catch{}})}),I.scan(m),!u.peek()){Y.value=!1;return}if(await Qe(),!l()){ae.done();return}if(await K({pending:ae}),!l())return;let C=null;try{C=S.get(B(a))}catch{}if(C?.values){try{S.remove?S.remove(B(a)):S.set(B(a),null)}catch{}let e=C.id?J(C.id):null;if(C.id&&!e&&(e=await k.collections.getEntry(a,C.id).catch(()=>null)),!l()||C.id&&!e)return;const t=e?`your changes to \u201C${U(W(e))}\u201D`:"a new entry",n=e?.meta?.updatedAt&&C.at&&e.meta.updatedAt>C.at?" It has been changed since - check before saving.":"";await E.confirm(`You left ${t} unsaved.${n} Pick up where you left off?`)&&l()&&z(e,C.values)}}};
|