lodash#kebabCase TypeScript Examples

The following examples show how to use lodash#kebabCase. 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: parseReactBlockToBlockData.tsx    From easy-email with MIT License 6 votes vote down vote up
describe('Test parseXml', () => {
  const componentNames = Object.keys(componentsMap).filter(item => item !== 'MjmlBlock');
  it.each(componentNames)('$name is valid block', (componentName) => {


    const Com = componentsMap[componentName];
    const type = snakeCase(kebabCase(componentName)).toUpperCase();
    const block = BlockManager.getBlockByType(BasicType[type]);


    expect(parseReactBlockToBlockData(<Com />)).toEqual(block?.create());
  });
});
Example #2
Source File: TagFilter.tsx    From nyxo-website with MIT License 6 votes vote down vote up
TagFilter = () => {
  const data = useStaticQuery(graphql`
    query TagQuery {
      tags: allMarkdownRemark(
        filter: { fileAbsolutePath: { regex: "/content/blog/" } }
      ) {
        group(field: frontmatter___tags) {
          tag: fieldValue
          totalCount
        }
      }
    }
  `)
  const tags = data?.tags?.group
  const tagCount = 3
  return (
    <TagList>
      {tags?.slice(0, tagCount).map(({ tag, totalCount }: any) => {
        return (
          <TagLinkLI key={tag}>
            <TagLink data-count={totalCount} to={`/tags/${kebabCase(tag)}/`}>
              {tag}
            </TagLink>
          </TagLinkLI>
        )
      })}
      <TagLinkLI>
        <TagLinkMoreTags to={`/tags`}>All Tags</TagLinkMoreTags>
      </TagLinkLI>
    </TagList>
  )
}
Example #3
Source File: Tags.tsx    From nyxo-website with MIT License 6 votes vote down vote up
TagSection: FC<Props> = ({ tags, largeTags }) => {
  return (
    <>
      {tags?.map((tag = "tag") => (
        <Tag
          large={largeTags}
          key={`${kebabCase(tag as string)}`}
          to={`/tags/${kebabCase(tag as string)}`}>
          {tag}
        </Tag>
      ))}
    </>
  )
}
Example #4
Source File: index.ts    From vue3-ts-base with MIT License 6 votes vote down vote up
/**
 * @description 自动将 ./src/components/global 下的组件注册成为全局组件
 * @param {vue} app 当前应用实例
 * @returns {void} void
 */
export function registeGlobalComponent(
  app: ReturnType<typeof createApp>
): void {
  const files = require.context('./global', true, /\.(vue|ts)$/)
  files.keys().forEach((key) => {
    const config = files(key)
    const name = kebabCase(key.replace(/^\.\//, '').replace(/\.\w+$/, ''))
    app.component(name, config.default || config)
  })

  // 全局注册 iconfont
  app.component('IconFont', IconFont)
}
Example #5
Source File: helpers.ts    From leda with MIT License 6 votes vote down vote up
extractIdAndNamespace = (props: SvgProps): SvgProps & { id: string, namespace: string } => Object.keys(props).reduce((acc, attr) => {
  if (svgNamespacesDictionary.includes(attr)) {
    return { ...acc, namespace: attr };
  }

  if (!isFunction((props as { [x: string]: unknown})[attr]) && attr !== 'style') { // исключить из поиска обработчики (onClick etc.)
    // не нужно передавать id, namespace дальше в элемент
    return { ...acc, id: kebabCase(attr) };
  }

  return { ...acc, [attr]: props[attr] };
}, {}) as SvgProps & { id: string, namespace: string }
Example #6
Source File: underscorePropToClassName.ts    From leda with MIT License 6 votes vote down vote up
underscorePropToClassName = (prop: string, underscoreClassesTransform: UnderscoreClasses): string => {
  if (underscoreClassesTransform === UnderscoreClasses.CamelCaseTransform) {
    return kebabCase(prop.slice(1));
  }
  if (underscoreClassesTransform === UnderscoreClasses.NoTransform) {
    return prop.slice(1);
  }
  return prop.slice(1);
}
Example #7
Source File: useToast.ts    From mozartfinance-swap-interface with GNU General Public License v3.0 6 votes vote down vote up
useToast = () => {
  const dispatch = useDispatch()
  const helpers = useMemo(() => {
    const push = (toast: Toast) => dispatch(pushToast(toast))

    return {
      toastError: (title: string, description?: string) => {
        return push({ id: kebabCase(title), type: toastTypes.DANGER, title, description })
      },
      toastInfo: (title: string, description?: string) => {
        return push({ id: kebabCase(title), type: toastTypes.INFO, title, description })
      },
      toastSuccess: (title: string, description?: string) => {
        return push({ id: kebabCase(title), type: toastTypes.SUCCESS, title, description })
      },
      toastWarning: (title: string, description?: string) => {
        return push({ id: kebabCase(title), type: toastTypes.WARNING, title, description })
      },
      push,
      remove: (id: string) => dispatch(removeToast(id)),
      clear: () => dispatch(clearToast()),
    }
  }, [dispatch])

  return helpers
}
Example #8
Source File: useToast.ts    From pancake-swap-exchange-testnet with GNU General Public License v3.0 6 votes vote down vote up
useToast = () => {
  const dispatch = useDispatch()
  const helpers = useMemo(() => {
    const push = (toast: Toast) => dispatch(pushToast(toast))

    return {
      toastError: (title: string, description?: string) => {
        return push({ id: kebabCase(title), type: toastTypes.DANGER, title, description })
      },
      toastInfo: (title: string, description?: string) => {
        return push({ id: kebabCase(title), type: toastTypes.INFO, title, description })
      },
      toastSuccess: (title: string, description?: string) => {
        return push({ id: kebabCase(title), type: toastTypes.SUCCESS, title, description })
      },
      toastWarning: (title: string, description?: string) => {
        return push({ id: kebabCase(title), type: toastTypes.WARNING, title, description })
      },
      push,
      remove: (id: string) => dispatch(removeToast(id)),
      clear: () => dispatch(clearToast()),
    }
  }, [dispatch])

  return helpers
}
Example #9
Source File: useToast.ts    From pancake-swap-testnet with MIT License 6 votes vote down vote up
useToast = () => {
  const dispatch = useDispatch()
  const helpers = useMemo(() => {
    const push = (toast: Toast) => dispatch(pushToast(toast))

    return {
      toastError: (title: string, description?: string) => {
        return push({ id: kebabCase(title), type: toastTypes.DANGER, title, description })
      },
      toastInfo: (title: string, description?: string) => {
        return push({ id: kebabCase(title), type: toastTypes.INFO, title, description })
      },
      toastSuccess: (title: string, description?: string) => {
        return push({ id: kebabCase(title), type: toastTypes.SUCCESS, title, description })
      },
      toastWarning: (title: string, description?: string) => {
        return push({ id: kebabCase(title), type: toastTypes.WARNING, title, description })
      },
      push,
      remove: (id: string) => dispatch(removeToast(id)),
      clear: () => dispatch(clearToast()),
    }
  }, [dispatch])

  return helpers
}
Example #10
Source File: generate-file-name.ts    From prisma-nestjs-graphql with MIT License 6 votes vote down vote up
export function generateFileName(args: {
  type: string;
  name: string;
  getModelName(name: string): string | undefined;
  template: string;
}) {
  const { template, type, name, getModelName } = args;

  return pupa(template, {
    type,
    get model() {
      const result = getModelName(name) || 'prisma';
      return kebabCase(result);
    },
    get name() {
      let result = kebabCase(name);
      for (const suffix of ['input', 'args', 'enum']) {
        const ending = `-${suffix}`;
        if (type === suffix && result.endsWith(ending)) {
          result = result.slice(0, -ending.length);
        }
      }
      return result;
    },
    plural: {
      get type() {
        return pluralize(type);
      },
    },
  });
}
Example #11
Source File: ng_react.ts    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
/**
 * Finds the normalized attribute knowing that React props accept any type of capitalization and it also handles
 * kabab case attributes which can be used in case the attribute would also be a standard html attribute and would be
 * evaluated by the browser as such.
 * @param attrs All attributes of the component.
 * @param propName Name of the prop that react component expects.
 */
function findAttribute(attrs: string, propName: string): string {
  const index = Object.keys(attrs).find(attr => {
    return attr.toLowerCase() === propName.toLowerCase() || attr.toLowerCase() === kebabCase(propName);
  });
  // @ts-ignore
  return attrs[index];
}
Example #12
Source File: sync.ts    From g2plot-vue with MIT License 6 votes vote down vote up
Object.entries(g2plot).forEach(([chartName, module]: [string, any]) => {
  try {
    if (module.prototype instanceof Plot && chartName !== 'P') {
      if (
        !fs.existsSync(
          path.resolve(plotDir, `${kebabCase(chartName)}/index.tsx`)
        )
      ) {
        newCharts.push(chartName)
      }
    }
  } catch (error) {}
})
Example #13
Source File: Provider.tsx    From glide-frontend with GNU General Public License v3.0 5 votes vote down vote up
ToastsProvider: React.FC = ({ children }) => {
  const [toasts, setToasts] = useState<ToastContextApi['toasts']>([])

  const toast = useCallback(
    ({ title, description, type }: Omit<Toast, 'id'>) => {
      setToasts((prevToasts) => {
        const id = kebabCase(title)

        // Remove any existing toasts with the same id
        const currentToasts = prevToasts.filter((prevToast) => prevToast.id !== id)

        return [
          {
            id,
            title,
            description,
            type,
          },
          ...currentToasts,
        ]
      })
    },
    [setToasts],
  )

  const toastError = (title: string, description?: ReactNode) => {
    return toast({ title, description, type: toastTypes.DANGER })
  }
  const toastInfo = (title: string, description?: ReactNode) => {
    return toast({ title, description, type: toastTypes.INFO })
  }
  const toastSuccess = (title: string, description?: ReactNode) => {
    return toast({ title, description, type: toastTypes.SUCCESS })
  }
  const toastWarning = (title: string, description?: ReactNode) => {
    return toast({ title, description, type: toastTypes.WARNING })
  }
  const clear = () => setToasts([])
  const remove = (id: string) => {
    setToasts((prevToasts) => prevToasts.filter((prevToast) => prevToast.id !== id))
  }

  return (
    <ToastsContext.Provider value={{ toasts, clear, remove, toastError, toastInfo, toastSuccess, toastWarning }}>
      {children}
    </ToastsContext.Provider>
  )
}
Example #14
Source File: Provider.tsx    From vvs-ui with GNU General Public License v3.0 5 votes vote down vote up
ToastsProvider: React.FC = ({ children }) => {
  const [toasts, setToasts] = useState<ToastContextApi['toasts']>([])

  const toast = useCallback(
    ({ title, description, type }: Omit<Toast, 'id'>) => {
      setToasts((prevToasts) => {
        const id = kebabCase(title)

        // Remove any existing toasts with the same id
        const currentToasts = prevToasts.filter((prevToast) => prevToast.id !== id)

        return [
          {
            id,
            title,
            description,
            type,
          },
          ...currentToasts,
        ]
      })
    },
    [setToasts],
  )

  const toastError = (title: Toast['title'], description?: Toast['description']) => {
    return toast({ title, description, type: toastTypes.DANGER })
  }
  const toastInfo = (title: Toast['title'], description?: Toast['description']) => {
    return toast({ title, description, type: toastTypes.INFO })
  }
  const toastSuccess = (title: Toast['title'], description?: Toast['description']) => {
    return toast({ title, description, type: toastTypes.SUCCESS })
  }
  const toastWarning = (title: Toast['title'], description?: Toast['description']) => {
    return toast({ title, description, type: toastTypes.WARNING })
  }
  const clear = () => setToasts([])
  const remove = (id: string) => {
    setToasts((prevToasts) => prevToasts.filter((prevToast) => prevToast.id !== id))
  }

  return (
    <ToastsContext.Provider value={{ toasts, clear, remove, toastError, toastInfo, toastSuccess, toastWarning }}>
      {children}
    </ToastsContext.Provider>
  )
}
Example #15
Source File: sync.ts    From g2plot-vue with MIT License 5 votes vote down vote up
getChartConfig = (chart: string) => {
  return {
    cmpName: `${chart}Chart`,
    cmpPath: kebabCase(chart),
  }
}
Example #16
Source File: sync.ts    From g2plot-react with MIT License 5 votes vote down vote up
getChartConfig = (chart: string) => {
  return {
    cmpName: `${chart}Chart`,
    cmpPath: kebabCase(chart),
  }
}
Example #17
Source File: upgrade-neo4j.ts    From relate with GNU General Public License v3.0 4 votes vote down vote up
upgradeNeo4j = async (
    env: LocalEnvironment,
    dbmsId: string,
    version: string,
    options: IDbmsUpgradeOptions,
): Promise<IDbmsInfo> => {
    const dbms = await env.dbmss.get(dbmsId);
    const dbmsManifest = await env.dbmss.manifest.get(dbmsId);

    if (semver.lte(version, dbms.version!)) {
        throw new InvalidArgumentError(`Target version must be greater than ${dbms.version}`, ['Use valid version']);
    }

    if (dbms.status !== DBMS_STATUS.STOPPED) {
        throw new InvalidArgumentError(`Can only upgrade stopped dbms`, ['Stop dbms']);
    }

    // The upgrade will fail if the DBMS folder is locked by another process, so we check here first
    // N.B. if the folder gets locked after this check that could still fail the upgrade, but this should catch
    // most typical cases
    await checkDbmsFolderIsNotLocked(env, dbmsId);

    const {entityType, entityId} = await emitHookEvent(HOOK_EVENTS.BACKUP_START, {
        entityType: ENTITY_TYPES.DBMS,
        entityId: dbms.id,
    });
    const dbmsBackup = await env.backups.create(entityType, entityId);
    const {backup: completeBackup} = await emitHookEvent(HOOK_EVENTS.BACKUP_COMPLETE, {backup: dbmsBackup});

    const upgradeTmpName = `[Upgrade ${version}] ${dbms.name}`;

    let upgradedDbmsInfo;
    try {
        upgradedDbmsInfo = await env.dbmss.install(upgradeTmpName, version, dbms.edition!, '', options.noCache);
        const upgradedConfigFileName = path.join(
            env.dbmss.getDbmsRootPath(upgradedDbmsInfo.id),
            NEO4J_CONF_DIR,
            NEO4J_CONF_FILE,
        );

        await dbmsUpgradeConfigs(dbms, upgradedDbmsInfo, upgradedConfigFileName);
        const upgradedConfig = await env.dbmss.getDbmsConfig(upgradedDbmsInfo.id);

        /**
         * Run Neo4j migration?
         */
        if (options.migrate) {
            upgradedConfig.set('dbms.allow_upgrade', 'true');
            await upgradedConfig.flush();
            const upgradedDbms = resolveDbms(env.dbmss.dbmss, upgradedDbmsInfo.id);

            await emitHookEvent(HOOK_EVENTS.DBMS_MIGRATION_START, {dbms: upgradedDbms});

            await env.dbmss.start([upgradedDbms.id]);
            await waitForDbmsToBeOnline(upgradedDbms);
            await env.dbmss.stop([upgradedDbms.id]);

            await emitHookEvent(HOOK_EVENTS.DBMS_MIGRATION_STOP, {dbms: upgradedDbms});

            await upgradedConfig.flush();
        } else {
            upgradedConfig.set('dbms.allow_upgrade', 'false');
            await upgradedConfig.flush();
        }

        // Install new plugins
        await upgradePlugins(env, dbms, upgradedDbmsInfo, options.pluginUpgradeMode);

        /**
         * Replace old installation
         */
        await env.dbmss.uninstall(dbms.id);
        await fse.move(upgradedDbmsInfo.rootPath!, dbms.rootPath!);
        await env.dbmss.manifest.update(dbms.id, {
            ...dbmsManifest,
            name: dbms.name,
        });

        if (!options.backup) {
            await env.backups.remove(completeBackup.id);
        }

        return env.dbmss.get(dbms.id);
    } catch (e) {
        await emitHookEvent(HOOK_EVENTS.DEBUG, {
            message: 'Error upgrading',
            error: e,
        });
        if (e instanceof RelateBackupError) {
            throw e;
        }

        // Backup logs and add extra debug information if an upgrade fails
        if (upgradedDbmsInfo) {
            const upgradedDbmsRootPath = env.dbmss.getDbmsRootPath(upgradedDbmsInfo.id);
            if (upgradedDbmsRootPath) {
                const neo4jConfig = await env.dbmss.getDbmsConfig(upgradedDbmsInfo.id);

                const dateISO = new Date().toISOString();
                const [date] = dateISO.split('.');

                const logOutputPath = path.join(
                    env.dirPaths.upgradeLogsData,
                    `${kebabCase(upgradedDbmsInfo.name)}-${date.replace(/:/g, '')}`,
                );

                await fse.copy(
                    path.join(upgradedDbmsRootPath, neo4jConfig.get('dbms.directories.logs')!),
                    logOutputPath,
                );

                const plugins = await env.dbmsPlugins.list(dbms.id).then((ps) => ps.toArray().map((p) => p.name));

                const debugFilePath = path.join(logOutputPath, DEBUG_FILE);
                await fse.ensureFile(debugFilePath);
                await fse.writeJson(debugFilePath, {
                    os: process.platform,
                    backup: completeBackup.directory,
                    sourceDbms: {
                        id: dbms.id,
                        version: dbms.version,
                        path: dbms.rootPath,
                        plugins,
                    },
                    targetDbms: {
                        id: upgradedDbmsInfo.id,
                        version,
                        path: upgradedDbmsInfo.rootPath,
                    },
                });
            }
        }

        await env.dbmss
            .get(upgradeTmpName)
            .then(({id}) => env.dbmss.uninstall(id))
            .catch((error) =>
                emitHookEvent(HOOK_EVENTS.DEBUG, {
                    message: 'Error during upgrade cleanup - could not uninstall temporary DBMS',
                    error,
                }),
            );
        await env.dbmss.uninstall(dbms.id).catch((error) =>
            emitHookEvent(HOOK_EVENTS.DEBUG, {
                message: 'Error during upgrade cleanup - could not uninstall original DBMS',
                error,
            }),
        );

        const restored = await env.backups.restore(completeBackup.directory).catch(async (error) => {
            await emitHookEvent(HOOK_EVENTS.DEBUG, {
                message: 'Error during upgrade cleanup - could not restore DBMS from backup',
                error,
            });
            throw error;
        });

        await fse.move(env.dbmss.getDbmsRootPath(restored.entityId)!, dbms.rootPath!).catch(async (error) => {
            await emitHookEvent(HOOK_EVENTS.DEBUG, {
                message: 'Error during upgrade cleanup - could not move restored DBMS to original DBMS folder',
                error,
            });
            throw error;
        });

        await env.dbmss.manifest.update(dbms.id, {
            name: dbms.name,
        });

        throw new DbmsUpgradeError(`Failed to upgrade dbms ${dbms.id}`, e.message, [
            `DBMS was restored from backup ${completeBackup.id}`,
        ]);
    }
}