@crombolo/backoffice-host 0.51.1 → 0.53.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.
@@ -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)
@@ -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.51.1",
5
+ "version": "0.53.2",
6
6
  "allowPublicAccess": false,
7
7
  "extensions": [
8
8
  {
@@ -21,11 +21,16 @@
21
21
  "weight": 250
22
22
  },
23
23
  {
24
- "type": "headerApp",
25
- "alias": "Crombolo.HeaderApp.Theme",
26
- "name": "Light or dark",
27
- "element": "/crombolo-plugin/theme-switch.js",
28
- "weight": 850
24
+ "type": "backofficeEntryPoint",
25
+ "alias": "Crombolo.EntryPoint.SessionGuard",
26
+ "name": "Crombolo Session Guard",
27
+ "js": "/crombolo-plugin/session-guard.js"
28
+ },
29
+ {
30
+ "type": "backofficeEntryPoint",
31
+ "alias": "Crombolo.EntryPoint.ThemeSync",
32
+ "name": "Crombolo Theme Sync",
33
+ "js": "/crombolo-plugin/theme-sync.js"
29
34
  },
30
35
  {
31
36
  "type": "entityUserPermission",
@@ -423,16 +428,22 @@
423
428
  }
424
429
  ]
425
430
  },
431
+ {
432
+ "type": "homeView",
433
+ "alias": "Crombolo.HomeView.Overview",
434
+ "name": "Crombolo Home",
435
+ "element": "/crombolo-plugin/overview-dashboard.js"
436
+ },
426
437
  {
427
438
  "type": "dashboard",
428
- "alias": "Crombolo.Dashboard.Overview",
429
- "name": "Crombolo Overview Dashboard",
430
- "element": "/crombolo-plugin/overview-dashboard.js",
439
+ "alias": "Crombolo.Dashboard.ContentHome",
440
+ "name": "Crombolo Content Home Dashboard",
441
+ "element": "/crombolo-plugin/content-home-dashboard.js",
431
442
  "weight": 20,
432
443
  "overwrites": ["Umb.Dashboard.UmbracoNews"],
433
444
  "meta": {
434
- "label": "Overview",
435
- "pathname": "overview"
445
+ "label": "Home",
446
+ "pathname": "home"
436
447
  },
437
448
  "conditions": [
438
449
  {
@@ -501,7 +512,7 @@
501
512
  "conditions": [
502
513
  {
503
514
  "alias": "Umb.Condition.SectionUserPermission",
504
- "match": "Umb.Section.Settings"
515
+ "match": "Crombolo.Section.AllSettings"
505
516
  }
506
517
  ]
507
518
  },
@@ -547,15 +558,84 @@
547
558
  "pathname": "forms"
548
559
  }
549
560
  },
561
+ {
562
+ "type": "entityAction",
563
+ "kind": "default",
564
+ "alias": "Crombolo.EntityAction.Document.EditContentType",
565
+ "name": "Edit Content Type",
566
+ "forEntityTypes": ["document"],
567
+ "api": "/crombolo-plugin/document-links.js",
568
+ "weight": 50,
569
+ "meta": {
570
+ "icon": "icon-document-dashed-line",
571
+ "label": "Edit content type",
572
+ "target": "document-type"
573
+ },
574
+ "conditions": [
575
+ {
576
+ "alias": "Umb.Condition.SectionUserPermission",
577
+ "match": "Umb.Section.Settings"
578
+ }
579
+ ]
580
+ },
581
+ {
582
+ "type": "entityAction",
583
+ "kind": "default",
584
+ "alias": "Crombolo.EntityAction.Document.EditTemplate",
585
+ "name": "Edit Template",
586
+ "forEntityTypes": ["document"],
587
+ "api": "/crombolo-plugin/document-links.js",
588
+ "weight": 49,
589
+ "meta": {
590
+ "icon": "icon-layout",
591
+ "label": "Edit template",
592
+ "target": "template"
593
+ },
594
+ "conditions": [
595
+ {
596
+ "alias": "Umb.Condition.SectionUserPermission",
597
+ "match": "Umb.Section.Settings"
598
+ }
599
+ ]
600
+ },
601
+ {
602
+ "type": "backofficeEntryPoint",
603
+ "alias": "Crombolo.EntryPoint.ContentStrip",
604
+ "name": "Crombolo Menu Under Content",
605
+ "js": "/crombolo-plugin/content-strip.js"
606
+ },
607
+ {
608
+ "type": "entityCreateOptionAction",
609
+ "alias": "Crombolo.EntityCreateOptionAction.DocumentType.Form",
610
+ "name": "Crombolo Form Create Option",
611
+ "weight": 100,
612
+ "api": "/crombolo-plugin/form-create-option.js",
613
+ "forEntityTypes": ["document-type-root", "document-type-folder"],
614
+ "meta": { "icon": "icon-autofill", "label": "Form" }
615
+ },
616
+ {
617
+ "type": "sectionSidebarApp",
618
+ "alias": "Crombolo.SectionSidebarApp.DefinitionTree",
619
+ "name": "Crombolo Forms And Workflows Tree",
620
+ "element": "/crombolo-plugin/definition-tree.js",
621
+ "weight": 100,
622
+ "conditions": [
623
+ {
624
+ "alias": "Umb.Condition.SectionAlias",
625
+ "match": "Crombolo.Section.Forms"
626
+ }
627
+ ]
628
+ },
550
629
  {
551
630
  "type": "sectionView",
552
631
  "alias": "Crombolo.SectionView.Forms.Overview",
553
632
  "name": "Crombolo Forms Overview",
554
633
  "element": "/crombolo-plugin/forms-overview.js",
555
- "weight": 100,
634
+ "weight": 200,
556
635
  "meta": {
557
636
  "label": "Forms",
558
637
  "pathname": "forms",
638
+ "noTab": true,
559
639
  "icon": "icon-notepad"
560
640
  },
561
641
  "conditions": [
@@ -570,10 +650,11 @@
570
650
  "alias": "Crombolo.SectionView.Forms.Entries",
571
651
  "name": "Crombolo Forms Entries",
572
652
  "element": "/crombolo-plugin/forms-entries.js",
573
- "weight": 200,
653
+ "weight": 100,
574
654
  "meta": {
575
655
  "label": "Entries",
576
656
  "pathname": "entries",
657
+ "noTab": true,
577
658
  "icon": "icon-inbox"
578
659
  },
579
660
  "conditions": [
@@ -640,6 +721,36 @@
640
721
  "name": "Crombolo Approvals Active Condition",
641
722
  "api": "/crombolo-plugin/approvals-active.js"
642
723
  },
724
+ {
725
+ "type": "section",
726
+ "alias": "Crombolo.Section.Structure",
727
+ "name": "Crombolo Structure Section",
728
+ "weight": 30,
729
+ "meta": {
730
+ "label": "Structure",
731
+ "pathname": "structure"
732
+ }
733
+ },
734
+ {
735
+ "type": "section",
736
+ "alias": "Crombolo.Section.Components",
737
+ "name": "Crombolo Code Section",
738
+ "weight": 29,
739
+ "meta": {
740
+ "label": "Code",
741
+ "pathname": "components"
742
+ }
743
+ },
744
+ {
745
+ "type": "section",
746
+ "alias": "Crombolo.Section.WorkflowSetup",
747
+ "name": "Crombolo Workflow setup Section",
748
+ "weight": 28,
749
+ "meta": {
750
+ "label": "Workflow setup",
751
+ "pathname": "workflow-setup"
752
+ }
753
+ },
643
754
  {
644
755
  "type": "section",
645
756
  "alias": "Crombolo.Section.Workflow",
@@ -709,18 +820,21 @@
709
820
  ]
710
821
  },
711
822
  {
712
- "type": "dashboard",
713
- "alias": "Crombolo.Dashboard.Workflows",
823
+ "type": "sectionView",
824
+ "alias": "Crombolo.SectionView.Workflows",
714
825
  "name": "Crombolo Workflow Designer",
715
826
  "element": "/crombolo-plugin/workflow-designer.js",
827
+ "weight": 50,
716
828
  "meta": {
717
829
  "label": "Workflows",
718
- "pathname": "workflows"
830
+ "pathname": "workflows",
831
+ "noTab": true,
832
+ "icon": "icon-mindmap"
719
833
  },
720
834
  "conditions": [
721
835
  {
722
836
  "alias": "Umb.Condition.SectionAlias",
723
- "match": "Umb.Section.Settings"
837
+ "match": "Crombolo.Section.Forms"
724
838
  },
725
839
  {
726
840
  "alias": "Umb.Condition.CurrentUser.IsAdmin"
@@ -127,3 +127,27 @@ export const personalisedPartInsert = {
127
127
  return chosen?.path ? personalisedPartSnippet(chosen.path) : undefined
128
128
  },
129
129
  }
130
+
131
+ /** The folder a view sits in under `components/`: `/pages`, or nothing for the top. */
132
+ export const folderOf = (file) => {
133
+ const folder = (file ?? '').replace(/^\/*/, '/').replace(/\/[^/]*$/, '')
134
+ return folder === '/' ? '' : folder
135
+ }
136
+
137
+ /** The extension a view opens with in the editor: a module's `.ts`, else a component's `.tsx`. */
138
+ export const modelExtension = (file) => (file?.endsWith('.ts') ? '.ts' : '.tsx')
139
+
140
+ /**
141
+ * The file a create page will make, as a path under `components/`, from its address.
142
+ * Its name isn't known yet, but its folder and kind are, and they are what the editor needs.
143
+ *
144
+ * @param {string} pathname
145
+ */
146
+ export function fileBeingCreated(pathname) {
147
+ const found = /\/workspace\/partial-view\/create\/parent\/[^/]+\/([^/]+)(\/module)?/.exec(
148
+ pathname,
149
+ )
150
+ if (!found) return undefined
151
+ const folder = found[1] === 'null' ? '' : decodeURIComponent(found[1]).replace(/\/$/, '')
152
+ return `${folder}/new${found[2] ? '.ts' : '.tsx'}`
153
+ }
@@ -31,11 +31,16 @@ export const finished = (skip = 0, take = 25) => call(`history?skip=${skip}&take
31
31
  export const listWorkflows = () => call('workflows')
32
32
  export const previewWorkflow = (alias, workflow) =>
33
33
  post(`workflows/${encodeURIComponent(alias)}/preview`, { workflow })
34
- export const saveWorkflow = (alias, workflow) =>
34
+ export const saveWorkflow = (alias, workflow, folder) =>
35
35
  call(`workflows/${encodeURIComponent(alias)}`, {
36
36
  method: 'PUT',
37
- body: JSON.stringify({ workflow }),
37
+ body: JSON.stringify({ workflow, folder }),
38
38
  })
39
+ /** A folder made (`POST`), renamed (`PUT`) or deleted (`DELETE`). */
40
+ export const sendWorkflowFolder = (method, body) =>
41
+ call('workflows/tree-folders', { method, body: JSON.stringify(body) })
42
+ export const moveWorkflow = (alias, folder) =>
43
+ call('workflows/tree-move', { method: 'POST', body: JSON.stringify({ alias, folder }) })
39
44
  export const deleteWorkflow = (alias) =>
40
45
  call(`workflows/${encodeURIComponent(alias)}`, { method: 'DELETE' })
41
46
  export const previewDelete = (alias) =>
@@ -13,6 +13,7 @@ import { css, html, nothing, unsafeCSS } from '@umbraco-cms/backoffice/external/
13
13
  import { UmbLitElement } from '@umbraco-cms/backoffice/lit-element'
14
14
  import { UMB_NOTIFICATION_CONTEXT } from '@umbraco-cms/backoffice/notification'
15
15
  import { approvalsChanged } from './approvals-active.js'
16
+ import { readOnlyWords } from './definition-tree-model.js'
16
17
  import {
17
18
  deleteWorkflow,
18
19
  listWorkflows,
@@ -101,6 +102,21 @@ export default class CromboloWorkflowDesignerElement extends UmbLitElement {
101
102
 
102
103
  #drag
103
104
  #notifications
105
+ /** The folder a new workflow goes in, from the tree's link. */
106
+ #folder
107
+ #query
108
+
109
+ #follow = () => {
110
+ if (!this._list || location.search === this.#query) return
111
+ this.#query = location.search
112
+ const asked = new URLSearchParams(location.search)
113
+ const named = this._list.items.find((w) => w.alias === asked.get('workflow'))
114
+ if (named) this.#edit(named)
115
+ else if (asked.has('new')) {
116
+ this.#edit(blank())
117
+ this.#folder = asked.get('new') || undefined
118
+ } else this._editing = undefined
119
+ }
104
120
 
105
121
  constructor() {
106
122
  super()
@@ -112,6 +128,14 @@ export default class CromboloWorkflowDesignerElement extends UmbLitElement {
112
128
  connectedCallback() {
113
129
  super.connectedCallback()
114
130
  this.#load()
131
+ window.addEventListener('changestate', this.#follow)
132
+ window.addEventListener('popstate', this.#follow)
133
+ }
134
+
135
+ disconnectedCallback() {
136
+ super.disconnectedCallback()
137
+ window.removeEventListener('changestate', this.#follow)
138
+ window.removeEventListener('popstate', this.#follow)
115
139
  }
116
140
 
117
141
  async #load() {
@@ -121,9 +145,11 @@ export default class CromboloWorkflowDesignerElement extends UmbLitElement {
121
145
  return
122
146
  }
123
147
  this._list = result
148
+ this.#follow()
124
149
  }
125
150
 
126
151
  #edit(workflow) {
152
+ this.#folder = undefined
127
153
  const copy = structuredClone(workflow)
128
154
  // Every stage gets the place the canvas would draw it, so dragging starts from there.
129
155
  const positions = layout(copy.stages)
@@ -271,7 +297,11 @@ export default class CromboloWorkflowDesignerElement extends UmbLitElement {
271
297
  return
272
298
  }
273
299
  }
274
- const saved = await saveWorkflow(this._originalAlias ?? this._editing.alias, this._editing)
300
+ const saved = await saveWorkflow(
301
+ this._originalAlias ?? this._editing.alias,
302
+ this._editing,
303
+ this.#folder,
304
+ )
275
305
  if (!saved.ok) {
276
306
  this._problems = saved.problems ?? [{ message: saved.message }]
277
307
  return
@@ -280,7 +310,9 @@ export default class CromboloWorkflowDesignerElement extends UmbLitElement {
280
310
  // The green toast every workspace shows on a save.
281
311
  this.#notifications?.peek('positive', { data: { message: 'Workflow saved' } })
282
312
  this._originalAlias = this._editing.alias
313
+ this.#folder = undefined
283
314
  approvalsChanged()
315
+ window.dispatchEvent(new Event('crombolo:definitions-changed'))
284
316
  await this.#load()
285
317
  }
286
318
 
@@ -305,6 +337,8 @@ export default class CromboloWorkflowDesignerElement extends UmbLitElement {
305
337
  }
306
338
  this._editing = undefined
307
339
  approvalsChanged()
340
+ window.dispatchEvent(new Event('crombolo:definitions-changed'))
341
+ if (location.search) history.replaceState(null, '', location.pathname)
308
342
  await this.#load()
309
343
  }
310
344
 
@@ -317,6 +351,11 @@ export default class CromboloWorkflowDesignerElement extends UmbLitElement {
317
351
  return this.#renderEditor()
318
352
  }
319
353
 
354
+ #readOnly() {
355
+ const words = readOnlyWords('Workflows', this._list.readOnlyBecause)
356
+ return words ? html`<p role="status">${words}</p>` : nothing
357
+ }
358
+
320
359
  #renderList() {
321
360
  const { items, editable } = this._list
322
361
  // The create button above the list, as the Created bundles view has it.
@@ -328,10 +367,10 @@ export default class CromboloWorkflowDesignerElement extends UmbLitElement {
328
367
  }
329
368
  ${this._message ? html`<uui-box><p class="message">${this._message}</p></uui-box>` : nothing}
330
369
  <uui-box headline="Workflows">
331
- ${editable ? nothing : html`<p>Workflows are kept with the site's files, which cannot be changed on this server. Change them in the repository and deploy.</p>`}
370
+ ${this.#readOnly()}
332
371
  ${
333
372
  items.length === 0
334
- ? html`<p>No workflow yet: every page publishes as soon as someone who may publish does.</p>`
373
+ ? html`<p>No workflows yet, so a page publishes as soon as someone who may publish does.</p>`
335
374
  : html`<uui-table>
336
375
  <uui-table-head>
337
376
  <uui-table-head-cell>Workflow</uui-table-head-cell>
@@ -372,6 +411,7 @@ export default class CromboloWorkflowDesignerElement extends UmbLitElement {
372
411
  this._editing = undefined
373
412
  this._message = undefined
374
413
  this._problems = undefined
414
+ if (location.search) history.replaceState(null, '', location.pathname)
375
415
  }
376
416
  const tab = (id, label, icon) => html`<uui-tab
377
417
  label=${label}
@@ -554,7 +594,7 @@ export default class CromboloWorkflowDesignerElement extends UmbLitElement {
554
594
  this.#touch()
555
595
  }
556
596
  return html`<div class="settings">
557
- ${editable ? nothing : html`<uui-box class="notice"><p>Workflows are kept with the site's files, which cannot be changed on this server.</p></uui-box>`}
597
+ ${readOnlyWords('Workflows', this._list.readOnlyBecause) ? html`<uui-box class="notice">${this.#readOnly()}</uui-box>` : nothing}
558
598
  <uui-box headline="Workflow">
559
599
  ${property(
560
600
  'Name',
package/src/paths.ts CHANGED
@@ -114,6 +114,7 @@ export function createBackOfficePaths(options: BackOfficePathOptions = {}): Back
114
114
  */
115
115
  export const SPA_ROUTES = [
116
116
  'section',
117
+ 'home',
117
118
  'preview',
118
119
  'upgrade',
119
120
  'install',
@@ -1,135 +0,0 @@
1
- /**
2
- * Light, dark or the computer's choice, from the header (story 049).
3
- *
4
- * The choice is Umbraco's theme context's — it links the stylesheet and keeps
5
- * the alias in `localStorage` for the shell's early script to apply before the
6
- * next paint. This adds the menu, and keeps the choice for the person in user
7
- * data, so it follows them to another browser.
8
- */
9
- import { css, html } from '@umbraco-cms/backoffice/external/lit'
10
- import { UmbLitElement } from '@umbraco-cms/backoffice/lit-element'
11
- import { UMB_THEME_CONTEXT } from '@umbraco-cms/backoffice/themes'
12
-
13
- /** The Management API, under the back office wherever it is mounted. */
14
- const USER_DATA = `${(document.querySelector('base')?.getAttribute('href') ?? '/crombolo/').replace(/\/$/, '')}/management/api/v1/user-data`
15
- const GROUP = 'crombolo'
16
- const IDENTIFIER = 'theme'
17
- const EARLY = 'crombolo-early-theme'
18
-
19
- const CHOICES = [
20
- { alias: 'umb-light-theme', label: 'Light', icon: 'icon-sunny' },
21
- { alias: 'Crombolo.Theme.Dark', label: 'Dark', icon: 'icon-contrast' },
22
- { alias: 'Crombolo.Theme.System', label: 'Match my system', icon: 'icon-lightbulb' },
23
- ]
24
-
25
- export default class CromboloThemeSwitchElement extends UmbLitElement {
26
- static properties = { _alias: { state: true } }
27
-
28
- #context
29
- #savedKey
30
-
31
- constructor() {
32
- super()
33
- this._alias = 'umb-light-theme'
34
- this.consumeContext(UMB_THEME_CONTEXT, (context) => {
35
- this.#context = context
36
- this.observe(context.theme, (alias) => {
37
- this._alias = alias || 'umb-light-theme'
38
- // The shell's early stylesheet stood in until the context took over;
39
- // once the choice differs from it, it would only fight the new one.
40
- const early = document.getElementById(EARLY)
41
- if (early && early.dataset.theme !== this._alias) early.remove()
42
- })
43
- this.#restore()
44
- })
45
- }
46
-
47
- /** The person's saved choice, when this browser's differs from it. */
48
- async #restore() {
49
- try {
50
- const query = new URLSearchParams({ groups: GROUP, identifiers: IDENTIFIER, take: '1' })
51
- const response = await fetch(`${USER_DATA}?${query}`, { credentials: 'include' })
52
- if (!response.ok) return
53
- const found = (await response.json()).items?.[0]
54
- if (!found) return
55
- this.#savedKey = found.key
56
- if (found.value && found.value !== this._alias) this.#context?.setThemeByAlias(found.value)
57
- } catch {
58
- // This browser's choice stands.
59
- }
60
- }
61
-
62
- async #save(alias) {
63
- const body = { group: GROUP, identifier: IDENTIFIER, value: alias }
64
- try {
65
- if (this.#savedKey) {
66
- await fetch(USER_DATA, {
67
- method: 'PUT',
68
- credentials: 'include',
69
- headers: { 'content-type': 'application/json' },
70
- body: JSON.stringify({ ...body, key: this.#savedKey }),
71
- })
72
- return
73
- }
74
- const response = await fetch(USER_DATA, {
75
- method: 'POST',
76
- credentials: 'include',
77
- headers: { 'content-type': 'application/json' },
78
- body: JSON.stringify(body),
79
- })
80
- this.#savedKey = response.headers.get('umb-generated-resource') ?? undefined
81
- } catch {
82
- // Kept in this browser regardless; another will start from its own.
83
- }
84
- }
85
-
86
- #choose(alias) {
87
- this.#context?.setThemeByAlias(alias)
88
- this.#save(alias)
89
- this.renderRoot.querySelector('#crombolo-theme-menu')?.hidePopover?.()
90
- }
91
-
92
- render() {
93
- const current = CHOICES.find((choice) => choice.alias === this._alias) ?? CHOICES[0]
94
- return html`
95
- <uui-button
96
- compact
97
- look="primary"
98
- label="Light or dark: ${current.label}"
99
- popovertarget="crombolo-theme-menu">
100
- <umb-icon name=${current.icon}></umb-icon>
101
- </uui-button>
102
- <uui-popover-container id="crombolo-theme-menu" placement="bottom-end">
103
- <umb-popover-layout>
104
- ${CHOICES.map(
105
- (choice) => html`<uui-menu-item
106
- label=${choice.label}
107
- ?active=${choice.alias === this._alias}
108
- @click-label=${() => this.#choose(choice.alias)}>
109
- <umb-icon slot="icon" name=${choice.icon}></umb-icon>
110
- </uui-menu-item>`,
111
- )}
112
- </umb-popover-layout>
113
- </uui-popover-container>
114
- `
115
- }
116
-
117
- static styles = css`
118
- uui-button {
119
- font-size: 18px;
120
- --uui-button-background-color: var(--umb-header-app-button-background-color, transparent);
121
- --uui-button-background-color-hover: var(
122
- --umb-header-app-button-background-color-hover,
123
- var(--uui-color-emphasis)
124
- );
125
- }
126
- :host {
127
- --uui-menu-item-flat-structure: 1;
128
- }
129
- umb-popover-layout {
130
- min-width: 12rem;
131
- }
132
- `
133
- }
134
-
135
- customElements.define('crombolo-theme-switch', CromboloThemeSwitchElement)