Skip to content

Latest commit

 

History

History
596 lines (528 loc) · 24.1 KB

CONFIG.adoc

File metadata and controls

596 lines (528 loc) · 24.1 KB

Config format

Has 7 sections:

{conjunctions, operators, widgets, types, funcs, settings, fields}

Each section is described below.

Usually it’s enough to just reuse basic config, provide your own fields and maybe change some settings.
Optionally you can override some options in basic config or add your own types/widgets/operators (or even conjunctions like XOR or NOR).

There are functions for building query string: formatConj, formatValue, formatOp, formatField, formatFunc which are used for QbUtils.queryString().
They have common param isForDisplay - false by default, true will be used for QbUtils.queryString(immutableTree, config, true) (see 3rd param true).
Also there are similar mongoConj, mongoFormatOp, mongoFormatValue, mongoFunc for building MongoDb query with QbUtils.mongodbFormat().
And sqlFormatConj, sqlFormatOp, sqlFormatValue, sqlFormatReverse, sqlFunc for building SQL where query with QbUtils.sqlFormat().

💡
Example: demo config

 

Basic config

import {BasicConfig} from 'react-awesome-query-builder';
const {
    conjunctions: {
        AND,
        OR
    },
    operators: {
        equal,
        not_equal,
        less,
        less_or_equal,
        greater,
        greater_or_equal,
        like,
        not_like,
        between,
        not_between,
        range_between, // like `between`, but for slider
        range_not_between,
        is_empty,
        is_not_empty,
        select_equals, // like `equal`, but for select
        select_not_equals,
        select_any_in,
        select_not_any_in,
        multiselect_equals, // like `equal`, but for multiselect
        multiselect_not_equals,
        proximity, // complex operator with options
    },
    widgets: {
      text,
      number,
      slider,
      rangeslider,
      select,
      multiselect,
      date,
      time,
      datetime,
      boolean,
      field, // to compare field with another field of same type
      func, // to compare field with result of function
    },
    types: {
      text,
      number,
      date,
      time,
      datetime,
      select,
      multiselect,
      boolean,
    },
    settings
} = BasicConfig;

const myConfig = {
  ...BasicConfig, // reuse basic config

  fields: {
    stock: {
        label: 'In stock',
        type: 'boolean',
    },
    // ... my other fields
  }
};

 

Sections

config.fields

{
  // simple
  qty: {
    type: 'number',
    label: 'Quantity',
  },
  // complex
  user: {
    type: '!struct', // special keyword for comlex fields
    label: 'User',
    subfields: {
      // subfields of complex field
      name: {
        type: 'text',
        label: 'Name',
        label2: 'User name', //optional, see below
      },
    },
  },
  ...
}
key required default meaning

type

+

One of types described in config.types or !struct for complex field

subfields

+ for !struct type

Config for subfields of complex field (multiple nesting is supported)

label

+

Label to be displayed in field list
(If not specified, fields’s key will be used instead)

label2

Can be optionally specified for nested fields.
By default, if nested field is selected (eg. name of user in example above), <FieldDropdown> component will show name.
Just name can be confusing, so can be overriden by setting label2 to something like User name.
As alternative, you can use <FieldCascader> component which handles nested fields right. See renderField in settings.

tooptip

Optional tooltip to be displayed in field list by hovering on item

listValues

+ for Select, MultiSelect widgets

List of values for Select widget.
Example: { yellow: 'Yellow', green: 'Green' } where Yellow - label to display at list of options

allowCustomValues

- for MultiSelect widget

false

If true, user can provide own options in multiselect, otherwise they will be limited to listValues

defaultValue

Default value

fieldSettings

Settings for widgets, will be passed as props. Example: {min: 1, max: 10}
Available settings for Number and Slider widgets: min, max, step. Slider also supports marks (example: { 0: "0%", 100: "100%" }).
Available settings for date/time widgets: timeFormat, dateFormat, valueFormat, use12Hours.

preferWidgets

See usecase at examples/demo for slider field.
Its type is number. There are 3 widgets defined for number type: number, slider, rangeslider.
So setting preferWidgets: ['slider', 'rangeslider'] will force rendering slider, and setting preferWidgets: ['number'] will render number input.

operators, defaultOperator, widgets, valueSources

You can override config of corresponding type (see below at section config.types)

mainWidgetProps

Shorthand for widgets.<main>.widgetProps

excludeOperators

Can exclude some operators, eg. proximity for text type

funcs

If comparing with funcs is enabled for this field (valueSources contains func), you can also limit list of funcs to be compared (by default will be available all funcs from config.funcs with returnType matching field’s type)

hideForSelect

false

If true, field will appear only at right side (when you compare field with another field)

hideForCompare

false

If true, field will appear only at left side

 
 

config.settings

import en_US from 'antd/lib/locale-provider/en_US';
import {Widgets} from 'react-awesome-query-builder';
const { FieldCascader, FieldDropdown } = Widgets;
{
  valueSourcesInfo: {
    value: {
      label: "Value"
    },
    field: {
      label: "Field",
      widget: "field",
    },
    func: {
        label: "Function",
        widget: "func",
    }
  },
  locale: {
      short: 'ru',
      full: 'ru-RU',
      antd: ru_RU,
  },
  renderField: (props) => <FieldCascader {...props} />,
  renderOperator: (props) => <FieldDropdown {...props} />,
  renderFunc: (props) => <FieldDropdown {...props} />,
  canReorder: true,
  canRegroup: true,
  hideConjForOne: true,
  maxNesting: 10,
  showLabels: false,
  showNot: true,
  setOpOnChangeField: ['keep', 'default'],
  customFieldSelectProps: {
      showSearch: true
  },
  ...
}

Behaviour settings:

key default meaning

valueSourcesInfo

{value: {}}

By default fields can be compared with values.
If you want to enable comparing with another fields, add field like in example above.
If you want to enable comparing with result of function, add func like in example above.

canReorder

true

Activate reordering support for rules and groups of rules?

canRegroup

true

Allow move rules (or groups) in/out groups during reorder?
False - allow "safe" reorder, means only reorder at same level

showNot

true

Show NOT together with AND/OR?

maxNesting

Max nesting for rule groups.
Set 1 if you don’t want to use groups at all. This will remove also Add group button.

immutableGroupsMode

false

Not allow to add/delete rules or groups, but allow change

setOpOnChangeField

['keep', 'default']

Strategies for selecting operator for new field (used by order until success):
default (default if present), keep (keep prev from last field), first, none

clearValueOnChangeField

false

Clear value on field change? false - if prev & next fields have same type (widget), keep

clearValueOnChangeOp

false

Clear value on operator change?

canLeaveEmptyGroup

false

Leave empty group after deletion or add 1 clean rule immediately?

canCompareFieldWithField

For <ValueFieldWidget> - Function for building right list of fields to compare field with field
(string leftField, Object leftFieldConfig, string rightField, Object rightFieldConfig) ⇒ boolean
For type == select/multiselect you can optionally check listValues

Render settings:

key default meaning

renderSize

small

Size of AntDesign components - small or large

renderField

(props) ⇒ <FieldSelect {…​props} />

Render fields list
Available widgets: FieldSelect, FieldDropdown, FieldCascader, VanillaFieldSelect (from Widgets)

renderOperator

(props) ⇒ <FieldSelect {…​props} />

Render operators list
Available widgets: FieldSelect, FieldDropdown, VanillaFieldSelect

renderFunc

(props) ⇒ <FieldSelect {…​props} />

Render functions list
Available widgets: FieldSelect, FieldDropdown, VanillaFieldSelect

showLabels

false

Show labels above all fields?

hideConjForOne

true

Don’t show conjunctions switcher for only 1 rule?

maxLabelsLength

100

To shorten long labels of fields/values (by length, i.e. number of chars)

dropdownPlacement

bottomLeft

Placement of antdesign’s dropdown pop-up menu

renderConjsAsRadios

false

How to render conjunctions switcher? true - use RadioGroup, false - use ButtonGroup

customFieldSelectProps

{}

You can pass props to Select field widget. Example: {showSearch: true}

groupActionsPosition

topRight

You can change the position of the group actions to the following:
topLeft, topCenter, topRight, bottomLeft, bottomCenter, bottomRight

Other settings:

key default meaning

locale

en

Locale used for AntDesign widgets

formatReverse

Function for formatting query string, used to format rule with reverse operator which haven’t formatOp.
(string q, string operator, string reversedOp, Object operatorDefinition, Object revOperatorDefinition, bool isForDisplay) ⇒ string
q - already formatted rule for opposite operator (which have formatOp)
return smth like "NOT(" + q + ")"

formatField

Function for formatting query string, used to format field
(string field, Array parts, string label2, Object fieldDefinition, Object config, bool isForDisplay) ⇒ string
parts - list of fields’s keys for struct field
label2 - field’s label2 OR parts joined by fieldSeparatorDisplay
Default impl will just return field (or label2 for isForDisplay==true)

fieldSeparator

.

Separaor for struct fields. Also used for formatting

fieldSeparatorDisplay

.

Separaor for struct fields to show at field’s select tooltip.

Localization:

key default

valueLabel

Value

valuePlaceholder

Value

fieldLabel

Field

operatorLabel

Operator

funcLabel

Function

fieldPlaceholder

Select field

funcPlaceholder

Select function

operatorPlaceholder

Select operator

deleteLabel

null

delGroupLabel

null

addGroupLabel

Add group

addRuleLabel

Add rule

notLabel

Not

valueSourcesPopupTitle

Select value source

removeRuleConfirmOptions

If you want to ask confirmation of removing non-empty rule/group, add these options.
List of all valid properties is here

removeRuleConfirmOptions.title

Are you sure delete this rule?

removeRuleConfirmOptions.okText

Yes

removeRuleConfirmOptions.okType

danger

removeGroupConfirmOptions.title

Are you sure delete this group?

removeGroupConfirmOptions.okText

Yes

removeGroupConfirmOptions.okType

danger

 
 

config.conjunctions

{
  AND: {
    label: 'And',
    formatConj: (children, _conj, not) => ( (not ? 'NOT ' : '') + '(' + children.join(' || ') + ')' ),
    reversedConj: 'OR',
    mongoConj: '$and',
  },
  OR: {...},
}

where AND and OR - available conjuctions (logical operators). You can add NOR if you want.

key required meaning

label

+

Label to be displayed in conjunctions swicther

formatConj

+

Function for formatting query, used to join rules into group with conjunction.
(Immultable.List children, string conj, bool not, bool isForDisplay) ⇒ string
children - list of already formatted queries (strings) to be joined with conjuction

mongoConj

+ for MongoDB format

Name of logical operator for MongoDb

sqlFormatConj

+ for SQL format

See formatConj

reversedConj

Opposite logical operator.
Can be used to optimize !(A OR B) to !A && !B (done for MongoDB format)

 
 

config.operators

{
  equal: {
    label: 'equals',
    reversedOp: 'not_equal',
    labelForFormat: '==',
    cardinality: 1,
    isUnary: false,
    formatOp: (field, _op, value, _valueSrc, _valueType, opDef) => `${field} ${opDef.labelForFormat} ${value}`,
    mongoFormatOp: (field, op, value) => ({ [field]: { '$eq': value } }),
  },
  ..
}
key required default meaning

label

+

Label to be displayed in operators select component

reversedOp

+

Opposite operator.

isUnary

false

true for is_empty operator only

cardinality

1

Number of right operands (1 for binary, 2 for between)

formatOp

+

Function for formatting query string, used to join operands into rule.
(string field, string op, mixed value, string valueSrc, string valueType, Object opDef, Object operatorOptions, bool isForDisplay) ⇒ string
value - string (already formatted value) for cardinality==1 -or- Immutable.List of strings for cardinality>1

labelForFormat

If formatOp is missing, labelForFormat will be used to join operands when building query string

mongoFormatOp

+ for MongoDB format

Function for formatting MongoDb expression, used to join operands into rule.
(string field, string op, mixed value, bool useExpr, string valueSrc, string valueType, Object opDef, Object operatorOptions) ⇒ object
value - mixed for cardinality==1 -or- Array for cardinality>2
useExpr - true if resulted expression will be wrapped in {'$expr': {…​}} (used only if you compare field with another field or function) (you need to use aggregation operators in this case, like $eq (aggregation) instead of $eq)

sqlOp

+ for SQL format

Operator name in SQL

sqlFormatOp

- for SQL format

Function for advanced formatting SQL WHERE query if just sqlOp is not enough.
(string field, string op, mixed value, string valueSrc, string valueType, Object opDef, Object operatorOptions) ⇒ object
value - mixed for cardinality==1 -or- Array for cardinality>2

valueLabels

+ for cardinality==2

Labels to be displayed on top of 2 values widgets if config.settings.showLabels is true
Example: ['Value from', {label: 'Value to', placeholder: 'Enter value to'}]

textSeparators

+ for cardinality==2

Labels to be displayed before each 2 values widgets
Example: [null, 'and']

options

Special for proximity operator

isSpecialRange

false

Special for cardinality==2. Used to show 1 range widget instead of 2 widgets (see range_between operator for rangeslider widget in demo)

ℹ️

There is also special proximity operator, its options are rendered with <ProximityOperator>.

import {Operators: {ProximityOperator}} from 'react-awesome-query-builder';

 
 

config.widgets

import {Widgets} from 'react-awesome-query-builder';
const {
    TextWidget,
    NumberWidget,
    SelectWidget,
    MultiSelectWidget,
    DateWidget,
    BooleanWidget,
    TimeWidget,
    DateTimeWidget,
    ValueFieldWidget,
    FuncWidget
} = Widgets;
{
  text: {
    type: 'text',
    valueSrc: 'value',
    factory: (props) => <TextWidget {...props} />,
    formatValue: (val, _fieldDef, _wgtDef, isForDisplay) => (isForDisplay ? '"' + val + '"' : JSON.stringify(val)),
    mongoFormatValue: (val, _fieldDef, _wgtDef) => (val),
    validateValue: (val, _fieldDef) => (val.length < 5),
    // Options:
    valueLabel: "Text",
    valuePlaceholder: "Enter text",
    // Custom props (https://ant.design/components/input/):
    customProps: {
        maxLength: 3
    },
  },
  ..
},
key required default meaning

type

+

One of types described in config.types

factory

+

React function component

formatValue

+

Function for formatting widget’s value in query string.
(mixed val, Object fieldDef, Object wgtDef, bool isForDisplay, string op, Object opDef) ⇒ string

mongoFormatValue

- for MongoDB format

v ⇒ v

Function for formatting widget’s value in MongoDb query.
(mixed val, Object fieldDef, Object wgtDef, string op, Object opDef) ⇒ object

sqlFormatValue

- for SQL format

v ⇒ SqlString.escape(v)

Function for formatting widget’s value in SQL WHERE query.
(mixed val, Object fieldDef, Object wgtDef, string op, Object opDef) ⇒ string

validateValue

Function to validate entered value.
(mixed val, Object fieldDef) ⇒ boolean

valueLabel

config.settings.valueLabel

Common option, text to be placed on top of widget if config.settings.showLabels is true

valuePlaceholder

config.settings.valuePlaceholder

Common option, placeholder text to be shown in widget for empty value

timeFormat

HH:mm:ss

Option for <TimeWidget>, <DateTimeWidget> to display time in widget. Example: 'HH:mm'

use12Hours

false

Option for <TimeWidget>

dateFormat

YYYY-MM-DD

Option for <DateWidget>, <DateTimeWidget> to display date in widget. Example: YYYY-MM-DD

valueFormat

Option for <TimeWidget>, <DateWidget>, <DateTimeWidget> to format value to be passed in formatValue(). Example: YYYY-MM-DD HH:mm

labelYes, labelNo

Option for <BooleanWidget>

customProps

You can pass any props directly to widget with customProps.
For example enable search for <Select> widget: customProps: {showSearch: true}

ℹ️
There is special field widget, rendered by <ValueFieldWidget>.
It can be used to compare field with another field of same type.
To enable this feature set valueSources of type to ['value', 'field''] (see below in config.types).
ℹ️
There is special func widget, rendered by <FuncWidget>.
It can be used to compare field with result of function (see config.funcs).
To enable this feature set valueSources of type to ['value', 'func''] (see below in config.types).

 
 

config.types

{
  time: {
      valueSources: ['value', 'field', 'func'],
      defaultOperator: 'equal',
      widgets: {
          time: {
              operators: ['equal', 'between'],
              widgetProps: {
                  valuePlaceholder: "Time",
                  timeFormat: 'h:mm:ss A',
                  use12Hours: true,
              },
              opProps: {
                  between: {
                      valueLabels: ['Time from', 'Time to'],
                  },
              },
          },
      },
  },
  ..
}
key required default meaning

valueSources

keys of valueSourcesInfo at config.settings

Array with values 'value', 'field', 'func'. If 'value' is included, you can compare field with values. If 'field' is included, you can compare field with another field of same type. If 'func' is included, you can compare field with result of function (see config.funcs).

defaultOperator

If specified, it will be auto selected when user selects field

widgets.*

+

Available widgets for current type and their config.
Normally there is only 1 widget per type. But see type number at examples/demo - it has 3 widhets number, slider, rangeslider.
Or see type select - it has widget select for operator = and widget multiselect for operator IN.

widgets.<widget>.operators

List of operators for widget, described in config.operators

widgets.<widget>.widgetProps

Can be used to override config of corresponding widget specified in config.widgets. Example: {timeFormat: 'h:mm:ss A'} for time field with AM/PM.

widgets.<widget>.opProps.<operator>

Can be used to override config of operator for widget. Example: opProps: { between: {valueLabels: ['Time from', 'Time to']} } for building range of times.

 
 

config.funcs

{
  lower: {
    label: 'Lowercase',
    sqlFunc: 'LOWER',
    mongoFunc: '$toLower',
    returnType: 'text',
    args: {
      str: {
        type: 'text',
        valueSources: ['value', 'field'],
      }
    }
  },
  ..
}
key required default meaning

returnType

+

One of types described in config.types

label

same as func key

Label to be displayed in functions list

formatFunc

Example: for isForDisplay==false - FUNC(val1, val2), for isForDisplay==true - FUNC(arg1: val1, arg2: val2)

Function for formatting func expression in query rule.
(Object args, bool isForDisplay) ⇒ string
where args is object {<arg name> : <arg value>}

sqlFunc

- for SQL format

same as func key

Func name in SQL

sqlFormatFunc

- for SQL format

Can be used instead of sqlFunc. Function with 1 param - args object {<arg name> : <arg value>}, should return formatted function expression string.
Example: SUM function can be formatted with ({a, b}) ⇒ a + " + " + b

mongoFunc

- for MongoDB format

same as func key

Func name in Mongo

mongoArgsAsObject

false

Some functions like $rtrim supports named args, other ones like $slice takes args as array

mongoFormatFunc

- for MongoDB format

Can be used instead of mongoFunc. Function with 1 param - args object {<arg name> : <arg value>}, should return formatted function expression object.

args.*

Arguments of function. Config is almost same as for simple fields

args.<arg>.label

arg’s key

Label to be displayed in arg’s label or placeholder (if config.settings.showLabels is false)

args.<arg>.type

+

One of types described in config.types

args.<arg>.valueSources

keys of valueSourcesInfo at config.settings

Array with values 'value', 'field', 'func', 'const'.
const requires defaultValue

args.<arg>.defaultValue

Default value

args.<arg>.listValues

+ for Select, MultiSelect widgets

List of values for Select widget.
Example: { yellow: 'Yellow', green: 'Green' } where Yellow - label to display at list of options

args.<arg>.fieldSettings

Settings for widgets, will be passed as props. Example: {min: 1, max: 10}

args.<arg>.isOptional

false

Last args can be optional

renderBrackets

['(', ')']

Can render custom function brackets in UI (or not render).

renderSeps

[', ']

Can render custom arguments separators in UI (other than ,).