@crombolo/backoffice-host 0.52.2 → 0.54.1

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.
@@ -0,0 +1,276 @@
1
+ /**
2
+ * The panel a page's template is chosen in (`template-picker.js`): every
3
+ * component on disk in a tree of its folders, the first level open, with a
4
+ * search that narrows it by name. One the content type does not allow says so,
5
+ * and someone with Structure allows it beside it, which makes it a template
6
+ * first when nothing names it yet; it is then picked like the rest.
7
+ */
8
+ import { DocumentTypeService } from '@umbraco-cms/backoffice/external/backend-api'
9
+ import { css, html, nothing } from '@umbraco-cms/backoffice/external/lit'
10
+ import { UmbModalBaseElement } from '@umbraco-cms/backoffice/modal'
11
+ import { componentName, filterTree, templateTree, withAllowed } from './template-picker-model.js'
12
+
13
+ const base = () =>
14
+ `${(document.querySelector('base')?.getAttribute('href') ?? '/umbraco/').replace(/\/$/, '')}/crombolo/api/templates`
15
+
16
+ async function components() {
17
+ const response = await fetch(base(), { credentials: 'include' })
18
+ if (!response.ok) throw new Error(`templates responded ${response.status}`)
19
+ return (await response.json()).items
20
+ }
21
+
22
+ /** The template a component is, made when nothing names it yet. */
23
+ async function templateOf(alias) {
24
+ const response = await fetch(base(), {
25
+ method: 'POST',
26
+ credentials: 'include',
27
+ headers: { 'content-type': 'application/json' },
28
+ body: JSON.stringify({ alias }),
29
+ })
30
+ if (!response.ok) throw new Error(`templates responded ${response.status}`)
31
+ return (await response.json()).id
32
+ }
33
+
34
+ /** Adds a template to a content type's allowed templates; the list of ids after. */
35
+ async function allowTemplate(documentTypeUnique, templateId) {
36
+ const { data: type } = await DocumentTypeService.getDocumentTypeById({
37
+ path: { id: documentTypeUnique },
38
+ })
39
+ const { id: _id, ...body } = type
40
+ const allowedTemplates = withAllowed(type.allowedTemplates, templateId)
41
+ await DocumentTypeService.putDocumentTypeById({
42
+ path: { id: documentTypeUnique },
43
+ body: { ...body, allowedTemplates },
44
+ })
45
+ return allowedTemplates.map((t) => t.id)
46
+ }
47
+
48
+ export default class CromboloTemplatePickerModalElement extends UmbModalBaseElement {
49
+ static properties = {
50
+ _templates: { state: true },
51
+ _allowedIds: { state: true },
52
+ _query: { state: true },
53
+ _toggled: { state: true },
54
+ _busy: { state: true },
55
+ _problem: { state: true },
56
+ }
57
+
58
+ constructor() {
59
+ super()
60
+ this._query = ''
61
+ /** Folders opened or closed by hand, against the first level being open. */
62
+ this._toggled = new Set()
63
+ }
64
+
65
+ async connectedCallback() {
66
+ super.connectedCallback()
67
+ this._allowedIds = this.data?.allowedTemplateIds ?? []
68
+ try {
69
+ this._templates = (await components()).map((c) => ({
70
+ id: c.id,
71
+ alias: c.alias,
72
+ name: componentName(c.alias),
73
+ }))
74
+ } catch {
75
+ this._problem = 'The templates could not be listed.'
76
+ this._templates = []
77
+ }
78
+ }
79
+
80
+ get #typeName() {
81
+ return this.data?.documentTypeName || 'this content type'
82
+ }
83
+
84
+ #pick(template) {
85
+ this.value = { unique: template.id, allowedTemplateIds: this._allowedIds }
86
+ this._submitModal()
87
+ }
88
+
89
+ async #allow(template) {
90
+ this._busy = template.alias
91
+ this._problem = undefined
92
+ try {
93
+ const id = template.id ?? (await templateOf(template.alias))
94
+ this._templates = this._templates.map((t) => (t.alias === template.alias ? { ...t, id } : t))
95
+ this._allowedIds = await allowTemplate(this.data.documentTypeUnique, id)
96
+ } catch {
97
+ this._problem = `${template.name} could not be allowed for ${this.#typeName}.`
98
+ } finally {
99
+ this._busy = undefined
100
+ }
101
+ }
102
+
103
+ #isOpen(folder, depth) {
104
+ if (this._query.trim()) return true
105
+ return (depth === 0) !== this._toggled.has(folder.path)
106
+ }
107
+
108
+ #toggle(folder) {
109
+ const toggled = new Set(this._toggled)
110
+ if (toggled.has(folder.path)) toggled.delete(folder.path)
111
+ else toggled.add(folder.path)
112
+ this._toggled = toggled
113
+ }
114
+
115
+ #folder(folder, depth) {
116
+ const open = this.#isOpen(folder, depth)
117
+ return html`<li role="treeitem" aria-expanded=${open ? 'true' : 'false'}>
118
+ <button type="button" class="row folder" @click=${() => this.#toggle(folder)}>
119
+ <uui-symbol-expand ?open=${open}></uui-symbol-expand>
120
+ <umb-icon name="icon-folder"></umb-icon>${folder.name}
121
+ </button>
122
+ ${open ? this.#branch(folder, depth + 1) : nothing}
123
+ </li>`
124
+ }
125
+
126
+ #branch(folder, depth) {
127
+ return html`<ul role="group">
128
+ ${folder.folders.map((child) => this.#folder(child, depth))}
129
+ ${folder.items.map((template) => this.#item(template))}
130
+ </ul>`
131
+ }
132
+
133
+ #item(template) {
134
+ const current = template.id !== null && template.id === this.data?.selected
135
+ if (template.allowed)
136
+ return html`<li role="treeitem">
137
+ <button
138
+ type="button"
139
+ class="row pick"
140
+ title=${template.alias}
141
+ aria-current=${current ? 'true' : 'false'}
142
+ @click=${() => this.#pick(template)}
143
+ >
144
+ <span class="spacer"></span><umb-icon name="icon-document-html"></umb-icon>${template.name}
145
+ </button>
146
+ </li>`
147
+ return html`<li role="treeitem" class="blocked">
148
+ <span class="row name" title=${template.alias}
149
+ ><span class="spacer"></span><umb-icon name="icon-document-html"></umb-icon>${template.name}</span
150
+ >
151
+ <span class="why">Not allowed for ${this.#typeName}</span>
152
+ ${
153
+ this.data?.mayAllow
154
+ ? html`<uui-button
155
+ compact
156
+ look="secondary"
157
+ label=${`Allow ${template.name} for ${this.#typeName}`}
158
+ .state=${this._busy === template.alias ? 'waiting' : undefined}
159
+ ?disabled=${this._busy !== undefined}
160
+ @click=${() => this.#allow(template)}
161
+ >Allow for ${this.#typeName}</uui-button
162
+ >`
163
+ : nothing
164
+ }
165
+ </li>`
166
+ }
167
+
168
+ #tree() {
169
+ if (!this._templates) return html`<uui-loader></uui-loader>`
170
+ const shown = filterTree(templateTree(this._templates, this._allowedIds), this._query)
171
+ if (shown.folders.length === 0 && shown.items.length === 0)
172
+ return html`<p class="note">No template has that name.</p>`
173
+ return html`<ul role="tree" aria-label="Templates">
174
+ ${shown.folders.map((folder) => this.#folder(folder, 0))}
175
+ ${shown.items.map((template) => this.#item(template))}
176
+ </ul>`
177
+ }
178
+
179
+ render() {
180
+ const blocked = (this._templates ?? []).some(
181
+ (t) =>
182
+ t.id === null || !this._allowedIds.some((id) => id.toLowerCase() === t.id.toLowerCase()),
183
+ )
184
+ return html`<umb-body-layout headline="Choose a template">
185
+ <uui-box>
186
+ <uui-input
187
+ class="search"
188
+ label="Search templates"
189
+ placeholder="Search by name"
190
+ .value=${this._query}
191
+ @input=${(e) => {
192
+ this._query = e.target.value ?? ''
193
+ }}
194
+ >
195
+ <umb-icon name="icon-search" slot="prepend"></umb-icon>
196
+ </uui-input>
197
+ ${this.#tree()}
198
+ ${
199
+ blocked && !this.data?.mayAllow
200
+ ? html`<p class="note" role="status">
201
+ Someone with access to Structure can allow more templates for ${this.#typeName}.
202
+ </p>`
203
+ : nothing
204
+ }
205
+ ${this._problem ? html`<p role="alert">${this._problem}</p>` : nothing}
206
+ </uui-box>
207
+ <uui-button slot="actions" label="Close" @click=${() => this._rejectModal()}>Close</uui-button>
208
+ </umb-body-layout>`
209
+ }
210
+
211
+ static styles = css`
212
+ .search {
213
+ width: 100%;
214
+ margin-bottom: var(--uui-size-space-4);
215
+ }
216
+ ul {
217
+ list-style: none;
218
+ margin: 0;
219
+ padding: 0;
220
+ }
221
+ ul ul {
222
+ padding-left: var(--uui-size-space-5);
223
+ }
224
+ li.blocked {
225
+ display: flex;
226
+ align-items: center;
227
+ gap: var(--uui-size-space-3);
228
+ }
229
+ .row {
230
+ display: flex;
231
+ align-items: center;
232
+ gap: var(--uui-size-space-2);
233
+ min-height: 2.2rem;
234
+ padding: 0 var(--uui-size-space-3);
235
+ border: 0;
236
+ border-radius: var(--uui-border-radius);
237
+ background: none;
238
+ color: inherit;
239
+ font: inherit;
240
+ text-align: left;
241
+ }
242
+ button.row {
243
+ width: 100%;
244
+ cursor: pointer;
245
+ }
246
+ button.row:hover,
247
+ .pick[aria-current='true'] {
248
+ background: var(--uui-color-surface-emphasis);
249
+ }
250
+ .pick[aria-current='true'] {
251
+ font-weight: 700;
252
+ }
253
+ .spacer {
254
+ display: inline-block;
255
+ width: 1em;
256
+ }
257
+ uui-symbol-expand {
258
+ width: 1em;
259
+ }
260
+ .blocked .name {
261
+ color: var(--uui-color-disabled-contrast);
262
+ }
263
+ .why,
264
+ .note {
265
+ color: var(--uui-color-text-alt);
266
+ font-size: var(--uui-type-small-size);
267
+ }
268
+ .why {
269
+ flex: 1;
270
+ }
271
+ `
272
+ }
273
+
274
+ customElements.define('crombolo-template-picker-modal', CromboloTemplatePickerModalElement)
275
+
276
+ export { CromboloTemplatePickerModalElement as element }
@@ -0,0 +1,77 @@
1
+ /**
2
+ * What a page's template picker shows (`template-picker.js`): every component as
3
+ * a tree of the folders `components/` keeps it in, each saying whether the page's
4
+ * content type allows it, and that tree narrowed to a search. A template's alias
5
+ * is its path, so its folders are the alias's parts before the last `/`. Pure, so
6
+ * each is tested on its own.
7
+ */
8
+
9
+ /**
10
+ * A component: `id` is its template's key, null while nothing names it.
11
+ * @typedef {{ id: string | null, name: string, alias: string, allowed: boolean }} TemplateItem
12
+ * @typedef {{ name: string, path: string, folders: TemplateFolder[], items: TemplateItem[] }} TemplateFolder
13
+ */
14
+
15
+ /** A component's name: the last part of its path. */
16
+ export const componentName = (alias) => alias.slice(alias.lastIndexOf('/') + 1)
17
+
18
+ /**
19
+ * @param {{ id: string | null, name: string, alias: string }[]} templates
20
+ * @param {string[]} allowedIds
21
+ * @returns {TemplateFolder} the root: its own components, and its folders
22
+ */
23
+ export function templateTree(templates, allowedIds) {
24
+ const allowed = new Set(allowedIds.map((id) => id.toLowerCase()))
25
+ const root = { name: '', path: '', folders: [], items: [] }
26
+ for (const template of templates) {
27
+ const parts = template.alias.split('/').slice(0, -1)
28
+ let at = root
29
+ for (const part of parts) {
30
+ const path = at.path ? `${at.path}/${part}` : part
31
+ let next = at.folders.find((folder) => folder.name === part)
32
+ if (!next) {
33
+ next = { name: part, path, folders: [], items: [] }
34
+ at.folders.push(next)
35
+ }
36
+ at = next
37
+ }
38
+ at.items.push({
39
+ ...template,
40
+ allowed: template.id !== null && allowed.has(template.id.toLowerCase()),
41
+ })
42
+ }
43
+ const sort = (folder) => {
44
+ folder.folders.sort((a, b) => a.name.localeCompare(b.name))
45
+ folder.items.sort((a, b) => a.name.localeCompare(b.name))
46
+ for (const child of folder.folders) sort(child)
47
+ return folder
48
+ }
49
+ return sort(root)
50
+ }
51
+
52
+ /**
53
+ * The tree with only the components whose name or path holds `query`, and the
54
+ * folders that lead to them; the same tree for no query.
55
+ *
56
+ * @param {TemplateFolder} folder
57
+ * @param {string} query
58
+ * @returns {TemplateFolder}
59
+ */
60
+ export function filterTree(folder, query) {
61
+ const q = query.trim().toLowerCase()
62
+ if (!q) return folder
63
+ const narrow = (at) => ({
64
+ ...at,
65
+ items: at.items.filter(
66
+ (item) => item.name.toLowerCase().includes(q) || item.alias.toLowerCase().includes(q),
67
+ ),
68
+ folders: at.folders.map(narrow).filter((f) => f.items.length > 0 || f.folders.length > 0),
69
+ })
70
+ return narrow(folder)
71
+ }
72
+
73
+ /** The content type's allowed templates with one more, as its update sends them. Pure. */
74
+ export function withAllowed(allowedTemplates, id) {
75
+ const list = allowedTemplates ?? []
76
+ return list.some((t) => t.id.toLowerCase() === id.toLowerCase()) ? list : [...list, { id }]
77
+ }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * A page's template picker (the Info view's "Choose"): a panel that slides in, as
3
+ * Umbraco's pickers do, with every component in a tree of its folders
4
+ * (`template-picker-modal.js`). The fork asks for it through
5
+ * `umbCromboloHooks.pickTemplate`.
6
+ */
7
+ import { UMB_CURRENT_USER_CONTEXT } from '@umbraco-cms/backoffice/current-user'
8
+
9
+ export const TEMPLATE_PICKER_MODAL = 'Crombolo.Modal.TemplatePicker'
10
+ const STRUCTURE = 'Crombolo.Section.Structure'
11
+
12
+ /** Whether the reader may change a content type: Structure, which Settings brings. */
13
+ async function mayChangeTypes(host) {
14
+ const context = await host.getContext?.(UMB_CURRENT_USER_CONTEXT).catch(() => undefined)
15
+ if (!context) return false
16
+ const user = await new Promise((resolve) => {
17
+ const subscription = context.currentUser.subscribe((current) => {
18
+ resolve(current)
19
+ queueMicrotask(() => subscription.unsubscribe())
20
+ })
21
+ })
22
+ return user?.isAdmin === true || (user?.allowedSections ?? []).includes(STRUCTURE)
23
+ }
24
+
25
+ export const onInit = async (_host, extensionRegistry) => {
26
+ extensionRegistry.register({
27
+ type: 'modal',
28
+ alias: TEMPLATE_PICKER_MODAL,
29
+ name: 'Crombolo Template Picker',
30
+ element: () => import('./template-picker-modal.js'),
31
+ })
32
+ const [{ umbCromboloHooks }, { UmbModalToken, umbOpenModal }] = await Promise.all([
33
+ import('@umbraco-cms/backoffice/extension-registry'),
34
+ import('@umbraco-cms/backoffice/modal'),
35
+ ])
36
+ const token = new UmbModalToken(TEMPLATE_PICKER_MODAL, {
37
+ modal: { type: 'sidebar', size: 'medium' },
38
+ })
39
+ umbCromboloHooks.pickTemplate = async (host, args) =>
40
+ umbOpenModal(host, token, {
41
+ data: { ...args, mayAllow: await mayChangeTypes(host) },
42
+ }).catch(() => undefined)
43
+ }
@@ -11,6 +11,7 @@
11
11
  * (an import as well as a tag) and Razor's sections, are hidden.
12
12
  */
13
13
  import { PartialViewService, TemplateService } from '@umbraco-cms/backoffice/external/backend-api'
14
+ import { highlightJsx } from './tsx-highlighting.js'
14
15
  import { toTsxSnippet } from './tsx-snippets.js'
15
16
  import {
16
17
  fileBeingCreated,
@@ -120,6 +121,7 @@ async function typeLibs() {
120
121
  }
121
122
 
122
123
  let loaded
124
+ let highlighted
123
125
 
124
126
  /**
125
127
  * Configures monaco's TypeScript service for TSX, and reports both monaco and
@@ -143,6 +145,9 @@ async function configureTsx() {
143
145
  const ts = monaco.typescript ?? monaco.languages?.typescript
144
146
  if (!ts) throw new Error('monaco exposes no TypeScript service')
145
147
  const { JsxEmit, ModuleKind, ScriptTarget, typescriptDefaults } = ts
148
+ // Colours the markup, which monaco's TypeScript grammar leaves plain.
149
+ highlighted ??= highlightJsx(monaco)
150
+ await highlighted
146
151
  const { libs, jsxImportSource } = await typeLibs()
147
152
  // The site's `apps/site/tsconfig.json`, so that what the editor underlines
148
153
  // is what `tsc` would report and nothing else — down to the JSX mode the
@@ -0,0 +1,81 @@
1
+ /**
2
+ * Colours JSX in a view's code editor. monaco's TypeScript highlighting has no
3
+ * rules for markup, so `<div className="x">` read as plain text in a TSX file;
4
+ * `withJsx` adds them to its grammar: tags, attributes and their values, and
5
+ * `{…}` inside markup, which is TypeScript again. A `<` right after a name is a
6
+ * type argument, `useState<string>`, never a tag: monaco's grammar matches from
7
+ * where it is and cannot look back, so the name and its `<` are read together. Pure.
8
+ */
9
+
10
+ /** A name with `<` straight after it: a type argument, as in `useState<string>`. */
11
+ export const TYPE_ARGUMENTS = /([A-Za-z_$][\w$]*)(<)/
12
+ /** A tag starts at `<` and a name, or `<>` for a fragment. */
13
+ export const TAG_START = /(<)([A-Za-z_$][\w$.:-]*)(?=[\s/>])/
14
+ const FRAGMENT_START = /(<)(>)/
15
+
16
+ /**
17
+ * monaco's TypeScript grammar, as its loader gives it, with JSX states added.
18
+ *
19
+ * @param {{ tokenizer: Record<string, unknown[]> } & Record<string, unknown>} language
20
+ */
21
+ export function withJsx(language) {
22
+ const root = language.tokenizer.root ?? []
23
+ return {
24
+ ...language,
25
+ tokenizer: {
26
+ ...language.tokenizer,
27
+ root: [
28
+ [
29
+ TYPE_ARGUMENTS,
30
+ [{ cases: { '@keywords': 'keyword', '@default': 'identifier' } }, 'delimiter.bracket'],
31
+ ],
32
+ [TAG_START, ['delimiter.html', { token: 'tag', next: '@jsxTag' }]],
33
+ [FRAGMENT_START, ['delimiter.html', { token: 'delimiter.html', next: '@jsxChildren' }]],
34
+ ...root,
35
+ ],
36
+ // Inside an opening tag: attributes until `>` (children follow) or `/>`.
37
+ jsxTag: [
38
+ [/\s+/, ''],
39
+ [/\/>/, { token: 'delimiter.html', next: '@pop' }],
40
+ [/>/, { token: 'delimiter.html', switchTo: '@jsxChildren' }],
41
+ [/[A-Za-z_$][\w$:-]*/, 'attribute.name'],
42
+ [/=/, 'delimiter'],
43
+ [/"[^"]*"/, 'attribute.value'],
44
+ [/'[^']*'/, 'attribute.value'],
45
+ [/\{/, { token: 'delimiter.bracket', next: '@jsxExpression' }],
46
+ ],
47
+ // Between an opening tag and its closing one: text, nested tags, `{…}`.
48
+ jsxChildren: [
49
+ [
50
+ /(<\/)([A-Za-z_$][\w$.:-]*)?(>)/,
51
+ ['delimiter.html', 'tag', { token: 'delimiter.html', next: '@pop' }],
52
+ ],
53
+ [/(<)([A-Za-z_$][\w$.:-]*)/, ['delimiter.html', { token: 'tag', next: '@jsxTag' }]],
54
+ [/(<)(>)/, ['delimiter.html', { token: 'delimiter.html', next: '@jsxChildren' }]],
55
+ [/\{/, { token: 'delimiter.bracket', next: '@jsxExpression' }],
56
+ [/[^<{]+/, ''],
57
+ ],
58
+ // TypeScript inside `{…}`, which may hold markup of its own.
59
+ jsxExpression: [
60
+ [/\{/, { token: 'delimiter.bracket', next: '@jsxExpression' }],
61
+ [/\}/, { token: 'delimiter.bracket', next: '@pop' }],
62
+ { include: '@root' },
63
+ ],
64
+ },
65
+ }
66
+ }
67
+
68
+ /**
69
+ * Puts JSX into monaco's `typescript` grammar, once. monaco sets the grammar when
70
+ * a language is first used, so it is used first, and ours goes in after it.
71
+ */
72
+ export async function highlightJsx(monaco) {
73
+ const typescript = monaco.languages.getLanguages().find((l) => l.id === 'typescript')
74
+ if (!typescript?.loader) return false
75
+ monaco.editor.createModel('', 'typescript').dispose()
76
+ const { language } = await typescript.loader()
77
+ // Let monaco's own registration, queued by the model above, land first.
78
+ await new Promise((resolve) => setTimeout(resolve, 0))
79
+ monaco.languages.setMonarchTokensProvider('typescript', withJsx(language))
80
+ return true
81
+ }