@crombolo/backoffice-host 0.46.1 → 0.47.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crombolo/backoffice-host",
3
- "version": "0.46.1",
3
+ "version": "0.47.0",
4
4
  "description": "Internal to crombolo, with no compatibility promise: use @crombolo/crombolo. Serves the Umbraco backoffice SPA: shell HTML, import map and package manifests.",
5
5
  "license": "MIT",
6
6
  "author": "Crombolo",
@@ -32,7 +32,7 @@
32
32
  "access": "public"
33
33
  },
34
34
  "dependencies": {
35
- "@crombolo/core": "0.46.1",
36
- "@crombolo/backoffice-dist": "0.46.1"
35
+ "@crombolo/core": "0.47.0",
36
+ "@crombolo/backoffice-dist": "0.47.0"
37
37
  }
38
38
  }
@@ -2,7 +2,7 @@
2
2
  "$schema": "../../../backoffice-dist/dist/umbraco-package-schema.json",
3
3
  "name": "Crombolo App Preview",
4
4
  "id": "Crombolo.AppPreview",
5
- "version": "0.46.1",
5
+ "version": "0.47.0",
6
6
  "allowPublicAccess": false,
7
7
  "extensions": [
8
8
  {
@@ -2,7 +2,7 @@
2
2
  "$schema": "../../../backoffice-dist/dist/umbraco-package-schema.json",
3
3
  "name": "Crombolo Localizations",
4
4
  "id": "Crombolo.Localizations",
5
- "version": "0.46.1",
5
+ "version": "0.47.0",
6
6
  "allowPublicAccess": true,
7
7
  "extensions": [
8
8
  {
@@ -0,0 +1,70 @@
1
+ /**
2
+ * The document workspace's note of whether a page's copies are shared, and
3
+ * the files that make it each member's (story 264). Registered by
4
+ * `page-sharing.js`; asked again each time the page is opened.
5
+ */
6
+ import { UMB_DOCUMENT_WORKSPACE_CONTEXT } from '@umbraco-cms/backoffice/document'
7
+ import { css, html, nothing } from '@umbraco-cms/backoffice/external/lit'
8
+ import { UmbLitElement } from '@umbraco-cms/backoffice/lit-element'
9
+ import { describeSharing, fileEditorHref, readPageSharing } from './page-sharing.js'
10
+
11
+ export default class CromboloPageSharingInfoElement extends UmbLitElement {
12
+ static properties = {
13
+ _said: { state: true },
14
+ }
15
+
16
+ #unique
17
+
18
+ constructor() {
19
+ super()
20
+ this._said = undefined
21
+ this.consumeContext(UMB_DOCUMENT_WORKSPACE_CONTEXT, (context) => {
22
+ this.observe(context?.unique, (unique) => {
23
+ if (!unique || unique === this.#unique) return
24
+ this.#unique = unique
25
+ readPageSharing(unique).then(
26
+ (state) => {
27
+ this._said = describeSharing(state)
28
+ },
29
+ () => {
30
+ this._said = undefined
31
+ },
32
+ )
33
+ })
34
+ })
35
+ }
36
+
37
+ render() {
38
+ if (!this._said) return nothing
39
+ return html`<umb-workspace-info-app-layout headline="Sharing">
40
+ <div class="body">
41
+ <p>${this._said.text}</p>
42
+ ${
43
+ this._said.files.length
44
+ ? html`<ul>
45
+ ${this._said.files.map(
46
+ (file) =>
47
+ html`<li><a href=${fileEditorHref(file)}>${file.replace(/^\//, '')}</a></li>`,
48
+ )}
49
+ </ul>`
50
+ : nothing
51
+ }
52
+ </div>
53
+ </umb-workspace-info-app-layout>`
54
+ }
55
+
56
+ static styles = css`
57
+ .body {
58
+ padding: var(--uui-size-space-4, 12px) var(--uui-size-space-5, 18px);
59
+ }
60
+ p {
61
+ margin: 0;
62
+ }
63
+ ul {
64
+ margin: var(--uui-size-space-3, 9px) 0 0;
65
+ padding-left: var(--uui-size-space-5, 18px);
66
+ }
67
+ `
68
+ }
69
+
70
+ customElements.define('crombolo-page-sharing-info', CromboloPageSharingInfoElement)
@@ -0,0 +1,93 @@
1
+ /**
2
+ * Whether a page's copies are shared, on the document's Info tab (story 264).
3
+ * The server renders the published page as a signed-out visitor and says how
4
+ * long copies are kept, whether a check is answered without rendering, and
5
+ * which view files show the signed-in member, which make it rendered for each
6
+ * member. Each file links to its editor. docs/rendering.md, "Caching, inferred".
7
+ */
8
+
9
+ const backOffice = () =>
10
+ (document.querySelector('base')?.getAttribute('href') ?? '/umbraco/').replace(/\/$/, '')
11
+
12
+ /** What the server says about a page's copies. */
13
+ export const readPageSharing = async (key, culture) => {
14
+ const query = culture ? `?culture=${encodeURIComponent(culture)}` : ''
15
+ const response = await fetch(
16
+ `${backOffice()}/crombolo/api/page-sharing/${encodeURIComponent(key)}${query}`,
17
+ { credentials: 'include', headers: { accept: 'application/json' } },
18
+ )
19
+ if (!response.ok) throw new Error(`The server answered ${response.status}.`)
20
+ return response.json()
21
+ }
22
+
23
+ /** Seconds as a person says them: "5 minutes", "1 hour". */
24
+ export const duration = (seconds) => {
25
+ const units = [
26
+ [86_400, 'day'],
27
+ [3_600, 'hour'],
28
+ [60, 'minute'],
29
+ [1, 'second'],
30
+ ]
31
+ for (const [size, name] of units)
32
+ if (seconds >= size && seconds % size === 0) {
33
+ const count = seconds / size
34
+ return `${count} ${name}${count === 1 ? '' : 's'}`
35
+ }
36
+ return `${seconds} seconds`
37
+ }
38
+
39
+ /** The editor of a view file, by its path under the views: `/shared/layout.tsx`. */
40
+ export const fileEditorHref = (path, base = backOffice()) =>
41
+ `${base}/section/settings/workspace/partial-view/edit/${encodeURIComponent(path.replace('.', '%dot%'))}`
42
+
43
+ /**
44
+ * The Info tab's words for a page: a headline sentence, and the files that
45
+ * make it each member's, if any. Pure.
46
+ */
47
+ export const describeSharing = (state) => {
48
+ switch (state?.status) {
49
+ case 'unpublished':
50
+ return { text: 'Not published, so there is nothing to share yet.', files: [] }
51
+ case 'membersOnly':
52
+ return { text: 'Members only: shown to each member on their own, never shared.', files: [] }
53
+ case 'notRendered':
54
+ return {
55
+ text: `It could not be shown to check${state.message ? `: ${state.message}` : '.'}`,
56
+ files: [],
57
+ }
58
+ case 'notShared':
59
+ return {
60
+ text: 'Not shared: it reads something from each visit, such as cookies or the address’s query.',
61
+ files: [],
62
+ }
63
+ case 'shared': {
64
+ const kept =
65
+ state.keptFor === null || state.keptFor === undefined
66
+ ? 'shared with every visitor, though the site sets no time to keep copies'
67
+ : state.keptFor === 0
68
+ ? 'shared with every visitor, but no copies are kept'
69
+ : `kept for ${duration(state.keptFor)}${state.checkedWithoutRendering ? ', checked without rendering' : ''}`
70
+ const files = state.memberFiles ?? []
71
+ if (files.length === 0) return { text: `Copies are ${kept}.`, files }
72
+ return {
73
+ text: `Copies are ${kept} for signed-out visitors, and shown to each signed-in member on their own, because ${files.length === 1 ? 'this file shows' : 'these files show'} the signed-in member. Move that part into a file of its own and mark it to load separately, and the page is shared with members too.`,
74
+ files,
75
+ }
76
+ }
77
+ default:
78
+ return undefined
79
+ }
80
+ }
81
+
82
+ export const PAGE_SHARING_INFO = {
83
+ type: 'workspaceInfoApp',
84
+ alias: 'Crombolo.WorkspaceInfoApp.Document.Sharing',
85
+ name: 'Crombolo Page Sharing Info',
86
+ element: () => import('./page-sharing-info.js'),
87
+ weight: 85,
88
+ conditions: [{ alias: 'Umb.Condition.WorkspaceAlias', match: 'Umb.Workspace.Document' }],
89
+ }
90
+
91
+ export const onInit = (_host, extensionRegistry) => {
92
+ extensionRegistry.register(PAGE_SHARING_INFO)
93
+ }
@@ -0,0 +1,112 @@
1
+ /**
2
+ * "A personalised part" from a view's Insert menu (story 264): pick an existing
3
+ * view, or name a new one, made from the "Personalised part" starter. Answers
4
+ * the view's path; `view-parts.js` writes its tag and import. Registered by
5
+ * `tsx-editors.js`.
6
+ */
7
+ import { PartialViewService } from '@umbraco-cms/backoffice/external/backend-api'
8
+ import { css, html, nothing } from '@umbraco-cms/backoffice/external/lit'
9
+ import { UmbModalBaseElement, umbOpenModal } from '@umbraco-cms/backoffice/modal'
10
+ import { UMB_PARTIAL_VIEW_PICKER_MODAL } from '@umbraco-cms/backoffice/partial-view'
11
+ import { componentName, partFileName } from './view-parts.js'
12
+
13
+ export default class CromboloPersonalisedPartModalElement extends UmbModalBaseElement {
14
+ static properties = {
15
+ _name: { state: true },
16
+ _busy: { state: true },
17
+ _message: { state: true },
18
+ }
19
+
20
+ constructor() {
21
+ super()
22
+ this._name = ''
23
+ this._busy = false
24
+ this._message = ''
25
+ }
26
+
27
+ async #pick() {
28
+ const picked = await umbOpenModal(this, UMB_PARTIAL_VIEW_PICKER_MODAL).catch(() => undefined)
29
+ const unique = picked?.selection?.[0]
30
+ if (!unique) return
31
+ this.value = { path: decodeURIComponent(unique).replace('%dot%', '.') }
32
+ this._submitModal()
33
+ }
34
+
35
+ async #make() {
36
+ const name = partFileName(this._name)
37
+ if (!name) {
38
+ this._message = 'Give the part a name.'
39
+ return
40
+ }
41
+ this._busy = true
42
+ this._message = ''
43
+ try {
44
+ const { data: starter } = await PartialViewService.getPartialViewSnippetById({
45
+ path: { id: 'PersonalisedPart' },
46
+ })
47
+ const content = (starter?.content ?? '').replace(
48
+ 'function Greeting',
49
+ `function ${componentName(name)}`,
50
+ )
51
+ await PartialViewService.postPartialView({ body: { name, parent: null, content } })
52
+ this.value = { path: `/${name}` }
53
+ this._submitModal()
54
+ } catch {
55
+ this._message = 'The part could not be made. Is there already one with that name?'
56
+ } finally {
57
+ this._busy = false
58
+ }
59
+ }
60
+
61
+ render() {
62
+ return html`<umb-body-layout headline="A personalised part">
63
+ <uui-box>
64
+ <p>
65
+ A part that shows the signed-in visitor, fetched for each visitor after the page loads, so
66
+ the rest of the page is shared.
67
+ </p>
68
+ <uui-button look="secondary" label="Choose an existing part" @click=${() => this.#pick()}
69
+ >Choose an existing part</uui-button
70
+ >
71
+ </uui-box>
72
+ <uui-box headline="Or make a new one">
73
+ <uui-label for="name">Name</uui-label>
74
+ <uui-input
75
+ id="name"
76
+ label="Name"
77
+ placeholder="User menu"
78
+ .value=${this._name}
79
+ @input=${(event) => {
80
+ this._name = event.target.value
81
+ }}></uui-input>
82
+ ${this._message ? html`<p class="problem" role="alert">${this._message}</p>` : nothing}
83
+ </uui-box>
84
+ <uui-button slot="actions" label="Cancel" @click=${() => this._rejectModal()}
85
+ >Cancel</uui-button
86
+ >
87
+ <uui-button
88
+ slot="actions"
89
+ look="primary"
90
+ color="positive"
91
+ label="Make it"
92
+ ?disabled=${this._busy}
93
+ @click=${() => this.#make()}
94
+ >Make it</uui-button
95
+ >
96
+ </umb-body-layout>`
97
+ }
98
+
99
+ static styles = css`
100
+ uui-box + uui-box {
101
+ margin-top: var(--uui-size-space-5, 18px);
102
+ }
103
+ uui-input {
104
+ width: 100%;
105
+ }
106
+ .problem {
107
+ color: var(--uui-color-danger);
108
+ }
109
+ `
110
+ }
111
+
112
+ customElements.define('crombolo-personalised-part-modal', CromboloPersonalisedPartModalElement)
@@ -0,0 +1,93 @@
1
+ /**
2
+ * The preview toolbar's visitor switch (story 264): signed out, or a member
3
+ * picked with Umbraco's member picker. Hidden from a user who cannot open
4
+ * Members. Registered by `preview-member.js`.
5
+ */
6
+ import { css, html, nothing } from '@umbraco-cms/backoffice/external/lit'
7
+ import { UmbLitElement } from '@umbraco-cms/backoffice/lit-element'
8
+ import { UMB_MEMBER_PICKER_MODAL } from '@umbraco-cms/backoffice/member'
9
+ import { umbOpenModal } from '@umbraco-cms/backoffice/modal'
10
+ import { UMB_PREVIEW_CONTEXT } from '@umbraco-cms/backoffice/preview'
11
+ import { choosePreviewMember, readPreviewMember, visitorLabel } from './preview-member.js'
12
+
13
+ export default class CromboloPreviewMemberElement extends UmbLitElement {
14
+ static properties = {
15
+ _allowed: { state: true },
16
+ _member: { state: true },
17
+ _open: { state: true },
18
+ }
19
+
20
+ constructor() {
21
+ super()
22
+ this._allowed = false
23
+ this._member = null
24
+ this._open = false
25
+ }
26
+
27
+ connectedCallback() {
28
+ super.connectedCallback()
29
+ this.hidden = true
30
+ readPreviewMember().then(({ allowed, member }) => {
31
+ this._allowed = allowed
32
+ this._member = member
33
+ this.hidden = !allowed
34
+ })
35
+ }
36
+
37
+ async #choose(member) {
38
+ this._open = false
39
+ const answer = await choosePreviewMember(member)
40
+ this._member = answer.member
41
+ const preview = await this.getContext(UMB_PREVIEW_CONTEXT)
42
+ const frame = preview?.getIFrameWrapper()?.querySelector('iframe')
43
+ if (frame) preview.reloadIFrame(frame)
44
+ }
45
+
46
+ async #pick() {
47
+ this._open = false
48
+ const picked = await umbOpenModal(this, UMB_MEMBER_PICKER_MODAL, {
49
+ data: { multiple: false },
50
+ }).catch(() => undefined)
51
+ const key = picked?.selection?.[0]
52
+ if (key) await this.#choose(key)
53
+ }
54
+
55
+ render() {
56
+ if (!this._allowed) return nothing
57
+ return html`
58
+ <uui-button look="primary" label="Visitor" compact @click=${() => (this._open = !this._open)}>
59
+ <uui-icon name="icon-user"></uui-icon><span>${visitorLabel(this._member)}</span>
60
+ </uui-button>
61
+ ${
62
+ this._open
63
+ ? html`<div class="menu" role="menu">
64
+ <uui-menu-item label="Signed out" @click-label=${() => this.#choose(null)}></uui-menu-item>
65
+ <uui-menu-item label="Choose a member…" @click-label=${() => this.#pick()}></uui-menu-item>
66
+ </div>`
67
+ : nothing
68
+ }
69
+ `
70
+ }
71
+
72
+ static styles = css`
73
+ :host {
74
+ position: relative;
75
+ display: flex;
76
+ }
77
+ span {
78
+ margin-left: var(--uui-size-space-2, 6px);
79
+ }
80
+ .menu {
81
+ position: absolute;
82
+ bottom: 100%;
83
+ right: 0;
84
+ min-width: 200px;
85
+ background: var(--uui-color-surface);
86
+ box-shadow: var(--uui-shadow-depth-3);
87
+ border-radius: var(--uui-border-radius);
88
+ z-index: 1;
89
+ }
90
+ `
91
+ }
92
+
93
+ customElements.define('crombolo-preview-member', CromboloPreviewMemberElement)
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Preview as a member (story 264): in the preview's toolbar, a user who can
3
+ * open Members chooses whether the page is shown signed out or as a member
4
+ * they pick. The server keeps the choice in a cookie of this user's, records
5
+ * each one in the audit log, and refuses it to anyone without Members.
6
+ */
7
+
8
+ const endpoint = () =>
9
+ `${(document.querySelector('base')?.getAttribute('href') ?? '/umbraco/').replace(/\/$/, '')}/crombolo/api/preview-member`
10
+
11
+ /** Who the preview shows the page as, and whether this user may choose. */
12
+ export const readPreviewMember = async () => {
13
+ const response = await fetch(endpoint(), {
14
+ credentials: 'include',
15
+ headers: { accept: 'application/json' },
16
+ })
17
+ if (!response.ok) return { allowed: false, member: null }
18
+ return response.json()
19
+ }
20
+
21
+ /** Shows the page as this member, or signed out with null. */
22
+ export const choosePreviewMember = async (member) => {
23
+ const response = await fetch(endpoint(), {
24
+ method: 'PUT',
25
+ credentials: 'include',
26
+ headers: { accept: 'application/json', 'content-type': 'application/json' },
27
+ body: JSON.stringify({ member }),
28
+ })
29
+ if (!response.ok) throw new Error(`The server answered ${response.status}.`)
30
+ return response.json()
31
+ }
32
+
33
+ /** The toolbar's words for who the page is shown as. Pure. */
34
+ export const visitorLabel = (member) => (member ? `As ${member.name}` : 'Signed out')
35
+
36
+ export const PREVIEW_MEMBER_APP = {
37
+ type: 'previewApp',
38
+ alias: 'Crombolo.PreviewApps.Member',
39
+ name: 'Crombolo Preview: Member',
40
+ element: () => import('./preview-member-app.js'),
41
+ weight: 305,
42
+ }
43
+
44
+ export const onInit = (_host, extensionRegistry) => {
45
+ extensionRegistry.register(PREVIEW_MEMBER_APP)
46
+ }
@@ -2,7 +2,7 @@
2
2
  "$schema": "../../../backoffice-dist/dist/umbraco-package-schema.json",
3
3
  "name": "Crombolo Search & sharing",
4
4
  "id": "Crombolo.Seo",
5
- "version": "0.46.1",
5
+ "version": "0.47.0",
6
6
  "allowPublicAccess": false,
7
7
  "extensions": [
8
8
  {
@@ -2,7 +2,7 @@
2
2
  "$schema": "../../../backoffice-dist/dist/umbraco-package-schema.json",
3
3
  "name": "Crombolo Sign-in Dialog",
4
4
  "id": "Crombolo.SignInDialog",
5
- "version": "0.46.1",
5
+ "version": "0.47.0",
6
6
  "allowPublicAccess": true,
7
7
  "extensions": [
8
8
  {
@@ -10,8 +10,16 @@
10
10
  * TSX (`tsx-snippets.js`), and the inserts with no TSX equivalent, a partial view
11
11
  * (an import as well as a tag) and Razor's sections, are hidden.
12
12
  */
13
- import { PartialViewService } from '@umbraco-cms/backoffice/external/backend-api'
13
+ import { PartialViewService, TemplateService } from '@umbraco-cms/backoffice/external/backend-api'
14
14
  import { toTsxSnippet } from './tsx-snippets.js'
15
+ import {
16
+ importFor,
17
+ memberNotes,
18
+ PERSONALISED_PART_DIALOG,
19
+ partInsert,
20
+ personalisedPartInsert,
21
+ withImport,
22
+ } from './view-parts.js'
15
23
 
16
24
  export const SCAFFOLD = `import type { PageProps } from '@crombolo/crombolo'
17
25
 
@@ -177,6 +185,8 @@ async function configureTsx() {
177
185
  */
178
186
  function viewEditor() {
179
187
  let configured = { monaco: undefined, ok: false }
188
+ let model
189
+ let file
180
190
  return {
181
191
  language: 'typescript',
182
192
  async prepare() {
@@ -196,7 +206,7 @@ function viewEditor() {
196
206
  // `.tsx` on it is a file TypeScript refuses to read JSX in: every tag in the
197
207
  // view would be a syntax error. So the model is replaced by one named as the
198
208
  // file it is.
199
- const model = monaco.editor.createModel(
209
+ model = monaco.editor.createModel(
200
210
  created.getValue(),
201
211
  'typescript',
202
212
  monaco.Uri.parse(`${COMPONENTS}/view-${++opened}.tsx`),
@@ -204,8 +214,61 @@ function viewEditor() {
204
214
  editor.setModel(model)
205
215
  created.dispose()
206
216
  editor.onDidDispose(() => model.dispose())
217
+ openFile().then((path) => {
218
+ file = path
219
+ })
220
+ // Story 264: a file that shows the signed-in member says what that does to sharing.
221
+ const note = () =>
222
+ monaco.editor.setModelMarkers(
223
+ model,
224
+ 'crombolo-member',
225
+ memberNotes(model.getValue()).map((at) => ({
226
+ severity: monaco.MarkerSeverity.Info,
227
+ message: at.message,
228
+ startLineNumber: at.line,
229
+ startColumn: at.start,
230
+ endLineNumber: at.line,
231
+ endColumn: at.end,
232
+ })),
233
+ )
234
+ note()
235
+ let pending
236
+ model.onDidChangeContent(() => {
237
+ clearTimeout(pending)
238
+ pending = setTimeout(note, 300)
239
+ })
207
240
  },
208
- insert: toTsxSnippet,
241
+ insert(text) {
242
+ // A part is a tag at the cursor and an import at the top (story 264).
243
+ const part = partInsert(text)
244
+ if (!part || !model) return toTsxSnippet(text)
245
+ const line = importFor(part.path, file)
246
+ const next = withImport(model.getValue(), line)
247
+ if (next !== model.getValue()) {
248
+ const { monaco } = configured
249
+ const at = /^(?:import[^\n]*\n)*/.exec(model.getValue())?.[0].split('\n').length ?? 1
250
+ model.pushEditOperations(
251
+ [],
252
+ [{ range: new monaco.Range(at, 1, at, 1), text: `${line}\n` }],
253
+ () => null,
254
+ )
255
+ }
256
+ return part.tag
257
+ },
258
+ }
259
+ }
260
+
261
+ /** The view open in the editor, as a path under `components/`, from the address. */
262
+ async function openFile() {
263
+ const partial = /\/workspace\/partial-view\/edit\/([^/?#]+)/.exec(location.pathname)
264
+ if (partial) return decodeURIComponent(partial[1]).replace('%dot%', '.')
265
+ const template = /\/workspace\/template\/edit\/([0-9a-f-]{36})/i.exec(location.pathname)
266
+ if (!template) return undefined
267
+ try {
268
+ const { data } = await TemplateService.getTemplateById({ path: { id: template[1] } })
269
+ return data?.alias ? `/${data.alias}.tsx` : undefined
270
+ } catch {
271
+ return undefined
209
272
  }
210
273
  }
211
274
 
@@ -221,9 +284,13 @@ export const TSX_HOOKS = {
221
284
  translateSnippet: toTsxSnippet,
222
285
  viewLanguageLabel: 'TypeScript',
223
286
  hideRazorInserts: true,
287
+ // A partial view is a tag and an import, which `insert` writes (story 264).
288
+ showPartialViewInsert: true,
289
+ extraInserts: [personalisedPartInsert],
224
290
  }
225
291
 
226
- export const onInit = async () => {
292
+ export const onInit = async (_host, extensionRegistry) => {
293
+ extensionRegistry?.register(PERSONALISED_PART_DIALOG)
227
294
  const { umbCromboloHooks } = await import('@umbraco-cms/backoffice/extension-registry')
228
295
  Object.assign(umbCromboloHooks, TSX_HOOKS)
229
296
  }
@@ -2,7 +2,7 @@
2
2
  "$schema": "../../backoffice-dist/dist/umbraco-package-schema.json",
3
3
  "name": "Crombolo",
4
4
  "id": "Crombolo.Core",
5
- "version": "0.46.1",
5
+ "version": "0.47.0",
6
6
  "allowPublicAccess": false,
7
7
  "extensions": [
8
8
  {
@@ -121,6 +121,18 @@
121
121
  "name": "Crombolo Media Permissions",
122
122
  "js": "/crombolo-plugin/media-permissions.js"
123
123
  },
124
+ {
125
+ "type": "backofficeEntryPoint",
126
+ "alias": "Crombolo.EntryPoint.PageSharing",
127
+ "name": "Crombolo Page Sharing",
128
+ "js": "/crombolo-plugin/page-sharing.js"
129
+ },
130
+ {
131
+ "type": "backofficeEntryPoint",
132
+ "alias": "Crombolo.EntryPoint.PreviewMember",
133
+ "name": "Crombolo Preview Member",
134
+ "js": "/crombolo-plugin/preview-member.js"
135
+ },
124
136
  {
125
137
  "type": "backofficeEntryPoint",
126
138
  "alias": "Crombolo.EntryPoint.MediaAccess",
@@ -0,0 +1,129 @@
1
+ /**
2
+ * Parts of a view in the template editor (story 264): the note on a file that
3
+ * shows the signed-in member, and the inserts that put another view in this
4
+ * one, a tag at the cursor and its import at the top. "A personalised part"
5
+ * inserts one fetched for each visitor, chosen or made new.
6
+ */
7
+
8
+ const DIRECTIVE = /^(?:\s|\/\/[^\n]*\n|\/\*[\s\S]*?\*\/)*(['"])(use deferred|use client)\1/
9
+
10
+ /** Whether a view loads on its own: a personalised part, or one that runs in the browser. Pure. */
11
+ export const loadsSeparately = (source) => DIRECTIVE.test(source)
12
+
13
+ /** `source` with its comments blanked, keeping every line and column where it was. Pure. */
14
+ const withoutComments = (source) =>
15
+ source.replace(/\/\*[\s\S]*?\*\/|\/\/[^\n]*/g, (comment) => comment.replace(/[^\n]/g, ' '))
16
+
17
+ export const MEMBER_NOTE =
18
+ "This shows the signed-in member, so a page using it is shown to each member on their own, never shared with them. To share it, move what shows the member into a file of its own that starts with 'use deferred', a personalised part."
19
+
20
+ /** Where a view mentions the member, one note per line, unless it loads separately. Pure. */
21
+ export const memberNotes = (source) => {
22
+ if (loadsSeparately(source)) return []
23
+ const notes = []
24
+ withoutComments(source)
25
+ .split('\n')
26
+ .forEach((text, index) => {
27
+ const found = /\bmember\b/.exec(text)
28
+ if (found)
29
+ notes.push({
30
+ line: index + 1,
31
+ start: found.index + 1,
32
+ end: found.index + 1 + 'member'.length,
33
+ message: MEMBER_NOTE,
34
+ })
35
+ })
36
+ return notes
37
+ }
38
+
39
+ /** A component's name from its file: `shared/user-menu.tsx` is `UserMenu`. Pure. */
40
+ export const componentName = (path) => {
41
+ const base = (path.split('/').pop() ?? 'part').replace(/\.[jt]sx?$/, '')
42
+ const words = base.split(/[^A-Za-z0-9]+/).filter(Boolean)
43
+ const name = words.map((word) => word[0].toUpperCase() + word.slice(1)).join('')
44
+ return /^[A-Za-z]/.test(name) ? name : `Part${name}`
45
+ }
46
+
47
+ /** A view's path as the partial view insert names it, under `components/`: `/shared/greeting.tsx`. */
48
+ const viewPath = (name) =>
49
+ `/${name
50
+ .replace(/%25dot%25|%dot%/g, '.')
51
+ .replace(/^\/+/, '')
52
+ .replace(/\.(cshtml|[jt]sx?)$/, '')}.tsx`
53
+
54
+ /** A new part's file name from what was typed: `User menu` is `user-menu.tsx`. Pure. */
55
+ export const partFileName = (typed) => {
56
+ const slug = typed
57
+ .trim()
58
+ .toLowerCase()
59
+ .replace(/\.[jt]sx?$/, '')
60
+ .replace(/[^a-z0-9]+/g, '-')
61
+ .replace(/^-+|-+$/g, '')
62
+ return slug ? `${slug}.tsx` : ''
63
+ }
64
+
65
+ const PERSONALISED = 'crombolo:personalised-part:'
66
+
67
+ /** What a personalised part's insert hands the editor, for `partInsert` to write. */
68
+ export const personalisedPartSnippet = (path) => `${PERSONALISED}${path}`
69
+
70
+ /**
71
+ * A view put in this one: Umbraco's partial view insert, or a personalised
72
+ * part, as the tag at the cursor and the file to import. Undefined for any
73
+ * other insert. Pure.
74
+ */
75
+ export const partInsert = (text) => {
76
+ if (typeof text !== 'string') return undefined
77
+ if (text.startsWith(PERSONALISED)) {
78
+ const path = viewPath(text.slice(PERSONALISED.length))
79
+ return {
80
+ path,
81
+ tag: `<${componentName(path)} fallback={<span>Loading…</span>} />`,
82
+ }
83
+ }
84
+ const partial = /^@await Html\.PartialAsync\("([^"]+)"\)$/.exec(text)
85
+ if (!partial) return undefined
86
+ const path = viewPath(partial[1])
87
+ return { path, tag: `<${componentName(path)} />` }
88
+ }
89
+
90
+ /** The import of `path` from the view at `from`, both under `components/`. Pure. */
91
+ export const importFor = (path, from) => {
92
+ const target = path.split('/').filter(Boolean)
93
+ const here = (from ?? '/view.tsx').split('/').filter(Boolean).slice(0, -1)
94
+ let shared = 0
95
+ while (shared < here.length && shared < target.length - 1 && here[shared] === target[shared])
96
+ shared += 1
97
+ const up = here.length - shared
98
+ const relative = [...(up === 0 ? ['.'] : Array(up).fill('..')), ...target.slice(shared)].join('/')
99
+ return `import ${componentName(path)} from '${relative}'`
100
+ }
101
+
102
+ /** `source` with `line` among its imports, unless it already imports that file. Pure. */
103
+ export const withImport = (source, line) => {
104
+ const from = /from '([^']+)'/.exec(line)?.[1]
105
+ if (from && source.includes(`'${from}'`)) return source
106
+ const imports = /^(?:import[^\n]*\n)*/.exec(source)?.[0] ?? ''
107
+ return `${imports}${line}\n${source.slice(imports.length)}`
108
+ }
109
+
110
+ export const PERSONALISED_PART_MODAL = 'Crombolo.Modal.PersonalisedPart'
111
+
112
+ export const PERSONALISED_PART_DIALOG = {
113
+ type: 'modal',
114
+ alias: PERSONALISED_PART_MODAL,
115
+ name: 'Crombolo Personalised Part Dialog',
116
+ element: () => import('./personalised-part-modal.js'),
117
+ }
118
+
119
+ /** The Insert menu's "A personalised part": a chosen one, or a new one made from the starter. */
120
+ export const personalisedPartInsert = {
121
+ label: 'A personalised part',
122
+ async pick(host) {
123
+ const { umbOpenModal } = await import('@umbraco-cms/backoffice/modal')
124
+ const chosen = await umbOpenModal(host, PERSONALISED_PART_MODAL, { data: {} }).catch(
125
+ () => undefined,
126
+ )
127
+ return chosen?.path ? personalisedPartSnippet(chosen.path) : undefined
128
+ },
129
+ }