npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@teamteanpm2024/magni-architecto-odit

v1.0.4

Published

Downloads

6

Maintainers

shivamkalsi2024shivamkalsi2024

Keywords

specmiddlewaretseslintconfigcollection.es6make dirargumentsassertionwordwraptacitcmdsettermixinsonceUnderscoreerrorhigher-orderposepyyamlcorsdefinePropertyform-validationfunctionURLSearchParamscompile lessenvbyteLengthargsless mixinsidletrimStartObject.keyscore-jsrobustmoduleyamlexewatchingrm -rfpostcssdomes-shimsaccessorexpressionapolloconnectworkspace:*json-schema-validatorawaitArray.prototype.includesforEachlistenerslruopenerwhatwgbrowserlistSetuuidpromisessymlinkmkdirpparentECMAScript 2018jsonschematoSortedinternalimportapptoArraystringcharactersdeep-copyFloat32ArrayeventEmitterframeworktypeconcurrencyhttpstranspilerchromiumpropertydom-testing-libraryoptimizerexecutabledataes2016Uint8Arraylettimeequalnested cssweaksetassignequalityrapidfinduploadingrangeerrorfigletprotobufbyteflatRegExp#flagsECMAScript 2022utilsdateinstallESnextanimationES2015configurableisConcatSpreadableES2019shrinkwrapUint32ArrayimmerdotenvWeakMapcryptoscheme-validationcoloursharedinvariantshamlimitsuperagenttrimhasOwnsettingsES2018SymboliteratorCSScheckschemereact-testing-libraryreadablestreamsetharmonymakelockfileopenstatusregular expressionsmonorepofunctionalargvbrowserslistfastObject.getPrototypeOf[[Prototype]]serializationObservablescss-in-jscolumnspreserve-symlinksES2017ES6protocol-buffersjson-schema-validationcallbackstatelessdataViewfullwidthplugintostringtaglinuxoptionponyfilljavascriptqssyntaxerrorzodspringenumerablegetterbatchjwtsidejssearchtapeairbnbObject.entriesbabelregexcolorirqfantasy-landmergeRFC-6455linksortperformantclijsdiffminimalwebprivateprocessdeepcopycolorsstreamdiffinterruptsstartgetPrototypeOfbcryptmulti-packageerror-handlingECMAScript 7negative zeronopedependenciesgroupreducerstarteromitFunction.prototype.namegroupBynumbertyped arrayfseventsarraystextterminalES2022throttlenodejsdirectoryi18nJSONpropertiesvariableseventslibphonenumbersymbolscall-bindcurriedruntimecollectionsharedarraybufferarrayio-tscallboundobjectestreeStyleSheetrateprogressoffsetparserrgbmetadatarequireansiTypeBoxCSSStyleDeclarationtypaniongetes2017bufferspnpm9persistentES2020ECMAScript 2021efficientcodesmkdirstrimLeftArray.prototype.flatelectronecmascriptiteratequoteTypeScriptrmhelpersbddmime-dbreusearraybufferIteratorECMAScript 2020ES2021gradients css3apiwaapicolumntypeerrorwritetermopenseast-asian-widthBigInt64ArrayqueueMicrotaskES256wordbreakrfc4122mochadefaultES5findLastentriesqueuePromiseajaxpackage.jsonesfixed-widthgesturessomeinputduplexpostcss-plugincharacterbusytraverseAsyncIteratorpushhastddtypeofchilditerationdescriptorMicrosoftthreemovewidthwritableshebangratelimitlimitedtypedarraysreadablebannermrulinewrapArray.prototype.flatMapstringifylengthString.prototype.matchAlltypesfast-deep-clonedirdeterministicflatMapvaluescallbindtranspiletrimRightfastcopysliceuser-streamsquerystringperformancebootstrap cssenvironmentcopyassertsArrayBuffer.prototype.slicecensorregular expressionnamesArray.prototype.findLastsuperstructqueryless.jsInt16ArrayloggerMapweakmapstylesheettaska11yttyenderprivate dataYAMLjsonurluninstallfromremovebundlingjoibrowseryupsanitizationutilparentsfast-copyrandompreprocessortrimEndArray.prototype.filter-0hardlinkscompareless cssArray.prototype.findLastIndexless compilerwebsiteStreamszerodeleteredux-toolkitcoercibleObject.definePropertyES2023packagesfullreal-timeauthnativefoldergetOwnPropertyDescriptorbundleres2018hookspackagemomentkeyreactunicodecommand-lineescapeeslintpluginRxJSprettyformatObject.fromEntriesArray.prototype.flatteneventDispatchersequencelookcircularboundWebSocketseditorredactargumentcss nestingprefixmobileintrinsicpolyfillgetintrinsicdefineresolveFloat64ArraytestdebuggertoolsES8launchjsxutilitieslanguagehandlerschaiObject.assignes-shim APIutil.inspectcode pointsfindutilityspinneremitECMAScript 6stylesrmdirshimECMAScript 2019iegradients cssprotogdprkeyswatchexpressStreamlesscsscontainscss variablesignalECMAScript 2023tc39execfetchschemagraphqlwatchermatcheswhichglobfptelephonecall-boundcommandermacosregexpECMAScript 5Int8Arraywalk_.extendclientTypedArray.envchrometypesafeimmutablepopmotionshelles5setImmediate0stabledeepclonexssjsdomjQuerystylephonejasminereadmatchAllfull-widthlook-upsyntaxfile systemlazyramdatypedarraylessreact posesymlinksHyBieslint-pluginString.prototype.trimjson-schemadescriptorsmimetypesemojiasyncpicomatchpropArrayBufferreduxmkdircryptclass-validatorxdg-opensetPrototypeOfserializeWeakSetmimepackage managersanitizevariables in csswaitwatchFileconcatrecursiveObject.valuesES2016fastclonetypescriptrequest$.extendconfigwarningformsvalidatorObjectSymbol.toStringTagdataviewkarmasafecss lesscreatevalidECMAScript 2015debugArray.prototype.containstouchcompilerbyteOffsettestingfastifyECMAScript 2017react animationinferenceslotES7argparsepasswordjapaneseviewclone@@toStringTagReactiveXcoreoperating-systemstructuredCloneReactiveExtensionsWebSocketURLtoStringTagbreakastdeep-clonelastfsxtermchannelwindowscjkformattingRegExp.prototype.flagscurl

Readme

@teamteanpm2024/magni-architecto-odit

The most lightweight, customizable React markdown component.

npm version downloads


@teamteanpm2024/magni-architecto-odit uses a heavily-modified fork of simple-markdown as its parsing engine and extends it in a number of ways to make your life easier. Notably, this package offers the following additional benefits:

  • Arbitrary HTML is supported and parsed into the appropriate JSX representation without dangerouslySetInnerHTML

  • Any HTML tags rendered by the compiler and/or <Markdown> component can be overridden to include additional props or even a different HTML representation entirely.

  • GFM task list support.

  • Fenced code blocks with highlight.js support; see Syntax highlighting for instructions on setting up highlight.js.

All this clocks in at around 6 kB gzipped, which is a fraction of the size of most other React markdown components.

Requires React >= 0.14.

Installation

Install @teamteanpm2024/magni-architecto-odit with your favorite package manager.

npm i @teamteanpm2024/magni-architecto-odit

Usage

@teamteanpm2024/magni-architecto-odit exports a React component by default for easy JSX composition:

ES6-style usage*:

import Markdown from '@teamteanpm2024/magni-architecto-odit'
import React from 'react'
import { render } from 'react-dom'

render(<Markdown># Hello world!</Markdown>, document.body)

/*
    renders:

    <h1>Hello world!</h1>
 */

* NOTE: JSX does not natively preserve newlines in multiline text. In general, writing markdown directly in JSX is discouraged and it's a better idea to keep your content in separate .md files and require them, perhaps using webpack's raw-loader.

Parsing Options

options.forceBlock

By default, the compiler will try to make an intelligent guess about the content passed and wrap it in a <div>, <p>, or <span> as needed to satisfy the "inline"-ness of the markdown. For instance, this string would be considered "inline":

Hello. _Beautiful_ day isn't it?

But this string would be considered "block" due to the existence of a header tag, which is a block-level HTML element:

# Whaddup?

However, if you really want all input strings to be treated as "block" layout, simply pass options.forceBlock = true like this:

;<Markdown options={{ forceBlock: true }}>Hello there old chap!</Markdown>

// or

compiler('Hello there old chap!', { forceBlock: true })

// renders
;<p>Hello there old chap!</p>

options.forceInline

The inverse is also available by passing options.forceInline = true:

;<Markdown options={{ forceInline: true }}># You got it babe!</Markdown>

// or

compiler('# You got it babe!', { forceInline: true })

// renders
;<span># You got it babe!</span>

options.wrapper

When there are multiple children to be rendered, the compiler will wrap the output in a div by default. You can override this default by setting the wrapper option to either a string (React Element) or a component.

const str = '# Heck Yes\n\nThis is great!'

<Markdown options={{ wrapper: 'article' }}>
  {str}
</Markdown>;

// or

compiler(str, { wrapper: 'article' });

// renders

<article>
  <h1>Heck Yes</h1>
  <p>This is great!</p>
</article>
Other useful recipes

To get an array of children back without a wrapper, set wrapper to null. This is particularly useful when using compiler(…) directly.

compiler('One\n\nTwo\n\nThree', { wrapper: null })

// returns
;[<p>One</p>, <p>Two</p>, <p>Three</p>]

To render children at the same DOM level as <Markdown> with no HTML wrapper, set wrapper to React.Fragment. This will still wrap your children in a React node for the purposes of rendering, but the wrapper element won't show up in the DOM.

options.forceWrapper

By default, the compiler does not wrap the rendered contents if there is only a single child. You can change this by setting forceWrapper to true. If the child is inline, it will not necessarily be wrapped in a span.

// Using `forceWrapper` with a single, inline child…
<Markdown options={{ wrapper: 'aside', forceWrapper: true }}>
  Mumble, mumble…
</Markdown>

// renders

<aside>Mumble, mumble…</aside>

options.overrides - Override Any HTML Tag's Representation

Pass the options.overrides prop to the compiler or <Markdown> component to seamlessly revise the rendered representation of any HTML tag. You can choose to change the component itself, add/change props, or both.

import Markdown from '@teamteanpm2024/magni-architecto-odit'
import React from 'react'
import { render } from 'react-dom'

// surprise, it's a div instead!
const MyParagraph = ({ children, ...props }) => <div {...props}>{children}</div>

render(
  <Markdown
    options={{
      overrides: {
        h1: {
          component: MyParagraph,
          props: {
            className: 'foo',
          },
        },
      },
    }}
  >
    # Hello world!
  </Markdown>,
  document.body
)

/*
    renders:

    <div class="foo">
        Hello World
    </div>
 */

If you only wish to provide a component override, a simplified syntax is available:

{
    overrides: {
        h1: MyParagraph,
    },
}

Depending on the type of element, there are some props that must be preserved to ensure the markdown is converted as intended. They are:

  • a: title, href
  • img: title, alt, src
  • input[type="checkbox"]: checked, readonly (specifically, the one rendered by a GFM task list)
  • ol: start
  • td: style
  • th: style

Any conflicts between passed props and the specific properties above will be resolved in favor of @teamteanpm2024/magni-architecto-odit's code.

Some element mappings are a bit different from other libraries, in particular:

  • span: Used for inline text.
  • code: Used for inline code.
  • pre > code: Code blocks are a code element with a pre as its direct ancestor.

options.overrides - Rendering Arbitrary React Components

One of the most interesting use cases enabled by the HTML syntax processing in @teamteanpm2024/magni-architecto-odit is the ability to use any kind of element, even ones that aren't real HTML tags like React component classes.

By adding an override for the components you plan to use in markdown documents, it's possible to dynamically render almost anything. One possible scenario could be writing documentation:

import Markdown from '@teamteanpm2024/magni-architecto-odit'
import React from 'react'
import { render } from 'react-dom'

import DatePicker from './date-picker'

const md = `
# DatePicker

The DatePicker works by supplying a date to bias towards,
as well as a default timezone.

<DatePicker biasTowardDateTime="2017-12-05T07:39:36.091Z" timezone="UTC+5" />
`

render(
  <Markdown
    children={md}
    options={{
      overrides: {
        DatePicker: {
          component: DatePicker,
        },
      },
    }}
  />,
  document.body
)

@teamteanpm2024/magni-architecto-odit also handles JSX interpolation syntax, but in a minimal way to not introduce a potential attack vector. Interpolations are sent to the component as their raw string, which the consumer can then eval() or process as desired to their security needs.

In the following case, DatePicker could simply run parseInt() on the passed startTime for example:

import Markdown from '@teamteanpm2024/magni-architecto-odit'
import React from 'react'
import { render } from 'react-dom'

import DatePicker from './date-picker'

const md = `
# DatePicker

The DatePicker works by supplying a date to bias towards,
as well as a default timezone.

<DatePicker
  biasTowardDateTime="2017-12-05T07:39:36.091Z"
  timezone="UTC+5"
  startTime={1514579720511}
/>
`

render(
  <Markdown
    children={md}
    options={{
      overrides: {
        DatePicker: {
          component: DatePicker,
        },
      },
    }}
  />,
  document.body
)

Another possibility is to use something like recompose's withProps() HOC to create various pregenerated scenarios and then reference them by name in the markdown:

import Markdown from '@teamteanpm2024/magni-architecto-odit'
import React from 'react'
import { render } from 'react-dom'
import withProps from 'recompose/withProps'

import DatePicker from './date-picker'

const DecemberDatePicker = withProps({
  range: {
    start: new Date('2017-12-01'),
    end: new Date('2017-12-31'),
  },
  timezone: 'UTC+5',
})(DatePicker)

const md = `
# DatePicker

The DatePicker works by supplying a date to bias towards,
as well as a default timezone.

<DatePicker
  biasTowardDateTime="2017-12-05T07:39:36.091Z"
  timezone="UTC+5"
  startTime={1514579720511}
/>

Here's an example of a DatePicker pre-set to only the month of December:

<DecemberDatePicker />
`

render(
  <Markdown
    children={md}
    options={{
      overrides: {
        DatePicker,
        DecemberDatePicker,
      },
    }}
  />,
  document.body
)

options.createElement - Custom React.createElement behavior

Sometimes, you might want to override the React.createElement default behavior to hook into the rendering process before the JSX gets rendered. This might be useful to add extra children or modify some props based on runtime conditions. The function mirrors the React.createElement function, so the params are type, [props], [...children]:

import Markdown from '@teamteanpm2024/magni-architecto-odit'
import React from 'react'
import { render } from 'react-dom'

const md = `
# Hello world
`

render(
  <Markdown
    children={md}
    options={{
      createElement(type, props, children) {
        return (
          <div className="parent">
            {React.createElement(type, props, children)}
          </div>
        )
      },
    }}
  />,
  document.body
)

options.enforceAtxHeadings

Forces the compiler to have space between hash sign # and the header text which is explicitly stated in the most of the markdown specs.

The opening sequence of # characters must be followed by a space or by the end of line.

options.renderRule

Supply your own rendering function that can selectively override how rules are rendered (note, this is different than options.overrides which operates at the HTML tag level and is more general). You can use this functionality to do pretty much anything with an established AST node; here's an example of selectively overriding the "codeBlock" rule to process LaTeX syntax using the @matejmazur/react-katex library:

import Markdown, { RuleType } from '@teamteanpm2024/magni-architecto-odit'
import TeX from '@matejmazur/react-katex'

const exampleContent =
  'Some important formula:\n\n```latex\nmathbb{N} = { a in mathbb{Z} : a > 0 }\n```\n'

function App() {
  return (
    <Markdown
      children={exampleContent}
      options={{
        renderRule(next, node, renderChildren, state) {
          if (node.type === RuleType.codeBlock && node.lang === 'latex') {
            return (
              <TeX as="div" key={state.key}>{String.raw`${node.text}`}</TeX>
            )
          }

          return next()
        },
      }}
    />
  )
}

options.slugify

By default, a lightweight deburring function is used to generate an HTML id from headings. You can override this by passing a function to options.slugify. This is helpful when you are using non-alphanumeric characters (e.g. Chinese or Japanese characters) in headings. For example:

;<Markdown options={{ slugify: str => str }}># 中文</Markdown>

// or

compiler('# 中文', { slugify: str => str })

// renders:
;<h1 id="中文">中文</h1>

options.namedCodesToUnicode

By default only a couple of named html codes are converted to unicode characters:

  • & (&amp;)
  • ' (&apos;)
  • > (&gt;)
  • < (&lt;)
  • (&nbsp;)
  • " (&quot;)

Some projects require to extend this map of named codes and unicode characters. To customize this list with additional html codes pass the option namedCodesToUnicode as object with the code names needed as in the example below:

<Markdown options={{ namedCodesToUnicode: {
    le: '\u2264',
    ge: '\u2265',
    '#39': '\u0027',
} }}>This text is &le; than this text.</Markdown>;

// or

compiler('This text is &le; than this text.', namedCodesToUnicode: {
    le: '\u2264',
    ge: '\u2265',
    '#39': '\u0027',
});

// renders:

<p>This text is ≤ than this text.</p>

options.disableParsingRawHTML

By default, raw HTML is parsed to JSX. This behavior can be disabled with this option.

<Markdown options={{ disableParsingRawHTML: true }}>
    This text has <span>html</span> in it but it won't be rendered
</Markdown>;

// or

compiler('This text has <span>html</span> in it but it won't be rendered', { disableParsingRawHTML: true });

// renders:

<span>This text has &lt;span&gt;html&lt;/span&gt; in it but it won't be rendered</span>

Syntax highlighting

When using fenced code blocks with language annotation, that language will be added to the <code> element as class="lang-${language}". For best results, you can use options.overrides to provide an appropriate syntax highlighting integration like this one using highlight.js:

import { Markdown, RuleType } from '@teamteanpm2024/magni-architecto-odit'

const mdContainingFencedCodeBlock = '```js\nconsole.log("Hello world!");\n```\n'

function App() {
  return (
    <Markdown
      children={mdContainingFencedCodeBlock}
      options={{
        overrides: {
          code: SyntaxHighlightedCode,
        },
      }}
    />
  )
}

/**
 * Add the following tags to your page <head> to automatically load hljs and styles:

  <link
    rel="stylesheet"
    href="https://unpkg.com/@highlightjs/[email protected]/styles/nord.min.css"
  />

  * NOTE: for best performance, load individual languages you need instead of all
          of them. See their docs for more info: https://highlightjs.org/

  <script
    crossorigin
    src="https://unpkg.com/@highlightjs/[email protected]/highlight.min.js"
  ></script>
 */

function SyntaxHighlightedCode(props) {
  const ref = (React.useRef < HTMLElement) | (null > null)

  React.useEffect(() => {
    if (ref.current && props.className?.includes('lang-') && window.hljs) {
      window.hljs.highlightElement(ref.current)

      // hljs won't reprocess the element unless this attribute is removed
      ref.current.removeAttribute('data-highlighted')
    }
  }, [props.className, props.children])

  return <code {...props} ref={ref} />
}

Getting the smallest possible bundle size

Many development conveniences are placed behind process.env.NODE_ENV !== "production" conditionals. When bundling your app, it's a good idea to replace these code snippets such that a minifier (like uglify) can sweep them away and leave a smaller overall bundle.

Here are instructions for some of the popular bundlers:

Usage with Preact

Everything will work just fine! Simply Alias react to preact/compat like you probably already are doing.

Gotchas

Significant indentation inside arbitrary HTML

People usually write HTML like this:

<div>Hey, how are you?</div>

Note the leading spaces before the inner content. This sort of thing unfortunately clashes with existing markdown syntaxes since 4 spaces === a code block and other similar collisions.

To get around this, @teamteanpm2024/magni-architecto-odit left-trims approximately as much whitespace as the first line inside the HTML block. So for example:

<div># Hello How are you?</div>

The two leading spaces in front of "# Hello" would be left-trimmed from all lines inside the HTML block. In the event that there are varying amounts of indentation, only the amount of the first line is trimmed.

NOTE! These syntaxes work just fine when you aren't writing arbitrary HTML wrappers inside your markdown. This is very much an edge case of an edge case. 🙃

Code blocks

⛔️

<div>
    var some = code();
</div>

<div>
```js
var some = code();
``\`
</div>

Using The Compiler Directly

If desired, the compiler function is a "named" export on the @teamteanpm2024/magni-architecto-odit module:

import { compiler } from '@teamteanpm2024/magni-architecto-odit'
import React from 'react'
import { render } from 'react-dom'

render(compiler('# Hello world!'), document.body)

/*
    renders:

    <h1>Hello world!</h1>
 */

It accepts the following arguments:

compiler(markdown: string, options: object?)

Changelog

See Github Releases.

Donate

Like this library? It's developed entirely on a volunteer basis; chip in a few bucks if you can via the Sponsor link!

MIT