1
1
mirror of https://github.com/primer/css.git synced 2024-12-01 04:21:12 +03:00
css/docs/utils.js

88 lines
2.3 KiB
JavaScript
Raw Normal View History

2019-01-17 08:27:39 +03:00
import React from 'react'
import getConfig from 'next/config'
2018-12-05 02:46:38 +03:00
import TreeModel from 'tree-model'
export const CommonStyles = () => {
2019-01-16 01:16:25 +03:00
const sheets = [getAssetPath('github/styleguide.css')]
2019-01-17 08:27:39 +03:00
return sheets.map(href => <link href={href} rel="stylesheet" key={href} />)
}
2019-01-16 01:16:25 +03:00
export const CommonScripts = () => <script src={getAssetPath('github/styleguide.js')} />
2018-12-05 02:46:38 +03:00
const INDEX_PATTERN = /\/index(\.[a-z]+)?$/
export const config = getConfig().publicRuntimeConfig || {}
export const assetPrefix = config.assetPrefix || ''
2018-12-05 12:39:40 +03:00
export const assetPath = `${assetPrefix}/static/`
export const getAssetPath = path => `${assetPath}${path}`
const ext = /\.mdx?$/
export const requirePage = require.context('../pages', true, /\.mdx?$/)
export const pathMap = requirePage.keys().reduce((map, key) => {
const base = key.replace(ext, '').replace(/\/index$/, '')
const path = base.substr(1) // strip the leading "."
map[path] = key
return map
}, {})
2018-12-05 02:46:38 +03:00
const nested = nest(pathMap)
export const pageTree = new TreeModel()
export const rootPage = pageTree.parse(nested)
rootPage.walk(node => {
const {model} = node
Object.assign(node, model)
if (node.file) {
const component = requirePage(node.file)
node.meta = component.frontMatter || {}
node.outline = component.tableOfContents
2018-12-05 02:46:38 +03:00
} else {
2018-12-05 03:20:57 +03:00
// eslint-disable-next-line no-console
2018-12-05 02:46:38 +03:00
console.warn('no file for page node:', node.path)
}
})
function nest(map) {
const nodeMap = {}
2018-12-05 03:20:57 +03:00
const nodes = Object.keys(map)
.sort()
.map(path => {
const file = map[path]
const keys = path.substr(1).split('/')
return (nodeMap[path] = {
path,
file,
isIndex: INDEX_PATTERN.test(file),
parent: `/${keys.slice(0, keys.length - 1).join('/')}`,
children: []
})
})
2018-12-05 02:46:38 +03:00
let root = nodeMap['/']
if (!root) {
const sorted = nodes.sort((a, b) => a.path.localeCompare(b.path))
root = sorted[0]
}
// remove root from the list of nodes
nodes.splice(nodes.indexOf(root), 1)
const rest = []
for (const node of nodes) {
const parent = nodeMap[node.parent]
if (parent) {
parent.children.push(node)
} else {
rest.push(node)
}
}
if (rest.length) {
2018-12-05 03:20:57 +03:00
// eslint-disable-next-line no-console
2018-12-05 02:46:38 +03:00
console.warn('unable to nest some pages:', rest)
}
return root
}