lodash#isArray JavaScript Examples

The following examples show how to use lodash#isArray. 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.js    From hzero-front with Apache License 2.0 7 votes vote down vote up
/**
 * todo 每次新增tpl可能都需要更改
 * 用于比较之后更新和template相关的事情
 * 顺序 和 templateCode相等才认为是相等的
 * @param {Object[]} prevTemplates
 * @param {Object[]} nextTemplates
 * @returns {boolean}
 */
export function templatesIsNoEqual(prevTemplates, nextTemplates) {
  if (isArray(prevTemplates) && isArray(nextTemplates)) {
    if (!(prevTemplates.length === 0 && nextTemplates.length === 0)) {
      if (prevTemplates.length !== nextTemplates.length) {
        return true;
      } else {
        let isEq = true;
        for (let i = 0; i < prevTemplates.length; i++) {
          isEq = prevTemplates[i].templateCode === nextTemplates[i].templateCode;
          if (!isEq) {
            break;
          }
        }
        return !isEq;
      }
    }
  }
  return true;
}
Example #2
Source File: createDataLoaders.js    From rate-repository-api with MIT License 6 votes vote down vote up
createModelLoader = Model =>
  new DataLoader(
    async ids => {
      const idColumns = isArray(Model.idColumn)
        ? Model.idColumn
        : [Model.idColumn];

      const camelCasedIdColumns = idColumns.map(id => camelCase(id));

      const results = await Model.query().findByIds(ids);

      return ids.map(
        id =>
          find(
            results,
            zipObject(camelCasedIdColumns, isArray(id) ? id : [id]),
          ) || null,
      );
    },
    {
      cacheKeyFn: jsonCacheKeyFn,
    },
  )
Example #3
Source File: AddDataModal.js    From hzero-front with Apache License 2.0 6 votes vote down vote up
/**
   * 处理返回列表数据
   * @param {Object|Array} data - 返回的列表数据
   */
  @Bind()
  dataFilter(data) {
    const {
      lov: { valueField: rowkey = 'lovId', childrenFieldName },
    } = this.props;
    const isTree = isArray(data);
    const hasParams = !isEmpty(
      Object.values(this.props.form.getFieldsValue()).filter((e) => e !== undefined && e !== '')
    );
    const list = isTree ? this.setChildren(data, childrenFieldName) : data.content;
    const pagination = !isTree && createPagination(data);
    const treeKeys = []; // 树状 key 列表
    if (isTree && hasParams) {
      /**
       * 遍历生成树列表
       * @param {*} treeList - 树列表数据
       */
      const flatKeys = (treeList) => {
        if (isArray(treeList.children) && !isEmpty(treeList.children)) {
          treeKeys.push(treeList[rowkey]);
          treeList.children.forEach((item) => flatKeys(item));
        } else {
          treeKeys.push(treeList[rowkey]);
        }
      };

      list.forEach((item) => flatKeys(item)); // 遍历生成 key 列表
    }
    this.setState({
      dataSource: list,
      treeKeys,
      pagination,
    });
  }
Example #4
Source File: data.js    From dynamic-form-render with MIT License 6 votes vote down vote up
generateOptions = function(propData, map, ignoredKeys = []) {
  let data = propData
  if (isEmpty(data) && !isObjectLike(data)) {
    return []
  }
  if (isArray(data)) {
    if (!isEmpty(map)) {
      data = formatByProps(data, {id: 'id', text: 'text'}, map)
    }
    return data.filter(item => !item.hide)
  }
  const options = []
  for (const key in data) {
    if (data.hasOwnProperty(key) && !ignoredKeys.includes(key) && !item.hide) {
      const item = Object.assign({}, data[key], {$key: key})
      const option = formatByProps(item, {id: 'id', text: 'text'}, map)
      options.push(option)
    }
  }
  return options
}
Example #5
Source File: App.js    From fluentui-starter with MIT License 6 votes vote down vote up
function renderRoute(route) {
  const isGroup = isArray(route.children);
  const PageComponent = isNil(route.component)
    ? isGroup
      ? RouteIndexList
      : ComingSoon
    : route.component;

  const routeComponent = (
    <AuthorizedRoute
      key={route.uniqueKey}
      path={route.path}
      exact={route.exact || isArray(route.children)}
      strict={route.strict}
      isPublic={route.isPublic}
    >
      <PageComponent route={route} />
    </AuthorizedRoute>
  );

  const childComponents = isGroup ? route.children.map(renderRoute) : [];
  return [routeComponent, ...childComponents];
}
Example #6
Source File: use-children.js    From awesome-react-starter with MIT License 6 votes vote down vote up
useChildren = (children) => {
  const childrenArray = isArray(children) ? children : [children];
  const elements = flatten(childrenArray).filter(isValidElement);

  return Children.map(elements, ({ props }) => {
    const { value, children, ...rest } = props;
    return {
      value: value || children,
      label: children,
      ...rest,
    };
  }).filter(({ hidden }) => !hidden);
}
Example #7
Source File: index.js    From gutenberg-forms with GNU General Public License v2.0 6 votes vote down vote up
// will get post url from the post id from the cwpGlobal variable

export function getPostUrl(id) {
	const posts = get(window, "cwpGlobal.cwp-cpt-forms");
	const filteredPost = isArray(posts)
		? posts.filter((post) => isEqual(toString(post.ID), id))
		: false;

	const requiredPost = isArray(filteredPost) ? filteredPost[0] : false;

	if (!requiredPost) {
		return "";
	} else {
		const url = get(requiredPost, "post_edit_url");
		const editUrl = url.concat("&action=edit");
		return editUrl;
	}
}
Example #8
Source File: helper.js    From d2admin-permission with MIT License 6 votes vote down vote up
/**
 * @description 在 source 中是否至少有一个 need 中的项目
 * @param {Array} source 数据源
 * @param {Array} need 需要存在的项目
 */
export function oneOf (source, need) {
  if (isArray(need)) return need.reduce((result, item) => result || source.indexOf(item) >= 0, false)
  return source.indexOf(need) >= 0
}
Example #9
Source File: api.js    From mapstore2-cadastrapp with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Utility function to support requests like GET `url.com/path?arg=value1&1arg=value2` or equivalent for POST in x-www-form-urlencoded.
 * Axios by default create arguments like arg[]=value1,value2. when passing arrays to the params object. (See axios doc for details)
 * This convert params object into URLSearchParams and append the parameters accordingly. If arrays, they will be appended with the same name.
 * @param {object} args params for the request. If array, it append each element to the param list with the same name
 */
function toURLParams(args) {
    const params = new URLSearchParams();
    Object.keys(args)
        .filter(k => !!args[k])
        .forEach(k =>
            isArray(args[k])
                ? args[k].forEach(v => params.append(k, v))
                : params.append(k, args[k])
        );
    return params;
}
Example #10
Source File: helper.js    From gutenberg-forms with GNU General Public License v2.0 6 votes vote down vote up
export function serializeFields(fields, omitClientId = "") {
	let f = [];

	if (!isArray(fields)) return [];

	fields.forEach((field) => {
		if (
			field.name.startsWith("cwp/") &&
			!layoutBlocks.includes(field.name) &&
			!isEqual(omitClientId, field.clientId)
		) {
			if (!misc_blocks.includes(field.name)) {
				f.push({
					blockName: field.name,
					fieldName: field.attributes.label,
					field_id: field.attributes.field_name,
					adminId: field.attributes.adminId,
				});
			}
		} else if (layoutBlocks.includes(field.name)) {
			f.push(...serializeFields(field.innerBlocks));
		}
	});

	return f;
}
Example #11
Source File: index.js    From Lambda with MIT License 6 votes vote down vote up
renderChildren(decorators) {
    const {
      animations,
      decorators: propDecorators,
      node,
      style,
      onToggle,
      onSelect,
      customStyles,
    } = this.props;

    if (node.loading) {
      return <Loading decorators={decorators} style={style} />;
    }

    let children = node.children;
    if (!isArray(children)) {
      children = children ? [children] : [];
    }

    return (
      <Ul style={style.subtree}>
        {children.map((child) => (
          <TreeNode
            onSelect={onSelect}
            onToggle={onToggle}
            animations={animations}
            style={style}
            customStyles={customStyles}
            decorators={propDecorators}
            key={child.id || randomString()}
            node={child}
          />
        ))}
      </Ul>
    );
  }
Example #12
Source File: index.js    From datapass with GNU Affero General Public License v3.0 6 votes vote down vote up
flattenDiffTransformerV2Factory =
  (keyPrefix = null) =>
  (accumulatorObject, objectValue, objectKey) => {
    const key = [keyPrefix, objectKey].filter((e) => e).join('.');

    if (isArray(objectValue)) {
      accumulatorObject[key] = objectValue;
    }

    // { scope: { nom: [false, true] } }
    if (isObject(objectValue)) {
      transform(
        objectValue,
        flattenDiffTransformerV2Factory(key),
        accumulatorObject
      );
    }

    return accumulatorObject;
  }
Example #13
Source File: normalizeOrderBy.js    From rate-repository-api with MIT License 6 votes vote down vote up
normalizeOrderBy = orderBy => {
  if (!orderBy) {
    return [];
  }

  if (isArray(orderBy)) {
    return orderBy.map(normalizeOrderByItem);
  }

  return [normalizeOrderByItem(orderBy)];
}
Example #14
Source File: index.js    From datapass with GNU Affero General Public License v3.0 6 votes vote down vote up
function flattenDiffTransformer(accumulatorObject, fullObjectDiff, objectKey) {
  if (!isObject(fullObjectDiff[0])) {
    accumulatorObject[objectKey] = fullObjectDiff;

    return accumulatorObject;
  }
  // {contacts: [[{'name': 'c', email: 'd', work_email: 'a'}], [{'name': 'e', email: 'd'}]]}
  const objectBefore = flatten(fullObjectDiff[0], objectKey);
  const objectAfter = flatten(fullObjectDiff[1], objectKey);
  const objectDiff = mergeWith(
    objectBefore,
    objectAfter,
    (valueBefore, valueAfter) => [valueBefore, valueAfter]
  );
  // {0.name: ['c', 'e'], 0.email: ['d', 'd'], 0.work_email: 'a'}
  const objectDiffNoUnchangedNoDeprecated = omitBy(
    objectDiff,
    (value) => !isArray(value) || value[0] === value[1]
  );
  // {0.name: ['c', 'e']}
  const objectDiffPrefixedKey = mapKeys(
    objectDiffNoUnchangedNoDeprecated,
    (value, flatKey) => `${objectKey}.${flatKey}`
  );
  // {contacts.0.name: ['c', 'e']}
  Object.assign(accumulatorObject, objectDiffPrefixedKey);

  return accumulatorObject;
}
Example #15
Source File: Mappers.js    From sampo-ui with MIT License 6 votes vote down vote up
merger = (a, b) => {
  if (isEqual(a, b)) {
    return a
  }
  if (a && !b) {
    return a
  }
  if (b && !a) {
    return b
  }
  if (isArray(a)) {
    if (isArray(b)) {
      b.forEach(function (bVal) {
        return mergeValueToList(a, bVal)
      })
      return a
    }
    return mergeValueToList(a, b)
  }
  if (isArray(b)) {
    return mergeValueToList(b, a)
  }
  if (!(isObject(a) && isObject(b) && a.id === b.id)) {
    return [a, b]
  }
  return mergeObjects(a, b)
}
Example #16
Source File: AddDataLov.js    From hzero-front with Apache License 2.0 5 votes vote down vote up
render() {
    const {
      title,
      modalVisible,
      confirmLoading,
      lov: { tableFields = [], valueField: rowKey = '' } = {},
    } = this.props;
    const { addRows, dataSource = [], pagination = {}, treeKeys, loading } = this.state;
    const rowSelection = {
      onChange: this.onSelectChange,
      selectedRowKeys: addRows.map(n => n[rowKey]),
    };
    const treeProps = isArray(dataSource)
      ? {
          uncontrolled: true,
          expandedRowKeys: treeKeys,
        }
      : {};
    return (
      <Modal
        destroyOnClose
        title={title}
        visible={modalVisible}
        confirmLoading={confirmLoading}
        width={630}
        onOk={this.okHandle}
        onCancel={this.cancelHandle}
      >
        <div className="table-list-search">{this.renderForm()}</div>
        <Table
          bordered
          rowKey={rowKey}
          columns={tableFields}
          scroll={{ x: tableScrollWidth(tableFields) }}
          loading={loading}
          dataSource={dataSource}
          rowSelection={rowSelection}
          pagination={pagination}
          onChange={this.handleTableChange}
          {...treeProps}
        />
      </Modal>
    );
  }
Example #17
Source File: Sidebar.jsx    From fluentui-starter with MIT License 5 votes vote down vote up
export function Sidebar() {
  const history = useHistory();
  const { pathname } = useLocation();

  const { current, paths } = findRoute(pathname);

  function mapRouteToNavLink(route, deeply = true) {
    return {
      name: route.name,
      key: route.uniqueKey,
      alternateText: route.name,
      title: route.name,
      url: route.path,
      onClick: (e) => {
        e.preventDefault();
        history.push(route.path);
      },
      isExpanded:
        deeply &&
        hasChildren(route) &&
        paths.some((that) => that.uniqueKey === route.uniqueKey),
      links:
        deeply &&
        hasChildren(route) &&
        route.children
          .filter(isVisible)
          .map((child) => mapRouteToNavLink(child, deeply)),
      icon: route.icon
        ? route.icon
        : hasChildren(route)
        ? "DocumentSet"
        : "TextDocument",
    };
  }

  const homeLink = mapRouteToNavLink(routes, false);
  const topPageLinks = routes.children
    .filter((route) => isVisible(route) && !isArray(route.children))
    .map((route) => mapRouteToNavLink(route, false));

  const groupLinks = routes.children.filter(hasChildren).map((route) => ({
    name: route.name,
    groupType: "MenuGroup",
    links: route.children
      .filter(isVisible)
      .map((child) => mapRouteToNavLink(child, true)),
  }));

  const navLinkGroups = [
    {
      links: [
        {
          key: "Collapse",
          name: "Collapsed",
          alternateText: "Expanded",
          icon: "GlobalNavButton",
          title: "Collapse",
        },
      ],
      groupType: "ToggleGroup",
    },
    {
      links: [homeLink, ...topPageLinks],
      groupType: "MenuGroup",
    },
    ...groupLinks,
  ];

  return <NavToggler groups={navLinkGroups} selectedKey={current?.uniqueKey} />;
}
Example #18
Source File: custTabPane.js    From hzero-front with Apache License 2.0 5 votes vote down vote up
export default function custTabPane(options = {}, tabs) {
  const { code } = options;
  const { custConfig: config, loading } = this.state;
  if (loading) return null;
  if (!code || isEmpty(config[code])) return tabs;
  const { fields = [] } = config[code];
  fields.sort((p, n) => (p.seq === undefined || n.seq === undefined ? -1 : p.seq - n.seq));
  const childrenMap = {};
  const newChildren = [];
  const refTabs = tabs;
  const refChildren = refTabs.props.children;
  const tools = this.getToolFuns();
  if (isArray(refChildren)) {
    refChildren.forEach((i) => {
      if (i.props && i.key !== undefined) {
        childrenMap[i.key] = i;
      }
    });
  } else if (refChildren && refChildren.props && refChildren.key) {
    childrenMap[refChildren.key] = refChildren;
  }
  const defaultActive = fields.find((field) => field.defaultActive === 1);
  if (defaultActive) {
    refTabs.props.activeKey = defaultActive.fieldCode;
  }
  fields.forEach((i) => {
    const { fieldName, fieldCode, conditionHeaderDTOs } = i;
    const { visible } = {
      visible: i.visible,
      ...coverConfig(conditionHeaderDTOs, tools, ['required', 'editable']),
    };
    const targetPane = childrenMap[fieldCode];
    if (!targetPane) return;
    if (fieldName !== undefined && targetPane && targetPane.props) {
      targetPane.props.tab = fieldName;
    }
    if (visible !== 0) {
      newChildren.push(targetPane);
    }
    delete childrenMap[fieldCode];
  });
  Object.keys(childrenMap).forEach((i) => newChildren.push(childrenMap[i]));
  refTabs.props.children = newChildren;
  return tabs;
}
Example #19
Source File: chart.js    From gobench with Apache License 2.0 5 votes vote down vote up
getChartData = (type, data) => isArray(data) ? data.map(m => ({
  x: m.time,
  y: getValue(m, values[type])
})) : [{
  x: new Date(data.time).getTime(),
  y: getValue(data, values[type])
}]
Example #20
Source File: index.js    From hzero-front with Apache License 2.0 5 votes vote down vote up
// 导出成excel
  @Bind()
  handleExport(outputType) {
    const { reportDataId } = this.state;
    const {
      form,
      dateFormat,
      dateTimeFormat,
      reportQuery: { detail = {} },
    } = this.props;
    const { paramsData = {} } = detail[reportDataId] || {};
    const { reportUuid, formElements } = paramsData;
    this.form.validateFields((err1) => {
      if (!err1) {
        const fieldValues = isUndefined(this.form)
          ? {}
          : filterNullValueObject(this.form.getFieldsValue());
        let newParams = [];
        let params = [];
        // 将是多选的参数分离出来,多个数组元素拆分成多个独立的对象
        map(fieldValues, (value1, key1) => {
          if (isArray(value1) && value1.length > 0) {
            newParams = map(value1, (value) => ({ key: key1, value }));
            const paramsList = newParams.map((item) => ({ name: item.key, value: item.value }));
            params = [...params, ...paramsList];
            // eslint-disable-next-line no-param-reassign
            delete fieldValues[key1];
          } else if (isArray(value1) && value1.length === 0) {
            // eslint-disable-next-line no-param-reassign
            delete fieldValues[key1];
          }
        });
        const othersParams = map(fieldValues, (value, key) => {
          let newValues = value;
          formElements.forEach((item) => {
            if (item.type === 'DatePicker') {
              if (item.name === key) {
                newValues = moment(value).format(dateFormat);
              }
            } else if (item.type === 'DatetimePicker') {
              if (item.name === key) {
                newValues = moment(value).format(dateTimeFormat);
              }
            }
          });
          return { key, value: newValues };
        });
        forEach(othersParams, (item) => {
          params.push({ name: item.key, value: item.value });
        });

        const requestUrl = `${HZERO_RPT}/v1/${
          isTenantRoleLevel() ? `${currentTenantId}/` : ''
        }reports/export/${reportUuid}/${outputType}`;

        form.validateFields((err, values) => {
          const { fCodeTenant, ...othersData } = values;
          const valueData = { ...othersData, 'f-templateCode': fCodeTenant };
          const baseParams = map(valueData, (value, key) => ({ key, value }));
          forEach(baseParams, (item) => {
            params.push({ name: item.key, value: item.value });
          });
          const newValues = filter(params, (item) => !isUndefined(item.value));
          if (!err) {
            // GET方法导出
            if (outputType !== 'PRINT') {
              downloadFile({
                requestUrl,
                queryParams: newValues,
              });
            } else {
              this.handlePrint(requestUrl, newValues);
            }
          }
        });
      }
    });
  }
Example #21
Source File: metric.js    From gobench with Apache License 2.0 5 votes vote down vote up
DefaultPage = ({ detail, graph, graphMetrics, metricDatas, unit, timeRange, dispatch }) => {
  let series
  const appStatus = get(detail, 'status', '')
  const timestamp = get(detail, 'timestamp', '')
  const isRealtime = appStatus === 'running'
  const { graphId, metrics } = graphMetrics.find(x => x.graphId === graph.id) || { metrics: [] }
  const metricData = metricDatas.find(x => x.graphId === graph.id) || { metrics: [] }
  const metricType = get(metrics, '[0].type', '')
  useEffect(() => {
    if (metrics.length > 0) {
      if (metricData.metrics.length === 0) {
        dispatch({
          type: 'application/GRAPH_METRIC_DATA',
          payload: { id: graphId, metrics, timeRange, timestamp, isRealtime }
        })
      }
    }
  }, [graphId])
  useInterval(() => {
    console.log('polling...')
    dispatch({
      type: 'application/METRIC_DATA_POLLING',
      payload: { id: graph.id, metrics, data: metricData.metrics }
    })
  }, isRealtime ? INTERVAL : null)

  if (metricType === METRIC_TYPE.HISTOGRAM) {
    series = [...makeHistogramSeriesData(get(metricData.metrics, '[0].chartData.data', []))]
  } else {
    if (isArray(metricData.metrics)) {
      series = metricData.metrics.map(d => get(d, 'chartData', {
        name: d.title,
        data: []
      }))
    }
  }
  const chartData = isRealtime ? makeChartDataByTimeRange(series, timeRange) : series
  return (
    <>
      <Suspense fallback={loading()}>
        <ApexChart
          series={chartData}
          unit={unit}
        />
      </Suspense>
    </>
  )
}
Example #22
Source File: List.js    From hzero-front with Apache License 2.0 5 votes vote down vote up
/**
   * 渲染角色名称列
   * @param {object} record - 表格当前行数据
   */
  @Bind()
  renderRoleNameColumn(_, record) {
    const { path, currentRoleId, childrenLoading, onFetchChildren = (e) => e } = this.props;
    const { name, childrenNum, children } = record;
    const pageSize = 10;
    let item = name;
    if (isArray(children)) {
      const { length } = children;
      const more =
        currentRoleId === record.id && childrenLoading ? (
          <ButtonPermission
            type="text"
            permissionList={[
              {
                code: `${path}.button.loading`,
                type: 'button',
                meaning: '角色管理树形-loading',
              },
            ]}
          >
            <Icon type="loading" />
          </ButtonPermission>
        ) : (
          length > 0 &&
          childrenNum > length && (
            <ButtonPermission
              type="text"
              permissionList={[
                {
                  code: `${path}.button.more`,
                  type: 'button',
                  meaning: '角色管理树形-更多',
                },
              ]}
              onClick={() =>
                onFetchChildren({
                  parentRoleId: record.id,
                  levelPath: record.levelPath,
                  page: { current: Math.floor(length / pageSize) + 1, pageSize },
                })
              }
            >
              {intl.get('hiam.roleManagement.view.button.more').d('更多')}
            </ButtonPermission>
          )
        );
      const count = childrenNum ? `(${childrenNum})` : null;
      item = (
        <span>
          {name}
          {count}
          {more}
        </span>
      );
    }
    return item;
  }
Example #23
Source File: helper.js    From d2admin-permission with MIT License 5 votes vote down vote up
/**
 * @description 检查一个对象是否有子元素
 * @param {Object} item 检查的对象
 * @param {String} keyname 子元素的 keyname
 */
export function hasChildren (item = {}, keyname = 'children_list') {
  return item[keyname] && isArray(item[keyname]) && item[keyname].length > 0
}
Example #24
Source File: index.js    From hzero-front with Apache License 2.0 5 votes vote down vote up
// 获取api总数图表的配置参数
  @Bind()
  getApiCountChartOption() {
    const { apiCountData = {} } = this.state;
    const { services, apiCounts = [] } = apiCountData;
    let handledApiCountData;
    if (isArray(services)) {
      handledApiCountData = services.map((item, index) => ({
        name: item,
        value: apiCounts[index],
      }));
    }
    return {
      title: {
        text: intl.get('hadm.apiOverview.view.title.apiCount').d('各服务API总数'),
        textStyle: {
          color: 'rgba(0,0,0,0.87)',
          fontWeight: '400',
        },
        top: 20,
        left: 16,
      },
      tooltip: {
        trigger: 'item',
        confine: true,
        formatter: '{b} <br/>百分比: {d}% <br/>总数: {c}',
        backgroundColor: '#FFFFFF',
        borderWidth: 1,
        borderColor: '#DDDDDD',
        extraCssText: 'box-shadow: 0 2px 4px 0 rgba(0,0,0,0.20)',
        textStyle: {
          fontSize: 13,
          color: '#000000',
        },
      },
      legend: {
        right: 15,
        itemHeight: 11,
        top: 60,
        height: '70%',
        y: 'center',
        type: 'scroll',
        data: services || [],
        orient: 'vertical', // 图例纵向排列
        icon: 'circle',
      },
      // calculable: true,
      series: [
        {
          type: 'pie',
          radius: [20, 110],
          center: ['31%', '50%'],
          roseType: 'radius',
          minAngle: 30,
          label: {
            normal: {
              show: false,
            },
            emphasis: {
              show: false,
            },
          },
          data: handledApiCountData || {},
        },
      ],
      color: colorArr,
    };
  }
Example #25
Source File: ETHWallet.js    From RRWallet with MIT License 4 votes vote down vote up
async sendBatchTransaction(coin, targets, gasPrice, perGasLimit, pwd, callback) {
    targets = JSON.parse(JSON.stringify(targets));

    const token = coin;
    if (!token || !isNumber(token.decimals)) {
      throw new Error("token不存在");
    }

    if (!isArray(targets) || targets.length === 0) {
      throw new Error("targets参数格式不正确");
    }

    gasPrice = new BigNumber(gasPrice + "");
    perGasLimit = new BigNumber(perGasLimit + "");

    if (perGasLimit.isLessThan(ETH_ERC20_TX_MIN_GASLIMIT)) {
      throw new Error(
        `单笔转账的gasLimit需大于${ETH_ERC20_TX_MIN_GASLIMIT}, 为保证交易正常, 请尽可能多的设置gasLimit, 未使用的gas将会在交易结束后退回`
      );
    }

    const tos = [];
    const amounts = [];

    let totalAmount = new BigNumber(0);

    for (const { address, amount } of targets) {
      if (isNil(address) || isNil(amount)) {
        throw new Error("targets含有非法输入");
      }

      if (!isString(address) || !isString(amount)) {
        throw new Error("非法输入,地址和数量必须为字符串");
      }

      let isStartsWith0x = _.startsWith(address, "0x"); //address.indexOf('0x') == 0;
      if ((isStartsWith0x && address.length != 42) || (!isStartsWith0x && address.length != 40)) {
        throw new Error(`含有非法地址${address}`);
      }

      tos.push(address);
      const amountBigNumber = new BigNumber(amount);
      amounts.push(new BigNumber(amountBigNumber));
      totalAmount = totalAmount.plus(amountBigNumber);
    }

    const balanceBigNumber = new BigNumber(token.balance + "");
    if (totalAmount.isGreaterThan(balanceBigNumber)) {
      throw new Error(
        `${token.name}余额不足, 转账数量:${toFixedLocaleString(totalAmount)}}, 余额:${toFixedLocaleString(
          balanceBigNumber
        )}`
      );
    }

    //两次approve 一次测试转账, 所以需要预留3笔gas数量
    const totalGasBignumber = ethereum.toEther(perGasLimit.multipliedBy(tos.length + 3).multipliedBy(gasPrice), "gwei");
    if (totalGasBignumber.isGreaterThan(this.ETH.balance + "")) {
      throw new Error(
        `ETH余额不足, 矿工费:${toFixedLocaleString(totalGasBignumber)}}, 余额:${toFixedLocaleString(this.ETH.balance)}`
      );
    }

    if (token instanceof ETH) {
      if (totalGasBignumber.plus(totalAmount).isGreaterThan(token.balance + "")) {
        throw new Error(
          `ETH余额不足, 矿工费:${toFixedLocaleString(totalGasBignumber)}}, 转账数量:${toFixedLocaleString(
            totalAmount
          )} 余额:${toFixedLocaleString(balanceBigNumber)}`
        );
      }
    }

    Device.keepScreenOn(true);
    try {
      if (coin instanceof ETH) {
        await this.sendETHBatchTransactionContract(token, tos, amounts, gasPrice, perGasLimit, pwd, callback);
      } else if (await this.shouldUseBatchTransactionContract(token.contract)) {
        let skinTestSuccess = false;
        try {
          //尝试调用单笔批量合约, 如果合约执行失败则降级到looping, 其他异常则中断发币
          await this.sendERC20BatchTransactionContract(
            token,
            _.take(tos, 1),
            _.take(amounts, 1),
            gasPrice,
            perGasLimit,
            pwd,
            callback
          );
          skinTestSuccess = true;
        } catch (error) {
          if (error.message === "批量发币合约执行失败") {
            await this.sendERC20BatchTransactionLooping(token, tos, amounts, gasPrice, perGasLimit, pwd, callback);
          } else {
            throw error;
          }
        }

        if (!skinTestSuccess) {
          return;
        }

        tos.splice(0, 1);
        amounts.splice(0, 1);
        await this.sendERC20BatchTransactionContract(token, tos, amounts, gasPrice, perGasLimit, pwd, result => {
          _.isFunction(callback) &&
            callback({
              ...result,
              from: result.from + 1,
            });
        });
      } else {
        await this.sendERC20BatchTransactionLooping(token, tos, amounts, gasPrice, perGasLimit, pwd, callback);
      }
    } catch (error) {
      throw error;
    }
    Device.keepScreenOn(false);
  }
Example #26
Source File: index.js    From hzero-front with Apache License 2.0 4 votes vote down vote up
export default function withCustomize({ unitCode = [], query, manualQuery = false } = {}) {
  return (Component) => {
    class WrapIndividual extends React.Component {
      constructor(props, ...args) {
        super(props, ...args);
        this.state = {
          // eslint-disable-next-line react/no-unused-state
          custConfig: {},
          loading: true,
          cacheType: {},
          // eslint-disable-next-line react/no-unused-state
          cache: {},
          dataMap: new Map(),
          arrayDataMap: {},
          lastUpdateUnit: '',
        };
      }

      @Bind()
      setDataMap(code, value) {
        this.state.dataMap.set(code, value);
      }

      @Bind()
      getDataValue(code) {
        return this.state.dataMap.get(code) || {};
      }

      @Bind()
      setArrayDataMap(code, value, index) {
        const { arrayDataMap } = this.state;
        if (!arrayDataMap[code]) {
          arrayDataMap[code] = new Map();
        }
        arrayDataMap[code].set(index, value);
      }

      @Bind()
      getArrayDataValue(code, index) {
        const { arrayDataMap } = this.state;
        if (!arrayDataMap[code]) {
          return {};
        }
        return arrayDataMap[code].get(index) || {};
      }

      @Bind()
      getCacheType(code) {
        return this.state.cacheType[code];
      }

      @Bind()
      getToolFuns() {
        return {
          setArrayDataMap: this.setArrayDataMap,
          getArrayDataValue: this.getArrayDataValue,
          setDataMap: this.setDataMap,
          getDataValue: this.getDataValue,
          getCacheType: this.getCacheType,
        };
      }

      componentDidMount() {
        if (manualQuery) {
          return;
        }
        this.queryUnitConfig();
      }

      @Bind()
      queryUnitConfig(params = query, fn) {
        if (unitCode && isArray(unitCode) && unitCode.length > 0) {
          queryUnitCustConfig({ unitCode: unitCode.join(','), ...params })
            .then((res) => {
              // eslint-disable-next-line no-unused-expressions
              typeof fn === 'function' && fn(res);
              if (res) {
                this.setState({
                  // eslint-disable-next-line react/no-unused-state
                  custConfig: res || {},
                });
              }
            })
            .finally(() => {
              this.setState({ loading: false });
            });
        } else {
          this.setState({ loading: false });
        }
      }

      customizeForm = B(custForm, this);

      customizeCollapseForm = B(custCollapseForm, this);

      custTable = B(custTable, this);

      customizeVTable = B(custVTable, this);

      customizeCollapse = B(custCollapse, this);

      customizeTabPane = B(custTabPane, this);

      render() {
        const { loading = true, lastUpdateUnit } = this.state;
        const newProps = {
          ...this.props,
          custLoading: loading,
          lastUpdateUnit,
          customizeTable: this.custTable,
          customizeVTable: this.customizeVTable,
          customizeForm: this.customizeForm,
          customizeCollapseForm: this.customizeCollapseForm,
          customizeTabPane: this.customizeTabPane,
          queryUnitConfig: this.queryUnitConfig,
        };

        return <Component {...newProps} ref={this.props.forwardRef} />;
      }
    }
    return React.forwardRef((props, ref) => <WrapIndividual {...props} forwardRef={ref} />);
  };
}
Example #27
Source File: index.js    From strapi-molecules with MIT License 4 votes vote down vote up
function SelectWrapper({
  componentUid,
  description,
  editable,
  label,
  isCreatingEntry,
  isFieldAllowed,
  isFieldReadable,
  mainField,
  name,
  relationType,
  slug,
  targetModel,
  placeholder,
  valueToSet,
}) {
  // Disable the input in case of a polymorphic relation
  const isMorph = relationType.toLowerCase().includes("morph");
  const {
    addRelation,
    modifiedData,
    moveRelation,
    onChange,
    onRemoveRelation,
    initialData,
  } = useDataManager();
  const { isDraggingComponent } = useEditView();

  const value =
    valueToSet && valueToSet !== "current"
      ? valueToSet
      : get(modifiedData, name, null);
  const initialValue = get(initialData, name, null);

  // This is needed for making requests when used in a component
  const fieldName = useMemo(() => {
    const fieldNameArray = getFieldName(name);
    return fieldNameArray[fieldNameArray.length - 1];
  }, [name]);

  const { pathname } = useLocation();

  const [state, setState] = useState({
    _contains: "",
    _limit: 20,
    _start: 0,
  });
  const [options, setOptions] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const abortController = new AbortController();
  const { signal } = abortController;
  const ref = useRef();
  const startRef = useRef();

  const filteredOptions = useMemo(() => {
    return options.filter((option) => {
      if (!isEmpty(value)) {
        // SelectMany
        if (Array.isArray(value)) {
          return findIndex(value, (o) => o.id === option.value.id) === -1;
        }

        // SelectOne
        return get(value, "id", "") !== option.value.id;
      }

      return true;
    });
  }, [options, value]);

  startRef.current = state._start;

  ref.current = async () => {
    if (isMorph) {
      setIsLoading(false);

      return;
    }

    if (!isDraggingComponent) {
      try {
        const requestUrl = `/${pluginId}/explorer/${slug}/relation-list/${fieldName}`;

        const containsKey = `${mainField}_contains`;
        const { _contains, ...restState } = cloneDeep(state);
        const params = isEmpty(state._contains)
          ? restState
          : { [containsKey]: _contains, ...restState };

        if (componentUid) {
          set(params, "_component", componentUid);
        }

        const data = await request(requestUrl, {
          method: "GET",
          params,
          signal,
        });

        const formattedData = data.map((obj) => {
          return { value: obj, label: obj[mainField] };
        });

        setOptions((prevState) =>
          prevState.concat(formattedData).filter((obj, index) => {
            const objIndex = prevState.findIndex(
              (el) => el.value.id === obj.value.id,
            );

            if (objIndex === -1) {
              return true;
            }

            return (
              prevState.findIndex((el) => el.value.id === obj.value.id) ===
              index
            );
          }),
        );
        setIsLoading(false);
      } catch (err) {
        if (err.code !== 20) {
          strapi.notification.error("notification.error");
        }
      }
    }
  };

  useEffect(() => {
    if (state._contains !== "") {
      let timer = setTimeout(() => {
        ref.current();
      }, 300);

      return () => clearTimeout(timer);
    }

    if (isFieldAllowed) {
      ref.current();
    }

    return () => {
      abortController.abort();
    };
  }, [state._contains, isFieldAllowed]);

  useEffect(() => {
    if (state._start !== 0) {
      ref.current();
    }

    return () => {
      abortController.abort();
    };
  }, [state._start]);

  const onInputChange = (inputValue, { action }) => {
    if (action === "input-change") {
      setState((prevState) => {
        if (prevState._contains === inputValue) {
          return prevState;
        }

        return { ...prevState, _contains: inputValue, _start: 0 };
      });
    }

    return inputValue;
  };

  const onMenuScrollToBottom = () => {
    setState((prevState) => ({ ...prevState, _start: prevState._start + 20 }));
  };

  const isSingle = [
    "oneWay",
    "oneToOne",
    "manyToOne",
    "oneToManyMorph",
    "oneToOneMorph",
  ].includes(relationType);

  const changeRelationValueForCurrentVersion = () => {
    if (valueToSet && startRef.current != 0) {
      valueToSet !== "current"
        ? onChange({ target: { name, value: valueToSet } })
        : onChange({ target: { name, value: initialValue } });
    }
  };

  useEffect(() => {
    changeRelationValueForCurrentVersion();
  }, [valueToSet]);

  const to = `/plugins/${pluginId}/collectionType/${targetModel}/${
    value ? value.id : null
  }`;
  const link =
    value === null ||
    value === undefined ||
    [
      "plugins::users-permissions.role",
      "plugins::users-permissions.permission",
    ].includes(targetModel) ? null : (
      <Link to={{ pathname: to, state: { from: pathname } }}>
        <FormattedMessage id="content-manager.containers.Edit.seeDetails" />
      </Link>
    );
  const Component = isSingle ? SelectOne : SelectMany;
  const associationsLength = isArray(value) ? value.length : 0;

  const customStyles = {
    option: (provided) => {
      return {
        ...provided,
        maxWidth: "100% !important",
        overflow: "hidden",
        textOverflow: "ellipsis",
        whiteSpace: "nowrap",
      };
    },
  };

  const isDisabled = useMemo(() => {
    if (isMorph) {
      return true;
    }

    if (!isCreatingEntry) {
      return !isFieldAllowed && isFieldReadable;
    }

    return !editable;
  });

  if (!isFieldAllowed && isCreatingEntry) {
    return <NotAllowedInput label={label} />;
  }

  if (!isCreatingEntry && !isFieldAllowed && !isFieldReadable) {
    return <NotAllowedInput label={label} />;
  }

  return (
    <Wrapper className="form-group">
      <Nav>
        <div>
          <label htmlFor={name}>
            {label}
            {!isSingle && (
              <span style={{ fontWeight: 400, fontSize: 12 }}>
                &nbsp;({associationsLength})
              </span>
            )}
          </label>
          {isSingle && link}
        </div>
        {!isEmpty(description) && <p className="description">{description}</p>}
      </Nav>
      <Component
        addRelation={(value) => {
          addRelation({ target: { name, value } });
        }}
        id={name}
        isDisabled={isDisabled}
        isLoading={isLoading}
        isClearable
        mainField={mainField}
        move={moveRelation}
        name={name}
        options={filteredOptions}
        onChange={(value) => {
          onChange({ target: { name, value: value ? value.value : value } });
        }}
        onInputChange={onInputChange}
        onMenuClose={() => {
          setState((prevState) => ({ ...prevState, _contains: "" }));
        }}
        onMenuScrollToBottom={onMenuScrollToBottom}
        onRemove={onRemoveRelation}
        placeholder={
          isEmpty(placeholder) ? (
            <FormattedMessage id={`${pluginId}.containers.Edit.addAnItem`} />
          ) : (
            placeholder
          )
        }
        styles={customStyles}
        targetModel={targetModel}
        value={value}
      />
      <div style={{ marginBottom: 18 }} />
    </Wrapper>
  );
}
Example #28
Source File: index.js    From hzero-front with Apache License 2.0 4 votes vote down vote up
/**
   * @function handleAdd - 新增或编辑可执行数据
   * @param {Object} fieldsValue - 编辑的数据
   * @param {Object} others - 其他参数(fix bug 新增)
   */
  @Bind()
  handleAdd(fieldsValue, others = {}) {
    const {
      dispatch,
      concRequest: { pagination, paramList = [] },
      currentTenantId,
    } = this.props;
    const {
      startDate,
      endDate,
      concurrentId,
      cycleFlag,
      intervalType,
      intervalNumber,
      intervalHour,
      intervalMinute,
      intervalSecond,
      tenantId,
    } = fieldsValue;
    const newFields = cloneDeep(fieldsValue);
    if (paramList.length > 0) {
      const { requestParamNameMap = new Map() } = others;
      [
        'concurrentId',
        'cycleFlag',
        'startDate',
        'endDate',
        'intervalType',
        'intervalNumber',
        'intervalHour',
        'intervalMinute',
        'intervalSecond',
        'tenantId',
      ].forEach((paramCode) => {
        if (!requestParamNameMap.has(paramCode)) {
          delete newFields[paramCode];
        }
      });
    }
    if (!newFields) {
      return null;
    }
    forEach(newFields, (value, key) => {
      // 值 只有可能是 数组/moment对象/字符串/数字
      if (isArray(value)) {
        newFields[key] = JSON.stringify(value);
      } else if (isObject(value)) {
        //  eslint-disable-next-line
        if (moment(value).isValid()) {
          //  eslint-disable-next-line
          newFields[key] = moment(value).format(getDateTimeFormat());
        }
      }
    });
    dispatch({
      type: 'concRequest/createRequest',
      payload: {
        startDate: startDate ? moment(startDate).format(DEFAULT_DATETIME_FORMAT) : null,
        endDate: endDate ? moment(endDate).format(DEFAULT_DATETIME_FORMAT) : null,
        requestParam: paramList.length > 0 ? JSON.stringify(newFields) : null,
        concurrentId,
        cycleFlag,
        intervalType,
        intervalNumber,
        intervalHour,
        intervalMinute,
        intervalSecond,
        tenantId: !isUndefined(tenantId) ? tenantId : currentTenantId,
      },
    }).then((res) => {
      if (res) {
        notification.success();
        this.handleModalVisible(false);
        this.handleSearch(pagination);
      }
    });
  }