domma-cms 1.34.0 → 1.36.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +11 -0
- package/admin/js/api.js +1 -1
- package/admin/js/app.js +2 -2
- package/admin/js/lib/image-editor.js +1 -1
- package/admin/js/lib/media-arrange.js +1 -1
- package/admin/js/lib/media-picker.js +2 -2
- package/admin/js/lib/media-upload.js +1 -1
- package/admin/js/lib/seo-redirects.js +1 -1
- package/admin/js/templates/docs/usage-media.html +6 -0
- package/admin/js/templates/media.html +1 -0
- package/admin/js/views/media.js +3 -3
- package/docs/DommaFeatures.md +3 -0
- package/package.json +1 -1
- package/plugins/_lib/admin/mail/body-menu.js +1 -1
- package/plugins/_lib/admin/mail/cms-host.js +1 -1
- package/plugins/_lib/admin/mail/compose-window.js +1 -1
- package/plugins/_lib/admin/mail/contacts.js +1 -1
- package/plugins/_lib/admin/mail/diagnostics-section.js +1 -1
- package/plugins/_lib/admin/mail/drag-drop.js +1 -1
- package/plugins/_lib/admin/mail/folder-tree.js +26 -1
- package/plugins/_lib/admin/mail/font-controls.js +1 -1
- package/plugins/_lib/admin/mail/fonts.js +1 -1
- package/plugins/_lib/admin/mail/host-context.js +1 -1
- package/plugins/_lib/admin/mail/identity.js +1 -1
- package/plugins/_lib/admin/mail/image-senders-section.js +1 -1
- package/plugins/_lib/admin/mail/keyboard.js +1 -1
- package/plugins/_lib/admin/mail/mail.html +4 -1
- package/plugins/_lib/admin/mail/message-actions.js +1 -1
- package/plugins/_lib/admin/mail/oauth-panel.js +1 -1
- package/plugins/_lib/admin/mail/panes.js +1 -1
- package/plugins/_lib/admin/mail/reader-kit.js +9 -3
- package/plugins/_lib/admin/mail/reader-runtime.js +154 -6
- package/plugins/_lib/admin/mail/reader-view.js +1 -1
- package/plugins/_lib/admin/mail/resizable.js +1 -1
- package/plugins/_lib/admin/mail/restore-spam.js +1 -1
- package/plugins/_lib/admin/mail/rules.js +1 -1
- package/plugins/_lib/admin/mail/scheduling.js +1 -1
- package/plugins/_lib/admin/mail/section-kit.js +1 -1
- package/plugins/_lib/admin/mail/security-note.js +1 -1
- package/plugins/_lib/admin/mail/settings-section.js +1 -1
- package/plugins/_lib/admin/mail/templates.js +1 -1
- package/plugins/_lib/admin/mail/threads.js +1 -1
- package/plugins/_lib/admin/mail/vacation.js +1 -1
- package/plugins/_lib/admin/mail/when-closed.js +1 -1
- package/plugins/_lib/admin/ui/dates.js +1 -1
- package/plugins/_lib/admin/ui/resizable.js +1 -1
- package/plugins/_lib/domma-mail.lock.json +80 -80
- package/plugins/_lib/mail/accountFileStore.js +1 -1
- package/plugins/_lib/mail/accountRepository.js +1 -1
- package/plugins/_lib/mail/accountRoutes.js +1 -1
- package/plugins/_lib/mail/bodyTokenProvider.js +1 -1
- package/plugins/_lib/mail/bodyTokens.js +1 -1
- package/plugins/_lib/mail/compose.js +1 -1
- package/plugins/_lib/mail/defaults.js +1 -1
- package/plugins/_lib/mail/envelope.js +1 -1
- package/plugins/_lib/mail/folderActions.js +1 -1
- package/plugins/_lib/mail/folderRuntime.js +1 -1
- package/plugins/_lib/mail/folders.js +1 -1
- package/plugins/_lib/mail/imapPoolRuntime.js +1 -1
- package/plugins/_lib/mail/mbox.js +1 -1
- package/plugins/_lib/mail/message-action.js +1 -1
- package/plugins/_lib/mail/messageSecurity.js +1 -1
- package/plugins/_lib/mail/messageSecurityProvider.js +1 -1
- package/plugins/_lib/mail/networkAddresses.js +1 -1
- package/plugins/_lib/mail/networkPolicy.js +1 -1
- package/plugins/_lib/mail/oauthAccounts.js +1 -1
- package/plugins/_lib/mail/oauthRouteRuntime.js +1 -1
- package/plugins/_lib/mail/oauthRuntime.js +1 -1
- package/plugins/_lib/mail/pollSchedule.js +1 -1
- package/plugins/_lib/mail/poller.js +1 -1
- package/plugins/_lib/mail/pollerRuntime.js +1 -1
- package/plugins/_lib/mail/priority.js +1 -1
- package/plugins/_lib/mail/publicMailbox.js +1 -1
- package/plugins/_lib/mail/readRuntime.js +1 -1
- package/plugins/_lib/mail/render.js +1 -1
- package/plugins/_lib/mail/ruleRunner.js +1 -1
- package/plugins/_lib/mail/schedulerRuntime.js +1 -1
- package/plugins/_lib/mail/secretProvider.js +1 -1
- package/plugins/_lib/mail/secretbox.js +1 -1
- package/plugins/_lib/mail/senderAuth.js +1 -1
- package/plugins/_lib/mail/sieve.js +1 -1
- package/plugins/_lib/mail/smtpService.js +1 -1
- package/plugins/_lib/mail/snoozeRuntime.js +1 -1
- package/plugins/_lib/mail/store.js +1 -1
- package/plugins/_lib/mail/subscriptions.js +1 -1
- package/plugins/_lib/mail/syncPlan.js +1 -1
- package/plugins/_lib/mail/syncRuntime.js +1 -1
- package/plugins/_lib/mail/syncSelection.js +1 -1
- package/plugins/_lib/mail/unreadBadge.js +1 -1
- package/plugins/_lib/mail/unsubscribe.js +1 -1
- package/plugins/_lib/mail/vacationRuntime.js +1 -1
- package/plugins/_lib/mail/write.js +1 -1
- package/server/routes/api/media.js +3 -1
- package/server/routes/api/sidebar.js +2 -2
- package/server/services/content.js +26 -2
- package/server/services/hooks.js +27 -4
- package/server/services/plugins.js +9 -3
- package/server/services/renderer.js +3 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,16 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [1.36.0] - 2026-11-03
|
|
4
|
+
|
|
5
|
+
- **Media knows about folders.** The list no longer shows a folder as if it were a file, and the screen says when files sit in folders it does not list (they keep working at their addresses). `GET /api/media/_folders` counts them.
|
|
6
|
+
- **Media can be taken over by a Pro Tool**, like Contacts: `supersedes: ["media"]` hides the built-in sidebar entry and hands over the route, and a Tool's `admin.mediaPicker` module takes every `pickMedia()` in the admin, with the built-in picker as the fallback. `openImageEditor(file, {api})` and `mediaUploader(zone, {url})` take a Tool's own routes. For Media Pro.
|
|
7
|
+
- **Blog posts and Tools' pages run `render:afterRender`** like every other page.
|
|
8
|
+
|
|
9
|
+
## [1.35.0] - 2026-11-03
|
|
10
|
+
|
|
11
|
+
- **Open or close every mail folder at once.** Email and Mail Reader offer Open all folders and Close all folders on a mailbox's right-click menu, on the Folders heading's right-click menu, and as a button in the Folders heading (which switches between the two, and is the place to find it with a single mailbox).
|
|
12
|
+
- **Mark a folder and the folders inside it.** In Email, Mark all as read and Mark all as unread on a folder that holds other folders open a submenu: This folder, or Including folders inside. Each folder is done in turn and one message reports the total.
|
|
13
|
+
|
|
3
14
|
## [1.34.0] - 2026-11-03
|
|
4
15
|
|
|
5
16
|
- Email Pro can notify for all folders or selected folders, with Check all and None controls in Email Settings. Folder choices are saved per mailbox and automatically included in background syncing. The sidebar badge continues to count Inbox unread messages. Folder notification marks are independent, including mailboxes with more than fifty folders.
|
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||[]),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};
|
|
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 y(e){S.set("auth_token",e)}function f(){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 f(),sendToLogin({expired:!0}),new Error("Token refresh failed");const{token:n}=await o.json();return y(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"}),folders:()=>t("/media/_folders",{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&&y(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(()=>{}),f()}export{t as apiRequest,g as refreshAccessToken,a as getToken,f as clearAuth};
|
package/admin/js/app.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{wireNotificationMenu as Q}from"./lib/topbar-notifications.js";import{installSmoothCarets as X}from"./lib/smooth-caret.js";import{viewLoaders as Z}from"./views/index.js";import{createLazyViews as ee}from"./lib/lazy-views.js";import{withPluginChrome as _}from"./lib/plugin-chrome.js";import{api as r,getUser as x,isAuthenticated as m,logout as te,sendToLogin as ae}from"./api.js";import{claimDrafts as ie}from"./lib/draft-owner.js";import{isAuthScreen as C,loginHashFor as oe}from"./lib/login-arrange.js";import{installHttpInterceptor as se}from"./http-interceptor.js";import{installResizableSlideovers as ne}from"./lib/slideover-resizable.js";import{installActivityThrobber as re}from"./lib/activity-throbber.js";import{installUpdateNotice as le,renderCmsVersion as ce}from"./lib/update-notice.js";import{renderFrameworkVersions as W,wireAccountMenu as me}from"./lib/topbar-account.js";import{refreshTopbarProject as B}from"./lib/topbar-project.js";import{isPathAllowed as pe,redirectFor as de}from"./lib/admin-scope.js";import{deliverDesktop as ue,desktopActive as he,notificationSettings as we}from"./lib/desktop-notify.js";import{avatarUrl as ge,installAccountAvatar as fe}from"./lib/avatar.js";import{installCalculator as ve}from"./lib/calculator.js";import{takeOverviewPass as be,withDashboardStrip as H}from"./lib/dashboards-strip.js";import{installHotkeys as Ce}from"./lib/hotkeys-ui.js";import{applyAdminBrand as K}from"./lib/admin-brand.js";import{installRouterCatchUp as Se}from"./lib/router-catch-up.js";import{installSidebarDrawer as Me}from"./lib/sidebar-drawer.js";$(()=>{X(document),se(),ve(),le(),re(),ne(),Me(),(async()=>{const{applyAdminTheme:e,refreshAdminTheme:i}=await import("./lib/admin-theme.js");m()?await i(r,{init:!0}):e({dommaTheme:"charcoal-dark"},{init:!0})})();let p=null,h=null,c="/",w=!1,g=null;function D(e){if(N[e])return E.toast(`${N[e]} is switched off on this site.`,{type:"info"}),"/";const[i,t]=e.split("?"),a=new URLSearchParams(t||"").get("tab");if(i==="/settings"&&["favicon","pageNavigation","breadcrumbs","motion","search"].includes(a))return`/appearance?tab=${a}`;if(e.split("?")[0]==="/my-dashboard")return"/dashboards";const o=y[e]||de(p,e);return o||((e.split("?")[0]||"/")==="/"&&c&&c!=="/"&&!be()?y[c]||c:null)}const y={},N={};R.use(async(e,i,t)=>{if(C(e.path))return t();if(!m()){ae();return}const a=D(e.path);if(a){R.navigate(a);return}t()});async function f(){try{const e=await r.get("/auth/permissions");p=e.adminScope||null,h=e.adminBrand||null,K(h),c=e.adminHome||"/",W(e.versions);const i=e.permissions||[];return w=pe(p,"/settings")&&i.some(t=>t==="settings"||t.startsWith("settings.")),g=i.some(t=>t==="notifications"||t.startsWith("notifications.")),i}catch{return p=null,c="/",h||K(null),w=!1,g=null,[]}}document.addEventListener("dm:admin-home-changed",()=>{f()});let P=null,A=!1;document.addEventListener("dm:sidebar-rebuild",()=>{if(B(r),P){A=!0;return}P=(async()=>{do{A=!1;try{await j(await f())}catch{}}while(A)})().finally(()=>{P=null})});async function j(e){const{renderAdminSidebar:i}=await import("./lib/sidebar-renderer.js");await i({mount:"#admin-sidebar",permissions:e,adminScope:p,brand:h})}M.subscribe("router:afterChange",({to:e})=>{C(e.path)&&(u&&(clearInterval(u),u=null),p=null,c="/",w=!1,g=null)});const q=[{path:"/",view:"dashboard",title:"Dashboard - Domma CMS"},{path:"/dashboards",view:"dashboards",title:"Dashboards - Domma CMS"},{path:"/my-dashboard",view:"dashboards",title:"Dashboards - Domma CMS"},{path:"/pages",view:"pages",title:"Pages - Domma CMS"},{path:"/pages/new",view:"pageEditor",title:"New Page - Domma CMS"},{path:"/pages/edit/*",view:"pageEditor",title:"Edit Page - Domma CMS"},{path:"/media",view:"media",title:"Media - Domma CMS"},{path:"/menus",view:"menus",title:"Menus - Domma CMS"},{path:"/context-menus",view:"contextMenus",title:"Context Menus - Domma CMS"},{path:"/context-menus/new",view:"contextMenuEditor",title:"New Context Menu - Domma CMS"},{path:"/context-menus/edit/:slug",view:"contextMenuEditor",title:"Edit Context Menu - Domma CMS"},{path:"/launchers",view:"launchers",title:"Launchers - Domma CMS"},{path:"/menus/new",view:"menuEditor",title:"New Menu - Domma CMS"},{path:"/menus/edit/:slug",view:"menuEditor",title:"Edit Menu - Domma CMS"},{path:"/menu-locations",view:"menuLocations",title:"Menu Locations - Domma CMS"},{path:"/navigation",view:"menusRedirect",title:"Menus - Domma CMS"},{path:"/layouts",view:"layouts",title:"Layouts - Domma CMS"},{path:"/appearance",view:"appearance",title:"Appearance - Domma CMS"},{path:"/footer",view:"footer",title:"Footer - Domma CMS"},{path:"/settings",view:"settings",title:"Settings - Domma CMS"},{path:"/theme",view:"theme",title:"Theme - Domma CMS"},{path:"/users",view:"users",title:"Users - Domma CMS"},{path:"/users/new",view:"userEditor",title:"New User - Domma CMS"},{path:"/users/edit/:id",view:"userEditor",title:"Edit User - Domma CMS"},{path:"/plugins",view:"plugins",title:"Plugins - Domma CMS"},{path:"/plugins/code/:name",view:"pluginCode",title:"Plugin Code - Domma CMS"},{path:"/documentation",view:"documentation",title:"Usage - Domma CMS"},{path:"/tutorials",view:"tutorials",title:"Tutorials - Domma CMS"},{path:"/tutorials/crud",view:"tutorialCrud",title:"Building a CRUD App - Domma CMS"},{path:"/tutorials/editor",view:"tutorialEditor",title:"The Editor - Domma CMS"},{path:"/tutorials/plugin",view:"tutorialPlugin",title:"Writing a Tool - Domma CMS"},{path:"/tutorials/forms",view:"tutorialForms",title:"Form Follow-Up - Domma CMS"},{path:"/docs/components",view:"componentsReference",title:"Components Reference - Domma CMS"},{path:"/docs/components-howto",view:"componentsHowto",title:"Components How-To - Domma CMS"},{path:"/docs/components-walkthrough",view:"componentsWalkthrough",title:"Components Walkthrough - Domma CMS"},{path:"/docs/components-rules",view:"componentsRules",title:"Components Rules - Domma CMS"},{path:"/docs/usage/pages",view:"usagePages",title:"Pages - Usage - Domma CMS"},{path:"/docs/usage/media",view:"usageMedia",title:"Media - Usage - Domma CMS"},{path:"/docs/usage/navigation",view:"usageNavigation",title:"Navigation - Usage - Domma CMS"},{path:"/docs/usage/dconfig",view:"usageDconfig",title:"DConfig - Usage - Domma CMS"},{path:"/docs/usage/shortcodes",view:"usageShortcodes",title:"Shortcodes - Usage - Domma CMS"},{path:"/docs/usage/site-settings",view:"usageSiteSettings",title:"Site Settings - Usage - Domma CMS"},{path:"/docs/usage/plugins",view:"usagePlugins",title:"Plugins - Usage - Domma CMS"},{path:"/docs/usage/users-roles",view:"usageUsersRoles",title:"Users & Roles - Usage - Domma CMS"},{path:"/docs/usage/views",view:"usageViews",title:"Views - Usage - Domma CMS"},{path:"/docs/usage/actions",view:"usageActions",title:"Actions - Usage - Domma CMS"},{path:"/docs/usage/cta-shortcode",view:"usageCtaShortcode",title:"CTA Shortcode - Usage - Domma CMS"},{path:"/docs/usage/editions",view:"usageEditions",title:"Editions & Licences - Usage - Domma CMS"},{path:"/docs/usage/collections",view:"usageCollections",title:"Collections & Forms - Usage - Domma CMS"},{path:"/docs/usage/blocks",view:"usageBlocks",title:"Blocks - Usage - Domma CMS"},{path:"/docs/usage/tools",view:"usageTools",title:"Built-in Tools - Usage - Domma CMS"},{path:"/docs/usage/dashboard",view:"usageDashboard",title:"Dashboard - Usage - Domma CMS"},{path:"/docs/usage/search-engines",view:"usageSearchEngines",title:"Search Engines & AI - Usage - Domma CMS"},{path:"/docs/usage/launchers",view:"usageLaunchers",title:"Launchers - Usage - Domma CMS"},{path:"/docs/usage/chat",view:"usageChat",title:"Chat & Knowledge - Usage - Domma CMS"},{path:"/docs/plugins",view:"pluginGuides",title:"Plugin Guides - Domma CMS"},{path:"/docs/plugins/*",view:"pluginGuide",title:"Plugin Guide - Domma CMS"},{path:"/docs/api/authentication",view:"apiRefAuthentication",title:"Authentication - API - Domma CMS"},{path:"/docs/api/pages",view:"apiRefPages",title:"Pages - API - Domma CMS"},{path:"/docs/api/settings",view:"apiRefSettings",title:"Settings - API - Domma CMS"},{path:"/docs/api/layouts",view:"apiRefLayouts",title:"Layouts - API - Domma CMS"},{path:"/docs/api/navigation",view:"apiRefNavigation",title:"Navigation - API - Domma CMS"},{path:"/docs/api/media",view:"apiRefMedia",title:"Media - API - Domma CMS"},{path:"/docs/api/users",view:"apiRefUsers",title:"Users - API - Domma CMS"},{path:"/docs/api/plugins",view:"apiRefPlugins",title:"Plugins - API - Domma CMS"},{path:"/docs/api/collections",view:"apiRefCollections",title:"Collections - API - Domma CMS"},{path:"/docs/api/views",view:"apiRefViews",title:"Views API - Domma CMS"},{path:"/docs/api/actions",view:"apiRefActions",title:"Actions API - Domma CMS"},{path:"/docs/api/forms",view:"apiRefForms",title:"Forms API - Domma CMS"},{path:"/docs/api/scaffold",view:"apiRefScaffold",title:"Scaffold API - Domma CMS"},{path:"/docs/api/external",view:"apiRefExternal",title:"External API & Tokens - Domma CMS"},{path:"/docs/api/content",view:"apiRefContent",title:"Content API - Domma CMS"},{path:"/docs/api/builder",view:"apiRefBuilder",title:"API Builder - Domma CMS"},{path:"/api-reference",view:"apiReference",title:"API Reference - Domma CMS"},{path:"/collections",view:"collections",title:"Collections - Domma CMS"},{path:"/collections/new",view:"collectionEditor",title:"New Collection - Domma CMS"},{path:"/collections/edit/:slug",view:"collectionEditor",title:"Edit Collection - Domma CMS"},{path:"/collections/:slug/entries",view:"collectionEntries",title:"Entries - Domma CMS"},{path:"/forms",view:"forms",title:"Forms - Domma CMS"},{path:"/forms/new",view:"formEditor",title:"New Form - Domma CMS"},{path:"/forms/edit/:slug",view:"formEditor",title:"Edit Form - Domma CMS"},{path:"/forms/:slug/submissions",view:"formSubmissions",title:"Submissions - Domma CMS"},{path:"/views",view:"viewsList",title:"Views - Domma CMS"},{path:"/views/new",view:"viewEditor",title:"New View - Domma CMS"},{path:"/views/edit/:slug",view:"viewEditor",title:"Edit View - Domma CMS"},{path:"/views/:slug/preview",view:"viewPreview",title:"View Preview - Domma CMS"},{path:"/actions",view:"actionsList",title:"Actions - Domma CMS"},{path:"/actions/new",view:"actionEditor",title:"New Action - Domma CMS"},{path:"/actions/edit/:slug",view:"actionEditor",title:"Edit Action - Domma CMS"},{path:"/pro/docs",view:"proDocs",title:"Pro Documentation - Domma CMS"},{path:"/blocks",view:"blocks",title:"Blocks - Domma CMS"},{path:"/blocks/new",view:"pageEditor",title:"New Block - Domma CMS"},{path:"/blocks/edit/:name",view:"pageEditor",title:"Edit Block - Domma CMS"},{path:"/components",view:"components",title:"Components - Domma CMS"},{path:"/components/new",view:"pageEditor",title:"New Component - Domma CMS"},{path:"/components/edit/:name",view:"pageEditor",title:"Edit Component - Domma CMS"},{path:"/my-profile",view:"myProfile",title:"My Profile - Domma CMS"},{path:"/roles",view:"roles",title:"Roles & Permissions - Domma CMS"},{path:"/roles/edit/:id",view:"roleEditor",title:"Edit Role - Domma CMS"},{path:"/effects",view:"effects",title:"Effects - Domma CMS"},{path:"/search",view:"search",title:"Search - Domma CMS"},{path:"/content-api",view:"contentApi",title:"Content API - Domma CMS"},{path:"/launchers/chats",view:"chats",title:"Chats - Domma CMS"},{path:"/launchers/chats/:id",view:"chats",title:"Chats - Domma CMS"},{path:"/launchers/knowledge",view:"chatKnowledge",title:"Chat Knowledge - Domma CMS"},{path:"/notes",view:"notes",title:"Notes - Domma CMS"},{path:"/todo",view:"todo",title:"Todo - Domma CMS"},{path:"/calculator",view:"calculator",title:"Calculator - Domma CMS"},{path:"/analytics",view:"analytics",title:"Analytics - Domma CMS"},{path:"/seo",view:"seo",title:"SEO - Domma CMS"},{path:"/seo/:tab",view:"seo",title:"SEO - Domma CMS"},{path:"/wordpress-import",view:"wordpressImport",title:"Import from WordPress - Domma CMS"},{path:"/contacts",view:"contacts",title:"Contacts - Domma CMS"},{path:"/calls/new",view:"callNew",title:"Call now - Domma CMS"},{path:"/system/notifications",view:"notifications",title:"Notifications - Domma CMS"},{path:"/api-tokens",view:"apiTokens",title:"API Tokens - Domma CMS"},{path:"/api-endpoints",view:"apiEndpoints",title:"API Builder - Domma CMS"},{path:"/api-endpoints/new",view:"apiEndpointEditor",title:"New API Endpoint - Domma CMS"},{path:"/api-endpoints/edit/:id",view:"apiEndpointEditor",title:"Edit API Endpoint - Domma CMS"},{path:"/projects",view:"projects",title:"Projects - Domma CMS"},{path:"/projects/new",view:"projects",title:"New Project - Domma CMS"},{path:"/projects/edit/:slug",view:"projects",title:"Edit Project - Domma CMS"},{path:"/projects/:slug/settings",view:"projectSettings",title:"Project settings - Domma CMS"},{path:"/projects/:slug/pages",view:"pages",title:"Project pages - Domma CMS"},{path:"/projects/:slug/collections",view:"collections",title:"Project collections - Domma CMS"},{path:"/projects/:slug/forms",view:"forms",title:"Project forms - Domma CMS"},{path:"/projects/:slug/actions",view:"actionsList",title:"Project actions - Domma CMS"},{path:"/projects/:slug/menus",view:"menus",title:"Project menus - Domma CMS"},{path:"/projects/:slug/blocks",view:"blocks",title:"Project blocks - Domma CMS"},{path:"/projects/:slug/components",view:"components",title:"Project components - Domma CMS"},{path:"/projects/:slug/views",view:"viewsList",title:"Project views - Domma CMS"},{path:"/projects/:slug/roles",view:"roles",title:"Project roles - Domma CMS"},{path:"/projects/:slug/users",view:"users",title:"Project users - Domma CMS"},{path:"/projects/:slug/apis",view:"apiEndpoints",title:"Project APIs - Domma CMS"},{path:"/projects/:slug",view:"projectDetail",title:"Project - Domma CMS"},{path:"/login",view:"login",title:"Sign in - Domma CMS",onEnter:()=>{$("#admin-sidebar").hide(),$("#admin-topbar").hide()}},{path:"/reset-password",view:"login",title:"Reset Password - Domma CMS",onEnter:()=>{$("#admin-sidebar").hide(),$("#admin-topbar").hide()}}];M.subscribe("router:afterChange",async({to:e,from:i})=>{if(!C(e.path)){if($("#admin-sidebar").show(),$("#admin-topbar").show(),C(i?.path)){$("#topbar-user-name").remove(),import("./lib/admin-theme.js").then(o=>o.refreshAdminTheme(r)),await U();const t=await f(),a=D(e.path);if(a&&R.navigate(a),j(t),we.read().signInToasts)try{const o=await r.system.notifications.list().catch(()=>[]),n=(Array.isArray(o)?o:[]).filter(s=>s.unread&&["warning","critical"].includes(s.data?.severity)).slice(0,3);for(const s of n){const l=d(s.data?.title||""),L=d((s.data?.body||"").slice(0,120));E.toast(`${l} - ${L}`,{type:s.data?.severity==="critical"?"error":"warning",duration:0})}}catch{}}V()}}),M.subscribe("router:afterChange",()=>{setTimeout(()=>{$(".btn-primary, .btn-danger").length&&Domma.effects.reveal(".btn-primary, .btn-danger",{animation:"fade",stagger:40,duration:300})},50)});const z=["#field-project","#menu-project","#collection-project","#endpoint-project","#action-project","#view-project","#block-project","#component-project","#role-project",'[name="project"]','[name="ownedByProject"]'];function G(e){return/^\/(pages|menus|context-menus|collections|forms|actions|views|blocks|components|users|roles|api-endpoints)\/(new|edit\/)/.test(e)}M.subscribe("router:afterChange",({to:e})=>{const i=e?String(e.path).split("?")[0]:"";if(!e||!G(i))return;const a=new URLSearchParams(location.hash.split("?")[1]||"").get("project");if(!a||!/\/new$/.test(i))return;let o=0;const n=60,s=1500,l=()=>{o+=n;for(const L of z){const b=document.querySelector(L);if(!b)continue;if(Array.from(b.options||[]).find(Y=>Y.value===a)){b.value=a,b.dispatchEvent(new Event("change",{bubbles:!0}));return}}o<s&&setTimeout(l,n)};setTimeout(l,n)});const F="cms_card_states",k=S.get(F)||{};M.subscribe("router:afterChange",()=>{setTimeout(()=>{$("#view-container .card-collapsible").each(function(){const e=$(this).find(".card-header h2, .card-header h3").first().text().trim();e&&k[e]==="collapsed"&&$(this).addClass("card-collapsed")})},200)}),$("#view-container").on("click",".card-collapsible .card-header",function(e){if($(e.target).closest("button, a").length)return;const i=$(this).closest(".card");i.toggleClass("card-collapsed");const t=$(this).find("h2, h3").first().text().trim();t&&(k[t]=i.hasClass("card-collapsed")?"collapsed":"open",S.set(F,k))}),Ce(),document.addEventListener("keydown",e=>{if(!(e.ctrlKey||e.metaKey)||e.key!=="s"||window.location.hash.startsWith("#/login")||window.location.hash.startsWith("#/reset-password"))return;const i=document.querySelector("#view-container .view-header button.btn-primary");i&&(e.preventDefault(),i.click())});const v=ee(),O=v.views,J={notes:{displayName:"Notes",icon:"edit-3"},todo:{displayName:"Todo",icon:"check-square"},calculator:{displayName:"Calculator",icon:"calculator"},analytics:{displayName:"Analytics",icon:"chart-bar"},seo:{displayName:"SEO",icon:"search"},wordpressImport:{displayName:"Import from WordPress",icon:"download"},contacts:{displayName:"Contacts",icon:"users"},projects:{displayName:"Projects",icon:"folder"},pages:{displayName:"Pages",icon:"file-text"},media:{displayName:"Media",icon:"image"},menus:{displayName:"Site menus",icon:"menu"},contextMenus:{displayName:"Context Menus",icon:"menu"},launchers:{displayName:"Launchers",icon:"rocket"},theme:{displayName:"Theme",icon:"droplet"},collections:{displayName:"Collections",icon:"database"},forms:{displayName:"Forms",icon:"layout"},viewsList:{displayName:"Views",icon:"eye"},actionsList:{displayName:"Actions",icon:"zap"},apiEndpoints:{displayName:"API Builder",icon:"code"},blocks:{displayName:"Blocks",icon:"box"},components:{displayName:"Components",icon:"component"},notifications:{displayName:"Notifications",icon:"bell"},roles:{displayName:"Roles",icon:"shield"},users:{displayName:"Users",icon:"users"},appearance:{displayName:"Appearance",icon:"layout"},footer:{displayName:"Footer",icon:"panel-bottom"},settings:{displayName:"Site Settings",icon:"settings"},effects:{displayName:"Effects",icon:"sparkles"},layouts:{displayName:"Layouts",icon:"layout"},plugins:{displayName:"Marketplace",icon:"store"},myProfile:{displayName:"My Profile",icon:"user"},apiTokens:{displayName:"API Tokens",icon:"key"},search:{displayName:"Search",icon:"search"},contentApi:{displayName:"Content API",icon:"file-text"},chats:{displayName:"Chats",icon:"message-circle"},dashboard:{displayName:"Dashboard",icon:"home"},dashboards:{displayName:"Dashboards",icon:"home"},pageEditor:{displayName:"Pages",section:"Edit",icon:"file-text"},menuEditor:{displayName:"Site menus",section:"Edit",icon:"menu"},menuLocations:{displayName:"Site menus",section:"Locations",icon:"map-pin"},contextMenuEditor:{displayName:"Context Menus",section:"Edit",icon:"menu"},collectionEditor:{displayName:"Collections",section:"Edit",icon:"database"},collectionEntries:{displayName:"Collections",section:"Entries",icon:"database"},formEditor:{displayName:"Forms",section:"Edit",icon:"layout"},formSubmissions:{displayName:"Forms",section:"Submissions",icon:"inbox"},viewEditor:{displayName:"Views",section:"Edit",icon:"eye"},viewPreview:{displayName:"Views",section:"Preview",icon:"eye"},actionEditor:{displayName:"Actions",section:"Edit",icon:"zap"},apiEndpointEditor:{displayName:"API Builder",section:"Edit",icon:"code"},roleEditor:{displayName:"Roles",section:"Edit",icon:"shield"},userEditor:{displayName:"Users",section:"Edit",icon:"users"},projectDetail:{displayName:"Projects",section:"Overview",icon:"folder"},projectSettings:{displayName:"Projects",section:"Settings",icon:"folder"},pluginCode:{displayName:"Marketplace",section:"Code",icon:"code"},chatKnowledge:{displayName:"Chats",section:"Knowledge",icon:"book-open"}};for(const[e,i]of Object.entries(Z))v.register(e,async()=>{let t=await i();const a=J[e];return a&&(t=_(t,{plugin:e,licence:"Built in",...a})),e==="dashboard"?H(t):t});R.use(async(e,i,t)=>{try{await v.load(e.view)}catch(a){console.error("[admin] Screen failed to load",a),O[e.view]={template:'<p role="alert">This screen could not load. Reload the page to try again.</p>'}}t()});const I=[...q];async function U(){if(m())try{const e=await r.plugins.adminConfig(),i=new Set(I.map(t=>t.path));for(const t of e.routes||[])i.has(t.path)||I.push(t);for(const[t,a]of Object.entries(e.views||{})){const o=(e.meta||{})[t];v.register(t,async()=>{const s=(await import(`/plugins/${a.entry}`))[a.exportName];if(!s)throw new Error(`Missing plugin screen: ${t}`);const l=_(s,o);return t==="dashboard"?H(l):l},JSON.stringify([a,o]))}for(const[t,{route:a}]of Object.entries(e.takeovers||{}))a&&(y[`/${t}`]=a);for(const[t,{enabled:a,displayName:o}]of Object.entries(e.tools||{}))a===!1&&(N[`/${t}`]=o);for(const{id:t,href:a}of e.css||[])if(!document.getElementById(t)){const o=document.createElement("link");o.id=t,o.rel="stylesheet",o.href=a,document.head.appendChild(o)}}catch{}}function V(){const e=x();if(!e)return;if($("#topbar-user-name").length){B(r);return}const t={"super-admin":"Super Admin",admin:"Admin",user:"User"}[e.role]||e.role,a=ge(e);$("#topbar-user").get(0).innerHTML=`
|
|
1
|
+
import{wireNotificationMenu as Q}from"./lib/topbar-notifications.js";import{installSmoothCarets as X}from"./lib/smooth-caret.js";import{viewLoaders as Z}from"./views/index.js";import{createLazyViews as ee}from"./lib/lazy-views.js";import{withPluginChrome as _}from"./lib/plugin-chrome.js";import{api as r,getUser as x,isAuthenticated as m,logout as te,sendToLogin as ae}from"./api.js";import{claimDrafts as ie}from"./lib/draft-owner.js";import{isAuthScreen as C,loginHashFor as oe}from"./lib/login-arrange.js";import{installHttpInterceptor as se}from"./http-interceptor.js";import{installResizableSlideovers as ne}from"./lib/slideover-resizable.js";import{installActivityThrobber as re}from"./lib/activity-throbber.js";import{installUpdateNotice as le,renderCmsVersion as ce}from"./lib/update-notice.js";import{renderFrameworkVersions as W,wireAccountMenu as me}from"./lib/topbar-account.js";import{refreshTopbarProject as B}from"./lib/topbar-project.js";import{isPathAllowed as pe,redirectFor as de}from"./lib/admin-scope.js";import{deliverDesktop as ue,desktopActive as he,notificationSettings as we}from"./lib/desktop-notify.js";import{avatarUrl as ge,installAccountAvatar as fe}from"./lib/avatar.js";import{installCalculator as ve}from"./lib/calculator.js";import{takeOverviewPass as be,withDashboardStrip as H}from"./lib/dashboards-strip.js";import{installHotkeys as Se}from"./lib/hotkeys-ui.js";import{applyAdminBrand as K}from"./lib/admin-brand.js";import{installRouterCatchUp as Ce}from"./lib/router-catch-up.js";import{installSidebarDrawer as Me}from"./lib/sidebar-drawer.js";$(()=>{X(document),se(),ve(),le(),re(),ne(),Me(),(async()=>{const{applyAdminTheme:e,refreshAdminTheme:i}=await import("./lib/admin-theme.js");m()?await i(r,{init:!0}):e({dommaTheme:"charcoal-dark"},{init:!0})})();let p=null,h=null,c="/",w=!1,g=null;function D(e){if(N[e])return E.toast(`${N[e]} is switched off on this site.`,{type:"info"}),"/";const[i,t]=e.split("?"),a=new URLSearchParams(t||"").get("tab");if(i==="/settings"&&["favicon","pageNavigation","breadcrumbs","motion","search"].includes(a))return`/appearance?tab=${a}`;if(e.split("?")[0]==="/my-dashboard")return"/dashboards";const o=y[e]||de(p,e);return o||((e.split("?")[0]||"/")==="/"&&c&&c!=="/"&&!be()?y[c]||c:null)}const y={},N={};R.use(async(e,i,t)=>{if(C(e.path))return t();if(!m()){ae();return}const a=D(e.path);if(a){R.navigate(a);return}t()});async function f(){try{const e=await r.get("/auth/permissions");p=e.adminScope||null,h=e.adminBrand||null,K(h),c=e.adminHome||"/",W(e.versions);const i=e.permissions||[];return w=pe(p,"/settings")&&i.some(t=>t==="settings"||t.startsWith("settings.")),g=i.some(t=>t==="notifications"||t.startsWith("notifications.")),i}catch{return p=null,c="/",h||K(null),w=!1,g=null,[]}}document.addEventListener("dm:admin-home-changed",()=>{f()});let P=null,A=!1;document.addEventListener("dm:sidebar-rebuild",()=>{if(B(r),P){A=!0;return}P=(async()=>{do{A=!1;try{await j(await f())}catch{}}while(A)})().finally(()=>{P=null})});async function j(e){const{renderAdminSidebar:i}=await import("./lib/sidebar-renderer.js");await i({mount:"#admin-sidebar",permissions:e,adminScope:p,brand:h})}M.subscribe("router:afterChange",({to:e})=>{C(e.path)&&(u&&(clearInterval(u),u=null),p=null,c="/",w=!1,g=null)});const q=[{path:"/",view:"dashboard",title:"Dashboard - Domma CMS"},{path:"/dashboards",view:"dashboards",title:"Dashboards - Domma CMS"},{path:"/my-dashboard",view:"dashboards",title:"Dashboards - Domma CMS"},{path:"/pages",view:"pages",title:"Pages - Domma CMS"},{path:"/pages/new",view:"pageEditor",title:"New Page - Domma CMS"},{path:"/pages/edit/*",view:"pageEditor",title:"Edit Page - Domma CMS"},{path:"/media",view:"media",title:"Media - Domma CMS"},{path:"/menus",view:"menus",title:"Menus - Domma CMS"},{path:"/context-menus",view:"contextMenus",title:"Context Menus - Domma CMS"},{path:"/context-menus/new",view:"contextMenuEditor",title:"New Context Menu - Domma CMS"},{path:"/context-menus/edit/:slug",view:"contextMenuEditor",title:"Edit Context Menu - Domma CMS"},{path:"/launchers",view:"launchers",title:"Launchers - Domma CMS"},{path:"/menus/new",view:"menuEditor",title:"New Menu - Domma CMS"},{path:"/menus/edit/:slug",view:"menuEditor",title:"Edit Menu - Domma CMS"},{path:"/menu-locations",view:"menuLocations",title:"Menu Locations - Domma CMS"},{path:"/navigation",view:"menusRedirect",title:"Menus - Domma CMS"},{path:"/layouts",view:"layouts",title:"Layouts - Domma CMS"},{path:"/appearance",view:"appearance",title:"Appearance - Domma CMS"},{path:"/footer",view:"footer",title:"Footer - Domma CMS"},{path:"/settings",view:"settings",title:"Settings - Domma CMS"},{path:"/theme",view:"theme",title:"Theme - Domma CMS"},{path:"/users",view:"users",title:"Users - Domma CMS"},{path:"/users/new",view:"userEditor",title:"New User - Domma CMS"},{path:"/users/edit/:id",view:"userEditor",title:"Edit User - Domma CMS"},{path:"/plugins",view:"plugins",title:"Plugins - Domma CMS"},{path:"/plugins/code/:name",view:"pluginCode",title:"Plugin Code - Domma CMS"},{path:"/documentation",view:"documentation",title:"Usage - Domma CMS"},{path:"/tutorials",view:"tutorials",title:"Tutorials - Domma CMS"},{path:"/tutorials/crud",view:"tutorialCrud",title:"Building a CRUD App - Domma CMS"},{path:"/tutorials/editor",view:"tutorialEditor",title:"The Editor - Domma CMS"},{path:"/tutorials/plugin",view:"tutorialPlugin",title:"Writing a Tool - Domma CMS"},{path:"/tutorials/forms",view:"tutorialForms",title:"Form Follow-Up - Domma CMS"},{path:"/docs/components",view:"componentsReference",title:"Components Reference - Domma CMS"},{path:"/docs/components-howto",view:"componentsHowto",title:"Components How-To - Domma CMS"},{path:"/docs/components-walkthrough",view:"componentsWalkthrough",title:"Components Walkthrough - Domma CMS"},{path:"/docs/components-rules",view:"componentsRules",title:"Components Rules - Domma CMS"},{path:"/docs/usage/pages",view:"usagePages",title:"Pages - Usage - Domma CMS"},{path:"/docs/usage/media",view:"usageMedia",title:"Media - Usage - Domma CMS"},{path:"/docs/usage/navigation",view:"usageNavigation",title:"Navigation - Usage - Domma CMS"},{path:"/docs/usage/dconfig",view:"usageDconfig",title:"DConfig - Usage - Domma CMS"},{path:"/docs/usage/shortcodes",view:"usageShortcodes",title:"Shortcodes - Usage - Domma CMS"},{path:"/docs/usage/site-settings",view:"usageSiteSettings",title:"Site Settings - Usage - Domma CMS"},{path:"/docs/usage/plugins",view:"usagePlugins",title:"Plugins - Usage - Domma CMS"},{path:"/docs/usage/users-roles",view:"usageUsersRoles",title:"Users & Roles - Usage - Domma CMS"},{path:"/docs/usage/views",view:"usageViews",title:"Views - Usage - Domma CMS"},{path:"/docs/usage/actions",view:"usageActions",title:"Actions - Usage - Domma CMS"},{path:"/docs/usage/cta-shortcode",view:"usageCtaShortcode",title:"CTA Shortcode - Usage - Domma CMS"},{path:"/docs/usage/editions",view:"usageEditions",title:"Editions & Licences - Usage - Domma CMS"},{path:"/docs/usage/collections",view:"usageCollections",title:"Collections & Forms - Usage - Domma CMS"},{path:"/docs/usage/blocks",view:"usageBlocks",title:"Blocks - Usage - Domma CMS"},{path:"/docs/usage/tools",view:"usageTools",title:"Built-in Tools - Usage - Domma CMS"},{path:"/docs/usage/dashboard",view:"usageDashboard",title:"Dashboard - Usage - Domma CMS"},{path:"/docs/usage/search-engines",view:"usageSearchEngines",title:"Search Engines & AI - Usage - Domma CMS"},{path:"/docs/usage/launchers",view:"usageLaunchers",title:"Launchers - Usage - Domma CMS"},{path:"/docs/usage/chat",view:"usageChat",title:"Chat & Knowledge - Usage - Domma CMS"},{path:"/docs/plugins",view:"pluginGuides",title:"Plugin Guides - Domma CMS"},{path:"/docs/plugins/*",view:"pluginGuide",title:"Plugin Guide - Domma CMS"},{path:"/docs/api/authentication",view:"apiRefAuthentication",title:"Authentication - API - Domma CMS"},{path:"/docs/api/pages",view:"apiRefPages",title:"Pages - API - Domma CMS"},{path:"/docs/api/settings",view:"apiRefSettings",title:"Settings - API - Domma CMS"},{path:"/docs/api/layouts",view:"apiRefLayouts",title:"Layouts - API - Domma CMS"},{path:"/docs/api/navigation",view:"apiRefNavigation",title:"Navigation - API - Domma CMS"},{path:"/docs/api/media",view:"apiRefMedia",title:"Media - API - Domma CMS"},{path:"/docs/api/users",view:"apiRefUsers",title:"Users - API - Domma CMS"},{path:"/docs/api/plugins",view:"apiRefPlugins",title:"Plugins - API - Domma CMS"},{path:"/docs/api/collections",view:"apiRefCollections",title:"Collections - API - Domma CMS"},{path:"/docs/api/views",view:"apiRefViews",title:"Views API - Domma CMS"},{path:"/docs/api/actions",view:"apiRefActions",title:"Actions API - Domma CMS"},{path:"/docs/api/forms",view:"apiRefForms",title:"Forms API - Domma CMS"},{path:"/docs/api/scaffold",view:"apiRefScaffold",title:"Scaffold API - Domma CMS"},{path:"/docs/api/external",view:"apiRefExternal",title:"External API & Tokens - Domma CMS"},{path:"/docs/api/content",view:"apiRefContent",title:"Content API - Domma CMS"},{path:"/docs/api/builder",view:"apiRefBuilder",title:"API Builder - Domma CMS"},{path:"/api-reference",view:"apiReference",title:"API Reference - Domma CMS"},{path:"/collections",view:"collections",title:"Collections - Domma CMS"},{path:"/collections/new",view:"collectionEditor",title:"New Collection - Domma CMS"},{path:"/collections/edit/:slug",view:"collectionEditor",title:"Edit Collection - Domma CMS"},{path:"/collections/:slug/entries",view:"collectionEntries",title:"Entries - Domma CMS"},{path:"/forms",view:"forms",title:"Forms - Domma CMS"},{path:"/forms/new",view:"formEditor",title:"New Form - Domma CMS"},{path:"/forms/edit/:slug",view:"formEditor",title:"Edit Form - Domma CMS"},{path:"/forms/:slug/submissions",view:"formSubmissions",title:"Submissions - Domma CMS"},{path:"/views",view:"viewsList",title:"Views - Domma CMS"},{path:"/views/new",view:"viewEditor",title:"New View - Domma CMS"},{path:"/views/edit/:slug",view:"viewEditor",title:"Edit View - Domma CMS"},{path:"/views/:slug/preview",view:"viewPreview",title:"View Preview - Domma CMS"},{path:"/actions",view:"actionsList",title:"Actions - Domma CMS"},{path:"/actions/new",view:"actionEditor",title:"New Action - Domma CMS"},{path:"/actions/edit/:slug",view:"actionEditor",title:"Edit Action - Domma CMS"},{path:"/pro/docs",view:"proDocs",title:"Pro Documentation - Domma CMS"},{path:"/blocks",view:"blocks",title:"Blocks - Domma CMS"},{path:"/blocks/new",view:"pageEditor",title:"New Block - Domma CMS"},{path:"/blocks/edit/:name",view:"pageEditor",title:"Edit Block - Domma CMS"},{path:"/components",view:"components",title:"Components - Domma CMS"},{path:"/components/new",view:"pageEditor",title:"New Component - Domma CMS"},{path:"/components/edit/:name",view:"pageEditor",title:"Edit Component - Domma CMS"},{path:"/my-profile",view:"myProfile",title:"My Profile - Domma CMS"},{path:"/roles",view:"roles",title:"Roles & Permissions - Domma CMS"},{path:"/roles/edit/:id",view:"roleEditor",title:"Edit Role - Domma CMS"},{path:"/effects",view:"effects",title:"Effects - Domma CMS"},{path:"/search",view:"search",title:"Search - Domma CMS"},{path:"/content-api",view:"contentApi",title:"Content API - Domma CMS"},{path:"/launchers/chats",view:"chats",title:"Chats - Domma CMS"},{path:"/launchers/chats/:id",view:"chats",title:"Chats - Domma CMS"},{path:"/launchers/knowledge",view:"chatKnowledge",title:"Chat Knowledge - Domma CMS"},{path:"/notes",view:"notes",title:"Notes - Domma CMS"},{path:"/todo",view:"todo",title:"Todo - Domma CMS"},{path:"/calculator",view:"calculator",title:"Calculator - Domma CMS"},{path:"/analytics",view:"analytics",title:"Analytics - Domma CMS"},{path:"/seo",view:"seo",title:"SEO - Domma CMS"},{path:"/seo/:tab",view:"seo",title:"SEO - Domma CMS"},{path:"/wordpress-import",view:"wordpressImport",title:"Import from WordPress - Domma CMS"},{path:"/contacts",view:"contacts",title:"Contacts - Domma CMS"},{path:"/calls/new",view:"callNew",title:"Call now - Domma CMS"},{path:"/system/notifications",view:"notifications",title:"Notifications - Domma CMS"},{path:"/api-tokens",view:"apiTokens",title:"API Tokens - Domma CMS"},{path:"/api-endpoints",view:"apiEndpoints",title:"API Builder - Domma CMS"},{path:"/api-endpoints/new",view:"apiEndpointEditor",title:"New API Endpoint - Domma CMS"},{path:"/api-endpoints/edit/:id",view:"apiEndpointEditor",title:"Edit API Endpoint - Domma CMS"},{path:"/projects",view:"projects",title:"Projects - Domma CMS"},{path:"/projects/new",view:"projects",title:"New Project - Domma CMS"},{path:"/projects/edit/:slug",view:"projects",title:"Edit Project - Domma CMS"},{path:"/projects/:slug/settings",view:"projectSettings",title:"Project settings - Domma CMS"},{path:"/projects/:slug/pages",view:"pages",title:"Project pages - Domma CMS"},{path:"/projects/:slug/collections",view:"collections",title:"Project collections - Domma CMS"},{path:"/projects/:slug/forms",view:"forms",title:"Project forms - Domma CMS"},{path:"/projects/:slug/actions",view:"actionsList",title:"Project actions - Domma CMS"},{path:"/projects/:slug/menus",view:"menus",title:"Project menus - Domma CMS"},{path:"/projects/:slug/blocks",view:"blocks",title:"Project blocks - Domma CMS"},{path:"/projects/:slug/components",view:"components",title:"Project components - Domma CMS"},{path:"/projects/:slug/views",view:"viewsList",title:"Project views - Domma CMS"},{path:"/projects/:slug/roles",view:"roles",title:"Project roles - Domma CMS"},{path:"/projects/:slug/users",view:"users",title:"Project users - Domma CMS"},{path:"/projects/:slug/apis",view:"apiEndpoints",title:"Project APIs - Domma CMS"},{path:"/projects/:slug",view:"projectDetail",title:"Project - Domma CMS"},{path:"/login",view:"login",title:"Sign in - Domma CMS",onEnter:()=>{$("#admin-sidebar").hide(),$("#admin-topbar").hide()}},{path:"/reset-password",view:"login",title:"Reset Password - Domma CMS",onEnter:()=>{$("#admin-sidebar").hide(),$("#admin-topbar").hide()}}];M.subscribe("router:afterChange",async({to:e,from:i})=>{if(!C(e.path)){if($("#admin-sidebar").show(),$("#admin-topbar").show(),C(i?.path)){$("#topbar-user-name").remove(),import("./lib/admin-theme.js").then(o=>o.refreshAdminTheme(r)),await T();const t=await f(),a=D(e.path);if(a&&R.navigate(a),j(t),we.read().signInToasts)try{const o=await r.system.notifications.list().catch(()=>[]),n=(Array.isArray(o)?o:[]).filter(s=>s.unread&&["warning","critical"].includes(s.data?.severity)).slice(0,3);for(const s of n){const l=d(s.data?.title||""),L=d((s.data?.body||"").slice(0,120));E.toast(`${l} - ${L}`,{type:s.data?.severity==="critical"?"error":"warning",duration:0})}}catch{}}V()}}),M.subscribe("router:afterChange",()=>{setTimeout(()=>{$(".btn-primary, .btn-danger").length&&Domma.effects.reveal(".btn-primary, .btn-danger",{animation:"fade",stagger:40,duration:300})},50)});const z=["#field-project","#menu-project","#collection-project","#endpoint-project","#action-project","#view-project","#block-project","#component-project","#role-project",'[name="project"]','[name="ownedByProject"]'];function G(e){return/^\/(pages|menus|context-menus|collections|forms|actions|views|blocks|components|users|roles|api-endpoints)\/(new|edit\/)/.test(e)}M.subscribe("router:afterChange",({to:e})=>{const i=e?String(e.path).split("?")[0]:"";if(!e||!G(i))return;const a=new URLSearchParams(location.hash.split("?")[1]||"").get("project");if(!a||!/\/new$/.test(i))return;let o=0;const n=60,s=1500,l=()=>{o+=n;for(const L of z){const b=document.querySelector(L);if(!b)continue;if(Array.from(b.options||[]).find(Y=>Y.value===a)){b.value=a,b.dispatchEvent(new Event("change",{bubbles:!0}));return}}o<s&&setTimeout(l,n)};setTimeout(l,n)});const F="cms_card_states",k=S.get(F)||{};M.subscribe("router:afterChange",()=>{setTimeout(()=>{$("#view-container .card-collapsible").each(function(){const e=$(this).find(".card-header h2, .card-header h3").first().text().trim();e&&k[e]==="collapsed"&&$(this).addClass("card-collapsed")})},200)}),$("#view-container").on("click",".card-collapsible .card-header",function(e){if($(e.target).closest("button, a").length)return;const i=$(this).closest(".card");i.toggleClass("card-collapsed");const t=$(this).find("h2, h3").first().text().trim();t&&(k[t]=i.hasClass("card-collapsed")?"collapsed":"open",S.set(F,k))}),Se(),document.addEventListener("keydown",e=>{if(!(e.ctrlKey||e.metaKey)||e.key!=="s"||window.location.hash.startsWith("#/login")||window.location.hash.startsWith("#/reset-password"))return;const i=document.querySelector("#view-container .view-header button.btn-primary");i&&(e.preventDefault(),i.click())});const v=ee(),O=v.views,J={notes:{displayName:"Notes",icon:"edit-3"},todo:{displayName:"Todo",icon:"check-square"},calculator:{displayName:"Calculator",icon:"calculator"},analytics:{displayName:"Analytics",icon:"chart-bar"},seo:{displayName:"SEO",icon:"search"},wordpressImport:{displayName:"Import from WordPress",icon:"download"},contacts:{displayName:"Contacts",icon:"users"},projects:{displayName:"Projects",icon:"folder"},pages:{displayName:"Pages",icon:"file-text"},media:{displayName:"Media",icon:"image"},menus:{displayName:"Site menus",icon:"menu"},contextMenus:{displayName:"Context Menus",icon:"menu"},launchers:{displayName:"Launchers",icon:"rocket"},theme:{displayName:"Theme",icon:"droplet"},collections:{displayName:"Collections",icon:"database"},forms:{displayName:"Forms",icon:"layout"},viewsList:{displayName:"Views",icon:"eye"},actionsList:{displayName:"Actions",icon:"zap"},apiEndpoints:{displayName:"API Builder",icon:"code"},blocks:{displayName:"Blocks",icon:"box"},components:{displayName:"Components",icon:"component"},notifications:{displayName:"Notifications",icon:"bell"},roles:{displayName:"Roles",icon:"shield"},users:{displayName:"Users",icon:"users"},appearance:{displayName:"Appearance",icon:"layout"},footer:{displayName:"Footer",icon:"panel-bottom"},settings:{displayName:"Site Settings",icon:"settings"},effects:{displayName:"Effects",icon:"sparkles"},layouts:{displayName:"Layouts",icon:"layout"},plugins:{displayName:"Marketplace",icon:"store"},myProfile:{displayName:"My Profile",icon:"user"},apiTokens:{displayName:"API Tokens",icon:"key"},search:{displayName:"Search",icon:"search"},contentApi:{displayName:"Content API",icon:"file-text"},chats:{displayName:"Chats",icon:"message-circle"},dashboard:{displayName:"Dashboard",icon:"home"},dashboards:{displayName:"Dashboards",icon:"home"},pageEditor:{displayName:"Pages",section:"Edit",icon:"file-text"},menuEditor:{displayName:"Site menus",section:"Edit",icon:"menu"},menuLocations:{displayName:"Site menus",section:"Locations",icon:"map-pin"},contextMenuEditor:{displayName:"Context Menus",section:"Edit",icon:"menu"},collectionEditor:{displayName:"Collections",section:"Edit",icon:"database"},collectionEntries:{displayName:"Collections",section:"Entries",icon:"database"},formEditor:{displayName:"Forms",section:"Edit",icon:"layout"},formSubmissions:{displayName:"Forms",section:"Submissions",icon:"inbox"},viewEditor:{displayName:"Views",section:"Edit",icon:"eye"},viewPreview:{displayName:"Views",section:"Preview",icon:"eye"},actionEditor:{displayName:"Actions",section:"Edit",icon:"zap"},apiEndpointEditor:{displayName:"API Builder",section:"Edit",icon:"code"},roleEditor:{displayName:"Roles",section:"Edit",icon:"shield"},userEditor:{displayName:"Users",section:"Edit",icon:"users"},projectDetail:{displayName:"Projects",section:"Overview",icon:"folder"},projectSettings:{displayName:"Projects",section:"Settings",icon:"folder"},pluginCode:{displayName:"Marketplace",section:"Code",icon:"code"},chatKnowledge:{displayName:"Chats",section:"Knowledge",icon:"book-open"}};for(const[e,i]of Object.entries(Z))v.register(e,async()=>{let t=await i();const a=J[e];return a&&(t=_(t,{plugin:e,licence:"Built in",...a})),e==="dashboard"?H(t):t});R.use(async(e,i,t)=>{try{await v.load(e.view)}catch(a){console.error("[admin] Screen failed to load",a),O[e.view]={template:'<p role="alert">This screen could not load. Reload the page to try again.</p>'}}t()});const I=[...q];async function T(){if(m())try{const e=await r.plugins.adminConfig(),i=new Set(I.map(t=>t.path));for(const t of e.routes||[])i.has(t.path)||I.push(t);for(const[t,a]of Object.entries(e.views||{})){const o=(e.meta||{})[t];v.register(t,async()=>{const s=(await import(`/plugins/${a.entry}`))[a.exportName];if(!s)throw new Error(`Missing plugin screen: ${t}`);const l=_(s,o);return t==="dashboard"?H(l):l},JSON.stringify([a,o]))}for(const[t,{route:a}]of Object.entries(e.takeovers||{}))a&&(y[`/${t}`]=a);e.mediaPicker&&(globalThis[Symbol.for("domma.media-picker")]=e.mediaPicker);for(const[t,{enabled:a,displayName:o}]of Object.entries(e.tools||{}))a===!1&&(N[`/${t}`]=o);for(const{id:t,href:a}of e.css||[])if(!document.getElementById(t)){const o=document.createElement("link");o.id=t,o.rel="stylesheet",o.href=a,document.head.appendChild(o)}}catch{}}function V(){const e=x();if(!e)return;if($("#topbar-user-name").length){B(r);return}const t={"super-admin":"Super Admin",admin:"Admin",user:"User"}[e.role]||e.role,a=ge(e);$("#topbar-user").get(0).innerHTML=`
|
|
2
2
|
<a id="topbar-project" class="topbar-action-link topbar-project" hidden>
|
|
3
3
|
<span data-icon="folder"></span>
|
|
4
4
|
<span id="topbar-project-name" class="topbar-project-name"></span>
|
|
@@ -50,4 +50,4 @@ import{wireNotificationMenu as Q}from"./lib/topbar-notifications.js";import{inst
|
|
|
50
50
|
</a>
|
|
51
51
|
</div>
|
|
52
52
|
</div>
|
|
53
|
-
`;const o=$("#topbar-bell").get(0);o&&(o.hidden=!0);const n=$("#topbar-settings").get(0);n&&(n.hidden=!w),$("#topbar-logout-btn").on("click",s=>{s.preventDefault(),te()}),Domma.icons.scan("#admin-topbar"),E.tooltip("#topbar-actions [data-tooltip]",{placement:"bottom"}),me(e),Q({refreshBadge:
|
|
53
|
+
`;const o=$("#topbar-bell").get(0);o&&(o.hidden=!0);const n=$("#topbar-settings").get(0);n&&(n.hidden=!w),$("#topbar-logout-btn").on("click",s=>{s.preventDefault(),te()}),Domma.icons.scan("#admin-topbar"),E.tooltip("#topbar-actions [data-tooltip]",{placement:"bottom"}),me(e),Q({refreshBadge:U}),fe(e),W(),ce(),B(r),U(),u||(u=setInterval(U,6e4))}function d(e){return String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}let u=null;async function U(){if(!(!m()||g===!1))try{const{count:e}=await r.system.notifications.unreadCount();$("#topbar-bell").removeAttr("hidden");const i=$("#topbar-bell-badge");e>0?i.text(e>99?"99+":String(e)).removeAttr("hidden"):i.attr("hidden","").text(""),e>0&&he()&&ue(await r.system.notifications.list().catch(()=>[]))}catch{}}(async()=>{if(!m()&&!window.location.hash.startsWith("#/reset-password"))window.location.hash.startsWith("#/login")||(window.location.hash=oe(window.location.hash));else{ie(x()?.id);const a=x(),[o]=await Promise.all([a?f():Promise.resolve([]),T()]);if(a){const n=(window.location.hash||"#/").slice(1)||"/",s=D(n);s&&(window.location.hash=`#${s}`),j(o).catch(l=>console.error("[admin] Sidebar failed to load",l)),V()}}const e=R._extractParams.bind(R);R._extractParams=function(a,o){const n=o.indexOf("?");if(n!==-1&&(o=o.slice(0,n)),a.endsWith("/*")){const s=a.slice(0,-2);return o.startsWith(s+"/")?{}:null}return e(a,o)};const i=R._renderNotFound.bind(R);let t="";R._renderNotFound=async function(a){return m()&&t!==a&&(t=a,await T(),R._matchRoute(a).route)?(t="",R._handleRouteChange()):(t="",m()&&$("#admin-sidebar").get(0)?.style.display==="none"?(E.toast("That link goes nowhere - here is your home page.",{type:"warning"}),R.navigate("/")):i(a))},Ce(R),R.init({container:"#view-container",routes:I,views:O,default:"/",transitions:{enter:"fadeIn",leave:"fadeOut",duration:150}})})()});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{api as Ee}from"../api.js";function Ae(){const o={"rotate-cw":{viewBox:"0 0 24 24",stroke:"currentColor",fill:"none",strokeWidth:2,path:"M21 2v6h-6M21 8A9 9 0 1 0 19.07 14.4"},"rotate-ccw":{viewBox:"0 0 24 24",stroke:"currentColor",fill:"none",strokeWidth:2,path:"M3 2v6h6M3 8a9 9 0 1 1 1.93 6.4"},"flip-h":{viewBox:"0 0 24 24",stroke:"currentColor",fill:"none",strokeWidth:2,paths:["M12 3v18","M4 6l4 6-4 6","M20 6l-4 6 4 6"]},"flip-v":{viewBox:"0 0 24 24",stroke:"currentColor",fill:"none",strokeWidth:2,paths:["M3 12h18","M6 4l6 4 6-4","M6 20l6-4 6 4"]},lock:{viewBox:"0 0 24 24",stroke:"currentColor",fill:"none",strokeWidth:2,paths:["M17 11H7a2 2 0 0 0-2 2v7a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2v-7a2 2 0 0 0-2-2z","M12 8a4 4 0 0 0-4 4"],path:"M12 8V5a4 4 0 0 1 4 4v2"},unlock:{viewBox:"0 0 24 24",stroke:"currentColor",fill:"none",strokeWidth:2,paths:["M17 11H7a2 2 0 0 0-2 2v7a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2v-7a2 2 0 0 0-2-2z","M8 11V7a4 4 0 0 1 8 0"]},"crop-icon":{viewBox:"0 0 24 24",stroke:"currentColor",fill:"none",strokeWidth:2,paths:["M6 2v14a2 2 0 0 0 2 2h14","M18 22V8a2 2 0 0 0-2-2H2"]},sliders:{viewBox:"0 0 24 24",stroke:"currentColor",fill:"none",strokeWidth:2,paths:["M4 21v-7","M4 10V3","M12 21v-9","M12 8V3","M20 21v-5","M20 12V3","M1 14h6","M9 8h6","M17 16h6"]},droplet:{viewBox:"0 0 24 24",stroke:"currentColor",fill:"none",strokeWidth:2,path:"M12 2.69l5.66 5.66a8 8 0 1 1-11.31 0z"},"image-plus":{viewBox:"0 0 24 24",stroke:"currentColor",fill:"none",strokeWidth:2,paths:["M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7","M16 5h6","M19 2v6","M3 15l5-5 4 4 3-3 4 4"]},frame:{viewBox:"0 0 24 24",stroke:"currentColor",fill:"none",strokeWidth:2,paths:["M7 3H3v4","M17 3h4v4","M7 21H3v-4","M17 21h4v-4"]},"file-type":{viewBox:"0 0 24 24",stroke:"currentColor",fill:"none",strokeWidth:2,paths:["M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z","M14 2v6h6","M10 13l-2 4h8l-2-4"]}};for(const[p,M]of Object.entries(o))try{I.register(p,M)}catch{}}function oe(o){const p=document.createElement("span");return p.setAttribute("data-icon",o),p}function K(o,p,M){const i=document.createElement("button");return i.className=o,i.type="button",i.title=M,i.appendChild(oe(p)),i}function je(){const o=document.createElement("span");return o.className="image-editor-sep",o}function Ve(o){for(;o.firstChild;)o.removeChild(o.firstChild)}export async function openImageEditor(o){Ae();let p;try{p=await Ee.media.info(o.name)}catch(M){return E.toast(`Cannot open editor: ${M.message}`,{type:"error"}),!1}return new Promise(M=>{let i=null,F=!1,j=0,D=!1,q=!1,O=!0;const ye=p.width/p.height;let se=null,y=null;const r={brightness:1,contrast:1,saturation:1,blur:0,sharpen:0,gamma:1},u={image:null,position:"bottom-right",opacity:50,scale:15},L={width:0,colour:"#000000",mode:"solid"},v={type:null,quality:85},k=document.createElement("div");k.className="image-editor";const C=document.createElement("div");C.className="image-editor-toolbar";const le=K("btn btn-sm btn-ghost editor-toolbar-btn","crop-icon","Toggle crop"),ke=K("btn btn-sm btn-ghost editor-toolbar-btn","rotate-cw","Rotate clockwise"),xe=K("btn btn-sm btn-ghost editor-toolbar-btn","rotate-ccw","Rotate counter-clockwise"),re=K("btn btn-sm btn-ghost editor-toolbar-btn","flip-h","Flip horizontal"),ie=K("btn btn-sm btn-ghost editor-toolbar-btn","flip-v","Flip vertical");C.appendChild(le),C.appendChild(je()),C.appendChild(xe),C.appendChild(ke),C.appendChild(je()),C.appendChild(re),C.appendChild(ie);const U=document.createElement("div");U.className="image-editor-canvas";const $=document.createElement("img");$.src=o.url+"?t="+Date.now(),$.alt=o.name,$.style.maxWidth="100%",U.appendChild($);const x=document.createElement("div");x.className="image-editor-resize";const Ne=document.createElement("label");Ne.textContent="W";const g=document.createElement("input");g.type="number",g.className="form-input",g.value=p.width,g.min=1;const h=document.createElement("button");h.type="button",h.className="btn btn-sm btn-ghost editor-toolbar-btn active",h.title="Lock aspect ratio",h.appendChild(oe("lock"));const Me=document.createElement("label");Me.textContent="H";const w=document.createElement("input");w.type="number",w.className="form-input",w.value=p.height,w.min=1;const X=document.createElement("span");X.className="text-muted",X.style.marginLeft="auto",X.textContent=`Original: ${p.width}\xD7${p.height}`,x.appendChild(Ne),x.appendChild(g),x.appendChild(h),x.appendChild(Me),x.appendChild(w),x.appendChild(X);const Y=document.createElement("div");Y.className="image-editor-effects";const ce=document.createElement("div");ce.className="image-editor-tab-bar";const de=[{id:"filters",label:"Filters",icon:"droplet"},{id:"adjust",label:"Adjust",icon:"sliders"},{id:"watermark",label:"Watermark",icon:"image-plus"},{id:"border",label:"Border",icon:"frame"},{id:"format",label:"Format",icon:"file-type"}],c={},Le={};de.forEach(({id:e,label:t,icon:a},s)=>{const n=document.createElement("button");n.type="button",n.className="image-editor-tab-btn"+(s===0?" active":""),n.dataset.tab=e,n.appendChild(oe(a));const m=document.createElement("span");m.textContent=t,n.appendChild(m),n.addEventListener("click",()=>Oe(e)),ce.appendChild(n),Le[e]=n;const l=document.createElement("div");l.className="image-editor-tab-panel",l.style.display=s===0?"block":"none",c[e]=l});function Oe(e){de.forEach(({id:t})=>{c[t].style.display=t===e?"block":"none",Le[t].classList.toggle("active",t===e)})}Y.appendChild(ce),de.forEach(({id:e})=>Y.appendChild(c[e]));const Be=[{id:"grayscale",label:"Grayscale",cssPreview:!0},{id:"sepia",label:"Sepia",cssPreview:!0},{id:"warm",label:"Warm",cssPreview:!1},{id:"cool",label:"Cool",cssPreview:!1},{id:"enhance",label:"Enhance",cssPreview:!1},{id:"sharpen",label:"Sharpen",cssPreview:!1},{id:"soften",label:"Soften",cssPreview:!1},{id:"invert",label:"Invert",cssPreview:!0}],pe=document.createElement("div");pe.className="ie-presets-grid";const Pe={};Be.forEach(({id:e,label:t})=>{const a=document.createElement("button");a.type="button",a.className="btn btn-sm btn-ghost ie-preset-btn",a.textContent=t,a.addEventListener("click",()=>{y=y===e?null:e,Be.forEach(({id:s})=>{Pe[s].classList.toggle("active",s===y)}),ae()}),Pe[e]=a,pe.appendChild(a)});const me=document.createElement("p");me.className="ie-server-note",me.textContent="Warm, Cool, Enhance, Sharpen, and Soften have no live preview - applied on save only.",c.filters.appendChild(pe),c.filters.appendChild(me);const Se={};function A(e,t,a,s,n,m){const l=document.createElement("div");l.className="ie-slider-row";const b=document.createElement("label");b.className="ie-slider-label",b.textContent=e;const d=document.createElement("input");d.type="range",d.min=t,d.max=a,d.step=s,d.value=n,d.className="ie-slider";const f=document.createElement("span");return f.className="ie-slider-val",f.textContent=n,d.addEventListener("input",()=>{const R=parseFloat(d.value);f.textContent=s<1?R.toFixed(1):String(Math.round(R)),m(R)}),l.appendChild(b),l.appendChild(d),l.appendChild(f),{row:l,slider:d,valDisplay:f,defaultVal:n,reset(){d.value=n,f.textContent=n}}}const We=[{key:"brightness",label:"Brightness",min:.2,max:3,step:.1,def:1},{key:"contrast",label:"Contrast",min:.2,max:3,step:.1,def:1},{key:"saturation",label:"Saturation",min:0,max:3,step:.1,def:1},{key:"blur",label:"Blur",min:0,max:10,step:.5,def:0},{key:"sharpen",label:"Sharpen",min:0,max:10,step:.5,def:0},{key:"gamma",label:"Gamma",min:.5,max:3,step:.1,def:1}];We.forEach(({key:e,label:t,min:a,max:s,step:n,def:m})=>{const l=A(t,a,s,n,m,b=>{r[e]=b,ae()});Se[e]=l,c.adjust.appendChild(l.row)});const z=document.createElement("button");z.type="button",z.className="btn btn-sm btn-ghost",z.style.marginTop="0.5rem",z.textContent="Reset adjustments",z.addEventListener("click",()=>{We.forEach(({key:e,def:t})=>{r[e]=t,Se[e].reset()}),ae()}),c.adjust.appendChild(z);const B=document.createElement("button");B.type="button",B.className="btn btn-sm btn-secondary",B.textContent="Choose watermark image\u2026";const N=document.createElement("div");N.className="ie-wm-preview-row",N.style.display="none";const ue=document.createElement("img");ue.className="ie-wm-preview-img";const he=document.createElement("span");he.className="ie-wm-preview-name";const V=document.createElement("button");V.type="button",V.className="btn btn-sm btn-ghost",V.textContent="Remove",V.addEventListener("click",()=>{u.image=null,N.style.display="none",B.style.display=""}),N.appendChild(ue),N.appendChild(he),N.appendChild(V),B.addEventListener("click",async()=>{const e=await De();e&&(u.image=e.name,ue.src=e.url,he.textContent=e.name,N.style.display="flex",B.style.display="none")});const _=document.createElement("div");_.className="ie-slider-row";const be=document.createElement("label");be.className="ie-slider-label",be.textContent="Position";const G=document.createElement("select");G.className="form-select ie-select",["top-left","top-center","top-right","center-left","center","center-right","bottom-left","bottom-center","bottom-right"].forEach(e=>{const t=document.createElement("option");t.value=e,t.textContent=e.replace(/-/g," ").replace(/\b\w/g,a=>a.toUpperCase()),e==="bottom-right"&&(t.selected=!0),G.appendChild(t)}),G.addEventListener("change",()=>{u.position=G.value}),_.appendChild(be),_.appendChild(G);const $e=A("Opacity %",0,100,1,50,e=>{u.opacity=e}),ze=A("Scale %",5,50,1,15,e=>{u.scale=e});c.watermark.appendChild(B),c.watermark.appendChild(N),c.watermark.appendChild(_),c.watermark.appendChild($e.row),c.watermark.appendChild(ze.row);const He=A("Width (px)",0,200,1,0,e=>{L.width=e}),Z=document.createElement("div");Z.className="ie-slider-row";const fe=document.createElement("label");fe.className="ie-slider-label",fe.textContent="Colour";const H=document.createElement("input");H.type="color",H.value="#000000",H.className="ie-colour-input",H.addEventListener("input",()=>{L.colour=H.value}),Z.appendChild(fe),Z.appendChild(H);const ee=document.createElement("div");ee.className="ie-slider-row";const ve=document.createElement("label");ve.className="ie-slider-label",ve.textContent="Mode";const T=document.createElement("select");T.className="form-select ie-select",[["solid","Solid"],["mirror","Mirror"],["repeat","Repeat"]].forEach(([e,t])=>{const a=document.createElement("option");a.value=e,a.textContent=t,T.appendChild(a)}),T.addEventListener("change",()=>{L.mode=T.value}),ee.appendChild(ve),ee.appendChild(T),c.border.appendChild(He.row),c.border.appendChild(Z),c.border.appendChild(ee);const te=document.createElement("div");te.className="ie-slider-row";const Ce=document.createElement("label");Ce.className="ie-slider-label",Ce.textContent="Output format";const P=document.createElement("select");P.className="form-select ie-select",[["","Keep original"],["jpeg","JPEG"],["png","PNG"],["webp","WebP"]].forEach(([e,t])=>{const a=document.createElement("option");a.value=e,a.textContent=t,P.appendChild(a)}),te.appendChild(Ce),te.appendChild(P);const ge=A("Quality",1,100,1,85,e=>{v.quality=e});ge.row.style.display="none",P.addEventListener("change",()=>{v.type=P.value||null,ge.row.style.display=P.value==="jpeg"||P.value==="webp"?"flex":"none"}),c.format.appendChild(te),c.format.appendChild(ge.row);const ne=document.createElement("div");ne.className="image-editor-footer";const Q=document.createElement("button");Q.type="button",Q.className="btn btn-ghost",Q.textContent="Cancel";const J=document.createElement("div");J.style.display="flex",J.style.gap="0.5rem";const S=document.createElement("button");S.type="button",S.className="btn btn-secondary",S.textContent="Save as copy";const W=document.createElement("button");W.type="button",W.className="btn btn-primary",W.textContent="Overwrite",J.appendChild(S),J.appendChild(W),ne.appendChild(Q),ne.appendChild(J),k.appendChild(C),k.appendChild(U),k.appendChild(x),k.appendChild(Y),k.appendChild(ne);const we=E.slideover({title:`Edit: ${o.name}`,size:"lg",position:"right"});we.element.appendChild(k),we.open(),$.addEventListener("ready",()=>{se=U.querySelector(".cropper-canvas"),ae()},{once:!0}),requestAnimationFrame(()=>{i=new Cropper($,{viewMode:1,autoCrop:!1,zoomable:!1,movable:!0}),Domma.icons.scan(k)}),le.addEventListener("click",()=>{F=!F,F?i.crop():i.clear(),le.classList.toggle("active",F)}),ke.addEventListener("click",()=>{i.rotate(90),j=(j+90)%360}),xe.addEventListener("click",()=>{i.rotate(-90),j=(j-90+360)%360}),re.addEventListener("click",()=>{D=!D,i.scaleX(D?-1:1),re.classList.toggle("active",D)}),ie.addEventListener("click",()=>{q=!q,i.scaleY(q?-1:1),ie.classList.toggle("active",q)}),h.addEventListener("click",()=>{O=!O,h.classList.toggle("active",O),Ve(h),h.appendChild(oe(O?"lock":"unlock")),Domma.icons.scan(h)}),g.addEventListener("input",()=>{if(!O)return;const e=parseInt(g.value,10);e>0&&(w.value=Math.round(e/ye))}),w.addEventListener("input",()=>{if(!O)return;const e=parseInt(w.value,10);e>0&&(g.value=Math.round(e*ye))});function Fe(){const e=[];return y==="grayscale"&&e.push("grayscale(1)"),y==="sepia"&&e.push("sepia(1)"),y==="invert"&&e.push("invert(1)"),r.brightness!==1&&e.push(`brightness(${r.brightness})`),r.contrast!==1&&e.push(`contrast(${r.contrast})`),r.saturation!==1&&e.push(`saturate(${r.saturation})`),r.blur>0&&e.push(`blur(${r.blur}px)`),e.join(" ")}function ae(){se&&(se.style.filter=Fe())}async function De(){return new Promise(async e=>{let t;try{t=await Ee.media.list()}catch(l){E.toast(`Failed to load media: ${l.message}`,{type:"error"}),e(null);return}const a=t.filter(l=>/\.(jpg|jpeg|png|webp|gif)$/i.test(l.name)),s=document.createElement("div");if(s.className="ie-media-picker",a.length===0){const l=document.createElement("p");l.className="text-muted",l.style.padding="1rem 0",l.textContent="No images in media library.",s.appendChild(l)}else{const l=document.createElement("div");l.className="ie-media-picker-grid",a.forEach(b=>{const d=document.createElement("div");d.className="ie-media-thumb";const f=document.createElement("img");f.src=b.url,f.alt=b.name;const R=document.createElement("span");R.className="ie-media-thumb-name",R.textContent=b.name,d.appendChild(f),d.appendChild(R),d.addEventListener("click",()=>{m.close(),e(b)}),l.appendChild(d)}),s.appendChild(l)}const n=document.createElement("button");n.type="button",n.className="btn btn-sm btn-ghost",n.style.marginTop="0.75rem",n.textContent="Cancel",n.addEventListener("click",()=>{m.close(),e(null)}),s.appendChild(n);const m=E.slideover({title:"Choose watermark image",size:"md",position:"right"});m.element.appendChild(s),m.open()})}function qe(){const e={};if(j&&(e.rotate=j),q&&(e.flip=!0),D&&(e.flop=!0),F){const n=i.getData(!0);n.width>0&&n.height>0&&(e.crop={left:n.x,top:n.y,width:n.width,height:n.height})}const t=parseInt(g.value,10)||null,a=parseInt(w.value,10)||null;(t!==p.width||a!==p.height)&&(e.resize={width:t,height:a}),y&&(e.preset=y);const s={};return r.brightness!==1&&(s.brightness=r.brightness),r.contrast!==1&&(s.contrast=r.contrast),r.saturation!==1&&(s.saturation=r.saturation),r.blur>0&&(s.blur=r.blur),r.sharpen>0&&(s.sharpen=r.sharpen),r.gamma!==1&&(s.gamma=r.gamma),Object.keys(s).length>0&&(e.adjustments=s),u.image&&(e.watermark={image:u.image,position:u.position,opacity:u.opacity/100,scale:u.scale/100}),L.width>0&&(e.border={width:L.width,colour:L.colour,mode:L.mode}),v.type&&(e.format={type:v.type,quality:v.quality}),e}async function Re(e){W.disabled=!0,S.disabled=!0;try{const t=qe();let a=e;if(!e&&v.type){const s=o.name.substring(o.name.lastIndexOf(".")).toLowerCase(),n="."+v.type;s!==n&&(a=o.name.slice(0,o.name.lastIndexOf("."))+n,t._deleteOriginal=o.name)}await Ee.media.transform(o.name,{operations:t,saveAs:a||void 0}),E.toast("Image saved.",{type:"success"}),Ie(!0)}catch(t){E.toast(`Save failed: ${t.message}`,{type:"error"}),W.disabled=!1,S.disabled=!1}}W.addEventListener("click",async()=>{await E.confirm(`Overwrite "${o.name}"? This cannot be undone.`)&&await Re(null)}),S.addEventListener("click",async()=>{const e=v.type?"."+v.type:o.name.substring(o.name.lastIndexOf(".")),t=o.name.slice(0,o.name.lastIndexOf("."));await Re(`${t}-edited${e}`)}),Q.addEventListener("click",()=>Ie(!1));function Ie(e){i&&(i.destroy(),i=null),we.close(),M(e)}})}
|
|
1
|
+
import{api as Oe}from"../api.js";function Te(){const o={"rotate-cw":{viewBox:"0 0 24 24",stroke:"currentColor",fill:"none",strokeWidth:2,path:"M21 2v6h-6M21 8A9 9 0 1 0 19.07 14.4"},"rotate-ccw":{viewBox:"0 0 24 24",stroke:"currentColor",fill:"none",strokeWidth:2,path:"M3 2v6h6M3 8a9 9 0 1 1 1.93 6.4"},"flip-h":{viewBox:"0 0 24 24",stroke:"currentColor",fill:"none",strokeWidth:2,paths:["M12 3v18","M4 6l4 6-4 6","M20 6l-4 6 4 6"]},"flip-v":{viewBox:"0 0 24 24",stroke:"currentColor",fill:"none",strokeWidth:2,paths:["M3 12h18","M6 4l6 4 6-4","M6 20l6-4 6 4"]},lock:{viewBox:"0 0 24 24",stroke:"currentColor",fill:"none",strokeWidth:2,paths:["M17 11H7a2 2 0 0 0-2 2v7a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2v-7a2 2 0 0 0-2-2z","M12 8a4 4 0 0 0-4 4"],path:"M12 8V5a4 4 0 0 1 4 4v2"},unlock:{viewBox:"0 0 24 24",stroke:"currentColor",fill:"none",strokeWidth:2,paths:["M17 11H7a2 2 0 0 0-2 2v7a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2v-7a2 2 0 0 0-2-2z","M8 11V7a4 4 0 0 1 8 0"]},"crop-icon":{viewBox:"0 0 24 24",stroke:"currentColor",fill:"none",strokeWidth:2,paths:["M6 2v14a2 2 0 0 0 2 2h14","M18 22V8a2 2 0 0 0-2-2H2"]},sliders:{viewBox:"0 0 24 24",stroke:"currentColor",fill:"none",strokeWidth:2,paths:["M4 21v-7","M4 10V3","M12 21v-9","M12 8V3","M20 21v-5","M20 12V3","M1 14h6","M9 8h6","M17 16h6"]},droplet:{viewBox:"0 0 24 24",stroke:"currentColor",fill:"none",strokeWidth:2,path:"M12 2.69l5.66 5.66a8 8 0 1 1-11.31 0z"},"image-plus":{viewBox:"0 0 24 24",stroke:"currentColor",fill:"none",strokeWidth:2,paths:["M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7","M16 5h6","M19 2v6","M3 15l5-5 4 4 3-3 4 4"]},frame:{viewBox:"0 0 24 24",stroke:"currentColor",fill:"none",strokeWidth:2,paths:["M7 3H3v4","M17 3h4v4","M7 21H3v-4","M17 21h4v-4"]},"file-type":{viewBox:"0 0 24 24",stroke:"currentColor",fill:"none",strokeWidth:2,paths:["M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z","M14 2v6h6","M10 13l-2 4h8l-2-4"]}};for(const[y,j]of Object.entries(o))try{I.register(y,j)}catch{}}function se(o){const y=document.createElement("span");return y.setAttribute("data-icon",o),y}function U(o,y,j){const d=document.createElement("button");return d.className=o,d.type="button",d.title=j,d.appendChild(se(y)),d}function $e(){const o=document.createElement("span");return o.className="image-editor-sep",o}const ze=o=>String(o??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""");function Qe(o){for(;o.firstChild;)o.removeChild(o.firstChild)}export async function openImageEditor(o,{api:y=null}={}){Te();const j=y||Oe.media;let d;try{d=await j.info(o.name)}catch(le){return E.toast(`Cannot open editor: ${le.message}`,{type:"error"}),!1}return new Promise(le=>{let m=null,D=!1,O=0,q=!1,A=!1,$=!0;const ke=d.width/d.height;let re=null,k=null;const r={brightness:1,contrast:1,saturation:1,blur:0,sharpen:0,gamma:1},u={image:null,position:"bottom-right",opacity:50,scale:15},L={width:0,colour:"#000000",mode:"solid"},v={type:null,quality:85},x=document.createElement("div");x.className="image-editor";const C=document.createElement("div");C.className="image-editor-toolbar";const ie=U("btn btn-sm btn-ghost editor-toolbar-btn","crop-icon","Toggle crop"),xe=U("btn btn-sm btn-ghost editor-toolbar-btn","rotate-cw","Rotate clockwise"),Ne=U("btn btn-sm btn-ghost editor-toolbar-btn","rotate-ccw","Rotate counter-clockwise"),ce=U("btn btn-sm btn-ghost editor-toolbar-btn","flip-h","Flip horizontal"),de=U("btn btn-sm btn-ghost editor-toolbar-btn","flip-v","Flip vertical");C.appendChild(ie),C.appendChild($e()),C.appendChild(Ne),C.appendChild(xe),C.appendChild($e()),C.appendChild(ce),C.appendChild(de);const X=document.createElement("div");X.className="image-editor-canvas";const z=document.createElement("img");z.src=o.url+"?t="+Date.now(),z.alt=o.name,z.style.maxWidth="100%",X.appendChild(z);const N=document.createElement("div");N.className="image-editor-resize";const Me=document.createElement("label");Me.textContent="W";const g=document.createElement("input");g.type="number",g.className="form-input",g.value=d.width,g.min=1;const h=document.createElement("button");h.type="button",h.className="btn btn-sm btn-ghost editor-toolbar-btn active",h.title="Lock aspect ratio",h.appendChild(se("lock"));const Le=document.createElement("label");Le.textContent="H";const w=document.createElement("input");w.type="number",w.className="form-input",w.value=d.height,w.min=1;const Y=document.createElement("span");Y.className="text-muted",Y.style.marginLeft="auto",Y.textContent=`Original: ${d.width}\xD7${d.height}`,N.appendChild(Me),N.appendChild(g),N.appendChild(h),N.appendChild(Le),N.appendChild(w),N.appendChild(Y);const _=document.createElement("div");_.className="image-editor-effects";const pe=document.createElement("div");pe.className="image-editor-tab-bar";const me=[{id:"filters",label:"Filters",icon:"droplet"},{id:"adjust",label:"Adjust",icon:"sliders"},{id:"watermark",label:"Watermark",icon:"image-plus"},{id:"border",label:"Border",icon:"frame"},{id:"format",label:"Format",icon:"file-type"}],i={},Be={};me.forEach(({id:e,label:t,icon:a},s)=>{const n=document.createElement("button");n.type="button",n.className="image-editor-tab-btn"+(s===0?" active":""),n.dataset.tab=e,n.appendChild(se(a));const p=document.createElement("span");p.textContent=t,n.appendChild(p),n.addEventListener("click",()=>He(e)),pe.appendChild(n),Be[e]=n;const l=document.createElement("div");l.className="image-editor-tab-panel",l.style.display=s===0?"block":"none",i[e]=l});function He(e){me.forEach(({id:t})=>{i[t].style.display=t===e?"block":"none",Be[t].classList.toggle("active",t===e)})}_.appendChild(pe),me.forEach(({id:e})=>_.appendChild(i[e]));const Pe=[{id:"grayscale",label:"Grayscale",cssPreview:!0},{id:"sepia",label:"Sepia",cssPreview:!0},{id:"warm",label:"Warm",cssPreview:!1},{id:"cool",label:"Cool",cssPreview:!1},{id:"enhance",label:"Enhance",cssPreview:!1},{id:"sharpen",label:"Sharpen",cssPreview:!1},{id:"soften",label:"Soften",cssPreview:!1},{id:"invert",label:"Invert",cssPreview:!0}],ue=document.createElement("div");ue.className="ie-presets-grid";const Se={};Pe.forEach(({id:e,label:t})=>{const a=document.createElement("button");a.type="button",a.className="btn btn-sm btn-ghost ie-preset-btn",a.textContent=t,a.addEventListener("click",()=>{k=k===e?null:e,Pe.forEach(({id:s})=>{Se[s].classList.toggle("active",s===k)}),oe()}),Se[e]=a,ue.appendChild(a)});const he=document.createElement("p");he.className="ie-server-note",he.textContent="Warm, Cool, Enhance, Sharpen, and Soften have no live preview - applied on save only.",i.filters.appendChild(ue),i.filters.appendChild(he);const We={};function V(e,t,a,s,n,p){const l=document.createElement("div");l.className="ie-slider-row";const b=document.createElement("label");b.className="ie-slider-label",b.textContent=e;const c=document.createElement("input");c.type="range",c.min=t,c.max=a,c.step=s,c.value=n,c.className="ie-slider";const f=document.createElement("span");return f.className="ie-slider-val",f.textContent=n,c.addEventListener("input",()=>{const R=parseFloat(c.value);f.textContent=s<1?R.toFixed(1):String(Math.round(R)),p(R)}),l.appendChild(b),l.appendChild(c),l.appendChild(f),{row:l,slider:c,valDisplay:f,defaultVal:n,reset(){c.value=n,f.textContent=n}}}const Re=[{key:"brightness",label:"Brightness",min:.2,max:3,step:.1,def:1},{key:"contrast",label:"Contrast",min:.2,max:3,step:.1,def:1},{key:"saturation",label:"Saturation",min:0,max:3,step:.1,def:1},{key:"blur",label:"Blur",min:0,max:10,step:.5,def:0},{key:"sharpen",label:"Sharpen",min:0,max:10,step:.5,def:0},{key:"gamma",label:"Gamma",min:.5,max:3,step:.1,def:1}];Re.forEach(({key:e,label:t,min:a,max:s,step:n,def:p})=>{const l=V(t,a,s,n,p,b=>{r[e]=b,oe()});We[e]=l,i.adjust.appendChild(l.row)});const H=document.createElement("button");H.type="button",H.className="btn btn-sm btn-ghost",H.style.marginTop="0.5rem",H.textContent="Reset adjustments",H.addEventListener("click",()=>{Re.forEach(({key:e,def:t})=>{r[e]=t,We[e].reset()}),oe()}),i.adjust.appendChild(H);const B=document.createElement("button");B.type="button",B.className="btn btn-sm btn-secondary",B.textContent="Choose watermark image\u2026";const M=document.createElement("div");M.className="ie-wm-preview-row",M.style.display="none";const be=document.createElement("img");be.className="ie-wm-preview-img";const fe=document.createElement("span");fe.className="ie-wm-preview-name";const G=document.createElement("button");G.type="button",G.className="btn btn-sm btn-ghost",G.textContent="Remove",G.addEventListener("click",()=>{u.image=null,M.style.display="none",B.style.display=""}),M.appendChild(be),M.appendChild(fe),M.appendChild(G),B.addEventListener("click",async()=>{const e=await Ve();e&&(u.image=e.name,be.src=e.url,fe.textContent=e.name,M.style.display="flex",B.style.display="none")});const Z=document.createElement("div");Z.className="ie-slider-row";const ve=document.createElement("label");ve.className="ie-slider-label",ve.textContent="Position";const T=document.createElement("select");T.className="form-select ie-select",["top-left","top-center","top-right","center-left","center","center-right","bottom-left","bottom-center","bottom-right"].forEach(e=>{const t=document.createElement("option");t.value=e,t.textContent=e.replace(/-/g," ").replace(/\b\w/g,a=>a.toUpperCase()),e==="bottom-right"&&(t.selected=!0),T.appendChild(t)}),T.addEventListener("change",()=>{u.position=T.value}),Z.appendChild(ve),Z.appendChild(T);const Fe=V("Opacity %",0,100,1,50,e=>{u.opacity=e}),De=V("Scale %",5,50,1,15,e=>{u.scale=e});i.watermark.appendChild(B),i.watermark.appendChild(M),i.watermark.appendChild(Z),i.watermark.appendChild(Fe.row),i.watermark.appendChild(De.row);const qe=V("Width (px)",0,200,1,0,e=>{L.width=e}),ee=document.createElement("div");ee.className="ie-slider-row";const Ce=document.createElement("label");Ce.className="ie-slider-label",Ce.textContent="Colour";const F=document.createElement("input");F.type="color",F.value="#000000",F.className="ie-colour-input",F.addEventListener("input",()=>{L.colour=F.value}),ee.appendChild(Ce),ee.appendChild(F);const te=document.createElement("div");te.className="ie-slider-row";const ge=document.createElement("label");ge.className="ie-slider-label",ge.textContent="Mode";const Q=document.createElement("select");Q.className="form-select ie-select",[["solid","Solid"],["mirror","Mirror"],["repeat","Repeat"]].forEach(([e,t])=>{const a=document.createElement("option");a.value=e,a.textContent=t,Q.appendChild(a)}),Q.addEventListener("change",()=>{L.mode=Q.value}),te.appendChild(ge),te.appendChild(Q),i.border.appendChild(qe.row),i.border.appendChild(ee),i.border.appendChild(te);const ne=document.createElement("div");ne.className="ie-slider-row";const we=document.createElement("label");we.className="ie-slider-label",we.textContent="Output format";const P=document.createElement("select");P.className="form-select ie-select",[["","Keep original"],["jpeg","JPEG"],["png","PNG"],["webp","WebP"]].forEach(([e,t])=>{const a=document.createElement("option");a.value=e,a.textContent=t,P.appendChild(a)}),ne.appendChild(we),ne.appendChild(P);const Ee=V("Quality",1,100,1,85,e=>{v.quality=e});Ee.row.style.display="none",P.addEventListener("change",()=>{v.type=P.value||null,Ee.row.style.display=P.value==="jpeg"||P.value==="webp"?"flex":"none"}),i.format.appendChild(ne),i.format.appendChild(Ee.row);const ae=document.createElement("div");ae.className="image-editor-footer";const J=document.createElement("button");J.type="button",J.className="btn btn-ghost",J.textContent="Cancel";const K=document.createElement("div");K.style.display="flex",K.style.gap="0.5rem";const S=document.createElement("button");S.type="button",S.className="btn btn-secondary",S.textContent="Save as copy";const W=document.createElement("button");W.type="button",W.className="btn btn-primary",W.textContent="Overwrite",K.appendChild(S),K.appendChild(W),ae.appendChild(J),ae.appendChild(K),x.appendChild(C),x.appendChild(X),x.appendChild(N),x.appendChild(_),x.appendChild(ae);const ye=E.slideover({title:`Edit: ${ze(o.name)}`,size:"lg",position:"right"});ye.element.appendChild(x),ye.open(),z.addEventListener("ready",()=>{re=X.querySelector(".cropper-canvas"),oe()},{once:!0}),requestAnimationFrame(()=>{m=new Cropper(z,{viewMode:1,autoCrop:!1,zoomable:!1,movable:!0}),Domma.icons.scan(x)}),ie.addEventListener("click",()=>{D=!D,D?m.crop():m.clear(),ie.classList.toggle("active",D)}),xe.addEventListener("click",()=>{m.rotate(90),O=(O+90)%360}),Ne.addEventListener("click",()=>{m.rotate(-90),O=(O-90+360)%360}),ce.addEventListener("click",()=>{q=!q,m.scaleX(q?-1:1),ce.classList.toggle("active",q)}),de.addEventListener("click",()=>{A=!A,m.scaleY(A?-1:1),de.classList.toggle("active",A)}),h.addEventListener("click",()=>{$=!$,h.classList.toggle("active",$),Qe(h),h.appendChild(se($?"lock":"unlock")),Domma.icons.scan(h)}),g.addEventListener("input",()=>{if(!$)return;const e=parseInt(g.value,10);e>0&&(w.value=Math.round(e/ke))}),w.addEventListener("input",()=>{if(!$)return;const e=parseInt(w.value,10);e>0&&(g.value=Math.round(e*ke))});function Ae(){const e=[];return k==="grayscale"&&e.push("grayscale(1)"),k==="sepia"&&e.push("sepia(1)"),k==="invert"&&e.push("invert(1)"),r.brightness!==1&&e.push(`brightness(${r.brightness})`),r.contrast!==1&&e.push(`contrast(${r.contrast})`),r.saturation!==1&&e.push(`saturate(${r.saturation})`),r.blur>0&&e.push(`blur(${r.blur}px)`),e.join(" ")}function oe(){re&&(re.style.filter=Ae())}async function Ve(){return new Promise(async e=>{let t;try{t=await Oe.media.list()}catch(l){E.toast(`Failed to load media: ${l.message}`,{type:"error"}),e(null);return}const a=t.filter(l=>/\.(jpg|jpeg|png|webp|gif)$/i.test(l.name)),s=document.createElement("div");if(s.className="ie-media-picker",a.length===0){const l=document.createElement("p");l.className="text-muted",l.style.padding="1rem 0",l.textContent="No images in media library.",s.appendChild(l)}else{const l=document.createElement("div");l.className="ie-media-picker-grid",a.forEach(b=>{const c=document.createElement("div");c.className="ie-media-thumb";const f=document.createElement("img");f.src=b.url,f.alt=b.name;const R=document.createElement("span");R.className="ie-media-thumb-name",R.textContent=b.name,c.appendChild(f),c.appendChild(R),c.addEventListener("click",()=>{p.close(),e(b)}),l.appendChild(c)}),s.appendChild(l)}const n=document.createElement("button");n.type="button",n.className="btn btn-sm btn-ghost",n.style.marginTop="0.75rem",n.textContent="Cancel",n.addEventListener("click",()=>{p.close(),e(null)}),s.appendChild(n);const p=E.slideover({title:"Choose watermark image",size:"md",position:"right"});p.element.appendChild(s),p.open()})}function Ge(){const e={};if(O&&(e.rotate=O),A&&(e.flip=!0),q&&(e.flop=!0),D){const n=m.getData(!0);n.width>0&&n.height>0&&(e.crop={left:n.x,top:n.y,width:n.width,height:n.height})}const t=parseInt(g.value,10)||null,a=parseInt(w.value,10)||null;(t!==d.width||a!==d.height)&&(e.resize={width:t,height:a}),k&&(e.preset=k);const s={};return r.brightness!==1&&(s.brightness=r.brightness),r.contrast!==1&&(s.contrast=r.contrast),r.saturation!==1&&(s.saturation=r.saturation),r.blur>0&&(s.blur=r.blur),r.sharpen>0&&(s.sharpen=r.sharpen),r.gamma!==1&&(s.gamma=r.gamma),Object.keys(s).length>0&&(e.adjustments=s),u.image&&(e.watermark={image:u.image,position:u.position,opacity:u.opacity/100,scale:u.scale/100}),L.width>0&&(e.border={width:L.width,colour:L.colour,mode:L.mode}),v.type&&(e.format={type:v.type,quality:v.quality}),e}async function Ie(e){W.disabled=!0,S.disabled=!0;try{const t=Ge();let a=e;if(!e&&v.type){const s=o.name.substring(o.name.lastIndexOf(".")).toLowerCase(),n="."+v.type;s!==n&&(a=o.name.slice(0,o.name.lastIndexOf("."))+n,t._deleteOriginal=o.name)}await j.transform(o.name,{operations:t,saveAs:a||void 0}),E.toast("Image saved.",{type:"success"}),je(!0)}catch(t){E.toast(`Save failed: ${t.message}`,{type:"error"}),W.disabled=!1,S.disabled=!1}}W.addEventListener("click",async()=>{await E.confirm(`Overwrite "${ze(o.name)}"? This cannot be undone.`)&&await Ie(null)}),S.addEventListener("click",async()=>{const e=v.type?"."+v.type:o.name.substring(o.name.lastIndexOf(".")),t=o.name.slice(0,o.name.lastIndexOf("."));await Ie(`${t}-edited${e}`)}),J.addEventListener("click",()=>je(!1));function je(e){m&&(m.destroy(),m=null),ye.close(),le(e)}})}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{fmtDate as u}from"./dates.js";export const KINDS=["all","image","video","audio","document","other"],KIND_LABEL={all:"All",image:"Images",video:"Video",audio:"Audio",document:"Documents",other:"Other"},SORTS=["newest","oldest","name","size"];const c={image:["png","jpg","jpeg","gif","webp","svg","avif","ico","bmp","tif","tiff"],video:["mp4","webm","ogv","mov"],audio:["mp3","ogg","oga","wav","weba","m4a"],document:["pdf","txt","csv","doc","docx","xls","xlsx"]},l=new Set(["png","jpg","jpeg","gif","webp","svg","avif","ico","bmp"]),m=new Set(["jpg","jpeg","png","webp","gif","tiff"]);export const extOf=e=>{const t=/\.([a-z0-9]+)$/i.exec(String(e??""));return t?t[1].toLowerCase():""};export function kindOf(e){const t=extOf(e);for(const[n,r]of Object.entries(c))if(r.includes(t))return n;return"other"}export const isPreviewable=e=>l.has(extOf(e)),isEditable=e=>m.has(extOf(e));export function formatBytes(e){const t=Number(e)||0;if(t<1024)return`${t} B`;const n=["KB","MB","GB","TB"];let r=t/1024,o=0;for(;r>=1024&&o<n.length-1;)r/=1024,o++;return`${r.toFixed(1)} ${n[o]}`}export function ago(e,t=Date.now()){const n=new Date(e).getTime();if(!Number.isFinite(n))return"";const r=Math.max(0,Math.round((t-n)/1e3));if(r<60)return"just now";if(r<3600)return`${Math.round(r/60)} min ago`;if(r<86400){const o=Math.round(r/3600);return`${o} hour${o===1?"":"s"} ago`}if(r<86400*14){const o=Math.round(r/86400);return`${o} day${o===1?"":"s"} ago`}return u(n)}export function safeName(e){return String(e??"").split(/[\\/]/).pop().replace(/[^a-zA-Z0-9._-]/g,"_")}export function clashes(e,t){const n=new Set(t);return[...new Set(e.map(safeName))].filter(r=>n.has(r))}export function altFromName(e){return String(e??"").replace(/\.[^.]+$/,"").replace(/[-_]+/g," ").replace(/\s+/g," ").trim()}export function markdownFor(e){return isPreviewable(e.name)?``:`[${e.name}](${e.url})`}export function kindCounts(e){const t=Object.fromEntries(KINDS.map(n=>[n,0]));for(const n of e||[])t.all++,t[kindOf(n.name)]++;return t}export function arrangeMedia(e,{kind:t="all",query:n="",sort:r="newest"}={}){const o=String(n).trim().toLowerCase(),a={newest:(i,s)=>String(s.createdAt).localeCompare(String(i.createdAt)),oldest:(i,s)=>String(i.createdAt).localeCompare(String(s.createdAt)),name:(i,s)=>i.name.localeCompare(s.name,void 0,{numeric:!0,sensitivity:"base"}),size:(i,s)=>(s.size||0)-(i.size||0)}[r]||(()=>0);return[...e||[]].filter(i=>t==="all"||kindOf(i.name)===t).filter(i=>!o||i.name.toLowerCase().includes(o)).sort((i,s)=>a(i,s)||i.name.localeCompare(s.name))}export function mediaTile(e,{now:t=Date.now(),stamp:n=""}={}){const r=kindOf(e.name),o=isPreviewable(e.name);return{name:e.name,url:e.url,thumb:o?`${e.url}${n?`?t=${encodeURIComponent(n)}`:""}`:null,preview:o,icon:{video:"video",audio:"music",document:"file-text"}[r]||(r==="image"?"image":"paperclip"),kind:r,kindLabel:(extOf(e.name)||r).toUpperCase(),meta:[formatBytes(e.size),ago(e.createdAt,t)].filter(Boolean).join(" \xB7 ")}}export function normalisePrefs(e){const t=e&&typeof e=="object"?e:{};return{kind:KINDS.includes(t.kind)?t.kind:"all",sort:SORTS.includes(t.sort)?t.sort:"newest"}}export function normaliseLimits(e){const t=e&&typeof e=="object"?e:{},n=Array.isArray(t.types)?t.types.filter(a=>typeof a=="string"&&/^[\w.+-]+\/[\w.+-]+$/.test(a)):[],r=Number(t.maxFileSize),o=Number(t.maxNameLength);return{types:n,maxFileSize:Number.isFinite(r)&&r>0?r:null,maxNameLength:Number.isInteger(o)&&o>0?o:null}}export function dropzoneRules(e){const t=normaliseLimits(e);return{accept:t.types.length?t.types.join(","):null,maxSize:t.maxFileSize}}export function uploadHint(e){const t=normaliseLimits(e),n=[],r=a=>t.types.some(i=>a.test(i));r(/^image\//)&&n.push("images"),r(/^(application|text)\//)&&n.push("documents"),r(/^audio\//)&&n.push("audio"),r(/^video\//)&&n.push("video");const o=[];if(n.length){const a=n.length===1?n[0]:`${n.slice(0,-1).join(", ")} and ${n.at(-1)}`;o.push(a[0].toUpperCase()+a.slice(1))}return t.maxFileSize&&o.push(`up to ${formatBytes(t.maxFileSize)} each`),o.join(" \xB7 ")}export function nameRefusal(e,t){const n=normaliseLimits(t),r=safeName(e);return r?n.maxNameLength&&r.length>n.maxNameLength?`its name is longer than ${n.maxNameLength} characters`:null:"it has no name"}export function shortName(e,t=60){const n=String(e??"");return n.length>t?`${n.slice(0,t-15)}\u2026${n.slice(-12)}`:n}export function rejectText(e,t,n){const r=normaliseLimits(n),o=shortName(e);return t==="type"?`${o}: that type of file is not taken here`:t==="size"?`${o}: it is larger than ${r.maxFileSize?formatBytes(r.maxFileSize):"the limit"}`:`${o}: not added`}export function uploadErrorText(e,t){const n=e||{},r=n.response&&typeof n.response=="object"?n.response:null,o=r&&(typeof r.error=="string"?r.error:typeof r.message=="string"?r.message:"");if(n.status===413){const a=normaliseLimits(t);return`larger than ${a.maxFileSize?formatBytes(a.maxFileSize):"the server takes"}`}return o||(n.status===0?"the connection failed":n.status===401?"signed out - sign in and retry":n.status===403?"you may not upload media":n.message||"failed")}export function narrowLimits(e,t=null){const n=normaliseLimits(e);return t instanceof RegExp?{...n,types:n.types.filter(r=>t.test(r))}:n}export function uploadedFile(e){const t=Array.isArray(e)?e[0]:e;return!t||typeof t!="object"||typeof t.name!="string"||!t.name?null:{name:t.name,url:typeof t.url=="string"&&t.url?t.url:`/media/${t.name}`}}export function pickerOutcome({files:e=[],failed:t=0,waiting:n=0,offered:r=e.length,open:o=!0,single:a=!0}={}){return o?a&&e.length===1&&!t&&!n&&r<=1&&e[0]?.url?{choose:e[0].url,reload:!1}:{choose:null,reload:e.length>0}:{choose:null,reload:!1}}
|
|
1
|
+
import{fmtDate as u}from"./dates.js";export const KINDS=["all","image","video","audio","document","other"],KIND_LABEL={all:"All",image:"Images",video:"Video",audio:"Audio",document:"Documents",other:"Other"},SORTS=["newest","oldest","name","size"];const c={image:["png","jpg","jpeg","gif","webp","svg","avif","ico","bmp","tif","tiff"],video:["mp4","webm","ogv","mov"],audio:["mp3","ogg","oga","wav","weba","m4a"],document:["pdf","txt","csv","doc","docx","xls","xlsx"]},l=new Set(["png","jpg","jpeg","gif","webp","svg","avif","ico","bmp"]),m=new Set(["jpg","jpeg","png","webp","gif","tiff"]);export const extOf=e=>{const t=/\.([a-z0-9]+)$/i.exec(String(e??""));return t?t[1].toLowerCase():""};export function kindOf(e){const t=extOf(e);for(const[n,r]of Object.entries(c))if(r.includes(t))return n;return"other"}export const isPreviewable=e=>l.has(extOf(e)),isEditable=e=>m.has(extOf(e));export function formatBytes(e){const t=Number(e)||0;if(t<1024)return`${t} B`;const n=["KB","MB","GB","TB"];let r=t/1024,o=0;for(;r>=1024&&o<n.length-1;)r/=1024,o++;return`${r.toFixed(1)} ${n[o]}`}export function ago(e,t=Date.now()){const n=new Date(e).getTime();if(!Number.isFinite(n))return"";const r=Math.max(0,Math.round((t-n)/1e3));if(r<60)return"just now";if(r<3600)return`${Math.round(r/60)} min ago`;if(r<86400){const o=Math.round(r/3600);return`${o} hour${o===1?"":"s"} ago`}if(r<86400*14){const o=Math.round(r/86400);return`${o} day${o===1?"":"s"} ago`}return u(n)}export function safeName(e){return String(e??"").split(/[\\/]/).pop().replace(/[^a-zA-Z0-9._-]/g,"_")}export function clashes(e,t){const n=new Set(t);return[...new Set(e.map(safeName))].filter(r=>n.has(r))}export function altFromName(e){return String(e??"").replace(/\.[^.]+$/,"").replace(/[-_]+/g," ").replace(/\s+/g," ").trim()}export function markdownFor(e){return isPreviewable(e.name)?``:`[${e.name}](${e.url})`}export function kindCounts(e){const t=Object.fromEntries(KINDS.map(n=>[n,0]));for(const n of e||[])t.all++,t[kindOf(n.name)]++;return t}export function arrangeMedia(e,{kind:t="all",query:n="",sort:r="newest"}={}){const o=String(n).trim().toLowerCase(),a={newest:(i,s)=>String(s.createdAt).localeCompare(String(i.createdAt)),oldest:(i,s)=>String(i.createdAt).localeCompare(String(s.createdAt)),name:(i,s)=>i.name.localeCompare(s.name,void 0,{numeric:!0,sensitivity:"base"}),size:(i,s)=>(s.size||0)-(i.size||0)}[r]||(()=>0);return[...e||[]].filter(i=>t==="all"||kindOf(i.name)===t).filter(i=>!o||i.name.toLowerCase().includes(o)).sort((i,s)=>a(i,s)||i.name.localeCompare(s.name))}export function mediaTile(e,{now:t=Date.now(),stamp:n=""}={}){const r=kindOf(e.name),o=isPreviewable(e.name);return{name:e.name,url:e.url,thumb:o?`${e.url}${n?`?t=${encodeURIComponent(n)}`:""}`:null,preview:o,icon:{video:"video",audio:"music",document:"file-text"}[r]||(r==="image"?"image":"paperclip"),kind:r,kindLabel:(extOf(e.name)||r).toUpperCase(),meta:[formatBytes(e.size),ago(e.createdAt,t)].filter(Boolean).join(" \xB7 ")}}export function foldersText({folders:e=0,files:t=0}={}){const n=`${t} more file${t===1?"":"s"}`,r=`${e} folder${e===1?"":"s"}`;return`${n} ${t===1?"is":"are"} in ${r}, not listed here. ${t===1?"It keeps":"They keep"} working at the same address${t===1?"":"es"}; Media Pro shows and manages folders.`}export function normalisePrefs(e){const t=e&&typeof e=="object"?e:{};return{kind:KINDS.includes(t.kind)?t.kind:"all",sort:SORTS.includes(t.sort)?t.sort:"newest"}}export function normaliseLimits(e){const t=e&&typeof e=="object"?e:{},n=Array.isArray(t.types)?t.types.filter(a=>typeof a=="string"&&/^[\w.+-]+\/[\w.+-]+$/.test(a)):[],r=Number(t.maxFileSize),o=Number(t.maxNameLength);return{types:n,maxFileSize:Number.isFinite(r)&&r>0?r:null,maxNameLength:Number.isInteger(o)&&o>0?o:null}}export function dropzoneRules(e){const t=normaliseLimits(e);return{accept:t.types.length?t.types.join(","):null,maxSize:t.maxFileSize}}export function uploadHint(e){const t=normaliseLimits(e),n=[],r=a=>t.types.some(i=>a.test(i));r(/^image\//)&&n.push("images"),r(/^(application|text)\//)&&n.push("documents"),r(/^audio\//)&&n.push("audio"),r(/^video\//)&&n.push("video");const o=[];if(n.length){const a=n.length===1?n[0]:`${n.slice(0,-1).join(", ")} and ${n.at(-1)}`;o.push(a[0].toUpperCase()+a.slice(1))}return t.maxFileSize&&o.push(`up to ${formatBytes(t.maxFileSize)} each`),o.join(" \xB7 ")}export function nameRefusal(e,t){const n=normaliseLimits(t),r=safeName(e);return r?n.maxNameLength&&r.length>n.maxNameLength?`its name is longer than ${n.maxNameLength} characters`:null:"it has no name"}export function shortName(e,t=60){const n=String(e??"");return n.length>t?`${n.slice(0,t-15)}\u2026${n.slice(-12)}`:n}export function rejectText(e,t,n){const r=normaliseLimits(n),o=shortName(e);return t==="type"?`${o}: that type of file is not taken here`:t==="size"?`${o}: it is larger than ${r.maxFileSize?formatBytes(r.maxFileSize):"the limit"}`:`${o}: not added`}export function uploadErrorText(e,t){const n=e||{},r=n.response&&typeof n.response=="object"?n.response:null,o=r&&(typeof r.error=="string"?r.error:typeof r.message=="string"?r.message:"");if(n.status===413){const a=normaliseLimits(t);return`larger than ${a.maxFileSize?formatBytes(a.maxFileSize):"the server takes"}`}return o||(n.status===0?"the connection failed":n.status===401?"signed out - sign in and retry":n.status===403?"you may not upload media":n.message||"failed")}export function narrowLimits(e,t=null){const n=normaliseLimits(e);return t instanceof RegExp?{...n,types:n.types.filter(r=>t.test(r))}:n}export function uploadedFile(e){const t=Array.isArray(e)?e[0]:e;return!t||typeof t!="object"||typeof t.name!="string"||!t.name?null:{name:t.name,url:typeof t.url=="string"&&t.url?t.url:`/media/${t.name}`}}export function pickerOutcome({files:e=[],failed:t=0,waiting:n=0,offered:r=e.length,open:o=!0,single:a=!0}={}){return o?a&&e.length===1&&!t&&!n&&r<=1&&e[0]?.url?{choose:e[0].url,reload:!1}:{choose:null,reload:e.length>0}:{choose:null,reload:!1}}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{api as $}from"../api.js";import{onceClosed as A,sidebarCount as
|
|
1
|
+
import{api as $}from"../api.js";import{onceClosed as A,sidebarCount as T}from"./tool-kit.js";import{catchFiles as P,mediaUploader as D}from"./media-upload.js";import{pickerOutcome as N}from"./media-arrange.js";const U=/\.(png|jpe?g|gif|webp|avif|svg)$/i;export const UPLOAD_TYPES=/^image\/(png|jpe?g|gif|webp|avif|svg\+xml)$/;export function pickable(n,{query:o="",accept:s=U}={}){const i=String(o).trim().toLowerCase();return(Array.isArray(n)?n:[]).map(t=>({name:t.name||t.filename||"",url:t.url||(t.name?`/media/${t.name}`:"")})).filter(t=>t.url&&s.test(t.name||t.url)&&(!i||t.name.toLowerCase().includes(i)))}export async function pickMedia({title:n="Choose an image",current:o=""}={}){const s=globalThis[Symbol.for("domma.media-picker")];if(s)try{const i=await import(`/plugins/${s}`);if(typeof i.pickMedia=="function")return await i.pickMedia({title:n,current:o})}catch(i){console.warn("[media-picker] the Tool's picker did not load, using the built-in one:",i)}return j({title:n,current:o})}function j({title:n,current:o}){return new Promise(s=>{let i=!1;const t=e=>{i||(i=!0,s(e))},r=E.slideover({title:n,size:"lg",position:"right"}),c=document.createElement("template");c.innerHTML=`<div class="mp-picker">
|
|
2
2
|
<div class="mp-bar">
|
|
3
3
|
<input type="search" class="form-input" placeholder="Search Media\u2026" aria-label="Search Media" data-model="query.value">
|
|
4
4
|
</div>
|
|
@@ -33,4 +33,4 @@ import{api as $}from"../api.js";import{onceClosed as A,sidebarCount as D}from"./
|
|
|
33
33
|
.mp-grid { max-height: none; }
|
|
34
34
|
.mp-grid .media-picker-item { background: none; padding: 0; text-align: left; color: inherit; font: inherit; }
|
|
35
35
|
.mp-grid .media-picker-item.is-current { border-color: var(--dm-primary); }
|
|
36
|
-
</style>`;const
|
|
36
|
+
</style>`;const a=c.content.firstElementChild,y=c.content.querySelector("style"),p=M.observable([]),m=M.observable(""),b=M.observable(""),d=M.observable("Loading\u2026"),u=M.computed(()=>pickable(p.value,{query:m.value})),z=M.effect(()=>{d.peek()==="Loading\u2026"&&!p.value.length||(d.value=u.value.length?"":m.value.trim()?"No picture matches.":"No pictures in Media yet - upload one.")}),k=async()=>{try{p.value=await $.media.list(),d.value="",pickable(p.peek()).length||(d.value="No pictures in Media yet - upload one.")}catch(e){d.value=`Could not load Media: ${e.message||e}`}},g=a.querySelector(".mp-grid"),x=e=>{const l=e.target.closest("[data-url]");l&&(t(l.dataset.url),r.close())};g.addEventListener("click",x),r.element.appendChild(a),y&&r.element.appendChild(y);const f=()=>!i,h=D(a.querySelector(".mp-zone"),{input:a.querySelector(".mp-file-input"),accept:"image/*",only:UPLOAD_TYPES,exists:e=>p.peek().some(l=>(l.name||l.filename)===e),showing:f,onHint:e=>{b.value=e},doneSuffix:()=>f()?"":" to Media",onUploaded({files:e,failed:l,waiting:C,offered:L}){T("#/media");const v=N({files:e,failed:l,waiting:C,offered:L,open:f()});if(v.choose){t(v.choose),setTimeout(()=>r.close(),0);return}v.reload&&k()}}),w=P(r.element,h.addFiles,{onDragging:e=>a.classList.toggle("is-drop",e)}),S=M.applyBindings({query:m,note:d,shown:u,hint:b},a),q=M.effect(()=>{u.value,queueMicrotask(()=>g.querySelectorAll("[data-url]").forEach(e=>e.classList.toggle("is-current",!!o&&e.dataset.url===o)))});A(r,()=>{const e=h.pending();S.dispose(),z?.(),q?.(),w(),g.removeEventListener("click",x),t(null),h.release()&&e&&E.toast(`Still uploading ${e} file${e===1?"":"s"} - ${e===1?"it goes":"they go"} into Media when done.`,{type:"info"})}),Domma.icons?.scan?.(a),r.open(),k(),setTimeout(()=>a.querySelector("input[type=search]")?.focus(),50)})}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{api as
|
|
1
|
+
import{api as V,getToken as W,refreshAccessToken as G}from"../api.js";import{dropzoneRules as I,nameRefusal as J,narrowLimits as _,rejectText as K,safeName as v,shortName as U,uploadErrorText as Q,uploadHint as X,uploadedFile as Y}from"./media-arrange.js";const Z=f=>String(f??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,"""),B=f=>setTimeout(f,0);export function mediaUploader(f,{input:$,multiple:h=!0,accept:c=null,only:u=null,url:L="/api/media",exists:j=()=>!1,showing:w=()=>!0,onHint:q=()=>{},onUploaded:O=()=>{},doneSuffix:b=()=>""}={}){let t=_(null,u);const o=new WeakSet;let p=[],m=[],y=[],x=0,i=!1,g=0,R=0,k=0,F=!1,d=null;const C=()=>{if(!m.length)return;const e=m;m=[],E.toast(`Not added - ${e.slice(0,4).join("; ")}${e.length>4?` and ${e.length-4} more`:""}`,{type:"error",duration:9e3})},D=e=>{m.length||B(C),m.push(e)};async function H(){const e=p;if(p=[],!(!e.length||!w())){R=e.length;try{await M(e)}finally{R=0}}}async function M(e){const n=[...new Set(e.map(r=>v(r.name)))],l=n.slice(0,5).map(r=>`"${Z(r)}"`).join(", ")+(n.length>5?` and ${n.length-5} more`:""),s=n.length===1;await E.confirm(`${s?"A file":`${n.length} files`} with the same name ${s?"is":"are"} already here: ${l}. Replace ${s?"it":"them"}?`)&&(i||d||(e.forEach(r=>o.add(r)),a.addFiles(e)))}const a=E.dropzone(f,{input:$,multiple:h,previews:!0,accept:c,upload:{url:L,field:"file",concurrency:3,headers:()=>{const e=W();return e?{Authorization:`Bearer ${e}`}:{}}},labels:{cancel:"Cancel the upload of {name}",remove:"Remove {name} from the list"},onBeforeAdd(e){const n=J(e.name,t);if(n)return D(`${U(e.name)}: ${n}`),!1;if(o.has(e.file))return o.delete(e.file),!0;const l=v(e.name),s=a.getEntries().filter(r=>v(r.name)===l);return s.some(r=>r.status==="uploading"||r.status==="queued")?(D(`${U(e.name)}: a file of that name is uploading already`),!1):(s.forEach(r=>{r.status!=="done"&&a.removeFile(r.id)}),F||(F=!0,queueMicrotask(()=>{F=!1}),!z()&&!a.getEntries().some(r=>r.status!=="done")&&(k=0)),k++,j(l,e.file)?(p.length||B(H),p.push(e.file),!1):!0)},onReject(e,n){D(K(e.name,n,t))},onSuccess(e,n){y.push(Y(n)||{name:v(e.name),url:`/media/${v(e.name)}`})},onError(e,n){if(n.status===401&&!e._mdxRefreshed&&S.get("auth_refresh_token")){e._mdxRefreshed=!0,n.message="signing in again\u2026",g++,G().then(()=>{i||a.retry(e.id)}).catch(()=>{}).finally(()=>{g--,d?.()});return}x++,n.message=Q(n,t)},onComplete(){const e=y,n=x;y=[],x=0;const l=e.length;if(l&&E.toast(`Uploaded ${l} file${l===1?"":"s"}${b()}.`,{type:"success"}),n){const s=`${n} file${n===1?"":"s"} not uploaded`;E.toast(w()?`${s} - Retry or remove ${n===1?"it":"them"} in the list.`:`${s}.`,{type:"error",duration:9e3})}a.getEntries().filter(s=>s.status==="done").forEach(s=>a.removeFile(s.id)),l&&O({files:e,failed:n,waiting:z(),offered:k})}});function z(){return p.length+R+g}const A=()=>!i&&a.getEntries().some(e=>e.status==="uploading"||e.status==="queued"),T=()=>A()||g>0,N=e=>{T()&&(e.preventDefault(),e.returnValue="")};window.addEventListener("beforeunload",N);const P=()=>{i||(i=!0,window.removeEventListener("beforeunload",N),a.destroy())};return V.media.limits().then(e=>{if(i||d||!w())return;t=_(e,u);const n=I(t);a.setOptions({...n,accept:n.accept??c}),q(X(t))}).catch(()=>{}),{dz:a,addFiles:e=>{!i&&!d&&a.addFiles(e)},browse:()=>{!i&&!d&&a.browse()},uploading:A,pending:()=>i?0:a.getEntries().filter(e=>e.status==="uploading"||e.status==="queued").length+g,release(){return i||d?!1:(d=()=>{T()||P()},T()?(a.on("complete",d),!0):(P(),!1))}}}export function catchFiles(f,$,{onDragging:h=()=>{}}={}){const c=t=>[...t.dataTransfer?.types||[]].includes("Files");let u=0;const b={dragenter:t=>{c(t)&&(t.preventDefault(),u++,h(!0))},dragover:t=>{c(t)&&(t.preventDefault(),t.dataTransfer.dropEffect="copy")},dragleave:t=>{c(t)&&(u=Math.max(0,u-1),u||h(!1))},drop:t=>{c(t)&&(u=0,h(!1),!t.defaultPrevented&&(t.preventDefault(),$(t.dataTransfer.files)))},paste:t=>{const o=[...t.clipboardData?.files||[]];t.defaultPrevented||!o.length||t.target?.closest?.('input, textarea, [contenteditable=""], [contenteditable="true"]')&&[...t.clipboardData.types||[]].includes("text/plain")||(t.preventDefault(),$(o))}};return Object.entries(b).forEach(([t,o])=>f.addEventListener(t,o)),()=>Object.entries(b).forEach(([t,o])=>f.removeEventListener(t,o))}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export const CODES=[301,302,307,308,410],MAX_RULES=5e3;export function normalisePath(
|
|
1
|
+
export const CODES=[301,302,307,308,410],MAX_RULES=5e3;export function normalisePath(r){let t=String(r??"").trim();if(!t)return"";try{t=decodeURI(t)}catch{}return t=t.split("#")[0].split("?")[0],t.startsWith("/")||(t=`/${t}`),t=t.replace(/\/{2,}/g,"/"),t.length>1&&(t=t.replace(/\/+$/,"")),t.toLowerCase()}function h(r){let t=String(r??"").trim();try{t=decodeURI(t)}catch{}return t=t.split("#")[0].split("?")[0],t.startsWith("/")||(t=`/${t}`),t=t.replace(/\/{2,}/g,"/"),t.length>1?t.replace(/\/+$/,""):t}const u=r=>String(r).endsWith("/*"),f=r=>/^https?:\/\//i.test(String(r));export function checkRule(r={},t=[]){const e={},l=Number(r.code??301),c=String(r.from??"").trim(),o=u(c),i=o?`${normalisePath(c.slice(0,-2))==="/"?"":normalisePath(c.slice(0,-2))}/*`:normalisePath(c);let n=String(r.to??"").trim();if(CODES.includes(l)||(e.code="Choose 301, 302, 307, 308 or 410."),c?/^https?:\/\//i.test(c)?e.from="The address to redirect is a path on this site, like /old-page.":/^\/(admin|api)(\/|$)/.test(i)?e.from="The admin and the API cannot be redirected.":i==="/*"&&(e.from="That would redirect the whole site."):e.from="Say which address to redirect.",l===410)n="";else if(!n)e.to="Say where it goes.";else if(f(n))try{new URL(n.replace("*","x"))}catch{e.to="Not a web address."}else if(/^[a-z][a-z0-9+.-]*:/i.test(n)||n.startsWith("//"))e.to="A path on this site (/new-page) or an http(s) address.";else{const[a,s]=n.split("?");n=normalisePath(a)+(s?`?${s}`:""),n.includes("*")&&!o&&(e.to='A "*" in the target needs a "/*" rule to fill it.')}if(!e.from&&!e.to&&l!==410&&!f(n)){const a=normalisePath(n.split("?")[0]);!o&&a===i?e.to="It would redirect to itself.":!o&&p(i,a,t)&&(e.to="That makes a loop with another redirect.")}return!e.from&&t.some(a=>a.from===i)&&(e.from=`There is already a redirect from ${i}.`),{errors:e,rule:{from:i,to:n,code:l,note:String(r.note??"").trim().slice(0,200),...r.auto===!0&&{auto:!0}}}}function p(r,t,e){const l=new Set([r]);let c=t;for(let o=0;o<20;o++){if(l.has(c))return!0;l.add(c);const i=matchRedirect(e,c);if(!i||!i.location||f(i.location))return!1;c=normalisePath(i.location.split("?")[0])}return!0}export function matchRedirect(r,t){const[e,l]=String(t??"").split("?"),c=normalisePath(e);if(!c)return null;let o=null,i="";for(const a of r)if(a.from===c){o=a,i="";break}if(!o){let a=-1;for(const s of r){if(!u(s.from))continue;const d=s.from.slice(0,-2);(c===d||c.startsWith(`${d}/`))&&d.length>a&&(a=d.length,o=s,i=(String(o.to).startsWith("/media/")?h(e):c).slice(d.length+1))}}if(!o)return null;if(o.code===410)return{rule:o,location:"",code:410};let n=o.to.includes("*")?o.to.replace("*",i):o.to;return f(n)||(n=n.replace(/\/{2,}/g,"/").replace(/(.)\/$/,"$1")),l&&!n.includes("?")&&(n+=`?${l}`),{rule:o,location:n,code:o.code}}export function onMoved(r,t,e,{now:l=new Date().toISOString(),id:c}={}){const o=normalisePath(t),i=normalisePath(e);if(!o||!i||o===i)return r;if(o==="/")return r.filter(s=>s.from!==i);const n=r.filter(s=>s.from!==i).map(s=>normalisePath(String(s.to).split("?")[0])===o&&!f(s.to)?{...s,to:i}:s),a=n.find(s=>s.from===o);return a?n.map(s=>s===a?{...s,to:i,code:301}:s):[...n,{id:c||`r${Date.now().toString(36)}`,from:o,to:i,code:301,note:"The page moved",auto:!0,hits:0,lastHit:null,at:l}]}export function chains(r){const t=[];for(const e of r){if(e.code===410||f(e.to)||u(e.from))continue;const l=matchRedirect(r,e.to);l&&l.rule!==e&&t.push({rule:e,via:l.rule})}return t}
|
|
@@ -45,6 +45,12 @@
|
|
|
45
45
|
small text cannot be read on the page. A picture with a <code>link</code> follows the link instead of
|
|
46
46
|
zooming. Every option is listed under Shortcodes.</p>
|
|
47
47
|
|
|
48
|
+
<h3>Folders</h3>
|
|
49
|
+
<p>This screen lists the files at the top of the library. If there are files in folders it says how
|
|
50
|
+
many, and they keep working at their addresses. Folders inside folders, moving files without
|
|
51
|
+
breaking pages, Trash and more come with the <strong>Media Pro</strong> Tool, which replaces this
|
|
52
|
+
screen and has its own guide.</p>
|
|
53
|
+
|
|
48
54
|
<h3>Upload limits</h3>
|
|
49
55
|
<p>The largest file is set in <code>config/server.json</code> under
|
|
50
56
|
<code>uploads.maxFileSize</code> (bytes). The default is 10 MB. File names are limited to 200
|
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
<p class="mdx-note">Files for your pages, stored in <code>content/media/</code>. Drop or paste files anywhere on this
|
|
8
8
|
screen to upload them.
|
|
9
9
|
<span data-help-title="Media" data-help="Upload with the drop area or the button in the banner, drop files anywhere on this screen, or paste them (Ctrl+V). Each file shows its progress; cancel one with its ×, and Retry one that failed. A type or size the site does not take is refused before it is sent. Click a file for its details - its address, a snippet to paste into a page, a rename box, and the image editor for pictures. Right-click a file (or ⋮, or Shift+F10) for the same actions without opening it. Uploading a file with the same name as one already here replaces it; you are asked first."></span></p>
|
|
10
|
+
<p class="mdx-note" data-bind-hidden="!foldersNote.value" data-bind-text="foldersNote.value"></p>
|
|
10
11
|
<!-- E.dropzone: the area is one button (click, Enter or Space opens the picker); its file list is drawn after it. -->
|
|
11
12
|
<div class="mdx-zone">
|
|
12
13
|
<span class="mdx-zone-icon" data-icon="upload" data-icon-size="20" aria-hidden="true"></span>
|