Skip to content

Commit

Permalink
refactor: regrouping hooks files
Browse files Browse the repository at this point in the history
- move hook doc files to src
- move hook demo files to src
- update import statement when copying hooks
- update hook imports
- update plop config to match
- fix tsconfig
- update hook queries in website
- update script files to match
  • Loading branch information
juliencrn committed Sep 19, 2022
1 parent a3afc57 commit b0066df
Show file tree
Hide file tree
Showing 139 changed files with 216 additions and 320 deletions.
20 changes: 20 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
"@typescript-eslint/eslint-plugin": "^5.37.0",
"@typescript-eslint/parser": "^5.37.0",
"all-contributors-cli": "^6.20.0",
"date-fns": "^2.29.3",
"eslint": "^8.9.0",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-jest": "^27.0.4",
Expand Down
52 changes: 18 additions & 34 deletions plopfile.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,64 +11,48 @@ module.exports = function (plop) {
},
],
actions: [
/**
* usehooks-ts packages side
*
* - Create the hook index file (for quick export)
* - Create the hook file itself
* - Create the test file
* - Update the global hooks index file
*/
// Create the hook index file (for quick export)
{
type: 'add',
path: 'src/{{camelCase name}}/index.ts',
templateFile: 'templates/plop/hooks/lib/index.ts.hbs',
templateFile: 'templates/plop/hooks/hook/index.ts.hbs',
},

// Create the hook file itself
{
type: 'add',
path: 'src/{{camelCase name}}/{{camelCase name}}.ts',
templateFile: 'templates/plop/hooks/lib/hook.ts.hbs',
templateFile: 'templates/plop/hooks/hook/hook.ts.hbs',
},

// Create the test file
{
type: 'add',
path: 'src/{{camelCase name}}/{{camelCase name}}.test.ts',
templateFile: 'templates/plop/hooks/lib/hook.test.ts.hbs',
},
{
type: 'append',
path: 'src/index.ts',
templateFile: 'templates/plop/hooks/index.ts.hbs',
templateFile: 'templates/plop/hooks/hook/hook.test.ts.hbs',
},

/**
* frontend side
*
* - Create the hook index file (for quick export)
* - Create the markdown file to present the hook
* - Create the demo react component file
* - Update the global hooks index file
*/
{
type: 'add',
path: 'website/src/content/{{camelCase name}}/index.ts',
templateFile: 'templates/plop/hooks/website/index.ts.hbs',
},
// Create the markdown file to present the hook (doc)
{
data: {
date: format(new Date(), 'yyyy-MM-dd'),
},
type: 'add',
path: 'website/src/content/{{camelCase name}}/{{camelCase name}}.mdx',
templateFile: 'templates/plop/hooks/website/post.mdx.hbs',
path: 'src/{{camelCase name}}/{{camelCase name}}.mdx',
templateFile: 'templates/plop/hooks/hook/post.mdx.hbs',
},

// Create the demo react component file
{
type: 'add',
path: 'website/src/content/{{camelCase name}}/{{camelCase name}}.demo.tsx',
templateFile: 'templates/plop/hooks/website/demo.tsx.hbs',
path: 'src/{{camelCase name}}/{{camelCase name}}.demo.tsx',
templateFile: 'templates/plop/hooks/hook/demo.tsx.hbs',
},

// Update the global hooks index file
{
type: 'append',
path: 'website/src/content/index.ts',
path: 'src/index.ts',
templateFile: 'templates/plop/hooks/index.ts.hbs',
},
],
Expand Down
118 changes: 61 additions & 57 deletions scripts/copyHooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import path from 'path'
import { isHookFile, toQueryParams } from './utils'

const hooksDir = path.resolve('./src')
const demosDir = path.resolve('./website/src/content')
const outputDir = path.resolve('./website/generated')
const sandboxTemplatePath = path.resolve('./templates/codesandbox')

Expand All @@ -14,32 +13,37 @@ const sandboxTemplatePath = path.resolve('./templates/codesandbox')

createDirIfNeeded(outputDir)
createDirIfNeeded(`${outputDir}/hooks/`)
createDirIfNeeded(`${outputDir}/hookDemos/`)
createDirIfNeeded(`${outputDir}/demos/`)
createDirIfNeeded(`${outputDir}/posts/`)

// Copy hooks as markdown file
// Copy hooks as a markdown file
fs.readdir(hooksDir, (err, files) => {
if (err) throw err
files.forEach(file => {
if (isHookFile(file))
copyHook({
sourceFile: path.resolve(`${hooksDir}/${file}/${file}.ts`),
destFile: path.resolve(`${outputDir}/hooks/${file}.hook.md`),
})
})
})

// Copy hooks's demo as markdown file
fs.readdir(demosDir, (err, files) => {
if (err) throw err
files.forEach(file => {
if (isHookFile(file)) {
copyHook({
sourceFile: path.resolve(`${demosDir}/${file}/${file}.demo.tsx`),
destFile: path.resolve(`${outputDir}/hookDemos/${file}.demo.md`),
useSandbox: true,
})
}
})
for (const file of files) {
if (!isHookFile(file)) continue

// Copy hook as a markdown file
copyFile({
source: path.resolve(`${hooksDir}/${file}/${file}.ts`),
dest: path.resolve(`${outputDir}/hooks/${file}.hook.md`),
toMarkdown: true,
})

// Copy demo as a markdown file
copyFile({
source: path.resolve(`${hooksDir}/${file}/${file}.demo.tsx`),
dest: path.resolve(`${outputDir}/demos/${file}.demo.md`),
toMarkdown: true,
useSandbox: true,
})

// Copy documentation file
copyFile({
source: path.resolve(`${hooksDir}/${file}/${file}.mdx`),
dest: path.resolve(`${outputDir}/posts/${file}.post.mdx`),
})
}
})

////////////////////////////////////////////////////////////////////////
Expand All @@ -51,65 +55,65 @@ function getFileName(pathname: string): string {
}

function createDirIfNeeded(dir: string): void {
if (!fs.existsSync(path.resolve(dir))) {
fs.mkdirSync(dir)
}
if (!fs.existsSync(path.resolve(dir))) fs.mkdirSync(dir)
}

function copyHook({
sourceFile,
destFile,
useSandbox,
}: {
sourceFile: string
destFile: string
interface CopyFileProps {
source: string
dest: string
useSandbox?: boolean
}) {
toMarkdown?: boolean
}

function copyFile({ source, dest, useSandbox, toMarkdown }: CopyFileProps) {
// Check source file
if (!fs.existsSync(sourceFile)) {
console.warn(`${getFileName(sourceFile)} doesn't exist`)
if (!fs.existsSync(source)) {
console.warn(`${getFileName(source)} doesn't exist`)
return
}

// If destination file exists, remove it
let existingFile = false

if (fs.existsSync(destFile)) {
fs.unlinkSync(destFile)
if (fs.existsSync(dest)) {
fs.unlinkSync(dest)
existingFile = true
}

// Read source then create markdown hook file
fs.readFile(sourceFile, 'utf8', (err, data) => {
fs.readFile(source, 'utf8', (err, data) => {
if (err) {
console.error(`Cannot read ${sourceFile}`)
console.error(`Cannot read ${source}`)
return
}

const extension = sourceFile.split('.').reverse()[0]

const writeStream = fs.createWriteStream(destFile)

let preCode = '```' + extension

const name = getFileName(dest)
const extension = source.split('.').reverse()[0]
const writeStream = fs.createWriteStream(dest)
// TODO: Theses hooks don't work on CodeSandbox, make it work.
const excludedHook = [
'useFetch.demo.md',
'useCopyToClipboard.demo.md',
].includes(getFileName(destFile))
const excludedHooks = ['useFetch.demo.md', 'useCopyToClipboard.demo.md']
let preCode = '```' + extension

if (useSandbox && !excludedHook) {
// If CodeSandbox enabled, add needed parameter
if (useSandbox && !excludedHooks.includes(name)) {
const templateOptions = toQueryParams({ entry: 'src/App.tsx' })
preCode += ' codesandbox=file:' + sandboxTemplatePath + templateOptions
}

writeStream.write(preCode + '\r')
if (toMarkdown) {
// rename import from "from '..'" to "from 'usehooks-ts'"
const re = new RegExp("^import { (use[A-Z][a-zA-Z]*..)+ } from '..'$")
const transform = (line: string) => {
return line.replace(re, match => match.replace('..', 'usehooks-ts'))
}
data = data.split('\n').map(transform).join('\n')

// wrap code into markdown code tags
data = preCode + '\r' + data + '```\r'
}

writeStream.write(data)
writeStream.write('```\r')
writeStream.end()

console.log(
`${getFileName(destFile)} ${existingFile ? 'updated' : 'created'}`,
)
console.log(`${name} ${existingFile ? 'updated' : 'created'}`)
})
}
17 changes: 9 additions & 8 deletions scripts/updateReadme.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,16 @@
import fs from 'fs'
import path from 'path'

import { camelToKebabCase, isHookFile } from './utils'
import { camelToKebabCase, isDemoFile, isHookFile } from './utils'

////////////////////////////////////////////////////////////////////////
// 1. Imperative script that updates the hook list in the README file.
////////////////////////////////////////////////////////////////////////

const demos = fs.readdirSync(
path.resolve(path.resolve('./website/src/content')),
)

const hooks = fs
.readdirSync(path.resolve(path.resolve('./src')))
.filter(isHookFile)
.map(name => formatHook(name, demos))
.map(formatHook)

const markdown = createMarkdownList(hooks)

Expand All @@ -34,8 +30,13 @@ interface MarkdownLine {
markdownLine: string
}

function formatHook(name: string, demos: string[]): MarkdownLine | null {
const hasDemo = demos.includes(name)
function formatHook(name: string): MarkdownLine | null {
// exclude hook from readme if it haven't demo
const hasDemo =
fs
.readdirSync(path.resolve(path.resolve(`./src/${name}`)))
.filter(isDemoFile).length === 1

if (!hasDemo) {
console.warn(`${name} haven't demo yet!`)
return null
Expand Down
5 changes: 5 additions & 0 deletions scripts/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,11 @@ export function isHookFile(filename: string): boolean {
return hookRegex.test(filename)
}

export function isDemoFile(filename: string): boolean {
const hookDemoRegex = new RegExp('^use[A-Z][a-zA-Z]*.demo.tsx$')
return hookDemoRegex.test(filename)
}

export function camelToKebabCase(str: string): string {
return str.replace(/[A-Z]/g, letter => `-${letter.toLowerCase()}`)
}
Expand Down
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ export * from './useDarkMode'
export * from './useDebounce'
export * from './useEffectOnce'
export * from './useElementSize'
export * from './useEventCallback'
export * from './useEventListener'
export * from './useFetch'
export * from './useHover'
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React from 'react'

import { useBoolean } from 'usehooks-ts'
import { useBoolean } from '..'

export default function Component() {
const { value, setValue, setTrue, setFalse, toggle } = useBoolean(false)
Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React, { useState } from 'react'

import { useClickAnyWhere } from 'usehooks-ts'
import { useClickAnyWhere } from '..'

export default function Component() {
const [count, setCount] = useState(0)
Expand Down
File renamed without changes.
2 changes: 1 addition & 1 deletion src/useClickAnyWhere/useClickAnyWhere.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useEventListener } from '../useEventListener'
import { useEventListener } from '..'

type Handler = (event: MouseEvent) => void

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React from 'react'

import { useCopyToClipboard } from 'usehooks-ts'
import { useCopyToClipboard } from '..'

export default function Component() {
const [value, copy] = useCopyToClipboard()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React, { ChangeEvent, useState } from 'react'

import { useCountdown } from 'usehooks-ts'
import { useCountdown } from '..'

export default function Component() {
const [intervalValue, setIntervalValue] = useState<number>(1000)
Expand Down
File renamed without changes.
Loading

0 comments on commit b0066df

Please sign in to comment.