micromark / micromark-extension-gfm

micromark extension to support GFM (GitHub Flavored Markdown)
https://unifiedjs.com
MIT License
30 stars 2 forks source link

Support for visual color helper when a HEX/RGB color code is written #9

Closed shreshthmohan closed 2 years ago

shreshthmohan commented 2 years ago

Initial checklist

Problem

In GitHub issues, when you write a color code like #ff9145, it adds a small span with the color set as background-color

GitHub issues screenshot: image

But I checked the generated markup and has a simple <code> tag without any visual color helper.

Solution

Can we have this feature? If yes, I am not sure about how to proceed with a contribution. Will it be a new extension like micromark-extension-gfm-color?

Alternatives

One could manually add a span with the same background color as written in the code block, but it won't be an ideal solution.

wooorm commented 2 years ago

Color “chips” aren’t part of the GFM spec, which is what these packages do. They’re part of what GH does in certain places (comments/issues/PRs), afterwards, while postprocessing the HTML.

Here’s an transform you can use on the hast (html ast) to match GH though:

/**
 * @typedef {import('hast').Root} Root
 */

import {visit} from 'unist-util-visit'
import {toString} from 'hast-util-to-string'

// ...

  visit(tree, 'element', function (node) {
    if (node.tagName === 'code' && node.properties) {
      const value = toString(node)
      if (/^#[\da-f]{6}$/i.test(value)) {
        node.children.push({
          type: 'element',
          tagName: 'span',
          properties: {
            className: [
              'ml-1',
              'd-inline-block',
              'border',
              'circle',
              'color-border-subtle'
            ],
            style: 'background-color: ' + value + '; height: 8px; width: 8px;'
          },
          children: []
        })
      }
    }
  })
github-actions[bot] commented 2 years ago

Hi! This was closed. Team: If this was fixed, please add phase/solved. Otherwise, please add one of the no/* labels.

shreshthmohan commented 2 years ago

@wooorm Thanks for the pointers. 🙏🏽 I published a rehype plugin for this: https://www.npmjs.com/package/rehype-color-chips

wooorm commented 2 years ago

Cool! It's a fun little feature. I wonder why GH doesn't support other colors, or do similar small useful things to common code examples :)