@nickpaustian/tela 0.1.2 → 0.1.3

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/README.md CHANGED
@@ -29,7 +29,7 @@ A project component with the same name as one of Tela's fails the build unless t
29
29
 
30
30
  ## Working on Tela and a project together
31
31
 
32
- A linked Tela is live in the project with no build step (outside `node_modules`, Node loads its source):
32
+ A linked Tela is live in the project with no build step: run from a checkout, the `tela` command compiles `lib/` before Vite reads it.
33
33
 
34
34
  ```sh
35
35
  cd tela && bun link
package/bin/tela.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env bun
2
- import { existsSync } from "fs"
2
+ import { existsSync, realpathSync } from "fs"
3
3
  import { createRequire } from "module"
4
- import { dirname, resolve } from "path"
4
+ import { dirname, resolve, sep } from "path"
5
5
  import { fileURLToPath } from "url"
6
6
 
7
7
  /**
@@ -96,6 +96,14 @@ async function vite(sub: "dev" | "build"): Promise<number> {
96
96
  return 1
97
97
  }
98
98
 
99
+ // Vite reads the compiled `lib/` for the entry points its config imports. An
100
+ // install ships it; a checkout (linked, or Tela itself) compiles it first,
101
+ // so a change there is live without a step to remember.
102
+ if (!realpathSync(TELA_ROOT).split(sep).includes("node_modules")) {
103
+ const built = await run(["bun", "run", "--silent", "build:lib"], TELA_ROOT, process.env)
104
+ if (built !== 0) return built
105
+ }
106
+
99
107
  const options = ["--experimental-strip-types", "--disable-warning=ExperimentalWarning"]
100
108
  const env = {
101
109
  ...process.env,
package/lib/index.js CHANGED
@@ -60,6 +60,20 @@ function imageUse(name, label, options = {}) {
60
60
  ]
61
61
  };
62
62
  }
63
+ function person(name, label, options = {}) {
64
+ return {
65
+ name,
66
+ label,
67
+ type: "block",
68
+ component: "person",
69
+ ...options.required ? { required: true } : {},
70
+ ...options.hint ? { options: { hint: options.hint } } : {},
71
+ fields: [
72
+ { name: "user", type: "reference", to: "users", label: "Person" },
73
+ { name: "name", type: "text", label: "Name", maxLength: 200 }
74
+ ]
75
+ };
76
+ }
63
77
 
64
78
  // src/config/seo.ts
65
79
  var SEO_FIELDS = {
@@ -745,6 +759,7 @@ export {
745
759
  iconFor,
746
760
  imageUse,
747
761
  initialsOf,
762
+ person,
748
763
  personName,
749
764
  slugField,
750
765
  splitBlock,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nickpaustian/tela",
3
- "version": "0.1.2",
3
+ "version": "0.1.3",
4
4
  "description": "A Git-backed headless CMS: collections of fields in TypeScript, edited in a Lightspeed admin, published as JSON commits to a content repo.",
5
5
  "license": "MIT",
6
6
  "author": "Nick Paustian",
@@ -0,0 +1,255 @@
1
+ <view>
2
+ <Field $field="props.field" $path="props.path" $controlId="'f-' + props.path">
3
+ <div class="person">
4
+ <div class="person-picked" $show="state.picked">
5
+ <span class="person-chip">
6
+ <span class="person-initials" aria-hidden="true">{{ state.initials }}</span>
7
+ <span class="person-name">{{ state.pickedName }}</span>
8
+ <span class="one-warning" $show="state.gone">No longer has an account. Choose again or type a name.</span>
9
+ </span>
10
+ <button
11
+ type="button"
12
+ class="btn btn-ghost btn-sm btn-icon"
13
+ $show="!state.readonly"
14
+ $aria-label="'Remove ' + state.pickedName"
15
+ @click="unpick"
16
+ >
17
+ <span class="icon icon-s icon-x" aria-hidden="true"></span>
18
+ </button>
19
+ </div>
20
+
21
+ <div class="person-entry" $show="!state.picked">
22
+ <input
23
+ class="input"
24
+ type="text"
25
+ role="combobox"
26
+ autocomplete="off"
27
+ aria-autocomplete="list"
28
+ $id="'f-' + props.path"
29
+ $aria-expanded="state.open ? 'true' : 'false'"
30
+ $aria-controls="'f-' + props.path + '-people'"
31
+ $aria-activedescendant="state.active >= 0 ? 'f-' + props.path + '-person-' + state.active : null"
32
+ $placeholder="state.placeholder"
33
+ $readonly="state.readonly"
34
+ $maxLength="200"
35
+ $model="state.typed"
36
+ @input="typed"
37
+ @keydown="key"
38
+ @blur="blurred"
39
+ />
40
+ <ul
41
+ class="menu person-options"
42
+ role="listbox"
43
+ $id="'f-' + props.path + '-people'"
44
+ $show="state.open && state.results.length > 0"
45
+ >
46
+ <li
47
+ $for="one in state.results"
48
+ $key="one.id"
49
+ role="option"
50
+ class="menu-item"
51
+ $class="{ active: one.index === state.active }"
52
+ $id="'f-' + props.path + '-person-' + one.index"
53
+ $aria-selected="one.index === state.active ? 'true' : 'false'"
54
+ @pointerdown="choose($event, one)"
55
+ >{{ one.name }}</li>
56
+ </ul>
57
+ <p class="person-note" $show="state.typed && !state.open">Not one of the CMS's people, so it shows as typed.</p>
58
+ </div>
59
+ </div>
60
+ </Field>
61
+ </view>
62
+
63
+ <logic lang="ts">
64
+ import { defineProps, onMounted, reactive, shared } from '@lightspeed-js/core'
65
+ import { api } from '../api.ts'
66
+ import { initialsOf } from '../content/person.ts'
67
+
68
+ /**
69
+ * Somebody named on an entry: one of the CMS's people, or a name as typed.
70
+ *
71
+ * One box. Typing asks `/api/people` for matching names - ids and names only,
72
+ * which any signed-in account may ask for - and picking one stores the
73
+ * account. Anything not picked is kept as typed. The two are never both set,
74
+ * so a site reads the account's name where there is one and the words where
75
+ * there is not.
76
+ */
77
+ const props = defineProps({
78
+ field: { default: {} },
79
+ path: { default: '' },
80
+ })
81
+
82
+ const user = shared('entry:value:' + props.path + '.user')
83
+ const name = shared('entry:value:' + props.path + '.name')
84
+ const readonly = shared('entry:readonly')
85
+
86
+ const state = reactive({
87
+ picked: false,
88
+ pickedName: '',
89
+ initials: '',
90
+ gone: false,
91
+ typed: '',
92
+ results: [] as { id: string; name: string; index: number }[],
93
+ open: false,
94
+ active: -1,
95
+ readonly: false,
96
+ placeholder: props.field.options?.placeholder || 'Start typing a name',
97
+ })
98
+
99
+ let asked = ''
100
+ let timer: ReturnType<typeof setTimeout> | undefined
101
+
102
+ /** What the cells hold, shown: a picked account by its name, or the words. */
103
+ async function show() {
104
+ state.readonly = Boolean(props.field.readOnly || readonly.value)
105
+ const id = typeof user.value === 'string' ? user.value : ''
106
+ if (!id) {
107
+ state.picked = false
108
+ state.typed = typeof name.value === 'string' ? name.value : ''
109
+ return
110
+ }
111
+ state.picked = true
112
+ if (id === asked) return
113
+ asked = id
114
+ const result = await api.get<{ people: { id: string; name: string }[] }>('/api/people?ids=' + encodeURIComponent(id))
115
+ if (asked !== id) return
116
+ const found = result.ok ? result.data.people[0] : undefined
117
+ state.gone = !found
118
+ state.pickedName = found?.name ?? 'Somebody'
119
+ state.initials = found ? initialsOf({ name: found.name }) : '?'
120
+ }
121
+
122
+ function typed() {
123
+ user.value = undefined
124
+ name.value = state.typed.trim() ? state.typed : undefined
125
+ clearTimeout(timer)
126
+ const words = state.typed.trim()
127
+ if (!words) {
128
+ close()
129
+ return
130
+ }
131
+ timer = setTimeout(() => search(words), 150)
132
+ }
133
+
134
+ async function search(words: string) {
135
+ const result = await api.get<{ people: { id: string; name: string }[] }>(
136
+ '/api/people?limit=8&q=' + encodeURIComponent(words),
137
+ )
138
+ if (state.typed.trim() !== words) return
139
+ state.results = result.ok ? result.data.people.map((one, index) => ({ ...one, index })) : []
140
+ state.active = -1
141
+ state.open = state.results.length > 0
142
+ }
143
+
144
+ function pick(one: { id: string; name: string }) {
145
+ asked = one.id
146
+ user.value = one.id
147
+ name.value = undefined
148
+ state.picked = true
149
+ state.gone = false
150
+ state.pickedName = one.name
151
+ state.initials = initialsOf({ name: one.name })
152
+ state.typed = ''
153
+ close()
154
+ }
155
+
156
+ /** Before the input loses focus, or the click would land on nothing. */
157
+ function choose(event: PointerEvent, one: { id: string; name: string }) {
158
+ event.preventDefault()
159
+ pick(one)
160
+ }
161
+
162
+ function unpick() {
163
+ asked = ''
164
+ user.value = undefined
165
+ state.picked = false
166
+ state.pickedName = ''
167
+ state.typed = ''
168
+ requestAnimationFrame(() => document.getElementById('f-' + props.path)?.focus())
169
+ }
170
+
171
+ function key(event: KeyboardEvent) {
172
+ if (!state.open) return
173
+ const last = state.results.length - 1
174
+ if (event.key === 'ArrowDown') {
175
+ event.preventDefault()
176
+ state.active = state.active >= last ? 0 : state.active + 1
177
+ } else if (event.key === 'ArrowUp') {
178
+ event.preventDefault()
179
+ state.active = state.active <= 0 ? last : state.active - 1
180
+ } else if (event.key === 'Enter' && state.active >= 0) {
181
+ event.preventDefault()
182
+ pick(state.results[state.active]!)
183
+ } else if (event.key === 'Escape') {
184
+ event.preventDefault()
185
+ close()
186
+ }
187
+ }
188
+
189
+ function blurred() {
190
+ close()
191
+ }
192
+
193
+ function close() {
194
+ state.open = false
195
+ state.active = -1
196
+ }
197
+
198
+ onMounted(() => {
199
+ user.subscribe(show)
200
+ name.subscribe(() => {
201
+ if (!state.picked && name.value !== state.typed) show()
202
+ })
203
+ readonly.subscribe(show)
204
+ show()
205
+ })
206
+ </logic>
207
+
208
+ <style>
209
+ .person {
210
+ position: relative;
211
+ }
212
+
213
+ .person-picked {
214
+ display: flex;
215
+ gap: 0.5rem;
216
+ align-items: center;
217
+ }
218
+
219
+ .person-chip {
220
+ display: inline-flex;
221
+ flex-wrap: wrap;
222
+ gap: 0.5rem;
223
+ align-items: center;
224
+ }
225
+
226
+ .person-initials {
227
+ display: inline-grid;
228
+ place-items: center;
229
+ inline-size: 1.75rem;
230
+ block-size: 1.75rem;
231
+ border-radius: 50%;
232
+ background: var(--surface-2);
233
+ font-size: 0.75rem;
234
+ font-weight: 600;
235
+ }
236
+
237
+ .person-options {
238
+ position: absolute;
239
+ inset-inline: 0;
240
+ z-index: 10;
241
+ margin: 0.25rem 0 0;
242
+ padding: 0.25rem;
243
+ list-style: none;
244
+ }
245
+
246
+ .person-options .active {
247
+ background: var(--surface-hover);
248
+ }
249
+
250
+ .person-note {
251
+ margin: 0.25rem 0 0;
252
+ color: var(--text-2);
253
+ font-size: 0.8125rem;
254
+ }
255
+ </style>
@@ -101,3 +101,33 @@ export function imageUse(
101
101
  ],
102
102
  }
103
103
  }
104
+
105
+ /**
106
+ * Somebody named on an entry: one of the CMS's people, or a name typed in.
107
+ *
108
+ * A byline is usually a colleague, who has an account, and sometimes not - a
109
+ * guest writer, a team, "Margaret Chen and Dev Rao". One input offers both:
110
+ * typing suggests people by name, and anything not picked is kept as typed.
111
+ *
112
+ * Stored as `{ user }` or `{ name }`, never both. `user` is a reference to an
113
+ * account and publishes as `{ name }` only, so a site reads
114
+ * `value.user?.name ?? value.name`.
115
+ */
116
+ export function person(
117
+ name: string,
118
+ label: string,
119
+ options: { hint?: string; required?: boolean } = {},
120
+ ): Field {
121
+ return {
122
+ name,
123
+ label,
124
+ type: "block",
125
+ component: "person",
126
+ ...(options.required ? { required: true } : {}),
127
+ ...(options.hint ? { options: { hint: options.hint } } : {}),
128
+ fields: [
129
+ { name: "user", type: "reference", to: "users", label: "Person" },
130
+ { name: "name", type: "text", label: "Name", maxLength: 200 },
131
+ ],
132
+ }
133
+ }
@@ -30,7 +30,7 @@ export interface Entry {
30
30
  const MAX_LIMIT = 100
31
31
 
32
32
  const ENTRY_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
33
- const isEntryId = (id: string) => ENTRY_ID.test(id)
33
+ export const isEntryId = (id: string) => ENTRY_ID.test(id)
34
34
 
35
35
  export async function listEntries(
36
36
  collection: Collection,
@@ -12,6 +12,17 @@ export function personName(person: Named): string {
12
12
  return full || text(person?.name) || text(person?.email)
13
13
  }
14
14
 
15
+ /**
16
+ * What to call somebody in public: their name, or nothing.
17
+ *
18
+ * Unlike `personName`, never their address. This is what leaves the CMS - a
19
+ * byline on a published page, a name offered to an editor who may not read
20
+ * accounts - and an address is not something either should be given.
21
+ */
22
+ export function publicName(person: Named): string {
23
+ return [text(person?.firstName), text(person?.lastName)].filter(Boolean).join(" ") || text(person?.name)
24
+ }
25
+
15
26
  /** Two letters to stand for somebody where there is no room for the name. */
16
27
  export function initialsOf(person: Named): string {
17
28
  const first = text(person?.firstName)
@@ -5,6 +5,7 @@ import { findCollection } from "./collections.ts"
5
5
  import { summarise } from "./summary.ts"
6
6
  import { linkedEntries, withLinkSlugs } from "./links.ts"
7
7
  import { media } from "../media/index.ts"
8
+ import { publicName } from "./person.ts"
8
9
  import type { MediaStore, StoredInfo } from "../media/store.ts"
9
10
 
10
11
  /**
@@ -265,6 +266,22 @@ export async function publishedReferences(
265
266
  if (row.live && row.data?.slug) resolved.set(String(row.id), row.data.slug)
266
267
  }
267
268
 
269
+ // Accounts, which have their own table. One is somebody to name - a byline -
270
+ // so it publishes as its name and nothing else; one without a name is left
271
+ // out, like a reference to something unpublished.
272
+ const found = new Set(rows.map((row: any) => String(row.id)))
273
+ const rest = ids.filter((id) => !found.has(id))
274
+ if (rest.length) {
275
+ const people = await sql`
276
+ select id, data from users
277
+ where id = any(string_to_array(${rest.join(",")}, ',')::uuid[])
278
+ `
279
+ for (const person of people) {
280
+ const name = publicName(person.data)
281
+ if (name) resolved.set(String(person.id), { name })
282
+ }
283
+ }
284
+
268
285
  return resolved
269
286
  }
270
287
 
@@ -3,6 +3,7 @@ import { narrowing } from "./filters.ts"
3
3
  import { sql } from "../db/client.ts"
4
4
  import type { Collection } from "../config/types.ts"
5
5
  import type { Entry, EntrySummary } from "./entries.ts"
6
+ import { publicName } from "./person.ts"
6
7
 
7
8
  /**
8
9
  * Users, stored where authentication needs them.
@@ -121,6 +122,37 @@ export async function listUsers(
121
122
  }
122
123
  }
123
124
 
125
+ /**
126
+ * Accounts as somebody to name: an id and a name, nothing else.
127
+ *
128
+ * For the person field, where an editor picks who wrote something. Editors
129
+ * may not read accounts - they are how permissions are held - so this answers
130
+ * any signed-in account but says only what a byline would. An account without
131
+ * a name is left out: there is nothing it could be called but its address.
132
+ */
133
+ export async function peopleNamed({
134
+ search = "",
135
+ ids = [],
136
+ limit = 20,
137
+ }: { search?: string; ids?: string[]; limit?: number } = {}): Promise<{ id: string; name: string }[]> {
138
+ // Every word typed somewhere in the name, so "nick pau" finds Nick Paustian.
139
+ const patterns = search.trim().split(/\s+/).filter(Boolean).map((word) => `%${word}%`).join("\n")
140
+ const wanted = ids.join(",")
141
+ const rows = await sql`
142
+ select id, data from users
143
+ where (${wanted} = '' or id = any(string_to_array(${wanted}, ',')::uuid[]))
144
+ and not exists (
145
+ select 1 from unnest(string_to_array(nullif(${patterns}, ''), E'\n')) as pattern
146
+ where concat_ws(' ', data ->> 'firstName', data ->> 'lastName', data ->> 'name') not ilike pattern
147
+ )
148
+ order by lower(concat_ws(' ', data ->> 'firstName', data ->> 'lastName', data ->> 'name'))
149
+ limit ${Math.min(Math.max(limit, 1), MAX_LIMIT)}
150
+ `
151
+ return rows
152
+ .map((row: any) => ({ id: String(row.id), name: publicName(row.data) }))
153
+ .filter((one: { name: string }) => one.name)
154
+ }
155
+
124
156
  export async function getUser(_: Collection, id: string): Promise<Entry | null> {
125
157
  const rows = await sql`
126
158
  select id, email, data, created_at, updated_at from users where id = ${id}
package/src/index.ts CHANGED
@@ -20,7 +20,7 @@ export type {
20
20
  WorkflowStage,
21
21
  NavSection,
22
22
  } from "./config/types.ts"
23
- export { imageUse, slugField } from "./config/fields.ts"
23
+ export { imageUse, person, slugField } from "./config/fields.ts"
24
24
  export type { UrlRule } from "./content/url.ts"
25
25
  export type { CounterSpec, Band, Tone } from "./content/counter.ts"
26
26
  export type { SharingOptions } from "./content/sharing.ts"
@@ -56,10 +56,11 @@ import { findCollection } from "../content/collections.ts"
56
56
  import { createAndStage, storeFor, isPublishable } from "../content/store.ts"
57
57
  import { withDerived } from "../content/derive-values.ts"
58
58
  import { withoutSecrets } from "../config/components.ts"
59
- import { countUsers } from "../content/users.ts"
59
+ import { countUsers, peopleNamed } from "../content/users.ts"
60
60
  import { blocking, checkEverything, checkServerRules } from "../content/validate.ts"
61
61
  import {
62
62
  getEntry,
63
+ isEntryId,
63
64
  isPublished,
64
65
  purgeEntry,
65
66
  } from "../content/entries.ts"
@@ -1187,6 +1188,27 @@ const server = Bun.serve({
1187
1188
  * Unpublished ones are included and say so, since a link written now may
1188
1189
  * go live with them.
1189
1190
  */
1191
+ /**
1192
+ * People to name on an entry: ids and names only, for anyone signed in.
1193
+ *
1194
+ * The person field asks this rather than `/api/entries/users`, which an
1195
+ * editor may not read - accounts are how permissions are held - and which
1196
+ * would hand over addresses and roles to offer a byline.
1197
+ */
1198
+ "/api/people": {
1199
+ GET: authed(async (req: { params?: unknown } & Request) => {
1200
+ const params = new URL(req.url).searchParams
1201
+ const ids = (params.get("ids") ?? "").split(",").filter((one) => isEntryId(one))
1202
+ return json({
1203
+ people: await peopleNamed({
1204
+ search: params.get("q") ?? "",
1205
+ ids,
1206
+ limit: Number(params.get("limit") ?? 20) || 20,
1207
+ }),
1208
+ })
1209
+ }),
1210
+ },
1211
+
1190
1212
  "/api/links": {
1191
1213
  GET: authed(async (req: { params?: unknown } & Request, user) => {
1192
1214
  const params = new URL(req.url).searchParams