Refactor CMS to handle ContentLayer and WordPress platforms
This commit refactors the CMS to handle two platforms: ContentLayer and WordPress. The CMS layer is abstracted into a core package, and separate implementations for each platform are created. This change allows the app to switch the CMS type based on environment variable, which can improve the flexibility of content management. It also updates several functions in the `server-sitemap.xml` route to accommodate these changes and generate sitemaps based on the CMS client. Further, documentation content and posts have been relocated to align with the new structure. Notably, this refactor is a comprehensive update to the way the CMS is structured and managed.
This commit is contained in:
9
packages/cms/contentlayer/README.md
Normal file
9
packages/cms/contentlayer/README.md
Normal file
@@ -0,0 +1,9 @@
|
||||
# CMS/Contentlayer - @kit/contentlayer
|
||||
|
||||
Implementation of the CMS layer using the [Contentlayer](https://contentlayer.dev) library.
|
||||
|
||||
This implementation is used when the host app's environment variable is set as:
|
||||
|
||||
```
|
||||
CMS_TYPE=contentlayer
|
||||
```
|
||||
@@ -0,0 +1,85 @@
|
||||
---
|
||||
title: Installing Makerkit
|
||||
label: Installing Makerkit
|
||||
description: Learn how to install Makerkit on your local machine
|
||||
---
|
||||
|
||||
If you have bought a license for MakerKit, you have access to all the
|
||||
repositories built by the MakerKit team. In this document, we will learn how
|
||||
to fetch and install the codebase.
|
||||
|
||||
### Requirements
|
||||
|
||||
To get started with the Next.js and Supabase SaaS template, we need to ensure
|
||||
you install the required software.
|
||||
|
||||
- Node.js
|
||||
- Git
|
||||
- Docker
|
||||
|
||||
### Getting Started with MakerKit
|
||||
|
||||
You have two choices for cloning the repository:
|
||||
|
||||
1. forking the original repository and cloning it from your fork
|
||||
2. cloning it manually from the original repository
|
||||
|
||||
#### Clone the repository
|
||||
|
||||
To get the codebase on your local machine using the original repository, clone the repository with the
|
||||
following command:
|
||||
|
||||
```
|
||||
git clone --depth=1 git@github.com:makerkit/next-supabase-saas-kit-lite.git my-saas
|
||||
```
|
||||
|
||||
The command above clones the repository in the folder `my-saas` which
|
||||
you can rename it with the name of your project.
|
||||
|
||||
If you forked the repository, point it to your fork instead of the original.
|
||||
|
||||
#### Initializing Git
|
||||
|
||||
Now, run the following commands for:
|
||||
|
||||
1. Moving into the folder
|
||||
2. Reinitialize your git repository
|
||||
|
||||
Personally I re-initialize the Git repository, but it's not required.
|
||||
|
||||
```
|
||||
cd my-saas
|
||||
rm -rf .git
|
||||
git init
|
||||
```
|
||||
|
||||
### Setting the Upstream repository, and fetching updates
|
||||
|
||||
Now, we can add the original Makerkit repository as "upstream" so we can fetch updates from the main repository:
|
||||
|
||||
```
|
||||
git remote add upstream git@github.com:makerkit/next-supabase-saas-kit-lite.git
|
||||
git add .
|
||||
git commit -a -m "Initial Commit"
|
||||
```
|
||||
|
||||
In this way, to fetch updates (after committing your files), simply run:
|
||||
|
||||
```
|
||||
git pull upstream main --allow-unrelated-histories
|
||||
```
|
||||
|
||||
You'll likely run into conflicts when running this command, so carefully choose the changes (sorry!).
|
||||
|
||||
### Installing the Node dependencies
|
||||
|
||||
Finally, we can install the NodeJS dependencies with `npm`:
|
||||
|
||||
```
|
||||
npm i
|
||||
```
|
||||
|
||||
While the application code is fully working, we now need to set up your Supabase
|
||||
project.
|
||||
|
||||
So let's jump on to the next step!
|
||||
@@ -0,0 +1,85 @@
|
||||
---
|
||||
title: Clone the MakerKit SaaS boilerplate repository
|
||||
label: Clone the repository
|
||||
description: Learn how to clone the MakerKit repository and install the NodeJS dependencies.
|
||||
---
|
||||
|
||||
If you have bought a license for MakerKit, you have access to all the
|
||||
repositories built by the MakerKit team. In this document, we will learn how
|
||||
to fetch and install the codebase.
|
||||
|
||||
### Requirements
|
||||
|
||||
To get started with the Next.js and Supabase SaaS template, we need to ensure
|
||||
you install the required software.
|
||||
|
||||
- Node.js
|
||||
- Git
|
||||
- Docker
|
||||
|
||||
### Getting Started with MakerKit
|
||||
|
||||
You have two choices for cloning the repository:
|
||||
|
||||
1. forking the original repository and cloning it from your fork
|
||||
2. cloning it manually from the original repository
|
||||
|
||||
#### Clone the repository
|
||||
|
||||
To get the codebase on your local machine using the original repository, clone the repository with the
|
||||
following command:
|
||||
|
||||
```
|
||||
git clone --depth=1 git@github.com:makerkit/next-supabase-saas-kit-lite.git my-saas
|
||||
```
|
||||
|
||||
The command above clones the repository in the folder `my-saas` which
|
||||
you can rename it with the name of your project.
|
||||
|
||||
If you forked the repository, point it to your fork instead of the original.
|
||||
|
||||
#### Initializing Git
|
||||
|
||||
Now, run the following commands for:
|
||||
|
||||
1. Moving into the folder
|
||||
2. Reinitialize your git repository
|
||||
|
||||
Personally I re-initialize the Git repository, but it's not required.
|
||||
|
||||
```
|
||||
cd my-saas
|
||||
rm -rf .git
|
||||
git init
|
||||
```
|
||||
|
||||
### Setting the Upstream repository, and fetching updates
|
||||
|
||||
Now, we can add the original Makerkit repository as "upstream" so we can fetch updates from the main repository:
|
||||
|
||||
```
|
||||
git remote add upstream git@github.com:makerkit/next-supabase-saas-kit-lite.git
|
||||
git add .
|
||||
git commit -a -m "Initial Commit"
|
||||
```
|
||||
|
||||
In this way, to fetch updates (after committing your files), simply run:
|
||||
|
||||
```
|
||||
git pull upstream main --allow-unrelated-histories
|
||||
```
|
||||
|
||||
You'll likely run into conflicts when running this command, so carefully choose the changes (sorry!).
|
||||
|
||||
### Installing the Node dependencies
|
||||
|
||||
Finally, we can install the NodeJS dependencies with `npm`:
|
||||
|
||||
```
|
||||
npm i
|
||||
```
|
||||
|
||||
While the application code is fully working, we now need to set up your Supabase
|
||||
project.
|
||||
|
||||
So let's jump on to the next step!
|
||||
@@ -0,0 +1,12 @@
|
||||
---
|
||||
title: Getting Started
|
||||
label: Getting Started
|
||||
description: Getting started with the Makerkit Kit
|
||||
---
|
||||
|
||||
Makerkit is a Next.js/Remix SaaS Starter that helps you build your own SaaS in minutes. It comes with a fully integrated Stripe billing system, a landing page, and a dashboard.
|
||||
|
||||
In this section, we learn how to install and run the SaaS kit on your local
|
||||
machine.
|
||||
|
||||
Buckle up and let's get started!
|
||||
@@ -0,0 +1,53 @@
|
||||
---
|
||||
title: Authentication Overview
|
||||
label: Overview
|
||||
description: Learn how authentication works in MakerKit and how to configure it.
|
||||
---
|
||||
|
||||
The way you want your users to authenticate can be driven via configuration.
|
||||
|
||||
If you open the global configuration at `src/configuration.ts`, you'll find
|
||||
the `auth` object:
|
||||
|
||||
```tsx title="configuration.ts"
|
||||
import type { Provider } from '@supabase/gotrue-js/src/lib/types';
|
||||
|
||||
auth: {
|
||||
requireEmailConfirmation: false,
|
||||
providers: {
|
||||
emailPassword: true,
|
||||
phoneNumber: false,
|
||||
emailLink: false,
|
||||
oAuth: ['google'] as Provider[],
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
As you can see, the `providers` object can be configured to only display the
|
||||
auth methods we want to use.
|
||||
|
||||
1. For example, by setting both `phoneNumber` and `emailLink` to `true`, the
|
||||
authentication pages will display the `Email Link` authentication
|
||||
and the `Phone Number` authentication forms.
|
||||
2. Instead, by setting `emailPassword` to `false`, we will remove the
|
||||
`email/password` form from the authentication and user profile pages.
|
||||
|
||||
## Requiring Email Verification
|
||||
|
||||
This setting needs to match what you have set up in Supabase. If you require email confirmation before your users can sign in, you will have to flip the following flag in your configuration:
|
||||
|
||||
```ts
|
||||
auth: {
|
||||
requireEmailConfirmation: false,
|
||||
}
|
||||
```
|
||||
|
||||
When the flag is set to `true`, the user will not be redirected to the onboarding flow, but will instead see a successful alert asking them to confirm their email. After confirmation, they will be able to sign in.
|
||||
|
||||
When the flag is set to `false`, the application will redirect them directly to the onboarding flow.
|
||||
|
||||
## Emails sent by Supabase
|
||||
|
||||
Supabase spins up an [InBucket](http://localhost:54324/) instance where all the emails are sent: this is where you can find emails related to password reset, sign-in links, and email verifications.
|
||||
|
||||
To access the InBucket instance, you can go to the following URL: [http://localhost:54324/](http://localhost:54324/). Save this URL, you will use it very often.
|
||||
@@ -0,0 +1,30 @@
|
||||
---
|
||||
title: Supabase Setup
|
||||
label: Supabase Setup
|
||||
description: How to setup authentication in MakerKit using Supabase.
|
||||
---
|
||||
|
||||
Supabase needs a few settings to be configured in their Dashboard to work correctly. This guide will walk you through the steps to get your Supabase authentication setup.
|
||||
|
||||
## Authentication URLs
|
||||
|
||||
The first thing you need to do is to set the authentication URLs in the Supabase Dashboard. These URLs are used to redirect users to the correct page after they have logged in or signed up.
|
||||
|
||||
1. Go to the [Supabase Dashboard](https://app.supabase.io/).
|
||||
2. Click on the project you want to use.
|
||||
3. Go to the **Authentication** tab.
|
||||
4. Click on **URL Configuration**.
|
||||
5. Add your Site URL to the **Site URL** field. This is the URL of your MakerKit site (e.g. `https://my-site.com`).
|
||||
6. Add your Redirect URLs to the **Redirect URLs** field. You need to add at least two URLs: This is the URL of your MakerKit site with `/auth/callback` appended to it (e.g. `https://my-site.com/auth/callback`) and another for redirecting users to their password reset page (e.g. `https://my-site.com/settings/profile/password`).
|
||||
|
||||
## Custom SMTP (optional)
|
||||
|
||||
If you want to send emails from your own domain, you can configure your SMTP settings in the Supabase Dashboard.
|
||||
|
||||
This is optional, but recommended if you want to send emails from your own domain.
|
||||
|
||||
1. Go to the [Supabase Dashboard](https://app.supabase.io/).
|
||||
2. Click on the project you want to use.
|
||||
3. Go to the **Project Settings** tab.
|
||||
4. Click on **Auth**.
|
||||
5. Tweak the `SMTP Settings` settings to your liking according to your provider's documentation.
|
||||
@@ -0,0 +1,23 @@
|
||||
---
|
||||
title: Authentication
|
||||
label: Authentication
|
||||
description: Learn everything about Authentication in Makerkit
|
||||
---
|
||||
|
||||
MakerKit uses Supabase to manage authentication within your application.
|
||||
|
||||
By default, every kit comes with the following built-in authentication methods:
|
||||
- **Email/Password** - we added, by default, the traditional way of signing in
|
||||
- **Third Party Providers** - we also added by default Google Auth sign-in
|
||||
- **Email Links**
|
||||
- **Phone Number**
|
||||
|
||||
You're free to add (or remove) any of the methods supported by Supabase's
|
||||
Authentication: we will see how.
|
||||
|
||||
This documentation will help you with the following:
|
||||
- **Setup** - setting up your Supabase project
|
||||
- **SSR** - use SSR to persist your users' authentication, adding new
|
||||
providers
|
||||
- **Customization** - an overview of how MakerKit works so that you can adapt
|
||||
it to your own application's needs
|
||||
47
packages/cms/contentlayer/content/posts/post-01.mdx
Normal file
47
packages/cms/contentlayer/content/posts/post-01.mdx
Normal file
@@ -0,0 +1,47 @@
|
||||
---
|
||||
title: Lorem Ipsum
|
||||
date: 2021-12-24
|
||||
live: false
|
||||
description: Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
|
||||
image: /assets/images/posts/lorem-ipsum.webp
|
||||
author: John Doe
|
||||
categories:
|
||||
- posts
|
||||
---
|
||||
|
||||
## Fecerat avis invenio mentis
|
||||
|
||||
Lorem markdownum signis vidi quisquis saepe inani inter animam laceras nequiquam
|
||||
castos cumque dum poste pede, **soliti et** eras. Cornua utendum. Ne dignus
|
||||
opacae? Moles percussis, redimitus equi quercus haurit perque *aras*; humo!
|
||||
Digessit Famemque membris vestrum [sua adveniens](http://erit.net/luctus.php)
|
||||
deserta, et me cum cum dicuntur et ignes.
|
||||
|
||||
var xmp_duplex = boolean + alu_unmount_tween - newline;
|
||||
var matrix_http_plain = facebook;
|
||||
rom = risc_flops + market + 2 + reimage_c_mca;
|
||||
|
||||
## Parilesque duae meritis
|
||||
|
||||
Suum spes medio faciunt miserarum artisque. Honor amplectique crescunt saepius
|
||||
cavis esse saepe laetabile modo. Fontis relinquit titulum est victa mundi!
|
||||
|
||||
## Orbem dare
|
||||
|
||||
More cingo concipit cumque armenta. Secuta quare profundi damni erigimur effugit
|
||||
facta ipsa, videt videt. Conantem et **campos animos usquam** ut munus erat
|
||||
audito, e!
|
||||
|
||||
> Talia ponit corpora Philemon. Volant pone dicta, fugerent hanc; trahunt plus
|
||||
> **cinxit agendo**, Sedit, animum, molli spargere. Perterrita et bella Tiresia
|
||||
> tanta auctor, colatur **nigro** externa. Stamina nunc bis *longeque* cornua.
|
||||
|
||||
## Cantat sequentes et illi opertos Cycno
|
||||
|
||||
Per inque Pallade cuspide errabat. Est dolor excitus ultorem avertere, numero et
|
||||
Minos pater flamine, ictu tune Phylius.
|
||||
|
||||
Ditem est qui Scythicis erubuit suae, qui nunc tacito aequare auras. Suas erat
|
||||
cubitoque esse, volventem quae, fera tinxi villo ita. Addit hic sine at orbe ut
|
||||
sanesque intravit pudore nullisque Canens, ait aut. Parabat Pittheia Pan cibus
|
||||
et perque inquit grave suae coniunx cura matris undaeque et stagni et.
|
||||
237
packages/cms/contentlayer/contentlayer.config.js
Normal file
237
packages/cms/contentlayer/contentlayer.config.js
Normal file
@@ -0,0 +1,237 @@
|
||||
import { defineDocumentType, makeSource } from 'contentlayer/source-files';
|
||||
import rehypeAutolinkHeadings from 'rehype-autolink-headings';
|
||||
import rehypeSlug from 'rehype-slug';
|
||||
|
||||
const siteUrl = process.env.NEXT_PUBLIC_SITE_URL || 'http://localhost:3000';
|
||||
|
||||
export const Post = defineDocumentType(() => ({
|
||||
name: 'Post',
|
||||
filePathPattern: `posts/*.mdx`,
|
||||
contentType: 'mdx',
|
||||
fields: {
|
||||
title: {
|
||||
type: 'string',
|
||||
description: 'The title of the post',
|
||||
required: true,
|
||||
},
|
||||
date: {
|
||||
type: 'date',
|
||||
description: 'The date of the post',
|
||||
required: true,
|
||||
},
|
||||
author: {
|
||||
type: 'string',
|
||||
description: 'The author of the post',
|
||||
required: true,
|
||||
},
|
||||
live: {
|
||||
type: 'boolean',
|
||||
description: 'Whether the post is live or not',
|
||||
required: true,
|
||||
default: false,
|
||||
},
|
||||
image: {
|
||||
type: 'string',
|
||||
description: 'The path to the cover image',
|
||||
},
|
||||
description: {
|
||||
type: 'string',
|
||||
description: 'The description of the post',
|
||||
},
|
||||
tags: {
|
||||
type: 'list',
|
||||
required: false,
|
||||
of: {
|
||||
type: 'string',
|
||||
},
|
||||
},
|
||||
categories: {
|
||||
type: 'list',
|
||||
required: false,
|
||||
of: {
|
||||
type: 'string',
|
||||
},
|
||||
},
|
||||
},
|
||||
computedFields: {
|
||||
readingTime: {
|
||||
type: 'number',
|
||||
resolve: (post) => calculateReadingTime(post.body.raw),
|
||||
},
|
||||
slug: {
|
||||
type: 'string',
|
||||
resolve: (post) => getSlug(post._raw.sourceFileName),
|
||||
},
|
||||
url: {
|
||||
type: 'string',
|
||||
resolve: (post) => `/blog/${getSlug(post._raw.sourceFileName)}`,
|
||||
},
|
||||
structuredData: {
|
||||
type: 'object',
|
||||
resolve: (doc) => ({
|
||||
'@context': 'https://schema.org',
|
||||
'@type': 'BlogPosting',
|
||||
headline: doc.title,
|
||||
datePublished: doc.date,
|
||||
dateModified: doc.date,
|
||||
description: doc.description,
|
||||
image: [siteUrl, doc.image].join(''),
|
||||
author: {
|
||||
'@type': 'Organization',
|
||||
name: `Makerkit`,
|
||||
},
|
||||
}),
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
export const DocumentationPage = defineDocumentType(() => ({
|
||||
name: 'DocumentationPage',
|
||||
filePathPattern: `docs/**/*.mdx`,
|
||||
contentType: 'mdx',
|
||||
fields: {
|
||||
title: {
|
||||
type: 'string',
|
||||
description: 'The title of the post',
|
||||
required: true,
|
||||
},
|
||||
label: {
|
||||
type: 'string',
|
||||
description: 'The label of the page in the sidebar',
|
||||
required: true,
|
||||
},
|
||||
description: {
|
||||
type: 'string',
|
||||
description: 'The description of the post',
|
||||
},
|
||||
tags: {
|
||||
type: 'list',
|
||||
required: false,
|
||||
of: {
|
||||
type: 'string',
|
||||
},
|
||||
},
|
||||
categories: {
|
||||
type: 'list',
|
||||
required: false,
|
||||
of: {
|
||||
type: 'string',
|
||||
},
|
||||
},
|
||||
},
|
||||
computedFields: {
|
||||
readingTime: {
|
||||
type: 'number',
|
||||
resolve: (post) => calculateReadingTime(post.body.raw),
|
||||
},
|
||||
structuredData: {
|
||||
type: 'object',
|
||||
resolve: (doc) => ({
|
||||
'@context': 'https://schema.org',
|
||||
'@type': 'LearningResource',
|
||||
headline: doc.title,
|
||||
datePublished: doc.date,
|
||||
dateModified: doc.date,
|
||||
description: doc.description,
|
||||
image: [siteUrl, doc.image].join(''),
|
||||
url: [siteUrl, 'blog', doc._raw.flattenedPath].join('/'),
|
||||
author: {
|
||||
'@type': 'Organization',
|
||||
name: `Makerkit`,
|
||||
},
|
||||
}),
|
||||
},
|
||||
path: {
|
||||
type: 'string',
|
||||
resolve: (doc) => {
|
||||
if (doc._id.startsWith('docs/index.md')) {
|
||||
return '/docs';
|
||||
}
|
||||
|
||||
return urlFromFilePath(doc);
|
||||
},
|
||||
},
|
||||
pathSegments: {
|
||||
type: 'json',
|
||||
resolve: (doc) => getPathSegments(doc).map(getMetaFromFolderName),
|
||||
},
|
||||
slug: {
|
||||
type: 'string',
|
||||
resolve: (doc) =>
|
||||
getPathSegments(doc)
|
||||
.map(getMetaFromFolderName)
|
||||
.map(({ pathName }) => pathName)
|
||||
.join('/'),
|
||||
},
|
||||
url: {
|
||||
type: 'string',
|
||||
resolve: (doc) => {
|
||||
return (
|
||||
'/docs/' +
|
||||
getPathSegments(doc)
|
||||
.map(getMetaFromFolderName)
|
||||
.map(({ pathName }) => pathName)
|
||||
.join('/')
|
||||
);
|
||||
},
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
export default makeSource({
|
||||
contentDirPath: './content',
|
||||
documentTypes: [Post, DocumentationPage],
|
||||
mdx: {
|
||||
remarkPlugins: [],
|
||||
rehypePlugins: [
|
||||
rehypeSlug,
|
||||
[
|
||||
rehypeAutolinkHeadings,
|
||||
{
|
||||
properties: {
|
||||
className: ['anchor'],
|
||||
},
|
||||
},
|
||||
],
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
function calculateReadingTime(content) {
|
||||
const wordsPerMinute = 235;
|
||||
const numberOfWords = content.split(/\s/g).length;
|
||||
const minutes = numberOfWords / wordsPerMinute;
|
||||
|
||||
return Math.ceil(minutes);
|
||||
}
|
||||
|
||||
function getSlug(fileName) {
|
||||
return fileName.replace('.mdx', '');
|
||||
}
|
||||
|
||||
function urlFromFilePath(doc) {
|
||||
let urlPath = doc._raw.flattenedPath.replace(/^app\/?/, '/');
|
||||
|
||||
if (!urlPath.startsWith('/')) {
|
||||
urlPath = `/${urlPath}`;
|
||||
}
|
||||
|
||||
return urlPath;
|
||||
}
|
||||
|
||||
function getMetaFromFolderName(dirName) {
|
||||
const re = /^((\d+)-)?(.*)$/;
|
||||
const [, , orderStr, pathName] = dirName.match(re) ?? [];
|
||||
const order = orderStr ? parseInt(orderStr) : 0;
|
||||
|
||||
return { order, pathName };
|
||||
}
|
||||
|
||||
function getPathSegments(doc) {
|
||||
return (
|
||||
urlFromFilePath(doc)
|
||||
.split('/')
|
||||
// skip `/docs` prefix
|
||||
.slice(2)
|
||||
);
|
||||
}
|
||||
45
packages/cms/contentlayer/package.json
Normal file
45
packages/cms/contentlayer/package.json
Normal file
@@ -0,0 +1,45 @@
|
||||
{
|
||||
"name": "@kit/contentlayer",
|
||||
"private": true,
|
||||
"version": "0.1.0",
|
||||
"scripts": {
|
||||
"clean": "git clean -xdf .turbo node_modules",
|
||||
"format": "prettier --check \"**/*.{ts,tsx}\"",
|
||||
"lint": "eslint .",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"build": "contentlayer build"
|
||||
},
|
||||
"prettier": "@kit/prettier-config",
|
||||
"exports": {
|
||||
".": "./src/index.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"contentlayer": "0.3.4",
|
||||
"next-contentlayer": "0.3.4",
|
||||
"rehype-slug": "^6.0.0",
|
||||
"rehype-autolink-headings": "^6.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@kit/cms": "workspace:^",
|
||||
"@kit/ui": "workspace:^"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@kit/eslint-config": "workspace:*",
|
||||
"@kit/prettier-config": "workspace:*",
|
||||
"@kit/tsconfig": "workspace:*"
|
||||
},
|
||||
"eslintConfig": {
|
||||
"root": true,
|
||||
"extends": [
|
||||
"@kit/eslint-config/base",
|
||||
"@kit/eslint-config/react"
|
||||
]
|
||||
},
|
||||
"typesVersions": {
|
||||
"*": {
|
||||
"*": [
|
||||
"src/*"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
192
packages/cms/contentlayer/src/client.ts
Normal file
192
packages/cms/contentlayer/src/client.ts
Normal file
@@ -0,0 +1,192 @@
|
||||
import { Cms, CmsClient } from '@kit/cms';
|
||||
|
||||
import type { DocumentationPage, Post } from '../.contentlayer/generated';
|
||||
|
||||
async function getAllContentItems() {
|
||||
const { allDocumentationPages, allPosts } = await import(
|
||||
'../.contentlayer/generated'
|
||||
);
|
||||
|
||||
return [
|
||||
...allPosts.map((item) => {
|
||||
return { ...item, type: 'post' };
|
||||
}),
|
||||
...allDocumentationPages.map((item) => {
|
||||
return { ...item, type: 'page', categories: ['documentation'] };
|
||||
}),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* A class that represents a Content Layer CMS client.
|
||||
* This class implements the base CmsClient class.
|
||||
*
|
||||
* @class ContentlayerClient
|
||||
* @extends {CmsClient}
|
||||
*/
|
||||
export class ContentlayerClient implements CmsClient {
|
||||
async getContentItems(options?: Cms.GetContentItemsOptions) {
|
||||
const allContentItems = await getAllContentItems();
|
||||
const { startOffset, endOffset } = this.getOffset(options);
|
||||
|
||||
const promise = allContentItems
|
||||
.filter((item) => {
|
||||
const tagMatch = options?.tags
|
||||
? item.tags?.some((tag) => options.tags?.includes(tag))
|
||||
: true;
|
||||
|
||||
const categoryMatch = options?.categories
|
||||
? item.categories?.some((category) =>
|
||||
options.categories?.includes(category),
|
||||
)
|
||||
: true;
|
||||
|
||||
const typeMatch = options?.type ? item.type === options.type : true;
|
||||
const path = item._raw.flattenedPath;
|
||||
const splitPath = path.split('/');
|
||||
|
||||
const depthMatch =
|
||||
options?.depth !== undefined
|
||||
? splitPath.length - 1 === options.depth
|
||||
: true;
|
||||
|
||||
return tagMatch && categoryMatch && typeMatch && depthMatch;
|
||||
})
|
||||
.slice(startOffset, endOffset)
|
||||
.map((post) => {
|
||||
const children: Cms.ContentItem[] = [];
|
||||
|
||||
for (const item of allContentItems) {
|
||||
if (item.url.startsWith(post.url + '/')) {
|
||||
children.push(this.mapPost(item));
|
||||
}
|
||||
}
|
||||
|
||||
return this.mapPost(post, children);
|
||||
});
|
||||
|
||||
return Promise.resolve(promise);
|
||||
}
|
||||
|
||||
async getContentItemById(id: string) {
|
||||
const allContentItems = await getAllContentItems();
|
||||
const post = allContentItems.find((item) => item.slug === id);
|
||||
|
||||
if (!post) {
|
||||
return Promise.resolve(undefined);
|
||||
}
|
||||
|
||||
const children: Cms.ContentItem[] = [];
|
||||
|
||||
for (const item of allContentItems) {
|
||||
if (item.url.startsWith(post.url + '/')) {
|
||||
children.push(this.mapPost(item));
|
||||
}
|
||||
}
|
||||
|
||||
return Promise.resolve(post ? this.mapPost(post, children) : undefined);
|
||||
}
|
||||
|
||||
async getCategoryBySlug(slug: string) {
|
||||
return Promise.resolve({
|
||||
id: slug,
|
||||
name: slug,
|
||||
slug,
|
||||
});
|
||||
}
|
||||
|
||||
async getTagBySlug(slug: string) {
|
||||
return Promise.resolve({
|
||||
id: slug,
|
||||
name: slug,
|
||||
slug,
|
||||
});
|
||||
}
|
||||
|
||||
async getCategories(options?: Cms.GetCategoriesOptions) {
|
||||
const { startOffset, endOffset } = this.getOffset(options);
|
||||
const allContentItems = await getAllContentItems();
|
||||
|
||||
const categories = allContentItems
|
||||
.filter((item) => {
|
||||
if (options?.type) {
|
||||
return item.type === options.type;
|
||||
}
|
||||
|
||||
return true;
|
||||
})
|
||||
.slice(startOffset, endOffset)
|
||||
.flatMap((post) => post.categories)
|
||||
.filter((category): category is string => !!category)
|
||||
.map((category) => ({
|
||||
id: category,
|
||||
name: category,
|
||||
slug: category,
|
||||
}));
|
||||
|
||||
return Promise.resolve(categories);
|
||||
}
|
||||
|
||||
async getTags(options?: Cms.GetTagsOptions) {
|
||||
const { startOffset, endOffset } = this.getOffset(options);
|
||||
const allContentItems = await getAllContentItems();
|
||||
|
||||
const tags = allContentItems
|
||||
.filter((item) => {
|
||||
if (options?.type) {
|
||||
return item.type === options.type;
|
||||
}
|
||||
|
||||
return true;
|
||||
})
|
||||
.slice(startOffset, endOffset)
|
||||
.flatMap((post) => post.tags)
|
||||
.filter((tag): tag is string => !!tag)
|
||||
.map((tag) => ({
|
||||
id: tag,
|
||||
name: tag,
|
||||
slug: tag,
|
||||
}));
|
||||
|
||||
return Promise.resolve(tags);
|
||||
}
|
||||
|
||||
private getOffset(options?: { offset?: number; limit?: number }) {
|
||||
const startOffset = options?.offset ?? 0;
|
||||
const endOffset = options?.limit ? startOffset + options.limit : undefined;
|
||||
|
||||
return { startOffset, endOffset };
|
||||
}
|
||||
|
||||
private mapPost(
|
||||
post: Post | DocumentationPage,
|
||||
children: Array<Post | DocumentationPage> = [],
|
||||
): Cms.ContentItem {
|
||||
console.log(post);
|
||||
return {
|
||||
id: post.slug,
|
||||
title: post.title,
|
||||
description: post.description ?? '',
|
||||
content: post.body?.code,
|
||||
image: 'image' in post ? post.image : undefined,
|
||||
publishedAt: 'date' in post ? new Date(post.date) : new Date(),
|
||||
parentId: 'parentId' in post ? post.parentId : undefined,
|
||||
url: post.url,
|
||||
slug: post.slug,
|
||||
author: 'author' in post ? post.author : '',
|
||||
children: children.map((child) => this.mapPost(child)),
|
||||
categories:
|
||||
post.categories?.map((category) => ({
|
||||
id: category,
|
||||
name: category,
|
||||
slug: category,
|
||||
})) ?? [],
|
||||
tags:
|
||||
post.tags?.map((tag) => ({
|
||||
id: tag,
|
||||
name: tag,
|
||||
slug: tag,
|
||||
})) ?? [],
|
||||
};
|
||||
}
|
||||
}
|
||||
5
packages/cms/contentlayer/src/content-renderer.tsx
Normal file
5
packages/cms/contentlayer/src/content-renderer.tsx
Normal file
@@ -0,0 +1,5 @@
|
||||
import { Mdx } from './mdx/mdx-renderer';
|
||||
|
||||
export function ContentRenderer(props: { content: string }) {
|
||||
return <Mdx code={props.content} />;
|
||||
}
|
||||
3
packages/cms/contentlayer/src/index.ts
Normal file
3
packages/cms/contentlayer/src/index.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
export * from './client';
|
||||
export * from './mdx/mdx-renderer';
|
||||
export * from './content-renderer';
|
||||
97
packages/cms/contentlayer/src/mdx/mdx-renderer.module.css
Normal file
97
packages/cms/contentlayer/src/mdx/mdx-renderer.module.css
Normal file
@@ -0,0 +1,97 @@
|
||||
.MDX h1 {
|
||||
@apply mt-14 text-4xl font-bold;
|
||||
}
|
||||
|
||||
.MDX h2 {
|
||||
@apply mb-4 mt-12 text-2xl font-semibold lg:text-3xl;
|
||||
}
|
||||
|
||||
.MDX h3 {
|
||||
@apply mt-10 text-2xl font-bold;
|
||||
}
|
||||
|
||||
.MDX h4 {
|
||||
@apply mt-8 text-xl font-bold;
|
||||
}
|
||||
|
||||
.MDX h5 {
|
||||
@apply mt-6 text-lg font-semibold;
|
||||
}
|
||||
|
||||
.MDX h6 {
|
||||
@apply mt-2 text-base font-medium;
|
||||
}
|
||||
|
||||
/**
|
||||
Tailwind "dark" variants do not work with CSS Modules
|
||||
We work it around using :global(.dark)
|
||||
For more info: https://github.com/tailwindlabs/tailwindcss/issues/3258#issuecomment-770215347
|
||||
*/
|
||||
:global(.dark) .MDX h1,
|
||||
:global(.dark) .MDX h2,
|
||||
:global(.dark) .MDX h3,
|
||||
:global(.dark) .MDX h4,
|
||||
:global(.dark) .MDX h5,
|
||||
:global(.dark) .MDX h6 {
|
||||
@apply text-white;
|
||||
}
|
||||
|
||||
.MDX p {
|
||||
@apply mb-4 mt-2 text-base leading-7;
|
||||
}
|
||||
|
||||
.MDX li {
|
||||
@apply relative my-1.5 text-base leading-7;
|
||||
}
|
||||
|
||||
.MDX ul > li:before {
|
||||
content: '-';
|
||||
|
||||
@apply mr-2;
|
||||
}
|
||||
|
||||
.MDX ol > li:before {
|
||||
@apply inline-flex font-medium;
|
||||
|
||||
content: counters(counts, '.') '. ';
|
||||
font-feature-settings: 'tnum';
|
||||
}
|
||||
|
||||
.MDX b,
|
||||
.MDX strong {
|
||||
@apply font-bold;
|
||||
}
|
||||
|
||||
:global(.dark) .MDX b,
|
||||
:global(.dark) .MDX strong {
|
||||
@apply text-white;
|
||||
}
|
||||
|
||||
.MDX img,
|
||||
.MDX video {
|
||||
@apply rounded-md;
|
||||
}
|
||||
|
||||
.MDX ul,
|
||||
.MDX ol {
|
||||
@apply pl-1;
|
||||
}
|
||||
|
||||
.MDX ol > li {
|
||||
counter-increment: counts;
|
||||
}
|
||||
|
||||
.MDX ol > li:before {
|
||||
@apply mr-2 inline-flex font-semibold;
|
||||
|
||||
content: counters(counts, '.') '. ';
|
||||
font-feature-settings: 'tnum';
|
||||
}
|
||||
|
||||
.MDX blockquote {
|
||||
@apply my-4 border-l-4 border-primary bg-muted px-6 py-4 text-lg font-medium text-gray-600;
|
||||
}
|
||||
|
||||
.MDX pre {
|
||||
@apply my-6 text-sm text-current;
|
||||
}
|
||||
21
packages/cms/contentlayer/src/mdx/mdx-renderer.tsx
Normal file
21
packages/cms/contentlayer/src/mdx/mdx-renderer.tsx
Normal file
@@ -0,0 +1,21 @@
|
||||
import type { MDXComponents as MDXComponentsType } from 'mdx/types';
|
||||
import { getMDXComponent } from 'next-contentlayer/hooks';
|
||||
|
||||
import { MDXComponents } from '@kit/ui/mdx-components';
|
||||
|
||||
// @ts-ignore: ignore weird error
|
||||
import styles from './mdx-renderer.module.css';
|
||||
|
||||
export function Mdx({
|
||||
code,
|
||||
}: React.PropsWithChildren<{
|
||||
code: string;
|
||||
}>) {
|
||||
const Component = getMDXComponent(code);
|
||||
|
||||
return (
|
||||
<div className={styles.MDX}>
|
||||
<Component components={MDXComponents as unknown as MDXComponentsType} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
8
packages/cms/contentlayer/tsconfig.json
Normal file
8
packages/cms/contentlayer/tsconfig.json
Normal file
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"extends": "@kit/tsconfig/base.json",
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "node_modules/.cache/tsbuildinfo.json"
|
||||
},
|
||||
"include": ["src"],
|
||||
"exclude": ["node_modules"]
|
||||
}
|
||||
Reference in New Issue
Block a user