lodash#isObject TypeScript Examples

The following examples show how to use lodash#isObject. 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 ts-di-starter with MIT License 7 votes vote down vote up
/**
 * Assert properties of object
 *
 * @param {{}} obj
 * @param {string[]} properties
 * @returns {void}
 */
export function assertProperties(obj: any, properties: string[]): void {
  if (!isObject(obj)) throw new Error('not object');
  if (properties.length === 0) throw new Error('no properties provided');

  properties.map((prop) => assert(!isNil(obj[prop]), `${prop} not found on obj`));
}
Example #2
Source File: helpers.ts    From leda with MIT License 6 votes vote down vote up
getSuggestionFromValue = ({
  data,
  value,
  textField,
}: {
  data: Suggestion[],
  value: string | DataObject,
  textField?: string,
}): Suggestion => {
  const isEveryIsObject = every(data, isObject);

  const isValidTextField = isString(textField) && textField.length > 0;

  if (isEveryIsObject && !isValidTextField) {
    // todo: handle textField error
  }

  const suggestion: Suggestion | undefined = isEveryIsObject
    ? (data as DataObject[]).find((el: DataObject): boolean => (el[textField as string] === value))
    : (data as string[]).find((el: string): boolean => (el === value));

  return suggestion || null;
}
Example #3
Source File: api.ts    From brick-design with MIT License 6 votes vote down vote up
export function isEffectiveApi(
  api?: Api,
  data?: any,
  initFetch?: boolean,
  initFetchOn?: string,
): api is Api {
  if (!api) {
    return false;
  }
  if (initFetch === false) {
    return false;
  }
  if (initFetchOn && data && !evalExpression(initFetchOn, data)) {
    return false;
  }
  if (typeof api === 'string' && api.length) {
    return true;
  } else if (isObject(api) && (api as ApiObject).url) {
    if (
      (api as ApiObject).sendOn &&
      data &&
      !evalExpression((api as ApiObject).sendOn as string, data)
    ) {
      return false;
    }
    return true;
  }
  return false;
}
Example #4
Source File: Picker.tsx    From react-native-jigsaw with MIT License 6 votes vote down vote up
function normalizeOptions(options: PickerProps["options"]): PickerOption[] {
  if (options.length === 0) {
    return [];
  }

  if (typeof options[0] === ("string" || "number")) {
    return (options as string[]).map((option) => ({
      label: String(option),
      value: String(option),
    }));
  }

  if (
    isObject(options[0]) &&
    options[0].value !== null &&
    options[0].label !== null
  ) {
    return (options as PickerOption[]).map((option) => {
      return {
        label: String(option.label),
        value: String(option.value),
      };
    });
  }

  throw new Error(
    'Picker options must be either an array of strings or array of { "label": string; "value": string; } objects.'
  );
}
Example #5
Source File: index.tsx    From next-basics with GNU General Public License v3.0 6 votes vote down vote up
/**
   * @params [{ detail: { fileName: string; data: object | string; } }]
   * @description 导出数据
   */
  @method()
  export(event: CustomEvent): void {
    const fileName = event.detail?.fileName ?? this.fileName;
    const data = event.detail?.data ?? this.data;

    if (this.isConnected) {
      const dataString = isObject(data) ? JSON.stringify(data) : data;

      try {
        const link = document.createElement("a");
        const blob = new Blob([dataString], {
          type: "text/plain",
        });
        link.download = fileName || "undefined";
        link.href = URL.createObjectURL(blob);
        link.click();
        this.success.emit();
      } catch (e) {
        handleHttpError(e);
        this.failed.emit();
      }
    }
  }
Example #6
Source File: fixture.ts    From ts-di-starter with MIT License 6 votes vote down vote up
checkFixture = (fixture, expected): void => {
  const { expressMiddleware, expressControllers } = fixture;

  const updateExpectationsFromFixture = (fixtureObj, expectedObj) => {
    return Object.keys(fixtureObj).reduce((_expectedObj, key) => {
      const isStub = has(fixtureObj[key], 'callsFake');

      if (isStub) {
        fixtureObj[key] = fixtureObj[key].callCount;
      }

      if (!has(_expectedObj, key)) {
        if (isStub) {
          _expectedObj[key] = 0;
        } else {
          _expectedObj[key] = {};
        }
      }

      if (isObject(fixtureObj[key])) {
        updateExpectationsFromFixture(fixtureObj[key], _expectedObj[key]);
      }

      return _expectedObj;
    }, expectedObj);
  };

  updateExpectationsFromFixture(expressControllers, expected.controllers);
  updateExpectationsFromFixture(expressMiddleware, expected.middleware);

  expect(expressControllers).to.deep.equal(expected.controllers);
  expect(expressMiddleware).to.deep.equal(expected.middleware);
}
Example #7
Source File: AwsConstruct.ts    From lift with MIT License 6 votes vote down vote up
private applyExtensions(extensions: Record<string, unknown>) {
        const availableExtensions = this.extend();
        if (isEmpty(extensions) || isEmpty(availableExtensions)) {
            return;
        }
        Object.entries(extensions).forEach(([extensionKey, extensionObject]) => {
            if (!Object.keys(availableExtensions).includes(extensionKey)) {
                throw new ServerlessError(
                    `There is no extension '${extensionKey}' available on this construct. Available extensions are: ${Object.keys(
                        availableExtensions
                    ).join(", ")}.`,
                    "LIFT_UNKNOWN_EXTENSION"
                );
            }
            if (isObject(extensionObject)) {
                paths(extensionObject)
                    .filter((path) => !isEmpty(path))
                    .map((path) => {
                        return path.join(".");
                    })
                    .filter((path) => !isObject(get(extensionObject, path)))
                    .map((path) => {
                        availableExtensions[extensionKey].addOverride(path, get(extensionObject, path));
                    });
            }
        });
    }
Example #8
Source File: SearchFields.tsx    From leda with MIT License 6 votes vote down vote up
customItemRender: L.AutoCompleteTypes.AutoCompleteProps['itemRender'] = (renderData) => {
  const { componentProps: { item }, elementProps } = renderData;

  if (!isObject(item)) return null;

  return (
    <L.Li {...elementProps}>
      <L.Small>
        {item.city}
        <br />
        <L.Span _txtGray>
          country
          {' '}
          {item.country}
          <br />
          code
          {' '}
          {item.code}
        </L.Span>
      </L.Small>
    </L.Li>
  );
}
Example #9
Source File: functions.ts    From strapi-plugin-comments with MIT License 6 votes vote down vote up
buildNestedStructure = (
  entities: Array<Comment>,
  id: Id | null = null,
  field: string = "threadOf",
  dropBlockedThreads = false,
  blockNestedThreads = false
): Array<Comment> =>
  entities
    .filter((entity: Comment) => {
      // mongo by default not return `null` for empty data
      const entityField: any = get(entity, field);
      if (entityField === null && id === null) {
        return true;
      }
      let data = entityField;
      if (data && typeof id === "string") {
        data = data.toString();
      }
      return (
        (data && data === id) ||
        (isObject(entityField) && (entityField as any).id === id)
      );
    })
    .map((entity: Comment) => ({
      ...entity,
      [field]: undefined,
      related: undefined,
      blockedThread: blockNestedThreads || entity.blockedThread,
      children:
        entity.blockedThread && dropBlockedThreads
          ? []
          : buildNestedStructure(
              entities,
              entity.id,
              field,
              dropBlockedThreads,
              entity.blockedThread
            ),
    }))
Example #10
Source File: helpers.ts    From leda with MIT License 6 votes vote down vote up
getSuggestionValue = (suggestion: Suggestion, textField?: string): string => {
  if (suggestion === null) {
    return '';
  }

  if (isString(suggestion)) {
    return suggestion;
  }

  if (isObject(suggestion) && textField) {
    return suggestion[textField];
  }

  return suggestion.toString();
}
Example #11
Source File: list-sources.ts    From relate with GNU General Public License v3.0 6 votes vote down vote up
fetchOfficialPluginSources = async (): Promise<List<IDbmsPluginSource>> => {
    const cachedSourcesFile = path.join(envPaths().cache, PLUGIN_SOURCES_DIR_NAME, DEFAULT_PLUGIN_SOURCES_FILE);
    const rawSourcesMap = await requestJson(NEO4J_PLUGIN_SOURCES_URL).catch(() => null);

    if (!rawSourcesMap || !isObject(rawSourcesMap)) {
        if (await fse.pathExists(cachedSourcesFile)) {
            return List.from<IDbmsPluginSource>(await fse.readJSON(cachedSourcesFile)).mapEach(
                (source) => new DbmsPluginSourceModel(source),
            );
        }

        return List.from([]);
    }

    const sources = List.from(Object.entries(rawSourcesMap)).mapEach(([name, source]) => {
        return new DbmsPluginSourceModel({
            ...source,
            name,
            isOfficial: true,
        });
    });

    await fse.ensureFile(cachedSourcesFile);
    await fse.writeJSON(cachedSourcesFile, sources);

    return sources;
}
Example #12
Source File: fixLocales.ts    From nextclade with MIT License 6 votes vote down vote up
export function readJson(filepath: string) {
  const content = fs.readFileSync(filepath, 'utf8')
  const jsonDangerous = JSON.parse(content) as unknown

  if (!isObject(jsonDangerous)) {
    console.warn(`'${filepath}':\nNot a valid JSON\n`)
  }

  const json = jsonDangerous as Record<string, string>

  return { content, json }
}
Example #13
Source File: extract-error.ts    From querybook with Apache License 2.0 6 votes vote down vote up
export function extractFormikError(rootErrors: Record<string, any>): string[] {
    const errorDescriptions = [];

    const helper = (errors: any, path: string = '') => {
        if (isString(errors)) {
            errorDescriptions.push(`${path}: ${errors}`);
            return;
        }
        if (isObject(errors) || isArray(errors)) {
            // It can be an array, object, or string
            for (const [parentName, childErrors] of Object.entries(errors)) {
                helper(
                    childErrors,
                    path ? path + '.' + parentName : parentName
                );
            }
        }
    };

    helper(rootErrors);

    return errorDescriptions;
}
Example #14
Source File: object-settings.ts    From prisma-nestjs-graphql with MIT License 6 votes vote down vote up
getObjectTypeArguments(options: Record<string, any>): string[] {
    const objectTypeOptions = merge({}, options);
    const resultArguments: any[] = [objectTypeOptions];
    const objectType = this.find(s => s.kind === 'ObjectType');
    if (objectType && isObject(objectType.arguments)) {
      const name = (objectType.arguments as PlainObject).name;
      merge(objectTypeOptions, omit(objectType.arguments, 'name'));
      if (name) {
        resultArguments.unshift(name);
      }
    }
    return resultArguments.map(x => JSON5.stringify(x));
  }
Example #15
Source File: primary-key.ts    From dyngoose with ISC License 6 votes vote down vote up
public async get(hash: HashKeyType | T | QueryFilters<T>, range?: RangeKeyType | PrimaryKeyGetInput, input?: PrimaryKeyGetInput): Promise<T | undefined> {
    let record: T

    if (isDyngooseTableInstance(hash)) {
      record = hash
    } else if (isObject(hash) && !isKeyValue(hash)) {
      record = this.fromKey(hash)
    } else if (hash != null && (range == null || isKeyValue(range))) {
      record = this.fromKey(hash as HashKeyType, range as RangeKeyType)
    } else {
      throw new QueryError('PrimaryKey.get called with unknown arguments')
    }

    const getGetInput: Partial<PrimaryKeyGetGetItemInput> = input == null ? ((range == null || isKeyValue(range)) ? {} : range as PrimaryKeyGetInput) : input
    getGetInput.key = record.getDynamoKey()
    const getItemInput = this.getGetInput(getGetInput as PrimaryKeyGetGetItemInput)
    const hasProjection = getItemInput.ProjectionExpression == null
    let dynamoRecord: DynamoDB.GetItemOutput

    try {
      dynamoRecord = await this.table.schema.dynamo.getItem(getItemInput).promise()
    } catch (ex) {
      throw new HelpfulError(ex, this.table, getItemInput)
    }

    if (dynamoRecord.Item != null) {
      return this.table.fromDynamo(dynamoRecord.Item, !hasProjection)
    }
  }
Example #16
Source File: index.ts    From S2 with MIT License 6 votes vote down vote up
processValueInCol = (
  viewMeta: ViewMeta,
  sheetInstance: SpreadSheet,
  isFormat?: boolean,
): string => {
  if (!viewMeta) {
    // If the meta equals null, replacing it with blank line.
    return '';
  }
  const { fieldValue, valueField, data } = viewMeta;

  if (isObject(fieldValue)) {
    return processObjectValueInCol(fieldValue);
  }

  if (!isFormat) {
    return `${fieldValue}`;
  }
  const mainFormatter = sheetInstance.dataSet.getFieldFormatter(valueField);
  return mainFormatter(fieldValue, data);
}
Example #17
Source File: JsonToMjml.ts    From easy-email with MIT License 6 votes vote down vote up
export function generaMjmlMetaData(data: IPage) {
  const values = data.data.value;
  const attributes = [
    'content-background-color',
    'text-color',
    'font-family',
    'font-size',
    'line-height',
    'font-weight',
    'user-style',
    'responsive',
  ];

  return `
    <mj-html-attributes>
      ${attributes
      .filter((key) => values[key as keyof typeof values] !== undefined)
      .map((key) => {
        const attKey = key as keyof typeof values;
        const isMultipleAttributes = isObject(values[attKey]);
        const value = isMultipleAttributes
          ? Object.keys(values[attKey]!)
            .map(
              (childKey) => {
                const childValue = (values[attKey] as any)[childKey];

                return `${childKey}="${isString(childValue) ? childValue.replace(/"/gm, '') : childValue}"`;
              }

            )
            .join(' ')
          : `${key}="${values[attKey]}"`;
        return `<mj-html-attribute class="easy-email" multiple-attributes="${isMultipleAttributes}" attribute-name="${key}" ${value}></mj-html-attribute>`;
      })
      .join('\n')}

    </mj-html-attributes>
  `;
}
Example #18
Source File: index.tsx    From strapi-plugin-comments with MIT License 6 votes vote down vote up
UserAvatar = ({ avatar, name }) => {
  if (avatar) {
    let image = avatar;
    if (isObject(avatar)) {
      image = avatar?.formats?.thumbnail.url || avatar.url;
    }
    return <Avatar src={image} alt={name} />;
  }
  return <Initials>{renderInitials(name)}</Initials>;
}
Example #19
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 #20
Source File: useProviderArgs.ts    From next-core with GNU General Public License v3.0 5 votes vote down vote up
export default function useProviderArgs(
  providerOrParamsOrGlobalOptions?: string | IncomingOptions,
  gloabalOptionsOrDeps?: IncomingOptions | any[],
  deps?: any[]
): UseProviderArgsReturn {
  const provider = useMemo(() => {
    if (typeof providerOrParamsOrGlobalOptions === "string") {
      return providerOrParamsOrGlobalOptions;
    }

    return useProviderArgsDefaults.provider;
  }, [providerOrParamsOrGlobalOptions, gloabalOptionsOrDeps]);

  const options = useMemo(() => {
    let localOptions = {};
    if (isObject(providerOrParamsOrGlobalOptions)) {
      localOptions = providerOrParamsOrGlobalOptions;
    } else if (isObject(gloabalOptionsOrDeps)) {
      localOptions = gloabalOptionsOrDeps;
    }
    return {
      ...defaults,
      ...localOptions,
    } as IncomingOptions;
  }, [providerOrParamsOrGlobalOptions, gloabalOptionsOrDeps]);

  const requestInit = useMemo((): {
    args: unknown;
    options?: HttpOptions;
  } => {
    const customOptionKeys = [
      ...Object.keys(useProviderArgsDefaults),
      ...Object.keys(useProviderArgsDefaults.customOptions),
    ] as Array<UseProviderOptionArgsDefaults>;

    const { args = null, ...restOptions } = (
      Object.keys(options) as any
    ).reduce((acc: Record<string, any>, key: UseProviderOptionArgsDefaults) => {
      if (!customOptionKeys.includes(key)) acc[key] = (options as never)[key];
      return acc;
    }, {} as Record<string, any>);

    return { options: { ...restOptions }, args };
  }, [options]);

  const dependencies = useMemo((): any[] | undefined => {
    if (Array.isArray(gloabalOptionsOrDeps)) return gloabalOptionsOrDeps;
    if (Array.isArray(deps)) return deps;
    return defaults.dependencies;
  }, [gloabalOptionsOrDeps, deps]);

  const loading = options.loading || Array.isArray(dependencies);

  const customOptions = useMemo(() => {
    const customOptionKeys = Object.keys(
      useProviderArgsDefaults.customOptions
    ) as (keyof UseProviderCustomOptions)[];

    const customOptions = customOptionKeys.reduce((opts, key) => {
      (opts as any)[key] = options[key];
      return opts;
    }, {} as UseProviderCustomOptions);

    return { ...customOptions, loading };
  }, [options]);

  return {
    provider,
    customOptions,
    requestInit,
    dependencies,
  };
}
Example #21
Source File: helpers.ts    From leda with MIT License 5 votes vote down vote up
validate = (formName: string | undefined, fieldName?: string, externalValue?: unknown): boolean => {
  const forms: Form[] = getForms();

  const currentForm = forms.find((form) => form.name === formName);

  if (!currentForm) return false;

  if (!fieldName) {
    return currentForm.fields.map((field) => validate(formName, field.name)).every((result) => result);
  }

  const currentField = getField(formName, fieldName);

  if (!currentField) return false;

  const invalidMessages: string[] = [];

  let isValid = true;

  const value = externalValue === undefined ? currentField.value : externalValue;

  const isFilled = checkIsFilled(value);

  // не проверяем валидаторы, если поле обязательное и не заполнено
  if (currentField.isRequired && !isFilled) {
    isValid = false;

    if (currentField.requiredMessage) invalidMessages.push(currentField.requiredMessage);
  } else if (isFilled) {
    currentField.validators.forEach((validator) => {
      // если валидатор имеет вид { validator, invalidMessage } - извлекаем сообщение об ошибке
      if (isObject(validator) && 'validator' in validator) {
        const result = validator.validator(value);

        if (!result) {
          if (validator.invalidMessage) invalidMessages.push(validator.invalidMessage);

          isValid = false;
        }
      }
    });
  }

  const newForms = [...forms.map((form: Form): Form => {
    if (form.name !== formName) return form;

    const newFields = currentForm.fields.map((field) => {
      if (field.name !== fieldName) return field;

      return {
        ...field, isValid, invalidMessages, value,
      };
    });

    return { name: formName, fields: newFields };
  })];

  setForms(newForms);

  currentField.setIsValid(isValid);

  currentField.setMessages(invalidMessages);

  return isValid;
}
Example #22
Source File: helper.ts    From brick-design with MIT License 5 votes vote down vote up
export function isObjectShallowModified(
  prev: any,
  next: any,
  strictMode = true,
  ignoreUndefined = false,
): boolean {
  if (Array.isArray(prev) && Array.isArray(next)) {
    return prev.length !== next.length
      ? true
      : prev.some((prev, index) =>
          isObjectShallowModified(
            prev,
            next[index],
            strictMode,
            ignoreUndefined,
          ),
        );
  } else if (
    null == prev ||
    null == next ||
    !isObject(prev) ||
    !isObject(next)
  ) {
    return strictMode ? prev !== next : prev != next;
  }

  if (ignoreUndefined) {
    prev = rmUndefined(prev);
    next = rmUndefined(next);
  }

  const keys = Object.keys(prev);
  const nextKeys = Object.keys(next);
  if (
    keys.length !== nextKeys.length ||
    keys.sort().join(',') !== nextKeys.sort().join(',')
  ) {
    return true;
  }
  for (let i: number = keys.length - 1; i >= 0; i--) {
    const key = keys[i];
    if (
      strictMode
        ? next[key] !== prev[key]
        : isObjectShallowModified(next[key], prev[key], false, ignoreUndefined)
    ) {
      return true;
    }
  }
  return false;
}
Example #23
Source File: helpers.ts    From leda with MIT License 5 votes vote down vote up
getText = (suggestion?: string | number | SomeObject | null, textField?: string): string => {
  if (!suggestion) return '';

  if (!textField) return suggestion.toString();

  return isObject(suggestion) ? (suggestion[textField] as string | number | undefined || '').toString() : suggestion.toString();
}
Example #24
Source File: Items.tsx    From yforms with MIT License 5 votes vote down vote up
Items = (props: YFormItemsProps) => {
  const formProps = useContext(YForm.YFormContext);
  const { getScene } = formProps;
  const itemsProps = useContext(YForm.YFormItemsContext);

  const mergeProps = merge(
    {},
    pick(formProps, ['scenes', 'offset', 'disabled']),
    itemsProps,
    props,
  );
  const { scenes: thisScenes } = mergeProps;
  const _defaultData = { formProps, itemsProps: props };
  mapKeys(thisScenes, (value: boolean, key: string) => {
    if (value && getScene[key] && getScene[key].items) {
      const data = getScene[key].items(_defaultData);
      if (data) {
        _defaultData.itemsProps = { ..._defaultData.itemsProps, ...data.itemsProps };
      }
    }
  });

  const _props = mergeWithDom({}, mergeProps, _defaultData.itemsProps, {
    offset: (props.offset || 0) + (itemsProps.offset || 0),
  });

  const { isShow, className, style, children, noStyle, shouldUpdate } = _props;

  const itemList = [];
  const eachItem = (
    list: YFormItemProps['children'][] | React.ReactFragment[],
    pIndex?: number,
  ) => {
    if (isArray(list)) {
      forEach(list, (item, index) => {
        // 如果还是是数组就回调该方法
        // if (isArray(item)) return eachItem(item, index);
        if (isArray(item)) {
          return eachItem(item, index);
        }
        const _index = pIndex ? `${pIndex}_${index}` : index;
        // 如果是 dom 直接渲染
        if (isValidElement(item)) {
          return itemList.push(item);
        }
        // 如果不是对象直接渲染
        if (!isObject(item)) {
          return itemList.push(item);
        }
        return itemList.push(<YForm.Item {...item} key={_index} />);
      });
    }
  };
  // 遍历元素
  eachItem(isArray(children) ? children : [children]);
  const child = (
    <YForm.YFormItemsContext.Provider value={pick(_props, ['scenes', 'offset', 'disabled'])}>
      {itemList}
    </YForm.YFormItemsContext.Provider>
  );
  const dom = noStyle ? (
    child
  ) : (
    <div className={classNames('yform-items', className)} style={style}>
      {child}
    </div>
  );

  if (typeof isShow === 'function') {
    return (
      <Form.Item noStyle shouldUpdate={shouldUpdate}>
        {(form) => isShow(form.getFieldsValue(true)) && dom}
      </Form.Item>
    );
  }
  if ('isShow' in props && !props.isShow) return null;

  return dom;
}
Example #25
Source File: data-item-type-checker.ts    From S2 with MIT License 5 votes vote down vote up
isMultiDataItem = (value: DataItem): value is MultiData => {
  return isObject(value) && 'values' in value;
}
Example #26
Source File: handlers.ts    From leda with MIT License 5 votes vote down vote up
suggestionClickHandlerCreator = ({
  data,
  isValueControlled,
  name,
  onChange,
  setIsFocused,
  setStateValue,
  setHighlightedSuggestion,
  textField,
}: {
  data: Suggestion[],
  textField?: string,
  name?: string,
  onChange: (event: ChangeEvent) => void,
  isValueControlled: boolean,
  setStateValue: SetState<string>,
  setIsFocused: SetState<boolean>,
  setHighlightedSuggestion: SetState<Suggestion>,
}): CustomEventHandler<React.MouseEvent<HTMLElement> & SuggestionTarget> => (event) => {
  if (isObject(event.target.value) && textField === undefined) {
    // todo handle error
    return;
  }

  const value = isObject(event.target.value)
    ? event.target.value[textField as string] as string
    : event.target.value.toString();

  const suggestion = isObject(event.target.value)
    ? event.target.value as DataObject
    : getSuggestionFromValue({ data, value, textField });

  const customEvent: ChangeEvent = {
    ...event,
    component: {
      method: CHANGE_METHOD.click,
      name,
      suggestion,
      value,
    },
  };

  setHighlightedSuggestion(suggestion);

  if (isFunction(onChange)) onChange(customEvent);
  if (!isValueControlled) setStateValue(value);
  setIsFocused(false);
}
Example #27
Source File: primary-key.ts    From dyngoose with ISC License 5 votes vote down vote up
public fromKey(hash: QueryFilters<T> | HashKeyType, range?: RangeKeyType): T {
    // if the hash was passed a query filters, then extract the hash and range
    if (isObject(hash) && !isDate(hash)) {
      const filters = hash
      if (!has(filters, this.metadata.hash.propertyName)) {
        throw new QueryError('Cannot perform .get() on a PrimaryKey without specifying a hash key value')
      } else if (this.metadata.range != null && !has(filters, this.metadata.range.propertyName)) {
        throw new QueryError('Cannot perform .get() on a PrimaryKey with a range key without specifying a range value')
      } else if (Object.keys(filters).length > 2) {
        throw new QueryError('Cannot perform a .get() on a PrimaryKey with additional filters, use .query() instead')
      }

      hash = get(filters, this.metadata.hash.propertyName)

      if (isArray(hash)) {
        if (hash[0] === '=') {
          hash = hash[1]
        } else {
          throw new QueryError('DynamoDB only supports using equal operator for the HASH key')
        }
      }

      if (this.metadata.range != null) {
        range = get(filters, this.metadata.range.propertyName)

        if (isArray(hash)) {
          if (hash[0] === '=') {
            hash = hash[1]
          } else {
            throw new QueryError('DynamoDB only supports using equal operator for the RANGE key on GetItem operations')
          }
        }
      }
    }

    if (this.metadata.range != null && range == null) {
      throw new QueryError('Cannot use primaryKey.get without a range key value')
    }

    const keyMap: DynamoDB.AttributeMap = {
      [this.metadata.hash.name]: this.metadata.hash.toDynamoAssert(hash),
    }

    if (this.metadata.range != null) {
      keyMap[this.metadata.range.name] = this.metadata.range.toDynamoAssert(range)
    }

    return this.table.fromDynamo(keyMap, false)
  }
Example #28
Source File: AnchorHeader.tsx    From hub with Apache License 2.0 5 votes vote down vote up
AnchorHeader: ElementType = (props: Props) => {
  let value = props.title;
  if (isUndefined(value) && props.children && props.children.length > 0) {
    const allContentValues = props.children.map((n: any) => {
      if (isString(n)) {
        return [n];
      } else if (isObject(n)) {
        return String((n as any).props.children);
      } else {
        return '';
      }
    });
    value = allContentValues.join('');
  }

  if (isUndefined(value)) return null;

  const Tag = `h${props.level}` as 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6';
  const anchor = props.anchorName || getAnchorValue(value);

  return (
    <span className={styles.header}>
      <Tag className={`position-relative anchorHeader ${styles.headingWrapper} ${props.className}`}>
        <div data-testid="anchor" className={`position-absolute ${styles.headerAnchor}`} id={anchor} />
        <a
          href={`${history.location.pathname}#${anchor}`}
          onClick={(e: ReactMouseEvent<HTMLAnchorElement, MouseEvent>) => {
            e.preventDefault();
            e.stopPropagation();
            props.scrollIntoView(`#${anchor}`);
          }}
          role="button"
          className={`text-reset text-center d-none d-md-block lh-1 float-start ${styles.headingLink}`}
          aria-label={value}
        >
          <GoLink />
        </a>
        {props.title || props.children}
      </Tag>
    </span>
  );
}
Example #29
Source File: Skeleton.tsx    From gio-design with Apache License 2.0 5 votes vote down vote up
InnerSkeleton = React.forwardRef<HTMLDivElement, SkeletonProps>((props, ref) => {
  const {
    prefixCls: customizePrefixCls,
    delay = 0,
    loading = true,
    children,
    active = true,
    className,
    paragraph,
    title,
    ...otherProps
  } = props;
  const prefixCls = usePrefixCls('skeleton', customizePrefixCls);
  const shouldLoading = useDebounceLoading(loading, delay);

  const renderSkeletonAvatar = () => {
    const { avatar = false } = props;
    if (!avatar) {
      return null;
    }
    const size = 'large';
    return (
      <div className={`${prefixCls}-header`}>
        <Avatar className={`${prefixCls}-avatar`} size={size}>
          {' '}
        </Avatar>
      </div>
    );
  };
  const renderSkeletonParagraph = () => {
    if (!paragraph && !title) {
      return null;
    }
    const { row, width } = isObject(paragraph) ? paragraph : { row: 3, width: '100%' };

    return (
      <div className={`${prefixCls}-content`}>
        {title && <div className={`${prefixCls}-title`} />}
        {paragraph && (
          <div className={`${prefixCls}-paragraph`}>
            {Array(row)
              .fill(0)
              .map((_, index) => (
                // eslint-disable-next-line react/no-array-index-key
                <p key={index} style={{ width: isArray(width) ? width[index] : width }} />
              ))}
          </div>
        )}
      </div>
    );
  };

  return shouldLoading ? (
    <div
      className={classNames(prefixCls, className, {
        [`${prefixCls}-active`]: active,
      })}
      ref={ref}
      data-testid="skeleton"
      {...otherProps}
    >
      {renderSkeletonAvatar()}
      {renderSkeletonParagraph()}
    </div>
  ) : (
    <>{children}</>
  );
})