lodash#set TypeScript Examples

The following examples show how to use lodash#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: utils.ts    From yforms with MIT License 7 votes vote down vote up
export function submitFormatValues(
  values: KeyValue,
  formatFieldsValue?: FormatFieldsValue[],
): KeyValue {
  const _values = mergeWithDom({}, values);
  const list: FormatFieldsValue[] = sortBy(formatFieldsValue, (item) => {
    if (!item) return;
    if (isArray(item.name)) {
      return -item.name.length;
    }
    return -`${item.name}`.length;
  }).filter((x) => x);
  forEach(list, (item) => {
    const { name, format } = item;
    if (name && format) {
      const parentValue = getParentNameData(values, name);
      // 如果上一级是 undefined,则不处理该字段。(List add 会生成空对象)
      if (parentValue === undefined) return;
      try {
        set(_values, name, format(get(values, name), parentValue, values));
      } catch (error) {
        // 如果 format 代码报错这里抛出异常
        // eslint-disable-next-line no-console
        console.error(error);
        warning(false, error);
      }
    }
  });
  return _values;
}
Example #2
Source File: utils.tsx    From erda-ui with GNU Affero General Public License v3.0 7 votes vote down vote up
walkTree = (treeData: TreeNode[], options: { disabled?: boolean }, excludeKey: string) => {
  treeData.forEach((node) => {
    Object.keys(options).forEach((optionKey) => {
      if (excludeKey === node.key) {
        return;
      }
      set(node, optionKey, options[optionKey]);
      if (node.children) {
        walkTree(node.children, options, excludeKey);
      }
    });
  });
}
Example #3
Source File: testutils.ts    From EIP-Bot with Creative Commons Zero v1.0 Universal 7 votes vote down vote up
convertTrueToStringOnLeafs = (
  _obj: Record<string, object | (boolean | null)>,
  setNull = false
): Record<string, string | undefined> => {
  const obj = _.cloneDeep(_obj);
  const paths = getAllPaths(obj);
  for (const path of paths) {
    const value = _.get(obj, path);
    if (value === true) {
      _.set(obj, path, "required");
    } else if (setNull && _.isNull(value)) {
      _.set(obj, path, "optional");
    } else {
      _.unset(obj, path);
    }
  }
  return obj as any;
}
Example #4
Source File: utils.tsx    From gant-design with MIT License 7 votes vote down vote up
transColumnsToObj = columns => {
  const res = {};
  const setPropertyType = currentColumn => {
    if (!currentColumn || !get(currentColumn, 'fieldName')) {
      return;
    }
    if (isArray(currentColumn.children)) {
      currentColumn.children.forEach((c: any) => {
        setPropertyType(c);
      });
      return;
    }
    const { fieldName } = currentColumn;

    set(res, `${fieldName}`, currentColumn);
    res[fieldName] = currentColumn;
  };
  columns.forEach(column => {
    setPropertyType(column);
  });
  return res;
}
Example #5
Source File: api.ts    From Adachi-BOT with MIT License 6 votes vote down vote up
/* mihoyo BBS API */
export async function getBaseInfo( mysID: number, cookie: string ): Promise<ResponseBody> {
	const query = { uid: mysID };
	return new Promise( ( resolve, reject ) => {
		request( {
			method: "GET",
			url: __API.FETCH_ROLE_ID,
			qs: query,
			headers: {
				...HEADERS,
				"DS": getDS( query ),
				"Cookie": cookie
			}
		} )
			.then( ( result ) => {
				const resp = toCamelCase( JSON.parse( result ) );
				const data: ResponseBody = set( resp, "data.type", "bbs" )
				resolve( data );
			} )
			.catch( ( reason ) => {
				reject( reason );
			} );
	} );
}
Example #6
Source File: index.ts    From strapi-plugin-comments with MIT License 6 votes vote down vote up
reducer = (state = initialState, action) =>
  // eslint-disable-next-line consistent-return
  produce(state, (draftState) => {
    switch (action.type) {
      case SET_CONFIG: {
        set(draftState, "config", action.data);
        break;
      }
      case GET_CONFIG: {
        return draftState?.config;
      }
      default:
        return draftState;
    }
  })
Example #7
Source File: formikValidateJsonSchema.ts    From amplication with Apache License 2.0 6 votes vote down vote up
/**
 * A function to validate a form based on a given JSON Schema.
 * When using formik validation, do no use any DOM validation attributes to avoid the default browser validation and error messages

 * @param values
 * The data to be validated
 * @param validationSchema
 * The JSON schema for validation
 * @returns
 * FormikErrors object
 * @example
 *   <Formik
 *      initialValues={INITIAL_VALUES}
 *      validate={(values: ValuesType) => {
 *        return validate<ValuesType>(values, FORM_SCHEMA);
 *      }}
 *      onSubmit={handleSubmit}
 *    >
 *  */
export function validate<T>(
  values: T,
  validationSchema: object
): FormikErrors<T> {
  const errors: FormikErrors<T> = {};

  const ajv = new Ajv({ allErrors: true });

  let isValid = ajv.validate(validationSchema, values);

  if (!isValid && ajv.errors) {
    for (const error of ajv.errors) {
      //remove the first dot from dataPath
      const fieldName = error.instancePath.substring(1).replaceAll("/", ".");
      set(errors, fieldName, error.message);
    }
  }

  return errors;
}
Example #8
Source File: table-facet.ts    From S2 with MIT License 6 votes vote down vote up
protected updateRowResizeArea() {
    const { foregroundGroup, options } = this.spreadsheet;
    const resize = get(options, 'interaction.resize');

    const shouldDrawResize = isBoolean(resize)
      ? resize
      : (resize as ResizeActiveOptions)?.rowCellVertical;
    if (!shouldDrawResize) {
      return;
    }

    const rowResizeGroup = foregroundGroup.findById(KEY_GROUP_ROW_RESIZE_AREA);
    const rowResizeFrozenGroup = foregroundGroup.findById(
      KEY_GROUP_FROZEN_ROW_RESIZE_AREA,
    );
    if (rowResizeGroup) {
      rowResizeGroup.set('children', []);
    }
    if (rowResizeFrozenGroup) {
      rowResizeFrozenGroup.set('children', []);
    }
    const allCells: TableRowCell[] = getAllChildCells(
      this.panelGroup.getChildren() as IElement[],
      TableRowCell,
    );

    allCells.forEach((cell) => {
      cell.drawResizeArea();
    });
  }
Example #9
Source File: compoundJSONSchemaYAML.ts    From hub with Apache License 2.0 6 votes vote down vote up
prepareValueFile = (obj: any) => {
  let newObj = {};

  const checkOpts = (el: any, path: string) => {
    if (isObject(el)) {
      if (el.hasOwnProperty('properties')) {
        const properties = (el as any).properties;
        if (!shouldIgnorePath(el)) {
          set(newObj, path, { ...el, properties: {} });
          Object.keys(properties).forEach((item: any) => {
            const currentPath = isUndefined(path) ? `properties.${item}` : `${path}.properties.${item}`;
            checkOpts(properties[item], currentPath);
          });
        }
      } else {
        if (path && !shouldIgnorePath(el)) {
          set(newObj, path, el);
        }
      }
    }
  };

  Object.keys(obj).forEach((propName: string) => {
    checkOpts(obj[propName], propName);
  });

  return newObj;
}
Example #10
Source File: index.ts    From reaction-role with MIT License 6 votes vote down vote up
public async createMessage(
		channel_id: string,
		message_id: string,
		limit: number,
		...emojis: IEmoji[]
	): Promise<IMessage> {
		const message: IMessage = {
			channel_id,
			emojis,
			message_id,
			limit,
			type: "regular",
		};
		set(this.config, message_id, message);
		if (this.on_set) await this.on_set(this.config);
		return message;
	}
Example #11
Source File: index.tsx    From next-basics with GNU General Public License v3.0 6 votes vote down vote up
// istanbul ignore next
  private initData(mutableProps: {
    mainTitle: string;
    description: string;
    subTitle: string;
  }): void {
    const pickFields = pick(this.fields, [
      "mainTitle",
      "description",
      "subTitle",
    ]);
    forEach(pickFields, (fieldKey, field: string) => {
      set(mutableProps, field, get(this.dataSource, fieldKey));
    });
  }
Example #12
Source File: setProperties.ts    From next-core with GNU General Public License v3.0 6 votes vote down vote up
export function setRealProperties(
  brick: HTMLElement,
  realProps: Record<string, unknown>,
  extractProps?: boolean
): void {
  for (const [propName, propValue] of Object.entries(realProps)) {
    if (propName === "style" || propName === "dataset") {
      for (const [k, v] of Object.entries(propValue)) {
        (brick[propName] as unknown as Record<string, unknown>)[k] = v;
      }
    } else if (propName === "innerHTML") {
      // `innerHTML` is dangerous, use `textContent` instead.
      // eslint-disable-next-line no-console
      console.error("Please use `textContent` instead of `innerHTML`.");
      brick.textContent = propValue as string;
    } else {
      if (extractProps) {
        set(brick, propName, propValue);
      } else {
        (brick as unknown as Record<string, unknown>)[propName] = propValue;
      }
    }
  }
}
Example #13
Source File: regist-router.tsx    From erda-ui with GNU Affero General Public License v3.0 6 votes vote down vote up
resetRouter = (routers: Obj<SHELL.Route[]>) => {
  return produce(routers, (draft) => {
    const routerMarkObj: Obj = {};
    const toMarkObj: Obj = {};
    const getRouterMarks = (_r: SHELL.Route[], _path: string) => {
      _r.forEach((rItem: SHELL.Route, idx: number) => {
        const { mark, routes: _rs, toMark } = rItem;
        if (mark && !routerMarkObj[mark]) {
          routerMarkObj[mark] = rItem;
        }
        if (toMark) {
          toMarkObj[toMark] = (toMarkObj[toMark] || []).concat({ router: rItem, key: `${_path}.[${idx}]` });
        }

        if (_rs) {
          getRouterMarks(_rs, `${_path}.[${idx}].routes`);
        }
      });
    };

    map(draft, (rItem, key) => {
      getRouterMarks(rItem, key);
    });

    map(toMarkObj, (_toObjArr, k) => {
      map(_toObjArr, (_toObj) => {
        const { key, router: _toRouter } = _toObj;
        if (_toRouter && routerMarkObj[k]) {
          _toRouter.toMark = undefined;
          routerMarkObj[k].routes = (routerMarkObj[k].routes || []).concat(_toRouter);
          set(draft, key, undefined);
        }
      });
    });
  });
}
Example #14
Source File: index.ts    From EIP-Bot with Creative Commons Zero v1.0 Universal 6 votes vote down vote up
innerJoinAncestors = (
  parent: TestResults,
  objects: TestResults[]
) => {
  const objectPaths = objects.map(getAllTruthyObjectPaths);
  const commonPaths = intersection(...objectPaths);
  const clearPaths = getAllTruthyObjectPaths(parent).filter(
    (path) => !commonPaths.includes(path)
  );

  return clearPaths.reduce(
    (obj, path) => set(obj, path, undefined),
    parent
  ) as TestResults;
}
Example #15
Source File: index.ts    From gant-design with MIT License 6 votes vote down vote up
errorSign(validateErros: any, newData: any[]) {
    let update: any[] = [];
    const indexArr: number[] = [];
    update = newData.map(itemData => {
      const nodeId = this.agGridConfig.getRowNodeId(itemData);
      const rowNode = this.agGridApi.getRowNode(nodeId);
      const rowIndex = get(rowNode, 'rowIndex', -1);
      const errorsArr = validateErros[rowIndex];
      const mergeData = { ...get(rowNode, 'data', {}), ...itemData };
      const { _rowError: merge_rowError, ...newItemData } = mergeData;
      if (errorsArr) {
        const _rowError: any = {};
        errorsArr.map(itemError => {
          set(_rowError, itemError.field, itemError.message);
        });
        rowNode.setData({ ...newItemData, _rowError });
      } else {
        if (merge_rowError) rowNode.setData({ ...newItemData });
      }
    });
  }
Example #16
Source File: schemaLoader.ts    From form-pa with GNU Affero General Public License v3.0 6 votes vote down vote up
getDataFromURL = (): Richiedente => {
  const urlParams = new URLSearchParams(window.location.search);
  const richiedente: { readonly [key: string]: string } = {};

  for (const [key, value] of urlParams.entries()) {
    if (!Object.keys(mapping).includes(key)) {
      continue;
    }
    set(richiedente, mapping[key], value);
  }

  return {
    richiedente,
  };
}
Example #17
Source File: hooks.tsx    From ovineherd with Apache License 2.0 6 votes vote down vote up
export function useSchema(option: UseSchemaOption, deps: DependencyList = []) {
  const { schemaProps, schema: optSchema, apis: optApis, getSchema, getApis, filterSchema } = option
  const { userInfo } = useAppContext()
  const depArr = [userInfo].concat(deps)

  const schemaComponent = useMemo(() => {
    const schema = getSchema ? getSchema() : optSchema
    const apis = getApis ? getApis() : optApis
    set(schema, 'preset.apis', apis || {})

    return (
      <Amis
        key={uuid()}
        schema={filterSchema ? filterSchema(schema) : schema}
        props={schemaProps}
      />
    )
  }, depArr)

  return schemaComponent
}
Example #18
Source File: transaction.ts    From dgraph-orm with MIT License 6 votes vote down vote up
public nodeFor<N extends Object, V extends Object>(nodeCls: Constructor<N>, data?: V & { uid?: string }, trackChanges: boolean = true): N {
    const uids = MetadataStorage.Instance.uids.get(nodeCls.name);
    if (!uids || uids.length === 0) {
      throw new Error('Node must have a property decorated with @Uid');
    }

    const nodeInstance = new nodeCls();
    set(nodeInstance, 'trackChanges', trackChanges)
    this.trackProperties(nodeInstance);
    this.trackPredicatesForFreshNode(nodeInstance);

    let id: string;
    if (data && data.uid) {
      id = data.uid;
      // Remove the field so we don't introduce extra fields to
      //  new created node instance when assigning data to it.
      delete data.uid;
    } else {
      id = uniqid();
      this.tempIDS.set(nodeInstance, id);
    }

    if (data) {
      // Mutate the original object so we trigger
      // a diff on the tracked properties.
      Object.assign(nodeInstance, data);
    }

    uids.forEach(m => ((nodeInstance as any)[m.args.propertyName] = id));
    return nodeInstance;
  }
Example #19
Source File: serverless-offline.ts    From nx-plugins with MIT License 5 votes vote down vote up
/**
 * Adds support to serverless-offline
 * @link https://www.npmjs.com/package/serverless-offline
 */
export function prepareOffline(serverless: Serverless.Instance, nx: NxFacade) {
  serverless.service.package.individually = false;
  set(serverless, 'service.custom.serverless-offline.location', nx.outputAbsolutePath);
}
Example #20
Source File: settings-config-spec.ts    From ui5-language-assistant with Apache License 2.0 5 votes vote down vote up
describe("settings configuration properties", () => {
  let packageJsonSettings: Record<string, Setting>;

  before(() => {
    // Get the settings from the package.json
    const packageJsonPath = require.resolve(
      "vscode-ui5-language-assistant/package.json"
    );
    const packageJsonContent = readJsonSync(packageJsonPath);
    packageJsonSettings =
      packageJsonContent.contributes.configuration.properties;
  });

  it("default setting values in package.json have the correct type", () => {
    forEach(packageJsonSettings, (value, key) => {
      expect(
        typeof value.default,
        `Setting ${key} default value type does not match the setting's defined type`
      ).to.equal(value.type);
    });
  });

  it("settings in package.json are in sync with the settings package", () => {
    const defaultSettingsFromPackageJson = parseSettings(packageJsonSettings);
    const defaultSettings = getDefaultSettings();
    expect(
      defaultSettingsFromPackageJson,
      "settings from package.json don't match the default settings in the language server"
    ).to.deep.equal({
      UI5LanguageAssistant: defaultSettings,
    });
  });

  it("enums in package.json are in sync with the settings package", () => {
    const pkgJsonSettingsWithEnum = pickBy(packageJsonSettings, (_) =>
      has(_, "enum")
    );
    forEach(pkgJsonSettingsWithEnum, (pkgJsonSetting, settingsKey) => {
      const settingsModulePropName = camelCase(
        settingsKey.replace(
          /UI5LanguageAssistant.(\w+)\.(\w+)/,
          "valid $1 $2 values"
        )
      );
      const settingsModulePropValue = keys(
        settingsModule[settingsModulePropName]
      );
      const pkgJsonPropValue = pkgJsonSetting.enum;
      expect(settingsModulePropValue).to.deep.equalInAnyOrder(pkgJsonPropValue);
    });
  });

  it("use the correct logging configuration property name", () => {
    expect(packageJsonSettings[LOGGING_LEVEL_CONFIG_PROP]).to.exist;
    expect(
      packageJsonSettings[LOGGING_LEVEL_CONFIG_PROP].description
    ).to.include("logging");
  });

  type Setting = {
    scope: string;
    type: string;
    default: unknown;
    description: string;
    enum?: string[];
  };

  function parseSettings(properties: Record<string, Setting>): unknown {
    const defaultSettings = {};
    forEach(properties, (value, key) => {
      set(defaultSettings, key, value.default);
    });
    return defaultSettings;
  }
});
Example #21
Source File: api.ts    From Adachi-BOT with MIT License 5 votes vote down vote up
export async function getAliasName(): Promise<any> {
	return new Promise( ( resolve ) => {
		fetch( __API.FETCH_ALIAS_SET )
			.then( async ( result: Response ) => {
				resolve( parse( await result.text() ).set );
			} );
	} );
}
Example #22
Source File: operation.ts    From openapi-mock-express-middleware with MIT License 5 votes vote down vote up
getParamsSchemas(): ParamsSchemas {
    const schemas: ParamsSchemas = {
      header: {
        type: 'object',
        required: [],
      },
      query: {
        type: 'object',
        additionalProperties: false,
        required: [],
      },
      path: {
        type: 'object',
        additionalProperties: false,
        required: [],
      },
    };

    let parameters: (OpenAPIV3.ReferenceObject | OpenAPIV3.ParameterObject)[] = [];

    if (this.parentParams) {
      parameters = [...this.parentParams];
    }

    const localParams = get(this.operation, ['parameters']);

    if (localParams) {
      parameters = [...parameters, ...localParams];
    }

    if (parameters) {
      parameters.forEach((parameter) => {
        if (
          parameter &&
          !isReferenceObject(parameter) &&
          (parameter.in === 'header' || parameter.in === 'query' || parameter.in === 'path') &&
          schemas[parameter.in]
        ) {
          const prevRequired: string[] = schemas[parameter.in].required || [];

          set(
            schemas,
            [
              parameter.in,
              'properties',
              parameter.in === 'header' ? parameter.name.toLowerCase() : parameter.name,
            ],
            parameter.schema
          );

          if (parameter.required) {
            set(
              schemas,
              [parameter.in, 'required'],
              [
                ...prevRequired,
                parameter.in === 'header' ? parameter.name.toLowerCase() : parameter.name,
              ]
            );
          }
        }
      });
    }

    return schemas;
  }
Example #23
Source File: table-facet.ts    From S2 with MIT License 5 votes vote down vote up
public constructor(cfg: SpreadSheetFacetCfg) {
    super(cfg);

    const s2 = this.spreadsheet;
    s2.on(S2Event.RANGE_SORT, (sortParams) => {
      let params = sortParams;
      // 兼容之前 sortParams 为对象的用法
      if (!Array.isArray(sortParams)) {
        params = [sortParams];
      }

      const currentParams = s2.dataCfg.sortParams || [];

      params = params.map((item: TableSortParam) => {
        const newItem = {
          ...item,
          // 兼容之前 sortKey 的用法
          sortFieldId: item.sortKey ?? item.sortFieldId,
        };

        const oldItem =
          currentParams.find((p) => p.sortFieldId === newItem.sortFieldId) ??
          {};
        return {
          ...oldItem,
          ...newItem,
        };
      });

      const oldConfigs = currentParams.filter((config) => {
        const newItem = params.find(
          (p) => p.sortFieldId === config.sortFieldId,
        );
        if (newItem) {
          return false;
        }
        return true;
      });

      set(s2.dataCfg, 'sortParams', [...oldConfigs, ...params]);
      s2.setDataCfg(s2.dataCfg);
      s2.render(true);
      s2.emit(
        S2Event.RANGE_SORTED,
        (s2.dataSet as TableDataSet).getDisplayDataSet(),
      );
    });

    s2.on(S2Event.RANGE_FILTER, (params) => {
      /** remove filter params on current key if passed an empty filterValues field */
      const unFilter =
        !params.filteredValues || params.filteredValues.length === 0;

      const oldConfig = s2.dataCfg.filterParams || [];
      // check whether filter condition already exists on column, if so, modify it instead.
      const oldIndex = oldConfig.findIndex(
        (item) => item.filterKey === params.filterKey,
      );

      if (oldIndex !== -1) {
        if (unFilter) {
          // remove filter params on current key if passed an empty filterValues field
          oldConfig.splice(oldIndex);
        } else {
          // if filter with same key already exists, replace it
          oldConfig[oldIndex] = params;
        }
      } else {
        oldConfig.push(params);
      }

      set(s2.dataCfg, 'filterParams', oldConfig);

      s2.render(true);
      s2.emit(
        S2Event.RANGE_FILTERED,
        (s2.dataSet as TableDataSet).getDisplayDataSet(),
      );
    });
  }
Example #24
Source File: MjmlBlock.tsx    From easy-email with MIT License 5 votes vote down vote up
export default function MjmlBlock<T extends IBlockData>({
  value,
  type,
  attributes,
  children,
}: MjmlBlockProps<T>) {
  const block = BlockManager.getBlockByType(type);
  if (!block) {
    throw new Error(`Can no find ${type}`);
  }

  const mergeValue = useMemo((): undefined | {} => {
    if (typeof children === 'string') {
      if (!value) {
        return {
          content: children,
        };
      } else {
        set(value, 'content', children);
        return value;
      }
    }

    return value;
  }, [children, value]);

  const getChild = (child: any) => {
    if (!child) return null;
    if (isValidBlockData(child)) return child;
    if (isValidElement(child)) return parseReactBlockToBlockData(child);
    return child;
  };

  const getChildren = () => {
    if (Array.isArray(children)) {
      return children.map(getChild).filter(Boolean);
    }

    if (isValidBlockData(children)) {
      return [children];
    }

    if (typeof children === 'string') return [];
    return React.Children.map(children, getChild);
  };

  const instance = block.create({
    data: {
      value: mergeValue,
    },
    attributes,
    children: getChildren() || [],
  });

  return <>{JSON.stringify(instance)}</>;
}
Example #25
Source File: CaaSMapper.ts    From fsxa-api with Apache License 2.0 5 votes vote down vote up
/**
   * This method will create a filter for all referenced items that are registered inside of the referencedItems
   * and fetch them in a single CaaS-Request. If remoteProjectId is set, referenced Items from the remoteProject are fetched
   * After a successful fetch all references in the json structure will be replaced with the fetched and mapped item
   */
  async resolveReferencesPerProject<T extends {}>(
    data: T,
    remoteProjectId?: string,
    filterContext?: unknown
  ): Promise<T> {
    const referencedItems = remoteProjectId
      ? this._remoteReferences[remoteProjectId]
      : this._referencedItems

    const remoteProjectKey = Object.keys(this.api.remotes || {}).find((key) => {
      return key === remoteProjectId
    })
    const locale =
      remoteProjectKey && this.api.remotes ? this.api.remotes[remoteProjectKey].locale : this.locale

    const ids = Object.keys(referencedItems)
    const idChunks = chunk(ids, REFERENCED_ITEMS_CHUNK_SIZE)
    if (ids?.length > 0) {
      const response = await Promise.all(
        idChunks.map((ids) =>
          this.api.fetchByFilter({
            filters: [
              {
                operator: ComparisonQueryOperatorEnum.IN,
                value: ids,
                field: 'identifier',
              },
            ],
            locale,
            pagesize: REFERENCED_ITEMS_CHUNK_SIZE,
            remoteProject: remoteProjectId,
            filterContext,
          })
        )
      )
      const fetchedItems = response.map(({ items }) => items).flat()
      ids.forEach((id) =>
        referencedItems[id].forEach((path) =>
          set(
            data,
            path,
            fetchedItems.find((data) => {
              const hasId = typeof data === 'object' && 'id' in (data as object)
              if (hasId) {
                return (data as { id: string }).id === id
              }
            })
          )
        )
      )
    }
    return data
  }
Example #26
Source File: index.tsx    From next-basics with GNU General Public License v3.0 5 votes vote down vote up
private initData(mutableProps: { modalTitle: string }): void {
    const pickFields = pick(this.fields, ["modalTitle"]);
    forEach(pickFields, (fieldKey, field: string) => {
      set(mutableProps, field, get(this.dataSource, fieldKey));
    });
  }
Example #27
Source File: createProviderClass.ts    From next-core with GNU General Public License v3.0 5 votes vote down vote up
export function createProviderClass<T extends unknown[], U>(
  api: (...args: T) => U
): { new (): ProviderElement<T, U> } {
  return class extends HTMLElement {
    get $$typeof(): string {
      return "provider";
    }

    static get _dev_only_definedProperties(): string[] {
      return ["args"];
    }

    args = [] as T;

    updateArgs(event: CustomEvent<Record<string, unknown>>): void {
      if (!(event instanceof CustomEvent)) {
        // eslint-disable-next-line no-console
        console.warn(
          "`updateArgs/updateArgsAndExecute` is designed to receive an CustomEvent, if not, please use `setArgs/setArgsAndExecute` instead."
        );
      }
      this.setArgs(event.detail);
    }

    updateArgsAndExecute(
      event: CustomEvent<Record<string, unknown>>
    ): Promise<U> {
      this.updateArgs(event);
      return this.execute();
    }

    setArgs(patch: Record<string, unknown>): void {
      for (const [path, value] of Object.entries(patch)) {
        set(this.args, path, value);
      }
    }

    setArgsAndExecute(patch: Record<string, unknown>): Promise<U> {
      this.setArgs(patch);
      return this.execute();
    }

    execute(): Promise<U> {
      return this.executeWithArgs(...this.args);
    }

    async saveAs(filename: string, ...args: T): Promise<void> {
      const blob = await api(...args);
      saveAs((blob as unknown) as Blob, filename);
    }

    async executeWithArgs(...args: T): Promise<U> {
      try {
        const result = await api(...args);
        this.dispatchEvent(
          new CustomEvent("response.success", {
            detail: result,
          })
        );
        return result;
      } catch (error) {
        this.dispatchEvent(
          new CustomEvent("response.error", {
            detail: error,
          })
        );
        return Promise.reject(error);
      }
    }

    resolve(...args: T): U {
      return api(...args);
    }
  };
}
Example #28
Source File: FormDataItem.tsx    From yugong with MIT License 5 votes vote down vote up
FormDataItem: React.FC<Props> = ({ onMinus, value, order }) => {
  const { onChangeRunningData, runningData, dataPath } = useContext(FormModuleContext)
  const onChange = useCallback(
    (data: {[keys: string]: any}) => {
      if (!runningData) return;
      const operateData = cloneDeep(runningData)
      const itemPath = `${dataPath}[${order - 1}]`;
      const itemData = get(operateData, itemPath);
      const newItemData = {
        ...itemData,
        ...data
      }
      set(operateData, itemPath, newItemData);
      onChangeRunningData?.(operateData)
    },
    [dataPath, onChangeRunningData, order, runningData],
  )
  
  const [showOptions, setShowOptions] = useState(false);
  const disabled = false;
  return (
    <div className={s.root}>
      <LineItem
        label={
          <div className={s.dragwrap}>
            <span className={s.drag}>
              <DragHandle />
            </span>
            第{order}项
          </div>
        }
      >
        <Input
          disabled={disabled}
          className={s.inp}
          onChange={(e) => onChange({title: e.target.value})}
          value={value.title}
          placeholder="名称"
        />
        <Input name="rowMap"
          disabled={disabled}
          className={classNames(s.inp, s.nbl, s.nbrad)}
          onChange={(e) => onChange({dataIndex: e.target.value})}
          value={value?.dataIndex}
          placeholder="字段(必填)"
          />
        <Button
          disabled={disabled}
          className={classNames(s.btn, s.nbl, s.nbr)}
          icon={showOptions ? <CaretDownOutlined /> : <CaretRightOutlined />}
          onClick={() => setShowOptions(!showOptions)}
        />
        <Button
          disabled={disabled}
          className={s.btn}
          icon={<MinusOutlined />}
          onClick={() => onMinus?.()}
        />
      </LineItem>
      <div style={{ display: showOptions ? 'block' : 'none' }}>
        <LineItem label="">
          <SubItem value={value} onChange={onChange} />
        </LineItem>
      </div>
    </div>
  );
}
Example #29
Source File: global-space.ts    From erda-ui with GNU Affero General Public License v3.0 5 votes vote down vote up
setGlobal = (key: string, value: any) => {
  set(globalSpace, key, value);
}