Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added textarea as form field #139

Merged
merged 3 commits into from
Feb 7, 2024
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
3 changes: 2 additions & 1 deletion demo/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from fastui import AnyComponent, FastUI
from fastui import components as c
from fastui.events import GoToEvent, PageEvent
from fastui.forms import FormFile, SelectSearchResponse, fastui_form
from fastui.forms import FormFile, SelectSearchResponse, Textarea, fastui_form
from httpx import AsyncClient
from pydantic import BaseModel, EmailStr, Field, SecretStr, field_validator
from pydantic_core import PydanticCustomError
Expand Down Expand Up @@ -143,6 +143,7 @@ class BigModel(BaseModel):
name: str | None = Field(
None, description='This field is not required, it must start with a capital letter if provided'
)
info: Annotated[str | None, Textarea(rows=5)] = Field(None, description='Optional free text information about you.')
profile_pic: Annotated[UploadFile, FormFile(accept='image/*', max_size=16_000)] = Field(
description='Upload a profile picture, must not be more than 16kb'
)
Expand Down
2 changes: 2 additions & 0 deletions src/npm-fastui-bootstrap/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -66,11 +66,13 @@ export const classNameGenerator: ClassNameGenerator = ({
}
}
case 'FormFieldInput':
case 'FormFieldTextarea':
case 'FormFieldBoolean':
case 'FormFieldSelect':
case 'FormFieldSelectSearch':
case 'FormFieldFile':
switch (subElement) {
case 'textarea':
case 'input':
return {
'form-control': type !== 'FormFieldBoolean',
Expand Down
28 changes: 28 additions & 0 deletions src/npm-fastui/src/components/FormField.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import Select, { StylesConfig } from 'react-select'

import type {
FormFieldInput,
FormFieldTextarea,
FormFieldBoolean,
FormFieldFile,
FormFieldSelect,
Expand Down Expand Up @@ -44,6 +45,32 @@ export const FormFieldInputComp: FC<FormFieldInputProps> = (props) => {
)
}

interface FormFieldTextareaProps extends FormFieldTextarea {
onChange?: PrivateOnChange
}

export const FormFieldTextareaComp: FC<FormFieldTextareaProps> = (props) => {
const { name, placeholder, required, locked, rows, cols } = props
return (
<div className={useClassName(props)}>
<Label {...props} />
<textarea
className={useClassName(props, { el: 'textarea' })}
defaultValue={props.initial}
id={inputId(props)}
rows={rows}
cols={cols}
name={name}
required={required}
disabled={locked}
placeholder={placeholder}
aria-describedby={descId(props)}
/>
<ErrorDescription {...props} />
</div>
)
}

interface FormFieldBooleanProps extends FormFieldBoolean {
onChange?: PrivateOnChange
}
Expand Down Expand Up @@ -284,6 +311,7 @@ const Label: FC<FormFieldProps> = (props) => {

export type FormFieldProps =
| FormFieldInputProps
| FormFieldTextareaProps
| FormFieldBooleanProps
| FormFieldFileProps
| FormFieldSelectProps
Expand Down
3 changes: 3 additions & 0 deletions src/npm-fastui/src/components/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { CodeComp } from './Code'
import { FormComp } from './form'
import {
FormFieldInputComp,
FormFieldTextareaComp,
FormFieldBooleanComp,
FormFieldSelectComp,
FormFieldSelectSearchComp,
Expand Down Expand Up @@ -125,6 +126,8 @@ export const AnyComp: FC<FastProps> = (props) => {
return <FormComp {...props} />
case 'FormFieldInput':
return <FormFieldInputComp {...props} />
case 'FormFieldTextarea':
return <FormFieldTextareaComp {...props} />
case 'FormFieldBoolean':
return <FormFieldBooleanComp {...props} />
case 'FormFieldFile':
Expand Down
34 changes: 32 additions & 2 deletions src/npm-fastui/src/models.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ export type FastProps =
| Details
| Form
| FormFieldInput
| FormFieldTextarea
| FormFieldBoolean
| FormFieldFile
| FormFieldSelect
Expand Down Expand Up @@ -304,7 +305,14 @@ export interface Form {
submitTrigger?: PageEvent
footer?: FastProps[]
className?: ClassName
formFields: (FormFieldInput | FormFieldBoolean | FormFieldFile | FormFieldSelect | FormFieldSelectSearch)[]
formFields: (
| FormFieldInput
| FormFieldTextarea
| FormFieldBoolean
| FormFieldFile
| FormFieldSelect
| FormFieldSelectSearch
)[]
type: 'Form'
}
export interface FormFieldInput {
Expand All @@ -321,6 +329,21 @@ export interface FormFieldInput {
placeholder?: string
type: 'FormFieldInput'
}
export interface FormFieldTextarea {
name: string
title: string[] | string
required?: boolean
error?: string
locked?: boolean
description?: string
displayMode?: 'default' | 'inline'
className?: ClassName
rows?: number
cols?: number
initial?: string
placeholder?: string
type: 'FormFieldTextarea'
}
export interface FormFieldBoolean {
name: string
title: string[] | string
Expand Down Expand Up @@ -399,5 +422,12 @@ export interface ModelForm {
footer?: FastProps[]
className?: ClassName
type: 'ModelForm'
formFields: (FormFieldInput | FormFieldBoolean | FormFieldFile | FormFieldSelect | FormFieldSelectSearch)[]
formFields: (
| FormFieldInput
| FormFieldTextarea
| FormFieldBoolean
| FormFieldFile
| FormFieldSelect
| FormFieldSelectSearch
)[]
}
12 changes: 11 additions & 1 deletion src/python-fastui/fastui/components/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,14 @@ class FormFieldInput(BaseFormField):
type: _t.Literal['FormFieldInput'] = 'FormFieldInput'


class FormFieldTextarea(BaseFormField):
rows: _t.Union[int, None] = None
cols: _t.Union[int, None] = None
initial: _t.Union[str, None] = None
placeholder: _t.Union[str, None] = None
type: _t.Literal['FormFieldTextarea'] = 'FormFieldTextarea'


class FormFieldBoolean(BaseFormField):
initial: _t.Union[bool, None] = None
mode: _t.Literal['checkbox', 'switch'] = 'checkbox'
Expand Down Expand Up @@ -65,7 +73,9 @@ class FormFieldSelectSearch(BaseFormField):
type: _t.Literal['FormFieldSelectSearch'] = 'FormFieldSelectSearch'


FormField = _t.Union[FormFieldInput, FormFieldBoolean, FormFieldFile, FormFieldSelect, FormFieldSelectSearch]
FormField = _t.Union[
FormFieldInput, FormFieldTextarea, FormFieldBoolean, FormFieldFile, FormFieldSelect, FormFieldSelectSearch
]


class BaseForm(pydantic.BaseModel, ABC, defer_build=True, extra='forbid'):
Expand Down
7 changes: 6 additions & 1 deletion src/python-fastui/fastui/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
if _t.TYPE_CHECKING:
from . import json_schema

__all__ = 'FastUIForm', 'fastui_form', 'FormFile', 'SelectSearchResponse', 'SelectOption'
__all__ = 'FastUIForm', 'fastui_form', 'FormFile', 'Textarea', 'SelectSearchResponse', 'SelectOption'

FormModel = _t.TypeVar('FormModel', bound=pydantic.BaseModel)

Expand Down Expand Up @@ -226,3 +226,8 @@ def name_to_loc(name: str) -> 'json_schema.SchemeLocation':
else:
loc.append(part)
return loc


# Use uppercase for consistency with pydantic.Field, which is also a function
def Textarea(rows: _t.Union[int, None] = None, cols: _t.Union[int, None] = None) -> _t.Any: # N802
return pydantic.Field(json_schema_extra={'format': 'textarea', 'rows': rows, 'cols': cols})
23 changes: 22 additions & 1 deletion src/python-fastui/fastui/json_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
FormFieldInput,
FormFieldSelect,
FormFieldSelectSearch,
FormFieldTextarea,
InputHtmlType,
)

Expand All @@ -30,7 +31,7 @@ def model_json_schema_to_fields(model: _t.Type[BaseModel]) -> _t.List[FormField]


JsonSchemaInput: _ta.TypeAlias = (
'JsonSchemaString | JsonSchemaStringEnum | JsonSchemaFile | JsonSchemaInt | JsonSchemaNumber'
'JsonSchemaString | JsonSchemaStringEnum | JsonSchemaFile | JsonSchemaTextarea | JsonSchemaInt | JsonSchemaNumber'
)
JsonSchemaField: _ta.TypeAlias = 'JsonSchemaInput | JsonSchemaBool'
JsonSchemaConcrete: _ta.TypeAlias = 'JsonSchemaField | JsonSchemaArray | JsonSchemaObject'
Expand Down Expand Up @@ -69,6 +70,15 @@ class JsonSchemaFile(JsonSchemaBase, total=False):
accept: str


class JsonSchemaTextarea(JsonSchemaBase, total=False):
type: _ta.Required[_t.Literal['string']]
format: _ta.Required[_t.Literal['textarea']]
rows: int
cols: int
default: str
placeholder: str


class JsonSchemaBool(JsonSchemaBase, total=False):
type: _ta.Required[_t.Literal['boolean']]
default: bool
Expand Down Expand Up @@ -236,6 +246,17 @@ def special_string_field(
accept=schema.get('accept'),
description=schema.get('description'),
)
elif schema.get('format') == 'textarea':
return FormFieldTextarea(
name=name,
title=title,
required=required,
rows=schema.get('rows'),
cols=schema.get('cols'),
placeholder=schema.get('placeholder'),
initial=schema.get('initial'),
description=schema.get('description'),
)
elif enum := schema.get('enum'):
enum_labels = schema.get('enum_labels', {})
return FormFieldSelect(
Expand Down
25 changes: 24 additions & 1 deletion src/python-fastui/tests/test_forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import pytest
from fastapi import HTTPException
from fastui import components
from fastui.forms import FormFile, fastui_form
from fastui.forms import FormFile, Textarea, fastui_form
from pydantic import BaseModel
from starlette.datastructures import FormData, Headers, UploadFile
from typing_extensions import Annotated
Expand Down Expand Up @@ -446,3 +446,26 @@ class TupleOptional(BaseModel):
m = components.ModelForm(model=TupleOptional, submit_url='/foo/')
with pytest.raises(NotImplementedError, match='Tuples with optional fields are not yet supported'):
m.model_dump(by_alias=True, exclude_none=True)


class FormTextarea(BaseModel):
text: Annotated[str, Textarea()]


def test_form_textarea_form_fields():
m = components.ModelForm(model=FormTextarea, submit_url='/foobar/')

assert m.model_dump(by_alias=True, exclude_none=True) == {
'submitUrl': '/foobar/',
'method': 'POST',
'type': 'ModelForm',
'formFields': [
{
'name': 'text',
'title': ['Text'],
'required': True,
'locked': False,
'type': 'FormFieldTextarea',
}
],
}