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

chore: sync fork properly #334

Closed
Closed
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 src/npm-fastui/src/components/FormField.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ interface FormFieldInputProps extends FormFieldInput {
}

export const FormFieldInputComp: FC<FormFieldInputProps> = (props) => {
const { name, placeholder, required, htmlType, locked, autocomplete, onChange } = props
const { name, placeholder, required, htmlType, locked, autocomplete, onChange, step } = props

return (
<div className={useClassName(props)}>
Expand All @@ -39,6 +39,7 @@ export const FormFieldInputComp: FC<FormFieldInputProps> = (props) => {
disabled={locked}
placeholder={placeholder}
autoComplete={autocomplete}
step={step}
aria-describedby={descId(props)}
onChange={onChange}
/>
Expand Down
1 change: 1 addition & 0 deletions src/npm-fastui/src/models.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -433,6 +433,7 @@ export interface FormFieldInput {
initial?: string | number
placeholder?: string
autocomplete?: string
step?: number | 'any'
type: 'FormFieldInput'
}
/**
Expand Down
3 changes: 3 additions & 0 deletions src/python-fastui/fastui/components/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,9 @@ class FormFieldInput(BaseFormField):
autocomplete: _t.Union[str, None] = None
"""Autocomplete value for the field."""

step: _t.Union[float, _t.Literal['any'], None] = None
"""Step value for the field."""

type: _t.Literal['FormFieldInput'] = 'FormFieldInput'
"""The type of the component. Always 'FormFieldInput'."""

Expand Down
19 changes: 18 additions & 1 deletion src/python-fastui/fastui/json_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,7 @@ def json_schema_field_to_field(
initial=schema.get('default'),
description=schema.get('description'),
mode=schema.get('mode', 'checkbox'),
class_name=schema.get('className'),
)
elif field := special_string_field(schema, name, title, required, False):
return field
Expand All @@ -197,7 +198,9 @@ def json_schema_field_to_field(
initial=schema.get('default'),
autocomplete=schema.get('autocomplete'),
description=schema.get('description'),
step=schema.get('step', get_default_step(schema)),
placeholder=schema.get('placeholder'),
class_name=schema.get('className'),
)


Expand Down Expand Up @@ -247,6 +250,7 @@ def special_string_field(
multiple=multiple,
accept=schema.get('accept'),
description=schema.get('description'),
class_name=schema.get('className'),
)
elif schema.get('format') == 'textarea':
return FormFieldTextarea(
Expand All @@ -259,6 +263,7 @@ def special_string_field(
initial=schema.get('initial'),
description=schema.get('description'),
autocomplete=schema.get('autocomplete'),
class_name=schema.get('className'),
)
elif enum := schema.get('enum'):
enum_labels = schema.get('enum_labels', {})
Expand All @@ -272,6 +277,7 @@ def special_string_field(
initial=schema.get('default'),
description=schema.get('description'),
autocomplete=schema.get('autocomplete'),
class_name=schema.get('className'),
)
elif search_url := schema.get('search_url'):
return FormFieldSelectSearch(
Expand All @@ -283,6 +289,7 @@ def special_string_field(
multiple=multiple,
initial=schema.get('initial'),
description=schema.get('description'),
class_name=schema.get('className'),
)


Expand Down Expand Up @@ -313,7 +320,9 @@ def deference_json_schema(
if def_schema is None:
raise ValueError(f'Invalid $ref "{ref}", not found in {defs}')
else:
return def_schema.copy(), required # clone dict to avoid attribute leakage via shared schema.
def_schema_new = def_schema.copy() # clone dict to avoid attribute leakage via shared schema.
def_schema_new.update({k: v for k, v in schema.items() if k != '$ref'}) # type: ignore
return def_schema_new, required
elif any_of := schema.get('anyOf'):
if len(any_of) == 2 and sum(s.get('type') == 'null' for s in any_of) == 1:
# If anyOf is a single type and null, then it is optional
Expand Down Expand Up @@ -373,6 +382,14 @@ def input_html_type(schema: JsonSchemaField) -> InputHtmlType:
raise ValueError(f'Unknown schema: {schema}') from e


def get_default_step(schema: JsonSchemaField) -> _t.Union[_t.Literal['any'], None]:
key = schema['type']
if key == 'integer':
return None
if key == 'number':
return 'any'


def schema_is_field(schema: JsonSchemaConcrete) -> _ta.TypeGuard[JsonSchemaField]:
"""
Determine if a schema is a field `JsonSchemaField`
Expand Down
91 changes: 91 additions & 0 deletions src/python-fastui/tests/test_forms.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import enum
from contextlib import asynccontextmanager
from enum import Enum
from io import BytesIO
from typing import List, Tuple, Union

Expand Down Expand Up @@ -547,3 +548,93 @@ def test_form_fields():
'submitUrl': '/foobar/',
'type': 'ModelForm',
}


class FormNumbersDefaultStep(BaseModel):
size: int
cost: float


def test_form_numbers_default_step():
m = components.ModelForm(model=FormNumbersDefaultStep, submit_url='/foobar')

assert m.model_dump(by_alias=True, exclude_none=True) == {
'submitUrl': '/foobar',
'method': 'POST',
'type': 'ModelForm',
'formFields': [
{
'name': 'size',
'title': ['Size'],
'required': True,
'locked': False,
'htmlType': 'number',
'type': 'FormFieldInput',
},
{
'name': 'cost',
'title': ['Cost'],
'required': True,
'locked': False,
'htmlType': 'number',
'step': 'any',
'type': 'FormFieldInput',
},
],
}


class ToolEnum(str, Enum):
"""Tools that can be leveraged to complete a job."""

hammer = 'hammer'
screwdriver = 'screwdriver'
saw = 'saw'
claw_hammer = 'claw_hammer'


class FormEnumWithOptionalEnum(BaseModel):
job_name: str
tool_required: Union[ToolEnum, None] = Field(
json_schema_extra={
# Override certain schema fields.
'placeholder': 'tool',
'description': '',
}
)


def test_form_with_enum():
m = components.ModelForm(model=FormEnumWithOptionalEnum, submit_url='/foobar')

assert m.model_dump(by_alias=True, exclude_none=True) == {
'submitUrl': '/foobar',
'method': 'POST',
'type': 'ModelForm',
'formFields': [
{
'name': 'job_name',
'title': ['Job Name'],
'required': True,
'locked': False,
'htmlType': 'text',
'type': 'FormFieldInput',
},
{
'name': 'tool_required',
'title': ['ToolEnum'],
'required': False,
'locked': False,
'description': '',
'options': [
{'value': 'hammer', 'label': 'Hammer'},
{'value': 'screwdriver', 'label': 'Screwdriver'},
{'value': 'saw', 'label': 'Saw'},
{'value': 'claw_hammer', 'label': 'Claw Hammer'},
],
'multiple': False,
'placeholder': 'tool',
'type': 'FormFieldSelect',
},
],
}
Loading