domma-cms 1.30.1 → 1.32.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.
Files changed (50) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/CLAUDE.md +36 -1
  3. package/admin/js/api.js +1 -1
  4. package/admin/js/lib/block-packs.js +26 -0
  5. package/admin/js/lib/block-tags.js +6 -1
  6. package/admin/js/lib/blocks-arrange.js +1 -1
  7. package/admin/js/lib/collection-editor-arrange.js +1 -1
  8. package/admin/js/lib/collection-entries-arrange.js +1 -1
  9. package/admin/js/lib/collections-arrange.js +1 -1
  10. package/admin/js/lib/list-tags-arrange.js +1 -1
  11. package/admin/js/lib/list-tags.js +9 -7
  12. package/admin/js/lib/pages-arrange.js +1 -1
  13. package/admin/js/lib/shortcode-context-menu.js +1 -1
  14. package/admin/js/lib/shortcode-form.js +7 -4
  15. package/admin/js/templates/blocks.html +5 -3
  16. package/admin/js/templates/collections.html +12 -2
  17. package/admin/js/templates/docs/usage-blocks.html +28 -1
  18. package/admin/js/templates/pages.html +5 -3
  19. package/admin/js/views/blocks.js +5 -4
  20. package/admin/js/views/collection-editor.js +10 -4
  21. package/admin/js/views/collection-entries.js +2 -2
  22. package/admin/js/views/collections.js +6 -5
  23. package/admin/js/views/page-editor.js +1 -1
  24. package/admin/js/views/pages.js +4 -4
  25. package/docs/DommaFeatures.md +156 -5
  26. package/docs/api-reference.md +8 -6
  27. package/docs/markdown-shortcodes.md +22 -1
  28. package/docs/starter-blocks.md +70 -1
  29. package/package.json +1 -1
  30. package/public/css/site.css +1 -1
  31. package/public/js/collection-browser.js +1 -1
  32. package/server/blocks/catalog.json +6 -0
  33. package/server/blocks/domma-block-cushion-card.css +30 -0
  34. package/server/blocks/domma-block-cushion-card.html +11 -0
  35. package/server/blocks/domma-block-cushion-card.meta.json +7 -0
  36. package/server/routes/api/block-packs.js +55 -0
  37. package/server/routes/api/blocks.js +16 -2
  38. package/server/routes/api/collections.js +9 -1
  39. package/server/routes/api/list-tags.js +35 -10
  40. package/server/routes/api/pages.js +16 -2
  41. package/server/services/block-pack-assets.js +6 -0
  42. package/server/services/block-packs.js +291 -0
  43. package/server/services/block-slots.js +43 -0
  44. package/server/services/block-write-lock.js +44 -0
  45. package/server/services/blocks.js +18 -3
  46. package/server/services/collections.js +6 -0
  47. package/server/services/listTags.js +243 -47
  48. package/server/services/markdown.js +105 -8
  49. package/server/services/starter-block-packs.js +22 -0
  50. package/server/templates/page.html +2 -2
package/CHANGELOG.md CHANGED
@@ -1,5 +1,19 @@
1
1
  # Changelog
2
2
 
3
+ ## [1.32.0] - 2026-11-03
4
+
5
+ - **Block packs.** Blocks > the package action: make a versioned pack from chosen blocks (with their pictures, schema 2), export it as a `.dmblockpack.json` file, import one, and install it after a preview that lists every block it adds or changes. A block edited here since a pack put it there, or one of the same name the pack did not make, stops the install rather than being overwritten. Each install is kept, so the last one can be rolled back while nothing has been edited since. Two starter packs (Domma Base Block Pack, Domma cards) come with every site. The Manager can preview and install a pack on chosen sites.
6
+ - **Slots in Custom Blocks.** A block template can declare `<slot>fallback</slot>` and `<slot name="footer"></slot>`, filled from a paired call: `[my-block heading="…"]body[slot name="footer"]…[/slot][/my-block]` (or `[block template="…"]…[/block]`). Slot content goes through the whole page pipeline - Markdown, shortcodes, other blocks - and collection values stay data. Self-closing calls use the fallbacks; at most 24 levels and 500 expansions a page. The page editor's Add block and the shortcode form offer a field per slot.
7
+ - **Cushion card**, a new starter block: a soft rim around an inset panel, with a heading, an icon, a body slot and a footer slot.
8
+
9
+ ## [1.31.0] - 2026-11-02
10
+
11
+ - **Collections can be tagged, like Pages and Blocks.** Right-click a collection to add or remove a tag, pick which tag to show with the new cog in the banner, and add, rename or delete tags there. A collection's tags are kept in `config/list-tags.json`, not in its schema, so built-in collections can be tagged too and nothing is lost when presets are reseeded; deleting a collection takes its tags with it.
12
+ - **Everything a Tool owns wears that Tool's tag.** A plugin's collections, blocks and pages show its name (with a package icon) as a tag without anyone adding it, and Notes, Todo and Contacts tag their own collections. Tool tags filter and count like any other, but cannot be removed, renamed or deleted, and no hand-made tag can take a Tool's name. "No tag" no longer shows an item that only has a Tool tag.
13
+ - **The tag you pick to show is the same on every list.** Choosing a tag on Collections keeps it chosen on Blocks and Pages until you clear it (each list's old choice is carried over once). A list with nothing wearing that tag now says so - "No blocks tagged "Scraper"." - with a Clear the tag filter button right there, instead of quietly dropping the filter.
14
+ - **Show in lists** on a collection field: switched off, the field is still stored, in the entry form, the API and the admin's export, but it is not a column in the entries list, and a `[collection]` display that names no fields leaves it out - including from that display's filter, search and download (`fields=""` can still name it). Fields carry it as `listHidden: true`.
15
+ - **Searchable and sortable collections use the full width again.** A `[collection]` or `[view]` with `searchable`, `sortable` or `paginate` but no `filterable` drew its rows in a column about 220px wide, because the hidden filter rail still held the first grid column. The rows now take the whole width; with filters, the rail sits beside them as before.
16
+
3
17
  ## [1.30.1] - 2026-11-02
4
18
 
5
19
  - Mail: Domma Mail core 0.20.0. A mailbox can hold 100 filing rules, up from 50, so a converted Sieve script has room. Conditions and actions per rule (10) and groups (20) are unchanged.
package/CLAUDE.md CHANGED
@@ -495,7 +495,9 @@ restarting) mid-run - keep that file's name and meaning.
495
495
  `#site-footer` - on BOTH render paths (`footerBlocksHtml`). site.js lifts that node out before `$footer.html()` (which
496
496
  would wipe and re-sanitise it) and prepends it back. Public page cache entries carry `block:<name>` for each footer
497
497
  block (`footerBlockCacheTags()` - routes/public.js and the docs pages), so saving one reaches cached pages. A block
498
- template's [collection]/[view]/expiry shortcodes never run (those stages precede [block]), so names are all it depends on.
498
+ template's [collection]/[view]/expiry shortcodes never run (those stages precede [block]), so names are all it depends on. Exception: a template with `<slot>`s is
499
+ expanded BEFORE those stages (processSlottedBlocks), so its markup and slot content do run them; its slot content's tags
500
+ join the page's, but a footer block's cache tags are still its name only.
499
501
 
500
502
  ## Site search
501
503
 
@@ -627,6 +629,39 @@ version gave it `mdx-grid`, and the tile template went into the slot), and parts
627
629
  render before the bindings apply need a static `hidden` too, or they show unbound beside the skeleton.
628
630
  Keep `E.loader` for work in progress (a save, an upload), where there is no shape to draw.
629
631
 
632
+ ## List tags (Pages, Blocks, Collections)
633
+
634
+ Admin-only labels: `server/services/listTags.js` + `routes/api/list-tags.js`, admin `lib/list-tags.js` (slideover,
635
+ shared filter) and `lib/list-tags-arrange.js` (pure). Pages keep frontmatter `adminTags`, blocks `meta.adminTags`;
636
+ **collections keep theirs in `config/list-tags.json` `collectionTags: {slug: [...]}`, never in schema.json** (seedAll()
637
+ rewrites presets; system collections are fixed) - `deleteCollection()` drops the entry, a stale one is ignored, and
638
+ `GET /api/collections` puts them on each row. The collections kind sits under the `collections` permission; pages
639
+ and blocks under `pages`.
640
+ - **Tool tags are derived, never stored**: owner = collection `schema.plugin` (or `PRESET_TOOL_COLLECTIONS` for
641
+ notes/todo/contacts - kept in step on both sides), block `meta.plugin`, page frontmatter `plugin`; name = manifest
642
+ `displayName` / `CORE_TOOLS` (`toolNames()`, cached 30 s), else the title-cased slug. GET returns them with
643
+ `tool: true` plus `tools: {slug: name}`. They count for filters (an item with only a Tool tag is not "No tag"), are
644
+ never in Remove tag, cannot be renamed or deleted, and a manual tag may not take a Tool name (server refuses, 400).
645
+ - **One filter for all three lists**: `SHARED_TAG_KEY` (`lists.tag`) via `sharedTagFilter()`; old per-list values
646
+ (`blocks.tag`, `pages.settings`.tag) are carried over once. A chosen tag no item wears is kept - the list shows
647
+ "No blocks tagged …" with a Clear button - never reset.
648
+
649
+ ## Block slots and block packs
650
+
651
+ - **Slots** (`server/services/block-slots.js`, `processSlottedBlocks()` in markdown.js): a template declaring
652
+ `<slot>`/`<slot name="x">` is expanded first, from a paired call's body; each slot is rendered once through
653
+ `parseMarkdown` and held behind a nonce token until the outer pipeline is done (so code examples and entry data in it
654
+ stay inert). `pairedRanges()` pairs a close with the NEAREST open of its name, so a stray `[my-card]` never hides a
655
+ later call. Past 24 levels or 500 expansions a block renders nothing - never throw out of parseMarkdown. A paired call
656
+ on a block without slots (or a missing one) keeps its body. Replacements use a function (`$&` in content is text).
657
+ - **Packs** (`services/block-packs.js`, `routes/api/block-packs.js`, admin `lib/block-packs.js`; data in
658
+ `content/block-packs/`): published versions are immutable; install = preview token + conflict check, under
659
+ `withBlockWriteLock` (cross-process: the Manager writes child sites). Blocks the site already had are `adopted` and
660
+ only ever let go (`release`), never deleted. `pending/<id>.json` marks an install in progress; preview, install and
661
+ rollback undo an interrupted one from its snapshot first. Asset packs need `media.create`. The starter `domma-cards`
662
+ pack is built from server/blocks on each site, so changing those five files means bumping `DOMMA_CARDS.version`
663
+ (a test holds the fingerprint).
664
+
630
665
  ## Key Gotchas
631
666
 
632
667
  1. **Structural menu items**: `{type:'separator'}`, `{type:'spacer', size}` and `{type:'theme-switcher'}` carry no text/url - every renderer (menuRender, site.js navbar+footer, sidebar-renderer, menu-editor flatten/nest) needs a branch, and anything zipping items against rendered DOM must skip them or the indices shift. Domma's navbar has no spacer concept, so site.js strips them pre-render and re-inserts `<li>`s afterwards **against a snapshot** of the children, not the live HTMLCollection. `size: 'flex'` needs a flex parent, so the renderers stamp `dm-menu--has-flex-spacer` / `dm-admin-sidebar--has-flex-spacer` rather than making every list flex.
package/admin/js/api.js CHANGED
@@ -1 +1 @@
1
- import{claimDrafts as $}from"./lib/draft-owner.js";import{loginHashFor as O}from"./lib/login-arrange.js";const m="/api";function a(){return S.get("auth_token")}function u(){return S.get("auth_refresh_token")}function f(e){S.set("auth_token",e)}function y(){S.remove("auth_token"),S.remove("auth_refresh_token"),S.remove("auth_user")}async function g(){const e=u();if(!e)throw new Error("No refresh token");const o=await fetch(`${m}/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e})});if(!o.ok)throw y(),sendToLogin({expired:!0}),new Error("Token refresh failed");const{token:n}=await o.json();return f(n),n}async function t(e,o={}){let n=a();const i=r=>({...o.body!==void 0?{"Content-Type":"application/json"}:{},...o.headers,...r?{Authorization:`Bearer ${r}`}:{}});let s=await fetch(`${m}${e}`,{...o,headers:i(n)});if(s.status===401&&u())try{n=await g(),s=await fetch(`${m}${e}`,{...o,headers:i(n)})}catch{return}if(!s.ok){const r=await s.json().catch(()=>({error:"Request failed"})),d=new Error(r.error||r.message||`HTTP ${s.status}`);throw Array.isArray(r.validation)&&(d.validation=r.validation),d.status=s.status,d.body=r,d}return s.status===204?null:s.json()}async function b(e,o){const n=a(),i=n?{Authorization:`Bearer ${n}`}:{},s=await fetch(`${m}${e}`,{method:"POST",headers:i,body:o});if(!s.ok){const r=await s.json().catch(()=>({error:"Upload failed"}));throw new Error(r.error||r.message||`HTTP ${s.status}`)}return s.json()}export const api={auth:{setupStatus:()=>t("/auth/setup-status",{method:"GET"}),setup:e=>t("/auth/setup",{method:"POST",body:JSON.stringify(e)}),login:e=>t("/auth/login",{method:"POST",body:JSON.stringify(e)}),verifyLogin:e=>t("/auth/login/verify",{method:"POST",body:JSON.stringify(e)}),me:()=>t("/auth/me",{method:"GET"}),updateMe:e=>t("/auth/me",{method:"PUT",body:JSON.stringify(e)}),refresh:e=>t("/auth/refresh",{method:"POST",body:JSON.stringify({refreshToken:e})}),forgotPassword:e=>t("/auth/forgot-password",{method:"POST",body:JSON.stringify({email:e})}),checkReset:(e,o)=>t("/auth/reset-password/check",{method:"POST",body:JSON.stringify({token:e,...o&&{password:o}})}),resetPassword:(e,o)=>t("/auth/reset-password",{method:"POST",body:JSON.stringify({token:e,password:o})})},pages:{list:()=>t("/pages",{method:"GET"}),get:e=>t(`/pages${e}`,{method:"GET"}),create:e=>t("/pages",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/pages${e}`,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(`/pages${e}`,{method:"DELETE"}),preview:e=>t("/pages/preview",{method:"POST",body:JSON.stringify({markdown:e})}),previewFull:(e,o,n,i)=>t("/pages/preview/full",{method:"POST",body:JSON.stringify({urlPath:e,frontmatter:o,body:n,...i&&Object.keys(i).length?{blocks:i}:{}})}),previewLinks:{list:e=>t(`/pages/preview-links${e?`?urlPath=${encodeURIComponent(e)}`:""}`,{method:"GET"}).then(o=>o.links||[]),create:(e,o,n)=>t("/pages/preview-links",{method:"POST",body:JSON.stringify({urlPath:e,expiresIn:o,label:n})}),revoke:e=>t(`/pages/preview-links/${e}`,{method:"DELETE"})},tags:()=>t("/pages/tags",{method:"GET"}).then(e=>e.tags||[]),dommaCatalogue:()=>t("/pages/_domma-catalogue",{method:"GET"}).catch(()=>null)},listTags:{list:e=>t(`/list-tags/${e}`,{method:"GET"}).then(o=>o.tags||[]),add:(e,o)=>t(`/list-tags/${e}`,{method:"POST",body:JSON.stringify({name:o})}),changeItem:(e,o,n)=>t(`/list-tags/${e}/item`,{method:"PUT",body:JSON.stringify({id:o,...n})}).then(i=>i.tags||[]),rename:(e,o,n)=>t(`/list-tags/${e}/rename`,{method:"POST",body:JSON.stringify({from:o,to:n})}),remove:(e,o)=>t(`/list-tags/${e}/delete`,{method:"POST",body:JSON.stringify({name:o})})},settings:{get:()=>t("/settings",{method:"GET"}),save:e=>t("/settings",{method:"PUT",body:JSON.stringify(e)}),getCustomCss:()=>t("/settings/custom-css",{method:"GET"}),saveCustomCss:e=>t("/settings/custom-css",{method:"PUT",body:JSON.stringify({css:e})})},theme:{get:()=>t("/theme",{method:"GET"}),save:e=>t("/theme",{method:"PUT",body:JSON.stringify(e)}),catalog:()=>t("/theme/catalog",{method:"GET"}),admin:e=>t(`/theme/admin${e?`?id=${encodeURIComponent(e)}`:""}`,{method:"GET"}),themeTokens:e=>t(`/theme/themes/${encodeURIComponent(e)}`,{method:"GET"}),compile:e=>t("/theme/compile",{method:"POST",body:JSON.stringify(e)})},navigation:{get:()=>t("/navigation",{method:"GET"}),save:e=>t("/navigation",{method:"PUT",body:JSON.stringify(e)})},menus:{list:()=>t("/menus",{method:"GET"}),get:e=>t(`/menus/${encodeURIComponent(e)}`,{method:"GET"}),create:e=>t("/menus",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/menus/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(o)}),remove:e=>t(`/menus/${encodeURIComponent(e)}`,{method:"DELETE"}),duplicate:e=>t(`/menus/${encodeURIComponent(e)}/duplicate`,{method:"POST"})},contextMenus:{list:()=>t("/context-menus",{method:"GET"}),get:e=>t(`/context-menus/${encodeURIComponent(e)}`,{method:"GET"}),create:e=>t("/context-menus",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/context-menus/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(o)}),remove:e=>t(`/context-menus/${encodeURIComponent(e)}`,{method:"DELETE"}),duplicate:e=>t(`/context-menus/${encodeURIComponent(e)}/duplicate`,{method:"POST"}),actionTypes:()=>t("/context-menus/action-types",{method:"GET"})},menuLocations:{get:()=>t("/menu-locations",{method:"GET"}),save:e=>t("/menu-locations",{method:"PUT",body:JSON.stringify(e)}),registry:()=>t("/menu-locations/registry",{method:"GET"})},projects:{list:()=>t("/projects",{method:"GET"}),listWithCounts:()=>t("/projects?counts=1",{method:"GET"}),get:e=>t(`/projects/${encodeURIComponent(e)}`,{method:"GET"}),create:e=>t("/projects",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/projects/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(o)}),remove:e=>t(`/projects/${encodeURIComponent(e)}`,{method:"DELETE"}),artefacts:e=>t(`/projects/${encodeURIComponent(e)}/artefacts`,{method:"GET"}),untagAll:e=>t(`/projects/${encodeURIComponent(e)}/untag-all`,{method:"POST"}),removeContents:(e,o)=>t(`/projects/${encodeURIComponent(e)}/remove-contents`,{method:"POST",body:JSON.stringify({confirm:o})})},apiTokens:{list:()=>t("/api-tokens",{method:"GET"}),create:e=>t("/api-tokens",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/api-tokens/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(o)}),revoke:e=>t(`/api-tokens/${encodeURIComponent(e)}`,{method:"DELETE"})},apiEndpoints:{list:()=>t("/api-endpoints",{method:"GET"}),get:e=>t(`/api-endpoints/${encodeURIComponent(e)}`,{method:"GET"}),create:e=>t("/api-endpoints",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/api-endpoints/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(o)}),remove:e=>t(`/api-endpoints/${encodeURIComponent(e)}`,{method:"DELETE"})},layouts:{get:()=>t("/layouts",{method:"GET"}),save:e=>t("/layouts",{method:"PUT",body:JSON.stringify(e)}),create:e=>t("/layouts",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/layouts/${e}`,{method:"PUT",body:JSON.stringify(o)}),remove:e=>t(`/layouts/${e}`,{method:"DELETE"}),getOptions:()=>t("/layouts/options",{method:"GET"}),saveOptions:e=>t("/layouts/options",{method:"PUT",body:JSON.stringify(e)})},media:{list:()=>t("/media",{method:"GET"}),upload:e=>b("/media",e),limits:()=>t("/media/_limits",{method:"GET"}),delete:e=>t(`/media/${encodeURIComponent(e)}`,{method:"DELETE"}),rename:(e,o)=>t(`/media/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify({newName:o})}),info:e=>t(`/media/${encodeURIComponent(e)}/info`,{method:"GET"}),transform:(e,o)=>t(`/media/${encodeURIComponent(e)}/transform`,{method:"POST",body:JSON.stringify(o)})},users:{list:()=>t("/users",{method:"GET"}),get:e=>t(`/users/${e}`,{method:"GET"}),create:e=>t("/users",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/users/${e}`,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(`/users/${e}`,{method:"DELETE"}),passwordReset:(e,o)=>t(`/users/${encodeURIComponent(e)}/password-reset`,{method:"POST",body:JSON.stringify({via:o})}),cancelPasswordReset:e=>t(`/users/${encodeURIComponent(e)}/password-reset`,{method:"DELETE"})},tools:{list:()=>t("/tools",{method:"GET"}),update:(e,o)=>t(`/tools/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(o)})},plugins:{list:()=>t("/plugins",{method:"GET"}),scaffold:e=>t("/plugins/scaffold",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/plugins/${e}`,{method:"PUT",body:JSON.stringify(o)}),files:e=>t(`/plugins/${e}/files`,{method:"GET"}),readFile:(e,o)=>t(`/plugins/${e}/file?path=${encodeURIComponent(o)}`,{method:"GET"}),writeFile:(e,o,n)=>t(`/plugins/${e}/file`,{method:"PUT",body:JSON.stringify({path:o,content:n})}),deleteFile:(e,o)=>t(`/plugins/${e}/file?path=${encodeURIComponent(o)}`,{method:"DELETE"}),restart:()=>t("/plugins/restart",{method:"POST"}),policy:()=>t("/plugins/_policy",{method:"GET"}),adminConfig:()=>t("/plugins/admin-config",{method:"GET"}),async exportBundle(e,{includeData:o=!1}={}){const n=a(),i=o?"?includeData=1":"",s=await fetch(`${m}/plugins/${encodeURIComponent(e)}/export${i}`,{headers:n?{Authorization:`Bearer ${n}`}:{}});if(!s.ok){const E=await s.json().catch(()=>({}));throw new Error(E.error||`Export failed (${s.status})`)}const r=s.headers.get("Content-Disposition")||"",d=/filename="([^"]+)"/.exec(r)?.[1],c=await s.blob(),h=URL.createObjectURL(c),l=document.createElement("a");l.href=h,l.download=d||`${e}.dcmsplugin`,document.body.appendChild(l),l.click(),l.remove(),URL.revokeObjectURL(h)},async installFile(e,{confirmUnsigned:o=!1,confirmUpgrade:n=!1,confirmDowngrade:i=!1}={}){const s=new FormData;o&&s.append("confirmUnsigned","true"),n&&s.append("confirmUpgrade","true"),i&&s.append("confirmDowngrade","true"),s.append("file",e);const r=a(),d=await fetch(`${m}/plugins/install-upload`,{method:"POST",headers:r?{Authorization:`Bearer ${r}`}:{},body:s}),c=await d.json().catch(()=>({}));if(d.status===409){const h=new Error(c.error||"Plugin already installed");throw h.code="CONFLICT",h.name=c.name,h.installedVersion=c.installedVersion,h.incomingVersion=c.incomingVersion,h}if(!d.ok)throw new Error(c.error||`Install failed (${d.status})`);return c}},marketplace:{catalogue:()=>t("/plugins/marketplace",{method:"GET"}),install:(e,o,{update:n=!1}={})=>t("/plugins/marketplace/install",{method:"POST",body:JSON.stringify({slug:e,version:o,update:n})}),uninstall:e=>t(`/plugins/marketplace/${encodeURIComponent(e)}`,{method:"DELETE"})},collections:{list:()=>t("/collections",{method:"GET"}),proStatus:()=>t("/collections/pro-status",{method:"GET"}),get:e=>t(`/collections/${e}`,{method:"GET"}),create:e=>t("/collections",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/collections/${e}`,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(`/collections/${e}`,{method:"DELETE"}),listEntries:(e,o={})=>{const n=new URLSearchParams(o).toString();return t(`/collections/${e}/entries${n?"?"+n:""}`,{method:"GET"})},getEntry:(e,o)=>t(`/collections/${e}/entries/${o}`,{method:"GET"}),createEntry:(e,o)=>t(`/collections/${e}/entries`,{method:"POST",body:JSON.stringify({data:o})}),updateEntry:(e,o,n)=>t(`/collections/${e}/entries/${o}`,{method:"PUT",body:JSON.stringify({data:n})}),deleteEntry:(e,o)=>t(`/collections/${e}/entries/${o}`,{method:"DELETE"}),clearEntries:e=>t(`/collections/${e}/entries`,{method:"DELETE"}),import:(e,o)=>t(`/collections/${e}/import`,{method:"POST",body:JSON.stringify({entries:o})}),publicList:(e,o={})=>{const n=new URLSearchParams(o).toString();return t(`/collections/${e}/public${n?"?"+n:""}`,{method:"GET"})},getConnections:()=>t("/collections/connections",{method:"GET"}),saveConnections:e=>t("/collections/connections",{method:"PUT",body:JSON.stringify(e)}),migrateStorage:(e,o)=>t(`/collections/${e}/migrate-storage`,{method:"POST",body:JSON.stringify({storage:o})})},forms:{list:()=>t("/forms",{method:"GET"}),create:e=>t("/forms",{method:"POST",body:JSON.stringify(e)}),get:e=>t(`/forms/${e}`,{method:"GET"}),update:(e,o)=>t(`/forms/${e}`,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(`/forms/${e}`,{method:"DELETE"}),listSubmissions:e=>t(`/forms/${e}/submissions`,{method:"GET"}),clearSubmissions:e=>t(`/forms/${e}/submissions`,{method:"DELETE"}),deleteSubmission:(e,o)=>t(`/forms/${e}/submissions/${o}`,{method:"DELETE"}),testEmail:e=>t("/forms/test-email",{method:"POST",body:JSON.stringify({to:e})})},views:{list:()=>t("/views",{method:"GET"}),get:e=>t(`/views/${e}`,{method:"GET"}),create:e=>t("/views",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/views/${e}`,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(`/views/${e}`,{method:"DELETE"}),execute:(e,o={})=>{const n=new URLSearchParams(o).toString();return t(`/views/${e}/execute${n?"?"+n:""}`,{method:"GET"})},forCollection:e=>t(`/views/collection/${e}`,{method:"GET"})},actions:{list:()=>t("/actions",{method:"GET"}),get:e=>t(`/actions/${e}`,{method:"GET"}),create:e=>t("/actions",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/actions/${e}`,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(`/actions/${e}`,{method:"DELETE"}),execute:(e,o)=>t(`/actions/${e}/execute`,{method:"POST",body:JSON.stringify({entryId:o})}),forCollection:e=>t(`/actions/collection/${e}`,{method:"GET"}),checkAccess:(e,o)=>t(`/actions/${e}/check-access`,{method:"POST",body:JSON.stringify({entryIds:o})})},versions:{list:e=>t(`/versions/list${e}`),get:(e,o)=>t(`/versions/get/${encodeURIComponent(o)}${e}`),create:(e,o)=>t(`/versions/create${e}`,{method:"POST",body:JSON.stringify({label:o})}),restore:(e,o)=>t(`/versions/restore/${encodeURIComponent(o)}${e}`,{method:"POST"}),delete:(e,o)=>t(`/versions/delete/${encodeURIComponent(o)}${e}`,{method:"DELETE"}),bulkDelete:(e,o)=>t(`/versions/bulk-delete${e}`,{method:"POST",body:JSON.stringify({filenames:o})}),prune:(e,o)=>t(`/versions/prune${e}`,{method:"POST",body:JSON.stringify({keep:o})})},blocks:{list:()=>t("/blocks",{method:"GET"}),get:e=>t(`/blocks/${encodeURIComponent(e)}`,{method:"GET"}),put:(e,o)=>t(`/blocks/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(`/blocks/${encodeURIComponent(e)}`,{method:"DELETE"}),async exportBundle(e){const o=a(),n=await fetch(`${m}/blocks/${encodeURIComponent(e)}/export`,{headers:o?{Authorization:`Bearer ${o}`}:{}});if(!n.ok){const d=await n.json().catch(()=>({}));throw new Error(d.error||`Export failed (${n.status})`)}const i=await n.blob(),s=URL.createObjectURL(i),r=document.createElement("a");r.href=s,r.download=`${e}.dmblock.json`,document.body.appendChild(r),r.click(),r.remove(),URL.revokeObjectURL(s)},async importBundle(e,{overwrite:o=!1}={}){const n=await fetch(`${m}/blocks/import`,{method:"POST",headers:{"Content-Type":"application/json",...a()?{Authorization:`Bearer ${a()}`}:{}},body:JSON.stringify({...e,overwrite:o})});if(n.status===409){const i=await n.json().catch(()=>({})),s=new Error(i.error||"Block already exists");throw s.code="CONFLICT",s.name=i.name,s}if(!n.ok){const i=await n.json().catch(()=>({}));throw new Error(i.error||`Import failed (${n.status})`)}return n.json()}},components:{list:()=>t("/components",{method:"GET"}),get:e=>t(`/components/${encodeURIComponent(e)}`,{method:"GET"}),compile:(e,o)=>t("/components/compile",{method:"POST",body:JSON.stringify({name:e,source:o})}),put:(e,o)=>t(`/components/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(`/components/${encodeURIComponent(e)}`,{method:"DELETE"}),async exportBundle(e){const o=a(),n=await fetch(`${m}/components/${encodeURIComponent(e)}/export`,{headers:o?{Authorization:`Bearer ${o}`}:{}});if(!n.ok){const d=await n.json().catch(()=>({}));throw new Error(d.error||`Export failed (${n.status})`)}const i=await n.blob(),s=URL.createObjectURL(i),r=document.createElement("a");r.href=s,r.download=`${e}.dmcomponent.json`,document.body.appendChild(r),r.click(),r.remove(),URL.revokeObjectURL(s)},async importBundle(e,{overwrite:o=!1}={}){const n=await fetch(`${m}/components/import`,{method:"POST",headers:{"Content-Type":"application/json",...a()?{Authorization:`Bearer ${a()}`}:{}},body:JSON.stringify({...e,overwrite:o})});if(n.status===409){const i=await n.json().catch(()=>({})),s=new Error(i.error||"Component already exists");throw s.code="CONFLICT",s.name=i.name,s}if(!n.ok){const i=await n.json().catch(()=>({}));throw new Error(i.error||`Import failed (${n.status})`)}return n.json()}},get:e=>t(e,{method:"GET"}),post:(e,o)=>t(e,{method:"POST",body:JSON.stringify(o)}),put:(e,o)=>t(e,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(e,{method:"DELETE"}),settingsExt:{testEmail:e=>t("/settings/test-email",{method:"POST",body:JSON.stringify({to:e})})},system:{notifications:{list:()=>t("/system/notifications",{method:"GET"}),unreadCount:()=>t("/system/notifications/unread-count",{method:"GET"}),markRead:e=>t(`/system/notifications/${e}/read`,{method:"POST"}),dismiss:e=>t(`/system/notifications/${e}/dismiss`,{method:"POST"}),remove:e=>t(`/system/notifications/${e}`,{method:"DELETE"})}},dashboard:{summary:()=>t("/dashboard/summary",{method:"GET"}),summaryLite:()=>t("/dashboard/summary?lite=1",{method:"GET"})}};export function isAuthenticated(){return!!a()}export function getUser(){return S.get("auth_user")}export function setAuthData({token:e,refreshToken:o,user:n}){e&&f(e),o&&S.set("auth_refresh_token",o),n&&($(n.id),S.set("auth_user",n))}let p=!1,T=!1;export function sendToLogin({expired:e=!1}={}){/^#\/(login|reset-password)(\?|\/|$)/.test(location.hash)||(location.hash=O(location.hash,{expired:e}))}export function logout(){!T&&window.M?.subscribe&&(T=!0,M.subscribe("router:afterChange",({to:e}={})=>{/^\/login(\?|$)/.test(e?.path||"")||(p=!1)})),p=!0,R.navigate("/login")}export function takePendingLogout(){return p?(p=!1,P(),!0):!1}function P(){const e=u();e&&fetch(`${m}/auth/logout`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e})}).catch(()=>{}),y()}export{t as apiRequest,g as refreshAccessToken,a as getToken,y as clearAuth};
1
+ import{claimDrafts as $}from"./lib/draft-owner.js";import{loginHashFor as O}from"./lib/login-arrange.js";const m="/api";function a(){return S.get("auth_token")}function u(){return S.get("auth_refresh_token")}function f(e){S.set("auth_token",e)}function y(){S.remove("auth_token"),S.remove("auth_refresh_token"),S.remove("auth_user")}async function g(){const e=u();if(!e)throw new Error("No refresh token");const o=await fetch(`${m}/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e})});if(!o.ok)throw y(),sendToLogin({expired:!0}),new Error("Token refresh failed");const{token:n}=await o.json();return f(n),n}async function t(e,o={}){let n=a();const i=r=>({...o.body!==void 0?{"Content-Type":"application/json"}:{},...o.headers,...r?{Authorization:`Bearer ${r}`}:{}});let s=await fetch(`${m}${e}`,{...o,headers:i(n)});if(s.status===401&&u())try{n=await g(),s=await fetch(`${m}${e}`,{...o,headers:i(n)})}catch{return}if(!s.ok){const r=await s.json().catch(()=>({error:"Request failed"})),d=new Error(r.error||r.message||`HTTP ${s.status}`);throw Array.isArray(r.validation)&&(d.validation=r.validation),d.status=s.status,d.body=r,d}return s.status===204?null:s.json()}async function b(e,o){const n=a(),i=n?{Authorization:`Bearer ${n}`}:{},s=await fetch(`${m}${e}`,{method:"POST",headers:i,body:o});if(!s.ok){const r=await s.json().catch(()=>({error:"Upload failed"}));throw new Error(r.error||r.message||`HTTP ${s.status}`)}return s.json()}export const api={auth:{setupStatus:()=>t("/auth/setup-status",{method:"GET"}),setup:e=>t("/auth/setup",{method:"POST",body:JSON.stringify(e)}),login:e=>t("/auth/login",{method:"POST",body:JSON.stringify(e)}),verifyLogin:e=>t("/auth/login/verify",{method:"POST",body:JSON.stringify(e)}),me:()=>t("/auth/me",{method:"GET"}),updateMe:e=>t("/auth/me",{method:"PUT",body:JSON.stringify(e)}),refresh:e=>t("/auth/refresh",{method:"POST",body:JSON.stringify({refreshToken:e})}),forgotPassword:e=>t("/auth/forgot-password",{method:"POST",body:JSON.stringify({email:e})}),checkReset:(e,o)=>t("/auth/reset-password/check",{method:"POST",body:JSON.stringify({token:e,...o&&{password:o}})}),resetPassword:(e,o)=>t("/auth/reset-password",{method:"POST",body:JSON.stringify({token:e,password:o})})},pages:{list:()=>t("/pages",{method:"GET"}),get:e=>t(`/pages${e}`,{method:"GET"}),create:e=>t("/pages",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/pages${e}`,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(`/pages${e}`,{method:"DELETE"}),preview:e=>t("/pages/preview",{method:"POST",body:JSON.stringify({markdown:e})}),previewFull:(e,o,n,i)=>t("/pages/preview/full",{method:"POST",body:JSON.stringify({urlPath:e,frontmatter:o,body:n,...i&&Object.keys(i).length?{blocks:i}:{}})}),previewLinks:{list:e=>t(`/pages/preview-links${e?`?urlPath=${encodeURIComponent(e)}`:""}`,{method:"GET"}).then(o=>o.links||[]),create:(e,o,n)=>t("/pages/preview-links",{method:"POST",body:JSON.stringify({urlPath:e,expiresIn:o,label:n})}),revoke:e=>t(`/pages/preview-links/${e}`,{method:"DELETE"})},tags:()=>t("/pages/tags",{method:"GET"}).then(e=>e.tags||[]),dommaCatalogue:()=>t("/pages/_domma-catalogue",{method:"GET"}).catch(()=>null)},listTags:{list:e=>t(`/list-tags/${e}`,{method:"GET"}).then(o=>o.tags||[]),load:e=>t(`/list-tags/${e}`,{method:"GET"}).then(o=>({tags:o.tags||[],tools:o.tools||{}})),add:(e,o)=>t(`/list-tags/${e}`,{method:"POST",body:JSON.stringify({name:o})}),changeItem:(e,o,n)=>t(`/list-tags/${e}/item`,{method:"PUT",body:JSON.stringify({id:o,...n})}).then(i=>i.tags||[]),rename:(e,o,n)=>t(`/list-tags/${e}/rename`,{method:"POST",body:JSON.stringify({from:o,to:n})}),remove:(e,o)=>t(`/list-tags/${e}/delete`,{method:"POST",body:JSON.stringify({name:o})})},settings:{get:()=>t("/settings",{method:"GET"}),save:e=>t("/settings",{method:"PUT",body:JSON.stringify(e)}),getCustomCss:()=>t("/settings/custom-css",{method:"GET"}),saveCustomCss:e=>t("/settings/custom-css",{method:"PUT",body:JSON.stringify({css:e})})},theme:{get:()=>t("/theme",{method:"GET"}),save:e=>t("/theme",{method:"PUT",body:JSON.stringify(e)}),catalog:()=>t("/theme/catalog",{method:"GET"}),admin:e=>t(`/theme/admin${e?`?id=${encodeURIComponent(e)}`:""}`,{method:"GET"}),themeTokens:e=>t(`/theme/themes/${encodeURIComponent(e)}`,{method:"GET"}),compile:e=>t("/theme/compile",{method:"POST",body:JSON.stringify(e)})},navigation:{get:()=>t("/navigation",{method:"GET"}),save:e=>t("/navigation",{method:"PUT",body:JSON.stringify(e)})},menus:{list:()=>t("/menus",{method:"GET"}),get:e=>t(`/menus/${encodeURIComponent(e)}`,{method:"GET"}),create:e=>t("/menus",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/menus/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(o)}),remove:e=>t(`/menus/${encodeURIComponent(e)}`,{method:"DELETE"}),duplicate:e=>t(`/menus/${encodeURIComponent(e)}/duplicate`,{method:"POST"})},contextMenus:{list:()=>t("/context-menus",{method:"GET"}),get:e=>t(`/context-menus/${encodeURIComponent(e)}`,{method:"GET"}),create:e=>t("/context-menus",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/context-menus/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(o)}),remove:e=>t(`/context-menus/${encodeURIComponent(e)}`,{method:"DELETE"}),duplicate:e=>t(`/context-menus/${encodeURIComponent(e)}/duplicate`,{method:"POST"}),actionTypes:()=>t("/context-menus/action-types",{method:"GET"})},menuLocations:{get:()=>t("/menu-locations",{method:"GET"}),save:e=>t("/menu-locations",{method:"PUT",body:JSON.stringify(e)}),registry:()=>t("/menu-locations/registry",{method:"GET"})},projects:{list:()=>t("/projects",{method:"GET"}),listWithCounts:()=>t("/projects?counts=1",{method:"GET"}),get:e=>t(`/projects/${encodeURIComponent(e)}`,{method:"GET"}),create:e=>t("/projects",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/projects/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(o)}),remove:e=>t(`/projects/${encodeURIComponent(e)}`,{method:"DELETE"}),artefacts:e=>t(`/projects/${encodeURIComponent(e)}/artefacts`,{method:"GET"}),untagAll:e=>t(`/projects/${encodeURIComponent(e)}/untag-all`,{method:"POST"}),removeContents:(e,o)=>t(`/projects/${encodeURIComponent(e)}/remove-contents`,{method:"POST",body:JSON.stringify({confirm:o})})},apiTokens:{list:()=>t("/api-tokens",{method:"GET"}),create:e=>t("/api-tokens",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/api-tokens/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(o)}),revoke:e=>t(`/api-tokens/${encodeURIComponent(e)}`,{method:"DELETE"})},apiEndpoints:{list:()=>t("/api-endpoints",{method:"GET"}),get:e=>t(`/api-endpoints/${encodeURIComponent(e)}`,{method:"GET"}),create:e=>t("/api-endpoints",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/api-endpoints/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(o)}),remove:e=>t(`/api-endpoints/${encodeURIComponent(e)}`,{method:"DELETE"})},layouts:{get:()=>t("/layouts",{method:"GET"}),save:e=>t("/layouts",{method:"PUT",body:JSON.stringify(e)}),create:e=>t("/layouts",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/layouts/${e}`,{method:"PUT",body:JSON.stringify(o)}),remove:e=>t(`/layouts/${e}`,{method:"DELETE"}),getOptions:()=>t("/layouts/options",{method:"GET"}),saveOptions:e=>t("/layouts/options",{method:"PUT",body:JSON.stringify(e)})},media:{list:()=>t("/media",{method:"GET"}),upload:e=>b("/media",e),limits:()=>t("/media/_limits",{method:"GET"}),delete:e=>t(`/media/${encodeURIComponent(e)}`,{method:"DELETE"}),rename:(e,o)=>t(`/media/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify({newName:o})}),info:e=>t(`/media/${encodeURIComponent(e)}/info`,{method:"GET"}),transform:(e,o)=>t(`/media/${encodeURIComponent(e)}/transform`,{method:"POST",body:JSON.stringify(o)})},users:{list:()=>t("/users",{method:"GET"}),get:e=>t(`/users/${e}`,{method:"GET"}),create:e=>t("/users",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/users/${e}`,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(`/users/${e}`,{method:"DELETE"}),passwordReset:(e,o)=>t(`/users/${encodeURIComponent(e)}/password-reset`,{method:"POST",body:JSON.stringify({via:o})}),cancelPasswordReset:e=>t(`/users/${encodeURIComponent(e)}/password-reset`,{method:"DELETE"})},tools:{list:()=>t("/tools",{method:"GET"}),update:(e,o)=>t(`/tools/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(o)})},plugins:{list:()=>t("/plugins",{method:"GET"}),scaffold:e=>t("/plugins/scaffold",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/plugins/${e}`,{method:"PUT",body:JSON.stringify(o)}),files:e=>t(`/plugins/${e}/files`,{method:"GET"}),readFile:(e,o)=>t(`/plugins/${e}/file?path=${encodeURIComponent(o)}`,{method:"GET"}),writeFile:(e,o,n)=>t(`/plugins/${e}/file`,{method:"PUT",body:JSON.stringify({path:o,content:n})}),deleteFile:(e,o)=>t(`/plugins/${e}/file?path=${encodeURIComponent(o)}`,{method:"DELETE"}),restart:()=>t("/plugins/restart",{method:"POST"}),policy:()=>t("/plugins/_policy",{method:"GET"}),adminConfig:()=>t("/plugins/admin-config",{method:"GET"}),async exportBundle(e,{includeData:o=!1}={}){const n=a(),i=o?"?includeData=1":"",s=await fetch(`${m}/plugins/${encodeURIComponent(e)}/export${i}`,{headers:n?{Authorization:`Bearer ${n}`}:{}});if(!s.ok){const E=await s.json().catch(()=>({}));throw new Error(E.error||`Export failed (${s.status})`)}const r=s.headers.get("Content-Disposition")||"",d=/filename="([^"]+)"/.exec(r)?.[1],c=await s.blob(),h=URL.createObjectURL(c),l=document.createElement("a");l.href=h,l.download=d||`${e}.dcmsplugin`,document.body.appendChild(l),l.click(),l.remove(),URL.revokeObjectURL(h)},async installFile(e,{confirmUnsigned:o=!1,confirmUpgrade:n=!1,confirmDowngrade:i=!1}={}){const s=new FormData;o&&s.append("confirmUnsigned","true"),n&&s.append("confirmUpgrade","true"),i&&s.append("confirmDowngrade","true"),s.append("file",e);const r=a(),d=await fetch(`${m}/plugins/install-upload`,{method:"POST",headers:r?{Authorization:`Bearer ${r}`}:{},body:s}),c=await d.json().catch(()=>({}));if(d.status===409){const h=new Error(c.error||"Plugin already installed");throw h.code="CONFLICT",h.name=c.name,h.installedVersion=c.installedVersion,h.incomingVersion=c.incomingVersion,h}if(!d.ok)throw new Error(c.error||`Install failed (${d.status})`);return c}},marketplace:{catalogue:()=>t("/plugins/marketplace",{method:"GET"}),install:(e,o,{update:n=!1}={})=>t("/plugins/marketplace/install",{method:"POST",body:JSON.stringify({slug:e,version:o,update:n})}),uninstall:e=>t(`/plugins/marketplace/${encodeURIComponent(e)}`,{method:"DELETE"})},collections:{list:()=>t("/collections",{method:"GET"}),proStatus:()=>t("/collections/pro-status",{method:"GET"}),get:e=>t(`/collections/${e}`,{method:"GET"}),create:e=>t("/collections",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/collections/${e}`,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(`/collections/${e}`,{method:"DELETE"}),listEntries:(e,o={})=>{const n=new URLSearchParams(o).toString();return t(`/collections/${e}/entries${n?"?"+n:""}`,{method:"GET"})},getEntry:(e,o)=>t(`/collections/${e}/entries/${o}`,{method:"GET"}),createEntry:(e,o)=>t(`/collections/${e}/entries`,{method:"POST",body:JSON.stringify({data:o})}),updateEntry:(e,o,n)=>t(`/collections/${e}/entries/${o}`,{method:"PUT",body:JSON.stringify({data:n})}),deleteEntry:(e,o)=>t(`/collections/${e}/entries/${o}`,{method:"DELETE"}),clearEntries:e=>t(`/collections/${e}/entries`,{method:"DELETE"}),import:(e,o)=>t(`/collections/${e}/import`,{method:"POST",body:JSON.stringify({entries:o})}),publicList:(e,o={})=>{const n=new URLSearchParams(o).toString();return t(`/collections/${e}/public${n?"?"+n:""}`,{method:"GET"})},getConnections:()=>t("/collections/connections",{method:"GET"}),saveConnections:e=>t("/collections/connections",{method:"PUT",body:JSON.stringify(e)}),migrateStorage:(e,o)=>t(`/collections/${e}/migrate-storage`,{method:"POST",body:JSON.stringify({storage:o})})},forms:{list:()=>t("/forms",{method:"GET"}),create:e=>t("/forms",{method:"POST",body:JSON.stringify(e)}),get:e=>t(`/forms/${e}`,{method:"GET"}),update:(e,o)=>t(`/forms/${e}`,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(`/forms/${e}`,{method:"DELETE"}),listSubmissions:e=>t(`/forms/${e}/submissions`,{method:"GET"}),clearSubmissions:e=>t(`/forms/${e}/submissions`,{method:"DELETE"}),deleteSubmission:(e,o)=>t(`/forms/${e}/submissions/${o}`,{method:"DELETE"}),testEmail:e=>t("/forms/test-email",{method:"POST",body:JSON.stringify({to:e})})},views:{list:()=>t("/views",{method:"GET"}),get:e=>t(`/views/${e}`,{method:"GET"}),create:e=>t("/views",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/views/${e}`,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(`/views/${e}`,{method:"DELETE"}),execute:(e,o={})=>{const n=new URLSearchParams(o).toString();return t(`/views/${e}/execute${n?"?"+n:""}`,{method:"GET"})},forCollection:e=>t(`/views/collection/${e}`,{method:"GET"})},actions:{list:()=>t("/actions",{method:"GET"}),get:e=>t(`/actions/${e}`,{method:"GET"}),create:e=>t("/actions",{method:"POST",body:JSON.stringify(e)}),update:(e,o)=>t(`/actions/${e}`,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(`/actions/${e}`,{method:"DELETE"}),execute:(e,o)=>t(`/actions/${e}/execute`,{method:"POST",body:JSON.stringify({entryId:o})}),forCollection:e=>t(`/actions/collection/${e}`,{method:"GET"}),checkAccess:(e,o)=>t(`/actions/${e}/check-access`,{method:"POST",body:JSON.stringify({entryIds:o})})},versions:{list:e=>t(`/versions/list${e}`),get:(e,o)=>t(`/versions/get/${encodeURIComponent(o)}${e}`),create:(e,o)=>t(`/versions/create${e}`,{method:"POST",body:JSON.stringify({label:o})}),restore:(e,o)=>t(`/versions/restore/${encodeURIComponent(o)}${e}`,{method:"POST"}),delete:(e,o)=>t(`/versions/delete/${encodeURIComponent(o)}${e}`,{method:"DELETE"}),bulkDelete:(e,o)=>t(`/versions/bulk-delete${e}`,{method:"POST",body:JSON.stringify({filenames:o})}),prune:(e,o)=>t(`/versions/prune${e}`,{method:"POST",body:JSON.stringify({keep:o})})},blocks:{list:()=>t("/blocks",{method:"GET"}),get:e=>t(`/blocks/${encodeURIComponent(e)}`,{method:"GET"}),put:(e,o)=>t(`/blocks/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(`/blocks/${encodeURIComponent(e)}`,{method:"DELETE"}),async exportBundle(e){const o=a(),n=await fetch(`${m}/blocks/${encodeURIComponent(e)}/export`,{headers:o?{Authorization:`Bearer ${o}`}:{}});if(!n.ok){const d=await n.json().catch(()=>({}));throw new Error(d.error||`Export failed (${n.status})`)}const i=await n.blob(),s=URL.createObjectURL(i),r=document.createElement("a");r.href=s,r.download=`${e}.dmblock.json`,document.body.appendChild(r),r.click(),r.remove(),URL.revokeObjectURL(s)},async importBundle(e,{overwrite:o=!1}={}){const n=await fetch(`${m}/blocks/import`,{method:"POST",headers:{"Content-Type":"application/json",...a()?{Authorization:`Bearer ${a()}`}:{}},body:JSON.stringify({...e,overwrite:o})});if(n.status===409){const i=await n.json().catch(()=>({})),s=new Error(i.error||"Block already exists");throw s.code="CONFLICT",s.name=i.name,s}if(!n.ok){const i=await n.json().catch(()=>({}));throw new Error(i.error||`Import failed (${n.status})`)}return n.json()}},components:{list:()=>t("/components",{method:"GET"}),get:e=>t(`/components/${encodeURIComponent(e)}`,{method:"GET"}),compile:(e,o)=>t("/components/compile",{method:"POST",body:JSON.stringify({name:e,source:o})}),put:(e,o)=>t(`/components/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(`/components/${encodeURIComponent(e)}`,{method:"DELETE"}),async exportBundle(e){const o=a(),n=await fetch(`${m}/components/${encodeURIComponent(e)}/export`,{headers:o?{Authorization:`Bearer ${o}`}:{}});if(!n.ok){const d=await n.json().catch(()=>({}));throw new Error(d.error||`Export failed (${n.status})`)}const i=await n.blob(),s=URL.createObjectURL(i),r=document.createElement("a");r.href=s,r.download=`${e}.dmcomponent.json`,document.body.appendChild(r),r.click(),r.remove(),URL.revokeObjectURL(s)},async importBundle(e,{overwrite:o=!1}={}){const n=await fetch(`${m}/components/import`,{method:"POST",headers:{"Content-Type":"application/json",...a()?{Authorization:`Bearer ${a()}`}:{}},body:JSON.stringify({...e,overwrite:o})});if(n.status===409){const i=await n.json().catch(()=>({})),s=new Error(i.error||"Component already exists");throw s.code="CONFLICT",s.name=i.name,s}if(!n.ok){const i=await n.json().catch(()=>({}));throw new Error(i.error||`Import failed (${n.status})`)}return n.json()}},get:e=>t(e,{method:"GET"}),post:(e,o)=>t(e,{method:"POST",body:JSON.stringify(o)}),put:(e,o)=>t(e,{method:"PUT",body:JSON.stringify(o)}),delete:e=>t(e,{method:"DELETE"}),settingsExt:{testEmail:e=>t("/settings/test-email",{method:"POST",body:JSON.stringify({to:e})})},system:{notifications:{list:()=>t("/system/notifications",{method:"GET"}),unreadCount:()=>t("/system/notifications/unread-count",{method:"GET"}),markRead:e=>t(`/system/notifications/${e}/read`,{method:"POST"}),dismiss:e=>t(`/system/notifications/${e}/dismiss`,{method:"POST"}),remove:e=>t(`/system/notifications/${e}`,{method:"DELETE"})}},dashboard:{summary:()=>t("/dashboard/summary",{method:"GET"}),summaryLite:()=>t("/dashboard/summary?lite=1",{method:"GET"})}};export function isAuthenticated(){return!!a()}export function getUser(){return S.get("auth_user")}export function setAuthData({token:e,refreshToken:o,user:n}){e&&f(e),o&&S.set("auth_refresh_token",o),n&&($(n.id),S.set("auth_user",n))}let p=!1,T=!1;export function sendToLogin({expired:e=!1}={}){/^#\/(login|reset-password)(\?|\/|$)/.test(location.hash)||(location.hash=O(location.hash,{expired:e}))}export function logout(){!T&&window.M?.subscribe&&(T=!0,M.subscribe("router:afterChange",({to:e}={})=>{/^\/login(\?|$)/.test(e?.path||"")||(p=!1)})),p=!0,R.navigate("/login")}export function takePendingLogout(){return p?(p=!1,P(),!0):!1}function P(){const e=u();e&&fetch(`${m}/auth/logout`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e})}).catch(()=>{}),y()}export{t as apiRequest,g as refreshAccessToken,a as getToken,y as clearAuth};
@@ -0,0 +1,26 @@
1
+ import{apiRequest as U}from"../api.js";import{onceClosed as V}from"./tool-kit.js";const L=`<div class="bpk" style="display:grid;gap:1rem">
2
+ <p>Versioned collections of reusable blocks. Preview checks local edits before an installation or update.</p>
3
+ <label class="form-label">Pack <select class="form-input" data-model="selected.value"></select></label>
4
+ <label class="form-label">Version <select class="form-input" data-model="version.value"></select></label>
5
+ <div style="display:flex;gap:.5rem;flex-wrap:wrap">
6
+ <button class="btn btn-primary" data-on-click="preview">Preview installation</button>
7
+ <button class="btn btn-ghost" data-on-click="download">Export pack</button>
8
+ <button class="btn btn-ghost" data-on-click="history">History</button>
9
+ <button class="btn btn-ghost" data-on-click="rollback">Roll back last installation</button>
10
+ </div>
11
+ <pre style="white-space:pre-wrap" data-bind-text="reviewText.value" aria-live="polite"></pre>
12
+ <button class="btn btn-primary" data-on-click="apply" data-bind-disabled="!canApply.value">Apply reviewed installation</button>
13
+ <hr>
14
+ <details><summary>Create a pack from this site's blocks</summary>
15
+ <label class="form-label">Pack ID <input class="form-input" data-model="packId.value" placeholder="studio-cards"></label>
16
+ <label class="form-label">Title <input class="form-input" data-model="title.value"></label>
17
+ <label class="form-label">Version <input class="form-input" data-model="newVersion.value" placeholder="1.0.0"></label>
18
+ <label class="form-label">Blocks <select class="form-input bpk-blocks" multiple size="8" aria-label="Blocks to include"></select></label>
19
+ <label class="form-label">Bundle local media (optional) <select class="form-input bpk-media" multiple size="5" aria-label="Media to bundle"></select></label>
20
+ <button class="btn btn-primary" data-on-click="create">Publish version to catalogue</button>
21
+ </details>
22
+ <label class="form-label">Import pack file <input class="form-input bpk-file" type="file" accept=".dmblockpack.json,application/json"></label>
23
+ <p class="text-danger" data-bind-text="error.value" role="alert"></p>
24
+ </div>`;export async function mountBlockPacks(s,{request:t=U,changed:n=async()=>{}}={}){$(s).html(L,{safe:!1});const l=M.observable(""),i=M.observable(""),m=M.observable(""),u=M.observable(""),g=M.observable(""),O=M.observable(""),x=M.observable("1.0.0"),p=M.observable(!1);let r=[],f=null,P=!1,R=!1;const v=$(s).find("select").get(),d=v[0],b=v[1],S=v[2],B=v[3],y=(e,a)=>new Option(a,e),w=()=>`/block-packs/${encodeURIComponent(l.peek())}/${encodeURIComponent(i.peek())}`,c=e=>async()=>{if(!(P||R)){P=!0,u.value="";try{await e()}catch(a){u.value=a.message||String(a)}finally{P=!1}}},k=async()=>{r=await t("/block-packs"),$(d).empty();for(const e of r)$(d).append(y(e.id,`${e.title}${e.installed?` (installed ${e.installed})`:""}`));l.value=r.some(e=>e.id===l.peek())?l.peek():r[0]?.id||"",d.value=l.peek(),j()};function j(){const e=r.find(a=>a.id===l.peek());$(b).empty();for(const a of e?.versions||[])$(b).append(y(a,a));i.value=e?.latest||"",b.value=i.peek(),h()}function h(){f=null,p.value=!1,m.value=""}$(d).on("change",()=>{l.value=d.value,j()}),$(b).on("change",()=>{i.value=b.value,h()});const C=e=>{f=e,m.value=[`${e.id}: ${e.from||"not installed"} -> ${e.version}`,...e.problems,...(e.assets||[]).map(a=>`${a.action} media: ${a.name}`),...e.changes.map(a=>`${a.action}: ${a.name}${a.conflict?` - ${a.conflict}`:""}`)].join(`
25
+ `),p.value=!e.problems.length&&!e.changes.some(a=>a.conflict)},T={preview:c(async()=>{if(!l.peek())throw Error("Choose a pack.");const e=w(),a=await t(e+"/preview",{method:"POST",body:"{}"});w()===e&&C(a)}),apply:c(async()=>{!f||!p.peek()||(await t(w()+"/install",{method:"POST",body:JSON.stringify({token:f.token})}),h(),await k(),await n(),E.toast("Pack installed.",{type:"success"}))}),download:c(async()=>{if(!l.peek())throw Error("Choose a pack.");const e=await t(w()+"/export");downloadPack(e)}),history:c(async()=>{const e=await t(`/block-packs/${encodeURIComponent(l.peek())}/history`);m.value=e.length?e.map(a=>`${a.at}: ${a.from||"not installed"} -> ${a.to}`).join(`
26
+ `):"No installations yet.",p.value=!1}),rollback:c(async()=>{l.peek()&&await E.confirm("Roll back the last installation of this pack? Locally edited blocks will prevent rollback.")&&(await t(`/block-packs/${encodeURIComponent(l.peek())}/rollback`,{method:"POST",body:"{}"}),h(),await k(),await n(),E.toast("Pack rolled back.",{type:"success"}))}),create:c(async()=>{const e=[...S.selectedOptions].map(o=>o.value),a=[...B.selectedOptions].map(o=>o.value);await t("/block-packs/assemble",{method:"POST",body:JSON.stringify({id:g.peek(),title:O.peek(),version:x.peek(),names:e,media:a})}),l.value=g.peek(),await k(),E.toast("Pack version published to catalogue.",{type:"success"})})},I=M.applyBindings({selected:l,version:i,reviewText:m,error:u,packId:g,title:O,newVersion:x,canApply:p},s,{methods:T});$(s).find(".bpk-file").on("change",c(async()=>{const e=$(s).find(".bpk-file").get(0),a=e.files?.[0];if(e.value="",!a)return;if(a.size>2e6)throw Error("Pack exceeds 2 MB.");const o=JSON.parse(await a.text());await t("/block-packs",{method:"POST",body:JSON.stringify(o)}),l.value=o.id,await k(),E.toast("Pack added to catalogue. Preview it before installing.",{type:"success"})}));try{const e=await t("/blocks");for(const o of e)$(S).append(y(o.name,o.name));const a=await t("/media").catch(()=>[]);for(const o of a)/\.(png|jpe?g|gif|webp|avif|ico|bmp|tiff?|woff2?)$/i.test(o.name)&&$(B).append(y(o.name,o.name));await k()}catch(e){u.value=e.message}return{dispose:()=>{R=!0,I.dispose()},selected:l,version:i}}export function downloadPack(s){const t=URL.createObjectURL(new Blob([JSON.stringify(s,null,2)],{type:"application/json"})),n=document.createElement("a");n.href=t,n.download=`${s.id}-${s.version}.dmblockpack.json`,n.click(),URL.revokeObjectURL(t)}export async function openBlockPacks({changed:s}={}){const t=E.slideover({title:"Block packs",size:"lg",position:"right"}),n=document.createElement("div");t.element.appendChild(n),t.open();let l,i=!1;V(t,()=>{i=!0,l?.dispose()}),l=await mountBlockPacks(n,{changed:s}),i&&l.dispose()}
@@ -1 +1,6 @@
1
- export function humanise(t){const e=String(t).replace(/_/g," ").replace(/([a-z0-9])([A-Z])/g,"$1 $2").trim().toLowerCase();return e.charAt(0).toUpperCase()+e.slice(1)}function m(t){return t.options?.length?"select":t.raw?"text":/^icon$|_icon$|Icon$/.test(t.name)?"icon":/image|photo|picture|avatar|logo|^img|Img$/i.test(t.name)?"image":"text"}function p(t){const e=m(t),n={name:t.name,label:humanise(t.name),type:e};e==="select"&&(n.options=t.options.map(a=>[a,a])),t.default&&(n.seed=t.default);const r=t.raw?`${t.hint?`${t.hint} - `:""}HTML allowed`:t.hint;return r&&e!=="select"&&(n.placeholder=r),n}export function blockTagDefs(t){return(Array.isArray(t)?t:[]).filter(e=>e?.name).map(e=>({name:e.name,label:e.name,icon:"box",block:!0,shortTag:!!e.shortTag,selfClosing:!0,description:e.description||"",example:e.example||"",attrs:(Array.isArray(e.fields)?e.fields:[]).map(p)})).sort((e,n)=>e.name.localeCompare(n.name))}function u(t){const e={};for(const[,n,r,a]of String(t).matchAll(/([\w-]+)=(?:"([^"]*)"|'([^']*)')/g))e[n]=r??a??"";return e}const g=t=>String(t).replace(/"/g,"&quot;");export function blockTagSnippet(t){const e=new RegExp(`^\\[(?:${t.name}|block)(?=[\\s/\\]])([^\\]]*)\\]`).exec(String(t.example||"").trim()),n=e?u(e[1]):{};if(e&&"template"in n&&n.template!==t.name)for(const a of Object.keys(n))delete n[a];const r=t.shortTag?[]:[`template="${t.name}"`];for(const a of t.attrs||[]){const s=a.name in n?n[a.name]:a.seed??"";r.push(`${a.name}="${g(s)}"`)}return`[${t.shortTag?t.name:"block"}${r.length?` ${r.join(" ")}`:""} /]`}export function blocksInBody(t,e,n=e){const r=String(t||""),a=new Set(e),s=new Set(n),i=new Map,l=(o,c)=>{a.has(o)&&!i.has(o)&&i.set(o,c)};for(const o of r.matchAll(/(?<![\w-])(?:block|template)\s*=\s*["']([a-z0-9][a-z0-9-]*)["']/g))l(o[1],o.index);for(const o of r.matchAll(/\[([a-z0-9][a-z0-9-]*)(?=[\s/\]])/g))s.has(o[1])&&l(o[1],o.index);return[...i.entries()].sort((o,c)=>o[1]-c[1]).map(([o])=>o)}
1
+ export function humanise(t){const e=String(t).replace(/_/g," ").replace(/([a-z0-9])([A-Z])/g,"$1 $2").trim().toLowerCase();return e.charAt(0).toUpperCase()+e.slice(1)}function m(t){return t.options?.length?"select":t.raw?"text":/^icon$|_icon$|Icon$/.test(t.name)?"icon":/image|photo|picture|avatar|logo|^img|Img$/i.test(t.name)?"image":"text"}function p(t){const e=m(t),n={name:t.name,label:humanise(t.name),type:e};e==="select"&&(n.options=t.options.map(r=>[r,r])),t.default&&(n.seed=t.default);const s=t.raw?`${t.hint?`${t.hint} - `:""}HTML allowed`:t.hint;return s&&e!=="select"&&(n.placeholder=s),n}export function blockTagDefs(t){return(Array.isArray(t)?t:[]).filter(e=>e?.name).map(e=>({name:e.name,label:e.name,icon:"box",block:!0,shortTag:!!e.shortTag,selfClosing:!e.slots?.length,container:!!e.slots?.length,slots:e.slots||[],description:e.description||"",example:e.example||"",attrs:(Array.isArray(e.fields)?e.fields:[]).map(p)})).sort((e,n)=>e.name.localeCompare(n.name)).map(e=>({...e,template:blockTagSnippet(e)}))}function g(t){const e={};for(const[,n,s,r]of String(t).matchAll(/([\w-]+)=(?:"([^"]*)"|'([^']*)')/g))e[n]=s??r??"";return e}const u=t=>String(t).replace(/"/g,"&quot;");export function blockTagSnippet(t){const e=new RegExp(`^\\[(?:${t.name}|block)(?=[\\s/\\]])([^\\]]*)\\]`).exec(String(t.example||"").trim()),n=e?g(e[1]):{};if(e&&"template"in n&&n.template!==t.name)for(const a of Object.keys(n))delete n[a];const s=t.shortTag?[]:[`template="${t.name}"`];for(const a of t.attrs||[]){const o=a.name in n?n[a.name]:a.seed??"";s.push(`${a.name}="${u(o)}"`)}const r=t.shortTag?t.name:"block",i=`[${r}${s.length?` ${s.join(" ")}`:""}`;if(!t.slots?.length)return i+" /]";const l=t.slots.map(a=>a==="default"?"Content":`[slot name="${a}"]
2
+
3
+ [/slot]`).join(`
4
+ `);return`${i}]
5
+ ${l}
6
+ [/${r}]`}export function blocksInBody(t,e,n=e){const s=String(t||""),r=new Set(e),i=new Set(n),l=new Map,a=(o,c)=>{r.has(o)&&!l.has(o)&&l.set(o,c)};for(const o of s.matchAll(/(?<![\w-])(?:block|template)\s*=\s*["']([a-z0-9][a-z0-9-]*)["']/g))a(o[1],o.index);for(const o of s.matchAll(/\[([a-z0-9][a-z0-9-]*)(?=[\s/\]])/g))i.has(o[1])&&a(o[1],o.index);return[...l.entries()].sort((o,c)=>o[1]-c[1]).map(([o])=>o)}
@@ -1 +1 @@
1
- import{fmtDate as u}from"./dates.js";import{matchesTag as l,tagsOf as c,tagsText as g}from"./list-tags-arrange.js";export const NAME_RE=/^[a-z0-9][a-z0-9-]*$/,FILTERS=["all","used","unused"];const i=(e,t,n=`${t}s`)=>`${e} ${e===1?t:n}`;export function formatSize(e){const t=Number(e)||0;return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(t<10*1024?1:0)} KB`:`${(t/1024/1024).toFixed(1)} MB`}export function usageCount(e){return e?.usage?(e.usage.pages?.length||0)+(e.usage.views?.length||0)+(e.usage.footer?1:0):null}export function usageText(e){const t=usageCount(e);if(t===null)return"";if(!t)return"Not used on any page or view";const n=e.usage.pages?.length||0,o=e.usage.views?.length||0,s=[e.usage.footer&&"the footer of every page",n&&i(n,"page"),o&&i(o,"view")].filter(Boolean);return`Used on ${s.length>2?`${s.slice(0,-1).join(", ")} and ${s.at(-1)}`:s.join(" and ")}`}export function shortcodeFor(e){return e?.example||`[block template="${e?.name??""}" /]`}export function arrangeBlocks(e,{filter:t="all",query:n="",tag:o=""}={}){const s=String(n).trim().toLowerCase();return[...e||[]].filter(r=>t==="used"?usageCount(r)>0:t==="unused"?usageCount(r)===0:!0).filter(r=>l(r,o)).filter(r=>!s||[r.name,r.description,r.meta?.project,...c(r)].some(a=>String(a||"").toLowerCase().includes(s))).sort((r,a)=>String(r.name).localeCompare(String(a.name)))}export function blockRow(e,t=u){const n=usageCount(e);return{name:e.name,description:e.description||"",meta:[`${e.name}.html`,formatSize(e.size),e.updatedAt?`changed ${t(e.updatedAt)}`:"",usageText(e)].filter(Boolean).join(" \xB7 "),hasCss:!!e.hasCss,bundled:!!e.bundled,project:e.meta?.project||"",listTags:g(e),unused:n===0,uses:n===null?"":String(n)}}export function checkNewName(e,t=[]){const n=String(e??"").trim();return n?NAME_RE.test(n)?t.includes(n)?`"${n}" already exists.`:"":"Lowercase letters, digits and hyphens; starting with a letter or digit.":"A block needs a name."}export function copyName(e,t=[]){const n=`${e}-copy`;if(!t.includes(n))return n;for(let o=2;o<1e3;o++)if(!t.includes(`${n}-${o}`))return`${n}-${o}`;return n}
1
+ import{fmtDate as l}from"./dates.js";import{allTagsOf as c,matchesTag as g,tagsText as d,toolTagOf as f}from"./list-tags-arrange.js";export const NAME_RE=/^[a-z0-9][a-z0-9-]*$/,FILTERS=["all","used","unused"];const u=(e,t,n=`${t}s`)=>`${e} ${e===1?t:n}`;export function formatSize(e){const t=Number(e)||0;return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(t<10*1024?1:0)} KB`:`${(t/1024/1024).toFixed(1)} MB`}export function usageCount(e){return e?.usage?(e.usage.pages?.length||0)+(e.usage.views?.length||0)+(e.usage.footer?1:0):null}export function usageText(e){const t=usageCount(e);if(t===null)return"";if(!t)return"Not used on any page or view";const n=e.usage.pages?.length||0,r=e.usage.views?.length||0,a=[e.usage.footer&&"the footer of every page",n&&u(n,"page"),r&&u(r,"view")].filter(Boolean);return`Used on ${a.length>2?`${a.slice(0,-1).join(", ")} and ${a.at(-1)}`:a.join(" and ")}`}export function shortcodeFor(e){return e?.example||`[block template="${e?.name??""}" /]`}export function arrangeBlocks(e,{filter:t="all",query:n="",tag:r="",tools:a={}}={}){const i=String(n).trim().toLowerCase();return[...e||[]].filter(o=>t==="used"?usageCount(o)>0:t==="unused"?usageCount(o)===0:!0).filter(o=>g(o,r,a)).filter(o=>!i||[o.name,o.description,o.meta?.project,...c(o,a)].some(s=>String(s||"").toLowerCase().includes(i))).sort((o,s)=>String(o.name).localeCompare(String(s.name)))}export function blockRow(e,t=l,n={}){const r=usageCount(e);return{name:e.name,description:e.description||"",meta:[`${e.name}.html`,formatSize(e.size),e.updatedAt?`changed ${t(e.updatedAt)}`:"",usageText(e)].filter(Boolean).join(" \xB7 "),hasCss:!!e.hasCss,bundled:!!e.bundled,project:e.meta?.project||"",listTags:d(e),toolTag:f(e,n),unused:r===0,uses:r===null?"":String(r)}}export function checkNewName(e,t=[]){const n=String(e??"").trim();return n?NAME_RE.test(n)?t.includes(n)?`"${n}" already exists.`:"":"Lowercase letters, digits and hyphens; starting with a letter or digit.":"A block needs a name."}export function copyName(e,t=[]){const n=`${e}-copy`;if(!t.includes(n))return n;for(let r=2;r<1e3;r++)if(!t.includes(`${n}-${r}`))return`${n}-${r}`;return n}
@@ -1,3 +1,3 @@
1
1
  export const FIELD_TYPES=[{value:"string",label:"Text (single line)"},{value:"email",label:"Email"},{value:"tel",label:"Phone"},{value:"number",label:"Number"},{value:"textarea",label:"Textarea (multi-line)"},{value:"select",label:"Dropdown (select)"},{value:"radio",label:"Radio buttons"},{value:"checkbox",label:"Single checkbox"},{value:"checkbox-group",label:"Checkbox group"},{value:"date",label:"Date"},{value:"time",label:"Time"},{value:"url",label:"URL"},{value:"hidden",label:"Hidden field"},{value:"file",label:"Files (uploaded with a form)"}],OPTION_TYPES=new Set(["select","radio","checkbox-group"]),ADDON_TYPES=new Set(["string","email","tel","number","textarea","select","date","time","url"]);const f=/^[a-z0-9-]+$/i;export const EXTRA_TYPES={clear:new Set(["string","email","tel","url","textarea"]),stepper:new Set(["number"]),counter:new Set(["string","textarea"])};const m=24;function p(e){return e?typeof e=="string"?{icon:"",text:e}:{icon:e.icon||"",text:e.icon?"":String(e.text??"")}:{icon:"",text:""}}export function addonFromBoxes(e,r){const n=String(e??"").trim(),t=String(r??"").trim();return n&&f.test(n)?{icon:n}:t?{text:t.slice(0,m)}:null}export const OPERATIONS=["create","read","update","delete"],EXPORT_FORMATS=["csv","json"],FIELD_NAME_RE=/^[A-Za-z_][A-Za-z0-9_-]*$/;export function slugify(e){return String(e??"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}export const nameFromLabel=e=>slugify(e).replace(/-/g,"_"),typeLabel=e=>FIELD_TYPES.find(r=>r.value===e)?.label||e||"";export function optionsText(e){return(Array.isArray(e)?e:[]).map(r=>typeof r=="string"?`${r}: ${r}`:`${r?.value??""}: ${r?.label??r?.value??""}`).join(`
2
2
  `)}export function parseOptions(e){return String(e??"").split(`
3
- `).filter(r=>r.trim()).map(r=>{const[n,...t]=r.split(":");return{value:n.trim(),label:t.join(":").trim()||n.trim()}})}const g=()=>({create:{enabled:!1,access:"admin"},read:{enabled:!0,access:"public"},update:{enabled:!1,access:"admin"},delete:{enabled:!1,access:"admin"}}),b=e=>({enabled:!0,access:e||"",formats:["csv","json"]});export function roleLadder(e){return(Array.isArray(e)?e:e?.entries||[]).map(n=>({name:n?.data?.name,label:n?.data?.label||n?.data?.name,level:Number(n?.data?.level)})).filter(n=>typeof n.name=="string"&&n.name&&Number.isFinite(n.level)).sort((n,t)=>n.level-t.level||n.name.localeCompare(t.name))}export function accessOptions(e,r,{token:n=!0}={}){const t=[{value:"public",label:"Public - anyone"}];n&&t.push({value:"token",label:"API token"});for(const l of[...e||[]].reverse())t.push({value:l.name,label:l.level===0?`${l.label} only`:`${l.label} and above`});return typeof r=="string"&&r&&!t.some(l=>l.value===r)&&t.push(e?.length?{value:r,label:`${r} (role not found)`,missing:!0}:{value:r,label:r}),t}let x=0;export const fieldKey=()=>`f${Date.now().toString(36)}${(x++).toString(36)}`;export function formFromCollection(e=null,{project:r="",defaultRole:n=""}={}){const t=e||{},l={...g(),...t.api||{}},o={...b(n),...t.export||{}},a={title:String(t.title??""),slug:String(t.slug??""),description:String(t.description??""),layout:t.layout==="grid"?"grid":"stacked",columns:String(Number.parseInt(t.columns,10)||2),project:String(t.meta?.project??r??""),bundled:t.bundled===!0,storageAdapter:t.storage?.adapter==="mongodb"?"mongodb":"file",storageConnection:String(t.storage?.connection||"default"),fields:(Array.isArray(t.fields)?t.fields:[]).map(i=>({...i,_key:fieldKey()})),readFields:Array.isArray(l.read?.fields)?l.read.fields.join(", "):"",exportEnabled:o.enabled!==!1,exportAccess:typeof o.access=="string"&&o.access?o.access:String(n||""),exportCsv:(Array.isArray(o.formats)?o.formats:EXPORT_FORMATS).includes("csv"),exportJson:(Array.isArray(o.formats)?o.formats:EXPORT_FORMATS).includes("json")};for(const i of OPERATIONS){a[`${i}Enabled`]=l[i]?.enabled===!0;const s=l[i]?.access;a[`${i}Access`]=typeof s=="string"&&s?s:"admin"}return a}export function cleanField(e){const{_key:r,...n}=e||{};return n}export function payloadFromForm(e,{isNew:r=!1,meta:n={}}={}){const t=e||{},l={};for(const i of OPERATIONS)l[i]={enabled:t[`${i}Enabled`]===!0,access:t[`${i}Access`]||"admin"};const o=String(t.readFields??"").split(",").map(i=>i.trim()).filter(Boolean);o.length&&(l.read.fields=o);const a=Math.min(6,Math.max(1,Number.parseInt(t.columns,10)||2));return{title:String(t.title??"").trim(),...r&&{slug:slugify(t.slug||t.title)},description:String(t.description??"").trim(),layout:t.layout==="grid"?"grid":"stacked",columns:a,fields:(t.fields||[]).map(cleanField),api:l,export:{enabled:t.exportEnabled!==!1,...t.exportAccess&&{access:t.exportAccess},formats:EXPORT_FORMATS.filter(i=>i==="csv"?t.exportCsv:t.exportJson)},storage:t.storageAdapter==="mongodb"?{adapter:"mongodb",connection:t.storageConnection||"default"}:{adapter:"file"},meta:{...n||{},project:String(t.project??"")||null},bundled:t.bundled===!0}}export function snapshot(e){const{fields:r=[],...n}=e||{};return JSON.stringify({...n,fields:r.map(cleanField)})}export function checkForm(e,{isNew:r=!1,taken:n=[],original:t={}}={}){const l=e||{},o={};if(String(l.title??"").trim()||(o.title="A collection needs a title."),r){const c=slugify(l.slug||l.title);c?n.includes(c)&&(o.slug=`"${c}" is already a collection.`):o.slug="The slug needs a letter or a number."}const a=Number.parseInt(l.columns,10);l.layout==="grid"&&!(a>=1&&a<=6)&&(o.columns="Between 1 and 6 columns.");const i={},s=new Map;return(l.fields||[]).forEach(c=>{const d=fieldProblem(c,t[c._key]);d&&(i[c._key]=d);const u=String(c.name??"").trim();u&&(s.has(u)?i[c._key]=i[c._key]||`"${u}" is used by another field.`:s.set(u,c._key))}),Object.keys(i).length&&(o.fields=i),l.exportEnabled&&!l.exportCsv&&!l.exportJson&&(o.export="Pick at least one export format, or turn export off."),o}export function fieldProblem(e,r){const n=String(e?.name??"").trim();return n?n!==r&&!FIELD_NAME_RE.test(n)?"Names start with a letter or _, then letters, digits, _ or -.":OPTION_TYPES.has(e.type)&&!(Array.isArray(e.options)&&e.options.length)?`A ${typeLabel(e.type).toLowerCase()} needs at least one option.`:"":"A field needs a name - it is what each entry is keyed by."}export const errorCount=e=>Object.keys(e||{}).filter(r=>r!=="fields").length+Object.keys(e?.fields||{}).length;export function fieldRow(e,r={},{grid:n=!1}={}){const t=[e.name||"(no name)",typeLabel(e.type)];return OPTION_TYPES.has(e.type)&&t.push(`${(e.options||[]).length} options`),n&&t.push(e.fullWidth?"full width":`span ${e.span>1?e.span:1}`),{key:e._key,label:e.label||"(Untitled field)",meta:t.join(" \xB7 "),required:e.required===!0,hidden:e.type==="hidden",problem:r[e._key]||"",rowCls:r[e._key]?"is-bad":""}}export function moveField(e,r,n){const t=[...e];if(r<0||r>=t.length||n<0||n>=t.length||r===n)return t;const[l]=t.splice(r,1);return t.splice(n,0,l),t}export function duplicateField(e,r){const n=e[r];if(!n)return[...e];const t=new Set(e.map(s=>s.name)),l=`${n.name||"field"}_copy`;let o=l;for(let s=2;t.has(o);s++)o=`${l}_${s}`;const a={...JSON.parse(JSON.stringify(cleanField(n))),name:o,label:`${n.label||"Field"} (copy)`,_key:fieldKey()};delete a.id;const i=[...e];return i.splice(r+1,0,a),i}export const newField=()=>({id:`field-${Date.now()}`,name:"",label:"",type:"string",required:!1,placeholder:"",helper:"",options:[],validation:[],logic:null,_key:fieldKey()});export function panelForm(e){return{label:String(e.label??""),name:String(e.name??""),type:e.type||"string",required:e.required===!0,placeholder:String(e.placeholder??""),helper:String(e.helper??""),options:optionsText(e.options),span:String(e.span>1?e.span:1),fullWidth:e.fullWidth===!0,prefixIcon:p(e.prefix).icon,prefixText:p(e.prefix).text,suffixIcon:p(e.suffix).icon,suffixText:p(e.suffix).text,clear:e.clear===!0,stepper:e.stepper===!0,counter:e.counter===!0}}export function fieldFromPanel(e,r){const n={...e,label:String(r.label??"").trim(),name:String(r.name??"").trim(),type:r.type||"string",required:r.required===!0,placeholder:String(r.placeholder??"").trim(),helper:String(r.helper??"").trim()};OPTION_TYPES.has(n.type)&&(n.options=parseOptions(r.options));for(const[t,l]of Object.entries(EXTRA_TYPES)){if(!l.has(n.type)){delete n[t];continue}t in r&&(r[t]===!0?n[t]=!0:delete n[t])}for(const t of["prefix","suffix"]){const l=`${t}Icon`in r||`${t}Text`in r;if(!ADDON_TYPES.has(n.type)){delete n[t];continue}if(!l)continue;const o=addonFromBoxes(r[`${t}Icon`],r[`${t}Text`]);o?n[t]=o:delete n[t]}if(r.fullWidth)n.fullWidth=!0,delete n.span;else{delete n.fullWidth;const t=Number.parseInt(r.span,10);t>1?n.span=Math.min(6,t):delete n.span}return n}export function storageChange(e,r){const n=e||"file",t=r||"file";return n===t?"":`${n} \u2192 ${t}`}export function draftOf(e){const{fields:r=[],...n}=e||{};return{...n,fields:r.map(cleanField)}}export function formFromDraft(e,r){const n=e||{};return{...r,...n,fields:(Array.isArray(n.fields)?n.fields:r.fields).map(t=>({...cleanField(t),_key:fieldKey()}))}}
3
+ `).filter(r=>r.trim()).map(r=>{const[n,...t]=r.split(":");return{value:n.trim(),label:t.join(":").trim()||n.trim()}})}const g=()=>({create:{enabled:!1,access:"admin"},read:{enabled:!0,access:"public"},update:{enabled:!1,access:"admin"},delete:{enabled:!1,access:"admin"}}),b=e=>({enabled:!0,access:e||"",formats:["csv","json"]});export function roleLadder(e){return(Array.isArray(e)?e:e?.entries||[]).map(n=>({name:n?.data?.name,label:n?.data?.label||n?.data?.name,level:Number(n?.data?.level)})).filter(n=>typeof n.name=="string"&&n.name&&Number.isFinite(n.level)).sort((n,t)=>n.level-t.level||n.name.localeCompare(t.name))}export function accessOptions(e,r,{token:n=!0}={}){const t=[{value:"public",label:"Public - anyone"}];n&&t.push({value:"token",label:"API token"});for(const i of[...e||[]].reverse())t.push({value:i.name,label:i.level===0?`${i.label} only`:`${i.label} and above`});return typeof r=="string"&&r&&!t.some(i=>i.value===r)&&t.push(e?.length?{value:r,label:`${r} (role not found)`,missing:!0}:{value:r,label:r}),t}let x=0;export const fieldKey=()=>`f${Date.now().toString(36)}${(x++).toString(36)}`;export function formFromCollection(e=null,{project:r="",defaultRole:n=""}={}){const t=e||{},i={...g(),...t.api||{}},l={...b(n),...t.export||{}},s={title:String(t.title??""),slug:String(t.slug??""),description:String(t.description??""),layout:t.layout==="grid"?"grid":"stacked",columns:String(Number.parseInt(t.columns,10)||2),project:String(t.meta?.project??r??""),bundled:t.bundled===!0,storageAdapter:t.storage?.adapter==="mongodb"?"mongodb":"file",storageConnection:String(t.storage?.connection||"default"),fields:(Array.isArray(t.fields)?t.fields:[]).map(o=>({...o,_key:fieldKey()})),readFields:Array.isArray(i.read?.fields)?i.read.fields.join(", "):"",exportEnabled:l.enabled!==!1,exportAccess:typeof l.access=="string"&&l.access?l.access:String(n||""),exportCsv:(Array.isArray(l.formats)?l.formats:EXPORT_FORMATS).includes("csv"),exportJson:(Array.isArray(l.formats)?l.formats:EXPORT_FORMATS).includes("json")};for(const o of OPERATIONS){s[`${o}Enabled`]=i[o]?.enabled===!0;const a=i[o]?.access;s[`${o}Access`]=typeof a=="string"&&a?a:"admin"}return s}export function cleanField(e){const{_key:r,...n}=e||{};return n}export function payloadFromForm(e,{isNew:r=!1,meta:n={}}={}){const t=e||{},i={};for(const o of OPERATIONS)i[o]={enabled:t[`${o}Enabled`]===!0,access:t[`${o}Access`]||"admin"};const l=String(t.readFields??"").split(",").map(o=>o.trim()).filter(Boolean);l.length&&(i.read.fields=l);const s=Math.min(6,Math.max(1,Number.parseInt(t.columns,10)||2));return{title:String(t.title??"").trim(),...r&&{slug:slugify(t.slug||t.title)},description:String(t.description??"").trim(),layout:t.layout==="grid"?"grid":"stacked",columns:s,fields:(t.fields||[]).map(cleanField),api:i,export:{enabled:t.exportEnabled!==!1,...t.exportAccess&&{access:t.exportAccess},formats:EXPORT_FORMATS.filter(o=>o==="csv"?t.exportCsv:t.exportJson)},storage:t.storageAdapter==="mongodb"?{adapter:"mongodb",connection:t.storageConnection||"default"}:{adapter:"file"},meta:{...n||{},project:String(t.project??"")||null},bundled:t.bundled===!0}}export function snapshot(e){const{fields:r=[],...n}=e||{};return JSON.stringify({...n,fields:r.map(cleanField)})}export function checkForm(e,{isNew:r=!1,taken:n=[],original:t={}}={}){const i=e||{},l={};if(String(i.title??"").trim()||(l.title="A collection needs a title."),r){const c=slugify(i.slug||i.title);c?n.includes(c)&&(l.slug=`"${c}" is already a collection.`):l.slug="The slug needs a letter or a number."}const s=Number.parseInt(i.columns,10);i.layout==="grid"&&!(s>=1&&s<=6)&&(l.columns="Between 1 and 6 columns.");const o={},a=new Map;return(i.fields||[]).forEach(c=>{const d=fieldProblem(c,t[c._key]);d&&(o[c._key]=d);const u=String(c.name??"").trim();u&&(a.has(u)?o[c._key]=o[c._key]||`"${u}" is used by another field.`:a.set(u,c._key))}),Object.keys(o).length&&(l.fields=o),i.exportEnabled&&!i.exportCsv&&!i.exportJson&&(l.export="Pick at least one export format, or turn export off."),l}export function fieldProblem(e,r){const n=String(e?.name??"").trim();return n?n!==r&&!FIELD_NAME_RE.test(n)?"Names start with a letter or _, then letters, digits, _ or -.":OPTION_TYPES.has(e.type)&&!(Array.isArray(e.options)&&e.options.length)?`A ${typeLabel(e.type).toLowerCase()} needs at least one option.`:"":"A field needs a name - it is what each entry is keyed by."}export const errorCount=e=>Object.keys(e||{}).filter(r=>r!=="fields").length+Object.keys(e?.fields||{}).length;export function fieldRow(e,r={},{grid:n=!1}={}){const t=[e.name||"(no name)",typeLabel(e.type)];return OPTION_TYPES.has(e.type)&&t.push(`${(e.options||[]).length} options`),n&&t.push(e.fullWidth?"full width":`span ${e.span>1?e.span:1}`),{key:e._key,label:e.label||"(Untitled field)",meta:t.join(" \xB7 "),required:e.required===!0,hidden:e.type==="hidden",notInLists:e.listHidden===!0&&e.type!=="hidden",problem:r[e._key]||"",rowCls:r[e._key]?"is-bad":""}}export function moveField(e,r,n){const t=[...e];if(r<0||r>=t.length||n<0||n>=t.length||r===n)return t;const[i]=t.splice(r,1);return t.splice(n,0,i),t}export function duplicateField(e,r){const n=e[r];if(!n)return[...e];const t=new Set(e.map(a=>a.name)),i=`${n.name||"field"}_copy`;let l=i;for(let a=2;t.has(l);a++)l=`${i}_${a}`;const s={...JSON.parse(JSON.stringify(cleanField(n))),name:l,label:`${n.label||"Field"} (copy)`,_key:fieldKey()};delete s.id;const o=[...e];return o.splice(r+1,0,s),o}export const newField=()=>({id:`field-${Date.now()}`,name:"",label:"",type:"string",required:!1,placeholder:"",helper:"",options:[],validation:[],logic:null,_key:fieldKey()});export function panelForm(e){return{label:String(e.label??""),name:String(e.name??""),type:e.type||"string",required:e.required===!0,placeholder:String(e.placeholder??""),helper:String(e.helper??""),options:optionsText(e.options),span:String(e.span>1?e.span:1),fullWidth:e.fullWidth===!0,prefixIcon:p(e.prefix).icon,prefixText:p(e.prefix).text,suffixIcon:p(e.suffix).icon,suffixText:p(e.suffix).text,clear:e.clear===!0,stepper:e.stepper===!0,counter:e.counter===!0,inLists:e.listHidden!==!0}}export function fieldFromPanel(e,r){const n={...e,label:String(r.label??"").trim(),name:String(r.name??"").trim(),type:r.type||"string",required:r.required===!0,placeholder:String(r.placeholder??"").trim(),helper:String(r.helper??"").trim()};OPTION_TYPES.has(n.type)&&(n.options=parseOptions(r.options)),"inLists"in r&&(r.inLists===!1?n.listHidden=!0:delete n.listHidden);for(const[t,i]of Object.entries(EXTRA_TYPES)){if(!i.has(n.type)){delete n[t];continue}t in r&&(r[t]===!0?n[t]=!0:delete n[t])}for(const t of["prefix","suffix"]){const i=`${t}Icon`in r||`${t}Text`in r;if(!ADDON_TYPES.has(n.type)){delete n[t];continue}if(!i)continue;const l=addonFromBoxes(r[`${t}Icon`],r[`${t}Text`]);l?n[t]=l:delete n[t]}if(r.fullWidth)n.fullWidth=!0,delete n.span;else{delete n.fullWidth;const t=Number.parseInt(r.span,10);t>1?n.span=Math.min(6,t):delete n.span}return n}export function storageChange(e,r){const n=e||"file",t=r||"file";return n===t?"":`${n} \u2192 ${t}`}export function draftOf(e){const{fields:r=[],...n}=e||{};return{...n,fields:r.map(cleanField)}}export function formFromDraft(e,r){const n=e||{};return{...r,...n,fields:(Array.isArray(n.fields)?n.fields:r.fields).map(t=>({...cleanField(t),_key:fieldKey()}))}}
@@ -1 +1 @@
1
- import{fmtDate as y,fmtDateTime as d}from"./dates.js";export const OP_LABELS={eq:"=",ne:"\u2260",contains:"contains",gt:">",lt:"<"},MAX_COLUMNS=5,PAGE_SIZE=500,SHOW_STEP=100;export function matchesFilter(t,e){const r=t?.data?.[e.field],n=String(r??"");switch(e.op){case"eq":return n===String(e.value);case"ne":return n!==String(e.value);case"contains":return n.toLowerCase().includes(String(e.value).toLowerCase());case"gt":case"lt":{const o=s=>String(s).trim()!==""&&Number.isFinite(Number(s))?Number(s):NaN,i=o(n),c=o(e.value);if(!Number.isNaN(i)&&!Number.isNaN(c))return e.op==="gt"?i>c:i<c;const a=Date.parse(n),u=Date.parse(e.value);return!Number.isNaN(a)&&!Number.isNaN(u)?e.op==="gt"?a>u:a<u:e.op==="gt"?n>String(e.value):n<String(e.value)}default:return!0}}export const isFileRef=t=>!!t&&typeof t=="object"&&!Array.isArray(t)&&typeof t.url=="string"&&(typeof t.name=="string"||t.name===void 0),fileRefsOf=t=>(Array.isArray(t)?t:[t]).filter(isFileRef),isFileValue=t=>{const e=fileRefsOf(t);return e.length>0&&e.length===(Array.isArray(t)?t.length:1)};const b=t=>t.name||t.url.split("/").pop()||"file";export const safeFileHref=t=>/^(https?:\/\/|\/(?!\/))/i.test(String(t||""))?String(t):"";export function valueText(t){return t==null?"":typeof t=="boolean"?t?"Yes":"No":isFileRef(t)?b(t):Array.isArray(t)?t.map(e=>isFileRef(e)?b(e):e&&typeof e=="object"?JSON.stringify(e):String(e)).join(", "):typeof t=="object"?JSON.stringify(t):String(t)}export function shownValue(t,e){return e==null||e===""?e:t?.type==="date"?y(e):t?.type==="datetime"?d(e):e}export function cellText(t,e=60){const r=valueText(t).replace(/\s+/g," ").trim();return r.length>e?`${r.slice(0,e-1)}\u2026`:r}export function arrangeEntries(t,{filters:e=[],query:r="",sort:n={key:"created",dir:"desc"}}={}){const o=String(r||"").toLowerCase().trim();let i=(t||[]).filter(s=>e.every(p=>matchesFilter(s,p)));o&&(i=i.filter(s=>Object.values(s?.data||{}).some(p=>valueText(p).toLowerCase().includes(o))));const c=n?.dir==="asc"?1:-1,a=n?.key||"created",u=s=>a==="created"?String(s?.meta?.createdAt||""):s?.data?.[a];return[...i].sort((s,p)=>{const l=u(s),f=u(p),m=typeof l=="number"?l:parseFloat(l),g=typeof f=="number"?f:parseFloat(f);return a!=="created"&&!Number.isNaN(m)&&!Number.isNaN(g)&&String(m)===String(l??"").trim()&&String(g)===String(f??"").trim()?(m-g)*c:valueText(l).localeCompare(valueText(f),void 0,{numeric:!0,sensitivity:"base"})*c})}export function filterChoices(t,e){const r=valueText(e);if(r==="")return[];const n=valueText(shownValue(t,e)),o=n.length>28?`${n.slice(0,27)}\u2026`:n,i=[{op:"eq",value:r,label:`= \u201C${o}\u201D`},{op:"ne",value:r,label:`\u2260 \u201C${o}\u201D`}];return["number","date","time","datetime"].includes(t?.type)&&i.push({op:"gt",value:r,label:`> \u201C${o}\u201D`},{op:"lt",value:r,label:`< \u201C${o}\u201D`}),i}export function filterText(t){const e=String(t.value),r=/^\d{4}-\d{2}-\d{2}$/.test(e)?y(e):/^\d{4}-\d{2}-\d{2}T\d/.test(e)?d(e):e;return`${t.label} ${OP_LABELS[t.op]||t.op} \u201C${r.length>24?`${r.slice(0,23)}\u2026`:r}\u201D`}export function typedValue(t,e){if(t?.type==="number"&&typeof e=="string"&&e.trim()!==""){const r=Number(e);if(Number.isFinite(r))return r}return e}export function isSecretField(t){return t?.type==="password"||/pass(word)?|secret|token|api[-_]?key|private|credential/i.test(String(t?.name||""))}export function draftable(t,e=[]){const r=new Set(e.filter(isSecretField).map(n=>n.name));return Object.fromEntries(Object.entries(t||{}).filter(([n])=>!r.has(n)))}export function snapshot(t){const e=Object.keys(t||{}).sort();return JSON.stringify(e.map(r=>[r,typeof t[r]=="boolean"?t[r]:valueText(t[r])]))}export const hasForm=t=>!["roles","user-profiles"].includes(t),canClear=t=>t!=="roles";export function countText(t,e,r){const n=c=>c.toLocaleString("en-GB"),o=c=>`entr${c===1?"y":"ies"}`,i=t===e?`${n(e)} ${o(e)}`:`Showing ${n(t)} of ${n(e)}`;return r>e?`${i} \xB7 ${n(e)} of ${n(r)} loaded`:i}
1
+ import{fmtDate as y,fmtDateTime as d}from"./dates.js";export const OP_LABELS={eq:"=",ne:"\u2260",contains:"contains",gt:">",lt:"<"},MAX_COLUMNS=5;export function listColumns(t){return(Array.isArray(t)?t:[]).filter(e=>e&&e.listHidden!==!0).slice(0,MAX_COLUMNS)}export const PAGE_SIZE=500,SHOW_STEP=100;export function matchesFilter(t,e){const r=t?.data?.[e.field],n=String(r??"");switch(e.op){case"eq":return n===String(e.value);case"ne":return n!==String(e.value);case"contains":return n.toLowerCase().includes(String(e.value).toLowerCase());case"gt":case"lt":{const o=s=>String(s).trim()!==""&&Number.isFinite(Number(s))?Number(s):NaN,i=o(n),c=o(e.value);if(!Number.isNaN(i)&&!Number.isNaN(c))return e.op==="gt"?i>c:i<c;const a=Date.parse(n),u=Date.parse(e.value);return!Number.isNaN(a)&&!Number.isNaN(u)?e.op==="gt"?a>u:a<u:e.op==="gt"?n>String(e.value):n<String(e.value)}default:return!0}}export const isFileRef=t=>!!t&&typeof t=="object"&&!Array.isArray(t)&&typeof t.url=="string"&&(typeof t.name=="string"||t.name===void 0),fileRefsOf=t=>(Array.isArray(t)?t:[t]).filter(isFileRef),isFileValue=t=>{const e=fileRefsOf(t);return e.length>0&&e.length===(Array.isArray(t)?t.length:1)};const b=t=>t.name||t.url.split("/").pop()||"file";export const safeFileHref=t=>/^(https?:\/\/|\/(?!\/))/i.test(String(t||""))?String(t):"";export function valueText(t){return t==null?"":typeof t=="boolean"?t?"Yes":"No":isFileRef(t)?b(t):Array.isArray(t)?t.map(e=>isFileRef(e)?b(e):e&&typeof e=="object"?JSON.stringify(e):String(e)).join(", "):typeof t=="object"?JSON.stringify(t):String(t)}export function shownValue(t,e){return e==null||e===""?e:t?.type==="date"?y(e):t?.type==="datetime"?d(e):e}export function cellText(t,e=60){const r=valueText(t).replace(/\s+/g," ").trim();return r.length>e?`${r.slice(0,e-1)}\u2026`:r}export function arrangeEntries(t,{filters:e=[],query:r="",sort:n={key:"created",dir:"desc"}}={}){const o=String(r||"").toLowerCase().trim();let i=(t||[]).filter(s=>e.every(p=>matchesFilter(s,p)));o&&(i=i.filter(s=>Object.values(s?.data||{}).some(p=>valueText(p).toLowerCase().includes(o))));const c=n?.dir==="asc"?1:-1,a=n?.key||"created",u=s=>a==="created"?String(s?.meta?.createdAt||""):s?.data?.[a];return[...i].sort((s,p)=>{const l=u(s),f=u(p),m=typeof l=="number"?l:parseFloat(l),g=typeof f=="number"?f:parseFloat(f);return a!=="created"&&!Number.isNaN(m)&&!Number.isNaN(g)&&String(m)===String(l??"").trim()&&String(g)===String(f??"").trim()?(m-g)*c:valueText(l).localeCompare(valueText(f),void 0,{numeric:!0,sensitivity:"base"})*c})}export function filterChoices(t,e){const r=valueText(e);if(r==="")return[];const n=valueText(shownValue(t,e)),o=n.length>28?`${n.slice(0,27)}\u2026`:n,i=[{op:"eq",value:r,label:`= \u201C${o}\u201D`},{op:"ne",value:r,label:`\u2260 \u201C${o}\u201D`}];return["number","date","time","datetime"].includes(t?.type)&&i.push({op:"gt",value:r,label:`> \u201C${o}\u201D`},{op:"lt",value:r,label:`< \u201C${o}\u201D`}),i}export function filterText(t){const e=String(t.value),r=/^\d{4}-\d{2}-\d{2}$/.test(e)?y(e):/^\d{4}-\d{2}-\d{2}T\d/.test(e)?d(e):e;return`${t.label} ${OP_LABELS[t.op]||t.op} \u201C${r.length>24?`${r.slice(0,23)}\u2026`:r}\u201D`}export function typedValue(t,e){if(t?.type==="number"&&typeof e=="string"&&e.trim()!==""){const r=Number(e);if(Number.isFinite(r))return r}return e}export function isSecretField(t){return t?.type==="password"||/pass(word)?|secret|token|api[-_]?key|private|credential/i.test(String(t?.name||""))}export function draftable(t,e=[]){const r=new Set(e.filter(isSecretField).map(n=>n.name));return Object.fromEntries(Object.entries(t||{}).filter(([n])=>!r.has(n)))}export function snapshot(t){const e=Object.keys(t||{}).sort();return JSON.stringify(e.map(r=>[r,typeof t[r]=="boolean"?t[r]:valueText(t[r])]))}export const hasForm=t=>!["roles","user-profiles"].includes(t),canClear=t=>t!=="roles";export function countText(t,e,r){const n=c=>c.toLocaleString("en-GB"),o=c=>`entr${c===1?"y":"ies"}`,i=t===e?`${n(e)} ${o(e)}`:`Showing ${n(t)} of ${n(e)}`;return r>e?`${i} \xB7 ${n(e)} of ${n(r)} loaded`:i}
@@ -1 +1 @@
1
- export const SYSTEM_SLUGS=["roles","user-profiles"],FILTERS=["all","own","builtin","plugin"];const u="core";export function slugify(n){return String(n??"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}export function kindOf(n){return n?.builtIn===!0||n?.preset===!0||SYSTEM_SLUGS.includes(n?.slug)?"builtin":n?.plugin?"plugin":"own"}export const projectOf=n=>n?.meta?.project||u;export function arrangeCollections(n,{filter:t="all",query:e="",project:o=null}={}){const i=String(e).trim().toLowerCase();return[...n||[]].filter(r=>!o||projectOf(r)===o).filter(r=>t==="all"||kindOf(r)===t).filter(r=>!i||[r.title,r.slug,r.description,r.plugin].some(l=>String(l||"").toLowerCase().includes(i))).sort((r,l)=>String(r.title||r.slug).localeCompare(String(l.title||l.slug)))}export function kindCounts(n,{project:t=null}={}){const e=(n||[]).filter(i=>!t||projectOf(i)===t),o={all:e.length,own:0,builtin:0,plugin:0};for(const i of e)o[kindOf(i)]++;return o}const a=(n,t,e=`${t}s`)=>`${n} ${n===1?t:e}`;export function collectionRow(n){const t=kindOf(n),e=Array.isArray(n.fields)?n.fields.length:0,o=Number(n.entryCount)||0,i=n.storage?.adapter==="mongodb",r=n.meta?.project||"";return{slug:n.slug,title:n.title||n.slug,meta:[n.slug,a(e,"field"),r?`project ${r}`:""].filter(Boolean).join(" \xB7 "),entries:o,entriesText:o.toLocaleString("en-GB"),mongo:i,mongoTitle:i?`MongoDB - connection "${n.storage.connection||"default"}"`:"",builtin:t==="builtin",bundled:t!=="builtin"&&n.bundled===!0,plugin:n.plugin||"",pluginTitle:n.plugin?`Managed by the ${n.plugin} plugin`:"",canDelete:t!=="builtin",hasForm:!SYSTEM_SLUGS.includes(n.slug)}}export function checkNewCollection(n,t=[]){const e=String(n??"").trim(),o=slugify(e);return e?o?t.includes(o)?{slug:o,error:`"${o}" is already a collection.`}:{slug:o,error:""}:{slug:o,error:"The title needs at least one letter or number."}:{slug:"",error:""}}let s=0;export function connectionRows(n){return Object.entries(n||{}).filter(([t])=>t!=="_comment").map(([t,e])=>({id:`c${++s}`,name:t,uri:String(e?.uri||""),database:String(e?.database||""),options:e?.options&&typeof e.options=="object"?e.options:{}}))}export function newConnectionRow(n){const t=new Set((n||[]).map(o=>o.name));let e=(n||[]).length+1;for(;t.has(`connection${e}`);)e++;return{id:`c${++s}`,name:e===1&&!t.has("default")?"default":`connection${e}`,uri:"",database:""}}export function connectionsFromRows(n){const t=[],e={};for(const o of n||[]){const i=String(o.name??"").trim();if(!i){t.push("Every connection needs a name.");continue}if(e[i]){t.push(`Two connections are called "${i}".`);continue}const r=String(o.uri??"").trim(),l=String(o.database??"").trim();r||t.push(`"${i}" needs a URI.`),l||t.push(`"${i}" needs a database.`),e[i]={type:"mongodb",uri:r,database:l,options:o.options&&typeof o.options=="object"?o.options:{}}}return{errors:t,config:e}}export function parseConnectionsJson(n){let t;try{t=JSON.parse(String(n??"").trim()||"{}")}catch(e){return{error:`Not valid JSON: ${e.message}`,config:null}}return!t||typeof t!="object"||Array.isArray(t)?{error:"The JSON must be an object of named connections.",config:null}:{error:"",config:t}}export function maskUri(n){return String(n??"").replace(/(\/\/[^:/@]+:)([^@]+)(@)/,"$1\u2022\u2022\u2022$3")}
1
+ import{allTagsOf as c,matchesTag as g,tagsText as p,toolTagOf as f}from"./list-tags-arrange.js";export const SYSTEM_SLUGS=["roles","user-profiles"],FILTERS=["all","own","builtin","plugin"];const d="core";export function slugify(t){return String(t??"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}export function kindOf(t){return t?.builtIn===!0||t?.preset===!0||SYSTEM_SLUGS.includes(t?.slug)?"builtin":t?.plugin?"plugin":"own"}export const projectOf=t=>t?.meta?.project||d;export function arrangeCollections(t,{filter:n="all",query:e="",project:o=null,tag:r="",tools:l={}}={}){const s=String(e).trim().toLowerCase();return[...t||[]].filter(i=>!o||projectOf(i)===o).filter(i=>n==="all"||kindOf(i)===n).filter(i=>g(i,r,l)).filter(i=>!s||[i.title,i.slug,i.description,i.plugin,...c(i,l)].some(u=>String(u||"").toLowerCase().includes(s))).sort((i,u)=>String(i.title||i.slug).localeCompare(String(u.title||u.slug)))}export function kindCounts(t,{project:n=null}={}){const e=(t||[]).filter(r=>!n||projectOf(r)===n),o={all:e.length,own:0,builtin:0,plugin:0};for(const r of e)o[kindOf(r)]++;return o}const m=(t,n,e=`${n}s`)=>`${t} ${t===1?n:e}`;export function collectionRow(t,n={}){const e=kindOf(t),o=Array.isArray(t.fields)?t.fields.length:0,r=Number(t.entryCount)||0,l=t.storage?.adapter==="mongodb",s=t.meta?.project||"";return{slug:t.slug,title:t.title||t.slug,meta:[t.slug,m(o,"field"),s?`project ${s}`:""].filter(Boolean).join(" \xB7 "),entries:r,entriesText:r.toLocaleString("en-GB"),mongo:l,mongoTitle:l?`MongoDB - connection "${t.storage.connection||"default"}"`:"",builtin:e==="builtin",bundled:e!=="builtin"&&t.bundled===!0,plugin:t.plugin||"",pluginTitle:t.plugin?`Managed by the ${t.plugin} plugin`:"",listTags:p(t),toolTag:f(t,n),canDelete:e!=="builtin",hasForm:!SYSTEM_SLUGS.includes(t.slug)}}export function checkNewCollection(t,n=[]){const e=String(t??"").trim(),o=slugify(e);return e?o?n.includes(o)?{slug:o,error:`"${o}" is already a collection.`}:{slug:o,error:""}:{slug:o,error:"The title needs at least one letter or number."}:{slug:"",error:""}}let a=0;export function connectionRows(t){return Object.entries(t||{}).filter(([n])=>n!=="_comment").map(([n,e])=>({id:`c${++a}`,name:n,uri:String(e?.uri||""),database:String(e?.database||""),options:e?.options&&typeof e.options=="object"?e.options:{}}))}export function newConnectionRow(t){const n=new Set((t||[]).map(o=>o.name));let e=(t||[]).length+1;for(;n.has(`connection${e}`);)e++;return{id:`c${++a}`,name:e===1&&!n.has("default")?"default":`connection${e}`,uri:"",database:""}}export function connectionsFromRows(t){const n=[],e={};for(const o of t||[]){const r=String(o.name??"").trim();if(!r){n.push("Every connection needs a name.");continue}if(e[r]){n.push(`Two connections are called "${r}".`);continue}const l=String(o.uri??"").trim(),s=String(o.database??"").trim();l||n.push(`"${r}" needs a URI.`),s||n.push(`"${r}" needs a database.`),e[r]={type:"mongodb",uri:l,database:s,options:o.options&&typeof o.options=="object"?o.options:{}}}return{errors:n,config:e}}export function parseConnectionsJson(t){let n;try{n=JSON.parse(String(t??"").trim()||"{}")}catch(e){return{error:`Not valid JSON: ${e.message}`,config:null}}return!n||typeof n!="object"||Array.isArray(n)?{error:"The JSON must be an object of named connections.",config:null}:{error:"",config:n}}export function maskUri(t){return String(t??"").replace(/(\/\/[^:/@]+:)([^@]+)(@)/,"$1\u2022\u2022\u2022$3")}
@@ -1 +1 @@
1
- export const UNTAGGED=" untagged",MAX_TAG=40,same=(t,e)=>String(t).toLowerCase()===String(e).toLowerCase();export function normaliseTag(t){return typeof t!="string"?"":t.replace(/[\u0000-\u001f\u007f]/g,"").replace(/\s+/g," ").trim().slice(0,40)}export function normaliseActive(t){return t===UNTAGGED?UNTAGGED:normaliseTag(t)}export function tagsOf(t){const e=Array.isArray(t?.adminTags)?t.adminTags:t?.meta?.adminTags;return Array.isArray(e)?e.filter(o=>typeof o=="string"&&o):[]}export function matchesTag(t,e){if(!e)return!0;const o=tagsOf(t);return e===UNTAGGED?o.length===0:o.some(r=>same(r,e))}export const tagsText=t=>tagsOf(t).join(", ");export function tagCounts(t,e){const o=[],r=n=>{n&&!o.some(i=>same(i,n))&&o.push(n)};return(t||[]).forEach(r),(e||[]).forEach(n=>tagsOf(n).forEach(r)),o.sort((n,i)=>n.localeCompare(i,void 0,{sensitivity:"base"})).map(n=>({name:n,count:(e||[]).filter(i=>tagsOf(i).some(s=>same(s,n))).length}))}export function activeNote(t,e,o){if(!t)return"";const r=`${e} ${e===1?o.replace(/s$/,""):o}`;return t===UNTAGGED?`Showing ${r} with no tag.`:`Showing ${r} tagged "${t}".`}export function tagMenuItems({all:t,current:e,change:o,newTag:r}){const n=(t||[]).filter(a=>!e.some(l=>same(l,a))),s=[{label:"Add tag",icon:"tag",submenu:[...n.map(a=>({label:a,icon:"tag",action:()=>o({add:[a]})})),...n.length?[{type:"divider"}]:[],{label:"New tag\u2026",icon:"plus",action:r}]}];return e.length?s.push({label:"Remove tag",icon:"x",submenu:[...e.map(a=>({label:a,icon:"tag",action:()=>o({remove:[a]})})),...e.length>1?[{type:"divider"},{label:"Remove all tags",icon:"x",action:()=>o({tags:[]})}]:[]]}):s.push({label:"Remove tag",icon:"x",disabled:!0}),s}
1
+ export const UNTAGGED=" untagged",MAX_TAG=40,SHARED_TAG_KEY="lists.tag",PRESET_TOOL_COLLECTIONS=Object.freeze({"notes-notes":"notes","todo-items":"todo","contacts-contacts":"contacts","contacts-groups":"contacts"}),same=(t,e)=>String(t).toLowerCase()===String(e).toLowerCase();export function normaliseTag(t){return typeof t!="string"?"":t.replace(/[\u0000-\u001f\u007f]/g,"").replace(/\s+/g," ").trim().slice(0,40)}export function normaliseActive(t){return t===UNTAGGED?UNTAGGED:normaliseTag(t)}export function pickSharedTag(t,e){return t!=null?{tag:normaliseActive(t),migrate:!1}:{tag:normaliseActive(e),migrate:!0}}export function tagsOf(t){const e=Array.isArray(t?.adminTags)?t.adminTags:t?.meta?.adminTags;return Array.isArray(e)?e.filter(o=>typeof o=="string"&&o):[]}export function titleCaseSlug(t){return String(t||"").split(/[-_\s]+/).filter(Boolean).map(e=>e[0].toUpperCase()+e.slice(1)).join(" ")}export function toolOf(t){if(!t)return"";const e=o=>typeof o=="string"?o:"";return t.urlPath?e(t.plugin):typeof t.slug=="string"?e(t.plugin)||PRESET_TOOL_COLLECTIONS[t.slug]||"":e(t.meta?.plugin)}export function toolTagOf(t,e={}){const o=toolOf(t);if(!o)return"";const r=e&&Object.hasOwn(e,o)?e[o]:"";return normaliseTag(r||titleCaseSlug(o))}export function allTagsOf(t,e={}){const o=[];for(const r of[toolTagOf(t,e),...tagsOf(t)])r&&!o.some(a=>same(a,r))&&o.push(r);return o}export function matchesTag(t,e,o={}){if(!e)return!0;const r=allTagsOf(t,o);return e===UNTAGGED?r.length===0:r.some(a=>same(a,e))}export const tagsText=t=>tagsOf(t).join(", ");export function tagCounts(t,e,o={}){const r=[],a=[],i=n=>{n&&!r.some(s=>same(s,n))&&r.push(n)};for(const n of t||[]){const s=typeof n=="string"?n:n?.name;typeof n=="object"&&n?.tool&&s&&a.push(s),i(s)}for(const n of e||[]){const s=toolTagOf(n,o);s&&a.push(s),allTagsOf(n,o).forEach(i)}return r.sort((n,s)=>n.localeCompare(s,void 0,{sensitivity:"base"})).map(n=>({name:n,count:(e||[]).filter(s=>allTagsOf(s,o).some(u=>same(u,n))).length,tool:a.some(s=>same(s,n))}))}export const manualNames=t=>(t||[]).filter(e=>!e.tool).map(e=>e.name);export function toolNameClash(t,e=[],o={}){const r=normaliseTag(t);if(!r)return"";const i=[...(e||[]).filter(n=>n.tool).map(n=>n.name),...Object.values(o||{})].find(n=>same(n,r));return i?`"${i}" is a Tool's tag - the Tool adds it itself. Pick another name.`:""}export function activeNote(t,e,o){if(!t)return"";if(!e)return t===UNTAGGED?`No ${o} without a tag.`:`No ${o} tagged "${t}".`;const r=`${e} ${e===1?o.replace(/s$/,""):o}`;return t===UNTAGGED?`Showing ${r} with no tag.`:`Showing ${r} tagged "${t}".`}export function tagMenuItems({all:t,current:e,change:o,newTag:r,reserved:a=[]}){const i=e||[],n=(t||[]).filter(c=>!a.some(l=>same(l,c))&&!i.some(l=>same(l,c))),u=[{label:"Add tag",icon:"tag",submenu:[...n.map(c=>({label:c,icon:"tag",action:()=>o({add:[c]})})),...n.length?[{type:"divider"}]:[],{label:"New tag\u2026",icon:"plus",action:r}]}];return i.length?u.push({label:"Remove tag",icon:"x",submenu:[...i.map(c=>({label:c,icon:"tag",action:()=>o({remove:[c]})})),...i.length>1?[{type:"divider"},{label:"Remove all tags",icon:"x",action:()=>o({tags:[]})}]:[]]}):u.push({label:"Remove tag",icon:"x",disabled:!0}),u}
@@ -1,4 +1,4 @@
1
- import{api as b}from"../api.js";import{helpPopovers as H}from"./help-popover.js";import{onceClosed as P,promptWith as U}from"./tool-kit.js";import{MAX_TAG as S,UNTAGGED as K,normaliseActive as W,normaliseTag as C,same as N}from"./list-tags-arrange.js";export*from"./list-tags-arrange.js";const x=a=>String(a??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;");export async function askTagName({title:a="New tag",value:l="",confirmText:u="Add"}={}){const p=await U(`Up to ${S} characters. Tags are only seen here in the admin.`,{title:a,inputPlaceholder:"e.g. Spring campaign",confirmText:u},l);return p==null?"":C(String(p))}let w=!1;function X(){if(w||document.getElementById("ltg-styles")){w=!0;return}const a=document.createElement("style");a.id="ltg-styles",a.textContent=`
1
+ import{api as $}from"../api.js";import{helpPopovers as j}from"./help-popover.js";import{onceClosed as J,promptWith as O}from"./tool-kit.js";import{MAX_TAG as L,SHARED_TAG_KEY as B,UNTAGGED as Q,normaliseActive as V,normaliseTag as G,pickSharedTag as Z,same as A,toolNameClash as H}from"./list-tags-arrange.js";export*from"./list-tags-arrange.js";const N=o=>String(o??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;");export async function askTagName({title:o="New tag",value:n="",confirmText:c="Add"}={}){const r=await O(`Up to ${L} characters. Tags are only seen here in the admin.`,{title:o,inputPlaceholder:"e.g. Spring campaign",confirmText:c},n);return r==null?"":G(String(r))}export async function askManualTagName(o,n={},c={}){const r=await askTagName(c),s=r&&H(r,o,n);return s?(E.toast(s,{type:"error"}),""):r}export function sharedTagFilter(o){let n;try{n=S.get(B)}catch{}const{tag:c,migrate:r}=Z(n,o),s=M.observable(c);let g=r&&!c;const f=M.effect(()=>{const m=s.value;if(!(g&&m===c)){g=!1;try{S.set(B,m)}catch{}}});return{tag:s,dispose:f}}let C=!1;function ee(){if(C||document.getElementById("ltg-styles")){C=!0;return}const o=document.createElement("style");o.id="ltg-styles",o.textContent=`
2
2
  .ltg-panel { display: flex; flex-direction: column; gap: 1rem; padding: .25rem 0 .5rem; }
3
3
  .ltg-panel .form-label { display: flex; align-items: center; gap: .3rem; font-weight: 500; margin-bottom: .3rem; }
4
4
  .ltg-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; border: 1px solid var(--dm-border); border-radius: var(--dm-radius-md); }
@@ -13,25 +13,27 @@ import{api as b}from"../api.js";import{helpPopovers as H}from"./help-popover.js"
13
13
  .ltg-add { display: flex; gap: .4rem; }
14
14
  .ltg-add .form-input { flex: 1; }
15
15
  .ltg-meta { font-size: var(--dm-text-xs); color: var(--dm-text-muted); }
16
+ .ltg-list li.is-tool .ltg-name { display: inline-flex; align-items: center; gap: .3rem; }
17
+ .ltg-tool-note { display: inline-flex; align-items: center; gap: .25rem; color: var(--dm-text-muted); font-size: var(--dm-text-xs); white-space: nowrap; }
16
18
  .ltg-actions { display: flex; align-items: center; gap: .5rem; padding-top: .75rem; border-top: 1px solid var(--dm-border); }
17
- .ltg-actions .spacer { flex: 1; }`,document.head.appendChild(a),w=!0}export function openTagSettings({kind:a,noun:l,title:u,tags:p,active:i,reload:A}){X();const d=E.slideover({title:u,size:"sm",position:"right"}),$=document.createElement("template");$.innerHTML=`
19
+ .ltg-actions .spacer { flex: 1; }`,document.head.appendChild(o),C=!0}export function openTagSettings({kind:o,noun:n,title:c,tags:r,active:s,reload:g,tools:f=null}){ee();const m=E.slideover({title:c,size:"sm",position:"right"}),q=document.createElement("template");q.innerHTML=`
18
20
  <div class="ltg-panel">
19
21
  <div>
20
22
  <label class="form-label" for="ltg-show">Show
21
- <span data-help="Narrow the list to the ${l} wearing one tag. Remembered in this browser; everyone else keeps their own choice."></span></label>
23
+ <span data-help="Narrow the list to the ${n} wearing one tag. Remembered in this browser and kept the same on the Pages, Blocks and Collections lists until you clear it; everyone else keeps their own choice."></span></label>
22
24
  <select id="ltg-show" class="form-input"></select>
23
25
  </div>
24
26
  <div>
25
27
  <label class="form-label">Tags
26
- <span data-help="Tags link ${l} together - an item can wear several. They are seen only here in the admin, never on the site. Right-click any of the ${l} to add or remove one. Deleting a tag takes it off its ${l}; nothing else changes."></span></label>
28
+ <span data-help="Tags link ${n} together - an item can wear several. They are seen only here in the admin, never on the site. Right-click any of the ${n} to add or remove one. Deleting a tag takes it off its ${n}; nothing else changes. A Tool's tag (with the package icon) is added by the Tool to everything it owns, so it cannot be removed, renamed or deleted."></span></label>
27
29
  <ul class="ltg-list"></ul>
28
30
  <p class="ltg-empty">No tags yet.</p>
29
31
  </div>
30
32
  <div class="ltg-add">
31
- <input type="text" class="form-input" maxlength="${S}" placeholder="New tag" aria-label="New tag">
33
+ <input type="text" class="form-input" maxlength="${L}" placeholder="New tag" aria-label="New tag">
32
34
  <button type="button" class="btn btn-sm btn-primary">Add</button>
33
35
  </div>
34
- <small class="ltg-meta">Tags are shared by everyone who edits ${l}.</small>
36
+ <small class="ltg-meta">Tags are shared by everyone who edits ${n}.</small>
35
37
  <div class="ltg-actions"><span class="spacer"></span>
36
38
  <button type="button" class="btn btn-sm btn-primary ltg-done">Done</button></div>
37
- </div>`;const o=$.content.firstElementChild,g=o.querySelector("#ltg-show"),f=o.querySelector(".ltg-list"),q=o.querySelector(".ltg-empty"),m=o.querySelector(".ltg-add input");let h=!1;const y=(e,n)=>{const t=document.createElement("option");return t.value=e,t.textContent=n,t},T=(e,n,t,c)=>{const r=document.createElement("button");r.type="button",r.title=n,r.setAttribute("aria-label",n),t&&(r.className=t);const s=document.createElement("span");return s.setAttribute("data-icon",e),s.setAttribute("data-icon-size","14"),r.appendChild(s),r.addEventListener("click",c),r};async function v(e,n){if(!h){h=!0;try{const t=await e();return await A(),n&&E.toast(n(t),{type:"success"}),!0}catch(t){return E.toast(t.message||"That did not work.",{type:"error"}),!1}finally{h=!1}}}async function D(e){const n=await askTagName({title:`Rename "${x(e)}"`,value:e,confirmText:"Rename"});if(!n||n===e)return;await v(()=>b.listTags.rename(a,e,n),c=>`Renamed - ${c.changed} ${l} updated.`)&&N(i.peek(),e)&&(i.value=n)}async function R(e){const n=e.count?`Delete the tag "${x(e.name)}"? It comes off ${e.count} ${e.count===1?l.replace(/s$/,""):l}; nothing else about them changes.`:`Delete the tag "${x(e.name)}"?`;if(!await E.confirm(n))return;await v(()=>b.listTags.remove(a,e.name),()=>"Tag deleted.")&&N(i.peek(),e.name)&&(i.value="")}async function k(){const e=C(m.value);if(!e){m.focus();return}await v(()=>b.listTags.add(a,e)),m.value="",m.focus()}const L=M.effect(()=>{const e=p.value,n=i.value;g.replaceChildren(y("",`All ${l}`),y(K,"No tag"),...e.map(t=>y(t.name,`${t.name} (${t.count})`))),g.value=n,f.replaceChildren(...e.map(t=>{const c=document.createElement("li"),r=document.createElement("span");r.className="ltg-name",r.textContent=t.name;const s=document.createElement("span");return s.className="ltg-count",s.textContent=String(t.count),c.append(r,s,T("edit",`Rename ${t.name}`,"",()=>D(t.name)),T("trash",`Delete ${t.name}`,"is-danger",()=>R(t))),c})),f.hidden=!e.length,q.hidden=e.length>0,I.scan(f)}),z=()=>{i.value=W(g.value)},G=e=>{e.key==="Enter"&&e.target===m&&(e.preventDefault(),k())};g.addEventListener("change",z),o.addEventListener("keydown",G),o.querySelector(".ltg-add button").addEventListener("click",k),o.querySelector(".ltg-done").addEventListener("click",()=>d.close()),d.element.appendChild(o);const B=H(o);return P(d,()=>{L(),B()}),I.scan(o),d.open(),d}
39
+ </div>`;const i=q.content.firstElementChild,h=i.querySelector("#ltg-show"),b=i.querySelector(".ltg-list"),P=i.querySelector(".ltg-empty"),u=i.querySelector(".ltg-add input");let v=!1;const x=(e,a)=>{const t=document.createElement("option");return t.value=e,t.textContent=a,t},z=(e,a,t,d)=>{const l=document.createElement("button");l.type="button",l.title=a,l.setAttribute("aria-label",a),t&&(l.className=t);const p=document.createElement("span");return p.setAttribute("data-icon",e),p.setAttribute("data-icon-size","14"),l.appendChild(p),l.addEventListener("click",d),l};async function w(e,a){if(!v){v=!0;try{const t=await e();return await g(),a&&E.toast(a(t),{type:"success"}),!0}catch(t){return E.toast(t.message||"That did not work.",{type:"error"}),!1}finally{v=!1}}}const _=()=>(f?f.peek():{})||{},D=e=>{const a=H(e,r.peek(),_());return a&&E.toast(a,{type:"error"}),!!a};async function K(e){const a=await askTagName({title:`Rename "${N(e)}"`,value:e,confirmText:"Rename"});if(!a||a===e||!A(a,e)&&D(a))return;await w(()=>$.listTags.rename(o,e,a),d=>`Renamed - ${d.changed} ${n} updated.`)&&A(s.peek(),e)&&(s.value=a)}async function U(e){const a=e.count?`Delete the tag "${N(e.name)}"? It comes off ${e.count} ${e.count===1?n.replace(/s$/,""):n}; nothing else about them changes.`:`Delete the tag "${N(e.name)}"?`;if(!await E.confirm(a))return;await w(()=>$.listTags.remove(o,e.name),()=>"Tag deleted.")&&A(s.peek(),e.name)&&(s.value="")}async function R(){const e=G(u.value);if(!e){u.focus();return}if(D(e)){u.focus();return}await w(()=>$.listTags.add(o,e)),u.value="",u.focus()}const F=M.effect(()=>{const e=r.value,a=s.value;h.replaceChildren(x("",`All ${n}`),x(Q,"No tag"),...e.map(t=>x(t.name,`${t.name} (${t.count})${t.tool?" - Tool":""}`))),h.value=a,b.replaceChildren(...e.map(t=>{const d=document.createElement("li"),l=document.createElement("span");l.className="ltg-name",l.textContent=t.name;const p=document.createElement("span");if(p.className="ltg-count",p.textContent=String(t.count),t.tool){d.className="is-tool";const T=document.createElement("span");T.setAttribute("data-icon","package"),T.setAttribute("data-icon-size","13"),l.prepend(T);const y=document.createElement("span");y.className="ltg-tool-note",y.title="Every item the Tool owns wears this tag. It cannot be renamed or deleted.";const k=document.createElement("span");return k.setAttribute("data-icon","lock"),k.setAttribute("data-icon-size","12"),y.append(k,document.createTextNode("added by the Tool")),d.append(l,p,y),d}return d.append(l,p,z("edit",`Rename ${t.name}`,"",()=>K(t.name)),z("trash",`Delete ${t.name}`,"is-danger",()=>U(t))),d})),b.hidden=!e.length,P.hidden=e.length>0,I.scan(b)}),W=()=>{s.value=V(h.value)},X=e=>{e.key==="Enter"&&e.target===u&&(e.preventDefault(),R())};h.addEventListener("change",W),i.addEventListener("keydown",X),i.querySelector(".ltg-add button").addEventListener("click",R),i.querySelector(".ltg-done").addEventListener("click",()=>m.close()),m.element.appendChild(i);const Y=j(i);return J(m,()=>{F(),Y()}),I.scan(i),m.open(),m}
@@ -1 +1 @@
1
- import{fmtDate as d}from"./dates.js";import{matchesTag as c,normaliseActive as f,tagsOf as h,tagsText as g}from"./list-tags-arrange.js";export const STATUSES=["all","published","draft"],SORTS=["order","updated","title","url"],MODES=["list","tree"],DEFAULT_SETTINGS={status:"all",sort:"order",mode:"list",tag:""};const u=(t,e,r=`${e}s`)=>`${t} ${t===1?e:r}`;export function normaliseSettings(t){const e=t&&typeof t=="object"?t:{};return{status:STATUSES.includes(e.status)?e.status:DEFAULT_SETTINGS.status,sort:SORTS.includes(e.sort)?e.sort:DEFAULT_SETTINGS.sort,mode:MODES.includes(e.mode)?e.mode:DEFAULT_SETTINGS.mode,tag:f(e.tag)}}export function ago(t,e=Date.now()){const r=new Date(t).getTime();if(!Number.isFinite(r))return"";const o=Math.max(0,Math.round((e-r)/1e3));return o<60?"just now":o<3600?`${Math.round(o/60)} min ago`:o<86400?`${u(Math.round(o/3600),"hour")} ago`:o<86400*14?`${u(Math.round(o/86400),"day")} ago`:d(r)}export function visibilityLabel(t){const e=String(t??"public").trim();return!e||e==="public"?"":e==="private"?"Private":e.startsWith("=")?`Only ${e.slice(1)}`:`${e}+`}const m=t=>`${t.title||""} ${t.urlPath||""} ${(t.tags||[]).join(" ")} ${h(t).join(" ")} ${t.layout||""}`.toLowerCase();export function arrangePages(t,{status:e="all",query:r="",sort:o="order",tag:s=""}={}){const n=String(r).trim().toLowerCase(),a=(t||[]).filter(i=>e==="all"||(e==="draft"?i.status!=="published":i.status==="published")).filter(i=>c(i,s)).filter(i=>!n||m(i).includes(n));return o==="updated"?[...a].sort((i,l)=>String(l.updatedAt||"").localeCompare(String(i.updatedAt||""))):o==="title"?[...a].sort((i,l)=>String(i.title||"").localeCompare(String(l.title||""))):o==="url"?[...a].sort((i,l)=>String(i.urlPath).localeCompare(String(l.urlPath))):a}export function statusCounts(t){const e=(t||[]).length,r=(t||[]).filter(o=>o.status==="published").length;return{all:e,published:r,draft:e-r}}export function pageRow(t,e=Date.now()){const r=t.status!=="published",o=Number.isFinite(t.versionCount)?t.versionCount:0,s=t.resolvedProject&&t.resolvedProject!=="core"?t.resolvedProject:"";return{urlPath:t.urlPath,title:t.title||t.urlPath,statusText:t.status==="review"?"Review":r?"Draft":"Published",statusCls:r?"is-warn":"is-ok",visibility:visibilityLabel(t.visibility),project:s,plugin:t.plugin?String(t.plugin):"",bundled:t.bundled===!0,tagsText:(t.tags||[]).filter(Boolean).map(n=>`#${n}`).join(" "),listTags:g(t),meta:[t.urlPath,t.layout||"default",u(o,"revision"),t.updatedAt?`updated ${ago(t.updatedAt,e)}`:""].filter(Boolean).join(" \xB7 "),revisions:o,rowCls:r?"is-draft":""}}export function treeRows(t){const e=new Set((t||[]).map(r=>r.urlPath));return(t||[]).map(r=>{const o=String(r.urlPath).split("/").filter(Boolean);let s=null;for(let n=o.length-1;n>0&&!s;n--){const a="/"+o.slice(0,n).join("/");e.has(a)&&(s=a)}return{id:r.urlPath,parent_id:s,name:r.title||r.urlPath,icon:r.status==="published"?"check-circle":"file-text"}})}export function checkPrune(t,e){const r=String(t??"").trim();if(!/^\d+$/.test(r))return{error:"A whole number, 0 or more.",keep:0,deletes:0};const o=Number.parseInt(r,10);return{error:"",keep:o,deletes:Math.max(0,(Number(e)||0)-o)}}
1
+ import{fmtDate as c}from"./dates.js";import{allTagsOf as f,matchesTag as g,normaliseActive as h,tagsText as m,toolTagOf as b}from"./list-tags-arrange.js";export const STATUSES=["all","published","draft"],SORTS=["order","updated","title","url"],MODES=["list","tree"],DEFAULT_SETTINGS={status:"all",sort:"order",mode:"list",tag:""};const d=(t,e,r=`${e}s`)=>`${t} ${t===1?e:r}`;export function normaliseSettings(t){const e=t&&typeof t=="object"?t:{};return{status:STATUSES.includes(e.status)?e.status:DEFAULT_SETTINGS.status,sort:SORTS.includes(e.sort)?e.sort:DEFAULT_SETTINGS.sort,mode:MODES.includes(e.mode)?e.mode:DEFAULT_SETTINGS.mode,tag:h(e.tag)}}export function ago(t,e=Date.now()){const r=new Date(t).getTime();if(!Number.isFinite(r))return"";const o=Math.max(0,Math.round((e-r)/1e3));return o<60?"just now":o<3600?`${Math.round(o/60)} min ago`:o<86400?`${d(Math.round(o/3600),"hour")} ago`:o<86400*14?`${d(Math.round(o/86400),"day")} ago`:c(r)}export function visibilityLabel(t){const e=String(t??"public").trim();return!e||e==="public"?"":e==="private"?"Private":e.startsWith("=")?`Only ${e.slice(1)}`:`${e}+`}const p=(t,e)=>`${t.title||""} ${t.urlPath||""} ${(t.tags||[]).join(" ")} ${f(t,e).join(" ")} ${t.layout||""}`.toLowerCase();export function arrangePages(t,{status:e="all",query:r="",sort:o="order",tag:n="",tools:s={}}={}){const a=String(r).trim().toLowerCase(),u=(t||[]).filter(i=>e==="all"||(e==="draft"?i.status!=="published":i.status==="published")).filter(i=>g(i,n,s)).filter(i=>!a||p(i,s).includes(a));return o==="updated"?[...u].sort((i,l)=>String(l.updatedAt||"").localeCompare(String(i.updatedAt||""))):o==="title"?[...u].sort((i,l)=>String(i.title||"").localeCompare(String(l.title||""))):o==="url"?[...u].sort((i,l)=>String(i.urlPath).localeCompare(String(l.urlPath))):u}export function statusCounts(t){const e=(t||[]).length,r=(t||[]).filter(o=>o.status==="published").length;return{all:e,published:r,draft:e-r}}export function pageRow(t,e=Date.now(),r={}){const o=t.status!=="published",n=Number.isFinite(t.versionCount)?t.versionCount:0,s=t.resolvedProject&&t.resolvedProject!=="core"?t.resolvedProject:"";return{urlPath:t.urlPath,title:t.title||t.urlPath,statusText:t.status==="review"?"Review":o?"Draft":"Published",statusCls:o?"is-warn":"is-ok",visibility:visibilityLabel(t.visibility),project:s,plugin:t.plugin?String(t.plugin):"",bundled:t.bundled===!0,tagsText:(t.tags||[]).filter(Boolean).map(a=>`#${a}`).join(" "),listTags:m(t),toolTag:b(t,r),meta:[t.urlPath,t.layout||"default",d(n,"revision"),t.updatedAt?`updated ${ago(t.updatedAt,e)}`:""].filter(Boolean).join(" \xB7 "),revisions:n,rowCls:o?"is-draft":""}}export function treeRows(t){const e=new Set((t||[]).map(r=>r.urlPath));return(t||[]).map(r=>{const o=String(r.urlPath).split("/").filter(Boolean);let n=null;for(let s=o.length-1;s>0&&!n;s--){const a="/"+o.slice(0,s).join("/");e.has(a)&&(n=a)}return{id:r.urlPath,parent_id:n,name:r.title||r.urlPath,icon:r.status==="published"?"check-circle":"file-text"}})}export function checkPrune(t,e){const r=String(t??"").trim();if(!/^\d+$/.test(r))return{error:"A whole number, 0 or more.",keep:0,deletes:0};const o=Number.parseInt(r,10);return{error:"",keep:o,deletes:Math.max(0,(Number(e)||0)-o)}}
@@ -1,3 +1,3 @@
1
- import{convertSelectionToBlock as Q}from"./selection-to-block.js";import{EDITOR_TOOLS as Z,SHORTCODES as R}from"./shortcode-registry.js";import{EFFECTS as _,CELEBRATION_THEMES as ee,getEffectAttrs as H}from"./effect-defs.js";import{boolState as te,boolValue as ne,findEnclosingShortcode as oe,setAttr as z,setAttrs as W,effectAttrKeys as se}from"./shortcode-tags.js";import{insertAtCursor as O,replaceRange as ie}from"./markdown-toolbar.js";import{clearLookupCache as ce,lookupOptions as ae}from"./shortcode-lookups.js";import{insertMenuGroups as le,insertShortcodeByName as j}from"./shortcode-insert.js";import{openShortcodeForm as M}from"./shortcode-form.js";import{pickMedia as re}from"./media-picker.js";import{blockTagSnippet as de}from"./block-tags.js";import{catalogueNow as pe,dommaHelp as me}from"./domma-catalogue.js";function ue(e){return ae(e,l?.span?.attrs||{})}const fe=R.map(e=>({name:e.name,selfClosing:!!e.selfClosing})),F=new Map(R.map(e=>[e.name,e])),B=new Map(_.map(e=>[e.name,e])),he=_.map(e=>({name:e.name,selfClosing:!!e.selfClosing})),be=[...fe,...he],Y=new Set(["card","box","hero","banner","col","button"]);let l=null;const q="position:fixed;z-index:10000;min-width:210px;max-height:70vh;overflow-y:auto;background:var(--dm-surface,#1c1c30);border:1px solid var(--dm-border,#2a2a40);border-radius:6px;box-shadow:var(--dm-shadow-lg);padding:.3rem;font-size:.83rem;color:var(--dm-text,#e5e5e5);",u="display:flex;align-items:center;gap:.5rem;width:100%;text-align:left;padding:.35rem .55rem;border:none;background:transparent;color:inherit;border-radius:4px;cursor:pointer;font-size:.83rem;",k="padding:.3rem .55rem;color:var(--dm-text-muted,#8a8a9a);font-size:.68rem;text-transform:uppercase;letter-spacing:.06em;",P="flex:1;min-width:0;padding:.2rem .4rem;background:var(--dm-input-bg,#12121e);border:1px solid var(--dm-border,#333);border-radius:3px;color:var(--dm-text,#eee);font-size:.8rem;",xe="height:1px;background:var(--dm-border,#2a2a40);margin:.3rem .2rem;";function f(e){return e.addEventListener("mouseenter",()=>{e.style.background="var(--dm-primary,#4338ca)",e.style.color="var(--dm-primary-text,#fff)"}),e.addEventListener("mouseleave",()=>{e.style.background="transparent",e.style.color="inherit"}),e}export function attachContextMenu(e,{blocks:t=()=>[],openBlock:n=null}={}){const o=()=>{const i=t()||[],s=i.filter(a=>a.shortTag&&!F.has(a.name)&&!B.has(a.name));return{defs:i,specs:[...be,...s.map(a=>({name:a.name,selfClosing:!0}))]}},c=(i,s)=>{p();const{defs:a,specs:r}=o();G(e,oe(e,r),i,s,a,n)};return typeof Domma>"u"||!Domma.elements?.contextMenu?(e.addEventListener("contextmenu",i=>{i.preventDefault(),c(i.clientX,i.clientY)}),null):Domma.elements.contextMenu(e,{inherit:!1,cursor:!1,render:i=>{c(i.x,i.y)}})}function p(){l&&(L(),l.root.remove(),document.removeEventListener("mousedown",U,!0),document.removeEventListener("keydown",V,!0),window.removeEventListener("scroll",K,!0),l=null)}const U=e=>{l&&!l.root.contains(e.target)&&!(l.submenu&&l.submenu.contains(e.target))&&p()},K=e=>{l&&!l.root.contains(e.target)&&!(l.submenu&&l.submenu.contains(e.target))&&p()},V=e=>{e.key==="Escape"&&p()};function G(e,t,n,o,c=[],i=null){ce();const s=document.createElement("div");s.className="dm-sc-menu",s.style.cssText=q,l={root:s,textarea:e,span:t,submenu:null,blocks:c,openBlock:i,keepEmpty:!1};const a=new Map(c.map(x=>[x.name,x])),r=t&&(F.get(t.name)||B.get(t.name)),d=t&&(r?t.name==="block"?a.get(String(t.attrs.template||"")):null:a.get(t.name)),b=t&&Y.has(t.name)?_.filter(x=>x.name in t.attrs):[];r&&ye(s,r),d&&Ee(s,d,!!r);for(const x of b)_e(s,x);(r||d||b.length)&&s.appendChild(S()),s.appendChild(C("Celebrations\u2026",()=>Se())),s.appendChild(C("Add effect\u2026",()=>$e())),s.appendChild(C("Insert\u2026",()=>Ae()));const m=e.selectionStart!==e.selectionEnd;if(m&&e.value.slice(e.selectionStart,e.selectionEnd).trim()){const x={start:e.selectionStart,end:e.selectionEnd,source:e.value},y=f(document.createElement("button"));y.type="button",y.style.cssText=u,y.textContent="Convert selection to Domma Block\u2026",y.addEventListener("click",()=>{p(),Q(e,x)}),s.appendChild(y)}(t||m)&&s.appendChild(C(m?"Wrap selection in\u2026":"Wrap in\u2026",()=>Ie())),c.length&&(s.appendChild(S()),s.appendChild(C("Add block\u2026",()=>Me()))),document.body.appendChild(s),J(s,n,o),document.addEventListener("mousedown",U,!0),document.addEventListener("keydown",V,!0),window.addEventListener("scroll",K,!0),window.I&&I.scan(s)}function S(){const e=document.createElement("div");return e.style.cssText=xe,e}function w(e){const t=document.createElement("div");return t.style.cssText=k,t.textContent=e,t}function ye(e,t){e.appendChild(w(`${t.label} options`));const n=f(document.createElement("button"));n.type="button",n.style.cssText=u,n.innerHTML='<span data-icon="edit" data-icon-size="13" style="display:inline-flex;align-items:center;"></span>',n.appendChild(document.createTextNode(`Edit ${t.label}\u2026`)),n.addEventListener("click",()=>{const{textarea:i,span:s}=l;p(),M(i,{...t,attrs:H(t,s.attrs)},{span:s})}),e.appendChild(n);for(const i of t.actions||[]){const s=f(document.createElement("button"));s.type="button",s.style.cssText=u,s.innerHTML=`<span data-icon="${i.icon||"zap"}" data-icon-size="13" style="display:inline-flex;align-items:center;"></span>`,s.appendChild(document.createTextNode(i.label)),s.addEventListener("click",()=>{const{textarea:a,span:r}=l;if(i.remove){ie(a,r.openTagStart,r.openTagEnd,""),p();return}l.span=W(a,r,i.set||{}),p()}),e.appendChild(s)}const o=Array.isArray(t.quickAttrs)?new Set(t.quickAttrs):null,c=H(t,l.span.attrs).filter(i=>!o||o.has(i.name));(t.actions||[]).length&&c.length&&e.appendChild(S());for(const i of c)e.appendChild(D(i))}function Ee(e,t,n){const{span:o}=l;if(l.keepEmpty=!0,n&&e.appendChild(S()),e.appendChild(w(n?`${t.name} parameters`:`${t.name} block`)),t.description&&!n){const s=document.createElement("div");s.style.cssText="padding:0 .55rem .3rem;font-size:.75rem;color:var(--dm-text-muted,#9a9aac);max-width:260px;",s.textContent=t.description,e.appendChild(s)}const c=(s,a,r)=>{const d=f(document.createElement("button"));d.type="button",d.style.cssText=u,d.innerHTML=`<span data-icon="${s}" data-icon-size="13" style="display:inline-flex;align-items:center;"></span>`,d.appendChild(document.createTextNode(a)),d.addEventListener("click",r),e.appendChild(d)};t.attrs.length&&c("edit","Edit parameters\u2026",()=>{const{textarea:s}=l;p(),M(s,{...t,name:o.name,label:t.name},{span:o})});const{openBlock:i}=l;c(i?"layout":"external-link",i?"Edit the block":"Open the block",()=>{p(),i?i(t.name):location.hash=`#/blocks/edit/${encodeURIComponent(t.name)}`});for(const s of t.attrs)e.appendChild(D(s));if(!t.attrs.length){const s=document.createElement("div");s.style.cssText=k+"text-transform:none;letter-spacing:0;",s.textContent="This block takes no parameters.",e.appendChild(s)}}function D(e,t=e.name){const n=Ce(e,t),o=e.domma?me(pe(),e):"";return o&&n&&!n.title&&(n.title=o),n}function Ce(e,t){const n=l.span.attrs[t];switch(e.type){case"checkbox":return ge(e,t,te(n,e.default));case"select":return Te(e,t,n);case"lookup":return Le(e,t,n);case"colour":return we(e,t,n);case"icon":return ke(e,t,n);default:return ve(e,t,n)}}function T(e,t){if(l.span=z(l.textarea,l.span,e,l.keepEmpty&&t==null?"":t,{keepEmpty:l.keepEmpty}),e==="theme"){const{textarea:n,span:o,root:c}=l,i=c.getBoundingClientRect(),{blocks:s,openBlock:a}=l;p(),G(n,o,i.left,i.top,s,a)}}function ge(e,t,n){const o=f(document.createElement("label"));o.style.cssText=u;const c=document.createElement("input");return c.type="checkbox",c.checked=n,c.addEventListener("change",()=>T(t,ne(e,c.checked))),o.appendChild(c),o.appendChild(document.createTextNode(e.label)),o}function ve(e,t,n){const o=document.createElement("div");o.style.cssText=u+"cursor:default;";const c=document.createElement("span");c.textContent=e.label,c.style.cssText="white-space:nowrap;color:var(--dm-text-muted,#9a9aac);";const i=document.createElement("input");i.type=e.type==="number"?"number":"text",i.value=n===!0||n==null?"":n,e.default!=null&&e.default!==""&&(i.placeholder=String(e.default)),i.style.cssText=P;let s=null;if(i.addEventListener("input",()=>{clearTimeout(s),s=setTimeout(()=>T(t,i.value.trim()),180)}),i.addEventListener("mousedown",a=>a.stopPropagation()),o.appendChild(c),o.appendChild(i),e.type==="image"){const a=document.createElement("button");a.type="button",a.textContent="Browse",a.title="Choose from Media",a.style.cssText="padding:2px 8px;background:transparent;border:1px solid var(--dm-border,#333);border-radius:4px;color:inherit;cursor:pointer;flex-shrink:0;font:inherit;",a.addEventListener("mousedown",r=>r.stopPropagation()),a.addEventListener("click",async()=>{const{textarea:r,span:d}=l;p();const b=await re({current:i.value.trim()});b&&r.isConnected&&z(r,d,t,b)}),o.appendChild(a)}return o}function we(e,t,n){const o=document.createElement("div");o.style.cssText=u+"cursor:default;";const c=document.createElement("span");c.textContent=e.label,c.style.flex="1";const i=document.createElement("input");return i.type="color",typeof n=="string"&&/^#/.test(n)?i.value=n:typeof e.default=="string"&&/^#/.test(e.default)&&(i.value=e.default),i.addEventListener("input",()=>T(t,i.value)),o.appendChild(c),o.appendChild(i),o}function Te(e,t,n){const o=n==null||n===!0?e.default??"":n;return C(`${e.label}${o!==""?`: ${o}`:""}`,()=>{const c=g();for(const[i,s]of e.options||[]){const a=f(document.createElement("button"));a.type="button",a.style.cssText=u,a.textContent=s,i===o&&(a.style.fontWeight="700"),a.addEventListener("click",()=>{T(t,i),L()}),c.appendChild(a)}return c})}function ke(e,t,n){const o=n==null||n===!0?"":String(n),c=o?`${e.label}: ${o}`:e.label;return C(c,()=>{const i=g();i.style.width="232px";const s=document.createElement("input");s.type="text",s.placeholder="Search icons\u2026",s.style.cssText=P+"margin:6px;width:calc(100% - 12px);",s.addEventListener("mousedown",x=>x.stopPropagation()),i.appendChild(s);const a=f(document.createElement("button"));a.type="button",a.style.cssText=u,a.textContent="- none -",o||(a.style.fontWeight="700"),a.addEventListener("click",()=>{T(t,null),L()}),i.appendChild(a);const r=document.createElement("div");r.style.cssText="display:flex;flex-wrap:wrap;gap:2px;padding:4px 6px;max-height:220px;overflow-y:auto;",i.appendChild(r);const d=96,b=()=>{const x=typeof I<"u"&&typeof I.list=="function"?I.list():[],y=s.value.trim().toLowerCase(),$=y?x.filter(h=>h.toLowerCase().includes(y)):x;r.replaceChildren();for(const h of $.slice(0,d)){const v=f(document.createElement("button"));v.type="button",v.title=h,v.style.cssText="width:26px;height:26px;display:inline-flex;align-items:center;justify-content:center;background:none;border:1px solid transparent;border-radius:4px;cursor:pointer;color:inherit;",h===o&&(v.style.borderColor="var(--dm-primary,#5b8cff)");const A=document.createElement("span");A.setAttribute("data-icon",h),A.setAttribute("data-icon-size","15"),A.style.cssText="display:inline-flex;align-items:center;",v.appendChild(A),v.addEventListener("click",()=>{T(t,h),L()}),r.appendChild(v)}if($.length>d){const h=document.createElement("div");h.style.cssText=k,h.textContent=`${$.length-d} more - refine search`,r.appendChild(h)}if(!$.length){const h=document.createElement("div");h.style.cssText=k,h.textContent="No icons match",r.appendChild(h)}window.I&&I.scan(r)};let m=null;return s.addEventListener("input",()=>{clearTimeout(m),m=setTimeout(b,120)}),b(),setTimeout(()=>s.focus(),0),i})}function Le(e,t,n){const o=n==null||n===!0?e.default??"":n;return C(`${e.label}${o!==""?`: ${o}`:""}`,()=>{const c=g();c.style.minHeight="48px";const i=typeof E<"u"&&E.loader?E.loader(c,{type:"dots"}):null;return ue(e.source).then(s=>{if(i&&i.destroy(),!l||l.submenu!==c)return;if(c.style.minHeight="",!s.length){const d=document.createElement("div");d.style.cssText=k,d.textContent="Nothing found",c.appendChild(d)}const a=s.some(([d])=>d===o),r=[["","- none -"],...s];o!==""&&!a&&r.push([o,`${o} (missing)`]);for(const[d,b]of r){const m=f(document.createElement("button"));m.type="button",m.style.cssText=u,m.textContent=b,d===o&&(m.style.fontWeight="700"),m.addEventListener("click",()=>{T(t,d===""?null:d),L()}),c.appendChild(m)}}),c})}function _e(e,t){e.appendChild(w(`Effect: ${t.label}`));for(const o of t.attrs||[])e.appendChild(D(o,`${t.name}-${o.name}`));const n=f(document.createElement("button"));n.type="button",n.style.cssText=u,n.innerHTML='<span data-icon="trash" data-icon-size="13" style="display:inline-flex;align-items:center;"></span> Remove effect',n.addEventListener("click",()=>{const o={};for(const c of se(l.span.attrs,t.name))o[c]=null;W(l.textarea,l.span,o),p()}),e.appendChild(n)}function Se(){const e=g();e.appendChild(w("Seasonal themes"));for(const[t,n]of[["auto","Auto (date-detected)"],...Object.entries(ee).map(([o,c])=>[o,c.label])]){const o=f(document.createElement("button"));o.type="button",o.style.cssText=u,o.textContent=n,o.addEventListener("click",()=>{O(l.textarea,`[celebrate theme="${t}" /]`),p()}),e.appendChild(o)}e.appendChild(S()),e.appendChild(w("Celebration effects"));for(const t of["butterflies","ticker-tape","firework","fireworks"]){const n=B.get(t),o=f(document.createElement("button"));o.type="button",o.style.cssText=u,o.textContent=n.label,o.addEventListener("click",()=>{const c=l.textarea;p(),M(c,n)}),e.appendChild(o)}return e}function $e(){const e=g(),t=l.span,n=t&&Y.has(t.name)?t.name:null;for(const o of[...new Set(_.map(c=>c.category))]){const c=_.filter(i=>i.category===o);if(c.length){e.appendChild(w(o));for(const i of c){const s=n&&(i.hosts||[]).includes(n)&&!(i.name in t.attrs),a=f(document.createElement("button"));if(a.type="button",a.style.cssText=u+"justify-content:space-between;",a.appendChild(document.createTextNode(i.label)),s){const r=document.createElement("span");r.textContent=`inject \u2192 [${n}]`,r.style.cssText="opacity:.6;font-size:.7rem;",a.appendChild(r)}a.addEventListener("click",()=>{if(s)z(l.textarea,l.span,i.name,!0);else{const r=i.selfClosing?`[${i.name} /]`:`[${i.name}]
1
+ import{convertSelectionToBlock as Q}from"./selection-to-block.js";import{EDITOR_TOOLS as Z,SHORTCODES as R}from"./shortcode-registry.js";import{EFFECTS as _,CELEBRATION_THEMES as ee,getEffectAttrs as H}from"./effect-defs.js";import{boolState as te,boolValue as ne,findEnclosingShortcode as oe,setAttr as z,setAttrs as W,effectAttrKeys as se}from"./shortcode-tags.js";import{insertAtCursor as O,replaceRange as ie}from"./markdown-toolbar.js";import{clearLookupCache as ce,lookupOptions as ae}from"./shortcode-lookups.js";import{insertMenuGroups as le,insertShortcodeByName as j}from"./shortcode-insert.js";import{openShortcodeForm as M}from"./shortcode-form.js";import{pickMedia as re}from"./media-picker.js";import{blockTagSnippet as de}from"./block-tags.js";import{catalogueNow as pe,dommaHelp as me}from"./domma-catalogue.js";function ue(e){return ae(e,l?.span?.attrs||{})}const fe=R.map(e=>({name:e.name,selfClosing:e.name==="block"?!1:!!e.selfClosing})),F=new Map(R.map(e=>[e.name,e])),B=new Map(_.map(e=>[e.name,e])),he=_.map(e=>({name:e.name,selfClosing:!!e.selfClosing})),be=[...fe,...he],Y=new Set(["card","box","hero","banner","col","button"]);let l=null;const q="position:fixed;z-index:10000;min-width:210px;max-height:70vh;overflow-y:auto;background:var(--dm-surface,#1c1c30);border:1px solid var(--dm-border,#2a2a40);border-radius:6px;box-shadow:var(--dm-shadow-lg);padding:.3rem;font-size:.83rem;color:var(--dm-text,#e5e5e5);",u="display:flex;align-items:center;gap:.5rem;width:100%;text-align:left;padding:.35rem .55rem;border:none;background:transparent;color:inherit;border-radius:4px;cursor:pointer;font-size:.83rem;",k="padding:.3rem .55rem;color:var(--dm-text-muted,#8a8a9a);font-size:.68rem;text-transform:uppercase;letter-spacing:.06em;",P="flex:1;min-width:0;padding:.2rem .4rem;background:var(--dm-input-bg,#12121e);border:1px solid var(--dm-border,#333);border-radius:3px;color:var(--dm-text,#eee);font-size:.8rem;",xe="height:1px;background:var(--dm-border,#2a2a40);margin:.3rem .2rem;";function f(e){return e.addEventListener("mouseenter",()=>{e.style.background="var(--dm-primary,#4338ca)",e.style.color="var(--dm-primary-text,#fff)"}),e.addEventListener("mouseleave",()=>{e.style.background="transparent",e.style.color="inherit"}),e}export function attachContextMenu(e,{blocks:t=()=>[],openBlock:n=null}={}){const o=()=>{const i=t()||[],s=i.filter(a=>a.shortTag&&!F.has(a.name)&&!B.has(a.name));return{defs:i,specs:[...be,...s.map(a=>({name:a.name,selfClosing:a.selfClosing}))]}},c=(i,s)=>{p();const{defs:a,specs:r}=o();G(e,oe(e,r),i,s,a,n)};return typeof Domma>"u"||!Domma.elements?.contextMenu?(e.addEventListener("contextmenu",i=>{i.preventDefault(),c(i.clientX,i.clientY)}),null):Domma.elements.contextMenu(e,{inherit:!1,cursor:!1,render:i=>{c(i.x,i.y)}})}function p(){l&&(L(),l.root.remove(),document.removeEventListener("mousedown",U,!0),document.removeEventListener("keydown",V,!0),window.removeEventListener("scroll",K,!0),l=null)}const U=e=>{l&&!l.root.contains(e.target)&&!(l.submenu&&l.submenu.contains(e.target))&&p()},K=e=>{l&&!l.root.contains(e.target)&&!(l.submenu&&l.submenu.contains(e.target))&&p()},V=e=>{e.key==="Escape"&&p()};function G(e,t,n,o,c=[],i=null){ce();const s=document.createElement("div");s.className="dm-sc-menu",s.style.cssText=q,l={root:s,textarea:e,span:t,submenu:null,blocks:c,openBlock:i,keepEmpty:!1};const a=new Map(c.map(x=>[x.name,x])),r=t&&(F.get(t.name)||B.get(t.name)),d=t&&(r?t.name==="block"?a.get(String(t.attrs.template||"")):null:a.get(t.name)),b=t&&Y.has(t.name)?_.filter(x=>x.name in t.attrs):[];r&&ye(s,r),d&&Ee(s,d,!!r);for(const x of b)_e(s,x);(r||d||b.length)&&s.appendChild(S()),s.appendChild(C("Celebrations\u2026",()=>Se())),s.appendChild(C("Add effect\u2026",()=>$e())),s.appendChild(C("Insert\u2026",()=>Ae()));const m=e.selectionStart!==e.selectionEnd;if(m&&e.value.slice(e.selectionStart,e.selectionEnd).trim()){const x={start:e.selectionStart,end:e.selectionEnd,source:e.value},y=f(document.createElement("button"));y.type="button",y.style.cssText=u,y.textContent="Convert selection to Domma Block\u2026",y.addEventListener("click",()=>{p(),Q(e,x)}),s.appendChild(y)}(t||m)&&s.appendChild(C(m?"Wrap selection in\u2026":"Wrap in\u2026",()=>Ie())),c.length&&(s.appendChild(S()),s.appendChild(C("Add block\u2026",()=>Me()))),document.body.appendChild(s),J(s,n,o),document.addEventListener("mousedown",U,!0),document.addEventListener("keydown",V,!0),window.addEventListener("scroll",K,!0),window.I&&I.scan(s)}function S(){const e=document.createElement("div");return e.style.cssText=xe,e}function w(e){const t=document.createElement("div");return t.style.cssText=k,t.textContent=e,t}function ye(e,t){e.appendChild(w(`${t.label} options`));const n=f(document.createElement("button"));n.type="button",n.style.cssText=u,n.innerHTML='<span data-icon="edit" data-icon-size="13" style="display:inline-flex;align-items:center;"></span>',n.appendChild(document.createTextNode(`Edit ${t.label}\u2026`)),n.addEventListener("click",()=>{const{textarea:i,span:s}=l;p(),M(i,{...t,attrs:H(t,s.attrs)},{span:s})}),e.appendChild(n);for(const i of t.actions||[]){const s=f(document.createElement("button"));s.type="button",s.style.cssText=u,s.innerHTML=`<span data-icon="${i.icon||"zap"}" data-icon-size="13" style="display:inline-flex;align-items:center;"></span>`,s.appendChild(document.createTextNode(i.label)),s.addEventListener("click",()=>{const{textarea:a,span:r}=l;if(i.remove){ie(a,r.openTagStart,r.openTagEnd,""),p();return}l.span=W(a,r,i.set||{}),p()}),e.appendChild(s)}const o=Array.isArray(t.quickAttrs)?new Set(t.quickAttrs):null,c=H(t,l.span.attrs).filter(i=>!o||o.has(i.name));(t.actions||[]).length&&c.length&&e.appendChild(S());for(const i of c)e.appendChild(D(i))}function Ee(e,t,n){const{span:o}=l;if(l.keepEmpty=!0,n&&e.appendChild(S()),e.appendChild(w(n?`${t.name} parameters`:`${t.name} block`)),t.description&&!n){const s=document.createElement("div");s.style.cssText="padding:0 .55rem .3rem;font-size:.75rem;color:var(--dm-text-muted,#9a9aac);max-width:260px;",s.textContent=t.description,e.appendChild(s)}const c=(s,a,r)=>{const d=f(document.createElement("button"));d.type="button",d.style.cssText=u,d.innerHTML=`<span data-icon="${s}" data-icon-size="13" style="display:inline-flex;align-items:center;"></span>`,d.appendChild(document.createTextNode(a)),d.addEventListener("click",r),e.appendChild(d)};t.attrs.length&&c("edit","Edit parameters\u2026",()=>{const{textarea:s}=l;p(),M(s,{...t,name:o.name,label:t.name},{span:o})});const{openBlock:i}=l;c(i?"layout":"external-link",i?"Edit the block":"Open the block",()=>{p(),i?i(t.name):location.hash=`#/blocks/edit/${encodeURIComponent(t.name)}`});for(const s of t.attrs)e.appendChild(D(s));if(!t.attrs.length){const s=document.createElement("div");s.style.cssText=k+"text-transform:none;letter-spacing:0;",s.textContent="This block takes no parameters.",e.appendChild(s)}}function D(e,t=e.name){const n=Ce(e,t),o=e.domma?me(pe(),e):"";return o&&n&&!n.title&&(n.title=o),n}function Ce(e,t){const n=l.span.attrs[t];switch(e.type){case"checkbox":return ge(e,t,te(n,e.default));case"select":return Te(e,t,n);case"lookup":return Le(e,t,n);case"colour":return we(e,t,n);case"icon":return ke(e,t,n);default:return ve(e,t,n)}}function T(e,t){if(l.span=z(l.textarea,l.span,e,l.keepEmpty&&t==null?"":t,{keepEmpty:l.keepEmpty}),e==="theme"){const{textarea:n,span:o,root:c}=l,i=c.getBoundingClientRect(),{blocks:s,openBlock:a}=l;p(),G(n,o,i.left,i.top,s,a)}}function ge(e,t,n){const o=f(document.createElement("label"));o.style.cssText=u;const c=document.createElement("input");return c.type="checkbox",c.checked=n,c.addEventListener("change",()=>T(t,ne(e,c.checked))),o.appendChild(c),o.appendChild(document.createTextNode(e.label)),o}function ve(e,t,n){const o=document.createElement("div");o.style.cssText=u+"cursor:default;";const c=document.createElement("span");c.textContent=e.label,c.style.cssText="white-space:nowrap;color:var(--dm-text-muted,#9a9aac);";const i=document.createElement("input");i.type=e.type==="number"?"number":"text",i.value=n===!0||n==null?"":n,e.default!=null&&e.default!==""&&(i.placeholder=String(e.default)),i.style.cssText=P;let s=null;if(i.addEventListener("input",()=>{clearTimeout(s),s=setTimeout(()=>T(t,i.value.trim()),180)}),i.addEventListener("mousedown",a=>a.stopPropagation()),o.appendChild(c),o.appendChild(i),e.type==="image"){const a=document.createElement("button");a.type="button",a.textContent="Browse",a.title="Choose from Media",a.style.cssText="padding:2px 8px;background:transparent;border:1px solid var(--dm-border,#333);border-radius:4px;color:inherit;cursor:pointer;flex-shrink:0;font:inherit;",a.addEventListener("mousedown",r=>r.stopPropagation()),a.addEventListener("click",async()=>{const{textarea:r,span:d}=l;p();const b=await re({current:i.value.trim()});b&&r.isConnected&&z(r,d,t,b)}),o.appendChild(a)}return o}function we(e,t,n){const o=document.createElement("div");o.style.cssText=u+"cursor:default;";const c=document.createElement("span");c.textContent=e.label,c.style.flex="1";const i=document.createElement("input");return i.type="color",typeof n=="string"&&/^#/.test(n)?i.value=n:typeof e.default=="string"&&/^#/.test(e.default)&&(i.value=e.default),i.addEventListener("input",()=>T(t,i.value)),o.appendChild(c),o.appendChild(i),o}function Te(e,t,n){const o=n==null||n===!0?e.default??"":n;return C(`${e.label}${o!==""?`: ${o}`:""}`,()=>{const c=g();for(const[i,s]of e.options||[]){const a=f(document.createElement("button"));a.type="button",a.style.cssText=u,a.textContent=s,i===o&&(a.style.fontWeight="700"),a.addEventListener("click",()=>{T(t,i),L()}),c.appendChild(a)}return c})}function ke(e,t,n){const o=n==null||n===!0?"":String(n),c=o?`${e.label}: ${o}`:e.label;return C(c,()=>{const i=g();i.style.width="232px";const s=document.createElement("input");s.type="text",s.placeholder="Search icons\u2026",s.style.cssText=P+"margin:6px;width:calc(100% - 12px);",s.addEventListener("mousedown",x=>x.stopPropagation()),i.appendChild(s);const a=f(document.createElement("button"));a.type="button",a.style.cssText=u,a.textContent="- none -",o||(a.style.fontWeight="700"),a.addEventListener("click",()=>{T(t,null),L()}),i.appendChild(a);const r=document.createElement("div");r.style.cssText="display:flex;flex-wrap:wrap;gap:2px;padding:4px 6px;max-height:220px;overflow-y:auto;",i.appendChild(r);const d=96,b=()=>{const x=typeof I<"u"&&typeof I.list=="function"?I.list():[],y=s.value.trim().toLowerCase(),$=y?x.filter(h=>h.toLowerCase().includes(y)):x;r.replaceChildren();for(const h of $.slice(0,d)){const v=f(document.createElement("button"));v.type="button",v.title=h,v.style.cssText="width:26px;height:26px;display:inline-flex;align-items:center;justify-content:center;background:none;border:1px solid transparent;border-radius:4px;cursor:pointer;color:inherit;",h===o&&(v.style.borderColor="var(--dm-primary,#5b8cff)");const A=document.createElement("span");A.setAttribute("data-icon",h),A.setAttribute("data-icon-size","15"),A.style.cssText="display:inline-flex;align-items:center;",v.appendChild(A),v.addEventListener("click",()=>{T(t,h),L()}),r.appendChild(v)}if($.length>d){const h=document.createElement("div");h.style.cssText=k,h.textContent=`${$.length-d} more - refine search`,r.appendChild(h)}if(!$.length){const h=document.createElement("div");h.style.cssText=k,h.textContent="No icons match",r.appendChild(h)}window.I&&I.scan(r)};let m=null;return s.addEventListener("input",()=>{clearTimeout(m),m=setTimeout(b,120)}),b(),setTimeout(()=>s.focus(),0),i})}function Le(e,t,n){const o=n==null||n===!0?e.default??"":n;return C(`${e.label}${o!==""?`: ${o}`:""}`,()=>{const c=g();c.style.minHeight="48px";const i=typeof E<"u"&&E.loader?E.loader(c,{type:"dots"}):null;return ue(e.source).then(s=>{if(i&&i.destroy(),!l||l.submenu!==c)return;if(c.style.minHeight="",!s.length){const d=document.createElement("div");d.style.cssText=k,d.textContent="Nothing found",c.appendChild(d)}const a=s.some(([d])=>d===o),r=[["","- none -"],...s];o!==""&&!a&&r.push([o,`${o} (missing)`]);for(const[d,b]of r){const m=f(document.createElement("button"));m.type="button",m.style.cssText=u,m.textContent=b,d===o&&(m.style.fontWeight="700"),m.addEventListener("click",()=>{T(t,d===""?null:d),L()}),c.appendChild(m)}}),c})}function _e(e,t){e.appendChild(w(`Effect: ${t.label}`));for(const o of t.attrs||[])e.appendChild(D(o,`${t.name}-${o.name}`));const n=f(document.createElement("button"));n.type="button",n.style.cssText=u,n.innerHTML='<span data-icon="trash" data-icon-size="13" style="display:inline-flex;align-items:center;"></span> Remove effect',n.addEventListener("click",()=>{const o={};for(const c of se(l.span.attrs,t.name))o[c]=null;W(l.textarea,l.span,o),p()}),e.appendChild(n)}function Se(){const e=g();e.appendChild(w("Seasonal themes"));for(const[t,n]of[["auto","Auto (date-detected)"],...Object.entries(ee).map(([o,c])=>[o,c.label])]){const o=f(document.createElement("button"));o.type="button",o.style.cssText=u,o.textContent=n,o.addEventListener("click",()=>{O(l.textarea,`[celebrate theme="${t}" /]`),p()}),e.appendChild(o)}e.appendChild(S()),e.appendChild(w("Celebration effects"));for(const t of["butterflies","ticker-tape","firework","fireworks"]){const n=B.get(t),o=f(document.createElement("button"));o.type="button",o.style.cssText=u,o.textContent=n.label,o.addEventListener("click",()=>{const c=l.textarea;p(),M(c,n)}),e.appendChild(o)}return e}function $e(){const e=g(),t=l.span,n=t&&Y.has(t.name)?t.name:null;for(const o of[...new Set(_.map(c=>c.category))]){const c=_.filter(i=>i.category===o);if(c.length){e.appendChild(w(o));for(const i of c){const s=n&&(i.hosts||[]).includes(n)&&!(i.name in t.attrs),a=f(document.createElement("button"));if(a.type="button",a.style.cssText=u+"justify-content:space-between;",a.appendChild(document.createTextNode(i.label)),s){const r=document.createElement("span");r.textContent=`inject \u2192 [${n}]`,r.style.cssText="opacity:.6;font-size:.7rem;",a.appendChild(r)}a.addEventListener("click",()=>{if(s)z(l.textarea,l.span,i.name,!0);else{const r=i.selfClosing?`[${i.name} /]`:`[${i.name}]
2
2
  Content
3
3
  [/${i.name}]`;O(l.textarea,r)}p()}),e.appendChild(a)}}}return e}function C(e,t){const n=f(document.createElement("button"));n.type="button",n.style.cssText=u+"justify-content:space-between;",n.appendChild(document.createTextNode(e));const o=document.createElement("span");return o.setAttribute("data-icon","chevron-right"),o.setAttribute("data-icon-size","12"),o.style.cssText="opacity:.6;display:inline-flex;align-items:center;flex-shrink:0;",n.appendChild(o),n.addEventListener("mouseenter",()=>X(n,t)),n.addEventListener("click",c=>{c.stopPropagation(),X(n,t)}),n}function g(){const e=document.createElement("div");return e.className="dm-sc-submenu",e.style.cssText=q,e}function X(e,t){L();const n=t();l.submenu=n,document.body.appendChild(n);const o=e.getBoundingClientRect();J(n,o.right+2,o.top,o.left-2),window.I&&I.scan(n)}function L(){l&&l.submenu&&(l.submenu.remove(),l.submenu=null)}function N(e){const t=f(document.createElement("button"));if(t.type="button",t.style.cssText=u,e.icon){const n=document.createElement("span");n.setAttribute("data-icon",e.icon),n.setAttribute("data-icon-size","14"),n.style.cssText="opacity:.75;display:inline-flex;align-items:center;flex-shrink:0;",t.appendChild(n)}return t.appendChild(document.createTextNode(e.label)),t}function Ae(){const e=g();for(const{category:t,items:n}of le()){e.appendChild(w(t));for(const o of n){const c=N(o);c.addEventListener("click",()=>{const i=l.textarea;p(),j(o.name,i)}),e.appendChild(c)}}return e}function Me(){const e=g();e.style.maxWidth="320px";const t=document.createElement("input");t.type="text",t.placeholder="Find a block\u2026",t.style.cssText=P+"margin:6px;width:calc(100% - 12px);",t.addEventListener("mousedown",c=>c.stopPropagation());const n=document.createElement("div");e.append(t,n);const o=()=>{const c=t.value.trim().toLowerCase(),i=l.blocks.filter(s=>!c||s.name.includes(c)||s.description.toLowerCase().includes(c));n.replaceChildren();for(const s of i){const a=N(s);if(s.description&&(a.title=s.description),!s.shortTag){const r=document.createElement("small");r.style.cssText="margin-left:auto;opacity:.6;",r.textContent="[block]",r.title='A built-in shortcode has this name, so it goes in as [block template="\u2026"]',a.appendChild(r)}a.addEventListener("click",()=>{const r=l.textarea;p();const d=r.selectionStart,b=de(s);O(r,b);const m=b.indexOf('=""');m>=0&&r.setSelectionRange(d+m+2,d+m+2),r.focus()}),n.appendChild(a)}if(!i.length){const s=document.createElement("div");s.style.cssText=k,s.textContent="No blocks match",n.appendChild(s)}window.I&&I.scan(n)};return t.addEventListener("input",o),o(),setTimeout(()=>t.focus(),0),e}function Ie(){const e=g();for(const t of R.filter(n=>n.wrappable||n.container)){const n=N(t);n.addEventListener("click",()=>{const o=l.textarea;p(),M(o,t)}),e.appendChild(n)}for(const t of Z.filter(n=>n.wrappable)){const n=N(t);n.addEventListener("click",()=>{const o=l.textarea;p(),j(t.name,o)}),e.appendChild(n)}return e}function J(e,t,n,o){e.style.left="0px",e.style.top="0px";const c=e.getBoundingClientRect();let i=t;t+c.width>window.innerWidth-8&&(i=o!=null?o-c.width:t-c.width);let s=n;n+c.height>window.innerHeight-8&&(s=Math.max(8,window.innerHeight-c.height-8)),e.style.left=`${Math.max(8,i)}px`,e.style.top=`${Math.max(8,s)}px`}