@appstrate/ui 1.0.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/LICENSE ADDED
@@ -0,0 +1,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to the Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by the Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding any notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2025-2026 Appstrate
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,5 @@
1
+ Appstrate UI
2
+ Copyright 2025-2026 Appstrate
3
+
4
+ This product includes software developed at
5
+ Appstrate (https://appstrate.dev).
package/README.md ADDED
@@ -0,0 +1,40 @@
1
+ # @appstrate/ui
2
+
3
+ Shared React UI components for Appstrate surfaces — schema-driven forms, upload widget, RJSF templates.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ bun add @appstrate/ui
9
+ ```
10
+
11
+ Peer deps: `react` 19, `react-dom` 19, `@rjsf/core` ^6, `@rjsf/utils` ^6, `@rjsf/validator-ajv8` ^6, `lucide-react`, `react-select` ^5, `@appstrate/core` ^2.10, `typescript` ^5.
12
+
13
+ The package ships raw `.tsx` sources (no build step) — consumers are expected to transpile via their bundler (Vite, Next.js, etc.). Same convention as `@appstrate/core`.
14
+
15
+ Designed to be consumed by any Appstrate surface (main app, portal, future dashboards) so schema forms render identically everywhere.
16
+
17
+ ## Usage
18
+
19
+ ```tsx
20
+ import { SchemaForm } from "@appstrate/ui/schema-form";
21
+
22
+ <SchemaForm
23
+ wrapper={manifest.input}
24
+ formData={values}
25
+ uploadPath="/api/uploads"
26
+ labels={labels}
27
+ onChange={(e) => setValues(e.formData)}
28
+ onSubmit={(e) => submit(e.formData)}
29
+ />;
30
+ ```
31
+
32
+ The widget is i18n-agnostic — pass translated strings via `labels`. See `apps/web/src/hooks/use-schema-form-labels.ts` for the i18next bridge used by the Appstrate platform.
33
+
34
+ ## Exports
35
+
36
+ - `./schema-form` — `SchemaForm` component, `FileWidgetLabels` type, RJSF widgets/templates.
37
+
38
+ ## License
39
+
40
+ Apache-2.0
package/package.json ADDED
@@ -0,0 +1,74 @@
1
+ {
2
+ "name": "@appstrate/ui",
3
+ "version": "1.0.0",
4
+ "description": "Shared React UI components for Appstrate surfaces — schema-driven forms, upload widget, RJSF templates",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "engines": {
8
+ "bun": ">=1.3.9"
9
+ },
10
+ "publishConfig": {
11
+ "access": "public",
12
+ "provenance": true
13
+ },
14
+ "sideEffects": false,
15
+ "author": "Appstrate <hello@appstrate.dev>",
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "https://github.com/appstrate/appstrate.git",
19
+ "directory": "packages/ui"
20
+ },
21
+ "homepage": "https://github.com/appstrate/appstrate/tree/main/packages/ui",
22
+ "bugs": {
23
+ "url": "https://github.com/appstrate/appstrate/issues"
24
+ },
25
+ "keywords": [
26
+ "appstrate",
27
+ "ui",
28
+ "react",
29
+ "rjsf",
30
+ "schema-form",
31
+ "afps"
32
+ ],
33
+ "files": [
34
+ "src",
35
+ "LICENSE",
36
+ "NOTICE"
37
+ ],
38
+ "exports": {
39
+ "./schema-form": "./src/schema-form/index.tsx"
40
+ },
41
+ "dependencies": {
42
+ "tailwind-merge": "^3.0.0"
43
+ },
44
+ "peerDependencies": {
45
+ "@appstrate/core": "^2.10.0",
46
+ "@rjsf/core": "^6",
47
+ "@rjsf/utils": "^6",
48
+ "@rjsf/validator-ajv8": "^6",
49
+ "lucide-react": ">=0.400.0",
50
+ "react": "^19",
51
+ "react-dom": "^19",
52
+ "react-select": "^5",
53
+ "typescript": "^5"
54
+ },
55
+ "devDependencies": {
56
+ "@appstrate/core": "workspace:*",
57
+ "@types/bun": "^1.3.9",
58
+ "@rjsf/core": "^6.4.2",
59
+ "@rjsf/utils": "^6.4.2",
60
+ "@rjsf/validator-ajv8": "^6.4.2",
61
+ "@types/react": "^19.0.0",
62
+ "@types/react-dom": "^19.0.0",
63
+ "lucide-react": "^1.8.0",
64
+ "react": "^19.2.5",
65
+ "react-dom": "^19.2.5",
66
+ "react-select": "^5.10.2",
67
+ "typescript": "^5.7.0"
68
+ },
69
+ "scripts": {
70
+ "typecheck": "tsc --noEmit",
71
+ "check": "tsc --noEmit",
72
+ "test": "bun test"
73
+ }
74
+ }
@@ -0,0 +1,11 @@
1
+ // Copyright 2025-2026 Appstrate
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ // Thin wrapper around `tailwind-merge` so conflicting Tailwind utilities
5
+ // (e.g. base `border-input` + conditional `border-destructive`) resolve
6
+ // deterministically by attribute order rather than CSS source order.
7
+ import { twMerge } from "tailwind-merge";
8
+
9
+ export function cn(...inputs: (string | false | null | undefined)[]): string {
10
+ return twMerge(inputs.filter(Boolean).join(" "));
11
+ }
@@ -0,0 +1,16 @@
1
+ // Copyright 2025-2026 Appstrate
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import type { FileWidgetLabels } from "./file-widget.tsx";
5
+ import type { UploadFn } from "./upload-client.ts";
6
+
7
+ /**
8
+ * Shape of `formContext` that `SchemaForm` feeds to RJSF templates and
9
+ * widgets. Templates should read it via `registry.formContext as SchemaFormContext`
10
+ * rather than re-declaring ad-hoc types.
11
+ */
12
+ export interface SchemaFormContext {
13
+ uploadPath?: string;
14
+ upload?: UploadFn;
15
+ labels?: FileWidgetLabels & { addItem?: string };
16
+ }
@@ -0,0 +1,278 @@
1
+ // Copyright 2025-2026 Appstrate
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import { useRef, useState, useCallback, useEffect, useMemo } from "react";
5
+ import { X } from "lucide-react";
6
+ import type { WidgetProps } from "@rjsf/utils";
7
+ import { Button, LABEL_CLASS } from "./primitives.tsx";
8
+ import { cn } from "./cn.ts";
9
+ import { createUploader, isUploadUri, type UploadFn } from "./upload-client.ts";
10
+ import type { SchemaFormContext } from "./context.ts";
11
+
12
+ function formatSize(bytes: number): string {
13
+ if (bytes < 1024) return `${bytes} B`;
14
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
15
+ return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;
16
+ }
17
+
18
+ interface Attachment {
19
+ uri: string;
20
+ name: string;
21
+ size: number;
22
+ }
23
+
24
+ function attachmentsFromValue(value: unknown): Attachment[] {
25
+ const list: Attachment[] = [];
26
+ const raw = Array.isArray(value) ? value : value != null ? [value] : [];
27
+ for (const v of raw) {
28
+ if (isUploadUri(v)) {
29
+ const tail = v.slice("upload://".length);
30
+ list.push({ uri: v, name: tail, size: 0 });
31
+ }
32
+ }
33
+ return list;
34
+ }
35
+
36
+ /**
37
+ * Labels consumed by FileWidget. Callers can pass translated strings via
38
+ * `<SchemaForm labels={...}>` so the widget integrates with the host app's
39
+ * i18n system without this package taking a hard dependency on i18next.
40
+ */
41
+ export interface FileWidgetLabels {
42
+ uploading?: string;
43
+ dragDrop?: string;
44
+ addFile?: string;
45
+ uploadsDisabled?: string;
46
+ maxSize?: (size: string) => string;
47
+ maxFiles?: (count: number) => string;
48
+ formats?: (formats: string) => string;
49
+ extError?: (name: string, accept: string) => string;
50
+ sizeError?: (name: string, size: string) => string;
51
+ }
52
+
53
+ const DEFAULT_LABELS: Required<FileWidgetLabels> = {
54
+ uploading: "Uploading…",
55
+ dragDrop: "Drag and drop a file here, or click to select",
56
+ addFile: "Add file",
57
+ uploadsDisabled: "File uploads are not configured for this form.",
58
+ maxSize: (size) => `Max ${size}`,
59
+ maxFiles: (count) => `At most ${count} files allowed`,
60
+ formats: (formats) => `Formats: ${formats}`,
61
+ extError: (name, accept) => `${name} is not a supported format (${accept})`,
62
+ sizeError: (name, size) => `${name} exceeds the ${size} size limit`,
63
+ };
64
+
65
+ /**
66
+ * RJSF file widget. Accepts:
67
+ * - `{ type: "string", format: "uri", contentMediaType }` → single
68
+ * - `{ type: "array", items: { type: "string", format: "uri", … } }` → multi
69
+ *
70
+ * The binary is uploaded directly to storage via the endpoint resolved from
71
+ * `formContext.uploadPath` (POST), and `onChange` writes back an
72
+ * `upload://upl_xxx` URI (or array of URIs). RJSF then validates the schema
73
+ * on this URI — the server re-validates when the run is triggered.
74
+ */
75
+ export function FileWidget(props: WidgetProps) {
76
+ const { id, value, onChange, required, label, schema, disabled, readonly, options, formContext } =
77
+ props;
78
+ const ctx = (formContext ?? {}) as SchemaFormContext;
79
+ const labels = useMemo<Required<FileWidgetLabels>>(
80
+ () => ({ ...DEFAULT_LABELS, ...(ctx.labels ?? {}) }),
81
+ [ctx.labels],
82
+ );
83
+ const upload = useMemo<UploadFn | null>(
84
+ () => ctx.upload ?? (ctx.uploadPath ? createUploader(ctx.uploadPath) : null),
85
+ [ctx.upload, ctx.uploadPath],
86
+ );
87
+
88
+ const inputRef = useRef<HTMLInputElement>(null);
89
+ const [uploading, setUploading] = useState(false);
90
+ const [dragOver, setDragOver] = useState(false);
91
+ const [error, setError] = useState<string | null>(null);
92
+ const [attachments, setAttachments] = useState<Attachment[]>(() => attachmentsFromValue(value));
93
+ const abortRef = useRef<AbortController | null>(null);
94
+ useEffect(() => () => abortRef.current?.abort(), []);
95
+
96
+ const multiple = schema.type === "array" || (options?.multiple as boolean | undefined) === true;
97
+ const accept = (options?.accept as string | undefined) ?? undefined;
98
+ const maxSize = options?.maxSize as number | undefined;
99
+ const maxFiles = options?.maxFiles as number | undefined;
100
+
101
+ const commit = useCallback(
102
+ (next: Attachment[]) => {
103
+ setAttachments(next);
104
+ if (multiple) {
105
+ onChange(next.map((a) => a.uri));
106
+ } else {
107
+ onChange(next[0]?.uri);
108
+ }
109
+ },
110
+ [multiple, onChange],
111
+ );
112
+
113
+ const addFiles = useCallback(
114
+ async (incoming: File[]) => {
115
+ setError(null);
116
+ if (!upload) {
117
+ setError(labels.uploadsDisabled);
118
+ return;
119
+ }
120
+ for (const f of incoming) {
121
+ if (accept) {
122
+ const allowed = accept
123
+ .split(",")
124
+ .map((e) => e.trim().toLowerCase())
125
+ .filter(Boolean);
126
+ const ext = f.name.includes(".") ? `.${f.name.split(".").pop()!.toLowerCase()}` : "";
127
+ const mimeMatch = allowed.some((a) => {
128
+ if (a.startsWith(".")) return a === ext;
129
+ if (a.endsWith("/*")) return f.type.startsWith(a.slice(0, -1));
130
+ return f.type === a;
131
+ });
132
+ if (!mimeMatch) {
133
+ setError(labels.extError(f.name, accept));
134
+ return;
135
+ }
136
+ }
137
+ if (maxSize && f.size > maxSize) {
138
+ setError(labels.sizeError(f.name, formatSize(maxSize)));
139
+ return;
140
+ }
141
+ }
142
+ const willHave = attachments.length + incoming.length;
143
+ if (multiple && maxFiles && willHave > maxFiles) {
144
+ setError(labels.maxFiles(maxFiles));
145
+ return;
146
+ }
147
+
148
+ setUploading(true);
149
+ abortRef.current?.abort();
150
+ const ctrl = new AbortController();
151
+ abortRef.current = ctrl;
152
+ try {
153
+ const uploaded: Attachment[] = [];
154
+ for (const f of incoming) {
155
+ const uri = await upload(f, ctrl.signal);
156
+ uploaded.push({ uri, name: f.name, size: f.size });
157
+ }
158
+ const next = multiple ? [...attachments, ...uploaded] : uploaded.slice(0, 1);
159
+ commit(next);
160
+ } catch (e) {
161
+ if ((e as { name?: string }).name === "AbortError") return;
162
+ setError(e instanceof Error ? e.message : String(e));
163
+ } finally {
164
+ setUploading(false);
165
+ if (abortRef.current === ctrl) abortRef.current = null;
166
+ }
167
+ },
168
+ [accept, attachments, commit, labels, maxFiles, maxSize, multiple, upload],
169
+ );
170
+
171
+ const handleDrop = (e: React.DragEvent) => {
172
+ e.preventDefault();
173
+ setDragOver(false);
174
+ const dropped = Array.from(e.dataTransfer.files);
175
+ if (dropped.length > 0) void addFiles(dropped);
176
+ };
177
+
178
+ const handleSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
179
+ const selected = Array.from(e.target.files || []);
180
+ if (selected.length > 0) void addFiles(selected);
181
+ e.target.value = "";
182
+ };
183
+
184
+ const remove = (idx: number) => {
185
+ commit(attachments.filter((_, i) => i !== idx));
186
+ setError(null);
187
+ };
188
+
189
+ const locked = disabled || readonly || uploading;
190
+
191
+ return (
192
+ <div className="space-y-2">
193
+ <label htmlFor={id} className={LABEL_CLASS}>
194
+ {label}
195
+ {required && " *"}
196
+ </label>
197
+ {attachments.length === 0 ? (
198
+ <div
199
+ role="button"
200
+ tabIndex={locked ? -1 : 0}
201
+ aria-disabled={locked || undefined}
202
+ aria-label={labels.addFile}
203
+ className={cn(
204
+ "text-muted-foreground hover:border-muted-foreground/50 focus-visible:ring-ring flex cursor-pointer flex-col items-center justify-center rounded-lg border-2 border-dashed p-6 text-center text-sm transition-colors focus-visible:ring-2 focus-visible:outline-none",
205
+ dragOver && "border-primary bg-primary/5",
206
+ locked && "pointer-events-none opacity-60",
207
+ )}
208
+ onClick={() => !locked && inputRef.current?.click()}
209
+ onKeyDown={(e) => {
210
+ if (locked) return;
211
+ if (e.key === "Enter" || e.key === " ") {
212
+ e.preventDefault();
213
+ inputRef.current?.click();
214
+ }
215
+ }}
216
+ onDragOver={(e) => {
217
+ e.preventDefault();
218
+ if (!locked) setDragOver(true);
219
+ }}
220
+ onDragLeave={() => setDragOver(false)}
221
+ onDrop={(e) => !locked && handleDrop(e)}
222
+ >
223
+ {uploading ? labels.uploading : labels.dragDrop}
224
+ {accept && <span className="mt-1 text-xs">{labels.formats(accept)}</span>}
225
+ {maxSize && <span className="mt-1 text-xs">{labels.maxSize(formatSize(maxSize))}</span>}
226
+ </div>
227
+ ) : (
228
+ <>
229
+ <div className="space-y-1">
230
+ {attachments.map((a, i) => (
231
+ <div
232
+ key={`${a.uri}-${i}`}
233
+ className="flex items-center justify-between rounded-md border px-3 py-2 text-sm"
234
+ >
235
+ <span className="truncate font-medium">{a.name}</span>
236
+ {a.size > 0 && (
237
+ <span className="text-muted-foreground ml-2 shrink-0">{formatSize(a.size)}</span>
238
+ )}
239
+ <Button
240
+ type="button"
241
+ variant="ghost"
242
+ size="icon"
243
+ className="text-muted-foreground ml-2 h-7 w-7 shrink-0"
244
+ disabled={locked}
245
+ onClick={() => remove(i)}
246
+ >
247
+ <X className="h-4 w-4" />
248
+ </Button>
249
+ </div>
250
+ ))}
251
+ </div>
252
+ {multiple && (!maxFiles || attachments.length < maxFiles) && (
253
+ <Button
254
+ type="button"
255
+ variant="outline"
256
+ size="sm"
257
+ disabled={locked}
258
+ onClick={() => inputRef.current?.click()}
259
+ >
260
+ {uploading ? labels.uploading : labels.addFile}
261
+ </Button>
262
+ )}
263
+ </>
264
+ )}
265
+ {error && <p className="text-destructive text-sm">{error}</p>}
266
+ <input
267
+ ref={inputRef}
268
+ id={id}
269
+ type="file"
270
+ accept={accept}
271
+ multiple={multiple}
272
+ disabled={locked}
273
+ onChange={handleSelect}
274
+ className="hidden"
275
+ />
276
+ </div>
277
+ );
278
+ }
@@ -0,0 +1,151 @@
1
+ // Copyright 2025-2026 Appstrate
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ /**
5
+ * Thin RJSF wrapper integrated with the Appstrate dark theme. Ships in
6
+ * `@appstrate/ui/schema-form` so every Appstrate frontend (main app,
7
+ * portal, future surfaces) renders AFPS input/config/output schemas
8
+ * identically.
9
+ *
10
+ * <SchemaForm
11
+ * wrapper={manifest.input}
12
+ * formData={…}
13
+ * onChange={…}
14
+ * onSubmit={…}
15
+ * uploadPath="/api/uploads"
16
+ * >
17
+ * {/* custom footer, or leave empty to let RJSF render a submit button *\/}
18
+ * </SchemaForm>
19
+ *
20
+ * The AFPS `SchemaWrapper` (schema + fileConstraints + uiHints + propertyOrder)
21
+ * is mapped to RJSF's `schema` + `uiSchema` by `@appstrate/core/form`. JSON
22
+ * Schema 2020-12 is used via `customizeValidator({ AjvClass: Ajv2020 })`.
23
+ */
24
+
25
+ import { forwardRef, useMemo, type ReactNode } from "react";
26
+ import type { FormProps as RjsfFormProps } from "@rjsf/core";
27
+ import RjsfForm from "@rjsf/core";
28
+ import { mapAfpsToRjsf, type SchemaWrapper } from "@appstrate/core/form";
29
+ import { schemaFormValidator } from "./validator.ts";
30
+ import {
31
+ BaseInputTemplate,
32
+ FieldTemplate,
33
+ TitleFieldTemplate,
34
+ DescriptionFieldTemplate,
35
+ ArrayFieldTemplate,
36
+ ArrayFieldItemTemplate,
37
+ ObjectFieldTemplate,
38
+ MultiSchemaFieldTemplate,
39
+ SubmitButton,
40
+ } from "./templates.tsx";
41
+ import {
42
+ FileWidget,
43
+ TextareaWidget,
44
+ CheckboxWidget,
45
+ SelectWidget,
46
+ MultiSelectWidget,
47
+ } from "./widgets.tsx";
48
+ import type { FileWidgetLabels } from "./file-widget.tsx";
49
+ import type { UploadFn } from "./upload-client.ts";
50
+
51
+ import type { SchemaFormContext } from "./context.ts";
52
+
53
+ export type { SchemaWrapper } from "@appstrate/core/form";
54
+ export type { FileWidgetLabels } from "./file-widget.tsx";
55
+ export type { UploadFn } from "./upload-client.ts";
56
+ export type { SchemaFormContext } from "./context.ts";
57
+
58
+ const widgets = {
59
+ file: FileWidget,
60
+ TextareaWidget,
61
+ CheckboxWidget,
62
+ SelectWidget,
63
+ multiselect: MultiSelectWidget,
64
+ };
65
+
66
+ const templates = {
67
+ BaseInputTemplate,
68
+ FieldTemplate,
69
+ TitleFieldTemplate,
70
+ DescriptionFieldTemplate,
71
+ ArrayFieldTemplate,
72
+ ArrayFieldItemTemplate,
73
+ ObjectFieldTemplate,
74
+ MultiSchemaFieldTemplate,
75
+ ButtonTemplates: { SubmitButton },
76
+ };
77
+
78
+ export interface SchemaFormProps extends Omit<
79
+ RjsfFormProps,
80
+ "schema" | "uiSchema" | "validator" | "widgets" | "templates" | "children" | "formContext"
81
+ > {
82
+ wrapper: SchemaWrapper;
83
+ /** Extra uiSchema merged on top of the AFPS-derived one. */
84
+ uiSchema?: Record<string, unknown>;
85
+ /** When true, render the default RJSF submit button. Default: false. */
86
+ showSubmitButton?: boolean;
87
+ /**
88
+ * Endpoint the `FileWidget` POSTs to for direct uploads. Must return an
89
+ * `UploadDescriptor`. Omit to disable uploads (the widget shows an error
90
+ * if the user tries to attach a file).
91
+ */
92
+ uploadPath?: string;
93
+ /** Escape hatch: provide your own uploader instead of the default fetch client. */
94
+ upload?: UploadFn;
95
+ /** Translated strings for the FileWidget. Defaults are English. */
96
+ labels?: FileWidgetLabels & { addItem?: string };
97
+ /** Extra formContext keys merged into what SchemaForm builds internally. */
98
+ formContext?: Record<string, unknown>;
99
+ children?: ReactNode;
100
+ }
101
+
102
+ /**
103
+ * Submit-button rendering is controlled by a single signal:
104
+ * `ui:submitButtonOptions.norender`. When `showSubmitButton` is false (default)
105
+ * we set `norender: true` and let RJSF render whatever `children` the caller
106
+ * passes as a footer (or nothing).
107
+ */
108
+ export const SchemaForm = forwardRef<RjsfForm, SchemaFormProps>(function SchemaForm(
109
+ {
110
+ wrapper,
111
+ showSubmitButton = false,
112
+ children,
113
+ uiSchema: extraUi,
114
+ uploadPath,
115
+ upload,
116
+ labels,
117
+ formContext,
118
+ ...rest
119
+ },
120
+ ref,
121
+ ) {
122
+ const mapped = mapAfpsToRjsf(wrapper);
123
+ const uiSchema = {
124
+ ...mapped.uiSchema,
125
+ ...(extraUi ?? {}),
126
+ ...(showSubmitButton ? {} : { "ui:submitButtonOptions": { norender: true } }),
127
+ };
128
+
129
+ // Stable identity so downstream `useMemo`s in FileWidget actually memoize.
130
+ const ctx = useMemo(
131
+ () =>
132
+ ({ ...(formContext ?? {}), uploadPath, upload, labels }) as SchemaFormContext &
133
+ Record<string, unknown>,
134
+ [formContext, uploadPath, upload, labels],
135
+ );
136
+
137
+ return (
138
+ <RjsfForm
139
+ ref={ref}
140
+ schema={mapped.schema as unknown as Record<string, unknown>}
141
+ uiSchema={uiSchema}
142
+ validator={schemaFormValidator}
143
+ widgets={widgets}
144
+ templates={templates}
145
+ formContext={ctx}
146
+ {...rest}
147
+ >
148
+ {children}
149
+ </RjsfForm>
150
+ );
151
+ });
@@ -0,0 +1,46 @@
1
+ // Copyright 2025-2026 Appstrate
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ // Inline Tailwind primitives (shadcn-equivalent look, zero extra deps) shared
5
+ // by templates and widgets. Styling relies solely on CSS tokens that all
6
+ // Appstrate surfaces expose (`--background`, `--input`, `--primary`, …).
7
+
8
+ import { cn } from "./cn.ts";
9
+
10
+ export const INPUT_CLASS =
11
+ "border-input placeholder:text-muted-foreground focus-visible:ring-ring flex h-9 w-full rounded-md border bg-transparent px-3 py-1 text-sm shadow-sm transition-colors focus-visible:ring-1 focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50";
12
+
13
+ export const LABEL_CLASS =
14
+ "text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70";
15
+
16
+ const BUTTON_VARIANTS: Record<string, string> = {
17
+ default: "bg-primary text-primary-foreground shadow hover:bg-primary/90",
18
+ outline:
19
+ "border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground",
20
+ ghost: "hover:bg-accent hover:text-accent-foreground",
21
+ };
22
+
23
+ const BUTTON_SIZES: Record<string, string> = {
24
+ default: "h-9 px-4 py-2",
25
+ sm: "h-8 rounded-md px-3 text-xs",
26
+ icon: "h-9 w-9",
27
+ };
28
+
29
+ export function Button({
30
+ variant = "default",
31
+ size = "default",
32
+ className,
33
+ ...rest
34
+ }: React.ButtonHTMLAttributes<HTMLButtonElement> & { variant?: string; size?: string }) {
35
+ return (
36
+ <button
37
+ {...rest}
38
+ className={cn(
39
+ "focus-visible:ring-ring inline-flex items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap transition-colors focus-visible:ring-1 focus-visible:outline-none disabled:pointer-events-none disabled:opacity-50",
40
+ BUTTON_VARIANTS[variant] ?? BUTTON_VARIANTS.default,
41
+ BUTTON_SIZES[size] ?? BUTTON_SIZES.default,
42
+ className,
43
+ )}
44
+ />
45
+ );
46
+ }
@@ -0,0 +1,272 @@
1
+ // Copyright 2025-2026 Appstrate
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ // Tailwind-styled RJSF templates matching the Appstrate dark theme. Only
5
+ // templates we actually want to restyle are overridden — RJSF defaults
6
+ // handle the rest. No shadcn/radix imports here so this module ships in
7
+ // `@appstrate/ui` and can be consumed by any Appstrate frontend (main app,
8
+ // portal, future surfaces). Styling relies solely on CSS tokens that all
9
+ // Appstrate UIs expose (`--background`, `--input`, `--primary`, …).
10
+
11
+ import type {
12
+ BaseInputTemplateProps,
13
+ FieldTemplateProps,
14
+ TitleFieldProps,
15
+ DescriptionFieldProps,
16
+ SubmitButtonProps,
17
+ ArrayFieldTemplateProps,
18
+ ArrayFieldItemTemplateProps,
19
+ ObjectFieldTemplateProps,
20
+ MultiSchemaFieldTemplateProps,
21
+ } from "@rjsf/utils";
22
+ import { getSubmitButtonOptions } from "@rjsf/utils";
23
+ import { Plus, Trash2, ArrowUp, ArrowDown } from "lucide-react";
24
+ import { cn } from "./cn.ts";
25
+ import { Button, INPUT_CLASS, LABEL_CLASS } from "./primitives.tsx";
26
+ import type { SchemaFormContext } from "./context.ts";
27
+
28
+ export function BaseInputTemplate<T = unknown>(props: BaseInputTemplateProps<T>) {
29
+ const {
30
+ id,
31
+ value,
32
+ required,
33
+ readonly,
34
+ disabled,
35
+ type,
36
+ schema,
37
+ onChange,
38
+ onBlur,
39
+ onFocus,
40
+ options,
41
+ autofocus,
42
+ placeholder,
43
+ rawErrors,
44
+ } = props;
45
+
46
+ const formatType =
47
+ schema.format === "email"
48
+ ? "email"
49
+ : schema.format === "uri"
50
+ ? "url"
51
+ : schema.format === "date"
52
+ ? "date"
53
+ : schema.format === "date-time"
54
+ ? "datetime-local"
55
+ : schema.format === "time"
56
+ ? "time"
57
+ : "text";
58
+ const inputType = type ?? formatType;
59
+
60
+ const isConst = schema && "const" in schema;
61
+ const isReadOnly = readonly || isConst;
62
+
63
+ return (
64
+ <input
65
+ id={id}
66
+ type={inputType}
67
+ value={(value as string | number | undefined) ?? ""}
68
+ required={required}
69
+ readOnly={isReadOnly}
70
+ disabled={disabled}
71
+ autoFocus={autofocus && !isReadOnly}
72
+ placeholder={(placeholder ?? (options?.["ui:placeholder"] as string | undefined)) as string}
73
+ className={cn(
74
+ INPUT_CLASS,
75
+ isReadOnly && "bg-muted/50 cursor-not-allowed",
76
+ rawErrors && rawErrors.length > 0 && "border-destructive",
77
+ )}
78
+ onChange={(e) =>
79
+ onChange(
80
+ e.target.value === "" ? (options?.emptyValue as T) : (e.target.value as unknown as T),
81
+ )
82
+ }
83
+ onBlur={(e) => onBlur?.(id, e.target.value)}
84
+ onFocus={(e) => onFocus?.(id, e.target.value)}
85
+ />
86
+ );
87
+ }
88
+
89
+ export function FieldTemplate(props: FieldTemplateProps) {
90
+ const {
91
+ id,
92
+ label,
93
+ children,
94
+ rawErrors,
95
+ rawDescription,
96
+ required,
97
+ displayLabel,
98
+ hidden,
99
+ schema,
100
+ uiSchema,
101
+ classNames,
102
+ } = props;
103
+
104
+ if (hidden) return <div className="hidden">{children}</div>;
105
+
106
+ // File widget renders its own label so we skip the FieldTemplate label.
107
+ const widget = (uiSchema as Record<string, unknown>)?.["ui:widget"];
108
+ const isFileWidget = widget === "file";
109
+ // Objects and arrays render labels via TitleField, so don't double up here —
110
+ // unless a custom single-control widget (multi-select) is in play, in which
111
+ // case we DO want the field-level label.
112
+ const isSingleControlWidget = widget === "multiselect";
113
+ const isContainer =
114
+ !isSingleControlWidget && (schema.type === "object" || schema.type === "array");
115
+
116
+ const showLabel = displayLabel && !isFileWidget && !isContainer && label;
117
+
118
+ const showDescription = rawDescription && !isFileWidget && !isContainer;
119
+
120
+ return (
121
+ <div className={cn("space-y-1.5", classNames)}>
122
+ {showLabel && (
123
+ <label htmlFor={id} className={LABEL_CLASS}>
124
+ {label}
125
+ {required && " *"}
126
+ </label>
127
+ )}
128
+ {showDescription && <p className="text-muted-foreground text-xs">{rawDescription}</p>}
129
+ {children}
130
+ {rawErrors && rawErrors.length > 0 && (
131
+ <ul className="space-y-0.5">
132
+ {rawErrors.map((err, i) => (
133
+ <li key={i} className="text-destructive text-xs">
134
+ {err}
135
+ </li>
136
+ ))}
137
+ </ul>
138
+ )}
139
+ </div>
140
+ );
141
+ }
142
+
143
+ export function TitleFieldTemplate(props: TitleFieldProps) {
144
+ const { title, required, id } = props;
145
+ if (!title) return null;
146
+ return (
147
+ <h3 id={id} className="text-sm font-medium">
148
+ {title}
149
+ {required && " *"}
150
+ </h3>
151
+ );
152
+ }
153
+
154
+ export function DescriptionFieldTemplate(props: DescriptionFieldProps) {
155
+ const { description, id } = props;
156
+ if (!description) return null;
157
+ return (
158
+ <p id={id} className="text-muted-foreground text-xs">
159
+ {description}
160
+ </p>
161
+ );
162
+ }
163
+
164
+ export function MultiSchemaFieldTemplate(props: MultiSchemaFieldTemplateProps) {
165
+ const { selector, optionSchemaField } = props;
166
+ return (
167
+ <div className="space-y-4">
168
+ {selector}
169
+ {optionSchemaField}
170
+ </div>
171
+ );
172
+ }
173
+
174
+ export function ObjectFieldTemplate(props: ObjectFieldTemplateProps) {
175
+ const { title, description, properties, fieldPathId } = props;
176
+ const isRoot = fieldPathId?.$id === "root";
177
+ return (
178
+ <div className={isRoot ? "space-y-6" : "space-y-4"}>
179
+ {title && !isRoot && <h3 className="text-sm font-medium">{title}</h3>}
180
+ {description && !isRoot && <p className="text-muted-foreground text-xs">{description}</p>}
181
+ {properties.map((p) => (
182
+ <div key={p.name}>{p.content}</div>
183
+ ))}
184
+ </div>
185
+ );
186
+ }
187
+
188
+ export function ArrayFieldItemTemplate(props: ArrayFieldItemTemplateProps) {
189
+ const { children, buttonsProps, hasToolbar } = props;
190
+ const {
191
+ hasMoveUp,
192
+ hasMoveDown,
193
+ hasRemove,
194
+ disabled,
195
+ onMoveUpItem,
196
+ onMoveDownItem,
197
+ onRemoveItem,
198
+ } = buttonsProps;
199
+ return (
200
+ <div className="border-border bg-muted/30 relative space-y-2 rounded-md border p-3">
201
+ <div className="space-y-3">{children}</div>
202
+ {hasToolbar && (hasMoveUp || hasMoveDown || hasRemove) && !disabled && (
203
+ <div className="flex justify-end gap-1">
204
+ {hasMoveUp && (
205
+ <Button
206
+ type="button"
207
+ size="icon"
208
+ variant="ghost"
209
+ onClick={onMoveUpItem}
210
+ aria-label="Move up"
211
+ >
212
+ <ArrowUp className="h-4 w-4" />
213
+ </Button>
214
+ )}
215
+ {hasMoveDown && (
216
+ <Button
217
+ type="button"
218
+ size="icon"
219
+ variant="ghost"
220
+ onClick={onMoveDownItem}
221
+ aria-label="Move down"
222
+ >
223
+ <ArrowDown className="h-4 w-4" />
224
+ </Button>
225
+ )}
226
+ {hasRemove && (
227
+ <Button
228
+ type="button"
229
+ size="icon"
230
+ variant="ghost"
231
+ onClick={onRemoveItem}
232
+ aria-label="Remove"
233
+ >
234
+ <Trash2 className="text-destructive h-4 w-4" />
235
+ </Button>
236
+ )}
237
+ </div>
238
+ )}
239
+ </div>
240
+ );
241
+ }
242
+
243
+ export function ArrayFieldTemplate(props: ArrayFieldTemplateProps) {
244
+ const { items, canAdd, onAddClick, disabled, readonly, title, schema, uiSchema, registry } =
245
+ props;
246
+ const description = (uiSchema?.["ui:description"] as string | undefined) ?? schema.description;
247
+ const ctx = (registry.formContext ?? {}) as SchemaFormContext;
248
+ return (
249
+ <div className="space-y-3">
250
+ {title && <h3 className="text-sm font-medium">{title}</h3>}
251
+ {description && <p className="text-muted-foreground text-xs">{description}</p>}
252
+ {items && items.length > 0 && <div className="space-y-2">{items}</div>}
253
+ {canAdd && !readonly && (
254
+ <Button type="button" variant="outline" size="sm" onClick={onAddClick} disabled={disabled}>
255
+ <Plus className="mr-1 h-4 w-4" />
256
+ {ctx.labels?.addItem ?? "Add"}
257
+ </Button>
258
+ )}
259
+ </div>
260
+ );
261
+ }
262
+
263
+ export function SubmitButton(props: SubmitButtonProps) {
264
+ const { uiSchema } = props;
265
+ const { norender, submitText, props: btnProps } = getSubmitButtonOptions(uiSchema);
266
+ if (norender) return null;
267
+ return (
268
+ <Button type="submit" {...btnProps}>
269
+ {submitText ?? "Submit"}
270
+ </Button>
271
+ );
272
+ }
@@ -0,0 +1,66 @@
1
+ // Copyright 2025-2026 Appstrate
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ // Tiny direct-upload client used by the FileWidget. The endpoint path is
5
+ // configurable so the same widget works against Appstrate's `/api/uploads`
6
+ // and Portal's `/share/:token/uploads` proxy.
7
+
8
+ interface UploadDescriptor {
9
+ id: string;
10
+ uri: string;
11
+ url: string;
12
+ method: "PUT";
13
+ headers: Record<string, string>;
14
+ }
15
+
16
+ export interface UploadFn {
17
+ (file: File, signal?: AbortSignal): Promise<string>;
18
+ }
19
+
20
+ /**
21
+ * Build an upload function bound to a specific POST endpoint. Returns the
22
+ * opaque `upload://upl_xxx` URI on success.
23
+ *
24
+ * Errors propagate the server-side RFC 9457 detail message so the caller
25
+ * can surface it to the user.
26
+ *
27
+ * `signal` lets callers cancel an in-flight upload.
28
+ */
29
+ export function createUploader(uploadPath: string): UploadFn {
30
+ return async (file, signal) => {
31
+ const descRes = await fetch(uploadPath, {
32
+ method: "POST",
33
+ credentials: "include",
34
+ headers: { "Content-Type": "application/json" },
35
+ body: JSON.stringify({
36
+ name: file.name,
37
+ size: file.size,
38
+ mime: file.type || "application/octet-stream",
39
+ }),
40
+ signal,
41
+ });
42
+ if (!descRes.ok) {
43
+ const body = (await descRes.json().catch(() => ({ detail: descRes.statusText }))) as {
44
+ detail?: string;
45
+ };
46
+ throw new Error(body.detail ?? `upload init failed: ${descRes.status}`);
47
+ }
48
+ const desc = (await descRes.json()) as UploadDescriptor;
49
+
50
+ const putRes = await fetch(desc.url, {
51
+ method: desc.method,
52
+ headers: desc.headers,
53
+ body: file,
54
+ signal,
55
+ });
56
+ if (!putRes.ok) {
57
+ throw new Error(`upload failed: ${putRes.status} ${putRes.statusText}`);
58
+ }
59
+
60
+ return desc.uri;
61
+ };
62
+ }
63
+
64
+ export function isUploadUri(v: unknown): v is string {
65
+ return typeof v === "string" && v.startsWith("upload://");
66
+ }
@@ -0,0 +1,15 @@
1
+ // Copyright 2025-2026 Appstrate
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ // Shared Ajv2020 + ajv-formats validator for RJSF, matching the backend via
5
+ // the single factory in `@appstrate/core/ajv`. The awkward `unknown` cast at
6
+ // the ajv-formats / ajv/dist/2020 boundary lives there, not here.
7
+
8
+ import { customizeValidator } from "@rjsf/validator-ajv8";
9
+ import { AjvClass } from "@appstrate/core/ajv";
10
+
11
+ export const schemaFormValidator = customizeValidator({
12
+ AjvClass,
13
+ ajvOptionsOverrides: { strict: false },
14
+ ajvFormatOptions: {},
15
+ });
@@ -0,0 +1,123 @@
1
+ // Copyright 2025-2026 Appstrate
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ // Custom RJSF widgets — framework-agnostic (no shadcn/radix deps).
5
+ // Single- and multi-selects both use react-select so we get a rich,
6
+ // consistent dropdown in every Appstrate surface.
7
+
8
+ import type { WidgetProps } from "@rjsf/utils";
9
+ import Select, { type StylesConfig } from "react-select";
10
+ import { cn } from "./cn.ts";
11
+ import { LABEL_CLASS } from "./primitives.tsx";
12
+ export { FileWidget } from "./file-widget.tsx";
13
+
14
+ interface EnumOption {
15
+ value: unknown;
16
+ label: string;
17
+ }
18
+
19
+ // react-select custom styles mapped onto Appstrate's CSS variables so the
20
+ // dropdown picks up the current theme (dark/light) via CSS tokens.
21
+ const selectStyles: StylesConfig<EnumOption> = {
22
+ control: (base) => ({
23
+ ...base,
24
+ backgroundColor: "transparent",
25
+ borderColor: "var(--border)",
26
+ minHeight: "2.25rem",
27
+ }),
28
+ menu: (base) => ({ ...base, backgroundColor: "var(--popover)" }),
29
+ option: (base, state) => ({
30
+ ...base,
31
+ backgroundColor: state.isFocused ? "var(--accent)" : "transparent",
32
+ color: "inherit",
33
+ }),
34
+ multiValue: (base) => ({ ...base, backgroundColor: "var(--secondary)" }),
35
+ input: (base) => ({ ...base, color: "inherit" }),
36
+ singleValue: (base) => ({ ...base, color: "inherit" }),
37
+ placeholder: (base) => ({ ...base, color: "var(--muted-foreground)" }),
38
+ };
39
+
40
+ export function TextareaWidget(props: WidgetProps) {
41
+ const { id, value, onChange, required, readonly, disabled, placeholder, rawErrors } = props;
42
+ return (
43
+ <textarea
44
+ id={id}
45
+ value={(value as string | undefined) ?? ""}
46
+ required={required}
47
+ readOnly={readonly}
48
+ disabled={disabled}
49
+ placeholder={placeholder}
50
+ rows={5}
51
+ className={cn(
52
+ "border-input placeholder:text-muted-foreground focus-visible:ring-ring flex min-h-[60px] w-full rounded-md border bg-transparent px-3 py-2 text-sm shadow-sm focus-visible:ring-1 focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50",
53
+ rawErrors && rawErrors.length > 0 && "border-destructive",
54
+ )}
55
+ onChange={(e) => onChange(e.target.value === "" ? undefined : e.target.value)}
56
+ />
57
+ );
58
+ }
59
+
60
+ export function CheckboxWidget(props: WidgetProps) {
61
+ const { id, value, onChange, required, disabled, label } = props;
62
+ return (
63
+ <div className="flex items-center gap-2">
64
+ <input
65
+ type="checkbox"
66
+ id={id}
67
+ checked={Boolean(value)}
68
+ disabled={disabled}
69
+ onChange={(e) => onChange(e.target.checked)}
70
+ className="border-primary text-primary focus-visible:ring-ring h-4 w-4 shrink-0 rounded-sm border shadow focus-visible:ring-1 focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50"
71
+ />
72
+ {label && (
73
+ <label htmlFor={id} className={cn(LABEL_CLASS, "cursor-pointer font-normal")}>
74
+ {label}
75
+ {required && " *"}
76
+ </label>
77
+ )}
78
+ </div>
79
+ );
80
+ }
81
+
82
+ export function SelectWidget(props: WidgetProps) {
83
+ const { id, value, onChange, disabled, options, placeholder } = props;
84
+ const enumOptions = (options.enumOptions as EnumOption[] | undefined) ?? [];
85
+
86
+ const selected = enumOptions.find((o) => String(o.value) === String(value)) ?? null;
87
+
88
+ return (
89
+ <Select<EnumOption, false>
90
+ inputId={id}
91
+ isDisabled={disabled}
92
+ isClearable
93
+ options={enumOptions}
94
+ value={selected}
95
+ placeholder={placeholder ?? ""}
96
+ onChange={(opt) => onChange(opt ? opt.value : undefined)}
97
+ classNamePrefix="rjsf-select"
98
+ styles={selectStyles}
99
+ />
100
+ );
101
+ }
102
+
103
+ /** Array of enums → multi-select dropdown via react-select. */
104
+ export function MultiSelectWidget(props: WidgetProps) {
105
+ const { id, value, onChange, disabled, options } = props;
106
+ const enumOptions = (options.enumOptions as EnumOption[] | undefined) ?? [];
107
+
108
+ const raw = Array.isArray(value) ? value : [];
109
+ const selected = enumOptions.filter((o) => raw.some((v) => String(v) === String(o.value)));
110
+
111
+ return (
112
+ <Select<EnumOption, true>
113
+ inputId={id}
114
+ isMulti
115
+ isDisabled={disabled}
116
+ options={enumOptions}
117
+ value={selected}
118
+ onChange={(sel) => onChange(sel.map((s) => s.value))}
119
+ classNamePrefix="rjsf-ms"
120
+ styles={selectStyles as StylesConfig<EnumOption, true>}
121
+ />
122
+ );
123
+ }