@architecture-model/editable-metadata 0.1.0 → 0.2.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/Editor.jsx ADDED
@@ -0,0 +1,148 @@
1
+ import * as Popover from '@radix-ui/react-popover'
2
+ import * as Switch from '@radix-ui/react-switch'
3
+ import { Command } from 'cmdk'
4
+ import { useRef, useState } from 'react'
5
+ import './editor.css'
6
+
7
+ const post = async (fqn, key, value) => {
8
+ const response = await fetch('/__model/metadata', { method: 'POST', body: JSON.stringify({ fqn, key, value }) })
9
+ if (!response.ok) throw new Error(await response.text())
10
+ }
11
+
12
+ const listOf = (value) => [value].flat().filter(Boolean)
13
+ const same = (a, b) => a.length === b.length && a.every((value) => b.includes(value))
14
+
15
+ function Options({ type, options, chosen, onChoose, onClear }) {
16
+ const [query, setQuery] = useState('')
17
+ const typed = query.trim()
18
+
19
+ return (
20
+ <Command className="em-command" loop>
21
+ <Command.Input
22
+ className="em-input"
23
+ value={query}
24
+ onValueChange={setQuery}
25
+ placeholder={type === 'text' ? 'Search or add a value…' : 'Search…'}
26
+ />
27
+ <Command.List className="em-list">
28
+ <Command.Empty className="em-empty">No options</Command.Empty>
29
+ {options.map((option) => (
30
+ <Command.Item key={option} value={option} className="em-item" onSelect={() => onChoose(option)}>
31
+ <span className="em-check">{chosen.includes(option) ? '✓' : ''}</span>
32
+ {option}
33
+ </Command.Item>
34
+ ))}
35
+ {type === 'text' && typed && !options.includes(typed) && (
36
+ <Command.Item value={typed} className="em-item" onSelect={() => (setQuery(''), onChoose(typed))}>
37
+ <span className="em-check">+</span>
38
+ Add “{typed}”
39
+ </Command.Item>
40
+ )}
41
+ </Command.List>
42
+ {type !== 'multiselect' && chosen.length > 0 && (
43
+ <button type="button" className="em-item em-muted em-clear" onClick={onClear}>
44
+ <span className="em-check" />
45
+ Clear
46
+ </button>
47
+ )}
48
+ </Command>
49
+ )
50
+ }
51
+
52
+ export default function Editor({ fqn, name, type, values: initial, options: listed }) {
53
+ const [values, setValues] = useState(initial)
54
+ const [open, setOpen] = useState(false)
55
+ const [draft, setDraft] = useState(initial)
56
+ const [error, setError] = useState('')
57
+ const cancelled = useRef(false)
58
+ const options = [...new Set([...listed, ...draft])]
59
+ const listedType = ['select', 'multiselect', 'text'].includes(type)
60
+
61
+ const save = (value) => {
62
+ setOpen(false)
63
+ const next = listOf(value)
64
+ if (same(next, values)) return
65
+ const previous = values
66
+ setValues(next)
67
+ setError('')
68
+ post(fqn, name, value).catch((failure) => {
69
+ setValues(previous)
70
+ setError(failure.message)
71
+ })
72
+ }
73
+
74
+ // A multiselect and the plain inputs keep a draft and save it on close, unless Escape closed them.
75
+ // A multiselect can't save per toggle because every save reloads the page.
76
+ const onOpenChange = (next) => {
77
+ if (next) {
78
+ cancelled.current = false
79
+ setDraft(values)
80
+ return setOpen(true)
81
+ }
82
+ if (!cancelled.current && (type === 'multiselect' || !listedType)) return save(type === 'multiselect' ? draft : draft[0] ?? '')
83
+ setOpen(false)
84
+ }
85
+ const onChoose = (option) => {
86
+ if (type !== 'multiselect') return save(option)
87
+ setDraft(draft.includes(option) ? draft.filter((value) => value !== option) : [...draft, option])
88
+ }
89
+
90
+ const label = `${name}: ${values.join(', ') || 'not set'}`
91
+ const problem = error && (
92
+ <span className="em-error" role="alert" title={error}>
93
+ {' '}
94
+ not saved
95
+ </span>
96
+ )
97
+
98
+ if (type === 'boolean') {
99
+ return (
100
+ <>
101
+ <Switch.Root
102
+ className="em-switch"
103
+ checked={values[0] === 'true'}
104
+ onCheckedChange={(checked) => save(String(checked))}
105
+ aria-label={name}
106
+ >
107
+ <Switch.Thumb className="em-thumb" />
108
+ </Switch.Root>
109
+ {problem}
110
+ </>
111
+ )
112
+ }
113
+
114
+ return (
115
+ <>
116
+ <Popover.Root open={open} onOpenChange={onOpenChange}>
117
+ <Popover.Trigger className="em-value" aria-label={`Edit ${label}`}>
118
+ {values.join(', ') || '—'}
119
+ </Popover.Trigger>
120
+ <Popover.Portal>
121
+ <Popover.Content
122
+ className="em-popover"
123
+ align="start"
124
+ sideOffset={6}
125
+ onEscapeKeyDown={() => (cancelled.current = true)}
126
+ >
127
+ {listedType ? (
128
+ <Options type={type} options={options} chosen={draft} onChoose={onChoose} onClear={() => save('')} />
129
+ ) : (
130
+ <div className="em-command">
131
+ <input
132
+ className="em-input"
133
+ type={type}
134
+ value={draft[0] ?? ''}
135
+ onChange={(event) => setDraft([event.target.value])}
136
+ onKeyDown={(event) => event.key === 'Enter' && (event.preventDefault(), save(draft[0]?.trim() ?? ''))}
137
+ autoFocus
138
+ />
139
+ <p className="em-hint">Enter or a click outside saves. Escape cancels. Empty removes the key.</p>
140
+ </div>
141
+ )}
142
+ </Popover.Content>
143
+ </Popover.Portal>
144
+ </Popover.Root>
145
+ {problem}
146
+ </>
147
+ )
148
+ }
package/LICENSE ADDED
@@ -0,0 +1,7 @@
1
+ Copyright 2020 Igor S. Morozov <igor@morozov.is>
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
+
5
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
+
7
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/Metadata.astro CHANGED
@@ -1,6 +1,7 @@
1
1
  ---
2
2
  import { existsSync, readFileSync } from 'node:fs'
3
3
  import config from 'virtual:editable-metadata/config'
4
+ import Editor from './Editor.jsx'
4
5
  import { model } from './model.js'
5
6
 
6
7
  interface Props {
@@ -27,131 +28,10 @@ const text = field.type === 'boolean' && values.length ? (values[0] === 'true' ?
27
28
 
28
29
  {
29
30
  import.meta.env.DEV ? (
30
- <span
31
- class="model-metadata not-content"
32
- tabindex="0"
33
- data-fqn={of}
34
- data-key={name}
35
- data-type={field.type}
36
- data-values={JSON.stringify(values)}
37
- data-options={JSON.stringify(options)}
38
- >{text}</span>
31
+ <Editor client:load fqn={of} name={name} type={field.type} values={values} options={options} />
39
32
  ) : field.type === 'url' && text ? (
40
33
  <a href={text}>{text}</a>
41
34
  ) : (
42
35
  text
43
36
  )
44
37
  }
45
-
46
- <style is:global>
47
- .model-metadata {
48
- border-bottom: 1px dashed currentColor;
49
- cursor: pointer;
50
- }
51
- .model-metadata:empty::before {
52
- content: '—';
53
- }
54
- .model-metadata.editing {
55
- border-bottom: none;
56
- cursor: auto;
57
- }
58
- .model-metadata label {
59
- margin-inline-end: 0.75em;
60
- }
61
- </style>
62
-
63
- <script>
64
- if (import.meta.env.DEV) {
65
- const create = <K extends keyof HTMLElementTagNameMap>(tag: K, props: Partial<HTMLElementTagNameMap[K]> = {}) =>
66
- Object.assign(document.createElement(tag), props)
67
-
68
- const edit = (el: HTMLElement) => {
69
- const type = el.dataset.type!
70
- const values: string[] = JSON.parse(el.dataset.values!)
71
- const options: string[] = JSON.parse(el.dataset.options!)
72
- const display = el.textContent
73
- const controls: HTMLElement[] = []
74
- let read: () => string | string[]
75
-
76
- if (type === 'multiselect') {
77
- const boxes = options.map((option) =>
78
- create('input', { type: 'checkbox', value: option, checked: values.includes(option) }),
79
- )
80
- for (const box of boxes) {
81
- const label = create('label')
82
- label.append(box, ` ${box.value}`)
83
- controls.push(label)
84
- }
85
- read = () => boxes.filter((box) => box.checked).map((box) => box.value)
86
- } else if (type === 'select') {
87
- const select = create('select')
88
- for (const option of ['', ...options]) select.append(create('option', { value: option, textContent: option }))
89
- select.value = values[0] ?? ''
90
- controls.push(select)
91
- read = () => select.value
92
- } else if (type === 'boolean') {
93
- const box = create('input', { type: 'checkbox', checked: values[0] === 'true' })
94
- controls.push(box)
95
- read = () => String(box.checked)
96
- } else {
97
- const input = create('input', { type, value: values[0] ?? '' })
98
- controls.push(input)
99
- if (type === 'text') {
100
- const list = create('datalist', { id: `model-metadata-${el.dataset.key}` })
101
- for (const option of options) list.append(create('option', { value: option }))
102
- input.setAttribute('list', list.id)
103
- controls.push(list)
104
- }
105
- read = () => input.value.trim()
106
- }
107
-
108
- let dirty = false
109
- let closed = false
110
- // Checkboxes and labels don't reliably take focus on click, so leaving is detected by where the pointer goes.
111
- const outside = (event: Event) => el.contains(event.target as Node) || close(true)
112
- const close = async (save: boolean) => {
113
- if (closed) return
114
- closed = true
115
- document.removeEventListener('pointerdown', outside)
116
- const value = read()
117
- el.classList.remove('editing')
118
- el.textContent = display
119
- if (!save || !dirty) return
120
- const response = await fetch('/__model/metadata', {
121
- method: 'POST',
122
- body: JSON.stringify({ fqn: el.dataset.fqn, key: el.dataset.key, value }),
123
- })
124
- // On success the dev server sees the model change and reloads the page with the new value.
125
- if (response.ok) el.textContent = [value].flat().join(', ')
126
- else console.error(await response.text())
127
- }
128
-
129
- el.classList.add('editing')
130
- el.replaceChildren(...controls)
131
- el.querySelector<HTMLElement>('input, select')!.focus()
132
- el.oninput = () => (dirty = true)
133
- el.onchange = () => {
134
- dirty = true
135
- if (type === 'select' || type === 'boolean') close(true)
136
- }
137
- el.onkeydown = (event) => {
138
- if (event.key === 'Enter') close(true)
139
- if (event.key === 'Escape') close(false)
140
- }
141
- el.onfocusout = (event) => {
142
- const next = event.relatedTarget as Node | null
143
- if (next && !el.contains(next)) close(true)
144
- }
145
- document.addEventListener('pointerdown', outside)
146
- }
147
-
148
- const start = (event: Event) => {
149
- const el = (event.target as HTMLElement).closest<HTMLElement>('.model-metadata:not(.editing)')
150
- if (!el || (event instanceof KeyboardEvent && event.key !== 'Enter')) return
151
- event.preventDefault()
152
- edit(el)
153
- }
154
- document.addEventListener('click', start)
155
- document.addEventListener('keydown', start)
156
- }
157
- </script>
package/NoEditor.jsx ADDED
@@ -0,0 +1,3 @@
1
+ export default function NoEditor() {
2
+ return null
3
+ }
package/README.md CHANGED
@@ -13,7 +13,7 @@ npx astro add @architecture-model/editable-metadata
13
13
  or by hand:
14
14
 
15
15
  ```bash
16
- npm install @architecture-model/editable-metadata
16
+ npm install @architecture-model/editable-metadata @astrojs/react react react-dom
17
17
  ```
18
18
 
19
19
  ```js
@@ -47,7 +47,9 @@ Owner: <Metadata of="system" name="owner" />
47
47
 
48
48
  `of` is the element's fully qualified name, `name` is the metadata key. Keep the component on the same line as its label.
49
49
 
50
- Run `npm run dev` and click the value to edit it. Enter or a click elsewhere saves, Escape cancels, and an empty value removes the key from the model.
50
+ Run `npm run dev` and click the value to edit it. A select saves the option you choose, text saves the value you choose or add, and a multiselect, number, date or url saves when its editor closes. Escape closes without saving, and Clear or an empty value removes the key from the model.
51
+
52
+ The editors are React components built on [Radix](https://www.radix-ui.com/) and [cmdk](https://cmdk.paco.me/). The addon adds Astro's React integration if the site doesn't have it, and the built site contains none of the editor code.
51
53
 
52
54
  ## Field types
53
55
 
@@ -63,11 +65,11 @@ Without configuration every key is text. To give keys other types, create `model
63
65
 
64
66
  | Type | Editor | Stored in the model as |
65
67
  | --- | --- | --- |
66
- | `text` | text input that suggests values already used for the key | string |
68
+ | `text` | searchable list of the values already used for the key, and adds what you type | string |
67
69
  | `number`, `date`, `url` | the browser's input for that type | string |
68
- | `boolean` | checkbox | `'true'` or `'false'`, shown as Yes or No |
69
- | `select` | dropdown | string |
70
- | `multiselect` | a checkbox per option | list of strings |
70
+ | `boolean` | switch | `'true'` or `'false'`, shown as Yes or No |
71
+ | `select` | searchable list of the options | string |
72
+ | `multiselect` | searchable list of the options, several can be checked | list of strings |
71
73
 
72
74
  The options of `select` and `multiselect` are the ones listed plus every value already in use in the model. A `url` is a link in the built site.
73
75
 
package/editor.css ADDED
@@ -0,0 +1,131 @@
1
+ .em-value {
2
+ all: unset;
3
+ cursor: pointer;
4
+ border-bottom: 1px dashed currentColor;
5
+ }
6
+ .em-value:focus-visible {
7
+ outline: 2px solid var(--sl-color-accent, Highlight);
8
+ outline-offset: 2px;
9
+ border-radius: 2px;
10
+ }
11
+
12
+ .em-popover {
13
+ --em-bg: var(--sl-color-bg, Canvas);
14
+ --em-border: var(--sl-color-hairline-light, #d4d4d8);
15
+ --em-hover: var(--sl-color-gray-6, #f4f4f5);
16
+ --em-muted: var(--sl-color-gray-3, #71717a);
17
+ z-index: 100;
18
+ min-width: 14rem;
19
+ max-width: 20rem;
20
+ padding: 0.25rem;
21
+ border: 1px solid var(--em-border);
22
+ border-radius: 0.5rem;
23
+ background: var(--em-bg);
24
+ color: var(--sl-color-text, CanvasText);
25
+ box-shadow: 0 10px 30px -10px rgb(0 0 0 / 0.25);
26
+ font-family: var(--sl-font, system-ui, sans-serif);
27
+ font-size: var(--sl-text-sm, 0.875rem);
28
+ line-height: 1.4;
29
+ }
30
+
31
+ .em-command {
32
+ display: flex;
33
+ flex-direction: column;
34
+ margin: 0;
35
+ }
36
+
37
+ .em-input {
38
+ font: inherit;
39
+ color: inherit;
40
+ background: transparent;
41
+ border: none;
42
+ border-bottom: 1px solid var(--em-border);
43
+ padding: 0.5rem 0.5rem 0.6rem;
44
+ outline: none;
45
+ }
46
+ .em-input::placeholder {
47
+ color: var(--em-muted);
48
+ }
49
+
50
+ .em-list {
51
+ max-height: 16rem;
52
+ overflow-y: auto;
53
+ padding-top: 0.25rem;
54
+ }
55
+
56
+ .em-item {
57
+ display: flex;
58
+ align-items: center;
59
+ gap: 0.5rem;
60
+ padding: 0.375rem 0.5rem;
61
+ border-radius: 0.25rem;
62
+ cursor: pointer;
63
+ user-select: none;
64
+ }
65
+ .em-item[data-selected='true'],
66
+ .em-clear:hover,
67
+ .em-clear:focus-visible {
68
+ background: var(--em-hover);
69
+ }
70
+ .em-clear {
71
+ all: unset;
72
+ display: flex;
73
+ align-items: center;
74
+ gap: 0.5rem;
75
+ margin-top: 0.25rem;
76
+ padding: 0.375rem 0.5rem;
77
+ border-top: 1px solid var(--em-border);
78
+ border-radius: 0 0 0.25rem 0.25rem;
79
+ cursor: pointer;
80
+ }
81
+ .em-error {
82
+ color: var(--sl-color-red, #dc2626);
83
+ font-size: 0.85em;
84
+ }
85
+ .em-muted,
86
+ .em-empty,
87
+ .em-hint {
88
+ color: var(--em-muted);
89
+ }
90
+ .em-empty,
91
+ .em-hint {
92
+ margin: 0;
93
+ padding: 0.5rem;
94
+ }
95
+
96
+ .em-check {
97
+ width: 1rem;
98
+ text-align: center;
99
+ color: var(--sl-color-accent, currentColor);
100
+ }
101
+
102
+ .em-switch {
103
+ all: unset;
104
+ position: relative;
105
+ display: inline-block;
106
+ vertical-align: middle;
107
+ width: 2.25rem;
108
+ height: 1.25rem;
109
+ border-radius: 999px;
110
+ background: var(--sl-color-gray-5, #d4d4d8);
111
+ cursor: pointer;
112
+ }
113
+ .em-switch[data-state='checked'] {
114
+ background: var(--sl-color-accent, #2563eb);
115
+ }
116
+ .em-switch:focus-visible {
117
+ outline: 2px solid var(--sl-color-accent, Highlight);
118
+ outline-offset: 2px;
119
+ }
120
+ .em-thumb {
121
+ display: block;
122
+ width: 1rem;
123
+ height: 1rem;
124
+ margin: 0.125rem;
125
+ border-radius: 999px;
126
+ background: white;
127
+ transition: transform 100ms;
128
+ }
129
+ .em-thumb[data-state='checked'] {
130
+ transform: translateX(1rem);
131
+ }
package/index.js CHANGED
@@ -1,18 +1,34 @@
1
- import { resolve } from 'node:path'
1
+ import react from '@astrojs/react'
2
+ import { dirname, resolve } from 'node:path'
2
3
  import { fileURLToPath } from 'node:url'
3
4
  import { editor } from './editor.js'
4
5
 
5
6
  const name = '@architecture-model/editable-metadata'
6
7
  const virtual = 'virtual:editable-metadata/config'
8
+ const here = dirname(fileURLToPath(import.meta.url))
9
+ const editorFile = resolve(here, 'Editor.jsx')
10
+
11
+ // The editor only runs in the dev server, so the build gets an empty component instead of Radix and cmdk.
12
+ const withoutEditor = {
13
+ name: 'editable-metadata-no-editor',
14
+ enforce: 'pre',
15
+ resolveId: (id, importer) => {
16
+ const path = id.split('?')[0]
17
+ const absolute = path.startsWith('.') && importer ? resolve(dirname(importer.split('?')[0]), path) : path
18
+ return absolute === editorFile ? resolve(here, 'NoEditor.jsx') : undefined
19
+ },
20
+ }
7
21
 
8
22
  export default function editableMetadata({ model = 'model', fields = 'model/metadata.json' } = {}) {
9
23
  return {
10
24
  name,
11
25
  hooks: {
12
- 'astro:config:setup': ({ config, updateConfig }) => {
26
+ 'astro:config:setup': ({ config, command, updateConfig }) => {
13
27
  const root = fileURLToPath(config.root)
14
28
  const paths = { modelDir: resolve(root, model), fieldsFile: resolve(root, fields) }
29
+ const hasReact = config.integrations.some((integration) => integration.name === '@astrojs/react')
15
30
  updateConfig({
31
+ integrations: hasReact ? [] : [react()],
16
32
  vite: {
17
33
  ssr: { noExternal: [name] },
18
34
  plugins: [
@@ -22,6 +38,7 @@ export default function editableMetadata({ model = 'model', fields = 'model/meta
22
38
  load: (id) => (id === `\0${virtual}` ? `export default ${JSON.stringify(paths)}` : undefined),
23
39
  },
24
40
  editor(paths),
41
+ command === 'build' && withoutEditor,
25
42
  ],
26
43
  },
27
44
  })
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@architecture-model/editable-metadata",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Show LikeC4 element metadata in Astro pages and edit it in place in the dev server",
5
5
  "keywords": [
6
6
  "astro-integration",
@@ -25,19 +25,28 @@
25
25
  "index.js",
26
26
  "editor.js",
27
27
  "model.js",
28
- "Metadata.astro"
28
+ "Metadata.astro",
29
+ "Editor.jsx",
30
+ "NoEditor.jsx",
31
+ "editor.css"
29
32
  ],
30
33
  "engines": {
31
34
  "node": ">=22.22.3"
32
35
  },
33
- "scripts": {
34
- "test": "node --test"
35
- },
36
36
  "peerDependencies": {
37
+ "@astrojs/react": ">=7",
37
38
  "astro": ">=7",
38
- "likec4": "^1.59.4"
39
+ "likec4": "^1.59.4",
40
+ "react": ">=19",
41
+ "react-dom": ">=19"
39
42
  },
40
43
  "dependencies": {
44
+ "@radix-ui/react-popover": "^1.3.1",
45
+ "@radix-ui/react-switch": "^1.4.1",
46
+ "cmdk": "^1.1.1",
41
47
  "likec4-mutator": "0.9.0"
48
+ },
49
+ "scripts": {
50
+ "test": "node --test"
42
51
  }
43
- }
52
+ }