Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .changeset/clear-trees-buy.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
'@openzeppelin/contracts-ui-builder-renderer': minor
'@openzeppelin/contracts-ui-builder-app': minor
'@openzeppelin/contracts-ui-builder-types': minor
'@openzeppelin/contracts-ui-builder-utils': minor
'@openzeppelin/contracts-ui-builder-ui': minor
---

support for new BytesField component with validation
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export function getFieldTypeLabel(type: FieldType): string {
const labelMap: Record<string, string> = {
text: 'Text Input',
textarea: 'Text Area',
bytes: 'Bytes Input (Hex/Base64)',
email: 'Email Input',
password: 'Password Input',
number: 'Number Input',
Expand Down Expand Up @@ -61,6 +62,7 @@ const DEFAULT_FIELD_TYPES: FieldType[] = [
'radio',
'select',
'textarea',
'bytes',
'email',
'password',
'blockchain-address',
Expand Down Expand Up @@ -99,7 +101,7 @@ export function getFieldTypeGroups(

// Define field type categories
const fieldTypeCategories: Record<string, FieldType[]> = {
text: ['text', 'textarea', 'email', 'password'],
text: ['text', 'textarea', 'bytes', 'email', 'password'],
numeric: ['number', 'amount'],
selection: ['select', 'radio', 'checkbox'],
blockchain: ['blockchain-address'],
Expand Down
Empty file modified packages/builder/src/export/cli/export-app.cjs
100644 → 100755
Empty file.
2 changes: 2 additions & 0 deletions packages/renderer/src/components/fieldRegistry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
ArrayObjectField,
BaseFieldProps,
BooleanField,
BytesField,
CodeEditorField,
NumberField,
ObjectField,
Expand Down Expand Up @@ -38,6 +39,7 @@ export const fieldComponents: Record<
select: SelectField,
'select-grouped': SelectGroupedField,
textarea: TextAreaField,
bytes: BytesField,
'code-editor': CodeEditorField,
date: () => React.createElement('div', null, 'Date field not implemented yet'),
email: () => React.createElement('div', null, 'Email field not implemented yet'),
Expand Down
2 changes: 2 additions & 0 deletions packages/types/src/forms/fields.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export type FieldType =
| 'radio'
| 'select'
| 'textarea'
| 'bytes' // Byte data with hex/base64 validation
| 'code-editor' // Code editor with syntax highlighting
| 'date'
| 'email'
Expand All @@ -38,6 +39,7 @@ export type FieldValue<T extends FieldType> = T extends
| 'email'
| 'password'
| 'textarea'
| 'bytes'
| 'code-editor'
| 'blockchain-address'
? string
Expand Down
204 changes: 204 additions & 0 deletions packages/ui/src/components/fields/BytesField.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,204 @@
import React from 'react';
import { Controller, FieldValues } from 'react-hook-form';

import { validateBytesSimple } from '@openzeppelin/contracts-ui-builder-utils';

import { Label } from '../ui/label';
import { Textarea } from '../ui/textarea';
import { BaseFieldProps } from './BaseField';
import {
ErrorMessage,
getAccessibilityProps,
getValidationStateClasses,
handleEscapeKey,
} from './utils';

/**
* BytesField component properties
*/
export interface BytesFieldProps<TFieldValues extends FieldValues = FieldValues>
extends BaseFieldProps<TFieldValues> {
/**
* Number of rows for the textarea
*/
rows?: number;

/**
* Maximum length in bytes (not characters)
*/
maxBytes?: number;

/**
* Whether to accept hex, base64, or both formats
*/
acceptedFormats?: 'hex' | 'base64' | 'both';

/**
* Whether to automatically add/remove 0x prefix for hex values
*/
autoPrefix?: boolean;

/**
* Whether to allow 0x prefix in hex input (defaults to true)
*/
allowHexPrefix?: boolean;
}

/**
* Specialized input field for bytes data with built-in hex/base64 validation.
*
* This component provides proper validation for blockchain bytes data including:
* - Hex encoding validation (with optional 0x prefix support)
* - Base64 encoding validation
* - Byte length validation
* - Format detection and conversion
*
* Key props for EVM compatibility:
* - `allowHexPrefix`: Whether to accept 0x prefixed input (defaults to true)
* - `autoPrefix`: Whether to automatically add 0x prefixes (defaults to false)
*
* These are separate concerns - you can accept 0x input without auto-adding prefixes.
*
* Architecture flow:
* 1. Form schemas are generated from contract functions using adapters
* 2. TransactionForm renders the overall form structure with React Hook Form
* 3. DynamicFormField selects BytesField for 'bytes' field types
* 4. BaseField provides consistent layout and hook form integration
* 5. This component handles bytes-specific validation and formatting
*/
export function BytesField<TFieldValues extends FieldValues = FieldValues>({
id,
label,
helperText,
control,
name,
width = 'full',
validation,
placeholder = 'Enter hex or base64 encoded bytes',
rows = 3,
maxBytes,
acceptedFormats = 'both',
autoPrefix = false,
allowHexPrefix = true,
readOnly,
}: BytesFieldProps<TFieldValues>): React.ReactElement {
const isRequired = !!validation?.required;
const errorId = `${id}-error`;
const descriptionId = `${id}-description`;

/**
* Validates bytes input format and encoding using validator.js
*/
const validateBytesField = (value: string): boolean | string => {
return validateBytesSimple(value, {
acceptedFormats,
maxBytes,
allowHexPrefix, // Allow prefix based on explicit prop (defaults to true)
});
};

/**
* Formats the input value (adds 0x prefix if needed)
*/
const formatValue = (value: string): string => {
if (!value || !autoPrefix) return value;

const cleanValue = value.trim().replace(/\s+/g, '');
const withoutPrefix = cleanValue.startsWith('0x') ? cleanValue.slice(2) : cleanValue;

// Only add prefix for valid hex that doesn't already have it
if (withoutPrefix && /^[0-9a-fA-F]*$/.test(withoutPrefix) && withoutPrefix.length % 2 === 0) {
return cleanValue.startsWith('0x') ? cleanValue : `0x${cleanValue}`;
}

return cleanValue;
};

return (
<div
className={`flex flex-col gap-2 ${width === 'full' ? 'w-full' : width === 'half' ? 'w-1/2' : 'w-1/3'}`}
>
{label && (
<Label htmlFor={id}>
{label} {isRequired && <span className="text-destructive">*</span>}
</Label>
)}

<Controller
control={control}
name={name}
disabled={readOnly}
rules={{
validate: (value) => {
// Handle required validation explicitly
if (value === undefined || value === null || value === '') {
return validation?.required ? 'This field is required' : true;
}

// Run bytes-specific validation using validator.js
return validateBytesField(value);
},
}}
render={({ field, fieldState: { error } }) => {
const hasError = !!error;
const validationClasses = getValidationStateClasses(error);

// Get accessibility attributes
const accessibilityProps = getAccessibilityProps({
id,
hasError,
isRequired,
hasHelperText: !!helperText,
});

return (
<>
<Textarea
{...field}
id={id}
placeholder={placeholder}
rows={rows}
className={validationClasses}
value={field.value ?? ''}
onChange={(e) => {
// Only update value without formatting for better performance
field.onChange(e.target.value);
}}
onBlur={(e) => {
// Apply formatting on blur when user finishes typing
const formatted = formatValue(e.target.value);
field.onChange(formatted);
field.onBlur();
}}
onKeyDown={handleEscapeKey(field.onChange, field.value)}
readOnly={readOnly}
{...accessibilityProps}
aria-describedby={`${helperText ? descriptionId : ''} ${hasError ? errorId : ''}`.trim()}
/>

{/* Display helper text with format hint */}
{helperText && (
<div id={descriptionId} className="text-muted-foreground text-sm">
{helperText}
<div className="text-xs text-muted-foreground mt-1">
{acceptedFormats === 'hex' && 'Hex format (e.g., 48656c6c6f or 0x48656c6c6f)'}
{acceptedFormats === 'base64' && 'Base64 format (e.g., SGVsbG8=)'}
{acceptedFormats === 'both' &&
'Hex (e.g., 48656c6c6f) or Base64 (e.g., SGVsbG8=) format'}
{maxBytes && ` • Max ${maxBytes} bytes`}
</div>
</div>
)}

{/* Display error message */}
<ErrorMessage error={error} id={errorId} />
</>
);
}}
/>
</div>
);
}

// Set displayName manually for better debugging
BytesField.displayName = 'BytesField';
1 change: 1 addition & 0 deletions packages/ui/src/components/fields/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export * from './ArrayField';
export * from './ArrayObjectField';
export * from './BaseField';
export * from './BooleanField';
export * from './BytesField';
export * from './CodeEditorField';
export * from './NumberField';
export * from './ObjectField';
Expand Down
4 changes: 3 additions & 1 deletion packages/utils/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,12 @@
"@openzeppelin/contracts-ui-builder-types": "workspace:^",
"clsx": "^2.1.1",
"tailwind-merge": "^3.3.1",
"uuid": "^11.1.0"
"uuid": "^11.1.0",
"validator": "^13.15.15"
},
"devDependencies": {
"@types/uuid": "^10.0.0",
"@types/validator": "^13.15.2",
"@typescript-eslint/eslint-plugin": "^8.39.0",
"@typescript-eslint/parser": "^8.39.0",
"eslint": "^9.32.0",
Expand Down
Loading
Loading