antd#Rate TypeScript Examples

The following examples show how to use antd#Rate. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: utils.tsx    From antdp with MIT License 6 votes vote down vote up
getItem = ({ attr, type, inputNode }: {
  attr?: Partial<ItemChildAttr<any, any>>;
  type?: ItemChildType;
  inputNode?: ((...arg: any[]) => React.ReactNode) | React.ReactNode;
}) => {
  let renderItem = undefined;
  if (type === 'Input') {
    const inputAttr = attr as InputProps;
    renderItem = <Input {...inputAttr} />;
  } else if (type === 'TextArea') {
    const inputAttr = attr as TextAreaProps;
    renderItem = <Input.TextArea {...inputAttr} />;
  } else if (type === 'InputNumber') {
    const inputAttr = attr as InputNumberProps;
    renderItem = <InputNumber {...inputAttr} />;
  } else if (type === 'AutoComplete') {
    const inputAttr = attr as AutoCompleteProps;
    renderItem = <AutoComplete {...inputAttr} />;
  } else if (type === 'Cascader') {
    const inputAttr = attr as CascaderProps;
    renderItem = <Cascader {...inputAttr} />;
  } else if (type === 'DatePicker') {
    const inputAttr = attr as DatePickerProps;
    renderItem = <DatePicker {...inputAttr} />;
  } else if (type === 'Rate') {
    const inputAttr = attr as RateProps;
    renderItem = <Rate {...inputAttr} />;
  } else if (type === 'Slider') {
    const inputAttr = attr as SliderSingleProps;
    renderItem = <Slider {...inputAttr} />;
  } else if (type === 'TreeSelect') {
    const inputAttr = attr as TreeSelectProps<any>;
    renderItem = <TreeSelect {...inputAttr} />;
  } else if (type === 'Select') {
    const inputAttr = attr as SelectProps<any>;
    renderItem = <Select {...inputAttr} />;
  } else if (type === 'Checkbox') {
    const inputAttr = attr as CheckboxGroupProps;
    renderItem = <Checkbox.Group {...inputAttr} />;
  } else if (type === 'Mentions') {
    const inputAttr = attr as MentionProps;
    renderItem = <Mentions {...inputAttr} />;
  } else if (type === 'Radio') {
    const inputAttr = attr as RadioProps;
    renderItem = <Radio.Group {...inputAttr} />;
  } else if (type === 'Switch') {
    const inputAttr = attr as SwitchProps;
    renderItem = <Switch {...inputAttr} />;
  } else if (type === 'TimePicker') {
    const inputAttr = attr as TimePickerProps;
    renderItem = <TimePicker {...inputAttr} />;
  } else if (type === 'Upload') {
    const inputAttr = attr as UploadProps;
    renderItem = <Upload {...inputAttr} />;
  } else if (type === 'RangePicker') {
    const inputAttr = attr as RangePickerProps;
    renderItem = <RangePicker {...inputAttr} />;
  } else if (type === 'Custom') {
    renderItem = inputNode;
  }
  return renderItem;
}
Example #2
Source File: rating.admin.tsx    From ui with GNU Affero General Public License v3.0 6 votes vote down vote up
RatingAdmin: React.FC<FieldAdminProps> = (props) => {
  const { t } = useTranslation()

  return (
    <div>
      <Form.Item
        label={t('type:rating:default')}
        name={[props.field.name as string, 'defaultValue']}
        labelCol={{ span: 6 }}
        extra={t('type:rating.clearNote')}
      >
        <Rate allowHalf allowClear />
      </Form.Item>
    </div>
  )
}
Example #3
Source File: rating.input.tsx    From ui with GNU Affero General Public License v3.0 6 votes vote down vote up
builder: FieldInputBuilderType = ({
  parseUrlValue,
  parseValue,
}) => function RatingInput ({
  field,
  urlValue,
}) {
  const { t } = useTranslation()

  let initialValue: number = undefined

  if (field.defaultValue) {
    try {
      initialValue = parseValue(field.defaultValue)
    } catch (e) {
      logger('invalid default value %O', e)
    }
  }

  if (urlValue) {
    initialValue = parseUrlValue(urlValue)
  }

  return (
    <div>
      <Form.Item
        name={[field.id]}
        rules={[{ required: field.required, message: t('validation:valueRequired') }]}
        initialValue={initialValue}
      >
        <Rate allowHalf />
      </Form.Item>
    </div>
  )
}
Example #4
Source File: index.tsx    From surveyo with Apache License 2.0 6 votes vote down vote up
function createQuestionField({question, updateQuestion}: any) {
  switch (question.type) {
    case 'SingleChoice':
      const options = question.options || [];
      return SingleChoiceQuestionField({question, updateQuestion, options});
    case 'Date':
      return (
        <DatePicker
          defaultValue={moment('2015/01/01', dateFormat)}
          format={dateFormat}
          disabled
        />
      );
    case 'Rating':
      let count = question.count || 3;
      return (
        <>
          <p>Maximum rating</p>
          <Radio.Group
            options={['3', '5', '10']}
            value={count}
            onChange={e => {
              count = e.target.value;
              updateQuestion({...question, count: e.target.value});
            }}
          />
          <Rate count={count} allowHalf />
        </>
      );
    case 'Text':
      return (
        <Input.TextArea placeholder="Short answer here" allowClear disabled />
      );
    case 'NetPromoterScore':
      return <NetPromoterScore disabled />;
  }
}
Example #5
Source File: BrickRate.tsx    From next-basics with GNU General Public License v3.0 5 votes vote down vote up
export function BrickRate(props: BrickRateProps): React.ReactElement {
  const { rateStyle, ...resProps } = props;
  const rateRef = useRef();
  const [value, setValue] = useState<number>();
  const defaultIcon = <>{props.type ? props.type : <StarOutlined />}</>;
  const icon = (
    <>{props.rateIcon ? <GeneralIcon icon={props.rateIcon} /> : defaultIcon}</>
  );
  const handleChange = (value: number): void => {
    setValue(value);
    props.onChange?.(value);
  };
  useEffect(() => {
    if (props.colors && props.colors.length > 0) {
      const colors = props.colors;
      const parentNodes = rateRef.current.rate;
      if (parentNodes) {
        const childNodes = parentNodes.childNodes;
        childNodes.forEach((child: any, index: number) => {
          if (index <= props.colors.length - 1) {
            child.style.color = colors[index];
          }
        });
      }
    }
  }, [props.colors]);
  useEffect(() => {
    setValue(props.value);
  }, [props.value]);
  return (
    <Rate
      {...resProps}
      ref={rateRef}
      onChange={handleChange}
      character={icon}
      style={rateStyle}
      value={value}
    />
  );
}
Example #6
Source File: index1.tsx    From jetlinks-ui-antd with MIT License 5 votes vote down vote up
GlobalComponent = {
    Rate,
    Input,
    MonthPicker,
    RangePicker,
    WeekPicker,
}
Example #7
Source File: config.tsx    From amiya with MIT License 5 votes vote down vote up
// 此函数只需要注册一次,你可以放在全局
registerTableRender('star', ({ text }: RenderProps) => {
  return <Rate count={Number(text + 1)} defaultValue={Number(text + 1)} disabled />
})
Example #8
Source File: form.tsx    From surveyo with Apache License 2.0 4 votes vote down vote up
export function SyForm(props: SyFormProps) {
  const [state, setState] = useState<SyFormState>({
    form: {id: props.data.id},
    entries: props.data.fields.map(field => ({
      field: {
        id: field.id,
      },
    })),
    submitted: false,
  });

  const [form] = Form.useForm();

  const [submit, {loading}] = useMutation(ADD_RESPONSE);

  if (state.submitted) {
    return (
      <Card type="inner">
        <Result
          status="success"
          title="Thank you!"
          subTitle="Your response has been recorded."
        />
      </Card>
    );
  }

  const handleChange = (idx: number) => ({
    DatePicker: (event: any) => {
      const value = event;
      setState(state =>
        update(state, {
          entries: {[idx]: {$merge: {date: value}}},
        })
      );
    },
    Input: (event: any) => {
      const value = event.target.value;
      setState(state =>
        update(state, {
          entries: {[idx]: {$merge: {text: value}}},
        })
      );
    },
    NetPromoterScore: (event: any) => {
      const value = event.target.value;
      setState(state =>
        update(state, {
          entries: {[idx]: {$merge: {netPromoterScore: value}}},
        })
      );
    },
    Radio: (event: any) => {
      const value = event.target.value;
      setState(state =>
        update(state, {
          entries: {[idx]: {$merge: {singleChoice: {id: value}}}},
        })
      );
    },
    Rate: (event: any) => {
      const value = event;
      setState(state =>
        update(state, {
          entries: {[idx]: {$merge: {rating: value}}},
        })
      );
    },
  });

  const createField = (field: FieldRef, idx: number) => {
    switch (field.type) {
      case 'Date':
        return (
          <DatePicker mode="date" onChange={handleChange(idx).DatePicker} />
        );
      case 'NetPromoterScore':
        return (
          <NetPromoterScore onChange={handleChange(idx).NetPromoterScore} />
        );
      case 'Rating':
        return (
          <Rate
            allowClear
            count={field.count!}
            onChange={handleChange(idx).Rate}
          />
        );
      case 'SingleChoice':
        return (
          <Radio.Group onChange={handleChange(idx).Radio}>
            {field.options!.map(option => (
              <Radio
                key={option.id!}
                value={option.id}
                style={{
                  display: 'block',
                  height: '30px',
                  lineHeight: '30px',
                }}
              >
                {option.title}
              </Radio>
            ))}
          </Radio.Group>
        );
      case 'Text':
        return (
          <Input
            placeholder="Write something..."
            onChange={handleChange(idx).Input}
          />
        );
    }
  };

  const createFieldItem = (field: any, idx: number): JSX.Element => (
    <Form.Item
      style={{margin: 0}}
      name={field.id}
      rules={[{required: field.required, message: 'This field is required.'}]}
    >
      {createField(field, idx)}
    </Form.Item>
  );

  async function handleSubmit() {
    await form.validateFields();
    try {
      await submit({
        variables: {
          response: {
            form: state.form,
            entries: state.entries,
          } as AddResponseInput,
        },
      });
      setState(state => update(state, {$merge: {submitted: true}}));
    } catch (e) {
      console.error(e);
      message.error('Internal error: could not submit response');
    }
  }

  const fields = props.data.fields.map((field, idx) => {
    return (
      <Row gutter={[16, 16]} key={field.id}>
        <Col span={24}>
          <Card key={idx} type="inner" style={{borderRadius: '4px'}}>
            <Row gutter={[16, 16]}>
              <Col span={24}>
                <SyTitle title={field.title} required={field.required} />
              </Col>
            </Row>
            <Row gutter={[16, 16]}>
              <Col span={24}>{createFieldItem(field, idx)}</Col>
            </Row>
          </Card>
        </Col>
      </Row>
    );
  });

  const submitButton = (
    <Row gutter={[16, 16]}>
      <Col span={24} style={{textAlign: 'right'}}>
        <Form.Item>
          <Button htmlType="submit" loading={loading} type="primary">
            Submit
          </Button>
        </Form.Item>
      </Col>
    </Row>
  );

  return (
    <PageHeader ghost={true} title={props.data.title}>
      <Form form={form} onFinish={handleSubmit}>
        {fields}
        {submitButton}
      </Form>
    </PageHeader>
  );
}
Example #9
Source File: FieldsInit.tsx    From amiya with MIT License 4 votes vote down vote up
install = (registerField: (fieldType: string, field: RegisterFieldProps) => void) => {
  // 注册输入框
  registerField(FORM_TYPE_INPUT, {
    type: FORM_TYPE_INPUT,
    defaultValue: FORM_DEFAULT_VALUE_INPUT,
    render: ({ field, readonly, getFieldValue }: AnyKeyProps) => {
      return readonly ? (
        <span className="ay-form-text">{getFieldValue(field.key) || FORM_READONLY_EMPTY}</span>
      ) : (
        <Input
          placeholder={`${locale.form.pleaseInput}${field.title || ''}${locale.form.pleaseInputAfter}`}
          disabled={readonly}
          maxLength={INPUT_DEFAULT_MAXLENGTH}
          allowClear={FORM_DEFAULT_ALLOW_CLEAR}
          {...omitObj(field.props, 'readonly')}
        />
      )
    }
  })

  // 注册搜索框
  registerField(FORM_TYPE_SEARCH, {
    type: FORM_TYPE_SEARCH,
    defaultValue: FORM_DEFAULT_VALUE_SEARCH,
    render: ({ field, readonly, getFieldValue, formInstans }: AnyKeyProps) => {
      return readonly ? (
        <span className="ay-form-text">{getFieldValue(field.key) || FORM_READONLY_EMPTY}</span>
      ) : (
        <Input.Search
          placeholder={`${locale.form.pleaseInput}${field.title || ''}${locale.form.pleaseInputAfter}`}
          disabled={readonly}
          onPressEnter={e => {
            e.preventDefault()
            formInstans.submit()
          }}
          onSearch={() => formInstans.submit()}
          maxLength={INPUT_DEFAULT_MAXLENGTH}
          allowClear={FORM_DEFAULT_ALLOW_CLEAR}
          enterButton
          {...field.props}
        />
      )
    }
  })

  // 注册数字框
  registerField(FORM_TYPE_NUMBER, {
    type: FORM_TYPE_NUMBER,
    defaultValue: FORM_DEFAULT_VALUE_NUMBER,
    render: ({ field, readonly, getFieldValue }: AnyKeyProps) =>
      readonly ? (
        <span className="ay-form-text">{getFieldValue(field.key) || FORM_READONLY_EMPTY}</span>
      ) : (
        <InputNumber
          className="max-width"
          disabled={readonly}
          min={NUMBER_DEFAULT_MIN}
          max={NUMBER_DEFAULT_MAX}
          {...field.props}
        />
      )
  })

  // 注册百分比数字框
  registerField(FORM_TYPE_PERCENT, {
    type: FORM_TYPE_PERCENT,
    defaultValue: FORM_DEFAULT_VALUE_PERCENT,
    render: ({ field, readonly, getFieldValue }: AnyKeyProps) =>
      readonly ? (
        <span className="ay-form-text">{getFieldValue(field.key) || FORM_READONLY_EMPTY}%</span>
      ) : (
        <InputNumber
          className="max-width"
          disabled={readonly}
          min={NUMBER_DEFAULT_MIN}
          max={PERCENT_DEFAULT_MAX}
          formatter={(value?: string | number) => (value !== '' ? `${value}%` : '')}
          parser={(value?: string) => (value || '').replace('%', '')}
          {...field.props}
        />
      )
  })

  // 注册密码框
  registerField(FORM_TYPE_PASSWORD, {
    type: FORM_TYPE_PASSWORD,
    defaultValue: FORM_DEFAULT_VALUE_PASSWORD,
    render: ({ field, readonly, getFieldValue }: AnyKeyProps) =>
      readonly ? (
        <span className="ay-form-text">
          {(getFieldValue(field.key) + '').replace(/./g, '*') || FORM_READONLY_EMPTY}
        </span>
      ) : (
        <Input.Password
          placeholder={`${locale.form.pleaseInput}${field.title || ''}${locale.form.pleaseInputAfter}`}
          disabled={readonly}
          allowClear={FORM_DEFAULT_ALLOW_CLEAR}
          {...field.props}
        />
      )
  })

  // 注册多行文本框
  registerField(FORM_TYPE_TEXTAREA, {
    type: FORM_TYPE_TEXTAREA,
    defaultValue: FORM_DEFAULT_VALUE_TEXTAREA,
    render: ({ field, readonly, getFieldValue }: AnyKeyProps) =>
      readonly ? (
        <span className="ay-form-text">{getFieldValue(field.key) || FORM_READONLY_EMPTY}</span>
      ) : (
        <Input.TextArea
          placeholder={`${locale.form.pleaseInput}${field.title || ''}${locale.form.pleaseInputAfter}`}
          disabled={readonly}
          allowClear={FORM_DEFAULT_ALLOW_CLEAR}
          maxLength={TEXTAREA_DEFAULT_MAXLENGTH}
          {...field.props}
        />
      )
  })

  // 注册选择框
  registerField(FORM_TYPE_SELECT, {
    type: FORM_TYPE_SELECT,
    defaultValue: FORM_DEFAULT_VALUE_SELECT,
    render: ({ field, readonly, getFieldValue }: AnyKeyProps) => {
      if (readonly) {
        let value = getFieldValue(field.key)
        let text = ''
        if (Array.isArray(value)) {
          if (!value.length) {
            text = FORM_READONLY_EMPTY
          }
          text = value.map(item => getValueByOptions(item, field.options)).join(field.splitText || '、')
        } else {
          text = getValueByOptions(value, field.options)
        }
        return <span className="ay-form-text">{text || FORM_READONLY_EMPTY}</span>
      }

      return (
        <AySelect
          placeholder={`${locale.form.pleaseSelect}${field.title || ''}${locale.form.pleaseSelectAfter}`}
          disabled={readonly}
          allowClear={FORM_DEFAULT_ALLOW_CLEAR}
          options={field.options}
          {...field.props}
        />
      )
    }
  })

  // 注册开关
  registerField(FORM_TYPE_SWITCH, {
    type: FORM_TYPE_SWITCH,
    defaultValue: FORM_DEFAULT_VALUE_SWITCH,
    valuePropName: 'checked',
    render: ({ field, readonly }: AnyKeyProps) => <Switch disabled={readonly} {...field.props} />
  })

  // 注册单个选择框
  registerField(FORM_TYPE_CHECKBOX, {
    type: FORM_TYPE_CHECKBOX,
    defaultValue: FORM_DEFAULT_VALUE_CHECKBOX,
    valuePropName: 'checked',
    render: ({ field, readonly }: AnyKeyProps) => <Checkbox disabled={readonly} {...field.props} />
  })

  // 注册多个选择框
  registerField(FORM_TYPE_CHECKBOX_GROUP, {
    type: FORM_TYPE_CHECKBOX_GROUP,
    defaultValue: FORM_DEFAULT_VALUE_CHECKBOX_GROUP,
    render: ({ field, readonly }: AnyKeyProps) => (
      <Checkbox.Group disabled={readonly} options={field.options} {...field.props} />
    )
  })

  // 注册多个单选框
  registerField(FORM_TYPE_RADIO_GROUP, {
    type: FORM_TYPE_RADIO_GROUP,
    defaultValue: FORM_DEFAULT_VALUE_RADIO_GROUP,
    render: ({ field, readonly }: AnyKeyProps) => (
      <Radio.Group disabled={readonly} options={field.options} {...field.props} />
    )
  })

  // 注册日期
  registerField(FORM_TYPE_DATE, {
    type: FORM_TYPE_DATE,
    defaultValue: FORM_DEFAULT_VALUE_DATE,
    render: ({ field, readonly, getFieldValue }: AnyKeyProps) => {
      let text = getFieldValue(field.key, readonly)
      if (typeof text !== 'string') {
        text = ''
      }
      return readonly ? (
        <span className="ay-form-text">{text || FORM_READONLY_EMPTY}</span>
      ) : (
        <DatePicker
          className="max-width"
          placeholder={`${locale.form.pleaseSelect}${field.title || ''}${locale.form.pleaseSelectAfter}`}
          {...field.props}
        />
      )
    }
  })

  // 注册区间日期
  registerField(FORM_TYPE_DATE_RANGE, {
    type: FORM_TYPE_DATE_RANGE,
    defaultValue: FORM_DEFAULT_VALUE_DATE_RANGE,
    render: ({ field, readonly, getFieldValue }: AnyKeyProps) => {
      let text = getFieldValue(field.key, readonly)
      if (Array.isArray(text)) {
        if (text[0] === null) {
          text = null
        } else if (text) {
          text = [
            <span key="start" style={{ display: 'inline-block' }}>
              {(text[0] || '').toString()}
            </span>,
            <span key="divider" style={{ margin: '0 0.5em' }}>
              {locale.form.dateTo}
            </span>,
            <span key="end" style={{ display: 'inline-block' }}>
              {(text[1] || '').toString()}
            </span>
          ]
        }
      }
      return readonly ? (
        <span className="ay-form-text">{text || FORM_READONLY_EMPTY}</span>
      ) : (
        <DatePicker.RangePicker
          placeholder={[locale.form.startDate, locale.form.endDate]}
          className="max-width"
          {...field.props}
        />
      )
    }
  })

  // 注册空节点
  registerField(FORM_TYPE_EMPTY, {
    type: FORM_TYPE_EMPTY,
    defaultValue: FORM_DEFAULT_VALUE_EMPTY,
    render: () => <input hidden type="text" />
  })

  // 注册评分
  registerField(FORM_TYPE_RATE, {
    type: FORM_TYPE_RATE,
    defaultValue: FORM_DEFAULT_VALUE_RATE,
    render: ({ field, readonly }: AnyKeyProps) => <Rate disabled={readonly} {...field.props} />
  })

  // 滑动输入条
  registerField(FORM_TYPE_SLIDER, {
    type: FORM_TYPE_SLIDER,
    defaultValue: FORM_DEFAULT_VALUE_SLIDER,
    render: ({ field, readonly }: AnyKeyProps) => <Slider disabled={readonly} {...field.props} />
  })

  // 标签选择
  registerField(FORM_TYPE_TAG_GROUP, {
    type: FORM_TYPE_TAG_GROUP,
    defaultValue: FORM_DEFAULT_VALUE_TAG_GROUP,
    render: ({ field, readonly }: AnyKeyProps) => (
      <AyTagGroup readonly={readonly} options={field.options} {...field.props} />
    )
  })

  // 卡片选择
  registerField(FORM_TYPE_CARD_GROUP, {
    type: FORM_TYPE_CARD_GROUP,
    defaultValue: FORM_DEFAULT_VALUE_CARD_GROUP,
    render: ({ field, readonly }: AnyKeyProps) => (
      <AyCardGroup readonly={readonly} options={field.options} {...field.props} />
    )
  })

  // 注册 html
  registerField(FORM_TYPE_HTML, {
    type: FORM_TYPE_HTML,
    defaultValue: FORM_DEFAULT_VALUE_HTML,
    render: ({ field }: AnyKeyProps) => <div dangerouslySetInnerHTML={{ __html: field.html }}></div>
  })
}