- FForm
- fformCores
- API
get(...paths: string | string[])set(path: string | string[], value: any, opts?: setOpts )getValue(opts?: getValueOpts)setValue(value: any, opts?: setValueOpts)getDefaultValue()reset(opts?: resetOpts)clear(opts?: clearOpts)validate(path: boolean | string | string[], opts?: APIOptsType)arrayAdd(path: string | string[], value: number | any[], opts?: APIOptsType)arrayItemOps(path: string | string[], op: string, opts: arrayItemOpts)setHidden(path: string | string[], value?: boolean, opts?: APIOptsType)showOnly(path: string | string[], opts?: APIOptsType)getActive()execute()
- Basic schema properties
- Extended schema properties
_placeholder?: string_params?: FFParamsType_data?: any_presets?: string_simple?: boolean_enumExten?: { [key: string]: undefined | string | object }_stateMaps?: Array_validators?: Array_oneOfSelector: string | dataHandler_custom?: FFCustomizeType_layout?: FFLayoutCustomizeType_strictLayout?: boolean
- Validation
- Field structure and customization
- Form layout
- Elements
- Styling
- SSR
Component expects following properties:
core- core created by fformCores or object with fformCores propsstate?: any- form's state.value?: any- form's current value.inital?: any- form's initial value.fieldCache?: boolean | number- caching delay on updating form's value. Used for optimization purposes._$useTag?: string | Function- tag to render form. Defaultform.touched- setsuntouchedproperty tofalse.onSubmit?: (event: any) => any- executed on form submit. Supportsevent.preventDefault().onChange?: (event: any) => void- executed on value change.onStateChange?: (event: any) => void- executed on state change.
For methods onSubmit, onChange, onStateChange passed param event has additional properties:
value- current form value.state- current form state.fform- link to thefforminstance.
After creation fformCores can be accessed throught api property of fform instance.
getRef(path: string)- returns field's input instance according to path.reset()- resets form value to inital.submit()- submits form.api- fformCores to manipulate form state.valid- valid form or not
To create new core pass to constructor object as first argument with following props:
schema- schema that will be used to create statename: string- name that will be used to access data in redux storage and for fields namingelements?- elements, that contains everything needed for components creationJSONValidator?- JSON schema validator for JSON validationstore?:any- redux store.getState?: () => any- external state settersetState?: (state: any) => void- external state getter
After creation core can be manipulated through API methods
const {fformCores} = require('fform');
core = fformCores({name, schema})
core.setValue(value)
Only one core created for each name property. If passed props with name that core already exists, props will be checked for equality (shallow) and if they are equal, the existed core will be returned without creation, otherwise, new core will be created and replace previous.
Also, fformCores accept string value as first argument. In this case core with passed name will be returned (if exists).
Create redux store with thunk and formReducer with "fforms" in root reducer:
const {formReducer} = require('fform');
const {createStore, combineReducers, applyMiddleware} = require('redux');
const thunk = require('redux-thunk').default;
store = createStore(combineReducers({fforms: formReducer()}), applyMiddleware(thunk))
Then pass redux store in store property on fformCores creation:
const {FFormStateAPI} = require('fform');
stateApi = new FFormStateAPI({store, schema})
Pass setState/getState function from any storage on fformCores creation and it will use them for setting and getting fform state.
if no setState/getState or store are passed on creation then fformCores will use own internal storage for fform state.
String (or array or strings) value delimited with '/' that describes path to field. Following paths are equal: '#/objects/array/field_1', ['#', 'object/array', 'field_1'], ['object', '/array/', '/field_1/']
Each field has data object that can be accessed in path by using '@' symbol: '/field_1@value', ['object/array', '@', 'length']
'#' - is the root element of schema state. Can be omitted.
A path can be relative. The relative path starts with '.' or '..' and resolved relatively fields it has used.
API set functions support path-multiplying:
- Comma-separated fields. Path 'array/1,2/field,prop' turns to 4 paths 'array/1/field', 'array/1/prop', 'array/2/field', 'array/2/prop'. Works for both field-part(part before '@') and data-part(part after '@') of path.
- Symbol
'*'turns into all props of object/array. Path 'array/*' (for array with length 3) turns to 'array/0', 'array/1', 'array/2'. Works only for field-part(part before '@') of path.
Each field has data object that is created according to JSON schema and can be changed through API Data object has the following props:
value?: anylength?: numberoneOf: numberfData:title: stringtype: stringrequired: booleancanAdd?: booleanplaceholder?: string
status:priority?: numberinvalid: number- 0 if all children is 0dirty: number- 0 if all children is 0untouched: number- 0 if all children is 0pending: number- 0 if all children is 0valid: boolean- null if pending else !invalidpristine: boolean- !dirtytouched: boolean- !untouched
params:liveUpdate?: booleanliveValidate?: booleanautofocus?: booleanreadonly?: booleandisabled?: booleanhidden?: booleannorender?: booleanviewer?: boolean
arrayItem?:canUp?: booleancanDown?: booleancanDel?: booleanmessages?: { [priority: number]: {textGroups: string[][]norender?: boolean} )
Returns data in path(es)
Set value in path. Returns ApiPromise
- path: string | string[] - path to data
- value: any - value to set
- opts?: setOpts - object with props:
- APIOptsType
- replace?: boolean - replace value if true or merge if false (actual for objects and arrays)
- setOneOf?: number - will try to switch to oneOf index
- macros?: string - executes macros
Returns form's value
- opts: getValueOpts - object with props:
- path?: string | string[] - path to field. If not passed value of all form will be returned.
- inital?: boolean - if true returns inital value else current value will be returned
Set form's value Returns ApiPromise
- value: any - value to set
- opts?: setValueOpts - object with props:
- APIOptsType
- path?: string | string[] - path to field. If not passed value of all form will be set.
- inital?: boolean - if true returns inital value else current value will be returned
- replace?: boolean - replace value if true or merge if false (actual for objects and arrays)
- setOneOf?: number - will try to switch to oneOf index
Returns form's default value
Set form's value to inital. Returns ApiPromise
- opts?: resetOpts - object with props:
- APIOptsType
- path?: string | string[] - path to field. If not passed all form will be reset.
- status?: 'untouched' | 'invalid' | 'dirty' | 'pending' = resets passed status instead of reseting form's value
Set form's value to default. Returns ApiPromise
- opts?: clearOpts - object with props:
- APIOptsType
- path?: string | string[] - path to field. If not passed all form will be cleared.
Validates form in path. Returns ApiPromise
- path: string | string[] - If path is true then validates full form. If path is false then cancel any validation that was set before.
- opts?: APIOptsType
Returns ApiPromise
- path: string | string[] - path to array field
- value - number determines how many items will added (or removed if negtive). If value is any[] then it will be concated to existing array's value
- opts?: APIOptsType
Returns ApiPromise
- path: string | string[] - path to array's item field
- op: 'up' | 'down' | 'first' | 'last' | 'del' | 'move' | 'shift' - operation that should be done to item
- opts?: arrayItemOpts - object with props:
- APIOptsType
- value?: number - for 'move' and 'shift'`operations. If 'move' then item will be moved to that position. If 'shift' then item will be shifted to that value
Set hidden param in path. Returns ApiPromise
- path: string | string[] - path to field
- value?: boolean - value that shold be set to param hidden. Default is true.
- opts?: APIOptsType
Shows properties of object in path and hides others. Returns ApiPromise
- path: string | string[] - path to field
- opts?: APIOptsType
Returns path of currently active field.
Executes all bathed updates. Returns ApiPromise
ApiPromise : API set functions returns promise that will be resolved after changes is made (actual only for asynchronous updates). Also returned promise has property 'vAsync' which is promise either. This promise will be resolved after all async validation that was triggered by update will be resolved.
ApiOptsType :
execute?: true | number- if true then execute synchronously and immediately. If number then executed asynchronously after the number in milliseconds passed. Default is 0, that means asynchronous execution right after calling code is finished. Multiple asynchronous commands are stacking in batch and executes together.noValidation?: boolean- No validation is made if true.
$ref?: string- used byfform. Reference to another part of the schema. Logically replaced with the thing that it points to. If set, then all other properties are ignored. Logically replaced with the thing that it points to. Togetger withallOfproperty, it is used to extend schemes.type?: string | string[]- used byfform. The basic type of this schema, can be one of * [string, number, object, array, boolean, null] * or an array of the acceptable typesenum?: any[]- used byfform. Enumerates the values that this schema can be e.g. {"type": "string", "enum": ["red", "green", "blue"]}definitions?: { [key: string]: JSONschema }- used byfform. Holds simple JSON Schema definitions for referencing from elsewhere.
title?: string- used byfform. Title of the field.default?: any- used byfform. Default value for the object represented by this schema.id?: string- This tells refs where the root of the document is located.$schema?: JSONschema;- It is recommended that the meta-schema is included in the root of any JSON Schema.description?: string- Schema description.
multipleOf?: number- The value must be a multiple of the number (e.g. 10 is a multiple of 5)maximum?: number- maximum value.exclusiveMaximum?: boolean- If true maximum must be > value, >= otherwise.minimum?: number- minimum value.exclusiveMinimum?: boolean- If true minimum must be < value, <= otherwise.
maxLength?: number- maximum length.minLength?: number- minimum length.pattern?: string- This is a regex string that the value must conform to.
items?: JSONschema | JSONschema[]- used byfform. Defines fields in array.additionalItems?: boolean | JSONschema- used byfform. Iffalsethen array limited toitemsproperty. Iftruethenitemsis used for array elements. IfJSONschemathen it is used for array elements which index is greater thenitemslength.maxItems?: number- used byfform. Maximum length of array. Used to calculatecanAddvalue in data-object.minItems?: number- used byfform. Used to calculatecanDelvalue in data-object.uniqueItems?: boolean- iftruethen array elements must be unique.
required?: string[] | boolean- used byfform.properties?: { [property: string]: JSONschema }- used byfform. The keys that can exist on the object with the json schema that should validate their valueadditionalProperties?: boolean | JSONschema- used byfform. Iffalse, then any keys that are not listed in thepropertiesor match thepatternPropertiesare not allowed.patternProperties?: { [pattern: string]: T }- The key of this object is a regex for which properties the schema applies todependencies?: { [key: string]: T | string[] }- If the key is present as property then the string of properties must also be present. If the value is a JSON Schema then it must. Also, be valid for the object if the key is present.maxProperties?: number- maximum number of properties.minProperties?: number- minimum number of properties.
oneOf?: JSONschema[]- used byfform. Switches the form between listed schemes. Must be valid against exactly one of the subschemas.allOf?: JSONschema[]- used byfform. Merges listed schemes. Must be valid against all of the subschemas.anyOf?: JSONschema[]- Must be valid against any of the subschemas.not?: JSONschema- Must not be valid against the given schema.
As JSON format doesn't support js-code all function moved to elements. So in the schema you should specify a reference to elements as a string value that starts with "^/". It will be resolved at fformCores creating.
Field's placeholder.
Inital values for parameters that can be futher changed in data-object
liveUpdate?: booleanliveValidate?: booleanautofocus?: booleanreadonly?: booleandisabled?: booleanhidden?: booleannorender?: booleanviewer?: boolean
Any additional inital data in data-object
References (divided by :) that points to elements. Merged into one object. If reference value without leading ^/ then ^/sets/ prepends to it. Used for component rendering.
Determines that the value controlled by the component itself (actual for objects and arrays). This means that fform will create state without routines that are normally executed for objects/arrays.
enum property extension. Keys are taken from enum. String converts to object with property {label}.
Transmits (and processes) data within the state. An array of objects with following properties: from - path (can be relative) from where value is taken, to - path (can be relative) to where value is placed, $ and args - data handler that process value when mapping. data handler receives value according to from property as the first parameter
During execution each function in data handler has access (as this) to special object with following properties:
api- API functions. Supports relative path.from- absolute path that points to value that were passed to data handlerto- absolute path that point to where result will be placedpath= absolute path points to location it is executed.
After data handler executed the result will be placed according to to property, even if value is undefined. Sometimes, it is not nessesary, so to prevent this behaviour use this.api.set(null) construction in any function during execution. Any API call of set or setValue methods prevents from setting result that returned by data handler.
Sync/async validators as an array of data handlers. Each data handler receives form value according to path as the first parameter when value changed.
During execution each validator has access (as this) to special object with following properties:
api- API functions. Supports relative path.path= absolute path points to location it is executed.
data handlers result expected to be following type: Array<MessageGroupType | string> | MessageGroupType | string;, where MessageGroupType is object with following properties:
group?: number- text group, default value is: 0 - for JSON validation, 1 - for sync validation, 2 - for async validation, 3 - for submit validation.data: string | string[]- message data. Can be reference to the elements and supports elements props processing for$_widgetand$_refproperties.priority?: number- Defines the priority layer the message will be set. Default priority is0. If0-priority layer is not empty the validation considered failed. Any other priority values used for information purposes only.path?: string- path of field where message will be placed. Default value is current schema path.[key: string]: any- any props (className, style, etc.) that will be set for this priority layer. inputClassName?: string; // className for input choosen from the message with lowest priority
For async validation data handlers should return Promise that will be resolved to the result of type described above. Notice, that due to data handler's limitation, the promise should be returne by the last function in a data handler.
data handler that receive value to determine which oneOf schema should be chosen. Receives form value according to schema path. Expected result is index of oneOf array.
Component customization.
Fields, objects, groups in an object/array layout
If true, then only the fields listed in the _layout property are displayed, otherwise fields that not listed in the _layout property will be added to the top layer.
FForm uses external JSON Validators by wrapping them and converting the result to a single format. There are 2 wrappers, for now, that can be found in addons/wrappers, one for is-my-json-valid, another for jsonschema. Use wrapper and pass the result as JSONValidator property for fformCores. Examle:
const jsonschemaWrapper = require('fform/addons/wrappers/jsonschema').default; const Validator = require('jsonschema').Validator; const JSONValidator = jsonschemaWrapper(new Validator());
Default group for JSON validation is 0 (more details about groups here).
Sync/async validation described here.
Each field of form is built by builder, that assembles field from the following blocks:
Wrapper- wraps all and add array item controls when the field is an array elementTitle- shows title property from the schema, and provide array add/del buttons when the field is an arrayBody- contains Main and Messages to align then togetherMain- in this block input element is placedMessages- element that shows messages (error, warnings, info, etc)
In _custom schema property, you can add/overwrite any property of any block. It supports the element's props processing. It merges with _presets refs on field build. See example for details.
Field receives a set of objects (structured as it described above) that is the parts of the elements (_presets and _custom props define it) that merged then into one object. All functions that is found by field's handler in that object binds to field's instance during render. The exception is the props that have leading _$ in their names or listed in _$skipKeys property.
For the object and array types, the JSON-schema's property _layout defines a layer that can be customized by setting the required props. It supports elements props processing.
Besides, it supports the $ _fieds property, which sets the order in which the fields listed in the definition property for object and in the items property for array will be displayed. In addition to the fields in $_fieds, you can add objects that are also processed by [elements props processing](# props-processing) and support the $_fieds property, which allows you to create layers with the desired level of nesting. See example for more details.
Elements is object that contains React components, functions, frequently used parts of components and, in principle, any other js or JSON code that can be referenced both from any part of the Elements and from the extended fields of the JSONSchema.
Elements can be extended, and in essence it is a repository of bricks of code from which the whole form is then assembled, and the degree of elementarity of these cypriots is determined by the developer.
Properties of elements are processed as follows:
^/- string value that begins with^/determines that value is the reference and resolved respectively_$- leading_$in property name prevent it value from deep processing, but if value is string and starts with^/resolving still made$_- leading$_in property name means than property has special processing_$skipKeys:string[]- props that listed in this array are prevented from deep processing, as if it name start with_$._%widget: string | Function- HTML tag or function that will we used as React-element. Can be reference to elements$_ref: string- reference starts with '^' path separated by/, multi-refs separated by:,example
{$_ref:'^/sets/base:^/sets/boolean'}$_reactRef: boolean | string- creates reference to element with default name if true, if value is string then it is used as name$_maps- maps data from state to element. Functions can be used to process data.
Any object in elements that has $ property threaten as data handler. It has following properties:
$: string- link (with leading^/) to function(s). Can be used in pipes (linux style, with|delimiter). Example^/fn/first | ^/fn/second. Output from first function send to second.replace?: boolean- iftruethe data handler's result will be replaced, otherwise merged.args?: any[]- arguments passed to very first function in$. Default['${...}']. Has several replacements:${<number>}- replaced with value that data handler receive according to number. If${...}passed then all values sent to input. Depending on the place where data handler is used it receive different values:- at
schema._stateMaps- value is taken according tofromproperty - at
schema._validatorsandschema._oneOfSelectorreceive form current value according to schema path - at
elements.$_mapsreceive no values - at
elements.<onEventMethod>receive event
- at
- Args that starts with
@replaced with data object value according to path. Example:@/value- Args starts with
!negated (!!negated twice). Example:!@/value
- Args starts with
update?: 'build' | 'data' | 'every'- for$_mapshandlers. Determines when it executes.build- on component build/rebuilddata- on data objectupdate,every` - on each update
As functions executed in pipe each function that used in handlers should return result as array (except for _oneOfSelector and _validators properties).
Each function (except for those ones that are used in _oneOfSelector) has access to API during runtime through this.api.
Any argument of args can be a data handler (an object with $ property), it will be executed (recursively as it args can be data handler too) and its result will be passed as a value.
$_maps: {path2property: string}: string | dataHandler | dataHandler[] is the object that decribes translation data from state's data objects to component properties.
Key path2property defines the path (with symbol / as delimiter) in object, where $_maps belongs, for example className/hidden. Notice: $_maps doesn't change the type of property if it was set before and is mergeable (i.e. array or object type), otherwise when needed object is created. For example, if you define something like this {"children": [], $_maps{"children/0":"@/anything"}} the type of children will always be array.
String value should start with @, and defines path in data object from where the value shold be taken, examle "className/hidden": "@/params/hidden[^]". Also, supports leading ! or !! to negate (convert to boolean) value, examle: "className/shown": "!@/params/hidden[^]".
data handler (array of it) process data it receives. In $_maps there is no default input values, so you have to define them in args property. Example:
{ "className": "", "$_maps": { "className/equal": { "$": "^/fn/equal", "args": ["@/someTestValue", "value2compare"] } } }
Here someTestValue property will be taken from data object and then passed as 1st argument with string value2compare as 2nd to function at elements.fn.equal, and the result will be set in className.equal with className converted to object.
Important notice: during runtime functions in data handler have acces to API througth this.api and can use api.get to gain access to data in another fields. It is not recommended, cause changing data in another field won't trigger data update in current. Instead use schema's _stateMaps propery to translate data from any other field's data to the current field's data object, and then take it from data object as it shown above.
widgets- contains react components that is used in form building, some of them:Section- renders object and array types of schemaGeneric- generic widget for many usesInput- widget that renders all types, except object and arrayBuilder- build field from blocksWrapper- wraps all others blocks and provides array item menu if neededItemMenu- renders array item menuCheckboxNull- renders tristate checkbox
sets- presets for frequently used field's schemes, some of them:base- basic set of blocks that used in every fieldsimple- basic set for non-object types of schemastring- set for string type of schematextarea- set for large string valuesinteger- set for integer type of schemaintegerNull- set for integer and null types of schemanumber- set for number type of schemanumberNull- set for number and null type of schemaboolean- set for boolean type of schemabooleanLeft- set for boolean type of schema with left placement of checkboxbooleanNull- set for boolean and null type of schemabooleanNullLeft- set for boolean and null type of schema with left placement of checkboxobject- set for object and array types of schemaarray- set for object and array types of schemaselect- set for enum valuesmultiselect- set for array of enum valuesradio- set for enum values as radio buttonscheckboxes- set for array of enum values as checkbox buttons
fn- functions that is used in data, event processing, some of them:api(fn: string, ...args: any[])- executesthis.api[fn](...args)format(str: string, ...args: any[])- replaces${<number>}instrwithargs[<number>]iif(iif: any, trueVal: any, falseVaL: any, ...args: any[])- ifiifis trusty returnstrueVal, otherwisefalseVaLnot(value: any, ...args: any[])- returns negatedvalue,argskeeps untouchedequal(value: any, ...args: any[])- tests ifvaluestrictly equal to any ofargseventValue: (event: any, ...args: any[])- returnsevent.target.value,argskeeps untouchedeventChecked: (event: any, ...args: any[])- returnsevent.target.checked,argskeeps untouchedeventMultiple: (event: any, ...args: any[])- returns selected values from multiselect,argskeeps untouchedparseNumber: (value: any, int: boolean, empty: number | null, ...args: any[])- conver value to number ifintis false, to iteger ifintis true. If value is empty string returnsempty.argskeeps untouchedsetValue(value: any, opts: any = {}, ...args: any[])- setvaluein state usingthis.api.setStatewithopts. Returns untouchedargs.liveUpdate- updates value not waiting for focus out (as if liveUpdate enabled)
parts- commonly used parts of JSON, js-code, some of them:Submit- submit buttonReset- reset buttonButton- buttonArrayAddButton- array add buttonArrayDelButton- array del buttonArrayEmpty- array is empty notificatorArrayItemMenu- array item menuExpander- expander to fill spaceRadioSelector- radio selector
extend(objects: any[])- merges elements with passed objects_$cx- simple classnames handler based on classnames with modificationexplanation
object property name added only if value is strict "true" or non-zero "number" (trusty in classnames), otherwise if value is trusty but not true or number it processes recursively_$cx.bindobjects with class replacements for_$cx.
FForm using classnames handler based on classnames/bind (_$cx property). Elements property _$cx.bind can be used to bind objects with class replacements to _$cx .
Most common classes that are used in elements:
fform-hidden - to hide elements
fform-message-priority-N - for message styles
fform-inline - to place elements in line
fform-required - to mark a title as required
fform-viewer - class for viewer
fform-layout - default class for object layout's elements
fform-shrink - to shrink an element
fform-expand - to expand an element
More classNames that can be applied to elements can be found in addons/styling/basic.json
Styles for the tacit and bootstrap frameworks are currently implemented. Example:
import 'bootstrap/dist/css/bootstrap.min.css'; import 'fform/addons/styling/fform.css' import 'fform/addons/styling/bootstrap.fform.css' import {elements} from 'fform'; import * as basicStyling from 'fform/addons/styling/basic.json' import * as bootstrapStyling from 'fform/addons/styling/bootstrap.json' const styledElements = elements.extend([basicStyling, bootstrapStyling]); const core = new FFormStateAPI({name, schema, elements: styledElements});
Use addon/dehydrator.js to convert state to string on server side and then pass it to the client. On the client side use the passed state as state prop of FForm component.
Server side:
const dehydrate = require('../addons/dehydrator').default; const core = new FFormStateAPI({name: 'core', schema, elements}); const state = core.getState(); let reState = dehydrate(state); // reState now string
Client side:
const reState = {reState string from server} const reCore = new FFormStateAPI({state: reState, name: 'core', schema, elements});