feat: support blog module (v1)

This commit is contained in:
javayhu 2025-02-20 00:33:50 +08:00
parent de1f8bbfcf
commit f3c844b426
30 changed files with 1614 additions and 0 deletions

137
content-collections.ts Normal file
View File

@ -0,0 +1,137 @@
import { defineCollection, defineConfig } from "@content-collections/core";
import { compileMDX } from "@content-collections/mdx";
import rehypeAutolinkHeadings from 'rehype-autolink-headings';
import rehypePrettyCode, { Options } from 'rehype-pretty-code';
import rehypeSlug from 'rehype-slug';
import { codeImport } from 'remark-code-import';
import remarkGfm from 'remark-gfm';
import { createHighlighter } from 'shiki';
import path from "path";
import { getBaseUrl } from "@/lib/urls/get-base-url";
/**
* Content Collections documentation
* 1. https://www.content-collections.dev/docs/quickstart/next
* 2. https://www.content-collections.dev/docs/configuration
* 3. https://www.content-collections.dev/docs/transform#join-collections
*/
/**
* Blog Author collection
*/
export const authors = defineCollection({
name: 'author',
directory: 'content',
include: '**/author/*.mdx',
schema: (z) => ({
slug: z.string(),
name: z.string(),
avatar: z.string()
}),
transform: async (data, context) => {
return {
...data,
avatar: getBaseUrl() + data.avatar
};
}
});
/**
* Blog Category collection
*/
export const categories = defineCollection({
name: 'category',
directory: 'content',
include: '**/category/*.mdx',
schema: (z) => ({
slug: z.string(),
name: z.string(),
description: z.string()
})
});
/**
* Blog Post collection
*
* 1. For a blog post file at content/blog/2023/year-review.mdx:
* slug: /blog/2023/year-review
* slugAsParams: 2023/year-review
*
* 2. For a blog post at content/blog/first-post.mdx:
* slug: /blog/first-post
* slugAsParams: first-post
*/
export const posts = defineCollection({
name: 'post',
directory: 'content',
include: '**/blog/*.mdx',
schema: (z) => ({
title: z.string(),
description: z.string(),
date: z.string().datetime(),
published: z.boolean().default(true),
categories: z.array(z.string()),
author: z.string()
}),
transform: async (data, context) => {
const body = await compileMDX(context, data, {
remarkPlugins: [
remarkGfm,
codeImport
],
rehypePlugins: [
rehypeSlug,
rehypeAutolinkHeadings,
[rehypePrettyCode, prettyCodeOptions]
]
});
const blogAuthor = context
.documents(authors)
.find((a) => a.slug === data.author);
const blogCategories = context
.documents(categories)
.filter((c) => data.categories.includes(c.slug));
return {
...data,
author: blogAuthor,
categories: blogCategories,
slug: `/${data._meta.path}`,
slugAsParams: data._meta.path.split(path.sep).slice(1).join('/'),
body: {
raw: data.content,
code: body
}
};
}
});
const prettyCodeOptions: Options = {
theme: 'github-dark',
getHighlighter: (options) =>
createHighlighter({
...options
}),
onVisitLine(node) {
// Prevent lines from collapsing in `display: grid` mode, and allow empty
// lines to be copy/pasted
if (node.children.length === 0) {
node.children = [{ type: 'text', value: ' ' }];
}
},
onVisitHighlightedLine(node) {
if (!node.properties.className) {
node.properties.className = [];
}
node.properties.className.push('line--highlighted');
},
onVisitHighlightedChars(node) {
if (!node.properties.className) {
node.properties.className = [];
}
node.properties.className = ['word--highlighted'];
}
};
export default defineConfig({
collections: [authors, categories, posts]
});

View File

@ -0,0 +1,5 @@
---
slug: indiehub
name: IndieHub
avatar: /images/avatars/indiehub.png
---

View File

@ -0,0 +1,5 @@
---
slug: mkdirs
name: mkdirs
avatar: /images/avatars/mkdirs.png
---

View File

@ -0,0 +1,5 @@
---
slug: mksaas
name: MkSaaS
avatar: /images/avatars/mksaas.png
---

View File

@ -0,0 +1,213 @@
---
title: What is IndieHub?
description: IndieHub is the best directory for indie hackers.
date: 2024-11-24T12:00:00.000Z
published: true
categories: [news]
author: indiehub
---
Until now, trying to style an article, document, or blog post with Tailwind has been a tedious task that required a keen eye for typography and a lot of complex custom CSS.
By default, Tailwind removes all of the default browser styling from paragraphs, headings, lists and more. This ends up being really useful for building application UIs because you spend less time undoing user-agent styles, but when you _really are_ just trying to style some content that came from a rich-text editor in a CMS or a markdown file, it can be surprising and unintuitive.
We get lots of complaints about it actually, with people regularly asking us things like:
> Why is Tailwind removing the default styles on my `h1` elements? How do I disable this? What do you mean I lose all the other base styles too?
> We hear you, but we're not convinced that simply disabling our base styles is what you really want. You don't want to have to remove annoying margins every time you use a `p` element in a piece of your dashboard UI. And I doubt you really want your blog posts to use the user-agent styles either — you want them to look _awesome_, not awful.
The `@tailwindcss/typography` plugin is our attempt to give you what you _actually_ want, without any of the downsides of doing something stupid like disabling our base styles.
It adds a new `prose` class that you can slap on any block of vanilla HTML content and turn it into a beautiful, well-formatted document:
```html
<article class="prose">
<h1>Garlic bread with cheese: What the science tells us</h1>
<p>
For years parents have espoused the health benefits of eating garlic bread
with cheese to their children, with the food earning such an iconic status
in our culture that kids will often dress up as warm, cheesy loaf for
Halloween.
</p>
<p>
But a recent study shows that the celebrated appetizer may be linked to a
series of rabies cases springing up around the country.
</p>
</article>
```
For more information about how to use the plugin and the features it includes, [read the documentation](https://github.com/tailwindcss/typography/blob/master/README.md).
---
## What to expect from here on out
What follows from here is just a bunch of absolute nonsense I've written to dogfood the plugin itself. It includes every sensible typographic element I could think of, like **bold text**, unordered lists, ordered lists, code blocks, block quotes, _and even italics_.
It's important to cover all of these use cases for a few reasons:
1. We want everything to look good out of the box.
2. Really just the first reason, that's the whole point of the plugin.
3. Here's a third pretend reason though a list with three items looks more realistic than a list with two items.
Now we're going to try out another header style.
### Typography should be easy
So that's a header for you — with any luck if we've done our job correctly that will look pretty reasonable.
Something a wise person once told me about typography is:
> Typography is pretty important if you don't want your stuff to look like trash. Make it good then it won't be bad.
It's probably important that images look okay here by default as well:
<Image
src="/images/blog/indiehub-og.png"
width="718"
height="404"
alt="Image"
/>
Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old.
Now I'm going to show you an example of an unordered list to make sure that looks good, too:
- So here is the first item in this list.
- In this example we're keeping the items short.
- Later, we'll use longer, more complex list items.
And that's the end of this section.
## What if we stack headings?
### We should make sure that looks good, too.
Sometimes you have headings directly underneath each other. In those cases you often have to undo the top margin on the second heading because it usually looks better for the headings to be closer together than a paragraph followed by a heading should be.
### When a heading comes after a paragraph …
When a heading comes after a paragraph, we need a bit more space, like I already mentioned above. Now let's see what a more complex list would look like.
- **I often do this thing where list items have headings.**
For some reason I think this looks cool which is unfortunate because it's pretty annoying to get the styles right.
I often have two or three paragraphs in these list items, too, so the hard part is getting the spacing between the paragraphs, list item heading, and separate list items to all make sense. Pretty tough honestly, you could make a strong argument that you just shouldn't write this way.
- **Since this is a list, I need at least two items.**
I explained what I'm doing already in the previous list item, but a list wouldn't be a list if it only had one item, and we really want this to look realistic. That's why I've added this second list item so I actually have something to look at when writing the styles.
- **It's not a bad idea to add a third item either.**
I think it probably would've been fine to just use two items but three is definitely not worse, and since I seem to be having no trouble making up arbitrary things to type, I might as well include it.
After this sort of list I usually have a closing statement or paragraph, because it kinda looks weird jumping right to a heading.
## Code should look okay by default.
I think most people are going to use [highlight.js](https://highlightjs.org/) or [Prism](https://prismjs.com/) or something if they want to style their code blocks but it wouldn't hurt to make them look _okay_ out of the box, even with no syntax highlighting.
Here's what a default `tailwind.config.js` file looks like at the time of writing:
```js
module.exports = {
purge: [],
theme: {
extend: {},
},
variants: {},
plugins: [],
};
```
Hopefully that looks good enough to you.
### What about nested lists?
Nested lists basically always look bad which is why editors like Medium don't even let you do it, but I guess since some of you goofballs are going to do it we have to carry the burden of at least making it work.
1. **Nested lists are rarely a good idea.**
- You might feel like you are being really "organized" or something but you are just creating a gross shape on the screen that is hard to read.
- Nested navigation in UIs is a bad idea too, keep things as flat as possible.
- Nesting tons of folders in your source code is also not helpful.
2. **Since we need to have more items, here's another one.**
- I'm not sure if we'll bother styling more than two levels deep.
- Two is already too much, three is guaranteed to be a bad idea.
- If you nest four levels deep you belong in prison.
3. **Two items isn't really a list, three is good though.**
- Again please don't nest lists if you want people to actually read your content.
- Nobody wants to look at this.
- I'm upset that we even have to bother styling this.
The most annoying thing about lists in Markdown is that `<li>` elements aren't given a child `<p>` tag unless there are multiple paragraphs in the list item. That means I have to worry about styling that annoying situation too.
- **For example, here's another nested list.**
But this time with a second paragraph.
- These list items won't have `<p>` tags
- Because they are only one line each
- **But in this second top-level list item, they will.**
This is especially annoying because of the spacing on this paragraph.
- As you can see here, because I've added a second line, this list item now has a `<p>` tag.
This is the second line I'm talking about by the way.
- Finally here's another list item so it's more like a list.
- A closing list item, but with no nested list, because why not?
And finally a sentence to close off this section.
## There are other elements we need to style
I almost forgot to mention links, like [this link to the Tailwind CSS website](https://tailwindcss.com). We almost made them blue but that's so yesterday, so we went with dark gray, feels edgier.
We even included table styles, check it out:
| Wrestler | Origin | Finisher |
| ----------------------- | ------------ | ------------------ |
| Bret "The Hitman" Hart | Calgary, AB | Sharpshooter |
| Stone Cold Steve Austin | Austin, TX | Stone Cold Stunner |
| Randy Savage | Sarasota, FL | Elbow Drop |
| Vader | Boulder, CO | Vader Bomb |
| Razor Ramon | Chuluota, FL | Razor's Edge |
We also need to make sure inline code looks good, like if I wanted to talk about `<span>` elements or tell you the good news about `@tailwindcss/typography`.
### Sometimes I even use `code` in headings
Even though it's probably a bad idea, and historically I've had a hard time making it look good. This _"wrap the code blocks in backticks"_ trick works pretty well though really.
Another thing I've done in the past is put a `code` tag inside of a link, like if I wanted to tell you about the [`tailwindcss/docs`](https://github.com/tailwindcss/docs) repository. I don't love that there is an underline below the backticks but it is absolutely not worth the madness it would require to avoid it.
#### We haven't used an `h4` yet
But now we have. Please don't use `h5` or `h6` in your content, Medium only supports two heading levels for a reason, you animals. I honestly considered using a `before` pseudo-element to scream at you if you use an `h5` or `h6`.
We don't style them at all out of the box because `h4` elements are already so small that they are the same size as the body copy. What are we supposed to do with an `h5`, make it _smaller_ than the body copy? No thanks.
### We still need to think about stacked headings though.
#### Let's make sure we don't screw that up with `h4` elements, either.
Phew, with any luck we have styled the headings above this text and they look pretty good.
Let's add a closing paragraph here so things end with a decently sized block of text. I can't explain why I want things to end that way but I have to assume it's because I think things will look weird or unbalanced if there is a heading too close to the end of the document.
What I've written here is probably long enough, but adding this final sentence can't hurt.
## GitHub Flavored Markdown
I've also added support for GitHub Flavored Mardown using `remark-gfm`.
With `remark-gfm`, we get a few extra features in our markdown. Example: autolink literals.
A link like www.example.com or https://example.com would automatically be converted into an `a` tag.
This works for email links too: contact@example.com.

View File

@ -0,0 +1,213 @@
---
title: What is Mkdirs?
description: Mkdirs is the best boilerplate for building directory websites.
date: 2024-11-25T12:00:00.000Z
published: true
categories: [news]
author: mkdirs
---
Until now, trying to style an article, document, or blog post with Tailwind has been a tedious task that required a keen eye for typography and a lot of complex custom CSS.
By default, Tailwind removes all of the default browser styling from paragraphs, headings, lists and more. This ends up being really useful for building application UIs because you spend less time undoing user-agent styles, but when you _really are_ just trying to style some content that came from a rich-text editor in a CMS or a markdown file, it can be surprising and unintuitive.
We get lots of complaints about it actually, with people regularly asking us things like:
> Why is Tailwind removing the default styles on my `h1` elements? How do I disable this? What do you mean I lose all the other base styles too?
> We hear you, but we're not convinced that simply disabling our base styles is what you really want. You don't want to have to remove annoying margins every time you use a `p` element in a piece of your dashboard UI. And I doubt you really want your blog posts to use the user-agent styles either — you want them to look _awesome_, not awful.
The `@tailwindcss/typography` plugin is our attempt to give you what you _actually_ want, without any of the downsides of doing something stupid like disabling our base styles.
It adds a new `prose` class that you can slap on any block of vanilla HTML content and turn it into a beautiful, well-formatted document:
```html
<article class="prose">
<h1>Garlic bread with cheese: What the science tells us</h1>
<p>
For years parents have espoused the health benefits of eating garlic bread
with cheese to their children, with the food earning such an iconic status
in our culture that kids will often dress up as warm, cheesy loaf for
Halloween.
</p>
<p>
But a recent study shows that the celebrated appetizer may be linked to a
series of rabies cases springing up around the country.
</p>
</article>
```
For more information about how to use the plugin and the features it includes, [read the documentation](https://github.com/tailwindcss/typography/blob/master/README.md).
---
## What to expect from here on out
What follows from here is just a bunch of absolute nonsense I've written to dogfood the plugin itself. It includes every sensible typographic element I could think of, like **bold text**, unordered lists, ordered lists, code blocks, block quotes, _and even italics_.
It's important to cover all of these use cases for a few reasons:
1. We want everything to look good out of the box.
2. Really just the first reason, that's the whole point of the plugin.
3. Here's a third pretend reason though a list with three items looks more realistic than a list with two items.
Now we're going to try out another header style.
### Typography should be easy
So that's a header for you — with any luck if we've done our job correctly that will look pretty reasonable.
Something a wise person once told me about typography is:
> Typography is pretty important if you don't want your stuff to look like trash. Make it good then it won't be bad.
It's probably important that images look okay here by default as well:
<Image
src="/images/blog/mkdirs-opengraph.png"
width="718"
height="404"
alt="Image"
/>
Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old.
Now I'm going to show you an example of an unordered list to make sure that looks good, too:
- So here is the first item in this list.
- In this example we're keeping the items short.
- Later, we'll use longer, more complex list items.
And that's the end of this section.
## What if we stack headings?
### We should make sure that looks good, too.
Sometimes you have headings directly underneath each other. In those cases you often have to undo the top margin on the second heading because it usually looks better for the headings to be closer together than a paragraph followed by a heading should be.
### When a heading comes after a paragraph …
When a heading comes after a paragraph, we need a bit more space, like I already mentioned above. Now let's see what a more complex list would look like.
- **I often do this thing where list items have headings.**
For some reason I think this looks cool which is unfortunate because it's pretty annoying to get the styles right.
I often have two or three paragraphs in these list items, too, so the hard part is getting the spacing between the paragraphs, list item heading, and separate list items to all make sense. Pretty tough honestly, you could make a strong argument that you just shouldn't write this way.
- **Since this is a list, I need at least two items.**
I explained what I'm doing already in the previous list item, but a list wouldn't be a list if it only had one item, and we really want this to look realistic. That's why I've added this second list item so I actually have something to look at when writing the styles.
- **It's not a bad idea to add a third item either.**
I think it probably would've been fine to just use two items but three is definitely not worse, and since I seem to be having no trouble making up arbitrary things to type, I might as well include it.
After this sort of list I usually have a closing statement or paragraph, because it kinda looks weird jumping right to a heading.
## Code should look okay by default.
I think most people are going to use [highlight.js](https://highlightjs.org/) or [Prism](https://prismjs.com/) or something if they want to style their code blocks but it wouldn't hurt to make them look _okay_ out of the box, even with no syntax highlighting.
Here's what a default `tailwind.config.js` file looks like at the time of writing:
```js
module.exports = {
purge: [],
theme: {
extend: {},
},
variants: {},
plugins: [],
};
```
Hopefully that looks good enough to you.
### What about nested lists?
Nested lists basically always look bad which is why editors like Medium don't even let you do it, but I guess since some of you goofballs are going to do it we have to carry the burden of at least making it work.
1. **Nested lists are rarely a good idea.**
- You might feel like you are being really "organized" or something but you are just creating a gross shape on the screen that is hard to read.
- Nested navigation in UIs is a bad idea too, keep things as flat as possible.
- Nesting tons of folders in your source code is also not helpful.
2. **Since we need to have more items, here's another one.**
- I'm not sure if we'll bother styling more than two levels deep.
- Two is already too much, three is guaranteed to be a bad idea.
- If you nest four levels deep you belong in prison.
3. **Two items isn't really a list, three is good though.**
- Again please don't nest lists if you want people to actually read your content.
- Nobody wants to look at this.
- I'm upset that we even have to bother styling this.
The most annoying thing about lists in Markdown is that `<li>` elements aren't given a child `<p>` tag unless there are multiple paragraphs in the list item. That means I have to worry about styling that annoying situation too.
- **For example, here's another nested list.**
But this time with a second paragraph.
- These list items won't have `<p>` tags
- Because they are only one line each
- **But in this second top-level list item, they will.**
This is especially annoying because of the spacing on this paragraph.
- As you can see here, because I've added a second line, this list item now has a `<p>` tag.
This is the second line I'm talking about by the way.
- Finally here's another list item so it's more like a list.
- A closing list item, but with no nested list, because why not?
And finally a sentence to close off this section.
## There are other elements we need to style
I almost forgot to mention links, like [this link to the Tailwind CSS website](https://tailwindcss.com). We almost made them blue but that's so yesterday, so we went with dark gray, feels edgier.
We even included table styles, check it out:
| Wrestler | Origin | Finisher |
| ----------------------- | ------------ | ------------------ |
| Bret "The Hitman" Hart | Calgary, AB | Sharpshooter |
| Stone Cold Steve Austin | Austin, TX | Stone Cold Stunner |
| Randy Savage | Sarasota, FL | Elbow Drop |
| Vader | Boulder, CO | Vader Bomb |
| Razor Ramon | Chuluota, FL | Razor's Edge |
We also need to make sure inline code looks good, like if I wanted to talk about `<span>` elements or tell you the good news about `@tailwindcss/typography`.
### Sometimes I even use `code` in headings
Even though it's probably a bad idea, and historically I've had a hard time making it look good. This _"wrap the code blocks in backticks"_ trick works pretty well though really.
Another thing I've done in the past is put a `code` tag inside of a link, like if I wanted to tell you about the [`tailwindcss/docs`](https://github.com/tailwindcss/docs) repository. I don't love that there is an underline below the backticks but it is absolutely not worth the madness it would require to avoid it.
#### We haven't used an `h4` yet
But now we have. Please don't use `h5` or `h6` in your content, Medium only supports two heading levels for a reason, you animals. I honestly considered using a `before` pseudo-element to scream at you if you use an `h5` or `h6`.
We don't style them at all out of the box because `h4` elements are already so small that they are the same size as the body copy. What are we supposed to do with an `h5`, make it _smaller_ than the body copy? No thanks.
### We still need to think about stacked headings though.
#### Let's make sure we don't screw that up with `h4` elements, either.
Phew, with any luck we have styled the headings above this text and they look pretty good.
Let's add a closing paragraph here so things end with a decently sized block of text. I can't explain why I want things to end that way but I have to assume it's because I think things will look weird or unbalanced if there is a heading too close to the end of the document.
What I've written here is probably long enough, but adding this final sentence can't hurt.
## GitHub Flavored Markdown
I've also added support for GitHub Flavored Mardown using `remark-gfm`.
With `remark-gfm`, we get a few extra features in our markdown. Example: autolink literals.
A link like www.example.com or https://example.com would automatically be converted into an `a` tag.
This works for email links too: contact@example.com.

View File

@ -0,0 +1,213 @@
---
title: What is MkSaaS?
description: MkSaaS is the best boilerplate for building AI SaaS websites.
date: 2024-11-24T12:00:00.000Z
published: true
categories: [news, guide]
author: mksaas
---
Until now, trying to style an article, document, or blog post with Tailwind has been a tedious task that required a keen eye for typography and a lot of complex custom CSS.
By default, Tailwind removes all of the default browser styling from paragraphs, headings, lists and more. This ends up being really useful for building application UIs because you spend less time undoing user-agent styles, but when you _really are_ just trying to style some content that came from a rich-text editor in a CMS or a markdown file, it can be surprising and unintuitive.
We get lots of complaints about it actually, with people regularly asking us things like:
> Why is Tailwind removing the default styles on my `h1` elements? How do I disable this? What do you mean I lose all the other base styles too?
> We hear you, but we're not convinced that simply disabling our base styles is what you really want. You don't want to have to remove annoying margins every time you use a `p` element in a piece of your dashboard UI. And I doubt you really want your blog posts to use the user-agent styles either — you want them to look _awesome_, not awful.
The `@tailwindcss/typography` plugin is our attempt to give you what you _actually_ want, without any of the downsides of doing something stupid like disabling our base styles.
It adds a new `prose` class that you can slap on any block of vanilla HTML content and turn it into a beautiful, well-formatted document:
```html
<article class="prose">
<h1>Garlic bread with cheese: What the science tells us</h1>
<p>
For years parents have espoused the health benefits of eating garlic bread
with cheese to their children, with the food earning such an iconic status
in our culture that kids will often dress up as warm, cheesy loaf for
Halloween.
</p>
<p>
But a recent study shows that the celebrated appetizer may be linked to a
series of rabies cases springing up around the country.
</p>
</article>
```
For more information about how to use the plugin and the features it includes, [read the documentation](https://github.com/tailwindcss/typography/blob/master/README.md).
---
## What to expect from here on out
What follows from here is just a bunch of absolute nonsense I've written to dogfood the plugin itself. It includes every sensible typographic element I could think of, like **bold text**, unordered lists, ordered lists, code blocks, block quotes, _and even italics_.
It's important to cover all of these use cases for a few reasons:
1. We want everything to look good out of the box.
2. Really just the first reason, that's the whole point of the plugin.
3. Here's a third pretend reason though a list with three items looks more realistic than a list with two items.
Now we're going to try out another header style.
### Typography should be easy
So that's a header for you — with any luck if we've done our job correctly that will look pretty reasonable.
Something a wise person once told me about typography is:
> Typography is pretty important if you don't want your stuff to look like trash. Make it good then it won't be bad.
It's probably important that images look okay here by default as well:
<Image
src="/images/blog/mkdirs-opengraph.png"
width="718"
height="404"
alt="Image"
/>
Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old.
Now I'm going to show you an example of an unordered list to make sure that looks good, too:
- So here is the first item in this list.
- In this example we're keeping the items short.
- Later, we'll use longer, more complex list items.
And that's the end of this section.
## What if we stack headings?
### We should make sure that looks good, too.
Sometimes you have headings directly underneath each other. In those cases you often have to undo the top margin on the second heading because it usually looks better for the headings to be closer together than a paragraph followed by a heading should be.
### When a heading comes after a paragraph …
When a heading comes after a paragraph, we need a bit more space, like I already mentioned above. Now let's see what a more complex list would look like.
- **I often do this thing where list items have headings.**
For some reason I think this looks cool which is unfortunate because it's pretty annoying to get the styles right.
I often have two or three paragraphs in these list items, too, so the hard part is getting the spacing between the paragraphs, list item heading, and separate list items to all make sense. Pretty tough honestly, you could make a strong argument that you just shouldn't write this way.
- **Since this is a list, I need at least two items.**
I explained what I'm doing already in the previous list item, but a list wouldn't be a list if it only had one item, and we really want this to look realistic. That's why I've added this second list item so I actually have something to look at when writing the styles.
- **It's not a bad idea to add a third item either.**
I think it probably would've been fine to just use two items but three is definitely not worse, and since I seem to be having no trouble making up arbitrary things to type, I might as well include it.
After this sort of list I usually have a closing statement or paragraph, because it kinda looks weird jumping right to a heading.
## Code should look okay by default.
I think most people are going to use [highlight.js](https://highlightjs.org/) or [Prism](https://prismjs.com/) or something if they want to style their code blocks but it wouldn't hurt to make them look _okay_ out of the box, even with no syntax highlighting.
Here's what a default `tailwind.config.js` file looks like at the time of writing:
```js
module.exports = {
purge: [],
theme: {
extend: {},
},
variants: {},
plugins: [],
};
```
Hopefully that looks good enough to you.
### What about nested lists?
Nested lists basically always look bad which is why editors like Medium don't even let you do it, but I guess since some of you goofballs are going to do it we have to carry the burden of at least making it work.
1. **Nested lists are rarely a good idea.**
- You might feel like you are being really "organized" or something but you are just creating a gross shape on the screen that is hard to read.
- Nested navigation in UIs is a bad idea too, keep things as flat as possible.
- Nesting tons of folders in your source code is also not helpful.
2. **Since we need to have more items, here's another one.**
- I'm not sure if we'll bother styling more than two levels deep.
- Two is already too much, three is guaranteed to be a bad idea.
- If you nest four levels deep you belong in prison.
3. **Two items isn't really a list, three is good though.**
- Again please don't nest lists if you want people to actually read your content.
- Nobody wants to look at this.
- I'm upset that we even have to bother styling this.
The most annoying thing about lists in Markdown is that `<li>` elements aren't given a child `<p>` tag unless there are multiple paragraphs in the list item. That means I have to worry about styling that annoying situation too.
- **For example, here's another nested list.**
But this time with a second paragraph.
- These list items won't have `<p>` tags
- Because they are only one line each
- **But in this second top-level list item, they will.**
This is especially annoying because of the spacing on this paragraph.
- As you can see here, because I've added a second line, this list item now has a `<p>` tag.
This is the second line I'm talking about by the way.
- Finally here's another list item so it's more like a list.
- A closing list item, but with no nested list, because why not?
And finally a sentence to close off this section.
## There are other elements we need to style
I almost forgot to mention links, like [this link to the Tailwind CSS website](https://tailwindcss.com). We almost made them blue but that's so yesterday, so we went with dark gray, feels edgier.
We even included table styles, check it out:
| Wrestler | Origin | Finisher |
| ----------------------- | ------------ | ------------------ |
| Bret "The Hitman" Hart | Calgary, AB | Sharpshooter |
| Stone Cold Steve Austin | Austin, TX | Stone Cold Stunner |
| Randy Savage | Sarasota, FL | Elbow Drop |
| Vader | Boulder, CO | Vader Bomb |
| Razor Ramon | Chuluota, FL | Razor's Edge |
We also need to make sure inline code looks good, like if I wanted to talk about `<span>` elements or tell you the good news about `@tailwindcss/typography`.
### Sometimes I even use `code` in headings
Even though it's probably a bad idea, and historically I've had a hard time making it look good. This _"wrap the code blocks in backticks"_ trick works pretty well though really.
Another thing I've done in the past is put a `code` tag inside of a link, like if I wanted to tell you about the [`tailwindcss/docs`](https://github.com/tailwindcss/docs) repository. I don't love that there is an underline below the backticks but it is absolutely not worth the madness it would require to avoid it.
#### We haven't used an `h4` yet
But now we have. Please don't use `h5` or `h6` in your content, Medium only supports two heading levels for a reason, you animals. I honestly considered using a `before` pseudo-element to scream at you if you use an `h5` or `h6`.
We don't style them at all out of the box because `h4` elements are already so small that they are the same size as the body copy. What are we supposed to do with an `h5`, make it _smaller_ than the body copy? No thanks.
### We still need to think about stacked headings though.
#### Let's make sure we don't screw that up with `h4` elements, either.
Phew, with any luck we have styled the headings above this text and they look pretty good.
Let's add a closing paragraph here so things end with a decently sized block of text. I can't explain why I want things to end that way but I have to assume it's because I think things will look weird or unbalanced if there is a heading too close to the end of the document.
What I've written here is probably long enough, but adding this final sentence can't hurt.
## GitHub Flavored Markdown
I've also added support for GitHub Flavored Mardown using `remark-gfm`.
With `remark-gfm`, we get a few extra features in our markdown. Example: autolink literals.
A link like www.example.com or https://example.com would automatically be converted into an `a` tag.
This works for email links too: contact@example.com.

View File

@ -0,0 +1,5 @@
---
slug: guide
name: Guide
description: Guides about MkSaaS Boilerplate
---

View File

@ -0,0 +1,5 @@
---
slug: news
name: News
description: News about MkSaaS Boilerplate
---

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 309 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 690 KiB

View File

@ -0,0 +1,75 @@
import type { Metadata } from 'next';
import { notFound } from 'next/navigation';
import { allPosts } from 'content-collections';
import { BlogPost } from '@/components/blog/blog-post';
import { getBaseUrl } from '@/lib/urls/get-base-url';
import type { NextPageProps } from '@/types/next-page-props';
import '@/app/mdx.css';
/**
* Gets the blog post from the params
* @param props - The props of the page
* @returns The blog post
*
* How it works:
* 1. /blog/first-post:
* params.slug = ["first-post"]
* slug becomes "first-post" after join('/')
* Matches post where slugAsParams === "first-post"
*
* 2. /blog/2023/year-review:
* params.slug = ["2023", "year-review"]
* slug becomes "2023/year-review" after join('/')
* Matches post where slugAsParams === "2023/year-review"
*/
async function getBlogPostFromParams(props: NextPageProps) {
const params = await props.params;
if (!params) {
return null;
}
const slug =
(Array.isArray(params.slug) ? params.slug?.join('/') : params.slug) || '';
const post = allPosts.find(
(post) =>
post.slugAsParams === slug || (!slug && post.slugAsParams === 'index')
);
if (!post) {
return null;
}
return post;
}
export async function generateMetadata(
props: NextPageProps
): Promise<Metadata> {
const post = await getBlogPostFromParams(props);
if (!post) {
return {};
}
return {
title: post.title,
description: post.description,
openGraph: {
title: post.title,
description: post.description,
type: 'article',
url: `${getBaseUrl()}${post.slug}`
}
};
}
export async function generateStaticParams() {
return allPosts.map((post) => ({
slug: post.slugAsParams.split('/')
}));
}
export default async function BlogPostPage(props: NextPageProps) {
const post = await getBlogPostFromParams(props);
if (!post) {
return notFound();
}
return <BlogPost post={post} />;
}

12
src/app/blog/page.tsx Normal file
View File

@ -0,0 +1,12 @@
import * as React from 'react';
import type { Metadata } from 'next';
import { BlogPosts } from '@/components/blog/blog-posts';
import { createTitle } from '@/lib/utils';
export const metadata: Metadata = {
title: createTitle('Blog')
};
export default function BlogPage(): React.JSX.Element {
return <BlogPosts />;
}

29
src/app/config/blog.ts Normal file
View File

@ -0,0 +1,29 @@
export const BLOG_CATEGORIES: {
title: string;
slug: "news" | "education";
description: string;
}[] = [
{
title: "News",
slug: "news",
description: "Updates and announcements from MkSaaS Starter.",
},
{
title: "Education",
slug: "education",
description: "Educational content about SaaS management.",
},
];
export const BLOG_AUTHORS = {
mksaas: {
name: "mksaas",
image: "/_static/avatars/mksaas.png",
twitter: "mksaas",
},
mkdirs: {
name: "mkdirs",
image: "/_static/avatars/mkdirs.png",
twitter: "mkdirs",
},
};

View File

@ -0,0 +1,15 @@
import type { ObjectValues } from '@/types/object-values';
import packageInfo from '../../../package.json';
/**
* TODO: update
*/
export const AppInfo = {
APP_NAME: process.env.NEXT_PUBLIC_APP_NAME ?? '',
APP_DESCRIPTION: 'The best AI SaaS template',
PRODUCTION: process.env.NODE_ENV === 'production',
VERSION: packageInfo.version
} as const;
export type AppInfo = ObjectValues<typeof AppInfo>;

28
src/app/mdx.css Normal file
View File

@ -0,0 +1,28 @@
/**
* TODO: update
*/
[data-rehype-pretty-code-figure] code {
@apply grid min-w-full break-words rounded-none border-0 bg-transparent p-0;
counter-reset: line;
box-decoration-break: clone;
}
[data-rehype-pretty-code-figure] [data-line] {
@apply inline-block min-h-[1rem] w-full px-4 py-0.5;
}
[data-rehype-pretty-code-figure] [data-line-numbers] [data-line] {
@apply px-2;
}
[data-rehype-pretty-code-figure] .line-highlighted span {
@apply relative;
}
[data-rehype-pretty-code-title] {
@apply mt-2 px-4 pt-6 text-sm font-medium text-foreground;
}
[data-rehype-pretty-code-title] + pre {
@apply mt-2;
}

View File

@ -0,0 +1,78 @@
import * as React from 'react';
import Link from 'next/link';
import { format } from 'date-fns';
import { Mdx } from '@/components/marketing/blog/mdx-component';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Separator } from '@/components/ui/separator';
import { getInitials } from '@/lib/utils';
import { Post } from 'content-collections';
type BlogPostProps = {
post: Post;
};
export function BlogPost({ post }: BlogPostProps): React.JSX.Element {
console.log(post);
console.log(post.author);
return (
<div className="border-b">
<div className="container mx-auto flex max-w-3xl flex-col space-y-4 py-20">
<div className="mx-auto w-full min-w-0">
<Link
href="/blog"
className="group mb-12 flex items-center space-x-1 text-base leading-none text-foreground duration-200"
>
<span className="transition-transform group-hover:-translate-x-0.5">
</span>
<span>All posts</span>
</Link>
<div className="space-y-8">
<div className="flex flex-row items-center justify-between gap-4 text-base text-muted-foreground">
<span className="flex flex-row items-center gap-2">
{post.categories.map((c) => c.name).join(', ')}
</span>
<span className="flex flex-row items-center gap-2">
<time dateTime={post.date}>
{format(post.date, 'dd MMM yyyy')}
</time>
</span>
</div>
<h1 className="font-heading text-3xl font-semibold tracking-tighter xl:text-5xl">
{post.title}
</h1>
<p className="text-lg text-muted-foreground">{post.description}</p>
<div className="flex flex-row items-center justify-between">
<div className="flex flex-row items-center gap-2">
<Avatar className="relative size-7 flex-none rounded-full">
<AvatarImage
src={post.author?.avatar}
alt="avatar"
/>
<AvatarFallback className="size-7 text-[10px]">
{getInitials(post.author?.name ?? '')}
</AvatarFallback>
</Avatar>
<span>{post.author?.name ?? ''}</span>
</div>
<div>{estimateReadingTime(post.body.raw)}</div>
</div>
</div>
</div>
</div>
<Separator />
<div className="container mx-auto flex max-w-3xl py-20">
<Mdx code={post.body.code} />
</div>
</div>
);
}
function estimateReadingTime(
text: string,
wordsPerMinute: number = 250
): string {
const words = text.trim().split(/\s+/).length;
const minutes = Math.ceil(words / wordsPerMinute);
return minutes === 1 ? '1 minute read' : `${minutes} minutes read`;
}

View File

@ -0,0 +1,73 @@
import * as React from 'react';
import Link from 'next/link';
import { allPosts } from 'content-collections';
import { format, isBefore } from 'date-fns';
import { ArrowRightIcon } from 'lucide-react';
import { GridSection } from '@/components/marketing/fragments/grid-section';
import { SiteHeading } from '@/components/marketing/fragments/site-heading';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { FillRemainingSpace } from '@/components/fill-remaining-space';
import { getBaseUrl } from '@/lib/urls/get-base-url';
import { getInitials } from '@/lib/utils';
export function BlogPosts(): React.JSX.Element {
return (
<GridSection>
<div className="container space-y-20 py-20">
<SiteHeading
badge="Blog Posts"
title="Insights & News"
description="Learn more about our products and the latest news."
/>
<div className="grid gap-x-12 gap-y-6 divide-y md:grid-cols-2 md:gap-x-6 md:divide-none xl:grid-cols-3">
{allPosts
.filter((post) => post.published)
.slice()
.sort((a, b) => (isBefore(a.date, b.date) ? 1 : -1))
.map((post, index) => (
<Link
key={index}
href={`${getBaseUrl()}${post.slug}`}
className="md:duration-2000 flex h-full flex-col space-y-4 text-clip border-dashed py-6 md:rounded-2xl md:px-6 md:shadow md:transition-shadow md:hover:shadow-xl dark:md:bg-accent/40 dark:md:hover:bg-accent"
>
<div className="flex flex-row items-center justify-between text-muted-foreground">
<span className="text-sm">{post.categories.map((c) => c.name).join(', ')}</span>
<time
className="text-sm"
dateTime={post.date}
>
{format(post.date, 'dd MMM yyyy')}
</time>
</div>
<h2 className="text-lg font-semibold md:mb-4 md:text-xl lg:mb-6">
{post.title}
</h2>
<p className="line-clamp-3 text-muted-foreground md:mb-4 lg:mb-6">
{post.description}
</p>
<FillRemainingSpace />
<div className="flex flex-1 shrink flex-row items-center justify-between">
<div className="flex flex-row items-center gap-2">
<Avatar className="relative size-7 flex-none rounded-full">
<AvatarImage
src={post.author?.avatar}
alt="avatar"
/>
<AvatarFallback className="size-7 text-[10px]">
{getInitials(post.author?.name ?? '')}
</AvatarFallback>
</Avatar>
<span className="text-sm">{post.author?.name ?? ''}</span>
</div>
<div className="group flex items-center gap-2 text-sm duration-200 hover:underline">
Read more
<ArrowRightIcon className="size-4 shrink-0 transition-transform group-hover:translate-x-0.5" />
</div>
</div>
</Link>
))}
</div>
</div>
</GridSection>
);
}

View File

@ -0,0 +1,10 @@
import * as React from 'react';
export function FillRemainingSpace(): React.JSX.Element {
return (
<div
aria-hidden="true"
className="flex-1 shrink"
/>
);
}

View File

@ -0,0 +1,30 @@
import * as React from 'react';
import { ComponentProps } from 'react';
import {
Alert,
AlertDescription,
AlertTitle
} from '@/components/ui/alert';
type CalloutProps = ComponentProps<typeof Alert> & {
icon?: string;
title?: string;
};
/**
* TODO: update
*/
export function Callout({
title,
children,
icon,
...props
}: CalloutProps): React.JSX.Element {
return (
<Alert {...props}>
{icon && <span className="mr-4 text-2xl">{icon}</span>}
{title && <AlertTitle>{title}</AlertTitle>}
<AlertDescription>{children}</AlertDescription>
</Alert>
);
}

View File

@ -0,0 +1,264 @@
'use client';
import * as React from 'react';
import Image from 'next/image';
import Link from 'next/link';
import { useMDXComponent } from '@content-collections/mdx/react';
import { Callout } from '@/components/marketing/blog/callout';
import {
Accordion,
AccordionContent,
AccordionItem,
AccordionTrigger
} from '@/components/ui/accordion';
import {
Tabs,
TabsContent,
TabsList,
TabsTrigger
} from '@/components/ui/tabs';
import { cn } from '@/lib/utils';
const components = {
h1: ({ className, ...props }: React.HTMLAttributes<HTMLHeadingElement>) => (
<h1
className={cn(
'font-heading mt-2 scroll-m-24 text-4xl font-bold',
className
)}
{...props}
/>
),
h2: ({ className, ...props }: React.HTMLAttributes<HTMLHeadingElement>) => (
<h2
className={cn(
'font-heading mb-4 mt-12 scroll-m-24 text-2xl font-semibold leading-8 tracking-tight',
className
)}
{...props}
/>
),
h3: ({ className, ...props }: React.HTMLAttributes<HTMLHeadingElement>) => (
<h3
className={cn(
'font-heading mt-8 scroll-m-24 text-xl font-semibold tracking-tight',
className
)}
{...props}
/>
),
h4: ({ className, ...props }: React.HTMLAttributes<HTMLHeadingElement>) => (
<h4
className={cn(
'font-heading mt-8 scroll-m-24 text-lg font-semibold tracking-tight',
className
)}
{...props}
/>
),
h5: ({ className, ...props }: React.HTMLAttributes<HTMLHeadingElement>) => (
<h5
className={cn(
'mt-8 scroll-m-24 text-base font-semibold tracking-tight',
className
)}
{...props}
/>
),
h6: ({ className, ...props }: React.HTMLAttributes<HTMLHeadingElement>) => (
<h6
className={cn(
'mt-8 scroll-m-24 text-sm font-semibold tracking-tight',
className
)}
{...props}
/>
),
a: ({ className, ...props }: React.HTMLAttributes<HTMLAnchorElement>) => (
<a
className={cn(
'font-medium text-blue-500 underline underline-offset-4',
className
)}
{...props}
/>
),
p: ({ className, ...props }: React.HTMLAttributes<HTMLParagraphElement>) => (
<p
className={cn('mt-6 leading-7', className)}
{...props}
/>
),
ul: ({ className, ...props }: React.HTMLAttributes<HTMLUListElement>) => (
<ul
className={cn('my-6 ml-6 list-disc', className)}
{...props}
/>
),
ol: ({ className, ...props }: React.HTMLAttributes<HTMLOListElement>) => (
<ol
className={cn('my-6 ml-6 list-decimal', className)}
{...props}
/>
),
li: ({ className, ...props }: React.HTMLAttributes<HTMLElement>) => (
<li
className={cn('mt-2', className)}
{...props}
/>
),
blockquote: ({ className, ...props }: React.HTMLAttributes<HTMLElement>) => (
<blockquote
className={cn('mt-6 border-l-2 pl-6 italic', className)}
{...props}
/>
),
img: ({
className,
alt,
...props
}: React.ImgHTMLAttributes<HTMLImageElement>) => (
<img
className={cn('rounded-md', className)}
alt={alt}
{...props}
/>
),
hr: ({ ...props }: React.HTMLAttributes<HTMLHRElement>) => (
<hr
className="my-4 md:my-8"
{...props}
/>
),
table: ({ className, ...props }: React.HTMLAttributes<HTMLTableElement>) => (
<div className="my-6 w-full overflow-y-auto rounded-none">
<table
className={cn('w-full overflow-hidden rounded-none', className)}
{...props}
/>
</div>
),
tr: ({ className, ...props }: React.HTMLAttributes<HTMLTableRowElement>) => (
<tr
className={cn('m-0 border-t p-0', className)}
{...props}
/>
),
th: ({ className, ...props }: React.HTMLAttributes<HTMLTableCellElement>) => (
<th
className={cn(
'border px-4 py-2 text-left font-bold [&[align=center]]:text-center [&[align=right]]:text-right',
className
)}
{...props}
/>
),
td: ({ className, ...props }: React.HTMLAttributes<HTMLTableCellElement>) => (
<td
className={cn(
'border px-4 py-2 text-left [&[align=center]]:text-center [&[align=right]]:text-right',
className
)}
{...props}
/>
),
pre: ({ className, ...props }: React.HTMLAttributes<HTMLElement>) => (
<pre
className={cn(
'relative mt-4 max-w-[calc(100vw-64px)] overflow-x-auto rounded bg-muted px-1 py-2 font-mono text-sm',
className
)}
{...props}
/>
),
code: ({ className, ...props }: React.HTMLAttributes<HTMLElement>) => (
<code
className={cn(
'relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-sm',
className
)}
{...props}
/>
),
Accordion,
AccordionContent: ({
className,
...props
}: React.ComponentProps<typeof AccordionContent>) => (
<AccordionContent
className={cn('[&>p]:m-0', className)}
{...props}
/>
),
AccordionItem,
AccordionTrigger,
Callout,
Image,
Tabs: ({
className,
...props
}: React.ComponentProps<typeof Tabs>) => (
<Tabs
className={cn('relative mt-6 w-full', className)}
{...props}
/>
),
TabsList: ({
className,
...props
}: React.ComponentProps<typeof TabsList>) => (
<TabsList
className={cn('w-full border-b', className)}
{...props}
/>
),
TabsTrigger: ({
className,
...props
}: React.ComponentProps<typeof TabsTrigger>) => (
<TabsTrigger
className={cn('', className)}
{...props}
/>
),
TabsContent: ({
className,
...props
}: React.ComponentProps<typeof TabsContent>) => (
<TabsContent
className={cn('p-4', className)}
{...props}
/>
),
Link: ({ className, ...props }: React.ComponentProps<typeof Link>) => (
<Link
className={cn('font-medium underline underline-offset-4', className)}
{...props}
/>
),
LinkedCard: ({ className, ...props }: React.ComponentProps<typeof Link>) => (
<Link
className={cn(
'flex w-full flex-col items-center rounded-xl border bg-card p-6 text-card-foreground shadow transition-colors hover:bg-muted/50 sm:p-10',
className
)}
{...props}
/>
)
};
type MdxProps = {
code: string;
};
/**
* TODO: update
*/
export function Mdx({ code }: MdxProps) {
const Component = useMDXComponent(code);
return (
<div className="mdx">
<Component components={components} />
</div>
);
}

View File

@ -0,0 +1,39 @@
import * as React from 'react';
import { cn } from '@/lib/utils';
export type GridSectionProps = React.HtmlHTMLAttributes<HTMLDivElement> & {
hideVerticalGridLines?: boolean;
hideBottomGridLine?: boolean;
containerProps?: React.HtmlHTMLAttributes<HTMLDivElement>;
};
/**
* TODO: remove
*/
export function GridSection({
children,
hideVerticalGridLines,
hideBottomGridLine,
containerProps: { className = '', ...containerProps } = {},
...other
}: GridSectionProps): React.JSX.Element {
return (
<section {...other}>
<div
className={cn('px-2 sm:container', className)}
{...containerProps}
>
<div className="relative grid">
{!hideVerticalGridLines && (
<>
<div className="absolute inset-y-0 block w-px bg-border" />
<div className="absolute inset-y-0 right-0 w-px bg-border" />
</>
)}
{children}
</div>
</div>
{!hideBottomGridLine && <div className="h-px w-full bg-border" />}
</section>
);
}

View File

@ -0,0 +1,38 @@
import * as React from 'react';
import { Badge } from '@/components/ui/badge';
export type SiteHeadingProps = {
badge?: React.ReactNode;
title?: React.ReactNode;
description?: React.ReactNode;
};
/**
* TODO: remove
*/
export function SiteHeading({
badge,
title,
description
}: SiteHeadingProps): React.JSX.Element {
return (
<div className="mx-auto flex max-w-5xl flex-col items-center gap-6 text-center">
{badge && (
<Badge
variant="outline"
className="h-8 rounded-full px-3 text-sm font-medium shadow-sm"
>
{badge}
</Badge>
)}
{title && (
<h1 className="text-pretty text-5xl font-bold lg:text-6xl">{title}</h1>
)}
{description && (
<p className="text-lg text-muted-foreground lg:text-xl">
{description}
</p>
)}
</div>
);
}

View File

@ -0,0 +1,17 @@
// import { DEFAULT_LOCALE } from '@/lib/i18n/locale';
const baseUrl =
process.env.NEXT_PUBLIC_BASE_URL ??
`http://localhost:${process.env.PORT ?? 3000}`;
export function getBaseUrl(): string {
return baseUrl;
}
// export function shouldAppendLocale(locale?: string | null): boolean {
// return !!locale && locale !== DEFAULT_LOCALE && locale !== 'default';
// }
// export function getBaseUrl(locale?: string | null): string {
// return shouldAppendLocale(locale) ? `${baseUrl}/${locale}` : baseUrl;
// }

View File

@ -1,6 +1,53 @@
import { AppInfo } from "@/app/constants/app-info";
import { type ClassValue, clsx } from "clsx";
import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
/**
* Creates a title for the page
* @param title - The title of the page
* @param addSuffix - Whether to add the app name as a suffix
* @returns The title for the page
*/
export function createTitle(title: string, addSuffix: boolean = true): string {
if (!addSuffix) {
return title;
}
if (!title) {
return AppInfo.APP_NAME;
}
return `${title} | ${AppInfo.APP_NAME}`;
}
/**
* Gets the initials of a name used for avatar placeholders display in UIs.
*
* This function extracts initials from a name by:
* - Taking first letters of up to 2 words
* - Converting them to uppercase
* - Joining them together
*
* Examples:
* "John Doe" "JD"
* "Alice Bob Charles" "AB" (only first 2 words)
* "jane" "J"
* "John Doe" "JD" (handles multiple spaces)
*
* @param name - The name to get the initials of
* @returns The initials of the name
*/
export function getInitials(name: string): string {
if (!name) {
return '';
}
return name
.replace(/\s+/, ' ')
.split(' ')
.slice(0, 2)
.map((v) => v && v[0].toUpperCase())
.join('');
}

View File

@ -0,0 +1,32 @@
/**
* TODO: update
*
* Types for Next.js App Router page components
*
* Params: Route parameters from dynamic segments
* Example: For route /blog/[slug] with URL /blog/hello-world
* params = { slug: "hello-world" }
* For catch-all route /blog/[...slug] with URL /blog/2023/01/post
* params = { slug: ["2023", "01", "post"] }
*/
export type Params = Record<string, string | Array<string> | undefined>;
/**
* SearchParams: URL query parameters
* Example: For URL /?page=1&sort=desc
* searchParams = { page: "1", sort: "desc" }
* For URL /?tags=react&tags=nextjs
* searchParams = { tags: ["react", "nextjs"] }
*/
export type SearchParams = {
[key: string]: string | string[] | undefined;
};
/**
* Props passed to Next.js page components in App Router
* Both params and searchParams are Promises that resolve to their respective types
*/
export type NextPageProps = {
params: Promise<Params>;
searchParams: Promise<SearchParams>;
};

View File

@ -0,0 +1,26 @@
/**
* TODO: update
*
* ObjectValues<T> is a utility type that extracts a union type of all value types in an object
*
* For example, in the AppInfo use case:
* const AppInfo = {
* APP_NAME: string,
* APP_DESCRIPTION: string,
* PRODUCTION: boolean,
* VERSION: string
* } as const
*
* type AppInfo = ObjectValues<typeof AppInfo>
* equals to: type AppInfo = string | boolean
*
* How it works:
* 1. keyof T gets the union of all keys in object T
* 2. T[keyof T] uses indexed access to get all value types
*
* Benefits:
* - Automatically extracts all possible value types from an object
* - Makes type definitions more precise and automated
* - Reduces manual type maintenance work
*/
export type ObjectValues<T> = T[keyof T];