lodash-es#set TypeScript Examples

The following examples show how to use lodash-es#set. 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: actions.ts    From github-deploy-center with MIT License 6 votes vote down vote up
setState = <T>(
  { state }: Context,
  { selector, value }: { selector: (state: AppState) => T; value: T }
) => {
  const path = selector.toString().replace(/^.*?\./, '')
  if (get(state, path) === undefined) {
    throw Error('Unkown path ' + path)
  }
  set(state, path, value)
}
Example #2
Source File: evalJsBindings.ts    From mui-toolpad with MIT License 6 votes vote down vote up
export function buildGlobalScope(bindings: Record<string, ParsedBinding>): Record<string, unknown> {
  const globalScope = {};
  for (const binding of Object.values(bindings)) {
    if (binding.scopePath) {
      const value = binding.result?.value;
      set(globalScope, binding.scopePath, value);
    }
  }
  return globalScope;
}
Example #3
Source File: edit-detail.tsx    From bext with MIT License 4 votes vote down vote up
Content: FC = () => {
  const { draft, setDraft } = useDraft();
  const { tagList } = useMeta();
  const tagOptions = useMemo(
    () =>
      uniq([...tagList.map(({ name }) => name), ...(draft?.tags || [])]).map(
        (tag) => ({
          key: tag,
          text: tag,
        }),
      ),
    [tagList, draft?.tags],
  );

  const [matchInput, setMatchInput] = useState(
    () => draft?.match?.join('@@') || '',
  );
  useEffect(() => {
    setDraft({
      match: matchInput
        ? matchInput.split('@@').filter((rule) => rule)
        : undefined,
    });
  }, [matchInput, setDraft]);

  return (
    <>
      <div className="grid grid-cols-3 gap-3">
        <TextField
          label="脚本ID"
          value={draft?.id || ''}
          onChange={(_, id = '') => setDraft({ id })}
          errorMessage={
            ID_RULE.test(draft?.id || '') ? undefined : '只允许数字 ID'
          }
        />
        <TextField
          label="脚本名称"
          value={draft?.name || ''}
          onChange={(_, name = '') => setDraft({ name })}
        />
        <TextField
          label="版本"
          value={draft?.version || ''}
          onChange={(_, version = '') => setDraft({ version })}
        />
      </div>
      <Dropdown
        className="flex-1"
        label="分类标签"
        multiSelect
        options={tagOptions}
        selectedKeys={draft?.tags || []}
        onChange={(_, item) =>
          setDraft({
            tags: item?.selected
              ? [...(draft?.tags || []), String(item.key)]
              : draft?.tags?.filter((key) => key !== item?.key),
          })
        }
      />
      <TextField
        label="简介"
        multiline
        placeholder="70字以内"
        value={draft?.synopsis || ''}
        onChange={(_, text) => {
          setDraft({ synopsis: text?.slice(0, 70) });
        }}
      />
      <TextField
        label="匹配规则(使用 @@ 分隔,匹配所有请留空)"
        value={matchInput}
        onChange={(_, text) => setMatchInput(text || '')}
        description={`当前将会匹配
        ${
          typeof draft?.match === 'undefined'
            ? '所有网站'
            : `以下网站:${draft.match.join(', ')}`
        }`}
      />
      <Label>详情(支持内联图片,请直接粘贴)</Label>
      <RichEditor
        defaultHtml={draft?.detail}
        onChange={(html) => setDraft({ detail: html })}
      />
      <TextField
        label="附加元信息"
        multiline
        value={draft?.extra?.xMetaComment || ''}
        onChange={(_, text) => {
          setDraft({
            extra: set(cloneDeep(draft?.extra ?? {}), 'xMetaComment', text),
          });
        }}
        description="专用于 X 浏览器和 Top 浏览器的元信息,填写示例:'// @run-at document-start'(去除单引号,保留注释符号),已自动生成无需在这里填写的:name、namespace、version、description、author、match"
      />
    </>
  );
}
Example #4
Source File: evalJsBindings.ts    From mui-toolpad with MIT License 4 votes vote down vote up
/**
 * Evaluates the expressions and replace with their result
 */
export default function evalJsBindings(
  bindings: Record<string, ParsedBinding>,
): Record<string, ParsedBinding> {
  const bindingsMap = new Map(Object.entries(bindings));

  const bindingIdMap = new Map<string, string>();
  for (const [bindingId, binding] of bindingsMap) {
    if (binding.scopePath) {
      bindingIdMap.set(binding.scopePath, bindingId);
    }
  }

  const computationStatuses = new Map<string, { result: null | BindingEvaluationResult }>();

  let proxiedScope: Record<string, unknown>;

  const proxify = (obj: Record<string, unknown>, label?: string): Record<string, unknown> =>
    new Proxy(obj, {
      get(target, prop, receiver) {
        if (typeof prop === 'symbol') {
          return Reflect.get(target, prop, receiver);
        }

        const scopePath = label ? `${label}.${prop}` : prop;
        const bindingId = bindingIdMap.get(scopePath);
        const binding = bindingId && bindingsMap.get(bindingId);

        if (binding) {
          const expression = binding.expression;

          if (expression) {
            const computed = computationStatuses.get(expression);
            if (computed) {
              if (computed.result) {
                // From cache
                return unwrapEvaluationResult(computed.result);
              }

              throw new Error(`Cycle detected "${scopePath}"`);
            }

            // use null to mark as "computing"
            computationStatuses.set(expression, { result: null });
            const result = evaluateExpression(expression, proxiedScope);
            computationStatuses.set(expression, { result });
            // From freshly computed
            return unwrapEvaluationResult(result);
          }

          if (binding.result) {
            // From input value on the page
            return unwrapEvaluationResult(binding.result);
          }
        }

        const result = target[prop];

        if (result && typeof result === 'object') {
          return proxify(result as Record<string, unknown>, scopePath);
        }

        return Reflect.get(target, prop, receiver);
      },
    });

  const scope = buildGlobalScope(bindings);
  proxiedScope = proxify(scope);

  return mapValues(bindings, (binding) => {
    const { expression, result, ...rest } = binding;
    return {
      ...rest,
      result: expression
        ? evaluateExpression(expression, proxiedScope)
        : result || { value: undefined },
    };
  });
}