jescalan / mdnext

The opinionated starter for MDX based Next apps for blogs, documentation, and more.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

mdnext

The opinionated starter for your MDX + Next.js needs




Installation

To install the base template, we're going to apply our base path to create-next-app:

npx create-next-app your-project-name -e https://github.com/domitriusclark/mdnext/tree/master/packages/mdnext

or

yarn create next-app your-project-name -e https://github.com/domitriusclark/mdnext/tree/master/packages/mdnext

If instead you'd like to use one of the opinionated example templates you can apply them similarly:

npx create-next-app your-project-name -e https://github.com/domitriusclark/mdnext/tree/master/examples/{example-template-name}

or

yarn create next-app your-project-name -e https://github.com/domitriusclark/mdnext/tree/master/examples/{example-template-name}

Usage

Out of the box this template comes with:

  • Local MDX examples + how to handle parsing & rendering them
  • Built in input & tag search
  • A growing list of components to pass to MDX and get up and running fast (thanks to Chakra UI)
  • Code highlighting + built in copy functionality
  • Built in light + dark mode
  • SEO defaults + configuration
  • Absolute import path support

Let's dig a bit into the tools used and where to get started in the project.

MDX w/ next-mdx-remote

To focus on flexibility of where our markdown can be sourced, we utilize two functions from next-mdx-remote.

  • renderToString(source: string, components: object, options?: object, scope?: object) This function consumes a string of mdx along with any components it utilizes in the format { ComponentName: ActualComponent }. It also can optionally be passed options which are passed directly to mdx, and a scope object that can be included in the mdx scope. The function returns an object that is intended to be passed into hydrate directly.

  • hydrate(source: object, components: object) This function consumes the output of renderToString as well as the same components argument as renderToString. Its result can be rendered directly into your component. This function will initially render static content, and hydrate it when the browser isn't busy with higher priority tasks.

These functions allow us to parse MDX as a source in our lifecycle methods like getStaticProps and getStaticPaths so we can statically generate content based on our MDX and finish by giving us the output from renderToString with something we can render.

// -- /pages/blog/[slug].js

import renderToString from 'next-mdx-remote/render-to-string';
import hydrate from 'next-mdx-remote/hydrate';
import fs from 'fs';
import matter from 'gray-matter';
import glob from 'fast-glob';

import Iframe from '@components/Iframe';
import Code from '@components/Code';

// Components that pass to the MDX
const components = { code: Code, Iframe };

export default ({ mdxSource, frontMatter }) => {
  // statically render + hydrate content passed to us from our renderToString output
  const content = hydrate(mdxSource, components);

  return (
    <div>
      <h1>{frontMatter.title}</h1>
      {content}
    </div>
  );
};

// This glob is what will be used to generate static routes
const contentGlob = 'src/blogs/*.mdx';

export async function getStaticPaths() {
  const files = glob.sync(contentGlob);

  const paths = files.map((file) => {
    const split = file.split('/');
    const filename = split[split.length - 1];
    const slug = filename.replace('.mdx', '');

    return {
      params: {
        slug,
      },
    };
  });

  return {
    paths,
    fallback: false,
  };
}

export async function getStaticProps({ params: { slug } }) {
  const files = glob.sync(contentGlob);

  const fullPath = files.filter((item) => {
    const split = item.split('/');
    const filename = split[split.length - 1];
    return filename.replace('.mdx', '') === slug;
  })[0];

  const mdxSource = fs.readFileSync(fullPath);
  const { content, data } = matter(mdxSource);

  if (!fullPath) {
    console.warn('No MDX file found for slug');
  }

  const mdx = await renderToString(content, components, null, data);

  return {
    props: {
      mdxSource: mdx,
      frontMatter: data,
    },
  };
}

Built-in Search w/ Fuse.js

A preconfigured Search component and accompanying page exist to demonstrate one way you can build out some search functionality for your content. Fuse.js allows us to quickly build a fuzzy search (with a list of configurations) that we can use with Input or tag based searching.

// -- /src/components/Search.js

import React, { useState } from 'react';
import Fuse from 'fuse.js';

import { Flex, Button, Stack, Input } from '@chakra-ui/core';

const TAG_LIST = ['react', 'nextjs', 'chakra ui'];

// Configuration options for refining your fuzzy search
const fuseOptions = {
  threshold: 0.35,
  location: 0,
  distance: 100,
  minMatchCharLength: 1,
  shouldSort: true,
  includeScore: true,
  useExtendedSearch: true,
  keys: ['title', 'tags'],
};

export default function Search({ blogs, handleFilter }) {
  const [searchValue, setSearchValue] = useState('');
  const [searchTags, setSearchTags] = useState([]);

  // New instance of your search w/ the content it's searching and the options from your config
  const fuse = new Fuse(blogs, fuseOptions);

  React.useEffect(() => {
    if (searchValue === '' && searchTags.length === 0) {
      handleFilter(blogs);
    } else {
      // Allow for a search for tag
      const formattedTags = [...searchTags.map((item) => ({ tags: item }))];
      const formattedTitle = searchValue.length ? [{ title: searchValue }] : [];
      const queries = {
        $or: [
          { tags: searchValue },
          { title: searchValue },
          {
            $and: [...formattedTags, ...formattedTitle],
          },
        ],
      };
      const results = fuse.search(queries).map((result) => result.item);
      handleFilter(results);
    }
  }, [searchValue, searchTags]);

  const onChange = (e) => {
    const { value } = e.target;
    setSearchValue(value);
  };

  const onTagClick = (tag) => {
    if (searchTags.includes(tag)) {
      setSearchTags(searchTags.filter((included) => included != tag));
    } else {
      setSearchTags([...searchTags, tag]);
    }
  };

  return (
    <Flex direction="column" w={['100%', '75%', '50%']}>
      <Flex justify="space-around">
        <Stack spacing={4}>
          {TAG_LIST.map((tag) => (
            <Button onClick={() => onTagClick(tag)}>#{tag}</Button>
          ))}
        </Stack>
      </Flex>
      <Input mt={6} value={searchValue} onChange={onChange} />
    </Flex>
  );
}

Chakra UI -- Light + Dark Mode & Themeing

Using the (currently experimental) v1 of Chakra UI, has given us the tools to handle theme persistence via cookies.

That combined with approachable & accessible components, direct theme config, and room to experiment for custom needs, gives this template the flexibility & cohesiveness to get you started on building your projects with confidence.

Shoutouts

Wanted to highlight some projects + people that helped inspire + round out this template.

Contributing

WIP!

Currently listing some discussion + features in issues!

About

The opinionated starter for MDX based Next apps for blogs, documentation, and more.


Languages

Language:JavaScript 100.0%