From 43ece07c151fd25e78c956d8650897e5d59b2c17 Mon Sep 17 00:00:00 2001 From: 20shivangi <45754171+20shivangi@users.noreply.github.com> Date: Wed, 8 Feb 2023 10:11:28 +0530 Subject: [PATCH] Setting up accessibility linting (#433) * Adding required packages and configurations * Fixes done by npm run lintfix * Linti errors fixed by disabling some rules * Fixing lint errors manually * Addressing comment --- package-lock.json | 25 +++-- theme/.eslintrc.js | 11 ++- theme/gatsby-browser.js | 4 +- theme/gatsby-config.js | 6 +- theme/gatsby-node.js | 52 ++++------ theme/gatsby-ssr.js | 4 +- theme/index.js | 30 +++--- theme/package.json | 8 +- theme/scripts/template-oss/index.js | 11 +-- theme/src/aria-live.js | 6 +- .../components/__tests__/contributors.test.js | 16 ++- .../components/__tests__/page-footer.test.js | 16 ++- theme/src/components/blockquote.js | 2 +- theme/src/components/caption.js | 4 +- theme/src/components/clipboard-copy.js | 8 +- theme/src/components/code.js | 56 +++++------ theme/src/components/container.js | 4 +- theme/src/components/contributors.js | 19 ++-- theme/src/components/dark-button.js | 2 +- theme/src/components/dark-text-input.js | 2 +- theme/src/components/description-list.js | 2 +- theme/src/components/details.js | 12 +-- theme/src/components/do-dont.js | 20 ++-- theme/src/components/drawer.js | 26 ++--- theme/src/components/frame.js | 12 +-- theme/src/components/head.js | 8 +- theme/src/components/header.js | 48 +++------ theme/src/components/heading.js | 42 ++++---- theme/src/components/hero-layout.js | 15 +-- theme/src/components/hero.js | 6 +- theme/src/components/horizontal-rule.js | 2 +- theme/src/components/image.js | 2 +- theme/src/components/index.js | 24 ++--- theme/src/components/inline-code.js | 2 +- theme/src/components/layout.js | 97 +++++++------------ theme/src/components/list.js | 2 +- theme/src/components/live-code.js | 40 +++----- theme/src/components/live-preview-wrapper.js | 4 +- theme/src/components/mobile-search.js | 57 +++++------ theme/src/components/nav-drawer.js | 64 +++--------- theme/src/components/nav-dropdown.js | 18 ++-- theme/src/components/nav-items.js | 56 ++++++----- theme/src/components/note.js | 22 ++--- theme/src/components/npm-logo.js | 13 ++- theme/src/components/page-footer.js | 10 +- theme/src/components/paragraph.js | 2 +- theme/src/components/prompt-reply.js | 4 +- theme/src/components/prompt.js | 10 +- theme/src/components/screenshot.js | 12 ++- theme/src/components/search-results.js | 15 ++- theme/src/components/search.js | 29 ++---- theme/src/components/sidebar.js | 14 +-- theme/src/components/skip-link.js | 13 +-- theme/src/components/source-link.js | 6 +- theme/src/components/status-label.js | 8 +- theme/src/components/table-of-contents.js | 20 ++-- theme/src/components/table.js | 2 +- theme/src/components/variant-select.js | 43 ++++---- theme/src/components/wrap-page-element.js | 4 +- theme/src/components/wrap-root-element.js | 10 +- theme/src/nav-hierarchy.js | 76 ++++++++------- theme/src/search.worker.js | 17 ++-- theme/src/use-search.js | 39 ++++---- theme/src/use-site-metadata.js | 4 +- 64 files changed, 532 insertions(+), 686 deletions(-) diff --git a/package-lock.json b/package-lock.json index 89aba8393df..3863bdf218e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -2631,6 +2631,12 @@ "resolved": "https://registry.npmjs.org/@github/paste-markdown/-/paste-markdown-1.4.2.tgz", "integrity": "sha512-ZwSgPyo9nA6TRngXV0QnFT4e5ujeOGxRDWN2aa6qfimz2o2VOsJ9bFGuGvB723nvzq5z9zKr6JWGtvK7MSJj3w==" }, + "node_modules/@github/prettier-config": { + "version": "0.0.6", + "resolved": "https://registry.npmjs.org/@github/prettier-config/-/prettier-config-0.0.6.tgz", + "integrity": "sha512-Sdb089z+QbGnFF2NivbDeaJ62ooPlD31wE6Fkb/ESjAOXSjNJo+gjqzYYhlM7G3ERJmKFZRUJYMlsqB7Tym8lQ==", + "dev": true + }, "node_modules/@github/relative-time-element": { "version": "4.1.2", "resolved": "https://registry.npmjs.org/@github/relative-time-element/-/relative-time-element-4.1.2.tgz", @@ -12133,9 +12139,9 @@ } }, "node_modules/eslint": { - "version": "8.31.0", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.31.0.tgz", - "integrity": "sha512-0tQQEVdmPZ1UtUKXjX7EMm9BlgJ08G90IhWh0PKDCb3ZLsgAOHI8fYSIzYVZej92zsgq+ft0FGsxhJ3xo2tbuA==", + "version": "8.33.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.33.0.tgz", + "integrity": "sha512-WjOpFQgKK8VrCnAtl8We0SUOy/oVZ5NHykyMiagV1M9r8IFpIJX7DduK6n1mpfhlG7T1NLWm2SuD8QB7KFySaA==", "dependencies": { "@eslint/eslintrc": "^1.4.1", "@humanwhocodes/config-array": "^0.11.8", @@ -24343,9 +24349,9 @@ } }, "node_modules/prettier": { - "version": "2.8.1", - "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.8.1.tgz", - "integrity": "sha512-lqGoSJBQNJidqCHE80vqZJHWHRFoNYsSpP9AjFhlhi9ODCJA541svILes/+/1GM3VaL/abZi7cpFzOpdR9UPKg==", + "version": "2.8.3", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.8.3.tgz", + "integrity": "sha512-tJ/oJ4amDihPoufT5sM0Z1SKEuKay8LfVAMlbbhnnkvt6BUserZylqo2PN+p9KeljLr0OHa2rXHU1T8reeoTrw==", "dev": true, "bin": { "prettier": "bin-prettier.js" @@ -32532,15 +32538,18 @@ "styled-system": "^5.1.5" }, "devDependencies": { + "@github/prettier-config": "^0.0.6", "@npmcli/template-oss": "4.11.0", "@testing-library/jest-dom": "^5.16.5", "babel-jest": "^29.3.1", - "eslint": "^8.29.0", + "eslint": "^8.33.0", + "eslint-plugin-github": "^4.6.0", "eslint-plugin-jsx-a11y": "^6.6.1", "eslint-plugin-primer-react": "1.0.1", "eslint-plugin-react": "^7.31.11", "jest": "^29.3.1", - "jest-environment-jsdom": "^29.3.1" + "jest-environment-jsdom": "^29.3.1", + "prettier": "^2.8.3" }, "engines": { "node": ">=18.0.0" diff --git a/theme/.eslintrc.js b/theme/.eslintrc.js index cc6c9b2ae2e..b4ba0573d3f 100644 --- a/theme/.eslintrc.js +++ b/theme/.eslintrc.js @@ -14,8 +14,9 @@ module.exports = { '@npmcli', 'eslint:recommended', 'plugin:react/recommended', - 'plugin:jsx-a11y/recommended', + 'plugin:github/react', 'plugin:primer-react/recommended', + 'prettier', ], settings: { react: { @@ -28,16 +29,18 @@ module.exports = { 'react/display-name': 'off', 'eslint-comments/no-use': 'off', 'no-shadow': 'off', - 'primer-react/no-system-props': ['warn', { includeUtilityComponents: true }], + 'primer-react/no-system-props': ['warn', {includeUtilityComponents: true}], + 'import/no-commonjs': 'off', + 'no-console': 'off', }, overrides: [ { files: ['gatsby-node.js', 'gatsby-config.js'], - env: { node: true, browser: false }, + env: {node: true, browser: false}, }, { files: ['test/*', './src/**/__tests__/*'], - env: { jest: true }, + env: {jest: true}, }, ], } diff --git a/theme/gatsby-browser.js b/theme/gatsby-browser.js index e665b80f2fa..d1c556c1098 100644 --- a/theme/gatsby-browser.js +++ b/theme/gatsby-browser.js @@ -1,2 +1,2 @@ -export { default as wrapPageElement } from './src/components/wrap-page-element' -export { default as wrapRootElement } from './src/components/wrap-root-element' +export {default as wrapPageElement} from './src/components/wrap-page-element' +export {default as wrapRootElement} from './src/components/wrap-root-element' diff --git a/theme/gatsby-config.js b/theme/gatsby-config.js index daa5d6a4fb4..24cd2d45c2d 100644 --- a/theme/gatsby-config.js +++ b/theme/gatsby-config.js @@ -1,6 +1,6 @@ const path = require('path') -module.exports = (themeOptions) => { +module.exports = themeOptions => { return { plugins: [ 'gatsby-plugin-styled-components', @@ -26,9 +26,7 @@ module.exports = (themeOptions) => { { resolve: 'gatsby-plugin-manifest', options: { - icon: themeOptions.icon - ? path.resolve(themeOptions.icon) - : require.resolve('./src/images/favicon.png'), + icon: themeOptions.icon ? path.resolve(themeOptions.icon) : require.resolve('./src/images/favicon.png'), }, }, ], diff --git a/theme/gatsby-node.js b/theme/gatsby-node.js index 5a9264849cc..ac2fe46a33c 100644 --- a/theme/gatsby-node.js +++ b/theme/gatsby-node.js @@ -6,7 +6,7 @@ const uniqBy = require('lodash.uniqby') const CONTRIBUTOR_CACHE = new Map() -exports.createSchemaCustomization = ({ actions: { createTypes } }) => { +exports.createSchemaCustomization = ({actions: {createTypes}}) => { createTypes(` type Mdx implements Node { frontmatter: MdxFrontmatter @@ -26,10 +26,10 @@ exports.createSchemaCustomization = ({ actions: { createTypes } }) => { `) } -exports.createPages = async ({ graphql, actions }, themeOptions) => { - const repo = themeOptions.repo ? themeOptions.repo : { url: getPkgRepo(readPkgUp.sync().package).browse() } +exports.createPages = async ({graphql, actions}, themeOptions) => { + const repo = themeOptions.repo ? themeOptions.repo : {url: getPkgRepo(readPkgUp.sync().package).browse()} - const { data } = await graphql(` + const {data} = await graphql(` { allMdx { nodes { @@ -68,15 +68,9 @@ exports.createPages = async ({ graphql, actions }, themeOptions) => { data.allMdx.nodes.map(async node => { const pagePath = getPath(node) - const rootAbsolutePath = path.resolve( - process.cwd(), - themeOptions.repoRootPath || '.' - ) + const rootAbsolutePath = path.resolve(process.cwd(), themeOptions.repoRootPath || '.') - const fileRelativePath = path.relative( - rootAbsolutePath, - node.fileAbsolutePath - ) + const fileRelativePath = path.relative(rootAbsolutePath, node.fileAbsolutePath) const editUrl = getEditUrl(themeOptions, repo, fileRelativePath, node.frontmatter) @@ -98,10 +92,10 @@ exports.createPages = async ({ graphql, actions }, themeOptions) => { }) if (node.frontmatter.redirect_from) { - node.frontmatter.redirect_from.forEach((from) => { + for (const from of node.frontmatter.redirect_from) { actions.createRedirect({ fromPath: from, - toPath: '/' + pagePath, + toPath: `/${pagePath}`, isPermanent: true, redirectInBrowser: true, }) @@ -109,18 +103,18 @@ exports.createPages = async ({ graphql, actions }, themeOptions) => { if (pagePath.startsWith('cli/') && !from.endsWith('index')) { actions.createRedirect({ fromPath: `${from}.html`, - toPath: '/' + pagePath, + toPath: `/${pagePath}`, isPermanent: true, redirectInBrowser: true, }) } - }) + } } - }) + }), ) } -function getPath (node) { +function getPath(node) { // sites can programmatically override slug, that takes priority if (node.fields && node.fields.slug) { return node.fields.slug @@ -132,14 +126,12 @@ function getPath (node) { } // finally, we'll just use the path on disk - return path.join( - node.parent.relativeDirectory, - node.parent.name === 'index' ? '/' : node.parent.name - ) + return path + .join(node.parent.relativeDirectory, node.parent.name === 'index' ? '/' : node.parent.name) .replace(/\\/g, '/') // Windows paths to forward slashes } -function getNameWithOwner (url) { +function getNameWithOwner(url) { const nwo = url.match(/^http(?:s)?:\/\/(?:www\.)?github\.com\/([^/]+\/[^/]+)(?:\/)?$/i) if (nwo) { @@ -149,7 +141,7 @@ function getNameWithOwner (url) { return null } -function getGitHubData (repo, overrideData, filePath) { +function getGitHubData(repo, overrideData, filePath) { const gh = { nwo: getNameWithOwner(repo.url), branch: 'master', @@ -168,7 +160,7 @@ function getGitHubData (repo, overrideData, filePath) { if (overrideData.github_path) { gh.path = overrideData.github_path } else if (repo.path) { - gh.path = repo.path + '/' + filePath + gh.path = `${repo.path}/${filePath}` } else { gh.path = filePath } @@ -176,7 +168,7 @@ function getGitHubData (repo, overrideData, filePath) { return gh } -function getEditUrl (themeOptions, repo, filePath, overrideData = { }) { +function getEditUrl(themeOptions, repo, filePath, overrideData = {}) { if (themeOptions.editOnGitHub === false || overrideData.edit_on_github === false) { return null } @@ -185,7 +177,7 @@ function getEditUrl (themeOptions, repo, filePath, overrideData = { }) { return `https://github.com/${gh.nwo}/edit/${gh.branch}/${gh.path}` } -async function fetchContributors (repo, filePath, overrideData = { }, accessToken = '') { +async function fetchContributors(repo, filePath, overrideData = {}, accessToken = '') { const gh = getGitHubData(repo, overrideData, filePath) const cached = CONTRIBUTOR_CACHE.get(gh) @@ -206,7 +198,7 @@ async function fetchContributors (repo, filePath, overrideData = { }, accessToke } } - const { data } = await axios.request(req) + const {data} = await axios.request(req) const commits = data .map(commit => ({ @@ -222,9 +214,7 @@ async function fetchContributors (repo, filePath, overrideData = { }, accessToke CONTRIBUTOR_CACHE.set(gh, result) return result } catch (error) { - console.error( - `[ERROR] Unable to fetch contributors for ${filePath}. ${error.message}` - ) + console.error(`[ERROR] Unable to fetch contributors for ${filePath}. ${error.message}`) return [] } } diff --git a/theme/gatsby-ssr.js b/theme/gatsby-ssr.js index e665b80f2fa..d1c556c1098 100644 --- a/theme/gatsby-ssr.js +++ b/theme/gatsby-ssr.js @@ -1,2 +1,2 @@ -export { default as wrapPageElement } from './src/components/wrap-page-element' -export { default as wrapRootElement } from './src/components/wrap-root-element' +export {default as wrapPageElement} from './src/components/wrap-page-element' +export {default as wrapRootElement} from './src/components/wrap-root-element' diff --git a/theme/index.js b/theme/index.js index 7df8f534300..56098d0fc7f 100644 --- a/theme/index.js +++ b/theme/index.js @@ -1,15 +1,15 @@ -export { default as Caption } from './src/components/caption' -export { default as Container } from './src/components/container' -export { default as Contributors } from './src/components/contributors' -export { Do, DoDontContainer, Dont } from './src/components/do-dont' -export { default as Frame } from './src/components/frame' -export { default as Head } from './src/components/head' -export { default as Header } from './src/components/header' -export { default as Hero } from './src/components/hero' -export { default as HeroLayout } from './src/components/hero-layout' -export { default as Index } from './src/components/index' -export { default as Note } from './src/components/note' -export { default as Screenshot } from './src/components/screenshot' -export { default as Sidebar } from './src/components/sidebar' -export { default as SourceLink } from './src/components/source-link' -export { default as StatusLabel } from './src/components/status-label' +export {default as Caption} from './src/components/caption' +export {default as Container} from './src/components/container' +export {default as Contributors} from './src/components/contributors' +export {Do, DoDontContainer, Dont} from './src/components/do-dont' +export {default as Frame} from './src/components/frame' +export {default as Head} from './src/components/head' +export {default as Header} from './src/components/header' +export {default as Hero} from './src/components/hero' +export {default as HeroLayout} from './src/components/hero-layout' +export {default as Index} from './src/components/index' +export {default as Note} from './src/components/note' +export {default as Screenshot} from './src/components/screenshot' +export {default as Sidebar} from './src/components/sidebar' +export {default as SourceLink} from './src/components/source-link' +export {default as StatusLabel} from './src/components/status-label' diff --git a/theme/package.json b/theme/package.json index 17c79704a2a..f00bc8a5d82 100644 --- a/theme/package.json +++ b/theme/package.json @@ -9,6 +9,7 @@ "private": true, "main": "index.js", "license": "MIT", + "prettier": "@github/prettier-config", "scripts": { "test": "jest", "lint": "eslint \"**/*.js\"", @@ -70,15 +71,18 @@ "styled-system": "^5.1.5" }, "devDependencies": { + "@github/prettier-config": "^0.0.6", "@npmcli/template-oss": "4.11.0", "@testing-library/jest-dom": "^5.16.5", "babel-jest": "^29.3.1", - "eslint": "^8.29.0", + "eslint": "^8.33.0", + "eslint-plugin-github": "^4.6.0", "eslint-plugin-jsx-a11y": "^6.6.1", "eslint-plugin-primer-react": "1.0.1", "eslint-plugin-react": "^7.31.11", "jest": "^29.3.1", - "jest-environment-jsdom": "^29.3.1" + "jest-environment-jsdom": "^29.3.1", + "prettier": "^2.8.3" }, "author": "GitHub Inc.", "engines": { diff --git a/theme/scripts/template-oss/index.js b/theme/scripts/template-oss/index.js index 920c942a0f6..74ee0ff9ad9 100644 --- a/theme/scripts/template-oss/index.js +++ b/theme/scripts/template-oss/index.js @@ -6,16 +6,9 @@ module.exports = { '.eslintrc.js': false, }, }, - allowPaths: [ - '/src', - '/gatsby-*.js', - '/jest*.js', - '/index.js', - ], + allowPaths: ['/src', '/gatsby-*.js', '/jest*.js', '/index.js'], requiredPackages: { devDependencies: [], }, - allowedPackages: [ - 'eslint', - ], + allowedPackages: ['eslint'], } diff --git a/theme/src/aria-live.js b/theme/src/aria-live.js index 38d8963d634..22632493414 100644 --- a/theme/src/aria-live.js +++ b/theme/src/aria-live.js @@ -15,7 +15,7 @@ if (typeof window !== 'undefined') { } // Announce message update to screen reader. -function announce (message) { +function announce(message) { if (!container || !container.isConnected) { /* This condition is for when the aria-live container no longer exists due to nav methods like turbo drive which replace the body getting rid of the region. We add the container if it's missing. We then add a delay @@ -33,7 +33,7 @@ function announce (message) { } // Set aria-live container to message. -function setContainerContent (message) { +function setContainerContent(message) { if (!container) { return } @@ -50,7 +50,7 @@ function setContainerContent (message) { } // Get the global screen reader notice container. -function createNoticeContainer () { +function createNoticeContainer() { container = document.createElement('div') container.setAttribute('aria-live', 'polite') container.style.position = 'absolute' diff --git a/theme/src/components/__tests__/contributors.test.js b/theme/src/components/__tests__/contributors.test.js index a3e86c3ce9e..72802c24e92 100644 --- a/theme/src/components/__tests__/contributors.test.js +++ b/theme/src/components/__tests__/contributors.test.js @@ -1,9 +1,9 @@ -import { render } from '@testing-library/react' +import {render} from '@testing-library/react' import React from 'react' import Contributors from '../contributors' test('renders contributors', () => { - const { queryByText } = render( + const {queryByText} = render( { }, }, ]} - /> + />, ) expect(queryByText(/2 contributors/)).toBeInTheDocument() @@ -31,9 +31,7 @@ test('renders contributors', () => { }) test('does not render "last edited by" if latest contributor does not have a latest commit', () => { - const { queryByText } = render( - - ) + const {queryByText} = render() expect(queryByText(/1 contributor/)).toBeInTheDocument() expect(queryByText(/Last edited by/)).toBeNull() @@ -42,13 +40,13 @@ test('does not render "last edited by" if latest contributor does not have a lat // The `Contributors` component is unlikely to be passed an empty array // but it should be able to handle an empty array gracefully just in case. test('handles no contributors', () => { - const { queryByText } = render() + const {queryByText} = render() expect(queryByText(/0 contributors/)).toBeInTheDocument() }) test('does not render duplicate contributors', () => { - const { queryByText } = render( + const {queryByText} = render( { }, }, ]} - /> + />, ) expect(queryByText(/1 contributor/)).toBeInTheDocument() diff --git a/theme/src/components/__tests__/page-footer.test.js b/theme/src/components/__tests__/page-footer.test.js index 19fa1bf4c20..f2ee21d839e 100644 --- a/theme/src/components/__tests__/page-footer.test.js +++ b/theme/src/components/__tests__/page-footer.test.js @@ -1,41 +1,37 @@ -import { render } from '@testing-library/react' +import {render} from '@testing-library/react' import React from 'react' import PageFooter from '../page-footer' test('renders correctly when editUrl and contributors are defined', () => { - const { queryByText } = render( - - ) + const {queryByText} = render() expect(queryByText(/Edit this page on GitHub/)).toBeInTheDocument() expect(queryByText(/contributor/)).toBeInTheDocument() }) test('renders correctly when editUrl and contributors are undefined', () => { - const { queryByText } = render() + const {queryByText} = render() expect(queryByText(/Edit this page on GitHub/)).toBeNull() expect(queryByText(/contributor/)).toBeNull() }) test('renders correctly when editUrl is defined but contributors is undefined', () => { - const { queryByText } = render() + const {queryByText} = render() expect(queryByText(/Edit this page on GitHub/)).toBeInTheDocument() expect(queryByText(/contributor/)).toBeNull() }) test('renders correctly when contributors is defined but editUrl is undefined', () => { - const { queryByText } = render( - - ) + const {queryByText} = render() expect(queryByText(/Edit this page on GitHub/)).toBeNull() expect(queryByText(/contributor/)).toBeInTheDocument() }) test('does not render contributors if contributors is an empty array', () => { - const { queryByText } = render() + const {queryByText} = render() expect(queryByText(/contributor/)).toBeNull() }) diff --git a/theme/src/components/blockquote.js b/theme/src/components/blockquote.js index f1fde994e02..fd0c467b244 100644 --- a/theme/src/components/blockquote.js +++ b/theme/src/components/blockquote.js @@ -1,5 +1,5 @@ import styled from 'styled-components' -import themeGet from '@styled-system/theme-get' +import {themeGet} from '@styled-system/theme-get' const Blockquote = styled.blockquote` margin: 0 0 ${themeGet('space.3')}; diff --git a/theme/src/components/caption.js b/theme/src/components/caption.js index 68c9b87fe58..c4692433b58 100644 --- a/theme/src/components/caption.js +++ b/theme/src/components/caption.js @@ -1,7 +1,7 @@ -import { Text } from '@primer/components' +import {Text} from '@primer/components' import React from 'react' -function Caption (props) { +function Caption(props) { return } diff --git a/theme/src/components/clipboard-copy.js b/theme/src/components/clipboard-copy.js index b1a23005158..3de806bba51 100644 --- a/theme/src/components/clipboard-copy.js +++ b/theme/src/components/clipboard-copy.js @@ -1,9 +1,9 @@ -import { Button, StyledOcticon, themeGet } from '@primer/components' -import { CheckIcon, CopyIcon } from '@primer/octicons-react' +import {Button, StyledOcticon, themeGet} from '@primer/components' +import {CheckIcon, CopyIcon} from '@primer/octicons-react' import styled from 'styled-components' import copy from 'copy-to-clipboard' import React from 'react' -import { announce } from '../aria-live' +import {announce} from '../aria-live' const CopyToClipboard = styled(Button)` &:focus { @@ -11,7 +11,7 @@ const CopyToClipboard = styled(Button)` } ` -function ClipboardCopy ({ value }) { +function ClipboardCopy({value}) { const [copied, setCopied] = React.useState(false) React.useEffect(() => { diff --git a/theme/src/components/code.js b/theme/src/components/code.js index ee31165d0fe..2024b1b7d94 100644 --- a/theme/src/components/code.js +++ b/theme/src/components/code.js @@ -1,12 +1,12 @@ -import { Absolute, BorderBox, Relative, Text } from '@primer/components' -import Highlight, { defaultProps } from 'prism-react-renderer' +import {Absolute, BorderBox, Relative, Text} from '@primer/components' +import Highlight, {defaultProps} from 'prism-react-renderer' import githubTheme from 'prism-react-renderer/themes/github' -import React, { useState, useEffect } from 'react' +import React, {useState, useEffect} from 'react' import ClipboardCopy from './clipboard-copy' import LiveCode from './live-code' -function Code ({ className, children, live, noinline }) { - const [scrollHandleStyle, setScrollHandleStyle] = useState({ position: 'absolute' }) +function Code({className, children, live, noinline}) { + const [scrollHandleStyle, setScrollHandleStyle] = useState({position: 'absolute'}) const language = className ? className.replace(/language-/, '') : '' const code = children.trim() const scrollHandleRef = React.createRef() @@ -24,34 +24,18 @@ function Code ({ className, children, live, noinline }) { - - {({ className, style, tokens, getLineProps, getTokenProps }) => ( - + + {({className, style, tokens, getLineProps, getTokenProps}) => ( + {/* This is the scroll handle, it is supposed to be focused with keyboard and scroll a wide codebox horizontally */} {/* eslint-disable-next-line jsx-a11y/no-noninteractive-tabindex */} - + {tokens.map((line, i) => ( -
+
{line.map((token, key) => ( - + ))}
))} @@ -64,7 +48,7 @@ function Code ({ className, children, live, noinline }) { /** * Resize the scroll handle to the size of the code contents, since the former has to be positioned absolutely. */ - function resizeScrollHandle () { + function resizeScrollHandle() { // Skip if already resized. if (typeof scrollHandleStyle.width !== 'undefined') { return @@ -73,9 +57,15 @@ function Code ({ className, children, live, noinline }) { const node = scrollHandleRef.current node.parentElement.style.position = 'relative' const computedStyle = getComputedStyle(node.parentElement) - const height = node.parentElement.clientHeight - parseInt(computedStyle.paddingTop, 10) - parseInt(computedStyle.paddingBottom, 10) - const width = node.parentElement.scrollWidth - parseInt(computedStyle.paddingLeft, 10) - parseInt(computedStyle.paddingRight, 10) - setScrollHandleStyle({ ...scrollHandleStyle, height, width }) + const height = + node.parentElement.clientHeight - + parseInt(computedStyle.paddingTop, 10) - + parseInt(computedStyle.paddingBottom, 10) + const width = + node.parentElement.scrollWidth - + parseInt(computedStyle.paddingLeft, 10) - + parseInt(computedStyle.paddingRight, 10) + setScrollHandleStyle({...scrollHandleStyle, height, width}) } } diff --git a/theme/src/components/container.js b/theme/src/components/container.js index 00812aee897..b760afed22d 100644 --- a/theme/src/components/container.js +++ b/theme/src/components/container.js @@ -1,7 +1,7 @@ -import { Box } from '@primer/components' +import {Box} from '@primer/components' import React from 'react' -function Container ({ children }) { +function Container({children}) { return ( {children} diff --git a/theme/src/components/contributors.js b/theme/src/components/contributors.js index da27402f835..43c617b002d 100644 --- a/theme/src/components/contributors.js +++ b/theme/src/components/contributors.js @@ -1,12 +1,12 @@ -import { Avatar, Flex, Link, Text, Tooltip } from '@primer/components' -import { format } from 'date-fns' +import {Avatar, Flex, Link, Text, Tooltip} from '@primer/components' +import {format} from 'date-fns' import uniqBy from 'lodash.uniqby' import pluralize from 'pluralize' import React from 'react' // The `contributors` array is fetched in gatsby-node.js at build-time. -function Contributors ({ contributors }) { +function Contributors({contributors}) { const uniqueContributors = uniqBy(contributors, 'login') const latestContributor = uniqueContributors[0] || {} @@ -14,8 +14,7 @@ function Contributors ({ contributors }) {
- {uniqueContributors.length}{' '} - {pluralize('contributor', uniqueContributors.length)} + {uniqueContributors.length} {pluralize('contributor', uniqueContributors.length)} {uniqueContributors.map(contributor => ( - + ))} @@ -36,10 +32,7 @@ function Contributors ({ contributors }) { {latestContributor.latestCommit ? ( - Last edited by{' '} - - {latestContributor.login} - {' '} + Last edited by {latestContributor.login}{' '} on{' '} {format(new Date(latestContributor.latestCommit.date), 'MMMM d, y')} diff --git a/theme/src/components/dark-button.js b/theme/src/components/dark-button.js index 1c4b27dbb4d..d2e965095c2 100644 --- a/theme/src/components/dark-button.js +++ b/theme/src/components/dark-button.js @@ -1,4 +1,4 @@ -import { ButtonOutline, themeGet } from '@primer/components' +import {ButtonOutline, themeGet} from '@primer/components' import styled from 'styled-components' const DarkButton = styled(ButtonOutline)` diff --git a/theme/src/components/dark-text-input.js b/theme/src/components/dark-text-input.js index d593b48a862..1753e5c9e6a 100644 --- a/theme/src/components/dark-text-input.js +++ b/theme/src/components/dark-text-input.js @@ -1,4 +1,4 @@ -import { TextInput, themeGet } from '@primer/components' +import {TextInput, themeGet} from '@primer/components' import styled from 'styled-components' const DarkTextInput = styled(TextInput)` diff --git a/theme/src/components/description-list.js b/theme/src/components/description-list.js index cf907c9a8ed..5d4e51bd23a 100644 --- a/theme/src/components/description-list.js +++ b/theme/src/components/description-list.js @@ -1,5 +1,5 @@ import styled from 'styled-components' -import themeGet from '@styled-system/theme-get' +import {themeGet} from '@styled-system/theme-get' const DescriptionList = styled.dl` padding: 0; diff --git a/theme/src/components/details.js b/theme/src/components/details.js index 3c3ad76bf47..7ab49e26016 100644 --- a/theme/src/components/details.js +++ b/theme/src/components/details.js @@ -25,14 +25,14 @@ const DetailsReset = styled.details` } ` -function getRenderer (children) { +function getRenderer(children) { return typeof children === 'function' ? children : () => children } -function Details ({ children, overlay, render = getRenderer(children), ...rest }) { +function Details({children, overlay, render = getRenderer(children), ...rest}) { const [open, setOpen] = React.useState(Boolean(rest.open)) - function toggle (event) { + function toggle(event) { if (event) { event.preventDefault() } @@ -43,21 +43,21 @@ function Details ({ children, overlay, render = getRenderer(children), ...rest } } } - function openMenu () { + function openMenu() { if (!open) { setOpen(true) document.addEventListener('click', closeMenu) } } - function closeMenu () { + function closeMenu() { setOpen(false) document.removeEventListener('click', closeMenu) } return ( - {render({ open, toggle })} + {render({open, toggle})} ) } diff --git a/theme/src/components/do-dont.js b/theme/src/components/do-dont.js index 0dd4b1bd37d..18b6a3dcb29 100644 --- a/theme/src/components/do-dont.js +++ b/theme/src/components/do-dont.js @@ -1,15 +1,11 @@ -import { Flex, Grid, Text, StyledOcticon } from '@primer/components' -import { CheckIcon, XIcon } from '@primer/octicons-react' +import {Flex, Grid, Text, StyledOcticon} from '@primer/components' +import {CheckIcon, XIcon} from '@primer/octicons-react' import React from 'react' import Caption from './caption' -export function DoDontContainer ({ stacked, children }) { +export function DoDontContainer({stacked, children}) { return ( - + {children} ) @@ -19,19 +15,19 @@ DoDontContainer.defaultProps = { stacked: false, } -export function Do (props) { +export function Do(props) { return } -export function Dont (props) { +export function Dont(props) { return } -function DoDontBase ({ src, alt, children, text, icon: Icon, iconBg }) { +function DoDontBase({src, alt, children, text, icon: Icon, iconBg}) { return ( - + diff --git a/theme/src/components/drawer.js b/theme/src/components/drawer.js index 8b023c95e5f..179549da771 100644 --- a/theme/src/components/drawer.js +++ b/theme/src/components/drawer.js @@ -1,9 +1,9 @@ -import { Fixed } from '@primer/components' -import { AnimatePresence, motion } from 'framer-motion' +import {Fixed} from '@primer/components' +import {AnimatePresence, motion} from 'framer-motion' import React from 'react' -import { FocusOn } from 'react-focus-on' +import {FocusOn} from 'react-focus-on' -function Drawer ({ isOpen, onDismiss, children }) { +function Drawer({isOpen, onDismiss, children}) { return ( {isOpen ? ( @@ -19,10 +19,10 @@ function Drawer ({ isOpen, onDismiss, children }) { {children} diff --git a/theme/src/components/frame.js b/theme/src/components/frame.js index 6537f441880..f0f38b7186f 100644 --- a/theme/src/components/frame.js +++ b/theme/src/components/frame.js @@ -1,14 +1,14 @@ import React from 'react' -import FrameComponent, { FrameContextConsumer } from 'react-frame-component' -import { StyleSheetManager } from 'styled-components' +import FrameComponent, {FrameContextConsumer} from 'react-frame-component' +import {StyleSheetManager} from 'styled-components' import Measure from 'react-measure' -function Frame ({ children }) { +function Frame({children}) { const [height, setHeight] = React.useState('auto') return ( - + - {({ document }) => { + {({document}) => { // By default, styled-components injects styles in the head of the page. // However, styles from the page's head don't apply inside iframes. // We're using StyleSheetManager to make styled-components inject styles @@ -22,7 +22,7 @@ function Frame ({ children }) { bounds={true} onResize={rect => setHeight(rect.bounds.height)} > - {({ measureRef }) =>
{children}
} + {({measureRef}) =>
{children}
} ) diff --git a/theme/src/components/head.js b/theme/src/components/head.js index 8c9579cd8e9..485e4d388ee 100644 --- a/theme/src/components/head.js +++ b/theme/src/components/head.js @@ -1,12 +1,10 @@ import React from 'react' -import Helmet from 'react-helmet' +import {Helmet} from 'react-helmet' import useSiteMetdata from '../use-site-metadata' -function Head (props) { +function Head(props) { const siteMetadata = useSiteMetdata() - const title = props.title - ? `${props.title} | ${siteMetadata.title}` - : siteMetadata.title + const title = props.title ? `${props.title} | ${siteMetadata.title}` : siteMetadata.title const description = props.description || siteMetadata.description const lang = props.lang || siteMetadata.lang diff --git a/theme/src/components/header.js b/theme/src/components/header.js index dcfc09bf405..bfe8de3d9b1 100644 --- a/theme/src/components/header.js +++ b/theme/src/components/header.js @@ -1,17 +1,14 @@ -import { Box, Flex, Link, Sticky } from '@primer/components' -import { - SearchIcon, - ThreeBarsIcon, -} from '@primer/octicons-react' -import { Link as GatsbyLink } from 'gatsby' +import {Box, Flex, Link, Sticky} from '@primer/components' +import {SearchIcon, ThreeBarsIcon} from '@primer/octicons-react' +import {Link as GatsbyLink} from 'gatsby' import React from 'react' -import styled, { ThemeContext } from 'styled-components' +import styled, {ThemeContext} from 'styled-components' import headerNavItems from '../header-nav.yml' import useSiteMetadata from '../use-site-metadata' import DarkButton from './dark-button' import MobileSearch from './mobile-search' -import NavDrawer, { useNavDrawerState } from './nav-drawer' -import NavDropdown, { NavDropdownItem } from './nav-dropdown' +import NavDrawer, {useNavDrawerState} from './nav-drawer' +import NavDropdown, {NavDropdownItem} from './nav-dropdown' import Search from './search' import NpmLogo from './npm-logo' @@ -22,16 +19,14 @@ const NpmHeaderBar = styled(Box)` background-image: linear-gradient(139deg, #fb8817, #ff4b01, #c12127, #e02aff); ` -function Header ({ location, isSearchEnabled = true }) { +function Header({location, isSearchEnabled = true}) { const theme = React.useContext(ThemeContext) - const [isNavDrawerOpen, setIsNavDrawerOpen] = useNavDrawerState( - theme.breakpoints[2] - ) + const [isNavDrawerOpen, setIsNavDrawerOpen] = useNavDrawerState(theme.breakpoints[2]) const [isMobileSearchOpen, setIsMobileSearchOpen] = React.useState(false) const siteMetadata = useSiteMetadata() - const logoStyle = { color: '#cb0000', marginRight: '16px' } - const titleStyle = { color: '#dddddd', fontWeight: '600', display: 'flex', alignItems: 'center' } + const logoStyle = {color: '#cb0000', marginRight: '16px'} + const titleStyle = {color: '#dddddd', fontWeight: '600', display: 'flex', alignItems: 'center'} return ( @@ -69,10 +64,7 @@ function Header ({ location, isSearchEnabled = true }) { > - setIsMobileSearchOpen(false)} - /> + setIsMobileSearchOpen(false)} /> ) : null} - setIsNavDrawerOpen(false)} - /> + setIsNavDrawerOpen(false)} />
@@ -95,7 +83,7 @@ function Header ({ location, isSearchEnabled = true }) { ) } -function HeaderNavItems ({ items }) { +function HeaderNavItems({items}) { return ( {items.map((item, index) => { @@ -103,7 +91,7 @@ function HeaderNavItems ({ items }) { return ( - {item.children.map((child) => ( + {item.children.map(child => ( {child.title} @@ -114,13 +102,7 @@ function HeaderNavItems ({ items }) { } return ( - + {item.title} ) diff --git a/theme/src/components/heading.js b/theme/src/components/heading.js index 70f81c431f2..672be045000 100644 --- a/theme/src/components/heading.js +++ b/theme/src/components/heading.js @@ -1,11 +1,11 @@ -import { Heading, Link } from '@primer/components' -import { LinkIcon } from '@primer/octicons-react' -import themeGet from '@styled-system/theme-get' +import {Heading, Link} from '@primer/components' +import {LinkIcon} from '@primer/octicons-react' +import {themeGet} from '@styled-system/theme-get' import GithubSlugger from 'github-slugger' import React from 'react' import textContent from 'react-addons-text-content' import styled from 'styled-components' -import { HEADER_HEIGHT } from './header' +import {HEADER_HEIGHT} from './header' const StyledHeading = styled(Heading)` margin-top: ${themeGet('space.4')}; @@ -22,20 +22,14 @@ const StyledHeading = styled(Heading)` } ` -function MarkdownHeading ({ children, ...props }) { +function MarkdownHeading({children, ...props}) { const slugger = new GithubSlugger() const text = children ? textContent(children) : '' const id = text ? slugger.slug(text) : '' return ( - + {children} @@ -43,38 +37,38 @@ function MarkdownHeading ({ children, ...props }) { ) } -const StyledH1 = styled(StyledHeading).attrs({ as: 'h1' })` +const StyledH1 = styled(StyledHeading).attrs({as: 'h1'})` padding-bottom: ${themeGet('space.1')}; font-size: ${themeGet('fontSizes.5')}; border-bottom: 1px solid ${themeGet('colors.gray.2')}; ` -const StyledH2 = styled(StyledHeading).attrs({ as: 'h2' })` +const StyledH2 = styled(StyledHeading).attrs({as: 'h2'})` padding-bottom: ${themeGet('space.1')}; font-size: ${themeGet('fontSizes.4')}; border-bottom: 1px solid ${themeGet('colors.gray.2')}; ` -const StyledH3 = styled(StyledHeading).attrs({ as: 'h3' })` +const StyledH3 = styled(StyledHeading).attrs({as: 'h3'})` font-size: ${themeGet('fontSizes.3')}; ` -const StyledH4 = styled(StyledHeading).attrs({ as: 'h4' })` +const StyledH4 = styled(StyledHeading).attrs({as: 'h4'})` font-size: ${themeGet('fontSizes.2')}; ` -const StyledH5 = styled(StyledHeading).attrs({ as: 'h5' })` +const StyledH5 = styled(StyledHeading).attrs({as: 'h5'})` font-size: ${themeGet('fontSizes.1')}; ` -const StyledH6 = styled(StyledHeading).attrs({ as: 'h6' })` +const StyledH6 = styled(StyledHeading).attrs({as: 'h6'})` font-size: ${themeGet('fontSizes.1')}; color: ${themeGet('colors.gray.5')}; ` -export const H1 = (props) => -export const H2 = (props) => -export const H3 = (props) => -export const H4 = (props) => -export const H5 = (props) => -export const H6 = (props) => +export const H1 = props => +export const H2 = props => +export const H3 = props => +export const H4 = props => +export const H5 = props => +export const H6 = props => diff --git a/theme/src/components/hero-layout.js b/theme/src/components/hero-layout.js index 258a6ae5226..a307cfa90ef 100644 --- a/theme/src/components/hero-layout.js +++ b/theme/src/components/hero-layout.js @@ -1,4 +1,4 @@ -import { Box, Flex } from '@primer/components' +import {Box, Flex} from '@primer/components' import React from 'react' import Container from './container' import PageFooter from './page-footer' @@ -7,8 +7,8 @@ import Header from './header' import Hero from './hero' import Sidebar from './sidebar' -function HeroLayout ({ children, pageContext, location }) { - const { additionalContributors = [] } = pageContext.frontmatter +function HeroLayout({children, pageContext, location}) { + const {additionalContributors = []} = pageContext.frontmatter return ( @@ -17,10 +17,7 @@ function HeroLayout ({ children, pageContext, location }) { @@ -31,9 +28,7 @@ function HeroLayout ({ children, pageContext, location }) { ({ login })) - )} + contributors={pageContext.contributors.concat(additionalContributors.map(login => ({login})))} /> diff --git a/theme/src/components/hero.js b/theme/src/components/hero.js index 6b55721e19d..f676b0348c0 100644 --- a/theme/src/components/hero.js +++ b/theme/src/components/hero.js @@ -1,10 +1,10 @@ -import { Box, Heading, Text } from '@primer/components' +import {Box, Heading, Text} from '@primer/components' import React from 'react' import useSiteMetadata from '../use-site-metadata' import Container from './container' -function Hero () { - const { title, description } = useSiteMetadata() +function Hero() { + const {title, description} = useSiteMetadata() return ( diff --git a/theme/src/components/horizontal-rule.js b/theme/src/components/horizontal-rule.js index b8e10ed6fff..4e20a0a4c71 100644 --- a/theme/src/components/horizontal-rule.js +++ b/theme/src/components/horizontal-rule.js @@ -1,5 +1,5 @@ import styled from 'styled-components' -import themeGet from '@styled-system/theme-get' +import {themeGet} from '@styled-system/theme-get' const HorizontalRule = styled.hr` height: ${themeGet('space.1')}; diff --git a/theme/src/components/image.js b/theme/src/components/image.js index e20b8b722fe..acd9ecbe6c1 100644 --- a/theme/src/components/image.js +++ b/theme/src/components/image.js @@ -1,4 +1,4 @@ -import themeGet from '@styled-system/theme-get' +import {themeGet} from '@styled-system/theme-get' import styled from 'styled-components' const Image = styled.img` diff --git a/theme/src/components/index.js b/theme/src/components/index.js index 82d51d031ee..04df9f8c767 100644 --- a/theme/src/components/index.js +++ b/theme/src/components/index.js @@ -1,11 +1,11 @@ import React from 'react' // eslint-disable-next-line import/no-unresolved -import { Location } from '@reach/router' -import { Box, Link } from '@primer/components' -import { Link as GatsbyLink } from 'gatsby' +import {Location} from '@reach/router' +import {Box, Link} from '@primer/components' +import {Link as GatsbyLink} from 'gatsby' import NavHierarchy from '../nav-hierarchy' -function showHierarchy (items, props, depth = 1) { +function showHierarchy(items, props, depth = 1) { let hierarchy if (props.depth && depth > props.depth) { @@ -16,25 +16,27 @@ function showHierarchy (items, props, depth = 1) { {items.map(item => ( - {item.title} + + {item.title} + {item.description != null ? ( <> - - {item.description} - + {item.description} ) : null} - {(hierarchy = NavHierarchy.getHierarchy(item, props)) != null ? showHierarchy(hierarchy, props, depth + 1) : null} + {(hierarchy = NavHierarchy.getHierarchy(item, props)) != null + ? showHierarchy(hierarchy, props, depth + 1) + : null} ))} ) } -function Index (props) { +function Index(props) { return ( - {({ location }) => { + {({location}) => { const path = NavHierarchy.getLocation(location.pathname) let root = props.root ? props.root : path root = root.replace(/\/+$/g, '') diff --git a/theme/src/components/inline-code.js b/theme/src/components/inline-code.js index 15d68fdc100..52f35e165b2 100644 --- a/theme/src/components/inline-code.js +++ b/theme/src/components/inline-code.js @@ -1,5 +1,5 @@ import styled from 'styled-components' -import themeGet from '@styled-system/theme-get' +import {themeGet} from '@styled-system/theme-get' const InlineCode = styled.code` padding: 0.2em 0.4em; diff --git a/theme/src/components/layout.js b/theme/src/components/layout.js index 6268605c7bf..5ccbaba12a7 100644 --- a/theme/src/components/layout.js +++ b/theme/src/components/layout.js @@ -1,19 +1,9 @@ -import { - BorderBox, - Box, - Details, - Flex, - Grid, - Heading, - Position, - StyledOcticon, - Text, -} from '@primer/components' -import { ChevronDownIcon, ChevronRightIcon } from '@primer/octicons-react' +import {BorderBox, Box, Details, Flex, Grid, Heading, Position, StyledOcticon, Text} from '@primer/components' +import {ChevronDownIcon, ChevronRightIcon} from '@primer/octicons-react' import React from 'react' -import { MDXProvider } from '@mdx-js/react' +import {MDXProvider} from '@mdx-js/react' import Head from './head' -import Header, { HEADER_HEIGHT } from './header' +import Header, {HEADER_HEIGHT} from './header' import Index from './index' import Note from './note' import PageFooter from './page-footer' @@ -27,36 +17,28 @@ import TableOfContents from './table-of-contents' import VariantSelect from './variant-select' import NavHierarchy from '../nav-hierarchy' -function Layout ({ children, pageContext, location }) { - const { - title, - description, - status, - source, - additionalContributors = [], - } = pageContext.frontmatter +function Layout({children, pageContext, location}) { + const {title, description, status, source, additionalContributors = []} = pageContext.frontmatter const variantRoot = NavHierarchy.getVariantRoot(location.pathname) return ( - - +
- + @@ -64,25 +46,16 @@ function Layout ({ children, pageContext, location }) { id="skip-nav" maxWidth="100%" gridTemplateColumns={['100%', null, 'minmax(0, 65ch) 220px']} - gridTemplateAreas={[ - '"heading" "content"', - null, - '"heading table-of-contents" "content table-of-contents"', - ]} + gridTemplateAreas={['"heading" "content"', null, '"heading table-of-contents" "content table-of-contents"']} gridColumnGap={[null, null, 6, 7]} gridRowGap={3} mx="auto" p={[5, 6, null, 7]} - css={{ alignItems: 'start', alignSelf: 'start' }} + css={{alignItems: 'start', alignSelf: 'start'}} role="region" > - - + + {title} @@ -91,15 +64,21 @@ function Layout ({ children, pageContext, location }) { {variantRoot != null ? ( - - + + ) : null} {pageContext.tableOfContents.items ? ( - + Table of contents - + ) : null} - + {status || source ? ( {status ? : null} @@ -125,7 +104,7 @@ function Layout ({ children, pageContext, location }) { {pageContext.tableOfContents.items ? (
- {({ open }) => ( + {({open}) => ( <> {open ? ( @@ -136,9 +115,7 @@ function Layout ({ children, pageContext, location }) { Table of contents - + )} @@ -149,9 +126,7 @@ function Layout ({ children, pageContext, location }) { ({ login })) - )} + contributors={pageContext.contributors.concat(additionalContributors.map(login => ({login})))} /> diff --git a/theme/src/components/list.js b/theme/src/components/list.js index 81e806babcc..56e1488362e 100644 --- a/theme/src/components/list.js +++ b/theme/src/components/list.js @@ -1,5 +1,5 @@ import styled from 'styled-components' -import themeGet from '@styled-system/theme-get' +import {themeGet} from '@styled-system/theme-get' const List = styled.ul` padding-left: 2em; diff --git a/theme/src/components/live-code.js b/theme/src/components/live-code.js index e87e2ebf9b3..38a77fadb14 100644 --- a/theme/src/components/live-code.js +++ b/theme/src/components/live-code.js @@ -1,10 +1,10 @@ -import { Absolute, BorderBox, Relative, Text } from '@primer/components' +import {Absolute, BorderBox, Relative, Text} from '@primer/components' import htmlReactParser from 'html-react-parser' import githubTheme from 'prism-react-renderer/themes/github' -import React, { useState } from 'react' +import React, {useState} from 'react' import reactElementToJsxString from 'react-element-to-jsx-string' -import { LiveEditor, LiveError, LivePreview, LiveProvider } from 'react-live' -import { ThemeContext } from 'styled-components' +import {LiveEditor, LiveError, LivePreview, LiveProvider} from 'react-live' +import {ThemeContext} from 'styled-components' import scope from '../live-code-scope' import ClipboardCopy from './clipboard-copy' import LivePreviewWrapper from './live-preview-wrapper' @@ -14,7 +14,7 @@ const languageTransformers = { jsx: jsx => wrapWithFragment(jsx), } -function htmlToJsx (html) { +function htmlToJsx(html) { try { const reactElement = htmlReactParser(removeNewlines(html)) // The output of htmlReactParser could be a single React element @@ -26,30 +26,22 @@ function htmlToJsx (html) { } } -function removeNewlines (string) { +function removeNewlines(string) { return string.replace(/(\r\n|\n|\r)/gm, '') } -function wrapWithFragment (jsx) { +function wrapWithFragment(jsx) { return `${jsx}` } -function LiveCode ({ code, language, noinline }) { +function LiveCode({code, language, noinline}) { const theme = React.useContext(ThemeContext) const [liveCode, setLiveCode] = useState(code) - const handleChange = (updatedLiveCode) => setLiveCode(updatedLiveCode) + const handleChange = updatedLiveCode => setLiveCode(updatedLiveCode) return ( - - + + @@ -70,15 +62,7 @@ function LiveCode ({ code, language, noinline }) { - + ) diff --git a/theme/src/components/live-preview-wrapper.js b/theme/src/components/live-preview-wrapper.js index bb68a9fb2b5..070c19c053c 100644 --- a/theme/src/components/live-preview-wrapper.js +++ b/theme/src/components/live-preview-wrapper.js @@ -1,10 +1,10 @@ -import { BaseStyles, Box } from '@primer/components' +import {BaseStyles, Box} from '@primer/components' import Frame from './frame' import React from 'react' // Users can shadow this file to wrap live previews. // This is useful for applying global styles. -function LivePreviewWrapper ({ children }) { +function LivePreviewWrapper({children}) { return ( diff --git a/theme/src/components/mobile-search.js b/theme/src/components/mobile-search.js index 1d3ac1539f8..01daea96447 100644 --- a/theme/src/components/mobile-search.js +++ b/theme/src/components/mobile-search.js @@ -1,38 +1,38 @@ -import { Absolute, Fixed, Flex } from '@primer/components' -import { XIcon } from '@primer/octicons-react' +import {Absolute, Fixed, Flex} from '@primer/components' +import {XIcon} from '@primer/octicons-react' import Downshift from 'downshift' -import { AnimatePresence, motion } from 'framer-motion' -import { navigate } from 'gatsby' +import {AnimatePresence, motion} from 'framer-motion' +import {navigate} from 'gatsby' import React from 'react' -import { FocusOn } from 'react-focus-on' +import {FocusOn} from 'react-focus-on' import useSearch from '../use-search' import DarkButton from './dark-button' import DarkTextInput from './dark-text-input' import SearchResults from './search-results' import useSiteMetadata from '../use-site-metadata' -function stateReducer (state, changes) { +function stateReducer(state, changes) { switch (changes.type) { case Downshift.stateChangeTypes.changeInput: if (!changes.inputValue) { // Close the menu if the input is empty. - return { ...changes, isOpen: false } + return {...changes, isOpen: false} } return changes case Downshift.stateChangeTypes.blurInput: // Don't let a blur event change the state of `inputValue` or `isOpen`. - return { ...changes, inputValue: state.inputValue, isOpen: state.isOpen } + return {...changes, inputValue: state.inputValue, isOpen: state.isOpen} default: return changes } } -function MobileSearch ({ isOpen, onDismiss }) { +function MobileSearch({isOpen, onDismiss}) { const [query, setQuery] = React.useState('') const results = useSearch(query) const siteMetadata = useSiteMetadata() - function handleDismiss () { + function handleDismiss() { setQuery('') onDismiss() } @@ -44,9 +44,9 @@ function MobileSearch ({ isOpen, onDismiss }) { setQuery(inputValue)} + onInputValueChange={inputValue => setQuery(inputValue)} selectedItem={null} - onSelect={(item) => { + onSelect={item => { if (item) { navigate(item.path) handleDismiss() } }} - itemToString={(item) => (item ? item.title : '')} + itemToString={item => (item ? item.title : '')} stateReducer={stateReducer} > - {({ - getInputProps, - getItemProps, - getMenuProps, - getRootProps, - isOpen: isMenuOpen, - highlightedIndex, - }) => ( + {({getInputProps, getItemProps, getMenuProps, getRootProps, isOpen: isMenuOpen, highlightedIndex}) => ( - + diff --git a/theme/src/components/nav-drawer.js b/theme/src/components/nav-drawer.js index 7cceaa54b25..592e63ea218 100644 --- a/theme/src/components/nav-drawer.js +++ b/theme/src/components/nav-drawer.js @@ -1,6 +1,6 @@ -import { BorderBox, Flex, Link, Text } from '@primer/components' -import { ChevronDownIcon, ChevronUpIcon, XIcon } from '@primer/octicons-react' -import { Link as GatsbyLink } from 'gatsby' +import {BorderBox, Flex, Link, Text} from '@primer/components' +import {ChevronDownIcon, ChevronUpIcon, XIcon} from '@primer/octicons-react' +import {Link as GatsbyLink} from 'gatsby' import debounce from 'lodash.debounce' import React from 'react' import navItems from '../nav.yml' @@ -11,7 +11,7 @@ import Details from './details' import Drawer from './drawer' import NavItems from './nav-items' -export function useNavDrawerState (breakpoint) { +export function useNavDrawerState(breakpoint) { // Handle string values from themes with units at the end if (typeof breakpoint === 'string') { breakpoint = parseInt(breakpoint, 10) @@ -24,9 +24,7 @@ export function useNavDrawerState (breakpoint) { } }, [setOpen]) - const debouncedOnResize = React.useCallback(debounce(onResize, 250), [ - onResize, - ]) + const debouncedOnResize = React.useCallback(debounce(onResize, 250), [onResize]) React.useEffect(() => { if (isOpen) { @@ -42,7 +40,7 @@ export function useNavDrawerState (breakpoint) { return [isOpen, setOpen] } -function NavDrawer ({ location, isOpen, onDismiss }) { +function NavDrawer({location, isOpen, onDismiss}) { const siteMetadata = useSiteMetadata() return ( @@ -50,30 +48,12 @@ function NavDrawer ({ location, isOpen, onDismiss }) { flexDirection="column" height="100%" bg="gray.0" - style={{ overflow: 'auto', WebkitOverflowScrolling: 'touch' }} + style={{overflow: 'auto', WebkitOverflowScrolling: 'touch'}} > - - - + + + {siteMetadata.title} @@ -88,12 +68,7 @@ function NavDrawer ({ location, isOpen, onDismiss }) { ) : null} {headerNavItems.length > 0 ? ( - + ) : null} @@ -102,7 +77,7 @@ function NavDrawer ({ location, isOpen, onDismiss }) { ) } -function HeaderNavItems ({ items }) { +function HeaderNavItems({items}) { return items.map((item, index) => { return ( {item.children ? (
- {({ open, toggle }) => ( + {({open, toggle}) => ( <> - + {item.title} {open ? : } - {item.children.map((child) => ( - + {item.children.map(child => ( + {child.title} ))} diff --git a/theme/src/components/nav-dropdown.js b/theme/src/components/nav-dropdown.js index aa210dce5a0..c8299fd55f8 100644 --- a/theme/src/components/nav-dropdown.js +++ b/theme/src/components/nav-dropdown.js @@ -1,26 +1,20 @@ -import { Absolute, BorderBox, StyledOcticon, Text, themeGet } from '@primer/components' -import { ChevronDownIcon } from '@primer/octicons-react' +import {Absolute, BorderBox, StyledOcticon, Text, themeGet} from '@primer/components' +import {ChevronDownIcon} from '@primer/octicons-react' import React from 'react' import styled from 'styled-components' import Details from './details' -function NavDropdown ({ title, children }) { +function NavDropdown({title, children}) { return (
- {({ toggle }) => ( + {({toggle}) => ( <> - + {title} - + {children} diff --git a/theme/src/components/nav-items.js b/theme/src/components/nav-items.js index 4a2505c2171..e134837df15 100644 --- a/theme/src/components/nav-items.js +++ b/theme/src/components/nav-items.js @@ -1,6 +1,6 @@ -import { BorderBox, Box, Flex, StyledOcticon, Link, themeGet } from '@primer/components' -import { LinkExternalIcon } from '@primer/octicons-react' -import { Link as GatsbyLink } from 'gatsby' +import {BorderBox, Box, Flex, StyledOcticon, Link, themeGet} from '@primer/components' +import {LinkExternalIcon} from '@primer/octicons-react' +import {Link as GatsbyLink} from 'gatsby' import preval from 'preval.macro' import React from 'react' import styled from 'styled-components' @@ -18,18 +18,18 @@ const repositoryUrl = preval` } ` -const getActiveProps = (className) => (props) => { +const getActiveProps = className => props => { const location = NavHierarchy.getLocation(props.location.pathname) const href = NavHierarchy.getLocation(props.href) if (NavHierarchy.isActiveUrl(location, href)) { - return { className: `${className} active` } + return {className: `${className} active`} } - return { className: `${className}` } + return {className: `${className}`} } -const ActiveLink = ({ className, children, ...props }) => ( +const ActiveLink = ({className, children, ...props}) => ( {children} @@ -87,28 +87,24 @@ const Description = styled(Box)` } ` -function topLevelItems (items, path) { +function topLevelItems(items, path) { if (items == null) { return null } return ( <> - {items.map((item) => { - const children = NavHierarchy.isActiveUrl(path, item.url) ? NavHierarchy.getHierarchy(item, { path: path, hideVariants: true }) : null + {items.map(item => { + const children = NavHierarchy.isActiveUrl(path, item.url) + ? NavHierarchy.getHierarchy(item, {path, hideVariants: true}) + : null return ( - + - {item.title} + + {item.title} + {secondLevelItems(children, path)} @@ -118,15 +114,17 @@ function topLevelItems (items, path) { ) } -function secondLevelItems (items, path) { +function secondLevelItems(items, path) { if (items == null) { return null } return ( - {items.map((item) => { - const children = NavHierarchy.isActiveUrl(path, item.url) ? NavHierarchy.getHierarchy(item, { path: path, hideVariants: true }) : null + {items.map(item => { + const children = NavHierarchy.isActiveUrl(path, item.url) + ? NavHierarchy.getHierarchy(item, {path, hideVariants: true}) + : null return ( @@ -145,14 +143,14 @@ function secondLevelItems (items, path) { ) } -function thirdLevelItems (items) { +function thirdLevelItems(items) { if (items == null) { return null } return ( - {items.map((item) => ( + {items.map(item => ( {item.title} @@ -163,7 +161,7 @@ function thirdLevelItems (items) { ) } -function githubLink () { +function githubLink() { if (!repositoryUrl) { return null } @@ -172,7 +170,7 @@ function githubLink () { - Edit on GitHub + Edit on GitHub @@ -180,9 +178,9 @@ function githubLink () { ) } -function NavItems (props) { +function NavItems(props) { const path = NavHierarchy.getLocation(props.location.pathname) - const items = NavHierarchy.getHierarchy(null, { path: path, hideVariants: true }) + const items = NavHierarchy.getHierarchy(null, {path, hideVariants: true}) return ( <> diff --git a/theme/src/components/note.js b/theme/src/components/note.js index 6419268989a..f4a9de85be4 100644 --- a/theme/src/components/note.js +++ b/theme/src/components/note.js @@ -1,22 +1,14 @@ import React from 'react' -import { BorderBox } from '@primer/components' +import {BorderBox} from '@primer/components' -function Note ({ children }) { +function Note({children}) { return ( - - {React.Children.toArray(children).map((child, index, list) => ( + + {React.Children.toArray(children).map((child, index, list) => React.cloneElement(child, { - style: index === list.length - 1 ? { marginBottom: '0' } : null, - }) - ))} + style: index === list.length - 1 ? {marginBottom: '0'} : null, + }), + )} ) } diff --git a/theme/src/components/npm-logo.js b/theme/src/components/npm-logo.js index b2ab3e19108..759a2d04f97 100644 --- a/theme/src/components/npm-logo.js +++ b/theme/src/components/npm-logo.js @@ -1,14 +1,21 @@ import React from 'react' export default class NpmLogo extends React.Component { - render () { + render() { const bgcolor = this.props.bg || '#cb0000' const fgcolor = this.props.fg || '#ffffff' return ( - {children}) +function PromptReply({children}) { + return {children} } export default PromptReply diff --git a/theme/src/components/prompt.js b/theme/src/components/prompt.js index 4b24f0167d2..1ed597aa0e7 100644 --- a/theme/src/components/prompt.js +++ b/theme/src/components/prompt.js @@ -1,7 +1,7 @@ import React from 'react' -import { BorderBox, Text } from '@primer/components' +import {BorderBox, Text} from '@primer/components' -function Prompt ({ children }) { +function Prompt({children}) { return ( - {children} + + {children} + ) } diff --git a/theme/src/components/screenshot.js b/theme/src/components/screenshot.js index cb126e91bfa..60a6383fcf0 100644 --- a/theme/src/components/screenshot.js +++ b/theme/src/components/screenshot.js @@ -1,7 +1,7 @@ import React from 'react' -import { withPrefix } from 'gatsby' +import {withPrefix} from 'gatsby' -function Screenshot (props) { +function Screenshot(props) { if (!props.src) { throw new Error('src is required') } @@ -11,7 +11,13 @@ function Screenshot (props) { } return ( -
{props.alt}
+
+ {props.alt} +
) } diff --git a/theme/src/components/search-results.js b/theme/src/components/search-results.js index d81ac8e8a3b..d94fff32509 100644 --- a/theme/src/components/search-results.js +++ b/theme/src/components/search-results.js @@ -1,9 +1,9 @@ -import { Flex, Text } from '@primer/components' +import {Flex, Text} from '@primer/components' import React from 'react' import useSiteMetadata from '../use-site-metadata' import NavHierarchy from '../nav-hierarchy' -function SearchResults ({ results, getItemProps, highlightedIndex }) { +function SearchResults({results, getItemProps, highlightedIndex}) { const siteMetadata = useSiteMetadata() if (results.length === 0) { @@ -25,13 +25,10 @@ function SearchResults ({ results, getItemProps, highlightedIndex }) { py: 2, color: highlightedIndex === index ? 'white' : 'gray.8', bg: highlightedIndex === index ? 'blue.5' : 'transparent', - style: { cursor: 'pointer' }, + style: {cursor: 'pointer'}, })} > - + {getBreadcrumbs(siteMetadata.shortName, item.path).join(' / ')} {item.title} @@ -39,12 +36,12 @@ function SearchResults ({ results, getItemProps, highlightedIndex }) { )) } -function getBreadcrumbs (siteTitle, path) { +function getBreadcrumbs(siteTitle, path) { const hierarchy = NavHierarchy.getItemHierarchy(path) if (hierarchy) { hierarchy.pop() - return hierarchy.map(item => item.shortName ? item.shortName : item.title) + return hierarchy.map(item => (item.shortName ? item.shortName : item.title)) } else { return [siteTitle] } diff --git a/theme/src/components/search.js b/theme/src/components/search.js index ea3eb19918a..ab55fa165fe 100644 --- a/theme/src/components/search.js +++ b/theme/src/components/search.js @@ -1,18 +1,18 @@ -import { BorderBox, Position } from '@primer/components' +import {BorderBox, Position} from '@primer/components' import Downshift from 'downshift' -import { navigate } from 'gatsby' +import {navigate} from 'gatsby' import React from 'react' import useSearch from '../use-search' import useSiteMetadata from '../use-site-metadata' import DarkTextInput from './dark-text-input' import SearchResults from './search-results' -function stateReducer (state, changes) { +function stateReducer(state, changes) { switch (changes.type) { case Downshift.stateChangeTypes.changeInput: if (!changes.inputValue) { // Close the menu if the input is empty. - return { ...changes, isOpen: false } + return {...changes, isOpen: false} } return changes default: @@ -20,7 +20,7 @@ function stateReducer (state, changes) { } } -function Search () { +function Search() { const [query, setQuery] = React.useState('') const results = useSearch(query) const siteMetadata = useSiteMetadata() @@ -43,15 +43,8 @@ function Search () { itemToString={item => (item ? item.title : '')} stateReducer={stateReducer} > - {({ - getInputProps, - getItemProps, - getMenuProps, - getRootProps, - isOpen, - highlightedIndex, - }) => ( - + {({getInputProps, getItemProps, getMenuProps, getRootProps, isOpen, highlightedIndex}) => ( + - +
) : null} diff --git a/theme/src/components/sidebar.js b/theme/src/components/sidebar.js index 41b3cad66fc..d0762a8b371 100644 --- a/theme/src/components/sidebar.js +++ b/theme/src/components/sidebar.js @@ -1,10 +1,10 @@ -import { BorderBox, Flex, Position } from '@primer/components' +import {BorderBox, Flex, Position} from '@primer/components' import React from 'react' import navItems from '../nav.yml' -import { HEADER_HEIGHT } from './header' +import {HEADER_HEIGHT} from './header' import NavItems from './nav-items' -function Sidebar ({ location, editOnGitHub }) { +function Sidebar({location, editOnGitHub}) { return ( - + diff --git a/theme/src/components/skip-link.js b/theme/src/components/skip-link.js index 3bacee2bf8b..de7f4932c25 100644 --- a/theme/src/components/skip-link.js +++ b/theme/src/components/skip-link.js @@ -1,17 +1,10 @@ -import { Link } from '@primer/components' +import {Link} from '@primer/components' import styled from 'styled-components' import React from 'react' -function SkipLinkBase (props) { +function SkipLinkBase(props) { return ( - + Skip to content ) diff --git a/theme/src/components/source-link.js b/theme/src/components/source-link.js index 71d34cc890e..11b17db3463 100644 --- a/theme/src/components/source-link.js +++ b/theme/src/components/source-link.js @@ -1,8 +1,8 @@ -import { Link, StyledOcticon } from '@primer/components' -import { CodeIcon } from '@primer/octicons-react' +import {Link, StyledOcticon} from '@primer/components' +import {CodeIcon} from '@primer/octicons-react' import React from 'react' -function SourceLink ({ href }) { +function SourceLink({href}) { return ( diff --git a/theme/src/components/status-label.js b/theme/src/components/status-label.js index 6c8e19c8a1a..5162c4dfa62 100644 --- a/theme/src/components/status-label.js +++ b/theme/src/components/status-label.js @@ -1,5 +1,5 @@ -import { BorderBox, StyledOcticon, Flex, Text } from '@primer/components' -import { DotFillIcon } from '@primer/octicons-react' +import {BorderBox, StyledOcticon, Flex, Text} from '@primer/components' +import {DotFillIcon} from '@primer/octicons-react' import React from 'react' const STATUS_COLORS = { @@ -10,11 +10,11 @@ const STATUS_COLORS = { deprecated: 'red.6', } -function getStatusColor (status) { +function getStatusColor(status) { return STATUS_COLORS[status.toLowerCase()] || 'gray.5' } -function StatusLabel ({ status }) { +function StatusLabel({status}) { return ( diff --git a/theme/src/components/table-of-contents.js b/theme/src/components/table-of-contents.js index 5b898a04282..851d364fb5e 100644 --- a/theme/src/components/table-of-contents.js +++ b/theme/src/components/table-of-contents.js @@ -1,17 +1,23 @@ -import { Box, Link } from '@primer/components' +import {Box, Link} from '@primer/components' import React from 'react' -function TableOfContents ({ items, depth, labelId }) { +function TableOfContents({items, depth, labelId}) { return ( - + {items.map(item => ( - 0 ? 3 : 0}> + 0 ? 3 : 0}> {item.title} - {item.items ? ( - - ) : null} + {item.items ? : null} ))} diff --git a/theme/src/components/table.js b/theme/src/components/table.js index cfb9e76e7bf..6003a3c6abc 100644 --- a/theme/src/components/table.js +++ b/theme/src/components/table.js @@ -1,5 +1,5 @@ import styled from 'styled-components' -import themeGet from '@styled-system/theme-get' +import {themeGet} from '@styled-system/theme-get' const Table = styled.table` display: block; diff --git a/theme/src/components/variant-select.js b/theme/src/components/variant-select.js index 02b927b71a4..ff42ff89214 100644 --- a/theme/src/components/variant-select.js +++ b/theme/src/components/variant-select.js @@ -5,10 +5,10 @@ // then you'll get a selection for the different variants (v1.0, v2.0). import React from 'react' -import { ActionList, ActionMenu, ThemeProvider } from '@primer/react' +import {ActionList, ActionMenu, ThemeProvider} from '@primer/react' import NavHierarchy from '../nav-hierarchy' -function VariantSelect (props) { +function VariantSelect(props) { const [open, setOpen] = React.useState(false) const path = NavHierarchy.getPath(props.location.pathname) const vp = NavHierarchy.getVariantAndPage(props.root, path) @@ -25,40 +25,47 @@ function VariantSelect (props) { return null } - function anchorClickHandler (event, url) { + function anchorClickHandler(event, url) { event.preventDefault() - window.location.href = url + '?v=true' + window.location.href = `${url}?v=true` } - function onItemEnterKey (event, url) { + function onItemEnterKey(event, url) { if (event.key === 'Enter') { - window.location.href = url + '?v=true' + window.location.href = `${url}?v=true` } } - variantPages.forEach((match, index) => { + for (const [index, match] of variantPages.entries()) { let active = false if (match.page.url === path) { selectedItem = match active = true } - items.push( onItemEnterKey(e, match.page.url)} - onClick={e => anchorClickHandler(e, match.page.url)} - id={match.variant.shortName} - key={index} - active={active}> - {match.variant.title} - ) - }) + items.push( + onItemEnterKey(e, match.page.url)} + onClick={e => anchorClickHandler(e, match.page.url)} + id={match.variant.shortName} + key={index} + active={active} + > + {match.variant.title} + , + ) + } const ariaLabelMenuButton = open ? 'Version release' : selectedItem.variant.title return ( - + - {selectedItem.variant.title} + + {selectedItem.variant.title} + setOpen(false)}> {items} diff --git a/theme/src/components/wrap-page-element.js b/theme/src/components/wrap-page-element.js index edab361c435..7c177bc910f 100644 --- a/theme/src/components/wrap-page-element.js +++ b/theme/src/components/wrap-page-element.js @@ -1,8 +1,8 @@ -import { BaseStyles } from '@primer/components' +import {BaseStyles} from '@primer/components' import React from 'react' import SkipLink from './skip-link' -function wrapPageElement ({ element }) { +function wrapPageElement({element}) { return ( diff --git a/theme/src/components/wrap-root-element.js b/theme/src/components/wrap-root-element.js index 5bc25b2ab77..94ba8123952 100644 --- a/theme/src/components/wrap-root-element.js +++ b/theme/src/components/wrap-root-element.js @@ -1,11 +1,11 @@ -import { MDXProvider } from '@mdx-js/react' -import { Link, theme } from '@primer/components' +import {MDXProvider} from '@mdx-js/react' +import {Link, theme} from '@primer/components' import React from 'react' -import { ThemeProvider } from 'styled-components' +import {ThemeProvider} from 'styled-components' import Blockquote from './blockquote' import Code from './code' import DescriptionList from './description-list' -import { H1, H2, H3, H4, H5, H6 } from './heading' +import {H1, H2, H3, H4, H5, H6} from './heading' import HorizontalRule from './horizontal-rule' import Image from './image' import InlineCode from './inline-code' @@ -34,7 +34,7 @@ const components = { dl: DescriptionList, } -function wrapRootElement ({ element }) { +function wrapRootElement({element}) { return ( {element} diff --git a/theme/src/nav-hierarchy.js b/theme/src/nav-hierarchy.js index 3b789d8354e..31f7c0af387 100644 --- a/theme/src/nav-hierarchy.js +++ b/theme/src/nav-hierarchy.js @@ -1,8 +1,8 @@ import navItems from './nav.yml' -import { withPrefix } from 'gatsby' +import {withPrefix} from 'gatsby' export default { - getLocation (path) { + getLocation(path) { const pathPrefix = withPrefix('/') if (!pathPrefix || pathPrefix === '/') { @@ -13,7 +13,7 @@ export default { return path.replace(match, '/') }, - getPath (path) { + getPath(path) { while (path && path.endsWith('/')) { path = path.substring(0, path.length - 1) } @@ -21,11 +21,11 @@ export default { return path }, - getVariantRoot (path) { + getVariantRoot(path) { path = this.getPath(path) - return this.findItem((item) => { - if (item.variants && path.startsWith(item.url + '/')) { + return this.findItem(item => { + if (item.variants && path.startsWith(`${item.url}/`)) { return item.url } @@ -33,7 +33,7 @@ export default { }) }, - findItem (fn, items = navItems) { + findItem(fn, items = navItems) { for (let i = 0; i < items.length; i++) { const item = items[i] let result = fn(item) @@ -50,7 +50,7 @@ export default { return null }, - getItemHierarchy (path, items = navItems) { + getItemHierarchy(path, items = navItems) { if (!path) { return null } @@ -76,9 +76,9 @@ export default { return null }, - getItem (path, items = navItems) { + getItem(path, items = navItems) { if (!path) { - return { url: '/', children: items } + return {url: '/', children: items} } for (let i = 0; i < items.length; i++) { @@ -102,19 +102,19 @@ export default { return null }, - isPathForItem (path, item) { - return (this.getPath(item.url) === this.getPath(path)) + isPathForItem(path, item) { + return this.getPath(item.url) === this.getPath(path) }, - isChildItem (path, items = navItems) { + isChildItem(path, items = navItems) { if (!path) { return false } - return (this.findItem((item) => this.isPathForItem(path, item) ? item : null, items) != null) + return this.findItem(item => (this.isPathForItem(path, item) ? item : null), items) != null }, - getHierarchy (root, props = { }) { + getHierarchy(root, props = {}) { let children if (!root) { @@ -135,7 +135,7 @@ export default { return children }, - hideVariantsForItems (items, props) { + hideVariantsForItems(items, props) { if (!items) { return null } @@ -144,7 +144,7 @@ export default { for (const item of items) { if (item.variants) { - const cloned = { } + const cloned = {} Object.assign(cloned, item) const variant = this.getCurrentOrDefaultVariant(item, props.path) @@ -160,7 +160,7 @@ export default { return updated }, - getCurrentOrDefaultVariant (root, path) { + getCurrentOrDefaultVariant(root, path) { let variant = path ? this.getCurrentVariant(root, path) : null if (!variant) { @@ -170,7 +170,7 @@ export default { return variant }, - getCurrentVariant (root, path) { + getCurrentVariant(root, path) { for (const v of root.variants) { if (this.isActiveItem(path, v)) { return v @@ -180,7 +180,7 @@ export default { return null }, - getDefaultVariant (root) { + getDefaultVariant(root) { for (const v of root.variants) { if (v.default) { return v @@ -190,8 +190,8 @@ export default { return root.variants[0] }, - getVariantAndPage (root, path) { - if (!path.startsWith(root + '/')) { + getVariantAndPage(root, path) { + if (!path.startsWith(`${root}/`)) { return null } @@ -203,17 +203,17 @@ export default { return null } - return { variant: match[1], page: match[2] } + return {variant: match[1], page: match[2]} }, - getVariantsForPage (root, page) { + getVariantsForPage(root, page) { const pages = [] - const rootItem = this.findItem((item) => this.getPath(item.url) === this.getPath(root) ? item : null) + const rootItem = this.findItem(item => (this.getPath(item.url) === this.getPath(root) ? item : null)) if (rootItem && rootItem.variants) { - rootItem.variants.forEach((variant) => { + for (const variant of rootItem.variants) { if (!variant.children) { - return + continue } const vp = this.getVariantAndPage(root, variant.url) @@ -222,30 +222,32 @@ export default { if (vp.page === page) { variantPage = variant } else { - variantPage = this.findItem((item) => { + variantPage = this.findItem(item => { const vp = this.getVariantAndPage(root, item.url) - return (vp && vp.page === page) ? item : null + return vp && vp.page === page ? item : null }, variant.children) } if (!variantPage) { - return + continue } - pages.push({ variant: variant, page: variantPage }) - }) + pages.push({variant, page: variantPage}) + } } return pages }, - isActiveItem (currentPath, linkItem) { - return (this.isPathForItem(currentPath, linkItem) || - (linkItem.children && this.isChildItem(currentPath, linkItem.children)) || - (linkItem.variants && this.isChildItem(currentPath, linkItem.variants))) + isActiveItem(currentPath, linkItem) { + return ( + this.isPathForItem(currentPath, linkItem) || + (linkItem.children && this.isChildItem(currentPath, linkItem.children)) || + (linkItem.variants && this.isChildItem(currentPath, linkItem.variants)) + ) }, - isActiveUrl (currentPath, linkPath) { + isActiveUrl(currentPath, linkPath) { const linkItem = this.getItem(linkPath) return linkItem ? this.isActiveItem(currentPath, linkItem) : false }, diff --git a/theme/src/search.worker.js b/theme/src/search.worker.js index 54a8161e4ae..8e3002553b0 100644 --- a/theme/src/search.worker.js +++ b/theme/src/search.worker.js @@ -1,7 +1,6 @@ import Fuse from 'fuse.js' import debounce from 'lodash.debounce' - -(function searchWorker () { +;(function searchWorker() { let fuse = null // [MKT]: I landed on the debouce wait value of 50 based mostly on @@ -13,12 +12,16 @@ import debounce from 'lodash.debounce' // > Note: If `leading` and `trailing` options are `true`, `func` is invoked // > on the trailing edge of the timeout only if the debounced function is // > invoked more than once during the wait timeout. - const performSearch = debounce(function performSearch (query) { - const results = fuse.search(query).slice(0, 20) - postMessage({ results: results, query: query }) - }, 50, { leading: true, trailing: true }) + const performSearch = debounce( + function performSearch(query) { + const results = fuse.search(query).slice(0, 20) + postMessage({results, query}) + }, + 50, + {leading: true, trailing: true}, + ) - onmessage = function ({ data }) { + onmessage = function ({data}) { if (data.list) { fuse = new Fuse(data.list, { threshold: 0.2, diff --git a/theme/src/use-search.js b/theme/src/use-search.js index 75c6342216b..7561c6fe88a 100644 --- a/theme/src/use-search.js +++ b/theme/src/use-search.js @@ -1,7 +1,7 @@ -import { graphql, useStaticQuery } from 'gatsby' +import {graphql, useStaticQuery} from 'gatsby' import React from 'react' -function useSearch (query) { +function useSearch(query) { const latestQuery = React.useRef(query) const workerRef = React.useRef() @@ -28,29 +28,30 @@ function useSearch (query) { const mdxNodes = data.allMdx.nodes.reduce((map, obj) => { map[obj.id] = obj return map - }, { }) + }, {}) const list = React.useMemo( () => - data.allSitePage.nodes.filter(node => { - return (node.pageContext && node.pageContext.mdxId && mdxNodes[node.pageContext.mdxId] != null) - }).map(node => { - const mdxNode = mdxNodes[node.pageContext.mdxId] + data.allSitePage.nodes + .filter(node => { + return node.pageContext && node.pageContext.mdxId && mdxNodes[node.pageContext.mdxId] != null + }) + .map(node => { + const mdxNode = mdxNodes[node.pageContext.mdxId] - const obj = - { - path: node.path, - title: mdxNode.frontmatter.title, - rawBody: mdxNode.rawBody, - } - return obj - }), - [data] + const obj = { + path: node.path, + title: mdxNode.frontmatter.title, + rawBody: mdxNode.rawBody, + } + return obj + }), + [data], ) const [results, setResults] = React.useState(list) - const handleSearchResults = React.useCallback(({ data }) => { + const handleSearchResults = React.useCallback(({data}) => { if (data.query && data.results && data.query === latestQuery.current) { setResults(data.results) } @@ -59,7 +60,7 @@ function useSearch (query) { React.useEffect(() => { const worker = new Worker(new URL('./search.worker.js', import.meta.url)) worker.addEventListener('message', handleSearchResults) - worker.postMessage({ list }) + worker.postMessage({list}) workerRef.current = worker return () => { @@ -70,7 +71,7 @@ function useSearch (query) { React.useEffect(() => { latestQuery.current = query if (query && workerRef.current) { - workerRef.current.postMessage({ query: query }) + workerRef.current.postMessage({query}) } else { setResults(list) } diff --git a/theme/src/use-site-metadata.js b/theme/src/use-site-metadata.js index 751a3c66e47..decba222137 100644 --- a/theme/src/use-site-metadata.js +++ b/theme/src/use-site-metadata.js @@ -1,6 +1,6 @@ -import { useStaticQuery, graphql } from 'gatsby' +import {useStaticQuery, graphql} from 'gatsby' -function useSiteMetadata () { +function useSiteMetadata() { const data = useStaticQuery(graphql` { site {