@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,233 @@
1
+ /**
2
+ * A `{#key}` as a chip (story 297): the item's words in the default language, and
3
+ * an × that removes it. Clicking the words opens an overlay with the item's words
4
+ * in each language, which someone with Translation can change.
5
+ */
6
+ import { css, html, LitElement, nothing } from '@umbraco-cms/backoffice/external/lit'
7
+ import {
8
+ dictionaryWord,
9
+ dictionaryWords,
10
+ saveDictionaryWord,
11
+ WORDS_CHANGED,
12
+ } from './dictionary-words-client.js'
13
+
14
+ export class CromboloDictionaryChipElement extends LitElement {
15
+ static properties = {
16
+ /** The item's name. */
17
+ name: { type: String },
18
+ readonly: { type: Boolean },
19
+ _text: { state: true },
20
+ _item: { state: true },
21
+ _language: { state: true },
22
+ _draft: { state: true },
23
+ _saving: { state: true },
24
+ _problem: { state: true },
25
+ }
26
+
27
+ #refresh = () => this.#loadText()
28
+
29
+ connectedCallback() {
30
+ super.connectedCallback()
31
+ window.addEventListener(WORDS_CHANGED, this.#refresh)
32
+ }
33
+
34
+ disconnectedCallback() {
35
+ super.disconnectedCallback()
36
+ window.removeEventListener(WORDS_CHANGED, this.#refresh)
37
+ }
38
+
39
+ willUpdate(changed) {
40
+ if (changed.has('name')) this.#loadText()
41
+ }
42
+
43
+ async #loadText() {
44
+ const name = (this.name ?? '').toLowerCase()
45
+ const word = (await dictionaryWords()).find((w) => w.name.toLowerCase() === name)
46
+ this._text = word?.text || word?.name || this.name
47
+ }
48
+
49
+ async #open() {
50
+ this._problem = undefined
51
+ this._item = undefined
52
+ this.renderRoot.querySelector('dialog')?.showModal()
53
+ const answer = await dictionaryWord(this.name)
54
+ if (!answer.ok) {
55
+ this._problem = answer.body.message ?? 'This dictionary item could not be read.'
56
+ return
57
+ }
58
+ this._item = answer.body
59
+ this._draft = Object.fromEntries(answer.body.languages.map((l) => [l.isoCode, l.text]))
60
+ this._language = answer.body.languages[0]?.isoCode
61
+ }
62
+
63
+ #close() {
64
+ this.renderRoot.querySelector('dialog')?.close()
65
+ }
66
+
67
+ async #save() {
68
+ this._saving = true
69
+ const answer = await saveDictionaryWord(this.name, this._draft)
70
+ this._saving = false
71
+ if (!answer.ok) {
72
+ this._problem = answer.body.message ?? 'The words could not be saved.'
73
+ return
74
+ }
75
+ this.#close()
76
+ }
77
+
78
+ #remove(event) {
79
+ event.stopPropagation()
80
+ this.dispatchEvent(new CustomEvent('remove', { bubbles: true, composed: true }))
81
+ }
82
+
83
+ #overlay() {
84
+ const item = this._item
85
+ if (this._problem && !item) return html`<p role="alert">${this._problem}</p>`
86
+ if (!item) return html`<uui-loader></uui-loader>`
87
+ const language = item.languages.find((l) => l.isoCode === this._language) ?? item.languages[0]
88
+ return html`<uui-tab-group>
89
+ ${item.languages.map(
90
+ (l) =>
91
+ html`<uui-tab
92
+ label=${l.name}
93
+ ?active=${l.isoCode === language?.isoCode}
94
+ @click=${() => {
95
+ this._language = l.isoCode
96
+ }}
97
+ >${l.name}${l.isDefault ? ' (default)' : ''}</uui-tab
98
+ >`,
99
+ )}
100
+ </uui-tab-group>
101
+ ${
102
+ language
103
+ ? html`<uui-textarea
104
+ label=${`Words in ${language.name}`}
105
+ .value=${this._draft?.[language.isoCode] ?? ''}
106
+ ?readonly=${!item.mayChange}
107
+ @input=${(event) => {
108
+ this._draft = { ...this._draft, [language.isoCode]: event.target.value }
109
+ }}
110
+ ></uui-textarea>`
111
+ : html`<p>This site has no languages.</p>`
112
+ }
113
+ ${
114
+ item.mayChange
115
+ ? nothing
116
+ : html`<p class="note" role="status">
117
+ You can see these words. Changing the dictionary needs access to Translation.
118
+ </p>`
119
+ }
120
+ ${this._problem ? html`<p role="alert">${this._problem}</p>` : nothing}`
121
+ }
122
+
123
+ render() {
124
+ const label = this._text ?? this.name
125
+ return html`<span class="chip">
126
+ <button type="button" class="words" title=${`From the dictionary: ${this.name}`} @click=${this.#open}>
127
+ <umb-icon name="icon-book-alt"></umb-icon>${label}
128
+ </button>
129
+ ${
130
+ this.readonly
131
+ ? nothing
132
+ : html`<button type="button" class="remove" aria-label=${`Remove ${this.name}`} @click=${this.#remove}>
133
+ ×
134
+ </button>`
135
+ }
136
+ </span>
137
+ <dialog aria-label=${`Dictionary item ${this.name}`} @close=${() => {
138
+ this._item = undefined
139
+ }}>
140
+ <h3>${this.name}</h3>
141
+ ${this.#overlay()}
142
+ <div class="actions">
143
+ <uui-button look="secondary" label="Close" @click=${this.#close}>Close</uui-button>
144
+ ${
145
+ this._item?.mayChange
146
+ ? html`<uui-button
147
+ look="primary"
148
+ color="positive"
149
+ label="Save"
150
+ .state=${this._saving ? 'waiting' : undefined}
151
+ @click=${this.#save}
152
+ >Save</uui-button
153
+ >`
154
+ : nothing
155
+ }
156
+ </div>
157
+ </dialog>`
158
+ }
159
+
160
+ static styles = css`
161
+ :host {
162
+ display: inline-block;
163
+ max-width: 100%;
164
+ }
165
+ .chip {
166
+ display: inline-flex;
167
+ align-items: stretch;
168
+ max-width: 100%;
169
+ border: 1px solid var(--uui-color-selected);
170
+ border-radius: var(--uui-border-radius);
171
+ background: var(--uui-color-surface-alt);
172
+ color: var(--uui-color-text);
173
+ font: inherit;
174
+ }
175
+ button {
176
+ font: inherit;
177
+ color: inherit;
178
+ background: none;
179
+ border: 0;
180
+ cursor: pointer;
181
+ }
182
+ .words {
183
+ display: inline-flex;
184
+ align-items: center;
185
+ gap: var(--uui-size-space-2);
186
+ padding: var(--uui-size-space-2) var(--uui-size-space-3);
187
+ overflow: hidden;
188
+ text-overflow: ellipsis;
189
+ white-space: nowrap;
190
+ }
191
+ .words:hover,
192
+ .remove:hover {
193
+ background: var(--uui-color-surface-emphasis);
194
+ }
195
+ .remove {
196
+ padding: 0 var(--uui-size-space-3);
197
+ border-left: 1px solid var(--uui-color-border);
198
+ font-size: 1.1em;
199
+ }
200
+ dialog {
201
+ width: min(36rem, calc(100vw - 2rem));
202
+ padding: var(--uui-size-space-5);
203
+ border: 1px solid var(--uui-color-border);
204
+ border-radius: var(--uui-border-radius);
205
+ background: var(--uui-color-surface);
206
+ color: var(--uui-color-text);
207
+ box-shadow: var(--uui-shadow-depth-5);
208
+ }
209
+ dialog::backdrop {
210
+ background: rgb(0 0 0 / 0.35);
211
+ }
212
+ h3 {
213
+ margin: 0 0 var(--uui-size-space-4);
214
+ }
215
+ uui-textarea {
216
+ width: 100%;
217
+ margin-top: var(--uui-size-space-4);
218
+ }
219
+ .note {
220
+ color: var(--uui-color-text-alt);
221
+ font-size: var(--uui-type-small-size);
222
+ }
223
+ .actions {
224
+ display: flex;
225
+ justify-content: flex-end;
226
+ gap: var(--uui-size-space-3);
227
+ margin-top: var(--uui-size-space-5);
228
+ }
229
+ `
230
+ }
231
+
232
+ if (!customElements.get('crombolo-dictionary-chip'))
233
+ customElements.define('crombolo-dictionary-chip', CromboloDictionaryChipElement)
@@ -0,0 +1,52 @@
1
+ /**
2
+ * The dictionary as a `{#key}` chip reads and changes it (story 297), at
3
+ * <backoffice>/crombolo/api/dictionary/*. The session cookie carries the auth.
4
+ * The list is fetched once and shared, and fetched again after a change.
5
+ */
6
+
7
+ /** Sent on `window` after a word is saved, so every chip shows the new words. */
8
+ export const WORDS_CHANGED = 'crombolo:dictionary-words-changed'
9
+
10
+ const base = () => {
11
+ const href = document.querySelector('base')?.getAttribute('href') ?? '/umbraco/'
12
+ return `${href.replace(/\/$/, '')}/crombolo/api/dictionary`
13
+ }
14
+
15
+ const call = async (path, init) => {
16
+ const response = await fetch(`${base()}${path}`, {
17
+ credentials: 'include',
18
+ headers: {
19
+ accept: 'application/json',
20
+ ...(init?.body ? { 'content-type': 'application/json' } : {}),
21
+ },
22
+ ...init,
23
+ })
24
+ const body = await response.json().catch(() => ({}))
25
+ return { ok: response.ok, status: response.status, body }
26
+ }
27
+
28
+ let listed
29
+
30
+ /** Every dictionary item, with its words in the default language. */
31
+ export const dictionaryWords = () => {
32
+ listed ??= call('/words')
33
+ .then((answer) => (answer.ok ? (answer.body.words ?? []) : []))
34
+ .catch(() => [])
35
+ return listed
36
+ }
37
+
38
+ /** One item: its words in each language, and whether this user may change them. */
39
+ export const dictionaryWord = (name) => call(`/words/${encodeURIComponent(name)}`)
40
+
41
+ /** Saves an item's words, by language; a language left empty has none. */
42
+ export const saveDictionaryWord = async (name, words) => {
43
+ const answer = await call(`/words/${encodeURIComponent(name)}`, {
44
+ method: 'PUT',
45
+ body: JSON.stringify({ words }),
46
+ })
47
+ if (answer.ok) {
48
+ listed = undefined
49
+ window.dispatchEvent(new CustomEvent(WORDS_CHANGED, { detail: { name } }))
50
+ }
51
+ return answer
52
+ }
@@ -0,0 +1,196 @@
1
+ /**
2
+ * Dictionary words in the back office (stories 294, 297). `crombolo-dictionary-words`
3
+ * goes around a text box, the form editor's and the text boxes and text areas
4
+ * of a page: a `{#key}` naming an item shows as a chip, and typing `{#`, or `#`
5
+ * at the start, offers the items. It sends `crombolo-word-choose` with the new
6
+ * value; the box it holds sends its own input as before. Without this module the
7
+ * element is unknown, and the box shows as it always did.
8
+ *
9
+ * Its entry point also tells the fork what `{#key}` in a block's label reads as.
10
+ */
11
+ import { css, html, LitElement, nothing } from '@umbraco-cms/backoffice/external/lit'
12
+ import './dictionary-chip.js'
13
+ import { dictionaryWords, WORDS_CHANGED } from './dictionary-words-client.js'
14
+ import { chipWord, suggestions, wordLine, wordValue } from './form-word-input-model.js'
15
+
16
+ export class CromboloDictionaryWordsElement extends LitElement {
17
+ static properties = {
18
+ value: { type: String },
19
+ readonly: { type: Boolean },
20
+ /** The items, when the host has them; else they are fetched. */
21
+ words: { attribute: false },
22
+ _loaded: { state: true },
23
+ _open: { state: true },
24
+ _active: { state: true },
25
+ }
26
+
27
+ #refresh = async () => {
28
+ this._loaded = await dictionaryWords()
29
+ }
30
+
31
+ constructor() {
32
+ super()
33
+ this._open = false
34
+ this._active = 0
35
+ this.addEventListener('input', () => {
36
+ this._active = 0
37
+ this._open = true
38
+ })
39
+ this.addEventListener('keydown', (event) => this.#onKeydown(event))
40
+ this.addEventListener('focusout', () => {
41
+ this._open = false
42
+ })
43
+ }
44
+
45
+ connectedCallback() {
46
+ super.connectedCallback()
47
+ window.addEventListener(WORDS_CHANGED, this.#refresh)
48
+ if (!this.words) this.#refresh()
49
+ }
50
+
51
+ disconnectedCallback() {
52
+ super.disconnectedCallback()
53
+ window.removeEventListener(WORDS_CHANGED, this.#refresh)
54
+ }
55
+
56
+ get #words() {
57
+ return this.words ?? this._loaded
58
+ }
59
+
60
+ get #found() {
61
+ return this.readonly || !this._open
62
+ ? { rows: [], more: false }
63
+ : suggestions(this.#words ?? [], this.value ?? '')
64
+ }
65
+
66
+ #choose(value) {
67
+ this._open = false
68
+ this.dispatchEvent(
69
+ new CustomEvent('crombolo-word-choose', { detail: { value }, bubbles: true, composed: true }),
70
+ )
71
+ }
72
+
73
+ #onKeydown(event) {
74
+ const { rows } = this.#found
75
+ if (rows.length === 0) return
76
+ if (event.key === 'Escape') {
77
+ event.stopPropagation()
78
+ this._open = false
79
+ } else if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
80
+ event.preventDefault()
81
+ const step = event.key === 'ArrowDown' ? 1 : rows.length - 1
82
+ this._active = (this._active + step) % rows.length
83
+ } else if (event.key === 'Enter') {
84
+ event.preventDefault()
85
+ this.#choose(wordValue((rows[this._active] ?? rows[0]).name))
86
+ }
87
+ }
88
+
89
+ updated() {
90
+ const list = this.renderRoot.querySelector('[popover]')
91
+ if (!list) return
92
+ const box = this.getBoundingClientRect()
93
+ list.style.top = `${box.bottom + 2}px`
94
+ list.style.left = `${box.left}px`
95
+ list.style.minWidth = `${box.width}px`
96
+ list.showPopover()
97
+ }
98
+
99
+ render() {
100
+ const words = this.#words
101
+ const chip = chipWord(words, this.value)
102
+ if (chip)
103
+ return html`<crombolo-dictionary-chip
104
+ .name=${chip.name}
105
+ ?readonly=${this.readonly}
106
+ @remove=${() => this.#choose('')}
107
+ ></crombolo-dictionary-chip>`
108
+ const { rows, more } = this.#found
109
+ const line = wordLine(words, this.value)
110
+ return html`<slot></slot>
111
+ ${line ? html`<p class="word">${line}</p>` : nothing}
112
+ <span class="status" role="status"
113
+ >${rows.length > 0 ? `${rows.length} dictionary items. Use the arrow keys to choose one.` : ''}</span
114
+ >
115
+ ${
116
+ rows.length > 0
117
+ ? html`<div popover="manual" role="listbox" aria-label="Dictionary items">
118
+ ${rows.map(
119
+ (word, index) => html`<div
120
+ role="option"
121
+ aria-selected=${index === this._active ? 'true' : 'false'}
122
+ @pointerdown=${(event) => {
123
+ event.preventDefault()
124
+ this.#choose(wordValue(word.name))
125
+ }}
126
+ >
127
+ <strong>${word.name}</strong> <span>${word.text}</span>
128
+ </div>`,
129
+ )}
130
+ ${more ? html`<p class="more">Keep typing to narrow this down.</p>` : nothing}
131
+ </div>`
132
+ : nothing
133
+ }`
134
+ }
135
+
136
+ static styles = css`
137
+ :host {
138
+ display: block;
139
+ }
140
+ .word {
141
+ margin: var(--uui-size-space-1) 0 0;
142
+ color: var(--uui-color-text-alt);
143
+ font-size: var(--uui-type-small-size);
144
+ }
145
+ .status {
146
+ position: absolute;
147
+ width: 1px;
148
+ height: 1px;
149
+ overflow: hidden;
150
+ clip-path: inset(50%);
151
+ }
152
+ [popover] {
153
+ position: fixed;
154
+ inset: auto;
155
+ margin: 0;
156
+ padding: var(--uui-size-space-1);
157
+ max-width: 28rem;
158
+ background: var(--uui-color-surface);
159
+ color: var(--uui-color-text);
160
+ border: 1px solid var(--uui-color-border);
161
+ border-radius: var(--uui-border-radius);
162
+ box-shadow: var(--uui-shadow-depth-3);
163
+ }
164
+ [role='option'] {
165
+ padding: var(--uui-size-space-2) var(--uui-size-space-3);
166
+ border-radius: var(--uui-border-radius);
167
+ cursor: pointer;
168
+ }
169
+ [role='option'] span {
170
+ color: var(--uui-color-text-alt);
171
+ }
172
+ [role='option'][aria-selected='true'],
173
+ [role='option']:hover {
174
+ background: var(--uui-color-surface-emphasis);
175
+ }
176
+ .more {
177
+ margin: var(--uui-size-space-1) var(--uui-size-space-3);
178
+ color: var(--uui-color-text-alt);
179
+ font-size: var(--uui-type-small-size);
180
+ }
181
+ `
182
+ }
183
+
184
+ if (!customElements.get('crombolo-dictionary-words'))
185
+ customElements.define('crombolo-dictionary-words', CromboloDictionaryWordsElement)
186
+
187
+ /** A block label's `{#key}`: the item's words in the default language, or its name. */
188
+ export const onInit = async () => {
189
+ const { umbCromboloHooks } = await import('@umbraco-cms/backoffice/extension-registry')
190
+ umbCromboloHooks.dictionaryWord = async (name) => {
191
+ const word = (await dictionaryWords()).find(
192
+ (w) => w.name.toLowerCase() === String(name).toLowerCase(),
193
+ )
194
+ return word ? word.text || word.name : undefined
195
+ }
196
+ }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Form, in the Create menu of Content Types: forms sit beside content types in
3
+ * Structure, so a new one starts from the same place. It is saved under Forms.
4
+ */
5
+ import { UmbEntityCreateOptionActionBase } from '@umbraco-cms/backoffice/entity-create-option-action'
6
+
7
+ export class CromboloFormCreateOptionAction extends UmbEntityCreateOptionActionBase {
8
+ async getHref() {
9
+ return 'section/settings/forms?new='
10
+ }
11
+ }
12
+
13
+ export { CromboloFormCreateOptionAction as api }
@@ -1,19 +1,29 @@
1
1
  /**
2
- * What the form editor's text boxes suggest (story 294). Pure, so each is tested
3
- * on its own.
2
+ * What a text box that can name a dictionary item shows (stories 294, 297): the
3
+ * items it suggests, the chip a `{#key}` becomes, and the line under it. Pure,
4
+ * so each is tested on its own. Shared by the form editor and a page's text boxes.
4
5
  */
5
6
  const ROWS = 8
7
+ /** What has been typed of a name: after `{#`, or after a `#` that starts the box. */
8
+ const TYPING = /^(?:\{#([^{}\s]*)|#(\S*))$/
9
+ const ONLY_WORD = /^\{#([^{}\s]+)\}$/
10
+ const BARE_WORD = /^#(\S+)$/
11
+
12
+ /** `{#key}` for an item's name. */
13
+ export const wordValue = (name) => `{#${name}}`
6
14
 
7
15
  /**
8
16
  * The dictionary items to offer for what has been typed: names starting with it
9
- * first, then those containing it, then those whose words do. Only after a `#`.
17
+ * first, then those containing it, then those whose words do. Only after `{#`,
18
+ * or a `#` at the start.
10
19
  *
11
20
  * @param {{ name: string, text: string }[]} words
12
21
  * @param {string} value
13
22
  */
14
23
  export function suggestions(words, value) {
15
- if (!/^#\S*$/.test(value)) return { rows: [], more: false }
16
- const typed = value.slice(1).toLowerCase()
24
+ const typing = TYPING.exec(value ?? '')
25
+ if (!typing) return { rows: [], more: false }
26
+ const typed = (typing[1] ?? typing[2] ?? '').toLowerCase()
17
27
  const rank = ({ name, text }) => {
18
28
  const lower = name.toLowerCase()
19
29
  if (lower.startsWith(typed)) return 0
@@ -29,17 +39,27 @@ export function suggestions(words, value) {
29
39
  }
30
40
 
31
41
  /**
32
- * What goes under a box: what a `#name` reads as, or that nothing has that name.
33
- * Nothing for ordinary text, or when `#` starts a few words, or before the list has loaded.
42
+ * The item a value shows as a chip: the whole of it one `{#key}`, or a `#key`
43
+ * as forms wrote it before, that names an item; undefined otherwise.
44
+ *
45
+ * @param {{ name: string, text: string }[] | undefined} words
46
+ * @param {string} value
47
+ */
48
+ export function chipWord(words, value) {
49
+ if (!words) return undefined
50
+ const name = (ONLY_WORD.exec((value ?? '').trim()) ?? BARE_WORD.exec(value ?? ''))?.[1]
51
+ if (!name) return undefined
52
+ return words.find((word) => word.name.toLowerCase() === name.toLowerCase())
53
+ }
54
+
55
+ /**
56
+ * What goes under a box: that a `{#key}` names no item. Nothing for ordinary
57
+ * text, for a chip, or before the list has loaded.
34
58
  *
35
59
  * @param {{ name: string, text: string }[] | undefined} words
36
60
  * @param {string} value
37
61
  */
38
62
  export function wordLine(words, value) {
39
- if (!words || !/^#\S+$/.test(value)) return undefined
40
- const name = value.slice(1).toLowerCase()
41
- const word = words.find((candidate) => candidate.name.toLowerCase() === name)
42
- return word
43
- ? `From the dictionary: ${word.text || word.name}`
44
- : 'No dictionary item has this name, so it shows as written.'
63
+ if (!words || !ONLY_WORD.test((value ?? '').trim()) || chipWord(words, value)) return undefined
64
+ return 'No dictionary item has this name, so it shows as written.'
45
65
  }