@stacksjs/defaults 0.75.551 → 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.
- package/ai/skills/stacks-actions/SKILL.md +1 -1
- package/ai/skills/stacks-dashboard/SKILL.md +347 -14
- package/ai/skills/stacks-desktop/SKILL.md +19 -0
- package/ai/skills/stacks-models/SKILL.md +19 -0
- package/ai/skills/stacks-native/CATALOG.md +7 -7
- package/ai/skills/stacks-storage/SKILL.md +9 -0
- package/app/Actions/Dashboard/Content/file-manager.ts +9 -3
- package/app/Actions/Dashboard/Data/SubscriberIndexAction.ts +6 -3
- package/app/Actions/Dashboard/Data/TeamIndexAction.ts +6 -3
- package/app/Actions/Dashboard/Data/UserIndexAction.ts +6 -3
- package/app/Actions/Dashboard/Data/data-records.ts +12 -0
- package/app/Actions/Dashboard/Models/ModelActionRunAction.ts +77 -0
- package/app/Actions/Dashboard/Models/ModelMarkdownAction.ts +42 -0
- package/app/Actions/Dashboard/Models/ModelShowAction.ts +63 -21
- package/app/Actions/Dashboard/Models/ModelUploadAction.ts +83 -0
- package/app/Actions/Dashboard/Models/model-actions.ts +393 -0
- package/app/Actions/Dashboard/Models/model-fields.ts +198 -0
- package/app/Actions/Dashboard/Models/model-forms.ts +36 -0
- package/app/Actions/Dashboard/Models/model-related.ts +62 -11
- package/app/Actions/Dashboard/Models/model-upload.ts +81 -0
- package/app/Actions/Dashboard/Models/model-write.ts +92 -5
- package/app/Actions/Dashboard/Users/UserPasswordResetAction.ts +50 -0
- package/app/Actions/Desktop/UpdateArtifactAction.ts +37 -0
- package/app/Models/CardAttachment.ts +5 -0
- package/app/Models/Deployment.ts +5 -0
- package/app/Models/QueryLog.ts +5 -0
- package/app/Models/Request.ts +4 -0
- package/app/Models/Team.ts +4 -0
- package/app/Models/User.ts +18 -0
- package/functions/dashboard-markdown.ts +132 -0
- package/functions/dashboard-model-bulk.ts +224 -0
- package/functions/dashboard-model-format.ts +201 -0
- package/functions/dashboard-model-record.test.ts +53 -30
- package/functions/dashboard-model-record.ts +267 -19
- package/functions/data.ts +9 -0
- package/ide/vscode/package.json +1 -1
- package/package.json +3 -3
- package/resources/components/Dashboard/Data/ActivityLog.stx +212 -0
- package/resources/components/Dashboard/Data/DataModelRecords.stx +89 -0
- package/resources/components/Dashboard/Models/ModelActionForm.stx +85 -0
- package/resources/components/Dashboard/Models/ModelBadge.stx +22 -0
- package/resources/components/Dashboard/Models/ModelFieldInputs.stx +43 -9
- package/resources/components/Dashboard/Models/ModelMarkdownInput.stx +139 -0
- package/resources/components/Dashboard/Models/ModelRecordActions.stx +32 -1
- package/resources/components/Dashboard/Models/ModelRecordCreate.stx +1 -1
- package/resources/components/Dashboard/Models/ModelRecordDetail.stx +114 -7
- package/resources/components/Dashboard/Models/ModelRecordEdit.stx +1 -1
- package/resources/components/Dashboard/Models/ModelRecordsDashboard.stx +387 -20
- package/resources/components/Dashboard/Models/ModelRelatedPanels.stx +197 -27
- package/resources/components/Dashboard/Models/ModelRelationPicker.stx +3 -0
- package/resources/components/Dashboard/Models/ModelUploadInput.stx +97 -0
- package/routes/dashboard-api.ts +9 -0
- package/routes/desktop-updates.ts +7 -0
- package/views/dashboard/data/activity/index.stx +1 -1
- package/views/dashboard/data/subscribers.stx +1 -3
- package/views/dashboard/data/teams.stx +1 -3
- package/views/dashboard/data/users.stx +1 -3
- package/resources/components/Dashboard/Data/DataRecords.stx +0 -427
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Writing Markdown in a form field (`dashboard.fields.<name>.input:
|
|
3
|
+
* 'markdown'`): what each toolbar button does to the text, and the preview.
|
|
4
|
+
*
|
|
5
|
+
* The buttons are plain text edits, so they are functions of the text and
|
|
6
|
+
* the selection and nothing else: the editor applies what they answer.
|
|
7
|
+
*/
|
|
8
|
+
import { dashboardApi } from './dashboard-api'
|
|
9
|
+
|
|
10
|
+
export type MarkdownMark = 'bold' | 'italic' | 'code' | 'link' | 'heading' | 'bullets' | 'numbers' | 'quote'
|
|
11
|
+
|
|
12
|
+
/** The toolbar, in order: what each button is called and its icon. */
|
|
13
|
+
export const MARKDOWN_MARKS: ReadonlyArray<{ mark: MarkdownMark, label: string, icon: string }> = [
|
|
14
|
+
{ mark: 'bold', label: 'Bold', icon: 'i-hugeicons-text-bold' },
|
|
15
|
+
{ mark: 'italic', label: 'Italic', icon: 'i-hugeicons-text-italic' },
|
|
16
|
+
{ mark: 'heading', label: 'Heading', icon: 'i-hugeicons-heading' },
|
|
17
|
+
{ mark: 'link', label: 'Link', icon: 'i-hugeicons-link-01' },
|
|
18
|
+
{ mark: 'bullets', label: 'Bulleted list', icon: 'i-hugeicons-left-to-right-list-bullet' },
|
|
19
|
+
{ mark: 'numbers', label: 'Numbered list', icon: 'i-hugeicons-left-to-right-list-number' },
|
|
20
|
+
{ mark: 'quote', label: 'Quote', icon: 'i-hugeicons-quote-down' },
|
|
21
|
+
{ mark: 'code', label: 'Code', icon: 'i-hugeicons-source-code' },
|
|
22
|
+
]
|
|
23
|
+
|
|
24
|
+
/** The text after a button was pressed, and what is selected in it. */
|
|
25
|
+
export interface MarkdownEdit {
|
|
26
|
+
text: string
|
|
27
|
+
start: number
|
|
28
|
+
end: number
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** What a mark that wraps a selection puts on each side of it, and what it wraps when nothing is selected. */
|
|
32
|
+
const WRAPS: Partial<Record<MarkdownMark, { around: string, empty: string }>> = {
|
|
33
|
+
bold: { around: '**', empty: 'bold text' },
|
|
34
|
+
italic: { around: '*', empty: 'italic text' },
|
|
35
|
+
code: { around: '`', empty: 'code' },
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** What a mark that works on whole lines puts in front of each. */
|
|
39
|
+
const PREFIXES: Partial<Record<MarkdownMark, (index: number) => string>> = {
|
|
40
|
+
heading: () => '## ',
|
|
41
|
+
bullets: () => '- ',
|
|
42
|
+
numbers: index => `${index + 1}. `,
|
|
43
|
+
quote: () => '> ',
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Any of the line marks, so one can be swapped for another instead of stacked. */
|
|
47
|
+
const ANY_PREFIX = /^(?:#{1,6} |[-*] |\d+\. |> )/
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Press a toolbar button: `mark` applied to `text`, with `start` to `end`
|
|
51
|
+
* selected.
|
|
52
|
+
*
|
|
53
|
+
* Bold, italic and code wrap the selection, or unwrap it when it is already
|
|
54
|
+
* wrapped; with nothing selected they insert a placeholder, selected, to
|
|
55
|
+
* type over. A link wraps the selection as its words and selects the address
|
|
56
|
+
* to replace. The line marks (heading, lists, quote) go in front of every
|
|
57
|
+
* line the selection touches, and come off again when they are all there.
|
|
58
|
+
*/
|
|
59
|
+
export function applyMarkdown(mark: MarkdownMark, text: string, start: number, end: number): MarkdownEdit {
|
|
60
|
+
const from = Math.max(0, Math.min(start, end, text.length))
|
|
61
|
+
const to = Math.max(from, Math.min(Math.max(start, end), text.length))
|
|
62
|
+
const selected = text.slice(from, to)
|
|
63
|
+
|
|
64
|
+
const wrap = WRAPS[mark]
|
|
65
|
+
if (wrap) {
|
|
66
|
+
const size = wrap.around.length
|
|
67
|
+
// Already wrapped, with the marks inside the selection or just outside it.
|
|
68
|
+
if (selected.length >= size * 2 && selected.startsWith(wrap.around) && selected.endsWith(wrap.around)) {
|
|
69
|
+
const inner = selected.slice(size, -size)
|
|
70
|
+
return { text: text.slice(0, from) + inner + text.slice(to), start: from, end: from + inner.length }
|
|
71
|
+
}
|
|
72
|
+
if (text.slice(from - size, from) === wrap.around && text.slice(to, to + size) === wrap.around)
|
|
73
|
+
return { text: text.slice(0, from - size) + selected + text.slice(to + size), start: from - size, end: to - size }
|
|
74
|
+
const inner = selected || wrap.empty
|
|
75
|
+
return { text: text.slice(0, from) + wrap.around + inner + wrap.around + text.slice(to), start: from + size, end: from + size + inner.length }
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
if (mark === 'link') {
|
|
79
|
+
const words = selected || 'link text'
|
|
80
|
+
const address = 'https://'
|
|
81
|
+
const before = `${text.slice(0, from)}[${words}](`
|
|
82
|
+
return { text: `${before}${address})${text.slice(to)}`, start: before.length, end: before.length + address.length }
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const prefix = PREFIXES[mark]
|
|
86
|
+
if (!prefix)
|
|
87
|
+
return { text, start: from, end: to }
|
|
88
|
+
// Every line the selection touches, whole.
|
|
89
|
+
const lineStart = text.lastIndexOf('\n', from - 1) + 1
|
|
90
|
+
const nextBreak = text.indexOf('\n', to)
|
|
91
|
+
const lineEnd = nextBreak === -1 ? text.length : nextBreak
|
|
92
|
+
const lines = text.slice(lineStart, lineEnd).split('\n')
|
|
93
|
+
const marked = lines.every((line, index) => line.startsWith(prefix(index)))
|
|
94
|
+
const changed = lines.map((line, index) => marked ? line.slice(prefix(index).length) : prefix(index) + line.replace(ANY_PREFIX, ''))
|
|
95
|
+
const block = changed.join('\n')
|
|
96
|
+
return { text: text.slice(0, lineStart) + block + text.slice(lineEnd), start: lineStart, end: lineStart + block.length }
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** How the Markdown reads, as sanitized HTML from the server. Nothing is stored. */
|
|
100
|
+
export async function fetchMarkdownPreview(text: string): Promise<string> {
|
|
101
|
+
const answer = await dashboardApi<{ html?: string }>('/api/dashboard/markdown', { method: 'POST', body: { text } })
|
|
102
|
+
return typeof answer?.html === 'string' ? answer.html : ''
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** What the preview's frame may load: nothing but its own styles and images. No script, ever. */
|
|
106
|
+
export const MARKDOWN_PREVIEW_POLICY = 'default-src \'none\'; img-src https: data:; style-src \'unsafe-inline\''
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* The document the preview's frame shows: the rendered HTML with enough
|
|
110
|
+
* style to read as prose, in the dashboard's light or dark. The frame is
|
|
111
|
+
* sandboxed and the policy forbids script, so the HTML is inert even if
|
|
112
|
+
* something got past the sanitizer.
|
|
113
|
+
*/
|
|
114
|
+
export function markdownPreviewDocument(html: string, dark: boolean): string {
|
|
115
|
+
const ink = dark ? '#e5e5e5' : '#171717'
|
|
116
|
+
const soft = dark ? '#a3a3a3' : '#525252'
|
|
117
|
+
const line = dark ? '#404040' : '#e5e5e5'
|
|
118
|
+
const wash = dark ? '#262626' : '#f5f5f5'
|
|
119
|
+
const link = dark ? '#60a5fa' : '#2563eb'
|
|
120
|
+
return `<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="${MARKDOWN_PREVIEW_POLICY}"><style>
|
|
121
|
+
html{color-scheme:${dark ? 'dark' : 'light'}}
|
|
122
|
+
body{margin:0;padding:12px 14px;font:14px/1.6 ui-sans-serif,system-ui,-apple-system,"Segoe UI",sans-serif;color:${ink};background:transparent;overflow-wrap:anywhere}
|
|
123
|
+
h1,h2,h3,h4{line-height:1.3;margin:1.2em 0 .5em}h1{font-size:1.5em}h2{font-size:1.25em}h3{font-size:1.1em}
|
|
124
|
+
p,ul,ol,blockquote,pre,table{margin:0 0 .9em}ul,ol{padding-left:1.4em}
|
|
125
|
+
a{color:${link}}img{max-width:100%;height:auto}
|
|
126
|
+
blockquote{padding-left:.9em;border-left:3px solid ${line};color:${soft}}
|
|
127
|
+
code{padding:.1em .3em;font:.9em ui-monospace,SFMono-Regular,Menlo,monospace;background:${wash};border-radius:4px}
|
|
128
|
+
pre{padding:.7em .9em;overflow-x:auto;background:${wash};border-radius:6px}pre code{padding:0;background:none}
|
|
129
|
+
table{border-collapse:collapse}th,td{padding:.3em .6em;border:1px solid ${line}}hr{border:0;border-top:1px solid ${line}}
|
|
130
|
+
body>:first-child{margin-top:0}body>:last-child{margin-bottom:0}
|
|
131
|
+
</style></head><body>${html}</body></html>`
|
|
132
|
+
}
|
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Acting on the rows selected in a model's list: one of the model's own
|
|
3
|
+
* actions (`on: ['bulk']`), or a delete.
|
|
4
|
+
*
|
|
5
|
+
* A selection is acted on one record at a time, each through the endpoint a
|
|
6
|
+
* single row uses, so every guard a single press has applies to each record
|
|
7
|
+
* and nothing about an action changes for it. It is not all or nothing and
|
|
8
|
+
* does not claim to be (a write through a model takes no part in a
|
|
9
|
+
* transaction, stacksjs/stacks#3269): what is reported is what happened, how
|
|
10
|
+
* many were done and, for the rest, which and why.
|
|
11
|
+
*/
|
|
12
|
+
import { DashboardApiError } from './dashboard-api'
|
|
13
|
+
import type { ModelActionResult, ModelCustomAction, ModelDeleteOutcome } from './dashboard-model-record'
|
|
14
|
+
import { deleteModelRecord, runModelAction } from './dashboard-model-record'
|
|
15
|
+
|
|
16
|
+
export interface ModelBulkFailure {
|
|
17
|
+
id: string
|
|
18
|
+
/** Why, in the words the refusal came back with. */
|
|
19
|
+
error: string
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface ModelBulkResult {
|
|
23
|
+
/** How many records were to be acted on. */
|
|
24
|
+
total: number
|
|
25
|
+
done: number
|
|
26
|
+
/** Of the ones done by a delete: kept, with their personal details removed. */
|
|
27
|
+
anonymized: number
|
|
28
|
+
/** The records that were refused, in the order they were tried. */
|
|
29
|
+
failed: ModelBulkFailure[]
|
|
30
|
+
/** Why the run stopped early, when it did. The records after it were not attempted. */
|
|
31
|
+
stopped: string
|
|
32
|
+
/** The record the run stopped at. It was tried, and not done. */
|
|
33
|
+
stoppedAt: string
|
|
34
|
+
/**
|
|
35
|
+
* The input itself was refused, by the first record tried: the messages
|
|
36
|
+
* for its fields. Nothing ran, and the form that asked can show them.
|
|
37
|
+
* Empty otherwise.
|
|
38
|
+
*/
|
|
39
|
+
invalid: Record<string, string[]>
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
type Attempt = { ok: true, anonymized?: boolean } | { ok: false, error: string, status: number, errors?: Record<string, string[]> }
|
|
43
|
+
|
|
44
|
+
/** The model's actions offered for a selection. */
|
|
45
|
+
export function modelBulkActions(actions: ModelCustomAction[] | undefined): ModelCustomAction[] {
|
|
46
|
+
return (actions ?? []).filter(action => action.places.includes('bulk'))
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* The selected rows an action is for. Which records an action applies to is
|
|
51
|
+
* the server's to say (its `when`, an erased account); a selected row it
|
|
52
|
+
* does not list for the action is left alone.
|
|
53
|
+
*/
|
|
54
|
+
export function modelBulkTargets(action: ModelCustomAction, rowActions: Record<string, string[]> | undefined, selected: string[]): string[] {
|
|
55
|
+
return selected.filter(id => (rowActions?.[id] ?? []).includes(action.name))
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** The selected rows a delete is for: every one that is not already anonymized. */
|
|
59
|
+
export function modelBulkDeleteTargets(selected: string[], anonymizedIds: string[]): string[] {
|
|
60
|
+
return selected.filter(id => !anonymizedIds.includes(id))
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* A refusal that is about the record (a rule it breaks, a state it is in)
|
|
65
|
+
* says nothing about the next one. One that is not (the server failing, the
|
|
66
|
+
* network gone) will be the same for all of them.
|
|
67
|
+
*/
|
|
68
|
+
function stopsTheRun(status: number): boolean {
|
|
69
|
+
return status === 0 || status >= 500
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Try each record in turn. A refused record is noted and the run goes on; a
|
|
74
|
+
* failure that is not about the record stops it, so a broken backend is not
|
|
75
|
+
* pressed a hundred times.
|
|
76
|
+
*/
|
|
77
|
+
export async function modelBulkRun(ids: string[], attempt: (id: string) => Promise<Attempt>, progress: (done: number, total: number) => void = () => {}): Promise<ModelBulkResult> {
|
|
78
|
+
const result: ModelBulkResult = { total: ids.length, done: 0, anonymized: 0, failed: [], stopped: '', stoppedAt: '', invalid: {} }
|
|
79
|
+
for (const [index, id] of ids.entries()) {
|
|
80
|
+
progress(index, ids.length)
|
|
81
|
+
const outcome = await attempt(id)
|
|
82
|
+
if (outcome.ok) {
|
|
83
|
+
result.done += 1
|
|
84
|
+
if (outcome.anonymized)
|
|
85
|
+
result.anonymized += 1
|
|
86
|
+
continue
|
|
87
|
+
}
|
|
88
|
+
// What was typed is the same for every record. If the first one says a
|
|
89
|
+
// field is wrong, so will the rest: back to the form, with nothing done.
|
|
90
|
+
if (index === 0 && outcome.errors && Object.keys(outcome.errors).length > 0) {
|
|
91
|
+
result.invalid = outcome.errors
|
|
92
|
+
break
|
|
93
|
+
}
|
|
94
|
+
if (stopsTheRun(outcome.status)) {
|
|
95
|
+
result.stopped = outcome.error
|
|
96
|
+
result.stoppedAt = id
|
|
97
|
+
break
|
|
98
|
+
}
|
|
99
|
+
result.failed.push({ id, error: outcome.error })
|
|
100
|
+
}
|
|
101
|
+
progress(ids.length, ids.length)
|
|
102
|
+
return result
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Run one of the model's own actions on each of these records. `input` is
|
|
107
|
+
* what its form was told, asked once and given to every record.
|
|
108
|
+
*/
|
|
109
|
+
export function runModelActionOnEach(
|
|
110
|
+
slug: string,
|
|
111
|
+
ids: string[],
|
|
112
|
+
name: string,
|
|
113
|
+
options: {
|
|
114
|
+
input?: Record<string, unknown>
|
|
115
|
+
progress?: (done: number, total: number) => void
|
|
116
|
+
run?: (slug: string, id: string, name: string, input: Record<string, unknown>) => Promise<ModelActionResult>
|
|
117
|
+
} = {},
|
|
118
|
+
): Promise<ModelBulkResult> {
|
|
119
|
+
const run = options.run ?? runModelAction
|
|
120
|
+
return modelBulkRun(ids, async (id) => {
|
|
121
|
+
const outcome = await run(slug, id, name, options.input ?? {})
|
|
122
|
+
return outcome.ok ? { ok: true } : { ok: false, error: outcome.error, status: outcome.status ?? 0, errors: outcome.errors }
|
|
123
|
+
}, options.progress)
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** Delete each of these records, as the trash on its row would. */
|
|
127
|
+
export function deleteModelRecords(
|
|
128
|
+
slug: string,
|
|
129
|
+
ids: string[],
|
|
130
|
+
progress?: (done: number, total: number) => void,
|
|
131
|
+
remove: (slug: string, id: string) => Promise<ModelDeleteOutcome> = deleteModelRecord,
|
|
132
|
+
): Promise<ModelBulkResult> {
|
|
133
|
+
return modelBulkRun(ids, async (id) => {
|
|
134
|
+
try {
|
|
135
|
+
return { ok: true, anonymized: (await remove(slug, id)) === 'anonymized' }
|
|
136
|
+
}
|
|
137
|
+
catch (reason) {
|
|
138
|
+
return { ok: false, error: reason instanceof Error ? reason.message : String(reason), status: reason instanceof DashboardApiError ? reason.status : 0 }
|
|
139
|
+
}
|
|
140
|
+
}, progress)
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function records(count: number): string {
|
|
144
|
+
return count === 1 ? 'record' : 'records'
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* How far an action on a selection reaches: how many of the selected records
|
|
149
|
+
* it will run on, and that each is done on its own.
|
|
150
|
+
*/
|
|
151
|
+
export function modelBulkActionScope(targets: number, selected: number): string {
|
|
152
|
+
const scope = targets === selected
|
|
153
|
+
? `It will run on the ${selected === 1 ? 'selected record' : `${selected} selected records`}.`
|
|
154
|
+
: `It will run on ${targets} of the ${selected} selected records. The other ${selected - targets === 1 ? 'one is not one' : `${selected - targets} are not ones`} it applies to.`
|
|
155
|
+
return [scope, targets > 1 ? 'Each record is done on its own: one that is refused does not stop the others.' : ''].filter(Boolean).join(' ')
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** What the confirmation says before one of the model's actions runs on a selection. */
|
|
159
|
+
export function modelBulkActionConfirm(action: ModelCustomAction, targets: number, selected: number): { title: string, description: string } {
|
|
160
|
+
return {
|
|
161
|
+
title: `${action.label}?`,
|
|
162
|
+
// The model's own sentence about what happens, then how far it reaches.
|
|
163
|
+
description: [action.confirm, modelBulkActionScope(targets, selected)].filter(Boolean).join(' '),
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** What the confirmation says before a selection is deleted. */
|
|
168
|
+
export function modelBulkDeleteConfirm(targets: number, selected: number, anonymizes: boolean): { title: string, description: string } {
|
|
169
|
+
const skipped = selected - targets
|
|
170
|
+
return {
|
|
171
|
+
title: `Delete ${targets === 1 ? 'this record' : `these ${targets} records`}?`,
|
|
172
|
+
description: [
|
|
173
|
+
`${targets === 1 ? 'It' : 'They'} will be deleted. This cannot be undone from the dashboard.`,
|
|
174
|
+
anonymizes ? 'An account other records still refer to is anonymized instead: its name and email are removed, sign-in is revoked and those records are kept.' : '',
|
|
175
|
+
skipped > 0 ? `${skipped === 1 ? 'One of the selected is' : `${skipped} of the selected are`} already anonymized and left alone.` : '',
|
|
176
|
+
targets > 1 ? 'Each record is deleted on its own: one that is refused does not stop the others.' : '',
|
|
177
|
+
].filter(Boolean).join(' '),
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** The most refusals a toast spells out before it counts the rest. */
|
|
182
|
+
const SPELLED_OUT = 3
|
|
183
|
+
|
|
184
|
+
function refusals(result: ModelBulkResult, modelName: string): string {
|
|
185
|
+
const said = result.failed.slice(0, SPELLED_OUT).map(failure => `${modelName} ${failure.id}: ${failure.error.replace(/[.\s]+$/, '')}.`)
|
|
186
|
+
const more = result.failed.length - said.length
|
|
187
|
+
if (more > 0)
|
|
188
|
+
said.push(`And ${more} more.`)
|
|
189
|
+
if (result.stopped) {
|
|
190
|
+
// The record it stopped at was tried; the ones after it were not.
|
|
191
|
+
const untried = result.total - result.done - result.failed.length - 1
|
|
192
|
+
said.push(`Stopped at ${modelName} ${result.stoppedAt}: ${result.stopped.replace(/[.\s]+$/, '')}.`)
|
|
193
|
+
if (untried > 0)
|
|
194
|
+
said.push(`The ${untried === 1 ? 'one' : untried} after it ${untried === 1 ? 'was' : 'were'} not attempted.`)
|
|
195
|
+
}
|
|
196
|
+
return said.join(' ')
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* The toast after a selection was acted on: what happened, in numbers, and
|
|
201
|
+
* for the records that were not done, which and why.
|
|
202
|
+
*/
|
|
203
|
+
export function modelBulkNotice(
|
|
204
|
+
what: { kind: 'action', label: string } | { kind: 'delete' },
|
|
205
|
+
modelName: string,
|
|
206
|
+
result: ModelBulkResult,
|
|
207
|
+
): { tone: 'success' | 'warning' | 'error', title: string, detail: string } {
|
|
208
|
+
const clean = result.failed.length === 0 && !result.stopped
|
|
209
|
+
if (what.kind === 'delete') {
|
|
210
|
+
const gone = result.done - result.anonymized
|
|
211
|
+
const counted = [gone > 0 ? `${gone} deleted` : '', result.anonymized > 0 ? `${result.anonymized} anonymized` : ''].filter(Boolean).join(', ')
|
|
212
|
+
const kept = result.anonymized > 0 ? 'Other records still refer to the anonymized accounts, so they were kept with their name and email removed.' : ''
|
|
213
|
+
if (clean)
|
|
214
|
+
return { tone: 'success', title: counted || 'Nothing to delete', detail: kept }
|
|
215
|
+
return { tone: result.done > 0 ? 'warning' : 'error', title: result.done > 0 ? `${counted}, ${result.total - result.done} not` : 'Could not delete', detail: [refusals(result, modelName), kept].filter(Boolean).join(' ') }
|
|
216
|
+
}
|
|
217
|
+
if (clean)
|
|
218
|
+
return { tone: 'success', title: what.label, detail: `Done for ${result.done} ${records(result.done)}.` }
|
|
219
|
+
return {
|
|
220
|
+
tone: result.done > 0 ? 'warning' : 'error',
|
|
221
|
+
title: result.done > 0 ? `${what.label}: ${result.done} of ${result.total} done` : `${what.label} did not run`,
|
|
222
|
+
detail: refusals(result, modelName),
|
|
223
|
+
}
|
|
224
|
+
}
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* How a model field's stored value reads, where the model says how
|
|
3
|
+
* (`dashboard.fields.<name>.format`): 1200 as "$12.00", 1536 as "1.5 KB".
|
|
4
|
+
*
|
|
5
|
+
* One function for the list, the record's page and the panels, so a value
|
|
6
|
+
* reads the same wherever it is shown. Formatting happens here and not on
|
|
7
|
+
* the server because it follows the viewer: their locale for a number and a
|
|
8
|
+
* date, their time zone for a moment.
|
|
9
|
+
*/
|
|
10
|
+
import { formatCurrency } from '@stacksjs/commerce/money'
|
|
11
|
+
import { parseDashboardDate } from './dashboard-dates'
|
|
12
|
+
|
|
13
|
+
export type ModelFieldFormat = 'badge' | 'bytes' | 'code' | 'date' | 'datetime' | 'duration' | 'image' | 'link' | 'money' | 'number' | 'percent' | 'text'
|
|
14
|
+
|
|
15
|
+
/** A format, with what it needs to be read: see `model-fields` on the server. */
|
|
16
|
+
export interface ModelFieldDisplay {
|
|
17
|
+
format: ModelFieldFormat
|
|
18
|
+
/** For `money`: the ISO code every amount is in. */
|
|
19
|
+
currency?: string
|
|
20
|
+
/** For `money`: the column holding each row's own ISO code. */
|
|
21
|
+
currencyColumn?: string
|
|
22
|
+
/** For `duration`: what the stored number counts. Milliseconds unless said. */
|
|
23
|
+
unit?: 'ms' | 's'
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** What a status-like word says: settled, ended, under way, or neither. */
|
|
27
|
+
export type ModelBadgeTone = 'positive' | 'negative' | 'pending' | 'neutral'
|
|
28
|
+
|
|
29
|
+
export interface ModelFormattedValue {
|
|
30
|
+
/** How it is drawn: words, a pill, a link out, a thumbnail, a code font. */
|
|
31
|
+
kind: 'text' | 'badge' | 'link' | 'image' | 'code'
|
|
32
|
+
text: string
|
|
33
|
+
/** Where a link leads, or what an image draws. */
|
|
34
|
+
href?: string
|
|
35
|
+
/** For a pill: what its word says, for its colour. */
|
|
36
|
+
tone?: ModelBadgeTone
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Columns whose value is one word out of a few: drawn as a pill. */
|
|
40
|
+
export const MODEL_BADGE_COLUMNS: ReadonlySet<string> = new Set(['status', 'state', 'type', 'role', 'source', 'plan', 'category', 'kind', 'channel', 'driver', 'priority', 'visibility', 'guard_name', 'provider', 'locale', 'currency'])
|
|
41
|
+
|
|
42
|
+
const POSITIVE: ReadonlySet<string> = new Set(['active', 'approved', 'completed', 'delivered', 'done', 'enabled', 'healthy', 'live', 'paid', 'published', 'resolved', 'subscribed', 'succeeded', 'success', 'verified'])
|
|
43
|
+
const NEGATIVE: ReadonlySet<string> = new Set(['banned', 'blocked', 'bounced', 'canceled', 'cancelled', 'declined', 'disabled', 'error', 'expired', 'failed', 'inactive', 'rejected', 'revoked', 'suspended', 'unsubscribed'])
|
|
44
|
+
const PENDING: ReadonlySet<string> = new Set(['draft', 'in_progress', 'invited', 'pending', 'processing', 'queued', 'review', 'scheduled', 'trialing', 'unverified'])
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* What a status-like word says. Only the words that say it: a role or a
|
|
48
|
+
* plan is a word out of a few too, and "admin" is neither good news nor bad.
|
|
49
|
+
*/
|
|
50
|
+
export function modelBadgeTone(word: unknown): ModelBadgeTone {
|
|
51
|
+
const said = String(word ?? '').trim().toLowerCase().replace(/[\s-]+/g, '_')
|
|
52
|
+
if (POSITIVE.has(said))
|
|
53
|
+
return 'positive'
|
|
54
|
+
if (NEGATIVE.has(said))
|
|
55
|
+
return 'negative'
|
|
56
|
+
return PENDING.has(said) ? 'pending' : 'neutral'
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* How a cell reads when the model says (`format`), or when its column is one
|
|
61
|
+
* the dashboard knows as a status-like word. Null when neither, or when
|
|
62
|
+
* nothing is stored: the caller words those itself.
|
|
63
|
+
*/
|
|
64
|
+
export function modelCellDisplay(column: { name: string, format?: ModelFieldDisplay }, value: unknown, row: Record<string, unknown> = {}): ModelFormattedValue | null {
|
|
65
|
+
if (column.format)
|
|
66
|
+
return modelFormattedValue(value, column.format, row)
|
|
67
|
+
if (MODEL_BADGE_COLUMNS.has(column.name) && typeof value === 'string' && value !== '' && value.length <= 32)
|
|
68
|
+
return { kind: 'badge', text: titleCase(value), tone: modelBadgeTone(value) }
|
|
69
|
+
return null
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const NUMERIC: ReadonlySet<ModelFieldFormat> = new Set(['bytes', 'duration', 'money', 'number', 'percent'])
|
|
73
|
+
|
|
74
|
+
/** Whether a column is read as an amount, and so lines up on the right. */
|
|
75
|
+
export function modelColumnIsNumeric(column: { type?: string, format?: ModelFieldDisplay }): boolean {
|
|
76
|
+
return column.format ? NUMERIC.has(column.format.format) : column.type === 'number'
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Whether a column is a day or a moment. */
|
|
80
|
+
export function modelColumnIsDate(column: { name: string, type?: string, format?: ModelFieldDisplay }): boolean {
|
|
81
|
+
if (column.format)
|
|
82
|
+
return column.format.format === 'date' || column.format.format === 'datetime'
|
|
83
|
+
return column.type === 'date' || /_(?:at|on)$/.test(column.name)
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function trimmed(value: number, digits: number): string {
|
|
87
|
+
return value.toLocaleString(undefined, { maximumFractionDigits: digits })
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const BYTE_UNITS = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']
|
|
91
|
+
|
|
92
|
+
/** A size in the largest unit that keeps it above one: 1536 is "1.5 KB". */
|
|
93
|
+
export function modelByteSize(bytes: number): string {
|
|
94
|
+
let value = Math.abs(bytes)
|
|
95
|
+
let unit = 0
|
|
96
|
+
while (value >= 1024 && unit < BYTE_UNITS.length - 1) {
|
|
97
|
+
value /= 1024
|
|
98
|
+
unit += 1
|
|
99
|
+
}
|
|
100
|
+
// Rounding 1023.96 KB would print "1,024 KB": that is 1 MB.
|
|
101
|
+
if (unit > 0 && unit < BYTE_UNITS.length - 1 && Number(value.toFixed(1)) >= 1024) {
|
|
102
|
+
value /= 1024
|
|
103
|
+
unit += 1
|
|
104
|
+
}
|
|
105
|
+
return `${bytes < 0 ? '-' : ''}${trimmed(value, unit === 0 ? 0 : 1)} ${BYTE_UNITS[unit]}`
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* A length of time in the two largest units that say it: 83000 ms is
|
|
110
|
+
* "1 min 23 s", 420 ms is "420 ms", 1250 ms is "1.3 s".
|
|
111
|
+
*/
|
|
112
|
+
export function modelDuration(value: number, unit: 'ms' | 's' = 'ms'): string {
|
|
113
|
+
const milliseconds = Math.abs(unit === 's' ? value * 1000 : value)
|
|
114
|
+
const sign = value < 0 ? '-' : ''
|
|
115
|
+
if (milliseconds < 999.5)
|
|
116
|
+
return `${sign}${trimmed(milliseconds, milliseconds < 10 ? 2 : 0)} ms`
|
|
117
|
+
if (milliseconds < 59_950)
|
|
118
|
+
return `${sign}${trimmed(milliseconds / 1000, 1)} s`
|
|
119
|
+
// Whole seconds from here, rounded once, so a part never reads "60 s".
|
|
120
|
+
const seconds = Math.round(milliseconds / 1000)
|
|
121
|
+
const parts: Array<[number, string]> = [
|
|
122
|
+
[Math.floor(seconds / 86_400), 'd'],
|
|
123
|
+
[Math.floor(seconds % 86_400 / 3600), 'h'],
|
|
124
|
+
[Math.floor(seconds % 3600 / 60), 'min'],
|
|
125
|
+
[seconds % 60, 's'],
|
|
126
|
+
]
|
|
127
|
+
const first = parts.findIndex(([amount]) => amount > 0)
|
|
128
|
+
return sign + parts.slice(first, first + 2).filter(([amount]) => amount > 0).map(([amount, name]) => `${amount} ${name}`).join(' ')
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function titleCase(words: string): string {
|
|
132
|
+
return words.replace(/[_-]+/g, ' ').replace(/\b[a-z]/g, letter => letter.toUpperCase())
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** A web or mail address a link may lead to. Nothing else: never `javascript:`. */
|
|
136
|
+
function linkTarget(text: string): string {
|
|
137
|
+
if (/^https?:\/\/\S+$/i.test(text) || /^mailto:\S+@\S+$/i.test(text))
|
|
138
|
+
return text
|
|
139
|
+
return /^[^\s@/]+@[^\s@/]+\.[^\s@/]+$/.test(text) ? `mailto:${text}` : ''
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** A web address or a path on this site an image may be drawn from. */
|
|
143
|
+
function imageSource(text: string): string {
|
|
144
|
+
return /^https?:\/\/\S+$/i.test(text) || /^\/(?!\/)\S*$/.test(text) ? text : ''
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* A stored value as the model says it reads. Null when nothing is stored:
|
|
149
|
+
* what an empty field says is the page's to decide.
|
|
150
|
+
*
|
|
151
|
+
* A value the format cannot read (text where an amount was expected) is
|
|
152
|
+
* shown as stored, never dropped and never dressed up as a number.
|
|
153
|
+
*/
|
|
154
|
+
export function modelFormattedValue(value: unknown, display: ModelFieldDisplay, row: Record<string, unknown> = {}): ModelFormattedValue | null {
|
|
155
|
+
if (value === null || value === undefined || value === '')
|
|
156
|
+
return null
|
|
157
|
+
const stored = typeof value === 'object' && !(value instanceof Date) ? JSON.stringify(value) : String(value)
|
|
158
|
+
const plain: ModelFormattedValue = { kind: 'text', text: stored }
|
|
159
|
+
const amount = typeof value === 'number' ? value : typeof value === 'string' && value.trim() !== '' ? Number(value) : Number.NaN
|
|
160
|
+
|
|
161
|
+
switch (display.format) {
|
|
162
|
+
case 'money': {
|
|
163
|
+
if (!Number.isFinite(amount))
|
|
164
|
+
return plain
|
|
165
|
+
const own = display.currencyColumn ? row[display.currencyColumn] : undefined
|
|
166
|
+
return { kind: 'text', text: formatCurrency(amount, typeof own === 'string' && own ? own : display.currency) }
|
|
167
|
+
}
|
|
168
|
+
case 'number':
|
|
169
|
+
return Number.isFinite(amount) ? { kind: 'text', text: amount.toLocaleString() } : plain
|
|
170
|
+
case 'percent':
|
|
171
|
+
return Number.isFinite(amount) ? { kind: 'text', text: `${trimmed(amount, 2)}%` } : plain
|
|
172
|
+
case 'bytes':
|
|
173
|
+
return Number.isFinite(amount) ? { kind: 'text', text: modelByteSize(amount) } : plain
|
|
174
|
+
case 'duration':
|
|
175
|
+
return Number.isFinite(amount) ? { kind: 'text', text: modelDuration(amount, display.unit) } : plain
|
|
176
|
+
case 'date':
|
|
177
|
+
case 'datetime': {
|
|
178
|
+
// A number is a unix time, in seconds unless it is too large to be.
|
|
179
|
+
const at = typeof value === 'number' ? new Date(value < 1e12 ? value * 1000 : value) : parseDashboardDate(value)
|
|
180
|
+
if (Number.isNaN(at.getTime()))
|
|
181
|
+
return plain
|
|
182
|
+
const options: Intl.DateTimeFormatOptions = display.format === 'date' ? { dateStyle: 'medium' } : { dateStyle: 'medium', timeStyle: 'short' }
|
|
183
|
+
return { kind: 'text', text: new Intl.DateTimeFormat(undefined, options).format(at) }
|
|
184
|
+
}
|
|
185
|
+
case 'badge':
|
|
186
|
+
return { kind: 'badge', text: titleCase(stored), tone: modelBadgeTone(stored) }
|
|
187
|
+
case 'link': {
|
|
188
|
+
const href = linkTarget(stored.trim())
|
|
189
|
+
// Without the scheme: it is the same on every row and says nothing.
|
|
190
|
+
return href ? { kind: 'link', text: stored.trim().replace(/^(?:https?:\/\/|mailto:)/i, '').replace(/\/$/, ''), href } : plain
|
|
191
|
+
}
|
|
192
|
+
case 'image': {
|
|
193
|
+
const href = imageSource(stored.trim())
|
|
194
|
+
return href ? { kind: 'image', text: stored.trim(), href } : plain
|
|
195
|
+
}
|
|
196
|
+
case 'code':
|
|
197
|
+
return { kind: 'code', text: stored }
|
|
198
|
+
default:
|
|
199
|
+
return plain
|
|
200
|
+
}
|
|
201
|
+
}
|