Skip to content

Commit

Permalink
fix: fixed reading time statistics error
Browse files Browse the repository at this point in the history
  • Loading branch information
mk965 committed Jun 6, 2024
1 parent 2303af7 commit a32a772
Show file tree
Hide file tree
Showing 7 changed files with 52 additions and 53 deletions.
6 changes: 3 additions & 3 deletions components/MDXComponents.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,17 @@ import { Image } from './Image'
import { Link } from './Link'
import { Pre } from './Pre'

let MDXComponents = {
const MDXComponents = {
Image,
a: Link,
pre: Pre,
wrapper: ({ components, layout, ...rest }) => {
let Layout = require(`../layouts/${layout}`).default
const Layout = require(`../layouts/${layout}`).default
return <Layout {...rest} />
},
}

export function MDXLayoutRenderer({ layout, mdxSource, ...rest }: MdxLayoutRendererProps) {
let MDXLayout = useMemo(() => getMDXComponent(mdxSource), [mdxSource])
const MDXLayout = useMemo(() => getMDXComponent(mdxSource), [mdxSource])
return <MDXLayout layout={layout} components={MDXComponents} {...rest} />
}
1 change: 0 additions & 1 deletion layouts/PostLayout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import type { PostLayoutProps } from '~/types'
export function PostLayout(props: PostLayoutProps) {
let { frontMatter, authorDetails, page, children, commentConfig } = props
let { slug, fileName, date, title, tags, readingTime } = frontMatter
console.log('=====', readingTime)
let postUrl = `${siteMetadata.siteUrl}/blog/${slug}`

return (
Expand Down
8 changes: 4 additions & 4 deletions layouts/PostSimple.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ import { siteMetadata } from '~/data/siteMetadata'
import type { PostSimpleLayoutProps } from '~/types'

export function PostSimple(props: PostSimpleLayoutProps) {
let { frontMatter, type, children, authorDetails, commentConfig } = props
let { date, title, slug, fileName, tags, readingTime } = frontMatter
let postUrl = `${siteMetadata.siteUrl}/${type}/${slug}`
const { frontMatter, type, children, authorDetails, commentConfig } = props
const { date, title, slug, fileName, tags, readingTime } = frontMatter
const postUrl = `${siteMetadata.siteUrl}/${type}/${slug}`

return (
<SectionContainer>
Expand All @@ -38,7 +38,7 @@ export function PostSimple(props: PostSimpleLayoutProps) {
</header>
<div className="pb-8" style={{ gridTemplateRows: 'auto 1fr' }}>
<div className="xl:col-span-3 xl:row-span-2 xl:pb-0">
<div className="prose prose-lg max-w-none pb-8 dark:prose-dark md:prose-xl">
<div className="pb-8 prose prose-lg max-w-none dark:prose-dark md:prose-xl">
{children}
</div>
<div className="border-t border-gray-200 dark:border-gray-700">
Expand Down
32 changes: 16 additions & 16 deletions libs/mdx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,10 @@ import { remarkImgToJsx } from './remark-img-to-jsx'
import { remarkTocHeading } from './remark-toc-heading'

export async function getFileBySlug(type: string, slug: string): Promise<MdxFileData> {
let root = process.cwd()
let mdxPath = path.join(root, 'data', type, `${slug}.mdx`)
let mdPath = path.join(root, 'data', type, `${slug}.md`)
let source = fs.existsSync(mdxPath)
const root = process.cwd()
const mdxPath = path.join(root, 'data', type, `${slug}.mdx`)
const mdPath = path.join(root, 'data', type, `${slug}.md`)
const source = fs.existsSync(mdxPath)
? fs.readFileSync(mdxPath, 'utf8')
: fs.readFileSync(mdPath, 'utf8')

Expand All @@ -46,8 +46,8 @@ export async function getFileBySlug(type: string, slug: string): Promise<MdxFile
)
}

let toc: TOC[] = []
let { frontmatter, code } = await bundleMDX<MdxFrontMatter>({
const toc: TOC[] = []
const { frontmatter, code } = await bundleMDX<MdxFrontMatter>({
source,
cwd: path.join(process.cwd(), 'components'),
esbuildOptions: (options) => {
Expand Down Expand Up @@ -79,7 +79,7 @@ export async function getFileBySlug(type: string, slug: string): Promise<MdxFile
() => {
return (tree) => {
visit(tree, 'element', (node: UnistNodeType) => {
let [token, type] = node.properties.className || []
const [token, type] = node.properties.className || []
if (token === 'token') {
node.properties.className = [TOKEN_CLASSNAME_MAP[type]]
}
Expand All @@ -95,7 +95,7 @@ export async function getFileBySlug(type: string, slug: string): Promise<MdxFile
toc,
mdxSource: code,
frontMatter: {
readingTime: readingTime(code),
readingTime: readingTime(source),
slug: slug || null,
fileName: fs.existsSync(mdxPath) ? `${slug}.mdx` : `${slug}.md`,
...frontmatter,
Expand All @@ -104,20 +104,20 @@ export async function getFileBySlug(type: string, slug: string): Promise<MdxFile
}

export function getAllFilesFrontMatter(folder: string) {
let root = process.cwd()
let prefixPaths = path.join(root, 'data', folder)
let files = getAllFilesRecursively(prefixPaths)
let allFrontMatter: BlogFrontMatter[] = []
const root = process.cwd()
const prefixPaths = path.join(root, 'data', folder)
const files = getAllFilesRecursively(prefixPaths)
const allFrontMatter: BlogFrontMatter[] = []
files.forEach((file) => {
// Replace is needed to work on Windows
let fileName = file.slice(prefixPaths.length + 1).replace(/\\/g, '/')
const fileName = file.slice(prefixPaths.length + 1).replace(/\\/g, '/')
// Remove Unexpected File
if (path.extname(fileName) !== '.md' && path.extname(fileName) !== '.mdx') {
return
}
let source = fs.readFileSync(file, 'utf8')
let grayMatterData = matter(source)
let data = grayMatterData.data as BlogFrontMatter
const source = fs.readFileSync(file, 'utf8')
const grayMatterData = matter(source)
const data = grayMatterData.data as BlogFrontMatter
if (data.draft !== true) {
allFrontMatter.push({ ...data, slug: formatSlug(fileName) })
}
Expand Down
30 changes: 15 additions & 15 deletions pages/blog/[...slug].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@ import { generateRss } from '~/libs/generate-rss'
import { getAllFilesFrontMatter, getFileBySlug } from '~/libs/mdx'
import type { AuthorFrontMatter, BlogProps, MdxPageLayout } from '~/types'

let DEFAULT_LAYOUT: MdxPageLayout = 'PostSimple'
const DEFAULT_LAYOUT: MdxPageLayout = 'PostSimple'

export async function getStaticPaths() {
let posts = getFiles('blog')
const posts = getFiles('blog')
return {
paths: posts.map((p: string) => ({
params: {
Expand All @@ -23,33 +23,33 @@ export async function getStaticPaths() {
}

export async function getStaticProps({ params }: { params: { slug: string[] } }) {
let allPosts = getAllFilesFrontMatter('blog')
let postIndex = allPosts.findIndex((post) => formatSlug(post.slug) === params.slug.join('/'))
let prev = allPosts[postIndex + 1] || null
let next = allPosts[postIndex - 1] || null
let page = Math.ceil((postIndex + 1) / POSTS_PER_PAGE)
let post = await getFileBySlug('blog', params.slug.join('/'))
const allPosts = getAllFilesFrontMatter('blog')
const postIndex = allPosts.findIndex((post) => formatSlug(post.slug) === params.slug.join('/'))
const prev = allPosts[postIndex + 1] || null
const next = allPosts[postIndex - 1] || null
const page = Math.ceil((postIndex + 1) / POSTS_PER_PAGE)
const post = await getFileBySlug('blog', params.slug.join('/'))

let authors = post.frontMatter.authors || ['default']
let authorDetails = await Promise.all(
const authors = post.frontMatter.authors || ['default']
const authorDetails = await Promise.all(
authors.map(async (author) => {
let authorData = await getFileBySlug('authors', author)
const authorData = await getFileBySlug('authors', author)
// eslint-disable-next-line
return authorData.frontMatter as unknown as AuthorFrontMatter
})
)

// rss
let rss = generateRss(allPosts)
const rss = generateRss(allPosts)
fs.writeFileSync('./public/feed.xml', rss)
let commentConfig = getCommentConfigs()
const commentConfig = getCommentConfigs()

return { props: { post, authorDetails, prev, next, page, commentConfig } }
}

export default function Blog(props: BlogProps) {
let { post, ...rest } = props
let { mdxSource, frontMatter } = post
const { post, ...rest } = props
const { mdxSource, frontMatter } = post

return (
<>
Expand Down
18 changes: 9 additions & 9 deletions pages/blog/page/[page].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ import { getAllFilesFrontMatter } from '~/libs/mdx'
import type { BlogListProps } from '~/types'

export async function getStaticPaths() {
let totalPosts = getAllFilesFrontMatter('blog')
let totalPages = Math.ceil(totalPosts.length / POSTS_PER_PAGE)
let paths = Array.from({ length: totalPages }, (_, i) => ({
const totalPosts = getAllFilesFrontMatter('blog')
const totalPages = Math.ceil(totalPosts.length / POSTS_PER_PAGE)
const paths = Array.from({ length: totalPages }, (_, i) => ({
params: { page: (i + 1).toString() },
}))

Expand All @@ -19,14 +19,14 @@ export async function getStaticPaths() {
}

export async function getStaticProps({ params }: { params: { page: string } }) {
let { page } = params
let posts = getAllFilesFrontMatter('blog')
let pageNumber = parseInt(page)
let initialDisplayPosts = posts.slice(
const { page } = params
const posts = getAllFilesFrontMatter('blog')
const pageNumber = parseInt(page)
const initialDisplayPosts = posts.slice(
POSTS_PER_PAGE * (pageNumber - 1),
POSTS_PER_PAGE * pageNumber
)
let pagination = {
const pagination = {
currentPage: pageNumber,
totalPages: Math.ceil(posts.length / POSTS_PER_PAGE),
}
Expand All @@ -41,7 +41,7 @@ export async function getStaticProps({ params }: { params: { page: string } }) {
}

export default function PostPage(props: BlogListProps) {
let { posts, initialDisplayPosts, pagination } = props
const { posts, initialDisplayPosts, pagination } = props
return (
<>
<PageSeo title={siteMetadata.title} description={siteMetadata.description} />
Expand Down
10 changes: 5 additions & 5 deletions pages/snippets/[...slug].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@ import { getFileBySlug } from '~/libs/mdx'
import type { MdxPageLayout } from '~/types/mdx'
import type { SnippetProps } from '~/types/page'

let DEFAULT_LAYOUT: MdxPageLayout = 'PostSimple'
const DEFAULT_LAYOUT: MdxPageLayout = 'PostSimple'

export async function getStaticPaths() {
let snippets = getFiles('snippets')
const snippets = getFiles('snippets')
return {
paths: snippets.map((p: string) => ({
params: {
Expand All @@ -21,15 +21,15 @@ export async function getStaticPaths() {
}

export async function getStaticProps({ params }) {
let snippet = await getFileBySlug('snippets', params.slug.join('/'))
let commentConfig = getCommentConfigs()
const snippet = await getFileBySlug('snippets', params.slug.join('/'))
const commentConfig = getCommentConfigs()
return {
props: { snippet, commentConfig },
}
}

export default function Snippet({ snippet, commentConfig }: SnippetProps) {
let { mdxSource, frontMatter } = snippet
const { mdxSource, frontMatter } = snippet

return (
<>
Expand Down

0 comments on commit a32a772

Please sign in to comment.