@crombolo/backoffice-host 0.51.1 → 0.52.2

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.
@@ -1,14 +1,16 @@
1
1
  /**
2
- * The Content section's Overview (story 236), in place of Umbraco's news: the
3
- * pages changed lately, how many are drafts or published, what people did, and
4
- * a way to start a new page. Everything comes from `crombolo/api/overview`,
2
+ * Home (stories 236, 288), where the back office opens and the logo leads: the pages changed lately, how many are drafts or published, what people
3
+ * did, a way to start a new page, and the system's details. It is the fork's
4
+ * `homeView`, outside any section. Everything comes from `crombolo/api/overview`,
5
5
  * already narrowed to what the signed-in user may see.
6
6
  */
7
+ import { UMB_AUTH_CONTEXT } from '@umbraco-cms/backoffice/auth'
7
8
  import { UMB_CURRENT_USER_CONTEXT } from '@umbraco-cms/backoffice/current-user'
8
9
  import { UMB_DOCUMENT_CREATE_OPTIONS_MODAL } from '@umbraco-cms/backoffice/document'
9
10
  import { css, html, nothing } from '@umbraco-cms/backoffice/external/lit'
10
11
  import { UmbLitElement } from '@umbraco-cms/backoffice/lit-element'
11
12
  import { umbOpenModal } from '@umbraco-cms/backoffice/modal'
13
+ import { UMB_SYSINFO_MODAL, UmbSysinfoRepository } from '@umbraco-cms/backoffice/sysinfo'
12
14
  import { activityLine, ago, avatarHue, firstName, initials, STATES } from './overview-format.js'
13
15
 
14
16
  const base = () =>
@@ -26,8 +28,13 @@ export default class CromboloOverviewDashboardElement extends UmbLitElement {
26
28
  _take: { state: true },
27
29
  _skip: { state: true },
28
30
  _error: { state: true },
31
+ _server: { state: true },
29
32
  }
30
33
 
34
+ /** The session had gone when it last asked, so signing back in is what to wait for. */
35
+ #signedOut = false
36
+ #auth
37
+
31
38
  constructor() {
32
39
  super()
33
40
  this._list = 'recent'
@@ -38,6 +45,18 @@ export default class CromboloOverviewDashboardElement extends UmbLitElement {
38
45
  this._name = current?.name
39
46
  })
40
47
  })
48
+ // Signing back in is a pop-up, so this page stays where it was and has to look again.
49
+ this.consumeContext(UMB_AUTH_CONTEXT, (auth) => {
50
+ this.#auth = auth
51
+ this.observe(auth?.isAuthorized, (authorized) => {
52
+ if (!authorized || !this.#signedOut) return
53
+ this.#signedOut = false
54
+ this.#load()
55
+ })
56
+ })
57
+ new UmbSysinfoRepository(this).requestServerInformation().then((server) => {
58
+ this._server = server
59
+ })
41
60
  }
42
61
 
43
62
  connectedCallback() {
@@ -52,10 +71,18 @@ export default class CromboloOverviewDashboardElement extends UmbLitElement {
52
71
  take: String(this._take),
53
72
  })
54
73
  try {
74
+ // Plain `fetch` renews nothing, so a token left to lapse would be refused.
75
+ await (await this.getContext(UMB_AUTH_CONTEXT))?.getLatestToken().catch(() => undefined)
55
76
  const response = await fetch(`${base()}/crombolo/api/overview?${query}`, {
56
77
  credentials: 'include',
57
78
  headers: { accept: 'application/json' },
58
79
  })
80
+ if (response.status === 401) {
81
+ // Not this page's to report: the sign-in dialog says so, and it loads after.
82
+ this.#signedOut = true
83
+ if (this.#auth?.getIsAuthorized()) this.#auth.timeOut()
84
+ return
85
+ }
59
86
  if (!response.ok) throw new Error(`overview responded ${response.status}`)
60
87
  this._data = await response.json()
61
88
  this._error = undefined
@@ -90,9 +117,9 @@ export default class CromboloOverviewDashboardElement extends UmbLitElement {
90
117
 
91
118
  render() {
92
119
  const name = firstName(this._name)
93
- return html`
120
+ return html`<div class="page">
94
121
  <header>
95
- <h1>Overview</h1>
122
+ <h1>Home</h1>
96
123
  <p>${name ? `Welcome back, ${name}. ` : ''}Here’s what’s happening in Crombolo.</p>
97
124
  </header>
98
125
  ${this._error ? html`<uui-box><p class="error">${this._error}</p></uui-box>` : nothing}
@@ -107,9 +134,34 @@ export default class CromboloOverviewDashboardElement extends UmbLitElement {
107
134
  <uui-icon name="icon-add"></uui-icon>
108
135
  </button>
109
136
  </div>
110
- <div class="side">${this.#renderStats()} ${this.#renderActivity()}</div>
137
+ <div class="side">
138
+ ${this.#renderStats()} ${this.#renderActivity()} ${this.#renderSystem()}
139
+ </div>
140
+ </div>
141
+ </div>`
142
+ }
143
+
144
+ #renderSystem() {
145
+ return html`<uui-box headline="System information">
146
+ <dl class="system">
147
+ <dt>Version</dt>
148
+ <dd>${this._server?.version ?? '…'}</dd>
149
+ <dt>Mode</dt>
150
+ <dd>${this._server?.runtimeMode ?? '…'}</dd>
151
+ </dl>
152
+ <div class="system-links">
153
+ <a href="https://github.com/kineco-au/crombolo-cms" target="_blank" rel="noopener">
154
+ Crombolo on GitHub
155
+ </a>
156
+ <button class="link" type="button" @click=${() => this.#openSystemDetails()}>
157
+ All details
158
+ </button>
111
159
  </div>
112
- `
160
+ </uui-box>`
161
+ }
162
+
163
+ #openSystemDetails() {
164
+ umbOpenModal(this, UMB_SYSINFO_MODAL).catch(() => undefined)
113
165
  }
114
166
 
115
167
  #renderPages() {
@@ -231,9 +283,27 @@ export default class CromboloOverviewDashboardElement extends UmbLitElement {
231
283
  static styles = css`
232
284
  :host {
233
285
  display: block;
286
+ height: 100%;
287
+ overflow: auto;
288
+ }
289
+ .page {
290
+ box-sizing: border-box;
234
291
  padding: var(--uui-size-layout-1);
235
292
  max-width: 1400px;
236
293
  }
294
+ .system {
295
+ display: grid;
296
+ grid-template-columns: auto 1fr;
297
+ gap: var(--uui-size-space-2) var(--uui-size-space-4);
298
+ margin: 0 0 var(--uui-size-space-4);
299
+ }
300
+ .system dt { color: var(--uui-color-text-alt); }
301
+ .system dd { margin: 0; }
302
+ .system-links {
303
+ display: flex;
304
+ justify-content: space-between;
305
+ gap: var(--uui-size-space-4);
306
+ }
237
307
  header h1 {
238
308
  margin: 0 0 var(--uui-size-space-3);
239
309
  font-size: 2rem;
@@ -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.51.1",
5
+ "version": "0.52.2",
6
6
  "allowPublicAccess": false,
7
7
  "extensions": [
8
8
  {
@@ -0,0 +1,54 @@
1
+ /**
2
+ * What a screen's own `fetch` does when a session has ended. Pure, given how to
3
+ * send and how to recover, so each is tested on its own.
4
+ */
5
+ const SIGNING_IN = /\/(security|login|oauth_complete)(\/|$)/
6
+
7
+ const hasAuthorization = (input, init) => {
8
+ const headers = new Headers(
9
+ init?.headers ?? (input instanceof Request ? input.headers : undefined),
10
+ )
11
+ return headers.has('authorization')
12
+ }
13
+
14
+ /**
15
+ * Whether a request is one of the back office's own, sent with the session cookie.
16
+ * The client's API calls carry a token and have a queue of their own, and signing
17
+ * in must never wait for itself.
18
+ *
19
+ * @param {RequestInfo | URL} input
20
+ * @param {RequestInit | undefined} init
21
+ * @param {string} base the back office's address, e.g. `http://localhost/crombolo`
22
+ */
23
+ export function covers(input, init, base) {
24
+ const url = input instanceof Request ? input.url : new URL(String(input), `${base}/`).href
25
+ if (!url.startsWith(`${base}/`)) return false
26
+ return !SIGNING_IN.test(new URL(url).pathname) && !hasAuthorization(input, init)
27
+ }
28
+
29
+ /** A consumed request cannot be sent twice, but a 401 means none of it was acted on. */
30
+ const canResend = (input) => !(input instanceof Request) || input.method === 'GET'
31
+
32
+ /**
33
+ * A `fetch` that waits for someone to sign in, rather than answering a 401.
34
+ *
35
+ * @param {typeof fetch} send
36
+ * @param {{
37
+ * covers: (input: RequestInfo | URL, init?: RequestInit) => boolean,
38
+ * signedIn: () => Promise<void>,
39
+ * recover: () => Promise<void>,
40
+ * }} session `signedIn` settles at once unless the session has ended; `recover`
41
+ * renews it, or asks the person to sign in, and settles when it is back.
42
+ */
43
+ export function guardedFetch(send, session) {
44
+ return async (input, init) => {
45
+ if (!session.covers(input, init)) return send(input, init)
46
+ await session.signedIn()
47
+ let response = await send(input, init)
48
+ for (let tries = 0; tries < 2 && response.status === 401 && canResend(input); tries++) {
49
+ await session.recover()
50
+ response = await send(input, init)
51
+ }
52
+ return response
53
+ }
54
+ }
@@ -0,0 +1,50 @@
1
+ /**
2
+ * When a session ends, a screen's own `fetch` gets a 401 that the client never
3
+ * hears of, so the screen shows an error and nothing asks anyone to sign in.
4
+ * This renews the session or opens the sign-in dialog, and each request waits
5
+ * and carries on, so the screen underneath never sees the 401.
6
+ */
7
+ import { UMB_AUTH_CONTEXT } from '@umbraco-cms/backoffice/auth'
8
+ import { UmbContextConsumerController } from '@umbraco-cms/backoffice/context-api'
9
+ import { covers, guardedFetch } from './session-guard-model.js'
10
+
11
+ const base = () =>
12
+ new URL(
13
+ document.querySelector('base')?.getAttribute('href') ?? '/umbraco/',
14
+ location.href,
15
+ ).href.replace(/\/$/, '')
16
+
17
+ const sessionOf = (auth) => {
18
+ let authorized = true
19
+ /** Those waiting for someone to sign in. */
20
+ const waiting = []
21
+ let recovering
22
+
23
+ auth.isAuthorized.subscribe((now) => {
24
+ authorized = now
25
+ if (now) for (const resume of waiting.splice(0)) resume()
26
+ })
27
+ const signedIn = () =>
28
+ authorized ? Promise.resolve() : new Promise((resume) => waiting.push(resume))
29
+
30
+ return {
31
+ covers: (input, init) => covers(input, init, base()),
32
+ signedIn,
33
+ recover: () => {
34
+ recovering ??= (async () => {
35
+ const renewed = await auth.makeRefreshTokenRequest().catch(() => false)
36
+ if (!renewed && authorized) auth.timeOut()
37
+ await signedIn()
38
+ })().finally(() => {
39
+ recovering = undefined
40
+ })
41
+ return recovering
42
+ },
43
+ }
44
+ }
45
+
46
+ export const onInit = (host) => {
47
+ new UmbContextConsumerController(host, UMB_AUTH_CONTEXT, (auth) => {
48
+ if (auth) window.fetch = guardedFetch(window.fetch.bind(window), sessionOf(auth))
49
+ })
50
+ }
@@ -13,31 +13,10 @@ export const SIDEBAR_APPS = {
13
13
  code: 'Umb.SectionSidebarMenu.Templating',
14
14
  }
15
15
 
16
- export const GROUPS = ['Build', 'Site', 'Health', 'History', 'Developers', 'Extensions', 'Other']
16
+ export const GROUPS = ['Site', 'Health', 'History', 'Developers', 'Extensions', 'Other']
17
17
 
18
18
  /** Our words for each tool, by the alias of its dashboard or menu item. */
19
19
  export const CARDS = {
20
- structure: {
21
- group: 'Build',
22
- title: 'Structure',
23
- description: 'Content, media and member types, data types and languages.',
24
- },
25
- code: {
26
- group: 'Build',
27
- title: 'Code',
28
- description: 'Components, stylesheets and scripts.',
29
- },
30
- 'Umb.Dashboard.ModelsBuilder': {
31
- group: 'Build',
32
- title: 'Types for code',
33
- description: 'The TypeScript types written from the schema, and whether they are out of date.',
34
- },
35
- 'Crombolo.Dashboard.Workflows': {
36
- group: 'Build',
37
- title: 'Workflows',
38
- description:
39
- 'The approval steps a page goes through before it is published, and who decides each.',
40
- },
41
20
  'Crombolo.Dashboard.Seo': {
42
21
  group: 'Site',
43
22
  title: 'Search & sharing',
@@ -110,6 +89,11 @@ export const CARDS = {
110
89
  title: 'CI access',
111
90
  description: 'The CI jobs that may pull and push here without a person, and what each may do.',
112
91
  },
92
+ 'Umb.Dashboard.ModelsBuilder': {
93
+ group: 'Developers',
94
+ title: 'Types for code',
95
+ description: 'The TypeScript types written from the schema, and whether they are out of date.',
96
+ },
113
97
  'Crombolo.Dashboard.Bundles': {
114
98
  group: 'Extensions',
115
99
  title: 'Bundles',
@@ -128,15 +112,11 @@ export const CARDS = {
128
112
  * @param {{
129
113
  * dashboards?: { alias: string, label?: string, description?: string, bundle?: { name: string, packageName: string }, path: string }[],
130
114
  * advanced?: { alias: string, label?: string, description?: string, bundle?: { name: string, packageName: string }, entityType: string }[],
131
- * structure?: boolean,
132
- * code?: boolean,
133
115
  * }} from
134
116
  * @returns {{ group: string, bundle?: { name: string, packageName: string, path: string }, cards: any[] }[]}
135
117
  */
136
- export function settingsCards({ dashboards = [], advanced = [], structure = false, code = false }) {
118
+ export function settingsCards({ dashboards = [], advanced = [] }) {
137
119
  const found = []
138
- if (structure) found.push({ alias: 'structure', path: 'structure' })
139
- if (code) found.push({ alias: 'code', path: 'code' })
140
120
  for (const d of dashboards)
141
121
  found.push({
142
122
  alias: d.alias,
@@ -210,15 +190,18 @@ export function treeFor(entityType) {
210
190
 
211
191
  /**
212
192
  * The trail above a Settings page: Settings, then the tree or tool it is in.
213
- * Paths are relative to the section; the last crumb is the page itself.
193
+ * Paths are relative to the section; the last crumb is the page itself, and `home`
194
+ * marks the crumb for the root of the back office, which is outside the section.
214
195
  *
215
196
  * @param {{ tree?: 'structure' | 'code', title?: string }} at
216
197
  */
217
198
  export function crumbsFor({ tree, title } = {}) {
199
+ const home = { label: 'Home', home: true }
218
200
  const settings = { label: 'Settings', path: '' }
219
- if (tree) return [settings, { label: CARDS[tree]?.title ?? tree }]
220
- if (title) return [settings, { label: title }]
221
- return []
201
+ // A tree is reached from the menu under Content, which says where it is (story 289).
202
+ if (tree) return []
203
+ if (title) return [home, settings, { label: title }]
204
+ return [home, { label: 'Settings' }]
222
205
  }
223
206
 
224
207
  /**
@@ -30,6 +30,7 @@ import {
30
30
  treeFor,
31
31
  } from './settings-cards.js'
32
32
  import './breadcrumb.js'
33
+ import { readOnlyWords } from './definition-tree-model.js'
33
34
  import './settings-card.js'
34
35
 
35
36
  const base = () =>
@@ -53,6 +54,7 @@ export class CromboloSettingsSectionElement extends UmbLitElement {
53
54
  _sidebarApps: { state: true },
54
55
  _tree: { state: true },
55
56
  _crumbs: { state: true },
57
+ _readOnly: { state: true },
56
58
  }
57
59
 
58
60
  #dashboards = []
@@ -64,6 +66,15 @@ export class CromboloSettingsSectionElement extends UmbLitElement {
64
66
 
65
67
  constructor() {
66
68
  super()
69
+ // An explanation, not a control: a failure leaves it out.
70
+ fetch(`${base()}/crombolo/api/site-files`, { credentials: 'include' })
71
+ .then((response) => (response.ok ? response.json() : { writable: true }))
72
+ .then(
73
+ (files) => {
74
+ this._readOnly = !files.writable
75
+ },
76
+ () => {},
77
+ )
67
78
  new UmbExtensionsElementInitializer(
68
79
  this,
69
80
  umbExtensionsRegistry,
@@ -154,8 +165,6 @@ export class CromboloSettingsSectionElement extends UmbLitElement {
154
165
  path: this.#dashboardPath(d),
155
166
  })),
156
167
  advanced: this.#advanced(),
157
- structure: this.#menuItems.some((m) => menuOf(m, STRUCTURE_MENU)),
158
- code: this.#menuItems.some((m) => menuOf(m, CODE_MENU)),
159
168
  })
160
169
  }
161
170
 
@@ -228,6 +237,18 @@ export class CromboloSettingsSectionElement extends UmbLitElement {
228
237
  tree('code'),
229
238
  // Umbraco's welcome, which this page replaces: an address people have.
230
239
  { path: 'dashboard/welcome', ...landing },
240
+ // Workflows moved beside forms (story 289): an address people have.
241
+ {
242
+ path: 'dashboard/workflows',
243
+ component: () => document.createElement('div'),
244
+ setup: () => {
245
+ history.replaceState(
246
+ null,
247
+ '',
248
+ new URL('section/forms/view/workflows', document.baseURI).pathname,
249
+ )
250
+ },
251
+ },
231
252
  ...dashboards,
232
253
  ...this.#sectionRoutes,
233
254
  { path: '', pathMatch: 'full', ...landing },
@@ -244,7 +265,13 @@ export class CromboloSettingsSectionElement extends UmbLitElement {
244
265
  const section = this.#sectionPath()
245
266
  const crumbs = (this._crumbs ?? []).map((c) => ({
246
267
  label: c.label,
247
- href: c.path === undefined ? undefined : c.path ? `${section}/${c.path}` : section,
268
+ href: c.home
269
+ ? document.baseURI
270
+ : c.path === undefined
271
+ ? undefined
272
+ : c.path
273
+ ? `${section}/${c.path}`
274
+ : section,
248
275
  }))
249
276
  const main = html`<umb-section-main>
250
277
  ${
@@ -258,6 +285,13 @@ export class CromboloSettingsSectionElement extends UmbLitElement {
258
285
  // Settings keeps its menus. A tree taken out and put back breaks: the trees
259
286
  // share the section's expansion state, and a detached one still answers it.
260
287
  return html`<umb-section-sidebar ?hidden=${!shown}>
288
+ ${
289
+ this._tree === 'structure' && this._readOnly
290
+ ? html`<p class="read-only" role="status">
291
+ ${readOnlyWords('Content types, data types and languages', 'site')}
292
+ </p>`
293
+ : nothing
294
+ }
261
295
  ${(this._sidebarApps ?? []).map(
262
296
  (app) => html`<div class="tree" ?hidden=${app.alias !== shown}>${app.component}</div>`,
263
297
  )}
@@ -291,6 +325,13 @@ export class CromboloSettingsSectionElement extends UmbLitElement {
291
325
  min-height: 0;
292
326
  overflow-y: auto;
293
327
  }
328
+ .read-only {
329
+ margin: 0;
330
+ padding: var(--uui-size-space-3) var(--uui-size-space-4);
331
+ font-size: var(--uui-type-small-size);
332
+ line-height: 1.5;
333
+ color: var(--uui-color-text-alt);
334
+ }
294
335
  .crumbs {
295
336
  display: block;
296
337
  padding: var(--uui-size-space-4) var(--uui-size-layout-1) 0;
@@ -317,18 +358,24 @@ export class CromboloSettingsLandingElement extends UmbLitElement {
317
358
  #email() {
318
359
  const status = this._email
319
360
  if (!status || status.available) return nothing
320
- return html`<div class="banner" role="status">
321
- <uui-icon name="icon-alert"></uui-icon>
322
- <p>
361
+ return html`<details class="banner" role="status">
362
+ <summary>
363
+ <uui-icon name="icon-alert"></uui-icon>
323
364
  <strong>E-mail is not set up.</strong>
324
- ${status.reason}
365
+ <uui-icon class="chevron" name="icon-navigation-right"></uui-icon>
366
+ </summary>
367
+ <div class="banner-details">
368
+ <p>${status.reason}</p>
325
369
  ${
326
370
  status.affects?.length > 0
327
- ? html`Until it is, these are unavailable: ${status.affects.join(', ')}.`
371
+ ? html`<p>Until it is, these are unavailable:</p>
372
+ <ul class="affected">
373
+ ${status.affects.map((feature) => html`<li>${feature}</li>`)}
374
+ </ul>`
328
375
  : nothing
329
376
  }
330
- </p>
331
- </div>`
377
+ </div>
378
+ </details>`
332
379
  }
333
380
 
334
381
  render() {
@@ -401,9 +448,6 @@ export class CromboloSettingsLandingElement extends UmbLitElement {
401
448
  gap: var(--uui-size-space-5);
402
449
  }
403
450
  .banner {
404
- display: flex;
405
- gap: var(--uui-size-space-4);
406
- align-items: flex-start;
407
451
  margin-bottom: var(--uui-size-layout-1);
408
452
  padding: var(--uui-size-space-4) var(--uui-size-space-5);
409
453
  border: 1px solid color-mix(in srgb, var(--uui-color-warning) 45%, transparent);
@@ -412,15 +456,59 @@ export class CromboloSettingsLandingElement extends UmbLitElement {
412
456
  background: color-mix(in srgb, var(--uui-color-warning) 12%, var(--uui-color-surface));
413
457
  color: var(--uui-color-text);
414
458
  }
459
+ .banner summary {
460
+ display: flex;
461
+ gap: var(--uui-size-space-4);
462
+ align-items: center;
463
+ cursor: pointer;
464
+ list-style: none;
465
+ }
466
+ .banner summary::-webkit-details-marker {
467
+ display: none;
468
+ }
469
+ .banner summary:focus-visible {
470
+ outline: 2px solid var(--uui-color-focus);
471
+ outline-offset: 2px;
472
+ }
415
473
  .banner uui-icon {
416
474
  flex: none;
417
- margin-top: 0.15em;
418
475
  color: var(--uui-color-warning-standalone, var(--uui-color-warning));
419
476
  }
477
+ .banner .chevron {
478
+ margin-left: auto;
479
+ transition: transform 120ms;
480
+ }
481
+ .banner[open] .chevron {
482
+ transform: rotate(90deg);
483
+ }
484
+ .banner-details {
485
+ margin-top: var(--uui-size-space-3);
486
+ padding-left: calc(1em + var(--uui-size-space-4));
487
+ }
420
488
  .banner p {
421
- margin: 0;
489
+ margin: 0 0 var(--uui-size-space-2);
422
490
  line-height: 1.5;
423
491
  }
492
+ .affected {
493
+ margin: 0;
494
+ padding: 0;
495
+ list-style: none;
496
+ }
497
+ .affected li {
498
+ position: relative;
499
+ padding-left: var(--uui-size-space-5);
500
+ line-height: 1.6;
501
+ }
502
+ .affected li::before {
503
+ content: '';
504
+ position: absolute;
505
+ left: 0.2em;
506
+ top: 0.6em;
507
+ width: 0.45em;
508
+ height: 0.45em;
509
+ border-radius: 50%;
510
+ background: var(--uui-color-warning-standalone, var(--uui-color-warning));
511
+ }
424
512
  `,
425
513
  ]
426
514
  }
@@ -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.51.1",
5
+ "version": "0.52.2",
6
6
  "allowPublicAccess": true,
7
7
  "extensions": [
8
8
  {
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Keeps a person's theme with them (story 049). The choice is made in their
3
+ * profile, on Umbraco's theme context, which links the stylesheet and keeps the
4
+ * alias in `localStorage` for the shell's early script to apply before the next
5
+ * paint. This keeps it in user data as well, so it follows them to another browser.
6
+ */
7
+ import { UmbContextConsumerController } from '@umbraco-cms/backoffice/context-api'
8
+ import { UMB_THEME_CONTEXT } from '@umbraco-cms/backoffice/themes'
9
+
10
+ /** The Management API, under the back office wherever it is mounted. */
11
+ const USER_DATA = `${(document.querySelector('base')?.getAttribute('href') ?? '/crombolo/').replace(/\/$/, '')}/management/api/v1/user-data`
12
+ const GROUP = 'crombolo'
13
+ const IDENTIFIER = 'theme'
14
+ const EARLY = 'crombolo-early-theme'
15
+
16
+ /** The person's saved theme, and its key for saving over it; undefined when it cannot be read. */
17
+ async function readSaved() {
18
+ try {
19
+ const query = new URLSearchParams({ groups: GROUP, identifiers: IDENTIFIER, take: '1' })
20
+ const response = await fetch(`${USER_DATA}?${query}`, { credentials: 'include' })
21
+ if (!response.ok) return undefined
22
+ return (await response.json()).items?.[0] ?? {}
23
+ } catch {
24
+ return undefined
25
+ }
26
+ }
27
+
28
+ async function save(alias, key) {
29
+ const body = { group: GROUP, identifier: IDENTIFIER, value: alias }
30
+ try {
31
+ const response = await fetch(USER_DATA, {
32
+ method: key ? 'PUT' : 'POST',
33
+ credentials: 'include',
34
+ headers: { 'content-type': 'application/json' },
35
+ body: JSON.stringify(key ? { ...body, key } : body),
36
+ })
37
+ return key ?? response.headers.get('umb-generated-resource') ?? undefined
38
+ } catch {
39
+ // Kept in this browser regardless; another will start from its own.
40
+ return key
41
+ }
42
+ }
43
+
44
+ export const onInit = (host) => {
45
+ new UmbContextConsumerController(host, UMB_THEME_CONTEXT, async (context) => {
46
+ if (!context) return
47
+ let current
48
+ let settled = false
49
+ let key
50
+ let saved
51
+ context.theme.subscribe((alias) => {
52
+ current = alias
53
+ // The shell's early stylesheet stood in until the context took over;
54
+ // once the choice differs from it, it would only fight the new one.
55
+ const early = document.getElementById(EARLY)
56
+ if (early && early.dataset.theme !== (alias || 'umb-light-theme')) early.remove()
57
+ if (!settled || !alias || alias === saved) return
58
+ saved = alias
59
+ save(alias, key).then((written) => {
60
+ key = written
61
+ })
62
+ })
63
+ const found = await readSaved()
64
+ key = found?.key
65
+ saved = found?.value ?? current
66
+ if (found?.value && found.value !== current) context.setThemeByAlias(found.value)
67
+ settled = true
68
+ })
69
+ }
@@ -13,8 +13,11 @@
13
13
  import { PartialViewService, TemplateService } from '@umbraco-cms/backoffice/external/backend-api'
14
14
  import { toTsxSnippet } from './tsx-snippets.js'
15
15
  import {
16
+ fileBeingCreated,
17
+ folderOf,
16
18
  importFor,
17
19
  memberNotes,
20
+ modelExtension,
18
21
  PERSONALISED_PART_DIALOG,
19
22
  partInsert,
20
23
  personalisedPartInsert,
@@ -191,6 +194,7 @@ function viewEditor() {
191
194
  language: 'typescript',
192
195
  async prepare() {
193
196
  configured = await configureTsx()
197
+ file = await openFile()
194
198
  },
195
199
  created(editor) {
196
200
  const { monaco, ok } = configured
@@ -205,18 +209,15 @@ function viewEditor() {
205
209
  // monaco names the model it creates `inmemory://model/1`, and a name with no
206
210
  // `.tsx` on it is a file TypeScript refuses to read JSX in: every tag in the
207
211
  // view would be a syntax error. So the model is replaced by one named as the
208
- // file it is.
212
+ // file it is, in its own folder, so that its relative imports resolve.
209
213
  model = monaco.editor.createModel(
210
214
  created.getValue(),
211
215
  'typescript',
212
- monaco.Uri.parse(`${COMPONENTS}/view-${++opened}.tsx`),
216
+ monaco.Uri.parse(`${COMPONENTS}${folderOf(file)}/view-${++opened}${modelExtension(file)}`),
213
217
  )
214
218
  editor.setModel(model)
215
219
  created.dispose()
216
220
  editor.onDidDispose(() => model.dispose())
217
- openFile().then((path) => {
218
- file = path
219
- })
220
221
  // Story 264: a file that shows the signed-in member says what that does to sharing.
221
222
  const note = () =>
222
223
  monaco.editor.setModelMarkers(
@@ -260,6 +261,8 @@ function viewEditor() {
260
261
 
261
262
  /** The view open in the editor, as a path under `components/`, from the address. */
262
263
  async function openFile() {
264
+ const creating = fileBeingCreated(location.pathname)
265
+ if (creating) return creating
263
266
  const partial = /\/workspace\/partial-view\/edit\/([^/?#]+)/.exec(location.pathname)
264
267
  if (partial) return decodeURIComponent(partial[1]).replace('%dot%', '.')
265
268
  const template = /\/workspace\/template\/edit\/([0-9a-f-]{36})/i.exec(location.pathname)