lodash#isNull JavaScript Examples

The following examples show how to use lodash#isNull. 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: Nav.js    From kaikas-tutorial with MIT License 6 votes vote down vote up
Nav = ({ network }) => (
  <header className="Nav">
    <div className="Nav__inner">
      <h1 className="Nav__logo">
        <a href="/">
          <img
            src="images/logo-kaikas-tutorial.png"
            alt="Kaikas Tutorial"
          />
        </a>
      </h1>
      <div className={cx('Nav__network', {
        'Nav__network--error': isNull(network),
        'Nav__network--loading': network === 'loading',
      })}>
        <span>&#9679;</span>
        {isNull(network) ? 'No connection' : networks[network]}
      </div>
    </div>
  </header>
)
Example #2
Source File: index.js    From hzero-front with Apache License 2.0 6 votes vote down vote up
componentDidMount() {
    const { code, chartParams = {} } = this.props;
    queryReport({ code, chartParams }).then((res) => {
      if (res) {
        const { dataRows, dimColumnMap, dimColumns, statColumns, htmlTable } = res;
        this.setState({
          dimColumns,
          dimColumnMap,
          statColumns,
          htmlTable,
        });
        if (!isNull(dimColumnMap) && !isNull(dataRows)) {
          this.handleProcessData(dimColumnMap, dataRows);
        }
      }
    });
  }
Example #3
Source File: diff.js    From hivemind with Apache License 2.0 4 votes vote down vote up
DiffAPI = async (req, res) => {
  const { token } = req.headers

  try {
    const claims = await verifyIdToken(token)
    const ukey = claims.uid
    const userId = `users/${ukey}`
    const { eid } = req.query
    const cEvent = await compoundEvents.document(eid)
    const { mid, event, fctime, lctime, nids, eids } = cEvent

    if (await hasReadAccess(mid, userId)) {
      let response, diff, nid, output, indexes, filteredNids, nKeys, path, timestamp

      switch (req.method) {
        case 'GET':
          output = {}

          switch (event) {
            case 'created':
            case 'restored':
              output.v1 = {}
              nid = nids.find((nid) => nid.startsWith('nodes/')) || mid
              response = await rg.get('/history/show', {
                path: `/n/${nid}`,
                timestamp: lctime,
              })
              output.v2 = response.body[0]

              break

            case 'deleted':
              indexes = chain(nids)
                .map((nid, idx) =>
                  /^(nodes|mindmaps)\//.test(nid) ? idx : null
                )
                .reject(isNull)
                .value()
              output.v2 = indexes.map(() => ({}))
              filteredNids = nids.filter((nid, idx) =>
                indexes.includes(idx)
              )

              nKeys = {}
              for (const nid of filteredNids) {
                const [coll, key] = nid.split('/')
                if (!nKeys[coll]) {
                  nKeys[coll] = []
                }
                nKeys[coll].push(key)
              }
              path = createNodeBracePath(nKeys)

              timestamp = fctime - 0.0001
              response = await rg.get('/history/show', { path, timestamp })
              output.v1 = response.body

              break

            case 'updated':
              nid = nids[0]
              response = await rg.get('/history/show', {
                path: `/n/${nid}`,
                timestamp: lctime,
              })
              output.v2 = response.body[0]

              diff = await getReversedDiff(nid, eids[0], fctime, lctime)
              output.v1 = patch(diff, response.body[0])
          }

          return res.status(200).json(output)
      }
    } else {
      return res.status(401).json({ message: 'Access Denied.' })
    }
  } catch (error) {
    console.error(error.message, error.stack)

    return res.status(401).json({ message: 'Access Denied.' })
  }
}
Example #4
Source File: index.js    From datapass with GNU Affero General Public License v3.0 4 votes vote down vote up
TextInputWithSuggestions = ({
  label,
  name,
  options = [],
  value,
  disabled,
  onChange,
  required,
}) => {
  // id will be set once when the component initially renders, but never again
  // we generate an unique id prefixed by the field name
  const [id] = useState(uniqueId(name));

  const [suggestions, setSuggestions] = useState([]);

  // from https://stackoverflow.com/questions/990904/remove-accents-diacritics-in-a-string-in-javascript
  const normalize = (string = '') =>
    string
      .toLowerCase()
      .normalize('NFD')
      .replace(/\p{Diacritic}/gu, '')
      .replace(/[^\w\s]/gi, ' ');

  useEffect(() => {
    const newSuggestions = chain(options)
      .map(({ id, label }) => ({
        id,
        label,
        distance: levenshtein(normalize(value), normalize(label)).similarity,
      }))
      .sortBy(['distance'])
      .reverse()
      .filter(({ distance }) => distance > 0.25)
      .take(10)
      .value();

    setSuggestions(newSuggestions);
  }, [options, value]);

  const [isDropDownOpen, setIsDropDownOpen] = useState(false);
  const [activeSuggestion, setActiveSuggestion] = useState(null);

  const closeDropDown = () => {
    setIsDropDownOpen(false);
    setActiveSuggestion(null);
  };

  const onKeyDown = (e) => {
    if (e.key === 'Tab' && isDropDownOpen) {
      e.preventDefault();
      closeDropDown();
    }

    if (e.key === 'Enter' && !isDropDownOpen) {
      e.preventDefault();
      setIsDropDownOpen(true);
    }

    if (e.key === 'Escape' && isDropDownOpen) {
      e.preventDefault();
      closeDropDown();
    }

    if (e.key === 'ArrowDown' && !isDropDownOpen) {
      e.preventDefault();
      setIsDropDownOpen(true);
      setActiveSuggestion(0);
    }

    if (e.key === 'ArrowDown' && isDropDownOpen && isNull(activeSuggestion)) {
      e.preventDefault();
      setActiveSuggestion(0);
    }

    if (e.key === 'ArrowDown' && isDropDownOpen && isNumber(activeSuggestion)) {
      e.preventDefault();
      setActiveSuggestion(min([activeSuggestion + 1, suggestions.length - 1]));
    }

    if (e.key === 'ArrowUp' && isDropDownOpen) {
      e.preventDefault();
      setActiveSuggestion(max([activeSuggestion - 1, 0]));
    }

    if (e.key === 'Enter' && isDropDownOpen) {
      e.preventDefault();
      onChange({
        target: { name, value: suggestions[activeSuggestion]?.label },
      });
      closeDropDown();
    }
  };

  const handleChange = (value) => {
    closeDropDown();
    onChange({ target: { name, value } });
  };

  return (
    <div className="fr-input-group">
      <label htmlFor={id}>
        {label}
        {required && ' *'}
      </label>
      <input
        className="fr-input"
        type="text"
        onChange={onChange}
        name={name}
        id={id}
        readOnly={disabled}
        value={value}
        required={required}
        onKeyDown={onKeyDown}
        onClick={() => setIsDropDownOpen(true)}
        onInput={() => setIsDropDownOpen(true)}
      />
      {!disabled && isDropDownOpen && !isEmpty(suggestions) && (
        <Dropdown onOutsideClick={closeDropDown} fillWidth>
          {suggestions.map(({ id, label }, index) => (
            <div
              key={id}
              className={`datapass-text-input-suggestion ${
                activeSuggestion === index
                  ? 'datapass-text-input-active-suggestion'
                  : ''
              }`}
              onClick={() => handleChange(label)}
            >
              {label}
            </div>
          ))}
        </Dropdown>
      )}
    </div>
  );
}
Example #5
Source File: DetailPage.js    From hzero-front with Apache License 2.0 4 votes vote down vote up
render() {
    const {
      match: { path },
      location,
    } = this.props;
    const { search = {} } = location;
    const { source } = queryString.parse(search);
    const { id } = this.props.match.params;
    const { activeKey, isSelf } = this.state;
    const commonProps = {
      secGrpId: id,
      isSelf,
      roleId: this.roleId,
      secGrpSource: source,
    };
    return (
      <>
        <Header
          title={intl.get('hiam.securityGroup.view.title.securityGroup.config').d('安全组权限配置')}
          backPath="/hiam/security-group/list"
          onBack={this.onBack}
        >
          {isSelf && (
            <ButtonPermission
              type="c7n-pro"
              permissionList={[
                {
                  code: `${path}.button.save`,
                  type: 'button',
                  meaning: '安全组详情-保存',
                },
              ]}
              color="primary"
              icon="save"
              onClick={() => this.handleSave()}
            >
              {intl.get(`hzero.common.button.save`).d('保存')}
            </ButtonPermission>
          )}
        </Header>
        <Content>
          <Card
            bordered={false}
            className={DETAIL_CARD_CLASSNAME}
            title={
              <h3>{intl.get('hiam.securityGroup.view.title.basicInformation').d('基本信息')}</h3>
            }
            loading={false}
          >
            <Form dataSet={this.secGrpDetailDS} columns={3}>
              <TextField name="secGrpCode" disabled />
              <IntlField name="secGrpName" disabled={!isSelf} />
              <IntlField name="remark" disabled={!isSelf} />
              <TextField name="levelMeaning" disabled />
              <TextField name="createRoleName" disabled />
              <Switch name="enabledFlag" />
            </Form>
          </Card>
          {!isNull(activeKey) && (
            <Tabs animated={false} onChange={this.handleChangePermissionType}>
              <TabPane
                tab={intl.get('hiam.securityGroup.view.title.tab.visit.permission').d('访问权限')}
                key="visit"
              >
                {activeKey === 'visit' && <VisitPermissionTab {...commonProps} />}
              </TabPane>
              <TabPane
                tab={intl.get('hiam.securityGroup.view.title.tab.field.permission').d('字段权限')}
                key="field"
              >
                {activeKey === 'field' && <FieldDimensionTab {...commonProps} />}
              </TabPane>
              <TabPane
                tab={intl.get('hiam.securityGroup.view.title.tab.workplace').d('工作台配置')}
                key="workplace"
              >
                {activeKey === 'workplace' && <CardTab {...commonProps} />}
              </TabPane>
              <TabPane
                tab={intl.get('hiam.securityGroup.view.title.tab.dimension').d('数据权限维度')}
                key="dimension"
              >
                {activeKey === 'dimension' && <DimensionTab {...commonProps} />}
              </TabPane>
              <TabPane
                tab={intl.get('hiam.securityGroup.view.title.tab.data.permission').d('数据权限')}
                key="data"
              >
                {activeKey === 'data' && <DataPermissionTab {...commonProps} />}
              </TabPane>
            </Tabs>
          )}
        </Content>
      </>
    );
  }
Example #6
Source File: index.js    From hzero-front with Apache License 2.0 4 votes vote down vote up
/**
   * 处理图表数据
   * @param {object} [dimColumnMap={}]
   * @param {object} [dataRows={}]
   */
  @Bind()
  handleProcessData(dimColumnMap = {}, dataRows = {}) {
    const { type, sign = '$', mark = '|', option = {} } = this.props;
    const { dimColumns = [], statColumns = [] } = this.state;
    const obj = {};
    let chartOption = {};
    const xAxisName = [];
    const checkedObj = {};
    const source = [['product', ...statColumns.map((item) => item.name)]];
    for (const prop in dataRows) {
      if (prop) {
        const name = prop.split(sign);
        if (name[name.length - 1] === '') {
          name.pop();
        }
        const newName = name.join(mark);
        const data = statColumns.map((item) => {
          const num = dataRows[prop][item.name];
          const val = isNull(num) ? null : Number(num);
          return val;
        });
        source.push([newName, ...data]);
      }
    }
    dimColumns.forEach((item) => {
      const { name, text } = item;
      if (text) {
        xAxisName.push(text);
      }
      if (isArray(dimColumnMap[name])) {
        const arr = [];
        dimColumnMap[name].forEach((n) => {
          if (n.value !== 'all') {
            arr.push(n.value);
          }
        });
        checkedObj[name] = dimColumnMap[name];
        obj[name] = arr;
      }
    });

    chartOption = {
      color: [
        '#c23531',
        '#2f4554',
        '#61a0a8',
        '#d48265',
        '#91c7ae',
        '#749f83',
        '#ca8622',
        '#bda29a',
        '#6e7074',
        '#546570',
        '#c4ccd3',
      ],
      tooltip: {},
      legend: {},
      ...option,
      dataset: {
        source,
      },
    };

    this.setState({
      // source,
      checkedObj,
      chartOption,
      allDataSource: source,
      checkedList: { ...obj },
      xAxisOptionsObj: checkedObj,
      xAxisName: xAxisName.join(mark),
    });
    if (this.ref.current) {
      this.eTable = echarts.init(this.ref.current);
      this.renderChart(type);
    }
  }