@stacksjs/defaults 0.75.552 → 0.75.555

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.
Files changed (57) hide show
  1. package/ai/skills/stacks-actions/SKILL.md +1 -1
  2. package/ai/skills/stacks-dashboard/SKILL.md +347 -14
  3. package/ai/skills/stacks-desktop/SKILL.md +19 -0
  4. package/ai/skills/stacks-models/SKILL.md +19 -0
  5. package/ai/skills/stacks-native/CATALOG.md +5 -5
  6. package/app/Actions/Dashboard/Content/file-manager.ts +9 -3
  7. package/app/Actions/Dashboard/Data/SubscriberIndexAction.ts +6 -3
  8. package/app/Actions/Dashboard/Data/TeamIndexAction.ts +6 -3
  9. package/app/Actions/Dashboard/Data/UserIndexAction.ts +6 -3
  10. package/app/Actions/Dashboard/Data/data-records.ts +12 -0
  11. package/app/Actions/Dashboard/Models/ModelActionRunAction.ts +77 -0
  12. package/app/Actions/Dashboard/Models/ModelMarkdownAction.ts +42 -0
  13. package/app/Actions/Dashboard/Models/ModelShowAction.ts +63 -21
  14. package/app/Actions/Dashboard/Models/ModelUploadAction.ts +83 -0
  15. package/app/Actions/Dashboard/Models/model-actions.ts +393 -0
  16. package/app/Actions/Dashboard/Models/model-fields.ts +198 -0
  17. package/app/Actions/Dashboard/Models/model-forms.ts +36 -0
  18. package/app/Actions/Dashboard/Models/model-related.ts +62 -11
  19. package/app/Actions/Dashboard/Models/model-upload.ts +81 -0
  20. package/app/Actions/Dashboard/Models/model-write.ts +92 -5
  21. package/app/Actions/Dashboard/Users/UserPasswordResetAction.ts +50 -0
  22. package/app/Actions/Desktop/UpdateArtifactAction.ts +37 -0
  23. package/app/Models/CardAttachment.ts +5 -0
  24. package/app/Models/Deployment.ts +5 -0
  25. package/app/Models/QueryLog.ts +5 -0
  26. package/app/Models/Request.ts +4 -0
  27. package/app/Models/Team.ts +4 -0
  28. package/app/Models/User.ts +18 -0
  29. package/functions/dashboard-markdown.ts +132 -0
  30. package/functions/dashboard-model-bulk.ts +224 -0
  31. package/functions/dashboard-model-format.ts +201 -0
  32. package/functions/dashboard-model-record.test.ts +53 -30
  33. package/functions/dashboard-model-record.ts +267 -19
  34. package/functions/data.ts +9 -0
  35. package/ide/vscode/package.json +1 -1
  36. package/package.json +3 -3
  37. package/resources/components/Dashboard/Data/ActivityLog.stx +212 -0
  38. package/resources/components/Dashboard/Data/DataModelRecords.stx +89 -0
  39. package/resources/components/Dashboard/Models/ModelActionForm.stx +85 -0
  40. package/resources/components/Dashboard/Models/ModelBadge.stx +22 -0
  41. package/resources/components/Dashboard/Models/ModelFieldInputs.stx +43 -9
  42. package/resources/components/Dashboard/Models/ModelMarkdownInput.stx +139 -0
  43. package/resources/components/Dashboard/Models/ModelRecordActions.stx +32 -1
  44. package/resources/components/Dashboard/Models/ModelRecordCreate.stx +1 -1
  45. package/resources/components/Dashboard/Models/ModelRecordDetail.stx +114 -7
  46. package/resources/components/Dashboard/Models/ModelRecordEdit.stx +1 -1
  47. package/resources/components/Dashboard/Models/ModelRecordsDashboard.stx +387 -20
  48. package/resources/components/Dashboard/Models/ModelRelatedPanels.stx +197 -27
  49. package/resources/components/Dashboard/Models/ModelRelationPicker.stx +3 -0
  50. package/resources/components/Dashboard/Models/ModelUploadInput.stx +97 -0
  51. package/routes/dashboard-api.ts +9 -0
  52. package/routes/desktop-updates.ts +7 -0
  53. package/views/dashboard/data/activity/index.stx +1 -1
  54. package/views/dashboard/data/subscribers.stx +1 -3
  55. package/views/dashboard/data/teams.stx +1 -3
  56. package/views/dashboard/data/users.stx +1 -3
  57. package/resources/components/Dashboard/Data/DataRecords.stx +0 -427
@@ -0,0 +1,212 @@
1
+ @import('../UI/Table')
2
+
3
+ <script client>
4
+ // The Activity log: the application's audit trail, newest first.
5
+ //
6
+ // Not a list of editable records, so not the model's list: an entry is
7
+ // something that happened. It can be opened, and nothing more unless the
8
+ // model says otherwise, which is the model's to say (`dashboard.writes`).
9
+ //
10
+ // This used to be one mode of a component that also drew Users, Teams and
11
+ // Subscribers, each a second list of a model that already had one. Those are
12
+ // the model's own list now (`DataModelRecords`).
13
+ import type { DashboardActivity, DataStats } from '../../../../functions/data'
14
+ import { fetchDashboardData } from '../../../../functions/data'
15
+ import type { ModelWriteCapabilities } from '../../../../functions/dashboard-model-record'
16
+ import { deleteModelRecord, fetchModelCapabilities, modelDeleteNotice, modelDeleteWarning, modelRecordEditHref, modelRecordHref, NO_WRITES } from '../../../../functions/dashboard-model-record'
17
+ import { pushToast } from '../../../../functions/toasts'
18
+
19
+ /** The model behind the rows, and this page, for a record's own page to come back to. */
20
+ const MODEL = 'activity'
21
+ const HOME = '/data/activity'
22
+
23
+ const records = state<DashboardActivity[]>([])
24
+ const stats = state<DataStats>({ total: 0 })
25
+ const search = state('')
26
+ const loading = state(true)
27
+ const loadError = state('')
28
+ const capabilities = state<ModelWriteCapabilities>(NO_WRITES)
29
+ const confirmingDelete = state<Record<string, any> | null>(null)
30
+ const working = state(false)
31
+
32
+ /** View always; edit and delete only where the model allows them. */
33
+ const rowActions = derived(() => [
34
+ { action: 'view', label: 'View' },
35
+ ...(capabilities().update ? [{ action: 'edit', label: 'Edit' }] : []),
36
+ ...(capabilities().destroy ? [{ action: 'delete', label: 'Delete' }] : []),
37
+ ])
38
+ const deleteDescription = derived(() => {
39
+ const row = confirmingDelete()
40
+ return modelDeleteWarning(row ? String(row.description ?? row.id) : '', false)
41
+ })
42
+
43
+ async function loadCapabilities(): Promise<void> {
44
+ try {
45
+ capabilities.set(await fetchModelCapabilities(MODEL))
46
+ }
47
+ catch {
48
+ // Without them the page still lists and views; it offers no writes.
49
+ capabilities.set(NO_WRITES)
50
+ }
51
+ }
52
+
53
+ /** The eye and the pencil each open a page of the entry's own, which comes back here. */
54
+ function handleRowAction(payload: { action: string, row: Record<string, any> }): void {
55
+ if (payload.action === 'delete')
56
+ confirmingDelete.set(payload.row)
57
+ else if (payload.action === 'edit')
58
+ navigate(modelRecordEditHref(MODEL, payload.row.id, { from: HOME }))
59
+ else
60
+ navigate(modelRecordHref(MODEL, payload.row.id, HOME))
61
+ }
62
+
63
+ async function confirmDelete(): Promise<void> {
64
+ const row = confirmingDelete()
65
+ if (!row)
66
+ return
67
+ working.set(true)
68
+ try {
69
+ const outcome = await deleteModelRecord(MODEL, row.id)
70
+ const notice = modelDeleteNotice(`Entry ${row.description ?? row.id}`, outcome)
71
+ pushToast('success', notice.title, { detail: notice.detail })
72
+ confirmingDelete.set(null)
73
+ await loadRecords()
74
+ }
75
+ catch (error) {
76
+ pushToast('error', 'Could not delete', { detail: error instanceof Error ? error.message : String(error) })
77
+ }
78
+ finally {
79
+ working.set(false)
80
+ }
81
+ }
82
+
83
+ const filteredRecords = derived(() => {
84
+ const query = search().trim().toLowerCase()
85
+ if (!query)
86
+ return records()
87
+ return records().filter(record => searchableText(record).includes(query))
88
+ })
89
+
90
+ /** "13 entries", or "2 of 13 entries" while a search narrows them. */
91
+ const countLabel = derived(() => {
92
+ const total = records().length
93
+ const shown = filteredRecords().length
94
+ const noun = (count: number) => count === 1 ? 'entry' : 'entries'
95
+ return shown === total ? `${total} ${noun(total)}` : `${shown} of ${total} ${noun(total)}`
96
+ })
97
+
98
+ function searchableText(record: DashboardActivity): string {
99
+ return Object.values(record)
100
+ .filter(value => typeof value === 'string' || typeof value === 'number')
101
+ .join(' ')
102
+ .toLowerCase()
103
+ }
104
+
105
+ function statValue(key: string): number {
106
+ return Number(stats()[key] || 0)
107
+ }
108
+
109
+ function formatSubject(record: DashboardActivity): string {
110
+ if (!record.subjectType)
111
+ return 'Application'
112
+ return record.subjectId > 0 ? `${record.subjectType} #${record.subjectId}` : record.subjectType
113
+ }
114
+
115
+ const COLUMNS = [
116
+ { key: 'description', label: 'Activity', sortable: true, subtitleKey: 'type', class: 'font-medium text-neutral-900 dark:text-white' },
117
+ { key: 'subject', label: 'Subject', sortable: true, class: 'text-neutral-600 dark:text-neutral-300' },
118
+ { key: 'causer', label: 'Causer', sortable: true, class: 'text-neutral-600 dark:text-neutral-300' },
119
+ { key: 'createdAt', label: 'Recorded', type: 'datetime' as const, align: 'right' as const, sortable: true, emptyText: 'Never', class: 'text-neutral-500 text-xs whitespace-nowrap dark:text-neutral-400' },
120
+ ]
121
+
122
+ const recordRows = derived(() => filteredRecords().map(record => ({ ...record, subject: formatSubject(record) })))
123
+
124
+ async function loadRecords(): Promise<void> {
125
+ loading.set(true)
126
+ loadError.set('')
127
+ try {
128
+ const response = await fetchDashboardData<DashboardActivity>('activity')
129
+ records.set(response.activities || [])
130
+ stats.set(response.stats)
131
+ }
132
+ catch (error) {
133
+ records.set([])
134
+ stats.set({ total: 0 })
135
+ loadError.set(error instanceof Error ? error.message : 'Activity Log could not be loaded.')
136
+ }
137
+ finally {
138
+ loading.set(false)
139
+ }
140
+ }
141
+
142
+ onMount(() => {
143
+ void loadRecords()
144
+ void loadCapabilities()
145
+ })
146
+ </script>
147
+
148
+ <div class="flex flex-col gap-6">
149
+ <header class="flex flex-col gap-4 sm:flex-row sm:items-end sm:justify-between">
150
+ <div>
151
+ <h1 class="font-bold text-2xl text-neutral-900 tracking-tight dark:text-white">Activity Log</h1>
152
+ <p class="mt-1 text-neutral-500 text-sm dark:text-neutral-400">Review the native application audit trail.</p>
153
+ </div>
154
+ <div class="flex flex-none gap-2 items-center">
155
+ <Button variant="secondary" :loading="loading()" @click="loadRecords">
156
+ <span :if="!loading()" class="h-4 w-4 i-hugeicons-refresh"></span>
157
+ Refresh
158
+ </Button>
159
+ </div>
160
+ </header>
161
+
162
+ <div class="grid gap-4 grid-cols-1 sm:grid-cols-3">
163
+ <StatsCard title="Total Activity Log" icon="i-hugeicons-activity-03" iconBg="primary">
164
+ <template #value>{{ statValue('total') }}</template>
165
+ </StatsCard>
166
+ <StatsCard title="Last 24 Hours" icon="i-hugeicons-clock-01" iconBg="success">
167
+ <template #value>{{ statValue('last24Hours') }}</template>
168
+ </StatsCard>
169
+ <StatsCard title="Last 7 Days" icon="i-hugeicons-calendar-03" iconBg="info">
170
+ <template #value>{{ statValue('last7Days') }}</template>
171
+ </StatsCard>
172
+ </div>
173
+
174
+ <div :if="loadError()" role="alert" class="px-4 py-3 text-red-700 text-sm dark:text-red-300 bg-red-50 dark:bg-red-950/40 border border-red-200 rounded-lg dark:border-red-900">
175
+ {{ loadError() }}
176
+ </div>
177
+
178
+ <Card padding="none">
179
+ <div class="flex flex-col gap-3 items-start sm:flex-row sm:items-center sm:justify-between p-5 border-b border-neutral-200 dark:border-neutral-700">
180
+ <div>
181
+ <h2 class="font-semibold text-neutral-900 dark:text-white">Activity Log</h2>
182
+ <p class="mt-1 text-neutral-500 text-xs dark:text-neutral-400">{{ countLabel() }}</p>
183
+ </div>
184
+ <label class="block relative w-full sm:w-72">
185
+ <span class="sr-only">Search activity log</span>
186
+ <span aria-hidden="true" class="absolute left-3 top-1/2 h-4 w-4 text-neutral-400 pointer-events-none -translate-y-1/2 i-hugeicons-search-01"></span>
187
+ <input x-model="search" type="search" placeholder="Search activity log" class="block pl-9 pr-3 py-2 w-full text-neutral-900 text-sm dark:text-white bg-white dark:bg-neutral-900 border border-neutral-300 rounded-lg dark:border-neutral-700 focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-500/20">
188
+ </label>
189
+ </div>
190
+
191
+ <div :if="loading()" class="flex items-center justify-center py-16 text-neutral-500 text-sm dark:text-neutral-400">
192
+ <span class="mr-2 h-5 w-5 animate-spin i-hugeicons-loading-03"></span>
193
+ Loading activity log...
194
+ </div>
195
+
196
+ <EmptyState :if="!loading() && !loadError() && filteredRecords().length === 0" icon="i-hugeicons-activity-03" :title="search() ? 'No matching records' : 'No activity has been recorded.'" :description="search() ? 'Try a different search term.' : 'New records will appear here automatically.'" />
197
+
198
+ <div :if="!loading() && filteredRecords().length > 0">
199
+ <Table :columns="COLUMNS" :data="recordRows()" paginated :page-size="25" :framed="false" :row-actions="rowActions()" action-label-key="description" @row-action="handleRowAction" />
200
+ </div>
201
+ </Card>
202
+
203
+ <ConfirmDialog
204
+ :isOpen="Boolean(confirmingDelete())"
205
+ title="Delete this entry?"
206
+ :description="deleteDescription()"
207
+ :busy="working()"
208
+ :confirmLabel="working() ? 'Deleting' : 'Delete'"
209
+ @close="confirmingDelete.set(null)"
210
+ @confirm="confirmDelete"
211
+ />
212
+ </div>
@@ -0,0 +1,89 @@
1
+ <script client>
2
+ // The Users, Teams and Subscribers pages. Each is the model's own list, the
3
+ // one every model has, hosted under the page's name with its row of stats
4
+ // above it. Nothing about the rows is this page's: paging, search, columns,
5
+ // actions and selection are the list's, so they are built once.
6
+ //
7
+ // What is the page's own: what it is called, what it is for, and the numbers
8
+ // at the top, which are read again whenever the list changes a record.
9
+ //
10
+ // Every name here that the summary below uses is the page's alone
11
+ // (`recordsPage`, `pageStats`). What goes in the list's slot is read against
12
+ // the list's own names first, and a `page` here was read as the list's page
13
+ // number: the first card said "Total undefined".
14
+ import type { DataStats } from '../../../../functions/data'
15
+ import { fetchDashboardStats } from '../../../../functions/data'
16
+
17
+ type RecordsPage = 'users' | 'teams' | 'subscribers'
18
+
19
+ const pageMode = useReactiveProp<RecordsPage>('mode', 'users')
20
+ const pageStats = state<DataStats>({ total: 0 })
21
+
22
+ const PAGES: Record<RecordsPage, { model: string, title: string, description: string, icon: string, cards: 3 | 4 }> = {
23
+ users: { model: 'user', title: 'Users', description: 'Review registered application users.', icon: 'i-hugeicons-user-group', cards: 3 },
24
+ teams: { model: 'team', title: 'Teams', description: 'Review collaborative teams and membership totals.', icon: 'i-hugeicons-user-multiple-02', cards: 4 },
25
+ subscribers: { model: 'subscriber', title: 'Subscribers', description: 'Review subscription status and acquisition sources.', icon: 'i-hugeicons-mail-account-01', cards: 4 },
26
+ }
27
+
28
+ const recordsPage = derived(() => PAGES[pageMode()] ?? PAGES.users)
29
+ /** Each page's stats fill their row: three cards in a four-column grid left a hole. */
30
+ const pageStatsGrid = derived(() => recordsPage().cards === 3 ? 'grid-cols-1 sm:grid-cols-3' : 'grid-cols-2 lg:grid-cols-4')
31
+
32
+ function pageStat(key: string): number {
33
+ return Number(pageStats()[key] || 0)
34
+ }
35
+
36
+ async function loadPageStats(): Promise<void> {
37
+ try {
38
+ pageStats.set(await fetchDashboardStats(pageMode()))
39
+ }
40
+ catch {
41
+ // The list below says what is wrong when the model cannot be read; the
42
+ // numbers stay as they were.
43
+ }
44
+ }
45
+
46
+ onMount(() => {
47
+ void loadPageStats()
48
+ })
49
+ </script>
50
+
51
+ <ModelRecordsDashboard
52
+ :model="recordsPage().model"
53
+ :heading="recordsPage().title"
54
+ :description="recordsPage().description"
55
+ :home="'/data/' + pageMode()"
56
+ @changed="loadPageStats"
57
+ >
58
+ <template #summary>
59
+ <div class="grid gap-4" :class="pageStatsGrid()" data-page-stats>
60
+ <StatsCard :title="'Total ' + recordsPage().title" :icon="recordsPage().icon" iconBg="primary">
61
+ <template #value>{{ pageStat('total') }}</template>
62
+ </StatsCard>
63
+ <StatsCard :if="pageMode() === 'users'" title="New This Week" icon="i-hugeicons-user-add-01" iconBg="success">
64
+ <template #value>{{ pageStat('newThisWeek') }}</template>
65
+ </StatsCard>
66
+ <StatsCard :if="pageMode() === 'users'" title="Email Verified" icon="i-hugeicons-mail-validation-01" iconBg="info">
67
+ <template #value>{{ pageStat('verified') }}</template>
68
+ </StatsCard>
69
+ <StatsCard :if="pageMode() === 'teams'" title="Active Teams" icon="i-hugeicons-checkmark-circle-02" iconBg="success">
70
+ <template #value>{{ pageStat('active') }}</template>
71
+ </StatsCard>
72
+ <StatsCard :if="pageMode() === 'teams'" title="Members" icon="i-hugeicons-user-multiple" iconBg="info">
73
+ <template #value>{{ pageStat('members') }}</template>
74
+ </StatsCard>
75
+ <StatsCard :if="pageMode() === 'teams'" title="New This Month" icon="i-hugeicons-calendar-add-01" iconBg="warning">
76
+ <template #value>{{ pageStat('newThisMonth') }}</template>
77
+ </StatsCard>
78
+ <StatsCard :if="pageMode() === 'subscribers'" title="Subscribed" icon="i-hugeicons-mail-open-01" iconBg="success">
79
+ <template #value>{{ pageStat('subscribed') }}</template>
80
+ </StatsCard>
81
+ <StatsCard :if="pageMode() === 'subscribers'" title="Unsubscribed" icon="i-hugeicons-mail-remove-01" iconBg="warning">
82
+ <template #value>{{ pageStat('unsubscribed') }}</template>
83
+ </StatsCard>
84
+ <StatsCard :if="pageMode() === 'subscribers'" title="New This Month" icon="i-hugeicons-calendar-add-01" iconBg="info">
85
+ <template #value>{{ pageStat('newThisMonth') }}</template>
86
+ </StatsCard>
87
+ </div>
88
+ </template>
89
+ </ModelRecordsDashboard>
@@ -0,0 +1,85 @@
1
+ <script client>
2
+ // The form an action's input is asked for in, before it runs: a refund's
3
+ // reason, a new owner. The fields are the action's own `validations`, read by
4
+ // the server, so what is asked for is what the action checks.
5
+ //
6
+ // It is the confirmation too: the model's sentence about what the action does
7
+ // sits above the inputs, and nothing runs until the form is submitted. A
8
+ // refusal comes back here, under the field it is about, and the form stays
9
+ // open. The page owns the running; this reports what was typed.
10
+ import type { ModelCustomAction, ModelFormValues } from '../../../../functions/dashboard-model-record'
11
+ import { modelActionInput, modelFormValues } from '../../../../functions/dashboard-model-record'
12
+
13
+ // The action being asked about. Null closes the form.
14
+ const action = useReactiveProp<ModelCustomAction | null>('action', null)
15
+ // What the page adds to the model's sentence: how many records it will run on.
16
+ const note = useReactiveProp('note', '')
17
+ const busy = useReactiveProp('busy', false)
18
+ // What the submit button says while it runs: how far a run over a selection has got.
19
+ const busyLabel = useReactiveProp('busyLabel', '')
20
+ const error = useReactiveProp('error', '')
21
+ const errors = useReactiveProp<Record<string, string[]>>('errors', {})
22
+ const emit = defineEmits(['submit', 'close'])
23
+
24
+ const values = state<ModelFormValues>({})
25
+ // Which action the values belong to, so each opening starts blank.
26
+ let filledFor = ''
27
+
28
+ effect(() => {
29
+ const current = action()
30
+ const name = current ? current.name : ''
31
+ if (name === filledFor)
32
+ return
33
+ filledFor = name
34
+ values.set(current ? modelFormValues(current.fields ?? []) : {})
35
+ })
36
+
37
+ const fields = derived(() => action()?.fields ?? [])
38
+ const title = derived(() => action()?.label ?? '')
39
+ const description = derived(() => [action()?.confirm ?? '', note()].filter(Boolean).join(' '))
40
+ const destructive = derived(() => Boolean(action()?.destructive))
41
+ const submitLabel = derived(() => (busy() && busyLabel()) || title())
42
+
43
+ function setValue(change: { name: string, value: string | boolean }): void {
44
+ values.set({ ...values(), [change.name]: change.value })
45
+ }
46
+
47
+ function close(): void {
48
+ if (!busy())
49
+ emit('close')
50
+ }
51
+
52
+ function submit(): void {
53
+ const current = action()
54
+ if (current && !busy())
55
+ emit('submit', modelActionInput(current.fields ?? [], values()))
56
+ }
57
+ </script>
58
+
59
+ <Modal
60
+ :isOpen="Boolean(action())"
61
+ :title="title()"
62
+ :description="description()"
63
+ :closable="!busy()"
64
+ size="lg"
65
+ @close="close"
66
+ >
67
+ <form id="model-action-form" class="flex flex-col gap-5" data-action-form @submit.prevent="submit">
68
+ <div :if="error()" role="alert" class="px-4 py-3 text-red-700 text-sm dark:text-red-300 bg-red-50 dark:bg-red-950/40 border border-red-200 rounded-lg dark:border-red-900">{{ error() }}</div>
69
+ <ModelFieldInputs
70
+ :fields="fields()"
71
+ :values="values()"
72
+ :errors="errors()"
73
+ :disabled="busy()"
74
+ @change="setValue"
75
+ />
76
+ </form>
77
+
78
+ <template #footer>
79
+ <div class="flex gap-2 items-center justify-end w-full">
80
+ <Button variant="secondary" :disabled="busy()" @click="close">Cancel</Button>
81
+ <Button :if="!destructive()" variant="primary" type="submit" form="model-action-form" :loading="busy()">{{ submitLabel() }}</Button>
82
+ <Button :if="destructive()" variant="danger" type="submit" form="model-action-form" :loading="busy()">{{ submitLabel() }}</Button>
83
+ </div>
84
+ </template>
85
+ </Modal>
@@ -0,0 +1,22 @@
1
+ <script client>
2
+ // A status-like word as a pill, coloured by what it says: settled (active,
3
+ // subscribed, paid), ended (inactive, bounced, failed), under way (pending,
4
+ // draft), or neither. One place for the colours, so a status reads the same
5
+ // in a list and on a record's page.
6
+ const text = useReactiveProp('text', '')
7
+ const tone = useReactiveProp('tone', 'neutral')
8
+
9
+ const TONES: Record<string, string> = {
10
+ positive: 'text-green-700 dark:text-green-300 bg-green-50 dark:bg-green-950/40 border-green-200 dark:border-green-900',
11
+ negative: 'text-red-700 dark:text-red-300 bg-red-50 dark:bg-red-950/40 border-red-200 dark:border-red-900',
12
+ pending: 'text-amber-700 dark:text-amber-300 bg-amber-50 dark:bg-amber-950/40 border-amber-200 dark:border-amber-900',
13
+ muted: 'text-neutral-600 dark:text-neutral-300 bg-neutral-100 dark:bg-white/10 border-transparent',
14
+ neutral: 'text-neutral-800 dark:text-neutral-100 border-neutral-400 dark:border-neutral-500',
15
+ }
16
+
17
+ function toneClass(): string {
18
+ return `inline-flex px-2 py-0.5 font-medium text-xs border rounded-md ${TONES[tone()] ?? TONES.neutral}`
19
+ }
20
+ </script>
21
+
22
+ <span :class="toneClass()" :data-tone="tone()">{{ text() }}</span>
@@ -2,7 +2,9 @@
2
2
  // The inputs of a model's form, one per field, each in the control its kind
3
3
  // calls for: a select for a choice, a checkbox for yes or no, a date or a
4
4
  // date-and-time picker, a number box, a tall box for prose and for JSON, a
5
- // search for another model's record, and a line of text for the rest.
5
+ // search for another model's record, a file chooser, a Markdown editor, and a
6
+ // line of text for the rest. Under each, the sentence the model wrote for it,
7
+ // when it wrote one.
6
8
  //
7
9
  // The create page and the edit page both render this, so a kind of field is
8
10
  // drawn once. The page owns the values: this reports each change upward as
@@ -11,6 +13,8 @@ import type { ModelCreateField, ModelFormValues } from '../../../../functions/da
11
13
  import { modelFieldError } from '../../../../functions/dashboard-model-record'
12
14
 
13
15
  const fields = useReactiveProp<ModelCreateField[]>('fields', [])
16
+ // The model these fields belong to, in a dashboard URL: where a chosen file is sent.
17
+ const slug = useReactiveProp('slug', '')
14
18
  const values = useReactiveProp<ModelFormValues>('values', {})
15
19
  const errors = useReactiveProp<Record<string, string[]>>('errors', {})
16
20
  const disabled = useReactiveProp('disabled', false)
@@ -25,25 +29,26 @@ function error(field: ModelCreateField): string {
25
29
  return modelFieldError(errors(), field.name)
26
30
  }
27
31
 
28
- function inputType(field: ModelCreateField): 'date' | 'datetime-local' | 'email' | 'number' | 'text' {
32
+ function inputType(field: ModelCreateField): 'date' | 'datetime-local' | 'email' | 'number' | 'text' | 'url' {
29
33
  if (field.type === 'datetime')
30
34
  return 'datetime-local'
31
- if (field.type === 'date' || field.type === 'email' || field.type === 'number')
35
+ if (field.type === 'date' || field.type === 'email' || field.type === 'number' || field.type === 'url')
32
36
  return field.type
33
37
  return 'text'
34
38
  }
35
39
 
36
40
  /** Everything that is one line: text, email, number, date, date and time. */
37
41
  function isLine(field: ModelCreateField): boolean {
38
- return field.type !== 'boolean' && field.type !== 'enum' && field.type !== 'longtext' && field.type !== 'json' && field.type !== 'relation'
42
+ return !['boolean', 'enum', 'json', 'longtext', 'markdown', 'relation', 'upload'].includes(field.type)
39
43
  }
40
44
 
45
+ /**
46
+ * The line under an input: what the model says about the field
47
+ * (`dashboard.fields.<name>.help`), then what its kind needs said.
48
+ */
41
49
  function hint(field: ModelCreateField): string {
42
- if (field.type === 'json')
43
- return 'JSON. Checked when you save.'
44
- if (field.type === 'datetime')
45
- return 'In your own time zone.'
46
- return ''
50
+ const kind = field.type === 'json' ? 'JSON. Checked when you save.' : field.type === 'datetime' ? 'In your own time zone.' : ''
51
+ return [field.help, kind].filter(Boolean).join(' ')
47
52
  }
48
53
 
49
54
  function change(field: ModelCreateField, value: string | boolean): void {
@@ -64,6 +69,7 @@ function change(field: ModelCreateField, value: string | boolean): void {
64
69
  />
65
70
  <span>
66
71
  <span class="block font-medium text-neutral-900 text-sm dark:text-white">{{ field.label }}</span>
72
+ <span :if="hint(field) && !error(field)" class="block mt-0.5 text-neutral-500 text-xs dark:text-neutral-400">{{ hint(field) }}</span>
67
73
  <span :if="error(field)" role="alert" class="block mt-0.5 text-red-600 text-xs dark:text-red-400">{{ error(field) }}</span>
68
74
  </span>
69
75
  </label>
@@ -75,6 +81,7 @@ function change(field: ModelCreateField, value: string | boolean): void {
75
81
  :options="field.options"
76
82
  :label="field.label"
77
83
  :ariaLabel="field.label"
84
+ :hint="hint(field)"
78
85
  :required="field.required"
79
86
  :disabled="disabled()"
80
87
  :error="error(field)"
@@ -87,6 +94,33 @@ function change(field: ModelCreateField, value: string | boolean): void {
87
94
  :name="field.name"
88
95
  :value="text(field)"
89
96
  :label="field.label"
97
+ :hint="hint(field)"
98
+ :required="field.required"
99
+ :disabled="disabled()"
100
+ :error="error(field)"
101
+ @update:value="change(field, $event)"
102
+ />
103
+
104
+ <ModelUploadInput
105
+ :if="field.type === 'upload'"
106
+ :slug="slug()"
107
+ :name="field.name"
108
+ :value="text(field)"
109
+ :label="field.label"
110
+ :accept="field.accept || ''"
111
+ :hint="hint(field)"
112
+ :required="field.required"
113
+ :disabled="disabled()"
114
+ :error="error(field)"
115
+ @update:value="change(field, $event)"
116
+ />
117
+
118
+ <ModelMarkdownInput
119
+ :if="field.type === 'markdown'"
120
+ :name="field.name"
121
+ :value="text(field)"
122
+ :label="field.label"
123
+ :hint="hint(field)"
90
124
  :required="field.required"
91
125
  :disabled="disabled()"
92
126
  :error="error(field)"
@@ -0,0 +1,139 @@
1
+ <script client>
2
+ // A field asked for as Markdown (`dashboard.fields.<name>.input:
3
+ // 'markdown'`): a box to write it in, a toolbar for the common marks, and a
4
+ // preview of how it reads. What is stored is the Markdown itself.
5
+ //
6
+ // A button wraps what is selected (or the lines it touches) and puts the
7
+ // selection back where typing would go on. The preview is rendered by the
8
+ // server, with the parser Stacks content uses, and shown in a frame that
9
+ // runs no script.
10
+ import { isDark } from '../../../functions/dark'
11
+ import type { MarkdownMark } from '../../../../functions/dashboard-markdown'
12
+ import { applyMarkdown, fetchMarkdownPreview, MARKDOWN_MARKS, MARKDOWN_PREVIEW_POLICY, markdownPreviewDocument } from '../../../../functions/dashboard-markdown'
13
+
14
+ const name = useReactiveProp('name', '')
15
+ const value = useReactiveProp('value', '')
16
+ const label = useReactiveProp('label', '')
17
+ const required = useReactiveProp('required', false)
18
+ const disabled = useReactiveProp('disabled', false)
19
+ const error = useReactiveProp('error', '')
20
+ const hint = useReactiveProp('hint', '')
21
+ const emit = defineEmits(['update:value'])
22
+ const generatedId = useId('markdown')
23
+
24
+ const area = useRef<HTMLTextAreaElement>('modelMarkdownArea')
25
+ const previewing = state(false)
26
+ const rendered = state('')
27
+ const rendering = state(false)
28
+ const renderFailed = state('')
29
+ // Answers can arrive out of order; only the latest preview may be shown.
30
+ let asked = 0
31
+
32
+ const inputId = derived(() => `${generatedId}-input`)
33
+ const frame = derived(() => markdownPreviewDocument(rendered(), isDark()))
34
+ const boxClass = derived(() => error() ? 'border-red-400/60 dark:border-red-500/60' : 'border-stone-200/80 dark:border-white/15')
35
+
36
+ function press(mark: MarkdownMark): void {
37
+ const box = area.current
38
+ if (!box || disabled())
39
+ return
40
+ const edit = applyMarkdown(mark, box.value, box.selectionStart, box.selectionEnd)
41
+ // The box first, so the selection lands in the text it belongs to.
42
+ box.value = edit.text
43
+ box.focus()
44
+ box.setSelectionRange(edit.start, edit.end)
45
+ emit('update:value', edit.text)
46
+ }
47
+
48
+ async function show(preview: boolean): Promise<void> {
49
+ previewing.set(preview)
50
+ if (!preview)
51
+ return
52
+ const mine = ++asked
53
+ rendering.set(true)
54
+ renderFailed.set('')
55
+ try {
56
+ const html = await fetchMarkdownPreview(value())
57
+ if (mine === asked)
58
+ rendered.set(html)
59
+ }
60
+ catch (reason) {
61
+ if (mine === asked)
62
+ renderFailed.set(reason instanceof Error ? reason.message : 'The preview could not be made.')
63
+ }
64
+ finally {
65
+ if (mine === asked)
66
+ rendering.set(false)
67
+ }
68
+ }
69
+
70
+ function tabClass(active: boolean): string {
71
+ return active
72
+ ? 'px-2.5 h-7 font-medium text-[12px] text-neutral-900 dark:text-white bg-white dark:bg-white/15 rounded-md shadow-sm'
73
+ : 'px-2.5 h-7 font-medium text-[12px] text-neutral-500 dark:text-neutral-400 hover:text-neutral-800 dark:hover:text-neutral-200 rounded-md'
74
+ }
75
+ </script>
76
+
77
+ <div class="w-full" data-markdown-input>
78
+ <label :if="label()" :for="inputId()" class="block mb-1.5 font-medium text-[13px] tracking-tight" :class="error() ? 'text-red-600 dark:text-red-400' : 'text-stone-600 dark:text-neutral-400'">
79
+ {{ label() }}
80
+ <span :if="required()" aria-hidden="true" class="ml-0.5 text-red-500">*</span>
81
+ </label>
82
+
83
+ <div class="overflow-hidden bg-white dark:bg-white/10 border rounded-lg" :class="boxClass()">
84
+ <div class="flex flex-wrap gap-2 items-center justify-between px-2 py-1.5 bg-neutral-50 dark:bg-white/5 border-b border-stone-200/80 dark:border-white/10">
85
+ <div role="toolbar" :aria-label="'Formatting for ' + (label() || 'this field')" class="flex flex-wrap gap-0.5 items-center">
86
+ <span :for="item in MARKDOWN_MARKS" class="contents">
87
+ <Button
88
+ variant="ghost"
89
+ size="sm"
90
+ iconOnly
91
+ :disabled="disabled() || previewing()"
92
+ :ariaLabel="item.label"
93
+ :title="item.label"
94
+ @click="press(item.mark)"
95
+ >
96
+ <span aria-hidden="true" :class="'h-4 w-4 ' + item.icon"></span>
97
+ </Button>
98
+ </span>
99
+ </div>
100
+ <div role="tablist" aria-label="Write or preview" class="flex gap-0.5 items-center p-0.5 bg-neutral-200/70 dark:bg-white/10 rounded-lg">
101
+ <button type="button" role="tab" :aria-selected="String(!previewing())" :class="tabClass(!previewing())" @click="show(false)">Write</button>
102
+ <button type="button" role="tab" :aria-selected="String(previewing())" :class="tabClass(previewing())" @click="show(true)">Preview</button>
103
+ </div>
104
+ </div>
105
+
106
+ <textarea
107
+ :if="!previewing()"
108
+ ref="modelMarkdownArea"
109
+ :id="inputId()"
110
+ :name="name()"
111
+ :value="value()"
112
+ :required="required()"
113
+ :disabled="disabled()"
114
+ :aria-invalid="error() ? 'true' : null"
115
+ rows="10"
116
+ class="block px-3 py-2 w-full font-mono leading-relaxed text-[13px] text-stone-900 dark:text-neutral-100 placeholder:text-stone-400 dark:placeholder:text-neutral-500 bg-transparent border-0 focus:outline-none focus:ring-0 resize-y"
117
+ placeholder="Write in Markdown"
118
+ @input="emit('update:value', $event.target.value)"
119
+ ></textarea>
120
+
121
+ <div :if="previewing()" class="min-h-[15.5rem]" data-markdown-preview>
122
+ <p :if="rendering()" class="px-3 py-2 text-neutral-500 text-sm dark:text-neutral-400">Making the preview</p>
123
+ <p :if="!rendering() && renderFailed()" role="alert" class="px-3 py-2 text-red-600 text-sm dark:text-red-400">{{ renderFailed() }}</p>
124
+ <p :if="!rendering() && !renderFailed() && !rendered().trim()" class="px-3 py-2 text-neutral-500 text-sm dark:text-neutral-400">Nothing to preview yet.</p>
125
+ <iframe
126
+ :if="!rendering() && !renderFailed() && rendered().trim()"
127
+ :title="'Preview of ' + (label() || 'this field')"
128
+ :srcdoc="frame()"
129
+ sandbox=""
130
+ :csp="MARKDOWN_PREVIEW_POLICY"
131
+ referrerpolicy="no-referrer"
132
+ class="block h-[15.5rem] w-full bg-transparent border-0"
133
+ ></iframe>
134
+ </div>
135
+ </div>
136
+
137
+ <p :if="error()" class="mt-1.5 text-[12px] text-red-600 dark:text-red-400" :text="error()"></p>
138
+ <p :if="!error() && hint()" class="mt-1.5 text-[12px] text-stone-500 dark:text-neutral-400" :text="hint()"></p>
139
+ </div>