lodash#replace TypeScript Examples

The following examples show how to use lodash#replace. 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.ts    From redux-with-domain with MIT License 6 votes vote down vote up
export function toStorePath(path) {
  return replace(path, /\//g, '.')
}
Example #2
Source File: my-reports.page.ts    From fyle-mobile-app with MIT License 6 votes vote down vote up
generateStateFilterPills(filterPills: FilterPill[], filter) {
    filterPills.push({
      label: 'State',
      type: 'state',
      value: filter.state
        .map((state) => {
          if (state === 'APPROVER_INQUIRY') {
            return 'Sent Back';
          }

          if (state === 'APPROVER_PENDING') {
            return 'Reported';
          }

          return state.replace(/_/g, ' ').toLowerCase();
        })
        .reduce((state1, state2) => `${state1}, ${state2}`),
    });
  }
Example #3
Source File: my-reports.page.ts    From fyle-mobile-app with MIT License 5 votes vote down vote up
async onDeleteReportClick(erpt: ExtendedReport) {
    if (['DRAFT', 'APPROVER_PENDING', 'APPROVER_INQUIRY'].indexOf(erpt.rp_state) === -1) {
      const cannotDeleteReportPopOver = await this.popoverController.create({
        component: PopupAlertComponentComponent,
        componentProps: {
          title: 'Cannot Delete Report',
          message: `${capitalize(replace(erpt.rp_state, '_', ' '))} report cannot be deleted.`,
          primaryCta: {
            text: 'Close',
            action: 'continue',
          },
        },
        cssClass: 'pop-up-in-center',
      });

      await cannotDeleteReportPopOver.present();
    } else {
      const deleteReportPopover = await this.popoverController.create({
        component: FyDeleteDialogComponent,
        cssClass: 'delete-dialog',
        backdropDismiss: false,
        componentProps: {
          header: 'Delete Report',
          body: 'Are you sure you want to delete this report?',
          infoMessage: 'Deleting the report will not delete any of the expenses.',
          deleteMethod: () => this.reportService.delete(erpt.rp_id),
        },
      });

      await deleteReportPopover.present();
      const { data } = await deleteReportPopover.onDidDismiss();

      if (data && data.status === 'success') {
        from(this.loaderService.showLoader())
          .pipe(
            tap(() => this.trackingService.deleteReport()),
            finalize(async () => {
              await this.loaderService.hideLoader();
              this.doRefresh();
            })
          )
          .subscribe(noop);
      }
    }
  }
Example #4
Source File: write-properties-file.test.ts    From relate with GNU General Public License v3.0 5 votes vote down vote up
describe('writePropertiesFile', () => {
    test('Writes properties to file', async () => {
        const plain: PropertyEntries = [
            ['bar.bam', 'baz'],
            ['bom.boz', 'true'],
        ];
        const expected = trim(
            replace(
                `
                bar.bam=baz
                bom.boz=true
            `,
                WHITESPACE,
                '',
            ),
        );

        const properties = await writePropertiesFile('plain', plain);

        expect(properties).toEqual(expected);
    });

    test('Adds comments (without separator)', async () => {
        const comments: PropertyEntries = [
            ['# hurr', ''],
            ['bar.bam', 'baz'],
            ['# durr', ''],
            ['bom.boz', 'true'],
        ];
        const expected = trim(
            replace(
                `
                # hurr
                bar.bam=baz
                # durr
                bom.boz=true
            `,
                WHITESPACE,
                '',
            ),
        );

        const properties = await writePropertiesFile('comments', comments);

        expect(properties).toEqual(expected);
    });

    test('preserves whitespace', async () => {
        const emptyKey: PropertyEntries = [
            ['bar.bam', 'baz'],
            ['', ''],
            ['bom', 'true'],
        ];
        const expected = 'bar.bam=baz\n\nbom=true';

        const properties = await writePropertiesFile('emptyKey', emptyKey);

        expect(properties).toEqual(expected);
    });
});
Example #5
Source File: str.monad.ts    From relate with GNU General Public License v3.0 5 votes vote down vote up
replace(pattern: string | RegExp | Str, replacement: string | Str): Str {
        return Str.from(replace(`${this}`, Str.isStr(pattern) ? `${pattern}` : pattern, `${replacement}`));
    }
Example #6
Source File: philosophers.tsx    From S2 with MIT License 4 votes vote down vote up
fetch(
  'https://gw.alipayobjects.com/os/bmw-prod/24cac0f7-70f0-4131-be61-df11da3ca921.json',
)
  .then((res) => res.json())
  .then((data) => {
    const weights = data.map((item) => item.weight);
    const maxWeight = max(weights);
    const minWeight = min(weights);
    const weightSpan = maxWeight - minWeight;

    const PaletteLegend = () => (
      <div className="legend">
        <div className="legend-limit">{minWeight.toFixed(2)}</div>
        {PALETTE_COLORS.map((color, index) => (
          <span
            key={index}
            className="legend-color"
            style={{ background: color }}
          />
        ))}
        <div className="legend-limit">{maxWeight.toFixed(2)}</div>
      </div>
    );

    const getFormatter = (val) => {
      if (val < 0) {
        return `公元前${replace(val, '-', '')}年`;
      } else {
        return `${val}年`;
      }
    };

    const s2DataConfig = {
      fields: {
        rows: ['country', 'name', 'start', 'end', 'points', 'word'],
        columns: [],
        values: ['weight'],
      },
      meta: [
        {
          field: 'word',
          name: '关键词',
        },
        {
          field: 'points',
          name: '观点',
        },
        {
          field: 'name',
          name: '姓名',
        },
        {
          field: 'country',
          name: '国家',
        },
        {
          field: 'start',
          name: '出生',
          formatter: getFormatter,
        },
        {
          field: 'end',
          name: '逝世',
          formatter: getFormatter,
        },
        {
          field: 'weight',
          name: '权重',
          formatter: (val) => val.toFixed(2),
        },
      ],
      data,
    };
    const TooltipContent = (props) => {
      const { rowQuery, fieldValue } = props;
      const { name, country, start, end, points } = rowQuery;
      const ponitsLines = points.split('&');
      return (
        <div className="antv-s2-tooltip-container">
          <div className="antv-s2-tooltip-head-info-list">
            <div>姓名:{name}</div>
            <div>国家:{country}</div>
            <div>出生:{getFormatter(start)}</div>
            <div>逝世:{getFormatter(end)}</div>
            {ponitsLines.length > 1 ? (
              <div>
                观点:
                {ponitsLines.map((point, index) => (
                  <div>
                    {index + 1}: {point}
                  </div>
                ))}
              </div>
            ) : (
              <div>观点: {ponitsLines[0]}</div>
            )}
          </div>
          <div className="antv-s2-tooltip-divider"></div>
          <div className="antv-s2-tooltip-detail-list">
            <div className="antv-s2-tooltip-detail-item">
              <span className="antv-s2-tooltip-detail-item-key">权重</span>
              <span className="antv-s2-tooltip-detail-item-val">
                {fieldValue}
              </span>
            </div>
          </div>
        </div>
      );
    };
    const s2Options = {
      width: '',
      height: 400,
      conditions: {
        text: [
          {
            field: 'weight',
            mapping(value) {
              if (value >= 20) {
                return {
                  fill: '#fff',
                };
              }
            },
          },
        ],
        background: [
          {
            field: 'weight',
            mapping(value) {
              let backgroundColor;
              const colorIndex =
                Math.floor(
                  (((value - minWeight) / weightSpan) * 100) /
                    PALETTE_COLORS.length,
                ) - 1;
              if (colorIndex <= 0) {
                backgroundColor = PALETTE_COLORS[0];
              } else if (colorIndex >= PALETTE_COLORS.length) {
                backgroundColor = PALETTE_COLORS[PALETTE_COLORS.length - 1];
              } else {
                backgroundColor = PALETTE_COLORS[colorIndex];
              }

              return {
                fill: backgroundColor,
              };
            },
          },
        ],
      },
      interaction: {
        selectedCellsSpotlight: false,
        hoverHighlight: false,
      },
    };

    const onDataCellMouseUp = (value) => {
      const viewMeta = value?.viewMeta;
      if (!viewMeta) {
        return;
      }

      const position = {
        x: value.event.clientX,
        y: value.event.clientY,
      };
      viewMeta.spreadsheet.tooltip.show({
        position,
        content: TooltipContent(viewMeta),
      });
    };

    ReactDOM.render(
      <SheetComponent
        dataCfg={s2DataConfig}
        options={s2Options}
        adaptive={true}
        header={{
          title: '哲学家的观点',
          extra: [<PaletteLegend />],
        }}
        onDataCellMouseUp={onDataCellMouseUp}
      />,

      document.getElementById('container'),
    );
  });
Example #7
Source File: PropertyPicker.tsx    From gio-design with Apache License 2.0 4 votes vote down vote up
PropertyPicker: React.FC<PropertyPickerProps> = (props: PropertyPickerProps) => {
  const {
    value: initialValue,
    searchBar,
    loading = false,
    dataSource: originDataSource,
    recentlyStorePrefix = '_gio',
    onChange,
    onSelect,
    onClick,
    detailVisibleDelay = 600,
    fetchDetailData = (data: PropertyItem): Promise<PropertyInfo> => Promise.resolve({ ...data }),
    disabledValues = [],
    shouldUpdateRecentlyUsed = true,
    className,
    ...rest
  } = props;
  const locale = useLocale('PropertyPicker');
  const localeText = { ...defaultLocale, ...locale } as typeof defaultLocale;
  const Tabs = toPairs(PropertyTypes(localeText)).map((v) => ({ key: v[0], children: v[1] }));
  const [scope, setScope] = useState('all');
  const [keyword, setKeyword] = useState<string | undefined>('');
  const [recentlyUsedInMemo, setRecentlyUsedInMemo] = useState<{
    [key: string]: any[];
  }>();
  const [recentlyUsed, setRecentlyUsed] = useLocalStorage<{
    [key: string]: any[];
  }>(`${recentlyStorePrefix}_propertyPicker`, {
    all: [],
  });

  useEffect(() => {
    if (shouldUpdateRecentlyUsed) {
      setRecentlyUsedInMemo(recentlyUsed);
    }
  }, [recentlyUsed, shouldUpdateRecentlyUsed]);

  const [currentValue, setCurrentValue] = useState<PropertyValue | undefined>(initialValue);

  const prefixCls = usePrefixCls('property-picker-legacy');

  const [detailVisible, setDetailVisible] = useState(false);
  const debounceSetDetailVisible = useDebounceFn((visible: boolean) => {
    setDetailVisible(visible);
  }, detailVisibleDelay);
  const [dataList, setDataList] = useState<PropertyItem[]>([]);
  const navRef = useRef([{ key: 'all', children: localeText.allText }]);
  useEffect(() => {
    // 如果是Dimension类型 需要做一个数据转换
    let propertiItemList: PropertyItem[] = [];
    if (originDataSource && originDataSource.length) {
      if (!('value' in originDataSource[0])) {
        propertiItemList = originDataSource.map((v) => {
          const item = dimensionToPropertyItem(v as Dimension, localeText);
          item.itemIcon = () => <IconRender group={item.iconId} />;
          return item;
        });
      } else {
        propertiItemList = originDataSource.map((v) => {
          const item = v as PropertyItem;
          item.itemIcon = () => <IconRender group={item.iconId} />;
          return item;
        });
      }
    }
    const list = propertiItemList.map((v) => {
      const disabled = !!disabledValues && disabledValues.includes(v.id);

      return {
        ...v,
        disabled,
        pinyinName: getShortPinyin(v.label ?? ''),
      };
    });

    setDataList(list);
    /**
     * 设置属性类型tab,如果传入的列表没有对应的类型 不显示该tab
     */
    const types = uniq(propertiItemList.map((p) => p.type));
    const tabs = Tabs.filter((t) => types.indexOf(t.key) > -1);
    navRef.current = [{ key: 'all', children: localeText.allText }].concat(tabs);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [localeText.allText, originDataSource]);

  /**
   * 搜索关键字的方法,支持拼音匹配
   * @param input 带匹配的项
   * @param key 匹配的关键字
   */
  const keywordFilter = (input = '', key = '') => {
    if (!input || !key) return true;
    return !!pinyinMatch?.match(input, key);
  };

  /**
   * 属性列表数据源
   */
  const dataSource = useMemo(() => {
    const filteredData = dataList.filter((item) => {
      const { label, type, groupId, valueType } = item;
      if (groupId === 'virtual' && valueType !== 'string') {
        return false;
      }
      if (scope === 'all') {
        return keywordFilter(label, keyword);
      }
      return type === scope && keywordFilter(label, keyword);
    });

    // 按照分组排序
    const sortedData = orderBy(filteredData, ['typeOrder', 'groupOrder', 'pinyinName']);

    // mixin 最近使用
    const rids: string[] = recentlyUsedInMemo ? recentlyUsedInMemo[scope] : [];
    const recent: PropertyItem[] = [];
    rids?.forEach((v: string) => {
      const r = filteredData.find((d) => d.value === v);
      if (r) {
        recent.push({
          ...r,
          itemIcon: () => <IconRender group={r.iconId} />,
          _groupKey: 'recently',
        });
      }
    });
    return [recent, sortedData];
  }, [dataList, keyword, recentlyUsedInMemo, scope]);

  function onTabNavChange(key: string) {
    setScope(key);
  }

  /**
   * 点选时 设置最近使用
   * @param item
   */
  function _saveRecentlyByScope(item: PropertyItem) {
    const { value: v, type } = item;
    const recent = cloneDeep(recentlyUsed);
    // save by type/scope
    const realScope = type || 'all';
    let scopedRecent = recent[realScope];
    if (!scopedRecent) {
      scopedRecent = [];
    }
    let newScopedRecent = uniq([v, ...scopedRecent]);
    if (newScopedRecent.length > 5) {
      newScopedRecent = newScopedRecent.slice(0, 5);
    }
    const allScopedRecent = recent.all || [];

    let newAllScopedRecent = uniq([v, ...allScopedRecent]);
    if (newAllScopedRecent.length > 5) {
      newAllScopedRecent = newAllScopedRecent.slice(0, 5);
    }
    recent[realScope] = newScopedRecent;
    recent.all = newAllScopedRecent;
    setRecentlyUsed(recent);
  }
  function handleSelect(node: PropertyItem) {
    setCurrentValue(node as PropertyValue);

    _saveRecentlyByScope(node);
    if (isEmpty(currentValue) || !isEqualWith(currentValue, node, (a, b) => a.value === b.value)) {
      onChange?.(node);
    }
    onSelect?.(node);
  }
  const handleSearch = (query: string) => {
    setKeyword(query);
  };
  const handleItemClick = (e: React.MouseEvent<HTMLElement>, node: PropertyItem) => {
    handleSelect(node);
    onClick?.(e);
  };
  const [recentlyPropertyItems, propertyItems] = dataSource;
  const groupDatasource = useMemo(
    () => groupBy([...propertyItems], (o) => replace(o.type, /^recently¥/, '')),
    [propertyItems]
  );

  function labelRender(item: PropertyItem) {
    const isShowIndent = Boolean(item.associatedKey && item._groupKey !== 'recently');
    return (
      <>
        <span className={classNames('item-icon', { indent: isShowIndent })}>{item.itemIcon?.()}</span>
        <span>{item.label}</span>
      </>
    );
  }
  const [hoverdNodeValue, setHoveredNodeValue] = useState<PropertyItem | undefined>();
  function getListItems(items: PropertyItem[], keyPrefix = '') {
    const handleItemMouseEnter = (data: PropertyItem) => {
      setHoveredNodeValue(data);
      debounceSetDetailVisible(true);
    };
    const handleItemMouseLeave = () => {
      setHoveredNodeValue(undefined);
      debounceSetDetailVisible.cancel();
      setDetailVisible(false);
    };
    const listItems = items.map((data: PropertyItem) => {
      const select =
        !isEmpty(currentValue) &&
        isEqualWith(currentValue, data, (a, b) => a?.value === b?.value) &&
        data._groupKey !== 'recently';
      const itemProp: ListItemProps = {
        disabled: data.disabled,
        ellipsis: true,
        key: ['item', keyPrefix, data.type, data.groupId, data.id].join('-'),
        className: classNames({ selected: select }),
        children: labelRender(data),
        onClick: (e) => handleItemClick(e, data),
        onMouseEnter: () => {
          handleItemMouseEnter(data);
        },
        onMouseLeave: () => {
          handleItemMouseLeave();
        },
      };
      return itemProp;
    });
    return listItems;
  }
  function subGroupRender(groupData: Dictionary<PropertyItem[]>) {
    const dom = keys(groupData).map((gkey) => {
      const { groupName, type } = groupData[gkey][0];
      const listItems = getListItems(groupData[gkey]);
      return (
        <ExpandableGroupOrSubGroup
          key={['exp', type, gkey].join('-')}
          groupKey={[type, gkey].join('-')}
          title={groupName}
          type="subgroup"
          items={listItems}
        />
      );
    });
    return dom as React.ReactNode;
  }
  const renderItems = () => {
    if (propertyItems?.length === 0) {
      return <Result type="empty-result" size="small" />;
    }
    const recentlyNodes = recentlyPropertyItems?.length > 0 && (
      <React.Fragment key="recentlyNodes">
        <ExpandableGroupOrSubGroup
          groupKey="recently"
          key="exp-group-recently"
          title={localeText.recent}
          type="group"
          items={getListItems(recentlyPropertyItems, 'recently')}
        />
        <List.Divider key="divider-group-recently" />
      </React.Fragment>
    );

    const groupFn = (item: PropertyItem, existIsSystem: boolean) => {
      if (existIsSystem) {
        if (item.groupId === 'tag') {
          return 'tag';
        }
        if (item.groupId === 'virtual') {
          return 'virtual';
        }
        return item.isSystem;
      }
      return item.groupId;
    };

    const groupDataNodes = keys(groupDatasource).map((key, index) => {
      const groupData = groupDatasource[key];
      const existIsSystem = has(groupData, '[0].isSystem');

      let subGroupDic;
      if (key === 'event' && 'associatedKey' in groupData[0] && groupData.length > 1) {
        subGroupDic = groupBy(
          groupData
            .filter((ele) => !ele.associatedKey)
            .map((ele) => [ele])
            ?.reduce((acc, cur) => {
              cur.push(
                ...groupData
                  .filter((e) => {
                    if (e.associatedKey === cur[0].id) {
                      if (existIsSystem) {
                        e.isSystem = cur[0].isSystem;
                      }
                      return true;
                    }
                    return false;
                  })
                  .map((item) => {
                    const { groupId, groupName } = [...cur].shift() || {};
                    return { ...item, groupId, groupName };
                  })
              );
              acc.push(...cur);
              return acc;
            }, []),
          (item) => groupFn(item, existIsSystem)
        );
      } else {
        subGroupDic = groupBy(groupData, (item) => groupFn(item, existIsSystem));
      }

      const { typeName } = groupData[0];
      // 此处的处理是 如果2级分组只有一组 提升为一级分组;如果没有这个需求删除该if分支 ;
      if (keys(subGroupDic).length === 1) {
        const items = getListItems(subGroupDic[keys(subGroupDic)[0]]);
        return (
          <React.Fragment key={`groupDataNodes-${index}`}>
            {index > 0 && <List.Divider key={`divider-group-${key}-${index}`} />}
            <ExpandableGroupOrSubGroup
              key={`exp-group-${key}`}
              groupKey={`${key}`}
              title={typeName}
              type="group"
              items={items}
            />
          </React.Fragment>
        );
      }
      return (
        <React.Fragment key={`groupDataNodes-${index}`}>
          {index > 0 && <List.Divider key={`divider-group-${key}-${index}`} />}
          <List.ItemGroup key={`group-${key}`} title={typeName} expandable={false}>
            {subGroupRender(subGroupDic)}
          </List.ItemGroup>
        </React.Fragment>
      );
    });
    const childrens = [recentlyNodes, groupDataNodes];
    return childrens as React.ReactNode;
  };
  const renderDetail = () =>
    hoverdNodeValue && <PropertyCard nodeData={hoverdNodeValue} fetchData={promisify(fetchDetailData)} />;
  return (
    <>
      <BasePicker
        {...rest}
        className={classNames(prefixCls, className)}
        renderItems={renderItems}
        detailVisible={detailVisible && !!hoverdNodeValue}
        renderDetail={renderDetail}
        loading={loading}
        searchBar={{
          placeholder: searchBar?.placeholder || localeText.searchPlaceholder,
          onSearch: handleSearch,
        }}
        tabNav={{
          items: navRef.current,
          onChange: onTabNavChange,
        }}
      />
    </>
  );
}