lodash-es#pick TypeScript Examples

The following examples show how to use lodash-es#pick. 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: MenuButton.tsx    From UUI with MIT License 6 votes vote down vote up
MenuButton = UUIFunctionComponent({
  name: 'MenuButton',
  nodes: {
    Root: 'div',
    Button: UUIButton,
  },
  propTypes: MenuButtonPropTypes,
}, (props: MenuButtonFeatureProps, { nodes }) => {
  const { Root, Button } = nodes

  return (
    <Root role="menuitem">
      <Button {...pick(props, 'onClick', 'loading', 'disabled')}>
        {props.children}
      </Button>
    </Root>
  )
})
Example #2
Source File: edge.ts    From LogicFlow with Apache License 2.0 6 votes vote down vote up
pickEdgeConfig = (data): EdgeConfig => pick(data, [
  'id',
  'type',
  'sourceNodeId',
  'sourceAnchorId',
  'targetNodeId',
  'targetAnchorId',
  'pointsList',
  'startPoint',
  'endPoint',
  'properties',
])
Example #3
Source File: node.ts    From LogicFlow with Apache License 2.0 6 votes vote down vote up
pickNodeConfig = (data): NodeConfig => {
  const nodeData = pick(data, [
    'id',
    'type',
    'x',
    'y',
    'text',
    'properties',
  ]);
  return nodeData;
}
Example #4
Source File: EditConfigModel.ts    From LogicFlow with Apache License 2.0 5 votes vote down vote up
getConfigDetail(config) {
    const { isSilentMode, textEdit } = config;
    const conf = {};
    // false表示从静默模式恢复
    if (isSilentMode === false) {
      assign(conf, this.defaultConfig);
    }
    // 如果不传,默认undefined表示非静默模式
    if (isSilentMode === true) {
      const silentConfig = pick(SilentConfig, keys);
      // 在修改之前,
      this.defaultConfig = {
        stopZoomGraph: this.stopZoomGraph,
        stopScrollGraph: this.stopScrollGraph,
        stopMoveGraph: this.stopMoveGraph,
        adjustEdge: this.adjustEdge,
        adjustEdgeMiddle: this.adjustEdgeMiddle,
        adjustEdgeStartAndEnd: this.adjustEdgeStartAndEnd,
        adjustNodePosition: this.adjustNodePosition,
        hideAnchors: this.hideAnchors,
        hoverOutline: this.hoverOutline,
        nodeSelectedOutline: this.nodeSelectedOutline,
        edgeSelectedOutline: this.edgeSelectedOutline,
        nodeTextEdit: this.nodeTextEdit,
        edgeTextEdit: this.edgeTextEdit,
        nodeTextDraggable: this.nodeTextDraggable,
        edgeTextDraggable: this.edgeTextDraggable,
      };
      assign(conf, silentConfig);
    }
    // 如果不传,默认undefined表示允许文本编辑
    if (textEdit === false) {
      assign(conf, {
        nodeTextEdit: false,
        edgeTextEdit: false,
      });
    }
    const userConfig = pick(config, keys);
    return assign(conf, userConfig);
  }
Example #5
Source File: EditConfigModel.ts    From LogicFlow with Apache License 2.0 5 votes vote down vote up
getConfig() {
    return pick(this, keys);
  }
Example #6
Source File: server.ts    From cross-seed with Apache License 2.0 5 votes vote down vote up
async function search(
	req: IncomingMessage,
	res: ServerResponse
): Promise<void> {
	const dataStr = await getData(req);
	let data;
	try {
		data = parseData(dataStr);
	} catch (e) {
		logger.error({
			label: Label.SERVER,
			message: e.message,
		});
		res.writeHead(400);
		res.end(e.message);
		return;
	}
	const criteria: TorrentLocator = pick(data, ["infoHash", "name"]);
	const nonceOptions: NonceOptions = pick(data, ["trackers", "outputDir"]);

	if (!("infoHash" in criteria || "name" in criteria)) {
		const message = "A name or info hash must be provided";
		logger.error({ label: Label.SERVER, message });
		res.writeHead(400);
		res.end(message);
	}

	const criteriaStr = inspect(criteria);

	res.writeHead(204);
	res.end();

	logger.info({
		label: Label.SERVER,
		message: `Received search request: ${criteriaStr}`,
	});

	try {
		let numFound = null;
		if (criteria) {
			numFound = await searchForLocalTorrentByCriteria(
				criteria,
				nonceOptions
			);
		}

		if (numFound === null) {
			logger.info({
				label: Label.SERVER,
				message: `Did not search for ${criteriaStr}`,
			});
		} else {
			logger.info({
				label: Label.SERVER,
				message: `Found ${numFound} torrents for ${criteriaStr}`,
			});
		}
	} catch (e) {
		logger.error(e);
	}
}
Example #7
Source File: Cascader.tsx    From UUI with MIT License 4 votes vote down vote up
Cascader = UUIFunctionComponent({
  name: 'Cascader',
  nodes: {
    Root: 'div',
    Activator: 'div',
    Placeholder: 'div',
    Result: 'div',
    DisplayValue: 'span',
    DisplayValueSeparator: 'span',
    Dropdown: Popover,
    DropdownIcon: Icons.ChevronDown,
    ActionBox: 'div',
    LevelList: 'div',
    OptionList: UUIListBox,
    Option: 'div',
    OptionLabel: 'div',
    OptionIcon: Icons.ChevronRight,
    SearchInput: UUITextField,
    SearchIcon: Icons.Search,
    SearchList: UUIListBox,
    SearchMatched: 'span',
    LoadingSpinner: LoadingSpinner,
  },
  propTypes: CascaderPropTypes,
}, (props: CascaderFeatureProps, { nodes, NodeDataProps }) => {
  /**
   * Component Nodes Spread
   */
  const {
    Activator, Result, Placeholder,
    DisplayValue, DisplayValueSeparator,
    Root, Dropdown, DropdownIcon,
    LevelList, LoadingSpinner,
    SearchList, SearchIcon,
    OptionList, Option, OptionLabel, OptionIcon,
    ActionBox, SearchInput,
  } = nodes

  /**
   * Default props value
   */
  const finalProps = {
    placeholder: props.placeholder || 'select options...',
    searchPlaceholder: props.searchPlaceholder || 'Search options...',
    expandTriggerType: props.expandTriggerType || 'click',
    searchable: props.searchable === undefined ? false : props.searchable,
    changeOnFinalSelect: props.changeOnFinalSelect === undefined ? true : props.changeOnFinalSelect,
    dropdownPlacement: props.dropdownPlacement === undefined ? 'bottom-start' : props.dropdownPlacement
  }

  /**
   * Component Inner States
   */
  const [innerValue, setInnerValue, resetInnerValue] = usePendingValue(props.value, props.onChange)
  const [popoverActive, setPopoverActive] = useState(false)
  const [searchInputValue, setSearchInputValue] = useState('')

  /**
   * Generate tree hierarchy data of cascade options for rendering.
   */
  type Levels = (CascaderOption & {
    selectedOption: Omit<CascaderOption, 'children'>[];
    selected: boolean;
  })[][]
  const levels = useMemo(() => {
    const dfs = (data: Levels, index: number, selectedOption: CascaderOption[], options: CascaderOption[]) => {
      const getNewSelectedOption = (option: CascaderOption) => [...selectedOption, pick(option, 'value', 'label')]
      const getSelected = (option: CascaderOption) => innerValue ? option.value === innerValue[index] : false
      data.push(options.map((i) => ({ ...i, selectedOption: getNewSelectedOption(i), selected: getSelected(i) })))
      if (innerValue && innerValue[index]) {
        const value = innerValue[index]
        const option = options.find((option) => option.value === value)
        if (option && option.children) {
          dfs(data, index+1, getNewSelectedOption(option), option.children)
        }
      }
    }
    const data: Levels = []
    dfs(data, 0, [], props.options)
    return data
  }, [props.options, innerValue])

  const renderValueResult = useCallback((options: CascaderOption[]) => {
    return (
      <Result>
        {ReactHelper.join(
          options.map((option) => {
            return (
              <DisplayValue key={option.value}>{option.content || option.label}</DisplayValue>
            )
          }),
          <DisplayValueSeparator>/</DisplayValueSeparator>
        )}
      </Result>
    )
  }, [DisplayValue, DisplayValueSeparator, Result])

  const valueResult = useMemo(() => {
    if (!props.value || props.value.length === 0) return null
    const selectedOptions = findSelectedOptions(props.value, props.options)
    return renderValueResult(selectedOptions)
  }, [props.options, props.value, renderValueResult])

  const displayResult = useMemo(() => {
    return props.value && props.value.length > 0
      ? valueResult
      : <Placeholder>{finalProps.placeholder}</Placeholder>
  }, [Placeholder, finalProps.placeholder, props.value, valueResult])

  /**
   * manage option ListBox data
   */

  const optionListDataOfLevels = useMemo(() => {
    return levels.map((level, levelIndex) => {
      const items: ListBoxItem[] = level.map((option) => {
        return {
          id: option.value,
          content: (
            <Option
              onMouseEnter={() => {
                if (finalProps.expandTriggerType !== 'hover') return
                if (option.disabled) return
                if (!option.children) return

                const newValue = [
                  ...(innerValue || []).slice(0, levelIndex),
                  option.value,
                ]
                setInnerValue(newValue)
              }}
            >
              <OptionLabel>{option.content || option.label}</OptionLabel>
              <OptionIcon
                {...NodeDataProps({
                  'hidden': !option.children,
                })}
                svgrProps={{ strokeWidth: 1 }}
              />
            </Option>
          ),
          disabled: option.disabled,
        }
      })
      const option = level.find((option) => option.selected)
      const selectedIds = option ? [option.value] : []

      const handleOnSelect = (selectedIds: string[]) => {
        if (selectedIds && selectedIds.length === 0) return

        const selectedOption = findOneInAllOptions(selectedIds[0], props.options)
        if (!selectedOption) return

        const newValue = (innerValue || []).slice(0, levelIndex)
        if (selectedIds && selectedIds[0]) {
          newValue.push(selectedIds[0])
        }

        const isLastLevel = !selectedOption.children
        const changeOnFinalSelect = finalProps.changeOnFinalSelect

        if (isLastLevel) {
          setInnerValue(newValue, true)
          setPopoverActive(false)
        } else {
          setInnerValue(newValue, !changeOnFinalSelect)
        }
      }
      return { items, selectedIds, handleOnSelect }
    })
  }, [levels, Option, OptionLabel, OptionIcon, NodeDataProps, finalProps.expandTriggerType, finalProps.changeOnFinalSelect, innerValue, setInnerValue, props.options])

  const searchListData = useMemo(() => {
    if (!searchInputValue) return null
    const matchedOptionsGroup = searchInOptions(searchInputValue, props.options, props.onSearch)
    const items = matchedOptionsGroup.map((options) => {
      const matchedSearchOptionId = JSON.stringify(options.map((i) => i.value))
      return {
        id: matchedSearchOptionId,
        content: (
          <Option>{renderValueResult(options)}</Option>
        ),
      }
    })
    const selectedIds: string[] = []
    const handleOnSelect = (selectedIds: string[]) => {
      if (selectedIds && selectedIds.length === 0) return
      const matchedSearchOptionId = selectedIds[0]
      const newValue = JSON.parse(matchedSearchOptionId)
      setInnerValue(newValue, true)
      setPopoverActive(false)
    }
    return { items, selectedIds, handleOnSelect }
  }, [Option, props.onSearch, props.options, renderValueResult, searchInputValue, setInnerValue])

  return (
    <Root
      {...NodeDataProps({
        'active': !!popoverActive,
        'loading': !!props.loading,
        'searchable': !!finalProps.searchable,
      })}
      role="select"
      tabIndex={0}
      onKeyDown={(event) => {
        switch (event.keyCode) {
          case KeyCode.Enter:
          case KeyCode.SpaceBar:
            if (!popoverActive) {
              setPopoverActive(true)
            }
            break
          case KeyCode.Escape:
            setPopoverActive(false)
            break
          default:
            // do nothing
        }
      }}
    >
      <Dropdown
        usePortal={props.usePortal}
        portalContainer={props.portalContainer}
        active={popoverActive}
        placement={finalProps.dropdownPlacement}
        onClickAway={() => {
          setPopoverActive(false)
          resetInnerValue()
          setSearchInputValue('')
        }}
        activator={
          <Activator
            onClick={() => {
              setPopoverActive((value) => !value)
            }}
          >
            {displayResult}
            {props.loading && (
              <LoadingSpinner width={16} height={16} />
            )}
            <DropdownIcon width={20} height={20} svgrProps={{ strokeWidth: 1 }} />
          </Activator>
        }
      >
        <ActionBox>
          {props.searchable && (
            <SearchInput
              value={searchInputValue}
              onChange={(value) => { setSearchInputValue(value) }}
              placeholder={finalProps.searchPlaceholder}
              customize={{
                Root: {
                  extendChildrenBefore: (
                    <SearchIcon />
                  )
                }
              }}
            />
          )}
          {searchListData ? (
            <SearchList
              items={searchListData.items}
              selectedIds={searchListData.selectedIds}
              onSelected={searchListData.handleOnSelect}
            />
          ) : (
            <LevelList>
              {optionListDataOfLevels.map((data, levelIndex) => {
                return (
                  <OptionList
                    key={levelIndex}
                    items={data.items}
                    selectedIds={data.selectedIds}
                    onSelected={data.handleOnSelect}
                  />
                )
              })}
            </LevelList>
          )}
        </ActionBox>
      </Dropdown>
    </Root>
  )
})