sindresorhus / github-markdown-css

The minimal amount of CSS to replicate the GitHub Markdown style
https://sindresorhus.com/github-markdown-css
MIT License
7.9k stars 2.11k forks source link

Switch themes based on class #104

Open sebdanielsson opened 1 year ago

sebdanielsson commented 1 year ago

I implement my color schemes with Tailwind and adding and removing the class "dark" from the html tag. Would be nice to do this with this project as well so that the color scheme matches the scheme chosen by the user. :)

FallenDeity commented 1 year ago

@SebDanielsson did u find a way yet to switch color schemes for the markdown I am unable to switch from dark to light not really sure how to do that

sebdanielsson commented 1 year ago

Yes I did manage to get it working!☺️ Here's my repo: https://github.com/SebDanielsson/gik2f8-group10-project

Basically I prepended [data-theme="dark"] to all CSS-entries and wrote some JS to set data-theme👍

FallenDeity commented 1 year ago

oh thats a nice way i had a similar solution i made two different css classes and made a js toggler function that way i can add more themes later just need to inherit and change class and base colors

sebdanielsson commented 1 year ago

Awesome😎

some-user123 commented 1 year ago

I'm looking for the same. Did you manipulate the CSS files manually? I'd ideally like to use this package as a dependency, not copy & paste from it...

sebdanielsson commented 1 year ago

Unfortunately I had to download the css files and find and replace all: Find: .markdown-body Replace: [data-theme="dark"] .markdown-body

https://github.com/sebdanielsson/gik2f8-group10-project/blob/main/src/github-markdown-dark.css

It was quick and easy but not very clean.

cyrus2281 commented 1 year ago

For the future reference, here is a cleaner way of doing what @sebdanielsson did

CSS Changes

Copy over the file github-markdown.css to your project and only change these 2 css lines (They are the first 2 blocks in the css file):

@media (prefers-color-scheme: dark)

with

[data-theme='dark'] 

and

@media (prefers-color-scheme: light)

with

[data-theme='light'] 

For example:

[data-theme='dark']  {
  .markdown-body {
    color-scheme: dark;
    --color-prettylights-syntax-comment: #8b949e;
    --color-prettylights-syntax-constant: #79c0ff;
    --color-prettylights-syntax-entity: #d2a8ff;
   /* Other variables... */
  }
}

Using the preferred theme color

In JavaScript you can add the following logic to still preserve the behavior of using the user preference:

const setDefaultTheme = () => {
  const prefersDarkMode = window.matchMedia(
    "(prefers-color-scheme: dark)"
  ).matches;
  if (prefersDarkMode) {
    document.body.setAttribute("data-theme", "dark");
  } else {
    document.body.setAttribute("data-theme", "light");
  }
};
setDefaultTheme()

Toggling Mode

you can toggle it with this function (you can add it to a button onClick):

    const toggleTheme = () => {
      if (document.body.getAttribute("data-theme") === "light") {
        document.body.setAttribute("data-theme", "dark");
      } else {
        document.body.setAttribute("data-theme", "light");
      }
    };
sebdanielsson commented 1 year ago

For the future reference, here is a cleaner way of doing what @sebdanielsson did

CSS Changes

Copy over the file github-markdown.css to your project and only change these 2 css lines (They are the first 2 blocks in the css file):

@media (prefers-color-scheme: dark)

with

[data-theme='dark'] 

and

@media (prefers-color-scheme: light)

with

[data-theme='light'] 

For example:

[data-theme='dark']  {
  .markdown-body {
    color-scheme: dark;
    --color-prettylights-syntax-comment: #8b949e;
    --color-prettylights-syntax-constant: #79c0ff;
    --color-prettylights-syntax-entity: #d2a8ff;
   /* Other variables... */
  }
}

Using the preferred theme color

In JavaScript you can add the following logic to still preserve the behavior of using the user preference:

const setDefaultTheme = () => {
  const prefersDarkMode = window.matchMedia(
    "(prefers-color-scheme: dark)"
  ).matches;
  if (prefersDarkMode) {
    document.body.setAttribute("data-theme", "dark");
  } else {
    document.body.setAttribute("data-theme", "light");
  }
};
setDefaultTheme()

Toggling Mode

you can toggle it with this function (you can add it to a button onClick):

    const toggleTheme = () => {
      if (document.body.getAttribute("data-theme") === "light") {
        document.body.setAttribute("data-theme", "dark");
      } else {
        document.body.setAttribute("data-theme", "light");
      }
    };

That worked flawlessly. Thanks!😊

maxpatiiuk commented 10 months ago

Here is a solution that doesn't involve manually editing the file.

Pre-requisite: you have to use PostCSS (you might already be using it as it's needed by Tailwind CSS and many other CSS libraries)

You can define a small PostCSS plugin that will do the transformation from @media query to .dark/.light class name selector:

// postcss.config.js

const postcss = require('postcss');

/** @type {import('postcss-load-config').ConfigPlugin} */
const makeGitHubCssUseClassName = {
  postcssPlugin: 'makeGitHubCssUseClassName',
  AtRule: {
    media(media, { Rule }) {
      const filePath = media.root().source?.input?.file ?? '';
      if (!filePath.endsWith('/github-markdown.css')) return;

      const scopeSelector =
        media.params === '(prefers-color-scheme: dark)'
          ? '.dark'
          : media.params === '(prefers-color-scheme: light)'
          ? '.light'
          : undefined;
      if (scopeSelector === undefined) return;

      media.each((child) => {
        if (child.type !== 'rule') return;
        const newRule = new Rule({
          selector: `${scopeSelector} ${child.selector}`,
        });

        child.each((grandChild) => void newRule.append(grandChild.clone()));
        media.before(newRule);
      });
      media.remove();
    },
  },
};

/** @type {import('postcss-load-config').Config} */
module.exports = {
  plugins: [
    ... // your other plugins here
    // Add the newly defined plugin to your PostCSS config:
    makeGitHubCssUseClassName,
  ],
};
nemanjam commented 2 weeks ago

Quite annoying that markdown-body-light and markdown-body-dark classes aren't exposed but I have to dynamically load/unload two css files and serve them myself. Or even more exported as a Tailwind layer so it can be used with dark: modifier.